diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/libs/stb/stb_vorbis.c | 8454 | ||||
-rw-r--r-- | src/libs/tiny/tinysound.h | 2560 | ||||
-rw-r--r-- | src/lua/audio/luaopen_audio.cpp | 12 | ||||
-rw-r--r-- | src/lua/embed/debug.lua.h | 253 | ||||
-rw-r--r-- | src/lua/embed/embed.h | 14 | ||||
-rw-r--r-- | src/lua/embed/graphics.lua.h | 12 | ||||
-rw-r--r-- | src/lua/embed/keyboard.lua.h | 31 | ||||
-rw-r--r-- | src/lua/embed/mouse.lua.h | 29 | ||||
-rw-r--r-- | src/lua/embed/path.lua.h | 36 | ||||
-rw-r--r-- | src/lua/event/luaopen_event.cpp | 2 | ||||
-rw-r--r-- | src/lua/filesystem/luaopen_filesystem.cpp | 4 | ||||
-rw-r--r-- | src/lua/graphics/luaopen_graphics.cpp | 34 | ||||
-rw-r--r-- | src/lua/luaopen_jin.cpp | 6 | ||||
-rw-r--r-- | src/main.cpp | 7 | ||||
-rw-r--r-- | src/render/font.cpp | 4 | ||||
-rw-r--r-- | src/render/graphics.cpp | 2 | ||||
-rw-r--r-- | src/render/jsl.cpp | 3 | ||||
-rw-r--r-- | src/utils/matrix.cpp | 2 |
18 files changed, 4505 insertions, 6960 deletions
diff --git a/src/libs/stb/stb_vorbis.c b/src/libs/stb/stb_vorbis.c index 1181e6d..3d338f0 100644 --- a/src/libs/stb/stb_vorbis.c +++ b/src/libs/stb/stb_vorbis.c @@ -1,11 +1,11 @@ -// Ogg Vorbis audio decoder - v1.10 - public domain +// Ogg Vorbis audio decoder - v1.14 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // -// Originally sponsored by RAD Game Tools. Seeking sponsored -// by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software, -// Aras Pranckevicius, and Sean Barrett. +// Originally sponsored by RAD Game Tools. Seeking implementation +// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, +// Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // @@ -29,22 +29,27 @@ // Bernhard Wodo Evan Balster alxprd@github // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart -// manxorist@github saga musix +// manxorist@github saga musix github:infatum +// Timur Gagiev // // Partial history: -// 1.10 - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory -// 1.09 - 2016/04/04 - back out 'truncation of last frame' fix from previous version -// 1.08 - 2016/04/02 - warnings; setup memory leaks; truncation of last frame -// 1.07 - 2015/01/16 - fixes for crashes on invalid files; warning fixes; const -// 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson) +// 1.14 - 2018-02-11 - delete bogus dealloca usage +// 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) +// 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files +// 1.11 - 2017-07-23 - fix MinGW compilation +// 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory +// 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version +// 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame +// 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const +// 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts -// 1.05 - 2015/04/19 - don't define __forceinline if it's redundant -// 1.04 - 2014/08/27 - fix missing const-correct case in API -// 1.03 - 2014/08/07 - warning fixes -// 1.02 - 2014/07/09 - declare qsort comparison as explicitly _cdecl in Windows -// 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float (interleaved was correct) -// 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in >2-channel; +// 1.05 - 2015-04-19 - don't define __forceinline if it's redundant +// 1.04 - 2014-08-27 - fix missing const-correct case in API +// 1.03 - 2014-08-07 - warning fixes +// 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows +// 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) +// 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. @@ -70,307 +75,307 @@ extern "C" { #endif -/////////// THREAD SAFETY + /////////// THREAD SAFETY -// Individual stb_vorbis* handles are not thread-safe; you cannot decode from -// them from multiple threads at the same time. However, you can have multiple -// stb_vorbis* handles and decode from them independently in multiple thrads. + // Individual stb_vorbis* handles are not thread-safe; you cannot decode from + // them from multiple threads at the same time. However, you can have multiple + // stb_vorbis* handles and decode from them independently in multiple thrads. -/////////// MEMORY ALLOCATION + /////////// MEMORY ALLOCATION -// normally stb_vorbis uses malloc() to allocate memory at startup, -// and alloca() to allocate temporary memory during a frame on the -// stack. (Memory consumption will depend on the amount of setup -// data in the file and how you set the compile flags for speed -// vs. size. In my test files the maximal-size usage is ~150KB.) -// -// You can modify the wrapper functions in the source (setup_malloc, -// setup_temp_malloc, temp_malloc) to change this behavior, or you -// can use a simpler allocation model: you pass in a buffer from -// which stb_vorbis will allocate _all_ its memory (including the -// temp memory). "open" may fail with a VORBIS_outofmem if you -// do not pass in enough data; there is no way to determine how -// much you do need except to succeed (at which point you can -// query get_info to find the exact amount required. yes I know -// this is lame). -// -// If you pass in a non-NULL buffer of the type below, allocation -// will occur from it as described above. Otherwise just pass NULL -// to use malloc()/alloca() + // normally stb_vorbis uses malloc() to allocate memory at startup, + // and alloca() to allocate temporary memory during a frame on the + // stack. (Memory consumption will depend on the amount of setup + // data in the file and how you set the compile flags for speed + // vs. size. In my test files the maximal-size usage is ~150KB.) + // + // You can modify the wrapper functions in the source (setup_malloc, + // setup_temp_malloc, temp_malloc) to change this behavior, or you + // can use a simpler allocation model: you pass in a buffer from + // which stb_vorbis will allocate _all_ its memory (including the + // temp memory). "open" may fail with a VORBIS_outofmem if you + // do not pass in enough data; there is no way to determine how + // much you do need except to succeed (at which point you can + // query get_info to find the exact amount required. yes I know + // this is lame). + // + // If you pass in a non-NULL buffer of the type below, allocation + // will occur from it as described above. Otherwise just pass NULL + // to use malloc()/alloca() -typedef struct -{ - char *alloc_buffer; - int alloc_buffer_length_in_bytes; -} stb_vorbis_alloc; + typedef struct + { + char *alloc_buffer; + int alloc_buffer_length_in_bytes; + } stb_vorbis_alloc; -/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES + /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES -typedef struct stb_vorbis stb_vorbis; + typedef struct stb_vorbis stb_vorbis; -typedef struct -{ - unsigned int sample_rate; - int channels; + typedef struct + { + unsigned int sample_rate; + int channels; - unsigned int setup_memory_required; - unsigned int setup_temp_memory_required; - unsigned int temp_memory_required; + unsigned int setup_memory_required; + unsigned int setup_temp_memory_required; + unsigned int temp_memory_required; - int max_frame_size; -} stb_vorbis_info; + int max_frame_size; + } stb_vorbis_info; -// get general information about the file -extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); + // get general information about the file + extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); -// get the last error detected (clears it, too) -extern int stb_vorbis_get_error(stb_vorbis *f); + // get the last error detected (clears it, too) + extern int stb_vorbis_get_error(stb_vorbis *f); -// close an ogg vorbis file and free all memory in use -extern void stb_vorbis_close(stb_vorbis *f); + // close an ogg vorbis file and free all memory in use + extern void stb_vorbis_close(stb_vorbis *f); -// this function returns the offset (in samples) from the beginning of the -// file that will be returned by the next decode, if it is known, or -1 -// otherwise. after a flush_pushdata() call, this may take a while before -// it becomes valid again. -// NOT WORKING YET after a seek with PULLDATA API -extern int stb_vorbis_get_sample_offset(stb_vorbis *f); + // this function returns the offset (in samples) from the beginning of the + // file that will be returned by the next decode, if it is known, or -1 + // otherwise. after a flush_pushdata() call, this may take a while before + // it becomes valid again. + // NOT WORKING YET after a seek with PULLDATA API + extern int stb_vorbis_get_sample_offset(stb_vorbis *f); -// returns the current seek point within the file, or offset from the beginning -// of the memory buffer. In pushdata mode it returns 0. -extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); + // returns the current seek point within the file, or offset from the beginning + // of the memory buffer. In pushdata mode it returns 0. + extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); -/////////// PUSHDATA API + /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API -// this API allows you to get blocks of data from any source and hand -// them to stb_vorbis. you have to buffer them; stb_vorbis will tell -// you how much it used, and you have to give it the rest next time; -// and stb_vorbis may not have enough data to work with and you will -// need to give it the same data again PLUS more. Note that the Vorbis -// specification does not bound the size of an individual frame. - -extern stb_vorbis *stb_vorbis_open_pushdata( - const unsigned char * datablock, int datablock_length_in_bytes, - int *datablock_memory_consumed_in_bytes, - int *error, - const stb_vorbis_alloc *alloc_buffer); -// create a vorbis decoder by passing in the initial data block containing -// the ogg&vorbis headers (you don't need to do parse them, just provide -// the first N bytes of the file--you're told if it's not enough, see below) -// on success, returns an stb_vorbis *, does not set error, returns the amount of -// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; -// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed -// if returns NULL and *error is VORBIS_need_more_data, then the input block was -// incomplete and you need to pass in a larger block from the start of the file - -extern int stb_vorbis_decode_frame_pushdata( - stb_vorbis *f, - const unsigned char *datablock, int datablock_length_in_bytes, - int *channels, // place to write number of float * buffers - float ***output, // place to write float ** array of float * buffers - int *samples // place to write number of output samples - ); -// decode a frame of audio sample data if possible from the passed-in data block -// -// return value: number of bytes we used from datablock -// -// possible cases: -// 0 bytes used, 0 samples output (need more data) -// N bytes used, 0 samples output (resynching the stream, keep going) -// N bytes used, M samples output (one frame of data) -// note that after opening a file, you will ALWAYS get one N-bytes,0-sample -// frame, because Vorbis always "discards" the first frame. -// -// Note that on resynch, stb_vorbis will rarely consume all of the buffer, -// instead only datablock_length_in_bytes-3 or less. This is because it wants -// to avoid missing parts of a page header if they cross a datablock boundary, -// without writing state-machiney code to record a partial detection. -// -// The number of channels returned are stored in *channels (which can be -// NULL--it is always the same as the number of channels reported by -// get_info). *output will contain an array of float* buffers, one per -// channel. In other words, (*output)[0][0] contains the first sample from -// the first channel, and (*output)[1][0] contains the first sample from -// the second channel. - -extern void stb_vorbis_flush_pushdata(stb_vorbis *f); -// inform stb_vorbis that your next datablock will not be contiguous with -// previous ones (e.g. you've seeked in the data); future attempts to decode -// frames will cause stb_vorbis to resynchronize (as noted above), and -// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it -// will begin decoding the _next_ frame. -// -// if you want to seek using pushdata, you need to seek in your file, then -// call stb_vorbis_flush_pushdata(), then start calling decoding, then once -// decoding is returning you data, call stb_vorbis_get_sample_offset, and -// if you don't like the result, seek your file again and repeat. + // this API allows you to get blocks of data from any source and hand + // them to stb_vorbis. you have to buffer them; stb_vorbis will tell + // you how much it used, and you have to give it the rest next time; + // and stb_vorbis may not have enough data to work with and you will + // need to give it the same data again PLUS more. Note that the Vorbis + // specification does not bound the size of an individual frame. + + extern stb_vorbis *stb_vorbis_open_pushdata( + const unsigned char * datablock, int datablock_length_in_bytes, + int *datablock_memory_consumed_in_bytes, + int *error, + const stb_vorbis_alloc *alloc_buffer); + // create a vorbis decoder by passing in the initial data block containing + // the ogg&vorbis headers (you don't need to do parse them, just provide + // the first N bytes of the file--you're told if it's not enough, see below) + // on success, returns an stb_vorbis *, does not set error, returns the amount of + // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; + // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed + // if returns NULL and *error is VORBIS_need_more_data, then the input block was + // incomplete and you need to pass in a larger block from the start of the file + + extern int stb_vorbis_decode_frame_pushdata( + stb_vorbis *f, + const unsigned char *datablock, int datablock_length_in_bytes, + int *channels, // place to write number of float * buffers + float ***output, // place to write float ** array of float * buffers + int *samples // place to write number of output samples + ); + // decode a frame of audio sample data if possible from the passed-in data block + // + // return value: number of bytes we used from datablock + // + // possible cases: + // 0 bytes used, 0 samples output (need more data) + // N bytes used, 0 samples output (resynching the stream, keep going) + // N bytes used, M samples output (one frame of data) + // note that after opening a file, you will ALWAYS get one N-bytes,0-sample + // frame, because Vorbis always "discards" the first frame. + // + // Note that on resynch, stb_vorbis will rarely consume all of the buffer, + // instead only datablock_length_in_bytes-3 or less. This is because it wants + // to avoid missing parts of a page header if they cross a datablock boundary, + // without writing state-machiney code to record a partial detection. + // + // The number of channels returned are stored in *channels (which can be + // NULL--it is always the same as the number of channels reported by + // get_info). *output will contain an array of float* buffers, one per + // channel. In other words, (*output)[0][0] contains the first sample from + // the first channel, and (*output)[1][0] contains the first sample from + // the second channel. + + extern void stb_vorbis_flush_pushdata(stb_vorbis *f); + // inform stb_vorbis that your next datablock will not be contiguous with + // previous ones (e.g. you've seeked in the data); future attempts to decode + // frames will cause stb_vorbis to resynchronize (as noted above), and + // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it + // will begin decoding the _next_ frame. + // + // if you want to seek using pushdata, you need to seek in your file, then + // call stb_vorbis_flush_pushdata(), then start calling decoding, then once + // decoding is returning you data, call stb_vorbis_get_sample_offset, and + // if you don't like the result, seek your file again and repeat. #endif -////////// PULLING INPUT API + ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API -// This API assumes stb_vorbis is allowed to pull data from a source-- -// either a block of memory containing the _entire_ vorbis stream, or a -// FILE * that you or it create, or possibly some other reading mechanism -// if you go modify the source to replace the FILE * case with some kind -// of callback to your code. (But if you don't support seeking, you may -// just want to go ahead and use pushdata.) + // This API assumes stb_vorbis is allowed to pull data from a source-- + // either a block of memory containing the _entire_ vorbis stream, or a + // FILE * that you or it create, or possibly some other reading mechanism + // if you go modify the source to replace the FILE * case with some kind + // of callback to your code. (But if you don't support seeking, you may + // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) -extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); + extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) -extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); + extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif -// decode an entire file and output the data interleaved into a malloc()ed -// buffer stored in *output. The return value is the number of samples -// decoded, or -1 if the file could not be opened or was not an ogg vorbis file. -// When you're done with it, just free() the pointer returned in *output. + // decode an entire file and output the data interleaved into a malloc()ed + // buffer stored in *output. The return value is the number of samples + // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. + // When you're done with it, just free() the pointer returned in *output. -extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, - int *error, const stb_vorbis_alloc *alloc_buffer); -// create an ogg vorbis decoder from an ogg vorbis stream in memory (note -// this must be the entire stream!). on failure, returns NULL and sets *error + extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, + int *error, const stb_vorbis_alloc *alloc_buffer); + // create an ogg vorbis decoder from an ogg vorbis stream in memory (note + // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO -extern stb_vorbis * stb_vorbis_open_filename(const char *filename, - int *error, const stb_vorbis_alloc *alloc_buffer); -// create an ogg vorbis decoder from a filename via fopen(). on failure, -// returns NULL and sets *error (possibly to VORBIS_file_open_failure). - -extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, - int *error, const stb_vorbis_alloc *alloc_buffer); -// create an ogg vorbis decoder from an open FILE *, looking for a stream at -// the _current_ seek point (ftell). on failure, returns NULL and sets *error. -// note that stb_vorbis must "own" this stream; if you seek it in between -// calls to stb_vorbis, it will become confused. Morever, if you attempt to -// perform stb_vorbis_seek_*() operations on this file, it will assume it -// owns the _entire_ rest of the file after the start point. Use the next -// function, stb_vorbis_open_file_section(), to limit it. - -extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, - int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); -// create an ogg vorbis decoder from an open FILE *, looking for a stream at -// the _current_ seek point (ftell); the stream will be of length 'len' bytes. -// on failure, returns NULL and sets *error. note that stb_vorbis must "own" -// this stream; if you seek it in between calls to stb_vorbis, it will become -// confused. + extern stb_vorbis * stb_vorbis_open_filename(const char *filename, + int *error, const stb_vorbis_alloc *alloc_buffer); + // create an ogg vorbis decoder from a filename via fopen(). on failure, + // returns NULL and sets *error (possibly to VORBIS_file_open_failure). + + extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, + int *error, const stb_vorbis_alloc *alloc_buffer); + // create an ogg vorbis decoder from an open FILE *, looking for a stream at + // the _current_ seek point (ftell). on failure, returns NULL and sets *error. + // note that stb_vorbis must "own" this stream; if you seek it in between + // calls to stb_vorbis, it will become confused. Morever, if you attempt to + // perform stb_vorbis_seek_*() operations on this file, it will assume it + // owns the _entire_ rest of the file after the start point. Use the next + // function, stb_vorbis_open_file_section(), to limit it. + + extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, + int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); + // create an ogg vorbis decoder from an open FILE *, looking for a stream at + // the _current_ seek point (ftell); the stream will be of length 'len' bytes. + // on failure, returns NULL and sets *error. note that stb_vorbis must "own" + // this stream; if you seek it in between calls to stb_vorbis, it will become + // confused. #endif -extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); -extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); -// these functions seek in the Vorbis file to (approximately) 'sample_number'. -// after calling seek_frame(), the next call to get_frame_*() will include -// the specified sample. after calling stb_vorbis_seek(), the next call to -// stb_vorbis_get_samples_* will start with the specified sample. If you -// do not need to seek to EXACTLY the target sample when using get_samples_*, -// you can also use seek_frame(). - -extern int stb_vorbis_seek_start(stb_vorbis *f); -// this function is equivalent to stb_vorbis_seek(f,0) - -extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); -extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); -// these functions return the total length of the vorbis stream - -extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); -// decode the next frame and return the number of samples. the number of -// channels returned are stored in *channels (which can be NULL--it is always -// the same as the number of channels reported by get_info). *output will -// contain an array of float* buffers, one per channel. These outputs will -// be overwritten on the next call to stb_vorbis_get_frame_*. -// -// You generally should not intermix calls to stb_vorbis_get_frame_*() -// and stb_vorbis_get_samples_*(), since the latter calls the former. + extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); + extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); + // these functions seek in the Vorbis file to (approximately) 'sample_number'. + // after calling seek_frame(), the next call to get_frame_*() will include + // the specified sample. after calling stb_vorbis_seek(), the next call to + // stb_vorbis_get_samples_* will start with the specified sample. If you + // do not need to seek to EXACTLY the target sample when using get_samples_*, + // you can also use seek_frame(). + + extern int stb_vorbis_seek_start(stb_vorbis *f); + // this function is equivalent to stb_vorbis_seek(f,0) + + extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); + extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); + // these functions return the total length of the vorbis stream + + extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); + // decode the next frame and return the number of samples. the number of + // channels returned are stored in *channels (which can be NULL--it is always + // the same as the number of channels reported by get_info). *output will + // contain an array of float* buffers, one per channel. These outputs will + // be overwritten on the next call to stb_vorbis_get_frame_*. + // + // You generally should not intermix calls to stb_vorbis_get_frame_*() + // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION -extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); -extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); + extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); + extern int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif -// decode the next frame and return the number of *samples* per channel. -// Note that for interleaved data, you pass in the number of shorts (the -// size of your array), but the return value is the number of samples per -// channel, not the total number of samples. -// -// The data is coerced to the number of channels you request according to the -// channel coercion rules (see below). You must pass in the size of your -// buffer(s) so that stb_vorbis will not overwrite the end of the buffer. -// The maximum buffer size needed can be gotten from get_info(); however, -// the Vorbis I specification implies an absolute maximum of 4096 samples -// per channel. - -// Channel coercion rules: -// Let M be the number of channels requested, and N the number of channels present, -// and Cn be the nth channel; let stereo L be the sum of all L and center channels, -// and stereo R be the sum of all R and center channels (channel assignment from the -// vorbis spec). -// M N output -// 1 k sum(Ck) for all k -// 2 * stereo L, stereo R -// k l k > l, the first l channels, then 0s -// k l k <= l, the first k channels -// Note that this is not _good_ surround etc. mixing at all! It's just so -// you get something useful. - -extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); -extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); -// gets num_samples samples, not necessarily on a frame boundary--this requires -// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. -// Returns the number of samples stored per channel; it may be less than requested -// at the end of the file. If there are no more samples in the file, returns 0. + // decode the next frame and return the number of *samples* per channel. + // Note that for interleaved data, you pass in the number of shorts (the + // size of your array), but the return value is the number of samples per + // channel, not the total number of samples. + // + // The data is coerced to the number of channels you request according to the + // channel coercion rules (see below). You must pass in the size of your + // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. + // The maximum buffer size needed can be gotten from get_info(); however, + // the Vorbis I specification implies an absolute maximum of 4096 samples + // per channel. + + // Channel coercion rules: + // Let M be the number of channels requested, and N the number of channels present, + // and Cn be the nth channel; let stereo L be the sum of all L and center channels, + // and stereo R be the sum of all R and center channels (channel assignment from the + // vorbis spec). + // M N output + // 1 k sum(Ck) for all k + // 2 * stereo L, stereo R + // k l k > l, the first l channels, then 0s + // k l k <= l, the first k channels + // Note that this is not _good_ surround etc. mixing at all! It's just so + // you get something useful. + + extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); + extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); + // gets num_samples samples, not necessarily on a frame boundary--this requires + // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. + // Returns the number of samples stored per channel; it may be less than requested + // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION -extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); -extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); + extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); + extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif -// gets num_samples samples, not necessarily on a frame boundary--this requires -// buffering so you have to supply the buffers. Applies the coercion rules above -// to produce 'channels' channels. Returns the number of samples stored per channel; -// it may be less than requested at the end of the file. If there are no more -// samples in the file, returns 0. + // gets num_samples samples, not necessarily on a frame boundary--this requires + // buffering so you have to supply the buffers. Applies the coercion rules above + // to produce 'channels' channels. Returns the number of samples stored per channel; + // it may be less than requested at the end of the file. If there are no more + // samples in the file, returns 0. #endif -//////// ERROR CODES + //////// ERROR CODES -enum STBVorbisError -{ - VORBIS__no_error, + enum STBVorbisError + { + VORBIS__no_error, - VORBIS_need_more_data=1, // not a real error + VORBIS_need_more_data = 1, // not a real error - VORBIS_invalid_api_mixing, // can't mix API modes - VORBIS_outofmem, // not enough memory - VORBIS_feature_not_supported, // uses floor 0 - VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small - VORBIS_file_open_failure, // fopen() failed - VORBIS_seek_without_length, // can't seek in unknown-length file + VORBIS_invalid_api_mixing, // can't mix API modes + VORBIS_outofmem, // not enough memory + VORBIS_feature_not_supported, // uses floor 0 + VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small + VORBIS_file_open_failure, // fopen() failed + VORBIS_seek_without_length, // can't seek in unknown-length file - VORBIS_unexpected_eof=10, // file is truncated? - VORBIS_seek_invalid, // seek past EOF + VORBIS_unexpected_eof = 10, // file is truncated? + VORBIS_seek_invalid, // seek past EOF - // decoding errors (corrupt/invalid stream) -- you probably - // don't care about the exact details of these + // decoding errors (corrupt/invalid stream) -- you probably + // don't care about the exact details of these - // vorbis errors: - VORBIS_invalid_setup=20, - VORBIS_invalid_stream, + // vorbis errors: + VORBIS_invalid_setup = 20, + VORBIS_invalid_stream, - // ogg errors: - VORBIS_missing_capture_pattern=30, - VORBIS_invalid_stream_structure_version, - VORBIS_continued_packet_flag_invalid, - VORBIS_incorrect_stream_serial_number, - VORBIS_invalid_first_page, - VORBIS_bad_packet_type, - VORBIS_cant_find_last_page, - VORBIS_seek_failed -}; + // ogg errors: + VORBIS_missing_capture_pattern = 30, + VORBIS_invalid_stream_structure_version, + VORBIS_continued_packet_flag_invalid, + VORBIS_incorrect_stream_serial_number, + VORBIS_invalid_first_page, + VORBIS_bad_packet_type, + VORBIS_cant_find_last_page, + VORBIS_seek_failed + }; #ifdef __cplusplus @@ -516,25 +521,25 @@ enum STBVorbisError ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API - #define STB_VORBIS_NO_INTEGER_CONVERSION - #define STB_VORBIS_NO_STDIO +#define STB_VORBIS_NO_INTEGER_CONVERSION +#define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) - #define STB_VORBIS_NO_STDIO 1 +#define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT - // only need endianness for fast-float-to-int, which we don't - // use for pushdata +// only need endianness for fast-float-to-int, which we don't +// use for pushdata - #ifndef STB_VORBIS_BIG_ENDIAN - #define STB_VORBIS_ENDIAN 0 - #else - #define STB_VORBIS_ENDIAN 1 - #endif +#ifndef STB_VORBIS_BIG_ENDIAN +#define STB_VORBIS_ENDIAN 0 +#else +#define STB_VORBIS_ENDIAN 1 +#endif #endif #endif @@ -545,43 +550,44 @@ enum STBVorbisError #endif #ifndef STB_VORBIS_NO_CRT - #include <stdlib.h> - #include <string.h> - #include <assert.h> - #include <math.h> - - // find definition of alloca if it's not in stdlib.h: - #ifdef _MSC_VER - #include <malloc.h> - #endif - #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) - #include <alloca.h> - #endif +#include <stdlib.h> +#include <string.h> +#include <assert.h> +#include <math.h> + +// find definition of alloca if it's not in stdlib.h: +#if defined(_MSC_VER) || defined(__MINGW32__) +#include <malloc.h> +#endif +#if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) +#include <alloca.h> +#endif #else // STB_VORBIS_NO_CRT - #define NULL 0 - #define malloc(s) 0 - #define free(s) ((void) 0) - #define realloc(s) 0 +#define NULL 0 +#define malloc(s) 0 +#define free(s) ((void) 0) +#define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ - // eff you mingw: - // "fixed": - // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ - // "no that broke the build, reverted, who cares about C": - // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ - #ifdef __forceinline - #undef __forceinline - #endif - #define __forceinline +// eff you mingw: +// "fixed": +// http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ +// "no that broke the build, reverted, who cares about C": +// http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ +#ifdef __forceinline +#undef __forceinline +#endif +#define __forceinline +#define alloca __builtin_alloca #elif !defined(_MSC_VER) - #if __GNUC__ - #define __forceinline inline - #else - #define __forceinline - #endif +#if __GNUC__ +#define __forceinline inline +#else +#define __forceinline +#endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 @@ -636,237 +642,237 @@ typedef float codetype; typedef struct { - int dimensions, entries; - uint8 *codeword_lengths; - float minimum_value; - float delta_value; - uint8 value_bits; - uint8 lookup_type; - uint8 sequence_p; - uint8 sparse; - uint32 lookup_values; - codetype *multiplicands; - uint32 *codewords; - #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT + int dimensions, entries; + uint8 *codeword_lengths; + float minimum_value; + float delta_value; + uint8 value_bits; + uint8 lookup_type; + uint8 sequence_p; + uint8 sparse; + uint32 lookup_values; + codetype *multiplicands; + uint32 *codewords; +#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; - #else +#else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; - #endif - uint32 *sorted_codewords; - int *sorted_values; - int sorted_entries; +#endif + uint32 *sorted_codewords; + int *sorted_values; + int sorted_entries; } Codebook; typedef struct { - uint8 order; - uint16 rate; - uint16 bark_map_size; - uint8 amplitude_bits; - uint8 amplitude_offset; - uint8 number_of_books; - uint8 book_list[16]; // varies + uint8 order; + uint16 rate; + uint16 bark_map_size; + uint8 amplitude_bits; + uint8 amplitude_offset; + uint8 number_of_books; + uint8 book_list[16]; // varies } Floor0; typedef struct { - uint8 partitions; - uint8 partition_class_list[32]; // varies - uint8 class_dimensions[16]; // varies - uint8 class_subclasses[16]; // varies - uint8 class_masterbooks[16]; // varies - int16 subclass_books[16][8]; // varies - uint16 Xlist[31*8+2]; // varies - uint8 sorted_order[31*8+2]; - uint8 neighbors[31*8+2][2]; - uint8 floor1_multiplier; - uint8 rangebits; - int values; + uint8 partitions; + uint8 partition_class_list[32]; // varies + uint8 class_dimensions[16]; // varies + uint8 class_subclasses[16]; // varies + uint8 class_masterbooks[16]; // varies + int16 subclass_books[16][8]; // varies + uint16 Xlist[31 * 8 + 2]; // varies + uint8 sorted_order[31 * 8 + 2]; + uint8 neighbors[31 * 8 + 2][2]; + uint8 floor1_multiplier; + uint8 rangebits; + int values; } Floor1; typedef union { - Floor0 floor0; - Floor1 floor1; + Floor0 floor0; + Floor1 floor1; } Floor; typedef struct { - uint32 begin, end; - uint32 part_size; - uint8 classifications; - uint8 classbook; - uint8 **classdata; - int16 (*residue_books)[8]; + uint32 begin, end; + uint32 part_size; + uint8 classifications; + uint8 classbook; + uint8 **classdata; + int16(*residue_books)[8]; } Residue; typedef struct { - uint8 magnitude; - uint8 angle; - uint8 mux; + uint8 magnitude; + uint8 angle; + uint8 mux; } MappingChannel; typedef struct { - uint16 coupling_steps; - MappingChannel *chan; - uint8 submaps; - uint8 submap_floor[15]; // varies - uint8 submap_residue[15]; // varies + uint16 coupling_steps; + MappingChannel *chan; + uint8 submaps; + uint8 submap_floor[15]; // varies + uint8 submap_residue[15]; // varies } Mapping; typedef struct { - uint8 blockflag; - uint8 mapping; - uint16 windowtype; - uint16 transformtype; + uint8 blockflag; + uint8 mapping; + uint16 windowtype; + uint16 transformtype; } Mode; typedef struct { - uint32 goal_crc; // expected crc if match - int bytes_left; // bytes left in packet - uint32 crc_so_far; // running crc - int bytes_done; // bytes processed in _current_ chunk - uint32 sample_loc; // granule pos encoded in page + uint32 goal_crc; // expected crc if match + int bytes_left; // bytes left in packet + uint32 crc_so_far; // running crc + int bytes_done; // bytes processed in _current_ chunk + uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { - uint32 page_start, page_end; - uint32 last_decoded_sample; + uint32 page_start, page_end; + uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { - // user-accessible info - unsigned int sample_rate; - int channels; + // user-accessible info + unsigned int sample_rate; + int channels; - unsigned int setup_memory_required; - unsigned int temp_memory_required; - unsigned int setup_temp_memory_required; + unsigned int setup_memory_required; + unsigned int temp_memory_required; + unsigned int setup_temp_memory_required; - // input config + // input config #ifndef STB_VORBIS_NO_STDIO - FILE *f; - uint32 f_start; - int close_on_free; + FILE *f; + uint32 f_start; + int close_on_free; +#endif + + uint8 *stream; + uint8 *stream_start; + uint8 *stream_end; + + uint32 stream_len; + + uint8 push_mode; + + uint32 first_audio_page_offset; + + ProbedPage p_first, p_last; + + // memory management + stb_vorbis_alloc alloc; + int setup_offset; + int temp_offset; + + // run-time results + int eof; + enum STBVorbisError error; + + // user-useful data + + // header info + int blocksize[2]; + int blocksize_0, blocksize_1; + int codebook_count; + Codebook *codebooks; + int floor_count; + uint16 floor_types[64]; // varies + Floor *floor_config; + int residue_count; + uint16 residue_types[64]; // varies + Residue *residue_config; + int mapping_count; + Mapping *mapping; + int mode_count; + Mode mode_config[64]; // varies + + uint32 total_samples; + + // decode buffer + float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; + float *outputs[STB_VORBIS_MAX_CHANNELS]; + + float *previous_window[STB_VORBIS_MAX_CHANNELS]; + int previous_length; + +#ifndef STB_VORBIS_NO_DEFER_FLOOR + int16 *finalY[STB_VORBIS_MAX_CHANNELS]; +#else + float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif - uint8 *stream; - uint8 *stream_start; - uint8 *stream_end; - - uint32 stream_len; - - uint8 push_mode; - - uint32 first_audio_page_offset; - - ProbedPage p_first, p_last; - - // memory management - stb_vorbis_alloc alloc; - int setup_offset; - int temp_offset; - - // run-time results - int eof; - enum STBVorbisError error; - - // user-useful data - - // header info - int blocksize[2]; - int blocksize_0, blocksize_1; - int codebook_count; - Codebook *codebooks; - int floor_count; - uint16 floor_types[64]; // varies - Floor *floor_config; - int residue_count; - uint16 residue_types[64]; // varies - Residue *residue_config; - int mapping_count; - Mapping *mapping; - int mode_count; - Mode mode_config[64]; // varies - - uint32 total_samples; - - // decode buffer - float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; - float *outputs [STB_VORBIS_MAX_CHANNELS]; - - float *previous_window[STB_VORBIS_MAX_CHANNELS]; - int previous_length; - - #ifndef STB_VORBIS_NO_DEFER_FLOOR - int16 *finalY[STB_VORBIS_MAX_CHANNELS]; - #else - float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; - #endif - - uint32 current_loc; // sample location of next frame to decode - int current_loc_valid; - - // per-blocksize precomputed data - - // twiddle factors - float *A[2],*B[2],*C[2]; - float *window[2]; - uint16 *bit_reverse[2]; - - // current page/packet/segment streaming info - uint32 serial; // stream serial number for verification - int last_page; - int segment_count; - uint8 segments[255]; - uint8 page_flag; - uint8 bytes_in_seg; - uint8 first_decode; - int next_seg; - int last_seg; // flag that we're on the last segment - int last_seg_which; // what was the segment number of the last seg? - uint32 acc; - int valid_bits; - int packet_bytes; - int end_seg_with_known_loc; - uint32 known_loc_for_packet; - int discard_samples_deferred; - uint32 samples_output; - - // push mode scanning - int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching + uint32 current_loc; // sample location of next frame to decode + int current_loc_valid; + + // per-blocksize precomputed data + + // twiddle factors + float *A[2], *B[2], *C[2]; + float *window[2]; + uint16 *bit_reverse[2]; + + // current page/packet/segment streaming info + uint32 serial; // stream serial number for verification + int last_page; + int segment_count; + uint8 segments[255]; + uint8 page_flag; + uint8 bytes_in_seg; + uint8 first_decode; + int next_seg; + int last_seg; // flag that we're on the last segment + int last_seg_which; // what was the segment number of the last seg? + uint32 acc; + int valid_bits; + int packet_bytes; + int end_seg_with_known_loc; + uint32 known_loc_for_packet; + int discard_samples_deferred; + uint32 samples_output; + + // push mode scanning + int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API - CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; + CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif - // sample-access - int channel_buffer_start; - int channel_buffer_end; + // sample-access + int channel_buffer_start; + int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) - #define IS_PUSH_MODE(f) FALSE +#define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) - #define IS_PUSH_MODE(f) TRUE +#define IS_PUSH_MODE(f) TRUE #else - #define IS_PUSH_MODE(f) ((f)->push_mode) +#define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { - f->error = e; - if (!f->eof && e != VORBIS_need_more_data) { - f->error=e; // breakpoint for debugging - } - return 0; + f->error = e; + if (!f->eof && e != VORBIS_need_more_data) { + f->error = e; // breakpoint for debugging + } + return 0; } @@ -878,11 +884,7 @@ static int error(vorb *f, enum STBVorbisError e) #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) -#ifdef dealloca -#define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size)) -#else #define temp_free(f,p) 0 -#endif #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) @@ -891,53 +893,53 @@ static int error(vorb *f, enum STBVorbisError e) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { - int i; - void ** p = (void **) mem; - char *q = (char *) (p + count); - for (i=0; i < count; ++i) { - p[i] = q; - q += size; - } - return p; + int i; + void ** p = (void **)mem; + char *q = (char *)(p + count); + for (i = 0; i < count; ++i) { + p[i] = q; + q += size; + } + return p; } static void *setup_malloc(vorb *f, int sz) { - sz = (sz+3) & ~3; - f->setup_memory_required += sz; - if (f->alloc.alloc_buffer) { - void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; - if (f->setup_offset + sz > f->temp_offset) return NULL; - f->setup_offset += sz; - return p; - } - return sz ? malloc(sz) : NULL; + sz = (sz + 3) & ~3; + f->setup_memory_required += sz; + if (f->alloc.alloc_buffer) { + void *p = (char *)f->alloc.alloc_buffer + f->setup_offset; + if (f->setup_offset + sz > f->temp_offset) return NULL; + f->setup_offset += sz; + return p; + } + return sz ? malloc(sz) : NULL; } static void setup_free(vorb *f, void *p) { - if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack - free(p); + if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack + free(p); } static void *setup_temp_malloc(vorb *f, int sz) { - sz = (sz+3) & ~3; - if (f->alloc.alloc_buffer) { - if (f->temp_offset - sz < f->setup_offset) return NULL; - f->temp_offset -= sz; - return (char *) f->alloc.alloc_buffer + f->temp_offset; - } - return malloc(sz); + sz = (sz + 3) & ~3; + if (f->alloc.alloc_buffer) { + if (f->temp_offset - sz < f->setup_offset) return NULL; + f->temp_offset -= sz; + return (char *)f->alloc.alloc_buffer + f->temp_offset; + } + return malloc(sz); } static void setup_temp_free(vorb *f, void *p, int sz) { - if (f->alloc.alloc_buffer) { - f->temp_offset += (sz+3)&~3; - return; - } - free(p); + if (f->alloc.alloc_buffer) { + f->temp_offset += (sz + 3)&~3; + return; + } + free(p); } #define CRC32_POLY 0x04c11db7 // from spec @@ -945,34 +947,34 @@ static void setup_temp_free(vorb *f, void *p, int sz) static uint32 crc_table[256]; static void crc32_init(void) { - int i,j; - uint32 s; - for(i=0; i < 256; i++) { - for (s=(uint32) i << 24, j=0; j < 8; ++j) - s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); - crc_table[i] = s; - } + int i, j; + uint32 s; + for (i = 0; i < 256; i++) { + for (s = (uint32)i << 24, j = 0; j < 8; ++j) + s = (s << 1) ^ (s >= (1U << 31) ? CRC32_POLY : 0); + crc_table[i] = s; + } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { - return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; + return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { - n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); - n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); - n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); - n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); - return (n >> 16) | (n << 16); + n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); + n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); + n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); + n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); + return (n >> 16) | (n << 16); } static float square(float x) { - return x*x; + return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 @@ -980,24 +982,24 @@ static float square(float x) // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { - static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; + static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; - if (n < 0) return 0; // signed n returns 0 + if (n < 0) return 0; // signed n returns 0 - // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) - if (n < (1 << 14)) - if (n < (1 << 4)) return 0 + log2_4[n ]; - else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; - else return 10 + log2_4[n >> 10]; - else if (n < (1 << 24)) - if (n < (1 << 19)) return 15 + log2_4[n >> 15]; - else return 20 + log2_4[n >> 20]; - else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; - else return 30 + log2_4[n >> 30]; + // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) + if (n < (1 << 14)) + if (n < (1 << 4)) return 0 + log2_4[n]; + else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; + else return 10 + log2_4[n >> 10]; + else if (n < (1 << 24)) + if (n < (1 << 19)) return 15 + log2_4[n >> 15]; + else return 20 + log2_4[n >> 20]; + else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; + else return 30 + log2_4[n >> 30]; } #ifndef M_PI - #define M_PI 3.14159265358979323846264f // from CRC +#define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding @@ -1010,12 +1012,12 @@ static int ilog(int32 n) static float float32_unpack(uint32 x) { - // from the specification - uint32 mantissa = x & 0x1fffff; - uint32 sign = x & 0x80000000; - uint32 exp = (x & 0x7fe00000) >> 21; - double res = sign ? -(double)mantissa : (double)mantissa; - return (float) ldexp((float)res, exp-788); + // from the specification + uint32 mantissa = x & 0x1fffff; + uint32 sign = x & 0x80000000; + uint32 exp = (x & 0x7fe00000) >> 21; + double res = sign ? -(double)mantissa : (double)mantissa; + return (float)ldexp((float)res, exp - 788); } @@ -1028,83 +1030,84 @@ static float float32_unpack(uint32 x) // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { - if (!c->sparse) { - c->codewords [symbol] = huff_code; - } else { - c->codewords [count] = huff_code; - c->codeword_lengths[count] = len; - values [count] = symbol; - } + if (!c->sparse) { + c->codewords[symbol] = huff_code; + } + else { + c->codewords[count] = huff_code; + c->codeword_lengths[count] = len; + values[count] = symbol; + } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { - int i,k,m=0; - uint32 available[32]; - - memset(available, 0, sizeof(available)); - // find the first entry - for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; - if (k == n) { assert(c->sorted_entries == 0); return TRUE; } - // add to the list - add_entry(c, 0, k, m++, len[k], values); - // add all available leaves - for (i=1; i <= len[k]; ++i) - available[i] = 1U << (32-i); - // note that the above code treats the first case specially, - // but it's really the same as the following code, so they - // could probably be combined (except the initial code is 0, - // and I use 0 in available[] to mean 'empty') - for (i=k+1; i < n; ++i) { - uint32 res; - int z = len[i], y; - if (z == NO_CODE) continue; - // find lowest available leaf (should always be earliest, - // which is what the specification calls for) - // note that this property, and the fact we can never have - // more than one free leaf at a given level, isn't totally - // trivial to prove, but it seems true and the assert never - // fires, so! - while (z > 0 && !available[z]) --z; - if (z == 0) { return FALSE; } - res = available[z]; - assert(z >= 0 && z < 32); - available[z] = 0; - add_entry(c, bit_reverse(res), i, m++, len[i], values); - // propogate availability up the tree - if (z != len[i]) { - assert(len[i] >= 0 && len[i] < 32); - for (y=len[i]; y > z; --y) { - assert(available[y] == 0); - available[y] = res + (1 << (32-y)); - } - } - } - return TRUE; + int i, k, m = 0; + uint32 available[32]; + + memset(available, 0, sizeof(available)); + // find the first entry + for (k = 0; k < n; ++k) if (len[k] < NO_CODE) break; + if (k == n) { assert(c->sorted_entries == 0); return TRUE; } + // add to the list + add_entry(c, 0, k, m++, len[k], values); + // add all available leaves + for (i = 1; i <= len[k]; ++i) + available[i] = 1U << (32 - i); + // note that the above code treats the first case specially, + // but it's really the same as the following code, so they + // could probably be combined (except the initial code is 0, + // and I use 0 in available[] to mean 'empty') + for (i = k + 1; i < n; ++i) { + uint32 res; + int z = len[i], y; + if (z == NO_CODE) continue; + // find lowest available leaf (should always be earliest, + // which is what the specification calls for) + // note that this property, and the fact we can never have + // more than one free leaf at a given level, isn't totally + // trivial to prove, but it seems true and the assert never + // fires, so! + while (z > 0 && !available[z]) --z; + if (z == 0) { return FALSE; } + res = available[z]; + assert(z >= 0 && z < 32); + available[z] = 0; + add_entry(c, bit_reverse(res), i, m++, len[i], values); + // propogate availability up the tree + if (z != len[i]) { + assert(len[i] >= 0 && len[i] < 32); + for (y = len[i]; y > z; --y) { + assert(available[y] == 0); + available[y] = res + (1 << (32 - y)); + } + } + } + return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { - int i, len; - for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) - c->fast_huffman[i] = -1; - - len = c->sparse ? c->sorted_entries : c->entries; - #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT - if (len > 32767) len = 32767; // largest possible value we can encode! - #endif - for (i=0; i < len; ++i) { - if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { - uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; - // set table entries for all bit combinations in the higher bits - while (z < FAST_HUFFMAN_TABLE_SIZE) { - c->fast_huffman[z] = i; - z += 1 << c->codeword_lengths[i]; - } - } - } + int i, len; + for (i = 0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) + c->fast_huffman[i] = -1; + + len = c->sparse ? c->sorted_entries : c->entries; +#ifdef STB_VORBIS_FAST_HUFFMAN_SHORT + if (len > 32767) len = 32767; // largest possible value we can encode! +#endif + for (i = 0; i < len; ++i) { + if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { + uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; + // set table entries for all bit combinations in the higher bits + while (z < FAST_HUFFMAN_TABLE_SIZE) { + c->fast_huffman[z] = i; + z += 1 << c->codeword_lengths[i]; + } + } + } } #ifdef _MSC_VER @@ -1115,165 +1118,168 @@ static void compute_accelerated_huffman(Codebook *c) static int STBV_CDECL uint32_compare(const void *p, const void *q) { - uint32 x = * (uint32 *) p; - uint32 y = * (uint32 *) q; - return x < y ? -1 : x > y; + uint32 x = *(uint32 *)p; + uint32 y = *(uint32 *)q; + return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { - if (c->sparse) { assert(len != NO_CODE); return TRUE; } - if (len == NO_CODE) return FALSE; - if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; - return FALSE; + if (c->sparse) { assert(len != NO_CODE); return TRUE; } + if (len == NO_CODE) return FALSE; + if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; + return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { - int i, len; - // build a list of all the entries - // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. - // this is kind of a frivolous optimization--I don't see any performance improvement, - // but it's like 4 extra lines of code, so. - if (!c->sparse) { - int k = 0; - for (i=0; i < c->entries; ++i) - if (include_in_sort(c, lengths[i])) - c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); - assert(k == c->sorted_entries); - } else { - for (i=0; i < c->sorted_entries; ++i) - c->sorted_codewords[i] = bit_reverse(c->codewords[i]); - } - - qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); - c->sorted_codewords[c->sorted_entries] = 0xffffffff; - - len = c->sparse ? c->sorted_entries : c->entries; - // now we need to indicate how they correspond; we could either - // #1: sort a different data structure that says who they correspond to - // #2: for each sorted entry, search the original list to find who corresponds - // #3: for each original entry, find the sorted entry - // #1 requires extra storage, #2 is slow, #3 can use binary search! - for (i=0; i < len; ++i) { - int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; - if (include_in_sort(c,huff_len)) { - uint32 code = bit_reverse(c->codewords[i]); - int x=0, n=c->sorted_entries; - while (n > 1) { - // invariant: sc[x] <= code < sc[x+n] - int m = x + (n >> 1); - if (c->sorted_codewords[m] <= code) { - x = m; - n -= (n>>1); - } else { - n >>= 1; + int i, len; + // build a list of all the entries + // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. + // this is kind of a frivolous optimization--I don't see any performance improvement, + // but it's like 4 extra lines of code, so. + if (!c->sparse) { + int k = 0; + for (i = 0; i < c->entries; ++i) + if (include_in_sort(c, lengths[i])) + c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); + assert(k == c->sorted_entries); + } + else { + for (i = 0; i < c->sorted_entries; ++i) + c->sorted_codewords[i] = bit_reverse(c->codewords[i]); + } + + qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); + c->sorted_codewords[c->sorted_entries] = 0xffffffff; + + len = c->sparse ? c->sorted_entries : c->entries; + // now we need to indicate how they correspond; we could either + // #1: sort a different data structure that says who they correspond to + // #2: for each sorted entry, search the original list to find who corresponds + // #3: for each original entry, find the sorted entry + // #1 requires extra storage, #2 is slow, #3 can use binary search! + for (i = 0; i < len; ++i) { + int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; + if (include_in_sort(c, huff_len)) { + uint32 code = bit_reverse(c->codewords[i]); + int x = 0, n = c->sorted_entries; + while (n > 1) { + // invariant: sc[x] <= code < sc[x+n] + int m = x + (n >> 1); + if (c->sorted_codewords[m] <= code) { + x = m; + n -= (n >> 1); + } + else { + n >>= 1; + } } - } - assert(c->sorted_codewords[x] == code); - if (c->sparse) { - c->sorted_values[x] = values[i]; - c->codeword_lengths[x] = huff_len; - } else { - c->sorted_values[x] = i; - } - } - } + assert(c->sorted_codewords[x] == code); + if (c->sparse) { + c->sorted_values[x] = values[i]; + c->codeword_lengths[x] = huff_len; + } + else { + c->sorted_values[x] = i; + } + } + } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { - static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; - return memcmp(data, vorbis, 6) == 0; + static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; + return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { - int r = (int) floor(exp((float) log((float) entries) / dim)); - if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; - ++r; // floor() to avoid _ftol() when non-CRT - assert(pow((float) r+1, dim) > entries); - assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above - return r; + int r = (int)floor(exp((float)log((float)entries) / dim)); + if ((int)floor(pow((float)r + 1, dim)) <= entries) // (int) cast for MinGW warning; + ++r; // floor() to avoid _ftol() when non-CRT + assert(pow((float)r + 1, dim) > entries); + assert((int)floor(pow((float)r, dim)) <= entries); // (int),floor() as above + return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { - int n4 = n >> 2, n8 = n >> 3; - int k,k2; - - for (k=k2=0; k < n4; ++k,k2+=2) { - A[k2 ] = (float) cos(4*k*M_PI/n); - A[k2+1] = (float) -sin(4*k*M_PI/n); - B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; - B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; - } - for (k=k2=0; k < n8; ++k,k2+=2) { - C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); - C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); - } + int n4 = n >> 2, n8 = n >> 3; + int k, k2; + + for (k = k2 = 0; k < n4; ++k, k2 += 2) { + A[k2] = (float)cos(4 * k*M_PI / n); + A[k2 + 1] = (float)-sin(4 * k*M_PI / n); + B[k2] = (float)cos((k2 + 1)*M_PI / n / 2) * 0.5f; + B[k2 + 1] = (float)sin((k2 + 1)*M_PI / n / 2) * 0.5f; + } + for (k = k2 = 0; k < n8; ++k, k2 += 2) { + C[k2] = (float)cos(2 * (k2 + 1)*M_PI / n); + C[k2 + 1] = (float)-sin(2 * (k2 + 1)*M_PI / n); + } } static void compute_window(int n, float *window) { - int n2 = n >> 1, i; - for (i=0; i < n2; ++i) - window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); + int n2 = n >> 1, i; + for (i = 0; i < n2; ++i) + window[i] = (float)sin(0.5 * M_PI * square((float)sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { - int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions - int i, n8 = n >> 3; - for (i=0; i < n8; ++i) - rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; + int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions + int i, n8 = n >> 3; + for (i = 0; i < n8; ++i) + rev[i] = (bit_reverse(i) >> (32 - ld + 3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { - int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; - f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); - f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); - f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); - if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); - compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); - f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); - if (!f->window[b]) return error(f, VORBIS_outofmem); - compute_window(n, f->window[b]); - f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); - if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); - compute_bitreverse(n, f->bit_reverse[b]); - return TRUE; + int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; + f->A[b] = (float *)setup_malloc(f, sizeof(float) * n2); + f->B[b] = (float *)setup_malloc(f, sizeof(float) * n2); + f->C[b] = (float *)setup_malloc(f, sizeof(float) * n4); + if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); + compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); + f->window[b] = (float *)setup_malloc(f, sizeof(float) * n2); + if (!f->window[b]) return error(f, VORBIS_outofmem); + compute_window(n, f->window[b]); + f->bit_reverse[b] = (uint16 *)setup_malloc(f, sizeof(uint16) * n8); + if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); + compute_bitreverse(n, f->bit_reverse[b]); + return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { - int low = -1; - int high = 65536; - int i; - for (i=0; i < n; ++i) { - if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } - if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } - } + int low = -1; + int high = 65536; + int i; + for (i = 0; i < n; ++i) { + if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } + if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } + } } // this has been repurposed so y is now the original index instead of y typedef struct { - uint16 x,id; + uint16 x, id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void *p, const void *q) { - stbv__floor_ordering *a = (stbv__floor_ordering *) p; - stbv__floor_ordering *b = (stbv__floor_ordering *) q; - return a->x < b->x ? -1 : a->x > b->x; + stbv__floor_ordering *a = (stbv__floor_ordering *)p; + stbv__floor_ordering *b = (stbv__floor_ordering *)q; + return a->x < b->x ? -1 : a->x > b->x; } // @@ -1281,100 +1287,102 @@ static int STBV_CDECL point_compare(const void *p, const void *q) #if defined(STB_VORBIS_NO_STDIO) - #define USE_MEMORY(z) TRUE +#define USE_MEMORY(z) TRUE #else - #define USE_MEMORY(z) ((z)->stream) +#define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { - if (USE_MEMORY(z)) { - if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } - return *z->stream++; - } + if (USE_MEMORY(z)) { + if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } + return *z->stream++; + } - #ifndef STB_VORBIS_NO_STDIO - { - int c = fgetc(z->f); - if (c == EOF) { z->eof = TRUE; return 0; } - return c; - } - #endif +#ifndef STB_VORBIS_NO_STDIO + { + int c = fgetc(z->f); + if (c == EOF) { z->eof = TRUE; return 0; } + return c; + } +#endif } static uint32 get32(vorb *f) { - uint32 x; - x = get8(f); - x += get8(f) << 8; - x += get8(f) << 16; - x += (uint32) get8(f) << 24; - return x; + uint32 x; + x = get8(f); + x += get8(f) << 8; + x += get8(f) << 16; + x += (uint32)get8(f) << 24; + return x; } static int getn(vorb *z, uint8 *data, int n) { - if (USE_MEMORY(z)) { - if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } - memcpy(data, z->stream, n); - z->stream += n; - return 1; - } - - #ifndef STB_VORBIS_NO_STDIO - if (fread(data, n, 1, z->f) == 1) - return 1; - else { - z->eof = 1; - return 0; - } - #endif + if (USE_MEMORY(z)) { + if (z->stream + n > z->stream_end) { z->eof = 1; return 0; } + memcpy(data, z->stream, n); + z->stream += n; + return 1; + } + +#ifndef STB_VORBIS_NO_STDIO + if (fread(data, n, 1, z->f) == 1) + return 1; + else { + z->eof = 1; + return 0; + } +#endif } static void skip(vorb *z, int n) { - if (USE_MEMORY(z)) { - z->stream += n; - if (z->stream >= z->stream_end) z->eof = 1; - return; - } - #ifndef STB_VORBIS_NO_STDIO - { - long x = ftell(z->f); - fseek(z->f, x+n, SEEK_SET); - } - #endif + if (USE_MEMORY(z)) { + z->stream += n; + if (z->stream >= z->stream_end) z->eof = 1; + return; + } +#ifndef STB_VORBIS_NO_STDIO + { + long x = ftell(z->f); + fseek(z->f, x + n, SEEK_SET); + } +#endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { - #ifndef STB_VORBIS_NO_PUSHDATA_API - if (f->push_mode) return 0; - #endif - f->eof = 0; - if (USE_MEMORY(f)) { - if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { - f->stream = f->stream_end; - f->eof = 1; - return 0; - } else { - f->stream = f->stream_start + loc; - return 1; - } - } - #ifndef STB_VORBIS_NO_STDIO - if (loc + f->f_start < loc || loc >= 0x80000000) { - loc = 0x7fffffff; - f->eof = 1; - } else { - loc += f->f_start; - } - if (!fseek(f->f, loc, SEEK_SET)) - return 1; - f->eof = 1; - fseek(f->f, f->f_start, SEEK_END); - return 0; - #endif +#ifndef STB_VORBIS_NO_PUSHDATA_API + if (f->push_mode) return 0; +#endif + f->eof = 0; + if (USE_MEMORY(f)) { + if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { + f->stream = f->stream_end; + f->eof = 1; + return 0; + } + else { + f->stream = f->stream_start + loc; + return 1; + } + } +#ifndef STB_VORBIS_NO_STDIO + if (loc + f->f_start < loc || loc >= 0x80000000) { + loc = 0x7fffffff; + f->eof = 1; + } + else { + loc += f->f_start; + } + if (!fseek(f->f, loc, SEEK_SET)) + return 1; + f->eof = 1; + fseek(f->f, f->f_start, SEEK_END); + return 0; +#endif } @@ -1382,11 +1390,11 @@ static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { - if (0x4f != get8(f)) return FALSE; - if (0x67 != get8(f)) return FALSE; - if (0x67 != get8(f)) return FALSE; - if (0x53 != get8(f)) return FALSE; - return TRUE; + if (0x4f != get8(f)) return FALSE; + if (0x67 != get8(f)) return FALSE; + if (0x67 != get8(f)) return FALSE; + if (0x53 != get8(f)) return FALSE; + return TRUE; } #define PAGEFLAG_continued_packet 1 @@ -1395,118 +1403,118 @@ static int capture_pattern(vorb *f) static int start_page_no_capturepattern(vorb *f) { - uint32 loc0,loc1,n; - // stream structure version - if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); - // header flag - f->page_flag = get8(f); - // absolute granule position - loc0 = get32(f); - loc1 = get32(f); - // @TODO: validate loc0,loc1 as valid positions? - // stream serial number -- vorbis doesn't interleave, so discard - get32(f); - //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); - // page sequence number - n = get32(f); - f->last_page = n; - // CRC32 - get32(f); - // page_segments - f->segment_count = get8(f); - if (!getn(f, f->segments, f->segment_count)) - return error(f, VORBIS_unexpected_eof); - // assume we _don't_ know any the sample position of any segments - f->end_seg_with_known_loc = -2; - if (loc0 != ~0U || loc1 != ~0U) { - int i; - // determine which packet is the last one that will complete - for (i=f->segment_count-1; i >= 0; --i) - if (f->segments[i] < 255) - break; - // 'i' is now the index of the _last_ segment of a packet that ends - if (i >= 0) { - f->end_seg_with_known_loc = i; - f->known_loc_for_packet = loc0; - } - } - if (f->first_decode) { - int i,len; - ProbedPage p; - len = 0; - for (i=0; i < f->segment_count; ++i) - len += f->segments[i]; - len += 27 + f->segment_count; - p.page_start = f->first_audio_page_offset; - p.page_end = p.page_start + len; - p.last_decoded_sample = loc0; - f->p_first = p; - } - f->next_seg = 0; - return TRUE; + uint32 loc0, loc1, n; + // stream structure version + if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); + // header flag + f->page_flag = get8(f); + // absolute granule position + loc0 = get32(f); + loc1 = get32(f); + // @TODO: validate loc0,loc1 as valid positions? + // stream serial number -- vorbis doesn't interleave, so discard + get32(f); + //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); + // page sequence number + n = get32(f); + f->last_page = n; + // CRC32 + get32(f); + // page_segments + f->segment_count = get8(f); + if (!getn(f, f->segments, f->segment_count)) + return error(f, VORBIS_unexpected_eof); + // assume we _don't_ know any the sample position of any segments + f->end_seg_with_known_loc = -2; + if (loc0 != ~0U || loc1 != ~0U) { + int i; + // determine which packet is the last one that will complete + for (i = f->segment_count - 1; i >= 0; --i) + if (f->segments[i] < 255) + break; + // 'i' is now the index of the _last_ segment of a packet that ends + if (i >= 0) { + f->end_seg_with_known_loc = i; + f->known_loc_for_packet = loc0; + } + } + if (f->first_decode) { + int i, len; + ProbedPage p; + len = 0; + for (i = 0; i < f->segment_count; ++i) + len += f->segments[i]; + len += 27 + f->segment_count; + p.page_start = f->first_audio_page_offset; + p.page_end = p.page_start + len; + p.last_decoded_sample = loc0; + f->p_first = p; + } + f->next_seg = 0; + return TRUE; } static int start_page(vorb *f) { - if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); - return start_page_no_capturepattern(f); + if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); + return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { - while (f->next_seg == -1) { - if (!start_page(f)) return FALSE; - if (f->page_flag & PAGEFLAG_continued_packet) - return error(f, VORBIS_continued_packet_flag_invalid); - } - f->last_seg = FALSE; - f->valid_bits = 0; - f->packet_bytes = 0; - f->bytes_in_seg = 0; - // f->next_seg is now valid - return TRUE; + while (f->next_seg == -1) { + if (!start_page(f)) return FALSE; + if (f->page_flag & PAGEFLAG_continued_packet) + return error(f, VORBIS_continued_packet_flag_invalid); + } + f->last_seg = FALSE; + f->valid_bits = 0; + f->packet_bytes = 0; + f->bytes_in_seg = 0; + // f->next_seg is now valid + return TRUE; } static int maybe_start_packet(vorb *f) { - if (f->next_seg == -1) { - int x = get8(f); - if (f->eof) return FALSE; // EOF at page boundary is not an error! - if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); - if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); - if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); - if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); - if (!start_page_no_capturepattern(f)) return FALSE; - if (f->page_flag & PAGEFLAG_continued_packet) { - // set up enough state that we can read this packet if we want, - // e.g. during recovery - f->last_seg = FALSE; - f->bytes_in_seg = 0; - return error(f, VORBIS_continued_packet_flag_invalid); - } - } - return start_packet(f); + if (f->next_seg == -1) { + int x = get8(f); + if (f->eof) return FALSE; // EOF at page boundary is not an error! + if (0x4f != x) return error(f, VORBIS_missing_capture_pattern); + if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); + if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); + if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); + if (!start_page_no_capturepattern(f)) return FALSE; + if (f->page_flag & PAGEFLAG_continued_packet) { + // set up enough state that we can read this packet if we want, + // e.g. during recovery + f->last_seg = FALSE; + f->bytes_in_seg = 0; + return error(f, VORBIS_continued_packet_flag_invalid); + } + } + return start_packet(f); } static int next_segment(vorb *f) { - int len; - if (f->last_seg) return 0; - if (f->next_seg == -1) { - f->last_seg_which = f->segment_count-1; // in case start_page fails - if (!start_page(f)) { f->last_seg = 1; return 0; } - if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); - } - len = f->segments[f->next_seg++]; - if (len < 255) { - f->last_seg = TRUE; - f->last_seg_which = f->next_seg-1; - } - if (f->next_seg >= f->segment_count) - f->next_seg = -1; - assert(f->bytes_in_seg == 0); - f->bytes_in_seg = len; - return len; + int len; + if (f->last_seg) return 0; + if (f->next_seg == -1) { + f->last_seg_which = f->segment_count - 1; // in case start_page fails + if (!start_page(f)) { f->last_seg = 1; return 0; } + if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); + } + len = f->segments[f->next_seg++]; + if (len < 255) { + f->last_seg = TRUE; + f->last_seg_which = f->next_seg - 1; + } + if (f->next_seg >= f->segment_count) + f->next_seg = -1; + assert(f->bytes_in_seg == 0); + f->bytes_in_seg = len; + return len; } #define EOP (-1) @@ -1514,58 +1522,58 @@ static int next_segment(vorb *f) static int get8_packet_raw(vorb *f) { - if (!f->bytes_in_seg) { // CLANG! - if (f->last_seg) return EOP; - else if (!next_segment(f)) return EOP; - } - assert(f->bytes_in_seg > 0); - --f->bytes_in_seg; - ++f->packet_bytes; - return get8(f); + if (!f->bytes_in_seg) { // CLANG! + if (f->last_seg) return EOP; + else if (!next_segment(f)) return EOP; + } + assert(f->bytes_in_seg > 0); + --f->bytes_in_seg; + ++f->packet_bytes; + return get8(f); } static int get8_packet(vorb *f) { - int x = get8_packet_raw(f); - f->valid_bits = 0; - return x; + int x = get8_packet_raw(f); + f->valid_bits = 0; + return x; } static void flush_packet(vorb *f) { - while (get8_packet_raw(f) != EOP); + while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { - uint32 z; - - if (f->valid_bits < 0) return 0; - if (f->valid_bits < n) { - if (n > 24) { - // the accumulator technique below would not work correctly in this case - z = get_bits(f, 24); - z += get_bits(f, n-24) << 24; - return z; - } - if (f->valid_bits == 0) f->acc = 0; - while (f->valid_bits < n) { - int z = get8_packet_raw(f); - if (z == EOP) { - f->valid_bits = INVALID_BITS; - return 0; - } - f->acc += z << f->valid_bits; - f->valid_bits += 8; - } - } - if (f->valid_bits < 0) return 0; - z = f->acc & ((1 << n)-1); - f->acc >>= n; - f->valid_bits -= n; - return z; + uint32 z; + + if (f->valid_bits < 0) return 0; + if (f->valid_bits < n) { + if (n > 24) { + // the accumulator technique below would not work correctly in this case + z = get_bits(f, 24); + z += get_bits(f, n - 24) << 24; + return z; + } + if (f->valid_bits == 0) f->acc = 0; + while (f->valid_bits < n) { + int z = get8_packet_raw(f); + if (z == EOP) { + f->valid_bits = INVALID_BITS; + return 0; + } + f->acc += z << f->valid_bits; + f->valid_bits += 8; + } + } + if (f->valid_bits < 0) return 0; + z = f->acc & ((1 << n) - 1); + f->acc >>= n; + f->valid_bits -= n; + return z; } // @OPTIMIZE: primary accumulator for huffman @@ -1574,83 +1582,84 @@ static uint32 get_bits(vorb *f, int n) // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb *f) { - if (f->valid_bits <= 24) { - if (f->valid_bits == 0) f->acc = 0; - do { - int z; - if (f->last_seg && !f->bytes_in_seg) return; - z = get8_packet_raw(f); - if (z == EOP) return; - f->acc += (unsigned) z << f->valid_bits; - f->valid_bits += 8; - } while (f->valid_bits <= 24); - } + if (f->valid_bits <= 24) { + if (f->valid_bits == 0) f->acc = 0; + do { + int z; + if (f->last_seg && !f->bytes_in_seg) return; + z = get8_packet_raw(f); + if (z == EOP) return; + f->acc += (unsigned)z << f->valid_bits; + f->valid_bits += 8; + } while (f->valid_bits <= 24); + } } enum { - VORBIS_packet_id = 1, - VORBIS_packet_comment = 3, - VORBIS_packet_setup = 5 + VORBIS_packet_id = 1, + VORBIS_packet_comment = 3, + VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { - int i; - prep_huffman(f); - - if (c->codewords == NULL && c->sorted_codewords == NULL) - return -1; - - // cases to use binary search: sorted_codewords && !c->codewords - // sorted_codewords && c->entries > 8 - if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { - // binary search - uint32 code = bit_reverse(f->acc); - int x=0, n=c->sorted_entries, len; - - while (n > 1) { - // invariant: sc[x] <= code < sc[x+n] - int m = x + (n >> 1); - if (c->sorted_codewords[m] <= code) { - x = m; - n -= (n>>1); - } else { - n >>= 1; - } - } - // x is now the sorted index - if (!c->sparse) x = c->sorted_values[x]; - // x is now sorted index if sparse, or symbol otherwise - len = c->codeword_lengths[x]; - if (f->valid_bits >= len) { - f->acc >>= len; - f->valid_bits -= len; - return x; - } - - f->valid_bits = 0; - return -1; - } + int i; + prep_huffman(f); - // if small, linear search - assert(!c->sparse); - for (i=0; i < c->entries; ++i) { - if (c->codeword_lengths[i] == NO_CODE) continue; - if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) { - if (f->valid_bits >= c->codeword_lengths[i]) { - f->acc >>= c->codeword_lengths[i]; - f->valid_bits -= c->codeword_lengths[i]; - return i; - } - f->valid_bits = 0; - return -1; - } - } + if (c->codewords == NULL && c->sorted_codewords == NULL) + return -1; - error(f, VORBIS_invalid_stream); - f->valid_bits = 0; - return -1; + // cases to use binary search: sorted_codewords && !c->codewords + // sorted_codewords && c->entries > 8 + if (c->entries > 8 ? c->sorted_codewords != NULL : !c->codewords) { + // binary search + uint32 code = bit_reverse(f->acc); + int x = 0, n = c->sorted_entries, len; + + while (n > 1) { + // invariant: sc[x] <= code < sc[x+n] + int m = x + (n >> 1); + if (c->sorted_codewords[m] <= code) { + x = m; + n -= (n >> 1); + } + else { + n >>= 1; + } + } + // x is now the sorted index + if (!c->sparse) x = c->sorted_values[x]; + // x is now sorted index if sparse, or symbol otherwise + len = c->codeword_lengths[x]; + if (f->valid_bits >= len) { + f->acc >>= len; + f->valid_bits -= len; + return x; + } + + f->valid_bits = 0; + return -1; + } + + // if small, linear search + assert(!c->sparse); + for (i = 0; i < c->entries; ++i) { + if (c->codeword_lengths[i] == NO_CODE) continue; + if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i]) - 1))) { + if (f->valid_bits >= c->codeword_lengths[i]) { + f->acc >>= c->codeword_lengths[i]; + f->valid_bits -= c->codeword_lengths[i]; + return i; + } + f->valid_bits = 0; + return -1; + } + } + + error(f, VORBIS_invalid_stream); + f->valid_bits = 0; + return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE @@ -1673,19 +1682,19 @@ static int codebook_decode_scalar_raw(vorb *f, Codebook *c) static int codebook_decode_scalar(vorb *f, Codebook *c) { - int i; - if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) - prep_huffman(f); - // fast huffman table lookup - i = f->acc & FAST_HUFFMAN_TABLE_MASK; - i = c->fast_huffman[i]; - if (i >= 0) { - f->acc >>= c->codeword_lengths[i]; - f->valid_bits -= c->codeword_lengths[i]; - if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } - return i; - } - return codebook_decode_scalar_raw(f,c); + int i; + if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) + prep_huffman(f); + // fast huffman table lookup + i = f->acc & FAST_HUFFMAN_TABLE_MASK; + i = c->fast_huffman[i]; + if (i >= 0) { + f->acc >>= c->codeword_lengths[i]; + f->valid_bits -= c->codeword_lengths[i]; + if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } + return i; + } + return codebook_decode_scalar_raw(f, c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); @@ -1697,9 +1706,9 @@ static int codebook_decode_scalar(vorb *f, Codebook *c) if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK - #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) +#define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else - #define DECODE_VQ(var,f,c) DECODE(var,f,c) +#define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif @@ -1715,241 +1724,244 @@ static int codebook_decode_scalar(vorb *f, Codebook *c) static int codebook_decode_start(vorb *f, Codebook *c) { - int z = -1; - - // type 0 is only legal in a scalar context - if (c->lookup_type == 0) - error(f, VORBIS_invalid_stream); - else { - DECODE_VQ(z,f,c); - if (c->sparse) assert(z < c->sorted_entries); - if (z < 0) { // check for EOP - if (!f->bytes_in_seg) - if (f->last_seg) - return z; - error(f, VORBIS_invalid_stream); - } - } - return z; + int z = -1; + + // type 0 is only legal in a scalar context + if (c->lookup_type == 0) + error(f, VORBIS_invalid_stream); + else { + DECODE_VQ(z, f, c); + if (c->sparse) assert(z < c->sorted_entries); + if (z < 0) { // check for EOP + if (!f->bytes_in_seg) + if (f->last_seg) + return z; + error(f, VORBIS_invalid_stream); + } + } + return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { - int i,z = codebook_decode_start(f,c); - if (z < 0) return FALSE; - if (len > c->dimensions) len = c->dimensions; + int i, z = codebook_decode_start(f, c); + if (z < 0) return FALSE; + if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK - if (c->lookup_type == 1) { - float last = CODEBOOK_ELEMENT_BASE(c); - int div = 1; - for (i=0; i < len; ++i) { - int off = (z / div) % c->lookup_values; - float val = CODEBOOK_ELEMENT_FAST(c,off) + last; - output[i] += val; - if (c->sequence_p) last = val + c->minimum_value; - div *= c->lookup_values; - } - return TRUE; - } + if (c->lookup_type == 1) { + float last = CODEBOOK_ELEMENT_BASE(c); + int div = 1; + for (i = 0; i < len; ++i) { + int off = (z / div) % c->lookup_values; + float val = CODEBOOK_ELEMENT_FAST(c, off) + last; + output[i] += val; + if (c->sequence_p) last = val + c->minimum_value; + div *= c->lookup_values; + } + return TRUE; + } #endif - z *= c->dimensions; - if (c->sequence_p) { - float last = CODEBOOK_ELEMENT_BASE(c); - for (i=0; i < len; ++i) { - float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; - output[i] += val; - last = val + c->minimum_value; - } - } else { - float last = CODEBOOK_ELEMENT_BASE(c); - for (i=0; i < len; ++i) { - output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; - } - } - - return TRUE; + z *= c->dimensions; + if (c->sequence_p) { + float last = CODEBOOK_ELEMENT_BASE(c); + for (i = 0; i < len; ++i) { + float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; + output[i] += val; + last = val + c->minimum_value; + } + } + else { + float last = CODEBOOK_ELEMENT_BASE(c); + for (i = 0; i < len; ++i) { + output[i] += CODEBOOK_ELEMENT_FAST(c, z + i) + last; + } + } + + return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { - int i,z = codebook_decode_start(f,c); - float last = CODEBOOK_ELEMENT_BASE(c); - if (z < 0) return FALSE; - if (len > c->dimensions) len = c->dimensions; + int i, z = codebook_decode_start(f, c); + float last = CODEBOOK_ELEMENT_BASE(c); + if (z < 0) return FALSE; + if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK - if (c->lookup_type == 1) { - int div = 1; - for (i=0; i < len; ++i) { - int off = (z / div) % c->lookup_values; - float val = CODEBOOK_ELEMENT_FAST(c,off) + last; - output[i*step] += val; - if (c->sequence_p) last = val; - div *= c->lookup_values; - } - return TRUE; - } + if (c->lookup_type == 1) { + int div = 1; + for (i = 0; i < len; ++i) { + int off = (z / div) % c->lookup_values; + float val = CODEBOOK_ELEMENT_FAST(c, off) + last; + output[i*step] += val; + if (c->sequence_p) last = val; + div *= c->lookup_values; + } + return TRUE; + } #endif - z *= c->dimensions; - for (i=0; i < len; ++i) { - float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; - output[i*step] += val; - if (c->sequence_p) last = val; - } + z *= c->dimensions; + for (i = 0; i < len; ++i) { + float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; + output[i*step] += val; + if (c->sequence_p) last = val; + } - return TRUE; + return TRUE; } 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) { - int c_inter = *c_inter_p; - int p_inter = *p_inter_p; - int i,z, effective = c->dimensions; - - // type 0 is only legal in a scalar context - if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); - - while (total_decode > 0) { - float last = CODEBOOK_ELEMENT_BASE(c); - DECODE_VQ(z,f,c); - #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK - assert(!c->sparse || z < c->sorted_entries); - #endif - if (z < 0) { - if (!f->bytes_in_seg) - if (f->last_seg) return FALSE; - return error(f, VORBIS_invalid_stream); - } - - // if this will take us off the end of the buffers, stop short! - // we check by computing the length of the virtual interleaved - // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), - // and the length we'll be using (effective) - if (c_inter + p_inter*ch + effective > len * ch) { - effective = len*ch - (p_inter*ch - c_inter); - } - - #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK - if (c->lookup_type == 1) { - int div = 1; - for (i=0; i < effective; ++i) { - int off = (z / div) % c->lookup_values; - float val = CODEBOOK_ELEMENT_FAST(c,off) + last; - if (outputs[c_inter]) - outputs[c_inter][p_inter] += val; - if (++c_inter == ch) { c_inter = 0; ++p_inter; } - if (c->sequence_p) last = val; - div *= c->lookup_values; - } - } else - #endif - { - z *= c->dimensions; - if (c->sequence_p) { - for (i=0; i < effective; ++i) { - float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; - if (outputs[c_inter]) - outputs[c_inter][p_inter] += val; - if (++c_inter == ch) { c_inter = 0; ++p_inter; } - last = val; + int c_inter = *c_inter_p; + int p_inter = *p_inter_p; + int i, z, effective = c->dimensions; + + // type 0 is only legal in a scalar context + if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); + + while (total_decode > 0) { + float last = CODEBOOK_ELEMENT_BASE(c); + DECODE_VQ(z, f, c); +#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK + assert(!c->sparse || z < c->sorted_entries); +#endif + if (z < 0) { + if (!f->bytes_in_seg) + if (f->last_seg) return FALSE; + return error(f, VORBIS_invalid_stream); + } + + // if this will take us off the end of the buffers, stop short! + // we check by computing the length of the virtual interleaved + // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), + // and the length we'll be using (effective) + if (c_inter + p_inter*ch + effective > len * ch) { + effective = len*ch - (p_inter*ch - c_inter); + } + +#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK + if (c->lookup_type == 1) { + int div = 1; + for (i = 0; i < effective; ++i) { + int off = (z / div) % c->lookup_values; + float val = CODEBOOK_ELEMENT_FAST(c, off) + last; + if (outputs[c_inter]) + outputs[c_inter][p_inter] += val; + if (++c_inter == ch) { c_inter = 0; ++p_inter; } + if (c->sequence_p) last = val; + div *= c->lookup_values; + } + } + else +#endif + { + z *= c->dimensions; + if (c->sequence_p) { + for (i = 0; i < effective; ++i) { + float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; + if (outputs[c_inter]) + outputs[c_inter][p_inter] += val; + if (++c_inter == ch) { c_inter = 0; ++p_inter; } + last = val; + } } - } else { - for (i=0; i < effective; ++i) { - float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; - if (outputs[c_inter]) - outputs[c_inter][p_inter] += val; - if (++c_inter == ch) { c_inter = 0; ++p_inter; } + else { + for (i = 0; i < effective; ++i) { + float val = CODEBOOK_ELEMENT_FAST(c, z + i) + last; + if (outputs[c_inter]) + outputs[c_inter][p_inter] += val; + if (++c_inter == ch) { c_inter = 0; ++p_inter; } + } } - } - } + } - total_decode -= effective; - } - *c_inter_p = c_inter; - *p_inter_p = p_inter; - return TRUE; + total_decode -= effective; + } + *c_inter_p = c_inter; + *p_inter_p = p_inter; + return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { - int dy = y1 - y0; - int adx = x1 - x0; - // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? - int err = abs(dy) * (x - x0); - int off = err / adx; - return dy < 0 ? y0 - off : y0 + off; + int dy = y1 - y0; + int adx = x1 - x0; + // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? + int err = abs(dy) * (x - x0); + int off = err / adx; + return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { - 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, - 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, - 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, - 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, - 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, - 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, - 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, - 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, - 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, - 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, - 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, - 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, - 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, - 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, - 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, - 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, - 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, - 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, - 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, - 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, - 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, - 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, - 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, - 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, - 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, - 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, - 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, - 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, - 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, - 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, - 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, - 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, - 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, - 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, - 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, - 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, - 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, - 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, - 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, - 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, - 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, - 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, - 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, - 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, - 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, - 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, - 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, - 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, - 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, - 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, - 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, - 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, - 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, - 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, - 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, - 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, - 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, - 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, - 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, - 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, - 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, - 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, - 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, - 0.82788260f, 0.88168307f, 0.9389798f, 1.0f + 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, + 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, + 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, + 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, + 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, + 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, + 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, + 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, + 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, + 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, + 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, + 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, + 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, + 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, + 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, + 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, + 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, + 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, + 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, + 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, + 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, + 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, + 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, + 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, + 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, + 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, + 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, + 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, + 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, + 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, + 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, + 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, + 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, + 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, + 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, + 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, + 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, + 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, + 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, + 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, + 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, + 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, + 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, + 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, + 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, + 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, + 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, + 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, + 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, + 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, + 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, + 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, + 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, + 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, + 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, + 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, + 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, + 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, + 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, + 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, + 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, + 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, + 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, + 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; @@ -1974,289 +1986,303 @@ int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { - int dy = y1 - y0; - int adx = x1 - x0; - int ady = abs(dy); - int base; - int x=x0,y=y0; - int err = 0; - int sy; + int dy = y1 - y0; + int adx = x1 - x0; + int ady = abs(dy); + int base; + int x = x0, y = y0; + int err = 0; + int sy; #ifdef STB_VORBIS_DIVIDE_TABLE - if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { - if (dy < 0) { - base = -integer_divide_table[ady][adx]; - sy = base-1; - } else { - base = integer_divide_table[ady][adx]; - sy = base+1; - } - } else { - base = dy / adx; - if (dy < 0) - sy = base - 1; - else - sy = base+1; - } + if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { + if (dy < 0) { + base = -integer_divide_table[ady][adx]; + sy = base - 1; + } + else { + base = integer_divide_table[ady][adx]; + sy = base + 1; + } + } + else { + base = dy / adx; + if (dy < 0) + sy = base - 1; + else + sy = base + 1; + } #else - base = dy / adx; - if (dy < 0) - sy = base - 1; - else - sy = base+1; + base = dy / adx; + if (dy < 0) + sy = base - 1; + else + sy = base + 1; #endif - ady -= abs(base) * adx; - if (x1 > n) x1 = n; - if (x < x1) { - LINE_OP(output[x], inverse_db_table[y]); - for (++x; x < x1; ++x) { - err += ady; - if (err >= adx) { - err -= adx; - y += sy; - } else - y += base; - LINE_OP(output[x], inverse_db_table[y]); - } - } + ady -= abs(base) * adx; + if (x1 > n) x1 = n; + if (x < x1) { + LINE_OP(output[x], inverse_db_table[y]); + for (++x; x < x1; ++x) { + err += ady; + if (err >= adx) { + err -= adx; + y += sy; + } + else + y += base; + LINE_OP(output[x], inverse_db_table[y]); + } + } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { - int k; - if (rtype == 0) { - int step = n / book->dimensions; - for (k=0; k < step; ++k) - if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) - return FALSE; - } else { - for (k=0; k < n; ) { - if (!codebook_decode(f, book, target+offset, n-k)) - return FALSE; - k += book->dimensions; - offset += book->dimensions; - } - } - return TRUE; + int k; + if (rtype == 0) { + int step = n / book->dimensions; + for (k = 0; k < step; ++k) + if (!codebook_decode_step(f, book, target + offset + k, n - offset - k, step)) + return FALSE; + } + else { + for (k = 0; k < n; ) { + if (!codebook_decode(f, book, target + offset, n - k)) + return FALSE; + k += book->dimensions; + offset += book->dimensions; + } + } + return TRUE; } +// n is 1/2 of the blocksize -- +// specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { - int i,j,pass; - Residue *r = f->residue_config + rn; - int rtype = f->residue_types[rn]; - int c = r->classbook; - int classwords = f->codebooks[c].dimensions; - int n_read = r->end - r->begin; - int part_read = n_read / r->part_size; - int temp_alloc_point = temp_alloc_save(f); - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); - #else - int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); - #endif - - CHECK(f); - - for (i=0; i < ch; ++i) - if (!do_not_decode[i]) - memset(residue_buffers[i], 0, sizeof(float) * n); - - if (rtype == 2 && ch != 1) { - for (j=0; j < ch; ++j) - if (!do_not_decode[j]) - break; - if (j == ch) - goto done; - - for (pass=0; pass < 8; ++pass) { - int pcount = 0, class_set = 0; - if (ch == 2) { - while (pcount < part_read) { - int z = r->begin + pcount*r->part_size; - int c_inter = (z & 1), p_inter = z>>1; - if (pass == 0) { - Codebook *c = f->codebooks+r->classbook; - int q; - DECODE(q,f,c); - if (q == EOP) goto done; - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - part_classdata[0][class_set] = r->classdata[q]; - #else - for (i=classwords-1; i >= 0; --i) { - classifications[0][i+pcount] = q % r->classifications; - q /= r->classifications; - } - #endif - } - for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { - int z = r->begin + pcount*r->part_size; - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - int c = part_classdata[0][class_set][i]; - #else - int c = classifications[0][pcount]; - #endif - int b = r->residue_books[c][pass]; - if (b >= 0) { - Codebook *book = f->codebooks + b; - #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK - if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) - goto done; - #else - // saves 1% - if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) - goto done; - #endif - } else { - z += r->part_size; - c_inter = z & 1; - p_inter = z >> 1; - } - } - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - ++class_set; - #endif + int i, j, pass; + Residue *r = f->residue_config + rn; + int rtype = f->residue_types[rn]; + int c = r->classbook; + int classwords = f->codebooks[c].dimensions; + unsigned int actual_size = rtype == 2 ? n * 2 : n; + unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); + unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); + int n_read = limit_r_end - limit_r_begin; + int part_read = n_read / r->part_size; + int temp_alloc_point = temp_alloc_save(f); +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + uint8 ***part_classdata = (uint8 ***)temp_block_array(f, f->channels, part_read * sizeof(**part_classdata)); +#else + int **classifications = (int **)temp_block_array(f, f->channels, part_read * sizeof(**classifications)); +#endif + + CHECK(f); + + for (i = 0; i < ch; ++i) + if (!do_not_decode[i]) + memset(residue_buffers[i], 0, sizeof(float) * n); + + if (rtype == 2 && ch != 1) { + for (j = 0; j < ch; ++j) + if (!do_not_decode[j]) + break; + if (j == ch) + goto done; + + for (pass = 0; pass < 8; ++pass) { + int pcount = 0, class_set = 0; + if (ch == 2) { + while (pcount < part_read) { + int z = r->begin + pcount*r->part_size; + int c_inter = (z & 1), p_inter = z >> 1; + if (pass == 0) { + Codebook *c = f->codebooks + r->classbook; + int q; + DECODE(q, f, c); + if (q == EOP) goto done; +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + part_classdata[0][class_set] = r->classdata[q]; +#else + for (i = classwords - 1; i >= 0; --i) { + classifications[0][i + pcount] = q % r->classifications; + q /= r->classifications; + } +#endif + } + for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) { + int z = r->begin + pcount*r->part_size; +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + int c = part_classdata[0][class_set][i]; +#else + int c = classifications[0][pcount]; +#endif + int b = r->residue_books[c][pass]; + if (b >= 0) { + Codebook *book = f->codebooks + b; +#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK + if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) + goto done; +#else + // saves 1% + if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) + goto done; +#endif + } + else { + z += r->part_size; + c_inter = z & 1; + p_inter = z >> 1; + } + } +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + ++class_set; +#endif + } } - } else if (ch == 1) { - while (pcount < part_read) { - int z = r->begin + pcount*r->part_size; - int c_inter = 0, p_inter = z; - if (pass == 0) { - Codebook *c = f->codebooks+r->classbook; - int q; - DECODE(q,f,c); - if (q == EOP) goto done; - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - part_classdata[0][class_set] = r->classdata[q]; - #else - for (i=classwords-1; i >= 0; --i) { - classifications[0][i+pcount] = q % r->classifications; - q /= r->classifications; - } - #endif - } - for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { - int z = r->begin + pcount*r->part_size; - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - int c = part_classdata[0][class_set][i]; - #else - int c = classifications[0][pcount]; - #endif - int b = r->residue_books[c][pass]; - if (b >= 0) { - Codebook *book = f->codebooks + b; - if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) - goto done; - } else { - z += r->part_size; - c_inter = 0; - p_inter = z; - } - } - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - ++class_set; - #endif + else if (ch == 1) { + while (pcount < part_read) { + int z = r->begin + pcount*r->part_size; + int c_inter = 0, p_inter = z; + if (pass == 0) { + Codebook *c = f->codebooks + r->classbook; + int q; + DECODE(q, f, c); + if (q == EOP) goto done; +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + part_classdata[0][class_set] = r->classdata[q]; +#else + for (i = classwords - 1; i >= 0; --i) { + classifications[0][i + pcount] = q % r->classifications; + q /= r->classifications; + } +#endif + } + for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) { + int z = r->begin + pcount*r->part_size; +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + int c = part_classdata[0][class_set][i]; +#else + int c = classifications[0][pcount]; +#endif + int b = r->residue_books[c][pass]; + if (b >= 0) { + Codebook *book = f->codebooks + b; + if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) + goto done; + } + else { + z += r->part_size; + c_inter = 0; + p_inter = z; + } + } +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + ++class_set; +#endif + } } - } else { - while (pcount < part_read) { - int z = r->begin + pcount*r->part_size; - int c_inter = z % ch, p_inter = z/ch; - if (pass == 0) { - Codebook *c = f->codebooks+r->classbook; - int q; - DECODE(q,f,c); - if (q == EOP) goto done; - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - part_classdata[0][class_set] = r->classdata[q]; - #else - for (i=classwords-1; i >= 0; --i) { - classifications[0][i+pcount] = q % r->classifications; - q /= r->classifications; - } - #endif - } - for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { - int z = r->begin + pcount*r->part_size; - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - int c = part_classdata[0][class_set][i]; - #else - int c = classifications[0][pcount]; - #endif - int b = r->residue_books[c][pass]; - if (b >= 0) { - Codebook *book = f->codebooks + b; - if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) - goto done; - } else { - z += r->part_size; - c_inter = z % ch; - p_inter = z / ch; - } - } - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - ++class_set; - #endif + else { + while (pcount < part_read) { + int z = r->begin + pcount*r->part_size; + int c_inter = z % ch, p_inter = z / ch; + if (pass == 0) { + Codebook *c = f->codebooks + r->classbook; + int q; + DECODE(q, f, c); + if (q == EOP) goto done; +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + part_classdata[0][class_set] = r->classdata[q]; +#else + for (i = classwords - 1; i >= 0; --i) { + classifications[0][i + pcount] = q % r->classifications; + q /= r->classifications; + } +#endif + } + for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) { + int z = r->begin + pcount*r->part_size; +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + int c = part_classdata[0][class_set][i]; +#else + int c = classifications[0][pcount]; +#endif + int b = r->residue_books[c][pass]; + if (b >= 0) { + Codebook *book = f->codebooks + b; + if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) + goto done; + } + else { + z += r->part_size; + c_inter = z % ch; + p_inter = z / ch; + } + } +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + ++class_set; +#endif + } } - } - } - goto done; - } - CHECK(f); - - for (pass=0; pass < 8; ++pass) { - int pcount = 0, class_set=0; - while (pcount < part_read) { - if (pass == 0) { - for (j=0; j < ch; ++j) { - if (!do_not_decode[j]) { - Codebook *c = f->codebooks+r->classbook; - int temp; - DECODE(temp,f,c); - if (temp == EOP) goto done; - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - part_classdata[j][class_set] = r->classdata[temp]; - #else - for (i=classwords-1; i >= 0; --i) { - classifications[j][i+pcount] = temp % r->classifications; - temp /= r->classifications; - } - #endif - } + } + goto done; + } + CHECK(f); + + for (pass = 0; pass < 8; ++pass) { + int pcount = 0, class_set = 0; + while (pcount < part_read) { + if (pass == 0) { + for (j = 0; j < ch; ++j) { + if (!do_not_decode[j]) { + Codebook *c = f->codebooks + r->classbook; + int temp; + DECODE(temp, f, c); + if (temp == EOP) goto done; +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + part_classdata[j][class_set] = r->classdata[temp]; +#else + for (i = classwords - 1; i >= 0; --i) { + classifications[j][i + pcount] = temp % r->classifications; + temp /= r->classifications; + } +#endif + } + } } - } - for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { - for (j=0; j < ch; ++j) { - if (!do_not_decode[j]) { - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - int c = part_classdata[j][class_set][i]; - #else - int c = classifications[j][pcount]; - #endif - int b = r->residue_books[c][pass]; - if (b >= 0) { - float *target = residue_buffers[j]; - int offset = r->begin + pcount * r->part_size; - int n = r->part_size; - Codebook *book = f->codebooks + b; - if (!residue_decode(f, book, target, offset, n, rtype)) - goto done; - } - } + for (i = 0; i < classwords && pcount < part_read; ++i, ++pcount) { + for (j = 0; j < ch; ++j) { + if (!do_not_decode[j]) { +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + int c = part_classdata[j][class_set][i]; +#else + int c = classifications[j][pcount]; +#endif + int b = r->residue_books[c][pass]; + if (b >= 0) { + float *target = residue_buffers[j]; + int offset = r->begin + pcount * r->part_size; + int n = r->part_size; + Codebook *book = f->codebooks + b; + if (!residue_decode(f, book, target, offset, n, rtype)) + goto done; + } + } + } } - } - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - ++class_set; - #endif - } - } - done: - CHECK(f); - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - temp_free(f,part_classdata); - #else - temp_free(f,classifications); - #endif - temp_alloc_restore(f,temp_alloc_point); +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + ++class_set; +#endif + } + } +done: + CHECK(f); +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + temp_free(f, part_classdata); +#else + temp_free(f, classifications); +#endif + temp_alloc_restore(f, temp_alloc_point); } @@ -2264,76 +2290,76 @@ static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { - int i,j; - int n2 = n >> 1; - float *x = (float *) malloc(sizeof(*x) * n2); - memcpy(x, buffer, sizeof(*x) * n2); - for (i=0; i < n; ++i) { - float acc = 0; - for (j=0; j < n2; ++j) - // formula from paper: - //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); - // formula from wikipedia - //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); - // these are equivalent, except the formula from the paper inverts the multiplier! - // however, what actually works is NO MULTIPLIER!?! - //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); - acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); - buffer[i] = acc; - } - free(x); + int i, j; + int n2 = n >> 1; + float *x = (float *)malloc(sizeof(*x) * n2); + memcpy(x, buffer, sizeof(*x) * n2); + for (i = 0; i < n; ++i) { + float acc = 0; + for (j = 0; j < n2; ++j) + // formula from paper: + //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); + // formula from wikipedia + //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); + // these are equivalent, except the formula from the paper inverts the multiplier! + // however, what actually works is NO MULTIPLIER!?! + //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); + acc += x[j] * (float)cos(M_PI / 2 / n * (2 * i + 1 + n / 2.0)*(2 * j + 1)); + buffer[i] = acc; + } + free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { - float mcos[16384]; - int i,j; - int n2 = n >> 1, nmask = (n << 2) -1; - float *x = (float *) malloc(sizeof(*x) * n2); - memcpy(x, buffer, sizeof(*x) * n2); - for (i=0; i < 4*n; ++i) - mcos[i] = (float) cos(M_PI / 2 * i / n); - - for (i=0; i < n; ++i) { - float acc = 0; - for (j=0; j < n2; ++j) - acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; - buffer[i] = acc; - } - free(x); + float mcos[16384]; + int i, j; + int n2 = n >> 1, nmask = (n << 2) - 1; + float *x = (float *)malloc(sizeof(*x) * n2); + memcpy(x, buffer, sizeof(*x) * n2); + for (i = 0; i < 4 * n; ++i) + mcos[i] = (float)cos(M_PI / 2 * i / n); + + for (i = 0; i < n; ++i) { + float acc = 0; + for (j = 0; j < n2; ++j) + acc += x[j] * mcos[(2 * i + 1 + n2)*(2 * j + 1) & nmask]; + buffer[i] = acc; + } + free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { - float mcos[16384]; - float x[2048]; - int i,j; - int n2 = n >> 1, nmask = (n << 3) - 1; - memcpy(x, buffer, sizeof(*x) * n); - for (i=0; i < 8*n; ++i) - mcos[i] = (float) cos(M_PI / 4 * i / n); - for (i=0; i < n; ++i) { - float acc = 0; - for (j=0; j < n; ++j) - acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; - buffer[i] = acc; - } + float mcos[16384]; + float x[2048]; + int i, j; + int n2 = n >> 1, nmask = (n << 3) - 1; + memcpy(x, buffer, sizeof(*x) * n); + for (i = 0; i < 8 * n; ++i) + mcos[i] = (float)cos(M_PI / 4 * i / n); + for (i = 0; i < n; ++i) { + float acc = 0; + for (j = 0; j < n; ++j) + acc += x[j] * mcos[((2 * i + 1)*(2 * j + 1)) & nmask]; + buffer[i] = acc; + } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { - int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; - float temp[4096]; + int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; + float temp[4096]; - memcpy(temp, buffer, n2 * sizeof(float)); - dct_iv_slow(temp, n2); // returns -c'-d, a-b' + memcpy(temp, buffer, n2 * sizeof(float)); + dct_iv_slow(temp, n2); // returns -c'-d, a-b' - for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' - for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' - for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d + for (i = 0; i < n4; ++i) buffer[i] = temp[i + n4]; // a-b' + for (; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' + for (; i < n; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif @@ -2344,36 +2370,36 @@ void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison -typedef struct +typedef struct { - int n; - int log2n; - - float *trig; - int *bitrev; + int n; + int log2n; + + float *trig; + int *bitrev; - float scale; + float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); -mdct_lookup M1,M2; +mdct_lookup M1, M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { - mdct_lookup *M; - if (M1.n == n) M = &M1; - else if (M2.n == n) M = &M2; - else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } - else { - if (M2.n) __asm int 3; - mdct_init(&M2, n); - M = &M2; - } - - mdct_backward(M, buffer, buffer); + mdct_lookup *M; + if (M1.n == n) M = &M1; + else if (M2.n == n) M = &M2; + else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } + else { + if (M2.n) __asm int 3; + mdct_init(&M2, n); + M = &M2; + } + + mdct_backward(M, buffer, buffer); } #endif @@ -2383,663 +2409,664 @@ void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { - float *ee0 = e + i_off; - float *ee2 = ee0 + k_off; - int i; - - assert((n & 3) == 0); - for (i=(n>>2); i > 0; --i) { - float k00_20, k01_21; - k00_20 = ee0[ 0] - ee2[ 0]; - k01_21 = ee0[-1] - ee2[-1]; - ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; - ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; - ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; - ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; - A += 8; - - k00_20 = ee0[-2] - ee2[-2]; - k01_21 = ee0[-3] - ee2[-3]; - ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; - ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; - ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; - ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; - A += 8; - - k00_20 = ee0[-4] - ee2[-4]; - k01_21 = ee0[-5] - ee2[-5]; - ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; - ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; - ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; - ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; - A += 8; - - k00_20 = ee0[-6] - ee2[-6]; - k01_21 = ee0[-7] - ee2[-7]; - ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; - ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; - ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; - ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; - A += 8; - ee0 -= 8; - ee2 -= 8; - } + float *ee0 = e + i_off; + float *ee2 = ee0 + k_off; + int i; + + assert((n & 3) == 0); + for (i = (n >> 2); i > 0; --i) { + float k00_20, k01_21; + k00_20 = ee0[0] - ee2[0]; + k01_21 = ee0[-1] - ee2[-1]; + ee0[0] += ee2[0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; + ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; + ee2[0] = k00_20 * A[0] - k01_21 * A[1]; + ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; + A += 8; + + k00_20 = ee0[-2] - ee2[-2]; + k01_21 = ee0[-3] - ee2[-3]; + ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; + ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; + ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; + ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; + A += 8; + + k00_20 = ee0[-4] - ee2[-4]; + k01_21 = ee0[-5] - ee2[-5]; + ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; + ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; + ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; + ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; + A += 8; + + k00_20 = ee0[-6] - ee2[-6]; + k01_21 = ee0[-7] - ee2[-7]; + ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; + ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; + ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; + ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; + A += 8; + ee0 -= 8; + ee2 -= 8; + } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { - int i; - float k00_20, k01_21; + int i; + float k00_20, k01_21; - float *e0 = e + d0; - float *e2 = e0 + k_off; + float *e0 = e + d0; + float *e2 = e0 + k_off; - for (i=lim >> 2; i > 0; --i) { - k00_20 = e0[-0] - e2[-0]; - k01_21 = e0[-1] - e2[-1]; - e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; - e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; - e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; - e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; + for (i = lim >> 2; i > 0; --i) { + k00_20 = e0[-0] - e2[-0]; + k01_21 = e0[-1] - e2[-1]; + e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; + e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; + e2[-0] = (k00_20)*A[0] - (k01_21)* A[1]; + e2[-1] = (k01_21)*A[0] + (k00_20)* A[1]; - A += k1; + A += k1; - k00_20 = e0[-2] - e2[-2]; - k01_21 = e0[-3] - e2[-3]; - e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; - e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; - e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; - e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; + k00_20 = e0[-2] - e2[-2]; + k01_21 = e0[-3] - e2[-3]; + e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; + e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; + e2[-2] = (k00_20)*A[0] - (k01_21)* A[1]; + e2[-3] = (k01_21)*A[0] + (k00_20)* A[1]; - A += k1; + A += k1; - k00_20 = e0[-4] - e2[-4]; - k01_21 = e0[-5] - e2[-5]; - e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; - e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; - e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; - e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; + k00_20 = e0[-4] - e2[-4]; + k01_21 = e0[-5] - e2[-5]; + e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; + e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; + e2[-4] = (k00_20)*A[0] - (k01_21)* A[1]; + e2[-5] = (k01_21)*A[0] + (k00_20)* A[1]; - A += k1; + A += k1; - k00_20 = e0[-6] - e2[-6]; - k01_21 = e0[-7] - e2[-7]; - e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; - e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; - e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; - e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; + k00_20 = e0[-6] - e2[-6]; + k01_21 = e0[-7] - e2[-7]; + e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; + e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; + e2[-6] = (k00_20)*A[0] - (k01_21)* A[1]; + e2[-7] = (k01_21)*A[0] + (k00_20)* A[1]; - e0 -= 8; - e2 -= 8; + e0 -= 8; + e2 -= 8; - A += k1; - } + A += k1; + } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { - int i; - float A0 = A[0]; - float A1 = A[0+1]; - float A2 = A[0+a_off]; - float A3 = A[0+a_off+1]; - float A4 = A[0+a_off*2+0]; - float A5 = A[0+a_off*2+1]; - float A6 = A[0+a_off*3+0]; - float A7 = A[0+a_off*3+1]; - - float k00,k11; - - float *ee0 = e +i_off; - float *ee2 = ee0+k_off; - - for (i=n; i > 0; --i) { - k00 = ee0[ 0] - ee2[ 0]; - k11 = ee0[-1] - ee2[-1]; - ee0[ 0] = ee0[ 0] + ee2[ 0]; - ee0[-1] = ee0[-1] + ee2[-1]; - ee2[ 0] = (k00) * A0 - (k11) * A1; - ee2[-1] = (k11) * A0 + (k00) * A1; - - k00 = ee0[-2] - ee2[-2]; - k11 = ee0[-3] - ee2[-3]; - ee0[-2] = ee0[-2] + ee2[-2]; - ee0[-3] = ee0[-3] + ee2[-3]; - ee2[-2] = (k00) * A2 - (k11) * A3; - ee2[-3] = (k11) * A2 + (k00) * A3; - - k00 = ee0[-4] - ee2[-4]; - k11 = ee0[-5] - ee2[-5]; - ee0[-4] = ee0[-4] + ee2[-4]; - ee0[-5] = ee0[-5] + ee2[-5]; - ee2[-4] = (k00) * A4 - (k11) * A5; - ee2[-5] = (k11) * A4 + (k00) * A5; - - k00 = ee0[-6] - ee2[-6]; - k11 = ee0[-7] - ee2[-7]; - ee0[-6] = ee0[-6] + ee2[-6]; - ee0[-7] = ee0[-7] + ee2[-7]; - ee2[-6] = (k00) * A6 - (k11) * A7; - ee2[-7] = (k11) * A6 + (k00) * A7; - - ee0 -= k0; - ee2 -= k0; - } + int i; + float A0 = A[0]; + float A1 = A[0 + 1]; + float A2 = A[0 + a_off]; + float A3 = A[0 + a_off + 1]; + float A4 = A[0 + a_off * 2 + 0]; + float A5 = A[0 + a_off * 2 + 1]; + float A6 = A[0 + a_off * 3 + 0]; + float A7 = A[0 + a_off * 3 + 1]; + + float k00, k11; + + float *ee0 = e + i_off; + float *ee2 = ee0 + k_off; + + for (i = n; i > 0; --i) { + k00 = ee0[0] - ee2[0]; + k11 = ee0[-1] - ee2[-1]; + ee0[0] = ee0[0] + ee2[0]; + ee0[-1] = ee0[-1] + ee2[-1]; + ee2[0] = (k00)* A0 - (k11)* A1; + ee2[-1] = (k11)* A0 + (k00)* A1; + + k00 = ee0[-2] - ee2[-2]; + k11 = ee0[-3] - ee2[-3]; + ee0[-2] = ee0[-2] + ee2[-2]; + ee0[-3] = ee0[-3] + ee2[-3]; + ee2[-2] = (k00)* A2 - (k11)* A3; + ee2[-3] = (k11)* A2 + (k00)* A3; + + k00 = ee0[-4] - ee2[-4]; + k11 = ee0[-5] - ee2[-5]; + ee0[-4] = ee0[-4] + ee2[-4]; + ee0[-5] = ee0[-5] + ee2[-5]; + ee2[-4] = (k00)* A4 - (k11)* A5; + ee2[-5] = (k11)* A4 + (k00)* A5; + + k00 = ee0[-6] - ee2[-6]; + k11 = ee0[-7] - ee2[-7]; + ee0[-6] = ee0[-6] + ee2[-6]; + ee0[-7] = ee0[-7] + ee2[-7]; + ee2[-6] = (k00)* A6 - (k11)* A7; + ee2[-7] = (k11)* A6 + (k00)* A7; + + ee0 -= k0; + ee2 -= k0; + } } static __forceinline void iter_54(float *z) { - float k00,k11,k22,k33; - float y0,y1,y2,y3; + float k00, k11, k22, k33; + float y0, y1, y2, y3; - k00 = z[ 0] - z[-4]; - y0 = z[ 0] + z[-4]; - y2 = z[-2] + z[-6]; - k22 = z[-2] - z[-6]; + k00 = z[0] - z[-4]; + y0 = z[0] + z[-4]; + y2 = z[-2] + z[-6]; + k22 = z[-2] - z[-6]; - z[-0] = y0 + y2; // z0 + z4 + z2 + z6 - z[-2] = y0 - y2; // z0 + z4 - z2 - z6 + z[-0] = y0 + y2; // z0 + z4 + z2 + z6 + z[-2] = y0 - y2; // z0 + z4 - z2 - z6 - // done with y0,y2 + // done with y0,y2 - k33 = z[-3] - z[-7]; + k33 = z[-3] - z[-7]; - z[-4] = k00 + k33; // z0 - z4 + z3 - z7 - z[-6] = k00 - k33; // z0 - z4 - z3 + z7 + z[-4] = k00 + k33; // z0 - z4 + z3 - z7 + z[-6] = k00 - k33; // z0 - z4 - z3 + z7 - // done with k33 + // done with k33 - k11 = z[-1] - z[-5]; - y1 = z[-1] + z[-5]; - y3 = z[-3] + z[-7]; + k11 = z[-1] - z[-5]; + y1 = z[-1] + z[-5]; + y3 = z[-3] + z[-7]; - z[-1] = y1 + y3; // z1 + z5 + z3 + z7 - z[-3] = y1 - y3; // z1 + z5 - z3 - z7 - z[-5] = k11 - k22; // z1 - z5 + z2 - z6 - z[-7] = k11 + k22; // z1 - z5 - z2 + z6 + z[-1] = y1 + y3; // z1 + z5 + z3 + z7 + z[-3] = y1 - y3; // z1 + z5 - z3 - z7 + z[-5] = k11 - k22; // z1 - z5 + z2 - z6 + z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { - int a_off = base_n >> 3; - float A2 = A[0+a_off]; - float *z = e + i_off; - float *base = z - 16 * n; - - while (z > base) { - float k00,k11; - - k00 = z[-0] - z[-8]; - k11 = z[-1] - z[-9]; - z[-0] = z[-0] + z[-8]; - z[-1] = z[-1] + z[-9]; - z[-8] = k00; - z[-9] = k11 ; - - k00 = z[ -2] - z[-10]; - k11 = z[ -3] - z[-11]; - z[ -2] = z[ -2] + z[-10]; - z[ -3] = z[ -3] + z[-11]; - z[-10] = (k00+k11) * A2; - z[-11] = (k11-k00) * A2; - - k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation - k11 = z[ -5] - z[-13]; - z[ -4] = z[ -4] + z[-12]; - z[ -5] = z[ -5] + z[-13]; - z[-12] = k11; - z[-13] = k00; - - k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation - k11 = z[ -7] - z[-15]; - z[ -6] = z[ -6] + z[-14]; - z[ -7] = z[ -7] + z[-15]; - z[-14] = (k00+k11) * A2; - z[-15] = (k00-k11) * A2; - - iter_54(z); - iter_54(z-8); - z -= 16; - } + int a_off = base_n >> 3; + float A2 = A[0 + a_off]; + float *z = e + i_off; + float *base = z - 16 * n; + + while (z > base) { + float k00, k11; + + k00 = z[-0] - z[-8]; + k11 = z[-1] - z[-9]; + z[-0] = z[-0] + z[-8]; + z[-1] = z[-1] + z[-9]; + z[-8] = k00; + z[-9] = k11; + + k00 = z[-2] - z[-10]; + k11 = z[-3] - z[-11]; + z[-2] = z[-2] + z[-10]; + z[-3] = z[-3] + z[-11]; + z[-10] = (k00 + k11) * A2; + z[-11] = (k11 - k00) * A2; + + k00 = z[-12] - z[-4]; // reverse to avoid a unary negation + k11 = z[-5] - z[-13]; + z[-4] = z[-4] + z[-12]; + z[-5] = z[-5] + z[-13]; + z[-12] = k11; + z[-13] = k00; + + k00 = z[-14] - z[-6]; // reverse to avoid a unary negation + k11 = z[-7] - z[-15]; + z[-6] = z[-6] + z[-14]; + z[-7] = z[-7] + z[-15]; + z[-14] = (k00 + k11) * A2; + z[-15] = (k00 - k11) * A2; + + iter_54(z); + iter_54(z - 8); + z -= 16; + } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { - int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; - int ld; - // @OPTIMIZE: reduce register pressure by using fewer variables? - int save_point = temp_alloc_save(f); - float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); - float *u=NULL,*v=NULL; - // twiddle factors - float *A = f->A[blocktype]; - - // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" - // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. - - // kernel from paper - - - // merged: - // copy and reflect spectral data - // step 0 - - // note that it turns out that the items added together during - // this step are, in fact, being added to themselves (as reflected - // by step 0). inexplicable inefficiency! this became obvious - // once I combined the passes. - - // so there's a missing 'times 2' here (for adding X to itself). - // this propogates through linearly to the end, where the numbers - // are 1/2 too small, and need to be compensated for. - - { - float *d,*e, *AA, *e_stop; - d = &buf2[n2-2]; - AA = A; - e = &buffer[0]; - e_stop = &buffer[n2]; - while (e != e_stop) { - d[1] = (e[0] * AA[0] - e[2]*AA[1]); - d[0] = (e[0] * AA[1] + e[2]*AA[0]); - d -= 2; - AA += 2; - e += 4; - } - - e = &buffer[n2-3]; - while (d >= buf2) { - d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); - d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); - d -= 2; - AA += 2; - e -= 4; - } - } - - // now we use symbolic names for these, so that we can - // possibly swap their meaning as we change which operations - // are in place - - u = buffer; - v = buf2; - - // step 2 (paper output is w, now u) - // this could be in place, but the data ends up in the wrong - // place... _somebody_'s got to swap it, so this is nominated - { - float *AA = &A[n2-8]; - float *d0,*d1, *e0, *e1; - - e0 = &v[n4]; - e1 = &v[0]; - - d0 = &u[n4]; - d1 = &u[0]; - - while (AA >= A) { - float v40_20, v41_21; - - v41_21 = e0[1] - e1[1]; - v40_20 = e0[0] - e1[0]; - d0[1] = e0[1] + e1[1]; - d0[0] = e0[0] + e1[0]; - d1[1] = v41_21*AA[4] - v40_20*AA[5]; - d1[0] = v40_20*AA[4] + v41_21*AA[5]; - - v41_21 = e0[3] - e1[3]; - v40_20 = e0[2] - e1[2]; - d0[3] = e0[3] + e1[3]; - d0[2] = e0[2] + e1[2]; - d1[3] = v41_21*AA[0] - v40_20*AA[1]; - d1[2] = v40_20*AA[0] + v41_21*AA[1]; - - AA -= 8; - - d0 += 4; - d1 += 4; - e0 += 4; - e1 += 4; - } - } - - // step 3 - ld = ilog(n) - 1; // ilog is off-by-one from normal definitions - - // optimized step 3: - - // the original step3 loop can be nested r inside s or s inside r; - // it's written originally as s inside r, but this is dumb when r - // iterates many times, and s few. So I have two copies of it and - // switch between them halfway. - - // this is iteration 0 of step 3 - imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); - imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); - - // this is iteration 1 of step 3 - imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); - imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); - imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); - imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); - - l=2; - for (; l < (ld-3)>>1; ++l) { - int k0 = n >> (l+2), k0_2 = k0>>1; - int lim = 1 << (l+1); - int i; - for (i=0; i < lim; ++i) - imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); - } - - for (; l < ld-6; ++l) { - int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; - int rlim = n >> (l+6), r; - int lim = 1 << (l+1); - int i_off; - float *A0 = A; - i_off = n2-1; - for (r=rlim; r > 0; --r) { - imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); - A0 += k1*4; - i_off -= 8; - } - } - - // iterations with count: - // ld-6,-5,-4 all interleaved together - // the big win comes from getting rid of needless flops - // due to the constants on pass 5 & 4 being all 1 and 0; - // combining them to be simultaneous to improve cache made little difference - imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); - - // output is u - - // step 4, 5, and 6 - // cannot be in-place because of step 5 - { - uint16 *bitrev = f->bit_reverse[blocktype]; - // weirdly, I'd have thought reading sequentially and writing - // erratically would have been better than vice-versa, but in - // fact that's not what my testing showed. (That is, with - // j = bitreverse(i), do you read i and write j, or read j and write i.) - - float *d0 = &v[n4-4]; - float *d1 = &v[n2-4]; - while (d0 >= v) { - int k4; - - k4 = bitrev[0]; - d1[3] = u[k4+0]; - d1[2] = u[k4+1]; - d0[3] = u[k4+2]; - d0[2] = u[k4+3]; - - k4 = bitrev[1]; - d1[1] = u[k4+0]; - d1[0] = u[k4+1]; - d0[1] = u[k4+2]; - d0[0] = u[k4+3]; - - d0 -= 4; - d1 -= 4; - bitrev += 2; - } - } - // (paper output is u, now v) - - - // data must be in buf2 - assert(v == buf2); - - // step 7 (paper output is v, now v) - // this is now in place - { - float *C = f->C[blocktype]; - float *d, *e; - - d = v; - e = v + n2 - 4; - - while (d < e) { - float a02,a11,b0,b1,b2,b3; - - a02 = d[0] - e[2]; - a11 = d[1] + e[3]; - - b0 = C[1]*a02 + C[0]*a11; - b1 = C[1]*a11 - C[0]*a02; - - b2 = d[0] + e[ 2]; - b3 = d[1] - e[ 3]; - - d[0] = b2 + b0; - d[1] = b3 + b1; - e[2] = b2 - b0; - e[3] = b1 - b3; - - a02 = d[2] - e[0]; - a11 = d[3] + e[1]; - - b0 = C[3]*a02 + C[2]*a11; - b1 = C[3]*a11 - C[2]*a02; - - b2 = d[2] + e[ 0]; - b3 = d[3] - e[ 1]; - - d[2] = b2 + b0; - d[3] = b3 + b1; - e[0] = b2 - b0; - e[1] = b1 - b3; - - C += 4; - d += 4; - e -= 4; - } - } - - // data must be in buf2 - + int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; + int ld; + // @OPTIMIZE: reduce register pressure by using fewer variables? + int save_point = temp_alloc_save(f); + float *buf2 = (float *)temp_alloc(f, n2 * sizeof(*buf2)); + float *u = NULL, *v = NULL; + // twiddle factors + float *A = f->A[blocktype]; + + // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" + // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. + + // kernel from paper + + + // merged: + // copy and reflect spectral data + // step 0 + + // note that it turns out that the items added together during + // this step are, in fact, being added to themselves (as reflected + // by step 0). inexplicable inefficiency! this became obvious + // once I combined the passes. + + // so there's a missing 'times 2' here (for adding X to itself). + // this propogates through linearly to the end, where the numbers + // are 1/2 too small, and need to be compensated for. + + { + float *d, *e, *AA, *e_stop; + d = &buf2[n2 - 2]; + AA = A; + e = &buffer[0]; + e_stop = &buffer[n2]; + while (e != e_stop) { + d[1] = (e[0] * AA[0] - e[2] * AA[1]); + d[0] = (e[0] * AA[1] + e[2] * AA[0]); + d -= 2; + AA += 2; + e += 4; + } + + e = &buffer[n2 - 3]; + while (d >= buf2) { + d[1] = (-e[2] * AA[0] - -e[0] * AA[1]); + d[0] = (-e[2] * AA[1] + -e[0] * AA[0]); + d -= 2; + AA += 2; + e -= 4; + } + } + + // now we use symbolic names for these, so that we can + // possibly swap their meaning as we change which operations + // are in place + + u = buffer; + v = buf2; + + // step 2 (paper output is w, now u) + // this could be in place, but the data ends up in the wrong + // place... _somebody_'s got to swap it, so this is nominated + { + float *AA = &A[n2 - 8]; + float *d0, *d1, *e0, *e1; + + e0 = &v[n4]; + e1 = &v[0]; + + d0 = &u[n4]; + d1 = &u[0]; + + while (AA >= A) { + float v40_20, v41_21; + + v41_21 = e0[1] - e1[1]; + v40_20 = e0[0] - e1[0]; + d0[1] = e0[1] + e1[1]; + d0[0] = e0[0] + e1[0]; + d1[1] = v41_21*AA[4] - v40_20*AA[5]; + d1[0] = v40_20*AA[4] + v41_21*AA[5]; + + v41_21 = e0[3] - e1[3]; + v40_20 = e0[2] - e1[2]; + d0[3] = e0[3] + e1[3]; + d0[2] = e0[2] + e1[2]; + d1[3] = v41_21*AA[0] - v40_20*AA[1]; + d1[2] = v40_20*AA[0] + v41_21*AA[1]; + + AA -= 8; + + d0 += 4; + d1 += 4; + e0 += 4; + e1 += 4; + } + } + + // step 3 + ld = ilog(n) - 1; // ilog is off-by-one from normal definitions + + // optimized step 3: + + // the original step3 loop can be nested r inside s or s inside r; + // it's written originally as s inside r, but this is dumb when r + // iterates many times, and s few. So I have two copies of it and + // switch between them halfway. + + // this is iteration 0 of step 3 + imdct_step3_iter0_loop(n >> 4, u, n2 - 1 - n4 * 0, -(n >> 3), A); + imdct_step3_iter0_loop(n >> 4, u, n2 - 1 - n4 * 1, -(n >> 3), A); + + // this is iteration 1 of step 3 + imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 0, -(n >> 4), A, 16); + imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 1, -(n >> 4), A, 16); + imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 2, -(n >> 4), A, 16); + imdct_step3_inner_r_loop(n >> 5, u, n2 - 1 - n8 * 3, -(n >> 4), A, 16); + + l = 2; + for (; l < (ld - 3) >> 1; ++l) { + int k0 = n >> (l + 2), k0_2 = k0 >> 1; + int lim = 1 << (l + 1); + int i; + for (i = 0; i < lim; ++i) + imdct_step3_inner_r_loop(n >> (l + 4), u, n2 - 1 - k0*i, -k0_2, A, 1 << (l + 3)); + } + + for (; l < ld - 6; ++l) { + int k0 = n >> (l + 2), k1 = 1 << (l + 3), k0_2 = k0 >> 1; + int rlim = n >> (l + 6), r; + int lim = 1 << (l + 1); + int i_off; + float *A0 = A; + i_off = n2 - 1; + for (r = rlim; r > 0; --r) { + imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); + A0 += k1 * 4; + i_off -= 8; + } + } + + // iterations with count: + // ld-6,-5,-4 all interleaved together + // the big win comes from getting rid of needless flops + // due to the constants on pass 5 & 4 being all 1 and 0; + // combining them to be simultaneous to improve cache made little difference + imdct_step3_inner_s_loop_ld654(n >> 5, u, n2 - 1, A, n); + + // output is u + + // step 4, 5, and 6 + // cannot be in-place because of step 5 + { + uint16 *bitrev = f->bit_reverse[blocktype]; + // weirdly, I'd have thought reading sequentially and writing + // erratically would have been better than vice-versa, but in + // fact that's not what my testing showed. (That is, with + // j = bitreverse(i), do you read i and write j, or read j and write i.) + + float *d0 = &v[n4 - 4]; + float *d1 = &v[n2 - 4]; + while (d0 >= v) { + int k4; + + k4 = bitrev[0]; + d1[3] = u[k4 + 0]; + d1[2] = u[k4 + 1]; + d0[3] = u[k4 + 2]; + d0[2] = u[k4 + 3]; + + k4 = bitrev[1]; + d1[1] = u[k4 + 0]; + d1[0] = u[k4 + 1]; + d0[1] = u[k4 + 2]; + d0[0] = u[k4 + 3]; + + d0 -= 4; + d1 -= 4; + bitrev += 2; + } + } + // (paper output is u, now v) + + + // data must be in buf2 + assert(v == buf2); + + // step 7 (paper output is v, now v) + // this is now in place + { + float *C = f->C[blocktype]; + float *d, *e; + + d = v; + e = v + n2 - 4; + + while (d < e) { + float a02, a11, b0, b1, b2, b3; + + a02 = d[0] - e[2]; + a11 = d[1] + e[3]; + + b0 = C[1] * a02 + C[0] * a11; + b1 = C[1] * a11 - C[0] * a02; + + b2 = d[0] + e[2]; + b3 = d[1] - e[3]; + + d[0] = b2 + b0; + d[1] = b3 + b1; + e[2] = b2 - b0; + e[3] = b1 - b3; + + a02 = d[2] - e[0]; + a11 = d[3] + e[1]; + + b0 = C[3] * a02 + C[2] * a11; + b1 = C[3] * a11 - C[2] * a02; + + b2 = d[2] + e[0]; + b3 = d[3] - e[1]; + + d[2] = b2 + b0; + d[3] = b3 + b1; + e[0] = b2 - b0; + e[1] = b1 - b3; + + C += 4; + d += 4; + e -= 4; + } + } + + // data must be in buf2 + + + // step 8+decode (paper output is X, now buffer) + // this generates pairs of data a la 8 and pushes them directly through + // the decode kernel (pushing rather than pulling) to avoid having + // to make another pass later + + // this cannot POSSIBLY be in place, so we refer to the buffers directly + + { + float *d0, *d1, *d2, *d3; + + float *B = f->B[blocktype] + n2 - 8; + float *e = buf2 + n2 - 8; + d0 = &buffer[0]; + d1 = &buffer[n2 - 4]; + d2 = &buffer[n2]; + d3 = &buffer[n - 4]; + while (e >= v) { + float p0, p1, p2, p3; + + p3 = e[6] * B[7] - e[7] * B[6]; + p2 = -e[6] * B[6] - e[7] * B[7]; + + d0[0] = p3; + d1[3] = -p3; + d2[0] = p2; + d3[3] = p2; + + p1 = e[4] * B[5] - e[5] * B[4]; + p0 = -e[4] * B[4] - e[5] * B[5]; + + d0[1] = p1; + d1[2] = -p1; + d2[1] = p0; + d3[2] = p0; + + p3 = e[2] * B[3] - e[3] * B[2]; + p2 = -e[2] * B[2] - e[3] * B[3]; - // step 8+decode (paper output is X, now buffer) - // this generates pairs of data a la 8 and pushes them directly through - // the decode kernel (pushing rather than pulling) to avoid having - // to make another pass later + d0[2] = p3; + d1[1] = -p3; + d2[2] = p2; + d3[1] = p2; - // this cannot POSSIBLY be in place, so we refer to the buffers directly + p1 = e[0] * B[1] - e[1] * B[0]; + p0 = -e[0] * B[0] - e[1] * B[1]; - { - float *d0,*d1,*d2,*d3; + d0[3] = p1; + d1[0] = -p1; + d2[3] = p0; + d3[0] = p0; - float *B = f->B[blocktype] + n2 - 8; - float *e = buf2 + n2 - 8; - d0 = &buffer[0]; - d1 = &buffer[n2-4]; - d2 = &buffer[n2]; - d3 = &buffer[n-4]; - while (e >= v) { - float p0,p1,p2,p3; + B -= 8; + e -= 8; + d0 += 4; + d2 += 4; + d1 -= 4; + d3 -= 4; + } + } - p3 = e[6]*B[7] - e[7]*B[6]; - p2 = -e[6]*B[6] - e[7]*B[7]; - - d0[0] = p3; - d1[3] = - p3; - d2[0] = p2; - d3[3] = p2; - - p1 = e[4]*B[5] - e[5]*B[4]; - p0 = -e[4]*B[4] - e[5]*B[5]; - - d0[1] = p1; - d1[2] = - p1; - d2[1] = p0; - d3[2] = p0; - - p3 = e[2]*B[3] - e[3]*B[2]; - p2 = -e[2]*B[2] - e[3]*B[3]; - - d0[2] = p3; - d1[1] = - p3; - d2[2] = p2; - d3[1] = p2; - - p1 = e[0]*B[1] - e[1]*B[0]; - p0 = -e[0]*B[0] - e[1]*B[1]; - - d0[3] = p1; - d1[0] = - p1; - d2[3] = p0; - d3[0] = p0; - - B -= 8; - e -= 8; - d0 += 4; - d2 += 4; - d1 -= 4; - d3 -= 4; - } - } - - temp_free(f,buf2); - temp_alloc_restore(f,save_point); + temp_free(f, buf2); + temp_alloc_restore(f, save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { - float s; - float A[1 << 12], B[1 << 12], C[1 << 11]; - int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; - int n3_4 = n - n4, ld; - // how can they claim this only uses N words?! - // oh, because they're only used sparsely, whoops - float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; - // set up twiddle factors - - for (k=k2=0; k < n4; ++k,k2+=2) { - A[k2 ] = (float) cos(4*k*M_PI/n); - A[k2+1] = (float) -sin(4*k*M_PI/n); - B[k2 ] = (float) cos((k2+1)*M_PI/n/2); - B[k2+1] = (float) sin((k2+1)*M_PI/n/2); - } - for (k=k2=0; k < n8; ++k,k2+=2) { - C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); - C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); - } - - // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" - // Note there are bugs in that pseudocode, presumably due to them attempting - // to rename the arrays nicely rather than representing the way their actual - // implementation bounces buffers back and forth. As a result, even in the - // "some formulars corrected" version, a direct implementation fails. These - // are noted below as "paper bug". - - // copy and reflect spectral data - for (k=0; k < n2; ++k) u[k] = buffer[k]; - for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; - // kernel from paper - // step 1 - for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { - v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; - v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; - } - // step 2 - for (k=k4=0; k < n8; k+=1, k4+=4) { - w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; - w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; - 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]; - 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]; - } - // step 3 - ld = ilog(n) - 1; // ilog is off-by-one from normal definitions - for (l=0; l < ld-3; ++l) { - int k0 = n >> (l+2), k1 = 1 << (l+3); - int rlim = n >> (l+4), r4, r; - int s2lim = 1 << (l+2), s2; - for (r=r4=0; r < rlim; r4+=4,++r) { - for (s2=0; s2 < s2lim; s2+=2) { - u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; - u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; - u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; - u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] - + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; - } - } - if (l+1 < ld-3) { - // paper bug: ping-ponging of u&w here is omitted - memcpy(w, u, sizeof(u)); - } - } - - // step 4 - for (i=0; i < n8; ++i) { - int j = bit_reverse(i) >> (32-ld+3); - assert(j < n8); - if (i == j) { - // paper bug: original code probably swapped in place; if copying, - // need to directly copy in this case - int i8 = i << 3; - v[i8+1] = u[i8+1]; - v[i8+3] = u[i8+3]; - v[i8+5] = u[i8+5]; - v[i8+7] = u[i8+7]; - } else if (i < j) { - int i8 = i << 3, j8 = j << 3; - v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; - v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; - v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; - v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; - } - } - // step 5 - for (k=0; k < n2; ++k) { - w[k] = v[k*2+1]; - } - // step 6 - for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { - u[n-1-k2] = w[k4]; - u[n-2-k2] = w[k4+1]; - u[n3_4 - 1 - k2] = w[k4+2]; - u[n3_4 - 2 - k2] = w[k4+3]; - } - // step 7 - for (k=k2=0; k < n8; ++k, k2 += 2) { - 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; - 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; - 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; - 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; - } - // step 8 - for (k=k2=0; k < n4; ++k,k2 += 2) { - X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; - X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; - } - - // decode kernel to output - // determined the following value experimentally - // (by first figuring out what made inverse_mdct_slow work); then matching that here - // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) - s = 0.5; // theoretically would be n4 - - // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, - // so it needs to use the "old" B values to behave correctly, or else - // set s to 1.0 ]]] - for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; - for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; - for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; + float s; + float A[1 << 12], B[1 << 12], C[1 << 11]; + int i, k, k2, k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; + int n3_4 = n - n4, ld; + // how can they claim this only uses N words?! + // oh, because they're only used sparsely, whoops + float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; + // set up twiddle factors + + for (k = k2 = 0; k < n4; ++k, k2 += 2) { + A[k2] = (float)cos(4 * k*M_PI / n); + A[k2 + 1] = (float)-sin(4 * k*M_PI / n); + B[k2] = (float)cos((k2 + 1)*M_PI / n / 2); + B[k2 + 1] = (float)sin((k2 + 1)*M_PI / n / 2); + } + for (k = k2 = 0; k < n8; ++k, k2 += 2) { + C[k2] = (float)cos(2 * (k2 + 1)*M_PI / n); + C[k2 + 1] = (float)-sin(2 * (k2 + 1)*M_PI / n); + } + + // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" + // Note there are bugs in that pseudocode, presumably due to them attempting + // to rename the arrays nicely rather than representing the way their actual + // implementation bounces buffers back and forth. As a result, even in the + // "some formulars corrected" version, a direct implementation fails. These + // are noted below as "paper bug". + + // copy and reflect spectral data + for (k = 0; k < n2; ++k) u[k] = buffer[k]; + for (; k < n; ++k) u[k] = -buffer[n - k - 1]; + // kernel from paper + // step 1 + for (k = k2 = k4 = 0; k < n4; k += 1, k2 += 2, k4 += 4) { + v[n - k4 - 1] = (u[k4] - u[n - k4 - 1]) * A[k2] - (u[k4 + 2] - u[n - k4 - 3])*A[k2 + 1]; + v[n - k4 - 3] = (u[k4] - u[n - k4 - 1]) * A[k2 + 1] + (u[k4 + 2] - u[n - k4 - 3])*A[k2]; + } + // step 2 + for (k = k4 = 0; k < n8; k += 1, k4 += 4) { + w[n2 + 3 + k4] = v[n2 + 3 + k4] + v[k4 + 3]; + w[n2 + 1 + k4] = v[n2 + 1 + k4] + v[k4 + 1]; + 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]; + 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]; + } + // step 3 + ld = ilog(n) - 1; // ilog is off-by-one from normal definitions + for (l = 0; l < ld - 3; ++l) { + int k0 = n >> (l + 2), k1 = 1 << (l + 3); + int rlim = n >> (l + 4), r4, r; + int s2lim = 1 << (l + 2), s2; + for (r = r4 = 0; r < rlim; r4 += 4, ++r) { + for (s2 = 0; s2 < s2lim; s2 += 2) { + u[n - 1 - k0*s2 - r4] = w[n - 1 - k0*s2 - r4] + w[n - 1 - k0*(s2 + 1) - r4]; + u[n - 3 - k0*s2 - r4] = w[n - 3 - k0*s2 - r4] + w[n - 3 - k0*(s2 + 1) - r4]; + u[n - 1 - k0*(s2 + 1) - r4] = (w[n - 1 - k0*s2 - r4] - w[n - 1 - k0*(s2 + 1) - r4]) * A[r*k1] + - (w[n - 3 - k0*s2 - r4] - w[n - 3 - k0*(s2 + 1) - r4]) * A[r*k1 + 1]; + u[n - 3 - k0*(s2 + 1) - r4] = (w[n - 3 - k0*s2 - r4] - w[n - 3 - k0*(s2 + 1) - r4]) * A[r*k1] + + (w[n - 1 - k0*s2 - r4] - w[n - 1 - k0*(s2 + 1) - r4]) * A[r*k1 + 1]; + } + } + if (l + 1 < ld - 3) { + // paper bug: ping-ponging of u&w here is omitted + memcpy(w, u, sizeof(u)); + } + } + + // step 4 + for (i = 0; i < n8; ++i) { + int j = bit_reverse(i) >> (32 - ld + 3); + assert(j < n8); + if (i == j) { + // paper bug: original code probably swapped in place; if copying, + // need to directly copy in this case + int i8 = i << 3; + v[i8 + 1] = u[i8 + 1]; + v[i8 + 3] = u[i8 + 3]; + v[i8 + 5] = u[i8 + 5]; + v[i8 + 7] = u[i8 + 7]; + } + else if (i < j) { + int i8 = i << 3, j8 = j << 3; + v[j8 + 1] = u[i8 + 1], v[i8 + 1] = u[j8 + 1]; + v[j8 + 3] = u[i8 + 3], v[i8 + 3] = u[j8 + 3]; + v[j8 + 5] = u[i8 + 5], v[i8 + 5] = u[j8 + 5]; + v[j8 + 7] = u[i8 + 7], v[i8 + 7] = u[j8 + 7]; + } + } + // step 5 + for (k = 0; k < n2; ++k) { + w[k] = v[k * 2 + 1]; + } + // step 6 + for (k = k2 = k4 = 0; k < n8; ++k, k2 += 2, k4 += 4) { + u[n - 1 - k2] = w[k4]; + u[n - 2 - k2] = w[k4 + 1]; + u[n3_4 - 1 - k2] = w[k4 + 2]; + u[n3_4 - 2 - k2] = w[k4 + 3]; + } + // step 7 + for (k = k2 = 0; k < n8; ++k, k2 += 2) { + 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; + 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; + 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; + 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; + } + // step 8 + for (k = k2 = 0; k < n4; ++k, k2 += 2) { + X[k] = v[k2 + n2] * B[k2] + v[k2 + 1 + n2] * B[k2 + 1]; + X[n2 - 1 - k] = v[k2 + n2] * B[k2 + 1] - v[k2 + 1 + n2] * B[k2]; + } + + // decode kernel to output + // determined the following value experimentally + // (by first figuring out what made inverse_mdct_slow work); then matching that here + // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) + s = 0.5; // theoretically would be n4 + + // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, + // so it needs to use the "old" B values to behave correctly, or else + // set s to 1.0 ]]] + for (i = 0; i < n4; ++i) buffer[i] = s * X[i + n4]; + for (; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; + for (; i < n; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { - len <<= 1; - if (len == f->blocksize_0) return f->window[0]; - if (len == f->blocksize_1) return f->window[1]; - assert(0); - return NULL; + len <<= 1; + if (len == f->blocksize_0) return f->window[0]; + if (len == f->blocksize_1) return f->window[1]; + assert(0); + return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR @@ -3049,39 +3076,40 @@ typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { - int n2 = n >> 1; - int s = map->chan[i].mux, floor; - floor = map->submap_floor[s]; - if (f->floor_types[floor] == 0) { - return error(f, VORBIS_invalid_stream); - } else { - Floor1 *g = &f->floor_config[floor].floor1; - int j,q; - int lx = 0, ly = finalY[0] * g->floor1_multiplier; - for (q=1; q < g->values; ++q) { - j = g->sorted_order[q]; - #ifndef STB_VORBIS_NO_DEFER_FLOOR - if (finalY[j] >= 0) - #else - if (step2_flag[j]) - #endif - { - int hy = finalY[j] * g->floor1_multiplier; - int hx = g->Xlist[j]; - if (lx != hx) - draw_line(target, lx,ly, hx,hy, n2); + int n2 = n >> 1; + int s = map->chan[i].mux, floor; + floor = map->submap_floor[s]; + if (f->floor_types[floor] == 0) { + return error(f, VORBIS_invalid_stream); + } + else { + Floor1 *g = &f->floor_config[floor].floor1; + int j, q; + int lx = 0, ly = finalY[0] * g->floor1_multiplier; + for (q = 1; q < g->values; ++q) { + j = g->sorted_order[q]; +#ifndef STB_VORBIS_NO_DEFER_FLOOR + if (finalY[j] >= 0) +#else + if (step2_flag[j]) +#endif + { + int hy = finalY[j] * g->floor1_multiplier; + int hx = g->Xlist[j]; + if (lx != hx) + draw_line(target, lx, ly, hx, hy, n2); + CHECK(f); + lx = hx, ly = hy; + } + } + if (lx < n2) { + // optimization of: draw_line(target, lx,ly, n,ly, n2); + for (j = lx; j < n2; ++j) + LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); - lx = hx, ly = hy; - } - } - if (lx < n2) { - // optimization of: draw_line(target, lx,ly, n,ly, n2); - for (j=lx; j < n2; ++j) - LINE_OP(target[j], inverse_db_table[ly]); - CHECK(f); - } - } - return TRUE; + } + } + return TRUE; } // The meaning of "left" and "right" @@ -3100,1340 +3128,1373 @@ static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *f 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) { - Mode *m; - int i, n, prev, next, window_center; - f->channel_buffer_start = f->channel_buffer_end = 0; - - retry: - if (f->eof) return FALSE; - if (!maybe_start_packet(f)) - return FALSE; - // check packet type - if (get_bits(f,1) != 0) { - if (IS_PUSH_MODE(f)) - return error(f,VORBIS_bad_packet_type); - while (EOP != get8_packet(f)); - goto retry; - } - - if (f->alloc.alloc_buffer) - assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); - - i = get_bits(f, ilog(f->mode_count-1)); - if (i == EOP) return FALSE; - if (i >= f->mode_count) return FALSE; - *mode = i; - m = f->mode_config + i; - if (m->blockflag) { - n = f->blocksize_1; - prev = get_bits(f,1); - next = get_bits(f,1); - } else { - prev = next = 0; - n = f->blocksize_0; - } - -// WINDOWING - - window_center = n >> 1; - if (m->blockflag && !prev) { - *p_left_start = (n - f->blocksize_0) >> 2; - *p_left_end = (n + f->blocksize_0) >> 2; - } else { - *p_left_start = 0; - *p_left_end = window_center; - } - if (m->blockflag && !next) { - *p_right_start = (n*3 - f->blocksize_0) >> 2; - *p_right_end = (n*3 + f->blocksize_0) >> 2; - } else { - *p_right_start = window_center; - *p_right_end = n; - } - - return TRUE; + Mode *m; + int i, n, prev, next, window_center; + f->channel_buffer_start = f->channel_buffer_end = 0; + +retry: + if (f->eof) return FALSE; + if (!maybe_start_packet(f)) + return FALSE; + // check packet type + if (get_bits(f, 1) != 0) { + if (IS_PUSH_MODE(f)) + return error(f, VORBIS_bad_packet_type); + while (EOP != get8_packet(f)); + goto retry; + } + + if (f->alloc.alloc_buffer) + assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); + + i = get_bits(f, ilog(f->mode_count - 1)); + if (i == EOP) return FALSE; + if (i >= f->mode_count) return FALSE; + *mode = i; + m = f->mode_config + i; + if (m->blockflag) { + n = f->blocksize_1; + prev = get_bits(f, 1); + next = get_bits(f, 1); + } + else { + prev = next = 0; + n = f->blocksize_0; + } + + // WINDOWING + + window_center = n >> 1; + if (m->blockflag && !prev) { + *p_left_start = (n - f->blocksize_0) >> 2; + *p_left_end = (n + f->blocksize_0) >> 2; + } + else { + *p_left_start = 0; + *p_left_end = window_center; + } + if (m->blockflag && !next) { + *p_right_start = (n * 3 - f->blocksize_0) >> 2; + *p_right_end = (n * 3 + f->blocksize_0) >> 2; + } + else { + *p_right_start = window_center; + *p_right_end = n; + } + + return TRUE; } 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) { - Mapping *map; - int i,j,k,n,n2; - int zero_channel[256]; - int really_zero_channel[256]; - -// WINDOWING - - n = f->blocksize[m->blockflag]; - map = &f->mapping[m->mapping]; - -// FLOORS - n2 = n >> 1; - - CHECK(f); - - for (i=0; i < f->channels; ++i) { - int s = map->chan[i].mux, floor; - zero_channel[i] = FALSE; - floor = map->submap_floor[s]; - if (f->floor_types[floor] == 0) { - return error(f, VORBIS_invalid_stream); - } else { - Floor1 *g = &f->floor_config[floor].floor1; - if (get_bits(f, 1)) { - short *finalY; - uint8 step2_flag[256]; - static int range_list[4] = { 256, 128, 86, 64 }; - int range = range_list[g->floor1_multiplier-1]; - int offset = 2; - finalY = f->finalY[i]; - finalY[0] = get_bits(f, ilog(range)-1); - finalY[1] = get_bits(f, ilog(range)-1); - for (j=0; j < g->partitions; ++j) { - int pclass = g->partition_class_list[j]; - int cdim = g->class_dimensions[pclass]; - int cbits = g->class_subclasses[pclass]; - int csub = (1 << cbits)-1; - int cval = 0; - if (cbits) { - Codebook *c = f->codebooks + g->class_masterbooks[pclass]; - DECODE(cval,f,c); - } - for (k=0; k < cdim; ++k) { - int book = g->subclass_books[pclass][cval & csub]; - cval = cval >> cbits; - if (book >= 0) { - int temp; - Codebook *c = f->codebooks + book; - DECODE(temp,f,c); - finalY[offset++] = temp; - } else - finalY[offset++] = 0; - } - } - if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec - step2_flag[0] = step2_flag[1] = 1; - for (j=2; j < g->values; ++j) { - int low, high, pred, highroom, lowroom, room, val; - low = g->neighbors[j][0]; - high = g->neighbors[j][1]; - //neighbors(g->Xlist, j, &low, &high); - pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); - val = finalY[j]; - highroom = range - pred; - lowroom = pred; - if (highroom < lowroom) - room = highroom * 2; - else - room = lowroom * 2; - if (val) { - step2_flag[low] = step2_flag[high] = 1; - step2_flag[j] = 1; - if (val >= room) - if (highroom > lowroom) - finalY[j] = val - lowroom + pred; - else - finalY[j] = pred - val + highroom - 1; - else - if (val & 1) - finalY[j] = pred - ((val+1)>>1); - else - finalY[j] = pred + (val>>1); - } else { - step2_flag[j] = 0; - finalY[j] = pred; - } - } + Mapping *map; + int i, j, k, n, n2; + int zero_channel[256]; + int really_zero_channel[256]; + + // WINDOWING + + n = f->blocksize[m->blockflag]; + map = &f->mapping[m->mapping]; + + // FLOORS + n2 = n >> 1; + + CHECK(f); + + for (i = 0; i < f->channels; ++i) { + int s = map->chan[i].mux, floor; + zero_channel[i] = FALSE; + floor = map->submap_floor[s]; + if (f->floor_types[floor] == 0) { + return error(f, VORBIS_invalid_stream); + } + else { + Floor1 *g = &f->floor_config[floor].floor1; + if (get_bits(f, 1)) { + short *finalY; + uint8 step2_flag[256]; + static int range_list[4] = { 256, 128, 86, 64 }; + int range = range_list[g->floor1_multiplier - 1]; + int offset = 2; + finalY = f->finalY[i]; + finalY[0] = get_bits(f, ilog(range) - 1); + finalY[1] = get_bits(f, ilog(range) - 1); + for (j = 0; j < g->partitions; ++j) { + int pclass = g->partition_class_list[j]; + int cdim = g->class_dimensions[pclass]; + int cbits = g->class_subclasses[pclass]; + int csub = (1 << cbits) - 1; + int cval = 0; + if (cbits) { + Codebook *c = f->codebooks + g->class_masterbooks[pclass]; + DECODE(cval, f, c); + } + for (k = 0; k < cdim; ++k) { + int book = g->subclass_books[pclass][cval & csub]; + cval = cval >> cbits; + if (book >= 0) { + int temp; + Codebook *c = f->codebooks + book; + DECODE(temp, f, c); + finalY[offset++] = temp; + } + else + finalY[offset++] = 0; + } + } + if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec + step2_flag[0] = step2_flag[1] = 1; + for (j = 2; j < g->values; ++j) { + int low, high, pred, highroom, lowroom, room, val; + low = g->neighbors[j][0]; + high = g->neighbors[j][1]; + //neighbors(g->Xlist, j, &low, &high); + pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); + val = finalY[j]; + highroom = range - pred; + lowroom = pred; + if (highroom < lowroom) + room = highroom * 2; + else + room = lowroom * 2; + if (val) { + step2_flag[low] = step2_flag[high] = 1; + step2_flag[j] = 1; + if (val >= room) + if (highroom > lowroom) + finalY[j] = val - lowroom + pred; + else + finalY[j] = pred - val + highroom - 1; + else + if (val & 1) + finalY[j] = pred - ((val + 1) >> 1); + else + finalY[j] = pred + (val >> 1); + } + else { + step2_flag[j] = 0; + finalY[j] = pred; + } + } #ifdef STB_VORBIS_NO_DEFER_FLOOR - do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); + do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else - // defer final floor computation until _after_ residue - for (j=0; j < g->values; ++j) { - if (!step2_flag[j]) - finalY[j] = -1; - } + // defer final floor computation until _after_ residue + for (j = 0; j < g->values; ++j) { + if (!step2_flag[j]) + finalY[j] = -1; + } #endif - } else { - error: - zero_channel[i] = TRUE; - } - // So we just defer everything else to later - - // at this point we've decoded the floor into buffer - } - } - CHECK(f); - // at this point we've decoded all floors - - if (f->alloc.alloc_buffer) - assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); - - // re-enable coupled channels if necessary - memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); - for (i=0; i < map->coupling_steps; ++i) - if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { - zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; - } - - CHECK(f); -// RESIDUE DECODE - for (i=0; i < map->submaps; ++i) { - float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; - int r; - uint8 do_not_decode[256]; - int ch = 0; - for (j=0; j < f->channels; ++j) { - if (map->chan[j].mux == i) { - if (zero_channel[j]) { - do_not_decode[ch] = TRUE; - residue_buffers[ch] = NULL; - } else { - do_not_decode[ch] = FALSE; - residue_buffers[ch] = f->channel_buffers[j]; } - ++ch; - } - } - r = map->submap_residue[i]; - decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); - } - - if (f->alloc.alloc_buffer) - assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); - CHECK(f); - -// INVERSE COUPLING - for (i = map->coupling_steps-1; i >= 0; --i) { - int n2 = n >> 1; - float *m = f->channel_buffers[map->chan[i].magnitude]; - float *a = f->channel_buffers[map->chan[i].angle ]; - for (j=0; j < n2; ++j) { - float a2,m2; - if (m[j] > 0) - if (a[j] > 0) - m2 = m[j], a2 = m[j] - a[j]; - else - a2 = m[j], m2 = m[j] + a[j]; - else - if (a[j] > 0) - m2 = m[j], a2 = m[j] + a[j]; + else { + error: + zero_channel[i] = TRUE; + } + // So we just defer everything else to later + + // at this point we've decoded the floor into buffer + } + } + CHECK(f); + // at this point we've decoded all floors + + if (f->alloc.alloc_buffer) + assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); + + // re-enable coupled channels if necessary + memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); + for (i = 0; i < map->coupling_steps; ++i) + if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { + zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; + } + + CHECK(f); + // RESIDUE DECODE + for (i = 0; i < map->submaps; ++i) { + float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; + int r; + uint8 do_not_decode[256]; + int ch = 0; + for (j = 0; j < f->channels; ++j) { + if (map->chan[j].mux == i) { + if (zero_channel[j]) { + do_not_decode[ch] = TRUE; + residue_buffers[ch] = NULL; + } + else { + do_not_decode[ch] = FALSE; + residue_buffers[ch] = f->channel_buffers[j]; + } + ++ch; + } + } + r = map->submap_residue[i]; + decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); + } + + if (f->alloc.alloc_buffer) + assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); + CHECK(f); + + // INVERSE COUPLING + for (i = map->coupling_steps - 1; i >= 0; --i) { + int n2 = n >> 1; + float *m = f->channel_buffers[map->chan[i].magnitude]; + float *a = f->channel_buffers[map->chan[i].angle]; + for (j = 0; j < n2; ++j) { + float a2, m2; + if (m[j] > 0) + if (a[j] > 0) + m2 = m[j], a2 = m[j] - a[j]; + else + a2 = m[j], m2 = m[j] + a[j]; else - a2 = m[j], m2 = m[j] - a[j]; - m[j] = m2; - a[j] = a2; - } - } - CHECK(f); - - // finish decoding the floors + if (a[j] > 0) + m2 = m[j], a2 = m[j] + a[j]; + else + a2 = m[j], m2 = m[j] - a[j]; + m[j] = m2; + a[j] = a2; + } + } + CHECK(f); + + // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR - for (i=0; i < f->channels; ++i) { - if (really_zero_channel[i]) { - memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); - } else { - do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); - } - } + for (i = 0; i < f->channels; ++i) { + if (really_zero_channel[i]) { + memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); + } + else { + do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); + } + } #else - for (i=0; i < f->channels; ++i) { - if (really_zero_channel[i]) { - memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); - } else { - for (j=0; j < n2; ++j) - f->channel_buffers[i][j] *= f->floor_buffers[i][j]; - } - } + for (i = 0; i < f->channels; ++i) { + if (really_zero_channel[i]) { + memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); + } + else { + for (j = 0; j < n2; ++j) + f->channel_buffers[i][j] *= f->floor_buffers[i][j]; + } + } #endif -// INVERSE MDCT - CHECK(f); - for (i=0; i < f->channels; ++i) - inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); - CHECK(f); - - // this shouldn't be necessary, unless we exited on an error - // and want to flush to get to the next packet - flush_packet(f); - - if (f->first_decode) { - // assume we start so first non-discarded sample is sample 0 - // this isn't to spec, but spec would require us to read ahead - // and decode the size of all current frames--could be done, - // but presumably it's not a commonly used feature - f->current_loc = -n2; // start of first frame is positioned for discard - // we might have to discard samples "from" the next frame too, - // if we're lapping a large block then a small at the start? - f->discard_samples_deferred = n - right_end; - f->current_loc_valid = TRUE; - f->first_decode = FALSE; - } else if (f->discard_samples_deferred) { - if (f->discard_samples_deferred >= right_start - left_start) { - f->discard_samples_deferred -= (right_start - left_start); - left_start = right_start; - *p_left = left_start; - } else { - left_start += f->discard_samples_deferred; - *p_left = left_start; - f->discard_samples_deferred = 0; - } - } else if (f->previous_length == 0 && f->current_loc_valid) { - // we're recovering from a seek... that means we're going to discard - // the samples from this packet even though we know our position from - // the last page header, so we need to update the position based on - // the discarded samples here - // but wait, the code below is going to add this in itself even - // on a discard, so we don't need to do it here... - } - - // check if we have ogg information about the sample # for this packet - if (f->last_seg_which == f->end_seg_with_known_loc) { - // if we have a valid current loc, and this is final: - if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { - uint32 current_end = f->known_loc_for_packet - (n-right_end); - // then let's infer the size of the (probably) short final frame - if (current_end < f->current_loc + (right_end-left_start)) { - if (current_end < f->current_loc) { - // negative truncation, that's impossible! - *len = 0; - } else { - *len = current_end - f->current_loc; + // INVERSE MDCT + CHECK(f); + for (i = 0; i < f->channels; ++i) + inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); + CHECK(f); + + // this shouldn't be necessary, unless we exited on an error + // and want to flush to get to the next packet + flush_packet(f); + + if (f->first_decode) { + // assume we start so first non-discarded sample is sample 0 + // this isn't to spec, but spec would require us to read ahead + // and decode the size of all current frames--could be done, + // but presumably it's not a commonly used feature + f->current_loc = -n2; // start of first frame is positioned for discard + // we might have to discard samples "from" the next frame too, + // if we're lapping a large block then a small at the start? + f->discard_samples_deferred = n - right_end; + f->current_loc_valid = TRUE; + f->first_decode = FALSE; + } + else if (f->discard_samples_deferred) { + if (f->discard_samples_deferred >= right_start - left_start) { + f->discard_samples_deferred -= (right_start - left_start); + left_start = right_start; + *p_left = left_start; + } + else { + left_start += f->discard_samples_deferred; + *p_left = left_start; + f->discard_samples_deferred = 0; + } + } + else if (f->previous_length == 0 && f->current_loc_valid) { + // we're recovering from a seek... that means we're going to discard + // the samples from this packet even though we know our position from + // the last page header, so we need to update the position based on + // the discarded samples here + // but wait, the code below is going to add this in itself even + // on a discard, so we don't need to do it here... + } + + // check if we have ogg information about the sample # for this packet + if (f->last_seg_which == f->end_seg_with_known_loc) { + // if we have a valid current loc, and this is final: + if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { + uint32 current_end = f->known_loc_for_packet; + // then let's infer the size of the (probably) short final frame + if (current_end < f->current_loc + (right_end - left_start)) { + if (current_end < f->current_loc) { + // negative truncation, that's impossible! + *len = 0; + } + else { + *len = current_end - f->current_loc; + } + *len += left_start; // this doesn't seem right, but has no ill effect on my test files + if (*len > right_end) *len = right_end; // this should never happen + f->current_loc += *len; + return TRUE; } - *len += left_start; - if (*len > right_end) *len = right_end; // this should never happen - f->current_loc += *len; - return TRUE; - } - } - // otherwise, just set our sample loc - // guess that the ogg granule pos refers to the _middle_ of the - // last frame? - // set f->current_loc to the position of left_start - f->current_loc = f->known_loc_for_packet - (n2-left_start); - f->current_loc_valid = TRUE; - } - if (f->current_loc_valid) - f->current_loc += (right_start - left_start); - - if (f->alloc.alloc_buffer) - assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); - *len = right_end; // ignore samples after the window goes to 0 - CHECK(f); - - return TRUE; + } + // otherwise, just set our sample loc + // guess that the ogg granule pos refers to the _middle_ of the + // last frame? + // set f->current_loc to the position of left_start + f->current_loc = f->known_loc_for_packet - (n2 - left_start); + f->current_loc_valid = TRUE; + } + if (f->current_loc_valid) + f->current_loc += (right_start - left_start); + + if (f->alloc.alloc_buffer) + assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); + *len = right_end; // ignore samples after the window goes to 0 + CHECK(f); + + return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { - int mode, left_end, right_end; - if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; - return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); + int mode, left_end, right_end; + if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; + return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { - int prev,i,j; - // we use right&left (the start of the right- and left-window sin()-regions) - // to determine how much to return, rather than inferring from the rules - // (same result, clearer code); 'left' indicates where our sin() window - // starts, therefore where the previous window's right edge starts, and - // therefore where to start mixing from the previous buffer. 'right' - // indicates where our sin() ending-window starts, therefore that's where - // we start saving, and where our returned-data ends. - - // mixin from previous window - if (f->previous_length) { - int i,j, n = f->previous_length; - float *w = get_window(f, n); - for (i=0; i < f->channels; ++i) { - for (j=0; j < n; ++j) - f->channel_buffers[i][left+j] = - f->channel_buffers[i][left+j]*w[ j] + - f->previous_window[i][ j]*w[n-1-j]; - } - } - - prev = f->previous_length; - - // last half of this data becomes previous window - f->previous_length = len - right; - - // @OPTIMIZE: could avoid this copy by double-buffering the - // output (flipping previous_window with channel_buffers), but - // then previous_window would have to be 2x as large, and - // channel_buffers couldn't be temp mem (although they're NOT - // currently temp mem, they could be (unless we want to level - // performance by spreading out the computation)) - for (i=0; i < f->channels; ++i) - for (j=0; right+j < len; ++j) - f->previous_window[i][j] = f->channel_buffers[i][right+j]; - - if (!prev) - // there was no previous packet, so this data isn't valid... - // this isn't entirely true, only the would-have-overlapped data - // isn't valid, but this seems to be what the spec requires - return 0; - - // truncate a short frame - if (len < right) right = len; - - f->samples_output += right-left; - - return right - left; + int prev, i, j; + // we use right&left (the start of the right- and left-window sin()-regions) + // to determine how much to return, rather than inferring from the rules + // (same result, clearer code); 'left' indicates where our sin() window + // starts, therefore where the previous window's right edge starts, and + // therefore where to start mixing from the previous buffer. 'right' + // indicates where our sin() ending-window starts, therefore that's where + // we start saving, and where our returned-data ends. + + // mixin from previous window + if (f->previous_length) { + int i, j, n = f->previous_length; + float *w = get_window(f, n); + for (i = 0; i < f->channels; ++i) { + for (j = 0; j < n; ++j) + f->channel_buffers[i][left + j] = + f->channel_buffers[i][left + j] * w[j] + + f->previous_window[i][j] * w[n - 1 - j]; + } + } + + prev = f->previous_length; + + // last half of this data becomes previous window + f->previous_length = len - right; + + // @OPTIMIZE: could avoid this copy by double-buffering the + // output (flipping previous_window with channel_buffers), but + // then previous_window would have to be 2x as large, and + // channel_buffers couldn't be temp mem (although they're NOT + // currently temp mem, they could be (unless we want to level + // performance by spreading out the computation)) + for (i = 0; i < f->channels; ++i) + for (j = 0; right + j < len; ++j) + f->previous_window[i][j] = f->channel_buffers[i][right + j]; + + if (!prev) + // there was no previous packet, so this data isn't valid... + // this isn't entirely true, only the would-have-overlapped data + // isn't valid, but this seems to be what the spec requires + return 0; + + // truncate a short frame + if (len < right) right = len; + + f->samples_output += right - left; + + return right - left; } static int vorbis_pump_first_frame(stb_vorbis *f) { - int len, right, left, res; - res = vorbis_decode_packet(f, &len, &left, &right); - if (res) - vorbis_finish_frame(f, len, left, right); - return res; + int len, right, left, res; + res = vorbis_decode_packet(f, &len, &left, &right); + if (res) + vorbis_finish_frame(f, len, left, right); + return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f, int end_page) { - // make sure that we have the packet available before continuing... - // this requires a full ogg parse, but we know we can fetch from f->stream - - // instead of coding this out explicitly, we could save the current read state, - // read the next packet with get8() until end-of-packet, check f->eof, then - // reset the state? but that would be slower, esp. since we'd have over 256 bytes - // of state to restore (primarily the page segment table) - - int s = f->next_seg, first = TRUE; - uint8 *p = f->stream; - - if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag - for (; s < f->segment_count; ++s) { - p += f->segments[s]; - if (f->segments[s] < 255) // stop at first short segment - break; - } - // either this continues, or it ends it... - if (end_page) - if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); - if (s == f->segment_count) - s = -1; // set 'crosses page' flag - if (p > f->stream_end) return error(f, VORBIS_need_more_data); - first = FALSE; - } - for (; s == -1;) { - uint8 *q; - int n; - - // check that we have the page header ready - if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); - // validate the page - if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); - if (p[4] != 0) return error(f, VORBIS_invalid_stream); - if (first) { // the first segment must NOT have 'continued_packet', later ones MUST - if (f->previous_length) - if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); - // if no previous length, we're resynching, so we can come in on a continued-packet, - // which we'll just drop - } else { - if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); - } - n = p[26]; // segment counts - q = p+27; // q points to segment table - p = q + n; // advance past header - // make sure we've read the segment table - if (p > f->stream_end) return error(f, VORBIS_need_more_data); - for (s=0; s < n; ++s) { - p += q[s]; - if (q[s] < 255) - break; - } - if (end_page) - if (s < n-1) return error(f, VORBIS_invalid_stream); - if (s == n) - s = -1; // set 'crosses page' flag - if (p > f->stream_end) return error(f, VORBIS_need_more_data); - first = FALSE; - } - return TRUE; + // make sure that we have the packet available before continuing... + // this requires a full ogg parse, but we know we can fetch from f->stream + + // instead of coding this out explicitly, we could save the current read state, + // read the next packet with get8() until end-of-packet, check f->eof, then + // reset the state? but that would be slower, esp. since we'd have over 256 bytes + // of state to restore (primarily the page segment table) + + int s = f->next_seg, first = TRUE; + uint8 *p = f->stream; + + if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag + for (; s < f->segment_count; ++s) { + p += f->segments[s]; + if (f->segments[s] < 255) // stop at first short segment + break; + } + // either this continues, or it ends it... + if (end_page) + if (s < f->segment_count - 1) return error(f, VORBIS_invalid_stream); + if (s == f->segment_count) + s = -1; // set 'crosses page' flag + if (p > f->stream_end) return error(f, VORBIS_need_more_data); + first = FALSE; + } + for (; s == -1;) { + uint8 *q; + int n; + + // check that we have the page header ready + if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); + // validate the page + if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); + if (p[4] != 0) return error(f, VORBIS_invalid_stream); + if (first) { // the first segment must NOT have 'continued_packet', later ones MUST + if (f->previous_length) + if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); + // if no previous length, we're resynching, so we can come in on a continued-packet, + // which we'll just drop + } + else { + if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); + } + n = p[26]; // segment counts + q = p + 27; // q points to segment table + p = q + n; // advance past header + // make sure we've read the segment table + if (p > f->stream_end) return error(f, VORBIS_need_more_data); + for (s = 0; s < n; ++s) { + p += q[s]; + if (q[s] < 255) + break; + } + if (end_page) + if (s < n - 1) return error(f, VORBIS_invalid_stream); + if (s == n) + s = -1; // set 'crosses page' flag + if (p > f->stream_end) return error(f, VORBIS_need_more_data); + first = FALSE; + } + return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { - uint8 header[6], x,y; - int len,i,j,k, max_submaps = 0; - int longest_floorlist=0; - - // first page, first packet - - if (!start_page(f)) return FALSE; - // validate page flag - if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); - if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); - if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); - // check for expected packet length - if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); - if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page); - // read packet - // check packet header - if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); - if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); - if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); - // vorbis_version - if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); - f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); - if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); - f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); - get32(f); // bitrate_maximum - get32(f); // bitrate_nominal - get32(f); // bitrate_minimum - x = get8(f); - { - int log0,log1; - log0 = x & 15; - log1 = x >> 4; - f->blocksize_0 = 1 << log0; - f->blocksize_1 = 1 << log1; - if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); - if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); - if (log0 > log1) return error(f, VORBIS_invalid_setup); - } + uint8 header[6], x, y; + int len, i, j, k, max_submaps = 0; + int longest_floorlist = 0; + + // first page, first packet + + if (!start_page(f)) return FALSE; + // validate page flag + if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); + if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); + if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); + // check for expected packet length + if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); + if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page); + // read packet + // check packet header + if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); + if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); + if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); + // vorbis_version + if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); + f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); + if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); + f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); + get32(f); // bitrate_maximum + get32(f); // bitrate_nominal + get32(f); // bitrate_minimum + x = get8(f); + { + int log0, log1; + log0 = x & 15; + log1 = x >> 4; + f->blocksize_0 = 1 << log0; + f->blocksize_1 = 1 << log1; + if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); + if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); + if (log0 > log1) return error(f, VORBIS_invalid_setup); + } + + // framing_flag + x = get8(f); + if (!(x & 1)) return error(f, VORBIS_invalid_first_page); + + // second packet! + if (!start_page(f)) return FALSE; + + if (!start_packet(f)) return FALSE; + do { + len = next_segment(f); + skip(f, len); + f->bytes_in_seg = 0; + } while (len); + + // third packet! + if (!start_packet(f)) return FALSE; - // framing_flag - x = get8(f); - if (!(x & 1)) return error(f, VORBIS_invalid_first_page); - - // second packet! - if (!start_page(f)) return FALSE; - - if (!start_packet(f)) return FALSE; - do { - len = next_segment(f); - skip(f, len); - f->bytes_in_seg = 0; - } while (len); - - // third packet! - if (!start_packet(f)) return FALSE; - - #ifndef STB_VORBIS_NO_PUSHDATA_API - if (IS_PUSH_MODE(f)) { - if (!is_whole_packet_present(f, TRUE)) { - // convert error in ogg header to write type - if (f->error == VORBIS_invalid_stream) - f->error = VORBIS_invalid_setup; - return FALSE; - } - } - #endif - - crc32_init(); // always init it, to avoid multithread race conditions - - if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); - for (i=0; i < 6; ++i) header[i] = get8_packet(f); - if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); - - // codebooks - - f->codebook_count = get_bits(f,8) + 1; - f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); - if (f->codebooks == NULL) return error(f, VORBIS_outofmem); - memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); - for (i=0; i < f->codebook_count; ++i) { - uint32 *values; - int ordered, sorted_count; - int total=0; - uint8 *lengths; - Codebook *c = f->codebooks+i; - CHECK(f); - x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); - x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); - x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); - x = get_bits(f, 8); - c->dimensions = (get_bits(f, 8)<<8) + x; - x = get_bits(f, 8); - y = get_bits(f, 8); - c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; - ordered = get_bits(f,1); - c->sparse = ordered ? 0 : get_bits(f,1); - - if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); - - if (c->sparse) - lengths = (uint8 *) setup_temp_malloc(f, c->entries); - else - lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); - - if (!lengths) return error(f, VORBIS_outofmem); - - if (ordered) { - int current_entry = 0; - int current_length = get_bits(f,5) + 1; - while (current_entry < c->entries) { - int limit = c->entries - current_entry; - int n = get_bits(f, ilog(limit)); - if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } - memset(lengths + current_entry, current_length, n); - current_entry += n; - ++current_length; - } - } else { - for (j=0; j < c->entries; ++j) { - int present = c->sparse ? get_bits(f,1) : 1; - if (present) { - lengths[j] = get_bits(f, 5) + 1; - ++total; - if (lengths[j] == 32) - return error(f, VORBIS_invalid_setup); - } else { - lengths[j] = NO_CODE; +#ifndef STB_VORBIS_NO_PUSHDATA_API + if (IS_PUSH_MODE(f)) { + if (!is_whole_packet_present(f, TRUE)) { + // convert error in ogg header to write type + if (f->error == VORBIS_invalid_stream) + f->error = VORBIS_invalid_setup; + return FALSE; + } + } +#endif + + crc32_init(); // always init it, to avoid multithread race conditions + + if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); + for (i = 0; i < 6; ++i) header[i] = get8_packet(f); + if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); + + // codebooks + + f->codebook_count = get_bits(f, 8) + 1; + f->codebooks = (Codebook *)setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); + if (f->codebooks == NULL) return error(f, VORBIS_outofmem); + memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); + for (i = 0; i < f->codebook_count; ++i) { + uint32 *values; + int ordered, sorted_count; + int total = 0; + uint8 *lengths; + Codebook *c = f->codebooks + i; + CHECK(f); + x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); + x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); + x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); + x = get_bits(f, 8); + c->dimensions = (get_bits(f, 8) << 8) + x; + x = get_bits(f, 8); + y = get_bits(f, 8); + c->entries = (get_bits(f, 8) << 16) + (y << 8) + x; + ordered = get_bits(f, 1); + c->sparse = ordered ? 0 : get_bits(f, 1); + + if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); + + if (c->sparse) + lengths = (uint8 *)setup_temp_malloc(f, c->entries); + else + lengths = c->codeword_lengths = (uint8 *)setup_malloc(f, c->entries); + + if (!lengths) return error(f, VORBIS_outofmem); + + if (ordered) { + int current_entry = 0; + int current_length = get_bits(f, 5) + 1; + while (current_entry < c->entries) { + int limit = c->entries - current_entry; + int n = get_bits(f, ilog(limit)); + if (current_entry + n >(int) c->entries) { return error(f, VORBIS_invalid_setup); } + memset(lengths + current_entry, current_length, n); + current_entry += n; + ++current_length; + } + } + else { + for (j = 0; j < c->entries; ++j) { + int present = c->sparse ? get_bits(f, 1) : 1; + if (present) { + lengths[j] = get_bits(f, 5) + 1; + ++total; + if (lengths[j] == 32) + return error(f, VORBIS_invalid_setup); + } + else { + lengths[j] = NO_CODE; + } } - } - } - - if (c->sparse && total >= c->entries >> 2) { - // convert sparse items to non-sparse! - if (c->entries > (int) f->setup_temp_memory_required) - f->setup_temp_memory_required = c->entries; - - c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); - if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); - memcpy(c->codeword_lengths, lengths, c->entries); - setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! - lengths = c->codeword_lengths; - c->sparse = 0; - } - - // compute the size of the sorted tables - if (c->sparse) { - sorted_count = total; - } else { - sorted_count = 0; - #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH - for (j=0; j < c->entries; ++j) - if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) - ++sorted_count; - #endif - } - - c->sorted_entries = sorted_count; - values = NULL; - - CHECK(f); - if (!c->sparse) { - c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); - if (!c->codewords) return error(f, VORBIS_outofmem); - } else { - unsigned int size; - if (c->sorted_entries) { - c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); - if (!c->codeword_lengths) return error(f, VORBIS_outofmem); - c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); + } + + if (c->sparse && total >= c->entries >> 2) { + // convert sparse items to non-sparse! + if (c->entries > (int)f->setup_temp_memory_required) + f->setup_temp_memory_required = c->entries; + + c->codeword_lengths = (uint8 *)setup_malloc(f, c->entries); + if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); + memcpy(c->codeword_lengths, lengths, c->entries); + setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! + lengths = c->codeword_lengths; + c->sparse = 0; + } + + // compute the size of the sorted tables + if (c->sparse) { + sorted_count = total; + } + else { + sorted_count = 0; +#ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH + for (j = 0; j < c->entries; ++j) + if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) + ++sorted_count; +#endif + } + + c->sorted_entries = sorted_count; + values = NULL; + + CHECK(f); + if (!c->sparse) { + c->codewords = (uint32 *)setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); - values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); - if (!values) return error(f, VORBIS_outofmem); - } - size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; - if (size > f->setup_temp_memory_required) - f->setup_temp_memory_required = size; - } - - if (!compute_codewords(c, lengths, c->entries, values)) { - if (c->sparse) setup_temp_free(f, values, 0); - return error(f, VORBIS_invalid_setup); - } - - if (c->sorted_entries) { - // allocate an extra slot for sentinels - c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); - if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); - // allocate an extra slot at the front so that c->sorted_values[-1] is defined - // so that we can catch that case without an extra if - c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); - if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); - ++c->sorted_values; - c->sorted_values[-1] = -1; - compute_sorted_huffman(c, lengths, values); - } - - if (c->sparse) { - setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); - setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); - setup_temp_free(f, lengths, c->entries); - c->codewords = NULL; - } - - compute_accelerated_huffman(c); - - CHECK(f); - c->lookup_type = get_bits(f, 4); - if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); - if (c->lookup_type > 0) { - uint16 *mults; - c->minimum_value = float32_unpack(get_bits(f, 32)); - c->delta_value = float32_unpack(get_bits(f, 32)); - c->value_bits = get_bits(f, 4)+1; - c->sequence_p = get_bits(f,1); - if (c->lookup_type == 1) { - c->lookup_values = lookup1_values(c->entries, c->dimensions); - } else { - c->lookup_values = c->entries * c->dimensions; - } - if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); - mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); - if (mults == NULL) return error(f, VORBIS_outofmem); - for (j=0; j < (int) c->lookup_values; ++j) { - int q = get_bits(f, c->value_bits); - if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } - mults[j] = q; - } + } + else { + unsigned int size; + if (c->sorted_entries) { + c->codeword_lengths = (uint8 *)setup_malloc(f, c->sorted_entries); + if (!c->codeword_lengths) return error(f, VORBIS_outofmem); + c->codewords = (uint32 *)setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); + if (!c->codewords) return error(f, VORBIS_outofmem); + values = (uint32 *)setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); + if (!values) return error(f, VORBIS_outofmem); + } + size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; + if (size > f->setup_temp_memory_required) + f->setup_temp_memory_required = size; + } + + if (!compute_codewords(c, lengths, c->entries, values)) { + if (c->sparse) setup_temp_free(f, values, 0); + return error(f, VORBIS_invalid_setup); + } + + if (c->sorted_entries) { + // allocate an extra slot for sentinels + c->sorted_codewords = (uint32 *)setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries + 1)); + if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); + // allocate an extra slot at the front so that c->sorted_values[-1] is defined + // so that we can catch that case without an extra if + c->sorted_values = (int *)setup_malloc(f, sizeof(*c->sorted_values) * (c->sorted_entries + 1)); + if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); + ++c->sorted_values; + c->sorted_values[-1] = -1; + compute_sorted_huffman(c, lengths, values); + } + + if (c->sparse) { + setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); + setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); + setup_temp_free(f, lengths, c->entries); + c->codewords = NULL; + } + + compute_accelerated_huffman(c); + + CHECK(f); + c->lookup_type = get_bits(f, 4); + if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); + if (c->lookup_type > 0) { + uint16 *mults; + c->minimum_value = float32_unpack(get_bits(f, 32)); + c->delta_value = float32_unpack(get_bits(f, 32)); + c->value_bits = get_bits(f, 4) + 1; + c->sequence_p = get_bits(f, 1); + if (c->lookup_type == 1) { + c->lookup_values = lookup1_values(c->entries, c->dimensions); + } + else { + c->lookup_values = c->entries * c->dimensions; + } + if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); + mults = (uint16 *)setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); + if (mults == NULL) return error(f, VORBIS_outofmem); + for (j = 0; j < (int)c->lookup_values; ++j) { + int q = get_bits(f, c->value_bits); + if (q == EOP) { setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } + mults[j] = q; + } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK - if (c->lookup_type == 1) { - int len, sparse = c->sparse; - float last=0; - // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop - if (sparse) { - if (c->sorted_entries == 0) goto skip; - c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); - } else - c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); - if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } - len = sparse ? c->sorted_entries : c->entries; - for (j=0; j < len; ++j) { - unsigned int z = sparse ? c->sorted_values[j] : j; - unsigned int div=1; - for (k=0; k < c->dimensions; ++k) { - int off = (z / div) % c->lookup_values; - float val = mults[off]; - val = mults[off]*c->delta_value + c->minimum_value + last; - c->multiplicands[j*c->dimensions + k] = val; - if (c->sequence_p) - last = val; - if (k+1 < c->dimensions) { - if (div > UINT_MAX / (unsigned int) c->lookup_values) { - setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); - return error(f, VORBIS_invalid_setup); - } - div *= c->lookup_values; - } - } + if (c->lookup_type == 1) { + int len, sparse = c->sparse; + float last = 0; + // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop + if (sparse) { + if (c->sorted_entries == 0) goto skip; + c->multiplicands = (codetype *)setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); + } + else + c->multiplicands = (codetype *)setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); + if (c->multiplicands == NULL) { setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } + len = sparse ? c->sorted_entries : c->entries; + for (j = 0; j < len; ++j) { + unsigned int z = sparse ? c->sorted_values[j] : j; + unsigned int div = 1; + for (k = 0; k < c->dimensions; ++k) { + int off = (z / div) % c->lookup_values; + float val = mults[off]; + val = mults[off] * c->delta_value + c->minimum_value + last; + c->multiplicands[j*c->dimensions + k] = val; + if (c->sequence_p) + last = val; + if (k + 1 < c->dimensions) { + if (div > UINT_MAX / (unsigned int)c->lookup_values) { + setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); + return error(f, VORBIS_invalid_setup); + } + div *= c->lookup_values; + } + } + } + c->lookup_type = 2; } - c->lookup_type = 2; - } - else + else #endif - { - float last=0; - CHECK(f); - c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); - if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } - for (j=0; j < (int) c->lookup_values; ++j) { - float val = mults[j] * c->delta_value + c->minimum_value + last; - c->multiplicands[j] = val; - if (c->sequence_p) - last = val; + { + float last = 0; + CHECK(f); + c->multiplicands = (codetype *)setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); + if (c->multiplicands == NULL) { setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } + for (j = 0; j < (int)c->lookup_values; ++j) { + float val = mults[j] * c->delta_value + c->minimum_value + last; + c->multiplicands[j] = val; + if (c->sequence_p) + last = val; + } } - } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK - skip:; + skip : ; #endif - setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); - - CHECK(f); - } - CHECK(f); - } - - // time domain transfers (notused) - - x = get_bits(f, 6) + 1; - for (i=0; i < x; ++i) { - uint32 z = get_bits(f, 16); - if (z != 0) return error(f, VORBIS_invalid_setup); - } - - // Floors - f->floor_count = get_bits(f, 6)+1; - f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); - if (f->floor_config == NULL) return error(f, VORBIS_outofmem); - for (i=0; i < f->floor_count; ++i) { - f->floor_types[i] = get_bits(f, 16); - if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); - if (f->floor_types[i] == 0) { - Floor0 *g = &f->floor_config[i].floor0; - g->order = get_bits(f,8); - g->rate = get_bits(f,16); - g->bark_map_size = get_bits(f,16); - g->amplitude_bits = get_bits(f,6); - g->amplitude_offset = get_bits(f,8); - g->number_of_books = get_bits(f,4) + 1; - for (j=0; j < g->number_of_books; ++j) - g->book_list[j] = get_bits(f,8); - return error(f, VORBIS_feature_not_supported); - } else { - stbv__floor_ordering p[31*8+2]; - Floor1 *g = &f->floor_config[i].floor1; - int max_class = -1; - g->partitions = get_bits(f, 5); - for (j=0; j < g->partitions; ++j) { - g->partition_class_list[j] = get_bits(f, 4); - if (g->partition_class_list[j] > max_class) - max_class = g->partition_class_list[j]; - } - for (j=0; j <= max_class; ++j) { - g->class_dimensions[j] = get_bits(f, 3)+1; - g->class_subclasses[j] = get_bits(f, 2); - if (g->class_subclasses[j]) { - g->class_masterbooks[j] = get_bits(f, 8); - if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); + setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); + + CHECK(f); + } + CHECK(f); + } + + // time domain transfers (notused) + + x = get_bits(f, 6) + 1; + for (i = 0; i < x; ++i) { + uint32 z = get_bits(f, 16); + if (z != 0) return error(f, VORBIS_invalid_setup); + } + + // Floors + f->floor_count = get_bits(f, 6) + 1; + f->floor_config = (Floor *)setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); + if (f->floor_config == NULL) return error(f, VORBIS_outofmem); + for (i = 0; i < f->floor_count; ++i) { + f->floor_types[i] = get_bits(f, 16); + if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); + if (f->floor_types[i] == 0) { + Floor0 *g = &f->floor_config[i].floor0; + g->order = get_bits(f, 8); + g->rate = get_bits(f, 16); + g->bark_map_size = get_bits(f, 16); + g->amplitude_bits = get_bits(f, 6); + g->amplitude_offset = get_bits(f, 8); + g->number_of_books = get_bits(f, 4) + 1; + for (j = 0; j < g->number_of_books; ++j) + g->book_list[j] = get_bits(f, 8); + return error(f, VORBIS_feature_not_supported); + } + else { + stbv__floor_ordering p[31 * 8 + 2]; + Floor1 *g = &f->floor_config[i].floor1; + int max_class = -1; + g->partitions = get_bits(f, 5); + for (j = 0; j < g->partitions; ++j) { + g->partition_class_list[j] = get_bits(f, 4); + if (g->partition_class_list[j] > max_class) + max_class = g->partition_class_list[j]; } - for (k=0; k < 1 << g->class_subclasses[j]; ++k) { - g->subclass_books[j][k] = get_bits(f,8)-1; - if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); + for (j = 0; j <= max_class; ++j) { + g->class_dimensions[j] = get_bits(f, 3) + 1; + g->class_subclasses[j] = get_bits(f, 2); + if (g->class_subclasses[j]) { + g->class_masterbooks[j] = get_bits(f, 8); + if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); + } + for (k = 0; k < 1 << g->class_subclasses[j]; ++k) { + g->subclass_books[j][k] = get_bits(f, 8) - 1; + if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); + } } - } - g->floor1_multiplier = get_bits(f,2)+1; - g->rangebits = get_bits(f,4); - g->Xlist[0] = 0; - g->Xlist[1] = 1 << g->rangebits; - g->values = 2; - for (j=0; j < g->partitions; ++j) { - int c = g->partition_class_list[j]; - for (k=0; k < g->class_dimensions[c]; ++k) { - g->Xlist[g->values] = get_bits(f, g->rangebits); - ++g->values; + g->floor1_multiplier = get_bits(f, 2) + 1; + g->rangebits = get_bits(f, 4); + g->Xlist[0] = 0; + g->Xlist[1] = 1 << g->rangebits; + g->values = 2; + for (j = 0; j < g->partitions; ++j) { + int c = g->partition_class_list[j]; + for (k = 0; k < g->class_dimensions[c]; ++k) { + g->Xlist[g->values] = get_bits(f, g->rangebits); + ++g->values; + } } - } - // precompute the sorting - for (j=0; j < g->values; ++j) { - p[j].x = g->Xlist[j]; - p[j].id = j; - } - qsort(p, g->values, sizeof(p[0]), point_compare); - for (j=0; j < g->values; ++j) - g->sorted_order[j] = (uint8) p[j].id; - // precompute the neighbors - for (j=2; j < g->values; ++j) { - int low,hi; - neighbors(g->Xlist, j, &low,&hi); - g->neighbors[j][0] = low; - g->neighbors[j][1] = hi; - } - - if (g->values > longest_floorlist) - longest_floorlist = g->values; - } - } - - // Residue - f->residue_count = get_bits(f, 6)+1; - f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); - if (f->residue_config == NULL) return error(f, VORBIS_outofmem); - memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); - for (i=0; i < f->residue_count; ++i) { - uint8 residue_cascade[64]; - Residue *r = f->residue_config+i; - f->residue_types[i] = get_bits(f, 16); - if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); - r->begin = get_bits(f, 24); - r->end = get_bits(f, 24); - if (r->end < r->begin) return error(f, VORBIS_invalid_setup); - r->part_size = get_bits(f,24)+1; - r->classifications = get_bits(f,6)+1; - r->classbook = get_bits(f,8); - if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); - for (j=0; j < r->classifications; ++j) { - uint8 high_bits=0; - uint8 low_bits=get_bits(f,3); - if (get_bits(f,1)) - high_bits = get_bits(f,5); - residue_cascade[j] = high_bits*8 + low_bits; - } - r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); - if (r->residue_books == NULL) return error(f, VORBIS_outofmem); - for (j=0; j < r->classifications; ++j) { - for (k=0; k < 8; ++k) { - if (residue_cascade[j] & (1 << k)) { - r->residue_books[j][k] = get_bits(f, 8); - if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); - } else { - r->residue_books[j][k] = -1; + // precompute the sorting + for (j = 0; j < g->values; ++j) { + p[j].x = g->Xlist[j]; + p[j].id = j; + } + qsort(p, g->values, sizeof(p[0]), point_compare); + for (j = 0; j < g->values; ++j) + g->sorted_order[j] = (uint8)p[j].id; + // precompute the neighbors + for (j = 2; j < g->values; ++j) { + int low, hi; + neighbors(g->Xlist, j, &low, &hi); + g->neighbors[j][0] = low; + g->neighbors[j][1] = hi; } - } - } - // precompute the classifications[] array to avoid inner-loop mod/divide - // call it 'classdata' since we already have r->classifications - r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); - if (!r->classdata) return error(f, VORBIS_outofmem); - memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); - for (j=0; j < f->codebooks[r->classbook].entries; ++j) { - int classwords = f->codebooks[r->classbook].dimensions; - int temp = j; - r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); - if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); - for (k=classwords-1; k >= 0; --k) { - r->classdata[j][k] = temp % r->classifications; - temp /= r->classifications; - } - } - } - - f->mapping_count = get_bits(f,6)+1; - f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); - if (f->mapping == NULL) return error(f, VORBIS_outofmem); - memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); - for (i=0; i < f->mapping_count; ++i) { - Mapping *m = f->mapping + i; - int mapping_type = get_bits(f,16); - if (mapping_type != 0) return error(f, VORBIS_invalid_setup); - m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); - if (m->chan == NULL) return error(f, VORBIS_outofmem); - if (get_bits(f,1)) - m->submaps = get_bits(f,4)+1; - else - m->submaps = 1; - if (m->submaps > max_submaps) - max_submaps = m->submaps; - if (get_bits(f,1)) { - m->coupling_steps = get_bits(f,8)+1; - for (k=0; k < m->coupling_steps; ++k) { - m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); - m->chan[k].angle = get_bits(f, ilog(f->channels-1)); - if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); - if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); - if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); - } - } else - m->coupling_steps = 0; - - // reserved field - if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); - if (m->submaps > 1) { - for (j=0; j < f->channels; ++j) { - m->chan[j].mux = get_bits(f, 4); - if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); - } - } else - // @SPECIFICATION: this case is missing from the spec - for (j=0; j < f->channels; ++j) - m->chan[j].mux = 0; - - for (j=0; j < m->submaps; ++j) { - get_bits(f,8); // discard - m->submap_floor[j] = get_bits(f,8); - m->submap_residue[j] = get_bits(f,8); - if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); - if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); - } - } - - // Modes - f->mode_count = get_bits(f, 6)+1; - for (i=0; i < f->mode_count; ++i) { - Mode *m = f->mode_config+i; - m->blockflag = get_bits(f,1); - m->windowtype = get_bits(f,16); - m->transformtype = get_bits(f,16); - m->mapping = get_bits(f,8); - if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); - if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); - if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); - } - - flush_packet(f); - - f->previous_length = 0; - for (i=0; i < f->channels; ++i) { - f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); - f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); - f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); - if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); - #ifdef STB_VORBIS_NO_DEFER_FLOOR - f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); - if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); - #endif - } + if (g->values > longest_floorlist) + longest_floorlist = g->values; + } + } + + // Residue + f->residue_count = get_bits(f, 6) + 1; + f->residue_config = (Residue *)setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); + if (f->residue_config == NULL) return error(f, VORBIS_outofmem); + memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); + for (i = 0; i < f->residue_count; ++i) { + uint8 residue_cascade[64]; + Residue *r = f->residue_config + i; + f->residue_types[i] = get_bits(f, 16); + if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); + r->begin = get_bits(f, 24); + r->end = get_bits(f, 24); + if (r->end < r->begin) return error(f, VORBIS_invalid_setup); + r->part_size = get_bits(f, 24) + 1; + r->classifications = get_bits(f, 6) + 1; + r->classbook = get_bits(f, 8); + if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); + for (j = 0; j < r->classifications; ++j) { + uint8 high_bits = 0; + uint8 low_bits = get_bits(f, 3); + if (get_bits(f, 1)) + high_bits = get_bits(f, 5); + residue_cascade[j] = high_bits * 8 + low_bits; + } + r->residue_books = (short(*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); + if (r->residue_books == NULL) return error(f, VORBIS_outofmem); + for (j = 0; j < r->classifications; ++j) { + for (k = 0; k < 8; ++k) { + if (residue_cascade[j] & (1 << k)) { + r->residue_books[j][k] = get_bits(f, 8); + if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); + } + else { + r->residue_books[j][k] = -1; + } + } + } + // precompute the classifications[] array to avoid inner-loop mod/divide + // call it 'classdata' since we already have r->classifications + r->classdata = (uint8 **)setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); + if (!r->classdata) return error(f, VORBIS_outofmem); + memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); + for (j = 0; j < f->codebooks[r->classbook].entries; ++j) { + int classwords = f->codebooks[r->classbook].dimensions; + int temp = j; + r->classdata[j] = (uint8 *)setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); + if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); + for (k = classwords - 1; k >= 0; --k) { + r->classdata[j][k] = temp % r->classifications; + temp /= r->classifications; + } + } + } + + f->mapping_count = get_bits(f, 6) + 1; + f->mapping = (Mapping *)setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); + if (f->mapping == NULL) return error(f, VORBIS_outofmem); + memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); + for (i = 0; i < f->mapping_count; ++i) { + Mapping *m = f->mapping + i; + int mapping_type = get_bits(f, 16); + if (mapping_type != 0) return error(f, VORBIS_invalid_setup); + m->chan = (MappingChannel *)setup_malloc(f, f->channels * sizeof(*m->chan)); + if (m->chan == NULL) return error(f, VORBIS_outofmem); + if (get_bits(f, 1)) + m->submaps = get_bits(f, 4) + 1; + else + m->submaps = 1; + if (m->submaps > max_submaps) + max_submaps = m->submaps; + if (get_bits(f, 1)) { + m->coupling_steps = get_bits(f, 8) + 1; + for (k = 0; k < m->coupling_steps; ++k) { + m->chan[k].magnitude = get_bits(f, ilog(f->channels - 1)); + m->chan[k].angle = get_bits(f, ilog(f->channels - 1)); + if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); + if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); + if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); + } + } + else + m->coupling_steps = 0; + + // reserved field + if (get_bits(f, 2)) return error(f, VORBIS_invalid_setup); + if (m->submaps > 1) { + for (j = 0; j < f->channels; ++j) { + m->chan[j].mux = get_bits(f, 4); + if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); + } + } + else + // @SPECIFICATION: this case is missing from the spec + for (j = 0; j < f->channels; ++j) + m->chan[j].mux = 0; + + for (j = 0; j < m->submaps; ++j) { + get_bits(f, 8); // discard + m->submap_floor[j] = get_bits(f, 8); + m->submap_residue[j] = get_bits(f, 8); + if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); + if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); + } + } + + // Modes + f->mode_count = get_bits(f, 6) + 1; + for (i = 0; i < f->mode_count; ++i) { + Mode *m = f->mode_config + i; + m->blockflag = get_bits(f, 1); + m->windowtype = get_bits(f, 16); + m->transformtype = get_bits(f, 16); + m->mapping = get_bits(f, 8); + if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); + if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); + if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); + } + + flush_packet(f); + + f->previous_length = 0; + + for (i = 0; i < f->channels; ++i) { + f->channel_buffers[i] = (float *)setup_malloc(f, sizeof(float) * f->blocksize_1); + f->previous_window[i] = (float *)setup_malloc(f, sizeof(float) * f->blocksize_1 / 2); + f->finalY[i] = (int16 *)setup_malloc(f, sizeof(int16) * longest_floorlist); + if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); + memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); +#ifdef STB_VORBIS_NO_DEFER_FLOOR + f->floor_buffers[i] = (float *)setup_malloc(f, sizeof(float) * f->blocksize_1 / 2); + if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); +#endif + } - if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; - if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; - f->blocksize[0] = f->blocksize_0; - f->blocksize[1] = f->blocksize_1; + if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; + if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; + f->blocksize[0] = f->blocksize_0; + f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE - if (integer_divide_table[1][1]==0) - for (i=0; i < DIVTAB_NUMER; ++i) - for (j=1; j < DIVTAB_DENOM; ++j) - integer_divide_table[i][j] = i / j; + if (integer_divide_table[1][1] == 0) + for (i = 0; i < DIVTAB_NUMER; ++i) + for (j = 1; j < DIVTAB_DENOM; ++j) + integer_divide_table[i][j] = i / j; #endif - // compute how much temporary memory is needed - - // 1. - { - uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); - uint32 classify_mem; - int i,max_part_read=0; - for (i=0; i < f->residue_count; ++i) { - Residue *r = f->residue_config + i; - int n_read = r->end - r->begin; - int part_read = n_read / r->part_size; - if (part_read > max_part_read) - max_part_read = part_read; - } - #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE - classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); - #else - classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); - #endif - - f->temp_memory_required = classify_mem; - if (imdct_mem > f->temp_memory_required) - f->temp_memory_required = imdct_mem; - } + // compute how much temporary memory is needed + + // 1. + { + uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); + uint32 classify_mem; + int i, max_part_read = 0; + for (i = 0; i < f->residue_count; ++i) { + Residue *r = f->residue_config + i; + unsigned int actual_size = f->blocksize_1 / 2; + unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; + unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; + int n_read = limit_r_end - limit_r_begin; + int part_read = n_read / r->part_size; + if (part_read > max_part_read) + max_part_read = part_read; + } +#ifndef STB_VORBIS_DIVIDES_IN_RESIDUE + classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); +#else + classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); +#endif - f->first_decode = TRUE; + // maximum reasonable partition size is f->blocksize_1 - if (f->alloc.alloc_buffer) { - assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); - // check if there's enough temp memory so we don't error later - if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) - return error(f, VORBIS_outofmem); - } + f->temp_memory_required = classify_mem; + if (imdct_mem > f->temp_memory_required) + f->temp_memory_required = imdct_mem; + } + + f->first_decode = TRUE; - f->first_audio_page_offset = stb_vorbis_get_file_offset(f); + if (f->alloc.alloc_buffer) { + assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); + // check if there's enough temp memory so we don't error later + if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned)f->temp_offset) + return error(f, VORBIS_outofmem); + } - return TRUE; + f->first_audio_page_offset = stb_vorbis_get_file_offset(f); + + return TRUE; } static void vorbis_deinit(stb_vorbis *p) { - int i,j; - if (p->residue_config) { - for (i=0; i < p->residue_count; ++i) { - Residue *r = p->residue_config+i; - if (r->classdata) { - for (j=0; j < p->codebooks[r->classbook].entries; ++j) - setup_free(p, r->classdata[j]); - setup_free(p, r->classdata); - } - setup_free(p, r->residue_books); - } - } - - if (p->codebooks) { - CHECK(p); - for (i=0; i < p->codebook_count; ++i) { - Codebook *c = p->codebooks + i; - setup_free(p, c->codeword_lengths); - setup_free(p, c->multiplicands); - setup_free(p, c->codewords); - setup_free(p, c->sorted_codewords); - // c->sorted_values[-1] is the first entry in the array - setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); - } - setup_free(p, p->codebooks); - } - setup_free(p, p->floor_config); - setup_free(p, p->residue_config); - if (p->mapping) { - for (i=0; i < p->mapping_count; ++i) - setup_free(p, p->mapping[i].chan); - setup_free(p, p->mapping); - } - CHECK(p); - for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { - setup_free(p, p->channel_buffers[i]); - setup_free(p, p->previous_window[i]); - #ifdef STB_VORBIS_NO_DEFER_FLOOR - setup_free(p, p->floor_buffers[i]); - #endif - setup_free(p, p->finalY[i]); - } - for (i=0; i < 2; ++i) { - setup_free(p, p->A[i]); - setup_free(p, p->B[i]); - setup_free(p, p->C[i]); - setup_free(p, p->window[i]); - setup_free(p, p->bit_reverse[i]); - } - #ifndef STB_VORBIS_NO_STDIO - if (p->close_on_free) fclose(p->f); - #endif + int i, j; + if (p->residue_config) { + for (i = 0; i < p->residue_count; ++i) { + Residue *r = p->residue_config + i; + if (r->classdata) { + for (j = 0; j < p->codebooks[r->classbook].entries; ++j) + setup_free(p, r->classdata[j]); + setup_free(p, r->classdata); + } + setup_free(p, r->residue_books); + } + } + + if (p->codebooks) { + CHECK(p); + for (i = 0; i < p->codebook_count; ++i) { + Codebook *c = p->codebooks + i; + setup_free(p, c->codeword_lengths); + setup_free(p, c->multiplicands); + setup_free(p, c->codewords); + setup_free(p, c->sorted_codewords); + // c->sorted_values[-1] is the first entry in the array + setup_free(p, c->sorted_values ? c->sorted_values - 1 : NULL); + } + setup_free(p, p->codebooks); + } + setup_free(p, p->floor_config); + setup_free(p, p->residue_config); + if (p->mapping) { + for (i = 0; i < p->mapping_count; ++i) + setup_free(p, p->mapping[i].chan); + setup_free(p, p->mapping); + } + CHECK(p); + for (i = 0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { + setup_free(p, p->channel_buffers[i]); + setup_free(p, p->previous_window[i]); +#ifdef STB_VORBIS_NO_DEFER_FLOOR + setup_free(p, p->floor_buffers[i]); +#endif + setup_free(p, p->finalY[i]); + } + for (i = 0; i < 2; ++i) { + setup_free(p, p->A[i]); + setup_free(p, p->B[i]); + setup_free(p, p->C[i]); + setup_free(p, p->window[i]); + setup_free(p, p->bit_reverse[i]); + } +#ifndef STB_VORBIS_NO_STDIO + if (p->close_on_free) fclose(p->f); +#endif } void stb_vorbis_close(stb_vorbis *p) { - if (p == NULL) return; - vorbis_deinit(p); - setup_free(p,p); + if (p == NULL) return; + vorbis_deinit(p); + setup_free(p, p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { - memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start - if (z) { - p->alloc = *z; - p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; - p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; - } - p->eof = 0; - p->error = VORBIS__no_error; - p->stream = NULL; - p->codebooks = NULL; - p->page_crc_tests = -1; - #ifndef STB_VORBIS_NO_STDIO - p->close_on_free = FALSE; - p->f = NULL; - #endif + memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start + if (z) { + p->alloc = *z; + p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes + 3) & ~3; + p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; + } + p->eof = 0; + p->error = VORBIS__no_error; + p->stream = NULL; + p->codebooks = NULL; + p->page_crc_tests = -1; +#ifndef STB_VORBIS_NO_STDIO + p->close_on_free = FALSE; + p->f = NULL; +#endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { - if (f->current_loc_valid) - return f->current_loc; - else - return -1; + if (f->current_loc_valid) + return f->current_loc; + else + return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { - stb_vorbis_info d; - d.channels = f->channels; - d.sample_rate = f->sample_rate; - d.setup_memory_required = f->setup_memory_required; - d.setup_temp_memory_required = f->setup_temp_memory_required; - d.temp_memory_required = f->temp_memory_required; - d.max_frame_size = f->blocksize_1 >> 1; - return d; + stb_vorbis_info d; + d.channels = f->channels; + d.sample_rate = f->sample_rate; + d.setup_memory_required = f->setup_memory_required; + d.setup_temp_memory_required = f->setup_temp_memory_required; + d.temp_memory_required = f->temp_memory_required; + d.max_frame_size = f->blocksize_1 >> 1; + return d; } int stb_vorbis_get_error(stb_vorbis *f) { - int e = f->error; - f->error = VORBIS__no_error; - return e; + int e = f->error; + f->error = VORBIS__no_error; + return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { - stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); - return p; + stb_vorbis *p = (stb_vorbis *)setup_malloc(f, sizeof(*p)); + return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { - f->previous_length = 0; - f->page_crc_tests = 0; - f->discard_samples_deferred = 0; - f->current_loc_valid = FALSE; - f->first_decode = FALSE; - f->samples_output = 0; - f->channel_buffer_start = 0; - f->channel_buffer_end = 0; + f->previous_length = 0; + f->page_crc_tests = 0; + f->discard_samples_deferred = 0; + f->current_loc_valid = FALSE; + f->first_decode = FALSE; + f->samples_output = 0; + f->channel_buffer_start = 0; + f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { - int i,n; - for (i=0; i < f->page_crc_tests; ++i) - f->scan[i].bytes_done = 0; - - // if we have room for more scans, search for them first, because - // they may cause us to stop early if their header is incomplete - if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { - if (data_len < 4) return 0; - data_len -= 3; // need to look for 4-byte sequence, so don't miss - // one that straddles a boundary - for (i=0; i < data_len; ++i) { - if (data[i] == 0x4f) { - if (0==memcmp(data+i, ogg_page_header, 4)) { - int j,len; - uint32 crc; - // make sure we have the whole page header - if (i+26 >= data_len || i+27+data[i+26] >= data_len) { - // only read up to this page start, so hopefully we'll - // have the whole page header start next time - data_len = i; - break; - } - // ok, we have it all; compute the length of the page - len = 27 + data[i+26]; - for (j=0; j < data[i+26]; ++j) - len += data[i+27+j]; - // scan everything up to the embedded crc (which we must 0) - crc = 0; - for (j=0; j < 22; ++j) - crc = crc32_update(crc, data[i+j]); - // now process 4 0-bytes - for ( ; j < 26; ++j) - crc = crc32_update(crc, 0); - // len is the total number of bytes we need to scan - n = f->page_crc_tests++; - f->scan[n].bytes_left = len-j; - f->scan[n].crc_so_far = crc; - f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); - // if the last frame on a page is continued to the next, then - // we can't recover the sample_loc immediately - if (data[i+27+data[i+26]-1] == 255) - f->scan[n].sample_loc = ~0; - else - f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); - f->scan[n].bytes_done = i+j; - if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) - break; - // keep going if we still have room for more + int i, n; + for (i = 0; i < f->page_crc_tests; ++i) + f->scan[i].bytes_done = 0; + + // if we have room for more scans, search for them first, because + // they may cause us to stop early if their header is incomplete + if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { + if (data_len < 4) return 0; + data_len -= 3; // need to look for 4-byte sequence, so don't miss + // one that straddles a boundary + for (i = 0; i < data_len; ++i) { + if (data[i] == 0x4f) { + if (0 == memcmp(data + i, ogg_page_header, 4)) { + int j, len; + uint32 crc; + // make sure we have the whole page header + if (i + 26 >= data_len || i + 27 + data[i + 26] >= data_len) { + // only read up to this page start, so hopefully we'll + // have the whole page header start next time + data_len = i; + break; + } + // ok, we have it all; compute the length of the page + len = 27 + data[i + 26]; + for (j = 0; j < data[i + 26]; ++j) + len += data[i + 27 + j]; + // scan everything up to the embedded crc (which we must 0) + crc = 0; + for (j = 0; j < 22; ++j) + crc = crc32_update(crc, data[i + j]); + // now process 4 0-bytes + for (; j < 26; ++j) + crc = crc32_update(crc, 0); + // len is the total number of bytes we need to scan + n = f->page_crc_tests++; + f->scan[n].bytes_left = len - j; + f->scan[n].crc_so_far = crc; + f->scan[n].goal_crc = data[i + 22] + (data[i + 23] << 8) + (data[i + 24] << 16) + (data[i + 25] << 24); + // if the last frame on a page is continued to the next, then + // we can't recover the sample_loc immediately + if (data[i + 27 + data[i + 26] - 1] == 255) + f->scan[n].sample_loc = ~0; + else + f->scan[n].sample_loc = data[i + 6] + (data[i + 7] << 8) + (data[i + 8] << 16) + (data[i + 9] << 24); + f->scan[n].bytes_done = i + j; + if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) + break; + // keep going if we still have room for more + } } - } - } - } - - for (i=0; i < f->page_crc_tests;) { - uint32 crc; - int j; - int n = f->scan[i].bytes_done; - int m = f->scan[i].bytes_left; - if (m > data_len - n) m = data_len - n; - // m is the bytes to scan in the current chunk - crc = f->scan[i].crc_so_far; - for (j=0; j < m; ++j) - crc = crc32_update(crc, data[n+j]); - f->scan[i].bytes_left -= m; - f->scan[i].crc_so_far = crc; - if (f->scan[i].bytes_left == 0) { - // does it match? - if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { - // Houston, we have page - data_len = n+m; // consumption amount is wherever that scan ended - f->page_crc_tests = -1; // drop out of page scan mode - f->previous_length = 0; // decode-but-don't-output one frame - f->next_seg = -1; // start a new page - f->current_loc = f->scan[i].sample_loc; // set the current sample location - // to the amount we'd have decoded had we decoded this page - f->current_loc_valid = f->current_loc != ~0U; - return data_len; - } - // delete entry - f->scan[i] = f->scan[--f->page_crc_tests]; - } else { - ++i; - } - } - - return data_len; + } + } + + for (i = 0; i < f->page_crc_tests;) { + uint32 crc; + int j; + int n = f->scan[i].bytes_done; + int m = f->scan[i].bytes_left; + if (m > data_len - n) m = data_len - n; + // m is the bytes to scan in the current chunk + crc = f->scan[i].crc_so_far; + for (j = 0; j < m; ++j) + crc = crc32_update(crc, data[n + j]); + f->scan[i].bytes_left -= m; + f->scan[i].crc_so_far = crc; + if (f->scan[i].bytes_left == 0) { + // does it match? + if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { + // Houston, we have page + data_len = n + m; // consumption amount is wherever that scan ended + f->page_crc_tests = -1; // drop out of page scan mode + f->previous_length = 0; // decode-but-don't-output one frame + f->next_seg = -1; // start a new page + f->current_loc = f->scan[i].sample_loc; // set the current sample location + // to the amount we'd have decoded had we decoded this page + f->current_loc_valid = f->current_loc != ~0U; + return data_len; + } + // delete entry + f->scan[i] = f->scan[--f->page_crc_tests]; + } + else { + ++i; + } + } + + return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( - stb_vorbis *f, // the file we're decoding - const uint8 *data, int data_len, // the memory available for decoding - int *channels, // place to write number of float * buffers - float ***output, // place to write float ** array of float * buffers - int *samples // place to write number of output samples - ) -{ - int i; - int len,right,left; - - if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); - - if (f->page_crc_tests >= 0) { - *samples = 0; - return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); - } - - f->stream = (uint8 *) data; - f->stream_end = (uint8 *) data + data_len; - f->error = VORBIS__no_error; - - // check that we have the entire packet in memory - if (!is_whole_packet_present(f, FALSE)) { - *samples = 0; - return 0; - } - - if (!vorbis_decode_packet(f, &len, &left, &right)) { - // save the actual error we encountered - enum STBVorbisError error = f->error; - if (error == VORBIS_bad_packet_type) { - // flush and resynch - f->error = VORBIS__no_error; - while (get8_packet(f) != EOP) - if (f->eof) break; - *samples = 0; - return (int) (f->stream - data); - } - if (error == VORBIS_continued_packet_flag_invalid) { - if (f->previous_length == 0) { - // we may be resynching, in which case it's ok to hit one - // of these; just discard the packet + stb_vorbis *f, // the file we're decoding + const uint8 *data, int data_len, // the memory available for decoding + int *channels, // place to write number of float * buffers + float ***output, // place to write float ** array of float * buffers + int *samples // place to write number of output samples +) +{ + int i; + int len, right, left; + + if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); + + if (f->page_crc_tests >= 0) { + *samples = 0; + return vorbis_search_for_page_pushdata(f, (uint8 *)data, data_len); + } + + f->stream = (uint8 *)data; + f->stream_end = (uint8 *)data + data_len; + f->error = VORBIS__no_error; + + // check that we have the entire packet in memory + if (!is_whole_packet_present(f, FALSE)) { + *samples = 0; + return 0; + } + + if (!vorbis_decode_packet(f, &len, &left, &right)) { + // save the actual error we encountered + enum STBVorbisError error = f->error; + if (error == VORBIS_bad_packet_type) { + // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) - if (f->eof) break; + if (f->eof) break; *samples = 0; - return (int) (f->stream - data); - } - } - // if we get an error while parsing, what to do? - // well, it DEFINITELY won't work to continue from where we are! - stb_vorbis_flush_pushdata(f); - // restore the error that actually made us bail - f->error = error; - *samples = 0; - return 1; - } - - // success! - len = vorbis_finish_frame(f, len, left, right); - for (i=0; i < f->channels; ++i) - f->outputs[i] = f->channel_buffers[i] + left; - - if (channels) *channels = f->channels; - *samples = len; - *output = f->outputs; - return (int) (f->stream - data); + return (int)(f->stream - data); + } + if (error == VORBIS_continued_packet_flag_invalid) { + if (f->previous_length == 0) { + // we may be resynching, in which case it's ok to hit one + // of these; just discard the packet + f->error = VORBIS__no_error; + while (get8_packet(f) != EOP) + if (f->eof) break; + *samples = 0; + return (int)(f->stream - data); + } + } + // if we get an error while parsing, what to do? + // well, it DEFINITELY won't work to continue from where we are! + stb_vorbis_flush_pushdata(f); + // restore the error that actually made us bail + f->error = error; + *samples = 0; + return 1; + } + + // success! + len = vorbis_finish_frame(f, len, left, right); + for (i = 0; i < f->channels; ++i) + f->outputs[i] = f->channel_buffers[i] + left; + + if (channels) *channels = f->channels; + *samples = len; + *output = f->outputs; + return (int)(f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( - const unsigned char *data, int data_len, // the memory available for decoding - int *data_used, // only defined if result is not NULL - int *error, const stb_vorbis_alloc *alloc) -{ - stb_vorbis *f, p; - vorbis_init(&p, alloc); - p.stream = (uint8 *) data; - p.stream_end = (uint8 *) data + data_len; - p.push_mode = TRUE; - if (!start_decoder(&p)) { - if (p.eof) - *error = VORBIS_need_more_data; - else - *error = p.error; - return NULL; - } - f = vorbis_alloc(&p); - if (f) { - *f = p; - *data_used = (int) (f->stream - data); - *error = 0; - return f; - } else { - vorbis_deinit(&p); - return NULL; - } + const unsigned char *data, int data_len, // the memory available for decoding + int *data_used, // only defined if result is not NULL + int *error, const stb_vorbis_alloc *alloc) +{ + stb_vorbis *f, p; + vorbis_init(&p, alloc); + p.stream = (uint8 *)data; + p.stream_end = (uint8 *)data + data_len; + p.push_mode = TRUE; + if (!start_decoder(&p)) { + if (p.eof) + *error = VORBIS_need_more_data; + else + *error = p.error; + return NULL; + } + f = vorbis_alloc(&p); + if (f) { + *f = p; + *data_used = (int)(f->stream - data); + *error = 0; + return f; + } + else { + vorbis_deinit(&p); + return NULL; + } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { - #ifndef STB_VORBIS_NO_PUSHDATA_API - if (f->push_mode) return 0; - #endif - if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); - #ifndef STB_VORBIS_NO_STDIO - return (unsigned int) (ftell(f->f) - f->f_start); - #endif +#ifndef STB_VORBIS_NO_PUSHDATA_API + if (f->push_mode) return 0; +#endif + if (USE_MEMORY(f)) return (unsigned int)(f->stream - f->stream_start); +#ifndef STB_VORBIS_NO_STDIO + return (unsigned int)(ftell(f->f) - f->f_start); +#endif } #ifndef STB_VORBIS_NO_PULLDATA_API @@ -4443,72 +4504,72 @@ unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { - for(;;) { - int n; - if (f->eof) return 0; - n = get8(f); - if (n == 0x4f) { // page header candidate - unsigned int retry_loc = stb_vorbis_get_file_offset(f); - int i; - // check if we're off the end of a file_section stream - if (retry_loc - 25 > f->stream_len) - return 0; - // check the rest of the header - for (i=1; i < 4; ++i) - if (get8(f) != ogg_page_header[i]) - break; - if (f->eof) return 0; - if (i == 4) { - uint8 header[27]; - uint32 i, crc, goal, len; - for (i=0; i < 4; ++i) - header[i] = ogg_page_header[i]; - for (; i < 27; ++i) - header[i] = get8(f); + for (;;) { + int n; + if (f->eof) return 0; + n = get8(f); + if (n == 0x4f) { // page header candidate + unsigned int retry_loc = stb_vorbis_get_file_offset(f); + int i; + // check if we're off the end of a file_section stream + if (retry_loc - 25 > f->stream_len) + return 0; + // check the rest of the header + for (i = 1; i < 4; ++i) + if (get8(f) != ogg_page_header[i]) + break; if (f->eof) return 0; - if (header[4] != 0) goto invalid; - goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); - for (i=22; i < 26; ++i) - header[i] = 0; - crc = 0; - for (i=0; i < 27; ++i) - crc = crc32_update(crc, header[i]); - len = 0; - for (i=0; i < header[26]; ++i) { - int s = get8(f); - crc = crc32_update(crc, s); - len += s; + if (i == 4) { + uint8 header[27]; + uint32 i, crc, goal, len; + for (i = 0; i < 4; ++i) + header[i] = ogg_page_header[i]; + for (; i < 27; ++i) + header[i] = get8(f); + if (f->eof) return 0; + if (header[4] != 0) goto invalid; + goal = header[22] + (header[23] << 8) + (header[24] << 16) + (header[25] << 24); + for (i = 22; i < 26; ++i) + header[i] = 0; + crc = 0; + for (i = 0; i < 27; ++i) + crc = crc32_update(crc, header[i]); + len = 0; + for (i = 0; i < header[26]; ++i) { + int s = get8(f); + crc = crc32_update(crc, s); + len += s; + } + if (len && f->eof) return 0; + for (i = 0; i < len; ++i) + crc = crc32_update(crc, get8(f)); + // finished parsing probable page + if (crc == goal) { + // we could now check that it's either got the last + // page flag set, OR it's followed by the capture + // pattern, but I guess TECHNICALLY you could have + // a file with garbage between each ogg page and recover + // from it automatically? So even though that paranoia + // might decrease the chance of an invalid decode by + // another 2^32, not worth it since it would hose those + // invalid-but-useful files? + if (end) + *end = stb_vorbis_get_file_offset(f); + if (last) { + if (header[5] & 0x04) + *last = 1; + else + *last = 0; + } + set_file_offset(f, retry_loc - 1); + return 1; + } } - if (len && f->eof) return 0; - for (i=0; i < len; ++i) - crc = crc32_update(crc, get8(f)); - // finished parsing probable page - if (crc == goal) { - // we could now check that it's either got the last - // page flag set, OR it's followed by the capture - // pattern, but I guess TECHNICALLY you could have - // a file with garbage between each ogg page and recover - // from it automatically? So even though that paranoia - // might decrease the chance of an invalid decode by - // another 2^32, not worth it since it would hose those - // invalid-but-useful files? - if (end) - *end = stb_vorbis_get_file_offset(f); - if (last) { - if (header[5] & 0x04) - *last = 1; - else - *last = 0; - } - set_file_offset(f, retry_loc-1); - return 1; - } - } invalid: - // not a valid page, so rewind and look for next one - set_file_offset(f, retry_loc); - } - } + // not a valid page, so rewind and look for next one + set_file_offset(f, retry_loc); + } + } } @@ -4525,55 +4586,55 @@ static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { - uint8 header[27], lacing[255]; - int i,len; + uint8 header[27], lacing[255]; + int i, len; - // record where the page starts - z->page_start = stb_vorbis_get_file_offset(f); + // record where the page starts + z->page_start = stb_vorbis_get_file_offset(f); - // parse the header - getn(f, header, 27); - if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') - return 0; - getn(f, lacing, header[26]); + // parse the header + getn(f, header, 27); + if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') + return 0; + getn(f, lacing, header[26]); - // determine the length of the payload - len = 0; - for (i=0; i < header[26]; ++i) - len += lacing[i]; + // determine the length of the payload + len = 0; + for (i = 0; i < header[26]; ++i) + len += lacing[i]; - // this implies where the page ends - z->page_end = z->page_start + 27 + header[26] + len; + // this implies where the page ends + z->page_end = z->page_start + 27 + header[26] + len; - // read the last-decoded sample out of the data - z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); + // read the last-decoded sample out of the data + z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); - // restore file state to where we were - set_file_offset(f, z->page_start); - return 1; + // restore file state to where we were + set_file_offset(f, z->page_start); + return 1; } // rarely used function to seek back to the preceeding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { - unsigned int previous_safe, end; + unsigned int previous_safe, end; - // now we want to seek back 64K from the limit - if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) - previous_safe = limit_offset - 65536; - else - previous_safe = f->first_audio_page_offset; + // now we want to seek back 64K from the limit + if (limit_offset >= 65536 && limit_offset - 65536 >= f->first_audio_page_offset) + previous_safe = limit_offset - 65536; + else + previous_safe = f->first_audio_page_offset; - set_file_offset(f, previous_safe); + set_file_offset(f, previous_safe); - while (vorbis_find_page(f, &end, NULL)) { - if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) - return 1; - set_file_offset(f, end); - } + while (vorbis_find_page(f, &end, NULL)) { + if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) + return 1; + set_file_offset(f, end); + } - return 0; + return 0; } // implements the search logic for finding a page and starting decoding. if @@ -4582,414 +4643,419 @@ static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { - ProbedPage left, right, mid; - int i, start_seg_with_known_loc, end_pos, page_start; - uint32 delta, stream_length, padding; - double offset, bytes_per_sample; - int probe = 0; - - // find the last page and validate the target sample - stream_length = stb_vorbis_stream_length_in_samples(f); - if (stream_length == 0) return error(f, VORBIS_seek_without_length); - if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); - - // this is the maximum difference between the window-center (which is the - // actual granule position value), and the right-start (which the spec - // indicates should be the granule position (give or take one)). - padding = ((f->blocksize_1 - f->blocksize_0) >> 2); - if (sample_number < padding) - sample_number = 0; - else - sample_number -= padding; - - left = f->p_first; - while (left.last_decoded_sample == ~0U) { - // (untested) the first page does not have a 'last_decoded_sample' - set_file_offset(f, left.page_end); - if (!get_seek_page_info(f, &left)) goto error; - } - - right = f->p_last; - assert(right.last_decoded_sample != ~0U); - - // starting from the start is handled differently - if (sample_number <= left.last_decoded_sample) { - if (stb_vorbis_seek_start(f)) - return 1; - return 0; - } - - while (left.page_end != right.page_start) { - assert(left.page_end < right.page_start); - // search range in bytes - delta = right.page_start - left.page_end; - if (delta <= 65536) { - // there's only 64K left to search - handle it linearly - set_file_offset(f, left.page_end); - } else { - if (probe < 2) { - if (probe == 0) { - // first probe (interpolate) - double data_bytes = right.page_end - left.page_start; - bytes_per_sample = data_bytes / right.last_decoded_sample; - offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); - } else { - // second probe (try to bound the other side) - double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample; - if (error >= 0 && error < 8000) error = 8000; - if (error < 0 && error > -8000) error = -8000; - offset += error * 2; + ProbedPage left, right, mid; + int i, start_seg_with_known_loc, end_pos, page_start; + uint32 delta, stream_length, padding; + double offset, bytes_per_sample; + int probe = 0; + + // find the last page and validate the target sample + stream_length = stb_vorbis_stream_length_in_samples(f); + if (stream_length == 0) return error(f, VORBIS_seek_without_length); + if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); + + // this is the maximum difference between the window-center (which is the + // actual granule position value), and the right-start (which the spec + // indicates should be the granule position (give or take one)). + padding = ((f->blocksize_1 - f->blocksize_0) >> 2); + if (sample_number < padding) + sample_number = 0; + else + sample_number -= padding; + + left = f->p_first; + while (left.last_decoded_sample == ~0U) { + // (untested) the first page does not have a 'last_decoded_sample' + set_file_offset(f, left.page_end); + if (!get_seek_page_info(f, &left)) goto error; + } + + right = f->p_last; + assert(right.last_decoded_sample != ~0U); + + // starting from the start is handled differently + if (sample_number <= left.last_decoded_sample) { + if (stb_vorbis_seek_start(f)) + return 1; + return 0; + } + + while (left.page_end != right.page_start) { + assert(left.page_end < right.page_start); + // search range in bytes + delta = right.page_start - left.page_end; + if (delta <= 65536) { + // there's only 64K left to search - handle it linearly + set_file_offset(f, left.page_end); + } + else { + if (probe < 2) { + if (probe == 0) { + // first probe (interpolate) + double data_bytes = right.page_end - left.page_start; + bytes_per_sample = data_bytes / right.last_decoded_sample; + offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); + } + else { + // second probe (try to bound the other side) + double error = ((double)sample_number - mid.last_decoded_sample) * bytes_per_sample; + if (error >= 0 && error < 8000) error = 8000; + if (error < 0 && error > -8000) error = -8000; + offset += error * 2; + } + + // ensure the offset is valid + if (offset < left.page_end) + offset = left.page_end; + if (offset > right.page_start - 65536) + offset = right.page_start - 65536; + + set_file_offset(f, (unsigned int)offset); + } + else { + // binary search for large ranges (offset by 32K to ensure + // we don't hit the right page) + set_file_offset(f, left.page_end + (delta / 2) - 32768); } - // ensure the offset is valid - if (offset < left.page_end) - offset = left.page_end; - if (offset > right.page_start - 65536) - offset = right.page_start - 65536; - - set_file_offset(f, (unsigned int) offset); - } else { - // binary search for large ranges (offset by 32K to ensure - // we don't hit the right page) - set_file_offset(f, left.page_end + (delta / 2) - 32768); - } - - if (!vorbis_find_page(f, NULL, NULL)) goto error; - } - - for (;;) { - if (!get_seek_page_info(f, &mid)) goto error; - if (mid.last_decoded_sample != ~0U) break; - // (untested) no frames end on this page - set_file_offset(f, mid.page_end); - assert(mid.page_start < right.page_start); - } - - // if we've just found the last page again then we're in a tricky file, - // and we're close enough. - if (mid.page_start == right.page_start) - break; - - if (sample_number < mid.last_decoded_sample) - right = mid; - else - left = mid; - - ++probe; - } + if (!vorbis_find_page(f, NULL, NULL)) goto error; + } - // seek back to start of the last packet - page_start = left.page_start; - set_file_offset(f, page_start); - if (!start_page(f)) return error(f, VORBIS_seek_failed); - end_pos = f->end_seg_with_known_loc; - assert(end_pos >= 0); + for (;;) { + if (!get_seek_page_info(f, &mid)) goto error; + if (mid.last_decoded_sample != ~0U) break; + // (untested) no frames end on this page + set_file_offset(f, mid.page_end); + assert(mid.page_start < right.page_start); + } - for (;;) { - for (i = end_pos; i > 0; --i) - if (f->segments[i-1] != 255) + // if we've just found the last page again then we're in a tricky file, + // and we're close enough. + if (mid.page_start == right.page_start) break; - start_seg_with_known_loc = i; + if (sample_number < mid.last_decoded_sample) + right = mid; + else + left = mid; - if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) - break; + ++probe; + } - // (untested) the final packet begins on an earlier page - if (!go_to_page_before(f, page_start)) - goto error; + // seek back to start of the last packet + page_start = left.page_start; + set_file_offset(f, page_start); + if (!start_page(f)) return error(f, VORBIS_seek_failed); + end_pos = f->end_seg_with_known_loc; + assert(end_pos >= 0); - page_start = stb_vorbis_get_file_offset(f); - if (!start_page(f)) goto error; - end_pos = f->segment_count - 1; - } + for (;;) { + for (i = end_pos; i > 0; --i) + if (f->segments[i - 1] != 255) + break; + + start_seg_with_known_loc = i; + + if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) + break; - // prepare to start decoding - f->current_loc_valid = FALSE; - f->last_seg = FALSE; - f->valid_bits = 0; - f->packet_bytes = 0; - f->bytes_in_seg = 0; - f->previous_length = 0; - f->next_seg = start_seg_with_known_loc; - - for (i = 0; i < start_seg_with_known_loc; i++) - skip(f, f->segments[i]); - - // start decoding (optimizable - this frame is generally discarded) - if (!vorbis_pump_first_frame(f)) - return 0; - if (f->current_loc > sample_number) - return error(f, VORBIS_seek_failed); - return 1; + // (untested) the final packet begins on an earlier page + if (!go_to_page_before(f, page_start)) + goto error; + + page_start = stb_vorbis_get_file_offset(f); + if (!start_page(f)) goto error; + end_pos = f->segment_count - 1; + } + + // prepare to start decoding + f->current_loc_valid = FALSE; + f->last_seg = FALSE; + f->valid_bits = 0; + f->packet_bytes = 0; + f->bytes_in_seg = 0; + f->previous_length = 0; + f->next_seg = start_seg_with_known_loc; + + for (i = 0; i < start_seg_with_known_loc; i++) + skip(f, f->segments[i]); + + // start decoding (optimizable - this frame is generally discarded) + if (!vorbis_pump_first_frame(f)) + return 0; + if (f->current_loc > sample_number) + return error(f, VORBIS_seek_failed); + return 1; error: - // try to restore the file to a valid state - stb_vorbis_seek_start(f); - return error(f, VORBIS_seek_failed); + // try to restore the file to a valid state + stb_vorbis_seek_start(f); + return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { - int bits_read, bytes_read; + int bits_read, bytes_read; - if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) - return 0; + if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) + return 0; - // either 1 or 2 bytes were read, figure out which so we can rewind - bits_read = 1 + ilog(f->mode_count-1); - if (f->mode_config[*mode].blockflag) - bits_read += 2; - bytes_read = (bits_read + 7) / 8; + // either 1 or 2 bytes were read, figure out which so we can rewind + bits_read = 1 + ilog(f->mode_count - 1); + if (f->mode_config[*mode].blockflag) + bits_read += 2; + bytes_read = (bits_read + 7) / 8; - f->bytes_in_seg += bytes_read; - f->packet_bytes -= bytes_read; - skip(f, -bytes_read); - if (f->next_seg == -1) - f->next_seg = f->segment_count - 1; - else - f->next_seg--; - f->valid_bits = 0; + f->bytes_in_seg += bytes_read; + f->packet_bytes -= bytes_read; + skip(f, -bytes_read); + if (f->next_seg == -1) + f->next_seg = f->segment_count - 1; + else + f->next_seg--; + f->valid_bits = 0; - return 1; + return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { - uint32 max_frame_samples; - - if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); - - // fast page-level search - if (!seek_to_sample_coarse(f, sample_number)) - return 0; - - assert(f->current_loc_valid); - assert(f->current_loc <= sample_number); - - // linear search for the relevant packet - max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; - while (f->current_loc < sample_number) { - int left_start, left_end, right_start, right_end, mode, frame_samples; - if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) - return error(f, VORBIS_seek_failed); - // calculate the number of samples returned by the next frame - frame_samples = right_start - left_start; - if (f->current_loc + frame_samples > sample_number) { - return 1; // the next frame will contain the sample - } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { - // there's a chance the frame after this could contain the sample - vorbis_pump_first_frame(f); - } else { - // this frame is too early to be relevant - f->current_loc += frame_samples; - f->previous_length = 0; - maybe_start_packet(f); - flush_packet(f); - } - } - // the next frame will start with the sample - assert(f->current_loc == sample_number); - return 1; + uint32 max_frame_samples; + + if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); + + // fast page-level search + if (!seek_to_sample_coarse(f, sample_number)) + return 0; + + assert(f->current_loc_valid); + assert(f->current_loc <= sample_number); + + // linear search for the relevant packet + max_frame_samples = (f->blocksize_1 * 3 - f->blocksize_0) >> 2; + while (f->current_loc < sample_number) { + int left_start, left_end, right_start, right_end, mode, frame_samples; + if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) + return error(f, VORBIS_seek_failed); + // calculate the number of samples returned by the next frame + frame_samples = right_start - left_start; + if (f->current_loc + frame_samples > sample_number) { + return 1; // the next frame will contain the sample + } + else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { + // there's a chance the frame after this could contain the sample + vorbis_pump_first_frame(f); + } + else { + // this frame is too early to be relevant + f->current_loc += frame_samples; + f->previous_length = 0; + maybe_start_packet(f); + flush_packet(f); + } + } + // the next frame will start with the sample + assert(f->current_loc == sample_number); + return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { - if (!stb_vorbis_seek_frame(f, sample_number)) - return 0; + if (!stb_vorbis_seek_frame(f, sample_number)) + return 0; - if (sample_number != f->current_loc) { - int n; - uint32 frame_start = f->current_loc; - stb_vorbis_get_frame_float(f, &n, NULL); - assert(sample_number > frame_start); - assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); - f->channel_buffer_start += (sample_number - frame_start); - } + if (sample_number != f->current_loc) { + int n; + uint32 frame_start = f->current_loc; + stb_vorbis_get_frame_float(f, &n, NULL); + assert(sample_number > frame_start); + assert(f->channel_buffer_start + (int)(sample_number - frame_start) <= f->channel_buffer_end); + f->channel_buffer_start += (sample_number - frame_start); + } - return 1; + return 1; } int stb_vorbis_seek_start(stb_vorbis *f) { - if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } - set_file_offset(f, f->first_audio_page_offset); - f->previous_length = 0; - f->first_decode = TRUE; - f->next_seg = -1; - return vorbis_pump_first_frame(f); + if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } + set_file_offset(f, f->first_audio_page_offset); + f->previous_length = 0; + f->first_decode = TRUE; + f->next_seg = -1; + return vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { - unsigned int restore_offset, previous_safe; - unsigned int end, last_page_loc; - - if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); - if (!f->total_samples) { - unsigned int last; - uint32 lo,hi; - char header[6]; - - // first, store the current decode position so we can restore it - restore_offset = stb_vorbis_get_file_offset(f); - - // now we want to seek back 64K from the end (the last page must - // be at most a little less than 64K, but let's allow a little slop) - if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) - previous_safe = f->stream_len - 65536; - else - previous_safe = f->first_audio_page_offset; - - set_file_offset(f, previous_safe); - // previous_safe is now our candidate 'earliest known place that seeking - // to will lead to the final page' - - if (!vorbis_find_page(f, &end, &last)) { - // if we can't find a page, we're hosed! - f->error = VORBIS_cant_find_last_page; - f->total_samples = 0xffffffff; - goto done; - } - - // check if there are more pages - last_page_loc = stb_vorbis_get_file_offset(f); - - // stop when the last_page flag is set, not when we reach eof; - // this allows us to stop short of a 'file_section' end without - // explicitly checking the length of the section - while (!last) { - set_file_offset(f, end); - if (!vorbis_find_page(f, &end, &last)) { - // the last page we found didn't have the 'last page' flag - // set. whoops! - break; - } - previous_safe = last_page_loc+1; - last_page_loc = stb_vorbis_get_file_offset(f); - } - - set_file_offset(f, last_page_loc); - - // parse the header - getn(f, (unsigned char *)header, 6); - // extract the absolute granule position - lo = get32(f); - hi = get32(f); - if (lo == 0xffffffff && hi == 0xffffffff) { - f->error = VORBIS_cant_find_last_page; - f->total_samples = SAMPLE_unknown; - goto done; - } - if (hi) - lo = 0xfffffffe; // saturate - f->total_samples = lo; - - f->p_last.page_start = last_page_loc; - f->p_last.page_end = end; - f->p_last.last_decoded_sample = lo; - - done: - set_file_offset(f, restore_offset); - } - return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; + unsigned int restore_offset, previous_safe; + unsigned int end, last_page_loc; + + if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); + if (!f->total_samples) { + unsigned int last; + uint32 lo, hi; + char header[6]; + + // first, store the current decode position so we can restore it + restore_offset = stb_vorbis_get_file_offset(f); + + // now we want to seek back 64K from the end (the last page must + // be at most a little less than 64K, but let's allow a little slop) + if (f->stream_len >= 65536 && f->stream_len - 65536 >= f->first_audio_page_offset) + previous_safe = f->stream_len - 65536; + else + previous_safe = f->first_audio_page_offset; + + set_file_offset(f, previous_safe); + // previous_safe is now our candidate 'earliest known place that seeking + // to will lead to the final page' + + if (!vorbis_find_page(f, &end, &last)) { + // if we can't find a page, we're hosed! + f->error = VORBIS_cant_find_last_page; + f->total_samples = 0xffffffff; + goto done; + } + + // check if there are more pages + last_page_loc = stb_vorbis_get_file_offset(f); + + // stop when the last_page flag is set, not when we reach eof; + // this allows us to stop short of a 'file_section' end without + // explicitly checking the length of the section + while (!last) { + set_file_offset(f, end); + if (!vorbis_find_page(f, &end, &last)) { + // the last page we found didn't have the 'last page' flag + // set. whoops! + break; + } + previous_safe = last_page_loc + 1; + last_page_loc = stb_vorbis_get_file_offset(f); + } + + set_file_offset(f, last_page_loc); + + // parse the header + getn(f, (unsigned char *)header, 6); + // extract the absolute granule position + lo = get32(f); + hi = get32(f); + if (lo == 0xffffffff && hi == 0xffffffff) { + f->error = VORBIS_cant_find_last_page; + f->total_samples = SAMPLE_unknown; + goto done; + } + if (hi) + lo = 0xfffffffe; // saturate + f->total_samples = lo; + + f->p_last.page_start = last_page_loc; + f->p_last.page_end = end; + f->p_last.last_decoded_sample = lo; + + done: + set_file_offset(f, restore_offset); + } + return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { - return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; + return stb_vorbis_stream_length_in_samples(f) / (float)f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { - int len, right,left,i; - if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); + int len, right, left, i; + if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); - if (!vorbis_decode_packet(f, &len, &left, &right)) { - f->channel_buffer_start = f->channel_buffer_end = 0; - return 0; - } + if (!vorbis_decode_packet(f, &len, &left, &right)) { + f->channel_buffer_start = f->channel_buffer_end = 0; + return 0; + } - len = vorbis_finish_frame(f, len, left, right); - for (i=0; i < f->channels; ++i) - f->outputs[i] = f->channel_buffers[i] + left; + len = vorbis_finish_frame(f, len, left, right); + for (i = 0; i < f->channels; ++i) + f->outputs[i] = f->channel_buffers[i] + left; - f->channel_buffer_start = left; - f->channel_buffer_end = left+len; + f->channel_buffer_start = left; + f->channel_buffer_end = left + len; - if (channels) *channels = f->channels; - if (output) *output = f->outputs; - return len; + if (channels) *channels = f->channels; + if (output) *output = f->outputs; + return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { - stb_vorbis *f, p; - vorbis_init(&p, alloc); - p.f = file; - p.f_start = (uint32) ftell(file); - p.stream_len = length; - p.close_on_free = close_on_free; - if (start_decoder(&p)) { - f = vorbis_alloc(&p); - if (f) { - *f = p; - vorbis_pump_first_frame(f); - return f; - } - } - if (error) *error = p.error; - vorbis_deinit(&p); - return NULL; + stb_vorbis *f, p; + vorbis_init(&p, alloc); + p.f = file; + p.f_start = (uint32)ftell(file); + p.stream_len = length; + p.close_on_free = close_on_free; + if (start_decoder(&p)) { + f = vorbis_alloc(&p); + if (f) { + *f = p; + vorbis_pump_first_frame(f); + return f; + } + } + if (error) *error = p.error; + vorbis_deinit(&p); + return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { - unsigned int len, start; - start = (unsigned int) ftell(file); - fseek(file, 0, SEEK_END); - len = (unsigned int) (ftell(file) - start); - fseek(file, start, SEEK_SET); - return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); + unsigned int len, start; + start = (unsigned int)ftell(file); + fseek(file, 0, SEEK_END); + len = (unsigned int)(ftell(file) - start); + fseek(file, start, SEEK_SET); + return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { - FILE *f = fopen(filename, "rb"); - if (f) - return stb_vorbis_open_file(f, TRUE, error, alloc); - if (error) *error = VORBIS_file_open_failure; - return NULL; + FILE *f = fopen(filename, "rb"); + if (f) + return stb_vorbis_open_file(f, TRUE, error, alloc); + if (error) *error = VORBIS_file_open_failure; + return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { - stb_vorbis *f, p; - if (data == NULL) return NULL; - vorbis_init(&p, alloc); - p.stream = (uint8 *) data; - p.stream_end = (uint8 *) data + len; - p.stream_start = (uint8 *) p.stream; - p.stream_len = len; - p.push_mode = FALSE; - if (start_decoder(&p)) { - f = vorbis_alloc(&p); - if (f) { - *f = p; - vorbis_pump_first_frame(f); - if (error) *error = VORBIS__no_error; - return f; - } - } - if (error) *error = p.error; - vorbis_deinit(&p); - return NULL; + stb_vorbis *f, p; + if (data == NULL) return NULL; + vorbis_init(&p, alloc); + p.stream = (uint8 *)data; + p.stream_end = (uint8 *)data + len; + p.stream_start = (uint8 *)p.stream; + p.stream_len = len; + p.push_mode = FALSE; + if (start_decoder(&p)) { + f = vorbis_alloc(&p); + if (f) { + *f = p; + vorbis_pump_first_frame(f); + if (error) *error = VORBIS__no_error; + return f; + } + } + if (error) *error = p.error; + vorbis_deinit(&p); + return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION @@ -5003,402 +5069,408 @@ stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *err static int8 channel_position[7][6] = { - { 0 }, - { C }, - { L, R }, - { L, C, R }, - { L, R, L, R }, - { L, C, R, L, R }, - { L, C, R, L, R, C }, + { 0 }, + { C }, + { L, R }, + { L, C, R }, + { L, R, L, R }, + { L, C, R, L, R }, + { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT - typedef union { - float f; - int i; - } float_conv; - typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; - #define FASTDEF(x) float_conv x - // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round - #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) - #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) - #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) - #define check_endianness() +typedef union { + float f; + int i; +} float_conv; +typedef char stb_vorbis_float_size_test[sizeof(float) == 4 && sizeof(int) == 4]; +#define FASTDEF(x) float_conv x +// add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round +#define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) +#define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) +#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) +#define check_endianness() #else - #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) - #define check_endianness() - #define FASTDEF(x) +#define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) +#define check_endianness() +#define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { - int i; - check_endianness(); - for (i=0; i < len; ++i) { - FASTDEF(temp); - int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); - if ((unsigned int) (v + 32768) > 65535) - v = v < 0 ? -32768 : 32767; - dest[i] = v; - } + int i; + check_endianness(); + for (i = 0; i < len; ++i) { + FASTDEF(temp); + int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i], 15); + if ((unsigned int)(v + 32768) > 65535) + v = v < 0 ? -32768 : 32767; + dest[i] = v; + } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { - #define BUFFER_SIZE 32 - float buffer[BUFFER_SIZE]; - int i,j,o,n = BUFFER_SIZE; - check_endianness(); - for (o = 0; o < len; o += BUFFER_SIZE) { - memset(buffer, 0, sizeof(buffer)); - if (o + n > len) n = len - o; - for (j=0; j < num_c; ++j) { - if (channel_position[num_c][j] & mask) { - for (i=0; i < n; ++i) - buffer[i] += data[j][d_offset+o+i]; - } - } - for (i=0; i < n; ++i) { - FASTDEF(temp); - int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); - if ((unsigned int) (v + 32768) > 65535) - v = v < 0 ? -32768 : 32767; - output[o+i] = v; - } - } +#define BUFFER_SIZE 32 + float buffer[BUFFER_SIZE]; + int i, j, o, n = BUFFER_SIZE; + check_endianness(); + for (o = 0; o < len; o += BUFFER_SIZE) { + memset(buffer, 0, sizeof(buffer)); + if (o + n > len) n = len - o; + for (j = 0; j < num_c; ++j) { + if (channel_position[num_c][j] & mask) { + for (i = 0; i < n; ++i) + buffer[i] += data[j][d_offset + o + i]; + } + } + for (i = 0; i < n; ++i) { + FASTDEF(temp); + int v = FAST_SCALED_FLOAT_TO_INT(temp, buffer[i], 15); + if ((unsigned int)(v + 32768) > 65535) + v = v < 0 ? -32768 : 32767; + output[o + i] = v; + } + } } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { - #define BUFFER_SIZE 32 - float buffer[BUFFER_SIZE]; - int i,j,o,n = BUFFER_SIZE >> 1; - // o is the offset in the source data - check_endianness(); - for (o = 0; o < len; o += BUFFER_SIZE >> 1) { - // o2 is the offset in the output data - int o2 = o << 1; - memset(buffer, 0, sizeof(buffer)); - if (o + n > len) n = len - o; - for (j=0; j < num_c; ++j) { - int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); - if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { - for (i=0; i < n; ++i) { - buffer[i*2+0] += data[j][d_offset+o+i]; - buffer[i*2+1] += data[j][d_offset+o+i]; +#define BUFFER_SIZE 32 + float buffer[BUFFER_SIZE]; + int i, j, o, n = BUFFER_SIZE >> 1; + // o is the offset in the source data + check_endianness(); + for (o = 0; o < len; o += BUFFER_SIZE >> 1) { + // o2 is the offset in the output data + int o2 = o << 1; + memset(buffer, 0, sizeof(buffer)); + if (o + n > len) n = len - o; + for (j = 0; j < num_c; ++j) { + int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); + if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { + for (i = 0; i < n; ++i) { + buffer[i * 2 + 0] += data[j][d_offset + o + i]; + buffer[i * 2 + 1] += data[j][d_offset + o + i]; + } } - } else if (m == PLAYBACK_LEFT) { - for (i=0; i < n; ++i) { - buffer[i*2+0] += data[j][d_offset+o+i]; + else if (m == PLAYBACK_LEFT) { + for (i = 0; i < n; ++i) { + buffer[i * 2 + 0] += data[j][d_offset + o + i]; + } } - } else if (m == PLAYBACK_RIGHT) { - for (i=0; i < n; ++i) { - buffer[i*2+1] += data[j][d_offset+o+i]; + else if (m == PLAYBACK_RIGHT) { + for (i = 0; i < n; ++i) { + buffer[i * 2 + 1] += data[j][d_offset + o + i]; + } } - } - } - for (i=0; i < (n<<1); ++i) { - FASTDEF(temp); - int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); - if ((unsigned int) (v + 32768) > 65535) - v = v < 0 ? -32768 : 32767; - output[o2+i] = v; - } - } + } + for (i = 0; i < (n << 1); ++i) { + FASTDEF(temp); + int v = FAST_SCALED_FLOAT_TO_INT(temp, buffer[i], 15); + if ((unsigned int)(v + 32768) > 65535) + v = v < 0 ? -32768 : 32767; + output[o2 + i] = v; + } + } } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { - int i; - if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { - static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; - for (i=0; i < buf_c; ++i) - compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); - } else { - int limit = buf_c < data_c ? buf_c : data_c; - for (i=0; i < limit; ++i) - copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); - for ( ; i < buf_c; ++i) - memset(buffer[i]+b_offset, 0, sizeof(short) * samples); - } + int i; + if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { + static int channel_selector[3][2] = { { 0 },{ PLAYBACK_MONO },{ PLAYBACK_LEFT, PLAYBACK_RIGHT } }; + for (i = 0; i < buf_c; ++i) + compute_samples(channel_selector[buf_c][i], buffer[i] + b_offset, data_c, data, d_offset, samples); + } + else { + int limit = buf_c < data_c ? buf_c : data_c; + for (i = 0; i < limit; ++i) + copy_samples(buffer[i] + b_offset, data[i] + d_offset, samples); + for (; i < buf_c; ++i) + memset(buffer[i] + b_offset, 0, sizeof(short) * samples); + } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { - float **output; - int len = stb_vorbis_get_frame_float(f, NULL, &output); - if (len > num_samples) len = num_samples; - if (len) - convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); - return len; + float **output; + int len = stb_vorbis_get_frame_float(f, NULL, &output); + if (len > num_samples) len = num_samples; + if (len) + convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); + return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { - int i; - check_endianness(); - if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { - assert(buf_c == 2); - for (i=0; i < buf_c; ++i) - compute_stereo_samples(buffer, data_c, data, d_offset, len); - } else { - int limit = buf_c < data_c ? buf_c : data_c; - int j; - for (j=0; j < len; ++j) { - for (i=0; i < limit; ++i) { - FASTDEF(temp); - float f = data[i][d_offset+j]; - int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); - if ((unsigned int) (v + 32768) > 65535) - v = v < 0 ? -32768 : 32767; - *buffer++ = v; - } - for ( ; i < buf_c; ++i) - *buffer++ = 0; - } - } + int i; + check_endianness(); + if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { + assert(buf_c == 2); + for (i = 0; i < buf_c; ++i) + compute_stereo_samples(buffer, data_c, data, d_offset, len); + } + else { + int limit = buf_c < data_c ? buf_c : data_c; + int j; + for (j = 0; j < len; ++j) { + for (i = 0; i < limit; ++i) { + FASTDEF(temp); + float f = data[i][d_offset + j]; + int v = FAST_SCALED_FLOAT_TO_INT(temp, f, 15);//data[i][d_offset+j],15); + if ((unsigned int)(v + 32768) > 65535) + v = v < 0 ? -32768 : 32767; + *buffer++ = v; + } + for (; i < buf_c; ++i) + *buffer++ = 0; + } + } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { - float **output; - int len; - if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); - len = stb_vorbis_get_frame_float(f, NULL, &output); - if (len) { - if (len*num_c > num_shorts) len = num_shorts / num_c; - convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); - } - return len; + float **output; + int len; + if (num_c == 1) return stb_vorbis_get_frame_short(f, num_c, &buffer, num_shorts); + len = stb_vorbis_get_frame_float(f, NULL, &output); + if (len) { + if (len*num_c > num_shorts) len = num_shorts / num_c; + convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); + } + return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { - float **outputs; - int len = num_shorts / channels; - int n=0; - int z = f->channels; - if (z > channels) z = channels; - while (n < len) { - int k = f->channel_buffer_end - f->channel_buffer_start; - if (n+k >= len) k = len - n; - if (k) - convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); - buffer += k*channels; - n += k; - f->channel_buffer_start += k; - if (n == len) break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; - } - return n; + float **outputs; + int len = num_shorts / channels; + int n = 0; + int z = f->channels; + if (z > channels) z = channels; + while (n < len) { + int k = f->channel_buffer_end - f->channel_buffer_start; + if (n + k >= len) k = len - n; + if (k) + convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); + buffer += k*channels; + n += k; + f->channel_buffer_start += k; + if (n == len) break; + if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; + } + return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { - float **outputs; - int n=0; - int z = f->channels; - if (z > channels) z = channels; - while (n < len) { - int k = f->channel_buffer_end - f->channel_buffer_start; - if (n+k >= len) k = len - n; - if (k) - convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); - n += k; - f->channel_buffer_start += k; - if (n == len) break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; - } - return n; + float **outputs; + int n = 0; + int z = f->channels; + if (z > channels) z = channels; + while (n < len) { + int k = f->channel_buffer_end - f->channel_buffer_start; + if (n + k >= len) k = len - n; + if (k) + convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); + n += k; + f->channel_buffer_start += k; + if (n == len) break; + if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; + } + return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { - int data_len, offset, total, limit, error; - short *data; - stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); - if (v == NULL) return -1; - limit = v->channels * 4096; - *channels = v->channels; - if (sample_rate) - *sample_rate = v->sample_rate; - offset = data_len = 0; - total = limit; - data = (short *) malloc(total * sizeof(*data)); - if (data == NULL) { - stb_vorbis_close(v); - return -2; - } - for (;;) { - int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); - if (n == 0) break; - data_len += n; - offset += n * v->channels; - if (offset + limit > total) { - short *data2; - total *= 2; - data2 = (short *) realloc(data, total * sizeof(*data)); - if (data2 == NULL) { - free(data); - stb_vorbis_close(v); - return -2; - } - data = data2; - } - } - *output = data; - stb_vorbis_close(v); - return data_len; + int data_len, offset, total, limit, error; + short *data; + stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); + if (v == NULL) return -1; + limit = v->channels * 4096; + *channels = v->channels; + if (sample_rate) + *sample_rate = v->sample_rate; + offset = data_len = 0; + total = limit; + data = (short *)malloc(total * sizeof(*data)); + if (data == NULL) { + stb_vorbis_close(v); + return -2; + } + for (;;) { + int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data + offset, total - offset); + if (n == 0) break; + data_len += n; + offset += n * v->channels; + if (offset + limit > total) { + short *data2; + total *= 2; + data2 = (short *)realloc(data, total * sizeof(*data)); + if (data2 == NULL) { + free(data); + stb_vorbis_close(v); + return -2; + } + data = data2; + } + } + *output = data; + stb_vorbis_close(v); + return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { - int data_len, offset, total, limit, error; - short *data; - stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); - if (v == NULL) return -1; - limit = v->channels * 4096; - *channels = v->channels; - if (sample_rate) - *sample_rate = v->sample_rate; - offset = data_len = 0; - total = limit; - data = (short *) malloc(total * sizeof(*data)); - if (data == NULL) { - stb_vorbis_close(v); - return -2; - } - for (;;) { - int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); - if (n == 0) break; - data_len += n; - offset += n * v->channels; - if (offset + limit > total) { - short *data2; - total *= 2; - data2 = (short *) realloc(data, total * sizeof(*data)); - if (data2 == NULL) { - free(data); - stb_vorbis_close(v); - return -2; - } - data = data2; - } - } - *output = data; - stb_vorbis_close(v); - return data_len; + int data_len, offset, total, limit, error; + short *data; + stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); + if (v == NULL) return -1; + limit = v->channels * 4096; + *channels = v->channels; + if (sample_rate) + *sample_rate = v->sample_rate; + offset = data_len = 0; + total = limit; + data = (short *)malloc(total * sizeof(*data)); + if (data == NULL) { + stb_vorbis_close(v); + return -2; + } + for (;;) { + int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data + offset, total - offset); + if (n == 0) break; + data_len += n; + offset += n * v->channels; + if (offset + limit > total) { + short *data2; + total *= 2; + data2 = (short *)realloc(data, total * sizeof(*data)); + if (data2 == NULL) { + free(data); + stb_vorbis_close(v); + return -2; + } + data = data2; + } + } + *output = data; + stb_vorbis_close(v); + return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { - float **outputs; - int len = num_floats / channels; - int n=0; - int z = f->channels; - if (z > channels) z = channels; - while (n < len) { - int i,j; - int k = f->channel_buffer_end - f->channel_buffer_start; - if (n+k >= len) k = len - n; - for (j=0; j < k; ++j) { - for (i=0; i < z; ++i) - *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; - for ( ; i < channels; ++i) - *buffer++ = 0; - } - n += k; - f->channel_buffer_start += k; - if (n == len) - break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) - break; - } - return n; + float **outputs; + int len = num_floats / channels; + int n = 0; + int z = f->channels; + if (z > channels) z = channels; + while (n < len) { + int i, j; + int k = f->channel_buffer_end - f->channel_buffer_start; + if (n + k >= len) k = len - n; + for (j = 0; j < k; ++j) { + for (i = 0; i < z; ++i) + *buffer++ = f->channel_buffers[i][f->channel_buffer_start + j]; + for (; i < channels; ++i) + *buffer++ = 0; + } + n += k; + f->channel_buffer_start += k; + if (n == len) + break; + if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) + break; + } + return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { - float **outputs; - int n=0; - int z = f->channels; - if (z > channels) z = channels; - while (n < num_samples) { - int i; - int k = f->channel_buffer_end - f->channel_buffer_start; - if (n+k >= num_samples) k = num_samples - n; - if (k) { - for (i=0; i < z; ++i) - memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); - for ( ; i < channels; ++i) - memset(buffer[i]+n, 0, sizeof(float) * k); - } - n += k; - f->channel_buffer_start += k; - if (n == num_samples) - break; - if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) - break; - } - return n; + float **outputs; + int n = 0; + int z = f->channels; + if (z > channels) z = channels; + while (n < num_samples) { + int i; + int k = f->channel_buffer_end - f->channel_buffer_start; + if (n + k >= num_samples) k = num_samples - n; + if (k) { + for (i = 0; i < z; ++i) + memcpy(buffer[i] + n, f->channel_buffers[i] + f->channel_buffer_start, sizeof(float)*k); + for (; i < channels; ++i) + memset(buffer[i] + n, 0, sizeof(float) * k); + } + n += k; + f->channel_buffer_start += k; + if (n == num_samples) + break; + if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) + break; + } + return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history - 1.10 - 2017/03/03 - more robust seeking; fix negative ilog(); clear error in open_memory - 1.09 - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version - 1.08 - 2016/04/02 - fixed multiple warnings; fix setup memory leaks; - avoid discarding last frame of audio data - 1.07 - 2015/01/16 - fixed some warnings, fix mingw, const-correct API - some more crash fixes when out of memory or with corrupt files - 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson) - some crash fixes when out of memory or with corrupt files - 1.05 - 2015/04/19 - don't define __forceinline if it's redundant - 1.04 - 2014/08/27 - fix missing const-correct case in API - 1.03 - 2014/08/07 - Warning fixes - 1.02 - 2014/07/09 - Declare qsort compare function _cdecl on windows - 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float - 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in multichannel - (API change) report sample rate for decode-full-file funcs - 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila - 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem - 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence - 0.99993 - remove assert that fired on legal files with empty tables - 0.99992 - rewind-to-start - 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo - 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ - 0.9998 - add a full-decode function with a memory source - 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition - 0.9996 - query length of vorbis stream in samples/seconds - 0.9995 - bugfix to another optimization that only happened in certain files - 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors - 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation - 0.9992 - performance improvement of IMDCT; now performs close to reference implementation - 0.9991 - performance improvement of IMDCT - 0.999 - (should have been 0.9990) performance improvement of IMDCT - 0.998 - no-CRT support from Casey Muratori - 0.997 - bugfixes for bugs found by Terje Mathisen - 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen - 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen - 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen - 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen - 0.992 - fixes for MinGW warning - 0.991 - turn fast-float-conversion on by default - 0.990 - fix push-mode seek recovery if you seek into the headers - 0.98b - fix to bad release of 0.98 - 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode - 0.97 - builds under c++ (typecasting, don't use 'class' keyword) - 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code - 0.95 - clamping code for 16-bit functions - 0.94 - not publically released - 0.93 - fixed all-zero-floor case (was decoding garbage) - 0.92 - fixed a memory leak - 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION - 0.90 - first public release +1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files +1.11 - 2017-07-23 - fix MinGW compilation +1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory +1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version +1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; +avoid discarding last frame of audio data +1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API +some more crash fixes when out of memory or with corrupt files +1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) +some crash fixes when out of memory or with corrupt files +1.05 - 2015-04-19 - don't define __forceinline if it's redundant +1.04 - 2014-08-27 - fix missing const-correct case in API +1.03 - 2014-08-07 - Warning fixes +1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows +1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float +1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel +(API change) report sample rate for decode-full-file funcs +0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila +0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem +0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence +0.99993 - remove assert that fired on legal files with empty tables +0.99992 - rewind-to-start +0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo +0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ +0.9998 - add a full-decode function with a memory source +0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition +0.9996 - query length of vorbis stream in samples/seconds +0.9995 - bugfix to another optimization that only happened in certain files +0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors +0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation +0.9992 - performance improvement of IMDCT; now performs close to reference implementation +0.9991 - performance improvement of IMDCT +0.999 - (should have been 0.9990) performance improvement of IMDCT +0.998 - no-CRT support from Casey Muratori +0.997 - bugfixes for bugs found by Terje Mathisen +0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen +0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen +0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen +0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen +0.992 - fixes for MinGW warning +0.991 - turn fast-float-conversion on by default +0.990 - fix push-mode seek recovery if you seek into the headers +0.98b - fix to bad release of 0.98 +0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode +0.97 - builds under c++ (typecasting, don't use 'class' keyword) +0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code +0.95 - clamping code for 16-bit functions +0.94 - not publically released +0.93 - fixed all-zero-floor case (was decoding garbage) +0.92 - fixed a memory leak +0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION +0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY @@ -5410,38 +5482,38 @@ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ -*/ +*/
\ No newline at end of file diff --git a/src/libs/tiny/tinysound.h b/src/libs/tiny/tinysound.h deleted file mode 100644 index 41d547d..0000000 --- a/src/libs/tiny/tinysound.h +++ /dev/null @@ -1,2560 +0,0 @@ -/* -tinysound.h - v1.07 - -Summary: -tinysound is a C API for loading, playing, looping, panning and fading mono -and stero sounds. This means tinysound imparts no external DLLs or large -libraries that adversely effect shipping size. tinysound can also run on -Windows XP since DirectSound ships with all recent versions of Windows. -tinysound implements a custom SSE2 mixer by explicitly locking and unlocking -portions of an internal. tinysound uses CoreAudio for Apple machines (like -OSX and iOS). SDL is used for all other platforms. Define TS_FORCE_SDL -before placaing the TS_IMPLEMENTATION in order to force the use of SDL. - -Revision history: -1.0 (06/04/2016) initial release -1.01 (06/06/2016) load WAV from memory -separate portable and OS-specific code in tsMix -fixed bug causing audio glitches when sounds ended -added stb_vorbis loaders + demo example -1.02 (06/08/2016) error checking + strings in vorbis loaders -SSE2 implementation of mixer -fix typos on docs/comments -corrected volume bug introduced in 1.01 -1.03 (07/05/2016) size calculation helper (to know size of sound in -bytes on the heap) tsSoundSize -1.04 (12/06/2016) merged in Aaron Balint's contributions -SFFT and pitch functions from Stephan M. Bernsee -tsMix can run on its own thread with tsSpawnMixThread -updated documentation, typo fixes -fixed typo in malloc16 that caused heap corruption -1.05 (12/08/2016) tsStopAllSounds, suggested by Aaron Balint -1.06 (02/17/2017) port to CoreAudio for Apple machines -1.07 (06/18/2017) SIMD the pitch shift code; swapped out old Bernsee -code for a new re-write, updated docs as necessary, -support for compiling as .c and .cpp on Windows, -port for SDL (for Linux, or any other platform). -Special thanks to DexP of github for 90% of the work -on the SDL port! -*/ - -/* -Contributors: -Aaron Balint 1.04 - real time pitch -1.04 - separate thread for tsMix -1.04 - bugfix, removed extra free16 call for second channel -DeXP 1.07 - initial work on SDL port -*/ - -/* -To create implementation (the function definitions) -#define TS_IMPLEMENTATION -in *one* C/CPP file (translation unit) that includes this file - -DOCUMENTATION (very quick intro): -1. create context -2. load sounds from disk into memory -3. play sounds -4. free context - -1. tsContext* ctx = tsMakeContext( hwnd, frequency, latency, seconds, N ); -2. tsPlaySoundDef def = tsMakeDef( &tsLoadWAV( "path_to_file/filename.wav" ) ); -3. tsPlaySound( ctx, def ); -4. tsShutdownContext( ctx ); - -DOCUMENTATION (longer introduction): -tinysound consists of tsLoadedSounds, tsPlayingSounds and the tsContext. -The tsContext encapsulates an OS sound API, as well as buffers + settings. -tsLoadedSound holds raw samples of a sound. tsPlayingSound is an instance -of a tsLoadedSound that represents a sound that can be played through the -tsContext. - -There are two main versions of the API, the low-level and the high-level -API. The low-level API does not manage any memory for tsPlayingSounds. The -high level api holds a memory pool of playing sounds. - -High-level API: -First create a context and pass in non-zero to the final parameter. This -final parameter controls how large of a memory pool to use for tsPlayingSounds. -Here's an example where N is the size of the internal pool: - -tsContext* ctx = tsMakeContext( hwnd, frequency, latency, seconds, N ); - -We create tsPlayingSounds indirectly with tsPlayDef structs. tsPlayDef is a -POD struct so feel free to make them straight on the stack. The tsPlayDef -sets up initialization parameters. Here's an example to load a wav and -play it: - -tsLoadedSound loaded = tsLoadWAV( "path_to_file/filename.wav" ); -tsPlaySoundDef def = tsMakeDef( &loaded ); -tsPlayingSound* sound = tsPlaySound( ctx, def ); - -The same def can be used to play as many sounds as desired (even simultaneously) -as long as the context playing sound pool is large enough. - -Low-level API: -First create a context and pass 0 in the final parameter (0 here means -the context will *not* allocate a tsPlayingSound memory pool): - -tsContext* ctx = tsMakeContext( hwnd, frequency, latency, seconds, 0 ); - -parameters: -hwnd -- HWND, handle to window (on OSX just pass in 0) -frequency -- int, represents Hz frequency rate in which samples are played -latency -- int, estimated latency in Hz from PlaySound call to speaker output -seconds -- int, number of second of samples internal buffers can hold -0 (last param) -- int, number of elements in tsPlayingSound pool - -We create a tsPlayingSound like so: -tsLoadedSound loaded = tsLoadWAV( "path_to_file/filename.wav" ); -tsPlayingSound playing_sound = tsMakePlayingSound( &loaded ); - -Then to play the sound we do: -tsInsertSound( ctx, &playing_sound ); - -The above tsInsertSound function call will place playing_sound into -a singly-linked list inside the context. The context will remove -the sound from its internal list when it finishes playing. - -WARNING: The high-level API cannot be mixed with the low-level API. If you -try then the internal code will assert and crash. Pick one and stick with it. -Usually he high-level API will be used, but if someone is *really* picky about -their memory usage, or wants more control, the low-level API can be used. - -Here is the Low-Level API: -tsPlayingSound tsMakePlayingSound( tsLoadedSound* loaded ); -void tsInsertSound( tsContext* ctx, tsPlayingSound* sound ); - -Here is the High-Level API: -tsPlayingSound* tsPlaySound( tsContext* ctx, tsPlaySoundDef def ); -tsPlaySoundDef tsMakeDef( tsLoadedSound* sound ); -void tsStopAllSounds( tsContext( ctx ); - -Be sure to link against dsound.dll (or dsound.lib) on Windows. - -Read the rest of the header for specific details on all available functions -and struct types. -*/ - -/* -Known Limitations: - -* PCM mono/stereo format is the only formats the LoadWAV function supports. I don't -guarantee it will work for all kinds of wav files, but it certainly does for the common -kind (and can be changed fairly easily if someone wanted to extend it). -* Only supports 16 bits per sample. -* Mixer does not do any fancy clipping. The algorithm is to convert all 16 bit samples -to float, mix all samples, and write back to audio API as 16 bit integers. In -practice this works very well and clipping is not often a big problem. -* I'm not super familiar with good ways to avoid the DirectSound play cursor from going -past the write cursor. To mitigate this pass in a larger number to tsMakeContext's 4th -parameter (buffer scale in seconds). -* Pitch shifting code is pretty darn expensive. This is due to the use of a Fast Fourier Transform -routine. The pitch shifting itself is written in rather efficient SIMD using SSE2 intrinsics, -but the FFT routine is very basic. FFT is a big bottleneck for pitch shifting. There is a -TODO optimization listed in this file for the FFT routine, but it's fairly low priority; -optimizing FFT routines is difficult and requires a lot of specialized knowledge. -*/ - -/* -FAQ -Q : Why DirectSound instead of (insert API here) on Windows? -A : Casey Muratori documented DS on Handmade Hero, other APIs do not have such good docs. DS has -shipped on Windows XP all the way through Windows 10 -- using this header effectively intro- -duces zero dependencies for the foreseeable future. The DS API itself is sane enough to quickly -implement needed features, and users won't hear the difference between various APIs. Latency is -not that great with DS but it is shippable. Additionally, many other APIs will in the end speak -to Windows through the DS API. - -Q : Why not include Linux support? -A : There have been a couple requests for ALSA support on Linux. For now the only option is to use -SDL backend, which can indirectly support ALSA. SDL is used only in a very low-level manner; -to get sound samples to the sound card via callback, so there shouldn't be much in the way of -considering SDL a good option for "name your flavor" of Linux backend. - -Q : I would like to use my own memory management, how can I achieve this? -A : This header makes a couple uses of malloc/free, and malloc16/free16. Simply find these bits -and replace them with your own memory allocation routines. They can be wrapped up into a macro, -or call your own functions directly -- it's up to you. Generally these functions allocate fairly -large chunks of memory, and not very often (if at all), with one exception: tsSetPitch is a very -expensive routine and requires frequent dynamic memory management. -*/ - -/* -Some past discussion threads: -https://www.reddit.com/r/gamedev/comments/6i39j2/tinysound_the_cutest_library_to_get_audio_into/ -https://www.reddit.com/r/gamedev/comments/4ml6l9/tinysound_singlefile_c_audio_library/ -https://forums.tigsource.com/index.php?topic=58706.0 -*/ - -#if !defined( TINYSOUND_H ) - -#define TS_WINDOWS 1 -#define TS_MAC 2 -#define TS_UNIX 3 -#define TS_SDL 4 - -#if defined( _WIN32 ) -#define TS_PLATFORM TS_WINDOWS -#elif defined( __APPLE__ ) -#define TS_PLATFORM TS_MAC -#else -#define TS_PLATFORM TS_SDL - -// please note TS_UNIX is not directly support -// instead, unix-style OSes are encouraged to use SDL -// see: https://www.libsdl.org/ - -#endif - -// Use TS_FORCE_SDL to override the above macros and use -// the SDL port. -#ifdef TS_FORCE_SDL - -#undef TS_PLATFORM -#define TS_PLATFORM TS_SDL - -#endif - -#include <stdint.h> - -// read this in the event of tsLoadWAV/tsLoadOGG errors -// also read this in the event of certain errors from tsMakeContext -extern const char* g_tsErrorReason; - -// stores a loaded sound in memory -typedef struct -{ - int sample_count; - int channel_count; - void* channels[2]; -} tsLoadedSound; - -struct tsPitchData; -typedef struct tsPitchData tsPitchData; - -// represents an instance of a tsLoadedSound, can be played through the tsContext -typedef struct tsPlayingSound -{ - int active; - int paused; - int looped; - float volume0; - float volume1; - float pan0; - float pan1; - float pitch; - tsPitchData* pitch_filter[2]; - int sample_index; - tsLoadedSound* loaded_sound; - struct tsPlayingSound* next; -} tsPlayingSound; - -// holds audio API info and other info -struct tsContext; -typedef struct tsContext tsContext; - -// The returned struct will contain a null pointer in tsLoadedSound::channel[ 0 ] -// in the case of errors. Read g_tsErrorReason string for details on what happened. -// Calls tsReadMemWAV internally. -tsLoadedSound tsLoadWAV(const char* path); - -// Reads a WAV file from memory. Still allocates memory for the tsLoadedSound since -// WAV format will interlace stereo, and we need separate data streams to do SIMD -// properly. -void tsReadMemWAV(const void* memory, tsLoadedSound* sound); - -// If stb_vorbis was included *before* tinysound go ahead and create -// some functions for dealing with OGG files. -#ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H -void tsReadMemOGG(const void* memory, int length, int* sample_rate, tsLoadedSound* sound); -tsLoadedSound tsLoadOGG(const char* path, int* sample_rate); -#endif - -// Uses free16 (aligned free, implemented later in this file) to free up both of -// the channels stored within sound -void tsFreeSound(tsLoadedSound* sound); - -// Returns the size, in bytes, of all heap-allocated memory for this particular -// loaded sound -int tsSoundSize(tsLoadedSound* sound); - -// playing_pool_count -- 0 to setup low-level API, non-zero to size the internal -// memory pool for tsPlayingSound instances -tsContext* tsMakeContext(void* hwnd, unsigned play_frequency_in_Hz, int latency_factor_in_Hz, int num_buffered_seconds, int playing_pool_count); -void tsShutdownContext(tsContext* ctx); - -// Call tsSpawnMixThread once to setup a separate thread for the context to run -// upon. The separate thread will continually call tsMix and perform mixing -// operations. -void tsSpawnMixThread(tsContext* ctx); - -// Use tsThreadSleepDelay to specify a custom sleep delay time. -// A sleep will occur after each call to tsMix. By default YieldProcessor -// is used, and no sleep occurs. Use a sleep delay to conserve CPU bandwidth. -// A recommended sleep time is a little less than 1/2 your predicted 1/FPS. -// 60 fps is 16 ms, so about 1-5 should work well in most cases. -void tsThreadSleepDelay(tsContext* ctx, int milliseconds); - -// Call this manually, once per game tick recommended, if you haven't ever -// called tsSpawnMixThread. Otherwise the thread will call tsMix itself. -// num_samples_to_write is not used on Windows. On Mac it is used to push -// samples into a circular buffer while CoreAudio simultaneously pulls samples -// off of the buffer. num_samples_to_write should be computed each update tick -// as delta_time * play_frequency_in_Hz + 1. -void tsMix(tsContext* ctx); - -// All of the functions in this next section should only be called if tsIsActive -// returns true. Calling them otherwise probably won't do anything bad, but it -// won't do anything at all. If a sound is active it resides in the context's -// internal list of playing sounds. -int tsIsActive(tsPlayingSound* sound); - -// Flags sound for removal. Upon next tsMix call will remove sound from playing -// list. If high-level API used sound is placed onto the internal free list. -void tsStopSound(tsPlayingSound* sound); - -void tsLoopSound(tsPlayingSound* sound, int zero_for_no_loop); -void tsPauseSound(tsPlayingSound* sound, int one_for_paused); - -// lerp from 0 to 1, 0 full left, 1 full right -void tsSetPan(tsPlayingSound* sound, float pan); - -// explicitly set volume of each channel. Can be used as panning (but it's -// recommended to use the tsSetPan function for panning). -void tsSetVolume(tsPlayingSound* sound, float volume_left, float volume_right); - -// Change pitch (not duration) of sound. pitch = 0.5f for one octave lower, pitch = 2.0f for one octave higher. -// pitch at 1.0f applies no change. pitch settings farther away from 1.0f create more distortion and lower -// the output sample quality. pitch can be adjusted in real-time for doppler effects and the like. Going beyond -// 0.5f and 2.0f may require some tweaking the pitch shifting parameters, and is not recommended. - -// Additional important information about performance: This function -// is quite expensive -- you have been warned! Try it out and be aware of how much CPU consumption it uses. -// To avoid destroying the originally loaded sound samples, tsSetPitch will do a one-time allocation to copy -// sound samples into a new buffer. The new buffer contains the pitch adjusted samples, and these will be played -// through tsMix. This lets the pitch be modulated at run-time, but requires dynamically allocated memory. The -// memory is freed once the sound finishes playing. If a one-time pitch adjustment is desired, for performance -// reasons please consider doing an off-line pitch adjustment manually as a pre-processing step for your sounds. -// Also, consider changing malloc16 and free16 to match your custom memory allocation needs. Try adjusting -// TS_PITCH_QUALITY (must be a power of two) and see how this affects your performance. -void tsSetPitch(tsPlayingSound* sound, float pitch); - -// Delays sound before actually playing it. Requires context to be passed in -// since there's a conversion from seconds to samples per second. -// If one were so inclined another version could be implemented like: -// void tsSetDelay( tsPlayingSound* sound, float delay, int samples_per_second ) -void tsSetDelay(tsContext* ctx, tsPlayingSound* sound, float delay_in_seconds); - -// Portable sleep function -void tsSleep(int milliseconds); - -// LOW-LEVEL API -tsPlayingSound tsMakePlayingSound(tsLoadedSound* loaded); -void tsInsertSound(tsContext* ctx, tsPlayingSound* sound); - -// HIGH-LEVEL API -typedef struct -{ - int paused; - int looped; - float volume_left; - float volume_right; - float pan; - float pitch; - float delay; - tsLoadedSound* loaded; -} tsPlaySoundDef; - -tsPlayingSound* tsPlaySound(tsContext* ctx, tsPlaySoundDef def); -tsPlaySoundDef tsMakeDef(tsLoadedSound* sound); -void tsStopAllSounds(tsContext* ctx); - -#define TINYSOUND_H -#endif - -#ifdef TS_IMPLEMENTATION - -#define _CRT_SECURE_NO_WARNINGS FUCK_YOU -#include <stdlib.h> // malloc, free -#include <stdio.h> // fopen, fclose -#include <string.h> // memcmp, memset, memcpy -#include <xmmintrin.h> -#include <emmintrin.h> - -#if TS_PLATFORM == TS_WINDOWS - -#include <dsound.h> -#undef PlaySound - -#if defined( _MSC_VER ) -#pragma comment( lib, "dsound.lib" ) -#endif - -#elif TS_PLATFORM == TS_MAC - -#include <CoreAudio/CoreAudio.h> -#include <AudioUnit/AudioUnit.h> -#include <pthread.h> -#include <mach/mach_time.h> - -#else - -#include "SDL2/SDL.h" - -#endif - -#define TS_CHECK( X, Y ) do { if ( !(X) ) { g_tsErrorReason = Y; goto ts_err; } } while ( 0 ) -#if TS_PLATFORM == TS_MAC && defined( __clang__ ) -#define TS_ASSERT_INTERNAL __builtin_trap( ) -#else -#define TS_ASSERT_INTERNAL *(int*)0 = 0 -#endif -#define TS_ASSERT( X ) do { if ( !(X) ) TS_ASSERT_INTERNAL; } while ( 0 ) -#define TS_ALIGN( X, Y ) ((((size_t)X) + ((Y) - 1)) & ~((Y) - 1)) -#define TS_TRUNC( X, Y ) ((size_t)(X) & ~((Y) - 1)) - -const char* g_tsErrorReason; - -static void* tsReadFileToMemory(const char* path, int* size) -{ - void* data = 0; - FILE* fp = fopen(path, "rb"); - int sizeNum = 0; - - if (fp) - { - fseek(fp, 0, SEEK_END); - sizeNum = (int)ftell(fp); - fseek(fp, 0, SEEK_SET); - data = malloc(sizeNum); - fread(data, sizeNum, 1, fp); - fclose(fp); - } - - if (size) *size = sizeNum; - return data; -} - -static int tsFourCC(const char* CC, void* memory) -{ - if (!memcmp(CC, memory, 4)) return 1; - return 0; -} - -static char* tsNext(char* data) -{ - uint32_t size = *(uint32_t*)(data + 4); - size = (size + 1) & ~1; - return data + 8 + size; -} - -static void* malloc16(size_t size) -{ - void* p = malloc(size + 16); - if (!p) return 0; - unsigned char offset = (size_t)p & 15; - p = (void*)TS_ALIGN(p + 1, 16); - *((char*)p - 1) = 16 - offset; - TS_ASSERT(!((size_t)p & 15)); - return p; -} - -static void free16(void* p) -{ - if (!p) return; - free((char*)p - (size_t)*((char*)p - 1)); -} - -static void tsLastElement(__m128* a, int i, int j, int16_t* samples, int offset) -{ - switch (offset) - { - case 1: - a[i] = _mm_set_ps(samples[j], 0.0f, 0.0f, 0.0f); - break; - - case 2: - a[i] = _mm_set_ps(samples[j], samples[j + 1], 0.0f, 0.0f); - break; - - case 3: - a[i] = _mm_set_ps(samples[j], samples[j + 1], samples[j + 2], 0.0f); - break; - - case 0: - a[i] = _mm_set_ps(samples[j], samples[j + 1], samples[j + 2], samples[j + 3]); - break; - } -} - -void tsReadMemWAV(const void* memory, tsLoadedSound* sound) -{ -#pragma pack( push, 1 ) - typedef struct - { - uint16_t wFormatTag; - uint16_t nChannels; - uint32_t nSamplesPerSec; - uint32_t nAvgBytesPerSec; - uint16_t nBlockAlign; - uint16_t wBitsPerSample; - uint16_t cbSize; - uint16_t wValidBitsPerSample; - uint32_t dwChannelMask; - uint8_t SubFormat[18]; - } Fmt; -#pragma pack( pop ) - - char* data = (char*)memory; - TS_CHECK(data, "Unable to read input file (file doesn't exist, or could not allocate heap memory."); - TS_CHECK(tsFourCC("RIFF", data), "Incorrect file header; is this a WAV file?"); - TS_CHECK(tsFourCC("WAVE", data + 8), "Incorrect file header; is this a WAV file?"); - - data += 12; - - TS_CHECK(tsFourCC("fmt ", data), "fmt chunk not found."); - Fmt fmt; - fmt = *(Fmt*)(data + 8); - TS_CHECK(fmt.wFormatTag == 1, "Only PCM WAV files are supported."); - TS_CHECK(fmt.nChannels == 1 || fmt.nChannels == 2, "Only mono or stereo supported (too many channels detected)."); - TS_CHECK(fmt.wBitsPerSample == 16, "Only 16 bits per sample supported."); - TS_CHECK(fmt.nBlockAlign == fmt.nChannels * 2, "implementation error"); - - data = tsNext(data); - TS_CHECK(tsFourCC("data", data), "data chunk not found."); - int sample_size = *((uint32_t*)(data + 4)); - int sample_count = sample_size / (fmt.nChannels * sizeof(uint16_t)); - sound->sample_count = sample_count; - sound->channel_count = fmt.nChannels; - - int wide_count = (int)TS_ALIGN(sample_count, 4); - wide_count /= 4; - int wide_offset = sample_count & 3; - int16_t* samples = (int16_t*)(data + 8); - float* sample = (float*)alloca(sizeof(float) * 4 + 16); - sample = (float*)TS_ALIGN(sample, 16); - - switch (sound->channel_count) - { - case 1: - { - sound->channels[0] = malloc16(wide_count * sizeof(__m128)); - sound->channels[1] = 0; - __m128* a = (__m128*)sound->channels[0]; - - for (int i = 0, j = 0; i < wide_count - 1; ++i, j += 4) - { - sample[0] = (float)samples[j]; - sample[1] = (float)samples[j + 1]; - sample[2] = (float)samples[j + 2]; - sample[3] = (float)samples[j + 3]; - a[i] = _mm_load_ps(sample); - } - - tsLastElement(a, wide_count - 1, (wide_count - 1) * 4, samples, wide_offset); - } break; - - case 2: - { - __m128* a = (__m128*)malloc16(wide_count * sizeof(__m128) * 2); - __m128* b = a + wide_count; - - for (int i = 0, j = 0; i < wide_count - 1; ++i, j += 8) - { - sample[0] = (float)samples[j]; - sample[1] = (float)samples[j + 2]; - sample[2] = (float)samples[j + 4]; - sample[3] = (float)samples[j + 6]; - a[i] = _mm_load_ps(sample); - - sample[0] = (float)samples[j + 1]; - sample[1] = (float)samples[j + 3]; - sample[2] = (float)samples[j + 5]; - sample[3] = (float)samples[j + 7]; - b[i] = _mm_load_ps(sample); - } - - tsLastElement(a, wide_count - 1, (wide_count - 1) * 4, samples, wide_offset); - tsLastElement(b, wide_count - 1, (wide_count - 1) * 4 + 4, samples, wide_offset); - sound->channels[0] = a; - sound->channels[1] = b; - } break; - - default: - TS_CHECK(0, "unsupported channel count (only support mono and stereo)."); - } - - return; - -ts_err: - memset(&sound, 0, sizeof(sound)); -} - -tsLoadedSound tsLoadWAV(const char* path) -{ - tsLoadedSound sound = { 0 }; - char* wav = (char*)tsReadFileToMemory(path, 0); - tsReadMemWAV(wav, &sound); - free(wav); - return sound; -} - -// If stb_vorbis was included *before* tinysound go ahead and create -// some functions for dealing with OGG files. -#ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H -void tsReadMemOGG(const void* memory, int length, int* sample_rate, tsLoadedSound* sound) -{ - int16_t* samples = 0; - int channel_count; - int sample_count = stb_vorbis_decode_memory((const unsigned char*)memory, length, &channel_count, sample_rate, &samples); - - TS_CHECK(sample_count > 0, "stb_vorbis_decode_memory failed. Make sure your file exists and is a valid OGG file."); - - int wide_count = (int)TS_ALIGN(sample_count, 4) / 4; - int wide_offset = sample_count & 3; - float* sample = (float*)alloca(sizeof(float) * 4 + 16); - sample = (float*)TS_ALIGN(sample, 16); - __m128* a; - __m128* b; - - switch (channel_count) - { - case 1: - { - a = (__m128*)malloc16(wide_count * sizeof(__m128)); - b = 0; - - for (int i = 0, j = 0; i < wide_count - 1; ++i, j += 4) - { - sample[0] = (float)samples[j]; - sample[1] = (float)samples[j + 1]; - sample[2] = (float)samples[j + 2]; - sample[3] = (float)samples[j + 3]; - a[i] = _mm_load_ps(sample); - } - - tsLastElement(a, wide_count - 1, (wide_count - 1) * 4, samples, wide_offset); - } break; - - case 2: - a = (__m128*)malloc16(wide_count * sizeof(__m128) * 2); - b = a + wide_count; - - for (int i = 0, j = 0; i < wide_count - 1; ++i, j += 8) - { - sample[0] = (float)samples[j]; - sample[1] = (float)samples[j + 2]; - sample[2] = (float)samples[j + 4]; - sample[3] = (float)samples[j + 6]; - a[i] = _mm_load_ps(sample); - - sample[0] = (float)samples[j + 1]; - sample[1] = (float)samples[j + 3]; - sample[2] = (float)samples[j + 5]; - sample[3] = (float)samples[j + 7]; - b[i] = _mm_load_ps(sample); - } - - tsLastElement(a, wide_count - 1, (wide_count - 1) * 4, samples, wide_offset); - tsLastElement(b, wide_count - 1, (wide_count - 1) * 4 + 4, samples, wide_offset); - break; - - default: - TS_CHECK(0, "Unsupported channel count."); - } - - sound->sample_count = sample_count; - sound->channel_count = channel_count; - sound->channels[0] = a; - sound->channels[1] = b; - free(samples); - return; - -ts_err: - free(samples); - memset(sound, 0, sizeof(tsLoadedSound)); -} - -tsLoadedSound tsLoadOGG(const char* path, int* sample_rate) -{ - int length; - void* memory = tsReadFileToMemory(path, &length); - tsLoadedSound sound; - tsReadMemOGG(memory, length, sample_rate, &sound); - free(memory); - - return sound; -} -#endif - -void tsFreeSound(tsLoadedSound* sound) -{ - free16(sound->channels[0]); - memset(sound, 0, sizeof(tsLoadedSound)); -} - -int tsSoundSize(tsLoadedSound* sound) -{ - return sound->sample_count * sound->channel_count * sizeof(uint16_t); -} - -tsPlayingSound tsMakePlayingSound(tsLoadedSound* loaded) -{ - tsPlayingSound playing; - playing.active = 0; - playing.paused = 0; - playing.looped = 0; - playing.volume0 = 1.0f; - playing.volume1 = 1.0f; - playing.pan0 = 0.5f; - playing.pan1 = 0.5f; - playing.pitch = 1.0f; - playing.pitch_filter[0] = 0; - playing.pitch_filter[1] = 0; - playing.sample_index = 0; - playing.loaded_sound = loaded; - playing.next = 0; - return playing; -} - -int tsIsActive(tsPlayingSound* sound) -{ - return sound->active; -} - -void tsStopSound(tsPlayingSound* sound) -{ - sound->active = 0; -} - -void tsLoopSound(tsPlayingSound* sound, int zero_for_no_loop) -{ - sound->looped = zero_for_no_loop; -} - -void tsPauseSound(tsPlayingSound* sound, int one_for_paused) -{ - sound->paused = one_for_paused; -} - -void tsSetPan(tsPlayingSound* sound, float pan) -{ - if (pan > 1.0f) pan = 1.0f; - else if (pan < 0.0f) pan = 0.0f; - float left = 1.0f - pan; - float right = pan; - sound->pan0 = left; - sound->pan1 = right; -} - -void tsSetPitch(tsPlayingSound* sound, float pitch) -{ - sound->pitch = pitch; -} - -void tsSetVolume(tsPlayingSound* sound, float volume_left, float volume_right) -{ - if (volume_left < 0.0f) volume_left = 0.0f; - if (volume_right < 0.0f) volume_right = 0.0f; - sound->volume0 = volume_left; - sound->volume1 = volume_right; -} - -static void tsRemoveFilter(tsPlayingSound* playing); - -#if TS_PLATFORM == TS_WINDOWS - -void tsSleep(int milliseconds) -{ - Sleep(milliseconds); -} - -struct tsContext -{ - unsigned latency_samples; - unsigned running_index; - int Hz; - int bps; - int buffer_size; - int wide_count; - tsPlayingSound* playing; - __m128* floatA; - __m128* floatB; - __m128i* samples; - tsPlayingSound* playing_pool; - tsPlayingSound* playing_free; - - // platform specific stuff - LPDIRECTSOUND dsound; - LPDIRECTSOUNDBUFFER buffer; - LPDIRECTSOUNDBUFFER primary; - - // data for tsMix thread, enable these with tsSpawnMixThread - CRITICAL_SECTION critical_section; - int separate_thread; - int running; - int sleep_milliseconds; -}; - -static void tsReleaseContext(tsContext* ctx) -{ - if (ctx->separate_thread) DeleteCriticalSection(&ctx->critical_section); -#ifdef __cplusplus - ctx->buffer->Release(); - ctx->primary->Release(); - ctx->dsound->Release(); -#else - ctx->buffer->lpVtbl->Release(ctx->buffer); - ctx->primary->lpVtbl->Release(ctx->primary); - ctx->dsound->lpVtbl->Release(ctx->dsound); -#endif - tsPlayingSound* playing = ctx->playing; - while (playing) - { - tsRemoveFilter(playing); - playing = playing->next; - } - free(ctx); -} - -static DWORD WINAPI tsCtxThread(LPVOID lpParameter) -{ - tsContext* ctx = (tsContext*)lpParameter; - - while (ctx->running) - { - tsMix(ctx); - if (ctx->sleep_milliseconds) tsSleep(ctx->sleep_milliseconds); - else YieldProcessor(); - } - - ctx->separate_thread = 0; - return 0; -} - -static void tsLock(tsContext* ctx) -{ - if (ctx->separate_thread) EnterCriticalSection(&ctx->critical_section); -} - -static void tsUnlock(tsContext* ctx) -{ - if (ctx->separate_thread) LeaveCriticalSection(&ctx->critical_section); -} - -tsContext* tsMakeContext(void* hwnd, unsigned play_frequency_in_Hz, int latency_factor_in_Hz, int num_buffered_seconds, int playing_pool_count) -{ - int bps = sizeof(INT16) * 2; - int buffer_size = play_frequency_in_Hz * bps * num_buffered_seconds; - tsContext* ctx = 0; - WAVEFORMATEX format = { 0 }; - DSBUFFERDESC bufdesc = { 0 }; - LPDIRECTSOUND dsound; - - TS_CHECK(hwnd, "Invalid hwnd passed to tsMakeContext."); - - HRESULT res = DirectSoundCreate(0, &dsound, 0); - TS_CHECK(res == DS_OK, "DirectSoundCreate failed"); -#ifdef __cplusplus - dsound->SetCooperativeLevel((HWND)hwnd, DSSCL_PRIORITY); -#else - dsound->lpVtbl->SetCooperativeLevel(dsound, (HWND)hwnd, DSSCL_PRIORITY); -#endif - bufdesc.dwSize = sizeof(bufdesc); - bufdesc.dwFlags = DSBCAPS_PRIMARYBUFFER; - - LPDIRECTSOUNDBUFFER primary_buffer; -#ifdef __cplusplus - res = dsound->CreateSoundBuffer(&bufdesc, &primary_buffer, 0); -#else - res = dsound->lpVtbl->CreateSoundBuffer(dsound, &bufdesc, &primary_buffer, 0); -#endif - TS_CHECK(res == DS_OK, "Failed to create primary sound buffer"); - - format.wFormatTag = WAVE_FORMAT_PCM; - format.nChannels = 2; - format.nSamplesPerSec = play_frequency_in_Hz; - format.wBitsPerSample = 16; - format.nBlockAlign = (format.nChannels * format.wBitsPerSample) / 8; - format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign; - format.cbSize = 0; -#ifdef __cplusplus - res = primary_buffer->SetFormat(&format); -#else - res = primary_buffer->lpVtbl->SetFormat(primary_buffer, &format); -#endif - TS_CHECK(res == DS_OK, "Failed to set format on primary buffer"); - - LPDIRECTSOUNDBUFFER secondary_buffer; - bufdesc.dwSize = sizeof(bufdesc); - bufdesc.dwFlags = 0; - bufdesc.dwBufferBytes = buffer_size; - bufdesc.lpwfxFormat = &format; -#ifdef __cplusplus - res = dsound->CreateSoundBuffer(&bufdesc, &secondary_buffer, 0); -#else - res = dsound->lpVtbl->CreateSoundBuffer(dsound, &bufdesc, &secondary_buffer, 0); -#endif - TS_CHECK(res == DS_OK, "Failed to set format on secondary buffer"); - - int sample_count = play_frequency_in_Hz * num_buffered_seconds; - int wide_count = (int)TS_ALIGN(sample_count, 4); - int pool_size = playing_pool_count * sizeof(tsPlayingSound); - int mix_buffers_size = sizeof(__m128) * wide_count * 2; - int sample_buffer_size = sizeof(__m128i) * wide_count; - ctx = (tsContext*)malloc(sizeof(tsContext) + mix_buffers_size + sample_buffer_size + 16 + pool_size); - ctx->latency_samples = (unsigned)TS_ALIGN(play_frequency_in_Hz / latency_factor_in_Hz, 4); - ctx->running_index = 0; - ctx->Hz = play_frequency_in_Hz; - ctx->bps = bps; - ctx->buffer_size = buffer_size; - ctx->wide_count = wide_count; - ctx->dsound = dsound; - ctx->buffer = secondary_buffer; - ctx->primary = primary_buffer; - ctx->playing = 0; - ctx->floatA = (__m128*)(ctx + 1); - ctx->floatA = (__m128*)TS_ALIGN(ctx->floatA, 16); - TS_ASSERT(!((size_t)ctx->floatA & 15)); - ctx->floatB = ctx->floatA + wide_count; - ctx->samples = (__m128i*)ctx->floatB + wide_count; - ctx->running = 1; - ctx->separate_thread = 0; - ctx->sleep_milliseconds = 0; - - if (playing_pool_count) - { - ctx->playing_pool = (tsPlayingSound*)(ctx->samples + wide_count); - for (int i = 0; i < playing_pool_count - 1; ++i) - ctx->playing_pool[i].next = ctx->playing_pool + i + 1; - ctx->playing_pool[playing_pool_count - 1].next = 0; - ctx->playing_free = ctx->playing_pool; - } - - else - { - ctx->playing_pool = 0; - ctx->playing_free = 0; - } - - return ctx; - -ts_err: - free(ctx); - return 0; -} - -void tsSpawnMixThread(tsContext* ctx) -{ - if (ctx->separate_thread) return; - InitializeCriticalSectionAndSpinCount(&ctx->critical_section, 0x00000400); - ctx->separate_thread = 1; - CreateThread(0, 0, tsCtxThread, ctx, 0, 0); -} - -#elif TS_PLATFORM == TS_MAC - -void tsSleep(int milliseconds) -{ - usleep(milliseconds * 1000); -} - -struct tsContext -{ - unsigned latency_samples; - unsigned index0; // read - unsigned index1; // write - int Hz; - int bps; - int wide_count; - int sample_count; - tsPlayingSound* playing; - __m128* floatA; - __m128* floatB; - __m128i* samples; - tsPlayingSound* playing_pool; - tsPlayingSound* playing_free; - - // platform specific stuff - AudioComponentInstance inst; - - // data for tsMix thread, enable these with tsSpawnMixThread - pthread_t thread; - pthread_mutex_t mutex; - int separate_thread; - int running; - int sleep_milliseconds; -}; - -static void tsReleaseContext(tsContext* ctx) -{ - if (ctx->separate_thread) pthread_mutex_destroy(&ctx->mutex); - AudioOutputUnitStop(ctx->inst); - AudioUnitUninitialize(ctx->inst); - AudioComponentInstanceDispose(ctx->inst); - tsPlayingSound* playing = ctx->playing; - while (playing) - { - tsRemoveFilter(playing); - playing = playing->next; - } - free(ctx); -} - -static void* tsCtxThread(void* udata) -{ - tsContext* ctx = (tsContext*)udata; - - while (ctx->running) - { - tsMix(ctx); - if (ctx->sleep_milliseconds) tsSleep(ctx->sleep_milliseconds); - else pthread_yield_np(); - } - - ctx->separate_thread = 0; - pthread_exit(0); - return 0; -} - -static void tsLock(tsContext* ctx) -{ - if (ctx->separate_thread) pthread_mutex_lock(&ctx->mutex); -} - -static void tsUnlock(tsContext* ctx) -{ - if (ctx->separate_thread) pthread_mutex_unlock(&ctx->mutex); -} - -static OSStatus tsMemcpyToCA(void* udata, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); - -tsContext* tsMakeContext(void* unused, unsigned play_frequency_in_Hz, int latency_factor_in_Hz, int num_buffered_seconds, int playing_pool_count) -{ - int bps = sizeof(uint16_t) * 2; - - AudioComponentDescription comp_desc = { 0 }; - comp_desc.componentType = kAudioUnitType_Output; - comp_desc.componentSubType = kAudioUnitSubType_DefaultOutput; - comp_desc.componentFlags = 0; - comp_desc.componentFlagsMask = 0; - comp_desc.componentManufacturer = kAudioUnitManufacturer_Apple; - - AudioComponent comp = AudioComponentFindNext(NULL, &comp_desc); - if (!comp) - { - g_tsErrorReason = "Failed to create output unit from AudioComponentFindNext."; - return 0; - } - - AudioStreamBasicDescription stream_desc = { 0 }; - stream_desc.mSampleRate = (double)play_frequency_in_Hz; - stream_desc.mFormatID = kAudioFormatLinearPCM; - stream_desc.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - stream_desc.mFramesPerPacket = 1; - stream_desc.mChannelsPerFrame = 2; - stream_desc.mBitsPerChannel = sizeof(uint16_t) * 8; - stream_desc.mBytesPerPacket = bps; - stream_desc.mBytesPerFrame = bps; - stream_desc.mReserved = 0; - - AudioComponentInstance inst; - OSStatus ret; - AURenderCallbackStruct input; - - ret = AudioComponentInstanceNew(comp, &inst); - - int sample_count = play_frequency_in_Hz * num_buffered_seconds; - int latency_count = (unsigned)TS_ALIGN(play_frequency_in_Hz / latency_factor_in_Hz, 4); - TS_ASSERT(sample_count > latency_count); - int wide_count = (int)TS_ALIGN(sample_count, 4) / 4; - int pool_size = playing_pool_count * sizeof(tsPlayingSound); - int mix_buffers_size = sizeof(__m128) * wide_count * 2; - int sample_buffer_size = sizeof(__m128i) * wide_count; - tsContext* ctx = (tsContext*)malloc(sizeof(tsContext) + mix_buffers_size + sample_buffer_size + 16 + pool_size); - TS_CHECK(ret == noErr, "AudioComponentInstanceNew failed"); - ctx->latency_samples = latency_count; - ctx->index0 = 0; - ctx->index1 = 0; - ctx->Hz = play_frequency_in_Hz; - ctx->bps = bps; - ctx->wide_count = wide_count; - ctx->sample_count = wide_count * 4; - ctx->inst = inst; - ctx->playing = 0; - ctx->floatA = (__m128*)(ctx + 1); - ctx->floatA = (__m128*)TS_ALIGN(ctx->floatA, 16); - TS_ASSERT(!((size_t)ctx->floatA & 15)); - ctx->floatB = ctx->floatA + wide_count; - ctx->samples = (__m128i*)ctx->floatB + wide_count; - ctx->running = 1; - ctx->separate_thread = 0; - ctx->sleep_milliseconds = 0; - - ret = AudioUnitSetProperty(inst, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &stream_desc, sizeof(stream_desc)); - TS_CHECK(ret == noErr, "Failed to set stream forat"); - - input.inputProc = tsMemcpyToCA; - input.inputProcRefCon = ctx; - ret = AudioUnitSetProperty(inst, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, sizeof(input)); - TS_CHECK(ret == noErr, "AudioUnitSetProperty failed"); - - ret = AudioUnitInitialize(inst); - TS_CHECK(ret == noErr, "Couldn't initialize output unit"); - - ret = AudioOutputUnitStart(inst); - TS_CHECK(ret == noErr, "Couldn't start output unit"); - - if (playing_pool_count) - { - ctx->playing_pool = (tsPlayingSound*)(ctx->samples + wide_count); - for (int i = 0; i < playing_pool_count - 1; ++i) - ctx->playing_pool[i].next = ctx->playing_pool + i + 1; - ctx->playing_pool[playing_pool_count - 1].next = 0; - ctx->playing_free = ctx->playing_pool; - } - - else - { - ctx->playing_pool = 0; - ctx->playing_free = 0; - } - - return ctx; - -ts_err: - free(ctx); - return 0; -} - -void tsSpawnMixThread(tsContext* ctx) -{ - if (ctx->separate_thread) return; - pthread_mutex_init(&ctx->mutex, 0); - ctx->separate_thread = 1; - pthread_create(&ctx->thread, 0, tsCtxThread, ctx); -} - -#else - -void tsSleep(int milliseconds) -{ - SDL_Delay(milliseconds); -} - -struct tsContext -{ - unsigned latency_samples; - unsigned index0; // read - unsigned index1; // write - unsigned running_index; - int Hz; - int bps; - int buffer_size; - int wide_count; - int sample_count; - tsPlayingSound* playing; - __m128* floatA; - __m128* floatB; - __m128i* samples; - tsPlayingSound* playing_pool; - tsPlayingSound* playing_free; - - // data for tsMix thread, enable these with tsSpawnMixThread - SDL_Thread* thread; - SDL_mutex* mutex; - int separate_thread; - int running; - int sleep_milliseconds; -}; - -static void tsReleaseContext(tsContext* ctx) -{ - if (ctx->separate_thread) SDL_DestroyMutex(ctx->mutex); - tsPlayingSound* playing = ctx->playing; - while (playing) - { - tsRemoveFilter(playing); - playing = playing->next; - } - SDL_CloseAudio(); - free(ctx); -} - -int tsCtxThread(void* udata) -{ - tsContext* ctx = (tsContext*)udata; - - while (ctx->running) - { - tsMix(ctx); - if (ctx->sleep_milliseconds) tsSleep(ctx->sleep_milliseconds); - else tsSleep(1); - } - - ctx->separate_thread = 0; - return 0; -} - -static void tsLock(tsContext* ctx) -{ - if (ctx->separate_thread) SDL_LockMutex(ctx->mutex); -} - -static void tsUnlock(tsContext* ctx) -{ - if (ctx->separate_thread) SDL_UnlockMutex(ctx->mutex); -} - -void tsSDL_AudioCallback(void* udata, Uint8* stream, int len); - -tsContext* tsMakeContext(void* unused, unsigned play_frequency_in_Hz, int latency_factor_in_Hz, int num_buffered_seconds, int playing_pool_count) -{ - (void)unused; - int bps = sizeof(uint16_t) * 2; - int sample_count = play_frequency_in_Hz * num_buffered_seconds; - int latency_count = (unsigned)TS_ALIGN(play_frequency_in_Hz / latency_factor_in_Hz, 4); - TS_ASSERT(sample_count > latency_count); - int wide_count = (int)TS_ALIGN(sample_count, 4) / 4; - int pool_size = playing_pool_count * sizeof(tsPlayingSound); - int mix_buffers_size = sizeof(__m128) * wide_count * 2; - int sample_buffer_size = sizeof(__m128i) * wide_count; - tsContext* ctx = 0; - SDL_AudioSpec wanted; - int ret = SDL_Init(SDL_INIT_AUDIO); - TS_CHECK(ret >= 0, "Can't init SDL audio"); - - ctx = (tsContext*)malloc(sizeof(tsContext) + mix_buffers_size + sample_buffer_size + 16 + pool_size); - TS_CHECK(ctx != NULL, "Can't create audio context"); - ctx->latency_samples = latency_count; - ctx->index0 = 0; - ctx->index1 = 0; - ctx->Hz = play_frequency_in_Hz; - ctx->bps = bps; - ctx->wide_count = wide_count; - ctx->sample_count = wide_count * 4; - ctx->playing = 0; - ctx->floatA = (__m128*)(ctx + 1); - ctx->floatA = (__m128*)TS_ALIGN(ctx->floatA, 16); - TS_ASSERT(!((size_t)ctx->floatA & 15)); - ctx->floatB = ctx->floatA + wide_count; - ctx->samples = (__m128i*)ctx->floatB + wide_count; - ctx->running = 1; - ctx->separate_thread = 0; - ctx->sleep_milliseconds = 0; - - SDL_memset(&wanted, 0, sizeof(wanted)); - wanted.freq = play_frequency_in_Hz; - wanted.format = AUDIO_S16SYS; - wanted.channels = 2; /* 1 = mono, 2 = stereo */ - wanted.samples = 1024; - wanted.callback = tsSDL_AudioCallback; - wanted.userdata = ctx; - ret = SDL_OpenAudio(&wanted, NULL); - TS_CHECK(ret >= 0, "Can't open SDL audio"); - SDL_PauseAudio(0); - - if (playing_pool_count) - { - ctx->playing_pool = (tsPlayingSound*)(ctx->samples + wide_count); - for (int i = 0; i < playing_pool_count - 1; ++i) - ctx->playing_pool[i].next = ctx->playing_pool + i + 1; - ctx->playing_pool[playing_pool_count - 1].next = 0; - ctx->playing_free = ctx->playing_pool; - } - - else - { - ctx->playing_pool = 0; - ctx->playing_free = 0; - } - - return ctx; - -ts_err: - if (ctx) free(ctx); - return 0; -} - -void tsSpawnMixThread(tsContext* ctx) -{ - if (ctx->separate_thread) return; - ctx->mutex = SDL_CreateMutex(); - ctx->separate_thread = 1; - ctx->thread = SDL_CreateThread(&tsCtxThread, "TinySoundThread", ctx); -} - -#endif - -#if TS_PLATFORM == TS_SDL || TS_PLATFORM == TS_MAC - -static int tsSamplesWritten(tsContext* ctx) -{ - int index0 = ctx->index0; - int index1 = ctx->index1; - if (index0 <= index1) return index1 - index0; - else return ctx->sample_count - index0 + index1; -} - -static int tsSamplesUnwritten(tsContext* ctx) -{ - int index0 = ctx->index0; - int index1 = ctx->index1; - if (index0 <= index1) return ctx->sample_count - index1 + index0; - else return index0 - index1; -} - -static int tsSamplesToMix(tsContext* ctx) -{ - int lat = ctx->latency_samples; - int written = tsSamplesWritten(ctx); - int dif = lat - written; - TS_ASSERT(dif >= 0); - if (dif) - { - int unwritten = tsSamplesUnwritten(ctx); - return dif < unwritten ? dif : unwritten; - } - return 0; -} - -#define TS_SAMPLES_TO_BYTES( interleaved_sample_count ) ((interleaved_sample_count) * ctx->bps) -#define TS_BYTES_TO_SAMPLES( byte_count ) ((byte_count) / ctx->bps) - -static void tsPushBytes(tsContext* ctx, void* data, int size) -{ - int index0 = ctx->index0; - int index1 = ctx->index1; - int samples = TS_BYTES_TO_SAMPLES(size); - int sample_count = ctx->sample_count; - - int unwritten = tsSamplesUnwritten(ctx); - if (unwritten < samples) samples = unwritten; - int can_overflow = index0 <= index1; - int would_overflow = index1 + samples > sample_count; - - if (can_overflow && would_overflow) - { - int first_size = TS_SAMPLES_TO_BYTES(sample_count - index1); - int second_size = size - first_size; - memcpy((char*)ctx->samples + TS_SAMPLES_TO_BYTES(index1), data, first_size); - memcpy(ctx->samples, (char*)data + first_size, second_size); - ctx->index1 = TS_BYTES_TO_SAMPLES(second_size); - } - - else - { - memcpy((char*)ctx->samples + TS_SAMPLES_TO_BYTES(index1), data, size); - ctx->index1 += TS_BYTES_TO_SAMPLES(size); - } -} - -static int tsPullBytes(tsContext* ctx, void* dst, int size) -{ - int index0 = ctx->index0; - int index1 = ctx->index1; - int allowed_size = TS_SAMPLES_TO_BYTES(tsSamplesWritten(ctx)); - int zeros = 0; - - if (allowed_size < size) - { - zeros = size - allowed_size; - size = allowed_size; - } - - if (index1 >= index0) - { - memcpy(dst, ((char*)ctx->samples) + TS_SAMPLES_TO_BYTES(index0), size); - ctx->index0 += TS_BYTES_TO_SAMPLES(size); - } - - else - { - int first_size = TS_SAMPLES_TO_BYTES(ctx->sample_count) - TS_SAMPLES_TO_BYTES(index0); - if (first_size > size) first_size = size; - int second_size = size - first_size; - memcpy(dst, ((char*)ctx->samples) + TS_SAMPLES_TO_BYTES(index0), first_size); - memcpy(((char*)dst) + first_size, ctx->samples, second_size); - if (second_size) ctx->index0 = TS_BYTES_TO_SAMPLES(second_size); - else ctx->index0 += TS_BYTES_TO_SAMPLES(first_size); - } - - return zeros; -} - -#endif - -void tsShutdownContext(tsContext* ctx) -{ - if (ctx->separate_thread) - { - tsLock(ctx); - ctx->running = 0; - tsUnlock(ctx); - } - - while (ctx->separate_thread) tsSleep(1); - tsReleaseContext(ctx); -} - -void tsThreadSleepDelay(tsContext* ctx, int milliseconds) -{ - ctx->sleep_milliseconds = milliseconds; -} - -void tsInsertSound(tsContext* ctx, tsPlayingSound* sound) -{ - // Cannot use tsPlayingSound if tsMakeContext was passed non-zero for playing_pool_count - // since non-zero playing_pool_count means the context is doing some memory-management - // for a playing sound pool. InsertSound assumes the pool does not exist, and is apart - // of the lower-level API (see top of this header for documentation details). - TS_ASSERT(ctx->playing_pool == 0); - - if (sound->active) return; - tsLock(ctx); - sound->next = ctx->playing; - ctx->playing = sound; - sound->active = 1; - tsUnlock(ctx); -} - -// NOTE: does not allow delay_in_seconds to be negative (clamps at 0) -void tsSetDelay(tsContext* ctx, tsPlayingSound* sound, float delay_in_seconds) -{ - if (delay_in_seconds < 0.0f) delay_in_seconds = 0.0f; - sound->sample_index = (int)(delay_in_seconds * (float)ctx->Hz); - sound->sample_index = -(int)TS_ALIGN(sound->sample_index, 4); -} - -tsPlaySoundDef tsMakeDef(tsLoadedSound* sound) -{ - tsPlaySoundDef def; - def.paused = 0; - def.looped = 0; - def.volume_left = 1.0f; - def.volume_right = 1.0f; - def.pan = 0.5f; - def.pitch = 1.0f; - def.delay = 0.0f; - def.loaded = sound; - return def; -} - -tsPlayingSound* tsPlaySound(tsContext* ctx, tsPlaySoundDef def) -{ - tsLock(ctx); - - tsPlayingSound* playing = ctx->playing_free; - if (!playing) return 0; - ctx->playing_free = playing->next; - *playing = tsMakePlayingSound(def.loaded); - playing->active = 1; - playing->paused = def.paused; - playing->looped = def.looped; - tsSetVolume(playing, def.volume_left, def.volume_right); - tsSetPan(playing, def.pan); - tsSetPitch(playing, def.pitch); - tsSetDelay(ctx, playing, def.delay); - playing->next = ctx->playing; - ctx->playing = playing; - - tsUnlock(ctx); - - return playing; -} - -void tsStopAllSounds(tsContext* ctx) -{ - // This is apart of the high level API, not the low level API. - // If using the low level API you must write your own function to - // stop playing all sounds. - TS_ASSERT(ctx->playing_pool == 0); - - tsPlayingSound* sound = ctx->playing; - ctx->playing = 0; - - while (sound) - { - tsPlayingSound* next = sound->next; - sound->next = ctx->playing_free; - ctx->playing_free = sound; - sound = next; - } -} - -#if TS_PLATFORM == TS_WINDOWS - -static void tsPosition(tsContext* ctx, int* byte_to_lock, int* bytes_to_write) -{ - // compute bytes to be written to direct sound - DWORD play_cursor; - DWORD write_cursor; -#ifdef __cplusplus - HRESULT hr = ctx->buffer->GetCurrentPosition(&play_cursor, &write_cursor); -#else - HRESULT hr = ctx->buffer->lpVtbl->GetCurrentPosition(ctx->buffer, &play_cursor, &write_cursor); -#endif - TS_ASSERT(hr == DS_OK); - - DWORD lock = (ctx->running_index * ctx->bps) % ctx->buffer_size; - DWORD target_cursor = (write_cursor + ctx->latency_samples * ctx->bps) % ctx->buffer_size; - target_cursor = (DWORD)TS_ALIGN(target_cursor, 16); - DWORD write; - - if (lock > target_cursor) - { - write = (ctx->buffer_size - lock) + target_cursor; - } - - else - { - write = target_cursor - lock; - } - - *byte_to_lock = lock; - *bytes_to_write = write; -} - -static void tsMemcpyToDS(tsContext* ctx, int16_t* samples, int byte_to_lock, int bytes_to_write) -{ - // copy mixer buffers to direct sound - void* region1; - DWORD size1; - void* region2; - DWORD size2; -#ifdef __cplusplus - HRESULT hr = ctx->buffer->Lock(byte_to_lock, bytes_to_write, ®ion1, &size1, ®ion2, &size2, 0); - - if (hr == DSERR_BUFFERLOST) - { - ctx->buffer->Restore(); - hr = ctx->buffer->Lock(byte_to_lock, bytes_to_write, ®ion1, &size1, ®ion2, &size2, 0); - } -#else - HRESULT hr = ctx->buffer->lpVtbl->Lock(ctx->buffer, byte_to_lock, bytes_to_write, ®ion1, &size1, ®ion2, &size2, 0); - - if (hr == DSERR_BUFFERLOST) - { - ctx->buffer->lpVtbl->Restore(ctx->buffer); - hr = ctx->buffer->lpVtbl->Lock(ctx->buffer, byte_to_lock, bytes_to_write, ®ion1, &size1, ®ion2, &size2, 0); - } -#endif - - if (!SUCCEEDED(hr)) - return; - - unsigned running_index = ctx->running_index; - INT16* sample1 = (INT16*)region1; - DWORD sample1_count = size1 / ctx->bps; - memcpy(sample1, samples, sample1_count * sizeof(INT16) * 2); - samples += sample1_count * 2; - running_index += sample1_count; - - INT16* sample2 = (INT16*)region2; - DWORD sample2_count = size2 / ctx->bps; - memcpy(sample2, samples, sample2_count * sizeof(INT16) * 2); - samples += sample2_count * 2; - running_index += sample2_count; - -#ifdef __cplusplus - ctx->buffer->Unlock(region1, size1, region2, size2); -#else - ctx->buffer->lpVtbl->Unlock(ctx->buffer, region1, size1, region2, size2); -#endif - ctx->running_index = running_index; - - // meager hack to fill out sound buffer before playing - static int first; - if (!first) - { -#ifdef __cplusplus - ctx->buffer->Play(0, 0, DSBPLAY_LOOPING); -#else - ctx->buffer->lpVtbl->Play(ctx->buffer, 0, 0, DSBPLAY_LOOPING); -#endif - first = 1; - } -} - -#elif TS_PLATFORM == TS_MAC - -static OSStatus tsMemcpyToCA(void* udata, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData) -{ - tsContext* ctx = (tsContext*)udata; - int bps = ctx->bps; - int samples_requested_to_consume = inNumberFrames; - AudioBuffer* buffer = ioData->mBuffers; - - TS_ASSERT(ioData->mNumberBuffers == 1); - TS_ASSERT(buffer->mNumberChannels == 2); - int byte_size = buffer->mDataByteSize; - TS_ASSERT(byte_size == samples_requested_to_consume * bps); - - int zero_bytes = tsPullBytes(ctx, buffer->mData, byte_size); - memset(((char*)buffer->mData) + (byte_size - zero_bytes), 0, zero_bytes); - - return noErr; -} - -#elif TS_PLATFORM == TS_SDL - -static void tsSDL_AudioCallback(void* udata, Uint8* stream, int len) -{ - tsContext* ctx = (tsContext*)udata; - int zero_bytes = tsPullBytes(ctx, stream, len); - memset(stream + (len - zero_bytes), 0, zero_bytes); -} - -#endif - -static void tsPitchShift(float pitchShift, int num_samples_to_process, float sampleRate, float* indata, tsPitchData** pitch_filter); - -// Pitch processing tunables -#define TS_MAX_FRAME_LENGTH 4096 -#define TS_PITCH_FRAME_SIZE 512 -#define TS_PITCH_QUALITY 8 - -// interals -#define TS_STEPSIZE (TS_PITCH_FRAME_SIZE / TS_PITCH_QUALITY) -#define TS_OVERLAP (TS_PITCH_FRAME_SIZE - TS_STEPSIZE) -#define TS_EXPECTED_FREQUENCY (2.0f * 3.14159265359f * (float)TS_STEPSIZE / (float)TS_PITCH_FRAME_SIZE) - -// TODO: -// Use a memory pool for these things. For now they are just malloc16'd/free16'd -// Not high priority to use a pool, since pitch shifting is already really expensive, -// and cost of malloc is dwarfed. But would be a nice-to-have for potential memory -// fragmentation issues. -typedef struct tsPitchData -{ - float pitch_shifted_output_samples[TS_MAX_FRAME_LENGTH]; - float in_FIFO[TS_STEPSIZE + TS_PITCH_FRAME_SIZE]; - float out_FIFO[TS_STEPSIZE + TS_PITCH_FRAME_SIZE]; - float fft_data[2 * TS_PITCH_FRAME_SIZE]; - float previous_phase[TS_PITCH_FRAME_SIZE / 2 + 4]; - float sum_phase[TS_PITCH_FRAME_SIZE / 2 + 4]; - float window_accumulator[TS_STEPSIZE + TS_PITCH_FRAME_SIZE]; - float freq[TS_PITCH_FRAME_SIZE]; - float mag[TS_PITCH_FRAME_SIZE]; - float pitch_shift_workspace[TS_PITCH_FRAME_SIZE]; - int index; -} tsPitchData; - -static void tsRemoveFilter(tsPlayingSound* playing) -{ - for (int i = 0; i < 2; i++) - { - if (playing->pitch_filter[i]) - { - free16(playing->pitch_filter[i]); - playing->pitch_filter[i] = 0; - } - } -} - -void tsMix(tsContext* ctx) -{ - tsLock(ctx); - -#if TS_PLATFORM == TS_WINDOWS - - int byte_to_lock; - int bytes_to_write; - tsPosition(ctx, &byte_to_lock, &bytes_to_write); - - if (!bytes_to_write) goto unlock; - int samples_to_write = bytes_to_write / ctx->bps; - -#elif TS_PLATFORM == TS_MAC || TS_PLATFORM == TS_SDL - - int samples_to_write = tsSamplesToMix(ctx); - if (!samples_to_write) goto unlock; - int bytes_to_write = samples_to_write * ctx->bps; - -#else -#endif - - // clear mixer buffers - int wide_count = samples_to_write / 4; - TS_ASSERT(!(samples_to_write & 3)); - - __m128* floatA = ctx->floatA; - __m128* floatB = ctx->floatB; - __m128 zero = _mm_set1_ps(0.0f); - - for (int i = 0; i < wide_count; ++i) - { - floatA[i] = zero; - floatB[i] = zero; - } - - // mix all playing sounds into the mixer buffers - tsPlayingSound** ptr = &ctx->playing; - while (*ptr) - { - tsPlayingSound* playing = *ptr; - tsLoadedSound* loaded = playing->loaded_sound; - __m128* cA = (__m128*)loaded->channels[0]; - __m128* cB = (__m128*)loaded->channels[1]; - - // Attempted to play a sound with no audio. - // Make sure the audio file was loaded properly. Check for - // error messages in g_tsErrorReason. - TS_ASSERT(cA); - - int mix_count = samples_to_write; - int offset = playing->sample_index; - int remaining = loaded->sample_count - offset; - if (remaining < mix_count) mix_count = remaining; - TS_ASSERT(remaining > 0); - - float vA0 = playing->volume0 * playing->pan0; - float vB0 = playing->volume1 * playing->pan1; - __m128 vA = _mm_set1_ps(vA0); - __m128 vB = _mm_set1_ps(vB0); - - // skip sound if it's delay is longer than mix_count and - // handle various delay cases - int delay_offset = 0; - if (offset < 0) - { - int samples_till_positive = -offset; - int mix_leftover = mix_count - samples_till_positive; - - if (mix_leftover <= 0) - { - playing->sample_index += mix_count; - goto get_next_playing_sound; - } - - else - { - offset = 0; - delay_offset = samples_till_positive; - mix_count = mix_leftover; - } - } - TS_ASSERT(!(delay_offset & 3)); - - // immediately remove any inactive elements - if (!playing->active || !ctx->running) - goto remove; - - // skip all paused sounds - if (playing->paused) - goto get_next_playing_sound; - - // SIMD offets - int mix_wide = (int)TS_ALIGN(mix_count, 4) / 4; - int offset_wide = (int)TS_TRUNC(offset, 4) / 4; - int delay_wide = (int)TS_ALIGN(delay_offset, 4) / 4; - - // use tsPitchShift to on-the-fly pitch shift some samples - // only call this function if the user set a custom pitch value - if (playing->pitch != 1.0f) - { - int sample_count = (mix_wide - 2 * delay_wide) * 4; - int falling_behind = sample_count > TS_MAX_FRAME_LENGTH; - - // TS_MAX_FRAME_LENGTH represents max samples we can pitch shift in one go. In the event - // that this process takes longer than the time required to play the actual sound, just - // fall back to the original sound (non-pitch shifted). This will sound very ugly. To - // prevent falling behind, make sure not to pitch shift too many sounds at once. Try tweaking - // TS_PITCH_QUALITY to make it lower (must be a power of 2). - if (!falling_behind) - { - tsPitchShift(playing->pitch, sample_count, (float)ctx->Hz, (float*)(cA + delay_wide + offset_wide), playing->pitch_filter); - cA = (__m128 *)playing->pitch_filter[0]->pitch_shifted_output_samples; - - if (loaded->channel_count == 2) - { - tsPitchShift(playing->pitch, sample_count, (float)ctx->Hz, (float*)(cB + delay_wide + offset_wide), playing->pitch_filter + 1); - cB = (__m128 *)playing->pitch_filter[1]->pitch_shifted_output_samples; - } - - offset_wide = -delay_wide; - } - } - - // apply volume, load samples into float buffers - switch (loaded->channel_count) - { - case 1: - for (int i = delay_wide; i < mix_wide - delay_wide; ++i) - { - __m128 A = cA[i + offset_wide]; - __m128 B = _mm_mul_ps(A, vB); - A = _mm_mul_ps(A, vA); - floatA[i] = _mm_add_ps(floatA[i], A); - floatB[i] = _mm_add_ps(floatB[i], B); - } - break; - - case 2: - { - for (int i = delay_wide; i < mix_wide - delay_wide; ++i) - { - __m128 A = cA[i + offset_wide]; - __m128 B = cB[i + offset_wide]; - - A = _mm_mul_ps(A, vA); - B = _mm_mul_ps(B, vB); - floatA[i] = _mm_add_ps(floatA[i], A); - floatB[i] = _mm_add_ps(floatB[i], B); - } - } break; - } - - // playing list logic - playing->sample_index += mix_count; - if (playing->sample_index == loaded->sample_count) - { - if (playing->looped) - { - playing->sample_index = 0; - goto get_next_playing_sound; - } - - remove: - playing->sample_index = 0; - *ptr = (*ptr)->next; - playing->next = 0; - playing->active = 0; - - tsRemoveFilter(playing); - - // if using high-level API manage the tsPlayingSound memory ourselves - if (ctx->playing_pool) - { - playing->next = ctx->playing_free; - ctx->playing_free = playing; - } - - // we already incremented next pointer, so don't do it again - continue; - } - - get_next_playing_sound: - if (*ptr) ptr = &(*ptr)->next; - else break; - } - - // load all floats into 16 bit packed interleaved samples -#if TS_PLATFORM == TS_WINDOWS - - __m128i* samples = ctx->samples; - for (int i = 0; i < wide_count; ++i) - { - __m128i a = _mm_cvtps_epi32(floatA[i]); - __m128i b = _mm_cvtps_epi32(floatB[i]); - __m128i a0b0a1b1 = _mm_unpacklo_epi32(a, b); - __m128i a2b2a3b3 = _mm_unpackhi_epi32(a, b); - samples[i] = _mm_packs_epi32(a0b0a1b1, a2b2a3b3); - } - tsMemcpyToDS(ctx, (int16_t*)samples, byte_to_lock, bytes_to_write); - -#elif TS_PLATFORM == TS_MAC || TS_PLATFORM == TS_SDL - - // Since the ctx->samples array is already in use as a ring buffer - // reusing floatA to store output is a good way to temporarly store - // the final samples. Then a single ring buffer push can be used - // afterwards. Pretty hacky, but whatever :) - __m128i* samples = (__m128i*)floatA; - memset(samples, 0, sizeof(__m128i) * wide_count); - for (int i = 0; i < wide_count; ++i) - { - __m128i a = _mm_cvtps_epi32(floatA[i]); - __m128i b = _mm_cvtps_epi32(floatB[i]); - __m128i a0b0a1b1 = _mm_unpacklo_epi32(a, b); - __m128i a2b2a3b3 = _mm_unpackhi_epi32(a, b); - samples[i] = _mm_packs_epi32(a0b0a1b1, a2b2a3b3); - } - tsPushBytes(ctx, samples, bytes_to_write); - -#else -#endif - -unlock: - tsUnlock(ctx); -} - -// TODO: -// Try this optimization out (2N POINT REAL FFT USING AN N POINT COMPLEX FFT) -// http://www.fftguru.com/fftguru.com.tutorial2.pdf - -#include <math.h> - -static uint32_t tsRev32(uint32_t x) -{ - uint32_t a = ((x & 0xAAAAAAAA) >> 1) | ((x & 0x55555555) << 1); - uint32_t b = ((a & 0xCCCCCCCC) >> 2) | ((a & 0x33333333) << 2); - uint32_t c = ((b & 0xF0F0F0F0) >> 4) | ((b & 0x0F0F0F0F) << 4); - uint32_t d = ((c & 0xFF00FF00) >> 8) | ((c & 0x00FF00FF) << 8); - return (d >> 16) | (d << 16); -} - -static uint32_t tsPopCount(uint32_t x) -{ - uint32_t a = x - ((x >> 1) & 0x55555555); - uint32_t b = (((a >> 2) & 0x33333333) + (a & 0x33333333)); - uint32_t c = (((b >> 4) + b) & 0x0F0F0F0F); - uint32_t d = c + (c >> 8); - uint32_t e = d + (d >> 16); - uint32_t f = e & 0x0000003F; - return f; -} - -static uint32_t tsLog2(uint32_t x) -{ - uint32_t a = x | (x >> 1); - uint32_t b = a | (a >> 2); - uint32_t c = b | (b >> 4); - uint32_t d = c | (c >> 8); - uint32_t e = d | (d >> 16); - uint32_t f = e >> 1; - return tsPopCount(f); -} - -// x contains real inputs -// y contains imaginary inputs -// count must be a power of 2 -// sign must be 1.0 (forward transform) or -1.0f (inverse transform) -static void tsFFT(float* x, float* y, int count, float sign) -{ - int exponent = (int)tsLog2((uint32_t)count); - - // bit reversal stage - // swap all elements with their bit reversed index within the - // lowest level of the Cooley-Tukey recursion tree - for (int i = 1; i < count - 1; i++) - { - uint32_t j = tsRev32((uint32_t)i); - j >>= (32 - exponent); - if (i < (int)j) - { - float tx = x[i]; - float ty = y[i]; - x[i] = x[j]; - y[i] = y[j]; - x[j] = tx; - y[j] = ty; - } - } - - // for each recursive iteration - for (int iter = 0, L = 1; iter < exponent; ++iter) - { - int Ls = L; - L <<= 1; - float ur = 1.0f; // cos( pi / 2 ) - float ui = 0; // sin( pi / 2 ) - float arg = 3.14159265359f / (float)Ls; - float wr = cosf(arg); - float wi = -sign * sinf(arg); - - // rows in DFT submatrix - for (int j = 0; j < Ls; ++j) - { - // do butterflies upon DFT row elements - for (int i = j; i < count; i += L) - { - int index = i + Ls; - float x_index = x[index]; - float y_index = y[index]; - float x_i = x[i]; - float y_i = y[i]; - - float tr = ur * x_index - ui * y_index; - float ti = ur * y_index + ui * x_index; - float x_low = x_i - tr; - float x_high = x_i + tr; - float y_low = y_i - ti; - float y_high = y_i + ti; - - x[index] = x_low; - y[index] = y_low; - x[i] = x_high; - y[i] = y_high; - } - - // Rotate u1 and u2 via Givens rotations (2d planar rotation). - // This keeps cos/sin calls in the outermost loop. - // Floating point error is scaled proportionally to Ls. - float t = ur * wr - ui * wi; - ui = ur * wi + ui * wr; - ur = t; - } - } - - // scale factor for forward transform - if (sign > 0) - { - float inv_count = 1.0f / (float)count; - for (int i = 0; i < count; i++) - { - x[i] *= inv_count; - y[i] *= inv_count; - } - } -} - -#ifdef _MSC_VER - -#define TS_ALIGN16_0 __declspec( align( 16 ) ) -#define TS_ALIGN16_1 -#define TS_SELECTANY extern const __declspec( selectany ) - -#else - -#define TS_ALIGN16_0 -#define TS_ALIGN16_1 __attribute__( (aligned( 16 )) ) -#define TS_SELECTANY const __attribute__( (selectany) ) - -#endif - -// SSE2 trig funcs from https://github.com/to-miz/sse_mathfun_extension/ -#define _PS_CONST( Name, Val ) \ - TS_SELECTANY TS_ALIGN16_0 float _ps_##Name[ 4 ] TS_ALIGN16_1 = { Val, Val, Val, Val } - -#define _PS_CONST_TYPE( Name, Type, Val ) \ - TS_SELECTANY TS_ALIGN16_0 Type _ps_##Name[ 4 ] TS_ALIGN16_1 = { Val, Val, Val, Val } - -#define _PI32_CONST( Name, Val ) \ - TS_SELECTANY TS_ALIGN16_0 int _pi32_##Name[ 4 ] TS_ALIGN16_1 = { Val, Val, Val, Val } - -_PS_CONST_TYPE(sign_mask, int, (int)0x80000000); -_PS_CONST_TYPE(inv_sign_mask, int, (int)~0x80000000); - -_PS_CONST(atanrange_hi, 2.414213562373095f); -_PS_CONST(atanrange_lo, 0.4142135623730950f); -_PS_CONST(cephes_PIO2F, 1.5707963267948966192f); -_PS_CONST(cephes_PIO4F, 0.7853981633974483096f); -_PS_CONST(1, 1.0f); -_PS_CONST(0p5, 0.5f); -_PS_CONST(0, 0); -_PS_CONST(sincof_p0, -1.9515295891E-4f); -_PS_CONST(sincof_p1, 8.3321608736E-3f); -_PS_CONST(sincof_p2, -1.6666654611E-1f); -_PS_CONST(atancof_p0, 8.05374449538e-2f); -_PS_CONST(atancof_p1, 1.38776856032E-1f); -_PS_CONST(atancof_p2, 1.99777106478E-1f); -_PS_CONST(atancof_p3, 3.33329491539E-1f); -_PS_CONST(cephes_PIF, 3.141592653589793238f); -_PS_CONST(cephes_2PIF, 2.0f * 3.141592653589793238f); -_PS_CONST(cephes_FOPI, 1.27323954473516f); // 4 / M_PI -_PS_CONST(minus_cephes_DP1, -0.78515625f); -_PS_CONST(minus_cephes_DP2, -2.4187564849853515625e-4f); -_PS_CONST(minus_cephes_DP3, -3.77489497744594108e-8f); -_PS_CONST(coscof_p0, 2.443315711809948E-005f); -_PS_CONST(coscof_p1, -1.388731625493765E-003f); -_PS_CONST(coscof_p2, 4.166664568298827E-002f); -_PS_CONST(frame_size, (float)TS_PITCH_FRAME_SIZE); - -_PI32_CONST(1, 1); -_PI32_CONST(inv1, ~1); -_PI32_CONST(2, 2); -_PI32_CONST(4, 4); - -static __m128 _mm_atan_ps(__m128 x) -{ - __m128 sign_bit, y; - - sign_bit = x; - /* take the absolute value */ - x = _mm_and_ps(x, *(__m128*)_ps_inv_sign_mask); - /* extract the sign bit (upper one) */ - sign_bit = _mm_and_ps(sign_bit, *(__m128*)_ps_sign_mask); - - /* range reduction, init x and y depending on range */ - /* x > 2.414213562373095 */ - __m128 cmp0 = _mm_cmpgt_ps(x, *(__m128*)_ps_atanrange_hi); - /* x > 0.4142135623730950 */ - __m128 cmp1 = _mm_cmpgt_ps(x, *(__m128*)_ps_atanrange_lo); - - /* x > 0.4142135623730950 && !( x > 2.414213562373095 ) */ - __m128 cmp2 = _mm_andnot_ps(cmp0, cmp1); - - /* -( 1.0/x ) */ - __m128 y0 = _mm_and_ps(cmp0, *(__m128*)_ps_cephes_PIO2F); - __m128 x0 = _mm_div_ps(*(__m128*)_ps_1, x); - x0 = _mm_xor_ps(x0, *(__m128*)_ps_sign_mask); - - __m128 y1 = _mm_and_ps(cmp2, *(__m128*)_ps_cephes_PIO4F); - /* (x-1.0)/(x+1.0) */ - __m128 x1_o = _mm_sub_ps(x, *(__m128*)_ps_1); - __m128 x1_u = _mm_add_ps(x, *(__m128*)_ps_1); - __m128 x1 = _mm_div_ps(x1_o, x1_u); - - __m128 x2 = _mm_and_ps(cmp2, x1); - x0 = _mm_and_ps(cmp0, x0); - x2 = _mm_or_ps(x2, x0); - cmp1 = _mm_or_ps(cmp0, cmp2); - x2 = _mm_and_ps(cmp1, x2); - x = _mm_andnot_ps(cmp1, x); - x = _mm_or_ps(x2, x); - - y = _mm_or_ps(y0, y1); - - __m128 zz = _mm_mul_ps(x, x); - __m128 acc = *(__m128*)_ps_atancof_p0; - acc = _mm_mul_ps(acc, zz); - acc = _mm_sub_ps(acc, *(__m128*)_ps_atancof_p1); - acc = _mm_mul_ps(acc, zz); - acc = _mm_add_ps(acc, *(__m128*)_ps_atancof_p2); - acc = _mm_mul_ps(acc, zz); - acc = _mm_sub_ps(acc, *(__m128*)_ps_atancof_p3); - acc = _mm_mul_ps(acc, zz); - acc = _mm_mul_ps(acc, x); - acc = _mm_add_ps(acc, x); - y = _mm_add_ps(y, acc); - - /* update the sign */ - y = _mm_xor_ps(y, sign_bit); - - return y; -} - -static __m128 _mm_atan2_ps(__m128 y, __m128 x) -{ - __m128 x_eq_0 = _mm_cmpeq_ps(x, *(__m128*)_ps_0); - __m128 x_gt_0 = _mm_cmpgt_ps(x, *(__m128*)_ps_0); - __m128 x_le_0 = _mm_cmple_ps(x, *(__m128*)_ps_0); - __m128 y_eq_0 = _mm_cmpeq_ps(y, *(__m128*)_ps_0); - __m128 x_lt_0 = _mm_cmplt_ps(x, *(__m128*)_ps_0); - __m128 y_lt_0 = _mm_cmplt_ps(y, *(__m128*)_ps_0); - - __m128 zero_mask = _mm_and_ps(x_eq_0, y_eq_0); - __m128 zero_mask_other_case = _mm_and_ps(y_eq_0, x_gt_0); - zero_mask = _mm_or_ps(zero_mask, zero_mask_other_case); - - __m128 pio2_mask = _mm_andnot_ps(y_eq_0, x_eq_0); - __m128 pio2_mask_sign = _mm_and_ps(y_lt_0, *(__m128*)_ps_sign_mask); - __m128 pio2_result = *(__m128*)_ps_cephes_PIO2F; - pio2_result = _mm_xor_ps(pio2_result, pio2_mask_sign); - pio2_result = _mm_and_ps(pio2_mask, pio2_result); - - __m128 pi_mask = _mm_and_ps(y_eq_0, x_le_0); - __m128 pi = *(__m128*)_ps_cephes_PIF; - __m128 pi_result = _mm_and_ps(pi_mask, pi); - - __m128 swap_sign_mask_offset = _mm_and_ps(x_lt_0, y_lt_0); - swap_sign_mask_offset = _mm_and_ps(swap_sign_mask_offset, *(__m128*)_ps_sign_mask); - - __m128 offset0 = _mm_setzero_ps(); - __m128 offset1 = *(__m128*)_ps_cephes_PIF; - offset1 = _mm_xor_ps(offset1, swap_sign_mask_offset); - - __m128 offset = _mm_andnot_ps(x_lt_0, offset0); - offset = _mm_and_ps(x_lt_0, offset1); - - __m128 arg = _mm_div_ps(y, x); - __m128 atan_result = _mm_atan_ps(arg); - atan_result = _mm_add_ps(atan_result, offset); - - /* select between zero_result, pio2_result and atan_result */ - - __m128 result = _mm_andnot_ps(zero_mask, pio2_result); - atan_result = _mm_andnot_ps(pio2_mask, atan_result); - atan_result = _mm_andnot_ps(pio2_mask, atan_result); - result = _mm_or_ps(result, atan_result); - result = _mm_or_ps(result, pi_result); - - return result; -} - -static void _mm_sincos_ps(__m128 x, __m128 *s, __m128 *c) -{ - __m128 xmm1, xmm2, xmm3 = _mm_setzero_ps(), sign_bit_sin, y; - __m128i emm0, emm2, emm4; - sign_bit_sin = x; - /* take the absolute value */ - x = _mm_and_ps(x, *(__m128*)_ps_inv_sign_mask); - /* extract the sign bit (upper one) */ - sign_bit_sin = _mm_and_ps(sign_bit_sin, *(__m128*)_ps_sign_mask); - - /* scale by 4/Pi */ - y = _mm_mul_ps(x, *(__m128*)_ps_cephes_FOPI); - - /* store the integer part of y in emm2 */ - emm2 = _mm_cvttps_epi32(y); - - /* j=(j+1) & (~1) (see the cephes sources) */ - emm2 = _mm_add_epi32(emm2, *(__m128i*)_pi32_1); - emm2 = _mm_and_si128(emm2, *(__m128i*)_pi32_inv1); - y = _mm_cvtepi32_ps(emm2); - - emm4 = emm2; - - /* get the swap sign flag for the sine */ - emm0 = _mm_and_si128(emm2, *(__m128i*)_pi32_4); - emm0 = _mm_slli_epi32(emm0, 29); - __m128 swap_sign_bit_sin = _mm_castsi128_ps(emm0); - - /* get the polynom selection mask for the sine*/ - emm2 = _mm_and_si128(emm2, *(__m128i*)_pi32_2); - emm2 = _mm_cmpeq_epi32(emm2, _mm_setzero_si128()); - __m128 poly_mask = _mm_castsi128_ps(emm2); - - /* The magic pass: "Extended precision modular arithmetic" - x = ((x - y * DP1) - y * DP2) - y * DP3; */ - xmm1 = *(__m128*)_ps_minus_cephes_DP1; - xmm2 = *(__m128*)_ps_minus_cephes_DP2; - xmm3 = *(__m128*)_ps_minus_cephes_DP3; - xmm1 = _mm_mul_ps(y, xmm1); - xmm2 = _mm_mul_ps(y, xmm2); - xmm3 = _mm_mul_ps(y, xmm3); - x = _mm_add_ps(x, xmm1); - x = _mm_add_ps(x, xmm2); - x = _mm_add_ps(x, xmm3); - - emm4 = _mm_sub_epi32(emm4, *(__m128i*)_pi32_2); - emm4 = _mm_andnot_si128(emm4, *(__m128i*)_pi32_4); - emm4 = _mm_slli_epi32(emm4, 29); - __m128 sign_bit_cos = _mm_castsi128_ps(emm4); - - sign_bit_sin = _mm_xor_ps(sign_bit_sin, swap_sign_bit_sin); - - - /* Evaluate the first polynom (0 <= x <= Pi/4) */ - __m128 z = _mm_mul_ps(x, x); - y = *(__m128*)_ps_coscof_p0; - - y = _mm_mul_ps(y, z); - y = _mm_add_ps(y, *(__m128*)_ps_coscof_p1); - y = _mm_mul_ps(y, z); - y = _mm_add_ps(y, *(__m128*)_ps_coscof_p2); - y = _mm_mul_ps(y, z); - y = _mm_mul_ps(y, z); - __m128 tmp = _mm_mul_ps(z, *(__m128*)_ps_0p5); - y = _mm_sub_ps(y, tmp); - y = _mm_add_ps(y, *(__m128*)_ps_1); - - /* Evaluate the second polynom (Pi/4 <= x <= 0) */ - - __m128 y2 = *(__m128*)_ps_sincof_p0; - y2 = _mm_mul_ps(y2, z); - y2 = _mm_add_ps(y2, *(__m128*)_ps_sincof_p1); - y2 = _mm_mul_ps(y2, z); - y2 = _mm_add_ps(y2, *(__m128*)_ps_sincof_p2); - y2 = _mm_mul_ps(y2, z); - y2 = _mm_mul_ps(y2, x); - y2 = _mm_add_ps(y2, x); - - /* select the correct result from the two polynoms */ - xmm3 = poly_mask; - __m128 ysin2 = _mm_and_ps(xmm3, y2); - __m128 ysin1 = _mm_andnot_ps(xmm3, y); - y2 = _mm_sub_ps(y2, ysin2); - y = _mm_sub_ps(y, ysin1); - - xmm1 = _mm_add_ps(ysin1, ysin2); - xmm2 = _mm_add_ps(y, y2); - - /* update the sign */ - *s = _mm_xor_ps(xmm1, sign_bit_sin); - *c = _mm_xor_ps(xmm2, sign_bit_cos); -} - -static __m128i select_si(__m128i a, __m128i b, __m128i mask) -{ - return _mm_xor_si128(a, _mm_and_si128(mask, _mm_xor_si128(b, a))); -} - -#define tsVonHann( i ) (-0.5f * cosf( 2.0f * 3.14159265359f * (float)(i) / (float)TS_PITCH_FRAME_SIZE ) + 0.5f) - -static __m128 tsVonHann4(int i) -{ - __m128 k4 = _mm_set_ps((float)(i * 4 + 3), (float)(i * 4 + 2), (float)(i * 4 + 1), (float)(i * 4)); - k4 = _mm_mul_ps(*(__m128*)_ps_cephes_2PIF, k4); - k4 = _mm_div_ps(k4, *(__m128*)_ps_frame_size); - - // Seems like _mm_cos_ps and _mm_sincos_ps was causing some audio popping... - // I'm not really skilled enough to fix it, but feel free to try: http://gruntthepeon.free.fr/ssemath/sse_mathfun.h - // My guess is some large negative or positive values were causing some - // precision trouble. In this case manually calling 4 cosines is not - // really a big deal, since this function is not a bottleneck. - -#if 0 - __m128 c = _mm_cos_ps(k4); -#elif 0 - __m128 s, c; - _mm_sincos_ps(k4, &s, &c); -#else - __m128 c = k4; - float* cf = (float*)&c; - cf[0] = cosf(cf[0]); - cf[1] = cosf(cf[1]); - cf[2] = cosf(cf[2]); - cf[3] = cosf(cf[3]); -#endif - - __m128 von_hann = _mm_add_ps(_mm_mul_ps(_mm_set_ps1(-0.5f), c), _mm_set_ps1(0.5f)); - return von_hann; -} - -// Analysis and synthesis steps learned from Bernsee's wonderful blog post: -// http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/ -static void tsPitchShift(float pitchShift, int num_samples_to_process, float sampleRate, float* indata, tsPitchData** pitch_filter) -{ - TS_ASSERT(num_samples_to_process <= TS_MAX_FRAME_LENGTH); - - // make sure compiler didn't do anything weird with the member - // offsets of tsPitchData. All arrays must be 16 byte aligned - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->pitch_shifted_output_samples) & 15)); - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->fft_data) & 15)); - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->previous_phase) & 15)); - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->sum_phase) & 15)); - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->window_accumulator) & 15)); - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->freq) & 15)); - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->mag) & 15)); - TS_ASSERT(!((size_t)&(((tsPitchData*)0)->pitch_shift_workspace) & 15)); - - tsPitchData* pf; - - if (*pitch_filter == NULL) - { - pf = (tsPitchData*)malloc16(sizeof(tsPitchData)); - memset(pf, 0, sizeof(tsPitchData)); - *pitch_filter = pf; - } - else - { - pf = *pitch_filter; - } - - float freqPerBin = sampleRate / (float)TS_PITCH_FRAME_SIZE; - __m128 freq_per_bin = _mm_set_ps1(sampleRate / (float)TS_PITCH_FRAME_SIZE); - __m128 pi = *(__m128*)_ps_cephes_PIF; - __m128 two_pi = *(__m128*)_ps_cephes_2PIF; - __m128 pitch_quality = _mm_set_ps1((float)TS_PITCH_QUALITY); - float* out_samples = pf->pitch_shifted_output_samples; - if (pf->index == 0) pf->index = TS_OVERLAP; - - while (num_samples_to_process) - { - int copy_count = TS_PITCH_FRAME_SIZE - pf->index; - if (num_samples_to_process < copy_count) copy_count = num_samples_to_process; - - memcpy(pf->in_FIFO + pf->index, indata, sizeof(float) * copy_count); - memcpy(out_samples, pf->out_FIFO + pf->index - TS_OVERLAP, sizeof(float) * copy_count); - - int start_index = pf->index; - int offset = start_index & 3; - start_index += 4 - offset; - - for (int i = 0; i < offset; ++i) - pf->in_FIFO[pf->index + i] /= 32768.0f; - - int extra = copy_count & 3; - copy_count = copy_count / 4 - extra; - __m128* in_FIFO = (__m128*)(pf->in_FIFO + pf->index + offset); - TS_ASSERT(!((size_t)in_FIFO & 15)); - __m128 int16_max = _mm_set_ps1(32768.0f); - - for (int i = 0; i < copy_count; ++i) - { - __m128 val = in_FIFO[i]; - __m128 div = _mm_div_ps(val, int16_max); - in_FIFO[i] = div; - } - - for (int i = 0, copy_count4 = copy_count * 4; i < extra; ++i) - { - int index = copy_count4 + i; - pf->in_FIFO[pf->index + index] /= 32768.0f; - } - - TS_ASSERT(!((size_t)out_samples & 15)); - __m128* out_samples4 = (__m128*)out_samples; - for (int i = 0; i < copy_count; ++i) - { - __m128 val = out_samples4[i]; - __m128 mul = _mm_mul_ps(val, int16_max); - out_samples4[i] = mul; - } - - for (int i = 0, copy_count4 = copy_count * 4; i < extra; ++i) - { - int index = copy_count4 + i; - out_samples[index] *= 32768.0f; - } - - copy_count = copy_count * 4 + extra; - num_samples_to_process -= copy_count; - pf->index += copy_count; - indata += copy_count; - out_samples += copy_count; - - if (pf->index >= TS_PITCH_FRAME_SIZE) - { - pf->index = TS_OVERLAP; - { - __m128* fft_data = (__m128*)pf->fft_data; - __m128* in_FIFO = (__m128*)pf->in_FIFO; - - for (int k = 0; k < TS_PITCH_FRAME_SIZE / 4; k++) - { - __m128 von_hann = tsVonHann4(k); - __m128 sample = in_FIFO[k]; - __m128 windowed_sample = _mm_mul_ps(sample, von_hann); - fft_data[k] = windowed_sample; - } - } - - memset(pf->fft_data + TS_PITCH_FRAME_SIZE, 0, TS_PITCH_FRAME_SIZE * sizeof(float)); - tsFFT(pf->fft_data, pf->fft_data + TS_PITCH_FRAME_SIZE, TS_PITCH_FRAME_SIZE, 1.0f); - - { - __m128* fft_data = (__m128*)pf->fft_data; - __m128* previous_phase = (__m128*)pf->previous_phase; - __m128* magnitudes = (__m128*)pf->mag; - __m128* frequencies = (__m128*)pf->freq; - int simd_count = (TS_PITCH_FRAME_SIZE / 2) / 4; - - for (int k = 0; k <= simd_count; k++) - { - __m128 real = fft_data[k]; - __m128 imag = fft_data[(TS_PITCH_FRAME_SIZE / 4) + k]; - __m128 overlap_phase = _mm_set_ps((float)(k * 4 + 3) * TS_EXPECTED_FREQUENCY, (float)(k * 4 + 2) * TS_EXPECTED_FREQUENCY, (float)(k * 4 + 1) * TS_EXPECTED_FREQUENCY, (float)(k * 4) * TS_EXPECTED_FREQUENCY); - __m128 k4 = _mm_set_ps((float)(k * 4 + 3), (float)(k * 4 + 2), (float)(k * 4 + 1), (float)(k * 4)); - - __m128 mag = _mm_mul_ps(_mm_set_ps1(2.0f), _mm_sqrt_ps(_mm_add_ps(_mm_mul_ps(real, real), _mm_mul_ps(imag, imag)))); - __m128 phase = _mm_atan2_ps(imag, real); - __m128 phase_dif = _mm_sub_ps(phase, previous_phase[k]); - - previous_phase[k] = phase; - phase_dif = _mm_sub_ps(phase_dif, overlap_phase); - - // map delta phase into +/- pi interval - __m128i qpd = _mm_cvttps_epi32(_mm_div_ps(phase_dif, pi)); - __m128i zero = _mm_setzero_si128(); - __m128i ltzero_mask = _mm_cmplt_epi32(qpd, zero); - __m128i ones_bit = _mm_and_si128(qpd, _mm_set1_epi32(1)); - __m128i neg_qpd = _mm_sub_epi32(qpd, ones_bit); - __m128i pos_qpd = _mm_add_epi32(qpd, ones_bit); - qpd = select_si(pos_qpd, neg_qpd, ltzero_mask); - __m128 pi_range_offset = _mm_mul_ps(pi, _mm_cvtepi32_ps(qpd)); - phase_dif = _mm_sub_ps(phase_dif, pi_range_offset); - - __m128 deviation = _mm_div_ps(_mm_mul_ps(_mm_set_ps1((float)TS_PITCH_QUALITY), phase_dif), two_pi); - __m128 true_freq_estimated = _mm_add_ps(_mm_mul_ps(k4, freq_per_bin), _mm_mul_ps(deviation, freq_per_bin)); - - magnitudes[k] = mag; - frequencies[k] = true_freq_estimated; - } - } - - // actual pitch shifting work - // shift frequencies into workspace - memset(pf->pitch_shift_workspace, 0, (TS_PITCH_FRAME_SIZE / 2) * sizeof(float)); - for (int k = 0; k <= TS_PITCH_FRAME_SIZE / 2; k++) - { - int index = (int)(k * pitchShift); - if (index <= TS_PITCH_FRAME_SIZE / 2) - pf->pitch_shift_workspace[index] = pf->freq[k] * pitchShift; - } - - // swap buffers around to reuse old pf->preq buffer as the new workspace - float* frequencies = pf->pitch_shift_workspace; - float* pitch_shift_workspace = pf->freq; - float* magnitudes = pf->mag; - - // shift magnitudes into workspace - memset(pitch_shift_workspace, 0, TS_PITCH_FRAME_SIZE * sizeof(float)); - for (int k = 0; k <= TS_PITCH_FRAME_SIZE / 2; k++) - { - int index = (int)(k * pitchShift); - if (index <= TS_PITCH_FRAME_SIZE / 2) - pitch_shift_workspace[index] += magnitudes[k]; - } - - // track where the shifted magnitudes are - magnitudes = pitch_shift_workspace; - - { - __m128* magnitudes4 = (__m128*)magnitudes; - __m128* frequencies4 = (__m128*)frequencies; - __m128* fft_data = (__m128*)pf->fft_data; - __m128* sum_phase = (__m128*)pf->sum_phase; - int simd_count = (TS_PITCH_FRAME_SIZE / 2) / 4; - - for (int k = 0; k <= simd_count; k++) - { - __m128 mag = magnitudes4[k]; - __m128 freq = frequencies4[k]; - __m128 freq_per_bin_k = _mm_set_ps((float)(k * 4 + 3) * freqPerBin, (float)(k * 4 + 2) * freqPerBin, (float)(k * 4 + 1) * freqPerBin, (float)(k * 4) * freqPerBin); - - freq = _mm_sub_ps(freq, freq_per_bin_k); - freq = _mm_div_ps(freq, freq_per_bin); - - freq = _mm_mul_ps(two_pi, freq); - freq = _mm_div_ps(freq, pitch_quality); - - __m128 overlap_phase = _mm_set_ps((float)(k * 4 + 3) * TS_EXPECTED_FREQUENCY, (float)(k * 4 + 2) * TS_EXPECTED_FREQUENCY, (float)(k * 4 + 1) * TS_EXPECTED_FREQUENCY, (float)(k * 4) * TS_EXPECTED_FREQUENCY); - freq = _mm_add_ps(freq, overlap_phase); - - __m128 phase = sum_phase[k]; - phase = _mm_add_ps(phase, freq); - sum_phase[k] = phase; - - __m128 c, s; - _mm_sincos_ps(phase, &s, &c); - __m128 real = _mm_mul_ps(mag, c); - __m128 imag = _mm_mul_ps(mag, s); - - fft_data[k] = real; - fft_data[(TS_PITCH_FRAME_SIZE / 4) + k] = imag; - } - } - - for (int k = TS_PITCH_FRAME_SIZE + 2; k < 2 * TS_PITCH_FRAME_SIZE - 2; ++k) - pf->fft_data[k] = 0; - - tsFFT(pf->fft_data, pf->fft_data + TS_PITCH_FRAME_SIZE, TS_PITCH_FRAME_SIZE, -1); - - { - __m128* fft_data = (__m128*)pf->fft_data; - __m128* window_accumulator = (__m128*)pf->window_accumulator; - - for (int k = 0; k < TS_PITCH_FRAME_SIZE / 4; ++k) - { - __m128 von_hann = tsVonHann4(k); - __m128 fft_data_segment = fft_data[k]; - __m128 accumulator_segment = window_accumulator[k]; - __m128 divisor = _mm_div_ps(pitch_quality, _mm_set_ps1(8.0f)); - fft_data_segment = _mm_mul_ps(von_hann, fft_data_segment); - fft_data_segment = _mm_div_ps(fft_data_segment, divisor); - accumulator_segment = _mm_add_ps(accumulator_segment, fft_data_segment); - window_accumulator[k] = accumulator_segment; - } - } - - memcpy(pf->out_FIFO, pf->window_accumulator, TS_STEPSIZE * sizeof(float)); - memmove(pf->window_accumulator, pf->window_accumulator + TS_STEPSIZE, TS_PITCH_FRAME_SIZE * sizeof(float)); - memmove(pf->in_FIFO, pf->in_FIFO + TS_STEPSIZE, TS_OVERLAP * sizeof(float)); - } - } -} - -/* -zlib license: - -Copyright (c) 2017 Randy Gaul http://www.randygaul.net - -This software is provided 'as-is', without any express or implied warranty. -In no event will the authors be held liable for any damages arising from -the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: -1. The origin of this software must not be misrepresented; you must not -claim that you wrote the original software. If you use this software -in a product, an acknowledgment in the product documentation would be -appreciated but is not required. -2. Altered source versions must be plainly marked as such, and must not -be misrepresented as being the original software. -3. This notice may not be removed or altered from any source distribution. -*/ - -#endif diff --git a/src/lua/audio/luaopen_audio.cpp b/src/lua/audio/luaopen_audio.cpp index 1378f89..4c9b5a7 100644 --- a/src/lua/audio/luaopen_audio.cpp +++ b/src/lua/audio/luaopen_audio.cpp @@ -1,3 +1,5 @@ +#include <SDL2/SDL.h> + #include "libs/luax/luax.h" #include "audio/audio.h" @@ -7,8 +9,12 @@ namespace lua { static int l_init(lua_State* L) { - - return 0; + if (SDL_Init(SDL_INIT_AUDIO) < 0) + { + luax_error(L, "could not init audio"); + luax_pushboolean(L, false); + return 1; + } } static int l_newSound(lua_State* L) @@ -25,7 +31,7 @@ namespace lua int luaopen_audio(lua_State* L) { - + return 1; } } diff --git a/src/lua/embed/debug.lua.h b/src/lua/embed/debug.lua.h index f3838a0..7ccc99d 100644 --- a/src/lua/embed/debug.lua.h +++ b/src/lua/embed/debug.lua.h @@ -1,125 +1,132 @@ /* debug.lua */ -static const char debug_lua[] = -{45,45,91,91,32,13,10,32,32,32,32,102,111,114,32,100,101,98,117,103,32,112,117, -114,112,111,115,101,32,13,10,32,32,32,32,43,45,45,45,45,45,45,45,45,45,45,45, -45,45,45,45,45,45,45,45,43,13,10,32,32,32,32,124,100,101,98,117,103,32,109, -115,103,32,111,108,100,32,32,32,32,32,32,124,13,10,32,32,32,32,124,46,46,46, -32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,124,13,10,32,32,32,32,124,46, -46,46,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,124,13,10,32,32,32,32, -124,46,46,46,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,124,13,10,32,32, -32,32,124,100,101,98,117,103,32,109,115,103,32,110,101,119,32,32,32,32,32,32, -124,13,10,32,32,32,32,43,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45, -45,45,43,13,10,93,93,32,13,10,13,10,106,105,110,46,100,101,98,117,103,32,61, -32,106,105,110,46,100,101,98,117,103,32,111,114,32,123,125,32,13,10,13,10,45, -45,32,114,101,110,100,101,114,32,112,97,110,101,108,32,13,10,108,111,99,97, -108,32,112,97,110,101,108,32,61,32,110,105,108,32,13,10,13,10,108,111,99,97, -108,32,100,101,98,117,103,32,61,32,102,97,108,115,101,13,10,13,10,45,45,32, -100,101,98,117,103,32,109,115,103,32,98,117,102,102,101,114,32,13,10,108,111, -99,97,108,32,98,117,102,102,101,114,32,61,32,123,125,32,13,10,13,10,45,45,32, -99,111,110,102,105,103,117,114,101,32,13,10,108,111,99,97,108,32,98,115,105, -122,101,32,32,32,61,32,49,48,13,10,108,111,99,97,108,32,102,115,105,122,101, -32,32,32,61,32,49,53,13,10,108,111,99,97,108,32,108,104,101,105,103,104,116, -32,61,32,49,56,13,10,108,111,99,97,108,32,97,108,112,104,97,32,32,32,61,32,50, -50,48,13,10,108,111,99,97,108,32,109,97,114,103,105,110,32,32,61,32,49,48,13, -10,13,10,45,45,32,114,101,102,114,101,115,104,32,98,117,102,102,101,114,32, -111,114,32,110,111,116,32,13,10,108,111,99,97,108,32,114,101,102,114,101,115, -104,32,61,32,116,114,117,101,32,13,10,13,10,102,117,110,99,116,105,111,110,32, -106,105,110,46,100,101,98,117,103,46,105,110,105,116,40,41,13,10,32,32,32,32, -100,101,98,117,103,32,61,32,116,114,117,101,13,10,9,112,97,110,101,108,32,61, -32,106,105,110,46,103,114,97,112,104,105,99,115,46,67,97,110,118,97,115,40, -106,105,110,46,103,114,97,112,104,105,99,115,46,115,105,122,101,40,41,41,32, -13,10,101,110,100,13,10,13,10,45,45,32,115,101,116,32,98,117,102,102,101,114, -32,115,105,122,101,32,13,10,102,117,110,99,116,105,111,110,32,106,105,110,46, -100,101,98,117,103,46,115,105,122,101,40,99,41,13,10,9,98,115,105,122,101,32, -61,32,99,13,10,101,110,100,32,13,10,13,10,102,117,110,99,116,105,111,110,32, -106,105,110,46,100,101,98,117,103,46,112,114,105,110,116,40,109,115,103,41,13, -10,9,105,102,32,110,111,116,32,100,101,98,117,103,32,116,104,101,110,32,114, -101,116,117,114,110,32,101,110,100,32,13,10,13,10,9,109,115,103,32,61,32,116, -111,115,116,114,105,110,103,40,109,115,103,41,13,10,9,108,111,99,97,108,32, -116,112,32,61,32,116,121,112,101,40,109,115,103,41,13,10,9,105,102,32,116,112, -32,126,61,32,34,115,116,114,105,110,103,34,32,97,110,100,32,116,112,32,126,61, -32,34,110,117,109,98,101,114,34,32,116,104,101,110,32,13,10,9,9,109,115,103, -32,61,32,115,116,114,105,110,103,46,102,111,114,109,97,116,40,34,112,114,105, -110,116,32,102,97,105,108,101,100,44,32,101,120,112,101,99,116,32,115,116,114, -105,110,103,32,111,114,32,110,117,109,98,101,114,32,98,117,116,32,103,101,116, -32,97,32,37,115,34,44,32,116,112,41,13,10,9,101,110,100,13,10,9,13,10,32,32, -32,32,45,45,32,114,101,109,111,118,101,32,116,104,101,32,102,105,114,115,116, -32,111,110,101,32,40,111,108,100,32,109,115,103,41,13,10,9,105,102,32,35,98, -117,102,102,101,114,32,62,61,32,98,115,105,122,101,32,116,104,101,110,32,13, -10,9,9,116,97,98,108,101,46,114,101,109,111,118,101,40,98,117,102,102,101,114, -44,32,49,41,13,10,9,101,110,100,32,13,10,32,32,32,32,13,10,32,32,32,32,98,117, -102,102,101,114,91,35,98,117,102,102,101,114,32,43,32,49,93,32,61,32,109,115, -103,13,10,32,32,32,32,114,101,102,114,101,115,104,32,61,32,116,114,117,101,13, -10,101,110,100,13,10,13,10,45,45,32,99,108,101,97,114,32,100,101,98,117,103, -32,98,117,102,102,101,114,32,13,10,102,117,110,99,116,105,111,110,32,106,105, -110,46,100,101,98,117,103,46,99,108,101,97,114,40,41,13,10,9,98,117,102,102, -101,114,32,61,32,123,125,32,13,10,101,110,100,13,10,13,10,108,111,99,97,108, -32,102,117,110,99,116,105,111,110,32,103,101,116,83,116,114,72,101,105,103, -104,116,40,115,116,114,44,32,108,104,101,105,103,104,116,41,32,13,10,9,108, -111,99,97,108,32,104,32,61,32,108,104,101,105,103,104,116,13,10,9,105,102,32, -35,115,116,114,32,61,61,32,48,32,116,104,101,110,32,13,10,9,9,104,32,61,32,48, -13,10,9,101,110,100,32,13,10,9,102,111,114,32,105,32,61,32,49,44,32,35,115, -116,114,32,100,111,32,13,10,9,9,108,111,99,97,108,32,99,32,61,32,115,116,114, -105,110,103,46,115,117,98,40,115,116,114,44,32,105,44,32,105,41,13,10,9,9,105, -102,32,99,32,61,61,32,39,92,110,39,32,116,104,101,110,32,13,10,9,9,9,104,32, -61,32,104,32,43,32,108,104,101,105,103,104,116,13,10,9,9,101,110,100,32,13,10, -9,101,110,100,32,13,10,9,114,101,116,117,114,110,32,104,32,13,10,101,110,100, -13,10,13,10,108,111,99,97,108,32,32,102,117,110,99,116,105,111,110,32,103,101, -116,66,103,81,117,97,100,40,41,32,13,10,9,108,111,99,97,108,32,119,105,100, -116,104,44,32,104,101,105,103,104,116,32,61,32,48,44,32,48,32,9,13,10,9,102, -111,114,32,105,32,61,32,49,44,32,35,98,117,102,102,101,114,32,100,111,13,10,9, -9,108,111,99,97,108,32,119,44,32,104,32,61,32,106,105,110,46,103,114,97,112, -104,105,99,115,46,98,111,120,40,32,98,117,102,102,101,114,91,105,93,44,32,102, -115,105,122,101,44,32,49,44,32,108,104,101,105,103,104,116,41,13,10,9,9,104, -101,105,103,104,116,32,61,32,104,101,105,103,104,116,32,43,32,104,32,13,10,9, -9,105,102,32,119,105,100,116,104,32,60,32,119,32,116,104,101,110,13,10,9,9,9, -119,105,100,116,104,32,61,32,119,32,13,10,9,9,101,110,100,32,13,10,9,101,110, -100,9,13,10,9,114,101,116,117,114,110,32,119,105,100,116,104,44,32,104,101, -105,103,104,116,13,10,101,110,100,32,13,10,13,10,45,45,32,114,101,110,100,101, -114,32,116,111,32,115,99,114,101,101,110,13,10,102,117,110,99,116,105,111,110, -32,106,105,110,46,100,101,98,117,103,46,114,101,110,100,101,114,40,41,32,13, -10,32,32,32,32,105,102,32,110,111,116,32,100,101,98,117,103,32,116,104,101, -110,32,114,101,116,117,114,110,32,101,110,100,13,10,32,32,32,32,13,10,32,32, -32,32,105,102,32,114,101,102,114,101,115,104,32,116,104,101,110,32,13,10,32, -32,32,32,32,32,32,13,10,32,32,32,32,32,32,32,32,106,105,110,46,103,114,97,112, -104,105,99,115,46,98,105,110,100,40,112,97,110,101,108,41,13,10,13,10,32,32, -32,32,32,32,32,32,32,32,32,32,106,105,110,46,103,114,97,112,104,105,99,115,46, -99,108,101,97,114,40,48,44,32,48,44,32,48,44,32,48,41,13,10,32,32,32,32,32,32, -32,32,32,32,32,32,13,10,32,32,32,32,32,32,32,32,32,32,32,32,106,105,110,46, -103,114,97,112,104,105,99,115,46,115,116,117,100,121,40,41,13,10,32,32,32,32, -32,32,32,32,32,32,32,32,13,10,32,32,32,32,32,32,32,32,32,32,32,32,108,111,99, -97,108,32,119,119,44,32,119,104,32,61,32,106,105,110,46,103,114,97,112,104, -105,99,115,46,115,105,122,101,40,41,13,10,32,32,32,32,32,32,32,32,32,32,32,32, -108,111,99,97,108,32,98,103,119,44,32,98,103,104,32,61,32,103,101,116,66,103, -81,117,97,100,40,41,13,10,32,32,32,32,32,32,32,32,32,32,32,32,106,105,110,46, -103,114,97,112,104,105,99,115,46,99,111,108,111,114,40,48,44,32,48,44,32,48, -44,32,97,108,112,104,97,41,13,10,32,32,32,32,32,32,32,32,32,32,32,32,106,105, -110,46,103,114,97,112,104,105,99,115,46,114,101,99,116,40,34,102,105,108,108, -34,44,32,48,44,32,119,104,32,45,32,98,103,104,32,45,32,109,97,114,103,105,110, -44,32,98,103,119,32,43,32,109,97,114,103,105,110,44,32,98,103,104,32,43,32, -109,97,114,103,105,110,41,13,10,32,32,32,32,32,32,32,32,32,32,32,32,13,10,32, -32,32,32,32,32,32,32,32,32,32,32,106,105,110,46,103,114,97,112,104,105,99,115, -46,99,111,108,111,114,40,41,13,10,32,32,32,32,32,32,32,32,32,32,32,32,108,111, -99,97,108,32,121,32,61,32,119,104,32,13,10,32,32,32,32,32,32,32,32,32,32,32, -32,102,111,114,32,105,32,61,32,35,98,117,102,102,101,114,44,32,49,44,32,45,49, -32,100,111,13,10,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,108,111,99, -97,108,32,109,115,103,32,61,32,98,117,102,102,101,114,91,105,93,32,13,10,32, -32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,108,111,99,97,108,32,104,32,61, -32,103,101,116,83,116,114,72,101,105,103,104,116,40,109,115,103,44,32,108,104, -101,105,103,104,116,41,13,10,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, -121,32,61,32,121,32,45,32,104,32,13,10,32,32,32,32,32,32,32,32,32,32,32,32,32, -32,32,32,106,105,110,46,103,114,97,112,104,105,99,115,46,119,114,105,116,101, -40,109,115,103,44,32,109,97,114,103,105,110,32,47,32,50,44,32,121,32,45,32, -109,97,114,103,105,110,47,32,50,44,32,102,115,105,122,101,44,32,49,44,32,108, -104,101,105,103,104,116,41,32,13,10,32,32,32,32,32,32,32,32,32,32,32,32,101, -110,100,13,10,9,13,10,32,32,32,32,32,32,32,32,106,105,110,46,103,114,97,112, -104,105,99,115,46,98,105,110,100,40,41,13,10,32,32,32,32,13,10,32,32,32,32,32, -32,32,32,114,101,102,114,101,115,104,32,61,32,102,97,108,115,101,13,10,32,32, -32,32,101,110,100,32,13,10,32,32,32,32,13,10,32,32,32,32,106,105,110,46,103, -114,97,112,104,105,99,115,46,99,111,108,111,114,40,41,13,10,32,32,32,32,106, -105,110,46,103,114,97,112,104,105,99,115,46,100,114,97,119,40,112,97,110,101, -108,44,32,48,44,32,48,41,13,10,101,110,100,13,10,13,10,102,117,110,99,116,105, -111,110,32,106,105,110,46,100,101,98,117,103,46,115,116,97,116,117,115,40,41, -32,13,10,9,114,101,116,117,114,110,32,100,101,98,117,103,32,13,10,101,110,100, -13,10}; +static const char* debug_lua = R"( +--[[ + for debug purpose + +-------------------+ + |debug msg old | + |... | + |... | + |... | + |debug msg new | + +-------------------+ +]] +jin.debug = jin.debug or {} + +-- render panel +local panel = nil + +local debug = false + +-- debug msg buffer +local buffer = {} + +-- configure +local bsize = 10 +local fsize = 15 +local lheight = 18 +local alpha = 220 +local margin = 10 + +-- refresh buffer or not +local refresh = true + +function jin.debug.init() + debug = true + panel = jin.graphics.Canvas(jin.graphics.size()) +end + +-- set buffer size +function jin.debug.size(c) + bsize = c +end + +function jin.debug.print(msg) + if not debug then return end + + msg = tostring(msg) + local tp = type(msg) + if tp ~= "string" and tp ~= "number" then + msg = string.format("print failed, expect string or number but get a %s", tp) + end + + -- remove the first one (old msg) + if #buffer >= bsize then + table.remove(buffer, 1) + end + + buffer[#buffer + 1] = msg + refresh = true +end + +-- clear debug buffer +function jin.debug.clear() + buffer = {} +end + +local function getStrHeight(str, lheight) + local h = lheight + if #str == 0 then + h = 0 + end + for i = 1, #str do + local c = string.sub(str, i, i) + if c == '\n' then + h = h + lheight + end + end + return h +end + +local function getBgQuad() + local width, height = 0, 0 + for i = 1, #buffer do + local w, h = jin.graphics.box( buffer[i], fsize, 1, lheight) + height = height + h + if width < w then + width = w + end + end + return width, height +end + +-- render to screen +function jin.debug.render() + if not debug then return end + + if refresh then + + jin.graphics.bind(panel) + + jin.graphics.clear(0, 0, 0, 0) + + jin.graphics.study() + + local ww, wh = jin.graphics.size() + local bgw, bgh = getBgQuad() + jin.graphics.color(0, 0, 0, alpha) + jin.graphics.rect("fill", 0, wh - bgh - margin, bgw + margin, bgh + margin) + + jin.graphics.color() + local y = wh + for i = #buffer, 1, -1 do + local msg = buffer[i] + local h = getStrHeight(msg, lheight) + y = y - h + jin.graphics.write(msg, margin / 2, y - margin/ 2, fsize, 1, lheight) + end + + jin.graphics.bind() + + refresh = false + end + + jin.graphics.color() + jin.graphics.draw(panel, 0, 0) +end + +function jin.debug.status() + return debug +end + +)";
\ No newline at end of file diff --git a/src/lua/embed/embed.h b/src/lua/embed/embed.h index 685355f..2ef8b75 100644 --- a/src/lua/embed/embed.h +++ b/src/lua/embed/embed.h @@ -33,16 +33,16 @@ namespace embed // embed scripts const jin_Embed scripts[] = { - { "graphics.lua", graphics_lua }, - { "keyboard.lua", keyboard_lua }, - { "mouse.lua", mouse_lua }, - { "debug.lua", debug_lua}, - { "boot.lua", boot_lua }, - { 0, 0 } + {"graphics.lua", graphics_lua}, + {"keyboard.lua", keyboard_lua}, + {"mouse.lua", mouse_lua}, + {"debug.lua", debug_lua}, + {"boot.lua", boot_lua}, + {0, 0} }; // load all emebd lua scripts - for (int i = 0; scripts[i].fname; i++) + for (int i = 0; scripts[i].fname; ++i) embed(L, scripts[i].source, scripts[i].fname); } } diff --git a/src/lua/embed/graphics.lua.h b/src/lua/embed/graphics.lua.h index 0e10e97..85cf979 100644 --- a/src/lua/embed/graphics.lua.h +++ b/src/lua/embed/graphics.lua.h @@ -1,8 +1,8 @@ /* graphics.lua */ -static const char graphics_lua[] = -{45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,45,13,10,45,45,32,106,105,110, -46,103,114,97,112,104,105,99,115,32,13,10,45,45,45,45,45,45,45,45,45,45,45,45, -45,45,45,45,45,13,10,13,10,106,105,110,46,103,114,97,112,104,105,99,115,32,61, -32,106,105,110,46,103,114,97,112,104,105,99,115,32,111,114,32,123,125,32,13, -10,13,10}; +static const char* graphics_lua = R"( +----------------- +-- jin.graphics +----------------- +jin.graphics = jin.graphics or {} +)"; diff --git a/src/lua/embed/keyboard.lua.h b/src/lua/embed/keyboard.lua.h index 037c255..66e3c2a 100644 --- a/src/lua/embed/keyboard.lua.h +++ b/src/lua/embed/keyboard.lua.h @@ -1,13 +1,20 @@ -static const char keyboard_lua[] = -{ 45,45,91,91,32,13,10,9,107,101,121,98,111,97,114,100,32,101,120,116,101,110, - 115,105,111,110,32,13,10,93,93,32,13,10,13,10,106,105,110,46,107,101,121,98, - 111,97,114,100,32,61,32,106,105,110,46,107,101,121,98,111,97,114,100,32,111, - 114,32,123,125,32,13,10,13,10,108,111,99,97,108,32,107,101,121,115,32,61,32, - 123,125,32,13,10,13,10,102,117,110,99,116,105,111,110,32,106,105,110,46,107, - 101,121,98,111,97,114,100,46,105,115,68,111,119,110,40,107,41,32,13,10,32,32, - 32,32,114,101,116,117,114,110,32,107,101,121,115,91,107,93,13,10,101,110,100, - 32,32,13,10,13,10,102,117,110,99,116,105,111,110,32,106,105,110,46,107,101, - 121,98,111,97,114,100,46,115,101,116,40,107,44,32,115,116,97,116,117,115,41, - 32,13,10,9,107,101,121,115,91,107,93,32,61,32,115,116,97,116,117,115,32,13,10, - 101,110,100,32,13,10 }; +static const char* keyboard_lua = R"( +--[[ + jin.keyboard extension +]] + +jin.keyboard = jin.keyboard or {} + +local keys = {} + +function jin.keyboard.isDown(k) + return keys[k] +end + +function jin.keyboard.set(k, status) + keys[k] = status +end + + +)"; diff --git a/src/lua/embed/mouse.lua.h b/src/lua/embed/mouse.lua.h index eb5a3ad..f57d08c 100644 --- a/src/lua/embed/mouse.lua.h +++ b/src/lua/embed/mouse.lua.h @@ -1,11 +1,18 @@ -static const char mouse_lua[] = -{45,45,91,91,32,13,10,9,109,111,117,115,101,32,101,120,116,101,110,115,105,111, -110,13,10,93,93,32,13,10,13,10,106,105,110,46,109,111,117,115,101,32,61,32, -106,105,110,46,109,111,117,115,101,32,111,114,32,123,125,32,13,10,13,10,108, -111,99,97,108,32,98,117,116,116,111,110,32,61,32,123,125,32,13,10,13,10,102, -117,110,99,116,105,111,110,32,106,105,110,46,109,111,117,115,101,46,105,115, -68,111,119,110,40,98,116,110,41,32,13,10,9,114,101,116,117,114,110,32,98,117, -116,116,111,110,91,98,116,110,93,13,10,101,110,100,32,13,10,13,10,102,117,110, -99,116,105,111,110,32,106,105,110,46,109,111,117,115,101,46,115,101,116,40,98, -116,110,44,32,115,116,97,116,117,115,41,32,13,10,9,98,117,116,116,111,110,91, -98,116,110,93,32,61,32,115,116,97,116,117,115,13,10,101,110,100,32,13,10}; +static const char* mouse_lua = R"( +--[[ + jin.mouse extension +]] + +jin.mouse = jin.mouse or {} + +local button = {} + +function jin.mouse.isDown(btn) + return button[btn] +end + +function jin.mouse.set(btn, status) + button[btn] = status +end + +)";
\ No newline at end of file diff --git a/src/lua/embed/path.lua.h b/src/lua/embed/path.lua.h index 8a2968a..3ebeab1 100644 --- a/src/lua/embed/path.lua.h +++ b/src/lua/embed/path.lua.h @@ -1,21 +1,19 @@ /* path.lua */ -static const char path_lua[] = -{45,45,91,91,32,13,10,32,32,32,32,106,105,110,46,112,97,116,104,32,101,120,116, -101,110,115,105,111,110,13,10,93,93,32,13,10,13,10,106,105,110,46,112,97,116, -104,32,61,32,106,105,110,46,112,97,116,104,32,111,114,32,123,125,32,13,10,13, -10,45,45,32,103,97,109,101,32,114,111,111,116,32,100,105,114,101,99,116,111, -114,121,32,13,10,106,105,110,46,95,114,111,111,116,32,61,32,110,105,108,32,13, -10,13,10,108,111,99,97,108,32,102,117,110,99,116,105,111,110,32,105,115,102, -117,108,108,40,112,97,116,104,41,32,13,10,32,32,32,32,13,10,101,110,100,32,13, -10,13,10,45,45,32,109,101,114,103,101,32,115,117,98,32,112,97,116,104,32,105, -110,116,111,32,111,110,101,32,13,10,108,111,99,97,108,32,102,117,110,99,116, -105,111,110,32,109,101,114,103,101,40,46,46,46,41,32,13,10,32,32,32,32,13,10, -101,110,100,32,13,10,13,10,45,45,32,114,101,116,117,114,110,32,102,117,108, -108,32,112,97,116,104,32,111,102,32,97,32,103,105,118,101,110,32,112,97,116, -104,32,13,10,102,117,110,99,116,105,111,110,32,106,105,110,46,112,97,116,104, -46,102,117,108,108,40,112,97,116,104,41,13,10,32,32,32,32,108,111,99,97,108, -32,114,111,111,116,32,61,32,106,105,110,46,95,100,105,114,32,46,46,32,39,47, -39,32,46,46,32,106,105,110,46,95,97,114,103,118,91,50,93,13,10,32,32,32,32, -114,101,116,117,114,110,32,114,111,111,116,32,46,46,32,39,47,39,32,46,46,32, -112,97,116,104,32,13,10,101,110,100,13,10,13,10}; +static const char* path_lua = R"( +--[[ + jin.path extension +]] +jin.path = jin.path or {} + +-- game root directory +jin._root = nil + +-- return full path of a given path +function jin.path.full(path) + local root = jin._dir .. '/' .. jin._argv[2] + return root .. '/' .. path +end + + +)"; diff --git a/src/lua/event/luaopen_event.cpp b/src/lua/event/luaopen_event.cpp index c12a969..a417b60 100644 --- a/src/lua/event/luaopen_event.cpp +++ b/src/lua/event/luaopen_event.cpp @@ -33,7 +33,7 @@ namespace lua case SDL_QUIT: luax_setfield_string(L, "type", "quit"); break; - + case SDL_KEYDOWN: luax_setfield_string(L, "type", "keydown"); luax_setfield_string(L, "key", SDL_GetKeyName(e.key.keysym.sym)); diff --git a/src/lua/filesystem/luaopen_filesystem.cpp b/src/lua/filesystem/luaopen_filesystem.cpp index bad293e..daf858c 100644 --- a/src/lua/filesystem/luaopen_filesystem.cpp +++ b/src/lua/filesystem/luaopen_filesystem.cpp @@ -80,7 +80,7 @@ namespace lua int size = tmp.size(); - for (int i = 0; i<size - 4; i++) + for (int i = 0; i<size - 4; ++i) { if (tmp[i] == '.') { @@ -99,7 +99,7 @@ namespace lua tmp = filename; size = tmp.size(); - for (int i = 0; i<size; i++) + for (int i = 0; i<size; ++i) { if (tmp[i] == '.') { diff --git a/src/lua/graphics/luaopen_graphics.cpp b/src/lua/graphics/luaopen_graphics.cpp index 490f560..8ddd455 100644 --- a/src/lua/graphics/luaopen_graphics.cpp +++ b/src/lua/graphics/luaopen_graphics.cpp @@ -1,24 +1,25 @@ +#include <SDL2/SDL.h> + #include "libs/luax/luax.h" + #include "render/image.h" #include "render/canvas.h" #include "render/jsl.h" #include "render/graphics.h" #include "render/window.h" #include "render/font.h" -#include "../luaopen_types.h" -#include "lua/embed/graphics.lua.h" -#include "libs/GLee/GLee.h" #include "fs/filesystem.h" -#include <SDL2/SDL.h> -using namespace jin::render; -using namespace jin::fs; +#include "../luaopen_types.h" +#include "../embed/graphics.lua.h" namespace jin { namespace lua { - + using namespace render; + using namespace fs; + /** * jin.graphics context, storge some module * shared variables. @@ -224,14 +225,24 @@ namespace lua return 0; } + static int l_unbindCanvas(lua_State* L) + { + Canvas::unbind(); + return 0; + } + static int l_useShader(lua_State* L) { + if (luax_gettop(L) == 0) + { + JSLProgram::unuse(); + return 0; + } if (luax_istype(L, 1, TYPE_JSL)) { /* is image */ JSLProgram* jsl = (JSLProgram*)luax_toudata(L, 1); jsl->use(); - } else { @@ -378,7 +389,7 @@ namespace lua return 1; } float* p = new float[2 * n]; - for (int i = 1; i <= 2 * n; i++) + for (int i = 1; i <= 2 * n; ++i) p[i - 1] = luax_rawgetnumber(L, 3, i); render::polygon(mode, p, n); delete[] p; @@ -494,6 +505,7 @@ namespace lua {"study", l_study}, // bind canvas {"bind", l_bindCanvas}, + {"unbind", l_unbindCanvas}, // use shader {"use", l_useShader}, {"unuse", l_unuseShader}, @@ -529,5 +541,5 @@ namespace lua return 1; } -} -} +}// lua +}// jin diff --git a/src/lua/luaopen_jin.cpp b/src/lua/luaopen_jin.cpp index 5c4edc8..e6d98a4 100644 --- a/src/lua/luaopen_jin.cpp +++ b/src/lua/luaopen_jin.cpp @@ -62,9 +62,7 @@ namespace lua {"keyboard", luaopen_keyboard}, {"filesystem", luaopen_filesystem}, {"net", luaopen_net}, - /* - {"audio", luaopen_audio} - */ + //{"audio", luaopen_audio}, {0, 0} }; @@ -77,7 +75,7 @@ namespace lua luax_justglobal(L, -1, MODULE_NAME); // register submodules - for (int i = 0; mods[i].name; i++) + for (int i = 0; mods[i].name; ++i) { // open submodules mods[i].func(L); diff --git a/src/main.cpp b/src/main.cpp index fb77f6d..7417591 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,7 +7,6 @@ #include "libs/luax/luax.h" #include "lua/luaopen_jin.h" -using namespace jin::lua; #include "fs/filesystem.h" @@ -23,11 +22,11 @@ int main(int argc, char* argv[]) * open jin module, jin module is on the top * of stack */ - luaopen_jin(L); + jin::lua::luaopen_jin(L); // add args to global field luax_newtable(L); - for (int i = 0; i < argc; i++) + for (int i = 0; i < argc; ++i) luax_setraw_string(L, -2, i + 1, argv[i]); luax_setfield(L, -2, "_argv"); @@ -45,7 +44,7 @@ int main(int argc, char* argv[]) luax_setfield_string(L, "_dir", buffer); // boot - boot(L); + jin::lua::boot(L); return 0; } diff --git a/src/render/font.cpp b/src/render/font.cpp index 1c13a34..39d1e4e 100644 --- a/src/render/font.cpp +++ b/src/render/font.cpp @@ -97,7 +97,7 @@ namespace render float factor = fheight / (float)PIXEL_HEIGHT; - for (int i = 0; i < len; i++) + for (int i = 0; i < len; ++i) { char c = text[i]; if (c == '\n') @@ -166,7 +166,7 @@ namespace render float factor = fheight / (float)PIXEL_HEIGHT; - for (int i = 0; i < len; i++) + for (int i = 0; i < len; ++i) { char c = str[i]; if (c == '\n') diff --git a/src/render/graphics.cpp b/src/render/graphics.cpp index 21bb0ec..15d8a9c 100644 --- a/src/render/graphics.cpp +++ b/src/render/graphics.cpp @@ -79,7 +79,7 @@ namespace render void polygon_line(float* p, int count) { float* verts = new float[count * 4]; - for (int i = 0; i < count; i++) + for (int i = 0; i < count; ++i) { // each line has two point n,n+1 verts[i * 4] = p[i * 2]; diff --git a/src/render/jsl.cpp b/src/render/jsl.cpp index 5bb9347..6fcee53 100644 --- a/src/render/jsl.cpp +++ b/src/render/jsl.cpp @@ -55,10 +55,9 @@ namespace render glUseProgram(pid); } - void JSLProgram::unuse() + shared void JSLProgram::unuse() { glUseProgram(0); - } void JSLProgram::sendFloat(const char* variable, float number) diff --git a/src/utils/matrix.cpp b/src/utils/matrix.cpp index 6a9c69e..b970ec0 100644 --- a/src/utils/matrix.cpp +++ b/src/utils/matrix.cpp @@ -162,7 +162,7 @@ namespace util void Matrix::transform(vertex * dst, const vertex * src, int size) const { - for (int i = 0; i<size; i++) + for (int i = 0; i<size; ++i) { // Store in temp variables in case src = dst float x = (e[0] * src[i].x) + (e[4] * src[i].y) + (0) + (e[12]); |