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

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