1 // Copyright (C) 2021 Harry Godden (hgn) - All Rights Reserved
3 #define MINIAUDIO_IMPLEMENTATION
4 #include "dr_soft/miniaudio.h"
6 #define STB_VORBIS_MAX_CHANNELS 2
7 #include "stb/stb_vorbis.h"
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)
17 typedef struct sfx_vol_control sfx_vol_control
;
18 typedef struct sfx_system sfx_system
;
20 struct sfx_vol_control
28 // Source buffer start
29 float *source
, *replacement
;
32 sfx_vol_control
*vol_src
;
40 u32 fadeout
, fadeout_current
;
42 sfx_system
*thread_clone
; // Memory of this structure is copied into thread 2
45 float signal_average
; // Current signal volume
49 // Set of up to 8 sound effects packed into one
50 typedef struct sfx_set sfx_set
;
56 u32 segments
[16]; //from->to,from->to ...
62 ma_device g_aud_device
;
63 ma_device_config g_aud_dconfig
;
65 // Thread 1 - audio engine ( spawned from miniaudio.h )
66 // ======================================================
67 sfx_system sfx_sys
[SFX_MAX_SYSTEMS
];
70 // Thread 0 - Critical transfer section
71 // ======================================================
72 MUTEX_TYPE sfx_mux_t01
; // Resources share: 0 & 1
74 sfx_system
*sfx_q
[SFX_MAX_SYSTEMS
]; // Stuff changed
75 int sfx_q_len
= 0; // How much
78 // ======================================================
80 // g_vol_master is never directly acessed by users
81 float g_master_volume
= 1.f
;
83 // Decompress entire vorbis stream into buffer
84 static float *sfx_vorbis_stream( const unsigned char *data
, int len
, int channels
, u32
*samples
)
87 stb_vorbis
*pv
= stb_vorbis_open_memory( data
, len
, &err
, NULL
);
91 vg_error( "stb_vorbis_open_memory() failed with error code: %i\n", err
);
95 u32 length_samples
= stb_vorbis_stream_length_in_samples( pv
);
96 float *buffer
= (float *)malloc( length_samples
* channels
* sizeof( float ));
100 stb_vorbis_close( pv
);
101 vg_error( "out of memory while allocating sound resource\n" );
105 int read_samples
= stb_vorbis_get_samples_float_interleaved( pv
, channels
, buffer
, length_samples
* channels
);
106 if( read_samples
!= length_samples
)
108 vg_warn( "| warning: sample count mismatch. Expected %u got %i\n", length_samples
, read_samples
);
109 length_samples
= read_samples
;
112 stb_vorbis_close( pv
);
113 *samples
= length_samples
;
117 static float *sfx_vorbis( const char *strFileName
, int channels
, u32
*samples
)
120 void *filedata
= vg_asset_read_s( strFileName
, &len
);
124 float *wav
= sfx_vorbis_stream( filedata
, len
, channels
, samples
);
130 vg_error( "OGG load failed\n" );
135 typedef struct sfx_bgload sfx_bgload_t
;
146 void(*OnComplete
)(sfx_bgload_t
*inf
);
149 // Thread worker for background load job
150 void *sfx_vorbis_a_t( void *_inf
)
152 sfx_bgload_t
*info
= _inf
;
155 info
->buffer
= sfx_vorbis( info
->path
, info
->channels
, &info
->samples
);
156 info
->OnComplete( info
);
161 // Asynchronous resource load
162 int sfx_vorbis_a( const char *path
, int channels
, void(*OnComplete
)(sfx_bgload_t
*inf
), void *user
)
164 vg_info( "background job started for: %s\n", path
);
166 sfx_bgload_t
*params
= malloc( sizeof( sfx_bgload_t
) );
167 params
->path
= malloc( strlen( path
) + 1 );
168 strcpy( params
->path
, path
);
169 params
->OnComplete
= OnComplete
;
171 params
->channels
= channels
;
173 return vg_thread_run( sfx_vorbis_a_t
, params
);
176 // Asynchronous load-to-system callback
177 struct sfx_vorbis_a_to_inf
183 #define SFX_A_FLAG_AUTOSTART 0x1
184 #define SFX_A_FLAG_AUTOFREE 0x2
187 static int sfx_save( sfx_system *sys );
189 // Asynchronous load-to-system callback
190 void sfx_vorbis_a_to_c( sfx_bgload_t *loadinf )
192 struct sfx_vorbis_a_to_inf *inf = loadinf->user;
194 // Mark buffer for deallocation if autofree is set
195 if( inf->flags & SFX_A_FLAG_AUTOFREE )
196 inf->sys->replacement = loadinf->buffer;
198 inf->sys->source = loadinf->buffer;
200 inf->sys->end = loadinf->samples;
202 if( inf->flags & SFX_A_FLAG_AUTOSTART )
203 sfx_save( inf->sys );
205 free( loadinf->path );
210 // Asynchronous vorbis load into audio system
211 void sfx_vorbis_a_to( sfx_system *sys, const char *strFileName, int channels, u32 flags )
213 struct sfx_vorbis_a_to_inf *inf = malloc( sizeof( struct sfx_vorbis_a_to_inf ) );
219 if( !sfx_vorbis_a( strFileName, channels, sfx_vorbis_a_to_c, inf ) )
224 // ======================================================
226 static int sfx_begin_edit( sfx_system
*sys
)
228 MUTEX_LOCK( sfx_mux_t01
);
230 if( sfx_q_len
>= SFX_MAX_SYSTEMS
)
232 MUTEX_UNLOCK( sfx_mux_t01
);
233 vg_warn( "Warning: No free space in sound queue\n" );
240 // Mark change to be uploaded to queue system
241 static int sfx_save( sfx_system
*sys
)
243 // Mark change in queue
244 sfx_q
[ sfx_q_len
++ ] = sys
;
246 MUTEX_UNLOCK( sfx_mux_t01
);
251 // Edit a volume float, has to be function wrapped because of mutex
252 static void sfx_vol_fset( sfx_vol_control
*src
, float to
)
254 MUTEX_LOCK( sfx_mux_t01
);
258 MUTEX_UNLOCK( sfx_mux_t01
);
261 // thread-safe get volume value
262 static float sfx_vol_fget( sfx_vol_control
*src
)
266 MUTEX_LOCK( sfx_mux_t01
);
270 MUTEX_UNLOCK( sfx_mux_t01
);
275 // thread-safe set master volume
276 static void sfx_set_master( float to
)
278 MUTEX_LOCK( sfx_mux_t01
);
280 g_master_volume
= to
;
282 MUTEX_UNLOCK( sfx_mux_t01
);
285 // thread-safe get master volume
286 static float sfx_get_master(void)
290 MUTEX_LOCK( sfx_mux_t01
);
292 val
= g_master_volume
;
294 MUTEX_UNLOCK( sfx_mux_t01
);
299 void audio_mixer_callback( ma_device
*pDevice
, void *pOutBuf
, const void *pInput
, ma_uint32 frameCount
);
302 static void vg_audio_init(void)
304 g_aud_dconfig
= ma_device_config_init( ma_device_type_playback
);
305 g_aud_dconfig
.playback
.format
= ma_format_f32
;
306 g_aud_dconfig
.playback
.channels
= 2;
307 g_aud_dconfig
.sampleRate
= 44100;
308 g_aud_dconfig
.dataCallback
= audio_mixer_callback
;
310 g_aud_dconfig
.pUserData
= NULL
;
312 vg_info( "Starting audio engine\n" );
314 if( ma_device_init( NULL
, &g_aud_dconfig
, &g_aud_device
) != MA_SUCCESS
)
316 vg_exiterr( "ma_device failed to initialize" );
320 if( ma_device_start( &g_aud_device
) != MA_SUCCESS
)
322 ma_device_uninit( &g_aud_device
);
323 vg_exiterr( "ma_device failed to start" );
328 // Shutdown audio device
329 static void vg_audio_free(void)
331 ma_device_uninit( &g_aud_device
);
335 // ======================================================
337 // Create and return slot for a sound
338 static sfx_system
*sfx_alloc(void)
340 if( sfx_sys_len
>= SFX_MAX_SYSTEMS
)
343 // A conditional is done against this in localization step,
344 // Needs to be initialized.
345 sfx_sys
[ sfx_sys_len
].source
= NULL
;
347 return sfx_sys
+ (sfx_sys_len
++);
350 // Fetch samples into pcf
351 static void audio_mixer_getsamples( float *pcf
, float *source
, u32 cur
, u32 ch
)
355 pcf
[0] = source
[ cur
*2+0 ];
356 pcf
[1] = source
[ cur
*2+1 ];
360 pcf
[0] = source
[ cur
];
361 pcf
[1] = source
[ cur
];
365 // miniaudio.h interface
366 void audio_mixer_callback( ma_device
*pDevice
, void *pOutBuf
, const void *pInput
, ma_uint32 frameCount
)
368 // Process incoming sound queue
369 MUTEX_LOCK( sfx_mux_t01
);
371 while( sfx_q_len
--> 0 )
373 sfx_system
*src
= sfx_q
[sfx_q_len
];
376 // This is a 'new' sound if thread_clone not set.
377 if( !src
->thread_clone
|| (src
->flags
& SFX_FLAG_ONESHOT
) )
383 src
->thread_clone
= clone
;
387 clone
= src
->thread_clone
;
389 // Modifying an active system's cursor spawns a small fadeout ghost system
390 if( clone
->cur
!= src
->cur
)
392 sfx_system
*ghost_system
= sfx_alloc();
397 ghost_system
->source
= clone
->source
;
398 ghost_system
->ch
= clone
->ch
;
399 ghost_system
->end
= clone
->end
;
400 ghost_system
->cur
= clone
->cur
;
401 ghost_system
->flags
= SFX_FLAG_GHOST
;
402 ghost_system
->fadeout
= FADEOUT_LENGTH
;
403 ghost_system
->fadeout_current
= FADEOUT_LENGTH
;
404 ghost_system
->vol_src
= clone
->vol_src
;
405 ghost_system
->name
= clone
->name
;
406 ghost_system
->thread_clone
= src
;
410 // run replacement routine if one is waiting (todo: what is this?)
411 if( src
->replacement
)
415 src
->source
= src
->replacement
;
416 src
->replacement
= NULL
;
419 // Localize data to thread 1's memory pool
420 clone
->source
= src
->source
;
422 clone
->end
= src
->end
;
423 clone
->cur
= src
->cur
;
424 clone
->flags
= src
->flags
;
425 clone
->vol_src
= src
->vol_src
;
426 clone
->name
= src
->name
;
427 clone
->fadeout
= src
->fadeout
;
428 clone
->fadeout_current
= src
->fadeout_current
;
430 // loopback pointer, mainly used for persistent sound handles
431 clone
->thread_clone
= src
;
436 // Pull in volume sliders
437 for( int i
= 0; i
< sfx_sys_len
; i
++ )
439 sfx_system
*sys
= sfx_sys
+ i
;
440 sys
->vol
= sys
->thread_clone
->vol
* g_master_volume
;
443 sys
->vol
*= sys
->vol_src
->val
;
446 MUTEX_UNLOCK( sfx_mux_t01
);
448 // Clear buffer ( is necessary ? )
449 float *pOut32F
= (float *)pOutBuf
;
450 for( int i
= 0; i
< frameCount
* 2; i
++ ){
454 // Do something with local..
455 for( int i
= 0; i
< sfx_sys_len
; i
++ )
457 sfx_system
*sys
= sfx_sys
+ i
;
459 u32 cursor
= sys
->cur
, buffer_pos
= 0;
461 float pcf
[2] = { 0.f
, 0.0f
};
463 u32 frames_write
= frameCount
;
464 float fadeout_divisor
= 1.0f
/ (float)sys
->fadeout
;
466 while( frames_write
)
468 u32 samples_this_run
= VG_MIN( frames_write
, sys
->end
- cursor
);
472 // Force this system to be removed
473 if( sys
->fadeout_current
== 0 )
475 sys
->flags
= SFX_FLAG_GHOST
;
480 samples_this_run
= VG_MIN( samples_this_run
, sys
->fadeout_current
);
483 for( u32 j
= 0; j
< samples_this_run
; j
++ )
485 audio_mixer_getsamples( pcf
, sys
->source
, cursor
, sys
->ch
);
487 float vol
= sys
->vol
;
491 vol
*= (float)sys
->fadeout_current
* fadeout_divisor
;
492 sys
->fadeout_current
--;
495 if( buffer_pos
>= frameCount
)
500 pOut32F
[ buffer_pos
*2+0 ] += pcf
[0] * vol
;
501 pOut32F
[ buffer_pos
*2+1 ] += pcf
[1] * vol
;
503 avgvol
+= fabs( pcf
[0] * vol
);
504 avgvol
+= fabs( pcf
[1] * vol
);
510 frames_write
-= samples_this_run
;
512 if( sys
->flags
& SFX_FLAG_REPEAT
)
522 sys
->signal_average
= avgvol
/ (float)(buffer_pos
*2);
528 // Redistribute sound systems
529 MUTEX_LOCK( sfx_mux_t01
);
532 while( idx
!= sfx_sys_len
)
534 sfx_system
*src
= sfx_sys
+ idx
;
536 // Keep only if cursor is before end or repeating
537 if( src
->cur
< src
->end
|| (src
->flags
& SFX_FLAG_REPEAT
) )
539 // Correct source pointer on persisitent originals since we shifted ID's
540 if( !(src
->flags
& (SFX_FLAG_ONESHOT
|SFX_FLAG_GHOST
)) )
542 src
->thread_clone
->thread_clone
= sfx_sys
+ wr
;
545 sfx_sys
[ wr
++ ] = sfx_sys
[ idx
];
549 // Clear link on persistent sources (done playing)
550 if( !(src
->flags
& (SFX_FLAG_ONESHOT
|SFX_FLAG_GHOST
)) )
551 src
->thread_clone
->thread_clone
= NULL
;
558 MUTEX_UNLOCK( sfx_mux_t01
);
563 // Load strings into sfx_set's memory
564 // String layout: "sounda.ogg\0soundb.ogg\0soundc.ogg\0\0"
565 static void sfx_set_strings( sfx_set
*dest
, char *strSources
, u32 flags
, int bAsync
)
567 printf( "Init sfx set\n| start | end | length | name \n" );
569 dest
->ch
= (flags
& SFX_FLAG_STEREO
)? 2: 1;
572 dest
->numsegments
= 0;
573 char *source
= strSources
;
577 while( (len
= strlen( source
)) )
580 float *sound
= sfx_vorbis( source
, dest
->ch
, &samples
);
585 dest
->numsegments
= 0;
591 float *nbuf
= realloc( dest
->main
, total
* dest
->ch
* sizeof(float) );
596 memcpy( dest
->main
+ (total
-samples
)*dest
->ch
, sound
, samples
*dest
->ch
*sizeof(float) );
599 dest
->segments
[ dest
->numsegments
*2+0 ] = total
-samples
;
600 dest
->segments
[ dest
->numsegments
*2+1 ] = total
;
602 printf( "| %09u | %09u | %09u | %s\n", total
-samples
, total
, samples
, source
);
606 vg_error( "realloc() failed\n" );
612 dest
->numsegments
++;
615 vg_info( "finished, numsegments: %u\n", dest
->numsegments
);
618 static void sfx_set_init( sfx_set
*dest
, char *sources
)
621 sfx_set_strings( dest
, dest
->sources
, dest
->flags
, 0 );
623 sfx_set_strings( dest
, sources
, dest
->flags
, 0 );
626 // Pick a random sound from the buffer and play it into system
627 static void sfx_set_playrnd( sfx_set
*source
, sfx_system
*sys
, int min_id
, int max_id
)
629 if( !source
->numsegments
)
632 int pick
= (rand() % (max_id
-min_id
)) + min_id
;
634 if( sfx_begin_edit( sys
) )
637 sys
->source
= source
->main
;
638 sys
->cur
= source
->segments
[ pick
*2 + 0 ];
639 sys
->end
= source
->segments
[ pick
*2 + 1 ];
640 sys
->ch
= source
->ch
;
646 static void sfx_system_fadeout( sfx_system
*sys
, u32 length_samples
)
648 if( sfx_begin_edit( sys
) )
650 sys
->fadeout_current
= length_samples
;
651 sys
->fadeout
= length_samples
;
653 if( sys
->thread_clone
)
654 sys
->cur
= sys
->thread_clone
->cur
;
660 // Free set resources
661 static void sfx_set_free( sfx_set
*set
)