stb_vorbis.c
This file
Path
stb_vorbis.c
5,559 lines · 187.0 KiB · C
Last changed by
stb_vorbis: fix bug in computing end of temp alloc buffer if it's not a multiple of 8Sean Barrettbefore adoptiondb2acff
History of this fileTake it
The walk stopped after 200 commits: lines older than 663deb3 point at it.
update version numbersSean Barrettbefore adoption37b9b20
line 1why, one step back1// Ogg Vorbis audio decoder - v1.19 - public domainredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 2–28why, one step back2// http://nothings.org/stb_vorbis/3//4// Original version written by Sean Barrett in 2007.5//6// Originally sponsored by RAD Game Tools. Seeking implementation7// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker,8// Elias Software, Aras Pranckevicius, and Sean Barrett.9//10// LICENSE11//12// See end of file for license information.13//14// Limitations:15//16// - floor 0 not supported (used in old ogg vorbis files pre-2004)17// - lossless sample-truncation at beginning ignored18// - cannot concatenate multiple vorbis streams19// - sample positions are 32-bit, limiting seekable 192Khz20// files to around 6 hours (Ogg supports 64-bit)21//22// Feature contributors:23// Dougall Johnson (sample-exact seeking)24//25// Bugfix/warning contributors:26// Terje Mathisen Niklas Frykholm Andy Hill27// Casey Muratori John Bolton Gargaj28// Laurent Gomila Marc LeBlanc Ronny Chevalierstb_vorbis: update creditsSean Barrettbefore adoptiond79349d
line 29why, one step back29// Bernhard Wodo Evan Balster github:alxprdredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 30–31why, one step back30// Tom Beaumont Ingo Leitgeb Nicolas Guillemot31// Phillip Bennefall Rohit Thiago Goulartstb_vorbis: update creditsSean Barrettbefore adoptiond79349d
line 32why, one step back32// github:manxorist saga musix github:infatumMerge branch 'issue-799' of https://github.com/pwaller/stb into work2Sean Barrettbefore adoptionaad77ec
line 33why, one step back33// Timur Gagiev Maxwell Koo Peter Walleradd credits for last few PR mergesSean Barrettbefore adoption6f7420a
line 34why, one step back34// github:audinowho Dougall Johnson David ReidMerge branch 'fix_stb_vorbis_alignment' of https://github.com/RandomShaper/stb into workingSean Barrettbefore adoptiona9df364
line 35why, one step back35// github:Clownacy Pedro J. Estebanezredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 36–37why, one step back36//37// Partial history:update version numbersSean Barrettbefore adoption37b9b20
line 38why, one step back38// 1.19 - 2020-02-05 - warningsupdate version numbersSean Barrettbefore adoption7a69424
line 39why, one step back39// 1.18 - 2020-02-02 - fix seek bugs; parse header comments; misc warnings etc.Fix seven bugs discovered and fixed by ForAllSecure:Sean Barrettbefore adoption98fdfc6
line 40why, one step back40// 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure)update version numbersSean Barrettbefore adoption2c2908f
line 41why, one step back41// 1.16 - 2019-03-04 - fix warningsupdate version numbersSean Barrettbefore adoption63b59b4
line 42why, one step back42// 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is foundMerge branch 'working'Sean Barrettbefore adoption19850aa
lines 43–45why, one step back43// 1.14 - 2018-02-11 - delete bogus dealloca usage44// 1.13 - 2018-01-29 - fix truncation of last frame (hopefully)45// 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt filesFix trailing whitespaceSean Barrettbefore adoption2bb4a0a
line 46why, one step back46// 1.11 - 2017-07-23 - fix MinGW compilationMerge branch 'working'Sean Barrettbefore adoption19850aa
lines 47–51why, one step back47// 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory48// 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version49// 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame50// 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const51// 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson)redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 52–53why, one step back52// some crash fixes when out of memory or with corrupt files53// fix some inappropriately signed shiftsMerge branch 'working'Sean Barrettbefore adoption19850aa
lines 54–59why, one step back54// 1.05 - 2015-04-19 - don't define __forceinline if it's redundant55// 1.04 - 2014-08-27 - fix missing const-correct case in API56// 1.03 - 2014-08-07 - warning fixes57// 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows58// 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct)59// 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel;redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 60–136why, one step back60// (API change) report sample rate for decode-full-file funcs61//62// See end of file for full version history.636465//////////////////////////////////////////////////////////////////////////////66//67// HEADER BEGINS HERE68//6970#ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H71#define STB_VORBIS_INCLUDE_STB_VORBIS_H7273#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)74#define STB_VORBIS_NO_STDIO 175#endif7677#ifndef STB_VORBIS_NO_STDIO78#include <stdio.h>79#endif8081#ifdef __cplusplus82extern "C" {83#endif8485/////////// THREAD SAFETY8687// Individual stb_vorbis* handles are not thread-safe; you cannot decode from88// them from multiple threads at the same time. However, you can have multiple89// stb_vorbis* handles and decode from them independently in multiple thrads.909192/////////// MEMORY ALLOCATION9394// normally stb_vorbis uses malloc() to allocate memory at startup,95// and alloca() to allocate temporary memory during a frame on the96// stack. (Memory consumption will depend on the amount of setup97// data in the file and how you set the compile flags for speed98// vs. size. In my test files the maximal-size usage is ~150KB.)99//100// You can modify the wrapper functions in the source (setup_malloc,101// setup_temp_malloc, temp_malloc) to change this behavior, or you102// can use a simpler allocation model: you pass in a buffer from103// which stb_vorbis will allocate _all_ its memory (including the104// temp memory). "open" may fail with a VORBIS_outofmem if you105// do not pass in enough data; there is no way to determine how106// much you do need except to succeed (at which point you can107// query get_info to find the exact amount required. yes I know108// this is lame).109//110// If you pass in a non-NULL buffer of the type below, allocation111// will occur from it as described above. Otherwise just pass NULL112// to use malloc()/alloca()113114typedef struct115{116 char *alloc_buffer;117 int alloc_buffer_length_in_bytes;118} stb_vorbis_alloc;119120121/////////// FUNCTIONS USEABLE WITH ALL INPUT MODES122123typedef struct stb_vorbis stb_vorbis;124125typedef struct126{127 unsigned int sample_rate;128 int channels;129130 unsigned int setup_memory_required;131 unsigned int setup_temp_memory_required;132 unsigned int temp_memory_required;133134 int max_frame_size;135} stb_vorbis_info;136Merge branch 'OggComment' of https://github.com/audinowho/stb into work2Sean Barrettbefore adoption95ce252
lines 137–144why, one step back137typedef struct138{139 char *vendor;140141 int comment_list_length;142 char **comment_list;143} stb_vorbis_comment;144redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 145–147why, one step back145// get general information about the file146extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f);147Merge branch 'OggComment' of https://github.com/audinowho/stb into work2Sean Barrettbefore adoption95ce252
lines 148–150why, one step back148// get ogg comments149extern stb_vorbis_comment stb_vorbis_get_comment(stb_vorbis *f);150redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 151–273why, one step back151// get the last error detected (clears it, too)152extern int stb_vorbis_get_error(stb_vorbis *f);153154// close an ogg vorbis file and free all memory in use155extern void stb_vorbis_close(stb_vorbis *f);156157// this function returns the offset (in samples) from the beginning of the158// file that will be returned by the next decode, if it is known, or -1159// otherwise. after a flush_pushdata() call, this may take a while before160// it becomes valid again.161// NOT WORKING YET after a seek with PULLDATA API162extern int stb_vorbis_get_sample_offset(stb_vorbis *f);163164// returns the current seek point within the file, or offset from the beginning165// of the memory buffer. In pushdata mode it returns 0.166extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f);167168/////////// PUSHDATA API169170#ifndef STB_VORBIS_NO_PUSHDATA_API171172// this API allows you to get blocks of data from any source and hand173// them to stb_vorbis. you have to buffer them; stb_vorbis will tell174// you how much it used, and you have to give it the rest next time;175// and stb_vorbis may not have enough data to work with and you will176// need to give it the same data again PLUS more. Note that the Vorbis177// specification does not bound the size of an individual frame.178179extern stb_vorbis *stb_vorbis_open_pushdata(180 const unsigned char * datablock, int datablock_length_in_bytes,181 int *datablock_memory_consumed_in_bytes,182 int *error,183 const stb_vorbis_alloc *alloc_buffer);184// create a vorbis decoder by passing in the initial data block containing185// the ogg&vorbis headers (you don't need to do parse them, just provide186// the first N bytes of the file--you're told if it's not enough, see below)187// on success, returns an stb_vorbis *, does not set error, returns the amount of188// data parsed/consumed on this call in *datablock_memory_consumed_in_bytes;189// on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed190// if returns NULL and *error is VORBIS_need_more_data, then the input block was191// incomplete and you need to pass in a larger block from the start of the file192193extern int stb_vorbis_decode_frame_pushdata(194 stb_vorbis *f,195 const unsigned char *datablock, int datablock_length_in_bytes,196 int *channels, // place to write number of float * buffers197 float ***output, // place to write float ** array of float * buffers198 int *samples // place to write number of output samples199 );200// decode a frame of audio sample data if possible from the passed-in data block201//202// return value: number of bytes we used from datablock203//204// possible cases:205// 0 bytes used, 0 samples output (need more data)206// N bytes used, 0 samples output (resynching the stream, keep going)207// N bytes used, M samples output (one frame of data)208// note that after opening a file, you will ALWAYS get one N-bytes,0-sample209// frame, because Vorbis always "discards" the first frame.210//211// Note that on resynch, stb_vorbis will rarely consume all of the buffer,212// instead only datablock_length_in_bytes-3 or less. This is because it wants213// to avoid missing parts of a page header if they cross a datablock boundary,214// without writing state-machiney code to record a partial detection.215//216// The number of channels returned are stored in *channels (which can be217// NULL--it is always the same as the number of channels reported by218// get_info). *output will contain an array of float* buffers, one per219// channel. In other words, (*output)[0][0] contains the first sample from220// the first channel, and (*output)[1][0] contains the first sample from221// the second channel.222223extern void stb_vorbis_flush_pushdata(stb_vorbis *f);224// inform stb_vorbis that your next datablock will not be contiguous with225// previous ones (e.g. you've seeked in the data); future attempts to decode226// frames will cause stb_vorbis to resynchronize (as noted above), and227// once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it228// will begin decoding the _next_ frame.229//230// if you want to seek using pushdata, you need to seek in your file, then231// call stb_vorbis_flush_pushdata(), then start calling decoding, then once232// decoding is returning you data, call stb_vorbis_get_sample_offset, and233// if you don't like the result, seek your file again and repeat.234#endif235236237////////// PULLING INPUT API238239#ifndef STB_VORBIS_NO_PULLDATA_API240// This API assumes stb_vorbis is allowed to pull data from a source--241// either a block of memory containing the _entire_ vorbis stream, or a242// FILE * that you or it create, or possibly some other reading mechanism243// if you go modify the source to replace the FILE * case with some kind244// of callback to your code. (But if you don't support seeking, you may245// just want to go ahead and use pushdata.)246247#if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION)248extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output);249#endif250#if !defined(STB_VORBIS_NO_INTEGER_CONVERSION)251extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output);252#endif253// decode an entire file and output the data interleaved into a malloc()ed254// buffer stored in *output. The return value is the number of samples255// decoded, or -1 if the file could not be opened or was not an ogg vorbis file.256// When you're done with it, just free() the pointer returned in *output.257258extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len,259 int *error, const stb_vorbis_alloc *alloc_buffer);260// create an ogg vorbis decoder from an ogg vorbis stream in memory (note261// this must be the entire stream!). on failure, returns NULL and sets *error262263#ifndef STB_VORBIS_NO_STDIO264extern stb_vorbis * stb_vorbis_open_filename(const char *filename,265 int *error, const stb_vorbis_alloc *alloc_buffer);266// create an ogg vorbis decoder from a filename via fopen(). on failure,267// returns NULL and sets *error (possibly to VORBIS_file_open_failure).268269extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close,270 int *error, const stb_vorbis_alloc *alloc_buffer);271// create an ogg vorbis decoder from an open FILE *, looking for a stream at272// the _current_ seek point (ftell). on failure, returns NULL and sets *error.273// note that stb_vorbis must "own" this stream; if you seek it in betweenMerge branch 'misc-typos' of https://github.com/luzpaz/stb into workingSean Barrettbefore adoption3005bcf
line 274why, one step back274// calls to stb_vorbis, it will become confused. Moreover, if you attempt toredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 275–394why, one step back275// perform stb_vorbis_seek_*() operations on this file, it will assume it276// owns the _entire_ rest of the file after the start point. Use the next277// function, stb_vorbis_open_file_section(), to limit it.278279extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close,280 int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len);281// create an ogg vorbis decoder from an open FILE *, looking for a stream at282// the _current_ seek point (ftell); the stream will be of length 'len' bytes.283// on failure, returns NULL and sets *error. note that stb_vorbis must "own"284// this stream; if you seek it in between calls to stb_vorbis, it will become285// confused.286#endif287288extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number);289extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number);290// these functions seek in the Vorbis file to (approximately) 'sample_number'.291// after calling seek_frame(), the next call to get_frame_*() will include292// the specified sample. after calling stb_vorbis_seek(), the next call to293// stb_vorbis_get_samples_* will start with the specified sample. If you294// do not need to seek to EXACTLY the target sample when using get_samples_*,295// you can also use seek_frame().296297extern int stb_vorbis_seek_start(stb_vorbis *f);298// this function is equivalent to stb_vorbis_seek(f,0)299300extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f);301extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f);302// these functions return the total length of the vorbis stream303304extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output);305// decode the next frame and return the number of samples. the number of306// channels returned are stored in *channels (which can be NULL--it is always307// the same as the number of channels reported by get_info). *output will308// contain an array of float* buffers, one per channel. These outputs will309// be overwritten on the next call to stb_vorbis_get_frame_*.310//311// You generally should not intermix calls to stb_vorbis_get_frame_*()312// and stb_vorbis_get_samples_*(), since the latter calls the former.313314#ifndef STB_VORBIS_NO_INTEGER_CONVERSION315extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts);316extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples);317#endif318// decode the next frame and return the number of *samples* per channel.319// Note that for interleaved data, you pass in the number of shorts (the320// size of your array), but the return value is the number of samples per321// channel, not the total number of samples.322//323// The data is coerced to the number of channels you request according to the324// channel coercion rules (see below). You must pass in the size of your325// buffer(s) so that stb_vorbis will not overwrite the end of the buffer.326// The maximum buffer size needed can be gotten from get_info(); however,327// the Vorbis I specification implies an absolute maximum of 4096 samples328// per channel.329330// Channel coercion rules:331// Let M be the number of channels requested, and N the number of channels present,332// and Cn be the nth channel; let stereo L be the sum of all L and center channels,333// and stereo R be the sum of all R and center channels (channel assignment from the334// vorbis spec).335// M N output336// 1 k sum(Ck) for all k337// 2 * stereo L, stereo R338// k l k > l, the first l channels, then 0s339// k l k <= l, the first k channels340// Note that this is not _good_ surround etc. mixing at all! It's just so341// you get something useful.342343extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats);344extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples);345// gets num_samples samples, not necessarily on a frame boundary--this requires346// buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES.347// Returns the number of samples stored per channel; it may be less than requested348// at the end of the file. If there are no more samples in the file, returns 0.349350#ifndef STB_VORBIS_NO_INTEGER_CONVERSION351extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts);352extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples);353#endif354// gets num_samples samples, not necessarily on a frame boundary--this requires355// buffering so you have to supply the buffers. Applies the coercion rules above356// to produce 'channels' channels. Returns the number of samples stored per channel;357// it may be less than requested at the end of the file. If there are no more358// samples in the file, returns 0.359360#endif361362//////// ERROR CODES363364enum STBVorbisError365{366 VORBIS__no_error,367368 VORBIS_need_more_data=1, // not a real error369370 VORBIS_invalid_api_mixing, // can't mix API modes371 VORBIS_outofmem, // not enough memory372 VORBIS_feature_not_supported, // uses floor 0373 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small374 VORBIS_file_open_failure, // fopen() failed375 VORBIS_seek_without_length, // can't seek in unknown-length file376377 VORBIS_unexpected_eof=10, // file is truncated?378 VORBIS_seek_invalid, // seek past EOF379380 // decoding errors (corrupt/invalid stream) -- you probably381 // don't care about the exact details of these382383 // vorbis errors:384 VORBIS_invalid_setup=20,385 VORBIS_invalid_stream,386387 // ogg errors:388 VORBIS_missing_capture_pattern=30,389 VORBIS_invalid_stream_structure_version,390 VORBIS_continued_packet_flag_invalid,391 VORBIS_incorrect_stream_serial_number,392 VORBIS_invalid_first_page,393 VORBIS_bad_packet_type,394 VORBIS_cant_find_last_page,Merge branch 'working'Sean Barrettbefore adoption9092c04
lines 395–396why, one step back395 VORBIS_seek_failed,396 VORBIS_ogg_skeleton_not_supportedredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 397–580why, one step back397};398399400#ifdef __cplusplus401}402#endif403404#endif // STB_VORBIS_INCLUDE_STB_VORBIS_H405//406// HEADER ENDS HERE407//408//////////////////////////////////////////////////////////////////////////////409410#ifndef STB_VORBIS_HEADER_ONLY411412// global configuration settings (e.g. set these in the project/makefile),413// or just set them in this file at the top (although ideally the first few414// should be visible when the header file is compiled too, although it's not415// crucial)416417// STB_VORBIS_NO_PUSHDATA_API418// does not compile the code for the various stb_vorbis_*_pushdata()419// functions420// #define STB_VORBIS_NO_PUSHDATA_API421422// STB_VORBIS_NO_PULLDATA_API423// does not compile the code for the non-pushdata APIs424// #define STB_VORBIS_NO_PULLDATA_API425426// STB_VORBIS_NO_STDIO427// does not compile the code for the APIs that use FILE *s internally428// or externally (implied by STB_VORBIS_NO_PULLDATA_API)429// #define STB_VORBIS_NO_STDIO430431// STB_VORBIS_NO_INTEGER_CONVERSION432// does not compile the code for converting audio sample data from433// float to integer (implied by STB_VORBIS_NO_PULLDATA_API)434// #define STB_VORBIS_NO_INTEGER_CONVERSION435436// STB_VORBIS_NO_FAST_SCALED_FLOAT437// does not use a fast float-to-int trick to accelerate float-to-int on438// most platforms which requires endianness be defined correctly.439//#define STB_VORBIS_NO_FAST_SCALED_FLOAT440441442// STB_VORBIS_MAX_CHANNELS [number]443// globally define this to the maximum number of channels you need.444// The spec does not put a restriction on channels except that445// the count is stored in a byte, so 255 is the hard limit.446// Reducing this saves about 16 bytes per value, so using 16 saves447// (255-16)*16 or around 4KB. Plus anything other memory usage448// I forgot to account for. Can probably go as low as 8 (7.1 audio),449// 6 (5.1 audio), or 2 (stereo only).450#ifndef STB_VORBIS_MAX_CHANNELS451#define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?452#endif453454// STB_VORBIS_PUSHDATA_CRC_COUNT [number]455// after a flush_pushdata(), stb_vorbis begins scanning for the456// next valid page, without backtracking. when it finds something457// that looks like a page, it streams through it and verifies its458// CRC32. Should that validation fail, it keeps scanning. But it's459// possible that _while_ streaming through to check the CRC32 of460// one candidate page, it sees another candidate page. This #define461// determines how many "overlapping" candidate pages it can search462// at once. Note that "real" pages are typically ~4KB to ~8KB, whereas463// garbage pages could be as big as 64KB, but probably average ~16KB.464// So don't hose ourselves by scanning an apparent 64KB page and465// missing a ton of real ones in the interim; so minimum of 2466#ifndef STB_VORBIS_PUSHDATA_CRC_COUNT467#define STB_VORBIS_PUSHDATA_CRC_COUNT 4468#endif469470// STB_VORBIS_FAST_HUFFMAN_LENGTH [number]471// sets the log size of the huffman-acceleration table. Maximum472// supported value is 24. with larger numbers, more decodings are O(1),473// but the table size is larger so worse cache missing, so you'll have474// to probe (and try multiple ogg vorbis files) to find the sweet spot.475#ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH476#define STB_VORBIS_FAST_HUFFMAN_LENGTH 10477#endif478479// STB_VORBIS_FAST_BINARY_LENGTH [number]480// sets the log size of the binary-search acceleration table. this481// is used in similar fashion to the fast-huffman size to set initial482// parameters for the binary search483484// STB_VORBIS_FAST_HUFFMAN_INT485// The fast huffman tables are much more efficient if they can be486// stored as 16-bit results instead of 32-bit results. This restricts487// the codebooks to having only 65535 possible outcomes, though.488// (At least, accelerated by the huffman table.)489#ifndef STB_VORBIS_FAST_HUFFMAN_INT490#define STB_VORBIS_FAST_HUFFMAN_SHORT491#endif492493// STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH494// If the 'fast huffman' search doesn't succeed, then stb_vorbis falls495// back on binary searching for the correct one. This requires storing496// extra tables with the huffman codes in sorted order. Defining this497// symbol trades off space for speed by forcing a linear search in the498// non-fast case, except for "sparse" codebooks.499// #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH500501// STB_VORBIS_DIVIDES_IN_RESIDUE502// stb_vorbis precomputes the result of the scalar residue decoding503// that would otherwise require a divide per chunk. you can trade off504// space for time by defining this symbol.505// #define STB_VORBIS_DIVIDES_IN_RESIDUE506507// STB_VORBIS_DIVIDES_IN_CODEBOOK508// vorbis VQ codebooks can be encoded two ways: with every case explicitly509// stored, or with all elements being chosen from a small range of values,510// and all values possible in all elements. By default, stb_vorbis expands511// this latter kind out to look like the former kind for ease of decoding,512// because otherwise an integer divide-per-vector-element is required to513// unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can514// trade off storage for speed.515//#define STB_VORBIS_DIVIDES_IN_CODEBOOK516517#ifdef STB_VORBIS_CODEBOOK_SHORTS518#error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"519#endif520521// STB_VORBIS_DIVIDE_TABLE522// this replaces small integer divides in the floor decode loop with523// table lookups. made less than 1% difference, so disabled by default.524525// STB_VORBIS_NO_INLINE_DECODE526// disables the inlining of the scalar codebook fast-huffman decode.527// might save a little codespace; useful for debugging528// #define STB_VORBIS_NO_INLINE_DECODE529530// STB_VORBIS_NO_DEFER_FLOOR531// Normally we only decode the floor without synthesizing the actual532// full curve. We can instead synthesize the curve immediately. This533// requires more memory and is very likely slower, so I don't think534// you'd ever want to do it except for debugging.535// #define STB_VORBIS_NO_DEFER_FLOOR536537538539540//////////////////////////////////////////////////////////////////////////////541542#ifdef STB_VORBIS_NO_PULLDATA_API543 #define STB_VORBIS_NO_INTEGER_CONVERSION544 #define STB_VORBIS_NO_STDIO545#endif546547#if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)548 #define STB_VORBIS_NO_STDIO 1549#endif550551#ifndef STB_VORBIS_NO_INTEGER_CONVERSION552#ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT553554 // only need endianness for fast-float-to-int, which we don't555 // use for pushdata556557 #ifndef STB_VORBIS_BIG_ENDIAN558 #define STB_VORBIS_ENDIAN 0559 #else560 #define STB_VORBIS_ENDIAN 1561 #endif562563#endif564#endif565566567#ifndef STB_VORBIS_NO_STDIO568#include <stdio.h>569#endif570571#ifndef STB_VORBIS_NO_CRT572 #include <stdlib.h>573 #include <string.h>574 #include <assert.h>575 #include <math.h>576577 // find definition of alloca if it's not in stdlib.h:578 #if defined(_MSC_VER) || defined(__MINGW32__)579 #include <malloc.h>580 #endifMerge branch 'fix_alloca' of https://github.com/Clownacy/stb into workingSean Barrettbefore adoption58b2e14
line 581why, one step back581 #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) || defined(__NEWLIB__)redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 582–602why, one step back582 #include <alloca.h>583 #endif584#else // STB_VORBIS_NO_CRT585 #define NULL 0586 #define malloc(s) 0587 #define free(s) ((void) 0)588 #define realloc(s) 0589#endif // STB_VORBIS_NO_CRT590591#include <limits.h>592593#ifdef __MINGW32__594 // eff you mingw:595 // "fixed":596 // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/597 // "no that broke the build, reverted, who cares about C":598 // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/599 #ifdef __forceinline600 #undef __forceinline601 #endif602 #define __forceinlineMerge branch 'alloca-fix' of https://github.com/mackron/stb into testSean Barrettbefore adoptioncae97bd
line 603why, one step back603 #ifndef allocaredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
line 604why, one step back604 #define alloca __builtin_allocaMerge branch 'alloca-fix' of https://github.com/mackron/stb into testSean Barrettbefore adoptioncae97bd
line 605why, one step back605 #endifredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 606–778why, one step back606#elif !defined(_MSC_VER)607 #if __GNUC__608 #define __forceinline inline609 #else610 #define __forceinline611 #endif612#endif613614#if STB_VORBIS_MAX_CHANNELS > 256615#error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"616#endif617618#if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24619#error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"620#endif621622623#if 0624#include <crtdbg.h>625#define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])626#else627#define CHECK(f) ((void) 0)628#endif629630#define MAX_BLOCKSIZE_LOG 13 // from specification631#define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)632633634typedef unsigned char uint8;635typedef signed char int8;636typedef unsigned short uint16;637typedef signed short int16;638typedef unsigned int uint32;639typedef signed int int32;640641#ifndef TRUE642#define TRUE 1643#define FALSE 0644#endif645646typedef float codetype;647648// @NOTE649//650// Some arrays below are tagged "//varies", which means it's actually651// a variable-sized piece of data, but rather than malloc I assume it's652// small enough it's better to just allocate it all together with the653// main thing654//655// Most of the variables are specified with the smallest size I could pack656// them into. It might give better performance to make them all full-sized657// integers. It should be safe to freely rearrange the structures or change658// the sizes larger--nothing relies on silently truncating etc., nor the659// order of variables.660661#define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)662#define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)663664typedef struct665{666 int dimensions, entries;667 uint8 *codeword_lengths;668 float minimum_value;669 float delta_value;670 uint8 value_bits;671 uint8 lookup_type;672 uint8 sequence_p;673 uint8 sparse;674 uint32 lookup_values;675 codetype *multiplicands;676 uint32 *codewords;677 #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT678 int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];679 #else680 int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];681 #endif682 uint32 *sorted_codewords;683 int *sorted_values;684 int sorted_entries;685} Codebook;686687typedef struct688{689 uint8 order;690 uint16 rate;691 uint16 bark_map_size;692 uint8 amplitude_bits;693 uint8 amplitude_offset;694 uint8 number_of_books;695 uint8 book_list[16]; // varies696} Floor0;697698typedef struct699{700 uint8 partitions;701 uint8 partition_class_list[32]; // varies702 uint8 class_dimensions[16]; // varies703 uint8 class_subclasses[16]; // varies704 uint8 class_masterbooks[16]; // varies705 int16 subclass_books[16][8]; // varies706 uint16 Xlist[31*8+2]; // varies707 uint8 sorted_order[31*8+2];708 uint8 neighbors[31*8+2][2];709 uint8 floor1_multiplier;710 uint8 rangebits;711 int values;712} Floor1;713714typedef union715{716 Floor0 floor0;717 Floor1 floor1;718} Floor;719720typedef struct721{722 uint32 begin, end;723 uint32 part_size;724 uint8 classifications;725 uint8 classbook;726 uint8 **classdata;727 int16 (*residue_books)[8];728} Residue;729730typedef struct731{732 uint8 magnitude;733 uint8 angle;734 uint8 mux;735} MappingChannel;736737typedef struct738{739 uint16 coupling_steps;740 MappingChannel *chan;741 uint8 submaps;742 uint8 submap_floor[15]; // varies743 uint8 submap_residue[15]; // varies744} Mapping;745746typedef struct747{748 uint8 blockflag;749 uint8 mapping;750 uint16 windowtype;751 uint16 transformtype;752} Mode;753754typedef struct755{756 uint32 goal_crc; // expected crc if match757 int bytes_left; // bytes left in packet758 uint32 crc_so_far; // running crc759 int bytes_done; // bytes processed in _current_ chunk760 uint32 sample_loc; // granule pos encoded in page761} CRCscan;762763typedef struct764{765 uint32 page_start, page_end;766 uint32 last_decoded_sample;767} ProbedPage;768769struct stb_vorbis770{771 // user-accessible info772 unsigned int sample_rate;773 int channels;774775 unsigned int setup_memory_required;776 unsigned int temp_memory_required;777 unsigned int setup_temp_memory_required;778Merge branch 'OggComment' of https://github.com/audinowho/stb into work2Sean Barrettbefore adoption95ce252
lines 779–782why, one step back779 char *vendor;780 int comment_list_length;781 char **comment_list;782redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 783–797why, one step back783 // input config784#ifndef STB_VORBIS_NO_STDIO785 FILE *f;786 uint32 f_start;787 int close_on_free;788#endif789790 uint8 *stream;791 uint8 *stream_start;792 uint8 *stream_end;793794 uint32 stream_len;795796 uint8 push_mode;797Merge branch 'vorbis_seek_fixes' of https://github.com/dougallj/stb into work2Sean Barrettbefore adoptiond882f54
line 798why, one step back798 // the page to seek to when seeking to start, may be zeroredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 799–800why, one step back799 uint32 first_audio_page_offset;800Merge branch 'vorbis_seek_fixes' of https://github.com/dougallj/stb into work2Sean Barrettbefore adoptiond882f54
lines 801–802why, one step back801 // p_first is the page on which the first audio packet ends802 // (but not necessarily the page on which it starts)redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 803–850why, one step back803 ProbedPage p_first, p_last;804805 // memory management806 stb_vorbis_alloc alloc;807 int setup_offset;808 int temp_offset;809810 // run-time results811 int eof;812 enum STBVorbisError error;813814 // user-useful data815816 // header info817 int blocksize[2];818 int blocksize_0, blocksize_1;819 int codebook_count;820 Codebook *codebooks;821 int floor_count;822 uint16 floor_types[64]; // varies823 Floor *floor_config;824 int residue_count;825 uint16 residue_types[64]; // varies826 Residue *residue_config;827 int mapping_count;828 Mapping *mapping;829 int mode_count;830 Mode mode_config[64]; // varies831832 uint32 total_samples;833834 // decode buffer835 float *channel_buffers[STB_VORBIS_MAX_CHANNELS];836 float *outputs [STB_VORBIS_MAX_CHANNELS];837838 float *previous_window[STB_VORBIS_MAX_CHANNELS];839 int previous_length;840841 #ifndef STB_VORBIS_NO_DEFER_FLOOR842 int16 *finalY[STB_VORBIS_MAX_CHANNELS];843 #else844 float *floor_buffers[STB_VORBIS_MAX_CHANNELS];845 #endif846847 uint32 current_loc; // sample location of next frame to decode848 int current_loc_valid;849850 // per-blocksize precomputed dataFix trailing whitespaceSean Barrettbefore adoption2bb4a0a
line 851why, one step back851redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 852–914why, one step back852 // twiddle factors853 float *A[2],*B[2],*C[2];854 float *window[2];855 uint16 *bit_reverse[2];856857 // current page/packet/segment streaming info858 uint32 serial; // stream serial number for verification859 int last_page;860 int segment_count;861 uint8 segments[255];862 uint8 page_flag;863 uint8 bytes_in_seg;864 uint8 first_decode;865 int next_seg;866 int last_seg; // flag that we're on the last segment867 int last_seg_which; // what was the segment number of the last seg?868 uint32 acc;869 int valid_bits;870 int packet_bytes;871 int end_seg_with_known_loc;872 uint32 known_loc_for_packet;873 int discard_samples_deferred;874 uint32 samples_output;875876 // push mode scanning877 int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching878#ifndef STB_VORBIS_NO_PUSHDATA_API879 CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];880#endif881882 // sample-access883 int channel_buffer_start;884 int channel_buffer_end;885};886887#if defined(STB_VORBIS_NO_PUSHDATA_API)888 #define IS_PUSH_MODE(f) FALSE889#elif defined(STB_VORBIS_NO_PULLDATA_API)890 #define IS_PUSH_MODE(f) TRUE891#else892 #define IS_PUSH_MODE(f) ((f)->push_mode)893#endif894895typedef struct stb_vorbis vorb;896897static int error(vorb *f, enum STBVorbisError e)898{899 f->error = e;900 if (!f->eof && e != VORBIS_need_more_data) {901 f->error=e; // breakpoint for debugging902 }903 return 0;904}905906907// these functions are used for allocating temporary memory908// while decoding. if you can afford the stack space, use909// alloca(); otherwise, provide a temp buffer and it will910// allocate out of those.911912#define array_size_required(count,size) (count*(sizeof(void *)+(size)))913914#define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))Merge branch 'master' of https://github.com/MarcoLizza/stb into workingSean Barrettbefore adoptionefdaadc
line 915why, one step back915#define temp_free(f,p) (void)0redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 916–935why, one step back916#define temp_alloc_save(f) ((f)->temp_offset)917#define temp_alloc_restore(f,p) ((f)->temp_offset = (p))918919#define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)920921// given a sufficiently large block of memory, make an array of pointers to subblocks of it922static void *make_block_array(void *mem, int count, int size)923{924 int i;925 void ** p = (void **) mem;926 char *q = (char *) (p + count);927 for (i=0; i < count; ++i) {928 p[i] = q;929 q += size;930 }931 return p;932}933934static void *setup_malloc(vorb *f, int sz)935{Merge branch 'issue-799' of https://github.com/pwaller/stb into work2Sean Barrettbefore adoptionaad77ec
line 936why, one step back936 sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 937–954why, one step back937 f->setup_memory_required += sz;938 if (f->alloc.alloc_buffer) {939 void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;940 if (f->setup_offset + sz > f->temp_offset) return NULL;941 f->setup_offset += sz;942 return p;943 }944 return sz ? malloc(sz) : NULL;945}946947static void setup_free(vorb *f, void *p)948{949 if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack950 free(p);951}952953static void *setup_temp_malloc(vorb *f, int sz)954{Merge branch 'issue-799' of https://github.com/pwaller/stb into work2Sean Barrettbefore adoptionaad77ec
line 955why, one step back955 sz = (sz+7) & ~7; // round up to nearest 8 for alignment of future allocs.redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 956–966why, one step back956 if (f->alloc.alloc_buffer) {957 if (f->temp_offset - sz < f->setup_offset) return NULL;958 f->temp_offset -= sz;959 return (char *) f->alloc.alloc_buffer + f->temp_offset;960 }961 return malloc(sz);962}963964static void setup_temp_free(vorb *f, void *p, int sz)965{966 if (f->alloc.alloc_buffer) {Merge branch 'fix_stb_vorbis_alignment' of https://github.com/RandomShaper/stb into workingSean Barrettbefore adoptiona9df364
line 967why, one step back967 f->temp_offset += (sz+7)&~7;redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 968–1103why, one step back968 return;969 }970 free(p);971}972973#define CRC32_POLY 0x04c11db7 // from spec974975static uint32 crc_table[256];976static void crc32_init(void)977{978 int i,j;979 uint32 s;980 for(i=0; i < 256; i++) {981 for (s=(uint32) i << 24, j=0; j < 8; ++j)982 s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);983 crc_table[i] = s;984 }985}986987static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)988{989 return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];990}991992993// used in setup, and for huffman that doesn't go fast path994static unsigned int bit_reverse(unsigned int n)995{996 n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);997 n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);998 n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);999 n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);1000 return (n >> 16) | (n << 16);1001}10021003static float square(float x)1004{1005 return x*x;1006}10071008// this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 31009// as required by the specification. fast(?) implementation from stb.h1010// @OPTIMIZE: called multiple times per-packet with "constants"; move to setup1011static int ilog(int32 n)1012{1013 static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };10141015 if (n < 0) return 0; // signed n returns 010161017 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)1018 if (n < (1 << 14))1019 if (n < (1 << 4)) return 0 + log2_4[n ];1020 else if (n < (1 << 9)) return 5 + log2_4[n >> 5];1021 else return 10 + log2_4[n >> 10];1022 else if (n < (1 << 24))1023 if (n < (1 << 19)) return 15 + log2_4[n >> 15];1024 else return 20 + log2_4[n >> 20];1025 else if (n < (1 << 29)) return 25 + log2_4[n >> 25];1026 else return 30 + log2_4[n >> 30];1027}10281029#ifndef M_PI1030 #define M_PI 3.14159265358979323846264f // from CRC1031#endif10321033// code length assigned to a value with no huffman encoding1034#define NO_CODE 25510351036/////////////////////// LEAF SETUP FUNCTIONS //////////////////////////1037//1038// these functions are only called at setup, and only a few times1039// per file10401041static float float32_unpack(uint32 x)1042{1043 // from the specification1044 uint32 mantissa = x & 0x1fffff;1045 uint32 sign = x & 0x80000000;1046 uint32 exp = (x & 0x7fe00000) >> 21;1047 double res = sign ? -(double)mantissa : (double)mantissa;1048 return (float) ldexp((float)res, exp-788);1049}105010511052// zlib & jpeg huffman tables assume that the output symbols1053// can either be arbitrarily arranged, or have monotonically1054// increasing frequencies--they rely on the lengths being sorted;1055// this makes for a very simple generation algorithm.1056// vorbis allows a huffman table with non-sorted lengths. This1057// requires a more sophisticated construction, since symbols in1058// order do not map to huffman codes "in order".1059static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)1060{1061 if (!c->sparse) {1062 c->codewords [symbol] = huff_code;1063 } else {1064 c->codewords [count] = huff_code;1065 c->codeword_lengths[count] = len;1066 values [count] = symbol;1067 }1068}10691070static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)1071{1072 int i,k,m=0;1073 uint32 available[32];10741075 memset(available, 0, sizeof(available));1076 // find the first entry1077 for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;1078 if (k == n) { assert(c->sorted_entries == 0); return TRUE; }1079 // add to the list1080 add_entry(c, 0, k, m++, len[k], values);1081 // add all available leaves1082 for (i=1; i <= len[k]; ++i)1083 available[i] = 1U << (32-i);1084 // note that the above code treats the first case specially,1085 // but it's really the same as the following code, so they1086 // could probably be combined (except the initial code is 0,1087 // and I use 0 in available[] to mean 'empty')1088 for (i=k+1; i < n; ++i) {1089 uint32 res;1090 int z = len[i], y;1091 if (z == NO_CODE) continue;1092 // find lowest available leaf (should always be earliest,1093 // which is what the specification calls for)1094 // note that this property, and the fact we can never have1095 // more than one free leaf at a given level, isn't totally1096 // trivial to prove, but it seems true and the assert never1097 // fires, so!1098 while (z > 0 && !available[z]) --z;1099 if (z == 0) { return FALSE; }1100 res = available[z];1101 assert(z >= 0 && z < 32);1102 available[z] = 0;1103 add_entry(c, bit_reverse(res), i, m++, len[i], values);Merge branch 'misc-typos' of https://github.com/luzpaz/stb into workingSean Barrettbefore adoption3005bcf
line 1104why, one step back1104 // propagate availability up the treeredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1105–1172why, one step back1105 if (z != len[i]) {1106 assert(len[i] >= 0 && len[i] < 32);1107 for (y=len[i]; y > z; --y) {1108 assert(available[y] == 0);1109 available[y] = res + (1 << (32-y));1110 }1111 }1112 }1113 return TRUE;1114}11151116// accelerated huffman table allows fast O(1) match of all symbols1117// of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH1118static void compute_accelerated_huffman(Codebook *c)1119{1120 int i, len;1121 for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)1122 c->fast_huffman[i] = -1;11231124 len = c->sparse ? c->sorted_entries : c->entries;1125 #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT1126 if (len > 32767) len = 32767; // largest possible value we can encode!1127 #endif1128 for (i=0; i < len; ++i) {1129 if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {1130 uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];1131 // set table entries for all bit combinations in the higher bits1132 while (z < FAST_HUFFMAN_TABLE_SIZE) {1133 c->fast_huffman[z] = i;1134 z += 1 << c->codeword_lengths[i];1135 }1136 }1137 }1138}11391140#ifdef _MSC_VER1141#define STBV_CDECL __cdecl1142#else1143#define STBV_CDECL1144#endif11451146static int STBV_CDECL uint32_compare(const void *p, const void *q)1147{1148 uint32 x = * (uint32 *) p;1149 uint32 y = * (uint32 *) q;1150 return x < y ? -1 : x > y;1151}11521153static int include_in_sort(Codebook *c, uint8 len)1154{1155 if (c->sparse) { assert(len != NO_CODE); return TRUE; }1156 if (len == NO_CODE) return FALSE;1157 if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;1158 return FALSE;1159}11601161// if the fast table above doesn't work, we want to binary1162// search them... need to reverse the bits1163static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)1164{1165 int i, len;1166 // build a list of all the entries1167 // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.1168 // this is kind of a frivolous optimization--I don't see any performance improvement,1169 // but it's like 4 extra lines of code, so.1170 if (!c->sparse) {1171 int k = 0;1172 for (i=0; i < c->entries; ++i)Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a
line 1173why, one step back1173 if (include_in_sort(c, lengths[i]))redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1174–1229why, one step back1174 c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);1175 assert(k == c->sorted_entries);1176 } else {1177 for (i=0; i < c->sorted_entries; ++i)1178 c->sorted_codewords[i] = bit_reverse(c->codewords[i]);1179 }11801181 qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);1182 c->sorted_codewords[c->sorted_entries] = 0xffffffff;11831184 len = c->sparse ? c->sorted_entries : c->entries;1185 // now we need to indicate how they correspond; we could either1186 // #1: sort a different data structure that says who they correspond to1187 // #2: for each sorted entry, search the original list to find who corresponds1188 // #3: for each original entry, find the sorted entry1189 // #1 requires extra storage, #2 is slow, #3 can use binary search!1190 for (i=0; i < len; ++i) {1191 int huff_len = c->sparse ? lengths[values[i]] : lengths[i];1192 if (include_in_sort(c,huff_len)) {1193 uint32 code = bit_reverse(c->codewords[i]);1194 int x=0, n=c->sorted_entries;1195 while (n > 1) {1196 // invariant: sc[x] <= code < sc[x+n]1197 int m = x + (n >> 1);1198 if (c->sorted_codewords[m] <= code) {1199 x = m;1200 n -= (n>>1);1201 } else {1202 n >>= 1;1203 }1204 }1205 assert(c->sorted_codewords[x] == code);1206 if (c->sparse) {1207 c->sorted_values[x] = values[i];1208 c->codeword_lengths[x] = huff_len;1209 } else {1210 c->sorted_values[x] = i;1211 }1212 }1213 }1214}12151216// only run while parsing the header (3 times)1217static int vorbis_validate(uint8 *data)1218{1219 static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };1220 return memcmp(data, vorbis, 6) == 0;1221}12221223// called from setup only, once per code book1224// (formula implied by specification)1225static int lookup1_values(int entries, int dim)1226{1227 int r = (int) floor(exp((float) log((float) entries) / dim));1228 if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;1229 ++r; // floor() to avoid _ftol() when non-CRTFix seven bugs discovered and fixed by ForAllSecure:Sean Barrettbefore adoption98fdfc6
lines 1230–1233why, one step back1230 if (pow((float) r+1, dim) <= entries)1231 return -1;1232 if ((int) floor(pow((float) r, dim)) > entries)1233 return -1;redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1234–1355why, one step back1234 return r;1235}12361237// called twice per file1238static void compute_twiddle_factors(int n, float *A, float *B, float *C)1239{1240 int n4 = n >> 2, n8 = n >> 3;1241 int k,k2;12421243 for (k=k2=0; k < n4; ++k,k2+=2) {1244 A[k2 ] = (float) cos(4*k*M_PI/n);1245 A[k2+1] = (float) -sin(4*k*M_PI/n);1246 B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;1247 B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;1248 }1249 for (k=k2=0; k < n8; ++k,k2+=2) {1250 C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);1251 C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);1252 }1253}12541255static void compute_window(int n, float *window)1256{1257 int n2 = n >> 1, i;1258 for (i=0; i < n2; ++i)1259 window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));1260}12611262static void compute_bitreverse(int n, uint16 *rev)1263{1264 int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions1265 int i, n8 = n >> 3;1266 for (i=0; i < n8; ++i)1267 rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;1268}12691270static int init_blocksize(vorb *f, int b, int n)1271{1272 int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;1273 f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);1274 f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);1275 f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);1276 if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);1277 compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);1278 f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);1279 if (!f->window[b]) return error(f, VORBIS_outofmem);1280 compute_window(n, f->window[b]);1281 f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);1282 if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);1283 compute_bitreverse(n, f->bit_reverse[b]);1284 return TRUE;1285}12861287static void neighbors(uint16 *x, int n, int *plow, int *phigh)1288{1289 int low = -1;1290 int high = 65536;1291 int i;1292 for (i=0; i < n; ++i) {1293 if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }1294 if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }1295 }1296}12971298// this has been repurposed so y is now the original index instead of y1299typedef struct1300{1301 uint16 x,id;1302} stbv__floor_ordering;13031304static int STBV_CDECL point_compare(const void *p, const void *q)1305{1306 stbv__floor_ordering *a = (stbv__floor_ordering *) p;1307 stbv__floor_ordering *b = (stbv__floor_ordering *) q;1308 return a->x < b->x ? -1 : a->x > b->x;1309}13101311//1312/////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////131313141315#if defined(STB_VORBIS_NO_STDIO)1316 #define USE_MEMORY(z) TRUE1317#else1318 #define USE_MEMORY(z) ((z)->stream)1319#endif13201321static uint8 get8(vorb *z)1322{1323 if (USE_MEMORY(z)) {1324 if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }1325 return *z->stream++;1326 }13271328 #ifndef STB_VORBIS_NO_STDIO1329 {1330 int c = fgetc(z->f);1331 if (c == EOF) { z->eof = TRUE; return 0; }1332 return c;1333 }1334 #endif1335}13361337static uint32 get32(vorb *f)1338{1339 uint32 x;1340 x = get8(f);1341 x += get8(f) << 8;1342 x += get8(f) << 16;1343 x += (uint32) get8(f) << 24;1344 return x;1345}13461347static int getn(vorb *z, uint8 *data, int n)1348{1349 if (USE_MEMORY(z)) {1350 if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }1351 memcpy(data, z->stream, n);1352 z->stream += n;1353 return 1;1354 }1355Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a
line 1356why, one step back1356 #ifndef STB_VORBIS_NO_STDIOredo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1357–1430why, one step back1357 if (fread(data, n, 1, z->f) == 1)1358 return 1;1359 else {1360 z->eof = 1;1361 return 0;1362 }1363 #endif1364}13651366static void skip(vorb *z, int n)1367{1368 if (USE_MEMORY(z)) {1369 z->stream += n;1370 if (z->stream >= z->stream_end) z->eof = 1;1371 return;1372 }1373 #ifndef STB_VORBIS_NO_STDIO1374 {1375 long x = ftell(z->f);1376 fseek(z->f, x+n, SEEK_SET);1377 }1378 #endif1379}13801381static int set_file_offset(stb_vorbis *f, unsigned int loc)1382{1383 #ifndef STB_VORBIS_NO_PUSHDATA_API1384 if (f->push_mode) return 0;1385 #endif1386 f->eof = 0;1387 if (USE_MEMORY(f)) {1388 if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {1389 f->stream = f->stream_end;1390 f->eof = 1;1391 return 0;1392 } else {1393 f->stream = f->stream_start + loc;1394 return 1;1395 }1396 }1397 #ifndef STB_VORBIS_NO_STDIO1398 if (loc + f->f_start < loc || loc >= 0x80000000) {1399 loc = 0x7fffffff;1400 f->eof = 1;1401 } else {1402 loc += f->f_start;1403 }1404 if (!fseek(f->f, loc, SEEK_SET))1405 return 1;1406 f->eof = 1;1407 fseek(f->f, f->f_start, SEEK_END);1408 return 0;1409 #endif1410}141114121413static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };14141415static int capture_pattern(vorb *f)1416{1417 if (0x4f != get8(f)) return FALSE;1418 if (0x67 != get8(f)) return FALSE;1419 if (0x67 != get8(f)) return FALSE;1420 if (0x53 != get8(f)) return FALSE;1421 return TRUE;1422}14231424#define PAGEFLAG_continued_packet 11425#define PAGEFLAG_first_page 21426#define PAGEFLAG_last_page 414271428static int start_page_no_capturepattern(vorb *f)1429{1430 uint32 loc0,loc1,n;Merge branch 'vorbis_seek_fixes' of https://github.com/dougallj/stb into work2Sean Barrettbefore adoptiond882f54
lines 1431–1433why, one step back1431 if (f->first_decode && !IS_PUSH_MODE(f)) {1432 f->p_first.page_start = stb_vorbis_get_file_offset(f) - 4;1433 }redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1434–1438why, one step back1434 // stream structure version1435 if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);1436 // header flag1437 f->page_flag = get8(f);1438 // absolute granule positionFix trailing whitespaceSean Barrettbefore adoption2bb4a0a
line 1439why, one step back1439 loc0 = get32(f);redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1440–1473why, one step back1440 loc1 = get32(f);1441 // @TODO: validate loc0,loc1 as valid positions?1442 // stream serial number -- vorbis doesn't interleave, so discard1443 get32(f);1444 //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);1445 // page sequence number1446 n = get32(f);1447 f->last_page = n;1448 // CRC321449 get32(f);1450 // page_segments1451 f->segment_count = get8(f);1452 if (!getn(f, f->segments, f->segment_count))1453 return error(f, VORBIS_unexpected_eof);1454 // assume we _don't_ know any the sample position of any segments1455 f->end_seg_with_known_loc = -2;1456 if (loc0 != ~0U || loc1 != ~0U) {1457 int i;1458 // determine which packet is the last one that will complete1459 for (i=f->segment_count-1; i >= 0; --i)1460 if (f->segments[i] < 255)1461 break;1462 // 'i' is now the index of the _last_ segment of a packet that ends1463 if (i >= 0) {1464 f->end_seg_with_known_loc = i;1465 f->known_loc_for_packet = loc0;1466 }1467 }1468 if (f->first_decode) {1469 int i,len;1470 len = 0;1471 for (i=0; i < f->segment_count; ++i)1472 len += f->segments[i];1473 len += 27 + f->segment_count;Merge branch 'vorbis_seek_fixes' of https://github.com/dougallj/stb into work2Sean Barrettbefore adoptiond882f54
lines 1474–1475why, one step back1474 f->p_first.page_end = f->p_first.page_start + len;1475 f->p_first.last_decoded_sample = loc0;redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1476–1565why, one step back1476 }1477 f->next_seg = 0;1478 return TRUE;1479}14801481static int start_page(vorb *f)1482{1483 if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);1484 return start_page_no_capturepattern(f);1485}14861487static int start_packet(vorb *f)1488{1489 while (f->next_seg == -1) {1490 if (!start_page(f)) return FALSE;1491 if (f->page_flag & PAGEFLAG_continued_packet)1492 return error(f, VORBIS_continued_packet_flag_invalid);1493 }1494 f->last_seg = FALSE;1495 f->valid_bits = 0;1496 f->packet_bytes = 0;1497 f->bytes_in_seg = 0;1498 // f->next_seg is now valid1499 return TRUE;1500}15011502static int maybe_start_packet(vorb *f)1503{1504 if (f->next_seg == -1) {1505 int x = get8(f);1506 if (f->eof) return FALSE; // EOF at page boundary is not an error!1507 if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);1508 if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);1509 if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);1510 if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);1511 if (!start_page_no_capturepattern(f)) return FALSE;1512 if (f->page_flag & PAGEFLAG_continued_packet) {1513 // set up enough state that we can read this packet if we want,1514 // e.g. during recovery1515 f->last_seg = FALSE;1516 f->bytes_in_seg = 0;1517 return error(f, VORBIS_continued_packet_flag_invalid);1518 }1519 }1520 return start_packet(f);1521}15221523static int next_segment(vorb *f)1524{1525 int len;1526 if (f->last_seg) return 0;1527 if (f->next_seg == -1) {1528 f->last_seg_which = f->segment_count-1; // in case start_page fails1529 if (!start_page(f)) { f->last_seg = 1; return 0; }1530 if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);1531 }1532 len = f->segments[f->next_seg++];1533 if (len < 255) {1534 f->last_seg = TRUE;1535 f->last_seg_which = f->next_seg-1;1536 }1537 if (f->next_seg >= f->segment_count)1538 f->next_seg = -1;1539 assert(f->bytes_in_seg == 0);1540 f->bytes_in_seg = len;1541 return len;1542}15431544#define EOP (-1)1545#define INVALID_BITS (-1)15461547static int get8_packet_raw(vorb *f)1548{1549 if (!f->bytes_in_seg) { // CLANG!1550 if (f->last_seg) return EOP;1551 else if (!next_segment(f)) return EOP;1552 }1553 assert(f->bytes_in_seg > 0);1554 --f->bytes_in_seg;1555 ++f->packet_bytes;1556 return get8(f);1557}15581559static int get8_packet(vorb *f)1560{1561 int x = get8_packet_raw(f);1562 f->valid_bits = 0;1563 return x;1564}1565Merge branch 'OggComment' of https://github.com/audinowho/stb into work2Sean Barrettbefore adoption95ce252
lines 1566–1575why, one step back1566static int get32_packet(vorb *f)1567{1568 uint32 x;1569 x = get8_packet(f);1570 x += get8_packet(f) << 8;1571 x += get8_packet(f) << 16;1572 x += (uint32) get8_packet(f) << 24;1573 return x;1574}1575redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1576–1605why, one step back1576static void flush_packet(vorb *f)1577{1578 while (get8_packet_raw(f) != EOP);1579}15801581// @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important1582// as the huffman decoder?1583static uint32 get_bits(vorb *f, int n)1584{1585 uint32 z;15861587 if (f->valid_bits < 0) return 0;1588 if (f->valid_bits < n) {1589 if (n > 24) {1590 // the accumulator technique below would not work correctly in this case1591 z = get_bits(f, 24);1592 z += get_bits(f, n-24) << 24;1593 return z;1594 }1595 if (f->valid_bits == 0) f->acc = 0;1596 while (f->valid_bits < n) {1597 int z = get8_packet_raw(f);1598 if (z == EOP) {1599 f->valid_bits = INVALID_BITS;1600 return 0;1601 }1602 f->acc += z << f->valid_bits;1603 f->valid_bits += 8;1604 }1605 }Merge branch 'patch-1' of https://github.com/vickit144/stb into workingSean Barrettbefore adoptionadd7adc
lines 1606–1607why, one step back16061607 assert(f->valid_bits >= n);redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1608–1931why, one step back1608 z = f->acc & ((1 << n)-1);1609 f->acc >>= n;1610 f->valid_bits -= n;1611 return z;1612}16131614// @OPTIMIZE: primary accumulator for huffman1615// expand the buffer to as many bits as possible without reading off end of packet1616// it might be nice to allow f->valid_bits and f->acc to be stored in registers,1617// e.g. cache them locally and decode locally1618static __forceinline void prep_huffman(vorb *f)1619{1620 if (f->valid_bits <= 24) {1621 if (f->valid_bits == 0) f->acc = 0;1622 do {1623 int z;1624 if (f->last_seg && !f->bytes_in_seg) return;1625 z = get8_packet_raw(f);1626 if (z == EOP) return;1627 f->acc += (unsigned) z << f->valid_bits;1628 f->valid_bits += 8;1629 } while (f->valid_bits <= 24);1630 }1631}16321633enum1634{1635 VORBIS_packet_id = 1,1636 VORBIS_packet_comment = 3,1637 VORBIS_packet_setup = 51638};16391640static int codebook_decode_scalar_raw(vorb *f, Codebook *c)1641{1642 int i;1643 prep_huffman(f);16441645 if (c->codewords == NULL && c->sorted_codewords == NULL)1646 return -1;16471648 // cases to use binary search: sorted_codewords && !c->codewords1649 // sorted_codewords && c->entries > 81650 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {1651 // binary search1652 uint32 code = bit_reverse(f->acc);1653 int x=0, n=c->sorted_entries, len;16541655 while (n > 1) {1656 // invariant: sc[x] <= code < sc[x+n]1657 int m = x + (n >> 1);1658 if (c->sorted_codewords[m] <= code) {1659 x = m;1660 n -= (n>>1);1661 } else {1662 n >>= 1;1663 }1664 }1665 // x is now the sorted index1666 if (!c->sparse) x = c->sorted_values[x];1667 // x is now sorted index if sparse, or symbol otherwise1668 len = c->codeword_lengths[x];1669 if (f->valid_bits >= len) {1670 f->acc >>= len;1671 f->valid_bits -= len;1672 return x;1673 }16741675 f->valid_bits = 0;1676 return -1;1677 }16781679 // if small, linear search1680 assert(!c->sparse);1681 for (i=0; i < c->entries; ++i) {1682 if (c->codeword_lengths[i] == NO_CODE) continue;1683 if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {1684 if (f->valid_bits >= c->codeword_lengths[i]) {1685 f->acc >>= c->codeword_lengths[i];1686 f->valid_bits -= c->codeword_lengths[i];1687 return i;1688 }1689 f->valid_bits = 0;1690 return -1;1691 }1692 }16931694 error(f, VORBIS_invalid_stream);1695 f->valid_bits = 0;1696 return -1;1697}16981699#ifndef STB_VORBIS_NO_INLINE_DECODE17001701#define DECODE_RAW(var, f,c) \1702 if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \1703 prep_huffman(f); \1704 var = f->acc & FAST_HUFFMAN_TABLE_MASK; \1705 var = c->fast_huffman[var]; \1706 if (var >= 0) { \1707 int n = c->codeword_lengths[var]; \1708 f->acc >>= n; \1709 f->valid_bits -= n; \1710 if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \1711 } else { \1712 var = codebook_decode_scalar_raw(f,c); \1713 }17141715#else17161717static int codebook_decode_scalar(vorb *f, Codebook *c)1718{1719 int i;1720 if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)1721 prep_huffman(f);1722 // fast huffman table lookup1723 i = f->acc & FAST_HUFFMAN_TABLE_MASK;1724 i = c->fast_huffman[i];1725 if (i >= 0) {1726 f->acc >>= c->codeword_lengths[i];1727 f->valid_bits -= c->codeword_lengths[i];1728 if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }1729 return i;1730 }1731 return codebook_decode_scalar_raw(f,c);1732}17331734#define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);17351736#endif17371738#define DECODE(var,f,c) \1739 DECODE_RAW(var,f,c) \1740 if (c->sparse) var = c->sorted_values[var];17411742#ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK1743 #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)1744#else1745 #define DECODE_VQ(var,f,c) DECODE(var,f,c)1746#endif1747174817491750175117521753// CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case1754// where we avoid one addition1755#define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])1756#define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])1757#define CODEBOOK_ELEMENT_BASE(c) (0)17581759static int codebook_decode_start(vorb *f, Codebook *c)1760{1761 int z = -1;17621763 // type 0 is only legal in a scalar context1764 if (c->lookup_type == 0)1765 error(f, VORBIS_invalid_stream);1766 else {1767 DECODE_VQ(z,f,c);1768 if (c->sparse) assert(z < c->sorted_entries);1769 if (z < 0) { // check for EOP1770 if (!f->bytes_in_seg)1771 if (f->last_seg)1772 return z;1773 error(f, VORBIS_invalid_stream);1774 }1775 }1776 return z;1777}17781779static int codebook_decode(vorb *f, Codebook *c, float *output, int len)1780{1781 int i,z = codebook_decode_start(f,c);1782 if (z < 0) return FALSE;1783 if (len > c->dimensions) len = c->dimensions;17841785#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK1786 if (c->lookup_type == 1) {1787 float last = CODEBOOK_ELEMENT_BASE(c);1788 int div = 1;1789 for (i=0; i < len; ++i) {1790 int off = (z / div) % c->lookup_values;1791 float val = CODEBOOK_ELEMENT_FAST(c,off) + last;1792 output[i] += val;1793 if (c->sequence_p) last = val + c->minimum_value;1794 div *= c->lookup_values;1795 }1796 return TRUE;1797 }1798#endif17991800 z *= c->dimensions;1801 if (c->sequence_p) {1802 float last = CODEBOOK_ELEMENT_BASE(c);1803 for (i=0; i < len; ++i) {1804 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1805 output[i] += val;1806 last = val + c->minimum_value;1807 }1808 } else {1809 float last = CODEBOOK_ELEMENT_BASE(c);1810 for (i=0; i < len; ++i) {1811 output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;1812 }1813 }18141815 return TRUE;1816}18171818static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)1819{1820 int i,z = codebook_decode_start(f,c);1821 float last = CODEBOOK_ELEMENT_BASE(c);1822 if (z < 0) return FALSE;1823 if (len > c->dimensions) len = c->dimensions;18241825#ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK1826 if (c->lookup_type == 1) {1827 int div = 1;1828 for (i=0; i < len; ++i) {1829 int off = (z / div) % c->lookup_values;1830 float val = CODEBOOK_ELEMENT_FAST(c,off) + last;1831 output[i*step] += val;1832 if (c->sequence_p) last = val;1833 div *= c->lookup_values;1834 }1835 return TRUE;1836 }1837#endif18381839 z *= c->dimensions;1840 for (i=0; i < len; ++i) {1841 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1842 output[i*step] += val;1843 if (c->sequence_p) last = val;1844 }18451846 return TRUE;1847}18481849static 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)1850{1851 int c_inter = *c_inter_p;1852 int p_inter = *p_inter_p;1853 int i,z, effective = c->dimensions;18541855 // type 0 is only legal in a scalar context1856 if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);18571858 while (total_decode > 0) {1859 float last = CODEBOOK_ELEMENT_BASE(c);1860 DECODE_VQ(z,f,c);1861 #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK1862 assert(!c->sparse || z < c->sorted_entries);1863 #endif1864 if (z < 0) {1865 if (!f->bytes_in_seg)1866 if (f->last_seg) return FALSE;1867 return error(f, VORBIS_invalid_stream);1868 }18691870 // if this will take us off the end of the buffers, stop short!1871 // we check by computing the length of the virtual interleaved1872 // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),1873 // and the length we'll be using (effective)1874 if (c_inter + p_inter*ch + effective > len * ch) {1875 effective = len*ch - (p_inter*ch - c_inter);1876 }18771878 #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK1879 if (c->lookup_type == 1) {1880 int div = 1;1881 for (i=0; i < effective; ++i) {1882 int off = (z / div) % c->lookup_values;1883 float val = CODEBOOK_ELEMENT_FAST(c,off) + last;1884 if (outputs[c_inter])1885 outputs[c_inter][p_inter] += val;1886 if (++c_inter == ch) { c_inter = 0; ++p_inter; }1887 if (c->sequence_p) last = val;1888 div *= c->lookup_values;1889 }1890 } else1891 #endif1892 {1893 z *= c->dimensions;1894 if (c->sequence_p) {1895 for (i=0; i < effective; ++i) {1896 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1897 if (outputs[c_inter])1898 outputs[c_inter][p_inter] += val;1899 if (++c_inter == ch) { c_inter = 0; ++p_inter; }1900 last = val;1901 }1902 } else {1903 for (i=0; i < effective; ++i) {1904 float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;1905 if (outputs[c_inter])1906 outputs[c_inter][p_inter] += val;1907 if (++c_inter == ch) { c_inter = 0; ++p_inter; }1908 }1909 }1910 }19111912 total_decode -= effective;1913 }1914 *c_inter_p = c_inter;1915 *p_inter_p = p_inter;1916 return TRUE;1917}19181919static int predict_point(int x, int x0, int x1, int y0, int y1)1920{1921 int dy = y1 - y0;1922 int adx = x1 - x0;1923 // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?1924 int err = abs(dy) * (x - x0);1925 int off = err / adx;1926 return dy < 0 ? y0 - off : y0 + off;1927}19281929// the following table is block-copied from the specification1930static float inverse_db_table[256] =1931{Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a
lines 1932–1994why, one step back1932 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,1933 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,1934 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,1935 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,1936 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,1937 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,1938 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,1939 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,1940 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,1941 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,1942 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,1943 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,1944 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,1945 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,1946 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,1947 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,1948 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,1949 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,1950 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,1951 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,1952 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,1953 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,1954 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,1955 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,1956 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,1957 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,1958 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,1959 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,1960 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,1961 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,1962 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,1963 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,1964 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,1965 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,1966 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,1967 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,1968 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,1969 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,1970 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,1971 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,1972 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,1973 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,1974 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,1975 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,1976 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,1977 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,1978 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,1979 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,1980 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,1981 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,1982 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,1983 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,1984 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,1985 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,1986 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,1987 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,1988 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,1989 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,1990 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,1991 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,1992 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,1993 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,1994 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,redo lost stb_vorbis fixesSean Barrettbefore adoption663deb3
lines 1995–2053why, one step back1995 0.82788260f, 0.88168307f, 0.9389798f, 1.0f1996};199719981999// @OPTIMIZE: if you want to replace this bresenham line-drawing routine,2000// note that you must produce bit-identical output to decode correctly;The first 2,000 of 5,559 lines.