doc.odin 188 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714
  1. package miniaudio
  2. /*
  3. Audio playback and capture library. Choice of public domain or MIT-0. See license statements at the end of this file.
  4. miniaudio - v0.11.21 - 2023-11-15
  5. David Reid - [email protected]
  6. Website: https://miniaud.io
  7. Documentation: https://miniaud.io/docs
  8. GitHub: https://github.com/mackron/miniaudio
  9. */
  10. /*
  11. 1. Introduction
  12. ===============
  13. miniaudio is a single file library for audio playback and capture. To use it, do the following in
  14. one .c file:
  15. ```c
  16. #define MINIAUDIO_IMPLEMENTATION
  17. #include "miniaudio.h"
  18. ```
  19. You can do `#include "miniaudio.h"` in other parts of the program just like any other header.
  20. miniaudio includes both low level and high level APIs. The low level API is good for those who want
  21. to do all of their mixing themselves and only require a light weight interface to the underlying
  22. audio device. The high level API is good for those who have complex mixing and effect requirements.
  23. In miniaudio, objects are transparent structures. Unlike many other libraries, there are no handles
  24. to opaque objects which means you need to allocate memory for objects yourself. In the examples
  25. presented in this documentation you will often see objects declared on the stack. You need to be
  26. careful when translating these examples to your own code so that you don't accidentally declare
  27. your objects on the stack and then cause them to become invalid once the function returns. In
  28. addition, you must ensure the memory address of your objects remain the same throughout their
  29. lifetime. You therefore cannot be making copies of your objects.
  30. A config/init pattern is used throughout the entire library. The idea is that you set up a config
  31. object and pass that into the initialization routine. The advantage to this system is that the
  32. config object can be initialized with logical defaults and new properties added to it without
  33. breaking the API. The config object can be allocated on the stack and does not need to be
  34. maintained after initialization of the corresponding object.
  35. 1.1. Low Level API
  36. ------------------
  37. The low level API gives you access to the raw audio data of an audio device. It supports playback,
  38. capture, full-duplex and loopback (WASAPI only). You can enumerate over devices to determine which
  39. physical device(s) you want to connect to.
  40. The low level API uses the concept of a "device" as the abstraction for physical devices. The idea
  41. is that you choose a physical device to emit or capture audio from, and then move data to/from the
  42. device when miniaudio tells you to. Data is delivered to and from devices asynchronously via a
  43. callback which you specify when initializing the device.
  44. When initializing the device you first need to configure it. The device configuration allows you to
  45. specify things like the format of the data delivered via the callback, the size of the internal
  46. buffer and the ID of the device you want to emit or capture audio from.
  47. Once you have the device configuration set up you can initialize the device. When initializing a
  48. device you need to allocate memory for the device object beforehand. This gives the application
  49. complete control over how the memory is allocated. In the example below we initialize a playback
  50. device on the stack, but you could allocate it on the heap if that suits your situation better.
  51. ```c
  52. void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  53. {
  54. // In playback mode copy data to pOutput. In capture mode read data from pInput. In full-duplex mode, both
  55. // pOutput and pInput will be valid and you can move data from pInput into pOutput. Never process more than
  56. // frameCount frames.
  57. }
  58. int main()
  59. {
  60. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  61. config.playback.format = ma_format_f32; // Set to ma_format_unknown to use the device's native format.
  62. config.playback.channels = 2; // Set to 0 to use the device's native channel count.
  63. config.sampleRate = 48000; // Set to 0 to use the device's native sample rate.
  64. config.dataCallback = data_callback; // This function will be called when miniaudio needs more data.
  65. config.pUserData = pMyCustomData; // Can be accessed from the device object (device.pUserData).
  66. ma_device device;
  67. if (ma_device_init(NULL, &config, &device) != MA_SUCCESS) {
  68. return -1; // Failed to initialize the device.
  69. }
  70. ma_device_start(&device); // The device is sleeping by default so you'll need to start it manually.
  71. // Do something here. Probably your program's main loop.
  72. ma_device_uninit(&device);
  73. return 0;
  74. }
  75. ```
  76. In the example above, `data_callback()` is where audio data is written and read from the device.
  77. The idea is in playback mode you cause sound to be emitted from the speakers by writing audio data
  78. to the output buffer (`pOutput` in the example). In capture mode you read data from the input
  79. buffer (`pInput`) to extract sound captured by the microphone. The `frameCount` parameter tells you
  80. how many frames can be written to the output buffer and read from the input buffer. A "frame" is
  81. one sample for each channel. For example, in a stereo stream (2 channels), one frame is 2
  82. samples: one for the left, one for the right. The channel count is defined by the device config.
  83. The size in bytes of an individual sample is defined by the sample format which is also specified
  84. in the device config. Multi-channel audio data is always interleaved, which means the samples for
  85. each frame are stored next to each other in memory. For example, in a stereo stream the first pair
  86. of samples will be the left and right samples for the first frame, the second pair of samples will
  87. be the left and right samples for the second frame, etc.
  88. The configuration of the device is defined by the `ma_device_config` structure. The config object
  89. is always initialized with `ma_device_config_init()`. It's important to always initialize the
  90. config with this function as it initializes it with logical defaults and ensures your program
  91. doesn't break when new members are added to the `ma_device_config` structure. The example above
  92. uses a fairly simple and standard device configuration. The call to `ma_device_config_init()` takes
  93. a single parameter, which is whether or not the device is a playback, capture, duplex or loopback
  94. device (loopback devices are not supported on all backends). The `config.playback.format` member
  95. sets the sample format which can be one of the following (all formats are native-endian):
  96. +---------------+----------------------------------------+---------------------------+
  97. | Symbol | Description | Range |
  98. +---------------+----------------------------------------+---------------------------+
  99. | ma_format_f32 | 32-bit floating point | [-1, 1] |
  100. | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
  101. | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
  102. | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
  103. | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
  104. +---------------+----------------------------------------+---------------------------+
  105. The `config.playback.channels` member sets the number of channels to use with the device. The
  106. channel count cannot exceed MA_MAX_CHANNELS. The `config.sampleRate` member sets the sample rate
  107. (which must be the same for both playback and capture in full-duplex configurations). This is
  108. usually set to 44100 or 48000, but can be set to anything. It's recommended to keep this between
  109. 8000 and 384000, however.
  110. Note that leaving the format, channel count and/or sample rate at their default values will result
  111. in the internal device's native configuration being used which is useful if you want to avoid the
  112. overhead of miniaudio's automatic data conversion.
  113. In addition to the sample format, channel count and sample rate, the data callback and user data
  114. pointer are also set via the config. The user data pointer is not passed into the callback as a
  115. parameter, but is instead set to the `pUserData` member of `ma_device` which you can access
  116. directly since all miniaudio structures are transparent.
  117. Initializing the device is done with `ma_device_init()`. This will return a result code telling you
  118. what went wrong, if anything. On success it will return `MA_SUCCESS`. After initialization is
  119. complete the device will be in a stopped state. To start it, use `ma_device_start()`.
  120. Uninitializing the device will stop it, which is what the example above does, but you can also stop
  121. the device with `ma_device_stop()`. To resume the device simply call `ma_device_start()` again.
  122. Note that it's important to never stop or start the device from inside the callback. This will
  123. result in a deadlock. Instead you set a variable or signal an event indicating that the device
  124. needs to stop and handle it in a different thread. The following APIs must never be called inside
  125. the callback:
  126. ```c
  127. ma_device_init()
  128. ma_device_init_ex()
  129. ma_device_uninit()
  130. ma_device_start()
  131. ma_device_stop()
  132. ```
  133. You must never try uninitializing and reinitializing a device inside the callback. You must also
  134. never try to stop and start it from inside the callback. There are a few other things you shouldn't
  135. do in the callback depending on your requirements, however this isn't so much a thread-safety
  136. thing, but rather a real-time processing thing which is beyond the scope of this introduction.
  137. The example above demonstrates the initialization of a playback device, but it works exactly the
  138. same for capture. All you need to do is change the device type from `ma_device_type_playback` to
  139. `ma_device_type_capture` when setting up the config, like so:
  140. ```c
  141. ma_device_config config = ma_device_config_init(ma_device_type_capture);
  142. config.capture.format = MY_FORMAT;
  143. config.capture.channels = MY_CHANNEL_COUNT;
  144. ```
  145. In the data callback you just read from the input buffer (`pInput` in the example above) and leave
  146. the output buffer alone (it will be set to NULL when the device type is set to
  147. `ma_device_type_capture`).
  148. These are the available device types and how you should handle the buffers in the callback:
  149. +-------------------------+--------------------------------------------------------+
  150. | Device Type | Callback Behavior |
  151. +-------------------------+--------------------------------------------------------+
  152. | ma_device_type_playback | Write to output buffer, leave input buffer untouched. |
  153. | ma_device_type_capture | Read from input buffer, leave output buffer untouched. |
  154. | ma_device_type_duplex | Read from input buffer, write to output buffer. |
  155. | ma_device_type_loopback | Read from input buffer, leave output buffer untouched. |
  156. +-------------------------+--------------------------------------------------------+
  157. You will notice in the example above that the sample format and channel count is specified
  158. separately for playback and capture. This is to support different data formats between the playback
  159. and capture devices in a full-duplex system. An example may be that you want to capture audio data
  160. as a monaural stream (one channel), but output sound to a stereo speaker system. Note that if you
  161. use different formats between playback and capture in a full-duplex configuration you will need to
  162. convert the data yourself. There are functions available to help you do this which will be
  163. explained later.
  164. The example above did not specify a physical device to connect to which means it will use the
  165. operating system's default device. If you have multiple physical devices connected and you want to
  166. use a specific one you will need to specify the device ID in the configuration, like so:
  167. ```c
  168. config.playback.pDeviceID = pMyPlaybackDeviceID; // Only if requesting a playback or duplex device.
  169. config.capture.pDeviceID = pMyCaptureDeviceID; // Only if requesting a capture, duplex or loopback device.
  170. ```
  171. To retrieve the device ID you will need to perform device enumeration, however this requires the
  172. use of a new concept called the "context". Conceptually speaking the context sits above the device.
  173. There is one context to many devices. The purpose of the context is to represent the backend at a
  174. more global level and to perform operations outside the scope of an individual device. Mainly it is
  175. used for performing run-time linking against backend libraries, initializing backends and
  176. enumerating devices. The example below shows how to enumerate devices.
  177. ```c
  178. ma_context context;
  179. if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) {
  180. // Error.
  181. }
  182. ma_device_info* pPlaybackInfos;
  183. ma_uint32 playbackCount;
  184. ma_device_info* pCaptureInfos;
  185. ma_uint32 captureCount;
  186. if (ma_context_get_devices(&context, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount) != MA_SUCCESS) {
  187. // Error.
  188. }
  189. // Loop over each device info and do something with it. Here we just print the name with their index. You may want
  190. // to give the user the opportunity to choose which device they'd prefer.
  191. for (ma_uint32 iDevice = 0; iDevice < playbackCount; iDevice += 1) {
  192. printf("%d - %s\n", iDevice, pPlaybackInfos[iDevice].name);
  193. }
  194. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  195. config.playback.pDeviceID = &pPlaybackInfos[chosenPlaybackDeviceIndex].id;
  196. config.playback.format = MY_FORMAT;
  197. config.playback.channels = MY_CHANNEL_COUNT;
  198. config.sampleRate = MY_SAMPLE_RATE;
  199. config.dataCallback = data_callback;
  200. config.pUserData = pMyCustomData;
  201. ma_device device;
  202. if (ma_device_init(&context, &config, &device) != MA_SUCCESS) {
  203. // Error
  204. }
  205. ...
  206. ma_device_uninit(&device);
  207. ma_context_uninit(&context);
  208. ```
  209. The first thing we do in this example is initialize a `ma_context` object with `ma_context_init()`.
  210. The first parameter is a pointer to a list of `ma_backend` values which are used to override the
  211. default backend priorities. When this is NULL, as in this example, miniaudio's default priorities
  212. are used. The second parameter is the number of backends listed in the array pointed to by the
  213. first parameter. The third parameter is a pointer to a `ma_context_config` object which can be
  214. NULL, in which case defaults are used. The context configuration is used for setting the logging
  215. callback, custom memory allocation callbacks, user-defined data and some backend-specific
  216. configurations.
  217. Once the context has been initialized you can enumerate devices. In the example above we use the
  218. simpler `ma_context_get_devices()`, however you can also use a callback for handling devices by
  219. using `ma_context_enumerate_devices()`. When using `ma_context_get_devices()` you provide a pointer
  220. to a pointer that will, upon output, be set to a pointer to a buffer containing a list of
  221. `ma_device_info` structures. You also provide a pointer to an unsigned integer that will receive
  222. the number of items in the returned buffer. Do not free the returned buffers as their memory is
  223. managed internally by miniaudio.
  224. The `ma_device_info` structure contains an `id` member which is the ID you pass to the device
  225. config. It also contains the name of the device which is useful for presenting a list of devices
  226. to the user via the UI.
  227. When creating your own context you will want to pass it to `ma_device_init()` when initializing the
  228. device. Passing in NULL, like we do in the first example, will result in miniaudio creating the
  229. context for you, which you don't want to do since you've already created a context. Note that
  230. internally the context is only tracked by it's pointer which means you must not change the location
  231. of the `ma_context` object. If this is an issue, consider using `malloc()` to allocate memory for
  232. the context.
  233. 1.2. High Level API
  234. -------------------
  235. The high level API consists of three main parts:
  236. * Resource management for loading and streaming sounds.
  237. * A node graph for advanced mixing and effect processing.
  238. * A high level "engine" that wraps around the resource manager and node graph.
  239. The resource manager (`ma_resource_manager`) is used for loading sounds. It supports loading sounds
  240. fully into memory and also streaming. It will also deal with reference counting for you which
  241. avoids the same sound being loaded multiple times.
  242. The node graph is used for mixing and effect processing. The idea is that you connect a number of
  243. nodes into the graph by connecting each node's outputs to another node's inputs. Each node can
  244. implement it's own effect. By chaining nodes together, advanced mixing and effect processing can
  245. be achieved.
  246. The engine encapsulates both the resource manager and the node graph to create a simple, easy to
  247. use high level API. The resource manager and node graph APIs are covered in more later sections of
  248. this manual.
  249. The code below shows how you can initialize an engine using it's default configuration.
  250. ```c
  251. ma_result result;
  252. ma_engine engine;
  253. result = ma_engine_init(NULL, &engine);
  254. if (result != MA_SUCCESS) {
  255. return result; // Failed to initialize the engine.
  256. }
  257. ```
  258. This creates an engine instance which will initialize a device internally which you can access with
  259. `ma_engine_get_device()`. It will also initialize a resource manager for you which can be accessed
  260. with `ma_engine_get_resource_manager()`. The engine itself is a node graph (`ma_node_graph`) which
  261. means you can pass a pointer to the engine object into any of the `ma_node_graph` APIs (with a
  262. cast). Alternatively, you can use `ma_engine_get_node_graph()` instead of a cast.
  263. Note that all objects in miniaudio, including the `ma_engine` object in the example above, are
  264. transparent structures. There are no handles to opaque structures in miniaudio which means you need
  265. to be mindful of how you declare them. In the example above we are declaring it on the stack, but
  266. this will result in the struct being invalidated once the function encapsulating it returns. If
  267. allocating the engine on the heap is more appropriate, you can easily do so with a standard call
  268. to `malloc()` or whatever heap allocation routine you like:
  269. ```c
  270. ma_engine* pEngine = malloc(sizeof(*pEngine));
  271. ```
  272. The `ma_engine` API uses the same config/init pattern used all throughout miniaudio. To configure
  273. an engine, you can fill out a `ma_engine_config` object and pass it into the first parameter of
  274. `ma_engine_init()`:
  275. ```c
  276. ma_result result;
  277. ma_engine engine;
  278. ma_engine_config engineConfig;
  279. engineConfig = ma_engine_config_init();
  280. engineConfig.pResourceManager = &myCustomResourceManager; // <-- Initialized as some earlier stage.
  281. result = ma_engine_init(&engineConfig, &engine);
  282. if (result != MA_SUCCESS) {
  283. return result;
  284. }
  285. ```
  286. This creates an engine instance using a custom config. In this particular example it's showing how
  287. you can specify a custom resource manager rather than having the engine initialize one internally.
  288. This is particularly useful if you want to have multiple engine's share the same resource manager.
  289. The engine must be uninitialized with `ma_engine_uninit()` when it's no longer needed.
  290. By default the engine will be started, but nothing will be playing because no sounds have been
  291. initialized. The easiest but least flexible way of playing a sound is like so:
  292. ```c
  293. ma_engine_play_sound(&engine, "my_sound.wav", NULL);
  294. ```
  295. This plays what miniaudio calls an "inline" sound. It plays the sound once, and then puts the
  296. internal sound up for recycling. The last parameter is used to specify which sound group the sound
  297. should be associated with which will be explained later. This particular way of playing a sound is
  298. simple, but lacks flexibility and features. A more flexible way of playing a sound is to first
  299. initialize a sound:
  300. ```c
  301. ma_result result;
  302. ma_sound sound;
  303. result = ma_sound_init_from_file(&engine, "my_sound.wav", 0, NULL, NULL, &sound);
  304. if (result != MA_SUCCESS) {
  305. return result;
  306. }
  307. ma_sound_start(&sound);
  308. ```
  309. This returns a `ma_sound` object which represents a single instance of the specified sound file. If
  310. you want to play the same file multiple times simultaneously, you need to create one sound for each
  311. instance.
  312. Sounds should be uninitialized with `ma_sound_uninit()`.
  313. Sounds are not started by default. Start a sound with `ma_sound_start()` and stop it with
  314. `ma_sound_stop()`. When a sound is stopped, it is not rewound to the start. Use
  315. `ma_sound_seek_to_pcm_frame(&sound, 0)` to seek back to the start of a sound. By default, starting
  316. and stopping sounds happens immediately, but sometimes it might be convenient to schedule the sound
  317. the be started and/or stopped at a specific time. This can be done with the following functions:
  318. ```c
  319. ma_sound_set_start_time_in_pcm_frames()
  320. ma_sound_set_start_time_in_milliseconds()
  321. ma_sound_set_stop_time_in_pcm_frames()
  322. ma_sound_set_stop_time_in_milliseconds()
  323. ```
  324. The start/stop time needs to be specified based on the absolute timer which is controlled by the
  325. engine. The current global time time in PCM frames can be retrieved with
  326. `ma_engine_get_time_in_pcm_frames()`. The engine's global time can be changed with
  327. `ma_engine_set_time_in_pcm_frames()` for synchronization purposes if required. Note that scheduling
  328. a start time still requires an explicit call to `ma_sound_start()` before anything will play:
  329. ```c
  330. ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2);
  331. ma_sound_start(&sound);
  332. ```
  333. The third parameter of `ma_sound_init_from_file()` is a set of flags that control how the sound be
  334. loaded and a few options on which features should be enabled for that sound. By default, the sound
  335. is synchronously loaded fully into memory straight from the file system without any kind of
  336. decoding. If you want to decode the sound before storing it in memory, you need to specify the
  337. `MA_SOUND_FLAG_DECODE` flag. This is useful if you want to incur the cost of decoding at an earlier
  338. stage, such as a loading stage. Without this option, decoding will happen dynamically at mixing
  339. time which might be too expensive on the audio thread.
  340. If you want to load the sound asynchronously, you can specify the `MA_SOUND_FLAG_ASYNC` flag. This
  341. will result in `ma_sound_init_from_file()` returning quickly, but the sound will not start playing
  342. until the sound has had some audio decoded.
  343. The fourth parameter is a pointer to sound group. A sound group is used as a mechanism to organise
  344. sounds into groups which have their own effect processing and volume control. An example is a game
  345. which might have separate groups for sfx, voice and music. Each of these groups have their own
  346. independent volume control. Use `ma_sound_group_init()` or `ma_sound_group_init_ex()` to initialize
  347. a sound group.
  348. Sounds and sound groups are nodes in the engine's node graph and can be plugged into any `ma_node`
  349. API. This makes it possible to connect sounds and sound groups to effect nodes to produce complex
  350. effect chains.
  351. A sound can have it's volume changed with `ma_sound_set_volume()`. If you prefer decibel volume
  352. control you can use `ma_volume_db_to_linear()` to convert from decibel representation to linear.
  353. Panning and pitching is supported with `ma_sound_set_pan()` and `ma_sound_set_pitch()`. If you know
  354. a sound will never have it's pitch changed with `ma_sound_set_pitch()` or via the doppler effect,
  355. you can specify the `MA_SOUND_FLAG_NO_PITCH` flag when initializing the sound for an optimization.
  356. By default, sounds and sound groups have spatialization enabled. If you don't ever want to
  357. spatialize your sounds, initialize the sound with the `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. The
  358. spatialization model is fairly simple and is roughly on feature parity with OpenAL. HRTF and
  359. environmental occlusion are not currently supported, but planned for the future. The supported
  360. features include:
  361. * Sound and listener positioning and orientation with cones
  362. * Attenuation models: none, inverse, linear and exponential
  363. * Doppler effect
  364. Sounds can be faded in and out with `ma_sound_set_fade_in_pcm_frames()`.
  365. To check if a sound is currently playing, you can use `ma_sound_is_playing()`. To check if a sound
  366. is at the end, use `ma_sound_at_end()`. Looping of a sound can be controlled with
  367. `ma_sound_set_looping()`. Use `ma_sound_is_looping()` to check whether or not the sound is looping.
  368. 2. Building
  369. ===========
  370. miniaudio should work cleanly out of the box without the need to download or install any
  371. dependencies. See below for platform-specific details.
  372. Note that GCC and Clang require `-msse2`, `-mavx2`, etc. for SIMD optimizations.
  373. If you get errors about undefined references to `__sync_val_compare_and_swap_8`, `__atomic_load_8`,
  374. etc. you need to link with `-latomic`.
  375. 2.1. Windows
  376. ------------
  377. The Windows build should compile cleanly on all popular compilers without the need to configure any
  378. include paths nor link to any libraries.
  379. The UWP build may require linking to mmdevapi.lib if you get errors about an unresolved external
  380. symbol for `ActivateAudioInterfaceAsync()`.
  381. 2.2. macOS and iOS
  382. ------------------
  383. The macOS build should compile cleanly without the need to download any dependencies nor link to
  384. any libraries or frameworks. The iOS build needs to be compiled as Objective-C and will need to
  385. link the relevant frameworks but should compile cleanly out of the box with Xcode. Compiling
  386. through the command line requires linking to `-lpthread` and `-lm`.
  387. Due to the way miniaudio links to frameworks at runtime, your application may not pass Apple's
  388. notarization process. To fix this there are two options. The first is to use the
  389. `MA_NO_RUNTIME_LINKING` option, like so:
  390. ```c
  391. #ifdef __APPLE__
  392. #define MA_NO_RUNTIME_LINKING
  393. #endif
  394. #define MINIAUDIO_IMPLEMENTATION
  395. #include "miniaudio.h"
  396. ```
  397. This will require linking with `-framework CoreFoundation -framework CoreAudio -framework AudioToolbox`.
  398. If you get errors about AudioToolbox, try with `-framework AudioUnit` instead. You may get this when
  399. using older versions of iOS. Alternatively, if you would rather keep using runtime linking you can
  400. add the following to your entitlements.xcent file:
  401. ```
  402. <key>com.apple.security.cs.allow-dyld-environment-variables</key>
  403. <true/>
  404. <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
  405. <true/>
  406. ```
  407. See this discussion for more info: https://github.com/mackron/miniaudio/issues/203.
  408. 2.3. Linux
  409. ----------
  410. The Linux build only requires linking to `-ldl`, `-lpthread` and `-lm`. You do not need any
  411. development packages. You may need to link with `-latomic` if you're compiling for 32-bit ARM.
  412. 2.4. BSD
  413. --------
  414. The BSD build only requires linking to `-lpthread` and `-lm`. NetBSD uses audio(4), OpenBSD uses
  415. sndio and FreeBSD uses OSS. You may need to link with `-latomic` if you're compiling for 32-bit
  416. ARM.
  417. 2.5. Android
  418. ------------
  419. AAudio is the highest priority backend on Android. This should work out of the box without needing
  420. any kind of compiler configuration. Support for AAudio starts with Android 8 which means older
  421. versions will fall back to OpenSL|ES which requires API level 16+.
  422. There have been reports that the OpenSL|ES backend fails to initialize on some Android based
  423. devices due to `dlopen()` failing to open "libOpenSLES.so". If this happens on your platform
  424. you'll need to disable run-time linking with `MA_NO_RUNTIME_LINKING` and link with -lOpenSLES.
  425. 2.6. Emscripten
  426. ---------------
  427. The Emscripten build emits Web Audio JavaScript directly and should compile cleanly out of the box.
  428. You cannot use `-std=c*` compiler flags, nor `-ansi`.
  429. You can enable the use of AudioWorkets by defining `MA_ENABLE_AUDIO_WORKLETS` and then compiling
  430. with the following options:
  431. -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY
  432. An example for compiling with AudioWorklet support might look like this:
  433. emcc program.c -o bin/program.html -DMA_ENABLE_AUDIO_WORKLETS -sAUDIO_WORKLET=1 -sWASM_WORKERS=1 -sASYNCIFY
  434. To run locally, you'll need to use emrun:
  435. emrun bin/program.html
  436. 2.7. Build Options
  437. ------------------
  438. `#define` these options before including miniaudio.h.
  439. +----------------------------------+--------------------------------------------------------------------+
  440. | Option | Description |
  441. +----------------------------------+--------------------------------------------------------------------+
  442. | MA_NO_WASAPI | Disables the WASAPI backend. |
  443. +----------------------------------+--------------------------------------------------------------------+
  444. | MA_NO_DSOUND | Disables the DirectSound backend. |
  445. +----------------------------------+--------------------------------------------------------------------+
  446. | MA_NO_WINMM | Disables the WinMM backend. |
  447. +----------------------------------+--------------------------------------------------------------------+
  448. | MA_NO_ALSA | Disables the ALSA backend. |
  449. +----------------------------------+--------------------------------------------------------------------+
  450. | MA_NO_PULSEAUDIO | Disables the PulseAudio backend. |
  451. +----------------------------------+--------------------------------------------------------------------+
  452. | MA_NO_JACK | Disables the JACK backend. |
  453. +----------------------------------+--------------------------------------------------------------------+
  454. | MA_NO_COREAUDIO | Disables the Core Audio backend. |
  455. +----------------------------------+--------------------------------------------------------------------+
  456. | MA_NO_SNDIO | Disables the sndio backend. |
  457. +----------------------------------+--------------------------------------------------------------------+
  458. | MA_NO_AUDIO4 | Disables the audio(4) backend. |
  459. +----------------------------------+--------------------------------------------------------------------+
  460. | MA_NO_OSS | Disables the OSS backend. |
  461. +----------------------------------+--------------------------------------------------------------------+
  462. | MA_NO_AAUDIO | Disables the AAudio backend. |
  463. +----------------------------------+--------------------------------------------------------------------+
  464. | MA_NO_OPENSL | Disables the OpenSL|ES backend. |
  465. +----------------------------------+--------------------------------------------------------------------+
  466. | MA_NO_WEBAUDIO | Disables the Web Audio backend. |
  467. +----------------------------------+--------------------------------------------------------------------+
  468. | MA_NO_NULL | Disables the null backend. |
  469. +----------------------------------+--------------------------------------------------------------------+
  470. | MA_ENABLE_ONLY_SPECIFIC_BACKENDS | Disables all backends by default and requires `MA_ENABLE_*` to |
  471. | | enable specific backends. |
  472. +----------------------------------+--------------------------------------------------------------------+
  473. | MA_ENABLE_WASAPI | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  474. | | enable the WASAPI backend. |
  475. +----------------------------------+--------------------------------------------------------------------+
  476. | MA_ENABLE_DSOUND | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  477. | | enable the DirectSound backend. |
  478. +----------------------------------+--------------------------------------------------------------------+
  479. | MA_ENABLE_WINMM | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  480. | | enable the WinMM backend. |
  481. +----------------------------------+--------------------------------------------------------------------+
  482. | MA_ENABLE_ALSA | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  483. | | enable the ALSA backend. |
  484. +----------------------------------+--------------------------------------------------------------------+
  485. | MA_ENABLE_PULSEAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  486. | | enable the PulseAudio backend. |
  487. +----------------------------------+--------------------------------------------------------------------+
  488. | MA_ENABLE_JACK | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  489. | | enable the JACK backend. |
  490. +----------------------------------+--------------------------------------------------------------------+
  491. | MA_ENABLE_COREAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  492. | | enable the Core Audio backend. |
  493. +----------------------------------+--------------------------------------------------------------------+
  494. | MA_ENABLE_SNDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  495. | | enable the sndio backend. |
  496. +----------------------------------+--------------------------------------------------------------------+
  497. | MA_ENABLE_AUDIO4 | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  498. | | enable the audio(4) backend. |
  499. +----------------------------------+--------------------------------------------------------------------+
  500. | MA_ENABLE_OSS | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  501. | | enable the OSS backend. |
  502. +----------------------------------+--------------------------------------------------------------------+
  503. | MA_ENABLE_AAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  504. | | enable the AAudio backend. |
  505. +----------------------------------+--------------------------------------------------------------------+
  506. | MA_ENABLE_OPENSL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  507. | | enable the OpenSL|ES backend. |
  508. +----------------------------------+--------------------------------------------------------------------+
  509. | MA_ENABLE_WEBAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  510. | | enable the Web Audio backend. |
  511. +----------------------------------+--------------------------------------------------------------------+
  512. | MA_ENABLE_NULL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  513. | | enable the null backend. |
  514. +----------------------------------+--------------------------------------------------------------------+
  515. | MA_NO_DECODING | Disables decoding APIs. |
  516. +----------------------------------+--------------------------------------------------------------------+
  517. | MA_NO_ENCODING | Disables encoding APIs. |
  518. +----------------------------------+--------------------------------------------------------------------+
  519. | MA_NO_WAV | Disables the built-in WAV decoder and encoder. |
  520. +----------------------------------+--------------------------------------------------------------------+
  521. | MA_NO_FLAC | Disables the built-in FLAC decoder. |
  522. +----------------------------------+--------------------------------------------------------------------+
  523. | MA_NO_MP3 | Disables the built-in MP3 decoder. |
  524. +----------------------------------+--------------------------------------------------------------------+
  525. | MA_NO_DEVICE_IO | Disables playback and recording. This will disable `ma_context` |
  526. | | and `ma_device` APIs. This is useful if you only want to use |
  527. | | miniaudio's data conversion and/or decoding APIs. |
  528. +----------------------------------+--------------------------------------------------------------------+
  529. | MA_NO_RESOURCE_MANAGER | Disables the resource manager. When using the engine this will |
  530. | | also disable the following functions: |
  531. | | |
  532. | | ``` |
  533. | | ma_sound_init_from_file() |
  534. | | ma_sound_init_from_file_w() |
  535. | | ma_sound_init_copy() |
  536. | | ma_engine_play_sound_ex() |
  537. | | ma_engine_play_sound() |
  538. | | ``` |
  539. | | |
  540. | | The only way to initialize a `ma_sound` object is to initialize it |
  541. | | from a data source. |
  542. +----------------------------------+--------------------------------------------------------------------+
  543. | MA_NO_NODE_GRAPH | Disables the node graph API. This will also disable the engine API |
  544. | | because it depends on the node graph. |
  545. +----------------------------------+--------------------------------------------------------------------+
  546. | MA_NO_ENGINE | Disables the engine API. |
  547. +----------------------------------+--------------------------------------------------------------------+
  548. | MA_NO_THREADING | Disables the `ma_thread`, `ma_mutex`, `ma_semaphore` and |
  549. | | `ma_event` APIs. This option is useful if you only need to use |
  550. | | miniaudio for data conversion, decoding and/or encoding. Some |
  551. | | families of APIs require threading which means the following |
  552. | | options must also be set: |
  553. | | |
  554. | | ``` |
  555. | | MA_NO_DEVICE_IO |
  556. | | ``` |
  557. +----------------------------------+--------------------------------------------------------------------+
  558. | MA_NO_GENERATION | Disables generation APIs such a `ma_waveform` and `ma_noise`. |
  559. +----------------------------------+--------------------------------------------------------------------+
  560. | MA_NO_SSE2 | Disables SSE2 optimizations. |
  561. +----------------------------------+--------------------------------------------------------------------+
  562. | MA_NO_AVX2 | Disables AVX2 optimizations. |
  563. +----------------------------------+--------------------------------------------------------------------+
  564. | MA_NO_NEON | Disables NEON optimizations. |
  565. +----------------------------------+--------------------------------------------------------------------+
  566. | MA_NO_RUNTIME_LINKING | Disables runtime linking. This is useful for passing Apple's |
  567. | | notarization process. When enabling this, you may need to avoid |
  568. | | using `-std=c89` or `-std=c99` on Linux builds or else you may end |
  569. | | up with compilation errors due to conflicts with `timespec` and |
  570. | | `timeval` data types. |
  571. | | |
  572. | | You may need to enable this if your target platform does not allow |
  573. | | runtime linking via `dlopen()`. |
  574. +----------------------------------+--------------------------------------------------------------------+
  575. | MA_DEBUG_OUTPUT | Enable `printf()` output of debug logs (`MA_LOG_LEVEL_DEBUG`). |
  576. +----------------------------------+--------------------------------------------------------------------+
  577. | MA_COINIT_VALUE | Windows only. The value to pass to internal calls to |
  578. | | `CoInitializeEx()`. Defaults to `COINIT_MULTITHREADED`. |
  579. +----------------------------------+--------------------------------------------------------------------+
  580. | MA_API | Controls how public APIs should be decorated. Default is `extern`. |
  581. +----------------------------------+--------------------------------------------------------------------+
  582. 3. Definitions
  583. ==============
  584. This section defines common terms used throughout miniaudio. Unfortunately there is often ambiguity
  585. in the use of terms throughout the audio space, so this section is intended to clarify how miniaudio
  586. uses each term.
  587. 3.1. Sample
  588. -----------
  589. A sample is a single unit of audio data. If the sample format is f32, then one sample is one 32-bit
  590. floating point number.
  591. 3.2. Frame / PCM Frame
  592. ----------------------
  593. A frame is a group of samples equal to the number of channels. For a stereo stream a frame is 2
  594. samples, a mono frame is 1 sample, a 5.1 surround sound frame is 6 samples, etc. The terms "frame"
  595. and "PCM frame" are the same thing in miniaudio. Note that this is different to a compressed frame.
  596. If ever miniaudio needs to refer to a compressed frame, such as a FLAC frame, it will always
  597. clarify what it's referring to with something like "FLAC frame".
  598. 3.3. Channel
  599. ------------
  600. A stream of monaural audio that is emitted from an individual speaker in a speaker system, or
  601. received from an individual microphone in a microphone system. A stereo stream has two channels (a
  602. left channel, and a right channel), a 5.1 surround sound system has 6 channels, etc. Some audio
  603. systems refer to a channel as a complex audio stream that's mixed with other channels to produce
  604. the final mix - this is completely different to miniaudio's use of the term "channel" and should
  605. not be confused.
  606. 3.4. Sample Rate
  607. ----------------
  608. The sample rate in miniaudio is always expressed in Hz, such as 44100, 48000, etc. It's the number
  609. of PCM frames that are processed per second.
  610. 3.5. Formats
  611. ------------
  612. Throughout miniaudio you will see references to different sample formats:
  613. +---------------+----------------------------------------+---------------------------+
  614. | Symbol | Description | Range |
  615. +---------------+----------------------------------------+---------------------------+
  616. | ma_format_f32 | 32-bit floating point | [-1, 1] |
  617. | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
  618. | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
  619. | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
  620. | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
  621. +---------------+----------------------------------------+---------------------------+
  622. All formats are native-endian.
  623. 4. Data Sources
  624. ===============
  625. The data source abstraction in miniaudio is used for retrieving audio data from some source. A few
  626. examples include `ma_decoder`, `ma_noise` and `ma_waveform`. You will need to be familiar with data
  627. sources in order to make sense of some of the higher level concepts in miniaudio.
  628. The `ma_data_source` API is a generic interface for reading from a data source. Any object that
  629. implements the data source interface can be plugged into any `ma_data_source` function.
  630. To read data from a data source:
  631. ```c
  632. ma_result result;
  633. ma_uint64 framesRead;
  634. result = ma_data_source_read_pcm_frames(pDataSource, pFramesOut, frameCount, &framesRead);
  635. if (result != MA_SUCCESS) {
  636. return result; // Failed to read data from the data source.
  637. }
  638. ```
  639. If you don't need the number of frames that were successfully read you can pass in `NULL` to the
  640. `pFramesRead` parameter. If this returns a value less than the number of frames requested it means
  641. the end of the file has been reached. `MA_AT_END` will be returned only when the number of frames
  642. read is 0.
  643. When calling any data source function, with the exception of `ma_data_source_init()` and
  644. `ma_data_source_uninit()`, you can pass in any object that implements a data source. For example,
  645. you could plug in a decoder like so:
  646. ```c
  647. ma_result result;
  648. ma_uint64 framesRead;
  649. ma_decoder decoder; // <-- This would be initialized with `ma_decoder_init_*()`.
  650. result = ma_data_source_read_pcm_frames(&decoder, pFramesOut, frameCount, &framesRead);
  651. if (result != MA_SUCCESS) {
  652. return result; // Failed to read data from the decoder.
  653. }
  654. ```
  655. If you want to seek forward you can pass in `NULL` to the `pFramesOut` parameter. Alternatively you
  656. can use `ma_data_source_seek_pcm_frames()`.
  657. To seek to a specific PCM frame:
  658. ```c
  659. result = ma_data_source_seek_to_pcm_frame(pDataSource, frameIndex);
  660. if (result != MA_SUCCESS) {
  661. return result; // Failed to seek to PCM frame.
  662. }
  663. ```
  664. You can retrieve the total length of a data source in PCM frames, but note that some data sources
  665. may not have the notion of a length, such as noise and waveforms, and others may just not have a
  666. way of determining the length such as some decoders. To retrieve the length:
  667. ```c
  668. ma_uint64 length;
  669. result = ma_data_source_get_length_in_pcm_frames(pDataSource, &length);
  670. if (result != MA_SUCCESS) {
  671. return result; // Failed to retrieve the length.
  672. }
  673. ```
  674. Care should be taken when retrieving the length of a data source where the underlying decoder is
  675. pulling data from a data stream with an undefined length, such as internet radio or some kind of
  676. broadcast. If you do this, `ma_data_source_get_length_in_pcm_frames()` may never return.
  677. The current position of the cursor in PCM frames can also be retrieved:
  678. ```c
  679. ma_uint64 cursor;
  680. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursor);
  681. if (result != MA_SUCCESS) {
  682. return result; // Failed to retrieve the cursor.
  683. }
  684. ```
  685. You will often need to know the data format that will be returned after reading. This can be
  686. retrieved like so:
  687. ```c
  688. ma_format format;
  689. ma_uint32 channels;
  690. ma_uint32 sampleRate;
  691. ma_channel channelMap[MA_MAX_CHANNELS];
  692. result = ma_data_source_get_data_format(pDataSource, &format, &channels, &sampleRate, channelMap, MA_MAX_CHANNELS);
  693. if (result != MA_SUCCESS) {
  694. return result; // Failed to retrieve data format.
  695. }
  696. ```
  697. If you do not need a specific data format property, just pass in NULL to the respective parameter.
  698. There may be cases where you want to implement something like a sound bank where you only want to
  699. read data within a certain range of the underlying data. To do this you can use a range:
  700. ```c
  701. result = ma_data_source_set_range_in_pcm_frames(pDataSource, rangeBegInFrames, rangeEndInFrames);
  702. if (result != MA_SUCCESS) {
  703. return result; // Failed to set the range.
  704. }
  705. ```
  706. This is useful if you have a sound bank where many sounds are stored in the same file and you want
  707. the data source to only play one of those sub-sounds. Note that once the range is set, everything
  708. that takes a position, such as cursors and loop points, should always be relatvie to the start of
  709. the range. When the range is set, any previously defined loop point will be reset.
  710. Custom loop points can also be used with data sources. By default, data sources will loop after
  711. they reach the end of the data source, but if you need to loop at a specific location, you can do
  712. the following:
  713. ```c
  714. result = ma_data_set_loop_point_in_pcm_frames(pDataSource, loopBegInFrames, loopEndInFrames);
  715. if (result != MA_SUCCESS) {
  716. return result; // Failed to set the loop point.
  717. }
  718. ```
  719. The loop point is relative to the current range.
  720. It's sometimes useful to chain data sources together so that a seamless transition can be achieved.
  721. To do this, you can use chaining:
  722. ```c
  723. ma_decoder decoder1;
  724. ma_decoder decoder2;
  725. // ... initialize decoders with ma_decoder_init_*() ...
  726. result = ma_data_source_set_next(&decoder1, &decoder2);
  727. if (result != MA_SUCCESS) {
  728. return result; // Failed to set the next data source.
  729. }
  730. result = ma_data_source_read_pcm_frames(&decoder1, pFramesOut, frameCount, pFramesRead);
  731. if (result != MA_SUCCESS) {
  732. return result; // Failed to read from the decoder.
  733. }
  734. ```
  735. In the example above we're using decoders. When reading from a chain, you always want to read from
  736. the top level data source in the chain. In the example above, `decoder1` is the top level data
  737. source in the chain. When `decoder1` reaches the end, `decoder2` will start seamlessly without any
  738. gaps.
  739. Note that when looping is enabled, only the current data source will be looped. You can loop the
  740. entire chain by linking in a loop like so:
  741. ```c
  742. ma_data_source_set_next(&decoder1, &decoder2); // decoder1 -> decoder2
  743. ma_data_source_set_next(&decoder2, &decoder1); // decoder2 -> decoder1 (loop back to the start).
  744. ```
  745. Note that setting up chaining is not thread safe, so care needs to be taken if you're dynamically
  746. changing links while the audio thread is in the middle of reading.
  747. Do not use `ma_decoder_seek_to_pcm_frame()` as a means to reuse a data source to play multiple
  748. instances of the same sound simultaneously. This can be extremely inefficient depending on the type
  749. of data source and can result in glitching due to subtle changes to the state of internal filters.
  750. Instead, initialize multiple data sources for each instance.
  751. 4.1. Custom Data Sources
  752. ------------------------
  753. You can implement a custom data source by implementing the functions in `ma_data_source_vtable`.
  754. Your custom object must have `ma_data_source_base` as it's first member:
  755. ```c
  756. struct my_data_source
  757. {
  758. ma_data_source_base base;
  759. ...
  760. };
  761. ```
  762. In your initialization routine, you need to call `ma_data_source_init()` in order to set up the
  763. base object (`ma_data_source_base`):
  764. ```c
  765. static ma_result my_data_source_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  766. {
  767. // Read data here. Output in the same format returned by my_data_source_get_data_format().
  768. }
  769. static ma_result my_data_source_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  770. {
  771. // Seek to a specific PCM frame here. Return MA_NOT_IMPLEMENTED if seeking is not supported.
  772. }
  773. static ma_result my_data_source_get_data_format(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap)
  774. {
  775. // Return the format of the data here.
  776. }
  777. static ma_result my_data_source_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  778. {
  779. // Retrieve the current position of the cursor here. Return MA_NOT_IMPLEMENTED and set *pCursor to 0 if there is no notion of a cursor.
  780. }
  781. static ma_result my_data_source_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  782. {
  783. // Retrieve the length in PCM frames here. Return MA_NOT_IMPLEMENTED and set *pLength to 0 if there is no notion of a length or if the length is unknown.
  784. }
  785. static ma_data_source_vtable g_my_data_source_vtable =
  786. {
  787. my_data_source_read,
  788. my_data_source_seek,
  789. my_data_source_get_data_format,
  790. my_data_source_get_cursor,
  791. my_data_source_get_length
  792. };
  793. ma_result my_data_source_init(my_data_source* pMyDataSource)
  794. {
  795. ma_result result;
  796. ma_data_source_config baseConfig;
  797. baseConfig = ma_data_source_config_init();
  798. baseConfig.vtable = &g_my_data_source_vtable;
  799. result = ma_data_source_init(&baseConfig, &pMyDataSource->base);
  800. if (result != MA_SUCCESS) {
  801. return result;
  802. }
  803. // ... do the initialization of your custom data source here ...
  804. return MA_SUCCESS;
  805. }
  806. void my_data_source_uninit(my_data_source* pMyDataSource)
  807. {
  808. // ... do the uninitialization of your custom data source here ...
  809. // You must uninitialize the base data source.
  810. ma_data_source_uninit(&pMyDataSource->base);
  811. }
  812. ```
  813. Note that `ma_data_source_init()` and `ma_data_source_uninit()` are never called directly outside
  814. of the custom data source. It's up to the custom data source itself to call these within their own
  815. init/uninit functions.
  816. 5. Engine
  817. =========
  818. The `ma_engine` API is a high level API for managing and mixing sounds and effect processing. The
  819. `ma_engine` object encapsulates a resource manager and a node graph, both of which will be
  820. explained in more detail later.
  821. Sounds are called `ma_sound` and are created from an engine. Sounds can be associated with a mixing
  822. group called `ma_sound_group` which are also created from the engine. Both `ma_sound` and
  823. `ma_sound_group` objects are nodes within the engine's node graph.
  824. When the engine is initialized, it will normally create a device internally. If you would rather
  825. manage the device yourself, you can do so and just pass a pointer to it via the engine config when
  826. you initialize the engine. You can also just use the engine without a device, which again can be
  827. configured via the engine config.
  828. The most basic way to initialize the engine is with a default config, like so:
  829. ```c
  830. ma_result result;
  831. ma_engine engine;
  832. result = ma_engine_init(NULL, &engine);
  833. if (result != MA_SUCCESS) {
  834. return result; // Failed to initialize the engine.
  835. }
  836. ```
  837. This will result in the engine initializing a playback device using the operating system's default
  838. device. This will be sufficient for many use cases, but if you need more flexibility you'll want to
  839. configure the engine with an engine config:
  840. ```c
  841. ma_result result;
  842. ma_engine engine;
  843. ma_engine_config engineConfig;
  844. engineConfig = ma_engine_config_init();
  845. engineConfig.pDevice = &myDevice;
  846. result = ma_engine_init(&engineConfig, &engine);
  847. if (result != MA_SUCCESS) {
  848. return result; // Failed to initialize the engine.
  849. }
  850. ```
  851. In the example above we're passing in a pre-initialized device. Since the caller is the one in
  852. control of the device's data callback, it's their responsibility to manually call
  853. `ma_engine_read_pcm_frames()` from inside their data callback:
  854. ```c
  855. void playback_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  856. {
  857. ma_engine_read_pcm_frames(&g_Engine, pOutput, frameCount, NULL);
  858. }
  859. ```
  860. You can also use the engine independent of a device entirely:
  861. ```c
  862. ma_result result;
  863. ma_engine engine;
  864. ma_engine_config engineConfig;
  865. engineConfig = ma_engine_config_init();
  866. engineConfig.noDevice = MA_TRUE;
  867. engineConfig.channels = 2; // Must be set when not using a device.
  868. engineConfig.sampleRate = 48000; // Must be set when not using a device.
  869. result = ma_engine_init(&engineConfig, &engine);
  870. if (result != MA_SUCCESS) {
  871. return result; // Failed to initialize the engine.
  872. }
  873. ```
  874. Note that when you're not using a device, you must set the channel count and sample rate in the
  875. config or else miniaudio won't know what to use (miniaudio will use the device to determine this
  876. normally). When not using a device, you need to use `ma_engine_read_pcm_frames()` to process audio
  877. data from the engine. This kind of setup is useful if you want to do something like offline
  878. processing or want to use a different audio system for playback such as SDL.
  879. When a sound is loaded it goes through a resource manager. By default the engine will initialize a
  880. resource manager internally, but you can also specify a pre-initialized resource manager:
  881. ```c
  882. ma_result result;
  883. ma_engine engine1;
  884. ma_engine engine2;
  885. ma_engine_config engineConfig;
  886. engineConfig = ma_engine_config_init();
  887. engineConfig.pResourceManager = &myResourceManager;
  888. ma_engine_init(&engineConfig, &engine1);
  889. ma_engine_init(&engineConfig, &engine2);
  890. ```
  891. In this example we are initializing two engines, both of which are sharing the same resource
  892. manager. This is especially useful for saving memory when loading the same file across multiple
  893. engines. If you were not to use a shared resource manager, each engine instance would use their own
  894. which would result in any sounds that are used between both engine's being loaded twice. By using
  895. a shared resource manager, it would only be loaded once. Using multiple engine's is useful when you
  896. need to output to multiple playback devices, such as in a local multiplayer game where each player
  897. is using their own set of headphones.
  898. By default an engine will be in a started state. To make it so the engine is not automatically
  899. started you can configure it as such:
  900. ```c
  901. engineConfig.noAutoStart = MA_TRUE;
  902. // The engine will need to be started manually.
  903. ma_engine_start(&engine);
  904. // Later on the engine can be stopped with ma_engine_stop().
  905. ma_engine_stop(&engine);
  906. ```
  907. The concept of starting or stopping an engine is only relevant when using the engine with a
  908. device. Attempting to start or stop an engine that is not associated with a device will result in
  909. `MA_INVALID_OPERATION`.
  910. The master volume of the engine can be controlled with `ma_engine_set_volume()` which takes a
  911. linear scale, with 0 resulting in silence and anything above 1 resulting in amplification. If you
  912. prefer decibel based volume control, use `ma_volume_db_to_linear()` to convert from dB to linear.
  913. When a sound is spatialized, it is done so relative to a listener. An engine can be configured to
  914. have multiple listeners which can be configured via the config:
  915. ```c
  916. engineConfig.listenerCount = 2;
  917. ```
  918. The maximum number of listeners is restricted to `MA_ENGINE_MAX_LISTENERS`. By default, when a
  919. sound is spatialized, it will be done so relative to the closest listener. You can also pin a sound
  920. to a specific listener which will be explained later. Listener's have a position, direction, cone,
  921. and velocity (for doppler effect). A listener is referenced by an index, the meaning of which is up
  922. to the caller (the index is 0 based and cannot go beyond the listener count, minus 1). The
  923. position, direction and velocity are all specified in absolute terms:
  924. ```c
  925. ma_engine_listener_set_position(&engine, listenerIndex, worldPosX, worldPosY, worldPosZ);
  926. ```
  927. The direction of the listener represents it's forward vector. The listener's up vector can also be
  928. specified and defaults to +1 on the Y axis.
  929. ```c
  930. ma_engine_listener_set_direction(&engine, listenerIndex, forwardX, forwardY, forwardZ);
  931. ma_engine_listener_set_world_up(&engine, listenerIndex, 0, 1, 0);
  932. ```
  933. The engine supports directional attenuation. The listener can have a cone the controls how sound is
  934. attenuated based on the listener's direction. When a sound is between the inner and outer cones, it
  935. will be attenuated between 1 and the cone's outer gain:
  936. ```c
  937. ma_engine_listener_set_cone(&engine, listenerIndex, innerAngleInRadians, outerAngleInRadians, outerGain);
  938. ```
  939. When a sound is inside the inner code, no directional attenuation is applied. When the sound is
  940. outside of the outer cone, the attenuation will be set to `outerGain` in the example above. When
  941. the sound is in between the inner and outer cones, the attenuation will be interpolated between 1
  942. and the outer gain.
  943. The engine's coordinate system follows the OpenGL coordinate system where positive X points right,
  944. positive Y points up and negative Z points forward.
  945. The simplest and least flexible way to play a sound is like so:
  946. ```c
  947. ma_engine_play_sound(&engine, "my_sound.wav", pGroup);
  948. ```
  949. This is a "fire and forget" style of function. The engine will manage the `ma_sound` object
  950. internally. When the sound finishes playing, it'll be put up for recycling. For more flexibility
  951. you'll want to initialize a sound object:
  952. ```c
  953. ma_sound sound;
  954. result = ma_sound_init_from_file(&engine, "my_sound.wav", flags, pGroup, NULL, &sound);
  955. if (result != MA_SUCCESS) {
  956. return result; // Failed to load sound.
  957. }
  958. ```
  959. Sounds need to be uninitialized with `ma_sound_uninit()`.
  960. The example above loads a sound from a file. If the resource manager has been disabled you will not
  961. be able to use this function and instead you'll need to initialize a sound directly from a data
  962. source:
  963. ```c
  964. ma_sound sound;
  965. result = ma_sound_init_from_data_source(&engine, &dataSource, flags, pGroup, &sound);
  966. if (result != MA_SUCCESS) {
  967. return result;
  968. }
  969. ```
  970. Each `ma_sound` object represents a single instance of the sound. If you want to play the same
  971. sound multiple times at the same time, you need to initialize a separate `ma_sound` object.
  972. For the most flexibility when initializing sounds, use `ma_sound_init_ex()`. This uses miniaudio's
  973. standard config/init pattern:
  974. ```c
  975. ma_sound sound;
  976. ma_sound_config soundConfig;
  977. soundConfig = ma_sound_config_init();
  978. soundConfig.pFilePath = NULL; // Set this to load from a file path.
  979. soundConfig.pDataSource = NULL; // Set this to initialize from an existing data source.
  980. soundConfig.pInitialAttachment = &someNodeInTheNodeGraph;
  981. soundConfig.initialAttachmentInputBusIndex = 0;
  982. soundConfig.channelsIn = 1;
  983. soundConfig.channelsOut = 0; // Set to 0 to use the engine's native channel count.
  984. result = ma_sound_init_ex(&soundConfig, &sound);
  985. if (result != MA_SUCCESS) {
  986. return result;
  987. }
  988. ```
  989. In the example above, the sound is being initialized without a file nor a data source. This is
  990. valid, in which case the sound acts as a node in the middle of the node graph. This means you can
  991. connect other sounds to this sound and allow it to act like a sound group. Indeed, this is exactly
  992. what a `ma_sound_group` is.
  993. When loading a sound, you specify a set of flags that control how the sound is loaded and what
  994. features are enabled for that sound. When no flags are set, the sound will be fully loaded into
  995. memory in exactly the same format as how it's stored on the file system. The resource manager will
  996. allocate a block of memory and then load the file directly into it. When reading audio data, it
  997. will be decoded dynamically on the fly. In order to save processing time on the audio thread, it
  998. might be beneficial to pre-decode the sound. You can do this with the `MA_SOUND_FLAG_DECODE` flag:
  999. ```c
  1000. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE, pGroup, NULL, &sound);
  1001. ```
  1002. By default, sounds will be loaded synchronously, meaning `ma_sound_init_*()` will not return until
  1003. the sound has been fully loaded. If this is prohibitive you can instead load sounds asynchronously
  1004. by specifying the `MA_SOUND_FLAG_ASYNC` flag:
  1005. ```c
  1006. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, NULL, &sound);
  1007. ```
  1008. This will result in `ma_sound_init_*()` returning quickly, but the sound won't yet have been fully
  1009. loaded. When you start the sound, it won't output anything until some sound is available. The sound
  1010. will start outputting audio before the sound has been fully decoded when the `MA_SOUND_FLAG_DECODE`
  1011. is specified.
  1012. If you need to wait for an asynchronously loaded sound to be fully loaded, you can use a fence. A
  1013. fence in miniaudio is a simple synchronization mechanism which simply blocks until it's internal
  1014. counter hit's zero. You can specify a fence like so:
  1015. ```c
  1016. ma_result result;
  1017. ma_fence fence;
  1018. ma_sound sounds[4];
  1019. result = ma_fence_init(&fence);
  1020. if (result != MA_SUCCESS) {
  1021. return result;
  1022. }
  1023. // Load some sounds asynchronously.
  1024. for (int iSound = 0; iSound < 4; iSound += 1) {
  1025. ma_sound_init_from_file(&engine, mySoundFilesPaths[iSound], MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, &fence, &sounds[iSound]);
  1026. }
  1027. // ... do some other stuff here in the mean time ...
  1028. // Wait for all sounds to finish loading.
  1029. ma_fence_wait(&fence);
  1030. ```
  1031. If loading the entire sound into memory is prohibitive, you can also configure the engine to stream
  1032. the audio data:
  1033. ```c
  1034. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_STREAM, pGroup, NULL, &sound);
  1035. ```
  1036. When streaming sounds, 2 seconds worth of audio data is stored in memory. Although it should work
  1037. fine, it's inefficient to use streaming for short sounds. Streaming is useful for things like music
  1038. tracks in games.
  1039. When loading a sound from a file path, the engine will reference count the file to prevent it from
  1040. being loaded if it's already in memory. When you uninitialize a sound, the reference count will be
  1041. decremented, and if it hits zero, the sound will be unloaded from memory. This reference counting
  1042. system is not used for streams. The engine will use a 64-bit hash of the file name when comparing
  1043. file paths which means there's a small chance you might encounter a name collision. If this is an
  1044. issue, you'll need to use a different name for one of the colliding file paths, or just not load
  1045. from files and instead load from a data source.
  1046. You can use `ma_sound_init_copy()` to initialize a copy of another sound. Note, however, that this
  1047. only works for sounds that were initialized with `ma_sound_init_from_file()` and without the
  1048. `MA_SOUND_FLAG_STREAM` flag.
  1049. When you initialize a sound, if you specify a sound group the sound will be attached to that group
  1050. automatically. If you set it to NULL, it will be automatically attached to the engine's endpoint.
  1051. If you would instead rather leave the sound unattached by default, you can can specify the
  1052. `MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT` flag. This is useful if you want to set up a complex node
  1053. graph.
  1054. Sounds are not started by default. To start a sound, use `ma_sound_start()`. Stop a sound with
  1055. `ma_sound_stop()`.
  1056. Sounds can have their volume controlled with `ma_sound_set_volume()` in the same way as the
  1057. engine's master volume.
  1058. Sounds support stereo panning and pitching. Set the pan with `ma_sound_set_pan()`. Setting the pan
  1059. to 0 will result in an unpanned sound. Setting it to -1 will shift everything to the left, whereas
  1060. +1 will shift it to the right. The pitch can be controlled with `ma_sound_set_pitch()`. A larger
  1061. value will result in a higher pitch. The pitch must be greater than 0.
  1062. The engine supports 3D spatialization of sounds. By default sounds will have spatialization
  1063. enabled, but if a sound does not need to be spatialized it's best to disable it. There are two ways
  1064. to disable spatialization of a sound:
  1065. ```c
  1066. // Disable spatialization at initialization time via a flag:
  1067. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_NO_SPATIALIZATION, NULL, NULL, &sound);
  1068. // Dynamically disable or enable spatialization post-initialization:
  1069. ma_sound_set_spatialization_enabled(&sound, isSpatializationEnabled);
  1070. ```
  1071. By default sounds will be spatialized based on the closest listener. If a sound should always be
  1072. spatialized relative to a specific listener it can be pinned to one:
  1073. ```c
  1074. ma_sound_set_pinned_listener_index(&sound, listenerIndex);
  1075. ```
  1076. Like listeners, sounds have a position. By default, the position of a sound is in absolute space,
  1077. but it can be changed to be relative to a listener:
  1078. ```c
  1079. ma_sound_set_positioning(&sound, ma_positioning_relative);
  1080. ```
  1081. Note that relative positioning of a sound only makes sense if there is either only one listener, or
  1082. the sound is pinned to a specific listener. To set the position of a sound:
  1083. ```c
  1084. ma_sound_set_position(&sound, posX, posY, posZ);
  1085. ```
  1086. The direction works the same way as a listener and represents the sound's forward direction:
  1087. ```c
  1088. ma_sound_set_direction(&sound, forwardX, forwardY, forwardZ);
  1089. ```
  1090. Sound's also have a cone for controlling directional attenuation. This works exactly the same as
  1091. listeners:
  1092. ```c
  1093. ma_sound_set_cone(&sound, innerAngleInRadians, outerAngleInRadians, outerGain);
  1094. ```
  1095. The velocity of a sound is used for doppler effect and can be set as such:
  1096. ```c
  1097. ma_sound_set_velocity(&sound, velocityX, velocityY, velocityZ);
  1098. ```
  1099. The engine supports different attenuation models which can be configured on a per-sound basis. By
  1100. default the attenuation model is set to `ma_attenuation_model_inverse` which is the equivalent to
  1101. OpenAL's `AL_INVERSE_DISTANCE_CLAMPED`. Configure the attenuation model like so:
  1102. ```c
  1103. ma_sound_set_attenuation_model(&sound, ma_attenuation_model_inverse);
  1104. ```
  1105. The supported attenuation models include the following:
  1106. +----------------------------------+----------------------------------------------+
  1107. | ma_attenuation_model_none | No distance attenuation. |
  1108. +----------------------------------+----------------------------------------------+
  1109. | ma_attenuation_model_inverse | Equivalent to `AL_INVERSE_DISTANCE_CLAMPED`. |
  1110. +----------------------------------+----------------------------------------------+
  1111. | ma_attenuation_model_linear | Linear attenuation. |
  1112. +----------------------------------+----------------------------------------------+
  1113. | ma_attenuation_model_exponential | Exponential attenuation. |
  1114. +----------------------------------+----------------------------------------------+
  1115. To control how quickly a sound rolls off as it moves away from the listener, you need to configure
  1116. the rolloff:
  1117. ```c
  1118. ma_sound_set_rolloff(&sound, rolloff);
  1119. ```
  1120. You can control the minimum and maximum gain to apply from spatialization:
  1121. ```c
  1122. ma_sound_set_min_gain(&sound, minGain);
  1123. ma_sound_set_max_gain(&sound, maxGain);
  1124. ```
  1125. Likewise, in the calculation of attenuation, you can control the minimum and maximum distances for
  1126. the attenuation calculation. This is useful if you want to ensure sounds don't drop below a certain
  1127. volume after the listener moves further away and to have sounds play a maximum volume when the
  1128. listener is within a certain distance:
  1129. ```c
  1130. ma_sound_set_min_distance(&sound, minDistance);
  1131. ma_sound_set_max_distance(&sound, maxDistance);
  1132. ```
  1133. The engine's spatialization system supports doppler effect. The doppler factor can be configure on
  1134. a per-sound basis like so:
  1135. ```c
  1136. ma_sound_set_doppler_factor(&sound, dopplerFactor);
  1137. ```
  1138. You can fade sounds in and out with `ma_sound_set_fade_in_pcm_frames()` and
  1139. `ma_sound_set_fade_in_milliseconds()`. Set the volume to -1 to use the current volume as the
  1140. starting volume:
  1141. ```c
  1142. // Fade in over 1 second.
  1143. ma_sound_set_fade_in_milliseconds(&sound, 0, 1, 1000);
  1144. // ... sometime later ...
  1145. // Fade out over 1 second, starting from the current volume.
  1146. ma_sound_set_fade_in_milliseconds(&sound, -1, 0, 1000);
  1147. ```
  1148. By default sounds will start immediately, but sometimes for timing and synchronization purposes it
  1149. can be useful to schedule a sound to start or stop:
  1150. ```c
  1151. // Start the sound in 1 second from now.
  1152. ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 1));
  1153. // Stop the sound in 2 seconds from now.
  1154. ma_sound_set_stop_time_in_pcm_frames(&sound, ma_engine_get_time_in_pcm_frames(&engine) + (ma_engine_get_sample_rate(&engine) * 2));
  1155. ```
  1156. Note that scheduling a start time still requires an explicit call to `ma_sound_start()` before
  1157. anything will play.
  1158. The time is specified in global time which is controlled by the engine. You can get the engine's
  1159. current time with `ma_engine_get_time_in_pcm_frames()`. The engine's global time is incremented
  1160. automatically as audio data is read, but it can be reset with `ma_engine_set_time_in_pcm_frames()`
  1161. in case it needs to be resynchronized for some reason.
  1162. To determine whether or not a sound is currently playing, use `ma_sound_is_playing()`. This will
  1163. take the scheduled start and stop times into account.
  1164. Whether or not a sound should loop can be controlled with `ma_sound_set_looping()`. Sounds will not
  1165. be looping by default. Use `ma_sound_is_looping()` to determine whether or not a sound is looping.
  1166. Use `ma_sound_at_end()` to determine whether or not a sound is currently at the end. For a looping
  1167. sound this should never return true. Alternatively, you can configure a callback that will be fired
  1168. when the sound reaches the end. Note that the callback is fired from the audio thread which means
  1169. you cannot be uninitializing sound from the callback. To set the callback you can use
  1170. `ma_sound_set_end_callback()`. Alternatively, if you're using `ma_sound_init_ex()`, you can pass it
  1171. into the config like so:
  1172. ```c
  1173. soundConfig.endCallback = my_end_callback;
  1174. soundConfig.pEndCallbackUserData = pMyEndCallbackUserData;
  1175. ```
  1176. The end callback is declared like so:
  1177. ```c
  1178. void my_end_callback(void* pUserData, ma_sound* pSound)
  1179. {
  1180. ...
  1181. }
  1182. ```
  1183. Internally a sound wraps around a data source. Some APIs exist to control the underlying data
  1184. source, mainly for convenience:
  1185. ```c
  1186. ma_sound_seek_to_pcm_frame(&sound, frameIndex);
  1187. ma_sound_get_data_format(&sound, &format, &channels, &sampleRate, pChannelMap, channelMapCapacity);
  1188. ma_sound_get_cursor_in_pcm_frames(&sound, &cursor);
  1189. ma_sound_get_length_in_pcm_frames(&sound, &length);
  1190. ```
  1191. Sound groups have the same API as sounds, only they are called `ma_sound_group`, and since they do
  1192. not have any notion of a data source, anything relating to a data source is unavailable.
  1193. Internally, sound data is loaded via the `ma_decoder` API which means by default it only supports
  1194. file formats that have built-in support in miniaudio. You can extend this to support any kind of
  1195. file format through the use of custom decoders. To do this you'll need to use a self-managed
  1196. resource manager and configure it appropriately. See the "Resource Management" section below for
  1197. details on how to set this up.
  1198. 6. Resource Management
  1199. ======================
  1200. Many programs will want to manage sound resources for things such as reference counting and
  1201. streaming. This is supported by miniaudio via the `ma_resource_manager` API.
  1202. The resource manager is mainly responsible for the following:
  1203. * Loading of sound files into memory with reference counting.
  1204. * Streaming of sound data.
  1205. When loading a sound file, the resource manager will give you back a `ma_data_source` compatible
  1206. object called `ma_resource_manager_data_source`. This object can be passed into any
  1207. `ma_data_source` API which is how you can read and seek audio data. When loading a sound file, you
  1208. specify whether or not you want the sound to be fully loaded into memory (and optionally
  1209. pre-decoded) or streamed. When loading into memory, you can also specify whether or not you want
  1210. the data to be loaded asynchronously.
  1211. The example below is how you can initialize a resource manager using it's default configuration:
  1212. ```c
  1213. ma_resource_manager_config config;
  1214. ma_resource_manager resourceManager;
  1215. config = ma_resource_manager_config_init();
  1216. result = ma_resource_manager_init(&config, &resourceManager);
  1217. if (result != MA_SUCCESS) {
  1218. ma_device_uninit(&device);
  1219. printf("Failed to initialize the resource manager.");
  1220. return -1;
  1221. }
  1222. ```
  1223. You can configure the format, channels and sample rate of the decoded audio data. By default it
  1224. will use the file's native data format, but you can configure it to use a consistent format. This
  1225. is useful for offloading the cost of data conversion to load time rather than dynamically
  1226. converting at mixing time. To do this, you configure the decoded format, channels and sample rate
  1227. like the code below:
  1228. ```c
  1229. config = ma_resource_manager_config_init();
  1230. config.decodedFormat = device.playback.format;
  1231. config.decodedChannels = device.playback.channels;
  1232. config.decodedSampleRate = device.sampleRate;
  1233. ```
  1234. In the code above, the resource manager will be configured so that any decoded audio data will be
  1235. pre-converted at load time to the device's native data format. If instead you used defaults and
  1236. the data format of the file did not match the device's data format, you would need to convert the
  1237. data at mixing time which may be prohibitive in high-performance and large scale scenarios like
  1238. games.
  1239. Internally the resource manager uses the `ma_decoder` API to load sounds. This means by default it
  1240. only supports decoders that are built into miniaudio. It's possible to support additional encoding
  1241. formats through the use of custom decoders. To do so, pass in your `ma_decoding_backend_vtable`
  1242. vtables into the resource manager config:
  1243. ```c
  1244. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  1245. {
  1246. &g_ma_decoding_backend_vtable_libvorbis,
  1247. &g_ma_decoding_backend_vtable_libopus
  1248. };
  1249. ...
  1250. resourceManagerConfig.ppCustomDecodingBackendVTables = pCustomBackendVTables;
  1251. resourceManagerConfig.customDecodingBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  1252. resourceManagerConfig.pCustomDecodingBackendUserData = NULL;
  1253. ```
  1254. This system can allow you to support any kind of file format. See the "Decoding" section for
  1255. details on how to implement custom decoders. The miniaudio repository includes examples for Opus
  1256. via libopus and libopusfile and Vorbis via libvorbis and libvorbisfile.
  1257. Asynchronicity is achieved via a job system. When an operation needs to be performed, such as the
  1258. decoding of a page, a job will be posted to a queue which will then be processed by a job thread.
  1259. By default there will be only one job thread running, but this can be configured, like so:
  1260. ```c
  1261. config = ma_resource_manager_config_init();
  1262. config.jobThreadCount = MY_JOB_THREAD_COUNT;
  1263. ```
  1264. By default job threads are managed internally by the resource manager, however you can also self
  1265. manage your job threads if, for example, you want to integrate the job processing into your
  1266. existing job infrastructure, or if you simply don't like the way the resource manager does it. To
  1267. do this, just set the job thread count to 0 and process jobs manually. To process jobs, you first
  1268. need to retrieve a job using `ma_resource_manager_next_job()` and then process it using
  1269. `ma_job_process()`:
  1270. ```c
  1271. config = ma_resource_manager_config_init();
  1272. config.jobThreadCount = 0; // Don't manage any job threads internally.
  1273. config.flags = MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING; // Optional. Makes `ma_resource_manager_next_job()` non-blocking.
  1274. // ... Initialize your custom job threads ...
  1275. void my_custom_job_thread(...)
  1276. {
  1277. for (;;) {
  1278. ma_job job;
  1279. ma_result result = ma_resource_manager_next_job(pMyResourceManager, &job);
  1280. if (result != MA_SUCCESS) {
  1281. if (result == MA_NO_DATA_AVAILABLE) {
  1282. // No jobs are available. Keep going. Will only get this if the resource manager was initialized
  1283. // with MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING.
  1284. continue;
  1285. } else if (result == MA_CANCELLED) {
  1286. // MA_JOB_TYPE_QUIT was posted. Exit.
  1287. break;
  1288. } else {
  1289. // Some other error occurred.
  1290. break;
  1291. }
  1292. }
  1293. ma_job_process(&job);
  1294. }
  1295. }
  1296. ```
  1297. In the example above, the `MA_JOB_TYPE_QUIT` event is the used as the termination
  1298. indicator, but you can use whatever you would like to terminate the thread. The call to
  1299. `ma_resource_manager_next_job()` is blocking by default, but can be configured to be non-blocking
  1300. by initializing the resource manager with the `MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING` configuration
  1301. flag. Note that the `MA_JOB_TYPE_QUIT` will never be removed from the job queue. This
  1302. is to give every thread the opportunity to catch the event and terminate naturally.
  1303. When loading a file, it's sometimes convenient to be able to customize how files are opened and
  1304. read instead of using standard `fopen()`, `fclose()`, etc. which is what miniaudio will use by
  1305. default. This can be done by setting `pVFS` member of the resource manager's config:
  1306. ```c
  1307. // Initialize your custom VFS object. See documentation for VFS for information on how to do this.
  1308. my_custom_vfs vfs = my_custom_vfs_init();
  1309. config = ma_resource_manager_config_init();
  1310. config.pVFS = &vfs;
  1311. ```
  1312. This is particularly useful in programs like games where you want to read straight from an archive
  1313. rather than the normal file system. If you do not specify a custom VFS, the resource manager will
  1314. use the operating system's normal file operations.
  1315. To load a sound file and create a data source, call `ma_resource_manager_data_source_init()`. When
  1316. loading a sound you need to specify the file path and options for how the sounds should be loaded.
  1317. By default a sound will be loaded synchronously. The returned data source is owned by the caller
  1318. which means the caller is responsible for the allocation and freeing of the data source. Below is
  1319. an example for initializing a data source:
  1320. ```c
  1321. ma_resource_manager_data_source dataSource;
  1322. ma_result result = ma_resource_manager_data_source_init(pResourceManager, pFilePath, flags, &dataSource);
  1323. if (result != MA_SUCCESS) {
  1324. // Error.
  1325. }
  1326. // ...
  1327. // A ma_resource_manager_data_source object is compatible with the `ma_data_source` API. To read data, just call
  1328. // the `ma_data_source_read_pcm_frames()` like you would with any normal data source.
  1329. result = ma_data_source_read_pcm_frames(&dataSource, pDecodedData, frameCount, &framesRead);
  1330. if (result != MA_SUCCESS) {
  1331. // Failed to read PCM frames.
  1332. }
  1333. // ...
  1334. ma_resource_manager_data_source_uninit(&dataSource);
  1335. ```
  1336. The `flags` parameter specifies how you want to perform loading of the sound file. It can be a
  1337. combination of the following flags:
  1338. ```
  1339. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM
  1340. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE
  1341. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC
  1342. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT
  1343. ```
  1344. When no flags are specified (set to 0), the sound will be fully loaded into memory, but not
  1345. decoded, meaning the raw file data will be stored in memory, and then dynamically decoded when
  1346. `ma_data_source_read_pcm_frames()` is called. To instead decode the audio data before storing it in
  1347. memory, use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` flag. By default, the sound file will
  1348. be loaded synchronously, meaning `ma_resource_manager_data_source_init()` will only return after
  1349. the entire file has been loaded. This is good for simplicity, but can be prohibitively slow. You
  1350. can instead load the sound asynchronously using the `MA_RESOURCE_MANAGER_DATA_SOURCE_ASYNC` flag.
  1351. This will result in `ma_resource_manager_data_source_init()` returning quickly, but no data will be
  1352. returned by `ma_data_source_read_pcm_frames()` until some data is available. When no data is
  1353. available because the asynchronous decoding hasn't caught up, `MA_BUSY` will be returned by
  1354. `ma_data_source_read_pcm_frames()`.
  1355. For large sounds, it's often prohibitive to store the entire file in memory. To mitigate this, you
  1356. can instead stream audio data which you can do by specifying the
  1357. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. When streaming, data will be decoded in 1
  1358. second pages. When a new page needs to be decoded, a job will be posted to the job queue and then
  1359. subsequently processed in a job thread.
  1360. For in-memory sounds, reference counting is used to ensure the data is loaded only once. This means
  1361. multiple calls to `ma_resource_manager_data_source_init()` with the same file path will result in
  1362. the file data only being loaded once. Each call to `ma_resource_manager_data_source_init()` must be
  1363. matched up with a call to `ma_resource_manager_data_source_uninit()`. Sometimes it can be useful
  1364. for a program to register self-managed raw audio data and associate it with a file path. Use the
  1365. `ma_resource_manager_register_*()` and `ma_resource_manager_unregister_*()` APIs to do this.
  1366. `ma_resource_manager_register_decoded_data()` is used to associate a pointer to raw, self-managed
  1367. decoded audio data in the specified data format with the specified name. Likewise,
  1368. `ma_resource_manager_register_encoded_data()` is used to associate a pointer to raw self-managed
  1369. encoded audio data (the raw file data) with the specified name. Note that these names need not be
  1370. actual file paths. When `ma_resource_manager_data_source_init()` is called (without the
  1371. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag), the resource manager will look for these
  1372. explicitly registered data buffers and, if found, will use it as the backing data for the data
  1373. source. Note that the resource manager does *not* make a copy of this data so it is up to the
  1374. caller to ensure the pointer stays valid for it's lifetime. Use
  1375. `ma_resource_manager_unregister_data()` to unregister the self-managed data. You can also use
  1376. `ma_resource_manager_register_file()` and `ma_resource_manager_unregister_file()` to register and
  1377. unregister a file. It does not make sense to use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM`
  1378. flag with a self-managed data pointer.
  1379. 6.1. Asynchronous Loading and Synchronization
  1380. ---------------------------------------------
  1381. When loading asynchronously, it can be useful to poll whether or not loading has finished. Use
  1382. `ma_resource_manager_data_source_result()` to determine this. For in-memory sounds, this will
  1383. return `MA_SUCCESS` when the file has been *entirely* decoded. If the sound is still being decoded,
  1384. `MA_BUSY` will be returned. Otherwise, some other error code will be returned if the sound failed
  1385. to load. For streaming data sources, `MA_SUCCESS` will be returned when the first page has been
  1386. decoded and the sound is ready to be played. If the first page is still being decoded, `MA_BUSY`
  1387. will be returned. Otherwise, some other error code will be returned if the sound failed to load.
  1388. In addition to polling, you can also use a simple synchronization object called a "fence" to wait
  1389. for asynchronously loaded sounds to finish. This is called `ma_fence`. The advantage to using a
  1390. fence is that it can be used to wait for a group of sounds to finish loading rather than waiting
  1391. for sounds on an individual basis. There are two stages to loading a sound:
  1392. * Initialization of the internal decoder; and
  1393. * Completion of decoding of the file (the file is fully decoded)
  1394. You can specify separate fences for each of the different stages. Waiting for the initialization
  1395. of the internal decoder is important for when you need to know the sample format, channels and
  1396. sample rate of the file.
  1397. The example below shows how you could use a fence when loading a number of sounds:
  1398. ```c
  1399. // This fence will be released when all sounds are finished loading entirely.
  1400. ma_fence fence;
  1401. ma_fence_init(&fence);
  1402. // This will be passed into the initialization routine for each sound.
  1403. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1404. notifications.done.pFence = &fence;
  1405. // Now load a bunch of sounds:
  1406. for (iSound = 0; iSound < soundCount; iSound += 1) {
  1407. ma_resource_manager_data_source_init(pResourceManager, pSoundFilePaths[iSound], flags, &notifications, &pSoundSources[iSound]);
  1408. }
  1409. // ... DO SOMETHING ELSE WHILE SOUNDS ARE LOADING ...
  1410. // Wait for loading of sounds to finish.
  1411. ma_fence_wait(&fence);
  1412. ```
  1413. In the example above we used a fence for waiting until the entire file has been fully decoded. If
  1414. you only need to wait for the initialization of the internal decoder to complete, you can use the
  1415. `init` member of the `ma_resource_manager_pipeline_notifications` object:
  1416. ```c
  1417. notifications.init.pFence = &fence;
  1418. ```
  1419. If a fence is not appropriate for your situation, you can instead use a callback that is fired on
  1420. an individual sound basis. This is done in a very similar way to fences:
  1421. ```c
  1422. typedef struct
  1423. {
  1424. ma_async_notification_callbacks cb;
  1425. void* pMyData;
  1426. } my_notification;
  1427. void my_notification_callback(ma_async_notification* pNotification)
  1428. {
  1429. my_notification* pMyNotification = (my_notification*)pNotification;
  1430. // Do something in response to the sound finishing loading.
  1431. }
  1432. ...
  1433. my_notification myCallback;
  1434. myCallback.cb.onSignal = my_notification_callback;
  1435. myCallback.pMyData = pMyData;
  1436. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1437. notifications.done.pNotification = &myCallback;
  1438. ma_resource_manager_data_source_init(pResourceManager, "my_sound.wav", flags, &notifications, &mySound);
  1439. ```
  1440. In the example above we just extend the `ma_async_notification_callbacks` object and pass an
  1441. instantiation into the `ma_resource_manager_pipeline_notifications` in the same way as we did with
  1442. the fence, only we set `pNotification` instead of `pFence`. You can set both of these at the same
  1443. time and they should both work as expected. If using the `pNotification` system, you need to ensure
  1444. your `ma_async_notification_callbacks` object stays valid.
  1445. 6.2. Resource Manager Implementation Details
  1446. --------------------------------------------
  1447. Resources are managed in two main ways:
  1448. * By storing the entire sound inside an in-memory buffer (referred to as a data buffer)
  1449. * By streaming audio data on the fly (referred to as a data stream)
  1450. A resource managed data source (`ma_resource_manager_data_source`) encapsulates a data buffer or
  1451. data stream, depending on whether or not the data source was initialized with the
  1452. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. If so, it will make use of a
  1453. `ma_resource_manager_data_stream` object. Otherwise it will use a `ma_resource_manager_data_buffer`
  1454. object. Both of these objects are data sources which means they can be used with any
  1455. `ma_data_source_*()` API.
  1456. Another major feature of the resource manager is the ability to asynchronously decode audio files.
  1457. This relieves the audio thread of time-consuming decoding which can negatively affect scalability
  1458. due to the audio thread needing to complete it's work extremely quickly to avoid glitching.
  1459. Asynchronous decoding is achieved through a job system. There is a central multi-producer,
  1460. multi-consumer, fixed-capacity job queue. When some asynchronous work needs to be done, a job is
  1461. posted to the queue which is then read by a job thread. The number of job threads can be
  1462. configured for improved scalability, and job threads can all run in parallel without needing to
  1463. worry about the order of execution (how this is achieved is explained below).
  1464. When a sound is being loaded asynchronously, playback can begin before the sound has been fully
  1465. decoded. This enables the application to start playback of the sound quickly, while at the same
  1466. time allowing to resource manager to keep loading in the background. Since there may be less
  1467. threads than the number of sounds being loaded at a given time, a simple scheduling system is used
  1468. to keep decoding time balanced and fair. The resource manager solves this by splitting decoding
  1469. into chunks called pages. By default, each page is 1 second long. When a page has been decoded, a
  1470. new job will be posted to start decoding the next page. By dividing up decoding into pages, an
  1471. individual sound shouldn't ever delay every other sound from having their first page decoded. Of
  1472. course, when loading many sounds at the same time, there will always be an amount of time required
  1473. to process jobs in the queue so in heavy load situations there will still be some delay. To
  1474. determine if a data source is ready to have some frames read, use
  1475. `ma_resource_manager_data_source_get_available_frames()`. This will return the number of frames
  1476. available starting from the current position.
  1477. 6.2.1. Job Queue
  1478. ----------------
  1479. The resource manager uses a job queue which is multi-producer, multi-consumer, and fixed-capacity.
  1480. This job queue is not currently lock-free, and instead uses a spinlock to achieve thread-safety.
  1481. Only a fixed number of jobs can be allocated and inserted into the queue which is done through a
  1482. lock-free data structure for allocating an index into a fixed sized array, with reference counting
  1483. for mitigation of the ABA problem. The reference count is 32-bit.
  1484. For many types of jobs it's important that they execute in a specific order. In these cases, jobs
  1485. are executed serially. For the resource manager, serial execution of jobs is only required on a
  1486. per-object basis (per data buffer or per data stream). Each of these objects stores an execution
  1487. counter. When a job is posted it is associated with an execution counter. When the job is
  1488. processed, it checks if the execution counter of the job equals the execution counter of the
  1489. owning object and if so, processes the job. If the counters are not equal, the job will be posted
  1490. back onto the job queue for later processing. When the job finishes processing the execution order
  1491. of the main object is incremented. This system means the no matter how many job threads are
  1492. executing, decoding of an individual sound will always get processed serially. The advantage to
  1493. having multiple threads comes into play when loading multiple sounds at the same time.
  1494. The resource manager's job queue is not 100% lock-free and will use a spinlock to achieve
  1495. thread-safety for a very small section of code. This is only relevant when the resource manager
  1496. uses more than one job thread. If only using a single job thread, which is the default, the
  1497. lock should never actually wait in practice. The amount of time spent locking should be quite
  1498. short, but it's something to be aware of for those who have pedantic lock-free requirements and
  1499. need to use more than one job thread. There are plans to remove this lock in a future version.
  1500. In addition, posting a job will release a semaphore, which on Win32 is implemented with
  1501. `ReleaseSemaphore` and on POSIX platforms via a condition variable:
  1502. ```c
  1503. pthread_mutex_lock(&pSemaphore->lock);
  1504. {
  1505. pSemaphore->value += 1;
  1506. pthread_cond_signal(&pSemaphore->cond);
  1507. }
  1508. pthread_mutex_unlock(&pSemaphore->lock);
  1509. ```
  1510. Again, this is relevant for those with strict lock-free requirements in the audio thread. To avoid
  1511. this, you can use non-blocking mode (via the `MA_JOB_QUEUE_FLAG_NON_BLOCKING`
  1512. flag) and implement your own job processing routine (see the "Resource Manager" section above for
  1513. details on how to do this).
  1514. 6.2.2. Data Buffers
  1515. -------------------
  1516. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag is excluded at initialization time, the
  1517. resource manager will try to load the data into an in-memory data buffer. Before doing so, however,
  1518. it will first check if the specified file is already loaded. If so, it will increment a reference
  1519. counter and just use the already loaded data. This saves both time and memory. When the data buffer
  1520. is uninitialized, the reference counter will be decremented. If the counter hits zero, the file
  1521. will be unloaded. This is a detail to keep in mind because it could result in excessive loading and
  1522. unloading of a sound. For example, the following sequence will result in a file be loaded twice,
  1523. once after the other:
  1524. ```c
  1525. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer0); // Refcount = 1. Initial load.
  1526. ma_resource_manager_data_source_uninit(&myDataBuffer0); // Refcount = 0. Unloaded.
  1527. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer1); // Refcount = 1. Reloaded because previous uninit() unloaded it.
  1528. ma_resource_manager_data_source_uninit(&myDataBuffer1); // Refcount = 0. Unloaded.
  1529. ```
  1530. A binary search tree (BST) is used for storing data buffers as it has good balance between
  1531. efficiency and simplicity. The key of the BST is a 64-bit hash of the file path that was passed
  1532. into `ma_resource_manager_data_source_init()`. The advantage of using a hash is that it saves
  1533. memory over storing the entire path, has faster comparisons, and results in a mostly balanced BST
  1534. due to the random nature of the hash. The disadvantages are that file names are case-sensitive and
  1535. there's a small chance of name collisions. If case-sensitivity is an issue, you should normalize
  1536. your file names to upper- or lower-case before initializing your data sources. If name collisions
  1537. become an issue, you'll need to change the name of one of the colliding names or just not use the
  1538. resource manager.
  1539. When a sound file has not already been loaded and the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC`
  1540. flag is excluded, the file will be decoded synchronously by the calling thread. There are two
  1541. options for controlling how the audio is stored in the data buffer - encoded or decoded. When the
  1542. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` option is excluded, the raw file data will be stored
  1543. in memory. Otherwise the sound will be decoded before storing it in memory. Synchronous loading is
  1544. a very simple and standard process of simply adding an item to the BST, allocating a block of
  1545. memory and then decoding (if `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` is specified).
  1546. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag is specified, loading of the data buffer
  1547. is done asynchronously. In this case, a job is posted to the queue to start loading and then the
  1548. function immediately returns, setting an internal result code to `MA_BUSY`. This result code is
  1549. returned when the program calls `ma_resource_manager_data_source_result()`. When decoding has fully
  1550. completed `MA_SUCCESS` will be returned. This can be used to know if loading has fully completed.
  1551. When loading asynchronously, a single job is posted to the queue of the type
  1552. `MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE`. This involves making a copy of the file path and
  1553. associating it with job. When the job is processed by the job thread, it will first load the file
  1554. using the VFS associated with the resource manager. When using a custom VFS, it's important that it
  1555. be completely thread-safe because it will be used from one or more job threads at the same time.
  1556. Individual files should only ever be accessed by one thread at a time, however. After opening the
  1557. file via the VFS, the job will determine whether or not the file is being decoded. If not, it
  1558. simply allocates a block of memory and loads the raw file contents into it and returns. On the
  1559. other hand, when the file is being decoded, it will first allocate a decoder on the heap and
  1560. initialize it. Then it will check if the length of the file is known. If so it will allocate a
  1561. block of memory to store the decoded output and initialize it to silence. If the size is unknown,
  1562. it will allocate room for one page. After memory has been allocated, the first page will be
  1563. decoded. If the sound is shorter than a page, the result code will be set to `MA_SUCCESS` and the
  1564. completion event will be signalled and loading is now complete. If, however, there is more to
  1565. decode, a job with the code `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` is posted. This job
  1566. will decode the next page and perform the same process if it reaches the end. If there is more to
  1567. decode, the job will post another `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` job which will
  1568. keep on happening until the sound has been fully decoded. For sounds of an unknown length, each
  1569. page will be linked together as a linked list. Internally this is implemented via the
  1570. `ma_paged_audio_buffer` object.
  1571. 6.2.3. Data Streams
  1572. -------------------
  1573. Data streams only ever store two pages worth of data for each instance. They are most useful for
  1574. large sounds like music tracks in games that would consume too much memory if fully decoded in
  1575. memory. After every frame from a page has been read, a job will be posted to load the next page
  1576. which is done from the VFS.
  1577. For data streams, the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag will determine whether or
  1578. not initialization of the data source waits until the two pages have been decoded. When unset,
  1579. `ma_resource_manager_data_source_init()` will wait until the two pages have been loaded, otherwise
  1580. it will return immediately.
  1581. When frames are read from a data stream using `ma_resource_manager_data_source_read_pcm_frames()`,
  1582. `MA_BUSY` will be returned if there are no frames available. If there are some frames available,
  1583. but less than the number requested, `MA_SUCCESS` will be returned, but the actual number of frames
  1584. read will be less than the number requested. Due to the asynchronous nature of data streams,
  1585. seeking is also asynchronous. If the data stream is in the middle of a seek, `MA_BUSY` will be
  1586. returned when trying to read frames.
  1587. When `ma_resource_manager_data_source_read_pcm_frames()` results in a page getting fully consumed
  1588. a job is posted to load the next page. This will be posted from the same thread that called
  1589. `ma_resource_manager_data_source_read_pcm_frames()`.
  1590. Data streams are uninitialized by posting a job to the queue, but the function won't return until
  1591. that job has been processed. The reason for this is that the caller owns the data stream object and
  1592. therefore miniaudio needs to ensure everything completes before handing back control to the caller.
  1593. Also, if the data stream is uninitialized while pages are in the middle of decoding, they must
  1594. complete before destroying any underlying object and the job system handles this cleanly.
  1595. Note that when a new page needs to be loaded, a job will be posted to the resource manager's job
  1596. thread from the audio thread. You must keep in mind the details mentioned in the "Job Queue"
  1597. section above regarding locking when posting an event if you require a strictly lock-free audio
  1598. thread.
  1599. 7. Node Graph
  1600. =============
  1601. miniaudio's routing infrastructure follows a node graph paradigm. The idea is that you create a
  1602. node whose outputs are attached to inputs of another node, thereby creating a graph. There are
  1603. different types of nodes, with each node in the graph processing input data to produce output,
  1604. which is then fed through the chain. Each node in the graph can apply their own custom effects. At
  1605. the start of the graph will usually be one or more data source nodes which have no inputs and
  1606. instead pull their data from a data source. At the end of the graph is an endpoint which represents
  1607. the end of the chain and is where the final output is ultimately extracted from.
  1608. Each node has a number of input buses and a number of output buses. An output bus from a node is
  1609. attached to an input bus of another. Multiple nodes can connect their output buses to another
  1610. node's input bus, in which case their outputs will be mixed before processing by the node. Below is
  1611. a diagram that illustrates a hypothetical node graph setup:
  1612. ```
  1613. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Data flows left to right >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  1614. +---------------+ +-----------------+
  1615. | Data Source 1 =----+ +----------+ +----= Low Pass Filter =----+
  1616. +---------------+ | | =----+ +-----------------+ | +----------+
  1617. +----= Splitter | +----= ENDPOINT |
  1618. +---------------+ | | =----+ +-----------------+ | +----------+
  1619. | Data Source 2 =----+ +----------+ +----= Echo / Delay =----+
  1620. +---------------+ +-----------------+
  1621. ```
  1622. In the above graph, it starts with two data sources whose outputs are attached to the input of a
  1623. splitter node. It's at this point that the two data sources are mixed. After mixing, the splitter
  1624. performs it's processing routine and produces two outputs which is simply a duplication of the
  1625. input stream. One output is attached to a low pass filter, whereas the other output is attached to
  1626. a echo/delay. The outputs of the the low pass filter and the echo are attached to the endpoint, and
  1627. since they're both connected to the same input bus, they'll be mixed.
  1628. Each input bus must be configured to accept the same number of channels, but the number of channels
  1629. used by input buses can be different to the number of channels for output buses in which case
  1630. miniaudio will automatically convert the input data to the output channel count before processing.
  1631. The number of channels of an output bus of one node must match the channel count of the input bus
  1632. it's attached to. The channel counts cannot be changed after the node has been initialized. If you
  1633. attempt to attach an output bus to an input bus with a different channel count, attachment will
  1634. fail.
  1635. To use a node graph, you first need to initialize a `ma_node_graph` object. This is essentially a
  1636. container around the entire graph. The `ma_node_graph` object is required for some thread-safety
  1637. issues which will be explained later. A `ma_node_graph` object is initialized using miniaudio's
  1638. standard config/init system:
  1639. ```c
  1640. ma_node_graph_config nodeGraphConfig = ma_node_graph_config_init(myChannelCount);
  1641. result = ma_node_graph_init(&nodeGraphConfig, NULL, &nodeGraph); // Second parameter is a pointer to allocation callbacks.
  1642. if (result != MA_SUCCESS) {
  1643. // Failed to initialize node graph.
  1644. }
  1645. ```
  1646. When you initialize the node graph, you're specifying the channel count of the endpoint. The
  1647. endpoint is a special node which has one input bus and one output bus, both of which have the
  1648. same channel count, which is specified in the config. Any nodes that connect directly to the
  1649. endpoint must be configured such that their output buses have the same channel count. When you read
  1650. audio data from the node graph, it'll have the channel count you specified in the config. To read
  1651. data from the graph:
  1652. ```c
  1653. ma_uint32 framesRead;
  1654. result = ma_node_graph_read_pcm_frames(&nodeGraph, pFramesOut, frameCount, &framesRead);
  1655. if (result != MA_SUCCESS) {
  1656. // Failed to read data from the node graph.
  1657. }
  1658. ```
  1659. When you read audio data, miniaudio starts at the node graph's endpoint node which then pulls in
  1660. data from it's input attachments, which in turn recursively pull in data from their inputs, and so
  1661. on. At the start of the graph there will be some kind of data source node which will have zero
  1662. inputs and will instead read directly from a data source. The base nodes don't literally need to
  1663. read from a `ma_data_source` object, but they will always have some kind of underlying object that
  1664. sources some kind of audio. The `ma_data_source_node` node can be used to read from a
  1665. `ma_data_source`. Data is always in floating-point format and in the number of channels you
  1666. specified when the graph was initialized. The sample rate is defined by the underlying data sources.
  1667. It's up to you to ensure they use a consistent and appropriate sample rate.
  1668. The `ma_node` API is designed to allow custom nodes to be implemented with relative ease, but
  1669. miniaudio includes a few stock nodes for common functionality. This is how you would initialize a
  1670. node which reads directly from a data source (`ma_data_source_node`) which is an example of one
  1671. of the stock nodes that comes with miniaudio:
  1672. ```c
  1673. ma_data_source_node_config config = ma_data_source_node_config_init(pMyDataSource);
  1674. ma_data_source_node dataSourceNode;
  1675. result = ma_data_source_node_init(&nodeGraph, &config, NULL, &dataSourceNode);
  1676. if (result != MA_SUCCESS) {
  1677. // Failed to create data source node.
  1678. }
  1679. ```
  1680. The data source node will use the output channel count to determine the channel count of the output
  1681. bus. There will be 1 output bus and 0 input buses (data will be drawn directly from the data
  1682. source). The data source must output to floating-point (`ma_format_f32`) or else an error will be
  1683. returned from `ma_data_source_node_init()`.
  1684. By default the node will not be attached to the graph. To do so, use `ma_node_attach_output_bus()`:
  1685. ```c
  1686. result = ma_node_attach_output_bus(&dataSourceNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0);
  1687. if (result != MA_SUCCESS) {
  1688. // Failed to attach node.
  1689. }
  1690. ```
  1691. The code above connects the data source node directly to the endpoint. Since the data source node
  1692. has only a single output bus, the index will always be 0. Likewise, the endpoint only has a single
  1693. input bus which means the input bus index will also always be 0.
  1694. To detach a specific output bus, use `ma_node_detach_output_bus()`. To detach all output buses, use
  1695. `ma_node_detach_all_output_buses()`. If you want to just move the output bus from one attachment to
  1696. another, you do not need to detach first. You can just call `ma_node_attach_output_bus()` and it'll
  1697. deal with it for you.
  1698. Less frequently you may want to create a specialized node. This will be a node where you implement
  1699. your own processing callback to apply a custom effect of some kind. This is similar to initializing
  1700. one of the stock node types, only this time you need to specify a pointer to a vtable containing a
  1701. pointer to the processing function and the number of input and output buses. Example:
  1702. ```c
  1703. static void my_custom_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  1704. {
  1705. // Do some processing of ppFramesIn (one stream of audio data per input bus)
  1706. const float* pFramesIn_0 = ppFramesIn[0]; // Input bus @ index 0.
  1707. const float* pFramesIn_1 = ppFramesIn[1]; // Input bus @ index 1.
  1708. float* pFramesOut_0 = ppFramesOut[0]; // Output bus @ index 0.
  1709. // Do some processing. On input, `pFrameCountIn` will be the number of input frames in each
  1710. // buffer in `ppFramesIn` and `pFrameCountOut` will be the capacity of each of the buffers
  1711. // in `ppFramesOut`. On output, `pFrameCountIn` should be set to the number of input frames
  1712. // your node consumed and `pFrameCountOut` should be set the number of output frames that
  1713. // were produced.
  1714. //
  1715. // You should process as many frames as you can. If your effect consumes input frames at the
  1716. // same rate as output frames (always the case, unless you're doing resampling), you need
  1717. // only look at `ppFramesOut` and process that exact number of frames. If you're doing
  1718. // resampling, you'll need to be sure to set both `pFrameCountIn` and `pFrameCountOut`
  1719. // properly.
  1720. }
  1721. static ma_node_vtable my_custom_node_vtable =
  1722. {
  1723. my_custom_node_process_pcm_frames, // The function that will be called to process your custom node. This is where you'd implement your effect processing.
  1724. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1725. 2, // 2 input buses.
  1726. 1, // 1 output bus.
  1727. 0 // Default flags.
  1728. };
  1729. ...
  1730. // Each bus needs to have a channel count specified. To do this you need to specify the channel
  1731. // counts in an array and then pass that into the node config.
  1732. ma_uint32 inputChannels[2]; // Equal in size to the number of input channels specified in the vtable.
  1733. ma_uint32 outputChannels[1]; // Equal in size to the number of output channels specified in the vtable.
  1734. inputChannels[0] = channelsIn;
  1735. inputChannels[1] = channelsIn;
  1736. outputChannels[0] = channelsOut;
  1737. ma_node_config nodeConfig = ma_node_config_init();
  1738. nodeConfig.vtable = &my_custom_node_vtable;
  1739. nodeConfig.pInputChannels = inputChannels;
  1740. nodeConfig.pOutputChannels = outputChannels;
  1741. ma_node_base node;
  1742. result = ma_node_init(&nodeGraph, &nodeConfig, NULL, &node);
  1743. if (result != MA_SUCCESS) {
  1744. // Failed to initialize node.
  1745. }
  1746. ```
  1747. When initializing a custom node, as in the code above, you'll normally just place your vtable in
  1748. static space. The number of input and output buses are specified as part of the vtable. If you need
  1749. a variable number of buses on a per-node bases, the vtable should have the relevant bus count set
  1750. to `MA_NODE_BUS_COUNT_UNKNOWN`. In this case, the bus count should be set in the node config:
  1751. ```c
  1752. static ma_node_vtable my_custom_node_vtable =
  1753. {
  1754. my_custom_node_process_pcm_frames, // The function that will be called process your custom node. This is where you'd implement your effect processing.
  1755. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1756. MA_NODE_BUS_COUNT_UNKNOWN, // The number of input buses is determined on a per-node basis.
  1757. 1, // 1 output bus.
  1758. 0 // Default flags.
  1759. };
  1760. ...
  1761. ma_node_config nodeConfig = ma_node_config_init();
  1762. nodeConfig.vtable = &my_custom_node_vtable;
  1763. nodeConfig.inputBusCount = myBusCount; // <-- Since the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN, the input bus count should be set here.
  1764. nodeConfig.pInputChannels = inputChannels; // <-- Make sure there are nodeConfig.inputBusCount elements in this array.
  1765. nodeConfig.pOutputChannels = outputChannels; // <-- The vtable specifies 1 output bus, so there must be 1 element in this array.
  1766. ```
  1767. In the above example it's important to never set the `inputBusCount` and `outputBusCount` members
  1768. to anything other than their defaults if the vtable specifies an explicit count. They can only be
  1769. set if the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN in the relevant bus count.
  1770. Most often you'll want to create a structure to encapsulate your node with some extra data. You
  1771. need to make sure the `ma_node_base` object is your first member of the structure:
  1772. ```c
  1773. typedef struct
  1774. {
  1775. ma_node_base base; // <-- Make sure this is always the first member.
  1776. float someCustomData;
  1777. } my_custom_node;
  1778. ```
  1779. By doing this, your object will be compatible with all `ma_node` APIs and you can attach it to the
  1780. graph just like any other node.
  1781. In the custom processing callback (`my_custom_node_process_pcm_frames()` in the example above), the
  1782. number of channels for each bus is what was specified by the config when the node was initialized
  1783. with `ma_node_init()`. In addition, all attachments to each of the input buses will have been
  1784. pre-mixed by miniaudio. The config allows you to specify different channel counts for each
  1785. individual input and output bus. It's up to the effect to handle it appropriate, and if it can't,
  1786. return an error in it's initialization routine.
  1787. Custom nodes can be assigned some flags to describe their behaviour. These are set via the vtable
  1788. and include the following:
  1789. +-----------------------------------------+---------------------------------------------------+
  1790. | Flag Name | Description |
  1791. +-----------------------------------------+---------------------------------------------------+
  1792. | MA_NODE_FLAG_PASSTHROUGH | Useful for nodes that do not do any kind of audio |
  1793. | | processing, but are instead used for tracking |
  1794. | | time, handling events, etc. Also used by the |
  1795. | | internal endpoint node. It reads directly from |
  1796. | | the input bus to the output bus. Nodes with this |
  1797. | | flag must have exactly 1 input bus and 1 output |
  1798. | | bus, and both buses must have the same channel |
  1799. | | counts. |
  1800. +-----------------------------------------+---------------------------------------------------+
  1801. | MA_NODE_FLAG_CONTINUOUS_PROCESSING | Causes the processing callback to be called even |
  1802. | | when no data is available to be read from input |
  1803. | | attachments. When a node has at least one input |
  1804. | | bus, but there are no inputs attached or the |
  1805. | | inputs do not deliver any data, the node's |
  1806. | | processing callback will not get fired. This flag |
  1807. | | will make it so the callback is always fired |
  1808. | | regardless of whether or not any input data is |
  1809. | | received. This is useful for effects like |
  1810. | | echos where there will be a tail of audio data |
  1811. | | that still needs to be processed even when the |
  1812. | | original data sources have reached their ends. It |
  1813. | | may also be useful for nodes that must always |
  1814. | | have their processing callback fired when there |
  1815. | | are no inputs attached. |
  1816. +-----------------------------------------+---------------------------------------------------+
  1817. | MA_NODE_FLAG_ALLOW_NULL_INPUT | Used in conjunction with |
  1818. | | `MA_NODE_FLAG_CONTINUOUS_PROCESSING`. When this |
  1819. | | is set, the `ppFramesIn` parameter of the |
  1820. | | processing callback will be set to NULL when |
  1821. | | there are no input frames are available. When |
  1822. | | this is unset, silence will be posted to the |
  1823. | | processing callback. |
  1824. +-----------------------------------------+---------------------------------------------------+
  1825. | MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES | Used to tell miniaudio that input and output |
  1826. | | frames are processed at different rates. You |
  1827. | | should set this for any nodes that perform |
  1828. | | resampling. |
  1829. +-----------------------------------------+---------------------------------------------------+
  1830. | MA_NODE_FLAG_SILENT_OUTPUT | Used to tell miniaudio that a node produces only |
  1831. | | silent output. This is useful for nodes where you |
  1832. | | don't want the output to contribute to the final |
  1833. | | mix. An example might be if you want split your |
  1834. | | stream and have one branch be output to a file. |
  1835. | | When using this flag, you should avoid writing to |
  1836. | | the output buffer of the node's processing |
  1837. | | callback because miniaudio will ignore it anyway. |
  1838. +-----------------------------------------+---------------------------------------------------+
  1839. If you need to make a copy of an audio stream for effect processing you can use a splitter node
  1840. called `ma_splitter_node`. This takes has 1 input bus and splits the stream into 2 output buses.
  1841. You can use it like this:
  1842. ```c
  1843. ma_splitter_node_config splitterNodeConfig = ma_splitter_node_config_init(channels);
  1844. ma_splitter_node splitterNode;
  1845. result = ma_splitter_node_init(&nodeGraph, &splitterNodeConfig, NULL, &splitterNode);
  1846. if (result != MA_SUCCESS) {
  1847. // Failed to create node.
  1848. }
  1849. // Attach your output buses to two different input buses (can be on two different nodes).
  1850. ma_node_attach_output_bus(&splitterNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0); // Attach directly to the endpoint.
  1851. ma_node_attach_output_bus(&splitterNode, 1, &myEffectNode, 0); // Attach to input bus 0 of some effect node.
  1852. ```
  1853. The volume of an output bus can be configured on a per-bus basis:
  1854. ```c
  1855. ma_node_set_output_bus_volume(&splitterNode, 0, 0.5f);
  1856. ma_node_set_output_bus_volume(&splitterNode, 1, 0.5f);
  1857. ```
  1858. In the code above we're using the splitter node from before and changing the volume of each of the
  1859. copied streams.
  1860. You can start and stop a node with the following:
  1861. ```c
  1862. ma_node_set_state(&splitterNode, ma_node_state_started); // The default state.
  1863. ma_node_set_state(&splitterNode, ma_node_state_stopped);
  1864. ```
  1865. By default the node is in a started state, but since it won't be connected to anything won't
  1866. actually be invoked by the node graph until it's connected. When you stop a node, data will not be
  1867. read from any of it's input connections. You can use this property to stop a group of sounds
  1868. atomically.
  1869. You can configure the initial state of a node in it's config:
  1870. ```c
  1871. nodeConfig.initialState = ma_node_state_stopped;
  1872. ```
  1873. Note that for the stock specialized nodes, all of their configs will have a `nodeConfig` member
  1874. which is the config to use with the base node. This is where the initial state can be configured
  1875. for specialized nodes:
  1876. ```c
  1877. dataSourceNodeConfig.nodeConfig.initialState = ma_node_state_stopped;
  1878. ```
  1879. When using a specialized node like `ma_data_source_node` or `ma_splitter_node`, be sure to not
  1880. modify the `vtable` member of the `nodeConfig` object.
  1881. 7.1. Timing
  1882. -----------
  1883. The node graph supports starting and stopping nodes at scheduled times. This is especially useful
  1884. for data source nodes where you want to get the node set up, but only start playback at a specific
  1885. time. There are two clocks: local and global.
  1886. A local clock is per-node, whereas the global clock is per graph. Scheduling starts and stops can
  1887. only be done based on the global clock because the local clock will not be running while the node
  1888. is stopped. The global clocks advances whenever `ma_node_graph_read_pcm_frames()` is called. On the
  1889. other hand, the local clock only advances when the node's processing callback is fired, and is
  1890. advanced based on the output frame count.
  1891. To retrieve the global time, use `ma_node_graph_get_time()`. The global time can be set with
  1892. `ma_node_graph_set_time()` which might be useful if you want to do seeking on a global timeline.
  1893. Getting and setting the local time is similar. Use `ma_node_get_time()` to retrieve the local time,
  1894. and `ma_node_set_time()` to set the local time. The global and local times will be advanced by the
  1895. audio thread, so care should be taken to avoid data races. Ideally you should avoid calling these
  1896. outside of the node processing callbacks which are always run on the audio thread.
  1897. There is basic support for scheduling the starting and stopping of nodes. You can only schedule one
  1898. start and one stop at a time. This is mainly intended for putting nodes into a started or stopped
  1899. state in a frame-exact manner. Without this mechanism, starting and stopping of a node is limited
  1900. to the resolution of a call to `ma_node_graph_read_pcm_frames()` which would typically be in blocks
  1901. of several milliseconds. The following APIs can be used for scheduling node states:
  1902. ```c
  1903. ma_node_set_state_time()
  1904. ma_node_get_state_time()
  1905. ```
  1906. The time is absolute and must be based on the global clock. An example is below:
  1907. ```c
  1908. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1); // Delay starting to 1 second.
  1909. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5); // Delay stopping to 5 seconds.
  1910. ```
  1911. An example for changing the state using a relative time.
  1912. ```c
  1913. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1 + ma_node_graph_get_time(&myNodeGraph));
  1914. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5 + ma_node_graph_get_time(&myNodeGraph));
  1915. ```
  1916. Note that due to the nature of multi-threading the times may not be 100% exact. If this is an
  1917. issue, consider scheduling state changes from within a processing callback. An idea might be to
  1918. have some kind of passthrough trigger node that is used specifically for tracking time and handling
  1919. events.
  1920. 7.2. Thread Safety and Locking
  1921. ------------------------------
  1922. When processing audio, it's ideal not to have any kind of locking in the audio thread. Since it's
  1923. expected that `ma_node_graph_read_pcm_frames()` would be run on the audio thread, it does so
  1924. without the use of any locks. This section discusses the implementation used by miniaudio and goes
  1925. over some of the compromises employed by miniaudio to achieve this goal. Note that the current
  1926. implementation may not be ideal - feedback and critiques are most welcome.
  1927. The node graph API is not *entirely* lock-free. Only `ma_node_graph_read_pcm_frames()` is expected
  1928. to be lock-free. Attachment, detachment and uninitialization of nodes use locks to simplify the
  1929. implementation, but are crafted in a way such that such locking is not required when reading audio
  1930. data from the graph. Locking in these areas are achieved by means of spinlocks.
  1931. The main complication with keeping `ma_node_graph_read_pcm_frames()` lock-free stems from the fact
  1932. that a node can be uninitialized, and it's memory potentially freed, while in the middle of being
  1933. processed on the audio thread. There are times when the audio thread will be referencing a node,
  1934. which means the uninitialization process of a node needs to make sure it delays returning until the
  1935. audio thread is finished so that control is not handed back to the caller thereby giving them a
  1936. chance to free the node's memory.
  1937. When the audio thread is processing a node, it does so by reading from each of the output buses of
  1938. the node. In order for a node to process data for one of it's output buses, it needs to read from
  1939. each of it's input buses, and so on an so forth. It follows that once all output buses of a node
  1940. are detached, the node as a whole will be disconnected and no further processing will occur unless
  1941. it's output buses are reattached, which won't be happening when the node is being uninitialized.
  1942. By having `ma_node_detach_output_bus()` wait until the audio thread is finished with it, we can
  1943. simplify a few things, at the expense of making `ma_node_detach_output_bus()` a bit slower. By
  1944. doing this, the implementation of `ma_node_uninit()` becomes trivial - just detach all output
  1945. nodes, followed by each of the attachments to each of it's input nodes, and then do any final clean
  1946. up.
  1947. With the above design, the worst-case scenario is `ma_node_detach_output_bus()` taking as long as
  1948. it takes to process the output bus being detached. This will happen if it's called at just the
  1949. wrong moment where the audio thread has just iterated it and has just started processing. The
  1950. caller of `ma_node_detach_output_bus()` will stall until the audio thread is finished, which
  1951. includes the cost of recursively processing it's inputs. This is the biggest compromise made with
  1952. the approach taken by miniaudio for it's lock-free processing system. The cost of detaching nodes
  1953. earlier in the pipeline (data sources, for example) will be cheaper than the cost of detaching
  1954. higher level nodes, such as some kind of final post-processing endpoint. If you need to do mass
  1955. detachments, detach starting from the lowest level nodes and work your way towards the final
  1956. endpoint node (but don't try detaching the node graph's endpoint). If the audio thread is not
  1957. running, detachment will be fast and detachment in any order will be the same. The reason nodes
  1958. need to wait for their input attachments to complete is due to the potential for desyncs between
  1959. data sources. If the node was to terminate processing mid way through processing it's inputs,
  1960. there's a chance that some of the underlying data sources will have been read, but then others not.
  1961. That will then result in a potential desynchronization when detaching and reattaching higher-level
  1962. nodes. A possible solution to this is to have an option when detaching to terminate processing
  1963. before processing all input attachments which should be fairly simple.
  1964. Another compromise, albeit less significant, is locking when attaching and detaching nodes. This
  1965. locking is achieved by means of a spinlock in order to reduce memory overhead. A lock is present
  1966. for each input bus and output bus. When an output bus is connected to an input bus, both the output
  1967. bus and input bus is locked. This locking is specifically for attaching and detaching across
  1968. different threads and does not affect `ma_node_graph_read_pcm_frames()` in any way. The locking and
  1969. unlocking is mostly self-explanatory, but a slightly less intuitive aspect comes into it when
  1970. considering that iterating over attachments must not break as a result of attaching or detaching a
  1971. node while iteration is occurring.
  1972. Attaching and detaching are both quite simple. When an output bus of a node is attached to an input
  1973. bus of another node, it's added to a linked list. Basically, an input bus is a linked list, where
  1974. each item in the list is and output bus. We have some intentional (and convenient) restrictions on
  1975. what can done with the linked list in order to simplify the implementation. First of all, whenever
  1976. something needs to iterate over the list, it must do so in a forward direction. Backwards iteration
  1977. is not supported. Also, items can only be added to the start of the list.
  1978. The linked list is a doubly-linked list where each item in the list (an output bus) holds a pointer
  1979. to the next item in the list, and another to the previous item. A pointer to the previous item is
  1980. only required for fast detachment of the node - it is never used in iteration. This is an
  1981. important property because it means from the perspective of iteration, attaching and detaching of
  1982. an item can be done with a single atomic assignment. This is exploited by both the attachment and
  1983. detachment process. When attaching the node, the first thing that is done is the setting of the
  1984. local "next" and "previous" pointers of the node. After that, the item is "attached" to the list
  1985. by simply performing an atomic exchange with the head pointer. After that, the node is "attached"
  1986. to the list from the perspective of iteration. Even though the "previous" pointer of the next item
  1987. hasn't yet been set, from the perspective of iteration it's been attached because iteration will
  1988. only be happening in a forward direction which means the "previous" pointer won't actually ever get
  1989. used. The same general process applies to detachment. See `ma_node_attach_output_bus()` and
  1990. `ma_node_detach_output_bus()` for the implementation of this mechanism.
  1991. 8. Decoding
  1992. ===========
  1993. The `ma_decoder` API is used for reading audio files. Decoders are completely decoupled from
  1994. devices and can be used independently. Built-in support is included for the following formats:
  1995. +---------+
  1996. | Format |
  1997. +---------+
  1998. | WAV |
  1999. | MP3 |
  2000. | FLAC |
  2001. +---------+
  2002. You can disable the built-in decoders by specifying one or more of the following options before the
  2003. miniaudio implementation:
  2004. ```c
  2005. #define MA_NO_WAV
  2006. #define MA_NO_MP3
  2007. #define MA_NO_FLAC
  2008. ```
  2009. miniaudio supports the ability to plug in custom decoders. See the section below for details on how
  2010. to use custom decoders.
  2011. A decoder can be initialized from a file with `ma_decoder_init_file()`, a block of memory with
  2012. `ma_decoder_init_memory()`, or from data delivered via callbacks with `ma_decoder_init()`. Here is
  2013. an example for loading a decoder from a file:
  2014. ```c
  2015. ma_decoder decoder;
  2016. ma_result result = ma_decoder_init_file("MySong.mp3", NULL, &decoder);
  2017. if (result != MA_SUCCESS) {
  2018. return false; // An error occurred.
  2019. }
  2020. ...
  2021. ma_decoder_uninit(&decoder);
  2022. ```
  2023. When initializing a decoder, you can optionally pass in a pointer to a `ma_decoder_config` object
  2024. (the `NULL` argument in the example above) which allows you to configure the output format, channel
  2025. count, sample rate and channel map:
  2026. ```c
  2027. ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 2, 48000);
  2028. ```
  2029. When passing in `NULL` for decoder config in `ma_decoder_init*()`, the output format will be the
  2030. same as that defined by the decoding backend.
  2031. Data is read from the decoder as PCM frames. This will output the number of PCM frames actually
  2032. read. If this is less than the requested number of PCM frames it means you've reached the end. The
  2033. return value will be `MA_AT_END` if no samples have been read and the end has been reached.
  2034. ```c
  2035. ma_result result = ma_decoder_read_pcm_frames(pDecoder, pFrames, framesToRead, &framesRead);
  2036. if (framesRead < framesToRead) {
  2037. // Reached the end.
  2038. }
  2039. ```
  2040. You can also seek to a specific frame like so:
  2041. ```c
  2042. ma_result result = ma_decoder_seek_to_pcm_frame(pDecoder, targetFrame);
  2043. if (result != MA_SUCCESS) {
  2044. return false; // An error occurred.
  2045. }
  2046. ```
  2047. If you want to loop back to the start, you can simply seek back to the first PCM frame:
  2048. ```c
  2049. ma_decoder_seek_to_pcm_frame(pDecoder, 0);
  2050. ```
  2051. When loading a decoder, miniaudio uses a trial and error technique to find the appropriate decoding
  2052. backend. This can be unnecessarily inefficient if the type is already known. In this case you can
  2053. use `encodingFormat` variable in the device config to specify a specific encoding format you want
  2054. to decode:
  2055. ```c
  2056. decoderConfig.encodingFormat = ma_encoding_format_wav;
  2057. ```
  2058. See the `ma_encoding_format` enum for possible encoding formats.
  2059. The `ma_decoder_init_file()` API will try using the file extension to determine which decoding
  2060. backend to prefer.
  2061. 8.1. Custom Decoders
  2062. --------------------
  2063. It's possible to implement a custom decoder and plug it into miniaudio. This is extremely useful
  2064. when you want to use the `ma_decoder` API, but need to support an encoding format that's not one of
  2065. the stock formats supported by miniaudio. This can be put to particularly good use when using the
  2066. `ma_engine` and/or `ma_resource_manager` APIs because they use `ma_decoder` internally. If, for
  2067. example, you wanted to support Opus, you can do so with a custom decoder (there if a reference
  2068. Opus decoder in the "extras" folder of the miniaudio repository which uses libopus + libopusfile).
  2069. A custom decoder must implement a data source. A vtable called `ma_decoding_backend_vtable` needs
  2070. to be implemented which is then passed into the decoder config:
  2071. ```c
  2072. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  2073. {
  2074. &g_ma_decoding_backend_vtable_libvorbis,
  2075. &g_ma_decoding_backend_vtable_libopus
  2076. };
  2077. ...
  2078. decoderConfig = ma_decoder_config_init_default();
  2079. decoderConfig.pCustomBackendUserData = NULL;
  2080. decoderConfig.ppCustomBackendVTables = pCustomBackendVTables;
  2081. decoderConfig.customBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  2082. ```
  2083. The `ma_decoding_backend_vtable` vtable has the following functions:
  2084. ```
  2085. onInit
  2086. onInitFile
  2087. onInitFileW
  2088. onInitMemory
  2089. onUninit
  2090. ```
  2091. There are only two functions that must be implemented - `onInit` and `onUninit`. The other
  2092. functions can be implemented for a small optimization for loading from a file path or memory. If
  2093. these are not specified, miniaudio will deal with it for you via a generic implementation.
  2094. When you initialize a custom data source (by implementing the `onInit` function in the vtable) you
  2095. will need to output a pointer to a `ma_data_source` which implements your custom decoder. See the
  2096. section about data sources for details on how to implement this. Alternatively, see the
  2097. "custom_decoders" example in the miniaudio repository.
  2098. The `onInit` function takes a pointer to some callbacks for the purpose of reading raw audio data
  2099. from some arbitrary source. You'll use these functions to read from the raw data and perform the
  2100. decoding. When you call them, you will pass in the `pReadSeekTellUserData` pointer to the relevant
  2101. parameter.
  2102. The `pConfig` parameter in `onInit` can be used to configure the backend if appropriate. It's only
  2103. used as a hint and can be ignored. However, if any of the properties are relevant to your decoder,
  2104. an optimal implementation will handle the relevant properties appropriately.
  2105. If memory allocation is required, it should be done so via the specified allocation callbacks if
  2106. possible (the `pAllocationCallbacks` parameter).
  2107. If an error occurs when initializing the decoder, you should leave `ppBackend` unset, or set to
  2108. NULL, and make sure everything is cleaned up appropriately and an appropriate result code returned.
  2109. When multiple custom backends are specified, miniaudio will cycle through the vtables in the order
  2110. they're listed in the array that's passed into the decoder config so it's important that your
  2111. initialization routine is clean.
  2112. When a decoder is uninitialized, the `onUninit` callback will be fired which will give you an
  2113. opportunity to clean up and internal data.
  2114. 9. Encoding
  2115. ===========
  2116. The `ma_encoding` API is used for writing audio files. The only supported output format is WAV.
  2117. This can be disabled by specifying the following option before the implementation of miniaudio:
  2118. ```c
  2119. #define MA_NO_WAV
  2120. ```
  2121. An encoder can be initialized to write to a file with `ma_encoder_init_file()` or from data
  2122. delivered via callbacks with `ma_encoder_init()`. Below is an example for initializing an encoder
  2123. to output to a file.
  2124. ```c
  2125. ma_encoder_config config = ma_encoder_config_init(ma_encoding_format_wav, FORMAT, CHANNELS, SAMPLE_RATE);
  2126. ma_encoder encoder;
  2127. ma_result result = ma_encoder_init_file("my_file.wav", &config, &encoder);
  2128. if (result != MA_SUCCESS) {
  2129. // Error
  2130. }
  2131. ...
  2132. ma_encoder_uninit(&encoder);
  2133. ```
  2134. When initializing an encoder you must specify a config which is initialized with
  2135. `ma_encoder_config_init()`. Here you must specify the file type, the output sample format, output
  2136. channel count and output sample rate. The following file types are supported:
  2137. +------------------------+-------------+
  2138. | Enum | Description |
  2139. +------------------------+-------------+
  2140. | ma_encoding_format_wav | WAV |
  2141. +------------------------+-------------+
  2142. If the format, channel count or sample rate is not supported by the output file type an error will
  2143. be returned. The encoder will not perform data conversion so you will need to convert it before
  2144. outputting any audio data. To output audio data, use `ma_encoder_write_pcm_frames()`, like in the
  2145. example below:
  2146. ```c
  2147. ma_uint64 framesWritten;
  2148. result = ma_encoder_write_pcm_frames(&encoder, pPCMFramesToWrite, framesToWrite, &framesWritten);
  2149. if (result != MA_SUCCESS) {
  2150. ... handle error ...
  2151. }
  2152. ```
  2153. The `framesWritten` variable will contain the number of PCM frames that were actually written. This
  2154. is optionally and you can pass in `NULL` if you need this.
  2155. Encoders must be uninitialized with `ma_encoder_uninit()`.
  2156. 10. Data Conversion
  2157. ===================
  2158. A data conversion API is included with miniaudio which supports the majority of data conversion
  2159. requirements. This supports conversion between sample formats, channel counts (with channel
  2160. mapping) and sample rates.
  2161. 10.1. Sample Format Conversion
  2162. ------------------------------
  2163. Conversion between sample formats is achieved with the `ma_pcm_*_to_*()`, `ma_pcm_convert()` and
  2164. `ma_convert_pcm_frames_format()` APIs. Use `ma_pcm_*_to_*()` to convert between two specific
  2165. formats. Use `ma_pcm_convert()` to convert based on a `ma_format` variable. Use
  2166. `ma_convert_pcm_frames_format()` to convert PCM frames where you want to specify the frame count
  2167. and channel count as a variable instead of the total sample count.
  2168. 10.1.1. Dithering
  2169. -----------------
  2170. Dithering can be set using the ditherMode parameter.
  2171. The different dithering modes include the following, in order of efficiency:
  2172. +-----------+--------------------------+
  2173. | Type | Enum Token |
  2174. +-----------+--------------------------+
  2175. | None | ma_dither_mode_none |
  2176. | Rectangle | ma_dither_mode_rectangle |
  2177. | Triangle | ma_dither_mode_triangle |
  2178. +-----------+--------------------------+
  2179. Note that even if the dither mode is set to something other than `ma_dither_mode_none`, it will be
  2180. ignored for conversions where dithering is not needed. Dithering is available for the following
  2181. conversions:
  2182. ```
  2183. s16 -> u8
  2184. s24 -> u8
  2185. s32 -> u8
  2186. f32 -> u8
  2187. s24 -> s16
  2188. s32 -> s16
  2189. f32 -> s16
  2190. ```
  2191. Note that it is not an error to pass something other than ma_dither_mode_none for conversions where
  2192. dither is not used. It will just be ignored.
  2193. 10.2. Channel Conversion
  2194. ------------------------
  2195. Channel conversion is used for channel rearrangement and conversion from one channel count to
  2196. another. The `ma_channel_converter` API is used for channel conversion. Below is an example of
  2197. initializing a simple channel converter which converts from mono to stereo.
  2198. ```c
  2199. ma_channel_converter_config config = ma_channel_converter_config_init(
  2200. ma_format, // Sample format
  2201. 1, // Input channels
  2202. NULL, // Input channel map
  2203. 2, // Output channels
  2204. NULL, // Output channel map
  2205. ma_channel_mix_mode_default); // The mixing algorithm to use when combining channels.
  2206. result = ma_channel_converter_init(&config, NULL, &converter);
  2207. if (result != MA_SUCCESS) {
  2208. // Error.
  2209. }
  2210. ```
  2211. To perform the conversion simply call `ma_channel_converter_process_pcm_frames()` like so:
  2212. ```c
  2213. ma_result result = ma_channel_converter_process_pcm_frames(&converter, pFramesOut, pFramesIn, frameCount);
  2214. if (result != MA_SUCCESS) {
  2215. // Error.
  2216. }
  2217. ```
  2218. It is up to the caller to ensure the output buffer is large enough to accommodate the new PCM
  2219. frames.
  2220. Input and output PCM frames are always interleaved. Deinterleaved layouts are not supported.
  2221. 10.2.1. Channel Mapping
  2222. -----------------------
  2223. In addition to converting from one channel count to another, like the example above, the channel
  2224. converter can also be used to rearrange channels. When initializing the channel converter, you can
  2225. optionally pass in channel maps for both the input and output frames. If the channel counts are the
  2226. same, and each channel map contains the same channel positions with the exception that they're in
  2227. a different order, a simple shuffling of the channels will be performed. If, however, there is not
  2228. a 1:1 mapping of channel positions, or the channel counts differ, the input channels will be mixed
  2229. based on a mixing mode which is specified when initializing the `ma_channel_converter_config`
  2230. object.
  2231. When converting from mono to multi-channel, the mono channel is simply copied to each output
  2232. channel. When going the other way around, the audio of each output channel is simply averaged and
  2233. copied to the mono channel.
  2234. In more complicated cases blending is used. The `ma_channel_mix_mode_simple` mode will drop excess
  2235. channels and silence extra channels. For example, converting from 4 to 2 channels, the 3rd and 4th
  2236. channels will be dropped, whereas converting from 2 to 4 channels will put silence into the 3rd and
  2237. 4th channels.
  2238. The `ma_channel_mix_mode_rectangle` mode uses spacial locality based on a rectangle to compute a
  2239. simple distribution between input and output. Imagine sitting in the middle of a room, with
  2240. speakers on the walls representing channel positions. The `MA_CHANNEL_FRONT_LEFT` position can be
  2241. thought of as being in the corner of the front and left walls.
  2242. Finally, the `ma_channel_mix_mode_custom_weights` mode can be used to use custom user-defined
  2243. weights. Custom weights can be passed in as the last parameter of
  2244. `ma_channel_converter_config_init()`.
  2245. Predefined channel maps can be retrieved with `ma_channel_map_init_standard()`. This takes a
  2246. `ma_standard_channel_map` enum as it's first parameter, which can be one of the following:
  2247. +-----------------------------------+-----------------------------------------------------------+
  2248. | Name | Description |
  2249. +-----------------------------------+-----------------------------------------------------------+
  2250. | ma_standard_channel_map_default | Default channel map used by miniaudio. See below. |
  2251. | ma_standard_channel_map_microsoft | Channel map used by Microsoft's bitfield channel maps. |
  2252. | ma_standard_channel_map_alsa | Default ALSA channel map. |
  2253. | ma_standard_channel_map_rfc3551 | RFC 3551. Based on AIFF. |
  2254. | ma_standard_channel_map_flac | FLAC channel map. |
  2255. | ma_standard_channel_map_vorbis | Vorbis channel map. |
  2256. | ma_standard_channel_map_sound4 | FreeBSD's sound(4). |
  2257. | ma_standard_channel_map_sndio | sndio channel map. http://www.sndio.org/tips.html. |
  2258. | ma_standard_channel_map_webaudio | https://webaudio.github.io/web-audio-api/#ChannelOrdering |
  2259. +-----------------------------------+-----------------------------------------------------------+
  2260. Below are the channel maps used by default in miniaudio (`ma_standard_channel_map_default`):
  2261. +---------------+---------------------------------+
  2262. | Channel Count | Mapping |
  2263. +---------------+---------------------------------+
  2264. | 1 (Mono) | 0: MA_CHANNEL_MONO |
  2265. +---------------+---------------------------------+
  2266. | 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2267. | | 1: MA_CHANNEL_FRONT_RIGHT |
  2268. +---------------+---------------------------------+
  2269. | 3 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2270. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2271. | | 2: MA_CHANNEL_FRONT_CENTER |
  2272. +---------------+---------------------------------+
  2273. | 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2274. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2275. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2276. | | 3: MA_CHANNEL_BACK_CENTER |
  2277. +---------------+---------------------------------+
  2278. | 5 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2279. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2280. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2281. | | 3: MA_CHANNEL_BACK_LEFT <br> |
  2282. | | 4: MA_CHANNEL_BACK_RIGHT |
  2283. +---------------+---------------------------------+
  2284. | 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2285. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2286. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2287. | | 3: MA_CHANNEL_LFE <br> |
  2288. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2289. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2290. +---------------+---------------------------------+
  2291. | 7 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2292. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2293. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2294. | | 3: MA_CHANNEL_LFE <br> |
  2295. | | 4: MA_CHANNEL_BACK_CENTER <br> |
  2296. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2297. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2298. +---------------+---------------------------------+
  2299. | 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2300. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2301. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2302. | | 3: MA_CHANNEL_LFE <br> |
  2303. | | 4: MA_CHANNEL_BACK_LEFT <br> |
  2304. | | 5: MA_CHANNEL_BACK_RIGHT <br> |
  2305. | | 6: MA_CHANNEL_SIDE_LEFT <br> |
  2306. | | 7: MA_CHANNEL_SIDE_RIGHT |
  2307. +---------------+---------------------------------+
  2308. | Other | All channels set to 0. This |
  2309. | | is equivalent to the same |
  2310. | | mapping as the device. |
  2311. +---------------+---------------------------------+
  2312. 10.3. Resampling
  2313. ----------------
  2314. Resampling is achieved with the `ma_resampler` object. To create a resampler object, do something
  2315. like the following:
  2316. ```c
  2317. ma_resampler_config config = ma_resampler_config_init(
  2318. ma_format_s16,
  2319. channels,
  2320. sampleRateIn,
  2321. sampleRateOut,
  2322. ma_resample_algorithm_linear);
  2323. ma_resampler resampler;
  2324. ma_result result = ma_resampler_init(&config, &resampler);
  2325. if (result != MA_SUCCESS) {
  2326. // An error occurred...
  2327. }
  2328. ```
  2329. Do the following to uninitialize the resampler:
  2330. ```c
  2331. ma_resampler_uninit(&resampler);
  2332. ```
  2333. The following example shows how data can be processed
  2334. ```c
  2335. ma_uint64 frameCountIn = 1000;
  2336. ma_uint64 frameCountOut = 2000;
  2337. ma_result result = ma_resampler_process_pcm_frames(&resampler, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2338. if (result != MA_SUCCESS) {
  2339. // An error occurred...
  2340. }
  2341. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the
  2342. // number of output frames written.
  2343. ```
  2344. To initialize the resampler you first need to set up a config (`ma_resampler_config`) with
  2345. `ma_resampler_config_init()`. You need to specify the sample format you want to use, the number of
  2346. channels, the input and output sample rate, and the algorithm.
  2347. The sample format can be either `ma_format_s16` or `ma_format_f32`. If you need a different format
  2348. you will need to perform pre- and post-conversions yourself where necessary. Note that the format
  2349. is the same for both input and output. The format cannot be changed after initialization.
  2350. The resampler supports multiple channels and is always interleaved (both input and output). The
  2351. channel count cannot be changed after initialization.
  2352. The sample rates can be anything other than zero, and are always specified in hertz. They should be
  2353. set to something like 44100, etc. The sample rate is the only configuration property that can be
  2354. changed after initialization.
  2355. The miniaudio resampler has built-in support for the following algorithms:
  2356. +-----------+------------------------------+
  2357. | Algorithm | Enum Token |
  2358. +-----------+------------------------------+
  2359. | Linear | ma_resample_algorithm_linear |
  2360. | Custom | ma_resample_algorithm_custom |
  2361. +-----------+------------------------------+
  2362. The algorithm cannot be changed after initialization.
  2363. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2364. De-interleaved processing is not supported. To process frames, use
  2365. `ma_resampler_process_pcm_frames()`. On input, this function takes the number of output frames you
  2366. can fit in the output buffer and the number of input frames contained in the input buffer. On
  2367. output these variables contain the number of output frames that were written to the output buffer
  2368. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2369. input buffer in which case it will be treated as an infinitely large buffer of zeros. The output
  2370. buffer can also be NULL, in which case the processing will be treated as seek.
  2371. The sample rate can be changed dynamically on the fly. You can change this with explicit sample
  2372. rates with `ma_resampler_set_rate()` and also with a decimal ratio with
  2373. `ma_resampler_set_rate_ratio()`. The ratio is in/out.
  2374. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2375. number of frames. You can calculate this with `ma_resampler_get_required_input_frame_count()`.
  2376. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2377. number of input frames. You can do this with `ma_resampler_get_expected_output_frame_count()`.
  2378. Due to the nature of how resampling works, the resampler introduces some latency. This can be
  2379. retrieved in terms of both the input rate and the output rate with
  2380. `ma_resampler_get_input_latency()` and `ma_resampler_get_output_latency()`.
  2381. 10.3.1. Resampling Algorithms
  2382. -----------------------------
  2383. The choice of resampling algorithm depends on your situation and requirements.
  2384. 10.3.1.1. Linear Resampling
  2385. ---------------------------
  2386. The linear resampler is the fastest, but comes at the expense of poorer quality. There is, however,
  2387. some control over the quality of the linear resampler which may make it a suitable option depending
  2388. on your requirements.
  2389. The linear resampler performs low-pass filtering before or after downsampling or upsampling,
  2390. depending on the sample rates you're converting between. When decreasing the sample rate, the
  2391. low-pass filter will be applied before downsampling. When increasing the rate it will be performed
  2392. after upsampling. By default a fourth order low-pass filter will be applied. This can be configured
  2393. via the `lpfOrder` configuration variable. Setting this to 0 will disable filtering.
  2394. The low-pass filter has a cutoff frequency which defaults to half the sample rate of the lowest of
  2395. the input and output sample rates (Nyquist Frequency).
  2396. The API for the linear resampler is the same as the main resampler API, only it's called
  2397. `ma_linear_resampler`.
  2398. 10.3.2. Custom Resamplers
  2399. -------------------------
  2400. You can implement a custom resampler by using the `ma_resample_algorithm_custom` resampling
  2401. algorithm and setting a vtable in the resampler config:
  2402. ```c
  2403. ma_resampler_config config = ma_resampler_config_init(..., ma_resample_algorithm_custom);
  2404. config.pBackendVTable = &g_customResamplerVTable;
  2405. ```
  2406. Custom resamplers are useful if the stock algorithms are not appropriate for your use case. You
  2407. need to implement the required functions in `ma_resampling_backend_vtable`. Note that not all
  2408. functions in the vtable need to be implemented, but if it's possible to implement, they should be.
  2409. You can use the `ma_linear_resampler` object for an example on how to implement the vtable. The
  2410. `onGetHeapSize` callback is used to calculate the size of any internal heap allocation the custom
  2411. resampler will need to make given the supplied config. When you initialize the resampler via the
  2412. `onInit` callback, you'll be given a pointer to a heap allocation which is where you should store
  2413. the heap allocated data. You should not free this data in `onUninit` because miniaudio will manage
  2414. it for you.
  2415. The `onProcess` callback is where the actual resampling takes place. On input, `pFrameCountIn`
  2416. points to a variable containing the number of frames in the `pFramesIn` buffer and
  2417. `pFrameCountOut` points to a variable containing the capacity in frames of the `pFramesOut` buffer.
  2418. On output, `pFrameCountIn` should be set to the number of input frames that were fully consumed,
  2419. whereas `pFrameCountOut` should be set to the number of frames that were written to `pFramesOut`.
  2420. The `onSetRate` callback is optional and is used for dynamically changing the sample rate. If
  2421. dynamic rate changes are not supported, you can set this callback to NULL.
  2422. The `onGetInputLatency` and `onGetOutputLatency` functions are used for retrieving the latency in
  2423. input and output rates respectively. These can be NULL in which case latency calculations will be
  2424. assumed to be NULL.
  2425. The `onGetRequiredInputFrameCount` callback is used to give miniaudio a hint as to how many input
  2426. frames are required to be available to produce the given number of output frames. Likewise, the
  2427. `onGetExpectedOutputFrameCount` callback is used to determine how many output frames will be
  2428. produced given the specified number of input frames. miniaudio will use these as a hint, but they
  2429. are optional and can be set to NULL if you're unable to implement them.
  2430. 10.4. General Data Conversion
  2431. -----------------------------
  2432. The `ma_data_converter` API can be used to wrap sample format conversion, channel conversion and
  2433. resampling into one operation. This is what miniaudio uses internally to convert between the format
  2434. requested when the device was initialized and the format of the backend's native device. The API
  2435. for general data conversion is very similar to the resampling API. Create a `ma_data_converter`
  2436. object like this:
  2437. ```c
  2438. ma_data_converter_config config = ma_data_converter_config_init(
  2439. inputFormat,
  2440. outputFormat,
  2441. inputChannels,
  2442. outputChannels,
  2443. inputSampleRate,
  2444. outputSampleRate
  2445. );
  2446. ma_data_converter converter;
  2447. ma_result result = ma_data_converter_init(&config, NULL, &converter);
  2448. if (result != MA_SUCCESS) {
  2449. // An error occurred...
  2450. }
  2451. ```
  2452. In the example above we use `ma_data_converter_config_init()` to initialize the config, however
  2453. there's many more properties that can be configured, such as channel maps and resampling quality.
  2454. Something like the following may be more suitable depending on your requirements:
  2455. ```c
  2456. ma_data_converter_config config = ma_data_converter_config_init_default();
  2457. config.formatIn = inputFormat;
  2458. config.formatOut = outputFormat;
  2459. config.channelsIn = inputChannels;
  2460. config.channelsOut = outputChannels;
  2461. config.sampleRateIn = inputSampleRate;
  2462. config.sampleRateOut = outputSampleRate;
  2463. ma_channel_map_init_standard(ma_standard_channel_map_flac, config.channelMapIn, sizeof(config.channelMapIn)/sizeof(config.channelMapIn[0]), config.channelCountIn);
  2464. config.resampling.linear.lpfOrder = MA_MAX_FILTER_ORDER;
  2465. ```
  2466. Do the following to uninitialize the data converter:
  2467. ```c
  2468. ma_data_converter_uninit(&converter, NULL);
  2469. ```
  2470. The following example shows how data can be processed
  2471. ```c
  2472. ma_uint64 frameCountIn = 1000;
  2473. ma_uint64 frameCountOut = 2000;
  2474. ma_result result = ma_data_converter_process_pcm_frames(&converter, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2475. if (result != MA_SUCCESS) {
  2476. // An error occurred...
  2477. }
  2478. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the number
  2479. // of output frames written.
  2480. ```
  2481. The data converter supports multiple channels and is always interleaved (both input and output).
  2482. The channel count cannot be changed after initialization.
  2483. Sample rates can be anything other than zero, and are always specified in hertz. They should be set
  2484. to something like 44100, etc. The sample rate is the only configuration property that can be
  2485. changed after initialization, but only if the `resampling.allowDynamicSampleRate` member of
  2486. `ma_data_converter_config` is set to `MA_TRUE`. To change the sample rate, use
  2487. `ma_data_converter_set_rate()` or `ma_data_converter_set_rate_ratio()`. The ratio must be in/out.
  2488. The resampling algorithm cannot be changed after initialization.
  2489. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2490. De-interleaved processing is not supported. To process frames, use
  2491. `ma_data_converter_process_pcm_frames()`. On input, this function takes the number of output frames
  2492. you can fit in the output buffer and the number of input frames contained in the input buffer. On
  2493. output these variables contain the number of output frames that were written to the output buffer
  2494. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2495. input buffer in which case it will be treated as an infinitely large
  2496. buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated
  2497. as seek.
  2498. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2499. number of frames. You can calculate this with `ma_data_converter_get_required_input_frame_count()`.
  2500. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2501. number of input frames. You can do this with `ma_data_converter_get_expected_output_frame_count()`.
  2502. Due to the nature of how resampling works, the data converter introduces some latency if resampling
  2503. is required. This can be retrieved in terms of both the input rate and the output rate with
  2504. `ma_data_converter_get_input_latency()` and `ma_data_converter_get_output_latency()`.
  2505. 11. Filtering
  2506. =============
  2507. 11.1. Biquad Filtering
  2508. ----------------------
  2509. Biquad filtering is achieved with the `ma_biquad` API. Example:
  2510. ```c
  2511. ma_biquad_config config = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
  2512. ma_result result = ma_biquad_init(&config, &biquad);
  2513. if (result != MA_SUCCESS) {
  2514. // Error.
  2515. }
  2516. ...
  2517. ma_biquad_process_pcm_frames(&biquad, pFramesOut, pFramesIn, frameCount);
  2518. ```
  2519. Biquad filtering is implemented using transposed direct form 2. The numerator coefficients are b0,
  2520. b1 and b2, and the denominator coefficients are a0, a1 and a2. The a0 coefficient is required and
  2521. coefficients must not be pre-normalized.
  2522. Supported formats are `ma_format_s16` and `ma_format_f32`. If you need to use a different format
  2523. you need to convert it yourself beforehand. When using `ma_format_s16` the biquad filter will use
  2524. fixed point arithmetic. When using `ma_format_f32`, floating point arithmetic will be used.
  2525. Input and output frames are always interleaved.
  2526. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2527. buffers, like so:
  2528. ```c
  2529. ma_biquad_process_pcm_frames(&biquad, pMyData, pMyData, frameCount);
  2530. ```
  2531. If you need to change the values of the coefficients, but maintain the values in the registers you
  2532. can do so with `ma_biquad_reinit()`. This is useful if you need to change the properties of the
  2533. filter while keeping the values of registers valid to avoid glitching. Do not use
  2534. `ma_biquad_init()` for this as it will do a full initialization which involves clearing the
  2535. registers to 0. Note that changing the format or channel count after initialization is invalid and
  2536. will result in an error.
  2537. 11.2. Low-Pass Filtering
  2538. ------------------------
  2539. Low-pass filtering is achieved with the following APIs:
  2540. +---------+------------------------------------------+
  2541. | API | Description |
  2542. +---------+------------------------------------------+
  2543. | ma_lpf1 | First order low-pass filter |
  2544. | ma_lpf2 | Second order low-pass filter |
  2545. | ma_lpf | High order low-pass filter (Butterworth) |
  2546. +---------+------------------------------------------+
  2547. Low-pass filter example:
  2548. ```c
  2549. ma_lpf_config config = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  2550. ma_result result = ma_lpf_init(&config, &lpf);
  2551. if (result != MA_SUCCESS) {
  2552. // Error.
  2553. }
  2554. ...
  2555. ma_lpf_process_pcm_frames(&lpf, pFramesOut, pFramesIn, frameCount);
  2556. ```
  2557. Supported formats are `ma_format_s16` and` ma_format_f32`. If you need to use a different format
  2558. you need to convert it yourself beforehand. Input and output frames are always interleaved.
  2559. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2560. buffers, like so:
  2561. ```c
  2562. ma_lpf_process_pcm_frames(&lpf, pMyData, pMyData, frameCount);
  2563. ```
  2564. The maximum filter order is limited to `MA_MAX_FILTER_ORDER` which is set to 8. If you need more,
  2565. you can chain first and second order filters together.
  2566. ```c
  2567. for (iFilter = 0; iFilter < filterCount; iFilter += 1) {
  2568. ma_lpf2_process_pcm_frames(&lpf2[iFilter], pMyData, pMyData, frameCount);
  2569. }
  2570. ```
  2571. If you need to change the configuration of the filter, but need to maintain the state of internal
  2572. registers you can do so with `ma_lpf_reinit()`. This may be useful if you need to change the sample
  2573. rate and/or cutoff frequency dynamically while maintaining smooth transitions. Note that changing the
  2574. format or channel count after initialization is invalid and will result in an error.
  2575. The `ma_lpf` object supports a configurable order, but if you only need a first order filter you
  2576. may want to consider using `ma_lpf1`. Likewise, if you only need a second order filter you can use
  2577. `ma_lpf2`. The advantage of this is that they're lighter weight and a bit more efficient.
  2578. If an even filter order is specified, a series of second order filters will be processed in a
  2579. chain. If an odd filter order is specified, a first order filter will be applied, followed by a
  2580. series of second order filters in a chain.
  2581. 11.3. High-Pass Filtering
  2582. -------------------------
  2583. High-pass filtering is achieved with the following APIs:
  2584. +---------+-------------------------------------------+
  2585. | API | Description |
  2586. +---------+-------------------------------------------+
  2587. | ma_hpf1 | First order high-pass filter |
  2588. | ma_hpf2 | Second order high-pass filter |
  2589. | ma_hpf | High order high-pass filter (Butterworth) |
  2590. +---------+-------------------------------------------+
  2591. High-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_hpf1`,
  2592. `ma_hpf2` and `ma_hpf`. See example code for low-pass filters for example usage.
  2593. 11.4. Band-Pass Filtering
  2594. -------------------------
  2595. Band-pass filtering is achieved with the following APIs:
  2596. +---------+-------------------------------+
  2597. | API | Description |
  2598. +---------+-------------------------------+
  2599. | ma_bpf2 | Second order band-pass filter |
  2600. | ma_bpf | High order band-pass filter |
  2601. +---------+-------------------------------+
  2602. Band-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_bpf2` and
  2603. `ma_hpf`. See example code for low-pass filters for example usage. Note that the order for
  2604. band-pass filters must be an even number which means there is no first order band-pass filter,
  2605. unlike low-pass and high-pass filters.
  2606. 11.5. Notch Filtering
  2607. ---------------------
  2608. Notch filtering is achieved with the following APIs:
  2609. +-----------+------------------------------------------+
  2610. | API | Description |
  2611. +-----------+------------------------------------------+
  2612. | ma_notch2 | Second order notching filter |
  2613. +-----------+------------------------------------------+
  2614. 11.6. Peaking EQ Filtering
  2615. -------------------------
  2616. Peaking filtering is achieved with the following APIs:
  2617. +----------+------------------------------------------+
  2618. | API | Description |
  2619. +----------+------------------------------------------+
  2620. | ma_peak2 | Second order peaking filter |
  2621. +----------+------------------------------------------+
  2622. 11.7. Low Shelf Filtering
  2623. -------------------------
  2624. Low shelf filtering is achieved with the following APIs:
  2625. +-------------+------------------------------------------+
  2626. | API | Description |
  2627. +-------------+------------------------------------------+
  2628. | ma_loshelf2 | Second order low shelf filter |
  2629. +-------------+------------------------------------------+
  2630. Where a high-pass filter is used to eliminate lower frequencies, a low shelf filter can be used to
  2631. just turn them down rather than eliminate them entirely.
  2632. 11.8. High Shelf Filtering
  2633. --------------------------
  2634. High shelf filtering is achieved with the following APIs:
  2635. +-------------+------------------------------------------+
  2636. | API | Description |
  2637. +-------------+------------------------------------------+
  2638. | ma_hishelf2 | Second order high shelf filter |
  2639. +-------------+------------------------------------------+
  2640. The high shelf filter has the same API as the low shelf filter, only you would use `ma_hishelf`
  2641. instead of `ma_loshelf`. Where a low shelf filter is used to adjust the volume of low frequencies,
  2642. the high shelf filter does the same thing for high frequencies.
  2643. 12. Waveform and Noise Generation
  2644. =================================
  2645. 12.1. Waveforms
  2646. ---------------
  2647. miniaudio supports generation of sine, square, triangle and sawtooth waveforms. This is achieved
  2648. with the `ma_waveform` API. Example:
  2649. ```c
  2650. ma_waveform_config config = ma_waveform_config_init(
  2651. FORMAT,
  2652. CHANNELS,
  2653. SAMPLE_RATE,
  2654. ma_waveform_type_sine,
  2655. amplitude,
  2656. frequency);
  2657. ma_waveform waveform;
  2658. ma_result result = ma_waveform_init(&config, &waveform);
  2659. if (result != MA_SUCCESS) {
  2660. // Error.
  2661. }
  2662. ...
  2663. ma_waveform_read_pcm_frames(&waveform, pOutput, frameCount);
  2664. ```
  2665. The amplitude, frequency, type, and sample rate can be changed dynamically with
  2666. `ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()`, `ma_waveform_set_type()`, and
  2667. `ma_waveform_set_sample_rate()` respectively.
  2668. You can invert the waveform by setting the amplitude to a negative value. You can use this to
  2669. control whether or not a sawtooth has a positive or negative ramp, for example.
  2670. Below are the supported waveform types:
  2671. +---------------------------+
  2672. | Enum Name |
  2673. +---------------------------+
  2674. | ma_waveform_type_sine |
  2675. | ma_waveform_type_square |
  2676. | ma_waveform_type_triangle |
  2677. | ma_waveform_type_sawtooth |
  2678. +---------------------------+
  2679. 12.2. Noise
  2680. -----------
  2681. miniaudio supports generation of white, pink and Brownian noise via the `ma_noise` API. Example:
  2682. ```c
  2683. ma_noise_config config = ma_noise_config_init(
  2684. FORMAT,
  2685. CHANNELS,
  2686. ma_noise_type_white,
  2687. SEED,
  2688. amplitude);
  2689. ma_noise noise;
  2690. ma_result result = ma_noise_init(&config, &noise);
  2691. if (result != MA_SUCCESS) {
  2692. // Error.
  2693. }
  2694. ...
  2695. ma_noise_read_pcm_frames(&noise, pOutput, frameCount);
  2696. ```
  2697. The noise API uses simple LCG random number generation. It supports a custom seed which is useful
  2698. for things like automated testing requiring reproducibility. Setting the seed to zero will default
  2699. to `MA_DEFAULT_LCG_SEED`.
  2700. The amplitude and seed can be changed dynamically with `ma_noise_set_amplitude()` and
  2701. `ma_noise_set_seed()` respectively.
  2702. By default, the noise API will use different values for different channels. So, for example, the
  2703. left side in a stereo stream will be different to the right side. To instead have each channel use
  2704. the same random value, set the `duplicateChannels` member of the noise config to true, like so:
  2705. ```c
  2706. config.duplicateChannels = MA_TRUE;
  2707. ```
  2708. Below are the supported noise types.
  2709. +------------------------+
  2710. | Enum Name |
  2711. +------------------------+
  2712. | ma_noise_type_white |
  2713. | ma_noise_type_pink |
  2714. | ma_noise_type_brownian |
  2715. +------------------------+
  2716. 13. Audio Buffers
  2717. =================
  2718. miniaudio supports reading from a buffer of raw audio data via the `ma_audio_buffer` API. This can
  2719. read from memory that's managed by the application, but can also handle the memory management for
  2720. you internally. Memory management is flexible and should support most use cases.
  2721. Audio buffers are initialized using the standard configuration system used everywhere in miniaudio:
  2722. ```c
  2723. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2724. format,
  2725. channels,
  2726. sizeInFrames,
  2727. pExistingData,
  2728. &allocationCallbacks);
  2729. ma_audio_buffer buffer;
  2730. result = ma_audio_buffer_init(&config, &buffer);
  2731. if (result != MA_SUCCESS) {
  2732. // Error.
  2733. }
  2734. ...
  2735. ma_audio_buffer_uninit(&buffer);
  2736. ```
  2737. In the example above, the memory pointed to by `pExistingData` will *not* be copied and is how an
  2738. application can do self-managed memory allocation. If you would rather make a copy of the data, use
  2739. `ma_audio_buffer_init_copy()`. To uninitialize the buffer, use `ma_audio_buffer_uninit()`.
  2740. Sometimes it can be convenient to allocate the memory for the `ma_audio_buffer` structure and the
  2741. raw audio data in a contiguous block of memory. That is, the raw audio data will be located
  2742. immediately after the `ma_audio_buffer` structure. To do this, use
  2743. `ma_audio_buffer_alloc_and_init()`:
  2744. ```c
  2745. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2746. format,
  2747. channels,
  2748. sizeInFrames,
  2749. pExistingData,
  2750. &allocationCallbacks);
  2751. ma_audio_buffer* pBuffer
  2752. result = ma_audio_buffer_alloc_and_init(&config, &pBuffer);
  2753. if (result != MA_SUCCESS) {
  2754. // Error
  2755. }
  2756. ...
  2757. ma_audio_buffer_uninit_and_free(&buffer);
  2758. ```
  2759. If you initialize the buffer with `ma_audio_buffer_alloc_and_init()` you should uninitialize it
  2760. with `ma_audio_buffer_uninit_and_free()`. In the example above, the memory pointed to by
  2761. `pExistingData` will be copied into the buffer, which is contrary to the behavior of
  2762. `ma_audio_buffer_init()`.
  2763. An audio buffer has a playback cursor just like a decoder. As you read frames from the buffer, the
  2764. cursor moves forward. The last parameter (`loop`) can be used to determine if the buffer should
  2765. loop. The return value is the number of frames actually read. If this is less than the number of
  2766. frames requested it means the end has been reached. This should never happen if the `loop`
  2767. parameter is set to true. If you want to manually loop back to the start, you can do so with with
  2768. `ma_audio_buffer_seek_to_pcm_frame(pAudioBuffer, 0)`. Below is an example for reading data from an
  2769. audio buffer.
  2770. ```c
  2771. ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames(pAudioBuffer, pFramesOut, desiredFrameCount, isLooping);
  2772. if (framesRead < desiredFrameCount) {
  2773. // If not looping, this means the end has been reached. This should never happen in looping mode with valid input.
  2774. }
  2775. ```
  2776. Sometimes you may want to avoid the cost of data movement between the internal buffer and the
  2777. output buffer. Instead you can use memory mapping to retrieve a pointer to a segment of data:
  2778. ```c
  2779. void* pMappedFrames;
  2780. ma_uint64 frameCount = frameCountToTryMapping;
  2781. ma_result result = ma_audio_buffer_map(pAudioBuffer, &pMappedFrames, &frameCount);
  2782. if (result == MA_SUCCESS) {
  2783. // Map was successful. The value in frameCount will be how many frames were _actually_ mapped, which may be
  2784. // less due to the end of the buffer being reached.
  2785. ma_copy_pcm_frames(pFramesOut, pMappedFrames, frameCount, pAudioBuffer->format, pAudioBuffer->channels);
  2786. // You must unmap the buffer.
  2787. ma_audio_buffer_unmap(pAudioBuffer, frameCount);
  2788. }
  2789. ```
  2790. When you use memory mapping, the read cursor is increment by the frame count passed in to
  2791. `ma_audio_buffer_unmap()`. If you decide not to process every frame you can pass in a value smaller
  2792. than the value returned by `ma_audio_buffer_map()`. The disadvantage to using memory mapping is
  2793. that it does not handle looping for you. You can determine if the buffer is at the end for the
  2794. purpose of looping with `ma_audio_buffer_at_end()` or by inspecting the return value of
  2795. `ma_audio_buffer_unmap()` and checking if it equals `MA_AT_END`. You should not treat `MA_AT_END`
  2796. as an error when returned by `ma_audio_buffer_unmap()`.
  2797. 14. Ring Buffers
  2798. ================
  2799. miniaudio supports lock free (single producer, single consumer) ring buffers which are exposed via
  2800. the `ma_rb` and `ma_pcm_rb` APIs. The `ma_rb` API operates on bytes, whereas the `ma_pcm_rb`
  2801. operates on PCM frames. They are otherwise identical as `ma_pcm_rb` is just a wrapper around
  2802. `ma_rb`.
  2803. Unlike most other APIs in miniaudio, ring buffers support both interleaved and deinterleaved
  2804. streams. The caller can also allocate their own backing memory for the ring buffer to use
  2805. internally for added flexibility. Otherwise the ring buffer will manage it's internal memory for
  2806. you.
  2807. The examples below use the PCM frame variant of the ring buffer since that's most likely the one
  2808. you will want to use. To initialize a ring buffer, do something like the following:
  2809. ```c
  2810. ma_pcm_rb rb;
  2811. ma_result result = ma_pcm_rb_init(FORMAT, CHANNELS, BUFFER_SIZE_IN_FRAMES, NULL, NULL, &rb);
  2812. if (result != MA_SUCCESS) {
  2813. // Error
  2814. }
  2815. ```
  2816. The `ma_pcm_rb_init()` function takes the sample format and channel count as parameters because
  2817. it's the PCM variant of the ring buffer API. For the regular ring buffer that operates on bytes you
  2818. would call `ma_rb_init()` which leaves these out and just takes the size of the buffer in bytes
  2819. instead of frames. The fourth parameter is an optional pre-allocated buffer and the fifth parameter
  2820. is a pointer to a `ma_allocation_callbacks` structure for custom memory allocation routines.
  2821. Passing in `NULL` for this results in `MA_MALLOC()` and `MA_FREE()` being used.
  2822. Use `ma_pcm_rb_init_ex()` if you need a deinterleaved buffer. The data for each sub-buffer is
  2823. offset from each other based on the stride. To manage your sub-buffers you can use
  2824. `ma_pcm_rb_get_subbuffer_stride()`, `ma_pcm_rb_get_subbuffer_offset()` and
  2825. `ma_pcm_rb_get_subbuffer_ptr()`.
  2826. Use `ma_pcm_rb_acquire_read()` and `ma_pcm_rb_acquire_write()` to retrieve a pointer to a section
  2827. of the ring buffer. You specify the number of frames you need, and on output it will set to what
  2828. was actually acquired. If the read or write pointer is positioned such that the number of frames
  2829. requested will require a loop, it will be clamped to the end of the buffer. Therefore, the number
  2830. of frames you're given may be less than the number you requested.
  2831. After calling `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()`, you do your work on the
  2832. buffer and then "commit" it with `ma_pcm_rb_commit_read()` or `ma_pcm_rb_commit_write()`. This is
  2833. where the read/write pointers are updated. When you commit you need to pass in the buffer that was
  2834. returned by the earlier call to `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()` and is
  2835. only used for validation. The number of frames passed to `ma_pcm_rb_commit_read()` and
  2836. `ma_pcm_rb_commit_write()` is what's used to increment the pointers, and can be less that what was
  2837. originally requested.
  2838. If you want to correct for drift between the write pointer and the read pointer you can use a
  2839. combination of `ma_pcm_rb_pointer_distance()`, `ma_pcm_rb_seek_read()` and
  2840. `ma_pcm_rb_seek_write()`. Note that you can only move the pointers forward, and you should only
  2841. move the read pointer forward via the consumer thread, and the write pointer forward by the
  2842. producer thread. If there is too much space between the pointers, move the read pointer forward. If
  2843. there is too little space between the pointers, move the write pointer forward.
  2844. You can use a ring buffer at the byte level instead of the PCM frame level by using the `ma_rb`
  2845. API. This is exactly the same, only you will use the `ma_rb` functions instead of `ma_pcm_rb` and
  2846. instead of frame counts you will pass around byte counts.
  2847. The maximum size of the buffer in bytes is `0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1)` due to the most
  2848. significant bit being used to encode a loop flag and the internally managed buffers always being
  2849. aligned to `MA_SIMD_ALIGNMENT`.
  2850. Note that the ring buffer is only thread safe when used by a single consumer thread and single
  2851. producer thread.
  2852. 15. Backends
  2853. ============
  2854. The following backends are supported by miniaudio. These are listed in order of default priority.
  2855. When no backend is specified when initializing a context or device, miniaudio will attempt to use
  2856. each of these backends in the order listed in the table below.
  2857. Note that backends that are not usable by the build target will not be included in the build. For
  2858. example, ALSA, which is specific to Linux, will not be included in the Windows build.
  2859. +-------------+-----------------------+--------------------------------------------------------+
  2860. | Name | Enum Name | Supported Operating Systems |
  2861. +-------------+-----------------------+--------------------------------------------------------+
  2862. | WASAPI | ma_backend_wasapi | Windows Vista+ |
  2863. | DirectSound | ma_backend_dsound | Windows XP+ |
  2864. | WinMM | ma_backend_winmm | Windows 95+ |
  2865. | Core Audio | ma_backend_coreaudio | macOS, iOS |
  2866. | sndio | ma_backend_sndio | OpenBSD |
  2867. | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
  2868. | OSS | ma_backend_oss | FreeBSD |
  2869. | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
  2870. | ALSA | ma_backend_alsa | Linux |
  2871. | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
  2872. | AAudio | ma_backend_aaudio | Android 8+ |
  2873. | OpenSL ES | ma_backend_opensl | Android (API level 16+) |
  2874. | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
  2875. | Custom | ma_backend_custom | Cross Platform |
  2876. | Null | ma_backend_null | Cross Platform (not used on Web) |
  2877. +-------------+-----------------------+--------------------------------------------------------+
  2878. Some backends have some nuance details you may want to be aware of.
  2879. 15.1. WASAPI
  2880. ------------
  2881. - Low-latency shared mode will be disabled when using an application-defined sample rate which is
  2882. different to the device's native sample rate. To work around this, set `wasapi.noAutoConvertSRC`
  2883. to true in the device config. This is due to IAudioClient3_InitializeSharedAudioStream() failing
  2884. when the `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` flag is specified. Setting wasapi.noAutoConvertSRC
  2885. will result in miniaudio's internal resampler being used instead which will in turn enable the
  2886. use of low-latency shared mode.
  2887. 15.2. PulseAudio
  2888. ----------------
  2889. - If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki:
  2890. https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling.
  2891. Alternatively, consider using a different backend such as ALSA.
  2892. 15.3. Android
  2893. -------------
  2894. - To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest:
  2895. `<uses-permission android:name="android.permission.RECORD_AUDIO" />`
  2896. - With OpenSL|ES, only a single ma_context can be active at any given time. This is due to a
  2897. limitation with OpenSL|ES.
  2898. - With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration
  2899. API (devices are enumerated through Java). You can however perform your own device enumeration
  2900. through Java and then set the ID in the ma_device_id structure (ma_device_id.aaudio) and pass it
  2901. to ma_device_init().
  2902. - The backend API will perform resampling where possible. The reason for this as opposed to using
  2903. miniaudio's built-in resampler is to take advantage of any potential device-specific
  2904. optimizations the driver may implement.
  2905. BSD
  2906. ---
  2907. - The sndio backend is currently only enabled on OpenBSD builds.
  2908. - The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can
  2909. use it.
  2910. 15.4. UWP
  2911. ---------
  2912. - UWP only supports default playback and capture devices.
  2913. - UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest):
  2914. ```
  2915. <Package ...>
  2916. ...
  2917. <Capabilities>
  2918. <DeviceCapability Name="microphone" />
  2919. </Capabilities>
  2920. </Package>
  2921. ```
  2922. 15.5. Web Audio / Emscripten
  2923. ----------------------------
  2924. - You cannot use `-std=c*` compiler flags, nor `-ansi`. This only applies to the Emscripten build.
  2925. - The first time a context is initialized it will create a global object called "miniaudio" whose
  2926. primary purpose is to act as a factory for device objects.
  2927. - Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as
  2928. they've been deprecated.
  2929. - Google has implemented a policy in their browsers that prevent automatic media output without
  2930. first receiving some kind of user input. The following web page has additional details:
  2931. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting the device
  2932. may fail if you try to start playback without first handling some kind of user input.
  2933. 16. Optimization Tips
  2934. =====================
  2935. See below for some tips on improving performance.
  2936. 16.1. Low Level API
  2937. -------------------
  2938. - In the data callback, if your data is already clipped prior to copying it into the output buffer,
  2939. set the `noClip` config option in the device config to true. This will disable miniaudio's built
  2940. in clipping function.
  2941. - By default, miniaudio will pre-silence the data callback's output buffer. If you know that you
  2942. will always write valid data to the output buffer you can disable pre-silencing by setting the
  2943. `noPreSilence` config option in the device config to true.
  2944. 16.2. High Level API
  2945. --------------------
  2946. - If a sound does not require doppler or pitch shifting, consider disabling pitching by
  2947. initializing the sound with the `MA_SOUND_FLAG_NO_PITCH` flag.
  2948. - If a sound does not require spatialization, disable it by initializing the sound with the
  2949. `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. It can be re-enabled again post-initialization with
  2950. `ma_sound_set_spatialization_enabled()`.
  2951. - If you know all of your sounds will always be the same sample rate, set the engine's sample
  2952. rate to match that of the sounds. Likewise, if you're using a self-managed resource manager,
  2953. consider setting the decoded sample rate to match your sounds. By configuring everything to
  2954. use a consistent sample rate, sample rate conversion can be avoided.
  2955. 17. Miscellaneous Notes
  2956. =======================
  2957. - Automatic stream routing is enabled on a per-backend basis. Support is explicitly enabled for
  2958. WASAPI and Core Audio, however other backends such as PulseAudio may naturally support it, though
  2959. not all have been tested.
  2960. - When compiling with VC6 and earlier, decoding is restricted to files less than 2GB in size. This
  2961. is due to 64-bit file APIs not being available.
  2962. */