]> git.sesse.net Git - ffmpeg/blob - libavcodec/alacenc.c
13ef2912855ac6c6c355dac4b3997ddfa171cde9
[ffmpeg] / libavcodec / alacenc.c
1 /*
2  * ALAC audio encoder
3  * Copyright (c) 2008  Jaikrishnan Menon <realityman@gmx.net>
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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.
11  *
12  * Libav 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.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "avcodec.h"
23 #include "put_bits.h"
24 #include "dsputil.h"
25 #include "lpc.h"
26 #include "mathops.h"
27
28 #define DEFAULT_FRAME_SIZE        4096
29 #define DEFAULT_SAMPLE_SIZE       16
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
34
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
41
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
46
47 typedef struct RiceContext {
48     int history_mult;
49     int initial_history;
50     int k_modifier;
51     int rice_modifier;
52 } RiceContext;
53
54 typedef struct AlacLPCContext {
55     int lpc_order;
56     int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
57     int lpc_quant;
58 } AlacLPCContext;
59
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;
68     int32_t sample_buf[MAX_CHANNELS][DEFAULT_FRAME_SIZE];
69     int32_t predictor_buf[DEFAULT_FRAME_SIZE];
70     int interlacing_shift;
71     int interlacing_leftweight;
72     PutBitContext pbctx;
73     RiceContext rc;
74     AlacLPCContext lpc[MAX_CHANNELS];
75     LPCContext lpc_ctx;
76     AVCodecContext *avctx;
77 } AlacEncodeContext;
78
79
80 static void init_sample_buffers(AlacEncodeContext *s,
81                                 const int16_t *input_samples)
82 {
83     int ch, i;
84
85     for (ch = 0; ch < s->avctx->channels; ch++) {
86         const int16_t *sptr = input_samples + ch;
87         for (i = 0; i < s->frame_size; i++) {
88             s->sample_buf[ch][i] = *sptr;
89             sptr += s->avctx->channels;
90         }
91     }
92 }
93
94 static void encode_scalar(AlacEncodeContext *s, int x,
95                           int k, int write_sample_size)
96 {
97     int divisor, q, r;
98
99     k = FFMIN(k, s->rc.k_modifier);
100     divisor = (1<<k) - 1;
101     q = x / divisor;
102     r = x % divisor;
103
104     if (q > 8) {
105         // write escape code and sample value directly
106         put_bits(&s->pbctx, 9, ALAC_ESCAPE_CODE);
107         put_bits(&s->pbctx, write_sample_size, x);
108     } else {
109         if (q)
110             put_bits(&s->pbctx, q, (1<<q) - 1);
111         put_bits(&s->pbctx, 1, 0);
112
113         if (k != 1) {
114             if (r > 0)
115                 put_bits(&s->pbctx, k, r+1);
116             else
117                 put_bits(&s->pbctx, k-1, 0);
118         }
119     }
120 }
121
122 static void write_frame_header(AlacEncodeContext *s)
123 {
124     int encode_fs = 0;
125
126     if (s->frame_size < DEFAULT_FRAME_SIZE)
127         encode_fs = 1;
128
129     put_bits(&s->pbctx, 3,  s->avctx->channels-1);  // No. of channels -1
130     put_bits(&s->pbctx, 16, 0);                     // Seems to be zero
131     put_bits(&s->pbctx, 1,  encode_fs);             // Sample count is in the header
132     put_bits(&s->pbctx, 2,  0);                     // FIXME: Wasted bytes field
133     put_bits(&s->pbctx, 1,  s->verbatim);           // Audio block is verbatim
134     if (encode_fs)
135         put_bits32(&s->pbctx, s->frame_size);       // No. of samples in the frame
136 }
137
138 static void calc_predictor_params(AlacEncodeContext *s, int ch)
139 {
140     int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
141     int shift[MAX_LPC_ORDER];
142     int opt_order;
143
144     if (s->compression_level == 1) {
145         s->lpc[ch].lpc_order = 6;
146         s->lpc[ch].lpc_quant = 6;
147         s->lpc[ch].lpc_coeff[0] =  160;
148         s->lpc[ch].lpc_coeff[1] = -190;
149         s->lpc[ch].lpc_coeff[2] =  170;
150         s->lpc[ch].lpc_coeff[3] = -130;
151         s->lpc[ch].lpc_coeff[4] =   80;
152         s->lpc[ch].lpc_coeff[5] =  -25;
153     } else {
154         opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, s->sample_buf[ch],
155                                       s->frame_size,
156                                       s->min_prediction_order,
157                                       s->max_prediction_order,
158                                       ALAC_MAX_LPC_PRECISION, coefs, shift,
159                                       FF_LPC_TYPE_LEVINSON, 0,
160                                       ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
161
162         s->lpc[ch].lpc_order = opt_order;
163         s->lpc[ch].lpc_quant = shift[opt_order-1];
164         memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
165     }
166 }
167
168 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
169 {
170     int i, best;
171     int32_t lt, rt;
172     uint64_t sum[4];
173     uint64_t score[4];
174
175     /* calculate sum of 2nd order residual for each channel */
176     sum[0] = sum[1] = sum[2] = sum[3] = 0;
177     for (i = 2; i < n; i++) {
178         lt =  left_ch[i] - 2 *  left_ch[i - 1] +  left_ch[i - 2];
179         rt = right_ch[i] - 2 * right_ch[i - 1] + right_ch[i - 2];
180         sum[2] += FFABS((lt + rt) >> 1);
181         sum[3] += FFABS(lt - rt);
182         sum[0] += FFABS(lt);
183         sum[1] += FFABS(rt);
184     }
185
186     /* calculate score for each mode */
187     score[0] = sum[0] + sum[1];
188     score[1] = sum[0] + sum[3];
189     score[2] = sum[1] + sum[3];
190     score[3] = sum[2] + sum[3];
191
192     /* return mode with lowest score */
193     best = 0;
194     for (i = 1; i < 4; i++) {
195         if (score[i] < score[best])
196             best = i;
197     }
198     return best;
199 }
200
201 static void alac_stereo_decorrelation(AlacEncodeContext *s)
202 {
203     int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
204     int i, mode, n = s->frame_size;
205     int32_t tmp;
206
207     mode = estimate_stereo_mode(left, right, n);
208
209     switch (mode) {
210     case ALAC_CHMODE_LEFT_RIGHT:
211         s->interlacing_leftweight = 0;
212         s->interlacing_shift      = 0;
213         break;
214     case ALAC_CHMODE_LEFT_SIDE:
215         for (i = 0; i < n; i++)
216             right[i] = left[i] - right[i];
217         s->interlacing_leftweight = 1;
218         s->interlacing_shift      = 0;
219         break;
220     case ALAC_CHMODE_RIGHT_SIDE:
221         for (i = 0; i < n; i++) {
222             tmp = right[i];
223             right[i] = left[i] - right[i];
224             left[i]  = tmp + (right[i] >> 31);
225         }
226         s->interlacing_leftweight = 1;
227         s->interlacing_shift      = 31;
228         break;
229     default:
230         for (i = 0; i < n; i++) {
231             tmp = left[i];
232             left[i]  = (tmp + right[i]) >> 1;
233             right[i] =  tmp - right[i];
234         }
235         s->interlacing_leftweight = 1;
236         s->interlacing_shift      = 1;
237         break;
238     }
239 }
240
241 static void alac_linear_predictor(AlacEncodeContext *s, int ch)
242 {
243     int i;
244     AlacLPCContext lpc = s->lpc[ch];
245
246     if (lpc.lpc_order == 31) {
247         s->predictor_buf[0] = s->sample_buf[ch][0];
248
249         for (i = 1; i < s->frame_size; i++) {
250             s->predictor_buf[i] = s->sample_buf[ch][i    ] -
251                                   s->sample_buf[ch][i - 1];
252         }
253
254         return;
255     }
256
257     // generalised linear predictor
258
259     if (lpc.lpc_order > 0) {
260         int32_t *samples  = s->sample_buf[ch];
261         int32_t *residual = s->predictor_buf;
262
263         // generate warm-up samples
264         residual[0] = samples[0];
265         for (i = 1; i <= lpc.lpc_order; i++)
266             residual[i] = samples[i] - samples[i-1];
267
268         // perform lpc on remaining samples
269         for (i = lpc.lpc_order + 1; i < s->frame_size; i++) {
270             int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
271
272             for (j = 0; j < lpc.lpc_order; j++) {
273                 sum += (samples[lpc.lpc_order-j] - samples[0]) *
274                        lpc.lpc_coeff[j];
275             }
276
277             sum >>= lpc.lpc_quant;
278             sum += samples[0];
279             residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
280                                       s->write_sample_size);
281             res_val = residual[i];
282
283             if (res_val) {
284                 int index = lpc.lpc_order - 1;
285                 int neg = (res_val < 0);
286
287                 while (index >= 0 && (neg ? (res_val < 0) : (res_val > 0))) {
288                     int val  = samples[0] - samples[lpc.lpc_order - index];
289                     int sign = (val ? FFSIGN(val) : 0);
290
291                     if (neg)
292                         sign *= -1;
293
294                     lpc.lpc_coeff[index] -= sign;
295                     val *= sign;
296                     res_val -= (val >> lpc.lpc_quant) * (lpc.lpc_order - index);
297                     index--;
298                 }
299             }
300             samples++;
301         }
302     }
303 }
304
305 static void alac_entropy_coder(AlacEncodeContext *s)
306 {
307     unsigned int history = s->rc.initial_history;
308     int sign_modifier = 0, i, k;
309     int32_t *samples = s->predictor_buf;
310
311     for (i = 0; i < s->frame_size;) {
312         int x;
313
314         k = av_log2((history >> 9) + 3);
315
316         x  = -2 * (*samples) -1;
317         x ^= x >> 31;
318
319         samples++;
320         i++;
321
322         encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
323
324         history += x * s->rc.history_mult -
325                    ((history * s->rc.history_mult) >> 9);
326
327         sign_modifier = 0;
328         if (x > 0xFFFF)
329             history = 0xFFFF;
330
331         if (history < 128 && i < s->frame_size) {
332             unsigned int block_size = 0;
333
334             k = 7 - av_log2(history) + ((history + 16) >> 6);
335
336             while (*samples == 0 && i < s->frame_size) {
337                 samples++;
338                 i++;
339                 block_size++;
340             }
341             encode_scalar(s, block_size, k, 16);
342             sign_modifier = (block_size <= 0xFFFF);
343             history = 0;
344         }
345
346     }
347 }
348
349 static int write_frame(AlacEncodeContext *s, uint8_t *data, int size,
350                        const int16_t *samples)
351 {
352     int i, j;
353     int prediction_type = 0;
354     PutBitContext *pb = &s->pbctx;
355
356     init_put_bits(pb, data, size);
357
358     if (s->verbatim) {
359         write_frame_header(s);
360         for (i = 0; i < s->frame_size * s->avctx->channels; i++)
361             put_sbits(pb, 16, *samples++);
362     } else {
363         init_sample_buffers(s, samples);
364         write_frame_header(s);
365
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);
370
371         for (i = 0; i < s->avctx->channels; i++) {
372             calc_predictor_params(s, i);
373
374             put_bits(pb, 4, prediction_type);
375             put_bits(pb, 4, s->lpc[i].lpc_quant);
376
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]);
382         }
383
384         // apply lpc and entropy coding to audio samples
385
386         for (i = 0; i < s->avctx->channels; i++) {
387             alac_linear_predictor(s, i);
388
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];
394             }
395
396             alac_entropy_coder(s);
397         }
398     }
399     put_bits(pb, 3, 7);
400     flush_put_bits(pb);
401     return put_bits_count(pb) >> 3;
402 }
403
404 static av_always_inline int get_max_frame_size(int frame_size, int ch, int bps)
405 {
406     int header_bits = 23 + 32 * (frame_size < DEFAULT_FRAME_SIZE);
407     return FFALIGN(header_bits + bps * ch * frame_size + 3, 8) / 8;
408 }
409
410 static av_cold int alac_encode_close(AVCodecContext *avctx)
411 {
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);
417     return 0;
418 }
419
420 static av_cold int alac_encode_init(AVCodecContext *avctx)
421 {
422     AlacEncodeContext *s = avctx->priv_data;
423     int ret;
424     uint8_t *alac_extradata;
425
426     avctx->frame_size = s->frame_size = DEFAULT_FRAME_SIZE;
427
428     if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {
429         av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
430         return -1;
431     }
432
433     /* TODO: Correctly implement multi-channel ALAC.
434              It is similar to multi-channel AAC, in that it has a series of
435              single-channel (SCE), channel-pair (CPE), and LFE elements. */
436     if (avctx->channels > 2) {
437         av_log(avctx, AV_LOG_ERROR, "only mono or stereo input is currently supported\n");
438         return AVERROR_PATCHWELCOME;
439     }
440
441     // Set default compression level
442     if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
443         s->compression_level = 2;
444     else
445         s->compression_level = av_clip(avctx->compression_level, 0, 2);
446
447     // Initialize default Rice parameters
448     s->rc.history_mult    = 40;
449     s->rc.initial_history = 10;
450     s->rc.k_modifier      = 14;
451     s->rc.rice_modifier   = 4;
452
453     s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,
454                                                  avctx->channels,
455                                                  DEFAULT_SAMPLE_SIZE);
456
457     // FIXME: consider wasted_bytes
458     s->write_sample_size  = DEFAULT_SAMPLE_SIZE + avctx->channels - 1;
459
460     avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
461     if (!avctx->extradata) {
462         ret = AVERROR(ENOMEM);
463         goto error;
464     }
465     avctx->extradata_size = ALAC_EXTRADATA_SIZE;
466
467     alac_extradata = avctx->extradata;
468     AV_WB32(alac_extradata,    ALAC_EXTRADATA_SIZE);
469     AV_WB32(alac_extradata+4,  MKBETAG('a','l','a','c'));
470     AV_WB32(alac_extradata+12, avctx->frame_size);
471     AV_WB8 (alac_extradata+17, DEFAULT_SAMPLE_SIZE);
472     AV_WB8 (alac_extradata+21, avctx->channels);
473     AV_WB32(alac_extradata+24, s->max_coded_frame_size);
474     AV_WB32(alac_extradata+28,
475             avctx->sample_rate * avctx->channels * DEFAULT_SAMPLE_SIZE); // average bitrate
476     AV_WB32(alac_extradata+32, avctx->sample_rate);
477
478     // Set relevant extradata fields
479     if (s->compression_level > 0) {
480         AV_WB8(alac_extradata+18, s->rc.history_mult);
481         AV_WB8(alac_extradata+19, s->rc.initial_history);
482         AV_WB8(alac_extradata+20, s->rc.k_modifier);
483     }
484
485     s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
486     if (avctx->min_prediction_order >= 0) {
487         if (avctx->min_prediction_order < MIN_LPC_ORDER ||
488            avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
489             av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
490                    avctx->min_prediction_order);
491             ret = AVERROR(EINVAL);
492             goto error;
493         }
494
495         s->min_prediction_order = avctx->min_prediction_order;
496     }
497
498     s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
499     if (avctx->max_prediction_order >= 0) {
500         if (avctx->max_prediction_order < MIN_LPC_ORDER ||
501             avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
502             av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
503                    avctx->max_prediction_order);
504             ret = AVERROR(EINVAL);
505             goto error;
506         }
507
508         s->max_prediction_order = avctx->max_prediction_order;
509     }
510
511     if (s->max_prediction_order < s->min_prediction_order) {
512         av_log(avctx, AV_LOG_ERROR,
513                "invalid prediction orders: min=%d max=%d\n",
514                s->min_prediction_order, s->max_prediction_order);
515         ret = AVERROR(EINVAL);
516         goto error;
517     }
518
519     avctx->coded_frame = avcodec_alloc_frame();
520     if (!avctx->coded_frame) {
521         ret = AVERROR(ENOMEM);
522         goto error;
523     }
524
525     s->avctx = avctx;
526
527     if ((ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
528                            s->max_prediction_order,
529                            FF_LPC_TYPE_LEVINSON)) < 0) {
530         goto error;
531     }
532
533     return 0;
534 error:
535     alac_encode_close(avctx);
536     return ret;
537 }
538
539 static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
540                              int buf_size, void *data)
541 {
542     AlacEncodeContext *s = avctx->priv_data;
543     int out_bytes, max_frame_size;
544
545     s->frame_size  = avctx->frame_size;
546
547     if (avctx->frame_size < DEFAULT_FRAME_SIZE)
548         max_frame_size = get_max_frame_size(s->frame_size, avctx->channels,
549                                             DEFAULT_SAMPLE_SIZE);
550     else
551         max_frame_size = s->max_coded_frame_size;
552
553     if (buf_size < 2 * max_frame_size) {
554         av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");
555         return AVERROR(EINVAL);
556     }
557
558     /* use verbatim mode for compression_level 0 */
559     s->verbatim = !s->compression_level;
560
561     out_bytes = write_frame(s, frame, buf_size, data);
562
563     if (out_bytes > max_frame_size) {
564         /* frame too large. use verbatim mode */
565         s->verbatim = 1;
566         out_bytes = write_frame(s, frame, buf_size, data);
567     }
568
569     return out_bytes;
570 }
571
572 AVCodec ff_alac_encoder = {
573     .name           = "alac",
574     .type           = AVMEDIA_TYPE_AUDIO,
575     .id             = CODEC_ID_ALAC,
576     .priv_data_size = sizeof(AlacEncodeContext),
577     .init           = alac_encode_init,
578     .encode         = alac_encode_frame,
579     .close          = alac_encode_close,
580     .capabilities   = CODEC_CAP_SMALL_LAST_FRAME,
581     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
582                                                      AV_SAMPLE_FMT_NONE },
583     .long_name      = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
584 };