Debian Codegraph @

examples/engine_steamaudio.c

raw symbols SCIP
1 /*
2 Demonstrates integration of Steam Audio with miniaudio's engine API.
3
4 In this example a HRTF effect from Steam Audio will be applied. To do this a custom node will be
5 implemented which uses Steam Audio's IPLBinauralEffect and IPLHRTF objects.
6
7 By implementing this as a node, it can be plugged into any position within the graph. The output
8 channel count of this node is always stereo.
9
10 Steam Audio requires fixed sized processing, the size of which must be specified at initialization
11 time of the IPLBinauralEffect and IPLHRTF objects. To ensure miniaudio and Steam Audio are
12 consistent, you must set the period size in the engine config to be consistent with the frame size
13 you specify in your IPLAudioSettings object. If for some reason you want the period size of the
14 engine to be different to that of your Steam Audio configuration, you'll need to implement a sort
15 of buffering solution to your node.
16 */
17 #include "../miniaudio.c"
18
19 #include <stdint.h> /* Required for uint32_t which is used by STEAMAUDIO_VERSION, and a random use of uint8_t. If there's a Steam Audio maintainer reading this, that needs to be fixed to use IPLuint32 and IPLuint8. */
20
21 /* Need to silence some warnings from the Steam Audio headers. */
22 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
23 #pragma GCC diagnostic push
24 #pragma GCC diagnostic ignored "-Wlong-long"
25 #pragma GCC diagnostic ignored "-Wpedantic"
26 #endif
27 #include <phonon.h> /* Steam Audio */
28 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
29 #pragma GCC diagnostic pop
30 #endif
31
32 #define FORMAT ma_format_f32 /* Must be floating point. */
33 #define CHANNELS 2 /* Must be stereo for this example. */
34 #define SAMPLE_RATE 48000
35
36
37 static ma_result ma_result_from_IPLerror(IPLerror error)
38 {
39 switch (error)
40 {
41 case IPL_STATUS_SUCCESS: return MA_SUCCESS;
42 case IPL_STATUS_OUTOFMEMORY: return MA_OUT_OF_MEMORY;
43 case IPL_STATUS_INITIALIZATION:
44 case IPL_STATUS_FAILURE:
45 default: return MA_ERROR;
46 }
47 }
48
49
50 typedef struct
51 {
52 ma_node_config nodeConfig;
53 ma_uint32 channelsIn;
54 IPLAudioSettings iplAudioSettings;
55 IPLContext iplContext;
56 IPLHRTF iplHRTF; /* There is one HRTF object to many binaural effect objects. */
57 } ma_steamaudio_binaural_node_config;
58
59 MA_API ma_steamaudio_binaural_node_config ma_steamaudio_binaural_node_config_init(ma_uint32 channelsIn, IPLAudioSettings iplAudioSettings, IPLContext iplContext, IPLHRTF iplHRTF);
60
61
62 typedef struct
63 {
64 ma_node_base baseNode;
65 IPLAudioSettings iplAudioSettings;
66 IPLContext iplContext;
67 IPLHRTF iplHRTF;
68 IPLBinauralEffect iplEffect;
69 ma_vec3f direction;
70 float* ppBuffersIn[2]; /* Each buffer is an offset of _pHeap. */
71 float* ppBuffersOut[2]; /* Each buffer is an offset of _pHeap. */
72 void* _pHeap;
73 } ma_steamaudio_binaural_node;
74
75 MA_API ma_result ma_steamaudio_binaural_node_init(ma_node_graph* pNodeGraph, const ma_steamaudio_binaural_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_steamaudio_binaural_node* pBinauralNode);
76 MA_API void ma_steamaudio_binaural_node_uninit(ma_steamaudio_binaural_node* pBinauralNode, const ma_allocation_callbacks* pAllocationCallbacks);
77 MA_API ma_result ma_steamaudio_binaural_node_set_direction(ma_steamaudio_binaural_node* pBinauralNode, float x, float y, float z);
78
79
80 MA_API ma_steamaudio_binaural_node_config ma_steamaudio_binaural_node_config_init(ma_uint32 channelsIn, IPLAudioSettings iplAudioSettings, IPLContext iplContext, IPLHRTF iplHRTF)
81 {
82 ma_steamaudio_binaural_node_config config;
83
84 MA_ZERO_OBJECT(&config);
85 config.nodeConfig = ma_node_config_init();
86 config.channelsIn = channelsIn;
87 config.iplAudioSettings = iplAudioSettings;
88 config.iplContext = iplContext;
89 config.iplHRTF = iplHRTF;
90
91 return config;
92 }
93
94
95 static void ma_steamaudio_binaural_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
96 {
97 ma_steamaudio_binaural_node* pBinauralNode = (ma_steamaudio_binaural_node*)pNode;
98 IPLBinauralEffectParams binauralParams;
99 IPLAudioBuffer inputBufferDesc;
100 IPLAudioBuffer outputBufferDesc;
101 ma_uint32 totalFramesToProcess = *pFrameCountOut;
102 ma_uint32 totalFramesProcessed = 0;
103
104 MA_ZERO_OBJECT(&binauralParams);
105 binauralParams.direction.x = pBinauralNode->direction.x;
106 binauralParams.direction.y = pBinauralNode->direction.y;
107 binauralParams.direction.z = pBinauralNode->direction.z;
108 binauralParams.interpolation = IPL_HRTFINTERPOLATION_NEAREST;
109 binauralParams.spatialBlend = 1.0f;
110 binauralParams.hrtf = pBinauralNode->iplHRTF;
111
112 inputBufferDesc.numChannels = (IPLint32)ma_node_get_input_channels(pNode, 0);
113
114 /* We'll run this in a loop just in case our deinterleaved buffers are too small. */
115 outputBufferDesc.numSamples = pBinauralNode->iplAudioSettings.frameSize;
116 outputBufferDesc.numChannels = 2;
117 outputBufferDesc.data = pBinauralNode->ppBuffersOut;
118
119 while (totalFramesProcessed < totalFramesToProcess) {
120 ma_uint32 framesToProcessThisIteration = totalFramesToProcess - totalFramesProcessed;
121 if (framesToProcessThisIteration > (ma_uint32)pBinauralNode->iplAudioSettings.frameSize) {
122 framesToProcessThisIteration = (ma_uint32)pBinauralNode->iplAudioSettings.frameSize;
123 }
124
125 if (inputBufferDesc.numChannels == 1) {
126 /* Fast path. No need for deinterleaving since it's a mono stream. */
127 pBinauralNode->ppBuffersIn[0] = (float*)ma_offset_pcm_frames_const_ptr_f32(ppFramesIn[0], totalFramesProcessed, 1);
128 } else {
129 /* Slow path. Need to deinterleave the input data. */
130 ma_deinterleave_pcm_frames(ma_format_f32, inputBufferDesc.numChannels, framesToProcessThisIteration, ma_offset_pcm_frames_const_ptr_f32(ppFramesIn[0], totalFramesProcessed, inputBufferDesc.numChannels), (void**)&pBinauralNode->ppBuffersIn[0]);
131 }
132
133 inputBufferDesc.data = pBinauralNode->ppBuffersIn;
134 inputBufferDesc.numSamples = (IPLint32)framesToProcessThisIteration;
135
136 /* Apply the effect. */
137 iplBinauralEffectApply(pBinauralNode->iplEffect, &binauralParams, &inputBufferDesc, &outputBufferDesc);
138
139 /* Interleave straight into the output buffer. */
140 ma_interleave_pcm_frames(ma_format_f32, 2, framesToProcessThisIteration, (const void**)&pBinauralNode->ppBuffersOut[0], ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesProcessed, 2));
141
142 /* Advance. */
143 totalFramesProcessed += framesToProcessThisIteration;
144 }
145
146 (void)pFrameCountIn; /* Unused. */
147 }
148
149 static ma_node_vtable g_ma_steamaudio_binaural_node_vtable =
150 {
151 ma_steamaudio_binaural_node_process_pcm_frames,
152 NULL,
153 1, /* 1 input channel. */
154 1, /* 1 output channel. */
155 0
156 };
157
158 MA_API ma_result ma_steamaudio_binaural_node_init(ma_node_graph* pNodeGraph, const ma_steamaudio_binaural_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_steamaudio_binaural_node* pBinauralNode)
159 {
160 ma_result result;
161 ma_node_config baseConfig;
162 ma_uint32 channelsIn;
163 ma_uint32 channelsOut;
164 IPLBinauralEffectSettings iplBinauralEffectSettings;
165 size_t heapSizeInBytes;
166
167 if (pBinauralNode == NULL) {
168 return MA_INVALID_ARGS;
169 }
170
171 MA_ZERO_OBJECT(pBinauralNode);
172
173 if (pConfig == NULL || pConfig->iplAudioSettings.frameSize == 0 || pConfig->iplContext == NULL || pConfig->iplHRTF == NULL) {
174 return MA_INVALID_ARGS;
175 }
176
177 /* Steam Audio only supports mono and stereo input. */
178 if (pConfig->channelsIn < 1 || pConfig->channelsIn > 2) {
179 return MA_INVALID_ARGS;
180 }
181
182 channelsIn = pConfig->channelsIn;
183 channelsOut = 2; /* Always stereo output. */
184
185 baseConfig = ma_node_config_init();
186 baseConfig.vtable = &g_ma_steamaudio_binaural_node_vtable;
187 baseConfig.pInputChannels = &channelsIn;
188 baseConfig.pOutputChannels = &channelsOut;
189 result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pBinauralNode->baseNode);
190 if (result != MA_SUCCESS) {
191 return result;
192 }
193
194 pBinauralNode->iplAudioSettings = pConfig->iplAudioSettings;
195 pBinauralNode->iplContext = pConfig->iplContext;
196 pBinauralNode->iplHRTF = pConfig->iplHRTF;
197
198 MA_ZERO_OBJECT(&iplBinauralEffectSettings);
199 iplBinauralEffectSettings.hrtf = pBinauralNode->iplHRTF;
200
201 result = ma_result_from_IPLerror(iplBinauralEffectCreate(pBinauralNode->iplContext, &pBinauralNode->iplAudioSettings, &iplBinauralEffectSettings, &pBinauralNode->iplEffect));
202 if (result != MA_SUCCESS) {
203 ma_node_uninit(&pBinauralNode->baseNode, pAllocationCallbacks);
204 return result;
205 }
206
207 heapSizeInBytes = 0;
208
209 /*
210 Unfortunately Steam Audio uses deinterleaved buffers for everything so we'll need to use some
211 intermediary buffers. We'll allocate one big buffer on the heap and then use offsets. We'll
212 use the frame size from the IPLAudioSettings structure as a basis for the size of the buffer.
213 */
214 heapSizeInBytes += sizeof(float) * channelsOut * pBinauralNode->iplAudioSettings.frameSize; /* Output buffer. */
215 heapSizeInBytes += sizeof(float) * channelsIn * pBinauralNode->iplAudioSettings.frameSize; /* Input buffer. */
216
217 pBinauralNode->_pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
218 if (pBinauralNode->_pHeap == NULL) {
219 iplBinauralEffectRelease(&pBinauralNode->iplEffect);
220 ma_node_uninit(&pBinauralNode->baseNode, pAllocationCallbacks);
221 return MA_OUT_OF_MEMORY;
222 }
223
224 pBinauralNode->ppBuffersOut[0] = (float*)pBinauralNode->_pHeap;
225 pBinauralNode->ppBuffersOut[1] = (float*)ma_offset_ptr(pBinauralNode->_pHeap, sizeof(float) * pBinauralNode->iplAudioSettings.frameSize);
226
227 {
228 ma_uint32 iChannelIn;
229 for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
230 pBinauralNode->ppBuffersIn[iChannelIn] = (float*)ma_offset_ptr(pBinauralNode->_pHeap, sizeof(float) * pBinauralNode->iplAudioSettings.frameSize * (channelsOut + iChannelIn));
231 }
232 }
233
234 return MA_SUCCESS;
235 }
236
237 MA_API void ma_steamaudio_binaural_node_uninit(ma_steamaudio_binaural_node* pBinauralNode, const ma_allocation_callbacks* pAllocationCallbacks)
238 {
239 if (pBinauralNode == NULL) {
240 return;
241 }
242
243 /* The base node is always uninitialized first. */
244 ma_node_uninit(&pBinauralNode->baseNode, pAllocationCallbacks);
245
246 /*
247 The Steam Audio objects are deleted after the base node. This ensures the base node is removed from the graph
248 first to ensure these objects aren't getting used by the audio thread.
249 */
250 iplBinauralEffectRelease(&pBinauralNode->iplEffect);
251 ma_free(pBinauralNode->_pHeap, pAllocationCallbacks);
252 }
253
254 MA_API ma_result ma_steamaudio_binaural_node_set_direction(ma_steamaudio_binaural_node* pBinauralNode, float x, float y, float z)
255 {
256 if (pBinauralNode == NULL) {
257 return MA_INVALID_ARGS;
258 }
259
260 pBinauralNode->direction.x = x;
261 pBinauralNode->direction.y = y;
262 pBinauralNode->direction.z = z;
263
264 return MA_SUCCESS;
265 }
266
267
268
269
270 static ma_engine g_engine;
271 static ma_sound g_sound; /* This example will play only a single sound at once, so we only need one `ma_sound` object. */
272 static ma_steamaudio_binaural_node g_binauralNode; /* The echo effect is achieved using a delay node. */
273
274 int main(int argc, char** argv)
275 {
276 ma_result result;
277 ma_engine_config engineConfig;
278 IPLAudioSettings iplAudioSettings;
279 IPLContextSettings iplContextSettings;
280 IPLContext iplContext;
281 IPLHRTFSettings iplHRTFSettings;
282 IPLHRTF iplHRTF;
283
284 if (argc < 2) {
285 printf("No input file.");
286 return -1;
287 }
288
289 /* The engine needs to be initialized first. */
290 engineConfig = ma_engine_config_init();
291 engineConfig.channels = CHANNELS;
292 engineConfig.sampleRate = SAMPLE_RATE;
293
294 /*
295 Steam Audio requires processing in fixed sized chunks. Setting the period size in the engine config will
296 ensure our updates happen in predicably sized chunks as required by Steam Audio.
297
298 Note that the configuration of Steam Audio below (IPLAudioSettings) will use this variable to specify the
299 update size to ensure it remains consistent.
300 */
301 engineConfig.periodSizeInFrames = 256;
302
303 result = ma_engine_init(&engineConfig, &g_engine);
304 if (result != MA_SUCCESS) {
305 printf("Failed to initialize audio engine.");
306 return -1;
307 }
308
309 /*
310 Now that we have the engine we can initialize the Steam Audio objects.
311 */
312 MA_ZERO_OBJECT(&iplAudioSettings);
313 iplAudioSettings.samplingRate = ma_engine_get_sample_rate(&g_engine);
314
315 /*
316 If there's any Steam Audio developers reading this, why is the frame size needed? This needs to
317 be documented. If this is for some kind of buffer management with FFT or something, then this
318 need not be exposed to the public API. There should be no need for the public API to require a
319 fixed sized update.
320
321 It's important that this be set to the periodSizeInFrames specified in the engine config above.
322 This ensures updates on both the miniaudio side and the Steam Audio side are consistent.
323 */
324 iplAudioSettings.frameSize = engineConfig.periodSizeInFrames;
325
326
327 /* IPLContext */
328 MA_ZERO_OBJECT(&iplContextSettings);
329 iplContextSettings.version = STEAMAUDIO_VERSION;
330
331 result = ma_result_from_IPLerror(iplContextCreate(&iplContextSettings, &iplContext));
332 if (result != MA_SUCCESS) {
333 ma_engine_uninit(&g_engine);
334 return result;
335 }
336
337
338 /* IPLHRTF */
339 MA_ZERO_OBJECT(&iplHRTFSettings);
340 iplHRTFSettings.type = IPL_HRTFTYPE_DEFAULT;
341 iplHRTFSettings.volume = 1;
342
343 result = ma_result_from_IPLerror(iplHRTFCreate(iplContext, &iplAudioSettings, &iplHRTFSettings, &iplHRTF));
344 if (result != MA_SUCCESS) {
345 iplContextRelease(&iplContext);
346 ma_engine_uninit(&g_engine);
347 return result;
348 }
349
350
351 /*
352 The binaural node will need to know the input channel count of the sound so we'll need to load
353 the sound first. We'll initialize this such that it'll be initially detached from the graph.
354 It will be attached to the graph after the binaural node is initialized.
355 */
356 {
357 ma_sound_config soundConfig;
358
359 soundConfig = ma_sound_config_init();
360 soundConfig.pFilePath = argv[1];
361 soundConfig.flags = MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT; /* We'll attach this to the graph later. */
362
363 result = ma_sound_init_ex(&g_engine, &soundConfig, &g_sound);
364 if (result != MA_SUCCESS) {
365 return result;
366 }
367
368 /* We'll let the Steam Audio binaural effect do the directional attenuation for us. */
369 ma_sound_set_directional_attenuation_factor(&g_sound, 0);
370
371 /* Loop the sound so we can get a continuous sound. */
372 ma_sound_set_looping(&g_sound, MA_TRUE);
373 }
374
375
376 /*
377 We'll build our graph starting from the end so initialize the binaural node now. The output of
378 this node will be connected straight to the output. You could also attach it to a sound group
379 or any other node that accepts an input.
380
381 Creating a node requires a pointer to the node graph that owns it. The engine itself is a node
382 graph. In the code below we can get a pointer to the node graph with `ma_engine_get_node_graph()`
383 or we could simple cast the engine to a ma_node_graph* like so:
384
385 (ma_node_graph*)&g_engine
386
387 The endpoint of the graph can be retrieved with `ma_engine_get_endpoint()`.
388 */
389 {
390 ma_steamaudio_binaural_node_config binauralNodeConfig;
391
392 /*
393 For this example we're just using the engine's channel count, but a more optimal solution
394 might be to set this to mono if the source data is also mono.
395 */
396 binauralNodeConfig = ma_steamaudio_binaural_node_config_init(CHANNELS, iplAudioSettings, iplContext, iplHRTF);
397
398 result = ma_steamaudio_binaural_node_init(ma_engine_get_node_graph(&g_engine), &binauralNodeConfig, NULL, &g_binauralNode);
399 if (result != MA_SUCCESS) {
400 printf("Failed to initialize binaural node.");
401 return -1;
402 }
403
404 /* Connect the output of the delay node to the input of the endpoint. */
405 ma_node_attach_output_bus(&g_binauralNode, 0, ma_engine_get_endpoint(&g_engine), 0);
406 }
407
408
409 /* We can now wire up the sound to the binaural node and start it. */
410 ma_node_attach_output_bus(&g_sound, 0, &g_binauralNode, 0);
411 ma_sound_start(&g_sound);
412
413 #if 1
414 {
415 /*
416 We'll move the sound around the listener which we'll leave at the origin. We'll then get
417 the direction to the listener and update the binaural node appropriately.
418 */
419 float stepAngle = 0.002f;
420 float angle = 0;
421 float distance = 2;
422
423 for (;;) {
424 double x = ma_cosd(angle) - ma_sind(angle);
425 double y = ma_sind(angle) + ma_cosd(angle);
426 ma_vec3f direction;
427
428 ma_sound_set_position(&g_sound, (float)x * distance, 0, (float)y * distance);
429 direction = ma_sound_get_direction_to_listener(&g_sound);
430
431 /* Update the direction of the sound. */
432 ma_steamaudio_binaural_node_set_direction(&g_binauralNode, direction.x, direction.y, direction.z);
433 angle += stepAngle;
434
435 ma_sleep(1);
436 }
437 }
438 #else
439 printf("Press Enter to quit...");
440 getchar();
441 #endif
442
443 ma_sound_uninit(&g_sound);
444 ma_steamaudio_binaural_node_uninit(&g_binauralNode, NULL);
445 ma_engine_uninit(&g_engine);
446
447 return 0;
448 }