]> git.sesse.net Git - ffmpeg/blob - libavcodec/flacenc.c
c769833c35e91b6796153845a409d9e53059c177
[ffmpeg] / libavcodec / flacenc.c
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/avassert.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/intmath.h"
25 #include "libavutil/md5.h"
26 #include "libavutil/opt.h"
27 #include "avcodec.h"
28 #include "bswapdsp.h"
29 #include "put_bits.h"
30 #include "golomb.h"
31 #include "internal.h"
32 #include "lpc.h"
33 #include "flac.h"
34 #include "flacdata.h"
35 #include "flacdsp.h"
36
37 #define FLAC_SUBFRAME_CONSTANT  0
38 #define FLAC_SUBFRAME_VERBATIM  1
39 #define FLAC_SUBFRAME_FIXED     8
40 #define FLAC_SUBFRAME_LPC      32
41
42 #define MAX_FIXED_ORDER     4
43 #define MAX_PARTITION_ORDER 8
44 #define MAX_PARTITIONS     (1 << MAX_PARTITION_ORDER)
45 #define MAX_LPC_PRECISION  15
46 #define MAX_LPC_SHIFT      15
47
48 enum CodingMode {
49     CODING_MODE_RICE  = 4,
50     CODING_MODE_RICE2 = 5,
51 };
52
53 typedef struct CompressionOptions {
54     int compression_level;
55     int block_time_ms;
56     enum FFLPCType lpc_type;
57     int lpc_passes;
58     int lpc_coeff_precision;
59     int min_prediction_order;
60     int max_prediction_order;
61     int prediction_order_method;
62     int min_partition_order;
63     int max_partition_order;
64     int ch_mode;
65     int exact_rice_parameters;
66     int multi_dim_quant;
67 } CompressionOptions;
68
69 typedef struct RiceContext {
70     enum CodingMode coding_mode;
71     int porder;
72     int params[MAX_PARTITIONS];
73 } RiceContext;
74
75 typedef struct FlacSubframe {
76     int type;
77     int type_code;
78     int obits;
79     int wasted;
80     int order;
81     int32_t coefs[MAX_LPC_ORDER];
82     int shift;
83
84     RiceContext rc;
85     uint32_t rc_udata[FLAC_MAX_BLOCKSIZE];
86     uint64_t rc_sums[32][MAX_PARTITIONS];
87
88     int32_t samples[FLAC_MAX_BLOCKSIZE];
89     int32_t residual[FLAC_MAX_BLOCKSIZE+11];
90 } FlacSubframe;
91
92 typedef struct FlacFrame {
93     FlacSubframe subframes[FLAC_MAX_CHANNELS];
94     int blocksize;
95     int bs_code[2];
96     uint8_t crc8;
97     int ch_mode;
98     int verbatim_only;
99 } FlacFrame;
100
101 typedef struct FlacEncodeContext {
102     AVClass *class;
103     PutBitContext pb;
104     int channels;
105     int samplerate;
106     int sr_code[2];
107     int bps_code;
108     int max_blocksize;
109     int min_framesize;
110     int max_framesize;
111     int max_encoded_framesize;
112     uint32_t frame_count;
113     uint64_t sample_count;
114     uint8_t md5sum[16];
115     FlacFrame frame;
116     CompressionOptions options;
117     AVCodecContext *avctx;
118     LPCContext lpc_ctx;
119     struct AVMD5 *md5ctx;
120     uint8_t *md5_buffer;
121     unsigned int md5_buffer_size;
122     BswapDSPContext bdsp;
123     FLACDSPContext flac_dsp;
124
125     int flushed;
126     int64_t next_pts;
127 } FlacEncodeContext;
128
129
130 /**
131  * Write streaminfo metadata block to byte array.
132  */
133 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
134 {
135     PutBitContext pb;
136
137     memset(header, 0, FLAC_STREAMINFO_SIZE);
138     init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
139
140     /* streaminfo metadata block */
141     put_bits(&pb, 16, s->max_blocksize);
142     put_bits(&pb, 16, s->max_blocksize);
143     put_bits(&pb, 24, s->min_framesize);
144     put_bits(&pb, 24, s->max_framesize);
145     put_bits(&pb, 20, s->samplerate);
146     put_bits(&pb, 3, s->channels-1);
147     put_bits(&pb,  5, s->avctx->bits_per_raw_sample - 1);
148     /* write 36-bit sample count in 2 put_bits() calls */
149     put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
150     put_bits(&pb, 12,  s->sample_count & 0x000000FFFLL);
151     flush_put_bits(&pb);
152     memcpy(&header[18], s->md5sum, 16);
153 }
154
155
156 /**
157  * Set blocksize based on samplerate.
158  * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
159  */
160 static int select_blocksize(int samplerate, int block_time_ms)
161 {
162     int i;
163     int target;
164     int blocksize;
165
166     av_assert0(samplerate > 0);
167     blocksize = ff_flac_blocksize_table[1];
168     target    = (samplerate * block_time_ms) / 1000;
169     for (i = 0; i < 16; i++) {
170         if (target >= ff_flac_blocksize_table[i] &&
171             ff_flac_blocksize_table[i] > blocksize) {
172             blocksize = ff_flac_blocksize_table[i];
173         }
174     }
175     return blocksize;
176 }
177
178
179 static av_cold void dprint_compression_options(FlacEncodeContext *s)
180 {
181     AVCodecContext     *avctx = s->avctx;
182     CompressionOptions *opt   = &s->options;
183
184     av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
185
186     switch (opt->lpc_type) {
187     case FF_LPC_TYPE_NONE:
188         av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
189         break;
190     case FF_LPC_TYPE_FIXED:
191         av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
192         break;
193     case FF_LPC_TYPE_LEVINSON:
194         av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
195         break;
196     case FF_LPC_TYPE_CHOLESKY:
197         av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
198                opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
199         break;
200     }
201
202     av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
203            opt->min_prediction_order, opt->max_prediction_order);
204
205     switch (opt->prediction_order_method) {
206     case ORDER_METHOD_EST:
207         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
208         break;
209     case ORDER_METHOD_2LEVEL:
210         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
211         break;
212     case ORDER_METHOD_4LEVEL:
213         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
214         break;
215     case ORDER_METHOD_8LEVEL:
216         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
217         break;
218     case ORDER_METHOD_SEARCH:
219         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
220         break;
221     case ORDER_METHOD_LOG:
222         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
223         break;
224     }
225
226
227     av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
228            opt->min_partition_order, opt->max_partition_order);
229
230     av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
231
232     av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
233            opt->lpc_coeff_precision);
234 }
235
236
237 static av_cold int flac_encode_init(AVCodecContext *avctx)
238 {
239     int freq = avctx->sample_rate;
240     int channels = avctx->channels;
241     FlacEncodeContext *s = avctx->priv_data;
242     int i, level, ret;
243     uint8_t *streaminfo;
244
245     s->avctx = avctx;
246
247     switch (avctx->sample_fmt) {
248     case AV_SAMPLE_FMT_S16:
249         avctx->bits_per_raw_sample = 16;
250         s->bps_code                = 4;
251         break;
252     case AV_SAMPLE_FMT_S32:
253         if (avctx->bits_per_raw_sample != 24)
254             av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
255         avctx->bits_per_raw_sample = 24;
256         s->bps_code                = 6;
257         break;
258     }
259
260     if (channels < 1 || channels > FLAC_MAX_CHANNELS) {
261         av_log(avctx, AV_LOG_ERROR, "%d channels not supported (max %d)\n",
262                channels, FLAC_MAX_CHANNELS);
263         return AVERROR(EINVAL);
264     }
265     s->channels = channels;
266
267     /* find samplerate in table */
268     if (freq < 1)
269         return -1;
270     for (i = 4; i < 12; i++) {
271         if (freq == ff_flac_sample_rate_table[i]) {
272             s->samplerate = ff_flac_sample_rate_table[i];
273             s->sr_code[0] = i;
274             s->sr_code[1] = 0;
275             break;
276         }
277     }
278     /* if not in table, samplerate is non-standard */
279     if (i == 12) {
280         if (freq % 1000 == 0 && freq < 255000) {
281             s->sr_code[0] = 12;
282             s->sr_code[1] = freq / 1000;
283         } else if (freq % 10 == 0 && freq < 655350) {
284             s->sr_code[0] = 14;
285             s->sr_code[1] = freq / 10;
286         } else if (freq < 65535) {
287             s->sr_code[0] = 13;
288             s->sr_code[1] = freq;
289         } else {
290             av_log(avctx, AV_LOG_ERROR, "%d Hz not supported\n", freq);
291             return AVERROR(EINVAL);
292         }
293         s->samplerate = freq;
294     }
295
296     /* set compression option defaults based on avctx->compression_level */
297     if (avctx->compression_level < 0)
298         s->options.compression_level = 5;
299     else
300         s->options.compression_level = avctx->compression_level;
301
302     level = s->options.compression_level;
303     if (level > 12) {
304         av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
305                s->options.compression_level);
306         return AVERROR(EINVAL);
307     }
308
309     s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
310
311     if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
312         s->options.lpc_type  = ((int[]){ FF_LPC_TYPE_FIXED,    FF_LPC_TYPE_FIXED,    FF_LPC_TYPE_FIXED,
313                                          FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
314                                          FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
315                                          FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
316                                          FF_LPC_TYPE_LEVINSON})[level];
317
318     s->options.min_prediction_order = ((int[]){  2,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
319     s->options.max_prediction_order = ((int[]){  3,  4,  4,  6,  8,  8,  8,  8, 12, 12, 12, 32, 32})[level];
320
321     if (s->options.prediction_order_method < 0)
322         s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
323                                                        ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
324                                                        ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG,    ORDER_METHOD_4LEVEL,
325                                                        ORDER_METHOD_LOG,    ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
326                                                        ORDER_METHOD_SEARCH})[level];
327
328     if (s->options.min_partition_order > s->options.max_partition_order) {
329         av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
330                s->options.min_partition_order, s->options.max_partition_order);
331         return AVERROR(EINVAL);
332     }
333     if (s->options.min_partition_order < 0)
334         s->options.min_partition_order = ((int[]){  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0})[level];
335     if (s->options.max_partition_order < 0)
336         s->options.max_partition_order = ((int[]){  2,  2,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,  8})[level];
337
338     if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
339         s->options.min_prediction_order = 0;
340     } else if (avctx->min_prediction_order >= 0) {
341         if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
342             if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
343                 av_log(avctx, AV_LOG_WARNING,
344                        "invalid min prediction order %d, clamped to %d\n",
345                        avctx->min_prediction_order, MAX_FIXED_ORDER);
346                 avctx->min_prediction_order = MAX_FIXED_ORDER;
347             }
348         } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
349                    avctx->min_prediction_order > MAX_LPC_ORDER) {
350             av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
351                    avctx->min_prediction_order);
352             return AVERROR(EINVAL);
353         }
354         s->options.min_prediction_order = avctx->min_prediction_order;
355     }
356     if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
357         s->options.max_prediction_order = 0;
358     } else if (avctx->max_prediction_order >= 0) {
359         if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
360             if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
361                 av_log(avctx, AV_LOG_WARNING,
362                        "invalid max prediction order %d, clamped to %d\n",
363                        avctx->max_prediction_order, MAX_FIXED_ORDER);
364                 avctx->max_prediction_order = MAX_FIXED_ORDER;
365             }
366         } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
367                    avctx->max_prediction_order > MAX_LPC_ORDER) {
368             av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
369                    avctx->max_prediction_order);
370             return AVERROR(EINVAL);
371         }
372         s->options.max_prediction_order = avctx->max_prediction_order;
373     }
374     if (s->options.max_prediction_order < s->options.min_prediction_order) {
375         av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
376                s->options.min_prediction_order, s->options.max_prediction_order);
377         return AVERROR(EINVAL);
378     }
379
380     if (avctx->frame_size > 0) {
381         if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
382                 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
383             av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
384                    avctx->frame_size);
385             return AVERROR(EINVAL);
386         }
387     } else {
388         s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
389     }
390     s->max_blocksize = s->avctx->frame_size;
391
392     /* set maximum encoded frame size in verbatim mode */
393     s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
394                                                   s->channels,
395                                                   s->avctx->bits_per_raw_sample);
396
397     /* initialize MD5 context */
398     s->md5ctx = av_md5_alloc();
399     if (!s->md5ctx)
400         return AVERROR(ENOMEM);
401     av_md5_init(s->md5ctx);
402
403     streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
404     if (!streaminfo)
405         return AVERROR(ENOMEM);
406     write_streaminfo(s, streaminfo);
407     avctx->extradata = streaminfo;
408     avctx->extradata_size = FLAC_STREAMINFO_SIZE;
409
410     s->frame_count   = 0;
411     s->min_framesize = s->max_framesize;
412
413     if (channels == 3 &&
414             avctx->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
415         channels == 4 &&
416             avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
417             avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
418         channels == 5 &&
419             avctx->channel_layout != AV_CH_LAYOUT_5POINT0 &&
420             avctx->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
421         channels == 6 &&
422             avctx->channel_layout != AV_CH_LAYOUT_5POINT1 &&
423             avctx->channel_layout != AV_CH_LAYOUT_5POINT1_BACK) {
424         if (avctx->channel_layout) {
425             av_log(avctx, AV_LOG_ERROR, "Channel layout not supported by Flac, "
426                                              "output stream will have incorrect "
427                                              "channel layout.\n");
428         } else {
429             av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The encoder "
430                                                "will use Flac channel layout for "
431                                                "%d channels.\n", channels);
432         }
433     }
434
435     ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
436                       s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
437
438     ff_bswapdsp_init(&s->bdsp);
439     ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt, channels,
440                     avctx->bits_per_raw_sample);
441
442     dprint_compression_options(s);
443
444     return ret;
445 }
446
447
448 static void init_frame(FlacEncodeContext *s, int nb_samples)
449 {
450     int i, ch;
451     FlacFrame *frame;
452
453     frame = &s->frame;
454
455     for (i = 0; i < 16; i++) {
456         if (nb_samples == ff_flac_blocksize_table[i]) {
457             frame->blocksize  = ff_flac_blocksize_table[i];
458             frame->bs_code[0] = i;
459             frame->bs_code[1] = 0;
460             break;
461         }
462     }
463     if (i == 16) {
464         frame->blocksize = nb_samples;
465         if (frame->blocksize <= 256) {
466             frame->bs_code[0] = 6;
467             frame->bs_code[1] = frame->blocksize-1;
468         } else {
469             frame->bs_code[0] = 7;
470             frame->bs_code[1] = frame->blocksize-1;
471         }
472     }
473
474     for (ch = 0; ch < s->channels; ch++) {
475         FlacSubframe *sub = &frame->subframes[ch];
476
477         sub->wasted = 0;
478         sub->obits  = s->avctx->bits_per_raw_sample;
479
480         if (sub->obits > 16)
481             sub->rc.coding_mode = CODING_MODE_RICE2;
482         else
483             sub->rc.coding_mode = CODING_MODE_RICE;
484     }
485
486     frame->verbatim_only = 0;
487 }
488
489
490 /**
491  * Copy channel-interleaved input samples into separate subframes.
492  */
493 static void copy_samples(FlacEncodeContext *s, const void *samples)
494 {
495     int i, j, ch;
496     FlacFrame *frame;
497     int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
498                 s->avctx->bits_per_raw_sample;
499
500 #define COPY_SAMPLES(bits) do {                                     \
501     const int ## bits ## _t *samples0 = samples;                    \
502     frame = &s->frame;                                              \
503     for (i = 0, j = 0; i < frame->blocksize; i++)                   \
504         for (ch = 0; ch < s->channels; ch++, j++)                   \
505             frame->subframes[ch].samples[i] = samples0[j] >> shift; \
506 } while (0)
507
508     if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
509         COPY_SAMPLES(16);
510     else
511         COPY_SAMPLES(32);
512 }
513
514
515 static uint64_t rice_count_exact(const int32_t *res, int n, int k)
516 {
517     int i;
518     uint64_t count = 0;
519
520     for (i = 0; i < n; i++) {
521         int32_t v = -2 * res[i] - 1;
522         v ^= v >> 31;
523         count += (v >> k) + 1 + k;
524     }
525     return count;
526 }
527
528
529 static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
530                                      int pred_order)
531 {
532     int p, porder, psize;
533     int i, part_end;
534     uint64_t count = 0;
535
536     /* subframe header */
537     count += 8;
538
539     if (sub->wasted)
540         count += sub->wasted;
541
542     /* subframe */
543     if (sub->type == FLAC_SUBFRAME_CONSTANT) {
544         count += sub->obits;
545     } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
546         count += s->frame.blocksize * sub->obits;
547     } else {
548         /* warm-up samples */
549         count += pred_order * sub->obits;
550
551         /* LPC coefficients */
552         if (sub->type == FLAC_SUBFRAME_LPC)
553             count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
554
555         /* rice-encoded block */
556         count += 2;
557
558         /* partition order */
559         porder = sub->rc.porder;
560         psize  = s->frame.blocksize >> porder;
561         count += 4;
562
563         /* residual */
564         i        = pred_order;
565         part_end = psize;
566         for (p = 0; p < 1 << porder; p++) {
567             int k = sub->rc.params[p];
568             count += sub->rc.coding_mode;
569             count += rice_count_exact(&sub->residual[i], part_end - i, k);
570             i = part_end;
571             part_end = FFMIN(s->frame.blocksize, part_end + psize);
572         }
573     }
574
575     return count;
576 }
577
578
579 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
580
581 /**
582  * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
583  */
584 static int find_optimal_param(uint64_t sum, int n, int max_param)
585 {
586     int k;
587     uint64_t sum2;
588
589     if (sum <= n >> 1)
590         return 0;
591     sum2 = sum - (n >> 1);
592     k    = av_log2(av_clipl_int32(sum2 / n));
593     return FFMIN(k, max_param);
594 }
595
596 static int find_optimal_param_exact(uint64_t sums[32][MAX_PARTITIONS], int i, int max_param)
597 {
598     int bestk = 0;
599     int64_t bestbits = INT64_MAX;
600     int k;
601
602     for (k = 0; k <= max_param; k++) {
603         int64_t bits = sums[k][i];
604         if (bits < bestbits) {
605             bestbits = bits;
606             bestk = k;
607         }
608     }
609
610     return bestk;
611 }
612
613 static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
614                                          uint64_t sums[32][MAX_PARTITIONS],
615                                          int n, int pred_order, int max_param, int exact)
616 {
617     int i;
618     int k, cnt, part;
619     uint64_t all_bits;
620
621     part     = (1 << porder);
622     all_bits = 4 * part;
623
624     cnt = (n >> porder) - pred_order;
625     for (i = 0; i < part; i++) {
626         if (exact) {
627             k = find_optimal_param_exact(sums, i, max_param);
628             all_bits += sums[k][i];
629         } else {
630             k = find_optimal_param(sums[0][i], cnt, max_param);
631             all_bits += rice_encode_count(sums[0][i], cnt, k);
632         }
633         rc->params[i] = k;
634         cnt = n >> porder;
635     }
636
637     rc->porder = porder;
638
639     return all_bits;
640 }
641
642
643 static void calc_sum_top(int pmax, int kmax, const uint32_t *data, int n, int pred_order,
644                          uint64_t sums[32][MAX_PARTITIONS])
645 {
646     int i, k;
647     int parts;
648     const uint32_t *res, *res_end;
649
650     /* sums for highest level */
651     parts   = (1 << pmax);
652
653     for (k = 0; k <= kmax; k++) {
654         res     = &data[pred_order];
655         res_end = &data[n >> pmax];
656         for (i = 0; i < parts; i++) {
657             if (kmax) {
658                 uint64_t sum = (1LL + k) * (res_end - res);
659                 while (res < res_end)
660                     sum += *(res++) >> k;
661                 sums[k][i] = sum;
662             } else {
663                 uint64_t sum = 0;
664                 while (res < res_end)
665                     sum += *(res++);
666                 sums[k][i] = sum;
667             }
668             res_end += n >> pmax;
669         }
670     }
671 }
672
673 static void calc_sum_next(int level, uint64_t sums[32][MAX_PARTITIONS], int kmax)
674 {
675     int i, k;
676     int parts = (1 << level);
677     for (i = 0; i < parts; i++) {
678         for (k=0; k<=kmax; k++)
679             sums[k][i] = sums[k][2*i] + sums[k][2*i+1];
680     }
681 }
682
683 static uint64_t calc_rice_params(RiceContext *rc,
684                                  uint32_t udata[FLAC_MAX_BLOCKSIZE],
685                                  uint64_t sums[32][MAX_PARTITIONS],
686                                  int pmin, int pmax,
687                                  const int32_t *data, int n, int pred_order, int exact)
688 {
689     int i;
690     uint64_t bits[MAX_PARTITION_ORDER+1];
691     int opt_porder;
692     RiceContext tmp_rc;
693     int kmax = (1 << rc->coding_mode) - 2;
694
695     av_assert1(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
696     av_assert1(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
697     av_assert1(pmin <= pmax);
698
699     tmp_rc.coding_mode = rc->coding_mode;
700
701     for (i = 0; i < n; i++)
702         udata[i] = (2 * data[i]) ^ (data[i] >> 31);
703
704     calc_sum_top(pmax, exact ? kmax : 0, udata, n, pred_order, sums);
705
706     opt_porder = pmin;
707     bits[pmin] = UINT32_MAX;
708     for (i = pmax; ; ) {
709         bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums, n, pred_order, kmax, exact);
710         if (bits[i] < bits[opt_porder] || pmax == pmin) {
711             opt_porder = i;
712             *rc = tmp_rc;
713         }
714         if (i == pmin)
715             break;
716         calc_sum_next(--i, sums, exact ? kmax : 0);
717     }
718
719     return bits[opt_porder];
720 }
721
722
723 static int get_max_p_order(int max_porder, int n, int order)
724 {
725     int porder = FFMIN(max_porder, av_log2(n^(n-1)));
726     if (order > 0)
727         porder = FFMIN(porder, av_log2(n/order));
728     return porder;
729 }
730
731
732 static uint64_t find_subframe_rice_params(FlacEncodeContext *s,
733                                           FlacSubframe *sub, int pred_order)
734 {
735     int pmin = get_max_p_order(s->options.min_partition_order,
736                                s->frame.blocksize, pred_order);
737     int pmax = get_max_p_order(s->options.max_partition_order,
738                                s->frame.blocksize, pred_order);
739
740     uint64_t bits = 8 + pred_order * sub->obits + 2 + sub->rc.coding_mode;
741     if (sub->type == FLAC_SUBFRAME_LPC)
742         bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
743     bits += calc_rice_params(&sub->rc, sub->rc_udata, sub->rc_sums, pmin, pmax, sub->residual,
744                              s->frame.blocksize, pred_order, s->options.exact_rice_parameters);
745     return bits;
746 }
747
748
749 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
750                                   int order)
751 {
752     int i;
753
754     for (i = 0; i < order; i++)
755         res[i] = smp[i];
756
757     if (order == 0) {
758         for (i = order; i < n; i++)
759             res[i] = smp[i];
760     } else if (order == 1) {
761         for (i = order; i < n; i++)
762             res[i] = smp[i] - smp[i-1];
763     } else if (order == 2) {
764         int a = smp[order-1] - smp[order-2];
765         for (i = order; i < n; i += 2) {
766             int b    = smp[i  ] - smp[i-1];
767             res[i]   = b - a;
768             a        = smp[i+1] - smp[i  ];
769             res[i+1] = a - b;
770         }
771     } else if (order == 3) {
772         int a = smp[order-1] -   smp[order-2];
773         int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
774         for (i = order; i < n; i += 2) {
775             int b    = smp[i  ] - smp[i-1];
776             int d    = b - a;
777             res[i]   = d - c;
778             a        = smp[i+1] - smp[i  ];
779             c        = a - b;
780             res[i+1] = c - d;
781         }
782     } else {
783         int a = smp[order-1] -   smp[order-2];
784         int c = smp[order-1] - 2*smp[order-2] +   smp[order-3];
785         int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
786         for (i = order; i < n; i += 2) {
787             int b    = smp[i  ] - smp[i-1];
788             int d    = b - a;
789             int f    = d - c;
790             res[i  ] = f - e;
791             a        = smp[i+1] - smp[i  ];
792             c        = a - b;
793             e        = c - d;
794             res[i+1] = e - f;
795         }
796     }
797 }
798
799
800 static int encode_residual_ch(FlacEncodeContext *s, int ch)
801 {
802     int i, n;
803     int min_order, max_order, opt_order, omethod;
804     FlacFrame *frame;
805     FlacSubframe *sub;
806     int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
807     int shift[MAX_LPC_ORDER];
808     int32_t *res, *smp;
809
810     frame = &s->frame;
811     sub   = &frame->subframes[ch];
812     res   = sub->residual;
813     smp   = sub->samples;
814     n     = frame->blocksize;
815
816     /* CONSTANT */
817     for (i = 1; i < n; i++)
818         if(smp[i] != smp[0])
819             break;
820     if (i == n) {
821         sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
822         res[0] = smp[0];
823         return subframe_count_exact(s, sub, 0);
824     }
825
826     /* VERBATIM */
827     if (frame->verbatim_only || n < 5) {
828         sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
829         memcpy(res, smp, n * sizeof(int32_t));
830         return subframe_count_exact(s, sub, 0);
831     }
832
833     min_order  = s->options.min_prediction_order;
834     max_order  = s->options.max_prediction_order;
835     omethod    = s->options.prediction_order_method;
836
837     /* FIXED */
838     sub->type = FLAC_SUBFRAME_FIXED;
839     if (s->options.lpc_type == FF_LPC_TYPE_NONE  ||
840         s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
841         uint64_t bits[MAX_FIXED_ORDER+1];
842         if (max_order > MAX_FIXED_ORDER)
843             max_order = MAX_FIXED_ORDER;
844         opt_order = 0;
845         bits[0]   = UINT32_MAX;
846         for (i = min_order; i <= max_order; i++) {
847             encode_residual_fixed(res, smp, n, i);
848             bits[i] = find_subframe_rice_params(s, sub, i);
849             if (bits[i] < bits[opt_order])
850                 opt_order = i;
851         }
852         sub->order     = opt_order;
853         sub->type_code = sub->type | sub->order;
854         if (sub->order != max_order) {
855             encode_residual_fixed(res, smp, n, sub->order);
856             find_subframe_rice_params(s, sub, sub->order);
857         }
858         return subframe_count_exact(s, sub, sub->order);
859     }
860
861     /* LPC */
862     sub->type = FLAC_SUBFRAME_LPC;
863     opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
864                                   s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
865                                   s->options.lpc_passes, omethod,
866                                   MAX_LPC_SHIFT, 0);
867
868     if (omethod == ORDER_METHOD_2LEVEL ||
869         omethod == ORDER_METHOD_4LEVEL ||
870         omethod == ORDER_METHOD_8LEVEL) {
871         int levels = 1 << omethod;
872         uint64_t bits[1 << ORDER_METHOD_8LEVEL];
873         int order       = -1;
874         int opt_index   = levels-1;
875         opt_order       = max_order-1;
876         bits[opt_index] = UINT32_MAX;
877         for (i = levels-1; i >= 0; i--) {
878             int last_order = order;
879             order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
880             order = av_clip(order, min_order - 1, max_order - 1);
881             if (order == last_order)
882                 continue;
883             if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(order) <= 32) {
884                 s->flac_dsp.lpc16_encode(res, smp, n, order+1, coefs[order],
885                                          shift[order]);
886             } else {
887                 s->flac_dsp.lpc32_encode(res, smp, n, order+1, coefs[order],
888                                          shift[order]);
889             }
890             bits[i] = find_subframe_rice_params(s, sub, order+1);
891             if (bits[i] < bits[opt_index]) {
892                 opt_index = i;
893                 opt_order = order;
894             }
895         }
896         opt_order++;
897     } else if (omethod == ORDER_METHOD_SEARCH) {
898         // brute-force optimal order search
899         uint64_t bits[MAX_LPC_ORDER];
900         opt_order = 0;
901         bits[0]   = UINT32_MAX;
902         for (i = min_order-1; i < max_order; i++) {
903             if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(i) <= 32) {
904                 s->flac_dsp.lpc16_encode(res, smp, n, i+1, coefs[i], shift[i]);
905             } else {
906                 s->flac_dsp.lpc32_encode(res, smp, n, i+1, coefs[i], shift[i]);
907             }
908             bits[i] = find_subframe_rice_params(s, sub, i+1);
909             if (bits[i] < bits[opt_order])
910                 opt_order = i;
911         }
912         opt_order++;
913     } else if (omethod == ORDER_METHOD_LOG) {
914         uint64_t bits[MAX_LPC_ORDER];
915         int step;
916
917         opt_order = min_order - 1 + (max_order-min_order)/3;
918         memset(bits, -1, sizeof(bits));
919
920         for (step = 16; step; step >>= 1) {
921             int last = opt_order;
922             for (i = last-step; i <= last+step; i += step) {
923                 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
924                     continue;
925                 if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(i) <= 32) {
926                     s->flac_dsp.lpc32_encode(res, smp, n, i+1, coefs[i], shift[i]);
927                 } else {
928                     s->flac_dsp.lpc16_encode(res, smp, n, i+1, coefs[i], shift[i]);
929                 }
930                 bits[i] = find_subframe_rice_params(s, sub, i+1);
931                 if (bits[i] < bits[opt_order])
932                     opt_order = i;
933             }
934         }
935         opt_order++;
936     }
937
938     if (s->options.multi_dim_quant) {
939         int allsteps = 1;
940         int i, step, improved;
941         int64_t best_score = INT64_MAX;
942         int32_t qmax;
943
944         qmax = (1 << (s->options.lpc_coeff_precision - 1)) - 1;
945
946         for (i=0; i<opt_order; i++)
947             allsteps *= 3;
948
949         do {
950             improved = 0;
951             for (step = 0; step < allsteps; step++) {
952                 int tmp = step;
953                 int32_t lpc_try[MAX_LPC_ORDER];
954                 int64_t score = 0;
955                 int diffsum = 0;
956
957                 for (i=0; i<opt_order; i++) {
958                     int diff = ((tmp + 1) % 3) - 1;
959                     lpc_try[i] = av_clip(coefs[opt_order - 1][i] + diff, -qmax, qmax);
960                     tmp /= 3;
961                     diffsum += !!diff;
962                 }
963                 if (diffsum >8)
964                     continue;
965
966                 if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(opt_order - 1) <= 32) {
967                     s->flac_dsp.lpc16_encode(res, smp, n, opt_order, lpc_try, shift[opt_order-1]);
968                 } else {
969                     s->flac_dsp.lpc32_encode(res, smp, n, opt_order, lpc_try, shift[opt_order-1]);
970                 }
971                 score = find_subframe_rice_params(s, sub, opt_order);
972                 if (score < best_score) {
973                     best_score = score;
974                     memcpy(coefs[opt_order-1], lpc_try, sizeof(*coefs));
975                     improved=1;
976                 }
977             }
978         } while(improved);
979     }
980
981     sub->order     = opt_order;
982     sub->type_code = sub->type | (sub->order-1);
983     sub->shift     = shift[sub->order-1];
984     for (i = 0; i < sub->order; i++)
985         sub->coefs[i] = coefs[sub->order-1][i];
986
987     if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(opt_order) <= 32) {
988         s->flac_dsp.lpc16_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
989     } else {
990         s->flac_dsp.lpc32_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
991     }
992
993     find_subframe_rice_params(s, sub, sub->order);
994
995     return subframe_count_exact(s, sub, sub->order);
996 }
997
998
999 static int count_frame_header(FlacEncodeContext *s)
1000 {
1001     uint8_t av_unused tmp;
1002     int count;
1003
1004     /*
1005     <14> Sync code
1006     <1>  Reserved
1007     <1>  Blocking strategy
1008     <4>  Block size in inter-channel samples
1009     <4>  Sample rate
1010     <4>  Channel assignment
1011     <3>  Sample size in bits
1012     <1>  Reserved
1013     */
1014     count = 32;
1015
1016     /* coded frame number */
1017     PUT_UTF8(s->frame_count, tmp, count += 8;)
1018
1019     /* explicit block size */
1020     if (s->frame.bs_code[0] == 6)
1021         count += 8;
1022     else if (s->frame.bs_code[0] == 7)
1023         count += 16;
1024
1025     /* explicit sample rate */
1026     count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12) * 2) * 8;
1027
1028     /* frame header CRC-8 */
1029     count += 8;
1030
1031     return count;
1032 }
1033
1034
1035 static int encode_frame(FlacEncodeContext *s)
1036 {
1037     int ch;
1038     uint64_t count;
1039
1040     count = count_frame_header(s);
1041
1042     for (ch = 0; ch < s->channels; ch++)
1043         count += encode_residual_ch(s, ch);
1044
1045     count += (8 - (count & 7)) & 7; // byte alignment
1046     count += 16;                    // CRC-16
1047
1048     count >>= 3;
1049     if (count > INT_MAX)
1050         return AVERROR_BUG;
1051     return count;
1052 }
1053
1054
1055 static void remove_wasted_bits(FlacEncodeContext *s)
1056 {
1057     int ch, i;
1058
1059     for (ch = 0; ch < s->channels; ch++) {
1060         FlacSubframe *sub = &s->frame.subframes[ch];
1061         int32_t v         = 0;
1062
1063         for (i = 0; i < s->frame.blocksize; i++) {
1064             v |= sub->samples[i];
1065             if (v & 1)
1066                 break;
1067         }
1068
1069         if (v && !(v & 1)) {
1070             v = ff_ctz(v);
1071
1072             for (i = 0; i < s->frame.blocksize; i++)
1073                 sub->samples[i] >>= v;
1074
1075             sub->wasted = v;
1076             sub->obits -= v;
1077
1078             /* for 24-bit, check if removing wasted bits makes the range better
1079                suited for using RICE instead of RICE2 for entropy coding */
1080             if (sub->obits <= 17)
1081                 sub->rc.coding_mode = CODING_MODE_RICE;
1082         }
1083     }
1084 }
1085
1086
1087 static int estimate_stereo_mode(const int32_t *left_ch, const int32_t *right_ch, int n,
1088                                 int max_rice_param)
1089 {
1090     int i, best;
1091     int32_t lt, rt;
1092     uint64_t sum[4];
1093     uint64_t score[4];
1094     int k;
1095
1096     /* calculate sum of 2nd order residual for each channel */
1097     sum[0] = sum[1] = sum[2] = sum[3] = 0;
1098     for (i = 2; i < n; i++) {
1099         lt = left_ch[i]  - 2*left_ch[i-1]  + left_ch[i-2];
1100         rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1101         sum[2] += FFABS((lt + rt) >> 1);
1102         sum[3] += FFABS(lt - rt);
1103         sum[0] += FFABS(lt);
1104         sum[1] += FFABS(rt);
1105     }
1106     /* estimate bit counts */
1107     for (i = 0; i < 4; i++) {
1108         k      = find_optimal_param(2 * sum[i], n, max_rice_param);
1109         sum[i] = rice_encode_count( 2 * sum[i], n, k);
1110     }
1111
1112     /* calculate score for each mode */
1113     score[0] = sum[0] + sum[1];
1114     score[1] = sum[0] + sum[3];
1115     score[2] = sum[1] + sum[3];
1116     score[3] = sum[2] + sum[3];
1117
1118     /* return mode with lowest score */
1119     best = 0;
1120     for (i = 1; i < 4; i++)
1121         if (score[i] < score[best])
1122             best = i;
1123
1124     return best;
1125 }
1126
1127
1128 /**
1129  * Perform stereo channel decorrelation.
1130  */
1131 static void channel_decorrelation(FlacEncodeContext *s)
1132 {
1133     FlacFrame *frame;
1134     int32_t *left, *right;
1135     int i, n;
1136
1137     frame = &s->frame;
1138     n     = frame->blocksize;
1139     left  = frame->subframes[0].samples;
1140     right = frame->subframes[1].samples;
1141
1142     if (s->channels != 2) {
1143         frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1144         return;
1145     }
1146
1147     if (s->options.ch_mode < 0) {
1148         int max_rice_param = (1 << frame->subframes[0].rc.coding_mode) - 2;
1149         frame->ch_mode = estimate_stereo_mode(left, right, n, max_rice_param);
1150     } else
1151         frame->ch_mode = s->options.ch_mode;
1152
1153     /* perform decorrelation and adjust bits-per-sample */
1154     if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1155         return;
1156     if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1157         int32_t tmp;
1158         for (i = 0; i < n; i++) {
1159             tmp      = left[i];
1160             left[i]  = (tmp + right[i]) >> 1;
1161             right[i] =  tmp - right[i];
1162         }
1163         frame->subframes[1].obits++;
1164     } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1165         for (i = 0; i < n; i++)
1166             right[i] = left[i] - right[i];
1167         frame->subframes[1].obits++;
1168     } else {
1169         for (i = 0; i < n; i++)
1170             left[i] -= right[i];
1171         frame->subframes[0].obits++;
1172     }
1173 }
1174
1175
1176 static void write_utf8(PutBitContext *pb, uint32_t val)
1177 {
1178     uint8_t tmp;
1179     PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1180 }
1181
1182
1183 static void write_frame_header(FlacEncodeContext *s)
1184 {
1185     FlacFrame *frame;
1186     int crc;
1187
1188     frame = &s->frame;
1189
1190     put_bits(&s->pb, 16, 0xFFF8);
1191     put_bits(&s->pb, 4, frame->bs_code[0]);
1192     put_bits(&s->pb, 4, s->sr_code[0]);
1193
1194     if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1195         put_bits(&s->pb, 4, s->channels-1);
1196     else
1197         put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
1198
1199     put_bits(&s->pb, 3, s->bps_code);
1200     put_bits(&s->pb, 1, 0);
1201     write_utf8(&s->pb, s->frame_count);
1202
1203     if (frame->bs_code[0] == 6)
1204         put_bits(&s->pb, 8, frame->bs_code[1]);
1205     else if (frame->bs_code[0] == 7)
1206         put_bits(&s->pb, 16, frame->bs_code[1]);
1207
1208     if (s->sr_code[0] == 12)
1209         put_bits(&s->pb, 8, s->sr_code[1]);
1210     else if (s->sr_code[0] > 12)
1211         put_bits(&s->pb, 16, s->sr_code[1]);
1212
1213     flush_put_bits(&s->pb);
1214     crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1215                  put_bits_count(&s->pb) >> 3);
1216     put_bits(&s->pb, 8, crc);
1217 }
1218
1219
1220 static void write_subframes(FlacEncodeContext *s)
1221 {
1222     int ch;
1223
1224     for (ch = 0; ch < s->channels; ch++) {
1225         FlacSubframe *sub = &s->frame.subframes[ch];
1226         int i, p, porder, psize;
1227         int32_t *part_end;
1228         int32_t *res       =  sub->residual;
1229         int32_t *frame_end = &sub->residual[s->frame.blocksize];
1230
1231         /* subframe header */
1232         put_bits(&s->pb, 1, 0);
1233         put_bits(&s->pb, 6, sub->type_code);
1234         put_bits(&s->pb, 1, !!sub->wasted);
1235         if (sub->wasted)
1236             put_bits(&s->pb, sub->wasted, 1);
1237
1238         /* subframe */
1239         if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1240             put_sbits(&s->pb, sub->obits, res[0]);
1241         } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1242             while (res < frame_end)
1243                 put_sbits(&s->pb, sub->obits, *res++);
1244         } else {
1245             /* warm-up samples */
1246             for (i = 0; i < sub->order; i++)
1247                 put_sbits(&s->pb, sub->obits, *res++);
1248
1249             /* LPC coefficients */
1250             if (sub->type == FLAC_SUBFRAME_LPC) {
1251                 int cbits = s->options.lpc_coeff_precision;
1252                 put_bits( &s->pb, 4, cbits-1);
1253                 put_sbits(&s->pb, 5, sub->shift);
1254                 for (i = 0; i < sub->order; i++)
1255                     put_sbits(&s->pb, cbits, sub->coefs[i]);
1256             }
1257
1258             /* rice-encoded block */
1259             put_bits(&s->pb, 2, sub->rc.coding_mode - 4);
1260
1261             /* partition order */
1262             porder  = sub->rc.porder;
1263             psize   = s->frame.blocksize >> porder;
1264             put_bits(&s->pb, 4, porder);
1265
1266             /* residual */
1267             part_end  = &sub->residual[psize];
1268             for (p = 0; p < 1 << porder; p++) {
1269                 int k = sub->rc.params[p];
1270                 put_bits(&s->pb, sub->rc.coding_mode, k);
1271                 while (res < part_end)
1272                     set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1273                 part_end = FFMIN(frame_end, part_end + psize);
1274             }
1275         }
1276     }
1277 }
1278
1279
1280 static void write_frame_footer(FlacEncodeContext *s)
1281 {
1282     int crc;
1283     flush_put_bits(&s->pb);
1284     crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1285                             put_bits_count(&s->pb)>>3));
1286     put_bits(&s->pb, 16, crc);
1287     flush_put_bits(&s->pb);
1288 }
1289
1290
1291 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1292 {
1293     init_put_bits(&s->pb, avpkt->data, avpkt->size);
1294     write_frame_header(s);
1295     write_subframes(s);
1296     write_frame_footer(s);
1297     return put_bits_count(&s->pb) >> 3;
1298 }
1299
1300
1301 static int update_md5_sum(FlacEncodeContext *s, const void *samples)
1302 {
1303     const uint8_t *buf;
1304     int buf_size = s->frame.blocksize * s->channels *
1305                    ((s->avctx->bits_per_raw_sample + 7) / 8);
1306
1307     if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
1308         av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
1309         if (!s->md5_buffer)
1310             return AVERROR(ENOMEM);
1311     }
1312
1313     if (s->avctx->bits_per_raw_sample <= 16) {
1314         buf = (const uint8_t *)samples;
1315 #if HAVE_BIGENDIAN
1316         s->bdsp.bswap16_buf((uint16_t *) s->md5_buffer,
1317                             (const uint16_t *) samples, buf_size / 2);
1318         buf = s->md5_buffer;
1319 #endif
1320     } else {
1321         int i;
1322         const int32_t *samples0 = samples;
1323         uint8_t *tmp            = s->md5_buffer;
1324
1325         for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1326             int32_t v = samples0[i] >> 8;
1327             AV_WL24(tmp + 3*i, v);
1328         }
1329         buf = s->md5_buffer;
1330     }
1331     av_md5_update(s->md5ctx, buf, buf_size);
1332
1333     return 0;
1334 }
1335
1336
1337 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1338                              const AVFrame *frame, int *got_packet_ptr)
1339 {
1340     FlacEncodeContext *s;
1341     int frame_bytes, out_bytes, ret;
1342
1343     s = avctx->priv_data;
1344
1345     /* when the last block is reached, update the header in extradata */
1346     if (!frame) {
1347         s->max_framesize = s->max_encoded_framesize;
1348         av_md5_final(s->md5ctx, s->md5sum);
1349         write_streaminfo(s, avctx->extradata);
1350
1351 #if FF_API_SIDEDATA_ONLY_PKT
1352 FF_DISABLE_DEPRECATION_WARNINGS
1353         if (avctx->side_data_only_packets && !s->flushed) {
1354 FF_ENABLE_DEPRECATION_WARNINGS
1355 #else
1356         if (!s->flushed) {
1357 #endif
1358             uint8_t *side_data = av_packet_new_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
1359                                                          avctx->extradata_size);
1360             if (!side_data)
1361                 return AVERROR(ENOMEM);
1362             memcpy(side_data, avctx->extradata, avctx->extradata_size);
1363
1364             avpkt->pts = s->next_pts;
1365
1366             *got_packet_ptr = 1;
1367             s->flushed = 1;
1368         }
1369
1370         return 0;
1371     }
1372
1373     /* change max_framesize for small final frame */
1374     if (frame->nb_samples < s->frame.blocksize) {
1375         s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
1376                                                       s->channels,
1377                                                       avctx->bits_per_raw_sample);
1378     }
1379
1380     init_frame(s, frame->nb_samples);
1381
1382     copy_samples(s, frame->data[0]);
1383
1384     channel_decorrelation(s);
1385
1386     remove_wasted_bits(s);
1387
1388     frame_bytes = encode_frame(s);
1389
1390     /* Fall back on verbatim mode if the compressed frame is larger than it
1391        would be if encoded uncompressed. */
1392     if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
1393         s->frame.verbatim_only = 1;
1394         frame_bytes = encode_frame(s);
1395         if (frame_bytes < 0) {
1396             av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
1397             return frame_bytes;
1398         }
1399     }
1400
1401     if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes, 0)) < 0)
1402         return ret;
1403
1404     out_bytes = write_frame(s, avpkt);
1405
1406     s->frame_count++;
1407     s->sample_count += frame->nb_samples;
1408     if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
1409         av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
1410         return ret;
1411     }
1412     if (out_bytes > s->max_encoded_framesize)
1413         s->max_encoded_framesize = out_bytes;
1414     if (out_bytes < s->min_framesize)
1415         s->min_framesize = out_bytes;
1416
1417     avpkt->pts      = frame->pts;
1418     avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1419     avpkt->size     = out_bytes;
1420
1421     s->next_pts = avpkt->pts + avpkt->duration;
1422
1423     *got_packet_ptr = 1;
1424     return 0;
1425 }
1426
1427
1428 static av_cold int flac_encode_close(AVCodecContext *avctx)
1429 {
1430     if (avctx->priv_data) {
1431         FlacEncodeContext *s = avctx->priv_data;
1432         av_freep(&s->md5ctx);
1433         av_freep(&s->md5_buffer);
1434         ff_lpc_end(&s->lpc_ctx);
1435     }
1436     av_freep(&avctx->extradata);
1437     avctx->extradata_size = 0;
1438     return 0;
1439 }
1440
1441 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1442 static const AVOption options[] = {
1443 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1444 { "lpc_type", "LPC algorithm", offsetof(FlacEncodeContext, options.lpc_type), AV_OPT_TYPE_INT, {.i64 = FF_LPC_TYPE_DEFAULT }, FF_LPC_TYPE_DEFAULT, FF_LPC_TYPE_NB-1, FLAGS, "lpc_type" },
1445 { "none",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE },     INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1446 { "fixed",    NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED },    INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1447 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1448 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1449 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes),  AV_OPT_TYPE_INT, {.i64 = 2 }, 1, INT_MAX, FLAGS },
1450 { "min_partition_order",  NULL, offsetof(FlacEncodeContext, options.min_partition_order),  AV_OPT_TYPE_INT, {.i64 = -1 },      -1, MAX_PARTITION_ORDER, FLAGS },
1451 { "max_partition_order",  NULL, offsetof(FlacEncodeContext, options.max_partition_order),  AV_OPT_TYPE_INT, {.i64 = -1 },      -1, MAX_PARTITION_ORDER, FLAGS },
1452 { "prediction_order_method", "Search method for selecting prediction order", offsetof(FlacEncodeContext, options.prediction_order_method), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, ORDER_METHOD_LOG, FLAGS, "predm" },
1453 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST },    INT_MIN, INT_MAX, FLAGS, "predm" },
1454 { "2level",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1455 { "4level",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1456 { "8level",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1457 { "search",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1458 { "log",        NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG },    INT_MIN, INT_MAX, FLAGS, "predm" },
1459 { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
1460 { "auto",       NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1                      }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1461 { "indep",      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1462 { "left_side",  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE   }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1463 { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE  }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1464 { "mid_side",   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE    }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1465 { "exact_rice_parameters", "Calculate rice parameters exactly", offsetof(FlacEncodeContext, options.exact_rice_parameters), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
1466 { "multi_dim_quant",       "Multi-dimensional quantization",    offsetof(FlacEncodeContext, options.multi_dim_quant),       AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
1467 { NULL },
1468 };
1469
1470 static const AVClass flac_encoder_class = {
1471     .class_name = "FLAC encoder",
1472     .item_name  = av_default_item_name,
1473     .option     = options,
1474     .version    = LIBAVUTIL_VERSION_INT,
1475 };
1476
1477 AVCodec ff_flac_encoder = {
1478     .name           = "flac",
1479     .long_name      = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1480     .type           = AVMEDIA_TYPE_AUDIO,
1481     .id             = AV_CODEC_ID_FLAC,
1482     .priv_data_size = sizeof(FlacEncodeContext),
1483     .init           = flac_encode_init,
1484     .encode2        = flac_encode_frame,
1485     .close          = flac_encode_close,
1486     .capabilities   = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY | AV_CODEC_CAP_LOSSLESS,
1487     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1488                                                      AV_SAMPLE_FMT_S32,
1489                                                      AV_SAMPLE_FMT_NONE },
1490     .priv_class     = &flac_encoder_class,
1491 };