libcm is a C development framework with an emphasis on audio signal processing applications.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

cmRtSys.c 46KB

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