1 /* Copyright (C) 2021-2023 Harry Godden (hgn) - All Rights Reserved */
9 #include "vg/vg_stdint.h"
10 #include "vg/vg_platform.h"
13 #include "vg/vg_console.h"
14 #include "vg/vg_store.h"
15 #include "vg/vg_profiler.h"
16 #include "vg/vg_audio_synth_bird.h"
20 #pragma GCC push_options
21 #pragma GCC optimize ("O3")
22 #pragma GCC diagnostic push
23 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
27 #define STB_VORBIS_MAX_CHANNELS 2
28 #include "submodules/stb/stb_vorbis.c"
35 #pragma GCC pop_options
36 #pragma GCC diagnostic pop
40 #define AUDIO_FRAME_SIZE 512
41 #define AUDIO_MIX_FRAME_SIZE 256
43 #define AUDIO_CHANNELS 32
45 #define AUDIO_FILTERS 16
46 #define AUDIO_FLAG_LOOP 0x1
47 #define AUDIO_FLAG_NO_DOPPLER 0x2
48 #define AUDIO_FLAG_SPACIAL_3D 0x4
49 #define AUDIO_FLAG_AUTO_START 0x8
50 #define AUDIO_FLAG_FORMAT 0x1E00
54 k_audio_format_mono
= 0x000u
,
55 k_audio_format_stereo
= 0x200u
,
56 k_audio_format_vorbis
= 0x400u
,
57 k_audio_format_none0
= 0x600u
,
58 k_audio_format_none1
= 0x800u
,
59 k_audio_format_none2
= 0xA00u
,
60 k_audio_format_none3
= 0xC00u
,
61 k_audio_format_none4
= 0xE00u
,
63 k_audio_format_bird
= 0x1000u
,
64 k_audio_format_none5
= 0x1200u
,
65 k_audio_format_none6
= 0x1400u
,
66 k_audio_format_none7
= 0x1600u
,
67 k_audio_format_none8
= 0x1800u
,
68 k_audio_format_none9
= 0x1A00u
,
69 k_audio_format_none10
= 0x1C00u
,
70 k_audio_format_none11
= 0x1E00u
,
73 #define AUDIO_DECODE_SIZE (1024*256) /* 256 kb decoding buffers */
74 #define AUDIO_MUTE_VOLUME 0.0f
75 #define AUDIO_BASE_VOLUME 1.0f
77 typedef struct audio_clip audio_clip
;
78 typedef struct audio_channel audio_channel
;
79 typedef struct audio_lfo audio_lfo
;
82 union { /* TODO oof.. */
96 struct vg_audio_system
{
97 SDL_AudioDeviceID sdl_output_device
;
106 SDL_SpinLock sl_checker
,
110 u32 time
, time_startframe
;
111 float sqrt_polynomial_coefficient
;
118 k_lfo_polynomial_bipolar
123 float polynomial_coefficient
;
126 u32 editble_state_write_mask
;
128 oscillators
[ AUDIO_LFOS
];
130 struct audio_channel
{
135 char name
[32]; /* only editable while allocated == 0 */
136 audio_clip
*source
; /* ... */
138 u32 colour
; /* ... */
140 /* internal non-readable state
141 * -----------------------------*/
142 u32 cursor
, source_length
;
144 float volume_movement_start
,
151 struct synth_bird
*bird_handle
;
152 stb_vorbis
*vorbis_handle
;
155 stb_vorbis_alloc vorbis_alloc
;
157 enum channel_activity
{
158 k_channel_activity_reset
, /* will advance if allocated==1, to wake */
159 k_channel_activity_wake
, /* will advance to either of next two */
160 k_channel_activity_alive
,
161 k_channel_activity_end
,
162 k_channel_activity_error
168 * editable structure, can be modified inside _lock and _unlock
169 * the edit mask tells which to copy into internal _, or to discard
170 * ----------------------------------------------------------------------
172 struct channel_state
{
175 float volume
, /* current volume */
176 volume_target
, /* target volume */
184 v4f spacial_falloff
; /* xyz, range */
190 u32 editble_state_write_mask
;
192 channels
[ AUDIO_CHANNELS
];
194 int debug_ui
, debug_ui_3d
, debug_dsp
;
196 v3f internal_listener_pos
,
197 internal_listener_ears
,
198 internal_listener_velocity
,
200 external_listener_pos
,
201 external_listener_ears
,
202 external_lister_velocity
;
204 float internal_global_volume
,
205 external_global_volume
;
207 static vg_audio
= { .external_global_volume
= 1.0f
};
209 #include "vg/vg_audio_dsp.h"
211 static struct vg_profile
212 _vg_prof_audio_decode
= {.mode
= k_profile_mode_accum
,
213 .name
= "[T2] audio_decode()"},
214 _vg_prof_audio_mix
= {.mode
= k_profile_mode_accum
,
215 .name
= "[T2] audio_mix()"},
216 _vg_prof_dsp
= {.mode
= k_profile_mode_accum
,
217 .name
= "[T2] dsp_process()"},
218 vg_prof_audio_decode
,
223 * These functions are called from the main thread and used to prevent bad
224 * access. TODO: They should be no-ops in release builds.
226 static int audio_lock_checker_load(void)
229 SDL_AtomicLock( &vg_audio
.sl_checker
);
230 value
= vg_audio
.sync_locked
;
231 SDL_AtomicUnlock( &vg_audio
.sl_checker
);
235 static void audio_lock_checker_store( int value
)
237 SDL_AtomicLock( &vg_audio
.sl_checker
);
238 vg_audio
.sync_locked
= value
;
239 SDL_AtomicUnlock( &vg_audio
.sl_checker
);
242 static void audio_require_lock(void)
244 if( audio_lock_checker_load() )
247 vg_error( "Modifying sound effects systems requires locking\n" );
251 static void audio_lock(void)
253 SDL_AtomicLock( &vg_audio
.sl_sync
);
254 audio_lock_checker_store(1);
257 static void audio_unlock(void)
259 audio_lock_checker_store(0);
260 SDL_AtomicUnlock( &vg_audio
.sl_sync
);
263 static void audio_mixer_callback( void *user
, u8
*stream
, int frame_count
);
264 static void vg_audio_init(void)
266 /* TODO: Move here? */
267 vg_console_reg_var( "debug_audio", &vg_audio
.debug_ui
,
268 k_var_dtype_i32
, VG_VAR_CHEAT
);
269 vg_console_reg_var( "debug_dsp", &vg_audio
.debug_dsp
,
270 k_var_dtype_i32
, VG_VAR_CHEAT
);
271 vg_console_reg_var( "volume", &vg_audio
.external_global_volume
,
272 k_var_dtype_f32
, VG_VAR_PERSISTENT
);
274 /* allocate memory */
276 vg_audio
.audio_pool
=
277 vg_create_linear_allocator( vg_mem
.rtmemory
, 1024*1024*32,
281 u32 decode_size
= AUDIO_DECODE_SIZE
* AUDIO_CHANNELS
;
282 vg_audio
.decode_buffer
= vg_linear_alloc( vg_mem
.rtmemory
, decode_size
);
286 SDL_AudioSpec spec_desired
, spec_got
;
287 spec_desired
.callback
= audio_mixer_callback
;
288 spec_desired
.channels
= 2;
289 spec_desired
.format
= AUDIO_F32
;
290 spec_desired
.freq
= 44100;
291 spec_desired
.padding
= 0;
292 spec_desired
.samples
= AUDIO_FRAME_SIZE
;
293 spec_desired
.silence
= 0;
294 spec_desired
.size
= 0;
295 spec_desired
.userdata
= NULL
;
297 vg_audio
.sdl_output_device
=
298 SDL_OpenAudioDevice( NULL
, 0, &spec_desired
, &spec_got
,0 );
300 if( vg_audio
.sdl_output_device
){
301 SDL_PauseAudioDevice( vg_audio
.sdl_output_device
, 0 );
305 "SDL_OpenAudioDevice failed. Your default audio device must support:\n"
306 " Frequency: 44100 hz\n"
307 " Buffer size: 512\n"
309 " Format: s16 or f32\n" );
313 static void vg_audio_free(void)
316 SDL_CloseAudioDevice( vg_audio
.sdl_output_device
);
323 #define AUDIO_EDIT_VOLUME_SLOPE 0x1
324 #define AUDIO_EDIT_VOLUME 0x2
325 #define AUDIO_EDIT_LFO_PERIOD 0x4
326 #define AUDIO_EDIT_LFO_WAVE 0x8
327 #define AUDIO_EDIT_LFO_ATTACHMENT 0x10
328 #define AUDIO_EDIT_SPACIAL 0x20
329 #define AUDIO_EDIT_OWNERSHIP 0x40
330 #define AUDIO_EDIT_SAMPLING_RATE 0x80
332 static void audio_channel_init( audio_channel
*ch
, audio_clip
*clip
, u32 flags
)
334 audio_require_lock();
339 ch
->colour
= 0x00333333;
341 if( (ch
->source
->flags
& AUDIO_FLAG_FORMAT
) == k_audio_format_bird
)
342 strcpy( ch
->name
, "[array]" );
344 vg_strncpy( clip
->path
, ch
->name
, 32, k_strncpy_always_add_null
);
348 ch
->editable_state
.relinquished
= 0;
349 ch
->editable_state
.volume
= 1.0f
;
350 ch
->editable_state
.volume_target
= 1.0f
;
351 ch
->editable_state
.pan
= 0.0f
;
352 ch
->editable_state
.pan_target
= 0.0f
;
353 ch
->editable_state
.volume_rate
= 0;
354 ch
->editable_state
.pan_rate
= 0;
355 v4_copy((v4f
){0.0f
,0.0f
,0.0f
,1.0f
},ch
->editable_state
.spacial_falloff
);
356 ch
->editable_state
.lfo
= NULL
;
357 ch
->editable_state
.lfo_amount
= 0.0f
;
358 ch
->editable_state
.sampling_rate
= 1.0f
;
359 ch
->editble_state_write_mask
= 0x00;
362 static void audio_channel_group( audio_channel
*ch
, u16 group
)
364 audio_require_lock();
366 ch
->colour
= (((u32
)group
* 29986577) & 0x00ffffff) | 0xff000000;
369 static void audio_channel_world( audio_channel
*ch
, u8 world_id
)
371 audio_require_lock();
372 ch
->world_id
= world_id
;
375 static audio_channel
*audio_get_first_idle_channel(void)
377 audio_require_lock();
378 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
379 audio_channel
*ch
= &vg_audio
.channels
[i
];
381 if( !ch
->allocated
){
389 static audio_channel
*audio_get_group_idle_channel( u16 group
, u32 max_count
)
391 audio_require_lock();
393 audio_channel
*dest
= NULL
;
395 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
396 audio_channel
*ch
= &vg_audio
.channels
[i
];
399 if( ch
->group
== group
){
409 if( dest
&& (count
< max_count
) ){
416 static audio_channel
*audio_get_group_first_active_channel( u16 group
)
418 audio_require_lock();
419 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
420 audio_channel
*ch
= &vg_audio
.channels
[i
];
421 if( ch
->allocated
&& (ch
->group
== group
) )
427 static int audio_channel_finished( audio_channel
*ch
)
429 audio_require_lock();
430 if( ch
->readable_activity
== k_channel_activity_end
)
436 static audio_channel
*audio_relinquish_channel( audio_channel
*ch
)
438 audio_require_lock();
439 ch
->editable_state
.relinquished
= 1;
440 ch
->editble_state_write_mask
|= AUDIO_EDIT_OWNERSHIP
;
444 static void audio_channel_slope_volume( audio_channel
*ch
, float length
,
447 audio_require_lock();
448 ch
->editable_state
.volume_target
= new_volume
;
449 ch
->editable_state
.volume_rate
= length
* 44100.0f
;
450 ch
->editble_state_write_mask
|= AUDIO_EDIT_VOLUME_SLOPE
;
453 static void audio_channel_set_sampling_rate( audio_channel
*ch
, float rate
)
455 audio_require_lock();
456 ch
->editable_state
.sampling_rate
= rate
;
457 ch
->editble_state_write_mask
|= AUDIO_EDIT_SAMPLING_RATE
;
460 static void audio_channel_edit_volume( audio_channel
*ch
,
461 float new_volume
, int instant
)
463 audio_require_lock();
465 ch
->editable_state
.volume
= new_volume
;
466 ch
->editble_state_write_mask
|= AUDIO_EDIT_VOLUME
;
469 audio_channel_slope_volume( ch
, 0.05f
, new_volume
);
473 static audio_channel
*audio_channel_fadeout( audio_channel
*ch
, float length
)
475 audio_require_lock();
476 audio_channel_slope_volume( ch
, length
, 0.0f
);
477 return audio_relinquish_channel( ch
);
480 static void audio_channel_fadein( audio_channel
*ch
, float length
)
482 audio_require_lock();
483 audio_channel_edit_volume( ch
, 0.0f
, 1 );
484 audio_channel_slope_volume( ch
, length
, 1.0f
);
487 static audio_channel
*audio_channel_crossfade( audio_channel
*ch
,
488 audio_clip
*new_clip
,
489 float length
, u32 flags
)
491 audio_require_lock();
495 ch
= audio_channel_fadeout( ch
, length
);
497 audio_channel
*replacement
= audio_get_first_idle_channel();
500 audio_channel_init( replacement
, new_clip
, flags
);
501 audio_channel_fadein( replacement
, length
);
507 static void audio_channel_sidechain_lfo( audio_channel
*ch
, int lfo_id
,
510 audio_require_lock();
511 ch
->editable_state
.lfo
= &vg_audio
.oscillators
[ lfo_id
];
512 ch
->editable_state
.lfo_amount
= amount
;
513 ch
->editble_state_write_mask
|= AUDIO_EDIT_LFO_ATTACHMENT
;
516 static void audio_channel_set_spacial( audio_channel
*ch
, v3f co
, float range
)
518 audio_require_lock();
519 if( ch
->flags
& AUDIO_FLAG_SPACIAL_3D
){
520 v3_copy( co
, ch
->editable_state
.spacial_falloff
);
523 ch
->editable_state
.spacial_falloff
[3] = 1.0f
;
525 ch
->editable_state
.spacial_falloff
[3] = 1.0f
/range
;
527 ch
->editble_state_write_mask
|= AUDIO_EDIT_SPACIAL
;
530 vg_warn( "Tried to set spacialization paramaters for 2D channel (%s)\n",
535 static int audio_oneshot_3d( audio_clip
*clip
, v3f position
,
536 float range
, float volume
)
538 audio_require_lock();
539 audio_channel
*ch
= audio_get_first_idle_channel();
542 audio_channel_init( ch
, clip
, AUDIO_FLAG_SPACIAL_3D
);
543 audio_channel_set_spacial( ch
, position
, range
);
544 audio_channel_edit_volume( ch
, volume
, 1 );
545 ch
= audio_relinquish_channel( ch
);
553 static int audio_oneshot( audio_clip
*clip
, float volume
, float pan
)
555 audio_require_lock();
556 audio_channel
*ch
= audio_get_first_idle_channel();
559 audio_channel_init( ch
, clip
, 0x00 );
560 audio_channel_edit_volume( ch
, volume
, 1 );
561 ch
= audio_relinquish_channel( ch
);
569 static void audio_set_lfo_wave( int id
, enum lfo_wave_type type
,
572 audio_require_lock();
573 audio_lfo
*lfo
= &vg_audio
.oscillators
[ id
];
574 lfo
->editable_state
.polynomial_coefficient
= coefficient
;
575 lfo
->editable_state
.wave_type
= type
;
577 lfo
->editble_state_write_mask
|= AUDIO_EDIT_LFO_WAVE
;
580 static void audio_set_lfo_frequency( int id
, float freq
)
582 audio_require_lock();
583 audio_lfo
*lfo
= &vg_audio
.oscillators
[ id
];
584 lfo
->editable_state
.period
= 44100.0f
/ freq
;
585 lfo
->editble_state_write_mask
|= AUDIO_EDIT_LFO_PERIOD
;
591 * -----------------------------------------------------------------------------
593 static int audio_channel_load_source( audio_channel
*ch
)
595 u32 format
= ch
->source
->flags
& AUDIO_FLAG_FORMAT
;
597 if( format
== k_audio_format_vorbis
){
598 /* Setup vorbis decoder */
599 u32 index
= ch
- vg_audio
.channels
;
601 u8
*buf
= (u8
*)vg_audio
.decode_buffer
,
602 *loc
= &buf
[AUDIO_DECODE_SIZE
*index
];
604 stb_vorbis_alloc alloc
= {
605 .alloc_buffer
= (char *)loc
,
606 .alloc_buffer_length_in_bytes
= AUDIO_DECODE_SIZE
610 stb_vorbis
*decoder
= stb_vorbis_open_memory(
612 ch
->source
->size
, &err
, &alloc
);
615 vg_error( "stb_vorbis_open_memory failed on '%s' (%d)\n",
616 ch
->source
->path
, err
);
620 ch
->source_length
= stb_vorbis_stream_length_in_samples( decoder
);
621 ch
->vorbis_handle
= decoder
;
624 else if( format
== k_audio_format_bird
){
625 u32 index
= ch
- vg_audio
.channels
;
627 u8
*buf
= (u8
*)vg_audio
.decode_buffer
;
628 struct synth_bird
*loc
= (void *)&buf
[AUDIO_DECODE_SIZE
*index
];
630 memcpy( loc
, ch
->source
->data
, ch
->source
->size
);
631 synth_bird_reset( loc
);
633 ch
->bird_handle
= loc
;
634 ch
->source_length
= synth_bird_get_length_in_samples( loc
);
636 else if( format
== k_audio_format_stereo
){
637 ch
->source_length
= ch
->source
->size
/ 2;
640 ch
->source_length
= ch
->source
->size
;
646 static void audio_decode_uncompressed_mono( i16
*src
, u32 count
, float *dst
)
648 for( u32 i
=0; i
<count
; i
++ ){
649 dst
[ i
*2 + 0 ] = ((float)src
[i
]) * (1.0f
/32767.0f
);
650 dst
[ i
*2 + 1 ] = ((float)src
[i
]) * (1.0f
/32767.0f
);
655 * adapted from stb_vorbis.h, since the original does not handle mono->stereo
658 stb_vorbis_get_samples_float_interleaved_stereo( stb_vorbis
*f
, float *buffer
,
662 c
= VG_MIN( 1, f
->channels
- 1 );
665 int k
= f
->channel_buffer_end
- f
->channel_buffer_start
;
670 for( int j
=0; j
< k
; ++j
) {
671 *buffer
++ = f
->channel_buffers
[ 0 ][f
->channel_buffer_start
+j
];
672 *buffer
++ = f
->channel_buffers
[ c
][f
->channel_buffer_start
+j
];
676 f
->channel_buffer_start
+= k
;
681 if( !stb_vorbis_get_frame_float( f
, NULL
, NULL
))
689 * ........ more wrecked code sorry!
692 stb_vorbis_get_samples_i16_downmixed( stb_vorbis
*f
, i16
*buffer
, int len
)
695 c
= VG_MIN( 1, f
->channels
- 1 );
698 int k
= f
->channel_buffer_end
- f
->channel_buffer_start
;
703 for( int j
=0; j
< k
; ++j
) {
704 float sl
= f
->channel_buffers
[ 0 ][f
->channel_buffer_start
+j
],
705 sr
= f
->channel_buffers
[ c
][f
->channel_buffer_start
+j
];
707 *buffer
++ = vg_clampf( 0.5f
*(sl
+sr
), -1.0f
, 1.0f
) * 32767.0f
;
708 //*buffer++ = vg_clampf( sr, -1.0f, 1.0f ) * 32767.0f;
712 f
->channel_buffer_start
+= k
;
717 if( !stb_vorbis_get_frame_float( f
, NULL
, NULL
))
724 static inline float audio_lfo_pull_sample( audio_lfo
*lfo
)
728 if( lfo
->time
>= lfo
->_
.period
)
732 t
/= (float)lfo
->_
.period
;
734 if( lfo
->_
.wave_type
== k_lfo_polynomial_bipolar
){
750 return (( 2.0f
* lfo
->sqrt_polynomial_coefficient
* t
) /
751 /* --------------------------------------- */
752 ( 1.0f
+ lfo
->_
.polynomial_coefficient
* t
*t
)
761 static void audio_channel_get_samples( audio_channel
*ch
,
762 u32 count
, float *buf
)
764 vg_profile_begin( &_vg_prof_audio_decode
);
766 u32 remaining
= count
;
769 u32 format
= ch
->source
->flags
& AUDIO_FLAG_FORMAT
;
772 u32 samples_this_run
= VG_MIN(remaining
, ch
->source_length
- ch
->cursor
);
773 remaining
-= samples_this_run
;
775 float *dst
= &buf
[ buffer_pos
* 2 ];
777 if( format
== k_audio_format_stereo
){
778 for( int i
=0;i
<samples_this_run
; i
++ ){
783 else if( format
== k_audio_format_vorbis
){
784 int read_samples
= stb_vorbis_get_samples_float_interleaved_stereo(
789 if( read_samples
!= samples_this_run
){
790 vg_warn( "Invalid samples read (%s)\n", ch
->source
->path
);
792 for( int i
=0; i
<samples_this_run
; i
++ ){
798 else if( format
== k_audio_format_bird
){
799 synth_bird_generate_samples( ch
->bird_handle
, dst
, samples_this_run
);
802 i16
*src_buffer
= ch
->source
->data
,
803 *src
= &src_buffer
[ch
->cursor
];
805 audio_decode_uncompressed_mono( src
, samples_this_run
, dst
);
808 ch
->cursor
+= samples_this_run
;
809 buffer_pos
+= samples_this_run
;
811 if( (ch
->flags
& AUDIO_FLAG_LOOP
) && remaining
){
812 if( format
== k_audio_format_vorbis
)
813 stb_vorbis_seek_start( ch
->vorbis_handle
);
814 else if( format
== k_audio_format_bird
)
815 synth_bird_reset( ch
->bird_handle
);
825 buf
[ buffer_pos
*2 + 0 ] = 0.0f
;
826 buf
[ buffer_pos
*2 + 1 ] = 0.0f
;
832 vg_profile_end( &_vg_prof_audio_decode
);
835 static void audio_channel_mix( audio_channel
*ch
, float *buffer
)
837 float framevol_l
= vg_audio
.internal_global_volume
,
838 framevol_r
= vg_audio
.internal_global_volume
;
840 float frame_samplerate
= ch
->_
.sampling_rate
;
842 if( ch
->flags
& AUDIO_FLAG_SPACIAL_3D
){
844 v3_sub( ch
->_
.spacial_falloff
, vg_audio
.internal_listener_pos
, delta
);
846 float dist
= v3_length( delta
),
847 vol
= vg_maxf( 0.0f
, 1.0f
- ch
->_
.spacial_falloff
[3]*dist
);
853 v3_muls( delta
, 1.0f
/dist
, delta
);
854 float pan
= v3_dot( vg_audio
.internal_listener_ears
, delta
);
855 vol
= powf( vol
, 5.0f
);
857 framevol_l
*= (vol
* 0.5f
) * (1.0f
- pan
);
858 framevol_r
*= (vol
* 0.5f
) * (1.0f
+ pan
);
860 if( !(ch
->source
->flags
& AUDIO_FLAG_NO_DOPPLER
) ){
861 const float vs
= 323.0f
;
863 float dv
= v3_dot(delta
,vg_audio
.internal_listener_velocity
);
864 float doppler
= (vs
+dv
)/vs
;
865 doppler
= vg_clampf( doppler
, 0.6f
, 1.4f
);
867 if( fabsf(doppler
-1.0f
) > 0.01f
)
868 frame_samplerate
*= doppler
;
872 if( !vg_validf( framevol_l
) ||
873 !vg_validf( framevol_r
) ||
874 !vg_validf( frame_samplerate
) ){
875 vg_fatal_error( "Invalid sampling conditions.\n"
876 "This crash is to protect your ears.\n"
877 " channel: %p (%s)\n"
880 " listener: %.2f %.2f %.2f [%.2f %.2f %.2f]\n",
881 ch
, ch
->name
, frame_samplerate
,
882 framevol_l
, framevol_r
,
883 vg_audio
.internal_listener_pos
[0],
884 vg_audio
.internal_listener_pos
[1],
885 vg_audio
.internal_listener_pos
[2],
886 vg_audio
.internal_listener_ears
[0],
887 vg_audio
.internal_listener_ears
[1],
888 vg_audio
.internal_listener_ears
[2]
893 u32 buffer_length
= AUDIO_MIX_FRAME_SIZE
;
894 if( frame_samplerate
!= 1.0f
){
895 float l
= ceilf( (float)(AUDIO_MIX_FRAME_SIZE
) * frame_samplerate
);
899 float pcf
[ AUDIO_MIX_FRAME_SIZE
* 2 * 2 ];
901 audio_channel_get_samples( ch
, buffer_length
, pcf
);
903 vg_profile_begin( &_vg_prof_audio_mix
);
905 float volume_movement
= ch
->volume_movement
;
906 float const fvolume_rate
= vg_maxf( 1.0f
, ch
->_
.volume_rate
);
907 const float inv_volume_rate
= 1.0f
/fvolume_rate
;
909 float volume
= ch
->_
.volume
;
910 const float volume_start
= ch
->volume_movement_start
;
911 const float volume_target
= ch
->_
.volume_target
;
913 for( u32 j
=0; j
<AUDIO_MIX_FRAME_SIZE
; j
++ ){
914 volume_movement
+= 1.0f
;
915 float movement_t
= volume_movement
* inv_volume_rate
;
916 movement_t
= vg_minf( movement_t
, 1.0f
);
917 volume
= vg_lerpf( volume_start
, volume_target
, movement_t
);
919 float vol_norm
= volume
* volume
;
922 vol_norm
*= 1.0f
+ audio_lfo_pull_sample(ch
->_
.lfo
) * ch
->_
.lfo_amount
;
924 float vol_l
= vol_norm
* framevol_l
,
925 vol_r
= vol_norm
* framevol_r
,
929 if( frame_samplerate
!= 1.0f
){
930 /* absolutely garbage resampling, but it will do
933 float sample_index
= frame_samplerate
* (float)j
;
934 float t
= vg_fractf( sample_index
);
936 u32 i0
= floorf( sample_index
),
939 sample_l
= pcf
[ i0
*2+0 ]*(1.0f
-t
) + pcf
[ i1
*2+0 ]*t
;
940 sample_r
= pcf
[ i0
*2+1 ]*(1.0f
-t
) + pcf
[ i1
*2+1 ]*t
;
943 sample_l
= pcf
[ j
*2+0 ];
944 sample_r
= pcf
[ j
*2+1 ];
947 buffer
[ j
*2+0 ] += sample_l
* vol_l
;
948 buffer
[ j
*2+1 ] += sample_r
* vol_r
;
951 ch
->volume_movement
+= AUDIO_MIX_FRAME_SIZE
;
952 ch
->volume_movement
= VG_MIN( ch
->volume_movement
, ch
->_
.volume_rate
);
953 ch
->_
.volume
= volume
;
955 vg_profile_end( &_vg_prof_audio_mix
);
958 static void audio_mixer_callback( void *user
, u8
*stream
, int byte_count
)
961 * Copy data and move edit flags to commit flags
962 * ------------------------------------------------------------- */
965 v3_copy( vg_audio
.external_listener_pos
, vg_audio
.internal_listener_pos
);
966 v3_copy( vg_audio
.external_listener_ears
, vg_audio
.internal_listener_ears
);
967 v3_copy( vg_audio
.external_lister_velocity
,
968 vg_audio
.internal_listener_velocity
);
969 vg_audio
.internal_global_volume
= vg_audio
.external_global_volume
;
971 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
972 audio_channel
*ch
= &vg_audio
.channels
[i
];
977 if( ch
->activity
== k_channel_activity_alive
){
978 if( (ch
->cursor
>= ch
->source_length
) &&
979 !(ch
->flags
& AUDIO_FLAG_LOOP
) )
981 ch
->activity
= k_channel_activity_end
;
985 /* process relinquishments */
986 if( (ch
->activity
!= k_channel_activity_reset
) && ch
->_
.relinquished
){
987 if( (ch
->activity
== k_channel_activity_end
)
988 || (ch
->_
.volume
== 0.0f
)
989 || (ch
->activity
== k_channel_activity_error
) )
991 ch
->_
.relinquished
= 0;
993 ch
->activity
= k_channel_activity_reset
;
998 /* process new channels */
999 if( ch
->activity
== k_channel_activity_reset
){
1000 ch
->_
= ch
->editable_state
;
1002 ch
->source_length
= 0;
1003 ch
->activity
= k_channel_activity_wake
;
1006 if( ch
->editble_state_write_mask
& AUDIO_EDIT_OWNERSHIP
)
1007 ch
->_
.relinquished
= ch
->editable_state
.relinquished
;
1009 ch
->editable_state
.relinquished
= ch
->_
.relinquished
;
1012 if( ch
->editble_state_write_mask
& AUDIO_EDIT_VOLUME
){
1013 ch
->_
.volume
= ch
->editable_state
.volume
;
1014 ch
->_
.volume_target
= ch
->editable_state
.volume
;
1017 ch
->editable_state
.volume
= ch
->_
.volume
;
1021 if( ch
->editble_state_write_mask
& AUDIO_EDIT_VOLUME_SLOPE
){
1022 ch
->volume_movement_start
= ch
->_
.volume
;
1023 ch
->volume_movement
= 0;
1025 ch
->_
.volume_target
= ch
->editable_state
.volume_target
;
1026 ch
->_
.volume_rate
= ch
->editable_state
.volume_rate
;
1029 ch
->editable_state
.volume_target
= ch
->_
.volume_target
;
1030 ch
->editable_state
.volume_rate
= ch
->_
.volume_rate
;
1034 if( ch
->editble_state_write_mask
& AUDIO_EDIT_SAMPLING_RATE
)
1035 ch
->_
.sampling_rate
= ch
->editable_state
.sampling_rate
;
1037 ch
->editable_state
.sampling_rate
= ch
->_
.sampling_rate
;
1040 if( ch
->editble_state_write_mask
& AUDIO_EDIT_LFO_ATTACHMENT
){
1041 ch
->_
.lfo
= ch
->editable_state
.lfo
;
1042 ch
->_
.lfo_amount
= ch
->editable_state
.lfo_amount
;
1045 ch
->editable_state
.lfo
= ch
->_
.lfo
;
1046 ch
->editable_state
.lfo_amount
= ch
->_
.lfo_amount
;
1050 if( ch
->editble_state_write_mask
& AUDIO_EDIT_SPACIAL
)
1051 v4_copy( ch
->editable_state
.spacial_falloff
,ch
->_
.spacial_falloff
);
1053 v4_copy( ch
->_
.spacial_falloff
,ch
->editable_state
.spacial_falloff
);
1056 /* currently readonly, i guess */
1057 ch
->editable_state
.pan_target
= ch
->_
.pan_target
;
1058 ch
->editable_state
.pan
= ch
->_
.pan
;
1059 ch
->editble_state_write_mask
= 0x00;
1062 for( int i
=0; i
<AUDIO_LFOS
; i
++ ){
1063 audio_lfo
*lfo
= &vg_audio
.oscillators
[ i
];
1065 if( lfo
->editble_state_write_mask
& AUDIO_EDIT_LFO_WAVE
){
1066 lfo
->_
.wave_type
= lfo
->editable_state
.wave_type
;
1068 if( lfo
->_
.wave_type
== k_lfo_polynomial_bipolar
){
1069 lfo
->_
.polynomial_coefficient
=
1070 lfo
->editable_state
.polynomial_coefficient
;
1071 lfo
->sqrt_polynomial_coefficient
=
1072 sqrtf(lfo
->_
.polynomial_coefficient
);
1076 if( lfo
->editble_state_write_mask
& AUDIO_EDIT_LFO_PERIOD
){
1077 if( lfo
->_
.period
){
1078 float t
= lfo
->time
;
1079 t
/= (float)lfo
->_
.period
;
1081 lfo
->_
.period
= lfo
->editable_state
.period
;
1082 lfo
->time
= lfo
->_
.period
* t
;
1086 lfo
->_
.period
= lfo
->editable_state
.period
;
1090 lfo
->editble_state_write_mask
= 0x00;
1093 dsp_update_tunings();
1098 * ------------------------------------------------------------- */
1099 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
1100 audio_channel
*ch
= &vg_audio
.channels
[i
];
1102 if( ch
->activity
== k_channel_activity_wake
){
1103 if( audio_channel_load_source( ch
) )
1104 ch
->activity
= k_channel_activity_alive
;
1106 ch
->activity
= k_channel_activity_error
;
1112 * -------------------------------------------------------- */
1113 int frame_count
= byte_count
/(2*sizeof(float));
1116 float *pOut32F
= (float *)stream
;
1117 for( int i
=0; i
<frame_count
*2; i
++ )
1120 for( int i
=0; i
<AUDIO_LFOS
; i
++ ){
1121 audio_lfo
*lfo
= &vg_audio
.oscillators
[i
];
1122 lfo
->time_startframe
= lfo
->time
;
1125 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
1126 audio_channel
*ch
= &vg_audio
.channels
[i
];
1128 if( ch
->activity
== k_channel_activity_alive
){
1130 ch
->_
.lfo
->time
= ch
->_
.lfo
->time_startframe
;
1132 u32 remaining
= frame_count
,
1136 audio_channel_mix( ch
, pOut32F
+subpos
);
1137 remaining
-= AUDIO_MIX_FRAME_SIZE
;
1138 subpos
+= AUDIO_MIX_FRAME_SIZE
*2;
1143 vg_profile_begin( &_vg_prof_dsp
);
1145 for( int i
=0; i
<frame_count
; i
++ )
1146 vg_dsp_process( pOut32F
+ i
*2, pOut32F
+ i
*2 );
1148 vg_profile_end( &_vg_prof_dsp
);
1152 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
1153 audio_channel
*ch
= &vg_audio
.channels
[i
];
1154 ch
->readable_activity
= ch
->activity
;
1157 /* Profiling information
1158 * ----------------------------------------------- */
1159 vg_profile_increment( &_vg_prof_audio_decode
);
1160 vg_profile_increment( &_vg_prof_audio_mix
);
1161 vg_profile_increment( &_vg_prof_dsp
);
1163 vg_prof_audio_mix
= _vg_prof_audio_mix
;
1164 vg_prof_audio_decode
= _vg_prof_audio_decode
;
1165 vg_prof_audio_dsp
= _vg_prof_dsp
;
1167 vg_audio
.samples_last
= frame_count
;
1169 if( vg_audio
.debug_dsp
){
1170 vg_dsp_update_texture();
1176 static void audio_clip_load( audio_clip
*clip
, void *lin_alloc
)
1178 if( lin_alloc
== NULL
)
1179 lin_alloc
= vg_audio
.audio_pool
;
1181 /* load in directly */
1182 u32 format
= clip
->flags
& AUDIO_FLAG_FORMAT
;
1184 /* TODO: This contains audio_lock() and unlock, but i don't know why
1185 * can probably remove them. Low priority to check this */
1187 /* TODO: packed files for vorbis etc, should take from data if its not not
1188 * NULL when we get the clip
1191 if( format
== k_audio_format_vorbis
){
1193 vg_fatal_error( "No path specified, embeded vorbis unsupported" );
1197 clip
->data
= vg_file_read( lin_alloc
, clip
->path
, &clip
->size
);
1201 vg_fatal_error( "Audio failed to load" );
1203 float mb
= (float)(clip
->size
) / (1024.0f
*1024.0f
);
1204 vg_info( "Loaded audio clip '%s' (%.1fmb)\n", clip
->path
, mb
);
1206 else if( format
== k_audio_format_stereo
){
1207 vg_fatal_error( "Unsupported format (Stereo uncompressed)" );
1209 else if( format
== k_audio_format_bird
){
1211 vg_fatal_error( "No data, external birdsynth unsupported" );
1214 u32 total_size
= clip
->size
+ sizeof(struct synth_bird
);
1215 total_size
-= sizeof(struct synth_bird_settings
);
1216 total_size
= vg_align8( total_size
);
1218 if( total_size
> AUDIO_DECODE_SIZE
)
1219 vg_fatal_error( "Bird coding too long\n" );
1221 struct synth_bird
*bird
= vg_linear_alloc( lin_alloc
, total_size
);
1222 memcpy( &bird
->settings
, clip
->data
, clip
->size
);
1225 clip
->size
= total_size
;
1227 vg_info( "Loaded bird synthesis pattern (%u bytes)\n", total_size
);
1231 vg_fatal_error( "No path specified, embeded mono unsupported" );
1234 vg_linear_clear( vg_mem
.scratch
);
1237 stb_vorbis_alloc alloc
= {
1238 .alloc_buffer
= vg_linear_alloc( vg_mem
.scratch
, AUDIO_DECODE_SIZE
),
1239 .alloc_buffer_length_in_bytes
= AUDIO_DECODE_SIZE
1242 void *filedata
= vg_file_read( vg_mem
.scratch
, clip
->path
, &fsize
);
1245 stb_vorbis
*decoder
= stb_vorbis_open_memory(
1246 filedata
, fsize
, &err
, &alloc
);
1249 vg_error( "stb_vorbis_open_memory failed on '%s' (%d)\n",
1251 vg_fatal_error( "Vorbis decode error" );
1254 /* only mono is supported in uncompressed */
1255 u32 length_samples
= stb_vorbis_stream_length_in_samples( decoder
),
1256 data_size
= length_samples
* sizeof(i16
);
1259 clip
->data
= vg_linear_alloc( lin_alloc
, vg_align8(data_size
) );
1260 clip
->size
= length_samples
;
1263 int read_samples
= stb_vorbis_get_samples_i16_downmixed(
1264 decoder
, clip
->data
, length_samples
);
1266 if( read_samples
!= length_samples
)
1267 vg_fatal_error( "Decode error" );
1270 float mb
= (float)(data_size
) / (1024.0f
*1024.0f
);
1271 vg_info( "Loaded audio clip '%s' (%.1fmb) %u samples\n", clip
->path
, mb
,
1277 static void audio_clip_loadn( audio_clip
*arr
, int count
, void *lin_alloc
)
1279 for( int i
=0; i
<count
; i
++ )
1280 audio_clip_load( &arr
[i
], lin_alloc
);
1283 static void audio_require_clip_loaded( audio_clip
*clip
)
1285 if( clip
->data
&& clip
->size
)
1289 vg_fatal_error( "Must load audio clip before playing! \n" );
1296 static void audio_debug_ui( m4x4f mtx_pv
)
1298 if( !vg_audio
.debug_ui
)
1303 glBindTexture( GL_TEXTURE_2D
, vg_dsp
.view_texture
);
1304 glTexSubImage2D( GL_TEXTURE_2D
, 0, 0, 0, 256, 256,
1305 GL_RGBA
, GL_UNSIGNED_BYTE
,
1306 vg_dsp
.view_texture_buffer
);
1310 * -----------------------------------------------------------------------
1313 float budget
= ((double)vg_audio
.samples_last
/ 44100.0) * 1000.0;
1314 vg_profile_drawn( (struct vg_profile
*[]){ &vg_prof_audio_decode
,
1316 &vg_prof_audio_dsp
}, 3,
1317 budget
, (ui_rect
){ 4, VG_PROFILE_SAMPLE_COUNT
*2 + 8,
1331 if( vg_audio
.debug_dsp
){
1332 ui_rect view_thing
= { 4, vg
.window_y
-512-4, 512, 512 };
1333 ui_image( view_thing
, vg_dsp
.view_texture
);
1336 ui_rect overlap_buffer
[ AUDIO_CHANNELS
];
1337 u32 overlap_length
= 0;
1339 /* Draw audio stack */
1340 for( int i
=0; i
<AUDIO_CHANNELS
; i
++ ){
1341 audio_channel
*ch
= &vg_audio
.channels
[i
];
1344 ui_split( window
, k_ui_axis_h
, 18, 1, row
, window
);
1346 if( !ch
->allocated
){
1347 ui_fill( row
, 0x50333333 );
1351 const char *formats
[] =
1371 const char *activties
[] =
1380 u32 format_index
= (ch
->source
->flags
& AUDIO_FLAG_FORMAT
)>>9;
1382 snprintf( perf
, 127, "%02d[%#04x.%#06x]%c%c%cD %s [%s] %4.2fv'%s'",
1384 ch
->world_id
, ch
->group
,
1385 (ch
->editable_state
.relinquished
)? 'r': '_',
1388 formats
[format_index
],
1389 activties
[ch
->readable_activity
],
1390 ch
->editable_state
.volume
,
1393 ui_fill( row
, 0xa0000000 | ch
->colour
);
1394 ui_text( row
, perf
, 1, k_ui_align_middle_left
, 0 );
1396 if( AUDIO_FLAG_SPACIAL_3D
){
1398 v3_copy( ch
->editable_state
.spacial_falloff
, wpos
);
1401 m4x4_mulv( mtx_pv
, wpos
, wpos
);
1403 if( wpos
[3] > 0.0f
){
1404 v2_muls( wpos
, (1.0f
/wpos
[3]) * 0.5f
, wpos
);
1405 v2_add( wpos
, (v2f
){ 0.5f
, 0.5f
}, wpos
);
1408 wr
[0] = vg_clampf(wpos
[0] * vg
.window_x
, -32000.0f
,32000.0f
);
1409 wr
[1] = vg_clampf((1.0f
-wpos
[1]) * vg
.window_y
,-32000.0f
,32000.0f
);
1413 for( int j
=0; j
<12; j
++ ){
1415 for( int k
=0; k
<overlap_length
; k
++ ){
1416 ui_px
*wk
= overlap_buffer
[k
];
1417 if( ((wr
[0] <= wk
[0]+wk
[2]) && (wr
[0]+wr
[2] >= wk
[0])) &&
1418 ((wr
[1] <= wk
[1]+wk
[3]) && (wr
[1]+wr
[3] >= wk
[1])) )
1431 ui_text( wr
, perf
, 1, k_ui_align_middle_left
, 0 );
1432 rect_copy( wr
, overlap_buffer
[ overlap_length
++ ] );
1440 #endif /* VG_AUDIO_H */