This repository has been archived by the owner on Jan 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfaun.c
2925 lines (2469 loc) · 78.4 KB
/
faun.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ___________
\_ _____/____ __ __ ____
| __) \__ \ | | \/ \
| \ / __ \| | / | \
\__ / (____ /____/|___| /
\/ \/ \/
Faun - A high-level C audio library
Copyright (c) 2022-2024 Karl Robillard
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "faun.h"
#if __STDC_VERSION__ < 201112L || defined(__STDC_NO_ATOMICS__)
#error "Atomic support is required for playback ids!"
#else
#include <stdatomic.h>
#endif
#ifdef ANDROID
#include "sys_aaudio.c"
#elif defined(__linux__)
#include "sys_pulseaudio.c"
#elif defined(_WIN32)
#include "sys_wasapi.c"
#else
#error "Unsupported system"
#endif
#include <vorbis/codec.h>
#include <vorbis/vorbisfile.h>
#ifdef CAPTURE
#include "wav_write.c"
FILE* wfp = NULL;
int endOnSignal = 0;
int endCapture = 0;
#endif
#if 0
#define REPORT_STREAM(st,msg) \
printf("FAUN strm %x: %s\n",_asource[st->sindex].serialNo,msg)
#define REPORT_BUF(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define REPORT_MIX(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define REPORT_STREAM(st,msg)
#define REPORT_BUF(msg, ...)
#define REPORT_MIX(msg, ...)
#endif
typedef struct {
#ifdef GLV_ASSET_H
struct AssetFile asset;
#define cfile asset.fp
#else
FILE* cfile;
#endif
uint32_t offset;
uint32_t size;
}
FileChunk;
typedef struct {
uint8_t op;
uint8_t select;
uint16_t ext;
union {
uint16_t u16[8];
uint32_t u32[4];
float f[4];
} arg;
}
CommandA;
typedef struct {
uint8_t op;
uint8_t select;
uint16_t ext;
FileChunk chunk;
}
CommandF;
enum FaunCmd {
CMD_QUIT,
CMD_SUSPEND,
CMD_RESUME,
CMD_PROGRAM,
CMD_PROGRAM_END,
CMD_PROGRAM_MID,
CMD_PROGRAM_BEG,
CMD_SET_BUFFER,
CMD_BUFFERS_FREE,
CMD_PLAY_SOURCE,
CMD_PLAY_SOURCE_VOL,
CMD_OPEN_STREAM_SIZE,
CMD_OPEN_STREAM,
CMD_PLAY_STREAM_PART,
CMD_VOLUME_VARY,
CMD_CON_START,
CMD_CON_STOP,
CMD_CON_RESUME,
CMD_CON_FADE_OUT,
CMD_PARAM_VOLUME,
CMD_PARAM_VOLUME_APPLY,
CMD_PARAM_FADE_PERIOD,
CMD_PARAM_END_TIME,
CMD_COUNT
};
#define MSG_SIZE 20
#define PROG_CHEAD 3
typedef struct {
uint8_t code[FAUN_PROGRAM_MAX];
int pc;
int used;
uint16_t running;
uint16_t si;
uint32_t waitPos;
}
FaunProgram;
enum SourceState {
SS_UNUSED,
SS_PLAYING,
SS_STOPPED
};
#define NUL_PLAY_ID 0
#define QACTIVE_NONE 0xffff
#define END_POS_NONE 0x7fffffff
#define SOURCE_QUEUE_SIZE 4
#define BID_PACKED 0x3ff
#define SOURCE_ID(src) (src->serialNo & 0xff)
// Internal FaunPlayMode flags
#define PLAY_TARGET_VOL 0x4000
#define END_AFTER_FADE 0x8000
typedef struct {
uint16_t state; // SourceState
uint16_t bufUsed; // Number of buffers in queue.
uint16_t qtail; // Queue index of append position.
uint16_t qhead;
uint16_t qactive; // Queue index of currently playing buffer.
uint16_t mode;
// These are ordered to match fadeTriplet.
float gainL; // Current volume.
float gainR;
float fadeL; // Gain delta per frame.
float fadeR;
float targetL; // Target volume.
float targetR;
float playVolume; // FAUN_VOLUME, used when play begins.
float fadePeriod; // FAUN_FADE_PERIOD
uint32_t serialNo;
uint32_t playPos; // Frame position in current buffer.
uint32_t framesOut; // Total frames played.
uint32_t endPos; // User specified end frame. FAUN_END_TIME
uint32_t fadePos; // Frame to begin fade out.
FaunBuffer* bufferQueue[SOURCE_QUEUE_SIZE];
}
FaunSource;
static const uint8_t faun_formatSize[FAUN_FORMAT_COUNT] = { 1, 2, 3, 4 };
static FILE* _errStream;
static void faun_sourceInit(FaunSource* src, int si)
{
memset(src, 0, sizeof(FaunSource));
src->qactive = QACTIVE_NONE;
src->gainL = src->gainR = 1.0f;
//src->fadeL = src->fadeR = 0.0f;
src->targetL = src->targetR =
src->playVolume = 1.0f;
src->fadePeriod = 1.5f;
src->serialNo = si;
src->endPos =
src->fadePos = END_POS_NONE;
}
static void faun_setBuffer(FaunSource* src, FaunBuffer* buf)
{
src->bufUsed = src->qtail = 1;
src->qhead = src->qactive = 0;
src->bufferQueue[0] = buf;
}
static void faun_sourceResetQueue(FaunSource* src)
{
src->bufUsed = src->qtail = src->qhead = 0;
src->qactive = QACTIVE_NONE;
}
static void faun_queueBuffer(FaunSource* src, FaunBuffer* buf)
{
int i;
if (src->bufUsed < SOURCE_QUEUE_SIZE) {
src->bufUsed++;
i = src->qtail;
src->bufferQueue[i] = buf;
if (src->qactive == QACTIVE_NONE)
src->qactive = i;
if (++i == SOURCE_QUEUE_SIZE)
i = 0;
src->qtail = i;
} else
fprintf(_errStream, "Faun source queue full (%x)\n", src->serialNo);
}
/*
* Dequeue the next played buffer.
* Return buffer pointer or NULL if there are none finished playing in the
* queue.
*/
static FaunBuffer* faun_processedBuffer(FaunSource* src)
{
FaunBuffer* ptr;
int i;
if (src->bufUsed && src->qactive != src->qhead) {
i = src->qhead;
ptr = src->bufferQueue[i];
if (++i == SOURCE_QUEUE_SIZE)
i = 0;
src->qhead = i;
src->bufUsed--;
return ptr;
}
return NULL;
}
void faun_reserve(FaunBuffer* buf, int frames)
{
if (buf->avail < (uint32_t) frames) {
buf->sample.ptr = realloc(buf->sample.ptr,
frames * faun_formatSize[buf->format] *
faun_channelCount(buf->chanLayout));
buf->avail = frames;
}
}
static void faun_allocBufferSamples(FaunBuffer* buf, int fmt, int chan,
int rate, int frames)
{
free(buf->sample.ptr);
buf->sample.ptr = malloc(frames * faun_formatSize[fmt] *
faun_channelCount(chan));
buf->avail = frames;
buf->used = 0;
buf->rate = rate;
buf->format = fmt;
buf->chanLayout = chan;
}
static void faun_freeBufferSamples(int n, FaunBuffer* buf)
{
int i;
for (i = 0; i < n; ++i) {
free(buf->sample.ptr);
buf->sample.ptr = NULL;
++buf;
}
}
#define STREAM_BUFFERS 4
#define SEGMENT_SET(st) st->sampleLimit
typedef struct {
FaunBuffer buffers[STREAM_BUFFERS];
int bufAvail;
int16_t feed;
int16_t sindex;
double start;
uint32_t sampleCount; // Number of samples read
uint32_t sampleLimit; // Number of samples to buffer before ending
FileChunk chunk;
OggVorbis_File vf;
vorbis_info* vinfo;
}
StreamOV;
enum AudioState
{
AUDIO_DOWN,
AUDIO_UP,
AUDIO_THREAD_UP
};
enum ReadOggStatus {
RSTAT_ERROR = 1,
RSTAT_EOF = 2,
RSTAT_DATA = 4
};
#define BUFFER_MAX 256
#define SOURCE_MAX 32
#define STREAM_MAX 6
#define PEXEC_MAX 16
static int _audioUp = AUDIO_DOWN;
static int _bufferLimit;
static int _sourceLimit;
static int _streamLimit;
static int _pexecLimit;
static uint32_t _playSerialNo;
static FaunVoice _voice;
static FaunBuffer* _abuffer = NULL;
static FaunSource* _asource = NULL;
static StreamOV* _stream = NULL;
static FaunProgram* _pexec = NULL;
static _Atomic uint32_t* _playbackId = NULL;
static atomic_flag _pidLock;
//----------------------------------------------------------------------------
#include "wav_read.c"
static void _allocBufferVoice(FaunBuffer*, int);
#ifdef USE_FLAC
#include "FlacReader.c"
#endif
#ifdef USE_SFX_GEN
#define CONFIG_SFX_NO_FILEIO
#define CONFIG_SFX_NO_GENERATORS
#define SINGLE_FORMAT 3
#include "sfx_gen.c"
#define well512_init faun_randomSeed
#define well512_genU32 faun_random
#include "well512.c"
Well512 _rng;
int sfx_random(int range) {
return faun_random(&_rng) % range;
}
static void convertMono(float*, float*, float**);
static void faun_generateSfx(FaunBuffer* buf, const SfxParams* sp)
{
SfxSynth* synth;
float* dst;
float* src;
uint32_t frames;
synth = sfx_allocSynth(SFX_F32, 44100, 6);
faun_randomSeed(&_rng, sp->randSeed);
frames = sfx_generateWave(synth, sp);
_allocBufferVoice(buf, frames);
dst = buf->sample.f32;
src = synth->samples.f;
convertMono(dst, dst + frames*2, &src);
buf->used = frames;
free(synth);
}
#endif
#define ID_FLAC MAKE_ID('f','L','a','C')
#define ID_OGGS MAKE_ID('O','g','g','S')
#define ID_RFX_ MAKE_ID('r','F','X',' ')
//----------------------------------------------------------------------------
static size_t chunk_fread(void* buf, size_t size, size_t nmemb, void* fh)
{
//printf("OV fread %ld %ld\n", size, nmemb);
return fread(buf, size, nmemb, ((FileChunk*) fh)->cfile);
}
static int chunk_fseek(void* fh, ogg_int64_t offset, int whence)
{
FileChunk* fc = (FileChunk*) fh;
//printf("OV seek %ld %d\n", offset, whence);
if (whence == SEEK_SET)
offset += fc->offset;
else if (whence == SEEK_END && fc->size) {
whence = SEEK_SET;
offset += fc->offset + fc->size;
}
return fseek(fc->cfile, offset, whence);
}
static int chunk_fclose(void* fh)
{
FileChunk* fc = (FileChunk*) fh;
int ok = fclose(fc->cfile);
fc->cfile = NULL;
return ok;
}
static long chunk_ftell(void* fh)
{
FileChunk* fc = (FileChunk*) fh;
long pos = ftell(fc->cfile);
long start = (long) fc->offset;
if (pos < start)
return -1;
//printf("OV ftell %ld %ld\n", pos, pos-start);
return pos - start;
}
static ov_callbacks chunkMethods = {
chunk_fread, chunk_fseek, chunk_fclose, chunk_ftell
};
static ov_callbacks chunkMethodsNoClose = {
chunk_fread, chunk_fseek, NULL, chunk_ftell
};
static int _readOgg(StreamOV* st, FaunBuffer* buffer);
//----------------------------------------------------------------------------
// Allocate a buffer with attributes that match the voice mixing buffer.
static void _allocBufferVoice(FaunBuffer* buf, int frames)
{
faun_allocBufferSamples(buf, FAUN_F32, FAUN_CHAN_2, _voice.mix.rate,
frames);
}
static void convS16_F32(float* dst, const int16_t* src, int frames, int rate,
int channels)
{
const int16_t* end = src + frames * channels;
float ls, rs;
if (channels == 1) {
if (rate == 22050) {
for (; src != end; ++src) {
ls = *src / 32767.0f;
*dst++ = ls;
*dst++ = ls;
*dst++ = ls;
*dst++ = ls;
}
} else {
for (; src != end; ++src) {
ls = *src / 32767.0f;
*dst++ = ls;
*dst++ = ls;
}
}
} else if (channels >= 2) {
if (rate == 22050) {
for (; src != end; src += channels) {
ls = src[0] / 32767.0f;
rs = src[1] / 32767.0f;
*dst++ = ls;
*dst++ = rs;
*dst++ = ls;
*dst++ = rs;
}
} else {
for (; src != end; src += channels) {
*dst++ = src[0] / 32767.0f;
*dst++ = src[1] / 32767.0f;
}
}
}
}
#ifdef USE_LOAD_MEM
static void convF32_F32(float* dst, const float* src, int frames, int rate,
int channels)
{
const float* end = src + frames * channels;
float ls, rs;
if (channels == 1) {
if (rate == 22050) {
for (; src != end; ++src) {
ls = *src;
*dst++ = ls;
*dst++ = ls;
*dst++ = ls;
*dst++ = ls;
}
} else {
for (; src != end; ++src) {
ls = *src;
*dst++ = ls;
*dst++ = ls;
}
}
} else if (channels >= 2) {
if (rate == 22050) {
for (; src != end; src += channels) {
ls = src[0];
rs = src[1];
*dst++ = ls;
*dst++ = rs;
*dst++ = ls;
*dst++ = rs;
}
} else {
for (; src != end; src += channels) {
*dst++ = src[0];
*dst++ = src[1];
}
}
}
}
#endif
/*
Read buffer sample data from a file.
The existing buf->sample data is freed first, so the sample.ptr must
be valid or NULL.
Return error message or NULL if successful.
*/
static const char* faun_readBuffer(FaunBuffer* buf, FILE* fp,
uint32_t offset, uint32_t size)
{
WavHeader wh;
const char* error = NULL;
uint32_t frames = 0;
const int wavReadLen = 20; // wav_readHeader() reads 20 bytes.
int err;
if (offset)
fseek(fp, offset, SEEK_SET);
err = wav_readHeader(fp, &wh);
if (err == 0) {
void* readBuf;
size_t n;
uint32_t wavFrames;
//wav_dumpHeader(stdout, &wh, NULL, " ");
if (wh.sampleRate != 44100 && wh.sampleRate != 22050)
return "WAVE sample rate is unsupported";
#ifdef USE_LOAD_MEM
if (wh.format == WAV_IEEE_FLOAT) {
if (wh.bitsPerSample != 32)
return "WAVE float bits per sample is not 32";
} else
#endif
if (wh.bitsPerSample != 16)
return "WAVE bits per sample is not 16";
frames = wavFrames = wav_sampleCount(&wh);
if (wh.sampleRate == 22050)
frames *= 2;
_allocBufferVoice(buf, frames);
readBuf = malloc(wh.dataSize);
n = fread(readBuf, 1, wh.dataSize, fp);
if (n != wh.dataSize) {
error = "WAVE fread failed";
} else {
buf->used = frames;
#ifdef USE_LOAD_MEM
if (wh.format == WAV_IEEE_FLOAT)
convF32_F32(buf->sample.f32, (float*) readBuf, wavFrames,
wh.sampleRate, wh.channels);
else
#endif
convS16_F32(buf->sample.f32, (int16_t*) readBuf, wavFrames,
wh.sampleRate, wh.channels);
}
free(readBuf);
}
else if (err == WAV_ERROR_ID)
{
if (wh.idRIFF == ID_OGGS)
{
StreamOV os;
int status;
// Minimal version of stream_init() to use _readOgg().
os.sampleCount = 0;
os.chunk.cfile = fp;
os.chunk.offset = offset;
os.chunk.size = size;
if (ov_open_callbacks(&os.chunk, &os.vf, (char*) &wh, wavReadLen,
chunkMethodsNoClose) < 0)
{
error = "Ogg open failed";
}
else
{
os.vinfo = ov_info(&os.vf, -1);
frames = ov_pcm_total(&os.vf, -1);
if (os.vinfo->rate == 22050)
frames *= 2;
//printf("FAUN ogg frame:%d chan:%d rate:%ld\n",
// frames, os.vinfo->channels, os.vinfo->rate);
_allocBufferVoice(buf, frames);
status = _readOgg(&os, buf);
if (status != RSTAT_DATA)
error = "Ogg read failed";
ov_clear(&os.vf);
}
}
else if (wh.idRIFF == ID_FLAC)
{
#ifndef USE_FLAC
error = "Faun built without FLAC support";
#elif USE_FLAC == 2
error = foxenFlacDecode(fp, size, buf, &wh, wavReadLen);
#else
fseek(fp, -wavReadLen, SEEK_CUR);
error = libFlacDecode(fp, size, buf);
#endif
}
#ifdef USE_SFX_GEN
else if (wh.idRIFF == ID_RFX_)
{
SfxParams sfx;
int version = ((uint16_t*) &wh)[2];
if (version != 200)
error = "rFX file version not supported";
else {
fseek(fp, offset + 8, SEEK_SET);
if (fread(&sfx, 1, sizeof(SfxParams), fp) == sizeof(SfxParams))
faun_generateSfx(buf, &sfx);
else
error = "rFX fread failed";
}
}
#endif
}
#if 0
fp = wav_open("/tmp/out.wav", 44100, 16, 2);
wav_write(fp, buf->sample.f32, buf->used*2);
wav_close(fp);
#endif
return error;
}
static void faun_deactivate(FaunSource* src, int si)
{
src->qactive = QACTIVE_NONE;
src->state = SS_UNUSED;
// Clear playback id (unless an incoming command has already changed it).
while (atomic_flag_test_and_set(&_pidLock)) {}
if (_playbackId[si] == src->serialNo)
_playbackId[si] = NUL_PLAY_ID;
atomic_flag_clear(&_pidLock);
}
// Abort all sources playing a freed buffer.
static void faun_detachBuffers()
{
FaunSource* src;
int i;
for (i = 0; i < _sourceLimit; ++i) {
src = _asource + i;
if (src->qactive != QACTIVE_NONE) {
// Only the current buffer is checked; any queued buffers
// will be skipped during the "Advance play positions" phase.
if (! src->bufferQueue[src->qactive]->sample.ptr) {
faun_deactivate(src, i);
}
}
}
}
//----------------------------------------------------------------------------
static void stream_init(StreamOV* st, int id)
{
memset(&st->buffers, 0, sizeof(FaunBuffer) * STREAM_BUFFERS);
st->feed = 0;
st->sindex = id;
#ifdef GLV_ASSET_H
memset(&st->asset, 0, sizeof(struct AssetFile));
#else
st->chunk.cfile = NULL;
#endif
}
static void stream_free(StreamOV* st)
{
faun_freeBufferSamples(STREAM_BUFFERS, st->buffers);
}
static void stream_closeFile(StreamOV* st)
{
ov_clear(&st->vf); // Closes st->chunk.cfile for us.
st->chunk.cfile = NULL;
#ifdef _ANDROID_
glv_assetClose(&st->asset);
#endif
}
static void convertStereoHR(float* dst, float* end, float** src)
{
const float* ls = src[0];
const float* rs = src[1];
float L, R;
while (dst != end) {
L = *ls++;
R = *rs++;
*dst++ = L;
*dst++ = R;
*dst++ = L;
*dst++ = R;
}
}
// Interleave the separate channel data.
static void convertStereo(float* dst, float* end, float** src)
{
const float* ls = src[0];
const float* rs = src[1];
while (dst != end) {
*dst++ = *ls++;
*dst++ = *rs++;
}
}
static void convertMonoHR(float* dst, float* end, float** src)
{
const float* c0 = src[0];
float L, R;
while (dst != end) {
L = *c0;
R = *c0++;
*dst++ = L;
*dst++ = R;
*dst++ = L;
*dst++ = R;
}
}
static void convertMono(float* dst, float* end, float** src)
{
const float* c0 = src[0];
float C;
while (dst != end) {
C = *c0++;
*dst++ = C;
*dst++ = C;
}
}
typedef void (*StreamConvertFunc)(float*, float*, float**);
/*
Decode some audio, copy it into a buffer, and update sampleCount.
Returns a mask of ReadOggStatus bits.
*/
static int _readOgg(StreamOV* st, FaunBuffer* buffer)
{
float** oggPcm;
float* dst;
StreamConvertFunc convert;
int status;
int bitstream;
int count;
int readFrames = buffer->avail;
int readSamples;
long amt = 0;
int halfRate = (st->vinfo->rate == (int) buffer->rate/2);
if (st->vinfo->channels > 1)
convert = halfRate ? convertStereoHR : convertStereo;
else
convert = halfRate ? convertMonoHR : convertMono;
for (count = 0; count < readFrames; count += amt)
{
// Decode one vorbis packet. Samples are decoded internally to float
// so ov_read_float is faster than ov_read.
readSamples = readFrames - count;
if (halfRate)
readSamples /= 2;
amt = ov_read_float(&st->vf, &oggPcm, readSamples, &bitstream);
if (amt < 1)
break;
if (halfRate)
amt *= 2;
dst = buffer->sample.f32 + count*2;
convert(dst, dst + amt*2, oggPcm);
}
if( amt < 0 )
{
fprintf(_errStream, "ov_read error %ld\n", amt);
status = RSTAT_ERROR;
}
else
status = amt ? 0 : RSTAT_EOF;
buffer->used = count;
if( count > 0 )
{
status |= RSTAT_DATA;
st->sampleCount += count;
REPORT_BUF("FAUN readOgg buf used: %d (%d)\n", count, st->sampleCount);
//wav_write(wfp, buffer->sample.f32, count*2);
}
return status;
}
static int stream_fillBuffers(StreamOV*);
static void stream_start(StreamOV* st)
{
FaunSource* src = _asource + st->sindex;
FaunBuffer* buf = st->buffers;
int i;
if (! buf->sample.ptr)
{
// Allocate on first use; match attributes of voice mixing buffer.
// Size each buffer to hold 1/4 second of data (multiple of 8 samples).
int rate = _voice.mix.rate;
int frameCount = ((rate / 4) + 7) & ~7;
for (i = 0; i < STREAM_BUFFERS; ++i)
faun_allocBufferSamples(buf + i, FAUN_F32, FAUN_CHAN_2,
rate, frameCount);
}
faun_sourceResetQueue(src);
for (i = 0; i < STREAM_BUFFERS; ++buf, ++i)
{
buf->used = 0;
src->bufferQueue[i] = buf;
}
src->bufUsed = STREAM_BUFFERS; // Prime faun_processedBuffer().
st->feed = 1;
stream_fillBuffers(st);
if (st->sampleCount)
{
src->state = SS_PLAYING;
src->playPos =
src->framesOut = 0;
REPORT_STREAM(st,"start");
}
}
static void stream_stop(StreamOV* st)
{
REPORT_STREAM(st,"stop");
_asource[st->sindex].state = SS_STOPPED;
st->feed = 0;
if( st->chunk.cfile )
stream_closeFile( st );
}
static void signalDone(const FaunSource* src)
{
FaunSignal sig;
sig.id = src->serialNo;
sig.signal = FAUN_SIGNAL_DONE;
//printf("signalDone %x\n", sig.id);
tmsg_push(_voice.sig, &sig);
#ifdef CAPTURE
if (endOnSignal)
endCapture = 1;
#endif
}
/*
Immediately set current volumes and halt fading.
*/
static inline void source_setGain(FaunSource* src, float volL, float volR)
{
src->gainL = volL;
src->gainR = volR;
src->fadeL = src->fadeR = 0.0f;
}
#define FADE_DELTA(vol,period) ((vol / period) / 44100.0f)
#define GAIN_SILENCE_THRESHOLD 0.001f
/*
Set fadeL/fadeR to change current gains to target volumes over fadePeriod.
*/
static void source_setFadeDeltas(FaunSource* src)
{
if (src->fadePeriod) {
float inc = FADE_DELTA(1.0f, src->fadePeriod);
#if 1
src->fadeL = inc * (src->targetL - src->gainL);
src->fadeR = inc * (src->targetR - src->gainR);
#else
src->fadeL = (src->targetL < src->gainL) ? -inc * src->gainL
: inc * src->targetL;
src->fadeR = (src->targetR < src->gainR) ? -inc * src->gainR
: inc * src->targetR;
#endif
} else {
source_setGain(src, src->targetL, src->targetR);
}
#if 0
printf("KR fadeDeltas hz:%d per:%f %f,%f\n",
_voice.updateHz, src->fadePeriod, src->fadeL, src->fadeR);
#endif
}
/*
Set fadePos to (totalFrames - (fadePeriod * 44100)).
*/
static void source_initFadeOut(FaunSource* src, uint32_t totalFrames)
{
uint32_t ff = (uint32_t) (src->fadePeriod * 44100.0f);
// Avoiding overlap with any fade-in.
if (totalFrames > 2*ff)
src->fadePos = totalFrames - ff;
}
static inline void source_fadeOut(FaunSource* src)
{
float inc = -FADE_DELTA(1.0f, src->fadePeriod);
src->fadeL = inc * src->gainL;
src->fadeR = inc * src->gainR;
src->targetL = src->targetR = 0.0f;
src->mode |= END_AFTER_FADE;
}
static void source_setMode(FaunSource* src, int mode)
{
src->mode = mode;
if (mode & FAUN_PLAY_FADE_IN) {
src->gainL = src->gainR = 0.0f;
src->targetL = src->targetR = src->playVolume;
source_setFadeDeltas(src);