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