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