libcm is a C development framework with an emphasis on audio signal processing applications.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cmRtSys.c 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  1. #include "cmPrefix.h"
  2. #include "cmGlobal.h"
  3. #include "cmFloatTypes.h"
  4. #include "cmRpt.h"
  5. #include "cmErr.h"
  6. #include "cmCtx.h"
  7. #include "cmMem.h"
  8. #include "cmMallocDebug.h"
  9. #include "cmAudioPort.h"
  10. #include "cmAudioNrtDev.h"
  11. #include "cmAudioPortFile.h"
  12. #include "cmApBuf.h"
  13. #include "cmJson.h"
  14. #include "cmThread.h"
  15. #include "cmUdpPort.h"
  16. #include "cmUdpNet.h"
  17. #include "cmRtSysMsg.h"
  18. #include "cmRtNet.h"
  19. #include "cmRtSys.h"
  20. #include "cmMidi.h"
  21. #include "cmMidiPort.h"
  22. #include "cmMath.h"
  23. typedef enum
  24. {
  25. kNoCmdId,
  26. kEnableCbCmdId,
  27. kDisableCbCmdId
  28. } kRtCmdId_t;
  29. cmRtSysH_t cmRtSysNullHandle = cmSTATIC_NULL_HANDLE;
  30. struct cmRt_str;
  31. typedef struct
  32. {
  33. struct cmRt_str* p; // pointer to the real-time system instance which owns this sub-system
  34. cmRtSysSubSys_t ss; // sub-system configuration record
  35. cmRtSysCtx_t ctx; // DSP context
  36. cmRtSysStatus_t status; // current runtime status of this sub-system
  37. cmThreadH_t threadH; // real-time system thread
  38. cmTsMp1cH_t htdQueueH; // host-to-dsp thread safe msg queue
  39. cmThreadMutexH_t engMutexH; // thread mutex and condition variable
  40. cmRtNetH_t netH;
  41. bool runFl; // false during finalization otherwise true
  42. bool statusFl; // true if regular status notifications should be sent
  43. bool syncInputFl;
  44. kRtCmdId_t cmdId; // written by app thread, read by rt thread
  45. unsigned cbEnableFl; // written by rt thread, read by app thread
  46. double* iMeterArray; //
  47. double* oMeterArray; //
  48. unsigned statusUpdateSmpCnt; // transmit a state update msg every statusUpdateSmpCnt samples
  49. unsigned statusUpdateSmpIdx; // state update phase
  50. } _cmRtCfg_t;
  51. typedef struct cmRt_str
  52. {
  53. cmErr_t err;
  54. cmCtx_t* ctx;
  55. _cmRtCfg_t* ssArray;
  56. unsigned ssCnt;
  57. unsigned waitRtSubIdx; // index of the next sub-system to try with cmRtSysIsMsgWaiting().
  58. cmTsMp1cH_t dthQueH;
  59. bool initFl; // true if the real-time system is initialized
  60. cmTsQueueCb_t clientCbFunc; // These fields are only used during configuration.
  61. void* clientCbArg; // See cmRtBeginCfg() and cmRtCfg().
  62. } cmRt_t;
  63. cmRt_t* _cmRtHandleToPtr( cmRtSysH_t h )
  64. {
  65. cmRt_t* p = (cmRt_t*)h.h;
  66. assert(p != NULL);
  67. return p;
  68. }
  69. cmRtRC_t _cmRtError( cmRt_t* p, cmRtRC_t rc, const char* fmt, ... )
  70. {
  71. va_list vl;
  72. va_start(vl,fmt);
  73. cmErrVMsg(&p->err,rc,fmt,vl);
  74. va_end(vl);
  75. return rc;
  76. }
  77. // Wrapper function to put msgs into thread safe queues and handle related errors.
  78. cmRtRC_t _cmRtEnqueueMsg( cmRt_t* p, cmTsMp1cH_t qH, const void* msgDataPtrArray[], unsigned msgCntArray[], unsigned segCnt, const char* queueLabel )
  79. {
  80. cmRtRC_t rc = kOkRtRC;
  81. switch( cmTsMp1cEnqueueSegMsg(qH, msgDataPtrArray, msgCntArray, segCnt) )
  82. {
  83. case kOkThRC:
  84. break;
  85. case kBufFullThRC:
  86. {
  87. unsigned i;
  88. unsigned byteCnt = 0;
  89. for(i=0; i<segCnt; ++i)
  90. byteCnt += msgCntArray[i];
  91. rc = _cmRtError(p,kMsgEnqueueFailRtRC,"The %s queue was unable to load a msg containing %i bytes. The queue is currently allocated %i bytes and has %i bytes available.",queueLabel,byteCnt,cmTsMp1cAllocByteCount(qH),cmTsMp1cAvailByteCount(qH));
  92. }
  93. break;
  94. default:
  95. rc = _cmRtError(p,kMsgEnqueueFailRtRC,"A %s msg. enqueue failed.",queueLabel);
  96. }
  97. return rc;
  98. }
  99. // This is the function pointed to by ctx->dspToHostFunc.
  100. // It is called by the DSP proces to pass msgs to the host.
  101. // therefore it is always called from inside of _cmRtDspExecCallback().
  102. cmRtRC_t _cmRtDspToHostMsgCallback(struct cmRtSysCtx_str* ctx, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt)
  103. {
  104. cmRt_t* p = (cmRt_t*)ctx->reserved;
  105. assert( ctx->rtSubIdx < p->ssCnt );
  106. return _cmRtEnqueueMsg(p,p->dthQueH,msgDataPtrArray,msgByteCntArray,msgSegCnt,"DSP-to-Host");
  107. }
  108. cmRtRC_t _cmRtSysDspToHostSegMsg( cmRt_t* p, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt)
  109. {
  110. return _cmRtEnqueueMsg(p,p->dthQueH,msgDataPtrArray,msgByteCntArray,msgSegCnt,"DSP-to-Host");
  111. }
  112. cmRtRC_t cmRtSysDspToHostSegMsg( cmRtSysH_t h, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt)
  113. {
  114. cmRt_t* p = _cmRtHandleToPtr(h);
  115. return _cmRtSysDspToHostSegMsg(p,msgDataPtrArray,msgByteCntArray,msgSegCnt);
  116. }
  117. cmRtRC_t cmRtSysDspToHost( cmRtSysH_t h, const void* msgDataPtr, unsigned msgByteCnt)
  118. {
  119. const void* msgDataArray[] = { msgDataPtr };
  120. unsigned msgByteCntArray[] = { msgByteCnt };
  121. return cmRtSysDspToHostSegMsg(h,msgDataArray,msgByteCntArray,1);
  122. }
  123. cmRtRC_t _cmRtParseNonSubSysMsg( cmRt_t* p, const void* msg, unsigned msgByteCnt )
  124. {
  125. cmRtRC_t rc = kOkRtRC;
  126. cmRtSysMstr_t* m = (cmRtSysMstr_t*)msg;
  127. /*
  128. unsigned devIdx = cmRtSysUiInstIdToDevIndex(h->instId);
  129. unsigned chIdx = cmRtSysUiInstIdToChIndex(h->instId);
  130. unsigned inFl = cmRtSysUiInstIdToInFlag(h->instId);
  131. unsigned ctlId = cmRtSysUiInstIdToCtlId(h->instId);
  132. */
  133. // if the valuu associated with this msg is a mtx then set
  134. // its mtx data area pointer to just after the msg header.
  135. //if( cmDsvIsMtx(&h->value) )
  136. // h->value.u.m.u.vp = ((char*)msg) + sizeof(cmDspUiHdr_t);
  137. unsigned flags = m->inFl ? kInApFl : kOutApFl;
  138. switch( m->ctlId )
  139. {
  140. case kSliderUiRtId: // slider
  141. cmApBufSetGain(m->devIdx,m->chIdx, flags, m->value);
  142. break;
  143. case kMeterUiRtId: // meter
  144. break;
  145. case kMuteUiRtId: // mute
  146. flags += m->value == 0 ? kEnableApFl : 0;
  147. cmApBufEnableChannel(m->devIdx,m->chIdx,flags);
  148. break;
  149. case kToneUiRtId: // tone
  150. flags += m->value > 0 ? kEnableApFl : 0;
  151. cmApBufEnableTone(m->devIdx,m->chIdx,flags);
  152. break;
  153. case kPassUiRtId: // pass
  154. flags += m->value > 0 ? kEnableApFl : 0;
  155. cmApBufEnablePass(m->devIdx,m->chIdx,flags);
  156. break;
  157. default:
  158. { assert(0); }
  159. }
  160. return rc;
  161. }
  162. // Process a UI msg sent from the host to the real-time system
  163. cmRtRC_t _cmRtHandleNonSubSysMsg( cmRt_t* p, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt )
  164. {
  165. cmRtRC_t rc = kOkRtRC;
  166. // if the message is contained in a single segment it can be dispatched immediately ...
  167. if( msgSegCnt == 1 )
  168. rc = _cmRtParseNonSubSysMsg(p,msgDataPtrArray[0],msgByteCntArray[0]);
  169. else
  170. {
  171. // ... otherwise deserialize the message into contiguous memory ....
  172. unsigned byteCnt = 0;
  173. unsigned i;
  174. for(i=0; i<msgSegCnt; ++i)
  175. byteCnt += msgByteCntArray[i];
  176. char buf[ byteCnt ];
  177. char* b = buf;
  178. for(i=0; i<msgSegCnt; ++i)
  179. {
  180. memcpy(b, msgDataPtrArray[i], msgByteCntArray[i] );
  181. b += msgByteCntArray[i];
  182. }
  183. // ... and then dispatch it
  184. rc = _cmRtParseNonSubSysMsg(p,buf,byteCnt);
  185. }
  186. return rc;
  187. }
  188. cmRtRC_t _cmRtSendStateStatusToHost( _cmRtCfg_t* cp )
  189. {
  190. cmRtRC_t rc = kOkRtRC;
  191. cp->status.hdr.rtSubIdx = cp->ctx.rtSubIdx;
  192. cp->status.hdr.selId = kStatusSelRtId;
  193. cmApBufGetStatus( cp->ss.args.inDevIdx, kInApFl, cp->iMeterArray, cp->status.iMeterCnt, &cp->status.overflowCnt );
  194. cmApBufGetStatus( cp->ss.args.outDevIdx, kOutApFl, cp->oMeterArray, cp->status.oMeterCnt, &cp->status.underflowCnt );
  195. unsigned iMeterByteCnt = sizeof(cp->iMeterArray[0]) * cp->status.iMeterCnt;
  196. unsigned oMeterByteCnt = sizeof(cp->oMeterArray[0]) * cp->status.oMeterCnt;
  197. const void* msgDataPtrArray[] = { &cp->status, cp->iMeterArray, cp->oMeterArray };
  198. unsigned msgByteCntArray[] = { sizeof(cp->status), iMeterByteCnt, oMeterByteCnt };
  199. unsigned segCnt = sizeof(msgByteCntArray)/sizeof(unsigned);
  200. _cmRtSysDspToHostSegMsg(cp->p,msgDataPtrArray,msgByteCntArray, segCnt );
  201. return rc;
  202. }
  203. // This function is called, within the real-time thread,
  204. // with _cmRtRecd.engMutexH locked, to deliver
  205. // messages to the real-time DSP processes via cp->ss.cbFunc()
  206. cmRtRC_t _cmRtDeliverMsgsWithLock( _cmRtCfg_t* cp )
  207. {
  208. int i;
  209. cmRtRC_t rc = kOkThRC;
  210. // as long msg's are in the queue incoming msg queue
  211. for(i=0; rc == kOkThRC; ++i)
  212. {
  213. // if a msg is waiting transmit it via cp->ss.cbFunc()
  214. if((rc = cmTsMp1cDequeueMsg(cp->htdQueueH,NULL,0)) == kOkThRC)
  215. ++cp->status.msgCbCnt;
  216. }
  217. return rc;
  218. }
  219. // This funciton is _cmRtDspExecCallback()->cmRtNetReceive() in the
  220. // real-time thread to deliver msg's to the DSP process.
  221. void _cmRtSysNetRecv( void* cbArg, const char* data, unsigned dataByteCnt, const struct sockaddr_in* fromAddr )
  222. {
  223. _cmRtCfg_t* cp = (_cmRtCfg_t*)cbArg;
  224. if( cp->cbEnableFl )
  225. {
  226. cmRtSysH_t h;
  227. h.h = cp->p;
  228. cmRtSysDeliverMsg(h,data,dataByteCnt,cmInvalidId);
  229. }
  230. }
  231. // The DSP execution callback happens through this function.
  232. // This function is only called from inside _cmRtThreadCallback()
  233. // with the engine mutex locked.
  234. void _cmRtDspExecCallback( _cmRtCfg_t* cp )
  235. {
  236. // Fill iChArray[] and oChArray[] with pointers to the incoming and outgoing sample buffers.
  237. // Notes:
  238. // 1) Buffers associated with disabled input/output channels will be set to NULL in iChArray[]/oChArray[].
  239. // 2) Buffers associated with channels marked for pass-through will be set to NULL in oChArray[].
  240. // 3) All samples returned in oChArray[] buffers will be set to zero.
  241. cmApBufGetIO(cp->ss.args.inDevIdx, cp->ctx.iChArray, cp->ctx.iChCnt, cp->ss.args.outDevIdx, cp->ctx.oChArray, cp->ctx.oChCnt );
  242. // calling this function results in callbacks to _cmRtSysNetRecv()
  243. // which in turn calls cmRtSysDeliverMsg() which queues any incoming messages
  244. // which are then transferred to the DSP processes by the the call to
  245. // _cmRtDeliverMsgWithLock() below.
  246. if( cmRtNetIsValid(cp->netH) )
  247. if( cmRtNetReceive(cp->netH) != kOkNetRC )
  248. _cmRtError(cp->p,kNetErrRtRC,"Network receive failed.");
  249. // NOTE: BY DEQUEUEING MSGS FIRST AND THEN SERVICING THE NETWORK
  250. // WE COULD ELIMINATE QUEUEING NETWORK MESSAGES - THEY COULD BE
  251. // SEND DIRECTLY THROUGH TO THE DSP PROCESSES
  252. // if there are msgs waiting to be sent to the DSP process send them.
  253. if( cp->cbEnableFl )
  254. if( cmTsMp1cMsgWaiting(cp->htdQueueH) )
  255. _cmRtDeliverMsgsWithLock(cp);
  256. // call the application provided DSP process
  257. if( cp->cbEnableFl )
  258. {
  259. cp->ctx.audioRateFl = true;
  260. cp->ss.cbFunc( &cp->ctx, 0, NULL );
  261. cp->ctx.audioRateFl = false;
  262. }
  263. // Notice client callback enable/disable
  264. // requests from the client thread
  265. switch( cp->cmdId )
  266. {
  267. case kNoCmdId:
  268. break;
  269. case kDisableCbCmdId:
  270. if( cp->cbEnableFl )
  271. cmThUIntDecr(&cp->cbEnableFl,1);
  272. break;
  273. case kEnableCbCmdId:
  274. if( cp->cbEnableFl==0)
  275. cmThUIntIncr(&cp->cbEnableFl,1);
  276. break;
  277. }
  278. // advance the audio buffer
  279. cmApBufAdvance( cp->ss.args.outDevIdx, kOutApFl );
  280. cmApBufAdvance( cp->ss.args.inDevIdx, kInApFl );
  281. // handle periodic status messages to the host
  282. if( (cp->statusUpdateSmpIdx += cp->ss.args.dspFramesPerCycle) >= cp->statusUpdateSmpCnt )
  283. {
  284. cp->statusUpdateSmpIdx -= cp->statusUpdateSmpCnt;
  285. if( cp->statusFl )
  286. _cmRtSendStateStatusToHost(cp);
  287. }
  288. }
  289. // Returns true if audio buffer is has waiting incoming samples and
  290. // available outgoing space.
  291. bool _cmRtBufIsReady( const _cmRtCfg_t* cp )
  292. {
  293. // if there neither the input or output device is valid
  294. if( cp->ss.args.inDevIdx==cmInvalidIdx && cp->ss.args.outDevIdx == cmInvalidIdx )
  295. return false;
  296. bool ibFl = cmApBufIsDeviceReady(cp->ss.args.inDevIdx, kInApFl);
  297. bool obFl = cmApBufIsDeviceReady(cp->ss.args.outDevIdx, kOutApFl);
  298. bool iFl = (cp->ss.args.inDevIdx == cmInvalidIdx) || ibFl;
  299. bool oFl = (cp->ss.args.outDevIdx == cmInvalidIdx) || obFl;
  300. //printf("br: %i %i %i %i\n",ibFl,obFl,iFl,oFl);
  301. return iFl && oFl;
  302. }
  303. // This is the main real-time system loop (and thread callback function).
  304. // It blocks by waiting on a cond. var (which simultaneously unlocks a mutex).
  305. // With the mutex unlocked messages can pass directly to the DSP process
  306. // via calls to cmRtDeliverMsg().
  307. // When the audio buffers need to be serviced the audio device callback
  308. // signals the cond. var. which results in this thread waking up (and
  309. // simultaneously locking the mutex) as soon as the mutex is available.
  310. bool _cmRtThreadCallback(void* arg)
  311. {
  312. cmRtRC_t rc;
  313. _cmRtCfg_t* cp = (_cmRtCfg_t*)arg;
  314. // lock the cmRtSys mutex
  315. if((rc = cmThreadMutexLock(cp->engMutexH)) != kOkRtRC )
  316. {
  317. _cmRtError(cp->p,rc,"The cmRtSys thread mutex lock failed.");
  318. return false;
  319. }
  320. // runFl is always set except during finalization
  321. while( cp->runFl )
  322. {
  323. // if the buffer is NOT ready or the cmRtSys is disabled
  324. if(_cmRtBufIsReady(cp) == false || cp->cbEnableFl==false )
  325. {
  326. // block on the cond var and unlock the mutex
  327. if( cmThreadMutexWaitOnCondVar(cp->engMutexH,false) != kOkRtRC )
  328. {
  329. cmThreadMutexUnlock(cp->engMutexH);
  330. _cmRtError(cp->p,rc,"The cmRtSys cond. var. wait failed.");
  331. return false;
  332. }
  333. //
  334. // the cond var was signaled and the mutex is now locked
  335. //
  336. ++cp->status.wakeupCnt;
  337. }
  338. // be sure we are still enabled and the buffer is still ready
  339. while( cp->runFl && _cmRtBufIsReady(cp) )
  340. {
  341. ++cp->status.audioCbCnt;
  342. // make the cmRtSys callback
  343. _cmRtDspExecCallback( cp );
  344. // update the signal time
  345. cp->ctx.begSmpIdx += cp->ss.args.dspFramesPerCycle;
  346. }
  347. }
  348. // unlock the mutex
  349. cmThreadMutexUnlock(cp->engMutexH);
  350. return true;
  351. }
  352. void _cmRtGenSignal( cmApAudioPacket_t* outPktArray, unsigned outPktCnt, bool sineFl )
  353. {
  354. static unsigned rtPhase = 0;
  355. //fill output with noise
  356. unsigned i = 0,j =0, k = 0, phs = 0;
  357. for(; i<outPktCnt; ++i)
  358. {
  359. cmApAudioPacket_t* a = outPktArray + i;
  360. cmApSample_t* dp = (cmApSample_t*)a->audioBytesPtr;
  361. phs = a->audioFramesCnt;
  362. if( sineFl )
  363. {
  364. for(j=0; j<a->audioFramesCnt; ++j)
  365. {
  366. cmApSample_t v = (cmApSample_t)(0.7 * sin(2*M_PI/44100.0 * rtPhase + j ));
  367. for(k=0; k<a->chCnt; ++k,++dp)
  368. *dp = v;
  369. }
  370. }
  371. else
  372. {
  373. for(j=0; j<a->audioFramesCnt*a->chCnt; ++j,++dp)
  374. *dp = (cmApSample_t)(rand() - (RAND_MAX/2))/(RAND_MAX/2);
  375. }
  376. }
  377. rtPhase += phs;
  378. }
  379. // This is the audio port callback function.
  380. //
  381. // _cmRtSysAudioUpdate() assumes that at most two audio device threads
  382. // (input and output) may call it. cmApBufUpdate() is safe under these conditions
  383. // since the input and output buffers are updated separately.
  384. // p->syncInputFl is used to allow either the input or output thread to signal
  385. // the condition variable. This flag is necessary to prevent both threads from simultaneously
  386. // attempting to signal the condition variable (which will lock the system).
  387. //
  388. // If more than two audio device threads call the function then this function is not safe.
  389. void _cmRtSysAudioUpdate( cmApAudioPacket_t* inPktArray, unsigned inPktCnt, cmApAudioPacket_t* outPktArray, unsigned outPktCnt )
  390. {
  391. _cmRtCfg_t* cp = (_cmRtCfg_t*)(inPktArray!=NULL ? inPktArray[0].userCbPtr : outPktArray[0].userCbPtr);
  392. ++cp->status.updateCnt;
  393. if( cp->runFl )
  394. {
  395. // transfer incoming/outgoing samples from/to the audio device
  396. cmApBufUpdate(inPktArray,inPktCnt,outPktArray,outPktCnt);
  397. // generate a test signal
  398. //_cmRtGenSignal( cmApAudioPacket_t* outPktArray, unsigned outPktCnt, bool sineFl );
  399. //return;
  400. bool testBufFl = (cp->syncInputFl==true && inPktCnt>0) || (cp->syncInputFl==false && outPktCnt>0);
  401. //printf("%i %i %i %i\n",testBufFl,cp->syncInputFl,inPktCnt,outPktCnt);
  402. // if the input/output buffer contain samples to be processed then signal the condition variable
  403. // - this will cause the real-time system thread to unblock and the used defined DSP process will be called.
  404. if( testBufFl && _cmRtBufIsReady(cp) )
  405. {
  406. if( cmThreadMutexSignalCondVar(cp->engMutexH) != kOkThRC )
  407. _cmRtError(cp->p,kMutexErrRtRC,"CmRtSys signal cond. var. failed.");
  408. }
  409. }
  410. }
  411. // Called when MIDI messages arrive from external MIDI ports.
  412. void _cmRtSysMidiCallback( const cmMidiPacket_t* pktArray, unsigned pktCnt )
  413. {
  414. unsigned i;
  415. for(i=0; i<pktCnt; ++i)
  416. {
  417. const cmMidiPacket_t* pkt = pktArray + i;
  418. _cmRtCfg_t* cp = (_cmRtCfg_t*)(pkt->cbDataPtr);
  419. if( !cp->runFl )
  420. continue;
  421. cmRtSysH_t asH;
  422. asH.h = cp->p;
  423. cmRtSysMidi_t m;
  424. m.hdr.rtSubIdx = cp->ctx.rtSubIdx;
  425. m.hdr.selId = kMidiMsgArraySelRtId;
  426. m.devIdx = pkt->devIdx;
  427. m.portIdx = pkt->portIdx;
  428. m.msgCnt = pkt->msgCnt;
  429. /*
  430. unsigned selId = kMidiMsgArraySelRtId;
  431. const void* msgPtrArray[] = { &cp->ctx.rtSubIdx, &selId, &pkt->devIdx, &pkt->portIdx, &pkt->msgCnt, pkt->msgArray };
  432. unsigned msgByteCntArray[] = { sizeof(cp->ctx.rtSubIdx), sizeof(selId), sizeof(pkt->devIdx), sizeof(pkt->portIdx), sizeof(pkt->msgCnt), pkt->msgCnt*sizeof(cmMidiMsg) };
  433. unsigned msgSegCnt = sizeof(msgByteCntArray)/sizeof(unsigned);
  434. */
  435. const void* msgPtrArray[] = { &m, pkt->msgArray };
  436. unsigned msgByteCntArray[] = { sizeof(m), pkt->msgCnt*sizeof(cmMidiMsg) };
  437. unsigned msgSegCnt = sizeof(msgByteCntArray)/sizeof(unsigned);
  438. cmRtSysDeliverSegMsg(asH,msgPtrArray,msgByteCntArray,msgSegCnt,cmInvalidId);
  439. }
  440. }
  441. cmRtRC_t cmRtSysAllocate( cmRtSysH_t* hp, cmCtx_t* ctx )
  442. {
  443. cmRtRC_t rc;
  444. if((rc = cmRtSysFree(hp)) != kOkRtRC )
  445. return rc;
  446. cmRt_t* p = cmMemAllocZ( cmRt_t, 1 );
  447. cmErrSetup(&p->err,&ctx->rpt,"Real-Time System");
  448. p->ctx = ctx;
  449. hp->h = p;
  450. return rc;
  451. }
  452. cmRtRC_t cmRtSysFree( cmRtSysH_t* hp )
  453. {
  454. cmRtRC_t rc;
  455. if( hp == NULL || hp->h == NULL )
  456. return kOkRtRC;
  457. if((rc = cmRtSysFinalize(*hp)) != kOkRtRC )
  458. return rc;
  459. cmRt_t* p = _cmRtHandleToPtr(*hp);
  460. cmMemFree(p);
  461. hp->h = NULL;
  462. return rc;
  463. }
  464. cmRtRC_t _cmRtSysEnable( cmRt_t* p, bool enableFl )
  465. {
  466. cmRtRC_t rc = kOkRtRC;
  467. unsigned i;
  468. unsigned n;
  469. unsigned tickMs = 20;
  470. unsigned timeOutMs = 10000;
  471. for(i=0; i<p->ssCnt; ++i)
  472. {
  473. _cmRtCfg_t* cp = p->ssArray + i;
  474. if( enableFl )
  475. {
  476. cp->cmdId = kNoCmdId;
  477. cmThUIntIncr(&cp->cmdId,kEnableCbCmdId);
  478. for(n=0; n<timeOutMs && cp->cbEnableFl==false; n+=tickMs )
  479. cmSleepMs(tickMs);
  480. cmThUIntDecr(&cp->cmdId,kEnableCbCmdId);
  481. }
  482. else
  483. {
  484. cp->cmdId = kNoCmdId;
  485. cmThUIntIncr(&cp->cmdId,kDisableCbCmdId);
  486. // wait for the rt thread to return from a client callbacks
  487. for(n=0; n<timeOutMs && cp->cbEnableFl; n+=tickMs )
  488. cmSleepMs(tickMs);
  489. cmThUIntDecr(&cp->cmdId,kDisableCbCmdId);
  490. }
  491. if( n >= timeOutMs )
  492. rc = cmErrMsg(&p->err,kTimeOutErrRtRC,"RT System %s timed out after %i milliseconds.",enableFl?"enable":"disable",timeOutMs);
  493. }
  494. // enable network sync mode
  495. if( enableFl)
  496. for(i=0; i<p->ssCnt; ++i)
  497. {
  498. _cmRtCfg_t* cp = p->ssArray + i;
  499. if( cmRtNetIsValid(cp->netH) )
  500. if( cmRtNetDoSync(cp->netH) != kOkNetRC )
  501. rc = cmErrMsg(&p->err,kNetErrRtRC,"Network Mgr. failed on entering sync mode.");
  502. }
  503. return rc;
  504. }
  505. cmRtRC_t _cmRtSysFinalize( cmRt_t* p )
  506. {
  507. cmRtRC_t rc = kOkRtRC;
  508. unsigned i;
  509. // mark the real-time system as NOT initialized
  510. p->initFl = false;
  511. // be sure all audio callbacks are disabled before continuing.
  512. if((rc = _cmRtSysEnable(p,false)) != kOkRtRC )
  513. return _cmRtError(p,rc,"real-time system finalize failed because device halting failed.");
  514. // stop the audio devices
  515. for(i=0; i<p->ssCnt; ++i)
  516. {
  517. _cmRtCfg_t* cp = p->ssArray + i;
  518. // stop the input device
  519. if((rc = cmApDeviceStop( cp->ss.args.inDevIdx )) != kOkRtRC )
  520. return _cmRtError(p,kAudioDevStopFailRtRC,"The audio input device stop failed.");
  521. // stop the output device
  522. if((rc = cmApDeviceStop( cp->ss.args.outDevIdx )) != kOkRtRC )
  523. return _cmRtError(p,kAudioDevStopFailRtRC,"The audio output device stop failed.");
  524. }
  525. for(i=0; i<p->ssCnt; ++i)
  526. {
  527. _cmRtCfg_t* cp = p->ssArray + i;
  528. if( cmThreadIsValid( cp->threadH ))
  529. {
  530. // inform the thread that it should exit
  531. cp->runFl = false;
  532. cp->statusFl = false;
  533. // signal the cond var to cause the thread to run
  534. if((rc = cmThreadMutexSignalCondVar(cp->engMutexH)) != kOkThRC )
  535. _cmRtError(p,kMutexErrRtRC,"Finalize signal cond. var. failed.");
  536. // wait to take control of the mutex - this will occur when the thread function exits
  537. if((rc = cmThreadMutexLock(cp->engMutexH)) != kOkThRC )
  538. _cmRtError(p,kMutexErrRtRC,"Finalize lock failed.");
  539. // unlock the mutex because it is no longer needed and must be unlocked to be destroyed
  540. if((rc = cmThreadMutexUnlock(cp->engMutexH)) != kOkThRC )
  541. _cmRtError(p,kMutexErrRtRC,"Finalize unlock failed.");
  542. // destroy the thread
  543. if((rc = cmThreadDestroy( &cp->threadH )) != kOkThRC )
  544. _cmRtError(p,kThreadErrRtRC,"Thread destroy failed.");
  545. }
  546. // destroy the mutex
  547. if( cmThreadMutexIsValid(cp->engMutexH) )
  548. if((rc = cmThreadMutexDestroy( &cp->engMutexH )) != kOkThRC )
  549. _cmRtError(p,kMutexErrRtRC,"Mutex destroy failed.");
  550. // release the network mgr
  551. if( cmRtNetFree(&cp->netH) != kOkNetRC )
  552. _cmRtError(p,kNetErrRtRC,"Network Mrr. release failed.");
  553. // remove the MIDI callback
  554. if( cmMpIsInitialized() && cmMpUsesCallback(-1,-1, _cmRtSysMidiCallback, cp) )
  555. if( cmMpRemoveCallback( -1, -1, _cmRtSysMidiCallback, cp ) != kOkMpRC )
  556. _cmRtError(p,kMidiSysFailRtRC,"MIDI callback removal failed.");
  557. // destroy the host-to-dsp msg queue
  558. if( cmTsMp1cIsValid(cp->htdQueueH ) )
  559. if((rc = cmTsMp1cDestroy( &cp->htdQueueH )) != kOkThRC )
  560. _cmRtError(p,kTsQueueErrRtRC,"Host-to-DSP msg queue destroy failed.");
  561. // destroy the dsp-to-host msg queue
  562. if( cmTsMp1cIsValid(p->dthQueH) )
  563. if((rc = cmTsMp1cDestroy( &p->dthQueH )) != kOkThRC )
  564. _cmRtError(p,kTsQueueErrRtRC,"DSP-to-Host msg queue destroy failed.");
  565. cmMemPtrFree(&cp->ctx.iChArray);
  566. cmMemPtrFree(&cp->ctx.oChArray);
  567. cp->ctx.iChCnt = 0;
  568. cp->ctx.oChCnt = 0;
  569. cmMemPtrFree(&cp->iMeterArray);
  570. cmMemPtrFree(&cp->oMeterArray);
  571. cp->status.iMeterCnt = 0;
  572. cp->status.oMeterCnt = 0;
  573. }
  574. cmMemPtrFree(&p->ssArray);
  575. p->ssCnt = 0;
  576. return rc;
  577. }
  578. // A given device may be used as an input device exactly once and an
  579. // output device exactly once. When the input to a given device is used
  580. // by one sub-system and the output is used by another then both sub-systems
  581. // must use the same srate,devFramesPerCycle, audioBufCnt and dspFramesPerCycle.
  582. cmRtRC_t _cmRtSysValidate( cmRt_t* p )
  583. {
  584. unsigned i,j,k;
  585. for(i=0; i<2; ++i)
  586. {
  587. // examine input devices - then output devices
  588. bool inputFl = i==0;
  589. bool outputFl = !inputFl;
  590. for(j=0; j<p->ssCnt; ++j)
  591. {
  592. cmRtSysArgs_t* s0 = &p->ssArray[j].ss.args;
  593. unsigned devIdx = inputFl ? s0->inDevIdx : s0->outDevIdx;
  594. for(k=0; k<p->ssCnt && devIdx != cmInvalidIdx; ++k)
  595. if( k != j )
  596. {
  597. cmRtSysArgs_t* s1 = &p->ssArray[k].ss.args;
  598. // if the device was used as input or output multple times then signal an error
  599. if( (inputFl && (s1->inDevIdx == devIdx) && s1->inDevIdx != cmInvalidIdx) || (outputFl && (s1->outDevIdx == devIdx) && s1->outDevIdx != cmInvalidIdx) )
  600. return cmErrMsg(&p->err,kInvalidArgRtRC,"The device %i was used as an %s by multiple sub-systems.", devIdx, inputFl ? "input" : "output");
  601. // if this device is being used by another subsystem ...
  602. if( (inputFl && (s1->outDevIdx == devIdx) && s1->inDevIdx != cmInvalidIdx) || (outputFl && (s1->outDevIdx == devIdx) && s1->outDevIdx != cmInvalidIdx ) )
  603. {
  604. // ... then some of its buffer spec's must match
  605. if( s0->srate != s1->srate || s0->audioBufCnt != s1->audioBufCnt || s0->dspFramesPerCycle != s1->dspFramesPerCycle || s0->devFramesPerCycle != s1->devFramesPerCycle )
  606. return cmErrMsg(&p->err,kInvalidArgRtRC,"The device %i is used by different sub-system with different audio buffer parameters.",devIdx);
  607. }
  608. }
  609. }
  610. }
  611. return kOkRtRC;
  612. }
  613. cmRtRC_t cmRtSysBeginCfg( cmRtSysH_t h, cmTsQueueCb_t clientCbFunc, void* clientCbArg, unsigned meterMs, unsigned ssCnt )
  614. {
  615. cmRt_t* p = _cmRtHandleToPtr(h);
  616. cmRtRC_t rc;
  617. // always finalize before iniitalize
  618. if((rc = cmRtSysFinalize(h)) != kOkRtRC )
  619. return rc;
  620. p->ssArray = cmMemAllocZ( _cmRtCfg_t, ssCnt );
  621. p->ssCnt = ssCnt;
  622. p->clientCbFunc = clientCbFunc;
  623. p->clientCbArg = clientCbArg;
  624. return rc;
  625. }
  626. cmRtRC_t cmRtSysCfg( cmRtSysH_t h, const cmRtSysSubSys_t* ss, unsigned rtSubIdx )
  627. {
  628. cmRtRC_t rc;
  629. unsigned j;
  630. cmRt_t* p = _cmRtHandleToPtr(h);
  631. assert( rtSubIdx < p->ssCnt);
  632. _cmRtCfg_t* cp = p->ssArray + rtSubIdx;;
  633. cp->p = p;
  634. cp->ss = *ss; // copy the cfg into the internal real-time system state
  635. cp->runFl = false;
  636. cp->statusFl = false;
  637. cp->ctx.reserved = p;
  638. cp->ctx.rtSubIdx = rtSubIdx;
  639. cp->ctx.ss = &cp->ss;
  640. cp->ctx.begSmpIdx = 0;
  641. cp->ctx.dspToHostFunc = _cmRtDspToHostMsgCallback;
  642. // validate the input device index
  643. if( ss->args.inDevIdx != cmInvalidIdx && ss->args.inDevIdx >= cmApDeviceCount() )
  644. {
  645. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"The audio input device index %i is invalid.",ss->args.inDevIdx);
  646. goto errLabel;
  647. }
  648. // validate the output device index
  649. if( ss->args.outDevIdx != cmInvalidIdx && ss->args.outDevIdx >= cmApDeviceCount() )
  650. {
  651. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"The audio output device index %i is invalid.",ss->args.outDevIdx);
  652. goto errLabel;
  653. }
  654. // setup the input device
  655. if( ss->args.inDevIdx != cmInvalidIdx )
  656. if((rc = cmApDeviceSetup( ss->args.inDevIdx, ss->args.srate, ss->args.devFramesPerCycle, _cmRtSysAudioUpdate, cp )) != kOkRtRC )
  657. {
  658. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"Audio input device setup failed.");
  659. goto errLabel;
  660. }
  661. // setup the output device
  662. if( ss->args.outDevIdx != ss->args.inDevIdx && ss->args.outDevIdx != cmInvalidIdx )
  663. if((rc = cmApDeviceSetup( ss->args.outDevIdx, ss->args.srate, ss->args.devFramesPerCycle, _cmRtSysAudioUpdate, cp )) != kOkRtRC )
  664. {
  665. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"Audio output device setup failed.");
  666. goto errLabel;
  667. }
  668. // setup the input device buffer
  669. if( ss->args.inDevIdx != cmInvalidIdx )
  670. if((rc = cmApBufSetup( ss->args.inDevIdx, ss->args.srate, ss->args.dspFramesPerCycle, ss->args.audioBufCnt, cmApDeviceChannelCount(ss->args.inDevIdx, true), ss->args.devFramesPerCycle, cmApDeviceChannelCount(ss->args.inDevIdx, false), ss->args.devFramesPerCycle )) != kOkRtRC )
  671. {
  672. rc = _cmRtError(p,kAudioBufSetupErrRtRC,"Audio buffer input setup failed.");
  673. goto errLabel;
  674. }
  675. cmApBufEnableMeter(ss->args.inDevIdx, -1, kInApFl | kEnableApFl );
  676. cmApBufEnableMeter(ss->args.outDevIdx,-1, kOutApFl | kEnableApFl );
  677. // setup the input audio buffer ptr array - used to send input audio to the DSP system in _cmRtDspExecCallback()
  678. if((cp->ctx.iChCnt = cmApDeviceChannelCount(ss->args.inDevIdx, true)) != 0 )
  679. cp->ctx.iChArray = cmMemAllocZ( cmSample_t*, cp->ctx.iChCnt );
  680. // setup the output device buffer
  681. if( ss->args.outDevIdx != ss->args.inDevIdx )
  682. if((rc = cmApBufSetup( ss->args.outDevIdx, ss->args.srate, ss->args.dspFramesPerCycle, ss->args.audioBufCnt, cmApDeviceChannelCount(ss->args.outDevIdx, true), ss->args.devFramesPerCycle, cmApDeviceChannelCount(ss->args.outDevIdx, false), ss->args.devFramesPerCycle )) != kOkRtRC )
  683. return _cmRtError(p,kAudioBufSetupErrRtRC,"Audio buffer ouput device setup failed.");
  684. // setup the output audio buffer ptr array - used to recv output audio from the DSP system in _cmRtDspExecCallback()
  685. if((cp->ctx.oChCnt = cmApDeviceChannelCount(ss->args.outDevIdx, false)) != 0 )
  686. cp->ctx.oChArray = cmMemAllocZ( cmSample_t*, cp->ctx.oChCnt );
  687. // determine the sync source
  688. cp->syncInputFl = ss->args.syncInputFl;
  689. // if sync'ing to an unavailable device then sync to the available device
  690. if( ss->args.syncInputFl && cp->ctx.iChCnt == 0 )
  691. cp->syncInputFl = false;
  692. if( ss->args.syncInputFl==false && cp->ctx.oChCnt == 0 )
  693. cp->syncInputFl = true;
  694. // setup the status record
  695. cp->status.hdr.rtSubIdx = cp->ctx.rtSubIdx;
  696. cp->status.iDevIdx = ss->args.inDevIdx;
  697. cp->status.oDevIdx = ss->args.outDevIdx;
  698. cp->status.iMeterCnt = cp->ctx.iChCnt;
  699. cp->status.oMeterCnt = cp->ctx.oChCnt;
  700. cp->iMeterArray = cmMemAllocZ( double, cp->status.iMeterCnt );
  701. cp->oMeterArray = cmMemAllocZ( double, cp->status.oMeterCnt );
  702. //cp->udpH = cfg->udpH;
  703. // create the real-time system thread
  704. if((rc = cmThreadCreate( &cp->threadH, _cmRtThreadCallback, cp, ss->args.rpt )) != kOkThRC )
  705. {
  706. rc = _cmRtError(p,kThreadErrRtRC,"Thread create failed.");
  707. goto errLabel;
  708. }
  709. // create the real-time system mutex
  710. if((rc = cmThreadMutexCreate( &cp->engMutexH, ss->args.rpt )) != kOkThRC )
  711. {
  712. rc = _cmRtError(p,kMutexErrRtRC,"Thread mutex create failed.");
  713. goto errLabel;
  714. }
  715. // create the host-to-dsp thread safe msg queue
  716. if((rc = cmTsMp1cCreate( &cp->htdQueueH, ss->args.msgQueueByteCnt, ss->cbFunc, &cp->ctx, ss->args.rpt )) != kOkThRC )
  717. {
  718. rc = _cmRtError(p,kTsQueueErrRtRC,"Host-to-DSP msg queue create failed.");
  719. goto errLabel;
  720. }
  721. // create the dsp-to-host thread safe msg queue
  722. if( cmTsMp1cIsValid( p->dthQueH ) == false )
  723. {
  724. if((rc = cmTsMp1cCreate( &p->dthQueH, ss->args.msgQueueByteCnt, p->clientCbFunc, p->clientCbArg, ss->args.rpt )) != kOkThRC )
  725. {
  726. rc = _cmRtError(p,kTsQueueErrRtRC,"DSP-to-Host msg queue create failed.");
  727. goto errLabel;
  728. }
  729. }
  730. // install an external MIDI port callback handler for incoming MIDI messages
  731. if( cmMpIsInitialized() )
  732. if( cmMpInstallCallback( -1, -1, _cmRtSysMidiCallback, cp ) != kOkMpRC )
  733. {
  734. rc = _cmRtError(p,kMidiSysFailRtRC,"MIDI system callback installation failed.");
  735. goto errLabel;
  736. }
  737. // setup the sub-system status notification
  738. cp->statusUpdateSmpCnt = floor(cmApBufMeterMs() * cp->ss.args.srate / 1000.0 );
  739. cp->statusUpdateSmpIdx = 0;
  740. // allocate the network mgr
  741. if( cmRtNetAlloc(p->ctx,&cp->netH, _cmRtSysNetRecv, cp ) != kOkNetRC )
  742. {
  743. rc = _cmRtError(p,kNetErrRtRC,"Network allocation failed.");
  744. goto errLabel;
  745. }
  746. if( cmRtNetInitialize( cp->netH, ss->bcastAddr, ss->localNodeLabel, ss->localIpAddr, ss->localIpPort) != kOkNetRC )
  747. {
  748. rc = _cmRtError(p,kNetErrRtRC,"Network node initialization failed on label:%s addr:%s port:%i.",cmStringNullGuard(ss->localNodeLabel),cmStringNullGuard(ss->localIpAddr),ss->localIpPort);
  749. goto errLabel;
  750. }
  751. // register the local endpoints
  752. for(j=0; j<ss->endptCnt; ++j)
  753. {
  754. cmRtSysNetEndpt_t* ep = ss->endptArray + j;
  755. if( cmRtNetRegisterEndPoint( cp->netH, cp->ctx.rtSubIdx, ep->label, ep->id ) != kOkNetRC )
  756. {
  757. rc = _cmRtError(p,kNetErrRtRC,"Network end point allocation failed on label:%s id:%i.",cmStringNullGuard(ep->label),ep->id);
  758. goto errLabel;
  759. }
  760. }
  761. errLabel:
  762. if( rc != kOkRtRC )
  763. _cmRtSysFinalize(p);
  764. return rc;
  765. }
  766. cmRtRC_t cmRtSysEndCfg( cmRtSysH_t h )
  767. {
  768. cmRtRC_t rc;
  769. cmRt_t* p = _cmRtHandleToPtr(h);
  770. unsigned i;
  771. if((rc = _cmRtSysValidate(p)) != kOkRtRC )
  772. goto errLabel;
  773. for(i=0; i<p->ssCnt; ++i)
  774. {
  775. _cmRtCfg_t* cp = p->ssArray + i;
  776. cp->runFl = true;
  777. // start the real-time system thread
  778. if( cmThreadPause( cp->threadH, 0 ) != kOkThRC )
  779. {
  780. rc = _cmRtError(p,kThreadErrRtRC,"Thread start failed.");
  781. goto errLabel;
  782. }
  783. // start the input device
  784. if((rc = cmApDeviceStart( cp->ss.args.inDevIdx )) != kOkRtRC )
  785. return _cmRtError(p,kAudioDevStartFailRtRC,"The audio input device start failed.");
  786. // start the output device
  787. if( cmApDeviceStart( cp->ss.args.outDevIdx ) != kOkRtRC )
  788. return _cmRtError(p,kAudioDevStartFailRtRC,"The audio ouput device start failed.");
  789. }
  790. p->initFl = true;
  791. errLabel:
  792. if( rc != kOkRtRC )
  793. _cmRtSysFinalize(p);
  794. return rc;
  795. }
  796. cmRtRC_t cmRtSysFinalize(cmRtSysH_t h )
  797. {
  798. cmRtRC_t rc = kOkRtRC;
  799. if( cmRtSysHandleIsValid(h) == false )
  800. return rc;
  801. cmRt_t* p = _cmRtHandleToPtr(h);
  802. rc = _cmRtSysFinalize(p);
  803. h.h = NULL;
  804. return rc;
  805. }
  806. bool cmRtSysIsInitialized( cmRtSysH_t h )
  807. {
  808. cmRt_t* p = _cmRtHandleToPtr(h);
  809. return p->initFl;
  810. }
  811. cmRtRC_t _cmRtSysVerifyInit( cmRt_t* p, bool errFl )
  812. {
  813. if( p->initFl == false )
  814. {
  815. // if the last msg generated was also a not init msg then don't
  816. // generate another message - just return the error
  817. if( errFl )
  818. if( cmErrLastRC(&p->err) != kNotInitRtRC )
  819. cmErrMsg(&p->err,kNotInitRtRC,"The real-time system is not initialized.");
  820. return kNotInitRtRC;
  821. }
  822. return kOkRtRC;
  823. }
  824. bool cmRtSysIsEnabled( cmRtSysH_t h )
  825. {
  826. if( cmRtSysIsInitialized(h) == false )
  827. return false;
  828. cmRt_t* p = _cmRtHandleToPtr(h);
  829. unsigned i;
  830. for(i=0; i<p->ssCnt; ++i)
  831. if( p->ssArray[i].cbEnableFl )
  832. return true;
  833. return false;
  834. }
  835. cmRtRC_t cmRtSysEnable( cmRtSysH_t h, bool enableFl )
  836. {
  837. cmRt_t* p = _cmRtHandleToPtr(h);
  838. return _cmRtSysEnable(p,enableFl);
  839. }
  840. cmRtRC_t cmRtSysDeliverSegMsg( cmRtSysH_t h, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt, unsigned srcNetNodeId )
  841. {
  842. cmRt_t* p = _cmRtHandleToPtr(h);
  843. cmRtRC_t rc;
  844. // the system must be initialized to use this function
  845. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  846. return rc;
  847. if( msgSegCnt == 0 )
  848. return kOkRtRC;
  849. // BUG BUG BUG - there is no reason that both the rtSubIdx and the selId must
  850. // be in the first segment but it would be nice.
  851. assert( msgByteCntArray[0] >= 2*sizeof(unsigned) || (msgSegCnt>1 && msgByteCntArray[0]==sizeof(unsigned) && msgByteCntArray[1]>=sizeof(unsigned)) );
  852. // The audio sub-system index is always the first field of the msg
  853. // and the msg selector id is always the second field
  854. unsigned* array = (unsigned*)msgDataPtrArray[0];
  855. unsigned rtSubIdx = array[0];
  856. unsigned selId = array[1];
  857. if( selId == kUiMstrSelRtId )
  858. return _cmRtHandleNonSubSysMsg( p, msgDataPtrArray, msgByteCntArray, msgSegCnt );
  859. /*
  860. if( selId == kNetSyncSelRtId )
  861. {
  862. assert( msgSegCnt==1);
  863. assert( rtSubIdx < p->ssCnt );
  864. p->ssArray[rtSubIdx].ctx.srcNetNodeId = srcNetNodeId;
  865. p->ssArray[rtSubIdx].ss.cbFunc(&p->ssArray[rtSubIdx].ctx,msgByteCntArray[0],msgDataPtrArray[0]);
  866. return kOkRtRC;
  867. }
  868. */
  869. return _cmRtEnqueueMsg(p,p->ssArray[rtSubIdx].htdQueueH,msgDataPtrArray,msgByteCntArray,msgSegCnt,"Host-to-DSP");
  870. }
  871. cmRtRC_t cmRtSysDeliverMsg( cmRtSysH_t h, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId )
  872. {
  873. const void* msgDataPtrArray[] = { msgPtr };
  874. unsigned msgByteCntArray[] = { msgByteCnt };
  875. return cmRtSysDeliverSegMsg(h,msgDataPtrArray,msgByteCntArray,1,srcNetNodeId);
  876. }
  877. cmRtRC_t cmRtSysDeliverIdMsg( cmRtSysH_t h, unsigned rtSubIdx, unsigned id, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId )
  878. {
  879. cmRtRC_t rc;
  880. cmRt_t* p = _cmRtHandleToPtr(h);
  881. // the system must be initialized to use this function
  882. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  883. return rc;
  884. const void* msgDataPtrArray[] = { &rtSubIdx, &id, msgPtr };
  885. unsigned msgByteCntArray[] = { sizeof(rtSubIdx), sizeof(id), msgByteCnt };
  886. return cmRtSysDeliverSegMsg(h,msgDataPtrArray,msgByteCntArray,3,srcNetNodeId);
  887. }
  888. unsigned cmRtSysIsMsgWaiting( cmRtSysH_t h )
  889. {
  890. cmRtRC_t rc;
  891. cmRt_t* p = _cmRtHandleToPtr(h);
  892. // the system must be initialized to use this function
  893. if((rc = _cmRtSysVerifyInit(p,false)) != kOkRtRC )
  894. return 0;
  895. unsigned n = 0;
  896. unsigned retByteCnt;
  897. for(n=0; n < p->ssCnt; ++n )
  898. {
  899. if( (retByteCnt = cmTsMp1cDequeueMsgByteCount(p->dthQueH)) > 0 )
  900. return retByteCnt;
  901. p->waitRtSubIdx = (p->waitRtSubIdx + 1) % p->ssCnt;
  902. }
  903. return 0;
  904. }
  905. cmRtRC_t cmRtSysReceiveMsg( cmRtSysH_t h, void* msgDataPtr, unsigned msgByteCnt )
  906. {
  907. cmRtRC_t rc;
  908. cmRt_t* p = _cmRtHandleToPtr(h);
  909. // the system must be initialized to use this function
  910. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  911. return rc;
  912. //switch( cmTsMp1cDequeueMsg(p->ssArray[p->waitRtSubIdx].dthQueueH,msgDataPtr,msgByteCnt) )
  913. switch( cmTsMp1cDequeueMsg(p->dthQueH,msgDataPtr,msgByteCnt) )
  914. {
  915. case kOkThRC:
  916. p->waitRtSubIdx = (p->waitRtSubIdx + 1) % p->ssCnt;
  917. return kOkRtRC;
  918. case kBufTooSmallThRC:
  919. return kBufTooSmallRtRC;
  920. case kBufEmptyThRC:
  921. return kNoMsgWaitingRtRC;
  922. }
  923. return _cmRtError(p,kTsQueueErrRtRC,"A deque operation failed on the DSP-to-Host message queue.");
  924. }
  925. void cmRtSysStatus( cmRtSysH_t h, unsigned rtSubIdx, cmRtSysStatus_t* statusPtr )
  926. {
  927. cmRt_t* p = _cmRtHandleToPtr(h);
  928. // the system must be initialized to use this function
  929. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  930. return;
  931. if( rtSubIdx < p->ssCnt )
  932. *statusPtr = p->ssArray[rtSubIdx].status;
  933. }
  934. void cmRtSysStatusNotifyEnable( cmRtSysH_t h, unsigned rtSubIdx, bool enableFl )
  935. {
  936. cmRt_t* p = _cmRtHandleToPtr(h);
  937. // the system must be initialized to use this function
  938. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  939. return;
  940. unsigned i = rtSubIdx == cmInvalidIdx ? 0 : rtSubIdx;
  941. unsigned n = rtSubIdx == cmInvalidIdx ? p->ssCnt : rtSubIdx+1;
  942. for(; i<n; ++i)
  943. p->ssArray[i].statusFl = enableFl;
  944. }
  945. bool cmRtSysHandleIsValid( cmRtSysH_t h )
  946. { return h.h != NULL; }
  947. cmRtSysCtx_t* cmRtSysContext( cmRtSysH_t h, unsigned rtSubIdx )
  948. {
  949. cmRt_t* p = _cmRtHandleToPtr(h);
  950. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  951. return NULL;
  952. if( rtSubIdx >= p->ssCnt )
  953. return NULL;
  954. return &p->ssArray[rtSubIdx].ctx;
  955. }
  956. unsigned cmRtSysSubSystemCount( cmRtSysH_t h )
  957. {
  958. cmRt_t* p = _cmRtHandleToPtr(h);
  959. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  960. return 0;
  961. return p->ssCnt;
  962. }
  963. bool cmRtSysNetIsInitialized( cmRtSysH_t h )
  964. {
  965. cmRt_t* p = _cmRtHandleToPtr(h);
  966. unsigned i = 0;
  967. for(; i<p->ssCnt; ++i)
  968. if( cmRtNetIsInitialized(p->ssArray[i].netH) )
  969. return true;
  970. return false;
  971. }
  972. cmRtRC_t cmRtSysNetDoSync( cmRtSysH_t h )
  973. {
  974. cmRtRC_t rc = kOkRtRC;
  975. cmRt_t* p = _cmRtHandleToPtr(h);
  976. unsigned i = 0;
  977. for(; i<p->ssCnt; ++i)
  978. if( cmRtNetIsInitialized(p->ssArray[i].netH) )
  979. cmRtNetDoSync(p->ssArray[i].netH);
  980. return rc;
  981. }
  982. cmRtRC_t cmRtSysNetReport( cmRtSysH_t h )
  983. {
  984. cmRtRC_t rc = kOkRtRC;
  985. cmRt_t* p = _cmRtHandleToPtr(h);
  986. unsigned i = 0;
  987. for(; i<p->ssCnt; ++i)
  988. {
  989. cmRptPrintf(p->err.rpt,"Sub-system:%i\n",i);
  990. if( cmRtNetIsValid(p->ssArray[i].netH))
  991. cmRtNetDoSync(p->ssArray[i].netH);
  992. }
  993. return rc;
  994. }
  995. cmRtRC_t cmRtSysNetGetHandle( cmRtSysH_t h, unsigned rtSubIdx, cmRtNetH_t* hp )
  996. {
  997. cmRtRC_t rc = kOkRtRC;
  998. cmRt_t* p = _cmRtHandleToPtr(h);
  999. assert( rtSubIdx < p->ssCnt );
  1000. if( rtSubIdx < p->ssCnt )
  1001. {
  1002. *hp = p->ssArray[rtSubIdx].netH;
  1003. return rc;
  1004. }
  1005. return cmErrMsg(&p->err,kInvalidArgRtRC,"The rtSubIdx %i is out of range %i.",rtSubIdx,p->ssCnt);
  1006. }
  1007. //===========================================================================================================================
  1008. //
  1009. // cmRtTest()
  1010. //
  1011. /// [cmRtSysTest]
  1012. typedef struct
  1013. {
  1014. double hz; // current synth frq
  1015. long phs; // current synth phase
  1016. double srate; // audio sample rate
  1017. unsigned cbCnt; // DSP cycle count
  1018. bool synthFl; // true=synth false=pass through
  1019. } _cmRtTestCbRecd;
  1020. typedef struct
  1021. {
  1022. unsigned rtSubIdx; // rtSubIdx must always be the first field in the msg
  1023. unsigned id; // 0 = set DSP Hz, 1 = report cbCount to host
  1024. double hz;
  1025. unsigned uint;
  1026. } _cmRtTestMsg;
  1027. long _cmRtSynthSine( _cmRtTestCbRecd* r, cmApSample_t* p, unsigned chCnt, unsigned frmCnt )
  1028. {
  1029. long ph = 0;
  1030. unsigned i;
  1031. for(i=0; i<chCnt; ++i)
  1032. {
  1033. unsigned j;
  1034. cmApSample_t* op = p + i;
  1035. ph = r->phs;
  1036. for(j=0; j<frmCnt; j++, op+=chCnt, ph++)
  1037. *op = (cmApSample_t)(0.9 * sin( 2.0 * M_PI * r->hz * ph / r->srate ));
  1038. }
  1039. return ph;
  1040. }
  1041. unsigned _cmRtTestChIdx = 0;
  1042. cmRC_t _cmRtTestCb( void* cbPtr, unsigned msgByteCnt, const void* msgDataPtr )
  1043. {
  1044. cmRC_t rc = cmOkRC;
  1045. cmRtSysCtx_t* ctx = (cmRtSysCtx_t*)cbPtr;
  1046. cmRtSysSubSys_t* ss = ctx->ss;
  1047. _cmRtTestCbRecd* r = (_cmRtTestCbRecd*)ss->cbDataPtr;
  1048. // update the calback counter
  1049. ++r->cbCnt;
  1050. // if this is an audio update request
  1051. if( msgByteCnt == 0 )
  1052. {
  1053. unsigned i;
  1054. if( r->synthFl )
  1055. {
  1056. long phs = 0;
  1057. if(0)
  1058. {
  1059. for(i=0; i<ctx->oChCnt; ++i)
  1060. if( ctx->oChArray[i] != NULL )
  1061. phs = _cmRtSynthSine(r, ctx->oChArray[i], 1, ss->args.dspFramesPerCycle );
  1062. }
  1063. else
  1064. {
  1065. if( _cmRtTestChIdx < ctx->oChCnt )
  1066. phs = _cmRtSynthSine(r, ctx->oChArray[_cmRtTestChIdx], 1, ss->args.dspFramesPerCycle );
  1067. }
  1068. r->phs = phs;
  1069. }
  1070. else
  1071. {
  1072. // BUG BUG BUG - this assumes that the input and output channels are the same.
  1073. unsigned chCnt = cmMin(ctx->oChCnt,ctx->iChCnt);
  1074. for(i=0; i<chCnt; ++i)
  1075. memcpy(ctx->oChArray[i],ctx->iChArray[i],sizeof(cmSample_t)*ss->args.dspFramesPerCycle);
  1076. }
  1077. }
  1078. else // ... otherwise it is a msg for the DSP process from the host
  1079. {
  1080. _cmRtTestMsg* msg = (_cmRtTestMsg*)msgDataPtr;
  1081. msg->rtSubIdx = ctx->rtSubIdx;
  1082. switch(msg->id)
  1083. {
  1084. case 0:
  1085. r->hz = msg->hz;
  1086. break;
  1087. case 1:
  1088. msg->uint = r->cbCnt;
  1089. msgByteCnt = sizeof(_cmRtTestMsg);
  1090. rc = ctx->dspToHostFunc(ctx,(const void **)&msg,&msgByteCnt,1);
  1091. break;
  1092. }
  1093. }
  1094. return rc;
  1095. }
  1096. // print the usage message for cmAudioPortTest.c
  1097. void _cmRtPrintUsage( cmRpt_t* rpt )
  1098. {
  1099. char msg[] =
  1100. "cmRtSysTest() command switches:\n"
  1101. "-r <srate> -c <chcnt> -b <bufcnt> -f <frmcnt> -i <idevidx> -o <odevidx> -m <msgqsize> -d <dspsize> -t -p -h \n"
  1102. "\n"
  1103. "-r <srate> = sample rate (48000)\n"
  1104. "-c <chcnt> = audio channels (2)\n"
  1105. "-b <bufcnt> = count of buffers (3)\n"
  1106. "-f <frmcnt> = count of samples per buffer (512)\n"
  1107. "-i <idevidx> = input device index (0)\n"
  1108. "-o <odevidx> = output device index (2)\n"
  1109. "-m <msgqsize> = message queue byte count (1024)\n"
  1110. "-d <dspsize> = samples per DSP frame (64)\n"
  1111. "-s = true: sync to input port false: sync to output port\n"
  1112. "-t = copy input to output otherwise synthesize a 1000 Hz sine (false)\n"
  1113. "-p = report but don't start audio devices\n"
  1114. "-h = print this usage message\n";
  1115. cmRptPrintf(rpt,"%s",msg);
  1116. }
  1117. // Get a command line option.
  1118. int _cmRtGetOpt( int argc, const char* argv[], const char* label, int defaultVal, bool boolFl )
  1119. {
  1120. int i = 0;
  1121. for(; i<argc; ++i)
  1122. if( strcmp(label,argv[i]) == 0 )
  1123. {
  1124. if(boolFl)
  1125. return 1;
  1126. if( i == (argc-1) )
  1127. return defaultVal;
  1128. return atoi(argv[i+1]);
  1129. }
  1130. return defaultVal;
  1131. }
  1132. bool _cmRtGetBoolOpt( int argc, const char* argv[], const char* label, bool defaultVal )
  1133. { return _cmRtGetOpt(argc,argv,label,defaultVal?1:0,true)!=0; }
  1134. int _cmRtGetIntOpt( int argc, const char* argv[], const char* label, int defaultVal )
  1135. { return _cmRtGetOpt(argc,argv,label,defaultVal,false); }
  1136. void cmRtSysTest( cmCtx_t* ctx, int argc, const char* argv[] )
  1137. {
  1138. cmRtSysSubSys_t ss;
  1139. cmRtSysH_t h = cmRtSysNullHandle;
  1140. cmRtSysStatus_t status;
  1141. _cmRtTestCbRecd cbRecd = {1000.0,0,48000.0,0};
  1142. cmRpt_t* rpt = &ctx->rpt;
  1143. unsigned meterMs = 50;
  1144. unsigned ssCnt = 1;
  1145. unsigned rtSubIdx = 0;
  1146. if(_cmRtGetBoolOpt(argc,argv,"-h",false))
  1147. _cmRtPrintUsage(rpt);
  1148. cbRecd.srate = _cmRtGetIntOpt(argc,argv,"-r",48000);
  1149. cbRecd.synthFl = _cmRtGetBoolOpt(argc,argv,"-t",false)==false;
  1150. ss.args.rpt = rpt;
  1151. ss.args.inDevIdx = _cmRtGetIntOpt( argc,argv,"-i",0);
  1152. ss.args.outDevIdx = _cmRtGetIntOpt( argc,argv,"-o",2);
  1153. ss.args.syncInputFl = _cmRtGetBoolOpt(argc,argv,"-s",true);
  1154. ss.args.msgQueueByteCnt = _cmRtGetIntOpt( argc,argv,"-m",8192);
  1155. ss.args.devFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-f",512);
  1156. ss.args.dspFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-d",64);;
  1157. ss.args.audioBufCnt = _cmRtGetIntOpt( argc,argv,"-b",3);
  1158. ss.args.srate = cbRecd.srate;
  1159. ss.cbFunc = _cmRtTestCb; // set the DSP entry function
  1160. ss.cbDataPtr = &cbRecd; // set the DSP function argument record
  1161. cmRptPrintf(rpt,"in:%i out:%i syncFl:%i que:%i fpc:%i dsp:%i bufs:%i sr:%f\n",ss.args.inDevIdx,ss.args.outDevIdx,ss.args.syncInputFl,
  1162. ss.args.msgQueueByteCnt,ss.args.devFramesPerCycle,ss.args.dspFramesPerCycle,ss.args.audioBufCnt,ss.args.srate);
  1163. if( cmApNrtAllocate(rpt) != kOkApRC )
  1164. goto errLabel;
  1165. if( cmApFileAllocate(rpt) != kOkApRC )
  1166. goto errLabel;
  1167. // initialize the audio device system
  1168. if( cmApInitialize(rpt) != kOkApRC )
  1169. goto errLabel;
  1170. cmApReport(rpt);
  1171. // initialize the audio buffer
  1172. if( cmApBufInitialize( cmApDeviceCount(), meterMs ) != kOkApRC )
  1173. goto errLabel;
  1174. // initialize the real-time system
  1175. if( cmRtSysAllocate(&h,ctx) != kOkRtRC )
  1176. goto errLabel;
  1177. if( cmRtSysBeginCfg(h,NULL,NULL,meterMs,ssCnt) != kOkRtRC )
  1178. goto errLabel;
  1179. if( cmRtSysCfg(h,&ss,rtSubIdx) != kOkRtRC )
  1180. goto errLabel;
  1181. if( cmRtSysEndCfg(h) != kOkRtRC )
  1182. goto errLabel;
  1183. // start the real-time system
  1184. cmRtSysEnable(h,true);
  1185. char c = 0;
  1186. printf("q=quit a-g=note n=ch r=rqst s=status\n");
  1187. // simulate a host event loop
  1188. while(c != 'q')
  1189. {
  1190. _cmRtTestMsg msg = {0,0,0,0};
  1191. bool fl = true;
  1192. // wait here for a key press
  1193. c =(char)fgetc(stdin);
  1194. fflush(stdin);
  1195. switch(c)
  1196. {
  1197. case 'c': msg.hz = cmMidiToHz(60); break;
  1198. case 'd': msg.hz = cmMidiToHz(62); break;
  1199. case 'e': msg.hz = cmMidiToHz(64); break;
  1200. case 'f': msg.hz = cmMidiToHz(65); break;
  1201. case 'g': msg.hz = cmMidiToHz(67); break;
  1202. case 'a': msg.hz = cmMidiToHz(69); break;
  1203. case 'b': msg.hz = cmMidiToHz(71); break;
  1204. case 'r': msg.id = 1; break; // request DSP process to send a callback count
  1205. case 'n': ++_cmRtTestChIdx; printf("ch:%i\n",_cmRtTestChIdx); break;
  1206. case 's':
  1207. // report the real-time system status
  1208. cmRtSysStatus(h,0,&status);
  1209. printf("phs:%li cb count:%i (upd:%i wake:%i acb:%i msgs:%i)\n",cbRecd.phs, cbRecd.cbCnt, status.updateCnt, status.wakeupCnt, status.audioCbCnt, status.msgCbCnt);
  1210. //printf("%f \n",status.oMeterArray[0]);
  1211. fl = false;
  1212. break;
  1213. default:
  1214. fl=false;
  1215. }
  1216. if( fl )
  1217. {
  1218. // transmit a command to the DSP process
  1219. cmRtSysDeliverMsg(h,&msg, sizeof(msg), cmInvalidId);
  1220. }
  1221. // check if messages are waiting to be delivered from the DSP process
  1222. unsigned msgByteCnt;
  1223. if((msgByteCnt = cmRtSysIsMsgWaiting(h)) > 0 )
  1224. {
  1225. char buf[ msgByteCnt ];
  1226. // rcv a msg from the DSP process
  1227. if( cmRtSysReceiveMsg(h,buf,msgByteCnt) == kOkRtRC )
  1228. {
  1229. _cmRtTestMsg* msg = (_cmRtTestMsg*)buf;
  1230. switch(msg->id)
  1231. {
  1232. case 1:
  1233. printf("RCV: Callback count:%i\n",msg->uint);
  1234. break;
  1235. }
  1236. }
  1237. }
  1238. // report the audio buffer status
  1239. //cmApBufReport(ss.args.rpt);
  1240. }
  1241. // stop the real-time system
  1242. cmRtSysEnable(h,false);
  1243. goto exitLabel;
  1244. errLabel:
  1245. printf("REAL-TIME SYSTEM TEST ERROR\n");
  1246. exitLabel:
  1247. cmRtSysFree(&h);
  1248. cmApFinalize();
  1249. cmApFileFree();
  1250. cmApNrtFree();
  1251. cmApBufFinalize();
  1252. }
  1253. /// [cmRtSysTest]