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

cmAudioSys.c 45KB

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