libavcodec/mlpdec.c
Go to the documentation of this file.
00001 /*
00002  * MLP decoder
00003  * Copyright (c) 2007-2008 Ian Caulfield
00004  *
00005  * This file is part of Libav.
00006  *
00007  * Libav is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * Libav is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with Libav; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00027 #include <stdint.h>
00028 
00029 #include "avcodec.h"
00030 #include "internal.h"
00031 #include "dsputil.h"
00032 #include "libavutil/intreadwrite.h"
00033 #include "get_bits.h"
00034 #include "libavutil/crc.h"
00035 #include "parser.h"
00036 #include "mlp_parser.h"
00037 #include "mlp.h"
00038 
00040 #define VLC_BITS            9
00041 
00042 
00043 static const char* sample_message =
00044     "Please file a bug report following the instructions at "
00045     "http://libav.org/bugreports.html and include "
00046     "a sample of this file.";
00047 
00048 typedef struct SubStream {
00050     uint8_t     restart_seen;
00051 
00053 
00054 
00055     uint16_t    noise_type;
00056 
00058     uint8_t     min_channel;
00060     uint8_t     max_channel;
00062     uint8_t     max_matrix_channel;
00064     uint8_t     ch_assign[MAX_CHANNELS];
00065 
00067     ChannelParams channel_params[MAX_CHANNELS];
00068 
00070     uint8_t     noise_shift;
00072     uint32_t    noisegen_seed;
00073 
00075     uint8_t     data_check_present;
00076 
00078     uint8_t     param_presence_flags;
00079 #define PARAM_BLOCKSIZE     (1 << 7)
00080 #define PARAM_MATRIX        (1 << 6)
00081 #define PARAM_OUTSHIFT      (1 << 5)
00082 #define PARAM_QUANTSTEP     (1 << 4)
00083 #define PARAM_FIR           (1 << 3)
00084 #define PARAM_IIR           (1 << 2)
00085 #define PARAM_HUFFOFFSET    (1 << 1)
00086 #define PARAM_PRESENCE      (1 << 0)
00087 
00088 
00090 
00092 
00093     uint8_t     num_primitive_matrices;
00094 
00096     uint8_t     matrix_out_ch[MAX_MATRICES];
00097 
00099     uint8_t     lsb_bypass[MAX_MATRICES];
00101     int32_t     matrix_coeff[MAX_MATRICES][MAX_CHANNELS];
00103     uint8_t     matrix_noise_shift[MAX_MATRICES];
00105 
00107     uint8_t     quant_step_size[MAX_CHANNELS];
00108 
00110     uint16_t    blocksize;
00112     uint16_t    blockpos;
00113 
00115     int8_t      output_shift[MAX_CHANNELS];
00116 
00118     int32_t     lossless_check_data;
00119 
00120 } SubStream;
00121 
00122 typedef struct MLPDecodeContext {
00123     AVCodecContext *avctx;
00124     AVFrame     frame;
00125 
00127     int         is_major_sync_unit;
00128 
00130     uint8_t     params_valid;
00131 
00133     uint8_t     num_substreams;
00134 
00136     uint8_t     max_decoded_substream;
00137 
00139     int         access_unit_size;
00141     int         access_unit_size_pow2;
00142 
00143     SubStream   substream[MAX_SUBSTREAMS];
00144 
00145     int         matrix_changed;
00146     int         filter_changed[MAX_CHANNELS][NUM_FILTERS];
00147 
00148     int8_t      noise_buffer[MAX_BLOCKSIZE_POW2];
00149     int8_t      bypassed_lsbs[MAX_BLOCKSIZE][MAX_CHANNELS];
00150     int32_t     sample_buffer[MAX_BLOCKSIZE][MAX_CHANNELS];
00151 
00152     DSPContext  dsp;
00153 } MLPDecodeContext;
00154 
00155 static VLC huff_vlc[3];
00156 
00159 static av_cold void init_static(void)
00160 {
00161     if (!huff_vlc[0].bits) {
00162         INIT_VLC_STATIC(&huff_vlc[0], VLC_BITS, 18,
00163                     &ff_mlp_huffman_tables[0][0][1], 2, 1,
00164                     &ff_mlp_huffman_tables[0][0][0], 2, 1, 512);
00165         INIT_VLC_STATIC(&huff_vlc[1], VLC_BITS, 16,
00166                     &ff_mlp_huffman_tables[1][0][1], 2, 1,
00167                     &ff_mlp_huffman_tables[1][0][0], 2, 1, 512);
00168         INIT_VLC_STATIC(&huff_vlc[2], VLC_BITS, 15,
00169                     &ff_mlp_huffman_tables[2][0][1], 2, 1,
00170                     &ff_mlp_huffman_tables[2][0][0], 2, 1, 512);
00171     }
00172 
00173     ff_mlp_init_crc();
00174 }
00175 
00176 static inline int32_t calculate_sign_huff(MLPDecodeContext *m,
00177                                           unsigned int substr, unsigned int ch)
00178 {
00179     SubStream *s = &m->substream[substr];
00180     ChannelParams *cp = &s->channel_params[ch];
00181     int lsb_bits = cp->huff_lsbs - s->quant_step_size[ch];
00182     int sign_shift = lsb_bits + (cp->codebook ? 2 - cp->codebook : -1);
00183     int32_t sign_huff_offset = cp->huff_offset;
00184 
00185     if (cp->codebook > 0)
00186         sign_huff_offset -= 7 << lsb_bits;
00187 
00188     if (sign_shift >= 0)
00189         sign_huff_offset -= 1 << sign_shift;
00190 
00191     return sign_huff_offset;
00192 }
00193 
00197 static inline int read_huff_channels(MLPDecodeContext *m, GetBitContext *gbp,
00198                                      unsigned int substr, unsigned int pos)
00199 {
00200     SubStream *s = &m->substream[substr];
00201     unsigned int mat, channel;
00202 
00203     for (mat = 0; mat < s->num_primitive_matrices; mat++)
00204         if (s->lsb_bypass[mat])
00205             m->bypassed_lsbs[pos + s->blockpos][mat] = get_bits1(gbp);
00206 
00207     for (channel = s->min_channel; channel <= s->max_channel; channel++) {
00208         ChannelParams *cp = &s->channel_params[channel];
00209         int codebook = cp->codebook;
00210         int quant_step_size = s->quant_step_size[channel];
00211         int lsb_bits = cp->huff_lsbs - quant_step_size;
00212         int result = 0;
00213 
00214         if (codebook > 0)
00215             result = get_vlc2(gbp, huff_vlc[codebook-1].table,
00216                             VLC_BITS, (9 + VLC_BITS - 1) / VLC_BITS);
00217 
00218         if (result < 0)
00219             return AVERROR_INVALIDDATA;
00220 
00221         if (lsb_bits > 0)
00222             result = (result << lsb_bits) + get_bits(gbp, lsb_bits);
00223 
00224         result  += cp->sign_huff_offset;
00225         result <<= quant_step_size;
00226 
00227         m->sample_buffer[pos + s->blockpos][channel] = result;
00228     }
00229 
00230     return 0;
00231 }
00232 
00233 static av_cold int mlp_decode_init(AVCodecContext *avctx)
00234 {
00235     MLPDecodeContext *m = avctx->priv_data;
00236     int substr;
00237 
00238     init_static();
00239     m->avctx = avctx;
00240     for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
00241         m->substream[substr].lossless_check_data = 0xffffffff;
00242     dsputil_init(&m->dsp, avctx);
00243 
00244     avcodec_get_frame_defaults(&m->frame);
00245     avctx->coded_frame = &m->frame;
00246 
00247     return 0;
00248 }
00249 
00255 static int read_major_sync(MLPDecodeContext *m, GetBitContext *gb)
00256 {
00257     MLPHeaderInfo mh;
00258     int substr, ret;
00259 
00260     if ((ret = ff_mlp_read_major_sync(m->avctx, &mh, gb)) != 0)
00261         return ret;
00262 
00263     if (mh.group1_bits == 0) {
00264         av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown bits per sample\n");
00265         return AVERROR_INVALIDDATA;
00266     }
00267     if (mh.group2_bits > mh.group1_bits) {
00268         av_log(m->avctx, AV_LOG_ERROR,
00269                "Channel group 2 cannot have more bits per sample than group 1.\n");
00270         return AVERROR_INVALIDDATA;
00271     }
00272 
00273     if (mh.group2_samplerate && mh.group2_samplerate != mh.group1_samplerate) {
00274         av_log(m->avctx, AV_LOG_ERROR,
00275                "Channel groups with differing sample rates are not currently supported.\n");
00276         return AVERROR_INVALIDDATA;
00277     }
00278 
00279     if (mh.group1_samplerate == 0) {
00280         av_log(m->avctx, AV_LOG_ERROR, "invalid/unknown sampling rate\n");
00281         return AVERROR_INVALIDDATA;
00282     }
00283     if (mh.group1_samplerate > MAX_SAMPLERATE) {
00284         av_log(m->avctx, AV_LOG_ERROR,
00285                "Sampling rate %d is greater than the supported maximum (%d).\n",
00286                mh.group1_samplerate, MAX_SAMPLERATE);
00287         return AVERROR_INVALIDDATA;
00288     }
00289     if (mh.access_unit_size > MAX_BLOCKSIZE) {
00290         av_log(m->avctx, AV_LOG_ERROR,
00291                "Block size %d is greater than the supported maximum (%d).\n",
00292                mh.access_unit_size, MAX_BLOCKSIZE);
00293         return AVERROR_INVALIDDATA;
00294     }
00295     if (mh.access_unit_size_pow2 > MAX_BLOCKSIZE_POW2) {
00296         av_log(m->avctx, AV_LOG_ERROR,
00297                "Block size pow2 %d is greater than the supported maximum (%d).\n",
00298                mh.access_unit_size_pow2, MAX_BLOCKSIZE_POW2);
00299         return AVERROR_INVALIDDATA;
00300     }
00301 
00302     if (mh.num_substreams == 0)
00303         return AVERROR_INVALIDDATA;
00304     if (m->avctx->codec_id == CODEC_ID_MLP && mh.num_substreams > 2) {
00305         av_log(m->avctx, AV_LOG_ERROR, "MLP only supports up to 2 substreams.\n");
00306         return AVERROR_INVALIDDATA;
00307     }
00308     if (mh.num_substreams > MAX_SUBSTREAMS) {
00309         av_log(m->avctx, AV_LOG_ERROR,
00310                "Number of substreams %d is larger than the maximum supported "
00311                "by the decoder. %s\n", mh.num_substreams, sample_message);
00312         return AVERROR_INVALIDDATA;
00313     }
00314 
00315     m->access_unit_size      = mh.access_unit_size;
00316     m->access_unit_size_pow2 = mh.access_unit_size_pow2;
00317 
00318     m->num_substreams        = mh.num_substreams;
00319     m->max_decoded_substream = m->num_substreams - 1;
00320 
00321     m->avctx->sample_rate    = mh.group1_samplerate;
00322     m->avctx->frame_size     = mh.access_unit_size;
00323 
00324     m->avctx->bits_per_raw_sample = mh.group1_bits;
00325     if (mh.group1_bits > 16)
00326         m->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
00327     else
00328         m->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
00329 
00330     m->params_valid = 1;
00331     for (substr = 0; substr < MAX_SUBSTREAMS; substr++)
00332         m->substream[substr].restart_seen = 0;
00333 
00334     return 0;
00335 }
00336 
00341 static int read_restart_header(MLPDecodeContext *m, GetBitContext *gbp,
00342                                const uint8_t *buf, unsigned int substr)
00343 {
00344     SubStream *s = &m->substream[substr];
00345     unsigned int ch;
00346     int sync_word, tmp;
00347     uint8_t checksum;
00348     uint8_t lossless_check;
00349     int start_count = get_bits_count(gbp);
00350     int min_channel, max_channel, max_matrix_channel;
00351     const int std_max_matrix_channel = m->avctx->codec_id == CODEC_ID_MLP
00352                                      ? MAX_MATRIX_CHANNEL_MLP
00353                                      : MAX_MATRIX_CHANNEL_TRUEHD;
00354 
00355     sync_word = get_bits(gbp, 13);
00356 
00357     if (sync_word != 0x31ea >> 1) {
00358         av_log(m->avctx, AV_LOG_ERROR,
00359                "restart header sync incorrect (got 0x%04x)\n", sync_word);
00360         return AVERROR_INVALIDDATA;
00361     }
00362 
00363     s->noise_type = get_bits1(gbp);
00364 
00365     if (m->avctx->codec_id == CODEC_ID_MLP && s->noise_type) {
00366         av_log(m->avctx, AV_LOG_ERROR, "MLP must have 0x31ea sync word.\n");
00367         return AVERROR_INVALIDDATA;
00368     }
00369 
00370     skip_bits(gbp, 16); /* Output timestamp */
00371 
00372     min_channel        = get_bits(gbp, 4);
00373     max_channel        = get_bits(gbp, 4);
00374     max_matrix_channel = get_bits(gbp, 4);
00375 
00376     if (max_matrix_channel > std_max_matrix_channel) {
00377         av_log(m->avctx, AV_LOG_ERROR,
00378                "Max matrix channel cannot be greater than %d.\n",
00379                max_matrix_channel);
00380         return AVERROR_INVALIDDATA;
00381     }
00382 
00383     if (max_channel != max_matrix_channel) {
00384         av_log(m->avctx, AV_LOG_ERROR,
00385                "Max channel must be equal max matrix channel.\n");
00386         return AVERROR_INVALIDDATA;
00387     }
00388 
00389     /* This should happen for TrueHD streams with >6 channels and MLP's noise
00390      * type. It is not yet known if this is allowed. */
00391     if (s->max_channel > MAX_MATRIX_CHANNEL_MLP && !s->noise_type) {
00392         av_log(m->avctx, AV_LOG_ERROR,
00393                "Number of channels %d is larger than the maximum supported "
00394                "by the decoder. %s\n", s->max_channel+2, sample_message);
00395         return AVERROR_INVALIDDATA;
00396     }
00397 
00398     if (min_channel > max_channel) {
00399         av_log(m->avctx, AV_LOG_ERROR,
00400                "Substream min channel cannot be greater than max channel.\n");
00401         return AVERROR_INVALIDDATA;
00402     }
00403 
00404 
00405     s->min_channel        = min_channel;
00406     s->max_channel        = max_channel;
00407     s->max_matrix_channel = max_matrix_channel;
00408 
00409     if (m->avctx->request_channels > 0 &&
00410         m->avctx->request_channels <= s->max_channel + 1 &&
00411         m->max_decoded_substream > substr) {
00412         av_log(m->avctx, AV_LOG_DEBUG,
00413                "Extracting %d channel downmix from substream %d. "
00414                "Further substreams will be skipped.\n",
00415                s->max_channel + 1, substr);
00416         m->max_decoded_substream = substr;
00417     }
00418 
00419     s->noise_shift   = get_bits(gbp,  4);
00420     s->noisegen_seed = get_bits(gbp, 23);
00421 
00422     skip_bits(gbp, 19);
00423 
00424     s->data_check_present = get_bits1(gbp);
00425     lossless_check = get_bits(gbp, 8);
00426     if (substr == m->max_decoded_substream
00427         && s->lossless_check_data != 0xffffffff) {
00428         tmp = xor_32_to_8(s->lossless_check_data);
00429         if (tmp != lossless_check)
00430             av_log(m->avctx, AV_LOG_WARNING,
00431                    "Lossless check failed - expected %02x, calculated %02x.\n",
00432                    lossless_check, tmp);
00433     }
00434 
00435     skip_bits(gbp, 16);
00436 
00437     memset(s->ch_assign, 0, sizeof(s->ch_assign));
00438 
00439     for (ch = 0; ch <= s->max_matrix_channel; ch++) {
00440         int ch_assign = get_bits(gbp, 6);
00441         if (ch_assign > s->max_matrix_channel) {
00442             av_log(m->avctx, AV_LOG_ERROR,
00443                    "Assignment of matrix channel %d to invalid output channel %d. %s\n",
00444                    ch, ch_assign, sample_message);
00445             return AVERROR_INVALIDDATA;
00446         }
00447         s->ch_assign[ch_assign] = ch;
00448     }
00449 
00450     checksum = ff_mlp_restart_checksum(buf, get_bits_count(gbp) - start_count);
00451 
00452     if (checksum != get_bits(gbp, 8))
00453         av_log(m->avctx, AV_LOG_ERROR, "restart header checksum error\n");
00454 
00455     /* Set default decoding parameters. */
00456     s->param_presence_flags   = 0xff;
00457     s->num_primitive_matrices = 0;
00458     s->blocksize              = 8;
00459     s->lossless_check_data    = 0;
00460 
00461     memset(s->output_shift   , 0, sizeof(s->output_shift   ));
00462     memset(s->quant_step_size, 0, sizeof(s->quant_step_size));
00463 
00464     for (ch = s->min_channel; ch <= s->max_channel; ch++) {
00465         ChannelParams *cp = &s->channel_params[ch];
00466         cp->filter_params[FIR].order = 0;
00467         cp->filter_params[IIR].order = 0;
00468         cp->filter_params[FIR].shift = 0;
00469         cp->filter_params[IIR].shift = 0;
00470 
00471         /* Default audio coding is 24-bit raw PCM. */
00472         cp->huff_offset      = 0;
00473         cp->sign_huff_offset = (-1) << 23;
00474         cp->codebook         = 0;
00475         cp->huff_lsbs        = 24;
00476     }
00477 
00478     if (substr == m->max_decoded_substream)
00479         m->avctx->channels = s->max_matrix_channel + 1;
00480 
00481     return 0;
00482 }
00483 
00486 static int read_filter_params(MLPDecodeContext *m, GetBitContext *gbp,
00487                               unsigned int substr, unsigned int channel,
00488                               unsigned int filter)
00489 {
00490     SubStream *s = &m->substream[substr];
00491     FilterParams *fp = &s->channel_params[channel].filter_params[filter];
00492     const int max_order = filter ? MAX_IIR_ORDER : MAX_FIR_ORDER;
00493     const char fchar = filter ? 'I' : 'F';
00494     int i, order;
00495 
00496     // Filter is 0 for FIR, 1 for IIR.
00497     assert(filter < 2);
00498 
00499     if (m->filter_changed[channel][filter]++ > 1) {
00500         av_log(m->avctx, AV_LOG_ERROR, "Filters may change only once per access unit.\n");
00501         return AVERROR_INVALIDDATA;
00502     }
00503 
00504     order = get_bits(gbp, 4);
00505     if (order > max_order) {
00506         av_log(m->avctx, AV_LOG_ERROR,
00507                "%cIR filter order %d is greater than maximum %d.\n",
00508                fchar, order, max_order);
00509         return AVERROR_INVALIDDATA;
00510     }
00511     fp->order = order;
00512 
00513     if (order > 0) {
00514         int32_t *fcoeff = s->channel_params[channel].coeff[filter];
00515         int coeff_bits, coeff_shift;
00516 
00517         fp->shift = get_bits(gbp, 4);
00518 
00519         coeff_bits  = get_bits(gbp, 5);
00520         coeff_shift = get_bits(gbp, 3);
00521         if (coeff_bits < 1 || coeff_bits > 16) {
00522             av_log(m->avctx, AV_LOG_ERROR,
00523                    "%cIR filter coeff_bits must be between 1 and 16.\n",
00524                    fchar);
00525             return AVERROR_INVALIDDATA;
00526         }
00527         if (coeff_bits + coeff_shift > 16) {
00528             av_log(m->avctx, AV_LOG_ERROR,
00529                    "Sum of coeff_bits and coeff_shift for %cIR filter must be 16 or less.\n",
00530                    fchar);
00531             return AVERROR_INVALIDDATA;
00532         }
00533 
00534         for (i = 0; i < order; i++)
00535             fcoeff[i] = get_sbits(gbp, coeff_bits) << coeff_shift;
00536 
00537         if (get_bits1(gbp)) {
00538             int state_bits, state_shift;
00539 
00540             if (filter == FIR) {
00541                 av_log(m->avctx, AV_LOG_ERROR,
00542                        "FIR filter has state data specified.\n");
00543                 return AVERROR_INVALIDDATA;
00544             }
00545 
00546             state_bits  = get_bits(gbp, 4);
00547             state_shift = get_bits(gbp, 4);
00548 
00549             /* TODO: Check validity of state data. */
00550 
00551             for (i = 0; i < order; i++)
00552                 fp->state[i] = get_sbits(gbp, state_bits) << state_shift;
00553         }
00554     }
00555 
00556     return 0;
00557 }
00558 
00561 static int read_matrix_params(MLPDecodeContext *m, unsigned int substr, GetBitContext *gbp)
00562 {
00563     SubStream *s = &m->substream[substr];
00564     unsigned int mat, ch;
00565     const int max_primitive_matrices = m->avctx->codec_id == CODEC_ID_MLP
00566                                      ? MAX_MATRICES_MLP
00567                                      : MAX_MATRICES_TRUEHD;
00568 
00569     if (m->matrix_changed++ > 1) {
00570         av_log(m->avctx, AV_LOG_ERROR, "Matrices may change only once per access unit.\n");
00571         return AVERROR_INVALIDDATA;
00572     }
00573 
00574     s->num_primitive_matrices = get_bits(gbp, 4);
00575 
00576     if (s->num_primitive_matrices > max_primitive_matrices) {
00577         av_log(m->avctx, AV_LOG_ERROR,
00578                "Number of primitive matrices cannot be greater than %d.\n",
00579                max_primitive_matrices);
00580         return AVERROR_INVALIDDATA;
00581     }
00582 
00583     for (mat = 0; mat < s->num_primitive_matrices; mat++) {
00584         int frac_bits, max_chan;
00585         s->matrix_out_ch[mat] = get_bits(gbp, 4);
00586         frac_bits             = get_bits(gbp, 4);
00587         s->lsb_bypass   [mat] = get_bits1(gbp);
00588 
00589         if (s->matrix_out_ch[mat] > s->max_matrix_channel) {
00590             av_log(m->avctx, AV_LOG_ERROR,
00591                     "Invalid channel %d specified as output from matrix.\n",
00592                     s->matrix_out_ch[mat]);
00593             return AVERROR_INVALIDDATA;
00594         }
00595         if (frac_bits > 14) {
00596             av_log(m->avctx, AV_LOG_ERROR,
00597                     "Too many fractional bits specified.\n");
00598             return AVERROR_INVALIDDATA;
00599         }
00600 
00601         max_chan = s->max_matrix_channel;
00602         if (!s->noise_type)
00603             max_chan+=2;
00604 
00605         for (ch = 0; ch <= max_chan; ch++) {
00606             int coeff_val = 0;
00607             if (get_bits1(gbp))
00608                 coeff_val = get_sbits(gbp, frac_bits + 2);
00609 
00610             s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);
00611         }
00612 
00613         if (s->noise_type)
00614             s->matrix_noise_shift[mat] = get_bits(gbp, 4);
00615         else
00616             s->matrix_noise_shift[mat] = 0;
00617     }
00618 
00619     return 0;
00620 }
00621 
00624 static int read_channel_params(MLPDecodeContext *m, unsigned int substr,
00625                                GetBitContext *gbp, unsigned int ch)
00626 {
00627     SubStream *s = &m->substream[substr];
00628     ChannelParams *cp = &s->channel_params[ch];
00629     FilterParams *fir = &cp->filter_params[FIR];
00630     FilterParams *iir = &cp->filter_params[IIR];
00631     int ret;
00632 
00633     if (s->param_presence_flags & PARAM_FIR)
00634         if (get_bits1(gbp))
00635             if ((ret = read_filter_params(m, gbp, substr, ch, FIR)) < 0)
00636                 return ret;
00637 
00638     if (s->param_presence_flags & PARAM_IIR)
00639         if (get_bits1(gbp))
00640             if ((ret = read_filter_params(m, gbp, substr, ch, IIR)) < 0)
00641                 return ret;
00642 
00643     if (fir->order + iir->order > 8) {
00644         av_log(m->avctx, AV_LOG_ERROR, "Total filter orders too high.\n");
00645         return AVERROR_INVALIDDATA;
00646     }
00647 
00648     if (fir->order && iir->order &&
00649         fir->shift != iir->shift) {
00650         av_log(m->avctx, AV_LOG_ERROR,
00651                 "FIR and IIR filters must use the same precision.\n");
00652         return AVERROR_INVALIDDATA;
00653     }
00654     /* The FIR and IIR filters must have the same precision.
00655      * To simplify the filtering code, only the precision of the
00656      * FIR filter is considered. If only the IIR filter is employed,
00657      * the FIR filter precision is set to that of the IIR filter, so
00658      * that the filtering code can use it. */
00659     if (!fir->order && iir->order)
00660         fir->shift = iir->shift;
00661 
00662     if (s->param_presence_flags & PARAM_HUFFOFFSET)
00663         if (get_bits1(gbp))
00664             cp->huff_offset = get_sbits(gbp, 15);
00665 
00666     cp->codebook  = get_bits(gbp, 2);
00667     cp->huff_lsbs = get_bits(gbp, 5);
00668 
00669     if (cp->huff_lsbs > 24) {
00670         av_log(m->avctx, AV_LOG_ERROR, "Invalid huff_lsbs.\n");
00671         return AVERROR_INVALIDDATA;
00672     }
00673 
00674     cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
00675 
00676     return 0;
00677 }
00678 
00682 static int read_decoding_params(MLPDecodeContext *m, GetBitContext *gbp,
00683                                 unsigned int substr)
00684 {
00685     SubStream *s = &m->substream[substr];
00686     unsigned int ch;
00687     int ret;
00688 
00689     if (s->param_presence_flags & PARAM_PRESENCE)
00690         if (get_bits1(gbp))
00691             s->param_presence_flags = get_bits(gbp, 8);
00692 
00693     if (s->param_presence_flags & PARAM_BLOCKSIZE)
00694         if (get_bits1(gbp)) {
00695             s->blocksize = get_bits(gbp, 9);
00696             if (s->blocksize < 8 || s->blocksize > m->access_unit_size) {
00697                 av_log(m->avctx, AV_LOG_ERROR, "Invalid blocksize.");
00698                 s->blocksize = 0;
00699                 return AVERROR_INVALIDDATA;
00700             }
00701         }
00702 
00703     if (s->param_presence_flags & PARAM_MATRIX)
00704         if (get_bits1(gbp))
00705             if ((ret = read_matrix_params(m, substr, gbp)) < 0)
00706                 return ret;
00707 
00708     if (s->param_presence_flags & PARAM_OUTSHIFT)
00709         if (get_bits1(gbp))
00710             for (ch = 0; ch <= s->max_matrix_channel; ch++)
00711                 s->output_shift[ch] = get_sbits(gbp, 4);
00712 
00713     if (s->param_presence_flags & PARAM_QUANTSTEP)
00714         if (get_bits1(gbp))
00715             for (ch = 0; ch <= s->max_channel; ch++) {
00716                 ChannelParams *cp = &s->channel_params[ch];
00717 
00718                 s->quant_step_size[ch] = get_bits(gbp, 4);
00719 
00720                 cp->sign_huff_offset = calculate_sign_huff(m, substr, ch);
00721             }
00722 
00723     for (ch = s->min_channel; ch <= s->max_channel; ch++)
00724         if (get_bits1(gbp))
00725             if ((ret = read_channel_params(m, substr, gbp, ch)) < 0)
00726                 return ret;
00727 
00728     return 0;
00729 }
00730 
00731 #define MSB_MASK(bits)  (-1u << bits)
00732 
00736 static void filter_channel(MLPDecodeContext *m, unsigned int substr,
00737                            unsigned int channel)
00738 {
00739     SubStream *s = &m->substream[substr];
00740     const int32_t *fircoeff = s->channel_params[channel].coeff[FIR];
00741     int32_t state_buffer[NUM_FILTERS][MAX_BLOCKSIZE + MAX_FIR_ORDER];
00742     int32_t *firbuf = state_buffer[FIR] + MAX_BLOCKSIZE;
00743     int32_t *iirbuf = state_buffer[IIR] + MAX_BLOCKSIZE;
00744     FilterParams *fir = &s->channel_params[channel].filter_params[FIR];
00745     FilterParams *iir = &s->channel_params[channel].filter_params[IIR];
00746     unsigned int filter_shift = fir->shift;
00747     int32_t mask = MSB_MASK(s->quant_step_size[channel]);
00748 
00749     memcpy(firbuf, fir->state, MAX_FIR_ORDER * sizeof(int32_t));
00750     memcpy(iirbuf, iir->state, MAX_IIR_ORDER * sizeof(int32_t));
00751 
00752     m->dsp.mlp_filter_channel(firbuf, fircoeff,
00753                               fir->order, iir->order,
00754                               filter_shift, mask, s->blocksize,
00755                               &m->sample_buffer[s->blockpos][channel]);
00756 
00757     memcpy(fir->state, firbuf - s->blocksize, MAX_FIR_ORDER * sizeof(int32_t));
00758     memcpy(iir->state, iirbuf - s->blocksize, MAX_IIR_ORDER * sizeof(int32_t));
00759 }
00760 
00763 static int read_block_data(MLPDecodeContext *m, GetBitContext *gbp,
00764                            unsigned int substr)
00765 {
00766     SubStream *s = &m->substream[substr];
00767     unsigned int i, ch, expected_stream_pos = 0;
00768     int ret;
00769 
00770     if (s->data_check_present) {
00771         expected_stream_pos  = get_bits_count(gbp);
00772         expected_stream_pos += get_bits(gbp, 16);
00773         av_log(m->avctx, AV_LOG_WARNING, "This file contains some features "
00774                "we have not tested yet. %s\n", sample_message);
00775     }
00776 
00777     if (s->blockpos + s->blocksize > m->access_unit_size) {
00778         av_log(m->avctx, AV_LOG_ERROR, "too many audio samples in frame\n");
00779         return AVERROR_INVALIDDATA;
00780     }
00781 
00782     memset(&m->bypassed_lsbs[s->blockpos][0], 0,
00783            s->blocksize * sizeof(m->bypassed_lsbs[0]));
00784 
00785     for (i = 0; i < s->blocksize; i++)
00786         if ((ret = read_huff_channels(m, gbp, substr, i)) < 0)
00787             return ret;
00788 
00789     for (ch = s->min_channel; ch <= s->max_channel; ch++)
00790         filter_channel(m, substr, ch);
00791 
00792     s->blockpos += s->blocksize;
00793 
00794     if (s->data_check_present) {
00795         if (get_bits_count(gbp) != expected_stream_pos)
00796             av_log(m->avctx, AV_LOG_ERROR, "block data length mismatch\n");
00797         skip_bits(gbp, 8);
00798     }
00799 
00800     return 0;
00801 }
00802 
00805 static const int8_t noise_table[256] = {
00806      30,  51,  22,  54,   3,   7,  -4,  38,  14,  55,  46,  81,  22,  58,  -3,   2,
00807      52,  31,  -7,  51,  15,  44,  74,  30,  85, -17,  10,  33,  18,  80,  28,  62,
00808      10,  32,  23,  69,  72,  26,  35,  17,  73,  60,   8,  56,   2,   6,  -2,  -5,
00809      51,   4,  11,  50,  66,  76,  21,  44,  33,  47,   1,  26,  64,  48,  57,  40,
00810      38,  16, -10, -28,  92,  22, -18,  29, -10,   5, -13,  49,  19,  24,  70,  34,
00811      61,  48,  30,  14,  -6,  25,  58,  33,  42,  60,  67,  17,  54,  17,  22,  30,
00812      67,  44,  -9,  50, -11,  43,  40,  32,  59,  82,  13,  49, -14,  55,  60,  36,
00813      48,  49,  31,  47,  15,  12,   4,  65,   1,  23,  29,  39,  45,  -2,  84,  69,
00814       0,  72,  37,  57,  27,  41, -15, -16,  35,  31,  14,  61,  24,   0,  27,  24,
00815      16,  41,  55,  34,  53,   9,  56,  12,  25,  29,  53,   5,  20, -20,  -8,  20,
00816      13,  28,  -3,  78,  38,  16,  11,  62,  46,  29,  21,  24,  46,  65,  43, -23,
00817      89,  18,  74,  21,  38, -12,  19,  12, -19,   8,  15,  33,   4,  57,   9,  -8,
00818      36,  35,  26,  28,   7,  83,  63,  79,  75,  11,   3,  87,  37,  47,  34,  40,
00819      39,  19,  20,  42,  27,  34,  39,  77,  13,  42,  59,  64,  45,  -1,  32,  37,
00820      45,  -5,  53,  -6,   7,  36,  50,  23,   6,  32,   9, -21,  18,  71,  27,  52,
00821     -25,  31,  35,  42,  -1,  68,  63,  52,  26,  43,  66,  37,  41,  25,  40,  70,
00822 };
00823 
00834 static void generate_2_noise_channels(MLPDecodeContext *m, unsigned int substr)
00835 {
00836     SubStream *s = &m->substream[substr];
00837     unsigned int i;
00838     uint32_t seed = s->noisegen_seed;
00839     unsigned int maxchan = s->max_matrix_channel;
00840 
00841     for (i = 0; i < s->blockpos; i++) {
00842         uint16_t seed_shr7 = seed >> 7;
00843         m->sample_buffer[i][maxchan+1] = ((int8_t)(seed >> 15)) << s->noise_shift;
00844         m->sample_buffer[i][maxchan+2] = ((int8_t) seed_shr7)   << s->noise_shift;
00845 
00846         seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);
00847     }
00848 
00849     s->noisegen_seed = seed;
00850 }
00851 
00854 static void fill_noise_buffer(MLPDecodeContext *m, unsigned int substr)
00855 {
00856     SubStream *s = &m->substream[substr];
00857     unsigned int i;
00858     uint32_t seed = s->noisegen_seed;
00859 
00860     for (i = 0; i < m->access_unit_size_pow2; i++) {
00861         uint8_t seed_shr15 = seed >> 15;
00862         m->noise_buffer[i] = noise_table[seed_shr15];
00863         seed = (seed << 8) ^ seed_shr15 ^ (seed_shr15 << 5);
00864     }
00865 
00866     s->noisegen_seed = seed;
00867 }
00868 
00869 
00873 static void rematrix_channels(MLPDecodeContext *m, unsigned int substr)
00874 {
00875     SubStream *s = &m->substream[substr];
00876     unsigned int mat, src_ch, i;
00877     unsigned int maxchan;
00878 
00879     maxchan = s->max_matrix_channel;
00880     if (!s->noise_type) {
00881         generate_2_noise_channels(m, substr);
00882         maxchan += 2;
00883     } else {
00884         fill_noise_buffer(m, substr);
00885     }
00886 
00887     for (mat = 0; mat < s->num_primitive_matrices; mat++) {
00888         int matrix_noise_shift = s->matrix_noise_shift[mat];
00889         unsigned int dest_ch = s->matrix_out_ch[mat];
00890         int32_t mask = MSB_MASK(s->quant_step_size[dest_ch]);
00891         int32_t *coeffs = s->matrix_coeff[mat];
00892         int index  = s->num_primitive_matrices - mat;
00893         int index2 = 2 * index + 1;
00894 
00895         /* TODO: DSPContext? */
00896 
00897         for (i = 0; i < s->blockpos; i++) {
00898             int32_t bypassed_lsb = m->bypassed_lsbs[i][mat];
00899             int32_t *samples = m->sample_buffer[i];
00900             int64_t accum = 0;
00901 
00902             for (src_ch = 0; src_ch <= maxchan; src_ch++)
00903                 accum += (int64_t) samples[src_ch] * coeffs[src_ch];
00904 
00905             if (matrix_noise_shift) {
00906                 index &= m->access_unit_size_pow2 - 1;
00907                 accum += m->noise_buffer[index] << (matrix_noise_shift + 7);
00908                 index += index2;
00909             }
00910 
00911             samples[dest_ch] = ((accum >> 14) & mask) + bypassed_lsb;
00912         }
00913     }
00914 }
00915 
00918 static int output_data(MLPDecodeContext *m, unsigned int substr,
00919                        void *data, int *got_frame_ptr)
00920 {
00921     AVCodecContext *avctx = m->avctx;
00922     SubStream *s = &m->substream[substr];
00923     unsigned int i, out_ch = 0;
00924     int32_t *data_32;
00925     int16_t *data_16;
00926     int ret;
00927     int is32 = (m->avctx->sample_fmt == AV_SAMPLE_FMT_S32);
00928 
00929     if (m->avctx->channels != s->max_matrix_channel + 1) {
00930         av_log(m->avctx, AV_LOG_ERROR, "channel count mismatch\n");
00931         return AVERROR_INVALIDDATA;
00932     }
00933 
00934     /* get output buffer */
00935     m->frame.nb_samples = s->blockpos;
00936     if ((ret = ff_get_buffer(avctx, &m->frame)) < 0) {
00937         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
00938         return ret;
00939     }
00940     data_32 = (int32_t *)m->frame.data[0];
00941     data_16 = (int16_t *)m->frame.data[0];
00942 
00943     for (i = 0; i < s->blockpos; i++) {
00944         for (out_ch = 0; out_ch <= s->max_matrix_channel; out_ch++) {
00945             int mat_ch = s->ch_assign[out_ch];
00946             int32_t sample = m->sample_buffer[i][mat_ch]
00947                           << s->output_shift[mat_ch];
00948             s->lossless_check_data ^= (sample & 0xffffff) << mat_ch;
00949             if (is32) *data_32++ = sample << 8;
00950             else      *data_16++ = sample >> 8;
00951         }
00952     }
00953 
00954     *got_frame_ptr   = 1;
00955     *(AVFrame *)data = m->frame;
00956 
00957     return 0;
00958 }
00959 
00964 static int read_access_unit(AVCodecContext *avctx, void* data,
00965                             int *got_frame_ptr, AVPacket *avpkt)
00966 {
00967     const uint8_t *buf = avpkt->data;
00968     int buf_size = avpkt->size;
00969     MLPDecodeContext *m = avctx->priv_data;
00970     GetBitContext gb;
00971     unsigned int length, substr;
00972     unsigned int substream_start;
00973     unsigned int header_size = 4;
00974     unsigned int substr_header_size = 0;
00975     uint8_t substream_parity_present[MAX_SUBSTREAMS];
00976     uint16_t substream_data_len[MAX_SUBSTREAMS];
00977     uint8_t parity_bits;
00978     int ret;
00979 
00980     if (buf_size < 4)
00981         return 0;
00982 
00983     length = (AV_RB16(buf) & 0xfff) * 2;
00984 
00985     if (length < 4 || length > buf_size)
00986         return AVERROR_INVALIDDATA;
00987 
00988     init_get_bits(&gb, (buf + 4), (length - 4) * 8);
00989 
00990     m->is_major_sync_unit = 0;
00991     if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {
00992         if (read_major_sync(m, &gb) < 0)
00993             goto error;
00994         m->is_major_sync_unit = 1;
00995         header_size += 28;
00996     }
00997 
00998     if (!m->params_valid) {
00999         av_log(m->avctx, AV_LOG_WARNING,
01000                "Stream parameters not seen; skipping frame.\n");
01001         *got_frame_ptr = 0;
01002         return length;
01003     }
01004 
01005     substream_start = 0;
01006 
01007     for (substr = 0; substr < m->num_substreams; substr++) {
01008         int extraword_present, checkdata_present, end, nonrestart_substr;
01009 
01010         extraword_present = get_bits1(&gb);
01011         nonrestart_substr = get_bits1(&gb);
01012         checkdata_present = get_bits1(&gb);
01013         skip_bits1(&gb);
01014 
01015         end = get_bits(&gb, 12) * 2;
01016 
01017         substr_header_size += 2;
01018 
01019         if (extraword_present) {
01020             if (m->avctx->codec_id == CODEC_ID_MLP) {
01021                 av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");
01022                 goto error;
01023             }
01024             skip_bits(&gb, 16);
01025             substr_header_size += 2;
01026         }
01027 
01028         if (!(nonrestart_substr ^ m->is_major_sync_unit)) {
01029             av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");
01030             goto error;
01031         }
01032 
01033         if (end + header_size + substr_header_size > length) {
01034             av_log(m->avctx, AV_LOG_ERROR,
01035                    "Indicated length of substream %d data goes off end of "
01036                    "packet.\n", substr);
01037             end = length - header_size - substr_header_size;
01038         }
01039 
01040         if (end < substream_start) {
01041             av_log(avctx, AV_LOG_ERROR,
01042                    "Indicated end offset of substream %d data "
01043                    "is smaller than calculated start offset.\n",
01044                    substr);
01045             goto error;
01046         }
01047 
01048         if (substr > m->max_decoded_substream)
01049             continue;
01050 
01051         substream_parity_present[substr] = checkdata_present;
01052         substream_data_len[substr] = end - substream_start;
01053         substream_start = end;
01054     }
01055 
01056     parity_bits  = ff_mlp_calculate_parity(buf, 4);
01057     parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);
01058 
01059     if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {
01060         av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");
01061         goto error;
01062     }
01063 
01064     buf += header_size + substr_header_size;
01065 
01066     for (substr = 0; substr <= m->max_decoded_substream; substr++) {
01067         SubStream *s = &m->substream[substr];
01068         init_get_bits(&gb, buf, substream_data_len[substr] * 8);
01069 
01070         m->matrix_changed = 0;
01071         memset(m->filter_changed, 0, sizeof(m->filter_changed));
01072 
01073         s->blockpos = 0;
01074         do {
01075             if (get_bits1(&gb)) {
01076                 if (get_bits1(&gb)) {
01077                     /* A restart header should be present. */
01078                     if (read_restart_header(m, &gb, buf, substr) < 0)
01079                         goto next_substr;
01080                     s->restart_seen = 1;
01081                 }
01082 
01083                 if (!s->restart_seen)
01084                     goto next_substr;
01085                 if (read_decoding_params(m, &gb, substr) < 0)
01086                     goto next_substr;
01087             }
01088 
01089             if (!s->restart_seen)
01090                 goto next_substr;
01091 
01092             if ((ret = read_block_data(m, &gb, substr)) < 0)
01093                 return ret;
01094 
01095             if (get_bits_count(&gb) >= substream_data_len[substr] * 8)
01096                 goto substream_length_mismatch;
01097 
01098         } while (!get_bits1(&gb));
01099 
01100         skip_bits(&gb, (-get_bits_count(&gb)) & 15);
01101 
01102         if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {
01103             int shorten_by;
01104 
01105             if (get_bits(&gb, 16) != 0xD234)
01106                 return AVERROR_INVALIDDATA;
01107 
01108             shorten_by = get_bits(&gb, 16);
01109             if      (m->avctx->codec_id == CODEC_ID_TRUEHD && shorten_by  & 0x2000)
01110                 s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);
01111             else if (m->avctx->codec_id == CODEC_ID_MLP    && shorten_by != 0xD234)
01112                 return AVERROR_INVALIDDATA;
01113 
01114             if (substr == m->max_decoded_substream)
01115                 av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");
01116         }
01117 
01118         if (substream_parity_present[substr]) {
01119             uint8_t parity, checksum;
01120 
01121             if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)
01122                 goto substream_length_mismatch;
01123 
01124             parity   = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);
01125             checksum = ff_mlp_checksum8       (buf, substream_data_len[substr] - 2);
01126 
01127             if ((get_bits(&gb, 8) ^ parity) != 0xa9    )
01128                 av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);
01129             if ( get_bits(&gb, 8)           != checksum)
01130                 av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n"    , substr);
01131         }
01132 
01133         if (substream_data_len[substr] * 8 != get_bits_count(&gb))
01134             goto substream_length_mismatch;
01135 
01136 next_substr:
01137         if (!s->restart_seen)
01138             av_log(m->avctx, AV_LOG_ERROR,
01139                    "No restart header present in substream %d.\n", substr);
01140 
01141         buf += substream_data_len[substr];
01142     }
01143 
01144     rematrix_channels(m, m->max_decoded_substream);
01145 
01146     if ((ret = output_data(m, m->max_decoded_substream, data, got_frame_ptr)) < 0)
01147         return ret;
01148 
01149     return length;
01150 
01151 substream_length_mismatch:
01152     av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);
01153     return AVERROR_INVALIDDATA;
01154 
01155 error:
01156     m->params_valid = 0;
01157     return AVERROR_INVALIDDATA;
01158 }
01159 
01160 AVCodec ff_mlp_decoder = {
01161     .name           = "mlp",
01162     .type           = AVMEDIA_TYPE_AUDIO,
01163     .id             = CODEC_ID_MLP,
01164     .priv_data_size = sizeof(MLPDecodeContext),
01165     .init           = mlp_decode_init,
01166     .decode         = read_access_unit,
01167     .capabilities   = CODEC_CAP_DR1,
01168     .long_name = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
01169 };
01170 
01171 #if CONFIG_TRUEHD_DECODER
01172 AVCodec ff_truehd_decoder = {
01173     .name           = "truehd",
01174     .type           = AVMEDIA_TYPE_AUDIO,
01175     .id             = CODEC_ID_TRUEHD,
01176     .priv_data_size = sizeof(MLPDecodeContext),
01177     .init           = mlp_decode_init,
01178     .decode         = read_access_unit,
01179     .capabilities   = CODEC_CAP_DR1,
01180     .long_name = NULL_IF_CONFIG_SMALL("TrueHD"),
01181 };
01182 #endif /* CONFIG_TRUEHD_DECODER */