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