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