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