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

cmAudioSys.c 44KB

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