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