• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • File List
  • Globals

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         free_vlc(&q->envelope_quant_index[i]);
00325     for (i = 0; i < 7; i++)
00326         free_vlc(&q->sqvh[i]);
00327     for (i = 0; i < q->num_subpackets; i++)
00328         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 void 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     }
00392 }
00393 
00402 static void categorize(COOKContext *q, COOKSubpacket *p, int *quant_index_table,
00403                        int *category, int *category_index)
00404 {
00405     int exp_idx, bias, tmpbias1, tmpbias2, bits_left, num_bits, index, v, i, j;
00406     int exp_index2[102];
00407     int exp_index1[102];
00408 
00409     int tmp_categorize_array[128 * 2];
00410     int tmp_categorize_array1_idx = p->numvector_size;
00411     int tmp_categorize_array2_idx = p->numvector_size;
00412 
00413     bits_left = p->bits_per_subpacket - get_bits_count(&q->gb);
00414 
00415     if (bits_left > q->samples_per_channel) {
00416         bits_left = q->samples_per_channel +
00417                     ((bits_left - q->samples_per_channel) * 5) / 8;
00418         //av_log(q->avctx, AV_LOG_ERROR, "bits_left = %d\n",bits_left);
00419     }
00420 
00421     memset(&exp_index1,           0, sizeof(exp_index1));
00422     memset(&exp_index2,           0, sizeof(exp_index2));
00423     memset(&tmp_categorize_array, 0, sizeof(tmp_categorize_array));
00424 
00425     bias = -32;
00426 
00427     /* Estimate bias. */
00428     for (i = 32; i > 0; i = i / 2) {
00429         num_bits = 0;
00430         index    = 0;
00431         for (j = p->total_subbands; j > 0; j--) {
00432             exp_idx = av_clip((i - quant_index_table[index] + bias) / 2, 0, 7);
00433             index++;
00434             num_bits += expbits_tab[exp_idx];
00435         }
00436         if (num_bits >= bits_left - 32)
00437             bias += i;
00438     }
00439 
00440     /* Calculate total number of bits. */
00441     num_bits = 0;
00442     for (i = 0; i < p->total_subbands; i++) {
00443         exp_idx = av_clip((bias - quant_index_table[i]) / 2, 0, 7);
00444         num_bits += expbits_tab[exp_idx];
00445         exp_index1[i] = exp_idx;
00446         exp_index2[i] = exp_idx;
00447     }
00448     tmpbias1 = tmpbias2 = num_bits;
00449 
00450     for (j = 1; j < p->numvector_size; j++) {
00451         if (tmpbias1 + tmpbias2 > 2 * bits_left) {  /* ---> */
00452             int max = -999999;
00453             index = -1;
00454             for (i = 0; i < p->total_subbands; i++) {
00455                 if (exp_index1[i] < 7) {
00456                     v = (-2 * exp_index1[i]) - quant_index_table[i] + bias;
00457                     if (v >= max) {
00458                         max   = v;
00459                         index = i;
00460                     }
00461                 }
00462             }
00463             if (index == -1)
00464                 break;
00465             tmp_categorize_array[tmp_categorize_array1_idx++] = index;
00466             tmpbias1 -= expbits_tab[exp_index1[index]] -
00467                         expbits_tab[exp_index1[index] + 1];
00468             ++exp_index1[index];
00469         } else {  /* <--- */
00470             int min = 999999;
00471             index = -1;
00472             for (i = 0; i < p->total_subbands; i++) {
00473                 if (exp_index2[i] > 0) {
00474                     v = (-2 * exp_index2[i]) - quant_index_table[i] + bias;
00475                     if (v < min) {
00476                         min   = v;
00477                         index = i;
00478                     }
00479                 }
00480             }
00481             if (index == -1)
00482                 break;
00483             tmp_categorize_array[--tmp_categorize_array2_idx] = index;
00484             tmpbias2 -= expbits_tab[exp_index2[index]] -
00485                         expbits_tab[exp_index2[index] - 1];
00486             --exp_index2[index];
00487         }
00488     }
00489 
00490     for (i = 0; i < p->total_subbands; i++)
00491         category[i] = exp_index2[i];
00492 
00493     for (i = 0; i < p->numvector_size - 1; i++)
00494         category_index[i] = tmp_categorize_array[tmp_categorize_array2_idx++];
00495 }
00496 
00497 
00505 static inline void expand_category(COOKContext *q, int *category,
00506                                    int *category_index)
00507 {
00508     int i;
00509     for (i = 0; i < q->num_vectors; i++)
00510         ++category[category_index[i]];
00511 }
00512 
00523 static void scalar_dequant_float(COOKContext *q, int index, int quant_index,
00524                                  int *subband_coef_index, int *subband_coef_sign,
00525                                  float *mlt_p)
00526 {
00527     int i;
00528     float f1;
00529 
00530     for (i = 0; i < SUBBAND_SIZE; i++) {
00531         if (subband_coef_index[i]) {
00532             f1 = quant_centroid_tab[index][subband_coef_index[i]];
00533             if (subband_coef_sign[i])
00534                 f1 = -f1;
00535         } else {
00536             /* noise coding if subband_coef_index[i] == 0 */
00537             f1 = dither_tab[index];
00538             if (av_lfg_get(&q->random_state) < 0x80000000)
00539                 f1 = -f1;
00540         }
00541         mlt_p[i] = f1 * rootpow2tab[quant_index + 63];
00542     }
00543 }
00552 static int unpack_SQVH(COOKContext *q, COOKSubpacket *p, int category,
00553                        int *subband_coef_index, int *subband_coef_sign)
00554 {
00555     int i, j;
00556     int vlc, vd, tmp, result;
00557 
00558     vd = vd_tab[category];
00559     result = 0;
00560     for (i = 0; i < vpr_tab[category]; i++) {
00561         vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
00562         if (p->bits_per_subpacket < get_bits_count(&q->gb)) {
00563             vlc = 0;
00564             result = 1;
00565         }
00566         for (j = vd - 1; j >= 0; j--) {
00567             tmp = (vlc * invradix_tab[category]) / 0x100000;
00568             subband_coef_index[vd * i + j] = vlc - tmp * (kmax_tab[category] + 1);
00569             vlc = tmp;
00570         }
00571         for (j = 0; j < vd; j++) {
00572             if (subband_coef_index[i * vd + j]) {
00573                 if (get_bits_count(&q->gb) < p->bits_per_subpacket) {
00574                     subband_coef_sign[i * vd + j] = get_bits1(&q->gb);
00575                 } else {
00576                     result = 1;
00577                     subband_coef_sign[i * vd + j] = 0;
00578                 }
00579             } else {
00580                 subband_coef_sign[i * vd + j] = 0;
00581             }
00582         }
00583     }
00584     return result;
00585 }
00586 
00587 
00596 static void decode_vectors(COOKContext *q, COOKSubpacket *p, int *category,
00597                            int *quant_index_table, float *mlt_buffer)
00598 {
00599     /* A zero in this table means that the subband coefficient is
00600        random noise coded. */
00601     int subband_coef_index[SUBBAND_SIZE];
00602     /* A zero in this table means that the subband coefficient is a
00603        positive multiplicator. */
00604     int subband_coef_sign[SUBBAND_SIZE];
00605     int band, j;
00606     int index = 0;
00607 
00608     for (band = 0; band < p->total_subbands; band++) {
00609         index = category[band];
00610         if (category[band] < 7) {
00611             if (unpack_SQVH(q, p, category[band], subband_coef_index, subband_coef_sign)) {
00612                 index = 7;
00613                 for (j = 0; j < p->total_subbands; j++)
00614                     category[band + j] = 7;
00615             }
00616         }
00617         if (index >= 7) {
00618             memset(subband_coef_index, 0, sizeof(subband_coef_index));
00619             memset(subband_coef_sign,  0, sizeof(subband_coef_sign));
00620         }
00621         q->scalar_dequant(q, index, quant_index_table[band],
00622                           subband_coef_index, subband_coef_sign,
00623                           &mlt_buffer[band * SUBBAND_SIZE]);
00624     }
00625 
00626     /* FIXME: should this be removed, or moved into loop above? */
00627     if (p->total_subbands * SUBBAND_SIZE >= q->samples_per_channel)
00628         return;
00629 }
00630 
00631 
00638 static void mono_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer)
00639 {
00640     int category_index[128];
00641     int quant_index_table[102];
00642     int category[128];
00643 
00644     memset(&category,       0, sizeof(category));
00645     memset(&category_index, 0, sizeof(category_index));
00646 
00647     decode_envelope(q, p, quant_index_table);
00648     q->num_vectors = get_bits(&q->gb, p->log2_numvector_size);
00649     categorize(q, p, quant_index_table, category, category_index);
00650     expand_category(q, category, category_index);
00651     decode_vectors(q, p, category, quant_index_table, mlt_buffer);
00652 }
00653 
00654 
00663 static void interpolate_float(COOKContext *q, float *buffer,
00664                               int gain_index, int gain_index_next)
00665 {
00666     int i;
00667     float fc1, fc2;
00668     fc1 = pow2tab[gain_index + 63];
00669 
00670     if (gain_index == gain_index_next) {             // static gain
00671         for (i = 0; i < q->gain_size_factor; i++)
00672             buffer[i] *= fc1;
00673     } else {                                        // smooth gain
00674         fc2 = q->gain_table[11 + (gain_index_next - gain_index)];
00675         for (i = 0; i < q->gain_size_factor; i++) {
00676             buffer[i] *= fc1;
00677             fc1       *= fc2;
00678         }
00679     }
00680 }
00681 
00690 static void imlt_window_float(COOKContext *q, float *inbuffer,
00691                               cook_gains *gains_ptr, float *previous_buffer)
00692 {
00693     const float fc = pow2tab[gains_ptr->previous[0] + 63];
00694     int i;
00695     /* The weird thing here, is that the two halves of the time domain
00696      * buffer are swapped. Also, the newest data, that we save away for
00697      * next frame, has the wrong sign. Hence the subtraction below.
00698      * Almost sounds like a complex conjugate/reverse data/FFT effect.
00699      */
00700 
00701     /* Apply window and overlap */
00702     for (i = 0; i < q->samples_per_channel; i++)
00703         inbuffer[i] = inbuffer[i] * fc * q->mlt_window[i] -
00704                       previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
00705 }
00706 
00718 static void imlt_gain(COOKContext *q, float *inbuffer,
00719                       cook_gains *gains_ptr, float *previous_buffer)
00720 {
00721     float *buffer0 = q->mono_mdct_output;
00722     float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
00723     int i;
00724 
00725     /* Inverse modified discrete cosine transform */
00726     q->mdct_ctx.imdct_calc(&q->mdct_ctx, q->mono_mdct_output, inbuffer);
00727 
00728     q->imlt_window(q, buffer1, gains_ptr, previous_buffer);
00729 
00730     /* Apply gain profile */
00731     for (i = 0; i < 8; i++)
00732         if (gains_ptr->now[i] || gains_ptr->now[i + 1])
00733             q->interpolate(q, &buffer1[q->gain_size_factor * i],
00734                            gains_ptr->now[i], gains_ptr->now[i + 1]);
00735 
00736     /* Save away the current to be previous block. */
00737     memcpy(previous_buffer, buffer0,
00738            q->samples_per_channel * sizeof(*previous_buffer));
00739 }
00740 
00741 
00749 static void decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)
00750 {
00751     int i;
00752     int vlc    = get_bits1(&q->gb);
00753     int start  = cplband[p->js_subband_start];
00754     int end    = cplband[p->subbands - 1];
00755     int length = end - start + 1;
00756 
00757     if (start > end)
00758         return;
00759 
00760     if (vlc)
00761         for (i = 0; i < length; i++)
00762             decouple_tab[start + i] = get_vlc2(&q->gb, p->ccpl.table, p->ccpl.bits, 2);
00763     else
00764         for (i = 0; i < length; i++)
00765             decouple_tab[start + i] = get_bits(&q->gb, p->js_vlc_bits);
00766 }
00767 
00768 /*
00769  * function decouples a pair of signals from a single signal via multiplication.
00770  *
00771  * @param q                 pointer to the COOKContext
00772  * @param subband           index of the current subband
00773  * @param f1                multiplier for channel 1 extraction
00774  * @param f2                multiplier for channel 2 extraction
00775  * @param decode_buffer     input buffer
00776  * @param mlt_buffer1       pointer to left channel mlt coefficients
00777  * @param mlt_buffer2       pointer to right channel mlt coefficients
00778  */
00779 static void decouple_float(COOKContext *q,
00780                            COOKSubpacket *p,
00781                            int subband,
00782                            float f1, float f2,
00783                            float *decode_buffer,
00784                            float *mlt_buffer1, float *mlt_buffer2)
00785 {
00786     int j, tmp_idx;
00787     for (j = 0; j < SUBBAND_SIZE; j++) {
00788         tmp_idx = ((p->js_subband_start + subband) * SUBBAND_SIZE) + j;
00789         mlt_buffer1[SUBBAND_SIZE * subband + j] = f1 * decode_buffer[tmp_idx];
00790         mlt_buffer2[SUBBAND_SIZE * subband + j] = f2 * decode_buffer[tmp_idx];
00791     }
00792 }
00793 
00801 static void joint_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer1,
00802                          float *mlt_buffer2)
00803 {
00804     int i, j;
00805     int decouple_tab[SUBBAND_SIZE];
00806     float *decode_buffer = q->decode_buffer_0;
00807     int idx, cpl_tmp;
00808     float f1, f2;
00809     const float *cplscale;
00810 
00811     memset(decouple_tab, 0, sizeof(decouple_tab));
00812     memset(decode_buffer, 0, sizeof(q->decode_buffer_0));
00813 
00814     /* Make sure the buffers are zeroed out. */
00815     memset(mlt_buffer1, 0, 1024 * sizeof(*mlt_buffer1));
00816     memset(mlt_buffer2, 0, 1024 * sizeof(*mlt_buffer2));
00817     decouple_info(q, p, decouple_tab);
00818     mono_decode(q, p, decode_buffer);
00819 
00820     /* The two channels are stored interleaved in decode_buffer. */
00821     for (i = 0; i < p->js_subband_start; i++) {
00822         for (j = 0; j < SUBBAND_SIZE; j++) {
00823             mlt_buffer1[i * 20 + j] = decode_buffer[i * 40 + j];
00824             mlt_buffer2[i * 20 + j] = decode_buffer[i * 40 + 20 + j];
00825         }
00826     }
00827 
00828     /* When we reach js_subband_start (the higher frequencies)
00829        the coefficients are stored in a coupling scheme. */
00830     idx = (1 << p->js_vlc_bits) - 1;
00831     for (i = p->js_subband_start; i < p->subbands; i++) {
00832         cpl_tmp = cplband[i];
00833         idx -= decouple_tab[cpl_tmp];
00834         cplscale = q->cplscales[p->js_vlc_bits - 2];  // choose decoupler table
00835         f1 = cplscale[decouple_tab[cpl_tmp]];
00836         f2 = cplscale[idx - 1];
00837         q->decouple(q, p, i, f1, f2, decode_buffer, mlt_buffer1, mlt_buffer2);
00838         idx = (1 << p->js_vlc_bits) - 1;
00839     }
00840 }
00841 
00850 static inline void decode_bytes_and_gain(COOKContext *q, COOKSubpacket *p,
00851                                          const uint8_t *inbuffer,
00852                                          cook_gains *gains_ptr)
00853 {
00854     int offset;
00855 
00856     offset = decode_bytes(inbuffer, q->decoded_bytes_buffer,
00857                           p->bits_per_subpacket / 8);
00858     init_get_bits(&q->gb, q->decoded_bytes_buffer + offset,
00859                   p->bits_per_subpacket);
00860     decode_gain_info(&q->gb, gains_ptr->now);
00861 
00862     /* Swap current and previous gains */
00863     FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
00864 }
00865 
00873 static void saturate_output_float(COOKContext *q, int chan, float *out)
00874 {
00875     int j;
00876     float *output = q->mono_mdct_output + q->samples_per_channel;
00877     for (j = 0; j < q->samples_per_channel; j++) {
00878         out[chan + q->nb_channels * j] = av_clipf(output[j], -1.0, 1.0);
00879     }
00880 }
00881 
00894 static inline void mlt_compensate_output(COOKContext *q, float *decode_buffer,
00895                                          cook_gains *gains_ptr, float *previous_buffer,
00896                                          float *out, int chan)
00897 {
00898     imlt_gain(q, decode_buffer, gains_ptr, previous_buffer);
00899     if (out)
00900         q->saturate_output(q, chan, out);
00901 }
00902 
00903 
00912 static void decode_subpacket(COOKContext *q, COOKSubpacket *p,
00913                              const uint8_t *inbuffer, float *outbuffer)
00914 {
00915     int sub_packet_size = p->size;
00916     /* packet dump */
00917     // for (i = 0; i < sub_packet_size ; i++)
00918     //     av_log(q->avctx, AV_LOG_ERROR, "%02x", inbuffer[i]);
00919     // av_log(q->avctx, AV_LOG_ERROR, "\n");
00920     memset(q->decode_buffer_1, 0, sizeof(q->decode_buffer_1));
00921     decode_bytes_and_gain(q, p, inbuffer, &p->gains1);
00922 
00923     if (p->joint_stereo) {
00924         joint_decode(q, p, q->decode_buffer_1, q->decode_buffer_2);
00925     } else {
00926         mono_decode(q, p, q->decode_buffer_1);
00927 
00928         if (p->num_channels == 2) {
00929             decode_bytes_and_gain(q, p, inbuffer + sub_packet_size / 2, &p->gains2);
00930             mono_decode(q, p, q->decode_buffer_2);
00931         }
00932     }
00933 
00934     mlt_compensate_output(q, q->decode_buffer_1, &p->gains1,
00935                           p->mono_previous_buffer1, outbuffer, p->ch_idx);
00936 
00937     if (p->num_channels == 2)
00938         if (p->joint_stereo)
00939             mlt_compensate_output(q, q->decode_buffer_2, &p->gains1,
00940                                   p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
00941         else
00942             mlt_compensate_output(q, q->decode_buffer_2, &p->gains2,
00943                                   p->mono_previous_buffer2, outbuffer, p->ch_idx + 1);
00944 }
00945 
00946 
00952 static int cook_decode_frame(AVCodecContext *avctx, void *data,
00953                              int *got_frame_ptr, AVPacket *avpkt)
00954 {
00955     const uint8_t *buf = avpkt->data;
00956     int buf_size = avpkt->size;
00957     COOKContext *q = avctx->priv_data;
00958     float *samples = NULL;
00959     int i, ret;
00960     int offset = 0;
00961     int chidx = 0;
00962 
00963     if (buf_size < avctx->block_align)
00964         return buf_size;
00965 
00966     /* get output buffer */
00967     if (q->discarded_packets >= 2) {
00968         q->frame.nb_samples = q->samples_per_channel;
00969         if ((ret = avctx->get_buffer(avctx, &q->frame)) < 0) {
00970             av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00971             return ret;
00972         }
00973         samples = (float *) q->frame.data[0];
00974     }
00975 
00976     /* estimate subpacket sizes */
00977     q->subpacket[0].size = avctx->block_align;
00978 
00979     for (i = 1; i < q->num_subpackets; i++) {
00980         q->subpacket[i].size = 2 * buf[avctx->block_align - q->num_subpackets + i];
00981         q->subpacket[0].size -= q->subpacket[i].size + 1;
00982         if (q->subpacket[0].size < 0) {
00983             av_log(avctx, AV_LOG_DEBUG,
00984                    "frame subpacket size total > avctx->block_align!\n");
00985             return AVERROR_INVALIDDATA;
00986         }
00987     }
00988 
00989     /* decode supbackets */
00990     for (i = 0; i < q->num_subpackets; i++) {
00991         q->subpacket[i].bits_per_subpacket = (q->subpacket[i].size * 8) >>
00992                                               q->subpacket[i].bits_per_subpdiv;
00993         q->subpacket[i].ch_idx = chidx;
00994         av_log(avctx, AV_LOG_DEBUG,
00995                "subpacket[%i] size %i js %i %i block_align %i\n",
00996                i, q->subpacket[i].size, q->subpacket[i].joint_stereo, offset,
00997                avctx->block_align);
00998 
00999         decode_subpacket(q, &q->subpacket[i], buf + offset, samples);
01000         offset += q->subpacket[i].size;
01001         chidx += q->subpacket[i].num_channels;
01002         av_log(avctx, AV_LOG_DEBUG, "subpacket[%i] %i %i\n",
01003                i, q->subpacket[i].size * 8, get_bits_count(&q->gb));
01004     }
01005 
01006     /* Discard the first two frames: no valid audio. */
01007     if (q->discarded_packets < 2) {
01008         q->discarded_packets++;
01009         *got_frame_ptr = 0;
01010         return avctx->block_align;
01011     }
01012 
01013     *got_frame_ptr    = 1;
01014     *(AVFrame *) data = q->frame;
01015 
01016     return avctx->block_align;
01017 }
01018 
01019 #ifdef DEBUG
01020 static void dump_cook_context(COOKContext *q)
01021 {
01022     //int i=0;
01023 #define PRINT(a, b) av_log(q->avctx, AV_LOG_ERROR, " %s = %d\n", a, b);
01024     av_log(q->avctx, AV_LOG_ERROR, "COOKextradata\n");
01025     av_log(q->avctx, AV_LOG_ERROR, "cookversion=%x\n", q->subpacket[0].cookversion);
01026     if (q->subpacket[0].cookversion > STEREO) {
01027         PRINT("js_subband_start", q->subpacket[0].js_subband_start);
01028         PRINT("js_vlc_bits", q->subpacket[0].js_vlc_bits);
01029     }
01030     av_log(q->avctx, AV_LOG_ERROR, "COOKContext\n");
01031     PRINT("nb_channels", q->nb_channels);
01032     PRINT("bit_rate", q->bit_rate);
01033     PRINT("sample_rate", q->sample_rate);
01034     PRINT("samples_per_channel", q->subpacket[0].samples_per_channel);
01035     PRINT("samples_per_frame", q->subpacket[0].samples_per_frame);
01036     PRINT("subbands", q->subpacket[0].subbands);
01037     PRINT("js_subband_start", q->subpacket[0].js_subband_start);
01038     PRINT("log2_numvector_size", q->subpacket[0].log2_numvector_size);
01039     PRINT("numvector_size", q->subpacket[0].numvector_size);
01040     PRINT("total_subbands", q->subpacket[0].total_subbands);
01041 }
01042 #endif
01043 
01044 static av_cold int cook_count_channels(unsigned int mask)
01045 {
01046     int i;
01047     int channels = 0;
01048     for (i = 0; i < 32; i++)
01049         if (mask & (1 << i))
01050             ++channels;
01051     return channels;
01052 }
01053 
01059 static av_cold int cook_decode_init(AVCodecContext *avctx)
01060 {
01061     COOKContext *q = avctx->priv_data;
01062     const uint8_t *edata_ptr = avctx->extradata;
01063     const uint8_t *edata_ptr_end = edata_ptr + avctx->extradata_size;
01064     int extradata_size = avctx->extradata_size;
01065     int s = 0;
01066     unsigned int channel_mask = 0;
01067     int ret;
01068     q->avctx = avctx;
01069 
01070     /* Take care of the codec specific extradata. */
01071     if (extradata_size <= 0) {
01072         av_log(avctx, AV_LOG_ERROR, "Necessary extradata missing!\n");
01073         return AVERROR_INVALIDDATA;
01074     }
01075     av_log(avctx, AV_LOG_DEBUG, "codecdata_length=%d\n", avctx->extradata_size);
01076 
01077     /* Take data from the AVCodecContext (RM container). */
01078     q->sample_rate = avctx->sample_rate;
01079     q->nb_channels = avctx->channels;
01080     q->bit_rate = avctx->bit_rate;
01081     if (!q->nb_channels) {
01082         av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
01083         return AVERROR_INVALIDDATA;
01084     }
01085 
01086     /* Initialize RNG. */
01087     av_lfg_init(&q->random_state, 0);
01088 
01089     while (edata_ptr < edata_ptr_end) {
01090         /* 8 for mono, 16 for stereo, ? for multichannel
01091            Swap to right endianness so we don't need to care later on. */
01092         if (extradata_size >= 8) {
01093             q->subpacket[s].cookversion = bytestream_get_be32(&edata_ptr);
01094             q->subpacket[s].samples_per_frame = bytestream_get_be16(&edata_ptr);
01095             q->subpacket[s].subbands = bytestream_get_be16(&edata_ptr);
01096             extradata_size -= 8;
01097         }
01098         if (extradata_size >= 8) {
01099             bytestream_get_be32(&edata_ptr);    // Unknown unused
01100             q->subpacket[s].js_subband_start = bytestream_get_be16(&edata_ptr);
01101             q->subpacket[s].js_vlc_bits = bytestream_get_be16(&edata_ptr);
01102             extradata_size -= 8;
01103         }
01104 
01105         /* Initialize extradata related variables. */
01106         q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame / q->nb_channels;
01107         q->subpacket[s].bits_per_subpacket = avctx->block_align * 8;
01108 
01109         /* Initialize default data states. */
01110         q->subpacket[s].log2_numvector_size = 5;
01111         q->subpacket[s].total_subbands = q->subpacket[s].subbands;
01112         q->subpacket[s].num_channels = 1;
01113 
01114         /* Initialize version-dependent variables */
01115 
01116         av_log(avctx, AV_LOG_DEBUG, "subpacket[%i].cookversion=%x\n", s,
01117                q->subpacket[s].cookversion);
01118         q->subpacket[s].joint_stereo = 0;
01119         switch (q->subpacket[s].cookversion) {
01120         case MONO:
01121             if (q->nb_channels != 1) {
01122                 av_log_ask_for_sample(avctx, "Container channels != 1.\n");
01123                 return AVERROR_PATCHWELCOME;
01124             }
01125             av_log(avctx, AV_LOG_DEBUG, "MONO\n");
01126             break;
01127         case STEREO:
01128             if (q->nb_channels != 1) {
01129                 q->subpacket[s].bits_per_subpdiv = 1;
01130                 q->subpacket[s].num_channels = 2;
01131             }
01132             av_log(avctx, AV_LOG_DEBUG, "STEREO\n");
01133             break;
01134         case JOINT_STEREO:
01135             if (q->nb_channels != 2) {
01136                 av_log_ask_for_sample(avctx, "Container channels != 2.\n");
01137                 return AVERROR_PATCHWELCOME;
01138             }
01139             av_log(avctx, AV_LOG_DEBUG, "JOINT_STEREO\n");
01140             if (avctx->extradata_size >= 16) {
01141                 q->subpacket[s].total_subbands = q->subpacket[s].subbands +
01142                                                  q->subpacket[s].js_subband_start;
01143                 q->subpacket[s].joint_stereo = 1;
01144                 q->subpacket[s].num_channels = 2;
01145             }
01146             if (q->subpacket[s].samples_per_channel > 256) {
01147                 q->subpacket[s].log2_numvector_size = 6;
01148             }
01149             if (q->subpacket[s].samples_per_channel > 512) {
01150                 q->subpacket[s].log2_numvector_size = 7;
01151             }
01152             break;
01153         case MC_COOK:
01154             av_log(avctx, AV_LOG_DEBUG, "MULTI_CHANNEL\n");
01155             if (extradata_size >= 4)
01156                 channel_mask |= q->subpacket[s].channel_mask = bytestream_get_be32(&edata_ptr);
01157 
01158             if (cook_count_channels(q->subpacket[s].channel_mask) > 1) {
01159                 q->subpacket[s].total_subbands = q->subpacket[s].subbands +
01160                                                  q->subpacket[s].js_subband_start;
01161                 q->subpacket[s].joint_stereo = 1;
01162                 q->subpacket[s].num_channels = 2;
01163                 q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame >> 1;
01164 
01165                 if (q->subpacket[s].samples_per_channel > 256) {
01166                     q->subpacket[s].log2_numvector_size = 6;
01167                 }
01168                 if (q->subpacket[s].samples_per_channel > 512) {
01169                     q->subpacket[s].log2_numvector_size = 7;
01170                 }
01171             } else
01172                 q->subpacket[s].samples_per_channel = q->subpacket[s].samples_per_frame;
01173 
01174             break;
01175         default:
01176             av_log_ask_for_sample(avctx, "Unknown Cook version.\n");
01177             return AVERROR_PATCHWELCOME;
01178         }
01179 
01180         if (s > 1 && q->subpacket[s].samples_per_channel != q->samples_per_channel) {
01181             av_log(avctx, AV_LOG_ERROR, "different number of samples per channel!\n");
01182             return AVERROR_INVALIDDATA;
01183         } else
01184             q->samples_per_channel = q->subpacket[0].samples_per_channel;
01185 
01186 
01187         /* Initialize variable relations */
01188         q->subpacket[s].numvector_size = (1 << q->subpacket[s].log2_numvector_size);
01189 
01190         /* Try to catch some obviously faulty streams, othervise it might be exploitable */
01191         if (q->subpacket[s].total_subbands > 53) {
01192             av_log_ask_for_sample(avctx, "total_subbands > 53\n");
01193             return AVERROR_PATCHWELCOME;
01194         }
01195 
01196         if ((q->subpacket[s].js_vlc_bits > 6) ||
01197             (q->subpacket[s].js_vlc_bits < 2 * q->subpacket[s].joint_stereo)) {
01198             av_log(avctx, AV_LOG_ERROR, "js_vlc_bits = %d, only >= %d and <= 6 allowed!\n",
01199                    q->subpacket[s].js_vlc_bits, 2 * q->subpacket[s].joint_stereo);
01200             return AVERROR_INVALIDDATA;
01201         }
01202 
01203         if (q->subpacket[s].subbands > 50) {
01204             av_log_ask_for_sample(avctx, "subbands > 50\n");
01205             return AVERROR_PATCHWELCOME;
01206         }
01207         q->subpacket[s].gains1.now      = q->subpacket[s].gain_1;
01208         q->subpacket[s].gains1.previous = q->subpacket[s].gain_2;
01209         q->subpacket[s].gains2.now      = q->subpacket[s].gain_3;
01210         q->subpacket[s].gains2.previous = q->subpacket[s].gain_4;
01211 
01212         q->num_subpackets++;
01213         s++;
01214         if (s > MAX_SUBPACKETS) {
01215             av_log_ask_for_sample(avctx, "Too many subpackets > 5\n");
01216             return AVERROR_PATCHWELCOME;
01217         }
01218     }
01219     /* Generate tables */
01220     init_pow2table();
01221     init_gain_table(q);
01222     init_cplscales_table(q);
01223 
01224     if ((ret = init_cook_vlc_tables(q)))
01225         return ret;
01226 
01227 
01228     if (avctx->block_align >= UINT_MAX / 2)
01229         return AVERROR(EINVAL);
01230 
01231     /* Pad the databuffer with:
01232        DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
01233        FF_INPUT_BUFFER_PADDING_SIZE, for the bitstreamreader. */
01234     q->decoded_bytes_buffer =
01235         av_mallocz(avctx->block_align
01236                    + DECODE_BYTES_PAD1(avctx->block_align)
01237                    + FF_INPUT_BUFFER_PADDING_SIZE);
01238     if (q->decoded_bytes_buffer == NULL)
01239         return AVERROR(ENOMEM);
01240 
01241     /* Initialize transform. */
01242     if ((ret = init_cook_mlt(q)))
01243         return ret;
01244 
01245     /* Initialize COOK signal arithmetic handling */
01246     if (1) {
01247         q->scalar_dequant  = scalar_dequant_float;
01248         q->decouple        = decouple_float;
01249         q->imlt_window     = imlt_window_float;
01250         q->interpolate     = interpolate_float;
01251         q->saturate_output = saturate_output_float;
01252     }
01253 
01254     /* Try to catch some obviously faulty streams, othervise it might be exploitable */
01255     if ((q->samples_per_channel == 256) || (q->samples_per_channel == 512)
01256                 || (q->samples_per_channel == 1024)) {
01257     } else {
01258         av_log_ask_for_sample(avctx,
01259                               "unknown amount of samples_per_channel = %d\n",
01260                               q->samples_per_channel);
01261         return AVERROR_PATCHWELCOME;
01262     }
01263 
01264     avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
01265     if (channel_mask)
01266         avctx->channel_layout = channel_mask;
01267     else
01268         avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
01269 
01270     avcodec_get_frame_defaults(&q->frame);
01271     avctx->coded_frame = &q->frame;
01272 
01273 #ifdef DEBUG
01274     dump_cook_context(q);
01275 #endif
01276     return 0;
01277 }
01278 
01279 AVCodec ff_cook_decoder = {
01280     .name           = "cook",
01281     .type           = AVMEDIA_TYPE_AUDIO,
01282     .id             = CODEC_ID_COOK,
01283     .priv_data_size = sizeof(COOKContext),
01284     .init           = cook_decode_init,
01285     .close          = cook_decode_close,
01286     .decode         = cook_decode_frame,
01287     .capabilities   = CODEC_CAP_DR1,
01288     .long_name      = NULL_IF_CONFIG_SMALL("COOK"),
01289 };
Generated on Sun Apr 22 2012 21:54:00 for Libav by doxygen 1.7.1