libcm is a C development framework with an emphasis on audio signal processing applications.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

cmRtSys.c 46KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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 _cmRtSysNetRecv( void* cbArg, const char* data, unsigned dataByteCnt, const struct sockaddr_in* fromAddr )
  428. {
  429. _cmRtCfg_t* cp = (_cmRtCfg_t*)cbArg;
  430. cmRtSysH_t h;
  431. h.h = cp->p;
  432. cmRtSysDeliverMsg(h,data,dataByteCnt,cmInvalidId);
  433. }
  434. cmRtRC_t cmRtSysAllocate( cmRtSysH_t* hp, cmCtx_t* ctx )
  435. {
  436. cmRtRC_t rc;
  437. if((rc = cmRtSysFree(hp)) != kOkRtRC )
  438. return rc;
  439. cmRt_t* p = cmMemAllocZ( cmRt_t, 1 );
  440. cmErrSetup(&p->err,&ctx->rpt,"Real-Time System");
  441. p->ctx = ctx;
  442. hp->h = p;
  443. return rc;
  444. }
  445. cmRtRC_t cmRtSysFree( cmRtSysH_t* hp )
  446. {
  447. cmRtRC_t rc;
  448. if( hp == NULL || hp->h == NULL )
  449. return kOkRtRC;
  450. if((rc = cmRtSysFinalize(*hp)) != kOkRtRC )
  451. return rc;
  452. cmRt_t* p = _cmRtHandleToPtr(*hp);
  453. cmMemFree(p);
  454. hp->h = NULL;
  455. return rc;
  456. }
  457. cmRtRC_t _cmRtSysEnable( cmRt_t* p, bool enableFl )
  458. {
  459. cmRtRC_t rc = kOkRtRC;
  460. unsigned i;
  461. unsigned n;
  462. unsigned tickMs = 20;
  463. unsigned timeOutMs = 10000;
  464. for(i=0; i<p->ssCnt; ++i)
  465. {
  466. _cmRtCfg_t* cp = p->ssArray + i;
  467. if( enableFl )
  468. {
  469. cp->cmdId = kNoCmdId;
  470. cmThUIntIncr(&cp->cmdId,kEnableCbCmdId);
  471. for(n=0; n<timeOutMs && cp->cbEnableFl==false; n+=tickMs )
  472. cmSleepMs(tickMs);
  473. cmThUIntDecr(&cp->cmdId,kEnableCbCmdId);
  474. }
  475. else
  476. {
  477. cp->cmdId = kNoCmdId;
  478. cmThUIntIncr(&cp->cmdId,kDisableCbCmdId);
  479. // wait for the rt thread to return from a client callbacks
  480. for(n=0; n<timeOutMs && cp->cbEnableFl; n+=tickMs )
  481. cmSleepMs(tickMs);
  482. cmThUIntDecr(&cp->cmdId,kDisableCbCmdId);
  483. }
  484. if( n >= timeOutMs )
  485. rc = cmErrMsg(&p->err,kTimeOutErrRtRC,"RT System %s timed out after %i milliseconds.",enableFl?"enable":"disable",timeOutMs);
  486. }
  487. // enable network sync mode
  488. if( enableFl)
  489. for(i=0; i<p->ssCnt; ++i)
  490. {
  491. _cmRtCfg_t* cp = p->ssArray + i;
  492. if( cmRtNetIsValid(cp->netH) )
  493. if( cmRtNetBeginSyncMode(cp->netH) != kOkNetRC )
  494. rc = cmErrMsg(&p->err,kNetErrRtRC,"Network Mgr. failed on entering sync mode.");
  495. }
  496. return rc;
  497. }
  498. cmRtRC_t _cmRtSysFinalize( cmRt_t* p )
  499. {
  500. cmRtRC_t rc = kOkRtRC;
  501. unsigned i;
  502. // mark the real-time system as NOT initialized
  503. p->initFl = false;
  504. // be sure all audio callbacks are disabled before continuing.
  505. if((rc = _cmRtSysEnable(p,false)) != kOkRtRC )
  506. return _cmRtError(p,rc,"real-time system finalize failed because device halting failed.");
  507. // stop the audio devices
  508. for(i=0; i<p->ssCnt; ++i)
  509. {
  510. _cmRtCfg_t* cp = p->ssArray + i;
  511. // stop the input device
  512. if((rc = cmApDeviceStop( cp->ss.args.inDevIdx )) != kOkRtRC )
  513. return _cmRtError(p,kAudioDevStopFailRtRC,"The audio input device stop failed.");
  514. // stop the output device
  515. if((rc = cmApDeviceStop( cp->ss.args.outDevIdx )) != kOkRtRC )
  516. return _cmRtError(p,kAudioDevStopFailRtRC,"The audio output device stop failed.");
  517. }
  518. for(i=0; i<p->ssCnt; ++i)
  519. {
  520. _cmRtCfg_t* cp = p->ssArray + i;
  521. if( cmThreadIsValid( cp->threadH ))
  522. {
  523. // inform the thread that it should exit
  524. cp->runFl = false;
  525. cp->statusFl = false;
  526. // signal the cond var to cause the thread to run
  527. if((rc = cmThreadMutexSignalCondVar(cp->engMutexH)) != kOkThRC )
  528. _cmRtError(p,kMutexErrRtRC,"Finalize signal cond. var. failed.");
  529. // wait to take control of the mutex - this will occur when the thread function exits
  530. if((rc = cmThreadMutexLock(cp->engMutexH)) != kOkThRC )
  531. _cmRtError(p,kMutexErrRtRC,"Finalize lock failed.");
  532. // unlock the mutex because it is no longer needed and must be unlocked to be destroyed
  533. if((rc = cmThreadMutexUnlock(cp->engMutexH)) != kOkThRC )
  534. _cmRtError(p,kMutexErrRtRC,"Finalize unlock failed.");
  535. // destroy the thread
  536. if((rc = cmThreadDestroy( &cp->threadH )) != kOkThRC )
  537. _cmRtError(p,kThreadErrRtRC,"Thread destroy failed.");
  538. }
  539. // destroy the mutex
  540. if( cmThreadMutexIsValid(cp->engMutexH) )
  541. if((rc = cmThreadMutexDestroy( &cp->engMutexH )) != kOkThRC )
  542. _cmRtError(p,kMutexErrRtRC,"Mutex destroy failed.");
  543. // release the network mgr
  544. if( cmRtNetFree(&cp->netH) != kOkNetRC )
  545. _cmRtError(p,kNetErrRtRC,"Network Mrr. release failed.");
  546. // remove the MIDI callback
  547. if( cmMpIsInitialized() && cmMpUsesCallback(-1,-1, _cmRtSysMidiCallback, cp) )
  548. if( cmMpRemoveCallback( -1, -1, _cmRtSysMidiCallback, cp ) != kOkMpRC )
  549. _cmRtError(p,kMidiSysFailRtRC,"MIDI callback removal failed.");
  550. // destroy the host-to-dsp msg queue
  551. if( cmTsMp1cIsValid(cp->htdQueueH ) )
  552. if((rc = cmTsMp1cDestroy( &cp->htdQueueH )) != kOkThRC )
  553. _cmRtError(p,kTsQueueErrRtRC,"Host-to-DSP msg queue destroy failed.");
  554. // destroy the dsp-to-host msg queue
  555. if( cmTsMp1cIsValid(p->dthQueH) )
  556. if((rc = cmTsMp1cDestroy( &p->dthQueH )) != kOkThRC )
  557. _cmRtError(p,kTsQueueErrRtRC,"DSP-to-Host msg queue destroy failed.");
  558. cmMemPtrFree(&cp->ctx.iChArray);
  559. cmMemPtrFree(&cp->ctx.oChArray);
  560. cp->ctx.iChCnt = 0;
  561. cp->ctx.oChCnt = 0;
  562. cmMemPtrFree(&cp->iMeterArray);
  563. cmMemPtrFree(&cp->oMeterArray);
  564. cp->status.iMeterCnt = 0;
  565. cp->status.oMeterCnt = 0;
  566. }
  567. cmMemPtrFree(&p->ssArray);
  568. p->ssCnt = 0;
  569. return rc;
  570. }
  571. // A given device may be used as an input device exactly once and an
  572. // output device exactly once. When the input to a given device is used
  573. // by one sub-system and the output is used by another then both sub-systems
  574. // must use the same srate,devFramesPerCycle, audioBufCnt and dspFramesPerCycle.
  575. cmRtRC_t _cmRtSysValidate( cmRt_t* p )
  576. {
  577. unsigned i,j,k;
  578. for(i=0; i<2; ++i)
  579. {
  580. // examine input devices - then output devices
  581. bool inputFl = i==0;
  582. bool outputFl = !inputFl;
  583. for(j=0; j<p->ssCnt; ++j)
  584. {
  585. cmRtSysArgs_t* s0 = &p->ssArray[j].ss.args;
  586. unsigned devIdx = inputFl ? s0->inDevIdx : s0->outDevIdx;
  587. for(k=0; k<p->ssCnt && devIdx != cmInvalidIdx; ++k)
  588. if( k != j )
  589. {
  590. cmRtSysArgs_t* s1 = &p->ssArray[k].ss.args;
  591. // if the device was used as input or output multple times then signal an error
  592. if( (inputFl && (s1->inDevIdx == devIdx) && s1->inDevIdx != cmInvalidIdx) || (outputFl && (s1->outDevIdx == devIdx) && s1->outDevIdx != cmInvalidIdx) )
  593. return cmErrMsg(&p->err,kInvalidArgRtRC,"The device %i was used as an %s by multiple sub-systems.", devIdx, inputFl ? "input" : "output");
  594. // if this device is being used by another subsystem ...
  595. if( (inputFl && (s1->outDevIdx == devIdx) && s1->inDevIdx != cmInvalidIdx) || (outputFl && (s1->outDevIdx == devIdx) && s1->outDevIdx != cmInvalidIdx ) )
  596. {
  597. // ... then some of its buffer spec's must match
  598. if( s0->srate != s1->srate || s0->audioBufCnt != s1->audioBufCnt || s0->dspFramesPerCycle != s1->dspFramesPerCycle || s0->devFramesPerCycle != s1->devFramesPerCycle )
  599. return cmErrMsg(&p->err,kInvalidArgRtRC,"The device %i is used by different sub-system with different audio buffer parameters.",devIdx);
  600. }
  601. }
  602. }
  603. }
  604. return kOkRtRC;
  605. }
  606. cmRtRC_t cmRtSysBeginCfg( cmRtSysH_t h, cmTsQueueCb_t clientCbFunc, void* clientCbArg, unsigned meterMs, unsigned ssCnt )
  607. {
  608. cmRt_t* p = _cmRtHandleToPtr(h);
  609. cmRtRC_t rc;
  610. // always finalize before iniitalize
  611. if((rc = cmRtSysFinalize(h)) != kOkRtRC )
  612. return rc;
  613. p->ssArray = cmMemAllocZ( _cmRtCfg_t, ssCnt );
  614. p->ssCnt = ssCnt;
  615. p->clientCbFunc = clientCbFunc;
  616. p->clientCbArg = clientCbArg;
  617. return rc;
  618. }
  619. cmRtRC_t cmRtSysCfg( cmRtSysH_t h, const cmRtSysSubSys_t* ss, unsigned rtSubIdx )
  620. {
  621. cmRtRC_t rc;
  622. unsigned j;
  623. cmRt_t* p = _cmRtHandleToPtr(h);
  624. assert( rtSubIdx < p->ssCnt);
  625. _cmRtCfg_t* cp = p->ssArray + rtSubIdx;;
  626. cp->p = p;
  627. cp->ss = *ss; // copy the cfg into the internal real-time system state
  628. cp->runFl = false;
  629. cp->statusFl = false;
  630. cp->ctx.reserved = p;
  631. cp->ctx.rtSubIdx = rtSubIdx;
  632. cp->ctx.ss = &cp->ss;
  633. cp->ctx.begSmpIdx = 0;
  634. cp->ctx.dspToHostFunc = _cmRtDspToHostMsgCallback;
  635. // validate the input device index
  636. if( ss->args.inDevIdx != cmInvalidIdx && ss->args.inDevIdx >= cmApDeviceCount() )
  637. {
  638. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"The audio input device index %i is invalid.",ss->args.inDevIdx);
  639. goto errLabel;
  640. }
  641. // validate the output device index
  642. if( ss->args.outDevIdx != cmInvalidIdx && ss->args.outDevIdx >= cmApDeviceCount() )
  643. {
  644. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"The audio output device index %i is invalid.",ss->args.outDevIdx);
  645. goto errLabel;
  646. }
  647. // setup the input device
  648. if( ss->args.inDevIdx != cmInvalidIdx )
  649. if((rc = cmApDeviceSetup( ss->args.inDevIdx, ss->args.srate, ss->args.devFramesPerCycle, _cmRtSysAudioUpdate, cp )) != kOkRtRC )
  650. {
  651. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"Audio input device setup failed.");
  652. goto errLabel;
  653. }
  654. // setup the output device
  655. if( ss->args.outDevIdx != ss->args.inDevIdx && ss->args.outDevIdx != cmInvalidIdx )
  656. if((rc = cmApDeviceSetup( ss->args.outDevIdx, ss->args.srate, ss->args.devFramesPerCycle, _cmRtSysAudioUpdate, cp )) != kOkRtRC )
  657. {
  658. rc = _cmRtError(p,kAudioDevSetupErrRtRC,"Audio output device setup failed.");
  659. goto errLabel;
  660. }
  661. // setup the input device buffer
  662. if( ss->args.inDevIdx != cmInvalidIdx )
  663. 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 )
  664. {
  665. rc = _cmRtError(p,kAudioBufSetupErrRtRC,"Audio buffer input setup failed.");
  666. goto errLabel;
  667. }
  668. cmApBufEnableMeter(ss->args.inDevIdx, -1, kInApFl | kEnableApFl );
  669. cmApBufEnableMeter(ss->args.outDevIdx,-1, kOutApFl | kEnableApFl );
  670. // setup the input audio buffer ptr array - used to send input audio to the DSP system in _cmRtDspExecCallback()
  671. if((cp->ctx.iChCnt = cmApDeviceChannelCount(ss->args.inDevIdx, true)) != 0 )
  672. cp->ctx.iChArray = cmMemAllocZ( cmSample_t*, cp->ctx.iChCnt );
  673. // setup the output device buffer
  674. if( ss->args.outDevIdx != ss->args.inDevIdx )
  675. 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 )
  676. return _cmRtError(p,kAudioBufSetupErrRtRC,"Audio buffer ouput device setup failed.");
  677. // setup the output audio buffer ptr array - used to recv output audio from the DSP system in _cmRtDspExecCallback()
  678. if((cp->ctx.oChCnt = cmApDeviceChannelCount(ss->args.outDevIdx, false)) != 0 )
  679. cp->ctx.oChArray = cmMemAllocZ( cmSample_t*, cp->ctx.oChCnt );
  680. // determine the sync source
  681. cp->syncInputFl = ss->args.syncInputFl;
  682. // if sync'ing to an unavailable device then sync to the available device
  683. if( ss->args.syncInputFl && cp->ctx.iChCnt == 0 )
  684. cp->syncInputFl = false;
  685. if( ss->args.syncInputFl==false && cp->ctx.oChCnt == 0 )
  686. cp->syncInputFl = true;
  687. // setup the status record
  688. cp->status.hdr.rtSubIdx = cp->ctx.rtSubIdx;
  689. cp->status.iDevIdx = ss->args.inDevIdx;
  690. cp->status.oDevIdx = ss->args.outDevIdx;
  691. cp->status.iMeterCnt = cp->ctx.iChCnt;
  692. cp->status.oMeterCnt = cp->ctx.oChCnt;
  693. cp->iMeterArray = cmMemAllocZ( double, cp->status.iMeterCnt );
  694. cp->oMeterArray = cmMemAllocZ( double, cp->status.oMeterCnt );
  695. //cp->udpH = cfg->udpH;
  696. // create the real-time system thread
  697. if((rc = cmThreadCreate( &cp->threadH, _cmRtThreadCallback, cp, ss->args.rpt )) != kOkThRC )
  698. {
  699. rc = _cmRtError(p,kThreadErrRtRC,"Thread create failed.");
  700. goto errLabel;
  701. }
  702. // create the real-time system mutex
  703. if((rc = cmThreadMutexCreate( &cp->engMutexH, ss->args.rpt )) != kOkThRC )
  704. {
  705. rc = _cmRtError(p,kMutexErrRtRC,"Thread mutex create failed.");
  706. goto errLabel;
  707. }
  708. // create the host-to-dsp thread safe msg queue
  709. if((rc = cmTsMp1cCreate( &cp->htdQueueH, ss->args.msgQueueByteCnt, ss->cbFunc, &cp->ctx, ss->args.rpt )) != kOkThRC )
  710. {
  711. rc = _cmRtError(p,kTsQueueErrRtRC,"Host-to-DSP msg queue create failed.");
  712. goto errLabel;
  713. }
  714. // create the dsp-to-host thread safe msg queue
  715. if( cmTsMp1cIsValid( p->dthQueH ) == false )
  716. {
  717. if((rc = cmTsMp1cCreate( &p->dthQueH, ss->args.msgQueueByteCnt, p->clientCbFunc, p->clientCbArg, ss->args.rpt )) != kOkThRC )
  718. {
  719. rc = _cmRtError(p,kTsQueueErrRtRC,"DSP-to-Host msg queue create failed.");
  720. goto errLabel;
  721. }
  722. }
  723. // install an external MIDI port callback handler for incoming MIDI messages
  724. if( cmMpIsInitialized() )
  725. if( cmMpInstallCallback( -1, -1, _cmRtSysMidiCallback, cp ) != kOkMpRC )
  726. {
  727. rc = _cmRtError(p,kMidiSysFailRtRC,"MIDI system callback installation failed.");
  728. goto errLabel;
  729. }
  730. // setup the sub-system status notification
  731. cp->statusUpdateSmpCnt = floor(cmApBufMeterMs() * cp->ss.args.srate / 1000.0 );
  732. cp->statusUpdateSmpIdx = 0;
  733. // allocate the network mgr
  734. if( cmRtNetAlloc(p->ctx,&cp->netH, _cmRtSysNetRecv, cp ) != kOkNetRC )
  735. {
  736. rc = _cmRtError(p,kNetErrRtRC,"Network allocation failed.");
  737. goto errLabel;
  738. }
  739. // register the local and remote notes
  740. for(j=0; j<ss->netNodeCnt; ++j)
  741. {
  742. cmRtSysNetNode_t* nn = ss->netNodeArray + j;
  743. if( cmRtNetRegisterLocalNode( cp->netH, nn->label, nn->ipAddr, nn->ipPort) != kOkNetRC )
  744. {
  745. rc = _cmRtError(p,kNetErrRtRC,"Network node allocation failed on label:%s addr:%s port:%i.",cmStringNullGuard(nn->label),cmStringNullGuard(nn->ipAddr),nn->ipPort);
  746. goto errLabel;
  747. }
  748. }
  749. // register the local endpoints
  750. for(j=0; j<ss->endptCnt; ++j)
  751. {
  752. cmRtSysNetEndpt_t* ep = ss->endptArray + j;
  753. if( cmRtNetRegisterEndPoint( cp->netH, ep->label, ep->id ) != kOkNetRC )
  754. {
  755. rc = _cmRtError(p,kNetErrRtRC,"Network end point allocation failed on label:%s id:%i.",cmStringNullGuard(ep->label),ep->id);
  756. goto errLabel;
  757. }
  758. }
  759. errLabel:
  760. if( rc != kOkRtRC )
  761. _cmRtSysFinalize(p);
  762. return rc;
  763. }
  764. cmRtRC_t cmRtSysEndCfg( cmRtSysH_t h )
  765. {
  766. cmRtRC_t rc;
  767. cmRt_t* p = _cmRtHandleToPtr(h);
  768. unsigned i;
  769. if((rc = _cmRtSysValidate(p)) != kOkRtRC )
  770. goto errLabel;
  771. for(i=0; i<p->ssCnt; ++i)
  772. {
  773. _cmRtCfg_t* cp = p->ssArray + i;
  774. cp->runFl = true;
  775. // start the real-time system thread
  776. if( cmThreadPause( cp->threadH, 0 ) != kOkThRC )
  777. {
  778. rc = _cmRtError(p,kThreadErrRtRC,"Thread start failed.");
  779. goto errLabel;
  780. }
  781. // start the input device
  782. if((rc = cmApDeviceStart( cp->ss.args.inDevIdx )) != kOkRtRC )
  783. return _cmRtError(p,kAudioDevStartFailRtRC,"The audio input device start failed.");
  784. // start the output device
  785. if( cmApDeviceStart( cp->ss.args.outDevIdx ) != kOkRtRC )
  786. return _cmRtError(p,kAudioDevStartFailRtRC,"The audio ouput device start failed.");
  787. }
  788. p->initFl = true;
  789. errLabel:
  790. if( rc != kOkRtRC )
  791. _cmRtSysFinalize(p);
  792. return rc;
  793. }
  794. cmRtRC_t cmRtSysFinalize(cmRtSysH_t h )
  795. {
  796. cmRtRC_t rc = kOkRtRC;
  797. if( cmRtSysHandleIsValid(h) == false )
  798. return rc;
  799. cmRt_t* p = _cmRtHandleToPtr(h);
  800. rc = _cmRtSysFinalize(p);
  801. h.h = NULL;
  802. return rc;
  803. }
  804. bool cmRtSysIsInitialized( cmRtSysH_t h )
  805. {
  806. cmRt_t* p = _cmRtHandleToPtr(h);
  807. return p->initFl;
  808. }
  809. cmRtRC_t _cmRtSysVerifyInit( cmRt_t* p, bool errFl )
  810. {
  811. if( p->initFl == false )
  812. {
  813. // if the last msg generated was also a not init msg then don't
  814. // generate another message - just return the error
  815. if( errFl )
  816. if( cmErrLastRC(&p->err) != kNotInitRtRC )
  817. cmErrMsg(&p->err,kNotInitRtRC,"The real-time system is not initialized.");
  818. return kNotInitRtRC;
  819. }
  820. return kOkRtRC;
  821. }
  822. bool cmRtSysIsEnabled( cmRtSysH_t h )
  823. {
  824. if( cmRtSysIsInitialized(h) == false )
  825. return false;
  826. cmRt_t* p = _cmRtHandleToPtr(h);
  827. unsigned i;
  828. for(i=0; i<p->ssCnt; ++i)
  829. if( p->ssArray[i].cbEnableFl )
  830. return true;
  831. return false;
  832. }
  833. cmRtRC_t cmRtSysEnable( cmRtSysH_t h, bool enableFl )
  834. {
  835. cmRt_t* p = _cmRtHandleToPtr(h);
  836. return _cmRtSysEnable(p,enableFl);
  837. }
  838. cmRtRC_t cmRtSysDeliverSegMsg( cmRtSysH_t h, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt, unsigned srcNetNodeId )
  839. {
  840. cmRt_t* p = _cmRtHandleToPtr(h);
  841. cmRtRC_t rc;
  842. // the system must be initialized to use this function
  843. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  844. return rc;
  845. if( msgSegCnt == 0 )
  846. return kOkRtRC;
  847. // BUG BUG BUG - there is no reason that both the rtSubIdx and the selId must
  848. // be in the first segment but it would be nice.
  849. assert( msgByteCntArray[0] >= 2*sizeof(unsigned) || (msgSegCnt>1 && msgByteCntArray[0]==sizeof(unsigned) && msgByteCntArray[1]>=sizeof(unsigned)) );
  850. // The audio sub-system index is always the first field of the msg
  851. // and the msg selector id is always the second field
  852. unsigned* array = (unsigned*)msgDataPtrArray[0];
  853. unsigned rtSubIdx = array[0];
  854. unsigned selId = array[1];
  855. if( selId == kUiMstrSelRtId )
  856. return _cmRtHandleNonSubSysMsg( p, msgDataPtrArray, msgByteCntArray, msgSegCnt );
  857. /*
  858. if( selId == kNetSyncSelRtId )
  859. {
  860. assert( msgSegCnt==1);
  861. assert( rtSubIdx < p->ssCnt );
  862. p->ssArray[rtSubIdx].ctx.srcNetNodeId = srcNetNodeId;
  863. p->ssArray[rtSubIdx].ss.cbFunc(&p->ssArray[rtSubIdx].ctx,msgByteCntArray[0],msgDataPtrArray[0]);
  864. return kOkRtRC;
  865. }
  866. */
  867. return _cmRtEnqueueMsg(p,p->ssArray[rtSubIdx].htdQueueH,msgDataPtrArray,msgByteCntArray,msgSegCnt,"Host-to-DSP");
  868. }
  869. cmRtRC_t cmRtSysDeliverMsg( cmRtSysH_t h, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId )
  870. {
  871. const void* msgDataPtrArray[] = { msgPtr };
  872. unsigned msgByteCntArray[] = { msgByteCnt };
  873. return cmRtSysDeliverSegMsg(h,msgDataPtrArray,msgByteCntArray,1,srcNetNodeId);
  874. }
  875. cmRtRC_t cmRtSysDeliverIdMsg( cmRtSysH_t h, unsigned rtSubIdx, unsigned id, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId )
  876. {
  877. cmRtRC_t rc;
  878. cmRt_t* p = _cmRtHandleToPtr(h);
  879. // the system must be initialized to use this function
  880. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  881. return rc;
  882. const void* msgDataPtrArray[] = { &rtSubIdx, &id, msgPtr };
  883. unsigned msgByteCntArray[] = { sizeof(rtSubIdx), sizeof(id), msgByteCnt };
  884. return cmRtSysDeliverSegMsg(h,msgDataPtrArray,msgByteCntArray,3,srcNetNodeId);
  885. }
  886. unsigned cmRtSysIsMsgWaiting( cmRtSysH_t h )
  887. {
  888. cmRtRC_t rc;
  889. cmRt_t* p = _cmRtHandleToPtr(h);
  890. // the system must be initialized to use this function
  891. if((rc = _cmRtSysVerifyInit(p,false)) != kOkRtRC )
  892. return 0;
  893. unsigned n = 0;
  894. unsigned retByteCnt;
  895. for(n=0; n < p->ssCnt; ++n )
  896. {
  897. if( (retByteCnt = cmTsMp1cDequeueMsgByteCount(p->dthQueH)) > 0 )
  898. return retByteCnt;
  899. p->waitRtSubIdx = (p->waitRtSubIdx + 1) % p->ssCnt;
  900. }
  901. return 0;
  902. }
  903. cmRtRC_t cmRtSysReceiveMsg( cmRtSysH_t h, void* msgDataPtr, unsigned msgByteCnt )
  904. {
  905. cmRtRC_t rc;
  906. cmRt_t* p = _cmRtHandleToPtr(h);
  907. // the system must be initialized to use this function
  908. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  909. return rc;
  910. //switch( cmTsMp1cDequeueMsg(p->ssArray[p->waitRtSubIdx].dthQueueH,msgDataPtr,msgByteCnt) )
  911. switch( cmTsMp1cDequeueMsg(p->dthQueH,msgDataPtr,msgByteCnt) )
  912. {
  913. case kOkThRC:
  914. p->waitRtSubIdx = (p->waitRtSubIdx + 1) % p->ssCnt;
  915. return kOkRtRC;
  916. case kBufTooSmallThRC:
  917. return kBufTooSmallRtRC;
  918. case kBufEmptyThRC:
  919. return kNoMsgWaitingRtRC;
  920. }
  921. return _cmRtError(p,kTsQueueErrRtRC,"A deque operation failed on the DSP-to-Host message queue.");
  922. }
  923. void cmRtSysStatus( cmRtSysH_t h, unsigned rtSubIdx, cmRtSysStatus_t* statusPtr )
  924. {
  925. cmRt_t* p = _cmRtHandleToPtr(h);
  926. // the system must be initialized to use this function
  927. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  928. return;
  929. if( rtSubIdx < p->ssCnt )
  930. *statusPtr = p->ssArray[rtSubIdx].status;
  931. }
  932. void cmRtSysStatusNotifyEnable( cmRtSysH_t h, unsigned rtSubIdx, bool enableFl )
  933. {
  934. cmRt_t* p = _cmRtHandleToPtr(h);
  935. // the system must be initialized to use this function
  936. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  937. return;
  938. unsigned i = rtSubIdx == cmInvalidIdx ? 0 : rtSubIdx;
  939. unsigned n = rtSubIdx == cmInvalidIdx ? p->ssCnt : rtSubIdx+1;
  940. for(; i<n; ++i)
  941. p->ssArray[i].statusFl = enableFl;
  942. }
  943. bool cmRtSysHandleIsValid( cmRtSysH_t h )
  944. { return h.h != NULL; }
  945. cmRtSysCtx_t* cmRtSysContext( cmRtSysH_t h, unsigned rtSubIdx )
  946. {
  947. cmRt_t* p = _cmRtHandleToPtr(h);
  948. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  949. return NULL;
  950. return &p->ssArray[rtSubIdx].ctx;
  951. }
  952. unsigned cmRtSysSubSystemCount( cmRtSysH_t h )
  953. {
  954. cmRt_t* p = _cmRtHandleToPtr(h);
  955. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  956. return 0;
  957. return p->ssCnt;
  958. }
  959. //===========================================================================================================================
  960. //
  961. // cmRtTest()
  962. //
  963. /// [cmRtSysTest]
  964. typedef struct
  965. {
  966. double hz; // current synth frq
  967. long phs; // current synth phase
  968. double srate; // audio sample rate
  969. unsigned cbCnt; // DSP cycle count
  970. bool synthFl; // true=synth false=pass through
  971. } _cmRtTestCbRecd;
  972. typedef struct
  973. {
  974. unsigned rtSubIdx; // rtSubIdx must always be the first field in the msg
  975. unsigned id; // 0 = set DSP Hz, 1 = report cbCount to host
  976. double hz;
  977. unsigned uint;
  978. } _cmRtTestMsg;
  979. long _cmRtSynthSine( _cmRtTestCbRecd* r, cmApSample_t* p, unsigned chCnt, unsigned frmCnt )
  980. {
  981. long ph = 0;
  982. unsigned i;
  983. for(i=0; i<chCnt; ++i)
  984. {
  985. unsigned j;
  986. cmApSample_t* op = p + i;
  987. ph = r->phs;
  988. for(j=0; j<frmCnt; j++, op+=chCnt, ph++)
  989. *op = (cmApSample_t)(0.9 * sin( 2.0 * M_PI * r->hz * ph / r->srate ));
  990. }
  991. return ph;
  992. }
  993. unsigned _cmRtTestChIdx = 0;
  994. cmRC_t _cmRtTestCb( void* cbPtr, unsigned msgByteCnt, const void* msgDataPtr )
  995. {
  996. cmRC_t rc = cmOkRC;
  997. cmRtSysCtx_t* ctx = (cmRtSysCtx_t*)cbPtr;
  998. cmRtSysSubSys_t* ss = ctx->ss;
  999. _cmRtTestCbRecd* r = (_cmRtTestCbRecd*)ss->cbDataPtr;
  1000. // update the calback counter
  1001. ++r->cbCnt;
  1002. // if this is an audio update request
  1003. if( msgByteCnt == 0 )
  1004. {
  1005. unsigned i;
  1006. if( r->synthFl )
  1007. {
  1008. long phs = 0;
  1009. if(0)
  1010. {
  1011. for(i=0; i<ctx->oChCnt; ++i)
  1012. if( ctx->oChArray[i] != NULL )
  1013. phs = _cmRtSynthSine(r, ctx->oChArray[i], 1, ss->args.dspFramesPerCycle );
  1014. }
  1015. else
  1016. {
  1017. if( _cmRtTestChIdx < ctx->oChCnt )
  1018. phs = _cmRtSynthSine(r, ctx->oChArray[_cmRtTestChIdx], 1, ss->args.dspFramesPerCycle );
  1019. }
  1020. r->phs = phs;
  1021. }
  1022. else
  1023. {
  1024. // BUG BUG BUG - this assumes that the input and output channels are the same.
  1025. unsigned chCnt = cmMin(ctx->oChCnt,ctx->iChCnt);
  1026. for(i=0; i<chCnt; ++i)
  1027. memcpy(ctx->oChArray[i],ctx->iChArray[i],sizeof(cmSample_t)*ss->args.dspFramesPerCycle);
  1028. }
  1029. }
  1030. else // ... otherwise it is a msg for the DSP process from the host
  1031. {
  1032. _cmRtTestMsg* msg = (_cmRtTestMsg*)msgDataPtr;
  1033. msg->rtSubIdx = ctx->rtSubIdx;
  1034. switch(msg->id)
  1035. {
  1036. case 0:
  1037. r->hz = msg->hz;
  1038. break;
  1039. case 1:
  1040. msg->uint = r->cbCnt;
  1041. msgByteCnt = sizeof(_cmRtTestMsg);
  1042. rc = ctx->dspToHostFunc(ctx,(const void **)&msg,&msgByteCnt,1);
  1043. break;
  1044. }
  1045. }
  1046. return rc;
  1047. }
  1048. // print the usage message for cmAudioPortTest.c
  1049. void _cmRtPrintUsage( cmRpt_t* rpt )
  1050. {
  1051. char msg[] =
  1052. "cmRtSysTest() command switches:\n"
  1053. "-r <srate> -c <chcnt> -b <bufcnt> -f <frmcnt> -i <idevidx> -o <odevidx> -m <msgqsize> -d <dspsize> -t -p -h \n"
  1054. "\n"
  1055. "-r <srate> = sample rate (48000)\n"
  1056. "-c <chcnt> = audio channels (2)\n"
  1057. "-b <bufcnt> = count of buffers (3)\n"
  1058. "-f <frmcnt> = count of samples per buffer (512)\n"
  1059. "-i <idevidx> = input device index (0)\n"
  1060. "-o <odevidx> = output device index (2)\n"
  1061. "-m <msgqsize> = message queue byte count (1024)\n"
  1062. "-d <dspsize> = samples per DSP frame (64)\n"
  1063. "-s = true: sync to input port false: sync to output port\n"
  1064. "-t = copy input to output otherwise synthesize a 1000 Hz sine (false)\n"
  1065. "-p = report but don't start audio devices\n"
  1066. "-h = print this usage message\n";
  1067. cmRptPrintf(rpt,"%s",msg);
  1068. }
  1069. // Get a command line option.
  1070. int _cmRtGetOpt( int argc, const char* argv[], const char* label, int defaultVal, bool boolFl )
  1071. {
  1072. int i = 0;
  1073. for(; i<argc; ++i)
  1074. if( strcmp(label,argv[i]) == 0 )
  1075. {
  1076. if(boolFl)
  1077. return 1;
  1078. if( i == (argc-1) )
  1079. return defaultVal;
  1080. return atoi(argv[i+1]);
  1081. }
  1082. return defaultVal;
  1083. }
  1084. bool _cmRtGetBoolOpt( int argc, const char* argv[], const char* label, bool defaultVal )
  1085. { return _cmRtGetOpt(argc,argv,label,defaultVal?1:0,true)!=0; }
  1086. int _cmRtGetIntOpt( int argc, const char* argv[], const char* label, int defaultVal )
  1087. { return _cmRtGetOpt(argc,argv,label,defaultVal,false); }
  1088. void cmRtSysTest( cmCtx_t* ctx, int argc, const char* argv[] )
  1089. {
  1090. cmRtSysSubSys_t ss;
  1091. cmRtSysH_t h = cmRtSysNullHandle;
  1092. cmRtSysStatus_t status;
  1093. _cmRtTestCbRecd cbRecd = {1000.0,0,48000.0,0};
  1094. cmRpt_t* rpt = &ctx->rpt;
  1095. unsigned meterMs = 50;
  1096. unsigned ssCnt = 1;
  1097. unsigned rtSubIdx = 0;
  1098. if(_cmRtGetBoolOpt(argc,argv,"-h",false))
  1099. _cmRtPrintUsage(rpt);
  1100. cbRecd.srate = _cmRtGetIntOpt(argc,argv,"-r",48000);
  1101. cbRecd.synthFl = _cmRtGetBoolOpt(argc,argv,"-t",false)==false;
  1102. ss.args.rpt = rpt;
  1103. ss.args.inDevIdx = _cmRtGetIntOpt( argc,argv,"-i",0);
  1104. ss.args.outDevIdx = _cmRtGetIntOpt( argc,argv,"-o",2);
  1105. ss.args.syncInputFl = _cmRtGetBoolOpt(argc,argv,"-s",true);
  1106. ss.args.msgQueueByteCnt = _cmRtGetIntOpt( argc,argv,"-m",8192);
  1107. ss.args.devFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-f",512);
  1108. ss.args.dspFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-d",64);;
  1109. ss.args.audioBufCnt = _cmRtGetIntOpt( argc,argv,"-b",3);
  1110. ss.args.srate = cbRecd.srate;
  1111. ss.cbFunc = _cmRtTestCb; // set the DSP entry function
  1112. ss.cbDataPtr = &cbRecd; // set the DSP function argument record
  1113. 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,
  1114. ss.args.msgQueueByteCnt,ss.args.devFramesPerCycle,ss.args.dspFramesPerCycle,ss.args.audioBufCnt,ss.args.srate);
  1115. if( cmApNrtAllocate(rpt) != kOkApRC )
  1116. goto errLabel;
  1117. if( cmApFileAllocate(rpt) != kOkApRC )
  1118. goto errLabel;
  1119. // initialize the audio device system
  1120. if( cmApInitialize(rpt) != kOkApRC )
  1121. goto errLabel;
  1122. cmApReport(rpt);
  1123. // initialize the audio buffer
  1124. if( cmApBufInitialize( cmApDeviceCount(), meterMs ) != kOkApRC )
  1125. goto errLabel;
  1126. // initialize the real-time system
  1127. if( cmRtSysAllocate(&h,ctx) != kOkRtRC )
  1128. goto errLabel;
  1129. if( cmRtSysBeginCfg(h,NULL,NULL,meterMs,ssCnt) != kOkRtRC )
  1130. goto errLabel;
  1131. if( cmRtSysCfg(h,&ss,rtSubIdx) != kOkRtRC )
  1132. goto errLabel;
  1133. if( cmRtSysEndCfg(h) != kOkRtRC )
  1134. goto errLabel;
  1135. // start the real-time system
  1136. cmRtSysEnable(h,true);
  1137. char c = 0;
  1138. printf("q=quit a-g=note n=ch r=rqst s=status\n");
  1139. // simulate a host event loop
  1140. while(c != 'q')
  1141. {
  1142. _cmRtTestMsg msg = {0,0,0,0};
  1143. bool fl = true;
  1144. // wait here for a key press
  1145. c =(char)fgetc(stdin);
  1146. fflush(stdin);
  1147. switch(c)
  1148. {
  1149. case 'c': msg.hz = cmMidiToHz(60); break;
  1150. case 'd': msg.hz = cmMidiToHz(62); break;
  1151. case 'e': msg.hz = cmMidiToHz(64); break;
  1152. case 'f': msg.hz = cmMidiToHz(65); break;
  1153. case 'g': msg.hz = cmMidiToHz(67); break;
  1154. case 'a': msg.hz = cmMidiToHz(69); break;
  1155. case 'b': msg.hz = cmMidiToHz(71); break;
  1156. case 'r': msg.id = 1; break; // request DSP process to send a callback count
  1157. case 'n': ++_cmRtTestChIdx; printf("ch:%i\n",_cmRtTestChIdx); break;
  1158. case 's':
  1159. // report the real-time system status
  1160. cmRtSysStatus(h,0,&status);
  1161. 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);
  1162. //printf("%f \n",status.oMeterArray[0]);
  1163. fl = false;
  1164. break;
  1165. default:
  1166. fl=false;
  1167. }
  1168. if( fl )
  1169. {
  1170. // transmit a command to the DSP process
  1171. cmRtSysDeliverMsg(h,&msg, sizeof(msg), cmInvalidId);
  1172. }
  1173. // check if messages are waiting to be delivered from the DSP process
  1174. unsigned msgByteCnt;
  1175. if((msgByteCnt = cmRtSysIsMsgWaiting(h)) > 0 )
  1176. {
  1177. char buf[ msgByteCnt ];
  1178. // rcv a msg from the DSP process
  1179. if( cmRtSysReceiveMsg(h,buf,msgByteCnt) == kOkRtRC )
  1180. {
  1181. _cmRtTestMsg* msg = (_cmRtTestMsg*)buf;
  1182. switch(msg->id)
  1183. {
  1184. case 1:
  1185. printf("RCV: Callback count:%i\n",msg->uint);
  1186. break;
  1187. }
  1188. }
  1189. }
  1190. // report the audio buffer status
  1191. //cmApBufReport(ss.args.rpt);
  1192. }
  1193. // stop the real-time system
  1194. cmRtSysEnable(h,false);
  1195. goto exitLabel;
  1196. errLabel:
  1197. printf("REAL-TIME SYSTEM TEST ERROR\n");
  1198. exitLabel:
  1199. cmRtSysFree(&h);
  1200. cmApFinalize();
  1201. cmApFileFree();
  1202. cmApNrtFree();
  1203. cmApBufFinalize();
  1204. }
  1205. /// [cmRtSysTest]