e62d5845447e35f09c3e3b6536911a38ff2e3e42
[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_PERSISTENT 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 sfx_system *persisitent_source;
29 int in_queue;
30
31 // Source buffer start
32 float *source, *replacement;
33
34 u32 clip_start, clip_end, buffer_length;
35
36 // Modifiers
37 sfx_vol_control *vol_src;
38 float vol, cvol;
39
40 // Info
41 u32 ch, end, cur;
42 u32 flags;
43
44 // Effects
45 u32 fadeout, fadeout_current;
46
47 // Diagnostic
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[32]; //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( sfx_q_len >= SFX_MAX_SYSTEMS && !sys->in_queue )
233 {
234 MUTEX_UNLOCK( sfx_mux_t01 );
235 vg_warn( "Warning: No free space in sound queue\n" );
236 return 0;
237 }
238
239 return 1;
240 }
241
242 static void sfx_end_edit( sfx_system *sys )
243 {
244 MUTEX_UNLOCK( sfx_mux_t01 );
245 }
246
247 // Mark change to be uploaded to queue system
248 static int sfx_push( sfx_system *sys )
249 {
250 if( !sys->in_queue )
251 {
252 // Mark change in queue
253 sfx_q[ sfx_q_len ++ ] = sys;
254 sys->in_queue = 1;
255 }
256
257 MUTEX_UNLOCK( sfx_mux_t01 );
258
259 return 1;
260 }
261
262 // Edit a volume float, has to be function wrapped because of mutex
263 static void sfx_vol_fset( sfx_vol_control *src, float to )
264 {
265 MUTEX_LOCK( sfx_mux_t01 );
266
267 src->val = to;
268
269 MUTEX_UNLOCK( sfx_mux_t01 );
270 }
271
272 // thread-safe get volume value
273 static float sfx_vol_fget( sfx_vol_control *src )
274 {
275 float val;
276
277 MUTEX_LOCK( sfx_mux_t01 );
278
279 val = src->val;
280
281 MUTEX_UNLOCK( sfx_mux_t01 );
282
283 return val;
284 }
285
286 // thread-safe set master volume
287 static void sfx_set_master( float to )
288 {
289 MUTEX_LOCK( sfx_mux_t01 );
290
291 g_master_volume = to;
292
293 MUTEX_UNLOCK( sfx_mux_t01 );
294 }
295
296 // thread-safe get master volume
297 static float sfx_get_master(void)
298 {
299 float val;
300
301 MUTEX_LOCK( sfx_mux_t01 );
302
303 val = g_master_volume;
304
305 MUTEX_UNLOCK( sfx_mux_t01 );
306
307 return val;
308 }
309
310 void audio_mixer_callback( ma_device *pDevice, void *pOutBuf, const void *pInput, ma_uint32 frameCount );
311
312 // Miniaudio.h init
313 static void vg_audio_init(void)
314 {
315 g_aud_dconfig = ma_device_config_init( ma_device_type_playback );
316 g_aud_dconfig.playback.format = ma_format_f32;
317 g_aud_dconfig.playback.channels = 2;
318 g_aud_dconfig.sampleRate = 44100;
319 g_aud_dconfig.dataCallback = audio_mixer_callback;
320
321 g_aud_dconfig.pUserData = NULL;
322
323 vg_info( "Starting audio engine\n" );
324
325 if( ma_device_init( NULL, &g_aud_dconfig, &g_aud_device ) != MA_SUCCESS )
326 {
327 vg_exiterr( "ma_device failed to initialize" );
328 }
329 else
330 {
331 if( ma_device_start( &g_aud_device ) != MA_SUCCESS )
332 {
333 ma_device_uninit( &g_aud_device );
334 vg_exiterr( "ma_device failed to start" );
335 }
336 }
337 }
338
339 // Shutdown audio device
340 static void vg_audio_free(void)
341 {
342 ma_device_uninit( &g_aud_device );
343 }
344
345 // 1
346 // ======================================================
347
348 // Create and return slot for a sound
349 static sfx_system *sfx_alloc(void)
350 {
351 if( sfx_sys_len >= SFX_MAX_SYSTEMS )
352 return NULL;
353
354 // A conditional is done against this in localization step,
355 // Needs to be initialized.
356 sfx_sys[ sfx_sys_len ].source = NULL;
357
358 return sfx_sys + (sfx_sys_len++);
359 }
360
361 // Fetch samples into pcf
362 static void audio_mixer_getsamples( float *pcf, float *source, u32 cur, u32 ch )
363 {
364 if( ch == 2 )
365 {
366 pcf[0] = source[ cur*2+0 ];
367 pcf[1] = source[ cur*2+1 ];
368 }
369 else
370 {
371 pcf[0] = source[ cur ];
372 pcf[1] = source[ cur ];
373 }
374 }
375
376 // miniaudio.h interface
377 void audio_mixer_callback( ma_device *pDevice, void *pOutBuf, const void *pInput, ma_uint32 frameCount )
378 {
379 // Process incoming sound queue
380 MUTEX_LOCK( sfx_mux_t01 );
381
382 while( sfx_q_len --> 0 )
383 {
384 sfx_system *src = sfx_q[sfx_q_len];
385 sfx_system *clone;
386
387 src->in_queue = 0;
388
389 // Copy
390 clone = sfx_alloc();
391 *clone = *src;
392
393 // Links need to exist on persistent sounds
394 clone->persisitent_source = src->flags & SFX_FLAG_PERSISTENT? src: NULL;
395 }
396
397 sfx_q_len = 0;
398
399 // Volume modifiers
400 for( int i = 0; i < sfx_sys_len; i ++ )
401 {
402 sfx_system *sys = sfx_sys + i;
403
404 // Apply persistent volume if linked
405 if( sys->flags & SFX_FLAG_PERSISTENT )
406 {
407 sys->vol = sys->persisitent_source->vol * g_master_volume;
408
409 // Persistent triggers
410 // -------------------
411
412 // Fadeout effect ( + remove )
413 if( sys->persisitent_source->fadeout )
414 {
415 sys->fadeout_current = sys->persisitent_source->fadeout_current;
416 sys->fadeout = sys->persisitent_source->fadeout;
417
418 sys->persisitent_source = NULL;
419 sys->flags &= ~SFX_FLAG_PERSISTENT;
420 }
421 }
422
423 // Apply volume slider if it has one linked
424 if( sys->vol_src )
425 sys->cvol = sys->vol * sys->vol_src->val;
426 else
427 sys->cvol = sys->vol;
428 }
429
430 MUTEX_UNLOCK( sfx_mux_t01 );
431
432 // Clear buffer
433 float *pOut32F = (float *)pOutBuf;
434 for( int i = 0; i < frameCount * 2; i ++ ){
435 pOut32F[i] = 0.f;
436 }
437
438 for( int i = 0; i < sfx_sys_len; i ++ )
439 {
440 sfx_system *sys = sfx_sys + i;
441
442 u32 cursor = sys->cur, buffer_pos = 0;
443 float pcf[2] = { 0.f, 0.0f };
444
445 u32 frames_write = frameCount;
446 float fadeout_divisor = 1.0f / (float)sys->fadeout;
447
448 while( frames_write )
449 {
450 u32 samples_this_run = VG_MIN( frames_write, sys->end - cursor );
451
452 if( sys->fadeout )
453 {
454 // Force this system to be removed now
455 if( sys->fadeout_current == 0 )
456 {
457 sys->flags &= 0x00000000;
458 sys->cur = sys->end;
459 break;
460 }
461
462 samples_this_run = VG_MIN( samples_this_run, sys->fadeout_current );
463 }
464
465 for( u32 j = 0; j < samples_this_run; j ++ )
466 {
467 audio_mixer_getsamples( pcf, sys->source, cursor, sys->ch );
468
469 float vol = sys->vol;
470
471 if( sys->fadeout )
472 {
473 vol *= (float)sys->fadeout_current * fadeout_divisor;
474 sys->fadeout_current --;
475 }
476
477 if( buffer_pos >= frameCount )
478 {
479 break;
480 }
481
482 pOut32F[ buffer_pos*2+0 ] += pcf[0] * vol;
483 pOut32F[ buffer_pos*2+1 ] += pcf[1] * vol;
484
485 cursor ++;
486 buffer_pos ++;
487 }
488
489 frames_write -= samples_this_run;
490
491 if( sys->flags & SFX_FLAG_REPEAT )
492 {
493 if( frames_write )
494 {
495 cursor = 0;
496 continue;
497 }
498 }
499
500 sys->cur = cursor;
501 break;
502 }
503 }
504
505 // Redistribute sound systems
506 MUTEX_LOCK( sfx_mux_t01 );
507
508 u32 idx = 0, wr = 0;
509 while( idx != sfx_sys_len )
510 {
511 sfx_system *src = sfx_sys + idx;
512
513 // Keep only if cursor is before end or repeating
514 if( src->cur < src->end || (src->flags & SFX_FLAG_REPEAT) )
515 {
516 sfx_sys[ wr ++ ] = sfx_sys[ idx ];
517 }
518
519 idx ++ ;
520 }
521 sfx_sys_len = wr;
522
523 MUTEX_UNLOCK( sfx_mux_t01 );
524
525 (void)pInput;
526 }
527
528 // Load strings into sfx_set's memory
529 // String layout: "sounda.ogg\0soundb.ogg\0soundc.ogg\0\0"
530 static void sfx_set_strings( sfx_set *dest, char *strSources, u32 flags, int bAsync )
531 {
532 dest->ch = (flags & SFX_FLAG_STEREO)? 2: 1;
533
534 dest->main = NULL;
535 dest->numsegments = 0;
536 char *source = strSources;
537
538 u32 total = 0;
539 int len;
540 while( (len = strlen( source )) )
541 {
542 u32 samples;
543 float *sound = sfx_vorbis( source, dest->ch, &samples );
544
545 if( !sound )
546 {
547 free( dest->main );
548 dest->numsegments = 0;
549 return;
550 }
551
552 total += samples;
553
554 float *nbuf = realloc( dest->main, total * dest->ch * sizeof(float) );
555
556 if( nbuf )
557 {
558 dest->main = nbuf;
559 memcpy( dest->main + (total-samples)*dest->ch, sound, samples*dest->ch*sizeof(float) );
560 free( sound );
561
562 dest->segments[ dest->numsegments*2+0 ] = total-samples;
563 dest->segments[ dest->numsegments*2+1 ] = total;
564 }
565 else
566 {
567 vg_error( "realloc() failed\n" );
568 free( sound );
569 return;
570 }
571
572 source += len +1;
573 dest->numsegments ++;
574 }
575 }
576
577 static void sfx_set_init( sfx_set *dest, char *sources )
578 {
579 if( !sources )
580 sfx_set_strings( dest, dest->sources, dest->flags, 0 );
581 else
582 sfx_set_strings( dest, sources, dest->flags, 0 );
583 }
584
585 static void sfx_set_play( sfx_set *source, sfx_system *sys, int id )
586 {
587 if( sfx_begin_edit( sys ) )
588 {
589 sys->fadeout = 0;
590 sys->fadeout_current = 0;
591 sys->source = source->main;
592 sys->cur = source->segments[ id*2 + 0 ];
593 sys->end = source->segments[ id*2 + 1 ];
594 sys->ch = source->ch;
595
596 // Diagnostics
597 sys->clip_start = sys->cur;
598 sys->clip_end = sys->end;
599 sys->buffer_length = source->segments[ (source->numsegments-1)*2 + 1 ];
600
601 sfx_push( sys );
602 }
603 }
604
605 // Pick a random sound from the buffer and play it into system
606 static void sfx_set_playrnd( sfx_set *source, sfx_system *sys, int min_id, int max_id )
607 {
608 if( !source->numsegments )
609 return;
610
611 if( max_id > source->numsegments )
612 {
613 vg_error( "Max ID out of range for playrnd\n" );
614 return;
615 }
616
617 int pick = (rand() % (max_id-min_id)) + min_id;
618
619 sfx_set_play( source, sys, pick );
620 }
621
622 static void sfx_system_fadeout( sfx_system *sys, u32 length_samples )
623 {
624 if( sfx_begin_edit( sys ) )
625 {
626 sys->fadeout_current = length_samples;
627 sys->fadeout = length_samples;
628
629 sfx_end_edit( sys );
630 }
631 }
632
633 // Free set resources
634 static void sfx_set_free( sfx_set *set )
635 {
636 free( set->main );
637 }