3 * Copyright (c) 2006 Justin Ruggles <justin.ruggles@gmail.com>
5 * This file is part of FFmpeg.
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.
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.
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
22 #include "libavutil/crc.h"
23 #include "libavutil/md5.h"
24 #include "libavutil/opt.h"
33 #define FLAC_SUBFRAME_CONSTANT 0
34 #define FLAC_SUBFRAME_VERBATIM 1
35 #define FLAC_SUBFRAME_FIXED 8
36 #define FLAC_SUBFRAME_LPC 32
38 #define MAX_FIXED_ORDER 4
39 #define MAX_PARTITION_ORDER 8
40 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
41 #define MAX_LPC_PRECISION 15
42 #define MAX_LPC_SHIFT 15
43 #define MAX_RICE_PARAM 14
45 typedef struct CompressionOptions {
46 int compression_level;
48 enum FFLPCType lpc_type;
50 int lpc_coeff_precision;
51 int min_prediction_order;
52 int max_prediction_order;
53 int prediction_order_method;
54 int min_partition_order;
55 int max_partition_order;
58 typedef struct RiceContext {
60 int params[MAX_PARTITIONS];
63 typedef struct FlacSubframe {
68 int32_t coefs[MAX_LPC_ORDER];
71 int32_t samples[FLAC_MAX_BLOCKSIZE];
72 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
75 typedef struct FlacFrame {
76 FlacSubframe subframes[FLAC_MAX_CHANNELS];
84 typedef struct FlacEncodeContext {
93 int max_encoded_framesize;
95 uint64_t sample_count;
98 CompressionOptions options;
99 AVCodecContext *avctx;
101 struct AVMD5 *md5ctx;
106 * Write streaminfo metadata block to byte array.
108 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
112 memset(header, 0, FLAC_STREAMINFO_SIZE);
113 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
115 /* streaminfo metadata block */
116 put_bits(&pb, 16, s->max_blocksize);
117 put_bits(&pb, 16, s->max_blocksize);
118 put_bits(&pb, 24, s->min_framesize);
119 put_bits(&pb, 24, s->max_framesize);
120 put_bits(&pb, 20, s->samplerate);
121 put_bits(&pb, 3, s->channels-1);
122 put_bits(&pb, 5, 15); /* bits per sample - 1 */
123 /* write 36-bit sample count in 2 put_bits() calls */
124 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
125 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
127 memcpy(&header[18], s->md5sum, 16);
132 * Set blocksize based on samplerate.
133 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
135 static int select_blocksize(int samplerate, int block_time_ms)
141 assert(samplerate > 0);
142 blocksize = ff_flac_blocksize_table[1];
143 target = (samplerate * block_time_ms) / 1000;
144 for (i = 0; i < 16; i++) {
145 if (target >= ff_flac_blocksize_table[i] &&
146 ff_flac_blocksize_table[i] > blocksize) {
147 blocksize = ff_flac_blocksize_table[i];
154 static av_cold void dprint_compression_options(FlacEncodeContext *s)
156 AVCodecContext *avctx = s->avctx;
157 CompressionOptions *opt = &s->options;
159 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
161 switch (opt->lpc_type) {
162 case FF_LPC_TYPE_NONE:
163 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
165 case FF_LPC_TYPE_FIXED:
166 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
168 case FF_LPC_TYPE_LEVINSON:
169 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
171 case FF_LPC_TYPE_CHOLESKY:
172 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
173 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
177 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
178 opt->min_prediction_order, opt->max_prediction_order);
180 switch (opt->prediction_order_method) {
181 case ORDER_METHOD_EST:
182 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
184 case ORDER_METHOD_2LEVEL:
185 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
187 case ORDER_METHOD_4LEVEL:
188 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
190 case ORDER_METHOD_8LEVEL:
191 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
193 case ORDER_METHOD_SEARCH:
194 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
196 case ORDER_METHOD_LOG:
197 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
202 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
203 opt->min_partition_order, opt->max_partition_order);
205 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
207 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
208 opt->lpc_coeff_precision);
212 static av_cold int flac_encode_init(AVCodecContext *avctx)
214 int freq = avctx->sample_rate;
215 int channels = avctx->channels;
216 FlacEncodeContext *s = avctx->priv_data;
222 if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
225 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
227 s->channels = channels;
229 /* find samplerate in table */
232 for (i = 4; i < 12; i++) {
233 if (freq == ff_flac_sample_rate_table[i]) {
234 s->samplerate = ff_flac_sample_rate_table[i];
240 /* if not in table, samplerate is non-standard */
242 if (freq % 1000 == 0 && freq < 255000) {
244 s->sr_code[1] = freq / 1000;
245 } else if (freq % 10 == 0 && freq < 655350) {
247 s->sr_code[1] = freq / 10;
248 } else if (freq < 65535) {
250 s->sr_code[1] = freq;
254 s->samplerate = freq;
257 /* set compression option defaults based on avctx->compression_level */
258 if (avctx->compression_level < 0)
259 s->options.compression_level = 5;
261 s->options.compression_level = avctx->compression_level;
263 level = s->options.compression_level;
265 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
266 s->options.compression_level);
270 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
272 if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
273 s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
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, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
277 FF_LPC_TYPE_LEVINSON})[level];
279 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
280 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
282 if (s->options.prediction_order_method < 0)
283 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
284 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
285 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
286 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
287 ORDER_METHOD_SEARCH})[level];
289 if (s->options.min_partition_order > s->options.max_partition_order) {
290 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
291 s->options.min_partition_order, s->options.max_partition_order);
292 return AVERROR(EINVAL);
294 if (s->options.min_partition_order < 0)
295 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
296 if (s->options.max_partition_order < 0)
297 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
299 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
300 s->options.min_prediction_order = 0;
301 } else if (avctx->min_prediction_order >= 0) {
302 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
303 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
304 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
305 avctx->min_prediction_order);
308 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
309 avctx->min_prediction_order > MAX_LPC_ORDER) {
310 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
311 avctx->min_prediction_order);
314 s->options.min_prediction_order = avctx->min_prediction_order;
316 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
317 s->options.max_prediction_order = 0;
318 } else if (avctx->max_prediction_order >= 0) {
319 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
320 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
321 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
322 avctx->max_prediction_order);
325 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
326 avctx->max_prediction_order > MAX_LPC_ORDER) {
327 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
328 avctx->max_prediction_order);
331 s->options.max_prediction_order = avctx->max_prediction_order;
333 if (s->options.max_prediction_order < s->options.min_prediction_order) {
334 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
335 s->options.min_prediction_order, s->options.max_prediction_order);
339 if (avctx->frame_size > 0) {
340 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
341 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
342 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
347 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
349 s->max_blocksize = s->avctx->frame_size;
351 /* set maximum encoded frame size in verbatim mode */
352 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
355 /* initialize MD5 context */
356 s->md5ctx = av_malloc(av_md5_size);
358 return AVERROR(ENOMEM);
359 av_md5_init(s->md5ctx);
361 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
363 return AVERROR(ENOMEM);
364 write_streaminfo(s, streaminfo);
365 avctx->extradata = streaminfo;
366 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
369 s->min_framesize = s->max_framesize;
371 #if FF_API_OLD_ENCODE_AUDIO
372 avctx->coded_frame = avcodec_alloc_frame();
373 if (!avctx->coded_frame)
374 return AVERROR(ENOMEM);
378 avctx->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
380 avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
381 avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
383 avctx->channel_layout != AV_CH_LAYOUT_5POINT0 &&
384 avctx->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
386 avctx->channel_layout != AV_CH_LAYOUT_5POINT1 &&
387 avctx->channel_layout != AV_CH_LAYOUT_5POINT1_BACK) {
388 if (avctx->channel_layout) {
389 av_log(avctx, AV_LOG_ERROR, "Channel layout not supported by Flac, "
390 "output stream will have incorrect "
391 "channel layout.\n");
393 av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The encoder "
394 "will use Flac channel layout for "
395 "%d channels.\n", channels);
399 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
400 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
402 dprint_compression_options(s);
408 static void init_frame(FlacEncodeContext *s, int nb_samples)
415 for (i = 0; i < 16; i++) {
416 if (nb_samples == ff_flac_blocksize_table[i]) {
417 frame->blocksize = ff_flac_blocksize_table[i];
418 frame->bs_code[0] = i;
419 frame->bs_code[1] = 0;
424 frame->blocksize = nb_samples;
425 if (frame->blocksize <= 256) {
426 frame->bs_code[0] = 6;
427 frame->bs_code[1] = frame->blocksize-1;
429 frame->bs_code[0] = 7;
430 frame->bs_code[1] = frame->blocksize-1;
434 for (ch = 0; ch < s->channels; ch++)
435 frame->subframes[ch].obits = 16;
437 frame->verbatim_only = 0;
442 * Copy channel-interleaved input samples into separate subframes.
444 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
450 for (i = 0, j = 0; i < frame->blocksize; i++)
451 for (ch = 0; ch < s->channels; ch++, j++)
452 frame->subframes[ch].samples[i] = samples[j];
456 static int rice_count_exact(int32_t *res, int n, int k)
461 for (i = 0; i < n; i++) {
462 int32_t v = -2 * res[i] - 1;
464 count += (v >> k) + 1 + k;
470 static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
473 int p, porder, psize;
477 /* subframe header */
481 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
483 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
484 count += s->frame.blocksize * sub->obits;
486 /* warm-up samples */
487 count += pred_order * sub->obits;
489 /* LPC coefficients */
490 if (sub->type == FLAC_SUBFRAME_LPC)
491 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
493 /* rice-encoded block */
496 /* partition order */
497 porder = sub->rc.porder;
498 psize = s->frame.blocksize >> porder;
504 for (p = 0; p < 1 << porder; p++) {
505 int k = sub->rc.params[p];
507 count += rice_count_exact(&sub->residual[i], part_end - i, k);
509 part_end = FFMIN(s->frame.blocksize, part_end + psize);
517 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
520 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
522 static int find_optimal_param(uint32_t sum, int n)
529 sum2 = sum - (n >> 1);
530 k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
531 return FFMIN(k, MAX_RICE_PARAM);
535 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
536 uint32_t *sums, int n, int pred_order)
542 part = (1 << porder);
545 cnt = (n >> porder) - pred_order;
546 for (i = 0; i < part; i++) {
547 k = find_optimal_param(sums[i], cnt);
549 all_bits += rice_encode_count(sums[i], cnt, k);
559 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
560 uint32_t sums[][MAX_PARTITIONS])
564 uint32_t *res, *res_end;
566 /* sums for highest level */
568 res = &data[pred_order];
569 res_end = &data[n >> pmax];
570 for (i = 0; i < parts; i++) {
572 while (res < res_end)
575 res_end += n >> pmax;
577 /* sums for lower levels */
578 for (i = pmax - 1; i >= pmin; i--) {
580 for (j = 0; j < parts; j++)
581 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
586 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
587 int32_t *data, int n, int pred_order)
590 uint32_t bits[MAX_PARTITION_ORDER+1];
594 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
596 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
597 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
598 assert(pmin <= pmax);
600 udata = av_malloc(n * sizeof(uint32_t));
601 for (i = 0; i < n; i++)
602 udata[i] = (2*data[i]) ^ (data[i]>>31);
604 calc_sums(pmin, pmax, udata, n, pred_order, sums);
607 bits[pmin] = UINT32_MAX;
608 for (i = pmin; i <= pmax; i++) {
609 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
610 if (bits[i] <= bits[opt_porder]) {
617 return bits[opt_porder];
621 static int get_max_p_order(int max_porder, int n, int order)
623 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
625 porder = FFMIN(porder, av_log2(n/order));
630 static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
631 FlacSubframe *sub, int pred_order)
633 int pmin = get_max_p_order(s->options.min_partition_order,
634 s->frame.blocksize, pred_order);
635 int pmax = get_max_p_order(s->options.max_partition_order,
636 s->frame.blocksize, pred_order);
638 uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
639 if (sub->type == FLAC_SUBFRAME_LPC)
640 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
641 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
642 s->frame.blocksize, pred_order);
647 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
652 for (i = 0; i < order; i++)
656 for (i = order; i < n; i++)
658 } else if (order == 1) {
659 for (i = order; i < n; i++)
660 res[i] = smp[i] - smp[i-1];
661 } else if (order == 2) {
662 int a = smp[order-1] - smp[order-2];
663 for (i = order; i < n; i += 2) {
664 int b = smp[i ] - smp[i-1];
666 a = smp[i+1] - smp[i ];
669 } else if (order == 3) {
670 int a = smp[order-1] - smp[order-2];
671 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
672 for (i = order; i < n; i += 2) {
673 int b = smp[i ] - smp[i-1];
676 a = smp[i+1] - smp[i ];
681 int a = smp[order-1] - smp[order-2];
682 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
683 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
684 for (i = order; i < n; i += 2) {
685 int b = smp[i ] - smp[i-1];
689 a = smp[i+1] - smp[i ];
699 int c = coefs[(x)-1];\
705 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
706 const int32_t *smp, int n, int order,
707 const int32_t *coefs, int shift, int big)
710 for (i = order; i < n; i += 2) {
711 int s = smp[i-order];
760 res[i ] = smp[i ] - (p0 >> shift);
761 res[i+1] = smp[i+1] - (p1 >> shift);
766 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
767 int order, const int32_t *coefs, int shift)
770 for (i = 0; i < order; i++)
773 for (i = order; i < n; i += 2) {
777 for (j = 0; j < order; j++) {
783 res[i ] = smp[i ] - (p0 >> shift);
784 res[i+1] = smp[i+1] - (p1 >> shift);
788 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
789 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
790 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
791 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
792 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
793 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
794 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
795 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
796 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
802 static int encode_residual_ch(FlacEncodeContext *s, int ch)
805 int min_order, max_order, opt_order, omethod;
808 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
809 int shift[MAX_LPC_ORDER];
813 sub = &frame->subframes[ch];
816 n = frame->blocksize;
819 for (i = 1; i < n; i++)
823 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
825 return subframe_count_exact(s, sub, 0);
829 if (frame->verbatim_only || n < 5) {
830 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
831 memcpy(res, smp, n * sizeof(int32_t));
832 return subframe_count_exact(s, sub, 0);
835 min_order = s->options.min_prediction_order;
836 max_order = s->options.max_prediction_order;
837 omethod = s->options.prediction_order_method;
840 sub->type = FLAC_SUBFRAME_FIXED;
841 if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
842 s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
843 uint32_t bits[MAX_FIXED_ORDER+1];
844 if (max_order > MAX_FIXED_ORDER)
845 max_order = MAX_FIXED_ORDER;
847 bits[0] = UINT32_MAX;
848 for (i = min_order; i <= max_order; i++) {
849 encode_residual_fixed(res, smp, n, i);
850 bits[i] = find_subframe_rice_params(s, sub, i);
851 if (bits[i] < bits[opt_order])
854 sub->order = opt_order;
855 sub->type_code = sub->type | sub->order;
856 if (sub->order != max_order) {
857 encode_residual_fixed(res, smp, n, sub->order);
858 find_subframe_rice_params(s, sub, sub->order);
860 return subframe_count_exact(s, sub, sub->order);
864 sub->type = FLAC_SUBFRAME_LPC;
865 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
866 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
867 s->options.lpc_passes, omethod,
870 if (omethod == ORDER_METHOD_2LEVEL ||
871 omethod == ORDER_METHOD_4LEVEL ||
872 omethod == ORDER_METHOD_8LEVEL) {
873 int levels = 1 << omethod;
874 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
876 int opt_index = levels-1;
877 opt_order = max_order-1;
878 bits[opt_index] = UINT32_MAX;
879 for (i = levels-1; i >= 0; i--) {
880 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
883 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
884 bits[i] = find_subframe_rice_params(s, sub, order+1);
885 if (bits[i] < bits[opt_index]) {
891 } else if (omethod == ORDER_METHOD_SEARCH) {
892 // brute-force optimal order search
893 uint32_t bits[MAX_LPC_ORDER];
895 bits[0] = UINT32_MAX;
896 for (i = min_order-1; i < max_order; i++) {
897 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
898 bits[i] = find_subframe_rice_params(s, sub, i+1);
899 if (bits[i] < bits[opt_order])
903 } else if (omethod == ORDER_METHOD_LOG) {
904 uint32_t bits[MAX_LPC_ORDER];
907 opt_order = min_order - 1 + (max_order-min_order)/3;
908 memset(bits, -1, sizeof(bits));
910 for (step = 16; step; step >>= 1) {
911 int last = opt_order;
912 for (i = last-step; i <= last+step; i += step) {
913 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
915 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
916 bits[i] = find_subframe_rice_params(s, sub, i+1);
917 if (bits[i] < bits[opt_order])
924 sub->order = opt_order;
925 sub->type_code = sub->type | (sub->order-1);
926 sub->shift = shift[sub->order-1];
927 for (i = 0; i < sub->order; i++)
928 sub->coefs[i] = coefs[sub->order-1][i];
930 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
932 find_subframe_rice_params(s, sub, sub->order);
934 return subframe_count_exact(s, sub, sub->order);
938 static int count_frame_header(FlacEncodeContext *s)
940 uint8_t av_unused tmp;
946 <1> Blocking strategy
947 <4> Block size in inter-channel samples
949 <4> Channel assignment
950 <3> Sample size in bits
955 /* coded frame number */
956 PUT_UTF8(s->frame_count, tmp, count += 8;)
958 /* explicit block size */
959 if (s->frame.bs_code[0] == 6)
961 else if (s->frame.bs_code[0] == 7)
964 /* explicit sample rate */
965 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
967 /* frame header CRC-8 */
974 static int encode_frame(FlacEncodeContext *s)
978 count = count_frame_header(s);
980 for (ch = 0; ch < s->channels; ch++)
981 count += encode_residual_ch(s, ch);
983 count += (8 - (count & 7)) & 7; // byte alignment
984 count += 16; // CRC-16
990 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
998 /* calculate sum of 2nd order residual for each channel */
999 sum[0] = sum[1] = sum[2] = sum[3] = 0;
1000 for (i = 2; i < n; i++) {
1001 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1002 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1003 sum[2] += FFABS((lt + rt) >> 1);
1004 sum[3] += FFABS(lt - rt);
1005 sum[0] += FFABS(lt);
1006 sum[1] += FFABS(rt);
1008 /* estimate bit counts */
1009 for (i = 0; i < 4; i++) {
1010 k = find_optimal_param(2 * sum[i], n);
1011 sum[i] = rice_encode_count( 2 * sum[i], n, k);
1014 /* calculate score for each mode */
1015 score[0] = sum[0] + sum[1];
1016 score[1] = sum[0] + sum[3];
1017 score[2] = sum[1] + sum[3];
1018 score[3] = sum[2] + sum[3];
1020 /* return mode with lowest score */
1022 for (i = 1; i < 4; i++)
1023 if (score[i] < score[best])
1026 return FLAC_CHMODE_INDEPENDENT;
1027 } else if (best == 1) {
1028 return FLAC_CHMODE_LEFT_SIDE;
1029 } else if (best == 2) {
1030 return FLAC_CHMODE_RIGHT_SIDE;
1032 return FLAC_CHMODE_MID_SIDE;
1038 * Perform stereo channel decorrelation.
1040 static void channel_decorrelation(FlacEncodeContext *s)
1043 int32_t *left, *right;
1047 n = frame->blocksize;
1048 left = frame->subframes[0].samples;
1049 right = frame->subframes[1].samples;
1051 if (s->channels != 2) {
1052 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1056 frame->ch_mode = estimate_stereo_mode(left, right, n);
1058 /* perform decorrelation and adjust bits-per-sample */
1059 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1061 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1063 for (i = 0; i < n; i++) {
1065 left[i] = (tmp + right[i]) >> 1;
1066 right[i] = tmp - right[i];
1068 frame->subframes[1].obits++;
1069 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1070 for (i = 0; i < n; i++)
1071 right[i] = left[i] - right[i];
1072 frame->subframes[1].obits++;
1074 for (i = 0; i < n; i++)
1075 left[i] -= right[i];
1076 frame->subframes[0].obits++;
1081 static void write_utf8(PutBitContext *pb, uint32_t val)
1084 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1088 static void write_frame_header(FlacEncodeContext *s)
1095 put_bits(&s->pb, 16, 0xFFF8);
1096 put_bits(&s->pb, 4, frame->bs_code[0]);
1097 put_bits(&s->pb, 4, s->sr_code[0]);
1099 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1100 put_bits(&s->pb, 4, s->channels-1);
1102 put_bits(&s->pb, 4, frame->ch_mode);
1104 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1105 put_bits(&s->pb, 1, 0);
1106 write_utf8(&s->pb, s->frame_count);
1108 if (frame->bs_code[0] == 6)
1109 put_bits(&s->pb, 8, frame->bs_code[1]);
1110 else if (frame->bs_code[0] == 7)
1111 put_bits(&s->pb, 16, frame->bs_code[1]);
1113 if (s->sr_code[0] == 12)
1114 put_bits(&s->pb, 8, s->sr_code[1]);
1115 else if (s->sr_code[0] > 12)
1116 put_bits(&s->pb, 16, s->sr_code[1]);
1118 flush_put_bits(&s->pb);
1119 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1120 put_bits_count(&s->pb) >> 3);
1121 put_bits(&s->pb, 8, crc);
1125 static void write_subframes(FlacEncodeContext *s)
1129 for (ch = 0; ch < s->channels; ch++) {
1130 FlacSubframe *sub = &s->frame.subframes[ch];
1131 int i, p, porder, psize;
1133 int32_t *res = sub->residual;
1134 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1136 /* subframe header */
1137 put_bits(&s->pb, 1, 0);
1138 put_bits(&s->pb, 6, sub->type_code);
1139 put_bits(&s->pb, 1, 0); /* no wasted bits */
1142 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1143 put_sbits(&s->pb, sub->obits, res[0]);
1144 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1145 while (res < frame_end)
1146 put_sbits(&s->pb, sub->obits, *res++);
1148 /* warm-up samples */
1149 for (i = 0; i < sub->order; i++)
1150 put_sbits(&s->pb, sub->obits, *res++);
1152 /* LPC coefficients */
1153 if (sub->type == FLAC_SUBFRAME_LPC) {
1154 int cbits = s->options.lpc_coeff_precision;
1155 put_bits( &s->pb, 4, cbits-1);
1156 put_sbits(&s->pb, 5, sub->shift);
1157 for (i = 0; i < sub->order; i++)
1158 put_sbits(&s->pb, cbits, sub->coefs[i]);
1161 /* rice-encoded block */
1162 put_bits(&s->pb, 2, 0);
1164 /* partition order */
1165 porder = sub->rc.porder;
1166 psize = s->frame.blocksize >> porder;
1167 put_bits(&s->pb, 4, porder);
1170 part_end = &sub->residual[psize];
1171 for (p = 0; p < 1 << porder; p++) {
1172 int k = sub->rc.params[p];
1173 put_bits(&s->pb, 4, k);
1174 while (res < part_end)
1175 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1176 part_end = FFMIN(frame_end, part_end + psize);
1183 static void write_frame_footer(FlacEncodeContext *s)
1186 flush_put_bits(&s->pb);
1187 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1188 put_bits_count(&s->pb)>>3));
1189 put_bits(&s->pb, 16, crc);
1190 flush_put_bits(&s->pb);
1194 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1196 init_put_bits(&s->pb, avpkt->data, avpkt->size);
1197 write_frame_header(s);
1199 write_frame_footer(s);
1200 return put_bits_count(&s->pb) >> 3;
1204 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1208 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1209 int16_t smp = av_le2ne16(samples[i]);
1210 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1213 av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1218 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1219 const AVFrame *frame, int *got_packet_ptr)
1221 FlacEncodeContext *s;
1222 const int16_t *samples;
1223 int frame_bytes, out_bytes, ret;
1225 s = avctx->priv_data;
1227 /* when the last block is reached, update the header in extradata */
1229 s->max_framesize = s->max_encoded_framesize;
1230 av_md5_final(s->md5ctx, s->md5sum);
1231 write_streaminfo(s, avctx->extradata);
1234 samples = (const int16_t *)frame->data[0];
1236 /* change max_framesize for small final frame */
1237 if (frame->nb_samples < s->frame.blocksize) {
1238 s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
1242 init_frame(s, frame->nb_samples);
1244 copy_samples(s, samples);
1246 channel_decorrelation(s);
1248 frame_bytes = encode_frame(s);
1250 /* fallback to verbatim mode if the compressed frame is larger than it
1251 would be if encoded uncompressed. */
1252 if (frame_bytes > s->max_framesize) {
1253 s->frame.verbatim_only = 1;
1254 frame_bytes = encode_frame(s);
1257 if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes)))
1260 out_bytes = write_frame(s, avpkt);
1263 s->sample_count += frame->nb_samples;
1264 update_md5_sum(s, samples);
1265 if (out_bytes > s->max_encoded_framesize)
1266 s->max_encoded_framesize = out_bytes;
1267 if (out_bytes < s->min_framesize)
1268 s->min_framesize = out_bytes;
1270 avpkt->pts = frame->pts;
1271 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1272 avpkt->size = out_bytes;
1273 *got_packet_ptr = 1;
1278 static av_cold int flac_encode_close(AVCodecContext *avctx)
1280 if (avctx->priv_data) {
1281 FlacEncodeContext *s = avctx->priv_data;
1282 av_freep(&s->md5ctx);
1283 ff_lpc_end(&s->lpc_ctx);
1285 av_freep(&avctx->extradata);
1286 avctx->extradata_size = 0;
1287 #if FF_API_OLD_ENCODE_AUDIO
1288 av_freep(&avctx->coded_frame);
1293 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1294 static const AVOption options[] = {
1295 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.dbl = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1296 { "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" },
1297 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1298 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1299 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1300 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1301 { "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 },
1302 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1303 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1304 { "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" },
1305 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1306 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1307 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1308 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1309 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1310 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1314 static const AVClass flac_encoder_class = {
1316 av_default_item_name,
1318 LIBAVUTIL_VERSION_INT,
1321 AVCodec ff_flac_encoder = {
1323 .type = AVMEDIA_TYPE_AUDIO,
1324 .id = CODEC_ID_FLAC,
1325 .priv_data_size = sizeof(FlacEncodeContext),
1326 .init = flac_encode_init,
1327 .encode2 = flac_encode_frame,
1328 .close = flac_encode_close,
1329 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY | CODEC_CAP_LOSSLESS,
1330 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1331 AV_SAMPLE_FMT_NONE },
1332 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1333 .priv_class = &flac_encoder_class,