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