/
stream.d
1359 lines (1181 loc) · 43.1 KB
/
stream.d
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
/**
Audio decoder and encoder abstraction. This delegates to format-specific encoders/decoders.
Copyright: Guillaume Piolats 2020.
License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
*/
module audioformats.stream;
import core.stdc.stdio;
import core.stdc.string;
import core.stdc.stdlib: malloc, realloc, free;
import dplug.core.nogc;
import dplug.core.vec;
import audioformats.io;
version(decodeMP3) import audioformats.minimp3_ex;
version(decodeFLAC) import audioformats.drflac;
version(decodeOGG) import audioformats.stb_vorbis2;
version(decodeOPUS) import audioformats.dopus;
version(decodeMOD) import audioformats.pocketmod;
version(decodeWAV) import audioformats.wav;
else version(encodeWAV) import audioformats.wav;
version(decodeXM) import audioformats.libxm;
/// Library for sound file decoding and encoding.
/// All operations are blocking, and should not be done in a real-time audio thread.
/// (besides, you would also need resampling for playback).
/// Also not thread-safe, synchronization in on yours.
/// Format of audio files.
enum AudioFileFormat
{
wav, /// WAVE format
mp3, /// MP3 format
flac, /// FLAC format
ogg, /// OGG format
opus, /// Opus format
mod, /// ProTracker MOD format
xm, /// FastTracker II Extended Module format
unknown
}
/// Returns: String representation of an `AudioFileFormat`.
string convertAudioFileFormatToString(AudioFileFormat fmt)
{
final switch(fmt) with (AudioFileFormat)
{
case wav: return "wav";
case mp3: return "mp3";
case flac: return "flac";
case ogg: return "ogg";
case opus: return "opus";
case mod: return "mod";
case xm: return "xm";
case unknown: return "unknown";
}
}
/// The length of things you shouldn't query a length about:
/// - files that are being written
/// - audio files you don't know the extent
enum audiostreamUnknownLength = -1;
/// An AudioStream is a pointer to a dynamically allocated `Stream`.
public struct AudioStream
{
public: // This is also part of the public API
/// Opens an audio stream that decodes from a file.
/// This stream will be opened for reading only.
///
/// Params:
/// path An UTF-8 path to the sound file.
///
/// Note: throws a manually allocated exception in case of error. Free it with `dplug.core.destroyFree`.
void openFromFile(const(char)[] path) @nogc
{
cleanUp();
fileContext = mallocNew!FileContext();
fileContext.initialize(path, false);
userData = fileContext;
_io = mallocNew!IOCallbacks();
_io.seek = &file_seek;
_io.tell = &file_tell;
_io.getFileLength = &file_getFileLength;
_io.read = &file_read;
_io.write = null;
_io.skip = &file_skip;
_io.flush = null;
startDecoding();
}
/// Opens an audio stream that decodes from memory.
/// This stream will be opened for reading only.
/// Note: throws a manually allocated exception in case of error. Free it with `dplug.core.destroyFree`.
///
/// Params: inputData The whole file to decode.
void openFromMemory(const(ubyte)[] inputData) @nogc
{
cleanUp();
memoryContext = mallocNew!MemoryContext();
memoryContext.initializeWithConstantInput(inputData.ptr, inputData.length);
userData = memoryContext;
_io = mallocNew!IOCallbacks();
_io.seek = &memory_seek;
_io.tell = &memory_tell;
_io.getFileLength = &memory_getFileLength;
_io.read = &memory_read;
_io.write = null;
_io.skip = &memory_skip;
_io.flush = null;
startDecoding();
}
/// Opens an audio stream that writes to file.
/// This stream will be opened for writing only.
/// Note: throws a manually allocated exception in case of error. Free it with `dplug.core.destroyFree`.
///
/// Params:
/// path An UTF-8 path to the sound file.
/// format Audio file format to generate.
/// sampleRate Sample rate of this audio stream. This samplerate might be rounded up to the nearest integer number.
/// numChannels Number of channels of this audio stream.
void openToFile(const(char)[] path, AudioFileFormat format, float sampleRate, int numChannels) @nogc
{
cleanUp();
fileContext = mallocNew!FileContext();
fileContext.initialize(path, true);
userData = fileContext;
_io = mallocNew!IOCallbacks();
_io.seek = &file_seek;
_io.tell = &file_tell;
_io.getFileLength = null;
_io.read = null;
_io.write = &file_write;
_io.skip = null;
_io.flush = &file_flush;
startEncoding(format, sampleRate, numChannels);
}
/// Opens an audio stream that writes to a dynamically growable output buffer.
/// This stream will be opened for writing only.
/// Access to the internal buffer after encoding with `finalizeAndGetEncodedResult`.
/// Note: throws a manually allocated exception in case of error. Free it with `dplug.core.destroyFree`.
///
/// Params:
/// format Audio file format to generate.
/// sampleRate Sample rate of this audio stream. This samplerate might be rounded up to the nearest integer number.
/// numChannels Number of channels of this audio stream.
void openToBuffer(AudioFileFormat format, float sampleRate, int numChannels) @nogc
{
cleanUp();
memoryContext = mallocNew!MemoryContext();
memoryContext.initializeWithInternalGrowableBuffer();
userData = memoryContext;
_io = mallocNew!IOCallbacks();
_io.seek = &memory_seek;
_io.tell = &memory_tell;
_io.getFileLength = null;
_io.read = null;
_io.write = &memory_write_append;
_io.skip = null;
_io.flush = &memory_flush;
startEncoding(format, sampleRate, numChannels);
}
/// Opens an audio stream that writes to a pre-defined area in memory of `maxLength` bytes.
/// This stream will be opened for writing only.
/// Destroy this stream with `closeAudioStream`.
/// Note: throws a manually allocated exception in case of error. Free it with `dplug.core.destroyFree`.
///
/// Params:
/// data Pointer to output memory.
/// size_t maxLength.
/// format Audio file format to generate.
/// sampleRate Sample rate of this audio stream. This samplerate might be rounded up to the nearest integer number.
/// numChannels Number of channels of this audio stream.
void openToMemory(ubyte* data,
size_t maxLength,
AudioFileFormat format,
float sampleRate,
int numChannels) @nogc
{
cleanUp();
memoryContext = mallocNew!MemoryContext();
memoryContext.initializeWithExternalOutputBuffer(data, maxLength);
userData = memoryContext;
_io = mallocNew!IOCallbacks();
_io.seek = &memory_seek;
_io.tell = &memory_tell;
_io.getFileLength = null;
_io.read = null;
_io.write = &memory_write_limited;
_io.skip = null;
_io.flush = &memory_flush;
startEncoding(format, sampleRate, numChannels);
}
/// Returns: `true` if using this stream's operations is acceptable in an audio thread (eg: no file I/O).
bool realtimeSafe() @nogc
{
return fileContext is null;
}
~this() @nogc
{
cleanUp();
}
void cleanUp() @nogc
{
// Write the last needed bytes if needed
finalizeEncodingIfNeeded();
version(decodeMP3)
{
if (_mp3DecoderNew !is null)
{
mp3dec_ex_close(_mp3DecoderNew);
free(_mp3DecoderNew);
_mp3DecoderNew = null;
}
if (_mp3io !is null)
{
free(_mp3io);
_mp3io = null;
}
}
version(decodeFLAC)
{
if (_flacDecoder !is null)
{
drflac_close(_flacDecoder);
_flacDecoder = null;
}
}
version(decodeOGG)
{
if (_oggHandle !is null)
{
stb_vorbis_close(_oggHandle);
_oggHandle = null;
}
_oggBuffer.reallocBuffer(0);
}
version(decodeOPUS)
{
if (_opusDecoder !is null)
{
opusClose(_opusDecoder);
_opusDecoder = null;
}
_opusBuffer = null;
}
version(decodeWAV)
{
if (_wavDecoder !is null)
{
destroyFree(_wavDecoder);
_wavDecoder = null;
}
}
version(decodeXM)
{
if (_xmDecoder !is null)
{
xm_free_context(_xmDecoder);
_xmDecoder = null;
}
if (_xmContent != null)
{
free(_xmContent);
_xmContent = null;
}
}
version(decodeMOD)
{
if (_modDecoder !is null)
{
free(_modDecoder);
_modDecoder = null;
_modContent.reallocBuffer(0);
}
}
version(encodeWAV)
{
if (_wavEncoder !is null)
{
destroyFree(_wavEncoder);
_wavEncoder = null;
}
}
if (_decoderContext)
{
destroyFree(_decoderContext);
_decoderContext = null;
}
if (fileContext !is null)
{
if (fileContext.file !is null)
{
int result = fclose(fileContext.file);
if (result)
throw mallocNew!Exception("Closing of audio file errored");
}
destroyFree(fileContext);
fileContext = null;
}
if (memoryContext !is null)
{
// TODO destroy buffer if any is owned
destroyFree(memoryContext);
memoryContext = null;
}
if (_io !is null)
{
destroyFree(_io);
_io = null;
}
}
/// Returns: File format of this stream.
AudioFileFormat getFormat() nothrow @nogc
{
return _format;
}
/// Returns: Number of channels in this stream. 1 means mono, 2 means stereo...
int getNumChannels() nothrow @nogc
{
return _numChannels;
}
/// Returns: Length of this stream in frames.
/// Note: may return the special value `audiostreamUnknownLength` if the length is unknown.
long getLengthInFrames() nothrow @nogc
{
return _lengthInFrames;
}
/// Returns: Sample-rate of this stream in Hz.
float getSamplerate() nothrow @nogc
{
return _sampleRate;
}
/// Read interleaved float samples in the given buffer `outData`.
///
/// Params:
/// outData Buffer where to put decoded samples. Samples are arranged in an interleaved fashion.
/// Must have room for `frames` x `getNumChannels()` samples.
/// For a stereo file, the output data will contain LRLRLR... repeated `result` times.
///
/// frames The number of multichannel frames to be read.
/// A frame is `getNumChannels()` samples.
///
/// Returns: Number of actually read frames. Multiply by `getNumChannels()` to get the number of read samples.
/// When that number is less than `frames`, it means the stream is done decoding, or that there was a decoding error.
///
/// TODO: once this returned less than `frames`, are we guaranteed we can keep calling that and it returns 0?
int readSamplesFloat(float* outData, int frames) @nogc
{
// If you fail here, you are using this `AudioStream` for decoding:
// - after it has been destroyed,
// - or it was created for encoding instead
assert(_io && _io.read !is null);
final switch(_format)
{
case AudioFileFormat.opus:
{
version(decodeOPUS)
{
try
{
int decoded = 0;
while (decoded < frames)
{
// Is there any sample left in _opusBuffer?
// If not decode some frames.
if (_opusBuffer is null || _opusBuffer.length == 0)
{
_opusBuffer = _opusDecoder.readFrame();
if (_opusBuffer is null)
break;
}
int samplesInBuffer = cast(int) _opusBuffer.length;
int framesInBuffer = samplesInBuffer / _numChannels;
if (framesInBuffer == 0)
break;
// Frames to pull are min( frames left to decode, frames available)
int framesToDecode = frames - decoded;
int framesToUse = framesToDecode < framesInBuffer ? framesToDecode : framesInBuffer;
assert(framesToUse != 0);
int samplesToUse = framesToUse * _numChannels;
int outOffset = decoded*_numChannels;
for (int n = 0; n < samplesToUse; ++n)
{
outData[outOffset + n] = _opusBuffer[n] / 32767.0f;
}
_opusBuffer = _opusBuffer[samplesToUse..$]; // reduce size of intermediate buffer
decoded += framesToUse;
}
return decoded;
}
catch(Exception e)
{
destroyFree(e);
return 0; // decoding might fail, in which case return zero samples
}
}
}
case AudioFileFormat.flac:
{
version(decodeFLAC)
{
assert(_flacDecoder !is null);
int* integerData = cast(int*)outData;
int samples = cast(int) drflac_read_s32(_flacDecoder, frames, integerData);
// "Samples are always output as interleaved signed 32-bit PCM."
// Convert to float with type-punning. Note that this looses some precision.
double factor = 1.0 / int.max;
foreach(n; 0..samples)
{
outData[n] = integerData[n] * factor;
}
return samples / _numChannels;
}
else
{
assert(false); // Impossible
}
}
case AudioFileFormat.ogg:
{
version(decodeOGG)
{
assert(_oggHandle !is null);
return stb_vorbis_get_samples_float_interleaved(_oggHandle, _numChannels, outData, frames * _numChannels);
}
else
{
assert(false); // Impossible
}
}
case AudioFileFormat.mp3:
{
version(decodeMP3)
{
assert(_mp3DecoderNew !is null);
int samplesNeeded = frames * _numChannels;
int result = cast(int) mp3dec_ex_read(_mp3DecoderNew, outData, samplesNeeded);
if (result < 0) // error
return 0;
return result / _numChannels;
}
else
{
assert(false); // Impossible
}
}
case AudioFileFormat.wav:
version(decodeWAV)
{
assert(_wavDecoder !is null);
int readFrames = _wavDecoder.readSamples(outData, frames);
return readFrames;
}
else
{
assert(false); // Impossible
}
case AudioFileFormat.xm:
version(decodeXM)
{
assert(_xmDecoder !is null);
if (xm_get_loop_count(_xmDecoder) >= 1)
return 0; // song is finished
xm_generate_samples(_xmDecoder, outData, frames);
return frames; // Note: XM decoder pads end with zeroes.
}
else
{
assert(false); // Impossible
}
case AudioFileFormat.mod:
version(decodeMOD)
{
if (pocketmod_loop_count(_modDecoder) >= 1)
return 0; // end stream after MOD finishes, looping not supported
assert(_modDecoder !is null);
int bytesReturned = pocketmod_render(_modDecoder, outData, frames * 2 * 4);
assert((bytesReturned % 8) == 0);
return bytesReturned / 8;
}
else
{
assert(false); // Impossible
}
case AudioFileFormat.unknown:
// One shouldn't ever get there, since in this case
// opening has failed.
assert(false);
}
}
///ditto
int readSamplesFloat(float[] outData) @nogc
{
assert( (outData.length % _numChannels) == 0);
return readSamplesFloat(outData.ptr, cast(int)(outData.length / _numChannels) );
}
/// Write interleaved float samples to the stream, from the given buffer `inData[0..frames]`.
///
/// Params:
/// inData Buffer of interleaved samples to append to the stream.
/// Must contain `frames` x `getNumChannels()` samples.
/// For a stereo file, `inData` contains LRLRLR... repeated `frames` times.
///
/// frames The number of frames to append to the stream.
/// A frame is `getNumChannels()` samples.
///
/// Returns: Number of actually written frames. Multiply by `getNumChannels()` to get the number of written samples.
/// When that number is less than `frames`, it means the stream had a write error.
int writeSamplesFloat(float* inData, int frames) nothrow @nogc
{
// If you fail here, you are using this `AudioStream` for encoding:
// - after it has been destroyed,
// - or after encoding has been finalized with
// - or it was created for encoding instead
assert(_io && _io.write !is null);
final switch(_format)
{
case AudioFileFormat.mp3:
case AudioFileFormat.flac:
case AudioFileFormat.ogg:
case AudioFileFormat.opus:
case AudioFileFormat.mod:
case AudioFileFormat.xm:
case AudioFileFormat.unknown:
{
assert(false); // Shouldn't have arrived here, such encoding aren't supported.
}
case AudioFileFormat.wav:
{
version(encodeWAV)
{
return _wavEncoder.writeSamples(inData, frames);
}
else
{
assert(false, "no support for WAV encoding");
}
}
}
}
///ditto
int writeSamplesFloat(float[] inData) nothrow @nogc
{
assert( (inData.length % _numChannels) == 0);
return writeSamplesFloat(inData.ptr, cast(int)(inData.length / _numChannels));
}
/// Seeking. Subsequent reads start from multi-channel frame index `frames`.
/// Only available for input streams.
/// Formats that support seeking: WAV, MP3, OGG, FLAC.
bool seekPosition(int frame)
{
assert(_io && (_io.read !is null) );
final switch(_format) with (AudioFileFormat)
{
case mp3:
version(decodeMP3)
return (mp3dec_ex_seek(_mp3DecoderNew, frame * _numChannels) == 0);
else
assert(false);
case flac:
version(decodeFLAC)
return drflac__seek_to_sample__brute_force (_flacDecoder, frame * _numChannels);
else
assert(false);
case ogg:
version(decodeOGG)
{
return stb_vorbis_seek(_oggHandle, frame) == 1;
}
else
assert(false);
case opus:
version(decodeOPUS)
{
// Note: drflac seeks 1sec too early for some reason.
// This isn't sample accurate, rather 64ms accurate.
long timeInMs = 1000 + cast(long)( 1000.0 * frame / _sampleRate);
_opusDecoder.seek(timeInMs);
return true;
}
else
assert(false);
case mod:
case xm:
return false; // NOT IMPLEMENTED
case wav:
version(decodeWAV)
return _wavDecoder.seekPosition(frame);
else
assert(false);
case unknown:
assert(false);
}
}
/// Call `fflush()` on written samples, if any.
/// It is only useful for streamable output formats, that may want to flush things to disk.
void flush() nothrow @nogc
{
assert( _io && (_io.write !is null) );
_io.flush(userData);
}
/// Finalize encoding. After finalization, further writes are not possible anymore
/// however the stream is considered complete and valid for storage.
void finalizeEncoding() @nogc
{
// If you crash here, it's because `finalizeEncoding` has been called twice.
assert( _io && (_io.write !is null) );
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case mod:
case xm:
assert(false); // unsupported output encoding
case wav:
{
_wavEncoder.finalizeEncoding();
break;
}
case unknown:
assert(false);
}
_io.write = null; // prevents further encodings
}
// Finalize encoding and get internal buffer.
// This can be called multiple times, in which cases the stream is finalized only the first time.
const(ubyte)[] finalizeAndGetEncodedResult() @nogc
{
// only callable while appending, else it's a programming error
assert( (memoryContext !is null) && ( memoryContext.bufferCanGrow ) );
finalizeEncodingIfNeeded();
return memoryContext.buffer[0..memoryContext.size];
}
private:
IOCallbacks* _io;
// This type of context is a closure to remember where the data is.
void* userData; // is equal to either fileContext or memoryContext
FileContext* fileContext;
MemoryContext* memoryContext;
// This type of context is a closure to remember where _io and user Data is.
DecoderContext* _decoderContext;
AudioFileFormat _format;
float _sampleRate;
int _numChannels;
long _lengthInFrames;
// Decoders
version(decodeMP3)
{
mp3dec_ex_t* _mp3DecoderNew; // allocated on heap since it's a 16kb object
mp3dec_io_t* _mp3io;
}
version(decodeFLAC)
{
drflac* _flacDecoder;
}
version(decodeOGG)
{
ubyte[] _oggBuffer; // all allocations from the ogg decoder
stb_vorbis* _oggHandle;
}
version(decodeWAV)
{
WAVDecoder _wavDecoder;
}
version(decodeMOD)
{
pocketmod_context* _modDecoder = null;
ubyte[] _modContent = null; // whole buffer, copied
}
version(decodeXM)
{
xm_context_t* _xmDecoder = null;
ubyte* _xmContent = null;
}
version(decodeOPUS)
{
OpusFile _opusDecoder;
short[] _opusBuffer;
}
// Encoder
version(encodeWAV)
{
WAVEncoder _wavEncoder;
}
bool isOpenedForWriting() nothrow @nogc
{
// Note:
// * when opened for reading, I/O operations given are: seek/tell/getFileLength/read.
// * when opened for writing, I/O operations given are: seek/tell/write/flush.
return (_io !is null) && (_io.read is null);
}
void startDecoding() @nogc
{
// Create a decoder context
_decoderContext = mallocNew!DecoderContext;
_decoderContext.userDataIO = userData;
_decoderContext.callbacks = _io;
version(decodeOPUS)
{
try
{
_opusDecoder = opusOpen(_io, userData);
assert(_opusDecoder !is null);
_format = AudioFileFormat.opus;
_sampleRate = _opusDecoder.rate; // Note: Opus file are always 48Khz
_numChannels = _opusDecoder.channels();
_lengthInFrames = _opusDecoder.smpduration();
return;
}
catch(Exception e)
{
destroyFree(e);
}
_opusDecoder = null;
}
version(decodeFLAC)
{
_io.seek(0, false, userData);
// Is it a FLAC?
{
drflac_read_proc onRead = &flac_read;
drflac_seek_proc onSeek = &flac_seek;
void* pUserData = _decoderContext;
_flacDecoder = drflac_open (onRead, onSeek, _decoderContext);
if (_flacDecoder !is null)
{
_format = AudioFileFormat.flac;
_sampleRate = _flacDecoder.sampleRate;
_numChannels = _flacDecoder.channels;
_lengthInFrames = _flacDecoder.totalSampleCount / _numChannels;
return;
}
}
}
version(decodeWAV)
{
// Check if it's a WAV.
_io.seek(0, false, userData);
try
{
_wavDecoder = mallocNew!WAVDecoder(_io, userData);
_wavDecoder.scan();
// WAV detected
_format = AudioFileFormat.wav;
_sampleRate = _wavDecoder._sampleRate;
_numChannels = _wavDecoder._channels;
_lengthInFrames = _wavDecoder._lengthInFrames;
return;
}
catch(Exception e)
{
// not a WAV
destroyFree(e);
}
destroyFree(_wavDecoder);
_wavDecoder = null;
}
version(decodeOGG)
{
_io.seek(0, false, userData);
// Is it an OGG?
{
//"In my test files the maximal-size usage is ~150KB", so let's take a bit more
_oggBuffer.reallocBuffer(200 * 1024);
stb_vorbis_alloc alloc;
alloc.alloc_buffer = cast(ubyte*)(_oggBuffer.ptr);
alloc.alloc_buffer_length_in_bytes = cast(int)(_oggBuffer.length);
int error;
_oggHandle = stb_vorbis_open_file(_io, userData, &error, &alloc);
if (error == VORBIS__no_error)
{
_format = AudioFileFormat.ogg;
_sampleRate = _oggHandle.sample_rate;
_numChannels = _oggHandle.channels;
_lengthInFrames = stb_vorbis_stream_length_in_samples(_oggHandle);
return;
}
else
{
_oggHandle = null;
}
}
}
version(decodeMP3)
{
// Check if it's a MP3.
{
_io.seek(0, false, userData);
ubyte* scratchBuffer = cast(ubyte*) malloc(MINIMP3_BUF_SIZE*2);
scope(exit) free(scratchBuffer);
_mp3io = cast(mp3dec_io_t*) malloc(mp3dec_io_t.sizeof);
_mp3io.read = &mp3_io_read;
_mp3io.read_data = _decoderContext;
_mp3io.seek = &mp3_io_seek;
_mp3io.seek_data = _decoderContext;
if ( mp3dec_detect_cb(_mp3io, scratchBuffer, MINIMP3_BUF_SIZE*2) == 0 )
{
// This is a MP3. Try to open a stream.
// Allocate a mp3dec_ex_t object
_mp3DecoderNew = cast(mp3dec_ex_t*) malloc(mp3dec_ex_t.sizeof);
int result = mp3dec_ex_open_cb(_mp3DecoderNew, _mp3io, MP3D_SEEK_TO_SAMPLE);
if (0 == result)
{
// MP3 detected
// but it seems we need to iterate all frames to know the length...
_format = AudioFileFormat.mp3;
_sampleRate = _mp3DecoderNew.info.hz;
_numChannels = _mp3DecoderNew.info.channels;
_lengthInFrames = _mp3DecoderNew.samples / _numChannels;
return;
}
else
{
free(_mp3DecoderNew);
_mp3DecoderNew = null;
free(_mp3io);
_mp3io = null;
}
}
}
}
version(decodeXM)
{
{
// we need the first 60 bytes to check if XM
char[60] xmHeader;
int bytes;
_io.seek(0, false, userData);
long lenBytes = _io.getFileLength(userData);
if (lenBytes < 60)
goto not_a_xm;
bytes = _io.read(xmHeader.ptr, 60, userData);
if (bytes != 60)
goto not_a_xm;
if (0 != xm_check_sanity_preload(xmHeader.ptr, 60))
goto not_a_xm;
_xmContent = cast(ubyte*) malloc(cast(int)lenBytes);
_io.seek(0, false, userData);
bytes = _io.read(_xmContent, cast(int)lenBytes, userData);
if (bytes != cast(int)lenBytes)
goto not_a_xm;
if (0 == xm_create_context_safe(&_xmDecoder, cast(const(char)*)_xmContent, cast(size_t)lenBytes, 44100))
{
assert(_xmDecoder !is null);
xm_set_max_loop_count(_xmDecoder, 1);
_format = AudioFileFormat.xm;
_sampleRate = 44100.0f;
_numChannels = 2;
_lengthInFrames = audiostreamUnknownLength;
return;
}
not_a_xm:
assert(_xmDecoder == null);
free(_xmContent);
_xmContent = null;
}
}
version(decodeMOD)
{
{
// we need either the first 1084 or 600 bytes if available
_io.seek(0, false, userData);
long lenBytes = _io.getFileLength(userData);
if (lenBytes >= 600)
{
int headerBytes = lenBytes > 1084 ? 1084 : cast(int)lenBytes;
ubyte[1084] header;
int bytes = _io.read(header.ptr, headerBytes, userData);
if (_pocketmod_ident(null, header.ptr, bytes))
{
// This is a MOD, allocate a proper context, and read the whole file.
_modDecoder = cast(pocketmod_context*) malloc(pocketmod_context.sizeof);
// Read whole .mod in a buffer, since the decoder work all from memory
_io.seek(0, false, userData);
_modContent.reallocBuffer(cast(size_t)lenBytes);
bytes = _io.read(_modContent.ptr, cast(int)lenBytes, userData);
if (pocketmod_init(_modDecoder, _modContent.ptr, bytes, 44100))
{
_format = AudioFileFormat.mod;
_sampleRate = 44100.0f;
_numChannels = 2;
_lengthInFrames = audiostreamUnknownLength;
return;
}
}