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.

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