libavcodec/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 Libav.
00007  *
00008  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
00020  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00021  */
00022 
00045 #include "libavutil/lfg.h"
00046 #include "avcodec.h"
00047 #include "get_bits.h"
00048 #include "dsputil.h"
00049 #include "bytestream.h"
00050 #include "fft.h"
00051 #include "libavutil/audioconvert.h"
00052 #include "sinewin.h"
00053 
00054 #include "cookdata.h"
00055 
00056 /* the different Cook versions */
00057 #define MONO            0x1000001
00058 #define STEREO          0x1000002
00059 #define JOINT_STEREO    0x1000003
00060 #define MC_COOK         0x2000000   // multichannel Cook, not supported
00061 
00062 #define SUBBAND_SIZE    20
00063 #define MAX_SUBPACKETS   5
00064 
00065 typedef struct {
00066     int *now;
00067     int *previous;
00068 } cook_gains;
00069 
00070 typedef struct {
00071     int                 ch_idx;
00072     int                 size;
00073     int                 num_channels;
00074     int                 cookversion;
00075     int                 samples_per_frame;
00076     int                 subbands;
00077     int                 js_subband_start;
00078     int                 js_vlc_bits;
00079     int                 samples_per_channel;
00080     int                 log2_numvector_size;
00081     unsigned int        channel_mask;
00082     VLC                 ccpl;                 
00083     int                 joint_stereo;
00084     int                 bits_per_subpacket;
00085     int                 bits_per_subpdiv;
00086     int                 total_subbands;
00087     int                 numvector_size;       
00088 
00089     float               mono_previous_buffer1[1024];
00090     float               mono_previous_buffer2[1024];
00092     cook_gains          gains1;
00093     cook_gains          gains2;
00094     int                 gain_1[9];
00095     int                 gain_2[9];
00096     int                 gain_3[9];
00097     int                 gain_4[9];
00098 } COOKSubpacket;
00099 
00100 typedef struct cook {
00101     /*
00102      * The following 5 functions provide the lowlevel arithmetic on
00103      * the internal audio buffers.
00104      */
00105     void (*scalar_dequant)(struct cook *q, int index, int quant_index,
00106                            int *subband_coef_index, int *subband_coef_sign,
00107                            float *mlt_p);
00108 
00109     void (*decouple)(struct cook *q,
00110                      COOKSubpacket *p,
00111                      int subband,
00112                      float f1, float f2,
00113                      float *decode_buffer,
00114                      float *mlt_buffer1, float *mlt_buffer2);
00115 
00116     void (*imlt_window)(struct cook *q, float *buffer1,
00117                         cook_gains *gains_ptr, float *previous_buffer);
00118 
00119     void (*interpolate)(struct cook *q, float *buffer,
00120                         int gain_index, int gain_index_next);
00121 
00122     void (*saturate_output)(struct cook *q, int chan, float *out);
00123 
00124     AVCodecContext*     avctx;
00125     AVFrame             frame;
00126     GetBitContext       gb;
00127     /* stream data */
00128     int                 nb_channels;
00129     int                 bit_rate;
00130     int                 sample_rate;
00131     int                 num_vectors;
00132     int                 samples_per_channel;
00133     /* states */
00134     AVLFG               random_state;
00135     int                 discarded_packets;
00136 
00137     /* transform data */
00138     FFTContext          mdct_ctx;
00139     float*              mlt_window;
00140 
00141     /* VLC data */
00142     VLC                 envelope_quant_index[13];
00143     VLC                 sqvh[7];          // scalar quantization
00144 
00145     /* generatable tables and related variables */
00146     int                 gain_size_factor;
00147     float               gain_table[23];
00148 
00149     /* data buffers */
00150 
00151     uint8_t*            decoded_bytes_buffer;
00152     DECLARE_ALIGNED(32, float, mono_mdct_output)[2048];
00153     float               decode_buffer_1[1024];
00154     float               decode_buffer_2[1024];
00155     float               decode_buffer_0[1060]; /* static allocation for joint decode */
00156 
00157     const float         *cplscales[5];
00158     int                 num_subpackets;
00159     COOKSubpacket       subpacket[MAX_SUBPACKETS];
00160 } COOKContext;
00161 
00162 static float     pow2tab[127];
00163 static float rootpow2tab[127];
00164 
00165 /*************** init functions ***************/
00166 
00167 /* table generator */
00168 static av_cold void init_pow2table(void)
00169 {
00170     int i;
00171     for (i = -63; i < 64; i++) {
00172         pow2tab[63 + i] = pow(2, i);
00173         rootpow2tab[63 + i] = sqrt(pow(2, i));
00174     }
00175 }
00176 
00177 /* table generator */
00178 static av_cold void init_gain_table(COOKContext *q)
00179 {
00180     int i;
00181     q->gain_size_factor = q->samples_per_channel / 8;
00182     for (i = 0; i < 23; i++)
00183         q->gain_table[i] = pow(pow2tab[i + 52],
00184                                (1.0 / (double) q->gain_size_factor));
00185 }
00186 
00187 
00188 static av_cold int init_cook_vlc_tables(COOKContext *q)
00189 {
00190     int i, result;
00191 
00192     result = 0;
00193     for (i = 0; i < 13; i++) {
00194         result |= init_vlc(&q->envelope_quant_index[i], 9, 24,
00195                            envelope_quant_index_huffbits[i], 1, 1,
00196                            envelope_quant_index_huffcodes[i], 2, 2, 0);
00197     }
00198     av_log(q->avctx, AV_LOG_DEBUG, "sqvh VLC init\n");
00199     for (i = 0; i < 7; i++) {
00200         result |= init_vlc(&q->sqvh[i], vhvlcsize_tab[i], vhsize_tab[i],
00201                            cvh_huffbits[i], 1, 1,
00202                            cvh_huffcodes[i], 2, 2, 0);
00203     }
00204 
00205     for (i = 0; i < q->num_subpackets; i++) {
00206         if (q->subpacket[i].joint_stereo == 1) {
00207             result |= init_vlc(&q->subpacket[i].ccpl, 6, (1 << q->subpacket[i].js_vlc_bits) - 1,
00208                                ccpl_huffbits[q->subpacket[i].js_vlc_bits - 2], 1, 1,
00209                                ccpl_huffcodes[q->subpacket[i].js_vlc_bits - 2], 2, 2, 0);
00210             av_log(q->avctx, AV_LOG_DEBUG, "subpacket %i Joint-stereo VLC used.\n", i);
00211         }
00212     }
00213 
00214     av_log(q->avctx, AV_LOG_DEBUG, "VLC tables initialized.\n");
00215     return result;
00216 }
00217 
00218 static av_cold int init_cook_mlt(COOKContext *q)
00219 {
00220     int j, ret;
00221     int mlt_size = q->samples_per_channel;
00222 
00223     if ((q->mlt_window = av_malloc(mlt_size * sizeof(*q->mlt_window))) == 0)
00224         return AVERROR(ENOMEM);
00225 
00226     /* Initialize the MLT window: simple sine window. */
00227     ff_sine_window_init(q->mlt_window, mlt_size);
00228     for (j = 0; j < mlt_size; j++)
00229         q->mlt_window[j] *= sqrt(2.0 / q->samples_per_channel);
00230 
00231     /* Initialize the MDCT. */
00232     if ((ret = ff_mdct_init(&q->mdct_ctx, av_log2(mlt_size) + 1, 1, 1.0 / 32768.0))) {
00233         av_free(q->mlt_window);
00234         return ret;
00235     }
00236     av_log(q->avctx, AV_LOG_DEBUG, "MDCT initialized, order = %d.\n",
00237            av_log2(mlt_size) + 1);
00238 
00239     return 0;
00240 }
00241 
00242 static const float *maybe_reformat_buffer32(COOKContext *q, const float *ptr, int n)
00243 {
00244     if (1)
00245         return ptr;
00246 }
00247 
00248 static av_cold void init_cplscales_table(COOKContext *q)
00249 {
00250     int i;
00251     for (i = 0; i < 5; i++)
00252         q->cplscales[i] = maybe_reformat_buffer32(q, cplscales[i], (1 << (i + 2)) - 1);
00253 }
00254 
00255 /*************** init functions end ***********/
00256 
00257 #define DECODE_BYTES_PAD1(bytes) (3 - ((bytes) + 3) % 4)
00258 #define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
00259 
00280 static inline int decode_bytes(const uint8_t *inbuffer, uint8_t *out, int bytes)
00281 {
00282     static const uint32_t tab[4] = {
00283         AV_BE2NE32C(0x37c511f2), AV_BE2NE32C(0xf237c511),
00284         AV_BE2NE32C(0x11f237c5), AV_BE2NE32C(0xc511f237),
00285     };
00286     int i, off;
00287     uint32_t c;
00288     const uint32_t *buf;
00289     uint32_t *obuf = (uint32_t *) out;
00290     /* FIXME: 64 bit platforms would be able to do 64 bits at a time.
00291      * I'm too lazy though, should be something like
00292      * for (i = 0; i < bitamount / 64; i++)
00293      *     (int64_t) out[i] = 0x37c511f237c511f2 ^ av_be2ne64(int64_t) in[i]);
00294      * Buffer alignment needs to be checked. */
00295 
00296     off = (intptr_t) inbuffer & 3;
00297     buf = (const uint32_t *) (inbuffer - off);
00298     c = tab[off];
00299     bytes += 3 + off;
00300     for (i = 0; i < bytes / 4; i++)
00301         obuf[i] = c ^ buf[i];
00302 
00303     return off;
00304 }
00305 
00309 static av_cold int cook_decode_close(AVCodecContext *avctx)
00310 {
00311     int i;
00312     COOKContext *q = avctx->priv_data;
00313     av_log(avctx, AV_LOG_DEBUG, "Deallocating memory.\n");
00314 
00315     /* Free allocated memory buffers. */
00316     av_free(q->mlt_window);
00317     av_free(q->decoded_bytes_buffer);
00318 
00319     /* Free the transform. */
00320     ff_mdct_end(&q->mdct_ctx);
00321 
00322     /* Free the VLC tables. */
00323     for (i = 0; i < 13; i++)
00324         ff_free_vlc(&q->envelope_quant_index[i]);
00325     for (i = 0; i < 7; i++)
00326         ff_free_vlc(&q->sqvh[i]);
00327     for (i = 0; i < q->num_subpackets; i++)
00328         ff_free_vlc(&q->subpacket[i].ccpl);
00329 
00330     av_log(avctx, AV_LOG_DEBUG, "Memory deallocated.\n");
00331 
00332     return 0;
00333 }
00334 
00341 static void decode_gain_info(GetBitContext *gb, int *gaininfo)
00342 {
00343     int i, n;
00344 
00345     while (get_bits1(gb)) {
00346         /* NOTHING */
00347     }
00348 
00349     n = get_bits_count(gb) - 1;     // amount of elements*2 to update
00350 
00351     i = 0;
00352     while (n--) {
00353         int index = get_bits(gb, 3);
00354         int gain = get_bits1(gb) ? get_bits(gb, 4) - 7 : -1;
00355 
00356         while (i <= index)
00357             gaininfo[i++] = gain;
00358     }
00359     while (i <= 8)
00360         gaininfo[i++] = 0;
00361 }
00362 
00369 static int decode_envelope(COOKContext *q, COOKSubpacket *p,
00370                            int *quant_index_table)
00371 {
00372     int i, j, vlc_index;
00373 
00374     quant_index_table[0] = get_bits(&q->gb, 6) - 6; // This is used later in categorize
00375 
00376     for (i = 1; i < p->total_subbands; i++) {
00377         vlc_index = i;
00378         if (i >= p->js_subband_start * 2) {
00379             vlc_index -= p->js_subband_start;
00380         } else {
00381             vlc_index /= 2;
00382             if (vlc_index < 1)
00383                 vlc_index = 1;
00384         }
00385         if (vlc_index > 13)
00386             vlc_index = 13; // the VLC tables >13 are identical to No. 13
00387 
00388         j = get_vlc2(&q->gb, q->envelope_quant_index[vlc_index - 1].table,
00389                      q->envelope_quant_index[vlc_index - 1].bits, 2);
00390         quant_index_table[i] = quant_index_table[i - 1] + j - 12; // differential encoding
00391         if (quant_index_table[i] > 63 || quant_index_table[i] < -63) {
00392             av_log(q->avctx, AV_LOG_ERROR,
00393                    "Invalid quantizer %d at position %d, outside [-63, 63] range\n",
00394                    quant_index_table[i], i);
00395             return AVERROR_INVALIDDATA;
00396         }
00397     }
00398 
00399     return 0;
00400 }
00401 
00410 static void categorize(COOKContext *q, COOKSubpacket *p, int *quant_index_table,
00411                        int *category, int *category_index)
00412 {
00413     int exp_idx, bias, tmpbias1, tmpbias2, bits_left, num_bits, index, v, i, j;
00414     int exp_index2[102];
00415     int exp_index1[102];
00416 
00417     int tmp_categorize_array[128 * 2];
00418     int tmp_categorize_array1_idx = p->numvector_size;
00419     int tmp_categorize_array2_idx = p->numvector_size;
00420 
00421     bits_left = p->bits_per_subpacket - get_bits_count(&q->gb);
00422 
00423     if (bits_left > q->samples_per_channel) {
00424         bits_left = q->samples_per_channel +
00425                     ((bits_left - q->samples_per_channel) * 5) / 8;
00426         //av_log(q->avctx, AV_LOG_ERROR, "bits_left = %d\n",bits_left);
00427     }
00428 
00429     memset(&exp_index1,           0, sizeof(exp_index1));
00430     memset(&exp_index2,           0, sizeof(exp_index2));
00431     memset(&tmp_categorize_array, 0, sizeof(tmp_categorize_array));
00432 
00433     bias = -32;
00434 
00435     /* Estimate bias. */
00436     for (i = 32; i > 0; i = i / 2) {
00437         num_bits = 0;
00438         index    = 0;
00439         for (j = p->total_subbands; j > 0; j--) {
00440             exp_idx = av_clip((i - quant_index_table[index] + bias) / 2, 0, 7);
00441             index++;
00442             num_bits += expbits_tab[exp_idx];
00443         }
00444         if (num_bits >= bits_left - 32)
00445             bias += i;
00446     }
00447 
00448     /* Calculate total number of bits. */
00449     num_bits = 0;
00450     for (i = 0; i < p->total_subbands; i++) {
00451         exp_idx = av_clip((bias - quant_index_table[i]) / 2, 0, 7);
00452         num_bits += expbits_tab[exp_idx];
00453         exp_index1[i] = exp_idx;
00454         exp_index2[i] = exp_idx;
00455     }
00456     tmpbias1 = tmpbias2 = num_bits;
00457 
00458     for (j = 1; j < p->numvector_size; j++) {
00459         if (tmpbias1 + tmpbias2 > 2 * bits_left) {  /* ---> */
00460             int max = -999999;
00461             index = -1;
00462             for (i = 0; i < p->total_subbands; i++) {
00463                 if (exp_index1[i] < 7) {
00464                     v = (-2 * exp_index1[i]) - quant_index_table[i] + bias;
00465                     if (v >= max) {
00466                         max   = v;
00467                         index = i;
00468                     }
00469                 }
00470             }
00471             if (index == -1)
00472                 break;
00473             tmp_categorize_array[tmp_categorize_array1_idx++] = index;
00474             tmpbias1 -= expbits_tab[exp_index1[index]] -
00475                         expbits_tab[exp_index1[index] + 1];
00476             ++exp_index1[index];
00477         } else {  /* <--- */
00478             int min = 999999;
00479             index = -1;
00480             for (i = 0; i < p->total_subbands; i++) {
00481                 if (exp_index2[i] > 0) {
00482                     v = (-2 * exp_index2[i]) - quant_index_table[i] + bias;
00483                     if (v < min) {
00484                         min   = v;
00485                         index = i;
00486                     }
00487                 }
00488             }
00489             if (index == -1)
00490                 break;
00491             tmp_categorize_array[--tmp_categorize_array2_idx] = index;
00492             tmpbias2 -= expbits_tab[exp_index2[index]] -
00493                         expbits_tab[exp_index2[index] - 1];
00494             --exp_index2[index];
00495         }
00496     }
00497 
00498     for (i = 0; i < p->total_subbands; i++)
00499         category[i] = exp_index2[i];
00500 
00501     for (i = 0; i < p->numvector_size - 1; i++)
00502         category_index[i] = tmp_categorize_array[tmp_categorize_array2_idx++];
00503 }
00504 
00505 
00513 static inline void expand_category(COOKContext *q, int *category,
00514                                    int *category_index)
00515 {
00516     int i;
00517     for (i = 0; i < q->num_vectors; i++)
00518     {
00519         int idx = category_index[i];
00520         if (++category[idx] >= FF_ARRAY_ELEMS(dither_tab))
00521             --category[idx];
00522     }
00523 }
00524 
00535 static void scalar_dequant_float(COOKContext *q, int index, int quant_index,
00536                                  int *subband_coef_index, int *subband_coef_sign,
00537                                  float *mlt_p)
00538 {
00539     int i;
00540     float f1;
00541 
00542     for (i = 0; i < SUBBAND_SIZE; i++) {
00543         if (subband_coef_index[i]) {
00544             f1 = quant_centroid_tab[index][subband_coef_index[i]];
00545             if (subband_coef_sign[i])
00546                 f1 = -f1;
00547         } else {
00548             /* noise coding if subband_coef_index[i] == 0 */
00549             f1 = dither_tab[index];
00550             if (av_lfg_get(&q->random_state) < 0x80000000)
00551                 f1 = -f1;
00552         }
00553         mlt_p[i] = f1 * rootpow2tab[quant_index + 63];
00554     }
00555 }
00564 static int unpack_SQVH(COOKContext *q, COOKSubpacket *p, int category,
00565                        int *subband_coef_index, int *subband_coef_sign)
00566 {
00567     int i, j;
00568     int vlc, vd, tmp, result;
00569 
00570     vd = vd_tab[category];
00571     result = 0;
00572     for (i = 0; i < vpr_tab[category]; i++) {
00573         vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
00574         if (p->bits_per_subpacket < get_bits_count(&q->gb)) {
00575             vlc = 0;
00576             result = 1;
00577         }
00578         for (j = vd - 1; j >= 0; j--) {
00579             tmp = (vlc * invradix_tab[category]) / 0x100000;
00580             subband_coef_index[vd * i + j] = vlc - tmp * (kmax_tab[category] + 1);
00581             vlc = tmp;
00582         }
00583         for (j = 0; j < vd; j++) {
00584             if (subband_coef_index[i * vd + j]) {
00585                 if (get_bits_count(&q->gb) < p->bits_per_subpacket) {
00586                     subband_coef_sign[i * vd + j] = get_bits1(&q->gb);
00587                 } else {
00588                     result = 1;
00589                     subband_coef_sign[i * vd + j] = 0;
00590                 }
00591             } else {
00592                 subband_coef_sign[i * vd + j] = 0;
00593             }
00594         }
00595     }
00596     return result;
00597 }
00598 
00599 
00608 static void decode_vectors(COOKContext *q, COOKSubpacket *p, int *category,
00609                            int *quant_index_table, float *mlt_buffer)
00610 {
00611     /* A zero in this table means that the subband coefficient is
00612        random noise coded. */
00613     int subband_coef_index[SUBBAND_SIZE];
00614     /* A zero in this table means that the subband coefficient is a
00615        positive multiplicator. */
00616     int subband_coef_sign[SUBBAND_SIZE];
00617     int band, j;
00618     int index = 0;
00619 
00620     for (band = 0; band < p->total_subbands; band++) {
00621         index = category[band];
00622         if (category[band] < 7) {
00623             if (unpack_SQVH(q, p, category[band], subband_coef_index, subband_coef_sign)) {
00624                 index = 7;
00625                 for (j = 0; j < p->total_subbands; j++)
00626                     category[band + j] = 7;
00627             }
00628         }
00629         if (index >= 7) {
00630             memset(subband_coef_index, 0, sizeof(subband_coef_index));
00631             memset(subband_coef_sign,  0, sizeof(subband_coef_sign));
00632         }
00633         q->scalar_dequant(q, index, quant_index_table[band],
00634                           subband_coef_index, subband_coef_sign,
00635                           &mlt_buffer[band * SUBBAND_SIZE]);
00636     }
00637 
00638     /* FIXME: should this be removed, or moved into loop above? */
00639     if (p->total_subbands * SUBBAND_SIZE >= q->samples_per_channel)
00640         return;
00641 }
00642 
00643 
00650 static int mono_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer)
00651 {
00652     int category_index[128];
00653     int quant_index_table[102];
00654     int category[128];
00655     int res;
00656 
00657     memset(&category,       0, sizeof(category));
00658     memset(&category_index, 0, sizeof(category_index));
00659 
00660     if ((res = decode_envelope(q, p, quant_index_table)) < 0)
00661         return res;
00662     q->num_vectors = get_bits(&q->gb, p->log2_numvector_size);
00663     categorize(q, p, quant_index_table, category, category_index);
00664     expand_category(q, category, category_index);
00665     decode_vectors(q, p, category, quant_index_table, mlt_buffer);
00666 
00667     return 0;
00668 }
00669 
00670 
00679 static void interpolate_float(COOKContext *q, float *buffer,
00680                               int gain_index, int gain_index_next)
00681 {
00682     int i;
00683     float fc1, fc2;
00684     fc1 = pow2tab[gain_index + 63];
00685 
00686     if (gain_index == gain_index_next) {             // static gain
00687         for (i = 0; i < q->gain_size_factor; i++)
00688             buffer[i] *= fc1;
00689     } else {                                        // smooth gain
00690         fc2 = q->gain_table[11 + (gain_index_next - gain_index)];
00691         for (i = 0; i < q->gain_size_factor; i++) {
00692             buffer[i] *= fc1;
00693             fc1       *= fc2;
00694         }
00695     }
00696 }
00697 
00706 static void imlt_window_float(COOKContext *q, float *inbuffer,
00707                               cook_gains *gains_ptr, float *previous_buffer)
00708 {
00709     const float fc = pow2tab[gains_ptr->previous[0] + 63];
00710     int i;
00711     /* The weird thing here, is that the two halves of the time domain
00712      * buffer are swapped. Also, the newest data, that we save away for
00713      * next frame, has the wrong sign. Hence the subtraction below.
00714      * Almost sounds like a complex conjugate/reverse data/FFT effect.
00715      */
00716 
00717     /* Apply window and overlap */
00718     for (i = 0; i < q->samples_per_channel; i++)
00719         inbuffer[i] = inbuffer[i] * fc * q->mlt_window[i] -
00720                       previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
00721 }
00722 
00734 static void imlt_gain(COOKContext *q, float *inbuffer,
00735                       cook_gains *gains_ptr, float *previous_buffer)
00736 {
00737     float *buffer0 = q->mono_mdct_output;
00738     float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
00739     int i;
00740 
00741     /* Inverse modified discrete cosine transform */
00742     q->mdct_ctx.imdct_calc(&q->mdct_ctx, q->mono_mdct_output, inbuffer);
00743 
00744     q->imlt_window(q, buffer1, gains_ptr, previous_buffer);
00745 
00746     /* Apply gain profile */
00747     for (i = 0; i < 8; i++)
00748         if (gains_ptr->now[i] || gains_ptr->now[i + 1])
00749             q->interpolate(q, &buffer1[q->gain_size_factor * i],
00750                            gains_ptr->now[i], gains_ptr->now[i + 1]);
00751 
00752     /* Save away the current to be previous block. */
00753     memcpy(previous_buffer, buffer0,
00754            q->samples_per_channel * sizeof(*previous_buffer));
00755 }
00756 
00757 
00765 static void decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)
00766 {
00767     int i;
00768     int vlc    = get_bits1(&q->gb);
00769     int start  = cplband[p->js_subband_start];
00770     int end    = cplband[p->subbands - 1];
00771     int length = end - start + 1;
00772 
00773     if (start > end)
00774         return;
00775 
00776     if (vlc)
00777         for (i = 0; i < length; i++)
00778             decouple_tab[start + i] = get_vlc2(&q->gb, p->ccpl.table, p->ccpl.bits, 2);
00779     else
00780         for (i = 0; i < length; i++)
00781             decouple_tab[start + i] = get_bits(&q->gb, p->js_vlc_bits);
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                            COOKSubpacket *p,
00797                            int subband,
00798                            float f1, float f2,
00799                            float *decode_buffer,
00800                            float *mlt_buffer1, float *mlt_buffer2)
00801 {
00802     int j, tmp_idx;
00803     for (j = 0; j < SUBBAND_SIZE; j++) {
00804         tmp_idx = ((p->js_subband_start + subband) * SUBBAND_SIZE) + j;
00805         mlt_buffer1[SUBBAND_SIZE * subband + j] = f1 * decode_buffer[tmp_idx];
00806         mlt_buffer2[SUBBAND_SIZE * subband + j] = f2 * decode_buffer[tmp_idx];
00807     }
00808 }
00809 
00817 static int joint_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer1,
00818                         float *mlt_buffer2)
00819 {
00820     int i, j, res;
00821     int decouple_tab[SUBBAND_SIZE];
00822     float *decode_buffer = q->decode_buffer_0;
00823     int idx, cpl_tmp;
00824     float f1, f2;
00825     const float *cplscale;
00826 
00827     memset(decouple_tab, 0, sizeof(decouple_tab));
00828     memset(decode_buffer, 0, sizeof(q->decode_buffer_0));
00829 
00830     /* Make sure the buffers are zeroed out. */
00831     memset(mlt_buffer1, 0, 1024 * sizeof(*mlt_buffer1));
00832     memset(mlt_buffer2, 0, 1024 * sizeof(*mlt_buffer2));
00833     decouple_info(q, p, decouple_tab);
00834     if ((res = mono_decode(q, p, decode_buffer)) < 0)
00835         return res;
00836 
00837     /* The two channels are stored interleaved in decode_buffer. */
00838     for (i = 0; i < p->js_subband_start; i++) {
00839         for (j = 0; j < SUBBAND_SIZE; j++) {
00840             mlt_buffer1[i * 20 + j] = decode_buffer[i * 40 + j];
00841             mlt_buffer2[i * 20 + j] = decode_buffer[i * 40 + 20 + j];
00842         }
00843     }
00844 
00845     /* When we reach js_subband_start (the higher frequencies)
00846        the coefficients are stored in a coupling scheme. */
00847     idx = (1 << p->js_vlc_bits) - 1;
00848     for (i = p->js_subband_start; i < p->subbands; i++) {
00849         cpl_tmp = cplband[i];
00850         idx -= decouple_tab[cpl_tmp];
00851         cplscale = q->cplscales[p->js_vlc_bits - 2];  // choose decoupler table
00852         f1 = cplscale[decouple_tab[cpl_tmp] + 1];
00853         f2 = cplscale[idx];
00854         q->decouple(q, p, i, f1, f2, decode_buffer, mlt_buffer1, mlt_buffer2);
00855         idx = (1 << p->js_vlc_bits) - 1;
00856     }
00857 
00858     return 0;
00859 }
00860 
00869 static inline void decode_bytes_and_gain(COOKContext *q, COOKSubpacket *p,
00870                                          const uint8_t *inbuffer,
00871                                          cook_gains *gains_ptr)
00872 {
00873     int offset;
00874 
00875     offset = decode_bytes(inbuffer, q->decoded_bytes_buffer,
00876                           p->bits_per_subpacket / 8);
00877     init_get_bits(&q->gb, q->decoded_bytes_buffer + offset,
00878                   p->bits_per_subpacket);
00879     decode_gain_info(&q->gb, gains_ptr->now);
00880 
00881     /* Swap current and previous gains */
00882     FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
00883 }
00884 
00892 static void saturate_output_float(COOKContext *q, int chan, float *out)
00893 {
00894     int j;
00895     float *output = q->mono_mdct_output + q->samples_per_channel;
00896     for (j = 0; j < q->samples_per_channel; j++) {
00897         out[chan + q->nb_channels * j] = av_clipf(output[j], -1.0, 1.0);
00898     }
00899 }
00900 
00913 static inline void mlt_compensate_output(COOKContext *q, float *decode_buffer,
00914                                          cook_gains *gains_ptr, float *previous_buffer,
00915                                          float *out, int chan)
00916 {
00917     imlt_gain(q, decode_buffer, gains_ptr, previous_buffer);
00918     if (out)
00919         q->saturate_output(q, chan, out);
00920 }
00921 
00922 
00931 static int decode_subpacket(COOKContext *q, COOKSubpacket *p,
00932                             const uint8_t *inbuffer, float *outbuffer)
00933 {
00934     int sub_packet_size = p->size;
00935     int res;
00936     /* packet dump */
00937     // for (i = 0; i < sub_packet_size ; i++)
00938     //     av_log(q->avctx, AV_LOG_ERROR, "%02x", inbuffer[i]);
00939     // av_log(q->avctx, AV_LOG_ERROR, "\n");
00940     memset(q->decode_buffer_1, 0, sizeof(q->decode_buffer_1));
00941     decode_bytes_and_gain(q, p, inbuffer, &p->gains1);
00942 
00943     if (p->joint_stereo) {
00944         if ((res = joint_decode(q, p, q->decode_buffer_1, q->decode_buffer_2)) < 0)
00945             return res;
00946     } else {
00947         if ((res = mono_decode(q, p, q->decode_buffer_1)) < 0)
00948             return res;
00949 
00950         if (p->num_channels == 2) {
00951             decode_bytes_and_gain(q, p, inbuffer + sub_packet_size / 2, &p->gains2);
00952             if ((res = mono_decode(q, p, q->decode_buffer_2)) < 0)
00953                 return res;
00954         }
00955     }
00956 
00957     mlt_compensate_output(q, q->decode_buffer_1, &p->gains1,
00958                           p->mono_previous_buffer1, outbuffer, p->ch_idx);
00959 
00960     if (p->num_channels == 2)
00961         if (p->joint_stereo)
00962             mlt_compensate_output(q, q->decode_buffer_2, &p->gains1,
00963                                   p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
00964         else
00965             mlt_compensate_output(q, q->decode_buffer_2, &p->gains2,
00966                                   p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
00967 
00968     return 0;
00969 }
00970 
00971 
00977 static int cook_decode_frame(AVCodecContext *avctx, void *data,
00978                              int *got_frame_ptr, AVPacket *avpkt)
00979 {
00980     const uint8_t *buf = avpkt->data;
00981     int buf_size = avpkt->size;
00982     COOKContext *q = avctx->priv_data;
00983     float *samples = NULL;
00984     int i, ret;
00985     int offset = 0;
00986     int chidx = 0;
00987 
00988     if (buf_size < avctx->block_align)
00989         return buf_size;
00990 
00991     /* get output buffer */
00992     if (q->discarded_packets >= 2) {
00993         q->frame.nb_samples = q->samples_per_channel;
00994         if ((ret = avctx->get_buffer(avctx, &q->frame)) < 0) {
00995             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00996             return ret;
00997         }
00998         samples = (float *) q->frame.data[0];
00999     }
01000 
01001     /* estimate subpacket sizes */
01002     q->subpacket[0].size = avctx->block_align;
01003 
01004     for (i = 1; i < q->num_subpackets; i++) {
01005         q->subpacket[i].size = 2 * buf[avctx->block_align - q->num_subpackets + i];
01006         q->subpacket[0].size -= q->subpacket[i].size + 1;
01007         if (q->subpacket[0].size < 0) {
01008             av_log(avctx, AV_LOG_DEBUG,
01009                    "frame subpacket size total > avctx->block_align!\n");
01010             return AVERROR_INVALIDDATA;
01011         }
01012     }
01013 
01014     /* decode supbackets */
01015     for (i = 0; i < q->num_subpackets; i++) {
01016         q->subpacket[i].bits_per_subpacket = (q->subpacket[i].size * 8) >>
01017                                               q->subpacket[i].bits_per_subpdiv;
01018         q->subpacket[i].ch_idx = chidx;
01019         av_log(avctx, AV_LOG_DEBUG,
01020                "subpacket[%i] size %i js %i %i block_align %i\n",
01021                i, q->subpacket[i].size, q->subpacket[i].joint_stereo, offset,
01022                avctx->block_align);
01023 
01024         if ((ret = decode_subpacket(q, &q->subpacket[i], buf + offset, samples)) < 0)
01025             return ret;
01026         offset += q->subpacket[i].size;
01027         chidx += q->subpacket[i].num_channels;
01028         av_log(avctx, AV_LOG_DEBUG, "subpacket[%i] %i %i\n",
01029                i, q->subpacket[i].size * 8, get_bits_count(&q->gb));
01030     }
01031 
01032     /* Discard the first two frames: no valid audio. */
01033     if (q->discarded_packets < 2) {
01034         q->discarded_packets++;
01035         *got_frame_ptr = 0;
01036         return avctx->block_align;
01037     }
01038 
01039     *got_frame_ptr    = 1;
01040     *(AVFrame *) data = q->frame;
01041 
01042     return avctx->block_align;
01043 }
01044 
01045 #ifdef DEBUG
01046 static void dump_cook_context(COOKContext *q)
01047 {
01048     //int i=0;
01049 #define PRINT(a, b) av_log(q->avctx, AV_LOG_ERROR, " %s = %d\n", a, b);
01050     av_log(q->avctx, AV_LOG_ERROR, "COOKextradata\n");
01051     av_log(q->avctx, AV_LOG_ERROR, "cookversion=%x\n", q->subpacket[0].cookversion);
01052     if (q->subpacket[0].cookversion > STEREO) {
01053         PRINT("js_subband_start", q->subpacket[0].js_subband_start);
01054         PRINT("js_vlc_bits", q->subpacket[0].js_vlc_bits);
01055     }
01056     av_log(q->avctx, AV_LOG_ERROR, "COOKContext\n");
01057     PRINT("nb_channels", q->nb_channels);
01058     PRINT("bit_rate", q->bit_rate);
01059     PRINT("sample_rate", q->sample_rate);
01060     PRINT("samples_per_channel", q->subpacket[0].samples_per_channel);
01061     PRINT("samples_per_frame", q->subpacket[0].samples_per_frame);
01062     PRINT("subbands", q->subpacket[0].subbands);
01063     PRINT("js_subband_start", q->subpacket[0].js_subband_start);
01064     PRINT("log2_numvector_size", q->subpacket[0].log2_numvector_size);
01065     PRINT("numvector_size", q->subpacket[0].numvector_size);
01066     PRINT("total_subbands", q->subpacket[0].total_subbands);
01067 }
01068 #endif
01069 
01070 static av_cold int cook_count_channels(unsigned int mask)
01071 {
01072     int i;
01073     int channels = 0;
01074     for (i = 0; i < 32; i++)
01075         if (mask & (1 << i))
01076             ++channels;
01077     return channels;
01078 }
01079 
01085 static av_cold int cook_decode_init(AVCodecContext *avctx)
01086 {
01087     COOKContext *q = avctx->priv_data;
01088     const uint8_t *edata_ptr = avctx->extradata;
01089     const uint8_t *edata_ptr_end = edata_ptr + avctx->extradata_size;
01090     int extradata_size = avctx->extradata_size;
01091     int s = 0;
01092     unsigned int channel_mask = 0;
01093     int ret;
01094     q->avctx = avctx;
01095 
01096     /* Take care of the codec specific extradata. */
01097     if (extradata_size <= 0) {
01098         av_log(avctx, AV_LOG_ERROR, "Necessary extradata missing!\n");
01099         return AVERROR_INVALIDDATA;
01100     }
01101     av_log(avctx, AV_LOG_DEBUG, "codecdata_length=%d\n", avctx->extradata_size);
01102 
01103     /* Take data from the AVCodecContext (RM container). */
01104     q->sample_rate = avctx->sample_rate;
01105     q->nb_channels = avctx->channels;
01106     q->bit_rate = avctx->bit_rate;
01107     if (!q->nb_channels) {
01108         av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
01109         return AVERROR_INVALIDDATA;
01110     }
01111 
01112     /* Initialize RNG. */
01113     av_lfg_init(&q->random_state, 0);
01114 
01115     while (edata_ptr < edata_ptr_end) {
01116         /* 8 for mono, 16 for stereo, ? for multichannel
01117            Swap to right endianness so we don't need to care later on. */
01118         if (extradata_size >= 8) {
01119             q->subpacket[s].cookversion = bytestream_get_be32(&edata_ptr);
01120             q->subpacket[s].samples_per_frame = bytestream_get_be16(&edata_ptr);
01121             q->subpacket[s].subbands = bytestream_get_be16(&edata_ptr);
01122             extradata_size -= 8;
01123         }
01124         if (extradata_size >= 8) {
01125             bytestream_get_be32(&edata_ptr);    // Unknown unused
01126             q->subpacket[s].js_subband_start = bytestream_get_be16(&edata_ptr);
01127             q->subpacket[s].js_vlc_bits = bytestream_get_be16(&edata_ptr);
01128             extradata_size -= 8;
01129         }
01130 
01131         /* Initialize extradata related variables. */
01132         q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame / q->nb_channels;
01133         q->subpacket[s].bits_per_subpacket = avctx->block_align * 8;
01134 
01135         /* Initialize default data states. */
01136         q->subpacket[s].log2_numvector_size = 5;
01137         q->subpacket[s].total_subbands = q->subpacket[s].subbands;
01138         q->subpacket[s].num_channels = 1;
01139 
01140         /* Initialize version-dependent variables */
01141 
01142         av_log(avctx, AV_LOG_DEBUG, "subpacket[%i].cookversion=%x\n", s,
01143                q->subpacket[s].cookversion);
01144         q->subpacket[s].joint_stereo = 0;
01145         switch (q->subpacket[s].cookversion) {
01146         case MONO:
01147             if (q->nb_channels != 1) {
01148                 av_log_ask_for_sample(avctx, "Container channels != 1.\n");
01149                 return AVERROR_PATCHWELCOME;
01150             }
01151             av_log(avctx, AV_LOG_DEBUG, "MONO\n");
01152             break;
01153         case STEREO:
01154             if (q->nb_channels != 1) {
01155                 q->subpacket[s].bits_per_subpdiv = 1;
01156                 q->subpacket[s].num_channels = 2;
01157             }
01158             av_log(avctx, AV_LOG_DEBUG, "STEREO\n");
01159             break;
01160         case JOINT_STEREO:
01161             if (q->nb_channels != 2) {
01162                 av_log_ask_for_sample(avctx, "Container channels != 2.\n");
01163                 return AVERROR_PATCHWELCOME;
01164             }
01165             av_log(avctx, AV_LOG_DEBUG, "JOINT_STEREO\n");
01166             if (avctx->extradata_size >= 16) {
01167                 q->subpacket[s].total_subbands = q->subpacket[s].subbands +
01168                                                  q->subpacket[s].js_subband_start;
01169                 q->subpacket[s].joint_stereo = 1;
01170                 q->subpacket[s].num_channels = 2;
01171             }
01172             if (q->subpacket[s].samples_per_channel > 256) {
01173                 q->subpacket[s].log2_numvector_size = 6;
01174             }
01175             if (q->subpacket[s].samples_per_channel > 512) {
01176                 q->subpacket[s].log2_numvector_size = 7;
01177             }
01178             break;
01179         case MC_COOK:
01180             av_log(avctx, AV_LOG_DEBUG, "MULTI_CHANNEL\n");
01181             if (extradata_size >= 4)
01182                 channel_mask |= q->subpacket[s].channel_mask = bytestream_get_be32(&edata_ptr);
01183 
01184             if (cook_count_channels(q->subpacket[s].channel_mask) > 1) {
01185                 q->subpacket[s].total_subbands = q->subpacket[s].subbands +
01186                                                  q->subpacket[s].js_subband_start;
01187                 q->subpacket[s].joint_stereo = 1;
01188                 q->subpacket[s].num_channels = 2;
01189                 q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame >> 1;
01190 
01191                 if (q->subpacket[s].samples_per_channel > 256) {
01192                     q->subpacket[s].log2_numvector_size = 6;
01193                 }
01194                 if (q->subpacket[s].samples_per_channel > 512) {
01195                     q->subpacket[s].log2_numvector_size = 7;
01196                 }
01197             } else
01198                 q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame;
01199 
01200             break;
01201         default:
01202             av_log_ask_for_sample(avctx, "Unknown Cook version.\n");
01203             return AVERROR_PATCHWELCOME;
01204         }
01205 
01206         if (s > 1 && q->subpacket[s].samples_per_channel != q->samples_per_channel) {
01207             av_log(avctx, AV_LOG_ERROR, "different number of samples per channel!\n");
01208             return AVERROR_INVALIDDATA;
01209         } else
01210             q->samples_per_channel = q->subpacket[0].samples_per_channel;
01211 
01212 
01213         /* Initialize variable relations */
01214         q->subpacket[s].numvector_size = (1 << q->subpacket[s].log2_numvector_size);
01215 
01216         /* Try to catch some obviously faulty streams, othervise it might be exploitable */
01217         if (q->subpacket[s].total_subbands > 53) {
01218             av_log_ask_for_sample(avctx, "total_subbands > 53\n");
01219             return AVERROR_PATCHWELCOME;
01220         }
01221 
01222         if ((q->subpacket[s].js_vlc_bits > 6) ||
01223             (q->subpacket[s].js_vlc_bits < 2 * q->subpacket[s].joint_stereo)) {
01224             av_log(avctx, AV_LOG_ERROR, "js_vlc_bits = %d, only >= %d and <= 6 allowed!\n",
01225                    q->subpacket[s].js_vlc_bits, 2 * q->subpacket[s].joint_stereo);
01226             return AVERROR_INVALIDDATA;
01227         }
01228 
01229         if (q->subpacket[s].subbands > 50) {
01230             av_log_ask_for_sample(avctx, "subbands > 50\n");
01231             return AVERROR_PATCHWELCOME;
01232         }
01233         q->subpacket[s].gains1.now      = q->subpacket[s].gain_1;
01234         q->subpacket[s].gains1.previous = q->subpacket[s].gain_2;
01235         q->subpacket[s].gains2.now      = q->subpacket[s].gain_3;
01236         q->subpacket[s].gains2.previous = q->subpacket[s].gain_4;
01237 
01238         q->num_subpackets++;
01239         s++;
01240         if (s > MAX_SUBPACKETS) {
01241             av_log_ask_for_sample(avctx, "Too many subpackets > 5\n");
01242             return AVERROR_PATCHWELCOME;
01243         }
01244     }
01245     /* Generate tables */
01246     init_pow2table();
01247     init_gain_table(q);
01248     init_cplscales_table(q);
01249 
01250     if ((ret = init_cook_vlc_tables(q)))
01251         return ret;
01252 
01253 
01254     if (avctx->block_align >= UINT_MAX / 2)
01255         return AVERROR(EINVAL);
01256 
01257     /* Pad the databuffer with:
01258        DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
01259        FF_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */
01260     q->decoded_bytes_buffer =
01261         av_mallocz(avctx->block_align
01262                    + DECODE_BYTES_PAD1(avctx->block_align)
01263                    + FF_INPUT_BUFFER_PADDING_SIZE);
01264     if (q->decoded_bytes_buffer == NULL)
01265         return AVERROR(ENOMEM);
01266 
01267     /* Initialize transform. */
01268     if ((ret = init_cook_mlt(q)))
01269         return ret;
01270 
01271     /* Initialize COOK signal arithmetic handling */
01272     if (1) {
01273         q->scalar_dequant  = scalar_dequant_float;
01274         q->decouple        = decouple_float;
01275         q->imlt_window     = imlt_window_float;
01276         q->interpolate     = interpolate_float;
01277         q->saturate_output = saturate_output_float;
01278     }
01279 
01280     /* Try to catch some obviously faulty streams, othervise it might be exploitable */
01281     if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512)
01282                 || (q->samples_per_channel == 1024)) {
01283     } else {
01284         av_log_ask_for_sample(avctx,
01285                               "unknown amount of samples_per_channel = %d\n",
01286                               q->samples_per_channel);
01287         return AVERROR_PATCHWELCOME;
01288     }
01289 
01290     avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
01291     if (channel_mask)
01292         avctx->channel_layout = channel_mask;
01293     else
01294         avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
01295 
01296     avcodec_get_frame_defaults(&q->frame);
01297     avctx->coded_frame = &q->frame;
01298 
01299 #ifdef DEBUG
01300     dump_cook_context(q);
01301 #endif
01302     return 0;
01303 }
01304 
01305 AVCodec ff_cook_decoder = {
01306     .name           = "cook",
01307     .type           = AVMEDIA_TYPE_AUDIO,
01308     .id             = CODEC_ID_COOK,
01309     .priv_data_size = sizeof(COOKContext),
01310     .init           = cook_decode_init,
01311     .close          = cook_decode_close,
01312     .decode         = cook_decode_frame,
01313     .capabilities   = CODEC_CAP_DR1,
01314     .long_name      = NULL_IF_CONFIG_SMALL("COOK"),
01315 };