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