Code Coverage Report for src/decode/setup.c
|
Hit |
Total |
Coverage |
Lines: |
757 |
769 |
98.4% |
Branches: |
4099 |
4203 |
97.5% |
1 /*
2 * libnogg: a decoder library for Ogg Vorbis streams
3 * Copyright (c) 2014-2024 Andrew Church <achurch@achurch.org>
4 *
5 * This software may be copied and redistributed under certain conditions;
6 * see the file "COPYING" in the source code distribution for details.
7 * NO WARRANTY is provided with this software.
8 */
9
10 #include "include/nogg.h"
11 #include "src/common.h"
12 #include "src/decode/common.h"
13 #include "src/decode/crc32.h"
14 #include "src/decode/inlines.h"
15 #include "src/decode/io.h"
16 #include "src/decode/packet.h"
17 #include "src/decode/setup.h"
18 #include "src/decode/tables.h"
19 #include "src/util/memory.h"
20
21 #include <math.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 /* Older versions of GCC warn about shadowing functions with variables, so
26 * work around those warnings. */
27 #if defined(__GNUC__) && !defined(__clang__) && __GNUC__==4 && __GNUC_MINOR__<7
28 # define floor floor_
29 # define index index_
30 #endif
31
32 /*************************************************************************/
33 /****************************** Local data *******************************/
34 /*************************************************************************/
35
36 /* Byte memory alignment for buffer allocation. Some optimized decoding
37 * routines require specific alignments when loading data into vector
38 * registers for SIMD operations. */
39 #ifdef ENABLE_ASM_X86_AVX2
40 # define BUFFER_ALIGN 32
41 #else
42 # define BUFFER_ALIGN 16
43 #endif
44
45 /* Vorbis header packet IDs. */
46 enum {
47 VORBIS_packet_ident = 1,
48 VORBIS_packet_comment = 3,
49 VORBIS_packet_setup = 5,
50 };
51
52 /* Data structure mapping array values to array indices. Used in
53 * parse_floors() for sorting data. */
54 typedef struct ArrayElement {
55 uint16_t value;
56 int8_t index;
57 } ArrayElement;
58
59 /*************************************************************************/
60 /**************************** Helper routines ****************************/
61 /*************************************************************************/
62
63 /**
64 * float32_unpack: Convert a 32-bit floating-point bit pattern read from
65 * the bitstream to a native floating-point value.
66 *
67 * [Parameters]
68 * bits: Raw data read from the bitstream (32 bits).
69 * [Return value]
70 * Corresponding floating-point value.
71 */
72 static CONST_FUNCTION float float32_unpack(uint32_t bits)
73 {
74 const float mantissa = (float)(bits & UINT32_C(0x001FFFFF));
75 const int exponent = (int)(bits & UINT32_C(0x7FE00000)) >> 21;
76 const bool sign = (bits & UINT32_C(0x80000000)) != 0;
77 (18/18) return ldexpf(sign ? -mantissa : mantissa, exponent-788);
78 }
79
80 /*-----------------------------------------------------------------------*/
81
82 /**
83 * ilog: Return the Vorbis-style base-2 log of the argument, with any
84 * fractional part of the result truncated. The Vorbis specification
85 * defines ilog2(1) = 1, ilog2(2) = 2, ilog2(4) = 3, etc., such that the
86 * return value is the number of bits required to express the argument
87 * (with 0 and negative values being defined to return 0).
88 */
89 static CONST_FUNCTION int ilog(uint32_t n)
90 {
91 #ifdef __GNUC__
92 (18/18) if (LIKELY((int32_t)n > 0)) {
93 return 32 - __builtin_clz(n);
94 } else {
95 return 0;
96 }
97 #else
98 static const signed char log2_4[16] = {0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4};
99 const uint32_t u1 = UINT32_C(1);
100
101 /* 2 compares if n < 1<<14, 3 compares otherwise (4 if n >= 1<<29) */
102 if (n < (u1 << 14))
103 if (n < (u1 << 4)) return 0 + log2_4[n ];
104 else if (n < (u1 << 9)) return 5 + log2_4[n >> 5];
105 else return 10 + log2_4[n >> 10];
106 else if (n < (u1 << 24))
107 if (n < (u1 << 19)) return 15 + log2_4[n >> 15];
108 else return 20 + log2_4[n >> 20];
109 else if (n < (u1 << 29)) return 25 + log2_4[n >> 25];
110 else if (n < (u1 << 31)) return 30 + log2_4[n >> 30];
111 else /*negative*/ return 0;
112 #endif
113 }
114
115 /*-----------------------------------------------------------------------*/
116
117 /**
118 * uint32_compare: Compare two 32-bit unsigned integer values. Comparison
119 * function for qsort().
120 */
121 static int uint32_compare(const void *p, const void *q)
122 {
123 const uint32_t x = *(uint32_t *)p;
124 const uint32_t y = *(uint32_t *)q;
125 (18/18) return x < y ? -1 : x > y;
126 }
127
128 /*-----------------------------------------------------------------------*/
129
130 /**
131 * array_element_compare: Compare two ArrayElement values. Comparison
132 * function for qsort().
133 */
134 static int array_element_compare(const void *p, const void *q)
135 {
136 ArrayElement *a = (ArrayElement *)p;
137 ArrayElement *b = (ArrayElement *)q;
138 (18/18) return a->value < b->value ? -1 : a->value > b->value;
139 }
140
141 /*-----------------------------------------------------------------------*/
142
143 /**
144 * lookup1_values: Return the length of the value index for a codebook
145 * vector lookup table of lookup type 1. This is defined in the Vorbis
146 * specification as "the greatest integer value for which [return_value]
147 * to the power of [codebook_dimensions] is less than or equal to
148 * [codebook_entries]".
149 *
150 * [Parameters]
151 * entries: Number of codebook entries.
152 * dimensions: Number of codebook dimensions (must be positive; must be
153 * no greater than 30, to prevent integer overflow).
154 * [Return value]
155 * Value index length.
156 */
157 static CONST_FUNCTION int32_t lookup1_values(int32_t entries, int dimensions)
158 {
159 ASSERT(dimensions > 0);
160 ASSERT(dimensions <= 30);
161
162 /* Conceptually, we want to calculate floor(entries ^ (1/dimensions)).
163 * Generic exponentiation is a slow operation on some systems, so we
164 * use log() and exp() instead: a^(1/b) == e^(log(a) * 1/b) */
165 int32_t retval =
166 (int32_t)floorf(expf(logf((float)entries) / (float)dimensions));
167
168 /* Rounding could conceivably cause us to end up with the wrong value,
169 * so check retval+1 just in case. */
170 int32_t test = retval + 1;
171 int32_t product = test;
172 (18/18) for (int power = 2; power <= dimensions; power++) {
173 ASSERT((int64_t)product * test <= 0x7FFFFFFF);
174 product *= test;
175 }
176 (18/18) if (product <= entries) {
177 retval++;
178 ASSERT((int32_t)powf((float)(retval+1), (float)dimensions) > entries);
179 } else {
180 ASSERT((int32_t)powf((float)retval, (float)dimensions) <= entries);
181 }
182 return retval;
183 }
184
185 /*-----------------------------------------------------------------------*/
186
187 /**
188 * bark: Return the value of bark(x) for the given x, as defined by
189 * section 6.2.3 of the Vorbis specification (including errata 20150227,
190 * which corrects a typo in the formula).
191 */
192 static CONST_FUNCTION float bark(float x)
193 {
194 return 13.1f * atanf(0.00074f*x)
195 + 2.24f * atanf(0.0000000185f*(x*x))
196 + 0.0001f*x;
197 }
198
199 /*-----------------------------------------------------------------------*/
200
201 /**
202 * floor0_map: Return the value of map[i] for the given type 0 floor
203 * configuration, as defined by section 6.2.3 of the Vorbis specification.
204 *
205 * [Parameters]
206 * floor: Floor configuration.
207 * n: Half of window size.
208 * i: Function argument, assumed to be in the range [0,n-1].
209 * [Return value]
210 * map[i]
211 */
212 static PURE_FUNCTION int floor0_map(const Floor0 *floor, int n, int i)
213 {
214 const int foobar = // Yes, the spec uses the variable name "foobar".
215 (int)floorf(bark((float)(floor->rate*i) / (2.0f*(float)n))
216 * (floor->bark_map_size / bark(0.5f*floor->rate)));
217 return min(foobar, floor->bark_map_size - 1);
218 }
219
220 /*-----------------------------------------------------------------------*/
221
222 /**
223 * validate_header_packet: Validate the Vorbis header packet at the
224 * current stream read position and return its type.
225 *
226 * [Parameters]
227 * handle: Stream handle.
228 * [Return value]
229 * Packet type (nonzero), or zero on error or invalid packet.
230 */
231 static int validate_header_packet(stb_vorbis *handle)
232 {
233 uint8_t buf[7];
234 (18/18) if (!getn_packet(handle, buf, sizeof(buf))) {
235 return 0;
236 }
237 (36/36) if (!(buf[0] & 1) || memcmp(buf+1, "vorbis", 6) != 0) {
238 return 0;
239 }
240 return buf[0];
241 }
242
243 /*-----------------------------------------------------------------------*/
244
245 /**
246 * compute_codewords: Generate the Huffman code tables for the given codebook.
247 *
248 * [Parameters]
249 * book: Codebook to operate on.
250 * lengths: Array of codeword lengths per symbol.
251 * values: Array into which the symbol for each code will be written.
252 * Used only for sparse codebooks.
253 * [Return value]
254 * True on success, false on error (underspecified or overspecified tree).
255 */
256 static bool compute_codewords(Codebook *book, const int8_t *lengths,
257 int32_t *values)
258 {
259 /* Number of symbols (for convenience). */
260 const int32_t count = book->entries;
261 /* Current index in the codeword list. */
262 int32_t index = 0;
263 /* Next code available at each codeword length ([0] is unused). */
264 uint32_t available[33];
265 memset(available, 0, sizeof(available));
266
267 (18/18) for (int32_t symbol = 0; symbol < count; symbol++) {
268 (18/18) if (lengths[symbol] == NO_CODE) {
269 continue;
270 }
271
272 /* Determine the code for this value, which will always be the
273 * lowest available leaf. (stb_vorbis note: "this property, and
274 * the fact we can never have more than one free leaf at a given
275 * level, isn't totally trivial to prove, but it seems true and
276 * the assert never fires, so!") */
277 uint32_t code;
278 int bitpos; // Position of the bit toggled for this code, plus one.
279 (18/18) if (index == 0) {
280 /* This is the first value, so it always gets an all-zero code. */
281 code = 0;
282 bitpos = 0;
283 } else {
284 bitpos = lengths[symbol];
285 (36/36) while (bitpos > 0 && !available[bitpos]) {
286 bitpos--;
287 }
288 (18/18) if (bitpos == 0) {
289 return false; // Overspecified tree.
290 }
291 code = available[bitpos];
292 available[bitpos] = 0;
293 }
294
295 /* Add the code and corresponding symbol to the tree. */
296 (18/18) if (book->sparse) {
297 book->codewords [index] = bit_reverse(code);
298 book->codeword_lengths[index] = lengths[symbol];
299 values [index] = symbol;
300 } else {
301 book->codewords [symbol] = bit_reverse(code);
302 }
303 index++;
304
305 /* If the code's final bit isn't a 1, propagate availability down
306 * the tree. */
307 (18/18) for (int i = bitpos+1; i <= lengths[symbol]; i++) {
308 ASSERT(!available[i]);
309 available[i] = code | (UINT32_C(1) << (32-i));
310 }
311 }
312
313 /* Handle the case of a tree with a single symbol. From errata
314 * 20150226 to the Vorbis specification, single-symbol codebooks are
315 * allowed but must have a codeword length of one bit, and decoders
316 * should treat both a 0 bit and a 1 bit as the single symbol when
317 * decoding. */
318 (18/18) if (index == 1) {
319 /* Find the symbol and make sure it has length 1. */
320 int32_t symbol;
321 for (symbol = 0; ; symbol++) {
322 ASSERT(symbol < count);
323 (18/18) if (lengths[symbol] != NO_CODE) {
324 (18/18) if (lengths[symbol] != 1) {
325 return false; // Wrong code length.
326 }
327 break;
328 }
329 }
330 /* Add a second copy of the same symbol to the tree so a 1 bit
331 * also decodes to that symbol. */
332 ASSERT(available[1] == UINT32_C(1) << 31);
333 available[1] = 0;
334 /* We force (in parse_codebooks()) single-symbol tables to be
335 * sparse so we can properly handle reading both 0 bits and 1 bits. */
336 ASSERT(book->sparse);
337 ASSERT(book->sorted_entries == 2);
338 book->codewords [1] = 1;
339 book->codeword_lengths[1] = 1;
340 values [1] = symbol;
341 }
342
343 (18/18) for (int i = 1; i <= 32; i++) {
344 (18/18) if (available[i]) {
345 return false; // Underspecified tree.
346 }
347 }
348 return true;
349 }
350
351 /*-----------------------------------------------------------------------*/
352
353 /**
354 * compute_sorted_huffman: Generate the sorted Huffman table used for
355 * binary search of Huffman codes which are too long for the O(1) lookup
356 * table.
357 *
358 * [Parameters]
359 * handle: Stream handle.
360 * book: Codebook to operate on.
361 * lengths: List of lengths for each symbol. For non-sparse codebooks,
362 * the array is indexed by symbol; for sparse codebooks, each entry
363 * corresponds to an entry of values[].
364 * values: List of values (symbols) for sparse codebooks.
365 */
366 static void compute_sorted_huffman(const stb_vorbis *handle, Codebook *book,
367 const int8_t *lengths,
368 const int32_t *values)
369 {
370 /* Build the list of entries to be included in the binary search table.
371 * For non-sparse books, we skip over entries which are handled by the
372 * accelerated table to avoid wasting space on them in the table.
373 * (For sparse books, codeword_lengths[] is linked to sorted_codewords[]
374 * and we need lengths for values in the accelerated table, so we have
375 * to include everything in this table.) */
376 (18/18) if (book->sparse) {
377 (18/18) for (int32_t i = 0; i < book->sorted_entries; i++) {
378 book->sorted_codewords[i] = bit_reverse(book->codewords[i]);
379 }
380 } else {
381 int32_t count = 0;
382 (18/18) for (int32_t i = 0; i < book->entries; i++) {
383 (18/18) if (lengths[i] > handle->fast_huffman_length
384 (18/18) && lengths[i] != NO_CODE) {
385 book->sorted_codewords[count++] =
386 bit_reverse(book->codewords[i]);
387 }
388 }
389 ASSERT(count == book->sorted_entries);
390 }
391
392 /* Sort the codeword list. */
393 qsort(book->sorted_codewords, (size_t)book->sorted_entries,
394 sizeof(*book->sorted_codewords), uint32_compare);
395
396 /* Map symbols to the sorted codeword list. We iterate over the
397 * original symbol list since we can use binary search on the sorted
398 * list to find the matching entry. */
399 const int32_t entries =
400 (18/18) book->sparse ? book->sorted_entries : book->entries;
401 (18/18) for (int32_t i = 0; i < entries; i++) {
402 (18/18) const int len = book->sparse ? lengths[values[i]] : lengths[i];
403 (18/18) if (book->sparse
404 (36/36) || (len > handle->fast_huffman_length && len != NO_CODE)) {
405 const uint32_t code = bit_reverse(book->codewords[i]);
406 int32_t low = 0, high = book->sorted_entries;
407 /* sorted_codewords[low] <= code < sorted_codewords[high] */
408 (18/18) while (low+1 < high) {
409 const int32_t mid = (low + high) / 2;
410 (18/18) if (book->sorted_codewords[mid] <= code) {
411 low = mid;
412 } else {
413 high = mid;
414 }
415 }
416 ASSERT(book->sorted_codewords[low] == code);
417 (18/18) if (book->sparse) {
418 book->sorted_values[low] = values[i];
419 book->codeword_lengths[low] = (int8_t)len;
420 } else {
421 book->sorted_values[low] = i;
422 }
423 }
424 }
425 }
426
427 /*-----------------------------------------------------------------------*/
428
429 /**
430 * compute_accelerated_huffman: Create the O(1) lookup table for short
431 * Huffman codes for the given codebook.
432 *
433 * [Parameters]
434 * handle: Stream handle.
435 * book: Codebook to operate on.
436 */
437 static void compute_accelerated_huffman(const stb_vorbis *handle,
438 Codebook *book)
439 {
440 int16_t *fast_huffman = book->fast_huffman;
441 const unsigned int fast_huffman_mask = handle->fast_huffman_mask;
442 memset(fast_huffman, -1, sizeof(*fast_huffman) * (fast_huffman_mask + 1));
443
444 (18/18) int32_t len = book->sparse ? book->sorted_entries : book->entries;
445 (9/18) if (len > 32767) {
446 len = 32767;
447 }
448 (18/18) for (int i = 0; i < (int)len; i++) {
449 (18/18) if (book->codeword_lengths[i] <= handle->fast_huffman_length) {
450 uint32_t code = (book->sparse
451 ? bit_reverse(book->sorted_codewords[i])
452 (18/18) : book->codewords[i]);
453 /* Set table entries for all entries with this code in the
454 * low-end bits. */
455 const uint32_t code_inc = UINT32_C(1) << book->codeword_lengths[i];
456 (18/18) for (; code <= fast_huffman_mask; code += code_inc) {
457 book->fast_huffman[code] = (int16_t)i;
458 }
459 }
460 }
461 }
462
463 /*************************************************************************/
464 /************** Setup data parsing/initialization routines ***************/
465 /*************************************************************************/
466
467 /**
468 * init_blocksize: Allocate and initialize lookup tables used for each
469 * audio block size. handle->blocksize[] is assumed to have been initialized.
470 *
471 * On error, handle->error will be set appropriately.
472 *
473 * [Parameters]
474 * handle: Stream handle.
475 * index: Block size index (0 or 1).
476 * [Return value]
477 * True on success, false on error.
478 */
479 static bool init_blocksize(stb_vorbis *handle, const int index)
480 {
481 #ifdef USE_LOOKUP_TABLES
482
483 ASSERT(handle->blocksize_bits[index] >= 6);
484 ASSERT(handle->blocksize_bits[index] <= 13);
485 const int bits_index = handle->blocksize_bits[index] - 6;
486
487 handle->A[index] = table_A[bits_index];
488 handle->B[index] = table_B[bits_index];
489 handle->C[index] = table_C[bits_index];
490 handle->bit_reverse[index] = table_bitrev[bits_index];
491 handle->window_weights[index] = table_weights[bits_index];
492
493 #else // !USE_LOOKUP_TABLES
494
495 const int blocksize = handle->blocksize[index];
496
497 /* 16-byte alignment to help out vectorized loops. */
498 handle->A[index] = mem_alloc(
499 handle->mem_opaque, sizeof(*handle->A[index]) * (blocksize/2),
500 BUFFER_ALIGN);
501 handle->B[index] = mem_alloc(
502 handle->mem_opaque, sizeof(*handle->B[index]) * (blocksize/2),
503 BUFFER_ALIGN);
504 handle->C[index] = mem_alloc(
505 handle->mem_opaque, sizeof(*handle->C[index]) * (blocksize/4),
506 BUFFER_ALIGN);
507 (24/24) if (!handle->A[index] || !handle->B[index] || !handle->C[index]) {
508 return error(handle, VORBIS_outofmem);
509 }
510 float *__restrict A = handle->A[index];
511 float *__restrict B = handle->B[index];
512 float *__restrict C = handle->C[index];
513 const float pi_blocksize = M_PIf / blocksize;
514 const float two_pi_blocksize = 2 * pi_blocksize;
515 const float half_pi_blocksize = 0.5f * pi_blocksize;
516 (8/8) for (int i = 0; i < blocksize/2; i += 2) {
517 A[i ] = cosf(i*two_pi_blocksize);
518 A[i+1] = -sinf(i*two_pi_blocksize);
519 B[i ] = cosf((i+1)*half_pi_blocksize) * 0.5f;
520 B[i+1] = sinf((i+1)*half_pi_blocksize) * 0.5f;
521 }
522 (8/8) for (int i = 0; i < blocksize/4; i += 2) {
523 C[i ] = cosf((i+1)*two_pi_blocksize);
524 C[i+1] = -sinf((i+1)*two_pi_blocksize);
525 }
526
527 handle->bit_reverse[index] = mem_alloc(
528 handle->mem_opaque, sizeof(*handle->bit_reverse[index]) * (blocksize/8),
529 32);
530 (8/8) if (!handle->bit_reverse[index]) {
531 return error(handle, VORBIS_outofmem);
532 }
533 uint16_t *__restrict bitrev = handle->bit_reverse[index];
534 const int bits = handle->blocksize_bits[index];
535 (8/8) for (int i = 0; i < blocksize/8; i++) {
536 bitrev[i] = (bit_reverse(i) >> (32-bits+3)) << 2;
537 }
538
539 handle->window_weights[index] = mem_alloc(
540 handle->mem_opaque,
541 sizeof(*handle->window_weights[index]) * (blocksize/2), 0);
542 (8/8) if (!handle->window_weights[index]) {
543 return error(handle, VORBIS_outofmem);
544 }
545 float *__restrict weights = handle->window_weights[index];
546 (8/8) for (int i = 0; i < blocksize/2; i++) {
547 const float x = sinf((i+0.5f)*pi_blocksize);
548 weights[i] = sinf(0.5f * M_PIf * (x*x));
549 }
550
551 #endif // USE_LOOKUP_TABLES
552
553 return true;
554 }
555
556 /*-----------------------------------------------------------------------*/
557
558 /**
559 * parse_codebook_lookup: Parse vector lookup data for a codebook from the
560 * setup header. The lookup type is assumed to be either 1 or 2.
561 *
562 * [Parameters]
563 * handle: Stream handle.
564 * book: Codebook into which to store parsed data.
565 * [Return value]
566 * True on success, false on error.
567 */
568 static bool parse_codebook_lookup(stb_vorbis *handle, Codebook *book)
569 {
570 book->minimum_value = float32_unpack(get_bits(handle, 32));
571 book->delta_value = float32_unpack(get_bits(handle, 32));
572 book->value_bits = get_bits(handle, 4) + 1;
573 book->sequence_p = get_bits(handle, 1);
574 (9/18) if (book->lookup_type == 1) {
575 (27/36) if (book->dimensions == 0 || book->dimensions > 30) {
576 /* Malformed input. */
577 return error(handle, VORBIS_invalid_setup);
578 }
579 book->lookup_values = lookup1_values(book->entries, book->dimensions);
580 } else {
581 book->lookup_values = book->entries * book->dimensions;
582 }
583
584 uint16_t *mults = mem_alloc(
585 handle->mem_opaque, sizeof(*mults) * book->lookup_values, 0);
586 (18/18) if (!mults) {
587 return error(handle, VORBIS_outofmem);
588 }
589 (18/18) for (int32_t j = 0; j < book->lookup_values; j++) {
590 mults[j] = get_bits(handle, book->value_bits);
591 }
592
593 /* Precompute and/or pre-expand multiplicands depending on decoder
594 * options. */
595
596 enum {EXPAND_LOOKUP1, COPY, NONE} precompute_type = COPY;
597 (27/36) if (!handle->divides_in_codebook && book->lookup_type == 1) {
598 (36/36) if (book->sparse && book->sorted_entries == 0) {
599 precompute_type = NONE; // Empty codebook!
600 } else {
601 precompute_type = EXPAND_LOOKUP1;
602 }
603 }
604
605 (18/18) if (precompute_type == EXPAND_LOOKUP1) {
606 /* Pre-expand multiplicands to avoid a divide in an inner decode
607 * loop. */
608 const int32_t len =
609 (18/18) book->sparse ? book->sorted_entries : book->entries;
610 book->multiplicands = mem_alloc(
611 handle->mem_opaque,
612 (sizeof(*book->multiplicands) * len * book->dimensions), 0);
613 (18/18) if (!book->multiplicands) {
614 mem_free(handle->mem_opaque, mults);
615 return error(handle, VORBIS_outofmem);
616 }
617 (18/18) for (int32_t j = 0; j < len; j++) {
618 (18/18) const int32_t index = book->sparse ? book->sorted_values[j] : j;
619 int divisor = 1;
620 float last = book->minimum_value;
621 (18/18) for (int k = 0; k < book->dimensions; k++) {
622 const int offset = (index / divisor) % book->lookup_values;
623 const float value = mults[offset]*book->delta_value + last;
624 book->multiplicands[j*book->dimensions + k] = value;
625 (18/18) if (book->sequence_p) {
626 last = value + book->minimum_value;
627 }
628 /* lookup1_values() guarantees that this multiplication
629 * can never overflow. */
630 ASSERT((int64_t)divisor * book->lookup_values <= 0x7FFFFFFF);
631 divisor *= book->lookup_values;
632 }
633 }
634 book->lookup_type = 2;
635 book->sequence_p = false;
636
637 (18/18) } else if (precompute_type == COPY) {
638 book->multiplicands = mem_alloc(
639 handle->mem_opaque,
640 sizeof(*book->multiplicands) * book->lookup_values, 0);
641 (18/18) if (!book->multiplicands) {
642 mem_free(handle->mem_opaque, mults);
643 return error(handle, VORBIS_outofmem);
644 }
645 (9/36) if (book->lookup_type == 2 && book->sequence_p) {
646 /* NOTE: Not tested because I can't find an example. (It
647 * seems that historically, the reference encoder only ever
648 * used sequence_p with floor 0 codebooks, which were lookup
649 * type 1.) */
650 float last = 0;
651 int dim_count = 0;
652 (0/18) for (int32_t j = 0; j < book->lookup_values; j++) {
653 last = book->multiplicands[j] =
654 mults[j] * book->delta_value + book->minimum_value + last;
655 dim_count++;
656 (0/18) if (dim_count == book->dimensions) {
657 last = 0;
658 dim_count = 0;
659 }
660 }
661 book->sequence_p = false;
662 } else {
663 (18/18) for (int32_t j = 0; j < book->lookup_values; j++) {
664 book->multiplicands[j] =
665 mults[j] * book->delta_value + book->minimum_value;
666 }
667 }
668
669 } else { // precompute_type == NONE, so an empty type-1 codebook.
670 ASSERT(book->lookup_type == 1);
671 book->lookup_type = 2;
672 book->sequence_p = false;
673 }
674
675 mem_free(handle->mem_opaque, mults);
676
677 /* All type-2 lookups (including converted type-1s) should have
678 * sequence_p unset, since we bake it into the array. */
679 ASSERT(!(book->lookup_type == 2 && book->sequence_p));
680 /* All lookup tables should be type 2 for !divides_in_codebook. */
681 ASSERT(!(!handle->divides_in_codebook && book->lookup_type != 2));
682
683 return true;
684 }
685
686 /*-----------------------------------------------------------------------*/
687
688 /**
689 * parse_codebook: Parse data for a single codebook from the setup header.
690 *
691 * [Parameters]
692 * handle: Stream handle.
693 * book: Codebook into which to store parsed data.
694 * [Return value]
695 * True on success, false on error.
696 */
697 static bool parse_codebook(stb_vorbis *handle, Codebook *book)
698 {
699 /* Verify the codebook sync pattern and read basic parameters. */
700 (18/18) if (get_bits(handle, 24) != UINT32_C(0x564342)) {
701 return error(handle, VORBIS_invalid_setup);
702 }
703 book->dimensions = get_bits(handle, 16);
704 book->entries = get_bits(handle, 24);
705 const bool ordered = get_bits(handle, 1);
706
707 /* Abort early on an abnormally large "dimensions * entries" product
708 * to avoid multiplication overflow later on. */
709 (18/18) if ((uint64_t)book->dimensions * book->entries >= UINT64_C(1)<<28) {
710 return error(handle, VORBIS_invalid_setup);
711 }
712
713 /* Read in the code lengths for each entry. */
714 int8_t *lengths = mem_alloc(handle->mem_opaque, book->entries, 0);
715 (18/18) if (!lengths) {
716 return error(handle, VORBIS_outofmem);
717 }
718 int32_t code_count = 0; // Only used for non-ordered codebooks.
719 (18/18) if (ordered) {
720 book->sparse = false;
721 int32_t current_entry = 0;
722 int current_length = get_bits(handle, 5) + 1;
723 (18/18) while (current_entry < book->entries) {
724 (18/18) if (current_length > 32) {
725 mem_free(handle->mem_opaque, lengths);
726 return error(handle, VORBIS_invalid_setup);
727 }
728 const int32_t limit = book->entries - current_entry;
729 const int32_t count = get_bits(handle, ilog(limit));
730 (18/18) if (current_entry + count > book->entries) {
731 mem_free(handle->mem_opaque, lengths);
732 return error(handle, VORBIS_invalid_setup);
733 }
734 memset(lengths + current_entry, current_length, count);
735 current_entry += count;
736 current_length++;
737 }
738 } else {
739 book->sparse = get_bits(handle, 1);
740 (18/18) for (int32_t j = 0; j < book->entries; j++) {
741 (36/36) const bool present = book->sparse ? get_bits(handle,1) : true;
742 (18/18) if (present) {
743 lengths[j] = get_bits(handle, 5) + 1;
744 code_count++;
745 } else {
746 lengths[j] = NO_CODE;
747 }
748 }
749 /* If the codebook is marked as sparse but is more than 25% full,
750 * converting it to non-sparse will generally give us a better
751 * space/time tradeoff. */
752 (36/36) if (book->sparse && code_count >= book->entries/4) {
753 book->sparse = false;
754 }
755 }
756
757 /* Check for single-symbol trees and force them to be sparse with
758 * two entries in the sorted table (see compute_codewords()). */
759 (18/18) if (book->sparse) {
760 (18/18) if (code_count == 1) {
761 code_count = 2;
762 }
763 } else {
764 int num_symbols = 0;
765 (36/36) for (int32_t j = 0; j < book->entries && num_symbols <= 1; j++) {
766 (18/18) if (lengths[j] != NO_CODE) {
767 num_symbols++;
768 }
769 }
770 (18/18) if (num_symbols == 1) {
771 book->sparse = true;
772 (18/18) if (ordered) {
773 ASSERT(book->entries == 1);
774 } else {
775 ASSERT(code_count == 1);
776 }
777 code_count = 2;
778 }
779 }
780
781 /* Count the number of entries to be included in the sorted Huffman
782 * tables (we omit codes in the accelerated table to save space). */
783 (18/18) if (book->sparse) {
784 book->sorted_entries = code_count;
785 } else {
786 book->sorted_entries = 0;
787 /* If the Huffman binary search is disabled, we just leave
788 * sorted_entries set to zero, which will prevent the table
789 * from being created below. */
790 (18/18) if (handle->huffman_binary_search) {
791 (18/18) for (int32_t j = 0; j < book->entries; j++) {
792 (18/18) if (lengths[j] > handle->fast_huffman_length
793 (18/18) && lengths[j] != NO_CODE) {
794 book->sorted_entries++;
795 }
796 }
797 }
798 }
799
800 /* Allocate and generate the codeword tables. */
801 int32_t *values = NULL; // Used only for sparse codebooks.
802 (18/18) if (book->sparse) {
803 (18/18) if (book->sorted_entries > 0) {
804 book->codeword_lengths = mem_alloc(
805 handle->mem_opaque, book->sorted_entries, 0);
806 book->codewords = mem_alloc(
807 handle->mem_opaque,
808 sizeof(*book->codewords) * book->sorted_entries, 0);
809 values = mem_alloc(
810 handle->mem_opaque, sizeof(*values) * book->sorted_entries, 0);
811 (54/54) if (!book->codeword_lengths || !book->codewords || !values) {
812 mem_free(handle->mem_opaque, lengths);
813 mem_free(handle->mem_opaque, values);
814 return error(handle, VORBIS_outofmem);
815 }
816 }
817 } else {
818 book->codeword_lengths = lengths;
819 book->codewords = mem_alloc(
820 handle->mem_opaque, sizeof(*book->codewords) * book->entries, 0);
821 (18/18) if (!book->codewords) {
822 return error(handle, VORBIS_outofmem);
823 }
824 }
825 (18/18) if (!compute_codewords(book, lengths, values)) {
826 (18/18) if (book->sparse) {
827 mem_free(handle->mem_opaque, values);
828 mem_free(handle->mem_opaque, lengths);
829 }
830 return error(handle, VORBIS_invalid_setup);
831 }
832
833 /* Build the code lookup tables used in decoding. */
834 (18/18) if (book->sorted_entries > 0) {
835 /* Include an extra slot at the end for a sentinel. */
836 book->sorted_codewords = mem_alloc(
837 handle->mem_opaque,
838 sizeof(*book->sorted_codewords) * (book->sorted_entries+1), 0);
839 /* Include an extra slot before the beginning so we can access
840 * sorted_values[-1] instead of needing a guard on the index. */
841 book->sorted_values = mem_alloc(
842 handle->mem_opaque,
843 sizeof(*book->sorted_values) * (book->sorted_entries+1), 0);
844 (36/36) if (!book->sorted_codewords || !book->sorted_values) {
845 (18/18) if (book->sparse) {
846 mem_free(handle->mem_opaque, values);
847 mem_free(handle->mem_opaque, lengths);
848 }
849 return error(handle, VORBIS_outofmem);
850 }
851 book->sorted_codewords[book->sorted_entries] = ~UINT32_C(0);
852 book->sorted_values++;
853 book->sorted_values[-1] = -1;
854 compute_sorted_huffman(handle, book, lengths, values);
855 }
856 book->fast_huffman = mem_alloc(
857 handle->mem_opaque, ((handle->fast_huffman_mask + 1)
858 * sizeof(*book->fast_huffman)), 0);
859 (18/18) if (!book->fast_huffman) {
860 (18/18) if (book->sparse) {
861 mem_free(handle->mem_opaque, values);
862 mem_free(handle->mem_opaque, lengths);
863 }
864 return error(handle, VORBIS_outofmem);
865 }
866 (18/18) if (handle->fast_huffman_length > 0) {
867 compute_accelerated_huffman(handle, book);
868 } else {
869 book->fast_huffman[0] = -1;
870 }
871
872 /* For sparse codebooks, we've now compressed the data into our
873 * target arrays so we no longer need the original buffers. */
874 (18/18) if (book->sparse) {
875 mem_free(handle->mem_opaque, lengths);
876 mem_free(handle->mem_opaque, values);
877 mem_free(handle->mem_opaque, book->codewords);
878 book->codewords = NULL;
879 }
880
881 /* Read the vector lookup table. */
882 book->lookup_type = get_bits(handle, 4);
883 (18/18) if (book->lookup_type == 0) {
884 /* No lookup data to be read. */
885 (18/18) } else if (book->lookup_type <= 2) {
886 (18/18) if (!parse_codebook_lookup(handle, book)) {
887 return false;
888 }
889 } else { // book->lookup_type > 2
890 return error(handle, VORBIS_invalid_setup);
891 }
892
893 return true;
894 }
895
896 /*-----------------------------------------------------------------------*/
897
898 /**
899 * parse_codebooks: Parse codebook data from the setup header.
900 *
901 * [Parameters]
902 * handle: Stream handle.
903 * [Return value]
904 * True on success, false on error.
905 */
906 static NOINLINE bool parse_codebooks(stb_vorbis *handle)
907 {
908 handle->codebook_count = get_bits(handle, 8) + 1;
909 handle->codebooks = mem_alloc(
910 handle->mem_opaque, sizeof(*handle->codebooks) * handle->codebook_count, 0);
911 (18/18) if (!handle->codebooks) {
912 return error(handle, VORBIS_outofmem);
913 }
914 memset(handle->codebooks, 0,
915 sizeof(*handle->codebooks) * handle->codebook_count);
916
917 (18/18) for (int i = 0; i < handle->codebook_count; i++) {
918 (18/18) if (!parse_codebook(handle, &handle->codebooks[i])) {
919 return false;
920 }
921 }
922
923 return true;
924 }
925
926 /*-----------------------------------------------------------------------*/
927
928 /**
929 * parse_time_domain_transforms: Parse time domain transform data from the
930 * setup header. The spec declares that these are all placeholders in the
931 * current Vorbis version, so we don't actually store any data.
932 *
933 * [Parameters]
934 * handle: Stream handle.
935 */
936 static NOINLINE bool parse_time_domain_transforms(stb_vorbis *handle)
937 {
938 const int vorbis_time_count = get_bits(handle, 6) + 1;
939 (18/18) for (int i = 0; i < vorbis_time_count; i++) {
940 const uint16_t value = get_bits(handle, 16);
941 (18/18) if (value != 0) {
942 return error(handle, VORBIS_invalid_setup);
943 }
944 }
945
946 return true;
947 }
948
949 /*-----------------------------------------------------------------------*/
950
951 /**
952 * parse_floors: Parse floor data from the setup header.
953 *
954 * [Parameters]
955 * handle: Stream handle.
956 */
957 static NOINLINE bool parse_floors(stb_vorbis *handle)
958 {
959 int largest_floor0_order = 0;
960 int longest_floor1_list = 0;
961
962 handle->floor_count = get_bits(handle, 6) + 1;
963 handle->floor_config = mem_alloc(
964 handle->mem_opaque, handle->floor_count * sizeof(*handle->floor_config), 0);
965 (18/18) if (!handle->floor_config) {
966 return error(handle, VORBIS_outofmem);
967 }
968 memset(handle->floor_config, 0,
969 handle->floor_count * sizeof(*handle->floor_config));
970
971 (18/18) for (int i = 0; i < handle->floor_count; i++) {
972 handle->floor_types[i] = get_bits(handle, 16);
973
974 (18/18) if (handle->floor_types[i] == 0) {
975 Floor0 *floor = &handle->floor_config[i].floor0;
976 floor->order = get_bits(handle, 8);
977 floor->rate = get_bits(handle, 16);
978 floor->bark_map_size = get_bits(handle, 16);
979 floor->amplitude_bits = get_bits(handle, 6);
980 floor->amplitude_offset = get_bits(handle, 8);
981 floor->number_of_books = get_bits(handle, 4) + 1;
982 /* The missing "-1" on the ilog() argument is deliberate,
983 * according to the specification. (Presumably, it's an error
984 * in the original encoder/decoder which wasn't detected until
985 * after the spec was published.) */
986 floor->book_bits = ilog(floor->number_of_books);
987 (18/18) for (int j = 0; j < floor->number_of_books; j++) {
988 floor->book_list[j] = get_bits(handle, 8);
989 (18/18) if (floor->book_list[j] >= handle->codebook_count) {
990 return error(handle, VORBIS_invalid_setup);
991 }
992 }
993
994 floor->map[0] = mem_alloc(
995 handle->mem_opaque,
996 (handle->blocksize[0] + handle->blocksize[1] + 2)
997 * sizeof(*floor->map[0]),
998 0);
999 (18/18) if (!floor->map[0]) {
1000 return error(handle, VORBIS_outofmem);
1001 }
1002 floor->map[1] = floor->map[0] + (handle->blocksize[0] + 1);
1003 (18/18) for (int blocktype = 0; blocktype < 2; blocktype++) {
1004 const int n = handle->blocksize[blocktype] / 2;
1005 (18/18) for (int j = 0; j < n; j++) {
1006 floor->map[blocktype][j] = floor0_map(floor, n, j);
1007 }
1008 floor->map[blocktype][n] = -1;
1009 }
1010
1011 /* Make sure the array is allocated so the decoder doesn't
1012 * have to worry about checking for NULL, even if the floor
1013 * definition improperly specifies order zero. */
1014 (18/18) if (largest_floor0_order < 1) {
1015 largest_floor0_order = 1;
1016 }
1017 (18/18) if (floor->order > largest_floor0_order) {
1018 largest_floor0_order = floor->order;
1019 }
1020
1021 (18/18) } else if (handle->floor_types[i] == 1) {
1022 Floor1 *floor = &handle->floor_config[i].floor1;
1023 floor->partitions = get_bits(handle, 5);
1024 int max_class = -1;
1025 (18/18) for (int j = 0; j < floor->partitions; j++) {
1026 floor->partition_class_list[j] = get_bits(handle, 4);
1027 (18/18) if (floor->partition_class_list[j] > max_class) {
1028 max_class = floor->partition_class_list[j];
1029 }
1030 }
1031 (18/18) for (int j = 0; j <= max_class; j++) {
1032 floor->class_dimensions[j] = get_bits(handle, 3) + 1;
1033 floor->class_subclasses[j] = get_bits(handle, 2);
1034 (18/18) if (floor->class_subclasses[j]) {
1035 floor->class_masterbooks[j] = get_bits(handle, 8);
1036 (18/18) if (floor->class_masterbooks[j] >= handle->codebook_count) {
1037 return error(handle, VORBIS_invalid_setup);
1038 }
1039 }
1040 (18/18) for (int k = 0; k < (1 << floor->class_subclasses[j]); k++) {
1041 floor->subclass_books[j][k] = get_bits(handle, 8) - 1;
1042 (18/18) if (floor->subclass_books[j][k] >= handle->codebook_count) {
1043 return error(handle, VORBIS_invalid_setup);
1044 }
1045 }
1046 }
1047 floor->floor1_multiplier = get_bits(handle, 2) + 1;
1048 floor->rangebits = get_bits(handle, 4);
1049 floor->X_list[0] = 0;
1050 floor->X_list[1] = 1U << floor->rangebits;
1051 floor->values = 2;
1052 (18/18) for (int j = 0; j < floor->partitions; j++) {
1053 int c = floor->partition_class_list[j];
1054 (18/18) for (int k = 0; k < floor->class_dimensions[c]; k++) {
1055 (18/18) if (floor->values >= FLOOR1_X_LIST_MAX) {
1056 return error(handle, VORBIS_invalid_setup);
1057 }
1058 floor->X_list[floor->values++] =
1059 get_bits(handle, floor->rangebits);
1060 }
1061 }
1062
1063 /* We'll need to process the floor curve in X value order, so
1064 * precompute a sorted list. */
1065 ArrayElement elements[FLOOR1_X_LIST_MAX];
1066 (18/18) for (int j = 0; j < floor->values; j++) {
1067 elements[j].value = floor->X_list[j];
1068 elements[j].index = j;
1069 }
1070 qsort(elements, floor->values, sizeof(*elements),
1071 array_element_compare);
1072 (18/18) for (int j = 0; j < floor->values; j++) {
1073 (36/36) if (j > 0 && elements[j].value == elements[j-1].value) {
1074 /* 7.2.2: All vector [floor1_x_list] element values
1075 * must be unique within the vector; a non-unique
1076 * value renders the stream undecodable. */
1077 return error(handle, VORBIS_invalid_setup);
1078 }
1079 floor->sorted_order[j] = elements[j].index;
1080 }
1081
1082 /* Find the low and high neighbors for each element of X_list,
1083 * following the Vorbis definition (which only looks at the
1084 * preceding elements of the list). */
1085 (18/18) for (int j = 2; j < floor->values; j++) {
1086 const unsigned int X_j = floor->X_list[j];
1087 int low_index = 0, high_index = 1;
1088 unsigned int low = floor->X_list[0], high = floor->X_list[1];
1089 (18/18) for (int k = 2; k < j; k++) {
1090 (36/36) if (floor->X_list[k] > low && floor->X_list[k] < X_j) {
1091 low = floor->X_list[k];
1092 low_index = k;
1093 }
1094 (36/36) if (floor->X_list[k] < high && floor->X_list[k] > X_j) {
1095 high = floor->X_list[k];
1096 high_index = k;
1097 }
1098 }
1099 floor->neighbors[j].low = low_index;
1100 floor->neighbors[j].high = high_index;
1101 }
1102
1103 /* Remember the longest X_list length we've seen for allocating
1104 * the final_Y buffer later. Unlike floor 0, we don't have to
1105 * worry about forcing the array to be allocated because
1106 * floor->values will always be at least 2. */
1107 ASSERT(floor->values > 0);
1108 (18/18) if (floor->values > longest_floor1_list) {
1109 longest_floor1_list = floor->values;
1110 }
1111
1112 } else { // handle->floor_types[i] > 1
1113 return error(handle, VORBIS_invalid_setup);
1114 }
1115 }
1116
1117 (18/18) if (largest_floor0_order > 0) {
1118 handle->coefficients = alloc_channel_array(
1119 handle->mem_opaque, handle->channels,
1120 sizeof(**handle->coefficients) * largest_floor0_order, 0);
1121 (18/18) if (!handle->coefficients) {
1122 return error(handle, VORBIS_outofmem);
1123 }
1124 }
1125 (18/18) if (longest_floor1_list > 0) {
1126 handle->final_Y = alloc_channel_array(
1127 handle->mem_opaque, handle->channels,
1128 sizeof(**handle->final_Y) * longest_floor1_list, 0);
1129 (18/18) if (!handle->final_Y) {
1130 return error(handle, VORBIS_outofmem);
1131 }
1132 }
1133
1134 return true;
1135 }
1136
1137 /*-----------------------------------------------------------------------*/
1138
1139 /**
1140 * parse_residues: Parse residue data from the setup header.
1141 *
1142 * [Parameters]
1143 * handle: Stream handle.
1144 */
1145 static NOINLINE bool parse_residues(stb_vorbis *handle)
1146 {
1147 /* Maximum number of temporary array entries needed by any residue
1148 * configuration. */
1149 int residue_max_temp = 0;
1150
1151 handle->residue_count = get_bits(handle, 6) + 1;
1152 handle->residue_config = mem_alloc(
1153 handle->mem_opaque,
1154 handle->residue_count * sizeof(*handle->residue_config), 0);
1155 (18/18) if (!handle->residue_config) {
1156 return error(handle, VORBIS_outofmem);
1157 }
1158 memset(handle->residue_config, 0,
1159 handle->residue_count * sizeof(*handle->residue_config));
1160
1161 (18/18) for (int i = 0; i < handle->residue_count; i++) {
1162 Residue *r = &handle->residue_config[i];
1163 handle->residue_types[i] = get_bits(handle, 16);
1164 (18/18) if (handle->residue_types[i] > 2) {
1165 return error(handle, VORBIS_invalid_setup);
1166 }
1167
1168 r->begin = get_bits(handle, 24);
1169 r->end = get_bits(handle, 24);
1170 r->part_size = get_bits(handle, 24) + 1;
1171 r->classifications = get_bits(handle, 6) + 1;
1172 r->classbook = get_bits(handle, 8);
1173 (18/18) if (r->classbook >= handle->codebook_count) {
1174 return error(handle, VORBIS_invalid_setup);
1175 }
1176 (18/18) if (handle->codebooks[r->classbook].dimensions == 0) {
1177 return error(handle, VORBIS_invalid_setup);
1178 }
1179
1180 uint8_t residue_cascade[64];
1181 (18/18) for (int j = 0; j < r->classifications; j++) {
1182 const uint8_t low_bits = get_bits(handle,3);
1183 (18/18) const uint8_t high_bits = (get_bits(handle, 1)
1184 ? get_bits(handle, 5) : 0);
1185 residue_cascade[j] = high_bits<<3 | low_bits;
1186 }
1187
1188 r->residue_books = mem_alloc(
1189 handle->mem_opaque, sizeof(*(r->residue_books)) * r->classifications,
1190 0);
1191 (18/18) if (!r->residue_books) {
1192 return error(handle, VORBIS_outofmem);
1193 }
1194 (18/18) for (int j = 0; j < r->classifications; j++) {
1195 (18/18) for (int k = 0; k < 8; k++) {
1196 (18/18) if (residue_cascade[j] & (1 << k)) {
1197 r->residue_books[j][k] = get_bits(handle, 8);
1198 (18/18) if (r->residue_books[j][k] >= handle->codebook_count) {
1199 return error(handle, VORBIS_invalid_setup);
1200 }
1201 } else {
1202 r->residue_books[j][k] = -1;
1203 }
1204 }
1205 }
1206
1207 const int classwords = handle->codebooks[r->classbook].dimensions;
1208 r->classdata = mem_alloc(
1209 handle->mem_opaque,
1210 sizeof(*r->classdata) * handle->codebooks[r->classbook].entries, 0);
1211 (18/18) if (!r->classdata) {
1212 return error(handle, VORBIS_outofmem);
1213 }
1214 r->classdata[0] = mem_alloc(
1215 handle->mem_opaque, (handle->codebooks[r->classbook].entries
1216 * sizeof(**r->classdata) * classwords), 0);
1217 (18/18) if (!r->classdata[0]) {
1218 return error(handle, VORBIS_outofmem);
1219 }
1220 (18/18) for (int j = 0; j < handle->codebooks[r->classbook].entries; j++) {
1221 r->classdata[j] = r->classdata[0] + (j * classwords);
1222 int temp = j;
1223 (18/18) for (int k = classwords-1; k >= 0; k--) {
1224 r->classdata[j][k] = temp % r->classifications;
1225 temp /= r->classifications;
1226 }
1227 }
1228
1229 /* Calculate how many temporary array entries we need, and update
1230 * the maximum across all residue configurations. */
1231 const int temp_required = (r->end - r->begin) / r->part_size;
1232 (18/18) if (temp_required > residue_max_temp) {
1233 residue_max_temp = temp_required;
1234 }
1235 }
1236
1237 (18/18) if (handle->divides_in_residue) {
1238 handle->classifications = alloc_channel_array(
1239 handle->mem_opaque, handle->channels, residue_max_temp * sizeof(int),
1240 0);
1241 } else {
1242 handle->classifications = alloc_channel_array(
1243 handle->mem_opaque, handle->channels,
1244 residue_max_temp * sizeof(uint8_t *), 0);
1245 }
1246 (18/18) if (!handle->classifications) {
1247 return error(handle, VORBIS_outofmem);
1248 }
1249
1250 return true;
1251 }
1252
1253 /*-----------------------------------------------------------------------*/
1254
1255 /**
1256 * parse_mappings: Parse mapping data from the setup header.
1257 *
1258 * [Parameters]
1259 * handle: Stream handle.
1260 */
1261 static NOINLINE bool parse_mappings(stb_vorbis *handle)
1262 {
1263 handle->mapping_count = get_bits(handle, 6) + 1;
1264 handle->mapping = mem_alloc(
1265 handle->mem_opaque, handle->mapping_count * sizeof(*handle->mapping), 0);
1266 (18/18) if (!handle->mapping) {
1267 return error(handle, VORBIS_outofmem);
1268 }
1269 memset(handle->mapping, 0,
1270 handle->mapping_count * sizeof(*handle->mapping));
1271 handle->mapping[0].mux = mem_alloc(
1272 handle->mem_opaque, (handle->mapping_count * handle->channels
1273 * sizeof(*(handle->mapping[0].mux))), 0);
1274 (18/18) if (!handle->mapping[0].mux) {
1275 return error(handle, VORBIS_outofmem);
1276 }
1277 (18/18) for (int i = 1; i < handle->mapping_count; i++) {
1278 handle->mapping[i].mux =
1279 handle->mapping[0].mux + (i * handle->channels);
1280 }
1281
1282 (18/18) for (int i = 0; i < handle->mapping_count; i++) {
1283 Mapping *m = &handle->mapping[i];
1284 int mapping_type = get_bits(handle, 16);
1285 (18/18) if (mapping_type != 0) {
1286 return error(handle, VORBIS_invalid_setup);
1287 }
1288 (18/18) if (get_bits(handle, 1)) {
1289 m->submaps = get_bits(handle, 4) + 1;
1290 } else {
1291 m->submaps = 1;
1292 }
1293
1294 (18/18) if (get_bits(handle, 1)) {
1295 m->coupling_steps = get_bits(handle, 8) + 1;
1296 m->coupling = mem_alloc(
1297 handle->mem_opaque, m->coupling_steps * sizeof(*m->coupling), 0);
1298 (18/18) if (!m->coupling) {
1299 return error(handle, VORBIS_outofmem);
1300 }
1301 (18/18) for (int j = 0; j < m->coupling_steps; j++) {
1302 m->coupling[j].magnitude =
1303 get_bits(handle, ilog(handle->channels - 1));
1304 m->coupling[j].angle =
1305 get_bits(handle, ilog(handle->channels - 1));
1306 (18/18) if (m->coupling[j].magnitude >= handle->channels
1307 (18/18) || m->coupling[j].angle >= handle->channels
1308 (18/18) || m->coupling[j].magnitude == m->coupling[j].angle) {
1309 return error(handle, VORBIS_invalid_setup);
1310 }
1311 }
1312 } else {
1313 m->coupling_steps = 0;
1314 m->coupling = NULL;
1315 }
1316
1317 (18/18) if (get_bits(handle, 2)) { // Reserved field, must be zero.
1318 return error(handle, VORBIS_invalid_setup);
1319 }
1320
1321 (18/18) if (m->submaps > 1) {
1322 (18/18) for (int j = 0; j < handle->channels; j++) {
1323 m->mux[j] = get_bits(handle, 4);
1324 (18/18) if (m->mux[j] >= m->submaps) {
1325 return error(handle, VORBIS_invalid_setup);
1326 }
1327 }
1328 } else {
1329 /* The specification doesn't explicitly say what to store in
1330 * the mux array for this case, but since the values are used
1331 * to index the submap list, it should be safe to assume that
1332 * all values are set to zero (the only valid submap index). */
1333 (18/18) for (int j = 0; j < handle->channels; j++) {
1334 m->mux[j] = 0;
1335 }
1336 }
1337
1338 (18/18) for (int j = 0; j < m->submaps; j++) {
1339 get_bits(handle, 8); // Unused time configuration placeholder.
1340 m->submap_floor[j] = get_bits(handle, 8);
1341 m->submap_residue[j] = get_bits(handle, 8);
1342 (18/18) if (m->submap_floor[j] >= handle->floor_count
1343 (18/18) || m->submap_residue[j] >= handle->residue_count) {
1344 return error(handle, VORBIS_invalid_setup);
1345 }
1346 }
1347 }
1348
1349 return true;
1350 }
1351
1352 /*-----------------------------------------------------------------------*/
1353
1354 /**
1355 * parse_modes: Parse mode data from the setup header.
1356 *
1357 * [Parameters]
1358 * handle: Stream handle.
1359 */
1360 static NOINLINE bool parse_modes(stb_vorbis *handle)
1361 {
1362 handle->mode_count = get_bits(handle, 6) + 1;
1363 handle->mode_bits = ilog(handle->mode_count - 1);
1364 (18/18) for (int i = 0; i < handle->mode_count; i++) {
1365 Mode *m = &handle->mode_config[i];
1366 m->blockflag = get_bits(handle, 1);
1367 m->windowtype = get_bits(handle, 16);
1368 m->transformtype = get_bits(handle, 16);
1369 m->mapping = get_bits(handle, 8);
1370 (18/18) if (m->windowtype != 0
1371 (18/18) || m->transformtype != 0
1372 (18/18) || m->mapping >= handle->mapping_count) {
1373 return error(handle, VORBIS_invalid_setup);
1374 }
1375 }
1376
1377 return true;
1378 }
1379
1380 /*************************************************************************/
1381 /*********************** Top-level packet parsers ************************/
1382 /*************************************************************************/
1383
1384 /**
1385 * parse_ident_header: Parse the Vorbis identification header packet.
1386 * The packet length is assumed to have been validated as 30 bytes, and
1387 * the 7-byte packet header is assumed to have already been read.
1388 *
1389 * [Parameters]
1390 * handle: Stream handle.
1391 * [Return value]
1392 * True on success, false on error.
1393 */
1394 static NOINLINE bool parse_ident_header(stb_vorbis *handle)
1395 {
1396 const uint32_t vorbis_version = get32_packet(handle);
1397 const int audio_channels = get8_packet(handle);
1398 const uint32_t audio_sample_rate = get32_packet(handle);
1399 const int32_t bitrate_maximum = get32_packet(handle);
1400 const int32_t bitrate_nominal = get32_packet(handle);
1401 const int32_t bitrate_minimum = get32_packet(handle);
1402 const int log2_blocksize = get8_packet(handle);
1403 const int framing_flag = get8_packet(handle);
1404 ASSERT(framing_flag != EOP);
1405 ASSERT(get8_packet(handle) == EOP);
1406
1407 const int log2_blocksize_0 = (log2_blocksize >> 0) & 15;
1408 const int log2_blocksize_1 = (log2_blocksize >> 4) & 15;
1409
1410 (18/18) if (vorbis_version != 0
1411 (18/18) || audio_channels == 0
1412 (18/18) || audio_sample_rate == 0
1413 (18/18) || !(framing_flag & 1)) {
1414 return error(handle, VORBIS_invalid_first_page);
1415 }
1416 (18/18) if (log2_blocksize_0 < 6
1417 (18/18) || log2_blocksize_0 > 13
1418 (18/18) || log2_blocksize_1 < log2_blocksize_0
1419 (18/18) || log2_blocksize_1 > 13) {
1420 return error(handle, VORBIS_invalid_setup);
1421 }
1422
1423 handle->channels = audio_channels;
1424 handle->sample_rate = audio_sample_rate;
1425 handle->nominal_bitrate = bitrate_nominal;
1426 handle->min_bitrate = bitrate_minimum;
1427 handle->max_bitrate = bitrate_maximum;
1428 handle->blocksize[0] = 1 << log2_blocksize_0;
1429 handle->blocksize[1] = 1 << log2_blocksize_1;
1430 handle->blocksize_bits[0] = log2_blocksize_0;
1431 handle->blocksize_bits[1] = log2_blocksize_1;
1432 return true;
1433 }
1434
1435 /*-----------------------------------------------------------------------*/
1436
1437 /**
1438 * parse_setup_header: Parse the Vorbis setup header packet. The 7-byte
1439 * packet header is assumed to have already been read.
1440 *
1441 * [Parameters]
1442 * handle: Stream handle.
1443 * [Return value]
1444 * True on success, false on error.
1445 */
1446 static NOINLINE bool parse_setup_header(stb_vorbis *handle)
1447 {
1448 (18/18) if (!parse_codebooks(handle)) {
1449 return false;
1450 }
1451 (18/18) if (!parse_time_domain_transforms(handle)) {
1452 return false;
1453 }
1454 (18/18) if (!parse_floors(handle)) {
1455 return false;
1456 }
1457 (18/18) if (!parse_residues(handle)) {
1458 return false;
1459 }
1460 (18/18) if (!parse_mappings(handle)) {
1461 return false;
1462 }
1463 (18/18) if (!parse_modes(handle)) {
1464 return false;
1465 }
1466
1467 (18/18) if (get_bits(handle, 1) != 1) { // Also catches EOP.
1468 return error(handle, VORBIS_invalid_setup);
1469 }
1470 flush_packet(handle);
1471
1472 return true;
1473 }
1474
1475 /*************************************************************************/
1476 /************************** Interface routines ***************************/
1477 /*************************************************************************/
1478
1479 bool start_decoder(
1480 stb_vorbis *handle, const void *id_packet, int32_t id_packet_len,
1481 const void *setup_packet, int32_t setup_packet_len)
1482 {
1483 /* Initialize the CRC lookup table, if necessary. This function
1484 * modifies global state but is multithread-safe, so we just call it
1485 * unconditionally. */
1486 crc32_init();
1487
1488 (18/18) if (handle->packet_mode) {
1489 ASSERT(id_packet);
1490 ASSERT(id_packet_len > 0);
1491 start_packet_direct(handle, id_packet, id_packet_len);
1492 } else {
1493 /* Check for and parse the identification header packet. The spec
1494 * requires that this packet is the only packet in the first Ogg
1495 * page of the stream. We follow this requirement to ensure that
1496 * we're looking at a valid Ogg Vorbis stream. */
1497 (18/18) if (!start_page(handle, false)) {
1498 return false;
1499 }
1500 (18/18) if (handle->page_flag != PAGEFLAG_first_page
1501 (18/18) || handle->segment_count != 1
1502 (18/18) || handle->segments[0] != 30) {
1503 return error(handle, VORBIS_invalid_first_page);
1504 }
1505 ASSERT(start_packet(handle));
1506 }
1507 (18/18) if (validate_header_packet(handle) != VORBIS_packet_ident) {
1508 return error(handle, VORBIS_invalid_first_page);
1509 }
1510 (18/18) if (!parse_ident_header(handle)) {
1511 return false;
1512 }
1513
1514 /* Set up stream parameters and allocate buffers based on the stream
1515 * format. */
1516 (18/18) for (int i = 0; i < 2; i++) {
1517 (13/18) if (!init_blocksize(handle, i)) {
1518 return false;
1519 }
1520 }
1521 /* 16-byte alignment to help out vectorized loops. */
1522 handle->channel_buffers[0] = alloc_channel_array(
1523 handle->mem_opaque, handle->channels*2,
1524 sizeof(float) * handle->blocksize[1], BUFFER_ALIGN);
1525 handle->channel_buffers[1] = handle->channel_buffers[0] + handle->channels;
1526 handle->outputs = mem_alloc(
1527 handle->mem_opaque, handle->channels * sizeof(float *), BUFFER_ALIGN);
1528 handle->previous_window = mem_alloc(
1529 handle->mem_opaque, handle->channels * sizeof(float *), BUFFER_ALIGN);
1530 handle->imdct_temp_buf = mem_alloc(
1531 handle->mem_opaque,
1532 (handle->blocksize[1] / 2) * sizeof(*handle->imdct_temp_buf),
1533 BUFFER_ALIGN);
1534 (18/18) if (!handle->channel_buffers[0]
1535 (18/18) || !handle->outputs
1536 (18/18) || !handle->previous_window
1537 (18/18) || !handle->imdct_temp_buf) {
1538 return error(handle, VORBIS_outofmem);
1539 }
1540 (18/18) for (int i = 0; i < handle->channels; i++) {
1541 memset(handle->channel_buffers[0][i], 0,
1542 sizeof(float) * handle->blocksize[1]);
1543 memset(handle->channel_buffers[1][i], 0,
1544 sizeof(float) * handle->blocksize[1]);
1545 }
1546
1547 (18/18) if (handle->packet_mode) {
1548 ASSERT(setup_packet);
1549 ASSERT(setup_packet_len > 0);
1550 start_packet_direct(handle, setup_packet, setup_packet_len);
1551 (18/18) if (validate_header_packet(handle) != VORBIS_packet_setup) {
1552 return error(handle, VORBIS_invalid_stream);
1553 }
1554 } else {
1555 /* The second Ogg page (and possibly subsequent pages) should
1556 * contain the comment and setup headers. The spec requires both
1557 * headers to exist in that order, but in the spirit of being
1558 * liberal with what we accept, we also allow the comment header
1559 * to be missing. */
1560 bool got_setup_header = false;
1561 (18/18) while (!got_setup_header) {
1562 (18/18) if (!start_packet(handle)) {
1563 return false;
1564 }
1565 const int type = validate_header_packet(handle);
1566 (27/27) switch (type) {
1567 case VORBIS_packet_comment:
1568 /* Currently, we don't attempt to parse anything out of the
1569 * comment header. */
1570 flush_packet(handle);
1571 break;
1572 case VORBIS_packet_setup:
1573 got_setup_header = true;
1574 break;
1575 default:
1576 return error(handle, VORBIS_invalid_stream);
1577 }
1578 }
1579 }
1580 (18/18) if (!parse_setup_header(handle)) {
1581 return false;
1582 }
1583
1584 /* Set up remaining state parameters for decoding. */
1585 handle->previous_length = 0;
1586 handle->first_decode = true;
1587 (18/18) if (handle->stream_len >= 0) {
1588 handle->p_first.page_start =
1589 (*handle->tell_callback)(handle->io_opaque);
1590 }
1591
1592 return true;
1593 }
1594
1595 /*************************************************************************/
1596 /*************************************************************************/