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