3 * Copyright (c) 2006 Justin Ruggles <justin.ruggles@gmail.com>
5 * This file is part of FFmpeg.
7 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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"
32 #define FLAC_SUBFRAME_CONSTANT 0
33 #define FLAC_SUBFRAME_VERBATIM 1
34 #define FLAC_SUBFRAME_FIXED 8
35 #define FLAC_SUBFRAME_LPC 32
37 #define MAX_FIXED_ORDER 4
38 #define MAX_PARTITION_ORDER 8
39 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
40 #define MAX_LPC_PRECISION 15
41 #define MAX_LPC_SHIFT 15
42 #define MAX_RICE_PARAM 14
44 typedef struct CompressionOptions {
45 int compression_level;
47 enum AVLPCType lpc_type;
49 int lpc_coeff_precision;
50 int min_prediction_order;
51 int max_prediction_order;
52 int prediction_order_method;
53 int min_partition_order;
54 int max_partition_order;
57 typedef struct RiceContext {
59 int params[MAX_PARTITIONS];
62 typedef struct FlacSubframe {
67 int32_t coefs[MAX_LPC_ORDER];
70 int32_t samples[FLAC_MAX_BLOCKSIZE];
71 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
74 typedef struct FlacFrame {
75 FlacSubframe subframes[FLAC_MAX_CHANNELS];
83 typedef struct FlacEncodeContext {
91 int max_encoded_framesize;
93 uint64_t sample_count;
96 CompressionOptions options;
97 AVCodecContext *avctx;
104 * Write streaminfo metadata block to byte array.
106 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
110 memset(header, 0, FLAC_STREAMINFO_SIZE);
111 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
113 /* streaminfo metadata block */
114 put_bits(&pb, 16, s->max_blocksize);
115 put_bits(&pb, 16, s->max_blocksize);
116 put_bits(&pb, 24, s->min_framesize);
117 put_bits(&pb, 24, s->max_framesize);
118 put_bits(&pb, 20, s->samplerate);
119 put_bits(&pb, 3, s->channels-1);
120 put_bits(&pb, 5, 15); /* bits per sample - 1 */
121 /* write 36-bit sample count in 2 put_bits() calls */
122 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
123 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
125 memcpy(&header[18], s->md5sum, 16);
130 * Set blocksize based on samplerate.
131 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
133 static int select_blocksize(int samplerate, int block_time_ms)
139 assert(samplerate > 0);
140 blocksize = ff_flac_blocksize_table[1];
141 target = (samplerate * block_time_ms) / 1000;
142 for (i = 0; i < 16; i++) {
143 if (target >= ff_flac_blocksize_table[i] &&
144 ff_flac_blocksize_table[i] > blocksize) {
145 blocksize = ff_flac_blocksize_table[i];
152 static av_cold void dprint_compression_options(FlacEncodeContext *s)
154 AVCodecContext *avctx = s->avctx;
155 CompressionOptions *opt = &s->options;
157 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
159 switch (opt->lpc_type) {
160 case AV_LPC_TYPE_NONE:
161 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
163 case AV_LPC_TYPE_FIXED:
164 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
166 case AV_LPC_TYPE_LEVINSON:
167 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
169 case AV_LPC_TYPE_CHOLESKY:
170 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
171 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
175 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
176 opt->min_prediction_order, opt->max_prediction_order);
178 switch (opt->prediction_order_method) {
179 case ORDER_METHOD_EST:
180 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
182 case ORDER_METHOD_2LEVEL:
183 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
185 case ORDER_METHOD_4LEVEL:
186 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
188 case ORDER_METHOD_8LEVEL:
189 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
191 case ORDER_METHOD_SEARCH:
192 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
194 case ORDER_METHOD_LOG:
195 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
200 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
201 opt->min_partition_order, opt->max_partition_order);
203 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
205 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
206 opt->lpc_coeff_precision);
210 static av_cold int flac_encode_init(AVCodecContext *avctx)
212 int freq = avctx->sample_rate;
213 int channels = avctx->channels;
214 FlacEncodeContext *s = avctx->priv_data;
220 dsputil_init(&s->dsp, avctx);
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 s->options.lpc_type = ((int[]){ AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED,
273 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
274 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
275 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
276 AV_LPC_TYPE_LEVINSON})[level];
278 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
279 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
281 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
282 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
283 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
284 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
285 ORDER_METHOD_SEARCH})[level];
287 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
288 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
290 /* set compression option overrides from AVCodecContext */
292 /* for compatibility with deprecated AVCodecContext.use_lpc */
293 if (avctx->use_lpc == 0) {
294 s->options.lpc_type = AV_LPC_TYPE_FIXED;
295 } else if (avctx->use_lpc == 1) {
296 s->options.lpc_type = AV_LPC_TYPE_LEVINSON;
297 } else if (avctx->use_lpc > 1) {
298 s->options.lpc_type = AV_LPC_TYPE_CHOLESKY;
299 s->options.lpc_passes = avctx->use_lpc - 1;
302 if (avctx->lpc_type > AV_LPC_TYPE_DEFAULT) {
303 if (avctx->lpc_type > AV_LPC_TYPE_CHOLESKY) {
304 av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
307 s->options.lpc_type = avctx->lpc_type;
308 if (s->options.lpc_type == AV_LPC_TYPE_CHOLESKY) {
309 if (avctx->lpc_passes < 0) {
310 // default number of passes for Cholesky
311 s->options.lpc_passes = 2;
312 } else if (avctx->lpc_passes == 0) {
313 av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
317 s->options.lpc_passes = avctx->lpc_passes;
322 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
323 s->options.min_prediction_order = 0;
324 } else if (avctx->min_prediction_order >= 0) {
325 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
326 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
327 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
328 avctx->min_prediction_order);
331 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
332 avctx->min_prediction_order > MAX_LPC_ORDER) {
333 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
334 avctx->min_prediction_order);
337 s->options.min_prediction_order = avctx->min_prediction_order;
339 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
340 s->options.max_prediction_order = 0;
341 } else if (avctx->max_prediction_order >= 0) {
342 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
343 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
344 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
345 avctx->max_prediction_order);
348 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
349 avctx->max_prediction_order > MAX_LPC_ORDER) {
350 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
351 avctx->max_prediction_order);
354 s->options.max_prediction_order = avctx->max_prediction_order;
356 if (s->options.max_prediction_order < s->options.min_prediction_order) {
357 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
358 s->options.min_prediction_order, s->options.max_prediction_order);
362 if (avctx->prediction_order_method >= 0) {
363 if (avctx->prediction_order_method > ORDER_METHOD_LOG) {
364 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
365 avctx->prediction_order_method);
368 s->options.prediction_order_method = avctx->prediction_order_method;
371 if (avctx->min_partition_order >= 0) {
372 if (avctx->min_partition_order > MAX_PARTITION_ORDER) {
373 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
374 avctx->min_partition_order);
377 s->options.min_partition_order = avctx->min_partition_order;
379 if (avctx->max_partition_order >= 0) {
380 if (avctx->max_partition_order > MAX_PARTITION_ORDER) {
381 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
382 avctx->max_partition_order);
385 s->options.max_partition_order = avctx->max_partition_order;
387 if (s->options.max_partition_order < s->options.min_partition_order) {
388 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
389 s->options.min_partition_order, s->options.max_partition_order);
393 if (avctx->frame_size > 0) {
394 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
395 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
396 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
401 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
403 s->max_blocksize = s->avctx->frame_size;
405 /* set LPC precision */
406 if (avctx->lpc_coeff_precision > 0) {
407 if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
408 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
409 avctx->lpc_coeff_precision);
412 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
414 /* default LPC precision */
415 s->options.lpc_coeff_precision = 15;
418 /* set maximum encoded frame size in verbatim mode */
419 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
422 /* initialize MD5 context */
423 s->md5ctx = av_malloc(av_md5_size);
425 return AVERROR(ENOMEM);
426 av_md5_init(s->md5ctx);
428 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
430 return AVERROR(ENOMEM);
431 write_streaminfo(s, streaminfo);
432 avctx->extradata = streaminfo;
433 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
436 s->min_framesize = s->max_framesize;
438 avctx->coded_frame = avcodec_alloc_frame();
439 if (!avctx->coded_frame)
440 return AVERROR(ENOMEM);
442 dprint_compression_options(s);
448 static void init_frame(FlacEncodeContext *s)
455 for (i = 0; i < 16; i++) {
456 if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
457 frame->blocksize = ff_flac_blocksize_table[i];
458 frame->bs_code[0] = i;
459 frame->bs_code[1] = 0;
464 frame->blocksize = s->avctx->frame_size;
465 if (frame->blocksize <= 256) {
466 frame->bs_code[0] = 6;
467 frame->bs_code[1] = frame->blocksize-1;
469 frame->bs_code[0] = 7;
470 frame->bs_code[1] = frame->blocksize-1;
474 for (ch = 0; ch < s->channels; ch++)
475 frame->subframes[ch].obits = 16;
477 frame->verbatim_only = 0;
482 * Copy channel-interleaved input samples into separate subframes.
484 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
490 for (i = 0, j = 0; i < frame->blocksize; i++)
491 for (ch = 0; ch < s->channels; ch++, j++)
492 frame->subframes[ch].samples[i] = samples[j];
496 static int rice_count_exact(int32_t *res, int n, int k)
501 for (i = 0; i < n; i++) {
502 int32_t v = -2 * res[i] - 1;
504 count += (v >> k) + 1 + k;
510 static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
513 int p, porder, psize;
517 /* subframe header */
521 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
523 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
524 count += s->frame.blocksize * sub->obits;
526 /* warm-up samples */
527 count += pred_order * sub->obits;
529 /* LPC coefficients */
530 if (sub->type == FLAC_SUBFRAME_LPC)
531 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
533 /* rice-encoded block */
536 /* partition order */
537 porder = sub->rc.porder;
538 psize = s->frame.blocksize >> porder;
544 for (p = 0; p < 1 << porder; p++) {
545 int k = sub->rc.params[p];
547 count += rice_count_exact(&sub->residual[i], part_end - i, k);
549 part_end = FFMIN(s->frame.blocksize, part_end + psize);
557 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
560 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
562 static int find_optimal_param(uint32_t sum, int n)
569 sum2 = sum - (n >> 1);
570 k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
571 return FFMIN(k, MAX_RICE_PARAM);
575 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
576 uint32_t *sums, int n, int pred_order)
582 part = (1 << porder);
585 cnt = (n >> porder) - pred_order;
586 for (i = 0; i < part; i++) {
587 k = find_optimal_param(sums[i], cnt);
589 all_bits += rice_encode_count(sums[i], cnt, k);
599 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
600 uint32_t sums[][MAX_PARTITIONS])
604 uint32_t *res, *res_end;
606 /* sums for highest level */
608 res = &data[pred_order];
609 res_end = &data[n >> pmax];
610 for (i = 0; i < parts; i++) {
612 while (res < res_end)
615 res_end += n >> pmax;
617 /* sums for lower levels */
618 for (i = pmax - 1; i >= pmin; i--) {
620 for (j = 0; j < parts; j++)
621 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
626 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
627 int32_t *data, int n, int pred_order)
630 uint32_t bits[MAX_PARTITION_ORDER+1];
634 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
636 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
637 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
638 assert(pmin <= pmax);
640 udata = av_malloc(n * sizeof(uint32_t));
641 for (i = 0; i < n; i++)
642 udata[i] = (2*data[i]) ^ (data[i]>>31);
644 calc_sums(pmin, pmax, udata, n, pred_order, sums);
647 bits[pmin] = UINT32_MAX;
648 for (i = pmin; i <= pmax; i++) {
649 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
650 if (bits[i] <= bits[opt_porder]) {
657 return bits[opt_porder];
661 static int get_max_p_order(int max_porder, int n, int order)
663 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
665 porder = FFMIN(porder, av_log2(n/order));
670 static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
671 FlacSubframe *sub, int pred_order)
673 int pmin = get_max_p_order(s->options.min_partition_order,
674 s->frame.blocksize, pred_order);
675 int pmax = get_max_p_order(s->options.max_partition_order,
676 s->frame.blocksize, pred_order);
678 uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
679 if (sub->type == FLAC_SUBFRAME_LPC)
680 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
681 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
682 s->frame.blocksize, pred_order);
687 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
692 for (i = 0; i < order; i++)
696 for (i = order; i < n; i++)
698 } else if (order == 1) {
699 for (i = order; i < n; i++)
700 res[i] = smp[i] - smp[i-1];
701 } else if (order == 2) {
702 int a = smp[order-1] - smp[order-2];
703 for (i = order; i < n; i += 2) {
704 int b = smp[i ] - smp[i-1];
706 a = smp[i+1] - smp[i ];
709 } else if (order == 3) {
710 int a = smp[order-1] - smp[order-2];
711 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
712 for (i = order; i < n; i += 2) {
713 int b = smp[i ] - smp[i-1];
716 a = smp[i+1] - smp[i ];
721 int a = smp[order-1] - smp[order-2];
722 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
723 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
724 for (i = order; i < n; i += 2) {
725 int b = smp[i ] - smp[i-1];
729 a = smp[i+1] - smp[i ];
739 int c = coefs[(x)-1];\
745 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
746 const int32_t *smp, int n, int order,
747 const int32_t *coefs, int shift, int big)
750 for (i = order; i < n; i += 2) {
751 int s = smp[i-order];
800 res[i ] = smp[i ] - (p0 >> shift);
801 res[i+1] = smp[i+1] - (p1 >> shift);
806 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
807 int order, const int32_t *coefs, int shift)
810 for (i = 0; i < order; i++)
813 for (i = order; i < n; i += 2) {
817 for (j = 0; j < order; j++) {
823 res[i ] = smp[i ] - (p0 >> shift);
824 res[i+1] = smp[i+1] - (p1 >> shift);
828 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
829 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
830 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
831 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
832 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
833 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
834 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
835 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
836 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
842 static int encode_residual_ch(FlacEncodeContext *s, int ch)
845 int min_order, max_order, opt_order, omethod;
848 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
849 int shift[MAX_LPC_ORDER];
853 sub = &frame->subframes[ch];
856 n = frame->blocksize;
859 for (i = 1; i < n; i++)
863 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
865 return subframe_count_exact(s, sub, 0);
869 if (frame->verbatim_only || n < 5) {
870 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
871 memcpy(res, smp, n * sizeof(int32_t));
872 return subframe_count_exact(s, sub, 0);
875 min_order = s->options.min_prediction_order;
876 max_order = s->options.max_prediction_order;
877 omethod = s->options.prediction_order_method;
880 sub->type = FLAC_SUBFRAME_FIXED;
881 if (s->options.lpc_type == AV_LPC_TYPE_NONE ||
882 s->options.lpc_type == AV_LPC_TYPE_FIXED || n <= max_order) {
883 uint32_t bits[MAX_FIXED_ORDER+1];
884 if (max_order > MAX_FIXED_ORDER)
885 max_order = MAX_FIXED_ORDER;
887 bits[0] = UINT32_MAX;
888 for (i = min_order; i <= max_order; i++) {
889 encode_residual_fixed(res, smp, n, i);
890 bits[i] = find_subframe_rice_params(s, sub, i);
891 if (bits[i] < bits[opt_order])
894 sub->order = opt_order;
895 sub->type_code = sub->type | sub->order;
896 if (sub->order != max_order) {
897 encode_residual_fixed(res, smp, n, sub->order);
898 find_subframe_rice_params(s, sub, sub->order);
900 return subframe_count_exact(s, sub, sub->order);
904 sub->type = FLAC_SUBFRAME_LPC;
905 opt_order = ff_lpc_calc_coefs(&s->dsp, smp, n, min_order, max_order,
906 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
907 s->options.lpc_passes, omethod,
910 if (omethod == ORDER_METHOD_2LEVEL ||
911 omethod == ORDER_METHOD_4LEVEL ||
912 omethod == ORDER_METHOD_8LEVEL) {
913 int levels = 1 << omethod;
914 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
916 int opt_index = levels-1;
917 opt_order = max_order-1;
918 bits[opt_index] = UINT32_MAX;
919 for (i = levels-1; i >= 0; i--) {
920 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
923 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
924 bits[i] = find_subframe_rice_params(s, sub, order+1);
925 if (bits[i] < bits[opt_index]) {
931 } else if (omethod == ORDER_METHOD_SEARCH) {
932 // brute-force optimal order search
933 uint32_t bits[MAX_LPC_ORDER];
935 bits[0] = UINT32_MAX;
936 for (i = min_order-1; i < max_order; i++) {
937 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
938 bits[i] = find_subframe_rice_params(s, sub, i+1);
939 if (bits[i] < bits[opt_order])
943 } else if (omethod == ORDER_METHOD_LOG) {
944 uint32_t bits[MAX_LPC_ORDER];
947 opt_order = min_order - 1 + (max_order-min_order)/3;
948 memset(bits, -1, sizeof(bits));
950 for (step = 16; step; step >>= 1) {
951 int last = opt_order;
952 for (i = last-step; i <= last+step; i += step) {
953 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
955 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
956 bits[i] = find_subframe_rice_params(s, sub, i+1);
957 if (bits[i] < bits[opt_order])
964 sub->order = opt_order;
965 sub->type_code = sub->type | (sub->order-1);
966 sub->shift = shift[sub->order-1];
967 for (i = 0; i < sub->order; i++)
968 sub->coefs[i] = coefs[sub->order-1][i];
970 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
972 find_subframe_rice_params(s, sub, sub->order);
974 return subframe_count_exact(s, sub, sub->order);
978 static int count_frame_header(FlacEncodeContext *s)
986 <1> Blocking strategy
987 <4> Block size in inter-channel samples
989 <4> Channel assignment
990 <3> Sample size in bits
995 /* coded frame number */
996 PUT_UTF8(s->frame_count, tmp, count += 8;)
998 /* explicit block size */
999 if (s->frame.bs_code[0] == 6)
1001 else if (s->frame.bs_code[0] == 7)
1004 /* explicit sample rate */
1005 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
1007 /* frame header CRC-8 */
1014 static int encode_frame(FlacEncodeContext *s)
1018 count = count_frame_header(s);
1020 for (ch = 0; ch < s->channels; ch++)
1021 count += encode_residual_ch(s, ch);
1023 count += (8 - (count & 7)) & 7; // byte alignment
1024 count += 16; // CRC-16
1030 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1038 /* calculate sum of 2nd order residual for each channel */
1039 sum[0] = sum[1] = sum[2] = sum[3] = 0;
1040 for (i = 2; i < n; i++) {
1041 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1042 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1043 sum[2] += FFABS((lt + rt) >> 1);
1044 sum[3] += FFABS(lt - rt);
1045 sum[0] += FFABS(lt);
1046 sum[1] += FFABS(rt);
1048 /* estimate bit counts */
1049 for (i = 0; i < 4; i++) {
1050 k = find_optimal_param(2 * sum[i], n);
1051 sum[i] = rice_encode_count( 2 * sum[i], n, k);
1054 /* calculate score for each mode */
1055 score[0] = sum[0] + sum[1];
1056 score[1] = sum[0] + sum[3];
1057 score[2] = sum[1] + sum[3];
1058 score[3] = sum[2] + sum[3];
1060 /* return mode with lowest score */
1062 for (i = 1; i < 4; i++)
1063 if (score[i] < score[best])
1066 return FLAC_CHMODE_INDEPENDENT;
1067 } else if (best == 1) {
1068 return FLAC_CHMODE_LEFT_SIDE;
1069 } else if (best == 2) {
1070 return FLAC_CHMODE_RIGHT_SIDE;
1072 return FLAC_CHMODE_MID_SIDE;
1078 * Perform stereo channel decorrelation.
1080 static void channel_decorrelation(FlacEncodeContext *s)
1083 int32_t *left, *right;
1087 n = frame->blocksize;
1088 left = frame->subframes[0].samples;
1089 right = frame->subframes[1].samples;
1091 if (s->channels != 2) {
1092 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1096 frame->ch_mode = estimate_stereo_mode(left, right, n);
1098 /* perform decorrelation and adjust bits-per-sample */
1099 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1101 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1103 for (i = 0; i < n; i++) {
1105 left[i] = (tmp + right[i]) >> 1;
1106 right[i] = tmp - right[i];
1108 frame->subframes[1].obits++;
1109 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1110 for (i = 0; i < n; i++)
1111 right[i] = left[i] - right[i];
1112 frame->subframes[1].obits++;
1114 for (i = 0; i < n; i++)
1115 left[i] -= right[i];
1116 frame->subframes[0].obits++;
1121 static void write_utf8(PutBitContext *pb, uint32_t val)
1124 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1128 static void write_frame_header(FlacEncodeContext *s)
1135 put_bits(&s->pb, 16, 0xFFF8);
1136 put_bits(&s->pb, 4, frame->bs_code[0]);
1137 put_bits(&s->pb, 4, s->sr_code[0]);
1139 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1140 put_bits(&s->pb, 4, s->channels-1);
1142 put_bits(&s->pb, 4, frame->ch_mode);
1144 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1145 put_bits(&s->pb, 1, 0);
1146 write_utf8(&s->pb, s->frame_count);
1148 if (frame->bs_code[0] == 6)
1149 put_bits(&s->pb, 8, frame->bs_code[1]);
1150 else if (frame->bs_code[0] == 7)
1151 put_bits(&s->pb, 16, frame->bs_code[1]);
1153 if (s->sr_code[0] == 12)
1154 put_bits(&s->pb, 8, s->sr_code[1]);
1155 else if (s->sr_code[0] > 12)
1156 put_bits(&s->pb, 16, s->sr_code[1]);
1158 flush_put_bits(&s->pb);
1159 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1160 put_bits_count(&s->pb) >> 3);
1161 put_bits(&s->pb, 8, crc);
1165 static void write_subframes(FlacEncodeContext *s)
1169 for (ch = 0; ch < s->channels; ch++) {
1170 FlacSubframe *sub = &s->frame.subframes[ch];
1171 int i, p, porder, psize;
1173 int32_t *res = sub->residual;
1174 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1176 /* subframe header */
1177 put_bits(&s->pb, 1, 0);
1178 put_bits(&s->pb, 6, sub->type_code);
1179 put_bits(&s->pb, 1, 0); /* no wasted bits */
1182 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1183 put_sbits(&s->pb, sub->obits, res[0]);
1184 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1185 while (res < frame_end)
1186 put_sbits(&s->pb, sub->obits, *res++);
1188 /* warm-up samples */
1189 for (i = 0; i < sub->order; i++)
1190 put_sbits(&s->pb, sub->obits, *res++);
1192 /* LPC coefficients */
1193 if (sub->type == FLAC_SUBFRAME_LPC) {
1194 int cbits = s->options.lpc_coeff_precision;
1195 put_bits( &s->pb, 4, cbits-1);
1196 put_sbits(&s->pb, 5, sub->shift);
1197 for (i = 0; i < sub->order; i++)
1198 put_sbits(&s->pb, cbits, sub->coefs[i]);
1201 /* rice-encoded block */
1202 put_bits(&s->pb, 2, 0);
1204 /* partition order */
1205 porder = sub->rc.porder;
1206 psize = s->frame.blocksize >> porder;
1207 put_bits(&s->pb, 4, porder);
1210 part_end = &sub->residual[psize];
1211 for (p = 0; p < 1 << porder; p++) {
1212 int k = sub->rc.params[p];
1213 put_bits(&s->pb, 4, k);
1214 while (res < part_end)
1215 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1216 part_end = FFMIN(frame_end, part_end + psize);
1223 static void write_frame_footer(FlacEncodeContext *s)
1226 flush_put_bits(&s->pb);
1227 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1228 put_bits_count(&s->pb)>>3));
1229 put_bits(&s->pb, 16, crc);
1230 flush_put_bits(&s->pb);
1234 static int write_frame(FlacEncodeContext *s, uint8_t *frame, int buf_size)
1236 init_put_bits(&s->pb, frame, buf_size);
1237 write_frame_header(s);
1239 write_frame_footer(s);
1240 return put_bits_count(&s->pb) >> 3;
1244 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1248 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1249 int16_t smp = av_le2ne16(samples[i]);
1250 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1253 av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1258 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1259 int buf_size, void *data)
1261 FlacEncodeContext *s;
1262 const int16_t *samples = data;
1263 int frame_bytes, out_bytes;
1265 s = avctx->priv_data;
1267 /* when the last block is reached, update the header in extradata */
1269 s->max_framesize = s->max_encoded_framesize;
1270 av_md5_final(s->md5ctx, s->md5sum);
1271 write_streaminfo(s, avctx->extradata);
1275 /* change max_framesize for small final frame */
1276 if (avctx->frame_size < s->frame.blocksize) {
1277 s->max_framesize = ff_flac_get_max_frame_size(avctx->frame_size,
1283 copy_samples(s, samples);
1285 channel_decorrelation(s);
1287 frame_bytes = encode_frame(s);
1289 /* fallback to verbatim mode if the compressed frame is larger than it
1290 would be if encoded uncompressed. */
1291 if (frame_bytes > s->max_framesize) {
1292 s->frame.verbatim_only = 1;
1293 frame_bytes = encode_frame(s);
1296 if (buf_size < frame_bytes) {
1297 av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1300 out_bytes = write_frame(s, frame, buf_size);
1303 avctx->coded_frame->pts = s->sample_count;
1304 s->sample_count += avctx->frame_size;
1305 update_md5_sum(s, samples);
1306 if (out_bytes > s->max_encoded_framesize)
1307 s->max_encoded_framesize = out_bytes;
1308 if (out_bytes < s->min_framesize)
1309 s->min_framesize = out_bytes;
1315 static av_cold int flac_encode_close(AVCodecContext *avctx)
1317 if (avctx->priv_data) {
1318 FlacEncodeContext *s = avctx->priv_data;
1319 av_freep(&s->md5ctx);
1321 av_freep(&avctx->extradata);
1322 avctx->extradata_size = 0;
1323 av_freep(&avctx->coded_frame);
1328 AVCodec flac_encoder = {
1332 sizeof(FlacEncodeContext),
1337 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1338 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1339 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),