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.

1119 lines
35KB

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