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