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/avassert.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/intmath.h"
25 #include "libavutil/md5.h"
26 #include "libavutil/opt.h"
37 #define FLAC_SUBFRAME_CONSTANT 0
38 #define FLAC_SUBFRAME_VERBATIM 1
39 #define FLAC_SUBFRAME_FIXED 8
40 #define FLAC_SUBFRAME_LPC 32
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
50 CODING_MODE_RICE2 = 5,
53 typedef struct CompressionOptions {
54 int compression_level;
56 enum FFLPCType lpc_type;
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;
67 typedef struct RiceContext {
68 enum CodingMode coding_mode;
70 int params[MAX_PARTITIONS];
73 typedef struct FlacSubframe {
79 int32_t coefs[MAX_LPC_ORDER];
82 int32_t samples[FLAC_MAX_BLOCKSIZE];
83 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
86 typedef struct FlacFrame {
87 FlacSubframe subframes[FLAC_MAX_CHANNELS];
95 typedef struct FlacEncodeContext {
105 int max_encoded_framesize;
106 uint32_t frame_count;
107 uint64_t sample_count;
110 CompressionOptions options;
111 AVCodecContext *avctx;
113 struct AVMD5 *md5ctx;
115 unsigned int md5_buffer_size;
117 FLACDSPContext flac_dsp;
122 * Write streaminfo metadata block to byte array.
124 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
128 memset(header, 0, FLAC_STREAMINFO_SIZE);
129 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
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);
143 memcpy(&header[18], s->md5sum, 16);
148 * Set blocksize based on samplerate.
149 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
151 static int select_blocksize(int samplerate, int block_time_ms)
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];
170 static av_cold void dprint_compression_options(FlacEncodeContext *s)
172 AVCodecContext *avctx = s->avctx;
173 CompressionOptions *opt = &s->options;
175 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
177 switch (opt->lpc_type) {
178 case FF_LPC_TYPE_NONE:
179 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
181 case FF_LPC_TYPE_FIXED:
182 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
184 case FF_LPC_TYPE_LEVINSON:
185 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
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");
193 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
194 opt->min_prediction_order, opt->max_prediction_order);
196 switch (opt->prediction_order_method) {
197 case ORDER_METHOD_EST:
198 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
200 case ORDER_METHOD_2LEVEL:
201 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
203 case ORDER_METHOD_4LEVEL:
204 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
206 case ORDER_METHOD_8LEVEL:
207 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
209 case ORDER_METHOD_SEARCH:
210 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
212 case ORDER_METHOD_LOG:
213 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
218 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
219 opt->min_partition_order, opt->max_partition_order);
221 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
223 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
224 opt->lpc_coeff_precision);
228 static av_cold int flac_encode_init(AVCodecContext *avctx)
230 int freq = avctx->sample_rate;
231 int channels = avctx->channels;
232 FlacEncodeContext *s = avctx->priv_data;
238 switch (avctx->sample_fmt) {
239 case AV_SAMPLE_FMT_S16:
240 avctx->bits_per_raw_sample = 16;
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;
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);
256 s->channels = channels;
258 /* find samplerate in table */
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];
269 /* if not in table, samplerate is non-standard */
271 if (freq % 1000 == 0 && freq < 255000) {
273 s->sr_code[1] = freq / 1000;
274 } else if (freq % 10 == 0 && freq < 655350) {
276 s->sr_code[1] = freq / 10;
277 } else if (freq < 65535) {
279 s->sr_code[1] = freq;
281 av_log(avctx, AV_LOG_ERROR, "%d Hz not supported\n", freq);
282 return AVERROR(EINVAL);
284 s->samplerate = freq;
287 /* set compression option defaults based on avctx->compression_level */
288 if (avctx->compression_level < 0)
289 s->options.compression_level = 5;
291 s->options.compression_level = avctx->compression_level;
293 level = s->options.compression_level;
295 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
296 s->options.compression_level);
297 return AVERROR(EINVAL);
300 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
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];
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];
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];
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);
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];
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);
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);
344 s->options.min_prediction_order = avctx->min_prediction_order;
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);
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);
361 s->options.max_prediction_order = avctx->max_prediction_order;
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);
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",
374 return AVERROR(EINVAL);
377 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
379 s->max_blocksize = s->avctx->frame_size;
381 /* set maximum encoded frame size in verbatim mode */
382 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
384 s->avctx->bits_per_raw_sample);
386 /* initialize MD5 context */
387 s->md5ctx = av_md5_alloc();
389 return AVERROR(ENOMEM);
390 av_md5_init(s->md5ctx);
392 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
394 return AVERROR(ENOMEM);
395 write_streaminfo(s, streaminfo);
396 avctx->extradata = streaminfo;
397 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
400 s->min_framesize = s->max_framesize;
402 #if FF_API_OLD_ENCODE_AUDIO
403 avctx->coded_frame = avcodec_alloc_frame();
404 if (!avctx->coded_frame)
405 return AVERROR(ENOMEM);
409 avctx->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
411 avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
412 avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
414 avctx->channel_layout != AV_CH_LAYOUT_5POINT0 &&
415 avctx->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
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");
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);
430 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
431 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
433 ff_dsputil_init(&s->dsp, avctx);
434 ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt,
435 avctx->bits_per_raw_sample);
437 dprint_compression_options(s);
443 static void init_frame(FlacEncodeContext *s, int nb_samples)
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;
459 frame->blocksize = nb_samples;
460 if (frame->blocksize <= 256) {
461 frame->bs_code[0] = 6;
462 frame->bs_code[1] = frame->blocksize-1;
464 frame->bs_code[0] = 7;
465 frame->bs_code[1] = frame->blocksize-1;
469 for (ch = 0; ch < s->channels; ch++) {
470 FlacSubframe *sub = &frame->subframes[ch];
473 sub->obits = s->avctx->bits_per_raw_sample;
476 sub->rc.coding_mode = CODING_MODE_RICE2;
478 sub->rc.coding_mode = CODING_MODE_RICE;
481 frame->verbatim_only = 0;
486 * Copy channel-interleaved input samples into separate subframes.
488 static void copy_samples(FlacEncodeContext *s, const void *samples)
492 int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
493 s->avctx->bits_per_raw_sample;
495 #define COPY_SAMPLES(bits) do { \
496 const int ## bits ## _t *samples0 = samples; \
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; \
503 if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
510 static uint64_t rice_count_exact(int32_t *res, int n, int k)
515 for (i = 0; i < n; i++) {
516 int32_t v = -2 * res[i] - 1;
518 count += (v >> k) + 1 + k;
524 static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
527 int p, porder, psize;
531 /* subframe header */
535 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
537 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
538 count += s->frame.blocksize * sub->obits;
540 /* warm-up samples */
541 count += pred_order * sub->obits;
543 /* LPC coefficients */
544 if (sub->type == FLAC_SUBFRAME_LPC)
545 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
547 /* rice-encoded block */
550 /* partition order */
551 porder = sub->rc.porder;
552 psize = s->frame.blocksize >> porder;
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);
563 part_end = FFMIN(s->frame.blocksize, part_end + psize);
571 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
574 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
576 static int find_optimal_param(uint64_t sum, int n, int max_param)
583 sum2 = sum - (n >> 1);
584 k = av_log2(av_clipl_int32(sum2 / n));
585 return FFMIN(k, max_param);
589 static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
590 uint64_t *sums, int n, int pred_order)
593 int k, cnt, part, max_param;
596 max_param = (1 << rc->coding_mode) - 2;
598 part = (1 << porder);
601 cnt = (n >> porder) - pred_order;
602 for (i = 0; i < part; i++) {
603 k = find_optimal_param(sums[i], cnt, max_param);
605 all_bits += rice_encode_count(sums[i], cnt, k);
615 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
616 uint64_t sums[][MAX_PARTITIONS])
620 uint32_t *res, *res_end;
622 /* sums for highest level */
624 res = &data[pred_order];
625 res_end = &data[n >> pmax];
626 for (i = 0; i < parts; i++) {
628 while (res < res_end)
631 res_end += n >> pmax;
633 /* sums for lower levels */
634 for (i = pmax - 1; i >= pmin; i--) {
636 for (j = 0; j < parts; j++)
637 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
642 static uint64_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
643 int32_t *data, int n, int pred_order)
646 uint64_t bits[MAX_PARTITION_ORDER+1];
650 uint64_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
652 av_assert1(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
653 av_assert1(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
654 av_assert1(pmin <= pmax);
656 tmp_rc.coding_mode = rc->coding_mode;
658 udata = av_malloc(n * sizeof(uint32_t));
659 for (i = 0; i < n; i++)
660 udata[i] = (2*data[i]) ^ (data[i]>>31);
662 calc_sums(pmin, pmax, udata, n, pred_order, sums);
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]) {
675 return bits[opt_porder];
679 static int get_max_p_order(int max_porder, int n, int order)
681 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
683 porder = FFMIN(porder, av_log2(n/order));
688 static uint64_t find_subframe_rice_params(FlacEncodeContext *s,
689 FlacSubframe *sub, int pred_order)
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);
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);
705 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
710 for (i = 0; i < order; i++)
714 for (i = order; i < n; 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];
724 a = smp[i+1] - smp[i ];
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];
734 a = smp[i+1] - smp[i ];
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];
747 a = smp[i+1] - smp[i ];
756 static int encode_residual_ch(FlacEncodeContext *s, int ch)
759 int min_order, max_order, opt_order, omethod;
762 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
763 int shift[MAX_LPC_ORDER];
767 sub = &frame->subframes[ch];
770 n = frame->blocksize;
773 for (i = 1; i < n; i++)
777 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
779 return subframe_count_exact(s, sub, 0);
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);
789 min_order = s->options.min_prediction_order;
790 max_order = s->options.max_prediction_order;
791 omethod = s->options.prediction_order_method;
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;
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])
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);
814 return subframe_count_exact(s, sub, sub->order);
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,
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];
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)
839 s->flac_dsp.lpc_encode(res, smp, n, order+1, coefs[order],
841 bits[i] = find_subframe_rice_params(s, sub, order+1);
842 if (bits[i] < bits[opt_index]) {
848 } else if (omethod == ORDER_METHOD_SEARCH) {
849 // brute-force optimal order search
850 uint64_t bits[MAX_LPC_ORDER];
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])
860 } else if (omethod == ORDER_METHOD_LOG) {
861 uint64_t bits[MAX_LPC_ORDER];
864 opt_order = min_order - 1 + (max_order-min_order)/3;
865 memset(bits, -1, sizeof(bits));
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)
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])
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];
887 s->flac_dsp.lpc_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
889 find_subframe_rice_params(s, sub, sub->order);
891 return subframe_count_exact(s, sub, sub->order);
895 static int count_frame_header(FlacEncodeContext *s)
897 uint8_t av_unused tmp;
903 <1> Blocking strategy
904 <4> Block size in inter-channel samples
906 <4> Channel assignment
907 <3> Sample size in bits
912 /* coded frame number */
913 PUT_UTF8(s->frame_count, tmp, count += 8;)
915 /* explicit block size */
916 if (s->frame.bs_code[0] == 6)
918 else if (s->frame.bs_code[0] == 7)
921 /* explicit sample rate */
922 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
924 /* frame header CRC-8 */
931 static int encode_frame(FlacEncodeContext *s)
936 count = count_frame_header(s);
938 for (ch = 0; ch < s->channels; ch++)
939 count += encode_residual_ch(s, ch);
941 count += (8 - (count & 7)) & 7; // byte alignment
942 count += 16; // CRC-16
951 static void remove_wasted_bits(FlacEncodeContext *s)
955 for (ch = 0; ch < s->channels; ch++) {
956 FlacSubframe *sub = &s->frame.subframes[ch];
959 for (i = 0; i < s->frame.blocksize; i++) {
960 v |= sub->samples[i];
968 for (i = 0; i < s->frame.blocksize; i++)
969 sub->samples[i] >>= v;
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;
983 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n,
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);
1000 sum[1] += FFABS(rt);
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);
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];
1014 /* return mode with lowest score */
1016 for (i = 1; i < 4; i++)
1017 if (score[i] < score[best])
1025 * Perform stereo channel decorrelation.
1027 static void channel_decorrelation(FlacEncodeContext *s)
1030 int32_t *left, *right;
1034 n = frame->blocksize;
1035 left = frame->subframes[0].samples;
1036 right = frame->subframes[1].samples;
1038 if (s->channels != 2) {
1039 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
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);
1047 frame->ch_mode = s->options.ch_mode;
1049 /* perform decorrelation and adjust bits-per-sample */
1050 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1052 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1054 for (i = 0; i < n; i++) {
1056 left[i] = (tmp + right[i]) >> 1;
1057 right[i] = tmp - right[i];
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++;
1065 for (i = 0; i < n; i++)
1066 left[i] -= right[i];
1067 frame->subframes[0].obits++;
1072 static void write_utf8(PutBitContext *pb, uint32_t val)
1075 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1079 static void write_frame_header(FlacEncodeContext *s)
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]);
1090 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1091 put_bits(&s->pb, 4, s->channels-1);
1093 put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
1095 put_bits(&s->pb, 3, s->bps_code);
1096 put_bits(&s->pb, 1, 0);
1097 write_utf8(&s->pb, s->frame_count);
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]);
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]);
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);
1116 static void write_subframes(FlacEncodeContext *s)
1120 for (ch = 0; ch < s->channels; ch++) {
1121 FlacSubframe *sub = &s->frame.subframes[ch];
1122 int i, p, porder, psize;
1124 int32_t *res = sub->residual;
1125 int32_t *frame_end = &sub->residual[s->frame.blocksize];
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);
1132 put_bits(&s->pb, sub->wasted, 1);
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++);
1141 /* warm-up samples */
1142 for (i = 0; i < sub->order; i++)
1143 put_sbits(&s->pb, sub->obits, *res++);
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]);
1154 /* rice-encoded block */
1155 put_bits(&s->pb, 2, sub->rc.coding_mode - 4);
1157 /* partition order */
1158 porder = sub->rc.porder;
1159 psize = s->frame.blocksize >> porder;
1160 put_bits(&s->pb, 4, porder);
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);
1176 static void write_frame_footer(FlacEncodeContext *s)
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);
1187 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1189 init_put_bits(&s->pb, avpkt->data, avpkt->size);
1190 write_frame_header(s);
1192 write_frame_footer(s);
1193 return put_bits_count(&s->pb) >> 3;
1197 static int update_md5_sum(FlacEncodeContext *s, const void *samples)
1200 int buf_size = s->frame.blocksize * s->channels *
1201 ((s->avctx->bits_per_raw_sample + 7) / 8);
1203 if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
1204 av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
1206 return AVERROR(ENOMEM);
1209 if (s->avctx->bits_per_raw_sample <= 16) {
1210 buf = (const uint8_t *)samples;
1212 s->dsp.bswap16_buf((uint16_t *)s->md5_buffer,
1213 (const uint16_t *)samples, buf_size / 2);
1214 buf = s->md5_buffer;
1218 const int32_t *samples0 = samples;
1219 uint8_t *tmp = s->md5_buffer;
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;
1227 buf = s->md5_buffer;
1229 av_md5_update(s->md5ctx, buf, buf_size);
1235 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1236 const AVFrame *frame, int *got_packet_ptr)
1238 FlacEncodeContext *s;
1239 int frame_bytes, out_bytes, ret;
1241 s = avctx->priv_data;
1243 /* when the last block is reached, update the header in extradata */
1245 s->max_framesize = s->max_encoded_framesize;
1246 av_md5_final(s->md5ctx, s->md5sum);
1247 write_streaminfo(s, avctx->extradata);
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,
1255 avctx->bits_per_raw_sample);
1258 init_frame(s, frame->nb_samples);
1260 copy_samples(s, frame->data[0]);
1262 channel_decorrelation(s);
1264 remove_wasted_bits(s);
1266 frame_bytes = encode_frame(s);
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");
1279 if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes)))
1282 out_bytes = write_frame(s, avpkt);
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");
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;
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;
1303 static av_cold int flac_encode_close(AVCodecContext *avctx)
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);
1311 av_freep(&avctx->extradata);
1312 avctx->extradata_size = 0;
1313 #if FF_API_OLD_ENCODE_AUDIO
1314 av_freep(&avctx->coded_frame);
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" },
1346 static const AVClass flac_encoder_class = {
1348 av_default_item_name,
1350 LIBAVUTIL_VERSION_INT,
1353 AVCodec ff_flac_encoder = {
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,
1364 AV_SAMPLE_FMT_NONE },
1365 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1366 .priv_class = &flac_encoder_class,