forked from libretro/RetroArch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstb_vorbis.h
3910 lines (3423 loc) · 127 KB
/
stb_vorbis.h
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
#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
#define STB_VORBIS_INCLUDE_STB_VORBIS_H
#include <assert.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct
{
char *alloc_buffer;
int alloc_buffer_length_in_bytes;
} stb_vorbis_alloc;
/* FUNCTIONS USEABLE WITH ALL INPUT MODES */
typedef struct stb_vorbis stb_vorbis;
typedef struct
{
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int setup_temp_memory_required;
unsigned int temp_memory_required;
int max_frame_size;
} stb_vorbis_info;
/* get general information about the file */
extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
/* get the last error detected (clears it, too) */
extern int stb_vorbis_get_error(stb_vorbis *f);
/* close an ogg vorbis file and free all memory in use */
extern void stb_vorbis_close(stb_vorbis *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 */
extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
/* returns the current seek point within the file, or offset from the beginning
* of the memory buffer. In pushdata mode it returns 0. */
extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
/* PULLING INPUT API */
#ifndef STB_VORBIS_NO_PULLDATA_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.) */
extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
int *error, stb_vorbis_alloc *alloc_buffer);
/* 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 */
extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
/* NOT WORKING YET
* 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(). */
extern void stb_vorbis_seek_start(stb_vorbis *f);
/* this function is equivalent to stb_vorbis_seek(f,0), but it
* actually works */
extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
/* these functions return the total length of the vorbis stream */
extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
/* 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.
*/
extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
extern int stb_vorbis_get_samples_float(stb_vorbis *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. 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.
*/
#endif
/* ERROR CODES */
enum STBVorbisError
{
VORBIS__no_error,
VORBIS_need_more_data=1, /* not a real error */
VORBIS_invalid_api_mixing, /* can't mix API modes */
VORBIS_outofmem, /* not enough memory */
VORBIS_feature_not_supported, /* uses floor 0 */
VORBIS_too_many_channels, /* STB_VORBIS_MAX_CHANNELS is too small */
VORBIS_file_open_failure, /* fopen() failed */
VORBIS_seek_without_length, /* can't seek in unknown-length file */
VORBIS_unexpected_eof=10, /* file is truncated? */
VORBIS_seek_invalid, /* seek past EOF */
/* decoding errors (corrupt/invalid stream) -- you probably
* don't care about the exact details of these */
/* vorbis errors: */
VORBIS_invalid_setup=20,
VORBIS_invalid_stream,
/* ogg errors: */
VORBIS_missing_capture_pattern=30,
VORBIS_invalid_stream_structure_version,
VORBIS_continued_packet_flag_invalid,
VORBIS_incorrect_stream_serial_number,
VORBIS_invalid_first_page,
VORBIS_bad_packet_type,
VORBIS_cant_find_last_page,
VORBIS_seek_failed
};
#ifdef __cplusplus
}
#endif
#endif /* STB_VORBIS_INCLUDE_STB_VORBIS_H */
#ifndef STB_VORBIS_HEADER_ONLY
/* 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_PULLDATA_API
* does not compile the code for the non-pushdata APIs
*/
#if 0
#define STB_VORBIS_NO_PULLDATA_API
#endif
/* 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).
*/
#ifndef STB_VORBIS_MAX_CHANNELS
#define STB_VORBIS_MAX_CHANNELS 16 /* enough for anyone? */
#endif
/* 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.
*/
#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
#endif
/* 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.)
*/
#ifndef STB_VORBIS_FAST_HUFFMAN_INT
#define STB_VORBIS_FAST_HUFFMAN_SHORT
#endif
/* 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.
*/
#if 0
#define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
#endif
/* STB_VORBIS_CODEBOOK_SHORTS
* The vorbis file format encodes VQ codebook floats as ax+b where a and
* b are floating point per-codebook constants, and x is a 16-bit int.
* Normally, stb_vorbis decodes them to floats rather than leaving them
* as 16-bit ints and computing ax+b while decoding. This is a speed/space
* tradeoff; you can save space by defining this flag.
*/
#ifndef STB_VORBIS_CODEBOOK_SHORTS
#define STB_VORBIS_CODEBOOK_FLOATS
#endif
#include <retro_inline.h>
#define MAX_BLOCKSIZE_LOG 13 /* from specification */
#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#ifdef STB_VORBIS_CODEBOOK_FLOATS
typedef float stb_vorbis_codetype;
#else
typedef uint16_t stb_vorbis_codetype;
#endif
/* @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.
*/
#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
typedef struct
{
int dimensions, entries;
uint8_t *codeword_lengths;
float minimum_value;
float delta_value;
uint8_t value_bits;
uint8_t lookup_type;
uint8_t sequence_p;
uint8_t sparse;
uint32_t lookup_values;
stb_vorbis_codetype *multiplicands;
uint32_t *codewords;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
int16_t fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#else
int32_t fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
#endif
uint32_t *sorted_codewords;
int *sorted_values;
int sorted_entries;
} Codebook;
typedef struct
{
uint8_t order;
uint16_t rate;
uint16_t bark_map_size;
uint8_t amplitude_bits;
uint8_t amplitude_offset;
uint8_t number_of_books;
uint8_t book_list[16]; /* varies */
} Floor0;
typedef struct
{
uint8_t partitions;
uint8_t partition_class_list[32]; /* varies */
uint8_t class_dimensions[16]; /* varies */
uint8_t class_subclasses[16]; /* varies */
uint8_t class_masterbooks[16]; /* varies */
int16_t subclass_books[16][8]; /* varies */
uint16_t Xlist[31*8+2]; /* varies */
uint8_t sorted_order[31*8+2];
uint8_t neighbors[31*8+2][2];
uint8_t floor1_multiplier;
uint8_t rangebits;
int values;
} Floor1;
typedef union
{
Floor0 floor0;
Floor1 floor1;
} Floor;
typedef struct
{
uint32_t begin, end;
uint32_t part_size;
uint8_t classifications;
uint8_t classbook;
uint8_t **classdata;
int16_t (*residue_books)[8];
} Residue;
typedef struct
{
uint8_t magnitude;
uint8_t angle;
uint8_t mux;
} MappingChannel;
typedef struct
{
uint16_t coupling_steps;
MappingChannel *chan;
uint8_t submaps;
uint8_t submap_floor[15]; /* varies */
uint8_t submap_residue[15]; /* varies */
} Mapping;
typedef struct
{
uint8_t blockflag;
uint8_t mapping;
uint16_t windowtype;
uint16_t transformtype;
} Mode;
typedef struct
{
uint32_t goal_crc; /* expected crc if match */
int bytes_left; /* bytes left in packet */
uint32_t crc_so_far; /* running crc */
int bytes_done; /* bytes processed in _current_ chunk */
uint32_t sample_loc; /* granule pos encoded in page */
} CRCscan;
typedef struct
{
uint32_t page_start, page_end;
uint32_t after_previous_page_start;
uint32_t first_decoded_sample;
uint32_t last_decoded_sample;
} ProbedPage;
struct stb_vorbis
{
/* user-accessible info */
unsigned int sample_rate;
int channels;
unsigned int setup_memory_required;
unsigned int temp_memory_required;
unsigned int setup_temp_memory_required;
uint8_t *stream;
uint8_t *stream_start;
uint8_t *stream_end;
uint32_t stream_len;
uint8_t push_mode;
uint32_t first_audio_page_offset;
ProbedPage p_first, p_last;
/* memory management */
stb_vorbis_alloc alloc;
int setup_offset;
int temp_offset;
/* run-time results */
int eof;
enum STBVorbisError error;
/* user-useful data */
/* header info */
int blocksize[2];
int blocksize_0, blocksize_1;
int codebook_count;
Codebook *codebooks;
int floor_count;
uint16_t floor_types[64]; /* varies */
Floor *floor_config;
int residue_count;
uint16_t residue_types[64]; /* varies */
Residue *residue_config;
int mapping_count;
Mapping *mapping;
int mode_count;
Mode mode_config[64]; /* varies */
uint32_t total_samples;
/* decode buffer */
float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
float *outputs [STB_VORBIS_MAX_CHANNELS];
float *previous_window[STB_VORBIS_MAX_CHANNELS];
int previous_length;
int16_t *finalY[STB_VORBIS_MAX_CHANNELS];
uint32_t current_loc; /* sample location of next frame to decode */
int current_loc_valid;
/* per-blocksize precomputed data */
/* twiddle factors */
float *A[2],*B[2],*C[2];
float *window[2];
uint16_t *bit_reverse[2];
/* current page/packet/segment streaming info */
uint32_t serial; /* stream serial number for verification */
int last_page;
int segment_count;
uint8_t segments[255];
uint8_t page_flag;
uint8_t bytes_in_seg;
uint8_t first_decode;
int next_seg;
int last_seg; /* flag that we're on the last segment */
int last_seg_which; /* what was the segment number of the last seg? */
uint32_t acc;
int valid_bits;
int packet_bytes;
int end_seg_with_known_loc;
uint32_t known_loc_for_packet;
int discard_samples_deferred;
uint32_t samples_output;
/* push mode scanning */
int page_crc_tests; /* only in push_mode: number of tests active; -1 if not searching */
/* sample-access */
int channel_buffer_start;
int channel_buffer_end;
};
#define IS_PUSH_MODE(f) FALSE
typedef struct stb_vorbis vorb;
static int error(vorb *f, enum STBVorbisError e)
{
f->error = e;
if (!f->eof && e != VORBIS_need_more_data) {
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.
*/
#define array_size_required(count,size) (count*(sizeof(void *)+(size)))
#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
#define temp_alloc_save(f) ((f)->temp_offset)
#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
/* given a sufficiently large block of memory, make an array of pointers to subblocks of it */
static void *make_block_array(void *mem, int count, int size)
{
int i;
void ** p = (void **) mem;
char *q = (char *) (p + count);
for (i=0; i < count; ++i) {
p[i] = q;
q += size;
}
return p;
}
static void *setup_malloc(vorb *f, int sz)
{
sz = (sz+3) & ~3;
f->setup_memory_required += sz;
if (f->alloc.alloc_buffer) {
void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
if (f->setup_offset + sz > f->temp_offset) return NULL;
f->setup_offset += sz;
return p;
}
return sz ? malloc(sz) : NULL;
}
static void setup_free(vorb *f, void *p)
{
if (f->alloc.alloc_buffer) return; /* do nothing; setup mem is not a stack */
free(p);
}
static void *setup_temp_malloc(vorb *f, int sz)
{
sz = (sz+3) & ~3;
if (f->alloc.alloc_buffer) {
if (f->temp_offset - sz < f->setup_offset) return NULL;
f->temp_offset -= sz;
return (char *) f->alloc.alloc_buffer + f->temp_offset;
}
return malloc(sz);
}
static void setup_temp_free(vorb *f, void *p, int sz)
{
if (f->alloc.alloc_buffer) {
f->temp_offset += (sz+3)&~3;
return;
}
free(p);
}
#define CRC32_POLY 0x04c11db7 /* from spec */
static uint32_t stb_vorbis_crc_table[256];
static void crc32_init(void)
{
int i,j;
uint32_t s;
for(i=0; i < 256; i++) {
for (s=i<<24, j=0; j < 8; ++j)
s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);
stb_vorbis_crc_table[i] = s;
}
}
static INLINE uint32_t crc32_update(uint32_t crc, uint8_t byte)
{
return (crc << 8) ^ stb_vorbis_crc_table[byte ^ (crc >> 24)];
}
/* used in setup, and for huffman that doesn't go fast path */
static unsigned int bit_reverse(unsigned int n)
{
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);
}
static float square(float x)
{
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
*/
static int ilog(int32_t n)
{
static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
/* 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 ];
else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
else return 10 + log2_4[n >> 10];
else if (n < (1 << 24))
if (n < (1 << 19)) return 15 + log2_4[n >> 15];
else return 20 + log2_4[n >> 20];
else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
else if (n < (1 << 31)) return 30 + log2_4[n >> 30];
else return 0; /* signed n returns 0 */
}
#ifndef M_PI
#define M_PI 3.14159265358979323846264f /* from CRC */
#endif
/* code length assigned to a value with no huffman encoding */
#define NO_CODE 255
/* LEAF SETUP FUNCTIONS */
/* these functions are only called at setup, and only a few times
* per file */
static float float32_unpack(uint32_t x)
{
/* from the specification */
uint32_t mantissa = x & 0x1fffff;
uint32_t sign = x & 0x80000000;
uint32_t exp = (x & 0x7fe00000) >> 21;
double res = sign ? -(double)mantissa : (double)mantissa;
return (float) ldexp((float)res, 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".
*/
static void add_entry(Codebook *c, uint32_t huff_code, int symbol, int count, int len, uint32_t *values)
{
if (!c->sparse) {
c->codewords [symbol] = huff_code;
} else {
c->codewords [count] = huff_code;
c->codeword_lengths[count] = len;
values [count] = symbol;
}
}
static int compute_codewords(Codebook *c, uint8_t *len, int n, uint32_t *values)
{
int i,k,m=0;
uint32_t available[32];
memset(available, 0, sizeof(available));
/* 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] = 1 << (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) {
uint32_t res;
int z = len[i], y;
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) { assert(0); return FALSE; }
res = available[z];
available[z] = 0;
add_entry(c, bit_reverse(res), i, m++, len[i], values);
/* propogate availability up the tree */
if (z != len[i]) {
for (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 */
static void compute_accelerated_huffman(Codebook *c)
{
int i, len;
for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
c->fast_huffman[i] = -1;
len = c->sparse ? c->sorted_entries : c->entries;
#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
if (len > 32767) len = 32767; /* largest possible value we can encode! */
#endif
for (i=0; i < len; ++i) {
if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
uint32_t 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[z] = i;
z += 1 << c->codeword_lengths[i];
}
}
}
}
#ifdef _MSC_VER
#define STBV_CDECL __cdecl
#else
#define STBV_CDECL
#endif
static int STBV_CDECL uint32_t_compare(const void *p, const void *q)
{
uint32_t x = * (uint32_t *) p;
uint32_t y = * (uint32_t *) q;
return x < y ? -1 : x > y;
}
static int include_in_sort(Codebook *c, uint8_t 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 */
static void compute_sorted_huffman(Codebook *c, uint8_t *lengths, uint32_t *values)
{
int i, len;
/* 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;
for (i=0; i < c->entries; ++i)
if (include_in_sort(c, lengths[i]))
c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
assert(k == c->sorted_entries);
} else {
for (i=0; i < c->sorted_entries; ++i)
c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
}
qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_t_compare);
c->sorted_codewords[c->sorted_entries] = 0xffffffff;
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! */
for (i=0; i < len; ++i) {
int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
if (include_in_sort(c,huff_len)) {
uint32_t 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) */
static int vorbis_validate(uint8_t *data)
{
static uint8_t vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
return memcmp(data, vorbis, 6) == 0;
}
/* called from setup only, once per code book
* (formula implied by specification) */
static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) /* (int) cast for MinGW warning; */
++r; /* floor() to avoid _ftol() when non-CRT */
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); /* (int),floor() as above */
return r;
}
/* called twice per file */
static void compute_twiddle_factors(int n, float *A, float *B, float *C)
{
int n4 = n >> 2, n8 = n >> 3;
int k,k2;
for (k=k2=0; k < n4; ++k,k2+=2) {
A[k2 ] = (float) cos(4*k*M_PI/n);
A[k2+1] = (float) -sin(4*k*M_PI/n);
B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
}
for (k=k2=0; k < n8; ++k,k2+=2) {
C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
}
}
static void compute_window(int n, float *window)
{
int n2 = n >> 1, i;
for (i=0; i < n2; ++i)
window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
}
static void compute_bitreverse(int n, uint16_t *rev)
{
int ld = ilog(n) - 1; /* ilog is off-by-one from normal definitions */
int i, n8 = n >> 3;
for (i=0; i < n8; ++i)
rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
}
static int init_blocksize(vorb *f, int b, int n)
{
int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
if (!f->window[b]) return error(f, VORBIS_outofmem);
compute_window(n, f->window[b]);
f->bit_reverse[b] = (uint16_t *) setup_malloc(f, sizeof(uint16_t) * n8);
if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
compute_bitreverse(n, f->bit_reverse[b]);
return TRUE;
}
static void neighbors(uint16_t *x, int n, int *plow, int *phigh)
{
int low = -1;
int high = 65536;
int i;
for (i=0; i < n; ++i) {
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 */
typedef struct
{
uint16_t x,y;
} STBV_Point;
static int STBV_CDECL point_compare(const void *p, const void *q)
{
STBV_Point *a = (STBV_Point *) p;
STBV_Point *b = (STBV_Point *) q;
return a->x < b->x ? -1 : a->x > b->x;
}
/* END LEAF SETUP FUNCTIONS */
static uint8_t get8(vorb *z)
{
if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
return *z->stream++;
}
static uint32_t get32(vorb *f)
{
uint32_t x;
x = get8(f);
x += get8(f) << 8;
x += get8(f) << 16;
x += get8(f) << 24;
return x;
}
static int getn(vorb *z, uint8_t *data, int n)
{
if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
memcpy(data, z->stream, n);
z->stream += n;
return 1;
}
static void skip(vorb *z, int n)
{
z->stream += n;
if (z->stream >= z->stream_end) z->eof = 1;
return;
}
static int set_file_offset(stb_vorbis *f, unsigned int loc)
{
f->eof = 0;
if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
f->stream = f->stream_end;
f->eof = 1;
return 0;
} else {
f->stream = f->stream_start + loc;
return 1;
}
}
static uint8_t ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
static int capture_pattern(vorb *f)
{
if (0x4f != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x67 != get8(f)) return FALSE;
if (0x53 != get8(f)) return FALSE;
return TRUE;
}
#define PAGEFLAG_continued_packet 1
#define PAGEFLAG_first_page 2
#define PAGEFLAG_last_page 4
static int start_page_no_capturepattern(vorb *f)
{
uint32_t loc0,loc1,n;
/* stream structure version */
if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
/* header flag */
f->page_flag = get8(f);
/* absolute granule position */
loc0 = get32(f);
loc1 = get32(f);
/* @TODO: validate loc0,loc1 as valid positions?
* stream serial number -- vorbis doesn't interleave, so discard */
get32(f);
/*if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
* page sequence number */
n = get32(f);
f->last_page = n;
/* CRC32 */
get32(f);
/* page_segments */
f->segment_count = get8(f);
if (!getn(f, f->segments, f->segment_count))
return error(f, VORBIS_unexpected_eof);
/* assume we _don't_ know any the sample position of any segments */
f->end_seg_with_known_loc = -2;
if (loc0 != ~0U || loc1 != ~0U) {
int i;
/* determine which packet is the last one that will complete */
for (i=f->segment_count-1; i >= 0; --i)
if (f->segments[i] < 255)
break;
/* 'i' is now the index of the _last_ segment of a packet that ends */
if (i >= 0) {
f->end_seg_with_known_loc = i;
f->known_loc_for_packet = loc0;
}
}
if (f->first_decode) {
int i,len;
ProbedPage p;
len = 0;
for (i=0; i < f->segment_count; ++i)
len += f->segments[i];
len += 27 + f->segment_count;
p.page_start = f->first_audio_page_offset;
p.page_end = p.page_start + len;
p.after_previous_page_start = p.page_start;
p.first_decoded_sample = 0;
p.last_decoded_sample = loc0;
f->p_first = p;
}
f->next_seg = 0;
return TRUE;
}
static int start_page(vorb *f)
{
if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
return start_page_no_capturepattern(f);
}
static int start_packet(vorb *f)
{