libcm is a C development framework with an emphasis on audio signal processing applications.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

cmAudioSys.c 43KB

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