libavcodec/alac.c
6d6d7970
 /*
  * ALAC (Apple Lossless Audio Codec) decoder
  * Copyright (c) 2005 David Hammerton
  *
b78e7197
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
6d6d7970
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
b78e7197
  * version 2.1 of the License, or (at your option) any later version.
6d6d7970
  *
b78e7197
  * FFmpeg is distributed in the hope that it will be useful,
6d6d7970
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
b78e7197
  * License along with FFmpeg; if not, write to the Free Software
5509bffa
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6d6d7970
  */
 
 /**
ba87f080
  * @file
6d6d7970
  * ALAC (Apple Lossless Audio Codec) decoder
  * @author 2005 David Hammerton
ad4cd0c2
  * @see http://crazney.net/programs/itunes/alac.html
6d6d7970
  *
e76c7b85
  * Note: This decoder expects a 36-byte QuickTime atom to be
6d6d7970
  * passed through the extradata[_size] fields. This atom is tacked onto
  * the end of an 'alac' stsd atom and has the following format:
a1db1fc4
  *
41ed7ab4
  * 32 bits  atom size
  * 32 bits  tag                  ("alac")
  * 32 bits  tag version          (0)
  * 32 bits  samples per frame    (used when not set explicitly in the frames)
  *  8 bits  compatible version   (0)
  *  8 bits  sample size
  *  8 bits  history mult         (40)
8ef57a0d
  *  8 bits  initial history      (10)
  *  8 bits  rice param limit     (14)
41ed7ab4
  *  8 bits  channels
  * 16 bits  maxRun               (255)
  * 32 bits  max coded frame size (0 means unknown)
  * 32 bits  average bitrate      (0 means unknown)
  * 32 bits  samplerate
6d6d7970
  */
 
cc8163e1
 #include <inttypes.h>
 
a903f8f0
 #include "libavutil/channel_layout.h"
30cac831
 #include "libavutil/opt.h"
6d6d7970
 #include "avcodec.h"
9106a698
 #include "get_bits.h"
f79488d4
 #include "bytestream.h"
594d4d5d
 #include "internal.h"
b28851a1
 #include "thread.h"
becc0ef9
 #include "unary.h"
8858990f
 #include "mathops.h"
5e1bbb8c
 #include "alac_data.h"
b70566d6
 #include "alacdsp.h"
6d6d7970
 
 #define ALAC_EXTRADATA_SIZE 36
 
7f9f771e
 typedef struct ALACContext {
30cac831
     AVClass *class;
6d021b00
     AVCodecContext *avctx;
     GetBitContext gb;
836e8b9b
     int channels;
6d6d7970
 
1b3ef155
     int32_t *predict_error_buffer[2];
     int32_t *output_samples_buffer[2];
     int32_t *extra_bits_buffer[2];
6d6d7970
 
836e8b9b
     uint32_t max_samples_per_frame;
     uint8_t  sample_size;
     uint8_t  rice_history_mult;
     uint8_t  rice_initial_history;
     uint8_t  rice_limit;
12f7c091
     int      sample_rate;
6d6d7970
 
eeb55f5f
     int extra_bits;     /**< number of extra bits beyond 16-bit */
     int nb_samples;     /**< number of samples in the current frame */
5e99df01
 
     int direct_output;
30cac831
     int extra_bit_bug;
b70566d6
 
     ALACDSPContext dsp;
6d6d7970
 } ALACContext;
 
2aebac69
 static inline unsigned int decode_scalar(GetBitContext *gb, int k, int bps)
d9837434
 {
cd632619
     unsigned int x = get_unary_0_9(gb);
5eeba07e
 
     if (x > 8) { /* RICE THRESHOLD */
         /* use alternative encoding */
2aebac69
         x = get_bits_long(gb, bps);
d9837434
     } else if (k != 1) {
a06fdadd
         int extrabits = show_bits(gb, k);
5a5a27c5
 
a06fdadd
         /* multiply x by 2^k - 1, as part of their strange algorithm */
         x = (x << k) - x;
5a5a27c5
 
a06fdadd
         if (extrabits > 1) {
             x += extrabits - 1;
             skip_bits(gb, k);
         } else
             skip_bits(gb, k - 1);
5eeba07e
     }
5a5a27c5
     return x;
 }
 
e4c00aca
 static int rice_decompress(ALACContext *alac, int32_t *output_buffer,
2aebac69
                             int nb_samples, int bps, int rice_history_mult)
6d6d7970
 {
2aebac69
     int i;
6e91f622
     unsigned int history = alac->rice_initial_history;
6d6d7970
     int sign_modifier = 0;
 
2aebac69
     for (i = 0; i < nb_samples; i++) {
cd632619
         int k;
         unsigned int x;
6d6d7970
 
a8469223
         if(get_bits_left(&alac->gb) <= 0)
5079eca2
             return AVERROR_INVALIDDATA;
a8469223
 
eeb55f5f
         /* calculate rice param and decode next value */
8431603a
         k = av_log2((history >> 9) + 3);
d9837434
         k = FFMIN(k, alac->rice_limit);
2aebac69
         x = decode_scalar(&alac->gb, k, bps);
7e6593e9
         x += sign_modifier;
6d6d7970
         sign_modifier = 0;
2aebac69
         output_buffer[i] = (x >> 1) ^ -(x & 1);
6d6d7970
 
eeb55f5f
         /* update the history */
7e6593e9
         if (x > 0xffff)
6d6d7970
             history = 0xffff;
6fd8a28b
         else
7e6593e9
             history +=         x * rice_history_mult -
                        ((history * rice_history_mult) >> 9);
6d6d7970
 
         /* special case: there may be compressed blocks of 0 */
2aebac69
         if ((history < 128) && (i + 1 < nb_samples)) {
91620a04
             int block_size;
6d6d7970
 
eeb55f5f
             /* calculate rice param and decode block size */
             k = 7 - av_log2(history) + ((history + 16) >> 6);
d9837434
             k = FFMIN(k, alac->rice_limit);
             block_size = decode_scalar(&alac->gb, k, 16);
6d6d7970
 
             if (block_size > 0) {
2aebac69
                 if (block_size >= nb_samples - i) {
                     av_log(alac->avctx, AV_LOG_ERROR,
                            "invalid zero block size of %d %d %d\n", block_size,
                            nb_samples, i);
                     block_size = nb_samples - i - 1;
83e9a67d
                 }
2aebac69
                 memset(&output_buffer[i + 1], 0,
4bcd637d
                        block_size * sizeof(*output_buffer));
2aebac69
                 i += block_size;
6d6d7970
             }
5177413d
             if (block_size <= 0xffff)
                 sign_modifier = 1;
6d6d7970
             history = 0;
         }
     }
a8469223
     return 0;
6d6d7970
 }
 
321c3138
 static inline int sign_only(int v)
 {
     return v ? FFSIGN(v) : 0;
 }
6d6d7970
 
ae3d6a33
 static void lpc_prediction(int32_t *error_buffer, uint32_t *buffer_out,
2aebac69
                            int nb_samples, int bps, int16_t *lpc_coefs,
                            int lpc_order, int lpc_quant)
6d6d7970
 {
     int i;
ae3d6a33
     uint32_t *pred = buffer_out;
6d6d7970
 
     /* first sample always copies */
     *buffer_out = *error_buffer;
 
2aebac69
     if (nb_samples <= 1)
9a6c528e
         return;
10024d44
 
2aebac69
     if (!lpc_order) {
4bcd637d
         memcpy(&buffer_out[1], &error_buffer[1],
2aebac69
                (nb_samples - 1) * sizeof(*buffer_out));
6d6d7970
         return;
     }
 
2aebac69
     if (lpc_order == 31) {
2ac17375
         /* simple 1st-order prediction */
2aebac69
         for (i = 1; i < nb_samples; i++) {
01880d28
             buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i],
2aebac69
                                         bps);
6d6d7970
         }
         return;
     }
 
     /* read warm-up samples */
fd4f4923
     for (i = 1; i <= lpc_order && i < nb_samples; i++)
fb57e913
         buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i], bps);
6d6d7970
 
2ac17375
     /* NOTE: 4 and 8 are very common cases that could be optimized. */
6d6d7970
 
fb57e913
     for (; i < nb_samples; i++) {
d0c0bf0d
         int j;
abc4376b
         int val = 0;
ae3d6a33
         unsigned error_val = error_buffer[i];
f2515cd6
         int error_sign;
fb57e913
         int d = *pred++;
d0c0bf0d
 
eeb55f5f
         /* LPC prediction */
         for (j = 0; j < lpc_order; j++)
fb57e913
             val += (pred[j] - d) * lpc_coefs[j];
44b73a05
         val = (val + (1LL << (lpc_quant - 1))) >> lpc_quant;
ebd4c3ad
         val += d + error_val;
fb57e913
         buffer_out[i] = sign_extend(val, bps);
6d6d7970
 
f2515cd6
         /* adapt LPC coefficients */
         error_sign = sign_only(error_val);
         if (error_sign) {
0831cbfe
             for (j = 0; j < lpc_order && (int)(error_val * error_sign) > 0; j++) {
abc4376b
                 int sign;
fb57e913
                 val  = d - pred[j];
f2515cd6
                 sign = sign_only(val) * error_sign;
2aebac69
                 lpc_coefs[j] -= sign;
7686ba1f
                 val *= (unsigned)sign;
6a865cec
                 error_val -= (val >> lpc_quant) * (j + 1U);
6d6d7970
             }
         }
     }
 }
 
5cd597f2
 static int decode_element(AVCodecContext *avctx, AVFrame *frame, int ch_index,
81c9e2e6
                           int channels)
f430c7b6
 {
6d021b00
     ALACContext *alac = avctx->priv_data;
eeb55f5f
     int has_size, bps, is_compressed, decorr_shift, decorr_left_weight, ret;
81c9e2e6
     uint32_t output_samples;
eeb55f5f
     int i, ch;
f770ee03
 
2ac17375
     skip_bits(&alac->gb, 4);  /* element instance tag */
     skip_bits(&alac->gb, 12); /* unused header bits */
6d6d7970
 
2ac17375
     /* the number of output samples is stored in the frame */
2aebac69
     has_size = get_bits1(&alac->gb);
6d6d7970
 
d251c85d
     alac->extra_bits = get_bits(&alac->gb, 2) << 3;
2aebac69
     bps = alac->sample_size - alac->extra_bits + channels - 1;
8f49176e
     if (bps > 32) {
67deba8a
         avpriv_report_missing_feature(avctx, "bps %d", bps);
cd632619
         return AVERROR_PATCHWELCOME;
     }
8f49176e
     if (bps < 1)
         return AVERROR_INVALIDDATA;
6d6d7970
 
586e5bd9
     /* whether the frame is compressed */
46043962
     is_compressed = !get_bits1(&alac->gb);
6d6d7970
 
2aebac69
     if (has_size)
81c9e2e6
         output_samples = get_bits_long(&alac->gb, 32);
     else
         output_samples = alac->max_samples_per_frame;
     if (!output_samples || output_samples > alac->max_samples_per_frame) {
cc8163e1
         av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %"PRIu32"\n",
81c9e2e6
                output_samples);
0eea2129
         return AVERROR_INVALIDDATA;
     }
81c9e2e6
     if (!alac->nb_samples) {
b28851a1
         ThreadFrame tframe = { .f = frame };
81c9e2e6
         /* get output buffer */
5cd597f2
         frame->nb_samples = output_samples;
b28851a1
         if ((ret = ff_thread_get_buffer(avctx, &tframe, 0)) < 0)
81c9e2e6
             return ret;
     } else if (output_samples != alac->nb_samples) {
cc8163e1
         av_log(avctx, AV_LOG_ERROR, "sample count mismatch: %"PRIu32" != %d\n",
81c9e2e6
                output_samples, alac->nb_samples);
         return AVERROR_INVALIDDATA;
95801b6a
     }
81c9e2e6
     alac->nb_samples = output_samples;
3c033d00
     if (alac->direct_output) {
4cd22b77
         for (ch = 0; ch < channels; ch++)
5cd597f2
             alac->output_samples_buffer[ch] = (int32_t *)frame->extended_data[ch_index + ch];
4cd22b77
     }
6d6d7970
 
46043962
     if (is_compressed) {
2aebac69
         int16_t lpc_coefs[2][32];
         int lpc_order[2];
1b3ef155
         int prediction_type[2];
2aebac69
         int lpc_quant[2];
         int rice_history_mult[2];
6d6d7970
 
4b657a1b
         if (!alac->rice_limit) {
243e8443
             avpriv_request_sample(alac->avctx,
                                   "Compression with rice limit 0");
4b657a1b
             return AVERROR(ENOSYS);
         }
 
2aebac69
         decorr_shift       = get_bits(&alac->gb, 8);
         decorr_left_weight = get_bits(&alac->gb, 8);
6d6d7970
 
01200f12
         for (ch = 0; ch < channels; ch++) {
2aebac69
             prediction_type[ch]   = get_bits(&alac->gb, 4);
             lpc_quant[ch]         = get_bits(&alac->gb, 4);
             rice_history_mult[ch] = get_bits(&alac->gb, 3);
             lpc_order[ch]         = get_bits(&alac->gb, 5);
6d6d7970
 
a6474b89
             if (lpc_order[ch] >= alac->max_samples_per_frame || !lpc_quant[ch])
59480abc
                 return AVERROR_INVALIDDATA;
 
6d6d7970
             /* read the predictor table */
fb57e913
             for (i = lpc_order[ch] - 1; i >= 0; i--)
2aebac69
                 lpc_coefs[ch][i] = get_sbits(&alac->gb, 16);
586e5bd9
         }
6d6d7970
 
d251c85d
         if (alac->extra_bits) {
7a50ec67
             for (i = 0; i < alac->nb_samples; i++) {
a8469223
                 if(get_bits_left(&alac->gb) <= 0)
5079eca2
                     return AVERROR_INVALIDDATA;
f430c7b6
                 for (ch = 0; ch < channels; ch++)
d251c85d
                     alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
f430c7b6
             }
         }
01200f12
         for (ch = 0; ch < channels; ch++) {
e4c00aca
             int ret=rice_decompress(alac, alac->predict_error_buffer[ch],
2aebac69
                             alac->nb_samples, bps,
                             rice_history_mult[ch] * alac->rice_history_mult / 4);
a8469223
             if(ret<0)
                 return ret;
6d6d7970
 
e49d2130
             /* adaptive FIR filter */
             if (prediction_type[ch] == 15) {
                 /* Prediction type 15 runs the adaptive FIR twice.
                  * The first pass uses the special-case coef_num = 31, while
                  * the second pass uses the coefs from the bitstream.
                  *
                  * However, this prediction type is not currently used by the
                  * reference encoder.
10fb5763
                  */
2aebac69
                 lpc_prediction(alac->predict_error_buffer[ch],
                                alac->predict_error_buffer[ch],
                                alac->nb_samples, bps, NULL, 31, 0);
e49d2130
             } else if (prediction_type[ch] > 0) {
                 av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
                        prediction_type[ch]);
6d6d7970
             }
2aebac69
             lpc_prediction(alac->predict_error_buffer[ch],
                            alac->output_samples_buffer[ch], alac->nb_samples,
                            bps, lpc_coefs[ch], lpc_order[ch], lpc_quant[ch]);
586e5bd9
         }
     } else {
         /* not compressed, easy case */
7a50ec67
         for (i = 0; i < alac->nb_samples; i++) {
a8469223
             if(get_bits_left(&alac->gb) <= 0)
5079eca2
                 return AVERROR_INVALIDDATA;
01200f12
             for (ch = 0; ch < channels; ch++) {
eeb55f5f
                 alac->output_samples_buffer[ch][i] =
                          get_sbits_long(&alac->gb, alac->sample_size);
f430c7b6
             }
         }
eeb55f5f
         alac->extra_bits   = 0;
2aebac69
         decorr_shift       = 0;
         decorr_left_weight = 0;
586e5bd9
     }
6d6d7970
 
b70566d6
     if (channels == 2) {
         if (alac->extra_bits && alac->extra_bit_bug) {
             alac->dsp.append_extra_bits[1](alac->output_samples_buffer, alac->extra_bits_buffer,
                                            alac->extra_bits, channels, alac->nb_samples);
         }
30cac831
 
b70566d6
         if (decorr_left_weight) {
             alac->dsp.decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
                                          decorr_shift, decorr_left_weight);
         }
e739d351
 
b70566d6
         if (alac->extra_bits && !alac->extra_bit_bug) {
             alac->dsp.append_extra_bits[1](alac->output_samples_buffer, alac->extra_bits_buffer,
                                            alac->extra_bits, channels, alac->nb_samples);
         }
     } else if (alac->extra_bits) {
         alac->dsp.append_extra_bits[0](alac->output_samples_buffer, alac->extra_bits_buffer,
                                        alac->extra_bits, channels, alac->nb_samples);
c39bddd3
     }
 
836e8b9b
     switch(alac->sample_size) {
6cda74c1
     case 16: {
81c9e2e6
         for (ch = 0; ch < channels; ch++) {
5cd597f2
             int16_t *outbuffer = (int16_t *)frame->extended_data[ch_index + ch];
73dc0db4
             for (i = 0; i < alac->nb_samples; i++)
                 *outbuffer++ = alac->output_samples_buffer[ch][i];
6cda74c1
         }}
586e5bd9
         break;
c5d2d3dc
     case 20: {
         for (ch = 0; ch < channels; ch++) {
             for (i = 0; i < alac->nb_samples; i++)
22e51e95
                 alac->output_samples_buffer[ch][i] *= 1U << 12;
c5d2d3dc
         }}
         break;
6cda74c1
     case 24: {
81c9e2e6
         for (ch = 0; ch < channels; ch++) {
73dc0db4
             for (i = 0; i < alac->nb_samples; i++)
22e51e95
                 alac->output_samples_buffer[ch][i] *= 1U << 8;
6cda74c1
         }}
586e5bd9
         break;
     }
6d6d7970
 
81c9e2e6
     return 0;
 }
 
 static int alac_decode_frame(AVCodecContext *avctx, void *data,
                              int *got_frame_ptr, AVPacket *avpkt)
 {
     ALACContext *alac = avctx->priv_data;
5cd597f2
     AVFrame *frame    = data;
5e1bbb8c
     enum AlacRawDataBlockType element;
81c9e2e6
     int channels;
81f548de
     int ch, ret, got_end;
81c9e2e6
 
b257d9a0
     if ((ret = init_get_bits8(&alac->gb, avpkt->data, avpkt->size)) < 0)
         return ret;
81c9e2e6
 
81f548de
     got_end = 0;
81c9e2e6
     alac->nb_samples = 0;
     ch = 0;
81f548de
     while (get_bits_left(&alac->gb) >= 3) {
81c9e2e6
         element = get_bits(&alac->gb, 3);
81f548de
         if (element == TYPE_END) {
             got_end = 1;
81c9e2e6
             break;
81f548de
         }
81c9e2e6
         if (element > TYPE_CPE && element != TYPE_LFE) {
67deba8a
             avpriv_report_missing_feature(avctx, "Syntax element %d", element);
81c9e2e6
             return AVERROR_PATCHWELCOME;
89fc7e36
         }
81c9e2e6
 
         channels = (element == TYPE_CPE) ? 2 : 1;
35cbc98b
         if (ch + channels > alac->channels ||
             ff_alac_channel_layout_offsets[alac->channels - 1][ch] + channels > alac->channels) {
81c9e2e6
             av_log(avctx, AV_LOG_ERROR, "invalid element channel count\n");
             return AVERROR_INVALIDDATA;
         }
 
5cd597f2
         ret = decode_element(avctx, frame,
5e1bbb8c
                              ff_alac_channel_layout_offsets[alac->channels - 1][ch],
1b3ef155
                              channels);
81f548de
         if (ret < 0 && get_bits_left(&alac->gb))
81c9e2e6
             return ret;
 
         ch += channels;
586e5bd9
     }
81f548de
     if (!got_end) {
         av_log(avctx, AV_LOG_ERROR, "no end tag found. incomplete packet.\n");
         return AVERROR_INVALIDDATA;
     }
6d6d7970
 
eeb55f5f
     if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8) {
5138ff14
         av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
                avpkt->size * 8 - get_bits_count(&alac->gb));
eeb55f5f
     }
e5ab7379
 
f09aa73b
     if (alac->channels == ch && alac->nb_samples)
e11983bd
         *got_frame_ptr = 1;
d5af4007
     else
         av_log(avctx, AV_LOG_WARNING, "Failed to decode all channels\n");
0eea2129
 
5138ff14
     return avpkt->size;
6d6d7970
 }
 
53df079a
 static av_cold int alac_decode_close(AVCodecContext *avctx)
 {
     ALACContext *alac = avctx->priv_data;
 
63cf54df
     int ch;
1b3ef155
     for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
836e8b9b
         av_freep(&alac->predict_error_buffer[ch]);
5e99df01
         if (!alac->direct_output)
73dc0db4
             av_freep(&alac->output_samples_buffer[ch]);
63cf54df
         av_freep(&alac->extra_bits_buffer[ch]);
53df079a
     }
 
     return 0;
 }
 
 static int allocate_buffers(ALACContext *alac)
 {
63cf54df
     int ch;
53064e13
     unsigned buf_size = alac->max_samples_per_frame * sizeof(int32_t);
53df079a
 
f7068bf2
     for (ch = 0; ch < 2; ch++) {
         alac->predict_error_buffer[ch]  = NULL;
         alac->output_samples_buffer[ch] = NULL;
         alac->extra_bits_buffer[ch]     = NULL;
     }
 
f3e5a784
     for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
836e8b9b
         FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
68f7e9cd
                          buf_size, buf_alloc_fail);
53df079a
 
eb011f73
         alac->direct_output = alac->sample_size > 16;
5e99df01
         if (!alac->direct_output) {
73dc0db4
             FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
72254b19
                              buf_size + AV_INPUT_BUFFER_PADDING_SIZE, buf_alloc_fail);
73dc0db4
         }
53df079a
 
68f7e9cd
         FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
72254b19
                          buf_size + AV_INPUT_BUFFER_PADDING_SIZE, buf_alloc_fail);
53df079a
     }
     return 0;
68f7e9cd
 buf_alloc_fail:
     alac_decode_close(alac->avctx);
     return AVERROR(ENOMEM);
53df079a
 }
 
 static int alac_set_info(ALACContext *alac)
 {
c3bbd0b5
     GetByteContext gb;
53df079a
 
c3bbd0b5
     bytestream2_init(&gb, alac->avctx->extradata,
                      alac->avctx->extradata_size);
53df079a
 
c3bbd0b5
     bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
53df079a
 
836e8b9b
     alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
f7c58831
     if (!alac->max_samples_per_frame ||
3357b68b
         alac->max_samples_per_frame > 4096 * 4096) {
cc8163e1
         av_log(alac->avctx, AV_LOG_ERROR,
                "max samples per frame invalid: %"PRIu32"\n",
7a206eb3
                alac->max_samples_per_frame);
c3bbd0b5
         return AVERROR_INVALIDDATA;
     }
     bytestream2_skipu(&gb, 1);  // compatible version
836e8b9b
     alac->sample_size          = bytestream2_get_byteu(&gb);
     alac->rice_history_mult    = bytestream2_get_byteu(&gb);
     alac->rice_initial_history = bytestream2_get_byteu(&gb);
     alac->rice_limit           = bytestream2_get_byteu(&gb);
     alac->channels             = bytestream2_get_byteu(&gb);
c3bbd0b5
     bytestream2_get_be16u(&gb); // maxRun
     bytestream2_get_be32u(&gb); // max coded frame size
     bytestream2_get_be32u(&gb); // average bitrate
12f7c091
     alac->sample_rate          = bytestream2_get_be32u(&gb);
53df079a
 
     return 0;
 }
 
98a6fff9
 static av_cold int alac_decode_init(AVCodecContext * avctx)
6d6d7970
 {
53df079a
     int ret;
6d021b00
     ALACContext *alac = avctx->priv_data;
     alac->avctx = avctx;
6d6d7970
 
313b52fb
     /* initialize from the extradata */
68a04b0c
     if (alac->avctx->extradata_size < ALAC_EXTRADATA_SIZE) {
2f9903f6
         av_log(avctx, AV_LOG_ERROR, "extradata is too small\n");
68a04b0c
         return AVERROR_INVALIDDATA;
313b52fb
     }
5079eca2
     if ((ret = alac_set_info(alac)) < 0) {
c2502b7b
         av_log(avctx, AV_LOG_ERROR, "set_info failed\n");
5079eca2
         return ret;
313b52fb
     }
 
836e8b9b
     switch (alac->sample_size) {
eb011f73
     case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
0f26f3d5
              break;
c5d2d3dc
     case 20:
6482bd88
     case 24:
eb011f73
     case 32: avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
0f26f3d5
              break;
6d97484d
     default: avpriv_request_sample(avctx, "Sample depth %d", alac->sample_size);
b316af7a
              return AVERROR_PATCHWELCOME;
0f26f3d5
     }
46a86c61
     avctx->bits_per_raw_sample = alac->sample_size;
12f7c091
     avctx->sample_rate         = alac->sample_rate;
6d6d7970
 
836e8b9b
     if (alac->channels < 1) {
dcaa83a0
         av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
836e8b9b
         alac->channels = avctx->channels;
dcaa83a0
     } else {
5e1bbb8c
         if (alac->channels > ALAC_MAX_CHANNELS)
836e8b9b
             alac->channels = avctx->channels;
dcaa83a0
         else
836e8b9b
             avctx->channels = alac->channels;
dcaa83a0
     }
71949ef7
     if (avctx->channels > ALAC_MAX_CHANNELS || avctx->channels <= 0 ) {
67deba8a
         avpriv_report_missing_feature(avctx, "Channel count %d",
                                       avctx->channels);
dcaa83a0
         return AVERROR_PATCHWELCOME;
     }
5e1bbb8c
     avctx->channel_layout = ff_alac_channel_layouts[alac->channels - 1];
6d6d7970
 
53df079a
     if ((ret = allocate_buffers(alac)) < 0) {
         av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
         return ret;
153696a6
     }
6d6d7970
 
b70566d6
     ff_alacdsp_init(&alac->dsp);
 
6d6d7970
     return 0;
 }
 
30cac831
 static const AVOption options[] = {
     { "extra_bits_bug", "Force non-standard decoding process",
fb99ef0b
       offsetof(ALACContext, extra_bit_bug), AV_OPT_TYPE_BOOL, { .i64 = 0 },
30cac831
       0, 1, AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM },
     { NULL },
 };
 
 static const AVClass alac_class = {
     .class_name = "alac",
     .item_name  = av_default_item_name,
     .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
e7e2df27
 AVCodec ff_alac_decoder = {
ec6402b7
     .name           = "alac",
b2bed932
     .long_name      = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
ec6402b7
     .type           = AVMEDIA_TYPE_AUDIO,
36ef5369
     .id             = AV_CODEC_ID_ALAC,
ec6402b7
     .priv_data_size = sizeof(ALACContext),
     .init           = alac_decode_init,
     .close          = alac_decode_close,
     .decode         = alac_decode_frame,
444e9874
     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,
30cac831
     .priv_class     = &alac_class
6d6d7970
 };