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