You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1692 lines
63KB

  1. /**
  2. * @file
  3. * Vorbis I decoder
  4. * @author Denes Balatoni ( dbalatoni programozo hu )
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * Vorbis I decoder
  25. * @author Denes Balatoni ( dbalatoni programozo hu )
  26. */
  27. #include <inttypes.h>
  28. #include <math.h>
  29. #define ALT_BITSTREAM_READER_LE
  30. #include "avcodec.h"
  31. #include "get_bits.h"
  32. #include "dsputil.h"
  33. #include "fft.h"
  34. #include "fmtconvert.h"
  35. #include "vorbis.h"
  36. #include "xiph.h"
  37. #define V_NB_BITS 8
  38. #define V_NB_BITS2 11
  39. #define V_MAX_VLCS (1 << 16)
  40. #define V_MAX_PARTITIONS (1 << 20)
  41. #undef NDEBUG
  42. #include <assert.h>
  43. typedef struct {
  44. uint8_t dimensions;
  45. uint8_t lookup_type;
  46. uint8_t maxdepth;
  47. VLC vlc;
  48. float *codevectors;
  49. unsigned int nb_bits;
  50. } vorbis_codebook;
  51. typedef union vorbis_floor_u vorbis_floor_data;
  52. typedef struct vorbis_floor0_s vorbis_floor0;
  53. typedef struct vorbis_floor1_s vorbis_floor1;
  54. struct vorbis_context_s;
  55. typedef
  56. int (* vorbis_floor_decode_func)
  57. (struct vorbis_context_s *, vorbis_floor_data *, float *);
  58. typedef struct {
  59. uint8_t floor_type;
  60. vorbis_floor_decode_func decode;
  61. union vorbis_floor_u {
  62. struct vorbis_floor0_s {
  63. uint8_t order;
  64. uint16_t rate;
  65. uint16_t bark_map_size;
  66. int32_t *map[2];
  67. uint32_t map_size[2];
  68. uint8_t amplitude_bits;
  69. uint8_t amplitude_offset;
  70. uint8_t num_books;
  71. uint8_t *book_list;
  72. float *lsp;
  73. } t0;
  74. struct vorbis_floor1_s {
  75. uint8_t partitions;
  76. uint8_t partition_class[32];
  77. uint8_t class_dimensions[16];
  78. uint8_t class_subclasses[16];
  79. uint8_t class_masterbook[16];
  80. int16_t subclass_books[16][8];
  81. uint8_t multiplier;
  82. uint16_t x_list_dim;
  83. vorbis_floor1_entry *list;
  84. } t1;
  85. } data;
  86. } vorbis_floor;
  87. typedef struct {
  88. uint16_t type;
  89. uint32_t begin;
  90. uint32_t end;
  91. unsigned partition_size;
  92. uint8_t classifications;
  93. uint8_t classbook;
  94. int16_t books[64][8];
  95. uint8_t maxpass;
  96. uint16_t ptns_to_read;
  97. uint8_t *classifs;
  98. } vorbis_residue;
  99. typedef struct {
  100. uint8_t submaps;
  101. uint16_t coupling_steps;
  102. uint8_t *magnitude;
  103. uint8_t *angle;
  104. uint8_t *mux;
  105. uint8_t submap_floor[16];
  106. uint8_t submap_residue[16];
  107. } vorbis_mapping;
  108. typedef struct {
  109. uint8_t blockflag;
  110. uint16_t windowtype;
  111. uint16_t transformtype;
  112. uint8_t mapping;
  113. } vorbis_mode;
  114. typedef struct vorbis_context_s {
  115. AVCodecContext *avccontext;
  116. GetBitContext gb;
  117. DSPContext dsp;
  118. FmtConvertContext fmt_conv;
  119. FFTContext mdct[2];
  120. uint8_t first_frame;
  121. uint32_t version;
  122. uint8_t audio_channels;
  123. uint32_t audio_samplerate;
  124. uint32_t bitrate_maximum;
  125. uint32_t bitrate_nominal;
  126. uint32_t bitrate_minimum;
  127. uint32_t blocksize[2];
  128. const float *win[2];
  129. uint16_t codebook_count;
  130. vorbis_codebook *codebooks;
  131. uint8_t floor_count;
  132. vorbis_floor *floors;
  133. uint8_t residue_count;
  134. vorbis_residue *residues;
  135. uint8_t mapping_count;
  136. vorbis_mapping *mappings;
  137. uint8_t mode_count;
  138. vorbis_mode *modes;
  139. uint8_t mode_number; // mode number for the current packet
  140. uint8_t previous_window;
  141. float *channel_residues;
  142. float *channel_floors;
  143. float *saved;
  144. float scale_bias; // for float->int conversion
  145. } vorbis_context;
  146. /* Helper functions */
  147. #define BARK(x) \
  148. (13.1f * atan(0.00074f * (x)) + 2.24f * atan(1.85e-8f * (x) * (x)) + 1e-4f * (x))
  149. static const char idx_err_str[] = "Index value %d out of range (0 - %d) for %s at %s:%i\n";
  150. #define VALIDATE_INDEX(idx, limit) \
  151. if (idx >= limit) {\
  152. av_log(vc->avccontext, AV_LOG_ERROR,\
  153. idx_err_str,\
  154. (int)(idx), (int)(limit - 1), #idx, __FILE__, __LINE__);\
  155. return AVERROR_INVALIDDATA;\
  156. }
  157. #define GET_VALIDATED_INDEX(idx, bits, limit) \
  158. {\
  159. idx = get_bits(gb, bits);\
  160. VALIDATE_INDEX(idx, limit)\
  161. }
  162. static float vorbisfloat2float(unsigned val)
  163. {
  164. double mant = val & 0x1fffff;
  165. long exp = (val & 0x7fe00000L) >> 21;
  166. if (val & 0x80000000)
  167. mant = -mant;
  168. return ldexp(mant, exp - 20 - 768);
  169. }
  170. // Free all allocated memory -----------------------------------------
  171. static void vorbis_free(vorbis_context *vc)
  172. {
  173. int i;
  174. av_freep(&vc->channel_residues);
  175. av_freep(&vc->channel_floors);
  176. av_freep(&vc->saved);
  177. for (i = 0; i < vc->residue_count; i++)
  178. av_free(vc->residues[i].classifs);
  179. av_freep(&vc->residues);
  180. av_freep(&vc->modes);
  181. ff_mdct_end(&vc->mdct[0]);
  182. ff_mdct_end(&vc->mdct[1]);
  183. for (i = 0; i < vc->codebook_count; ++i) {
  184. av_free(vc->codebooks[i].codevectors);
  185. free_vlc(&vc->codebooks[i].vlc);
  186. }
  187. av_freep(&vc->codebooks);
  188. for (i = 0; i < vc->floor_count; ++i) {
  189. if (vc->floors[i].floor_type == 0) {
  190. av_free(vc->floors[i].data.t0.map[0]);
  191. av_free(vc->floors[i].data.t0.map[1]);
  192. av_free(vc->floors[i].data.t0.book_list);
  193. av_free(vc->floors[i].data.t0.lsp);
  194. } else {
  195. av_free(vc->floors[i].data.t1.list);
  196. }
  197. }
  198. av_freep(&vc->floors);
  199. for (i = 0; i < vc->mapping_count; ++i) {
  200. av_free(vc->mappings[i].magnitude);
  201. av_free(vc->mappings[i].angle);
  202. av_free(vc->mappings[i].mux);
  203. }
  204. av_freep(&vc->mappings);
  205. }
  206. // Parse setup header -------------------------------------------------
  207. // Process codebooks part
  208. static int vorbis_parse_setup_hdr_codebooks(vorbis_context *vc)
  209. {
  210. unsigned cb;
  211. uint8_t *tmp_vlc_bits;
  212. uint32_t *tmp_vlc_codes;
  213. GetBitContext *gb = &vc->gb;
  214. uint16_t *codebook_multiplicands;
  215. int ret = 0;
  216. vc->codebook_count = get_bits(gb, 8) + 1;
  217. av_dlog(NULL, " Codebooks: %d \n", vc->codebook_count);
  218. vc->codebooks = av_mallocz(vc->codebook_count * sizeof(*vc->codebooks));
  219. tmp_vlc_bits = av_mallocz(V_MAX_VLCS * sizeof(*tmp_vlc_bits));
  220. tmp_vlc_codes = av_mallocz(V_MAX_VLCS * sizeof(*tmp_vlc_codes));
  221. codebook_multiplicands = av_malloc(V_MAX_VLCS * sizeof(*codebook_multiplicands));
  222. for (cb = 0; cb < vc->codebook_count; ++cb) {
  223. vorbis_codebook *codebook_setup = &vc->codebooks[cb];
  224. unsigned ordered, t, entries, used_entries = 0;
  225. av_dlog(NULL, " %u. Codebook\n", cb);
  226. if (get_bits(gb, 24) != 0x564342) {
  227. av_log(vc->avccontext, AV_LOG_ERROR,
  228. " %u. Codebook setup data corrupt.\n", cb);
  229. ret = AVERROR_INVALIDDATA;
  230. goto error;
  231. }
  232. codebook_setup->dimensions=get_bits(gb, 16);
  233. if (codebook_setup->dimensions > 16 || codebook_setup->dimensions == 0) {
  234. av_log(vc->avccontext, AV_LOG_ERROR,
  235. " %u. Codebook's dimension is invalid (%d).\n",
  236. cb, codebook_setup->dimensions);
  237. ret = AVERROR_INVALIDDATA;
  238. goto error;
  239. }
  240. entries = get_bits(gb, 24);
  241. if (entries > V_MAX_VLCS) {
  242. av_log(vc->avccontext, AV_LOG_ERROR,
  243. " %u. Codebook has too many entries (%u).\n",
  244. cb, entries);
  245. ret = AVERROR_INVALIDDATA;
  246. goto error;
  247. }
  248. ordered = get_bits1(gb);
  249. av_dlog(NULL, " codebook_dimensions %d, codebook_entries %u\n",
  250. codebook_setup->dimensions, entries);
  251. if (!ordered) {
  252. unsigned ce, flag;
  253. unsigned sparse = get_bits1(gb);
  254. av_dlog(NULL, " not ordered \n");
  255. if (sparse) {
  256. av_dlog(NULL, " sparse \n");
  257. used_entries = 0;
  258. for (ce = 0; ce < entries; ++ce) {
  259. flag = get_bits1(gb);
  260. if (flag) {
  261. tmp_vlc_bits[ce] = get_bits(gb, 5) + 1;
  262. ++used_entries;
  263. } else
  264. tmp_vlc_bits[ce] = 0;
  265. }
  266. } else {
  267. av_dlog(NULL, " not sparse \n");
  268. used_entries = entries;
  269. for (ce = 0; ce < entries; ++ce)
  270. tmp_vlc_bits[ce] = get_bits(gb, 5) + 1;
  271. }
  272. } else {
  273. unsigned current_entry = 0;
  274. unsigned current_length = get_bits(gb, 5) + 1;
  275. av_dlog(NULL, " ordered, current length: %u\n", current_length); //FIXME
  276. used_entries = entries;
  277. for (; current_entry < used_entries && current_length <= 32; ++current_length) {
  278. unsigned i, number;
  279. av_dlog(NULL, " number bits: %u ", ilog(entries - current_entry));
  280. number = get_bits(gb, ilog(entries - current_entry));
  281. av_dlog(NULL, " number: %u\n", number);
  282. for (i = current_entry; i < number+current_entry; ++i)
  283. if (i < used_entries)
  284. tmp_vlc_bits[i] = current_length;
  285. current_entry+=number;
  286. }
  287. if (current_entry>used_entries) {
  288. av_log(vc->avccontext, AV_LOG_ERROR, " More codelengths than codes in codebook. \n");
  289. ret = AVERROR_INVALIDDATA;
  290. goto error;
  291. }
  292. }
  293. codebook_setup->lookup_type = get_bits(gb, 4);
  294. av_dlog(NULL, " lookup type: %d : %s \n", codebook_setup->lookup_type,
  295. codebook_setup->lookup_type ? "vq" : "no lookup");
  296. // If the codebook is used for (inverse) VQ, calculate codevectors.
  297. if (codebook_setup->lookup_type == 1) {
  298. unsigned i, j, k;
  299. unsigned codebook_lookup_values = ff_vorbis_nth_root(entries, codebook_setup->dimensions);
  300. float codebook_minimum_value = vorbisfloat2float(get_bits_long(gb, 32));
  301. float codebook_delta_value = vorbisfloat2float(get_bits_long(gb, 32));
  302. unsigned codebook_value_bits = get_bits(gb, 4) + 1;
  303. unsigned codebook_sequence_p = get_bits1(gb);
  304. av_dlog(NULL, " We expect %d numbers for building the codevectors. \n",
  305. codebook_lookup_values);
  306. av_dlog(NULL, " delta %f minmum %f \n",
  307. codebook_delta_value, codebook_minimum_value);
  308. for (i = 0; i < codebook_lookup_values; ++i) {
  309. codebook_multiplicands[i] = get_bits(gb, codebook_value_bits);
  310. av_dlog(NULL, " multiplicands*delta+minmum : %e \n",
  311. (float)codebook_multiplicands[i] * codebook_delta_value + codebook_minimum_value);
  312. av_dlog(NULL, " multiplicand %u\n", codebook_multiplicands[i]);
  313. }
  314. // Weed out unused vlcs and build codevector vector
  315. codebook_setup->codevectors = used_entries ? av_mallocz(used_entries *
  316. codebook_setup->dimensions *
  317. sizeof(*codebook_setup->codevectors))
  318. : NULL;
  319. for (j = 0, i = 0; i < entries; ++i) {
  320. unsigned dim = codebook_setup->dimensions;
  321. if (tmp_vlc_bits[i]) {
  322. float last = 0.0;
  323. unsigned lookup_offset = i;
  324. av_dlog(vc->avccontext, "Lookup offset %u ,", i);
  325. for (k = 0; k < dim; ++k) {
  326. unsigned multiplicand_offset = lookup_offset % codebook_lookup_values;
  327. codebook_setup->codevectors[j * dim + k] = codebook_multiplicands[multiplicand_offset] * codebook_delta_value + codebook_minimum_value + last;
  328. if (codebook_sequence_p)
  329. last = codebook_setup->codevectors[j * dim + k];
  330. lookup_offset/=codebook_lookup_values;
  331. }
  332. tmp_vlc_bits[j] = tmp_vlc_bits[i];
  333. av_dlog(vc->avccontext, "real lookup offset %u, vector: ", j);
  334. for (k = 0; k < dim; ++k)
  335. av_dlog(vc->avccontext, " %f ",
  336. codebook_setup->codevectors[j * dim + k]);
  337. av_dlog(vc->avccontext, "\n");
  338. ++j;
  339. }
  340. }
  341. if (j != used_entries) {
  342. av_log(vc->avccontext, AV_LOG_ERROR, "Bug in codevector vector building code. \n");
  343. ret = AVERROR_INVALIDDATA;
  344. goto error;
  345. }
  346. entries = used_entries;
  347. } else if (codebook_setup->lookup_type >= 2) {
  348. av_log(vc->avccontext, AV_LOG_ERROR, "Codebook lookup type not supported. \n");
  349. ret = AVERROR_INVALIDDATA;
  350. goto error;
  351. }
  352. // Initialize VLC table
  353. if (ff_vorbis_len2vlc(tmp_vlc_bits, tmp_vlc_codes, entries)) {
  354. av_log(vc->avccontext, AV_LOG_ERROR, " Invalid code lengths while generating vlcs. \n");
  355. ret = AVERROR_INVALIDDATA;
  356. goto error;
  357. }
  358. codebook_setup->maxdepth = 0;
  359. for (t = 0; t < entries; ++t)
  360. if (tmp_vlc_bits[t] >= codebook_setup->maxdepth)
  361. codebook_setup->maxdepth = tmp_vlc_bits[t];
  362. if (codebook_setup->maxdepth > 3 * V_NB_BITS)
  363. codebook_setup->nb_bits = V_NB_BITS2;
  364. else
  365. codebook_setup->nb_bits = V_NB_BITS;
  366. codebook_setup->maxdepth = (codebook_setup->maxdepth+codebook_setup->nb_bits - 1) / codebook_setup->nb_bits;
  367. if ((ret = init_vlc(&codebook_setup->vlc, codebook_setup->nb_bits,
  368. entries, tmp_vlc_bits, sizeof(*tmp_vlc_bits),
  369. sizeof(*tmp_vlc_bits), tmp_vlc_codes,
  370. sizeof(*tmp_vlc_codes), sizeof(*tmp_vlc_codes),
  371. INIT_VLC_LE))) {
  372. av_log(vc->avccontext, AV_LOG_ERROR, " Error generating vlc tables. \n");
  373. goto error;
  374. }
  375. }
  376. av_free(tmp_vlc_bits);
  377. av_free(tmp_vlc_codes);
  378. av_free(codebook_multiplicands);
  379. return 0;
  380. // Error:
  381. error:
  382. av_free(tmp_vlc_bits);
  383. av_free(tmp_vlc_codes);
  384. av_free(codebook_multiplicands);
  385. return ret;
  386. }
  387. // Process time domain transforms part (unused in Vorbis I)
  388. static int vorbis_parse_setup_hdr_tdtransforms(vorbis_context *vc)
  389. {
  390. GetBitContext *gb = &vc->gb;
  391. unsigned i, vorbis_time_count = get_bits(gb, 6) + 1;
  392. for (i = 0; i < vorbis_time_count; ++i) {
  393. unsigned vorbis_tdtransform = get_bits(gb, 16);
  394. av_dlog(NULL, " Vorbis time domain transform %u: %u\n",
  395. vorbis_time_count, vorbis_tdtransform);
  396. if (vorbis_tdtransform) {
  397. av_log(vc->avccontext, AV_LOG_ERROR, "Vorbis time domain transform data nonzero. \n");
  398. return AVERROR_INVALIDDATA;
  399. }
  400. }
  401. return 0;
  402. }
  403. // Process floors part
  404. static int vorbis_floor0_decode(vorbis_context *vc,
  405. vorbis_floor_data *vfu, float *vec);
  406. static void create_map(vorbis_context *vc, unsigned floor_number);
  407. static int vorbis_floor1_decode(vorbis_context *vc,
  408. vorbis_floor_data *vfu, float *vec);
  409. static int vorbis_parse_setup_hdr_floors(vorbis_context *vc)
  410. {
  411. GetBitContext *gb = &vc->gb;
  412. int i,j,k;
  413. vc->floor_count = get_bits(gb, 6) + 1;
  414. vc->floors = av_mallocz(vc->floor_count * sizeof(*vc->floors));
  415. for (i = 0; i < vc->floor_count; ++i) {
  416. vorbis_floor *floor_setup = &vc->floors[i];
  417. floor_setup->floor_type = get_bits(gb, 16);
  418. av_dlog(NULL, " %d. floor type %d \n", i, floor_setup->floor_type);
  419. if (floor_setup->floor_type == 1) {
  420. int maximum_class = -1;
  421. unsigned rangebits, rangemax, floor1_values = 2;
  422. floor_setup->decode = vorbis_floor1_decode;
  423. floor_setup->data.t1.partitions = get_bits(gb, 5);
  424. av_dlog(NULL, " %d.floor: %d partitions \n",
  425. i, floor_setup->data.t1.partitions);
  426. for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
  427. floor_setup->data.t1.partition_class[j] = get_bits(gb, 4);
  428. if (floor_setup->data.t1.partition_class[j] > maximum_class)
  429. maximum_class = floor_setup->data.t1.partition_class[j];
  430. av_dlog(NULL, " %d. floor %d partition class %d \n",
  431. i, j, floor_setup->data.t1.partition_class[j]);
  432. }
  433. av_dlog(NULL, " maximum class %d \n", maximum_class);
  434. for (j = 0; j <= maximum_class; ++j) {
  435. floor_setup->data.t1.class_dimensions[j] = get_bits(gb, 3) + 1;
  436. floor_setup->data.t1.class_subclasses[j] = get_bits(gb, 2);
  437. av_dlog(NULL, " %d floor %d class dim: %d subclasses %d \n", i, j,
  438. floor_setup->data.t1.class_dimensions[j],
  439. floor_setup->data.t1.class_subclasses[j]);
  440. if (floor_setup->data.t1.class_subclasses[j]) {
  441. GET_VALIDATED_INDEX(floor_setup->data.t1.class_masterbook[j], 8, vc->codebook_count)
  442. av_dlog(NULL, " masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);
  443. }
  444. for (k = 0; k < (1 << floor_setup->data.t1.class_subclasses[j]); ++k) {
  445. int16_t bits = get_bits(gb, 8) - 1;
  446. if (bits != -1)
  447. VALIDATE_INDEX(bits, vc->codebook_count)
  448. floor_setup->data.t1.subclass_books[j][k] = bits;
  449. av_dlog(NULL, " book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);
  450. }
  451. }
  452. floor_setup->data.t1.multiplier = get_bits(gb, 2) + 1;
  453. floor_setup->data.t1.x_list_dim = 2;
  454. for (j = 0; j < floor_setup->data.t1.partitions; ++j)
  455. floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];
  456. floor_setup->data.t1.list = av_mallocz(floor_setup->data.t1.x_list_dim *
  457. sizeof(*floor_setup->data.t1.list));
  458. rangebits = get_bits(gb, 4);
  459. rangemax = (1 << rangebits);
  460. if (rangemax > vc->blocksize[1] / 2) {
  461. av_log(vc->avccontext, AV_LOG_ERROR,
  462. "Floor value is too large for blocksize: %u (%"PRIu32")\n",
  463. rangemax, vc->blocksize[1] / 2);
  464. return AVERROR_INVALIDDATA;
  465. }
  466. floor_setup->data.t1.list[0].x = 0;
  467. floor_setup->data.t1.list[1].x = rangemax;
  468. for (j = 0; j < floor_setup->data.t1.partitions; ++j) {
  469. for (k = 0; k < floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]]; ++k, ++floor1_values) {
  470. floor_setup->data.t1.list[floor1_values].x = get_bits(gb, rangebits);
  471. av_dlog(NULL, " %u. floor1 Y coord. %d\n", floor1_values,
  472. floor_setup->data.t1.list[floor1_values].x);
  473. }
  474. }
  475. // Precalculate order of x coordinates - needed for decode
  476. ff_vorbis_ready_floor1_list(floor_setup->data.t1.list, floor_setup->data.t1.x_list_dim);
  477. } else if (floor_setup->floor_type == 0) {
  478. unsigned max_codebook_dim = 0;
  479. floor_setup->decode = vorbis_floor0_decode;
  480. floor_setup->data.t0.order = get_bits(gb, 8);
  481. floor_setup->data.t0.rate = get_bits(gb, 16);
  482. floor_setup->data.t0.bark_map_size = get_bits(gb, 16);
  483. floor_setup->data.t0.amplitude_bits = get_bits(gb, 6);
  484. /* zero would result in a div by zero later *
  485. * 2^0 - 1 == 0 */
  486. if (floor_setup->data.t0.amplitude_bits == 0) {
  487. av_log(vc->avccontext, AV_LOG_ERROR,
  488. "Floor 0 amplitude bits is 0.\n");
  489. return AVERROR_INVALIDDATA;
  490. }
  491. floor_setup->data.t0.amplitude_offset = get_bits(gb, 8);
  492. floor_setup->data.t0.num_books = get_bits(gb, 4) + 1;
  493. /* allocate mem for booklist */
  494. floor_setup->data.t0.book_list =
  495. av_malloc(floor_setup->data.t0.num_books);
  496. if (!floor_setup->data.t0.book_list)
  497. return AVERROR(ENOMEM);
  498. /* read book indexes */
  499. {
  500. int idx;
  501. unsigned book_idx;
  502. for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
  503. GET_VALIDATED_INDEX(book_idx, 8, vc->codebook_count)
  504. floor_setup->data.t0.book_list[idx] = book_idx;
  505. if (vc->codebooks[book_idx].dimensions > max_codebook_dim)
  506. max_codebook_dim = vc->codebooks[book_idx].dimensions;
  507. }
  508. }
  509. create_map(vc, i);
  510. /* codebook dim is for padding if codebook dim doesn't *
  511. * divide order+1 then we need to read more data */
  512. floor_setup->data.t0.lsp =
  513. av_malloc((floor_setup->data.t0.order + 1 + max_codebook_dim)
  514. * sizeof(*floor_setup->data.t0.lsp));
  515. if (!floor_setup->data.t0.lsp)
  516. return AVERROR(ENOMEM);
  517. /* debug output parsed headers */
  518. av_dlog(NULL, "floor0 order: %u\n", floor_setup->data.t0.order);
  519. av_dlog(NULL, "floor0 rate: %u\n", floor_setup->data.t0.rate);
  520. av_dlog(NULL, "floor0 bark map size: %u\n",
  521. floor_setup->data.t0.bark_map_size);
  522. av_dlog(NULL, "floor0 amplitude bits: %u\n",
  523. floor_setup->data.t0.amplitude_bits);
  524. av_dlog(NULL, "floor0 amplitude offset: %u\n",
  525. floor_setup->data.t0.amplitude_offset);
  526. av_dlog(NULL, "floor0 number of books: %u\n",
  527. floor_setup->data.t0.num_books);
  528. av_dlog(NULL, "floor0 book list pointer: %p\n",
  529. floor_setup->data.t0.book_list);
  530. {
  531. int idx;
  532. for (idx = 0; idx < floor_setup->data.t0.num_books; ++idx) {
  533. av_dlog(NULL, " Book %d: %u\n", idx + 1,
  534. floor_setup->data.t0.book_list[idx]);
  535. }
  536. }
  537. } else {
  538. av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");
  539. return AVERROR_INVALIDDATA;
  540. }
  541. }
  542. return 0;
  543. }
  544. // Process residues part
  545. static int vorbis_parse_setup_hdr_residues(vorbis_context *vc)
  546. {
  547. GetBitContext *gb = &vc->gb;
  548. unsigned i, j, k;
  549. vc->residue_count = get_bits(gb, 6)+1;
  550. vc->residues = av_mallocz(vc->residue_count * sizeof(*vc->residues));
  551. av_dlog(NULL, " There are %d residues. \n", vc->residue_count);
  552. for (i = 0; i < vc->residue_count; ++i) {
  553. vorbis_residue *res_setup = &vc->residues[i];
  554. uint8_t cascade[64];
  555. unsigned high_bits, low_bits;
  556. res_setup->type = get_bits(gb, 16);
  557. av_dlog(NULL, " %u. residue type %d\n", i, res_setup->type);
  558. res_setup->begin = get_bits(gb, 24);
  559. res_setup->end = get_bits(gb, 24);
  560. res_setup->partition_size = get_bits(gb, 24) + 1;
  561. /* Validations to prevent a buffer overflow later. */
  562. if (res_setup->begin>res_setup->end ||
  563. res_setup->end > vc->avccontext->channels * vc->blocksize[1] / 2 ||
  564. (res_setup->end-res_setup->begin) / res_setup->partition_size > V_MAX_PARTITIONS) {
  565. av_log(vc->avccontext, AV_LOG_ERROR,
  566. "partition out of bounds: type, begin, end, size, blocksize: %"PRIu16", %"PRIu32", %"PRIu32", %u, %"PRIu32"\n",
  567. res_setup->type, res_setup->begin, res_setup->end,
  568. res_setup->partition_size, vc->blocksize[1] / 2);
  569. return AVERROR_INVALIDDATA;
  570. }
  571. res_setup->classifications = get_bits(gb, 6) + 1;
  572. GET_VALIDATED_INDEX(res_setup->classbook, 8, vc->codebook_count)
  573. res_setup->ptns_to_read =
  574. (res_setup->end - res_setup->begin) / res_setup->partition_size;
  575. res_setup->classifs = av_malloc(res_setup->ptns_to_read *
  576. vc->audio_channels *
  577. sizeof(*res_setup->classifs));
  578. if (!res_setup->classifs)
  579. return AVERROR(ENOMEM);
  580. av_dlog(NULL, " begin %d end %d part.size %d classif.s %d classbook %d \n",
  581. res_setup->begin, res_setup->end, res_setup->partition_size,
  582. res_setup->classifications, res_setup->classbook);
  583. for (j = 0; j < res_setup->classifications; ++j) {
  584. high_bits = 0;
  585. low_bits = get_bits(gb, 3);
  586. if (get_bits1(gb))
  587. high_bits = get_bits(gb, 5);
  588. cascade[j] = (high_bits << 3) + low_bits;
  589. av_dlog(NULL, " %u class cascade depth: %d\n", j, ilog(cascade[j]));
  590. }
  591. res_setup->maxpass = 0;
  592. for (j = 0; j < res_setup->classifications; ++j) {
  593. for (k = 0; k < 8; ++k) {
  594. if (cascade[j]&(1 << k)) {
  595. GET_VALIDATED_INDEX(res_setup->books[j][k], 8, vc->codebook_count)
  596. av_dlog(NULL, " %u class cascade depth %u book: %d\n",
  597. j, k, res_setup->books[j][k]);
  598. if (k>res_setup->maxpass)
  599. res_setup->maxpass = k;
  600. } else {
  601. res_setup->books[j][k] = -1;
  602. }
  603. }
  604. }
  605. }
  606. return 0;
  607. }
  608. // Process mappings part
  609. static int vorbis_parse_setup_hdr_mappings(vorbis_context *vc)
  610. {
  611. GetBitContext *gb = &vc->gb;
  612. unsigned i, j;
  613. vc->mapping_count = get_bits(gb, 6)+1;
  614. vc->mappings = av_mallocz(vc->mapping_count * sizeof(*vc->mappings));
  615. av_dlog(NULL, " There are %d mappings. \n", vc->mapping_count);
  616. for (i = 0; i < vc->mapping_count; ++i) {
  617. vorbis_mapping *mapping_setup = &vc->mappings[i];
  618. if (get_bits(gb, 16)) {
  619. av_log(vc->avccontext, AV_LOG_ERROR, "Other mappings than type 0 are not compliant with the Vorbis I specification. \n");
  620. return AVERROR_INVALIDDATA;
  621. }
  622. if (get_bits1(gb)) {
  623. mapping_setup->submaps = get_bits(gb, 4) + 1;
  624. } else {
  625. mapping_setup->submaps = 1;
  626. }
  627. if (get_bits1(gb)) {
  628. mapping_setup->coupling_steps = get_bits(gb, 8) + 1;
  629. mapping_setup->magnitude = av_mallocz(mapping_setup->coupling_steps *
  630. sizeof(*mapping_setup->magnitude));
  631. mapping_setup->angle = av_mallocz(mapping_setup->coupling_steps *
  632. sizeof(*mapping_setup->angle));
  633. for (j = 0; j < mapping_setup->coupling_steps; ++j) {
  634. GET_VALIDATED_INDEX(mapping_setup->magnitude[j], ilog(vc->audio_channels - 1), vc->audio_channels)
  635. GET_VALIDATED_INDEX(mapping_setup->angle[j], ilog(vc->audio_channels - 1), vc->audio_channels)
  636. }
  637. } else {
  638. mapping_setup->coupling_steps = 0;
  639. }
  640. av_dlog(NULL, " %u mapping coupling steps: %d\n",
  641. i, mapping_setup->coupling_steps);
  642. if (get_bits(gb, 2)) {
  643. av_log(vc->avccontext, AV_LOG_ERROR, "%u. mapping setup data invalid.\n", i);
  644. return AVERROR_INVALIDDATA; // following spec.
  645. }
  646. if (mapping_setup->submaps>1) {
  647. mapping_setup->mux = av_mallocz(vc->audio_channels *
  648. sizeof(*mapping_setup->mux));
  649. for (j = 0; j < vc->audio_channels; ++j)
  650. mapping_setup->mux[j] = get_bits(gb, 4);
  651. }
  652. for (j = 0; j < mapping_setup->submaps; ++j) {
  653. skip_bits(gb, 8); // FIXME check?
  654. GET_VALIDATED_INDEX(mapping_setup->submap_floor[j], 8, vc->floor_count)
  655. GET_VALIDATED_INDEX(mapping_setup->submap_residue[j], 8, vc->residue_count)
  656. av_dlog(NULL, " %u mapping %u submap : floor %d, residue %d\n", i, j,
  657. mapping_setup->submap_floor[j],
  658. mapping_setup->submap_residue[j]);
  659. }
  660. }
  661. return 0;
  662. }
  663. // Process modes part
  664. static void create_map(vorbis_context *vc, unsigned floor_number)
  665. {
  666. vorbis_floor *floors = vc->floors;
  667. vorbis_floor0 *vf;
  668. int idx;
  669. int blockflag, n;
  670. int32_t *map;
  671. for (blockflag = 0; blockflag < 2; ++blockflag) {
  672. n = vc->blocksize[blockflag] / 2;
  673. floors[floor_number].data.t0.map[blockflag] =
  674. av_malloc((n + 1) * sizeof(int32_t)); // n + sentinel
  675. map = floors[floor_number].data.t0.map[blockflag];
  676. vf = &floors[floor_number].data.t0;
  677. for (idx = 0; idx < n; ++idx) {
  678. map[idx] = floor(BARK((vf->rate * idx) / (2.0f * n)) *
  679. ((vf->bark_map_size) /
  680. BARK(vf->rate / 2.0f)));
  681. if (vf->bark_map_size-1 < map[idx])
  682. map[idx] = vf->bark_map_size - 1;
  683. }
  684. map[n] = -1;
  685. vf->map_size[blockflag] = n;
  686. }
  687. for (idx = 0; idx <= n; ++idx) {
  688. av_dlog(NULL, "floor0 map: map at pos %d is %d\n", idx, map[idx]);
  689. }
  690. }
  691. static int vorbis_parse_setup_hdr_modes(vorbis_context *vc)
  692. {
  693. GetBitContext *gb = &vc->gb;
  694. unsigned i;
  695. vc->mode_count = get_bits(gb, 6) + 1;
  696. vc->modes = av_mallocz(vc->mode_count * sizeof(*vc->modes));
  697. av_dlog(NULL, " There are %d modes.\n", vc->mode_count);
  698. for (i = 0; i < vc->mode_count; ++i) {
  699. vorbis_mode *mode_setup = &vc->modes[i];
  700. mode_setup->blockflag = get_bits1(gb);
  701. mode_setup->windowtype = get_bits(gb, 16); //FIXME check
  702. mode_setup->transformtype = get_bits(gb, 16); //FIXME check
  703. GET_VALIDATED_INDEX(mode_setup->mapping, 8, vc->mapping_count);
  704. av_dlog(NULL, " %u mode: blockflag %d, windowtype %d, transformtype %d, mapping %d\n",
  705. i, mode_setup->blockflag, mode_setup->windowtype,
  706. mode_setup->transformtype, mode_setup->mapping);
  707. }
  708. return 0;
  709. }
  710. // Process the whole setup header using the functions above
  711. static int vorbis_parse_setup_hdr(vorbis_context *vc)
  712. {
  713. GetBitContext *gb = &vc->gb;
  714. int ret;
  715. if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
  716. (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
  717. (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
  718. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (no vorbis signature). \n");
  719. return AVERROR_INVALIDDATA;
  720. }
  721. if ((ret = vorbis_parse_setup_hdr_codebooks(vc))) {
  722. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (codebooks). \n");
  723. return ret;
  724. }
  725. if ((ret = vorbis_parse_setup_hdr_tdtransforms(vc))) {
  726. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (time domain transforms). \n");
  727. return ret;
  728. }
  729. if ((ret = vorbis_parse_setup_hdr_floors(vc))) {
  730. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (floors). \n");
  731. return ret;
  732. }
  733. if ((ret = vorbis_parse_setup_hdr_residues(vc))) {
  734. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (residues). \n");
  735. return ret;
  736. }
  737. if ((ret = vorbis_parse_setup_hdr_mappings(vc))) {
  738. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (mappings). \n");
  739. return ret;
  740. }
  741. if ((ret = vorbis_parse_setup_hdr_modes(vc))) {
  742. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (modes). \n");
  743. return ret;
  744. }
  745. if (!get_bits1(gb)) {
  746. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis setup header packet corrupt (framing flag). \n");
  747. return AVERROR_INVALIDDATA; // framing flag bit unset error
  748. }
  749. return 0;
  750. }
  751. // Process the identification header
  752. static int vorbis_parse_id_hdr(vorbis_context *vc)
  753. {
  754. GetBitContext *gb = &vc->gb;
  755. unsigned bl0, bl1;
  756. if ((get_bits(gb, 8) != 'v') || (get_bits(gb, 8) != 'o') ||
  757. (get_bits(gb, 8) != 'r') || (get_bits(gb, 8) != 'b') ||
  758. (get_bits(gb, 8) != 'i') || (get_bits(gb, 8) != 's')) {
  759. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (no vorbis signature). \n");
  760. return AVERROR_INVALIDDATA;
  761. }
  762. vc->version = get_bits_long(gb, 32); //FIXME check 0
  763. vc->audio_channels = get_bits(gb, 8);
  764. if (vc->audio_channels <= 0) {
  765. av_log(vc->avccontext, AV_LOG_ERROR, "Invalid number of channels\n");
  766. return AVERROR_INVALIDDATA;
  767. }
  768. vc->audio_samplerate = get_bits_long(gb, 32);
  769. if (vc->audio_samplerate <= 0) {
  770. av_log(vc->avccontext, AV_LOG_ERROR, "Invalid samplerate\n");
  771. return AVERROR_INVALIDDATA;
  772. }
  773. vc->bitrate_maximum = get_bits_long(gb, 32);
  774. vc->bitrate_nominal = get_bits_long(gb, 32);
  775. vc->bitrate_minimum = get_bits_long(gb, 32);
  776. bl0 = get_bits(gb, 4);
  777. bl1 = get_bits(gb, 4);
  778. vc->blocksize[0] = (1 << bl0);
  779. vc->blocksize[1] = (1 << bl1);
  780. if (bl0 > 13 || bl0 < 6 || bl1 > 13 || bl1 < 6 || bl1 < bl0) {
  781. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (illegal blocksize). \n");
  782. return AVERROR_INVALIDDATA;
  783. }
  784. vc->win[0] = ff_vorbis_vwin[bl0 - 6];
  785. vc->win[1] = ff_vorbis_vwin[bl1 - 6];
  786. if ((get_bits1(gb)) == 0) {
  787. av_log(vc->avccontext, AV_LOG_ERROR, " Vorbis id header packet corrupt (framing flag not set). \n");
  788. return AVERROR_INVALIDDATA;
  789. }
  790. vc->channel_residues = av_malloc((vc->blocksize[1] / 2) * vc->audio_channels * sizeof(*vc->channel_residues));
  791. vc->channel_floors = av_malloc((vc->blocksize[1] / 2) * vc->audio_channels * sizeof(*vc->channel_floors));
  792. vc->saved = av_mallocz((vc->blocksize[1] / 4) * vc->audio_channels * sizeof(*vc->saved));
  793. vc->previous_window = 0;
  794. ff_mdct_init(&vc->mdct[0], bl0, 1, -vc->scale_bias);
  795. ff_mdct_init(&vc->mdct[1], bl1, 1, -vc->scale_bias);
  796. av_dlog(NULL, " vorbis version %d \n audio_channels %d \n audio_samplerate %d \n bitrate_max %d \n bitrate_nom %d \n bitrate_min %d \n blk_0 %d blk_1 %d \n ",
  797. vc->version, vc->audio_channels, vc->audio_samplerate, vc->bitrate_maximum, vc->bitrate_nominal, vc->bitrate_minimum, vc->blocksize[0], vc->blocksize[1]);
  798. /*
  799. BLK = vc->blocksize[0];
  800. for (i = 0; i < BLK / 2; ++i) {
  801. vc->win[0][i] = sin(0.5*3.14159265358*(sin(((float)i + 0.5) / (float)BLK*3.14159265358))*(sin(((float)i + 0.5) / (float)BLK*3.14159265358)));
  802. }
  803. */
  804. return 0;
  805. }
  806. // Process the extradata using the functions above (identification header, setup header)
  807. static av_cold int vorbis_decode_init(AVCodecContext *avccontext)
  808. {
  809. vorbis_context *vc = avccontext->priv_data;
  810. uint8_t *headers = avccontext->extradata;
  811. int headers_len = avccontext->extradata_size;
  812. uint8_t *header_start[3];
  813. int header_len[3];
  814. GetBitContext *gb = &(vc->gb);
  815. int hdr_type, ret;
  816. vc->avccontext = avccontext;
  817. dsputil_init(&vc->dsp, avccontext);
  818. ff_fmt_convert_init(&vc->fmt_conv, avccontext);
  819. if (avccontext->request_sample_fmt == AV_SAMPLE_FMT_FLT) {
  820. avccontext->sample_fmt = AV_SAMPLE_FMT_FLT;
  821. vc->scale_bias = 1.0f;
  822. } else {
  823. avccontext->sample_fmt = AV_SAMPLE_FMT_S16;
  824. vc->scale_bias = 32768.0f;
  825. }
  826. if (!headers_len) {
  827. av_log(avccontext, AV_LOG_ERROR, "Extradata missing.\n");
  828. return AVERROR_INVALIDDATA;
  829. }
  830. if ((ret = avpriv_split_xiph_headers(headers, headers_len, 30, header_start, header_len)) < 0) {
  831. av_log(avccontext, AV_LOG_ERROR, "Extradata corrupt.\n");
  832. return ret;
  833. }
  834. init_get_bits(gb, header_start[0], header_len[0]*8);
  835. hdr_type = get_bits(gb, 8);
  836. if (hdr_type != 1) {
  837. av_log(avccontext, AV_LOG_ERROR, "First header is not the id header.\n");
  838. return AVERROR_INVALIDDATA;
  839. }
  840. if ((ret = vorbis_parse_id_hdr(vc))) {
  841. av_log(avccontext, AV_LOG_ERROR, "Id header corrupt.\n");
  842. vorbis_free(vc);
  843. return ret;
  844. }
  845. init_get_bits(gb, header_start[2], header_len[2]*8);
  846. hdr_type = get_bits(gb, 8);
  847. if (hdr_type != 5) {
  848. av_log(avccontext, AV_LOG_ERROR, "Third header is not the setup header.\n");
  849. vorbis_free(vc);
  850. return AVERROR_INVALIDDATA;
  851. }
  852. if ((ret = vorbis_parse_setup_hdr(vc))) {
  853. av_log(avccontext, AV_LOG_ERROR, "Setup header corrupt.\n");
  854. vorbis_free(vc);
  855. return ret;
  856. }
  857. if (vc->audio_channels > 8)
  858. avccontext->channel_layout = 0;
  859. else
  860. avccontext->channel_layout = ff_vorbis_channel_layouts[vc->audio_channels - 1];
  861. avccontext->channels = vc->audio_channels;
  862. avccontext->sample_rate = vc->audio_samplerate;
  863. avccontext->frame_size = FFMIN(vc->blocksize[0], vc->blocksize[1]) >> 2;
  864. return 0;
  865. }
  866. // Decode audiopackets -------------------------------------------------
  867. // Read and decode floor
  868. static int vorbis_floor0_decode(vorbis_context *vc,
  869. vorbis_floor_data *vfu, float *vec)
  870. {
  871. vorbis_floor0 *vf = &vfu->t0;
  872. float *lsp = vf->lsp;
  873. unsigned amplitude, book_idx;
  874. unsigned blockflag = vc->modes[vc->mode_number].blockflag;
  875. amplitude = get_bits(&vc->gb, vf->amplitude_bits);
  876. if (amplitude > 0) {
  877. float last = 0;
  878. unsigned idx, lsp_len = 0;
  879. vorbis_codebook codebook;
  880. book_idx = get_bits(&vc->gb, ilog(vf->num_books));
  881. if (book_idx >= vf->num_books) {
  882. av_log(vc->avccontext, AV_LOG_ERROR,
  883. "floor0 dec: booknumber too high!\n");
  884. book_idx = 0;
  885. }
  886. av_dlog(NULL, "floor0 dec: booknumber: %u\n", book_idx);
  887. codebook = vc->codebooks[vf->book_list[book_idx]];
  888. /* Invalid codebook! */
  889. if (!codebook.codevectors)
  890. return AVERROR_INVALIDDATA;
  891. while (lsp_len<vf->order) {
  892. int vec_off;
  893. av_dlog(NULL, "floor0 dec: book dimension: %d\n", codebook.dimensions);
  894. av_dlog(NULL, "floor0 dec: maximum depth: %d\n", codebook.maxdepth);
  895. /* read temp vector */
  896. vec_off = get_vlc2(&vc->gb, codebook.vlc.table,
  897. codebook.nb_bits, codebook.maxdepth)
  898. * codebook.dimensions;
  899. av_dlog(NULL, "floor0 dec: vector offset: %d\n", vec_off);
  900. /* copy each vector component and add last to it */
  901. for (idx = 0; idx < codebook.dimensions; ++idx)
  902. lsp[lsp_len+idx] = codebook.codevectors[vec_off+idx] + last;
  903. last = lsp[lsp_len+idx-1]; /* set last to last vector component */
  904. lsp_len += codebook.dimensions;
  905. }
  906. /* DEBUG: output lsp coeffs */
  907. {
  908. int idx;
  909. for (idx = 0; idx < lsp_len; ++idx)
  910. av_dlog(NULL, "floor0 dec: coeff at %d is %f\n", idx, lsp[idx]);
  911. }
  912. /* synthesize floor output vector */
  913. {
  914. int i;
  915. int order = vf->order;
  916. float wstep = M_PI / vf->bark_map_size;
  917. for (i = 0; i < order; i++)
  918. lsp[i] = 2.0f * cos(lsp[i]);
  919. av_dlog(NULL, "floor0 synth: map_size = %"PRIu32"; m = %d; wstep = %f\n",
  920. vf->map_size[blockflag], order, wstep);
  921. i = 0;
  922. while (i < vf->map_size[blockflag]) {
  923. int j, iter_cond = vf->map[blockflag][i];
  924. float p = 0.5f;
  925. float q = 0.5f;
  926. float two_cos_w = 2.0f * cos(wstep * iter_cond); // needed all times
  927. /* similar part for the q and p products */
  928. for (j = 0; j + 1 < order; j += 2) {
  929. q *= lsp[j] - two_cos_w;
  930. p *= lsp[j + 1] - two_cos_w;
  931. }
  932. if (j == order) { // even order
  933. p *= p * (2.0f - two_cos_w);
  934. q *= q * (2.0f + two_cos_w);
  935. } else { // odd order
  936. q *= two_cos_w-lsp[j]; // one more time for q
  937. /* final step and square */
  938. p *= p * (4.f - two_cos_w * two_cos_w);
  939. q *= q;
  940. }
  941. /* calculate linear floor value */
  942. q = exp((((amplitude*vf->amplitude_offset) /
  943. (((1 << vf->amplitude_bits) - 1) * sqrt(p + q)))
  944. - vf->amplitude_offset) * .11512925f);
  945. /* fill vector */
  946. do {
  947. vec[i] = q; ++i;
  948. } while (vf->map[blockflag][i] == iter_cond);
  949. }
  950. }
  951. } else {
  952. /* this channel is unused */
  953. return 1;
  954. }
  955. av_dlog(NULL, " Floor0 decoded\n");
  956. return 0;
  957. }
  958. static int vorbis_floor1_decode(vorbis_context *vc,
  959. vorbis_floor_data *vfu, float *vec)
  960. {
  961. vorbis_floor1 *vf = &vfu->t1;
  962. GetBitContext *gb = &vc->gb;
  963. uint16_t range_v[4] = { 256, 128, 86, 64 };
  964. unsigned range = range_v[vf->multiplier - 1];
  965. uint16_t floor1_Y[258];
  966. uint16_t floor1_Y_final[258];
  967. int floor1_flag[258];
  968. unsigned partition_class, cdim, cbits, csub, cval, offset, i, j;
  969. int book, adx, ady, dy, off, predicted, err;
  970. if (!get_bits1(gb)) // silence
  971. return 1;
  972. // Read values (or differences) for the floor's points
  973. floor1_Y[0] = get_bits(gb, ilog(range - 1));
  974. floor1_Y[1] = get_bits(gb, ilog(range - 1));
  975. av_dlog(NULL, "floor 0 Y %d floor 1 Y %d \n", floor1_Y[0], floor1_Y[1]);
  976. offset = 2;
  977. for (i = 0; i < vf->partitions; ++i) {
  978. partition_class = vf->partition_class[i];
  979. cdim = vf->class_dimensions[partition_class];
  980. cbits = vf->class_subclasses[partition_class];
  981. csub = (1 << cbits) - 1;
  982. cval = 0;
  983. av_dlog(NULL, "Cbits %u\n", cbits);
  984. if (cbits) // this reads all subclasses for this partition's class
  985. cval = get_vlc2(gb, vc->codebooks[vf->class_masterbook[partition_class]].vlc.table,
  986. vc->codebooks[vf->class_masterbook[partition_class]].nb_bits, 3);
  987. for (j = 0; j < cdim; ++j) {
  988. book = vf->subclass_books[partition_class][cval & csub];
  989. av_dlog(NULL, "book %d Cbits %u cval %u bits:%d\n",
  990. book, cbits, cval, get_bits_count(gb));
  991. cval = cval >> cbits;
  992. if (book > -1) {
  993. floor1_Y[offset+j] = get_vlc2(gb, vc->codebooks[book].vlc.table,
  994. vc->codebooks[book].nb_bits, 3);
  995. } else {
  996. floor1_Y[offset+j] = 0;
  997. }
  998. av_dlog(NULL, " floor(%d) = %d \n",
  999. vf->list[offset+j].x, floor1_Y[offset+j]);
  1000. }
  1001. offset+=cdim;
  1002. }
  1003. // Amplitude calculation from the differences
  1004. floor1_flag[0] = 1;
  1005. floor1_flag[1] = 1;
  1006. floor1_Y_final[0] = floor1_Y[0];
  1007. floor1_Y_final[1] = floor1_Y[1];
  1008. for (i = 2; i < vf->x_list_dim; ++i) {
  1009. unsigned val, highroom, lowroom, room, high_neigh_offs, low_neigh_offs;
  1010. low_neigh_offs = vf->list[i].low;
  1011. high_neigh_offs = vf->list[i].high;
  1012. dy = floor1_Y_final[high_neigh_offs] - floor1_Y_final[low_neigh_offs]; // render_point begin
  1013. adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x;
  1014. ady = FFABS(dy);
  1015. err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x);
  1016. off = err / adx;
  1017. if (dy < 0) {
  1018. predicted = floor1_Y_final[low_neigh_offs] - off;
  1019. } else {
  1020. predicted = floor1_Y_final[low_neigh_offs] + off;
  1021. } // render_point end
  1022. val = floor1_Y[i];
  1023. highroom = range-predicted;
  1024. lowroom = predicted;
  1025. if (highroom < lowroom) {
  1026. room = highroom * 2;
  1027. } else {
  1028. room = lowroom * 2; // SPEC mispelling
  1029. }
  1030. if (val) {
  1031. floor1_flag[low_neigh_offs] = 1;
  1032. floor1_flag[high_neigh_offs] = 1;
  1033. floor1_flag[i] = 1;
  1034. if (val >= room) {
  1035. if (highroom > lowroom) {
  1036. floor1_Y_final[i] = val - lowroom + predicted;
  1037. } else {
  1038. floor1_Y_final[i] = predicted - val + highroom - 1;
  1039. }
  1040. } else {
  1041. if (val & 1) {
  1042. floor1_Y_final[i] = predicted - (val + 1) / 2;
  1043. } else {
  1044. floor1_Y_final[i] = predicted + val / 2;
  1045. }
  1046. }
  1047. } else {
  1048. floor1_flag[i] = 0;
  1049. floor1_Y_final[i] = predicted;
  1050. }
  1051. av_dlog(NULL, " Decoded floor(%d) = %u / val %u\n",
  1052. vf->list[i].x, floor1_Y_final[i], val);
  1053. }
  1054. // Curve synth - connect the calculated dots and convert from dB scale FIXME optimize ?
  1055. ff_vorbis_floor1_render_list(vf->list, vf->x_list_dim, floor1_Y_final, floor1_flag, vf->multiplier, vec, vf->list[1].x);
  1056. av_dlog(NULL, " Floor decoded\n");
  1057. return 0;
  1058. }
  1059. // Read and decode residue
  1060. static av_always_inline int vorbis_residue_decode_internal(vorbis_context *vc,
  1061. vorbis_residue *vr,
  1062. unsigned ch,
  1063. uint8_t *do_not_decode,
  1064. float *vec,
  1065. unsigned vlen,
  1066. int vr_type)
  1067. {
  1068. GetBitContext *gb = &vc->gb;
  1069. unsigned c_p_c = vc->codebooks[vr->classbook].dimensions;
  1070. unsigned ptns_to_read = vr->ptns_to_read;
  1071. uint8_t *classifs = vr->classifs;
  1072. unsigned pass, ch_used, i, j, k, l;
  1073. if (vr_type == 2) {
  1074. for (j = 1; j < ch; ++j)
  1075. do_not_decode[0] &= do_not_decode[j]; // FIXME - clobbering input
  1076. if (do_not_decode[0])
  1077. return 0;
  1078. ch_used = 1;
  1079. } else {
  1080. ch_used = ch;
  1081. }
  1082. av_dlog(NULL, " residue type 0/1/2 decode begin, ch: %d cpc %d \n", ch, c_p_c);
  1083. for (pass = 0; pass <= vr->maxpass; ++pass) { // FIXME OPTIMIZE?
  1084. uint16_t voffset, partition_count, j_times_ptns_to_read;
  1085. voffset = vr->begin;
  1086. for (partition_count = 0; partition_count < ptns_to_read;) { // SPEC error
  1087. if (!pass) {
  1088. unsigned inverse_class = ff_inverse[vr->classifications];
  1089. for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
  1090. if (!do_not_decode[j]) {
  1091. unsigned temp = get_vlc2(gb, vc->codebooks[vr->classbook].vlc.table,
  1092. vc->codebooks[vr->classbook].nb_bits, 3);
  1093. av_dlog(NULL, "Classword: %u\n", temp);
  1094. assert(vr->classifications > 1 && temp <= 65536); //needed for inverse[]
  1095. for (i = 0; i < c_p_c; ++i) {
  1096. unsigned temp2;
  1097. temp2 = (((uint64_t)temp) * inverse_class) >> 32;
  1098. if (partition_count + c_p_c - 1 - i < ptns_to_read)
  1099. classifs[j_times_ptns_to_read + partition_count + c_p_c - 1 - i] = temp - temp2 * vr->classifications;
  1100. temp = temp2;
  1101. }
  1102. }
  1103. j_times_ptns_to_read += ptns_to_read;
  1104. }
  1105. }
  1106. for (i = 0; (i < c_p_c) && (partition_count < ptns_to_read); ++i) {
  1107. for (j_times_ptns_to_read = 0, j = 0; j < ch_used; ++j) {
  1108. unsigned voffs;
  1109. if (!do_not_decode[j]) {
  1110. unsigned vqclass = classifs[j_times_ptns_to_read + partition_count];
  1111. int vqbook = vr->books[vqclass][pass];
  1112. if (vqbook >= 0 && vc->codebooks[vqbook].codevectors) {
  1113. unsigned coffs;
  1114. unsigned dim = vc->codebooks[vqbook].dimensions;
  1115. unsigned step = dim == 1 ? vr->partition_size
  1116. : FASTDIV(vr->partition_size, dim);
  1117. vorbis_codebook codebook = vc->codebooks[vqbook];
  1118. if (vr_type == 0) {
  1119. voffs = voffset+j*vlen;
  1120. for (k = 0; k < step; ++k) {
  1121. coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
  1122. for (l = 0; l < dim; ++l)
  1123. vec[voffs + k + l * step] += codebook.codevectors[coffs + l]; // FPMATH
  1124. }
  1125. } else if (vr_type == 1) {
  1126. voffs = voffset + j * vlen;
  1127. for (k = 0; k < step; ++k) {
  1128. coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
  1129. for (l = 0; l < dim; ++l, ++voffs) {
  1130. vec[voffs]+=codebook.codevectors[coffs+l]; // FPMATH
  1131. av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d \n",
  1132. pass, voffs, vec[voffs], codebook.codevectors[coffs+l], coffs);
  1133. }
  1134. }
  1135. } else if (vr_type == 2 && ch == 2 && (voffset & 1) == 0 && (dim & 1) == 0) { // most frequent case optimized
  1136. voffs = voffset >> 1;
  1137. if (dim == 2) {
  1138. for (k = 0; k < step; ++k) {
  1139. coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 2;
  1140. vec[voffs + k ] += codebook.codevectors[coffs ]; // FPMATH
  1141. vec[voffs + k + vlen] += codebook.codevectors[coffs + 1]; // FPMATH
  1142. }
  1143. } else if (dim == 4) {
  1144. for (k = 0; k < step; ++k, voffs += 2) {
  1145. coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * 4;
  1146. vec[voffs ] += codebook.codevectors[coffs ]; // FPMATH
  1147. vec[voffs + 1 ] += codebook.codevectors[coffs + 2]; // FPMATH
  1148. vec[voffs + vlen ] += codebook.codevectors[coffs + 1]; // FPMATH
  1149. vec[voffs + vlen + 1] += codebook.codevectors[coffs + 3]; // FPMATH
  1150. }
  1151. } else
  1152. for (k = 0; k < step; ++k) {
  1153. coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
  1154. for (l = 0; l < dim; l += 2, voffs++) {
  1155. vec[voffs ] += codebook.codevectors[coffs + l ]; // FPMATH
  1156. vec[voffs + vlen] += codebook.codevectors[coffs + l + 1]; // FPMATH
  1157. av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d \n",
  1158. pass, voffset / ch + (voffs % ch) * vlen,
  1159. vec[voffset / ch + (voffs % ch) * vlen],
  1160. codebook.codevectors[coffs + l], coffs, l);
  1161. }
  1162. }
  1163. } else if (vr_type == 2) {
  1164. voffs = voffset;
  1165. for (k = 0; k < step; ++k) {
  1166. coffs = get_vlc2(gb, codebook.vlc.table, codebook.nb_bits, 3) * dim;
  1167. for (l = 0; l < dim; ++l, ++voffs) {
  1168. vec[voffs / ch + (voffs % ch) * vlen] += codebook.codevectors[coffs + l]; // FPMATH FIXME use if and counter instead of / and %
  1169. av_dlog(NULL, " pass %d offs: %d curr: %f change: %f cv offs.: %d+%d \n",
  1170. pass, voffset / ch + (voffs % ch) * vlen,
  1171. vec[voffset / ch + (voffs % ch) * vlen],
  1172. codebook.codevectors[coffs + l], coffs, l);
  1173. }
  1174. }
  1175. }
  1176. }
  1177. }
  1178. j_times_ptns_to_read += ptns_to_read;
  1179. }
  1180. ++partition_count;
  1181. voffset += vr->partition_size;
  1182. }
  1183. }
  1184. }
  1185. return 0;
  1186. }
  1187. static inline int vorbis_residue_decode(vorbis_context *vc, vorbis_residue *vr,
  1188. unsigned ch,
  1189. uint8_t *do_not_decode,
  1190. float *vec, unsigned vlen)
  1191. {
  1192. if (vr->type == 2)
  1193. return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 2);
  1194. else if (vr->type == 1)
  1195. return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 1);
  1196. else if (vr->type == 0)
  1197. return vorbis_residue_decode_internal(vc, vr, ch, do_not_decode, vec, vlen, 0);
  1198. else {
  1199. av_log(vc->avccontext, AV_LOG_ERROR, " Invalid residue type while residue decode?! \n");
  1200. return AVERROR_INVALIDDATA;
  1201. }
  1202. }
  1203. void vorbis_inverse_coupling(float *mag, float *ang, int blocksize)
  1204. {
  1205. int i;
  1206. for (i = 0; i < blocksize; i++) {
  1207. if (mag[i] > 0.0) {
  1208. if (ang[i] > 0.0) {
  1209. ang[i] = mag[i] - ang[i];
  1210. } else {
  1211. float temp = ang[i];
  1212. ang[i] = mag[i];
  1213. mag[i] += temp;
  1214. }
  1215. } else {
  1216. if (ang[i] > 0.0) {
  1217. ang[i] += mag[i];
  1218. } else {
  1219. float temp = ang[i];
  1220. ang[i] = mag[i];
  1221. mag[i] -= temp;
  1222. }
  1223. }
  1224. }
  1225. }
  1226. // Decode the audio packet using the functions above
  1227. static int vorbis_parse_audio_packet(vorbis_context *vc)
  1228. {
  1229. GetBitContext *gb = &vc->gb;
  1230. FFTContext *mdct;
  1231. unsigned previous_window = vc->previous_window;
  1232. unsigned mode_number, blockflag, blocksize;
  1233. int i, j;
  1234. uint8_t no_residue[255];
  1235. uint8_t do_not_decode[255];
  1236. vorbis_mapping *mapping;
  1237. float *ch_res_ptr = vc->channel_residues;
  1238. float *ch_floor_ptr = vc->channel_floors;
  1239. uint8_t res_chan[255];
  1240. unsigned res_num = 0;
  1241. int retlen = 0;
  1242. if (get_bits1(gb)) {
  1243. av_log(vc->avccontext, AV_LOG_ERROR, "Not a Vorbis I audio packet.\n");
  1244. return AVERROR_INVALIDDATA; // packet type not audio
  1245. }
  1246. if (vc->mode_count == 1) {
  1247. mode_number = 0;
  1248. } else {
  1249. GET_VALIDATED_INDEX(mode_number, ilog(vc->mode_count-1), vc->mode_count)
  1250. }
  1251. vc->mode_number = mode_number;
  1252. mapping = &vc->mappings[vc->modes[mode_number].mapping];
  1253. av_dlog(NULL, " Mode number: %u , mapping: %d , blocktype %d\n", mode_number,
  1254. vc->modes[mode_number].mapping, vc->modes[mode_number].blockflag);
  1255. blockflag = vc->modes[mode_number].blockflag;
  1256. blocksize = vc->blocksize[blockflag];
  1257. if (blockflag)
  1258. skip_bits(gb, 2); // previous_window, next_window
  1259. memset(ch_res_ptr, 0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
  1260. memset(ch_floor_ptr, 0, sizeof(float) * vc->audio_channels * blocksize / 2); //FIXME can this be removed ?
  1261. // Decode floor
  1262. for (i = 0; i < vc->audio_channels; ++i) {
  1263. vorbis_floor *floor;
  1264. int ret;
  1265. if (mapping->submaps > 1) {
  1266. floor = &vc->floors[mapping->submap_floor[mapping->mux[i]]];
  1267. } else {
  1268. floor = &vc->floors[mapping->submap_floor[0]];
  1269. }
  1270. ret = floor->decode(vc, &floor->data, ch_floor_ptr);
  1271. if (ret < 0) {
  1272. av_log(vc->avccontext, AV_LOG_ERROR, "Invalid codebook in vorbis_floor_decode.\n");
  1273. return AVERROR_INVALIDDATA;
  1274. }
  1275. no_residue[i] = ret;
  1276. ch_floor_ptr += blocksize / 2;
  1277. }
  1278. // Nonzero vector propagate
  1279. for (i = mapping->coupling_steps - 1; i >= 0; --i) {
  1280. if (!(no_residue[mapping->magnitude[i]] & no_residue[mapping->angle[i]])) {
  1281. no_residue[mapping->magnitude[i]] = 0;
  1282. no_residue[mapping->angle[i]] = 0;
  1283. }
  1284. }
  1285. // Decode residue
  1286. for (i = 0; i < mapping->submaps; ++i) {
  1287. vorbis_residue *residue;
  1288. unsigned ch = 0;
  1289. for (j = 0; j < vc->audio_channels; ++j) {
  1290. if ((mapping->submaps == 1) || (i == mapping->mux[j])) {
  1291. res_chan[j] = res_num;
  1292. if (no_residue[j]) {
  1293. do_not_decode[ch] = 1;
  1294. } else {
  1295. do_not_decode[ch] = 0;
  1296. }
  1297. ++ch;
  1298. ++res_num;
  1299. }
  1300. }
  1301. residue = &vc->residues[mapping->submap_residue[i]];
  1302. vorbis_residue_decode(vc, residue, ch, do_not_decode, ch_res_ptr, blocksize/2);
  1303. ch_res_ptr += ch * blocksize / 2;
  1304. }
  1305. // Inverse coupling
  1306. for (i = mapping->coupling_steps - 1; i >= 0; --i) { //warning: i has to be signed
  1307. float *mag, *ang;
  1308. mag = vc->channel_residues+res_chan[mapping->magnitude[i]] * blocksize / 2;
  1309. ang = vc->channel_residues+res_chan[mapping->angle[i]] * blocksize / 2;
  1310. vc->dsp.vorbis_inverse_coupling(mag, ang, blocksize / 2);
  1311. }
  1312. // Dotproduct, MDCT
  1313. mdct = &vc->mdct[blockflag];
  1314. for (j = vc->audio_channels-1;j >= 0; j--) {
  1315. ch_floor_ptr = vc->channel_floors + j * blocksize / 2;
  1316. ch_res_ptr = vc->channel_residues + res_chan[j] * blocksize / 2;
  1317. vc->dsp.vector_fmul(ch_floor_ptr, ch_floor_ptr, ch_res_ptr, blocksize / 2);
  1318. mdct->imdct_half(mdct, ch_res_ptr, ch_floor_ptr);
  1319. }
  1320. // Overlap/add, save data for next overlapping FPMATH
  1321. retlen = (blocksize + vc->blocksize[previous_window]) / 4;
  1322. for (j = 0; j < vc->audio_channels; j++) {
  1323. unsigned bs0 = vc->blocksize[0];
  1324. unsigned bs1 = vc->blocksize[1];
  1325. float *residue = vc->channel_residues + res_chan[j] * blocksize / 2;
  1326. float *saved = vc->saved + j * bs1 / 4;
  1327. float *ret = vc->channel_floors + j * retlen;
  1328. float *buf = residue;
  1329. const float *win = vc->win[blockflag & previous_window];
  1330. if (blockflag == previous_window) {
  1331. vc->dsp.vector_fmul_window(ret, saved, buf, win, blocksize / 4);
  1332. } else if (blockflag > previous_window) {
  1333. vc->dsp.vector_fmul_window(ret, saved, buf, win, bs0 / 4);
  1334. memcpy(ret+bs0/2, buf+bs0/4, ((bs1-bs0)/4) * sizeof(float));
  1335. } else {
  1336. memcpy(ret, saved, ((bs1 - bs0) / 4) * sizeof(float));
  1337. vc->dsp.vector_fmul_window(ret + (bs1 - bs0) / 4, saved + (bs1 - bs0) / 4, buf, win, bs0 / 4);
  1338. }
  1339. memcpy(saved, buf + blocksize / 4, blocksize / 4 * sizeof(float));
  1340. }
  1341. vc->previous_window = blockflag;
  1342. return retlen;
  1343. }
  1344. // Return the decoded audio packet through the standard api
  1345. static int vorbis_decode_frame(AVCodecContext *avccontext,
  1346. void *data, int *data_size,
  1347. AVPacket *avpkt)
  1348. {
  1349. const uint8_t *buf = avpkt->data;
  1350. int buf_size = avpkt->size;
  1351. vorbis_context *vc = avccontext->priv_data;
  1352. GetBitContext *gb = &(vc->gb);
  1353. const float *channel_ptrs[255];
  1354. int i, len, out_size;
  1355. av_dlog(NULL, "packet length %d \n", buf_size);
  1356. init_get_bits(gb, buf, buf_size*8);
  1357. if ((len = vorbis_parse_audio_packet(vc)) <= 0)
  1358. return len;
  1359. if (!vc->first_frame) {
  1360. vc->first_frame = 1;
  1361. *data_size = 0;
  1362. return buf_size;
  1363. }
  1364. av_dlog(NULL, "parsed %d bytes %d bits, returned %d samples (*ch*bits) \n",
  1365. get_bits_count(gb) / 8, get_bits_count(gb) % 8, len);
  1366. out_size = len * vc->audio_channels *
  1367. av_get_bytes_per_sample(avccontext->sample_fmt);
  1368. if (*data_size < out_size) {
  1369. av_log(avccontext, AV_LOG_ERROR, "output buffer is too small\n");
  1370. return AVERROR(EINVAL);
  1371. }
  1372. if (vc->audio_channels > 8) {
  1373. for (i = 0; i < vc->audio_channels; i++)
  1374. channel_ptrs[i] = vc->channel_floors + i * len;
  1375. } else {
  1376. for (i = 0; i < vc->audio_channels; i++)
  1377. channel_ptrs[i] = vc->channel_floors +
  1378. len * ff_vorbis_channel_layout_offsets[vc->audio_channels - 1][i];
  1379. }
  1380. if (avccontext->sample_fmt == AV_SAMPLE_FMT_FLT)
  1381. vc->fmt_conv.float_interleave(data, channel_ptrs, len, vc->audio_channels);
  1382. else
  1383. vc->fmt_conv.float_to_int16_interleave(data, channel_ptrs, len,
  1384. vc->audio_channels);
  1385. *data_size = out_size;
  1386. return buf_size;
  1387. }
  1388. // Close decoder
  1389. static av_cold int vorbis_decode_close(AVCodecContext *avccontext)
  1390. {
  1391. vorbis_context *vc = avccontext->priv_data;
  1392. vorbis_free(vc);
  1393. return 0;
  1394. }
  1395. AVCodec ff_vorbis_decoder = {
  1396. .name = "vorbis",
  1397. .type = AVMEDIA_TYPE_AUDIO,
  1398. .id = CODEC_ID_VORBIS,
  1399. .priv_data_size = sizeof(vorbis_context),
  1400. .init = vorbis_decode_init,
  1401. .close = vorbis_decode_close,
  1402. .decode = vorbis_decode_frame,
  1403. .long_name = NULL_IF_CONFIG_SMALL("Vorbis"),
  1404. .channel_layouts = ff_vorbis_channel_layouts,
  1405. .sample_fmts = (const enum AVSampleFormat[]) {
  1406. AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
  1407. },
  1408. };