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