Statistics
| Branch: | Revision:

ffmpeg / libavcodec / flacenc.c @ 19b9c7cc

History | View | Annotate | Download (42.7 KB)

1
/**
2
 * FLAC audio encoder
3
 * Copyright (c) 2006  Justin Ruggles <jruggle@earthlink.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 "crc.h"
25
#include "golomb.h"
26
#include "lls.h"
27

    
28
#define FLAC_MAX_CH  8
29
#define FLAC_MIN_BLOCKSIZE  16
30
#define FLAC_MAX_BLOCKSIZE  65535
31

    
32
#define FLAC_SUBFRAME_CONSTANT  0
33
#define FLAC_SUBFRAME_VERBATIM  1
34
#define FLAC_SUBFRAME_FIXED     8
35
#define FLAC_SUBFRAME_LPC      32
36

    
37
#define FLAC_CHMODE_NOT_STEREO      0
38
#define FLAC_CHMODE_LEFT_RIGHT      1
39
#define FLAC_CHMODE_LEFT_SIDE       8
40
#define FLAC_CHMODE_RIGHT_SIDE      9
41
#define FLAC_CHMODE_MID_SIDE       10
42

    
43
#define ORDER_METHOD_EST     0
44
#define ORDER_METHOD_2LEVEL  1
45
#define ORDER_METHOD_4LEVEL  2
46
#define ORDER_METHOD_8LEVEL  3
47
#define ORDER_METHOD_SEARCH  4
48
#define ORDER_METHOD_LOG     5
49

    
50
#define FLAC_STREAMINFO_SIZE  34
51

    
52
#define MIN_LPC_ORDER       1
53
#define MAX_LPC_ORDER      32
54
#define MAX_FIXED_ORDER     4
55
#define MAX_PARTITION_ORDER 8
56
#define MAX_PARTITIONS     (1 << MAX_PARTITION_ORDER)
57
#define MAX_LPC_PRECISION  15
58
#define MAX_LPC_SHIFT      15
59
#define MAX_RICE_PARAM     14
60

    
61
typedef struct CompressionOptions {
62
    int compression_level;
63
    int block_time_ms;
64
    int use_lpc;
65
    int lpc_coeff_precision;
66
    int min_prediction_order;
67
    int max_prediction_order;
68
    int prediction_order_method;
69
    int min_partition_order;
70
    int max_partition_order;
71
} CompressionOptions;
72

    
73
typedef struct RiceContext {
74
    int porder;
75
    int params[MAX_PARTITIONS];
76
} RiceContext;
77

    
78
typedef struct FlacSubframe {
79
    int type;
80
    int type_code;
81
    int obits;
82
    int order;
83
    int32_t coefs[MAX_LPC_ORDER];
84
    int shift;
85
    RiceContext rc;
86
    int32_t samples[FLAC_MAX_BLOCKSIZE];
87
    int32_t residual[FLAC_MAX_BLOCKSIZE+1];
88
} FlacSubframe;
89

    
90
typedef struct FlacFrame {
91
    FlacSubframe subframes[FLAC_MAX_CH];
92
    int blocksize;
93
    int bs_code[2];
94
    uint8_t crc8;
95
    int ch_mode;
96
} FlacFrame;
97

    
98
typedef struct FlacEncodeContext {
99
    PutBitContext pb;
100
    int channels;
101
    int ch_code;
102
    int samplerate;
103
    int sr_code[2];
104
    int blocksize;
105
    int max_framesize;
106
    uint32_t frame_count;
107
    FlacFrame frame;
108
    CompressionOptions options;
109
    AVCodecContext *avctx;
110
} FlacEncodeContext;
111

    
112
static const int flac_samplerates[16] = {
113
    0, 0, 0, 0,
114
    8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
115
    0, 0, 0, 0
116
};
117

    
118
static const int flac_blocksizes[16] = {
119
    0,
120
    192,
121
    576, 1152, 2304, 4608,
122
    0, 0,
123
    256, 512, 1024, 2048, 4096, 8192, 16384, 32768
124
};
125

    
126
/**
127
 * Writes streaminfo metadata block to byte array
128
 */
129
static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
130
{
131
    PutBitContext pb;
132

    
133
    memset(header, 0, FLAC_STREAMINFO_SIZE);
134
    init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
135

    
136
    /* streaminfo metadata block */
137
    put_bits(&pb, 16, s->blocksize);
138
    put_bits(&pb, 16, s->blocksize);
139
    put_bits(&pb, 24, 0);
140
    put_bits(&pb, 24, s->max_framesize);
141
    put_bits(&pb, 20, s->samplerate);
142
    put_bits(&pb, 3, s->channels-1);
143
    put_bits(&pb, 5, 15);       /* bits per sample - 1 */
144
    flush_put_bits(&pb);
145
    /* total samples = 0 */
146
    /* MD5 signature = 0 */
147
}
148

    
149
/**
150
 * Sets blocksize based on samplerate
151
 * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
152
 */
153
static int select_blocksize(int samplerate, int block_time_ms)
154
{
155
    int i;
156
    int target;
157
    int blocksize;
158

    
159
    assert(samplerate > 0);
160
    blocksize = flac_blocksizes[1];
161
    target = (samplerate * block_time_ms) / 1000;
162
    for(i=0; i<16; i++) {
163
        if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
164
            blocksize = flac_blocksizes[i];
165
        }
166
    }
167
    return blocksize;
168
}
169

    
170
static int flac_encode_init(AVCodecContext *avctx)
171
{
172
    int freq = avctx->sample_rate;
173
    int channels = avctx->channels;
174
    FlacEncodeContext *s = avctx->priv_data;
175
    int i, level;
176
    uint8_t *streaminfo;
177

    
178
    s->avctx = avctx;
179

    
180
    if(avctx->sample_fmt != SAMPLE_FMT_S16) {
181
        return -1;
182
    }
183

    
184
    if(channels < 1 || channels > FLAC_MAX_CH) {
185
        return -1;
186
    }
187
    s->channels = channels;
188
    s->ch_code = s->channels-1;
189

    
190
    /* find samplerate in table */
191
    if(freq < 1)
192
        return -1;
193
    for(i=4; i<12; i++) {
194
        if(freq == flac_samplerates[i]) {
195
            s->samplerate = flac_samplerates[i];
196
            s->sr_code[0] = i;
197
            s->sr_code[1] = 0;
198
            break;
199
        }
200
    }
201
    /* if not in table, samplerate is non-standard */
202
    if(i == 12) {
203
        if(freq % 1000 == 0 && freq < 255000) {
204
            s->sr_code[0] = 12;
205
            s->sr_code[1] = freq / 1000;
206
        } else if(freq % 10 == 0 && freq < 655350) {
207
            s->sr_code[0] = 14;
208
            s->sr_code[1] = freq / 10;
209
        } else if(freq < 65535) {
210
            s->sr_code[0] = 13;
211
            s->sr_code[1] = freq;
212
        } else {
213
            return -1;
214
        }
215
        s->samplerate = freq;
216
    }
217

    
218
    /* set compression option defaults based on avctx->compression_level */
219
    if(avctx->compression_level < 0) {
220
        s->options.compression_level = 5;
221
    } else {
222
        s->options.compression_level = avctx->compression_level;
223
    }
224
    av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
225

    
226
    level= s->options.compression_level;
227
    if(level > 12) {
228
        av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
229
               s->options.compression_level);
230
        return -1;
231
    }
232

    
233
    s->options.block_time_ms       = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
234
    s->options.use_lpc             = ((int[]){  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
235
    s->options.min_prediction_order= ((int[]){  2,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
236
    s->options.max_prediction_order= ((int[]){  3,  4,  4,  6,  8,  8,  8,  8, 12, 12, 12, 32, 32})[level];
237
    s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
238
                                                   ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
239
                                                   ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG,    ORDER_METHOD_4LEVEL,
240
                                                   ORDER_METHOD_LOG,    ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
241
                                                   ORDER_METHOD_SEARCH})[level];
242
    s->options.min_partition_order = ((int[]){  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0})[level];
243
    s->options.max_partition_order = ((int[]){  2,  2,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,  8})[level];
244

    
245
    /* set compression option overrides from AVCodecContext */
246
    if(avctx->use_lpc >= 0) {
247
        s->options.use_lpc = av_clip(avctx->use_lpc, 0, 11);
248
    }
249
    if(s->options.use_lpc == 1)
250
        av_log(avctx, AV_LOG_DEBUG, " use lpc: Levinson-Durbin recursion with Welch window\n");
251
    else if(s->options.use_lpc > 1)
252
        av_log(avctx, AV_LOG_DEBUG, " use lpc: Cholesky factorization\n");
253

    
254
    if(avctx->min_prediction_order >= 0) {
255
        if(s->options.use_lpc) {
256
            if(avctx->min_prediction_order < MIN_LPC_ORDER ||
257
                    avctx->min_prediction_order > MAX_LPC_ORDER) {
258
                av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
259
                       avctx->min_prediction_order);
260
                return -1;
261
            }
262
        } else {
263
            if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
264
                av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
265
                       avctx->min_prediction_order);
266
                return -1;
267
            }
268
        }
269
        s->options.min_prediction_order = avctx->min_prediction_order;
270
    }
271
    if(avctx->max_prediction_order >= 0) {
272
        if(s->options.use_lpc) {
273
            if(avctx->max_prediction_order < MIN_LPC_ORDER ||
274
                    avctx->max_prediction_order > MAX_LPC_ORDER) {
275
                av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
276
                       avctx->max_prediction_order);
277
                return -1;
278
            }
279
        } else {
280
            if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
281
                av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
282
                       avctx->max_prediction_order);
283
                return -1;
284
            }
285
        }
286
        s->options.max_prediction_order = avctx->max_prediction_order;
287
    }
288
    if(s->options.max_prediction_order < s->options.min_prediction_order) {
289
        av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
290
               s->options.min_prediction_order, s->options.max_prediction_order);
291
        return -1;
292
    }
293
    av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
294
           s->options.min_prediction_order, s->options.max_prediction_order);
295

    
296
    if(avctx->prediction_order_method >= 0) {
297
        if(avctx->prediction_order_method > ORDER_METHOD_LOG) {
298
            av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
299
                   avctx->prediction_order_method);
300
            return -1;
301
        }
302
        s->options.prediction_order_method = avctx->prediction_order_method;
303
    }
304
    switch(s->options.prediction_order_method) {
305
        case ORDER_METHOD_EST:    av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
306
                                         "estimate"); break;
307
        case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
308
                                         "2-level"); break;
309
        case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
310
                                         "4-level"); break;
311
        case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
312
                                         "8-level"); break;
313
        case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
314
                                         "full search"); break;
315
        case ORDER_METHOD_LOG:    av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
316
                                         "log search"); break;
317
    }
318

    
319
    if(avctx->min_partition_order >= 0) {
320
        if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
321
            av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
322
                   avctx->min_partition_order);
323
            return -1;
324
        }
325
        s->options.min_partition_order = avctx->min_partition_order;
326
    }
327
    if(avctx->max_partition_order >= 0) {
328
        if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
329
            av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
330
                   avctx->max_partition_order);
331
            return -1;
332
        }
333
        s->options.max_partition_order = avctx->max_partition_order;
334
    }
335
    if(s->options.max_partition_order < s->options.min_partition_order) {
336
        av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
337
               s->options.min_partition_order, s->options.max_partition_order);
338
        return -1;
339
    }
340
    av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
341
           s->options.min_partition_order, s->options.max_partition_order);
342

    
343
    if(avctx->frame_size > 0) {
344
        if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
345
                avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
346
            av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
347
                   avctx->frame_size);
348
            return -1;
349
        }
350
        s->blocksize = avctx->frame_size;
351
    } else {
352
        s->blocksize = select_blocksize(s->samplerate, s->options.block_time_ms);
353
        avctx->frame_size = s->blocksize;
354
    }
355
    av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->blocksize);
356

    
357
    /* set LPC precision */
358
    if(avctx->lpc_coeff_precision > 0) {
359
        if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
360
            av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
361
                   avctx->lpc_coeff_precision);
362
            return -1;
363
        }
364
        s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
365
    } else {
366
        /* select LPC precision based on block size */
367
        if(     s->blocksize <=   192) s->options.lpc_coeff_precision =  7;
368
        else if(s->blocksize <=   384) s->options.lpc_coeff_precision =  8;
369
        else if(s->blocksize <=   576) s->options.lpc_coeff_precision =  9;
370
        else if(s->blocksize <=  1152) s->options.lpc_coeff_precision = 10;
371
        else if(s->blocksize <=  2304) s->options.lpc_coeff_precision = 11;
372
        else if(s->blocksize <=  4608) s->options.lpc_coeff_precision = 12;
373
        else if(s->blocksize <=  8192) s->options.lpc_coeff_precision = 13;
374
        else if(s->blocksize <= 16384) s->options.lpc_coeff_precision = 14;
375
        else                           s->options.lpc_coeff_precision = 15;
376
    }
377
    av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
378
           s->options.lpc_coeff_precision);
379

    
380
    /* set maximum encoded frame size in verbatim mode */
381
    if(s->channels == 2) {
382
        s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
383
    } else {
384
        s->max_framesize = 14 + (s->blocksize * s->channels * 2);
385
    }
386

    
387
    streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
388
    write_streaminfo(s, streaminfo);
389
    avctx->extradata = streaminfo;
390
    avctx->extradata_size = FLAC_STREAMINFO_SIZE;
391

    
392
    s->frame_count = 0;
393

    
394
    avctx->coded_frame = avcodec_alloc_frame();
395
    avctx->coded_frame->key_frame = 1;
396

    
397
    return 0;
398
}
399

    
400
static void init_frame(FlacEncodeContext *s)
401
{
402
    int i, ch;
403
    FlacFrame *frame;
404

    
405
    frame = &s->frame;
406

    
407
    for(i=0; i<16; i++) {
408
        if(s->blocksize == flac_blocksizes[i]) {
409
            frame->blocksize = flac_blocksizes[i];
410
            frame->bs_code[0] = i;
411
            frame->bs_code[1] = 0;
412
            break;
413
        }
414
    }
415
    if(i == 16) {
416
        frame->blocksize = s->blocksize;
417
        if(frame->blocksize <= 256) {
418
            frame->bs_code[0] = 6;
419
            frame->bs_code[1] = frame->blocksize-1;
420
        } else {
421
            frame->bs_code[0] = 7;
422
            frame->bs_code[1] = frame->blocksize-1;
423
        }
424
    }
425

    
426
    for(ch=0; ch<s->channels; ch++) {
427
        frame->subframes[ch].obits = 16;
428
    }
429
}
430

    
431
/**
432
 * Copy channel-interleaved input samples into separate subframes
433
 */
434
static void copy_samples(FlacEncodeContext *s, int16_t *samples)
435
{
436
    int i, j, ch;
437
    FlacFrame *frame;
438

    
439
    frame = &s->frame;
440
    for(i=0,j=0; i<frame->blocksize; i++) {
441
        for(ch=0; ch<s->channels; ch++,j++) {
442
            frame->subframes[ch].samples[i] = samples[j];
443
        }
444
    }
445
}
446

    
447

    
448
#define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
449

    
450
/**
451
 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0
452
 */
453
static int find_optimal_param(uint32_t sum, int n)
454
{
455
    int k;
456
    uint32_t sum2;
457

    
458
    if(sum <= n>>1)
459
        return 0;
460
    sum2 = sum-(n>>1);
461
    k = av_log2(n<256 ? FASTDIV(sum2,n) : sum2/n);
462
    return FFMIN(k, MAX_RICE_PARAM);
463
}
464

    
465
static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
466
                                         uint32_t *sums, int n, int pred_order)
467
{
468
    int i;
469
    int k, cnt, part;
470
    uint32_t all_bits;
471

    
472
    part = (1 << porder);
473
    all_bits = 0;
474

    
475
    cnt = (n >> porder) - pred_order;
476
    for(i=0; i<part; i++) {
477
        if(i == 1) cnt = (n >> porder);
478
        k = find_optimal_param(sums[i], cnt);
479
        rc->params[i] = k;
480
        all_bits += rice_encode_count(sums[i], cnt, k);
481
    }
482
    all_bits += (4 * part);
483

    
484
    rc->porder = porder;
485

    
486
    return all_bits;
487
}
488

    
489
static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
490
                      uint32_t sums[][MAX_PARTITIONS])
491
{
492
    int i, j;
493
    int parts;
494
    uint32_t *res, *res_end;
495

    
496
    /* sums for highest level */
497
    parts = (1 << pmax);
498
    res = &data[pred_order];
499
    res_end = &data[n >> pmax];
500
    for(i=0; i<parts; i++) {
501
        uint32_t sum = 0;
502
        while(res < res_end){
503
            sum += *(res++);
504
        }
505
        sums[pmax][i] = sum;
506
        res_end+= n >> pmax;
507
    }
508
    /* sums for lower levels */
509
    for(i=pmax-1; i>=pmin; i--) {
510
        parts = (1 << i);
511
        for(j=0; j<parts; j++) {
512
            sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
513
        }
514
    }
515
}
516

    
517
static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
518
                                 int32_t *data, int n, int pred_order)
519
{
520
    int i;
521
    uint32_t bits[MAX_PARTITION_ORDER+1];
522
    int opt_porder;
523
    RiceContext tmp_rc;
524
    uint32_t *udata;
525
    uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
526

    
527
    assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
528
    assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
529
    assert(pmin <= pmax);
530

    
531
    udata = av_malloc(n * sizeof(uint32_t));
532
    for(i=0; i<n; i++) {
533
        udata[i] = (2*data[i]) ^ (data[i]>>31);
534
    }
535

    
536
    calc_sums(pmin, pmax, udata, n, pred_order, sums);
537

    
538
    opt_porder = pmin;
539
    bits[pmin] = UINT32_MAX;
540
    for(i=pmin; i<=pmax; i++) {
541
        bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
542
        if(bits[i] <= bits[opt_porder]) {
543
            opt_porder = i;
544
            *rc= tmp_rc;
545
        }
546
    }
547

    
548
    av_freep(&udata);
549
    return bits[opt_porder];
550
}
551

    
552
static int get_max_p_order(int max_porder, int n, int order)
553
{
554
    int porder = FFMIN(max_porder, av_log2(n^(n-1)));
555
    if(order > 0)
556
        porder = FFMIN(porder, av_log2(n/order));
557
    return porder;
558
}
559

    
560
static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
561
                                       int32_t *data, int n, int pred_order,
562
                                       int bps)
563
{
564
    uint32_t bits;
565
    pmin = get_max_p_order(pmin, n, pred_order);
566
    pmax = get_max_p_order(pmax, n, pred_order);
567
    bits = pred_order*bps + 6;
568
    bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
569
    return bits;
570
}
571

    
572
static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
573
                                     int32_t *data, int n, int pred_order,
574
                                     int bps, int precision)
575
{
576
    uint32_t bits;
577
    pmin = get_max_p_order(pmin, n, pred_order);
578
    pmax = get_max_p_order(pmax, n, pred_order);
579
    bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
580
    bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
581
    return bits;
582
}
583

    
584
/**
585
 * Apply Welch window function to audio block
586
 */
587
static void apply_welch_window(const int32_t *data, int len, double *w_data)
588
{
589
    int i, n2;
590
    double w;
591
    double c;
592

    
593
    n2 = (len >> 1);
594
    c = 2.0 / (len - 1.0);
595
    for(i=0; i<n2; i++) {
596
        w = c - i - 1.0;
597
        w = 1.0 - (w * w);
598
        w_data[i] = data[i] * w;
599
        w_data[len-1-i] = data[len-1-i] * w;
600
    }
601
}
602

    
603
/**
604
 * Calculates autocorrelation data from audio samples
605
 * A Welch window function is applied before calculation.
606
 */
607
static void compute_autocorr(const int32_t *data, int len, int lag,
608
                             double *autoc)
609
{
610
    int i, j;
611
    double tmp[len + lag + 1];
612
    double *data1= tmp + lag;
613

    
614
    apply_welch_window(data, len, data1);
615

    
616
    for(j=0; j<lag; j++)
617
        data1[j-lag]= 0.0;
618
    data1[len] = 0.0;
619

    
620
    for(j=0; j<lag; j+=2){
621
        double sum0 = 1.0, sum1 = 1.0;
622
        for(i=0; i<len; i++){
623
            sum0 += data1[i] * data1[i-j];
624
            sum1 += data1[i] * data1[i-j-1];
625
        }
626
        autoc[j  ] = sum0;
627
        autoc[j+1] = sum1;
628
    }
629

    
630
    if(j==lag){
631
        double sum = 1.0;
632
        for(i=0; i<len; i+=2){
633
            sum += data1[i  ] * data1[i-j  ]
634
                 + data1[i+1] * data1[i-j+1];
635
        }
636
        autoc[j] = sum;
637
    }
638
}
639

    
640
/**
641
 * Levinson-Durbin recursion.
642
 * Produces LPC coefficients from autocorrelation data.
643
 */
644
static void compute_lpc_coefs(const double *autoc, int max_order,
645
                              double lpc[][MAX_LPC_ORDER], double *ref)
646
{
647
   int i, j, i2;
648
   double r, err, tmp;
649
   double lpc_tmp[MAX_LPC_ORDER];
650

    
651
   for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
652
   err = autoc[0];
653

    
654
   for(i=0; i<max_order; i++) {
655
      r = -autoc[i+1];
656
      for(j=0; j<i; j++) {
657
          r -= lpc_tmp[j] * autoc[i-j];
658
      }
659
      r /= err;
660
      ref[i] = fabs(r);
661

    
662
      err *= 1.0 - (r * r);
663

    
664
      i2 = (i >> 1);
665
      lpc_tmp[i] = r;
666
      for(j=0; j<i2; j++) {
667
         tmp = lpc_tmp[j];
668
         lpc_tmp[j] += r * lpc_tmp[i-1-j];
669
         lpc_tmp[i-1-j] += r * tmp;
670
      }
671
      if(i & 1) {
672
          lpc_tmp[j] += lpc_tmp[j] * r;
673
      }
674

    
675
      for(j=0; j<=i; j++) {
676
          lpc[i][j] = -lpc_tmp[j];
677
      }
678
   }
679
}
680

    
681
/**
682
 * Quantize LPC coefficients
683
 */
684
static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
685
                               int32_t *lpc_out, int *shift)
686
{
687
    int i;
688
    double cmax, error;
689
    int32_t qmax;
690
    int sh;
691

    
692
    /* define maximum levels */
693
    qmax = (1 << (precision - 1)) - 1;
694

    
695
    /* find maximum coefficient value */
696
    cmax = 0.0;
697
    for(i=0; i<order; i++) {
698
        cmax= FFMAX(cmax, fabs(lpc_in[i]));
699
    }
700

    
701
    /* if maximum value quantizes to zero, return all zeros */
702
    if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
703
        *shift = 0;
704
        memset(lpc_out, 0, sizeof(int32_t) * order);
705
        return;
706
    }
707

    
708
    /* calculate level shift which scales max coeff to available bits */
709
    sh = MAX_LPC_SHIFT;
710
    while((cmax * (1 << sh) > qmax) && (sh > 0)) {
711
        sh--;
712
    }
713

    
714
    /* since negative shift values are unsupported in decoder, scale down
715
       coefficients instead */
716
    if(sh == 0 && cmax > qmax) {
717
        double scale = ((double)qmax) / cmax;
718
        for(i=0; i<order; i++) {
719
            lpc_in[i] *= scale;
720
        }
721
    }
722

    
723
    /* output quantized coefficients and level shift */
724
    error=0;
725
    for(i=0; i<order; i++) {
726
        error += lpc_in[i] * (1 << sh);
727
        lpc_out[i] = av_clip(lrintf(error), -qmax, qmax);
728
        error -= lpc_out[i];
729
    }
730
    *shift = sh;
731
}
732

    
733
static int estimate_best_order(double *ref, int max_order)
734
{
735
    int i, est;
736

    
737
    est = 1;
738
    for(i=max_order-1; i>=0; i--) {
739
        if(ref[i] > 0.10) {
740
            est = i+1;
741
            break;
742
        }
743
    }
744
    return est;
745
}
746

    
747
/**
748
 * Calculate LPC coefficients for multiple orders
749
 */
750
static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
751
                          int precision, int32_t coefs[][MAX_LPC_ORDER],
752
                          int *shift, int use_lpc, int omethod)
753
{
754
    double autoc[MAX_LPC_ORDER+1];
755
    double ref[MAX_LPC_ORDER];
756
    double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
757
    int i, j, pass;
758
    int opt_order;
759

    
760
    assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
761

    
762
    if(use_lpc == 1){
763
        compute_autocorr(samples, blocksize, max_order, autoc);
764

    
765
        compute_lpc_coefs(autoc, max_order, lpc, ref);
766
    }else{
767
        LLSModel m[2];
768
        double var[MAX_LPC_ORDER+1], eval, weight;
769

    
770
        for(pass=0; pass<use_lpc-1; pass++){
771
            av_init_lls(&m[pass&1], max_order);
772

    
773
            weight=0;
774
            for(i=max_order; i<blocksize; i++){
775
                for(j=0; j<=max_order; j++)
776
                    var[j]= samples[i-j];
777

    
778
                if(pass){
779
                    eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
780
                    eval= (512>>pass) + fabs(eval - var[0]);
781
                    for(j=0; j<=max_order; j++)
782
                        var[j]/= sqrt(eval);
783
                    weight += 1/eval;
784
                }else
785
                    weight++;
786

    
787
                av_update_lls(&m[pass&1], var, 1.0);
788
            }
789
            av_solve_lls(&m[pass&1], 0.001, 0);
790
        }
791

    
792
        for(i=0; i<max_order; i++){
793
            for(j=0; j<max_order; j++)
794
                lpc[i][j]= m[(pass-1)&1].coeff[i][j];
795
            ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
796
        }
797
        for(i=max_order-1; i>0; i--)
798
            ref[i] = ref[i-1] - ref[i];
799
    }
800
    opt_order = max_order;
801

    
802
    if(omethod == ORDER_METHOD_EST) {
803
        opt_order = estimate_best_order(ref, max_order);
804
        i = opt_order-1;
805
        quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
806
    } else {
807
        for(i=0; i<max_order; i++) {
808
            quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
809
        }
810
    }
811

    
812
    return opt_order;
813
}
814

    
815

    
816
static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
817
{
818
    assert(n > 0);
819
    memcpy(res, smp, n * sizeof(int32_t));
820
}
821

    
822
static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
823
                                  int order)
824
{
825
    int i;
826

    
827
    for(i=0; i<order; i++) {
828
        res[i] = smp[i];
829
    }
830

    
831
    if(order==0){
832
        for(i=order; i<n; i++)
833
            res[i]= smp[i];
834
    }else if(order==1){
835
        for(i=order; i<n; i++)
836
            res[i]= smp[i] - smp[i-1];
837
    }else if(order==2){
838
        for(i=order; i<n; i++)
839
            res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
840
    }else if(order==3){
841
        for(i=order; i<n; i++)
842
            res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
843
    }else{
844
        for(i=order; i<n; i++)
845
            res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
846
    }
847
}
848

    
849
#define LPC1(x) {\
850
    int s = smp[i-(x)+1];\
851
    p1 += c*s;\
852
    c = coefs[(x)-2];\
853
    p0 += c*s;\
854
}
855

    
856
static av_always_inline void encode_residual_lpc_unrolled(
857
    int32_t *res, const int32_t *smp, int n,
858
    int order, const int32_t *coefs, int shift, int big)
859
{
860
    int i;
861
    for(i=order; i<n; i+=2) {
862
        int c = coefs[order-1];
863
        int p0 = c * smp[i-order];
864
        int p1 = 0;
865
        if(big) {
866
            switch(order) {
867
                case 32: LPC1(32)
868
                case 31: LPC1(31)
869
                case 30: LPC1(30)
870
                case 29: LPC1(29)
871
                case 28: LPC1(28)
872
                case 27: LPC1(27)
873
                case 26: LPC1(26)
874
                case 25: LPC1(25)
875
                case 24: LPC1(24)
876
                case 23: LPC1(23)
877
                case 22: LPC1(22)
878
                case 21: LPC1(21)
879
                case 20: LPC1(20)
880
                case 19: LPC1(19)
881
                case 18: LPC1(18)
882
                case 17: LPC1(17)
883
                case 16: LPC1(16)
884
                case 15: LPC1(15)
885
                case 14: LPC1(14)
886
                case 13: LPC1(13)
887
                case 12: LPC1(12)
888
                case 11: LPC1(11)
889
                case 10: LPC1(10)
890
                case  9: LPC1( 9)
891
                         LPC1( 8)
892
                         LPC1( 7)
893
                         LPC1( 6)
894
                         LPC1( 5)
895
                         LPC1( 4)
896
                         LPC1( 3)
897
                         LPC1( 2)
898
            }
899
        } else {
900
            switch(order) {
901
                case  8: LPC1( 8)
902
                case  7: LPC1( 7)
903
                case  6: LPC1( 6)
904
                case  5: LPC1( 5)
905
                case  4: LPC1( 4)
906
                case  3: LPC1( 3)
907
                case  2: LPC1( 2)
908
            }
909
        }
910
        p1 += c * smp[i];
911
        res[i  ] = smp[i  ] - (p0 >> shift);
912
        res[i+1] = smp[i+1] - (p1 >> shift);
913
    }
914
}
915

    
916
static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
917
                                int order, const int32_t *coefs, int shift)
918
{
919
    int i;
920
    for(i=0; i<order; i++) {
921
        res[i] = smp[i];
922
    }
923
#ifdef CONFIG_SMALL
924
    for(i=order; i<n; i+=2) {
925
        int j;
926
        int32_t c = coefs[0];
927
        int32_t p0 = 0, p1 = c*smp[i];
928
        for(j=1; j<order; j++) {
929
            int32_t s = smp[i-j];
930
            p0 += c*s;
931
            c = coefs[j];
932
            p1 += c*s;
933
        }
934
        p0 += c*smp[i-order];
935
        res[i+0] = smp[i+0] - (p0 >> shift);
936
        res[i+1] = smp[i+1] - (p1 >> shift);
937
    }
938
#else
939
    switch(order) {
940
        case  1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
941
        case  2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
942
        case  3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
943
        case  4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
944
        case  5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
945
        case  6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
946
        case  7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
947
        case  8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
948
        default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
949
    }
950
#endif
951
}
952

    
953
static int encode_residual(FlacEncodeContext *ctx, int ch)
954
{
955
    int i, n;
956
    int min_order, max_order, opt_order, precision, omethod;
957
    int min_porder, max_porder;
958
    FlacFrame *frame;
959
    FlacSubframe *sub;
960
    int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
961
    int shift[MAX_LPC_ORDER];
962
    int32_t *res, *smp;
963

    
964
    frame = &ctx->frame;
965
    sub = &frame->subframes[ch];
966
    res = sub->residual;
967
    smp = sub->samples;
968
    n = frame->blocksize;
969

    
970
    /* CONSTANT */
971
    for(i=1; i<n; i++) {
972
        if(smp[i] != smp[0]) break;
973
    }
974
    if(i == n) {
975
        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
976
        res[0] = smp[0];
977
        return sub->obits;
978
    }
979

    
980
    /* VERBATIM */
981
    if(n < 5) {
982
        sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
983
        encode_residual_verbatim(res, smp, n);
984
        return sub->obits * n;
985
    }
986

    
987
    min_order = ctx->options.min_prediction_order;
988
    max_order = ctx->options.max_prediction_order;
989
    min_porder = ctx->options.min_partition_order;
990
    max_porder = ctx->options.max_partition_order;
991
    precision = ctx->options.lpc_coeff_precision;
992
    omethod = ctx->options.prediction_order_method;
993

    
994
    /* FIXED */
995
    if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
996
        uint32_t bits[MAX_FIXED_ORDER+1];
997
        if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
998
        opt_order = 0;
999
        bits[0] = UINT32_MAX;
1000
        for(i=min_order; i<=max_order; i++) {
1001
            encode_residual_fixed(res, smp, n, i);
1002
            bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
1003
                                             n, i, sub->obits);
1004
            if(bits[i] < bits[opt_order]) {
1005
                opt_order = i;
1006
            }
1007
        }
1008
        sub->order = opt_order;
1009
        sub->type = FLAC_SUBFRAME_FIXED;
1010
        sub->type_code = sub->type | sub->order;
1011
        if(sub->order != max_order) {
1012
            encode_residual_fixed(res, smp, n, sub->order);
1013
            return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
1014
                                          sub->order, sub->obits);
1015
        }
1016
        return bits[sub->order];
1017
    }
1018

    
1019
    /* LPC */
1020
    opt_order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
1021

    
1022
    if(omethod == ORDER_METHOD_2LEVEL ||
1023
       omethod == ORDER_METHOD_4LEVEL ||
1024
       omethod == ORDER_METHOD_8LEVEL) {
1025
        int levels = 1 << omethod;
1026
        uint32_t bits[levels];
1027
        int order;
1028
        int opt_index = levels-1;
1029
        opt_order = max_order-1;
1030
        bits[opt_index] = UINT32_MAX;
1031
        for(i=levels-1; i>=0; i--) {
1032
            order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
1033
            if(order < 0) order = 0;
1034
            encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
1035
            bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1036
                                           res, n, order+1, sub->obits, precision);
1037
            if(bits[i] < bits[opt_index]) {
1038
                opt_index = i;
1039
                opt_order = order;
1040
            }
1041
        }
1042
        opt_order++;
1043
    } else if(omethod == ORDER_METHOD_SEARCH) {
1044
        // brute-force optimal order search
1045
        uint32_t bits[MAX_LPC_ORDER];
1046
        opt_order = 0;
1047
        bits[0] = UINT32_MAX;
1048
        for(i=min_order-1; i<max_order; i++) {
1049
            encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
1050
            bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1051
                                           res, n, i+1, sub->obits, precision);
1052
            if(bits[i] < bits[opt_order]) {
1053
                opt_order = i;
1054
            }
1055
        }
1056
        opt_order++;
1057
    } else if(omethod == ORDER_METHOD_LOG) {
1058
        uint32_t bits[MAX_LPC_ORDER];
1059
        int step;
1060

    
1061
        opt_order= min_order - 1 + (max_order-min_order)/3;
1062
        memset(bits, -1, sizeof(bits));
1063

    
1064
        for(step=16 ;step; step>>=1){
1065
            int last= opt_order;
1066
            for(i=last-step; i<=last+step; i+= step){
1067
                if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
1068
                    continue;
1069
                encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
1070
                bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1071
                                            res, n, i+1, sub->obits, precision);
1072
                if(bits[i] < bits[opt_order])
1073
                    opt_order= i;
1074
            }
1075
        }
1076
        opt_order++;
1077
    }
1078

    
1079
    sub->order = opt_order;
1080
    sub->type = FLAC_SUBFRAME_LPC;
1081
    sub->type_code = sub->type | (sub->order-1);
1082
    sub->shift = shift[sub->order-1];
1083
    for(i=0; i<sub->order; i++) {
1084
        sub->coefs[i] = coefs[sub->order-1][i];
1085
    }
1086
    encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
1087
    return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
1088
                                sub->obits, precision);
1089
}
1090

    
1091
static int encode_residual_v(FlacEncodeContext *ctx, int ch)
1092
{
1093
    int i, n;
1094
    FlacFrame *frame;
1095
    FlacSubframe *sub;
1096
    int32_t *res, *smp;
1097

    
1098
    frame = &ctx->frame;
1099
    sub = &frame->subframes[ch];
1100
    res = sub->residual;
1101
    smp = sub->samples;
1102
    n = frame->blocksize;
1103

    
1104
    /* CONSTANT */
1105
    for(i=1; i<n; i++) {
1106
        if(smp[i] != smp[0]) break;
1107
    }
1108
    if(i == n) {
1109
        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
1110
        res[0] = smp[0];
1111
        return sub->obits;
1112
    }
1113

    
1114
    /* VERBATIM */
1115
    sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
1116
    encode_residual_verbatim(res, smp, n);
1117
    return sub->obits * n;
1118
}
1119

    
1120
static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1121
{
1122
    int i, best;
1123
    int32_t lt, rt;
1124
    uint64_t sum[4];
1125
    uint64_t score[4];
1126
    int k;
1127

    
1128
    /* calculate sum of 2nd order residual for each channel */
1129
    sum[0] = sum[1] = sum[2] = sum[3] = 0;
1130
    for(i=2; i<n; i++) {
1131
        lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1132
        rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1133
        sum[2] += FFABS((lt + rt) >> 1);
1134
        sum[3] += FFABS(lt - rt);
1135
        sum[0] += FFABS(lt);
1136
        sum[1] += FFABS(rt);
1137
    }
1138
    /* estimate bit counts */
1139
    for(i=0; i<4; i++) {
1140
        k = find_optimal_param(2*sum[i], n);
1141
        sum[i] = rice_encode_count(2*sum[i], n, k);
1142
    }
1143

    
1144
    /* calculate score for each mode */
1145
    score[0] = sum[0] + sum[1];
1146
    score[1] = sum[0] + sum[3];
1147
    score[2] = sum[1] + sum[3];
1148
    score[3] = sum[2] + sum[3];
1149

    
1150
    /* return mode with lowest score */
1151
    best = 0;
1152
    for(i=1; i<4; i++) {
1153
        if(score[i] < score[best]) {
1154
            best = i;
1155
        }
1156
    }
1157
    if(best == 0) {
1158
        return FLAC_CHMODE_LEFT_RIGHT;
1159
    } else if(best == 1) {
1160
        return FLAC_CHMODE_LEFT_SIDE;
1161
    } else if(best == 2) {
1162
        return FLAC_CHMODE_RIGHT_SIDE;
1163
    } else {
1164
        return FLAC_CHMODE_MID_SIDE;
1165
    }
1166
}
1167

    
1168
/**
1169
 * Perform stereo channel decorrelation
1170
 */
1171
static void channel_decorrelation(FlacEncodeContext *ctx)
1172
{
1173
    FlacFrame *frame;
1174
    int32_t *left, *right;
1175
    int i, n;
1176

    
1177
    frame = &ctx->frame;
1178
    n = frame->blocksize;
1179
    left  = frame->subframes[0].samples;
1180
    right = frame->subframes[1].samples;
1181

    
1182
    if(ctx->channels != 2) {
1183
        frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1184
        return;
1185
    }
1186

    
1187
    frame->ch_mode = estimate_stereo_mode(left, right, n);
1188

    
1189
    /* perform decorrelation and adjust bits-per-sample */
1190
    if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1191
        return;
1192
    }
1193
    if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1194
        int32_t tmp;
1195
        for(i=0; i<n; i++) {
1196
            tmp = left[i];
1197
            left[i] = (tmp + right[i]) >> 1;
1198
            right[i] = tmp - right[i];
1199
        }
1200
        frame->subframes[1].obits++;
1201
    } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1202
        for(i=0; i<n; i++) {
1203
            right[i] = left[i] - right[i];
1204
        }
1205
        frame->subframes[1].obits++;
1206
    } else {
1207
        for(i=0; i<n; i++) {
1208
            left[i] -= right[i];
1209
        }
1210
        frame->subframes[0].obits++;
1211
    }
1212
}
1213

    
1214
static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1215
{
1216
    assert(bits >= 0 && bits <= 31);
1217

    
1218
    put_bits(pb, bits, val & ((1<<bits)-1));
1219
}
1220

    
1221
static void write_utf8(PutBitContext *pb, uint32_t val)
1222
{
1223
    uint8_t tmp;
1224
    PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1225
}
1226

    
1227
static void output_frame_header(FlacEncodeContext *s)
1228
{
1229
    FlacFrame *frame;
1230
    int crc;
1231

    
1232
    frame = &s->frame;
1233

    
1234
    put_bits(&s->pb, 16, 0xFFF8);
1235
    put_bits(&s->pb, 4, frame->bs_code[0]);
1236
    put_bits(&s->pb, 4, s->sr_code[0]);
1237
    if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1238
        put_bits(&s->pb, 4, s->ch_code);
1239
    } else {
1240
        put_bits(&s->pb, 4, frame->ch_mode);
1241
    }
1242
    put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1243
    put_bits(&s->pb, 1, 0);
1244
    write_utf8(&s->pb, s->frame_count);
1245
    if(frame->bs_code[0] == 6) {
1246
        put_bits(&s->pb, 8, frame->bs_code[1]);
1247
    } else if(frame->bs_code[0] == 7) {
1248
        put_bits(&s->pb, 16, frame->bs_code[1]);
1249
    }
1250
    if(s->sr_code[0] == 12) {
1251
        put_bits(&s->pb, 8, s->sr_code[1]);
1252
    } else if(s->sr_code[0] > 12) {
1253
        put_bits(&s->pb, 16, s->sr_code[1]);
1254
    }
1255
    flush_put_bits(&s->pb);
1256
    crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1257
    put_bits(&s->pb, 8, crc);
1258
}
1259

    
1260
static void output_subframe_constant(FlacEncodeContext *s, int ch)
1261
{
1262
    FlacSubframe *sub;
1263
    int32_t res;
1264

    
1265
    sub = &s->frame.subframes[ch];
1266
    res = sub->residual[0];
1267
    put_sbits(&s->pb, sub->obits, res);
1268
}
1269

    
1270
static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1271
{
1272
    int i;
1273
    FlacFrame *frame;
1274
    FlacSubframe *sub;
1275
    int32_t res;
1276

    
1277
    frame = &s->frame;
1278
    sub = &frame->subframes[ch];
1279

    
1280
    for(i=0; i<frame->blocksize; i++) {
1281
        res = sub->residual[i];
1282
        put_sbits(&s->pb, sub->obits, res);
1283
    }
1284
}
1285

    
1286
static void output_residual(FlacEncodeContext *ctx, int ch)
1287
{
1288
    int i, j, p, n, parts;
1289
    int k, porder, psize, res_cnt;
1290
    FlacFrame *frame;
1291
    FlacSubframe *sub;
1292
    int32_t *res;
1293

    
1294
    frame = &ctx->frame;
1295
    sub = &frame->subframes[ch];
1296
    res = sub->residual;
1297
    n = frame->blocksize;
1298

    
1299
    /* rice-encoded block */
1300
    put_bits(&ctx->pb, 2, 0);
1301

    
1302
    /* partition order */
1303
    porder = sub->rc.porder;
1304
    psize = n >> porder;
1305
    parts = (1 << porder);
1306
    put_bits(&ctx->pb, 4, porder);
1307
    res_cnt = psize - sub->order;
1308

    
1309
    /* residual */
1310
    j = sub->order;
1311
    for(p=0; p<parts; p++) {
1312
        k = sub->rc.params[p];
1313
        put_bits(&ctx->pb, 4, k);
1314
        if(p == 1) res_cnt = psize;
1315
        for(i=0; i<res_cnt && j<n; i++, j++) {
1316
            set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1317
        }
1318
    }
1319
}
1320

    
1321
static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1322
{
1323
    int i;
1324
    FlacFrame *frame;
1325
    FlacSubframe *sub;
1326

    
1327
    frame = &ctx->frame;
1328
    sub = &frame->subframes[ch];
1329

    
1330
    /* warm-up samples */
1331
    for(i=0; i<sub->order; i++) {
1332
        put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1333
    }
1334

    
1335
    /* residual */
1336
    output_residual(ctx, ch);
1337
}
1338

    
1339
static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1340
{
1341
    int i, cbits;
1342
    FlacFrame *frame;
1343
    FlacSubframe *sub;
1344

    
1345
    frame = &ctx->frame;
1346
    sub = &frame->subframes[ch];
1347

    
1348
    /* warm-up samples */
1349
    for(i=0; i<sub->order; i++) {
1350
        put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1351
    }
1352

    
1353
    /* LPC coefficients */
1354
    cbits = ctx->options.lpc_coeff_precision;
1355
    put_bits(&ctx->pb, 4, cbits-1);
1356
    put_sbits(&ctx->pb, 5, sub->shift);
1357
    for(i=0; i<sub->order; i++) {
1358
        put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1359
    }
1360

    
1361
    /* residual */
1362
    output_residual(ctx, ch);
1363
}
1364

    
1365
static void output_subframes(FlacEncodeContext *s)
1366
{
1367
    FlacFrame *frame;
1368
    FlacSubframe *sub;
1369
    int ch;
1370

    
1371
    frame = &s->frame;
1372

    
1373
    for(ch=0; ch<s->channels; ch++) {
1374
        sub = &frame->subframes[ch];
1375

    
1376
        /* subframe header */
1377
        put_bits(&s->pb, 1, 0);
1378
        put_bits(&s->pb, 6, sub->type_code);
1379
        put_bits(&s->pb, 1, 0); /* no wasted bits */
1380

    
1381
        /* subframe */
1382
        if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1383
            output_subframe_constant(s, ch);
1384
        } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1385
            output_subframe_verbatim(s, ch);
1386
        } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1387
            output_subframe_fixed(s, ch);
1388
        } else if(sub->type == FLAC_SUBFRAME_LPC) {
1389
            output_subframe_lpc(s, ch);
1390
        }
1391
    }
1392
}
1393

    
1394
static void output_frame_footer(FlacEncodeContext *s)
1395
{
1396
    int crc;
1397
    flush_put_bits(&s->pb);
1398
    crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1399
    put_bits(&s->pb, 16, crc);
1400
    flush_put_bits(&s->pb);
1401
}
1402

    
1403
static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1404
                             int buf_size, void *data)
1405
{
1406
    int ch;
1407
    FlacEncodeContext *s;
1408
    int16_t *samples = data;
1409
    int out_bytes;
1410

    
1411
    s = avctx->priv_data;
1412

    
1413
    s->blocksize = avctx->frame_size;
1414
    init_frame(s);
1415

    
1416
    copy_samples(s, samples);
1417

    
1418
    channel_decorrelation(s);
1419

    
1420
    for(ch=0; ch<s->channels; ch++) {
1421
        encode_residual(s, ch);
1422
    }
1423
    init_put_bits(&s->pb, frame, buf_size);
1424
    output_frame_header(s);
1425
    output_subframes(s);
1426
    output_frame_footer(s);
1427
    out_bytes = put_bits_count(&s->pb) >> 3;
1428

    
1429
    if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1430
        /* frame too large. use verbatim mode */
1431
        for(ch=0; ch<s->channels; ch++) {
1432
            encode_residual_v(s, ch);
1433
        }
1434
        init_put_bits(&s->pb, frame, buf_size);
1435
        output_frame_header(s);
1436
        output_subframes(s);
1437
        output_frame_footer(s);
1438
        out_bytes = put_bits_count(&s->pb) >> 3;
1439

    
1440
        if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1441
            /* still too large. must be an error. */
1442
            av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1443
            return -1;
1444
        }
1445
    }
1446

    
1447
    s->frame_count++;
1448
    return out_bytes;
1449
}
1450

    
1451
static int flac_encode_close(AVCodecContext *avctx)
1452
{
1453
    av_freep(&avctx->extradata);
1454
    avctx->extradata_size = 0;
1455
    av_freep(&avctx->coded_frame);
1456
    return 0;
1457
}
1458

    
1459
AVCodec flac_encoder = {
1460
    "flac",
1461
    CODEC_TYPE_AUDIO,
1462
    CODEC_ID_FLAC,
1463
    sizeof(FlacEncodeContext),
1464
    flac_encode_init,
1465
    flac_encode_frame,
1466
    flac_encode_close,
1467
    NULL,
1468
    .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
1469
};