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.

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