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];
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 int flac_encode_init(AVCodecContext *avctx)
153 int freq = avctx->sample_rate;
154 int channels = avctx->channels;
155 FlacEncodeContext *s = avctx->priv_data;
161 dsputil_init(&s->dsp, avctx);
163 if (avctx->sample_fmt != SAMPLE_FMT_S16)
166 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
168 s->channels = channels;
170 /* find samplerate in table */
173 for (i = 4; i < 12; i++) {
174 if (freq == ff_flac_sample_rate_table[i]) {
175 s->samplerate = ff_flac_sample_rate_table[i];
181 /* if not in table, samplerate is non-standard */
183 if (freq % 1000 == 0 && freq < 255000) {
185 s->sr_code[1] = freq / 1000;
186 } else if (freq % 10 == 0 && freq < 655350) {
188 s->sr_code[1] = freq / 10;
189 } else if (freq < 65535) {
191 s->sr_code[1] = freq;
195 s->samplerate = freq;
198 /* set compression option defaults based on avctx->compression_level */
199 if (avctx->compression_level < 0)
200 s->options.compression_level = 5;
202 s->options.compression_level = avctx->compression_level;
203 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
205 level = s->options.compression_level;
207 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
208 s->options.compression_level);
212 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
214 s->options.lpc_type = ((int[]){ AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED,
215 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
216 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
217 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
218 AV_LPC_TYPE_LEVINSON})[level];
220 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
221 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
223 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
224 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
225 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
226 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
227 ORDER_METHOD_SEARCH})[level];
229 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
230 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
232 /* set compression option overrides from AVCodecContext */
233 #if LIBAVCODEC_VERSION_MAJOR < 53
234 /* for compatibility with deprecated AVCodecContext.use_lpc */
235 if (avctx->use_lpc == 0) {
236 s->options.lpc_type = AV_LPC_TYPE_FIXED;
237 } else if (avctx->use_lpc == 1) {
238 s->options.lpc_type = AV_LPC_TYPE_LEVINSON;
239 } else if (avctx->use_lpc > 1) {
240 s->options.lpc_type = AV_LPC_TYPE_CHOLESKY;
241 s->options.lpc_passes = avctx->use_lpc - 1;
244 if (avctx->lpc_type > AV_LPC_TYPE_DEFAULT) {
245 if (avctx->lpc_type > AV_LPC_TYPE_CHOLESKY) {
246 av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
249 s->options.lpc_type = avctx->lpc_type;
250 if (s->options.lpc_type == AV_LPC_TYPE_CHOLESKY) {
251 if (avctx->lpc_passes < 0) {
252 // default number of passes for Cholesky
253 s->options.lpc_passes = 2;
254 } else if (avctx->lpc_passes == 0) {
255 av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
259 s->options.lpc_passes = avctx->lpc_passes;
263 switch (s->options.lpc_type) {
264 case AV_LPC_TYPE_NONE:
265 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
267 case AV_LPC_TYPE_FIXED:
268 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
270 case AV_LPC_TYPE_LEVINSON:
271 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
273 case AV_LPC_TYPE_CHOLESKY:
274 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
275 s->options.lpc_passes, s->options.lpc_passes==1?"":"es");
279 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
280 s->options.min_prediction_order = 0;
281 } else if (avctx->min_prediction_order >= 0) {
282 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
283 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
284 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
285 avctx->min_prediction_order);
288 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
289 avctx->min_prediction_order > MAX_LPC_ORDER) {
290 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
291 avctx->min_prediction_order);
294 s->options.min_prediction_order = avctx->min_prediction_order;
296 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
297 s->options.max_prediction_order = 0;
298 } else if (avctx->max_prediction_order >= 0) {
299 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
300 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
301 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
302 avctx->max_prediction_order);
305 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
306 avctx->max_prediction_order > MAX_LPC_ORDER) {
307 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
308 avctx->max_prediction_order);
311 s->options.max_prediction_order = avctx->max_prediction_order;
313 if (s->options.max_prediction_order < s->options.min_prediction_order) {
314 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
315 s->options.min_prediction_order, s->options.max_prediction_order);
318 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
319 s->options.min_prediction_order, s->options.max_prediction_order);
321 if (avctx->prediction_order_method >= 0) {
322 if (avctx->prediction_order_method > ORDER_METHOD_LOG) {
323 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
324 avctx->prediction_order_method);
327 s->options.prediction_order_method = avctx->prediction_order_method;
329 switch (s->options.prediction_order_method) {
330 case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
332 case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
334 case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
336 case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
338 case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
339 "full search"); break;
340 case ORDER_METHOD_LOG: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
341 "log search"); break;
344 if (avctx->min_partition_order >= 0) {
345 if (avctx->min_partition_order > MAX_PARTITION_ORDER) {
346 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
347 avctx->min_partition_order);
350 s->options.min_partition_order = avctx->min_partition_order;
352 if (avctx->max_partition_order >= 0) {
353 if (avctx->max_partition_order > MAX_PARTITION_ORDER) {
354 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
355 avctx->max_partition_order);
358 s->options.max_partition_order = avctx->max_partition_order;
360 if (s->options.max_partition_order < s->options.min_partition_order) {
361 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
362 s->options.min_partition_order, s->options.max_partition_order);
365 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
366 s->options.min_partition_order, s->options.max_partition_order);
368 if (avctx->frame_size > 0) {
369 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
370 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
371 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
376 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
378 s->max_blocksize = s->avctx->frame_size;
379 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->avctx->frame_size);
381 /* set LPC precision */
382 if (avctx->lpc_coeff_precision > 0) {
383 if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
384 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
385 avctx->lpc_coeff_precision);
388 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
390 /* default LPC precision */
391 s->options.lpc_coeff_precision = 15;
393 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
394 s->options.lpc_coeff_precision);
396 /* set maximum encoded frame size in verbatim mode */
397 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
400 /* initialize MD5 context */
401 s->md5ctx = av_malloc(av_md5_size);
403 return AVERROR(ENOMEM);
404 av_md5_init(s->md5ctx);
406 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
407 write_streaminfo(s, streaminfo);
408 avctx->extradata = streaminfo;
409 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
412 s->min_framesize = s->max_framesize;
414 avctx->coded_frame = avcodec_alloc_frame();
415 avctx->coded_frame->key_frame = 1;
421 static void init_frame(FlacEncodeContext *s)
428 for (i = 0; i < 16; i++) {
429 if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
430 frame->blocksize = ff_flac_blocksize_table[i];
431 frame->bs_code[0] = i;
432 frame->bs_code[1] = 0;
437 frame->blocksize = s->avctx->frame_size;
438 if (frame->blocksize <= 256) {
439 frame->bs_code[0] = 6;
440 frame->bs_code[1] = frame->blocksize-1;
442 frame->bs_code[0] = 7;
443 frame->bs_code[1] = frame->blocksize-1;
447 for (ch = 0; ch < s->channels; ch++)
448 frame->subframes[ch].obits = 16;
453 * Copy channel-interleaved input samples into separate subframes.
455 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
461 for (i = 0, j = 0; i < frame->blocksize; i++)
462 for (ch = 0; ch < s->channels; ch++, j++)
463 frame->subframes[ch].samples[i] = samples[j];
467 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
470 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
472 static int find_optimal_param(uint32_t sum, int n)
479 sum2 = sum - (n >> 1);
480 k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
481 return FFMIN(k, MAX_RICE_PARAM);
485 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
486 uint32_t *sums, int n, int pred_order)
492 part = (1 << porder);
495 cnt = (n >> porder) - pred_order;
496 for (i = 0; i < part; i++) {
497 k = find_optimal_param(sums[i], cnt);
499 all_bits += rice_encode_count(sums[i], cnt, k);
509 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
510 uint32_t sums[][MAX_PARTITIONS])
514 uint32_t *res, *res_end;
516 /* sums for highest level */
518 res = &data[pred_order];
519 res_end = &data[n >> pmax];
520 for (i = 0; i < parts; i++) {
522 while (res < res_end)
525 res_end += n >> pmax;
527 /* sums for lower levels */
528 for (i = pmax - 1; i >= pmin; i--) {
530 for (j = 0; j < parts; j++)
531 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
536 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
537 int32_t *data, int n, int pred_order)
540 uint32_t bits[MAX_PARTITION_ORDER+1];
544 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
546 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
547 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
548 assert(pmin <= pmax);
550 udata = av_malloc(n * sizeof(uint32_t));
551 for (i = 0; i < n; i++)
552 udata[i] = (2*data[i]) ^ (data[i]>>31);
554 calc_sums(pmin, pmax, udata, n, pred_order, sums);
557 bits[pmin] = UINT32_MAX;
558 for (i = pmin; i <= pmax; i++) {
559 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
560 if (bits[i] <= bits[opt_porder]) {
567 return bits[opt_porder];
571 static int get_max_p_order(int max_porder, int n, int order)
573 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
575 porder = FFMIN(porder, av_log2(n/order));
580 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
581 int32_t *data, int n, int pred_order,
585 pmin = get_max_p_order(pmin, n, pred_order);
586 pmax = get_max_p_order(pmax, n, pred_order);
587 bits = pred_order * bps + 6;
588 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
593 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
594 int32_t *data, int n, int pred_order,
595 int bps, int precision)
598 pmin = get_max_p_order(pmin, n, pred_order);
599 pmax = get_max_p_order(pmax, n, pred_order);
600 bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
601 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
606 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
609 memcpy(res, smp, n * sizeof(int32_t));
613 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
618 for (i = 0; i < order; i++)
622 for (i = order; i < n; i++)
624 } else if (order == 1) {
625 for (i = order; i < n; i++)
626 res[i] = smp[i] - smp[i-1];
627 } else if (order == 2) {
628 int a = smp[order-1] - smp[order-2];
629 for (i = order; i < n; i += 2) {
630 int b = smp[i ] - smp[i-1];
632 a = smp[i+1] - smp[i ];
635 } else if (order == 3) {
636 int a = smp[order-1] - smp[order-2];
637 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
638 for (i = order; i < n; i += 2) {
639 int b = smp[i ] - smp[i-1];
642 a = smp[i+1] - smp[i ];
647 int a = smp[order-1] - smp[order-2];
648 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
649 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
650 for (i = order; i < n; i += 2) {
651 int b = smp[i ] - smp[i-1];
655 a = smp[i+1] - smp[i ];
665 int c = coefs[(x)-1];\
671 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
672 const int32_t *smp, int n, int order,
673 const int32_t *coefs, int shift, int big)
676 for (i = order; i < n; i += 2) {
677 int s = smp[i-order];
726 res[i ] = smp[i ] - (p0 >> shift);
727 res[i+1] = smp[i+1] - (p1 >> shift);
732 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
733 int order, const int32_t *coefs, int shift)
736 for (i = 0; i < order; i++)
739 for (i = order; i < n; i += 2) {
743 for (j = 0; j < order; j++) {
749 res[i ] = smp[i ] - (p0 >> shift);
750 res[i+1] = smp[i+1] - (p1 >> shift);
754 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
755 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
756 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
757 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
758 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
759 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
760 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
761 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
762 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
768 static int encode_residual(FlacEncodeContext *ctx, int ch)
771 int min_order, max_order, opt_order, precision, omethod;
772 int min_porder, max_porder;
775 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
776 int shift[MAX_LPC_ORDER];
780 sub = &frame->subframes[ch];
783 n = frame->blocksize;
786 for (i = 1; i < n; i++)
790 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
797 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
798 encode_residual_verbatim(res, smp, n);
799 return sub->obits * n;
802 min_order = ctx->options.min_prediction_order;
803 max_order = ctx->options.max_prediction_order;
804 min_porder = ctx->options.min_partition_order;
805 max_porder = ctx->options.max_partition_order;
806 precision = ctx->options.lpc_coeff_precision;
807 omethod = ctx->options.prediction_order_method;
810 if (ctx->options.lpc_type == AV_LPC_TYPE_NONE ||
811 ctx->options.lpc_type == AV_LPC_TYPE_FIXED || n <= max_order) {
812 uint32_t bits[MAX_FIXED_ORDER+1];
813 if (max_order > MAX_FIXED_ORDER)
814 max_order = MAX_FIXED_ORDER;
816 bits[0] = UINT32_MAX;
817 for (i = min_order; i <= max_order; i++) {
818 encode_residual_fixed(res, smp, n, i);
819 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
821 if (bits[i] < bits[opt_order])
824 sub->order = opt_order;
825 sub->type = FLAC_SUBFRAME_FIXED;
826 sub->type_code = sub->type | sub->order;
827 if (sub->order != max_order) {
828 encode_residual_fixed(res, smp, n, sub->order);
829 return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
830 sub->order, sub->obits);
832 return bits[sub->order];
836 opt_order = ff_lpc_calc_coefs(&ctx->dsp, smp, n, min_order, max_order,
837 precision, coefs, shift, ctx->options.lpc_type,
838 ctx->options.lpc_passes, omethod,
841 if (omethod == ORDER_METHOD_2LEVEL ||
842 omethod == ORDER_METHOD_4LEVEL ||
843 omethod == ORDER_METHOD_8LEVEL) {
844 int levels = 1 << omethod;
845 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
847 int opt_index = levels-1;
848 opt_order = max_order-1;
849 bits[opt_index] = UINT32_MAX;
850 for (i = levels-1; i >= 0; i--) {
851 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
854 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
855 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
856 res, n, order+1, sub->obits, precision);
857 if (bits[i] < bits[opt_index]) {
863 } else if (omethod == ORDER_METHOD_SEARCH) {
864 // brute-force optimal order search
865 uint32_t bits[MAX_LPC_ORDER];
867 bits[0] = UINT32_MAX;
868 for (i = min_order-1; i < max_order; i++) {
869 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
870 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
871 res, n, i+1, sub->obits, precision);
872 if (bits[i] < bits[opt_order])
876 } else if (omethod == ORDER_METHOD_LOG) {
877 uint32_t bits[MAX_LPC_ORDER];
880 opt_order = min_order - 1 + (max_order-min_order)/3;
881 memset(bits, -1, sizeof(bits));
883 for (step = 16; step; step >>= 1) {
884 int last = opt_order;
885 for (i = last-step; i <= last+step; i += step) {
886 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
888 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
889 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
890 res, n, i+1, sub->obits,
892 if (bits[i] < bits[opt_order])
899 sub->order = opt_order;
900 sub->type = FLAC_SUBFRAME_LPC;
901 sub->type_code = sub->type | (sub->order-1);
902 sub->shift = shift[sub->order-1];
903 for (i = 0; i < sub->order; i++)
904 sub->coefs[i] = coefs[sub->order-1][i];
906 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
908 return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n,
909 sub->order, sub->obits, precision);
913 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
921 sub = &frame->subframes[ch];
924 n = frame->blocksize;
927 for (i = 1; i < n; i++)
928 if (smp[i] != smp[0])
931 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
937 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
938 encode_residual_verbatim(res, smp, n);
939 return sub->obits * n;
943 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
951 /* calculate sum of 2nd order residual for each channel */
952 sum[0] = sum[1] = sum[2] = sum[3] = 0;
953 for (i = 2; i < n; i++) {
954 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
955 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
956 sum[2] += FFABS((lt + rt) >> 1);
957 sum[3] += FFABS(lt - rt);
961 /* estimate bit counts */
962 for (i = 0; i < 4; i++) {
963 k = find_optimal_param(2 * sum[i], n);
964 sum[i] = rice_encode_count( 2 * sum[i], n, k);
967 /* calculate score for each mode */
968 score[0] = sum[0] + sum[1];
969 score[1] = sum[0] + sum[3];
970 score[2] = sum[1] + sum[3];
971 score[3] = sum[2] + sum[3];
973 /* return mode with lowest score */
975 for (i = 1; i < 4; i++)
976 if (score[i] < score[best])
979 return FLAC_CHMODE_INDEPENDENT;
980 } else if (best == 1) {
981 return FLAC_CHMODE_LEFT_SIDE;
982 } else if (best == 2) {
983 return FLAC_CHMODE_RIGHT_SIDE;
985 return FLAC_CHMODE_MID_SIDE;
991 * Perform stereo channel decorrelation.
993 static void channel_decorrelation(FlacEncodeContext *ctx)
996 int32_t *left, *right;
1000 n = frame->blocksize;
1001 left = frame->subframes[0].samples;
1002 right = frame->subframes[1].samples;
1004 if (ctx->channels != 2) {
1005 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1009 frame->ch_mode = estimate_stereo_mode(left, right, n);
1011 /* perform decorrelation and adjust bits-per-sample */
1012 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1014 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1016 for (i = 0; i < n; i++) {
1018 left[i] = (tmp + right[i]) >> 1;
1019 right[i] = tmp - right[i];
1021 frame->subframes[1].obits++;
1022 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1023 for (i = 0; i < n; i++)
1024 right[i] = left[i] - right[i];
1025 frame->subframes[1].obits++;
1027 for (i = 0; i < n; i++)
1028 left[i] -= right[i];
1029 frame->subframes[0].obits++;
1034 static void write_utf8(PutBitContext *pb, uint32_t val)
1037 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1041 static void output_frame_header(FlacEncodeContext *s)
1048 put_bits(&s->pb, 16, 0xFFF8);
1049 put_bits(&s->pb, 4, frame->bs_code[0]);
1050 put_bits(&s->pb, 4, s->sr_code[0]);
1052 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1053 put_bits(&s->pb, 4, s->channels-1);
1055 put_bits(&s->pb, 4, frame->ch_mode);
1057 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1058 put_bits(&s->pb, 1, 0);
1059 write_utf8(&s->pb, s->frame_count);
1061 if (frame->bs_code[0] == 6)
1062 put_bits(&s->pb, 8, frame->bs_code[1]);
1063 else if (frame->bs_code[0] == 7)
1064 put_bits(&s->pb, 16, frame->bs_code[1]);
1066 if (s->sr_code[0] == 12)
1067 put_bits(&s->pb, 8, s->sr_code[1]);
1068 else if (s->sr_code[0] > 12)
1069 put_bits(&s->pb, 16, s->sr_code[1]);
1071 flush_put_bits(&s->pb);
1072 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1073 put_bits_count(&s->pb) >> 3);
1074 put_bits(&s->pb, 8, crc);
1078 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1083 sub = &s->frame.subframes[ch];
1084 res = sub->residual[0];
1085 put_sbits(&s->pb, sub->obits, res);
1089 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1097 sub = &frame->subframes[ch];
1099 for (i = 0; i < frame->blocksize; i++) {
1100 res = sub->residual[i];
1101 put_sbits(&s->pb, sub->obits, res);
1106 static void output_residual(FlacEncodeContext *ctx, int ch)
1108 int i, j, p, n, parts;
1109 int k, porder, psize, res_cnt;
1114 frame = &ctx->frame;
1115 sub = &frame->subframes[ch];
1116 res = sub->residual;
1117 n = frame->blocksize;
1119 /* rice-encoded block */
1120 put_bits(&ctx->pb, 2, 0);
1122 /* partition order */
1123 porder = sub->rc.porder;
1124 psize = n >> porder;
1125 parts = (1 << porder);
1126 put_bits(&ctx->pb, 4, porder);
1127 res_cnt = psize - sub->order;
1131 for (p = 0; p < parts; p++) {
1132 k = sub->rc.params[p];
1133 put_bits(&ctx->pb, 4, k);
1136 for (i = 0; i < res_cnt && j < n; i++, j++)
1137 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1142 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1148 frame = &ctx->frame;
1149 sub = &frame->subframes[ch];
1151 /* warm-up samples */
1152 for (i = 0; i < sub->order; i++)
1153 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1156 output_residual(ctx, ch);
1160 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1166 frame = &ctx->frame;
1167 sub = &frame->subframes[ch];
1169 /* warm-up samples */
1170 for (i = 0; i < sub->order; i++)
1171 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1173 /* LPC coefficients */
1174 cbits = ctx->options.lpc_coeff_precision;
1175 put_bits( &ctx->pb, 4, cbits-1);
1176 put_sbits(&ctx->pb, 5, sub->shift);
1177 for (i = 0; i < sub->order; i++)
1178 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1181 output_residual(ctx, ch);
1185 static void output_subframes(FlacEncodeContext *s)
1193 for (ch = 0; ch < s->channels; ch++) {
1194 sub = &frame->subframes[ch];
1196 /* subframe header */
1197 put_bits(&s->pb, 1, 0);
1198 put_bits(&s->pb, 6, sub->type_code);
1199 put_bits(&s->pb, 1, 0); /* no wasted bits */
1202 if(sub->type == FLAC_SUBFRAME_CONSTANT)
1203 output_subframe_constant(s, ch);
1204 else if(sub->type == FLAC_SUBFRAME_VERBATIM)
1205 output_subframe_verbatim(s, ch);
1206 else if(sub->type == FLAC_SUBFRAME_FIXED)
1207 output_subframe_fixed(s, ch);
1208 else if(sub->type == FLAC_SUBFRAME_LPC)
1209 output_subframe_lpc(s, ch);
1214 static void output_frame_footer(FlacEncodeContext *s)
1217 flush_put_bits(&s->pb);
1218 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1219 put_bits_count(&s->pb)>>3));
1220 put_bits(&s->pb, 16, crc);
1221 flush_put_bits(&s->pb);
1225 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1229 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1230 int16_t smp = av_le2ne16(samples[i]);
1231 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1234 av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1239 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1240 int buf_size, void *data)
1243 FlacEncodeContext *s;
1244 const int16_t *samples = data;
1248 s = avctx->priv_data;
1250 if (buf_size < s->max_framesize * 2) {
1251 av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1255 /* when the last block is reached, update the header in extradata */
1257 s->max_framesize = s->max_encoded_framesize;
1258 av_md5_final(s->md5ctx, s->md5sum);
1259 write_streaminfo(s, avctx->extradata);
1265 copy_samples(s, samples);
1267 channel_decorrelation(s);
1269 for (ch = 0; ch < s->channels; ch++)
1270 encode_residual(s, ch);
1273 init_put_bits(&s->pb, frame, buf_size);
1274 output_frame_header(s);
1275 output_subframes(s);
1276 output_frame_footer(s);
1277 out_bytes = put_bits_count(&s->pb) >> 3;
1279 if (out_bytes > s->max_framesize) {
1281 /* still too large. must be an error. */
1282 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1286 /* frame too large. use verbatim mode */
1287 for (ch = 0; ch < s->channels; ch++)
1288 encode_residual_v(s, ch);
1294 s->sample_count += avctx->frame_size;
1295 update_md5_sum(s, samples);
1296 if (out_bytes > s->max_encoded_framesize)
1297 s->max_encoded_framesize = out_bytes;
1298 if (out_bytes < s->min_framesize)
1299 s->min_framesize = out_bytes;
1305 static av_cold int flac_encode_close(AVCodecContext *avctx)
1307 if (avctx->priv_data) {
1308 FlacEncodeContext *s = avctx->priv_data;
1309 av_freep(&s->md5ctx);
1311 av_freep(&avctx->extradata);
1312 avctx->extradata_size = 0;
1313 av_freep(&avctx->coded_frame);
1318 AVCodec flac_encoder = {
1322 sizeof(FlacEncodeContext),
1327 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1328 .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
1329 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),