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