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