3 * Copyright (c) 2006 Justin Ruggles <justin.ruggles@gmail.com>
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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/intmath.h"
24 #include "libavutil/md5.h"
25 #include "libavutil/opt.h"
36 #define FLAC_SUBFRAME_CONSTANT 0
37 #define FLAC_SUBFRAME_VERBATIM 1
38 #define FLAC_SUBFRAME_FIXED 8
39 #define FLAC_SUBFRAME_LPC 32
41 #define MAX_FIXED_ORDER 4
42 #define MAX_PARTITION_ORDER 8
43 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
44 #define MAX_LPC_PRECISION 15
45 #define MAX_LPC_SHIFT 15
49 CODING_MODE_RICE2 = 5,
52 typedef struct CompressionOptions {
53 int compression_level;
55 enum FFLPCType lpc_type;
57 int lpc_coeff_precision;
58 int min_prediction_order;
59 int max_prediction_order;
60 int prediction_order_method;
61 int min_partition_order;
62 int max_partition_order;
66 typedef struct RiceContext {
67 enum CodingMode coding_mode;
69 int params[MAX_PARTITIONS];
70 uint32_t udata[FLAC_MAX_BLOCKSIZE];
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;
116 BswapDSPContext bdsp;
117 FLACDSPContext flac_dsp;
125 * Write streaminfo metadata block to byte array.
127 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
131 memset(header, 0, FLAC_STREAMINFO_SIZE);
132 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
134 /* streaminfo metadata block */
135 put_bits(&pb, 16, s->max_blocksize);
136 put_bits(&pb, 16, s->max_blocksize);
137 put_bits(&pb, 24, s->min_framesize);
138 put_bits(&pb, 24, s->max_framesize);
139 put_bits(&pb, 20, s->samplerate);
140 put_bits(&pb, 3, s->channels-1);
141 put_bits(&pb, 5, s->avctx->bits_per_raw_sample - 1);
142 /* write 36-bit sample count in 2 put_bits() calls */
143 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
144 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
146 memcpy(&header[18], s->md5sum, 16);
151 * Set blocksize based on samplerate.
152 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
154 static int select_blocksize(int samplerate, int block_time_ms)
160 assert(samplerate > 0);
161 blocksize = ff_flac_blocksize_table[1];
162 target = (samplerate * block_time_ms) / 1000;
163 for (i = 0; i < 16; i++) {
164 if (target >= ff_flac_blocksize_table[i] &&
165 ff_flac_blocksize_table[i] > blocksize) {
166 blocksize = ff_flac_blocksize_table[i];
173 static av_cold void dprint_compression_options(FlacEncodeContext *s)
175 AVCodecContext *avctx = s->avctx;
176 CompressionOptions *opt = &s->options;
178 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
180 switch (opt->lpc_type) {
181 case FF_LPC_TYPE_NONE:
182 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
184 case FF_LPC_TYPE_FIXED:
185 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
187 case FF_LPC_TYPE_LEVINSON:
188 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
190 case FF_LPC_TYPE_CHOLESKY:
191 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
192 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
196 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
197 opt->min_prediction_order, opt->max_prediction_order);
199 switch (opt->prediction_order_method) {
200 case ORDER_METHOD_EST:
201 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
203 case ORDER_METHOD_2LEVEL:
204 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
206 case ORDER_METHOD_4LEVEL:
207 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
209 case ORDER_METHOD_8LEVEL:
210 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
212 case ORDER_METHOD_SEARCH:
213 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
215 case ORDER_METHOD_LOG:
216 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
221 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
222 opt->min_partition_order, opt->max_partition_order);
224 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
226 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
227 opt->lpc_coeff_precision);
231 static av_cold int flac_encode_init(AVCodecContext *avctx)
233 int freq = avctx->sample_rate;
234 int channels = avctx->channels;
235 FlacEncodeContext *s = avctx->priv_data;
241 switch (avctx->sample_fmt) {
242 case AV_SAMPLE_FMT_S16:
243 avctx->bits_per_raw_sample = 16;
246 case AV_SAMPLE_FMT_S32:
247 if (avctx->bits_per_raw_sample != 24)
248 av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
249 avctx->bits_per_raw_sample = 24;
254 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
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;
283 s->samplerate = freq;
286 /* set compression option defaults based on avctx->compression_level */
287 if (avctx->compression_level < 0)
288 s->options.compression_level = 5;
290 s->options.compression_level = avctx->compression_level;
292 level = s->options.compression_level;
294 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
295 s->options.compression_level);
299 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
301 if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
302 s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
303 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
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})[level];
308 if (s->options.min_prediction_order < 0)
309 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
310 if (s->options.max_prediction_order < 0)
311 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
313 if (s->options.prediction_order_method < 0)
314 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
315 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
316 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
317 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
318 ORDER_METHOD_SEARCH})[level];
320 if (s->options.min_partition_order > s->options.max_partition_order) {
321 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
322 s->options.min_partition_order, s->options.max_partition_order);
323 return AVERROR(EINVAL);
325 if (s->options.min_partition_order < 0)
326 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
327 if (s->options.max_partition_order < 0)
328 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
330 #if FF_API_PRIVATE_OPT
331 FF_DISABLE_DEPRECATION_WARNINGS
332 if (avctx->min_prediction_order >= 0) {
333 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
334 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
335 av_log(avctx, AV_LOG_WARNING,
336 "invalid min prediction order %d, clamped to %d\n",
337 avctx->min_prediction_order, MAX_FIXED_ORDER);
338 avctx->min_prediction_order = MAX_FIXED_ORDER;
340 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
341 avctx->min_prediction_order > MAX_LPC_ORDER) {
342 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
343 avctx->min_prediction_order);
346 s->options.min_prediction_order = avctx->min_prediction_order;
348 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_WARNING,
352 "invalid max prediction order %d, clamped to %d\n",
353 avctx->max_prediction_order, MAX_FIXED_ORDER);
354 avctx->max_prediction_order = MAX_FIXED_ORDER;
356 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
357 avctx->max_prediction_order > MAX_LPC_ORDER) {
358 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
359 avctx->max_prediction_order);
362 s->options.max_prediction_order = avctx->max_prediction_order;
364 FF_ENABLE_DEPRECATION_WARNINGS
366 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
367 s->options.min_prediction_order = 0;
368 s->options.max_prediction_order = 0;
369 } else if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
370 if (s->options.min_prediction_order > MAX_FIXED_ORDER) {
371 av_log(avctx, AV_LOG_WARNING,
372 "invalid min prediction order %d, clamped to %d\n",
373 s->options.min_prediction_order, MAX_FIXED_ORDER);
374 s->options.min_prediction_order = MAX_FIXED_ORDER;
376 if (s->options.max_prediction_order > MAX_FIXED_ORDER) {
377 av_log(avctx, AV_LOG_WARNING,
378 "invalid max prediction order %d, clamped to %d\n",
379 s->options.max_prediction_order, MAX_FIXED_ORDER);
380 s->options.max_prediction_order = MAX_FIXED_ORDER;
384 if (s->options.max_prediction_order < s->options.min_prediction_order) {
385 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
386 s->options.min_prediction_order, s->options.max_prediction_order);
390 if (avctx->frame_size > 0) {
391 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
392 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
393 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
398 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
400 s->max_blocksize = s->avctx->frame_size;
402 /* set maximum encoded frame size in verbatim mode */
403 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
405 s->avctx->bits_per_raw_sample);
407 /* initialize MD5 context */
408 s->md5ctx = av_md5_alloc();
410 return AVERROR(ENOMEM);
411 av_md5_init(s->md5ctx);
413 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
415 return AVERROR(ENOMEM);
416 write_streaminfo(s, streaminfo);
417 avctx->extradata = streaminfo;
418 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
421 s->min_framesize = s->max_framesize;
423 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
424 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
426 ff_bswapdsp_init(&s->bdsp);
427 ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt,
428 avctx->bits_per_raw_sample);
430 dprint_compression_options(s);
436 static void init_frame(FlacEncodeContext *s, int nb_samples)
443 for (i = 0; i < 16; i++) {
444 if (nb_samples == ff_flac_blocksize_table[i]) {
445 frame->blocksize = ff_flac_blocksize_table[i];
446 frame->bs_code[0] = i;
447 frame->bs_code[1] = 0;
452 frame->blocksize = nb_samples;
453 if (frame->blocksize <= 256) {
454 frame->bs_code[0] = 6;
455 frame->bs_code[1] = frame->blocksize-1;
457 frame->bs_code[0] = 7;
458 frame->bs_code[1] = frame->blocksize-1;
462 for (ch = 0; ch < s->channels; ch++) {
463 FlacSubframe *sub = &frame->subframes[ch];
466 sub->obits = s->avctx->bits_per_raw_sample;
469 sub->rc.coding_mode = CODING_MODE_RICE2;
471 sub->rc.coding_mode = CODING_MODE_RICE;
474 frame->verbatim_only = 0;
479 * Copy channel-interleaved input samples into separate subframes.
481 static void copy_samples(FlacEncodeContext *s, const void *samples)
485 int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
486 s->avctx->bits_per_raw_sample;
488 #define COPY_SAMPLES(bits) do { \
489 const int ## bits ## _t *samples0 = samples; \
491 for (i = 0, j = 0; i < frame->blocksize; i++) \
492 for (ch = 0; ch < s->channels; ch++, j++) \
493 frame->subframes[ch].samples[i] = samples0[j] >> shift; \
496 if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
503 static uint64_t rice_count_exact(int32_t *res, int n, int k)
508 for (i = 0; i < n; i++) {
509 int32_t v = -2 * res[i] - 1;
511 count += (v >> k) + 1 + k;
517 static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
520 int p, porder, psize;
524 /* subframe header */
528 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
530 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
531 count += s->frame.blocksize * sub->obits;
533 /* warm-up samples */
534 count += pred_order * sub->obits;
536 /* LPC coefficients */
537 if (sub->type == FLAC_SUBFRAME_LPC)
538 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
540 /* rice-encoded block */
543 /* partition order */
544 porder = sub->rc.porder;
545 psize = s->frame.blocksize >> porder;
551 for (p = 0; p < 1 << porder; p++) {
552 int k = sub->rc.params[p];
553 count += sub->rc.coding_mode;
554 count += rice_count_exact(&sub->residual[i], part_end - i, k);
556 part_end = FFMIN(s->frame.blocksize, part_end + psize);
564 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
567 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
569 static int find_optimal_param(uint64_t sum, int n, int max_param)
576 sum2 = sum - (n >> 1);
577 k = av_log2(av_clipl_int32(sum2 / n));
578 return FFMIN(k, max_param);
582 static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
583 uint64_t *sums, int n, int pred_order)
586 int k, cnt, part, max_param;
589 max_param = (1 << rc->coding_mode) - 2;
591 part = (1 << porder);
594 cnt = (n >> porder) - pred_order;
595 for (i = 0; i < part; i++) {
596 k = find_optimal_param(sums[i], cnt, max_param);
598 all_bits += rice_encode_count(sums[i], cnt, k);
608 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
609 uint64_t sums[][MAX_PARTITIONS])
613 uint32_t *res, *res_end;
615 /* sums for highest level */
617 res = &data[pred_order];
618 res_end = &data[n >> pmax];
619 for (i = 0; i < parts; i++) {
621 while (res < res_end)
624 res_end += n >> pmax;
626 /* sums for lower levels */
627 for (i = pmax - 1; i >= pmin; i--) {
629 for (j = 0; j < parts; j++)
630 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
635 static uint64_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
636 int32_t *data, int n, int pred_order)
639 uint64_t bits[MAX_PARTITION_ORDER+1];
642 uint64_t sums[MAX_PARTITION_ORDER + 1][MAX_PARTITIONS] = { { 0 } };
644 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
645 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
646 assert(pmin <= pmax);
648 tmp_rc.coding_mode = rc->coding_mode;
650 for (i = 0; i < n; i++)
651 rc->udata[i] = (2 * data[i]) ^ (data[i] >> 31);
653 calc_sums(pmin, pmax, rc->udata, n, pred_order, sums);
656 bits[pmin] = UINT32_MAX;
657 for (i = pmin; i <= pmax; i++) {
658 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
659 if (bits[i] <= bits[opt_porder]) {
665 return bits[opt_porder];
669 static int get_max_p_order(int max_porder, int n, int order)
671 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
673 porder = FFMIN(porder, av_log2(n/order));
678 static uint64_t find_subframe_rice_params(FlacEncodeContext *s,
679 FlacSubframe *sub, int pred_order)
681 int pmin = get_max_p_order(s->options.min_partition_order,
682 s->frame.blocksize, pred_order);
683 int pmax = get_max_p_order(s->options.max_partition_order,
684 s->frame.blocksize, pred_order);
686 uint64_t bits = 8 + pred_order * sub->obits + 2 + sub->rc.coding_mode;
687 if (sub->type == FLAC_SUBFRAME_LPC)
688 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
689 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
690 s->frame.blocksize, pred_order);
695 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
700 for (i = 0; i < order; i++)
704 for (i = order; i < n; i++)
706 } else if (order == 1) {
707 for (i = order; i < n; i++)
708 res[i] = smp[i] - smp[i-1];
709 } else if (order == 2) {
710 int a = smp[order-1] - smp[order-2];
711 for (i = order; i < n; i += 2) {
712 int b = smp[i ] - smp[i-1];
714 a = smp[i+1] - smp[i ];
717 } else if (order == 3) {
718 int a = smp[order-1] - smp[order-2];
719 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
720 for (i = order; i < n; i += 2) {
721 int b = smp[i ] - smp[i-1];
724 a = smp[i+1] - smp[i ];
729 int a = smp[order-1] - smp[order-2];
730 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
731 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
732 for (i = order; i < n; i += 2) {
733 int b = smp[i ] - smp[i-1];
737 a = smp[i+1] - smp[i ];
746 static int encode_residual_ch(FlacEncodeContext *s, int ch)
749 int min_order, max_order, opt_order, omethod;
752 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
753 int shift[MAX_LPC_ORDER];
757 sub = &frame->subframes[ch];
760 n = frame->blocksize;
763 for (i = 1; i < n; i++)
767 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
769 return subframe_count_exact(s, sub, 0);
773 if (frame->verbatim_only || n < 5) {
774 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
775 memcpy(res, smp, n * sizeof(int32_t));
776 return subframe_count_exact(s, sub, 0);
779 min_order = s->options.min_prediction_order;
780 max_order = s->options.max_prediction_order;
781 omethod = s->options.prediction_order_method;
784 sub->type = FLAC_SUBFRAME_FIXED;
785 if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
786 s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
787 uint64_t bits[MAX_FIXED_ORDER+1];
788 if (max_order > MAX_FIXED_ORDER)
789 max_order = MAX_FIXED_ORDER;
791 bits[0] = UINT32_MAX;
792 for (i = min_order; i <= max_order; i++) {
793 encode_residual_fixed(res, smp, n, i);
794 bits[i] = find_subframe_rice_params(s, sub, i);
795 if (bits[i] < bits[opt_order])
798 sub->order = opt_order;
799 sub->type_code = sub->type | sub->order;
800 if (sub->order != max_order) {
801 encode_residual_fixed(res, smp, n, sub->order);
802 find_subframe_rice_params(s, sub, sub->order);
804 return subframe_count_exact(s, sub, sub->order);
808 sub->type = FLAC_SUBFRAME_LPC;
809 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
810 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
811 s->options.lpc_passes, omethod,
814 if (omethod == ORDER_METHOD_2LEVEL ||
815 omethod == ORDER_METHOD_4LEVEL ||
816 omethod == ORDER_METHOD_8LEVEL) {
817 int levels = 1 << omethod;
818 uint64_t bits[1 << ORDER_METHOD_8LEVEL];
820 int opt_index = levels-1;
821 opt_order = max_order-1;
822 bits[opt_index] = UINT32_MAX;
823 for (i = levels-1; i >= 0; i--) {
824 int last_order = order;
825 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
826 order = av_clip(order, min_order - 1, max_order - 1);
827 if (order == last_order)
829 s->flac_dsp.lpc_encode(res, smp, n, order+1, coefs[order],
831 bits[i] = find_subframe_rice_params(s, sub, order+1);
832 if (bits[i] < bits[opt_index]) {
838 } else if (omethod == ORDER_METHOD_SEARCH) {
839 // brute-force optimal order search
840 uint64_t bits[MAX_LPC_ORDER];
842 bits[0] = UINT32_MAX;
843 for (i = min_order-1; i < max_order; i++) {
844 s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
845 bits[i] = find_subframe_rice_params(s, sub, i+1);
846 if (bits[i] < bits[opt_order])
850 } else if (omethod == ORDER_METHOD_LOG) {
851 uint64_t bits[MAX_LPC_ORDER];
854 opt_order = min_order - 1 + (max_order-min_order)/3;
855 memset(bits, -1, sizeof(bits));
857 for (step = 16; step; step >>= 1) {
858 int last = opt_order;
859 for (i = last-step; i <= last+step; i += step) {
860 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
862 s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
863 bits[i] = find_subframe_rice_params(s, sub, i+1);
864 if (bits[i] < bits[opt_order])
871 sub->order = opt_order;
872 sub->type_code = sub->type | (sub->order-1);
873 sub->shift = shift[sub->order-1];
874 for (i = 0; i < sub->order; i++)
875 sub->coefs[i] = coefs[sub->order-1][i];
877 s->flac_dsp.lpc_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
879 find_subframe_rice_params(s, sub, sub->order);
881 return subframe_count_exact(s, sub, sub->order);
885 static int count_frame_header(FlacEncodeContext *s)
887 uint8_t av_unused tmp;
893 <1> Blocking strategy
894 <4> Block size in inter-channel samples
896 <4> Channel assignment
897 <3> Sample size in bits
902 /* coded frame number */
903 PUT_UTF8(s->frame_count, tmp, count += 8;)
905 /* explicit block size */
906 if (s->frame.bs_code[0] == 6)
908 else if (s->frame.bs_code[0] == 7)
911 /* explicit sample rate */
912 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
914 /* frame header CRC-8 */
921 static int encode_frame(FlacEncodeContext *s)
926 count = count_frame_header(s);
928 for (ch = 0; ch < s->channels; ch++)
929 count += encode_residual_ch(s, ch);
931 count += (8 - (count & 7)) & 7; // byte alignment
932 count += 16; // CRC-16
941 static void remove_wasted_bits(FlacEncodeContext *s)
945 for (ch = 0; ch < s->channels; ch++) {
946 FlacSubframe *sub = &s->frame.subframes[ch];
949 for (i = 0; i < s->frame.blocksize; i++) {
950 v |= sub->samples[i];
958 for (i = 0; i < s->frame.blocksize; i++)
959 sub->samples[i] >>= v;
964 /* for 24-bit, check if removing wasted bits makes the range better
965 suited for using RICE instead of RICE2 for entropy coding */
966 if (sub->obits <= 17)
967 sub->rc.coding_mode = CODING_MODE_RICE;
973 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n,
982 /* calculate sum of 2nd order residual for each channel */
983 sum[0] = sum[1] = sum[2] = sum[3] = 0;
984 for (i = 2; i < n; i++) {
985 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
986 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
987 sum[2] += FFABS((lt + rt) >> 1);
988 sum[3] += FFABS(lt - rt);
992 /* estimate bit counts */
993 for (i = 0; i < 4; i++) {
994 k = find_optimal_param(2 * sum[i], n, max_rice_param);
995 sum[i] = rice_encode_count( 2 * sum[i], n, k);
998 /* calculate score for each mode */
999 score[0] = sum[0] + sum[1];
1000 score[1] = sum[0] + sum[3];
1001 score[2] = sum[1] + sum[3];
1002 score[3] = sum[2] + sum[3];
1004 /* return mode with lowest score */
1006 for (i = 1; i < 4; i++)
1007 if (score[i] < score[best])
1015 * Perform stereo channel decorrelation.
1017 static void channel_decorrelation(FlacEncodeContext *s)
1020 int32_t *left, *right;
1024 n = frame->blocksize;
1025 left = frame->subframes[0].samples;
1026 right = frame->subframes[1].samples;
1028 if (s->channels != 2) {
1029 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1033 if (s->options.ch_mode < 0) {
1034 int max_rice_param = (1 << frame->subframes[0].rc.coding_mode) - 2;
1035 frame->ch_mode = estimate_stereo_mode(left, right, n, max_rice_param);
1037 frame->ch_mode = s->options.ch_mode;
1039 /* perform decorrelation and adjust bits-per-sample */
1040 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1042 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1044 for (i = 0; i < n; i++) {
1046 left[i] = (tmp + right[i]) >> 1;
1047 right[i] = tmp - right[i];
1049 frame->subframes[1].obits++;
1050 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1051 for (i = 0; i < n; i++)
1052 right[i] = left[i] - right[i];
1053 frame->subframes[1].obits++;
1055 for (i = 0; i < n; i++)
1056 left[i] -= right[i];
1057 frame->subframes[0].obits++;
1062 static void write_utf8(PutBitContext *pb, uint32_t val)
1065 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1069 static void write_frame_header(FlacEncodeContext *s)
1076 put_bits(&s->pb, 16, 0xFFF8);
1077 put_bits(&s->pb, 4, frame->bs_code[0]);
1078 put_bits(&s->pb, 4, s->sr_code[0]);
1080 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1081 put_bits(&s->pb, 4, s->channels-1);
1083 put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
1085 put_bits(&s->pb, 3, s->bps_code);
1086 put_bits(&s->pb, 1, 0);
1087 write_utf8(&s->pb, s->frame_count);
1089 if (frame->bs_code[0] == 6)
1090 put_bits(&s->pb, 8, frame->bs_code[1]);
1091 else if (frame->bs_code[0] == 7)
1092 put_bits(&s->pb, 16, frame->bs_code[1]);
1094 if (s->sr_code[0] == 12)
1095 put_bits(&s->pb, 8, s->sr_code[1]);
1096 else if (s->sr_code[0] > 12)
1097 put_bits(&s->pb, 16, s->sr_code[1]);
1099 flush_put_bits(&s->pb);
1100 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1101 put_bits_count(&s->pb) >> 3);
1102 put_bits(&s->pb, 8, crc);
1106 static void write_subframes(FlacEncodeContext *s)
1110 for (ch = 0; ch < s->channels; ch++) {
1111 FlacSubframe *sub = &s->frame.subframes[ch];
1112 int i, p, porder, psize;
1114 int32_t *res = sub->residual;
1115 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1117 /* subframe header */
1118 put_bits(&s->pb, 1, 0);
1119 put_bits(&s->pb, 6, sub->type_code);
1120 put_bits(&s->pb, 1, !!sub->wasted);
1122 put_bits(&s->pb, sub->wasted, 1);
1125 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1126 put_sbits(&s->pb, sub->obits, res[0]);
1127 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1128 while (res < frame_end)
1129 put_sbits(&s->pb, sub->obits, *res++);
1131 /* warm-up samples */
1132 for (i = 0; i < sub->order; i++)
1133 put_sbits(&s->pb, sub->obits, *res++);
1135 /* LPC coefficients */
1136 if (sub->type == FLAC_SUBFRAME_LPC) {
1137 int cbits = s->options.lpc_coeff_precision;
1138 put_bits( &s->pb, 4, cbits-1);
1139 put_sbits(&s->pb, 5, sub->shift);
1140 for (i = 0; i < sub->order; i++)
1141 put_sbits(&s->pb, cbits, sub->coefs[i]);
1144 /* rice-encoded block */
1145 put_bits(&s->pb, 2, sub->rc.coding_mode - 4);
1147 /* partition order */
1148 porder = sub->rc.porder;
1149 psize = s->frame.blocksize >> porder;
1150 put_bits(&s->pb, 4, porder);
1153 part_end = &sub->residual[psize];
1154 for (p = 0; p < 1 << porder; p++) {
1155 int k = sub->rc.params[p];
1156 put_bits(&s->pb, sub->rc.coding_mode, k);
1157 while (res < part_end)
1158 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1159 part_end = FFMIN(frame_end, part_end + psize);
1166 static void write_frame_footer(FlacEncodeContext *s)
1169 flush_put_bits(&s->pb);
1170 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1171 put_bits_count(&s->pb)>>3));
1172 put_bits(&s->pb, 16, crc);
1173 flush_put_bits(&s->pb);
1177 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1179 init_put_bits(&s->pb, avpkt->data, avpkt->size);
1180 write_frame_header(s);
1182 write_frame_footer(s);
1183 return put_bits_count(&s->pb) >> 3;
1187 static int update_md5_sum(FlacEncodeContext *s, const void *samples)
1190 int buf_size = s->frame.blocksize * s->channels *
1191 ((s->avctx->bits_per_raw_sample + 7) / 8);
1193 if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
1194 av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
1196 return AVERROR(ENOMEM);
1199 if (s->avctx->bits_per_raw_sample <= 16) {
1200 buf = (const uint8_t *)samples;
1202 s->bdsp.bswap16_buf((uint16_t *) s->md5_buffer,
1203 (const uint16_t *) samples, buf_size / 2);
1204 buf = s->md5_buffer;
1208 const int32_t *samples0 = samples;
1209 uint8_t *tmp = s->md5_buffer;
1211 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1212 int32_t v = samples0[i] >> 8;
1213 *tmp++ = (v ) & 0xFF;
1214 *tmp++ = (v >> 8) & 0xFF;
1215 *tmp++ = (v >> 16) & 0xFF;
1217 buf = s->md5_buffer;
1219 av_md5_update(s->md5ctx, buf, buf_size);
1225 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1226 const AVFrame *frame, int *got_packet_ptr)
1228 FlacEncodeContext *s;
1229 int frame_bytes, out_bytes, ret;
1231 s = avctx->priv_data;
1233 /* when the last block is reached, update the header in extradata */
1235 s->max_framesize = s->max_encoded_framesize;
1236 av_md5_final(s->md5ctx, s->md5sum);
1237 write_streaminfo(s, avctx->extradata);
1239 #if FF_API_SIDEDATA_ONLY_PKT
1240 FF_DISABLE_DEPRECATION_WARNINGS
1241 if (avctx->side_data_only_packets && !s->flushed) {
1242 FF_ENABLE_DEPRECATION_WARNINGS
1246 uint8_t *side_data = av_packet_new_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
1247 avctx->extradata_size);
1249 return AVERROR(ENOMEM);
1250 memcpy(side_data, avctx->extradata, avctx->extradata_size);
1252 avpkt->pts = s->next_pts;
1254 *got_packet_ptr = 1;
1261 /* change max_framesize for small final frame */
1262 if (frame->nb_samples < s->frame.blocksize) {
1263 s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
1265 avctx->bits_per_raw_sample);
1268 init_frame(s, frame->nb_samples);
1270 copy_samples(s, frame->data[0]);
1272 channel_decorrelation(s);
1274 remove_wasted_bits(s);
1276 frame_bytes = encode_frame(s);
1278 /* Fall back on verbatim mode if the compressed frame is larger than it
1279 would be if encoded uncompressed. */
1280 if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
1281 s->frame.verbatim_only = 1;
1282 frame_bytes = encode_frame(s);
1283 if (frame_bytes < 0) {
1284 av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
1289 if ((ret = ff_alloc_packet(avpkt, frame_bytes))) {
1290 av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
1294 out_bytes = write_frame(s, avpkt);
1297 s->sample_count += frame->nb_samples;
1298 if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
1299 av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
1302 if (out_bytes > s->max_encoded_framesize)
1303 s->max_encoded_framesize = out_bytes;
1304 if (out_bytes < s->min_framesize)
1305 s->min_framesize = out_bytes;
1307 avpkt->pts = frame->pts;
1308 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1309 avpkt->size = out_bytes;
1311 s->next_pts = avpkt->pts + avpkt->duration;
1313 *got_packet_ptr = 1;
1318 static av_cold int flac_encode_close(AVCodecContext *avctx)
1320 if (avctx->priv_data) {
1321 FlacEncodeContext *s = avctx->priv_data;
1322 av_freep(&s->md5ctx);
1323 av_freep(&s->md5_buffer);
1324 ff_lpc_end(&s->lpc_ctx);
1326 av_freep(&avctx->extradata);
1327 avctx->extradata_size = 0;
1331 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1332 static const AVOption options[] = {
1333 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1334 { "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" },
1335 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1336 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1337 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1338 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1339 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes), AV_OPT_TYPE_INT, {.i64 = 1 }, 1, INT_MAX, FLAGS },
1340 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1341 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1342 { "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" },
1343 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1344 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1345 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1346 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1347 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1348 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1349 { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
1350 { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1351 { "indep", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1352 { "left_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1353 { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1354 { "mid_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1355 { "min_prediction_order", NULL, offsetof(FlacEncodeContext, options.min_prediction_order), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, MAX_LPC_ORDER, FLAGS },
1356 { "max_prediction_order", NULL, offsetof(FlacEncodeContext, options.max_prediction_order), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, MAX_LPC_ORDER, FLAGS },
1361 static const AVClass flac_encoder_class = {
1363 av_default_item_name,
1365 LIBAVUTIL_VERSION_INT,
1368 AVCodec ff_flac_encoder = {
1370 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1371 .type = AVMEDIA_TYPE_AUDIO,
1372 .id = AV_CODEC_ID_FLAC,
1373 .priv_data_size = sizeof(FlacEncodeContext),
1374 .init = flac_encode_init,
1375 .encode2 = flac_encode_frame,
1376 .close = flac_encode_close,
1377 .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
1378 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1380 AV_SAMPLE_FMT_NONE },
1381 .priv_class = &flac_encoder_class,