]> git.sesse.net Git - ffmpeg/blob - libavcodec/flacenc.c
2.5x faster compute_autocorr()
[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+1];
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, j;
611     double tmp[len + lag];
612     double *data1= tmp + lag;
613
614     apply_welch_window(data, len, data1);
615
616     for(j=0; j<lag; j++)
617         data1[j-lag]= 0.0;
618
619     for(j=0; j<lag; j+=2){
620         double sum0 = 1.0, sum1 = 1.0;
621         for(i=0; i<len; i++){
622             sum0 += data1[i] * data1[i-j];
623             sum1 += data1[i] * data1[i-j-1];
624         }
625         autoc[j  ] = sum0;
626         autoc[j+1] = sum1;
627     }
628
629     if(j==lag){
630         double sum = 1.0;
631         for(i=0; i<len; i++)
632             sum += data1[i] * data1[i-j];
633         autoc[j] = sum;
634     }
635 }
636
637 /**
638  * Levinson-Durbin recursion.
639  * Produces LPC coefficients from autocorrelation data.
640  */
641 static void compute_lpc_coefs(const double *autoc, int max_order,
642                               double lpc[][MAX_LPC_ORDER], double *ref)
643 {
644    int i, j, i2;
645    double r, err, tmp;
646    double lpc_tmp[MAX_LPC_ORDER];
647
648    for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
649    err = autoc[0];
650
651    for(i=0; i<max_order; i++) {
652       r = -autoc[i+1];
653       for(j=0; j<i; j++) {
654           r -= lpc_tmp[j] * autoc[i-j];
655       }
656       r /= err;
657       ref[i] = fabs(r);
658
659       err *= 1.0 - (r * r);
660
661       i2 = (i >> 1);
662       lpc_tmp[i] = r;
663       for(j=0; j<i2; j++) {
664          tmp = lpc_tmp[j];
665          lpc_tmp[j] += r * lpc_tmp[i-1-j];
666          lpc_tmp[i-1-j] += r * tmp;
667       }
668       if(i & 1) {
669           lpc_tmp[j] += lpc_tmp[j] * r;
670       }
671
672       for(j=0; j<=i; j++) {
673           lpc[i][j] = -lpc_tmp[j];
674       }
675    }
676 }
677
678 /**
679  * Quantize LPC coefficients
680  */
681 static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
682                                int32_t *lpc_out, int *shift)
683 {
684     int i;
685     double cmax, error;
686     int32_t qmax;
687     int sh;
688
689     /* define maximum levels */
690     qmax = (1 << (precision - 1)) - 1;
691
692     /* find maximum coefficient value */
693     cmax = 0.0;
694     for(i=0; i<order; i++) {
695         cmax= FFMAX(cmax, fabs(lpc_in[i]));
696     }
697
698     /* if maximum value quantizes to zero, return all zeros */
699     if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
700         *shift = 0;
701         memset(lpc_out, 0, sizeof(int32_t) * order);
702         return;
703     }
704
705     /* calculate level shift which scales max coeff to available bits */
706     sh = MAX_LPC_SHIFT;
707     while((cmax * (1 << sh) > qmax) && (sh > 0)) {
708         sh--;
709     }
710
711     /* since negative shift values are unsupported in decoder, scale down
712        coefficients instead */
713     if(sh == 0 && cmax > qmax) {
714         double scale = ((double)qmax) / cmax;
715         for(i=0; i<order; i++) {
716             lpc_in[i] *= scale;
717         }
718     }
719
720     /* output quantized coefficients and level shift */
721     error=0;
722     for(i=0; i<order; i++) {
723         error += lpc_in[i] * (1 << sh);
724         lpc_out[i] = av_clip(lrintf(error), -qmax, qmax);
725         error -= lpc_out[i];
726     }
727     *shift = sh;
728 }
729
730 static int estimate_best_order(double *ref, int max_order)
731 {
732     int i, est;
733
734     est = 1;
735     for(i=max_order-1; i>=0; i--) {
736         if(ref[i] > 0.10) {
737             est = i+1;
738             break;
739         }
740     }
741     return est;
742 }
743
744 /**
745  * Calculate LPC coefficients for multiple orders
746  */
747 static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
748                           int precision, int32_t coefs[][MAX_LPC_ORDER],
749                           int *shift, int use_lpc, int omethod)
750 {
751     double autoc[MAX_LPC_ORDER+1];
752     double ref[MAX_LPC_ORDER];
753     double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
754     int i, j, pass;
755     int opt_order;
756
757     assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
758
759     if(use_lpc == 1){
760         compute_autocorr(samples, blocksize, max_order+1, autoc);
761
762         compute_lpc_coefs(autoc, max_order, lpc, ref);
763     }else{
764         LLSModel m[2];
765         double var[MAX_LPC_ORDER+1], eval, weight;
766
767         for(pass=0; pass<use_lpc-1; pass++){
768             av_init_lls(&m[pass&1], max_order);
769
770             weight=0;
771             for(i=max_order; i<blocksize; i++){
772                 for(j=0; j<=max_order; j++)
773                     var[j]= samples[i-j];
774
775                 if(pass){
776                     eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
777                     eval= (512>>pass) + fabs(eval - var[0]);
778                     for(j=0; j<=max_order; j++)
779                         var[j]/= sqrt(eval);
780                     weight += 1/eval;
781                 }else
782                     weight++;
783
784                 av_update_lls(&m[pass&1], var, 1.0);
785             }
786             av_solve_lls(&m[pass&1], 0.001, 0);
787         }
788
789         for(i=0; i<max_order; i++){
790             for(j=0; j<max_order; j++)
791                 lpc[i][j]= m[(pass-1)&1].coeff[i][j];
792             ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
793         }
794         for(i=max_order-1; i>0; i--)
795             ref[i] = ref[i-1] - ref[i];
796     }
797     opt_order = max_order;
798
799     if(omethod == ORDER_METHOD_EST) {
800         opt_order = estimate_best_order(ref, max_order);
801         i = opt_order-1;
802         quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
803     } else {
804         for(i=0; i<max_order; i++) {
805             quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
806         }
807     }
808
809     return opt_order;
810 }
811
812
813 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
814 {
815     assert(n > 0);
816     memcpy(res, smp, n * sizeof(int32_t));
817 }
818
819 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
820                                   int order)
821 {
822     int i;
823
824     for(i=0; i<order; i++) {
825         res[i] = smp[i];
826     }
827
828     if(order==0){
829         for(i=order; i<n; i++)
830             res[i]= smp[i];
831     }else if(order==1){
832         for(i=order; i<n; i++)
833             res[i]= smp[i] - smp[i-1];
834     }else if(order==2){
835         for(i=order; i<n; i++)
836             res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
837     }else if(order==3){
838         for(i=order; i<n; i++)
839             res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
840     }else{
841         for(i=order; i<n; i++)
842             res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
843     }
844 }
845
846 #define LPC1(x) {\
847     int s = smp[i-(x)+1];\
848     p1 += c*s;\
849     c = coefs[(x)-2];\
850     p0 += c*s;\
851 }
852
853 static av_always_inline void encode_residual_lpc_unrolled(
854     int32_t *res, const int32_t *smp, int n,
855     int order, const int32_t *coefs, int shift, int big)
856 {
857     int i;
858     for(i=order; i<n; i+=2) {
859         int c = coefs[order-1];
860         int p0 = c * smp[i-order];
861         int p1 = 0;
862         if(big) {
863             switch(order) {
864                 case 32: LPC1(32)
865                 case 31: LPC1(31)
866                 case 30: LPC1(30)
867                 case 29: LPC1(29)
868                 case 28: LPC1(28)
869                 case 27: LPC1(27)
870                 case 26: LPC1(26)
871                 case 25: LPC1(25)
872                 case 24: LPC1(24)
873                 case 23: LPC1(23)
874                 case 22: LPC1(22)
875                 case 21: LPC1(21)
876                 case 20: LPC1(20)
877                 case 19: LPC1(19)
878                 case 18: LPC1(18)
879                 case 17: LPC1(17)
880                 case 16: LPC1(16)
881                 case 15: LPC1(15)
882                 case 14: LPC1(14)
883                 case 13: LPC1(13)
884                 case 12: LPC1(12)
885                 case 11: LPC1(11)
886                 case 10: LPC1(10)
887                 case  9: LPC1( 9)
888                          LPC1( 8)
889                          LPC1( 7)
890                          LPC1( 6)
891                          LPC1( 5)
892                          LPC1( 4)
893                          LPC1( 3)
894                          LPC1( 2)
895             }
896         } else {
897             switch(order) {
898                 case  8: LPC1( 8)
899                 case  7: LPC1( 7)
900                 case  6: LPC1( 6)
901                 case  5: LPC1( 5)
902                 case  4: LPC1( 4)
903                 case  3: LPC1( 3)
904                 case  2: LPC1( 2)
905             }
906         }
907         p1 += c * smp[i];
908         res[i  ] = smp[i  ] - (p0 >> shift);
909         res[i+1] = smp[i+1] - (p1 >> shift);
910     }
911 }
912
913 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
914                                 int order, const int32_t *coefs, int shift)
915 {
916     int i;
917     for(i=0; i<order; i++) {
918         res[i] = smp[i];
919     }
920 #ifdef CONFIG_SMALL
921     for(i=order; i<n; i+=2) {
922         int j;
923         int32_t c = coefs[0];
924         int32_t p0 = 0, p1 = c*smp[i];
925         for(j=1; j<order; j++) {
926             int32_t s = smp[i-j];
927             p0 += c*s;
928             c = coefs[j];
929             p1 += c*s;
930         }
931         p0 += c*smp[i-order];
932         res[i+0] = smp[i+0] - (p0 >> shift);
933         res[i+1] = smp[i+1] - (p1 >> shift);
934     }
935 #else
936     switch(order) {
937         case  1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
938         case  2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
939         case  3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
940         case  4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
941         case  5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
942         case  6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
943         case  7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
944         case  8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
945         default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
946     }
947 #endif
948 }
949
950 static int encode_residual(FlacEncodeContext *ctx, int ch)
951 {
952     int i, n;
953     int min_order, max_order, opt_order, precision, omethod;
954     int min_porder, max_porder;
955     FlacFrame *frame;
956     FlacSubframe *sub;
957     int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
958     int shift[MAX_LPC_ORDER];
959     int32_t *res, *smp;
960
961     frame = &ctx->frame;
962     sub = &frame->subframes[ch];
963     res = sub->residual;
964     smp = sub->samples;
965     n = frame->blocksize;
966
967     /* CONSTANT */
968     for(i=1; i<n; i++) {
969         if(smp[i] != smp[0]) break;
970     }
971     if(i == n) {
972         sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
973         res[0] = smp[0];
974         return sub->obits;
975     }
976
977     /* VERBATIM */
978     if(n < 5) {
979         sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
980         encode_residual_verbatim(res, smp, n);
981         return sub->obits * n;
982     }
983
984     min_order = ctx->options.min_prediction_order;
985     max_order = ctx->options.max_prediction_order;
986     min_porder = ctx->options.min_partition_order;
987     max_porder = ctx->options.max_partition_order;
988     precision = ctx->options.lpc_coeff_precision;
989     omethod = ctx->options.prediction_order_method;
990
991     /* FIXED */
992     if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
993         uint32_t bits[MAX_FIXED_ORDER+1];
994         if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
995         opt_order = 0;
996         bits[0] = UINT32_MAX;
997         for(i=min_order; i<=max_order; i++) {
998             encode_residual_fixed(res, smp, n, i);
999             bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
1000                                              n, i, sub->obits);
1001             if(bits[i] < bits[opt_order]) {
1002                 opt_order = i;
1003             }
1004         }
1005         sub->order = opt_order;
1006         sub->type = FLAC_SUBFRAME_FIXED;
1007         sub->type_code = sub->type | sub->order;
1008         if(sub->order != max_order) {
1009             encode_residual_fixed(res, smp, n, sub->order);
1010             return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
1011                                           sub->order, sub->obits);
1012         }
1013         return bits[sub->order];
1014     }
1015
1016     /* LPC */
1017     opt_order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
1018
1019     if(omethod == ORDER_METHOD_2LEVEL ||
1020        omethod == ORDER_METHOD_4LEVEL ||
1021        omethod == ORDER_METHOD_8LEVEL) {
1022         int levels = 1 << omethod;
1023         uint32_t bits[levels];
1024         int order;
1025         int opt_index = levels-1;
1026         opt_order = max_order-1;
1027         bits[opt_index] = UINT32_MAX;
1028         for(i=levels-1; i>=0; i--) {
1029             order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
1030             if(order < 0) order = 0;
1031             encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
1032             bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1033                                            res, n, order+1, sub->obits, precision);
1034             if(bits[i] < bits[opt_index]) {
1035                 opt_index = i;
1036                 opt_order = order;
1037             }
1038         }
1039         opt_order++;
1040     } else if(omethod == ORDER_METHOD_SEARCH) {
1041         // brute-force optimal order search
1042         uint32_t bits[MAX_LPC_ORDER];
1043         opt_order = 0;
1044         bits[0] = UINT32_MAX;
1045         for(i=min_order-1; i<max_order; i++) {
1046             encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
1047             bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1048                                            res, n, i+1, sub->obits, precision);
1049             if(bits[i] < bits[opt_order]) {
1050                 opt_order = i;
1051             }
1052         }
1053         opt_order++;
1054     } else if(omethod == ORDER_METHOD_LOG) {
1055         uint32_t bits[MAX_LPC_ORDER];
1056         int step;
1057
1058         opt_order= min_order - 1 + (max_order-min_order)/3;
1059         memset(bits, -1, sizeof(bits));
1060
1061         for(step=16 ;step; step>>=1){
1062             int last= opt_order;
1063             for(i=last-step; i<=last+step; i+= step){
1064                 if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
1065                     continue;
1066                 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
1067                 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1068                                             res, n, i+1, sub->obits, precision);
1069                 if(bits[i] < bits[opt_order])
1070                     opt_order= i;
1071             }
1072         }
1073         opt_order++;
1074     }
1075
1076     sub->order = opt_order;
1077     sub->type = FLAC_SUBFRAME_LPC;
1078     sub->type_code = sub->type | (sub->order-1);
1079     sub->shift = shift[sub->order-1];
1080     for(i=0; i<sub->order; i++) {
1081         sub->coefs[i] = coefs[sub->order-1][i];
1082     }
1083     encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
1084     return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
1085                                 sub->obits, precision);
1086 }
1087
1088 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
1089 {
1090     int i, n;
1091     FlacFrame *frame;
1092     FlacSubframe *sub;
1093     int32_t *res, *smp;
1094
1095     frame = &ctx->frame;
1096     sub = &frame->subframes[ch];
1097     res = sub->residual;
1098     smp = sub->samples;
1099     n = frame->blocksize;
1100
1101     /* CONSTANT */
1102     for(i=1; i<n; i++) {
1103         if(smp[i] != smp[0]) break;
1104     }
1105     if(i == n) {
1106         sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
1107         res[0] = smp[0];
1108         return sub->obits;
1109     }
1110
1111     /* VERBATIM */
1112     sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
1113     encode_residual_verbatim(res, smp, n);
1114     return sub->obits * n;
1115 }
1116
1117 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1118 {
1119     int i, best;
1120     int32_t lt, rt;
1121     uint64_t sum[4];
1122     uint64_t score[4];
1123     int k;
1124
1125     /* calculate sum of 2nd order residual for each channel */
1126     sum[0] = sum[1] = sum[2] = sum[3] = 0;
1127     for(i=2; i<n; i++) {
1128         lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1129         rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1130         sum[2] += FFABS((lt + rt) >> 1);
1131         sum[3] += FFABS(lt - rt);
1132         sum[0] += FFABS(lt);
1133         sum[1] += FFABS(rt);
1134     }
1135     /* estimate bit counts */
1136     for(i=0; i<4; i++) {
1137         k = find_optimal_param(2*sum[i], n);
1138         sum[i] = rice_encode_count(2*sum[i], n, k);
1139     }
1140
1141     /* calculate score for each mode */
1142     score[0] = sum[0] + sum[1];
1143     score[1] = sum[0] + sum[3];
1144     score[2] = sum[1] + sum[3];
1145     score[3] = sum[2] + sum[3];
1146
1147     /* return mode with lowest score */
1148     best = 0;
1149     for(i=1; i<4; i++) {
1150         if(score[i] < score[best]) {
1151             best = i;
1152         }
1153     }
1154     if(best == 0) {
1155         return FLAC_CHMODE_LEFT_RIGHT;
1156     } else if(best == 1) {
1157         return FLAC_CHMODE_LEFT_SIDE;
1158     } else if(best == 2) {
1159         return FLAC_CHMODE_RIGHT_SIDE;
1160     } else {
1161         return FLAC_CHMODE_MID_SIDE;
1162     }
1163 }
1164
1165 /**
1166  * Perform stereo channel decorrelation
1167  */
1168 static void channel_decorrelation(FlacEncodeContext *ctx)
1169 {
1170     FlacFrame *frame;
1171     int32_t *left, *right;
1172     int i, n;
1173
1174     frame = &ctx->frame;
1175     n = frame->blocksize;
1176     left  = frame->subframes[0].samples;
1177     right = frame->subframes[1].samples;
1178
1179     if(ctx->channels != 2) {
1180         frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1181         return;
1182     }
1183
1184     frame->ch_mode = estimate_stereo_mode(left, right, n);
1185
1186     /* perform decorrelation and adjust bits-per-sample */
1187     if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1188         return;
1189     }
1190     if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1191         int32_t tmp;
1192         for(i=0; i<n; i++) {
1193             tmp = left[i];
1194             left[i] = (tmp + right[i]) >> 1;
1195             right[i] = tmp - right[i];
1196         }
1197         frame->subframes[1].obits++;
1198     } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1199         for(i=0; i<n; i++) {
1200             right[i] = left[i] - right[i];
1201         }
1202         frame->subframes[1].obits++;
1203     } else {
1204         for(i=0; i<n; i++) {
1205             left[i] -= right[i];
1206         }
1207         frame->subframes[0].obits++;
1208     }
1209 }
1210
1211 static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1212 {
1213     assert(bits >= 0 && bits <= 31);
1214
1215     put_bits(pb, bits, val & ((1<<bits)-1));
1216 }
1217
1218 static void write_utf8(PutBitContext *pb, uint32_t val)
1219 {
1220     uint8_t tmp;
1221     PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1222 }
1223
1224 static void output_frame_header(FlacEncodeContext *s)
1225 {
1226     FlacFrame *frame;
1227     int crc;
1228
1229     frame = &s->frame;
1230
1231     put_bits(&s->pb, 16, 0xFFF8);
1232     put_bits(&s->pb, 4, frame->bs_code[0]);
1233     put_bits(&s->pb, 4, s->sr_code[0]);
1234     if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1235         put_bits(&s->pb, 4, s->ch_code);
1236     } else {
1237         put_bits(&s->pb, 4, frame->ch_mode);
1238     }
1239     put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1240     put_bits(&s->pb, 1, 0);
1241     write_utf8(&s->pb, s->frame_count);
1242     if(frame->bs_code[0] == 6) {
1243         put_bits(&s->pb, 8, frame->bs_code[1]);
1244     } else if(frame->bs_code[0] == 7) {
1245         put_bits(&s->pb, 16, frame->bs_code[1]);
1246     }
1247     if(s->sr_code[0] == 12) {
1248         put_bits(&s->pb, 8, s->sr_code[1]);
1249     } else if(s->sr_code[0] > 12) {
1250         put_bits(&s->pb, 16, s->sr_code[1]);
1251     }
1252     flush_put_bits(&s->pb);
1253     crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1254     put_bits(&s->pb, 8, crc);
1255 }
1256
1257 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1258 {
1259     FlacSubframe *sub;
1260     int32_t res;
1261
1262     sub = &s->frame.subframes[ch];
1263     res = sub->residual[0];
1264     put_sbits(&s->pb, sub->obits, res);
1265 }
1266
1267 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1268 {
1269     int i;
1270     FlacFrame *frame;
1271     FlacSubframe *sub;
1272     int32_t res;
1273
1274     frame = &s->frame;
1275     sub = &frame->subframes[ch];
1276
1277     for(i=0; i<frame->blocksize; i++) {
1278         res = sub->residual[i];
1279         put_sbits(&s->pb, sub->obits, res);
1280     }
1281 }
1282
1283 static void output_residual(FlacEncodeContext *ctx, int ch)
1284 {
1285     int i, j, p, n, parts;
1286     int k, porder, psize, res_cnt;
1287     FlacFrame *frame;
1288     FlacSubframe *sub;
1289     int32_t *res;
1290
1291     frame = &ctx->frame;
1292     sub = &frame->subframes[ch];
1293     res = sub->residual;
1294     n = frame->blocksize;
1295
1296     /* rice-encoded block */
1297     put_bits(&ctx->pb, 2, 0);
1298
1299     /* partition order */
1300     porder = sub->rc.porder;
1301     psize = n >> porder;
1302     parts = (1 << porder);
1303     put_bits(&ctx->pb, 4, porder);
1304     res_cnt = psize - sub->order;
1305
1306     /* residual */
1307     j = sub->order;
1308     for(p=0; p<parts; p++) {
1309         k = sub->rc.params[p];
1310         put_bits(&ctx->pb, 4, k);
1311         if(p == 1) res_cnt = psize;
1312         for(i=0; i<res_cnt && j<n; i++, j++) {
1313             set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1314         }
1315     }
1316 }
1317
1318 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1319 {
1320     int i;
1321     FlacFrame *frame;
1322     FlacSubframe *sub;
1323
1324     frame = &ctx->frame;
1325     sub = &frame->subframes[ch];
1326
1327     /* warm-up samples */
1328     for(i=0; i<sub->order; i++) {
1329         put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1330     }
1331
1332     /* residual */
1333     output_residual(ctx, ch);
1334 }
1335
1336 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1337 {
1338     int i, cbits;
1339     FlacFrame *frame;
1340     FlacSubframe *sub;
1341
1342     frame = &ctx->frame;
1343     sub = &frame->subframes[ch];
1344
1345     /* warm-up samples */
1346     for(i=0; i<sub->order; i++) {
1347         put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1348     }
1349
1350     /* LPC coefficients */
1351     cbits = ctx->options.lpc_coeff_precision;
1352     put_bits(&ctx->pb, 4, cbits-1);
1353     put_sbits(&ctx->pb, 5, sub->shift);
1354     for(i=0; i<sub->order; i++) {
1355         put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1356     }
1357
1358     /* residual */
1359     output_residual(ctx, ch);
1360 }
1361
1362 static void output_subframes(FlacEncodeContext *s)
1363 {
1364     FlacFrame *frame;
1365     FlacSubframe *sub;
1366     int ch;
1367
1368     frame = &s->frame;
1369
1370     for(ch=0; ch<s->channels; ch++) {
1371         sub = &frame->subframes[ch];
1372
1373         /* subframe header */
1374         put_bits(&s->pb, 1, 0);
1375         put_bits(&s->pb, 6, sub->type_code);
1376         put_bits(&s->pb, 1, 0); /* no wasted bits */
1377
1378         /* subframe */
1379         if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1380             output_subframe_constant(s, ch);
1381         } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1382             output_subframe_verbatim(s, ch);
1383         } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1384             output_subframe_fixed(s, ch);
1385         } else if(sub->type == FLAC_SUBFRAME_LPC) {
1386             output_subframe_lpc(s, ch);
1387         }
1388     }
1389 }
1390
1391 static void output_frame_footer(FlacEncodeContext *s)
1392 {
1393     int crc;
1394     flush_put_bits(&s->pb);
1395     crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1396     put_bits(&s->pb, 16, crc);
1397     flush_put_bits(&s->pb);
1398 }
1399
1400 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1401                              int buf_size, void *data)
1402 {
1403     int ch;
1404     FlacEncodeContext *s;
1405     int16_t *samples = data;
1406     int out_bytes;
1407
1408     s = avctx->priv_data;
1409
1410     s->blocksize = avctx->frame_size;
1411     init_frame(s);
1412
1413     copy_samples(s, samples);
1414
1415     channel_decorrelation(s);
1416
1417     for(ch=0; ch<s->channels; ch++) {
1418         encode_residual(s, ch);
1419     }
1420     init_put_bits(&s->pb, frame, buf_size);
1421     output_frame_header(s);
1422     output_subframes(s);
1423     output_frame_footer(s);
1424     out_bytes = put_bits_count(&s->pb) >> 3;
1425
1426     if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1427         /* frame too large. use verbatim mode */
1428         for(ch=0; ch<s->channels; ch++) {
1429             encode_residual_v(s, ch);
1430         }
1431         init_put_bits(&s->pb, frame, buf_size);
1432         output_frame_header(s);
1433         output_subframes(s);
1434         output_frame_footer(s);
1435         out_bytes = put_bits_count(&s->pb) >> 3;
1436
1437         if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1438             /* still too large. must be an error. */
1439             av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1440             return -1;
1441         }
1442     }
1443
1444     s->frame_count++;
1445     return out_bytes;
1446 }
1447
1448 static int flac_encode_close(AVCodecContext *avctx)
1449 {
1450     av_freep(&avctx->extradata);
1451     avctx->extradata_size = 0;
1452     av_freep(&avctx->coded_frame);
1453     return 0;
1454 }
1455
1456 AVCodec flac_encoder = {
1457     "flac",
1458     CODEC_TYPE_AUDIO,
1459     CODEC_ID_FLAC,
1460     sizeof(FlacEncodeContext),
1461     flac_encode_init,
1462     flac_encode_frame,
1463     flac_encode_close,
1464     NULL,
1465     .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
1466 };