libcm is a C development framework with an emphasis on audio signal processing applications.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

cmRtSys.c 49KB

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