/
stream.d
1928 lines (1690 loc) · 63.8 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 audioformats.io;
import audioformats.internals;
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
}
/// Output sample format.
enum AudioSampleFormat
{
s8, /// Signed 8-bit PCM
s16, /// Signed 16-bit PCM
s24, /// Signed 24-bit PCM
fp32, /// 32-bit floating-point
fp64 /// 64-bit floating-point
}
/// An optional struct, passed when encoding a sound.
struct EncodingOptions
{
/// The desired sample bitdepth to encode with.
AudioSampleFormat sampleFormat = AudioSampleFormat.fp32; // defaults to 32-bit float
/// Enable dither when exporting 8-bit, 16-bit, 24-bit WAV
bool enableDither = true;
}
/// 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 `destroyAudioFormatsException`.
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 `destroyAudioFormatsException`.
///
/// 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 open for writing only.
/// Note: throws a manually allocated exception in case of error. Free it with `destroyAudioFormatsException`.
///
/// 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,
EncodingOptions options = EncodingOptions.init) @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, options);
}
/// Opens an audio stream that writes to a dynamically growable output buffer.
/// This stream will be open 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 `destroyAudioFormatsException`.
///
/// 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,
EncodingOptions options = EncodingOptions.init) @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, options);
}
/// Opens an audio stream that writes to a pre-defined area in memory of `maxLength` bytes.
/// This stream will be open for writing only.
/// Destroy this stream with `closeAudioStream`.
/// Note: throws a manually allocated exception in case of error. Free it with `destroyAudioFormatsException`.
///
/// 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,
EncodingOptions options = EncodingOptions.init) @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, options);
}
~this() @nogc
{
cleanUp();
}
/// Returns: File format of this stream.
AudioFileFormat getFormat() nothrow @nogc
{
return _format;
}
/// 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;
}
/// Returns: `true` if this stream is concerning a tracker module format.
/// This is useful because the seek/tell functions are different.
bool isModule() @nogc
{
final switch(_format) with (AudioFileFormat)
{
case wav:
case mp3:
case flac:
case ogg:
case opus:
return false;
case mod:
case xm:
return true;
case unknown:
assert(false);
}
}
/// Returns: `true` if this stream allows seeking.
/// Note: the particular function to call for seeking depends on whether the stream is a tracker module.
/// See_also: `seekPosition`.
bool canSeek() @nogc
{
final switch(_format) with (AudioFileFormat)
{
case wav:
case mp3:
case flac:
case ogg:
case opus:
return true;
case mod:
case xm:
return true;
case unknown:
assert(false);
}
}
/// Returns: `true` if this stream is currently open for reading (decoding).
/// `false` if the stream has been destroyed, or if it was created for encoding instead.
bool isOpenForReading() nothrow @nogc
{
return (_io !is null) && (_io.read !is null);
}
deprecated("Use isOpenForWriting instead") alias isOpenedForWriting = isOpenForWriting;
/// Returns: `true` if this stream is currently open for writing (encoding).
/// `false` if the stream has been destroyed, finalized with `finalizeEncoding()`,
/// or if it was created for decoding instead.
bool isOpenForWriting() 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);
}
/// 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
{
assert(isOpenForReading());
final switch(_format)
{
case AudioFileFormat.opus:
{
version(decodeOPUS)
{
try
{
// Can't decoder further than end of the stream.
if (_opusPositionFrame + frames > _lengthInFrames)
{
frames = cast(int)(_lengthInFrames - _opusPositionFrame);
}
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;
if (outData !is null) // for seeking, we have the ability in OPUS to call readSamplesFloat with no outData
{
for (int n = 0; n < samplesToUse; ++n)
{
outData[outOffset + n] = _opusBuffer[n] / 32767.0f;
}
}
_opusBuffer = _opusBuffer[samplesToUse..$]; // reduce size of intermediate buffer
decoded += framesToUse;
}
_opusPositionFrame += decoded;
assert(_opusPositionFrame <= _lengthInFrames);
return decoded;
}
catch(AudioFormatsException e)
{
destroyFree(e);
return 0; // decoding might fail, in which case return zero samples
}
}
}
case AudioFileFormat.flac:
{
version(decodeFLAC)
{
assert(_flacDecoder !is null);
if (_flacPositionFrame == _lengthInFrames)
return 0; // internally the decoder might be elsewhere
int* integerData = cast(int*)outData;
int samples = cast(int) drflac_read_s32(_flacDecoder, frames * _numChannels, 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;
}
int framesDecoded = samples / _numChannels;
_flacPositionFrame += framesDecoded;
return framesDecoded;
}
else
{
assert(false); // Impossible
}
}
case AudioFileFormat.ogg:
{
version(decodeOGG)
{
assert(_oggHandle !is null);
int framesRead = stb_vorbis_get_samples_float_interleaved(_oggHandle, _numChannels, outData, frames * _numChannels);
_oggPositionFrame += framesRead;
return framesRead;
}
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!float(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) );
}
/// Read interleaved double 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.
///
/// Note: the only formats to possibly take advantage of double decoding are WAV and FLAC.
///
/// 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 readSamplesDouble(double* outData, int frames) @nogc
{
assert(isOpenForReading());
switch(_format)
{
case AudioFileFormat.wav:
version(decodeWAV)
{
assert(_wavDecoder !is null);
int readFrames = _wavDecoder.readSamples!double(outData, frames);
return readFrames;
}
else
{
assert(false); // Impossible
}
case AudioFileFormat.flac:
{
version(decodeFLAC)
{
assert(_flacDecoder !is null);
if (_flacPositionFrame == _lengthInFrames)
return 0; // internally the decoder might be elsewhere
// use second half of the output buffer as temporary integer decoding area
int* integerData = (cast(int*)outData) + frames;
int samples = cast(int) drflac_read_s32(_flacDecoder, frames, integerData);
// "Samples are always output as interleaved signed 32-bit PCM."
// Converting to double doesn't loose mantissa, unlike float.
double factor = 1.0 / int.max;
foreach(n; 0..samples)
{
outData[n] = integerData[n] * factor;
}
int framesDecoded = samples / _numChannels;
_flacPositionFrame += framesDecoded;
return framesDecoded;
}
else
{
assert(false); // Impossible
}
}
case AudioFileFormat.unknown:
// One shouldn't ever get there
assert(false);
default:
// Decode to float buffer, and then convert
if (_floatDecodeBuf.length < frames * _numChannels)
_floatDecodeBuf.reallocBuffer(frames * _numChannels);
int read = readSamplesFloat(_floatDecodeBuf.ptr, frames);
for (int n = 0; n < read * _numChannels; ++n)
outData[n] = _floatDecodeBuf[n];
return read;
}
}
///ditto
int readSamplesDouble(double[] outData) @nogc
{
assert( (outData.length % _numChannels) == 0);
return readSamplesDouble(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(const(float)* inData, int frames) nothrow @nogc
{
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(const(float)[] inData) nothrow @nogc
{
assert( (inData.length % _numChannels) == 0);
return writeSamplesFloat(inData.ptr, cast(int)(inData.length / _numChannels));
}
/// Write interleaved double 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.
///
/// Note: this only does something if the output format is WAV and was setup for 64-bit output.
///
/// 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 writeSamplesDouble(const(double)* inData, int frames) nothrow @nogc
{
assert (_io && _io.write !is null);
switch (_format)
{
case AudioFileFormat.unknown:
// One shouldn't ever get there
assert(false);
case AudioFileFormat.wav:
{
version(encodeWAV)
{
return _wavEncoder.writeSamples(inData, frames);
}
else
{
assert(false, "no support for WAV encoding");
}
}
default:
// Decode to float buffer, and then convert
if (_floatDecodeBuf.length < frames * _numChannels)
_floatDecodeBuf.reallocBuffer(frames * _numChannels);
for (int n = 0; n < frames * _numChannels; ++n)
_floatDecodeBuf[n] = inData[n];
return writeSamplesFloat(_floatDecodeBuf.ptr, frames);
}
}
///ditto
int writeSamplesDouble(const(double)[] inData) nothrow @nogc
{
assert( (inData.length % _numChannels) == 0);
return writeSamplesDouble(inData.ptr, cast(int)(inData.length / _numChannels));
}
// -----------------------------------------------------------------------------------------------------
// <module functions>
// Those tracker module-specific functions below can only be called when `isModule()` returns `true`.
// Additionally, seeking function can only be called if `canSeek()` also returns `true`.
// -----------------------------------------------------------------------------------------------------
/// Length. Returns the amount of patterns in the module
/// Formats that support this: MOD, XM.
int countModulePatterns()
{
assert(isOpenForReading() && isModule());
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case wav:
case unknown:
assert(false);
case mod:
return _modDecoder.num_patterns;
case xm:
return xm_get_number_of_patterns(_xmDecoder);
}
}
/// Length. Returns the amount of PLAYED patterns in the module
/// Formats that support this: MOD, XM.
int getModuleLength()
{
assert(isOpenForReading() && isModule());
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case wav:
case unknown:
assert(false);
case mod:
return _modDecoder.length;
case xm:
return xm_get_module_length(_xmDecoder);
}
}
/// Tell. Returns amount of rows in a pattern.
/// Formats that support this: MOD, XM.
/// Returns: -1 on error. Else, number of patterns.
int rowsInPattern(int pattern)
{
assert(isOpenForReading() && isModule());
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case wav:
case unknown:
assert(false);
case mod:
// According to http://lclevy.free.fr/mo3/mod.txt
// there's 64 lines (aka rows) per pattern.
// TODO: error checking, make sure no out of bounds happens.
return 64;
case xm:
{
int numPatterns = xm_get_number_of_patterns(_xmDecoder);
if (pattern < 0 || pattern >= numPatterns)
return -1;
return xm_get_number_of_rows(_xmDecoder, cast(ushort) pattern);
}
}
}
/// Tell. Returns the current playing pattern id
/// Formats that support this: MOD, XM
int tellModulePattern()
{
assert(isOpenForReading() && isModule());
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case wav:
case unknown:
assert(false);
case mod:
return _modDecoder.pattern;
case xm:
return _xmDecoder.current_table_index;
}
}
/// Tell. Returns the current playing row id
/// Formats that support this: MOD, XM
int tellModuleRow()
{
assert(isOpenForReading() && isModule());
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case wav:
case unknown:
assert(false);
case mod:
return _modDecoder.line;
case xm:
return _xmDecoder.current_row;
}
}
/// Playback info. Returns the amount of multi-channel frames remaining in the current playing pattern.
/// Formats that support this: MOD
int framesRemainingInPattern()
{
assert(isOpenForReading() && isModule());
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case wav:
case unknown:
assert(false);
case mod:
return pocketmod_count_remaining_samples(_modDecoder);
case xm:
return xm_count_remaining_samples(_xmDecoder);
}
}
/// Seeking. Subsequent reads start from pattern + row, 0 index
/// Only available for input streams.
/// Formats that support seeking per pattern/row: MOD, XM
/// Returns: `true` in case of success.
bool seekPosition(int pattern, int row)
{
assert(isOpenForReading() && isModule() && canSeek());
final switch(_format) with (AudioFileFormat)
{
case mp3:
case flac:
case ogg:
case opus:
case wav:
case unknown:
assert(false);
case mod:
// NOTE: This is untested.
return pocketmod_seek(_modDecoder, pattern, row, 0);
case xm:
return xm_seek(_xmDecoder, pattern, row, 0);
}
}
// -----------------------------------------------------------------------------------------------------
// </module functions>
// -----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------
// <non-module functions>
// Those functions below can't be used for tracker module formats, because there is no real concept of
// absolute position in these formats.
// -----------------------------------------------------------------------------------------------------
/// Seeking. Subsequent reads start from multi-channel frame index `frames`.
/// Only available for input streams, for streams whose `canSeek()` returns `true`.
/// Warning: `seekPosition(lengthInFrames)` is Undefined Behaviour for now. (it works in MP3
bool seekPosition(int frame)
{
assert(isOpenForReading() && !isModule() && canSeek()); // seeking doesn't have the same sense with modules.
final switch(_format) with (AudioFileFormat)
{
case mp3:
version(decodeMP3)
{
assert(_lengthInFrames != audiostreamUnknownLength);
if (frame < 0 || frame > _lengthInFrames)
return false;
return (mp3dec_ex_seek(_mp3DecoderNew, frame * _numChannels) == 0);
}
else
assert(false);
case flac:
version(decodeFLAC)
{
if (frame < 0 || frame > _lengthInFrames)
return false;
if (_flacPositionFrame == frame)
return true;
// Note: seeking + FLAC is a dark side of that library.
// I'm not entirely sure we are handling all cases perfectly.
// But weren't able to fault the current situation.
// Would probably be easier to re-tanslate drflac if a problem arised.
bool success = drflac_seek_to_sample(_flacDecoder, frame * _numChannels);
if (success || frame == _lengthInFrames) // always succeed if end of stream is requested
_flacPositionFrame = frame;
return success;
}
else
assert(false);
case ogg:
version(decodeOGG)
{
if (_oggPositionFrame == frame)
return true;
if (_oggPositionFrame == _lengthInFrames)
{
// When the OGG stream is finished, and an earlier position is detected,
// the OGG decoder has to be restarted
assert(_oggHandle !is null);
cleanUpCodecs();
assert(_oggHandle is null);
startDecoding();
assert(_oggHandle !is null);
}
if (stb_vorbis_seek(_oggHandle, frame) == 1)
{
_oggPositionFrame = frame;
return true;
}
else
return false;
}
else
assert(false);
case opus:
version(decodeOPUS)
{
if (frame < 0 || frame > _lengthInFrames)
return false;
long where = _opusDecoder.ogg.seekPCM(frame);
_opusPositionFrame = where;
int toSkip = cast(int)(frame - where);
// skip remaining samples for sample-accurate seeking
// Note: this also updates _opusPositionFrame
int skipped = readSamplesFloat(null, cast(int) toSkip);
// TODO: if decoding `toSkip` samples failed, restore previous state?
return skipped == toSkip;
}
else
assert(false);
case mod:
case xm:
assert(false);
case wav:
version(decodeWAV)
return _wavDecoder.seekPosition(frame);