Statistics
| Branch: | Revision:

ffmpeg / libavcodec / flacenc.c @ a403fc03

History | View | Annotate | Download (37 KB)

1
/**
2
 * FLAC audio encoder
3
 * Copyright (c) 2006  Justin Ruggles <jruggle@earthlink.net>
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
 */
19

    
20
#include "avcodec.h"
21
#include "bitstream.h"
22
#include "crc.h"
23
#include "golomb.h"
24

    
25
#define FLAC_MAX_CH  8
26
#define FLAC_MIN_BLOCKSIZE  16
27
#define FLAC_MAX_BLOCKSIZE  65535
28

    
29
#define FLAC_SUBFRAME_CONSTANT  0
30
#define FLAC_SUBFRAME_VERBATIM  1
31
#define FLAC_SUBFRAME_FIXED     8
32
#define FLAC_SUBFRAME_LPC      32
33

    
34
#define FLAC_CHMODE_NOT_STEREO      0
35
#define FLAC_CHMODE_LEFT_RIGHT      1
36
#define FLAC_CHMODE_LEFT_SIDE       8
37
#define FLAC_CHMODE_RIGHT_SIDE      9
38
#define FLAC_CHMODE_MID_SIDE       10
39

    
40
#define ORDER_METHOD_EST     0
41
#define ORDER_METHOD_2LEVEL  1
42
#define ORDER_METHOD_4LEVEL  2
43
#define ORDER_METHOD_8LEVEL  3
44
#define ORDER_METHOD_SEARCH  4
45

    
46
#define FLAC_STREAMINFO_SIZE  34
47

    
48
#define MIN_LPC_ORDER       1
49
#define MAX_LPC_ORDER      32
50
#define MAX_FIXED_ORDER     4
51
#define MAX_PARTITION_ORDER 8
52
#define MAX_PARTITIONS     (1 << MAX_PARTITION_ORDER)
53
#define MAX_LPC_PRECISION  15
54
#define MAX_LPC_SHIFT      15
55
#define MAX_RICE_PARAM     14
56

    
57
typedef struct CompressionOptions {
58
    int compression_level;
59
    int block_time_ms;
60
    int use_lpc;
61
    int lpc_coeff_precision;
62
    int min_prediction_order;
63
    int max_prediction_order;
64
    int prediction_order_method;
65
    int min_partition_order;
66
    int max_partition_order;
67
} CompressionOptions;
68

    
69
typedef struct RiceContext {
70
    int porder;
71
    int params[MAX_PARTITIONS];
72
} RiceContext;
73

    
74
typedef struct FlacSubframe {
75
    int type;
76
    int type_code;
77
    int obits;
78
    int order;
79
    int32_t coefs[MAX_LPC_ORDER];
80
    int shift;
81
    RiceContext rc;
82
    int32_t samples[FLAC_MAX_BLOCKSIZE];
83
    int32_t residual[FLAC_MAX_BLOCKSIZE];
84
} FlacSubframe;
85

    
86
typedef struct FlacFrame {
87
    FlacSubframe subframes[FLAC_MAX_CH];
88
    int blocksize;
89
    int bs_code[2];
90
    uint8_t crc8;
91
    int ch_mode;
92
} FlacFrame;
93

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

    
108
static const int flac_samplerates[16] = {
109
    0, 0, 0, 0,
110
    8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
111
    0, 0, 0, 0
112
};
113

    
114
static const int flac_blocksizes[16] = {
115
    0,
116
    192,
117
    576, 1152, 2304, 4608,
118
    0, 0,
119
    256, 512, 1024, 2048, 4096, 8192, 16384, 32768
120
};
121

    
122
/**
123
 * Writes streaminfo metadata block to byte array
124
 */
125
static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
126
{
127
    PutBitContext pb;
128

    
129
    memset(header, 0, FLAC_STREAMINFO_SIZE);
130
    init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
131

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

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

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

    
166
static int flac_encode_init(AVCodecContext *avctx)
167
{
168
    int freq = avctx->sample_rate;
169
    int channels = avctx->channels;
170
    FlacEncodeContext *s = avctx->priv_data;
171
    int i;
172
    uint8_t *streaminfo;
173

    
174
    s->avctx = avctx;
175

    
176
    if(avctx->sample_fmt != SAMPLE_FMT_S16) {
177
        return -1;
178
    }
179

    
180
    if(channels < 1 || channels > FLAC_MAX_CH) {
181
        return -1;
182
    }
183
    s->channels = channels;
184
    s->ch_code = s->channels-1;
185

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

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

    
222
    if(s->options.compression_level == 0) {
223
        s->options.block_time_ms = 27;
224
        s->options.use_lpc = 0;
225
        s->options.min_prediction_order = 2;
226
        s->options.max_prediction_order = 3;
227
        s->options.prediction_order_method = ORDER_METHOD_EST;
228
        s->options.min_partition_order = 2;
229
        s->options.max_partition_order = 2;
230
    } else if(s->options.compression_level == 1) {
231
        s->options.block_time_ms = 27;
232
        s->options.use_lpc = 0;
233
        s->options.min_prediction_order = 0;
234
        s->options.max_prediction_order = 4;
235
        s->options.prediction_order_method = ORDER_METHOD_EST;
236
        s->options.min_partition_order = 2;
237
        s->options.max_partition_order = 2;
238
    } else if(s->options.compression_level == 2) {
239
        s->options.block_time_ms = 27;
240
        s->options.use_lpc = 0;
241
        s->options.min_prediction_order = 0;
242
        s->options.max_prediction_order = 4;
243
        s->options.prediction_order_method = ORDER_METHOD_EST;
244
        s->options.min_partition_order = 0;
245
        s->options.max_partition_order = 3;
246
    } else if(s->options.compression_level == 3) {
247
        s->options.block_time_ms = 105;
248
        s->options.use_lpc = 1;
249
        s->options.min_prediction_order = 1;
250
        s->options.max_prediction_order = 6;
251
        s->options.prediction_order_method = ORDER_METHOD_EST;
252
        s->options.min_partition_order = 0;
253
        s->options.max_partition_order = 3;
254
    } else if(s->options.compression_level == 4) {
255
        s->options.block_time_ms = 105;
256
        s->options.use_lpc = 1;
257
        s->options.min_prediction_order = 1;
258
        s->options.max_prediction_order = 8;
259
        s->options.prediction_order_method = ORDER_METHOD_EST;
260
        s->options.min_partition_order = 0;
261
        s->options.max_partition_order = 3;
262
    } else if(s->options.compression_level == 5) {
263
        s->options.block_time_ms = 105;
264
        s->options.use_lpc = 1;
265
        s->options.min_prediction_order = 1;
266
        s->options.max_prediction_order = 8;
267
        s->options.prediction_order_method = ORDER_METHOD_EST;
268
        s->options.min_partition_order = 0;
269
        s->options.max_partition_order = 8;
270
    } else {
271
        av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
272
               s->options.compression_level);
273
        return -1;
274
    }
275

    
276
    /* set compression option overrides from AVCodecContext */
277
    if(avctx->use_lpc >= 0) {
278
        s->options.use_lpc = !!avctx->use_lpc;
279
    }
280
    av_log(avctx, AV_LOG_DEBUG, " use lpc: %s\n",
281
           s->options.use_lpc? "yes" : "no");
282

    
283
    if(avctx->min_prediction_order >= 0) {
284
        if(s->options.use_lpc) {
285
            if(avctx->min_prediction_order < MIN_LPC_ORDER ||
286
                    avctx->min_prediction_order > MAX_LPC_ORDER) {
287
                av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
288
                       avctx->min_prediction_order);
289
                return -1;
290
            }
291
        } else {
292
            if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
293
                av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
294
                       avctx->min_prediction_order);
295
                return -1;
296
            }
297
        }
298
        s->options.min_prediction_order = avctx->min_prediction_order;
299
    }
300
    if(avctx->max_prediction_order >= 0) {
301
        if(s->options.use_lpc) {
302
            if(avctx->max_prediction_order < MIN_LPC_ORDER ||
303
                    avctx->max_prediction_order > MAX_LPC_ORDER) {
304
                av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
305
                       avctx->max_prediction_order);
306
                return -1;
307
            }
308
        } else {
309
            if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
310
                av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
311
                       avctx->max_prediction_order);
312
                return -1;
313
            }
314
        }
315
        s->options.max_prediction_order = avctx->max_prediction_order;
316
    }
317
    if(s->options.max_prediction_order < s->options.min_prediction_order) {
318
        av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
319
               s->options.min_prediction_order, s->options.max_prediction_order);
320
        return -1;
321
    }
322
    av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
323
           s->options.min_prediction_order, s->options.max_prediction_order);
324

    
325
    if(avctx->prediction_order_method >= 0) {
326
        if(avctx->prediction_order_method > ORDER_METHOD_SEARCH) {
327
            av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
328
                   avctx->prediction_order_method);
329
            return -1;
330
        }
331
        s->options.prediction_order_method = avctx->prediction_order_method;
332
    }
333
    switch(avctx->prediction_order_method) {
334
        case ORDER_METHOD_EST:    av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
335
                                         "estimate"); break;
336
        case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
337
                                         "2-level"); break;
338
        case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
339
                                         "4-level"); break;
340
        case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
341
                                         "8-level"); break;
342
        case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
343
                                         "full search"); break;
344
    }
345

    
346
    if(avctx->min_partition_order >= 0) {
347
        if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
348
            av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
349
                   avctx->min_partition_order);
350
            return -1;
351
        }
352
        s->options.min_partition_order = avctx->min_partition_order;
353
    }
354
    if(avctx->max_partition_order >= 0) {
355
        if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
356
            av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
357
                   avctx->max_partition_order);
358
            return -1;
359
        }
360
        s->options.max_partition_order = avctx->max_partition_order;
361
    }
362
    if(s->options.max_partition_order < s->options.min_partition_order) {
363
        av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
364
               s->options.min_partition_order, s->options.max_partition_order);
365
        return -1;
366
    }
367
    av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
368
           s->options.min_partition_order, s->options.max_partition_order);
369

    
370
    if(avctx->frame_size > 0) {
371
        if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
372
                avctx->frame_size > FLAC_MIN_BLOCKSIZE) {
373
            av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
374
                   avctx->frame_size);
375
            return -1;
376
        }
377
        s->blocksize = avctx->frame_size;
378
    } else {
379
        s->blocksize = select_blocksize(s->samplerate, s->options.block_time_ms);
380
        avctx->frame_size = s->blocksize;
381
    }
382
    av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->blocksize);
383

    
384
    /* set LPC precision */
385
    if(avctx->lpc_coeff_precision > 0) {
386
        if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
387
            av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
388
                   avctx->lpc_coeff_precision);
389
            return -1;
390
        }
391
        s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
392
    } else {
393
        /* select LPC precision based on block size */
394
        if(     s->blocksize <=   192) s->options.lpc_coeff_precision =  7;
395
        else if(s->blocksize <=   384) s->options.lpc_coeff_precision =  8;
396
        else if(s->blocksize <=   576) s->options.lpc_coeff_precision =  9;
397
        else if(s->blocksize <=  1152) s->options.lpc_coeff_precision = 10;
398
        else if(s->blocksize <=  2304) s->options.lpc_coeff_precision = 11;
399
        else if(s->blocksize <=  4608) s->options.lpc_coeff_precision = 12;
400
        else if(s->blocksize <=  8192) s->options.lpc_coeff_precision = 13;
401
        else if(s->blocksize <= 16384) s->options.lpc_coeff_precision = 14;
402
        else                           s->options.lpc_coeff_precision = 15;
403
    }
404
    av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
405
           s->options.lpc_coeff_precision);
406

    
407
    /* set maximum encoded frame size in verbatim mode */
408
    if(s->channels == 2) {
409
        s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
410
    } else {
411
        s->max_framesize = 14 + (s->blocksize * s->channels * 2);
412
    }
413

    
414
    streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
415
    write_streaminfo(s, streaminfo);
416
    avctx->extradata = streaminfo;
417
    avctx->extradata_size = FLAC_STREAMINFO_SIZE;
418

    
419
    s->frame_count = 0;
420

    
421
    avctx->coded_frame = avcodec_alloc_frame();
422
    avctx->coded_frame->key_frame = 1;
423

    
424
    return 0;
425
}
426

    
427
static void init_frame(FlacEncodeContext *s)
428
{
429
    int i, ch;
430
    FlacFrame *frame;
431

    
432
    frame = &s->frame;
433

    
434
    for(i=0; i<16; i++) {
435
        if(s->blocksize == flac_blocksizes[i]) {
436
            frame->blocksize = flac_blocksizes[i];
437
            frame->bs_code[0] = i;
438
            frame->bs_code[1] = 0;
439
            break;
440
        }
441
    }
442
    if(i == 16) {
443
        frame->blocksize = s->blocksize;
444
        if(frame->blocksize <= 256) {
445
            frame->bs_code[0] = 6;
446
            frame->bs_code[1] = frame->blocksize-1;
447
        } else {
448
            frame->bs_code[0] = 7;
449
            frame->bs_code[1] = frame->blocksize-1;
450
        }
451
    }
452

    
453
    for(ch=0; ch<s->channels; ch++) {
454
        frame->subframes[ch].obits = 16;
455
    }
456
}
457

    
458
/**
459
 * Copy channel-interleaved input samples into separate subframes
460
 */
461
static void copy_samples(FlacEncodeContext *s, int16_t *samples)
462
{
463
    int i, j, ch;
464
    FlacFrame *frame;
465

    
466
    frame = &s->frame;
467
    for(i=0,j=0; i<frame->blocksize; i++) {
468
        for(ch=0; ch<s->channels; ch++,j++) {
469
            frame->subframes[ch].samples[i] = samples[j];
470
        }
471
    }
472
}
473

    
474

    
475
#define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
476

    
477
static int find_optimal_param(uint32_t sum, int n)
478
{
479
    int k, k_opt;
480
    uint32_t nbits[MAX_RICE_PARAM+1];
481

    
482
    k_opt = 0;
483
    nbits[0] = UINT32_MAX;
484
    for(k=0; k<=MAX_RICE_PARAM; k++) {
485
        nbits[k] = rice_encode_count(sum, n, k);
486
        if(nbits[k] < nbits[k_opt]) {
487
            k_opt = k;
488
        }
489
    }
490
    return k_opt;
491
}
492

    
493
static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
494
                                         uint32_t *sums, int n, int pred_order)
495
{
496
    int i;
497
    int k, cnt, part;
498
    uint32_t all_bits;
499

    
500
    part = (1 << porder);
501
    all_bits = 0;
502

    
503
    cnt = (n >> porder) - pred_order;
504
    for(i=0; i<part; i++) {
505
        if(i == 1) cnt = (n >> porder);
506
        k = find_optimal_param(sums[i], cnt);
507
        rc->params[i] = k;
508
        all_bits += rice_encode_count(sums[i], cnt, k);
509
    }
510
    all_bits += (4 * part);
511

    
512
    rc->porder = porder;
513

    
514
    return all_bits;
515
}
516

    
517
static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
518
                      uint32_t sums[][MAX_PARTITIONS])
519
{
520
    int i, j;
521
    int parts;
522
    uint32_t *res, *res_end;
523

    
524
    /* sums for highest level */
525
    parts = (1 << pmax);
526
    res = &data[pred_order];
527
    res_end = &data[n >> pmax];
528
    for(i=0; i<parts; i++) {
529
        sums[pmax][i] = 0;
530
        while(res < res_end){
531
            sums[pmax][i] += *(res++);
532
        }
533
        res_end+= n >> pmax;
534
    }
535
    /* sums for lower levels */
536
    for(i=pmax-1; i>=pmin; i--) {
537
        parts = (1 << i);
538
        for(j=0; j<parts; j++) {
539
            sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
540
        }
541
    }
542
}
543

    
544
static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
545
                                 int32_t *data, int n, int pred_order)
546
{
547
    int i;
548
    uint32_t bits[MAX_PARTITION_ORDER+1];
549
    int opt_porder;
550
    RiceContext tmp_rc;
551
    uint32_t *udata;
552
    uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
553

    
554
    assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
555
    assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
556
    assert(pmin <= pmax);
557

    
558
    udata = av_malloc(n * sizeof(uint32_t));
559
    for(i=0; i<n; i++) {
560
        udata[i] = (2*data[i]) ^ (data[i]>>31);
561
    }
562

    
563
    calc_sums(pmin, pmax, udata, n, pred_order, sums);
564

    
565
    opt_porder = pmin;
566
    bits[pmin] = UINT32_MAX;
567
    for(i=pmin; i<=pmax; i++) {
568
        bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
569
        if(bits[i] <= bits[opt_porder]) {
570
            opt_porder = i;
571
            memcpy(rc, &tmp_rc, sizeof(RiceContext));
572
        }
573
    }
574

    
575
    av_freep(&udata);
576
    return bits[opt_porder];
577
}
578

    
579
static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
580
                                       int32_t *data, int n, int pred_order,
581
                                       int bps)
582
{
583
    uint32_t bits;
584
    bits = pred_order*bps + 6;
585
    bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
586
    return bits;
587
}
588

    
589
static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
590
                                     int32_t *data, int n, int pred_order,
591
                                     int bps, int precision)
592
{
593
    uint32_t bits;
594
    bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
595
    bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
596
    return bits;
597
}
598

    
599
/**
600
 * Apply Welch window function to audio block
601
 */
602
static void apply_welch_window(const int32_t *data, int len, double *w_data)
603
{
604
    int i, n2;
605
    double w;
606
    double c;
607

    
608
    n2 = (len >> 1);
609
    c = 2.0 / (len - 1.0);
610
    for(i=0; i<n2; i++) {
611
        w = c - i - 1.0;
612
        w = 1.0 - (w * w);
613
        w_data[i] = data[i] * w;
614
        w_data[len-1-i] = data[len-1-i] * w;
615
    }
616
}
617

    
618
/**
619
 * Calculates autocorrelation data from audio samples
620
 * A Welch window function is applied before calculation.
621
 */
622
static void compute_autocorr(const int32_t *data, int len, int lag,
623
                             double *autoc)
624
{
625
    int i;
626
    double *data1;
627
    int lag_ptr, ptr;
628

    
629
    data1 = av_malloc(len * sizeof(double));
630
    apply_welch_window(data, len, data1);
631

    
632
    for(i=0; i<lag; i++) autoc[i] = 1.0;
633

    
634
    ptr = 0;
635
    while(ptr <= lag) {
636
        lag_ptr = 0;
637
        while(lag_ptr <= ptr) {
638
            autoc[ptr-lag_ptr] += data1[ptr] * data1[lag_ptr];
639
            lag_ptr++;
640
        }
641
        ptr++;
642
    }
643
    while(ptr < len) {
644
        lag_ptr = ptr - lag;
645
        while(lag_ptr <= ptr) {
646
            autoc[ptr-lag_ptr] += data1[ptr] * data1[lag_ptr];
647
            lag_ptr++;
648
        }
649
        ptr++;
650
    }
651

    
652
    av_freep(&data1);
653
}
654

    
655
/**
656
 * Levinson-Durbin recursion.
657
 * Produces LPC coefficients from autocorrelation data.
658
 */
659
static void compute_lpc_coefs(const double *autoc, int max_order,
660
                              double lpc[][MAX_LPC_ORDER], double *ref)
661
{
662
   int i, j, i2;
663
   double r, err, tmp;
664
   double lpc_tmp[MAX_LPC_ORDER];
665

    
666
   for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
667
   err = autoc[0];
668

    
669
   for(i=0; i<max_order; i++) {
670
      r = -autoc[i+1];
671
      for(j=0; j<i; j++) {
672
          r -= lpc_tmp[j] * autoc[i-j];
673
      }
674
      r /= err;
675
      ref[i] = fabs(r);
676

    
677
      err *= 1.0 - (r * r);
678

    
679
      i2 = (i >> 1);
680
      lpc_tmp[i] = r;
681
      for(j=0; j<i2; j++) {
682
         tmp = lpc_tmp[j];
683
         lpc_tmp[j] += r * lpc_tmp[i-1-j];
684
         lpc_tmp[i-1-j] += r * tmp;
685
      }
686
      if(i & 1) {
687
          lpc_tmp[j] += lpc_tmp[j] * r;
688
      }
689

    
690
      for(j=0; j<=i; j++) {
691
          lpc[i][j] = -lpc_tmp[j];
692
      }
693
   }
694
}
695

    
696
/**
697
 * Quantize LPC coefficients
698
 */
699
static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
700
                               int32_t *lpc_out, int *shift)
701
{
702
    int i;
703
    double d, cmax;
704
    int32_t qmax;
705
    int sh;
706

    
707
    /* define maximum levels */
708
    qmax = (1 << (precision - 1)) - 1;
709

    
710
    /* find maximum coefficient value */
711
    cmax = 0.0;
712
    for(i=0; i<order; i++) {
713
        d = lpc_in[i];
714
        if(d < 0) d = -d;
715
        if(d > cmax)
716
            cmax = d;
717
    }
718

    
719
    /* if maximum value quantizes to zero, return all zeros */
720
    if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
721
        *shift = 0;
722
        for(i=0; i<order; i++) {
723
            lpc_out[i] = 0;
724
        }
725
        return;
726
    }
727

    
728
    /* calculate level shift which scales max coeff to available bits */
729
    sh = MAX_LPC_SHIFT;
730
    while((cmax * (1 << sh) > qmax) && (sh > 0)) {
731
        sh--;
732
    }
733

    
734
    /* since negative shift values are unsupported in decoder, scale down
735
       coefficients instead */
736
    if(sh == 0 && cmax > qmax) {
737
        double scale = ((double)qmax) / cmax;
738
        for(i=0; i<order; i++) {
739
            lpc_in[i] *= scale;
740
        }
741
    }
742

    
743
    /* output quantized coefficients and level shift */
744
    for(i=0; i<order; i++) {
745
        lpc_out[i] = (int32_t)(lpc_in[i] * (1 << sh));
746
    }
747
    *shift = sh;
748
}
749

    
750
static int estimate_best_order(double *ref, int max_order)
751
{
752
    int i, est;
753

    
754
    est = 1;
755
    for(i=max_order-1; i>=0; i--) {
756
        if(ref[i] > 0.10) {
757
            est = i+1;
758
            break;
759
        }
760
    }
761
    return est;
762
}
763

    
764
/**
765
 * Calculate LPC coefficients for multiple orders
766
 */
767
static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
768
                          int precision, int32_t coefs[][MAX_LPC_ORDER],
769
                          int *shift)
770
{
771
    double autoc[MAX_LPC_ORDER+1];
772
    double ref[MAX_LPC_ORDER];
773
    double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
774
    int i;
775
    int opt_order;
776

    
777
    assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
778

    
779
    compute_autocorr(samples, blocksize, max_order+1, autoc);
780

    
781
    compute_lpc_coefs(autoc, max_order, lpc, ref);
782

    
783
    opt_order = estimate_best_order(ref, max_order);
784

    
785
    i = opt_order-1;
786
    quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
787

    
788
    return opt_order;
789
}
790

    
791

    
792
static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
793
{
794
    assert(n > 0);
795
    memcpy(res, smp, n * sizeof(int32_t));
796
}
797

    
798
static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
799
                                  int order)
800
{
801
    int i;
802

    
803
    for(i=0; i<order; i++) {
804
        res[i] = smp[i];
805
    }
806

    
807
    if(order==0){
808
        for(i=order; i<n; i++)
809
            res[i]= smp[i];
810
    }else if(order==1){
811
        for(i=order; i<n; i++)
812
            res[i]= smp[i] - smp[i-1];
813
    }else if(order==2){
814
        for(i=order; i<n; i++)
815
            res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
816
    }else if(order==3){
817
        for(i=order; i<n; i++)
818
            res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
819
    }else{
820
        for(i=order; i<n; i++)
821
            res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
822
    }
823
}
824

    
825
static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
826
                                int order, const int32_t *coefs, int shift)
827
{
828
    int i, j;
829
    int32_t pred;
830

    
831
    for(i=0; i<order; i++) {
832
        res[i] = smp[i];
833
    }
834
    for(i=order; i<n; i++) {
835
        pred = 0;
836
        for(j=0; j<order; j++) {
837
            pred += coefs[j] * smp[i-j-1];
838
        }
839
        res[i] = smp[i] - (pred >> shift);
840
    }
841
}
842

    
843
static int get_max_p_order(int max_porder, int n, int order)
844
{
845
    int porder, max_parts;
846

    
847
    porder = max_porder;
848
    while(porder > 0) {
849
        max_parts = (1 << porder);
850
        if(!(n % max_parts) && (n > max_parts*order)) {
851
            break;
852
        }
853
        porder--;
854
    }
855
    return porder;
856
}
857

    
858
static int encode_residual(FlacEncodeContext *ctx, int ch)
859
{
860
    int i, n;
861
    int min_order, max_order, opt_order, precision;
862
    int porder, min_porder, max_porder;
863
    FlacFrame *frame;
864
    FlacSubframe *sub;
865
    int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
866
    int shift[MAX_LPC_ORDER];
867
    int32_t *res, *smp;
868

    
869
    frame = &ctx->frame;
870
    sub = &frame->subframes[ch];
871
    res = sub->residual;
872
    smp = sub->samples;
873
    n = frame->blocksize;
874

    
875
    /* CONSTANT */
876
    for(i=1; i<n; i++) {
877
        if(smp[i] != smp[0]) break;
878
    }
879
    if(i == n) {
880
        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
881
        res[0] = smp[0];
882
        return sub->obits;
883
    }
884

    
885
    /* VERBATIM */
886
    if(n < 5) {
887
        sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
888
        encode_residual_verbatim(res, smp, n);
889
        return sub->obits * n;
890
    }
891

    
892
    min_order = ctx->options.min_prediction_order;
893
    max_order = ctx->options.max_prediction_order;
894
    min_porder = ctx->options.min_partition_order;
895
    max_porder = ctx->options.max_partition_order;
896
    precision = ctx->options.lpc_coeff_precision;
897

    
898
    /* FIXED */
899
    if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
900
        uint32_t bits[MAX_FIXED_ORDER+1];
901
        if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
902
        opt_order = 0;
903
        bits[0] = UINT32_MAX;
904
        for(i=min_order; i<=max_order; i++) {
905
            encode_residual_fixed(res, smp, n, i);
906
            porder = get_max_p_order(max_porder, n, i);
907
            bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, porder, res,
908
                                             n, i, sub->obits);
909
            if(bits[i] < bits[opt_order]) {
910
                opt_order = i;
911
            }
912
        }
913
        sub->order = opt_order;
914
        sub->type = FLAC_SUBFRAME_FIXED;
915
        sub->type_code = sub->type | sub->order;
916
        if(sub->order != max_order) {
917
            encode_residual_fixed(res, smp, n, sub->order);
918
            porder = get_max_p_order(max_porder, n, sub->order);
919
            return calc_rice_params_fixed(&sub->rc, min_porder, porder, res, n,
920
                                          sub->order, sub->obits);
921
        }
922
        return bits[sub->order];
923
    }
924

    
925
    /* LPC */
926
    sub->order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift);
927
    sub->type = FLAC_SUBFRAME_LPC;
928
    sub->type_code = sub->type | (sub->order-1);
929
    sub->shift = shift[sub->order-1];
930
    for(i=0; i<sub->order; i++) {
931
        sub->coefs[i] = coefs[sub->order-1][i];
932
    }
933
    porder = get_max_p_order(max_porder, n, sub->order);
934
    encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
935
    return calc_rice_params_lpc(&sub->rc, 0, porder, res, n, sub->order,
936
                                sub->obits, precision);
937
}
938

    
939
static int encode_residual_v(FlacEncodeContext *ctx, int ch)
940
{
941
    int i, n;
942
    FlacFrame *frame;
943
    FlacSubframe *sub;
944
    int32_t *res, *smp;
945

    
946
    frame = &ctx->frame;
947
    sub = &frame->subframes[ch];
948
    res = sub->residual;
949
    smp = sub->samples;
950
    n = frame->blocksize;
951

    
952
    /* CONSTANT */
953
    for(i=1; i<n; i++) {
954
        if(smp[i] != smp[0]) break;
955
    }
956
    if(i == n) {
957
        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
958
        res[0] = smp[0];
959
        return sub->obits;
960
    }
961

    
962
    /* VERBATIM */
963
    sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
964
    encode_residual_verbatim(res, smp, n);
965
    return sub->obits * n;
966
}
967

    
968
static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
969
{
970
    int i, best;
971
    int32_t lt, rt;
972
    uint64_t sum[4];
973
    uint64_t score[4];
974
    int k;
975

    
976
    /* calculate sum of 2nd order residual for each channel */
977
    sum[0] = sum[1] = sum[2] = sum[3] = 0;
978
    for(i=2; i<n; i++) {
979
        lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
980
        rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
981
        sum[2] += ABS((lt + rt) >> 1);
982
        sum[3] += ABS(lt - rt);
983
        sum[0] += ABS(lt);
984
        sum[1] += ABS(rt);
985
    }
986
    /* estimate bit counts */
987
    for(i=0; i<4; i++) {
988
        k = find_optimal_param(2*sum[i], n);
989
        sum[i] = rice_encode_count(2*sum[i], n, k);
990
    }
991

    
992
    /* calculate score for each mode */
993
    score[0] = sum[0] + sum[1];
994
    score[1] = sum[0] + sum[3];
995
    score[2] = sum[1] + sum[3];
996
    score[3] = sum[2] + sum[3];
997

    
998
    /* return mode with lowest score */
999
    best = 0;
1000
    for(i=1; i<4; i++) {
1001
        if(score[i] < score[best]) {
1002
            best = i;
1003
        }
1004
    }
1005
    if(best == 0) {
1006
        return FLAC_CHMODE_LEFT_RIGHT;
1007
    } else if(best == 1) {
1008
        return FLAC_CHMODE_LEFT_SIDE;
1009
    } else if(best == 2) {
1010
        return FLAC_CHMODE_RIGHT_SIDE;
1011
    } else {
1012
        return FLAC_CHMODE_MID_SIDE;
1013
    }
1014
}
1015

    
1016
/**
1017
 * Perform stereo channel decorrelation
1018
 */
1019
static void channel_decorrelation(FlacEncodeContext *ctx)
1020
{
1021
    FlacFrame *frame;
1022
    int32_t *left, *right;
1023
    int i, n;
1024

    
1025
    frame = &ctx->frame;
1026
    n = frame->blocksize;
1027
    left  = frame->subframes[0].samples;
1028
    right = frame->subframes[1].samples;
1029

    
1030
    if(ctx->channels != 2) {
1031
        frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1032
        return;
1033
    }
1034

    
1035
    frame->ch_mode = estimate_stereo_mode(left, right, n);
1036

    
1037
    /* perform decorrelation and adjust bits-per-sample */
1038
    if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1039
        return;
1040
    }
1041
    if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1042
        int32_t tmp;
1043
        for(i=0; i<n; i++) {
1044
            tmp = left[i];
1045
            left[i] = (tmp + right[i]) >> 1;
1046
            right[i] = tmp - right[i];
1047
        }
1048
        frame->subframes[1].obits++;
1049
    } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1050
        for(i=0; i<n; i++) {
1051
            right[i] = left[i] - right[i];
1052
        }
1053
        frame->subframes[1].obits++;
1054
    } else {
1055
        for(i=0; i<n; i++) {
1056
            left[i] -= right[i];
1057
        }
1058
        frame->subframes[0].obits++;
1059
    }
1060
}
1061

    
1062
static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1063
{
1064
    assert(bits >= 0 && bits <= 31);
1065

    
1066
    put_bits(pb, bits, val & ((1<<bits)-1));
1067
}
1068

    
1069
static void write_utf8(PutBitContext *pb, uint32_t val)
1070
{
1071
    int bytes, shift;
1072

    
1073
    if(val < 0x80){
1074
        put_bits(pb, 8, val);
1075
        return;
1076
    }
1077

    
1078
    bytes= (av_log2(val)+4) / 5;
1079
    shift = (bytes - 1) * 6;
1080
    put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
1081
    while(shift >= 6){
1082
        shift -= 6;
1083
        put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
1084
    }
1085
}
1086

    
1087
static void output_frame_header(FlacEncodeContext *s)
1088
{
1089
    FlacFrame *frame;
1090
    int crc;
1091

    
1092
    frame = &s->frame;
1093

    
1094
    put_bits(&s->pb, 16, 0xFFF8);
1095
    put_bits(&s->pb, 4, frame->bs_code[0]);
1096
    put_bits(&s->pb, 4, s->sr_code[0]);
1097
    if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1098
        put_bits(&s->pb, 4, s->ch_code);
1099
    } else {
1100
        put_bits(&s->pb, 4, frame->ch_mode);
1101
    }
1102
    put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1103
    put_bits(&s->pb, 1, 0);
1104
    write_utf8(&s->pb, s->frame_count);
1105
    if(frame->bs_code[0] == 6) {
1106
        put_bits(&s->pb, 8, frame->bs_code[1]);
1107
    } else if(frame->bs_code[0] == 7) {
1108
        put_bits(&s->pb, 16, frame->bs_code[1]);
1109
    }
1110
    if(s->sr_code[0] == 12) {
1111
        put_bits(&s->pb, 8, s->sr_code[1]);
1112
    } else if(s->sr_code[0] > 12) {
1113
        put_bits(&s->pb, 16, s->sr_code[1]);
1114
    }
1115
    flush_put_bits(&s->pb);
1116
    crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1117
    put_bits(&s->pb, 8, crc);
1118
}
1119

    
1120
static void output_subframe_constant(FlacEncodeContext *s, int ch)
1121
{
1122
    FlacSubframe *sub;
1123
    int32_t res;
1124

    
1125
    sub = &s->frame.subframes[ch];
1126
    res = sub->residual[0];
1127
    put_sbits(&s->pb, sub->obits, res);
1128
}
1129

    
1130
static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1131
{
1132
    int i;
1133
    FlacFrame *frame;
1134
    FlacSubframe *sub;
1135
    int32_t res;
1136

    
1137
    frame = &s->frame;
1138
    sub = &frame->subframes[ch];
1139

    
1140
    for(i=0; i<frame->blocksize; i++) {
1141
        res = sub->residual[i];
1142
        put_sbits(&s->pb, sub->obits, res);
1143
    }
1144
}
1145

    
1146
static void output_residual(FlacEncodeContext *ctx, int ch)
1147
{
1148
    int i, j, p, n, parts;
1149
    int k, porder, psize, res_cnt;
1150
    FlacFrame *frame;
1151
    FlacSubframe *sub;
1152
    int32_t *res;
1153

    
1154
    frame = &ctx->frame;
1155
    sub = &frame->subframes[ch];
1156
    res = sub->residual;
1157
    n = frame->blocksize;
1158

    
1159
    /* rice-encoded block */
1160
    put_bits(&ctx->pb, 2, 0);
1161

    
1162
    /* partition order */
1163
    porder = sub->rc.porder;
1164
    psize = n >> porder;
1165
    parts = (1 << porder);
1166
    put_bits(&ctx->pb, 4, porder);
1167
    res_cnt = psize - sub->order;
1168

    
1169
    /* residual */
1170
    j = sub->order;
1171
    for(p=0; p<parts; p++) {
1172
        k = sub->rc.params[p];
1173
        put_bits(&ctx->pb, 4, k);
1174
        if(p == 1) res_cnt = psize;
1175
        for(i=0; i<res_cnt && j<n; i++, j++) {
1176
            set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1177
        }
1178
    }
1179
}
1180

    
1181
static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1182
{
1183
    int i;
1184
    FlacFrame *frame;
1185
    FlacSubframe *sub;
1186

    
1187
    frame = &ctx->frame;
1188
    sub = &frame->subframes[ch];
1189

    
1190
    /* warm-up samples */
1191
    for(i=0; i<sub->order; i++) {
1192
        put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1193
    }
1194

    
1195
    /* residual */
1196
    output_residual(ctx, ch);
1197
}
1198

    
1199
static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1200
{
1201
    int i, cbits;
1202
    FlacFrame *frame;
1203
    FlacSubframe *sub;
1204

    
1205
    frame = &ctx->frame;
1206
    sub = &frame->subframes[ch];
1207

    
1208
    /* warm-up samples */
1209
    for(i=0; i<sub->order; i++) {
1210
        put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1211
    }
1212

    
1213
    /* LPC coefficients */
1214
    cbits = ctx->options.lpc_coeff_precision;
1215
    put_bits(&ctx->pb, 4, cbits-1);
1216
    put_sbits(&ctx->pb, 5, sub->shift);
1217
    for(i=0; i<sub->order; i++) {
1218
        put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1219
    }
1220

    
1221
    /* residual */
1222
    output_residual(ctx, ch);
1223
}
1224

    
1225
static void output_subframes(FlacEncodeContext *s)
1226
{
1227
    FlacFrame *frame;
1228
    FlacSubframe *sub;
1229
    int ch;
1230

    
1231
    frame = &s->frame;
1232

    
1233
    for(ch=0; ch<s->channels; ch++) {
1234
        sub = &frame->subframes[ch];
1235

    
1236
        /* subframe header */
1237
        put_bits(&s->pb, 1, 0);
1238
        put_bits(&s->pb, 6, sub->type_code);
1239
        put_bits(&s->pb, 1, 0); /* no wasted bits */
1240

    
1241
        /* subframe */
1242
        if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1243
            output_subframe_constant(s, ch);
1244
        } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1245
            output_subframe_verbatim(s, ch);
1246
        } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1247
            output_subframe_fixed(s, ch);
1248
        } else if(sub->type == FLAC_SUBFRAME_LPC) {
1249
            output_subframe_lpc(s, ch);
1250
        }
1251
    }
1252
}
1253

    
1254
static void output_frame_footer(FlacEncodeContext *s)
1255
{
1256
    int crc;
1257
    flush_put_bits(&s->pb);
1258
    crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1259
    put_bits(&s->pb, 16, crc);
1260
    flush_put_bits(&s->pb);
1261
}
1262

    
1263
static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1264
                             int buf_size, void *data)
1265
{
1266
    int ch;
1267
    FlacEncodeContext *s;
1268
    int16_t *samples = data;
1269
    int out_bytes;
1270

    
1271
    s = avctx->priv_data;
1272

    
1273
    s->blocksize = avctx->frame_size;
1274
    init_frame(s);
1275

    
1276
    copy_samples(s, samples);
1277

    
1278
    channel_decorrelation(s);
1279

    
1280
    for(ch=0; ch<s->channels; ch++) {
1281
        encode_residual(s, ch);
1282
    }
1283
    init_put_bits(&s->pb, frame, buf_size);
1284
    output_frame_header(s);
1285
    output_subframes(s);
1286
    output_frame_footer(s);
1287
    out_bytes = put_bits_count(&s->pb) >> 3;
1288

    
1289
    if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1290
        /* frame too large. use verbatim mode */
1291
        for(ch=0; ch<s->channels; ch++) {
1292
            encode_residual_v(s, ch);
1293
        }
1294
        init_put_bits(&s->pb, frame, buf_size);
1295
        output_frame_header(s);
1296
        output_subframes(s);
1297
        output_frame_footer(s);
1298
        out_bytes = put_bits_count(&s->pb) >> 3;
1299

    
1300
        if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1301
            /* still too large. must be an error. */
1302
            av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1303
            return -1;
1304
        }
1305
    }
1306

    
1307
    s->frame_count++;
1308
    return out_bytes;
1309
}
1310

    
1311
static int flac_encode_close(AVCodecContext *avctx)
1312
{
1313
    av_freep(&avctx->extradata);
1314
    avctx->extradata_size = 0;
1315
    av_freep(&avctx->coded_frame);
1316
    return 0;
1317
}
1318

    
1319
AVCodec flac_encoder = {
1320
    "flac",
1321
    CODEC_TYPE_AUDIO,
1322
    CODEC_ID_FLAC,
1323
    sizeof(FlacEncodeContext),
1324
    flac_encode_init,
1325
    flac_encode_frame,
1326
    flac_encode_close,
1327
    NULL,
1328
    .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
1329
};