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