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

cmRtSys.c 47KB

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