3 * Copyright (c) 2008 Jaikrishnan Menon <realityman@gmx.net>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 #define DEFAULT_FRAME_SIZE 4096
30 #define MAX_CHANNELS 8
31 #define ALAC_EXTRADATA_SIZE 36
32 #define ALAC_FRAME_HEADER_SIZE 55
33 #define ALAC_FRAME_FOOTER_SIZE 3
35 #define ALAC_ESCAPE_CODE 0x1FF
36 #define ALAC_MAX_LPC_ORDER 30
37 #define DEFAULT_MAX_PRED_ORDER 6
38 #define DEFAULT_MIN_PRED_ORDER 4
39 #define ALAC_MAX_LPC_PRECISION 9
40 #define ALAC_MAX_LPC_SHIFT 9
42 #define ALAC_CHMODE_LEFT_RIGHT 0
43 #define ALAC_CHMODE_LEFT_SIDE 1
44 #define ALAC_CHMODE_RIGHT_SIDE 2
45 #define ALAC_CHMODE_MID_SIDE 3
47 typedef struct RiceContext {
54 typedef struct AlacLPCContext {
56 int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
60 typedef struct AlacEncodeContext {
61 int frame_size; /**< current frame size */
62 int verbatim; /**< current frame verbatim mode flag */
63 int compression_level;
64 int min_prediction_order;
65 int max_prediction_order;
66 int max_coded_frame_size;
67 int write_sample_size;
69 int32_t sample_buf[MAX_CHANNELS][DEFAULT_FRAME_SIZE];
70 int32_t predictor_buf[DEFAULT_FRAME_SIZE];
71 int interlacing_shift;
72 int interlacing_leftweight;
75 AlacLPCContext lpc[MAX_CHANNELS];
77 AVCodecContext *avctx;
81 static void init_sample_buffers(AlacEncodeContext *s,
82 uint8_t * const *samples)
85 int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
86 s->avctx->bits_per_raw_sample;
88 #define COPY_SAMPLES(type) do { \
89 for (ch = 0; ch < s->avctx->channels; ch++) { \
90 int32_t *bptr = s->sample_buf[ch]; \
91 const type *sptr = (const type *)samples[ch]; \
92 for (i = 0; i < s->frame_size; i++) \
93 bptr[i] = sptr[i] >> shift; \
97 if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S32P)
98 COPY_SAMPLES(int32_t);
100 COPY_SAMPLES(int16_t);
103 static void encode_scalar(AlacEncodeContext *s, int x,
104 int k, int write_sample_size)
108 k = FFMIN(k, s->rc.k_modifier);
109 divisor = (1<<k) - 1;
114 // write escape code and sample value directly
115 put_bits(&s->pbctx, 9, ALAC_ESCAPE_CODE);
116 put_bits(&s->pbctx, write_sample_size, x);
119 put_bits(&s->pbctx, q, (1<<q) - 1);
120 put_bits(&s->pbctx, 1, 0);
124 put_bits(&s->pbctx, k, r+1);
126 put_bits(&s->pbctx, k-1, 0);
131 static void write_frame_header(AlacEncodeContext *s)
135 if (s->frame_size < DEFAULT_FRAME_SIZE)
138 put_bits(&s->pbctx, 3, s->avctx->channels-1); // No. of channels -1
139 put_bits(&s->pbctx, 16, 0); // Seems to be zero
140 put_bits(&s->pbctx, 1, encode_fs); // Sample count is in the header
141 put_bits(&s->pbctx, 2, s->extra_bits >> 3); // Extra bytes (for 24-bit)
142 put_bits(&s->pbctx, 1, s->verbatim); // Audio block is verbatim
144 put_bits32(&s->pbctx, s->frame_size); // No. of samples in the frame
147 static void calc_predictor_params(AlacEncodeContext *s, int ch)
149 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
150 int shift[MAX_LPC_ORDER];
153 if (s->compression_level == 1) {
154 s->lpc[ch].lpc_order = 6;
155 s->lpc[ch].lpc_quant = 6;
156 s->lpc[ch].lpc_coeff[0] = 160;
157 s->lpc[ch].lpc_coeff[1] = -190;
158 s->lpc[ch].lpc_coeff[2] = 170;
159 s->lpc[ch].lpc_coeff[3] = -130;
160 s->lpc[ch].lpc_coeff[4] = 80;
161 s->lpc[ch].lpc_coeff[5] = -25;
163 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, s->sample_buf[ch],
165 s->min_prediction_order,
166 s->max_prediction_order,
167 ALAC_MAX_LPC_PRECISION, coefs, shift,
168 FF_LPC_TYPE_LEVINSON, 0,
169 ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
171 s->lpc[ch].lpc_order = opt_order;
172 s->lpc[ch].lpc_quant = shift[opt_order-1];
173 memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
177 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
184 /* calculate sum of 2nd order residual for each channel */
185 sum[0] = sum[1] = sum[2] = sum[3] = 0;
186 for (i = 2; i < n; i++) {
187 lt = left_ch[i] - 2 * left_ch[i - 1] + left_ch[i - 2];
188 rt = right_ch[i] - 2 * right_ch[i - 1] + right_ch[i - 2];
189 sum[2] += FFABS((lt + rt) >> 1);
190 sum[3] += FFABS(lt - rt);
195 /* calculate score for each mode */
196 score[0] = sum[0] + sum[1];
197 score[1] = sum[0] + sum[3];
198 score[2] = sum[1] + sum[3];
199 score[3] = sum[2] + sum[3];
201 /* return mode with lowest score */
203 for (i = 1; i < 4; i++) {
204 if (score[i] < score[best])
210 static void alac_stereo_decorrelation(AlacEncodeContext *s)
212 int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
213 int i, mode, n = s->frame_size;
216 mode = estimate_stereo_mode(left, right, n);
219 case ALAC_CHMODE_LEFT_RIGHT:
220 s->interlacing_leftweight = 0;
221 s->interlacing_shift = 0;
223 case ALAC_CHMODE_LEFT_SIDE:
224 for (i = 0; i < n; i++)
225 right[i] = left[i] - right[i];
226 s->interlacing_leftweight = 1;
227 s->interlacing_shift = 0;
229 case ALAC_CHMODE_RIGHT_SIDE:
230 for (i = 0; i < n; i++) {
232 right[i] = left[i] - right[i];
233 left[i] = tmp + (right[i] >> 31);
235 s->interlacing_leftweight = 1;
236 s->interlacing_shift = 31;
239 for (i = 0; i < n; i++) {
241 left[i] = (tmp + right[i]) >> 1;
242 right[i] = tmp - right[i];
244 s->interlacing_leftweight = 1;
245 s->interlacing_shift = 1;
250 static void alac_linear_predictor(AlacEncodeContext *s, int ch)
253 AlacLPCContext lpc = s->lpc[ch];
255 if (lpc.lpc_order == 31) {
256 s->predictor_buf[0] = s->sample_buf[ch][0];
258 for (i = 1; i < s->frame_size; i++) {
259 s->predictor_buf[i] = s->sample_buf[ch][i ] -
260 s->sample_buf[ch][i - 1];
266 // generalised linear predictor
268 if (lpc.lpc_order > 0) {
269 int32_t *samples = s->sample_buf[ch];
270 int32_t *residual = s->predictor_buf;
272 // generate warm-up samples
273 residual[0] = samples[0];
274 for (i = 1; i <= lpc.lpc_order; i++)
275 residual[i] = samples[i] - samples[i-1];
277 // perform lpc on remaining samples
278 for (i = lpc.lpc_order + 1; i < s->frame_size; i++) {
279 int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
281 for (j = 0; j < lpc.lpc_order; j++) {
282 sum += (samples[lpc.lpc_order-j] - samples[0]) *
286 sum >>= lpc.lpc_quant;
288 residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
289 s->write_sample_size);
290 res_val = residual[i];
293 int index = lpc.lpc_order - 1;
294 int neg = (res_val < 0);
296 while (index >= 0 && (neg ? (res_val < 0) : (res_val > 0))) {
297 int val = samples[0] - samples[lpc.lpc_order - index];
298 int sign = (val ? FFSIGN(val) : 0);
303 lpc.lpc_coeff[index] -= sign;
305 res_val -= (val >> lpc.lpc_quant) * (lpc.lpc_order - index);
314 static void alac_entropy_coder(AlacEncodeContext *s)
316 unsigned int history = s->rc.initial_history;
317 int sign_modifier = 0, i, k;
318 int32_t *samples = s->predictor_buf;
320 for (i = 0; i < s->frame_size;) {
323 k = av_log2((history >> 9) + 3);
325 x = -2 * (*samples) -1;
331 encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
333 history += x * s->rc.history_mult -
334 ((history * s->rc.history_mult) >> 9);
340 if (history < 128 && i < s->frame_size) {
341 unsigned int block_size = 0;
343 k = 7 - av_log2(history) + ((history + 16) >> 6);
345 while (*samples == 0 && i < s->frame_size) {
350 encode_scalar(s, block_size, k, 16);
351 sign_modifier = (block_size <= 0xFFFF);
358 static int write_frame(AlacEncodeContext *s, AVPacket *avpkt,
359 uint8_t * const *samples)
362 int prediction_type = 0;
363 PutBitContext *pb = &s->pbctx;
365 init_put_bits(pb, avpkt->data, avpkt->size);
368 write_frame_header(s);
369 /* samples are channel-interleaved in verbatim mode */
370 if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S32P) {
371 int shift = 32 - s->avctx->bits_per_raw_sample;
372 int32_t * const *samples_s32 = (int32_t * const *)samples;
373 for (i = 0; i < s->frame_size; i++)
374 for (j = 0; j < s->avctx->channels; j++)
375 put_sbits(pb, s->avctx->bits_per_raw_sample,
376 samples_s32[j][i] >> shift);
378 int16_t * const *samples_s16 = (int16_t * const *)samples;
379 for (i = 0; i < s->frame_size; i++)
380 for (j = 0; j < s->avctx->channels; j++)
381 put_sbits(pb, s->avctx->bits_per_raw_sample,
385 init_sample_buffers(s, samples);
386 write_frame_header(s);
388 if (s->avctx->channels == 2)
389 alac_stereo_decorrelation(s);
390 put_bits(pb, 8, s->interlacing_shift);
391 put_bits(pb, 8, s->interlacing_leftweight);
393 for (i = 0; i < s->avctx->channels; i++) {
394 calc_predictor_params(s, i);
396 put_bits(pb, 4, prediction_type);
397 put_bits(pb, 4, s->lpc[i].lpc_quant);
399 put_bits(pb, 3, s->rc.rice_modifier);
400 put_bits(pb, 5, s->lpc[i].lpc_order);
401 // predictor coeff. table
402 for (j = 0; j < s->lpc[i].lpc_order; j++)
403 put_sbits(pb, 16, s->lpc[i].lpc_coeff[j]);
406 // write extra bits if needed
408 uint32_t mask = (1 << s->extra_bits) - 1;
409 for (i = 0; i < s->frame_size; i++) {
410 for (j = 0; j < s->avctx->channels; j++) {
411 put_bits(pb, s->extra_bits, s->sample_buf[j][i] & mask);
412 s->sample_buf[j][i] >>= s->extra_bits;
417 // apply lpc and entropy coding to audio samples
419 for (i = 0; i < s->avctx->channels; i++) {
420 alac_linear_predictor(s, i);
422 // TODO: determine when this will actually help. for now it's not used.
423 if (prediction_type == 15) {
424 // 2nd pass 1st order filter
425 for (j = s->frame_size - 1; j > 0; j--)
426 s->predictor_buf[j] -= s->predictor_buf[j - 1];
429 alac_entropy_coder(s);
434 return put_bits_count(pb) >> 3;
437 static av_always_inline int get_max_frame_size(int frame_size, int ch, int bps)
439 int header_bits = 23 + 32 * (frame_size < DEFAULT_FRAME_SIZE);
440 return FFALIGN(header_bits + bps * ch * frame_size + 3, 8) / 8;
443 static av_cold int alac_encode_close(AVCodecContext *avctx)
445 AlacEncodeContext *s = avctx->priv_data;
446 ff_lpc_end(&s->lpc_ctx);
447 av_freep(&avctx->extradata);
448 avctx->extradata_size = 0;
449 av_freep(&avctx->coded_frame);
453 static av_cold int alac_encode_init(AVCodecContext *avctx)
455 AlacEncodeContext *s = avctx->priv_data;
457 uint8_t *alac_extradata;
459 avctx->frame_size = s->frame_size = DEFAULT_FRAME_SIZE;
461 /* TODO: Correctly implement multi-channel ALAC.
462 It is similar to multi-channel AAC, in that it has a series of
463 single-channel (SCE), channel-pair (CPE), and LFE elements. */
464 if (avctx->channels > 2) {
465 av_log(avctx, AV_LOG_ERROR, "only mono or stereo input is currently supported\n");
466 return AVERROR_PATCHWELCOME;
469 if (avctx->sample_fmt == AV_SAMPLE_FMT_S32P) {
470 if (avctx->bits_per_raw_sample != 24)
471 av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
472 avctx->bits_per_raw_sample = 24;
474 avctx->bits_per_raw_sample = 16;
478 // Set default compression level
479 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
480 s->compression_level = 2;
482 s->compression_level = av_clip(avctx->compression_level, 0, 2);
484 // Initialize default Rice parameters
485 s->rc.history_mult = 40;
486 s->rc.initial_history = 10;
487 s->rc.k_modifier = 14;
488 s->rc.rice_modifier = 4;
490 s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,
492 avctx->bits_per_raw_sample);
494 avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
495 if (!avctx->extradata) {
496 ret = AVERROR(ENOMEM);
499 avctx->extradata_size = ALAC_EXTRADATA_SIZE;
501 alac_extradata = avctx->extradata;
502 AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);
503 AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));
504 AV_WB32(alac_extradata+12, avctx->frame_size);
505 AV_WB8 (alac_extradata+17, avctx->bits_per_raw_sample);
506 AV_WB8 (alac_extradata+21, avctx->channels);
507 AV_WB32(alac_extradata+24, s->max_coded_frame_size);
508 AV_WB32(alac_extradata+28,
509 avctx->sample_rate * avctx->channels * avctx->bits_per_raw_sample); // average bitrate
510 AV_WB32(alac_extradata+32, avctx->sample_rate);
512 // Set relevant extradata fields
513 if (s->compression_level > 0) {
514 AV_WB8(alac_extradata+18, s->rc.history_mult);
515 AV_WB8(alac_extradata+19, s->rc.initial_history);
516 AV_WB8(alac_extradata+20, s->rc.k_modifier);
519 s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
520 if (avctx->min_prediction_order >= 0) {
521 if (avctx->min_prediction_order < MIN_LPC_ORDER ||
522 avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
523 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
524 avctx->min_prediction_order);
525 ret = AVERROR(EINVAL);
529 s->min_prediction_order = avctx->min_prediction_order;
532 s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
533 if (avctx->max_prediction_order >= 0) {
534 if (avctx->max_prediction_order < MIN_LPC_ORDER ||
535 avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
536 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
537 avctx->max_prediction_order);
538 ret = AVERROR(EINVAL);
542 s->max_prediction_order = avctx->max_prediction_order;
545 if (s->max_prediction_order < s->min_prediction_order) {
546 av_log(avctx, AV_LOG_ERROR,
547 "invalid prediction orders: min=%d max=%d\n",
548 s->min_prediction_order, s->max_prediction_order);
549 ret = AVERROR(EINVAL);
553 avctx->coded_frame = avcodec_alloc_frame();
554 if (!avctx->coded_frame) {
555 ret = AVERROR(ENOMEM);
561 if ((ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
562 s->max_prediction_order,
563 FF_LPC_TYPE_LEVINSON)) < 0) {
569 alac_encode_close(avctx);
573 static int alac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
574 const AVFrame *frame, int *got_packet_ptr)
576 AlacEncodeContext *s = avctx->priv_data;
577 int out_bytes, max_frame_size, ret;
579 s->frame_size = frame->nb_samples;
581 if (frame->nb_samples < DEFAULT_FRAME_SIZE)
582 max_frame_size = get_max_frame_size(s->frame_size, avctx->channels,
583 avctx->bits_per_raw_sample);
585 max_frame_size = s->max_coded_frame_size;
587 if ((ret = ff_alloc_packet2(avctx, avpkt, 2 * max_frame_size)))
590 /* use verbatim mode for compression_level 0 */
591 if (s->compression_level) {
593 s->extra_bits = avctx->bits_per_raw_sample - 16;
598 s->write_sample_size = avctx->bits_per_raw_sample - s->extra_bits +
601 out_bytes = write_frame(s, avpkt, frame->extended_data);
603 if (out_bytes > max_frame_size) {
604 /* frame too large. use verbatim mode */
607 s->write_sample_size = avctx->bits_per_raw_sample + avctx->channels - 1;
608 out_bytes = write_frame(s, avpkt, frame->extended_data);
611 avpkt->size = out_bytes;
616 AVCodec ff_alac_encoder = {
618 .type = AVMEDIA_TYPE_AUDIO,
619 .id = AV_CODEC_ID_ALAC,
620 .priv_data_size = sizeof(AlacEncodeContext),
621 .init = alac_encode_init,
622 .encode2 = alac_encode_frame,
623 .close = alac_encode_close,
624 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
625 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S32P,
627 AV_SAMPLE_FMT_NONE },
628 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),