Merge branch 'working'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sean Barrett · committed by Sean Barrett · parents 33c9010, f026837 · Browse files · 4 files·+5535 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+5535 added−21 removed
- other:+5535 added−21 removed
Provenance
- Commit
39522da- Tree
461f4cd- Author
Sean Barrett <sean2@nothings.org>- Committer
Sean Barrett <sean2@nothings.org>- Parent 1
33c9010- Parent 2
f026837
4 files changed+5535 added−21 removed
modified:stb_leakcheck.h+2 added
13 unmodified lines14 #undef free15 #undef realloc16 #endif17 18+#include <assert.h>19+#include <string.h>20 #include <stdlib.h>21 #include <stdio.h>22 #include <stddef.h>23 typedef struct malloc_info stb_leakcheck_malloc_info;101 unmodified linesmodified:stb_tilemap_editor.h+6 added
324 unmodified lines325 326 #ifndef STB_TILEMAP_INCLUDE_STB_TILEMAP_EDITOR_H327 #define STB_TILEMAP_INCLUDE_STB_TILEMAP_EDITOR_H328 329+#ifdef _WIN32330+ #define _CRT_SECURE_NO_WARNINGS331+ #include <stdlib.h>332+ #include <stdio.h>333+#endif334+335 typedef struct stbte_tilemap stbte_tilemap;336 337 // these are the drawmodes used in STBTE_DRAW_TILE338 enum3788 unmodified linesadded:stb_vorbis.h+5463 added
1+// Ogg Vorbis audio decoder - v1.05 - public domain2+// http://nothings.org/stb_vorbis/3+//4+// Written by Sean Barrett in 2007, last updated in 20145+// Sponsored by RAD Game Tools.6+//7+// Placed in the public domain April 2007 by the author: no copyright8+// is claimed, and you may use it for any purpose you like.9+//10+// No warranty for any purpose is expressed or implied by the author (nor11+// by RAD Game Tools). Report bugs and send enhancements to the author.12+//13+// Limitations:14+//15+// - seeking not supported except manually via PUSHDATA api16+// - floor 0 not supported (used in old ogg vorbis files pre-2004)17+// - lossless sample-truncation at beginning ignored18+// - cannot concatenate multiple vorbis streams19+// - sample positions are 32-bit, limiting seekable 192Khz20+// files to around 6 hours (Ogg supports 64-bit)21+//22+// Bugfix/warning contributors:23+// Terje Mathisen Niklas Frykholm Andy Hill24+// Casey Muratori John Bolton Gargaj25+// Laurent Gomila Marc LeBlanc Ronny Chevalier26+// Bernhard Wodo Evan Balster "alxprd"@github27+// Tom Beaumont Ingo Leitgeb Nicolas Guillemot28+// (If you reported a bug but do not appear in this list, it is because29+// someone else reported the bug before you. There were too many of you to30+// list them all because I was lax about updating for a long time, sorry.)31+//32+// Partial history:33+// 1.05 - 2015/04/19 - don't define __forceinline if it's redundant34+// 1.04 - 2014/08/27 - fix missing const-correct case in API35+// 1.03 - 2014/08/07 - warning fixes36+// 1.02 - 2014/07/09 - declare qsort comparison as explicitly _cdecl in Windows37+// 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float (interleaved was correct)38+// 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in >2-channel;39+// (API change) report sample rate for decode-full-file funcs40+// 0.99996 - - bracket #include <malloc.h> for macintosh compilation41+// 0.99995 - - avoid alias-optimization issue in float-to-int conversion42+//43+// See end of file for full version history.44+45+46+//////////////////////////////////////////////////////////////////////////////47+//48+// HEADER BEGINS HERE49+//50+51+#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H52+#define STB_VORBIS_INCLUDE_STB_VORBIS_H53+54+#ifdef _WIN3255+ #define _CRT_SECURE_NO_WARNINGS56+#endif57+58+#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)59+#define STB_VORBIS_NO_STDIO 160+#endif61+62+#ifndef STB_VORBIS_NO_STDIO63+#include <stdio.h>64+#endif65+66+#ifdef __cplusplus67+extern "C" {68+#endif69+70+/////////// THREAD SAFETY71+72+// Individual stb_vorbis* handles are not thread-safe; you cannot decode from73+// them from multiple threads at the same time. However, you can have multiple74+// stb_vorbis* handles and decode from them independently in multiple thrads.75+76+77+/////////// MEMORY ALLOCATION78+79+// normally stb_vorbis uses malloc() to allocate memory at startup,80+// and alloca() to allocate temporary memory during a frame on the81+// stack. (Memory consumption will depend on the amount of setup82+// data in the file and how you set the compile flags for speed83+// vs. size. In my test files the maximal-size usage is ~150KB.)84+//85+// You can modify the wrapper functions in the source (setup_malloc,86+// setup_temp_malloc, temp_malloc) to change this behavior, or you87+// can use a simpler allocation model: you pass in a buffer from88+// which stb_vorbis will allocate _all_ its memory (including the89+// temp memory). "open" may fail with a VORBIS_outofmem if you90+// do not pass in enough data; there is no way to determine how91+// much you do need except to succeed (at which point you can92+// query get_info to find the exact amount required. yes I know93+// this is lame).94+//95+// If you pass in a non-NULL buffer of the type below, allocation96+// will occur from it as described above. Otherwise just pass NULL97+// to use malloc()/alloca()98+99+typedef struct100+{101+ char *alloc_buffer;102+ int alloc_buffer_length_in_bytes;103+} stb_vorbis_alloc;104+105+106+/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES107+108+typedef struct stb_vorbis stb_vorbis;109+110+typedef struct111+{112+ unsigned int sample_rate;113+ int channels;114+115+ unsigned int setup_memory_required;116+ unsigned int setup_temp_memory_required;117+ unsigned int temp_memory_required;118+119+ int max_frame_size;120+} stb_vorbis_info;121+122+// get general information about the file123+extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);124+125+// get the last error detected (clears it, too)126+extern int stb_vorbis_get_error(stb_vorbis *f);127+128+// close an ogg vorbis file and free all memory in use129+extern void stb_vorbis_close(stb_vorbis *f);130+131+// this function returns the offset (in samples) from the beginning of the132+// file that will be returned by the next decode, if it is known, or -1133+// otherwise. after a flush_pushdata() call, this may take a while before134+// it becomes valid again.135+// NOT WORKING YET after a seek with PULLDATA API136+extern int stb_vorbis_get_sample_offset(stb_vorbis *f);137+138+// returns the current seek point within the file, or offset from the beginning139+// of the memory buffer. In pushdata mode it returns 0.140+extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);141+142+/////////// PUSHDATA API143+144+#ifndef STB_VORBIS_NO_PUSHDATA_API145+146+// this API allows you to get blocks of data from any source and hand147+// them to stb_vorbis. you have to buffer them; stb_vorbis will tell148+// you how much it used, and you have to give it the rest next time;149+// and stb_vorbis may not have enough data to work with and you will150+// need to give it the same data again PLUS more. Note that the Vorbis151+// specification does not bound the size of an individual frame.152+153+extern stb_vorbis *stb_vorbis_open_pushdata(154+ unsigned char *datablock, int datablock_length_in_bytes,155+ int *datablock_memory_consumed_in_bytes,156+ int *error,157+ stb_vorbis_alloc *alloc_buffer);158+// create a vorbis decoder by passing in the initial data block containing159+// the ogg&vorbis headers (you don't need to do parse them, just provide160+// the first N bytes of the file--you're told if it's not enough, see below)161+// on success, returns an stb_vorbis *, does not set error, returns the amount of162+// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;163+// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed164+// if returns NULL and *error is VORBIS_need_more_data, then the input block was165+// incomplete and you need to pass in a larger block from the start of the file166+167+extern int stb_vorbis_decode_frame_pushdata(168+ stb_vorbis *f, unsigned char *datablock, int datablock_length_in_bytes,169+ int *channels, // place to write number of float * buffers170+ float ***output, // place to write float ** array of float * buffers171+ int *samples // place to write number of output samples172+ );173+// decode a frame of audio sample data if possible from the passed-in data block174+//175+// return value: number of bytes we used from datablock176+//177+// possible cases:178+// 0 bytes used, 0 samples output (need more data)179+// N bytes used, 0 samples output (resynching the stream, keep going)180+// N bytes used, M samples output (one frame of data)181+// note that after opening a file, you will ALWAYS get one N-bytes,0-sample182+// frame, because Vorbis always "discards" the first frame.183+//184+// Note that on resynch, stb_vorbis will rarely consume all of the buffer,185+// instead only datablock_length_in_bytes-3 or less. This is because it wants186+// to avoid missing parts of a page header if they cross a datablock boundary,187+// without writing state-machiney code to record a partial detection.188+//189+// The number of channels returned are stored in *channels (which can be190+// NULL--it is always the same as the number of channels reported by191+// get_info). *output will contain an array of float* buffers, one per192+// channel. In other words, (*output)[0][0] contains the first sample from193+// the first channel, and (*output)[1][0] contains the first sample from194+// the second channel.195+196+extern void stb_vorbis_flush_pushdata(stb_vorbis *f);197+// inform stb_vorbis that your next datablock will not be contiguous with198+// previous ones (e.g. you've seeked in the data); future attempts to decode199+// frames will cause stb_vorbis to resynchronize (as noted above), and200+// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it201+// will begin decoding the _next_ frame.202+//203+// if you want to seek using pushdata, you need to seek in your file, then204+// call stb_vorbis_flush_pushdata(), then start calling decoding, then once205+// decoding is returning you data, call stb_vorbis_get_sample_offset, and206+// if you don't like the result, seek your file again and repeat.207+#endif208+209+210+////////// PULLING INPUT API211+212+#ifndef STB_VORBIS_NO_PULLDATA_API213+// This API assumes stb_vorbis is allowed to pull data from a source--214+// either a block of memory containing the _entire_ vorbis stream, or a215+// FILE * that you or it create, or possibly some other reading mechanism216+// if you go modify the source to replace the FILE * case with some kind217+// of callback to your code. (But if you don't support seeking, you may218+// just want to go ahead and use pushdata.)219+220+#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)221+extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);222+#endif223+#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)224+extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);225+#endif226+// decode an entire file and output the data interleaved into a malloc()ed227+// buffer stored in *output. The return value is the number of samples228+// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.229+// When you're done with it, just free() the pointer returned in *output.230+231+extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,232+ int *error, stb_vorbis_alloc *alloc_buffer);233+// create an ogg vorbis decoder from an ogg vorbis stream in memory (note234+// this must be the entire stream!). on failure, returns NULL and sets *error235+236+#ifndef STB_VORBIS_NO_STDIO237+extern stb_vorbis * stb_vorbis_open_filename(const char *filename,238+ int *error, stb_vorbis_alloc *alloc_buffer);239+// create an ogg vorbis decoder from a filename via fopen(). on failure,240+// returns NULL and sets *error (possibly to VORBIS_file_open_failure).241+242+extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,243+ int *error, stb_vorbis_alloc *alloc_buffer);244+// create an ogg vorbis decoder from an open FILE *, looking for a stream at245+// the _current_ seek point (ftell). on failure, returns NULL and sets *error.246+// note that stb_vorbis must "own" this stream; if you seek it in between247+// calls to stb_vorbis, it will become confused. Morever, if you attempt to248+// perform stb_vorbis_seek_*() operations on this file, it will assume it249+// owns the _entire_ rest of the file after the start point. Use the next250+// function, stb_vorbis_open_file_section(), to limit it.251+252+extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,253+ int *error, stb_vorbis_alloc *alloc_buffer, unsigned int len);254+// create an ogg vorbis decoder from an open FILE *, looking for a stream at255+// the _current_ seek point (ftell); the stream will be of length 'len' bytes.256+// on failure, returns NULL and sets *error. note that stb_vorbis must "own"257+// this stream; if you seek it in between calls to stb_vorbis, it will become258+// confused.259+#endif260+261+extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);262+extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);263+// NOT WORKING YET264+// these functions seek in the Vorbis file to (approximately) 'sample_number'.265+// after calling seek_frame(), the next call to get_frame_*() will include266+// the specified sample. after calling stb_vorbis_seek(), the next call to267+// stb_vorbis_get_samples_* will start with the specified sample. If you268+// do not need to seek to EXACTLY the target sample when using get_samples_*,269+// you can also use seek_frame().270+271+extern void stb_vorbis_seek_start(stb_vorbis *f);272+// this function is equivalent to stb_vorbis_seek(f,0), but it273+// actually works274+275+extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);276+extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);277+// these functions return the total length of the vorbis stream278+279+extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);280+// decode the next frame and return the number of samples. the number of281+// channels returned are stored in *channels (which can be NULL--it is always282+// the same as the number of channels reported by get_info). *output will283+// contain an array of float* buffers, one per channel. These outputs will284+// be overwritten on the next call to stb_vorbis_get_frame_*.285+//286+// You generally should not intermix calls to stb_vorbis_get_frame_*()287+// and stb_vorbis_get_samples_*(), since the latter calls the former.288+289+#ifndef STB_VORBIS_NO_INTEGER_CONVERSION290+extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);291+extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);292+#endif293+// decode the next frame and return the number of samples per channel. the294+// data is coerced to the number of channels you request according to the295+// channel coercion rules (see below). You must pass in the size of your296+// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.297+// The maximum buffer size needed can be gotten from get_info(); however,298+// the Vorbis I specification implies an absolute maximum of 4096 samples299+// per channel. Note that for interleaved data, you pass in the number of300+// shorts (the size of your array), but the return value is the number of301+// samples per channel, not the total number of samples.302+303+// Channel coercion rules:304+// Let M be the number of channels requested, and N the number of channels present,305+// and Cn be the nth channel; let stereo L be the sum of all L and center channels,306+// and stereo R be the sum of all R and center channels (channel assignment from the307+// vorbis spec).308+// M N output309+// 1 k sum(Ck) for all k310+// 2 * stereo L, stereo R311+// k l k > l, the first l channels, then 0s312+// k l k <= l, the first k channels313+// Note that this is not _good_ surround etc. mixing at all! It's just so314+// you get something useful.315+316+extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);317+extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);318+// gets num_samples samples, not necessarily on a frame boundary--this requires319+// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.320+// Returns the number of samples stored per channel; it may be less than requested321+// at the end of the file. If there are no more samples in the file, returns 0.322+323+#ifndef STB_VORBIS_NO_INTEGER_CONVERSION324+extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);325+extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);326+#endif327+// gets num_samples samples, not necessarily on a frame boundary--this requires328+// buffering so you have to supply the buffers. Applies the coercion rules above329+// to produce 'channels' channels. Returns the number of samples stored per channel;330+// it may be less than requested at the end of the file. If there are no more331+// samples in the file, returns 0.332+333+#endif334+335+//////// ERROR CODES336+337+enum STBVorbisError338+{339+ VORBIS__no_error,340+341+ VORBIS_need_more_data=1, // not a real error342+343+ VORBIS_invalid_api_mixing, // can't mix API modes344+ VORBIS_outofmem, // not enough memory345+ VORBIS_feature_not_supported, // uses floor 0346+ VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small347+ VORBIS_file_open_failure, // fopen() failed348+ VORBIS_seek_without_length, // can't seek in unknown-length file349+350+ VORBIS_unexpected_eof=10, // file is truncated?351+ VORBIS_seek_invalid, // seek past EOF352+353+ // decoding errors (corrupt/invalid stream) -- you probably354+ // don't care about the exact details of these355+356+ // vorbis errors:357+ VORBIS_invalid_setup=20,358+ VORBIS_invalid_stream,359+360+ // ogg errors:361+ VORBIS_missing_capture_pattern=30,362+ VORBIS_invalid_stream_structure_version,363+ VORBIS_continued_packet_flag_invalid,364+ VORBIS_incorrect_stream_serial_number,365+ VORBIS_invalid_first_page,366+ VORBIS_bad_packet_type,367+ VORBIS_cant_find_last_page,368+ VORBIS_seek_failed,369+};370+371+372+#ifdef __cplusplus373+}374+#endif375+376+#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H377+//378+// HEADER ENDS HERE379+//380+//////////////////////////////////////////////////////////////////////////////381+382+#ifndef STB_VORBIS_HEADER_ONLY383+384+// global configuration settings (e.g. set these in the project/makefile),385+// or just set them in this file at the top (although ideally the first few386+// should be visible when the header file is compiled too, although it's not387+// crucial)388+389+// STB_VORBIS_NO_PUSHDATA_API390+// does not compile the code for the various stb_vorbis_*_pushdata()391+// functions392+// #define STB_VORBIS_NO_PUSHDATA_API393+394+// STB_VORBIS_NO_PULLDATA_API395+// does not compile the code for the non-pushdata APIs396+// #define STB_VORBIS_NO_PULLDATA_API397+398+// STB_VORBIS_NO_STDIO399+// does not compile the code for the APIs that use FILE *s internally400+// or externally (implied by STB_VORBIS_NO_PULLDATA_API)401+// #define STB_VORBIS_NO_STDIO402+403+// STB_VORBIS_NO_INTEGER_CONVERSION404+// does not compile the code for converting audio sample data from405+// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)406+// #define STB_VORBIS_NO_INTEGER_CONVERSION407+408+// STB_VORBIS_NO_FAST_SCALED_FLOAT409+// does not use a fast float-to-int trick to accelerate float-to-int on410+// most platforms which requires endianness be defined correctly.411+//#define STB_VORBIS_NO_FAST_SCALED_FLOAT412+413+414+// STB_VORBIS_MAX_CHANNELS [number]415+// globally define this to the maximum number of channels you need.416+// The spec does not put a restriction on channels except that417+// the count is stored in a byte, so 255 is the hard limit.418+// Reducing this saves about 16 bytes per value, so using 16 saves419+// (255-16)*16 or around 4KB. Plus anything other memory usage420+// I forgot to account for. Can probably go as low as 8 (7.1 audio),421+// 6 (5.1 audio), or 2 (stereo only).422+#ifndef STB_VORBIS_MAX_CHANNELS423+#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?424+#endif425+426+// STB_VORBIS_PUSHDATA_CRC_COUNT [number]427+// after a flush_pushdata(), stb_vorbis begins scanning for the428+// next valid page, without backtracking. when it finds something429+// that looks like a page, it streams through it and verifies its430+// CRC32. Should that validation fail, it keeps scanning. But it's431+// possible that _while_ streaming through to check the CRC32 of432+// one candidate page, it sees another candidate page. This #define433+// determines how many "overlapping" candidate pages it can search434+// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas435+// garbage pages could be as big as 64KB, but probably average ~16KB.436+// So don't hose ourselves by scanning an apparent 64KB page and437+// missing a ton of real ones in the interim; so minimum of 2438+#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT439+#define STB_VORBIS_PUSHDATA_CRC_COUNT 4440+#endif441+442+// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]443+// sets the log size of the huffman-acceleration table. Maximum444+// supported value is 24. with larger numbers, more decodings are O(1),445+// but the table size is larger so worse cache missing, so you'll have446+// to probe (and try multiple ogg vorbis files) to find the sweet spot.447+#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH448+#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10449+#endif450+451+// STB_VORBIS_FAST_BINARY_LENGTH [number]452+// sets the log size of the binary-search acceleration table. this453+// is used in similar fashion to the fast-huffman size to set initial454+// parameters for the binary search455+456+// STB_VORBIS_FAST_HUFFMAN_INT457+// The fast huffman tables are much more efficient if they can be458+// stored as 16-bit results instead of 32-bit results. This restricts459+// the codebooks to having only 65535 possible outcomes, though.460+// (At least, accelerated by the huffman table.)461+#ifndef STB_VORBIS_FAST_HUFFMAN_INT462+#define STB_VORBIS_FAST_HUFFMAN_SHORT463+#endif464+465+// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH466+// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls467+// back on binary searching for the correct one. This requires storing468+// extra tables with the huffman codes in sorted order. Defining this469+// symbol trades off space for speed by forcing a linear search in the470+// non-fast case, except for "sparse" codebooks.471+// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH472+473+// STB_VORBIS_DIVIDES_IN_RESIDUE474+// stb_vorbis precomputes the result of the scalar residue decoding475+// that would otherwise require a divide per chunk. you can trade off476+// space for time by defining this symbol.477+// #define STB_VORBIS_DIVIDES_IN_RESIDUE478+479+// STB_VORBIS_DIVIDES_IN_CODEBOOK480+// vorbis VQ codebooks can be encoded two ways: with every case explicitly481+// stored, or with all elements being chosen from a small range of values,482+// and all values possible in all elements. By default, stb_vorbis expands483+// this latter kind out to look like the former kind for ease of decoding,484+// because otherwise an integer divide-per-vector-element is required to485+// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can486+// trade off storage for speed.487+//#define STB_VORBIS_DIVIDES_IN_CODEBOOK488+489+// STB_VORBIS_CODEBOOK_SHORTS490+// The vorbis file format encodes VQ codebook floats as ax+b where a and491+// b are floating point per-codebook constants, and x is a 16-bit int.492+// Normally, stb_vorbis decodes them to floats rather than leaving them493+// as 16-bit ints and computing ax+b while decoding. This is a speed/space494+// tradeoff; you can save space by defining this flag.495+#ifndef STB_VORBIS_CODEBOOK_SHORTS496+#define STB_VORBIS_CODEBOOK_FLOATS497+#endif498+499+// STB_VORBIS_DIVIDE_TABLE500+// this replaces small integer divides in the floor decode loop with501+// table lookups. made less than 1% difference, so disabled by default.502+503+// STB_VORBIS_NO_INLINE_DECODE504+// disables the inlining of the scalar codebook fast-huffman decode.505+// might save a little codespace; useful for debugging506+// #define STB_VORBIS_NO_INLINE_DECODE507+508+// STB_VORBIS_NO_DEFER_FLOOR509+// Normally we only decode the floor without synthesizing the actual510+// full curve. We can instead synthesize the curve immediately. This511+// requires more memory and is very likely slower, so I don't think512+// you'd ever want to do it except for debugging.513+// #define STB_VORBIS_NO_DEFER_FLOOR514+515+516+517+518+//////////////////////////////////////////////////////////////////////////////519+520+#ifdef STB_VORBIS_NO_PULLDATA_API521+ #define STB_VORBIS_NO_INTEGER_CONVERSION522+ #define STB_VORBIS_NO_STDIO523+#endif524+525+#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)526+ #define STB_VORBIS_NO_STDIO 1527+#endif528+529+#ifndef STB_VORBIS_NO_INTEGER_CONVERSION530+#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT531+532+ // only need endianness for fast-float-to-int, which we don't533+ // use for pushdata534+535+ #ifndef STB_VORBIS_BIG_ENDIAN536+ #define STB_VORBIS_ENDIAN 0537+ #else538+ #define STB_VORBIS_ENDIAN 1539+ #endif540+541+#endif542+#endif543+544+545+#ifndef STB_VORBIS_NO_STDIO546+#include <stdio.h>547+#endif548+549+#ifndef STB_VORBIS_NO_CRT550+#include <stdlib.h>551+#include <string.h>552+#include <assert.h>553+#include <math.h>554+#if !(defined(__APPLE__) || defined(MACOSX) || defined(macintosh) || defined(Macintosh))555+#include <malloc.h>556+#endif557+#else558+#define NULL 0559+#endif560+561+#if !defined(_MSC_VER) && !(defined(__MINGW32__) && defined(__forceinline))562+ #if __GNUC__563+ #define __forceinline inline564+ #else565+ #define __forceinline566+ #endif567+#endif568+569+#if STB_VORBIS_MAX_CHANNELS > 256570+#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"571+#endif572+573+#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24574+#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"575+#endif576+577+578+#define MAX_BLOCKSIZE_LOG 13 // from specification579+#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)580+581+582+typedef unsigned char uint8;583+typedef signed char int8;584+typedef unsigned short uint16;585+typedef signed short int16;586+typedef unsigned int uint32;587+typedef signed int int32;588+589+#ifndef TRUE590+#define TRUE 1591+#define FALSE 0592+#endif593+594+#ifdef STB_VORBIS_CODEBOOK_FLOATS595+typedef float codetype;596+#else597+typedef uint16 codetype;598+#endif599+600+// @NOTE601+//602+// Some arrays below are tagged "//varies", which means it's actually603+// a variable-sized piece of data, but rather than malloc I assume it's604+// small enough it's better to just allocate it all together with the605+// main thing606+//607+// Most of the variables are specified with the smallest size I could pack608+// them into. It might give better performance to make them all full-sized609+// integers. It should be safe to freely rearrange the structures or change610+// the sizes larger--nothing relies on silently truncating etc., nor the611+// order of variables.612+613+#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)614+#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)615+616+typedef struct617+{618+ int dimensions, entries;619+ uint8 *codeword_lengths;620+ float minimum_value;621+ float delta_value;622+ uint8 value_bits;623+ uint8 lookup_type;624+ uint8 sequence_p;625+ uint8 sparse;626+ uint32 lookup_values;627+ codetype *multiplicands;628+ uint32 *codewords;629+ #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT630+ int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];631+ #else632+ int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];633+ #endif634+ uint32 *sorted_codewords;635+ int *sorted_values;636+ int sorted_entries;637+} Codebook;638+639+typedef struct640+{641+ uint8 order;642+ uint16 rate;643+ uint16 bark_map_size;644+ uint8 amplitude_bits;645+ uint8 amplitude_offset;646+ uint8 number_of_books;647+ uint8 book_list[16]; // varies648+} Floor0;649+650+typedef struct651+{652+ uint8 partitions;653+ uint8 partition_class_list[32]; // varies654+ uint8 class_dimensions[16]; // varies655+ uint8 class_subclasses[16]; // varies656+ uint8 class_masterbooks[16]; // varies657+ int16 subclass_books[16][8]; // varies658+ uint16 Xlist[31*8+2]; // varies659+ uint8 sorted_order[31*8+2];660+ uint8 neighbors[31*8+2][2];661+ uint8 floor1_multiplier;662+ uint8 rangebits;663+ int values;664+} Floor1;665+666+typedef union667+{668+ Floor0 floor0;669+ Floor1 floor1;670+} Floor;671+672+typedef struct673+{674+ uint32 begin, end;675+ uint32 part_size;676+ uint8 classifications;677+ uint8 classbook;678+ uint8 **classdata;679+ int16 (*residue_books)[8];680+} Residue;681+682+typedef struct683+{684+ uint8 magnitude;685+ uint8 angle;686+ uint8 mux;687+} MappingChannel;688+689+typedef struct690+{691+ uint16 coupling_steps;692+ MappingChannel *chan;693+ uint8 submaps;694+ uint8 submap_floor[15]; // varies695+ uint8 submap_residue[15]; // varies696+} Mapping;697+698+typedef struct699+{700+ uint8 blockflag;701+ uint8 mapping;702+ uint16 windowtype;703+ uint16 transformtype;704+} Mode;705+706+typedef struct707+{708+ uint32 goal_crc; // expected crc if match709+ int bytes_left; // bytes left in packet710+ uint32 crc_so_far; // running crc711+ int bytes_done; // bytes processed in _current_ chunk712+ uint32 sample_loc; // granule pos encoded in page713+} CRCscan;714+715+typedef struct716+{717+ uint32 page_start, page_end;718+ uint32 after_previous_page_start;719+ uint32 first_decoded_sample;720+ uint32 last_decoded_sample;721+} ProbedPage;722+723+struct stb_vorbis724+{725+ // user-accessible info726+ unsigned int sample_rate;727+ int channels;728+729+ unsigned int setup_memory_required;730+ unsigned int temp_memory_required;731+ unsigned int setup_temp_memory_required;732+733+ // input config734+#ifndef STB_VORBIS_NO_STDIO735+ FILE *f;736+ uint32 f_start;737+ int close_on_free;738+#endif739+740+ uint8 *stream;741+ uint8 *stream_start;742+ uint8 *stream_end;743+744+ uint32 stream_len;745+746+ uint8 push_mode;747+748+ uint32 first_audio_page_offset;749+750+ ProbedPage p_first, p_last;751+752+ // memory management753+ stb_vorbis_alloc alloc;754+ int setup_offset;755+ int temp_offset;756+757+ // run-time results758+ int eof;759+ enum STBVorbisError error;760+761+ // user-useful data762+763+ // header info764+ int blocksize[2];765+ int blocksize_0, blocksize_1;766+ int codebook_count;767+ Codebook *codebooks;768+ int floor_count;769+ uint16 floor_types[64]; // varies770+ Floor *floor_config;771+ int residue_count;772+ uint16 residue_types[64]; // varies773+ Residue *residue_config;774+ int mapping_count;775+ Mapping *mapping;776+ int mode_count;777+ Mode mode_config[64]; // varies778+779+ uint32 total_samples;780+781+ // decode buffer782+ float *channel_buffers[STB_VORBIS_MAX_CHANNELS];783+ float *outputs [STB_VORBIS_MAX_CHANNELS];784+785+ float *previous_window[STB_VORBIS_MAX_CHANNELS];786+ int previous_length;787+788+ #ifndef STB_VORBIS_NO_DEFER_FLOOR789+ int16 *finalY[STB_VORBIS_MAX_CHANNELS];790+ #else791+ float *floor_buffers[STB_VORBIS_MAX_CHANNELS];792+ #endif793+794+ uint32 current_loc; // sample location of next frame to decode795+ int current_loc_valid;796+797+ // per-blocksize precomputed data798+ 799+ // twiddle factors800+ float *A[2],*B[2],*C[2];801+ float *window[2];802+ uint16 *bit_reverse[2];803+804+ // current page/packet/segment streaming info805+ uint32 serial; // stream serial number for verification806+ int last_page;807+ int segment_count;808+ uint8 segments[255];809+ uint8 page_flag;810+ uint8 bytes_in_seg;811+ uint8 first_decode;812+ int next_seg;813+ int last_seg; // flag that we're on the last segment814+ int last_seg_which; // what was the segment number of the last seg?815+ uint32 acc;816+ int valid_bits;817+ int packet_bytes;818+ int end_seg_with_known_loc;819+ uint32 known_loc_for_packet;820+ int discard_samples_deferred;821+ uint32 samples_output;822+823+ // push mode scanning824+ int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching825+#ifndef STB_VORBIS_NO_PUSHDATA_API826+ CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];827+#endif828+829+ // sample-access830+ int channel_buffer_start;831+ int channel_buffer_end;832+};833+834+extern int my_prof(int slot);835+//#define stb_prof my_prof836+837+#ifndef stb_prof838+#define stb_prof(x) ((void) 0)839+#endif840+841+#if defined(STB_VORBIS_NO_PUSHDATA_API)842+ #define IS_PUSH_MODE(f) FALSE843+#elif defined(STB_VORBIS_NO_PULLDATA_API)844+ #define IS_PUSH_MODE(f) TRUE845+#else846+ #define IS_PUSH_MODE(f) ((f)->push_mode)847+#endif848+849+typedef struct stb_vorbis vorb;850+851+static int error(vorb *f, enum STBVorbisError e)852+{853+ f->error = e;854+ if (!f->eof && e != VORBIS_need_more_data) {855+ f->error=e; // breakpoint for debugging856+ }857+ return 0;858+}859+860+861+// these functions are used for allocating temporary memory862+// while decoding. if you can afford the stack space, use863+// alloca(); otherwise, provide a temp buffer and it will864+// allocate out of those.865+866+#define array_size_required(count,size) (count*(sizeof(void *)+(size)))867+868+#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))869+#ifdef dealloca870+#define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size))871+#else872+#define temp_free(f,p) 0873+#endif874+#define temp_alloc_save(f) ((f)->temp_offset)875+#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))876+877+#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)878+879+// given a sufficiently large block of memory, make an array of pointers to subblocks of it880+static void *make_block_array(void *mem, int count, int size)881+{882+ int i;883+ void ** p = (void **) mem;884+ char *q = (char *) (p + count);885+ for (i=0; i < count; ++i) {886+ p[i] = q;887+ q += size;888+ }889+ return p;890+}891+892+static void *setup_malloc(vorb *f, int sz)893+{894+ sz = (sz+3) & ~3;895+ f->setup_memory_required += sz;896+ if (f->alloc.alloc_buffer) {897+ void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;898+ if (f->setup_offset + sz > f->temp_offset) return NULL;899+ f->setup_offset += sz;900+ return p;901+ }902+ return sz ? malloc(sz) : NULL;903+}904+905+static void setup_free(vorb *f, void *p)906+{907+ if (f->alloc.alloc_buffer) return; // do nothing; setup mem is not a stack908+ free(p);909+}910+911+static void *setup_temp_malloc(vorb *f, int sz)912+{913+ sz = (sz+3) & ~3;914+ if (f->alloc.alloc_buffer) {915+ if (f->temp_offset - sz < f->setup_offset) return NULL;916+ f->temp_offset -= sz;917+ return (char *) f->alloc.alloc_buffer + f->temp_offset;918+ }919+ return malloc(sz);920+}921+922+static void setup_temp_free(vorb *f, void *p, int sz)923+{924+ if (f->alloc.alloc_buffer) {925+ f->temp_offset += (sz+3)&~3;926+ return;927+ }928+ free(p);929+}930+931+#define CRC32_POLY 0x04c11db7 // from spec932+933+static uint32 crc_table[256];934+static void crc32_init(void)935+{936+ int i,j;937+ uint32 s;938+ for(i=0; i < 256; i++) {939+ for (s=i<<24, j=0; j < 8; ++j)940+ s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);941+ crc_table[i] = s;942+ }943+}944+945+static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)946+{947+ return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];948+}949+950+951+// used in setup, and for huffman that doesn't go fast path952+static unsigned int bit_reverse(unsigned int n)953+{954+ n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);955+ n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);956+ n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);957+ n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);958+ return (n >> 16) | (n << 16);959+}960+961+static float square(float x)962+{963+ return x*x;964+}965+966+// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3967+// as required by the specification. fast(?) implementation from stb.h968+// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup969+static int ilog(int32 n)970+{971+ static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };972+973+ // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)974+ if (n < (1 << 14))975+ if (n < (1 << 4)) return 0 + log2_4[n ];976+ else if (n < (1 << 9)) return 5 + log2_4[n >> 5];977+ else return 10 + log2_4[n >> 10];978+ else if (n < (1 << 24))979+ if (n < (1 << 19)) return 15 + log2_4[n >> 15];980+ else return 20 + log2_4[n >> 20];981+ else if (n < (1 << 29)) return 25 + log2_4[n >> 25];982+ else if (n < (1 << 31)) return 30 + log2_4[n >> 30];983+ else return 0; // signed n returns 0984+}985+986+#ifndef M_PI987+ #define M_PI 3.14159265358979323846264f // from CRC988+#endif989+990+// code length assigned to a value with no huffman encoding991+#define NO_CODE 255992+993+/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////994+//995+// these functions are only called at setup, and only a few times996+// per file997+998+static float float32_unpack(uint32 x)999+{1000+ // from the specification1001+ uint32 mantissa = x & 0x1fffff;1002+ uint32 sign = x & 0x80000000;1003+ uint32 exp = (x & 0x7fe00000) >> 21;1004+ double res = sign ? -(double)mantissa : (double)mantissa;1005+ return (float) ldexp((float)res, exp-788);1006+}1007+1008+1009+// zlib & jpeg huffman tables assume that the output symbols1010+// can either be arbitrarily arranged, or have monotonically1011+// increasing frequencies--they rely on the lengths being sorted;1012+// this makes for a very simple generation algorithm.1013+// vorbis allows a huffman table with non-sorted lengths. This1014+// requires a more sophisticated construction, since symbols in1015+// order do not map to huffman codes "in order".1016+static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)1017+{1018+ if (!c->sparse) {1019+ c->codewords [symbol] = huff_code;1020+ } else {1021+ c->codewords [count] = huff_code;1022+ c->codeword_lengths[count] = len;1023+ values [count] = symbol;1024+ }1025+}1026+1027+static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)1028+{1029+ int i,k,m=0;1030+ uint32 available[32];1031+1032+ memset(available, 0, sizeof(available));1033+ // find the first entry1034+ for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;1035+ if (k == n) { assert(c->sorted_entries == 0); return TRUE; }1036+ // add to the list1037+ add_entry(c, 0, k, m++, len[k], values);1038+ // add all available leaves1039+ for (i=1; i <= len[k]; ++i)1040+ available[i] = 1 << (32-i);1041+ // note that the above code treats the first case specially,1042+ // but it's really the same as the following code, so they1043+ // could probably be combined (except the initial code is 0,1044+ // and I use 0 in available[] to mean 'empty')1045+ for (i=k+1; i < n; ++i) {1046+ uint32 res;1047+ int z = len[i], y;1048+ if (z == NO_CODE) continue;1049+ // find lowest available leaf (should always be earliest,1050+ // which is what the specification calls for)1051+ // note that this property, and the fact we can never have1052+ // more than one free leaf at a given level, isn't totally1053+ // trivial to prove, but it seems true and the assert never1054+ // fires, so!1055+ while (z > 0 && !available[z]) --z;1056+ if (z == 0) { assert(0); return FALSE; }1057+ res = available[z];1058+ available[z] = 0;1059+ add_entry(c, bit_reverse(res), i, m++, len[i], values);1060+ // propogate availability up the tree1061+ if (z != len[i]) {1062+ for (y=len[i]; y > z; --y) {1063+ assert(available[y] == 0);1064+ available[y] = res + (1 << (32-y));1065+ }1066+ }1067+ }1068+ return TRUE;1069+}1070+1071+// accelerated huffman table allows fast O(1) match of all symbols1072+// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH1073+static void compute_accelerated_huffman(Codebook *c)1074+{1075+ int i, len;1076+ for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)1077+ c->fast_huffman[i] = -1;1078+1079+ len = c->sparse ? c->sorted_entries : c->entries;1080+ #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT1081+ if (len > 32767) len = 32767; // largest possible value we can encode!1082+ #endif1083+ for (i=0; i < len; ++i) {1084+ if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {1085+ uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];1086+ // set table entries for all bit combinations in the higher bits1087+ while (z < FAST_HUFFMAN_TABLE_SIZE) {1088+ c->fast_huffman[z] = i;1089+ z += 1 << c->codeword_lengths[i];1090+ }1091+ }1092+ }1093+}1094+1095+#ifdef _MSC_VER1096+#define STBV_CDECL __cdecl1097+#else1098+#define STBV_CDECL1099+#endif1100+1101+static int STBV_CDECL uint32_compare(const void *p, const void *q)1102+{1103+ uint32 x = * (uint32 *) p;1104+ uint32 y = * (uint32 *) q;1105+ return x < y ? -1 : x > y;1106+}1107+1108+static int include_in_sort(Codebook *c, uint8 len)1109+{1110+ if (c->sparse) { assert(len != NO_CODE); return TRUE; }1111+ if (len == NO_CODE) return FALSE;1112+ if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;1113+ return FALSE;1114+}1115+1116+// if the fast table above doesn't work, we want to binary1117+// search them... need to reverse the bits1118+static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)1119+{1120+ int i, len;1121+ // build a list of all the entries1122+ // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.1123+ // this is kind of a frivolous optimization--I don't see any performance improvement,1124+ // but it's like 4 extra lines of code, so.1125+ if (!c->sparse) {1126+ int k = 0;1127+ for (i=0; i < c->entries; ++i)1128+ if (include_in_sort(c, lengths[i])) 1129+ c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);1130+ assert(k == c->sorted_entries);1131+ } else {1132+ for (i=0; i < c->sorted_entries; ++i)1133+ c->sorted_codewords[i] = bit_reverse(c->codewords[i]);1134+ }1135+1136+ qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);1137+ c->sorted_codewords[c->sorted_entries] = 0xffffffff;1138+1139+ len = c->sparse ? c->sorted_entries : c->entries;1140+ // now we need to indicate how they correspond; we could either1141+ // #1: sort a different data structure that says who they correspond to1142+ // #2: for each sorted entry, search the original list to find who corresponds1143+ // #3: for each original entry, find the sorted entry1144+ // #1 requires extra storage, #2 is slow, #3 can use binary search!1145+ for (i=0; i < len; ++i) {1146+ int huff_len = c->sparse ? lengths[values[i]] : lengths[i];1147+ if (include_in_sort(c,huff_len)) {1148+ uint32 code = bit_reverse(c->codewords[i]);1149+ int x=0, n=c->sorted_entries;1150+ while (n > 1) {1151+ // invariant: sc[x] <= code < sc[x+n]1152+ int m = x + (n >> 1);1153+ if (c->sorted_codewords[m] <= code) {1154+ x = m;1155+ n -= (n>>1);1156+ } else {1157+ n >>= 1;1158+ }1159+ }1160+ assert(c->sorted_codewords[x] == code);1161+ if (c->sparse) {1162+ c->sorted_values[x] = values[i];1163+ c->codeword_lengths[x] = huff_len;1164+ } else {1165+ c->sorted_values[x] = i;1166+ }1167+ }1168+ }1169+}1170+1171+// only run while parsing the header (3 times)1172+static int vorbis_validate(uint8 *data)1173+{1174+ static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };1175+ return memcmp(data, vorbis, 6) == 0;1176+}1177+1178+// called from setup only, once per code book1179+// (formula implied by specification)1180+static int lookup1_values(int entries, int dim)1181+{1182+ int r = (int) floor(exp((float) log((float) entries) / dim));1183+ if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;1184+ ++r; // floor() to avoid _ftol() when non-CRT1185+ assert(pow((float) r+1, dim) > entries);1186+ assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above1187+ return r;1188+}1189+1190+// called twice per file1191+static void compute_twiddle_factors(int n, float *A, float *B, float *C)1192+{1193+ int n4 = n >> 2, n8 = n >> 3;1194+ int k,k2;1195+1196+ for (k=k2=0; k < n4; ++k,k2+=2) {1197+ A[k2 ] = (float) cos(4*k*M_PI/n);1198+ A[k2+1] = (float) -sin(4*k*M_PI/n);1199+ B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;1200+ B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;1201+ }1202+ for (k=k2=0; k < n8; ++k,k2+=2) {1203+ C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);1204+ C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);1205+ }1206+}1207+1208+static void compute_window(int n, float *window)1209+{1210+ int n2 = n >> 1, i;1211+ for (i=0; i < n2; ++i)1212+ window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));1213+}1214+1215+static void compute_bitreverse(int n, uint16 *rev)1216+{1217+ int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions1218+ int i, n8 = n >> 3;1219+ for (i=0; i < n8; ++i)1220+ rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;1221+}1222+1223+static int init_blocksize(vorb *f, int b, int n)1224+{1225+ int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;1226+ f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);1227+ f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);1228+ f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);1229+ if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);1230+ compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);1231+ f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);1232+ if (!f->window[b]) return error(f, VORBIS_outofmem);1233+ compute_window(n, f->window[b]);1234+ f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);1235+ if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);1236+ compute_bitreverse(n, f->bit_reverse[b]);1237+ return TRUE;1238+}1239+1240+static void neighbors(uint16 *x, int n, int *plow, int *phigh)1241+{1242+ int low = -1;1243+ int high = 65536;1244+ int i;1245+ for (i=0; i < n; ++i) {1246+ if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }1247+ if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }1248+ }1249+}1250+1251+// this has been repurposed so y is now the original index instead of y1252+typedef struct1253+{1254+ uint16 x,y;1255+} Point;1256+1257+static int STBV_CDECL point_compare(const void *p, const void *q)1258+{1259+ Point *a = (Point *) p;1260+ Point *b = (Point *) q;1261+ return a->x < b->x ? -1 : a->x > b->x;1262+}1263+1264+//1265+/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////1266+1267+1268+#if defined(STB_VORBIS_NO_STDIO)1269+ #define USE_MEMORY(z) TRUE1270+#else1271+ #define USE_MEMORY(z) ((z)->stream)1272+#endif1273+1274+static uint8 get8(vorb *z)1275+{1276+ if (USE_MEMORY(z)) {1277+ if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }1278+ return *z->stream++;1279+ }1280+1281+ #ifndef STB_VORBIS_NO_STDIO1282+ {1283+ int c = fgetc(z->f);1284+ if (c == EOF) { z->eof = TRUE; return 0; }1285+ return c;1286+ }1287+ #endif1288+}1289+1290+static uint32 get32(vorb *f)1291+{1292+ uint32 x;1293+ x = get8(f);1294+ x += get8(f) << 8;1295+ x += get8(f) << 16;1296+ x += get8(f) << 24;1297+ return x;1298+}1299+1300+static int getn(vorb *z, uint8 *data, int n)1301+{1302+ if (USE_MEMORY(z)) {1303+ if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }1304+ memcpy(data, z->stream, n);1305+ z->stream += n;1306+ return 1;1307+ }1308+1309+ #ifndef STB_VORBIS_NO_STDIO 1310+ if (fread(data, n, 1, z->f) == 1)1311+ return 1;1312+ else {1313+ z->eof = 1;1314+ return 0;1315+ }1316+ #endif1317+}1318+1319+static void skip(vorb *z, int n)1320+{1321+ if (USE_MEMORY(z)) {1322+ z->stream += n;1323+ if (z->stream >= z->stream_end) z->eof = 1;1324+ return;1325+ }1326+ #ifndef STB_VORBIS_NO_STDIO1327+ {1328+ long x = ftell(z->f);1329+ fseek(z->f, x+n, SEEK_SET);1330+ }1331+ #endif1332+}1333+1334+static int set_file_offset(stb_vorbis *f, unsigned int loc)1335+{1336+ #ifndef STB_VORBIS_NO_PUSHDATA_API1337+ if (f->push_mode) return 0;1338+ #endif1339+ f->eof = 0;1340+ if (USE_MEMORY(f)) {1341+ if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {1342+ f->stream = f->stream_end;1343+ f->eof = 1;1344+ return 0;1345+ } else {1346+ f->stream = f->stream_start + loc;1347+ return 1;1348+ }1349+ }1350+ #ifndef STB_VORBIS_NO_STDIO1351+ if (loc + f->f_start < loc || loc >= 0x80000000) {1352+ loc = 0x7fffffff;1353+ f->eof = 1;1354+ } else {1355+ loc += f->f_start;1356+ }1357+ if (!fseek(f->f, loc, SEEK_SET))1358+ return 1;1359+ f->eof = 1;1360+ fseek(f->f, f->f_start, SEEK_END);1361+ return 0;1362+ #endif1363+}1364+1365+1366+static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };1367+1368+static int capture_pattern(vorb *f)1369+{1370+ if (0x4f != get8(f)) return FALSE;1371+ if (0x67 != get8(f)) return FALSE;1372+ if (0x67 != get8(f)) return FALSE;1373+ if (0x53 != get8(f)) return FALSE;1374+ return TRUE;1375+}1376+1377+#define PAGEFLAG_continued_packet 11378+#define PAGEFLAG_first_page 21379+#define PAGEFLAG_last_page 41380+1381+static int start_page_no_capturepattern(vorb *f)1382+{1383+ uint32 loc0,loc1,n;1384+ // stream structure version1385+ if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);1386+ // header flag1387+ f->page_flag = get8(f);1388+ // absolute granule position1389+ loc0 = get32(f); 1390+ loc1 = get32(f);1391+ // @TODO: validate loc0,loc1 as valid positions?1392+ // stream serial number -- vorbis doesn't interleave, so discard1393+ get32(f);1394+ //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);1395+ // page sequence number1396+ n = get32(f);1397+ f->last_page = n;1398+ // CRC321399+ get32(f);1400+ // page_segments1401+ f->segment_count = get8(f);1402+ if (!getn(f, f->segments, f->segment_count))1403+ return error(f, VORBIS_unexpected_eof);1404+ // assume we _don't_ know any the sample position of any segments1405+ f->end_seg_with_known_loc = -2;1406+ if (loc0 != ~0U || loc1 != ~0U) {1407+ int i;1408+ // determine which packet is the last one that will complete1409+ for (i=f->segment_count-1; i >= 0; --i)1410+ if (f->segments[i] < 255)1411+ break;1412+ // 'i' is now the index of the _last_ segment of a packet that ends1413+ if (i >= 0) {1414+ f->end_seg_with_known_loc = i;1415+ f->known_loc_for_packet = loc0;1416+ }1417+ }1418+ if (f->first_decode) {1419+ int i,len;1420+ ProbedPage p;1421+ len = 0;1422+ for (i=0; i < f->segment_count; ++i)1423+ len += f->segments[i];1424+ len += 27 + f->segment_count;1425+ p.page_start = f->first_audio_page_offset;1426+ p.page_end = p.page_start + len;1427+ p.after_previous_page_start = p.page_start;1428+ p.first_decoded_sample = 0;1429+ p.last_decoded_sample = loc0;1430+ f->p_first = p;1431+ }1432+ f->next_seg = 0;1433+ return TRUE;1434+}1435+1436+static int start_page(vorb *f)1437+{1438+ if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);1439+ return start_page_no_capturepattern(f);1440+}1441+1442+static int start_packet(vorb *f)1443+{1444+ while (f->next_seg == -1) {1445+ if (!start_page(f)) return FALSE;1446+ if (f->page_flag & PAGEFLAG_continued_packet)1447+ return error(f, VORBIS_continued_packet_flag_invalid);1448+ }1449+ f->last_seg = FALSE;1450+ f->valid_bits = 0;1451+ f->packet_bytes = 0;1452+ f->bytes_in_seg = 0;1453+ // f->next_seg is now valid1454+ return TRUE;1455+}1456+1457+static int maybe_start_packet(vorb *f)1458+{1459+ if (f->next_seg == -1) {1460+ int x = get8(f);1461+ if (f->eof) return FALSE; // EOF at page boundary is not an error!1462+ if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);1463+ if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);1464+ if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);1465+ if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);1466+ if (!start_page_no_capturepattern(f)) return FALSE;1467+ if (f->page_flag & PAGEFLAG_continued_packet) {1468+ // set up enough state that we can read this packet if we want,1469+ // e.g. during recovery1470+ f->last_seg = FALSE;1471+ f->bytes_in_seg = 0;1472+ return error(f, VORBIS_continued_packet_flag_invalid);1473+ }1474+ }1475+ return start_packet(f);1476+}1477+1478+static int next_segment(vorb *f)1479+{1480+ int len;1481+ if (f->last_seg) return 0;1482+ if (f->next_seg == -1) {1483+ f->last_seg_which = f->segment_count-1; // in case start_page fails1484+ if (!start_page(f)) { f->last_seg = 1; return 0; }1485+ if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);1486+ }1487+ len = f->segments[f->next_seg++];1488+ if (len < 255) {1489+ f->last_seg = TRUE;1490+ f->last_seg_which = f->next_seg-1;1491+ }1492+ if (f->next_seg >= f->segment_count)1493+ f->next_seg = -1;1494+ assert(f->bytes_in_seg == 0);1495+ f->bytes_in_seg = len;1496+ return len;1497+}1498+1499+#define EOP (-1)1500+#define INVALID_BITS (-1)1501+1502+static int get8_packet_raw(vorb *f)1503+{1504+ if (!f->bytes_in_seg) { // CLANG!1505+ if (f->last_seg) return EOP;1506+ else if (!next_segment(f)) return EOP;1507+ }1508+ assert(f->bytes_in_seg > 0);1509+ --f->bytes_in_seg;1510+ ++f->packet_bytes;1511+ return get8(f);1512+}1513+1514+static int get8_packet(vorb *f)1515+{1516+ int x = get8_packet_raw(f);1517+ f->valid_bits = 0;1518+ return x;1519+}1520+1521+static void flush_packet(vorb *f)1522+{1523+ while (get8_packet_raw(f) != EOP);1524+}1525+1526+// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important1527+// as the huffman decoder?1528+static uint32 get_bits(vorb *f, int n)1529+{1530+ uint32 z;1531+1532+ if (f->valid_bits < 0) return 0;1533+ if (f->valid_bits < n) {1534+ if (n > 24) {1535+ // the accumulator technique below would not work correctly in this case1536+ z = get_bits(f, 24);1537+ z += get_bits(f, n-24) << 24;1538+ return z;1539+ }1540+ if (f->valid_bits == 0) f->acc = 0;1541+ while (f->valid_bits < n) {1542+ int z = get8_packet_raw(f);1543+ if (z == EOP) {1544+ f->valid_bits = INVALID_BITS;1545+ return 0;1546+ }1547+ f->acc += z << f->valid_bits;1548+ f->valid_bits += 8;1549+ }1550+ }1551+ if (f->valid_bits < 0) return 0;1552+ z = f->acc & ((1 << n)-1);1553+ f->acc >>= n;1554+ f->valid_bits -= n;1555+ return z;1556+}1557+1558+// @OPTIMIZE: primary accumulator for huffman1559+// expand the buffer to as many bits as possible without reading off end of packet1560+// it might be nice to allow f->valid_bits and f->acc to be stored in registers,1561+// e.g. cache them locally and decode locally1562+static __forceinline void prep_huffman(vorb *f)1563+{1564+ if (f->valid_bits <= 24) {1565+ if (f->valid_bits == 0) f->acc = 0;1566+ do {1567+ int z;1568+ if (f->last_seg && !f->bytes_in_seg) return;1569+ z = get8_packet_raw(f);1570+ if (z == EOP) return;1571+ f->acc += z << f->valid_bits;1572+ f->valid_bits += 8;1573+ } while (f->valid_bits <= 24);1574+ }1575+}1576+1577+enum1578+{1579+ VORBIS_packet_id = 1,1580+ VORBIS_packet_comment = 3,1581+ VORBIS_packet_setup = 5,1582+};1583+1584+static int codebook_decode_scalar_raw(vorb *f, Codebook *c)1585+{1586+ int i;1587+ prep_huffman(f);1588+1589+ assert(c->sorted_codewords || c->codewords);1590+ // cases to use binary search: sorted_codewords && !c->codewords1591+ // sorted_codewords && c->entries > 81592+ if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {1593+ // binary search1594+ uint32 code = bit_reverse(f->acc);1595+ int x=0, n=c->sorted_entries, len;1596+1597+ while (n > 1) {1598+ // invariant: sc[x] <= code < sc[x+n]1599+ int m = x + (n >> 1);1600+ if (c->sorted_codewords[m] <= code) {1601+ x = m;1602+ n -= (n>>1);1603+ } else {1604+ n >>= 1;1605+ }1606+ }1607+ // x is now the sorted index1608+ if (!c->sparse) x = c->sorted_values[x];1609+ // x is now sorted index if sparse, or symbol otherwise1610+ len = c->codeword_lengths[x];1611+ if (f->valid_bits >= len) {1612+ f->acc >>= len;1613+ f->valid_bits -= len;1614+ return x;1615+ }1616+1617+ f->valid_bits = 0;1618+ return -1;1619+ }1620+1621+ // if small, linear search1622+ assert(!c->sparse);1623+ for (i=0; i < c->entries; ++i) {1624+ if (c->codeword_lengths[i] == NO_CODE) continue;1625+ if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {1626+ if (f->valid_bits >= c->codeword_lengths[i]) {1627+ f->acc >>= c->codeword_lengths[i];1628+ f->valid_bits -= c->codeword_lengths[i];1629+ return i;1630+ }1631+ f->valid_bits = 0;1632+ return -1;1633+ }1634+ }1635+1636+ error(f, VORBIS_invalid_stream);1637+ f->valid_bits = 0;1638+ return -1;1639+}1640+1641+#ifndef STB_VORBIS_NO_INLINE_DECODE1642+1643+#define DECODE_RAW(var, f,c) \1644+ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \1645+ prep_huffman(f); \1646+ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \1647+ var = c->fast_huffman[var]; \1648+ if (var >= 0) { \1649+ int n = c->codeword_lengths[var]; \1650+ f->acc >>= n; \1651+ f->valid_bits -= n; \1652+ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \1653+ } else { \1654+ var = codebook_decode_scalar_raw(f,c); \1655+ }1656+1657+#else1658+1659+static int codebook_decode_scalar(vorb *f, Codebook *c)1660+{1661+ int i;1662+ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)1663+ prep_huffman(f);1664+ // fast huffman table lookup1665+ i = f->acc & FAST_HUFFMAN_TABLE_MASK;1666+ i = c->fast_huffman[i];1667+ if (i >= 0) {1668+ f->acc >>= c->codeword_lengths[i];1669+ f->valid_bits -= c->codeword_lengths[i];1670+ if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }1671+ return i;1672+ }1673+ return codebook_decode_scalar_raw(f,c);1674+}1675+1676+#define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);1677+1678+#endif1679+1680+#define DECODE(var,f,c) \1681+ DECODE_RAW(var,f,c) \1682+ if (c->sparse) var = c->sorted_values[var];1683+1684+#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK1685+ #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)1686+#else1687+ #define DECODE_VQ(var,f,c) DECODE(var,f,c)1688+#endif1689+1690+1691+1692+1693+1694+1695+// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case1696+// where we avoid one addition1697+#ifndef STB_VORBIS_CODEBOOK_FLOATS1698+ #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off] * c->delta_value + c->minimum_value)1699+ #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off] * c->delta_value)1700+ #define CODEBOOK_ELEMENT_BASE(c) (c->minimum_value)1701+#else1702+ #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])1703+ #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])1704+ #define CODEBOOK_ELEMENT_BASE(c) (0)1705+#endif1706+1707+static int codebook_decode_start(vorb *f, Codebook *c)1708+{1709+ int z = -1;1710+1711+ // type 0 is only legal in a scalar context1712+ if (c->lookup_type == 0)1713+ error(f, VORBIS_invalid_stream);1714+ else {1715+ DECODE_VQ(z,f,c);1716+ if (c->sparse) assert(z < c->sorted_entries);1717+ if (z < 0) { // check for EOP1718+ if (!f->bytes_in_seg)1719+ if (f->last_seg)1720+ return z;1721+ error(f, VORBIS_invalid_stream);1722+ }1723+ }1724+ return z;1725+}1726+1727+static int codebook_decode(vorb *f, Codebook *c, float *output, int len)1728+{1729+ int i,z = codebook_decode_start(f,c);1730+ if (z < 0) return FALSE;1731+ if (len > c->dimensions) len = c->dimensions;1732+1733+#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK1734+ if (c->lookup_type == 1) {1735+ float last = CODEBOOK_ELEMENT_BASE(c);1736+ int div = 1;1737+ for (i=0; i < len; ++i) {1738+ int off = (z / div) % c->lookup_values;1739+ float val = CODEBOOK_ELEMENT_FAST(c,off) + last;1740+ output[i] += val;1741+ if (c->sequence_p) last = val + c->minimum_value;1742+ div *= c->lookup_values;1743+ }1744+ return TRUE;1745+ }1746+#endif1747+1748+ z *= c->dimensions;1749+ if (c->sequence_p) {1750+ float last = CODEBOOK_ELEMENT_BASE(c);1751+ for (i=0; i < len; ++i) {1752+ float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1753+ output[i] += val;1754+ last = val + c->minimum_value;1755+ }1756+ } else {1757+ float last = CODEBOOK_ELEMENT_BASE(c);1758+ for (i=0; i < len; ++i) {1759+ output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;1760+ }1761+ }1762+1763+ return TRUE;1764+}1765+1766+static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)1767+{1768+ int i,z = codebook_decode_start(f,c);1769+ float last = CODEBOOK_ELEMENT_BASE(c);1770+ if (z < 0) return FALSE;1771+ if (len > c->dimensions) len = c->dimensions;1772+1773+#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK1774+ if (c->lookup_type == 1) {1775+ int div = 1;1776+ for (i=0; i < len; ++i) {1777+ int off = (z / div) % c->lookup_values;1778+ float val = CODEBOOK_ELEMENT_FAST(c,off) + last;1779+ output[i*step] += val;1780+ if (c->sequence_p) last = val;1781+ div *= c->lookup_values;1782+ }1783+ return TRUE;1784+ }1785+#endif1786+1787+ z *= c->dimensions;1788+ for (i=0; i < len; ++i) {1789+ float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1790+ output[i*step] += val;1791+ if (c->sequence_p) last = val;1792+ }1793+1794+ return TRUE;1795+}1796+1797+static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)1798+{1799+ int c_inter = *c_inter_p;1800+ int p_inter = *p_inter_p;1801+ int i,z, effective = c->dimensions;1802+1803+ // type 0 is only legal in a scalar context1804+ if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);1805+1806+ while (total_decode > 0) {1807+ float last = CODEBOOK_ELEMENT_BASE(c);1808+ DECODE_VQ(z,f,c);1809+ #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK1810+ assert(!c->sparse || z < c->sorted_entries);1811+ #endif1812+ if (z < 0) {1813+ if (!f->bytes_in_seg)1814+ if (f->last_seg) return FALSE;1815+ return error(f, VORBIS_invalid_stream);1816+ }1817+1818+ // if this will take us off the end of the buffers, stop short!1819+ // we check by computing the length of the virtual interleaved1820+ // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),1821+ // and the length we'll be using (effective)1822+ if (c_inter + p_inter*ch + effective > len * ch) {1823+ effective = len*ch - (p_inter*ch - c_inter);1824+ }1825+1826+ #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK1827+ if (c->lookup_type == 1) {1828+ int div = 1;1829+ for (i=0; i < effective; ++i) {1830+ int off = (z / div) % c->lookup_values;1831+ float val = CODEBOOK_ELEMENT_FAST(c,off) + last;1832+ if (outputs[c_inter])1833+ outputs[c_inter][p_inter] += val;1834+ if (++c_inter == ch) { c_inter = 0; ++p_inter; }1835+ if (c->sequence_p) last = val;1836+ div *= c->lookup_values;1837+ }1838+ } else1839+ #endif1840+ {1841+ z *= c->dimensions;1842+ if (c->sequence_p) {1843+ for (i=0; i < effective; ++i) {1844+ float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1845+ if (outputs[c_inter])1846+ outputs[c_inter][p_inter] += val;1847+ if (++c_inter == ch) { c_inter = 0; ++p_inter; }1848+ last = val;1849+ }1850+ } else {1851+ for (i=0; i < effective; ++i) {1852+ float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1853+ if (outputs[c_inter])1854+ outputs[c_inter][p_inter] += val;1855+ if (++c_inter == ch) { c_inter = 0; ++p_inter; }1856+ }1857+ }1858+ }1859+1860+ total_decode -= effective;1861+ }1862+ *c_inter_p = c_inter;1863+ *p_inter_p = p_inter;1864+ return TRUE;1865+}1866+1867+#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK1868+static int codebook_decode_deinterleave_repeat_2(vorb *f, Codebook *c, float **outputs, int *c_inter_p, int *p_inter_p, int len, int total_decode)1869+{1870+ int c_inter = *c_inter_p;1871+ int p_inter = *p_inter_p;1872+ int i,z, effective = c->dimensions;1873+1874+ // type 0 is only legal in a scalar context1875+ if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);1876+1877+ while (total_decode > 0) {1878+ float last = CODEBOOK_ELEMENT_BASE(c);1879+ DECODE_VQ(z,f,c);1880+1881+ if (z < 0) {1882+ if (!f->bytes_in_seg)1883+ if (f->last_seg) return FALSE;1884+ return error(f, VORBIS_invalid_stream);1885+ }1886+1887+ // if this will take us off the end of the buffers, stop short!1888+ // we check by computing the length of the virtual interleaved1889+ // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),1890+ // and the length we'll be using (effective)1891+ if (c_inter + p_inter*2 + effective > len * 2) {1892+ effective = len*2 - (p_inter*2 - c_inter);1893+ }1894+1895+ {1896+ z *= c->dimensions;1897+ stb_prof(11);1898+ if (c->sequence_p) {1899+ // haven't optimized this case because I don't have any examples1900+ for (i=0; i < effective; ++i) {1901+ float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1902+ if (outputs[c_inter])1903+ outputs[c_inter][p_inter] += val;1904+ if (++c_inter == 2) { c_inter = 0; ++p_inter; }1905+ last = val;1906+ }1907+ } else {1908+ i=0;1909+ if (c_inter == 1) {1910+ float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1911+ if (outputs[c_inter])1912+ outputs[c_inter][p_inter] += val;1913+ c_inter = 0; ++p_inter;1914+ ++i;1915+ }1916+ {1917+ float *z0 = outputs[0];1918+ float *z1 = outputs[1];1919+ for (; i+1 < effective;) {1920+ float v0 = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1921+ float v1 = CODEBOOK_ELEMENT_FAST(c,z+i+1) + last;1922+ if (z0)1923+ z0[p_inter] += v0;1924+ if (z1)1925+ z1[p_inter] += v1;1926+ ++p_inter;1927+ i += 2;1928+ }1929+ }1930+ if (i < effective) {1931+ float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1932+ if (outputs[c_inter])1933+ outputs[c_inter][p_inter] += val;1934+ if (++c_inter == 2) { c_inter = 0; ++p_inter; }1935+ }1936+ }1937+ }1938+1939+ total_decode -= effective;1940+ }1941+ *c_inter_p = c_inter;1942+ *p_inter_p = p_inter;1943+ return TRUE;1944+}1945+#endif1946+1947+static int predict_point(int x, int x0, int x1, int y0, int y1)1948+{1949+ int dy = y1 - y0;1950+ int adx = x1 - x0;1951+ // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?1952+ int err = abs(dy) * (x - x0);1953+ int off = err / adx;1954+ return dy < 0 ? y0 - off : y0 + off;1955+}1956+1957+// the following table is block-copied from the specification1958+static float inverse_db_table[256] =1959+{1960+ 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1961+ 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1962+ 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 1963+ 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 1964+ 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 1965+ 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 1966+ 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 1967+ 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 1968+ 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1969+ 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1970+ 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1971+ 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 1972+ 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 1973+ 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 1974+ 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 1975+ 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 1976+ 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 1977+ 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 1978+ 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1979+ 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1980+ 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 1981+ 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 1982+ 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 1983+ 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 1984+ 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 1985+ 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 1986+ 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 1987+ 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 1988+ 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 1989+ 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 1990+ 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 1991+ 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 1992+ 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 1993+ 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 1994+ 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 1995+ 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 1996+ 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 1997+ 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 1998+ 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 1999+ 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 2000+ 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 2001+ 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 2002+ 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 2003+ 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 2004+ 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 2005+ 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 2006+ 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 2007+ 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 2008+ 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 2009+ 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 2010+ 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 2011+ 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 2012+ 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 2013+ 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 2014+ 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 2015+ 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 2016+ 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 2017+ 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 2018+ 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 2019+ 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 2020+ 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 2021+ 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 2022+ 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 2023+ 0.82788260f, 0.88168307f, 0.9389798f, 1.0f2024+};2025+2026+2027+// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,2028+// note that you must produce bit-identical output to decode correctly;2029+// this specific sequence of operations is specified in the spec (it's2030+// drawing integer-quantized frequency-space lines that the encoder2031+// expects to be exactly the same)2032+// ... also, isn't the whole point of Bresenham's algorithm to NOT2033+// have to divide in the setup? sigh.2034+#ifndef STB_VORBIS_NO_DEFER_FLOOR2035+#define LINE_OP(a,b) a *= b2036+#else2037+#define LINE_OP(a,b) a = b2038+#endif2039+2040+#ifdef STB_VORBIS_DIVIDE_TABLE2041+#define DIVTAB_NUMER 322042+#define DIVTAB_DENOM 642043+int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB2044+#endif2045+2046+static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)2047+{2048+ int dy = y1 - y0;2049+ int adx = x1 - x0;2050+ int ady = abs(dy);2051+ int base;2052+ int x=x0,y=y0;2053+ int err = 0;2054+ int sy;2055+2056+#ifdef STB_VORBIS_DIVIDE_TABLE2057+ if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {2058+ if (dy < 0) {2059+ base = -integer_divide_table[ady][adx];2060+ sy = base-1;2061+ } else {2062+ base = integer_divide_table[ady][adx];2063+ sy = base+1;2064+ }2065+ } else {2066+ base = dy / adx;2067+ if (dy < 0)2068+ sy = base - 1;2069+ else2070+ sy = base+1;2071+ }2072+#else2073+ base = dy / adx;2074+ if (dy < 0)2075+ sy = base - 1;2076+ else2077+ sy = base+1;2078+#endif2079+ ady -= abs(base) * adx;2080+ if (x1 > n) x1 = n;2081+ LINE_OP(output[x], inverse_db_table[y]);2082+ for (++x; x < x1; ++x) {2083+ err += ady;2084+ if (err >= adx) {2085+ err -= adx;2086+ y += sy;2087+ } else2088+ y += base;2089+ LINE_OP(output[x], inverse_db_table[y]);2090+ }2091+}2092+2093+static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)2094+{2095+ int k;2096+ if (rtype == 0) {2097+ int step = n / book->dimensions;2098+ for (k=0; k < step; ++k)2099+ if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))2100+ return FALSE;2101+ } else {2102+ for (k=0; k < n; ) {2103+ if (!codebook_decode(f, book, target+offset, n-k))2104+ return FALSE;2105+ k += book->dimensions;2106+ offset += book->dimensions;2107+ }2108+ }2109+ return TRUE;2110+}2111+2112+static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)2113+{2114+ int i,j,pass;2115+ Residue *r = f->residue_config + rn;2116+ int rtype = f->residue_types[rn];2117+ int c = r->classbook;2118+ int classwords = f->codebooks[c].dimensions;2119+ int n_read = r->end - r->begin;2120+ int part_read = n_read / r->part_size;2121+ int temp_alloc_point = temp_alloc_save(f);2122+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2123+ uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));2124+ #else2125+ int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));2126+ #endif2127+2128+ stb_prof(2);2129+ for (i=0; i < ch; ++i)2130+ if (!do_not_decode[i])2131+ memset(residue_buffers[i], 0, sizeof(float) * n);2132+2133+ if (rtype == 2 && ch != 1) {2134+ for (j=0; j < ch; ++j)2135+ if (!do_not_decode[j])2136+ break;2137+ if (j == ch)2138+ goto done;2139+2140+ stb_prof(3);2141+ for (pass=0; pass < 8; ++pass) {2142+ int pcount = 0, class_set = 0;2143+ if (ch == 2) {2144+ stb_prof(13);2145+ while (pcount < part_read) {2146+ int z = r->begin + pcount*r->part_size;2147+ int c_inter = (z & 1), p_inter = z>>1;2148+ if (pass == 0) {2149+ Codebook *c = f->codebooks+r->classbook;2150+ int q;2151+ DECODE(q,f,c);2152+ if (q == EOP) goto done;2153+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2154+ part_classdata[0][class_set] = r->classdata[q];2155+ #else2156+ for (i=classwords-1; i >= 0; --i) {2157+ classifications[0][i+pcount] = q % r->classifications;2158+ q /= r->classifications;2159+ }2160+ #endif2161+ }2162+ stb_prof(5);2163+ for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {2164+ int z = r->begin + pcount*r->part_size;2165+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2166+ int c = part_classdata[0][class_set][i];2167+ #else2168+ int c = classifications[0][pcount];2169+ #endif2170+ int b = r->residue_books[c][pass];2171+ if (b >= 0) {2172+ Codebook *book = f->codebooks + b;2173+ stb_prof(20); // accounts for X time2174+ #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK2175+ if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))2176+ goto done;2177+ #else2178+ // saves 1%2179+ if (!codebook_decode_deinterleave_repeat_2(f, book, residue_buffers, &c_inter, &p_inter, n, r->part_size))2180+ goto done;2181+ #endif2182+ stb_prof(7);2183+ } else {2184+ z += r->part_size;2185+ c_inter = z & 1;2186+ p_inter = z >> 1;2187+ }2188+ }2189+ stb_prof(8);2190+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2191+ ++class_set;2192+ #endif2193+ }2194+ } else if (ch == 1) {2195+ while (pcount < part_read) {2196+ int z = r->begin + pcount*r->part_size;2197+ int c_inter = 0, p_inter = z;2198+ if (pass == 0) {2199+ Codebook *c = f->codebooks+r->classbook;2200+ int q;2201+ DECODE(q,f,c);2202+ if (q == EOP) goto done;2203+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2204+ part_classdata[0][class_set] = r->classdata[q];2205+ #else2206+ for (i=classwords-1; i >= 0; --i) {2207+ classifications[0][i+pcount] = q % r->classifications;2208+ q /= r->classifications;2209+ }2210+ #endif2211+ }2212+ for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {2213+ int z = r->begin + pcount*r->part_size;2214+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2215+ int c = part_classdata[0][class_set][i];2216+ #else2217+ int c = classifications[0][pcount];2218+ #endif2219+ int b = r->residue_books[c][pass];2220+ if (b >= 0) {2221+ Codebook *book = f->codebooks + b;2222+ stb_prof(22);2223+ if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))2224+ goto done;2225+ stb_prof(3);2226+ } else {2227+ z += r->part_size;2228+ c_inter = 0;2229+ p_inter = z;2230+ }2231+ }2232+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2233+ ++class_set;2234+ #endif2235+ }2236+ } else {2237+ while (pcount < part_read) {2238+ int z = r->begin + pcount*r->part_size;2239+ int c_inter = z % ch, p_inter = z/ch;2240+ if (pass == 0) {2241+ Codebook *c = f->codebooks+r->classbook;2242+ int q;2243+ DECODE(q,f,c);2244+ if (q == EOP) goto done;2245+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2246+ part_classdata[0][class_set] = r->classdata[q];2247+ #else2248+ for (i=classwords-1; i >= 0; --i) {2249+ classifications[0][i+pcount] = q % r->classifications;2250+ q /= r->classifications;2251+ }2252+ #endif2253+ }2254+ for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {2255+ int z = r->begin + pcount*r->part_size;2256+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2257+ int c = part_classdata[0][class_set][i];2258+ #else2259+ int c = classifications[0][pcount];2260+ #endif2261+ int b = r->residue_books[c][pass];2262+ if (b >= 0) {2263+ Codebook *book = f->codebooks + b;2264+ stb_prof(22);2265+ if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))2266+ goto done;2267+ stb_prof(3);2268+ } else {2269+ z += r->part_size;2270+ c_inter = z % ch;2271+ p_inter = z / ch;2272+ }2273+ }2274+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2275+ ++class_set;2276+ #endif2277+ }2278+ }2279+ }2280+ goto done;2281+ }2282+ stb_prof(9);2283+2284+ for (pass=0; pass < 8; ++pass) {2285+ int pcount = 0, class_set=0;2286+ while (pcount < part_read) {2287+ if (pass == 0) {2288+ for (j=0; j < ch; ++j) {2289+ if (!do_not_decode[j]) {2290+ Codebook *c = f->codebooks+r->classbook;2291+ int temp;2292+ DECODE(temp,f,c);2293+ if (temp == EOP) goto done;2294+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2295+ part_classdata[j][class_set] = r->classdata[temp];2296+ #else2297+ for (i=classwords-1; i >= 0; --i) {2298+ classifications[j][i+pcount] = temp % r->classifications;2299+ temp /= r->classifications;2300+ }2301+ #endif2302+ }2303+ }2304+ }2305+ for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {2306+ for (j=0; j < ch; ++j) {2307+ if (!do_not_decode[j]) {2308+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2309+ int c = part_classdata[j][class_set][i];2310+ #else2311+ int c = classifications[j][pcount];2312+ #endif2313+ int b = r->residue_books[c][pass];2314+ if (b >= 0) {2315+ float *target = residue_buffers[j];2316+ int offset = r->begin + pcount * r->part_size;2317+ int n = r->part_size;2318+ Codebook *book = f->codebooks + b;2319+ if (!residue_decode(f, book, target, offset, n, rtype))2320+ goto done;2321+ }2322+ }2323+ }2324+ }2325+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE2326+ ++class_set;2327+ #endif2328+ }2329+ }2330+ done:2331+ stb_prof(0);2332+ temp_alloc_restore(f,temp_alloc_point);2333+}2334+2335+2336+#if 02337+// slow way for debugging2338+void inverse_mdct_slow(float *buffer, int n)2339+{2340+ int i,j;2341+ int n2 = n >> 1;2342+ float *x = (float *) malloc(sizeof(*x) * n2);2343+ memcpy(x, buffer, sizeof(*x) * n2);2344+ for (i=0; i < n; ++i) {2345+ float acc = 0;2346+ for (j=0; j < n2; ++j)2347+ // formula from paper:2348+ //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));2349+ // formula from wikipedia2350+ //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));2351+ // these are equivalent, except the formula from the paper inverts the multiplier!2352+ // however, what actually works is NO MULTIPLIER!?!2353+ //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));2354+ acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));2355+ buffer[i] = acc;2356+ }2357+ free(x);2358+}2359+#elif 02360+// same as above, but just barely able to run in real time on modern machines2361+void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)2362+{2363+ float mcos[16384];2364+ int i,j;2365+ int n2 = n >> 1, nmask = (n << 2) -1;2366+ float *x = (float *) malloc(sizeof(*x) * n2);2367+ memcpy(x, buffer, sizeof(*x) * n2);2368+ for (i=0; i < 4*n; ++i)2369+ mcos[i] = (float) cos(M_PI / 2 * i / n);2370+2371+ for (i=0; i < n; ++i) {2372+ float acc = 0;2373+ for (j=0; j < n2; ++j)2374+ acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];2375+ buffer[i] = acc;2376+ }2377+ free(x);2378+}2379+#elif 02380+// transform to use a slow dct-iv; this is STILL basically trivial,2381+// but only requires half as many ops2382+void dct_iv_slow(float *buffer, int n)2383+{2384+ float mcos[16384];2385+ float x[2048];2386+ int i,j;2387+ int n2 = n >> 1, nmask = (n << 3) - 1;2388+ memcpy(x, buffer, sizeof(*x) * n);2389+ for (i=0; i < 8*n; ++i)2390+ mcos[i] = (float) cos(M_PI / 4 * i / n);2391+ for (i=0; i < n; ++i) {2392+ float acc = 0;2393+ for (j=0; j < n; ++j)2394+ acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];2395+ buffer[i] = acc;2396+ }2397+}2398+2399+void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)2400+{2401+ int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;2402+ float temp[4096];2403+2404+ memcpy(temp, buffer, n2 * sizeof(float));2405+ dct_iv_slow(temp, n2); // returns -c'-d, a-b'2406+2407+ for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'2408+ for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'2409+ for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d2410+}2411+#endif2412+2413+#ifndef LIBVORBIS_MDCT2414+#define LIBVORBIS_MDCT 02415+#endif2416+2417+#if LIBVORBIS_MDCT2418+// directly call the vorbis MDCT using an interface documented2419+// by Jeff Roberts... useful for performance comparison2420+typedef struct 2421+{2422+ int n;2423+ int log2n;2424+ 2425+ float *trig;2426+ int *bitrev;2427+2428+ float scale;2429+} mdct_lookup;2430+2431+extern void mdct_init(mdct_lookup *lookup, int n);2432+extern void mdct_clear(mdct_lookup *l);2433+extern void mdct_backward(mdct_lookup *init, float *in, float *out);2434+2435+mdct_lookup M1,M2;2436+2437+void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)2438+{2439+ mdct_lookup *M;2440+ if (M1.n == n) M = &M1;2441+ else if (M2.n == n) M = &M2;2442+ else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }2443+ else { 2444+ if (M2.n) __asm int 3;2445+ mdct_init(&M2, n);2446+ M = &M2;2447+ }2448+2449+ mdct_backward(M, buffer, buffer);2450+}2451+#endif2452+2453+2454+// the following were split out into separate functions while optimizing;2455+// they could be pushed back up but eh. __forceinline showed no change;2456+// they're probably already being inlined.2457+static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)2458+{2459+ float *ee0 = e + i_off;2460+ float *ee2 = ee0 + k_off;2461+ int i;2462+2463+ assert((n & 3) == 0);2464+ for (i=(n>>2); i > 0; --i) {2465+ float k00_20, k01_21;2466+ k00_20 = ee0[ 0] - ee2[ 0];2467+ k01_21 = ee0[-1] - ee2[-1];2468+ ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];2469+ ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];2470+ ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];2471+ ee2[-1] = k01_21 * A[0] + k00_20 * A[1];2472+ A += 8;2473+2474+ k00_20 = ee0[-2] - ee2[-2];2475+ k01_21 = ee0[-3] - ee2[-3];2476+ ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];2477+ ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];2478+ ee2[-2] = k00_20 * A[0] - k01_21 * A[1];2479+ ee2[-3] = k01_21 * A[0] + k00_20 * A[1];2480+ A += 8;2481+2482+ k00_20 = ee0[-4] - ee2[-4];2483+ k01_21 = ee0[-5] - ee2[-5];2484+ ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];2485+ ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];2486+ ee2[-4] = k00_20 * A[0] - k01_21 * A[1];2487+ ee2[-5] = k01_21 * A[0] + k00_20 * A[1];2488+ A += 8;2489+2490+ k00_20 = ee0[-6] - ee2[-6];2491+ k01_21 = ee0[-7] - ee2[-7];2492+ ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];2493+ ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];2494+ ee2[-6] = k00_20 * A[0] - k01_21 * A[1];2495+ ee2[-7] = k01_21 * A[0] + k00_20 * A[1];2496+ A += 8;2497+ ee0 -= 8;2498+ ee2 -= 8;2499+ }2500+}2501+2502+static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)2503+{2504+ int i;2505+ float k00_20, k01_21;2506+2507+ float *e0 = e + d0;2508+ float *e2 = e0 + k_off;2509+2510+ for (i=lim >> 2; i > 0; --i) {2511+ k00_20 = e0[-0] - e2[-0];2512+ k01_21 = e0[-1] - e2[-1];2513+ e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];2514+ e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];2515+ e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];2516+ e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];2517+2518+ A += k1;2519+2520+ k00_20 = e0[-2] - e2[-2];2521+ k01_21 = e0[-3] - e2[-3];2522+ e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];2523+ e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];2524+ e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];2525+ e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];2526+2527+ A += k1;2528+2529+ k00_20 = e0[-4] - e2[-4];2530+ k01_21 = e0[-5] - e2[-5];2531+ e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];2532+ e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];2533+ e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];2534+ e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];2535+2536+ A += k1;2537+2538+ k00_20 = e0[-6] - e2[-6];2539+ k01_21 = e0[-7] - e2[-7];2540+ e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];2541+ e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];2542+ e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];2543+ e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];2544+2545+ e0 -= 8;2546+ e2 -= 8;2547+2548+ A += k1;2549+ }2550+}2551+2552+static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)2553+{2554+ int i;2555+ float A0 = A[0];2556+ float A1 = A[0+1];2557+ float A2 = A[0+a_off];2558+ float A3 = A[0+a_off+1];2559+ float A4 = A[0+a_off*2+0];2560+ float A5 = A[0+a_off*2+1];2561+ float A6 = A[0+a_off*3+0];2562+ float A7 = A[0+a_off*3+1];2563+2564+ float k00,k11;2565+2566+ float *ee0 = e +i_off;2567+ float *ee2 = ee0+k_off;2568+2569+ for (i=n; i > 0; --i) {2570+ k00 = ee0[ 0] - ee2[ 0];2571+ k11 = ee0[-1] - ee2[-1];2572+ ee0[ 0] = ee0[ 0] + ee2[ 0];2573+ ee0[-1] = ee0[-1] + ee2[-1];2574+ ee2[ 0] = (k00) * A0 - (k11) * A1;2575+ ee2[-1] = (k11) * A0 + (k00) * A1;2576+2577+ k00 = ee0[-2] - ee2[-2];2578+ k11 = ee0[-3] - ee2[-3];2579+ ee0[-2] = ee0[-2] + ee2[-2];2580+ ee0[-3] = ee0[-3] + ee2[-3];2581+ ee2[-2] = (k00) * A2 - (k11) * A3;2582+ ee2[-3] = (k11) * A2 + (k00) * A3;2583+2584+ k00 = ee0[-4] - ee2[-4];2585+ k11 = ee0[-5] - ee2[-5];2586+ ee0[-4] = ee0[-4] + ee2[-4];2587+ ee0[-5] = ee0[-5] + ee2[-5];2588+ ee2[-4] = (k00) * A4 - (k11) * A5;2589+ ee2[-5] = (k11) * A4 + (k00) * A5;2590+2591+ k00 = ee0[-6] - ee2[-6];2592+ k11 = ee0[-7] - ee2[-7];2593+ ee0[-6] = ee0[-6] + ee2[-6];2594+ ee0[-7] = ee0[-7] + ee2[-7];2595+ ee2[-6] = (k00) * A6 - (k11) * A7;2596+ ee2[-7] = (k11) * A6 + (k00) * A7;2597+2598+ ee0 -= k0;2599+ ee2 -= k0;2600+ }2601+}2602+2603+static __forceinline void iter_54(float *z)2604+{2605+ float k00,k11,k22,k33;2606+ float y0,y1,y2,y3;2607+2608+ k00 = z[ 0] - z[-4];2609+ y0 = z[ 0] + z[-4];2610+ y2 = z[-2] + z[-6];2611+ k22 = z[-2] - z[-6];2612+2613+ z[-0] = y0 + y2; // z0 + z4 + z2 + z62614+ z[-2] = y0 - y2; // z0 + z4 - z2 - z62615+2616+ // done with y0,y22617+2618+ k33 = z[-3] - z[-7];2619+2620+ z[-4] = k00 + k33; // z0 - z4 + z3 - z72621+ z[-6] = k00 - k33; // z0 - z4 - z3 + z72622+2623+ // done with k332624+2625+ k11 = z[-1] - z[-5];2626+ y1 = z[-1] + z[-5];2627+ y3 = z[-3] + z[-7];2628+2629+ z[-1] = y1 + y3; // z1 + z5 + z3 + z72630+ z[-3] = y1 - y3; // z1 + z5 - z3 - z72631+ z[-5] = k11 - k22; // z1 - z5 + z2 - z62632+ z[-7] = k11 + k22; // z1 - z5 - z2 + z62633+}2634+2635+static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)2636+{2637+ int a_off = base_n >> 3;2638+ float A2 = A[0+a_off];2639+ float *z = e + i_off;2640+ float *base = z - 16 * n;2641+2642+ while (z > base) {2643+ float k00,k11;2644+2645+ k00 = z[-0] - z[-8];2646+ k11 = z[-1] - z[-9];2647+ z[-0] = z[-0] + z[-8];2648+ z[-1] = z[-1] + z[-9];2649+ z[-8] = k00;2650+ z[-9] = k11 ;2651+2652+ k00 = z[ -2] - z[-10];2653+ k11 = z[ -3] - z[-11];2654+ z[ -2] = z[ -2] + z[-10];2655+ z[ -3] = z[ -3] + z[-11];2656+ z[-10] = (k00+k11) * A2;2657+ z[-11] = (k11-k00) * A2;2658+2659+ k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation2660+ k11 = z[ -5] - z[-13];2661+ z[ -4] = z[ -4] + z[-12];2662+ z[ -5] = z[ -5] + z[-13];2663+ z[-12] = k11;2664+ z[-13] = k00;2665+2666+ k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation2667+ k11 = z[ -7] - z[-15];2668+ z[ -6] = z[ -6] + z[-14];2669+ z[ -7] = z[ -7] + z[-15];2670+ z[-14] = (k00+k11) * A2;2671+ z[-15] = (k00-k11) * A2;2672+2673+ iter_54(z);2674+ iter_54(z-8);2675+ z -= 16;2676+ }2677+}2678+2679+static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)2680+{2681+ int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;2682+ int ld;2683+ // @OPTIMIZE: reduce register pressure by using fewer variables?2684+ int save_point = temp_alloc_save(f);2685+ float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));2686+ float *u=NULL,*v=NULL;2687+ // twiddle factors2688+ float *A = f->A[blocktype];2689+2690+ // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"2691+ // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.2692+2693+ // kernel from paper2694+2695+2696+ // merged:2697+ // copy and reflect spectral data2698+ // step 02699+2700+ // note that it turns out that the items added together during2701+ // this step are, in fact, being added to themselves (as reflected2702+ // by step 0). inexplicable inefficiency! this became obvious2703+ // once I combined the passes.2704+2705+ // so there's a missing 'times 2' here (for adding X to itself).2706+ // this propogates through linearly to the end, where the numbers2707+ // are 1/2 too small, and need to be compensated for.2708+2709+ {2710+ float *d,*e, *AA, *e_stop;2711+ d = &buf2[n2-2];2712+ AA = A;2713+ e = &buffer[0];2714+ e_stop = &buffer[n2];2715+ while (e != e_stop) {2716+ d[1] = (e[0] * AA[0] - e[2]*AA[1]);2717+ d[0] = (e[0] * AA[1] + e[2]*AA[0]);2718+ d -= 2;2719+ AA += 2;2720+ e += 4;2721+ }2722+2723+ e = &buffer[n2-3];2724+ while (d >= buf2) {2725+ d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);2726+ d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);2727+ d -= 2;2728+ AA += 2;2729+ e -= 4;2730+ }2731+ }2732+2733+ // now we use symbolic names for these, so that we can2734+ // possibly swap their meaning as we change which operations2735+ // are in place2736+2737+ u = buffer;2738+ v = buf2;2739+2740+ // step 2 (paper output is w, now u)2741+ // this could be in place, but the data ends up in the wrong2742+ // place... _somebody_'s got to swap it, so this is nominated2743+ {2744+ float *AA = &A[n2-8];2745+ float *d0,*d1, *e0, *e1;2746+2747+ e0 = &v[n4];2748+ e1 = &v[0];2749+2750+ d0 = &u[n4];2751+ d1 = &u[0];2752+2753+ while (AA >= A) {2754+ float v40_20, v41_21;2755+2756+ v41_21 = e0[1] - e1[1];2757+ v40_20 = e0[0] - e1[0];2758+ d0[1] = e0[1] + e1[1];2759+ d0[0] = e0[0] + e1[0];2760+ d1[1] = v41_21*AA[4] - v40_20*AA[5];2761+ d1[0] = v40_20*AA[4] + v41_21*AA[5];2762+2763+ v41_21 = e0[3] - e1[3];2764+ v40_20 = e0[2] - e1[2];2765+ d0[3] = e0[3] + e1[3];2766+ d0[2] = e0[2] + e1[2];2767+ d1[3] = v41_21*AA[0] - v40_20*AA[1];2768+ d1[2] = v40_20*AA[0] + v41_21*AA[1];2769+2770+ AA -= 8;2771+2772+ d0 += 4;2773+ d1 += 4;2774+ e0 += 4;2775+ e1 += 4;2776+ }2777+ }2778+2779+ // step 32780+ ld = ilog(n) - 1; // ilog is off-by-one from normal definitions2781+2782+ // optimized step 3:2783+2784+ // the original step3 loop can be nested r inside s or s inside r;2785+ // it's written originally as s inside r, but this is dumb when r2786+ // iterates many times, and s few. So I have two copies of it and2787+ // switch between them halfway.2788+2789+ // this is iteration 0 of step 32790+ imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);2791+ imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);2792+2793+ // this is iteration 1 of step 32794+ imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);2795+ imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);2796+ imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);2797+ imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);2798+2799+ l=2;2800+ for (; l < (ld-3)>>1; ++l) {2801+ int k0 = n >> (l+2), k0_2 = k0>>1;2802+ int lim = 1 << (l+1);2803+ int i;2804+ for (i=0; i < lim; ++i)2805+ imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));2806+ }2807+2808+ for (; l < ld-6; ++l) {2809+ int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;2810+ int rlim = n >> (l+6), r;2811+ int lim = 1 << (l+1);2812+ int i_off;2813+ float *A0 = A;2814+ i_off = n2-1;2815+ for (r=rlim; r > 0; --r) {2816+ imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);2817+ A0 += k1*4;2818+ i_off -= 8;2819+ }2820+ }2821+2822+ // iterations with count:2823+ // ld-6,-5,-4 all interleaved together2824+ // the big win comes from getting rid of needless flops2825+ // due to the constants on pass 5 & 4 being all 1 and 0;2826+ // combining them to be simultaneous to improve cache made little difference2827+ imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);2828+2829+ // output is u2830+2831+ // step 4, 5, and 62832+ // cannot be in-place because of step 52833+ {2834+ uint16 *bitrev = f->bit_reverse[blocktype];2835+ // weirdly, I'd have thought reading sequentially and writing2836+ // erratically would have been better than vice-versa, but in2837+ // fact that's not what my testing showed. (That is, with2838+ // j = bitreverse(i), do you read i and write j, or read j and write i.)2839+2840+ float *d0 = &v[n4-4];2841+ float *d1 = &v[n2-4];2842+ while (d0 >= v) {2843+ int k4;2844+2845+ k4 = bitrev[0];2846+ d1[3] = u[k4+0];2847+ d1[2] = u[k4+1];2848+ d0[3] = u[k4+2];2849+ d0[2] = u[k4+3];2850+2851+ k4 = bitrev[1];2852+ d1[1] = u[k4+0];2853+ d1[0] = u[k4+1];2854+ d0[1] = u[k4+2];2855+ d0[0] = u[k4+3];2856+ 2857+ d0 -= 4;2858+ d1 -= 4;2859+ bitrev += 2;2860+ }2861+ }2862+ // (paper output is u, now v)2863+2864+2865+ // data must be in buf22866+ assert(v == buf2);2867+2868+ // step 7 (paper output is v, now v)2869+ // this is now in place2870+ {2871+ float *C = f->C[blocktype];2872+ float *d, *e;2873+2874+ d = v;2875+ e = v + n2 - 4;2876+2877+ while (d < e) {2878+ float a02,a11,b0,b1,b2,b3;2879+2880+ a02 = d[0] - e[2];2881+ a11 = d[1] + e[3];2882+2883+ b0 = C[1]*a02 + C[0]*a11;2884+ b1 = C[1]*a11 - C[0]*a02;2885+2886+ b2 = d[0] + e[ 2];2887+ b3 = d[1] - e[ 3];2888+2889+ d[0] = b2 + b0;2890+ d[1] = b3 + b1;2891+ e[2] = b2 - b0;2892+ e[3] = b1 - b3;2893+2894+ a02 = d[2] - e[0];2895+ a11 = d[3] + e[1];2896+2897+ b0 = C[3]*a02 + C[2]*a11;2898+ b1 = C[3]*a11 - C[2]*a02;2899+2900+ b2 = d[2] + e[ 0];2901+ b3 = d[3] - e[ 1];2902+2903+ d[2] = b2 + b0;2904+ d[3] = b3 + b1;2905+ e[0] = b2 - b0;2906+ e[1] = b1 - b3;2907+2908+ C += 4;2909+ d += 4;2910+ e -= 4;2911+ }2912+ }2913+2914+ // data must be in buf22915+2916+2917+ // step 8+decode (paper output is X, now buffer)2918+ // this generates pairs of data a la 8 and pushes them directly through2919+ // the decode kernel (pushing rather than pulling) to avoid having2920+ // to make another pass later2921+2922+ // this cannot POSSIBLY be in place, so we refer to the buffers directly2923+2924+ {2925+ float *d0,*d1,*d2,*d3;2926+2927+ float *B = f->B[blocktype] + n2 - 8;2928+ float *e = buf2 + n2 - 8;2929+ d0 = &buffer[0];2930+ d1 = &buffer[n2-4];2931+ d2 = &buffer[n2];2932+ d3 = &buffer[n-4];2933+ while (e >= v) {2934+ float p0,p1,p2,p3;2935+2936+ p3 = e[6]*B[7] - e[7]*B[6];2937+ p2 = -e[6]*B[6] - e[7]*B[7]; 2938+2939+ d0[0] = p3;2940+ d1[3] = - p3;2941+ d2[0] = p2;2942+ d3[3] = p2;2943+2944+ p1 = e[4]*B[5] - e[5]*B[4];2945+ p0 = -e[4]*B[4] - e[5]*B[5]; 2946+2947+ d0[1] = p1;2948+ d1[2] = - p1;2949+ d2[1] = p0;2950+ d3[2] = p0;2951+2952+ p3 = e[2]*B[3] - e[3]*B[2];2953+ p2 = -e[2]*B[2] - e[3]*B[3]; 2954+2955+ d0[2] = p3;2956+ d1[1] = - p3;2957+ d2[2] = p2;2958+ d3[1] = p2;2959+2960+ p1 = e[0]*B[1] - e[1]*B[0];2961+ p0 = -e[0]*B[0] - e[1]*B[1]; 2962+2963+ d0[3] = p1;2964+ d1[0] = - p1;2965+ d2[3] = p0;2966+ d3[0] = p0;2967+2968+ B -= 8;2969+ e -= 8;2970+ d0 += 4;2971+ d2 += 4;2972+ d1 -= 4;2973+ d3 -= 4;2974+ }2975+ }2976+2977+ temp_alloc_restore(f,save_point);2978+}2979+2980+#if 02981+// this is the original version of the above code, if you want to optimize it from scratch2982+void inverse_mdct_naive(float *buffer, int n)2983+{2984+ float s;2985+ float A[1 << 12], B[1 << 12], C[1 << 11];2986+ int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;2987+ int n3_4 = n - n4, ld;2988+ // how can they claim this only uses N words?!2989+ // oh, because they're only used sparsely, whoops2990+ float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];2991+ // set up twiddle factors2992+2993+ for (k=k2=0; k < n4; ++k,k2+=2) {2994+ A[k2 ] = (float) cos(4*k*M_PI/n);2995+ A[k2+1] = (float) -sin(4*k*M_PI/n);2996+ B[k2 ] = (float) cos((k2+1)*M_PI/n/2);2997+ B[k2+1] = (float) sin((k2+1)*M_PI/n/2);2998+ }2999+ for (k=k2=0; k < n8; ++k,k2+=2) {3000+ C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);3001+ C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);3002+ }3003+3004+ // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"3005+ // Note there are bugs in that pseudocode, presumably due to them attempting3006+ // to rename the arrays nicely rather than representing the way their actual3007+ // implementation bounces buffers back and forth. As a result, even in the3008+ // "some formulars corrected" version, a direct implementation fails. These3009+ // are noted below as "paper bug".3010+3011+ // copy and reflect spectral data3012+ for (k=0; k < n2; ++k) u[k] = buffer[k];3013+ for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];3014+ // kernel from paper3015+ // step 13016+ for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {3017+ v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];3018+ v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];3019+ }3020+ // step 23021+ for (k=k4=0; k < n8; k+=1, k4+=4) {3022+ w[n2+3+k4] = v[n2+3+k4] + v[k4+3];3023+ w[n2+1+k4] = v[n2+1+k4] + v[k4+1];3024+ 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];3025+ 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];3026+ }3027+ // step 33028+ ld = ilog(n) - 1; // ilog is off-by-one from normal definitions3029+ for (l=0; l < ld-3; ++l) {3030+ int k0 = n >> (l+2), k1 = 1 << (l+3);3031+ int rlim = n >> (l+4), r4, r;3032+ int s2lim = 1 << (l+2), s2;3033+ for (r=r4=0; r < rlim; r4+=4,++r) {3034+ for (s2=0; s2 < s2lim; s2+=2) {3035+ u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];3036+ u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];3037+ u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]3038+ - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];3039+ u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]3040+ + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];3041+ }3042+ }3043+ if (l+1 < ld-3) {3044+ // paper bug: ping-ponging of u&w here is omitted3045+ memcpy(w, u, sizeof(u));3046+ }3047+ }3048+3049+ // step 43050+ for (i=0; i < n8; ++i) {3051+ int j = bit_reverse(i) >> (32-ld+3);3052+ assert(j < n8);3053+ if (i == j) {3054+ // paper bug: original code probably swapped in place; if copying,3055+ // need to directly copy in this case3056+ int i8 = i << 3;3057+ v[i8+1] = u[i8+1];3058+ v[i8+3] = u[i8+3];3059+ v[i8+5] = u[i8+5];3060+ v[i8+7] = u[i8+7];3061+ } else if (i < j) {3062+ int i8 = i << 3, j8 = j << 3;3063+ v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];3064+ v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];3065+ v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];3066+ v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];3067+ }3068+ }3069+ // step 53070+ for (k=0; k < n2; ++k) {3071+ w[k] = v[k*2+1];3072+ }3073+ // step 63074+ for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {3075+ u[n-1-k2] = w[k4];3076+ u[n-2-k2] = w[k4+1];3077+ u[n3_4 - 1 - k2] = w[k4+2];3078+ u[n3_4 - 2 - k2] = w[k4+3];3079+ }3080+ // step 73081+ for (k=k2=0; k < n8; ++k, k2 += 2) {3082+ 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;3083+ 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;3084+ 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;3085+ 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;3086+ }3087+ // step 83088+ for (k=k2=0; k < n4; ++k,k2 += 2) {3089+ X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];3090+ X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];3091+ }3092+3093+ // decode kernel to output3094+ // determined the following value experimentally3095+ // (by first figuring out what made inverse_mdct_slow work); then matching that here3096+ // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)3097+ s = 0.5; // theoretically would be n43098+3099+ // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,3100+ // so it needs to use the "old" B values to behave correctly, or else3101+ // set s to 1.0 ]]]3102+ for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];3103+ for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];3104+ for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];3105+}3106+#endif3107+3108+static float *get_window(vorb *f, int len)3109+{3110+ len <<= 1;3111+ if (len == f->blocksize_0) return f->window[0];3112+ if (len == f->blocksize_1) return f->window[1];3113+ assert(0);3114+ return NULL;3115+}3116+3117+#ifndef STB_VORBIS_NO_DEFER_FLOOR3118+typedef int16 YTYPE;3119+#else3120+typedef int YTYPE;3121+#endif3122+static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)3123+{3124+ int n2 = n >> 1;3125+ int s = map->chan[i].mux, floor;3126+ floor = map->submap_floor[s];3127+ if (f->floor_types[floor] == 0) {3128+ return error(f, VORBIS_invalid_stream);3129+ } else {3130+ Floor1 *g = &f->floor_config[floor].floor1;3131+ int j,q;3132+ int lx = 0, ly = finalY[0] * g->floor1_multiplier;3133+ for (q=1; q < g->values; ++q) {3134+ j = g->sorted_order[q];3135+ #ifndef STB_VORBIS_NO_DEFER_FLOOR3136+ if (finalY[j] >= 0)3137+ #else3138+ if (step2_flag[j])3139+ #endif3140+ {3141+ int hy = finalY[j] * g->floor1_multiplier;3142+ int hx = g->Xlist[j];3143+ draw_line(target, lx,ly, hx,hy, n2);3144+ lx = hx, ly = hy;3145+ }3146+ }3147+ if (lx < n2)3148+ // optimization of: draw_line(target, lx,ly, n,ly, n2);3149+ for (j=lx; j < n2; ++j)3150+ LINE_OP(target[j], inverse_db_table[ly]);3151+ }3152+ return TRUE;3153+}3154+3155+// The meaning of "left" and "right"3156+//3157+// For a given frame:3158+// we compute samples from 0..n3159+// window_center is n/23160+// we'll window and mix the samples from left_start to left_end with data from the previous frame3161+// all of the samples from left_end to right_start can be output without mixing; however,3162+// this interval is 0-length except when transitioning between short and long frames3163+// all of the samples from right_start to right_end need to be mixed with the next frame,3164+// which we don't have, so those get saved in a buffer3165+// frame N's right_end-right_start, the number of samples to mix with the next frame,3166+// has to be the same as frame N+1's left_end-left_start (which they are by3167+// construction)3168+3169+static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)3170+{3171+ Mode *m;3172+ int i, n, prev, next, window_center;3173+ f->channel_buffer_start = f->channel_buffer_end = 0;3174+3175+ retry:3176+ if (f->eof) return FALSE;3177+ if (!maybe_start_packet(f))3178+ return FALSE;3179+ // check packet type3180+ if (get_bits(f,1) != 0) {3181+ if (IS_PUSH_MODE(f))3182+ return error(f,VORBIS_bad_packet_type);3183+ while (EOP != get8_packet(f));3184+ goto retry;3185+ }3186+3187+ if (f->alloc.alloc_buffer)3188+ assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);3189+3190+ i = get_bits(f, ilog(f->mode_count-1));3191+ if (i == EOP) return FALSE;3192+ if (i >= f->mode_count) return FALSE;3193+ *mode = i;3194+ m = f->mode_config + i;3195+ if (m->blockflag) {3196+ n = f->blocksize_1;3197+ prev = get_bits(f,1);3198+ next = get_bits(f,1);3199+ } else {3200+ prev = next = 0;3201+ n = f->blocksize_0;3202+ }3203+3204+// WINDOWING3205+3206+ window_center = n >> 1;3207+ if (m->blockflag && !prev) {3208+ *p_left_start = (n - f->blocksize_0) >> 2;3209+ *p_left_end = (n + f->blocksize_0) >> 2;3210+ } else {3211+ *p_left_start = 0;3212+ *p_left_end = window_center;3213+ }3214+ if (m->blockflag && !next) {3215+ *p_right_start = (n*3 - f->blocksize_0) >> 2;3216+ *p_right_end = (n*3 + f->blocksize_0) >> 2;3217+ } else {3218+ *p_right_start = window_center;3219+ *p_right_end = n;3220+ }3221+ return TRUE;3222+}3223+3224+static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)3225+{3226+ Mapping *map;3227+ int i,j,k,n,n2;3228+ int zero_channel[256];3229+ int really_zero_channel[256];3230+3231+// WINDOWING3232+3233+ n = f->blocksize[m->blockflag];3234+ map = &f->mapping[m->mapping];3235+3236+// FLOORS3237+ n2 = n >> 1;3238+3239+ stb_prof(1);3240+ for (i=0; i < f->channels; ++i) {3241+ int s = map->chan[i].mux, floor;3242+ zero_channel[i] = FALSE;3243+ floor = map->submap_floor[s];3244+ if (f->floor_types[floor] == 0) {3245+ return error(f, VORBIS_invalid_stream);3246+ } else {3247+ Floor1 *g = &f->floor_config[floor].floor1;3248+ if (get_bits(f, 1)) {3249+ short *finalY;3250+ uint8 step2_flag[256];3251+ static int range_list[4] = { 256, 128, 86, 64 };3252+ int range = range_list[g->floor1_multiplier-1];3253+ int offset = 2;3254+ finalY = f->finalY[i];3255+ finalY[0] = get_bits(f, ilog(range)-1);3256+ finalY[1] = get_bits(f, ilog(range)-1);3257+ for (j=0; j < g->partitions; ++j) {3258+ int pclass = g->partition_class_list[j];3259+ int cdim = g->class_dimensions[pclass];3260+ int cbits = g->class_subclasses[pclass];3261+ int csub = (1 << cbits)-1;3262+ int cval = 0;3263+ if (cbits) {3264+ Codebook *c = f->codebooks + g->class_masterbooks[pclass];3265+ DECODE(cval,f,c);3266+ }3267+ for (k=0; k < cdim; ++k) {3268+ int book = g->subclass_books[pclass][cval & csub];3269+ cval = cval >> cbits;3270+ if (book >= 0) {3271+ int temp;3272+ Codebook *c = f->codebooks + book;3273+ DECODE(temp,f,c);3274+ finalY[offset++] = temp;3275+ } else3276+ finalY[offset++] = 0;3277+ }3278+ }3279+ if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec3280+ step2_flag[0] = step2_flag[1] = 1;3281+ for (j=2; j < g->values; ++j) {3282+ int low, high, pred, highroom, lowroom, room, val;3283+ low = g->neighbors[j][0];3284+ high = g->neighbors[j][1];3285+ //neighbors(g->Xlist, j, &low, &high);3286+ pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);3287+ val = finalY[j];3288+ highroom = range - pred;3289+ lowroom = pred;3290+ if (highroom < lowroom)3291+ room = highroom * 2;3292+ else3293+ room = lowroom * 2;3294+ if (val) {3295+ step2_flag[low] = step2_flag[high] = 1;3296+ step2_flag[j] = 1;3297+ if (val >= room)3298+ if (highroom > lowroom)3299+ finalY[j] = val - lowroom + pred;3300+ else3301+ finalY[j] = pred - val + highroom - 1;3302+ else3303+ if (val & 1)3304+ finalY[j] = pred - ((val+1)>>1);3305+ else3306+ finalY[j] = pred + (val>>1);3307+ } else {3308+ step2_flag[j] = 0;3309+ finalY[j] = pred;3310+ }3311+ }3312+3313+#ifdef STB_VORBIS_NO_DEFER_FLOOR3314+ do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);3315+#else3316+ // defer final floor computation until _after_ residue3317+ for (j=0; j < g->values; ++j) {3318+ if (!step2_flag[j])3319+ finalY[j] = -1;3320+ }3321+#endif3322+ } else {3323+ error:3324+ zero_channel[i] = TRUE;3325+ }3326+ // So we just defer everything else to later3327+3328+ // at this point we've decoded the floor into buffer3329+ }3330+ }3331+ stb_prof(0);3332+ // at this point we've decoded all floors3333+3334+ if (f->alloc.alloc_buffer)3335+ assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);3336+3337+ // re-enable coupled channels if necessary3338+ memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);3339+ for (i=0; i < map->coupling_steps; ++i)3340+ if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {3341+ zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;3342+ }3343+3344+// RESIDUE DECODE3345+ for (i=0; i < map->submaps; ++i) {3346+ float *residue_buffers[STB_VORBIS_MAX_CHANNELS];3347+ int r;3348+ uint8 do_not_decode[256];3349+ int ch = 0;3350+ for (j=0; j < f->channels; ++j) {3351+ if (map->chan[j].mux == i) {3352+ if (zero_channel[j]) {3353+ do_not_decode[ch] = TRUE;3354+ residue_buffers[ch] = NULL;3355+ } else {3356+ do_not_decode[ch] = FALSE;3357+ residue_buffers[ch] = f->channel_buffers[j];3358+ }3359+ ++ch;3360+ }3361+ }3362+ r = map->submap_residue[i];3363+ decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);3364+ }3365+3366+ if (f->alloc.alloc_buffer)3367+ assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);3368+3369+// INVERSE COUPLING3370+ stb_prof(14);3371+ for (i = map->coupling_steps-1; i >= 0; --i) {3372+ int n2 = n >> 1;3373+ float *m = f->channel_buffers[map->chan[i].magnitude];3374+ float *a = f->channel_buffers[map->chan[i].angle ];3375+ for (j=0; j < n2; ++j) {3376+ float a2,m2;3377+ if (m[j] > 0)3378+ if (a[j] > 0)3379+ m2 = m[j], a2 = m[j] - a[j];3380+ else3381+ a2 = m[j], m2 = m[j] + a[j];3382+ else3383+ if (a[j] > 0)3384+ m2 = m[j], a2 = m[j] + a[j];3385+ else3386+ a2 = m[j], m2 = m[j] - a[j];3387+ m[j] = m2;3388+ a[j] = a2;3389+ }3390+ }3391+3392+ // finish decoding the floors3393+#ifndef STB_VORBIS_NO_DEFER_FLOOR3394+ stb_prof(15);3395+ for (i=0; i < f->channels; ++i) {3396+ if (really_zero_channel[i]) {3397+ memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);3398+ } else {3399+ do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);3400+ }3401+ }3402+#else3403+ for (i=0; i < f->channels; ++i) {3404+ if (really_zero_channel[i]) {3405+ memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);3406+ } else {3407+ for (j=0; j < n2; ++j)3408+ f->channel_buffers[i][j] *= f->floor_buffers[i][j];3409+ }3410+ }3411+#endif3412+3413+// INVERSE MDCT3414+ stb_prof(16);3415+ for (i=0; i < f->channels; ++i)3416+ inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);3417+ stb_prof(0);3418+3419+ // this shouldn't be necessary, unless we exited on an error3420+ // and want to flush to get to the next packet3421+ flush_packet(f);3422+3423+ if (f->first_decode) {3424+ // assume we start so first non-discarded sample is sample 03425+ // this isn't to spec, but spec would require us to read ahead3426+ // and decode the size of all current frames--could be done,3427+ // but presumably it's not a commonly used feature3428+ f->current_loc = -n2; // start of first frame is positioned for discard3429+ // we might have to discard samples "from" the next frame too,3430+ // if we're lapping a large block then a small at the start?3431+ f->discard_samples_deferred = n - right_end;3432+ f->current_loc_valid = TRUE;3433+ f->first_decode = FALSE;3434+ } else if (f->discard_samples_deferred) {3435+ left_start += f->discard_samples_deferred;3436+ *p_left = left_start;3437+ f->discard_samples_deferred = 0;3438+ } else if (f->previous_length == 0 && f->current_loc_valid) {3439+ // we're recovering from a seek... that means we're going to discard3440+ // the samples from this packet even though we know our position from3441+ // the last page header, so we need to update the position based on3442+ // the discarded samples here3443+ // but wait, the code below is going to add this in itself even3444+ // on a discard, so we don't need to do it here...3445+ }3446+3447+ // check if we have ogg information about the sample # for this packet3448+ if (f->last_seg_which == f->end_seg_with_known_loc) {3449+ // if we have a valid current loc, and this is final:3450+ if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {3451+ uint32 current_end = f->known_loc_for_packet - (n-right_end);3452+ // then let's infer the size of the (probably) short final frame3453+ if (current_end < f->current_loc + right_end) {3454+ if (current_end < f->current_loc) {3455+ // negative truncation, that's impossible!3456+ *len = 0;3457+ } else {3458+ *len = current_end - f->current_loc;3459+ }3460+ *len += left_start;3461+ f->current_loc += *len;3462+ return TRUE;3463+ }3464+ }3465+ // otherwise, just set our sample loc3466+ // guess that the ogg granule pos refers to the _middle_ of the3467+ // last frame?3468+ // set f->current_loc to the position of left_start3469+ f->current_loc = f->known_loc_for_packet - (n2-left_start);3470+ f->current_loc_valid = TRUE;3471+ }3472+ if (f->current_loc_valid)3473+ f->current_loc += (right_start - left_start);3474+3475+ if (f->alloc.alloc_buffer)3476+ assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);3477+ *len = right_end; // ignore samples after the window goes to 03478+ return TRUE;3479+}3480+3481+static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)3482+{3483+ int mode, left_end, right_end;3484+ if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;3485+ return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);3486+}3487+3488+static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)3489+{3490+ int prev,i,j;3491+ // we use right&left (the start of the right- and left-window sin()-regions)3492+ // to determine how much to return, rather than inferring from the rules3493+ // (same result, clearer code); 'left' indicates where our sin() window3494+ // starts, therefore where the previous window's right edge starts, and3495+ // therefore where to start mixing from the previous buffer. 'right'3496+ // indicates where our sin() ending-window starts, therefore that's where3497+ // we start saving, and where our returned-data ends.3498+3499+ // mixin from previous window3500+ if (f->previous_length) {3501+ int i,j, n = f->previous_length;3502+ float *w = get_window(f, n);3503+ for (i=0; i < f->channels; ++i) {3504+ for (j=0; j < n; ++j)3505+ f->channel_buffers[i][left+j] =3506+ f->channel_buffers[i][left+j]*w[ j] +3507+ f->previous_window[i][ j]*w[n-1-j];3508+ }3509+ }3510+3511+ prev = f->previous_length;3512+3513+ // last half of this data becomes previous window3514+ f->previous_length = len - right;3515+3516+ // @OPTIMIZE: could avoid this copy by double-buffering the3517+ // output (flipping previous_window with channel_buffers), but3518+ // then previous_window would have to be 2x as large, and3519+ // channel_buffers couldn't be temp mem (although they're NOT3520+ // currently temp mem, they could be (unless we want to level3521+ // performance by spreading out the computation))3522+ for (i=0; i < f->channels; ++i)3523+ for (j=0; right+j < len; ++j)3524+ f->previous_window[i][j] = f->channel_buffers[i][right+j];3525+3526+ if (!prev)3527+ // there was no previous packet, so this data isn't valid...3528+ // this isn't entirely true, only the would-have-overlapped data3529+ // isn't valid, but this seems to be what the spec requires3530+ return 0;3531+3532+ // truncate a short frame3533+ if (len < right) right = len;3534+3535+ f->samples_output += right-left;3536+3537+ return right - left;3538+}3539+3540+static void vorbis_pump_first_frame(stb_vorbis *f)3541+{3542+ int len, right, left;3543+ if (vorbis_decode_packet(f, &len, &left, &right))3544+ vorbis_finish_frame(f, len, left, right);3545+}3546+3547+#ifndef STB_VORBIS_NO_PUSHDATA_API3548+static int is_whole_packet_present(stb_vorbis *f, int end_page)3549+{3550+ // make sure that we have the packet available before continuing...3551+ // this requires a full ogg parse, but we know we can fetch from f->stream3552+3553+ // instead of coding this out explicitly, we could save the current read state,3554+ // read the next packet with get8() until end-of-packet, check f->eof, then3555+ // reset the state? but that would be slower, esp. since we'd have over 256 bytes3556+ // of state to restore (primarily the page segment table)3557+3558+ int s = f->next_seg, first = TRUE;3559+ uint8 *p = f->stream;3560+3561+ if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag3562+ for (; s < f->segment_count; ++s) {3563+ p += f->segments[s];3564+ if (f->segments[s] < 255) // stop at first short segment3565+ break;3566+ }3567+ // either this continues, or it ends it...3568+ if (end_page)3569+ if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream);3570+ if (s == f->segment_count)3571+ s = -1; // set 'crosses page' flag3572+ if (p > f->stream_end) return error(f, VORBIS_need_more_data);3573+ first = FALSE;3574+ }3575+ for (; s == -1;) {3576+ uint8 *q; 3577+ int n;3578+3579+ // check that we have the page header ready3580+ if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);3581+ // validate the page3582+ if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);3583+ if (p[4] != 0) return error(f, VORBIS_invalid_stream);3584+ if (first) { // the first segment must NOT have 'continued_packet', later ones MUST3585+ if (f->previous_length)3586+ if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);3587+ // if no previous length, we're resynching, so we can come in on a continued-packet,3588+ // which we'll just drop3589+ } else {3590+ if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);3591+ }3592+ n = p[26]; // segment counts3593+ q = p+27; // q points to segment table3594+ p = q + n; // advance past header3595+ // make sure we've read the segment table3596+ if (p > f->stream_end) return error(f, VORBIS_need_more_data);3597+ for (s=0; s < n; ++s) {3598+ p += q[s];3599+ if (q[s] < 255)3600+ break;3601+ }3602+ if (end_page)3603+ if (s < n-1) return error(f, VORBIS_invalid_stream);3604+ if (s == n)3605+ s = -1; // set 'crosses page' flag3606+ if (p > f->stream_end) return error(f, VORBIS_need_more_data);3607+ first = FALSE;3608+ }3609+ return TRUE;3610+}3611+#endif // !STB_VORBIS_NO_PUSHDATA_API3612+3613+static int start_decoder(vorb *f)3614+{3615+ uint8 header[6], x,y;3616+ int len,i,j,k, max_submaps = 0;3617+ int longest_floorlist=0;3618+3619+ // first page, first packet3620+3621+ if (!start_page(f)) return FALSE;3622+ // validate page flag3623+ if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);3624+ if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);3625+ if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);3626+ // check for expected packet length3627+ if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);3628+ if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);3629+ // read packet3630+ // check packet header3631+ if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);3632+ if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);3633+ if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);3634+ // vorbis_version3635+ if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);3636+ f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);3637+ if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);3638+ f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);3639+ get32(f); // bitrate_maximum3640+ get32(f); // bitrate_nominal3641+ get32(f); // bitrate_minimum3642+ x = get8(f);3643+ { int log0,log1;3644+ log0 = x & 15;3645+ log1 = x >> 4;3646+ f->blocksize_0 = 1 << log0;3647+ f->blocksize_1 = 1 << log1;3648+ if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);3649+ if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);3650+ if (log0 > log1) return error(f, VORBIS_invalid_setup);3651+ }3652+3653+ // framing_flag3654+ x = get8(f);3655+ if (!(x & 1)) return error(f, VORBIS_invalid_first_page);3656+3657+ // second packet!3658+ if (!start_page(f)) return FALSE;3659+3660+ if (!start_packet(f)) return FALSE;3661+ do {3662+ len = next_segment(f);3663+ skip(f, len);3664+ f->bytes_in_seg = 0;3665+ } while (len);3666+3667+ // third packet!3668+ if (!start_packet(f)) return FALSE;3669+3670+ #ifndef STB_VORBIS_NO_PUSHDATA_API3671+ if (IS_PUSH_MODE(f)) {3672+ if (!is_whole_packet_present(f, TRUE)) {3673+ // convert error in ogg header to write type3674+ if (f->error == VORBIS_invalid_stream)3675+ f->error = VORBIS_invalid_setup;3676+ return FALSE;3677+ }3678+ }3679+ #endif3680+3681+ crc32_init(); // always init it, to avoid multithread race conditions3682+3683+ if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);3684+ for (i=0; i < 6; ++i) header[i] = get8_packet(f);3685+ if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);3686+3687+ // codebooks3688+3689+ f->codebook_count = get_bits(f,8) + 1;3690+ f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);3691+ if (f->codebooks == NULL) return error(f, VORBIS_outofmem);3692+ memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);3693+ for (i=0; i < f->codebook_count; ++i) {3694+ uint32 *values;3695+ int ordered, sorted_count;3696+ int total=0;3697+ uint8 *lengths;3698+ Codebook *c = f->codebooks+i;3699+ x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);3700+ x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);3701+ x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);3702+ x = get_bits(f, 8);3703+ c->dimensions = (get_bits(f, 8)<<8) + x;3704+ x = get_bits(f, 8);3705+ y = get_bits(f, 8);3706+ c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;3707+ ordered = get_bits(f,1);3708+ c->sparse = ordered ? 0 : get_bits(f,1);3709+3710+ if (c->sparse)3711+ lengths = (uint8 *) setup_temp_malloc(f, c->entries);3712+ else3713+ lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);3714+3715+ if (!lengths) return error(f, VORBIS_outofmem);3716+3717+ if (ordered) {3718+ int current_entry = 0;3719+ int current_length = get_bits(f,5) + 1;3720+ while (current_entry < c->entries) {3721+ int limit = c->entries - current_entry;3722+ int n = get_bits(f, ilog(limit));3723+ if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }3724+ memset(lengths + current_entry, current_length, n);3725+ current_entry += n;3726+ ++current_length;3727+ }3728+ } else {3729+ for (j=0; j < c->entries; ++j) {3730+ int present = c->sparse ? get_bits(f,1) : 1;3731+ if (present) {3732+ lengths[j] = get_bits(f, 5) + 1;3733+ ++total;3734+ } else {3735+ lengths[j] = NO_CODE;3736+ }3737+ }3738+ }3739+3740+ if (c->sparse && total >= c->entries >> 2) {3741+ // convert sparse items to non-sparse!3742+ if (c->entries > (int) f->setup_temp_memory_required)3743+ f->setup_temp_memory_required = c->entries;3744+3745+ c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);3746+ memcpy(c->codeword_lengths, lengths, c->entries);3747+ setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!3748+ lengths = c->codeword_lengths;3749+ c->sparse = 0;3750+ }3751+3752+ // compute the size of the sorted tables3753+ if (c->sparse) {3754+ sorted_count = total;3755+ } else {3756+ sorted_count = 0;3757+ #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH3758+ for (j=0; j < c->entries; ++j)3759+ if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)3760+ ++sorted_count;3761+ #endif3762+ }3763+3764+ c->sorted_entries = sorted_count;3765+ values = NULL;3766+3767+ if (!c->sparse) {3768+ c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);3769+ if (!c->codewords) return error(f, VORBIS_outofmem);3770+ } else {3771+ unsigned int size;3772+ if (c->sorted_entries) {3773+ c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);3774+ if (!c->codeword_lengths) return error(f, VORBIS_outofmem);3775+ c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);3776+ if (!c->codewords) return error(f, VORBIS_outofmem);3777+ values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);3778+ if (!values) return error(f, VORBIS_outofmem);3779+ }3780+ size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;3781+ if (size > f->setup_temp_memory_required)3782+ f->setup_temp_memory_required = size;3783+ }3784+3785+ if (!compute_codewords(c, lengths, c->entries, values)) {3786+ if (c->sparse) setup_temp_free(f, values, 0);3787+ return error(f, VORBIS_invalid_setup);3788+ }3789+3790+ if (c->sorted_entries) {3791+ // allocate an extra slot for sentinels3792+ c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));3793+ // allocate an extra slot at the front so that c->sorted_values[-1] is defined3794+ // so that we can catch that case without an extra if3795+ c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));3796+ if (c->sorted_values) { ++c->sorted_values; c->sorted_values[-1] = -1; }3797+ compute_sorted_huffman(c, lengths, values);3798+ }3799+3800+ if (c->sparse) {3801+ setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);3802+ setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);3803+ setup_temp_free(f, lengths, c->entries);3804+ c->codewords = NULL;3805+ }3806+3807+ compute_accelerated_huffman(c);3808+3809+ c->lookup_type = get_bits(f, 4);3810+ if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);3811+ if (c->lookup_type > 0) {3812+ uint16 *mults;3813+ c->minimum_value = float32_unpack(get_bits(f, 32));3814+ c->delta_value = float32_unpack(get_bits(f, 32));3815+ c->value_bits = get_bits(f, 4)+1;3816+ c->sequence_p = get_bits(f,1);3817+ if (c->lookup_type == 1) {3818+ c->lookup_values = lookup1_values(c->entries, c->dimensions);3819+ } else {3820+ c->lookup_values = c->entries * c->dimensions;3821+ }3822+ mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);3823+ if (mults == NULL) return error(f, VORBIS_outofmem);3824+ for (j=0; j < (int) c->lookup_values; ++j) {3825+ int q = get_bits(f, c->value_bits);3826+ if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }3827+ mults[j] = q;3828+ }3829+3830+#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK3831+ if (c->lookup_type == 1) {3832+ int len, sparse = c->sparse;3833+ // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop3834+ if (sparse) {3835+ if (c->sorted_entries == 0) goto skip;3836+ c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);3837+ } else3838+ c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);3839+ if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }3840+ len = sparse ? c->sorted_entries : c->entries;3841+ for (j=0; j < len; ++j) {3842+ int z = sparse ? c->sorted_values[j] : j, div=1;3843+ for (k=0; k < c->dimensions; ++k) {3844+ int off = (z / div) % c->lookup_values;3845+ c->multiplicands[j*c->dimensions + k] =3846+ #ifndef STB_VORBIS_CODEBOOK_FLOATS3847+ mults[off];3848+ #else3849+ mults[off]*c->delta_value + c->minimum_value;3850+ // in this case (and this case only) we could pre-expand c->sequence_p,3851+ // and throw away the decode logic for it; have to ALSO do3852+ // it in the case below, but it can only be done if3853+ // STB_VORBIS_CODEBOOK_FLOATS3854+ // !STB_VORBIS_DIVIDES_IN_CODEBOOK3855+ #endif3856+ div *= c->lookup_values;3857+ }3858+ }3859+ setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);3860+ c->lookup_type = 2;3861+ }3862+ else3863+#endif3864+ {3865+ c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);3866+ #ifndef STB_VORBIS_CODEBOOK_FLOATS3867+ memcpy(c->multiplicands, mults, sizeof(c->multiplicands[0]) * c->lookup_values);3868+ #else3869+ for (j=0; j < (int) c->lookup_values; ++j)3870+ c->multiplicands[j] = mults[j] * c->delta_value + c->minimum_value;3871+ #endif3872+ setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);3873+ }3874+#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK3875+ skip:;3876+#endif3877+3878+ #ifdef STB_VORBIS_CODEBOOK_FLOATS3879+ if (c->lookup_type == 2 && c->sequence_p) {3880+ for (j=1; j < (int) c->lookup_values; ++j)3881+ c->multiplicands[j] = c->multiplicands[j-1];3882+ c->sequence_p = 0;3883+ }3884+ #endif3885+ }3886+ }3887+3888+ // time domain transfers (notused)3889+3890+ x = get_bits(f, 6) + 1;3891+ for (i=0; i < x; ++i) {3892+ uint32 z = get_bits(f, 16);3893+ if (z != 0) return error(f, VORBIS_invalid_setup);3894+ }3895+3896+ // Floors3897+ f->floor_count = get_bits(f, 6)+1;3898+ f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));3899+ for (i=0; i < f->floor_count; ++i) {3900+ f->floor_types[i] = get_bits(f, 16);3901+ if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);3902+ if (f->floor_types[i] == 0) {3903+ Floor0 *g = &f->floor_config[i].floor0;3904+ g->order = get_bits(f,8);3905+ g->rate = get_bits(f,16);3906+ g->bark_map_size = get_bits(f,16);3907+ g->amplitude_bits = get_bits(f,6);3908+ g->amplitude_offset = get_bits(f,8);3909+ g->number_of_books = get_bits(f,4) + 1;3910+ for (j=0; j < g->number_of_books; ++j)3911+ g->book_list[j] = get_bits(f,8);3912+ return error(f, VORBIS_feature_not_supported);3913+ } else {3914+ Point p[31*8+2];3915+ Floor1 *g = &f->floor_config[i].floor1;3916+ int max_class = -1; 3917+ g->partitions = get_bits(f, 5);3918+ for (j=0; j < g->partitions; ++j) {3919+ g->partition_class_list[j] = get_bits(f, 4);3920+ if (g->partition_class_list[j] > max_class)3921+ max_class = g->partition_class_list[j];3922+ }3923+ for (j=0; j <= max_class; ++j) {3924+ g->class_dimensions[j] = get_bits(f, 3)+1;3925+ g->class_subclasses[j] = get_bits(f, 2);3926+ if (g->class_subclasses[j]) {3927+ g->class_masterbooks[j] = get_bits(f, 8);3928+ if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);3929+ }3930+ for (k=0; k < 1 << g->class_subclasses[j]; ++k) {3931+ g->subclass_books[j][k] = get_bits(f,8)-1;3932+ if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);3933+ }3934+ }3935+ g->floor1_multiplier = get_bits(f,2)+1;3936+ g->rangebits = get_bits(f,4);3937+ g->Xlist[0] = 0;3938+ g->Xlist[1] = 1 << g->rangebits;3939+ g->values = 2;3940+ for (j=0; j < g->partitions; ++j) {3941+ int c = g->partition_class_list[j];3942+ for (k=0; k < g->class_dimensions[c]; ++k) {3943+ g->Xlist[g->values] = get_bits(f, g->rangebits);3944+ ++g->values;3945+ }3946+ }3947+ // precompute the sorting3948+ for (j=0; j < g->values; ++j) {3949+ p[j].x = g->Xlist[j];3950+ p[j].y = j;3951+ }3952+ qsort(p, g->values, sizeof(p[0]), point_compare);3953+ for (j=0; j < g->values; ++j)3954+ g->sorted_order[j] = (uint8) p[j].y;3955+ // precompute the neighbors3956+ for (j=2; j < g->values; ++j) {3957+ int low,hi;3958+ neighbors(g->Xlist, j, &low,&hi);3959+ g->neighbors[j][0] = low;3960+ g->neighbors[j][1] = hi;3961+ }3962+3963+ if (g->values > longest_floorlist)3964+ longest_floorlist = g->values;3965+ }3966+ }3967+3968+ // Residue3969+ f->residue_count = get_bits(f, 6)+1;3970+ f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(*f->residue_config));3971+ for (i=0; i < f->residue_count; ++i) {3972+ uint8 residue_cascade[64];3973+ Residue *r = f->residue_config+i;3974+ f->residue_types[i] = get_bits(f, 16);3975+ if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);3976+ r->begin = get_bits(f, 24);3977+ r->end = get_bits(f, 24);3978+ r->part_size = get_bits(f,24)+1;3979+ r->classifications = get_bits(f,6)+1;3980+ r->classbook = get_bits(f,8);3981+ for (j=0; j < r->classifications; ++j) {3982+ uint8 high_bits=0;3983+ uint8 low_bits=get_bits(f,3);3984+ if (get_bits(f,1))3985+ high_bits = get_bits(f,5);3986+ residue_cascade[j] = high_bits*8 + low_bits;3987+ }3988+ r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);3989+ for (j=0; j < r->classifications; ++j) {3990+ for (k=0; k < 8; ++k) {3991+ if (residue_cascade[j] & (1 << k)) {3992+ r->residue_books[j][k] = get_bits(f, 8);3993+ if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);3994+ } else {3995+ r->residue_books[j][k] = -1;3996+ }3997+ }3998+ }3999+ // precompute the classifications[] array to avoid inner-loop mod/divide4000+ // call it 'classdata' since we already have r->classifications4001+ r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);4002+ if (!r->classdata) return error(f, VORBIS_outofmem);4003+ memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);4004+ for (j=0; j < f->codebooks[r->classbook].entries; ++j) {4005+ int classwords = f->codebooks[r->classbook].dimensions;4006+ int temp = j;4007+ r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);4008+ for (k=classwords-1; k >= 0; --k) {4009+ r->classdata[j][k] = temp % r->classifications;4010+ temp /= r->classifications;4011+ }4012+ }4013+ }4014+4015+ f->mapping_count = get_bits(f,6)+1;4016+ f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));4017+ for (i=0; i < f->mapping_count; ++i) {4018+ Mapping *m = f->mapping + i; 4019+ int mapping_type = get_bits(f,16);4020+ if (mapping_type != 0) return error(f, VORBIS_invalid_setup);4021+ m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));4022+ if (get_bits(f,1))4023+ m->submaps = get_bits(f,4)+1;4024+ else4025+ m->submaps = 1;4026+ if (m->submaps > max_submaps)4027+ max_submaps = m->submaps;4028+ if (get_bits(f,1)) {4029+ m->coupling_steps = get_bits(f,8)+1;4030+ for (k=0; k < m->coupling_steps; ++k) {4031+ m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));4032+ m->chan[k].angle = get_bits(f, ilog(f->channels-1));4033+ if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);4034+ if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);4035+ if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);4036+ }4037+ } else4038+ m->coupling_steps = 0;4039+4040+ // reserved field4041+ if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);4042+ if (m->submaps > 1) {4043+ for (j=0; j < f->channels; ++j) {4044+ m->chan[j].mux = get_bits(f, 4);4045+ if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);4046+ }4047+ } else4048+ // @SPECIFICATION: this case is missing from the spec4049+ for (j=0; j < f->channels; ++j)4050+ m->chan[j].mux = 0;4051+4052+ for (j=0; j < m->submaps; ++j) {4053+ get_bits(f,8); // discard4054+ m->submap_floor[j] = get_bits(f,8);4055+ m->submap_residue[j] = get_bits(f,8);4056+ if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);4057+ if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);4058+ }4059+ }4060+4061+ // Modes4062+ f->mode_count = get_bits(f, 6)+1;4063+ for (i=0; i < f->mode_count; ++i) {4064+ Mode *m = f->mode_config+i;4065+ m->blockflag = get_bits(f,1);4066+ m->windowtype = get_bits(f,16);4067+ m->transformtype = get_bits(f,16);4068+ m->mapping = get_bits(f,8);4069+ if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);4070+ if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);4071+ if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);4072+ }4073+4074+ flush_packet(f);4075+4076+ f->previous_length = 0;4077+4078+ for (i=0; i < f->channels; ++i) {4079+ f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);4080+ f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);4081+ f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);4082+ #ifdef STB_VORBIS_NO_DEFER_FLOOR4083+ f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);4084+ #endif4085+ }4086+4087+ if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;4088+ if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;4089+ f->blocksize[0] = f->blocksize_0;4090+ f->blocksize[1] = f->blocksize_1;4091+4092+#ifdef STB_VORBIS_DIVIDE_TABLE4093+ if (integer_divide_table[1][1]==0)4094+ for (i=0; i < DIVTAB_NUMER; ++i)4095+ for (j=1; j < DIVTAB_DENOM; ++j)4096+ integer_divide_table[i][j] = i / j;4097+#endif4098+4099+ // compute how much temporary memory is needed4100+4101+ // 1.4102+ {4103+ uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);4104+ uint32 classify_mem;4105+ int i,max_part_read=0;4106+ for (i=0; i < f->residue_count; ++i) {4107+ Residue *r = f->residue_config + i;4108+ int n_read = r->end - r->begin;4109+ int part_read = n_read / r->part_size;4110+ if (part_read > max_part_read)4111+ max_part_read = part_read;4112+ }4113+ #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE4114+ classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));4115+ #else4116+ classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));4117+ #endif4118+4119+ f->temp_memory_required = classify_mem;4120+ if (imdct_mem > f->temp_memory_required)4121+ f->temp_memory_required = imdct_mem;4122+ }4123+4124+ f->first_decode = TRUE;4125+4126+ if (f->alloc.alloc_buffer) {4127+ assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);4128+ // check if there's enough temp memory so we don't error later4129+ if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)4130+ return error(f, VORBIS_outofmem);4131+ }4132+4133+ f->first_audio_page_offset = stb_vorbis_get_file_offset(f);4134+4135+ return TRUE;4136+}4137+4138+static void vorbis_deinit(stb_vorbis *p)4139+{4140+ int i,j;4141+ for (i=0; i < p->residue_count; ++i) {4142+ Residue *r = p->residue_config+i;4143+ if (r->classdata) {4144+ for (j=0; j < p->codebooks[r->classbook].entries; ++j)4145+ setup_free(p, r->classdata[j]);4146+ setup_free(p, r->classdata);4147+ }4148+ setup_free(p, r->residue_books);4149+ }4150+4151+ if (p->codebooks) {4152+ for (i=0; i < p->codebook_count; ++i) {4153+ Codebook *c = p->codebooks + i;4154+ setup_free(p, c->codeword_lengths);4155+ setup_free(p, c->multiplicands);4156+ setup_free(p, c->codewords);4157+ setup_free(p, c->sorted_codewords);4158+ // c->sorted_values[-1] is the first entry in the array4159+ setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);4160+ }4161+ setup_free(p, p->codebooks);4162+ }4163+ setup_free(p, p->floor_config);4164+ setup_free(p, p->residue_config);4165+ for (i=0; i < p->mapping_count; ++i)4166+ setup_free(p, p->mapping[i].chan);4167+ setup_free(p, p->mapping);4168+ for (i=0; i < p->channels; ++i) {4169+ setup_free(p, p->channel_buffers[i]);4170+ setup_free(p, p->previous_window[i]);4171+ #ifdef STB_VORBIS_NO_DEFER_FLOOR4172+ setup_free(p, p->floor_buffers[i]);4173+ #endif4174+ setup_free(p, p->finalY[i]);4175+ }4176+ for (i=0; i < 2; ++i) {4177+ setup_free(p, p->A[i]);4178+ setup_free(p, p->B[i]);4179+ setup_free(p, p->C[i]);4180+ setup_free(p, p->window[i]);4181+ setup_free(p, p->bit_reverse[i]);4182+ }4183+ #ifndef STB_VORBIS_NO_STDIO4184+ if (p->close_on_free) fclose(p->f);4185+ #endif4186+}4187+4188+void stb_vorbis_close(stb_vorbis *p)4189+{4190+ if (p == NULL) return;4191+ vorbis_deinit(p);4192+ setup_free(p,p);4193+}4194+4195+static void vorbis_init(stb_vorbis *p, stb_vorbis_alloc *z)4196+{4197+ memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start4198+ if (z) {4199+ p->alloc = *z;4200+ p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3;4201+ p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;4202+ }4203+ p->eof = 0;4204+ p->error = VORBIS__no_error;4205+ p->stream = NULL;4206+ p->codebooks = NULL;4207+ p->page_crc_tests = -1;4208+ #ifndef STB_VORBIS_NO_STDIO4209+ p->close_on_free = FALSE;4210+ p->f = NULL;4211+ #endif4212+}4213+4214+int stb_vorbis_get_sample_offset(stb_vorbis *f)4215+{4216+ if (f->current_loc_valid)4217+ return f->current_loc;4218+ else4219+ return -1;4220+}4221+4222+stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)4223+{4224+ stb_vorbis_info d;4225+ d.channels = f->channels;4226+ d.sample_rate = f->sample_rate;4227+ d.setup_memory_required = f->setup_memory_required;4228+ d.setup_temp_memory_required = f->setup_temp_memory_required;4229+ d.temp_memory_required = f->temp_memory_required;4230+ d.max_frame_size = f->blocksize_1 >> 1;4231+ return d;4232+}4233+4234+int stb_vorbis_get_error(stb_vorbis *f)4235+{4236+ int e = f->error;4237+ f->error = VORBIS__no_error;4238+ return e;4239+}4240+4241+static stb_vorbis * vorbis_alloc(stb_vorbis *f)4242+{4243+ stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));4244+ return p;4245+}4246+4247+#ifndef STB_VORBIS_NO_PUSHDATA_API4248+4249+void stb_vorbis_flush_pushdata(stb_vorbis *f)4250+{4251+ f->previous_length = 0;4252+ f->page_crc_tests = 0;4253+ f->discard_samples_deferred = 0;4254+ f->current_loc_valid = FALSE;4255+ f->first_decode = FALSE;4256+ f->samples_output = 0;4257+ f->channel_buffer_start = 0;4258+ f->channel_buffer_end = 0;4259+}4260+4261+static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)4262+{4263+ int i,n;4264+ for (i=0; i < f->page_crc_tests; ++i)4265+ f->scan[i].bytes_done = 0;4266+4267+ // if we have room for more scans, search for them first, because4268+ // they may cause us to stop early if their header is incomplete4269+ if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {4270+ if (data_len < 4) return 0;4271+ data_len -= 3; // need to look for 4-byte sequence, so don't miss4272+ // one that straddles a boundary4273+ for (i=0; i < data_len; ++i) {4274+ if (data[i] == 0x4f) {4275+ if (0==memcmp(data+i, ogg_page_header, 4)) {4276+ int j,len;4277+ uint32 crc;4278+ // make sure we have the whole page header4279+ if (i+26 >= data_len || i+27+data[i+26] >= data_len) {4280+ // only read up to this page start, so hopefully we'll4281+ // have the whole page header start next time4282+ data_len = i;4283+ break;4284+ }4285+ // ok, we have it all; compute the length of the page4286+ len = 27 + data[i+26];4287+ for (j=0; j < data[i+26]; ++j)4288+ len += data[i+27+j];4289+ // scan everything up to the embedded crc (which we must 0)4290+ crc = 0;4291+ for (j=0; j < 22; ++j)4292+ crc = crc32_update(crc, data[i+j]);4293+ // now process 4 0-bytes4294+ for ( ; j < 26; ++j)4295+ crc = crc32_update(crc, 0);4296+ // len is the total number of bytes we need to scan4297+ n = f->page_crc_tests++;4298+ f->scan[n].bytes_left = len-j;4299+ f->scan[n].crc_so_far = crc;4300+ f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);4301+ // if the last frame on a page is continued to the next, then4302+ // we can't recover the sample_loc immediately4303+ if (data[i+27+data[i+26]-1] == 255)4304+ f->scan[n].sample_loc = ~0;4305+ else4306+ f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);4307+ f->scan[n].bytes_done = i+j;4308+ if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)4309+ break;4310+ // keep going if we still have room for more4311+ }4312+ }4313+ }4314+ }4315+4316+ for (i=0; i < f->page_crc_tests;) {4317+ uint32 crc;4318+ int j;4319+ int n = f->scan[i].bytes_done;4320+ int m = f->scan[i].bytes_left;4321+ if (m > data_len - n) m = data_len - n;4322+ // m is the bytes to scan in the current chunk4323+ crc = f->scan[i].crc_so_far;4324+ for (j=0; j < m; ++j)4325+ crc = crc32_update(crc, data[n+j]);4326+ f->scan[i].bytes_left -= m;4327+ f->scan[i].crc_so_far = crc;4328+ if (f->scan[i].bytes_left == 0) {4329+ // does it match?4330+ if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {4331+ // Houston, we have page4332+ data_len = n+m; // consumption amount is wherever that scan ended4333+ f->page_crc_tests = -1; // drop out of page scan mode4334+ f->previous_length = 0; // decode-but-don't-output one frame4335+ f->next_seg = -1; // start a new page4336+ f->current_loc = f->scan[i].sample_loc; // set the current sample location4337+ // to the amount we'd have decoded had we decoded this page4338+ f->current_loc_valid = f->current_loc != ~0U;4339+ return data_len;4340+ }4341+ // delete entry4342+ f->scan[i] = f->scan[--f->page_crc_tests];4343+ } else {4344+ ++i;4345+ }4346+ }4347+4348+ return data_len;4349+}4350+4351+// return value: number of bytes we used4352+int stb_vorbis_decode_frame_pushdata(4353+ stb_vorbis *f, // the file we're decoding4354+ uint8 *data, int data_len, // the memory available for decoding4355+ int *channels, // place to write number of float * buffers4356+ float ***output, // place to write float ** array of float * buffers4357+ int *samples // place to write number of output samples4358+ )4359+{4360+ int i;4361+ int len,right,left;4362+4363+ if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);4364+4365+ if (f->page_crc_tests >= 0) {4366+ *samples = 0;4367+ return vorbis_search_for_page_pushdata(f, data, data_len);4368+ }4369+4370+ f->stream = data;4371+ f->stream_end = data + data_len;4372+ f->error = VORBIS__no_error;4373+4374+ // check that we have the entire packet in memory4375+ if (!is_whole_packet_present(f, FALSE)) {4376+ *samples = 0;4377+ return 0;4378+ }4379+4380+ if (!vorbis_decode_packet(f, &len, &left, &right)) {4381+ // save the actual error we encountered4382+ enum STBVorbisError error = f->error;4383+ if (error == VORBIS_bad_packet_type) {4384+ // flush and resynch4385+ f->error = VORBIS__no_error;4386+ while (get8_packet(f) != EOP)4387+ if (f->eof) break;4388+ *samples = 0;4389+ return f->stream - data;4390+ }4391+ if (error == VORBIS_continued_packet_flag_invalid) {4392+ if (f->previous_length == 0) {4393+ // we may be resynching, in which case it's ok to hit one4394+ // of these; just discard the packet4395+ f->error = VORBIS__no_error;4396+ while (get8_packet(f) != EOP)4397+ if (f->eof) break;4398+ *samples = 0;4399+ return f->stream - data;4400+ }4401+ }4402+ // if we get an error while parsing, what to do?4403+ // well, it DEFINITELY won't work to continue from where we are!4404+ stb_vorbis_flush_pushdata(f);4405+ // restore the error that actually made us bail4406+ f->error = error;4407+ *samples = 0;4408+ return 1;4409+ }4410+4411+ // success!4412+ len = vorbis_finish_frame(f, len, left, right);4413+ for (i=0; i < f->channels; ++i)4414+ f->outputs[i] = f->channel_buffers[i] + left;4415+4416+ if (channels) *channels = f->channels;4417+ *samples = len;4418+ *output = f->outputs;4419+ return f->stream - data;4420+}4421+4422+stb_vorbis *stb_vorbis_open_pushdata(4423+ unsigned char *data, int data_len, // the memory available for decoding4424+ int *data_used, // only defined if result is not NULL4425+ int *error, stb_vorbis_alloc *alloc)4426+{4427+ stb_vorbis *f, p;4428+ vorbis_init(&p, alloc);4429+ p.stream = data;4430+ p.stream_end = data + data_len;4431+ p.push_mode = TRUE;4432+ if (!start_decoder(&p)) {4433+ if (p.eof)4434+ *error = VORBIS_need_more_data;4435+ else4436+ *error = p.error;4437+ return NULL;4438+ }4439+ f = vorbis_alloc(&p);4440+ if (f) {4441+ *f = p;4442+ *data_used = f->stream - data;4443+ *error = 0;4444+ return f;4445+ } else {4446+ vorbis_deinit(&p);4447+ return NULL;4448+ }4449+}4450+#endif // STB_VORBIS_NO_PUSHDATA_API4451+4452+unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)4453+{4454+ #ifndef STB_VORBIS_NO_PUSHDATA_API4455+ if (f->push_mode) return 0;4456+ #endif4457+ if (USE_MEMORY(f)) return f->stream - f->stream_start;4458+ #ifndef STB_VORBIS_NO_STDIO4459+ return ftell(f->f) - f->f_start;4460+ #endif4461+}4462+4463+#ifndef STB_VORBIS_NO_PULLDATA_API4464+//4465+// DATA-PULLING API4466+//4467+4468+static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)4469+{4470+ for(;;) {4471+ int n;4472+ if (f->eof) return 0;4473+ n = get8(f);4474+ if (n == 0x4f) { // page header4475+ unsigned int retry_loc = stb_vorbis_get_file_offset(f);4476+ int i;4477+ // check if we're off the end of a file_section stream4478+ if (retry_loc - 25 > f->stream_len)4479+ return 0;4480+ // check the rest of the header4481+ for (i=1; i < 4; ++i)4482+ if (get8(f) != ogg_page_header[i])4483+ break;4484+ if (f->eof) return 0;4485+ if (i == 4) {4486+ uint8 header[27];4487+ uint32 i, crc, goal, len;4488+ for (i=0; i < 4; ++i)4489+ header[i] = ogg_page_header[i];4490+ for (; i < 27; ++i)4491+ header[i] = get8(f);4492+ if (f->eof) return 0;4493+ if (header[4] != 0) goto invalid;4494+ goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);4495+ for (i=22; i < 26; ++i)4496+ header[i] = 0;4497+ crc = 0;4498+ for (i=0; i < 27; ++i)4499+ crc = crc32_update(crc, header[i]);4500+ len = 0;4501+ for (i=0; i < header[26]; ++i) {4502+ int s = get8(f);4503+ crc = crc32_update(crc, s);4504+ len += s;4505+ }4506+ if (len && f->eof) return 0;4507+ for (i=0; i < len; ++i)4508+ crc = crc32_update(crc, get8(f));4509+ // finished parsing probable page4510+ if (crc == goal) {4511+ // we could now check that it's either got the last4512+ // page flag set, OR it's followed by the capture4513+ // pattern, but I guess TECHNICALLY you could have4514+ // a file with garbage between each ogg page and recover4515+ // from it automatically? So even though that paranoia4516+ // might decrease the chance of an invalid decode by4517+ // another 2^32, not worth it since it would hose those4518+ // invalid-but-useful files?4519+ if (end)4520+ *end = stb_vorbis_get_file_offset(f);4521+ if (last) {4522+ if (header[5] & 0x04)4523+ *last = 1;4524+ else4525+ *last = 0;4526+ }4527+ set_file_offset(f, retry_loc-1);4528+ return 1;4529+ }4530+ }4531+ invalid:4532+ // not a valid page, so rewind and look for next one4533+ set_file_offset(f, retry_loc);4534+ }4535+ }4536+}4537+4538+// seek is implemented with 'interpolation search'--this is like4539+// binary search, but we use the data values to estimate the likely4540+// location of the data item (plus a bit of a bias so when the4541+// estimation is wrong we don't waste overly much time)4542+4543+#define SAMPLE_unknown 0xffffffff4544+4545+4546+// ogg vorbis, in its insane infinite wisdom, only provides4547+// information about the sample at the END of the page.4548+// therefore we COULD have the data we need in the current4549+// page, and not know it. we could just use the end location4550+// as our only knowledge for bounds, seek back, and eventually4551+// the binary search finds it. or we can try to be smart and4552+// not waste time trying to locate more pages. we try to be4553+// smart, since this data is already in memory anyway, so4554+// doing needless I/O would be crazy!4555+static int vorbis_analyze_page(stb_vorbis *f, ProbedPage *z)4556+{4557+ uint8 header[27], lacing[255];4558+ uint8 packet_type[255];4559+ int num_packet, packet_start;4560+ int i,len;4561+ uint32 samples;4562+4563+ // record where the page starts4564+ z->page_start = stb_vorbis_get_file_offset(f);4565+4566+ // parse the header4567+ getn(f, header, 27);4568+ assert(header[0] == 'O' && header[1] == 'g' && header[2] == 'g' && header[3] == 'S');4569+ getn(f, lacing, header[26]);4570+4571+ // determine the length of the payload4572+ len = 0;4573+ for (i=0; i < header[26]; ++i)4574+ len += lacing[i];4575+4576+ // this implies where the page ends4577+ z->page_end = z->page_start + 27 + header[26] + len;4578+4579+ // read the last-decoded sample out of the data4580+ z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 16);4581+4582+ if (header[5] & 4) {4583+ // if this is the last page, it's not possible to work4584+ // backwards to figure out the first sample! whoops! fuck.4585+ z->first_decoded_sample = SAMPLE_unknown;4586+ set_file_offset(f, z->page_start);4587+ return 1;4588+ }4589+4590+ // scan through the frames to determine the sample-count of each one...4591+ // our goal is the sample # of the first fully-decoded sample on the4592+ // page, which is the first decoded sample of the 2nd packet4593+4594+ num_packet=0;4595+4596+ packet_start = ((header[5] & 1) == 0);4597+4598+ for (i=0; i < header[26]; ++i) {4599+ if (packet_start) {4600+ uint8 n,b;4601+ if (lacing[i] == 0) goto bail; // trying to read from zero-length packet4602+ n = get8(f);4603+ // if bottom bit is non-zero, we've got corruption4604+ if (n & 1) goto bail;4605+ n >>= 1;4606+ b = ilog(f->mode_count-1);4607+ n &= (1 << b)-1;4608+ if (n >= f->mode_count) goto bail;4609+ packet_type[num_packet++] = f->mode_config[n].blockflag;4610+ skip(f, lacing[i]-1);4611+ } else4612+ skip(f, lacing[i]);4613+ packet_start = (lacing[i] < 255);4614+ }4615+4616+ // now that we know the sizes of all the pages, we can start determining4617+ // how much sample data there is.4618+4619+ samples = 0;4620+4621+ // for the last packet, we step by its whole length, because the definition4622+ // is that we encoded the end sample loc of the 'last packet completed',4623+ // where 'completed' refers to packets being split, and we are left to guess4624+ // what 'end sample loc' means. we assume it means ignoring the fact that4625+ // the last half of the data is useless without windowing against the next4626+ // packet... (so it's not REALLY complete in that sense)4627+ if (num_packet > 1)4628+ samples += f->blocksize[packet_type[num_packet-1]];4629+4630+ for (i=num_packet-2; i >= 1; --i) {4631+ // now, for this packet, how many samples do we have that4632+ // do not overlap the following packet?4633+ if (packet_type[i] == 1)4634+ if (packet_type[i+1] == 1)4635+ samples += f->blocksize_1 >> 1;4636+ else4637+ samples += ((f->blocksize_1 - f->blocksize_0) >> 2) + (f->blocksize_0 >> 1);4638+ else4639+ samples += f->blocksize_0 >> 1;4640+ }4641+ // now, at this point, we've rewound to the very beginning of the4642+ // _second_ packet. if we entirely discard the first packet after4643+ // a seek, this will be exactly the right sample number. HOWEVER!4644+ // we can't as easily compute this number for the LAST page. The4645+ // only way to get the sample offset of the LAST page is to use4646+ // the end loc from the previous page. But what that returns us4647+ // is _exactly_ the place where we get our first non-overlapped4648+ // sample. (I think. Stupid spec for being ambiguous.) So for4649+ // consistency it's better to do that here, too. However, that4650+ // will then require us to NOT discard all of the first frame we4651+ // decode, in some cases, which means an even weirder frame size4652+ // and extra code. what a fucking pain.4653+ 4654+ // we're going to discard the first packet if we4655+ // start the seek here, so we don't care about it. (we could actually4656+ // do better; if the first packet is long, and the previous packet4657+ // is short, there's actually data in the first half of the first4658+ // packet that doesn't need discarding... but not worth paying the4659+ // effort of tracking that of that here and in the seeking logic)4660+ // except crap, if we infer it from the _previous_ packet's end4661+ // location, we DO need to use that definition... and we HAVE to4662+ // infer the start loc of the LAST packet from the previous packet's4663+ // end location. fuck you, ogg vorbis.4664+4665+ z->first_decoded_sample = z->last_decoded_sample - samples;4666+4667+ // restore file state to where we were4668+ set_file_offset(f, z->page_start);4669+ return 1;4670+4671+ // restore file state to where we were4672+ bail:4673+ set_file_offset(f, z->page_start);4674+ return 0;4675+}4676+4677+static int vorbis_seek_frame_from_page(stb_vorbis *f, uint32 page_start, uint32 first_sample, uint32 target_sample, int fine)4678+{4679+ int left_start, left_end, right_start, right_end, mode,i;4680+ int frame=0;4681+ uint32 frame_start;4682+ int frames_to_skip, data_to_skip;4683+4684+ // first_sample is the sample # of the first sample that doesn't4685+ // overlap the previous page... note that this requires us to4686+ // _partially_ discard the first packet! bleh.4687+ set_file_offset(f, page_start);4688+4689+ f->next_seg = -1; // force page resync4690+4691+ frame_start = first_sample;4692+ // frame start is where the previous packet's last decoded sample4693+ // was, which corresponds to left_end... EXCEPT if the previous4694+ // packet was long and this packet is short? Probably a bug here.4695+4696+4697+ // now, we can start decoding frames... we'll only FAKE decode them,4698+ // until we find the frame that contains our sample; then we'll rewind,4699+ // and try again4700+ for (;;) {4701+ int start;4702+4703+ if (!vorbis_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))4704+ return error(f, VORBIS_seek_failed);4705+4706+ if (frame == 0)4707+ start = left_end;4708+ else4709+ start = left_start;4710+4711+ // the window starts at left_start; the last valid sample we generate4712+ // before the next frame's window start is right_start-14713+ if (target_sample < frame_start + right_start-start)4714+ break;4715+4716+ flush_packet(f);4717+ if (f->eof)4718+ return error(f, VORBIS_seek_failed);4719+4720+ frame_start += right_start - start;4721+4722+ ++frame;4723+ }4724+4725+ // ok, at this point, the sample we want is contained in frame #'frame'4726+4727+ // to decode frame #'frame' normally, we have to decode the4728+ // previous frame first... but if it's the FIRST frame of the page4729+ // we can't. if it's the first frame, it means it falls in the part4730+ // of the first frame that doesn't overlap either of the other frames.4731+ // so, if we have to handle that case for the first frame, we might4732+ // as well handle it for all of them, so:4733+ if (target_sample > frame_start + (left_end - left_start)) {4734+ // so what we want to do is go ahead and just immediately decode4735+ // this frame, but then make it so the next get_frame_float() uses4736+ // this already-decoded data? or do we want to go ahead and rewind,4737+ // and leave a flag saying to skip the first N data? let's do that4738+ frames_to_skip = frame; // if this is frame #1, skip 1 frame (#0)4739+ data_to_skip = left_end - left_start;4740+ } else {4741+ // otherwise, we want to skip frames 0, 1, 2, ... frame-24742+ // (which means frame-2+1 total frames) then decode frame-1,4743+ // then leave frame pending4744+ frames_to_skip = frame - 1;4745+ assert(frames_to_skip >= 0);4746+ data_to_skip = -1; 4747+ }4748+4749+ set_file_offset(f, page_start);4750+ f->next_seg = - 1; // force page resync4751+4752+ for (i=0; i < frames_to_skip; ++i) {4753+ maybe_start_packet(f);4754+ flush_packet(f);4755+ }4756+4757+ if (data_to_skip >= 0) {4758+ int i,j,n = f->blocksize_0 >> 1;4759+ f->discard_samples_deferred = data_to_skip;4760+ for (i=0; i < f->channels; ++i)4761+ for (j=0; j < n; ++j)4762+ f->previous_window[i][j] = 0;4763+ f->previous_length = n;4764+ frame_start += data_to_skip;4765+ } else {4766+ f->previous_length = 0;4767+ vorbis_pump_first_frame(f);4768+ }4769+4770+ // at this point, the NEXT decoded frame will generate the desired sample4771+ if (fine) {4772+ // so if we're doing sample accurate streaming, we want to go ahead and decode it!4773+ if (target_sample != frame_start) {4774+ int n;4775+ stb_vorbis_get_frame_float(f, &n, NULL);4776+ assert(target_sample > frame_start);4777+ assert(f->channel_buffer_start + (int) (target_sample-frame_start) < f->channel_buffer_end);4778+ f->channel_buffer_start += (target_sample - frame_start);4779+ }4780+ }4781+4782+ return 0;4783+}4784+4785+static int vorbis_seek_base(stb_vorbis *f, unsigned int sample_number, int fine)4786+{4787+ ProbedPage p[2],q;4788+ if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);4789+4790+ // do we know the location of the last page?4791+ if (f->p_last.page_start == 0) {4792+ uint32 z = stb_vorbis_stream_length_in_samples(f);4793+ if (z == 0) return error(f, VORBIS_cant_find_last_page);4794+ }4795+4796+ p[0] = f->p_first;4797+ p[1] = f->p_last;4798+4799+ if (sample_number >= f->p_last.last_decoded_sample)4800+ sample_number = f->p_last.last_decoded_sample-1;4801+4802+ if (sample_number < f->p_first.last_decoded_sample) {4803+ vorbis_seek_frame_from_page(f, p[0].page_start, 0, sample_number, fine);4804+ return 0;4805+ } else {4806+ int attempts=0;4807+ while (p[0].page_end < p[1].page_start) {4808+ uint32 probe;4809+ uint32 start_offset, end_offset;4810+ uint32 start_sample, end_sample;4811+4812+ // copy these into local variables so we can tweak them4813+ // if any are unknown4814+ start_offset = p[0].page_end;4815+ end_offset = p[1].after_previous_page_start; // an address known to seek to page p[1]4816+ start_sample = p[0].last_decoded_sample;4817+ end_sample = p[1].last_decoded_sample;4818+4819+ // currently there is no such tweaking logic needed/possible?4820+ if (start_sample == SAMPLE_unknown || end_sample == SAMPLE_unknown)4821+ return error(f, VORBIS_seek_failed);4822+4823+ // now we want to lerp between these for the target samples...4824+ 4825+ // step 1: we need to bias towards the page start...4826+ if (start_offset + 4000 < end_offset)4827+ end_offset -= 4000;4828+4829+ // now compute an interpolated search loc4830+ probe = start_offset + (int) floor((float) (end_offset - start_offset) / (end_sample - start_sample) * (sample_number - start_sample));4831+4832+ // next we need to bias towards binary search...4833+ // code is a little wonky to allow for full 32-bit unsigned values4834+ if (attempts >= 4) {4835+ uint32 probe2 = start_offset + ((end_offset - start_offset) >> 1);4836+ if (attempts >= 8)4837+ probe = probe2;4838+ else if (probe < probe2)4839+ probe = probe + ((probe2 - probe) >> 1);4840+ else4841+ probe = probe2 + ((probe - probe2) >> 1);4842+ }4843+ ++attempts;4844+4845+ set_file_offset(f, probe);4846+ if (!vorbis_find_page(f, NULL, NULL)) return error(f, VORBIS_seek_failed);4847+ if (!vorbis_analyze_page(f, &q)) return error(f, VORBIS_seek_failed);4848+ q.after_previous_page_start = probe;4849+4850+ // it's possible we've just found the last page again4851+ if (q.page_start == p[1].page_start) {4852+ p[1] = q;4853+ continue;4854+ }4855+4856+ if (sample_number < q.last_decoded_sample)4857+ p[1] = q;4858+ else4859+ p[0] = q;4860+ }4861+4862+ if (p[0].last_decoded_sample <= sample_number && sample_number < p[1].last_decoded_sample) {4863+ vorbis_seek_frame_from_page(f, p[1].page_start, p[0].last_decoded_sample, sample_number, fine);4864+ return 0;4865+ }4866+ return error(f, VORBIS_seek_failed);4867+ }4868+}4869+4870+int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)4871+{4872+ return vorbis_seek_base(f, sample_number, FALSE);4873+}4874+4875+int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)4876+{4877+ return vorbis_seek_base(f, sample_number, TRUE);4878+}4879+4880+void stb_vorbis_seek_start(stb_vorbis *f)4881+{4882+ if (IS_PUSH_MODE(f)) { error(f, VORBIS_invalid_api_mixing); return; }4883+ set_file_offset(f, f->first_audio_page_offset);4884+ f->previous_length = 0;4885+ f->first_decode = TRUE;4886+ f->next_seg = -1;4887+ vorbis_pump_first_frame(f);4888+}4889+4890+unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)4891+{4892+ unsigned int restore_offset, previous_safe;4893+ unsigned int end, last_page_loc;4894+4895+ if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);4896+ if (!f->total_samples) {4897+ unsigned int last;4898+ uint32 lo,hi;4899+ char header[6];4900+4901+ // first, store the current decode position so we can restore it4902+ restore_offset = stb_vorbis_get_file_offset(f);4903+4904+ // now we want to seek back 64K from the end (the last page must4905+ // be at most a little less than 64K, but let's allow a little slop)4906+ if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)4907+ previous_safe = f->stream_len - 65536;4908+ else4909+ previous_safe = f->first_audio_page_offset;4910+4911+ set_file_offset(f, previous_safe);4912+ // previous_safe is now our candidate 'earliest known place that seeking4913+ // to will lead to the final page'4914+4915+ if (!vorbis_find_page(f, &end, &last)) {4916+ // if we can't find a page, we're hosed!4917+ f->error = VORBIS_cant_find_last_page;4918+ f->total_samples = 0xffffffff;4919+ goto done;4920+ }4921+4922+ // check if there are more pages4923+ last_page_loc = stb_vorbis_get_file_offset(f);4924+4925+ // stop when the last_page flag is set, not when we reach eof;4926+ // this allows us to stop short of a 'file_section' end without4927+ // explicitly checking the length of the section4928+ while (!last) {4929+ set_file_offset(f, end);4930+ if (!vorbis_find_page(f, &end, &last)) {4931+ // the last page we found didn't have the 'last page' flag4932+ // set. whoops!4933+ break;4934+ }4935+ previous_safe = last_page_loc+1;4936+ last_page_loc = stb_vorbis_get_file_offset(f);4937+ }4938+4939+ set_file_offset(f, last_page_loc);4940+4941+ // parse the header4942+ getn(f, (unsigned char *)header, 6);4943+ // extract the absolute granule position4944+ lo = get32(f);4945+ hi = get32(f);4946+ if (lo == 0xffffffff && hi == 0xffffffff) {4947+ f->error = VORBIS_cant_find_last_page;4948+ f->total_samples = SAMPLE_unknown;4949+ goto done;4950+ }4951+ if (hi)4952+ lo = 0xfffffffe; // saturate4953+ f->total_samples = lo;4954+4955+ f->p_last.page_start = last_page_loc;4956+ f->p_last.page_end = end;4957+ f->p_last.last_decoded_sample = lo;4958+ f->p_last.first_decoded_sample = SAMPLE_unknown;4959+ f->p_last.after_previous_page_start = previous_safe;4960+4961+ done:4962+ set_file_offset(f, restore_offset);4963+ }4964+ return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;4965+}4966+4967+float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)4968+{4969+ return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;4970+}4971+4972+4973+4974+int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)4975+{4976+ int len, right,left,i;4977+ if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);4978+4979+ if (!vorbis_decode_packet(f, &len, &left, &right)) {4980+ f->channel_buffer_start = f->channel_buffer_end = 0;4981+ return 0;4982+ }4983+4984+ len = vorbis_finish_frame(f, len, left, right);4985+ for (i=0; i < f->channels; ++i)4986+ f->outputs[i] = f->channel_buffers[i] + left;4987+4988+ f->channel_buffer_start = left;4989+ f->channel_buffer_end = left+len;4990+4991+ if (channels) *channels = f->channels;4992+ if (output) *output = f->outputs;4993+ return len;4994+}4995+4996+#ifndef STB_VORBIS_NO_STDIO4997+4998+stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc, unsigned int length)4999+{5000+ stb_vorbis *f, p;5001+ vorbis_init(&p, alloc);5002+ p.f = file;5003+ p.f_start = ftell(file);5004+ p.stream_len = length;5005+ p.close_on_free = close_on_free;5006+ if (start_decoder(&p)) {5007+ f = vorbis_alloc(&p);5008+ if (f) {5009+ *f = p;5010+ vorbis_pump_first_frame(f);5011+ return f;5012+ }5013+ }5014+ if (error) *error = p.error;5015+ vorbis_deinit(&p);5016+ return NULL;5017+}5018+5019+stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, stb_vorbis_alloc *alloc)5020+{5021+ unsigned int len, start;5022+ start = ftell(file);5023+ fseek(file, 0, SEEK_END);5024+ len = ftell(file) - start;5025+ fseek(file, start, SEEK_SET);5026+ return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);5027+}5028+5029+stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, stb_vorbis_alloc *alloc)5030+{5031+ FILE *f = fopen(filename, "rb");5032+ if (f) 5033+ return stb_vorbis_open_file(f, TRUE, error, alloc);5034+ if (error) *error = VORBIS_file_open_failure;5035+ return NULL;5036+}5037+#endif // STB_VORBIS_NO_STDIO5038+5039+stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, stb_vorbis_alloc *alloc)5040+{5041+ stb_vorbis *f, p;5042+ if (data == NULL) return NULL;5043+ vorbis_init(&p, alloc);5044+ p.stream = (uint8 *) data;5045+ p.stream_end = (uint8 *) data + len;5046+ p.stream_start = (uint8 *) p.stream;5047+ p.stream_len = len;5048+ p.push_mode = FALSE;5049+ if (start_decoder(&p)) {5050+ f = vorbis_alloc(&p);5051+ if (f) {5052+ *f = p;5053+ vorbis_pump_first_frame(f);5054+ return f;5055+ }5056+ }5057+ if (error) *error = p.error;5058+ vorbis_deinit(&p);5059+ return NULL;5060+}5061+5062+#ifndef STB_VORBIS_NO_INTEGER_CONVERSION5063+#define PLAYBACK_MONO 15064+#define PLAYBACK_LEFT 25065+#define PLAYBACK_RIGHT 45066+5067+#define L (PLAYBACK_LEFT | PLAYBACK_MONO)5068+#define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)5069+#define R (PLAYBACK_RIGHT | PLAYBACK_MONO)5070+5071+static int8 channel_position[7][6] =5072+{5073+ { 0 },5074+ { C },5075+ { L, R },5076+ { L, C, R },5077+ { L, R, L, R },5078+ { L, C, R, L, R },5079+ { L, C, R, L, R, C },5080+};5081+5082+5083+#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT5084+ typedef union {5085+ float f;5086+ int i;5087+ } float_conv;5088+ typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];5089+ #define FASTDEF(x) float_conv x5090+ // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round5091+ #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))5092+ #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))5093+ #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))5094+ #define check_endianness() 5095+#else5096+ #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))5097+ #define check_endianness()5098+ #define FASTDEF(x)5099+#endif5100+5101+static void copy_samples(short *dest, float *src, int len)5102+{5103+ int i;5104+ check_endianness();5105+ for (i=0; i < len; ++i) {5106+ FASTDEF(temp);5107+ int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);5108+ if ((unsigned int) (v + 32768) > 65535)5109+ v = v < 0 ? -32768 : 32767;5110+ dest[i] = v;5111+ }5112+}5113+5114+static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)5115+{5116+ #define BUFFER_SIZE 325117+ float buffer[BUFFER_SIZE];5118+ int i,j,o,n = BUFFER_SIZE;5119+ check_endianness();5120+ for (o = 0; o < len; o += BUFFER_SIZE) {5121+ memset(buffer, 0, sizeof(buffer));5122+ if (o + n > len) n = len - o;5123+ for (j=0; j < num_c; ++j) {5124+ if (channel_position[num_c][j] & mask) {5125+ for (i=0; i < n; ++i)5126+ buffer[i] += data[j][d_offset+o+i];5127+ }5128+ }5129+ for (i=0; i < n; ++i) {5130+ FASTDEF(temp);5131+ int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);5132+ if ((unsigned int) (v + 32768) > 65535)5133+ v = v < 0 ? -32768 : 32767;5134+ output[o+i] = v;5135+ }5136+ }5137+}5138+5139+static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)5140+{5141+ #define BUFFER_SIZE 325142+ float buffer[BUFFER_SIZE];5143+ int i,j,o,n = BUFFER_SIZE >> 1;5144+ // o is the offset in the source data5145+ check_endianness();5146+ for (o = 0; o < len; o += BUFFER_SIZE >> 1) {5147+ // o2 is the offset in the output data5148+ int o2 = o << 1;5149+ memset(buffer, 0, sizeof(buffer));5150+ if (o + n > len) n = len - o;5151+ for (j=0; j < num_c; ++j) {5152+ int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);5153+ if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {5154+ for (i=0; i < n; ++i) {5155+ buffer[i*2+0] += data[j][d_offset+o+i];5156+ buffer[i*2+1] += data[j][d_offset+o+i];5157+ }5158+ } else if (m == PLAYBACK_LEFT) {5159+ for (i=0; i < n; ++i) {5160+ buffer[i*2+0] += data[j][d_offset+o+i];5161+ }5162+ } else if (m == PLAYBACK_RIGHT) {5163+ for (i=0; i < n; ++i) {5164+ buffer[i*2+1] += data[j][d_offset+o+i];5165+ }5166+ }5167+ }5168+ for (i=0; i < (n<<1); ++i) {5169+ FASTDEF(temp);5170+ int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);5171+ if ((unsigned int) (v + 32768) > 65535)5172+ v = v < 0 ? -32768 : 32767;5173+ output[o2+i] = v;5174+ }5175+ }5176+}5177+5178+static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)5179+{5180+ int i;5181+ if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {5182+ static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };5183+ for (i=0; i < buf_c; ++i)5184+ compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);5185+ } else {5186+ int limit = buf_c < data_c ? buf_c : data_c;5187+ for (i=0; i < limit; ++i)5188+ copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);5189+ for ( ; i < buf_c; ++i)5190+ memset(buffer[i]+b_offset, 0, sizeof(short) * samples);5191+ }5192+}5193+5194+int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)5195+{5196+ float **output;5197+ int len = stb_vorbis_get_frame_float(f, NULL, &output);5198+ if (len > num_samples) len = num_samples;5199+ if (len)5200+ convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);5201+ return len;5202+}5203+5204+static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)5205+{5206+ int i;5207+ check_endianness();5208+ if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {5209+ assert(buf_c == 2);5210+ for (i=0; i < buf_c; ++i)5211+ compute_stereo_samples(buffer, data_c, data, d_offset, len);5212+ } else {5213+ int limit = buf_c < data_c ? buf_c : data_c;5214+ int j;5215+ for (j=0; j < len; ++j) {5216+ for (i=0; i < limit; ++i) {5217+ FASTDEF(temp);5218+ float f = data[i][d_offset+j];5219+ int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);5220+ if ((unsigned int) (v + 32768) > 65535)5221+ v = v < 0 ? -32768 : 32767;5222+ *buffer++ = v;5223+ }5224+ for ( ; i < buf_c; ++i)5225+ *buffer++ = 0;5226+ }5227+ }5228+}5229+5230+int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)5231+{5232+ float **output;5233+ int len;5234+ if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);5235+ len = stb_vorbis_get_frame_float(f, NULL, &output);5236+ if (len) {5237+ if (len*num_c > num_shorts) len = num_shorts / num_c;5238+ convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);5239+ }5240+ return len;5241+}5242+5243+int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)5244+{5245+ float **outputs;5246+ int len = num_shorts / channels;5247+ int n=0;5248+ int z = f->channels;5249+ if (z > channels) z = channels;5250+ while (n < len) {5251+ int k = f->channel_buffer_end - f->channel_buffer_start;5252+ if (n+k >= len) k = len - n;5253+ if (k)5254+ convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);5255+ buffer += k*channels;5256+ n += k;5257+ f->channel_buffer_start += k;5258+ if (n == len) break;5259+ if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;5260+ }5261+ return n;5262+}5263+5264+int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)5265+{5266+ float **outputs;5267+ int n=0;5268+ int z = f->channels;5269+ if (z > channels) z = channels;5270+ while (n < len) {5271+ int k = f->channel_buffer_end - f->channel_buffer_start;5272+ if (n+k >= len) k = len - n;5273+ if (k)5274+ convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);5275+ n += k;5276+ f->channel_buffer_start += k;5277+ if (n == len) break;5278+ if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;5279+ }5280+ return n;5281+}5282+5283+#ifndef STB_VORBIS_NO_STDIO5284+int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)5285+{5286+ int data_len, offset, total, limit, error;5287+ short *data;5288+ stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);5289+ if (v == NULL) return -1;5290+ limit = v->channels * 4096;5291+ *channels = v->channels;5292+ if (sample_rate)5293+ *sample_rate = v->sample_rate;5294+ offset = data_len = 0;5295+ total = limit;5296+ data = (short *) malloc(total * sizeof(*data));5297+ if (data == NULL) {5298+ stb_vorbis_close(v);5299+ return -2;5300+ }5301+ for (;;) {5302+ int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);5303+ if (n == 0) break;5304+ data_len += n;5305+ offset += n * v->channels;5306+ if (offset + limit > total) {5307+ short *data2;5308+ total *= 2;5309+ data2 = (short *) realloc(data, total * sizeof(*data));5310+ if (data2 == NULL) {5311+ free(data);5312+ stb_vorbis_close(v);5313+ return -2;5314+ }5315+ data = data2;5316+ }5317+ }5318+ *output = data;5319+ stb_vorbis_close(v);5320+ return data_len;5321+}5322+#endif // NO_STDIO5323+5324+int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)5325+{5326+ int data_len, offset, total, limit, error;5327+ short *data;5328+ stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);5329+ if (v == NULL) return -1;5330+ limit = v->channels * 4096;5331+ *channels = v->channels;5332+ if (sample_rate)5333+ *sample_rate = v->sample_rate;5334+ offset = data_len = 0;5335+ total = limit;5336+ data = (short *) malloc(total * sizeof(*data));5337+ if (data == NULL) {5338+ stb_vorbis_close(v);5339+ return -2;5340+ }5341+ for (;;) {5342+ int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);5343+ if (n == 0) break;5344+ data_len += n;5345+ offset += n * v->channels;5346+ if (offset + limit > total) {5347+ short *data2;5348+ total *= 2;5349+ data2 = (short *) realloc(data, total * sizeof(*data));5350+ if (data2 == NULL) {5351+ free(data);5352+ stb_vorbis_close(v);5353+ return -2;5354+ }5355+ data = data2;5356+ }5357+ }5358+ *output = data;5359+ stb_vorbis_close(v);5360+ return data_len;5361+}5362+#endif // STB_VORBIS_NO_INTEGER_CONVERSION5363+5364+int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)5365+{5366+ float **outputs;5367+ int len = num_floats / channels;5368+ int n=0;5369+ int z = f->channels;5370+ if (z > channels) z = channels;5371+ while (n < len) {5372+ int i,j;5373+ int k = f->channel_buffer_end - f->channel_buffer_start;5374+ if (n+k >= len) k = len - n;5375+ for (j=0; j < k; ++j) {5376+ for (i=0; i < z; ++i)5377+ *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];5378+ for ( ; i < channels; ++i)5379+ *buffer++ = 0;5380+ }5381+ n += k;5382+ f->channel_buffer_start += k;5383+ if (n == len)5384+ break;5385+ if (!stb_vorbis_get_frame_float(f, NULL, &outputs))5386+ break;5387+ }5388+ return n;5389+}5390+5391+int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)5392+{5393+ float **outputs;5394+ int n=0;5395+ int z = f->channels;5396+ if (z > channels) z = channels;5397+ while (n < num_samples) {5398+ int i;5399+ int k = f->channel_buffer_end - f->channel_buffer_start;5400+ if (n+k >= num_samples) k = num_samples - n;5401+ if (k) {5402+ for (i=0; i < z; ++i)5403+ memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);5404+ for ( ; i < channels; ++i)5405+ memset(buffer[i]+n, 0, sizeof(float) * k);5406+ }5407+ n += k;5408+ f->channel_buffer_start += k;5409+ if (n == num_samples)5410+ break;5411+ if (!stb_vorbis_get_frame_float(f, NULL, &outputs))5412+ break;5413+ }5414+ return n;5415+}5416+#endif // STB_VORBIS_NO_PULLDATA_API5417+5418+/* Version history5419+ 1.05 - 2015/04/19 - don't define __forceinline if it's redundant5420+ 1.04 - 2014/08/27 - fix missing const-correct case in API5421+ 1.03 - 2014/08/07 - Warning fixes5422+ 1.02 - 2014/07/09 - Declare qsort compare function _cdecl on windows5423+ 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float5424+ 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in multichannel5425+ (API change) report sample rate for decode-full-file funcs5426+ 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila5427+ 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem5428+ 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence5429+ 0.99993 - remove assert that fired on legal files with empty tables5430+ 0.99992 - rewind-to-start5431+ 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo5432+ 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++5433+ 0.9998 - add a full-decode function with a memory source5434+ 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition5435+ 0.9996 - query length of vorbis stream in samples/seconds5436+ 0.9995 - bugfix to another optimization that only happened in certain files5437+ 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors5438+ 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation5439+ 0.9992 - performance improvement of IMDCT; now performs close to reference implementation5440+ 0.9991 - performance improvement of IMDCT5441+ 0.999 - (should have been 0.9990) performance improvement of IMDCT5442+ 0.998 - no-CRT support from Casey Muratori5443+ 0.997 - bugfixes for bugs found by Terje Mathisen5444+ 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen5445+ 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen5446+ 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen5447+ 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen5448+ 0.992 - fixes for MinGW warning5449+ 0.991 - turn fast-float-conversion on by default5450+ 0.990 - fix push-mode seek recovery if you seek into the headers5451+ 0.98b - fix to bad release of 0.985452+ 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode5453+ 0.97 - builds under c++ (typecasting, don't use 'class' keyword)5454+ 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 code5455+ 0.95 - clamping code for 16-bit functions5456+ 0.94 - not publically released5457+ 0.93 - fixed all-zero-floor case (was decoding garbage)5458+ 0.92 - fixed a memory leak5459+ 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_CONVERSION5460+ 0.90 - first public release5461+*/5462+5463+#endif // STB_VORBIS_HEADER_ONLYmodified:stb.h+64 added-21 removed
1-/* stb.h - v2.24 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h1+/* stb.h - v2.25 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h2 no warranty is offered or implied; use this code at your own risk3 4 This is a single header file with a bunch of useful utilities5 for getting stuff done in C/C++.18 unmodified lines24 25 26 Version History27 28+ 2.25 various warning & bugfixes29 2.24 various warning & bugfixes30 2.23 fix 2.2231 2.22 64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name32 2.21 utf-8 decoder rejects "overlong" encodings; attempted 64-bit improvements140 unmodified lines173 This software is in the public domain. Where that dedication is not174 recognized, you are granted a perpetual, irrevocable license to copy,175 distribute, and modify this file as you see fit.176 177+CREDITS178+179+ Written by Sean Barrett.180+181+ Fixes:182+ Philipp Wiesemann183+ Robert Nix184+ r-lyeh185+ blackpawn186+ Mojofreem@github187+ Ryan Whitworth188+ Vincent Isambart189 */190 191 #ifndef STB__INCLUDE_STB_H192 #define STB__INCLUDE_STB_H12 unmodified lines205 #define STB_THREADS206 #endif207 #endif208 209+#ifdef _WIN32210+ #define _CRT_SECURE_NO_WARNINGS211+ #define _CRT_NONSTDC_NO_DEPRECATE212+ #define _CRT_NON_CONFORMING_SWPRINTFS213+ #if !defined(_MSC_VER) || _MSC_VER > 1700214+ #include <intrin.h> // _BitScanReverse215+ #endif216+#endif217+218 #include <stdlib.h> // stdlib could have min/max219 #include <stdio.h> // need FILE220 #include <string.h> // stb_define_hash needs memcpy/memset221 #include <time.h> // stb_dirtree222+#ifdef __MINGW32__223+ #include <fcntl.h> // O_RDWR224+#endif225 226 #ifdef STB_PERSONAL227 typedef int Bool;228 #define False 0125 unmodified lines354 typedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];355 356 // add platform-specific ways of checking for sizeof(char*) == 8,357 // and make those define STB_PTR64333-#if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__)358+#if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__)359 #define STB_PTR64360 #endif361 362 #ifdef STB_PTR64689 unmodified lines1052 fputs("Fatal error: ", stderr);1053 vfprintf(stderr, s, a);1054 va_end(a);1055 fputs("\n", stderr);1031- #ifdef _WIN321056 #ifdef STB_DEBUG1057+ #ifdef _MSC_VER1058+ #ifndef STB_PTR641059 __asm int 3; // trap to debugger!1060+ #else1061+ __debugbreak();1062 #endif1063+ #else1064+ __builtin_trap();1065 #endif1066+ #endif1067 exit(1);1068 }1069 1070 static int stb__log_active=1, stb__log_fileline=1;361 unmodified lines1432 }1433 1434 // tricky use of 4-bit table to identify 5 bit positions (note the '-1')1435 // 3-bit table would require another tree level; 5-bit table wouldn't save one1405-#ifdef _WIN321436+#if defined(_WIN32) && !defined(__MINGW32__)1437 #pragma warning(push)1438 #pragma warning(disable: 4035) // disable warning about no return value1439 int stb_log2_floor(unsigned int n)1440 {1441 #if _MSC_VER > 17001411- DWORD i;1442+ unsigned long i;1443 _BitScanReverse(&i, n);1444 return i != 0 ? i : -1;1445 #else1446 __asm {1151 unmodified lines2598 2599 static void * stb__try_chunk(stb__chunk *c, int size, int align, int pre_align)2600 {2601 char *memblock = (char *) (c+1), *q;2602+ stb_inta iq;2571- int iq, start_offset;2603+ int start_offset;2604 2605 // we going to allocate at the end of the chunk, not the start. confusing,2606 // but it means we don't need both a 'limit' and a 'cur', just a 'cur'.2607 // the block ends at: p + c->data_left403 unmodified lines3011 #ifdef STB_DEBUG3012 #define stb_arr_check(a) assert(!a || stb_arrhead(a)->signature == stb_arr_signature)3013 #define stb_arr_check2(a) assert(!a || stb_arrhead2(a)->signature == stb_arr_signature)3014 #else2983-#define stb_arr_check(a) 02984-#define stb_arr_check2(a) 03015+#define stb_arr_check(a) ((void) 0)3016+#define stb_arr_check2(a) ((void) 0)3017 #endif3018 3019 // ARRAY LENGTH3020 314 unmodified lines3335 }3336 3337 unsigned int stb_rehash_improved(unsigned int v)3338 {3307- return stb_hashptr((void *) v);3339+ return stb_hashptr((void *)(size_t) v);3340 }3341 3342 unsigned int stb_hash2(char *str, unsigned int *hash2_ptr)3343 {1743 unmodified lines5087 {5088 fwrite(&x, 4, 1, f);5089 }5090 5059-#ifdef _MSC_VER5091+#if defined(_MSC_VER) || defined(__MINGW32__)5092 #define stb__stat _stat5093 #else5094 #define stb__stat stat5095 #endif331 unmodified lines5427 }5428 #else5429 {5430 strcpy(temp_full+p, "stmpXXXXXX");5431+ #ifdef __MINGW32__5432+ int fd = open(mktemp(temp_full), O_RDWR);5433+ #else5399- int fd = mkstemp(temp_full);5434+ int fd = mkstemp(temp_full);5435+ #endif5436 if (fd == -1) return NULL;5437 f = fdopen(fd, mode);5438 if (f == NULL) {5439 unlink(temp_full);427 unmodified lines5867 static char **readdir_raw(char *dir, int return_subdirs, char *mask)5868 {5869 char **results = NULL;5870 char buffer[512], with_slash[512];5835- int n;5871+ size_t n;5872 5873 #ifdef _MSC_VER5874 stb__wchar *ws;5875 struct _wfinddata_t data;5876+ #ifdef _WIN645877+ const intptr_t none = -1;5878+ intptr_t z;5879+ #else5880 const long none = -1;5881 long z;5842- #else5882+ #endif5883+ #else // !_MSC_VER5884 const DIR *none = NULL;5885 DIR *z;5886 #endif5887 965 unmodified lines6853 6854 int n;6855 6856 struct _wfinddata_t c_file;6857+ #ifdef STB_PTR646858+ intptr_t hFile;6859+ #else6860 long hFile;6861+ #endif6862 stb__wchar full_path[1024];6863 int has_slash;6864 6865 has_slash = (path[0] && path[strlen(path)-1] == '/'); 173 unmodified lines7039 stb_tolower(dir_lower);7040 stb_sha1(sha, (unsigned char *) dir_lower, strlen(dir_lower));7041 strcpy(cache_file, cache_dir);7042 s = cache_file + strlen(cache_file);6998- if (s[-1] != '//' && s[-1] != '\\') *s++ = '/';7043+ if (s[-1] != '/' && s[-1] != '\\') *s++ = '/';7044 strcpy(s, "dirtree_");7045 s += strlen(s);7046 for (i=0; i < 8; ++i) {7047 char *hex = "0123456789abcdef";341 unmodified lines7389 // returns a list, *count is the length of that list,7390 // but some entries of the list may be invalid;7391 // test with 'stb_ps_fastlist_valid(x)'7392 7348-#define stb_ps_fastlist_valid(x) ((unsigned int) (x) > 1)7393+#define stb_ps_fastlist_valid(x) ((stb_uinta) (x) > 1)7394 7395 #ifdef STB_DEFINE7396 7397 enum12 unmodified lines7410 } stb_ps_bucket;7411 #define GetBucket(p) ((stb_ps_bucket *) ((char *) (p) - STB_ps_bucket))7412 #define EncodeBucket(p) ((stb_ps *) ((char *) (p) + STB_ps_bucket))7413 7369-typedef char stb__verify_bucket_heap_size[sizeof(stb_ps_bucket) == 16];7370-7414 static void stb_bucket_free(stb_ps_bucket *b)7415 {7416 free(b);7417 }2689 unmodified lines10107 fclose(f);10108 if (p == NULL) return NULL;10109 if (p[0] != 0x57 || p[1] != 0xBc || p[2] || p[3]) { free(p); return NULL; }10110 q = (char *) malloc(stb_decompress_length(p)+1);10068- if (!q) { free(p); free(p); return NULL; }10111+ if (!q) { free(p); return NULL; }10112 *len = stb_decompress((unsigned char *) q, p, n);10113 if (*len) q[*len] = 0;10114 free(p);10115 return q;340 unmodified lines10456 10457 ////////////////////// streaming I/O version /////////////////////10458 10459 10417-static stb_uint stb_out_backpatch_id(void)10460+static size_t stb_out_backpatch_id(void)10461 {10462 if (stb__out)10420- return (stb_uint) stb__out;10463+ return (size_t) stb__out;10464 else10465 return ftell(stb__outfile);10466 }10467 10425-static void stb_out_backpatch(stb_uint id, stb_uint value)10468+static void stb_out_backpatch(size_t id, stb_uint value)10469 {10470 stb_uchar data[4] = { value >> 24, value >> 16, value >> 8, value };10471 if (stb__out) {10472 memcpy((void *) id, data, 4);3664 unmodified lines