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