cook.c

Go to the documentation of this file.
00001 /*
00002  * COOK compatible decoder
00003  * Copyright (c) 2003 Sascha Sommer
00004  * Copyright (c) 2005 Benjamin Larsson
00005  *
00006  * This file is part of FFmpeg.
00007  *
00008  * FFmpeg is free software; you can redistribute it and/or
00009  * modify it under the terms of the GNU Lesser General Public
00010  * License as published by the Free Software Foundation; either
00011  * version 2.1 of the License, or (at your option) any later version.
00012  *
00013  * FFmpeg is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016  * Lesser General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU Lesser General Public
00019  * License along with FFmpeg; if not, write to the Free Software
00020  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00021  */
00022 
00023 /**
00024  * @file cook.c
00025  * Cook compatible decoder. Bastardization of the G.722.1 standard.
00026  * This decoder handles RealNetworks, RealAudio G2 data.
00027  * Cook is identified by the codec name cook in RM files.
00028  *
00029  * To use this decoder, a calling application must supply the extradata
00030  * bytes provided from the RM container; 8+ bytes for mono streams and
00031  * 16+ for stereo streams (maybe more).
00032  *
00033  * Codec technicalities (all this assume a buffer length of 1024):
00034  * Cook works with several different techniques to achieve its compression.
00035  * In the timedomain the buffer is divided into 8 pieces and quantized. If
00036  * two neighboring pieces have different quantization index a smooth
00037  * quantization curve is used to get a smooth overlap between the different
00038  * pieces.
00039  * To get to the transformdomain Cook uses a modulated lapped transform.
00040  * The transform domain has 50 subbands with 20 elements each. This
00041  * means only a maximum of 50*20=1000 coefficients are used out of the 1024
00042  * available.
00043  */
00044 
00045 #include <math.h>
00046 #include <stddef.h>
00047 #include <stdio.h>
00048 
00049 #include "libavutil/random.h"
00050 #include "avcodec.h"
00051 #include "bitstream.h"
00052 #include "dsputil.h"
00053 #include "bytestream.h"
00054 
00055 #include "cookdata.h"
00056 
00057 /* the different Cook versions */
00058 #define MONO            0x1000001
00059 #define STEREO          0x1000002
00060 #define JOINT_STEREO    0x1000003
00061 #define MC_COOK         0x2000000   //multichannel Cook, not supported
00062 
00063 #define SUBBAND_SIZE    20
00064 //#define COOKDEBUG
00065 
00066 typedef struct {
00067     int *now;
00068     int *previous;
00069 } cook_gains;
00070 
00071 typedef struct cook {
00072     /*
00073      * The following 5 functions provide the lowlevel arithmetic on
00074      * the internal audio buffers.
00075      */
00076     void (* scalar_dequant)(struct cook *q, int index, int quant_index,
00077                             int* subband_coef_index, int* subband_coef_sign,
00078                             float* mlt_p);
00079 
00080     void (* decouple) (struct cook *q,
00081                        int subband,
00082                        float f1, float f2,
00083                        float *decode_buffer,
00084                        float *mlt_buffer1, float *mlt_buffer2);
00085 
00086     void (* imlt_window) (struct cook *q, float *buffer1,
00087                           cook_gains *gains_ptr, float *previous_buffer);
00088 
00089     void (* interpolate) (struct cook *q, float* buffer,
00090                           int gain_index, int gain_index_next);
00091 
00092     void (* saturate_output) (struct cook *q, int chan, int16_t *out);
00093 
00094     GetBitContext       gb;
00095     /* stream data */
00096     int                 nb_channels;
00097     int                 joint_stereo;
00098     int                 bit_rate;
00099     int                 sample_rate;
00100     int                 samples_per_channel;
00101     int                 samples_per_frame;
00102     int                 subbands;
00103     int                 log2_numvector_size;
00104     int                 numvector_size;                //1 << log2_numvector_size;
00105     int                 js_subband_start;
00106     int                 total_subbands;
00107     int                 num_vectors;
00108     int                 bits_per_subpacket;
00109     int                 cookversion;
00110     /* states */
00111     AVRandomState       random_state;
00112 
00113     /* transform data */
00114     MDCTContext         mdct_ctx;
00115     DECLARE_ALIGNED_16(FFTSample, mdct_tmp[1024]);  /* temporary storage for imlt */
00116     float*              mlt_window;
00117 
00118     /* gain buffers */
00119     cook_gains          gains1;
00120     cook_gains          gains2;
00121     int                 gain_1[9];
00122     int                 gain_2[9];
00123     int                 gain_3[9];
00124     int                 gain_4[9];
00125 
00126     /* VLC data */
00127     int                 js_vlc_bits;
00128     VLC                 envelope_quant_index[13];
00129     VLC                 sqvh[7];          //scalar quantization
00130     VLC                 ccpl;             //channel coupling
00131 
00132     /* generatable tables and related variables */
00133     int                 gain_size_factor;
00134     float               gain_table[23];
00135 
00136     /* data buffers */
00137 
00138     uint8_t*            decoded_bytes_buffer;
00139     DECLARE_ALIGNED_16(float,mono_mdct_output[2048]);
00140     float               mono_previous_buffer1[1024];
00141     float               mono_previous_buffer2[1024];
00142     float               decode_buffer_1[1024];
00143     float               decode_buffer_2[1024];
00144     float               decode_buffer_0[1060]; /* static allocation for joint decode */
00145 
00146     const float         *cplscales[5];
00147 } COOKContext;
00148 
00149 static float     pow2tab[127];
00150 static float rootpow2tab[127];
00151 
00152 /* debug functions */
00153 
00154 #ifdef COOKDEBUG
00155 static void dump_float_table(float* table, int size, int delimiter) {
00156     int i=0;
00157     av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i);
00158     for (i=0 ; i<size ; i++) {
00159         av_log(NULL, AV_LOG_ERROR, "%5.1f, ", table[i]);
00160         if ((i+1)%delimiter == 0) av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i+1);
00161     }
00162 }
00163 
00164 static void dump_int_table(int* table, int size, int delimiter) {
00165     int i=0;
00166     av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i);
00167     for (i=0 ; i<size ; i++) {
00168         av_log(NULL, AV_LOG_ERROR, "%d, ", table[i]);
00169         if ((i+1)%delimiter == 0) av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i+1);
00170     }
00171 }
00172 
00173 static void dump_short_table(short* table, int size, int delimiter) {
00174     int i=0;
00175     av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i);
00176     for (i=0 ; i<size ; i++) {
00177         av_log(NULL, AV_LOG_ERROR, "%d, ", table[i]);
00178         if ((i+1)%delimiter == 0) av_log(NULL,AV_LOG_ERROR,"\n[%d]: ",i+1);
00179     }
00180 }
00181 
00182 #endif
00183 
00184 /*************** init functions ***************/
00185 
00186 /* table generator */
00187 static void init_pow2table(void){
00188     int i;
00189     for (i=-63 ; i<64 ; i++){
00190             pow2tab[63+i]=     pow(2, i);
00191         rootpow2tab[63+i]=sqrt(pow(2, i));
00192     }
00193 }
00194 
00195 /* table generator */
00196 static void init_gain_table(COOKContext *q) {
00197     int i;
00198     q->gain_size_factor = q->samples_per_channel/8;
00199     for (i=0 ; i<23 ; i++) {
00200         q->gain_table[i] = pow(pow2tab[i+52] ,
00201                                (1.0/(double)q->gain_size_factor));
00202     }
00203 }
00204 
00205 
00206 static int init_cook_vlc_tables(COOKContext *q) {
00207     int i, result;
00208 
00209     result = 0;
00210     for (i=0 ; i<13 ; i++) {
00211         result |= init_vlc (&q->envelope_quant_index[i], 9, 24,
00212             envelope_quant_index_huffbits[i], 1, 1,
00213             envelope_quant_index_huffcodes[i], 2, 2, 0);
00214     }
00215     av_log(NULL,AV_LOG_DEBUG,"sqvh VLC init\n");
00216     for (i=0 ; i<7 ; i++) {
00217         result |= init_vlc (&q->sqvh[i], vhvlcsize_tab[i], vhsize_tab[i],
00218             cvh_huffbits[i], 1, 1,
00219             cvh_huffcodes[i], 2, 2, 0);
00220     }
00221 
00222     if (q->nb_channels==2 && q->joint_stereo==1){
00223         result |= init_vlc (&q->ccpl, 6, (1<<q->js_vlc_bits)-1,
00224             ccpl_huffbits[q->js_vlc_bits-2], 1, 1,
00225             ccpl_huffcodes[q->js_vlc_bits-2], 2, 2, 0);
00226         av_log(NULL,AV_LOG_DEBUG,"Joint-stereo VLC used.\n");
00227     }
00228 
00229     av_log(NULL,AV_LOG_DEBUG,"VLC tables initialized.\n");
00230     return result;
00231 }
00232 
00233 static int init_cook_mlt(COOKContext *q) {
00234     int j;
00235     int mlt_size = q->samples_per_channel;
00236 
00237     if ((q->mlt_window = av_malloc(sizeof(float)*mlt_size)) == 0)
00238       return -1;
00239 
00240     /* Initialize the MLT window: simple sine window. */
00241     ff_sine_window_init(q->mlt_window, mlt_size);
00242     for(j=0 ; j<mlt_size ; j++)
00243         q->mlt_window[j] *= sqrt(2.0 / q->samples_per_channel);
00244 
00245     /* Initialize the MDCT. */
00246     if (ff_mdct_init(&q->mdct_ctx, av_log2(mlt_size)+1, 1)) {
00247       av_free(q->mlt_window);
00248       return -1;
00249     }
00250     av_log(NULL,AV_LOG_DEBUG,"MDCT initialized, order = %d.\n",
00251            av_log2(mlt_size)+1);
00252 
00253     return 0;
00254 }
00255 
00256 static const float *maybe_reformat_buffer32 (COOKContext *q, const float *ptr, int n)
00257 {
00258     if (1)
00259         return ptr;
00260 }
00261 
00262 static void init_cplscales_table (COOKContext *q) {
00263     int i;
00264     for (i=0;i<5;i++)
00265         q->cplscales[i] = maybe_reformat_buffer32 (q, cplscales[i], (1<<(i+2))-1);
00266 }
00267 
00268 /*************** init functions end ***********/
00269 
00270 /**
00271  * Cook indata decoding, every 32 bits are XORed with 0x37c511f2.
00272  * Why? No idea, some checksum/error detection method maybe.
00273  *
00274  * Out buffer size: extra bytes are needed to cope with
00275  * padding/misalignment.
00276  * Subpackets passed to the decoder can contain two, consecutive
00277  * half-subpackets, of identical but arbitrary size.
00278  *          1234 1234 1234 1234  extraA extraB
00279  * Case 1:  AAAA BBBB              0      0
00280  * Case 2:  AAAA ABBB BB--         3      3
00281  * Case 3:  AAAA AABB BBBB         2      2
00282  * Case 4:  AAAA AAAB BBBB BB--    1      5
00283  *
00284  * Nice way to waste CPU cycles.
00285  *
00286  * @param inbuffer  pointer to byte array of indata
00287  * @param out       pointer to byte array of outdata
00288  * @param bytes     number of bytes
00289  */
00290 #define DECODE_BYTES_PAD1(bytes) (3 - ((bytes)+3) % 4)
00291 #define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
00292 
00293 static inline int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){
00294     int i, off;
00295     uint32_t c;
00296     const uint32_t* buf;
00297     uint32_t* obuf = (uint32_t*) out;
00298     /* FIXME: 64 bit platforms would be able to do 64 bits at a time.
00299      * I'm too lazy though, should be something like
00300      * for(i=0 ; i<bitamount/64 ; i++)
00301      *     (int64_t)out[i] = 0x37c511f237c511f2^be2me_64(int64_t)in[i]);
00302      * Buffer alignment needs to be checked. */
00303 
00304     off = (int)((long)inbuffer & 3);
00305     buf = (const uint32_t*) (inbuffer - off);
00306     c = be2me_32((0x37c511f2 >> (off*8)) | (0x37c511f2 << (32-(off*8))));
00307     bytes += 3 + off;
00308     for (i = 0; i < bytes/4; i++)
00309         obuf[i] = c ^ buf[i];
00310 
00311     return off;
00312 }
00313 
00314 /**
00315  * Cook uninit
00316  */
00317 
00318 static int cook_decode_close(AVCodecContext *avctx)
00319 {
00320     int i;
00321     COOKContext *q = avctx->priv_data;
00322     av_log(avctx,AV_LOG_DEBUG, "Deallocating memory.\n");
00323 
00324     /* Free allocated memory buffers. */
00325     av_free(q->mlt_window);
00326     av_free(q->decoded_bytes_buffer);
00327 
00328     /* Free the transform. */
00329     ff_mdct_end(&q->mdct_ctx);
00330 
00331     /* Free the VLC tables. */
00332     for (i=0 ; i<13 ; i++) {
00333         free_vlc(&q->envelope_quant_index[i]);
00334     }
00335     for (i=0 ; i<7 ; i++) {
00336         free_vlc(&q->sqvh[i]);
00337     }
00338     if(q->nb_channels==2 && q->joint_stereo==1 ){
00339         free_vlc(&q->ccpl);
00340     }
00341 
00342     av_log(NULL,AV_LOG_DEBUG,"Memory deallocated.\n");
00343 
00344     return 0;
00345 }
00346 
00347 /**
00348  * Fill the gain array for the timedomain quantization.
00349  *
00350  * @param q                 pointer to the COOKContext
00351  * @param gaininfo[9]       array of gain indexes
00352  */
00353 
00354 static void decode_gain_info(GetBitContext *gb, int *gaininfo)
00355 {
00356     int i, n;
00357 
00358     while (get_bits1(gb)) {}
00359     n = get_bits_count(gb) - 1;     //amount of elements*2 to update
00360 
00361     i = 0;
00362     while (n--) {
00363         int index = get_bits(gb, 3);
00364         int gain = get_bits1(gb) ? get_bits(gb, 4) - 7 : -1;
00365 
00366         while (i <= index) gaininfo[i++] = gain;
00367     }
00368     while (i <= 8) gaininfo[i++] = 0;
00369 }
00370 
00371 /**
00372  * Create the quant index table needed for the envelope.
00373  *
00374  * @param q                 pointer to the COOKContext
00375  * @param quant_index_table pointer to the array
00376  */
00377 
00378 static void decode_envelope(COOKContext *q, int* quant_index_table) {
00379     int i,j, vlc_index;
00380 
00381     quant_index_table[0]= get_bits(&q->gb,6) - 6;       //This is used later in categorize
00382 
00383     for (i=1 ; i < q->total_subbands ; i++){
00384         vlc_index=i;
00385         if (i >= q->js_subband_start * 2) {
00386             vlc_index-=q->js_subband_start;
00387         } else {
00388             vlc_index/=2;
00389             if(vlc_index < 1) vlc_index = 1;
00390         }
00391         if (vlc_index>13) vlc_index = 13;           //the VLC tables >13 are identical to No. 13
00392 
00393         j = get_vlc2(&q->gb, q->envelope_quant_index[vlc_index-1].table,
00394                      q->envelope_quant_index[vlc_index-1].bits,2);
00395         quant_index_table[i] = quant_index_table[i-1] + j - 12;    //differential encoding
00396     }
00397 }
00398 
00399 /**
00400  * Calculate the category and category_index vector.
00401  *
00402  * @param q                     pointer to the COOKContext
00403  * @param quant_index_table     pointer to the array
00404  * @param category              pointer to the category array
00405  * @param category_index        pointer to the category_index array
00406  */
00407 
00408 static void categorize(COOKContext *q, int* quant_index_table,
00409                        int* category, int* category_index){
00410     int exp_idx, bias, tmpbias1, tmpbias2, bits_left, num_bits, index, v, i, j;
00411     int exp_index2[102];
00412     int exp_index1[102];
00413 
00414     int tmp_categorize_array[128*2];
00415     int tmp_categorize_array1_idx=q->numvector_size;
00416     int tmp_categorize_array2_idx=q->numvector_size;
00417 
00418     bits_left =  q->bits_per_subpacket - get_bits_count(&q->gb);
00419 
00420     if(bits_left > q->samples_per_channel) {
00421         bits_left = q->samples_per_channel +
00422                     ((bits_left - q->samples_per_channel)*5)/8;
00423         //av_log(NULL, AV_LOG_ERROR, "bits_left = %d\n",bits_left);
00424     }
00425 
00426     memset(&exp_index1,0,102*sizeof(int));
00427     memset(&exp_index2,0,102*sizeof(int));
00428     memset(&tmp_categorize_array,0,128*2*sizeof(int));
00429 
00430     bias=-32;
00431 
00432     /* Estimate bias. */
00433     for (i=32 ; i>0 ; i=i/2){
00434         num_bits = 0;
00435         index = 0;
00436         for (j=q->total_subbands ; j>0 ; j--){
00437             exp_idx = av_clip((i - quant_index_table[index] + bias) / 2, 0, 7);
00438             index++;
00439             num_bits+=expbits_tab[exp_idx];
00440         }
00441         if(num_bits >= bits_left - 32){
00442             bias+=i;
00443         }
00444     }
00445 
00446     /* Calculate total number of bits. */
00447     num_bits=0;
00448     for (i=0 ; i<q->total_subbands ; i++) {
00449         exp_idx = av_clip((bias - quant_index_table[i]) / 2, 0, 7);
00450         num_bits += expbits_tab[exp_idx];
00451         exp_index1[i] = exp_idx;
00452         exp_index2[i] = exp_idx;
00453     }
00454     tmpbias1 = tmpbias2 = num_bits;
00455 
00456     for (j = 1 ; j < q->numvector_size ; j++) {
00457         if (tmpbias1 + tmpbias2 > 2*bits_left) {  /* ---> */
00458             int max = -999999;
00459             index=-1;
00460             for (i=0 ; i<q->total_subbands ; i++){
00461                 if (exp_index1[i] < 7) {
00462                     v = (-2*exp_index1[i]) - quant_index_table[i] + bias;
00463                     if ( v >= max) {
00464                         max = v;
00465                         index = i;
00466                     }
00467                 }
00468             }
00469             if(index==-1)break;
00470             tmp_categorize_array[tmp_categorize_array1_idx++] = index;
00471             tmpbias1 -= expbits_tab[exp_index1[index]] -
00472                         expbits_tab[exp_index1[index]+1];
00473             ++exp_index1[index];
00474         } else {  /* <--- */
00475             int min = 999999;
00476             index=-1;
00477             for (i=0 ; i<q->total_subbands ; i++){
00478                 if(exp_index2[i] > 0){
00479                     v = (-2*exp_index2[i])-quant_index_table[i]+bias;
00480                     if ( v < min) {
00481                         min = v;
00482                         index = i;
00483                     }
00484                 }
00485             }
00486             if(index == -1)break;
00487             tmp_categorize_array[--tmp_categorize_array2_idx] = index;
00488             tmpbias2 -= expbits_tab[exp_index2[index]] -
00489                         expbits_tab[exp_index2[index]-1];
00490             --exp_index2[index];
00491         }
00492     }
00493 
00494     for(i=0 ; i<q->total_subbands ; i++)
00495         category[i] = exp_index2[i];
00496 
00497     for(i=0 ; i<q->numvector_size-1 ; i++)
00498         category_index[i] = tmp_categorize_array[tmp_categorize_array2_idx++];
00499 
00500 }
00501 
00502 
00503 /**
00504  * Expand the category vector.
00505  *
00506  * @param q                     pointer to the COOKContext
00507  * @param category              pointer to the category array
00508  * @param category_index        pointer to the category_index array
00509  */
00510 
00511 static inline void expand_category(COOKContext *q, int* category,
00512                                    int* category_index){
00513     int i;
00514     for(i=0 ; i<q->num_vectors ; i++){
00515         ++category[category_index[i]];
00516     }
00517 }
00518 
00519 /**
00520  * The real requantization of the mltcoefs
00521  *
00522  * @param q                     pointer to the COOKContext
00523  * @param index                 index
00524  * @param quant_index           quantisation index
00525  * @param subband_coef_index    array of indexes to quant_centroid_tab
00526  * @param subband_coef_sign     signs of coefficients
00527  * @param mlt_p                 pointer into the mlt buffer
00528  */
00529 
00530 static void scalar_dequant_float(COOKContext *q, int index, int quant_index,
00531                            int* subband_coef_index, int* subband_coef_sign,
00532                            float* mlt_p){
00533     int i;
00534     float f1;
00535 
00536     for(i=0 ; i<SUBBAND_SIZE ; i++) {
00537         if (subband_coef_index[i]) {
00538             f1 = quant_centroid_tab[index][subband_coef_index[i]];
00539             if (subband_coef_sign[i]) f1 = -f1;
00540         } else {
00541             /* noise coding if subband_coef_index[i] == 0 */
00542             f1 = dither_tab[index];
00543             if (av_random(&q->random_state) < 0x80000000) f1 = -f1;
00544         }
00545         mlt_p[i] = f1 * rootpow2tab[quant_index+63];
00546     }
00547 }
00548 /**
00549  * Unpack the subband_coef_index and subband_coef_sign vectors.
00550  *
00551  * @param q                     pointer to the COOKContext
00552  * @param category              pointer to the category array
00553  * @param subband_coef_index    array of indexes to quant_centroid_tab
00554  * @param subband_coef_sign     signs of coefficients
00555  */
00556 
00557 static int unpack_SQVH(COOKContext *q, int category, int* subband_coef_index,
00558                        int* subband_coef_sign) {
00559     int i,j;
00560     int vlc, vd ,tmp, result;
00561 
00562     vd = vd_tab[category];
00563     result = 0;
00564     for(i=0 ; i<vpr_tab[category] ; i++){
00565         vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
00566         if (q->bits_per_subpacket < get_bits_count(&q->gb)){
00567             vlc = 0;
00568             result = 1;
00569         }
00570         for(j=vd-1 ; j>=0 ; j--){
00571             tmp = (vlc * invradix_tab[category])/0x100000;
00572             subband_coef_index[vd*i+j] = vlc - tmp * (kmax_tab[category]+1);
00573             vlc = tmp;
00574         }
00575         for(j=0 ; j<vd ; j++){
00576             if (subband_coef_index[i*vd + j]) {
00577                 if(get_bits_count(&q->gb) < q->bits_per_subpacket){
00578                     subband_coef_sign[i*vd+j] = get_bits1(&q->gb);
00579                 } else {
00580                     result=1;
00581                     subband_coef_sign[i*vd+j]=0;
00582                 }
00583             } else {
00584                 subband_coef_sign[i*vd+j]=0;
00585             }
00586         }
00587     }
00588     return result;
00589 }
00590 
00591 
00592 /**
00593  * Fill the mlt_buffer with mlt coefficients.
00594  *
00595  * @param q                 pointer to the COOKContext
00596  * @param category          pointer to the category array
00597  * @param quant_index_table pointer to the array
00598  * @param mlt_buffer        pointer to mlt coefficients
00599  */
00600 
00601 
00602 static void decode_vectors(COOKContext* q, int* category,
00603                            int *quant_index_table, float* mlt_buffer){
00604     /* A zero in this table means that the subband coefficient is
00605        random noise coded. */
00606     int subband_coef_index[SUBBAND_SIZE];
00607     /* A zero in this table means that the subband coefficient is a
00608        positive multiplicator. */
00609     int subband_coef_sign[SUBBAND_SIZE];
00610     int band, j;
00611     int index=0;
00612 
00613     for(band=0 ; band<q->total_subbands ; band++){
00614         index = category[band];
00615         if(category[band] < 7){
00616             if(unpack_SQVH(q, category[band], subband_coef_index, subband_coef_sign)){
00617                 index=7;
00618                 for(j=0 ; j<q->total_subbands ; j++) category[band+j]=7;
00619             }
00620         }
00621         if(index==7) {
00622             memset(subband_coef_index, 0, sizeof(subband_coef_index));
00623             memset(subband_coef_sign, 0, sizeof(subband_coef_sign));
00624         }
00625         q->scalar_dequant(q, index, quant_index_table[band],
00626                           subband_coef_index, subband_coef_sign,
00627                           &mlt_buffer[band * SUBBAND_SIZE]);
00628     }
00629 
00630     if(q->total_subbands*SUBBAND_SIZE >= q->samples_per_channel){
00631         return;
00632     } /* FIXME: should this be removed, or moved into loop above? */
00633 }
00634 
00635 
00636 /**
00637  * function for decoding mono data
00638  *
00639  * @param q                 pointer to the COOKContext
00640  * @param mlt_buffer        pointer to mlt coefficients
00641  */
00642 
00643 static void mono_decode(COOKContext *q, float* mlt_buffer) {
00644 
00645     int category_index[128];
00646     int quant_index_table[102];
00647     int category[128];
00648 
00649     memset(&category, 0, 128*sizeof(int));
00650     memset(&category_index, 0, 128*sizeof(int));
00651 
00652     decode_envelope(q, quant_index_table);
00653     q->num_vectors = get_bits(&q->gb,q->log2_numvector_size);
00654     categorize(q, quant_index_table, category, category_index);
00655     expand_category(q, category, category_index);
00656     decode_vectors(q, category, quant_index_table, mlt_buffer);
00657 }
00658 
00659 
00660 /**
00661  * the actual requantization of the timedomain samples
00662  *
00663  * @param q                 pointer to the COOKContext
00664  * @param buffer            pointer to the timedomain buffer
00665  * @param gain_index        index for the block multiplier
00666  * @param gain_index_next   index for the next block multiplier
00667  */
00668 
00669 static void interpolate_float(COOKContext *q, float* buffer,
00670                         int gain_index, int gain_index_next){
00671     int i;
00672     float fc1, fc2;
00673     fc1 = pow2tab[gain_index+63];
00674 
00675     if(gain_index == gain_index_next){              //static gain
00676         for(i=0 ; i<q->gain_size_factor ; i++){
00677             buffer[i]*=fc1;
00678         }
00679         return;
00680     } else {                                        //smooth gain
00681         fc2 = q->gain_table[11 + (gain_index_next-gain_index)];
00682         for(i=0 ; i<q->gain_size_factor ; i++){
00683             buffer[i]*=fc1;
00684             fc1*=fc2;
00685         }
00686         return;
00687     }
00688 }
00689 
00690 /**
00691  * Apply transform window, overlap buffers.
00692  *
00693  * @param q                 pointer to the COOKContext
00694  * @param inbuffer          pointer to the mltcoefficients
00695  * @param gains_ptr         current and previous gains
00696  * @param previous_buffer   pointer to the previous buffer to be used for overlapping
00697  */
00698 
00699 static void imlt_window_float (COOKContext *q, float *buffer1,
00700                                cook_gains *gains_ptr, float *previous_buffer)
00701 {
00702     const float fc = pow2tab[gains_ptr->previous[0] + 63];
00703     int i;
00704     /* The weird thing here, is that the two halves of the time domain
00705      * buffer are swapped. Also, the newest data, that we save away for
00706      * next frame, has the wrong sign. Hence the subtraction below.
00707      * Almost sounds like a complex conjugate/reverse data/FFT effect.
00708      */
00709 
00710     /* Apply window and overlap */
00711     for(i = 0; i < q->samples_per_channel; i++){
00712         buffer1[i] = buffer1[i] * fc * q->mlt_window[i] -
00713           previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
00714     }
00715 }
00716 
00717 /**
00718  * The modulated lapped transform, this takes transform coefficients
00719  * and transforms them into timedomain samples.
00720  * Apply transform window, overlap buffers, apply gain profile
00721  * and buffer management.
00722  *
00723  * @param q                 pointer to the COOKContext
00724  * @param inbuffer          pointer to the mltcoefficients
00725  * @param gains_ptr         current and previous gains
00726  * @param previous_buffer   pointer to the previous buffer to be used for overlapping
00727  */
00728 
00729 static void imlt_gain(COOKContext *q, float *inbuffer,
00730                       cook_gains *gains_ptr, float* previous_buffer)
00731 {
00732     float *buffer0 = q->mono_mdct_output;
00733     float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
00734     int i;
00735 
00736     /* Inverse modified discrete cosine transform */
00737     q->mdct_ctx.fft.imdct_calc(&q->mdct_ctx, q->mono_mdct_output,
00738                                inbuffer, q->mdct_tmp);
00739 
00740     q->imlt_window (q, buffer1, gains_ptr, previous_buffer);
00741 
00742     /* Apply gain profile */
00743     for (i = 0; i < 8; i++) {
00744         if (gains_ptr->now[i] || gains_ptr->now[i + 1])
00745             q->interpolate(q, &buffer1[q->gain_size_factor * i],
00746                            gains_ptr->now[i], gains_ptr->now[i + 1]);
00747     }
00748 
00749     /* Save away the current to be previous block. */
00750     memcpy(previous_buffer, buffer0, sizeof(float)*q->samples_per_channel);
00751 }
00752 
00753 
00754 /**
00755  * function for getting the jointstereo coupling information
00756  *
00757  * @param q                 pointer to the COOKContext
00758  * @param decouple_tab      decoupling array
00759  *
00760  */
00761 
00762 static void decouple_info(COOKContext *q, int* decouple_tab){
00763     int length, i;
00764 
00765     if(get_bits1(&q->gb)) {
00766         if(cplband[q->js_subband_start] > cplband[q->subbands-1]) return;
00767 
00768         length = cplband[q->subbands-1] - cplband[q->js_subband_start] + 1;
00769         for (i=0 ; i<length ; i++) {
00770             decouple_tab[cplband[q->js_subband_start] + i] = get_vlc2(&q->gb, q->ccpl.table, q->ccpl.bits, 2);
00771         }
00772         return;
00773     }
00774 
00775     if(cplband[q->js_subband_start] > cplband[q->subbands-1]) return;
00776 
00777     length = cplband[q->subbands-1] - cplband[q->js_subband_start] + 1;
00778     for (i=0 ; i<length ; i++) {
00779        decouple_tab[cplband[q->js_subband_start] + i] = get_bits(&q->gb, q->js_vlc_bits);
00780     }
00781     return;
00782 }
00783 
00784 /*
00785  * function decouples a pair of signals from a single signal via multiplication.
00786  *
00787  * @param q                 pointer to the COOKContext
00788  * @param subband           index of the current subband
00789  * @param f1                multiplier for channel 1 extraction
00790  * @param f2                multiplier for channel 2 extraction
00791  * @param decode_buffer     input buffer
00792  * @param mlt_buffer1       pointer to left channel mlt coefficients
00793  * @param mlt_buffer2       pointer to right channel mlt coefficients
00794  */
00795 static void decouple_float (COOKContext *q,
00796                             int subband,
00797                             float f1, float f2,
00798                             float *decode_buffer,
00799                             float *mlt_buffer1, float *mlt_buffer2)
00800 {
00801     int j, tmp_idx;
00802     for (j=0 ; j<SUBBAND_SIZE ; j++) {
00803         tmp_idx = ((q->js_subband_start + subband)*SUBBAND_SIZE)+j;
00804         mlt_buffer1[SUBBAND_SIZE*subband + j] = f1 * decode_buffer[tmp_idx];
00805         mlt_buffer2[SUBBAND_SIZE*subband + j] = f2 * decode_buffer[tmp_idx];
00806     }
00807 }
00808 
00809 /**
00810  * function for decoding joint stereo data
00811  *
00812  * @param q                 pointer to the COOKContext
00813  * @param mlt_buffer1       pointer to left channel mlt coefficients
00814  * @param mlt_buffer2       pointer to right channel mlt coefficients
00815  */
00816 
00817 static void joint_decode(COOKContext *q, float* mlt_buffer1,
00818                          float* mlt_buffer2) {
00819     int i,j;
00820     int decouple_tab[SUBBAND_SIZE];
00821     float *decode_buffer = q->decode_buffer_0;
00822     int idx, cpl_tmp;
00823     float f1,f2;
00824     const float* cplscale;
00825 
00826     memset(decouple_tab, 0, sizeof(decouple_tab));
00827     memset(decode_buffer, 0, sizeof(decode_buffer));
00828 
00829     /* Make sure the buffers are zeroed out. */
00830     memset(mlt_buffer1,0, 1024*sizeof(float));
00831     memset(mlt_buffer2,0, 1024*sizeof(float));
00832     decouple_info(q, decouple_tab);
00833     mono_decode(q, decode_buffer);
00834 
00835     /* The two channels are stored interleaved in decode_buffer. */
00836     for (i=0 ; i<q->js_subband_start ; i++) {
00837         for (j=0 ; j<SUBBAND_SIZE ; j++) {
00838             mlt_buffer1[i*20+j] = decode_buffer[i*40+j];
00839             mlt_buffer2[i*20+j] = decode_buffer[i*40+20+j];
00840         }
00841     }
00842 
00843     /* When we reach js_subband_start (the higher frequencies)
00844        the coefficients are stored in a coupling scheme. */
00845     idx = (1 << q->js_vlc_bits) - 1;
00846     for (i=q->js_subband_start ; i<q->subbands ; i++) {
00847         cpl_tmp = cplband[i];
00848         idx -=decouple_tab[cpl_tmp];
00849         cplscale = q->cplscales[q->js_vlc_bits-2];  //choose decoupler table
00850         f1 = cplscale[decouple_tab[cpl_tmp]];
00851         f2 = cplscale[idx-1];
00852         q->decouple (q, i, f1, f2, decode_buffer, mlt_buffer1, mlt_buffer2);
00853         idx = (1 << q->js_vlc_bits) - 1;
00854     }
00855 }
00856 
00857 /**
00858  * First part of subpacket decoding:
00859  *  decode raw stream bytes and read gain info.
00860  *
00861  * @param q                 pointer to the COOKContext
00862  * @param inbuffer          pointer to raw stream data
00863  * @param gain_ptr          array of current/prev gain pointers
00864  */
00865 
00866 static inline void
00867 decode_bytes_and_gain(COOKContext *q, const uint8_t *inbuffer,
00868                       cook_gains *gains_ptr)
00869 {
00870     int offset;
00871 
00872     offset = decode_bytes(inbuffer, q->decoded_bytes_buffer,
00873                           q->bits_per_subpacket/8);
00874     init_get_bits(&q->gb, q->decoded_bytes_buffer + offset,
00875                   q->bits_per_subpacket);
00876     decode_gain_info(&q->gb, gains_ptr->now);
00877 
00878     /* Swap current and previous gains */
00879     FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
00880 }
00881 
00882  /**
00883  * Saturate the output signal to signed 16bit integers.
00884  *
00885  * @param q                 pointer to the COOKContext
00886  * @param chan              channel to saturate
00887  * @param out               pointer to the output vector
00888  */
00889 static void
00890 saturate_output_float (COOKContext *q, int chan, int16_t *out)
00891 {
00892     int j;
00893     float *output = q->mono_mdct_output + q->samples_per_channel;
00894     /* Clip and convert floats to 16 bits.
00895      */
00896     for (j = 0; j < q->samples_per_channel; j++) {
00897         out[chan + q->nb_channels * j] =
00898           av_clip_int16(lrintf(output[j]));
00899     }
00900 }
00901 
00902 /**
00903  * Final part of subpacket decoding:
00904  *  Apply modulated lapped transform, gain compensation,
00905  *  clip and convert to integer.
00906  *
00907  * @param q                 pointer to the COOKContext
00908  * @param decode_buffer     pointer to the mlt coefficients
00909  * @param gain_ptr          array of current/prev gain pointers
00910  * @param previous_buffer   pointer to the previous buffer to be used for overlapping
00911  * @param out               pointer to the output buffer
00912  * @param chan              0: left or single channel, 1: right channel
00913  */
00914 
00915 static inline void
00916 mlt_compensate_output(COOKContext *q, float *decode_buffer,
00917                       cook_gains *gains, float *previous_buffer,
00918                       int16_t *out, int chan)
00919 {
00920     imlt_gain(q, decode_buffer, gains, previous_buffer);
00921     q->saturate_output (q, chan, out);
00922 }
00923 
00924 
00925 /**
00926  * Cook subpacket decoding. This function returns one decoded subpacket,
00927  * usually 1024 samples per channel.
00928  *
00929  * @param q                 pointer to the COOKContext
00930  * @param inbuffer          pointer to the inbuffer
00931  * @param sub_packet_size   subpacket size
00932  * @param outbuffer         pointer to the outbuffer
00933  */
00934 
00935 
00936 static int decode_subpacket(COOKContext *q, const uint8_t *inbuffer,
00937                             int sub_packet_size, int16_t *outbuffer) {
00938     /* packet dump */
00939 //    for (i=0 ; i<sub_packet_size ; i++) {
00940 //        av_log(NULL, AV_LOG_ERROR, "%02x", inbuffer[i]);
00941 //    }
00942 //    av_log(NULL, AV_LOG_ERROR, "\n");
00943 
00944     decode_bytes_and_gain(q, inbuffer, &q->gains1);
00945 
00946     if (q->joint_stereo) {
00947         joint_decode(q, q->decode_buffer_1, q->decode_buffer_2);
00948     } else {
00949         mono_decode(q, q->decode_buffer_1);
00950 
00951         if (q->nb_channels == 2) {
00952             decode_bytes_and_gain(q, inbuffer + sub_packet_size/2, &q->gains2);
00953             mono_decode(q, q->decode_buffer_2);
00954         }
00955     }
00956 
00957     mlt_compensate_output(q, q->decode_buffer_1, &q->gains1,
00958                           q->mono_previous_buffer1, outbuffer, 0);
00959 
00960     if (q->nb_channels == 2) {
00961         if (q->joint_stereo) {
00962             mlt_compensate_output(q, q->decode_buffer_2, &q->gains1,
00963                                   q->mono_previous_buffer2, outbuffer, 1);
00964         } else {
00965             mlt_compensate_output(q, q->decode_buffer_2, &q->gains2,
00966                                   q->mono_previous_buffer2, outbuffer, 1);
00967         }
00968     }
00969     return q->samples_per_frame * sizeof(int16_t);
00970 }
00971 
00972 
00973 /**
00974  * Cook frame decoding
00975  *
00976  * @param avctx     pointer to the AVCodecContext
00977  */
00978 
00979 static int cook_decode_frame(AVCodecContext *avctx,
00980             void *data, int *data_size,
00981             const uint8_t *buf, int buf_size) {
00982     COOKContext *q = avctx->priv_data;
00983 
00984     if (buf_size < avctx->block_align)
00985         return buf_size;
00986 
00987     *data_size = decode_subpacket(q, buf, avctx->block_align, data);
00988 
00989     /* Discard the first two frames: no valid audio. */
00990     if (avctx->frame_number < 2) *data_size = 0;
00991 
00992     return avctx->block_align;
00993 }
00994 
00995 #ifdef COOKDEBUG
00996 static void dump_cook_context(COOKContext *q)
00997 {
00998     //int i=0;
00999 #define PRINT(a,b) av_log(NULL,AV_LOG_ERROR," %s = %d\n", a, b);
01000     av_log(NULL,AV_LOG_ERROR,"COOKextradata\n");
01001     av_log(NULL,AV_LOG_ERROR,"cookversion=%x\n",q->cookversion);
01002     if (q->cookversion > STEREO) {
01003         PRINT("js_subband_start",q->js_subband_start);
01004         PRINT("js_vlc_bits",q->js_vlc_bits);
01005     }
01006     av_log(NULL,AV_LOG_ERROR,"COOKContext\n");
01007     PRINT("nb_channels",q->nb_channels);
01008     PRINT("bit_rate",q->bit_rate);
01009     PRINT("sample_rate",q->sample_rate);
01010     PRINT("samples_per_channel",q->samples_per_channel);
01011     PRINT("samples_per_frame",q->samples_per_frame);
01012     PRINT("subbands",q->subbands);
01013     PRINT("random_state",q->random_state);
01014     PRINT("js_subband_start",q->js_subband_start);
01015     PRINT("log2_numvector_size",q->log2_numvector_size);
01016     PRINT("numvector_size",q->numvector_size);
01017     PRINT("total_subbands",q->total_subbands);
01018 }
01019 #endif
01020 
01021 /**
01022  * Cook initialization
01023  *
01024  * @param avctx     pointer to the AVCodecContext
01025  */
01026 
01027 static int cook_decode_init(AVCodecContext *avctx)
01028 {
01029     COOKContext *q = avctx->priv_data;
01030     const uint8_t *edata_ptr = avctx->extradata;
01031 
01032     /* Take care of the codec specific extradata. */
01033     if (avctx->extradata_size <= 0) {
01034         av_log(avctx,AV_LOG_ERROR,"Necessary extradata missing!\n");
01035         return -1;
01036     } else {
01037         /* 8 for mono, 16 for stereo, ? for multichannel
01038            Swap to right endianness so we don't need to care later on. */
01039         av_log(avctx,AV_LOG_DEBUG,"codecdata_length=%d\n",avctx->extradata_size);
01040         if (avctx->extradata_size >= 8){
01041             q->cookversion = bytestream_get_be32(&edata_ptr);
01042             q->samples_per_frame =  bytestream_get_be16(&edata_ptr);
01043             q->subbands = bytestream_get_be16(&edata_ptr);
01044         }
01045         if (avctx->extradata_size >= 16){
01046             bytestream_get_be32(&edata_ptr);    //Unknown unused
01047             q->js_subband_start = bytestream_get_be16(&edata_ptr);
01048             q->js_vlc_bits = bytestream_get_be16(&edata_ptr);
01049         }
01