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