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
28 #include "alac_data.h"
30 #define DEFAULT_FRAME_SIZE 4096
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[2][DEFAULT_FRAME_SIZE];
70 int32_t predictor_buf[DEFAULT_FRAME_SIZE];
71 int interlacing_shift;
72 int interlacing_leftweight;
75 AlacLPCContext lpc[2];
77 AVCodecContext *avctx;
81 static void init_sample_buffers(AlacEncodeContext *s, int channels,
82 uint8_t const *samples[2])
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 < 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_element_header(AlacEncodeContext *s,
132 enum AlacRawDataBlockType element,
137 if (s->frame_size < DEFAULT_FRAME_SIZE)
140 put_bits(&s->pbctx, 3, element); // element type
141 put_bits(&s->pbctx, 4, instance); // element instance
142 put_bits(&s->pbctx, 12, 0); // unused header bits
143 put_bits(&s->pbctx, 1, encode_fs); // Sample count is in the header
144 put_bits(&s->pbctx, 2, s->extra_bits >> 3); // Extra bytes (for 24-bit)
145 put_bits(&s->pbctx, 1, s->verbatim); // Audio block is verbatim
147 put_bits32(&s->pbctx, s->frame_size); // No. of samples in the frame
150 static void calc_predictor_params(AlacEncodeContext *s, int ch)
152 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
153 int shift[MAX_LPC_ORDER];
156 if (s->compression_level == 1) {
157 s->lpc[ch].lpc_order = 6;
158 s->lpc[ch].lpc_quant = 6;
159 s->lpc[ch].lpc_coeff[0] = 160;
160 s->lpc[ch].lpc_coeff[1] = -190;
161 s->lpc[ch].lpc_coeff[2] = 170;
162 s->lpc[ch].lpc_coeff[3] = -130;
163 s->lpc[ch].lpc_coeff[4] = 80;
164 s->lpc[ch].lpc_coeff[5] = -25;
166 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, s->sample_buf[ch],
168 s->min_prediction_order,
169 s->max_prediction_order,
170 ALAC_MAX_LPC_PRECISION, coefs, shift,
171 FF_LPC_TYPE_LEVINSON, 0,
172 ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
174 s->lpc[ch].lpc_order = opt_order;
175 s->lpc[ch].lpc_quant = shift[opt_order-1];
176 memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
180 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
187 /* calculate sum of 2nd order residual for each channel */
188 sum[0] = sum[1] = sum[2] = sum[3] = 0;
189 for (i = 2; i < n; i++) {
190 lt = left_ch[i] - 2 * left_ch[i - 1] + left_ch[i - 2];
191 rt = right_ch[i] - 2 * right_ch[i - 1] + right_ch[i - 2];
192 sum[2] += FFABS((lt + rt) >> 1);
193 sum[3] += FFABS(lt - rt);
198 /* calculate score for each mode */
199 score[0] = sum[0] + sum[1];
200 score[1] = sum[0] + sum[3];
201 score[2] = sum[1] + sum[3];
202 score[3] = sum[2] + sum[3];
204 /* return mode with lowest score */
206 for (i = 1; i < 4; i++) {
207 if (score[i] < score[best])
213 static void alac_stereo_decorrelation(AlacEncodeContext *s)
215 int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
216 int i, mode, n = s->frame_size;
219 mode = estimate_stereo_mode(left, right, n);
222 case ALAC_CHMODE_LEFT_RIGHT:
223 s->interlacing_leftweight = 0;
224 s->interlacing_shift = 0;
226 case ALAC_CHMODE_LEFT_SIDE:
227 for (i = 0; i < n; i++)
228 right[i] = left[i] - right[i];
229 s->interlacing_leftweight = 1;
230 s->interlacing_shift = 0;
232 case ALAC_CHMODE_RIGHT_SIDE:
233 for (i = 0; i < n; i++) {
235 right[i] = left[i] - right[i];
236 left[i] = tmp + (right[i] >> 31);
238 s->interlacing_leftweight = 1;
239 s->interlacing_shift = 31;
242 for (i = 0; i < n; i++) {
244 left[i] = (tmp + right[i]) >> 1;
245 right[i] = tmp - right[i];
247 s->interlacing_leftweight = 1;
248 s->interlacing_shift = 1;
253 static void alac_linear_predictor(AlacEncodeContext *s, int ch)
256 AlacLPCContext lpc = s->lpc[ch];
258 if (lpc.lpc_order == 31) {
259 s->predictor_buf[0] = s->sample_buf[ch][0];
261 for (i = 1; i < s->frame_size; i++) {
262 s->predictor_buf[i] = s->sample_buf[ch][i ] -
263 s->sample_buf[ch][i - 1];
269 // generalised linear predictor
271 if (lpc.lpc_order > 0) {
272 int32_t *samples = s->sample_buf[ch];
273 int32_t *residual = s->predictor_buf;
275 // generate warm-up samples
276 residual[0] = samples[0];
277 for (i = 1; i <= lpc.lpc_order; i++)
278 residual[i] = samples[i] - samples[i-1];
280 // perform lpc on remaining samples
281 for (i = lpc.lpc_order + 1; i < s->frame_size; i++) {
282 int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
284 for (j = 0; j < lpc.lpc_order; j++) {
285 sum += (samples[lpc.lpc_order-j] - samples[0]) *
289 sum >>= lpc.lpc_quant;
291 residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
292 s->write_sample_size);
293 res_val = residual[i];
296 int index = lpc.lpc_order - 1;
297 int neg = (res_val < 0);
299 while (index >= 0 && (neg ? (res_val < 0) : (res_val > 0))) {
300 int val = samples[0] - samples[lpc.lpc_order - index];
301 int sign = (val ? FFSIGN(val) : 0);
306 lpc.lpc_coeff[index] -= sign;
308 res_val -= (val >> lpc.lpc_quant) * (lpc.lpc_order - index);
317 static void alac_entropy_coder(AlacEncodeContext *s)
319 unsigned int history = s->rc.initial_history;
320 int sign_modifier = 0, i, k;
321 int32_t *samples = s->predictor_buf;
323 for (i = 0; i < s->frame_size;) {
326 k = av_log2((history >> 9) + 3);
328 x = -2 * (*samples) -1;
334 encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
336 history += x * s->rc.history_mult -
337 ((history * s->rc.history_mult) >> 9);
343 if (history < 128 && i < s->frame_size) {
344 unsigned int block_size = 0;
346 k = 7 - av_log2(history) + ((history + 16) >> 6);
348 while (*samples == 0 && i < s->frame_size) {
353 encode_scalar(s, block_size, k, 16);
354 sign_modifier = (block_size <= 0xFFFF);
361 static void write_element(AlacEncodeContext *s,
362 enum AlacRawDataBlockType element, int instance,
363 const uint8_t *samples0, const uint8_t *samples1)
365 uint8_t const *samples[2] = { samples0, samples1 };
367 int prediction_type = 0;
368 PutBitContext *pb = &s->pbctx;
370 channels = element == TYPE_CPE ? 2 : 1;
373 write_element_header(s, element, instance);
374 /* samples are channel-interleaved in verbatim mode */
375 if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S32P) {
376 int shift = 32 - s->avctx->bits_per_raw_sample;
377 int32_t const *samples_s32[2] = { (const int32_t *)samples0,
378 (const int32_t *)samples1 };
379 for (i = 0; i < s->frame_size; i++)
380 for (j = 0; j < channels; j++)
381 put_sbits(pb, s->avctx->bits_per_raw_sample,
382 samples_s32[j][i] >> shift);
384 int16_t const *samples_s16[2] = { (const int16_t *)samples0,
385 (const int16_t *)samples1 };
386 for (i = 0; i < s->frame_size; i++)
387 for (j = 0; j < channels; j++)
388 put_sbits(pb, s->avctx->bits_per_raw_sample,
392 s->write_sample_size = s->avctx->bits_per_raw_sample - s->extra_bits +
395 init_sample_buffers(s, channels, samples);
396 write_element_header(s, element, instance);
399 alac_stereo_decorrelation(s);
401 s->interlacing_shift = s->interlacing_leftweight = 0;
402 put_bits(pb, 8, s->interlacing_shift);
403 put_bits(pb, 8, s->interlacing_leftweight);
405 for (i = 0; i < channels; i++) {
406 calc_predictor_params(s, i);
408 put_bits(pb, 4, prediction_type);
409 put_bits(pb, 4, s->lpc[i].lpc_quant);
411 put_bits(pb, 3, s->rc.rice_modifier);
412 put_bits(pb, 5, s->lpc[i].lpc_order);
413 // predictor coeff. table
414 for (j = 0; j < s->lpc[i].lpc_order; j++)
415 put_sbits(pb, 16, s->lpc[i].lpc_coeff[j]);
418 // write extra bits if needed
420 uint32_t mask = (1 << s->extra_bits) - 1;
421 for (i = 0; i < s->frame_size; i++) {
422 for (j = 0; j < channels; j++) {
423 put_bits(pb, s->extra_bits, s->sample_buf[j][i] & mask);
424 s->sample_buf[j][i] >>= s->extra_bits;
429 // apply lpc and entropy coding to audio samples
430 for (i = 0; i < channels; i++) {
431 alac_linear_predictor(s, i);
433 // TODO: determine when this will actually help. for now it's not used.
434 if (prediction_type == 15) {
435 // 2nd pass 1st order filter
436 for (j = s->frame_size - 1; j > 0; j--)
437 s->predictor_buf[j] -= s->predictor_buf[j - 1];
439 alac_entropy_coder(s);
444 static int write_frame(AlacEncodeContext *s, AVPacket *avpkt,
445 uint8_t * const *samples)
447 PutBitContext *pb = &s->pbctx;
448 const enum AlacRawDataBlockType *ch_elements = ff_alac_channel_elements[s->avctx->channels - 1];
449 const uint8_t *ch_map = ff_alac_channel_layout_offsets[s->avctx->channels - 1];
450 int ch, element, sce, cpe;
452 init_put_bits(pb, avpkt->data, avpkt->size);
454 ch = element = sce = cpe = 0;
455 while (ch < s->avctx->channels) {
456 if (ch_elements[element] == TYPE_CPE) {
457 write_element(s, TYPE_CPE, cpe, samples[ch_map[ch]],
458 samples[ch_map[ch + 1]]);
462 write_element(s, TYPE_SCE, sce, samples[ch_map[ch]], NULL);
469 put_bits(pb, 3, TYPE_END);
472 return put_bits_count(pb) >> 3;
475 static av_always_inline int get_max_frame_size(int frame_size, int ch, int bps)
477 int header_bits = 23 + 32 * (frame_size < DEFAULT_FRAME_SIZE);
478 return FFALIGN(header_bits + bps * ch * frame_size + 3, 8) / 8;
481 static av_cold int alac_encode_close(AVCodecContext *avctx)
483 AlacEncodeContext *s = avctx->priv_data;
484 ff_lpc_end(&s->lpc_ctx);
485 av_freep(&avctx->extradata);
486 avctx->extradata_size = 0;
487 av_freep(&avctx->coded_frame);
491 static av_cold int alac_encode_init(AVCodecContext *avctx)
493 AlacEncodeContext *s = avctx->priv_data;
495 uint8_t *alac_extradata;
497 avctx->frame_size = s->frame_size = DEFAULT_FRAME_SIZE;
499 if (avctx->sample_fmt == AV_SAMPLE_FMT_S32P) {
500 if (avctx->bits_per_raw_sample != 24)
501 av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
502 avctx->bits_per_raw_sample = 24;
504 avctx->bits_per_raw_sample = 16;
508 // Set default compression level
509 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
510 s->compression_level = 2;
512 s->compression_level = av_clip(avctx->compression_level, 0, 2);
514 // Initialize default Rice parameters
515 s->rc.history_mult = 40;
516 s->rc.initial_history = 10;
517 s->rc.k_modifier = 14;
518 s->rc.rice_modifier = 4;
520 s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,
522 avctx->bits_per_raw_sample);
524 avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
525 if (!avctx->extradata) {
526 ret = AVERROR(ENOMEM);
529 avctx->extradata_size = ALAC_EXTRADATA_SIZE;
531 alac_extradata = avctx->extradata;
532 AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);
533 AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));
534 AV_WB32(alac_extradata+12, avctx->frame_size);
535 AV_WB8 (alac_extradata+17, avctx->bits_per_raw_sample);
536 AV_WB8 (alac_extradata+21, avctx->channels);
537 AV_WB32(alac_extradata+24, s->max_coded_frame_size);
538 AV_WB32(alac_extradata+28,
539 avctx->sample_rate * avctx->channels * avctx->bits_per_raw_sample); // average bitrate
540 AV_WB32(alac_extradata+32, avctx->sample_rate);
542 // Set relevant extradata fields
543 if (s->compression_level > 0) {
544 AV_WB8(alac_extradata+18, s->rc.history_mult);
545 AV_WB8(alac_extradata+19, s->rc.initial_history);
546 AV_WB8(alac_extradata+20, s->rc.k_modifier);
549 s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
550 if (avctx->min_prediction_order >= 0) {
551 if (avctx->min_prediction_order < MIN_LPC_ORDER ||
552 avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
553 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
554 avctx->min_prediction_order);
555 ret = AVERROR(EINVAL);
559 s->min_prediction_order = avctx->min_prediction_order;
562 s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
563 if (avctx->max_prediction_order >= 0) {
564 if (avctx->max_prediction_order < MIN_LPC_ORDER ||
565 avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
566 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
567 avctx->max_prediction_order);
568 ret = AVERROR(EINVAL);
572 s->max_prediction_order = avctx->max_prediction_order;
575 if (s->max_prediction_order < s->min_prediction_order) {
576 av_log(avctx, AV_LOG_ERROR,
577 "invalid prediction orders: min=%d max=%d\n",
578 s->min_prediction_order, s->max_prediction_order);
579 ret = AVERROR(EINVAL);
583 avctx->coded_frame = avcodec_alloc_frame();
584 if (!avctx->coded_frame) {
585 ret = AVERROR(ENOMEM);
591 if ((ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
592 s->max_prediction_order,
593 FF_LPC_TYPE_LEVINSON)) < 0) {
599 alac_encode_close(avctx);
603 static int alac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
604 const AVFrame *frame, int *got_packet_ptr)
606 AlacEncodeContext *s = avctx->priv_data;
607 int out_bytes, max_frame_size, ret;
609 s->frame_size = frame->nb_samples;
611 if (frame->nb_samples < DEFAULT_FRAME_SIZE)
612 max_frame_size = get_max_frame_size(s->frame_size, avctx->channels,
613 avctx->bits_per_raw_sample);
615 max_frame_size = s->max_coded_frame_size;
617 if ((ret = ff_alloc_packet2(avctx, avpkt, 2 * max_frame_size)))
620 /* use verbatim mode for compression_level 0 */
621 if (s->compression_level) {
623 s->extra_bits = avctx->bits_per_raw_sample - 16;
629 out_bytes = write_frame(s, avpkt, frame->extended_data);
631 if (out_bytes > max_frame_size) {
632 /* frame too large. use verbatim mode */
635 out_bytes = write_frame(s, avpkt, frame->extended_data);
638 avpkt->size = out_bytes;
643 AVCodec ff_alac_encoder = {
645 .type = AVMEDIA_TYPE_AUDIO,
646 .id = AV_CODEC_ID_ALAC,
647 .priv_data_size = sizeof(AlacEncodeContext),
648 .init = alac_encode_init,
649 .encode2 = alac_encode_frame,
650 .close = alac_encode_close,
651 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
652 .channel_layouts = ff_alac_channel_layouts,
653 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S32P,
655 AV_SAMPLE_FMT_NONE },
656 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),