libcm is a C development framework with an emphasis on audio signal processing applications.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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