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 DEFAULT_SAMPLE_SIZE 16
31 #define MAX_CHANNELS 8
32 #define ALAC_EXTRADATA_SIZE 36
33 #define ALAC_FRAME_HEADER_SIZE 55
34 #define ALAC_FRAME_FOOTER_SIZE 3
36 #define ALAC_ESCAPE_CODE 0x1FF
37 #define ALAC_MAX_LPC_ORDER 30
38 #define DEFAULT_MAX_PRED_ORDER 6
39 #define DEFAULT_MIN_PRED_ORDER 4
40 #define ALAC_MAX_LPC_PRECISION 9
41 #define ALAC_MAX_LPC_SHIFT 9
43 #define ALAC_CHMODE_LEFT_RIGHT 0
44 #define ALAC_CHMODE_LEFT_SIDE 1
45 #define ALAC_CHMODE_RIGHT_SIDE 2
46 #define ALAC_CHMODE_MID_SIDE 3
48 typedef struct RiceContext {
55 typedef struct AlacLPCContext {
57 int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
61 typedef struct AlacEncodeContext {
62 int frame_size; /**< current frame size */
63 int verbatim; /**< current frame verbatim mode flag */
64 int compression_level;
65 int min_prediction_order;
66 int max_prediction_order;
67 int max_coded_frame_size;
68 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, int16_t **input_samples)
85 for (ch = 0; ch < s->avctx->channels; ch++) {
86 int32_t *bptr = s->sample_buf[ch];
87 const int16_t *sptr = input_samples[ch];
88 for (i = 0; i < s->frame_size; i++)
93 static void encode_scalar(AlacEncodeContext *s, int x,
94 int k, int write_sample_size)
98 k = FFMIN(k, s->rc.k_modifier);
104 // write escape code and sample value directly
105 put_bits(&s->pbctx, 9, ALAC_ESCAPE_CODE);
106 put_bits(&s->pbctx, write_sample_size, x);
109 put_bits(&s->pbctx, q, (1<<q) - 1);
110 put_bits(&s->pbctx, 1, 0);
114 put_bits(&s->pbctx, k, r+1);
116 put_bits(&s->pbctx, k-1, 0);
121 static void write_frame_header(AlacEncodeContext *s)
125 if (s->frame_size < DEFAULT_FRAME_SIZE)
128 put_bits(&s->pbctx, 3, s->avctx->channels-1); // No. of channels -1
129 put_bits(&s->pbctx, 16, 0); // Seems to be zero
130 put_bits(&s->pbctx, 1, encode_fs); // Sample count is in the header
131 put_bits(&s->pbctx, 2, 0); // FIXME: Wasted bytes field
132 put_bits(&s->pbctx, 1, s->verbatim); // Audio block is verbatim
134 put_bits32(&s->pbctx, s->frame_size); // No. of samples in the frame
137 static void calc_predictor_params(AlacEncodeContext *s, int ch)
139 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
140 int shift[MAX_LPC_ORDER];
143 if (s->compression_level == 1) {
144 s->lpc[ch].lpc_order = 6;
145 s->lpc[ch].lpc_quant = 6;
146 s->lpc[ch].lpc_coeff[0] = 160;
147 s->lpc[ch].lpc_coeff[1] = -190;
148 s->lpc[ch].lpc_coeff[2] = 170;
149 s->lpc[ch].lpc_coeff[3] = -130;
150 s->lpc[ch].lpc_coeff[4] = 80;
151 s->lpc[ch].lpc_coeff[5] = -25;
153 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, s->sample_buf[ch],
155 s->min_prediction_order,
156 s->max_prediction_order,
157 ALAC_MAX_LPC_PRECISION, coefs, shift,
158 FF_LPC_TYPE_LEVINSON, 0,
159 ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
161 s->lpc[ch].lpc_order = opt_order;
162 s->lpc[ch].lpc_quant = shift[opt_order-1];
163 memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
167 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
174 /* calculate sum of 2nd order residual for each channel */
175 sum[0] = sum[1] = sum[2] = sum[3] = 0;
176 for (i = 2; i < n; i++) {
177 lt = left_ch[i] - 2 * left_ch[i - 1] + left_ch[i - 2];
178 rt = right_ch[i] - 2 * right_ch[i - 1] + right_ch[i - 2];
179 sum[2] += FFABS((lt + rt) >> 1);
180 sum[3] += FFABS(lt - rt);
185 /* calculate score for each mode */
186 score[0] = sum[0] + sum[1];
187 score[1] = sum[0] + sum[3];
188 score[2] = sum[1] + sum[3];
189 score[3] = sum[2] + sum[3];
191 /* return mode with lowest score */
193 for (i = 1; i < 4; i++) {
194 if (score[i] < score[best])
200 static void alac_stereo_decorrelation(AlacEncodeContext *s)
202 int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
203 int i, mode, n = s->frame_size;
206 mode = estimate_stereo_mode(left, right, n);
209 case ALAC_CHMODE_LEFT_RIGHT:
210 s->interlacing_leftweight = 0;
211 s->interlacing_shift = 0;
213 case ALAC_CHMODE_LEFT_SIDE:
214 for (i = 0; i < n; i++)
215 right[i] = left[i] - right[i];
216 s->interlacing_leftweight = 1;
217 s->interlacing_shift = 0;
219 case ALAC_CHMODE_RIGHT_SIDE:
220 for (i = 0; i < n; i++) {
222 right[i] = left[i] - right[i];
223 left[i] = tmp + (right[i] >> 31);
225 s->interlacing_leftweight = 1;
226 s->interlacing_shift = 31;
229 for (i = 0; i < n; i++) {
231 left[i] = (tmp + right[i]) >> 1;
232 right[i] = tmp - right[i];
234 s->interlacing_leftweight = 1;
235 s->interlacing_shift = 1;
240 static void alac_linear_predictor(AlacEncodeContext *s, int ch)
243 AlacLPCContext lpc = s->lpc[ch];
245 if (lpc.lpc_order == 31) {
246 s->predictor_buf[0] = s->sample_buf[ch][0];
248 for (i = 1; i < s->frame_size; i++) {
249 s->predictor_buf[i] = s->sample_buf[ch][i ] -
250 s->sample_buf[ch][i - 1];
256 // generalised linear predictor
258 if (lpc.lpc_order > 0) {
259 int32_t *samples = s->sample_buf[ch];
260 int32_t *residual = s->predictor_buf;
262 // generate warm-up samples
263 residual[0] = samples[0];
264 for (i = 1; i <= lpc.lpc_order; i++)
265 residual[i] = samples[i] - samples[i-1];
267 // perform lpc on remaining samples
268 for (i = lpc.lpc_order + 1; i < s->frame_size; i++) {
269 int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
271 for (j = 0; j < lpc.lpc_order; j++) {
272 sum += (samples[lpc.lpc_order-j] - samples[0]) *
276 sum >>= lpc.lpc_quant;
278 residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
279 s->write_sample_size);
280 res_val = residual[i];
283 int index = lpc.lpc_order - 1;
284 int neg = (res_val < 0);
286 while (index >= 0 && (neg ? (res_val < 0) : (res_val > 0))) {
287 int val = samples[0] - samples[lpc.lpc_order - index];
288 int sign = (val ? FFSIGN(val) : 0);
293 lpc.lpc_coeff[index] -= sign;
295 res_val -= (val >> lpc.lpc_quant) * (lpc.lpc_order - index);
304 static void alac_entropy_coder(AlacEncodeContext *s)
306 unsigned int history = s->rc.initial_history;
307 int sign_modifier = 0, i, k;
308 int32_t *samples = s->predictor_buf;
310 for (i = 0; i < s->frame_size;) {
313 k = av_log2((history >> 9) + 3);
315 x = -2 * (*samples) -1;
321 encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
323 history += x * s->rc.history_mult -
324 ((history * s->rc.history_mult) >> 9);
330 if (history < 128 && i < s->frame_size) {
331 unsigned int block_size = 0;
333 k = 7 - av_log2(history) + ((history + 16) >> 6);
335 while (*samples == 0 && i < s->frame_size) {
340 encode_scalar(s, block_size, k, 16);
341 sign_modifier = (block_size <= 0xFFFF);
348 static int write_frame(AlacEncodeContext *s, AVPacket *avpkt, int16_t **samples)
351 int prediction_type = 0;
352 PutBitContext *pb = &s->pbctx;
354 init_put_bits(pb, avpkt->data, avpkt->size);
357 write_frame_header(s);
358 /* samples are channel-interleaved in verbatim mode */
359 for (i = 0; i < s->frame_size; i++)
360 for (j = 0; j < s->avctx->channels; j++)
361 put_sbits(pb, 16, samples[j][i]);
363 init_sample_buffers(s, samples);
364 write_frame_header(s);
366 if (s->avctx->channels == 2)
367 alac_stereo_decorrelation(s);
368 put_bits(pb, 8, s->interlacing_shift);
369 put_bits(pb, 8, s->interlacing_leftweight);
371 for (i = 0; i < s->avctx->channels; i++) {
372 calc_predictor_params(s, i);
374 put_bits(pb, 4, prediction_type);
375 put_bits(pb, 4, s->lpc[i].lpc_quant);
377 put_bits(pb, 3, s->rc.rice_modifier);
378 put_bits(pb, 5, s->lpc[i].lpc_order);
379 // predictor coeff. table
380 for (j = 0; j < s->lpc[i].lpc_order; j++)
381 put_sbits(pb, 16, s->lpc[i].lpc_coeff[j]);
384 // apply lpc and entropy coding to audio samples
386 for (i = 0; i < s->avctx->channels; i++) {
387 alac_linear_predictor(s, i);
389 // TODO: determine when this will actually help. for now it's not used.
390 if (prediction_type == 15) {
391 // 2nd pass 1st order filter
392 for (j = s->frame_size - 1; j > 0; j--)
393 s->predictor_buf[j] -= s->predictor_buf[j - 1];
396 alac_entropy_coder(s);
401 return put_bits_count(pb) >> 3;
404 static av_always_inline int get_max_frame_size(int frame_size, int ch, int bps)
406 int header_bits = 23 + 32 * (frame_size < DEFAULT_FRAME_SIZE);
407 return FFALIGN(header_bits + bps * ch * frame_size + 3, 8) / 8;
410 static av_cold int alac_encode_close(AVCodecContext *avctx)
412 AlacEncodeContext *s = avctx->priv_data;
413 ff_lpc_end(&s->lpc_ctx);
414 av_freep(&avctx->extradata);
415 avctx->extradata_size = 0;
416 av_freep(&avctx->coded_frame);
420 static av_cold int alac_encode_init(AVCodecContext *avctx)
422 AlacEncodeContext *s = avctx->priv_data;
424 uint8_t *alac_extradata;
426 avctx->frame_size = s->frame_size = DEFAULT_FRAME_SIZE;
428 /* TODO: Correctly implement multi-channel ALAC.
429 It is similar to multi-channel AAC, in that it has a series of
430 single-channel (SCE), channel-pair (CPE), and LFE elements. */
431 if (avctx->channels > 2) {
432 av_log(avctx, AV_LOG_ERROR, "only mono or stereo input is currently supported\n");
433 return AVERROR_PATCHWELCOME;
436 // Set default compression level
437 if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
438 s->compression_level = 2;
440 s->compression_level = av_clip(avctx->compression_level, 0, 2);
442 // Initialize default Rice parameters
443 s->rc.history_mult = 40;
444 s->rc.initial_history = 10;
445 s->rc.k_modifier = 14;
446 s->rc.rice_modifier = 4;
448 s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,
450 DEFAULT_SAMPLE_SIZE);
452 // FIXME: consider wasted_bytes
453 s->write_sample_size = DEFAULT_SAMPLE_SIZE + avctx->channels - 1;
455 avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
456 if (!avctx->extradata) {
457 ret = AVERROR(ENOMEM);
460 avctx->extradata_size = ALAC_EXTRADATA_SIZE;
462 alac_extradata = avctx->extradata;
463 AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);
464 AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));
465 AV_WB32(alac_extradata+12, avctx->frame_size);
466 AV_WB8 (alac_extradata+17, DEFAULT_SAMPLE_SIZE);
467 AV_WB8 (alac_extradata+21, avctx->channels);
468 AV_WB32(alac_extradata+24, s->max_coded_frame_size);
469 AV_WB32(alac_extradata+28,
470 avctx->sample_rate * avctx->channels * DEFAULT_SAMPLE_SIZE); // average bitrate
471 AV_WB32(alac_extradata+32, avctx->sample_rate);
473 // Set relevant extradata fields
474 if (s->compression_level > 0) {
475 AV_WB8(alac_extradata+18, s->rc.history_mult);
476 AV_WB8(alac_extradata+19, s->rc.initial_history);
477 AV_WB8(alac_extradata+20, s->rc.k_modifier);
480 s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
481 if (avctx->min_prediction_order >= 0) {
482 if (avctx->min_prediction_order < MIN_LPC_ORDER ||
483 avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
484 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
485 avctx->min_prediction_order);
486 ret = AVERROR(EINVAL);
490 s->min_prediction_order = avctx->min_prediction_order;
493 s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
494 if (avctx->max_prediction_order >= 0) {
495 if (avctx->max_prediction_order < MIN_LPC_ORDER ||
496 avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
497 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
498 avctx->max_prediction_order);
499 ret = AVERROR(EINVAL);
503 s->max_prediction_order = avctx->max_prediction_order;
506 if (s->max_prediction_order < s->min_prediction_order) {
507 av_log(avctx, AV_LOG_ERROR,
508 "invalid prediction orders: min=%d max=%d\n",
509 s->min_prediction_order, s->max_prediction_order);
510 ret = AVERROR(EINVAL);
514 avctx->coded_frame = avcodec_alloc_frame();
515 if (!avctx->coded_frame) {
516 ret = AVERROR(ENOMEM);
522 if ((ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
523 s->max_prediction_order,
524 FF_LPC_TYPE_LEVINSON)) < 0) {
530 alac_encode_close(avctx);
534 static int alac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
535 const AVFrame *frame, int *got_packet_ptr)
537 AlacEncodeContext *s = avctx->priv_data;
538 int out_bytes, max_frame_size, ret;
539 int16_t **samples = (int16_t **)frame->extended_data;
541 s->frame_size = frame->nb_samples;
543 if (frame->nb_samples < DEFAULT_FRAME_SIZE)
544 max_frame_size = get_max_frame_size(s->frame_size, avctx->channels,
545 DEFAULT_SAMPLE_SIZE);
547 max_frame_size = s->max_coded_frame_size;
549 if ((ret = ff_alloc_packet2(avctx, avpkt, 2 * max_frame_size)))
552 /* use verbatim mode for compression_level 0 */
553 s->verbatim = !s->compression_level;
555 out_bytes = write_frame(s, avpkt, samples);
557 if (out_bytes > max_frame_size) {
558 /* frame too large. use verbatim mode */
560 out_bytes = write_frame(s, avpkt, samples);
563 avpkt->size = out_bytes;
568 AVCodec ff_alac_encoder = {
570 .type = AVMEDIA_TYPE_AUDIO,
571 .id = AV_CODEC_ID_ALAC,
572 .priv_data_size = sizeof(AlacEncodeContext),
573 .init = alac_encode_init,
574 .encode2 = alac_encode_frame,
575 .close = alac_encode_close,
576 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
577 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16P,
578 AV_SAMPLE_FMT_NONE },
579 .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),