memory semantics
[vg.git] / vg_audio.h
1 /* Copyright (C) 2021-2023 Harry Godden (hgn) - All Rights Reserved */
2
3 #ifndef VG_AUDIO_H
4 #define VG_AUDIO_H
5
6 #define VG_GAME
7
8 #include "vg/vg.h"
9 #include "vg/vg_stdint.h"
10 #include "vg/vg_platform.h"
11 #include "vg/vg_io.h"
12 #include "vg/vg_m.h"
13 #include "vg/vg_ui.h"
14 #include "vg/vg_console.h"
15 #include "vg/vg_store.h"
16 #include "vg/vg_profiler.h"
17 #include "vg/vg_audio_synth_bird.h"
18
19 #include <sys/time.h>
20 #include <math.h>
21
22 #ifdef __GNUC__
23 #ifndef __clang__
24 #pragma GCC push_options
25 #pragma GCC optimize ("O3")
26 #pragma GCC diagnostic push
27 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
28 #endif
29 #endif
30
31 #define STB_VORBIS_MAX_CHANNELS 2
32 #include "submodules/stb/stb_vorbis.c"
33 #undef L
34 #undef R
35 #undef C
36
37 #ifdef __GNUC__
38 #ifndef __clang__
39 #pragma GCC pop_options
40 #pragma GCC diagnostic pop
41 #endif
42 #endif
43
44 #define AUDIO_FRAME_SIZE 512
45 #define AUDIO_MIX_FRAME_SIZE 256
46
47 #define AUDIO_CHANNELS 32
48 #define AUDIO_LFOS 8
49 #define AUDIO_FILTERS 16
50 #define AUDIO_FLAG_LOOP 0x1
51 #define AUDIO_FLAG_NO_DOPPLER 0x2
52 #define AUDIO_FLAG_SPACIAL_3D 0x4
53 #define AUDIO_FLAG_AUTO_START 0x8
54 #define AUDIO_FLAG_FORMAT 0x1E00
55
56 enum audio_format
57 {
58 k_audio_format_mono = 0x000u,
59 k_audio_format_stereo = 0x200u,
60 k_audio_format_vorbis = 0x400u,
61 k_audio_format_none0 = 0x600u,
62 k_audio_format_none1 = 0x800u,
63 k_audio_format_none2 = 0xA00u,
64 k_audio_format_none3 = 0xC00u,
65 k_audio_format_none4 = 0xE00u,
66
67 k_audio_format_bird = 0x1000u,
68 k_audio_format_none5 = 0x1200u,
69 k_audio_format_none6 = 0x1400u,
70 k_audio_format_none7 = 0x1600u,
71 k_audio_format_none8 = 0x1800u,
72 k_audio_format_none9 = 0x1A00u,
73 k_audio_format_none10 = 0x1C00u,
74 k_audio_format_none11 = 0x1E00u,
75 };
76
77 #define AUDIO_DECODE_SIZE (1024*256) /* 256 kb decoding buffers */
78 #define AUDIO_MUTE_VOLUME 0.0f
79 #define AUDIO_BASE_VOLUME 1.0f
80
81 typedef struct audio_clip audio_clip;
82 typedef struct audio_channel audio_channel;
83 typedef struct audio_lfo audio_lfo;
84
85 struct audio_clip{
86 const char *path;
87 u32 flags;
88 u32 size;
89 void *data;
90 };
91
92 static struct vg_audio_system{
93 SDL_AudioDeviceID sdl_output_device;
94
95 void *audio_pool,
96 *decode_buffer;
97 u32 samples_last;
98
99 /* synchro */
100 int sync_locked;
101
102 SDL_SpinLock sl_checker,
103 sl_sync;
104
105 struct audio_lfo{
106 u32 time, time_startframe;
107 float sqrt_polynomial_coefficient;
108
109 struct{
110 enum lfo_wave_type{
111 k_lfo_triangle,
112 k_lfo_square,
113 k_lfo_saw,
114 k_lfo_polynomial_bipolar
115 }
116 wave_type;
117
118 u32 period;
119 float polynomial_coefficient;
120 }
121 _, editable_state;
122 u32 editble_state_write_mask;
123 }
124 oscillators[ AUDIO_LFOS ];
125
126 struct audio_channel{
127 int allocated;
128 u16 group;
129 u8 world_id;
130
131 char name[32]; /* only editable while allocated == 0 */
132 audio_clip *source; /* ... */
133 u32 flags; /* ... */
134 u32 colour; /* ... */
135
136 /* internal non-readable state
137 * -----------------------------*/
138 u32 cursor, source_length;
139
140 float volume_movement_start,
141 pan_movement_start;
142
143 u32 volume_movement,
144 pan_movement;
145
146 union{
147 struct synth_bird *bird_handle;
148 stb_vorbis *vorbis_handle;
149 };
150
151 stb_vorbis_alloc vorbis_alloc;
152
153 enum channel_activity{
154 k_channel_activity_reset, /* will advance if allocated==1, to wake */
155 k_channel_activity_wake, /* will advance to either of next two */
156 k_channel_activity_alive,
157 k_channel_activity_end,
158 k_channel_activity_error
159 }
160 activity,
161 readable_activity;
162
163 /*
164 * editable structure, can be modified inside _lock and _unlock
165 * the edit mask tells which to copy into internal _, or to discard
166 * ----------------------------------------------------------------------
167 */
168 struct channel_state{
169 int relinquished;
170
171 float volume, /* current volume */
172 volume_target, /* target volume */
173 pan,
174 pan_target,
175 sampling_rate;
176
177 u32 volume_rate,
178 pan_rate;
179
180 v4f spacial_falloff; /* xyz, range */
181
182 audio_lfo *lfo;
183 float lfo_amount;
184 }
185 _, editable_state;
186 u32 editble_state_write_mask;
187 }
188 channels[ AUDIO_CHANNELS ];
189
190 int debug_ui, debug_ui_3d, debug_dsp;
191
192 v3f internal_listener_pos,
193 internal_listener_ears,
194 internal_listener_velocity,
195
196 external_listener_pos,
197 external_listener_ears,
198 external_lister_velocity;
199
200 float internal_global_volume,
201 external_global_volume;
202 }
203 vg_audio = { .external_global_volume = 1.0f };
204
205 #include "vg/vg_audio_dsp.h"
206
207 static struct vg_profile
208 _vg_prof_audio_decode = {.mode = k_profile_mode_accum,
209 .name = "[T2] audio_decode()"},
210 _vg_prof_audio_mix = {.mode = k_profile_mode_accum,
211 .name = "[T2] audio_mix()"},
212 _vg_prof_dsp = {.mode = k_profile_mode_accum,
213 .name = "[T2] dsp_process()"},
214 vg_prof_audio_decode,
215 vg_prof_audio_mix,
216 vg_prof_audio_dsp;
217
218 /*
219 * These functions are called from the main thread and used to prevent bad
220 * access. TODO: They should be no-ops in release builds.
221 */
222 VG_STATIC int audio_lock_checker_load(void)
223 {
224 int value;
225 SDL_AtomicLock( &vg_audio.sl_checker );
226 value = vg_audio.sync_locked;
227 SDL_AtomicUnlock( &vg_audio.sl_checker );
228 return value;
229 }
230
231 VG_STATIC void audio_lock_checker_store( int value )
232 {
233 SDL_AtomicLock( &vg_audio.sl_checker );
234 vg_audio.sync_locked = value;
235 SDL_AtomicUnlock( &vg_audio.sl_checker );
236 }
237
238 VG_STATIC void audio_require_lock(void)
239 {
240 if( audio_lock_checker_load() )
241 return;
242
243 vg_error( "Modifying sound effects systems requires locking\n" );
244 abort();
245 }
246
247 VG_STATIC void audio_lock(void)
248 {
249 SDL_AtomicLock( &vg_audio.sl_sync );
250 audio_lock_checker_store(1);
251 }
252
253 VG_STATIC void audio_unlock(void)
254 {
255 audio_lock_checker_store(0);
256 SDL_AtomicUnlock( &vg_audio.sl_sync );
257 }
258
259 VG_STATIC void audio_mixer_callback( void *user, u8 *stream, int frame_count );
260 VG_STATIC void vg_audio_init(void)
261 {
262 /* TODO: Move here? */
263 vg_console_reg_var( "debug_audio", &vg_audio.debug_ui,
264 k_var_dtype_i32, VG_VAR_CHEAT );
265 vg_console_reg_var( "debug_dsp", &vg_audio.debug_dsp,
266 k_var_dtype_i32, VG_VAR_CHEAT );
267 vg_console_reg_var( "volume", &vg_audio.external_global_volume,
268 k_var_dtype_f32, VG_VAR_PERSISTENT );
269
270 /* allocate memory */
271 /* 32mb fixed */
272 vg_audio.audio_pool =
273 vg_create_linear_allocator( vg_mem.rtmemory, 1024*1024*32,
274 VG_MEMORY_SYSTEM );
275
276 /* fixed */
277 u32 decode_size = AUDIO_DECODE_SIZE * AUDIO_CHANNELS;
278 vg_audio.decode_buffer = vg_linear_alloc( vg_mem.rtmemory, decode_size );
279
280 vg_dsp_init();
281
282 SDL_AudioSpec spec_desired, spec_got;
283 spec_desired.callback = audio_mixer_callback;
284 spec_desired.channels = 2;
285 spec_desired.format = AUDIO_F32;
286 spec_desired.freq = 44100;
287 spec_desired.padding = 0;
288 spec_desired.samples = AUDIO_FRAME_SIZE;
289 spec_desired.silence = 0;
290 spec_desired.size = 0;
291 spec_desired.userdata = NULL;
292
293 vg_audio.sdl_output_device =
294 SDL_OpenAudioDevice( NULL, 0, &spec_desired, &spec_got,0 );
295
296 if( vg_audio.sdl_output_device ){
297 SDL_PauseAudioDevice( vg_audio.sdl_output_device, 0 );
298 }
299 else{
300 vg_fatal_error(
301 "SDL_OpenAudioDevice failed. Your default audio device must support:\n"
302 " Frequency: 44100 hz\n"
303 " Buffer size: 512\n"
304 " Channels: 2\n"
305 " Format: s16 or f32\n" );
306 }
307 }
308
309 VG_STATIC void vg_audio_free(void)
310 {
311 vg_dsp_free();
312 SDL_CloseAudioDevice( vg_audio.sdl_output_device );
313 }
314
315 /*
316 * thread 1
317 */
318
319 #define AUDIO_EDIT_VOLUME_SLOPE 0x1
320 #define AUDIO_EDIT_VOLUME 0x2
321 #define AUDIO_EDIT_LFO_PERIOD 0x4
322 #define AUDIO_EDIT_LFO_WAVE 0x8
323 #define AUDIO_EDIT_LFO_ATTACHMENT 0x10
324 #define AUDIO_EDIT_SPACIAL 0x20
325 #define AUDIO_EDIT_OWNERSHIP 0x40
326 #define AUDIO_EDIT_SAMPLING_RATE 0x80
327
328 static void audio_channel_init( audio_channel *ch, audio_clip *clip, u32 flags )
329 {
330 ch->group = 0;
331 ch->world_id = 0;
332 ch->source = clip;
333 ch->flags = flags;
334 ch->colour = 0x00333333;
335
336 if( (ch->source->flags & AUDIO_FLAG_FORMAT) == k_audio_format_bird )
337 strcpy( ch->name, "[array]" );
338 else
339 vg_strncpy( clip->path, ch->name, 32, k_strncpy_always_add_null );
340
341 ch->allocated = 1;
342
343 ch->editable_state.relinquished = 0;
344 ch->editable_state.volume = 1.0f;
345 ch->editable_state.volume_target = 1.0f;
346 ch->editable_state.pan = 0.0f;
347 ch->editable_state.pan_target = 0.0f;
348 ch->editable_state.volume_rate = 0;
349 ch->editable_state.pan_rate = 0;
350 v4_copy((v4f){0.0f,0.0f,0.0f,1.0f},ch->editable_state.spacial_falloff);
351 ch->editable_state.lfo = NULL;
352 ch->editable_state.lfo_amount = 0.0f;
353 ch->editable_state.sampling_rate = 1.0f;
354 ch->editble_state_write_mask = 0x00;
355 }
356
357 static void audio_channel_group( audio_channel *ch, u16 group )
358 {
359 ch->group = group;
360 ch->colour = (((u32)group * 29986577) & 0x00ffffff) | 0xff000000;
361 }
362
363 static void audio_channel_world( audio_channel *ch, u8 world_id )
364 {
365 ch->world_id = world_id;
366 }
367
368 static audio_channel *audio_get_first_idle_channel(void)
369 {
370 for( int i=0; i<AUDIO_CHANNELS; i++ ){
371 audio_channel *ch = &vg_audio.channels[i];
372
373 if( !ch->allocated ){
374 return ch;
375 }
376 }
377
378 return NULL;
379 }
380
381 static audio_channel *audio_get_group_idle_channel( u16 group, u32 max_count )
382 {
383 u32 count = 0;
384 audio_channel *dest = NULL;
385
386 for( int i=0; i<AUDIO_CHANNELS; i++ ){
387 audio_channel *ch = &vg_audio.channels[i];
388
389 if( ch->allocated ){
390 if( ch->group == group ){
391 count ++;
392 }
393 }
394 else{
395 if( !dest )
396 dest = ch;
397 }
398 }
399
400 if( dest && (count < max_count) ){
401 return dest;
402 }
403
404 return NULL;
405 }
406
407 static audio_channel *audio_get_group_first_active_channel( u16 group )
408 {
409 for( int i=0; i<AUDIO_CHANNELS; i++ ){
410 audio_channel *ch = &vg_audio.channels[i];
411 if( ch->allocated && (ch->group == group) )
412 return ch;
413 }
414 return NULL;
415 }
416
417 static int audio_channel_finished( audio_channel *ch )
418 {
419 if( ch->readable_activity == k_channel_activity_end )
420 return 1;
421 else
422 return 0;
423 }
424
425 static audio_channel *audio_relinquish_channel( audio_channel *ch )
426 {
427 ch->editable_state.relinquished = 1;
428 ch->editble_state_write_mask |= AUDIO_EDIT_OWNERSHIP;
429 return NULL;
430 }
431
432 static void audio_channel_slope_volume( audio_channel *ch, float length,
433 float new_volume )
434 {
435 ch->editable_state.volume_target = new_volume;
436 ch->editable_state.volume_rate = length * 44100.0f;
437 ch->editble_state_write_mask |= AUDIO_EDIT_VOLUME_SLOPE;
438 }
439
440 static void audio_channel_set_sampling_rate( audio_channel *ch, float rate )
441 {
442 ch->editable_state.sampling_rate = rate;
443 ch->editble_state_write_mask |= AUDIO_EDIT_SAMPLING_RATE;
444 }
445
446 static void audio_channel_edit_volume( audio_channel *ch,
447 float new_volume, int instant )
448 {
449 if( instant ){
450 ch->editable_state.volume = new_volume;
451 ch->editble_state_write_mask |= AUDIO_EDIT_VOLUME;
452 }
453 else{
454 audio_channel_slope_volume( ch, 0.05f, new_volume );
455 }
456 }
457
458 static audio_channel *audio_channel_fadeout( audio_channel *ch, float length )
459 {
460 audio_channel_slope_volume( ch, length, 0.0f );
461 return audio_relinquish_channel( ch );
462 }
463
464 static void audio_channel_fadein( audio_channel *ch, float length )
465 {
466 audio_channel_edit_volume( ch, 0.0f, 1 );
467 audio_channel_slope_volume( ch, length, 1.0f );
468 }
469
470 static audio_channel *audio_channel_crossfade( audio_channel *ch,
471 audio_clip *new_clip,
472 float length, u32 flags )
473 {
474 u32 cursor = 0;
475
476 if( ch )
477 ch = audio_channel_fadeout( ch, length );
478
479 audio_channel *replacement = audio_get_first_idle_channel();
480
481 if( replacement ){
482 audio_channel_init( replacement, new_clip, flags );
483 audio_channel_fadein( replacement, length );
484 }
485
486 return replacement;
487 }
488
489 static void audio_channel_sidechain_lfo( audio_channel *ch, int lfo_id,
490 float amount )
491 {
492 ch->editable_state.lfo = &vg_audio.oscillators[ lfo_id ];
493 ch->editable_state.lfo_amount = amount;
494 ch->editble_state_write_mask |= AUDIO_EDIT_LFO_ATTACHMENT;
495 }
496
497 static void audio_channel_set_spacial( audio_channel *ch, v3f co, float range )
498 {
499 if( ch->flags & AUDIO_FLAG_SPACIAL_3D ){
500 v3_copy( co, ch->editable_state.spacial_falloff );
501
502 if( range == 0.0f )
503 ch->editable_state.spacial_falloff[3] = 1.0f;
504 else
505 ch->editable_state.spacial_falloff[3] = 1.0f/range;
506
507 ch->editble_state_write_mask |= AUDIO_EDIT_SPACIAL;
508 }
509 else{
510 vg_warn( "Tried to set spacialization paramaters for 2D channel (%s)\n",
511 ch->name );
512 }
513 }
514
515 static int audio_oneshot_3d( audio_clip *clip, v3f position,
516 float range, float volume )
517 {
518 audio_channel *ch = audio_get_first_idle_channel();
519
520 if( ch ){
521 audio_channel_init( ch, clip, AUDIO_FLAG_SPACIAL_3D );
522 audio_channel_set_spacial( ch, position, range );
523 audio_channel_edit_volume( ch, volume, 1 );
524 ch = audio_relinquish_channel( ch );
525
526 return 1;
527 }
528 else
529 return 0;
530 }
531
532 static int audio_oneshot( audio_clip *clip, float volume, float pan )
533 {
534 audio_channel *ch = audio_get_first_idle_channel();
535
536 if( ch ){
537 audio_channel_init( ch, clip, 0x00 );
538 audio_channel_edit_volume( ch, volume, 1 );
539 ch = audio_relinquish_channel( ch );
540
541 return 1;
542 }
543 else
544 return 0;
545 }
546
547 static void audio_set_lfo_wave( int id, enum lfo_wave_type type,
548 float coefficient )
549 {
550 audio_lfo *lfo = &vg_audio.oscillators[ id ];
551 lfo->editable_state.polynomial_coefficient = coefficient;
552 lfo->editable_state.wave_type = type;
553
554 lfo->editble_state_write_mask |= AUDIO_EDIT_LFO_WAVE;
555 }
556
557 static void audio_set_lfo_frequency( int id, float freq )
558 {
559 audio_lfo *lfo = &vg_audio.oscillators[ id ];
560 lfo->editable_state.period = 44100.0f / freq;
561 lfo->editble_state_write_mask |= AUDIO_EDIT_LFO_PERIOD;
562 }
563
564
565 /*
566 * Committers
567 * -----------------------------------------------------------------------------
568 */
569 static int audio_channel_load_source( audio_channel *ch )
570 {
571 u32 format = ch->source->flags & AUDIO_FLAG_FORMAT;
572
573 if( format == k_audio_format_vorbis ){
574 /* Setup vorbis decoder */
575 u32 index = ch - vg_audio.channels;
576
577 u8 *buf = (u8*)vg_audio.decode_buffer,
578 *loc = &buf[AUDIO_DECODE_SIZE*index];
579
580 stb_vorbis_alloc alloc = {
581 .alloc_buffer = (char *)loc,
582 .alloc_buffer_length_in_bytes = AUDIO_DECODE_SIZE
583 };
584
585 int err;
586 stb_vorbis *decoder = stb_vorbis_open_memory(
587 ch->source->data,
588 ch->source->size, &err, &alloc );
589
590 if( !decoder ){
591 vg_error( "stb_vorbis_open_memory failed on '%s' (%d)\n",
592 ch->source->path, err );
593 return 0;
594 }
595 else{
596 ch->source_length = stb_vorbis_stream_length_in_samples( decoder );
597 ch->vorbis_handle = decoder;
598 }
599 }
600 else if( format == k_audio_format_bird ){
601 u32 index = ch - vg_audio.channels;
602
603 u8 *buf = (u8*)vg_audio.decode_buffer;
604 struct synth_bird *loc = (void *)&buf[AUDIO_DECODE_SIZE*index];
605
606 memcpy( loc, ch->source->data, ch->source->size );
607 synth_bird_reset( loc );
608
609 ch->bird_handle = loc;
610 ch->source_length = synth_bird_get_length_in_samples( loc );
611 }
612 else if( format == k_audio_format_stereo ){
613 ch->source_length = ch->source->size / 2;
614 }
615 else{
616 ch->source_length = ch->source->size;
617 }
618
619 return 1;
620 }
621
622 VG_STATIC void audio_decode_uncompressed_mono( i16 *src, u32 count, float *dst )
623 {
624 for( u32 i=0; i<count; i++ ){
625 dst[ i*2 + 0 ] = ((float)src[i]) * (1.0f/32767.0f);
626 dst[ i*2 + 1 ] = ((float)src[i]) * (1.0f/32767.0f);
627 }
628 }
629
630 /*
631 * adapted from stb_vorbis.h, since the original does not handle mono->stereo
632 */
633 VG_STATIC int
634 stb_vorbis_get_samples_float_interleaved_stereo( stb_vorbis *f, float *buffer,
635 int len )
636 {
637 int n = 0,
638 c = VG_MIN( 1, f->channels - 1 );
639
640 while( n < len ) {
641 int k = f->channel_buffer_end - f->channel_buffer_start;
642
643 if( n+k >= len )
644 k = len - n;
645
646 for( int j=0; j < k; ++j ) {
647 *buffer++ = f->channel_buffers[ 0 ][f->channel_buffer_start+j];
648 *buffer++ = f->channel_buffers[ c ][f->channel_buffer_start+j];
649 }
650
651 n += k;
652 f->channel_buffer_start += k;
653
654 if( n == len )
655 break;
656
657 if( !stb_vorbis_get_frame_float( f, NULL, NULL ))
658 break;
659 }
660
661 return n;
662 }
663
664 /*
665 * ........ more wrecked code sorry!
666 */
667 VG_STATIC int
668 stb_vorbis_get_samples_i16_downmixed( stb_vorbis *f, i16 *buffer, int len )
669 {
670 int n = 0,
671 c = VG_MIN( 1, f->channels - 1 );
672
673 while( n < len ) {
674 int k = f->channel_buffer_end - f->channel_buffer_start;
675
676 if( n+k >= len )
677 k = len - n;
678
679 for( int j=0; j < k; ++j ) {
680 float sl = f->channel_buffers[ 0 ][f->channel_buffer_start+j],
681 sr = f->channel_buffers[ c ][f->channel_buffer_start+j];
682
683 *buffer++ = vg_clampf( 0.5f*(sl+sr), -1.0f, 1.0f ) * 32767.0f;
684 //*buffer++ = vg_clampf( sr, -1.0f, 1.0f ) * 32767.0f;
685 }
686
687 n += k;
688 f->channel_buffer_start += k;
689
690 if( n == len )
691 break;
692
693 if( !stb_vorbis_get_frame_float( f, NULL, NULL ))
694 break;
695 }
696
697 return n;
698 }
699
700 static inline float audio_lfo_pull_sample( audio_lfo *lfo )
701 {
702 lfo->time ++;
703
704 if( lfo->time >= lfo->_.period )
705 lfo->time = 0;
706
707 float t = lfo->time;
708 t /= (float)lfo->_.period;
709
710 if( lfo->_.wave_type == k_lfo_polynomial_bipolar ){
711 /*
712 * #
713 * # #
714 * # #
715 * # #
716 * ### # ###
717 * ## #
718 * # #
719 * # #
720 * ##
721 */
722
723 t *= 2.0f;
724 t -= 1.0f;
725
726 return (( 2.0f * lfo->sqrt_polynomial_coefficient * t ) /
727 /* --------------------------------------- */
728 ( 1.0f + lfo->_.polynomial_coefficient * t*t )
729
730 ) * (1.0f-fabsf(t));
731 }
732 else{
733 return 0.0f;
734 }
735 }
736
737 static void audio_channel_get_samples( audio_channel *ch,
738 u32 count, float *buf )
739 {
740 vg_profile_begin( &_vg_prof_audio_decode );
741
742 u32 remaining = count;
743 u32 buffer_pos = 0;
744
745 u32 format = ch->source->flags & AUDIO_FLAG_FORMAT;
746
747 while( remaining ){
748 u32 samples_this_run = VG_MIN(remaining, ch->source_length - ch->cursor);
749 remaining -= samples_this_run;
750
751 float *dst = &buf[ buffer_pos * 2 ];
752
753 if( format == k_audio_format_stereo ){
754 for( int i=0;i<samples_this_run; i++ ){
755 dst[i*2+0] = 0.0f;
756 dst[i*2+1] = 0.0f;
757 }
758 }
759 else if( format == k_audio_format_vorbis ){
760 int read_samples = stb_vorbis_get_samples_float_interleaved_stereo(
761 ch->vorbis_handle,
762 dst,
763 samples_this_run );
764
765 if( read_samples != samples_this_run ){
766 vg_warn( "Invalid samples read (%s)\n", ch->source->path );
767
768 for( int i=0; i<samples_this_run; i++ ){
769 dst[i*2+0] = 0.0f;
770 dst[i*2+1] = 0.0f;
771 }
772 }
773 }
774 else if( format == k_audio_format_bird ){
775 synth_bird_generate_samples( ch->bird_handle, dst, samples_this_run );
776 }
777 else{
778 i16 *src_buffer = ch->source->data,
779 *src = &src_buffer[ch->cursor];
780
781 audio_decode_uncompressed_mono( src, samples_this_run, dst );
782 }
783
784 ch->cursor += samples_this_run;
785 buffer_pos += samples_this_run;
786
787 if( (ch->flags & AUDIO_FLAG_LOOP) && remaining ){
788 if( format == k_audio_format_vorbis )
789 stb_vorbis_seek_start( ch->vorbis_handle );
790 else if( format == k_audio_format_bird )
791 synth_bird_reset( ch->bird_handle );
792
793 ch->cursor = 0;
794 continue;
795 }
796 else
797 break;
798 }
799
800 while( remaining ){
801 buf[ buffer_pos*2 + 0 ] = 0.0f;
802 buf[ buffer_pos*2 + 1 ] = 0.0f;
803 buffer_pos ++;
804
805 remaining --;
806 }
807
808 vg_profile_end( &_vg_prof_audio_decode );
809 }
810
811 static void audio_channel_mix( audio_channel *ch, float *buffer )
812 {
813 float framevol_l = vg_audio.internal_global_volume,
814 framevol_r = vg_audio.internal_global_volume;
815
816 float frame_samplerate = ch->_.sampling_rate;
817
818 if( ch->flags & AUDIO_FLAG_SPACIAL_3D ){
819 v3f delta;
820 v3_sub( ch->_.spacial_falloff, vg_audio.internal_listener_pos, delta );
821
822 float dist = v3_length( delta ),
823 vol = vg_maxf( 0.0f, 1.0f - ch->_.spacial_falloff[3]*dist );
824
825 if( dist <= 0.01f ){
826
827 }
828 else{
829 v3_muls( delta, 1.0f/dist, delta );
830 float pan = v3_dot( vg_audio.internal_listener_ears, delta );
831 vol = powf( vol, 5.0f );
832
833 framevol_l *= (vol * 0.5f) * (1.0f - pan);
834 framevol_r *= (vol * 0.5f) * (1.0f + pan);
835
836 if( !(ch->source->flags & AUDIO_FLAG_NO_DOPPLER) ){
837 const float vs = 323.0f;
838
839 float dv = v3_dot(delta,vg_audio.internal_listener_velocity);
840 float doppler = (vs+dv)/vs;
841 doppler = vg_clampf( doppler, 0.6f, 1.4f );
842
843 if( fabsf(doppler-1.0f) > 0.01f )
844 frame_samplerate *= doppler;
845 }
846 }
847
848 if( !vg_validf( framevol_l ) ) vg_fatal_error( "NaN left channel" );
849 if( !vg_validf( framevol_r ) ) vg_fatal_error( "NaN right channel" );
850 if( !vg_validf( frame_samplerate ) )
851 vg_fatal_error( "NaN sample rate" );
852 }
853
854 u32 buffer_length = AUDIO_MIX_FRAME_SIZE;
855 if( frame_samplerate != 1.0f ){
856 float l = ceilf( (float)(AUDIO_MIX_FRAME_SIZE) * frame_samplerate );
857 buffer_length = l+1;
858 }
859
860 float pcf[ AUDIO_MIX_FRAME_SIZE * 2 * 2 ];
861
862 audio_channel_get_samples( ch, buffer_length, pcf );
863
864 vg_profile_begin( &_vg_prof_audio_mix );
865
866 float volume_movement = ch->volume_movement;
867 float const fvolume_rate = vg_maxf( 1.0f, ch->_.volume_rate );
868 const float inv_volume_rate = 1.0f/fvolume_rate;
869
870 float volume = ch->_.volume;
871 const float volume_start = ch->volume_movement_start;
872 const float volume_target = ch->_.volume_target;
873
874 for( u32 j=0; j<AUDIO_MIX_FRAME_SIZE; j++ ){
875 volume_movement += 1.0f;
876 float movement_t = volume_movement * inv_volume_rate;
877 movement_t = vg_minf( movement_t, 1.0f );
878 volume = vg_lerpf( volume_start, volume_target, movement_t );
879
880 float vol_norm = volume * volume;
881
882 if( ch->_.lfo )
883 vol_norm *= 1.0f + audio_lfo_pull_sample(ch->_.lfo) * ch->_.lfo_amount;
884
885 float vol_l = vol_norm * framevol_l,
886 vol_r = vol_norm * framevol_r,
887 sample_l,
888 sample_r;
889
890 if( frame_samplerate != 1.0f ){
891 /* absolutely garbage resampling, but it will do
892 */
893
894 float sample_index = frame_samplerate * (float)j;
895 float t = vg_fractf( sample_index );
896
897 u32 i0 = floorf( sample_index ),
898 i1 = i0+1;
899
900 sample_l = pcf[ i0*2+0 ]*(1.0f-t) + pcf[ i1*2+0 ]*t;
901 sample_r = pcf[ i0*2+1 ]*(1.0f-t) + pcf[ i1*2+1 ]*t;
902 }
903 else{
904 sample_l = pcf[ j*2+0 ];
905 sample_r = pcf[ j*2+1 ];
906 }
907
908 buffer[ j*2+0 ] += sample_l * vol_l;
909 buffer[ j*2+1 ] += sample_r * vol_r;
910 }
911
912 ch->volume_movement += AUDIO_MIX_FRAME_SIZE;
913 ch->volume_movement = VG_MIN( ch->volume_movement, ch->_.volume_rate );
914 ch->_.volume = volume;
915
916 vg_profile_end( &_vg_prof_audio_mix );
917 }
918
919 VG_STATIC void audio_mixer_callback( void *user, u8 *stream, int byte_count )
920 {
921 /*
922 * Copy data and move edit flags to commit flags
923 * ------------------------------------------------------------- */
924 audio_lock();
925
926 v3_copy( vg_audio.external_listener_pos, vg_audio.internal_listener_pos );
927 v3_copy( vg_audio.external_listener_ears, vg_audio.internal_listener_ears );
928 v3_copy( vg_audio.external_lister_velocity,
929 vg_audio.internal_listener_velocity );
930 vg_audio.internal_global_volume = vg_audio.external_global_volume;
931
932 for( int i=0; i<AUDIO_CHANNELS; i++ ){
933 audio_channel *ch = &vg_audio.channels[i];
934
935 if( !ch->allocated )
936 continue;
937
938 if( ch->activity == k_channel_activity_alive ){
939 if( (ch->cursor >= ch->source_length) &&
940 !(ch->flags & AUDIO_FLAG_LOOP) )
941 {
942 ch->activity = k_channel_activity_end;
943 }
944 }
945
946 /* process relinquishments */
947 if( (ch->activity != k_channel_activity_reset) && ch->_.relinquished ){
948 if( (ch->activity == k_channel_activity_end)
949 || (ch->_.volume == 0.0f)
950 || (ch->activity == k_channel_activity_error) )
951 {
952 ch->_.relinquished = 0;
953 ch->allocated = 0;
954 ch->activity = k_channel_activity_reset;
955 continue;
956 }
957 }
958
959 /* process new channels */
960 if( ch->activity == k_channel_activity_reset ){
961 ch->_ = ch->editable_state;
962 ch->cursor = 0;
963 ch->source_length = 0;
964 ch->activity = k_channel_activity_wake;
965 }
966
967 if( ch->editble_state_write_mask & AUDIO_EDIT_OWNERSHIP )
968 ch->_.relinquished = ch->editable_state.relinquished;
969 else
970 ch->editable_state.relinquished = ch->_.relinquished;
971
972
973 if( ch->editble_state_write_mask & AUDIO_EDIT_VOLUME ){
974 ch->_.volume = ch->editable_state.volume;
975 ch->_.volume_target = ch->editable_state.volume;
976 }
977 else{
978 ch->editable_state.volume = ch->_.volume;
979 }
980
981
982 if( ch->editble_state_write_mask & AUDIO_EDIT_VOLUME_SLOPE ){
983 ch->volume_movement_start = ch->_.volume;
984 ch->volume_movement = 0;
985
986 ch->_.volume_target = ch->editable_state.volume_target;
987 ch->_.volume_rate = ch->editable_state.volume_rate;
988 }
989 else{
990 ch->editable_state.volume_target = ch->_.volume_target;
991 ch->editable_state.volume_rate = ch->_.volume_rate;
992 }
993
994
995 if( ch->editble_state_write_mask & AUDIO_EDIT_SAMPLING_RATE )
996 ch->_.sampling_rate = ch->editable_state.sampling_rate;
997 else
998 ch->editable_state.sampling_rate = ch->_.sampling_rate;
999
1000
1001 if( ch->editble_state_write_mask & AUDIO_EDIT_LFO_ATTACHMENT ){
1002 ch->_.lfo = ch->editable_state.lfo;
1003 ch->_.lfo_amount = ch->editable_state.lfo_amount;
1004 }
1005 else{
1006 ch->editable_state.lfo = ch->_.lfo;
1007 ch->editable_state.lfo_amount = ch->_.lfo_amount;
1008 }
1009
1010
1011 if( ch->editble_state_write_mask & AUDIO_EDIT_SPACIAL )
1012 v4_copy( ch->editable_state.spacial_falloff,ch->_.spacial_falloff );
1013 else
1014 v4_copy( ch->_.spacial_falloff,ch->editable_state.spacial_falloff );
1015
1016
1017 /* currently readonly, i guess */
1018 ch->editable_state.pan_target = ch->_.pan_target;
1019 ch->editable_state.pan = ch->_.pan;
1020 ch->editble_state_write_mask = 0x00;
1021 }
1022
1023 for( int i=0; i<AUDIO_LFOS; i++ ){
1024 audio_lfo *lfo = &vg_audio.oscillators[ i ];
1025
1026 if( lfo->editble_state_write_mask & AUDIO_EDIT_LFO_WAVE ){
1027 lfo->_.wave_type = lfo->editable_state.wave_type;
1028
1029 if( lfo->_.wave_type == k_lfo_polynomial_bipolar ){
1030 lfo->_.polynomial_coefficient =
1031 lfo->editable_state.polynomial_coefficient;
1032 lfo->sqrt_polynomial_coefficient =
1033 sqrtf(lfo->_.polynomial_coefficient);
1034 }
1035 }
1036
1037 if( lfo->editble_state_write_mask & AUDIO_EDIT_LFO_PERIOD ){
1038 if( lfo->_.period ){
1039 float t = lfo->time;
1040 t/= (float)lfo->_.period;
1041
1042 lfo->_.period = lfo->editable_state.period;
1043 lfo->time = lfo->_.period * t;
1044 }
1045 else{
1046 lfo->time = 0;
1047 lfo->_.period = lfo->editable_state.period;
1048 }
1049 }
1050
1051 lfo->editble_state_write_mask = 0x00;
1052 }
1053
1054 dsp_update_tunings();
1055 audio_unlock();
1056
1057 /*
1058 * Process spawns
1059 * ------------------------------------------------------------- */
1060 for( int i=0; i<AUDIO_CHANNELS; i++ ){
1061 audio_channel *ch = &vg_audio.channels[i];
1062
1063 if( ch->activity == k_channel_activity_wake ){
1064 if( audio_channel_load_source( ch ) )
1065 ch->activity = k_channel_activity_alive;
1066 else
1067 ch->activity = k_channel_activity_error;
1068 }
1069 }
1070
1071 /*
1072 * Mix everything
1073 * -------------------------------------------------------- */
1074 int frame_count = byte_count/(2*sizeof(float));
1075
1076 /* Clear buffer */
1077 float *pOut32F = (float *)stream;
1078 for( int i=0; i<frame_count*2; i ++ )
1079 pOut32F[i] = 0.0f;
1080
1081 for( int i=0; i<AUDIO_LFOS; i++ ){
1082 audio_lfo *lfo = &vg_audio.oscillators[i];
1083 lfo->time_startframe = lfo->time;
1084 }
1085
1086 for( int i=0; i<AUDIO_CHANNELS; i ++ ){
1087 audio_channel *ch = &vg_audio.channels[i];
1088
1089 if( ch->activity == k_channel_activity_alive ){
1090 if( ch->_.lfo )
1091 ch->_.lfo->time = ch->_.lfo->time_startframe;
1092
1093 u32 remaining = frame_count,
1094 subpos = 0;
1095
1096 while( remaining ){
1097 audio_channel_mix( ch, pOut32F+subpos );
1098 remaining -= AUDIO_MIX_FRAME_SIZE;
1099 subpos += AUDIO_MIX_FRAME_SIZE*2;
1100 }
1101 }
1102 }
1103
1104 vg_profile_begin( &_vg_prof_dsp );
1105
1106 for( int i=0; i<frame_count; i++ )
1107 vg_dsp_process( pOut32F + i*2, pOut32F + i*2 );
1108
1109 vg_profile_end( &_vg_prof_dsp );
1110
1111 audio_lock();
1112
1113 for( int i=0; i<AUDIO_CHANNELS; i ++ ){
1114 audio_channel *ch = &vg_audio.channels[i];
1115 ch->readable_activity = ch->activity;
1116 }
1117
1118 /* Profiling information
1119 * ----------------------------------------------- */
1120 vg_profile_increment( &_vg_prof_audio_decode );
1121 vg_profile_increment( &_vg_prof_audio_mix );
1122 vg_profile_increment( &_vg_prof_dsp );
1123
1124 vg_prof_audio_mix = _vg_prof_audio_mix;
1125 vg_prof_audio_decode = _vg_prof_audio_decode;
1126 vg_prof_audio_dsp = _vg_prof_dsp;
1127
1128 vg_audio.samples_last = frame_count;
1129
1130 if( vg_audio.debug_dsp ){
1131 vg_dsp_update_texture();
1132 }
1133
1134 audio_unlock();
1135 }
1136
1137 VG_STATIC void audio_clip_load( audio_clip *clip, void *lin_alloc )
1138 {
1139 if( lin_alloc == NULL )
1140 lin_alloc = vg_audio.audio_pool;
1141
1142 /* load in directly */
1143 u32 format = clip->flags & AUDIO_FLAG_FORMAT;
1144
1145 /* TODO: This contains audio_lock() and unlock, but i don't know why
1146 * can probably remove them. Low priority to check this */
1147
1148 /* TODO: packed files for vorbis etc, should take from data if its not not
1149 * NULL when we get the clip
1150 */
1151
1152 if( format == k_audio_format_vorbis ){
1153 if( !clip->path ){
1154 vg_fatal_error( "No path specified, embeded vorbis unsupported" );
1155 }
1156
1157 audio_lock();
1158 clip->data = vg_file_read( lin_alloc, clip->path, &clip->size );
1159 audio_unlock();
1160
1161 if( !clip->data )
1162 vg_fatal_error( "Audio failed to load" );
1163
1164 float mb = (float)(clip->size) / (1024.0f*1024.0f);
1165 vg_info( "Loaded audio clip '%s' (%.1fmb)\n", clip->path, mb );
1166 }
1167 else if( format == k_audio_format_stereo ){
1168 vg_fatal_error( "Unsupported format (Stereo uncompressed)" );
1169 }
1170 else if( format == k_audio_format_bird ){
1171 if( !clip->data ){
1172 vg_fatal_error( "No data, external birdsynth unsupported" );
1173 }
1174
1175 u32 total_size = clip->size + sizeof(struct synth_bird);
1176 total_size -= sizeof(struct synth_bird_settings);
1177 total_size = vg_align8( total_size );
1178
1179 if( total_size > AUDIO_DECODE_SIZE )
1180 vg_fatal_error( "Bird coding too long\n" );
1181
1182 struct synth_bird *bird = vg_linear_alloc( lin_alloc, total_size );
1183 memcpy( &bird->settings, clip->data, clip->size );
1184
1185 clip->data = bird;
1186 clip->size = total_size;
1187
1188 vg_info( "Loaded bird synthesis pattern (%u bytes)\n", total_size );
1189 }
1190 else{
1191 if( !clip->path ){
1192 vg_fatal_error( "No path specified, embeded mono unsupported" );
1193 }
1194
1195 vg_linear_clear( vg_mem.scratch );
1196 u32 fsize;
1197
1198 stb_vorbis_alloc alloc = {
1199 .alloc_buffer = vg_linear_alloc( vg_mem.scratch, AUDIO_DECODE_SIZE ),
1200 .alloc_buffer_length_in_bytes = AUDIO_DECODE_SIZE
1201 };
1202
1203 void *filedata = vg_file_read( vg_mem.scratch, clip->path, &fsize );
1204
1205 int err;
1206 stb_vorbis *decoder = stb_vorbis_open_memory(
1207 filedata, fsize, &err, &alloc );
1208
1209 if( !decoder ){
1210 vg_error( "stb_vorbis_open_memory failed on '%s' (%d)\n",
1211 clip->path, err );
1212 vg_fatal_error( "Vorbis decode error" );
1213 }
1214
1215 /* only mono is supported in uncompressed */
1216 u32 length_samples = stb_vorbis_stream_length_in_samples( decoder ),
1217 data_size = length_samples * sizeof(i16);
1218
1219 audio_lock();
1220 clip->data = vg_linear_alloc( lin_alloc, vg_align8(data_size) );
1221 clip->size = length_samples;
1222 audio_unlock();
1223
1224 int read_samples = stb_vorbis_get_samples_i16_downmixed(
1225 decoder, clip->data, length_samples );
1226
1227 if( read_samples != length_samples )
1228 vg_fatal_error( "Decode error" );
1229
1230 float mb = (float)(data_size) / (1024.0f*1024.0f);
1231 vg_info( "Loaded audio clip '%s' (%.1fmb) %u samples\n", clip->path, mb,
1232 length_samples );
1233 }
1234 }
1235
1236 VG_STATIC void audio_clip_loadn( audio_clip *arr, int count, void *lin_alloc )
1237 {
1238 for( int i=0; i<count; i++ )
1239 audio_clip_load( &arr[i], lin_alloc );
1240 }
1241
1242 VG_STATIC void audio_require_clip_loaded( audio_clip *clip )
1243 {
1244 if( clip->data && clip->size )
1245 return;
1246
1247 audio_unlock();
1248 vg_fatal_error( "Must load audio clip before playing! \n" );
1249 }
1250
1251 /*
1252 * Debugging
1253 */
1254
1255 VG_STATIC void audio_debug_ui( m4x4f mtx_pv )
1256 {
1257 if( !vg_audio.debug_ui )
1258 return;
1259
1260 audio_lock();
1261
1262 glBindTexture( GL_TEXTURE_2D, vg_dsp.view_texture );
1263 glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, 256, 256,
1264 GL_RGBA, GL_UNSIGNED_BYTE,
1265 vg_dsp.view_texture_buffer );
1266
1267 /*
1268 * Profiler
1269 * -----------------------------------------------------------------------
1270 */
1271
1272 float budget = ((double)vg_audio.samples_last / 44100.0) * 1000.0;
1273 #if 0
1274 vg_profile_drawn( (struct vg_profile *[]){ &vg_prof_audio_decode,
1275 &vg_prof_audio_mix,
1276 &vg_prof_audio_dsp}, 3,
1277 budget, (ui_rect){ 4, VG_PROFILE_SAMPLE_COUNT*2 + 8,
1278 512, 0 }, 3 );
1279 #endif
1280
1281
1282 char perf[128];
1283
1284 /* Draw UI */
1285 ui_rect window = {
1286 0,
1287 0,
1288 800,
1289 AUDIO_CHANNELS * 18
1290 };
1291
1292 if( vg_audio.debug_dsp ){
1293 ui_rect view_thing = { 4, vg.window_y-512-4, 512, 512 };
1294 ui_image( view_thing, vg_dsp.view_texture );
1295 }
1296
1297 ui_rect overlap_buffer[ AUDIO_CHANNELS ];
1298 u32 overlap_length = 0;
1299
1300 /* Draw audio stack */
1301 for( int i=0; i<AUDIO_CHANNELS; i ++ ){
1302 audio_channel *ch = &vg_audio.channels[i];
1303
1304 ui_rect row;
1305 ui_split( window, k_ui_axis_h, 18, 1, row, window );
1306
1307 if( !ch->allocated ){
1308 ui_fill( row, 0x50333333 );
1309 continue;
1310 }
1311
1312 const char *formats[] =
1313 {
1314 " mono ",
1315 " stereo ",
1316 " vorbis ",
1317 " none0 ",
1318 " none1 ",
1319 " none2 ",
1320 " none3 ",
1321 " none4 ",
1322 "synth:bird",
1323 " none5 ",
1324 " none6 ",
1325 " none7 ",
1326 " none8 ",
1327 " none9 ",
1328 " none10 ",
1329 " none11 ",
1330 };
1331
1332 const char *activties[] =
1333 {
1334 "reset",
1335 "wake ",
1336 "alive",
1337 "end ",
1338 "error"
1339 };
1340
1341 u32 format_index = (ch->source->flags & AUDIO_FLAG_FORMAT)>>9;
1342
1343 snprintf( perf, 127, "%02d[%#04x.%#06x]%c%c%cD %s [%s] %4.2fv'%s'",
1344 i,
1345 ch->world_id, ch->group,
1346 (ch->editable_state.relinquished)? 'r': '_',
1347 0? 'r': '_',
1348 0? '3': '2',
1349 formats[format_index],
1350 activties[ch->readable_activity],
1351 ch->editable_state.volume,
1352 ch->name );
1353
1354 ui_fill( row, 0xa0000000 | ch->colour );
1355 ui_text( row, perf, 1, k_ui_align_middle_left, 0 );
1356
1357 if( AUDIO_FLAG_SPACIAL_3D ){
1358 v4f wpos;
1359 v3_copy( ch->editable_state.spacial_falloff, wpos );
1360
1361 wpos[3] = 1.0f;
1362 m4x4_mulv( mtx_pv, wpos, wpos );
1363
1364 if( wpos[3] > 0.0f ){
1365 v2_muls( wpos, (1.0f/wpos[3]) * 0.5f, wpos );
1366 v2_add( wpos, (v2f){ 0.5f, 0.5f }, wpos );
1367
1368 ui_rect wr;
1369 wr[0] = vg_clampf(wpos[0] * vg.window_x, -32000.0f,32000.0f);
1370 wr[1] = vg_clampf((1.0f-wpos[1]) * vg.window_y,-32000.0f,32000.0f);
1371 wr[2] = 1000;
1372 wr[3] = 17;
1373
1374 for( int j=0; j<12; j++ ){
1375 int collide = 0;
1376 for( int k=0; k<overlap_length; k++ ){
1377 ui_px *wk = overlap_buffer[k];
1378 if( ((wr[0] <= wk[0]+wk[2]) && (wr[0]+wr[2] >= wk[0])) &&
1379 ((wr[1] <= wk[1]+wk[3]) && (wr[1]+wr[3] >= wk[1])) )
1380 {
1381 collide = 1;
1382 break;
1383 }
1384 }
1385
1386 if( !collide )
1387 break;
1388 else
1389 wr[1] += 18;
1390 }
1391
1392 ui_text( wr, perf, 1, k_ui_align_middle_left, 0 );
1393 rect_copy( wr, overlap_buffer[ overlap_length ++ ] );
1394 }
1395 }
1396 }
1397
1398 audio_unlock();
1399 }
1400
1401 #endif /* VG_AUDIO_H */