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