]> git.sesse.net Git - ffmpeg/blob - libavcodec/alacenc.c
Merge remote-tracking branch 'qatar/master'
[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 "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     }
191     return best;
192 }
193
194 static void alac_stereo_decorrelation(AlacEncodeContext *s)
195 {
196     int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
197     int i, mode, n = s->avctx->frame_size;
198     int32_t tmp;
199
200     mode = estimate_stereo_mode(left, right, n);
201
202     switch(mode)
203     {
204         case ALAC_CHMODE_LEFT_RIGHT:
205             s->interlacing_leftweight = 0;
206             s->interlacing_shift = 0;
207             break;
208
209         case ALAC_CHMODE_LEFT_SIDE:
210             for (i = 0; i < n; i++) {
211                 right[i] = left[i] - right[i];
212             }
213             s->interlacing_leftweight = 1;
214             s->interlacing_shift = 0;
215             break;
216
217         case ALAC_CHMODE_RIGHT_SIDE:
218             for (i = 0; i < n; i++) {
219                 tmp = right[i];
220                 right[i] = left[i] - right[i];
221                 left[i] = tmp + (right[i] >> 31);
222             }
223             s->interlacing_leftweight = 1;
224             s->interlacing_shift = 31;
225             break;
226
227         default:
228             for (i = 0; i < n; i++) {
229                 tmp = left[i];
230                 left[i] = (tmp + right[i]) >> 1;
231                 right[i] = tmp - right[i];
232             }
233             s->interlacing_leftweight = 1;
234             s->interlacing_shift = 1;
235             break;
236     }
237 }
238
239 static void alac_linear_predictor(AlacEncodeContext *s, int ch)
240 {
241     int i;
242     AlacLPCContext lpc = s->lpc[ch];
243
244     if (lpc.lpc_order == 31) {
245         s->predictor_buf[0] = s->sample_buf[ch][0];
246
247         for (i = 1; i < s->avctx->frame_size; i++)
248             s->predictor_buf[i] = s->sample_buf[ch][i] - s->sample_buf[ch][i-1];
249
250         return;
251     }
252
253     // generalised linear predictor
254
255     if (lpc.lpc_order > 0) {
256         int32_t *samples  = s->sample_buf[ch];
257         int32_t *residual = s->predictor_buf;
258
259         // generate warm-up samples
260         residual[0] = samples[0];
261         for (i = 1; i <= lpc.lpc_order; i++)
262             residual[i] = samples[i] - samples[i-1];
263
264         // perform lpc on remaining samples
265         for (i = lpc.lpc_order + 1; i < s->avctx->frame_size; i++) {
266             int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
267
268             for (j = 0; j < lpc.lpc_order; j++) {
269                 sum += (samples[lpc.lpc_order-j] - samples[0]) *
270                         lpc.lpc_coeff[j];
271             }
272
273             sum >>= lpc.lpc_quant;
274             sum += samples[0];
275             residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
276                                       s->write_sample_size);
277             res_val = residual[i];
278
279             if(res_val) {
280                 int index = lpc.lpc_order - 1;
281                 int neg = (res_val < 0);
282
283                 while(index >= 0 && (neg ? (res_val < 0):(res_val > 0))) {
284                     int val = samples[0] - samples[lpc.lpc_order - index];
285                     int sign = (val ? FFSIGN(val) : 0);
286
287                     if(neg)
288                         sign*=-1;
289
290                     lpc.lpc_coeff[index] -= sign;
291                     val *= sign;
292                     res_val -= ((val >> lpc.lpc_quant) *
293                             (lpc.lpc_order - index));
294                     index--;
295                 }
296             }
297             samples++;
298         }
299     }
300 }
301
302 static void alac_entropy_coder(AlacEncodeContext *s)
303 {
304     unsigned int history = s->rc.initial_history;
305     int sign_modifier = 0, i, k;
306     int32_t *samples = s->predictor_buf;
307
308     for (i = 0; i < s->avctx->frame_size;) {
309         int x;
310
311         k = av_log2((history >> 9) + 3);
312
313         x = -2*(*samples)-1;
314         x ^= (x>>31);
315
316         samples++;
317         i++;
318
319         encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
320
321         history += x * s->rc.history_mult
322                    - ((history * s->rc.history_mult) >> 9);
323
324         sign_modifier = 0;
325         if (x > 0xFFFF)
326             history = 0xFFFF;
327
328         if (history < 128 && i < s->avctx->frame_size) {
329             unsigned int block_size = 0;
330
331             k = 7 - av_log2(history) + ((history + 16) >> 6);
332
333             while (*samples == 0 && i < s->avctx->frame_size) {
334                 samples++;
335                 i++;
336                 block_size++;
337             }
338             encode_scalar(s, block_size, k, 16);
339
340             sign_modifier = (block_size <= 0xFFFF);
341
342             history = 0;
343         }
344
345     }
346 }
347
348 static void write_compressed_frame(AlacEncodeContext *s)
349 {
350     int i, j;
351
352     if (s->avctx->channels == 2)
353         alac_stereo_decorrelation(s);
354     put_bits(&s->pbctx, 8, s->interlacing_shift);
355     put_bits(&s->pbctx, 8, s->interlacing_leftweight);
356
357     for (i = 0; i < s->avctx->channels; i++) {
358
359         calc_predictor_params(s, i);
360
361         put_bits(&s->pbctx, 4, 0);  // prediction type : currently only type 0 has been RE'd
362         put_bits(&s->pbctx, 4, s->lpc[i].lpc_quant);
363
364         put_bits(&s->pbctx, 3, s->rc.rice_modifier);
365         put_bits(&s->pbctx, 5, s->lpc[i].lpc_order);
366         // predictor coeff. table
367         for (j = 0; j < s->lpc[i].lpc_order; j++) {
368             put_sbits(&s->pbctx, 16, s->lpc[i].lpc_coeff[j]);
369         }
370     }
371
372     // apply lpc and entropy coding to audio samples
373
374     for (i = 0; i < s->avctx->channels; i++) {
375         alac_linear_predictor(s, i);
376         alac_entropy_coder(s);
377     }
378 }
379
380 static av_cold int alac_encode_init(AVCodecContext *avctx)
381 {
382     AlacEncodeContext *s    = avctx->priv_data;
383     int ret;
384     uint8_t *alac_extradata = av_mallocz(ALAC_EXTRADATA_SIZE+1);
385
386     avctx->frame_size      = DEFAULT_FRAME_SIZE;
387     avctx->bits_per_coded_sample = DEFAULT_SAMPLE_SIZE;
388
389     if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {
390         av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
391         return -1;
392     }
393
394     if(avctx->channels > 2) {
395         av_log(avctx, AV_LOG_ERROR, "channels > 2 not supported\n");
396         return AVERROR_PATCHWELCOME;
397     }
398
399     // Set default compression level
400     if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
401         s->compression_level = 2;
402     else
403         s->compression_level = av_clip(avctx->compression_level, 0, 2);
404
405     // Initialize default Rice parameters
406     s->rc.history_mult    = 40;
407     s->rc.initial_history = 10;
408     s->rc.k_modifier      = 14;
409     s->rc.rice_modifier   = 4;
410
411     s->max_coded_frame_size = 8 + (avctx->frame_size*avctx->channels*avctx->bits_per_coded_sample>>3);
412
413     s->write_sample_size  = avctx->bits_per_coded_sample + avctx->channels - 1; // FIXME: consider wasted_bytes
414
415     AV_WB32(alac_extradata,    ALAC_EXTRADATA_SIZE);
416     AV_WB32(alac_extradata+4,  MKBETAG('a','l','a','c'));
417     AV_WB32(alac_extradata+12, avctx->frame_size);
418     AV_WB8 (alac_extradata+17, avctx->bits_per_coded_sample);
419     AV_WB8 (alac_extradata+21, avctx->channels);
420     AV_WB32(alac_extradata+24, s->max_coded_frame_size);
421     AV_WB32(alac_extradata+28,
422             avctx->sample_rate * avctx->channels * avctx->bits_per_coded_sample); // average bitrate
423     AV_WB32(alac_extradata+32, avctx->sample_rate);
424
425     // Set relevant extradata fields
426     if (s->compression_level > 0) {
427         AV_WB8(alac_extradata+18, s->rc.history_mult);
428         AV_WB8(alac_extradata+19, s->rc.initial_history);
429         AV_WB8(alac_extradata+20, s->rc.k_modifier);
430     }
431
432     s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
433     if (avctx->min_prediction_order >= 0) {
434         if (avctx->min_prediction_order < MIN_LPC_ORDER ||
435            avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
436             av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
437                    avctx->min_prediction_order);
438                 return -1;
439         }
440
441         s->min_prediction_order = avctx->min_prediction_order;
442     }
443
444     s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
445     if (avctx->max_prediction_order >= 0) {
446         if (avctx->max_prediction_order < MIN_LPC_ORDER ||
447             avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
448             av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
449                    avctx->max_prediction_order);
450                 return -1;
451         }
452
453         s->max_prediction_order = avctx->max_prediction_order;
454     }
455
456     if (s->max_prediction_order < s->min_prediction_order) {
457         av_log(avctx, AV_LOG_ERROR,
458                "invalid prediction orders: min=%d max=%d\n",
459                s->min_prediction_order, s->max_prediction_order);
460         return -1;
461     }
462
463     avctx->extradata = alac_extradata;
464     avctx->extradata_size = ALAC_EXTRADATA_SIZE;
465
466     avctx->coded_frame = avcodec_alloc_frame();
467     avctx->coded_frame->key_frame = 1;
468
469     s->avctx = avctx;
470     ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size, s->max_prediction_order,
471                       FF_LPC_TYPE_LEVINSON);
472
473     return ret;
474 }
475
476 static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
477                              int buf_size, void *data)
478 {
479     AlacEncodeContext *s = avctx->priv_data;
480     PutBitContext *pb = &s->pbctx;
481     int i, out_bytes, verbatim_flag = 0;
482
483     if (avctx->frame_size > DEFAULT_FRAME_SIZE) {
484         av_log(avctx, AV_LOG_ERROR, "input frame size exceeded\n");
485         return -1;
486     }
487
488     if (buf_size < 2 * s->max_coded_frame_size) {
489         av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");
490         return -1;
491     }
492
493 verbatim:
494     init_put_bits(pb, frame, buf_size);
495
496     if (s->compression_level == 0 || verbatim_flag) {
497         // Verbatim mode
498         const int16_t *samples = data;
499         write_frame_header(s, 1);
500         for (i = 0; i < avctx->frame_size * avctx->channels; i++) {
501             put_sbits(pb, 16, *samples++);
502         }
503     } else {
504         init_sample_buffers(s, data);
505         write_frame_header(s, 0);
506         write_compressed_frame(s);
507     }
508
509     put_bits(pb, 3, 7);
510     flush_put_bits(pb);
511     out_bytes = put_bits_count(pb) >> 3;
512
513     if (out_bytes > s->max_coded_frame_size) {
514         /* frame too large. use verbatim mode */
515         if (verbatim_flag || s->compression_level == 0) {
516             /* still too large. must be an error. */
517             av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
518             return -1;
519         }
520         verbatim_flag = 1;
521         goto verbatim;
522     }
523
524     return out_bytes;
525 }
526
527 static av_cold int alac_encode_close(AVCodecContext *avctx)
528 {
529     AlacEncodeContext *s = avctx->priv_data;
530     ff_lpc_end(&s->lpc_ctx);
531     av_freep(&avctx->extradata);
532     avctx->extradata_size = 0;
533     av_freep(&avctx->coded_frame);
534     return 0;
535 }
536
537 AVCodec ff_alac_encoder = {
538     .name           = "alac",
539     .type           = AVMEDIA_TYPE_AUDIO,
540     .id             = CODEC_ID_ALAC,
541     .priv_data_size = sizeof(AlacEncodeContext),
542     .init           = alac_encode_init,
543     .encode         = alac_encode_frame,
544     .close          = alac_encode_close,
545     .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
546     .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
547                                                   AV_SAMPLE_FMT_NONE },
548     .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
549 };