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.

1145 lines
36KB

  1. /*
  2. * COOK compatible decoder
  3. * Copyright (c) 2003 Sascha Sommer
  4. * Copyright (c) 2005 Benjamin Larsson
  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. /**
  24. * @file cook.c
  25. * Cook compatible decoder. Bastardization of the G.722.1 standard.
  26. * This decoder handles RealNetworks, RealAudio G2 data.
  27. * Cook is identified by the codec name cook in RM files.
  28. *
  29. * To use this decoder, a calling application must supply the extradata
  30. * bytes provided from the RM container; 8+ bytes for mono streams and
  31. * 16+ for stereo streams (maybe more).
  32. *
  33. * Codec technicalities (all this assume a buffer length of 1024):
  34. * Cook works with several different techniques to achieve its compression.
  35. * In the timedomain the buffer is divided into 8 pieces and quantized. If
  36. * two neighboring pieces have different quantization index a smooth
  37. * quantization curve is used to get a smooth overlap between the different
  38. * pieces.
  39. * To get to the transformdomain Cook uses a modulated lapped transform.
  40. * The transform domain has 50 subbands with 20 elements each. This
  41. * means only a maximum of 50*20=1000 coefficients are used out of the 1024
  42. * available.
  43. */
  44. #include <math.h>
  45. #include <stddef.h>
  46. #include <stdio.h>
  47. #include "avcodec.h"
  48. #include "bitstream.h"
  49. #include "dsputil.h"
  50. #include "common.h"
  51. #include "bytestream.h"
  52. #include "random.h"
  53. #include "cookdata.h"
  54. /* the different Cook versions */
  55. #define MONO 0x1000001
  56. #define STEREO 0x1000002
  57. #define JOINT_STEREO 0x1000003
  58. #define MC_COOK 0x2000000 //multichannel Cook, not supported
  59. #define SUBBAND_SIZE 20
  60. //#define COOKDEBUG
  61. typedef struct {
  62. int *now;
  63. int *previous;
  64. } cook_gains;
  65. typedef struct {
  66. GetBitContext gb;
  67. /* stream data */
  68. int nb_channels;
  69. int joint_stereo;
  70. int bit_rate;
  71. int sample_rate;
  72. int samples_per_channel;
  73. int samples_per_frame;
  74. int subbands;
  75. int log2_numvector_size;
  76. int numvector_size; //1 << log2_numvector_size;
  77. int js_subband_start;
  78. int total_subbands;
  79. int num_vectors;
  80. int bits_per_subpacket;
  81. int cookversion;
  82. /* states */
  83. AVRandomState random_state;
  84. /* transform data */
  85. MDCTContext mdct_ctx;
  86. DECLARE_ALIGNED_16(FFTSample, mdct_tmp[1024]); /* temporary storage for imlt */
  87. float* mlt_window;
  88. /* gain buffers */
  89. cook_gains gains1;
  90. cook_gains gains2;
  91. int gain_1[9];
  92. int gain_2[9];
  93. int gain_3[9];
  94. int gain_4[9];
  95. /* VLC data */
  96. int js_vlc_bits;
  97. VLC envelope_quant_index[13];
  98. VLC sqvh[7]; //scalar quantization
  99. VLC ccpl; //channel coupling
  100. /* generatable tables and related variables */
  101. int gain_size_factor;
  102. float gain_table[23];
  103. float pow2tab[127];
  104. float rootpow2tab[127];
  105. /* data buffers */
  106. uint8_t* decoded_bytes_buffer;
  107. DECLARE_ALIGNED_16(float,mono_mdct_output[2048]);
  108. float mono_previous_buffer1[1024];
  109. float mono_previous_buffer2[1024];
  110. float decode_buffer_1[1024];
  111. float decode_buffer_2[1024];
  112. } COOKContext;
  113. /* debug functions */
  114. #ifdef COOKDEBUG
  115. static void dump_float_table(float* table, int size, int delimiter) {
  116. int i=0;
  117. av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i);
  118. for (i=0 ; i<size ; i++) {
  119. av_log(NULL, AV_LOG_ERROR, "%5.1f, ", table[i]);
  120. if ((i+1)%delimiter == 0) av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i+1);
  121. }
  122. }
  123. static void dump_int_table(int* table, int size, int delimiter) {
  124. int i=0;
  125. av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i);
  126. for (i=0 ; i<size ; i++) {
  127. av_log(NULL, AV_LOG_ERROR, "%d, ", table[i]);
  128. if ((i+1)%delimiter == 0) av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i+1);
  129. }
  130. }
  131. static void dump_short_table(short* table, int size, int delimiter) {
  132. int i=0;
  133. av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i);
  134. for (i=0 ; i<size ; i++) {
  135. av_log(NULL, AV_LOG_ERROR, "%d, ", table[i]);
  136. if ((i+1)%delimiter == 0) av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i+1);
  137. }
  138. }
  139. #endif
  140. /*************** init functions ***************/
  141. /* table generator */
  142. static void init_pow2table(COOKContext *q){
  143. int i;
  144. q->pow2tab[63] = 1.0;
  145. for (i=1 ; i<64 ; i++){
  146. q->pow2tab[63+i]=(float)((uint64_t)1<<i);
  147. q->pow2tab[63-i]=1.0/(float)((uint64_t)1<<i);
  148. }
  149. }
  150. /* table generator */
  151. static void init_rootpow2table(COOKContext *q){
  152. int i;
  153. q->rootpow2tab[63] = 1.0;
  154. for (i=1 ; i<64 ; i++){
  155. q->rootpow2tab[63+i]=sqrt((float)((uint64_t)1<<i));
  156. q->rootpow2tab[63-i]=sqrt(1.0/(float)((uint64_t)1<<i));
  157. }
  158. }
  159. /* table generator */
  160. static void init_gain_table(COOKContext *q) {
  161. int i;
  162. q->gain_size_factor = q->samples_per_channel/8;
  163. for (i=0 ; i<23 ; i++) {
  164. q->gain_table[i] = pow((double)q->pow2tab[i+52] ,
  165. (1.0/(double)q->gain_size_factor));
  166. }
  167. }
  168. static int init_cook_vlc_tables(COOKContext *q) {
  169. int i, result;
  170. result = 0;
  171. for (i=0 ; i<13 ; i++) {
  172. result &= init_vlc (&q->envelope_quant_index[i], 9, 24,
  173. envelope_quant_index_huffbits[i], 1, 1,
  174. envelope_quant_index_huffcodes[i], 2, 2, 0);
  175. }
  176. av_log(NULL,AV_LOG_DEBUG,"sqvh VLC init\n");
  177. for (i=0 ; i<7 ; i++) {
  178. result &= init_vlc (&q->sqvh[i], vhvlcsize_tab[i], vhsize_tab[i],
  179. cvh_huffbits[i], 1, 1,
  180. cvh_huffcodes[i], 2, 2, 0);
  181. }
  182. if (q->nb_channels==2 && q->joint_stereo==1){
  183. result &= init_vlc (&q->ccpl, 6, (1<<q->js_vlc_bits)-1,
  184. ccpl_huffbits[q->js_vlc_bits-2], 1, 1,
  185. ccpl_huffcodes[q->js_vlc_bits-2], 2, 2, 0);
  186. av_log(NULL,AV_LOG_DEBUG,"Joint-stereo VLC used.\n");
  187. }
  188. av_log(NULL,AV_LOG_DEBUG,"VLC tables initialized.\n");
  189. return result;
  190. }
  191. static int init_cook_mlt(COOKContext *q) {
  192. int j;
  193. float alpha;
  194. int mlt_size = q->samples_per_channel;
  195. if ((q->mlt_window = av_malloc(sizeof(float)*mlt_size)) == 0)
  196. return -1;
  197. /* Initialize the MLT window: simple sine window. */
  198. alpha = M_PI / (2.0 * (float)mlt_size);
  199. for(j=0 ; j<mlt_size ; j++)
  200. q->mlt_window[j] = sin((j + 0.5) * alpha) * sqrt(2.0 / q->samples_per_channel);
  201. /* Initialize the MDCT. */
  202. if (ff_mdct_init(&q->mdct_ctx, av_log2(mlt_size)+1, 1)) {
  203. av_free(q->mlt_window);
  204. return -1;
  205. }
  206. av_log(NULL,AV_LOG_DEBUG,"MDCT initialized, order = %d.\n",
  207. av_log2(mlt_size)+1);
  208. return 0;
  209. }
  210. /*************** init functions end ***********/
  211. /**
  212. * Cook indata decoding, every 32 bits are XORed with 0x37c511f2.
  213. * Why? No idea, some checksum/error detection method maybe.
  214. *
  215. * Out buffer size: extra bytes are needed to cope with
  216. * padding/missalignment.
  217. * Subpackets passed to the decoder can contain two, consecutive
  218. * half-subpackets, of identical but arbitrary size.
  219. * 1234 1234 1234 1234 extraA extraB
  220. * Case 1: AAAA BBBB 0 0
  221. * Case 2: AAAA ABBB BB-- 3 3
  222. * Case 3: AAAA AABB BBBB 2 2
  223. * Case 4: AAAA AAAB BBBB BB-- 1 5
  224. *
  225. * Nice way to waste CPU cycles.
  226. *
  227. * @param inbuffer pointer to byte array of indata
  228. * @param out pointer to byte array of outdata
  229. * @param bytes number of bytes
  230. */
  231. #define DECODE_BYTES_PAD1(bytes) (3 - ((bytes)+3) % 4)
  232. #define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
  233. static inline int decode_bytes(uint8_t* inbuffer, uint8_t* out, int bytes){
  234. int i, off;
  235. uint32_t c;
  236. uint32_t* buf;
  237. uint32_t* obuf = (uint32_t*) out;
  238. /* FIXME: 64 bit platforms would be able to do 64 bits at a time.
  239. * I'm too lazy though, should be something like
  240. * for(i=0 ; i<bitamount/64 ; i++)
  241. * (int64_t)out[i] = 0x37c511f237c511f2^be2me_64(int64_t)in[i]);
  242. * Buffer alignment needs to be checked. */
  243. off = (int)((long)inbuffer & 3);
  244. buf = (uint32_t*) (inbuffer - off);
  245. c = be2me_32((0x37c511f2 >> (off*8)) | (0x37c511f2 << (32-(off*8))));
  246. bytes += 3 + off;
  247. for (i = 0; i < bytes/4; i++)
  248. obuf[i] = c ^ buf[i];
  249. return off;
  250. }
  251. /**
  252. * Cook uninit
  253. */
  254. static int cook_decode_close(AVCodecContext *avctx)
  255. {
  256. int i;
  257. COOKContext *q = avctx->priv_data;
  258. av_log(avctx,AV_LOG_DEBUG, "Deallocating memory.\n");
  259. /* Free allocated memory buffers. */
  260. av_free(q->mlt_window);
  261. av_free(q->decoded_bytes_buffer);
  262. /* Free the transform. */
  263. ff_mdct_end(&q->mdct_ctx);
  264. /* Free the VLC tables. */
  265. for (i=0 ; i<13 ; i++) {
  266. free_vlc(&q->envelope_quant_index[i]);
  267. }
  268. for (i=0 ; i<7 ; i++) {
  269. free_vlc(&q->sqvh[i]);
  270. }
  271. if(q->nb_channels==2 && q->joint_stereo==1 ){
  272. free_vlc(&q->ccpl);
  273. }
  274. av_log(NULL,AV_LOG_DEBUG,"Memory deallocated.\n");
  275. return 0;
  276. }
  277. /**
  278. * Fill the gain array for the timedomain quantization.
  279. *
  280. * @param q pointer to the COOKContext
  281. * @param gaininfo[9] array of gain indices
  282. */
  283. static void decode_gain_info(GetBitContext *gb, int *gaininfo)
  284. {
  285. int i, n;
  286. while (get_bits1(gb)) {}
  287. n = get_bits_count(gb) - 1; //amount of elements*2 to update
  288. i = 0;
  289. while (n--) {
  290. int index = get_bits(gb, 3);
  291. int gain = get_bits1(gb) ? get_bits(gb, 4) - 7 : -1;
  292. while (i <= index) gaininfo[i++] = gain;
  293. }
  294. while (i <= 8) gaininfo[i++] = 0;
  295. }
  296. /**
  297. * Create the quant index table needed for the envelope.
  298. *
  299. * @param q pointer to the COOKContext
  300. * @param quant_index_table pointer to the array
  301. */
  302. static void decode_envelope(COOKContext *q, int* quant_index_table) {
  303. int i,j, vlc_index;
  304. quant_index_table[0]= get_bits(&q->gb,6) - 6; //This is used later in categorize
  305. for (i=1 ; i < q->total_subbands ; i++){
  306. vlc_index=i;
  307. if (i >= q->js_subband_start * 2) {
  308. vlc_index-=q->js_subband_start;
  309. } else {
  310. vlc_index/=2;
  311. if(vlc_index < 1) vlc_index = 1;
  312. }
  313. if (vlc_index>13) vlc_index = 13; //the VLC tables >13 are identical to No. 13
  314. j = get_vlc2(&q->gb, q->envelope_quant_index[vlc_index-1].table,
  315. q->envelope_quant_index[vlc_index-1].bits,2);
  316. quant_index_table[i] = quant_index_table[i-1] + j - 12; //differential encoding
  317. }
  318. }
  319. /**
  320. * Calculate the category and category_index vector.
  321. *
  322. * @param q pointer to the COOKContext
  323. * @param quant_index_table pointer to the array
  324. * @param category pointer to the category array
  325. * @param category_index pointer to the category_index array
  326. */
  327. static void categorize(COOKContext *q, int* quant_index_table,
  328. int* category, int* category_index){
  329. int exp_idx, bias, tmpbias, bits_left, num_bits, index, v, i, j;
  330. int exp_index2[102];
  331. int exp_index1[102];
  332. int tmp_categorize_array1[128];
  333. int tmp_categorize_array1_idx=0;
  334. int tmp_categorize_array2[128];
  335. int tmp_categorize_array2_idx=0;
  336. int category_index_size=0;
  337. bits_left = q->bits_per_subpacket - get_bits_count(&q->gb);
  338. if(bits_left > q->samples_per_channel) {
  339. bits_left = q->samples_per_channel +
  340. ((bits_left - q->samples_per_channel)*5)/8;
  341. //av_log(NULL, AV_LOG_ERROR, "bits_left = %d\n",bits_left);
  342. }
  343. memset(&exp_index1,0,102*sizeof(int));
  344. memset(&exp_index2,0,102*sizeof(int));
  345. memset(&tmp_categorize_array1,0,128*sizeof(int));
  346. memset(&tmp_categorize_array2,0,128*sizeof(int));
  347. bias=-32;
  348. /* Estimate bias. */
  349. for (i=32 ; i>0 ; i=i/2){
  350. num_bits = 0;
  351. index = 0;
  352. for (j=q->total_subbands ; j>0 ; j--){
  353. exp_idx = (i - quant_index_table[index] + bias) / 2;
  354. if (exp_idx<0){
  355. exp_idx=0;
  356. } else if(exp_idx >7) {
  357. exp_idx=7;
  358. }
  359. index++;
  360. num_bits+=expbits_tab[exp_idx];
  361. }
  362. if(num_bits >= bits_left - 32){
  363. bias+=i;
  364. }
  365. }
  366. /* Calculate total number of bits. */
  367. num_bits=0;
  368. for (i=0 ; i<q->total_subbands ; i++) {
  369. exp_idx = (bias - quant_index_table[i]) / 2;
  370. if (exp_idx<0) {
  371. exp_idx=0;
  372. } else if(exp_idx >7) {
  373. exp_idx=7;
  374. }
  375. num_bits += expbits_tab[exp_idx];
  376. exp_index1[i] = exp_idx;
  377. exp_index2[i] = exp_idx;
  378. }
  379. tmpbias = bias = num_bits;
  380. for (j = 1 ; j < q->numvector_size ; j++) {
  381. if (tmpbias + bias > 2*bits_left) { /* ---> */
  382. int max = -999999;
  383. index=-1;
  384. for (i=0 ; i<q->total_subbands ; i++){
  385. if (exp_index1[i] < 7) {
  386. v = (-2*exp_index1[i]) - quant_index_table[i] - 32;
  387. if ( v >= max) {
  388. max = v;
  389. index = i;
  390. }
  391. }
  392. }
  393. if(index==-1)break;
  394. tmp_categorize_array1[tmp_categorize_array1_idx++] = index;
  395. tmpbias -= expbits_tab[exp_index1[index]] -
  396. expbits_tab[exp_index1[index]+1];
  397. ++exp_index1[index];
  398. } else { /* <--- */
  399. int min = 999999;
  400. index=-1;
  401. for (i=0 ; i<q->total_subbands ; i++){
  402. if(exp_index2[i] > 0){
  403. v = (-2*exp_index2[i])-quant_index_table[i];
  404. if ( v < min) {
  405. min = v;
  406. index = i;
  407. }
  408. }
  409. }
  410. if(index == -1)break;
  411. tmp_categorize_array2[tmp_categorize_array2_idx++] = index;
  412. tmpbias -= expbits_tab[exp_index2[index]] -
  413. expbits_tab[exp_index2[index]-1];
  414. --exp_index2[index];
  415. }
  416. }
  417. for(i=0 ; i<q->total_subbands ; i++)
  418. category[i] = exp_index2[i];
  419. /* Concatenate the two arrays. */
  420. for(i=tmp_categorize_array2_idx-1 ; i >= 0; i--)
  421. category_index[category_index_size++] = tmp_categorize_array2[i];
  422. for(i=0;i<tmp_categorize_array1_idx;i++)
  423. category_index[category_index_size++ ] = tmp_categorize_array1[i];
  424. /* FIXME: mc_sich_ra8_20.rm triggers this, not sure with what we
  425. should fill the remaining bytes. */
  426. for(i=category_index_size;i<q->numvector_size;i++)
  427. category_index[i]=0;
  428. }
  429. /**
  430. * Expand the category vector.
  431. *
  432. * @param q pointer to the COOKContext
  433. * @param category pointer to the category array
  434. * @param category_index pointer to the category_index array
  435. */
  436. static void inline expand_category(COOKContext *q, int* category,
  437. int* category_index){
  438. int i;
  439. for(i=0 ; i<q->num_vectors ; i++){
  440. ++category[category_index[i]];
  441. }
  442. }
  443. /**
  444. * The real requantization of the mltcoefs
  445. *
  446. * @param q pointer to the COOKContext
  447. * @param index index
  448. * @param quant_index quantisation index
  449. * @param subband_coef_index array of indexes to quant_centroid_tab
  450. * @param subband_coef_sign signs of coefficients
  451. * @param mlt_p pointer into the mlt buffer
  452. */
  453. static void scalar_dequant(COOKContext *q, int index, int quant_index,
  454. int* subband_coef_index, int* subband_coef_sign,
  455. float* mlt_p){
  456. int i;
  457. float f1;
  458. for(i=0 ; i<SUBBAND_SIZE ; i++) {
  459. if (subband_coef_index[i]) {
  460. f1 = quant_centroid_tab[index][subband_coef_index[i]];
  461. if (subband_coef_sign[i]) f1 = -f1;
  462. } else {
  463. /* noise coding if subband_coef_index[i] == 0 */
  464. f1 = dither_tab[index];
  465. if (av_random(&q->random_state) < 0x80000000) f1 = -f1;
  466. }
  467. mlt_p[i] = f1 * q->rootpow2tab[quant_index+63];
  468. }
  469. }
  470. /**
  471. * Unpack the subband_coef_index and subband_coef_sign vectors.
  472. *
  473. * @param q pointer to the COOKContext
  474. * @param category pointer to the category array
  475. * @param subband_coef_index array of indexes to quant_centroid_tab
  476. * @param subband_coef_sign signs of coefficients
  477. */
  478. static int unpack_SQVH(COOKContext *q, int category, int* subband_coef_index,
  479. int* subband_coef_sign) {
  480. int i,j;
  481. int vlc, vd ,tmp, result;
  482. int ub;
  483. int cb;
  484. vd = vd_tab[category];
  485. result = 0;
  486. for(i=0 ; i<vpr_tab[category] ; i++){
  487. ub = get_bits_count(&q->gb);
  488. vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
  489. cb = get_bits_count(&q->gb);
  490. if (q->bits_per_subpacket < get_bits_count(&q->gb)){
  491. vlc = 0;
  492. result = 1;
  493. }
  494. for(j=vd-1 ; j>=0 ; j--){
  495. tmp = (vlc * invradix_tab[category])/0x100000;
  496. subband_coef_index[vd*i+j] = vlc - tmp * (kmax_tab[category]+1);
  497. vlc = tmp;
  498. }
  499. for(j=0 ; j<vd ; j++){
  500. if (subband_coef_index[i*vd + j]) {
  501. if(get_bits_count(&q->gb) < q->bits_per_subpacket){
  502. subband_coef_sign[i*vd+j] = get_bits1(&q->gb);
  503. } else {
  504. result=1;
  505. subband_coef_sign[i*vd+j]=0;
  506. }
  507. } else {
  508. subband_coef_sign[i*vd+j]=0;
  509. }
  510. }
  511. }
  512. return result;
  513. }
  514. /**
  515. * Fill the mlt_buffer with mlt coefficients.
  516. *
  517. * @param q pointer to the COOKContext
  518. * @param category pointer to the category array
  519. * @param quant_index_table pointer to the array
  520. * @param mlt_buffer pointer to mlt coefficients
  521. */
  522. static void decode_vectors(COOKContext* q, int* category,
  523. int *quant_index_table, float* mlt_buffer){
  524. /* A zero in this table means that the subband coefficient is
  525. random noise coded. */
  526. int subband_coef_index[SUBBAND_SIZE];
  527. /* A zero in this table means that the subband coefficient is a
  528. positive multiplicator. */
  529. int subband_coef_sign[SUBBAND_SIZE];
  530. int band, j;
  531. int index=0;
  532. for(band=0 ; band<q->total_subbands ; band++){
  533. index = category[band];
  534. if(category[band] < 7){
  535. if(unpack_SQVH(q, category[band], subband_coef_index, subband_coef_sign)){
  536. index=7;
  537. for(j=0 ; j<q->total_subbands ; j++) category[band+j]=7;
  538. }
  539. }
  540. if(index==7) {
  541. memset(subband_coef_index, 0, sizeof(subband_coef_index));
  542. memset(subband_coef_sign, 0, sizeof(subband_coef_sign));
  543. }
  544. scalar_dequant(q, index, quant_index_table[band],
  545. subband_coef_index, subband_coef_sign,
  546. &mlt_buffer[band * 20]);
  547. }
  548. if(q->total_subbands*SUBBAND_SIZE >= q->samples_per_channel){
  549. return;
  550. } /* FIXME: should this be removed, or moved into loop above? */
  551. }
  552. /**
  553. * function for decoding mono data
  554. *
  555. * @param q pointer to the COOKContext
  556. * @param mlt_buffer pointer to mlt coefficients
  557. */
  558. static void mono_decode(COOKContext *q, float* mlt_buffer) {
  559. int category_index[128];
  560. int quant_index_table[102];
  561. int category[128];
  562. memset(&category, 0, 128*sizeof(int));
  563. memset(&category_index, 0, 128*sizeof(int));
  564. decode_envelope(q, quant_index_table);
  565. q->num_vectors = get_bits(&q->gb,q->log2_numvector_size);
  566. categorize(q, quant_index_table, category, category_index);
  567. expand_category(q, category, category_index);
  568. decode_vectors(q, category, quant_index_table, mlt_buffer);
  569. }
  570. /**
  571. * the actual requantization of the timedomain samples
  572. *
  573. * @param q pointer to the COOKContext
  574. * @param buffer pointer to the timedomain buffer
  575. * @param gain_index index for the block multiplier
  576. * @param gain_index_next index for the next block multiplier
  577. */
  578. static void interpolate(COOKContext *q, float* buffer,
  579. int gain_index, int gain_index_next){
  580. int i;
  581. float fc1, fc2;
  582. fc1 = q->pow2tab[gain_index+63];
  583. if(gain_index == gain_index_next){ //static gain
  584. for(i=0 ; i<q->gain_size_factor ; i++){
  585. buffer[i]*=fc1;
  586. }
  587. return;
  588. } else { //smooth gain
  589. fc2 = q->gain_table[11 + (gain_index_next-gain_index)];
  590. for(i=0 ; i<q->gain_size_factor ; i++){
  591. buffer[i]*=fc1;
  592. fc1*=fc2;
  593. }
  594. return;
  595. }
  596. }
  597. /**
  598. * The modulated lapped transform, this takes transform coefficients
  599. * and transforms them into timedomain samples.
  600. * Apply transform window, overlap buffers, apply gain profile
  601. * and buffer management.
  602. *
  603. * @param q pointer to the COOKContext
  604. * @param inbuffer pointer to the mltcoefficients
  605. * @param gains_ptr current and previous gains
  606. * @param previous_buffer pointer to the previous buffer to be used for overlapping
  607. */
  608. static void imlt_gain(COOKContext *q, float *inbuffer,
  609. cook_gains *gains_ptr, float* previous_buffer)
  610. {
  611. const float fc = q->pow2tab[gains_ptr->previous[0] + 63];
  612. float *buffer0 = q->mono_mdct_output;
  613. float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
  614. int i;
  615. /* Inverse modified discrete cosine transform */
  616. q->mdct_ctx.fft.imdct_calc(&q->mdct_ctx, q->mono_mdct_output,
  617. inbuffer, q->mdct_tmp);
  618. /* The weird thing here, is that the two halves of the time domain
  619. * buffer are swapped. Also, the newest data, that we save away for
  620. * next frame, has the wrong sign. Hence the subtraction below.
  621. * Almost sounds like a complex conjugate/reverse data/FFT effect.
  622. */
  623. /* Apply window and overlap */
  624. for(i = 0; i < q->samples_per_channel; i++){
  625. buffer1[i] = buffer1[i] * fc * q->mlt_window[i] -
  626. previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
  627. }
  628. /* Apply gain profile */
  629. for (i = 0; i < 8; i++) {
  630. if (gains_ptr->now[i] || gains_ptr->now[i + 1])
  631. interpolate(q, &buffer1[q->gain_size_factor * i],
  632. gains_ptr->now[i], gains_ptr->now[i + 1]);
  633. }
  634. /* Save away the current to be previous block. */
  635. memcpy(previous_buffer, buffer0, sizeof(float)*q->samples_per_channel);
  636. }
  637. /**
  638. * function for getting the jointstereo coupling information
  639. *
  640. * @param q pointer to the COOKContext
  641. * @param decouple_tab decoupling array
  642. *
  643. */
  644. static void decouple_info(COOKContext *q, int* decouple_tab){
  645. int length, i;
  646. if(get_bits1(&q->gb)) {
  647. if(cplband[q->js_subband_start] > cplband[q->subbands-1]) return;
  648. length = cplband[q->subbands-1] - cplband[q->js_subband_start] + 1;
  649. for (i=0 ; i<length ; i++) {
  650. decouple_tab[cplband[q->js_subband_start] + i] = get_vlc2(&q->gb, q->ccpl.table, q->ccpl.bits, 2);
  651. }
  652. return;
  653. }
  654. if(cplband[q->js_subband_start] > cplband[q->subbands-1]) return;
  655. length = cplband[q->subbands-1] - cplband[q->js_subband_start] + 1;
  656. for (i=0 ; i<length ; i++) {
  657. decouple_tab[cplband[q->js_subband_start] + i] = get_bits(&q->gb, q->js_vlc_bits);
  658. }
  659. return;
  660. }
  661. /**
  662. * function for decoding joint stereo data
  663. *
  664. * @param q pointer to the COOKContext
  665. * @param mlt_buffer1 pointer to left channel mlt coefficients
  666. * @param mlt_buffer2 pointer to right channel mlt coefficients
  667. */
  668. static void joint_decode(COOKContext *q, float* mlt_buffer1,
  669. float* mlt_buffer2) {
  670. int i,j;
  671. int decouple_tab[SUBBAND_SIZE];
  672. float decode_buffer[1060];
  673. int idx, cpl_tmp,tmp_idx;
  674. float f1,f2;
  675. float* cplscale;
  676. memset(decouple_tab, 0, sizeof(decouple_tab));
  677. memset(decode_buffer, 0, sizeof(decode_buffer));
  678. /* Make sure the buffers are zeroed out. */
  679. memset(mlt_buffer1,0, 1024*sizeof(float));
  680. memset(mlt_buffer2,0, 1024*sizeof(float));
  681. decouple_info(q, decouple_tab);
  682. mono_decode(q, decode_buffer);
  683. /* The two channels are stored interleaved in decode_buffer. */
  684. for (i=0 ; i<q->js_subband_start ; i++) {
  685. for (j=0 ; j<SUBBAND_SIZE ; j++) {
  686. mlt_buffer1[i*20+j] = decode_buffer[i*40+j];
  687. mlt_buffer2[i*20+j] = decode_buffer[i*40+20+j];
  688. }
  689. }
  690. /* When we reach js_subband_start (the higher frequencies)
  691. the coefficients are stored in a coupling scheme. */
  692. idx = (1 << q->js_vlc_bits) - 1;
  693. for (i=q->js_subband_start ; i<q->subbands ; i++) {
  694. cpl_tmp = cplband[i];
  695. idx -=decouple_tab[cpl_tmp];
  696. cplscale = (float*)cplscales[q->js_vlc_bits-2]; //choose decoupler table
  697. f1 = cplscale[decouple_tab[cpl_tmp]];
  698. f2 = cplscale[idx-1];
  699. for (j=0 ; j<SUBBAND_SIZE ; j++) {
  700. tmp_idx = ((q->js_subband_start + i)*20)+j;
  701. mlt_buffer1[20*i + j] = f1 * decode_buffer[tmp_idx];
  702. mlt_buffer2[20*i + j] = f2 * decode_buffer[tmp_idx];
  703. }
  704. idx = (1 << q->js_vlc_bits) - 1;
  705. }
  706. }
  707. /**
  708. * First part of subpacket decoding:
  709. * decode raw stream bytes and read gain info.
  710. *
  711. * @param q pointer to the COOKContext
  712. * @param inbuffer pointer to raw stream data
  713. * @param gain_ptr array of current/prev gain pointers
  714. */
  715. static inline void
  716. decode_bytes_and_gain(COOKContext *q, uint8_t *inbuffer,
  717. cook_gains *gains_ptr)
  718. {
  719. int offset;
  720. offset = decode_bytes(inbuffer, q->decoded_bytes_buffer,
  721. q->bits_per_subpacket/8);
  722. init_get_bits(&q->gb, q->decoded_bytes_buffer + offset,
  723. q->bits_per_subpacket);
  724. decode_gain_info(&q->gb, gains_ptr->now);
  725. /* Swap current and previous gains */
  726. FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
  727. }
  728. /**
  729. * Final part of subpacket decoding:
  730. * Apply modulated lapped transform, gain compensation,
  731. * clip and convert to integer.
  732. *
  733. * @param q pointer to the COOKContext
  734. * @param decode_buffer pointer to the mlt coefficients
  735. * @param gain_ptr array of current/prev gain pointers
  736. * @param previous_buffer pointer to the previous buffer to be used for overlapping
  737. * @param out pointer to the output buffer
  738. * @param chan 0: left or single channel, 1: right channel
  739. */
  740. static inline void
  741. mlt_compensate_output(COOKContext *q, float *decode_buffer,
  742. cook_gains *gains, float *previous_buffer,
  743. int16_t *out, int chan)
  744. {
  745. float *output = q->mono_mdct_output + q->samples_per_channel;
  746. int j;
  747. imlt_gain(q, decode_buffer, gains, previous_buffer);
  748. /* Clip and convert floats to 16 bits.
  749. */
  750. for (j = 0; j < q->samples_per_channel; j++) {
  751. out[chan + q->nb_channels * j] =
  752. av_clip(lrintf(output[j]), -32768, 32767);
  753. }
  754. }
  755. /**
  756. * Cook subpacket decoding. This function returns one decoded subpacket,
  757. * usually 1024 samples per channel.
  758. *
  759. * @param q pointer to the COOKContext
  760. * @param inbuffer pointer to the inbuffer
  761. * @param sub_packet_size subpacket size
  762. * @param outbuffer pointer to the outbuffer
  763. */
  764. static int decode_subpacket(COOKContext *q, uint8_t *inbuffer,
  765. int sub_packet_size, int16_t *outbuffer) {
  766. /* packet dump */
  767. // for (i=0 ; i<sub_packet_size ; i++) {
  768. // av_log(NULL, AV_LOG_ERROR, "%02x", inbuffer[i]);
  769. // }
  770. // av_log(NULL, AV_LOG_ERROR, "\n");
  771. decode_bytes_and_gain(q, inbuffer, &q->gains1);
  772. if (q->joint_stereo) {
  773. joint_decode(q, q->decode_buffer_1, q->decode_buffer_2);
  774. } else {
  775. mono_decode(q, q->decode_buffer_1);
  776. if (q->nb_channels == 2) {
  777. decode_bytes_and_gain(q, inbuffer + sub_packet_size/2, &q->gains2);
  778. mono_decode(q, q->decode_buffer_2);
  779. }
  780. }
  781. mlt_compensate_output(q, q->decode_buffer_1, &q->gains1,
  782. q->mono_previous_buffer1, outbuffer, 0);
  783. if (q->nb_channels == 2) {
  784. if (q->joint_stereo) {
  785. mlt_compensate_output(q, q->decode_buffer_2, &q->gains1,
  786. q->mono_previous_buffer2, outbuffer, 1);
  787. } else {
  788. mlt_compensate_output(q, q->decode_buffer_2, &q->gains2,
  789. q->mono_previous_buffer2, outbuffer, 1);
  790. }
  791. }
  792. return q->samples_per_frame * sizeof(int16_t);
  793. }
  794. /**
  795. * Cook frame decoding
  796. *
  797. * @param avctx pointer to the AVCodecContext
  798. */
  799. static int cook_decode_frame(AVCodecContext *avctx,
  800. void *data, int *data_size,
  801. uint8_t *buf, int buf_size) {
  802. COOKContext *q = avctx->priv_data;
  803. if (buf_size < avctx->block_align)
  804. return buf_size;
  805. *data_size = decode_subpacket(q, buf, avctx->block_align, data);
  806. /* Discard the first two frames: no valid audio. */
  807. if (avctx->frame_number < 2) *data_size = 0;
  808. return avctx->block_align;
  809. }
  810. #ifdef COOKDEBUG
  811. static void dump_cook_context(COOKContext *q)
  812. {
  813. //int i=0;
  814. #define PRINT(a,b) av_log(NULL,AV_LOG_ERROR," %s = %d\n", a, b);
  815. av_log(NULL,AV_LOG_ERROR,"COOKextradata\n");
  816. av_log(NULL,AV_LOG_ERROR,"cookversion=%x\n",q->cookversion);
  817. if (q->cookversion > STEREO) {
  818. PRINT("js_subband_start",q->js_subband_start);
  819. PRINT("js_vlc_bits",q->js_vlc_bits);
  820. }
  821. av_log(NULL,AV_LOG_ERROR,"COOKContext\n");
  822. PRINT("nb_channels",q->nb_channels);
  823. PRINT("bit_rate",q->bit_rate);
  824. PRINT("sample_rate",q->sample_rate);
  825. PRINT("samples_per_channel",q->samples_per_channel);
  826. PRINT("samples_per_frame",q->samples_per_frame);
  827. PRINT("subbands",q->subbands);
  828. PRINT("random_state",q->random_state);
  829. PRINT("js_subband_start",q->js_subband_start);
  830. PRINT("log2_numvector_size",q->log2_numvector_size);
  831. PRINT("numvector_size",q->numvector_size);
  832. PRINT("total_subbands",q->total_subbands);
  833. }
  834. #endif
  835. /**
  836. * Cook initialization
  837. *
  838. * @param avctx pointer to the AVCodecContext
  839. */
  840. static int cook_decode_init(AVCodecContext *avctx)
  841. {
  842. COOKContext *q = avctx->priv_data;
  843. uint8_t *edata_ptr = avctx->extradata;
  844. /* Take care of the codec specific extradata. */
  845. if (avctx->extradata_size <= 0) {
  846. av_log(avctx,AV_LOG_ERROR,"Necessary extradata missing!\n");
  847. return -1;
  848. } else {
  849. /* 8 for mono, 16 for stereo, ? for multichannel
  850. Swap to right endianness so we don't need to care later on. */
  851. av_log(avctx,AV_LOG_DEBUG,"codecdata_length=%d\n",avctx->extradata_size);
  852. if (avctx->extradata_size >= 8){
  853. q->cookversion = bytestream_get_be32(&edata_ptr);
  854. q->samples_per_frame = bytestream_get_be16(&edata_ptr);
  855. q->subbands = bytestream_get_be16(&edata_ptr);
  856. }
  857. if (avctx->extradata_size >= 16){
  858. bytestream_get_be32(&edata_ptr); //Unknown unused
  859. q->js_subband_start = bytestream_get_be16(&edata_ptr);
  860. q->js_vlc_bits = bytestream_get_be16(&edata_ptr);
  861. }
  862. }
  863. /* Take data from the AVCodecContext (RM container). */
  864. q->sample_rate = avctx->sample_rate;
  865. q->nb_channels = avctx->channels;
  866. q->bit_rate = avctx->bit_rate;
  867. /* Initialize RNG. */
  868. av_init_random(1, &q->random_state);
  869. /* Initialize extradata related variables. */
  870. q->samples_per_channel = q->samples_per_frame / q->nb_channels;
  871. q->bits_per_subpacket = avctx->block_align * 8;
  872. /* Initialize default data states. */
  873. q->log2_numvector_size = 5;
  874. q->total_subbands = q->subbands;
  875. /* Initialize version-dependent variables */
  876. av_log(NULL,AV_LOG_DEBUG,"q->cookversion=%x\n",q->cookversion);
  877. q->joint_stereo = 0;
  878. switch (q->cookversion) {
  879. case MONO:
  880. if (q->nb_channels != 1) {
  881. av_log(avctx,AV_LOG_ERROR,"Container channels != 1, report sample!\n");
  882. return -1;
  883. }
  884. av_log(avctx,AV_LOG_DEBUG,"MONO\n");
  885. break;
  886. case STEREO:
  887. if (q->nb_channels != 1) {
  888. q->bits_per_subpacket = q->bits_per_subpacket/2;
  889. }
  890. av_log(avctx,AV_LOG_DEBUG,"STEREO\n");
  891. break;
  892. case JOINT_STEREO:
  893. if (q->nb_channels != 2) {
  894. av_log(avctx,AV_LOG_ERROR,"Container channels != 2, report sample!\n");
  895. return -1;
  896. }
  897. av_log(avctx,AV_LOG_DEBUG,"JOINT_STEREO\n");
  898. if (avctx->extradata_size >= 16){
  899. q->total_subbands = q->subbands + q->js_subband_start;
  900. q->joint_stereo = 1;
  901. }
  902. if (q->samples_per_channel > 256) {
  903. q->log2_numvector_size = 6;
  904. }
  905. if (q->samples_per_channel > 512) {
  906. q->log2_numvector_size = 7;
  907. }
  908. break;
  909. case MC_COOK:
  910. av_log(avctx,AV_LOG_ERROR,"MC_COOK not supported!\n");
  911. return -1;
  912. break;
  913. default:
  914. av_log(avctx,AV_LOG_ERROR,"Unknown Cook version, report sample!\n");
  915. return -1;
  916. break;
  917. }
  918. /* Initialize variable relations */
  919. q->numvector_size = (1 << q->log2_numvector_size);
  920. /* Generate tables */
  921. init_rootpow2table(q);
  922. init_pow2table(q);
  923. init_gain_table(q);
  924. if (init_cook_vlc_tables(q) != 0)
  925. return -1;
  926. if(avctx->block_align >= UINT_MAX/2)
  927. return -1;
  928. /* Pad the databuffer with:
  929. DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
  930. FF_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */
  931. if (q->nb_channels==2 && q->joint_stereo==0) {
  932. q->decoded_bytes_buffer =
  933. av_mallocz(avctx->block_align/2
  934. + DECODE_BYTES_PAD2(avctx->block_align/2)
  935. + FF_INPUT_BUFFER_PADDING_SIZE);
  936. } else {
  937. q->decoded_bytes_buffer =
  938. av_mallocz(avctx->block_align
  939. + DECODE_BYTES_PAD1(avctx->block_align)
  940. + FF_INPUT_BUFFER_PADDING_SIZE);
  941. }
  942. if (q->decoded_bytes_buffer == NULL)
  943. return -1;
  944. q->gains1.now = q->gain_1;
  945. q->gains1.previous = q->gain_2;
  946. q->gains2.now = q->gain_3;
  947. q->gains2.previous = q->gain_4;
  948. /* Initialize transform. */
  949. if ( init_cook_mlt(q) != 0 )
  950. return -1;
  951. /* Try to catch some obviously faulty streams, othervise it might be exploitable */
  952. if (q->total_subbands > 53) {
  953. av_log(avctx,AV_LOG_ERROR,"total_subbands > 53, report sample!\n");
  954. return -1;
  955. }
  956. if (q->subbands > 50) {
  957. av_log(avctx,AV_LOG_ERROR,"subbands > 50, report sample!\n");
  958. return -1;
  959. }
  960. if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512) || (q->samples_per_channel == 1024)) {
  961. } else {
  962. av_log(avctx,AV_LOG_ERROR,"unknown amount of samples_per_channel = %d, report sample!\n",q->samples_per_channel);
  963. return -1;
  964. }
  965. if ((q->js_vlc_bits > 6) || (q->js_vlc_bits < 0)) {
  966. av_log(avctx,AV_LOG_ERROR,"q->js_vlc_bits = %d, only >= 0 and <= 6 allowed!\n",q->js_vlc_bits);
  967. return -1;
  968. }
  969. #ifdef COOKDEBUG
  970. dump_cook_context(q);
  971. #endif
  972. return 0;
  973. }
  974. AVCodec cook_decoder =
  975. {
  976. .name = "cook",
  977. .type = CODEC_TYPE_AUDIO,
  978. .id = CODEC_ID_COOK,
  979. .priv_data_size = sizeof(COOKContext),
  980. .init = cook_decode_init,
  981. .close = cook_decode_close,
  982. .decode = cook_decode_frame,
  983. };