libcm is a C development framework with an emphasis on audio signal processing applications.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

cmAudioSys.h 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /// \file cmAudioSys.h
  2. /// \brief Implements a real-time audio processing engine.
  3. ///
  4. /// The audio system is composed a collection of independent sub-systems.
  5. /// Each sub-system maintains a thread which runs asynchrounsly
  6. /// from the application, the MIDI devices, and the audio devices.
  7. /// To faciliate communication between these components each sub-system maintains
  8. /// two thread-safe data buffers one for control information and a second
  9. /// for audio data.
  10. ///
  11. /// The audio devices are the primary driver for the system.
  12. /// Callbacks from the audio devices (See #cmApCallbackPtr_t)
  13. /// inserts incoming audio samples into the audio
  14. /// record buffers and extracts samples from the playback buffer.
  15. /// When sufficient incoming samples and outgoing empty buffer space exists
  16. /// a sub-system thread is waken up by the callback. This triggers a DSP audio
  17. /// processing cycle which empties/fills the audio buffers. During a DSP
  18. /// processing cycle control messages from the application and MIDI are blocked and
  19. /// buffered. Upon completetion of the DSP cycle a control message
  20. /// transfer cycles occurs - buffered incoming messages are passed to
  21. /// the DSP system and messages originating in the DSP system are
  22. /// buffered by the audio system for later pickup by the application
  23. /// or MIDI system.
  24. ///
  25. /// Note that control messages that arrive when the DSP cycle is not
  26. /// occurring can pass directly through to the DSP system.
  27. ///
  28. /// The DSP system sends messages back to the host by calling
  29. /// cmAsDspToHostFunc_t provided by cmAudioSysCtx_t. These
  30. /// calls are always made from within an audio system call to
  31. /// audio or control update within cmAsCallback_t. cmAsDspToHostFunc_t
  32. /// simply stores the message in a message buffer. The host picks
  33. /// up the message at some later time when it notices that messages
  34. /// are waiting via polling cmAudioSysIsMsgWaiting().
  35. ///
  36. /// Implementation: \n
  37. /// The audio sub-systems work by maintaining an internal thread
  38. /// which blocks on a mutex condition variable.
  39. /// While the thread is blocked the mutex is unlocked allowing messages
  40. /// to pass directly through to the DSP procedure via cmAsCallback().
  41. ///
  42. /// Periodic calls from running audio devices update the audio buffer.
  43. /// When the audio buffer has input samples waiting and output space
  44. /// available the condition variable is signaled, the mutex is
  45. /// then automatically locked by the system, and the DSP execution
  46. /// procedure is called via cmAsCallback().
  47. ///
  48. /// Messages arriving while the mutex is locked are queued and
  49. /// delivered to the DSP procedure at the end of the DSP execution
  50. /// procedure.
  51. ///
  52. /// Usage example and testing code:
  53. /// See cmAudioSysTest().
  54. /// \snippet cmAudioSys.c cmAudioSysTest
  55. #ifndef cmAudioSys_h
  56. #define cmAudioSys_h
  57. #ifdef __cplusplus
  58. extern "C" {
  59. #endif
  60. /// Audio system result codes
  61. enum
  62. {
  63. kOkAsRC = cmOkRC,
  64. kThreadErrAsRC,
  65. kMutexErrAsRC,
  66. kTsQueueErrAsRC,
  67. kMsgEnqueueFailAsRC,
  68. kAudioDevSetupErrAsRC,
  69. kAudioBufSetupErrAsRC,
  70. kAudioDevStartFailAsRC,
  71. kAudioDevStopFailAsRC,
  72. kBufTooSmallAsRC,
  73. kNoMsgWaitingAsRC,
  74. kMidiSysFailAsRC,
  75. kMsgSerializeFailAsRC,
  76. kStateBufFailAsRC,
  77. kInvalidArgAsRC,
  78. kNotInitAsRC
  79. };
  80. typedef cmHandle_t cmAudioSysH_t; ///< Audio system handle type
  81. typedef unsigned cmAsRC_t; ///< Audio system result code
  82. struct cmAudioSysCtx_str;
  83. ///
  84. /// DSP system callback function.
  85. ///
  86. /// This is the sole point of entry into the DSP system while the audio system is running.
  87. ///
  88. /// ctxPtr is pointer to a cmAudioSysCtx_t record.
  89. ///
  90. /// This function is called under two circumstances:
  91. ///
  92. /// 1) To notify the DSP system that the audio input/output buffers need to be serviced.
  93. /// This is a perioidic request which the DSP system uses as its execution trigger.
  94. /// The msgByteCnt argument is set to zero to indicate this type of call.
  95. ///
  96. /// 2) To pass messages from the host application to the DSP system.
  97. /// The DSP system is asyncronous with the host because it executes in the audio system thread
  98. /// rather than the host thread. The cmAudioSysDeliverMsg() function synchronizes incoming
  99. /// messages with the internal audio system thread to prevent thread collisions.
  100. ///
  101. /// Notes:
  102. /// This callback is always made with the internal audio system mutex locked.
  103. ///
  104. /// The signal time covered by the callback is from
  105. /// ctx->begSmpIdx to ctx->begSmpIdx+cfg->dspFramesPerCycle.
  106. ///
  107. /// The return value is currently not used.
  108. typedef cmRC_t (*cmAsCallback_t)(void* ctxPtr, unsigned msgByteCnt, const void* msgDataPtr );
  109. /// Audio device sub-sytem configuration record
  110. typedef struct
  111. {
  112. cmRpt_t* rpt; ///< system console object
  113. unsigned inDevIdx; ///< input audio device
  114. unsigned outDevIdx; ///< output audio device
  115. bool syncInputFl; ///< true/false sync the DSP update callbacks with audio input/output
  116. unsigned msgQueueByteCnt; ///< Size of the internal msg queue used to buffer msgs arriving via cmAudioSysDeliverMsg().
  117. unsigned devFramesPerCycle; ///< (512) Audio device samples per channel per device update buffer.
  118. unsigned dspFramesPerCycle; ///< (64) Audio samples per channel per DSP cycle.
  119. unsigned audioBufCnt; ///< (3) Audio device buffers.
  120. double srate; ///< Audio sample rate.
  121. } cmAudioSysArgs_t;
  122. /// Audio sub-system configuration record.
  123. /// This record is provided by the host to configure the audio system
  124. /// via cmAudioSystemAllocate() or cmAudioSystemInitialize().
  125. typedef struct cmAudioSysSubSys_str
  126. {
  127. cmAudioSysArgs_t args; ///< Audio device configuration
  128. cmAsCallback_t cbFunc; ///< DSP system entry point function.
  129. void* cbDataPtr; ///< Host provided data for the DSP system callback.
  130. } cmAudioSysSubSys_t;
  131. /// Signature of a callback function provided by the audio system to receive messages
  132. /// from the DSP system for later dispatch to the host application.
  133. /// This declaration is used by the DSP system implementation and the audio system.
  134. /// Note that this function is intended to convey one message broken into multiple parts.
  135. /// See cmTsQueueEnqueueSegMsg() for the equivalent interface.
  136. typedef cmAsRC_t (*cmAsDspToHostFunc_t)(struct cmAudioSysCtx_str* p, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt);
  137. /// Informational record passed with each call to the DSP callback function cmAsCallback_t
  138. typedef struct cmAudioSysCtx_str
  139. {
  140. void* reserved; ///< used internally by the system
  141. bool audioRateFl;
  142. unsigned srcNetNodeId; ///<
  143. unsigned asSubIdx; ///< index of the sub-system this DSP process is serving
  144. cmAudioSysSubSys_t* ss; ///< ptr to a copy of the cfg recd used to initialize the audio system
  145. unsigned begSmpIdx; ///< gives signal time as a sample count
  146. cmAsDspToHostFunc_t dspToHostFunc; ///< Callback used by the DSP process to send messages to the host
  147. ///< via the audio system. Returns a cmAsRC_t result code.
  148. ///< output (playback) buffers
  149. cmSample_t** oChArray; ///< each ele is a ptr to buffer with cfg.dspFramesPerCycle samples
  150. unsigned oChCnt; ///< count of output channels (ele's in oChArray[])
  151. ///< input (recording) buffers
  152. cmSample_t** iChArray; ///< each ele is a ptr to buffer with cfg.dspFramesPerCycle samples
  153. unsigned iChCnt; ///< count of input channels (ele's in iChArray[])
  154. } cmAudioSysCtx_t;
  155. /*
  156. typedef struct
  157. {
  158. const cmChar_t* devLabel;
  159. const cmChar_t* inAudioFn;
  160. const cmChar_t* outAudioFn;
  161. unsigned oBits;
  162. unsigned oChCnt;
  163. } cmAudioSysFilePort_t;
  164. */
  165. /// Audio system configuration record used by cmAudioSysAllocate().
  166. typedef struct cmAudioSysCfg_str
  167. {
  168. cmAudioSysSubSys_t* ssArray; ///< sub-system cfg record array
  169. unsigned ssCnt; ///< count of sub-systems
  170. //cmAudioSysFilePort_t* afpArray; ///< audio port file cfg recd array
  171. //unsigned afpCnt; ///< audio port file cnt
  172. unsigned meterMs; ///< Meter sample period in milliseconds
  173. void* clientCbData; ///< User arg. for clientCbFunc().
  174. cmTsQueueCb_t clientCbFunc; ///< Called by cmAudioSysReceiveMsg() to deliver internally generated msg's to the host.
  175. /// Set to NULL if msg's will be directly returned by buffers passed to cmAudioSysReceiveMsg().
  176. cmUdpNetH_t netH;
  177. } cmAudioSysCfg_t;
  178. extern cmAudioSysH_t cmAudioSysNullHandle;
  179. /// Allocate and initialize an audio system as a collection of 'cfgCnt' sub-systems.
  180. /// Notes:
  181. /// The audio ports system must be initalized (via cmApInitialize()) prior to calling cmAudioSysAllocate().
  182. /// The MIDI port system must be initialized (via cmMpInitialize()) prior to calling cmAudioSysAllocate().
  183. /// Furthermore cmApFinalize() and cmMpFinalize() cannot be called prior to cmAudioSysFree().
  184. /// See cmAudioSystemTest() for a complete example.
  185. cmAsRC_t cmAudioSysAllocate( cmAudioSysH_t* hp, cmRpt_t* rpt, const cmAudioSysCfg_t* cfg );
  186. /// Finalize and release any resources held by the audio system.
  187. cmAsRC_t cmAudioSysFree( cmAudioSysH_t* hp );
  188. /// Returns true if 'h' is a handle which was successfully allocated by cmAudioSysAllocate().
  189. bool cmAudioSysHandleIsValid( cmAudioSysH_t h );
  190. /// Reinitialize a previously allocated audio system. This function
  191. /// begins with a call to cmAudioSysFinalize().
  192. /// Use cmAudioSysEnable(h,true) to begin processing audio following this call.
  193. cmAsRC_t cmAudioSysInitialize( cmAudioSysH_t h, const cmAudioSysCfg_t* cfg );
  194. /// Complements cmAudioSysInitialize(). In general there is no need to call this function
  195. /// since calls to cmAudioSysInitialize() and cmAudioSysFree() automaticatically call it.
  196. cmAsRC_t cmAudioSysFinalize( cmAudioSysH_t h );
  197. /// Returns true if the audio system has been successfully initialized.
  198. bool cmAudioSysIsInitialized( cmAudioSysH_t );
  199. /// Returns true if the audio system is enabled.
  200. bool cmAudioSysIsEnabled( cmAudioSysH_t h );
  201. /// Enable/disable the audio system. Enabling the starts audio stream
  202. /// in/out of the system.
  203. cmAsRC_t cmAudioSysEnable( cmAudioSysH_t h, bool enableFl );
  204. /// \name Host to DSP delivery functions
  205. /// @{
  206. /// Deliver a message from the host application to the DSP process. (host -> DSP);
  207. /// The message is formed as a concatenation of the bytes in each of the segments
  208. /// pointed to by 'msgDataPtrArrary[segCnt][msgByteCntArray[segCnt]'.
  209. /// This is the canonical msg delivery function in so far as the other host->DSP
  210. /// msg delivery function are written in terms of this function.
  211. /// The first 4 bytes in the first segment must contain the index of the audio sub-system
  212. /// which is to receive the message.
  213. cmAsRC_t cmAudioSysDeliverSegMsg( cmAudioSysH_t h, const void* msgDataPtrArray[], unsigned msgByteCntArray[], unsigned msgSegCnt, unsigned srcNetNodeId );
  214. /// Deliver a single message from the host to the DSP system.
  215. cmAsRC_t cmAudioSysDeliverMsg( cmAudioSysH_t h, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId );
  216. /// Deliver a single message from the host to the DSP system.
  217. /// Prior to delivery the 'id' is prepended to the message.
  218. cmAsRC_t cmAudioSysDeliverIdMsg( cmAudioSysH_t h, unsigned asSubIdx, unsigned id, const void* msgPtr, unsigned msgByteCnt, unsigned srcNetNodeId );
  219. ///@}
  220. /// \name DSP to Host message functions
  221. /// @{
  222. /// Is a msg from the DSP waiting to be picked up by the host? (host <- DSP)
  223. /// 0 = no msgs are waiting or the msg queue is locked by the DSP process.
  224. /// >0 = the size of the buffer required to hold the next msg returned via
  225. /// cmAudioSysReceiveMsg().
  226. unsigned cmAudioSysIsMsgWaiting( cmAudioSysH_t h );
  227. /// Copy the next available msg sent from the DSP process to the host into the host supplied msg buffer
  228. /// pointed to by 'msgBufPtr'. Set 'msgDataPtr' to NULL to receive msg by callback from cmAudioSysCfg_t.clientCbFunc.
  229. /// Returns kBufTooSmallAsRC if msgDataPtr[msgByteCnt] is too small to hold the msg.
  230. /// Returns kNoMsgWaitingAsRC if no messages are waiting for delivery or the msg queue is locked by the DSP process.
  231. /// Returns kOkAsRC if a msg was delivered.
  232. /// Call cmAudioSysIsMsgWaiting() prior to calling this function to get
  233. /// the size of the data buffer required to hold the next message.
  234. cmAsRC_t cmAudioSysReceiveMsg( cmAudioSysH_t h, void* msgDataPtr, unsigned msgByteCnt );
  235. /// @}
  236. /// Fill an audio system status record.
  237. void cmAudioSysStatus( cmAudioSysH_t h, unsigned asSubIdx, cmAudioSysStatus_t* statusPtr );
  238. /// Enable cmAudioSysStatus_t notifications to be sent periodically to the host.
  239. /// Set asSubIdx to cmInvalidIdx to enable/disable all sub-systems.
  240. /// The notifications occur approximately every cmAudioSysCfg_t.meterMs milliseconds.
  241. void cmAudioSysStatusNotifyEnable( cmAudioSysH_t, unsigned asSubIdx, bool enableFl );
  242. /// Return a pointer the context record associated with a sub-system
  243. cmAudioSysCtx_t* cmAudioSysContext( cmAudioSysH_t h, unsigned asSubIdx );
  244. /// Return the count of audio sub-systems.
  245. /// This is the same as the count of cfg recds passed to cmAudioSystemInitialize().
  246. unsigned cmAudioSysSubSystemCount( cmAudioSysH_t h );
  247. /// Audio system test and example function.
  248. void cmAudioSysTest( cmRpt_t* rpt, int argc, const char* argv[] );
  249. #ifdef __cplusplus
  250. }
  251. #endif
  252. #endif