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

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