libcm is a C development framework with an emphasis on audio signal processing applications.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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