libcm is a C development framework with an emphasis on audio signal processing applications.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

cmAudioSys.c 43KB

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