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/md5.h"
24 #include "libavutil/opt.h"
33 #define FLAC_SUBFRAME_CONSTANT 0
34 #define FLAC_SUBFRAME_VERBATIM 1
35 #define FLAC_SUBFRAME_FIXED 8
36 #define FLAC_SUBFRAME_LPC 32
38 #define MAX_FIXED_ORDER 4
39 #define MAX_PARTITION_ORDER 8
40 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
41 #define MAX_LPC_PRECISION 15
42 #define MAX_LPC_SHIFT 15
43 #define MAX_RICE_PARAM 14
45 typedef struct CompressionOptions {
46 int compression_level;
48 enum FFLPCType lpc_type;
50 int lpc_coeff_precision;
51 int min_prediction_order;
52 int max_prediction_order;
53 int prediction_order_method;
54 int min_partition_order;
55 int max_partition_order;
58 typedef struct RiceContext {
60 int params[MAX_PARTITIONS];
63 typedef struct FlacSubframe {
68 int32_t coefs[MAX_LPC_ORDER];
71 int32_t samples[FLAC_MAX_BLOCKSIZE];
72 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
75 typedef struct FlacFrame {
76 FlacSubframe subframes[FLAC_MAX_CHANNELS];
84 typedef struct FlacEncodeContext {
93 int max_encoded_framesize;
95 uint64_t sample_count;
98 CompressionOptions options;
99 AVCodecContext *avctx;
101 struct AVMD5 *md5ctx;
106 * Write streaminfo metadata block to byte array.
108 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
112 memset(header, 0, FLAC_STREAMINFO_SIZE);
113 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
115 /* streaminfo metadata block */
116 put_bits(&pb, 16, s->max_blocksize);
117 put_bits(&pb, 16, s->max_blocksize);
118 put_bits(&pb, 24, s->min_framesize);
119 put_bits(&pb, 24, s->max_framesize);
120 put_bits(&pb, 20, s->samplerate);
121 put_bits(&pb, 3, s->channels-1);
122 put_bits(&pb, 5, 15); /* bits per sample - 1 */
123 /* write 36-bit sample count in 2 put_bits() calls */
124 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
125 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
127 memcpy(&header[18], s->md5sum, 16);
132 * Set blocksize based on samplerate.
133 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
135 static int select_blocksize(int samplerate, int block_time_ms)
141 assert(samplerate > 0);
142 blocksize = ff_flac_blocksize_table[1];
143 target = (samplerate * block_time_ms) / 1000;
144 for (i = 0; i < 16; i++) {
145 if (target >= ff_flac_blocksize_table[i] &&
146 ff_flac_blocksize_table[i] > blocksize) {
147 blocksize = ff_flac_blocksize_table[i];
154 static av_cold void dprint_compression_options(FlacEncodeContext *s)
156 AVCodecContext *avctx = s->avctx;
157 CompressionOptions *opt = &s->options;
159 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
161 switch (opt->lpc_type) {
162 case FF_LPC_TYPE_NONE:
163 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
165 case FF_LPC_TYPE_FIXED:
166 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
168 case FF_LPC_TYPE_LEVINSON:
169 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
171 case FF_LPC_TYPE_CHOLESKY:
172 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
173 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
177 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
178 opt->min_prediction_order, opt->max_prediction_order);
180 switch (opt->prediction_order_method) {
181 case ORDER_METHOD_EST:
182 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
184 case ORDER_METHOD_2LEVEL:
185 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
187 case ORDER_METHOD_4LEVEL:
188 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
190 case ORDER_METHOD_8LEVEL:
191 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
193 case ORDER_METHOD_SEARCH:
194 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
196 case ORDER_METHOD_LOG:
197 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
202 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
203 opt->min_partition_order, opt->max_partition_order);
205 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
207 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
208 opt->lpc_coeff_precision);
212 static av_cold int flac_encode_init(AVCodecContext *avctx)
214 int freq = avctx->sample_rate;
215 int channels = avctx->channels;
216 FlacEncodeContext *s = avctx->priv_data;
222 if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
225 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
227 s->channels = channels;
229 /* find samplerate in table */
232 for (i = 4; i < 12; i++) {
233 if (freq == ff_flac_sample_rate_table[i]) {
234 s->samplerate = ff_flac_sample_rate_table[i];
240 /* if not in table, samplerate is non-standard */
242 if (freq % 1000 == 0 && freq < 255000) {
244 s->sr_code[1] = freq / 1000;
245 } else if (freq % 10 == 0 && freq < 655350) {
247 s->sr_code[1] = freq / 10;
248 } else if (freq < 65535) {
250 s->sr_code[1] = freq;
254 s->samplerate = freq;
257 /* set compression option defaults based on avctx->compression_level */
258 if (avctx->compression_level < 0)
259 s->options.compression_level = 5;
261 s->options.compression_level = avctx->compression_level;
263 level = s->options.compression_level;
265 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
266 s->options.compression_level);
270 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
272 if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
273 s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
274 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
275 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
276 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
277 FF_LPC_TYPE_LEVINSON})[level];
279 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
280 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
282 if (s->options.prediction_order_method < 0)
283 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
284 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
285 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
286 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
287 ORDER_METHOD_SEARCH})[level];
289 if (s->options.min_partition_order > s->options.max_partition_order) {
290 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
291 s->options.min_partition_order, s->options.max_partition_order);
292 return AVERROR(EINVAL);
294 if (s->options.min_partition_order < 0)
295 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
296 if (s->options.max_partition_order < 0)
297 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
299 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
300 s->options.min_prediction_order = 0;
301 } else if (avctx->min_prediction_order >= 0) {
302 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
303 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
304 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
305 avctx->min_prediction_order);
308 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
309 avctx->min_prediction_order > MAX_LPC_ORDER) {
310 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
311 avctx->min_prediction_order);
314 s->options.min_prediction_order = avctx->min_prediction_order;
316 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
317 s->options.max_prediction_order = 0;
318 } else if (avctx->max_prediction_order >= 0) {
319 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
320 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
321 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
322 avctx->max_prediction_order);
325 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
326 avctx->max_prediction_order > MAX_LPC_ORDER) {
327 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
328 avctx->max_prediction_order);
331 s->options.max_prediction_order = avctx->max_prediction_order;
333 if (s->options.max_prediction_order < s->options.min_prediction_order) {
334 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
335 s->options.min_prediction_order, s->options.max_prediction_order);
339 if (avctx->frame_size > 0) {
340 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
341 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
342 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
347 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
349 s->max_blocksize = s->avctx->frame_size;
351 /* set maximum encoded frame size in verbatim mode */
352 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
355 /* initialize MD5 context */
356 s->md5ctx = av_malloc(av_md5_size);
358 return AVERROR(ENOMEM);
359 av_md5_init(s->md5ctx);
361 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
363 return AVERROR(ENOMEM);
364 write_streaminfo(s, streaminfo);
365 avctx->extradata = streaminfo;
366 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
369 s->min_framesize = s->max_framesize;
371 #if FF_API_OLD_ENCODE_AUDIO
372 avctx->coded_frame = avcodec_alloc_frame();
373 if (!avctx->coded_frame)
374 return AVERROR(ENOMEM);
377 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
378 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
380 dprint_compression_options(s);
386 static void init_frame(FlacEncodeContext *s, int nb_samples)
393 for (i = 0; i < 16; i++) {
394 if (nb_samples == ff_flac_blocksize_table[i]) {
395 frame->blocksize = ff_flac_blocksize_table[i];
396 frame->bs_code[0] = i;
397 frame->bs_code[1] = 0;
402 frame->blocksize = nb_samples;
403 if (frame->blocksize <= 256) {
404 frame->bs_code[0] = 6;
405 frame->bs_code[1] = frame->blocksize-1;
407 frame->bs_code[0] = 7;
408 frame->bs_code[1] = frame->blocksize-1;
412 for (ch = 0; ch < s->channels; ch++)
413 frame->subframes[ch].obits = 16;
415 frame->verbatim_only = 0;
420 * Copy channel-interleaved input samples into separate subframes.
422 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
428 for (i = 0, j = 0; i < frame->blocksize; i++)
429 for (ch = 0; ch < s->channels; ch++, j++)
430 frame->subframes[ch].samples[i] = samples[j];
434 static int rice_count_exact(int32_t *res, int n, int k)
439 for (i = 0; i < n; i++) {
440 int32_t v = -2 * res[i] - 1;
442 count += (v >> k) + 1 + k;
448 static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
451 int p, porder, psize;
455 /* subframe header */
459 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
461 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
462 count += s->frame.blocksize * sub->obits;
464 /* warm-up samples */
465 count += pred_order * sub->obits;
467 /* LPC coefficients */
468 if (sub->type == FLAC_SUBFRAME_LPC)
469 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
471 /* rice-encoded block */
474 /* partition order */
475 porder = sub->rc.porder;
476 psize = s->frame.blocksize >> porder;
482 for (p = 0; p < 1 << porder; p++) {
483 int k = sub->rc.params[p];
485 count += rice_count_exact(&sub->residual[i], part_end - i, k);
487 part_end = FFMIN(s->frame.blocksize, part_end + psize);
495 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
498 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
500 static int find_optimal_param(uint32_t sum, int n)
507 sum2 = sum - (n >> 1);
508 k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
509 return FFMIN(k, MAX_RICE_PARAM);
513 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
514 uint32_t *sums, int n, int pred_order)
520 part = (1 << porder);
523 cnt = (n >> porder) - pred_order;
524 for (i = 0; i < part; i++) {
525 k = find_optimal_param(sums[i], cnt);
527 all_bits += rice_encode_count(sums[i], cnt, k);
537 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
538 uint32_t sums[][MAX_PARTITIONS])
542 uint32_t *res, *res_end;
544 /* sums for highest level */
546 res = &data[pred_order];
547 res_end = &data[n >> pmax];
548 for (i = 0; i < parts; i++) {
550 while (res < res_end)
553 res_end += n >> pmax;
555 /* sums for lower levels */
556 for (i = pmax - 1; i >= pmin; i--) {
558 for (j = 0; j < parts; j++)
559 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
564 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
565 int32_t *data, int n, int pred_order)
568 uint32_t bits[MAX_PARTITION_ORDER+1];
572 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
574 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
575 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
576 assert(pmin <= pmax);
578 udata = av_malloc(n * sizeof(uint32_t));
579 for (i = 0; i < n; i++)
580 udata[i] = (2*data[i]) ^ (data[i]>>31);
582 calc_sums(pmin, pmax, udata, n, pred_order, sums);
585 bits[pmin] = UINT32_MAX;
586 for (i = pmin; i <= pmax; i++) {
587 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
588 if (bits[i] <= bits[opt_porder]) {
595 return bits[opt_porder];
599 static int get_max_p_order(int max_porder, int n, int order)
601 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
603 porder = FFMIN(porder, av_log2(n/order));
608 static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
609 FlacSubframe *sub, int pred_order)
611 int pmin = get_max_p_order(s->options.min_partition_order,
612 s->frame.blocksize, pred_order);
613 int pmax = get_max_p_order(s->options.max_partition_order,
614 s->frame.blocksize, pred_order);
616 uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
617 if (sub->type == FLAC_SUBFRAME_LPC)
618 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
619 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
620 s->frame.blocksize, pred_order);
625 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
630 for (i = 0; i < order; i++)
634 for (i = order; i < n; i++)
636 } else if (order == 1) {
637 for (i = order; i < n; i++)
638 res[i] = smp[i] - smp[i-1];
639 } else if (order == 2) {
640 int a = smp[order-1] - smp[order-2];
641 for (i = order; i < n; i += 2) {
642 int b = smp[i ] - smp[i-1];
644 a = smp[i+1] - smp[i ];
647 } else if (order == 3) {
648 int a = smp[order-1] - smp[order-2];
649 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
650 for (i = order; i < n; i += 2) {
651 int b = smp[i ] - smp[i-1];
654 a = smp[i+1] - smp[i ];
659 int a = smp[order-1] - smp[order-2];
660 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
661 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
662 for (i = order; i < n; i += 2) {
663 int b = smp[i ] - smp[i-1];
667 a = smp[i+1] - smp[i ];
677 int c = coefs[(x)-1];\
683 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
684 const int32_t *smp, int n, int order,
685 const int32_t *coefs, int shift, int big)
688 for (i = order; i < n; i += 2) {
689 int s = smp[i-order];
738 res[i ] = smp[i ] - (p0 >> shift);
739 res[i+1] = smp[i+1] - (p1 >> shift);
744 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
745 int order, const int32_t *coefs, int shift)
748 for (i = 0; i < order; i++)
751 for (i = order; i < n; i += 2) {
755 for (j = 0; j < order; j++) {
761 res[i ] = smp[i ] - (p0 >> shift);
762 res[i+1] = smp[i+1] - (p1 >> shift);
766 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
767 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
768 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
769 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
770 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
771 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
772 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
773 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
774 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
780 static int encode_residual_ch(FlacEncodeContext *s, int ch)
783 int min_order, max_order, opt_order, omethod;
786 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
787 int shift[MAX_LPC_ORDER];
791 sub = &frame->subframes[ch];
794 n = frame->blocksize;
797 for (i = 1; i < n; i++)
801 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
803 return subframe_count_exact(s, sub, 0);
807 if (frame->verbatim_only || n < 5) {
808 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
809 memcpy(res, smp, n * sizeof(int32_t));
810 return subframe_count_exact(s, sub, 0);
813 min_order = s->options.min_prediction_order;
814 max_order = s->options.max_prediction_order;
815 omethod = s->options.prediction_order_method;
818 sub->type = FLAC_SUBFRAME_FIXED;
819 if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
820 s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
821 uint32_t bits[MAX_FIXED_ORDER+1];
822 if (max_order > MAX_FIXED_ORDER)
823 max_order = MAX_FIXED_ORDER;
825 bits[0] = UINT32_MAX;
826 for (i = min_order; i <= max_order; i++) {
827 encode_residual_fixed(res, smp, n, i);
828 bits[i] = find_subframe_rice_params(s, sub, i);
829 if (bits[i] < bits[opt_order])
832 sub->order = opt_order;
833 sub->type_code = sub->type | sub->order;
834 if (sub->order != max_order) {
835 encode_residual_fixed(res, smp, n, sub->order);
836 find_subframe_rice_params(s, sub, sub->order);
838 return subframe_count_exact(s, sub, sub->order);
842 sub->type = FLAC_SUBFRAME_LPC;
843 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
844 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
845 s->options.lpc_passes, omethod,
848 if (omethod == ORDER_METHOD_2LEVEL ||
849 omethod == ORDER_METHOD_4LEVEL ||
850 omethod == ORDER_METHOD_8LEVEL) {
851 int levels = 1 << omethod;
852 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
854 int opt_index = levels-1;
855 opt_order = max_order-1;
856 bits[opt_index] = UINT32_MAX;
857 for (i = levels-1; i >= 0; i--) {
858 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
861 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
862 bits[i] = find_subframe_rice_params(s, sub, order+1);
863 if (bits[i] < bits[opt_index]) {
869 } else if (omethod == ORDER_METHOD_SEARCH) {
870 // brute-force optimal order search
871 uint32_t bits[MAX_LPC_ORDER];
873 bits[0] = UINT32_MAX;
874 for (i = min_order-1; i < max_order; i++) {
875 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
876 bits[i] = find_subframe_rice_params(s, sub, i+1);
877 if (bits[i] < bits[opt_order])
881 } else if (omethod == ORDER_METHOD_LOG) {
882 uint32_t bits[MAX_LPC_ORDER];
885 opt_order = min_order - 1 + (max_order-min_order)/3;
886 memset(bits, -1, sizeof(bits));
888 for (step = 16; step; step >>= 1) {
889 int last = opt_order;
890 for (i = last-step; i <= last+step; i += step) {
891 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
893 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
894 bits[i] = find_subframe_rice_params(s, sub, i+1);
895 if (bits[i] < bits[opt_order])
902 sub->order = opt_order;
903 sub->type_code = sub->type | (sub->order-1);
904 sub->shift = shift[sub->order-1];
905 for (i = 0; i < sub->order; i++)
906 sub->coefs[i] = coefs[sub->order-1][i];
908 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
910 find_subframe_rice_params(s, sub, sub->order);
912 return subframe_count_exact(s, sub, sub->order);
916 static int count_frame_header(FlacEncodeContext *s)
918 uint8_t av_unused tmp;
924 <1> Blocking strategy
925 <4> Block size in inter-channel samples
927 <4> Channel assignment
928 <3> Sample size in bits
933 /* coded frame number */
934 PUT_UTF8(s->frame_count, tmp, count += 8;)
936 /* explicit block size */
937 if (s->frame.bs_code[0] == 6)
939 else if (s->frame.bs_code[0] == 7)
942 /* explicit sample rate */
943 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
945 /* frame header CRC-8 */
952 static int encode_frame(FlacEncodeContext *s)
956 count = count_frame_header(s);
958 for (ch = 0; ch < s->channels; ch++)
959 count += encode_residual_ch(s, ch);
961 count += (8 - (count & 7)) & 7; // byte alignment
962 count += 16; // CRC-16
968 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
976 /* calculate sum of 2nd order residual for each channel */
977 sum[0] = sum[1] = sum[2] = sum[3] = 0;
978 for (i = 2; i < n; i++) {
979 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
980 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
981 sum[2] += FFABS((lt + rt) >> 1);
982 sum[3] += FFABS(lt - rt);
986 /* estimate bit counts */
987 for (i = 0; i < 4; i++) {
988 k = find_optimal_param(2 * sum[i], n);
989 sum[i] = rice_encode_count( 2 * sum[i], n, k);
992 /* calculate score for each mode */
993 score[0] = sum[0] + sum[1];
994 score[1] = sum[0] + sum[3];
995 score[2] = sum[1] + sum[3];
996 score[3] = sum[2] + sum[3];
998 /* return mode with lowest score */
1000 for (i = 1; i < 4; i++)
1001 if (score[i] < score[best])
1004 return FLAC_CHMODE_INDEPENDENT;
1005 } else if (best == 1) {
1006 return FLAC_CHMODE_LEFT_SIDE;
1007 } else if (best == 2) {
1008 return FLAC_CHMODE_RIGHT_SIDE;
1010 return FLAC_CHMODE_MID_SIDE;
1016 * Perform stereo channel decorrelation.
1018 static void channel_decorrelation(FlacEncodeContext *s)
1021 int32_t *left, *right;
1025 n = frame->blocksize;
1026 left = frame->subframes[0].samples;
1027 right = frame->subframes[1].samples;
1029 if (s->channels != 2) {
1030 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1034 frame->ch_mode = estimate_stereo_mode(left, right, n);
1036 /* perform decorrelation and adjust bits-per-sample */
1037 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1039 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1041 for (i = 0; i < n; i++) {
1043 left[i] = (tmp + right[i]) >> 1;
1044 right[i] = tmp - right[i];
1046 frame->subframes[1].obits++;
1047 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1048 for (i = 0; i < n; i++)
1049 right[i] = left[i] - right[i];
1050 frame->subframes[1].obits++;
1052 for (i = 0; i < n; i++)
1053 left[i] -= right[i];
1054 frame->subframes[0].obits++;
1059 static void write_utf8(PutBitContext *pb, uint32_t val)
1062 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1066 static void write_frame_header(FlacEncodeContext *s)
1073 put_bits(&s->pb, 16, 0xFFF8);
1074 put_bits(&s->pb, 4, frame->bs_code[0]);
1075 put_bits(&s->pb, 4, s->sr_code[0]);
1077 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1078 put_bits(&s->pb, 4, s->channels-1);
1080 put_bits(&s->pb, 4, frame->ch_mode);
1082 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1083 put_bits(&s->pb, 1, 0);
1084 write_utf8(&s->pb, s->frame_count);
1086 if (frame->bs_code[0] == 6)
1087 put_bits(&s->pb, 8, frame->bs_code[1]);
1088 else if (frame->bs_code[0] == 7)
1089 put_bits(&s->pb, 16, frame->bs_code[1]);
1091 if (s->sr_code[0] == 12)
1092 put_bits(&s->pb, 8, s->sr_code[1]);
1093 else if (s->sr_code[0] > 12)
1094 put_bits(&s->pb, 16, s->sr_code[1]);
1096 flush_put_bits(&s->pb);
1097 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1098 put_bits_count(&s->pb) >> 3);
1099 put_bits(&s->pb, 8, crc);
1103 static void write_subframes(FlacEncodeContext *s)
1107 for (ch = 0; ch < s->channels; ch++) {
1108 FlacSubframe *sub = &s->frame.subframes[ch];
1109 int i, p, porder, psize;
1111 int32_t *res = sub->residual;
1112 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1114 /* subframe header */
1115 put_bits(&s->pb, 1, 0);
1116 put_bits(&s->pb, 6, sub->type_code);
1117 put_bits(&s->pb, 1, 0); /* no wasted bits */
1120 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1121 put_sbits(&s->pb, sub->obits, res[0]);
1122 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1123 while (res < frame_end)
1124 put_sbits(&s->pb, sub->obits, *res++);
1126 /* warm-up samples */
1127 for (i = 0; i < sub->order; i++)
1128 put_sbits(&s->pb, sub->obits, *res++);
1130 /* LPC coefficients */
1131 if (sub->type == FLAC_SUBFRAME_LPC) {
1132 int cbits = s->options.lpc_coeff_precision;
1133 put_bits( &s->pb, 4, cbits-1);
1134 put_sbits(&s->pb, 5, sub->shift);
1135 for (i = 0; i < sub->order; i++)
1136 put_sbits(&s->pb, cbits, sub->coefs[i]);
1139 /* rice-encoded block */
1140 put_bits(&s->pb, 2, 0);
1142 /* partition order */
1143 porder = sub->rc.porder;
1144 psize = s->frame.blocksize >> porder;
1145 put_bits(&s->pb, 4, porder);
1148 part_end = &sub->residual[psize];
1149 for (p = 0; p < 1 << porder; p++) {
1150 int k = sub->rc.params[p];
1151 put_bits(&s->pb, 4, k);
1152 while (res < part_end)
1153 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1154 part_end = FFMIN(frame_end, part_end + psize);
1161 static void write_frame_footer(FlacEncodeContext *s)
1164 flush_put_bits(&s->pb);
1165 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1166 put_bits_count(&s->pb)>>3));
1167 put_bits(&s->pb, 16, crc);
1168 flush_put_bits(&s->pb);
1172 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1174 init_put_bits(&s->pb, avpkt->data, avpkt->size);
1175 write_frame_header(s);
1177 write_frame_footer(s);
1178 return put_bits_count(&s->pb) >> 3;
1182 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1186 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1187 int16_t smp = av_le2ne16(samples[i]);
1188 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1191 av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1196 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1197 const AVFrame *frame, int *got_packet_ptr)
1199 FlacEncodeContext *s;
1200 const int16_t *samples;
1201 int frame_bytes, out_bytes, ret;
1203 s = avctx->priv_data;
1205 /* when the last block is reached, update the header in extradata */
1207 s->max_framesize = s->max_encoded_framesize;
1208 av_md5_final(s->md5ctx, s->md5sum);
1209 write_streaminfo(s, avctx->extradata);
1212 samples = (const int16_t *)frame->data[0];
1214 /* change max_framesize for small final frame */
1215 if (frame->nb_samples < s->frame.blocksize) {
1216 s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
1220 init_frame(s, frame->nb_samples);
1222 copy_samples(s, samples);
1224 channel_decorrelation(s);
1226 frame_bytes = encode_frame(s);
1228 /* fallback to verbatim mode if the compressed frame is larger than it
1229 would be if encoded uncompressed. */
1230 if (frame_bytes > s->max_framesize) {
1231 s->frame.verbatim_only = 1;
1232 frame_bytes = encode_frame(s);
1235 if ((ret = ff_alloc_packet(avpkt, frame_bytes))) {
1236 av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
1240 out_bytes = write_frame(s, avpkt);
1243 s->sample_count += frame->nb_samples;
1244 update_md5_sum(s, samples);
1245 if (out_bytes > s->max_encoded_framesize)
1246 s->max_encoded_framesize = out_bytes;
1247 if (out_bytes < s->min_framesize)
1248 s->min_framesize = out_bytes;
1250 avpkt->pts = frame->pts;
1251 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1252 avpkt->size = out_bytes;
1253 *got_packet_ptr = 1;
1258 static av_cold int flac_encode_close(AVCodecContext *avctx)
1260 if (avctx->priv_data) {
1261 FlacEncodeContext *s = avctx->priv_data;
1262 av_freep(&s->md5ctx);
1263 ff_lpc_end(&s->lpc_ctx);
1265 av_freep(&avctx->extradata);
1266 avctx->extradata_size = 0;
1267 #if FF_API_OLD_ENCODE_AUDIO
1268 av_freep(&avctx->coded_frame);
1273 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1274 static const AVOption options[] = {
1275 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.dbl = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1276 { "lpc_type", "LPC algorithm", offsetof(FlacEncodeContext, options.lpc_type), AV_OPT_TYPE_INT, {.dbl = FF_LPC_TYPE_DEFAULT }, FF_LPC_TYPE_DEFAULT, FF_LPC_TYPE_NB-1, FLAGS, "lpc_type" },
1277 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1278 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1279 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1280 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1281 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, FLAGS },
1282 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1283 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1284 { "prediction_order_method", "Search method for selecting prediction order", offsetof(FlacEncodeContext, options.prediction_order_method), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, ORDER_METHOD_LOG, FLAGS, "predm" },
1285 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1286 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1287 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1288 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1289 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1290 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1294 static const AVClass flac_encoder_class = {
1296 av_default_item_name,
1298 LIBAVUTIL_VERSION_INT,
1301 AVCodec ff_flac_encoder = {
1303 .type = AVMEDIA_TYPE_AUDIO,
1304 .id = CODEC_ID_FLAC,
1305 .priv_data_size = sizeof(FlacEncodeContext),
1306 .init = flac_encode_init,
1307 .encode2 = flac_encode_frame,
1308 .close = flac_encode_close,
1309 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1310 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1311 AV_SAMPLE_FMT_NONE },
1312 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1313 .priv_class = &flac_encoder_class,