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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590
  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( cmRtNetDoSync(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. if( cmRtNetInitialize( cp->netH, ss->bcastAddr, ss->localNodeLabel, ss->localIpAddr, ss->localIpPort) != kOkNetRC )
  740. {
  741. rc = _cmRtError(p,kNetErrRtRC,"Network node initialization failed on label:%s addr:%s port:%i.",cmStringNullGuard(ss->localNodeLabel),cmStringNullGuard(ss->localIpAddr),ss->localIpPort);
  742. goto errLabel;
  743. }
  744. // register the local endpoints
  745. for(j=0; j<ss->endptCnt; ++j)
  746. {
  747. cmRtSysNetEndpt_t* ep = ss->endptArray + j;
  748. if( cmRtNetRegisterEndPoint( cp->netH, ep->label, ep->id ) != kOkNetRC )
  749. {
  750. rc = _cmRtError(p,kNetErrRtRC,"Network end point allocation failed on label:%s id:%i.",cmStringNullGuard(ep->label),ep->id);
  751. goto errLabel;
  752. }
  753. }
  754. errLabel:
  755. if( rc != kOkRtRC )
  756. _cmRtSysFinalize(p);
  757. return rc;
  758. }
  759. cmRtRC_t cmRtSysEndCfg( cmRtSysH_t h )
  760. {
  761. cmRtRC_t rc;
  762. cmRt_t* p = _cmRtHandleToPtr(h);
  763. unsigned i;
  764. if((rc = _cmRtSysValidate(p)) != kOkRtRC )
  765. goto errLabel;
  766. for(i=0; i<p->ssCnt; ++i)
  767. {
  768. _cmRtCfg_t* cp = p->ssArray + i;
  769. cp->runFl = true;
  770. // start the real-time system thread
  771. if( cmThreadPause( cp->threadH, 0 ) != kOkThRC )
  772. {
  773. rc = _cmRtError(p,kThreadErrRtRC,"Thread start failed.");
  774. goto errLabel;
  775. }
  776. // start the input device
  777. if((rc = cmApDeviceStart( cp->ss.args.inDevIdx )) != kOkRtRC )
  778. return _cmRtError(p,kAudioDevStartFailRtRC,"The audio input device start failed.");
  779. // start the output device
  780. if( cmApDeviceStart( cp->ss.args.outDevIdx ) != kOkRtRC )
  781. return _cmRtError(p,kAudioDevStartFailRtRC,"The audio ouput device start failed.");
  782. }
  783. p->initFl = true;
  784. errLabel:
  785. if( rc != kOkRtRC )
  786. _cmRtSysFinalize(p);
  787. return rc;
  788. }
  789. cmRtRC_t cmRtSysFinalize(cmRtSysH_t h )
  790. {
  791. cmRtRC_t rc = kOkRtRC;
  792. if( cmRtSysHandleIsValid(h) == false )
  793. return rc;
  794. cmRt_t* p = _cmRtHandleToPtr(h);
  795. rc = _cmRtSysFinalize(p);
  796. h.h = NULL;
  797. return rc;
  798. }
  799. bool cmRtSysIsInitialized( cmRtSysH_t h )
  800. {
  801. cmRt_t* p = _cmRtHandleToPtr(h);
  802. return p->initFl;
  803. }
  804. cmRtRC_t _cmRtSysVerifyInit( cmRt_t* p, bool errFl )
  805. {
  806. if( p->initFl == false )
  807. {
  808. // if the last msg generated was also a not init msg then don't
  809. // generate another message - just return the error
  810. if( errFl )
  811. if( cmErrLastRC(&p->err) != kNotInitRtRC )
  812. cmErrMsg(&p->err,kNotInitRtRC,"The real-time system is not initialized.");
  813. return kNotInitRtRC;
  814. }
  815. return kOkRtRC;
  816. }
  817. bool cmRtSysIsEnabled( cmRtSysH_t h )
  818. {
  819. if( cmRtSysIsInitialized(h) == false )
  820. return false;
  821. cmRt_t* p = _cmRtHandleToPtr(h);
  822. unsigned i;
  823. for(i=0; i<p->ssCnt; ++i)
  824. if( p->ssArray[i].cbEnableFl )
  825. return true;
  826. return false;
  827. }
  828. cmRtRC_t cmRtSysEnable( cmRtSysH_t h, bool enableFl )
  829. {
  830. cmRt_t* p = _cmRtHandleToPtr(h);
  831. return _cmRtSysEnable(p,enableFl);
  832. }
  833. cmRtRC_t cmRtSysDeliverSegMsg( cmRtSysH_t h, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt, unsigned srcNetNodeId )
  834. {
  835. cmRt_t* p = _cmRtHandleToPtr(h);
  836. cmRtRC_t rc;
  837. // the system must be initialized to use this function
  838. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  839. return rc;
  840. if( msgSegCnt == 0 )
  841. return kOkRtRC;
  842. // BUG BUG BUG - there is no reason that both the rtSubIdx and the selId must
  843. // be in the first segment but it would be nice.
  844. assert( msgByteCntArray[0] >= 2*sizeof(unsigned) || (msgSegCnt>1 && msgByteCntArray[0]==sizeof(unsigned) && msgByteCntArray[1]>=sizeof(unsigned)) );
  845. // The audio sub-system index is always the first field of the msg
  846. // and the msg selector id is always the second field
  847. unsigned* array = (unsigned*)msgDataPtrArray[0];
  848. unsigned rtSubIdx = array[0];
  849. unsigned selId = array[1];
  850. if( selId == kUiMstrSelRtId )
  851. return _cmRtHandleNonSubSysMsg( p, msgDataPtrArray, msgByteCntArray, msgSegCnt );
  852. /*
  853. if( selId == kNetSyncSelRtId )
  854. {
  855. assert( msgSegCnt==1);
  856. assert( rtSubIdx < p->ssCnt );
  857. p->ssArray[rtSubIdx].ctx.srcNetNodeId = srcNetNodeId;
  858. p->ssArray[rtSubIdx].ss.cbFunc(&p->ssArray[rtSubIdx].ctx,msgByteCntArray[0],msgDataPtrArray[0]);
  859. return kOkRtRC;
  860. }
  861. */
  862. return _cmRtEnqueueMsg(p,p->ssArray[rtSubIdx].htdQueueH,msgDataPtrArray,msgByteCntArray,msgSegCnt,"Host-to-DSP");
  863. }
  864. cmRtRC_t cmRtSysDeliverMsg( cmRtSysH_t h, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId )
  865. {
  866. const void* msgDataPtrArray[] = { msgPtr };
  867. unsigned msgByteCntArray[] = { msgByteCnt };
  868. return cmRtSysDeliverSegMsg(h,msgDataPtrArray,msgByteCntArray,1,srcNetNodeId);
  869. }
  870. cmRtRC_t cmRtSysDeliverIdMsg( cmRtSysH_t h, unsigned rtSubIdx, unsigned id, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId )
  871. {
  872. cmRtRC_t rc;
  873. cmRt_t* p = _cmRtHandleToPtr(h);
  874. // the system must be initialized to use this function
  875. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  876. return rc;
  877. const void* msgDataPtrArray[] = { &rtSubIdx, &id, msgPtr };
  878. unsigned msgByteCntArray[] = { sizeof(rtSubIdx), sizeof(id), msgByteCnt };
  879. return cmRtSysDeliverSegMsg(h,msgDataPtrArray,msgByteCntArray,3,srcNetNodeId);
  880. }
  881. unsigned cmRtSysIsMsgWaiting( cmRtSysH_t h )
  882. {
  883. cmRtRC_t rc;
  884. cmRt_t* p = _cmRtHandleToPtr(h);
  885. // the system must be initialized to use this function
  886. if((rc = _cmRtSysVerifyInit(p,false)) != kOkRtRC )
  887. return 0;
  888. unsigned n = 0;
  889. unsigned retByteCnt;
  890. for(n=0; n < p->ssCnt; ++n )
  891. {
  892. if( (retByteCnt = cmTsMp1cDequeueMsgByteCount(p->dthQueH)) > 0 )
  893. return retByteCnt;
  894. p->waitRtSubIdx = (p->waitRtSubIdx + 1) % p->ssCnt;
  895. }
  896. return 0;
  897. }
  898. cmRtRC_t cmRtSysReceiveMsg( cmRtSysH_t h, void* msgDataPtr, unsigned msgByteCnt )
  899. {
  900. cmRtRC_t rc;
  901. cmRt_t* p = _cmRtHandleToPtr(h);
  902. // the system must be initialized to use this function
  903. if((rc = _cmRtSysVerifyInit(p,true)) != kOkRtRC )
  904. return rc;
  905. //switch( cmTsMp1cDequeueMsg(p->ssArray[p->waitRtSubIdx].dthQueueH,msgDataPtr,msgByteCnt) )
  906. switch( cmTsMp1cDequeueMsg(p->dthQueH,msgDataPtr,msgByteCnt) )
  907. {
  908. case kOkThRC:
  909. p->waitRtSubIdx = (p->waitRtSubIdx + 1) % p->ssCnt;
  910. return kOkRtRC;
  911. case kBufTooSmallThRC:
  912. return kBufTooSmallRtRC;
  913. case kBufEmptyThRC:
  914. return kNoMsgWaitingRtRC;
  915. }
  916. return _cmRtError(p,kTsQueueErrRtRC,"A deque operation failed on the DSP-to-Host message queue.");
  917. }
  918. void cmRtSysStatus( cmRtSysH_t h, unsigned rtSubIdx, cmRtSysStatus_t* statusPtr )
  919. {
  920. cmRt_t* p = _cmRtHandleToPtr(h);
  921. // the system must be initialized to use this function
  922. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  923. return;
  924. if( rtSubIdx < p->ssCnt )
  925. *statusPtr = p->ssArray[rtSubIdx].status;
  926. }
  927. void cmRtSysStatusNotifyEnable( cmRtSysH_t h, unsigned rtSubIdx, bool enableFl )
  928. {
  929. cmRt_t* p = _cmRtHandleToPtr(h);
  930. // the system must be initialized to use this function
  931. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  932. return;
  933. unsigned i = rtSubIdx == cmInvalidIdx ? 0 : rtSubIdx;
  934. unsigned n = rtSubIdx == cmInvalidIdx ? p->ssCnt : rtSubIdx+1;
  935. for(; i<n; ++i)
  936. p->ssArray[i].statusFl = enableFl;
  937. }
  938. bool cmRtSysHandleIsValid( cmRtSysH_t h )
  939. { return h.h != NULL; }
  940. cmRtSysCtx_t* cmRtSysContext( cmRtSysH_t h, unsigned rtSubIdx )
  941. {
  942. cmRt_t* p = _cmRtHandleToPtr(h);
  943. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  944. return NULL;
  945. return &p->ssArray[rtSubIdx].ctx;
  946. }
  947. unsigned cmRtSysSubSystemCount( cmRtSysH_t h )
  948. {
  949. cmRt_t* p = _cmRtHandleToPtr(h);
  950. if( _cmRtSysVerifyInit(p,true) != kOkRtRC )
  951. return 0;
  952. return p->ssCnt;
  953. }
  954. bool cmRtSysNetIsInitialized( cmRtSysH_t h )
  955. {
  956. cmRt_t* p = _cmRtHandleToPtr(h);
  957. unsigned i = 0;
  958. for(; i<p->ssCnt; ++i)
  959. if( cmRtNetIsInitialized(p->ssArray[i].netH) )
  960. return true;
  961. return false;
  962. }
  963. cmRtRC_t cmRtSysNetDoSync( cmRtSysH_t h )
  964. {
  965. cmRtRC_t rc = kOkRtRC;
  966. cmRt_t* p = _cmRtHandleToPtr(h);
  967. unsigned i = 0;
  968. for(; i<p->ssCnt; ++i)
  969. if( cmRtNetIsInitialized(p->ssArray[i].netH) )
  970. cmRtNetDoSync(p->ssArray[i].netH);
  971. return rc;
  972. }
  973. cmRtRC_t cmRtSysNetReport( cmRtSysH_t h )
  974. {
  975. cmRtRC_t rc = kOkRtRC;
  976. cmRt_t* p = _cmRtHandleToPtr(h);
  977. unsigned i = 0;
  978. for(; i<p->ssCnt; ++i)
  979. {
  980. cmRptPrintf(p->err.rpt,"Sub-system:%i\n",i);
  981. if( cmRtNetIsValid(p->ssArray[i].netH))
  982. cmRtNetDoSync(p->ssArray[i].netH);
  983. }
  984. return rc;
  985. }
  986. //===========================================================================================================================
  987. //
  988. // cmRtTest()
  989. //
  990. /// [cmRtSysTest]
  991. typedef struct
  992. {
  993. double hz; // current synth frq
  994. long phs; // current synth phase
  995. double srate; // audio sample rate
  996. unsigned cbCnt; // DSP cycle count
  997. bool synthFl; // true=synth false=pass through
  998. } _cmRtTestCbRecd;
  999. typedef struct
  1000. {
  1001. unsigned rtSubIdx; // rtSubIdx must always be the first field in the msg
  1002. unsigned id; // 0 = set DSP Hz, 1 = report cbCount to host
  1003. double hz;
  1004. unsigned uint;
  1005. } _cmRtTestMsg;
  1006. long _cmRtSynthSine( _cmRtTestCbRecd* r, cmApSample_t* p, unsigned chCnt, unsigned frmCnt )
  1007. {
  1008. long ph = 0;
  1009. unsigned i;
  1010. for(i=0; i<chCnt; ++i)
  1011. {
  1012. unsigned j;
  1013. cmApSample_t* op = p + i;
  1014. ph = r->phs;
  1015. for(j=0; j<frmCnt; j++, op+=chCnt, ph++)
  1016. *op = (cmApSample_t)(0.9 * sin( 2.0 * M_PI * r->hz * ph / r->srate ));
  1017. }
  1018. return ph;
  1019. }
  1020. unsigned _cmRtTestChIdx = 0;
  1021. cmRC_t _cmRtTestCb( void* cbPtr, unsigned msgByteCnt, const void* msgDataPtr )
  1022. {
  1023. cmRC_t rc = cmOkRC;
  1024. cmRtSysCtx_t* ctx = (cmRtSysCtx_t*)cbPtr;
  1025. cmRtSysSubSys_t* ss = ctx->ss;
  1026. _cmRtTestCbRecd* r = (_cmRtTestCbRecd*)ss->cbDataPtr;
  1027. // update the calback counter
  1028. ++r->cbCnt;
  1029. // if this is an audio update request
  1030. if( msgByteCnt == 0 )
  1031. {
  1032. unsigned i;
  1033. if( r->synthFl )
  1034. {
  1035. long phs = 0;
  1036. if(0)
  1037. {
  1038. for(i=0; i<ctx->oChCnt; ++i)
  1039. if( ctx->oChArray[i] != NULL )
  1040. phs = _cmRtSynthSine(r, ctx->oChArray[i], 1, ss->args.dspFramesPerCycle );
  1041. }
  1042. else
  1043. {
  1044. if( _cmRtTestChIdx < ctx->oChCnt )
  1045. phs = _cmRtSynthSine(r, ctx->oChArray[_cmRtTestChIdx], 1, ss->args.dspFramesPerCycle );
  1046. }
  1047. r->phs = phs;
  1048. }
  1049. else
  1050. {
  1051. // BUG BUG BUG - this assumes that the input and output channels are the same.
  1052. unsigned chCnt = cmMin(ctx->oChCnt,ctx->iChCnt);
  1053. for(i=0; i<chCnt; ++i)
  1054. memcpy(ctx->oChArray[i],ctx->iChArray[i],sizeof(cmSample_t)*ss->args.dspFramesPerCycle);
  1055. }
  1056. }
  1057. else // ... otherwise it is a msg for the DSP process from the host
  1058. {
  1059. _cmRtTestMsg* msg = (_cmRtTestMsg*)msgDataPtr;
  1060. msg->rtSubIdx = ctx->rtSubIdx;
  1061. switch(msg->id)
  1062. {
  1063. case 0:
  1064. r->hz = msg->hz;
  1065. break;
  1066. case 1:
  1067. msg->uint = r->cbCnt;
  1068. msgByteCnt = sizeof(_cmRtTestMsg);
  1069. rc = ctx->dspToHostFunc(ctx,(const void **)&msg,&msgByteCnt,1);
  1070. break;
  1071. }
  1072. }
  1073. return rc;
  1074. }
  1075. // print the usage message for cmAudioPortTest.c
  1076. void _cmRtPrintUsage( cmRpt_t* rpt )
  1077. {
  1078. char msg[] =
  1079. "cmRtSysTest() command switches:\n"
  1080. "-r <srate> -c <chcnt> -b <bufcnt> -f <frmcnt> -i <idevidx> -o <odevidx> -m <msgqsize> -d <dspsize> -t -p -h \n"
  1081. "\n"
  1082. "-r <srate> = sample rate (48000)\n"
  1083. "-c <chcnt> = audio channels (2)\n"
  1084. "-b <bufcnt> = count of buffers (3)\n"
  1085. "-f <frmcnt> = count of samples per buffer (512)\n"
  1086. "-i <idevidx> = input device index (0)\n"
  1087. "-o <odevidx> = output device index (2)\n"
  1088. "-m <msgqsize> = message queue byte count (1024)\n"
  1089. "-d <dspsize> = samples per DSP frame (64)\n"
  1090. "-s = true: sync to input port false: sync to output port\n"
  1091. "-t = copy input to output otherwise synthesize a 1000 Hz sine (false)\n"
  1092. "-p = report but don't start audio devices\n"
  1093. "-h = print this usage message\n";
  1094. cmRptPrintf(rpt,"%s",msg);
  1095. }
  1096. // Get a command line option.
  1097. int _cmRtGetOpt( int argc, const char* argv[], const char* label, int defaultVal, bool boolFl )
  1098. {
  1099. int i = 0;
  1100. for(; i<argc; ++i)
  1101. if( strcmp(label,argv[i]) == 0 )
  1102. {
  1103. if(boolFl)
  1104. return 1;
  1105. if( i == (argc-1) )
  1106. return defaultVal;
  1107. return atoi(argv[i+1]);
  1108. }
  1109. return defaultVal;
  1110. }
  1111. bool _cmRtGetBoolOpt( int argc, const char* argv[], const char* label, bool defaultVal )
  1112. { return _cmRtGetOpt(argc,argv,label,defaultVal?1:0,true)!=0; }
  1113. int _cmRtGetIntOpt( int argc, const char* argv[], const char* label, int defaultVal )
  1114. { return _cmRtGetOpt(argc,argv,label,defaultVal,false); }
  1115. void cmRtSysTest( cmCtx_t* ctx, int argc, const char* argv[] )
  1116. {
  1117. cmRtSysSubSys_t ss;
  1118. cmRtSysH_t h = cmRtSysNullHandle;
  1119. cmRtSysStatus_t status;
  1120. _cmRtTestCbRecd cbRecd = {1000.0,0,48000.0,0};
  1121. cmRpt_t* rpt = &ctx->rpt;
  1122. unsigned meterMs = 50;
  1123. unsigned ssCnt = 1;
  1124. unsigned rtSubIdx = 0;
  1125. if(_cmRtGetBoolOpt(argc,argv,"-h",false))
  1126. _cmRtPrintUsage(rpt);
  1127. cbRecd.srate = _cmRtGetIntOpt(argc,argv,"-r",48000);
  1128. cbRecd.synthFl = _cmRtGetBoolOpt(argc,argv,"-t",false)==false;
  1129. ss.args.rpt = rpt;
  1130. ss.args.inDevIdx = _cmRtGetIntOpt( argc,argv,"-i",0);
  1131. ss.args.outDevIdx = _cmRtGetIntOpt( argc,argv,"-o",2);
  1132. ss.args.syncInputFl = _cmRtGetBoolOpt(argc,argv,"-s",true);
  1133. ss.args.msgQueueByteCnt = _cmRtGetIntOpt( argc,argv,"-m",8192);
  1134. ss.args.devFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-f",512);
  1135. ss.args.dspFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-d",64);;
  1136. ss.args.audioBufCnt = _cmRtGetIntOpt( argc,argv,"-b",3);
  1137. ss.args.srate = cbRecd.srate;
  1138. ss.cbFunc = _cmRtTestCb; // set the DSP entry function
  1139. ss.cbDataPtr = &cbRecd; // set the DSP function argument record
  1140. 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,
  1141. ss.args.msgQueueByteCnt,ss.args.devFramesPerCycle,ss.args.dspFramesPerCycle,ss.args.audioBufCnt,ss.args.srate);
  1142. if( cmApNrtAllocate(rpt) != kOkApRC )
  1143. goto errLabel;
  1144. if( cmApFileAllocate(rpt) != kOkApRC )
  1145. goto errLabel;
  1146. // initialize the audio device system
  1147. if( cmApInitialize(rpt) != kOkApRC )
  1148. goto errLabel;
  1149. cmApReport(rpt);
  1150. // initialize the audio buffer
  1151. if( cmApBufInitialize( cmApDeviceCount(), meterMs ) != kOkApRC )
  1152. goto errLabel;
  1153. // initialize the real-time system
  1154. if( cmRtSysAllocate(&h,ctx) != kOkRtRC )
  1155. goto errLabel;
  1156. if( cmRtSysBeginCfg(h,NULL,NULL,meterMs,ssCnt) != kOkRtRC )
  1157. goto errLabel;
  1158. if( cmRtSysCfg(h,&ss,rtSubIdx) != kOkRtRC )
  1159. goto errLabel;
  1160. if( cmRtSysEndCfg(h) != kOkRtRC )
  1161. goto errLabel;
  1162. // start the real-time system
  1163. cmRtSysEnable(h,true);
  1164. char c = 0;
  1165. printf("q=quit a-g=note n=ch r=rqst s=status\n");
  1166. // simulate a host event loop
  1167. while(c != 'q')
  1168. {
  1169. _cmRtTestMsg msg = {0,0,0,0};
  1170. bool fl = true;
  1171. // wait here for a key press
  1172. c =(char)fgetc(stdin);
  1173. fflush(stdin);
  1174. switch(c)
  1175. {
  1176. case 'c': msg.hz = cmMidiToHz(60); break;
  1177. case 'd': msg.hz = cmMidiToHz(62); break;
  1178. case 'e': msg.hz = cmMidiToHz(64); break;
  1179. case 'f': msg.hz = cmMidiToHz(65); break;
  1180. case 'g': msg.hz = cmMidiToHz(67); break;
  1181. case 'a': msg.hz = cmMidiToHz(69); break;
  1182. case 'b': msg.hz = cmMidiToHz(71); break;
  1183. case 'r': msg.id = 1; break; // request DSP process to send a callback count
  1184. case 'n': ++_cmRtTestChIdx; printf("ch:%i\n",_cmRtTestChIdx); break;
  1185. case 's':
  1186. // report the real-time system status
  1187. cmRtSysStatus(h,0,&status);
  1188. 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);
  1189. //printf("%f \n",status.oMeterArray[0]);
  1190. fl = false;
  1191. break;
  1192. default:
  1193. fl=false;
  1194. }
  1195. if( fl )
  1196. {
  1197. // transmit a command to the DSP process
  1198. cmRtSysDeliverMsg(h,&msg, sizeof(msg), cmInvalidId);
  1199. }
  1200. // check if messages are waiting to be delivered from the DSP process
  1201. unsigned msgByteCnt;
  1202. if((msgByteCnt = cmRtSysIsMsgWaiting(h)) > 0 )
  1203. {
  1204. char buf[ msgByteCnt ];
  1205. // rcv a msg from the DSP process
  1206. if( cmRtSysReceiveMsg(h,buf,msgByteCnt) == kOkRtRC )
  1207. {
  1208. _cmRtTestMsg* msg = (_cmRtTestMsg*)buf;
  1209. switch(msg->id)
  1210. {
  1211. case 1:
  1212. printf("RCV: Callback count:%i\n",msg->uint);
  1213. break;
  1214. }
  1215. }
  1216. }
  1217. // report the audio buffer status
  1218. //cmApBufReport(ss.args.rpt);
  1219. }
  1220. // stop the real-time system
  1221. cmRtSysEnable(h,false);
  1222. goto exitLabel;
  1223. errLabel:
  1224. printf("REAL-TIME SYSTEM TEST ERROR\n");
  1225. exitLabel:
  1226. cmRtSysFree(&h);
  1227. cmApFinalize();
  1228. cmApFileFree();
  1229. cmApNrtFree();
  1230. cmApBufFinalize();
  1231. }
  1232. /// [cmRtSysTest]