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