Debian Codegraph @

examples/resource_manager_advanced.c

raw symbols SCIP
1 /*
2 Demonstrates how you can use the resource manager to manage loaded sounds.
3
4 The resource manager can be used to create a data source whose resources are managed internally by miniaudio. The data
5 sources can then be read just like any other data source such as decoders and audio buffers.
6
7 In this example we use the resource manager independently of the `ma_engine` API so that we can demonstrate how it can
8 be used by itself without getting it confused with `ma_engine`.
9
10 The main feature of the resource manager is the ability to decode and stream audio data asynchronously. Asynchronicity
11 is achieved with a job system. The resource manager will issue jobs which are processed by a configurable number of job
12 threads. You can also implement your own custom job threads which this example also demonstrates.
13
14 In this example we show how you can create a data source, mix them with other data sources, configure the number of job
15 threads to manage internally and how to implement your own custom job thread.
16 */
17 #define MA_NO_ENGINE /* We're intentionally not using the ma_engine API here. */
18 #include "../miniaudio.c"
19
20 static ma_resource_manager_data_source g_dataSources[16];
21 static ma_uint32 g_dataSourceCount;
22
23
24 /*
25 TODO: Consider putting these public functions in miniaudio.h. Will depend on ma_mix_pcm_frames_f32()
26 being merged into miniaudio.h (it's currently in miniaudio_engine.h).
27 */
28 static ma_result ma_data_source_read_pcm_frames_f32_ex(ma_data_source* pDataSource, float* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead, ma_format dataSourceFormat, ma_uint32 dataSourceChannels)
29 {
30 /*
31 This function is intended to be used when the format and channel count of the data source is
32 known beforehand. The idea is to avoid overhead due to redundant calls to ma_data_source_get_data_format().
33 */
34 if (dataSourceFormat == ma_format_f32) {
35 /* Fast path. No conversion necessary. */
36 return ma_data_source_read_pcm_frames(pDataSource, pFramesOut, frameCount, pFramesRead);
37 } else {
38 /* Slow path. Conversion necessary. */
39 ma_result result;
40 ma_uint64 totalFramesRead;
41 ma_uint8 temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
42 ma_uint64 tempCapInFrames = sizeof(temp) / ma_get_bytes_per_frame(dataSourceFormat, dataSourceChannels);
43
44 if (pFramesRead != NULL) {
45 *pFramesRead = 0;
46 }
47
48 totalFramesRead = 0;
49 while (totalFramesRead < frameCount) {
50 ma_uint64 framesJustRead;
51 ma_uint64 framesToRead = frameCount - totalFramesRead;
52 if (framesToRead > tempCapInFrames) {
53 framesToRead = tempCapInFrames;
54 }
55
56 result = ma_data_source_read_pcm_frames(pDataSource, temp, framesToRead, &framesJustRead);
57 if (result != MA_SUCCESS) {
58 break;
59 }
60
61 ma_convert_pcm_frames_format(ma_offset_pcm_frames_ptr_f32(pFramesOut, totalFramesRead, dataSourceChannels), ma_format_f32, temp, dataSourceFormat, framesJustRead, dataSourceChannels, ma_dither_mode_none);
62 totalFramesRead += framesJustRead;
63
64 if (result != MA_SUCCESS) {
65 break;
66 }
67 }
68
69 if (pFramesRead != NULL) {
70 *pFramesRead = totalFramesRead;
71 }
72
73 return MA_SUCCESS;
74 }
75 }
76
77 MA_API ma_result ma_data_source_read_pcm_frames_f32(ma_data_source* pDataSource, float* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
78 {
79 ma_result result;
80 ma_format format;
81 ma_uint32 channels;
82
83 result = ma_data_source_get_data_format(pDataSource, &format, &channels, NULL, NULL, 0);
84 if (result != MA_SUCCESS) {
85 return result; /* Failed to retrieve the data format of the data source. */
86 }
87
88 return ma_data_source_read_pcm_frames_f32_ex(pDataSource, pFramesOut, frameCount, pFramesRead, format, channels);
89 }
90
91 MA_API ma_result ma_data_source_read_pcm_frames_and_mix_f32(ma_data_source* pDataSource, float* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead, float volume)
92 {
93 ma_result result;
94 ma_format format;
95 ma_uint32 channels;
96 ma_uint64 totalFramesRead;
97
98 if (pFramesRead != NULL) {
99 *pFramesRead = 0;
100 }
101
102 if (pDataSource == NULL) {
103 return MA_INVALID_ARGS;
104 }
105
106 result = ma_data_source_get_data_format(pDataSource, &format, &channels, NULL, NULL, 0);
107 if (result != MA_SUCCESS) {
108 return result; /* Failed to retrieve the data format of the data source. */
109 }
110
111 totalFramesRead = 0;
112 while (totalFramesRead < frameCount) {
113 float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE/sizeof(float)];
114 ma_uint64 tempCapInFrames = ma_countof(temp) / channels;
115 ma_uint64 framesJustRead;
116 ma_uint64 framesToRead = frameCount - totalFramesRead;
117 if (framesToRead > tempCapInFrames) {
118 framesToRead = tempCapInFrames;
119 }
120
121 result = ma_data_source_read_pcm_frames_f32_ex(pDataSource, temp, framesToRead, &framesJustRead, format, channels);
122
123 ma_mix_pcm_frames_f32(ma_offset_pcm_frames_ptr_f32(pFramesOut, totalFramesRead, channels), temp, framesJustRead, channels, volume);
124 totalFramesRead += framesJustRead;
125
126 if (result != MA_SUCCESS) {
127 break;
128 }
129 }
130
131 if (pFramesRead != NULL) {
132 *pFramesRead = totalFramesRead;
133 }
134
135 return MA_SUCCESS;
136 }
137
138
139 void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
140 {
141 /*
142 In this example we're just going to play our data sources layered on top of each other. This
143 assumes the device's format is f32 and that the buffer is not pre-silenced.
144 */
145 ma_uint32 iDataSource;
146
147 /*
148 If the device was configured with noPreSilencedOutputBuffer then you would need to silence the
149 buffer here, or make sure the first data source to be mixed is copied rather than mixed.
150 */
151 /*ma_silence_pcm_frames(pOutput, frameCount, ma_format_f32, pDevice->playback.channels);*/
152
153 /* For each sound, mix as much data as we can. */
154 for (iDataSource = 0; iDataSource < g_dataSourceCount; iDataSource += 1) {
155 ma_data_source_read_pcm_frames_and_mix_f32(&g_dataSources[iDataSource], (float*)pOutput, frameCount, NULL, /* volume = */1);
156 }
157
158 /* Unused. */
159 (void)pInput;
160 (void)pDevice;
161 }
162
163 static ma_thread_result MA_THREADCALL custom_job_thread(void* pUserData)
164 {
165 ma_resource_manager* pResourceManager = (ma_resource_manager*)pUserData;
166
167 for (;;) {
168 ma_result result;
169 ma_resource_manager_job job;
170
171 /*
172 Retrieve a job from the queue first. This defines what it is you're about to do. By default this will be
173 blocking. You can initialize the resource manager with MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING to not block in
174 which case MA_NO_DATA_AVAILABLE will be returned if no jobs are available.
175
176 When the quit job is returned (MA_RESOURCE_MANAGER_JOB_QUIT), the return value will always be MA_CANCELLED. If you don't want
177 to check the return value (you should), you can instead check if the job code is MA_RESOURCE_MANAGER_JOB_QUIT and use that
178 instead.
179 */
180 result = ma_resource_manager_next_job(pResourceManager, &job);
181 if (result != MA_SUCCESS) {
182 if (result == MA_CANCELLED) {
183 printf("CUSTOM JOB THREAD TERMINATING VIA MA_CANCELLED... ");
184 } else {
185 printf("CUSTOM JOB THREAD ERROR: %s. TERMINATING... ", ma_result_description(result));
186 }
187
188 break;
189 }
190
191 /*
192 Terminate if we got a quit message. You don't need to terminate like this, but's a bit more robust. You can
193 just use a global variable or something similar if it's easier for your particular situation. The quit job
194 remains in the queue and will continue to be returned by future calls to ma_resource_manager_next_job(). The
195 reason for this is to give every job thread visibility to the quit job so they have a chance to exit.
196
197 We won't actually be hitting this code because the call above will return MA_CANCELLED when the MA_RESOURCE_MANAGER_JOB_QUIT
198 event is received which means the `result != MA_SUCCESS` logic above will catch it. If you do not check the
199 return value of ma_resource_manager_next_job() you will want to check for MA_RESOURCE_MANAGER_JOB_QUIT like the code below.
200 */
201 if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) {
202 printf("CUSTOM JOB THREAD TERMINATING VIA MA_JOB_TYPE_QUIT... ");
203 break;
204 }
205
206 /* Call ma_resource_manager_process_job() to actually do the work to process the job. */
207 printf("PROCESSING IN CUSTOM JOB THREAD: %d\n", job.toc.breakup.code);
208 ma_resource_manager_process_job(pResourceManager, &job);
209 }
210
211 printf("TERMINATED\n");
212 return (ma_thread_result)0;
213 }
214
215 int main(int argc, char** argv)
216 {
217 ma_result result;
218 ma_device_config deviceConfig;
219 ma_device device;
220 ma_resource_manager_config resourceManagerConfig;
221 ma_resource_manager resourceManager;
222 ma_thread jobThread;
223 int iFile;
224
225 deviceConfig = ma_device_config_init(ma_device_type_playback);
226 deviceConfig.playback.format = ma_format_f32;
227 deviceConfig.dataCallback = data_callback;
228 deviceConfig.pUserData = NULL;
229
230 result = ma_device_init(NULL, &deviceConfig, &device);
231 if (result != MA_SUCCESS) {
232 printf("Failed to initialize device.");
233 return -1;
234 }
235
236
237 /* We can start the device before loading any sounds. We'll just end up outputting silence. */
238 result = ma_device_start(&device);
239 if (result != MA_SUCCESS) {
240 ma_device_uninit(&device);
241 printf("Failed to start device.");
242 return -1;
243 }
244
245
246 /*
247 We have the device so now we want to initialize the resource manager. We'll use the resource manager to load some
248 sounds based on the command line.
249 */
250 resourceManagerConfig = ma_resource_manager_config_init();
251
252 /*
253 We'll set a standard decoding format to save us to processing time at mixing time. If you're wanting to use
254 spatialization with your decoded sounds, you may want to consider leaving this as 0 to ensure the file's native
255 channel count is used so you can do proper spatialization.
256 */
257 resourceManagerConfig.decodedFormat = device.playback.format;
258 resourceManagerConfig.decodedChannels = device.playback.channels;
259 resourceManagerConfig.decodedSampleRate = device.sampleRate;
260
261 /* The number of job threads to be managed internally. Set this to 0 if you want to self-manage your job threads */
262 resourceManagerConfig.jobThreadCount = 4;
263
264 result = ma_resource_manager_init(&resourceManagerConfig, &resourceManager);
265 if (result != MA_SUCCESS) {
266 ma_device_uninit(&device);
267 printf("Failed to initialize the resource manager.");
268 return -1;
269 }
270
271 /*
272 Now that we have a resource manager we can set up our custom job thread. This is optional. Normally when doing
273 self-managed job threads you would set the internal job thread count to zero. We're doing both internal and
274 self-managed job threads in this example just for demonstration purposes.
275 */
276 ma_thread_create(&jobThread, ma_thread_priority_default, 0, custom_job_thread, &resourceManager, NULL);
277
278 /* Create each data source from the resource manager. Note that the caller is the owner. */
279 for (iFile = 0; iFile < (int)ma_countof(g_dataSources) && iFile < argc-1; iFile += 1) {
280 result = ma_resource_manager_data_source_init(
281 &resourceManager,
282 argv[iFile+1],
283 MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE | MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC /*| MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM*/,
284 NULL, /* Async notification. */
285 &g_dataSources[iFile]);
286
287 if (result != MA_SUCCESS) {
288 break;
289 }
290
291 /* Use looping in this example. */
292 ma_data_source_set_looping(&g_dataSources[iFile], MA_TRUE);
293
294 g_dataSourceCount += 1;
295 }
296
297 printf("Press Enter to quit...");
298 getchar();
299
300
301 /* Teardown. */
302
303 /*
304 Uninitialize the device first to ensure the data callback is stopped and doesn't try to access
305 any data.
306 */
307 ma_device_uninit(&device);
308
309 /*
310 Our data sources need to be explicitly uninitialized. ma_resource_manager_uninit() will not do
311 it for us. This needs to be done before posting the quit event and uninitializing the resource
312 manager or else we'll get stuck in a deadlock because ma_resource_manager_data_source_uninit()
313 will be waiting for the job thread(s) to finish work, which will never happen because they were
314 just terminated.
315 */
316 for (iFile = 0; (size_t)iFile < g_dataSourceCount; iFile += 1) {
317 ma_resource_manager_data_source_uninit(&g_dataSources[iFile]);
318 }
319
320 /*
321 Before uninitializing the resource manager we need to make sure a quit event has been posted to
322 ensure we can get out of our custom thread. The call to ma_resource_manager_uninit() will also
323 do this, but we need to call it explicitly so that our self-managed thread can exit naturally.
324 You only need to post a quit job if you're using that as the exit indicator. You can instead
325 use whatever variable you want to terminate your job thread, but since this example is using a
326 quit job we need to post one. Note that you don't need to do this if you're not managing your
327 own threads - ma_resource_manager_uninit() alone will suffice in that case.
328 */
329 ma_resource_manager_post_job_quit(&resourceManager);
330 ma_thread_wait(&jobThread); /* Wait for the custom job thread to finish so it doesn't try to access any data. */
331
332 /* Uninitialize the resource manager after each data source. */
333 ma_resource_manager_uninit(&resourceManager);
334
335 return 0;
336 }