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