Debian Codegraph @

dokidoki-support/stb_vorbis.c

raw symbols SCIP
1 // Ogg Vorbis I audio decoder -- version 0.99996
2 //
3 // Written in April 2007 by Sean Barrett, sponsored by RAD Game Tools.
4 //
5 // Placed in the public domain April 2007 by the author: no copyright is
6 // claimed, and you may use it for any purpose you like.
7 //
8 // No warranty for any purpose is expressed or implied by the author (nor
9 // by RAD Game Tools). Report bugs and send enhancements to the author.
10 //
11 // Get the latest version and other information at:
12 // http://nothings.org/stb_vorbis/
13
14
15 // Todo:
16 //
17 // - seeking (note you can seek yourself using the pushdata API)
18 //
19 // Limitations:
20 //
21 // - floor 0 not supported (used in old ogg vorbis files)
22 // - lossless sample-truncation at beginning ignored
23 // - cannot concatenate multiple vorbis streams
24 // - sample positions are 32-bit, limiting seekable 192Khz
25 // files to around 6 hours (Ogg supports 64-bit)
26 //
27 // All of these limitations may be removed in future versions.
28
29
30 //////////////////////////////////////////////////////////////////////////////
31 //
32 // HEADER BEGINS HERE
33 //
34
35 #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
36 #define STB_VORBIS_INCLUDE_STB_VORBIS_H
37
38 #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
39 #define STB_VORBIS_NO_STDIO 1
40 #endif
41
42 #ifndef STB_VORBIS_NO_STDIO
43 #include <stdio.h>
44 #endif
45
46 #ifdef __cplusplus
47 extern "C" {
48 #endif
49
50 /////////// THREAD SAFETY
51
52 // Individual stb_vorbis* handles are not thread-safe; you cannot decode from
53 // them from multiple threads at the same time. However, you can have multiple
54 // stb_vorbis* handles and decode from them independently in multiple thrads.
55
56
57 /////////// MEMORY ALLOCATION
58
59 // normally stb_vorbis uses malloc() to allocate memory at startup,
60 // and alloca() to allocate temporary memory during a frame on the
61 // stack. (Memory consumption will depend on the amount of setup
62 // data in the file and how you set the compile flags for speed
63 // vs. size. In my test files the maximal-size usage is ~150KB.)
64 //
65 // You can modify the wrapper functions in the source (setup_malloc,
66 // setup_temp_malloc, temp_malloc) to change this behavior, or you
67 // can use a simpler allocation model: you pass in a buffer from
68 // which stb_vorbis will allocate _all_ its memory (including the
69 // temp memory). "open" may fail with a VORBIS_outofmem if you
70 // do not pass in enough data; there is no way to determine how
71 // much you do need except to succeed (at which point you can
72 // query get_info to find the exact amount required. yes I know
73 // this is lame).
74 //
75 // If you pass in a non-NULL buffer of the type below, allocation
76 // will occur from it as described above. Otherwise just pass NULL
77 // to use malloc()/alloca()
78
79 typedef struct
80 {
81 char *alloc_buffer;
82 int alloc_buffer_length_in_bytes;
83 } stb_vorbis_alloc;
84
85
86 /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
87
88 typedef struct stb_vorbis stb_vorbis;
89
90 typedef struct
91 {
92 unsigned int sample_rate;
93 int channels;
94
95 unsigned int setup_memory_required;
96 unsigned int setup_temp_memory_required;
97 unsigned int temp_memory_required;
98
99 int max_frame_size;
100 } stb_vorbis_info;
101
102 // get general information about the file
103 extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
104
105 // get the last error detected (clears it, too)
106 extern int stb_vorbis_get_error(stb_vorbis *f);
107
108 // close an ogg vorbis file and free all memory in use
109 extern void stb_vorbis_close(stb_vorbis *f);
110
111 // this function returns the offset (in samples) from the beginning of the
112 // file that will be returned by the next decode, if it is known, or -1
113 // otherwise. after a flush_pushdata() call, this may take a while before
114 // it becomes valid again.
115 // NOT WORKING YET after a seek with PULLDATA API
116 extern int stb_vorbis_get_sample_offset(stb_vorbis *f);
117
118 // returns the current seek point within the file, or offset from the beginning
119 // of the memory buffer. In pushdata mode it returns 0.
120 extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
121
122 /////////// PUSHDATA API
123
124 #ifndef STB_VORBIS_NO_PUSHDATA_API
125
126 // this API allows you to get blocks of data from any source and hand
127 // them to stb_vorbis. you have to buffer them; stb_vorbis will tell
128 // you how much it used, and you have to give it the rest next time;
129 // and stb_vorbis may not have enough data to work with and you will
130 // need to give it the same data again PLUS more. Note that the Vorbis
131 // specification does not bound the size of an individual frame.
132
133 extern stb_vorbis *stb_vorbis_open_pushdata(
134 unsigned char *datablock, int datablock_length_in_bytes,
135 int *datablock_memory_consumed_in_bytes,
136 int *error,
137 stb_vorbis_alloc *alloc_buffer);
138 // create a vorbis decoder by passing in the initial data block containing
139 // the ogg&vorbis headers (you don't need to do parse them, just provide
140 // the first N bytes of the file--you're told if it's not enough, see below)
141 // on success, returns an stb_vorbis *, does not set error, returns the amount of
142 // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
143 // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
144 // if returns NULL and *error is VORBIS_need_more_data, then the input block was
145 // incomplete and you need to pass in a larger block from the start of the file
146
147 extern int stb_vorbis_decode_frame_pushdata(
148 stb_vorbis *f, unsigned char *datablock, int datablock_length_in_bytes,
149 int *channels, // place to write number of float * buffers
150 float ***output, // place to write float ** array of float * buffers
151 int *samples // place to write number of output samples
152 );
153 // decode a frame of audio sample data if possible from the passed-in data block
154 //
155 // return value: number of bytes we used from datablock
156 // possible cases:
157 // 0 bytes used, 0 samples output (need more data)
158 // N bytes used, 0 samples output (resynching the stream, keep going)
159 // N bytes used, M samples output (one frame of data)
160 // note that after opening a file, you will ALWAYS get one N-bytes,0-sample
161 // frame, because Vorbis always "discards" the first frame.
162 //
163 // Note that on resynch, stb_vorbis will rarely consume all of the buffer,
164 // instead only datablock_length_in_bytes-3 or less. This is because it wants
165 // to avoid missing parts of a page header if they cross a datablock boundary,
166 // without writing state-machiney code to record a partial detection.
167 //
168 // The number of channels returned are stored in *channels (which can be
169 // NULL--it is always the same as the number of channels reported by
170 // get_info). *output will contain an array of float* buffers, one per
171 // channel. In other words, (*output)[0][0] contains the first sample from
172 // the first channel, and (*output)[1][0] contains the first sample from
173 // the second channel.
174
175 extern void stb_vorbis_flush_pushdata(stb_vorbis *f);
176 // inform stb_vorbis that your next datablock will not be contiguous with
177 // previous ones (e.g. you've seeked in the data); future attempts to decode
178 // frames will cause stb_vorbis to resynchronize (as noted above), and
179 // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
180 // will begin decoding the _next_ frame.
181 //
182 // if you want to seek using pushdata, you need to seek in your file, then
183 // call stb_vorbis_flush_pushdata(), then start calling decoding, then once
184 // decoding is returning you data, call stb_vorbis_get_sample_offset, and
185 // if you don't like the result, seek your file again and repeat.
186 #endif
187
188
189 ////////// PULLING INPUT API
190
191 #ifndef STB_VORBIS_NO_PULLDATA_API
192 // This API assumes stb_vorbis is allowed to pull data from a source--
193 // either a block of memory containing the _entire_ vorbis stream, or a
194 // FILE * that you or it create, or possibly some other reading mechanism
195 // if you go modify the source to replace the FILE * case with some kind
196 // of callback to your code. (But if you don't support seeking, you may
197 // just want to go ahead and use pushdata.)
198
199 #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
200 extern int stb_vorbis_decode_filename(char *filename, int *channels, short **output);
201 #endif
202 extern int stb_vorbis_decode_memory(unsigned char *mem, int len, int *channels, short **output);
203 // decode an entire file and output the data interleaved into a malloc()ed
204 // buffer stored in *output. The return value is the number of samples
205 // decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
206 // When you're done with it, just free() the pointer returned in *output.
207
208 extern stb_vorbis * stb_vorbis_open_memory(unsigned char *data, int len,
209 int *error, stb_vorbis_alloc *alloc_buffer);
210 // create an ogg vorbis decoder from an ogg vorbis stream in memory (note
211 // this must be the entire stream!). on failure, returns NULL and sets *error
212
213 #ifndef STB_VORBIS_NO_STDIO
214 extern stb_vorbis * stb_vorbis_open_filename(char *filename,
215 int *error, stb_vorbis_alloc *alloc_buffer);
216 // create an ogg vorbis decoder from a filename via fopen(). on failure,
217 // returns NULL and sets *error (possibly to VORBIS_file_open_failure).
218
219 extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
220 int *error, stb_vorbis_alloc *alloc_buffer);
221 // create an ogg vorbis decoder from an open FILE *, looking for a stream at
222 // the _current_ seek point (ftell). on failure, returns NULL and sets *error.
223 // note that stb_vorbis must "own" this stream; if you seek it in between
224 // calls to stb_vorbis, it will become confused. Morever, if you attempt to
225 // perform stb_vorbis_seek_*() operations on this file, it will assume it
226 // owns the _entire_ rest of the file after the start point. Use the next
227 // function, stb_vorbis_open_file_section(), to limit it.
228
229 extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
230 int *error, stb_vorbis_alloc *alloc_buffer, unsigned int len);
231 // create an ogg vorbis decoder from an open FILE *, looking for a stream at
232 // the _current_ seek point (ftell); the stream will be of length 'len' bytes.
233 // on failure, returns NULL and sets *error. note that stb_vorbis must "own"
234 // this stream; if you seek it in between calls to stb_vorbis, it will become
235 // confused.
236 #endif
237
238 extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
239 extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
240 // NOT WORKING YET
241 // these functions seek in the Vorbis file to (approximately) 'sample_number'.
242 // after calling seek_frame(), the next call to get_frame_*() will include
243 // the specified sample. after calling stb_vorbis_seek(), the next call to
244 // stb_vorbis_get_samples_* will start with the specified sample. If you
245 // do not need to seek to EXACTLY the target sample when using get_samples_*,
246 // you can also use seek_frame().
247
248 extern void stb_vorbis_seek_start(stb_vorbis *f);
249 // this function is equivalent to stb_vorbis_seek(f,0), but it
250 // actually works
251
252 extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
253 extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
254 // these functions return the total length of the vorbis stream
255
256 extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
257 // decode the next frame and return the number of samples. the number of
258 // channels returned are stored in *channels (which can be NULL--it is always
259 // the same as the number of channels reported by get_info). *output will
260 // contain an array of float* buffers, one per channel. These outputs will
261 // be overwritten on the next call to stb_vorbis_get_frame_*.
262 //
263 // You generally should not intermix calls to stb_vorbis_get_frame_*()
264 // and stb_vorbis_get_samples_*(), since the latter calls the former.
265
266 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
267 extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
268 extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
269 #endif
270 // decode the next frame and return the number of samples per channel. the
271 // data is coerced to the number of channels you request according to the
272 // channel coercion rules (see below). You must pass in the size of your
273 // buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
274 // The maximum buffer size needed can be gotten from get_info(); however,
275 // the Vorbis I specification implies an absolute maximum of 4096 samples
276 // per channel. Note that for interleaved data, you pass in the number of
277 // shorts (the size of your array), but the return value is the number of
278 // samples per channel, not the total number of samples.
279
280 // Channel coercion rules:
281 // Let M be the number of channels requested, and N the number of channels present,
282 // and Cn be the nth channel; let stereo L be the sum of all L and center channels,
283 // and stereo R be the sum of all R and center channels (channel assignment from the
284 // vorbis spec).
285 // M N output
286 // 1 k sum(Ck) for all k
287 // 2 * stereo L, stereo R
288 // k l k > l, the first l channels, then 0s
289 // k l k <= l, the first k channels
290 // Note that this is not _good_ surround etc. mixing at all! It's just so
291 // you get something useful.
292
293 extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
294 extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
295 // gets num_samples samples, not necessarily on a frame boundary--this requires
296 // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
297 // Returns the number of samples stored per channel; it may be less than requested
298 // at the end of the file. If there are no more samples in the file, returns 0.
299
300 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
301 extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
302 extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
303 #endif
304 // gets num_samples samples, not necessarily on a frame boundary--this requires
305 // buffering so you have to supply the buffers. Applies the coercion rules above
306 // to produce 'channels' channels. Returns the number of samples stored per channel;
307 // it may be less than requested at the end of the file. If there are no more
308 // samples in the file, returns 0.
309
310 #endif
311
312 //////// ERROR CODES
313
314 enum STBVorbisError
315 {
316 VORBIS__no_error,
317
318 VORBIS_need_more_data=1, // not a real error
319
320 VORBIS_invalid_api_mixing, // can't mix API modes
321 VORBIS_outofmem, // not enough memory
322 VORBIS_feature_not_supported, // uses floor 0
323 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
324 VORBIS_file_open_failure, // fopen() failed
325 VORBIS_seek_without_length, // can't seek in unknown-length file
326
327 VORBIS_unexpected_eof=10, // file is truncated?
328 VORBIS_seek_invalid, // seek past EOF
329
330 // decoding errors (corrupt/invalid stream) -- you probably
331 // don't care about the exact details of these
332
333 // vorbis errors:
334 VORBIS_invalid_setup=20,
335 VORBIS_invalid_stream,
336
337 // ogg errors:
338 VORBIS_missing_capture_pattern=30,
339 VORBIS_invalid_stream_structure_version,
340 VORBIS_continued_packet_flag_invalid,
341 VORBIS_incorrect_stream_serial_number,
342 VORBIS_invalid_first_page,
343 VORBIS_bad_packet_type,
344 VORBIS_cant_find_last_page,
345 VORBIS_seek_failed,
346 };
347
348
349 #ifdef __cplusplus
350 }
351 #endif
352
353 #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
354 //
355 // HEADER ENDS HERE
356 //
357 //////////////////////////////////////////////////////////////////////////////
358
359 #ifndef STB_VORBIS_HEADER_ONLY
360
361 // global configuration settings (e.g. set these in the project/makefile),
362 // or just set them in this file at the top (although ideally the first few
363 // should be visible when the header file is compiled too, although it's not
364 // crucial)
365
366 // STB_VORBIS_NO_PUSHDATA_API
367 // does not compile the code for the various stb_vorbis_*_pushdata()
368 // functions
369 // #define STB_VORBIS_NO_PUSHDATA_API
370
371 // STB_VORBIS_NO_PULLDATA_API
372 // does not compile the code for the non-pushdata APIs
373 // #define STB_VORBIS_NO_PULLDATA_API
374
375 // STB_VORBIS_NO_STDIO
376 // does not compile the code for the APIs that use FILE *s internally
377 // or externally (implied by STB_VORBIS_NO_PULLDATA_API)
378 // #define STB_VORBIS_NO_STDIO
379
380 // STB_VORBIS_NO_INTEGER_CONVERSION
381 // does not compile the code for converting audio sample data from
382 // float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
383 // #define STB_VORBIS_NO_INTEGER_CONVERSION
384
385 // STB_VORBIS_NO_FAST_SCALED_FLOAT
386 // does not use a fast float-to-int trick to accelerate float-to-int on
387 // most platforms which requires endianness be defined correctly.
388 //#define STB_VORBIS_NO_FAST_SCALED_FLOAT
389
390
391 // STB_VORBIS_MAX_CHANNELS [number]
392 // globally define this to the maximum number of channels you need.
393 // The spec does not put a restriction on channels except that
394 // the count is stored in a byte, so 255 is the hard limit.
395 // Reducing this saves about 16 bytes per value, so using 16 saves
396 // (255-16)*16 or around 4KB. Plus anything other memory usage
397 // I forgot to account for. Can probably go as low as 8 (7.1 audio),
398 // 6 (5.1 audio), or 2 (stereo only).
399 #ifndef STB_VORBIS_MAX_CHANNELS
400 #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
401 #endif
402
403 // STB_VORBIS_PUSHDATA_CRC_COUNT [number]
404 // after a flush_pushdata(), stb_vorbis begins scanning for the
405 // next valid page, without backtracking. when it finds something
406 // that looks like a page, it streams through it and verifies its
407 // CRC32. Should that validation fail, it keeps scanning. But it's
408 // possible that _while_ streaming through to check the CRC32 of
409 // one candidate page, it sees another candidate page. This #define
410 // determines how many "overlapping" candidate pages it can search
411 // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
412 // garbage pages could be as big as 64KB, but probably average ~16KB.
413 // So don't hose ourselves by scanning an apparent 64KB page and
414 // missing a ton of real ones in the interim; so minimum of 2
415 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
416 #define STB_VORBIS_PUSHDATA_CRC_COUNT 4
417 #endif
418
419 // STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
420 // sets the log size of the huffman-acceleration table. Maximum
421 // supported value is 24. with larger numbers, more decodings are O(1),
422 // but the table size is larger so worse cache missing, so you'll have
423 // to probe (and try multiple ogg vorbis files) to find the sweet spot.
424 #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
425 #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
426 #endif
427
428 // STB_VORBIS_FAST_BINARY_LENGTH [number]
429 // sets the log size of the binary-search acceleration table. this
430 // is used in similar fashion to the fast-huffman size to set initial
431 // parameters for the binary search
432
433 // STB_VORBIS_FAST_HUFFMAN_INT
434 // The fast huffman tables are much more efficient if they can be
435 // stored as 16-bit results instead of 32-bit results. This restricts
436 // the codebooks to having only 65535 possible outcomes, though.
437 // (At least, accelerated by the huffman table.)
438 #ifndef STB_VORBIS_FAST_HUFFMAN_INT
439 #define STB_VORBIS_FAST_HUFFMAN_SHORT
440 #endif
441
442 // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
443 // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
444 // back on binary searching for the correct one. This requires storing
445 // extra tables with the huffman codes in sorted order. Defining this
446 // symbol trades off space for speed by forcing a linear search in the
447 // non-fast case, except for "sparse" codebooks.
448 // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
449
450 // STB_VORBIS_DIVIDES_IN_RESIDUE
451 // stb_vorbis precomputes the result of the scalar residue decoding
452 // that would otherwise require a divide per chunk. you can trade off
453 // space for time by defining this symbol.
454 // #define STB_VORBIS_DIVIDES_IN_RESIDUE
455
456 // STB_VORBIS_DIVIDES_IN_CODEBOOK
457 // vorbis VQ codebooks can be encoded two ways: with every case explicitly
458 // stored, or with all elements being chosen from a small range of values,
459 // and all values possible in all elements. By default, stb_vorbis expands
460 // this latter kind out to look like the former kind for ease of decoding,
461 // because otherwise an integer divide-per-vector-element is required to
462 // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
463 // trade off storage for speed.
464 //#define STB_VORBIS_DIVIDES_IN_CODEBOOK
465
466 // STB_VORBIS_CODEBOOK_SHORTS
467 // The vorbis file format encodes VQ codebook floats as ax+b where a and
468 // b are floating point per-codebook constants, and x is a 16-bit int.
469 // Normally, stb_vorbis decodes them to floats rather than leaving them
470 // as 16-bit ints and computing ax+b while decoding. This is a speed/space
471 // tradeoff; you can save space by defining this flag.
472 #ifndef STB_VORBIS_CODEBOOK_SHORTS
473 #define STB_VORBIS_CODEBOOK_FLOATS
474 #endif
475
476 // STB_VORBIS_DIVIDE_TABLE
477 // this replaces small integer divides in the floor decode loop with
478 // table lookups. made less than 1% difference, so disabled by default.
479
480 // STB_VORBIS_NO_INLINE_DECODE
481 // disables the inlining of the scalar codebook fast-huffman decode.
482 // might save a little codespace; useful for debugging
483 // #define STB_VORBIS_NO_INLINE_DECODE
484
485 // STB_VORBIS_NO_DEFER_FLOOR
486 // Normally we only decode the floor without synthesizing the actual
487 // full curve. We can instead synthesize the curve immediately. This
488 // requires more memory and is very likely slower, so I don't think
489 // you'd ever want to do it except for debugging.
490 // #define STB_VORBIS_NO_DEFER_FLOOR
491
492
493
494
495 //////////////////////////////////////////////////////////////////////////////
496
497 #ifdef STB_VORBIS_NO_PULLDATA_API
498 #define STB_VORBIS_NO_INTEGER_CONVERSION
499 #define STB_VORBIS_NO_STDIO
500 #endif
501
502 #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
503 #define STB_VORBIS_NO_STDIO 1
504 #endif
505
506 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
507 #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
508
509 // only need endianness for fast-float-to-int, which we don't
510 // use for pushdata
511
512 #ifndef STB_VORBIS_BIG_ENDIAN
513 #define STB_VORBIS_ENDIAN 0
514 #else
515 #define STB_VORBIS_ENDIAN 1
516 #endif
517
518 #endif
519 #endif
520
521
522 #ifndef STB_VORBIS_NO_STDIO
523 #include <stdio.h>
524 #endif
525
526 #ifndef STB_VORBIS_NO_CRT
527 #include <stdlib.h>
528 #include <string.h>
529 #include <assert.h>
530 #include <math.h>
531 #if !(defined(__APPLE__) || defined(MACOSX) || defined(macintosh) || defined(Macintosh))
532 #include <malloc.h>
533 #endif
534 #else
535 #define NULL 0
536 #endif
537
538 #ifndef _MSC_VER
539 #if __GNUC__
540 #define __forceinline inline
541 #else
542 #define __forceinline
543 #endif
544 #endif
545
546 #if STB_VORBIS_MAX_CHANNELS > 256
547 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
548 #endif
549
550 #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
551 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
552 #endif
553
554
555 #define MAX_BLOCKSIZE_LOG 13 // from specification
556 #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
557
558
559 typedef unsigned char uint8;
560 typedef signed char int8;
561 typedef unsigned short uint16;
562 typedef signed short int16;
563 typedef unsigned int uint32;
564 typedef signed int int32;
565
566 #ifndef TRUE
567 #define TRUE 1
568 #define FALSE 0
569 #endif
570
571 #ifdef STB_VORBIS_CODEBOOK_FLOATS
572 typedef float codetype;
573 #else
574 typedef uint16 codetype;
575 #endif
576
577 // @NOTE
578 //
579 // Some arrays below are tagged "//varies", which means it's actually
580 // a variable-sized piece of data, but rather than malloc I assume it's
581 // small enough it's better to just allocate it all together with the
582 // main thing
583 //
584 // Most of the variables are specified with the smallest size I could pack
585 // them into. It might give better performance to make them all full-sized
586 // integers. It should be safe to freely rearrange the structures or change
587 // the sizes larger--nothing relies on silently truncating etc., nor the
588 // order of variables.
589
590 #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
591 #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
592
593 typedef struct
594 {
595 int dimensions, entries;
596 uint8 *codeword_lengths;
597 float minimum_value;
598 float delta_value;
599 uint8 value_bits;
600 uint8 lookup_type;
601 uint8 sequence_p;
602 uint8 sparse;
603 uint32 lookup_values;
604 codetype *multiplicands;
605 uint32 *codewords;
606 #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
607 int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
608 #else
609 int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
610 #endif
611 uint32 *sorted_codewords;
612 int *sorted_values;
613 int sorted_entries;
614 } Codebook;
615
616 typedef struct
617 {
618 uint8 order;
619 uint16 rate;
620 uint16 bark_map_size;
621 uint8 amplitude_bits;
622 uint8 amplitude_offset;
623 uint8 number_of_books;
624 uint8 book_list[16]; // varies
625 } Floor0;
626
627 typedef struct
628 {
629 uint8 partitions;
630 uint8 partition_class_list[32]; // varies
631 uint8 class_dimensions[16]; // varies
632 uint8 class_subclasses[16]; // varies
633 uint8 class_masterbooks[16]; // varies
634 int16 subclass_books[16][8]; // varies
635 uint16 Xlist[31*8+2]; // varies
636 uint8 sorted_order[31*8+2];
637 uint8 neighbors[31*8+2][2];
638 uint8 floor1_multiplier;
639 uint8 rangebits;
640 int values;
641 } Floor1;
642
643 typedef union
644 {
645 Floor0 floor0;
646 Floor1 floor1;
647 } Floor;
648
649 typedef struct
650 {
651 uint32 begin, end;
652 uint32 part_size;
653 uint8 classifications;
654 uint8 classbook;
655 uint8 **classdata;
656 int16 (*residue_books)[8];
657 } Residue;
658
659 typedef struct
660 {
661 uint8 magnitude;
662 uint8 angle;
663 uint8 mux;
664 } MappingChannel;
665
666 typedef struct
667 {
668 uint16 coupling_steps;
669 MappingChannel *chan;
670 uint8 submaps;
671 uint8 submap_floor[15]; // varies
672 uint8 submap_residue[15]; // varies
673 } Mapping;
674
675 typedef struct
676 {
677 uint8 blockflag;
678 uint8 mapping;
679 uint16 windowtype;
680 uint16 transformtype;
681 } Mode;
682
683 typedef struct
684 {
685 uint32 goal_crc; // expected crc if match
686 int bytes_left; // bytes left in packet
687 uint32 crc_so_far; // running crc
688 int bytes_done; // bytes processed in _current_ chunk
689 uint32 sample_loc; // granule pos encoded in page
690 } CRCscan;
691
692 typedef struct
693 {
694 uint32 page_start, page_end;
695 uint32 after_previous_page_start;
696 uint32 first_decoded_sample;
697 uint32 last_decoded_sample;
698 } ProbedPage;
699
700 struct stb_vorbis
701 {
702 // user-accessible info
703 unsigned int sample_rate;
704 int channels;
705
706 unsigned int setup_memory_required;
707 unsigned int temp_memory_required;
708 unsigned int setup_temp_memory_required;
709
710 // input config
711 #ifndef STB_VORBIS_NO_STDIO
712 FILE *f;
713 uint32 f_start;
714 int close_on_free;
715 #endif
716
717 uint8 *stream;
718 uint8 *stream_start;
719 uint8 *stream_end;
720
721 uint32 stream_len;
722
723 uint8 push_mode;
724
725 uint32 first_audio_page_offset;
726
727 ProbedPage p_first, p_last;
728
729 // memory management
730 stb_vorbis_alloc alloc;
731 int setup_offset;
732 int temp_offset;
733
734 // run-time results
735 int eof;
736 enum STBVorbisError error;
737
738 // user-useful data
739
740 // header info
741 int blocksize[2];
742 int blocksize_0, blocksize_1;
743 int codebook_count;
744 Codebook *codebooks;
745 int floor_count;
746 uint16 floor_types[64]; // varies
747 Floor *floor_config;
748 int residue_count;
749 uint16 residue_types[64]; // varies
750 Residue *residue_config;
751 int mapping_count;
752 Mapping *mapping;
753 int mode_count;
754 Mode mode_config[64]; // varies
755
756 uint32 total_samples;
757
758 // decode buffer
759 float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
760 float *outputs [STB_VORBIS_MAX_CHANNELS];
761
762 float *previous_window[STB_VORBIS_MAX_CHANNELS];
763 int previous_length;
764
765 #ifndef STB_VORBIS_NO_DEFER_FLOOR
766 int16 *finalY[STB_VORBIS_MAX_CHANNELS];
767 #else
768 float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
769 #endif
770
771 uint32 current_loc; // sample location of next frame to decode
772 int current_loc_valid;
773
774 // per-blocksize precomputed data
775
776 // twiddle factors
777 float *A[2],*B[2],*C[2];
778 float *window[2];
779 uint16 *bit_reverse[2];
780
781 // current page/packet/segment streaming info
782 uint32 serial; // stream serial number for verification
783 int last_page;
784 int segment_count;
785 uint8 segments[255];
786 uint8 page_flag;
787 uint8 bytes_in_seg;
788 uint8 first_decode;
789 int next_seg;
790 int last_seg; // flag that we're on the last segment
791 int last_seg_which; // what was the segment number of the last seg?
792 uint32 acc;
793 int valid_bits;
794 int packet_bytes;
795 int end_seg_with_known_loc;
796 uint32 known_loc_for_packet;
797 int discard_samples_deferred;
798 uint32 samples_output;
799
800 // push mode scanning
801 int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
802 #ifndef STB_VORBIS_NO_PUSHDATA_API
803 CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
804 #endif
805
806 // sample-access
807 int channel_buffer_start;
808 int channel_buffer_end;
809 };
810
811 extern int my_prof(int slot);
812 //#define stb_prof my_prof
813
814 #ifndef stb_prof
815 #define stb_prof(x) 0
816 #endif
817
818 #if defined(STB_VORBIS_NO_PUSHDATA_API)
819 #define IS_PUSH_MODE(f) FALSE
820 #elif defined(STB_VORBIS_NO_PULLDATA_API)
821 #define IS_PUSH_MODE(f) TRUE
822 #else
823 #define IS_PUSH_MODE(f) ((f)->push_mode)
824 #endif
825
826 typedef struct stb_vorbis vorb;
827
828 static int error(vorb *f, enum STBVorbisError e)
829 {
830 f->error = e;
831 if (!f->eof && e != VORBIS_need_more_data) {
832 f->error=e; // breakpoint for debugging
833 }
834 return 0;
835 }
836
837
838 // these functions are used for allocating temporary memory
839 // while decoding. if you can afford the stack space, use
840 // alloca(); otherwise, provide a temp buffer and it will
841 // allocate out of those.
842
843 #define array_size_required(count,size) (count*(sizeof(void *)+(size)))
844
845 #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
846 #ifdef dealloca
847 #define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size))
848 #else
849 #define temp_free(f,p) 0
850 #endif
851 #define temp_alloc_save(f) ((f)->temp_offset)
852 #define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
853
854 #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
855
856 // given a sufficiently large block of memory, make an array of pointers to subblocks of it
857 static void *make_block_array(void *mem, int count, int size)
858 {
859 int i;
860 void ** p = (void **) mem;
861 char *q = (char *) (p + count);
862 for (i=0; i < count; ++i) {
863 p[i] = q;
864 q += size;
865 }
866 return p;
867 }
868
869 static void *setup_malloc(vorb *f, int sz)
870 {
871 sz = (sz+3) & ~3;
872 f->setup_memory_required += sz;
873 if (f->alloc.alloc_buffer) {
874 void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
875 if (f->setup_offset + sz > f->temp_offset) return NULL;
876 f->setup_offset += sz;
877 return p;
878 }
879 return sz ? malloc(sz) : NULL;
880 }
881
882 static void setup_free(vorb *f, void *p)
883 {
884 if (f->alloc.alloc_buffer) return; // do nothing; setup mem is not a stack
885 free(p);
886 }
887
888 static void *setup_temp_malloc(vorb *f, int sz)
889 {
890 sz = (sz+3) & ~3;
891 if (f->alloc.alloc_buffer) {
892 if (f->temp_offset - sz < f->setup_offset) return NULL;
893 f->temp_offset -= sz;
894 return (char *) f->alloc.alloc_buffer + f->temp_offset;
895 }
896 return malloc(sz);
897 }
898
899 static void setup_temp_free(vorb *f, void *p, size_t sz)
900 {
901 if (f->alloc.alloc_buffer) {
902 f->temp_offset += (sz+3)&~3;
903 return;
904 }
905 free(p);
906 }
907
908 #define CRC32_POLY 0x04c11db7 // from spec
909
910 static uint32 crc_table[256];
911 static void crc32_init(void)
912 {
913 int i,j;
914 uint32 s;
915 for(i=0; i < 256; i++) {
916 for (s=i<<24, j=0; j < 8; ++j)
917 s = (s << 1) ^ (s >= (1<<31) ? CRC32_POLY : 0);
918 crc_table[i] = s;
919 }
920 }
921
922 static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
923 {
924 return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
925 }
926
927
928 // used in setup, and for huffman that doesn't go fast path
929 static unsigned int bit_reverse(unsigned int n)
930 {
931 n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
932 n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
933 n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
934 n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
935 return (n >> 16) | (n << 16);
936 }
937
938 static float square(float x)
939 {
940 return x*x;
941 }
942
943 // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
944 // as required by the specification. fast(?) implementation from stb.h
945 // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
946 static int ilog(int32 n)
947 {
948 static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
949
950 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
951 if (n < (1U << 14))
952 if (n < (1U << 4)) return 0 + log2_4[n ];
953 else if (n < (1U << 9)) return 5 + log2_4[n >> 5];
954 else return 10 + log2_4[n >> 10];
955 else if (n < (1U << 24))
956 if (n < (1U << 19)) return 15 + log2_4[n >> 15];
957 else return 20 + log2_4[n >> 20];
958 else if (n < (1U << 29)) return 25 + log2_4[n >> 25];
959 else if (n < (1U << 31)) return 30 + log2_4[n >> 30];
960 else return 0; // signed n returns 0
961 }
962
963 #ifndef M_PI
964 #define M_PI 3.14159265358979323846264f // from CRC
965 #endif
966
967 // code length assigned to a value with no huffman encoding
968 #define NO_CODE 255
969
970 /////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
971 //
972 // these functions are only called at setup, and only a few times
973 // per file
974
975 static float float32_unpack(uint32 x)
976 {
977 // from the specification
978 uint32 mantissa = x & 0x1fffff;
979 uint32 sign = x & 0x80000000;
980 uint32 exp = (x & 0x7fe00000) >> 21;
981 double res = sign ? -(double)mantissa : (double)mantissa;
982 return (float) ldexp((float)res, exp-788);
983 }
984
985
986 // zlib & jpeg huffman tables assume that the output symbols
987 // can either be arbitrarily arranged, or have monotonically
988 // increasing frequencies--they rely on the lengths being sorted;
989 // this makes for a very simple generation algorithm.
990 // vorbis allows a huffman table with non-sorted lengths. This
991 // requires a more sophisticated construction, since symbols in
992 // order do not map to huffman codes "in order".
993 static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
994 {
995 if (!c->sparse) {
996 c->codewords [symbol] = huff_code;
997 } else {
998 c->codewords [count] = huff_code;
999 c->codeword_lengths[count] = len;
1000 values [count] = symbol;
1001 }
1002 }
1003
1004 static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
1005 {
1006 int i,k,m=0;
1007 uint32 available[32];
1008
1009 memset(available, 0, sizeof(available));
1010 // find the first entry
1011 for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
1012 if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
1013 // add to the list
1014 add_entry(c, 0, k, m++, len[k], values);
1015 // add all available leaves
1016 for (i=1; i <= len[k]; ++i)
1017 available[i] = 1 << (32-i);
1018 // note that the above code treats the first case specially,
1019 // but it's really the same as the following code, so they
1020 // could probably be combined (except the initial code is 0,
1021 // and I use 0 in available[] to mean 'empty')
1022 for (i=k+1; i < n; ++i) {
1023 uint32 res;
1024 int z = len[i], y;
1025 if (z == NO_CODE) continue;
1026 // find lowest available leaf (should always be earliest,
1027 // which is what the specification calls for)
1028 // note that this property, and the fact we can never have
1029 // more than one free leaf at a given level, isn't totally
1030 // trivial to prove, but it seems true and the assert never
1031 // fires, so!
1032 while (z > 0 && !available[z]) --z;
1033 if (z == 0) { assert(0); return FALSE; }
1034 res = available[z];
1035 available[z] = 0;
1036 add_entry(c, bit_reverse(res), i, m++, len[i], values);
1037 // propogate availability up the tree
1038 if (z != len[i]) {
1039 for (y=len[i]; y > z; --y) {
1040 assert(available[y] == 0);
1041 available[y] = res + (1 << (32-y));
1042 }
1043 }
1044 }
1045 return TRUE;
1046 }
1047
1048 // accelerated huffman table allows fast O(1) match of all symbols
1049 // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
1050 static void compute_accelerated_huffman(Codebook *c)
1051 {
1052 int i, len;
1053 for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
1054 c->fast_huffman[i] = -1;
1055
1056 len = c->sparse ? c->sorted_entries : c->entries;
1057 #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
1058 if (len > 32767) len = 32767; // largest possible value we can encode!
1059 #endif
1060 for (i=0; i < len; ++i) {
1061 if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
1062 uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
1063 // set table entries for all bit combinations in the higher bits
1064 while (z < FAST_HUFFMAN_TABLE_SIZE) {
1065 c->fast_huffman[z] = i;
1066 z += 1 << c->codeword_lengths[i];
1067 }
1068 }
1069 }
1070 }
1071
1072 static int uint32_compare(const void *p, const void *q)
1073 {
1074 uint32 x = * (uint32 *) p;
1075 uint32 y = * (uint32 *) q;
1076 return x < y ? -1 : x > y;
1077 }
1078
1079 static int include_in_sort(Codebook *c, uint8 len)
1080 {
1081 if (c->sparse) { assert(len != NO_CODE); return TRUE; }
1082 if (len == NO_CODE) return FALSE;
1083 if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
1084 return FALSE;
1085 }
1086
1087 // if the fast table above doesn't work, we want to binary
1088 // search them... need to reverse the bits
1089 static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
1090 {
1091 int i, len;
1092 // build a list of all the entries
1093 // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
1094 // this is kind of a frivolous optimization--I don't see any performance improvement,
1095 // but it's like 4 extra lines of code, so.
1096 if (!c->sparse) {
1097 int k = 0;
1098 for (i=0; i < c->entries; ++i)
1099 if (include_in_sort(c, lengths[i]))
1100 c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
1101 assert(k == c->sorted_entries);
1102 } else {
1103 for (i=0; i < c->sorted_entries; ++i)
1104 c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
1105 }
1106
1107 qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
1108 c->sorted_codewords[c->sorted_entries] = 0xffffffff;
1109
1110 len = c->sparse ? c->sorted_entries : c->entries;
1111 // now we need to indicate how they correspond; we could either
1112 // #1: sort a different data structure that says who they correspond to
1113 // #2: for each sorted entry, search the original list to find who corresponds
1114 // #3: for each original entry, find the sorted entry
1115 // #1 requires extra storage, #2 is slow, #3 can use binary search!
1116 for (i=0; i < len; ++i) {
1117 int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
1118 if (include_in_sort(c,huff_len)) {
1119 uint32 code = bit_reverse(c->codewords[i]);
1120 int x=0, n=c->sorted_entries;
1121 while (n > 1) {
1122 // invariant: sc[x] <= code < sc[x+n]
1123 int m = x + (n >> 1);
1124 if (c->sorted_codewords[m] <= code) {
1125 x = m;
1126 n -= (n>>1);
1127 } else {
1128 n >>= 1;
1129 }
1130 }
1131 assert(c->sorted_codewords[x] == code);
1132 if (c->sparse) {
1133 c->sorted_values[x] = values[i];
1134 c->codeword_lengths[x] = huff_len;
1135 } else {
1136 c->sorted_values[x] = i;
1137 }
1138 }
1139 }
1140 }
1141
1142 // only run while parsing the header (3 times)
1143 static int vorbis_validate(uint8 *data)
1144 {
1145 static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
1146 return memcmp(data, vorbis, 6) == 0;
1147 }
1148
1149 // called from setup only, once per code book
1150 // (formula implied by specification)
1151 static int lookup1_values(int entries, int dim)
1152 {
1153 int r = (int) floor(exp((float) log((float) entries) / dim));
1154 if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
1155 ++r; // floor() to avoid _ftol() when non-CRT
1156 assert(pow((float) r+1, dim) > entries);
1157 assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
1158 return r;
1159 }
1160
1161 // called twice per file
1162 static void compute_twiddle_factors(int n, float *A, float *B, float *C)
1163 {
1164 int n4 = n >> 2, n8 = n >> 3;
1165 int k,k2;
1166
1167 for (k=k2=0; k < n4; ++k,k2+=2) {
1168 A[k2 ] = (float) cos(4*k*M_PI/n);
1169 A[k2+1] = (float) -sin(4*k*M_PI/n);
1170 B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
1171 B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
1172 }
1173 for (k=k2=0; k < n8; ++k,k2+=2) {
1174 C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
1175 C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
1176 }
1177 }
1178
1179 static void compute_window(int n, float *window)
1180 {
1181 int n2 = n >> 1, i;
1182 for (i=0; i < n2; ++i)
1183 window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
1184 }
1185
1186 static void compute_bitreverse(int n, uint16 *rev)
1187 {
1188 int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
1189 int i, n8 = n >> 3;
1190 for (i=0; i < n8; ++i)
1191 rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
1192 }
1193
1194 static int init_blocksize(vorb *f, int b, int n)
1195 {
1196 int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
1197 f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
1198 f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
1199 f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
1200 if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
1201 compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
1202 f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
1203 if (!f->window[b]) return error(f, VORBIS_outofmem);
1204 compute_window(n, f->window[b]);
1205 f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
1206 if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
1207 compute_bitreverse(n, f->bit_reverse[b]);
1208 return TRUE;
1209 }
1210
1211 static void neighbors(uint16 *x, int n, int *plow, int *phigh)
1212 {
1213 int low = -1;
1214 int high = 65536;
1215 int i;
1216 for (i=0; i < n; ++i) {
1217 if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
1218 if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
1219 }
1220 }
1221
1222 // this has been repurposed so y is now the original index instead of y
1223 typedef struct
1224 {
1225 uint16 x,y;
1226 } Point;
1227
1228 int point_compare(const void *p, const void *q)
1229 {
1230 Point *a = (Point *) p;
1231 Point *b = (Point *) q;
1232 return a->x < b->x ? -1 : a->x > b->x;
1233 }
1234
1235 //
1236 /////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
1237
1238
1239 #if defined(STB_VORBIS_NO_STDIO)
1240 #define USE_MEMORY(z) TRUE
1241 #else
1242 #define USE_MEMORY(z) ((z)->stream)
1243 #endif
1244
1245 static uint8 get8(vorb *z)
1246 {
1247 if (USE_MEMORY(z)) {
1248 if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
1249 return *z->stream++;
1250 }
1251
1252 #ifndef STB_VORBIS_NO_STDIO
1253 {
1254 int c = fgetc(z->f);
1255 if (c == EOF) { z->eof = TRUE; return 0; }
1256 return c;
1257 }
1258 #endif
1259 }
1260
1261 static uint32 get32(vorb *f)
1262 {
1263 uint32 x;
1264 x = get8(f);
1265 x += get8(f) << 8;
1266 x += get8(f) << 16;
1267 x += get8(f) << 24;
1268 return x;
1269 }
1270
1271 static int getn(vorb *z, uint8 *data, int n)
1272 {
1273 if (USE_MEMORY(z)) {
1274 if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
1275 memcpy(data, z->stream, n);
1276 z->stream += n;
1277 return 1;
1278 }
1279
1280 #ifndef STB_VORBIS_NO_STDIO
1281 if (fread(data, n, 1, z->f) == 1)
1282 return 1;
1283 else {
1284 z->eof = 1;
1285 return 0;
1286 }
1287 #endif
1288 }
1289
1290 static void skip(vorb *z, int n)
1291 {
1292 if (USE_MEMORY(z)) {
1293 z->stream += n;
1294 if (z->stream >= z->stream_end) z->eof = 1;
1295 return;
1296 }
1297 #ifndef STB_VORBIS_NO_STDIO
1298 {
1299 long x = ftell(z->f);
1300 fseek(z->f, x+n, SEEK_SET);
1301 }
1302 #endif
1303 }
1304
1305 static int set_file_offset(stb_vorbis *f, unsigned int loc)
1306 {
1307 #ifndef STB_VORBIS_NO_PUSHDATA_API
1308 if (f->push_mode) return 0;
1309 #endif
1310 f->eof = 0;
1311 if (USE_MEMORY(f)) {
1312 if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
1313 f->stream = f->stream_end;
1314 f->eof = 1;
1315 return 0;
1316 } else {
1317 f->stream = f->stream_start + loc;
1318 return 1;
1319 }
1320 }
1321 #ifndef STB_VORBIS_NO_STDIO
1322 if (loc + f->f_start < loc || loc >= 0x80000000) {
1323 loc = 0x7fffffff;
1324 f->eof = 1;
1325 } else {
1326 loc += f->f_start;
1327 }
1328 if (!fseek(f->f, loc, SEEK_SET))
1329 return 1;
1330 f->eof = 1;
1331 fseek(f->f, f->f_start, SEEK_END);
1332 return 0;
1333 #endif
1334 }
1335
1336
1337 static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
1338
1339 static int capture_pattern(vorb *f)
1340 {
1341 if (0x4f != get8(f)) return FALSE;
1342 if (0x67 != get8(f)) return FALSE;
1343 if (0x67 != get8(f)) return FALSE;
1344 if (0x53 != get8(f)) return FALSE;
1345 return TRUE;
1346 }
1347
1348 #define PAGEFLAG_continued_packet 1
1349 #define PAGEFLAG_first_page 2
1350 #define PAGEFLAG_last_page 4
1351
1352 static int start_page_no_capturepattern(vorb *f)
1353 {
1354 uint32 loc0,loc1,n,i;
1355 // stream structure version
1356 if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
1357 // header flag
1358 f->page_flag = get8(f);
1359 // absolute granule position
1360 loc0 = get32(f);
1361 loc1 = get32(f);
1362 // @TODO: validate loc0,loc1 as valid positions?
1363 // stream serial number -- vorbis doesn't interleave, so discard
1364 get32(f);
1365 //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
1366 // page sequence number
1367 n = get32(f);
1368 f->last_page = n;
1369 // CRC32
1370 get32(f);
1371 // page_segments
1372 f->segment_count = get8(f);
1373 if (!getn(f, f->segments, f->segment_count))
1374 return error(f, VORBIS_unexpected_eof);
1375 // assume we _don't_ know any the sample position of any segments
1376 f->end_seg_with_known_loc = -2;
1377 if (loc0 != ~0 || loc1 != ~0) {
1378 // determine which packet is the last one that will complete
1379 for (i=f->segment_count-1; i >= 0; --i)
1380 if (f->segments[i] < 255)
1381 break;
1382 // 'i' is now the index of the _last_ segment of a packet that ends
1383 if (i >= 0) {
1384 f->end_seg_with_known_loc = i;
1385 f->known_loc_for_packet = loc0;
1386 }
1387 }
1388 if (f->first_decode) {
1389 int i,len;
1390 ProbedPage p;
1391 len = 0;
1392 for (i=0; i < f->segment_count; ++i)
1393 len += f->segments[i];
1394 len += 27 + f->segment_count;
1395 p.page_start = f->first_audio_page_offset;
1396 p.page_end = p.page_start + len;
1397 p.after_previous_page_start = p.page_start;
1398 p.first_decoded_sample = 0;
1399 p.last_decoded_sample = loc0;
1400 f->p_first = p;
1401 }
1402 f->next_seg = 0;
1403 return TRUE;
1404 }
1405
1406 static int start_page(vorb *f)
1407 {
1408 if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
1409 return start_page_no_capturepattern(f);
1410 }
1411
1412 static int start_packet(vorb *f)
1413 {
1414 while (f->next_seg == -1) {
1415 if (!start_page(f)) return FALSE;
1416 if (f->page_flag & PAGEFLAG_continued_packet)
1417 return error(f, VORBIS_continued_packet_flag_invalid);
1418 }
1419 f->last_seg = FALSE;
1420 f->valid_bits = 0;
1421 f->packet_bytes = 0;
1422 f->bytes_in_seg = 0;
1423 // f->next_seg is now valid
1424 return TRUE;
1425 }
1426
1427 static int maybe_start_packet(vorb *f)
1428 {
1429 if (f->next_seg == -1) {
1430 int x = get8(f);
1431 if (f->eof) return FALSE; // EOF at page boundary is not an error!
1432 if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
1433 if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
1434 if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
1435 if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
1436 if (!start_page_no_capturepattern(f)) return FALSE;
1437 if (f->page_flag & PAGEFLAG_continued_packet) {
1438 // set up enough state that we can read this packet if we want,
1439 // e.g. during recovery
1440 f->last_seg = FALSE;
1441 f->bytes_in_seg = 0;
1442 return error(f, VORBIS_continued_packet_flag_invalid);
1443 }
1444 }
1445 return start_packet(f);
1446 }
1447
1448 static int next_segment(vorb *f)
1449 {
1450 int len;
1451 if (f->last_seg) return 0;
1452 if (f->next_seg == -1) {
1453 f->last_seg_which = f->segment_count-1; // in case start_page fails
1454 if (!start_page(f)) { f->last_seg = 1; return 0; }
1455 if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
1456 }
1457 len = f->segments[f->next_seg++];
1458 if (len < 255) {
1459 f->last_seg = TRUE;
1460 f->last_seg_which = f->next_seg-1;
1461 }
1462 if (f->next_seg >= f->segment_count)
1463 f->next_seg = -1;
1464 assert(f->bytes_in_seg == 0);
1465 f->bytes_in_seg = len;
1466 return len;
1467 }
1468
1469 #define EOP (-1)
1470 #define INVALID_BITS (-1)
1471
1472 static int get8_packet_raw(vorb *f)
1473 {
1474 if (!f->bytes_in_seg)
1475 if (f->last_seg) return EOP;
1476 else if (!next_segment(f)) return EOP;
1477 assert(f->bytes_in_seg > 0);
1478 --f->bytes_in_seg;
1479 ++f->packet_bytes;
1480 return get8(f);
1481 }
1482
1483 static int get8_packet(vorb *f)
1484 {
1485 int x = get8_packet_raw(f);
1486 f->valid_bits = 0;
1487 return x;
1488 }
1489
1490 static void flush_packet(vorb *f)
1491 {
1492 while (get8_packet_raw(f) != EOP);
1493 }
1494
1495 // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
1496 // as the huffman decoder?
1497 static uint32 get_bits(vorb *f, int n)
1498 {
1499 uint32 z;
1500
1501 if (f->valid_bits < 0) return 0;
1502 if (f->valid_bits < n) {
1503 if (n > 24) {
1504 // the accumulator technique below would not work correctly in this case
1505 z = get_bits(f, 24);
1506 z += get_bits(f, n-24) << 24;
1507 return z;
1508 }
1509 if (f->valid_bits == 0) f->acc = 0;
1510 while (f->valid_bits < n) {
1511 int z = get8_packet_raw(f);
1512 if (z == EOP) {
1513 f->valid_bits = INVALID_BITS;
1514 return 0;
1515 }
1516 f->acc += z << f->valid_bits;
1517 f->valid_bits += 8;
1518 }
1519 }
1520 if (f->valid_bits < 0) return 0;
1521 z = f->acc & ((1 << n)-1);
1522 f->acc >>= n;
1523 f->valid_bits -= n;
1524 return z;
1525 }
1526
1527 static int32 get_bits_signed(vorb *f, int n)
1528 {
1529 uint32 z = get_bits(f, n);
1530 if (z & (1 << (n-1)))
1531 z += ~((1 << n) - 1);
1532 return (int32) z;
1533 }
1534
1535 // @OPTIMIZE: primary accumulator for huffman
1536 // expand the buffer to as many bits as possible without reading off end of packet
1537 // it might be nice to allow f->valid_bits and f->acc to be stored in registers,
1538 // e.g. cache them locally and decode locally
1539 static __forceinline void prep_huffman(vorb *f)
1540 {
1541 if (f->valid_bits <= 24) {
1542 if (f->valid_bits == 0) f->acc = 0;
1543 do {
1544 int z;
1545 if (f->last_seg && !f->bytes_in_seg) return;
1546 z = get8_packet_raw(f);
1547 if (z == EOP) return;
1548 f->acc += z << f->valid_bits;
1549 f->valid_bits += 8;
1550 } while (f->valid_bits <= 24);
1551 }
1552 }
1553
1554 enum
1555 {
1556 VORBIS_packet_id = 1,
1557 VORBIS_packet_comment = 3,
1558 VORBIS_packet_setup = 5,
1559 };
1560
1561 static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
1562 {
1563 int i;
1564 prep_huffman(f);
1565
1566 assert(c->sorted_codewords || c->codewords);
1567 // cases to use binary search: sorted_codewords && !c->codewords
1568 // sorted_codewords && c->entries > 8
1569 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
1570 // binary search
1571 uint32 code = bit_reverse(f->acc);
1572 int x=0, n=c->sorted_entries, len;
1573
1574 while (n > 1) {
1575 // invariant: sc[x] <= code < sc[x+n]
1576 int m = x + (n >> 1);
1577 if (c->sorted_codewords[m] <= code) {
1578 x = m;
1579 n -= (n>>1);
1580 } else {
1581 n >>= 1;
1582 }
1583 }
1584 // x is now the sorted index
1585 if (!c->sparse) x = c->sorted_values[x];
1586 // x is now sorted index if sparse, or symbol otherwise
1587 len = c->codeword_lengths[x];
1588 if (f->valid_bits >= len) {
1589 f->acc >>= len;
1590 f->valid_bits -= len;
1591 return x;
1592 }
1593
1594 f->valid_bits = 0;
1595 return -1;
1596 }
1597
1598 // if small, linear search
1599 assert(!c->sparse);
1600 for (i=0; i < c->entries; ++i) {
1601 if (c->codeword_lengths[i] == NO_CODE) continue;
1602 if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
1603 if (f->valid_bits >= c->codeword_lengths[i]) {
1604 f->acc >>= c->codeword_lengths[i];
1605 f->valid_bits -= c->codeword_lengths[i];
1606 return i;
1607 }
1608 f->valid_bits = 0;
1609 return -1;
1610 }
1611 }
1612
1613 error(f, VORBIS_invalid_stream);
1614 f->valid_bits = 0;
1615 return -1;
1616 }
1617
1618 static int codebook_decode_scalar(vorb *f, Codebook *c)
1619 {
1620 int i;
1621 if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
1622 prep_huffman(f);
1623 // fast huffman table lookup
1624 i = f->acc & FAST_HUFFMAN_TABLE_MASK;
1625 i = c->fast_huffman[i];
1626 if (i >= 0) {
1627 f->acc >>= c->codeword_lengths[i];
1628 f->valid_bits -= c->codeword_lengths[i];
1629 if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
1630 return i;
1631 }
1632 return codebook_decode_scalar_raw(f,c);
1633 }
1634
1635 #ifndef STB_VORBIS_NO_INLINE_DECODE
1636
1637 #define DECODE_RAW(var, f,c) \
1638 if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
1639 prep_huffman(f); \
1640 var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
1641 var = c->fast_huffman[var]; \
1642 if (var >= 0) { \
1643 int n = c->codeword_lengths[var]; \
1644 f->acc >>= n; \
1645 f->valid_bits -= n; \
1646 if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
1647 } else { \
1648 var = codebook_decode_scalar_raw(f,c); \
1649 }
1650
1651 #else
1652
1653 #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
1654
1655 #endif
1656
1657 #define DECODE(var,f,c) \
1658 DECODE_RAW(var,f,c) \
1659 if (c->sparse) var = c->sorted_values[var];
1660
1661 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
1662 #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
1663 #else
1664 #define DECODE_VQ(var,f,c) DECODE(var,f,c)
1665 #endif
1666
1667
1668
1669
1670
1671
1672 // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
1673 // where we avoid one addition
1674 #ifndef STB_VORBIS_CODEBOOK_FLOATS
1675 #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off] * c->delta_value + c->minimum_value)
1676 #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off] * c->delta_value)
1677 #define CODEBOOK_ELEMENT_BASE(c) (c->minimum_value)
1678 #else
1679 #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
1680 #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
1681 #define CODEBOOK_ELEMENT_BASE(c) (0)
1682 #endif
1683
1684 static int codebook_decode_start(vorb *f, Codebook *c, int len)
1685 {
1686 int z = -1;
1687
1688 // type 0 is only legal in a scalar context
1689 if (c->lookup_type == 0)
1690 error(f, VORBIS_invalid_stream);
1691 else {
1692 DECODE_VQ(z,f,c);
1693 if (c->sparse) assert(z < c->sorted_entries);
1694 if (z < 0) { // check for EOP
1695 if (!f->bytes_in_seg)
1696 if (f->last_seg)
1697 return z;
1698 error(f, VORBIS_invalid_stream);
1699 }
1700 }
1701 return z;
1702 }
1703
1704 static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
1705 {
1706 int i,z = codebook_decode_start(f,c,len);
1707 if (z < 0) return FALSE;
1708 if (len > c->dimensions) len = c->dimensions;
1709
1710 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
1711 if (c->lookup_type == 1) {
1712 float last = CODEBOOK_ELEMENT_BASE(c);
1713 int div = 1;
1714 for (i=0; i < len; ++i) {
1715 int off = (z / div) % c->lookup_values;
1716 float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
1717 output[i] += val;
1718 if (c->sequence_p) last = val + c->minimum_value;
1719 div *= c->lookup_values;
1720 }
1721 return TRUE;
1722 }
1723 #endif
1724
1725 z *= c->dimensions;
1726 if (c->sequence_p) {
1727 float last = CODEBOOK_ELEMENT_BASE(c);
1728 for (i=0; i < len; ++i) {
1729 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1730 output[i] += val;
1731 last = val + c->minimum_value;
1732 }
1733 } else {
1734 float last = CODEBOOK_ELEMENT_BASE(c);
1735 for (i=0; i < len; ++i) {
1736 output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1737 }
1738 }
1739
1740 return TRUE;
1741 }
1742
1743 static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
1744 {
1745 int i,z = codebook_decode_start(f,c,len);
1746 float last = CODEBOOK_ELEMENT_BASE(c);
1747 if (z < 0) return FALSE;
1748 if (len > c->dimensions) len = c->dimensions;
1749
1750 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
1751 if (c->lookup_type == 1) {
1752 int div = 1;
1753 for (i=0; i < len; ++i) {
1754 int off = (z / div) % c->lookup_values;
1755 float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
1756 output[i*step] += val;
1757 if (c->sequence_p) last = val;
1758 div *= c->lookup_values;
1759 }
1760 return TRUE;
1761 }
1762 #endif
1763
1764 z *= c->dimensions;
1765 for (i=0; i < len; ++i) {
1766 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1767 output[i*step] += val;
1768 if (c->sequence_p) last = val;
1769 }
1770
1771 return TRUE;
1772 }
1773
1774 static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
1775 {
1776 int c_inter = *c_inter_p;
1777 int p_inter = *p_inter_p;
1778 int i,z, effective = c->dimensions;
1779
1780 // type 0 is only legal in a scalar context
1781 if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
1782
1783 while (total_decode > 0) {
1784 float last = CODEBOOK_ELEMENT_BASE(c);
1785 DECODE_VQ(z,f,c);
1786 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
1787 assert(!c->sparse || z < c->sorted_entries);
1788 #endif
1789 if (z < 0) {
1790 if (!f->bytes_in_seg)
1791 if (f->last_seg) return FALSE;
1792 return error(f, VORBIS_invalid_stream);
1793 }
1794
1795 // if this will take us off the end of the buffers, stop short!
1796 // we check by computing the length of the virtual interleaved
1797 // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
1798 // and the length we'll be using (effective)
1799 if (c_inter + p_inter*ch + effective > len * ch) {
1800 effective = len*ch - (p_inter*ch - c_inter);
1801 }
1802
1803 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
1804 if (c->lookup_type == 1) {
1805 int div = 1;
1806 for (i=0; i < effective; ++i) {
1807 int off = (z / div) % c->lookup_values;
1808 float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
1809 outputs[c_inter][p_inter] += val;
1810 if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1811 if (c->sequence_p) last = val;
1812 div *= c->lookup_values;
1813 }
1814 } else
1815 #endif
1816 {
1817 z *= c->dimensions;
1818 if (c->sequence_p) {
1819 for (i=0; i < effective; ++i) {
1820 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1821 outputs[c_inter][p_inter] += val;
1822 if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1823 last = val;
1824 }
1825 } else {
1826 for (i=0; i < effective; ++i) {
1827 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1828 outputs[c_inter][p_inter] += val;
1829 if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1830 }
1831 }
1832 }
1833
1834 total_decode -= effective;
1835 }
1836 *c_inter_p = c_inter;
1837 *p_inter_p = p_inter;
1838 return TRUE;
1839 }
1840
1841 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
1842 static int codebook_decode_deinterleave_repeat_2(vorb *f, Codebook *c, float **outputs, int *c_inter_p, int *p_inter_p, int len, int total_decode)
1843 {
1844 int c_inter = *c_inter_p;
1845 int p_inter = *p_inter_p;
1846 int i,z, effective = c->dimensions;
1847
1848 // type 0 is only legal in a scalar context
1849 if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
1850
1851 while (total_decode > 0) {
1852 float last = CODEBOOK_ELEMENT_BASE(c);
1853 DECODE_VQ(z,f,c);
1854
1855 if (z < 0) {
1856 if (!f->bytes_in_seg)
1857 if (f->last_seg) return FALSE;
1858 return error(f, VORBIS_invalid_stream);
1859 }
1860
1861 // if this will take us off the end of the buffers, stop short!
1862 // we check by computing the length of the virtual interleaved
1863 // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
1864 // and the length we'll be using (effective)
1865 if (c_inter + p_inter*2 + effective > len * 2) {
1866 effective = len*2 - (p_inter*2 - c_inter);
1867 }
1868
1869 {
1870 z *= c->dimensions;
1871 stb_prof(11);
1872 if (c->sequence_p) {
1873 // haven't optimized this case because I don't have any examples
1874 for (i=0; i < effective; ++i) {
1875 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1876 outputs[c_inter][p_inter] += val;
1877 if (++c_inter == 2) { c_inter = 0; ++p_inter; }
1878 last = val;
1879 }
1880 } else {
1881 i=0;
1882 if (c_inter == 1) {
1883 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1884 outputs[c_inter][p_inter] += val;
1885 c_inter = 0; ++p_inter;
1886 ++i;
1887 }
1888 {
1889 float *z0 = outputs[0];
1890 float *z1 = outputs[1];
1891 for (; i+1 < effective;) {
1892 z0[p_inter] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1893 z1[p_inter] += CODEBOOK_ELEMENT_FAST(c,z+i+1) + last;
1894 ++p_inter;
1895 i += 2;
1896 }
1897 }
1898 if (i < effective) {
1899 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1900 outputs[c_inter][p_inter] += val;
1901 if (++c_inter == 2) { c_inter = 0; ++p_inter; }
1902 }
1903 }
1904 }
1905
1906 total_decode -= effective;
1907 }
1908 *c_inter_p = c_inter;
1909 *p_inter_p = p_inter;
1910 return TRUE;
1911 }
1912 #endif
1913
1914 static int predict_point(int x, int x0, int x1, int y0, int y1)
1915 {
1916 int dy = y1 - y0;
1917 int adx = x1 - x0;
1918 // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
1919 int err = abs(dy) * (x - x0);
1920 int off = err / adx;
1921 return dy < 0 ? y0 - off : y0 + off;
1922 }
1923
1924 // the following table is block-copied from the specification
1925 static float inverse_db_table[256] =
1926 {
1927 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
1928 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
1929 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
1930 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
1931 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
1932 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
1933 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
1934 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
1935 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
1936 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
1937 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
1938 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
1939 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
1940 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
1941 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
1942 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
1943 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
1944 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
1945 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
1946 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
1947 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
1948 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
1949 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
1950 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
1951 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
1952 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
1953 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
1954 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
1955 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
1956 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
1957 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
1958 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
1959 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
1960 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
1961 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
1962 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
1963 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
1964 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
1965 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
1966 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
1967 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
1968 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
1969 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
1970 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
1971 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
1972 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
1973 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
1974 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
1975 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
1976 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
1977 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
1978 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
1979 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
1980 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
1981 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
1982 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
1983 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
1984 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
1985 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
1986 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
1987 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
1988 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
1989 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
1990 0.82788260f, 0.88168307f, 0.9389798f, 1.0f
1991 };
1992
1993
1994 // @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
1995 // note that you must produce bit-identical output to decode correctly;
1996 // this specific sequence of operations is specified in the spec (it's
1997 // drawing integer-quantized frequency-space lines that the encoder
1998 // expects to be exactly the same)
1999 // ... also, isn't the whole point of Bresenham's algorithm to NOT
2000 // have to divide in the setup? sigh.
2001 #ifndef STB_VORBIS_NO_DEFER_FLOOR
2002 #define LINE_OP(a,b) a *= b
2003 #else
2004 #define LINE_OP(a,b) a = b
2005 #endif
2006
2007 #ifdef STB_VORBIS_DIVIDE_TABLE
2008 #define DIVTAB_NUMER 32
2009 #define DIVTAB_DENOM 64
2010 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
2011 #endif
2012
2013 static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
2014 {
2015 int dy = y1 - y0;
2016 int adx = x1 - x0;
2017 int ady = abs(dy);
2018 int base;
2019 int x=x0,y=y0;
2020 int err = 0;
2021 int sy;
2022
2023 #ifdef STB_VORBIS_DIVIDE_TABLE
2024 if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
2025 if (dy < 0) {
2026 base = -integer_divide_table[ady][adx];
2027 sy = base-1;
2028 } else {
2029 base = integer_divide_table[ady][adx];
2030 sy = base+1;
2031 }
2032 } else {
2033 base = dy / adx;
2034 if (dy < 0)
2035 sy = base - 1;
2036 else
2037 sy = base+1;
2038 }
2039 #else
2040 base = dy / adx;
2041 if (dy < 0)
2042 sy = base - 1;
2043 else
2044 sy = base+1;
2045 #endif
2046 ady -= abs(base) * adx;
2047 if (x1 > n) x1 = n;
2048 LINE_OP(output[x], inverse_db_table[y]);
2049 for (++x; x < x1; ++x) {
2050 err += ady;
2051 if (err >= adx) {
2052 err -= adx;
2053 y += sy;
2054 } else
2055 y += base;
2056 LINE_OP(output[x], inverse_db_table[y]);
2057 }
2058 }
2059
2060 static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
2061 {
2062 int k;
2063 if (rtype == 0) {
2064 int step = n / book->dimensions;
2065 for (k=0; k < step; ++k)
2066 if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
2067 return FALSE;
2068 } else {
2069 for (k=0; k < n; ) {
2070 if (!codebook_decode(f, book, target+offset, n-k))
2071 return FALSE;
2072 k += book->dimensions;
2073 offset += book->dimensions;
2074 }
2075 }
2076 return TRUE;
2077 }
2078
2079 static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
2080 {
2081 int i,j,pass;
2082 Residue *r = f->residue_config + rn;
2083 int rtype = f->residue_types[rn];
2084 int c = r->classbook;
2085 int classwords = f->codebooks[c].dimensions;
2086 int n_read = r->end - r->begin;
2087 int part_read = n_read / r->part_size;
2088 int temp_alloc_point = temp_alloc_save(f);
2089 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2090 uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
2091 #else
2092 int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
2093 #endif
2094
2095 stb_prof(2);
2096 for (i=0; i < ch; ++i)
2097 if (!do_not_decode[i])
2098 memset(residue_buffers[i], 0, sizeof(float) * n);
2099
2100 if (rtype == 2 && ch != 1) {
2101 int len = ch * n;
2102 for (j=0; j < ch; ++j)
2103 if (!do_not_decode[j])
2104 break;
2105 if (j == ch)
2106 goto done;
2107
2108 stb_prof(3);
2109 for (pass=0; pass < 8; ++pass) {
2110 int pcount = 0, class_set = 0;
2111 if (ch == 2) {
2112 stb_prof(13);
2113 while (pcount < part_read) {
2114 int z = r->begin + pcount*r->part_size;
2115 int c_inter = (z & 1), p_inter = z>>1;
2116 if (pass == 0) {
2117 Codebook *c = f->codebooks+r->classbook;
2118 int q;
2119 DECODE(q,f,c);
2120 if (q == EOP) goto done;
2121 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2122 part_classdata[0][class_set] = r->classdata[q];
2123 #else
2124 for (i=classwords-1; i >= 0; --i) {
2125 classifications[0][i+pcount] = q % r->classifications;
2126 q /= r->classifications;
2127 }
2128 #endif
2129 }
2130 stb_prof(5);
2131 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2132 int z = r->begin + pcount*r->part_size;
2133 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2134 int c = part_classdata[0][class_set][i];
2135 #else
2136 int c = classifications[0][pcount];
2137 #endif
2138 int b = r->residue_books[c][pass];
2139 if (b >= 0) {
2140 Codebook *book = f->codebooks + b;
2141 stb_prof(20); // accounts for X time
2142 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
2143 if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
2144 goto done;
2145 #else
2146 // saves 1%
2147 if (!codebook_decode_deinterleave_repeat_2(f, book, residue_buffers, &c_inter, &p_inter, n, r->part_size))
2148 goto done;
2149 #endif
2150 stb_prof(7);
2151 } else {
2152 z += r->part_size;
2153 c_inter = z & 1;
2154 p_inter = z >> 1;
2155 }
2156 }
2157 stb_prof(8);
2158 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2159 ++class_set;
2160 #endif
2161 }
2162 } else if (ch == 1) {
2163 while (pcount < part_read) {
2164 int z = r->begin + pcount*r->part_size;
2165 int c_inter = 0, p_inter = z;
2166 if (pass == 0) {
2167 Codebook *c = f->codebooks+r->classbook;
2168 int q;
2169 DECODE(q,f,c);
2170 if (q == EOP) goto done;
2171 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2172 part_classdata[0][class_set] = r->classdata[q];
2173 #else
2174 for (i=classwords-1; i >= 0; --i) {
2175 classifications[0][i+pcount] = q % r->classifications;
2176 q /= r->classifications;
2177 }
2178 #endif
2179 }
2180 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2181 int z = r->begin + pcount*r->part_size;
2182 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2183 int c = part_classdata[0][class_set][i];
2184 #else
2185 int c = classifications[0][pcount];
2186 #endif
2187 int b = r->residue_books[c][pass];
2188 if (b >= 0) {
2189 Codebook *book = f->codebooks + b;
2190 stb_prof(22);
2191 if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
2192 goto done;
2193 stb_prof(3);
2194 } else {
2195 z += r->part_size;
2196 c_inter = 0;
2197 p_inter = z;
2198 }
2199 }
2200 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2201 ++class_set;
2202 #endif
2203 }
2204 } else {
2205 while (pcount < part_read) {
2206 int z = r->begin + pcount*r->part_size;
2207 int c_inter = z % ch, p_inter = z/ch;
2208 if (pass == 0) {
2209 Codebook *c = f->codebooks+r->classbook;
2210 int q;
2211 DECODE(q,f,c);
2212 if (q == EOP) goto done;
2213 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2214 part_classdata[0][class_set] = r->classdata[q];
2215 #else
2216 for (i=classwords-1; i >= 0; --i) {
2217 classifications[0][i+pcount] = q % r->classifications;
2218 q /= r->classifications;
2219 }
2220 #endif
2221 }
2222 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2223 int z = r->begin + pcount*r->part_size;
2224 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2225 int c = part_classdata[0][class_set][i];
2226 #else
2227 int c = classifications[0][pcount];
2228 #endif
2229 int b = r->residue_books[c][pass];
2230 if (b >= 0) {
2231 Codebook *book = f->codebooks + b;
2232 stb_prof(22);
2233 if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
2234 goto done;
2235 stb_prof(3);
2236 } else {
2237 z += r->part_size;
2238 c_inter = z % ch;
2239 p_inter = z / ch;
2240 }
2241 }
2242 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2243 ++class_set;
2244 #endif
2245 }
2246 }
2247 }
2248 goto done;
2249 }
2250 stb_prof(9);
2251
2252 for (pass=0; pass < 8; ++pass) {
2253 int pcount = 0, class_set=0;
2254 while (pcount < part_read) {
2255 if (pass == 0) {
2256 for (j=0; j < ch; ++j) {
2257 if (!do_not_decode[j]) {
2258 Codebook *c = f->codebooks+r->classbook;
2259 int temp;
2260 DECODE(temp,f,c);
2261 if (temp == EOP) goto done;
2262 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2263 part_classdata[j][class_set] = r->classdata[temp];
2264 #else
2265 for (i=classwords-1; i >= 0; --i) {
2266 classifications[j][i+pcount] = temp % r->classifications;
2267 temp /= r->classifications;
2268 }
2269 #endif
2270 }
2271 }
2272 }
2273 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2274 for (j=0; j < ch; ++j) {
2275 if (!do_not_decode[j]) {
2276 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2277 int c = part_classdata[j][class_set][i];
2278 #else
2279 int c = classifications[j][pcount];
2280 #endif
2281 int b = r->residue_books[c][pass];
2282 if (b >= 0) {
2283 float *target = residue_buffers[j];
2284 int offset = r->begin + pcount * r->part_size;
2285 int n = r->part_size;
2286 Codebook *book = f->codebooks + b;
2287 if (!residue_decode(f, book, target, offset, n, rtype))
2288 goto done;
2289 }
2290 }
2291 }
2292 }
2293 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2294 ++class_set;
2295 #endif
2296 }
2297 }
2298 done:
2299 stb_prof(0);
2300 temp_alloc_restore(f,temp_alloc_point);
2301 }
2302
2303
2304 #if 0
2305 // slow way for debugging
2306 void inverse_mdct_slow(float *buffer, int n)
2307 {
2308 int i,j;
2309 int n2 = n >> 1;
2310 float *x = (float *) malloc(sizeof(*x) * n2);
2311 memcpy(x, buffer, sizeof(*x) * n2);
2312 for (i=0; i < n; ++i) {
2313 float acc = 0;
2314 for (j=0; j < n2; ++j)
2315 // formula from paper:
2316 //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
2317 // formula from wikipedia
2318 //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
2319 // these are equivalent, except the formula from the paper inverts the multiplier!
2320 // however, what actually works is NO MULTIPLIER!?!
2321 //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
2322 acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
2323 buffer[i] = acc;
2324 }
2325 free(x);
2326 }
2327 #elif 0
2328 // same as above, but just barely able to run in real time on modern machines
2329 void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
2330 {
2331 float mcos[16384];
2332 int i,j;
2333 int n2 = n >> 1, nmask = (n << 2) -1;
2334 float *x = (float *) malloc(sizeof(*x) * n2);
2335 memcpy(x, buffer, sizeof(*x) * n2);
2336 for (i=0; i < 4*n; ++i)
2337 mcos[i] = (float) cos(M_PI / 2 * i / n);
2338
2339 for (i=0; i < n; ++i) {
2340 float acc = 0;
2341 for (j=0; j < n2; ++j)
2342 acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
2343 buffer[i] = acc;
2344 }
2345 free(x);
2346 }
2347 #else
2348 // transform to use a slow dct-iv; this is STILL basically trivial,
2349 // but only requires half as many ops
2350 void dct_iv_slow(float *buffer, int n)
2351 {
2352 float mcos[16384];
2353 float x[2048];
2354 int i,j;
2355 int n2 = n >> 1, nmask = (n << 3) - 1;
2356 memcpy(x, buffer, sizeof(*x) * n);
2357 for (i=0; i < 8*n; ++i)
2358 mcos[i] = (float) cos(M_PI / 4 * i / n);
2359 for (i=0; i < n; ++i) {
2360 float acc = 0;
2361 for (j=0; j < n; ++j)
2362 acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
2363 //acc += x[j] * cos(M_PI / n * (i + 0.5) * (j + 0.5));
2364 buffer[i] = acc;
2365 }
2366 free(x);
2367 }
2368
2369 void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
2370 {
2371 int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
2372 float temp[4096];
2373
2374 memcpy(temp, buffer, n2 * sizeof(float));
2375 dct_iv_slow(temp, n2); // returns -c'-d, a-b'
2376
2377 for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
2378 for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
2379 for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
2380 }
2381 #endif
2382
2383 #ifndef LIBVORBIS_MDCT
2384 #define LIBVORBIS_MDCT 0
2385 #endif
2386
2387 #if LIBVORBIS_MDCT
2388 // directly call the vorbis MDCT using an interface documented
2389 // by Jeff Roberts... useful for performance comparison
2390 typedef struct
2391 {
2392 int n;
2393 int log2n;
2394
2395 float *trig;
2396 int *bitrev;
2397
2398 float scale;
2399 } mdct_lookup;
2400
2401 extern void mdct_init(mdct_lookup *lookup, int n);
2402 extern void mdct_clear(mdct_lookup *l);
2403 extern void mdct_backward(mdct_lookup *init, float *in, float *out);
2404
2405 mdct_lookup M1,M2;
2406
2407 void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
2408 {
2409 mdct_lookup *M;
2410 if (M1.n == n) M = &M1;
2411 else if (M2.n == n) M = &M2;
2412 else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
2413 else {
2414 if (M2.n) __asm int 3;
2415 mdct_init(&M2, n);
2416 M = &M2;
2417 }
2418
2419 mdct_backward(M, buffer, buffer);
2420 }
2421 #endif
2422
2423
2424 // the following were split out into separate functions while optimizing;
2425 // they could be pushed back up but eh. __forceinline showed no change;
2426 // they're probably already being inlined.
2427 static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
2428 {
2429 float *ee0 = e + i_off;
2430 float *ee2 = ee0 + k_off;
2431 int i;
2432
2433 assert((n & 3) == 0);
2434 for (i=(n>>2); i > 0; --i) {
2435 float k00_20, k01_21;
2436 k00_20 = ee0[ 0] - ee2[ 0];
2437 k01_21 = ee0[-1] - ee2[-1];
2438 ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
2439 ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
2440 ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
2441 ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
2442 A += 8;
2443
2444 k00_20 = ee0[-2] - ee2[-2];
2445 k01_21 = ee0[-3] - ee2[-3];
2446 ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
2447 ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
2448 ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
2449 ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
2450 A += 8;
2451
2452 k00_20 = ee0[-4] - ee2[-4];
2453 k01_21 = ee0[-5] - ee2[-5];
2454 ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
2455 ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
2456 ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
2457 ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
2458 A += 8;
2459
2460 k00_20 = ee0[-6] - ee2[-6];
2461 k01_21 = ee0[-7] - ee2[-7];
2462 ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
2463 ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
2464 ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
2465 ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
2466 A += 8;
2467 ee0 -= 8;
2468 ee2 -= 8;
2469 }
2470 }
2471
2472 static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
2473 {
2474 int i;
2475 float k00_20, k01_21;
2476
2477 float *e0 = e + d0;
2478 float *e2 = e0 + k_off;
2479
2480 for (i=lim >> 2; i > 0; --i) {
2481 k00_20 = e0[-0] - e2[-0];
2482 k01_21 = e0[-1] - e2[-1];
2483 e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
2484 e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
2485 e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
2486 e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
2487
2488 A += k1;
2489
2490 k00_20 = e0[-2] - e2[-2];
2491 k01_21 = e0[-3] - e2[-3];
2492 e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
2493 e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
2494 e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
2495 e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
2496
2497 A += k1;
2498
2499 k00_20 = e0[-4] - e2[-4];
2500 k01_21 = e0[-5] - e2[-5];
2501 e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
2502 e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
2503 e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
2504 e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
2505
2506 A += k1;
2507
2508 k00_20 = e0[-6] - e2[-6];
2509 k01_21 = e0[-7] - e2[-7];
2510 e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
2511 e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
2512 e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
2513 e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
2514
2515 e0 -= 8;
2516 e2 -= 8;
2517
2518 A += k1;
2519 }
2520 }
2521
2522 static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
2523 {
2524 int i;
2525 float A0 = A[0];
2526 float A1 = A[0+1];
2527 float A2 = A[0+a_off];
2528 float A3 = A[0+a_off+1];
2529 float A4 = A[0+a_off*2+0];
2530 float A5 = A[0+a_off*2+1];
2531 float A6 = A[0+a_off*3+0];
2532 float A7 = A[0+a_off*3+1];
2533
2534 float k00,k11;
2535
2536 float *ee0 = e +i_off;
2537 float *ee2 = ee0+k_off;
2538
2539 for (i=n; i > 0; --i) {
2540 k00 = ee0[ 0] - ee2[ 0];
2541 k11 = ee0[-1] - ee2[-1];
2542 ee0[ 0] = ee0[ 0] + ee2[ 0];
2543 ee0[-1] = ee0[-1] + ee2[-1];
2544 ee2[ 0] = (k00) * A0 - (k11) * A1;
2545 ee2[-1] = (k11) * A0 + (k00) * A1;
2546
2547 k00 = ee0[-2] - ee2[-2];
2548 k11 = ee0[-3] - ee2[-3];
2549 ee0[-2] = ee0[-2] + ee2[-2];
2550 ee0[-3] = ee0[-3] + ee2[-3];
2551 ee2[-2] = (k00) * A2 - (k11) * A3;
2552 ee2[-3] = (k11) * A2 + (k00) * A3;
2553
2554 k00 = ee0[-4] - ee2[-4];
2555 k11 = ee0[-5] - ee2[-5];
2556 ee0[-4] = ee0[-4] + ee2[-4];
2557 ee0[-5] = ee0[-5] + ee2[-5];
2558 ee2[-4] = (k00) * A4 - (k11) * A5;
2559 ee2[-5] = (k11) * A4 + (k00) * A5;
2560
2561 k00 = ee0[-6] - ee2[-6];
2562 k11 = ee0[-7] - ee2[-7];
2563 ee0[-6] = ee0[-6] + ee2[-6];
2564 ee0[-7] = ee0[-7] + ee2[-7];
2565 ee2[-6] = (k00) * A6 - (k11) * A7;
2566 ee2[-7] = (k11) * A6 + (k00) * A7;
2567
2568 ee0 -= k0;
2569 ee2 -= k0;
2570 }
2571 }
2572
2573 static __forceinline void iter_54(float *z)
2574 {
2575 float k00,k11,k22,k33;
2576 float y0,y1,y2,y3;
2577
2578 k00 = z[ 0] - z[-4];
2579 y0 = z[ 0] + z[-4];
2580 y2 = z[-2] + z[-6];
2581 k22 = z[-2] - z[-6];
2582
2583 z[-0] = y0 + y2; // z0 + z4 + z2 + z6
2584 z[-2] = y0 - y2; // z0 + z4 - z2 - z6
2585
2586 // done with y0,y2
2587
2588 k33 = z[-3] - z[-7];
2589
2590 z[-4] = k00 + k33; // z0 - z4 + z3 - z7
2591 z[-6] = k00 - k33; // z0 - z4 - z3 + z7
2592
2593 // done with k33
2594
2595 k11 = z[-1] - z[-5];
2596 y1 = z[-1] + z[-5];
2597 y3 = z[-3] + z[-7];
2598
2599 z[-1] = y1 + y3; // z1 + z5 + z3 + z7
2600 z[-3] = y1 - y3; // z1 + z5 - z3 - z7
2601 z[-5] = k11 - k22; // z1 - z5 + z2 - z6
2602 z[-7] = k11 + k22; // z1 - z5 - z2 + z6
2603 }
2604
2605 static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
2606 {
2607 int k_off = -8;
2608 int a_off = base_n >> 3;
2609 float A2 = A[0+a_off];
2610 float *z = e + i_off;
2611 float *base = z - 16 * n;
2612
2613 while (z > base) {
2614 float k00,k11;
2615
2616 k00 = z[-0] - z[-8];
2617 k11 = z[-1] - z[-9];
2618 z[-0] = z[-0] + z[-8];
2619 z[-1] = z[-1] + z[-9];
2620 z[-8] = k00;
2621 z[-9] = k11 ;
2622
2623 k00 = z[ -2] - z[-10];
2624 k11 = z[ -3] - z[-11];
2625 z[ -2] = z[ -2] + z[-10];
2626 z[ -3] = z[ -3] + z[-11];
2627 z[-10] = (k00+k11) * A2;
2628 z[-11] = (k11-k00) * A2;
2629
2630 k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
2631 k11 = z[ -5] - z[-13];
2632 z[ -4] = z[ -4] + z[-12];
2633 z[ -5] = z[ -5] + z[-13];
2634 z[-12] = k11;
2635 z[-13] = k00;
2636
2637 k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
2638 k11 = z[ -7] - z[-15];
2639 z[ -6] = z[ -6] + z[-14];
2640 z[ -7] = z[ -7] + z[-15];
2641 z[-14] = (k00+k11) * A2;
2642 z[-15] = (k00-k11) * A2;
2643
2644 iter_54(z);
2645 iter_54(z-8);
2646 z -= 16;
2647 }
2648 }
2649
2650 static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
2651 {
2652 int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
2653 int n3_4 = n - n4, ld;
2654 // @OPTIMIZE: reduce register pressure by using fewer variables?
2655 int save_point = temp_alloc_save(f);
2656 float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
2657 float *u=NULL,*v=NULL;
2658 // twiddle factors
2659 float *A = f->A[blocktype];
2660
2661 // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
2662 // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
2663
2664 // kernel from paper
2665
2666
2667 // merged:
2668 // copy and reflect spectral data
2669 // step 0
2670
2671 // note that it turns out that the items added together during
2672 // this step are, in fact, being added to themselves (as reflected
2673 // by step 0). inexplicable inefficiency! this became obvious
2674 // once I combined the passes.
2675
2676 // so there's a missing 'times 2' here (for adding X to itself).
2677 // this propogates through linearly to the end, where the numbers
2678 // are 1/2 too small, and need to be compensated for.
2679
2680 {
2681 float *d,*e, *AA, *e_stop;
2682 d = &buf2[n2-2];
2683 AA = A;
2684 e = &buffer[0];
2685 e_stop = &buffer[n2];
2686 while (e != e_stop) {
2687 d[1] = (e[0] * AA[0] - e[2]*AA[1]);
2688 d[0] = (e[0] * AA[1] + e[2]*AA[0]);
2689 d -= 2;
2690 AA += 2;
2691 e += 4;
2692 }
2693
2694 e = &buffer[n2-3];
2695 while (d >= buf2) {
2696 d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
2697 d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
2698 d -= 2;
2699 AA += 2;
2700 e -= 4;
2701 }
2702 }
2703
2704 // now we use symbolic names for these, so that we can
2705 // possibly swap their meaning as we change which operations
2706 // are in place
2707
2708 u = buffer;
2709 v = buf2;
2710
2711 // step 2 (paper output is w, now u)
2712 // this could be in place, but the data ends up in the wrong
2713 // place... _somebody_'s got to swap it, so this is nominated
2714 {
2715 float *AA = &A[n2-8];
2716 float *d0,*d1, *e0, *e1;
2717
2718 e0 = &v[n4];
2719 e1 = &v[0];
2720
2721 d0 = &u[n4];
2722 d1 = &u[0];
2723
2724 while (AA >= A) {
2725 float v40_20, v41_21;
2726
2727 v41_21 = e0[1] - e1[1];
2728 v40_20 = e0[0] - e1[0];
2729 d0[1] = e0[1] + e1[1];
2730 d0[0] = e0[0] + e1[0];
2731 d1[1] = v41_21*AA[4] - v40_20*AA[5];
2732 d1[0] = v40_20*AA[4] + v41_21*AA[5];
2733
2734 v41_21 = e0[3] - e1[3];
2735 v40_20 = e0[2] - e1[2];
2736 d0[3] = e0[3] + e1[3];
2737 d0[2] = e0[2] + e1[2];
2738 d1[3] = v41_21*AA[0] - v40_20*AA[1];
2739 d1[2] = v40_20*AA[0] + v41_21*AA[1];
2740
2741 AA -= 8;
2742
2743 d0 += 4;
2744 d1 += 4;
2745 e0 += 4;
2746 e1 += 4;
2747 }
2748 }
2749
2750 // step 3
2751 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
2752
2753 // optimized step 3:
2754
2755 // the original step3 loop can be nested r inside s or s inside r;
2756 // it's written originally as s inside r, but this is dumb when r
2757 // iterates many times, and s few. So I have two copies of it and
2758 // switch between them halfway.
2759
2760 // this is iteration 0 of step 3
2761 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
2762 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
2763
2764 // this is iteration 1 of step 3
2765 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
2766 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
2767 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
2768 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
2769
2770 l=2;
2771 for (; l < (ld-3)>>1; ++l) {
2772 int k0 = n >> (l+2), k0_2 = k0>>1;
2773 int lim = 1 << (l+1);
2774 int i;
2775 for (i=0; i < lim; ++i)
2776 imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
2777 }
2778
2779 for (; l < ld-6; ++l) {
2780 int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
2781 int rlim = n >> (l+6), r;
2782 int lim = 1 << (l+1);
2783 int i_off;
2784 float *A0 = A;
2785 i_off = n2-1;
2786 for (r=rlim; r > 0; --r) {
2787 imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
2788 A0 += k1*4;
2789 i_off -= 8;
2790 }
2791 }
2792
2793 // iterations with count:
2794 // ld-6,-5,-4 all interleaved together
2795 // the big win comes from getting rid of needless flops
2796 // due to the constants on pass 5 & 4 being all 1 and 0;
2797 // combining them to be simultaneous to improve cache made little difference
2798 imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
2799
2800 // output is u
2801
2802 // step 4, 5, and 6
2803 // cannot be in-place because of step 5
2804 {
2805 uint16 *bitrev = f->bit_reverse[blocktype];
2806 // weirdly, I'd have thought reading sequentially and writing
2807 // erratically would have been better than vice-versa, but in
2808 // fact that's not what my testing showed. (That is, with
2809 // j = bitreverse(i), do you read i and write j, or read j and write i.)
2810
2811 float *d0 = &v[n4-4];
2812 float *d1 = &v[n2-4];
2813 while (d0 >= v) {
2814 int k4;
2815
2816 k4 = bitrev[0];
2817 d1[3] = u[k4+0];
2818 d1[2] = u[k4+1];
2819 d0[3] = u[k4+2];
2820 d0[2] = u[k4+3];
2821
2822 k4 = bitrev[1];
2823 d1[1] = u[k4+0];
2824 d1[0] = u[k4+1];
2825 d0[1] = u[k4+2];
2826 d0[0] = u[k4+3];
2827
2828 d0 -= 4;
2829 d1 -= 4;
2830 bitrev += 2;
2831 }
2832 }
2833 // (paper output is u, now v)
2834
2835
2836 // data must be in buf2
2837 assert(v == buf2);
2838
2839 // step 7 (paper output is v, now v)
2840 // this is now in place
2841 {
2842 float *C = f->C[blocktype];
2843 float *d, *e;
2844
2845 d = v;
2846 e = v + n2 - 4;
2847
2848 while (d < e) {
2849 float a02,a11,b0,b1,b2,b3;
2850
2851 a02 = d[0] - e[2];
2852 a11 = d[1] + e[3];
2853
2854 b0 = C[1]*a02 + C[0]*a11;
2855 b1 = C[1]*a11 - C[0]*a02;
2856
2857 b2 = d[0] + e[ 2];
2858 b3 = d[1] - e[ 3];
2859
2860 d[0] = b2 + b0;
2861 d[1] = b3 + b1;
2862 e[2] = b2 - b0;
2863 e[3] = b1 - b3;
2864
2865 a02 = d[2] - e[0];
2866 a11 = d[3] + e[1];
2867
2868 b0 = C[3]*a02 + C[2]*a11;
2869 b1 = C[3]*a11 - C[2]*a02;
2870
2871 b2 = d[2] + e[ 0];
2872 b3 = d[3] - e[ 1];
2873
2874 d[2] = b2 + b0;
2875 d[3] = b3 + b1;
2876 e[0] = b2 - b0;
2877 e[1] = b1 - b3;
2878
2879 C += 4;
2880 d += 4;
2881 e -= 4;
2882 }
2883 }
2884
2885 // data must be in buf2
2886
2887
2888 // step 8+decode (paper output is X, now buffer)
2889 // this generates pairs of data a la 8 and pushes them directly through
2890 // the decode kernel (pushing rather than pulling) to avoid having
2891 // to make another pass later
2892
2893 // this cannot POSSIBLY be in place, so we refer to the buffers directly
2894
2895 {
2896 float *d0,*d1,*d2,*d3;
2897
2898 float *B = f->B[blocktype] + n2 - 8;
2899 float *e = buf2 + n2 - 8;
2900 d0 = &buffer[0];
2901 d1 = &buffer[n2-4];
2902 d2 = &buffer[n2];
2903 d3 = &buffer[n-4];
2904 while (e >= v) {
2905 float p0,p1,p2,p3;
2906
2907 p3 = e[6]*B[7] - e[7]*B[6];
2908 p2 = -e[6]*B[6] - e[7]*B[7];
2909
2910 d0[0] = p3;
2911 d1[3] = - p3;
2912 d2[0] = p2;
2913 d3[3] = p2;
2914
2915 p1 = e[4]*B[5] - e[5]*B[4];
2916 p0 = -e[4]*B[4] - e[5]*B[5];
2917
2918 d0[1] = p1;
2919 d1[2] = - p1;
2920 d2[1] = p0;
2921 d3[2] = p0;
2922
2923 p3 = e[2]*B[3] - e[3]*B[2];
2924 p2 = -e[2]*B[2] - e[3]*B[3];
2925
2926 d0[2] = p3;
2927 d1[1] = - p3;
2928 d2[2] = p2;
2929 d3[1] = p2;
2930
2931 p1 = e[0]*B[1] - e[1]*B[0];
2932 p0 = -e[0]*B[0] - e[1]*B[1];
2933
2934 d0[3] = p1;
2935 d1[0] = - p1;
2936 d2[3] = p0;
2937 d3[0] = p0;
2938
2939 B -= 8;
2940 e -= 8;
2941 d0 += 4;
2942 d2 += 4;
2943 d1 -= 4;
2944 d3 -= 4;
2945 }
2946 }
2947
2948 temp_alloc_restore(f,save_point);
2949 }
2950
2951 #if 0
2952 // this is the original version of the above code, if you want to optimize it from scratch
2953 void inverse_mdct_naive(float *buffer, int n)
2954 {
2955 float s;
2956 float A[1 << 12], B[1 << 12], C[1 << 11];
2957 int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
2958 int n3_4 = n - n4, ld;
2959 // how can they claim this only uses N words?!
2960 // oh, because they're only used sparsely, whoops
2961 float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
2962 // set up twiddle factors
2963
2964 for (k=k2=0; k < n4; ++k,k2+=2) {
2965 A[k2 ] = (float) cos(4*k*M_PI/n);
2966 A[k2+1] = (float) -sin(4*k*M_PI/n);
2967 B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
2968 B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
2969 }
2970 for (k=k2=0; k < n8; ++k,k2+=2) {
2971 C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
2972 C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
2973 }
2974
2975 // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
2976 // Note there are bugs in that pseudocode, presumably due to them attempting
2977 // to rename the arrays nicely rather than representing the way their actual
2978 // implementation bounces buffers back and forth. As a result, even in the
2979 // "some formulars corrected" version, a direct implementation fails. These
2980 // are noted below as "paper bug".
2981
2982 // copy and reflect spectral data
2983 for (k=0; k < n2; ++k) u[k] = buffer[k];
2984 for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
2985 // kernel from paper
2986 // step 1
2987 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
2988 v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
2989 v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
2990 }
2991 // step 2
2992 for (k=k4=0; k < n8; k+=1, k4+=4) {
2993 w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
2994 w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
2995 w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
2996 w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
2997 }
2998 // step 3
2999 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
3000 for (l=0; l < ld-3; ++l) {
3001 int k0 = n >> (l+2), k1 = 1 << (l+3);
3002 int rlim = n >> (l+4), r4, r;
3003 int s2lim = 1 << (l+2), s2;
3004 for (r=r4=0; r < rlim; r4+=4,++r) {
3005 for (s2=0; s2 < s2lim; s2+=2) {
3006 u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
3007 u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
3008 u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
3009 - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
3010 u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
3011 + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
3012 }
3013 }
3014 if (l+1 < ld-3) {
3015 // paper bug: ping-ponging of u&w here is omitted
3016 memcpy(w, u, sizeof(u));
3017 }
3018 }
3019
3020 // step 4
3021 for (i=0; i < n8; ++i) {
3022 int j = bit_reverse(i) >> (32-ld+3);
3023 assert(j < n8);
3024 if (i == j) {
3025 // paper bug: original code probably swapped in place; if copying,
3026 // need to directly copy in this case
3027 int i8 = i << 3;
3028 v[i8+1] = u[i8+1];
3029 v[i8+3] = u[i8+3];
3030 v[i8+5] = u[i8+5];
3031 v[i8+7] = u[i8+7];
3032 } else if (i < j) {
3033 int i8 = i << 3, j8 = j << 3;
3034 v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
3035 v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
3036 v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
3037 v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
3038 }
3039 }
3040 // step 5
3041 for (k=0; k < n2; ++k) {
3042 w[k] = v[k*2+1];
3043 }
3044 // step 6
3045 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
3046 u[n-1-k2] = w[k4];
3047 u[n-2-k2] = w[k4+1];
3048 u[n3_4 - 1 - k2] = w[k4+2];
3049 u[n3_4 - 2 - k2] = w[k4+3];
3050 }
3051 // step 7
3052 for (k=k2=0; k < n8; ++k, k2 += 2) {
3053 v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
3054 v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
3055 v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
3056 v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
3057 }
3058 // step 8
3059 for (k=k2=0; k < n4; ++k,k2 += 2) {
3060 X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
3061 X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
3062 }
3063
3064 // decode kernel to output
3065 // determined the following value experimentally
3066 // (by first figuring out what made inverse_mdct_slow work); then matching that here
3067 // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
3068 s = 0.5; // theoretically would be n4
3069
3070 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
3071 // so it needs to use the "old" B values to behave correctly, or else
3072 // set s to 1.0 ]]]
3073 for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
3074 for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
3075 for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
3076 }
3077 #endif
3078
3079 static float *get_window(vorb *f, int len)
3080 {
3081 len <<= 1;
3082 if (len == f->blocksize_0) return f->window[0];
3083 if (len == f->blocksize_1) return f->window[1];
3084 assert(0);
3085 return NULL;
3086 }
3087
3088 #ifndef STB_VORBIS_NO_DEFER_FLOOR
3089 typedef int16 YTYPE;
3090 #else
3091 typedef int YTYPE;
3092 #endif
3093 static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
3094 {
3095 int n2 = n >> 1;
3096 int s = map->chan[i].mux, floor;
3097 floor = map->submap_floor[s];
3098 if (f->floor_types[floor] == 0) {
3099 return error(f, VORBIS_invalid_stream);
3100 } else {
3101 Floor1 *g = &f->floor_config[floor].floor1;
3102 int j,q;
3103 int lx = 0, ly = finalY[0] * g->floor1_multiplier;
3104 for (q=1; q < g->values; ++q) {
3105 j = g->sorted_order[q];
3106 #ifndef STB_VORBIS_NO_DEFER_FLOOR
3107 if (finalY[j] >= 0)
3108 #else
3109 if (step2_flag[j])
3110 #endif
3111 {
3112 int hy = finalY[j] * g->floor1_multiplier;
3113 int hx = g->Xlist[j];
3114 draw_line(target, lx,ly, hx,hy, n2);
3115 lx = hx, ly = hy;
3116 }
3117 }
3118 if (lx < n2)
3119 // optimization of: draw_line(target, lx,ly, n,ly, n2);
3120 for (j=lx; j < n2; ++j)
3121 LINE_OP(target[j], inverse_db_table[ly]);
3122 }
3123 return TRUE;
3124 }
3125
3126 static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
3127 {
3128 Mode *m;
3129 int i, n, prev, next, window_center;
3130 f->channel_buffer_start = f->channel_buffer_end = 0;
3131
3132 retry:
3133 if (f->eof) return FALSE;
3134 if (!maybe_start_packet(f))
3135 return FALSE;
3136 // check packet type
3137 if (get_bits(f,1) != 0) {
3138 if (IS_PUSH_MODE(f))
3139 return error(f,VORBIS_bad_packet_type);
3140 while (EOP != get8_packet(f));
3141 goto retry;
3142 }
3143
3144 if (f->alloc.alloc_buffer)
3145 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3146
3147 i = get_bits(f, ilog(f->mode_count-1));
3148 if (i == EOP) return FALSE;
3149 if (i >= f->mode_count) return FALSE;
3150 *mode = i;
3151 m = f->mode_config + i;
3152 if (m->blockflag) {
3153 n = f->blocksize_1;
3154 prev = get_bits(f,1);
3155 next = get_bits(f,1);
3156 } else {
3157 prev = next = 0;
3158 n = f->blocksize_0;
3159 }
3160
3161 // WINDOWING
3162
3163 window_center = n >> 1;
3164 if (m->blockflag && !prev) {
3165 *p_left_start = (n - f->blocksize_0) >> 2;
3166 *p_left_end = (n + f->blocksize_0) >> 2;
3167 } else {
3168 *p_left_start = 0;
3169 *p_left_end = window_center;
3170 }
3171 if (m->blockflag && !next) {
3172 *p_right_start = (n*3 - f->blocksize_0) >> 2;
3173 *p_right_end = (n*3 + f->blocksize_0) >> 2;
3174 } else {
3175 *p_right_start = window_center;
3176 *p_right_end = n;
3177 }
3178 return TRUE;
3179 }
3180
3181 static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
3182 {
3183 Mapping *map;
3184 int i,j,k,n,n2;
3185 int zero_channel[256];
3186 int really_zero_channel[256];
3187 int window_center;
3188
3189 // WINDOWING
3190
3191 n = f->blocksize[m->blockflag];
3192 window_center = n >> 1;
3193
3194 map = &f->mapping[m->mapping];
3195
3196 // FLOORS
3197 n2 = n >> 1;
3198
3199 stb_prof(1);
3200 for (i=0; i < f->channels; ++i) {
3201 int s = map->chan[i].mux, floor;
3202 zero_channel[i] = FALSE;
3203 floor = map->submap_floor[s];
3204 if (f->floor_types[floor] == 0) {
3205 return error(f, VORBIS_invalid_stream);
3206 } else {
3207 Floor1 *g = &f->floor_config[floor].floor1;
3208 if (get_bits(f, 1)) {
3209 short *finalY;
3210 uint8 step2_flag[256];
3211 static int range_list[4] = { 256, 128, 86, 64 };
3212 int range = range_list[g->floor1_multiplier-1];
3213 int offset = 2;
3214 finalY = f->finalY[i];
3215 finalY[0] = get_bits(f, ilog(range)-1);
3216 finalY[1] = get_bits(f, ilog(range)-1);
3217 for (j=0; j < g->partitions; ++j) {
3218 int pclass = g->partition_class_list[j];
3219 int cdim = g->class_dimensions[pclass];
3220 int cbits = g->class_subclasses[pclass];
3221 int csub = (1 << cbits)-1;
3222 int cval = 0;
3223 if (cbits) {
3224 Codebook *c = f->codebooks + g->class_masterbooks[pclass];
3225 DECODE(cval,f,c);
3226 }
3227 for (k=0; k < cdim; ++k) {
3228 int book = g->subclass_books[pclass][cval & csub];
3229 cval = cval >> cbits;
3230 if (book >= 0) {
3231 int temp;
3232 Codebook *c = f->codebooks + book;
3233 DECODE(temp,f,c);
3234 finalY[offset++] = temp;
3235 } else
3236 finalY[offset++] = 0;
3237 }
3238 }
3239 if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
3240 step2_flag[0] = step2_flag[1] = 1;
3241 for (j=2; j < g->values; ++j) {
3242 int low, high, pred, highroom, lowroom, room, val;
3243 low = g->neighbors[j][0];
3244 high = g->neighbors[j][1];
3245 //neighbors(g->Xlist, j, &low, &high);
3246 pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
3247 val = finalY[j];
3248 highroom = range - pred;
3249 lowroom = pred;
3250 if (highroom < lowroom)
3251 room = highroom * 2;
3252 else
3253 room = lowroom * 2;
3254 if (val) {
3255 step2_flag[low] = step2_flag[high] = 1;
3256 step2_flag[j] = 1;
3257 if (val >= room)
3258 if (highroom > lowroom)
3259 finalY[j] = val - lowroom + pred;
3260 else
3261 finalY[j] = pred - val + highroom - 1;
3262 else
3263 if (val & 1)
3264 finalY[j] = pred - ((val+1)>>1);
3265 else
3266 finalY[j] = pred + (val>>1);
3267 } else {
3268 step2_flag[j] = 0;
3269 finalY[j] = pred;
3270 }
3271 }
3272
3273 #ifdef STB_VORBIS_NO_DEFER_FLOOR
3274 do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
3275 #else
3276 // defer final floor computation until _after_ residue
3277 for (j=0; j < g->values; ++j) {
3278 if (!step2_flag[j])
3279 finalY[j] = -1;
3280 }
3281 #endif
3282 } else {
3283 error:
3284 zero_channel[i] = TRUE;
3285 }
3286 // So we just defer everything else to later
3287
3288 // at this point we've decoded the floor into buffer
3289 }
3290 }
3291 stb_prof(0);
3292 // at this point we've decoded all floors
3293
3294 if (f->alloc.alloc_buffer)
3295 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3296
3297 // re-enable coupled channels if necessary
3298 memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
3299 for (i=0; i < map->coupling_steps; ++i)
3300 if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
3301 zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
3302 }
3303
3304 // RESIDUE DECODE
3305 for (i=0; i < map->submaps; ++i) {
3306 float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
3307 int r,t;
3308 uint8 do_not_decode[256];
3309 int ch = 0;
3310 for (j=0; j < f->channels; ++j) {
3311 if (map->chan[j].mux == i) {
3312 if (zero_channel[j]) {
3313 do_not_decode[ch] = TRUE;
3314 residue_buffers[ch] = NULL;
3315 } else {
3316 do_not_decode[ch] = FALSE;
3317 residue_buffers[ch] = f->channel_buffers[j];
3318 }
3319 ++ch;
3320 }
3321 }
3322 r = map->submap_residue[i];
3323 t = f->residue_types[r];
3324 decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
3325 }
3326
3327 if (f->alloc.alloc_buffer)
3328 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3329
3330 // INVERSE COUPLING
3331 stb_prof(14);
3332 for (i = map->coupling_steps-1; i >= 0; --i) {
3333 int n2 = n >> 1;
3334 float *m = f->channel_buffers[map->chan[i].magnitude];
3335 float *a = f->channel_buffers[map->chan[i].angle ];
3336 for (j=0; j < n2; ++j) {
3337 float a2,m2;
3338 if (m[j] > 0)
3339 if (a[j] > 0)
3340 m2 = m[j], a2 = m[j] - a[j];
3341 else
3342 a2 = m[j], m2 = m[j] + a[j];
3343 else
3344 if (a[j] > 0)
3345 m2 = m[j], a2 = m[j] + a[j];
3346 else
3347 a2 = m[j], m2 = m[j] - a[j];
3348 m[j] = m2;
3349 a[j] = a2;
3350 }
3351 }
3352
3353 // finish decoding the floors
3354 #ifndef STB_VORBIS_NO_DEFER_FLOOR
3355 stb_prof(15);
3356 for (i=0; i < f->channels; ++i) {
3357 if (really_zero_channel[i]) {
3358 memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
3359 } else {
3360 do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
3361 }
3362 }
3363 #else
3364 for (i=0; i < f->channels; ++i) {
3365 if (really_zero_channel[i]) {
3366 memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
3367 } else {
3368 for (j=0; j < n2; ++j)
3369 f->channel_buffers[i][j] *= f->floor_buffers[i][j];
3370 }
3371 }
3372 #endif
3373
3374 // INVERSE MDCT
3375 stb_prof(16);
3376 for (i=0; i < f->channels; ++i)
3377 inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
3378 stb_prof(0);
3379
3380 // this shouldn't be necessary, unless we exited on an error
3381 // and want to flush to get to the next packet
3382 flush_packet(f);
3383
3384 if (f->first_decode) {
3385 // assume we start so first non-discarded sample is sample 0
3386 // this isn't to spec, but spec would require us to read ahead
3387 // and decode the size of all current frames--could be done,
3388 // but presumably it's not a commonly used feature
3389 f->current_loc = -n2; // start of first frame is positioned for discard
3390 // we might have to discard samples "from" the next frame too,
3391 // if we're lapping a large block then a small at the start?
3392 f->discard_samples_deferred = n - right_end;
3393 f->current_loc_valid = TRUE;
3394 f->first_decode = FALSE;
3395 } else if (f->discard_samples_deferred) {
3396 left_start += f->discard_samples_deferred;
3397 *p_left = left_start;
3398 f->discard_samples_deferred = 0;
3399 } else if (f->previous_length == 0 && f->current_loc_valid) {
3400 // we're recovering from a seek... that means we're going to discard
3401 // the samples from this packet even though we know our position from
3402 // the last page header, so we need to update the position based on
3403 // the discarded samples here
3404 // but wait, the code below is going to add this in itself even
3405 // on a discard, so we don't need to do it here...
3406 }
3407
3408 // check if we have ogg information about the sample # for this packet
3409 if (f->last_seg_which == f->end_seg_with_known_loc) {
3410 // if we have a valid current loc, and this is final:
3411 if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
3412 uint32 current_end = f->known_loc_for_packet - (n-right_end);
3413 // then let's infer the size of the (probably) short final frame
3414 if (current_end < f->current_loc + right_end) {
3415 if (current_end < f->current_loc) {
3416 // negative truncation, that's impossible!
3417 *len = 0;
3418 } else {
3419 *len = current_end - f->current_loc;
3420 }
3421 *len += left_start;
3422 f->current_loc += *len;
3423 return TRUE;
3424 }
3425 }
3426 // otherwise, just set our sample loc
3427 // guess that the ogg granule pos refers to the _middle_ of the
3428 // last frame?
3429 // set f->current_loc to the position of left_start
3430 f->current_loc = f->known_loc_for_packet - (n2-left_start);
3431 f->current_loc_valid = TRUE;
3432 }
3433 if (f->current_loc_valid)
3434 f->current_loc += (right_start - left_start);
3435
3436 if (f->alloc.alloc_buffer)
3437 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3438 *len = right_end; // ignore samples after the window goes to 0
3439 return TRUE;
3440 }
3441
3442 static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
3443 {
3444 int mode, left_end, right_end;
3445 if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
3446 return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
3447 }
3448
3449 static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
3450 {
3451 int prev,i,j;
3452 // we use right&left (the start of the right- and left-window sin()-regions)
3453 // to determine how much to return, rather than inferring from the rules
3454 // (same result, clearer code); 'left' indicates where our sin() window
3455 // starts, therefore where the previous window's right edge starts, and
3456 // therefore where to start mixing from the previous buffer. 'right'
3457 // indicates where our sin() ending-window starts, therefore that's where
3458 // we start saving, and where our returned-data ends.
3459
3460 // mixin from previous window
3461 if (f->previous_length) {
3462 int i,j, n = f->previous_length;
3463 float *w = get_window(f, n);
3464 for (i=0; i < f->channels; ++i) {
3465 for (j=0; j < n; ++j)
3466 f->channel_buffers[i][left+j] =
3467 f->channel_buffers[i][left+j]*w[ j] +
3468 f->previous_window[i][ j]*w[n-1-j];
3469 }
3470 }
3471
3472 prev = f->previous_length;
3473
3474 // last half of this data becomes previous window
3475 f->previous_length = len - right;
3476
3477 // @OPTIMIZE: could avoid this copy by double-buffering the
3478 // output (flipping previous_window with channel_buffers), but
3479 // then previous_window would have to be 2x as large, and
3480 // channel_buffers couldn't be temp mem (although they're NOT
3481 // currently temp mem, they could be (unless we want to level
3482 // performance by spreading out the computation))
3483 for (i=0; i < f->channels; ++i)
3484 for (j=0; right+j < len; ++j)
3485 f->previous_window[i][j] = f->channel_buffers[i][right+j];
3486
3487 if (!prev)
3488 // there was no previous packet, so this data isn't valid...
3489 // this isn't entirely true, only the would-have-overlapped data
3490 // isn't valid, but this seems to be what the spec requires
3491 return 0;
3492
3493 // truncate a short frame
3494 if (len < right) right = len;
3495
3496 f->samples_output += right-left;
3497
3498 return right - left;
3499 }
3500
3501 static void vorbis_pump_first_frame(stb_vorbis *f)
3502 {
3503 int len, right, left;
3504 if (vorbis_decode_packet(f, &len, &left, &right))
3505 vorbis_finish_frame(f, len, left, right);
3506 }
3507
3508 #ifndef STB_VORBIS_NO_PUSHDATA_API
3509 static int is_whole_packet_present(stb_vorbis *f, int end_page)
3510 {
3511 // make sure that we have the packet available before continuing...
3512 // this requires a full ogg parse, but we know we can fetch from f->stream
3513
3514 // instead of coding this out explicitly, we could save the current read state,
3515 // read the next packet with get8() until end-of-packet, check f->eof, then
3516 // reset the state? but that would be slower, esp. since we'd have over 256 bytes
3517 // of state to restore (primarily the page segment table)
3518
3519 int s = f->next_seg, first = TRUE;
3520 uint8 *p = f->stream;
3521
3522 if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
3523 for (; s < f->segment_count; ++s) {
3524 p += f->segments[s];
3525 if (f->segments[s] < 255) // stop at first short segment
3526 break;
3527 }
3528 // either this continues, or it ends it...
3529 if (end_page)
3530 if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream);
3531 if (s == f->segment_count)
3532 s = -1; // set 'crosses page' flag
3533 if (p > f->stream_end) return error(f, VORBIS_need_more_data);
3534 first = FALSE;
3535 }
3536 for (; s == -1;) {
3537 uint8 *q;
3538 int n;
3539
3540 // check that we have the page header ready
3541 if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
3542 // validate the page
3543 if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
3544 if (p[4] != 0) return error(f, VORBIS_invalid_stream);
3545 if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
3546 if (f->previous_length)
3547 if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
3548 // if no previous length, we're resynching, so we can come in on a continued-packet,
3549 // which we'll just drop
3550 } else {
3551 if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
3552 }
3553 n = p[26]; // segment counts
3554 q = p+27; // q points to segment table
3555 p = q + n; // advance past header
3556 // make sure we've read the segment table
3557 if (p > f->stream_end) return error(f, VORBIS_need_more_data);
3558 for (s=0; s < n; ++s) {
3559 p += q[s];
3560 if (q[s] < 255)
3561 break;
3562 }
3563 if (end_page)
3564 if (s < n-1) return error(f, VORBIS_invalid_stream);
3565 if (s == f->segment_count)
3566 s = -1; // set 'crosses page' flag
3567 if (p > f->stream_end) return error(f, VORBIS_need_more_data);
3568 first = FALSE;
3569 }
3570 return TRUE;
3571 }
3572 #endif // !STB_VORBIS_NO_PUSHDATA_API
3573
3574 static int start_decoder(vorb *f)
3575 {
3576 uint8 header[6], x,y;
3577 int len,i,j,k, max_submaps = 0;
3578 int longest_floorlist=0;
3579
3580 // first page, first packet
3581
3582 if (!start_page(f)) return FALSE;
3583 // validate page flag
3584 if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
3585 if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
3586 if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
3587 // check for expected packet length
3588 if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
3589 if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
3590 // read packet
3591 // check packet header
3592 if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
3593 if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
3594 if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
3595 // vorbis_version
3596 if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
3597 f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
3598 if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
3599 f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
3600 get32(f); // bitrate_maximum
3601 get32(f); // bitrate_nominal
3602 get32(f); // bitrate_minimum
3603 x = get8(f);
3604 { int log0,log1;
3605 log0 = x & 15;
3606 log1 = x >> 4;
3607 f->blocksize_0 = 1 << log0;
3608 f->blocksize_1 = 1 << log1;
3609 if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
3610 if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
3611 if (log0 > log1) return error(f, VORBIS_invalid_setup);
3612 }
3613
3614 // framing_flag
3615 x = get8(f);
3616 if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
3617
3618 // second packet!
3619 if (!start_page(f)) return FALSE;
3620
3621 if (!start_packet(f)) return FALSE;
3622 do {
3623 len = next_segment(f);
3624 skip(f, len);
3625 f->bytes_in_seg = 0;
3626 } while (len);
3627
3628 // third packet!
3629 if (!start_packet(f)) return FALSE;
3630
3631 #ifndef STB_VORBIS_NO_PUSHDATA_API
3632 if (IS_PUSH_MODE(f)) {
3633 if (!is_whole_packet_present(f, TRUE)) {
3634 // convert error in ogg header to write type
3635 if (f->error == VORBIS_invalid_stream)
3636 f->error = VORBIS_invalid_setup;
3637 return FALSE;
3638 }
3639 }
3640 #endif
3641
3642 crc32_init(); // always init it, to avoid multithread race conditions
3643
3644 if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
3645 for (i=0; i < 6; ++i) header[i] = get8_packet(f);
3646 if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
3647
3648 // codebooks
3649
3650 f->codebook_count = get_bits(f,8) + 1;
3651 f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
3652 if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
3653 memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
3654 for (i=0; i < f->codebook_count; ++i) {
3655 uint32 *values;
3656 int ordered, sorted_count;
3657 int total=0;
3658 uint8 *lengths;
3659 Codebook *c = f->codebooks+i;
3660 x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
3661 x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
3662 x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
3663 x = get_bits(f, 8);
3664 c->dimensions = (get_bits(f, 8)<<8) + x;
3665 x = get_bits(f, 8);
3666 y = get_bits(f, 8);
3667 c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
3668 ordered = get_bits(f,1);
3669 c->sparse = ordered ? 0 : get_bits(f,1);
3670
3671 if (c->sparse)
3672 lengths = (uint8 *) setup_temp_malloc(f, c->entries);
3673 else
3674 lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
3675
3676 if (!lengths) return error(f, VORBIS_outofmem);
3677
3678 if (ordered) {
3679 int current_entry = 0;
3680 int current_length = get_bits(f,5) + 1;
3681 while (current_entry < c->entries) {
3682 int limit = c->entries - current_entry;
3683 int n = get_bits(f, ilog(limit));
3684 if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
3685 memset(lengths + current_entry, current_length, n);
3686 current_entry += n;
3687 ++current_length;
3688 }
3689 } else {
3690 for (j=0; j < c->entries; ++j) {
3691 int present = c->sparse ? get_bits(f,1) : 1;
3692 if (present) {
3693 lengths[j] = get_bits(f, 5) + 1;
3694 ++total;
3695 } else {
3696 lengths[j] = NO_CODE;
3697 }
3698 }
3699 }
3700
3701 if (c->sparse && total >= c->entries >> 2) {
3702 // convert sparse items to non-sparse!
3703 if (c->entries > (int) f->setup_temp_memory_required)
3704 f->setup_temp_memory_required = c->entries;
3705
3706 c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
3707 memcpy(c->codeword_lengths, lengths, c->entries);
3708 setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
3709 lengths = c->codeword_lengths;
3710 c->sparse = 0;
3711 }
3712
3713 // compute the size of the sorted tables
3714 if (c->sparse) {
3715 sorted_count = total;
3716 //assert(total != 0);
3717 } else {
3718 sorted_count = 0;
3719 #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
3720 for (j=0; j < c->entries; ++j)
3721 if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
3722 ++sorted_count;
3723 #endif
3724 }
3725
3726 c->sorted_entries = sorted_count;
3727 values = NULL;
3728
3729 if (!c->sparse) {
3730 c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
3731 if (!c->codewords) return error(f, VORBIS_outofmem);
3732 } else {
3733 unsigned int size;
3734 if (c->sorted_entries) {
3735 c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
3736 if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
3737 c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
3738 if (!c->codewords) return error(f, VORBIS_outofmem);
3739 values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
3740 if (!values) return error(f, VORBIS_outofmem);
3741 }
3742 size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
3743 if (size > f->setup_temp_memory_required)
3744 f->setup_temp_memory_required = size;
3745 }
3746
3747 if (!compute_codewords(c, lengths, c->entries, values)) {
3748 if (c->sparse) setup_temp_free(f, values, 0);
3749 return error(f, VORBIS_invalid_setup);
3750 }
3751
3752 if (c->sorted_entries) {
3753 // allocate an extra slot for sentinels
3754 c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
3755 // allocate an extra slot at the front so that c->sorted_values[-1] is defined
3756 // so that we can catch that case without an extra if
3757 c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
3758 if (c->sorted_values) { ++c->sorted_values; c->sorted_values[-1] = -1; }
3759 compute_sorted_huffman(c, lengths, values);
3760 }
3761
3762 if (c->sparse) {
3763 setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
3764 setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
3765 setup_temp_free(f, lengths, c->entries);
3766 c->codewords = NULL;
3767 }
3768
3769 compute_accelerated_huffman(c);
3770
3771 c->lookup_type = get_bits(f, 4);
3772 if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
3773 if (c->lookup_type > 0) {
3774 uint16 *mults;
3775 c->minimum_value = float32_unpack(get_bits(f, 32));
3776 c->delta_value = float32_unpack(get_bits(f, 32));
3777 c->value_bits = get_bits(f, 4)+1;
3778 c->sequence_p = get_bits(f,1);
3779 if (c->lookup_type == 1) {
3780 c->lookup_values = lookup1_values(c->entries, c->dimensions);
3781 } else {
3782 c->lookup_values = c->entries * c->dimensions;
3783 }
3784 mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
3785 if (mults == NULL) return error(f, VORBIS_outofmem);
3786 for (j=0; j < (int) c->lookup_values; ++j) {
3787 int q = get_bits(f, c->value_bits);
3788 if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
3789 mults[j] = q;
3790 }
3791
3792 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
3793 if (c->lookup_type == 1) {
3794 int len, sparse = c->sparse;
3795 // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
3796 if (sparse) {
3797 if (c->sorted_entries == 0) goto skip;
3798 c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
3799 } else
3800 c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
3801 if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
3802 len = sparse ? c->sorted_entries : c->entries;
3803 for (j=0; j < len; ++j) {
3804 int z = sparse ? c->sorted_values[j] : j, div=1;
3805 for (k=0; k < c->dimensions; ++k) {
3806 int off = (z / div) % c->lookup_values;
3807 c->multiplicands[j*c->dimensions + k] =
3808 #ifndef STB_VORBIS_CODEBOOK_FLOATS
3809 mults[off];
3810 #else
3811 mults[off]*c->delta_value + c->minimum_value;
3812 // in this case (and this case only) we could pre-expand c->sequence_p,
3813 // and throw away the decode logic for it; have to ALSO do
3814 // it in the case below, but it can only be done if
3815 // STB_VORBIS_CODEBOOK_FLOATS
3816 // !STB_VORBIS_DIVIDES_IN_CODEBOOK
3817 #endif
3818 div *= c->lookup_values;
3819 }
3820 }
3821 setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
3822 c->lookup_type = 2;
3823 }
3824 else
3825 #endif
3826 {
3827 c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
3828 #ifndef STB_VORBIS_CODEBOOK_FLOATS
3829 memcpy(c->multiplicands, mults, sizeof(c->multiplicands[0]) * c->lookup_values);
3830 #else
3831 for (j=0; j < (int) c->lookup_values; ++j)
3832 c->multiplicands[j] = mults[j] * c->delta_value + c->minimum_value;
3833 setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
3834 #endif
3835 }
3836 skip:;
3837
3838 #ifdef STB_VORBIS_CODEBOOK_FLOATS
3839 if (c->lookup_type == 2 && c->sequence_p) {
3840 for (j=1; j < (int) c->lookup_values; ++j)
3841 c->multiplicands[j] = c->multiplicands[j-1];
3842 c->sequence_p = 0;
3843 }
3844 #endif
3845 }
3846 }
3847
3848 // time domain transfers (notused)
3849
3850 x = get_bits(f, 6) + 1;
3851 for (i=0; i < x; ++i) {
3852 uint32 z = get_bits(f, 16);
3853 if (z != 0) return error(f, VORBIS_invalid_setup);
3854 }
3855
3856 // Floors
3857 f->floor_count = get_bits(f, 6)+1;
3858 f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
3859 for (i=0; i < f->floor_count; ++i) {
3860 f->floor_types[i] = get_bits(f, 16);
3861 if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
3862 if (f->floor_types[i] == 0) {
3863 Floor0 *g = &f->floor_config[i].floor0;
3864 g->order = get_bits(f,8);
3865 g->rate = get_bits(f,16);
3866 g->bark_map_size = get_bits(f,16);
3867 g->amplitude_bits = get_bits(f,6);
3868 g->amplitude_offset = get_bits(f,8);
3869 g->number_of_books = get_bits(f,4) + 1;
3870 for (j=0; j < g->number_of_books; ++j)
3871 g->book_list[j] = get_bits(f,8);
3872 return error(f, VORBIS_feature_not_supported);
3873 } else {
3874 Point p[31*8+2];
3875 Floor1 *g = &f->floor_config[i].floor1;
3876 int max_class = -1;
3877 g->partitions = get_bits(f, 5);
3878 for (j=0; j < g->partitions; ++j) {
3879 g->partition_class_list[j] = get_bits(f, 4);
3880 if (g->partition_class_list[j] > max_class)
3881 max_class = g->partition_class_list[j];
3882 }
3883 for (j=0; j <= max_class; ++j) {
3884 g->class_dimensions[j] = get_bits(f, 3)+1;
3885 g->class_subclasses[j] = get_bits(f, 2);
3886 if (g->class_subclasses[j]) {
3887 g->class_masterbooks[j] = get_bits(f, 8);
3888 if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
3889 }
3890 for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
3891 g->subclass_books[j][k] = get_bits(f,8)-1;
3892 if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
3893 }
3894 }
3895 g->floor1_multiplier = get_bits(f,2)+1;
3896 g->rangebits = get_bits(f,4);
3897 g->Xlist[0] = 0;
3898 g->Xlist[1] = 1 << g->rangebits;
3899 g->values = 2;
3900 for (j=0; j < g->partitions; ++j) {
3901 int c = g->partition_class_list[j];
3902 for (k=0; k < g->class_dimensions[c]; ++k) {
3903 g->Xlist[g->values] = get_bits(f, g->rangebits);
3904 ++g->values;
3905 }
3906 }
3907 // precompute the sorting
3908 for (j=0; j < g->values; ++j) {
3909 p[j].x = g->Xlist[j];
3910 p[j].y = j;
3911 }
3912 qsort(p, g->values, sizeof(p[0]), point_compare);
3913 for (j=0; j < g->values; ++j)
3914 g->sorted_order[j] = (uint8) p[j].y;
3915 // precompute the neighbors
3916 for (j=2; j < g->values; ++j) {
3917 int low,hi;
3918 neighbors(g->Xlist, j, &low,&hi);
3919 g->neighbors[j][0] = low;
3920 g->neighbors[j][1] = hi;
3921 }
3922
3923 if (g->values > longest_floorlist)
3924 longest_floorlist = g->values;
3925 }
3926 }
3927
3928 // Residue
3929 f->residue_count = get_bits(f, 6)+1;
3930 f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(*f->residue_config));
3931 for (i=0; i < f->residue_count; ++i) {
3932 uint8 residue_cascade[64];
3933 Residue *r = f->residue_config+i;
3934 f->residue_types[i] = get_bits(f, 16);
3935 if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
3936 r->begin = get_bits(f, 24);
3937 r->end = get_bits(f, 24);
3938 r->part_size = get_bits(f,24)+1;
3939 r->classifications = get_bits(f,6)+1;
3940 r->classbook = get_bits(f,8);
3941 for (j=0; j < r->classifications; ++j) {
3942 uint8 high_bits=0;
3943 uint8 low_bits=get_bits(f,3);
3944 if (get_bits(f,1))
3945 high_bits = get_bits(f,5);
3946 residue_cascade[j] = high_bits*8 + low_bits;
3947 }
3948 r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
3949 for (j=0; j < r->classifications; ++j) {
3950 for (k=0; k < 8; ++k) {
3951 if (residue_cascade[j] & (1 << k)) {
3952 r->residue_books[j][k] = get_bits(f, 8);
3953 if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
3954 } else {
3955 r->residue_books[j][k] = -1;
3956 }
3957 }
3958 }
3959 // precompute the classifications[] array to avoid inner-loop mod/divide
3960 // call it 'classdata' since we already have r->classifications
3961 r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
3962 if (!r->classdata) return error(f, VORBIS_outofmem);
3963 memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
3964 for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
3965 int classwords = f->codebooks[r->classbook].dimensions;
3966 int temp = j;
3967 r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
3968 for (k=classwords-1; k >= 0; --k) {
3969 r->classdata[j][k] = temp % r->classifications;
3970 temp /= r->classifications;
3971 }
3972 }
3973 }
3974
3975 f->mapping_count = get_bits(f,6)+1;
3976 f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
3977 for (i=0; i < f->mapping_count; ++i) {
3978 Mapping *m = f->mapping + i;
3979 int mapping_type = get_bits(f,16);
3980 if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
3981 m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
3982 if (get_bits(f,1))
3983 m->submaps = get_bits(f,4);
3984 else
3985 m->submaps = 1;
3986 if (m->submaps > max_submaps)
3987 max_submaps = m->submaps;
3988 if (get_bits(f,1)) {
3989 m->coupling_steps = get_bits(f,8)+1;
3990 for (k=0; k < m->coupling_steps; ++k) {
3991 m->chan[k].magnitude = get_bits(f, ilog(f->channels)-1);
3992 m->chan[k].angle = get_bits(f, ilog(f->channels)-1);
3993 if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
3994 if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
3995 if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
3996 }
3997 } else
3998 m->coupling_steps = 0;
3999
4000 // reserved field
4001 if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
4002 if (m->submaps > 1) {
4003 for (j=0; j < f->channels; ++j) {
4004 m->chan[j].mux = get_bits(f, 4);
4005 if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
4006 }
4007 } else
4008 // @SPECIFICATION: this case is missing from the spec
4009 for (j=0; j < f->channels; ++j)
4010 m->chan[j].mux = 0;
4011
4012 for (j=0; j < m->submaps; ++j) {
4013 get_bits(f,8); // discard
4014 m->submap_floor[j] = get_bits(f,8);
4015 m->submap_residue[j] = get_bits(f,8);
4016 if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
4017 if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
4018 }
4019 }
4020
4021 // Modes
4022 f->mode_count = get_bits(f, 6)+1;
4023 for (i=0; i < f->mode_count; ++i) {
4024 Mode *m = f->mode_config+i;
4025 m->blockflag = get_bits(f,1);
4026 m->windowtype = get_bits(f,16);
4027 m->transformtype = get_bits(f,16);
4028 m->mapping = get_bits(f,8);
4029 if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
4030 if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
4031 if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
4032 }
4033
4034 flush_packet(f);
4035
4036 f->previous_length = 0;
4037
4038 for (i=0; i < f->channels; ++i) {
4039 f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
4040 f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
4041 f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
4042 #ifdef STB_VORBIS_NO_DEFER_FLOOR
4043 f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
4044 #endif
4045 }
4046
4047 if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
4048 if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
4049 f->blocksize[0] = f->blocksize_0;
4050 f->blocksize[1] = f->blocksize_1;
4051
4052 #ifdef STB_VORBIS_DIVIDE_TABLE
4053 if (integer_divide_table[1][1]==0)
4054 for (i=0; i < DIVTAB_NUMER; ++i)
4055 for (j=1; j < DIVTAB_DENOM; ++j)
4056 integer_divide_table[i][j] = i / j;
4057 #endif
4058
4059 // compute how much temporary memory is needed
4060
4061 // 1.
4062 {
4063 uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
4064 uint32 classify_mem;
4065 int i,max_part_read=0;
4066 for (i=0; i < f->residue_count; ++i) {
4067 Residue *r = f->residue_config + i;
4068 int n_read = r->end - r->begin;
4069 int part_read = n_read / r->part_size;
4070 if (part_read > max_part_read)
4071 max_part_read = part_read;
4072 }
4073 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
4074 classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
4075 #else
4076 classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
4077 #endif
4078
4079 f->temp_memory_required = classify_mem;
4080 if (imdct_mem > f->temp_memory_required)
4081 f->temp_memory_required = imdct_mem;
4082 }
4083
4084 f->first_decode = TRUE;
4085
4086 if (f->alloc.alloc_buffer) {
4087 assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
4088 // check if there's enough temp memory so we don't error later
4089 if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
4090 return error(f, VORBIS_outofmem);
4091 }
4092
4093 f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
4094
4095 return TRUE;
4096 }
4097
4098 static void vorbis_deinit(stb_vorbis *p)
4099 {
4100 int i,j;
4101 for (i=0; i < p->residue_count; ++i) {
4102 Residue *r = p->residue_config+i;
4103 if (r->classdata) {
4104 for (j=0; j < p->codebooks[r->classbook].entries; ++j)
4105 setup_free(p, r->classdata[j]);
4106 setup_free(p, r->classdata);
4107 }
4108 setup_free(p, r->residue_books);
4109 }
4110
4111 if (p->codebooks) {
4112 for (i=0; i < p->codebook_count; ++i) {
4113 Codebook *c = p->codebooks + i;
4114 setup_free(p, c->codeword_lengths);
4115 setup_free(p, c->multiplicands);
4116 setup_free(p, c->codewords);
4117 setup_free(p, c->sorted_codewords);
4118 // c->sorted_values[-1] is the first entry in the array
4119 setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
4120 }
4121 setup_free(p, p->codebooks);
4122 }
4123 setup_free(p, p->floor_config);
4124 setup_free(p, p->residue_config);
4125 for (i=0; i < p->mapping_count; ++i)
4126 setup_free(p, p->mapping[i].chan);
4127 setup_free(p, p->mapping);
4128 for (i=0; i < p->channels; ++i) {
4129 setup_free(p, p->channel_buffers[i]);
4130 setup_free(p, p->previous_window[i]);
4131 #ifdef STB_VORBIS_NO_DEFER_FLOOR
4132 setup_free(p, p->floor_buffers[i]);
4133 #endif
4134 setup_free(p, p->finalY[i]);
4135 }
4136 for (i=0; i < 2; ++i) {
4137 setup_free(p, p->A[i]);
4138 setup_free(p, p->B[i]);
4139 setup_free(p, p->C[i]);
4140 setup_free(p, p->window[i]);
4141 }
4142 #ifndef STB_VORBIS_NO_STDIO
4143 if (p->close_on_free) fclose(p->f);
4144 #endif
4145 }
4146
4147 void stb_vorbis_close(stb_vorbis *p)
4148 {
4149 if (p == NULL) return;
4150 vorbis_deinit(p);
4151 setup_free(p,p);
4152 }
4153
4154 static void vorbis_init(stb_vorbis *p, stb_vorbis_alloc *z)
4155 {
4156 memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
4157 if (z) {
4158 p->alloc = *z;
4159 p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3;
4160 p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
4161 }
4162 p->eof = 0;
4163 p->error = VORBIS__no_error;
4164 p->stream = NULL;
4165 p->codebooks = NULL;
4166 p->page_crc_tests = -1;
4167 #ifndef STB_VORBIS_NO_STDIO
4168 p->close_on_free = FALSE;
4169 p->f = NULL;
4170 #endif
4171 }
4172
4173 int stb_vorbis_get_sample_offset(stb_vorbis *f)
4174 {
4175 if (f->current_loc_valid)
4176 return f->current_loc;
4177 else
4178 return -1;
4179 }
4180
4181 stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
4182 {
4183 stb_vorbis_info d;
4184 d.channels = f->channels;
4185 d.sample_rate = f->sample_rate;
4186 d.setup_memory_required = f->setup_memory_required;
4187 d.setup_temp_memory_required = f->setup_temp_memory_required;
4188 d.temp_memory_required = f->temp_memory_required;
4189 d.max_frame_size = f->blocksize_1 >> 1;
4190 return d;
4191 }
4192
4193 int stb_vorbis_get_error(stb_vorbis *f)
4194 {
4195 int e = f->error;
4196 f->error = VORBIS__no_error;
4197 return e;
4198 }
4199
4200 static stb_vorbis * vorbis_alloc(stb_vorbis *f)
4201 {
4202 stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
4203 return p;
4204 }
4205
4206 #ifndef STB_VORBIS_NO_PUSHDATA_API
4207
4208 void stb_vorbis_flush_pushdata(stb_vorbis *f)
4209 {
4210 f->previous_length = 0;
4211 f->page_crc_tests = 0;
4212 f->discard_samples_deferred = 0;
4213 f->current_loc_valid = FALSE;
4214 f->first_decode = FALSE;
4215 f->samples_output = 0;
4216 f->channel_buffer_start = 0;
4217 f->channel_buffer_end = 0;
4218 }
4219
4220 static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
4221 {
4222 int i,n;
4223 for (i=0; i < f->page_crc_tests; ++i)
4224 f->scan[i].bytes_done = 0;
4225
4226 // if we have room for more scans, search for them first, because
4227 // they may cause us to stop early if their header is incomplete
4228 if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
4229 if (data_len < 4) return 0;
4230 data_len -= 3; // need to look for 4-byte sequence, so don't miss
4231 // one that straddles a boundary
4232 for (i=0; i < data_len; ++i) {
4233 if (data[i] == 0x4f) {
4234 if (0==memcmp(data+i, ogg_page_header, 4)) {
4235 int j,len;
4236 uint32 crc;
4237 // make sure we have the whole page header
4238 if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
4239 // only read up to this page start, so hopefully we'll
4240 // have the whole page header start next time
4241 data_len = i;
4242 break;
4243 }
4244 // ok, we have it all; compute the length of the page
4245 len = 27 + data[i+26];
4246 for (j=0; j < data[i+26]; ++j)
4247 len += data[i+27+j];
4248 // scan everything up to the embedded crc (which we must 0)
4249 crc = 0;
4250 for (j=0; j < 22; ++j)
4251 crc = crc32_update(crc, data[i+j]);
4252 // now process 4 0-bytes
4253 for ( ; j < 26; ++j)
4254 crc = crc32_update(crc, 0);
4255 // len is the total number of bytes we need to scan
4256 n = f->page_crc_tests++;
4257 f->scan[n].bytes_left = len-j;
4258 f->scan[n].crc_so_far = crc;
4259 f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
4260 // if the last frame on a page is continued to the next, then
4261 // we can't recover the sample_loc immediately
4262 if (data[i+27+data[i+26]-1] == 255)
4263 f->scan[n].sample_loc = ~0;
4264 else
4265 f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
4266 f->scan[n].bytes_done = i+j;
4267 if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
4268 break;
4269 // keep going if we still have room for more
4270 }
4271 }
4272 }
4273 }
4274
4275 for (i=0; i < f->page_crc_tests;) {
4276 uint32 crc;
4277 int j;
4278 int n = f->scan[i].bytes_done;
4279 int m = f->scan[i].bytes_left;
4280 if (m > data_len - n) m = data_len - n;
4281 // m is the bytes to scan in the current chunk
4282 crc = f->scan[i].crc_so_far;
4283 for (j=0; j < m; ++j)
4284 crc = crc32_update(crc, data[n+j]);
4285 f->scan[i].bytes_left -= m;
4286 f->scan[i].crc_so_far = crc;
4287 if (f->scan[i].bytes_left == 0) {
4288 // does it match?
4289 if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
4290 // Houston, we have page
4291 data_len = n+m; // consumption amount is wherever that scan ended
4292 f->page_crc_tests = -1; // drop out of page scan mode
4293 f->previous_length = 0; // decode-but-don't-output one frame
4294 f->next_seg = -1; // start a new page
4295 f->current_loc = f->scan[i].sample_loc; // set the current sample location
4296 // to the amount we'd have decoded had we decoded this page
4297 f->current_loc_valid = f->current_loc != ~0;
4298 return data_len;
4299 }
4300 // delete entry
4301 f->scan[i] = f->scan[--f->page_crc_tests];
4302 } else {
4303 ++i;
4304 }
4305 }
4306
4307 return data_len;
4308 }
4309
4310 // return value: number of bytes we used
4311 int stb_vorbis_decode_frame_pushdata(
4312 stb_vorbis *f, // the file we're decoding
4313 uint8 *data, int data_len, // the memory available for decoding
4314 int *channels, // place to write number of float * buffers
4315 float ***output, // place to write float ** array of float * buffers
4316 int *samples // place to write number of output samples
4317 )
4318 {
4319 int i;
4320 int len,right,left;
4321
4322 if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
4323
4324 if (f->page_crc_tests >= 0) {
4325 *samples = 0;
4326 return vorbis_search_for_page_pushdata(f, data, data_len);
4327 }
4328
4329 f->stream = data;
4330 f->stream_end = data + data_len;
4331 f->error = VORBIS__no_error;
4332
4333 // check that we have the entire packet in memory
4334 if (!is_whole_packet_present(f, FALSE)) {
4335 *samples = 0;
4336 return 0;
4337 }
4338
4339 if (!vorbis_decode_packet(f, &len, &left, &right)) {
4340 // save the actual error we encountered
4341 enum STBVorbisError error = f->error;
4342 if (error == VORBIS_bad_packet_type) {
4343 // flush and resynch
4344 f->error = VORBIS__no_error;
4345 while (get8_packet(f) != EOP)
4346 if (f->eof) break;
4347 *samples = 0;
4348 return f->stream - data;
4349 }
4350 if (error == VORBIS_continued_packet_flag_invalid) {
4351 if (f->previous_length == 0) {
4352 // we may be resynching, in which case it's ok to hit one
4353 // of these; just discard the packet
4354 f->error = VORBIS__no_error;
4355 while (get8_packet(f) != EOP)
4356 if (f->eof) break;
4357 *samples = 0;
4358 return f->stream - data;
4359 }
4360 }
4361 // if we get an error while parsing, what to do?
4362 // well, it DEFINITELY won't work to continue from where we are!
4363 stb_vorbis_flush_pushdata(f);
4364 // restore the error that actually made us bail
4365 f->error = error;
4366 *samples = 0;
4367 return 1;
4368 }
4369
4370 // success!
4371 len = vorbis_finish_frame(f, len, left, right);
4372 for (i=0; i < f->channels; ++i)
4373 f->outputs[i] = f->channel_buffers[i] + left;
4374
4375 if (channels) *channels = f->channels;
4376 *samples = len;
4377 *output = f->outputs;
4378 return f->stream - data;
4379 }
4380
4381 stb_vorbis *stb_vorbis_open_pushdata(
4382 unsigned char *data, int data_len, // the memory available for decoding
4383 int *data_used, // only defined if result is not NULL
4384 int *error, stb_vorbis_alloc *alloc)
4385 {
4386 stb_vorbis *f, p;
4387 vorbis_init(&p, alloc);
4388 p.stream = data;
4389 p.stream_end = data + data_len;
4390 p.push_mode = TRUE;
4391 if (!start_decoder(&p)) {
4392 if (p.eof)
4393 *error = VORBIS_need_more_data;
4394 else
4395 *error = p.error;
4396 return NULL;
4397 }
4398 f = vorbis_alloc(&p);
4399 if (f) {
4400 *f = p;
4401 *data_used = f->stream - data;
4402 *error = 0;
4403 return f;
4404 } else {
4405 vorbis_deinit(&p);
4406 return NULL;
4407 }
4408 }
4409 #endif // STB_VORBIS_NO_PUSHDATA_API
4410
4411 unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
4412 {
4413 #ifndef STB_VORBIS_NO_PUSHDATA_API
4414 if (f->push_mode) return 0;
4415 #endif
4416 if (USE_MEMORY(f)) return f->stream - f->stream_start;
4417 #ifndef STB_VORBIS_NO_STDIO
4418 return ftell(f->f) - f->f_start;
4419 #endif
4420 }
4421
4422 #ifndef STB_VORBIS_NO_PULLDATA_API
4423 //
4424 // DATA-PULLING API
4425 //
4426
4427 static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
4428 {
4429 for(;;) {
4430 int n;
4431 if (f->eof) return 0;
4432 n = get8(f);
4433 if (n == 0x4f) { // page header
4434 unsigned int retry_loc = stb_vorbis_get_file_offset(f);
4435 int i;
4436 // check if we're off the end of a file_section stream
4437 if (retry_loc - 25 > f->stream_len)
4438 return 0;
4439 // check the rest of the header
4440 for (i=1; i < 4; ++i)
4441 if (get8(f) != ogg_page_header[i])
4442 break;
4443 if (f->eof) return 0;
4444 if (i == 4) {
4445 uint8 header[27];
4446 uint32 i, crc, goal, len;
4447 for (i=0; i < 4; ++i)
4448 header[i] = ogg_page_header[i];
4449 for (; i < 27; ++i)
4450 header[i] = get8(f);
4451 if (f->eof) return 0;
4452 if (header[4] != 0) goto invalid;
4453 goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
4454 for (i=22; i < 26; ++i)
4455 header[i] = 0;
4456 crc = 0;
4457 for (i=0; i < 27; ++i)
4458 crc = crc32_update(crc, header[i]);
4459 len = 0;
4460 for (i=0; i < header[26]; ++i) {
4461 int s = get8(f);
4462 crc = crc32_update(crc, s);
4463 len += s;
4464 }
4465 if (len && f->eof) return 0;
4466 for (i=0; i < len; ++i)
4467 crc = crc32_update(crc, get8(f));
4468 // finished parsing probable page
4469 if (crc == goal) {
4470 // we could now check that it's either got the last
4471 // page flag set, OR it's followed by the capture
4472 // pattern, but I guess TECHNICALLY you could have
4473 // a file with garbage between each ogg page and recover
4474 // from it automatically? So even though that paranoia
4475 // might decrease the chance of an invalid decode by
4476 // another 2^32, not worth it since it would hose those
4477 // invalid-but-useful files?
4478 if (end)
4479 *end = stb_vorbis_get_file_offset(f);
4480 if (last)
4481 if (header[5] & 0x04)
4482 *last = 1;
4483 else
4484 *last = 0;
4485 set_file_offset(f, retry_loc-1);
4486 return 1;
4487 }
4488 }
4489 invalid:
4490 // not a valid page, so rewind and look for next one
4491 set_file_offset(f, retry_loc);
4492 }
4493 }
4494 }
4495
4496 // seek is implemented with 'interpolation search'--this is like
4497 // binary search, but we use the data values to estimate the likely
4498 // location of the data item (plus a bit of a bias so when the
4499 // estimation is wrong we don't waste overly much time)
4500
4501 #define SAMPLE_unknown 0xffffffff
4502
4503
4504 // ogg vorbis, in its insane infinite wisdom, only provides
4505 // information about the sample at the END of the page.
4506 // therefore we COULD have the data we need in the current
4507 // page, and not know it. we could just use the end location
4508 // as our only knowledge for bounds, seek back, and eventually
4509 // the binary search finds it. or we can try to be smart and
4510 // not waste time trying to locate more pages. we try to be
4511 // smart, since this data is already in memory anyway, so
4512 // doing needless I/O would be crazy!
4513 static int vorbis_analyze_page(stb_vorbis *f, ProbedPage *z)
4514 {
4515 uint8 header[27], lacing[255];
4516 uint8 packet_type[255];
4517 int num_packet, packet_start, previous =0;
4518 int i,len;
4519 uint32 samples;
4520
4521 // record where the page starts
4522 z->page_start = stb_vorbis_get_file_offset(f);
4523
4524 // parse the header
4525 getn(f, header, 27);
4526 assert(header[0] == 'O' && header[1] == 'g' && header[2] == 'g' && header[3] == 'S');
4527 getn(f, lacing, header[26]);
4528
4529 // determine the length of the payload
4530 len = 0;
4531 for (i=0; i < header[26]; ++i)
4532 len += lacing[i];
4533
4534 // this implies where the page ends
4535 z->page_end = z->page_start + 27 + header[26] + len;
4536
4537 // read the last-decoded sample out of the data
4538 z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 16);
4539
4540 if (header[5] & 4) {
4541 // if this is the last page, it's not possible to work
4542 // backwards to figure out the first sample! whoops! fuck.
4543 z->first_decoded_sample = SAMPLE_unknown;
4544 set_file_offset(f, z->page_start);
4545 return 1;
4546 }
4547
4548 // scan through the frames to determine the sample-count of each one...
4549 // our goal is the sample # of the first fully-decoded sample on the
4550 // page, which is the first decoded sample of the 2nd page
4551
4552 num_packet=0;
4553
4554 packet_start = ((header[5] & 1) == 0);
4555
4556 for (i=0; i < header[26]; ++i) {
4557 if (packet_start) {
4558 uint8 n,b,m;
4559 if (lacing[i] == 0) goto bail; // trying to read from zero-length packet
4560 n = get8(f);
4561 // if bottom bit is non-zero, we've got corruption
4562 if (n & 1) goto bail;
4563 n >>= 1;
4564 b = ilog(f->mode_count-1);
4565 m = n >> b;
4566 n &= (1 << b)-1;
4567 if (n >= f->mode_count) goto bail;
4568 if (num_packet == 0 && f->mode_config[n].blockflag)
4569 previous = (m & 1);
4570 packet_type[num_packet++] = f->mode_config[n].blockflag;
4571 skip(f, lacing[i]-1);
4572 } else
4573 skip(f, lacing[i]);
4574 packet_start = (lacing[i] < 255);
4575 }
4576
4577 // now that we know the sizes of all the pages, we can start determining
4578 // how much sample data there is.
4579
4580 samples = 0;
4581
4582 // for the last packet, we step by its whole length, because the definition
4583 // is that we encoded the end sample loc of the 'last packet completed',
4584 // where 'completed' refers to packets being split, and we are left to guess
4585 // what 'end sample loc' means. we assume it means ignoring the fact that
4586 // the last half of the data is useless without windowing against the next
4587 // packet... (so it's not REALLY complete in that sense)
4588 if (num_packet > 1)
4589 samples += f->blocksize[packet_type[num_packet-1]];
4590
4591 for (i=num_packet-2; i >= 1; --i) {
4592 // now, for this packet, how many samples do we have that
4593 // do not overlap the following packet?
4594 if (packet_type[i] == 1)
4595 if (packet_type[i+1] == 1)
4596 samples += f->blocksize_1 >> 1;
4597 else
4598 samples += ((f->blocksize_1 - f->blocksize_0) >> 2) + (f->blocksize_0 >> 1);
4599 else
4600 samples += f->blocksize_0 >> 1;
4601 }
4602 // now, at this point, we've rewound to the very beginning of the
4603 // _second_ packet. if we entirely discard the first packet after
4604 // a seek, this will be exactly the right sample number. HOWEVER!
4605 // we can't as easily compute this number for the LAST page. The
4606 // only way to get the sample offset of the LAST page is to use
4607 // the end loc from the previous page. But what that returns us
4608 // is _exactly_ the place where we get our first non-overlapped
4609 // sample. (I think. Stupid spec for being ambiguous.) So for
4610 // consistency it's better to do that here, too. However, that
4611 // will then require us to NOT discard all of the first frame we
4612 // decode, in some cases, which means an even weirder frame size
4613 // and extra code. what a fucking pain.
4614
4615 // we're going to discard the first packet if we
4616 // start the seek here, so we don't care about it. (we could actually
4617 // do better; if the first packet is long, and the previous packet
4618 // is short, there's actually data in the first half of the first
4619 // packet that doesn't need discarding... but not worth paying the
4620 // effort of tracking that of that here and in the seeking logic)
4621 // except crap, if we infer it from the _previous_ packet's end
4622 // location, we DO need to use that definition... and we HAVE to
4623 // infer the start loc of the LAST packet from the previous packet's
4624 // end location. fuck you, ogg vorbis.
4625
4626 z->first_decoded_sample = z->last_decoded_sample - samples;
4627
4628 // restore file state to where we were
4629 set_file_offset(f, z->page_start);
4630 return 1;
4631
4632 // restore file state to where we were
4633 bail:
4634 set_file_offset(f, z->page_start);
4635 return 0;
4636 }
4637
4638 static int vorbis_seek_frame_from_page(stb_vorbis *f, uint32 page_start, uint32 first_sample, uint32 target_sample, int fine)
4639 {
4640 int left_start, left_end, right_start, right_end, mode,i;
4641 int frame=0;
4642 uint32 frame_start;
4643 int frames_to_skip, data_to_skip;
4644
4645 // first_sample is the sample # of the first sample that doesn't
4646 // overlap the previous page... note that this requires us to
4647 // _partially_ discard the first packet! bleh.
4648 set_file_offset(f, page_start);
4649
4650 f->next_seg = -1; // force page resync
4651
4652 frame_start = first_sample;
4653 // frame start is where the previous packet's last decoded sample
4654 // was, which corresponds to left_end... EXCEPT if the previous
4655 // packet was long and this packet is short? Probably a bug here.
4656
4657
4658 // now, we can start decoding frames... we'll only FAKE decode them,
4659 // until we find the frame that contains our sample; then we'll rewind,
4660 // and try again
4661 for (;;) {
4662 int start;
4663
4664 if (!vorbis_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
4665 return error(f, VORBIS_seek_failed);
4666
4667 if (frame == 0)
4668 start = left_end;
4669 else
4670 start = left_start;
4671
4672 // the window starts at left_start; the last valid sample we generate
4673 // before the next frame's window start is right_start-1
4674 if (target_sample < frame_start + right_start-start)
4675 break;
4676
4677 flush_packet(f);
4678 if (f->eof)
4679 return error(f, VORBIS_seek_failed);
4680
4681 frame_start += right_start - start;
4682
4683 ++frame;
4684 }
4685
4686 // ok, at this point, the sample we want is contained in frame #'frame'
4687
4688 // to decode frame #'frame' normally, we have to decode the
4689 // previous frame first... but if it's the FIRST frame of the page
4690 // we can't. if it's the first frame, it means it falls in the part
4691 // of the first frame that doesn't overlap either of the other frames.
4692 // so, if we have to handle that case for the first frame, we might
4693 // as well handle it for all of them, so:
4694 if (target_sample > frame_start + (left_end - left_start)) {
4695 // so what we want to do is go ahead and just immediately decode
4696 // this frame, but then make it so the next get_frame_float() uses
4697 // this already-decoded data? or do we want to go ahead and rewind,
4698 // and leave a flag saying to skip the first N data? let's do that
4699 frames_to_skip = frame; // if this is frame #1, skip 1 frame (#0)
4700 data_to_skip = left_end - left_start;
4701 } else {
4702 // otherwise, we want to skip frames 0, 1, 2, ... frame-2
4703 // (which means frame-2+1 total frames) then decode frame-1,
4704 // then leave frame pending
4705 frames_to_skip = frame - 1;
4706 assert(frames_to_skip >= 0);
4707 data_to_skip = -1;
4708 }
4709
4710 set_file_offset(f, page_start);
4711 f->next_seg = - 1; // force page resync
4712
4713 for (i=0; i < frames_to_skip; ++i) {
4714 maybe_start_packet(f);
4715 flush_packet(f);
4716 }
4717
4718 if (data_to_skip >= 0) {
4719 int i,j,n = f->blocksize_0 >> 1;
4720 f->discard_samples_deferred = data_to_skip;
4721 for (i=0; i < f->channels; ++i)
4722 for (j=0; j < n; ++j)
4723 f->previous_window[i][j] = 0;
4724 f->previous_length = n;
4725 frame_start += data_to_skip;
4726 } else {
4727 f->previous_length = 0;
4728 vorbis_pump_first_frame(f);
4729 }
4730
4731 // at this point, the NEXT decoded frame will generate the desired sample
4732 if (fine) {
4733 // so if we're doing sample accurate streaming, we want to go ahead and decode it!
4734 if (target_sample != frame_start) {
4735 int n;
4736 stb_vorbis_get_frame_float(f, &n, NULL);
4737 assert(target_sample > frame_start);
4738 assert(f->channel_buffer_start + (int) (target_sample-frame_start) < f->channel_buffer_end);
4739 f->channel_buffer_start += (target_sample - frame_start);
4740 }
4741 }
4742
4743 return 0;
4744 }
4745
4746 static int vorbis_seek_base(stb_vorbis *f, unsigned int sample_number, int fine)
4747 {
4748 ProbedPage p[2],q;
4749 if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
4750
4751 // do we know the location of the last page?
4752 if (f->p_last.page_start == 0) {
4753 uint32 z = stb_vorbis_stream_length_in_samples(f);
4754 if (z == 0) return error(f, VORBIS_cant_find_last_page);
4755 }
4756
4757 p[0] = f->p_first;
4758 p[1] = f->p_last;
4759
4760 if (sample_number >= f->p_last.last_decoded_sample)
4761 sample_number = f->p_last.last_decoded_sample-1;
4762
4763 if (sample_number < f->p_first.last_decoded_sample) {
4764 vorbis_seek_frame_from_page(f, p[0].page_start, 0, sample_number, fine);
4765 return 0;
4766 } else {
4767 int attempts=0;
4768 while (p[0].page_end < p[1].page_start) {
4769 uint32 probe;
4770 uint32 start_offset, end_offset;
4771 uint32 start_sample, end_sample;
4772
4773 // copy these into local variables so we can tweak them
4774 // if any are unknown
4775 start_offset = p[0].page_end;
4776 end_offset = p[1].after_previous_page_start; // an address known to seek to page p[1]
4777 start_sample = p[0].last_decoded_sample;
4778 end_sample = p[1].last_decoded_sample;
4779
4780 // currently there is no such tweaking logic needed/possible?
4781 if (start_sample == SAMPLE_unknown || end_sample == SAMPLE_unknown)
4782 return error(f, VORBIS_seek_failed);
4783
4784 // now we want to lerp between these for the target samples...
4785
4786 // step 1: we need to bias towards the page start...
4787 if (start_offset + 4000 < end_offset)
4788 end_offset -= 4000;
4789
4790 // now compute an interpolated search loc
4791 probe = start_offset + (int) floor((float) (end_offset - start_offset) / (end_sample - start_sample) * (sample_number - start_sample));
4792
4793 // next we need to bias towards binary search...
4794 // code is a little wonky to allow for full 32-bit unsigned values
4795 if (attempts >= 4) {
4796 uint32 probe2 = start_offset + ((end_offset - start_offset) >> 1);
4797 if (attempts >= 8)
4798 probe = probe2;
4799 else if (probe < probe2)
4800 probe = probe + ((probe2 - probe) >> 1);
4801 else
4802 probe = probe2 + ((probe - probe2) >> 1);
4803 }
4804 ++attempts;
4805
4806 set_file_offset(f, probe);
4807 if (!vorbis_find_page(f, NULL, NULL)) return error(f, VORBIS_seek_failed);
4808 if (!vorbis_analyze_page(f, &q)) return error(f, VORBIS_seek_failed);
4809 q.after_previous_page_start = probe;
4810
4811 // it's possible we've just found the last page again
4812 if (q.page_start == p[1].page_start) {
4813 p[1] = q;
4814 continue;
4815 }
4816
4817 if (sample_number < q.last_decoded_sample)
4818 p[1] = q;
4819 else
4820 p[0] = q;
4821 }
4822
4823 if (p[0].last_decoded_sample <= sample_number && sample_number < p[1].last_decoded_sample) {
4824 vorbis_seek_frame_from_page(f, p[1].page_start, p[0].last_decoded_sample, sample_number, fine);
4825 return 0;
4826 }
4827 return error(f, VORBIS_seek_failed);
4828 }
4829 }
4830
4831 int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
4832 {
4833 return vorbis_seek_base(f, sample_number, FALSE);
4834 }
4835
4836 int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
4837 {
4838 return vorbis_seek_base(f, sample_number, TRUE);
4839 }
4840
4841 void stb_vorbis_seek_start(stb_vorbis *f)
4842 {
4843 if (IS_PUSH_MODE(f)) { error(f, VORBIS_invalid_api_mixing); return; }
4844 set_file_offset(f, f->first_audio_page_offset);
4845 f->previous_length = 0;
4846 f->first_decode = TRUE;
4847 f->next_seg = -1;
4848 vorbis_pump_first_frame(f);
4849 }
4850
4851 unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
4852 {
4853 unsigned int restore_offset, previous_safe;
4854 unsigned int end, last_page_loc;
4855
4856 if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
4857 if (!f->total_samples) {
4858 int last;
4859 uint32 lo,hi;
4860 char header[6];
4861
4862 // first, store the current decode position so we can restore it
4863 restore_offset = stb_vorbis_get_file_offset(f);
4864
4865 // now we want to seek back 64K from the end (the last page must
4866 // be at most a little less than 64K, but let's allow a little slop)
4867 if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
4868 previous_safe = f->stream_len - 65536;
4869 else
4870 previous_safe = f->first_audio_page_offset;
4871
4872 set_file_offset(f, previous_safe);
4873 // previous_safe is now our candidate 'earliest known place that seeking
4874 // to will lead to the final page'
4875
4876 if (!vorbis_find_page(f, &end, (int unsigned *)&last)) {
4877 // if we can't find a page, we're hosed!
4878 f->error = VORBIS_cant_find_last_page;
4879 f->total_samples = 0xffffffff;
4880 goto done;
4881 }
4882
4883 // check if there are more pages
4884 last_page_loc = stb_vorbis_get_file_offset(f);
4885
4886 // stop when the last_page flag is set, not when we reach eof;
4887 // this allows us to stop short of a 'file_section' end without
4888 // explicitly checking the length of the section
4889 while (!last) {
4890 set_file_offset(f, end);
4891 if (!vorbis_find_page(f, &end, (int unsigned *)&last)) {
4892 // the last page we found didn't have the 'last page' flag
4893 // set. whoops!
4894 break;
4895 }
4896 previous_safe = last_page_loc+1;
4897 last_page_loc = stb_vorbis_get_file_offset(f);
4898 }
4899
4900 set_file_offset(f, last_page_loc);
4901
4902 // parse the header
4903 getn(f, (unsigned char *)header, 6);
4904 // extract the absolute granule position
4905 lo = get32(f);
4906 hi = get32(f);
4907 if (lo == 0xffffffff && hi == 0xffffffff) {
4908 f->error = VORBIS_cant_find_last_page;
4909 f->total_samples = SAMPLE_unknown;
4910 goto done;
4911 }
4912 if (hi)
4913 lo = 0xfffffffe; // saturate
4914 f->total_samples = lo;
4915
4916 f->p_last.page_start = last_page_loc;
4917 f->p_last.page_end = end;
4918 f->p_last.last_decoded_sample = lo;
4919 f->p_last.first_decoded_sample = SAMPLE_unknown;
4920 f->p_last.after_previous_page_start = previous_safe;
4921
4922 done:
4923 set_file_offset(f, restore_offset);
4924 }
4925 return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
4926 }
4927
4928 float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
4929 {
4930 return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
4931 }
4932
4933
4934
4935 int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
4936 {
4937 int len, right,left,i;
4938 if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
4939
4940 if (!vorbis_decode_packet(f, &len, &left, &right)) {
4941 f->channel_buffer_start = f->channel_buffer_end = 0;
4942 return 0;
4943 }
4944
4945 len = vorbis_finish_frame(f, len, left, right);
4946 for (i=0; i < f->channels; ++i)
4947 f->outputs[i] = f->channel_buffers[i] + left;
4948
4949 f->channel_buffer_start = left;
4950 f->channel_buffer_end = left+len;
4951
4952 if (channels) *channels = f->channels;
4953 if (output) *output = f->outputs;
4954 return len;
4955 }
4956
4957 #ifndef STB_VORBIS_NO_STDIO
4958
4959 stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc, unsigned int length)
4960 {
4961 stb_vorbis *f, p;
4962 vorbis_init(&p, alloc);
4963 p.f = file;
4964 p.f_start = ftell(file);
4965 p.stream_len = length;
4966 p.close_on_free = close_on_free;
4967 if (start_decoder(&p)) {
4968 f = vorbis_alloc(&p);
4969 if (f) {
4970 *f = p;
4971 vorbis_pump_first_frame(f);
4972 return f;
4973 }
4974 }
4975 if (error) *error = p.error;
4976 vorbis_deinit(&p);
4977 return NULL;
4978 }
4979
4980 stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc)
4981 {
4982 unsigned int len, start;
4983 start = ftell(file);
4984 fseek(file, 0, SEEK_END);
4985 len = ftell(file) - start;
4986 fseek(file, start, SEEK_SET);
4987 return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
4988 }
4989
4990 stb_vorbis * stb_vorbis_open_filename(char *filename, int *error, stb_vorbis_alloc *alloc)
4991 {
4992 FILE *f = fopen(filename, "rb");
4993 if (f)
4994 return stb_vorbis_open_file(f, TRUE, error, alloc);
4995 if (error) *error = VORBIS_file_open_failure;
4996 return NULL;
4997 }
4998 #endif // STB_VORBIS_NO_STDIO
4999
5000 stb_vorbis * stb_vorbis_open_memory(unsigned char *data, int len, int *error, stb_vorbis_alloc *alloc)
5001 {
5002 stb_vorbis *f, p;
5003 if (data == NULL) return NULL;
5004 vorbis_init(&p, alloc);
5005 p.stream = data;
5006 p.stream_end = data + len;
5007 p.stream_start = p.stream;
5008 p.stream_len = len;
5009 p.push_mode = FALSE;
5010 if (start_decoder(&p)) {
5011 f = vorbis_alloc(&p);
5012 if (f) {
5013 *f = p;
5014 vorbis_pump_first_frame(f);
5015 return f;
5016 }
5017 }
5018 if (error) *error = p.error;
5019 vorbis_deinit(&p);
5020 return NULL;
5021 }
5022
5023 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
5024 #define PLAYBACK_MONO 1
5025 #define PLAYBACK_LEFT 2
5026 #define PLAYBACK_RIGHT 4
5027
5028 #define L (PLAYBACK_LEFT | PLAYBACK_MONO)
5029 #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
5030 #define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
5031
5032 static int8 channel_position[7][6] =
5033 {
5034 { 0 },
5035 { C },
5036 { L, R },
5037 { L, C, R },
5038 { L, R, L, R },
5039 { L, C, R, L, R },
5040 { L, C, R, L, R, C },
5041 };
5042
5043
5044 #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
5045 typedef union {
5046 float f;
5047 int i;
5048 } float_conv;
5049 typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
5050 #define FASTDEF(x) float_conv x
5051 // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
5052 #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
5053 #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
5054 #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
5055 #define check_endianness()
5056 #else
5057 #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
5058 #define check_endianness()
5059 #define FASTDEF(x)
5060 #endif
5061
5062 static void copy_samples(short *dest, float *src, int len)
5063 {
5064 int i;
5065 check_endianness();
5066 for (i=0; i < len; ++i) {
5067 FASTDEF(temp);
5068 int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
5069 if ((unsigned int) (v + 32768) > 65535)
5070 v = v < 0 ? -32768 : 32767;
5071 dest[i] = v;
5072 }
5073 }
5074
5075 static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
5076 {
5077 #define BUFFER_SIZE 32
5078 float buffer[BUFFER_SIZE];
5079 int i,j,o,n = BUFFER_SIZE;
5080 check_endianness();
5081 for (o = 0; o < len; o += BUFFER_SIZE) {
5082 memset(buffer, 0, sizeof(buffer));
5083 if (o + n > len) n = len - o;
5084 for (j=0; j < num_c; ++j) {
5085 if (channel_position[num_c][j] & mask) {
5086 for (i=0; i < n; ++i)
5087 buffer[i] += data[j][d_offset+o+i];
5088 }
5089 }
5090 for (i=0; i < n; ++i) {
5091 FASTDEF(temp);
5092 int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
5093 if ((unsigned int) (v + 32768) > 65535)
5094 v = v < 0 ? -32768 : 32767;
5095 output[o+i] = v;
5096 }
5097 }
5098 }
5099
5100 static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
5101 static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
5102 {
5103 #define BUFFER_SIZE 32
5104 float buffer[BUFFER_SIZE];
5105 int i,j,o,n = BUFFER_SIZE >> 1;
5106 // o is the offset in the source data
5107 check_endianness();
5108 for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
5109 // o2 is the offset in the output data
5110 int o2 = o << 1;
5111 memset(buffer, 0, sizeof(buffer));
5112 if (o + n > len) n = len - o;
5113 for (j=0; j < num_c; ++j) {
5114 int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
5115 if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
5116 for (i=0; i < n; ++i) {
5117 buffer[i*2+0] += data[j][d_offset+o+i];
5118 buffer[i*2+1] += data[j][d_offset+o+i];
5119 }
5120 } else if (m == PLAYBACK_LEFT) {
5121 for (i=0; i < n; ++i) {
5122 buffer[i*2+0] += data[j][d_offset+o+i];
5123 }
5124 } else if (m == PLAYBACK_RIGHT) {
5125 for (i=0; i < n; ++i) {
5126 buffer[i*2+1] += data[j][d_offset+o+i];
5127 }
5128 }
5129 }
5130 for (i=0; i < (n<<1); ++i) {
5131 FASTDEF(temp);
5132 int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
5133 if ((unsigned int) (v + 32768) > 65535)
5134 v = v < 0 ? -32768 : 32767;
5135 output[o2+i] = v;
5136 }
5137 }
5138 }
5139
5140 static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
5141 {
5142 int i;
5143 if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
5144 static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
5145 for (i=0; i < buf_c; ++i)
5146 compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
5147 } else {
5148 int limit = buf_c < data_c ? buf_c : data_c;
5149 for (i=0; i < limit; ++i)
5150 copy_samples(buffer[i]+b_offset, data[i], samples);
5151 for ( ; i < buf_c; ++i)
5152 memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
5153 }
5154 }
5155
5156 int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
5157 {
5158 float **output;
5159 int len = stb_vorbis_get_frame_float(f, NULL, &output);
5160 if (len > num_samples) len = num_samples;
5161 if (len)
5162 convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
5163 return len;
5164 }
5165
5166 static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
5167 {
5168 int i;
5169 check_endianness();
5170 if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
5171 assert(buf_c == 2);
5172 for (i=0; i < buf_c; ++i)
5173 compute_stereo_samples(buffer, data_c, data, d_offset, len);
5174 } else {
5175 int limit = buf_c < data_c ? buf_c : data_c;
5176 int j;
5177 for (j=0; j < len; ++j) {
5178 for (i=0; i < limit; ++i) {
5179 FASTDEF(temp);
5180 float f = data[i][d_offset+j];
5181 int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
5182 if ((unsigned int) (v + 32768) > 65535)
5183 v = v < 0 ? -32768 : 32767;
5184 *buffer++ = v;
5185 }
5186 for ( ; i < buf_c; ++i)
5187 *buffer++ = 0;
5188 }
5189 }
5190 }
5191
5192 int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
5193 {
5194 float **output;
5195 int len;
5196 if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
5197 len = stb_vorbis_get_frame_float(f, NULL, &output);
5198 if (len) {
5199 if (len*num_c > num_shorts) len = num_shorts / num_c;
5200 convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
5201 }
5202 return len;
5203 }
5204
5205 int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
5206 {
5207 float **outputs;
5208 int len = num_shorts / channels;
5209 int n=0;
5210 int z = f->channels;
5211 if (z > channels) z = channels;
5212 while (n < len) {
5213 int k = f->channel_buffer_end - f->channel_buffer_start;
5214 if (n+k >= len) k = len - n;
5215 if (k)
5216 convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
5217 buffer += k*channels;
5218 n += k;
5219 f->channel_buffer_start += k;
5220 if (n == len) break;
5221 if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
5222 }
5223 return n;
5224 }
5225
5226 int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
5227 {
5228 float **outputs;
5229 int n=0;
5230 int z = f->channels;
5231 if (z > channels) z = channels;
5232 while (n < len) {
5233 int k = f->channel_buffer_end - f->channel_buffer_start;
5234 if (n+k >= len) k = len - n;
5235 if (k)
5236 convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
5237 n += k;
5238 f->channel_buffer_start += k;
5239 if (n == len) break;
5240 if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
5241 }
5242 return n;
5243 }
5244
5245 #ifndef STB_VORBIS_NO_STDIO
5246 int stb_vorbis_decode_filename(char *filename, int *channels, short **output)
5247 {
5248 int data_len, offset, total, limit, error;
5249 short *data;
5250 stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
5251 if (v == NULL) return -1;
5252 limit = v->channels * 4096;
5253 *channels = v->channels;
5254 offset = data_len = 0;
5255 total = limit;
5256 data = (short *) malloc(total * sizeof(*data));
5257 if (data == NULL) {
5258 stb_vorbis_close(v);
5259 return -2;
5260 }
5261 for (;;) {
5262 int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
5263 if (n == 0) break;
5264 data_len += n;
5265 offset += n * v->channels;
5266 if (offset + limit > total) {
5267 short *data2;
5268 total *= 2;
5269 data2 = (short *) realloc(data, total * sizeof(*data));
5270 if (data2 == NULL) {
5271 free(data);
5272 stb_vorbis_close(v);
5273 return -2;
5274 }
5275 data = data2;
5276 }
5277 }
5278 *output = data;
5279 return data_len;
5280 }
5281 #endif // NO_STDIO
5282
5283 int stb_vorbis_decode_memory(uint8 *mem, int len, int *channels, short **output)
5284 {
5285 int data_len, offset, total, limit, error;
5286 short *data;
5287 stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
5288 if (v == NULL) return -1;
5289 limit = v->channels * 4096;
5290 *channels = v->channels;
5291 offset = data_len = 0;
5292 total = limit;
5293 data = (short *) malloc(total * sizeof(*data));
5294 if (data == NULL) {
5295 stb_vorbis_close(v);
5296 return -2;
5297 }
5298 for (;;) {
5299 int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
5300 if (n == 0) break;
5301 data_len += n;
5302 offset += n * v->channels;
5303 if (offset + limit > total) {
5304 short *data2;
5305 total *= 2;
5306 data2 = (short *) realloc(data, total * sizeof(*data));
5307 if (data2 == NULL) {
5308 free(data);
5309 stb_vorbis_close(v);
5310 return -2;
5311 }
5312 data = data2;
5313 }
5314 }
5315 *output = data;
5316 return data_len;
5317 }
5318 #endif
5319
5320 int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
5321 {
5322 float **outputs;
5323 int len = num_floats / channels;
5324 int n=0;
5325 int z = f->channels;
5326 if (z > channels) z = channels;
5327 while (n < len) {
5328 int i,j;
5329 int k = f->channel_buffer_end - f->channel_buffer_start;
5330 if (n+k >= len) k = len - n;
5331 for (j=0; j < k; ++j) {
5332 for (i=0; i < z; ++i)
5333 *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
5334 for ( ; i < channels; ++i)
5335 *buffer++ = 0;
5336 }
5337 n += k;
5338 f->channel_buffer_start += k;
5339 if (n == len) break;
5340 if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
5341 }
5342 return n;
5343 }
5344
5345 int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
5346 {
5347 float **outputs;
5348 int n=0;
5349 int z = f->channels;
5350 if (z > channels) z = channels;
5351 while (n < num_samples) {
5352 int i;
5353 int k = f->channel_buffer_end - f->channel_buffer_start;
5354 if (n+k >= num_samples) k = num_samples - n;
5355 if (k) {
5356 for (i=0; i < z; ++i)
5357 memcpy(buffer[i]+n, f->channel_buffers+f->channel_buffer_start, sizeof(float)*k);
5358 for ( ; i < channels; ++i)
5359 memset(buffer[i]+n, 0, sizeof(float) * k);
5360 }
5361 n += k;
5362 f->channel_buffer_start += k;
5363 if (n == num_samples) break;
5364 if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
5365 }
5366 return n;
5367 }
5368 #endif // STB_VORBIS_NO_PULLDATA_API
5369
5370 #endif // STB_VORBIS_HEADER_ONLY