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