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.

1141 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. vd = vd_tab[category];
  483. result = 0;
  484. for(i=0 ; i<vpr_tab[category] ; i++){
  485. vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
  486. if (q->bits_per_subpacket < get_bits_count(&q->gb)){
  487. vlc = 0;
  488. result = 1;
  489. }
  490. for(j=vd-1 ; j>=0 ; j--){
  491. tmp = (vlc * invradix_tab[category])/0x100000;
  492. subband_coef_index[vd*i+j] = vlc - tmp * (kmax_tab[category]+1);
  493. vlc = tmp;
  494. }
  495. for(j=0 ; j<vd ; j++){
  496. if (subband_coef_index[i*vd + j]) {
  497. if(get_bits_count(&q->gb) < q->bits_per_subpacket){
  498. subband_coef_sign[i*vd+j] = get_bits1(&q->gb);
  499. } else {
  500. result=1;
  501. subband_coef_sign[i*vd+j]=0;
  502. }
  503. } else {
  504. subband_coef_sign[i*vd+j]=0;
  505. }
  506. }
  507. }
  508. return result;
  509. }
  510. /**
  511. * Fill the mlt_buffer with mlt coefficients.
  512. *
  513. * @param q pointer to the COOKContext
  514. * @param category pointer to the category array
  515. * @param quant_index_table pointer to the array
  516. * @param mlt_buffer pointer to mlt coefficients
  517. */
  518. static void decode_vectors(COOKContext* q, int* category,
  519. int *quant_index_table, float* mlt_buffer){
  520. /* A zero in this table means that the subband coefficient is
  521. random noise coded. */
  522. int subband_coef_index[SUBBAND_SIZE];
  523. /* A zero in this table means that the subband coefficient is a
  524. positive multiplicator. */
  525. int subband_coef_sign[SUBBAND_SIZE];
  526. int band, j;
  527. int index=0;
  528. for(band=0 ; band<q->total_subbands ; band++){
  529. index = category[band];
  530. if(category[band] < 7){
  531. if(unpack_SQVH(q, category[band], subband_coef_index, subband_coef_sign)){
  532. index=7;
  533. for(j=0 ; j<q->total_subbands ; j++) category[band+j]=7;
  534. }
  535. }
  536. if(index==7) {
  537. memset(subband_coef_index, 0, sizeof(subband_coef_index));
  538. memset(subband_coef_sign, 0, sizeof(subband_coef_sign));
  539. }
  540. scalar_dequant(q, index, quant_index_table[band],
  541. subband_coef_index, subband_coef_sign,
  542. &mlt_buffer[band * 20]);
  543. }
  544. if(q->total_subbands*SUBBAND_SIZE >= q->samples_per_channel){
  545. return;
  546. } /* FIXME: should this be removed, or moved into loop above? */
  547. }
  548. /**
  549. * function for decoding mono data
  550. *
  551. * @param q pointer to the COOKContext
  552. * @param mlt_buffer pointer to mlt coefficients
  553. */
  554. static void mono_decode(COOKContext *q, float* mlt_buffer) {
  555. int category_index[128];
  556. int quant_index_table[102];
  557. int category[128];
  558. memset(&category, 0, 128*sizeof(int));
  559. memset(&category_index, 0, 128*sizeof(int));
  560. decode_envelope(q, quant_index_table);
  561. q->num_vectors = get_bits(&q->gb,q->log2_numvector_size);
  562. categorize(q, quant_index_table, category, category_index);
  563. expand_category(q, category, category_index);
  564. decode_vectors(q, category, quant_index_table, mlt_buffer);
  565. }
  566. /**
  567. * the actual requantization of the timedomain samples
  568. *
  569. * @param q pointer to the COOKContext
  570. * @param buffer pointer to the timedomain buffer
  571. * @param gain_index index for the block multiplier
  572. * @param gain_index_next index for the next block multiplier
  573. */
  574. static void interpolate(COOKContext *q, float* buffer,
  575. int gain_index, int gain_index_next){
  576. int i;
  577. float fc1, fc2;
  578. fc1 = q->pow2tab[gain_index+63];
  579. if(gain_index == gain_index_next){ //static gain
  580. for(i=0 ; i<q->gain_size_factor ; i++){
  581. buffer[i]*=fc1;
  582. }
  583. return;
  584. } else { //smooth gain
  585. fc2 = q->gain_table[11 + (gain_index_next-gain_index)];
  586. for(i=0 ; i<q->gain_size_factor ; i++){
  587. buffer[i]*=fc1;
  588. fc1*=fc2;
  589. }
  590. return;
  591. }
  592. }
  593. /**
  594. * The modulated lapped transform, this takes transform coefficients
  595. * and transforms them into timedomain samples.
  596. * Apply transform window, overlap buffers, apply gain profile
  597. * and buffer management.
  598. *
  599. * @param q pointer to the COOKContext
  600. * @param inbuffer pointer to the mltcoefficients
  601. * @param gains_ptr current and previous gains
  602. * @param previous_buffer pointer to the previous buffer to be used for overlapping
  603. */
  604. static void imlt_gain(COOKContext *q, float *inbuffer,
  605. cook_gains *gains_ptr, float* previous_buffer)
  606. {
  607. const float fc = q->pow2tab[gains_ptr->previous[0] + 63];
  608. float *buffer0 = q->mono_mdct_output;
  609. float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
  610. int i;
  611. /* Inverse modified discrete cosine transform */
  612. q->mdct_ctx.fft.imdct_calc(&q->mdct_ctx, q->mono_mdct_output,
  613. inbuffer, q->mdct_tmp);
  614. /* The weird thing here, is that the two halves of the time domain
  615. * buffer are swapped. Also, the newest data, that we save away for
  616. * next frame, has the wrong sign. Hence the subtraction below.
  617. * Almost sounds like a complex conjugate/reverse data/FFT effect.
  618. */
  619. /* Apply window and overlap */
  620. for(i = 0; i < q->samples_per_channel; i++){
  621. buffer1[i] = buffer1[i] * fc * q->mlt_window[i] -
  622. previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
  623. }
  624. /* Apply gain profile */
  625. for (i = 0; i < 8; i++) {
  626. if (gains_ptr->now[i] || gains_ptr->now[i + 1])
  627. interpolate(q, &buffer1[q->gain_size_factor * i],
  628. gains_ptr->now[i], gains_ptr->now[i + 1]);
  629. }
  630. /* Save away the current to be previous block. */
  631. memcpy(previous_buffer, buffer0, sizeof(float)*q->samples_per_channel);
  632. }
  633. /**
  634. * function for getting the jointstereo coupling information
  635. *
  636. * @param q pointer to the COOKContext
  637. * @param decouple_tab decoupling array
  638. *
  639. */
  640. static void decouple_info(COOKContext *q, int* decouple_tab){
  641. int length, i;
  642. if(get_bits1(&q->gb)) {
  643. if(cplband[q->js_subband_start] > cplband[q->subbands-1]) return;
  644. length = cplband[q->subbands-1] - cplband[q->js_subband_start] + 1;
  645. for (i=0 ; i<length ; i++) {
  646. decouple_tab[cplband[q->js_subband_start] + i] = get_vlc2(&q->gb, q->ccpl.table, q->ccpl.bits, 2);
  647. }
  648. return;
  649. }
  650. if(cplband[q->js_subband_start] > cplband[q->subbands-1]) return;
  651. length = cplband[q->subbands-1] - cplband[q->js_subband_start] + 1;
  652. for (i=0 ; i<length ; i++) {
  653. decouple_tab[cplband[q->js_subband_start] + i] = get_bits(&q->gb, q->js_vlc_bits);
  654. }
  655. return;
  656. }
  657. /**
  658. * function for decoding joint stereo data
  659. *
  660. * @param q pointer to the COOKContext
  661. * @param mlt_buffer1 pointer to left channel mlt coefficients
  662. * @param mlt_buffer2 pointer to right channel mlt coefficients
  663. */
  664. static void joint_decode(COOKContext *q, float* mlt_buffer1,
  665. float* mlt_buffer2) {
  666. int i,j;
  667. int decouple_tab[SUBBAND_SIZE];
  668. float decode_buffer[1060];
  669. int idx, cpl_tmp,tmp_idx;
  670. float f1,f2;
  671. float* cplscale;
  672. memset(decouple_tab, 0, sizeof(decouple_tab));
  673. memset(decode_buffer, 0, sizeof(decode_buffer));
  674. /* Make sure the buffers are zeroed out. */
  675. memset(mlt_buffer1,0, 1024*sizeof(float));
  676. memset(mlt_buffer2,0, 1024*sizeof(float));
  677. decouple_info(q, decouple_tab);
  678. mono_decode(q, decode_buffer);
  679. /* The two channels are stored interleaved in decode_buffer. */
  680. for (i=0 ; i<q->js_subband_start ; i++) {
  681. for (j=0 ; j<SUBBAND_SIZE ; j++) {
  682. mlt_buffer1[i*20+j] = decode_buffer[i*40+j];
  683. mlt_buffer2[i*20+j] = decode_buffer[i*40+20+j];
  684. }
  685. }
  686. /* When we reach js_subband_start (the higher frequencies)
  687. the coefficients are stored in a coupling scheme. */
  688. idx = (1 << q->js_vlc_bits) - 1;
  689. for (i=q->js_subband_start ; i<q->subbands ; i++) {
  690. cpl_tmp = cplband[i];
  691. idx -=decouple_tab[cpl_tmp];
  692. cplscale = (float*)cplscales[q->js_vlc_bits-2]; //choose decoupler table
  693. f1 = cplscale[decouple_tab[cpl_tmp]];
  694. f2 = cplscale[idx-1];
  695. for (j=0 ; j<SUBBAND_SIZE ; j++) {
  696. tmp_idx = ((q->js_subband_start + i)*20)+j;
  697. mlt_buffer1[20*i + j] = f1 * decode_buffer[tmp_idx];
  698. mlt_buffer2[20*i + j] = f2 * decode_buffer[tmp_idx];
  699. }
  700. idx = (1 << q->js_vlc_bits) - 1;
  701. }
  702. }
  703. /**
  704. * First part of subpacket decoding:
  705. * decode raw stream bytes and read gain info.
  706. *
  707. * @param q pointer to the COOKContext
  708. * @param inbuffer pointer to raw stream data
  709. * @param gain_ptr array of current/prev gain pointers
  710. */
  711. static inline void
  712. decode_bytes_and_gain(COOKContext *q, uint8_t *inbuffer,
  713. cook_gains *gains_ptr)
  714. {
  715. int offset;
  716. offset = decode_bytes(inbuffer, q->decoded_bytes_buffer,
  717. q->bits_per_subpacket/8);
  718. init_get_bits(&q->gb, q->decoded_bytes_buffer + offset,
  719. q->bits_per_subpacket);
  720. decode_gain_info(&q->gb, gains_ptr->now);
  721. /* Swap current and previous gains */
  722. FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
  723. }
  724. /**
  725. * Final part of subpacket decoding:
  726. * Apply modulated lapped transform, gain compensation,
  727. * clip and convert to integer.
  728. *
  729. * @param q pointer to the COOKContext
  730. * @param decode_buffer pointer to the mlt coefficients
  731. * @param gain_ptr array of current/prev gain pointers
  732. * @param previous_buffer pointer to the previous buffer to be used for overlapping
  733. * @param out pointer to the output buffer
  734. * @param chan 0: left or single channel, 1: right channel
  735. */
  736. static inline void
  737. mlt_compensate_output(COOKContext *q, float *decode_buffer,
  738. cook_gains *gains, float *previous_buffer,
  739. int16_t *out, int chan)
  740. {
  741. float *output = q->mono_mdct_output + q->samples_per_channel;
  742. int j;
  743. imlt_gain(q, decode_buffer, gains, previous_buffer);
  744. /* Clip and convert floats to 16 bits.
  745. */
  746. for (j = 0; j < q->samples_per_channel; j++) {
  747. out[chan + q->nb_channels * j] =
  748. av_clip(lrintf(output[j]), -32768, 32767);
  749. }
  750. }
  751. /**
  752. * Cook subpacket decoding. This function returns one decoded subpacket,
  753. * usually 1024 samples per channel.
  754. *
  755. * @param q pointer to the COOKContext
  756. * @param inbuffer pointer to the inbuffer
  757. * @param sub_packet_size subpacket size
  758. * @param outbuffer pointer to the outbuffer
  759. */
  760. static int decode_subpacket(COOKContext *q, uint8_t *inbuffer,
  761. int sub_packet_size, int16_t *outbuffer) {
  762. /* packet dump */
  763. // for (i=0 ; i<sub_packet_size ; i++) {
  764. // av_log(NULL, AV_LOG_ERROR, "%02x", inbuffer[i]);
  765. // }
  766. // av_log(NULL, AV_LOG_ERROR, "\n");
  767. decode_bytes_and_gain(q, inbuffer, &q->gains1);
  768. if (q->joint_stereo) {
  769. joint_decode(q, q->decode_buffer_1, q->decode_buffer_2);
  770. } else {
  771. mono_decode(q, q->decode_buffer_1);
  772. if (q->nb_channels == 2) {
  773. decode_bytes_and_gain(q, inbuffer + sub_packet_size/2, &q->gains2);
  774. mono_decode(q, q->decode_buffer_2);
  775. }
  776. }
  777. mlt_compensate_output(q, q->decode_buffer_1, &q->gains1,
  778. q->mono_previous_buffer1, outbuffer, 0);
  779. if (q->nb_channels == 2) {
  780. if (q->joint_stereo) {
  781. mlt_compensate_output(q, q->decode_buffer_2, &q->gains1,
  782. q->mono_previous_buffer2, outbuffer, 1);
  783. } else {
  784. mlt_compensate_output(q, q->decode_buffer_2, &q->gains2,
  785. q->mono_previous_buffer2, outbuffer, 1);
  786. }
  787. }
  788. return q->samples_per_frame * sizeof(int16_t);
  789. }
  790. /**
  791. * Cook frame decoding
  792. *
  793. * @param avctx pointer to the AVCodecContext
  794. */
  795. static int cook_decode_frame(AVCodecContext *avctx,
  796. void *data, int *data_size,
  797. uint8_t *buf, int buf_size) {
  798. COOKContext *q = avctx->priv_data;
  799. if (buf_size < avctx->block_align)
  800. return buf_size;
  801. *data_size = decode_subpacket(q, buf, avctx->block_align, data);
  802. /* Discard the first two frames: no valid audio. */
  803. if (avctx->frame_number < 2) *data_size = 0;
  804. return avctx->block_align;
  805. }
  806. #ifdef COOKDEBUG
  807. static void dump_cook_context(COOKContext *q)
  808. {
  809. //int i=0;
  810. #define PRINT(a,b) av_log(NULL,AV_LOG_ERROR," %s = %d\n", a, b);
  811. av_log(NULL,AV_LOG_ERROR,"COOKextradata\n");
  812. av_log(NULL,AV_LOG_ERROR,"cookversion=%x\n",q->cookversion);
  813. if (q->cookversion > STEREO) {
  814. PRINT("js_subband_start",q->js_subband_start);
  815. PRINT("js_vlc_bits",q->js_vlc_bits);
  816. }
  817. av_log(NULL,AV_LOG_ERROR,"COOKContext\n");
  818. PRINT("nb_channels",q->nb_channels);
  819. PRINT("bit_rate",q->bit_rate);
  820. PRINT("sample_rate",q->sample_rate);
  821. PRINT("samples_per_channel",q->samples_per_channel);
  822. PRINT("samples_per_frame",q->samples_per_frame);
  823. PRINT("subbands",q->subbands);
  824. PRINT("random_state",q->random_state);
  825. PRINT("js_subband_start",q->js_subband_start);
  826. PRINT("log2_numvector_size",q->log2_numvector_size);
  827. PRINT("numvector_size",q->numvector_size);
  828. PRINT("total_subbands",q->total_subbands);
  829. }
  830. #endif
  831. /**
  832. * Cook initialization
  833. *
  834. * @param avctx pointer to the AVCodecContext
  835. */
  836. static int cook_decode_init(AVCodecContext *avctx)
  837. {
  838. COOKContext *q = avctx->priv_data;
  839. uint8_t *edata_ptr = avctx->extradata;
  840. /* Take care of the codec specific extradata. */
  841. if (avctx->extradata_size <= 0) {
  842. av_log(avctx,AV_LOG_ERROR,"Necessary extradata missing!\n");
  843. return -1;
  844. } else {
  845. /* 8 for mono, 16 for stereo, ? for multichannel
  846. Swap to right endianness so we don't need to care later on. */
  847. av_log(avctx,AV_LOG_DEBUG,"codecdata_length=%d\n",avctx->extradata_size);
  848. if (avctx->extradata_size >= 8){
  849. q->cookversion = bytestream_get_be32(&edata_ptr);
  850. q->samples_per_frame = bytestream_get_be16(&edata_ptr);
  851. q->subbands = bytestream_get_be16(&edata_ptr);
  852. }
  853. if (avctx->extradata_size >= 16){
  854. bytestream_get_be32(&edata_ptr); //Unknown unused
  855. q->js_subband_start = bytestream_get_be16(&edata_ptr);
  856. q->js_vlc_bits = bytestream_get_be16(&edata_ptr);
  857. }
  858. }
  859. /* Take data from the AVCodecContext (RM container). */
  860. q->sample_rate = avctx->sample_rate;
  861. q->nb_channels = avctx->channels;
  862. q->bit_rate = avctx->bit_rate;
  863. /* Initialize RNG. */
  864. av_init_random(1, &q->random_state);
  865. /* Initialize extradata related variables. */
  866. q->samples_per_channel = q->samples_per_frame / q->nb_channels;
  867. q->bits_per_subpacket = avctx->block_align * 8;
  868. /* Initialize default data states. */
  869. q->log2_numvector_size = 5;
  870. q->total_subbands = q->subbands;
  871. /* Initialize version-dependent variables */
  872. av_log(NULL,AV_LOG_DEBUG,"q->cookversion=%x\n",q->cookversion);
  873. q->joint_stereo = 0;
  874. switch (q->cookversion) {
  875. case MONO:
  876. if (q->nb_channels != 1) {
  877. av_log(avctx,AV_LOG_ERROR,"Container channels != 1, report sample!\n");
  878. return -1;
  879. }
  880. av_log(avctx,AV_LOG_DEBUG,"MONO\n");
  881. break;
  882. case STEREO:
  883. if (q->nb_channels != 1) {
  884. q->bits_per_subpacket = q->bits_per_subpacket/2;
  885. }
  886. av_log(avctx,AV_LOG_DEBUG,"STEREO\n");
  887. break;
  888. case JOINT_STEREO:
  889. if (q->nb_channels != 2) {
  890. av_log(avctx,AV_LOG_ERROR,"Container channels != 2, report sample!\n");
  891. return -1;
  892. }
  893. av_log(avctx,AV_LOG_DEBUG,"JOINT_STEREO\n");
  894. if (avctx->extradata_size >= 16){
  895. q->total_subbands = q->subbands + q->js_subband_start;
  896. q->joint_stereo = 1;
  897. }
  898. if (q->samples_per_channel > 256) {
  899. q->log2_numvector_size = 6;
  900. }
  901. if (q->samples_per_channel > 512) {
  902. q->log2_numvector_size = 7;
  903. }
  904. break;
  905. case MC_COOK:
  906. av_log(avctx,AV_LOG_ERROR,"MC_COOK not supported!\n");
  907. return -1;
  908. break;
  909. default:
  910. av_log(avctx,AV_LOG_ERROR,"Unknown Cook version, report sample!\n");
  911. return -1;
  912. break;
  913. }
  914. /* Initialize variable relations */
  915. q->numvector_size = (1 << q->log2_numvector_size);
  916. /* Generate tables */
  917. init_rootpow2table(q);
  918. init_pow2table(q);
  919. init_gain_table(q);
  920. if (init_cook_vlc_tables(q) != 0)
  921. return -1;
  922. if(avctx->block_align >= UINT_MAX/2)
  923. return -1;
  924. /* Pad the databuffer with:
  925. DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
  926. FF_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */
  927. if (q->nb_channels==2 && q->joint_stereo==0) {
  928. q->decoded_bytes_buffer =
  929. av_mallocz(avctx->block_align/2
  930. + DECODE_BYTES_PAD2(avctx->block_align/2)
  931. + FF_INPUT_BUFFER_PADDING_SIZE);
  932. } else {
  933. q->decoded_bytes_buffer =
  934. av_mallocz(avctx->block_align
  935. + DECODE_BYTES_PAD1(avctx->block_align)
  936. + FF_INPUT_BUFFER_PADDING_SIZE);
  937. }
  938. if (q->decoded_bytes_buffer == NULL)
  939. return -1;
  940. q->gains1.now = q->gain_1;
  941. q->gains1.previous = q->gain_2;
  942. q->gains2.now = q->gain_3;
  943. q->gains2.previous = q->gain_4;
  944. /* Initialize transform. */
  945. if ( init_cook_mlt(q) != 0 )
  946. return -1;
  947. /* Try to catch some obviously faulty streams, othervise it might be exploitable */
  948. if (q->total_subbands > 53) {
  949. av_log(avctx,AV_LOG_ERROR,"total_subbands > 53, report sample!\n");
  950. return -1;
  951. }
  952. if (q->subbands > 50) {
  953. av_log(avctx,AV_LOG_ERROR,"subbands > 50, report sample!\n");
  954. return -1;
  955. }
  956. if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512) || (q->samples_per_channel == 1024)) {
  957. } else {
  958. av_log(avctx,AV_LOG_ERROR,"unknown amount of samples_per_channel = %d, report sample!\n",q->samples_per_channel);
  959. return -1;
  960. }
  961. if ((q->js_vlc_bits > 6) || (q->js_vlc_bits < 0)) {
  962. av_log(avctx,AV_LOG_ERROR,"q->js_vlc_bits = %d, only >= 0 and <= 6 allowed!\n",q->js_vlc_bits);
  963. return -1;
  964. }
  965. #ifdef COOKDEBUG
  966. dump_cook_context(q);
  967. #endif
  968. return 0;
  969. }
  970. AVCodec cook_decoder =
  971. {
  972. .name = "cook",
  973. .type = CODEC_TYPE_AUDIO,
  974. .id = CODEC_ID_COOK,
  975. .priv_data_size = sizeof(COOKContext),
  976. .init = cook_decode_init,
  977. .close = cook_decode_close,
  978. .decode = cook_decode_frame,
  979. };