Fixes for clang
[vg.git] / src / vg / vg_audio.h
1 /* Copyright (C) 2021-2022 Harry Godden (hgn) - All Rights Reserved */
2
3 #ifndef VG_AUDIO_H
4 #define VG_AUDIO_H
5
6 #define MA_NO_GENERATION
7 #define MA_NO_DECODING
8 #define MA_NO_ENCODING
9 #define MA_NO_WAV
10 #define MA_NO_FLAC
11 #define MA_NO_MP3
12 #define MA_NO_ENGINE
13 #define MA_NO_NODE_GRAPH
14 #define MA_NO_RESOURCE_MANAGER
15
16 #include "dr_soft/miniaudio.h"
17
18
19 #include "vg/vg.h"
20 #include "vg/vg_stdint.h"
21 #include "vg/vg_platform.h"
22 #include "vg/vg_io.h"
23 #include "vg/vg_m.h"
24 #include "vg/vg_ui.h"
25 #include "vg/vg_console.h"
26 #include "vg/vg_store.h"
27
28 #include <time.h>
29
30 #ifdef __GNUC__
31 #ifndef __clang__
32 #pragma GCC push_options
33 #pragma GCC optimize ("O3")
34 #endif
35 #endif
36
37 #pragma GCC diagnostic push
38 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
39
40 #define STB_VORBIS_MAX_CHANNELS 2
41 #include "stb/stb_vorbis.h"
42
43 #pragma GCC diagnostic pop
44
45 #ifdef __GNUC__
46 #ifndef __clang__
47 #pragma GCC pop_options
48 #endif
49 #endif
50
51 #define SFX_MAX_SYSTEMS 32
52 #define AUDIO_FLAG_LOOP 0x1
53 #define AUDIO_FLAG_ONESHOT 0x2
54 #define AUDIO_FLAG_SPACIAL_3D 0x4
55 #define AUDIO_FLAG_AUTO_START 0x8
56 #define AUDIO_FLAG_KILL 0x10
57
58 #define FADEOUT_LENGTH 1100
59 #define FADEOUT_DIVISOR (1.0f/(float)FADEOUT_LENGTH)
60
61 #define AUDIO_DECODE_SIZE (1024*256) /* 256 kb decoding buffers */
62
63 enum audio_source_mode
64 {
65 k_audio_source_mono,
66 k_audio_source_compressed,
67 };
68
69 typedef struct audio_clip audio_clip;
70 struct audio_clip
71 {
72 const char *path;
73 enum audio_source_mode source_mode;
74
75 void *data;
76 u32 size;
77 };
78
79 typedef struct audio_mix_info audio_mix_info;
80 struct audio_mix_info
81 {
82 audio_clip *source;
83 v3f world_position;
84
85 float vol, pan;
86 u32 flags;
87 };
88
89 typedef struct audio_player audio_player;
90 struct audio_player
91 {
92 aatree_ptr active_entity; /* non-nil if currently playing */
93 audio_mix_info info;
94 int enqued, init;
95
96 /* Diagnostic */
97 const char *name;
98 };
99
100 typedef struct audio_entity audio_entity;
101 struct audio_entity
102 {
103 audio_player *player;
104 audio_mix_info info;
105
106 u32 length, cur;
107
108 /* Effects */
109 u32 fadeout, fadeout_current;
110 const char *name;
111 };
112
113 /*
114 * TODO list sunday
115 *
116 * play again: if already playing, leave in queue while it fadeouts
117 * oneshot: create a ghost entity
118 *
119 */
120
121 static struct vg_audio_system
122 {
123 ma_device miniaudio_device;
124 ma_device_config miniaudio_dconfig;
125
126 void *audio_pool,
127 *decode_buffer;
128 u32 samples_last;
129
130 /* synchro */
131 int sync_locked;
132
133 vg_mutex mux_checker,
134 mux_sync;
135
136 /* Audio engine, thread 1 */
137 struct active_audio_player
138 {
139 int active;
140 union
141 {
142 audio_entity ent;
143 aatree_pool_node pool_node;
144 };
145
146 stb_vorbis *vorbis_handle;
147 stb_vorbis_alloc vorbis_alloc;
148 }
149 active_players[ SFX_MAX_SYSTEMS ];
150
151 aatree active_pool_info; /* note: just using the pool */
152 aatree_ptr active_pool_head;
153
154 /* System queue, and access from thread 0 */
155 audio_entity entity_queue[SFX_MAX_SYSTEMS];
156 int queue_len;
157 int debug_ui, debug_ui_3d;
158
159 v3f listener_pos,
160 listener_ears;
161 }
162 vg_audio;
163
164 static struct vg_profile
165 _vg_prof_audio_decode = {.mode = k_profile_mode_accum,
166 .name = "[T2] audio_decode()"},
167 _vg_prof_audio_mix = {.mode = k_profile_mode_accum,
168 .name = "[T2] audio_mix()"},
169 vg_prof_audio_decode,
170 vg_prof_audio_mix;
171
172 /*
173 * These functions are called from the main thread and used to prevent bad
174 * access. TODO: They should be no-ops in release builds.
175 */
176 VG_STATIC int audio_lock_checker_load(void)
177 {
178 int value;
179 vg_mutex_lock( &vg_audio.mux_checker );
180 value = vg_audio.sync_locked;
181 vg_mutex_unlock( &vg_audio.mux_checker );
182 return value;
183 }
184
185 VG_STATIC void audio_lock_checker_store( int value )
186 {
187 vg_mutex_lock( &vg_audio.mux_checker );
188 vg_audio.sync_locked = value;
189 vg_mutex_unlock( &vg_audio.mux_checker );
190 }
191
192 VG_STATIC void audio_require_lock(void)
193 {
194 if( audio_lock_checker_load() )
195 return;
196
197 vg_error( "Modifying sound effects systems requires locking\n" );
198 abort();
199 }
200
201 VG_STATIC void audio_lock(void)
202 {
203 vg_mutex_lock( &vg_audio.mux_sync );
204 audio_lock_checker_store(1);
205 }
206
207 VG_STATIC void audio_unlock(void)
208 {
209 audio_lock_checker_store(0);
210 vg_mutex_unlock( &vg_audio.mux_sync );
211 }
212
213
214 VG_STATIC void audio_mixer_callback( ma_device *pDevice, void *pOutBuf,
215 const void *pInput, ma_uint32 frameCount );
216
217 VG_STATIC void vg_audio_init(void)
218 {
219 vg_mutex_init( &vg_audio.mux_checker );
220 vg_mutex_init( &vg_audio.mux_sync );
221
222 /* TODO: Move here? */
223 vg_convar_push( (struct vg_convar){
224 .name = "debug_audio",
225 .data = &vg_audio.debug_ui,
226 .data_type = k_convar_dtype_i32,
227 .opt_i32 = { .min=0, .max=1, .clamp=1 },
228 .persistent = 1
229 });
230
231 /* allocate memory */
232
233 /* 32mb fixed */
234 vg_audio.audio_pool =
235 vg_create_linear_allocator( vg_mem.rtmemory, 1024*1024*32 );
236
237 /* fixed */
238 u32 decode_size = AUDIO_DECODE_SIZE * SFX_MAX_SYSTEMS;
239 vg_audio.decode_buffer = vg_linear_alloc( vg_mem.rtmemory, decode_size );
240
241 /* setup pool */
242 vg_audio.active_pool_info.base = vg_audio.active_players;
243 vg_audio.active_pool_info.offset = offsetof(struct active_audio_player,
244 pool_node );
245 vg_audio.active_pool_info.stride = sizeof(struct active_audio_player);
246 vg_audio.active_pool_info.p_cmp = NULL;
247 aatree_init_pool( &vg_audio.active_pool_info, SFX_MAX_SYSTEMS );
248
249 ma_device_config *dconf = &vg_audio.miniaudio_dconfig;
250 ma_device *device = &vg_audio.miniaudio_device;
251
252 *dconf = ma_device_config_init( ma_device_type_playback );
253 dconf->playback.format = ma_format_f32;
254 dconf->playback.channels = 2;
255 dconf->sampleRate = 44100;
256 dconf->dataCallback = audio_mixer_callback;
257 dconf->periodSizeInFrames = 441;
258
259 dconf->pUserData = NULL;
260
261 vg_info( "Starting audio engine\n" );
262
263 if( ma_device_init( NULL, dconf, device) != MA_SUCCESS )
264 {
265 vg_fatal_exit_loop( "(audio) ma_device failed to initialize" );
266 }
267 else
268 {
269 if( ma_device_start( device ) != MA_SUCCESS )
270 {
271 ma_device_uninit( device );
272 vg_fatal_exit_loop( "(audio) ma_device failed to start" );
273 }
274 }
275
276 vg_success( "Ready\n" );
277 }
278
279 VG_STATIC void vg_audio_free(void * nothing)
280 {
281 ma_device *device = &vg_audio.miniaudio_device;
282 ma_device_uninit( device );
283
284 #if 0
285 vg_free( vg_audio.mem );
286 vg_audio.mem = NULL;
287 #endif
288 }
289
290 /*
291 * thread 1
292 */
293
294 static aatree_ptr audio_alloc_entity_internal(void)
295 {
296 aatree_ptr playerid = aatree_pool_alloc( &vg_audio.active_pool_info,
297 &vg_audio.active_pool_head );
298
299 if( playerid == AATREE_PTR_NIL )
300 return AATREE_PTR_NIL;
301
302 struct active_audio_player *aap = &vg_audio.active_players[ playerid ];
303 aap->active = 1;
304
305 return playerid;
306 }
307
308 VG_STATIC void audio_entity_free_internal( aatree_ptr id )
309 {
310 struct active_audio_player *aap = &vg_audio.active_players[ id ];
311 aap->active = 0;
312
313 /* Notify player that we've finished */
314 if( aap->ent.player )
315 aap->ent.player->active_entity = AATREE_PTR_NIL;
316
317 /* delete */
318 aatree_pool_free( &vg_audio.active_pool_info, id,
319 &vg_audio.active_pool_head );
320 }
321
322 VG_STATIC void *audio_entity_vorbis_ptr( aatree_ptr entid )
323 {
324 u8 *buf = (u8*)vg_audio.decode_buffer,
325 *loc = &buf[AUDIO_DECODE_SIZE*entid];
326
327 return (void *)loc;
328 }
329
330 VG_STATIC void audio_entity_start( audio_entity *src )
331 {
332 aatree_ptr entid = audio_alloc_entity_internal();
333 if( entid == AATREE_PTR_NIL )
334 return;
335
336 audio_entity *ent = &vg_audio.active_players[ entid ].ent;
337
338 ent->info = src->info;
339 ent->name = src->info.source->path;
340 ent->cur = 0;
341 ent->player = src->player;
342
343 ent->fadeout = 0;
344 ent->fadeout_current = 0;
345
346 /* Notify main player we are dequeud and playing */
347 if( src->player )
348 {
349 src->player->enqued = 0;
350 src->player->active_entity = entid;
351 }
352
353 if( src->info.source->source_mode == k_audio_source_compressed )
354 {
355 /* Setup vorbis decoder */
356 struct active_audio_player *aap = &vg_audio.active_players[ entid ];
357
358 stb_vorbis_alloc alloc = {
359 .alloc_buffer = (char *)audio_entity_vorbis_ptr( entid ),
360 .alloc_buffer_length_in_bytes = AUDIO_DECODE_SIZE
361 };
362
363 int err;
364 stb_vorbis *decoder = stb_vorbis_open_memory(
365 src->info.source->data,
366 src->info.source->size, &err, &alloc );
367
368 if( !decoder )
369 {
370 vg_error( "stb_vorbis_open_memory failed on '%s' (%d)\n",
371 src->info.source->path, err );
372
373 audio_entity_free_internal( entid );
374 return;
375 }
376 else
377 {
378 ent->length = stb_vorbis_stream_length_in_samples( decoder );
379 }
380
381 aap->vorbis_handle = decoder;
382 }
383 else
384 {
385 ent->length = src->info.source->size;
386 }
387 }
388
389 /*
390 * Read everything from the queue
391 */
392 VG_STATIC void audio_system_enque(void)
393 {
394 /* Process incoming sound queue */
395 audio_lock();
396
397 int wr = 0;
398 for( int i=0; i<vg_audio.queue_len; i++ )
399 {
400 audio_entity *src = &vg_audio.entity_queue[ i ];
401
402 if( src->player )
403 {
404 /* Start new */
405 if( src->player->active_entity == AATREE_PTR_NIL )
406 {
407 audio_entity_start( src );
408 }
409 else
410 {
411 /* Otherwise try start fadeout but dont remove from queue */
412
413 aatree_ptr entid = src->player->active_entity;
414 audio_entity *ent = &vg_audio.active_players[ entid ].ent;
415 if( !ent->fadeout )
416 {
417 ent->fadeout = FADEOUT_LENGTH;
418 ent->fadeout_current = FADEOUT_LENGTH;
419 }
420
421 vg_audio.entity_queue[ wr ++ ] = *src;
422 }
423 }
424 else
425 {
426 audio_entity_start( src );
427 }
428 }
429
430 vg_audio.queue_len = wr;
431
432 /* Localize others memory */
433 for( int i=0; i<SFX_MAX_SYSTEMS; i ++ )
434 {
435 struct active_audio_player *aap = &vg_audio.active_players[i];
436 if( !aap->active )
437 continue;
438
439 if( aap->ent.player )
440 {
441 /* Only copy information in whilst not requeing */
442 if( aap->ent.player->enqued == 0 )
443 {
444 aap->ent.info = aap->ent.player->info;
445
446 if( (aap->ent.info.flags & AUDIO_FLAG_KILL) && !aap->ent.fadeout )
447 {
448 aap->ent.fadeout = FADEOUT_LENGTH;
449 aap->ent.fadeout_current = FADEOUT_LENGTH;
450 }
451 }
452 }
453 }
454
455 audio_unlock();
456 }
457
458 /*
459 * Redistribute sound systems
460 */
461 VG_STATIC void audio_system_cleanup(void)
462 {
463 audio_lock();
464
465 for( int i=0; i<SFX_MAX_SYSTEMS; i ++ )
466 {
467 struct active_audio_player *aap = &vg_audio.active_players[i];
468 if( aap->active )
469 {
470 audio_entity *src = &aap->ent;
471 if( src->cur < src->length || (src->info.flags & AUDIO_FLAG_LOOP ))
472 {
473 /* Good to keep */
474 }
475 else
476 {
477 audio_entity_free_internal( i );
478 }
479 }
480 }
481
482 audio_unlock();
483 }
484
485 /*
486 * Get effective volume and pan from this entity
487 */
488 VG_STATIC void audio_entity_spacialize( audio_entity *ent, float *vol, float *pan )
489 {
490 if( ent->info.vol < 0.01f )
491 {
492 *vol = ent->info.vol;
493 *pan = 0.0f;
494 return;
495 }
496
497 v3f delta;
498 v3_sub( ent->info.world_position, vg_audio.listener_pos, delta );
499
500 float dist2 = v3_length2( delta );
501
502 if( dist2 < 0.0001f )
503 {
504 *pan = 0.0f;
505 *vol = 1.0f;
506 }
507 else
508 {
509 float dist = sqrtf( dist2 ),
510 attn = (dist / ent->info.vol) +1.0f;
511
512 v3_muls( delta, 1.0f/dist, delta );
513 *pan = v3_dot( vg_audio.listener_ears, delta );
514 *vol = 1.0f/(attn*attn);
515 }
516 }
517
518 VG_STATIC void audio_decode_uncompressed_mono( i16 *src, u32 count, float *dst )
519 {
520 for( u32 i=0; i<count; i++ )
521 {
522 dst[ i*2 + 0 ] = (float)src[i] * (1.0f/32767.0f);
523 dst[ i*2 + 1 ] = (float)src[i] * (1.0f/32767.0f);
524 }
525 }
526
527 /*
528 * adapted from stb_vorbis.h, since the original does not handle mono->stereo
529 */
530 VG_STATIC int
531 stb_vorbis_get_samples_float_interleaved_stereo( stb_vorbis *f, float *buffer,
532 int len )
533 {
534 int n = 0,
535 c = VG_MIN( 1, f->channels - 1 );
536
537 while( n < len )
538 {
539 int k = f->channel_buffer_end - f->channel_buffer_start;
540
541 if( n+k >= len )
542 k = len - n;
543
544 for( int j=0; j < k; ++j )
545 {
546 *buffer++ = f->channel_buffers[ 0 ][f->channel_buffer_start+j];
547 *buffer++ = f->channel_buffers[ c ][f->channel_buffer_start+j];
548 }
549
550 n += k;
551 f->channel_buffer_start += k;
552
553 if( n == len )
554 break;
555
556 if( !stb_vorbis_get_frame_float( f, NULL, NULL ))
557 break;
558 }
559
560 return n;
561 }
562
563 /*
564 * ........ more wrecked code sorry!
565 */
566 VG_STATIC int
567 stb_vorbis_get_samples_i16_interleaved_mono( stb_vorbis *f, i16 *buffer,
568 int len )
569 {
570 int n = 0,
571 c = VG_MIN( 1, f->channels - 1 );
572
573 while( n < len )
574 {
575 int k = f->channel_buffer_end - f->channel_buffer_start;
576
577 if( n+k >= len )
578 k = len - n;
579
580 for( int j=0; j < k; ++j )
581 {
582 float sl = f->channel_buffers[ 0 ][f->channel_buffer_start+j],
583 sr = f->channel_buffers[ c ][f->channel_buffer_start+j];
584
585 *buffer++ = vg_clampf( 0.5f*(sl+sr), -1.0f, 1.0f ) * 32767.0f;
586 //*buffer++ = vg_clampf( sr, -1.0f, 1.0f ) * 32767.0f;
587 }
588
589 n += k;
590 f->channel_buffer_start += k;
591
592 if( n == len )
593 break;
594
595 if( !stb_vorbis_get_frame_float( f, NULL, NULL ))
596 break;
597 }
598
599 return n;
600 }
601
602 VG_STATIC void audio_entity_get_samples( aatree_ptr id, u32 count, float *buf )
603 {
604 vg_profile_begin( &_vg_prof_audio_decode );
605
606 struct active_audio_player *aap = &vg_audio.active_players[id];
607 audio_entity *ent = &aap->ent;
608
609 u32 remaining = count;
610 u32 cursor = ent->cur;
611 u32 buffer_pos = 0;
612
613 while( remaining )
614 {
615 u32 samples_this_run = VG_MIN( remaining, ent->length - cursor );
616 remaining -= samples_this_run;
617
618 float *dst = &buf[ buffer_pos * 2 ];
619
620 int source_mode = ent->info.source->source_mode;
621
622 if( source_mode == k_audio_source_mono )
623 {
624 i16 *src = &((i16 *)ent->info.source->data)[ cursor ];
625 audio_decode_uncompressed_mono( src, samples_this_run, dst );
626 }
627 else if( source_mode == k_audio_source_compressed )
628 {
629 int read_samples = stb_vorbis_get_samples_float_interleaved_stereo(
630 aap->vorbis_handle,
631 dst,
632 samples_this_run );
633
634 if( read_samples != samples_this_run )
635 {
636 vg_warn( "Invalid samples read (%s)\n", ent->info.source->path );
637 }
638 }
639
640 cursor += samples_this_run;
641 buffer_pos += samples_this_run;
642
643 if( (ent->info.flags & AUDIO_FLAG_LOOP) && remaining )
644 {
645 if( source_mode == k_audio_source_compressed )
646 {
647 stb_vorbis_seek_start( aap->vorbis_handle );
648 }
649
650 cursor = 0;
651 continue;
652 }
653 else
654 break;
655 }
656
657 while( remaining )
658 {
659 buf[ buffer_pos*2 + 0 ] = 0.0f;
660 buf[ buffer_pos*2 + 1 ] = 0.0f;
661 buffer_pos ++;
662
663 remaining --;
664 }
665
666 ent->cur = cursor;
667 vg_profile_end( &_vg_prof_audio_decode );
668 }
669
670 VG_STATIC void audio_entity_mix( aatree_ptr id, float *buffer,
671 u32 frame_count )
672 {
673 audio_entity *ent = &vg_audio.active_players[id].ent;
674
675 u32 cursor = ent->cur, buffer_pos = 0;
676 float *pcf = alloca( frame_count * 2 * sizeof(float) );
677
678 u32 frames_write = frame_count;
679 float fadeout_divisor = 1.0f / (float)ent->fadeout;
680
681 float vol = ent->info.vol,
682 pan = ent->info.pan;
683
684 audio_entity_get_samples( id, frame_count, pcf );
685
686 vg_profile_begin( &_vg_prof_audio_mix );
687
688 if( ent->info.flags & AUDIO_FLAG_SPACIAL_3D )
689 audio_entity_spacialize( ent, &vol, &pan );
690
691 for( u32 j=0; j<frame_count; j++ )
692 {
693 float frame_vol = vol;
694
695 if( ent->fadeout )
696 {
697 /* Force this system to be removed now */
698 if( ent->fadeout_current == 0 )
699 {
700 ent->info.flags = 0x00;
701 ent->cur = ent->length;
702 break;
703 }
704
705 frame_vol *= (float)ent->fadeout_current * fadeout_divisor;
706 ent->fadeout_current --;
707 }
708
709 float sl = 1.0f-pan,
710 sr = 1.0f+pan;
711
712 buffer[ buffer_pos*2+0 ] += pcf[ buffer_pos*2+0 ] * frame_vol * sl;
713 buffer[ buffer_pos*2+1 ] += pcf[ buffer_pos*2+1 ] * frame_vol * sr;
714
715 buffer_pos ++;
716 }
717
718 vg_profile_end( &_vg_prof_audio_mix );
719 }
720
721 /*
722 * callback from miniaudio.h interface
723 */
724 VG_STATIC void audio_mixer_callback( ma_device *pDevice, void *pOutBuf,
725 const void *pInput, ma_uint32 frame_count )
726 {
727 struct timespec time_start, time_end;
728 clock_gettime( CLOCK_REALTIME, &time_start );
729
730 audio_system_enque();
731
732 /* Clear buffer */
733 float *pOut32F = (float *)pOutBuf;
734 for( int i=0; i<frame_count*2; i ++ )
735 pOut32F[i] = 0.0f;
736
737 /* Mix all sounds */
738 for( int i=0; i<SFX_MAX_SYSTEMS; i ++ )
739 {
740 struct active_audio_player *aap = &vg_audio.active_players[i];
741
742 if( aap->active )
743 {
744 audio_entity_mix( i, pOut32F, frame_count );
745 }
746 }
747
748 /* redistribute */
749 audio_system_cleanup();
750
751 /* TODO: what the hell is this? */
752 (void)pInput;
753
754
755 audio_lock();
756 vg_profile_increment( &_vg_prof_audio_decode );
757 vg_profile_increment( &_vg_prof_audio_mix );
758
759 vg_prof_audio_mix = _vg_prof_audio_mix;
760 vg_prof_audio_decode = _vg_prof_audio_decode;
761
762 vg_audio.samples_last = frame_count;
763 audio_unlock();
764 }
765
766 VG_STATIC void audio_clip_load( audio_clip *clip )
767 {
768 if( clip->source_mode == k_audio_source_mono )
769 {
770 vg_linear_clear( vg_mem.scratch );
771 u32 fsize;
772 void *filedata = vg_file_read( vg_mem.scratch, clip->path, &fsize );
773
774 stb_vorbis_alloc alloc = {
775 .alloc_buffer = vg_linear_alloc( vg_mem.scratch, AUDIO_DECODE_SIZE ),
776 .alloc_buffer_length_in_bytes = AUDIO_DECODE_SIZE
777 };
778
779 int err;
780 stb_vorbis *decoder = stb_vorbis_open_memory(
781 filedata, fsize, &err, &alloc );
782
783 if( !decoder )
784 {
785 vg_error( "stb_vorbis_open_memory failed on '%s' (%d)\n",
786 clip->path, err );
787 vg_fatal_exit_loop( "Vorbis decode error" );
788 }
789
790 /* only mono is supported in uncompressed */
791 u32 length_samples = stb_vorbis_stream_length_in_samples( decoder ),
792 data_size = length_samples * sizeof(i16);
793
794 clip->data = vg_linear_alloc( vg_audio.audio_pool, data_size );
795 clip->size = length_samples;
796
797 int read_samples = stb_vorbis_get_samples_i16_interleaved_mono(
798 decoder, clip->data, length_samples );
799
800 float mb = (float)(data_size) / (1024.0f*1024.0f);
801 vg_info( "Loaded audio clip '%s' (%.1fmb)\n", clip->path, mb );
802 }
803
804 /* load in directly */
805 else if( clip->source_mode == k_audio_source_compressed )
806 {
807 clip->data = vg_file_read( vg_audio.audio_pool, clip->path, &clip->size );
808
809 if( !clip->data )
810 vg_fatal_exit_loop( "Audio failed to load" );
811
812 float mb = (float)(clip->size) / (1024.0f*1024.0f);
813 vg_info( "Loaded audio clip '%s' (%.1fmb)\n", clip->path, mb );
814 }
815 }
816
817 VG_STATIC void audio_clip_loadn( audio_clip *arr, int count )
818 {
819 for( int i=0; i<count; i++ )
820 audio_clip_load( &arr[i] );
821 }
822
823 /* Mark change to be uploaded through queue system */
824 VG_STATIC void audio_player_commit( audio_player *sys )
825 {
826 audio_require_lock();
827
828 if( vg_audio.queue_len >= vg_list_size( vg_audio.entity_queue ) )
829 {
830 vg_warn( "Audio commit queue full\n" );
831 return;
832 }
833
834 if( sys->enqued )
835 {
836 vg_warn( "Audio commit spamming; already enqued (%s)\n", sys->name );
837 return;
838 }
839
840 sys->enqued = 1;
841 audio_entity *ent = &vg_audio.entity_queue[ vg_audio.queue_len ++ ];
842 ent->info = sys->info;
843 ent->player = sys;
844 }
845
846 VG_STATIC void audio_require_init( audio_player *player )
847 {
848 if( player->init )
849 return;
850
851 vg_fatal_exit_loop( "Must init audio player before playing! \n" );
852 }
853
854 VG_STATIC void audio_require_clip_loaded( audio_clip *clip )
855 {
856 if( clip->data && clip->size )
857 return;
858
859 vg_fatal_exit_loop( "Must load audio clip before playing! \n" );
860 }
861
862 /* Play a clip using player. If its already playing something, it will
863 * fadeout quickly and start the next sound */
864 VG_STATIC void audio_player_playclip( audio_player *player, audio_clip *clip )
865 {
866 audio_require_lock();
867 audio_require_init( player );
868 audio_require_clip_loaded( clip );
869
870 if( player->info.flags & AUDIO_FLAG_KILL )
871 {
872 vg_error( "Can't start audio clip on player that is/has disconnected" );
873 return;
874 }
875
876 player->info.source = clip;
877 audio_player_commit( player );
878 }
879
880 #if 0
881 VG_STATIC void audio_player_playoneshot( audio_player *player, audio_clip *clip )
882 {
883 audio_require_lock();
884 audio_require_init( player );
885 }
886 #endif
887
888 VG_STATIC void audio_play_oneshot( audio_clip *clip, float volume )
889 {
890 audio_require_lock();
891 audio_require_clip_loaded( clip );
892
893 if( vg_audio.queue_len >= vg_list_size( vg_audio.entity_queue ) )
894 {
895 vg_warn( "Audio commit queue full\n" );
896 return;
897 }
898
899 audio_entity *ent = &vg_audio.entity_queue[ vg_audio.queue_len ++ ];
900
901 ent->info.flags = AUDIO_FLAG_ONESHOT;
902 ent->info.pan = 0.0f;
903 ent->info.source = clip;
904 ent->info.vol = volume;
905 ent->player = NULL;
906 }
907
908 VG_STATIC void audio_player_init( audio_player *player )
909 {
910 player->active_entity = AATREE_PTR_NIL;
911 player->init = 1;
912 }
913
914 /*
915 * Effects
916 */
917
918 /*
919 * Safety enforced Get/set attributes
920 */
921
922 VG_STATIC int audio_player_is_playing( audio_player *sys )
923 {
924 audio_require_lock();
925
926 if( sys->active_entity != AATREE_PTR_NIL )
927 return 1;
928 else
929 return 0;
930 }
931
932 VG_STATIC void audio_player_set_position( audio_player *sys, v3f pos )
933 {
934 audio_require_lock();
935 v3_copy( pos, sys->info.world_position );
936 }
937
938 VG_STATIC void audio_player_set_vol( audio_player *sys, float vol )
939 {
940 audio_require_lock();
941 sys->info.vol = vol;
942 }
943
944 VG_STATIC float audio_player_get_vol( audio_player *sys )
945 {
946 audio_require_lock();
947 return sys->info.vol;
948 }
949
950 VG_STATIC void audio_player_set_pan( audio_player *sys, float pan )
951 {
952 audio_require_lock();
953 sys->info.pan = pan;
954 }
955
956 VG_STATIC float audio_player_get_pan( audio_player *sys )
957 {
958 audio_require_lock();
959 return sys->info.pan;
960 }
961
962 VG_STATIC void audio_player_set_flags( audio_player *sys, u32 flags )
963 {
964 audio_require_lock();
965 sys->info.flags = flags;
966 }
967
968 VG_STATIC u32 audio_player_get_flags( audio_player *sys )
969 {
970 audio_require_lock();
971 return sys->info.flags;
972 }
973
974
975 /*
976 * Debugging
977 */
978
979 VG_STATIC void audio_debug_ui( m4x4f mtx_pv )
980 {
981 if( !vg_audio.debug_ui )
982 return;
983
984 /* Get data */
985 struct sound_info
986 {
987 const char *name;
988 u32 cursor, flags, length;
989 v3f pos;
990 float vol;
991 }
992 infos[ SFX_MAX_SYSTEMS ];
993 int num_systems = 0;
994
995 audio_lock();
996
997 for( int i=0; i<SFX_MAX_SYSTEMS; i ++ )
998 {
999 struct active_audio_player *aap = &vg_audio.active_players[i];
1000
1001 if( !aap->active )
1002 continue;
1003
1004 audio_entity *ent = &aap->ent;
1005 struct sound_info *snd = &infos[ num_systems ++ ];
1006
1007 snd->name = ent->name;
1008 snd->cursor = ent->cur;
1009 snd->flags = ent->info.flags;
1010 snd->length = ent->length;
1011 snd->vol = ent->info.vol*100.0f;
1012 v3_copy( ent->info.world_position, snd->pos );
1013 }
1014
1015 float budget = ((double)vg_audio.samples_last / 44100.0) * 1000.0;
1016 vg_profile_drawn( (struct vg_profile *[]){ &vg_prof_audio_decode,
1017 &vg_prof_audio_mix }, 2,
1018 budget, (ui_rect){ 4, VG_PROFILE_SAMPLE_COUNT*2 + 8,
1019 250, 0 }, 3 );
1020
1021 audio_unlock();
1022
1023 char perf[128];
1024
1025 /* Draw UI */
1026 vg_uictx.cursor[0] = 258;
1027 vg_uictx.cursor[1] = VG_PROFILE_SAMPLE_COUNT*2+8+24+12;
1028 vg_uictx.cursor[2] = 150;
1029 vg_uictx.cursor[3] = 12;
1030
1031 float mb1 = 1024.0f*1024.0f,
1032 usage = vg_linear_get_cur( vg_audio.audio_pool ) / mb1,
1033 total = vg_linear_get_capacity( vg_audio.audio_pool ) / mb1,
1034 percent = (usage/total) * 100.0f;
1035
1036 snprintf( perf, 127, "Mem: %.1f/%.1fmb (%.1f%%)\n", usage, total, percent );
1037
1038 ui_text( vg_uictx.cursor, perf, 1, 0 );
1039 vg_uictx.cursor[1] += 20;
1040
1041 ui_rect overlap_buffer[ SFX_MAX_SYSTEMS ];
1042 u32 overlap_length = 0;
1043
1044 /* Draw audio stack */
1045 for( int i=0; i<num_systems; i ++ )
1046 {
1047 struct sound_info *inf = &infos[i];
1048
1049 vg_uictx.cursor[2] = 200;
1050 vg_uictx.cursor[3] = 18;
1051
1052 u32 alpha = 0xa0000000;
1053
1054 ui_new_node();
1055 {
1056 ui_fill_rect( vg_uictx.cursor, 0x00333333|alpha );
1057
1058 ui_px baseline = vg_uictx.cursor[0],
1059 w = 200,
1060 c = baseline + ((float)inf->cursor / (float)inf->length) * w;
1061
1062 /* cursor */
1063 vg_uictx.cursor[2] = 2;
1064 vg_uictx.cursor[0] = c;
1065 ui_fill_rect( vg_uictx.cursor, 0xffffffff );
1066
1067 vg_uictx.cursor[0] = baseline + 2;
1068 vg_uictx.cursor[1] += 2;
1069 snprintf( perf, 127, "%s %.1f%%", infos[i].name, infos[i].vol );
1070 ui_text( vg_uictx.cursor, perf, 1, 0 );
1071
1072 if( inf->flags & AUDIO_FLAG_SPACIAL_3D )
1073 {
1074 v4f wpos;
1075 v3_copy( inf->pos, wpos );
1076 wpos[3] = 1.0f;
1077 m4x4_mulv( mtx_pv, wpos, wpos );
1078
1079 if( wpos[3] < 0.0f )
1080 goto projected_behind;
1081
1082 v2_muls( wpos, (1.0f/wpos[3]) * 0.5f, wpos );
1083 v2_add( wpos, (v2f){ 0.5f, 0.5f }, wpos );
1084
1085 ui_rect wr;
1086 wr[0] = wpos[0] * vg.window_x;
1087 wr[1] = (1.0f-wpos[1]) * vg.window_y;
1088 wr[2] = 100;
1089 wr[3] = 17;
1090
1091 for( int j=0; j<12; j++ )
1092 {
1093 int collide = 0;
1094 for( int k=0; k<overlap_length; k++ )
1095 {
1096 ui_px *wk = overlap_buffer[k];
1097 if( ((wr[0] <= wk[0]+wk[2]) && (wr[0]+wr[2] >= wk[0])) &&
1098 ((wr[1] <= wk[1]+wk[3]) && (wr[1]+wr[3] >= wk[1])) )
1099 {
1100 collide = 1;
1101 break;
1102 }
1103 }
1104
1105 if( !collide )
1106 break;
1107 else
1108 wr[1] += 18;
1109 }
1110
1111 ui_text( wr, perf, 1, 0 );
1112
1113 ui_rect_copy( wr, overlap_buffer[ overlap_length ++ ] );
1114 }
1115 }
1116
1117 projected_behind:
1118
1119 ui_end_down();
1120 vg_uictx.cursor[1] += 1;
1121 }
1122 }
1123
1124 #endif /* VG_AUDIO_H */