acbba435c13d0df10a5590fcc935592dac202d98
[vg.git] / src / vg / vg_audio.h
1 // Copyright (C) 2021 Harry Godden (hgn) - All Rights Reserved
2
3 #define MA_NO_GENERATION
4 #define MA_NO_DECODING
5 #define MA_NO_ENCODING
6 #include "dr_soft/miniaudio.h"
7
8 #define STB_VORBIS_MAX_CHANNELS 2
9 #include "stb/stb_vorbis.h"
10
11 #define SFX_MAX_SYSTEMS 32
12 //#define SFX_FLAG_ONESHOT 0x1
13 #define SFX_FLAG_STEREO 0x2
14 #define SFX_FLAG_REPEAT 0x4
15 #define SFX_FLAG_PERSISTENT 0x8
16 #define FADEOUT_LENGTH 4410
17 #define FADEOUT_DIVISOR (1.f/(float)FADEOUT_LENGTH)
18
19 typedef struct sfx_vol_control sfx_vol_control;
20 typedef struct sfx_system sfx_system;
21
22 struct sfx_vol_control
23 {
24 float val;
25 const char *name;
26 };
27
28 struct sfx_system
29 {
30 sfx_system *persisitent_source;
31 int in_queue;
32
33 // Source buffer start
34 float *source, *replacement;
35
36 u32 clip_start, clip_end, buffer_length;
37
38 // Modifiers
39 sfx_vol_control *vol_src;
40 float vol, cvol;
41
42 // Info
43 u32 ch, end, cur;
44 u32 flags;
45
46 // Effects
47 u32 fadeout, fadeout_current;
48
49 // Diagnostic
50 const char *name;
51 };
52
53 // Set of up to 8 sound effects packed into one
54 typedef struct sfx_set sfx_set;
55 struct sfx_set
56 {
57 float *main;
58 char *sources;
59
60 u32 segments[32]; //from->to,from->to ...
61 u32 numsegments;
62 u32 ch;
63 u32 flags;
64 };
65
66 ma_device g_aud_device;
67 ma_device_config g_aud_dconfig;
68
69 // Thread 1 - audio engine ( spawned from miniaudio.h )
70 // ======================================================
71 sfx_system sfx_sys[SFX_MAX_SYSTEMS];
72 int sfx_sys_len = 0;
73
74 // Thread 0 - Critical transfer section
75 // ======================================================
76 MUTEX_TYPE sfx_mux_t01; // Resources share: 0 & 1
77
78 sfx_system *sfx_q[SFX_MAX_SYSTEMS]; // Stuff changed
79 int sfx_q_len = 0; // How much
80
81 // x / 2
82 // ======================================================
83
84 // g_vol_master is never directly acessed by users
85 float g_master_volume = 1.f;
86
87 // Decompress entire vorbis stream into buffer
88 static float *sfx_vorbis_stream( const unsigned char *data, int len, int channels, u32 *samples )
89 {
90 int err;
91 stb_vorbis *pv = stb_vorbis_open_memory( data, len, &err, NULL );
92
93 if( !pv )
94 {
95 vg_error( "stb_vorbis_open_memory() failed with error code: %i\n", err );
96 return NULL;
97 }
98
99 u32 length_samples = stb_vorbis_stream_length_in_samples( pv );
100 float *buffer = (float *)malloc( length_samples * channels * sizeof( float ));
101
102 if( !buffer )
103 {
104 stb_vorbis_close( pv );
105 vg_error( "out of memory while allocating sound resource\n" );
106 return NULL;
107 }
108
109 int read_samples = stb_vorbis_get_samples_float_interleaved( pv, channels, buffer, length_samples * channels );
110 if( read_samples != length_samples )
111 {
112 vg_warn( "| warning: sample count mismatch. Expected %u got %i\n", length_samples, read_samples );
113 length_samples = read_samples;
114 }
115
116 stb_vorbis_close( pv );
117 *samples = length_samples;
118 return buffer;
119 }
120
121 static float *sfx_vorbis( const char *strFileName, int channels, u32 *samples )
122 {
123 i64 len;
124 void *filedata = vg_asset_read_s( strFileName, &len );
125
126 if( filedata )
127 {
128 float *wav = sfx_vorbis_stream( filedata, len, channels, samples );
129 free( filedata );
130 return wav;
131 }
132 else
133 {
134 vg_error( "OGG load failed\n" );
135 return NULL;
136 }
137 }
138
139 typedef struct sfx_bgload sfx_bgload_t;
140 struct sfx_bgload
141 {
142 char *path;
143 u32 channels;
144
145 float *buffer;
146 u32 samples;
147
148 void *user;
149
150 void(*OnComplete)(sfx_bgload_t *inf);
151 };
152
153 // Thread worker for background load job
154 void *sfx_vorbis_a_t( void *_inf )
155 {
156 sfx_bgload_t *info = _inf;
157
158 // Load the ogg clip
159 info->buffer = sfx_vorbis( info->path, info->channels, &info->samples );
160 info->OnComplete( info );
161
162 return NULL;
163 }
164
165 // Asynchronous resource load
166 int sfx_vorbis_a( const char *path, int channels, void(*OnComplete)(sfx_bgload_t *inf), void *user )
167 {
168 vg_info( "background job started for: %s\n", path );
169
170 sfx_bgload_t *params = malloc( sizeof( sfx_bgload_t ) );
171 params->path = malloc( strlen( path ) + 1 );
172 strcpy( params->path, path );
173 params->OnComplete = OnComplete;
174 params->user = user;
175 params->channels = channels;
176
177 return vg_thread_run( sfx_vorbis_a_t, params );
178 }
179
180 // Asynchronous load-to-system callback
181 struct sfx_vorbis_a_to_inf
182 {
183 sfx_system *sys;
184 u32 flags;
185 };
186
187 #define SFX_A_FLAG_AUTOSTART 0x1
188 #define SFX_A_FLAG_AUTOFREE 0x2
189
190 /*
191 static int sfx_save( sfx_system *sys );
192
193 // Asynchronous load-to-system callback
194 void sfx_vorbis_a_to_c( sfx_bgload_t *loadinf )
195 {
196 struct sfx_vorbis_a_to_inf *inf = loadinf->user;
197
198 // Mark buffer for deallocation if autofree is set
199 if( inf->flags & SFX_A_FLAG_AUTOFREE )
200 inf->sys->replacement = loadinf->buffer;
201 else
202 inf->sys->source = loadinf->buffer;
203
204 inf->sys->end = loadinf->samples;
205
206 if( inf->flags & SFX_A_FLAG_AUTOSTART )
207 sfx_save( inf->sys );
208
209 free( loadinf->path );
210 free( loadinf );
211 free( inf );
212 }
213
214 // Asynchronous vorbis load into audio system
215 void sfx_vorbis_a_to( sfx_system *sys, const char *strFileName, int channels, u32 flags )
216 {
217 struct sfx_vorbis_a_to_inf *inf = malloc( sizeof( struct sfx_vorbis_a_to_inf ) );
218 inf->flags = flags;
219 inf->sys = sys;
220
221 sys->ch = channels;
222
223 if( !sfx_vorbis_a( strFileName, channels, sfx_vorbis_a_to_c, inf ) )
224 free( inf );
225 }*/
226
227 // 0
228 // ======================================================
229
230 static int sfx_begin_edit( sfx_system *sys )
231 {
232 MUTEX_LOCK( sfx_mux_t01 );
233
234 if( sfx_q_len >= SFX_MAX_SYSTEMS && !sys->in_queue )
235 {
236 MUTEX_UNLOCK( sfx_mux_t01 );
237 vg_warn( "Warning: No free space in sound queue\n" );
238 return 0;
239 }
240
241 return 1;
242 }
243
244 static void sfx_end_edit( sfx_system *sys )
245 {
246 MUTEX_UNLOCK( sfx_mux_t01 );
247 }
248
249 // Mark change to be uploaded to queue system
250 static int sfx_push( sfx_system *sys )
251 {
252 if( !sys->in_queue )
253 {
254 // Mark change in queue
255 sfx_q[ sfx_q_len ++ ] = sys;
256 sys->in_queue = 1;
257 }
258
259 MUTEX_UNLOCK( sfx_mux_t01 );
260
261 return 1;
262 }
263
264 // Edit a volume float, has to be function wrapped because of mutex
265 static void sfx_vol_fset( sfx_vol_control *src, float to )
266 {
267 MUTEX_LOCK( sfx_mux_t01 );
268
269 src->val = to;
270
271 MUTEX_UNLOCK( sfx_mux_t01 );
272 }
273
274 // thread-safe get volume value
275 static float sfx_vol_fget( sfx_vol_control *src )
276 {
277 float val;
278
279 MUTEX_LOCK( sfx_mux_t01 );
280
281 val = src->val;
282
283 MUTEX_UNLOCK( sfx_mux_t01 );
284
285 return val;
286 }
287
288 // thread-safe set master volume
289 static void sfx_set_master( float to )
290 {
291 MUTEX_LOCK( sfx_mux_t01 );
292
293 g_master_volume = to;
294
295 MUTEX_UNLOCK( sfx_mux_t01 );
296 }
297
298 // thread-safe get master volume
299 static float sfx_get_master(void)
300 {
301 float val;
302
303 MUTEX_LOCK( sfx_mux_t01 );
304
305 val = g_master_volume;
306
307 MUTEX_UNLOCK( sfx_mux_t01 );
308
309 return val;
310 }
311
312 void audio_mixer_callback( ma_device *pDevice, void *pOutBuf, const void *pInput, ma_uint32 frameCount );
313
314 // Miniaudio.h init
315 static void vg_audio_init(void)
316 {
317 g_aud_dconfig = ma_device_config_init( ma_device_type_playback );
318 g_aud_dconfig.playback.format = ma_format_f32;
319 g_aud_dconfig.playback.channels = 2;
320 g_aud_dconfig.sampleRate = 44100;
321 g_aud_dconfig.dataCallback = audio_mixer_callback;
322
323 g_aud_dconfig.pUserData = NULL;
324
325 vg_info( "Starting audio engine\n" );
326
327 if( ma_device_init( NULL, &g_aud_dconfig, &g_aud_device ) != MA_SUCCESS )
328 {
329 vg_exiterr( "ma_device failed to initialize" );
330 }
331 else
332 {
333 if( ma_device_start( &g_aud_device ) != MA_SUCCESS )
334 {
335 ma_device_uninit( &g_aud_device );
336 vg_exiterr( "ma_device failed to start" );
337 }
338 }
339 }
340
341 // Shutdown audio device
342 static void vg_audio_free(void)
343 {
344 ma_device_uninit( &g_aud_device );
345 }
346
347 // 1
348 // ======================================================
349
350 // Create and return slot for a sound
351 static sfx_system *sfx_alloc(void)
352 {
353 if( sfx_sys_len >= SFX_MAX_SYSTEMS )
354 return NULL;
355
356 // A conditional is done against this in localization step,
357 // Needs to be initialized.
358 sfx_sys[ sfx_sys_len ].source = NULL;
359
360 return sfx_sys + (sfx_sys_len++);
361 }
362
363 // Fetch samples into pcf
364 static void audio_mixer_getsamples( float *pcf, float *source, u32 cur, u32 ch )
365 {
366 if( ch == 2 )
367 {
368 pcf[0] = source[ cur*2+0 ];
369 pcf[1] = source[ cur*2+1 ];
370 }
371 else
372 {
373 pcf[0] = source[ cur ];
374 pcf[1] = source[ cur ];
375 }
376 }
377
378 // miniaudio.h interface
379 void audio_mixer_callback( ma_device *pDevice, void *pOutBuf, const void *pInput, ma_uint32 frameCount )
380 {
381 // Process incoming sound queue
382 MUTEX_LOCK( sfx_mux_t01 );
383
384 while( sfx_q_len --> 0 )
385 {
386 sfx_system *src = sfx_q[sfx_q_len];
387 sfx_system *clone;
388
389 src->in_queue = 0;
390
391 // Copy
392 clone = sfx_alloc();
393 *clone = *src;
394
395 // Links need to exist on persistent sounds
396 clone->persisitent_source = src->flags & SFX_FLAG_PERSISTENT? src: NULL;
397 }
398
399 sfx_q_len = 0;
400
401 // Volume modifiers
402 for( int i = 0; i < sfx_sys_len; i ++ )
403 {
404 sfx_system *sys = sfx_sys + i;
405
406 // Apply persistent volume if linked
407 if( sys->flags & SFX_FLAG_PERSISTENT )
408 {
409 sys->vol = sys->persisitent_source->vol * g_master_volume;
410
411 // Persistent triggers
412 // -------------------
413
414 // Fadeout effect ( + remove )
415 if( sys->persisitent_source->fadeout )
416 {
417 sys->fadeout_current = sys->persisitent_source->fadeout_current;
418 sys->fadeout = sys->persisitent_source->fadeout;
419
420 sys->persisitent_source = NULL;
421 sys->flags &= ~SFX_FLAG_PERSISTENT;
422 }
423 }
424
425 // Apply volume slider if it has one linked
426 if( sys->vol_src )
427 sys->cvol = sys->vol * sys->vol_src->val;
428 else
429 sys->cvol = sys->vol;
430 }
431
432 MUTEX_UNLOCK( sfx_mux_t01 );
433
434 // Clear buffer
435 float *pOut32F = (float *)pOutBuf;
436 for( int i = 0; i < frameCount * 2; i ++ ){
437 pOut32F[i] = 0.f;
438 }
439
440 for( int i = 0; i < sfx_sys_len; i ++ )
441 {
442 sfx_system *sys = sfx_sys + i;
443
444 u32 cursor = sys->cur, buffer_pos = 0;
445 float pcf[2] = { 0.f, 0.0f };
446
447 u32 frames_write = frameCount;
448 float fadeout_divisor = 1.0f / (float)sys->fadeout;
449
450 while( frames_write )
451 {
452 u32 samples_this_run = VG_MIN( frames_write, sys->end - cursor );
453
454 if( sys->fadeout )
455 {
456 // Force this system to be removed now
457 if( sys->fadeout_current == 0 )
458 {
459 sys->flags &= 0x00000000;
460 sys->cur = sys->end;
461 break;
462 }
463
464 samples_this_run = VG_MIN( samples_this_run, sys->fadeout_current );
465 }
466
467 for( u32 j = 0; j < samples_this_run; j ++ )
468 {
469 audio_mixer_getsamples( pcf, sys->source, cursor, sys->ch );
470
471 float vol = sys->vol;
472
473 if( sys->fadeout )
474 {
475 vol *= (float)sys->fadeout_current * fadeout_divisor;
476 sys->fadeout_current --;
477 }
478
479 if( buffer_pos >= frameCount )
480 {
481 break;
482 }
483
484 pOut32F[ buffer_pos*2+0 ] += pcf[0] * vol;
485 pOut32F[ buffer_pos*2+1 ] += pcf[1] * vol;
486
487 cursor ++;
488 buffer_pos ++;
489 }
490
491 frames_write -= samples_this_run;
492
493 if( sys->flags & SFX_FLAG_REPEAT )
494 {
495 if( frames_write )
496 {
497 cursor = 0;
498 continue;
499 }
500 }
501
502 sys->cur = cursor;
503 break;
504 }
505 }
506
507 // Redistribute sound systems
508 MUTEX_LOCK( sfx_mux_t01 );
509
510 u32 idx = 0, wr = 0;
511 while( idx != sfx_sys_len )
512 {
513 sfx_system *src = sfx_sys + idx;
514
515 // Keep only if cursor is before end or repeating
516 if( src->cur < src->end || (src->flags & SFX_FLAG_REPEAT) )
517 {
518 sfx_sys[ wr ++ ] = sfx_sys[ idx ];
519 }
520
521 idx ++ ;
522 }
523 sfx_sys_len = wr;
524
525 MUTEX_UNLOCK( sfx_mux_t01 );
526
527 (void)pInput;
528 }
529
530 // Load strings into sfx_set's memory
531 // String layout: "sounda.ogg\0soundb.ogg\0soundc.ogg\0\0"
532 static void sfx_set_strings( sfx_set *dest, char *strSources, u32 flags, int bAsync )
533 {
534 dest->ch = (flags & SFX_FLAG_STEREO)? 2: 1;
535
536 dest->main = NULL;
537 dest->numsegments = 0;
538 char *source = strSources;
539
540 u32 total = 0;
541 int len;
542 while( (len = strlen( source )) )
543 {
544 u32 samples;
545 float *sound = sfx_vorbis( source, dest->ch, &samples );
546
547 if( !sound )
548 {
549 free( dest->main );
550 dest->numsegments = 0;
551 return;
552 }
553
554 total += samples;
555
556 float *nbuf = realloc( dest->main, total * dest->ch * sizeof(float) );
557
558 if( nbuf )
559 {
560 dest->main = nbuf;
561 memcpy( dest->main + (total-samples)*dest->ch, sound, samples*dest->ch*sizeof(float) );
562 free( sound );
563
564 dest->segments[ dest->numsegments*2+0 ] = total-samples;
565 dest->segments[ dest->numsegments*2+1 ] = total;
566 }
567 else
568 {
569 vg_error( "realloc() failed\n" );
570 free( sound );
571 return;
572 }
573
574 source += len +1;
575 dest->numsegments ++;
576 }
577 }
578
579 static void sfx_set_init( sfx_set *dest, char *sources )
580 {
581 if( !sources )
582 sfx_set_strings( dest, dest->sources, dest->flags, 0 );
583 else
584 sfx_set_strings( dest, sources, dest->flags, 0 );
585 }
586
587 static void sfx_set_play( sfx_set *source, sfx_system *sys, int id )
588 {
589 if( sfx_begin_edit( sys ) )
590 {
591 sys->fadeout = 0;
592 sys->fadeout_current = 0;
593 sys->source = source->main;
594 sys->cur = source->segments[ id*2 + 0 ];
595 sys->end = source->segments[ id*2 + 1 ];
596 sys->ch = source->ch;
597
598 // Diagnostics
599 sys->clip_start = sys->cur;
600 sys->clip_end = sys->end;
601 sys->buffer_length = source->segments[ (source->numsegments-1)*2 + 1 ];
602
603 sfx_push( sys );
604 }
605 }
606
607 // Pick a random sound from the buffer and play it into system
608 static void sfx_set_playrnd( sfx_set *source, sfx_system *sys, int min_id, int max_id )
609 {
610 if( !source->numsegments )
611 return;
612
613 if( max_id > source->numsegments )
614 {
615 vg_error( "Max ID out of range for playrnd\n" );
616 return;
617 }
618
619 int pick = (rand() % (max_id-min_id)) + min_id;
620
621 sfx_set_play( source, sys, pick );
622 }
623
624 static void sfx_system_fadeout( sfx_system *sys, u32 length_samples )
625 {
626 if( sfx_begin_edit( sys ) )
627 {
628 sys->fadeout_current = length_samples;
629 sys->fadeout = length_samples;
630
631 sfx_end_edit( sys );
632 }
633 }
634
635 // Free set resources
636 static void sfx_set_free( sfx_set *set )
637 {
638 free( set->main );
639 }