1 // Ogg Vorbis audio decoder - v1.14 - public domain
2 // http://nothings.org/stb_vorbis/
4 // Original version written by Sean Barrett in 2007.
6 // Originally sponsored by RAD Game Tools. Seeking implementation
7 // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,
8 // Elias Software, Aras Pranckevicius, and Sean Barrett.
12 // See end of file for license information.
16 // - floor 0 not supported (used in old ogg vorbis files pre-2004)
17 // - lossless sample-truncation at beginning ignored
18 // - cannot concatenate multiple vorbis streams
19 // - sample positions are 32-bit, limiting seekable 192Khz
20 // files to around 6 hours (Ogg supports 64-bit)
22 // Feature contributors:
23 // Dougall Johnson (sample-exact seeking)
25 // Bugfix/warning contributors:
26 // Terje Mathisen Niklas Frykholm Andy Hill
27 // Casey Muratori John Bolton Gargaj
28 // Laurent Gomila Marc LeBlanc Ronny Chevalier
29 // Bernhard Wodo Evan Balster alxprd@github
30 // Tom Beaumont Ingo Leitgeb Nicolas Guillemot
31 // Phillip Bennefall Rohit Thiago Goulart
32 // manxorist@github saga musix github:infatum
33 // Timur Gagiev BareRose
36 // 1.14 - 2018-02-11 - delete bogus dealloca usage
37 // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)
38 // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
39 // 1.11 - 2017-07-23 - fix MinGW compilation
40 // 1.10 - 2017-03-03 - more robust seeking; fix negative stbv_ilog(); clear error in open_memory
41 // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version
42 // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame
43 // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const
44 // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
45 // some crash fixes when out of memory or with corrupt files
46 // fix some inappropriately signed shifts
47 // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant
48 // 1.04 - 2014-08-27 - fix missing const-correct case in API
49 // 1.03 - 2014-08-07 - warning fixes
50 // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows
51 // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct)
52 // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
53 // (API change) report sample rate for decode-full-file funcs
55 // See end of file for full version history.
58 //////////////////////////////////////////////////////////////////////////////
63 #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H
64 #define STB_VORBIS_INCLUDE_STB_VORBIS_H
66 #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
67 #define STB_VORBIS_NO_STDIO
70 #ifndef STB_VORBIS_NO_STDIO
74 // NOTE: Added to work with raylib on Android
75 #if defined(PLATFORM_ANDROID)
76 #include "utils.h" // Android fopen function map
83 #ifdef STB_VORBIS_STATIC
84 #define STBVDEF static
86 #define STBVDEF extern
89 /////////// THREAD SAFETY
91 // Individual stb_vorbis* handles are not thread-safe; you cannot decode from
92 // them from multiple threads at the same time. However, you can have multiple
93 // stb_vorbis* handles and decode from them independently in multiple thrads.
96 /////////// MEMORY ALLOCATION
98 // normally stb_vorbis uses malloc() to allocate memory at startup,
99 // and alloca() to allocate temporary memory during a frame on the
100 // stack. (Memory consumption will depend on the amount of setup
101 // data in the file and how you set the compile flags for speed
102 // vs. size. In my test files the maximal-size usage is ~150KB.)
104 // You can modify the wrapper functions in the source (stbv_setup_malloc,
105 // stbv_setup_temp_malloc, temp_malloc) to change this behavior, or you
106 // can use a simpler allocation model: you pass in a buffer from
107 // which stb_vorbis will allocate _all_ its memory (including the
108 // temp memory). "open" may fail with a VORBIS_outofmem if you
109 // do not pass in enough data; there is no way to determine how
110 // much you do need except to succeed (at which point you can
111 // query get_info to find the exact amount required. yes I know
114 // If you pass in a non-NULL buffer of the type below, allocation
115 // will occur from it as described above. Otherwise just pass NULL
116 // to use malloc()/alloca()
121 int alloc_buffer_length_in_bytes;
125 /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES
127 typedef struct stb_vorbis stb_vorbis;
131 unsigned int sample_rate;
134 unsigned int setup_memory_required;
135 unsigned int setup_temp_memory_required;
136 unsigned int temp_memory_required;
141 // get general information about the file
142 STBVDEF stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);
144 // get the last error detected (clears it, too)
145 STBVDEF int stb_vorbis_get_error(stb_vorbis *f);
147 // close an ogg vorbis file and free all memory in use
148 STBVDEF void stb_vorbis_close(stb_vorbis *f);
150 // this function returns the offset (in samples) from the beginning of the
151 // file that will be returned by the next decode, if it is known, or -1
152 // otherwise. after a flush_pushdata() call, this may take a while before
153 // it becomes valid again.
154 // NOT WORKING YET after a seek with PULLDATA API
155 STBVDEF int stb_vorbis_get_sample_offset(stb_vorbis *f);
157 // returns the current seek point within the file, or offset from the beginning
158 // of the memory buffer. In pushdata mode it returns 0.
159 STBVDEF unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);
161 /////////// PUSHDATA API
163 #ifndef STB_VORBIS_NO_PUSHDATA_API
165 // this API allows you to get blocks of data from any source and hand
166 // them to stb_vorbis. you have to buffer them; stb_vorbis will tell
167 // you how much it used, and you have to give it the rest next time;
168 // and stb_vorbis may not have enough data to work with and you will
169 // need to give it the same data again PLUS more. Note that the Vorbis
170 // specification does not bound the size of an individual frame.
172 STBVDEF stb_vorbis *stb_vorbis_open_pushdata(
173 const unsigned char * datablock, int datablock_length_in_bytes,
174 int *datablock_memory_consumed_in_bytes,
176 const stb_vorbis_alloc *alloc_buffer);
177 // create a vorbis decoder by passing in the initial data block containing
178 // the ogg&vorbis headers (you don't need to do parse them, just provide
179 // the first N bytes of the file--you're told if it's not enough, see below)
180 // on success, returns an stb_vorbis *, does not set error, returns the amount of
181 // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;
182 // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed
183 // if returns NULL and *error is VORBIS_need_more_data, then the input block was
184 // incomplete and you need to pass in a larger block from the start of the file
186 STBVDEF int stb_vorbis_decode_frame_pushdata(
188 const unsigned char *datablock, int datablock_length_in_bytes,
189 int *channels, // place to write number of float * buffers
190 float ***output, // place to write float ** array of float * buffers
191 int *samples // place to write number of output samples
193 // decode a frame of audio sample data if possible from the passed-in data block
195 // return value: number of bytes we used from datablock
198 // 0 bytes used, 0 samples output (need more data)
199 // N bytes used, 0 samples output (resynching the stream, keep going)
200 // N bytes used, M samples output (one frame of data)
201 // note that after opening a file, you will ALWAYS get one N-bytes,0-sample
202 // frame, because Vorbis always "discards" the first frame.
204 // Note that on resynch, stb_vorbis will rarely consume all of the buffer,
205 // instead only datablock_length_in_bytes-3 or less. This is because it wants
206 // to avoid missing parts of a page header if they cross a datablock boundary,
207 // without writing state-machiney code to record a partial detection.
209 // The number of channels returned are stored in *channels (which can be
210 // NULL--it is always the same as the number of channels reported by
211 // get_info). *output will contain an array of float* buffers, one per
212 // channel. In other words, (*output)[0][0] contains the first sample from
213 // the first channel, and (*output)[1][0] contains the first sample from
214 // the second channel.
216 STBVDEF void stb_vorbis_flush_pushdata(stb_vorbis *f);
217 // inform stb_vorbis that your next datablock will not be contiguous with
218 // previous ones (e.g. you've seeked in the data); future attempts to decode
219 // frames will cause stb_vorbis to resynchronize (as noted above), and
220 // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it
221 // will begin decoding the _next_ frame.
223 // if you want to seek using pushdata, you need to seek in your file, then
224 // call stb_vorbis_flush_pushdata(), then start calling decoding, then once
225 // decoding is returning you data, call stb_vorbis_get_sample_offset, and
226 // if you don't like the result, seek your file again and repeat.
230 ////////// PULLING INPUT API
232 #ifndef STB_VORBIS_NO_PULLDATA_API
233 // This API assumes stb_vorbis is allowed to pull data from a source--
234 // either a block of memory containing the _entire_ vorbis stream, or a
235 // FILE * that you or it create, or possibly some other reading mechanism
236 // if you go modify the source to replace the FILE * case with some kind
237 // of callback to your code. (But if you don't support seeking, you may
238 // just want to go ahead and use pushdata.)
240 #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)
241 STBVDEF int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);
243 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
244 STBVDEF int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);
246 // decode an entire file and output the data interleaved into a malloc()ed
247 // buffer stored in *output. The return value is the number of samples
248 // decoded, or -1 if the file could not be opened or was not an ogg vorbis file.
249 // When you're done with it, just free() the pointer returned in *output.
251 STBVDEF stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,
252 int *error, const stb_vorbis_alloc *alloc_buffer);
253 // create an ogg vorbis decoder from an ogg vorbis stream in memory (note
254 // this must be the entire stream!). on failure, returns NULL and sets *error
256 #ifndef STB_VORBIS_NO_STDIO
257 STBVDEF stb_vorbis * stb_vorbis_open_filename(const char *filename,
258 int *error, const stb_vorbis_alloc *alloc_buffer);
259 // create an ogg vorbis decoder from a filename via fopen(). on failure,
260 // returns NULL and sets *error (possibly to VORBIS_file_open_failure).
262 STBVDEF stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,
263 int *error, const stb_vorbis_alloc *alloc_buffer);
264 // create an ogg vorbis decoder from an open FILE *, looking for a stream at
265 // the _current_ seek point (ftell). on failure, returns NULL and sets *error.
266 // note that stb_vorbis must "own" this stream; if you seek it in between
267 // calls to stb_vorbis, it will become confused. Morever, if you attempt to
268 // perform stb_vorbis_seek_*() operations on this file, it will assume it
269 // owns the _entire_ rest of the file after the start point. Use the next
270 // function, stb_vorbis_open_file_section(), to limit it.
272 STBVDEF stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,
273 int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);
274 // create an ogg vorbis decoder from an open FILE *, looking for a stream at
275 // the _current_ seek point (ftell); the stream will be of length 'len' bytes.
276 // on failure, returns NULL and sets *error. note that stb_vorbis must "own"
277 // this stream; if you seek it in between calls to stb_vorbis, it will become
281 STBVDEF int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);
282 STBVDEF int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);
283 // these functions seek in the Vorbis file to (approximately) 'sample_number'.
284 // after calling seek_frame(), the next call to get_frame_*() will include
285 // the specified sample. after calling stb_vorbis_seek(), the next call to
286 // stb_vorbis_get_samples_* will start with the specified sample. If you
287 // do not need to seek to EXACTLY the target sample when using get_samples_*,
288 // you can also use seek_frame().
290 STBVDEF int stb_vorbis_seek_start(stb_vorbis *f);
291 // this function is equivalent to stb_vorbis_seek(f,0)
293 STBVDEF unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);
294 STBVDEF float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);
295 // these functions return the total length of the vorbis stream
297 STBVDEF int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);
298 // decode the next frame and return the number of samples. the number of
299 // channels returned are stored in *channels (which can be NULL--it is always
300 // the same as the number of channels reported by get_info). *output will
301 // contain an array of float* buffers, one per channel. These outputs will
302 // be overwritten on the next call to stb_vorbis_get_frame_*.
304 // You generally should not intermix calls to stb_vorbis_get_frame_*()
305 // and stb_vorbis_get_samples_*(), since the latter calls the former.
307 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
308 STBVDEF int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);
309 STBVDEF int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);
311 // decode the next frame and return the number of *samples* per channel.
312 // Note that for interleaved data, you pass in the number of shorts (the
313 // size of your array), but the return value is the number of samples per
314 // channel, not the total number of samples.
316 // The data is coerced to the number of channels you request according to the
317 // channel coercion rules (see below). You must pass in the size of your
318 // buffer(s) so that stb_vorbis will not overwrite the end of the buffer.
319 // The maximum buffer size needed can be gotten from get_info(); however,
320 // the Vorbis I specification implies an absolute maximum of 4096 samples
323 // Channel coercion rules:
324 // Let M be the number of channels requested, and N the number of channels present,
325 // and Cn be the nth channel; let stereo L be the sum of all L and center channels,
326 // and stereo R be the sum of all R and center channels (channel assignment from the
329 // 1 k sum(Ck) for all k
330 // 2 * stereo L, stereo R
331 // k l k > l, the first l channels, then 0s
332 // k l k <= l, the first k channels
333 // Note that this is not _good_ surround etc. mixing at all! It's just so
334 // you get something useful.
336 STBVDEF int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);
337 STBVDEF int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);
338 // gets num_samples samples, not necessarily on a frame boundary--this requires
339 // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.
340 // Returns the number of samples stored per channel; it may be less than requested
341 // at the end of the file. If there are no more samples in the file, returns 0.
343 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
344 STBVDEF int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);
345 STBVDEF int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);
347 // gets num_samples samples, not necessarily on a frame boundary--this requires
348 // buffering so you have to supply the buffers. Applies the coercion rules above
349 // to produce 'channels' channels. Returns the number of samples stored per channel;
350 // it may be less than requested at the end of the file. If there are no more
351 // samples in the file, returns 0.
361 VORBIS_need_more_data=1, // not a real error
363 VORBIS_invalid_api_mixing, // can't mix API modes
364 VORBIS_outofmem, // not enough memory
365 VORBIS_feature_not_supported, // uses floor 0
366 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small
367 VORBIS_file_open_failure, // fopen() failed
368 VORBIS_seek_without_length, // can't seek in unknown-length file
370 VORBIS_unexpected_eof=10, // file is truncated?
371 VORBIS_seek_invalid, // seek past EOF
373 // decoding errors (corrupt/invalid stream) -- you probably
374 // don't care about the exact details of these
377 VORBIS_invalid_setup=20,
378 VORBIS_invalid_stream,
381 VORBIS_missing_capture_pattern=30,
382 VORBIS_invalid_stream_structure_version,
383 VORBIS_continued_packet_flag_invalid,
384 VORBIS_incorrect_stream_serial_number,
385 VORBIS_invalid_first_page,
386 VORBIS_bad_packet_type,
387 VORBIS_cant_find_last_page,
396 #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H
400 //////////////////////////////////////////////////////////////////////////////
402 #ifdef STB_VORBIS_IMPLEMENTATION
404 // global configuration settings (e.g. set these in the project/makefile),
405 // or just set them in this file at the top (although ideally the first few
406 // should be visible when the header file is compiled too, although it's not
409 // STB_VORBIS_NO_PUSHDATA_API
410 // does not compile the code for the various stb_vorbis_*_pushdata()
412 // #define STB_VORBIS_NO_PUSHDATA_API
414 // STB_VORBIS_NO_PULLDATA_API
415 // does not compile the code for the non-pushdata APIs
416 // #define STB_VORBIS_NO_PULLDATA_API
418 // STB_VORBIS_NO_STDIO
419 // does not compile the code for the APIs that use FILE *s internally
420 // or externally (implied by STB_VORBIS_NO_PULLDATA_API)
421 // #define STB_VORBIS_NO_STDIO
423 // STB_VORBIS_NO_INTEGER_CONVERSION
424 // does not compile the code for converting audio sample data from
425 // float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
426 // #define STB_VORBIS_NO_INTEGER_CONVERSION
428 // STB_VORBIS_NO_FAST_SCALED_FLOAT
429 // does not use a fast float-to-int trick to accelerate float-to-int on
430 // most platforms which requires endianness be defined correctly.
431 // #define STB_VORBIS_NO_FAST_SCALED_FLOAT
434 // STB_VORBIS_MAX_CHANNELS [number]
435 // globally define this to the maximum number of channels you need.
436 // The spec does not put a restriction on channels except that
437 // the count is stored in a byte, so 255 is the hard limit.
438 // Reducing this saves about 16 bytes per value, so using 16 saves
439 // (255-16)*16 or around 4KB. Plus anything other memory usage
440 // I forgot to account for. Can probably go as low as 8 (7.1 audio),
441 // 6 (5.1 audio), or 2 (stereo only).
442 #ifndef STB_VORBIS_MAX_CHANNELS
443 #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
446 // STB_VORBIS_PUSHDATA_CRC_COUNT [number]
447 // after a flush_pushdata(), stb_vorbis begins scanning for the
448 // next valid page, without backtracking. when it finds something
449 // that looks like a page, it streams through it and verifies its
450 // CRC32. Should that validation fail, it keeps scanning. But it's
451 // possible that _while_ streaming through to check the CRC32 of
452 // one candidate page, it sees another candidate page. This #define
453 // determines how many "overlapping" candidate pages it can search
454 // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
455 // garbage pages could be as big as 64KB, but probably average ~16KB.
456 // So don't hose ourselves by scanning an apparent 64KB page and
457 // missing a ton of real ones in the interim; so minimum of 2
458 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
459 #define STB_VORBIS_PUSHDATA_CRC_COUNT 4
462 // STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
463 // sets the log size of the huffman-acceleration table. Maximum
464 // supported value is 24. with larger numbers, more decodings are O(1),
465 // but the table size is larger so worse cache missing, so you'll have
466 // to probe (and try multiple ogg vorbis files) to find the sweet spot.
467 #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
468 #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
471 // STB_VORBIS_FAST_BINARY_LENGTH [number]
472 // sets the log size of the binary-search acceleration table. this
473 // is used in similar fashion to the fast-huffman size to set initial
474 // parameters for the binary search
476 // STB_VORBIS_FAST_HUFFMAN_INT
477 // The fast huffman tables are much more efficient if they can be
478 // stored as 16-bit results instead of 32-bit results. This restricts
479 // the codebooks to having only 65535 possible outcomes, though.
480 // (At least, accelerated by the huffman table.)
481 #ifndef STB_VORBIS_FAST_HUFFMAN_INT
482 #define STB_VORBIS_FAST_HUFFMAN_SHORT
485 // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
486 // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
487 // back on binary searching for the correct one. This requires storing
488 // extra tables with the huffman codes in sorted order. Defining this
489 // symbol trades off space for speed by forcing a linear search in the
490 // non-fast case, except for "sparse" codebooks.
491 // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
493 // STB_VORBIS_DIVIDES_IN_RESIDUE
494 // stb_vorbis precomputes the result of the scalar residue decoding
495 // that would otherwise require a divide per chunk. you can trade off
496 // space for time by defining this symbol.
497 // #define STB_VORBIS_DIVIDES_IN_RESIDUE
499 // STB_VORBIS_DIVIDES_IN_CODEBOOK
500 // vorbis VQ codebooks can be encoded two ways: with every case explicitly
501 // stored, or with all elements being chosen from a small range of values,
502 // and all values possible in all elements. By default, stb_vorbis expands
503 // this latter kind out to look like the former kind for ease of decoding,
504 // because otherwise an integer divide-per-vector-element is required to
505 // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
506 // trade off storage for speed.
507 //#define STB_VORBIS_DIVIDES_IN_CODEBOOK
509 #ifdef STB_VORBIS_CODEBOOK_SHORTS
510 #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
513 // STB_VORBIS_DIVIDE_TABLE
514 // this replaces small integer divides in the floor decode loop with
515 // table lookups. made less than 1% difference, so disabled by default.
517 // STB_VORBIS_NO_INLINE_DECODE
518 // disables the inlining of the scalar codebook fast-huffman decode.
519 // might save a little codespace; useful for debugging
520 // #define STB_VORBIS_NO_INLINE_DECODE
522 // STB_VORBIS_NO_DEFER_FLOOR
523 // Normally we only decode the floor without synthesizing the actual
524 // full curve. We can instead synthesize the curve immediately. This
525 // requires more memory and is very likely slower, so I don't think
526 // you'd ever want to do it except for debugging.
527 // #define STB_VORBIS_NO_DEFER_FLOOR
532 //////////////////////////////////////////////////////////////////////////////
534 #ifdef STB_VORBIS_NO_PULLDATA_API
535 #define STB_VORBIS_NO_INTEGER_CONVERSION
536 #define STB_VORBIS_NO_STDIO
539 #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
540 #define STB_VORBIS_NO_STDIO 1
543 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
544 #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
546 // only need endianness for fast-float-to-int, which we don't
549 #ifndef STB_VORBIS_BIG_ENDIAN
550 #define STB_VORBIS_ENDIAN 0
552 #define STB_VORBIS_ENDIAN 1
559 #ifndef STB_VORBIS_NO_STDIO
563 #ifndef STB_VORBIS_NO_CRT
569 // find definition of alloca if it's not in stdlib.h:
570 #if defined(_MSC_VER) || defined(__MINGW32__)
573 #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) || defined(__APPLE__)
576 #else // STB_VORBIS_NO_CRT
579 #define free(s) ((void) 0)
581 #endif // STB_VORBIS_NO_CRT
588 // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/
589 // "no that broke the build, reverted, who cares about C":
590 // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/
594 #define __forceinline
596 #define alloca(s) __builtin_alloca(s)
598 #elif !defined(_MSC_VER)
600 #define __forceinline inline
602 #define __forceinline
606 #if STB_VORBIS_MAX_CHANNELS > 256
607 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
610 #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
611 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
617 #define STBV_CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
619 #define STBV_CHECK(f) ((void) 0)
622 #define STBV_MAX_BLOCKSIZE_LOG 13 // from specification
623 #define STBV_MAX_BLOCKSIZE (1 << STBV_MAX_BLOCKSIZE_LOG)
626 typedef unsigned char stbv_uint8;
627 typedef signed char stbv_int8;
628 typedef unsigned short stbv_uint16;
629 typedef signed short stbv_int16;
630 typedef unsigned int stbv_uint32;
631 typedef signed int stbv_int32;
638 typedef float stbv_codetype;
642 // Some arrays below are tagged "//varies", which means it's actually
643 // a variable-sized piece of data, but rather than malloc I assume it's
644 // small enough it's better to just allocate it all together with the
647 // Most of the variables are specified with the smallest size I could pack
648 // them into. It might give better performance to make them all full-sized
649 // integers. It should be safe to freely rearrange the structures or change
650 // the sizes larger--nothing relies on silently truncating etc., nor the
651 // order of variables.
653 #define STBV_FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
654 #define STBV_FAST_HUFFMAN_TABLE_MASK (STBV_FAST_HUFFMAN_TABLE_SIZE - 1)
658 int dimensions, entries;
659 stbv_uint8 *codeword_lengths;
662 stbv_uint8 value_bits;
663 stbv_uint8 lookup_type;
664 stbv_uint8 sequence_p;
666 stbv_uint32 lookup_values;
667 stbv_codetype *multiplicands;
668 stbv_uint32 *codewords;
669 #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
670 stbv_int16 fast_huffman[STBV_FAST_HUFFMAN_TABLE_SIZE];
672 stbv_int32 fast_huffman[STBV_FAST_HUFFMAN_TABLE_SIZE];
674 stbv_uint32 *sorted_codewords;
683 stbv_uint16 bark_map_size;
684 stbv_uint8 amplitude_bits;
685 stbv_uint8 amplitude_offset;
686 stbv_uint8 number_of_books;
687 stbv_uint8 book_list[16]; // varies
692 stbv_uint8 partitions;
693 stbv_uint8 partition_class_list[32]; // varies
694 stbv_uint8 class_dimensions[16]; // varies
695 stbv_uint8 class_subclasses[16]; // varies
696 stbv_uint8 class_masterbooks[16]; // varies
697 stbv_int16 subclass_books[16][8]; // varies
698 stbv_uint16 Xlist[31*8+2]; // varies
699 stbv_uint8 sorted_order[31*8+2];
700 stbv_uint8 stbv_neighbors[31*8+2][2];
701 stbv_uint8 floor1_multiplier;
702 stbv_uint8 rangebits;
714 stbv_uint32 begin, end;
715 stbv_uint32 part_size;
716 stbv_uint8 classifications;
717 stbv_uint8 classbook;
718 stbv_uint8 **classdata;
719 stbv_int16 (*residue_books)[8];
724 stbv_uint8 magnitude;
727 } StbvMappingChannel;
731 stbv_uint16 coupling_steps;
732 StbvMappingChannel *chan;
734 stbv_uint8 submap_floor[15]; // varies
735 stbv_uint8 submap_residue[15]; // varies
740 stbv_uint8 blockflag;
742 stbv_uint16 windowtype;
743 stbv_uint16 transformtype;
748 stbv_uint32 goal_crc; // expected crc if match
749 int bytes_left; // bytes left in packet
750 stbv_uint32 crc_so_far; // running crc
751 int bytes_done; // bytes processed in _current_ chunk
752 stbv_uint32 sample_loc; // granule pos encoded in page
757 stbv_uint32 page_start, page_end;
758 stbv_uint32 last_decoded_sample;
763 // user-accessible info
764 unsigned int sample_rate;
767 unsigned int setup_memory_required;
768 unsigned int temp_memory_required;
769 unsigned int setup_temp_memory_required;
772 #ifndef STB_VORBIS_NO_STDIO
779 stbv_uint8 *stream_start;
780 stbv_uint8 *stream_end;
782 stbv_uint32 stream_len;
784 stbv_uint8 push_mode;
786 stbv_uint32 first_audio_page_offset;
788 StbvProbedPage p_first, p_last;
791 stb_vorbis_alloc alloc;
797 enum STBVorbisError error;
803 int blocksize_0, blocksize_1;
805 StbvCodebook *codebooks;
807 stbv_uint16 floor_types[64]; // varies
808 StbvFloor *floor_config;
810 stbv_uint16 residue_types[64]; // varies
811 StbvResidue *residue_config;
813 StbvMapping *mapping;
815 StbvMode mode_config[64]; // varies
817 stbv_uint32 total_samples;
820 float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
821 float *outputs [STB_VORBIS_MAX_CHANNELS];
823 float *previous_window[STB_VORBIS_MAX_CHANNELS];
826 #ifndef STB_VORBIS_NO_DEFER_FLOOR
827 stbv_int16 *finalY[STB_VORBIS_MAX_CHANNELS];
829 float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
832 stbv_uint32 current_loc; // sample location of next frame to decode
833 int current_loc_valid;
835 // per-blocksize precomputed data
838 float *A[2],*B[2],*C[2];
840 stbv_uint16 *stbv_bit_reverse[2];
842 // current page/packet/segment streaming info
843 stbv_uint32 serial; // stream serial number for verification
846 stbv_uint8 segments[255];
847 stbv_uint8 page_flag;
848 stbv_uint8 bytes_in_seg;
849 stbv_uint8 first_decode;
851 int last_seg; // flag that we're on the last segment
852 int last_seg_which; // what was the segment number of the last seg?
856 int end_seg_with_known_loc;
857 stbv_uint32 known_loc_for_packet;
858 int discard_samples_deferred;
859 stbv_uint32 samples_output;
861 // push mode scanning
862 int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
863 #ifndef STB_VORBIS_NO_PUSHDATA_API
864 StbvCRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
868 int channel_buffer_start;
869 int channel_buffer_end;
872 #if defined(STB_VORBIS_NO_PUSHDATA_API)
873 #define STBV_IS_PUSH_MODE(f) FALSE
874 #elif defined(STB_VORBIS_NO_PULLDATA_API)
875 #define STBV_IS_PUSH_MODE(f) TRUE
877 #define STBV_IS_PUSH_MODE(f) ((f)->push_mode)
880 typedef struct stb_vorbis stbv_vorb;
882 static int stbv_error(stbv_vorb *f, enum STBVorbisError e)
885 if (!f->eof && e != VORBIS_need_more_data) {
886 f->error=e; // breakpoint for debugging
892 // these functions are used for allocating temporary memory
893 // while decoding. if you can afford the stack space, use
894 // alloca(); otherwise, provide a temp buffer and it will
895 // allocate out of those.
897 #define stbv_array_size_required(count,size) (count*(sizeof(void *)+(size)))
899 #define stbv_temp_alloc(f,size) (f->alloc.alloc_buffer ? stbv_setup_temp_malloc(f,size) : alloca(size))
900 #define stbv_temp_free(f,p) 0
901 #define stbv_temp_alloc_save(f) ((f)->temp_offset)
902 #define stbv_temp_alloc_restore(f,p) ((f)->temp_offset = (p))
904 #define stbv_temp_block_array(f,count,size) stbv_make_block_array(stbv_temp_alloc(f,stbv_array_size_required(count,size)), count, size)
906 // given a sufficiently large block of memory, make an array of pointers to subblocks of it
907 static void *stbv_make_block_array(void *mem, int count, int size)
910 void ** p = (void **) mem;
911 char *q = (char *) (p + count);
912 for (i=0; i < count; ++i) {
919 static void *stbv_setup_malloc(stbv_vorb *f, int sz)
922 f->setup_memory_required += sz;
923 if (f->alloc.alloc_buffer) {
924 void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
925 if (f->setup_offset + sz > f->temp_offset) return NULL;
926 f->setup_offset += sz;
929 return sz ? malloc(sz) : NULL;
932 static void stbv_setup_free(stbv_vorb *f, void *p)
934 if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
938 static void *stbv_setup_temp_malloc(stbv_vorb *f, int sz)
941 if (f->alloc.alloc_buffer) {
942 if (f->temp_offset - sz < f->setup_offset) return NULL;
943 f->temp_offset -= sz;
944 return (char *) f->alloc.alloc_buffer + f->temp_offset;
949 static void stbv_setup_temp_free(stbv_vorb *f, void *p, int sz)
951 if (f->alloc.alloc_buffer) {
952 f->temp_offset += (sz+3)&~3;
958 #define STBV_CRC32_POLY 0x04c11db7 // from spec
960 static stbv_uint32 stbv_crc_table[256];
961 static void stbv_crc32_init(void)
965 for(i=0; i < 256; i++) {
966 for (s=(stbv_uint32) i << 24, j=0; j < 8; ++j)
967 s = (s << 1) ^ (s >= (1U<<31) ? STBV_CRC32_POLY : 0);
968 stbv_crc_table[i] = s;
972 static __forceinline stbv_uint32 stbv_crc32_update(stbv_uint32 crc, stbv_uint8 byte)
974 return (crc << 8) ^ stbv_crc_table[byte ^ (crc >> 24)];
978 // used in setup, and for huffman that doesn't go fast path
979 static unsigned int stbv_bit_reverse(unsigned int n)
981 n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
982 n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
983 n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
984 n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
985 return (n >> 16) | (n << 16);
988 static float stbv_square(float x)
993 // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
994 // as required by the specification. fast(?) implementation from stb.h
995 // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
996 static int stbv_ilog(stbv_int32 n)
998 static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
1000 if (n < 0) return 0; // signed n returns 0
1002 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
1004 if (n < (1 << 4)) return 0 + log2_4[n ];
1005 else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
1006 else return 10 + log2_4[n >> 10];
1007 else if (n < (1 << 24))
1008 if (n < (1 << 19)) return 15 + log2_4[n >> 15];
1009 else return 20 + log2_4[n >> 20];
1010 else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
1011 else return 30 + log2_4[n >> 30];
1015 #define M_PI 3.14159265358979323846264f // from CRC
1018 // code length assigned to a value with no huffman encoding
1021 /////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
1023 // these functions are only called at setup, and only a few times
1026 static float stbv_float32_unpack(stbv_uint32 x)
1028 // from the specification
1029 stbv_uint32 mantissa = x & 0x1fffff;
1030 stbv_uint32 sign = x & 0x80000000;
1031 stbv_uint32 exp = (x & 0x7fe00000) >> 21;
1032 double res = sign ? -(double)mantissa : (double)mantissa;
1033 return (float) ldexp((float)res, exp-788);
1037 // zlib & jpeg huffman tables assume that the output symbols
1038 // can either be arbitrarily arranged, or have monotonically
1039 // increasing frequencies--they rely on the lengths being sorted;
1040 // this makes for a very simple generation algorithm.
1041 // vorbis allows a huffman table with non-sorted lengths. This
1042 // requires a more sophisticated construction, since symbols in
1043 // order do not map to huffman codes "in order".
1044 static void stbv_add_entry(StbvCodebook *c, stbv_uint32 huff_code, int symbol, int count, int len, stbv_uint32 *values)
1047 c->codewords [symbol] = huff_code;
1049 c->codewords [count] = huff_code;
1050 c->codeword_lengths[count] = len;
1051 values [count] = symbol;
1055 static int stbv_compute_codewords(StbvCodebook *c, stbv_uint8 *len, int n, stbv_uint32 *values)
1058 stbv_uint32 available[32];
1060 memset(available, 0, sizeof(available));
1061 // find the first entry
1062 for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
1063 if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
1065 stbv_add_entry(c, 0, k, m++, len[k], values);
1066 // add all available leaves
1067 for (i=1; i <= len[k]; ++i)
1068 available[i] = 1U << (32-i);
1069 // note that the above code treats the first case specially,
1070 // but it's really the same as the following code, so they
1071 // could probably be combined (except the initial code is 0,
1072 // and I use 0 in available[] to mean 'empty')
1073 for (i=k+1; i < n; ++i) {
1076 if (z == NO_CODE) continue;
1077 // find lowest available leaf (should always be earliest,
1078 // which is what the specification calls for)
1079 // note that this property, and the fact we can never have
1080 // more than one free leaf at a given level, isn't totally
1081 // trivial to prove, but it seems true and the assert never
1083 while (z > 0 && !available[z]) --z;
1084 if (z == 0) { return FALSE; }
1086 assert(z >= 0 && z < 32);
1088 stbv_add_entry(c, stbv_bit_reverse(res), i, m++, len[i], values);
1089 // propogate availability up the tree
1091 assert(len[i] >= 0 && len[i] < 32);
1092 for (y=len[i]; y > z; --y) {
1093 assert(available[y] == 0);
1094 available[y] = res + (1 << (32-y));
1101 // accelerated huffman table allows fast O(1) match of all symbols
1102 // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
1103 static void stbv_compute_accelerated_huffman(StbvCodebook *c)
1106 for (i=0; i < STBV_FAST_HUFFMAN_TABLE_SIZE; ++i)
1107 c->fast_huffman[i] = -1;
1109 len = c->sparse ? c->sorted_entries : c->entries;
1110 #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
1111 if (len > 32767) len = 32767; // largest possible value we can encode!
1113 for (i=0; i < len; ++i) {
1114 if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
1115 stbv_uint32 z = c->sparse ? stbv_bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
1116 // set table entries for all bit combinations in the higher bits
1117 while (z < STBV_FAST_HUFFMAN_TABLE_SIZE) {
1118 c->fast_huffman[z] = i;
1119 z += 1 << c->codeword_lengths[i];
1126 #define STBV_CDECL __cdecl
1131 static int STBV_CDECL stbv_uint32_compare(const void *p, const void *q)
1133 stbv_uint32 x = * (stbv_uint32 *) p;
1134 stbv_uint32 y = * (stbv_uint32 *) q;
1135 return x < y ? -1 : x > y;
1138 static int stbv_include_in_sort(StbvCodebook *c, stbv_uint8 len)
1140 if (c->sparse) { assert(len != NO_CODE); return TRUE; }
1141 if (len == NO_CODE) return FALSE;
1142 if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
1146 // if the fast table above doesn't work, we want to binary
1147 // search them... need to reverse the bits
1148 static void stbv_compute_sorted_huffman(StbvCodebook *c, stbv_uint8 *lengths, stbv_uint32 *values)
1151 // build a list of all the entries
1152 // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
1153 // this is kind of a frivolous optimization--I don't see any performance improvement,
1154 // but it's like 4 extra lines of code, so.
1157 for (i=0; i < c->entries; ++i)
1158 if (stbv_include_in_sort(c, lengths[i]))
1159 c->sorted_codewords[k++] = stbv_bit_reverse(c->codewords[i]);
1160 assert(k == c->sorted_entries);
1162 for (i=0; i < c->sorted_entries; ++i)
1163 c->sorted_codewords[i] = stbv_bit_reverse(c->codewords[i]);
1166 qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), stbv_uint32_compare);
1167 c->sorted_codewords[c->sorted_entries] = 0xffffffff;
1169 len = c->sparse ? c->sorted_entries : c->entries;
1170 // now we need to indicate how they correspond; we could either
1171 // #1: sort a different data structure that says who they correspond to
1172 // #2: for each sorted entry, search the original list to find who corresponds
1173 // #3: for each original entry, find the sorted entry
1174 // #1 requires extra storage, #2 is slow, #3 can use binary search!
1175 for (i=0; i < len; ++i) {
1176 int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
1177 if (stbv_include_in_sort(c,huff_len)) {
1178 stbv_uint32 code = stbv_bit_reverse(c->codewords[i]);
1179 int x=0, n=c->sorted_entries;
1181 // invariant: sc[x] <= code < sc[x+n]
1182 int m = x + (n >> 1);
1183 if (c->sorted_codewords[m] <= code) {
1190 assert(c->sorted_codewords[x] == code);
1192 c->sorted_values[x] = values[i];
1193 c->codeword_lengths[x] = huff_len;
1195 c->sorted_values[x] = i;
1201 // only run while parsing the header (3 times)
1202 static int stbv_vorbis_validate(stbv_uint8 *data)
1204 static stbv_uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
1205 return memcmp(data, vorbis, 6) == 0;
1208 // called from setup only, once per code book
1209 // (formula implied by specification)
1210 static int stbv_lookup1_values(int entries, int dim)
1212 int r = (int) floor(exp((float) log((float) entries) / dim));
1213 if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
1214 ++r; // floor() to avoid _ftol() when non-CRT
1215 assert(pow((float) r+1, dim) > entries);
1216 assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
1220 // called twice per file
1221 static void stbv_compute_twiddle_factors(int n, float *A, float *B, float *C)
1223 int n4 = n >> 2, n8 = n >> 3;
1226 for (k=k2=0; k < n4; ++k,k2+=2) {
1227 A[k2 ] = (float) cos(4*k*M_PI/n);
1228 A[k2+1] = (float) -sin(4*k*M_PI/n);
1229 B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
1230 B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
1232 for (k=k2=0; k < n8; ++k,k2+=2) {
1233 C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
1234 C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
1238 static void stbv_compute_window(int n, float *window)
1241 for (i=0; i < n2; ++i)
1242 window[i] = (float) sin(0.5 * M_PI * stbv_square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
1245 static void stbv_compute_bitreverse(int n, stbv_uint16 *rev)
1247 int ld = stbv_ilog(n) - 1; // stbv_ilog is off-by-one from normal definitions
1249 for (i=0; i < n8; ++i)
1250 rev[i] = (stbv_bit_reverse(i) >> (32-ld+3)) << 2;
1253 static int stbv_init_blocksize(stbv_vorb *f, int b, int n)
1255 int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
1256 f->A[b] = (float *) stbv_setup_malloc(f, sizeof(float) * n2);
1257 f->B[b] = (float *) stbv_setup_malloc(f, sizeof(float) * n2);
1258 f->C[b] = (float *) stbv_setup_malloc(f, sizeof(float) * n4);
1259 if (!f->A[b] || !f->B[b] || !f->C[b]) return stbv_error(f, VORBIS_outofmem);
1260 stbv_compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
1261 f->window[b] = (float *) stbv_setup_malloc(f, sizeof(float) * n2);
1262 if (!f->window[b]) return stbv_error(f, VORBIS_outofmem);
1263 stbv_compute_window(n, f->window[b]);
1264 f->stbv_bit_reverse[b] = (stbv_uint16 *) stbv_setup_malloc(f, sizeof(stbv_uint16) * n8);
1265 if (!f->stbv_bit_reverse[b]) return stbv_error(f, VORBIS_outofmem);
1266 stbv_compute_bitreverse(n, f->stbv_bit_reverse[b]);
1270 static void stbv_neighbors(stbv_uint16 *x, int n, int *plow, int *phigh)
1275 for (i=0; i < n; ++i) {
1276 if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
1277 if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
1281 // this has been repurposed so y is now the original index instead of y
1285 } stbv_floor_ordering;
1287 static int STBV_CDECL stbv_point_compare(const void *p, const void *q)
1289 stbv_floor_ordering *a = (stbv_floor_ordering *) p;
1290 stbv_floor_ordering *b = (stbv_floor_ordering *) q;
1291 return a->x < b->x ? -1 : a->x > b->x;
1295 /////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
1298 #if defined(STB_VORBIS_NO_STDIO)
1299 #define STBV_USE_MEMORY(z) TRUE
1301 #define STBV_USE_MEMORY(z) ((z)->stream)
1304 static stbv_uint8 stbv_get8(stbv_vorb *z)
1306 if (STBV_USE_MEMORY(z)) {
1307 if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
1308 return *z->stream++;
1311 #ifndef STB_VORBIS_NO_STDIO
1313 int c = fgetc(z->f);
1314 if (c == EOF) { z->eof = TRUE; return 0; }
1320 static stbv_uint32 stbv_get32(stbv_vorb *f)
1324 x += stbv_get8(f) << 8;
1325 x += stbv_get8(f) << 16;
1326 x += (stbv_uint32) stbv_get8(f) << 24;
1330 static int stbv_getn(stbv_vorb *z, stbv_uint8 *data, int n)
1332 if (STBV_USE_MEMORY(z)) {
1333 if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
1334 memcpy(data, z->stream, n);
1339 #ifndef STB_VORBIS_NO_STDIO
1340 if (fread(data, n, 1, z->f) == 1)
1349 static void stbv_skip(stbv_vorb *z, int n)
1351 if (STBV_USE_MEMORY(z)) {
1353 if (z->stream >= z->stream_end) z->eof = 1;
1356 #ifndef STB_VORBIS_NO_STDIO
1358 long x = ftell(z->f);
1359 fseek(z->f, x+n, SEEK_SET);
1364 static int stbv_set_file_offset(stb_vorbis *f, unsigned int loc)
1366 #ifndef STB_VORBIS_NO_PUSHDATA_API
1367 if (f->push_mode) return 0;
1370 if (STBV_USE_MEMORY(f)) {
1371 if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
1372 f->stream = f->stream_end;
1376 f->stream = f->stream_start + loc;
1380 #ifndef STB_VORBIS_NO_STDIO
1381 if (loc + f->f_start < loc || loc >= 0x80000000) {
1387 if (!fseek(f->f, loc, SEEK_SET))
1390 fseek(f->f, f->f_start, SEEK_END);
1396 static stbv_uint8 stbv_ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
1398 static int stbv_capture_pattern(stbv_vorb *f)
1400 if (0x4f != stbv_get8(f)) return FALSE;
1401 if (0x67 != stbv_get8(f)) return FALSE;
1402 if (0x67 != stbv_get8(f)) return FALSE;
1403 if (0x53 != stbv_get8(f)) return FALSE;
1407 #define STBV_PAGEFLAG_continued_packet 1
1408 #define STBV_PAGEFLAG_first_page 2
1409 #define STBV_PAGEFLAG_last_page 4
1411 static int stbv_start_page_no_capturepattern(stbv_vorb *f)
1413 stbv_uint32 loc0,loc1,n;
1414 // stream structure version
1415 if (0 != stbv_get8(f)) return stbv_error(f, VORBIS_invalid_stream_structure_version);
1417 f->page_flag = stbv_get8(f);
1418 // absolute granule position
1419 loc0 = stbv_get32(f);
1420 loc1 = stbv_get32(f);
1421 // @TODO: validate loc0,loc1 as valid positions?
1422 // stream serial number -- vorbis doesn't interleave, so discard
1424 //if (f->serial != stbv_get32(f)) return stbv_error(f, VORBIS_incorrect_stream_serial_number);
1425 // page sequence number
1431 f->segment_count = stbv_get8(f);
1432 if (!stbv_getn(f, f->segments, f->segment_count))
1433 return stbv_error(f, VORBIS_unexpected_eof);
1434 // assume we _don't_ know any the sample position of any segments
1435 f->end_seg_with_known_loc = -2;
1436 if (loc0 != ~0U || loc1 != ~0U) {
1438 // determine which packet is the last one that will complete
1439 for (i=f->segment_count-1; i >= 0; --i)
1440 if (f->segments[i] < 255)
1442 // 'i' is now the index of the _last_ segment of a packet that ends
1444 f->end_seg_with_known_loc = i;
1445 f->known_loc_for_packet = loc0;
1448 if (f->first_decode) {
1452 for (i=0; i < f->segment_count; ++i)
1453 len += f->segments[i];
1454 len += 27 + f->segment_count;
1455 p.page_start = f->first_audio_page_offset;
1456 p.page_end = p.page_start + len;
1457 p.last_decoded_sample = loc0;
1464 static int stbv_start_page(stbv_vorb *f)
1466 if (!stbv_capture_pattern(f)) return stbv_error(f, VORBIS_missing_capture_pattern);
1467 return stbv_start_page_no_capturepattern(f);
1470 static int stbv_start_packet(stbv_vorb *f)
1472 while (f->next_seg == -1) {
1473 if (!stbv_start_page(f)) return FALSE;
1474 if (f->page_flag & STBV_PAGEFLAG_continued_packet)
1475 return stbv_error(f, VORBIS_continued_packet_flag_invalid);
1477 f->last_seg = FALSE;
1479 f->packet_bytes = 0;
1480 f->bytes_in_seg = 0;
1481 // f->next_seg is now valid
1485 static int stbv_maybe_start_packet(stbv_vorb *f)
1487 if (f->next_seg == -1) {
1488 int x = stbv_get8(f);
1489 if (f->eof) return FALSE; // EOF at page boundary is not an error!
1490 if (0x4f != x ) return stbv_error(f, VORBIS_missing_capture_pattern);
1491 if (0x67 != stbv_get8(f)) return stbv_error(f, VORBIS_missing_capture_pattern);
1492 if (0x67 != stbv_get8(f)) return stbv_error(f, VORBIS_missing_capture_pattern);
1493 if (0x53 != stbv_get8(f)) return stbv_error(f, VORBIS_missing_capture_pattern);
1494 if (!stbv_start_page_no_capturepattern(f)) return FALSE;
1495 if (f->page_flag & STBV_PAGEFLAG_continued_packet) {
1496 // set up enough state that we can read this packet if we want,
1497 // e.g. during recovery
1498 f->last_seg = FALSE;
1499 f->bytes_in_seg = 0;
1500 return stbv_error(f, VORBIS_continued_packet_flag_invalid);
1503 return stbv_start_packet(f);
1506 static int stbv_next_segment(stbv_vorb *f)
1509 if (f->last_seg) return 0;
1510 if (f->next_seg == -1) {
1511 f->last_seg_which = f->segment_count-1; // in case stbv_start_page fails
1512 if (!stbv_start_page(f)) { f->last_seg = 1; return 0; }
1513 if (!(f->page_flag & STBV_PAGEFLAG_continued_packet)) return stbv_error(f, VORBIS_continued_packet_flag_invalid);
1515 len = f->segments[f->next_seg++];
1518 f->last_seg_which = f->next_seg-1;
1520 if (f->next_seg >= f->segment_count)
1522 assert(f->bytes_in_seg == 0);
1523 f->bytes_in_seg = len;
1527 #define STBV_EOP (-1)
1528 #define STBV_INVALID_BITS (-1)
1530 static int stbv_get8_packet_raw(stbv_vorb *f)
1532 if (!f->bytes_in_seg) { // CLANG!
1533 if (f->last_seg) return STBV_EOP;
1534 else if (!stbv_next_segment(f)) return STBV_EOP;
1536 assert(f->bytes_in_seg > 0);
1539 return stbv_get8(f);
1542 static int stbv_get8_packet(stbv_vorb *f)
1544 int x = stbv_get8_packet_raw(f);
1549 static void stbv_flush_packet(stbv_vorb *f)
1551 while (stbv_get8_packet_raw(f) != STBV_EOP);
1554 // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
1555 // as the huffman decoder?
1556 static stbv_uint32 stbv_get_bits(stbv_vorb *f, int n)
1560 if (f->valid_bits < 0) return 0;
1561 if (f->valid_bits < n) {
1563 // the accumulator technique below would not work correctly in this case
1564 z = stbv_get_bits(f, 24);
1565 z += stbv_get_bits(f, n-24) << 24;
1568 if (f->valid_bits == 0) f->acc = 0;
1569 while (f->valid_bits < n) {
1570 int z = stbv_get8_packet_raw(f);
1571 if (z == STBV_EOP) {
1572 f->valid_bits = STBV_INVALID_BITS;
1575 f->acc += z << f->valid_bits;
1579 if (f->valid_bits < 0) return 0;
1580 z = f->acc & ((1 << n)-1);
1586 // @OPTIMIZE: primary accumulator for huffman
1587 // expand the buffer to as many bits as possible without reading off end of packet
1588 // it might be nice to allow f->valid_bits and f->acc to be stored in registers,
1589 // e.g. cache them locally and decode locally
1590 static __forceinline void stbv_prep_huffman(stbv_vorb *f)
1592 if (f->valid_bits <= 24) {
1593 if (f->valid_bits == 0) f->acc = 0;
1596 if (f->last_seg && !f->bytes_in_seg) return;
1597 z = stbv_get8_packet_raw(f);
1598 if (z == STBV_EOP) return;
1599 f->acc += (unsigned) z << f->valid_bits;
1601 } while (f->valid_bits <= 24);
1607 STBV_VORBIS_packet_id = 1,
1608 STBV_VORBIS_packet_comment = 3,
1609 STBV_VORBIS_packet_setup = 5
1612 static int stbv_codebook_decode_scalar_raw(stbv_vorb *f, StbvCodebook *c)
1615 stbv_prep_huffman(f);
1617 if (c->codewords == NULL && c->sorted_codewords == NULL)
1620 // cases to use binary search: sorted_codewords && !c->codewords
1621 // sorted_codewords && c->entries > 8
1622 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
1624 stbv_uint32 code = stbv_bit_reverse(f->acc);
1625 int x=0, n=c->sorted_entries, len;
1628 // invariant: sc[x] <= code < sc[x+n]
1629 int m = x + (n >> 1);
1630 if (c->sorted_codewords[m] <= code) {
1637 // x is now the sorted index
1638 if (!c->sparse) x = c->sorted_values[x];
1639 // x is now sorted index if sparse, or symbol otherwise
1640 len = c->codeword_lengths[x];
1641 if (f->valid_bits >= len) {
1643 f->valid_bits -= len;
1651 // if small, linear search
1653 for (i=0; i < c->entries; ++i) {
1654 if (c->codeword_lengths[i] == NO_CODE) continue;
1655 if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
1656 if (f->valid_bits >= c->codeword_lengths[i]) {
1657 f->acc >>= c->codeword_lengths[i];
1658 f->valid_bits -= c->codeword_lengths[i];
1666 stbv_error(f, VORBIS_invalid_stream);
1671 #ifndef STB_VORBIS_NO_INLINE_DECODE
1673 #define STBV_DECODE_RAW(var, f,c) \
1674 if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
1675 stbv_prep_huffman(f); \
1676 var = f->acc & STBV_FAST_HUFFMAN_TABLE_MASK; \
1677 var = c->fast_huffman[var]; \
1679 int n = c->codeword_lengths[var]; \
1681 f->valid_bits -= n; \
1682 if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
1684 var = stbv_codebook_decode_scalar_raw(f,c); \
1689 static int stbv_codebook_decode_scalar(stbv_vorb *f, StbvCodebook *c)
1692 if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
1693 stbv_prep_huffman(f);
1694 // fast huffman table lookup
1695 i = f->acc & STBV_FAST_HUFFMAN_TABLE_MASK;
1696 i = c->fast_huffman[i];
1698 f->acc >>= c->codeword_lengths[i];
1699 f->valid_bits -= c->codeword_lengths[i];
1700 if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
1703 return stbv_codebook_decode_scalar_raw(f,c);
1706 #define STBV_DECODE_RAW(var,f,c) var = stbv_codebook_decode_scalar(f,c);
1710 #define STBV_DECODE(var,f,c) \
1711 STBV_DECODE_RAW(var,f,c) \
1712 if (c->sparse) var = c->sorted_values[var];
1714 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
1715 #define DECODE_VQ(var,f,c) STBV_DECODE_RAW(var,f,c)
1717 #define DECODE_VQ(var,f,c) STBV_DECODE(var,f,c)
1725 // STBV_CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
1726 // where we avoid one addition
1727 #define STBV_CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
1728 #define STBV_CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
1729 #define STBV_CODEBOOK_ELEMENT_BASE(c) (0)
1731 static int stbv_codebook_decode_start(stbv_vorb *f, StbvCodebook *c)
1735 // type 0 is only legal in a scalar context
1736 if (c->lookup_type == 0)
1737 stbv_error(f, VORBIS_invalid_stream);
1740 if (c->sparse) assert(z < c->sorted_entries);
1741 if (z < 0) { // check for STBV_EOP
1742 if (!f->bytes_in_seg)
1745 stbv_error(f, VORBIS_invalid_stream);
1751 static int stbv_codebook_decode(stbv_vorb *f, StbvCodebook *c, float *output, int len)
1753 int i,z = stbv_codebook_decode_start(f,c);
1754 if (z < 0) return FALSE;
1755 if (len > c->dimensions) len = c->dimensions;
1757 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
1758 if (c->lookup_type == 1) {
1759 float last = STBV_CODEBOOK_ELEMENT_BASE(c);
1761 for (i=0; i < len; ++i) {
1762 int off = (z / div) % c->lookup_values;
1763 float val = STBV_CODEBOOK_ELEMENT_FAST(c,off) + last;
1765 if (c->sequence_p) last = val + c->minimum_value;
1766 div *= c->lookup_values;
1773 if (c->sequence_p) {
1774 float last = STBV_CODEBOOK_ELEMENT_BASE(c);
1775 for (i=0; i < len; ++i) {
1776 float val = STBV_CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1778 last = val + c->minimum_value;
1781 float last = STBV_CODEBOOK_ELEMENT_BASE(c);
1782 for (i=0; i < len; ++i) {
1783 output[i] += STBV_CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1790 static int stbv_codebook_decode_step(stbv_vorb *f, StbvCodebook *c, float *output, int len, int step)
1792 int i,z = stbv_codebook_decode_start(f,c);
1793 float last = STBV_CODEBOOK_ELEMENT_BASE(c);
1794 if (z < 0) return FALSE;
1795 if (len > c->dimensions) len = c->dimensions;
1797 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
1798 if (c->lookup_type == 1) {
1800 for (i=0; i < len; ++i) {
1801 int off = (z / div) % c->lookup_values;
1802 float val = STBV_CODEBOOK_ELEMENT_FAST(c,off) + last;
1803 output[i*step] += val;
1804 if (c->sequence_p) last = val;
1805 div *= c->lookup_values;
1812 for (i=0; i < len; ++i) {
1813 float val = STBV_CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1814 output[i*step] += val;
1815 if (c->sequence_p) last = val;
1821 static int stbv_codebook_decode_deinterleave_repeat(stbv_vorb *f, StbvCodebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
1823 int c_inter = *c_inter_p;
1824 int p_inter = *p_inter_p;
1825 int i,z, effective = c->dimensions;
1827 // type 0 is only legal in a scalar context
1828 if (c->lookup_type == 0) return stbv_error(f, VORBIS_invalid_stream);
1830 while (total_decode > 0) {
1831 float last = STBV_CODEBOOK_ELEMENT_BASE(c);
1833 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
1834 assert(!c->sparse || z < c->sorted_entries);
1837 if (!f->bytes_in_seg)
1838 if (f->last_seg) return FALSE;
1839 return stbv_error(f, VORBIS_invalid_stream);
1842 // if this will take us off the end of the buffers, stop short!
1843 // we check by computing the length of the virtual interleaved
1844 // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
1845 // and the length we'll be using (effective)
1846 if (c_inter + p_inter*ch + effective > len * ch) {
1847 effective = len*ch - (p_inter*ch - c_inter);
1850 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
1851 if (c->lookup_type == 1) {
1853 for (i=0; i < effective; ++i) {
1854 int off = (z / div) % c->lookup_values;
1855 float val = STBV_CODEBOOK_ELEMENT_FAST(c,off) + last;
1856 if (outputs[c_inter])
1857 outputs[c_inter][p_inter] += val;
1858 if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1859 if (c->sequence_p) last = val;
1860 div *= c->lookup_values;
1866 if (c->sequence_p) {
1867 for (i=0; i < effective; ++i) {
1868 float val = STBV_CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1869 if (outputs[c_inter])
1870 outputs[c_inter][p_inter] += val;
1871 if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1875 for (i=0; i < effective; ++i) {
1876 float val = STBV_CODEBOOK_ELEMENT_FAST(c,z+i) + last;
1877 if (outputs[c_inter])
1878 outputs[c_inter][p_inter] += val;
1879 if (++c_inter == ch) { c_inter = 0; ++p_inter; }
1884 total_decode -= effective;
1886 *c_inter_p = c_inter;
1887 *p_inter_p = p_inter;
1891 static int stbv_predict_point(int x, int x0, int x1, int y0, int y1)
1895 // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
1896 int err = abs(dy) * (x - x0);
1897 int off = err / adx;
1898 return dy < 0 ? y0 - off : y0 + off;
1901 // the following table is block-copied from the specification
1902 static float stbv_inverse_db_table[256] =
1904 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
1905 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
1906 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
1907 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
1908 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
1909 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
1910 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
1911 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
1912 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
1913 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
1914 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
1915 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
1916 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
1917 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
1918 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
1919 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
1920 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
1921 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
1922 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
1923 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
1924 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
1925 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
1926 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
1927 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
1928 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
1929 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
1930 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
1931 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
1932 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
1933 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
1934 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
1935 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
1936 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
1937 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
1938 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
1939 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
1940 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
1941 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
1942 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
1943 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
1944 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
1945 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
1946 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
1947 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
1948 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
1949 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
1950 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
1951 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
1952 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
1953 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
1954 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
1955 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
1956 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
1957 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
1958 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
1959 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
1960 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
1961 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
1962 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
1963 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
1964 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
1965 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
1966 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
1967 0.82788260f, 0.88168307f, 0.9389798f, 1.0f
1971 // @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
1972 // note that you must produce bit-identical output to decode correctly;
1973 // this specific sequence of operations is specified in the spec (it's
1974 // drawing integer-quantized frequency-space lines that the encoder
1975 // expects to be exactly the same)
1976 // ... also, isn't the whole point of Bresenham's algorithm to NOT
1977 // have to divide in the setup? sigh.
1978 #ifndef STB_VORBIS_NO_DEFER_FLOOR
1979 #define STBV_LINE_OP(a,b) a *= b
1981 #define STBV_LINE_OP(a,b) a = b
1984 #ifdef STB_VORBIS_DIVIDE_TABLE
1985 #define STBV_DIVTAB_NUMER 32
1986 #define STBV_DIVTAB_DENOM 64
1987 stbv_int8 stbv_integer_divide_table[STBV_DIVTAB_NUMER][STBV_DIVTAB_DENOM]; // 2KB
1990 static __forceinline void stbv_draw_line(float *output, int x0, int y0, int x1, int y1, int n)
2000 #ifdef STB_VORBIS_DIVIDE_TABLE
2001 if (adx < STBV_DIVTAB_DENOM && ady < STBV_DIVTAB_NUMER) {
2003 base = -stbv_integer_divide_table[ady][adx];
2006 base = stbv_integer_divide_table[ady][adx];
2023 ady -= abs(base) * adx;
2026 STBV_LINE_OP(output[x], stbv_inverse_db_table[y]);
2027 for (++x; x < x1; ++x) {
2034 STBV_LINE_OP(output[x], stbv_inverse_db_table[y]);
2039 static int stbv_residue_decode(stbv_vorb *f, StbvCodebook *book, float *target, int offset, int n, int rtype)
2043 int step = n / book->dimensions;
2044 for (k=0; k < step; ++k)
2045 if (!stbv_codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
2048 for (k=0; k < n; ) {
2049 if (!stbv_codebook_decode(f, book, target+offset, n-k))
2051 k += book->dimensions;
2052 offset += book->dimensions;
2058 // n is 1/2 of the blocksize --
2059 // specification: "Correct per-vector decode length is [n]/2"
2060 static void stbv_decode_residue(stbv_vorb *f, float *residue_buffers[], int ch, int n, int rn, stbv_uint8 *do_not_decode)
2063 StbvResidue *r = f->residue_config + rn;
2064 int rtype = f->residue_types[rn];
2065 int c = r->classbook;
2066 int classwords = f->codebooks[c].dimensions;
2067 unsigned int actual_size = rtype == 2 ? n*2 : n;
2068 unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size);
2069 unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size);
2070 int n_read = limit_r_end - limit_r_begin;
2071 int part_read = n_read / r->part_size;
2072 int temp_alloc_point = stbv_temp_alloc_save(f);
2073 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2074 stbv_uint8 ***part_classdata = (stbv_uint8 ***) stbv_temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
2076 int **classifications = (int **) stbv_temp_block_array(f,f->channels, part_read * sizeof(**classifications));
2081 for (i=0; i < ch; ++i)
2082 if (!do_not_decode[i])
2083 memset(residue_buffers[i], 0, sizeof(float) * n);
2085 if (rtype == 2 && ch != 1) {
2086 for (j=0; j < ch; ++j)
2087 if (!do_not_decode[j])
2092 for (pass=0; pass < 8; ++pass) {
2093 int pcount = 0, class_set = 0;
2095 while (pcount < part_read) {
2096 int z = r->begin + pcount*r->part_size;
2097 int c_inter = (z & 1), p_inter = z>>1;
2099 StbvCodebook *c = f->codebooks+r->classbook;
2102 if (q == STBV_EOP) goto done;
2103 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2104 part_classdata[0][class_set] = r->classdata[q];
2106 for (i=classwords-1; i >= 0; --i) {
2107 classifications[0][i+pcount] = q % r->classifications;
2108 q /= r->classifications;
2112 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2113 int z = r->begin + pcount*r->part_size;
2114 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2115 int c = part_classdata[0][class_set][i];
2117 int c = classifications[0][pcount];
2119 int b = r->residue_books[c][pass];
2121 StbvCodebook *book = f->codebooks + b;
2122 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
2123 if (!stbv_codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
2127 if (!stbv_codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
2136 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2140 } else if (ch == 1) {
2141 while (pcount < part_read) {
2142 int z = r->begin + pcount*r->part_size;
2143 int c_inter = 0, p_inter = z;
2145 StbvCodebook *c = f->codebooks+r->classbook;
2148 if (q == STBV_EOP) goto done;
2149 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2150 part_classdata[0][class_set] = r->classdata[q];
2152 for (i=classwords-1; i >= 0; --i) {
2153 classifications[0][i+pcount] = q % r->classifications;
2154 q /= r->classifications;
2158 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2159 int z = r->begin + pcount*r->part_size;
2160 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2161 int c = part_classdata[0][class_set][i];
2163 int c = classifications[0][pcount];
2165 int b = r->residue_books[c][pass];
2167 StbvCodebook *book = f->codebooks + b;
2168 if (!stbv_codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
2176 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2181 while (pcount < part_read) {
2182 int z = r->begin + pcount*r->part_size;
2183 int c_inter = z % ch, p_inter = z/ch;
2185 StbvCodebook *c = f->codebooks+r->classbook;
2188 if (q == STBV_EOP) goto done;
2189 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2190 part_classdata[0][class_set] = r->classdata[q];
2192 for (i=classwords-1; i >= 0; --i) {
2193 classifications[0][i+pcount] = q % r->classifications;
2194 q /= r->classifications;
2198 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2199 int z = r->begin + pcount*r->part_size;
2200 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2201 int c = part_classdata[0][class_set][i];
2203 int c = classifications[0][pcount];
2205 int b = r->residue_books[c][pass];
2207 StbvCodebook *book = f->codebooks + b;
2208 if (!stbv_codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
2216 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2226 for (pass=0; pass < 8; ++pass) {
2227 int pcount = 0, class_set=0;
2228 while (pcount < part_read) {
2230 for (j=0; j < ch; ++j) {
2231 if (!do_not_decode[j]) {
2232 StbvCodebook *c = f->codebooks+r->classbook;
2234 STBV_DECODE(temp,f,c);
2235 if (temp == STBV_EOP) goto done;
2236 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2237 part_classdata[j][class_set] = r->classdata[temp];
2239 for (i=classwords-1; i >= 0; --i) {
2240 classifications[j][i+pcount] = temp % r->classifications;
2241 temp /= r->classifications;
2247 for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
2248 for (j=0; j < ch; ++j) {
2249 if (!do_not_decode[j]) {
2250 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2251 int c = part_classdata[j][class_set][i];
2253 int c = classifications[j][pcount];
2255 int b = r->residue_books[c][pass];
2257 float *target = residue_buffers[j];
2258 int offset = r->begin + pcount * r->part_size;
2259 int n = r->part_size;
2260 StbvCodebook *book = f->codebooks + b;
2261 if (!stbv_residue_decode(f, book, target, offset, n, rtype))
2267 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2274 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
2275 stbv_temp_free(f,part_classdata);
2277 stbv_temp_free(f,classifications);
2279 stbv_temp_alloc_restore(f,temp_alloc_point);
2284 // slow way for debugging
2285 void inverse_mdct_slow(float *buffer, int n)
2289 float *x = (float *) malloc(sizeof(*x) * n2);
2290 memcpy(x, buffer, sizeof(*x) * n2);
2291 for (i=0; i < n; ++i) {
2293 for (j=0; j < n2; ++j)
2294 // formula from paper:
2295 //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
2296 // formula from wikipedia
2297 //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
2298 // these are equivalent, except the formula from the paper inverts the multiplier!
2299 // however, what actually works is NO MULTIPLIER!?!
2300 //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
2301 acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
2307 // same as above, but just barely able to run in real time on modern machines
2308 void inverse_mdct_slow(float *buffer, int n, stbv_vorb *f, int blocktype)
2312 int n2 = n >> 1, nmask = (n << 2) -1;
2313 float *x = (float *) malloc(sizeof(*x) * n2);
2314 memcpy(x, buffer, sizeof(*x) * n2);
2315 for (i=0; i < 4*n; ++i)
2316 mcos[i] = (float) cos(M_PI / 2 * i / n);
2318 for (i=0; i < n; ++i) {
2320 for (j=0; j < n2; ++j)
2321 acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
2327 // transform to use a slow dct-iv; this is STILL basically trivial,
2328 // but only requires half as many ops
2329 void dct_iv_slow(float *buffer, int n)
2334 int n2 = n >> 1, nmask = (n << 3) - 1;
2335 memcpy(x, buffer, sizeof(*x) * n);
2336 for (i=0; i < 8*n; ++i)
2337 mcos[i] = (float) cos(M_PI / 4 * i / n);
2338 for (i=0; i < n; ++i) {
2340 for (j=0; j < n; ++j)
2341 acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
2346 void inverse_mdct_slow(float *buffer, int n, stbv_vorb *f, int blocktype)
2348 int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
2351 memcpy(temp, buffer, n2 * sizeof(float));
2352 dct_iv_slow(temp, n2); // returns -c'-d, a-b'
2354 for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
2355 for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
2356 for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
2360 #ifndef LIBVORBIS_MDCT
2361 #define LIBVORBIS_MDCT 0
2365 // directly call the vorbis MDCT using an interface documented
2366 // by Jeff Roberts... useful for performance comparison
2378 extern void mdct_init(mdct_lookup *lookup, int n);
2379 extern void mdct_clear(mdct_lookup *l);
2380 extern void mdct_backward(mdct_lookup *init, float *in, float *out);
2384 void stbv_inverse_mdct(float *buffer, int n, stbv_vorb *f, int blocktype)
2387 if (M1.n == n) M = &M1;
2388 else if (M2.n == n) M = &M2;
2389 else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
2391 if (M2.n) __asm int 3;
2396 mdct_backward(M, buffer, buffer);
2401 // the following were split out into separate functions while optimizing;
2402 // they could be pushed back up but eh. __forceinline showed no change;
2403 // they're probably already being inlined.
2404 static void stbv_imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
2406 float *ee0 = e + i_off;
2407 float *ee2 = ee0 + k_off;
2410 assert((n & 3) == 0);
2411 for (i=(n>>2); i > 0; --i) {
2412 float k00_20, k01_21;
2413 k00_20 = ee0[ 0] - ee2[ 0];
2414 k01_21 = ee0[-1] - ee2[-1];
2415 ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
2416 ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
2417 ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
2418 ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
2421 k00_20 = ee0[-2] - ee2[-2];
2422 k01_21 = ee0[-3] - ee2[-3];
2423 ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
2424 ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
2425 ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
2426 ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
2429 k00_20 = ee0[-4] - ee2[-4];
2430 k01_21 = ee0[-5] - ee2[-5];
2431 ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
2432 ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
2433 ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
2434 ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
2437 k00_20 = ee0[-6] - ee2[-6];
2438 k01_21 = ee0[-7] - ee2[-7];
2439 ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
2440 ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
2441 ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
2442 ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
2449 static void stbv_imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
2452 float k00_20, k01_21;
2455 float *e2 = e0 + k_off;
2457 for (i=lim >> 2; i > 0; --i) {
2458 k00_20 = e0[-0] - e2[-0];
2459 k01_21 = e0[-1] - e2[-1];
2460 e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
2461 e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
2462 e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
2463 e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
2467 k00_20 = e0[-2] - e2[-2];
2468 k01_21 = e0[-3] - e2[-3];
2469 e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
2470 e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
2471 e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
2472 e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
2476 k00_20 = e0[-4] - e2[-4];
2477 k01_21 = e0[-5] - e2[-5];
2478 e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
2479 e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
2480 e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
2481 e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
2485 k00_20 = e0[-6] - e2[-6];
2486 k01_21 = e0[-7] - e2[-7];
2487 e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
2488 e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
2489 e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
2490 e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
2499 static void stbv_imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
2504 float A2 = A[0+a_off];
2505 float A3 = A[0+a_off+1];
2506 float A4 = A[0+a_off*2+0];
2507 float A5 = A[0+a_off*2+1];
2508 float A6 = A[0+a_off*3+0];
2509 float A7 = A[0+a_off*3+1];
2513 float *ee0 = e +i_off;
2514 float *ee2 = ee0+k_off;
2516 for (i=n; i > 0; --i) {
2517 k00 = ee0[ 0] - ee2[ 0];
2518 k11 = ee0[-1] - ee2[-1];
2519 ee0[ 0] = ee0[ 0] + ee2[ 0];
2520 ee0[-1] = ee0[-1] + ee2[-1];
2521 ee2[ 0] = (k00) * A0 - (k11) * A1;
2522 ee2[-1] = (k11) * A0 + (k00) * A1;
2524 k00 = ee0[-2] - ee2[-2];
2525 k11 = ee0[-3] - ee2[-3];
2526 ee0[-2] = ee0[-2] + ee2[-2];
2527 ee0[-3] = ee0[-3] + ee2[-3];
2528 ee2[-2] = (k00) * A2 - (k11) * A3;
2529 ee2[-3] = (k11) * A2 + (k00) * A3;
2531 k00 = ee0[-4] - ee2[-4];
2532 k11 = ee0[-5] - ee2[-5];
2533 ee0[-4] = ee0[-4] + ee2[-4];
2534 ee0[-5] = ee0[-5] + ee2[-5];
2535 ee2[-4] = (k00) * A4 - (k11) * A5;
2536 ee2[-5] = (k11) * A4 + (k00) * A5;
2538 k00 = ee0[-6] - ee2[-6];
2539 k11 = ee0[-7] - ee2[-7];
2540 ee0[-6] = ee0[-6] + ee2[-6];
2541 ee0[-7] = ee0[-7] + ee2[-7];
2542 ee2[-6] = (k00) * A6 - (k11) * A7;
2543 ee2[-7] = (k11) * A6 + (k00) * A7;
2550 static __forceinline void stbv_iter_54(float *z)
2552 float k00,k11,k22,k33;
2555 k00 = z[ 0] - z[-4];
2558 k22 = z[-2] - z[-6];
2560 z[-0] = y0 + y2; // z0 + z4 + z2 + z6
2561 z[-2] = y0 - y2; // z0 + z4 - z2 - z6
2565 k33 = z[-3] - z[-7];
2567 z[-4] = k00 + k33; // z0 - z4 + z3 - z7
2568 z[-6] = k00 - k33; // z0 - z4 - z3 + z7
2572 k11 = z[-1] - z[-5];
2576 z[-1] = y1 + y3; // z1 + z5 + z3 + z7
2577 z[-3] = y1 - y3; // z1 + z5 - z3 - z7
2578 z[-5] = k11 - k22; // z1 - z5 + z2 - z6
2579 z[-7] = k11 + k22; // z1 - z5 - z2 + z6
2582 static void stbv_imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
2584 int a_off = base_n >> 3;
2585 float A2 = A[0+a_off];
2586 float *z = e + i_off;
2587 float *base = z - 16 * n;
2592 k00 = z[-0] - z[-8];
2593 k11 = z[-1] - z[-9];
2594 z[-0] = z[-0] + z[-8];
2595 z[-1] = z[-1] + z[-9];
2599 k00 = z[ -2] - z[-10];
2600 k11 = z[ -3] - z[-11];
2601 z[ -2] = z[ -2] + z[-10];
2602 z[ -3] = z[ -3] + z[-11];
2603 z[-10] = (k00+k11) * A2;
2604 z[-11] = (k11-k00) * A2;
2606 k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
2607 k11 = z[ -5] - z[-13];
2608 z[ -4] = z[ -4] + z[-12];
2609 z[ -5] = z[ -5] + z[-13];
2613 k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
2614 k11 = z[ -7] - z[-15];
2615 z[ -6] = z[ -6] + z[-14];
2616 z[ -7] = z[ -7] + z[-15];
2617 z[-14] = (k00+k11) * A2;
2618 z[-15] = (k00-k11) * A2;
2626 static void stbv_inverse_mdct(float *buffer, int n, stbv_vorb *f, int blocktype)
2628 int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
2630 // @OPTIMIZE: reduce register pressure by using fewer variables?
2631 int save_point = stbv_temp_alloc_save(f);
2632 float *buf2 = (float *) stbv_temp_alloc(f, n2 * sizeof(*buf2));
2633 float *u=NULL,*v=NULL;
2635 float *A = f->A[blocktype];
2637 // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
2638 // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
2640 // kernel from paper
2644 // copy and reflect spectral data
2647 // note that it turns out that the items added together during
2648 // this step are, in fact, being added to themselves (as reflected
2649 // by step 0). inexplicable inefficiency! this became obvious
2650 // once I combined the passes.
2652 // so there's a missing 'times 2' here (for adding X to itself).
2653 // this propogates through linearly to the end, where the numbers
2654 // are 1/2 too small, and need to be compensated for.
2657 float *d,*e, *AA, *e_stop;
2661 e_stop = &buffer[n2];
2662 while (e != e_stop) {
2663 d[1] = (e[0] * AA[0] - e[2]*AA[1]);
2664 d[0] = (e[0] * AA[1] + e[2]*AA[0]);
2672 d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
2673 d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
2680 // now we use symbolic names for these, so that we can
2681 // possibly swap their meaning as we change which operations
2687 // step 2 (paper output is w, now u)
2688 // this could be in place, but the data ends up in the wrong
2689 // place... _somebody_'s got to swap it, so this is nominated
2691 float *AA = &A[n2-8];
2692 float *d0,*d1, *e0, *e1;
2701 float v40_20, v41_21;
2703 v41_21 = e0[1] - e1[1];
2704 v40_20 = e0[0] - e1[0];
2705 d0[1] = e0[1] + e1[1];
2706 d0[0] = e0[0] + e1[0];
2707 d1[1] = v41_21*AA[4] - v40_20*AA[5];
2708 d1[0] = v40_20*AA[4] + v41_21*AA[5];
2710 v41_21 = e0[3] - e1[3];
2711 v40_20 = e0[2] - e1[2];
2712 d0[3] = e0[3] + e1[3];
2713 d0[2] = e0[2] + e1[2];
2714 d1[3] = v41_21*AA[0] - v40_20*AA[1];
2715 d1[2] = v40_20*AA[0] + v41_21*AA[1];
2727 ld = stbv_ilog(n) - 1; // stbv_ilog is off-by-one from normal definitions
2729 // optimized step 3:
2731 // the original step3 loop can be nested r inside s or s inside r;
2732 // it's written originally as s inside r, but this is dumb when r
2733 // iterates many times, and s few. So I have two copies of it and
2734 // switch between them halfway.
2736 // this is iteration 0 of step 3
2737 stbv_imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
2738 stbv_imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
2740 // this is iteration 1 of step 3
2741 stbv_imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
2742 stbv_imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
2743 stbv_imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
2744 stbv_imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
2747 for (; l < (ld-3)>>1; ++l) {
2748 int k0 = n >> (l+2), k0_2 = k0>>1;
2749 int lim = 1 << (l+1);
2751 for (i=0; i < lim; ++i)
2752 stbv_imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
2755 for (; l < ld-6; ++l) {
2756 int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
2757 int rlim = n >> (l+6), r;
2758 int lim = 1 << (l+1);
2762 for (r=rlim; r > 0; --r) {
2763 stbv_imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
2769 // iterations with count:
2770 // ld-6,-5,-4 all interleaved together
2771 // the big win comes from getting rid of needless flops
2772 // due to the constants on pass 5 & 4 being all 1 and 0;
2773 // combining them to be simultaneous to improve cache made little difference
2774 stbv_imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
2779 // cannot be in-place because of step 5
2781 stbv_uint16 *bitrev = f->stbv_bit_reverse[blocktype];
2782 // weirdly, I'd have thought reading sequentially and writing
2783 // erratically would have been better than vice-versa, but in
2784 // fact that's not what my testing showed. (That is, with
2785 // j = bitreverse(i), do you read i and write j, or read j and write i.)
2787 float *d0 = &v[n4-4];
2788 float *d1 = &v[n2-4];
2809 // (paper output is u, now v)
2812 // data must be in buf2
2815 // step 7 (paper output is v, now v)
2816 // this is now in place
2818 float *C = f->C[blocktype];
2825 float a02,a11,b0,b1,b2,b3;
2830 b0 = C[1]*a02 + C[0]*a11;
2831 b1 = C[1]*a11 - C[0]*a02;
2844 b0 = C[3]*a02 + C[2]*a11;
2845 b1 = C[3]*a11 - C[2]*a02;
2861 // data must be in buf2
2864 // step 8+decode (paper output is X, now buffer)
2865 // this generates pairs of data a la 8 and pushes them directly through
2866 // the decode kernel (pushing rather than pulling) to avoid having
2867 // to make another pass later
2869 // this cannot POSSIBLY be in place, so we refer to the buffers directly
2872 float *d0,*d1,*d2,*d3;
2874 float *B = f->B[blocktype] + n2 - 8;
2875 float *e = buf2 + n2 - 8;
2883 p3 = e[6]*B[7] - e[7]*B[6];
2884 p2 = -e[6]*B[6] - e[7]*B[7];
2891 p1 = e[4]*B[5] - e[5]*B[4];
2892 p0 = -e[4]*B[4] - e[5]*B[5];
2899 p3 = e[2]*B[3] - e[3]*B[2];
2900 p2 = -e[2]*B[2] - e[3]*B[3];
2907 p1 = e[0]*B[1] - e[1]*B[0];
2908 p0 = -e[0]*B[0] - e[1]*B[1];
2924 stbv_temp_free(f,buf2);
2925 stbv_temp_alloc_restore(f,save_point);
2929 // this is the original version of the above code, if you want to optimize it from scratch
2930 void inverse_mdct_naive(float *buffer, int n)
2933 float A[1 << 12], B[1 << 12], C[1 << 11];
2934 int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
2935 int n3_4 = n - n4, ld;
2936 // how can they claim this only uses N words?!
2937 // oh, because they're only used sparsely, whoops
2938 float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
2939 // set up twiddle factors
2941 for (k=k2=0; k < n4; ++k,k2+=2) {
2942 A[k2 ] = (float) cos(4*k*M_PI/n);
2943 A[k2+1] = (float) -sin(4*k*M_PI/n);
2944 B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
2945 B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
2947 for (k=k2=0; k < n8; ++k,k2+=2) {
2948 C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
2949 C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
2952 // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
2953 // Note there are bugs in that pseudocode, presumably due to them attempting
2954 // to rename the arrays nicely rather than representing the way their actual
2955 // implementation bounces buffers back and forth. As a result, even in the
2956 // "some formulars corrected" version, a direct implementation fails. These
2957 // are noted below as "paper bug".
2959 // copy and reflect spectral data
2960 for (k=0; k < n2; ++k) u[k] = buffer[k];
2961 for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
2962 // kernel from paper
2964 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
2965 v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
2966 v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
2969 for (k=k4=0; k < n8; k+=1, k4+=4) {
2970 w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
2971 w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
2972 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];
2973 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];
2976 ld = stbv_ilog(n) - 1; // stbv_ilog is off-by-one from normal definitions
2977 for (l=0; l < ld-3; ++l) {
2978 int k0 = n >> (l+2), k1 = 1 << (l+3);
2979 int rlim = n >> (l+4), r4, r;
2980 int s2lim = 1 << (l+2), s2;
2981 for (r=r4=0; r < rlim; r4+=4,++r) {
2982 for (s2=0; s2 < s2lim; s2+=2) {
2983 u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
2984 u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
2985 u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
2986 - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
2987 u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
2988 + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
2992 // paper bug: ping-ponging of u&w here is omitted
2993 memcpy(w, u, sizeof(u));
2998 for (i=0; i < n8; ++i) {
2999 int j = stbv_bit_reverse(i) >> (32-ld+3);
3002 // paper bug: original code probably swapped in place; if copying,
3003 // need to directly copy in this case
3010 int i8 = i << 3, j8 = j << 3;
3011 v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
3012 v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
3013 v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
3014 v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
3018 for (k=0; k < n2; ++k) {
3022 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
3024 u[n-2-k2] = w[k4+1];
3025 u[n3_4 - 1 - k2] = w[k4+2];
3026 u[n3_4 - 2 - k2] = w[k4+3];
3029 for (k=k2=0; k < n8; ++k, k2 += 2) {
3030 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;
3031 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;
3032 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;
3033 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;
3036 for (k=k2=0; k < n4; ++k,k2 += 2) {
3037 X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
3038 X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
3041 // decode kernel to output
3042 // determined the following value experimentally
3043 // (by first figuring out what made inverse_mdct_slow work); then matching that here
3044 // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
3045 s = 0.5; // theoretically would be n4
3047 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
3048 // so it needs to use the "old" B values to behave correctly, or else
3050 for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
3051 for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
3052 for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
3056 static float *stbv_get_window(stbv_vorb *f, int len)
3059 if (len == f->blocksize_0) return f->window[0];
3060 if (len == f->blocksize_1) return f->window[1];
3065 #ifndef STB_VORBIS_NO_DEFER_FLOOR
3066 typedef stbv_int16 STBV_YTYPE;
3068 typedef int STBV_YTYPE;
3070 static int stbv_do_floor(stbv_vorb *f, StbvMapping *map, int i, int n, float *target, STBV_YTYPE *finalY, stbv_uint8 *step2_flag)
3073 int s = map->chan[i].mux, floor;
3074 floor = map->submap_floor[s];
3075 if (f->floor_types[floor] == 0) {
3076 return stbv_error(f, VORBIS_invalid_stream);
3078 StbvFloor1 *g = &f->floor_config[floor].floor1;
3080 int lx = 0, ly = finalY[0] * g->floor1_multiplier;
3081 for (q=1; q < g->values; ++q) {
3082 j = g->sorted_order[q];
3083 #ifndef STB_VORBIS_NO_DEFER_FLOOR
3089 int hy = finalY[j] * g->floor1_multiplier;
3090 int hx = g->Xlist[j];
3092 stbv_draw_line(target, lx,ly, hx,hy, n2);
3098 // optimization of: stbv_draw_line(target, lx,ly, n,ly, n2);
3099 for (j=lx; j < n2; ++j)
3100 STBV_LINE_OP(target[j], stbv_inverse_db_table[ly]);
3107 // The meaning of "left" and "right"
3109 // For a given frame:
3110 // we compute samples from 0..n
3111 // window_center is n/2
3112 // we'll window and mix the samples from left_start to left_end with data from the previous frame
3113 // all of the samples from left_end to right_start can be output without mixing; however,
3114 // this interval is 0-length except when transitioning between short and long frames
3115 // all of the samples from right_start to right_end need to be mixed with the next frame,
3116 // which we don't have, so those get saved in a buffer
3117 // frame N's right_end-right_start, the number of samples to mix with the next frame,
3118 // has to be the same as frame N+1's left_end-left_start (which they are by
3121 static int stbv_vorbis_decode_initial(stbv_vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
3124 int i, n, prev, next, window_center;
3125 f->channel_buffer_start = f->channel_buffer_end = 0;
3128 if (f->eof) return FALSE;
3129 if (!stbv_maybe_start_packet(f))
3131 // check packet type
3132 if (stbv_get_bits(f,1) != 0) {
3133 if (STBV_IS_PUSH_MODE(f))
3134 return stbv_error(f,VORBIS_bad_packet_type);
3135 while (STBV_EOP != stbv_get8_packet(f));
3139 if (f->alloc.alloc_buffer)
3140 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3142 i = stbv_get_bits(f, stbv_ilog(f->mode_count-1));
3143 if (i == STBV_EOP) return FALSE;
3144 if (i >= f->mode_count) return FALSE;
3146 m = f->mode_config + i;
3149 prev = stbv_get_bits(f,1);
3150 next = stbv_get_bits(f,1);
3158 window_center = n >> 1;
3159 if (m->blockflag && !prev) {
3160 *p_left_start = (n - f->blocksize_0) >> 2;
3161 *p_left_end = (n + f->blocksize_0) >> 2;
3164 *p_left_end = window_center;
3166 if (m->blockflag && !next) {
3167 *p_right_start = (n*3 - f->blocksize_0) >> 2;
3168 *p_right_end = (n*3 + f->blocksize_0) >> 2;
3170 *p_right_start = window_center;
3177 static int stbv_vorbis_decode_packet_rest(stbv_vorb *f, int *len, StbvMode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
3181 int zero_channel[256];
3182 int really_zero_channel[256];
3186 n = f->blocksize[m->blockflag];
3187 map = &f->mapping[m->mapping];
3194 for (i=0; i < f->channels; ++i) {
3195 int s = map->chan[i].mux, floor;
3196 zero_channel[i] = FALSE;
3197 floor = map->submap_floor[s];
3198 if (f->floor_types[floor] == 0) {
3199 return stbv_error(f, VORBIS_invalid_stream);
3201 StbvFloor1 *g = &f->floor_config[floor].floor1;
3202 if (stbv_get_bits(f, 1)) {
3204 stbv_uint8 step2_flag[256];
3205 static int range_list[4] = { 256, 128, 86, 64 };
3206 int range = range_list[g->floor1_multiplier-1];
3208 finalY = f->finalY[i];
3209 finalY[0] = stbv_get_bits(f, stbv_ilog(range)-1);
3210 finalY[1] = stbv_get_bits(f, stbv_ilog(range)-1);
3211 for (j=0; j < g->partitions; ++j) {
3212 int pclass = g->partition_class_list[j];
3213 int cdim = g->class_dimensions[pclass];
3214 int cbits = g->class_subclasses[pclass];
3215 int csub = (1 << cbits)-1;
3218 StbvCodebook *c = f->codebooks + g->class_masterbooks[pclass];
3219 STBV_DECODE(cval,f,c);
3221 for (k=0; k < cdim; ++k) {
3222 int book = g->subclass_books[pclass][cval & csub];
3223 cval = cval >> cbits;
3226 StbvCodebook *c = f->codebooks + book;
3227 STBV_DECODE(temp,f,c);
3228 finalY[offset++] = temp;
3230 finalY[offset++] = 0;
3233 if (f->valid_bits == STBV_INVALID_BITS) goto error; // behavior according to spec
3234 step2_flag[0] = step2_flag[1] = 1;
3235 for (j=2; j < g->values; ++j) {
3236 int low, high, pred, highroom, lowroom, room, val;
3237 low = g->stbv_neighbors[j][0];
3238 high = g->stbv_neighbors[j][1];
3239 //stbv_neighbors(g->Xlist, j, &low, &high);
3240 pred = stbv_predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
3242 highroom = range - pred;
3244 if (highroom < lowroom)
3245 room = highroom * 2;
3249 step2_flag[low] = step2_flag[high] = 1;
3252 if (highroom > lowroom)
3253 finalY[j] = val - lowroom + pred;
3255 finalY[j] = pred - val + highroom - 1;
3258 finalY[j] = pred - ((val+1)>>1);
3260 finalY[j] = pred + (val>>1);
3267 #ifdef STB_VORBIS_NO_DEFER_FLOOR
3268 stbv_do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
3270 // defer final floor computation until _after_ residue
3271 for (j=0; j < g->values; ++j) {
3278 zero_channel[i] = TRUE;
3280 // So we just defer everything else to later
3282 // at this point we've decoded the floor into buffer
3286 // at this point we've decoded all floors
3288 if (f->alloc.alloc_buffer)
3289 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3291 // re-enable coupled channels if necessary
3292 memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
3293 for (i=0; i < map->coupling_steps; ++i)
3294 if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
3295 zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
3299 // RESIDUE STBV_DECODE
3300 for (i=0; i < map->submaps; ++i) {
3301 float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
3303 stbv_uint8 do_not_decode[256];
3305 for (j=0; j < f->channels; ++j) {
3306 if (map->chan[j].mux == i) {
3307 if (zero_channel[j]) {
3308 do_not_decode[ch] = TRUE;
3309 residue_buffers[ch] = NULL;
3311 do_not_decode[ch] = FALSE;
3312 residue_buffers[ch] = f->channel_buffers[j];
3317 r = map->submap_residue[i];
3318 stbv_decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
3321 if (f->alloc.alloc_buffer)
3322 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3326 for (i = map->coupling_steps-1; i >= 0; --i) {
3328 float *m = f->channel_buffers[map->chan[i].magnitude];
3329 float *a = f->channel_buffers[map->chan[i].angle ];
3330 for (j=0; j < n2; ++j) {
3334 m2 = m[j], a2 = m[j] - a[j];
3336 a2 = m[j], m2 = m[j] + a[j];
3339 m2 = m[j], a2 = m[j] + a[j];
3341 a2 = m[j], m2 = m[j] - a[j];
3348 // finish decoding the floors
3349 #ifndef STB_VORBIS_NO_DEFER_FLOOR
3350 for (i=0; i < f->channels; ++i) {
3351 if (really_zero_channel[i]) {
3352 memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
3354 stbv_do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
3358 for (i=0; i < f->channels; ++i) {
3359 if (really_zero_channel[i]) {
3360 memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
3362 for (j=0; j < n2; ++j)
3363 f->channel_buffers[i][j] *= f->floor_buffers[i][j];
3370 for (i=0; i < f->channels; ++i)
3371 stbv_inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
3374 // this shouldn't be necessary, unless we exited on an error
3375 // and want to flush to get to the next packet
3376 stbv_flush_packet(f);
3378 if (f->first_decode) {
3379 // assume we start so first non-discarded sample is sample 0
3380 // this isn't to spec, but spec would require us to read ahead
3381 // and decode the size of all current frames--could be done,
3382 // but presumably it's not a commonly used feature
3383 f->current_loc = -n2; // start of first frame is positioned for discard
3384 // we might have to discard samples "from" the next frame too,
3385 // if we're lapping a large block then a small at the start?
3386 f->discard_samples_deferred = n - right_end;
3387 f->current_loc_valid = TRUE;
3388 f->first_decode = FALSE;
3389 } else if (f->discard_samples_deferred) {
3390 if (f->discard_samples_deferred >= right_start - left_start) {
3391 f->discard_samples_deferred -= (right_start - left_start);
3392 left_start = right_start;
3393 *p_left = left_start;
3395 left_start += f->discard_samples_deferred;
3396 *p_left = left_start;
3397 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...
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 & STBV_PAGEFLAG_last_page)) {
3412 stbv_uint32 current_end = f->known_loc_for_packet;
3413 // then let's infer the size of the (probably) short final frame
3414 if (current_end < f->current_loc + (right_end-left_start)) {
3415 if (current_end < f->current_loc) {
3416 // negative truncation, that's impossible!
3419 *len = current_end - f->current_loc;
3421 *len += left_start; // this doesn't seem right, but has no ill effect on my test files
3422 if (*len > right_end) *len = right_end; // this should never happen
3423 f->current_loc += *len;
3427 // otherwise, just set our sample loc
3428 // guess that the ogg granule pos refers to the _middle_ of the
3430 // set f->current_loc to the position of left_start
3431 f->current_loc = f->known_loc_for_packet - (n2-left_start);
3432 f->current_loc_valid = TRUE;
3434 if (f->current_loc_valid)
3435 f->current_loc += (right_start - left_start);
3437 if (f->alloc.alloc_buffer)
3438 assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
3439 *len = right_end; // ignore samples after the window goes to 0
3445 static int stbv_vorbis_decode_packet(stbv_vorb *f, int *len, int *p_left, int *p_right)
3447 int mode, left_end, right_end;
3448 if (!stbv_vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
3449 return stbv_vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
3452 static int stbv_vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
3455 // we use right&left (the start of the right- and left-window sin()-regions)
3456 // to determine how much to return, rather than inferring from the rules
3457 // (same result, clearer code); 'left' indicates where our sin() window
3458 // starts, therefore where the previous window's right edge starts, and
3459 // therefore where to start mixing from the previous buffer. 'right'
3460 // indicates where our sin() ending-window starts, therefore that's where
3461 // we start saving, and where our returned-data ends.
3463 // mixin from previous window
3464 if (f->previous_length) {
3465 int i,j, n = f->previous_length;
3466 float *w = stbv_get_window(f, n);
3467 for (i=0; i < f->channels; ++i) {
3468 for (j=0; j < n; ++j)
3469 f->channel_buffers[i][left+j] =
3470 f->channel_buffers[i][left+j]*w[ j] +
3471 f->previous_window[i][ j]*w[n-1-j];
3475 prev = f->previous_length;
3477 // last half of this data becomes previous window
3478 f->previous_length = len - right;
3480 // @OPTIMIZE: could avoid this copy by double-buffering the
3481 // output (flipping previous_window with channel_buffers), but
3482 // then previous_window would have to be 2x as large, and
3483 // channel_buffers couldn't be temp mem (although they're NOT
3484 // currently temp mem, they could be (unless we want to level
3485 // performance by spreading out the computation))
3486 for (i=0; i < f->channels; ++i)
3487 for (j=0; right+j < len; ++j)
3488 f->previous_window[i][j] = f->channel_buffers[i][right+j];
3491 // there was no previous packet, so this data isn't valid...
3492 // this isn't entirely true, only the would-have-overlapped data
3493 // isn't valid, but this seems to be what the spec requires
3496 // truncate a short frame
3497 if (len < right) right = len;
3499 f->samples_output += right-left;
3501 return right - left;
3504 static int stbv_vorbis_pump_first_frame(stb_vorbis *f)
3506 int len, right, left, res;
3507 res = stbv_vorbis_decode_packet(f, &len, &left, &right);
3509 stbv_vorbis_finish_frame(f, len, left, right);
3513 #ifndef STB_VORBIS_NO_PUSHDATA_API
3514 static int stbv_is_whole_packet_present(stb_vorbis *f, int end_page)
3516 // make sure that we have the packet available before continuing...
3517 // this requires a full ogg parse, but we know we can fetch from f->stream
3519 // instead of coding this out explicitly, we could save the current read state,
3520 // read the next packet with stbv_get8() until end-of-packet, check f->eof, then
3521 // reset the state? but that would be slower, esp. since we'd have over 256 bytes
3522 // of state to restore (primarily the page segment table)
3524 int s = f->next_seg, first = TRUE;
3525 stbv_uint8 *p = f->stream;
3527 if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
3528 for (; s < f->segment_count; ++s) {
3529 p += f->segments[s];
3530 if (f->segments[s] < 255) // stop at first short segment
3533 // either this continues, or it ends it...
3535 if (s < f->segment_count-1) return stbv_error(f, VORBIS_invalid_stream);
3536 if (s == f->segment_count)
3537 s = -1; // set 'crosses page' flag
3538 if (p > f->stream_end) return stbv_error(f, VORBIS_need_more_data);
3545 // check that we have the page header ready
3546 if (p + 26 >= f->stream_end) return stbv_error(f, VORBIS_need_more_data);
3547 // validate the page
3548 if (memcmp(p, stbv_ogg_page_header, 4)) return stbv_error(f, VORBIS_invalid_stream);
3549 if (p[4] != 0) return stbv_error(f, VORBIS_invalid_stream);
3550 if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
3551 if (f->previous_length)
3552 if ((p[5] & STBV_PAGEFLAG_continued_packet)) return stbv_error(f, VORBIS_invalid_stream);
3553 // if no previous length, we're resynching, so we can come in on a continued-packet,
3554 // which we'll just drop
3556 if (!(p[5] & STBV_PAGEFLAG_continued_packet)) return stbv_error(f, VORBIS_invalid_stream);
3558 n = p[26]; // segment counts
3559 q = p+27; // q points to segment table
3560 p = q + n; // advance past header
3561 // make sure we've read the segment table
3562 if (p > f->stream_end) return stbv_error(f, VORBIS_need_more_data);
3563 for (s=0; s < n; ++s) {
3569 if (s < n-1) return stbv_error(f, VORBIS_invalid_stream);
3571 s = -1; // set 'crosses page' flag
3572 if (p > f->stream_end) return stbv_error(f, VORBIS_need_more_data);
3577 #endif // !STB_VORBIS_NO_PUSHDATA_API
3579 static int stbv_start_decoder(stbv_vorb *f)
3581 stbv_uint8 header[6], x,y;
3582 int len,i,j,k, max_submaps = 0;
3583 int longest_floorlist=0;
3585 // first page, first packet
3587 if (!stbv_start_page(f)) return FALSE;
3588 // validate page flag
3589 if (!(f->page_flag & STBV_PAGEFLAG_first_page)) return stbv_error(f, VORBIS_invalid_first_page);
3590 if (f->page_flag & STBV_PAGEFLAG_last_page) return stbv_error(f, VORBIS_invalid_first_page);
3591 if (f->page_flag & STBV_PAGEFLAG_continued_packet) return stbv_error(f, VORBIS_invalid_first_page);
3592 // check for expected packet length
3593 if (f->segment_count != 1) return stbv_error(f, VORBIS_invalid_first_page);
3594 if (f->segments[0] != 30) return stbv_error(f, VORBIS_invalid_first_page);
3596 // check packet header
3597 if (stbv_get8(f) != STBV_VORBIS_packet_id) return stbv_error(f, VORBIS_invalid_first_page);
3598 if (!stbv_getn(f, header, 6)) return stbv_error(f, VORBIS_unexpected_eof);
3599 if (!stbv_vorbis_validate(header)) return stbv_error(f, VORBIS_invalid_first_page);
3601 if (stbv_get32(f) != 0) return stbv_error(f, VORBIS_invalid_first_page);
3602 f->channels = stbv_get8(f); if (!f->channels) return stbv_error(f, VORBIS_invalid_first_page);
3603 if (f->channels > STB_VORBIS_MAX_CHANNELS) return stbv_error(f, VORBIS_too_many_channels);
3604 f->sample_rate = stbv_get32(f); if (!f->sample_rate) return stbv_error(f, VORBIS_invalid_first_page);
3605 stbv_get32(f); // bitrate_maximum
3606 stbv_get32(f); // bitrate_nominal
3607 stbv_get32(f); // bitrate_minimum
3613 f->blocksize_0 = 1 << log0;
3614 f->blocksize_1 = 1 << log1;
3615 if (log0 < 6 || log0 > 13) return stbv_error(f, VORBIS_invalid_setup);
3616 if (log1 < 6 || log1 > 13) return stbv_error(f, VORBIS_invalid_setup);
3617 if (log0 > log1) return stbv_error(f, VORBIS_invalid_setup);
3622 if (!(x & 1)) return stbv_error(f, VORBIS_invalid_first_page);
3625 if (!stbv_start_page(f)) return FALSE;
3627 if (!stbv_start_packet(f)) return FALSE;
3629 len = stbv_next_segment(f);
3631 f->bytes_in_seg = 0;
3635 if (!stbv_start_packet(f)) return FALSE;
3637 #ifndef STB_VORBIS_NO_PUSHDATA_API
3638 if (STBV_IS_PUSH_MODE(f)) {
3639 if (!stbv_is_whole_packet_present(f, TRUE)) {
3640 // convert error in ogg header to write type
3641 if (f->error == VORBIS_invalid_stream)
3642 f->error = VORBIS_invalid_setup;
3648 stbv_crc32_init(); // always init it, to avoid multithread race conditions
3650 if (stbv_get8_packet(f) != STBV_VORBIS_packet_setup) return stbv_error(f, VORBIS_invalid_setup);
3651 for (i=0; i < 6; ++i) header[i] = stbv_get8_packet(f);
3652 if (!stbv_vorbis_validate(header)) return stbv_error(f, VORBIS_invalid_setup);
3656 f->codebook_count = stbv_get_bits(f,8) + 1;
3657 f->codebooks = (StbvCodebook *) stbv_setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
3658 if (f->codebooks == NULL) return stbv_error(f, VORBIS_outofmem);
3659 memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
3660 for (i=0; i < f->codebook_count; ++i) {
3661 stbv_uint32 *values;
3662 int ordered, sorted_count;
3664 stbv_uint8 *lengths;
3665 StbvCodebook *c = f->codebooks+i;
3667 x = stbv_get_bits(f, 8); if (x != 0x42) return stbv_error(f, VORBIS_invalid_setup);
3668 x = stbv_get_bits(f, 8); if (x != 0x43) return stbv_error(f, VORBIS_invalid_setup);
3669 x = stbv_get_bits(f, 8); if (x != 0x56) return stbv_error(f, VORBIS_invalid_setup);
3670 x = stbv_get_bits(f, 8);
3671 c->dimensions = (stbv_get_bits(f, 8)<<8) + x;
3672 x = stbv_get_bits(f, 8);
3673 y = stbv_get_bits(f, 8);
3674 c->entries = (stbv_get_bits(f, 8)<<16) + (y<<8) + x;
3675 ordered = stbv_get_bits(f,1);
3676 c->sparse = ordered ? 0 : stbv_get_bits(f,1);
3678 if (c->dimensions == 0 && c->entries != 0) return stbv_error(f, VORBIS_invalid_setup);
3681 lengths = (stbv_uint8 *) stbv_setup_temp_malloc(f, c->entries);
3683 lengths = c->codeword_lengths = (stbv_uint8 *) stbv_setup_malloc(f, c->entries);
3685 if (!lengths) return stbv_error(f, VORBIS_outofmem);
3688 int current_entry = 0;
3689 int current_length = stbv_get_bits(f,5) + 1;
3690 while (current_entry < c->entries) {
3691 int limit = c->entries - current_entry;
3692 int n = stbv_get_bits(f, stbv_ilog(limit));
3693 if (current_entry + n > (int) c->entries) { return stbv_error(f, VORBIS_invalid_setup); }
3694 memset(lengths + current_entry, current_length, n);
3699 for (j=0; j < c->entries; ++j) {
3700 int present = c->sparse ? stbv_get_bits(f,1) : 1;
3702 lengths[j] = stbv_get_bits(f, 5) + 1;
3704 if (lengths[j] == 32)
3705 return stbv_error(f, VORBIS_invalid_setup);
3707 lengths[j] = NO_CODE;
3712 if (c->sparse && total >= c->entries >> 2) {
3713 // convert sparse items to non-sparse!
3714 if (c->entries > (int) f->setup_temp_memory_required)
3715 f->setup_temp_memory_required = c->entries;
3717 c->codeword_lengths = (stbv_uint8 *) stbv_setup_malloc(f, c->entries);
3718 if (c->codeword_lengths == NULL) return stbv_error(f, VORBIS_outofmem);
3719 memcpy(c->codeword_lengths, lengths, c->entries);
3720 stbv_setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
3721 lengths = c->codeword_lengths;
3725 // compute the size of the sorted tables
3727 sorted_count = total;
3730 #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
3731 for (j=0; j < c->entries; ++j)
3732 if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
3737 c->sorted_entries = sorted_count;
3742 c->codewords = (stbv_uint32 *) stbv_setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
3743 if (!c->codewords) return stbv_error(f, VORBIS_outofmem);
3746 if (c->sorted_entries) {
3747 c->codeword_lengths = (stbv_uint8 *) stbv_setup_malloc(f, c->sorted_entries);
3748 if (!c->codeword_lengths) return stbv_error(f, VORBIS_outofmem);
3749 c->codewords = (stbv_uint32 *) stbv_setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
3750 if (!c->codewords) return stbv_error(f, VORBIS_outofmem);
3751 values = (stbv_uint32 *) stbv_setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
3752 if (!values) return stbv_error(f, VORBIS_outofmem);
3754 size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
3755 if (size > f->setup_temp_memory_required)
3756 f->setup_temp_memory_required = size;
3759 if (!stbv_compute_codewords(c, lengths, c->entries, values)) {
3760 if (c->sparse) stbv_setup_temp_free(f, values, 0);
3761 return stbv_error(f, VORBIS_invalid_setup);
3764 if (c->sorted_entries) {
3765 // allocate an extra slot for sentinels
3766 c->sorted_codewords = (stbv_uint32 *) stbv_setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
3767 if (c->sorted_codewords == NULL) return stbv_error(f, VORBIS_outofmem);
3768 // allocate an extra slot at the front so that c->sorted_values[-1] is defined
3769 // so that we can catch that case without an extra if
3770 c->sorted_values = ( int *) stbv_setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
3771 if (c->sorted_values == NULL) return stbv_error(f, VORBIS_outofmem);
3773 c->sorted_values[-1] = -1;
3774 stbv_compute_sorted_huffman(c, lengths, values);
3778 stbv_setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
3779 stbv_setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
3780 stbv_setup_temp_free(f, lengths, c->entries);
3781 c->codewords = NULL;
3784 stbv_compute_accelerated_huffman(c);
3787 c->lookup_type = stbv_get_bits(f, 4);
3788 if (c->lookup_type > 2) return stbv_error(f, VORBIS_invalid_setup);
3789 if (c->lookup_type > 0) {
3791 c->minimum_value = stbv_float32_unpack(stbv_get_bits(f, 32));
3792 c->delta_value = stbv_float32_unpack(stbv_get_bits(f, 32));
3793 c->value_bits = stbv_get_bits(f, 4)+1;
3794 c->sequence_p = stbv_get_bits(f,1);
3795 if (c->lookup_type == 1) {
3796 c->lookup_values = stbv_lookup1_values(c->entries, c->dimensions);
3798 c->lookup_values = c->entries * c->dimensions;
3800 if (c->lookup_values == 0) return stbv_error(f, VORBIS_invalid_setup);
3801 mults = (stbv_uint16 *) stbv_setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
3802 if (mults == NULL) return stbv_error(f, VORBIS_outofmem);
3803 for (j=0; j < (int) c->lookup_values; ++j) {
3804 int q = stbv_get_bits(f, c->value_bits);
3805 if (q == STBV_EOP) { stbv_setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return stbv_error(f, VORBIS_invalid_setup); }
3809 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
3810 if (c->lookup_type == 1) {
3811 int len, sparse = c->sparse;
3813 // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
3815 if (c->sorted_entries == 0) goto stbv_skip;
3816 c->multiplicands = (stbv_codetype *) stbv_setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
3818 c->multiplicands = (stbv_codetype *) stbv_setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
3819 if (c->multiplicands == NULL) { stbv_setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return stbv_error(f, VORBIS_outofmem); }
3820 len = sparse ? c->sorted_entries : c->entries;
3821 for (j=0; j < len; ++j) {
3822 unsigned int z = sparse ? c->sorted_values[j] : j;
3824 for (k=0; k < c->dimensions; ++k) {
3825 int off = (z / div) % c->lookup_values;
3826 float val = mults[off];
3827 val = mults[off]*c->delta_value + c->minimum_value + last;
3828 c->multiplicands[j*c->dimensions + k] = val;
3831 if (k+1 < c->dimensions) {
3832 if (div > UINT_MAX / (unsigned int) c->lookup_values) {
3833 stbv_setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
3834 return stbv_error(f, VORBIS_invalid_setup);
3836 div *= c->lookup_values;
3847 c->multiplicands = (stbv_codetype *) stbv_setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
3848 if (c->multiplicands == NULL) { stbv_setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return stbv_error(f, VORBIS_outofmem); }
3849 for (j=0; j < (int) c->lookup_values; ++j) {
3850 float val = mults[j] * c->delta_value + c->minimum_value + last;
3851 c->multiplicands[j] = val;
3856 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
3859 stbv_setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
3866 // time domain transfers (notused)
3868 x = stbv_get_bits(f, 6) + 1;
3869 for (i=0; i < x; ++i) {
3870 stbv_uint32 z = stbv_get_bits(f, 16);
3871 if (z != 0) return stbv_error(f, VORBIS_invalid_setup);
3875 f->floor_count = stbv_get_bits(f, 6)+1;
3876 f->floor_config = (StbvFloor *) stbv_setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
3877 if (f->floor_config == NULL) return stbv_error(f, VORBIS_outofmem);
3878 for (i=0; i < f->floor_count; ++i) {
3879 f->floor_types[i] = stbv_get_bits(f, 16);
3880 if (f->floor_types[i] > 1) return stbv_error(f, VORBIS_invalid_setup);
3881 if (f->floor_types[i] == 0) {
3882 StbvFloor0 *g = &f->floor_config[i].floor0;
3883 g->order = stbv_get_bits(f,8);
3884 g->rate = stbv_get_bits(f,16);
3885 g->bark_map_size = stbv_get_bits(f,16);
3886 g->amplitude_bits = stbv_get_bits(f,6);
3887 g->amplitude_offset = stbv_get_bits(f,8);
3888 g->number_of_books = stbv_get_bits(f,4) + 1;
3889 for (j=0; j < g->number_of_books; ++j)
3890 g->book_list[j] = stbv_get_bits(f,8);
3891 return stbv_error(f, VORBIS_feature_not_supported);
3893 stbv_floor_ordering p[31*8+2];
3894 StbvFloor1 *g = &f->floor_config[i].floor1;
3896 g->partitions = stbv_get_bits(f, 5);
3897 for (j=0; j < g->partitions; ++j) {
3898 g->partition_class_list[j] = stbv_get_bits(f, 4);
3899 if (g->partition_class_list[j] > max_class)
3900 max_class = g->partition_class_list[j];
3902 for (j=0; j <= max_class; ++j) {
3903 g->class_dimensions[j] = stbv_get_bits(f, 3)+1;
3904 g->class_subclasses[j] = stbv_get_bits(f, 2);
3905 if (g->class_subclasses[j]) {
3906 g->class_masterbooks[j] = stbv_get_bits(f, 8);
3907 if (g->class_masterbooks[j] >= f->codebook_count) return stbv_error(f, VORBIS_invalid_setup);
3909 for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
3910 g->subclass_books[j][k] = stbv_get_bits(f,8)-1;
3911 if (g->subclass_books[j][k] >= f->codebook_count) return stbv_error(f, VORBIS_invalid_setup);
3914 g->floor1_multiplier = stbv_get_bits(f,2)+1;
3915 g->rangebits = stbv_get_bits(f,4);
3917 g->Xlist[1] = 1 << g->rangebits;
3919 for (j=0; j < g->partitions; ++j) {
3920 int c = g->partition_class_list[j];
3921 for (k=0; k < g->class_dimensions[c]; ++k) {
3922 g->Xlist[g->values] = stbv_get_bits(f, g->rangebits);
3926 // precompute the sorting
3927 for (j=0; j < g->values; ++j) {
3928 p[j].x = g->Xlist[j];
3931 qsort(p, g->values, sizeof(p[0]), stbv_point_compare);
3932 for (j=0; j < g->values; ++j)
3933 g->sorted_order[j] = (stbv_uint8) p[j].id;
3934 // precompute the stbv_neighbors
3935 for (j=2; j < g->values; ++j) {
3937 stbv_neighbors(g->Xlist, j, &low,&hi);
3938 g->stbv_neighbors[j][0] = low;
3939 g->stbv_neighbors[j][1] = hi;
3942 if (g->values > longest_floorlist)
3943 longest_floorlist = g->values;
3948 f->residue_count = stbv_get_bits(f, 6)+1;
3949 f->residue_config = (StbvResidue *) stbv_setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
3950 if (f->residue_config == NULL) return stbv_error(f, VORBIS_outofmem);
3951 memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
3952 for (i=0; i < f->residue_count; ++i) {
3953 stbv_uint8 residue_cascade[64];
3954 StbvResidue *r = f->residue_config+i;
3955 f->residue_types[i] = stbv_get_bits(f, 16);
3956 if (f->residue_types[i] > 2) return stbv_error(f, VORBIS_invalid_setup);
3957 r->begin = stbv_get_bits(f, 24);
3958 r->end = stbv_get_bits(f, 24);
3959 if (r->end < r->begin) return stbv_error(f, VORBIS_invalid_setup);
3960 r->part_size = stbv_get_bits(f,24)+1;
3961 r->classifications = stbv_get_bits(f,6)+1;
3962 r->classbook = stbv_get_bits(f,8);
3963 if (r->classbook >= f->codebook_count) return stbv_error(f, VORBIS_invalid_setup);
3964 for (j=0; j < r->classifications; ++j) {
3965 stbv_uint8 high_bits=0;
3966 stbv_uint8 low_bits=stbv_get_bits(f,3);
3967 if (stbv_get_bits(f,1))
3968 high_bits = stbv_get_bits(f,5);
3969 residue_cascade[j] = high_bits*8 + low_bits;
3971 r->residue_books = (short (*)[8]) stbv_setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
3972 if (r->residue_books == NULL) return stbv_error(f, VORBIS_outofmem);
3973 for (j=0; j < r->classifications; ++j) {
3974 for (k=0; k < 8; ++k) {
3975 if (residue_cascade[j] & (1 << k)) {
3976 r->residue_books[j][k] = stbv_get_bits(f, 8);
3977 if (r->residue_books[j][k] >= f->codebook_count) return stbv_error(f, VORBIS_invalid_setup);
3979 r->residue_books[j][k] = -1;
3983 // precompute the classifications[] array to avoid inner-loop mod/divide
3984 // call it 'classdata' since we already have r->classifications
3985 r->classdata = (stbv_uint8 **) stbv_setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
3986 if (!r->classdata) return stbv_error(f, VORBIS_outofmem);
3987 memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
3988 for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
3989 int classwords = f->codebooks[r->classbook].dimensions;
3991 r->classdata[j] = (stbv_uint8 *) stbv_setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
3992 if (r->classdata[j] == NULL) return stbv_error(f, VORBIS_outofmem);
3993 for (k=classwords-1; k >= 0; --k) {
3994 r->classdata[j][k] = temp % r->classifications;
3995 temp /= r->classifications;
4000 f->mapping_count = stbv_get_bits(f,6)+1;
4001 f->mapping = (StbvMapping *) stbv_setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
4002 if (f->mapping == NULL) return stbv_error(f, VORBIS_outofmem);
4003 memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
4004 for (i=0; i < f->mapping_count; ++i) {
4005 StbvMapping *m = f->mapping + i;
4006 int mapping_type = stbv_get_bits(f,16);
4007 if (mapping_type != 0) return stbv_error(f, VORBIS_invalid_setup);
4008 m->chan = (StbvMappingChannel *) stbv_setup_malloc(f, f->channels * sizeof(*m->chan));
4009 if (m->chan == NULL) return stbv_error(f, VORBIS_outofmem);
4010 if (stbv_get_bits(f,1))
4011 m->submaps = stbv_get_bits(f,4)+1;
4014 if (m->submaps > max_submaps)
4015 max_submaps = m->submaps;
4016 if (stbv_get_bits(f,1)) {
4017 m->coupling_steps = stbv_get_bits(f,8)+1;
4018 for (k=0; k < m->coupling_steps; ++k) {
4019 m->chan[k].magnitude = stbv_get_bits(f, stbv_ilog(f->channels-1));
4020 m->chan[k].angle = stbv_get_bits(f, stbv_ilog(f->channels-1));
4021 if (m->chan[k].magnitude >= f->channels) return stbv_error(f, VORBIS_invalid_setup);
4022 if (m->chan[k].angle >= f->channels) return stbv_error(f, VORBIS_invalid_setup);
4023 if (m->chan[k].magnitude == m->chan[k].angle) return stbv_error(f, VORBIS_invalid_setup);
4026 m->coupling_steps = 0;
4029 if (stbv_get_bits(f,2)) return stbv_error(f, VORBIS_invalid_setup);
4030 if (m->submaps > 1) {
4031 for (j=0; j < f->channels; ++j) {
4032 m->chan[j].mux = stbv_get_bits(f, 4);
4033 if (m->chan[j].mux >= m->submaps) return stbv_error(f, VORBIS_invalid_setup);
4036 // @SPECIFICATION: this case is missing from the spec
4037 for (j=0; j < f->channels; ++j)
4040 for (j=0; j < m->submaps; ++j) {
4041 stbv_get_bits(f,8); // discard
4042 m->submap_floor[j] = stbv_get_bits(f,8);
4043 m->submap_residue[j] = stbv_get_bits(f,8);
4044 if (m->submap_floor[j] >= f->floor_count) return stbv_error(f, VORBIS_invalid_setup);
4045 if (m->submap_residue[j] >= f->residue_count) return stbv_error(f, VORBIS_invalid_setup);
4050 f->mode_count = stbv_get_bits(f, 6)+1;
4051 for (i=0; i < f->mode_count; ++i) {
4052 StbvMode *m = f->mode_config+i;
4053 m->blockflag = stbv_get_bits(f,1);
4054 m->windowtype = stbv_get_bits(f,16);
4055 m->transformtype = stbv_get_bits(f,16);
4056 m->mapping = stbv_get_bits(f,8);
4057 if (m->windowtype != 0) return stbv_error(f, VORBIS_invalid_setup);
4058 if (m->transformtype != 0) return stbv_error(f, VORBIS_invalid_setup);
4059 if (m->mapping >= f->mapping_count) return stbv_error(f, VORBIS_invalid_setup);
4062 stbv_flush_packet(f);
4064 f->previous_length = 0;
4066 for (i=0; i < f->channels; ++i) {
4067 f->channel_buffers[i] = (float *) stbv_setup_malloc(f, sizeof(float) * f->blocksize_1);
4068 f->previous_window[i] = (float *) stbv_setup_malloc(f, sizeof(float) * f->blocksize_1/2);
4069 f->finalY[i] = (stbv_int16 *) stbv_setup_malloc(f, sizeof(stbv_int16) * longest_floorlist);
4070 if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return stbv_error(f, VORBIS_outofmem);
4071 memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1);
4072 #ifdef STB_VORBIS_NO_DEFER_FLOOR
4073 f->floor_buffers[i] = (float *) stbv_setup_malloc(f, sizeof(float) * f->blocksize_1/2);
4074 if (f->floor_buffers[i] == NULL) return stbv_error(f, VORBIS_outofmem);
4078 if (!stbv_init_blocksize(f, 0, f->blocksize_0)) return FALSE;
4079 if (!stbv_init_blocksize(f, 1, f->blocksize_1)) return FALSE;
4080 f->blocksize[0] = f->blocksize_0;
4081 f->blocksize[1] = f->blocksize_1;
4083 #ifdef STB_VORBIS_DIVIDE_TABLE
4084 if (stbv_integer_divide_table[1][1]==0)
4085 for (i=0; i < STBV_DIVTAB_NUMER; ++i)
4086 for (j=1; j < STBV_DIVTAB_DENOM; ++j)
4087 stbv_integer_divide_table[i][j] = i / j;
4090 // compute how much temporary memory is needed
4094 stbv_uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
4095 stbv_uint32 classify_mem;
4096 int i,max_part_read=0;
4097 for (i=0; i < f->residue_count; ++i) {
4098 StbvResidue *r = f->residue_config + i;
4099 unsigned int actual_size = f->blocksize_1 / 2;
4100 unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size;
4101 unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size;
4102 int n_read = limit_r_end - limit_r_begin;
4103 int part_read = n_read / r->part_size;
4104 if (part_read > max_part_read)
4105 max_part_read = part_read;
4107 #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
4108 classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(stbv_uint8 *));
4110 classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
4113 // maximum reasonable partition size is f->blocksize_1
4115 f->temp_memory_required = classify_mem;
4116 if (imdct_mem > f->temp_memory_required)
4117 f->temp_memory_required = imdct_mem;
4120 f->first_decode = TRUE;
4122 if (f->alloc.alloc_buffer) {
4123 assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
4124 // check if there's enough temp memory so we don't error later
4125 if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
4126 return stbv_error(f, VORBIS_outofmem);
4129 f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
4134 static void stbv_vorbis_deinit(stb_vorbis *p)
4137 if (p->residue_config) {
4138 for (i=0; i < p->residue_count; ++i) {
4139 StbvResidue *r = p->residue_config+i;
4141 for (j=0; j < p->codebooks[r->classbook].entries; ++j)
4142 stbv_setup_free(p, r->classdata[j]);
4143 stbv_setup_free(p, r->classdata);
4145 stbv_setup_free(p, r->residue_books);
4151 for (i=0; i < p->codebook_count; ++i) {
4152 StbvCodebook *c = p->codebooks + i;
4153 stbv_setup_free(p, c->codeword_lengths);
4154 stbv_setup_free(p, c->multiplicands);
4155 stbv_setup_free(p, c->codewords);
4156 stbv_setup_free(p, c->sorted_codewords);
4157 // c->sorted_values[-1] is the first entry in the array
4158 stbv_setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
4160 stbv_setup_free(p, p->codebooks);
4162 stbv_setup_free(p, p->floor_config);
4163 stbv_setup_free(p, p->residue_config);
4165 for (i=0; i < p->mapping_count; ++i)
4166 stbv_setup_free(p, p->mapping[i].chan);
4167 stbv_setup_free(p, p->mapping);
4170 for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
4171 stbv_setup_free(p, p->channel_buffers[i]);
4172 stbv_setup_free(p, p->previous_window[i]);
4173 #ifdef STB_VORBIS_NO_DEFER_FLOOR
4174 stbv_setup_free(p, p->floor_buffers[i]);
4176 stbv_setup_free(p, p->finalY[i]);
4178 for (i=0; i < 2; ++i) {
4179 stbv_setup_free(p, p->A[i]);
4180 stbv_setup_free(p, p->B[i]);
4181 stbv_setup_free(p, p->C[i]);
4182 stbv_setup_free(p, p->window[i]);
4183 stbv_setup_free(p, p->stbv_bit_reverse[i]);
4185 #ifndef STB_VORBIS_NO_STDIO
4186 if (p->close_on_free) fclose(p->f);
4190 STBVDEF void stb_vorbis_close(stb_vorbis *p)
4192 if (p == NULL) return;
4193 stbv_vorbis_deinit(p);
4194 stbv_setup_free(p,p);
4197 static void stbv_vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)
4199 memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
4202 p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3;
4203 p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
4206 p->error = VORBIS__no_error;
4208 p->codebooks = NULL;
4209 p->page_crc_tests = -1;
4210 #ifndef STB_VORBIS_NO_STDIO
4211 p->close_on_free = FALSE;
4216 STBVDEF int stb_vorbis_get_sample_offset(stb_vorbis *f)
4218 if (f->current_loc_valid)
4219 return f->current_loc;
4224 STBVDEF stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
4227 d.channels = f->channels;
4228 d.sample_rate = f->sample_rate;
4229 d.setup_memory_required = f->setup_memory_required;
4230 d.setup_temp_memory_required = f->setup_temp_memory_required;
4231 d.temp_memory_required = f->temp_memory_required;
4232 d.max_frame_size = f->blocksize_1 >> 1;
4236 STBVDEF int stb_vorbis_get_error(stb_vorbis *f)
4239 f->error = VORBIS__no_error;
4243 static stb_vorbis * stbv_vorbis_alloc(stb_vorbis *f)
4245 stb_vorbis *p = (stb_vorbis *) stbv_setup_malloc(f, sizeof(*p));
4249 #ifndef STB_VORBIS_NO_PUSHDATA_API
4251 STBVDEF void stb_vorbis_flush_pushdata(stb_vorbis *f)
4253 f->previous_length = 0;
4254 f->page_crc_tests = 0;
4255 f->discard_samples_deferred = 0;
4256 f->current_loc_valid = FALSE;
4257 f->first_decode = FALSE;
4258 f->samples_output = 0;
4259 f->channel_buffer_start = 0;
4260 f->channel_buffer_end = 0;
4263 static int stbv_vorbis_search_for_page_pushdata(stbv_vorb *f, stbv_uint8 *data, int data_len)
4266 for (i=0; i < f->page_crc_tests; ++i)
4267 f->scan[i].bytes_done = 0;
4269 // if we have room for more scans, search for them first, because
4270 // they may cause us to stop early if their header is incomplete
4271 if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
4272 if (data_len < 4) return 0;
4273 data_len -= 3; // need to look for 4-byte sequence, so don't miss
4274 // one that straddles a boundary
4275 for (i=0; i < data_len; ++i) {
4276 if (data[i] == 0x4f) {
4277 if (0==memcmp(data+i, stbv_ogg_page_header, 4)) {
4280 // make sure we have the whole page header
4281 if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
4282 // only read up to this page start, so hopefully we'll
4283 // have the whole page header start next time
4287 // ok, we have it all; compute the length of the page
4288 len = 27 + data[i+26];
4289 for (j=0; j < data[i+26]; ++j)
4290 len += data[i+27+j];
4291 // scan everything up to the embedded crc (which we must 0)
4293 for (j=0; j < 22; ++j)
4294 crc = stbv_crc32_update(crc, data[i+j]);
4295 // now process 4 0-bytes
4296 for ( ; j < 26; ++j)
4297 crc = stbv_crc32_update(crc, 0);
4298 // len is the total number of bytes we need to scan
4299 n = f->page_crc_tests++;
4300 f->scan[n].bytes_left = len-j;
4301 f->scan[n].crc_so_far = crc;
4302 f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
4303 // if the last frame on a page is continued to the next, then
4304 // we can't recover the sample_loc immediately
4305 if (data[i+27+data[i+26]-1] == 255)
4306 f->scan[n].sample_loc = ~0;
4308 f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
4309 f->scan[n].bytes_done = i+j;
4310 if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
4312 // keep going if we still have room for more
4318 for (i=0; i < f->page_crc_tests;) {
4321 int n = f->scan[i].bytes_done;
4322 int m = f->scan[i].bytes_left;
4323 if (m > data_len - n) m = data_len - n;
4324 // m is the bytes to scan in the current chunk
4325 crc = f->scan[i].crc_so_far;
4326 for (j=0; j < m; ++j)
4327 crc = stbv_crc32_update(crc, data[n+j]);
4328 f->scan[i].bytes_left -= m;
4329 f->scan[i].crc_so_far = crc;
4330 if (f->scan[i].bytes_left == 0) {
4332 if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
4333 // Houston, we have page
4334 data_len = n+m; // consumption amount is wherever that scan ended
4335 f->page_crc_tests = -1; // drop out of page scan mode
4336 f->previous_length = 0; // decode-but-don't-output one frame
4337 f->next_seg = -1; // start a new page
4338 f->current_loc = f->scan[i].sample_loc; // set the current sample location
4339 // to the amount we'd have decoded had we decoded this page
4340 f->current_loc_valid = f->current_loc != ~0U;
4344 f->scan[i] = f->scan[--f->page_crc_tests];
4353 // return value: number of bytes we used
4354 STBVDEF int stb_vorbis_decode_frame_pushdata(
4355 stb_vorbis *f, // the file we're decoding
4356 const stbv_uint8 *data, int data_len, // the memory available for decoding
4357 int *channels, // place to write number of float * buffers
4358 float ***output, // place to write float ** array of float * buffers
4359 int *samples // place to write number of output samples
4365 if (!STBV_IS_PUSH_MODE(f)) return stbv_error(f, VORBIS_invalid_api_mixing);
4367 if (f->page_crc_tests >= 0) {
4369 return stbv_vorbis_search_for_page_pushdata(f, (stbv_uint8 *) data, data_len);
4372 f->stream = (stbv_uint8 *) data;
4373 f->stream_end = (stbv_uint8 *) data + data_len;
4374 f->error = VORBIS__no_error;
4376 // check that we have the entire packet in memory
4377 if (!stbv_is_whole_packet_present(f, FALSE)) {
4382 if (!stbv_vorbis_decode_packet(f, &len, &left, &right)) {
4383 // save the actual error we encountered
4384 enum STBVorbisError error = f->error;
4385 if (error == VORBIS_bad_packet_type) {
4386 // flush and resynch
4387 f->error = VORBIS__no_error;
4388 while (stbv_get8_packet(f) != STBV_EOP)
4391 return (int) (f->stream - data);
4393 if (error == VORBIS_continued_packet_flag_invalid) {
4394 if (f->previous_length == 0) {
4395 // we may be resynching, in which case it's ok to hit one
4396 // of these; just discard the packet
4397 f->error = VORBIS__no_error;
4398 while (stbv_get8_packet(f) != STBV_EOP)
4401 return (int) (f->stream - data);
4404 // if we get an error while parsing, what to do?
4405 // well, it DEFINITELY won't work to continue from where we are!
4406 stb_vorbis_flush_pushdata(f);
4407 // restore the error that actually made us bail
4414 len = stbv_vorbis_finish_frame(f, len, left, right);
4415 for (i=0; i < f->channels; ++i)
4416 f->outputs[i] = f->channel_buffers[i] + left;
4418 if (channels) *channels = f->channels;
4420 *output = f->outputs;
4421 return (int) (f->stream - data);
4424 STBVDEF stb_vorbis *stb_vorbis_open_pushdata(
4425 const unsigned char *data, int data_len, // the memory available for decoding
4426 int *data_used, // only defined if result is not NULL
4427 int *error, const stb_vorbis_alloc *alloc)
4430 stbv_vorbis_init(&p, alloc);
4431 p.stream = (stbv_uint8 *) data;
4432 p.stream_end = (stbv_uint8 *) data + data_len;
4434 if (!stbv_start_decoder(&p)) {
4436 *error = VORBIS_need_more_data;
4441 f = stbv_vorbis_alloc(&p);
4444 *data_used = (int) (f->stream - data);
4448 stbv_vorbis_deinit(&p);
4452 #endif // STB_VORBIS_NO_PUSHDATA_API
4454 STBVDEF unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
4456 #ifndef STB_VORBIS_NO_PUSHDATA_API
4457 if (f->push_mode) return 0;
4459 if (STBV_USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);
4460 #ifndef STB_VORBIS_NO_STDIO
4461 return (unsigned int) (ftell(f->f) - f->f_start);
4465 #ifndef STB_VORBIS_NO_PULLDATA_API
4470 static stbv_uint32 stbv_vorbis_find_page(stb_vorbis *f, stbv_uint32 *end, stbv_uint32 *last)
4474 if (f->eof) return 0;
4476 if (n == 0x4f) { // page header candidate
4477 unsigned int retry_loc = stb_vorbis_get_file_offset(f);
4479 // check if we're off the end of a file_section stream
4480 if (retry_loc - 25 > f->stream_len)
4482 // check the rest of the header
4483 for (i=1; i < 4; ++i)
4484 if (stbv_get8(f) != stbv_ogg_page_header[i])
4486 if (f->eof) return 0;
4488 stbv_uint8 header[27];
4489 stbv_uint32 i, crc, goal, len;
4490 for (i=0; i < 4; ++i)
4491 header[i] = stbv_ogg_page_header[i];
4493 header[i] = stbv_get8(f);
4494 if (f->eof) return 0;
4495 if (header[4] != 0) goto invalid;
4496 goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
4497 for (i=22; i < 26; ++i)
4500 for (i=0; i < 27; ++i)
4501 crc = stbv_crc32_update(crc, header[i]);
4503 for (i=0; i < header[26]; ++i) {
4504 int s = stbv_get8(f);
4505 crc = stbv_crc32_update(crc, s);
4508 if (len && f->eof) return 0;
4509 for (i=0; i < len; ++i)
4510 crc = stbv_crc32_update(crc, stbv_get8(f));
4511 // finished parsing probable page
4513 // we could now check that it's either got the last
4514 // page flag set, OR it's followed by the capture
4515 // pattern, but I guess TECHNICALLY you could have
4516 // a file with garbage between each ogg page and recover
4517 // from it automatically? So even though that paranoia
4518 // might decrease the chance of an invalid decode by
4519 // another 2^32, not worth it since it would hose those
4520 // invalid-but-useful files?
4522 *end = stb_vorbis_get_file_offset(f);
4524 if (header[5] & 0x04)
4529 stbv_set_file_offset(f, retry_loc-1);
4534 // not a valid page, so rewind and look for next one
4535 stbv_set_file_offset(f, retry_loc);
4541 #define STBV_SAMPLE_unknown 0xffffffff
4543 // seeking is implemented with a binary search, which narrows down the range to
4544 // 64K, before using a linear search (because finding the synchronization
4545 // pattern can be expensive, and the chance we'd find the end page again is
4546 // relatively high for small ranges)
4548 // two initial interpolation-style probes are used at the start of the search
4549 // to try to bound either side of the binary search sensibly, while still
4550 // working in O(log n) time if they fail.
4552 static int stbv_get_seek_page_info(stb_vorbis *f, StbvProbedPage *z)
4554 stbv_uint8 header[27], lacing[255];
4557 // record where the page starts
4558 z->page_start = stb_vorbis_get_file_offset(f);
4561 stbv_getn(f, header, 27);
4562 if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')
4564 stbv_getn(f, lacing, header[26]);
4566 // determine the length of the payload
4568 for (i=0; i < header[26]; ++i)
4571 // this implies where the page ends
4572 z->page_end = z->page_start + 27 + header[26] + len;
4574 // read the last-decoded sample out of the data
4575 z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
4577 // restore file state to where we were
4578 stbv_set_file_offset(f, z->page_start);
4582 // rarely used function to seek back to the preceeding page while finding the
4583 // start of a packet
4584 static int stbv_go_to_page_before(stb_vorbis *f, unsigned int limit_offset)
4586 unsigned int previous_safe, end;
4588 // now we want to seek back 64K from the limit
4589 if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)
4590 previous_safe = limit_offset - 65536;
4592 previous_safe = f->first_audio_page_offset;
4594 stbv_set_file_offset(f, previous_safe);
4596 while (stbv_vorbis_find_page(f, &end, NULL)) {
4597 if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
4599 stbv_set_file_offset(f, end);
4605 // implements the search logic for finding a page and starting decoding. if
4606 // the function succeeds, current_loc_valid will be true and current_loc will
4607 // be less than or equal to the provided sample number (the closer the
4609 static int stbv_seek_to_sample_coarse(stb_vorbis *f, stbv_uint32 sample_number)
4611 StbvProbedPage left, right, mid;
4612 int i, start_seg_with_known_loc, end_pos, page_start;
4613 stbv_uint32 delta, stream_length, padding;
4614 double offset, bytes_per_sample;
4617 // find the last page and validate the target sample
4618 stream_length = stb_vorbis_stream_length_in_samples(f);
4619 if (stream_length == 0) return stbv_error(f, VORBIS_seek_without_length);
4620 if (sample_number > stream_length) return stbv_error(f, VORBIS_seek_invalid);
4622 // this is the maximum difference between the window-center (which is the
4623 // actual granule position value), and the right-start (which the spec
4624 // indicates should be the granule position (give or take one)).
4625 padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
4626 if (sample_number < padding)
4629 sample_number -= padding;
4632 while (left.last_decoded_sample == ~0U) {
4633 // (untested) the first page does not have a 'last_decoded_sample'
4634 stbv_set_file_offset(f, left.page_end);
4635 if (!stbv_get_seek_page_info(f, &left)) goto error;
4639 assert(right.last_decoded_sample != ~0U);
4641 // starting from the start is handled differently
4642 if (sample_number <= left.last_decoded_sample) {
4643 if (stb_vorbis_seek_start(f))
4648 while (left.page_end != right.page_start) {
4649 assert(left.page_end < right.page_start);
4650 // search range in bytes
4651 delta = right.page_start - left.page_end;
4652 if (delta <= 65536) {
4653 // there's only 64K left to search - handle it linearly
4654 stbv_set_file_offset(f, left.page_end);
4658 // first probe (interpolate)
4659 double data_bytes = right.page_end - left.page_start;
4660 bytes_per_sample = data_bytes / right.last_decoded_sample;
4661 offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample);
4663 // second probe (try to bound the other side)
4664 double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample;
4665 if (error >= 0 && error < 8000) error = 8000;
4666 if (error < 0 && error > -8000) error = -8000;
4667 offset += error * 2;
4670 // ensure the offset is valid
4671 if (offset < left.page_end)
4672 offset = left.page_end;
4673 if (offset > right.page_start - 65536)
4674 offset = right.page_start - 65536;
4676 stbv_set_file_offset(f, (unsigned int) offset);
4678 // binary search for large ranges (offset by 32K to ensure
4679 // we don't hit the right page)
4680 stbv_set_file_offset(f, left.page_end + (delta / 2) - 32768);
4683 if (!stbv_vorbis_find_page(f, NULL, NULL)) goto error;
4687 if (!stbv_get_seek_page_info(f, &mid)) goto error;
4688 if (mid.last_decoded_sample != ~0U) break;
4689 // (untested) no frames end on this page
4690 stbv_set_file_offset(f, mid.page_end);
4691 assert(mid.page_start < right.page_start);
4694 // if we've just found the last page again then we're in a tricky file,
4695 // and we're close enough.
4696 if (mid.page_start == right.page_start)
4699 if (sample_number < mid.last_decoded_sample)
4707 // seek back to start of the last packet
4708 page_start = left.page_start;
4709 stbv_set_file_offset(f, page_start);
4710 if (!stbv_start_page(f)) return stbv_error(f, VORBIS_seek_failed);
4711 end_pos = f->end_seg_with_known_loc;
4712 assert(end_pos >= 0);
4715 for (i = end_pos; i > 0; --i)
4716 if (f->segments[i-1] != 255)
4719 start_seg_with_known_loc = i;
4721 if (start_seg_with_known_loc > 0 || !(f->page_flag & STBV_PAGEFLAG_continued_packet))
4724 // (untested) the final packet begins on an earlier page
4725 if (!stbv_go_to_page_before(f, page_start))
4728 page_start = stb_vorbis_get_file_offset(f);
4729 if (!stbv_start_page(f)) goto error;
4730 end_pos = f->segment_count - 1;
4733 // prepare to start decoding
4734 f->current_loc_valid = FALSE;
4735 f->last_seg = FALSE;
4737 f->packet_bytes = 0;
4738 f->bytes_in_seg = 0;
4739 f->previous_length = 0;
4740 f->next_seg = start_seg_with_known_loc;
4742 for (i = 0; i < start_seg_with_known_loc; i++)
4743 stbv_skip(f, f->segments[i]);
4745 // start decoding (optimizable - this frame is generally discarded)
4746 if (!stbv_vorbis_pump_first_frame(f))
4748 if (f->current_loc > sample_number)
4749 return stbv_error(f, VORBIS_seek_failed);
4753 // try to restore the file to a valid state
4754 stb_vorbis_seek_start(f);
4755 return stbv_error(f, VORBIS_seek_failed);
4758 // the same as stbv_vorbis_decode_initial, but without advancing
4759 static int stbv_peek_decode_initial(stbv_vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
4761 int bits_read, bytes_read;
4763 if (!stbv_vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))
4766 // either 1 or 2 bytes were read, figure out which so we can rewind
4767 bits_read = 1 + stbv_ilog(f->mode_count-1);
4768 if (f->mode_config[*mode].blockflag)
4770 bytes_read = (bits_read + 7) / 8;
4772 f->bytes_in_seg += bytes_read;
4773 f->packet_bytes -= bytes_read;
4774 stbv_skip(f, -bytes_read);
4775 if (f->next_seg == -1)
4776 f->next_seg = f->segment_count - 1;
4784 STBVDEF int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
4786 stbv_uint32 max_frame_samples;
4788 if (STBV_IS_PUSH_MODE(f)) return stbv_error(f, VORBIS_invalid_api_mixing);
4790 // fast page-level search
4791 if (!stbv_seek_to_sample_coarse(f, sample_number))
4794 assert(f->current_loc_valid);
4795 assert(f->current_loc <= sample_number);
4797 // linear search for the relevant packet
4798 max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;
4799 while (f->current_loc < sample_number) {
4800 int left_start, left_end, right_start, right_end, mode, frame_samples;
4801 if (!stbv_peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
4802 return stbv_error(f, VORBIS_seek_failed);
4803 // calculate the number of samples returned by the next frame
4804 frame_samples = right_start - left_start;
4805 if (f->current_loc + frame_samples > sample_number) {
4806 return 1; // the next frame will contain the sample
4807 } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {
4808 // there's a chance the frame after this could contain the sample
4809 stbv_vorbis_pump_first_frame(f);
4811 // this frame is too early to be relevant
4812 f->current_loc += frame_samples;
4813 f->previous_length = 0;
4814 stbv_maybe_start_packet(f);
4815 stbv_flush_packet(f);
4818 // the next frame will start with the sample
4819 assert(f->current_loc == sample_number);
4823 STBVDEF int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
4825 if (!stb_vorbis_seek_frame(f, sample_number))
4828 if (sample_number != f->current_loc) {
4830 stbv_uint32 frame_start = f->current_loc;
4831 stb_vorbis_get_frame_float(f, &n, NULL);
4832 assert(sample_number > frame_start);
4833 assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);
4834 f->channel_buffer_start += (sample_number - frame_start);
4840 STBVDEF int stb_vorbis_seek_start(stb_vorbis *f)
4842 if (STBV_IS_PUSH_MODE(f)) { return stbv_error(f, VORBIS_invalid_api_mixing); }
4843 stbv_set_file_offset(f, f->first_audio_page_offset);
4844 f->previous_length = 0;
4845 f->first_decode = TRUE;
4847 return stbv_vorbis_pump_first_frame(f);
4850 STBVDEF unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
4852 unsigned int restore_offset, previous_safe;
4853 unsigned int end, last_page_loc;
4855 if (STBV_IS_PUSH_MODE(f)) return stbv_error(f, VORBIS_invalid_api_mixing);
4856 if (!f->total_samples) {
4861 // first, store the current decode position so we can restore it
4862 restore_offset = stb_vorbis_get_file_offset(f);
4864 // now we want to seek back 64K from the end (the last page must
4865 // be at most a little less than 64K, but let's allow a little slop)
4866 if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
4867 previous_safe = f->stream_len - 65536;
4869 previous_safe = f->first_audio_page_offset;
4871 stbv_set_file_offset(f, previous_safe);
4872 // previous_safe is now our candidate 'earliest known place that seeking
4873 // to will lead to the final page'
4875 if (!stbv_vorbis_find_page(f, &end, &last)) {
4876 // if we can't find a page, we're hosed!
4877 f->error = VORBIS_cant_find_last_page;
4878 f->total_samples = 0xffffffff;
4882 // check if there are more pages
4883 last_page_loc = stb_vorbis_get_file_offset(f);
4885 // stop when the last_page flag is set, not when we reach eof;
4886 // this allows us to stop short of a 'file_section' end without
4887 // explicitly checking the length of the section
4889 stbv_set_file_offset(f, end);
4890 if (!stbv_vorbis_find_page(f, &end, &last)) {
4891 // the last page we found didn't have the 'last page' flag
4895 previous_safe = last_page_loc+1;
4896 last_page_loc = stb_vorbis_get_file_offset(f);
4899 stbv_set_file_offset(f, last_page_loc);
4902 stbv_getn(f, (unsigned char *)header, 6);
4903 // extract the absolute granule position
4906 if (lo == 0xffffffff && hi == 0xffffffff) {
4907 f->error = VORBIS_cant_find_last_page;
4908 f->total_samples = STBV_SAMPLE_unknown;
4912 lo = 0xfffffffe; // saturate
4913 f->total_samples = lo;
4915 f->p_last.page_start = last_page_loc;
4916 f->p_last.page_end = end;
4917 f->p_last.last_decoded_sample = lo;
4920 stbv_set_file_offset(f, restore_offset);
4922 return f->total_samples == STBV_SAMPLE_unknown ? 0 : f->total_samples;
4925 STBVDEF float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
4927 return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
4932 STBVDEF int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
4934 int len, right,left,i;
4935 if (STBV_IS_PUSH_MODE(f)) return stbv_error(f, VORBIS_invalid_api_mixing);
4937 if (!stbv_vorbis_decode_packet(f, &len, &left, &right)) {
4938 f->channel_buffer_start = f->channel_buffer_end = 0;
4942 len = stbv_vorbis_finish_frame(f, len, left, right);
4943 for (i=0; i < f->channels; ++i)
4944 f->outputs[i] = f->channel_buffers[i] + left;
4946 f->channel_buffer_start = left;
4947 f->channel_buffer_end = left+len;
4949 if (channels) *channels = f->channels;
4950 if (output) *output = f->outputs;
4954 #ifndef STB_VORBIS_NO_STDIO
4956 STBVDEF stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length)
4959 stbv_vorbis_init(&p, alloc);
4961 p.f_start = (stbv_uint32) ftell(file);
4962 p.stream_len = length;
4963 p.close_on_free = close_on_free;
4964 if (stbv_start_decoder(&p)) {
4965 f = stbv_vorbis_alloc(&p);
4968 stbv_vorbis_pump_first_frame(f);
4972 if (error) *error = p.error;
4973 stbv_vorbis_deinit(&p);
4977 STBVDEF stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)
4979 unsigned int len, start;
4980 start = (unsigned int) ftell(file);
4981 fseek(file, 0, SEEK_END);
4982 len = (unsigned int) (ftell(file) - start);
4983 fseek(file, start, SEEK_SET);
4984 return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
4987 STBVDEF stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc)
4989 FILE *f = fopen(filename, "rb");
4991 return stb_vorbis_open_file(f, TRUE, error, alloc);
4992 if (error) *error = VORBIS_file_open_failure;
4995 #endif // STB_VORBIS_NO_STDIO
4997 STBVDEF stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)
5000 if (data == NULL) return NULL;
5001 stbv_vorbis_init(&p, alloc);
5002 p.stream = (stbv_uint8 *) data;
5003 p.stream_end = (stbv_uint8 *) data + len;
5004 p.stream_start = (stbv_uint8 *) p.stream;
5006 p.push_mode = FALSE;
5007 if (stbv_start_decoder(&p)) {
5008 f = stbv_vorbis_alloc(&p);
5011 stbv_vorbis_pump_first_frame(f);
5012 if (error) *error = VORBIS__no_error;
5016 if (error) *error = p.error;
5017 stbv_vorbis_deinit(&p);
5021 #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
5022 #define STBV_PLAYBACK_MONO 1
5023 #define STBV_PLAYBACK_LEFT 2
5024 #define STBV_PLAYBACK_RIGHT 4
5026 #define STBV_L (STBV_PLAYBACK_LEFT | STBV_PLAYBACK_MONO)
5027 #define STBV_C (STBV_PLAYBACK_LEFT | STBV_PLAYBACK_RIGHT | STBV_PLAYBACK_MONO)
5028 #define STBV_R (STBV_PLAYBACK_RIGHT | STBV_PLAYBACK_MONO)
5030 static stbv_int8 stbv_channel_position[7][6] =
5035 { STBV_L, STBV_C, STBV_R },
5036 { STBV_L, STBV_R, STBV_L, STBV_R },
5037 { STBV_L, STBV_C, STBV_R, STBV_L, STBV_R },
5038 { STBV_L, STBV_C, STBV_R, STBV_L, STBV_R, STBV_C },
5042 #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
5047 typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
5048 #define STBV_FASTDEF(x) stbv_float_conv x
5049 // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
5050 #define STBV_MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
5051 #define STBV_ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
5052 #define STBV_FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + STBV_MAGIC(s), temp.i - STBV_ADDEND(s))
5053 #define stbv_check_endianness()
5055 #define STBV_FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
5056 #define stbv_check_endianness()
5057 #define STBV_FASTDEF(x)
5060 static void stbv_copy_samples(short *dest, float *src, int len)
5063 stbv_check_endianness();
5064 for (i=0; i < len; ++i) {
5066 int v = STBV_FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
5067 if ((unsigned int) (v + 32768) > 65535)
5068 v = v < 0 ? -32768 : 32767;
5073 static void stbv_compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
5075 #define BUFFER_SIZE 32
5076 float buffer[BUFFER_SIZE];
5077 int i,j,o,n = BUFFER_SIZE;
5078 stbv_check_endianness();
5079 for (o = 0; o < len; o += BUFFER_SIZE) {
5080 memset(buffer, 0, sizeof(buffer));
5081 if (o + n > len) n = len - o;
5082 for (j=0; j < num_c; ++j) {
5083 if (stbv_channel_position[num_c][j] & mask) {
5084 for (i=0; i < n; ++i)
5085 buffer[i] += data[j][d_offset+o+i];
5088 for (i=0; i < n; ++i) {
5090 int v = STBV_FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
5091 if ((unsigned int) (v + 32768) > 65535)
5092 v = v < 0 ? -32768 : 32767;
5098 static void stbv_compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
5100 #define BUFFER_SIZE 32
5101 float buffer[BUFFER_SIZE];
5102 int i,j,o,n = BUFFER_SIZE >> 1;
5103 // o is the offset in the source data
5104 stbv_check_endianness();
5105 for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
5106 // o2 is the offset in the output data
5108 memset(buffer, 0, sizeof(buffer));
5109 if (o + n > len) n = len - o;
5110 for (j=0; j < num_c; ++j) {
5111 int m = stbv_channel_position[num_c][j] & (STBV_PLAYBACK_LEFT | STBV_PLAYBACK_RIGHT);
5112 if (m == (STBV_PLAYBACK_LEFT | STBV_PLAYBACK_RIGHT)) {
5113 for (i=0; i < n; ++i) {
5114 buffer[i*2+0] += data[j][d_offset+o+i];
5115 buffer[i*2+1] += data[j][d_offset+o+i];
5117 } else if (m == STBV_PLAYBACK_LEFT) {
5118 for (i=0; i < n; ++i) {
5119 buffer[i*2+0] += data[j][d_offset+o+i];
5121 } else if (m == STBV_PLAYBACK_RIGHT) {
5122 for (i=0; i < n; ++i) {
5123 buffer[i*2+1] += data[j][d_offset+o+i];
5127 for (i=0; i < (n<<1); ++i) {
5129 int v = STBV_FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
5130 if ((unsigned int) (v + 32768) > 65535)
5131 v = v < 0 ? -32768 : 32767;
5137 static void stbv_convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
5140 if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
5141 static int channel_selector[3][2] = { {0}, {STBV_PLAYBACK_MONO}, {STBV_PLAYBACK_LEFT, STBV_PLAYBACK_RIGHT} };
5142 for (i=0; i < buf_c; ++i)
5143 stbv_compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
5145 int limit = buf_c < data_c ? buf_c : data_c;
5146 for (i=0; i < limit; ++i)
5147 stbv_copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
5148 for ( ; i < buf_c; ++i)
5149 memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
5153 STBVDEF int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
5156 int len = stb_vorbis_get_frame_float(f, NULL, &output);
5157 if (len > num_samples) len = num_samples;
5159 stbv_convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
5163 static void stbv_convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
5166 stbv_check_endianness();
5167 if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
5169 for (i=0; i < buf_c; ++i)
5170 stbv_compute_stereo_samples(buffer, data_c, data, d_offset, len);
5172 int limit = buf_c < data_c ? buf_c : data_c;
5174 for (j=0; j < len; ++j) {
5175 for (i=0; i < limit; ++i) {
5177 float f = data[i][d_offset+j];
5178 int v = STBV_FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
5179 if ((unsigned int) (v + 32768) > 65535)
5180 v = v < 0 ? -32768 : 32767;
5183 for ( ; i < buf_c; ++i)
5189 STBVDEF int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
5193 if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
5194 len = stb_vorbis_get_frame_float(f, NULL, &output);
5196 if (len*num_c > num_shorts) len = num_shorts / num_c;
5197 stbv_convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
5202 STBVDEF int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
5205 int len = num_shorts / channels;
5207 int z = f->channels;
5208 if (z > channels) z = channels;
5210 int k = f->channel_buffer_end - f->channel_buffer_start;
5211 if (n+k >= len) k = len - n;
5213 stbv_convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
5214 buffer += k*channels;
5216 f->channel_buffer_start += k;
5217 if (n == len) break;
5218 if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
5223 STBVDEF int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
5227 int z = f->channels;
5228 if (z > channels) z = channels;
5230 int k = f->channel_buffer_end - f->channel_buffer_start;
5231 if (n+k >= len) k = len - n;
5233 stbv_convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
5235 f->channel_buffer_start += k;
5236 if (n == len) break;
5237 if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
5242 #ifndef STB_VORBIS_NO_STDIO
5243 STBVDEF int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)
5245 int data_len, offset, total, limit, error;
5247 stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
5248 if (v == NULL) return -1;
5249 limit = v->channels * 4096;
5250 *channels = v->channels;
5252 *sample_rate = v->sample_rate;
5253 offset = data_len = 0;
5255 data = (short *) malloc(total * sizeof(*data));
5257 stb_vorbis_close(v);
5261 int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
5264 offset += n * v->channels;
5265 if (offset + limit > total) {
5268 data2 = (short *) realloc(data, total * sizeof(*data));
5269 if (data2 == NULL) {
5271 stb_vorbis_close(v);
5278 stb_vorbis_close(v);
5283 STBVDEF int stb_vorbis_decode_memory(const stbv_uint8 *mem, int len, int *channels, int *sample_rate, short **output)
5285 int data_len, offset, total, limit, error;
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;
5292 *sample_rate = v->sample_rate;
5293 offset = data_len = 0;
5295 data = (short *) malloc(total * sizeof(*data));
5297 stb_vorbis_close(v);
5301 int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
5304 offset += n * v->channels;
5305 if (offset + limit > total) {
5308 data2 = (short *) realloc(data, total * sizeof(*data));
5309 if (data2 == NULL) {
5311 stb_vorbis_close(v);
5318 stb_vorbis_close(v);
5321 #endif // STB_VORBIS_NO_INTEGER_CONVERSION
5323 STBVDEF int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
5326 int len = num_floats / channels;
5328 int z = f->channels;
5329 if (z > channels) z = channels;
5332 int k = f->channel_buffer_end - f->channel_buffer_start;
5333 if (n+k >= len) k = len - n;
5334 for (j=0; j < k; ++j) {
5335 for (i=0; i < z; ++i)
5336 *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
5337 for ( ; i < channels; ++i)
5341 f->channel_buffer_start += k;
5344 if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
5350 STBVDEF int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
5354 int z = f->channels;
5355 if (z > channels) z = channels;
5356 while (n < num_samples) {
5358 int k = f->channel_buffer_end - f->channel_buffer_start;
5359 if (n+k >= num_samples) k = num_samples - n;
5361 for (i=0; i < z; ++i)
5362 memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);
5363 for ( ; i < channels; ++i)
5364 memset(buffer[i]+n, 0, sizeof(float) * k);
5367 f->channel_buffer_start += k;
5368 if (n == num_samples)
5370 if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
5375 #endif // STB_VORBIS_NO_PULLDATA_API
5378 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files
5379 1.11 - 2017-07-23 - fix MinGW compilation
5380 1.10 - 2017-03-03 - more robust seeking; fix negative stbv_ilog(); clear error in open_memory
5381 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version
5382 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks;
5383 avoid discarding last frame of audio data
5384 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API
5385 some more crash fixes when out of memory or with corrupt files
5386 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)
5387 some crash fixes when out of memory or with corrupt files
5388 1.05 - 2015-04-19 - don't define __forceinline if it's redundant
5389 1.04 - 2014-08-27 - fix missing const-correct case in API
5390 1.03 - 2014-08-07 - Warning fixes
5391 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows
5392 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float
5393 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel
5394 (API change) report sample rate for decode-full-file funcs
5395 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
5396 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
5397 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
5398 0.99993 - remove assert that fired on legal files with empty tables
5399 0.99992 - rewind-to-start
5400 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
5401 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
5402 0.9998 - add a full-decode function with a memory source
5403 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
5404 0.9996 - query length of vorbis stream in samples/seconds
5405 0.9995 - bugfix to another optimization that only happened in certain files
5406 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
5407 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
5408 0.9992 - performance improvement of IMDCT; now performs close to reference implementation
5409 0.9991 - performance improvement of IMDCT
5410 0.999 - (should have been 0.9990) performance improvement of IMDCT
5411 0.998 - no-CRT support from Casey Muratori
5412 0.997 - bugfixes for bugs found by Terje Mathisen
5413 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
5414 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
5415 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
5416 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
5417 0.992 - fixes for MinGW warning
5418 0.991 - turn fast-float-conversion on by default
5419 0.990 - fix push-mode seek recovery if you seek into the headers
5420 0.98b - fix to bad release of 0.98
5421 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
5422 0.97 - builds under c++ (typecasting, don't use 'class' keyword)
5423 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
5424 0.95 - clamping code for 16-bit functions
5425 0.94 - not publically released
5426 0.93 - fixed all-zero-floor case (was decoding garbage)
5427 0.92 - fixed a memory leak
5428 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
5429 0.90 - first public release
5432 #endif // STB_VORBIS_IMPLEMENTATION
5436 ------------------------------------------------------------------------------
5437 This software is available under 2 licenses -- choose whichever you prefer.
5438 ------------------------------------------------------------------------------
5439 ALTERNATIVE A - MIT License
5440 Copyright (c) 2017 Sean Barrett
5441 Permission is hereby granted, free of charge, to any person obtaining a copy of
5442 this software and associated documentation files (the "Software"), to deal in
5443 the Software without restriction, including without limitation the rights to
5444 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
5445 of the Software, and to permit persons to whom the Software is furnished to do
5446 so, subject to the following conditions:
5447 The above copyright notice and this permission notice shall be included in all
5448 copies or substantial portions of the Software.
5449 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5450 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
5451 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
5452 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
5453 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
5454 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
5456 ------------------------------------------------------------------------------
5457 ALTERNATIVE B - Public Domain (www.unlicense.org)
5458 This is free and unencumbered software released into the public domain.
5459 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
5460 software, either in source code form or as a compiled binary, for any purpose,
5461 commercial or non-commercial, and by any means.
5462 In jurisdictions that recognize copyright laws, the author or authors of this
5463 software dedicate any and all copyright interest in the software to the public
5464 domain. We make this dedication for the benefit of the public at large and to
5465 the detriment of our heirs and successors. We intend this dedication to be an
5466 overt act of relinquishment in perpetuity of all present and future rights to
5467 this software under copyright law.
5468 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5469 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
5470 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
5471 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
5472 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
5473 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
5474 ------------------------------------------------------------------------------