Statistics
| Branch: | Revision:

ffmpeg / libavcodec / flacenc.c @ 0d8837bd

History | View | Annotate | Download (40.2 KB)

1
/**
2
 * FLAC audio encoder
3
 * Copyright (c) 2006  Justin Ruggles <justin.ruggles@gmail.com>
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 "libavutil/crc.h"
23
#include "libavutil/md5.h"
24
#include "avcodec.h"
25
#include "get_bits.h"
26
#include "golomb.h"
27
#include "lpc.h"
28
#include "flac.h"
29
#include "flacdata.h"
30

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

    
36
#define MAX_FIXED_ORDER     4
37
#define MAX_PARTITION_ORDER 8
38
#define MAX_PARTITIONS     (1 << MAX_PARTITION_ORDER)
39
#define MAX_LPC_PRECISION  15
40
#define MAX_LPC_SHIFT      15
41
#define MAX_RICE_PARAM     14
42

    
43
typedef struct CompressionOptions {
44
    int compression_level;
45
    int block_time_ms;
46
    enum AVLPCType lpc_type;
47
    int lpc_passes;
48
    int lpc_coeff_precision;
49
    int min_prediction_order;
50
    int max_prediction_order;
51
    int prediction_order_method;
52
    int min_partition_order;
53
    int max_partition_order;
54
} CompressionOptions;
55

    
56
typedef struct RiceContext {
57
    int porder;
58
    int params[MAX_PARTITIONS];
59
} RiceContext;
60

    
61
typedef struct FlacSubframe {
62
    int type;
63
    int type_code;
64
    int obits;
65
    int order;
66
    int32_t coefs[MAX_LPC_ORDER];
67
    int shift;
68
    RiceContext rc;
69
    int32_t samples[FLAC_MAX_BLOCKSIZE];
70
    int32_t residual[FLAC_MAX_BLOCKSIZE+1];
71
} FlacSubframe;
72

    
73
typedef struct FlacFrame {
74
    FlacSubframe subframes[FLAC_MAX_CHANNELS];
75
    int blocksize;
76
    int bs_code[2];
77
    uint8_t crc8;
78
    int ch_mode;
79
    int verbatim_only;
80
} FlacFrame;
81

    
82
typedef struct FlacEncodeContext {
83
    PutBitContext pb;
84
    int channels;
85
    int samplerate;
86
    int sr_code[2];
87
    int max_blocksize;
88
    int min_framesize;
89
    int max_framesize;
90
    int max_encoded_framesize;
91
    uint32_t frame_count;
92
    uint64_t sample_count;
93
    uint8_t md5sum[16];
94
    FlacFrame frame;
95
    CompressionOptions options;
96
    AVCodecContext *avctx;
97
    LPCContext lpc_ctx;
98
    struct AVMD5 *md5ctx;
99
} FlacEncodeContext;
100

    
101

    
102
/**
103
 * Write streaminfo metadata block to byte array.
104
 */
105
static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
106
{
107
    PutBitContext pb;
108

    
109
    memset(header, 0, FLAC_STREAMINFO_SIZE);
110
    init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
111

    
112
    /* streaminfo metadata block */
113
    put_bits(&pb, 16, s->max_blocksize);
114
    put_bits(&pb, 16, s->max_blocksize);
115
    put_bits(&pb, 24, s->min_framesize);
116
    put_bits(&pb, 24, s->max_framesize);
117
    put_bits(&pb, 20, s->samplerate);
118
    put_bits(&pb, 3, s->channels-1);
119
    put_bits(&pb, 5, 15);       /* bits per sample - 1 */
120
    /* write 36-bit sample count in 2 put_bits() calls */
121
    put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
122
    put_bits(&pb, 12,  s->sample_count & 0x000000FFFLL);
123
    flush_put_bits(&pb);
124
    memcpy(&header[18], s->md5sum, 16);
125
}
126

    
127

    
128
/**
129
 * Set blocksize based on samplerate.
130
 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
131
 */
132
static int select_blocksize(int samplerate, int block_time_ms)
133
{
134
    int i;
135
    int target;
136
    int blocksize;
137

    
138
    assert(samplerate > 0);
139
    blocksize = ff_flac_blocksize_table[1];
140
    target    = (samplerate * block_time_ms) / 1000;
141
    for (i = 0; i < 16; i++) {
142
        if (target >= ff_flac_blocksize_table[i] &&
143
            ff_flac_blocksize_table[i] > blocksize) {
144
            blocksize = ff_flac_blocksize_table[i];
145
        }
146
    }
147
    return blocksize;
148
}
149

    
150

    
151
static av_cold void dprint_compression_options(FlacEncodeContext *s)
152
{
153
    AVCodecContext     *avctx = s->avctx;
154
    CompressionOptions *opt   = &s->options;
155

    
156
    av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
157

    
158
    switch (opt->lpc_type) {
159
    case AV_LPC_TYPE_NONE:
160
        av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
161
        break;
162
    case AV_LPC_TYPE_FIXED:
163
        av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
164
        break;
165
    case AV_LPC_TYPE_LEVINSON:
166
        av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
167
        break;
168
    case AV_LPC_TYPE_CHOLESKY:
169
        av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
170
               opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
171
        break;
172
    }
173

    
174
    av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
175
           opt->min_prediction_order, opt->max_prediction_order);
176

    
177
    switch (opt->prediction_order_method) {
178
    case ORDER_METHOD_EST:
179
        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
180
        break;
181
    case ORDER_METHOD_2LEVEL:
182
        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
183
        break;
184
    case ORDER_METHOD_4LEVEL:
185
        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
186
        break;
187
    case ORDER_METHOD_8LEVEL:
188
        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
189
        break;
190
    case ORDER_METHOD_SEARCH:
191
        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
192
        break;
193
    case ORDER_METHOD_LOG:
194
        av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
195
        break;
196
    }
197

    
198

    
199
    av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
200
           opt->min_partition_order, opt->max_partition_order);
201

    
202
    av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
203

    
204
    av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
205
           opt->lpc_coeff_precision);
206
}
207

    
208

    
209
static av_cold int flac_encode_init(AVCodecContext *avctx)
210
{
211
    int freq = avctx->sample_rate;
212
    int channels = avctx->channels;
213
    FlacEncodeContext *s = avctx->priv_data;
214
    int i, level;
215
    uint8_t *streaminfo;
216

    
217
    s->avctx = avctx;
218

    
219
    ff_lpc_init(&s->lpc_ctx);
220

    
221
    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
222
        return -1;
223

    
224
    if (channels < 1 || channels > FLAC_MAX_CHANNELS)
225
        return -1;
226
    s->channels = channels;
227

    
228
    /* find samplerate in table */
229
    if (freq < 1)
230
        return -1;
231
    for (i = 4; i < 12; i++) {
232
        if (freq == ff_flac_sample_rate_table[i]) {
233
            s->samplerate = ff_flac_sample_rate_table[i];
234
            s->sr_code[0] = i;
235
            s->sr_code[1] = 0;
236
            break;
237
        }
238
    }
239
    /* if not in table, samplerate is non-standard */
240
    if (i == 12) {
241
        if (freq % 1000 == 0 && freq < 255000) {
242
            s->sr_code[0] = 12;
243
            s->sr_code[1] = freq / 1000;
244
        } else if (freq % 10 == 0 && freq < 655350) {
245
            s->sr_code[0] = 14;
246
            s->sr_code[1] = freq / 10;
247
        } else if (freq < 65535) {
248
            s->sr_code[0] = 13;
249
            s->sr_code[1] = freq;
250
        } else {
251
            return -1;
252
        }
253
        s->samplerate = freq;
254
    }
255

    
256
    /* set compression option defaults based on avctx->compression_level */
257
    if (avctx->compression_level < 0)
258
        s->options.compression_level = 5;
259
    else
260
        s->options.compression_level = avctx->compression_level;
261

    
262
    level = s->options.compression_level;
263
    if (level > 12) {
264
        av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
265
               s->options.compression_level);
266
        return -1;
267
    }
268

    
269
    s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
270

    
271
    s->options.lpc_type      = ((int[]){ AV_LPC_TYPE_FIXED,    AV_LPC_TYPE_FIXED,    AV_LPC_TYPE_FIXED,
272
                                         AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
273
                                         AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
274
                                         AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
275
                                         AV_LPC_TYPE_LEVINSON})[level];
276

    
277
    s->options.min_prediction_order = ((int[]){  2,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
278
    s->options.max_prediction_order = ((int[]){  3,  4,  4,  6,  8,  8,  8,  8, 12, 12, 12, 32, 32})[level];
279

    
280
    s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
281
                                                   ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
282
                                                   ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG,    ORDER_METHOD_4LEVEL,
283
                                                   ORDER_METHOD_LOG,    ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
284
                                                   ORDER_METHOD_SEARCH})[level];
285

    
286
    s->options.min_partition_order = ((int[]){  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0})[level];
287
    s->options.max_partition_order = ((int[]){  2,  2,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,  8})[level];
288

    
289
    /* set compression option overrides from AVCodecContext */
290
#if FF_API_USE_LPC
291
    /* for compatibility with deprecated AVCodecContext.use_lpc */
292
    if (avctx->use_lpc == 0) {
293
        s->options.lpc_type = AV_LPC_TYPE_FIXED;
294
    } else if (avctx->use_lpc == 1) {
295
        s->options.lpc_type = AV_LPC_TYPE_LEVINSON;
296
    } else if (avctx->use_lpc > 1) {
297
        s->options.lpc_type   = AV_LPC_TYPE_CHOLESKY;
298
        s->options.lpc_passes = avctx->use_lpc - 1;
299
    }
300
#endif
301
    if (avctx->lpc_type > AV_LPC_TYPE_DEFAULT) {
302
        if (avctx->lpc_type > AV_LPC_TYPE_CHOLESKY) {
303
            av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
304
            return -1;
305
        }
306
        s->options.lpc_type = avctx->lpc_type;
307
        if (s->options.lpc_type == AV_LPC_TYPE_CHOLESKY) {
308
            if (avctx->lpc_passes < 0) {
309
                // default number of passes for Cholesky
310
                s->options.lpc_passes = 2;
311
            } else if (avctx->lpc_passes == 0) {
312
                av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
313
                       avctx->lpc_passes);
314
                return -1;
315
            } else {
316
                s->options.lpc_passes = avctx->lpc_passes;
317
            }
318
        }
319
    }
320

    
321
    if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
322
        s->options.min_prediction_order = 0;
323
    } else if (avctx->min_prediction_order >= 0) {
324
        if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
325
            if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
326
                av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
327
                       avctx->min_prediction_order);
328
                return -1;
329
            }
330
        } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
331
                   avctx->min_prediction_order > MAX_LPC_ORDER) {
332
            av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
333
                   avctx->min_prediction_order);
334
            return -1;
335
        }
336
        s->options.min_prediction_order = avctx->min_prediction_order;
337
    }
338
    if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
339
        s->options.max_prediction_order = 0;
340
    } else if (avctx->max_prediction_order >= 0) {
341
        if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
342
            if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
343
                av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
344
                       avctx->max_prediction_order);
345
                return -1;
346
            }
347
        } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
348
                   avctx->max_prediction_order > MAX_LPC_ORDER) {
349
            av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
350
                   avctx->max_prediction_order);
351
            return -1;
352
        }
353
        s->options.max_prediction_order = avctx->max_prediction_order;
354
    }
355
    if (s->options.max_prediction_order < s->options.min_prediction_order) {
356
        av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
357
               s->options.min_prediction_order, s->options.max_prediction_order);
358
        return -1;
359
    }
360

    
361
    if (avctx->prediction_order_method >= 0) {
362
        if (avctx->prediction_order_method > ORDER_METHOD_LOG) {
363
            av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
364
                   avctx->prediction_order_method);
365
            return -1;
366
        }
367
        s->options.prediction_order_method = avctx->prediction_order_method;
368
    }
369

    
370
    if (avctx->min_partition_order >= 0) {
371
        if (avctx->min_partition_order > MAX_PARTITION_ORDER) {
372
            av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
373
                   avctx->min_partition_order);
374
            return -1;
375
        }
376
        s->options.min_partition_order = avctx->min_partition_order;
377
    }
378
    if (avctx->max_partition_order >= 0) {
379
        if (avctx->max_partition_order > MAX_PARTITION_ORDER) {
380
            av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
381
                   avctx->max_partition_order);
382
            return -1;
383
        }
384
        s->options.max_partition_order = avctx->max_partition_order;
385
    }
386
    if (s->options.max_partition_order < s->options.min_partition_order) {
387
        av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
388
               s->options.min_partition_order, s->options.max_partition_order);
389
        return -1;
390
    }
391

    
392
    if (avctx->frame_size > 0) {
393
        if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
394
                avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
395
            av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
396
                   avctx->frame_size);
397
            return -1;
398
        }
399
    } else {
400
        s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
401
    }
402
    s->max_blocksize = s->avctx->frame_size;
403

    
404
    /* set LPC precision */
405
    if (avctx->lpc_coeff_precision > 0) {
406
        if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
407
            av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
408
                   avctx->lpc_coeff_precision);
409
            return -1;
410
        }
411
        s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
412
    } else {
413
        /* default LPC precision */
414
        s->options.lpc_coeff_precision = 15;
415
    }
416

    
417
    /* set maximum encoded frame size in verbatim mode */
418
    s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
419
                                                  s->channels, 16);
420

    
421
    /* initialize MD5 context */
422
    s->md5ctx = av_malloc(av_md5_size);
423
    if (!s->md5ctx)
424
        return AVERROR(ENOMEM);
425
    av_md5_init(s->md5ctx);
426

    
427
    streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
428
    if (!streaminfo)
429
        return AVERROR(ENOMEM);
430
    write_streaminfo(s, streaminfo);
431
    avctx->extradata = streaminfo;
432
    avctx->extradata_size = FLAC_STREAMINFO_SIZE;
433

    
434
    s->frame_count   = 0;
435
    s->min_framesize = s->max_framesize;
436

    
437
    avctx->coded_frame = avcodec_alloc_frame();
438
    if (!avctx->coded_frame)
439
        return AVERROR(ENOMEM);
440

    
441
    dprint_compression_options(s);
442

    
443
    return 0;
444
}
445

    
446

    
447
static void init_frame(FlacEncodeContext *s)
448
{
449
    int i, ch;
450
    FlacFrame *frame;
451

    
452
    frame = &s->frame;
453

    
454
    for (i = 0; i < 16; i++) {
455
        if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
456
            frame->blocksize  = ff_flac_blocksize_table[i];
457
            frame->bs_code[0] = i;
458
            frame->bs_code[1] = 0;
459
            break;
460
        }
461
    }
462
    if (i == 16) {
463
        frame->blocksize = s->avctx->frame_size;
464
        if (frame->blocksize <= 256) {
465
            frame->bs_code[0] = 6;
466
            frame->bs_code[1] = frame->blocksize-1;
467
        } else {
468
            frame->bs_code[0] = 7;
469
            frame->bs_code[1] = frame->blocksize-1;
470
        }
471
    }
472

    
473
    for (ch = 0; ch < s->channels; ch++)
474
        frame->subframes[ch].obits = 16;
475

    
476
    frame->verbatim_only = 0;
477
}
478

    
479

    
480
/**
481
 * Copy channel-interleaved input samples into separate subframes.
482
 */
483
static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
484
{
485
    int i, j, ch;
486
    FlacFrame *frame;
487

    
488
    frame = &s->frame;
489
    for (i = 0, j = 0; i < frame->blocksize; i++)
490
        for (ch = 0; ch < s->channels; ch++, j++)
491
            frame->subframes[ch].samples[i] = samples[j];
492
}
493

    
494

    
495
static int rice_count_exact(int32_t *res, int n, int k)
496
{
497
    int i;
498
    int count = 0;
499

    
500
    for (i = 0; i < n; i++) {
501
        int32_t v = -2 * res[i] - 1;
502
        v ^= v >> 31;
503
        count += (v >> k) + 1 + k;
504
    }
505
    return count;
506
}
507

    
508

    
509
static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
510
                                int pred_order)
511
{
512
    int p, porder, psize;
513
    int i, part_end;
514
    int count = 0;
515

    
516
    /* subframe header */
517
    count += 8;
518

    
519
    /* subframe */
520
    if (sub->type == FLAC_SUBFRAME_CONSTANT) {
521
        count += sub->obits;
522
    } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
523
        count += s->frame.blocksize * sub->obits;
524
    } else {
525
        /* warm-up samples */
526
        count += pred_order * sub->obits;
527

    
528
        /* LPC coefficients */
529
        if (sub->type == FLAC_SUBFRAME_LPC)
530
            count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
531

    
532
        /* rice-encoded block */
533
        count += 2;
534

    
535
        /* partition order */
536
        porder = sub->rc.porder;
537
        psize  = s->frame.blocksize >> porder;
538
        count += 4;
539

    
540
        /* residual */
541
        i        = pred_order;
542
        part_end = psize;
543
        for (p = 0; p < 1 << porder; p++) {
544
            int k = sub->rc.params[p];
545
            count += 4;
546
            count += rice_count_exact(&sub->residual[i], part_end - i, k);
547
            i = part_end;
548
            part_end = FFMIN(s->frame.blocksize, part_end + psize);
549
        }
550
    }
551

    
552
    return count;
553
}
554

    
555

    
556
#define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
557

    
558
/**
559
 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
560
 */
561
static int find_optimal_param(uint32_t sum, int n)
562
{
563
    int k;
564
    uint32_t sum2;
565

    
566
    if (sum <= n >> 1)
567
        return 0;
568
    sum2 = sum - (n >> 1);
569
    k    = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
570
    return FFMIN(k, MAX_RICE_PARAM);
571
}
572

    
573

    
574
static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
575
                                         uint32_t *sums, int n, int pred_order)
576
{
577
    int i;
578
    int k, cnt, part;
579
    uint32_t all_bits;
580

    
581
    part     = (1 << porder);
582
    all_bits = 4 * part;
583

    
584
    cnt = (n >> porder) - pred_order;
585
    for (i = 0; i < part; i++) {
586
        k = find_optimal_param(sums[i], cnt);
587
        rc->params[i] = k;
588
        all_bits += rice_encode_count(sums[i], cnt, k);
589
        cnt = n >> porder;
590
    }
591

    
592
    rc->porder = porder;
593

    
594
    return all_bits;
595
}
596

    
597

    
598
static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
599
                      uint32_t sums[][MAX_PARTITIONS])
600
{
601
    int i, j;
602
    int parts;
603
    uint32_t *res, *res_end;
604

    
605
    /* sums for highest level */
606
    parts   = (1 << pmax);
607
    res     = &data[pred_order];
608
    res_end = &data[n >> pmax];
609
    for (i = 0; i < parts; i++) {
610
        uint32_t sum = 0;
611
        while (res < res_end)
612
            sum += *(res++);
613
        sums[pmax][i] = sum;
614
        res_end += n >> pmax;
615
    }
616
    /* sums for lower levels */
617
    for (i = pmax - 1; i >= pmin; i--) {
618
        parts = (1 << i);
619
        for (j = 0; j < parts; j++)
620
            sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
621
    }
622
}
623

    
624

    
625
static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
626
                                 int32_t *data, int n, int pred_order)
627
{
628
    int i;
629
    uint32_t bits[MAX_PARTITION_ORDER+1];
630
    int opt_porder;
631
    RiceContext tmp_rc;
632
    uint32_t *udata;
633
    uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
634

    
635
    assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
636
    assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
637
    assert(pmin <= pmax);
638

    
639
    udata = av_malloc(n * sizeof(uint32_t));
640
    for (i = 0; i < n; i++)
641
        udata[i] = (2*data[i]) ^ (data[i]>>31);
642

    
643
    calc_sums(pmin, pmax, udata, n, pred_order, sums);
644

    
645
    opt_porder = pmin;
646
    bits[pmin] = UINT32_MAX;
647
    for (i = pmin; i <= pmax; i++) {
648
        bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
649
        if (bits[i] <= bits[opt_porder]) {
650
            opt_porder = i;
651
            *rc = tmp_rc;
652
        }
653
    }
654

    
655
    av_freep(&udata);
656
    return bits[opt_porder];
657
}
658

    
659

    
660
static int get_max_p_order(int max_porder, int n, int order)
661
{
662
    int porder = FFMIN(max_porder, av_log2(n^(n-1)));
663
    if (order > 0)
664
        porder = FFMIN(porder, av_log2(n/order));
665
    return porder;
666
}
667

    
668

    
669
static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
670
                                          FlacSubframe *sub, int pred_order)
671
{
672
    int pmin = get_max_p_order(s->options.min_partition_order,
673
                               s->frame.blocksize, pred_order);
674
    int pmax = get_max_p_order(s->options.max_partition_order,
675
                               s->frame.blocksize, pred_order);
676

    
677
    uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
678
    if (sub->type == FLAC_SUBFRAME_LPC)
679
        bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
680
    bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
681
                             s->frame.blocksize, pred_order);
682
    return bits;
683
}
684

    
685

    
686
static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
687
                                  int order)
688
{
689
    int i;
690

    
691
    for (i = 0; i < order; i++)
692
        res[i] = smp[i];
693

    
694
    if (order == 0) {
695
        for (i = order; i < n; i++)
696
            res[i] = smp[i];
697
    } else if (order == 1) {
698
        for (i = order; i < n; i++)
699
            res[i] = smp[i] - smp[i-1];
700
    } else if (order == 2) {
701
        int a = smp[order-1] - smp[order-2];
702
        for (i = order; i < n; i += 2) {
703
            int b    = smp[i  ] - smp[i-1];
704
            res[i]   = b - a;
705
            a        = smp[i+1] - smp[i  ];
706
            res[i+1] = a - b;
707
        }
708
    } else if (order == 3) {
709
        int a = smp[order-1] -   smp[order-2];
710
        int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
711
        for (i = order; i < n; i += 2) {
712
            int b    = smp[i  ] - smp[i-1];
713
            int d    = b - a;
714
            res[i]   = d - c;
715
            a        = smp[i+1] - smp[i  ];
716
            c        = a - b;
717
            res[i+1] = c - d;
718
        }
719
    } else {
720
        int a = smp[order-1] -   smp[order-2];
721
        int c = smp[order-1] - 2*smp[order-2] +   smp[order-3];
722
        int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
723
        for (i = order; i < n; i += 2) {
724
            int b    = smp[i  ] - smp[i-1];
725
            int d    = b - a;
726
            int f    = d - c;
727
            res[i  ] = f - e;
728
            a        = smp[i+1] - smp[i  ];
729
            c        = a - b;
730
            e        = c - d;
731
            res[i+1] = e - f;
732
        }
733
    }
734
}
735

    
736

    
737
#define LPC1(x) {\
738
    int c = coefs[(x)-1];\
739
    p0   += c * s;\
740
    s     = smp[i-(x)+1];\
741
    p1   += c * s;\
742
}
743

    
744
static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
745
                                    const int32_t *smp, int n, int order,
746
                                    const int32_t *coefs, int shift, int big)
747
{
748
    int i;
749
    for (i = order; i < n; i += 2) {
750
        int s  = smp[i-order];
751
        int p0 = 0, p1 = 0;
752
        if (big) {
753
            switch (order) {
754
            case 32: LPC1(32)
755
            case 31: LPC1(31)
756
            case 30: LPC1(30)
757
            case 29: LPC1(29)
758
            case 28: LPC1(28)
759
            case 27: LPC1(27)
760
            case 26: LPC1(26)
761
            case 25: LPC1(25)
762
            case 24: LPC1(24)
763
            case 23: LPC1(23)
764
            case 22: LPC1(22)
765
            case 21: LPC1(21)
766
            case 20: LPC1(20)
767
            case 19: LPC1(19)
768
            case 18: LPC1(18)
769
            case 17: LPC1(17)
770
            case 16: LPC1(16)
771
            case 15: LPC1(15)
772
            case 14: LPC1(14)
773
            case 13: LPC1(13)
774
            case 12: LPC1(12)
775
            case 11: LPC1(11)
776
            case 10: LPC1(10)
777
            case  9: LPC1( 9)
778
                     LPC1( 8)
779
                     LPC1( 7)
780
                     LPC1( 6)
781
                     LPC1( 5)
782
                     LPC1( 4)
783
                     LPC1( 3)
784
                     LPC1( 2)
785
                     LPC1( 1)
786
            }
787
        } else {
788
            switch (order) {
789
            case  8: LPC1( 8)
790
            case  7: LPC1( 7)
791
            case  6: LPC1( 6)
792
            case  5: LPC1( 5)
793
            case  4: LPC1( 4)
794
            case  3: LPC1( 3)
795
            case  2: LPC1( 2)
796
            case  1: LPC1( 1)
797
            }
798
        }
799
        res[i  ] = smp[i  ] - (p0 >> shift);
800
        res[i+1] = smp[i+1] - (p1 >> shift);
801
    }
802
}
803

    
804

    
805
static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
806
                                int order, const int32_t *coefs, int shift)
807
{
808
    int i;
809
    for (i = 0; i < order; i++)
810
        res[i] = smp[i];
811
#if CONFIG_SMALL
812
    for (i = order; i < n; i += 2) {
813
        int j;
814
        int s  = smp[i];
815
        int p0 = 0, p1 = 0;
816
        for (j = 0; j < order; j++) {
817
            int c = coefs[j];
818
            p1   += c * s;
819
            s     = smp[i-j-1];
820
            p0   += c * s;
821
        }
822
        res[i  ] = smp[i  ] - (p0 >> shift);
823
        res[i+1] = smp[i+1] - (p1 >> shift);
824
    }
825
#else
826
    switch (order) {
827
    case  1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
828
    case  2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
829
    case  3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
830
    case  4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
831
    case  5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
832
    case  6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
833
    case  7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
834
    case  8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
835
    default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
836
    }
837
#endif
838
}
839

    
840

    
841
static int encode_residual_ch(FlacEncodeContext *s, int ch)
842
{
843
    int i, n;
844
    int min_order, max_order, opt_order, omethod;
845
    FlacFrame *frame;
846
    FlacSubframe *sub;
847
    int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
848
    int shift[MAX_LPC_ORDER];
849
    int32_t *res, *smp;
850

    
851
    frame = &s->frame;
852
    sub   = &frame->subframes[ch];
853
    res   = sub->residual;
854
    smp   = sub->samples;
855
    n     = frame->blocksize;
856

    
857
    /* CONSTANT */
858
    for (i = 1; i < n; i++)
859
        if(smp[i] != smp[0])
860
            break;
861
    if (i == n) {
862
        sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
863
        res[0] = smp[0];
864
        return subframe_count_exact(s, sub, 0);
865
    }
866

    
867
    /* VERBATIM */
868
    if (frame->verbatim_only || n < 5) {
869
        sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
870
        memcpy(res, smp, n * sizeof(int32_t));
871
        return subframe_count_exact(s, sub, 0);
872
    }
873

    
874
    min_order  = s->options.min_prediction_order;
875
    max_order  = s->options.max_prediction_order;
876
    omethod    = s->options.prediction_order_method;
877

    
878
    /* FIXED */
879
    sub->type = FLAC_SUBFRAME_FIXED;
880
    if (s->options.lpc_type == AV_LPC_TYPE_NONE  ||
881
        s->options.lpc_type == AV_LPC_TYPE_FIXED || n <= max_order) {
882
        uint32_t bits[MAX_FIXED_ORDER+1];
883
        if (max_order > MAX_FIXED_ORDER)
884
            max_order = MAX_FIXED_ORDER;
885
        opt_order = 0;
886
        bits[0]   = UINT32_MAX;
887
        for (i = min_order; i <= max_order; i++) {
888
            encode_residual_fixed(res, smp, n, i);
889
            bits[i] = find_subframe_rice_params(s, sub, i);
890
            if (bits[i] < bits[opt_order])
891
                opt_order = i;
892
        }
893
        sub->order     = opt_order;
894
        sub->type_code = sub->type | sub->order;
895
        if (sub->order != max_order) {
896
            encode_residual_fixed(res, smp, n, sub->order);
897
            find_subframe_rice_params(s, sub, sub->order);
898
        }
899
        return subframe_count_exact(s, sub, sub->order);
900
    }
901

    
902
    /* LPC */
903
    sub->type = FLAC_SUBFRAME_LPC;
904
    opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
905
                                  s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
906
                                  s->options.lpc_passes, omethod,
907
                                  MAX_LPC_SHIFT, 0);
908

    
909
    if (omethod == ORDER_METHOD_2LEVEL ||
910
        omethod == ORDER_METHOD_4LEVEL ||
911
        omethod == ORDER_METHOD_8LEVEL) {
912
        int levels = 1 << omethod;
913
        uint32_t bits[1 << ORDER_METHOD_8LEVEL];
914
        int order;
915
        int opt_index   = levels-1;
916
        opt_order       = max_order-1;
917
        bits[opt_index] = UINT32_MAX;
918
        for (i = levels-1; i >= 0; i--) {
919
            order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
920
            if (order < 0)
921
                order = 0;
922
            encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
923
            bits[i] = find_subframe_rice_params(s, sub, order+1);
924
            if (bits[i] < bits[opt_index]) {
925
                opt_index = i;
926
                opt_order = order;
927
            }
928
        }
929
        opt_order++;
930
    } else if (omethod == ORDER_METHOD_SEARCH) {
931
        // brute-force optimal order search
932
        uint32_t bits[MAX_LPC_ORDER];
933
        opt_order = 0;
934
        bits[0]   = UINT32_MAX;
935
        for (i = min_order-1; i < max_order; i++) {
936
            encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
937
            bits[i] = find_subframe_rice_params(s, sub, i+1);
938
            if (bits[i] < bits[opt_order])
939
                opt_order = i;
940
        }
941
        opt_order++;
942
    } else if (omethod == ORDER_METHOD_LOG) {
943
        uint32_t bits[MAX_LPC_ORDER];
944
        int step;
945

    
946
        opt_order = min_order - 1 + (max_order-min_order)/3;
947
        memset(bits, -1, sizeof(bits));
948

    
949
        for (step = 16; step; step >>= 1) {
950
            int last = opt_order;
951
            for (i = last-step; i <= last+step; i += step) {
952
                if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
953
                    continue;
954
                encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
955
                bits[i] = find_subframe_rice_params(s, sub, i+1);
956
                if (bits[i] < bits[opt_order])
957
                    opt_order = i;
958
            }
959
        }
960
        opt_order++;
961
    }
962

    
963
    sub->order     = opt_order;
964
    sub->type_code = sub->type | (sub->order-1);
965
    sub->shift     = shift[sub->order-1];
966
    for (i = 0; i < sub->order; i++)
967
        sub->coefs[i] = coefs[sub->order-1][i];
968

    
969
    encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
970

    
971
    find_subframe_rice_params(s, sub, sub->order);
972

    
973
    return subframe_count_exact(s, sub, sub->order);
974
}
975

    
976

    
977
static int count_frame_header(FlacEncodeContext *s)
978
{
979
    uint8_t tmp;
980
    int count;
981

    
982
    /*
983
    <14> Sync code
984
    <1>  Reserved
985
    <1>  Blocking strategy
986
    <4>  Block size in inter-channel samples
987
    <4>  Sample rate
988
    <4>  Channel assignment
989
    <3>  Sample size in bits
990
    <1>  Reserved
991
    */
992
    count = 32;
993

    
994
    /* coded frame number */
995
    PUT_UTF8(s->frame_count, tmp, count += 8;)
996

    
997
    /* explicit block size */
998
    if (s->frame.bs_code[0] == 6)
999
        count += 8;
1000
    else if (s->frame.bs_code[0] == 7)
1001
        count += 16;
1002

    
1003
    /* explicit sample rate */
1004
    count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
1005

    
1006
    /* frame header CRC-8 */
1007
    count += 8;
1008

    
1009
    return count;
1010
}
1011

    
1012

    
1013
static int encode_frame(FlacEncodeContext *s)
1014
{
1015
    int ch, count;
1016

    
1017
    count = count_frame_header(s);
1018

    
1019
    for (ch = 0; ch < s->channels; ch++)
1020
        count += encode_residual_ch(s, ch);
1021

    
1022
    count += (8 - (count & 7)) & 7; // byte alignment
1023
    count += 16;                    // CRC-16
1024

    
1025
    return count >> 3;
1026
}
1027

    
1028

    
1029
static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1030
{
1031
    int i, best;
1032
    int32_t lt, rt;
1033
    uint64_t sum[4];
1034
    uint64_t score[4];
1035
    int k;
1036

    
1037
    /* calculate sum of 2nd order residual for each channel */
1038
    sum[0] = sum[1] = sum[2] = sum[3] = 0;
1039
    for (i = 2; i < n; i++) {
1040
        lt = left_ch[i]  - 2*left_ch[i-1]  + left_ch[i-2];
1041
        rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1042
        sum[2] += FFABS((lt + rt) >> 1);
1043
        sum[3] += FFABS(lt - rt);
1044
        sum[0] += FFABS(lt);
1045
        sum[1] += FFABS(rt);
1046
    }
1047
    /* estimate bit counts */
1048
    for (i = 0; i < 4; i++) {
1049
        k      = find_optimal_param(2 * sum[i], n);
1050
        sum[i] = rice_encode_count( 2 * sum[i], n, k);
1051
    }
1052

    
1053
    /* calculate score for each mode */
1054
    score[0] = sum[0] + sum[1];
1055
    score[1] = sum[0] + sum[3];
1056
    score[2] = sum[1] + sum[3];
1057
    score[3] = sum[2] + sum[3];
1058

    
1059
    /* return mode with lowest score */
1060
    best = 0;
1061
    for (i = 1; i < 4; i++)
1062
        if (score[i] < score[best])
1063
            best = i;
1064
    if (best == 0) {
1065
        return FLAC_CHMODE_INDEPENDENT;
1066
    } else if (best == 1) {
1067
        return FLAC_CHMODE_LEFT_SIDE;
1068
    } else if (best == 2) {
1069
        return FLAC_CHMODE_RIGHT_SIDE;
1070
    } else {
1071
        return FLAC_CHMODE_MID_SIDE;
1072
    }
1073
}
1074

    
1075

    
1076
/**
1077
 * Perform stereo channel decorrelation.
1078
 */
1079
static void channel_decorrelation(FlacEncodeContext *s)
1080
{
1081
    FlacFrame *frame;
1082
    int32_t *left, *right;
1083
    int i, n;
1084

    
1085
    frame = &s->frame;
1086
    n     = frame->blocksize;
1087
    left  = frame->subframes[0].samples;
1088
    right = frame->subframes[1].samples;
1089

    
1090
    if (s->channels != 2) {
1091
        frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1092
        return;
1093
    }
1094

    
1095
    frame->ch_mode = estimate_stereo_mode(left, right, n);
1096

    
1097
    /* perform decorrelation and adjust bits-per-sample */
1098
    if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1099
        return;
1100
    if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1101
        int32_t tmp;
1102
        for (i = 0; i < n; i++) {
1103
            tmp      = left[i];
1104
            left[i]  = (tmp + right[i]) >> 1;
1105
            right[i] =  tmp - right[i];
1106
        }
1107
        frame->subframes[1].obits++;
1108
    } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1109
        for (i = 0; i < n; i++)
1110
            right[i] = left[i] - right[i];
1111
        frame->subframes[1].obits++;
1112
    } else {
1113
        for (i = 0; i < n; i++)
1114
            left[i] -= right[i];
1115
        frame->subframes[0].obits++;
1116
    }
1117
}
1118

    
1119

    
1120
static void write_utf8(PutBitContext *pb, uint32_t val)
1121
{
1122
    uint8_t tmp;
1123
    PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1124
}
1125

    
1126

    
1127
static void write_frame_header(FlacEncodeContext *s)
1128
{
1129
    FlacFrame *frame;
1130
    int crc;
1131

    
1132
    frame = &s->frame;
1133

    
1134
    put_bits(&s->pb, 16, 0xFFF8);
1135
    put_bits(&s->pb, 4, frame->bs_code[0]);
1136
    put_bits(&s->pb, 4, s->sr_code[0]);
1137

    
1138
    if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1139
        put_bits(&s->pb, 4, s->channels-1);
1140
    else
1141
        put_bits(&s->pb, 4, frame->ch_mode);
1142

    
1143
    put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1144
    put_bits(&s->pb, 1, 0);
1145
    write_utf8(&s->pb, s->frame_count);
1146

    
1147
    if (frame->bs_code[0] == 6)
1148
        put_bits(&s->pb, 8, frame->bs_code[1]);
1149
    else if (frame->bs_code[0] == 7)
1150
        put_bits(&s->pb, 16, frame->bs_code[1]);
1151

    
1152
    if (s->sr_code[0] == 12)
1153
        put_bits(&s->pb, 8, s->sr_code[1]);
1154
    else if (s->sr_code[0] > 12)
1155
        put_bits(&s->pb, 16, s->sr_code[1]);
1156

    
1157
    flush_put_bits(&s->pb);
1158
    crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1159
                 put_bits_count(&s->pb) >> 3);
1160
    put_bits(&s->pb, 8, crc);
1161
}
1162

    
1163

    
1164
static void write_subframes(FlacEncodeContext *s)
1165
{
1166
    int ch;
1167

    
1168
    for (ch = 0; ch < s->channels; ch++) {
1169
        FlacSubframe *sub = &s->frame.subframes[ch];
1170
        int i, p, porder, psize;
1171
        int32_t *part_end;
1172
        int32_t *res       =  sub->residual;
1173
        int32_t *frame_end = &sub->residual[s->frame.blocksize];
1174

    
1175
        /* subframe header */
1176
        put_bits(&s->pb, 1, 0);
1177
        put_bits(&s->pb, 6, sub->type_code);
1178
        put_bits(&s->pb, 1, 0); /* no wasted bits */
1179

    
1180
        /* subframe */
1181
        if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1182
            put_sbits(&s->pb, sub->obits, res[0]);
1183
        } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1184
            while (res < frame_end)
1185
                put_sbits(&s->pb, sub->obits, *res++);
1186
        } else {
1187
            /* warm-up samples */
1188
            for (i = 0; i < sub->order; i++)
1189
                put_sbits(&s->pb, sub->obits, *res++);
1190

    
1191
            /* LPC coefficients */
1192
            if (sub->type == FLAC_SUBFRAME_LPC) {
1193
                int cbits = s->options.lpc_coeff_precision;
1194
                put_bits( &s->pb, 4, cbits-1);
1195
                put_sbits(&s->pb, 5, sub->shift);
1196
                for (i = 0; i < sub->order; i++)
1197
                    put_sbits(&s->pb, cbits, sub->coefs[i]);
1198
            }
1199

    
1200
            /* rice-encoded block */
1201
            put_bits(&s->pb, 2, 0);
1202

    
1203
            /* partition order */
1204
            porder  = sub->rc.porder;
1205
            psize   = s->frame.blocksize >> porder;
1206
            put_bits(&s->pb, 4, porder);
1207

    
1208
            /* residual */
1209
            part_end  = &sub->residual[psize];
1210
            for (p = 0; p < 1 << porder; p++) {
1211
                int k = sub->rc.params[p];
1212
                put_bits(&s->pb, 4, k);
1213
                while (res < part_end)
1214
                    set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1215
                part_end = FFMIN(frame_end, part_end + psize);
1216
            }
1217
        }
1218
    }
1219
}
1220

    
1221

    
1222
static void write_frame_footer(FlacEncodeContext *s)
1223
{
1224
    int crc;
1225
    flush_put_bits(&s->pb);
1226
    crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1227
                            put_bits_count(&s->pb)>>3));
1228
    put_bits(&s->pb, 16, crc);
1229
    flush_put_bits(&s->pb);
1230
}
1231

    
1232

    
1233
static int write_frame(FlacEncodeContext *s, uint8_t *frame, int buf_size)
1234
{
1235
    init_put_bits(&s->pb, frame, buf_size);
1236
    write_frame_header(s);
1237
    write_subframes(s);
1238
    write_frame_footer(s);
1239
    return put_bits_count(&s->pb) >> 3;
1240
}
1241

    
1242

    
1243
static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1244
{
1245
#if HAVE_BIGENDIAN
1246
    int i;
1247
    for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1248
        int16_t smp = av_le2ne16(samples[i]);
1249
        av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1250
    }
1251
#else
1252
    av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1253
#endif
1254
}
1255

    
1256

    
1257
static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1258
                             int buf_size, void *data)
1259
{
1260
    FlacEncodeContext *s;
1261
    const int16_t *samples = data;
1262
    int frame_bytes, out_bytes;
1263

    
1264
    s = avctx->priv_data;
1265

    
1266
    /* when the last block is reached, update the header in extradata */
1267
    if (!data) {
1268
        s->max_framesize = s->max_encoded_framesize;
1269
        av_md5_final(s->md5ctx, s->md5sum);
1270
        write_streaminfo(s, avctx->extradata);
1271
        return 0;
1272
    }
1273

    
1274
    /* change max_framesize for small final frame */
1275
    if (avctx->frame_size < s->frame.blocksize) {
1276
        s->max_framesize = ff_flac_get_max_frame_size(avctx->frame_size,
1277
                                                      s->channels, 16);
1278
    }
1279

    
1280
    init_frame(s);
1281

    
1282
    copy_samples(s, samples);
1283

    
1284
    channel_decorrelation(s);
1285

    
1286
    frame_bytes = encode_frame(s);
1287

    
1288
    /* fallback to verbatim mode if the compressed frame is larger than it
1289
       would be if encoded uncompressed. */
1290
    if (frame_bytes > s->max_framesize) {
1291
        s->frame.verbatim_only = 1;
1292
        frame_bytes = encode_frame(s);
1293
    }
1294

    
1295
    if (buf_size < frame_bytes) {
1296
        av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1297
        return 0;
1298
    }
1299
    out_bytes = write_frame(s, frame, buf_size);
1300

    
1301
    s->frame_count++;
1302
    avctx->coded_frame->pts = s->sample_count;
1303
    s->sample_count += avctx->frame_size;
1304
    update_md5_sum(s, samples);
1305
    if (out_bytes > s->max_encoded_framesize)
1306
        s->max_encoded_framesize = out_bytes;
1307
    if (out_bytes < s->min_framesize)
1308
        s->min_framesize = out_bytes;
1309

    
1310
    return out_bytes;
1311
}
1312

    
1313

    
1314
static av_cold int flac_encode_close(AVCodecContext *avctx)
1315
{
1316
    if (avctx->priv_data) {
1317
        FlacEncodeContext *s = avctx->priv_data;
1318
        av_freep(&s->md5ctx);
1319
    }
1320
    av_freep(&avctx->extradata);
1321
    avctx->extradata_size = 0;
1322
    av_freep(&avctx->coded_frame);
1323
    return 0;
1324
}
1325

    
1326

    
1327
AVCodec flac_encoder = {
1328
    "flac",
1329
    AVMEDIA_TYPE_AUDIO,
1330
    CODEC_ID_FLAC,
1331
    sizeof(FlacEncodeContext),
1332
    flac_encode_init,
1333
    flac_encode_frame,
1334
    flac_encode_close,
1335
    NULL,
1336
    .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1337
    .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1338
    .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1339
};