PageRenderTime 92ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/middleware/stb_vorbis/stb_vorbis.c

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