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"
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 FFLPCType 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 {
92 int max_encoded_framesize;
94 uint64_t sample_count;
97 CompressionOptions options;
98 AVCodecContext *avctx;
100 struct AVMD5 *md5ctx;
105 * Write streaminfo metadata block to byte array.
107 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
111 memset(header, 0, FLAC_STREAMINFO_SIZE);
112 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
114 /* streaminfo metadata block */
115 put_bits(&pb, 16, s->max_blocksize);
116 put_bits(&pb, 16, s->max_blocksize);
117 put_bits(&pb, 24, s->min_framesize);
118 put_bits(&pb, 24, s->max_framesize);
119 put_bits(&pb, 20, s->samplerate);
120 put_bits(&pb, 3, s->channels-1);
121 put_bits(&pb, 5, 15); /* bits per sample - 1 */
122 /* write 36-bit sample count in 2 put_bits() calls */
123 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
124 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
126 memcpy(&header[18], s->md5sum, 16);
131 * Set blocksize based on samplerate.
132 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
134 static int select_blocksize(int samplerate, int block_time_ms)
140 assert(samplerate > 0);
141 blocksize = ff_flac_blocksize_table[1];
142 target = (samplerate * block_time_ms) / 1000;
143 for (i = 0; i < 16; i++) {
144 if (target >= ff_flac_blocksize_table[i] &&
145 ff_flac_blocksize_table[i] > blocksize) {
146 blocksize = ff_flac_blocksize_table[i];
153 static av_cold void dprint_compression_options(FlacEncodeContext *s)
155 AVCodecContext *avctx = s->avctx;
156 CompressionOptions *opt = &s->options;
158 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
160 switch (opt->lpc_type) {
161 case FF_LPC_TYPE_NONE:
162 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
164 case FF_LPC_TYPE_FIXED:
165 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
167 case FF_LPC_TYPE_LEVINSON:
168 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
170 case FF_LPC_TYPE_CHOLESKY:
171 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
172 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
176 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
177 opt->min_prediction_order, opt->max_prediction_order);
179 switch (opt->prediction_order_method) {
180 case ORDER_METHOD_EST:
181 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
183 case ORDER_METHOD_2LEVEL:
184 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
186 case ORDER_METHOD_4LEVEL:
187 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
189 case ORDER_METHOD_8LEVEL:
190 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
192 case ORDER_METHOD_SEARCH:
193 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
195 case ORDER_METHOD_LOG:
196 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
201 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
202 opt->min_partition_order, opt->max_partition_order);
204 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
206 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
207 opt->lpc_coeff_precision);
211 static av_cold int flac_encode_init(AVCodecContext *avctx)
213 int freq = avctx->sample_rate;
214 int channels = avctx->channels;
215 FlacEncodeContext *s = avctx->priv_data;
221 if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
224 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
226 s->channels = channels;
228 /* find samplerate in table */
231 for (i = 4; i < 12; i++) {
232 if (freq == ff_flac_sample_rate_table[i]) {
233 s->samplerate = ff_flac_sample_rate_table[i];
239 /* if not in table, samplerate is non-standard */
241 if (freq % 1000 == 0 && freq < 255000) {
243 s->sr_code[1] = freq / 1000;
244 } else if (freq % 10 == 0 && freq < 655350) {
246 s->sr_code[1] = freq / 10;
247 } else if (freq < 65535) {
249 s->sr_code[1] = freq;
253 s->samplerate = freq;
256 /* set compression option defaults based on avctx->compression_level */
257 if (avctx->compression_level < 0)
258 s->options.compression_level = 5;
260 s->options.compression_level = avctx->compression_level;
262 level = s->options.compression_level;
264 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
265 s->options.compression_level);
269 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
271 if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
272 s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
273 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
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})[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 if (s->options.prediction_order_method < 0)
282 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
283 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
284 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
285 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
286 ORDER_METHOD_SEARCH})[level];
288 if (s->options.min_partition_order > s->options.max_partition_order) {
289 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
290 s->options.min_partition_order, s->options.max_partition_order);
291 return AVERROR(EINVAL);
293 if (s->options.min_partition_order < 0)
294 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
295 if (s->options.max_partition_order < 0)
296 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
298 /* set compression option overrides from AVCodecContext */
299 #if FF_API_FLAC_GLOBAL_OPTS
300 if (avctx->lpc_type > FF_LPC_TYPE_DEFAULT) {
301 if (avctx->lpc_type > FF_LPC_TYPE_CHOLESKY) {
302 av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
305 s->options.lpc_type = avctx->lpc_type;
306 if (s->options.lpc_type == FF_LPC_TYPE_CHOLESKY) {
307 if (avctx->lpc_passes < 0) {
308 // default number of passes for Cholesky
309 s->options.lpc_passes = 2;
310 } else if (avctx->lpc_passes == 0) {
311 av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
315 s->options.lpc_passes = avctx->lpc_passes;
321 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
322 s->options.min_prediction_order = 0;
323 } else if (avctx->min_prediction_order >= 0) {
324 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
325 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
326 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
327 avctx->min_prediction_order);
330 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
331 avctx->min_prediction_order > MAX_LPC_ORDER) {
332 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
333 avctx->min_prediction_order);
336 s->options.min_prediction_order = avctx->min_prediction_order;
338 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
339 s->options.max_prediction_order = 0;
340 } else if (avctx->max_prediction_order >= 0) {
341 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
342 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
343 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
344 avctx->max_prediction_order);
347 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
348 avctx->max_prediction_order > MAX_LPC_ORDER) {
349 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
350 avctx->max_prediction_order);
353 s->options.max_prediction_order = avctx->max_prediction_order;
355 if (s->options.max_prediction_order < s->options.min_prediction_order) {
356 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
357 s->options.min_prediction_order, s->options.max_prediction_order);
361 #if FF_API_FLAC_GLOBAL_OPTS
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);
394 if (avctx->frame_size > 0) {
395 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
396 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
397 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
402 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
404 s->max_blocksize = s->avctx->frame_size;
406 #if FF_API_FLAC_GLOBAL_OPTS
407 /* set LPC precision */
408 if (avctx->lpc_coeff_precision > 0) {
409 if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
410 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
411 avctx->lpc_coeff_precision);
414 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
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 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
443 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
445 dprint_compression_options(s);
451 static void init_frame(FlacEncodeContext *s)
458 for (i = 0; i < 16; i++) {
459 if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
460 frame->blocksize = ff_flac_blocksize_table[i];
461 frame->bs_code[0] = i;
462 frame->bs_code[1] = 0;
467 frame->blocksize = s->avctx->frame_size;
468 if (frame->blocksize <= 256) {
469 frame->bs_code[0] = 6;
470 frame->bs_code[1] = frame->blocksize-1;
472 frame->bs_code[0] = 7;
473 frame->bs_code[1] = frame->blocksize-1;
477 for (ch = 0; ch < s->channels; ch++)
478 frame->subframes[ch].obits = 16;
480 frame->verbatim_only = 0;
485 * Copy channel-interleaved input samples into separate subframes.
487 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
493 for (i = 0, j = 0; i < frame->blocksize; i++)
494 for (ch = 0; ch < s->channels; ch++, j++)
495 frame->subframes[ch].samples[i] = samples[j];
499 static int rice_count_exact(int32_t *res, int n, int k)
504 for (i = 0; i < n; i++) {
505 int32_t v = -2 * res[i] - 1;
507 count += (v >> k) + 1 + k;
513 static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
516 int p, porder, psize;
520 /* subframe header */
524 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
526 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
527 count += s->frame.blocksize * sub->obits;
529 /* warm-up samples */
530 count += pred_order * sub->obits;
532 /* LPC coefficients */
533 if (sub->type == FLAC_SUBFRAME_LPC)
534 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
536 /* rice-encoded block */
539 /* partition order */
540 porder = sub->rc.porder;
541 psize = s->frame.blocksize >> porder;
547 for (p = 0; p < 1 << porder; p++) {
548 int k = sub->rc.params[p];
550 count += rice_count_exact(&sub->residual[i], part_end - i, k);
552 part_end = FFMIN(s->frame.blocksize, part_end + psize);
560 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
563 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
565 static int find_optimal_param(uint32_t sum, int n)
572 sum2 = sum - (n >> 1);
573 k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
574 return FFMIN(k, MAX_RICE_PARAM);
578 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
579 uint32_t *sums, int n, int pred_order)
585 part = (1 << porder);
588 cnt = (n >> porder) - pred_order;
589 for (i = 0; i < part; i++) {
590 k = find_optimal_param(sums[i], cnt);
592 all_bits += rice_encode_count(sums[i], cnt, k);
602 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
603 uint32_t sums[][MAX_PARTITIONS])
607 uint32_t *res, *res_end;
609 /* sums for highest level */
611 res = &data[pred_order];
612 res_end = &data[n >> pmax];
613 for (i = 0; i < parts; i++) {
615 while (res < res_end)
618 res_end += n >> pmax;
620 /* sums for lower levels */
621 for (i = pmax - 1; i >= pmin; i--) {
623 for (j = 0; j < parts; j++)
624 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
629 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
630 int32_t *data, int n, int pred_order)
633 uint32_t bits[MAX_PARTITION_ORDER+1];
637 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
639 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
640 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
641 assert(pmin <= pmax);
643 udata = av_malloc(n * sizeof(uint32_t));
644 for (i = 0; i < n; i++)
645 udata[i] = (2*data[i]) ^ (data[i]>>31);
647 calc_sums(pmin, pmax, udata, n, pred_order, sums);
650 bits[pmin] = UINT32_MAX;
651 for (i = pmin; i <= pmax; i++) {
652 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
653 if (bits[i] <= bits[opt_porder]) {
660 return bits[opt_porder];
664 static int get_max_p_order(int max_porder, int n, int order)
666 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
668 porder = FFMIN(porder, av_log2(n/order));
673 static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
674 FlacSubframe *sub, int pred_order)
676 int pmin = get_max_p_order(s->options.min_partition_order,
677 s->frame.blocksize, pred_order);
678 int pmax = get_max_p_order(s->options.max_partition_order,
679 s->frame.blocksize, pred_order);
681 uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
682 if (sub->type == FLAC_SUBFRAME_LPC)
683 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
684 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
685 s->frame.blocksize, pred_order);
690 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
695 for (i = 0; i < order; i++)
699 for (i = order; i < n; i++)
701 } else if (order == 1) {
702 for (i = order; i < n; i++)
703 res[i] = smp[i] - smp[i-1];
704 } else if (order == 2) {
705 int a = smp[order-1] - smp[order-2];
706 for (i = order; i < n; i += 2) {
707 int b = smp[i ] - smp[i-1];
709 a = smp[i+1] - smp[i ];
712 } else if (order == 3) {
713 int a = smp[order-1] - smp[order-2];
714 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
715 for (i = order; i < n; i += 2) {
716 int b = smp[i ] - smp[i-1];
719 a = smp[i+1] - smp[i ];
724 int a = smp[order-1] - smp[order-2];
725 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
726 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
727 for (i = order; i < n; i += 2) {
728 int b = smp[i ] - smp[i-1];
732 a = smp[i+1] - smp[i ];
742 int c = coefs[(x)-1];\
748 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
749 const int32_t *smp, int n, int order,
750 const int32_t *coefs, int shift, int big)
753 for (i = order; i < n; i += 2) {
754 int s = smp[i-order];
803 res[i ] = smp[i ] - (p0 >> shift);
804 res[i+1] = smp[i+1] - (p1 >> shift);
809 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
810 int order, const int32_t *coefs, int shift)
813 for (i = 0; i < order; i++)
816 for (i = order; i < n; i += 2) {
820 for (j = 0; j < order; j++) {
826 res[i ] = smp[i ] - (p0 >> shift);
827 res[i+1] = smp[i+1] - (p1 >> shift);
831 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
832 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
833 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
834 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
835 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
836 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
837 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
838 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
839 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
845 static int encode_residual_ch(FlacEncodeContext *s, int ch)
848 int min_order, max_order, opt_order, omethod;
851 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
852 int shift[MAX_LPC_ORDER];
856 sub = &frame->subframes[ch];
859 n = frame->blocksize;
862 for (i = 1; i < n; i++)
866 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
868 return subframe_count_exact(s, sub, 0);
872 if (frame->verbatim_only || n < 5) {
873 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
874 memcpy(res, smp, n * sizeof(int32_t));
875 return subframe_count_exact(s, sub, 0);
878 min_order = s->options.min_prediction_order;
879 max_order = s->options.max_prediction_order;
880 omethod = s->options.prediction_order_method;
883 sub->type = FLAC_SUBFRAME_FIXED;
884 if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
885 s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
886 uint32_t bits[MAX_FIXED_ORDER+1];
887 if (max_order > MAX_FIXED_ORDER)
888 max_order = MAX_FIXED_ORDER;
890 bits[0] = UINT32_MAX;
891 for (i = min_order; i <= max_order; i++) {
892 encode_residual_fixed(res, smp, n, i);
893 bits[i] = find_subframe_rice_params(s, sub, i);
894 if (bits[i] < bits[opt_order])
897 sub->order = opt_order;
898 sub->type_code = sub->type | sub->order;
899 if (sub->order != max_order) {
900 encode_residual_fixed(res, smp, n, sub->order);
901 find_subframe_rice_params(s, sub, sub->order);
903 return subframe_count_exact(s, sub, sub->order);
907 sub->type = FLAC_SUBFRAME_LPC;
908 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
909 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
910 s->options.lpc_passes, omethod,
913 if (omethod == ORDER_METHOD_2LEVEL ||
914 omethod == ORDER_METHOD_4LEVEL ||
915 omethod == ORDER_METHOD_8LEVEL) {
916 int levels = 1 << omethod;
917 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
919 int opt_index = levels-1;
920 opt_order = max_order-1;
921 bits[opt_index] = UINT32_MAX;
922 for (i = levels-1; i >= 0; i--) {
923 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
926 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
927 bits[i] = find_subframe_rice_params(s, sub, order+1);
928 if (bits[i] < bits[opt_index]) {
934 } else if (omethod == ORDER_METHOD_SEARCH) {
935 // brute-force optimal order search
936 uint32_t bits[MAX_LPC_ORDER];
938 bits[0] = UINT32_MAX;
939 for (i = min_order-1; i < max_order; i++) {
940 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
941 bits[i] = find_subframe_rice_params(s, sub, i+1);
942 if (bits[i] < bits[opt_order])
946 } else if (omethod == ORDER_METHOD_LOG) {
947 uint32_t bits[MAX_LPC_ORDER];
950 opt_order = min_order - 1 + (max_order-min_order)/3;
951 memset(bits, -1, sizeof(bits));
953 for (step = 16; step; step >>= 1) {
954 int last = opt_order;
955 for (i = last-step; i <= last+step; i += step) {
956 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
958 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
959 bits[i] = find_subframe_rice_params(s, sub, i+1);
960 if (bits[i] < bits[opt_order])
967 sub->order = opt_order;
968 sub->type_code = sub->type | (sub->order-1);
969 sub->shift = shift[sub->order-1];
970 for (i = 0; i < sub->order; i++)
971 sub->coefs[i] = coefs[sub->order-1][i];
973 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
975 find_subframe_rice_params(s, sub, sub->order);
977 return subframe_count_exact(s, sub, sub->order);
981 static int count_frame_header(FlacEncodeContext *s)
983 uint8_t av_unused tmp;
989 <1> Blocking strategy
990 <4> Block size in inter-channel samples
992 <4> Channel assignment
993 <3> Sample size in bits
998 /* coded frame number */
999 PUT_UTF8(s->frame_count, tmp, count += 8;)
1001 /* explicit block size */
1002 if (s->frame.bs_code[0] == 6)
1004 else if (s->frame.bs_code[0] == 7)
1007 /* explicit sample rate */
1008 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
1010 /* frame header CRC-8 */
1017 static int encode_frame(FlacEncodeContext *s)
1021 count = count_frame_header(s);
1023 for (ch = 0; ch < s->channels; ch++)
1024 count += encode_residual_ch(s, ch);
1026 count += (8 - (count & 7)) & 7; // byte alignment
1027 count += 16; // CRC-16
1033 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1041 /* calculate sum of 2nd order residual for each channel */
1042 sum[0] = sum[1] = sum[2] = sum[3] = 0;
1043 for (i = 2; i < n; i++) {
1044 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1045 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1046 sum[2] += FFABS((lt + rt) >> 1);
1047 sum[3] += FFABS(lt - rt);
1048 sum[0] += FFABS(lt);
1049 sum[1] += FFABS(rt);
1051 /* estimate bit counts */
1052 for (i = 0; i < 4; i++) {
1053 k = find_optimal_param(2 * sum[i], n);
1054 sum[i] = rice_encode_count( 2 * sum[i], n, k);
1057 /* calculate score for each mode */
1058 score[0] = sum[0] + sum[1];
1059 score[1] = sum[0] + sum[3];
1060 score[2] = sum[1] + sum[3];
1061 score[3] = sum[2] + sum[3];
1063 /* return mode with lowest score */
1065 for (i = 1; i < 4; i++)
1066 if (score[i] < score[best])
1069 return FLAC_CHMODE_INDEPENDENT;
1070 } else if (best == 1) {
1071 return FLAC_CHMODE_LEFT_SIDE;
1072 } else if (best == 2) {
1073 return FLAC_CHMODE_RIGHT_SIDE;
1075 return FLAC_CHMODE_MID_SIDE;
1081 * Perform stereo channel decorrelation.
1083 static void channel_decorrelation(FlacEncodeContext *s)
1086 int32_t *left, *right;
1090 n = frame->blocksize;
1091 left = frame->subframes[0].samples;
1092 right = frame->subframes[1].samples;
1094 if (s->channels != 2) {
1095 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1099 frame->ch_mode = estimate_stereo_mode(left, right, n);
1101 /* perform decorrelation and adjust bits-per-sample */
1102 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1104 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1106 for (i = 0; i < n; i++) {
1108 left[i] = (tmp + right[i]) >> 1;
1109 right[i] = tmp - right[i];
1111 frame->subframes[1].obits++;
1112 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1113 for (i = 0; i < n; i++)
1114 right[i] = left[i] - right[i];
1115 frame->subframes[1].obits++;
1117 for (i = 0; i < n; i++)
1118 left[i] -= right[i];
1119 frame->subframes[0].obits++;
1124 static void write_utf8(PutBitContext *pb, uint32_t val)
1127 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1131 static void write_frame_header(FlacEncodeContext *s)
1138 put_bits(&s->pb, 16, 0xFFF8);
1139 put_bits(&s->pb, 4, frame->bs_code[0]);
1140 put_bits(&s->pb, 4, s->sr_code[0]);
1142 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1143 put_bits(&s->pb, 4, s->channels-1);
1145 put_bits(&s->pb, 4, frame->ch_mode);
1147 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1148 put_bits(&s->pb, 1, 0);
1149 write_utf8(&s->pb, s->frame_count);
1151 if (frame->bs_code[0] == 6)
1152 put_bits(&s->pb, 8, frame->bs_code[1]);
1153 else if (frame->bs_code[0] == 7)
1154 put_bits(&s->pb, 16, frame->bs_code[1]);
1156 if (s->sr_code[0] == 12)
1157 put_bits(&s->pb, 8, s->sr_code[1]);
1158 else if (s->sr_code[0] > 12)
1159 put_bits(&s->pb, 16, s->sr_code[1]);
1161 flush_put_bits(&s->pb);
1162 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1163 put_bits_count(&s->pb) >> 3);
1164 put_bits(&s->pb, 8, crc);
1168 static void write_subframes(FlacEncodeContext *s)
1172 for (ch = 0; ch < s->channels; ch++) {
1173 FlacSubframe *sub = &s->frame.subframes[ch];
1174 int i, p, porder, psize;
1176 int32_t *res = sub->residual;
1177 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1179 /* subframe header */
1180 put_bits(&s->pb, 1, 0);
1181 put_bits(&s->pb, 6, sub->type_code);
1182 put_bits(&s->pb, 1, 0); /* no wasted bits */
1185 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1186 put_sbits(&s->pb, sub->obits, res[0]);
1187 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1188 while (res < frame_end)
1189 put_sbits(&s->pb, sub->obits, *res++);
1191 /* warm-up samples */
1192 for (i = 0; i < sub->order; i++)
1193 put_sbits(&s->pb, sub->obits, *res++);
1195 /* LPC coefficients */
1196 if (sub->type == FLAC_SUBFRAME_LPC) {
1197 int cbits = s->options.lpc_coeff_precision;
1198 put_bits( &s->pb, 4, cbits-1);
1199 put_sbits(&s->pb, 5, sub->shift);
1200 for (i = 0; i < sub->order; i++)
1201 put_sbits(&s->pb, cbits, sub->coefs[i]);
1204 /* rice-encoded block */
1205 put_bits(&s->pb, 2, 0);
1207 /* partition order */
1208 porder = sub->rc.porder;
1209 psize = s->frame.blocksize >> porder;
1210 put_bits(&s->pb, 4, porder);
1213 part_end = &sub->residual[psize];
1214 for (p = 0; p < 1 << porder; p++) {
1215 int k = sub->rc.params[p];
1216 put_bits(&s->pb, 4, k);
1217 while (res < part_end)
1218 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1219 part_end = FFMIN(frame_end, part_end + psize);
1226 static void write_frame_footer(FlacEncodeContext *s)
1229 flush_put_bits(&s->pb);
1230 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1231 put_bits_count(&s->pb)>>3));
1232 put_bits(&s->pb, 16, crc);
1233 flush_put_bits(&s->pb);
1237 static int write_frame(FlacEncodeContext *s, uint8_t *frame, int buf_size)
1239 init_put_bits(&s->pb, frame, buf_size);
1240 write_frame_header(s);
1242 write_frame_footer(s);
1243 return put_bits_count(&s->pb) >> 3;
1247 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1251 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1252 int16_t smp = av_le2ne16(samples[i]);
1253 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1256 av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1261 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1262 int buf_size, void *data)
1264 FlacEncodeContext *s;
1265 const int16_t *samples = data;
1266 int frame_bytes, out_bytes;
1268 s = avctx->priv_data;
1270 /* when the last block is reached, update the header in extradata */
1272 s->max_framesize = s->max_encoded_framesize;
1273 av_md5_final(s->md5ctx, s->md5sum);
1274 write_streaminfo(s, avctx->extradata);
1278 /* change max_framesize for small final frame */
1279 if (avctx->frame_size < s->frame.blocksize) {
1280 s->max_framesize = ff_flac_get_max_frame_size(avctx->frame_size,
1286 copy_samples(s, samples);
1288 channel_decorrelation(s);
1290 frame_bytes = encode_frame(s);
1292 /* fallback to verbatim mode if the compressed frame is larger than it
1293 would be if encoded uncompressed. */
1294 if (frame_bytes > s->max_framesize) {
1295 s->frame.verbatim_only = 1;
1296 frame_bytes = encode_frame(s);
1299 if (buf_size < frame_bytes) {
1300 av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1303 out_bytes = write_frame(s, frame, buf_size);
1306 avctx->coded_frame->pts = s->sample_count;
1307 s->sample_count += avctx->frame_size;
1308 update_md5_sum(s, samples);
1309 if (out_bytes > s->max_encoded_framesize)
1310 s->max_encoded_framesize = out_bytes;
1311 if (out_bytes < s->min_framesize)
1312 s->min_framesize = out_bytes;
1318 static av_cold int flac_encode_close(AVCodecContext *avctx)
1320 if (avctx->priv_data) {
1321 FlacEncodeContext *s = avctx->priv_data;
1322 av_freep(&s->md5ctx);
1323 ff_lpc_end(&s->lpc_ctx);
1325 av_freep(&avctx->extradata);
1326 avctx->extradata_size = 0;
1327 av_freep(&avctx->coded_frame);
1331 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1332 static const AVOption options[] = {
1333 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.dbl = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1334 { "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" },
1335 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1336 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1337 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1338 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1339 { "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 },
1340 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1341 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1342 { "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" },
1343 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1344 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1345 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1346 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1347 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1348 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1352 static const AVClass flac_encoder_class = {
1354 av_default_item_name,
1356 LIBAVUTIL_VERSION_INT,
1359 AVCodec ff_flac_encoder = {
1361 .type = AVMEDIA_TYPE_AUDIO,
1362 .id = CODEC_ID_FLAC,
1363 .priv_data_size = sizeof(FlacEncodeContext),
1364 .init = flac_encode_init,
1365 .encode = flac_encode_frame,
1366 .close = flac_encode_close,
1367 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1368 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1369 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1370 .priv_class = &flac_encoder_class,