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