libcm is a C development framework with an emphasis on audio signal processing applications.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

cmRtSys.c 46KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  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. //===========================================================================================================================
  955. //
  956. // cmRtTest()
  957. //
  958. /// [cmRtSysTest]
  959. typedef struct
  960. {
  961. double hz; // current synth frq
  962. long phs; // current synth phase
  963. double srate; // audio sample rate
  964. unsigned cbCnt; // DSP cycle count
  965. bool synthFl; // true=synth false=pass through
  966. } _cmRtTestCbRecd;
  967. typedef struct
  968. {
  969. unsigned rtSubIdx; // rtSubIdx must always be the first field in the msg
  970. unsigned id; // 0 = set DSP Hz, 1 = report cbCount to host
  971. double hz;
  972. unsigned uint;
  973. } _cmRtTestMsg;
  974. long _cmRtSynthSine( _cmRtTestCbRecd* r, cmApSample_t* p, unsigned chCnt, unsigned frmCnt )
  975. {
  976. long ph = 0;
  977. unsigned i;
  978. for(i=0; i<chCnt; ++i)
  979. {
  980. unsigned j;
  981. cmApSample_t* op = p + i;
  982. ph = r->phs;
  983. for(j=0; j<frmCnt; j++, op+=chCnt, ph++)
  984. *op = (cmApSample_t)(0.9 * sin( 2.0 * M_PI * r->hz * ph / r->srate ));
  985. }
  986. return ph;
  987. }
  988. unsigned _cmRtTestChIdx = 0;
  989. cmRC_t _cmRtTestCb( void* cbPtr, unsigned msgByteCnt, const void* msgDataPtr )
  990. {
  991. cmRC_t rc = cmOkRC;
  992. cmRtSysCtx_t* ctx = (cmRtSysCtx_t*)cbPtr;
  993. cmRtSysSubSys_t* ss = ctx->ss;
  994. _cmRtTestCbRecd* r = (_cmRtTestCbRecd*)ss->cbDataPtr;
  995. // update the calback counter
  996. ++r->cbCnt;
  997. // if this is an audio update request
  998. if( msgByteCnt == 0 )
  999. {
  1000. unsigned i;
  1001. if( r->synthFl )
  1002. {
  1003. long phs = 0;
  1004. if(0)
  1005. {
  1006. for(i=0; i<ctx->oChCnt; ++i)
  1007. if( ctx->oChArray[i] != NULL )
  1008. phs = _cmRtSynthSine(r, ctx->oChArray[i], 1, ss->args.dspFramesPerCycle );
  1009. }
  1010. else
  1011. {
  1012. if( _cmRtTestChIdx < ctx->oChCnt )
  1013. phs = _cmRtSynthSine(r, ctx->oChArray[_cmRtTestChIdx], 1, ss->args.dspFramesPerCycle );
  1014. }
  1015. r->phs = phs;
  1016. }
  1017. else
  1018. {
  1019. // BUG BUG BUG - this assumes that the input and output channels are the same.
  1020. unsigned chCnt = cmMin(ctx->oChCnt,ctx->iChCnt);
  1021. for(i=0; i<chCnt; ++i)
  1022. memcpy(ctx->oChArray[i],ctx->iChArray[i],sizeof(cmSample_t)*ss->args.dspFramesPerCycle);
  1023. }
  1024. }
  1025. else // ... otherwise it is a msg for the DSP process from the host
  1026. {
  1027. _cmRtTestMsg* msg = (_cmRtTestMsg*)msgDataPtr;
  1028. msg->rtSubIdx = ctx->rtSubIdx;
  1029. switch(msg->id)
  1030. {
  1031. case 0:
  1032. r->hz = msg->hz;
  1033. break;
  1034. case 1:
  1035. msg->uint = r->cbCnt;
  1036. msgByteCnt = sizeof(_cmRtTestMsg);
  1037. rc = ctx->dspToHostFunc(ctx,(const void **)&msg,&msgByteCnt,1);
  1038. break;
  1039. }
  1040. }
  1041. return rc;
  1042. }
  1043. // print the usage message for cmAudioPortTest.c
  1044. void _cmRtPrintUsage( cmRpt_t* rpt )
  1045. {
  1046. char msg[] =
  1047. "cmRtSysTest() command switches:\n"
  1048. "-r <srate> -c <chcnt> -b <bufcnt> -f <frmcnt> -i <idevidx> -o <odevidx> -m <msgqsize> -d <dspsize> -t -p -h \n"
  1049. "\n"
  1050. "-r <srate> = sample rate (48000)\n"
  1051. "-c <chcnt> = audio channels (2)\n"
  1052. "-b <bufcnt> = count of buffers (3)\n"
  1053. "-f <frmcnt> = count of samples per buffer (512)\n"
  1054. "-i <idevidx> = input device index (0)\n"
  1055. "-o <odevidx> = output device index (2)\n"
  1056. "-m <msgqsize> = message queue byte count (1024)\n"
  1057. "-d <dspsize> = samples per DSP frame (64)\n"
  1058. "-s = true: sync to input port false: sync to output port\n"
  1059. "-t = copy input to output otherwise synthesize a 1000 Hz sine (false)\n"
  1060. "-p = report but don't start audio devices\n"
  1061. "-h = print this usage message\n";
  1062. cmRptPrintf(rpt,"%s",msg);
  1063. }
  1064. // Get a command line option.
  1065. int _cmRtGetOpt( int argc, const char* argv[], const char* label, int defaultVal, bool boolFl )
  1066. {
  1067. int i = 0;
  1068. for(; i<argc; ++i)
  1069. if( strcmp(label,argv[i]) == 0 )
  1070. {
  1071. if(boolFl)
  1072. return 1;
  1073. if( i == (argc-1) )
  1074. return defaultVal;
  1075. return atoi(argv[i+1]);
  1076. }
  1077. return defaultVal;
  1078. }
  1079. bool _cmRtGetBoolOpt( int argc, const char* argv[], const char* label, bool defaultVal )
  1080. { return _cmRtGetOpt(argc,argv,label,defaultVal?1:0,true)!=0; }
  1081. int _cmRtGetIntOpt( int argc, const char* argv[], const char* label, int defaultVal )
  1082. { return _cmRtGetOpt(argc,argv,label,defaultVal,false); }
  1083. void cmRtSysTest( cmCtx_t* ctx, int argc, const char* argv[] )
  1084. {
  1085. cmRtSysSubSys_t ss;
  1086. cmRtSysH_t h = cmRtSysNullHandle;
  1087. cmRtSysStatus_t status;
  1088. _cmRtTestCbRecd cbRecd = {1000.0,0,48000.0,0};
  1089. cmRpt_t* rpt = &ctx->rpt;
  1090. unsigned meterMs = 50;
  1091. unsigned ssCnt = 1;
  1092. unsigned rtSubIdx = 0;
  1093. if(_cmRtGetBoolOpt(argc,argv,"-h",false))
  1094. _cmRtPrintUsage(rpt);
  1095. cbRecd.srate = _cmRtGetIntOpt(argc,argv,"-r",48000);
  1096. cbRecd.synthFl = _cmRtGetBoolOpt(argc,argv,"-t",false)==false;
  1097. ss.args.rpt = rpt;
  1098. ss.args.inDevIdx = _cmRtGetIntOpt( argc,argv,"-i",0);
  1099. ss.args.outDevIdx = _cmRtGetIntOpt( argc,argv,"-o",2);
  1100. ss.args.syncInputFl = _cmRtGetBoolOpt(argc,argv,"-s",true);
  1101. ss.args.msgQueueByteCnt = _cmRtGetIntOpt( argc,argv,"-m",8192);
  1102. ss.args.devFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-f",512);
  1103. ss.args.dspFramesPerCycle = _cmRtGetIntOpt( argc,argv,"-d",64);;
  1104. ss.args.audioBufCnt = _cmRtGetIntOpt( argc,argv,"-b",3);
  1105. ss.args.srate = cbRecd.srate;
  1106. ss.cbFunc = _cmRtTestCb; // set the DSP entry function
  1107. ss.cbDataPtr = &cbRecd; // set the DSP function argument record
  1108. 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,
  1109. ss.args.msgQueueByteCnt,ss.args.devFramesPerCycle,ss.args.dspFramesPerCycle,ss.args.audioBufCnt,ss.args.srate);
  1110. if( cmApNrtAllocate(rpt) != kOkApRC )
  1111. goto errLabel;
  1112. if( cmApFileAllocate(rpt) != kOkApRC )
  1113. goto errLabel;
  1114. // initialize the audio device system
  1115. if( cmApInitialize(rpt) != kOkApRC )
  1116. goto errLabel;
  1117. cmApReport(rpt);
  1118. // initialize the audio buffer
  1119. if( cmApBufInitialize( cmApDeviceCount(), meterMs ) != kOkApRC )
  1120. goto errLabel;
  1121. // initialize the real-time system
  1122. if( cmRtSysAllocate(&h,ctx) != kOkRtRC )
  1123. goto errLabel;
  1124. if( cmRtSysBeginCfg(h,NULL,NULL,meterMs,ssCnt) != kOkRtRC )
  1125. goto errLabel;
  1126. if( cmRtSysCfg(h,&ss,rtSubIdx) != kOkRtRC )
  1127. goto errLabel;
  1128. if( cmRtSysEndCfg(h) != kOkRtRC )
  1129. goto errLabel;
  1130. // start the real-time system
  1131. cmRtSysEnable(h,true);
  1132. char c = 0;
  1133. printf("q=quit a-g=note n=ch r=rqst s=status\n");
  1134. // simulate a host event loop
  1135. while(c != 'q')
  1136. {
  1137. _cmRtTestMsg msg = {0,0,0,0};
  1138. bool fl = true;
  1139. // wait here for a key press
  1140. c =(char)fgetc(stdin);
  1141. fflush(stdin);
  1142. switch(c)
  1143. {
  1144. case 'c': msg.hz = cmMidiToHz(60); break;
  1145. case 'd': msg.hz = cmMidiToHz(62); break;
  1146. case 'e': msg.hz = cmMidiToHz(64); break;
  1147. case 'f': msg.hz = cmMidiToHz(65); break;
  1148. case 'g': msg.hz = cmMidiToHz(67); break;
  1149. case 'a': msg.hz = cmMidiToHz(69); break;
  1150. case 'b': msg.hz = cmMidiToHz(71); break;
  1151. case 'r': msg.id = 1; break; // request DSP process to send a callback count
  1152. case 'n': ++_cmRtTestChIdx; printf("ch:%i\n",_cmRtTestChIdx); break;
  1153. case 's':
  1154. // report the real-time system status
  1155. cmRtSysStatus(h,0,&status);
  1156. 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);
  1157. //printf("%f \n",status.oMeterArray[0]);
  1158. fl = false;
  1159. break;
  1160. default:
  1161. fl=false;
  1162. }
  1163. if( fl )
  1164. {
  1165. // transmit a command to the DSP process
  1166. cmRtSysDeliverMsg(h,&msg, sizeof(msg), cmInvalidId);
  1167. }
  1168. // check if messages are waiting to be delivered from the DSP process
  1169. unsigned msgByteCnt;
  1170. if((msgByteCnt = cmRtSysIsMsgWaiting(h)) > 0 )
  1171. {
  1172. char buf[ msgByteCnt ];
  1173. // rcv a msg from the DSP process
  1174. if( cmRtSysReceiveMsg(h,buf,msgByteCnt) == kOkRtRC )
  1175. {
  1176. _cmRtTestMsg* msg = (_cmRtTestMsg*)buf;
  1177. switch(msg->id)
  1178. {
  1179. case 1:
  1180. printf("RCV: Callback count:%i\n",msg->uint);
  1181. break;
  1182. }
  1183. }
  1184. }
  1185. // report the audio buffer status
  1186. //cmApBufReport(ss.args.rpt);
  1187. }
  1188. // stop the real-time system
  1189. cmRtSysEnable(h,false);
  1190. goto exitLabel;
  1191. errLabel:
  1192. printf("REAL-TIME SYSTEM TEST ERROR\n");
  1193. exitLabel:
  1194. cmRtSysFree(&h);
  1195. cmApFinalize();
  1196. cmApFileFree();
  1197. cmApNrtFree();
  1198. cmApBufFinalize();
  1199. }
  1200. /// [cmRtSysTest]