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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  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 = { NULL };
  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, 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. //===========================================================================================================================
  996. //
  997. // cmRtTest()
  998. //
  999. /// [cmRtSysTest]
  1000. typedef struct
  1001. {
  1002. double hz; // current synth frq
  1003. long phs; // current synth phase
  1004. double srate; // audio sample rate
  1005. unsigned cbCnt; // DSP cycle count
  1006. bool synthFl; // true=synth false=pass through
  1007. } _cmRtTestCbRecd;
  1008. typedef struct
  1009. {
  1010. unsigned rtSubIdx; // rtSubIdx must always be the first field in the msg
  1011. unsigned id; // 0 = set DSP Hz, 1 = report cbCount to host
  1012. double hz;
  1013. unsigned uint;
  1014. } _cmRtTestMsg;
  1015. long _cmRtSynthSine( _cmRtTestCbRecd* r, cmApSample_t* p, unsigned chCnt, unsigned frmCnt )
  1016. {
  1017. long ph = 0;
  1018. unsigned i;
  1019. for(i=0; i<chCnt; ++i)
  1020. {
  1021. unsigned j;
  1022. cmApSample_t* op = p + i;
  1023. ph = r->phs;
  1024. for(j=0; j<frmCnt; j++, op+=chCnt, ph++)
  1025. *op = (cmApSample_t)(0.9 * sin( 2.0 * M_PI * r->hz * ph / r->srate ));
  1026. }
  1027. return ph;
  1028. }
  1029. unsigned _cmRtTestChIdx = 0;
  1030. cmRC_t _cmRtTestCb( void* cbPtr, unsigned msgByteCnt, const void* msgDataPtr )
  1031. {
  1032. cmRC_t rc = cmOkRC;
  1033. cmRtSysCtx_t* ctx = (cmRtSysCtx_t*)cbPtr;
  1034. cmRtSysSubSys_t* ss = ctx->ss;
  1035. _cmRtTestCbRecd* r = (_cmRtTestCbRecd*)ss->cbDataPtr;
  1036. // update the calback counter
  1037. ++r->cbCnt;
  1038. // if this is an audio update request
  1039. if( msgByteCnt == 0 )
  1040. {
  1041. unsigned i;
  1042. if( r->synthFl )
  1043. {
  1044. long phs = 0;
  1045. if(0)
  1046. {
  1047. for(i=0; i<ctx->oChCnt; ++i)
  1048. if( ctx->oChArray[i] != NULL )
  1049. phs = _cmRtSynthSine(r, ctx->oChArray[i], 1, ss->args.dspFramesPerCycle );
  1050. }
  1051. else
  1052. {
  1053. if( _cmRtTestChIdx < ctx->oChCnt )
  1054. phs = _cmRtSynthSine(r, ctx->oChArray[_cmRtTestChIdx], 1, ss->args.dspFramesPerCycle );
  1055. }
  1056. r->phs = phs;
  1057. }
  1058. else
  1059. {
  1060. // BUG BUG BUG - this assumes that the input and output channels are the same.
  1061. unsigned chCnt = cmMin(ctx->oChCnt,ctx->iChCnt);
  1062. for(i=0; i<chCnt; ++i)
  1063. memcpy(ctx->oChArray[i],ctx->iChArray[i],sizeof(cmSample_t)*ss->args.dspFramesPerCycle);
  1064. }
  1065. }
  1066. else // ... otherwise it is a msg for the DSP process from the host
  1067. {
  1068. _cmRtTestMsg* msg = (_cmRtTestMsg*)msgDataPtr;
  1069. msg->rtSubIdx = ctx->rtSubIdx;
  1070. switch(msg->id)
  1071. {
  1072. case 0:
  1073. r->hz = msg->hz;
  1074. break;
  1075. case 1:
  1076. msg->uint = r->cbCnt;
  1077. msgByteCnt = sizeof(_cmRtTestMsg);
  1078. rc = ctx->dspToHostFunc(ctx,(const void **)&msg,&msgByteCnt,1);
  1079. break;
  1080. }
  1081. }
  1082. return rc;
  1083. }
  1084. // print the usage message for cmAudioPortTest.c
  1085. void _cmRtPrintUsage( cmRpt_t* rpt )
  1086. {
  1087. char msg[] =
  1088. "cmRtSysTest() command switches:\n"
  1089. "-r <srate> -c <chcnt> -b <bufcnt> -f <frmcnt> -i <idevidx> -o <odevidx> -m <msgqsize> -d <dspsize> -t -p -h \n"
  1090. "\n"
  1091. "-r <srate> = sample rate (48000)\n"
  1092. "-c <chcnt> = audio channels (2)\n"
  1093. "-b <bufcnt> = count of buffers (3)\n"
  1094. "-f <frmcnt> = count of samples per buffer (512)\n"
  1095. "-i <idevidx> = input device index (0)\n"
  1096. "-o <odevidx> = output device index (2)\n"
  1097. "-m <msgqsize> = message queue byte count (1024)\n"
  1098. "-d <dspsize> = samples per DSP frame (64)\n"
  1099. "-s = true: sync to input port false: sync to output port\n"
  1100. "-t = copy input to output otherwise synthesize a 1000 Hz sine (false)\n"
  1101. "-p = report but don't start audio devices\n"
  1102. "-h = print this usage message\n";
  1103. cmRptPrintf(rpt,"%s",msg);
  1104. }
  1105. // Get a command line option.
  1106. int _cmRtGetOpt( int argc, const char* argv[], const char* label, int defaultVal, bool boolFl )
  1107. {
  1108. int i = 0;
  1109. for(; i<argc; ++i)
  1110. if( strcmp(label,argv[i]) == 0 )
  1111. {
  1112. if(boolFl)
  1113. return 1;
  1114. if( i == (argc-1) )
  1115. return defaultVal;
  1116. return atoi(argv[i+1]);
  1117. }
  1118. return defaultVal;
  1119. }
  1120. bool _cmRtGetBoolOpt( int argc, const char* argv[], const char* label, bool defaultVal )
  1121. { return _cmRtGetOpt(argc,argv,label,defaultVal?1:0,true)!=0; }
  1122. int _cmRtGetIntOpt( int argc, const char* argv[], const char* label, int defaultVal )
  1123. { return _cmRtGetOpt(argc,argv,label,defaultVal,false); }
  1124. void cmRtSysTest( cmCtx_t* ctx, int argc, const char* argv[] )
  1125. {
  1126. cmRtSysSubSys_t ss;
  1127. cmRtSysH_t h = cmRtSysNullHandle;
  1128. cmRtSysStatus_t status;
  1129. _cmRtTestCbRecd cbRecd = {1000.0,0,48000.0,0};
  1130. cmRpt_t* rpt = &ctx->rpt;
  1131. unsigned meterMs = 50;
  1132. unsigned ssCnt = 1;
  1133. unsigned rtSubIdx = 0;
  1134. if(_cmRtGetBoolOpt(argc,argv,"-h",false))
  1135. _cmRtPrintUsage(rpt);
  1136. cbRecd.srate = _cmRtGetIntOpt(argc,argv,"-r",48000);
  1137. cbRecd.synthFl = _cmRtGetBoolOpt(argc,argv,"-t",false)==false;
  1138. ss.args.rpt = rpt;
  1139. ss.args.inDevIdx = _cmRtGetIntOpt( argc,argv,"-i",0);
  1140. ss.args.outDevIdx = _cmRtGetIntOpt( argc,argv,"-o",2);
  1141. ss.args.syncInputFl = _cmRtGetBoolOpt(argc,argv,"-s",true);
  1142. ss.args.msgQueueByteCnt = _cmRtGetIntOpt( argc,argv,"-m",8192);
  1143. ss.args.devFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-f",512);
  1144. ss.args.dspFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-d",64);;
  1145. ss.args.audioBufCnt = _cmRtGetIntOpt( argc,argv,"-b",3);
  1146. ss.args.srate = cbRecd.srate;
  1147. ss.cbFunc = _cmRtTestCb; // set the DSP entry function
  1148. ss.cbDataPtr = &cbRecd; // set the DSP function argument record
  1149. 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,
  1150. ss.args.msgQueueByteCnt,ss.args.devFramesPerCycle,ss.args.dspFramesPerCycle,ss.args.audioBufCnt,ss.args.srate);
  1151. if( cmApNrtAllocate(rpt) != kOkApRC )
  1152. goto errLabel;
  1153. if( cmApFileAllocate(rpt) != kOkApRC )
  1154. goto errLabel;
  1155. // initialize the audio device system
  1156. if( cmApInitialize(rpt) != kOkApRC )
  1157. goto errLabel;
  1158. cmApReport(rpt);
  1159. // initialize the audio buffer
  1160. if( cmApBufInitialize( cmApDeviceCount(), meterMs ) != kOkApRC )
  1161. goto errLabel;
  1162. // initialize the real-time system
  1163. if( cmRtSysAllocate(&h,ctx) != kOkRtRC )
  1164. goto errLabel;
  1165. if( cmRtSysBeginCfg(h,NULL,NULL,meterMs,ssCnt) != kOkRtRC )
  1166. goto errLabel;
  1167. if( cmRtSysCfg(h,&ss,rtSubIdx) != kOkRtRC )
  1168. goto errLabel;
  1169. if( cmRtSysEndCfg(h) != kOkRtRC )
  1170. goto errLabel;
  1171. // start the real-time system
  1172. cmRtSysEnable(h,true);
  1173. char c = 0;
  1174. printf("q=quit a-g=note n=ch r=rqst s=status\n");
  1175. // simulate a host event loop
  1176. while(c != 'q')
  1177. {
  1178. _cmRtTestMsg msg = {0,0,0,0};
  1179. bool fl = true;
  1180. // wait here for a key press
  1181. c =(char)fgetc(stdin);
  1182. fflush(stdin);
  1183. switch(c)
  1184. {
  1185. case 'c': msg.hz = cmMidiToHz(60); break;
  1186. case 'd': msg.hz = cmMidiToHz(62); break;
  1187. case 'e': msg.hz = cmMidiToHz(64); break;
  1188. case 'f': msg.hz = cmMidiToHz(65); break;
  1189. case 'g': msg.hz = cmMidiToHz(67); break;
  1190. case 'a': msg.hz = cmMidiToHz(69); break;
  1191. case 'b': msg.hz = cmMidiToHz(71); break;
  1192. case 'r': msg.id = 1; break; // request DSP process to send a callback count
  1193. case 'n': ++_cmRtTestChIdx; printf("ch:%i\n",_cmRtTestChIdx); break;
  1194. case 's':
  1195. // report the real-time system status
  1196. cmRtSysStatus(h,0,&status);
  1197. 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);
  1198. //printf("%f \n",status.oMeterArray[0]);
  1199. fl = false;
  1200. break;
  1201. default:
  1202. fl=false;
  1203. }
  1204. if( fl )
  1205. {
  1206. // transmit a command to the DSP process
  1207. cmRtSysDeliverMsg(h,&msg, sizeof(msg), cmInvalidId);
  1208. }
  1209. // check if messages are waiting to be delivered from the DSP process
  1210. unsigned msgByteCnt;
  1211. if((msgByteCnt = cmRtSysIsMsgWaiting(h)) > 0 )
  1212. {
  1213. char buf[ msgByteCnt ];
  1214. // rcv a msg from the DSP process
  1215. if( cmRtSysReceiveMsg(h,buf,msgByteCnt) == kOkRtRC )
  1216. {
  1217. _cmRtTestMsg* msg = (_cmRtTestMsg*)buf;
  1218. switch(msg->id)
  1219. {
  1220. case 1:
  1221. printf("RCV: Callback count:%i\n",msg->uint);
  1222. break;
  1223. }
  1224. }
  1225. }
  1226. // report the audio buffer status
  1227. //cmApBufReport(ss.args.rpt);
  1228. }
  1229. // stop the real-time system
  1230. cmRtSysEnable(h,false);
  1231. goto exitLabel;
  1232. errLabel:
  1233. printf("REAL-TIME SYSTEM TEST ERROR\n");
  1234. exitLabel:
  1235. cmRtSysFree(&h);
  1236. cmApFinalize();
  1237. cmApFileFree();
  1238. cmApNrtFree();
  1239. cmApBufFinalize();
  1240. }
  1241. /// [cmRtSysTest]