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];
72 typedef struct FlacSubframe {
78 int32_t coefs[MAX_LPC_ORDER];
81 int32_t samples[FLAC_MAX_BLOCKSIZE];
82 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
85 typedef struct FlacFrame {
86 FlacSubframe subframes[FLAC_MAX_CHANNELS];
94 typedef struct FlacEncodeContext {
104 int max_encoded_framesize;
105 uint32_t frame_count;
106 uint64_t sample_count;
109 CompressionOptions options;
110 AVCodecContext *avctx;
112 struct AVMD5 *md5ctx;
114 unsigned int md5_buffer_size;
115 BswapDSPContext bdsp;
116 FLACDSPContext flac_dsp;
124 * Write streaminfo metadata block to byte array.
126 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
130 memset(header, 0, FLAC_STREAMINFO_SIZE);
131 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
133 /* streaminfo metadata block */
134 put_bits(&pb, 16, s->max_blocksize);
135 put_bits(&pb, 16, s->max_blocksize);
136 put_bits(&pb, 24, s->min_framesize);
137 put_bits(&pb, 24, s->max_framesize);
138 put_bits(&pb, 20, s->samplerate);
139 put_bits(&pb, 3, s->channels-1);
140 put_bits(&pb, 5, s->avctx->bits_per_raw_sample - 1);
141 /* write 36-bit sample count in 2 put_bits() calls */
142 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
143 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
145 memcpy(&header[18], s->md5sum, 16);
150 * Set blocksize based on samplerate.
151 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
153 static int select_blocksize(int samplerate, int block_time_ms)
159 assert(samplerate > 0);
160 blocksize = ff_flac_blocksize_table[1];
161 target = (samplerate * block_time_ms) / 1000;
162 for (i = 0; i < 16; i++) {
163 if (target >= ff_flac_blocksize_table[i] &&
164 ff_flac_blocksize_table[i] > blocksize) {
165 blocksize = ff_flac_blocksize_table[i];
172 static av_cold void dprint_compression_options(FlacEncodeContext *s)
174 AVCodecContext *avctx = s->avctx;
175 CompressionOptions *opt = &s->options;
177 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
179 switch (opt->lpc_type) {
180 case FF_LPC_TYPE_NONE:
181 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
183 case FF_LPC_TYPE_FIXED:
184 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
186 case FF_LPC_TYPE_LEVINSON:
187 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
189 case FF_LPC_TYPE_CHOLESKY:
190 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
191 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
195 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
196 opt->min_prediction_order, opt->max_prediction_order);
198 switch (opt->prediction_order_method) {
199 case ORDER_METHOD_EST:
200 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
202 case ORDER_METHOD_2LEVEL:
203 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
205 case ORDER_METHOD_4LEVEL:
206 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
208 case ORDER_METHOD_8LEVEL:
209 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
211 case ORDER_METHOD_SEARCH:
212 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
214 case ORDER_METHOD_LOG:
215 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
220 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
221 opt->min_partition_order, opt->max_partition_order);
223 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
225 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
226 opt->lpc_coeff_precision);
230 static av_cold int flac_encode_init(AVCodecContext *avctx)
232 int freq = avctx->sample_rate;
233 int channels = avctx->channels;
234 FlacEncodeContext *s = avctx->priv_data;
240 switch (avctx->sample_fmt) {
241 case AV_SAMPLE_FMT_S16:
242 avctx->bits_per_raw_sample = 16;
245 case AV_SAMPLE_FMT_S32:
246 if (avctx->bits_per_raw_sample != 24)
247 av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
248 avctx->bits_per_raw_sample = 24;
253 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
255 s->channels = channels;
257 /* find samplerate in table */
260 for (i = 4; i < 12; i++) {
261 if (freq == ff_flac_sample_rate_table[i]) {
262 s->samplerate = ff_flac_sample_rate_table[i];
268 /* if not in table, samplerate is non-standard */
270 if (freq % 1000 == 0 && freq < 255000) {
272 s->sr_code[1] = freq / 1000;
273 } else if (freq % 10 == 0 && freq < 655350) {
275 s->sr_code[1] = freq / 10;
276 } else if (freq < 65535) {
278 s->sr_code[1] = freq;
282 s->samplerate = freq;
285 /* set compression option defaults based on avctx->compression_level */
286 if (avctx->compression_level < 0)
287 s->options.compression_level = 5;
289 s->options.compression_level = avctx->compression_level;
291 level = s->options.compression_level;
293 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
294 s->options.compression_level);
298 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
300 if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
301 s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
302 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
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})[level];
307 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
308 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
310 if (s->options.prediction_order_method < 0)
311 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
312 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
313 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
314 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
315 ORDER_METHOD_SEARCH})[level];
317 if (s->options.min_partition_order > s->options.max_partition_order) {
318 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
319 s->options.min_partition_order, s->options.max_partition_order);
320 return AVERROR(EINVAL);
322 if (s->options.min_partition_order < 0)
323 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
324 if (s->options.max_partition_order < 0)
325 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
327 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
328 s->options.min_prediction_order = 0;
329 } else if (avctx->min_prediction_order >= 0) {
330 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
331 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
332 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
333 avctx->min_prediction_order);
336 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
337 avctx->min_prediction_order > MAX_LPC_ORDER) {
338 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
339 avctx->min_prediction_order);
342 s->options.min_prediction_order = avctx->min_prediction_order;
344 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
345 s->options.max_prediction_order = 0;
346 } else if (avctx->max_prediction_order >= 0) {
347 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
348 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
349 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
350 avctx->max_prediction_order);
353 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
354 avctx->max_prediction_order > MAX_LPC_ORDER) {
355 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
356 avctx->max_prediction_order);
359 s->options.max_prediction_order = avctx->max_prediction_order;
361 if (s->options.max_prediction_order < s->options.min_prediction_order) {
362 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
363 s->options.min_prediction_order, s->options.max_prediction_order);
367 if (avctx->frame_size > 0) {
368 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
369 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
370 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
375 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
377 s->max_blocksize = s->avctx->frame_size;
379 /* set maximum encoded frame size in verbatim mode */
380 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
382 s->avctx->bits_per_raw_sample);
384 /* initialize MD5 context */
385 s->md5ctx = av_md5_alloc();
387 return AVERROR(ENOMEM);
388 av_md5_init(s->md5ctx);
390 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
392 return AVERROR(ENOMEM);
393 write_streaminfo(s, streaminfo);
394 avctx->extradata = streaminfo;
395 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
398 s->min_framesize = s->max_framesize;
400 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
401 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
403 ff_bswapdsp_init(&s->bdsp);
404 ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt,
405 avctx->bits_per_raw_sample);
407 dprint_compression_options(s);
413 static void init_frame(FlacEncodeContext *s, int nb_samples)
420 for (i = 0; i < 16; i++) {
421 if (nb_samples == ff_flac_blocksize_table[i]) {
422 frame->blocksize = ff_flac_blocksize_table[i];
423 frame->bs_code[0] = i;
424 frame->bs_code[1] = 0;
429 frame->blocksize = nb_samples;
430 if (frame->blocksize <= 256) {
431 frame->bs_code[0] = 6;
432 frame->bs_code[1] = frame->blocksize-1;
434 frame->bs_code[0] = 7;
435 frame->bs_code[1] = frame->blocksize-1;
439 for (ch = 0; ch < s->channels; ch++) {
440 FlacSubframe *sub = &frame->subframes[ch];
443 sub->obits = s->avctx->bits_per_raw_sample;
446 sub->rc.coding_mode = CODING_MODE_RICE2;
448 sub->rc.coding_mode = CODING_MODE_RICE;
451 frame->verbatim_only = 0;
456 * Copy channel-interleaved input samples into separate subframes.
458 static void copy_samples(FlacEncodeContext *s, const void *samples)
462 int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
463 s->avctx->bits_per_raw_sample;
465 #define COPY_SAMPLES(bits) do { \
466 const int ## bits ## _t *samples0 = samples; \
468 for (i = 0, j = 0; i < frame->blocksize; i++) \
469 for (ch = 0; ch < s->channels; ch++, j++) \
470 frame->subframes[ch].samples[i] = samples0[j] >> shift; \
473 if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
480 static uint64_t rice_count_exact(int32_t *res, int n, int k)
485 for (i = 0; i < n; i++) {
486 int32_t v = -2 * res[i] - 1;
488 count += (v >> k) + 1 + k;
494 static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
497 int p, porder, psize;
501 /* subframe header */
505 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
507 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
508 count += s->frame.blocksize * sub->obits;
510 /* warm-up samples */
511 count += pred_order * sub->obits;
513 /* LPC coefficients */
514 if (sub->type == FLAC_SUBFRAME_LPC)
515 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
517 /* rice-encoded block */
520 /* partition order */
521 porder = sub->rc.porder;
522 psize = s->frame.blocksize >> porder;
528 for (p = 0; p < 1 << porder; p++) {
529 int k = sub->rc.params[p];
530 count += sub->rc.coding_mode;
531 count += rice_count_exact(&sub->residual[i], part_end - i, k);
533 part_end = FFMIN(s->frame.blocksize, part_end + psize);
541 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
544 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
546 static int find_optimal_param(uint64_t sum, int n, int max_param)
553 sum2 = sum - (n >> 1);
554 k = av_log2(av_clipl_int32(sum2 / n));
555 return FFMIN(k, max_param);
559 static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
560 uint64_t *sums, int n, int pred_order)
563 int k, cnt, part, max_param;
566 max_param = (1 << rc->coding_mode) - 2;
568 part = (1 << porder);
571 cnt = (n >> porder) - pred_order;
572 for (i = 0; i < part; i++) {
573 k = find_optimal_param(sums[i], cnt, max_param);
575 all_bits += rice_encode_count(sums[i], cnt, k);
585 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
586 uint64_t sums[][MAX_PARTITIONS])
590 uint32_t *res, *res_end;
592 /* sums for highest level */
594 res = &data[pred_order];
595 res_end = &data[n >> pmax];
596 for (i = 0; i < parts; i++) {
598 while (res < res_end)
601 res_end += n >> pmax;
603 /* sums for lower levels */
604 for (i = pmax - 1; i >= pmin; i--) {
606 for (j = 0; j < parts; j++)
607 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
612 static uint64_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
613 int32_t *data, int n, int pred_order)
616 uint64_t bits[MAX_PARTITION_ORDER+1];
620 uint64_t sums[MAX_PARTITION_ORDER + 1][MAX_PARTITIONS] = { { 0 } };
622 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
623 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
624 assert(pmin <= pmax);
626 tmp_rc.coding_mode = rc->coding_mode;
628 udata = av_malloc(n * sizeof(uint32_t));
629 for (i = 0; i < n; i++)
630 udata[i] = (2*data[i]) ^ (data[i]>>31);
632 calc_sums(pmin, pmax, udata, n, pred_order, sums);
635 bits[pmin] = UINT32_MAX;
636 for (i = pmin; i <= pmax; i++) {
637 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
638 if (bits[i] <= bits[opt_porder]) {
645 return bits[opt_porder];
649 static int get_max_p_order(int max_porder, int n, int order)
651 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
653 porder = FFMIN(porder, av_log2(n/order));
658 static uint64_t find_subframe_rice_params(FlacEncodeContext *s,
659 FlacSubframe *sub, int pred_order)
661 int pmin = get_max_p_order(s->options.min_partition_order,
662 s->frame.blocksize, pred_order);
663 int pmax = get_max_p_order(s->options.max_partition_order,
664 s->frame.blocksize, pred_order);
666 uint64_t bits = 8 + pred_order * sub->obits + 2 + sub->rc.coding_mode;
667 if (sub->type == FLAC_SUBFRAME_LPC)
668 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
669 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
670 s->frame.blocksize, pred_order);
675 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
680 for (i = 0; i < order; i++)
684 for (i = order; i < n; i++)
686 } else if (order == 1) {
687 for (i = order; i < n; i++)
688 res[i] = smp[i] - smp[i-1];
689 } else if (order == 2) {
690 int a = smp[order-1] - smp[order-2];
691 for (i = order; i < n; i += 2) {
692 int b = smp[i ] - smp[i-1];
694 a = smp[i+1] - smp[i ];
697 } else if (order == 3) {
698 int a = smp[order-1] - smp[order-2];
699 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
700 for (i = order; i < n; i += 2) {
701 int b = smp[i ] - smp[i-1];
704 a = smp[i+1] - smp[i ];
709 int a = smp[order-1] - smp[order-2];
710 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
711 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
712 for (i = order; i < n; i += 2) {
713 int b = smp[i ] - smp[i-1];
717 a = smp[i+1] - smp[i ];
726 static int encode_residual_ch(FlacEncodeContext *s, int ch)
729 int min_order, max_order, opt_order, omethod;
732 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
733 int shift[MAX_LPC_ORDER];
737 sub = &frame->subframes[ch];
740 n = frame->blocksize;
743 for (i = 1; i < n; i++)
747 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
749 return subframe_count_exact(s, sub, 0);
753 if (frame->verbatim_only || n < 5) {
754 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
755 memcpy(res, smp, n * sizeof(int32_t));
756 return subframe_count_exact(s, sub, 0);
759 min_order = s->options.min_prediction_order;
760 max_order = s->options.max_prediction_order;
761 omethod = s->options.prediction_order_method;
764 sub->type = FLAC_SUBFRAME_FIXED;
765 if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
766 s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
767 uint64_t bits[MAX_FIXED_ORDER+1];
768 if (max_order > MAX_FIXED_ORDER)
769 max_order = MAX_FIXED_ORDER;
771 bits[0] = UINT32_MAX;
772 for (i = min_order; i <= max_order; i++) {
773 encode_residual_fixed(res, smp, n, i);
774 bits[i] = find_subframe_rice_params(s, sub, i);
775 if (bits[i] < bits[opt_order])
778 sub->order = opt_order;
779 sub->type_code = sub->type | sub->order;
780 if (sub->order != max_order) {
781 encode_residual_fixed(res, smp, n, sub->order);
782 find_subframe_rice_params(s, sub, sub->order);
784 return subframe_count_exact(s, sub, sub->order);
788 sub->type = FLAC_SUBFRAME_LPC;
789 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
790 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
791 s->options.lpc_passes, omethod,
794 if (omethod == ORDER_METHOD_2LEVEL ||
795 omethod == ORDER_METHOD_4LEVEL ||
796 omethod == ORDER_METHOD_8LEVEL) {
797 int levels = 1 << omethod;
798 uint64_t bits[1 << ORDER_METHOD_8LEVEL];
800 int opt_index = levels-1;
801 opt_order = max_order-1;
802 bits[opt_index] = UINT32_MAX;
803 for (i = levels-1; i >= 0; i--) {
804 int last_order = order;
805 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
806 order = av_clip(order, min_order - 1, max_order - 1);
807 if (order == last_order)
809 s->flac_dsp.lpc_encode(res, smp, n, order+1, coefs[order],
811 bits[i] = find_subframe_rice_params(s, sub, order+1);
812 if (bits[i] < bits[opt_index]) {
818 } else if (omethod == ORDER_METHOD_SEARCH) {
819 // brute-force optimal order search
820 uint64_t bits[MAX_LPC_ORDER];
822 bits[0] = UINT32_MAX;
823 for (i = min_order-1; i < max_order; i++) {
824 s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
825 bits[i] = find_subframe_rice_params(s, sub, i+1);
826 if (bits[i] < bits[opt_order])
830 } else if (omethod == ORDER_METHOD_LOG) {
831 uint64_t bits[MAX_LPC_ORDER];
834 opt_order = min_order - 1 + (max_order-min_order)/3;
835 memset(bits, -1, sizeof(bits));
837 for (step = 16; step; step >>= 1) {
838 int last = opt_order;
839 for (i = last-step; i <= last+step; i += step) {
840 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
842 s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
843 bits[i] = find_subframe_rice_params(s, sub, i+1);
844 if (bits[i] < bits[opt_order])
851 sub->order = opt_order;
852 sub->type_code = sub->type | (sub->order-1);
853 sub->shift = shift[sub->order-1];
854 for (i = 0; i < sub->order; i++)
855 sub->coefs[i] = coefs[sub->order-1][i];
857 s->flac_dsp.lpc_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
859 find_subframe_rice_params(s, sub, sub->order);
861 return subframe_count_exact(s, sub, sub->order);
865 static int count_frame_header(FlacEncodeContext *s)
867 uint8_t av_unused tmp;
873 <1> Blocking strategy
874 <4> Block size in inter-channel samples
876 <4> Channel assignment
877 <3> Sample size in bits
882 /* coded frame number */
883 PUT_UTF8(s->frame_count, tmp, count += 8;)
885 /* explicit block size */
886 if (s->frame.bs_code[0] == 6)
888 else if (s->frame.bs_code[0] == 7)
891 /* explicit sample rate */
892 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
894 /* frame header CRC-8 */
901 static int encode_frame(FlacEncodeContext *s)
906 count = count_frame_header(s);
908 for (ch = 0; ch < s->channels; ch++)
909 count += encode_residual_ch(s, ch);
911 count += (8 - (count & 7)) & 7; // byte alignment
912 count += 16; // CRC-16
921 static void remove_wasted_bits(FlacEncodeContext *s)
925 for (ch = 0; ch < s->channels; ch++) {
926 FlacSubframe *sub = &s->frame.subframes[ch];
929 for (i = 0; i < s->frame.blocksize; i++) {
930 v |= sub->samples[i];
938 for (i = 0; i < s->frame.blocksize; i++)
939 sub->samples[i] >>= v;
944 /* for 24-bit, check if removing wasted bits makes the range better
945 suited for using RICE instead of RICE2 for entropy coding */
946 if (sub->obits <= 17)
947 sub->rc.coding_mode = CODING_MODE_RICE;
953 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n,
962 /* calculate sum of 2nd order residual for each channel */
963 sum[0] = sum[1] = sum[2] = sum[3] = 0;
964 for (i = 2; i < n; i++) {
965 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
966 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
967 sum[2] += FFABS((lt + rt) >> 1);
968 sum[3] += FFABS(lt - rt);
972 /* estimate bit counts */
973 for (i = 0; i < 4; i++) {
974 k = find_optimal_param(2 * sum[i], n, max_rice_param);
975 sum[i] = rice_encode_count( 2 * sum[i], n, k);
978 /* calculate score for each mode */
979 score[0] = sum[0] + sum[1];
980 score[1] = sum[0] + sum[3];
981 score[2] = sum[1] + sum[3];
982 score[3] = sum[2] + sum[3];
984 /* return mode with lowest score */
986 for (i = 1; i < 4; i++)
987 if (score[i] < score[best])
995 * Perform stereo channel decorrelation.
997 static void channel_decorrelation(FlacEncodeContext *s)
1000 int32_t *left, *right;
1004 n = frame->blocksize;
1005 left = frame->subframes[0].samples;
1006 right = frame->subframes[1].samples;
1008 if (s->channels != 2) {
1009 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1013 if (s->options.ch_mode < 0) {
1014 int max_rice_param = (1 << frame->subframes[0].rc.coding_mode) - 2;
1015 frame->ch_mode = estimate_stereo_mode(left, right, n, max_rice_param);
1017 frame->ch_mode = s->options.ch_mode;
1019 /* perform decorrelation and adjust bits-per-sample */
1020 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1022 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1024 for (i = 0; i < n; i++) {
1026 left[i] = (tmp + right[i]) >> 1;
1027 right[i] = tmp - right[i];
1029 frame->subframes[1].obits++;
1030 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1031 for (i = 0; i < n; i++)
1032 right[i] = left[i] - right[i];
1033 frame->subframes[1].obits++;
1035 for (i = 0; i < n; i++)
1036 left[i] -= right[i];
1037 frame->subframes[0].obits++;
1042 static void write_utf8(PutBitContext *pb, uint32_t val)
1045 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1049 static void write_frame_header(FlacEncodeContext *s)
1056 put_bits(&s->pb, 16, 0xFFF8);
1057 put_bits(&s->pb, 4, frame->bs_code[0]);
1058 put_bits(&s->pb, 4, s->sr_code[0]);
1060 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1061 put_bits(&s->pb, 4, s->channels-1);
1063 put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
1065 put_bits(&s->pb, 3, s->bps_code);
1066 put_bits(&s->pb, 1, 0);
1067 write_utf8(&s->pb, s->frame_count);
1069 if (frame->bs_code[0] == 6)
1070 put_bits(&s->pb, 8, frame->bs_code[1]);
1071 else if (frame->bs_code[0] == 7)
1072 put_bits(&s->pb, 16, frame->bs_code[1]);
1074 if (s->sr_code[0] == 12)
1075 put_bits(&s->pb, 8, s->sr_code[1]);
1076 else if (s->sr_code[0] > 12)
1077 put_bits(&s->pb, 16, s->sr_code[1]);
1079 flush_put_bits(&s->pb);
1080 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1081 put_bits_count(&s->pb) >> 3);
1082 put_bits(&s->pb, 8, crc);
1086 static void write_subframes(FlacEncodeContext *s)
1090 for (ch = 0; ch < s->channels; ch++) {
1091 FlacSubframe *sub = &s->frame.subframes[ch];
1092 int i, p, porder, psize;
1094 int32_t *res = sub->residual;
1095 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1097 /* subframe header */
1098 put_bits(&s->pb, 1, 0);
1099 put_bits(&s->pb, 6, sub->type_code);
1100 put_bits(&s->pb, 1, !!sub->wasted);
1102 put_bits(&s->pb, sub->wasted, 1);
1105 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1106 put_sbits(&s->pb, sub->obits, res[0]);
1107 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1108 while (res < frame_end)
1109 put_sbits(&s->pb, sub->obits, *res++);
1111 /* warm-up samples */
1112 for (i = 0; i < sub->order; i++)
1113 put_sbits(&s->pb, sub->obits, *res++);
1115 /* LPC coefficients */
1116 if (sub->type == FLAC_SUBFRAME_LPC) {
1117 int cbits = s->options.lpc_coeff_precision;
1118 put_bits( &s->pb, 4, cbits-1);
1119 put_sbits(&s->pb, 5, sub->shift);
1120 for (i = 0; i < sub->order; i++)
1121 put_sbits(&s->pb, cbits, sub->coefs[i]);
1124 /* rice-encoded block */
1125 put_bits(&s->pb, 2, sub->rc.coding_mode - 4);
1127 /* partition order */
1128 porder = sub->rc.porder;
1129 psize = s->frame.blocksize >> porder;
1130 put_bits(&s->pb, 4, porder);
1133 part_end = &sub->residual[psize];
1134 for (p = 0; p < 1 << porder; p++) {
1135 int k = sub->rc.params[p];
1136 put_bits(&s->pb, sub->rc.coding_mode, k);
1137 while (res < part_end)
1138 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1139 part_end = FFMIN(frame_end, part_end + psize);
1146 static void write_frame_footer(FlacEncodeContext *s)
1149 flush_put_bits(&s->pb);
1150 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1151 put_bits_count(&s->pb)>>3));
1152 put_bits(&s->pb, 16, crc);
1153 flush_put_bits(&s->pb);
1157 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1159 init_put_bits(&s->pb, avpkt->data, avpkt->size);
1160 write_frame_header(s);
1162 write_frame_footer(s);
1163 return put_bits_count(&s->pb) >> 3;
1167 static int update_md5_sum(FlacEncodeContext *s, const void *samples)
1170 int buf_size = s->frame.blocksize * s->channels *
1171 ((s->avctx->bits_per_raw_sample + 7) / 8);
1173 if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
1174 av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
1176 return AVERROR(ENOMEM);
1179 if (s->avctx->bits_per_raw_sample <= 16) {
1180 buf = (const uint8_t *)samples;
1182 s->bdsp.bswap16_buf((uint16_t *) s->md5_buffer,
1183 (const uint16_t *) samples, buf_size / 2);
1184 buf = s->md5_buffer;
1188 const int32_t *samples0 = samples;
1189 uint8_t *tmp = s->md5_buffer;
1191 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1192 int32_t v = samples0[i] >> 8;
1193 *tmp++ = (v ) & 0xFF;
1194 *tmp++ = (v >> 8) & 0xFF;
1195 *tmp++ = (v >> 16) & 0xFF;
1197 buf = s->md5_buffer;
1199 av_md5_update(s->md5ctx, buf, buf_size);
1205 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1206 const AVFrame *frame, int *got_packet_ptr)
1208 FlacEncodeContext *s;
1209 int frame_bytes, out_bytes, ret;
1211 s = avctx->priv_data;
1213 /* when the last block is reached, update the header in extradata */
1215 s->max_framesize = s->max_encoded_framesize;
1216 av_md5_final(s->md5ctx, s->md5sum);
1217 write_streaminfo(s, avctx->extradata);
1219 if (avctx->side_data_only_packets && !s->flushed) {
1220 uint8_t *side_data = av_packet_new_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA,
1221 avctx->extradata_size);
1223 return AVERROR(ENOMEM);
1224 memcpy(side_data, avctx->extradata, avctx->extradata_size);
1226 avpkt->pts = s->next_pts;
1228 *got_packet_ptr = 1;
1235 /* change max_framesize for small final frame */
1236 if (frame->nb_samples < s->frame.blocksize) {
1237 s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
1239 avctx->bits_per_raw_sample);
1242 init_frame(s, frame->nb_samples);
1244 copy_samples(s, frame->data[0]);
1246 channel_decorrelation(s);
1248 remove_wasted_bits(s);
1250 frame_bytes = encode_frame(s);
1252 /* Fall back on verbatim mode if the compressed frame is larger than it
1253 would be if encoded uncompressed. */
1254 if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
1255 s->frame.verbatim_only = 1;
1256 frame_bytes = encode_frame(s);
1257 if (frame_bytes < 0) {
1258 av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
1263 if ((ret = ff_alloc_packet(avpkt, frame_bytes))) {
1264 av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
1268 out_bytes = write_frame(s, avpkt);
1271 s->sample_count += frame->nb_samples;
1272 if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
1273 av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
1276 if (out_bytes > s->max_encoded_framesize)
1277 s->max_encoded_framesize = out_bytes;
1278 if (out_bytes < s->min_framesize)
1279 s->min_framesize = out_bytes;
1281 avpkt->pts = frame->pts;
1282 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1283 avpkt->size = out_bytes;
1285 s->next_pts = avpkt->pts + avpkt->duration;
1287 *got_packet_ptr = 1;
1292 static av_cold int flac_encode_close(AVCodecContext *avctx)
1294 if (avctx->priv_data) {
1295 FlacEncodeContext *s = avctx->priv_data;
1296 av_freep(&s->md5ctx);
1297 av_freep(&s->md5_buffer);
1298 ff_lpc_end(&s->lpc_ctx);
1300 av_freep(&avctx->extradata);
1301 avctx->extradata_size = 0;
1305 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1306 static const AVOption options[] = {
1307 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1308 { "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" },
1309 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1310 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1311 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1312 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1313 { "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 },
1314 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1315 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1316 { "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" },
1317 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1318 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1319 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1320 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1321 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1322 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1323 { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
1324 { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1325 { "indep", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1326 { "left_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1327 { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1328 { "mid_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1332 static const AVClass flac_encoder_class = {
1334 av_default_item_name,
1336 LIBAVUTIL_VERSION_INT,
1339 AVCodec ff_flac_encoder = {
1341 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1342 .type = AVMEDIA_TYPE_AUDIO,
1343 .id = AV_CODEC_ID_FLAC,
1344 .priv_data_size = sizeof(FlacEncodeContext),
1345 .init = flac_encode_init,
1346 .encode2 = flac_encode_frame,
1347 .close = flac_encode_close,
1348 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1349 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1351 AV_SAMPLE_FMT_NONE },
1352 .priv_class = &flac_encoder_class,