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 441
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
;
36 int ch
, end
, cur
, cur_lagged
;
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
186 static int sfx_save( sfx_system
*sys
);
188 // Asynchronous load-to-system callback
189 void sfx_vorbis_a_to_c( sfx_bgload_t
*loadinf
)
191 struct sfx_vorbis_a_to_inf
*inf
= loadinf
->user
;
193 // Mark buffer for deallocation if autofree is set
194 if( inf
->flags
& SFX_A_FLAG_AUTOFREE
)
195 inf
->sys
->replacement
= loadinf
->buffer
;
197 inf
->sys
->source
= loadinf
->buffer
;
199 inf
->sys
->end
= loadinf
->samples
;
201 if( inf
->flags
& SFX_A_FLAG_AUTOSTART
)
202 sfx_save( inf
->sys
);
204 free( loadinf
->path
);
209 // Asynchronous vorbis load into audio system
210 void sfx_vorbis_a_to( sfx_system
*sys
, const char *strFileName
, int channels
, u32 flags
)
212 struct sfx_vorbis_a_to_inf
*inf
= malloc( sizeof( struct sfx_vorbis_a_to_inf
) );
218 if( !sfx_vorbis_a( strFileName
, channels
, sfx_vorbis_a_to_c
, inf
) )
223 // ======================================================
225 // Mark change to be uploaded to queue system
226 static int sfx_save( sfx_system
*sys
)
228 MUTEX_LOCK( sfx_mux_t01
);
230 if( sfx_q_len
>= SFX_MAX_SYSTEMS
)
232 vg_error( "Warning: No free space in sound queue\n" );
234 MUTEX_UNLOCK( sfx_mux_t01
);
238 // Mark change in queue
239 sfx_q
[ sfx_q_len
++ ] = sys
;
241 MUTEX_UNLOCK( sfx_mux_t01
);
246 // Edit a volume float, has to be function wrapped because of mutex
247 static void sfx_vol_fset( sfx_vol_control
*src
, float to
)
249 MUTEX_LOCK( sfx_mux_t01
);
253 MUTEX_UNLOCK( sfx_mux_t01
);
256 // thread-safe get volume value
257 static float sfx_vol_fget( sfx_vol_control
*src
)
261 MUTEX_LOCK( sfx_mux_t01
);
265 MUTEX_UNLOCK( sfx_mux_t01
);
270 // thread-safe set master volume
271 static void sfx_set_master( float to
)
273 MUTEX_LOCK( sfx_mux_t01
);
275 g_master_volume
= to
;
277 MUTEX_UNLOCK( sfx_mux_t01
);
280 // thread-safe get master volume
281 static float sfx_get_master(void)
285 MUTEX_LOCK( sfx_mux_t01
);
287 val
= g_master_volume
;
289 MUTEX_UNLOCK( sfx_mux_t01
);
294 void audio_mixer_callback( ma_device
*pDevice
, void *pOutBuf
, const void *pInput
, ma_uint32 frameCount
);
297 static void vg_audio_init(void)
299 g_aud_dconfig
= ma_device_config_init( ma_device_type_playback
);
300 g_aud_dconfig
.playback
.format
= ma_format_f32
;
301 g_aud_dconfig
.playback
.channels
= 2;
302 g_aud_dconfig
.sampleRate
= 44100;
303 g_aud_dconfig
.dataCallback
= audio_mixer_callback
;
305 g_aud_dconfig
.pUserData
= NULL
;
307 vg_info( "Starting audio engine\n" );
309 if( ma_device_init( NULL
, &g_aud_dconfig
, &g_aud_device
) != MA_SUCCESS
)
311 vg_exiterr( "ma_device failed to initialize" );
315 if( ma_device_start( &g_aud_device
) != MA_SUCCESS
)
317 ma_device_uninit( &g_aud_device
);
318 vg_exiterr( "ma_device failed to start" );
323 // Shutdown audio device
324 static void vg_audio_free(void)
326 ma_device_uninit( &g_aud_device
);
330 // ======================================================
332 // Create and return slot for a sound
333 static sfx_system
*sfx_alloc(void)
335 if( sfx_sys_len
>= SFX_MAX_SYSTEMS
)
338 // A conditional is done against this in localization step,
339 // Needs to be initialized.
340 sfx_sys
[ sfx_sys_len
].source
= NULL
;
342 return sfx_sys
+ (sfx_sys_len
++);
345 // Fetch samples into pcf
346 static void audio_mixer_getsamples( float *pcf
, float *source
, u32 cur
, u32 ch
)
350 pcf
[0] = source
[ cur
*2+0 ];
351 pcf
[1] = source
[ cur
*2+1 ];
355 pcf
[0] = source
[ cur
];
356 pcf
[1] = source
[ cur
];
360 // miniaudio.h interface
361 void audio_mixer_callback( ma_device
*pDevice
, void *pOutBuf
, const void *pInput
, ma_uint32 frameCount
)
363 // Process incoming sound queue
364 MUTEX_LOCK( sfx_mux_t01
);
366 while( sfx_q_len
--> 0 )
368 sfx_system
*src
= sfx_q
[sfx_q_len
];
371 // This is a 'new' sound if thread_clone not set.
372 if( !src
->thread_clone
|| src
->flags
& SFX_FLAG_ONESHOT
)
374 src
->thread_clone
= sfx_alloc();
375 if( !src
->thread_clone
)
380 // Modifying an active system spawns a small fadeout ghost system
381 sfx_system
*ghost_system
= sfx_alloc();
386 ghost_system
->source
= src
->source
;
387 ghost_system
->ch
= src
->ch
;
388 ghost_system
->end
= src
->end
;
389 ghost_system
->cur
= src
->cur_lagged
;
390 ghost_system
->flags
= SFX_FLAG_GHOST
;
391 ghost_system
->fadeout
= FADEOUT_LENGTH
;
392 ghost_system
->fadeout_current
= FADEOUT_LENGTH
;
393 ghost_system
->vol_src
= src
->vol_src
;
394 ghost_system
->name
= src
->name
;
395 ghost_system
->thread_clone
= src
;
398 clone
= src
->thread_clone
;
400 // run replacement routine if one is waiting (todo: what is this?)
401 if( src
->replacement
)
405 src
->source
= src
->replacement
;
406 src
->replacement
= NULL
;
409 // Localize data to thread 1's memory pool
410 clone
->source
= src
->source
;
412 clone
->end
= src
->end
;
413 clone
->cur
= src
->cur
;
414 clone
->flags
= src
->flags
;
415 clone
->vol_src
= src
->vol_src
;
416 clone
->name
= src
->name
;
417 clone
->fadeout
= src
->fadeout
;
418 clone
->fadeout_current
= src
->fadeout_current
;
420 // loopback pointer, mainly used for persistent sound handles
421 clone
->thread_clone
= src
;
426 // Pull in volume sliders
427 for( int i
= 0; i
< sfx_sys_len
; i
++ )
429 sfx_system
*sys
= sfx_sys
+ i
;
430 sys
->vol
= sys
->thread_clone
->vol
* g_master_volume
;
433 sys
->vol
*= sys
->vol_src
->val
;
436 MUTEX_UNLOCK( sfx_mux_t01
);
438 // Clear buffer ( is necessary ? )
439 float *pOut32F
= (float *)pOutBuf
;
440 for( int i
= 0; i
< frameCount
* 2; i
++ ){
444 // Do something with local..
445 for( int i
= 0; i
< sfx_sys_len
; i
++ )
447 sfx_system
*sys
= sfx_sys
+ i
;
449 u32 cursor
= sys
->cur
, buffer_pos
= 0;
452 float pcf
[2] = { 0.f
, 0.0f
};
454 u32 frames_write
= frameCount
;
455 float fadeout_divisor
= 1.0f
/ (float)sys
->fadeout
;
457 while( frames_write
)
459 u32 samples_this_run
= vg_min( frames_write
, sys
->end
- cursor
);
463 // Force this system to be removed
464 if( sys
->fadeout_current
== 0 )
466 sys
->flags
= SFX_FLAG_GHOST
;
471 samples_this_run
= vg_min( samples_this_run
, sys
->fadeout_current
);
474 for( u32 j
= 0; j
< samples_this_run
; j
++ )
476 audio_mixer_getsamples( pcf
, sys
->source
, cursor
, sys
->ch
);
478 float vol
= sys
->vol
;
482 vol
*= (float)sys
->fadeout_current
* fadeout_divisor
;
483 sys
->fadeout_current
--;
486 pOut32F
[ buffer_pos
*2+0 ] += pcf
[0] * vol
;
487 pOut32F
[ buffer_pos
*2+1 ] += pcf
[1] * vol
;
489 avgvol
+= fabs( pcf
[0] * vol
);
490 avgvol
+= fabs( pcf
[1] * vol
);
496 frames_write
-= samples_this_run
;
498 if( sys
->flags
& SFX_FLAG_REPEAT
)
508 sys
->cur_lagged
= cursor
;
509 sys
->signal_average
= avgvol
/ (float)(buffer_pos
*2);
515 // Redistribute sound systems
516 MUTEX_LOCK( sfx_mux_t01
);
518 unsigned int idx
= 0, wr
= 0;
519 while( idx
!= sfx_sys_len
)
521 sfx_system
*src
= sfx_sys
+ idx
;
523 // Keep only if cursor is before end or repeating
524 if( src
->cur
< src
->end
|| (src
->flags
& SFX_FLAG_REPEAT
) )
526 // Correct source pointer on persisitent originals since we shifted ID's
527 if( !(src
->flags
& SFX_FLAG_ONESHOT
) )
528 src
->thread_clone
->thread_clone
= sfx_sys
+ wr
;
530 sfx_sys
[ wr
++ ] = sfx_sys
[ idx
];
534 // Clear link on persistent sources (done playing)
535 if( !(src
->flags
& SFX_FLAG_ONESHOT
) )
536 src
->thread_clone
->thread_clone
= NULL
;
543 MUTEX_UNLOCK( sfx_mux_t01
);
548 // Load strings into sfx_set's memory
549 // String layout: "sounda.ogg\0soundb.ogg\0soundc.ogg\0\0"
550 static void sfx_set_strings( sfx_set
*dest
, char *strSources
, u32 flags
, int bAsync
)
552 printf( "Init sfx set\n| start | end | length | name \n" );
554 dest
->ch
= (flags
& SFX_FLAG_STEREO
)? 2: 1;
557 dest
->numsegments
= 0;
558 char *source
= strSources
;
562 while( (len
= strlen( source
)) )
565 float *sound
= sfx_vorbis( source
, dest
->ch
, &samples
);
570 dest
->numsegments
= 0;
576 float *nbuf
= realloc( dest
->main
, total
* dest
->ch
* sizeof(float) );
581 memcpy( dest
->main
+ (total
-samples
)*dest
->ch
, sound
, samples
*dest
->ch
*sizeof(float) );
584 dest
->segments
[ dest
->numsegments
*2+0 ] = total
-samples
;
585 dest
->segments
[ dest
->numsegments
*2+1 ] = total
;
587 printf( "| %09u | %09u | %09u | %s\n", total
-samples
, total
, samples
, source
);
591 vg_error( "realloc() failed\n" );
597 dest
->numsegments
++;
600 vg_info( "finished, numsegments: %u\n", dest
->numsegments
);
603 static void sfx_set_init( sfx_set
*dest
, char *sources
)
606 sfx_set_strings( dest
, dest
->sources
, dest
->flags
, 0 );
608 sfx_set_strings( dest
, sources
, dest
->flags
, 0 );
611 // Pick a random sound from the buffer and play it into system
612 static void sfx_set_playrnd( sfx_set
*source
, sfx_system
*sys
, int min_id
, int max_id
)
614 if( !source
->numsegments
)
617 int pick
= (rand() % (max_id
-min_id
)) + min_id
;
620 sys
->source
= source
->main
;
621 sys
->cur
= source
->segments
[ pick
*2 + 0 ];
622 sys
->end
= source
->segments
[ pick
*2 + 1 ];
623 sys
->ch
= source
->ch
;
628 static void sfx_system_fadeout( sfx_system
*sys
, u32 length_samples
)
630 sys
->fadeout_current
= length_samples
;
631 sys
->fadeout
= length_samples
;
636 // Free set resources
637 static void sfx_set_free( sfx_set
*set
)