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