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.

1149 lines
37KB

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