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"
31 #define FLAC_SUBFRAME_CONSTANT 0
32 #define FLAC_SUBFRAME_VERBATIM 1
33 #define FLAC_SUBFRAME_FIXED 8
34 #define FLAC_SUBFRAME_LPC 32
36 #define MAX_FIXED_ORDER 4
37 #define MAX_PARTITION_ORDER 8
38 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
39 #define MAX_LPC_PRECISION 15
40 #define MAX_LPC_SHIFT 15
41 #define MAX_RICE_PARAM 14
43 typedef struct CompressionOptions {
44 int compression_level;
46 enum AVLPCType lpc_type;
48 int lpc_coeff_precision;
49 int min_prediction_order;
50 int max_prediction_order;
51 int prediction_order_method;
52 int min_partition_order;
53 int max_partition_order;
56 typedef struct RiceContext {
58 int params[MAX_PARTITIONS];
61 typedef struct FlacSubframe {
66 int32_t coefs[MAX_LPC_ORDER];
69 int32_t samples[FLAC_MAX_BLOCKSIZE];
70 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
73 typedef struct FlacFrame {
74 FlacSubframe subframes[FLAC_MAX_CHANNELS];
82 typedef struct FlacEncodeContext {
90 int max_encoded_framesize;
92 uint64_t sample_count;
95 CompressionOptions options;
96 AVCodecContext *avctx;
103 * Write streaminfo metadata block to byte array.
105 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
109 memset(header, 0, FLAC_STREAMINFO_SIZE);
110 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
112 /* streaminfo metadata block */
113 put_bits(&pb, 16, s->max_blocksize);
114 put_bits(&pb, 16, s->max_blocksize);
115 put_bits(&pb, 24, s->min_framesize);
116 put_bits(&pb, 24, s->max_framesize);
117 put_bits(&pb, 20, s->samplerate);
118 put_bits(&pb, 3, s->channels-1);
119 put_bits(&pb, 5, 15); /* bits per sample - 1 */
120 /* write 36-bit sample count in 2 put_bits() calls */
121 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
122 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
124 memcpy(&header[18], s->md5sum, 16);
129 * Set blocksize based on samplerate.
130 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
132 static int select_blocksize(int samplerate, int block_time_ms)
138 assert(samplerate > 0);
139 blocksize = ff_flac_blocksize_table[1];
140 target = (samplerate * block_time_ms) / 1000;
141 for (i = 0; i < 16; i++) {
142 if (target >= ff_flac_blocksize_table[i] &&
143 ff_flac_blocksize_table[i] > blocksize) {
144 blocksize = ff_flac_blocksize_table[i];
151 static av_cold void dprint_compression_options(FlacEncodeContext *s)
153 AVCodecContext *avctx = s->avctx;
154 CompressionOptions *opt = &s->options;
156 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
158 switch (opt->lpc_type) {
159 case AV_LPC_TYPE_NONE:
160 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
162 case AV_LPC_TYPE_FIXED:
163 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
165 case AV_LPC_TYPE_LEVINSON:
166 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
168 case AV_LPC_TYPE_CHOLESKY:
169 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
170 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
174 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
175 opt->min_prediction_order, opt->max_prediction_order);
177 switch (opt->prediction_order_method) {
178 case ORDER_METHOD_EST:
179 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
181 case ORDER_METHOD_2LEVEL:
182 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
184 case ORDER_METHOD_4LEVEL:
185 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
187 case ORDER_METHOD_8LEVEL:
188 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
190 case ORDER_METHOD_SEARCH:
191 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
193 case ORDER_METHOD_LOG:
194 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
199 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
200 opt->min_partition_order, opt->max_partition_order);
202 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
204 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
205 opt->lpc_coeff_precision);
209 static av_cold int flac_encode_init(AVCodecContext *avctx)
211 int freq = avctx->sample_rate;
212 int channels = avctx->channels;
213 FlacEncodeContext *s = avctx->priv_data;
219 if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
222 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
224 s->channels = channels;
226 /* find samplerate in table */
229 for (i = 4; i < 12; i++) {
230 if (freq == ff_flac_sample_rate_table[i]) {
231 s->samplerate = ff_flac_sample_rate_table[i];
237 /* if not in table, samplerate is non-standard */
239 if (freq % 1000 == 0 && freq < 255000) {
241 s->sr_code[1] = freq / 1000;
242 } else if (freq % 10 == 0 && freq < 655350) {
244 s->sr_code[1] = freq / 10;
245 } else if (freq < 65535) {
247 s->sr_code[1] = freq;
251 s->samplerate = freq;
254 /* set compression option defaults based on avctx->compression_level */
255 if (avctx->compression_level < 0)
256 s->options.compression_level = 5;
258 s->options.compression_level = avctx->compression_level;
260 level = s->options.compression_level;
262 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
263 s->options.compression_level);
267 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
269 s->options.lpc_type = ((int[]){ AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED,
270 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
271 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
272 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
273 AV_LPC_TYPE_LEVINSON})[level];
275 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
276 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
278 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
279 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
280 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
281 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
282 ORDER_METHOD_SEARCH})[level];
284 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
285 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
287 /* set compression option overrides from AVCodecContext */
288 if (avctx->lpc_type > AV_LPC_TYPE_DEFAULT) {
289 if (avctx->lpc_type > AV_LPC_TYPE_CHOLESKY) {
290 av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
293 s->options.lpc_type = avctx->lpc_type;
294 if (s->options.lpc_type == AV_LPC_TYPE_CHOLESKY) {
295 if (avctx->lpc_passes < 0) {
296 // default number of passes for Cholesky
297 s->options.lpc_passes = 2;
298 } else if (avctx->lpc_passes == 0) {
299 av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
303 s->options.lpc_passes = avctx->lpc_passes;
308 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
309 s->options.min_prediction_order = 0;
310 } else if (avctx->min_prediction_order >= 0) {
311 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
312 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
313 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
314 avctx->min_prediction_order);
317 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
318 avctx->min_prediction_order > MAX_LPC_ORDER) {
319 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
320 avctx->min_prediction_order);
323 s->options.min_prediction_order = avctx->min_prediction_order;
325 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
326 s->options.max_prediction_order = 0;
327 } else if (avctx->max_prediction_order >= 0) {
328 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
329 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
330 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
331 avctx->max_prediction_order);
334 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
335 avctx->max_prediction_order > MAX_LPC_ORDER) {
336 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
337 avctx->max_prediction_order);
340 s->options.max_prediction_order = avctx->max_prediction_order;
342 if (s->options.max_prediction_order < s->options.min_prediction_order) {
343 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
344 s->options.min_prediction_order, s->options.max_prediction_order);
348 if (avctx->prediction_order_method >= 0) {
349 if (avctx->prediction_order_method > ORDER_METHOD_LOG) {
350 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
351 avctx->prediction_order_method);
354 s->options.prediction_order_method = avctx->prediction_order_method;
357 if (avctx->min_partition_order >= 0) {
358 if (avctx->min_partition_order > MAX_PARTITION_ORDER) {
359 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
360 avctx->min_partition_order);
363 s->options.min_partition_order = avctx->min_partition_order;
365 if (avctx->max_partition_order >= 0) {
366 if (avctx->max_partition_order > MAX_PARTITION_ORDER) {
367 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
368 avctx->max_partition_order);
371 s->options.max_partition_order = avctx->max_partition_order;
373 if (s->options.max_partition_order < s->options.min_partition_order) {
374 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
375 s->options.min_partition_order, s->options.max_partition_order);
379 if (avctx->frame_size > 0) {
380 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
381 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
382 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
387 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
389 s->max_blocksize = s->avctx->frame_size;
391 /* set LPC precision */
392 if (avctx->lpc_coeff_precision > 0) {
393 if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
394 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
395 avctx->lpc_coeff_precision);
398 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
400 /* default LPC precision */
401 s->options.lpc_coeff_precision = 15;
404 /* set maximum encoded frame size in verbatim mode */
405 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
408 /* initialize MD5 context */
409 s->md5ctx = av_malloc(av_md5_size);
411 return AVERROR(ENOMEM);
412 av_md5_init(s->md5ctx);
414 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
416 return AVERROR(ENOMEM);
417 write_streaminfo(s, streaminfo);
418 avctx->extradata = streaminfo;
419 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
422 s->min_framesize = s->max_framesize;
424 avctx->coded_frame = avcodec_alloc_frame();
425 if (!avctx->coded_frame)
426 return AVERROR(ENOMEM);
428 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
429 s->options.max_prediction_order, AV_LPC_TYPE_LEVINSON);
431 dprint_compression_options(s);
437 static void init_frame(FlacEncodeContext *s)
444 for (i = 0; i < 16; i++) {
445 if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
446 frame->blocksize = ff_flac_blocksize_table[i];
447 frame->bs_code[0] = i;
448 frame->bs_code[1] = 0;
453 frame->blocksize = s->avctx->frame_size;
454 if (frame->blocksize <= 256) {
455 frame->bs_code[0] = 6;
456 frame->bs_code[1] = frame->blocksize-1;
458 frame->bs_code[0] = 7;
459 frame->bs_code[1] = frame->blocksize-1;
463 for (ch = 0; ch < s->channels; ch++)
464 frame->subframes[ch].obits = 16;
466 frame->verbatim_only = 0;
471 * Copy channel-interleaved input samples into separate subframes.
473 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
479 for (i = 0, j = 0; i < frame->blocksize; i++)
480 for (ch = 0; ch < s->channels; ch++, j++)
481 frame->subframes[ch].samples[i] = samples[j];
485 static int rice_count_exact(int32_t *res, int n, int k)
490 for (i = 0; i < n; i++) {
491 int32_t v = -2 * res[i] - 1;
493 count += (v >> k) + 1 + k;
499 static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
502 int p, porder, psize;
506 /* subframe header */
510 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
512 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
513 count += s->frame.blocksize * sub->obits;
515 /* warm-up samples */
516 count += pred_order * sub->obits;
518 /* LPC coefficients */
519 if (sub->type == FLAC_SUBFRAME_LPC)
520 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
522 /* rice-encoded block */
525 /* partition order */
526 porder = sub->rc.porder;
527 psize = s->frame.blocksize >> porder;
533 for (p = 0; p < 1 << porder; p++) {
534 int k = sub->rc.params[p];
536 count += rice_count_exact(&sub->residual[i], part_end - i, k);
538 part_end = FFMIN(s->frame.blocksize, part_end + psize);
546 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
549 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
551 static int find_optimal_param(uint32_t sum, int n)
558 sum2 = sum - (n >> 1);
559 k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
560 return FFMIN(k, MAX_RICE_PARAM);
564 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
565 uint32_t *sums, int n, int pred_order)
571 part = (1 << porder);
574 cnt = (n >> porder) - pred_order;
575 for (i = 0; i < part; i++) {
576 k = find_optimal_param(sums[i], cnt);
578 all_bits += rice_encode_count(sums[i], cnt, k);
588 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
589 uint32_t sums[][MAX_PARTITIONS])
593 uint32_t *res, *res_end;
595 /* sums for highest level */
597 res = &data[pred_order];
598 res_end = &data[n >> pmax];
599 for (i = 0; i < parts; i++) {
601 while (res < res_end)
604 res_end += n >> pmax;
606 /* sums for lower levels */
607 for (i = pmax - 1; i >= pmin; i--) {
609 for (j = 0; j < parts; j++)
610 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
615 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
616 int32_t *data, int n, int pred_order)
619 uint32_t bits[MAX_PARTITION_ORDER+1];
623 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
625 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
626 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
627 assert(pmin <= pmax);
629 udata = av_malloc(n * sizeof(uint32_t));
630 for (i = 0; i < n; i++)
631 udata[i] = (2*data[i]) ^ (data[i]>>31);
633 calc_sums(pmin, pmax, udata, n, pred_order, sums);
636 bits[pmin] = UINT32_MAX;
637 for (i = pmin; i <= pmax; i++) {
638 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
639 if (bits[i] <= bits[opt_porder]) {
646 return bits[opt_porder];
650 static int get_max_p_order(int max_porder, int n, int order)
652 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
654 porder = FFMIN(porder, av_log2(n/order));
659 static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
660 FlacSubframe *sub, int pred_order)
662 int pmin = get_max_p_order(s->options.min_partition_order,
663 s->frame.blocksize, pred_order);
664 int pmax = get_max_p_order(s->options.max_partition_order,
665 s->frame.blocksize, pred_order);
667 uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
668 if (sub->type == FLAC_SUBFRAME_LPC)
669 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
670 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
671 s->frame.blocksize, pred_order);
676 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
681 for (i = 0; i < order; i++)
685 for (i = order; i < n; i++)
687 } else if (order == 1) {
688 for (i = order; i < n; i++)
689 res[i] = smp[i] - smp[i-1];
690 } else if (order == 2) {
691 int a = smp[order-1] - smp[order-2];
692 for (i = order; i < n; i += 2) {
693 int b = smp[i ] - smp[i-1];
695 a = smp[i+1] - smp[i ];
698 } else if (order == 3) {
699 int a = smp[order-1] - smp[order-2];
700 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
701 for (i = order; i < n; i += 2) {
702 int b = smp[i ] - smp[i-1];
705 a = smp[i+1] - smp[i ];
710 int a = smp[order-1] - smp[order-2];
711 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
712 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
713 for (i = order; i < n; i += 2) {
714 int b = smp[i ] - smp[i-1];
718 a = smp[i+1] - smp[i ];
728 int c = coefs[(x)-1];\
734 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
735 const int32_t *smp, int n, int order,
736 const int32_t *coefs, int shift, int big)
739 for (i = order; i < n; i += 2) {
740 int s = smp[i-order];
789 res[i ] = smp[i ] - (p0 >> shift);
790 res[i+1] = smp[i+1] - (p1 >> shift);
795 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
796 int order, const int32_t *coefs, int shift)
799 for (i = 0; i < order; i++)
802 for (i = order; i < n; i += 2) {
806 for (j = 0; j < order; j++) {
812 res[i ] = smp[i ] - (p0 >> shift);
813 res[i+1] = smp[i+1] - (p1 >> shift);
817 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
818 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
819 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
820 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
821 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
822 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
823 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
824 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
825 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
831 static int encode_residual_ch(FlacEncodeContext *s, int ch)
834 int min_order, max_order, opt_order, omethod;
837 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
838 int shift[MAX_LPC_ORDER];
842 sub = &frame->subframes[ch];
845 n = frame->blocksize;
848 for (i = 1; i < n; i++)
852 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
854 return subframe_count_exact(s, sub, 0);
858 if (frame->verbatim_only || n < 5) {
859 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
860 memcpy(res, smp, n * sizeof(int32_t));
861 return subframe_count_exact(s, sub, 0);
864 min_order = s->options.min_prediction_order;
865 max_order = s->options.max_prediction_order;
866 omethod = s->options.prediction_order_method;
869 sub->type = FLAC_SUBFRAME_FIXED;
870 if (s->options.lpc_type == AV_LPC_TYPE_NONE ||
871 s->options.lpc_type == AV_LPC_TYPE_FIXED || n <= max_order) {
872 uint32_t bits[MAX_FIXED_ORDER+1];
873 if (max_order > MAX_FIXED_ORDER)
874 max_order = MAX_FIXED_ORDER;
876 bits[0] = UINT32_MAX;
877 for (i = min_order; i <= max_order; i++) {
878 encode_residual_fixed(res, smp, n, i);
879 bits[i] = find_subframe_rice_params(s, sub, i);
880 if (bits[i] < bits[opt_order])
883 sub->order = opt_order;
884 sub->type_code = sub->type | sub->order;
885 if (sub->order != max_order) {
886 encode_residual_fixed(res, smp, n, sub->order);
887 find_subframe_rice_params(s, sub, sub->order);
889 return subframe_count_exact(s, sub, sub->order);
893 sub->type = FLAC_SUBFRAME_LPC;
894 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
895 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
896 s->options.lpc_passes, omethod,
899 if (omethod == ORDER_METHOD_2LEVEL ||
900 omethod == ORDER_METHOD_4LEVEL ||
901 omethod == ORDER_METHOD_8LEVEL) {
902 int levels = 1 << omethod;
903 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
905 int opt_index = levels-1;
906 opt_order = max_order-1;
907 bits[opt_index] = UINT32_MAX;
908 for (i = levels-1; i >= 0; i--) {
909 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
912 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
913 bits[i] = find_subframe_rice_params(s, sub, order+1);
914 if (bits[i] < bits[opt_index]) {
920 } else if (omethod == ORDER_METHOD_SEARCH) {
921 // brute-force optimal order search
922 uint32_t bits[MAX_LPC_ORDER];
924 bits[0] = UINT32_MAX;
925 for (i = min_order-1; i < max_order; i++) {
926 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
927 bits[i] = find_subframe_rice_params(s, sub, i+1);
928 if (bits[i] < bits[opt_order])
932 } else if (omethod == ORDER_METHOD_LOG) {
933 uint32_t bits[MAX_LPC_ORDER];
936 opt_order = min_order - 1 + (max_order-min_order)/3;
937 memset(bits, -1, sizeof(bits));
939 for (step = 16; step; step >>= 1) {
940 int last = opt_order;
941 for (i = last-step; i <= last+step; i += step) {
942 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
944 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
945 bits[i] = find_subframe_rice_params(s, sub, i+1);
946 if (bits[i] < bits[opt_order])
953 sub->order = opt_order;
954 sub->type_code = sub->type | (sub->order-1);
955 sub->shift = shift[sub->order-1];
956 for (i = 0; i < sub->order; i++)
957 sub->coefs[i] = coefs[sub->order-1][i];
959 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
961 find_subframe_rice_params(s, sub, sub->order);
963 return subframe_count_exact(s, sub, sub->order);
967 static int count_frame_header(FlacEncodeContext *s)
975 <1> Blocking strategy
976 <4> Block size in inter-channel samples
978 <4> Channel assignment
979 <3> Sample size in bits
984 /* coded frame number */
985 PUT_UTF8(s->frame_count, tmp, count += 8;)
987 /* explicit block size */
988 if (s->frame.bs_code[0] == 6)
990 else if (s->frame.bs_code[0] == 7)
993 /* explicit sample rate */
994 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
996 /* frame header CRC-8 */
1003 static int encode_frame(FlacEncodeContext *s)
1007 count = count_frame_header(s);
1009 for (ch = 0; ch < s->channels; ch++)
1010 count += encode_residual_ch(s, ch);
1012 count += (8 - (count & 7)) & 7; // byte alignment
1013 count += 16; // CRC-16
1019 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1027 /* calculate sum of 2nd order residual for each channel */
1028 sum[0] = sum[1] = sum[2] = sum[3] = 0;
1029 for (i = 2; i < n; i++) {
1030 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1031 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1032 sum[2] += FFABS((lt + rt) >> 1);
1033 sum[3] += FFABS(lt - rt);
1034 sum[0] += FFABS(lt);
1035 sum[1] += FFABS(rt);
1037 /* estimate bit counts */
1038 for (i = 0; i < 4; i++) {
1039 k = find_optimal_param(2 * sum[i], n);
1040 sum[i] = rice_encode_count( 2 * sum[i], n, k);
1043 /* calculate score for each mode */
1044 score[0] = sum[0] + sum[1];
1045 score[1] = sum[0] + sum[3];
1046 score[2] = sum[1] + sum[3];
1047 score[3] = sum[2] + sum[3];
1049 /* return mode with lowest score */
1051 for (i = 1; i < 4; i++)
1052 if (score[i] < score[best])
1055 return FLAC_CHMODE_INDEPENDENT;
1056 } else if (best == 1) {
1057 return FLAC_CHMODE_LEFT_SIDE;
1058 } else if (best == 2) {
1059 return FLAC_CHMODE_RIGHT_SIDE;
1061 return FLAC_CHMODE_MID_SIDE;
1067 * Perform stereo channel decorrelation.
1069 static void channel_decorrelation(FlacEncodeContext *s)
1072 int32_t *left, *right;
1076 n = frame->blocksize;
1077 left = frame->subframes[0].samples;
1078 right = frame->subframes[1].samples;
1080 if (s->channels != 2) {
1081 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1085 frame->ch_mode = estimate_stereo_mode(left, right, n);
1087 /* perform decorrelation and adjust bits-per-sample */
1088 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1090 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1092 for (i = 0; i < n; i++) {
1094 left[i] = (tmp + right[i]) >> 1;
1095 right[i] = tmp - right[i];
1097 frame->subframes[1].obits++;
1098 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1099 for (i = 0; i < n; i++)
1100 right[i] = left[i] - right[i];
1101 frame->subframes[1].obits++;
1103 for (i = 0; i < n; i++)
1104 left[i] -= right[i];
1105 frame->subframes[0].obits++;
1110 static void write_utf8(PutBitContext *pb, uint32_t val)
1113 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1117 static void write_frame_header(FlacEncodeContext *s)
1124 put_bits(&s->pb, 16, 0xFFF8);
1125 put_bits(&s->pb, 4, frame->bs_code[0]);
1126 put_bits(&s->pb, 4, s->sr_code[0]);
1128 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1129 put_bits(&s->pb, 4, s->channels-1);
1131 put_bits(&s->pb, 4, frame->ch_mode);
1133 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1134 put_bits(&s->pb, 1, 0);
1135 write_utf8(&s->pb, s->frame_count);
1137 if (frame->bs_code[0] == 6)
1138 put_bits(&s->pb, 8, frame->bs_code[1]);
1139 else if (frame->bs_code[0] == 7)
1140 put_bits(&s->pb, 16, frame->bs_code[1]);
1142 if (s->sr_code[0] == 12)
1143 put_bits(&s->pb, 8, s->sr_code[1]);
1144 else if (s->sr_code[0] > 12)
1145 put_bits(&s->pb, 16, s->sr_code[1]);
1147 flush_put_bits(&s->pb);
1148 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1149 put_bits_count(&s->pb) >> 3);
1150 put_bits(&s->pb, 8, crc);
1154 static void write_subframes(FlacEncodeContext *s)
1158 for (ch = 0; ch < s->channels; ch++) {
1159 FlacSubframe *sub = &s->frame.subframes[ch];
1160 int i, p, porder, psize;
1162 int32_t *res = sub->residual;
1163 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1165 /* subframe header */
1166 put_bits(&s->pb, 1, 0);
1167 put_bits(&s->pb, 6, sub->type_code);
1168 put_bits(&s->pb, 1, 0); /* no wasted bits */
1171 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1172 put_sbits(&s->pb, sub->obits, res[0]);
1173 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1174 while (res < frame_end)
1175 put_sbits(&s->pb, sub->obits, *res++);
1177 /* warm-up samples */
1178 for (i = 0; i < sub->order; i++)
1179 put_sbits(&s->pb, sub->obits, *res++);
1181 /* LPC coefficients */
1182 if (sub->type == FLAC_SUBFRAME_LPC) {
1183 int cbits = s->options.lpc_coeff_precision;
1184 put_bits( &s->pb, 4, cbits-1);
1185 put_sbits(&s->pb, 5, sub->shift);
1186 for (i = 0; i < sub->order; i++)
1187 put_sbits(&s->pb, cbits, sub->coefs[i]);
1190 /* rice-encoded block */
1191 put_bits(&s->pb, 2, 0);
1193 /* partition order */
1194 porder = sub->rc.porder;
1195 psize = s->frame.blocksize >> porder;
1196 put_bits(&s->pb, 4, porder);
1199 part_end = &sub->residual[psize];
1200 for (p = 0; p < 1 << porder; p++) {
1201 int k = sub->rc.params[p];
1202 put_bits(&s->pb, 4, k);
1203 while (res < part_end)
1204 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1205 part_end = FFMIN(frame_end, part_end + psize);
1212 static void write_frame_footer(FlacEncodeContext *s)
1215 flush_put_bits(&s->pb);
1216 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1217 put_bits_count(&s->pb)>>3));
1218 put_bits(&s->pb, 16, crc);
1219 flush_put_bits(&s->pb);
1223 static int write_frame(FlacEncodeContext *s, uint8_t *frame, int buf_size)
1225 init_put_bits(&s->pb, frame, buf_size);
1226 write_frame_header(s);
1228 write_frame_footer(s);
1229 return put_bits_count(&s->pb) >> 3;
1233 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1237 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1238 int16_t smp = av_le2ne16(samples[i]);
1239 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1242 av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1247 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1248 int buf_size, void *data)
1250 FlacEncodeContext *s;
1251 const int16_t *samples = data;
1252 int frame_bytes, out_bytes;
1254 s = avctx->priv_data;
1256 /* when the last block is reached, update the header in extradata */
1258 s->max_framesize = s->max_encoded_framesize;
1259 av_md5_final(s->md5ctx, s->md5sum);
1260 write_streaminfo(s, avctx->extradata);
1264 /* change max_framesize for small final frame */
1265 if (avctx->frame_size < s->frame.blocksize) {
1266 s->max_framesize = ff_flac_get_max_frame_size(avctx->frame_size,
1272 copy_samples(s, samples);
1274 channel_decorrelation(s);
1276 frame_bytes = encode_frame(s);
1278 /* fallback to verbatim mode if the compressed frame is larger than it
1279 would be if encoded uncompressed. */
1280 if (frame_bytes > s->max_framesize) {
1281 s->frame.verbatim_only = 1;
1282 frame_bytes = encode_frame(s);
1285 if (buf_size < frame_bytes) {
1286 av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1289 out_bytes = write_frame(s, frame, buf_size);
1292 avctx->coded_frame->pts = s->sample_count;
1293 s->sample_count += avctx->frame_size;
1294 update_md5_sum(s, samples);
1295 if (out_bytes > s->max_encoded_framesize)
1296 s->max_encoded_framesize = out_bytes;
1297 if (out_bytes < s->min_framesize)
1298 s->min_framesize = out_bytes;
1304 static av_cold int flac_encode_close(AVCodecContext *avctx)
1306 if (avctx->priv_data) {
1307 FlacEncodeContext *s = avctx->priv_data;
1308 av_freep(&s->md5ctx);
1309 ff_lpc_end(&s->lpc_ctx);
1311 av_freep(&avctx->extradata);
1312 avctx->extradata_size = 0;
1313 av_freep(&avctx->coded_frame);
1318 AVCodec ff_flac_encoder = {
1322 sizeof(FlacEncodeContext),
1327 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1328 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1329 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),