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