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