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
46 #define MAX_RICE_PARAM 14
48 typedef struct CompressionOptions {
49 int compression_level;
51 enum FFLPCType lpc_type;
53 int lpc_coeff_precision;
54 int min_prediction_order;
55 int max_prediction_order;
56 int prediction_order_method;
57 int min_partition_order;
58 int max_partition_order;
62 typedef struct RiceContext {
64 int params[MAX_PARTITIONS];
67 typedef struct FlacSubframe {
73 int32_t coefs[MAX_LPC_ORDER];
76 int32_t samples[FLAC_MAX_BLOCKSIZE];
77 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
80 typedef struct FlacFrame {
81 FlacSubframe subframes[FLAC_MAX_CHANNELS];
89 typedef struct FlacEncodeContext {
99 int max_encoded_framesize;
100 uint32_t frame_count;
101 uint64_t sample_count;
104 CompressionOptions options;
105 AVCodecContext *avctx;
107 struct AVMD5 *md5ctx;
109 unsigned int md5_buffer_size;
111 FLACDSPContext flac_dsp;
116 * Write streaminfo metadata block to byte array.
118 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
122 memset(header, 0, FLAC_STREAMINFO_SIZE);
123 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
125 /* streaminfo metadata block */
126 put_bits(&pb, 16, s->max_blocksize);
127 put_bits(&pb, 16, s->max_blocksize);
128 put_bits(&pb, 24, s->min_framesize);
129 put_bits(&pb, 24, s->max_framesize);
130 put_bits(&pb, 20, s->samplerate);
131 put_bits(&pb, 3, s->channels-1);
132 put_bits(&pb, 5, s->avctx->bits_per_raw_sample - 1);
133 /* write 36-bit sample count in 2 put_bits() calls */
134 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
135 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
137 memcpy(&header[18], s->md5sum, 16);
142 * Set blocksize based on samplerate.
143 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
145 static int select_blocksize(int samplerate, int block_time_ms)
151 assert(samplerate > 0);
152 blocksize = ff_flac_blocksize_table[1];
153 target = (samplerate * block_time_ms) / 1000;
154 for (i = 0; i < 16; i++) {
155 if (target >= ff_flac_blocksize_table[i] &&
156 ff_flac_blocksize_table[i] > blocksize) {
157 blocksize = ff_flac_blocksize_table[i];
164 static av_cold void dprint_compression_options(FlacEncodeContext *s)
166 AVCodecContext *avctx = s->avctx;
167 CompressionOptions *opt = &s->options;
169 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
171 switch (opt->lpc_type) {
172 case FF_LPC_TYPE_NONE:
173 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
175 case FF_LPC_TYPE_FIXED:
176 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
178 case FF_LPC_TYPE_LEVINSON:
179 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
181 case FF_LPC_TYPE_CHOLESKY:
182 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
183 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
187 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
188 opt->min_prediction_order, opt->max_prediction_order);
190 switch (opt->prediction_order_method) {
191 case ORDER_METHOD_EST:
192 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
194 case ORDER_METHOD_2LEVEL:
195 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
197 case ORDER_METHOD_4LEVEL:
198 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
200 case ORDER_METHOD_8LEVEL:
201 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
203 case ORDER_METHOD_SEARCH:
204 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
206 case ORDER_METHOD_LOG:
207 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
212 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
213 opt->min_partition_order, opt->max_partition_order);
215 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
217 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
218 opt->lpc_coeff_precision);
222 static av_cold int flac_encode_init(AVCodecContext *avctx)
224 int freq = avctx->sample_rate;
225 int channels = avctx->channels;
226 FlacEncodeContext *s = avctx->priv_data;
232 switch (avctx->sample_fmt) {
233 case AV_SAMPLE_FMT_S16:
234 avctx->bits_per_raw_sample = 16;
237 case AV_SAMPLE_FMT_S32:
238 if (avctx->bits_per_raw_sample != 24)
239 av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
240 avctx->bits_per_raw_sample = 24;
245 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
247 s->channels = channels;
249 /* find samplerate in table */
252 for (i = 4; i < 12; i++) {
253 if (freq == ff_flac_sample_rate_table[i]) {
254 s->samplerate = ff_flac_sample_rate_table[i];
260 /* if not in table, samplerate is non-standard */
262 if (freq % 1000 == 0 && freq < 255000) {
264 s->sr_code[1] = freq / 1000;
265 } else if (freq % 10 == 0 && freq < 655350) {
267 s->sr_code[1] = freq / 10;
268 } else if (freq < 65535) {
270 s->sr_code[1] = freq;
274 s->samplerate = freq;
277 /* set compression option defaults based on avctx->compression_level */
278 if (avctx->compression_level < 0)
279 s->options.compression_level = 5;
281 s->options.compression_level = avctx->compression_level;
283 level = s->options.compression_level;
285 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
286 s->options.compression_level);
290 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
292 if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
293 s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
294 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
295 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
296 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
297 FF_LPC_TYPE_LEVINSON})[level];
299 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
300 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
302 if (s->options.prediction_order_method < 0)
303 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
304 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
305 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
306 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
307 ORDER_METHOD_SEARCH})[level];
309 if (s->options.min_partition_order > s->options.max_partition_order) {
310 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
311 s->options.min_partition_order, s->options.max_partition_order);
312 return AVERROR(EINVAL);
314 if (s->options.min_partition_order < 0)
315 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
316 if (s->options.max_partition_order < 0)
317 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
319 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
320 s->options.min_prediction_order = 0;
321 } else if (avctx->min_prediction_order >= 0) {
322 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
323 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
324 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
325 avctx->min_prediction_order);
328 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
329 avctx->min_prediction_order > MAX_LPC_ORDER) {
330 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
331 avctx->min_prediction_order);
334 s->options.min_prediction_order = avctx->min_prediction_order;
336 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
337 s->options.max_prediction_order = 0;
338 } else if (avctx->max_prediction_order >= 0) {
339 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
340 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
341 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
342 avctx->max_prediction_order);
345 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
346 avctx->max_prediction_order > MAX_LPC_ORDER) {
347 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
348 avctx->max_prediction_order);
351 s->options.max_prediction_order = avctx->max_prediction_order;
353 if (s->options.max_prediction_order < s->options.min_prediction_order) {
354 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
355 s->options.min_prediction_order, s->options.max_prediction_order);
359 if (avctx->frame_size > 0) {
360 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
361 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
362 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
367 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
369 s->max_blocksize = s->avctx->frame_size;
371 /* set maximum encoded frame size in verbatim mode */
372 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
374 s->avctx->bits_per_raw_sample);
376 /* initialize MD5 context */
377 s->md5ctx = av_md5_alloc();
379 return AVERROR(ENOMEM);
380 av_md5_init(s->md5ctx);
382 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
384 return AVERROR(ENOMEM);
385 write_streaminfo(s, streaminfo);
386 avctx->extradata = streaminfo;
387 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
390 s->min_framesize = s->max_framesize;
392 #if FF_API_OLD_ENCODE_AUDIO
393 avctx->coded_frame = avcodec_alloc_frame();
394 if (!avctx->coded_frame)
395 return AVERROR(ENOMEM);
398 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
399 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
401 ff_dsputil_init(&s->dsp, avctx);
402 ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt,
403 avctx->bits_per_raw_sample);
405 dprint_compression_options(s);
411 static void init_frame(FlacEncodeContext *s, int nb_samples)
418 for (i = 0; i < 16; i++) {
419 if (nb_samples == ff_flac_blocksize_table[i]) {
420 frame->blocksize = ff_flac_blocksize_table[i];
421 frame->bs_code[0] = i;
422 frame->bs_code[1] = 0;
427 frame->blocksize = nb_samples;
428 if (frame->blocksize <= 256) {
429 frame->bs_code[0] = 6;
430 frame->bs_code[1] = frame->blocksize-1;
432 frame->bs_code[0] = 7;
433 frame->bs_code[1] = frame->blocksize-1;
437 for (ch = 0; ch < s->channels; ch++) {
438 frame->subframes[ch].wasted = 0;
439 frame->subframes[ch].obits = s->avctx->bits_per_raw_sample;
442 frame->verbatim_only = 0;
447 * Copy channel-interleaved input samples into separate subframes.
449 static void copy_samples(FlacEncodeContext *s, const void *samples)
453 int shift = av_get_bytes_per_sample(s->avctx->sample_fmt) * 8 -
454 s->avctx->bits_per_raw_sample;
456 #define COPY_SAMPLES(bits) do { \
457 const int ## bits ## _t *samples0 = samples; \
459 for (i = 0, j = 0; i < frame->blocksize; i++) \
460 for (ch = 0; ch < s->channels; ch++, j++) \
461 frame->subframes[ch].samples[i] = samples0[j] >> shift; \
464 if (s->avctx->sample_fmt == AV_SAMPLE_FMT_S16)
471 static uint64_t rice_count_exact(int32_t *res, int n, int k)
476 for (i = 0; i < n; i++) {
477 int32_t v = -2 * res[i] - 1;
479 count += (v >> k) + 1 + k;
485 static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
488 int p, porder, psize;
492 /* subframe header */
496 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
498 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
499 count += s->frame.blocksize * sub->obits;
501 /* warm-up samples */
502 count += pred_order * sub->obits;
504 /* LPC coefficients */
505 if (sub->type == FLAC_SUBFRAME_LPC)
506 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
508 /* rice-encoded block */
511 /* partition order */
512 porder = sub->rc.porder;
513 psize = s->frame.blocksize >> porder;
519 for (p = 0; p < 1 << porder; p++) {
520 int k = sub->rc.params[p];
522 count += rice_count_exact(&sub->residual[i], part_end - i, k);
524 part_end = FFMIN(s->frame.blocksize, part_end + psize);
532 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
535 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
537 static int find_optimal_param(uint64_t sum, int n)
544 sum2 = sum - (n >> 1);
545 k = av_log2(av_clipl_int32(sum2 / n));
546 return FFMIN(k, MAX_RICE_PARAM);
550 static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
551 uint64_t *sums, int n, int pred_order)
557 part = (1 << porder);
560 cnt = (n >> porder) - pred_order;
561 for (i = 0; i < part; i++) {
562 k = find_optimal_param(sums[i], cnt);
564 all_bits += rice_encode_count(sums[i], cnt, k);
574 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
575 uint64_t sums[][MAX_PARTITIONS])
579 uint32_t *res, *res_end;
581 /* sums for highest level */
583 res = &data[pred_order];
584 res_end = &data[n >> pmax];
585 for (i = 0; i < parts; i++) {
587 while (res < res_end)
590 res_end += n >> pmax;
592 /* sums for lower levels */
593 for (i = pmax - 1; i >= pmin; i--) {
595 for (j = 0; j < parts; j++)
596 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
601 static uint64_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
602 int32_t *data, int n, int pred_order)
605 uint64_t bits[MAX_PARTITION_ORDER+1];
609 uint64_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
611 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
612 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
613 assert(pmin <= pmax);
615 udata = av_malloc(n * sizeof(uint32_t));
616 for (i = 0; i < n; i++)
617 udata[i] = (2*data[i]) ^ (data[i]>>31);
619 calc_sums(pmin, pmax, udata, n, pred_order, sums);
622 bits[pmin] = UINT32_MAX;
623 for (i = pmin; i <= pmax; i++) {
624 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
625 if (bits[i] <= bits[opt_porder]) {
632 return bits[opt_porder];
636 static int get_max_p_order(int max_porder, int n, int order)
638 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
640 porder = FFMIN(porder, av_log2(n/order));
645 static uint64_t find_subframe_rice_params(FlacEncodeContext *s,
646 FlacSubframe *sub, int pred_order)
648 int pmin = get_max_p_order(s->options.min_partition_order,
649 s->frame.blocksize, pred_order);
650 int pmax = get_max_p_order(s->options.max_partition_order,
651 s->frame.blocksize, pred_order);
653 uint64_t bits = 8 + pred_order * sub->obits + 2 + 4;
654 if (sub->type == FLAC_SUBFRAME_LPC)
655 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
656 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
657 s->frame.blocksize, pred_order);
662 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
667 for (i = 0; i < order; i++)
671 for (i = order; i < n; i++)
673 } else if (order == 1) {
674 for (i = order; i < n; i++)
675 res[i] = smp[i] - smp[i-1];
676 } else if (order == 2) {
677 int a = smp[order-1] - smp[order-2];
678 for (i = order; i < n; i += 2) {
679 int b = smp[i ] - smp[i-1];
681 a = smp[i+1] - smp[i ];
684 } else if (order == 3) {
685 int a = smp[order-1] - smp[order-2];
686 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
687 for (i = order; i < n; i += 2) {
688 int b = smp[i ] - smp[i-1];
691 a = smp[i+1] - smp[i ];
696 int a = smp[order-1] - smp[order-2];
697 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
698 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
699 for (i = order; i < n; i += 2) {
700 int b = smp[i ] - smp[i-1];
704 a = smp[i+1] - smp[i ];
713 static int encode_residual_ch(FlacEncodeContext *s, int ch)
716 int min_order, max_order, opt_order, omethod;
719 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
720 int shift[MAX_LPC_ORDER];
724 sub = &frame->subframes[ch];
727 n = frame->blocksize;
730 for (i = 1; i < n; i++)
734 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
736 return subframe_count_exact(s, sub, 0);
740 if (frame->verbatim_only || n < 5) {
741 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
742 memcpy(res, smp, n * sizeof(int32_t));
743 return subframe_count_exact(s, sub, 0);
746 min_order = s->options.min_prediction_order;
747 max_order = s->options.max_prediction_order;
748 omethod = s->options.prediction_order_method;
751 sub->type = FLAC_SUBFRAME_FIXED;
752 if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
753 s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
754 uint64_t bits[MAX_FIXED_ORDER+1];
755 if (max_order > MAX_FIXED_ORDER)
756 max_order = MAX_FIXED_ORDER;
758 bits[0] = UINT32_MAX;
759 for (i = min_order; i <= max_order; i++) {
760 encode_residual_fixed(res, smp, n, i);
761 bits[i] = find_subframe_rice_params(s, sub, i);
762 if (bits[i] < bits[opt_order])
765 sub->order = opt_order;
766 sub->type_code = sub->type | sub->order;
767 if (sub->order != max_order) {
768 encode_residual_fixed(res, smp, n, sub->order);
769 find_subframe_rice_params(s, sub, sub->order);
771 return subframe_count_exact(s, sub, sub->order);
775 sub->type = FLAC_SUBFRAME_LPC;
776 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
777 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
778 s->options.lpc_passes, omethod,
781 if (omethod == ORDER_METHOD_2LEVEL ||
782 omethod == ORDER_METHOD_4LEVEL ||
783 omethod == ORDER_METHOD_8LEVEL) {
784 int levels = 1 << omethod;
785 uint64_t bits[1 << ORDER_METHOD_8LEVEL];
787 int opt_index = levels-1;
788 opt_order = max_order-1;
789 bits[opt_index] = UINT32_MAX;
790 for (i = levels-1; i >= 0; i--) {
791 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
794 s->flac_dsp.lpc_encode(res, smp, n, order+1, coefs[order],
796 bits[i] = find_subframe_rice_params(s, sub, order+1);
797 if (bits[i] < bits[opt_index]) {
803 } else if (omethod == ORDER_METHOD_SEARCH) {
804 // brute-force optimal order search
805 uint64_t bits[MAX_LPC_ORDER];
807 bits[0] = UINT32_MAX;
808 for (i = min_order-1; i < max_order; i++) {
809 s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
810 bits[i] = find_subframe_rice_params(s, sub, i+1);
811 if (bits[i] < bits[opt_order])
815 } else if (omethod == ORDER_METHOD_LOG) {
816 uint64_t bits[MAX_LPC_ORDER];
819 opt_order = min_order - 1 + (max_order-min_order)/3;
820 memset(bits, -1, sizeof(bits));
822 for (step = 16; step; step >>= 1) {
823 int last = opt_order;
824 for (i = last-step; i <= last+step; i += step) {
825 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
827 s->flac_dsp.lpc_encode(res, smp, n, i+1, coefs[i], shift[i]);
828 bits[i] = find_subframe_rice_params(s, sub, i+1);
829 if (bits[i] < bits[opt_order])
836 sub->order = opt_order;
837 sub->type_code = sub->type | (sub->order-1);
838 sub->shift = shift[sub->order-1];
839 for (i = 0; i < sub->order; i++)
840 sub->coefs[i] = coefs[sub->order-1][i];
842 s->flac_dsp.lpc_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
844 find_subframe_rice_params(s, sub, sub->order);
846 return subframe_count_exact(s, sub, sub->order);
850 static int count_frame_header(FlacEncodeContext *s)
852 uint8_t av_unused tmp;
858 <1> Blocking strategy
859 <4> Block size in inter-channel samples
861 <4> Channel assignment
862 <3> Sample size in bits
867 /* coded frame number */
868 PUT_UTF8(s->frame_count, tmp, count += 8;)
870 /* explicit block size */
871 if (s->frame.bs_code[0] == 6)
873 else if (s->frame.bs_code[0] == 7)
876 /* explicit sample rate */
877 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
879 /* frame header CRC-8 */
886 static int encode_frame(FlacEncodeContext *s)
891 count = count_frame_header(s);
893 for (ch = 0; ch < s->channels; ch++)
894 count += encode_residual_ch(s, ch);
896 count += (8 - (count & 7)) & 7; // byte alignment
897 count += 16; // CRC-16
906 static void remove_wasted_bits(FlacEncodeContext *s)
910 for (ch = 0; ch < s->channels; ch++) {
911 FlacSubframe *sub = &s->frame.subframes[ch];
914 for (i = 0; i < s->frame.blocksize; i++) {
915 v |= sub->samples[i];
923 for (i = 0; i < s->frame.blocksize; i++)
924 sub->samples[i] >>= v;
933 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
941 /* calculate sum of 2nd order residual for each channel */
942 sum[0] = sum[1] = sum[2] = sum[3] = 0;
943 for (i = 2; i < n; i++) {
944 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
945 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
946 sum[2] += FFABS((lt + rt) >> 1);
947 sum[3] += FFABS(lt - rt);
951 /* estimate bit counts */
952 for (i = 0; i < 4; i++) {
953 k = find_optimal_param(2 * sum[i], n);
954 sum[i] = rice_encode_count( 2 * sum[i], n, k);
957 /* calculate score for each mode */
958 score[0] = sum[0] + sum[1];
959 score[1] = sum[0] + sum[3];
960 score[2] = sum[1] + sum[3];
961 score[3] = sum[2] + sum[3];
963 /* return mode with lowest score */
965 for (i = 1; i < 4; i++)
966 if (score[i] < score[best])
974 * Perform stereo channel decorrelation.
976 static void channel_decorrelation(FlacEncodeContext *s)
979 int32_t *left, *right;
983 n = frame->blocksize;
984 left = frame->subframes[0].samples;
985 right = frame->subframes[1].samples;
987 if (s->channels != 2) {
988 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
992 if (s->options.ch_mode < 0)
993 frame->ch_mode = estimate_stereo_mode(left, right, n);
995 frame->ch_mode = s->options.ch_mode;
997 /* perform decorrelation and adjust bits-per-sample */
998 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1000 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1002 for (i = 0; i < n; i++) {
1004 left[i] = (tmp + right[i]) >> 1;
1005 right[i] = tmp - right[i];
1007 frame->subframes[1].obits++;
1008 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1009 for (i = 0; i < n; i++)
1010 right[i] = left[i] - right[i];
1011 frame->subframes[1].obits++;
1013 for (i = 0; i < n; i++)
1014 left[i] -= right[i];
1015 frame->subframes[0].obits++;
1020 static void write_utf8(PutBitContext *pb, uint32_t val)
1023 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1027 static void write_frame_header(FlacEncodeContext *s)
1034 put_bits(&s->pb, 16, 0xFFF8);
1035 put_bits(&s->pb, 4, frame->bs_code[0]);
1036 put_bits(&s->pb, 4, s->sr_code[0]);
1038 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1039 put_bits(&s->pb, 4, s->channels-1);
1041 put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
1043 put_bits(&s->pb, 3, s->bps_code);
1044 put_bits(&s->pb, 1, 0);
1045 write_utf8(&s->pb, s->frame_count);
1047 if (frame->bs_code[0] == 6)
1048 put_bits(&s->pb, 8, frame->bs_code[1]);
1049 else if (frame->bs_code[0] == 7)
1050 put_bits(&s->pb, 16, frame->bs_code[1]);
1052 if (s->sr_code[0] == 12)
1053 put_bits(&s->pb, 8, s->sr_code[1]);
1054 else if (s->sr_code[0] > 12)
1055 put_bits(&s->pb, 16, s->sr_code[1]);
1057 flush_put_bits(&s->pb);
1058 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1059 put_bits_count(&s->pb) >> 3);
1060 put_bits(&s->pb, 8, crc);
1064 static void write_subframes(FlacEncodeContext *s)
1068 for (ch = 0; ch < s->channels; ch++) {
1069 FlacSubframe *sub = &s->frame.subframes[ch];
1070 int i, p, porder, psize;
1072 int32_t *res = sub->residual;
1073 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1075 /* subframe header */
1076 put_bits(&s->pb, 1, 0);
1077 put_bits(&s->pb, 6, sub->type_code);
1078 put_bits(&s->pb, 1, !!sub->wasted);
1080 put_bits(&s->pb, sub->wasted, 1);
1083 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1084 put_sbits(&s->pb, sub->obits, res[0]);
1085 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1086 while (res < frame_end)
1087 put_sbits(&s->pb, sub->obits, *res++);
1089 /* warm-up samples */
1090 for (i = 0; i < sub->order; i++)
1091 put_sbits(&s->pb, sub->obits, *res++);
1093 /* LPC coefficients */
1094 if (sub->type == FLAC_SUBFRAME_LPC) {
1095 int cbits = s->options.lpc_coeff_precision;
1096 put_bits( &s->pb, 4, cbits-1);
1097 put_sbits(&s->pb, 5, sub->shift);
1098 for (i = 0; i < sub->order; i++)
1099 put_sbits(&s->pb, cbits, sub->coefs[i]);
1102 /* rice-encoded block */
1103 put_bits(&s->pb, 2, 0);
1105 /* partition order */
1106 porder = sub->rc.porder;
1107 psize = s->frame.blocksize >> porder;
1108 put_bits(&s->pb, 4, porder);
1111 part_end = &sub->residual[psize];
1112 for (p = 0; p < 1 << porder; p++) {
1113 int k = sub->rc.params[p];
1114 put_bits(&s->pb, 4, k);
1115 while (res < part_end)
1116 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1117 part_end = FFMIN(frame_end, part_end + psize);
1124 static void write_frame_footer(FlacEncodeContext *s)
1127 flush_put_bits(&s->pb);
1128 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1129 put_bits_count(&s->pb)>>3));
1130 put_bits(&s->pb, 16, crc);
1131 flush_put_bits(&s->pb);
1135 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1137 init_put_bits(&s->pb, avpkt->data, avpkt->size);
1138 write_frame_header(s);
1140 write_frame_footer(s);
1141 return put_bits_count(&s->pb) >> 3;
1145 static int update_md5_sum(FlacEncodeContext *s, const void *samples)
1148 int buf_size = s->frame.blocksize * s->channels *
1149 ((s->avctx->bits_per_raw_sample + 7) / 8);
1151 if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
1152 av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
1154 return AVERROR(ENOMEM);
1157 if (s->avctx->bits_per_raw_sample <= 16) {
1158 buf = (const uint8_t *)samples;
1160 s->dsp.bswap16_buf((uint16_t *)s->md5_buffer,
1161 (const uint16_t *)samples, buf_size / 2);
1162 buf = s->md5_buffer;
1166 const int32_t *samples0 = samples;
1167 uint8_t *tmp = s->md5_buffer;
1169 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1170 int32_t v = samples0[i] >> 8;
1171 *tmp++ = (v ) & 0xFF;
1172 *tmp++ = (v >> 8) & 0xFF;
1173 *tmp++ = (v >> 16) & 0xFF;
1175 buf = s->md5_buffer;
1177 av_md5_update(s->md5ctx, buf, buf_size);
1183 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1184 const AVFrame *frame, int *got_packet_ptr)
1186 FlacEncodeContext *s;
1187 int frame_bytes, out_bytes, ret;
1189 s = avctx->priv_data;
1191 /* when the last block is reached, update the header in extradata */
1193 s->max_framesize = s->max_encoded_framesize;
1194 av_md5_final(s->md5ctx, s->md5sum);
1195 write_streaminfo(s, avctx->extradata);
1199 /* change max_framesize for small final frame */
1200 if (frame->nb_samples < s->frame.blocksize) {
1201 s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
1203 avctx->bits_per_raw_sample);
1206 init_frame(s, frame->nb_samples);
1208 copy_samples(s, frame->data[0]);
1210 channel_decorrelation(s);
1212 remove_wasted_bits(s);
1214 frame_bytes = encode_frame(s);
1216 /* fallback to verbatim mode if the compressed frame is larger than it
1217 would be if encoded uncompressed. */
1218 if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
1219 s->frame.verbatim_only = 1;
1220 frame_bytes = encode_frame(s);
1221 if (frame_bytes < 0) {
1222 av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
1227 if ((ret = ff_alloc_packet(avpkt, frame_bytes))) {
1228 av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
1232 out_bytes = write_frame(s, avpkt);
1235 s->sample_count += frame->nb_samples;
1236 if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
1237 av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
1240 if (out_bytes > s->max_encoded_framesize)
1241 s->max_encoded_framesize = out_bytes;
1242 if (out_bytes < s->min_framesize)
1243 s->min_framesize = out_bytes;
1245 avpkt->pts = frame->pts;
1246 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1247 avpkt->size = out_bytes;
1248 *got_packet_ptr = 1;
1253 static av_cold int flac_encode_close(AVCodecContext *avctx)
1255 if (avctx->priv_data) {
1256 FlacEncodeContext *s = avctx->priv_data;
1257 av_freep(&s->md5ctx);
1258 av_freep(&s->md5_buffer);
1259 ff_lpc_end(&s->lpc_ctx);
1261 av_freep(&avctx->extradata);
1262 avctx->extradata_size = 0;
1263 #if FF_API_OLD_ENCODE_AUDIO
1264 av_freep(&avctx->coded_frame);
1269 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1270 static const AVOption options[] = {
1271 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1272 { "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" },
1273 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1274 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1275 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1276 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1277 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes), AV_OPT_TYPE_INT, {.i64 = -1 }, INT_MIN, INT_MAX, FLAGS },
1278 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1279 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1280 { "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" },
1281 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1282 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1283 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1284 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1285 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1286 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1287 { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
1288 { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1289 { "indep", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1290 { "left_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1291 { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1292 { "mid_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1296 static const AVClass flac_encoder_class = {
1298 av_default_item_name,
1300 LIBAVUTIL_VERSION_INT,
1303 AVCodec ff_flac_encoder = {
1305 .type = AVMEDIA_TYPE_AUDIO,
1306 .id = AV_CODEC_ID_FLAC,
1307 .priv_data_size = sizeof(FlacEncodeContext),
1308 .init = flac_encode_init,
1309 .encode2 = flac_encode_frame,
1310 .close = flac_encode_close,
1311 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1312 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1314 AV_SAMPLE_FMT_NONE },
1315 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1316 .priv_class = &flac_encoder_class,