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