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

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