Statistics
| Branch: | Revision:

ffmpeg / libavcodec / alacenc.c @ cc940caf

History | View | Annotate | Download (12.2 KB)

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 "bitstream.h"
24
#include "dsputil.h"
25
#include "lpc.h"
26

    
27
#define DEFAULT_FRAME_SIZE        4096
28
#define DEFAULT_SAMPLE_SIZE       16
29
#define MAX_CHANNELS              8
30
#define ALAC_EXTRADATA_SIZE       36
31
#define ALAC_FRAME_HEADER_SIZE    55
32
#define ALAC_FRAME_FOOTER_SIZE    3
33

    
34
#define ALAC_ESCAPE_CODE          0x1FF
35
#define ALAC_MAX_LPC_ORDER        30
36
#define DEFAULT_MAX_PRED_ORDER    6
37
#define DEFAULT_MIN_PRED_ORDER    4
38
#define ALAC_MAX_LPC_PRECISION    9
39
#define ALAC_MAX_LPC_SHIFT        9
40

    
41
#define ALAC_CHMODE_LEFT_RIGHT    0
42
#define ALAC_CHMODE_LEFT_SIDE     1
43
#define ALAC_CHMODE_RIGHT_SIDE    2
44
#define ALAC_CHMODE_MID_SIDE      3
45

    
46
typedef struct RiceContext {
47
    int history_mult;
48
    int initial_history;
49
    int k_modifier;
50
    int rice_modifier;
51
} RiceContext;
52

    
53
typedef struct LPCContext {
54
    int lpc_order;
55
    int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
56
    int lpc_quant;
57
} LPCContext;
58

    
59
typedef struct AlacEncodeContext {
60
    int compression_level;
61
    int min_prediction_order;
62
    int max_prediction_order;
63
    int max_coded_frame_size;
64
    int write_sample_size;
65
    int32_t sample_buf[MAX_CHANNELS][DEFAULT_FRAME_SIZE];
66
    int32_t predictor_buf[DEFAULT_FRAME_SIZE];
67
    int interlacing_shift;
68
    int interlacing_leftweight;
69
    PutBitContext pbctx;
70
    RiceContext rc;
71
    LPCContext lpc[MAX_CHANNELS];
72
    DSPContext dspctx;
73
    AVCodecContext *avctx;
74
} AlacEncodeContext;
75

    
76

    
77
static void init_sample_buffers(AlacEncodeContext *s, int16_t *input_samples)
78
{
79
    int ch, i;
80

    
81
    for(ch=0;ch<s->avctx->channels;ch++) {
82
        int16_t *sptr = input_samples + ch;
83
        for(i=0;i<s->avctx->frame_size;i++) {
84
            s->sample_buf[ch][i] = *sptr;
85
            sptr += s->avctx->channels;
86
        }
87
    }
88
}
89

    
90
static void encode_scalar(AlacEncodeContext *s, int x, int k, int write_sample_size)
91
{
92
    int divisor, q, r;
93

    
94
    k = FFMIN(k, s->rc.k_modifier);
95
    divisor = (1<<k) - 1;
96
    q = x / divisor;
97
    r = x % divisor;
98

    
99
    if(q > 8) {
100
        // write escape code and sample value directly
101
        put_bits(&s->pbctx, 9, ALAC_ESCAPE_CODE);
102
        put_bits(&s->pbctx, write_sample_size, x);
103
    } else {
104
        if(q)
105
            put_bits(&s->pbctx, q, (1<<q) - 1);
106
        put_bits(&s->pbctx, 1, 0);
107

    
108
        if(k != 1) {
109
            if(r > 0)
110
                put_bits(&s->pbctx, k, r+1);
111
            else
112
                put_bits(&s->pbctx, k-1, 0);
113
        }
114
    }
115
}
116

    
117
static void write_frame_header(AlacEncodeContext *s, int is_verbatim)
118
{
119
    put_bits(&s->pbctx, 3,  s->avctx->channels-1);          // No. of channels -1
120
    put_bits(&s->pbctx, 16, 0);                             // Seems to be zero
121
    put_bits(&s->pbctx, 1,  1);                             // Sample count is in the header
122
    put_bits(&s->pbctx, 2,  0);                             // FIXME: Wasted bytes field
123
    put_bits(&s->pbctx, 1,  is_verbatim);                   // Audio block is verbatim
124
    put_bits(&s->pbctx, 32, s->avctx->frame_size);          // No. of samples in the frame
125
}
126

    
127
static void calc_predictor_params(AlacEncodeContext *s, int ch)
128
{
129
    int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
130
    int shift[MAX_LPC_ORDER];
131
    int opt_order;
132

    
133
    opt_order = ff_lpc_calc_coefs(&s->dspctx, s->sample_buf[ch], s->avctx->frame_size, s->min_prediction_order, s->max_prediction_order,
134
                                   ALAC_MAX_LPC_PRECISION, coefs, shift, 1, ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
135

    
136
    s->lpc[ch].lpc_order = opt_order;
137
    s->lpc[ch].lpc_quant = shift[opt_order-1];
138
    memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
139
}
140

    
141
static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
142
{
143
    int i, best;
144
    int32_t lt, rt;
145
    uint64_t sum[4];
146
    uint64_t score[4];
147

    
148
    /* calculate sum of 2nd order residual for each channel */
149
    sum[0] = sum[1] = sum[2] = sum[3] = 0;
150
    for(i=2; i<n; i++) {
151
        lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
152
        rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
153
        sum[2] += FFABS((lt + rt) >> 1);
154
        sum[3] += FFABS(lt - rt);
155
        sum[0] += FFABS(lt);
156
        sum[1] += FFABS(rt);
157
    }
158

    
159
    /* calculate score for each mode */
160
    score[0] = sum[0] + sum[1];
161
    score[1] = sum[0] + sum[3];
162
    score[2] = sum[1] + sum[3];
163
    score[3] = sum[2] + sum[3];
164

    
165
    /* return mode with lowest score */
166
    best = 0;
167
    for(i=1; i<4; i++) {
168
        if(score[i] < score[best]) {
169
            best = i;
170
        }
171
    }
172
    return best;
173
}
174

    
175
static void alac_stereo_decorrelation(AlacEncodeContext *s)
176
{
177
    int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
178
    int i, mode, n = s->avctx->frame_size;
179
    int32_t tmp;
180

    
181
    mode = estimate_stereo_mode(left, right, n);
182

    
183
    switch(mode)
184
    {
185
        case ALAC_CHMODE_LEFT_RIGHT:
186
            s->interlacing_leftweight = 0;
187
            s->interlacing_shift = 0;
188
            break;
189

    
190
        case ALAC_CHMODE_LEFT_SIDE:
191
            for(i=0; i<n; i++) {
192
                right[i] = left[i] - right[i];
193
            }
194
            s->interlacing_leftweight = 1;
195
            s->interlacing_shift = 0;
196
            break;
197

    
198
        case ALAC_CHMODE_RIGHT_SIDE:
199
            for(i=0; i<n; i++) {
200
                tmp = right[i];
201
                right[i] = left[i] - right[i];
202
                left[i] = tmp + (right[i] >> 31);
203
            }
204
            s->interlacing_leftweight = 1;
205
            s->interlacing_shift = 31;
206
            break;
207

    
208
        default:
209
            for(i=0; i<n; i++) {
210
                tmp = left[i];
211
                left[i] = (tmp + right[i]) >> 1;
212
                right[i] = tmp - right[i];
213
            }
214
            s->interlacing_leftweight = 1;
215
            s->interlacing_shift = 1;
216
            break;
217
    }
218
}
219

    
220
static void write_compressed_frame(AlacEncodeContext *s)
221
{
222
    int i, j;
223

    
224
    /* only simple mid/side decorrelation supported as of now */
225
    alac_stereo_decorrelation(s);
226
    put_bits(&s->pbctx, 8, s->interlacing_shift);
227
    put_bits(&s->pbctx, 8, s->interlacing_leftweight);
228

    
229
    for(i=0;i<s->avctx->channels;i++) {
230

    
231
        calc_predictor_params(s, i);
232

    
233
        put_bits(&s->pbctx, 4, 0);  // prediction type : currently only type 0 has been RE'd
234
        put_bits(&s->pbctx, 4, s->lpc[i].lpc_quant);
235

    
236
        put_bits(&s->pbctx, 3, s->rc.rice_modifier);
237
        put_bits(&s->pbctx, 5, s->lpc[i].lpc_order);
238
        // predictor coeff. table
239
        for(j=0;j<s->lpc[i].lpc_order;j++) {
240
            put_sbits(&s->pbctx, 16, s->lpc[i].lpc_coeff[j]);
241
        }
242
    }
243

    
244
    // apply lpc and entropy coding to audio samples
245

    
246
    for(i=0;i<s->avctx->channels;i++) {
247
        alac_linear_predictor(s, i);
248
        alac_entropy_coder(s);
249
    }
250
}
251

    
252
static av_cold int alac_encode_init(AVCodecContext *avctx)
253
{
254
    AlacEncodeContext *s    = avctx->priv_data;
255
    uint8_t *alac_extradata = av_mallocz(ALAC_EXTRADATA_SIZE+1);
256

    
257
    avctx->frame_size      = DEFAULT_FRAME_SIZE;
258
    avctx->bits_per_sample = DEFAULT_SAMPLE_SIZE;
259

    
260
    if(avctx->sample_fmt != SAMPLE_FMT_S16) {
261
        av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
262
        return -1;
263
    }
264

    
265
    // Set default compression level
266
    if(avctx->compression_level == FF_COMPRESSION_DEFAULT)
267
        s->compression_level = 1;
268
    else
269
        s->compression_level = av_clip(avctx->compression_level, 0, 1);
270

    
271
    // Initialize default Rice parameters
272
    s->rc.history_mult    = 40;
273
    s->rc.initial_history = 10;
274
    s->rc.k_modifier      = 14;
275
    s->rc.rice_modifier   = 4;
276

    
277
    s->max_coded_frame_size = (ALAC_FRAME_HEADER_SIZE + ALAC_FRAME_FOOTER_SIZE +
278
                               avctx->frame_size*avctx->channels*avctx->bits_per_sample)>>3;
279

    
280
    s->write_sample_size  = avctx->bits_per_sample + avctx->channels - 1; // FIXME: consider wasted_bytes
281

    
282
    AV_WB32(alac_extradata,    ALAC_EXTRADATA_SIZE);
283
    AV_WB32(alac_extradata+4,  MKBETAG('a','l','a','c'));
284
    AV_WB32(alac_extradata+12, avctx->frame_size);
285
    AV_WB8 (alac_extradata+17, avctx->bits_per_sample);
286
    AV_WB8 (alac_extradata+21, avctx->channels);
287
    AV_WB32(alac_extradata+24, s->max_coded_frame_size);
288
    AV_WB32(alac_extradata+28, avctx->sample_rate*avctx->channels*avctx->bits_per_sample); // average bitrate
289
    AV_WB32(alac_extradata+32, avctx->sample_rate);
290

    
291
    // Set relevant extradata fields
292
    if(s->compression_level > 0) {
293
        AV_WB8(alac_extradata+18, s->rc.history_mult);
294
        AV_WB8(alac_extradata+19, s->rc.initial_history);
295
        AV_WB8(alac_extradata+20, s->rc.k_modifier);
296
    }
297

    
298
    if(avctx->min_prediction_order >= 0) {
299
        if(avctx->min_prediction_order < MIN_LPC_ORDER ||
300
            avctx->min_prediction_order > MAX_LPC_ORDER) {
301
            av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n", avctx->min_prediction_order);
302
                return -1;
303
        }
304

    
305
        s->min_prediction_order = avctx->min_prediction_order;
306
    }
307

    
308
    if(avctx->max_prediction_order >= 0) {
309
        if(avctx->max_prediction_order < MIN_LPC_ORDER ||
310
           avctx->max_prediction_order > MAX_LPC_ORDER) {
311
            av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n", avctx->max_prediction_order);
312
                return -1;
313
        }
314

    
315
        s->max_prediction_order = avctx->max_prediction_order;
316
    }
317

    
318
    if(s->max_prediction_order < s->min_prediction_order) {
319
        av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
320
               s->min_prediction_order, s->max_prediction_order);
321
        return -1;
322
    }
323

    
324
    avctx->extradata = alac_extradata;
325
    avctx->extradata_size = ALAC_EXTRADATA_SIZE;
326

    
327
    avctx->coded_frame = avcodec_alloc_frame();
328
    avctx->coded_frame->key_frame = 1;
329

    
330
    s->avctx = avctx;
331
    dsputil_init(&s->dspctx, avctx);
332

    
333
    return 0;
334
}
335

    
336
static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
337
                             int buf_size, void *data)
338
{
339
    AlacEncodeContext *s = avctx->priv_data;
340
    PutBitContext *pb = &s->pbctx;
341
    int i, out_bytes, verbatim_flag = 0;
342

    
343
    if(avctx->frame_size > DEFAULT_FRAME_SIZE) {
344
        av_log(avctx, AV_LOG_ERROR, "input frame size exceeded\n");
345
        return -1;
346
    }
347

    
348
    if(buf_size < 2*s->max_coded_frame_size) {
349
        av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");
350
        return -1;
351
    }
352

    
353
verbatim:
354
    init_put_bits(pb, frame, buf_size);
355

    
356
    if((s->compression_level == 0) || verbatim_flag) {
357
        // Verbatim mode
358
        int16_t *samples = data;
359
        write_frame_header(s, 1);
360
        for(i=0; i<avctx->frame_size*avctx->channels; i++) {
361
            put_sbits(pb, 16, *samples++);
362
        }
363
    } else {
364
        init_sample_buffers(s, data);
365
        write_frame_header(s, 0);
366
        write_compressed_frame(s);
367
    }
368

    
369
    put_bits(pb, 3, 7);
370
    flush_put_bits(pb);
371
    out_bytes = put_bits_count(pb) >> 3;
372

    
373
    if(out_bytes > s->max_coded_frame_size) {
374
        /* frame too large. use verbatim mode */
375
        if(verbatim_flag || (s->compression_level == 0)) {
376
            /* still too large. must be an error. */
377
            av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
378
            return -1;
379
        }
380
        verbatim_flag = 1;
381
        goto verbatim;
382
    }
383

    
384
    return out_bytes;
385
}
386

    
387
static av_cold int alac_encode_close(AVCodecContext *avctx)
388
{
389
    av_freep(&avctx->extradata);
390
    avctx->extradata_size = 0;
391
    av_freep(&avctx->coded_frame);
392
    return 0;
393
}
394

    
395
AVCodec alac_encoder = {
396
    "alac",
397
    CODEC_TYPE_AUDIO,
398
    CODEC_ID_ALAC,
399
    sizeof(AlacEncodeContext),
400
    alac_encode_init,
401
    alac_encode_frame,
402
    alac_encode_close,
403
    .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
404
    .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
405
};