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