Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5462 lines
184 KiB

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