forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vorbis.d
5157 lines (4615 loc) · 182 KB
/
vorbis.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
// Ogg Vorbis audio decoder - v1.10 - public domain
// http://nothings.org/stb_vorbis/
//
// Original version written by Sean Barrett in 2007.
//
// Originally sponsored by RAD Game Tools. Seeking sponsored
// by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software,
// Aras Pranckevicius, and Sean Barrett.
//
// LICENSE
//
// See end of file for license information.
//
// Limitations:
//
// - floor 0 not supported (used in old ogg vorbis files pre-2004)
// - lossless sample-truncation at beginning ignored
// - cannot concatenate multiple vorbis streams
// - sample positions are 32-bit, limiting seekable 192Khz
// files to around 6 hours (Ogg supports 64-bit)
//
// Feature contributors:
// Dougall Johnson (sample-exact seeking)
//
// Bugfix/warning contributors:
// Terje Mathisen Niklas Frykholm Andy Hill
// Casey Muratori John Bolton Gargaj
// Laurent Gomila Marc LeBlanc Ronny Chevalier
// Bernhard Wodo Evan Balster alxprd@github
// Tom Beaumont Ingo Leitgeb Nicolas Guillemot
// Phillip Bennefall Rohit Thiago Goulart
// manxorist@github saga musix
//
// Partial history:
// 1.10 - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory
// 1.09 - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version
// 1.08 - 2016/04/02 - fixed multiple warnings; fix setup memory leaks;
// avoid discarding last frame of audio data
// 1.07 - 2015/01/16 - fixed some warnings, fix mingw, const-correct API
// some more crash fixes when out of memory or with corrupt files
// 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson)
// some crash fixes when out of memory or with corrupt files
// fix some inappropriately signed shifts
// 1.05 - 2015/04/19 - don't define __forceinline if it's redundant
// 1.04 - 2014/08/27 - fix missing const-correct case in API
// 1.03 - 2014/08/07 - warning fixes
// 1.02 - 2014/07/09 - declare qsort comparison as explicitly _cdecl in Windows
// 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float (interleaved was correct)
// 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
// (API change) report sample rate for decode-full-file funcs
// 0.99996 - - bracket #include <malloc.h> for macintosh compilation
// 0.99995 - - avoid alias-optimization issue in float-to-int conversion
//
// See end of file for full version history.
// D translation by Ketmar // Invisible Vector
// stolen by adam and module renamed.
/++
Port of stb_vorbis to D. Provides .ogg audio file reading capabilities. See [arsd.simpleaudio] for code that can use this to actually load and play the file.
+/
module arsd.vorbis;
import core.stdc.stdio : FILE;
version(Windows)
extern(C) int lrintf(float f) { return cast(int) f; }
nothrow /*@trusted*/:
@nogc { // code block, as c macro helper is not @nogc; yet it's CTFE-only
// import it here, as druntime has no `@nogc` on it (for a reason)
private extern(C) void qsort (void* base, size_t nmemb, size_t size, int function(const scope void*, const scope void*) compar);
//////////////////////////////////////////////////////////////////////////////
//
// HEADER BEGINS HERE
//
/////////// THREAD SAFETY
// Individual VorbisDecoder handles are not thread-safe; you cannot decode from
// them from multiple threads at the same time. However, you can have multiple
// VorbisDecoder handles and decode from them independently in multiple thrads.
/////////// MEMORY ALLOCATION
// normally stb_vorbis uses malloc() to allocate memory at startup,
// and alloca() to allocate temporary memory during a frame on the
// stack. (Memory consumption will depend on the amount of setup
// data in the file and how you set the compile flags for speed
// vs. size. In my test files the maximal-size usage is ~150KB.)
//
// You can modify the wrapper functions in the source (setup_malloc,
// setup_temp_malloc, temp_malloc) to change this behavior, or you
// can use a simpler allocation model: you pass in a buffer from
// which stb_vorbis will allocate _all_ its memory (including the
// temp memory). "open" may fail with a VORBIS_outofmem if you
// do not pass in enough data; there is no way to determine how
// much you do need except to succeed (at which point you can
// query get_info to find the exact amount required. yes I know
// this is lame).
//
// If you pass in a non-null buffer of the type below, allocation
// will occur from it as described above. Otherwise just pass null
// to use malloc()/alloca()
public struct stb_vorbis_alloc {
ubyte* alloc_buffer;
int alloc_buffer_length_in_bytes;
}
/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
/*
public struct stb_vorbis_info {
uint sample_rate;
int channels;
uint setup_memory_required;
uint setup_temp_memory_required;
uint temp_memory_required;
int max_frame_size;
}
*/
/* ************************************************************************** *
// get general information about the file
stb_vorbis_info stb_vorbis_get_info (VorbisDecoder f);
// get the last error detected (clears it, too)
int stb_vorbis_get_error (VorbisDecoder f);
// close an ogg vorbis file and free all memory in use
void stb_vorbis_close (VorbisDecoder f);
// this function returns the offset (in samples) from the beginning of the
// file that will be returned by the next decode, if it is known, or -1
// otherwise. after a flush_pushdata() call, this may take a while before
// it becomes valid again.
// NOT WORKING YET after a seek with PULLDATA API
int stb_vorbis_get_sample_offset (VorbisDecoder f);
// returns the current seek point within the file, or offset from the beginning
// of the memory buffer. In pushdata mode it returns 0.
uint stb_vorbis_get_file_offset (VorbisDecoder f);
/////////// PUSHDATA API
// this API allows you to get blocks of data from any source and hand
// them to stb_vorbis. you have to buffer them; stb_vorbis will tell
// you how much it used, and you have to give it the rest next time;
// and stb_vorbis may not have enough data to work with and you will
// need to give it the same data again PLUS more. Note that the Vorbis
// specification does not bound the size of an individual frame.
// create a vorbis decoder by passing in the initial data block containing
// the ogg&vorbis headers (you don't need to do parse them, just provide
// the first N bytes of the file--you're told if it's not enough, see below)
// on success, returns an VorbisDecoder, does not set error, returns the amount of
// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
// on failure, returns null on error and sets *error, does not change *datablock_memory_consumed
// if returns null and *error is VORBIS_need_more_data, then the input block was
// incomplete and you need to pass in a larger block from the start of the file
VorbisDecoder stb_vorbis_open_pushdata (
ubyte* datablock, int datablock_length_in_bytes,
int* datablock_memory_consumed_in_bytes,
int* error,
stb_vorbis_alloc* alloc_buffer
);
// decode a frame of audio sample data if possible from the passed-in data block
//
// return value: number of bytes we used from datablock
//
// possible cases:
// 0 bytes used, 0 samples output (need more data)
// N bytes used, 0 samples output (resynching the stream, keep going)
// N bytes used, M samples output (one frame of data)
// note that after opening a file, you will ALWAYS get one N-bytes, 0-sample
// frame, because Vorbis always "discards" the first frame.
//
// Note that on resynch, stb_vorbis will rarely consume all of the buffer,
// instead only datablock_length_in_bytes-3 or less. This is because it wants
// to avoid missing parts of a page header if they cross a datablock boundary,
// without writing state-machiney code to record a partial detection.
//
// The number of channels returned are stored in *channels (which can be
// null--it is always the same as the number of channels reported by
// get_info). *output will contain an array of float* buffers, one per
// channel. In other words, (*output)[0][0] contains the first sample from
// the first channel, and (*output)[1][0] contains the first sample from
// the second channel.
int stb_vorbis_decode_frame_pushdata (
VorbisDecoder f, ubyte* datablock, int datablock_length_in_bytes,
int* channels, // place to write number of float * buffers
float*** output, // place to write float ** array of float * buffers
int* samples // place to write number of output samples
);
// inform stb_vorbis that your next datablock will not be contiguous with
// previous ones (e.g. you've seeked in the data); future attempts to decode
// frames will cause stb_vorbis to resynchronize (as noted above), and
// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
// will begin decoding the _next_ frame.
//
// if you want to seek using pushdata, you need to seek in your file, then
// call stb_vorbis_flush_pushdata(), then start calling decoding, then once
// decoding is returning you data, call stb_vorbis_get_sample_offset, and
// if you don't like the result, seek your file again and repeat.
void stb_vorbis_flush_pushdata (VorbisDecoder f);
////////// PULLING INPUT API
// This API assumes stb_vorbis is allowed to pull data from a source--
// either a block of memory containing the _entire_ vorbis stream, or a
// FILE* that you or it create, or possibly some other reading mechanism
// if you go modify the source to replace the FILE* case with some kind
// of callback to your code. (But if you don't support seeking, you may
// just want to go ahead and use pushdata.)
// decode an entire file and output the data interleaved into a malloc()ed
// buffer stored in *output. The return value is the number of samples
// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
// When you're done with it, just free() the pointer returned in *output.
int stb_vorbis_decode_filename (const(char)* filename, int* channels, int* sample_rate, short** output);
int stb_vorbis_decode_memory (const(ubyte)* mem, int len, int* channels, int* sample_rate, short** output);
// create an ogg vorbis decoder from an ogg vorbis stream in memory (note
// this must be the entire stream!). on failure, returns null and sets *error
VorbisDecoder stb_vorbis_open_memory (const(ubyte)* data, int len, int* error, stb_vorbis_alloc* alloc_buffer);
// create an ogg vorbis decoder from a filename via fopen(). on failure,
// returns null and sets *error (possibly to VORBIS_file_open_failure).
VorbisDecoder stb_vorbis_open_filename (const(char)* filename, int* error, stb_vorbis_alloc* alloc_buffer);
// create an ogg vorbis decoder from an open FILE*, looking for a stream at
// the _current_ seek point (ftell). on failure, returns null and sets *error.
// note that stb_vorbis must "own" this stream; if you seek it in between
// calls to stb_vorbis, it will become confused. Morever, if you attempt to
// perform stb_vorbis_seek_*() operations on this file, it will assume it
// owns the _entire_ rest of the file after the start point. Use the next
// function, stb_vorbis_open_file_section(), to limit it.
VorbisDecoder stb_vorbis_open_file (FILE* f, int close_handle_on_close, int* error, stb_vorbis_alloc* alloc_buffer);
// create an ogg vorbis decoder from an open FILE*, looking for a stream at
// the _current_ seek point (ftell); the stream will be of length 'len' bytes.
// on failure, returns null and sets *error. note that stb_vorbis must "own"
// this stream; if you seek it in between calls to stb_vorbis, it will become
// confused.
VorbisDecoder stb_vorbis_open_file_section (FILE* f, int close_handle_on_close, int* error, stb_vorbis_alloc* alloc_buffer, uint len);
// these functions seek in the Vorbis file to (approximately) 'sample_number'.
// after calling seek_frame(), the next call to get_frame_*() will include
// the specified sample. after calling stb_vorbis_seek(), the next call to
// stb_vorbis_get_samples_* will start with the specified sample. If you
// do not need to seek to EXACTLY the target sample when using get_samples_*,
// you can also use seek_frame().
int stb_vorbis_seek_frame (VorbisDecoder f, uint sample_number);
int stb_vorbis_seek (VorbisDecoder f, uint sample_number);
// this function is equivalent to stb_vorbis_seek(f, 0)
int stb_vorbis_seek_start (VorbisDecoder f);
// these functions return the total length of the vorbis stream
uint stb_vorbis_stream_length_in_samples (VorbisDecoder f);
float stb_vorbis_stream_length_in_seconds (VorbisDecoder f);
// decode the next frame and return the number of samples. the number of
// channels returned are stored in *channels (which can be null--it is always
// the same as the number of channels reported by get_info). *output will
// contain an array of float* buffers, one per channel. These outputs will
// be overwritten on the next call to stb_vorbis_get_frame_*.
//
// You generally should not intermix calls to stb_vorbis_get_frame_*()
// and stb_vorbis_get_samples_*(), since the latter calls the former.
int stb_vorbis_get_frame_float (VorbisDecoder f, int* channels, float*** output);
// decode the next frame and return the number of *samples* per channel.
// Note that for interleaved data, you pass in the number of shorts (the
// size of your array), but the return value is the number of samples per
// channel, not the total number of samples.
//
// The data is coerced to the number of channels you request according to the
// channel coercion rules (see below). You must pass in the size of your
// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
// The maximum buffer size needed can be gotten from get_info(); however,
// the Vorbis I specification implies an absolute maximum of 4096 samples
// per channel.
int stb_vorbis_get_frame_short_interleaved (VorbisDecoder f, int num_c, short* buffer, int num_shorts);
int stb_vorbis_get_frame_short (VorbisDecoder f, int num_c, short** buffer, int num_samples);
// Channel coercion rules:
// Let M be the number of channels requested, and N the number of channels present,
// and Cn be the nth channel; let stereo L be the sum of all L and center channels,
// and stereo R be the sum of all R and center channels (channel assignment from the
// vorbis spec).
// M N output
// 1 k sum(Ck) for all k
// 2 * stereo L, stereo R
// k l k > l, the first l channels, then 0s
// k l k <= l, the first k channels
// Note that this is not _good_ surround etc. mixing at all! It's just so
// you get something useful.
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
// Returns the number of samples stored per channel; it may be less than requested
// at the end of the file. If there are no more samples in the file, returns 0.
int stb_vorbis_get_samples_float_interleaved (VorbisDecoder f, int channels, float* buffer, int num_floats);
int stb_vorbis_get_samples_float (VorbisDecoder f, int channels, float** buffer, int num_samples);
// gets num_samples samples, not necessarily on a frame boundary--this requires
// buffering so you have to supply the buffers. Applies the coercion rules above
// to produce 'channels' channels. Returns the number of samples stored per channel;
// it may be less than requested at the end of the file. If there are no more
// samples in the file, returns 0.
int stb_vorbis_get_samples_short_interleaved (VorbisDecoder f, int channels, short* buffer, int num_shorts);
int stb_vorbis_get_samples_short (VorbisDecoder f, int channels, short** buffer, int num_samples);
*/
//////// ERROR CODES
public enum STBVorbisError {
no_error,
need_more_data = 1, // not a real error
invalid_api_mixing, // can't mix API modes
outofmem, // not enough memory
feature_not_supported, // uses floor 0
too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
file_open_failure, // fopen() failed
seek_without_length, // can't seek in unknown-length file
unexpected_eof = 10, // file is truncated?
seek_invalid, // seek past EOF
// decoding errors (corrupt/invalid stream) -- you probably
// don't care about the exact details of these
// vorbis errors:
invalid_setup = 20,
invalid_stream,
// ogg errors:
missing_capture_pattern = 30,
invalid_stream_structure_version,
continued_packet_flag_invalid,
incorrect_stream_serial_number,
invalid_first_page,
bad_packet_type,
cant_find_last_page,
seek_failed,
}
//
// HEADER ENDS HERE
//
//////////////////////////////////////////////////////////////////////////////
// global configuration settings (e.g. set these in the project/makefile),
// or just set them in this file at the top (although ideally the first few
// should be visible when the header file is compiled too, although it's not
// crucial)
// STB_VORBIS_NO_INTEGER_CONVERSION
// does not compile the code for converting audio sample data from
// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
//version = STB_VORBIS_NO_INTEGER_CONVERSION;
// STB_VORBIS_NO_FAST_SCALED_FLOAT
// does not use a fast float-to-int trick to accelerate float-to-int on
// most platforms which requires endianness be defined correctly.
//version = STB_VORBIS_NO_FAST_SCALED_FLOAT;
// STB_VORBIS_MAX_CHANNELS [number]
// globally define this to the maximum number of channels you need.
// The spec does not put a restriction on channels except that
// the count is stored in a byte, so 255 is the hard limit.
// Reducing this saves about 16 bytes per value, so using 16 saves
// (255-16)*16 or around 4KB. Plus anything other memory usage
// I forgot to account for. Can probably go as low as 8 (7.1 audio),
// 6 (5.1 audio), or 2 (stereo only).
enum STB_VORBIS_MAX_CHANNELS = 16; // enough for anyone?
// STB_VORBIS_PUSHDATA_CRC_COUNT [number]
// after a flush_pushdata(), stb_vorbis begins scanning for the
// next valid page, without backtracking. when it finds something
// that looks like a page, it streams through it and verifies its
// CRC32. Should that validation fail, it keeps scanning. But it's
// possible that _while_ streaming through to check the CRC32 of
// one candidate page, it sees another candidate page. This #define
// determines how many "overlapping" candidate pages it can search
// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
// garbage pages could be as big as 64KB, but probably average ~16KB.
// So don't hose ourselves by scanning an apparent 64KB page and
// missing a ton of real ones in the interim; so minimum of 2
enum STB_VORBIS_PUSHDATA_CRC_COUNT = 4;
// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
// sets the log size of the huffman-acceleration table. Maximum
// supported value is 24. with larger numbers, more decodings are O(1),
// but the table size is larger so worse cache missing, so you'll have
// to probe (and try multiple ogg vorbis files) to find the sweet spot.
enum STB_VORBIS_FAST_HUFFMAN_LENGTH = 10;
// STB_VORBIS_FAST_BINARY_LENGTH [number]
// sets the log size of the binary-search acceleration table. this
// is used in similar fashion to the fast-huffman size to set initial
// parameters for the binary search
// STB_VORBIS_FAST_HUFFMAN_INT
// The fast huffman tables are much more efficient if they can be
// stored as 16-bit results instead of 32-bit results. This restricts
// the codebooks to having only 65535 possible outcomes, though.
// (At least, accelerated by the huffman table.)
//version = STB_VORBIS_FAST_HUFFMAN_INT;
version(STB_VORBIS_FAST_HUFFMAN_INT) {} else version = STB_VORBIS_FAST_HUFFMAN_SHORT;
// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
// back on binary searching for the correct one. This requires storing
// extra tables with the huffman codes in sorted order. Defining this
// symbol trades off space for speed by forcing a linear search in the
// non-fast case, except for "sparse" codebooks.
//version = STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH;
// STB_VORBIS_DIVIDES_IN_RESIDUE
// stb_vorbis precomputes the result of the scalar residue decoding
// that would otherwise require a divide per chunk. you can trade off
// space for time by defining this symbol.
//version = STB_VORBIS_DIVIDES_IN_RESIDUE;
// STB_VORBIS_DIVIDES_IN_CODEBOOK
// vorbis VQ codebooks can be encoded two ways: with every case explicitly
// stored, or with all elements being chosen from a small range of values,
// and all values possible in all elements. By default, stb_vorbis expands
// this latter kind out to look like the former kind for ease of decoding,
// because otherwise an integer divide-per-vector-element is required to
// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
// trade off storage for speed.
//version = STB_VORBIS_DIVIDES_IN_CODEBOOK;
version(STB_VORBIS_CODEBOOK_SHORTS) static assert(0, "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats");
// STB_VORBIS_DIVIDE_TABLE
// this replaces small integer divides in the floor decode loop with
// table lookups. made less than 1% difference, so disabled by default.
//version = STB_VORBIS_DIVIDE_TABLE;
// STB_VORBIS_NO_DEFER_FLOOR
// Normally we only decode the floor without synthesizing the actual
// full curve. We can instead synthesize the curve immediately. This
// requires more memory and is very likely slower, so I don't think
// you'd ever want to do it except for debugging.
//version = STB_VORBIS_NO_DEFER_FLOOR;
//version(STB_VORBIS_CODEBOOK_FLOATS) static assert(0);
// ////////////////////////////////////////////////////////////////////////// //
private:
static assert(STB_VORBIS_MAX_CHANNELS <= 256, "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range");
static assert(STB_VORBIS_FAST_HUFFMAN_LENGTH <= 24, "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range");
enum MAX_BLOCKSIZE_LOG = 13; // from specification
enum MAX_BLOCKSIZE = (1 << MAX_BLOCKSIZE_LOG);
alias codetype = float;
// @NOTE
//
// Some arrays below are tagged "//varies", which means it's actually
// a variable-sized piece of data, but rather than malloc I assume it's
// small enough it's better to just allocate it all together with the
// main thing
//
// Most of the variables are specified with the smallest size I could pack
// them into. It might give better performance to make them all full-sized
// integers. It should be safe to freely rearrange the structures or change
// the sizes larger--nothing relies on silently truncating etc., nor the
// order of variables.
enum FAST_HUFFMAN_TABLE_SIZE = (1<<STB_VORBIS_FAST_HUFFMAN_LENGTH);
enum FAST_HUFFMAN_TABLE_MASK = (FAST_HUFFMAN_TABLE_SIZE-1);
struct Codebook {
int dimensions, entries;
ubyte* codeword_lengths;
float minimum_value;
float delta_value;
ubyte value_bits;
ubyte lookup_type;
ubyte sequence_p;
ubyte sparse;
uint lookup_values;
codetype* multiplicands;
uint *codewords;
version(STB_VORBIS_FAST_HUFFMAN_SHORT) {
short[FAST_HUFFMAN_TABLE_SIZE] fast_huffman;
} else {
int[FAST_HUFFMAN_TABLE_SIZE] fast_huffman;
}
uint* sorted_codewords;
int* sorted_values;
int sorted_entries;
}
struct Floor0 {
ubyte order;
ushort rate;
ushort bark_map_size;
ubyte amplitude_bits;
ubyte amplitude_offset;
ubyte number_of_books;
ubyte[16] book_list; // varies
}
struct Floor1 {
ubyte partitions;
ubyte[32] partition_class_list; // varies
ubyte[16] class_dimensions; // varies
ubyte[16] class_subclasses; // varies
ubyte[16] class_masterbooks; // varies
short[8][16] subclass_books; // varies
ushort[31*8+2] Xlist; // varies
ubyte[31*8+2] sorted_order;
ubyte[2][31*8+2] neighbors;
ubyte floor1_multiplier;
ubyte rangebits;
int values;
}
union Floor {
Floor0 floor0;
Floor1 floor1;
}
struct Residue {
uint begin, end;
uint part_size;
ubyte classifications;
ubyte classbook;
ubyte** classdata;
//int16 (*residue_books)[8];
short[8]* residue_books;
}
struct MappingChannel {
ubyte magnitude;
ubyte angle;
ubyte mux;
}
struct Mapping {
ushort coupling_steps;
MappingChannel* chan;
ubyte submaps;
ubyte[15] submap_floor; // varies
ubyte[15] submap_residue; // varies
}
struct Mode {
ubyte blockflag;
ubyte mapping;
ushort windowtype;
ushort transformtype;
}
struct CRCscan {
uint goal_crc; // expected crc if match
int bytes_left; // bytes left in packet
uint crc_so_far; // running crc
int bytes_done; // bytes processed in _current_ chunk
uint sample_loc; // granule pos encoded in page
}
struct ProbedPage {
uint page_start, page_end;
uint last_decoded_sample;
}
private int error (VorbisDecoder f, STBVorbisError e) {
f.error = e;
if (!f.eof && e != STBVorbisError.need_more_data) {
// import std.stdio; debug writeln(e);
f.error = e; // breakpoint for debugging
}
return 0;
}
// these functions are used for allocating temporary memory
// while decoding. if you can afford the stack space, use
// alloca(); otherwise, provide a temp buffer and it will
// allocate out of those.
uint temp_alloc_save (VorbisDecoder f) nothrow @nogc { static if (__VERSION__ > 2067) pragma(inline, true); return f.alloc.tempSave(f); }
void temp_alloc_restore (VorbisDecoder f, uint p) nothrow @nogc { static if (__VERSION__ > 2067) pragma(inline, true); f.alloc.tempRestore(p, f); }
void temp_free (VorbisDecoder f, void* p) nothrow @nogc {}
/*
T* temp_alloc(T) (VorbisDecoder f, uint count) nothrow @nogc {
auto res = f.alloc.alloc(count*T.sizeof, f);
return cast(T*)res;
}
*/
/+
enum array_size_required(string count, string size) = q{((${count})*((void*).sizeof+(${size})))}.cmacroFixVars!("count", "size")(count, size);
// has to be a mixin, due to `alloca`
template temp_alloc(string size) {
enum temp_alloc = q{(f.alloc.alloc_buffer ? setup_temp_malloc(f, (${size})) : alloca(${size}))}.cmacroFixVars!("size")(size);
}
// has to be a mixin, due to `alloca`
template temp_block_array(string count, string size) {
enum temp_block_array = q{(make_block_array(${tam}, (${count}), (${size})))}
.cmacroFixVars!("count", "size", "tam")(count, size, temp_alloc!(array_size_required!(count, size)));
}
+/
enum array_size_required(string count, string size) = q{((${count})*((void*).sizeof+(${size})))}.cmacroFixVars!("count", "size")(count, size);
template temp_alloc(string size) {
enum temp_alloc = q{alloca(${size})}.cmacroFixVars!("size")(size);
}
template temp_block_array(string count, string size) {
enum temp_block_array = q{(make_block_array(${tam}, (${count}), (${size})))}
.cmacroFixVars!("count", "size", "tam")(count, size, temp_alloc!(array_size_required!(count, size)));
}
/*
T** temp_block_array(T) (VorbisDecoder f, uint count, uint size) {
size *= T.sizeof;
auto mem = f.alloc.alloc(count*(void*).sizeof+size, f);
if (mem !is null) make_block_array(mem, count, size);
return cast(T**)mem;
}
*/
// given a sufficiently large block of memory, make an array of pointers to subblocks of it
private void* make_block_array (void* mem, int count, int size) {
void** p = cast(void**)mem;
char* q = cast(char*)(p+count);
foreach (immutable i; 0..count) {
p[i] = q;
q += size;
}
return p;
}
private T* setup_malloc(T) (VorbisDecoder f, uint sz) {
sz *= T.sizeof;
/*
f.setup_memory_required += sz;
if (f.alloc.alloc_buffer) {
void* p = cast(char*)f.alloc.alloc_buffer+f.setup_offset;
if (f.setup_offset+sz > f.temp_offset) return null;
f.setup_offset += sz;
return cast(T*)p;
}
*/
auto res = f.alloc.alloc(sz+8, f); // +8 to compensate dmd codegen bug: it can read dword(qword?) when told to read only byte
if (res !is null) {
import core.stdc.string : memset;
memset(res, 0, sz+8);
}
return cast(T*)res;
}
private void setup_free (VorbisDecoder f, void* p) {
//if (f.alloc.alloc_buffer) return; // do nothing; setup mem is a stack
if (p !is null) f.alloc.free(p, f);
}
private void* setup_temp_malloc (VorbisDecoder f, uint sz) {
auto res = f.alloc.allocTemp(sz+8, f); // +8 to compensate dmd codegen bug: it can read dword(qword?) when told to read only byte
if (res !is null) {
import core.stdc.string : memset;
memset(res, 0, sz+8);
}
return res;
}
private void setup_temp_free (VorbisDecoder f, void* p, uint sz) {
if (p !is null) f.alloc.freeTemp(p, (sz ? sz : 1)+8, f); // +8 to compensate dmd codegen bug: it can read dword(qword?) when told to read only byte
}
immutable uint[256] crc_table;
shared static this () {
enum CRC32_POLY = 0x04c11db7; // from spec
// init crc32 table
foreach (uint i; 0..256) {
uint s = i<<24;
foreach (immutable _; 0..8) s = (s<<1)^(s >= (1U<<31) ? CRC32_POLY : 0);
crc_table[i] = s;
}
}
uint crc32_update (uint crc, ubyte b) {
static if (__VERSION__ > 2067) pragma(inline, true);
return (crc<<8)^crc_table[b^(crc>>24)];
}
// used in setup, and for huffman that doesn't go fast path
private uint bit_reverse (uint n) {
static if (__VERSION__ > 2067) pragma(inline, true);
n = ((n&0xAAAAAAAA)>>1)|((n&0x55555555)<<1);
n = ((n&0xCCCCCCCC)>>2)|((n&0x33333333)<<2);
n = ((n&0xF0F0F0F0)>>4)|((n&0x0F0F0F0F)<<4);
n = ((n&0xFF00FF00)>>8)|((n&0x00FF00FF)<<8);
return (n>>16)|(n<<16);
}
private float square (float x) {
static if (__VERSION__ > 2067) pragma(inline, true);
return x*x;
}
// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
// as required by the specification. fast(?) implementation from stb.h
// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
immutable byte[16] log2_4 = [0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4];
private int ilog (int n) {
//static if (__VERSION__ > 2067) pragma(inline, true);
if (n < 0) return 0; // signed n returns 0
// 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
if (n < (1<<14)) {
if (n < (1<<4)) return 0+log2_4[n];
if (n < (1<<9)) return 5+log2_4[n>>5];
return 10+log2_4[n>>10];
} else if (n < (1<<24)) {
if (n < (1<<19)) return 15+log2_4[n>>15];
return 20+log2_4[n>>20];
} else {
if (n < (1<<29)) return 25+log2_4[n>>25];
return 30+log2_4[n>>30];
}
}
// code length assigned to a value with no huffman encoding
enum NO_CODE = 255;
/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
//
// these functions are only called at setup, and only a few times per file
private float float32_unpack (uint x) {
import core.math : ldexp;
//static if (__VERSION__ > 2067) pragma(inline, true);
// from the specification
uint mantissa = x&0x1fffff;
uint sign = x&0x80000000;
uint exp = (x&0x7fe00000)>>21;
double res = (sign ? -cast(double)mantissa : cast(double)mantissa);
return cast(float)ldexp(cast(float)res, cast(int)exp-788);
}
// zlib & jpeg huffman tables assume that the output symbols
// can either be arbitrarily arranged, or have monotonically
// increasing frequencies--they rely on the lengths being sorted;
// this makes for a very simple generation algorithm.
// vorbis allows a huffman table with non-sorted lengths. This
// requires a more sophisticated construction, since symbols in
// order do not map to huffman codes "in order".
private void add_entry (Codebook* c, uint huff_code, int symbol, int count, ubyte len, uint* values) {
if (!c.sparse) {
c.codewords[symbol] = huff_code;
} else {
c.codewords[count] = huff_code;
c.codeword_lengths[count] = len;
values[count] = symbol;
}
}
private int compute_codewords (Codebook* c, ubyte* len, int n, uint* values) {
import core.stdc.string : memset;
int i, k, m = 0;
uint[32] available;
memset(available.ptr, 0, available.sizeof);
// find the first entry
for (k = 0; k < n; ++k) if (len[k] < NO_CODE) break;
if (k == n) { assert(c.sorted_entries == 0); return true; }
// add to the list
add_entry(c, 0, k, m++, len[k], values);
// add all available leaves
for (i = 1; i <= len[k]; ++i) available[i] = 1U<<(32-i);
// note that the above code treats the first case specially,
// but it's really the same as the following code, so they
// could probably be combined (except the initial code is 0,
// and I use 0 in available[] to mean 'empty')
for (i = k+1; i < n; ++i) {
uint res;
int z = len[i];
if (z == NO_CODE) continue;
// find lowest available leaf (should always be earliest,
// which is what the specification calls for)
// note that this property, and the fact we can never have
// more than one free leaf at a given level, isn't totally
// trivial to prove, but it seems true and the assert never
// fires, so!
while (z > 0 && !available[z]) --z;
if (z == 0) return false;
res = available[z];
assert(z >= 0 && z < 32);
available[z] = 0;
ubyte xxx = len[i];
add_entry(c,
bit_reverse(res),
i,
m++,
xxx, // dmd bug: it reads 4 bytes without temp
values);
// propogate availability up the tree
if (z != len[i]) {
assert(len[i] >= 0 && len[i] < 32);
for (int y = len[i]; y > z; --y) {
assert(available[y] == 0);
available[y] = res+(1<<(32-y));
}
}
}
return true;
}
// accelerated huffman table allows fast O(1) match of all symbols
// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
private void compute_accelerated_huffman (Codebook* c) {
//for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c.fast_huffman.ptr[i] = -1;
c.fast_huffman.ptr[0..FAST_HUFFMAN_TABLE_SIZE] = -1;
auto len = (c.sparse ? c.sorted_entries : c.entries);
version(STB_VORBIS_FAST_HUFFMAN_SHORT) {
if (len > 32767) len = 32767; // largest possible value we can encode!
}
foreach (uint i; 0..len) {
if (c.codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
uint z = (c.sparse ? bit_reverse(c.sorted_codewords[i]) : c.codewords[i]);
// set table entries for all bit combinations in the higher bits
while (z < FAST_HUFFMAN_TABLE_SIZE) {
c.fast_huffman.ptr[z] = cast(typeof(c.fast_huffman[0]))i; //k8
z += 1<<c.codeword_lengths[i];
}
}
}
}
extern(C) int uint32_compare (const scope void* p, const scope void* q) {
uint x = *cast(uint*)p;
uint y = *cast(uint*)q;
return (x < y ? -1 : x > y);
}
private int include_in_sort (Codebook* c, uint len) {
if (c.sparse) { assert(len != NO_CODE); return true; }
if (len == NO_CODE) return false;
if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return true;
return false;
}
// if the fast table above doesn't work, we want to binary
// search them... need to reverse the bits
private void compute_sorted_huffman (Codebook* c, ubyte* lengths, uint* values) {
// build a list of all the entries
// OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
// this is kind of a frivolous optimization--I don't see any performance improvement,
// but it's like 4 extra lines of code, so.
if (!c.sparse) {
int k = 0;
foreach (uint i; 0..c.entries) if (include_in_sort(c, lengths[i])) c.sorted_codewords[k++] = bit_reverse(c.codewords[i]);
assert(k == c.sorted_entries);
} else {
foreach (uint i; 0..c.sorted_entries) c.sorted_codewords[i] = bit_reverse(c.codewords[i]);
}
qsort(c.sorted_codewords, c.sorted_entries, (c.sorted_codewords[0]).sizeof, &uint32_compare);
c.sorted_codewords[c.sorted_entries] = 0xffffffff;
auto len = (c.sparse ? c.sorted_entries : c.entries);
// now we need to indicate how they correspond; we could either
// #1: sort a different data structure that says who they correspond to
// #2: for each sorted entry, search the original list to find who corresponds
// #3: for each original entry, find the sorted entry
// #1 requires extra storage, #2 is slow, #3 can use binary search!
foreach (uint i; 0..len) {
auto huff_len = (c.sparse ? lengths[values[i]] : lengths[i]);
if (include_in_sort(c, huff_len)) {
uint code = bit_reverse(c.codewords[i]);
int x = 0, n = c.sorted_entries;
while (n > 1) {
// invariant: sc[x] <= code < sc[x+n]
int m = x+(n>>1);
if (c.sorted_codewords[m] <= code) {
x = m;
n -= (n>>1);
} else {
n >>= 1;
}
}
assert(c.sorted_codewords[x] == code);
if (c.sparse) {
c.sorted_values[x] = values[i];
c.codeword_lengths[x] = huff_len;
} else {
c.sorted_values[x] = i;
}
}
}
}
// only run while parsing the header (3 times)
private int vorbis_validate (const(void)* data) {
static if (__VERSION__ > 2067) pragma(inline, true);
immutable char[6] vorbis = "vorbis";
return ((cast(char*)data)[0..6] == vorbis[]);
}
// called from setup only, once per code book
// (formula implied by specification)
private int lookup1_values (int entries, int dim) {
import core.stdc.math : lrintf;
import std.math : floor, exp, pow, log;
int r = cast(int)lrintf(floor(exp(cast(float)log(cast(float)entries)/dim)));
if (lrintf(floor(pow(cast(float)r+1, dim))) <= entries) ++r; // (int) cast for MinGW warning; floor() to avoid _ftol() when non-CRT
assert(pow(cast(float)r+1, dim) > entries);
assert(lrintf(floor(pow(cast(float)r, dim))) <= entries); // (int), floor() as above
return r;
}
// called twice per file
private void compute_twiddle_factors (int n, float* A, float* B, float* C) {
import std.math : cos, sin, PI;
int n4 = n>>2, n8 = n>>3;
int k, k2;
for (k = k2 = 0; k < n4; ++k, k2 += 2) {
A[k2 ] = cast(float) cos(4*k*PI/n);
A[k2+1] = cast(float)-sin(4*k*PI/n);
B[k2 ] = cast(float) cos((k2+1)*PI/n/2)*0.5f;
B[k2+1] = cast(float) sin((k2+1)*PI/n/2)*0.5f;
}
for (k = k2 = 0; k < n8; ++k, k2 += 2) {
C[k2 ] = cast(float) cos(2*(k2+1)*PI/n);
C[k2+1] = cast(float)-sin(2*(k2+1)*PI/n);
}
}
private void compute_window (int n, float* window) {
import std.math : sin, PI;
int n2 = n>>1;
foreach (int i; 0..n2) *window++ = cast(float)sin(0.5*PI*square(cast(float)sin((i-0+0.5)/n2*0.5*PI)));
}
private void compute_bitreverse (int n, ushort* rev) {
int ld = ilog(n)-1; // ilog is off-by-one from normal definitions
int n8 = n>>3;
foreach (int i; 0..n8) *rev++ = cast(ushort)((bit_reverse(i)>>(32-ld+3))<<2); //k8
}
private int init_blocksize (VorbisDecoder f, int b, int n) {
int n2 = n>>1, n4 = n>>2, n8 = n>>3;
f.A[b] = setup_malloc!float(f, n2);
f.B[b] = setup_malloc!float(f, n2);
f.C[b] = setup_malloc!float(f, n4);
if (f.A[b] is null || f.B[b] is null || f.C[b] is null) return error(f, STBVorbisError.outofmem);
compute_twiddle_factors(n, f.A[b], f.B[b], f.C[b]);
f.window[b] = setup_malloc!float(f, n2);
if (f.window[b] is null) return error(f, STBVorbisError.outofmem);
compute_window(n, f.window[b]);
f.bit_reverse[b] = setup_malloc!ushort(f, n8);
if (f.bit_reverse[b] is null) return error(f, STBVorbisError.outofmem);
compute_bitreverse(n, f.bit_reverse[b]);
return true;
}
private void neighbors (ushort* x, int n, ushort* plow, ushort* phigh) {
int low = -1;
int high = 65536;
assert(n >= 0 && n <= ushort.max);
foreach (ushort i; 0..cast(ushort)n) {
if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
}
}
// this has been repurposed so y is now the original index instead of y
struct Point {
ushort x, y;
}
extern(C) int point_compare (const scope void *p, const scope void *q) {
auto a = cast(const(Point)*)p;
auto b = cast(const(Point)*)q;
return (a.x < b.x ? -1 : a.x > b.x);
}
/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////