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