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