3 * Copyright (c) 2006 Justin Ruggles <justin.ruggles@gmail.com>
5 * This file is part of Libav.
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/crc.h"
23 #include "libavutil/md5.h"
24 #include "libavutil/opt.h"
33 #define FLAC_SUBFRAME_CONSTANT 0
34 #define FLAC_SUBFRAME_VERBATIM 1
35 #define FLAC_SUBFRAME_FIXED 8
36 #define FLAC_SUBFRAME_LPC 32
38 #define MAX_FIXED_ORDER 4
39 #define MAX_PARTITION_ORDER 8
40 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
41 #define MAX_LPC_PRECISION 15
42 #define MAX_LPC_SHIFT 15
43 #define MAX_RICE_PARAM 14
45 typedef struct CompressionOptions {
46 int compression_level;
48 enum FFLPCType lpc_type;
50 int lpc_coeff_precision;
51 int min_prediction_order;
52 int max_prediction_order;
53 int prediction_order_method;
54 int min_partition_order;
55 int max_partition_order;
59 typedef struct RiceContext {
61 int params[MAX_PARTITIONS];
64 typedef struct FlacSubframe {
69 int32_t coefs[MAX_LPC_ORDER];
72 int32_t samples[FLAC_MAX_BLOCKSIZE];
73 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
76 typedef struct FlacFrame {
77 FlacSubframe subframes[FLAC_MAX_CHANNELS];
85 typedef struct FlacEncodeContext {
94 int max_encoded_framesize;
96 uint64_t sample_count;
99 CompressionOptions options;
100 AVCodecContext *avctx;
102 struct AVMD5 *md5ctx;
107 * Write streaminfo metadata block to byte array.
109 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
113 memset(header, 0, FLAC_STREAMINFO_SIZE);
114 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
116 /* streaminfo metadata block */
117 put_bits(&pb, 16, s->max_blocksize);
118 put_bits(&pb, 16, s->max_blocksize);
119 put_bits(&pb, 24, s->min_framesize);
120 put_bits(&pb, 24, s->max_framesize);
121 put_bits(&pb, 20, s->samplerate);
122 put_bits(&pb, 3, s->channels-1);
123 put_bits(&pb, 5, 15); /* bits per sample - 1 */
124 /* write 36-bit sample count in 2 put_bits() calls */
125 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
126 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
128 memcpy(&header[18], s->md5sum, 16);
133 * Set blocksize based on samplerate.
134 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
136 static int select_blocksize(int samplerate, int block_time_ms)
142 assert(samplerate > 0);
143 blocksize = ff_flac_blocksize_table[1];
144 target = (samplerate * block_time_ms) / 1000;
145 for (i = 0; i < 16; i++) {
146 if (target >= ff_flac_blocksize_table[i] &&
147 ff_flac_blocksize_table[i] > blocksize) {
148 blocksize = ff_flac_blocksize_table[i];
155 static av_cold void dprint_compression_options(FlacEncodeContext *s)
157 AVCodecContext *avctx = s->avctx;
158 CompressionOptions *opt = &s->options;
160 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
162 switch (opt->lpc_type) {
163 case FF_LPC_TYPE_NONE:
164 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
166 case FF_LPC_TYPE_FIXED:
167 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
169 case FF_LPC_TYPE_LEVINSON:
170 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
172 case FF_LPC_TYPE_CHOLESKY:
173 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
174 opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
178 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
179 opt->min_prediction_order, opt->max_prediction_order);
181 switch (opt->prediction_order_method) {
182 case ORDER_METHOD_EST:
183 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
185 case ORDER_METHOD_2LEVEL:
186 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
188 case ORDER_METHOD_4LEVEL:
189 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
191 case ORDER_METHOD_8LEVEL:
192 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
194 case ORDER_METHOD_SEARCH:
195 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
197 case ORDER_METHOD_LOG:
198 av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
203 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
204 opt->min_partition_order, opt->max_partition_order);
206 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
208 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
209 opt->lpc_coeff_precision);
213 static av_cold int flac_encode_init(AVCodecContext *avctx)
215 int freq = avctx->sample_rate;
216 int channels = avctx->channels;
217 FlacEncodeContext *s = avctx->priv_data;
223 if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
226 if (channels < 1 || channels > FLAC_MAX_CHANNELS)
228 s->channels = channels;
230 /* find samplerate in table */
233 for (i = 4; i < 12; i++) {
234 if (freq == ff_flac_sample_rate_table[i]) {
235 s->samplerate = ff_flac_sample_rate_table[i];
241 /* if not in table, samplerate is non-standard */
243 if (freq % 1000 == 0 && freq < 255000) {
245 s->sr_code[1] = freq / 1000;
246 } else if (freq % 10 == 0 && freq < 655350) {
248 s->sr_code[1] = freq / 10;
249 } else if (freq < 65535) {
251 s->sr_code[1] = freq;
255 s->samplerate = freq;
258 /* set compression option defaults based on avctx->compression_level */
259 if (avctx->compression_level < 0)
260 s->options.compression_level = 5;
262 s->options.compression_level = avctx->compression_level;
264 level = s->options.compression_level;
266 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
267 s->options.compression_level);
271 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
273 if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
274 s->options.lpc_type = ((int[]){ FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED, FF_LPC_TYPE_FIXED,
275 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
276 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
277 FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
278 FF_LPC_TYPE_LEVINSON})[level];
280 s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
281 s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
283 if (s->options.prediction_order_method < 0)
284 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
285 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
286 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
287 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
288 ORDER_METHOD_SEARCH})[level];
290 if (s->options.min_partition_order > s->options.max_partition_order) {
291 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
292 s->options.min_partition_order, s->options.max_partition_order);
293 return AVERROR(EINVAL);
295 if (s->options.min_partition_order < 0)
296 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
297 if (s->options.max_partition_order < 0)
298 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
300 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
301 s->options.min_prediction_order = 0;
302 } else if (avctx->min_prediction_order >= 0) {
303 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
304 if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
305 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
306 avctx->min_prediction_order);
309 } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
310 avctx->min_prediction_order > MAX_LPC_ORDER) {
311 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
312 avctx->min_prediction_order);
315 s->options.min_prediction_order = avctx->min_prediction_order;
317 if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
318 s->options.max_prediction_order = 0;
319 } else if (avctx->max_prediction_order >= 0) {
320 if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
321 if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
322 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
323 avctx->max_prediction_order);
326 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
327 avctx->max_prediction_order > MAX_LPC_ORDER) {
328 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
329 avctx->max_prediction_order);
332 s->options.max_prediction_order = avctx->max_prediction_order;
334 if (s->options.max_prediction_order < s->options.min_prediction_order) {
335 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
336 s->options.min_prediction_order, s->options.max_prediction_order);
340 if (avctx->frame_size > 0) {
341 if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
342 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
343 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
348 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
350 s->max_blocksize = s->avctx->frame_size;
352 /* set maximum encoded frame size in verbatim mode */
353 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
356 /* initialize MD5 context */
357 s->md5ctx = av_malloc(av_md5_size);
359 return AVERROR(ENOMEM);
360 av_md5_init(s->md5ctx);
362 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
364 return AVERROR(ENOMEM);
365 write_streaminfo(s, streaminfo);
366 avctx->extradata = streaminfo;
367 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
370 s->min_framesize = s->max_framesize;
372 #if FF_API_OLD_ENCODE_AUDIO
373 avctx->coded_frame = avcodec_alloc_frame();
374 if (!avctx->coded_frame)
375 return AVERROR(ENOMEM);
378 ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
379 s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
381 dprint_compression_options(s);
387 static void init_frame(FlacEncodeContext *s, int nb_samples)
394 for (i = 0; i < 16; i++) {
395 if (nb_samples == ff_flac_blocksize_table[i]) {
396 frame->blocksize = ff_flac_blocksize_table[i];
397 frame->bs_code[0] = i;
398 frame->bs_code[1] = 0;
403 frame->blocksize = nb_samples;
404 if (frame->blocksize <= 256) {
405 frame->bs_code[0] = 6;
406 frame->bs_code[1] = frame->blocksize-1;
408 frame->bs_code[0] = 7;
409 frame->bs_code[1] = frame->blocksize-1;
413 for (ch = 0; ch < s->channels; ch++)
414 frame->subframes[ch].obits = 16;
416 frame->verbatim_only = 0;
421 * Copy channel-interleaved input samples into separate subframes.
423 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
429 for (i = 0, j = 0; i < frame->blocksize; i++)
430 for (ch = 0; ch < s->channels; ch++, j++)
431 frame->subframes[ch].samples[i] = samples[j];
435 static int rice_count_exact(int32_t *res, int n, int k)
440 for (i = 0; i < n; i++) {
441 int32_t v = -2 * res[i] - 1;
443 count += (v >> k) + 1 + k;
449 static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
452 int p, porder, psize;
456 /* subframe header */
460 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
462 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
463 count += s->frame.blocksize * sub->obits;
465 /* warm-up samples */
466 count += pred_order * sub->obits;
468 /* LPC coefficients */
469 if (sub->type == FLAC_SUBFRAME_LPC)
470 count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
472 /* rice-encoded block */
475 /* partition order */
476 porder = sub->rc.porder;
477 psize = s->frame.blocksize >> porder;
483 for (p = 0; p < 1 << porder; p++) {
484 int k = sub->rc.params[p];
486 count += rice_count_exact(&sub->residual[i], part_end - i, k);
488 part_end = FFMIN(s->frame.blocksize, part_end + psize);
496 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
499 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
501 static int find_optimal_param(uint32_t sum, int n)
508 sum2 = sum - (n >> 1);
509 k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
510 return FFMIN(k, MAX_RICE_PARAM);
514 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
515 uint32_t *sums, int n, int pred_order)
521 part = (1 << porder);
524 cnt = (n >> porder) - pred_order;
525 for (i = 0; i < part; i++) {
526 k = find_optimal_param(sums[i], cnt);
528 all_bits += rice_encode_count(sums[i], cnt, k);
538 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
539 uint32_t sums[][MAX_PARTITIONS])
543 uint32_t *res, *res_end;
545 /* sums for highest level */
547 res = &data[pred_order];
548 res_end = &data[n >> pmax];
549 for (i = 0; i < parts; i++) {
551 while (res < res_end)
554 res_end += n >> pmax;
556 /* sums for lower levels */
557 for (i = pmax - 1; i >= pmin; i--) {
559 for (j = 0; j < parts; j++)
560 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
565 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
566 int32_t *data, int n, int pred_order)
569 uint32_t bits[MAX_PARTITION_ORDER+1];
573 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
575 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
576 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
577 assert(pmin <= pmax);
579 udata = av_malloc(n * sizeof(uint32_t));
580 for (i = 0; i < n; i++)
581 udata[i] = (2*data[i]) ^ (data[i]>>31);
583 calc_sums(pmin, pmax, udata, n, pred_order, sums);
586 bits[pmin] = UINT32_MAX;
587 for (i = pmin; i <= pmax; i++) {
588 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
589 if (bits[i] <= bits[opt_porder]) {
596 return bits[opt_porder];
600 static int get_max_p_order(int max_porder, int n, int order)
602 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
604 porder = FFMIN(porder, av_log2(n/order));
609 static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
610 FlacSubframe *sub, int pred_order)
612 int pmin = get_max_p_order(s->options.min_partition_order,
613 s->frame.blocksize, pred_order);
614 int pmax = get_max_p_order(s->options.max_partition_order,
615 s->frame.blocksize, pred_order);
617 uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
618 if (sub->type == FLAC_SUBFRAME_LPC)
619 bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
620 bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
621 s->frame.blocksize, pred_order);
626 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
631 for (i = 0; i < order; i++)
635 for (i = order; i < n; i++)
637 } else if (order == 1) {
638 for (i = order; i < n; i++)
639 res[i] = smp[i] - smp[i-1];
640 } else if (order == 2) {
641 int a = smp[order-1] - smp[order-2];
642 for (i = order; i < n; i += 2) {
643 int b = smp[i ] - smp[i-1];
645 a = smp[i+1] - smp[i ];
648 } else if (order == 3) {
649 int a = smp[order-1] - smp[order-2];
650 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
651 for (i = order; i < n; i += 2) {
652 int b = smp[i ] - smp[i-1];
655 a = smp[i+1] - smp[i ];
660 int a = smp[order-1] - smp[order-2];
661 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
662 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
663 for (i = order; i < n; i += 2) {
664 int b = smp[i ] - smp[i-1];
668 a = smp[i+1] - smp[i ];
678 int c = coefs[(x)-1];\
684 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
685 const int32_t *smp, int n, int order,
686 const int32_t *coefs, int shift, int big)
689 for (i = order; i < n; i += 2) {
690 int s = smp[i-order];
739 res[i ] = smp[i ] - (p0 >> shift);
740 res[i+1] = smp[i+1] - (p1 >> shift);
745 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
746 int order, const int32_t *coefs, int shift)
749 for (i = 0; i < order; i++)
752 for (i = order; i < n; i += 2) {
756 for (j = 0; j < order; j++) {
762 res[i ] = smp[i ] - (p0 >> shift);
763 res[i+1] = smp[i+1] - (p1 >> shift);
767 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
768 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
769 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
770 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
771 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
772 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
773 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
774 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
775 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
781 static int encode_residual_ch(FlacEncodeContext *s, int ch)
784 int min_order, max_order, opt_order, omethod;
787 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
788 int shift[MAX_LPC_ORDER];
792 sub = &frame->subframes[ch];
795 n = frame->blocksize;
798 for (i = 1; i < n; i++)
802 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
804 return subframe_count_exact(s, sub, 0);
808 if (frame->verbatim_only || n < 5) {
809 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
810 memcpy(res, smp, n * sizeof(int32_t));
811 return subframe_count_exact(s, sub, 0);
814 min_order = s->options.min_prediction_order;
815 max_order = s->options.max_prediction_order;
816 omethod = s->options.prediction_order_method;
819 sub->type = FLAC_SUBFRAME_FIXED;
820 if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
821 s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
822 uint32_t bits[MAX_FIXED_ORDER+1];
823 if (max_order > MAX_FIXED_ORDER)
824 max_order = MAX_FIXED_ORDER;
826 bits[0] = UINT32_MAX;
827 for (i = min_order; i <= max_order; i++) {
828 encode_residual_fixed(res, smp, n, i);
829 bits[i] = find_subframe_rice_params(s, sub, i);
830 if (bits[i] < bits[opt_order])
833 sub->order = opt_order;
834 sub->type_code = sub->type | sub->order;
835 if (sub->order != max_order) {
836 encode_residual_fixed(res, smp, n, sub->order);
837 find_subframe_rice_params(s, sub, sub->order);
839 return subframe_count_exact(s, sub, sub->order);
843 sub->type = FLAC_SUBFRAME_LPC;
844 opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
845 s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
846 s->options.lpc_passes, omethod,
849 if (omethod == ORDER_METHOD_2LEVEL ||
850 omethod == ORDER_METHOD_4LEVEL ||
851 omethod == ORDER_METHOD_8LEVEL) {
852 int levels = 1 << omethod;
853 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
855 int opt_index = levels-1;
856 opt_order = max_order-1;
857 bits[opt_index] = UINT32_MAX;
858 for (i = levels-1; i >= 0; i--) {
859 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
862 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
863 bits[i] = find_subframe_rice_params(s, sub, order+1);
864 if (bits[i] < bits[opt_index]) {
870 } else if (omethod == ORDER_METHOD_SEARCH) {
871 // brute-force optimal order search
872 uint32_t bits[MAX_LPC_ORDER];
874 bits[0] = UINT32_MAX;
875 for (i = min_order-1; i < max_order; i++) {
876 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
877 bits[i] = find_subframe_rice_params(s, sub, i+1);
878 if (bits[i] < bits[opt_order])
882 } else if (omethod == ORDER_METHOD_LOG) {
883 uint32_t bits[MAX_LPC_ORDER];
886 opt_order = min_order - 1 + (max_order-min_order)/3;
887 memset(bits, -1, sizeof(bits));
889 for (step = 16; step; step >>= 1) {
890 int last = opt_order;
891 for (i = last-step; i <= last+step; i += step) {
892 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
894 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
895 bits[i] = find_subframe_rice_params(s, sub, i+1);
896 if (bits[i] < bits[opt_order])
903 sub->order = opt_order;
904 sub->type_code = sub->type | (sub->order-1);
905 sub->shift = shift[sub->order-1];
906 for (i = 0; i < sub->order; i++)
907 sub->coefs[i] = coefs[sub->order-1][i];
909 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
911 find_subframe_rice_params(s, sub, sub->order);
913 return subframe_count_exact(s, sub, sub->order);
917 static int count_frame_header(FlacEncodeContext *s)
919 uint8_t av_unused tmp;
925 <1> Blocking strategy
926 <4> Block size in inter-channel samples
928 <4> Channel assignment
929 <3> Sample size in bits
934 /* coded frame number */
935 PUT_UTF8(s->frame_count, tmp, count += 8;)
937 /* explicit block size */
938 if (s->frame.bs_code[0] == 6)
940 else if (s->frame.bs_code[0] == 7)
943 /* explicit sample rate */
944 count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
946 /* frame header CRC-8 */
953 static int encode_frame(FlacEncodeContext *s)
957 count = count_frame_header(s);
959 for (ch = 0; ch < s->channels; ch++)
960 count += encode_residual_ch(s, ch);
962 count += (8 - (count & 7)) & 7; // byte alignment
963 count += 16; // CRC-16
969 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
977 /* calculate sum of 2nd order residual for each channel */
978 sum[0] = sum[1] = sum[2] = sum[3] = 0;
979 for (i = 2; i < n; i++) {
980 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
981 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
982 sum[2] += FFABS((lt + rt) >> 1);
983 sum[3] += FFABS(lt - rt);
987 /* estimate bit counts */
988 for (i = 0; i < 4; i++) {
989 k = find_optimal_param(2 * sum[i], n);
990 sum[i] = rice_encode_count( 2 * sum[i], n, k);
993 /* calculate score for each mode */
994 score[0] = sum[0] + sum[1];
995 score[1] = sum[0] + sum[3];
996 score[2] = sum[1] + sum[3];
997 score[3] = sum[2] + sum[3];
999 /* return mode with lowest score */
1001 for (i = 1; i < 4; i++)
1002 if (score[i] < score[best])
1010 * Perform stereo channel decorrelation.
1012 static void channel_decorrelation(FlacEncodeContext *s)
1015 int32_t *left, *right;
1019 n = frame->blocksize;
1020 left = frame->subframes[0].samples;
1021 right = frame->subframes[1].samples;
1023 if (s->channels != 2) {
1024 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
1028 if (s->options.ch_mode < 0)
1029 frame->ch_mode = estimate_stereo_mode(left, right, n);
1031 frame->ch_mode = s->options.ch_mode;
1033 /* perform decorrelation and adjust bits-per-sample */
1034 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1036 if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1038 for (i = 0; i < n; i++) {
1040 left[i] = (tmp + right[i]) >> 1;
1041 right[i] = tmp - right[i];
1043 frame->subframes[1].obits++;
1044 } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1045 for (i = 0; i < n; i++)
1046 right[i] = left[i] - right[i];
1047 frame->subframes[1].obits++;
1049 for (i = 0; i < n; i++)
1050 left[i] -= right[i];
1051 frame->subframes[0].obits++;
1056 static void write_utf8(PutBitContext *pb, uint32_t val)
1059 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1063 static void write_frame_header(FlacEncodeContext *s)
1070 put_bits(&s->pb, 16, 0xFFF8);
1071 put_bits(&s->pb, 4, frame->bs_code[0]);
1072 put_bits(&s->pb, 4, s->sr_code[0]);
1074 if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1075 put_bits(&s->pb, 4, s->channels-1);
1077 put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
1079 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1080 put_bits(&s->pb, 1, 0);
1081 write_utf8(&s->pb, s->frame_count);
1083 if (frame->bs_code[0] == 6)
1084 put_bits(&s->pb, 8, frame->bs_code[1]);
1085 else if (frame->bs_code[0] == 7)
1086 put_bits(&s->pb, 16, frame->bs_code[1]);
1088 if (s->sr_code[0] == 12)
1089 put_bits(&s->pb, 8, s->sr_code[1]);
1090 else if (s->sr_code[0] > 12)
1091 put_bits(&s->pb, 16, s->sr_code[1]);
1093 flush_put_bits(&s->pb);
1094 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1095 put_bits_count(&s->pb) >> 3);
1096 put_bits(&s->pb, 8, crc);
1100 static void write_subframes(FlacEncodeContext *s)
1104 for (ch = 0; ch < s->channels; ch++) {
1105 FlacSubframe *sub = &s->frame.subframes[ch];
1106 int i, p, porder, psize;
1108 int32_t *res = sub->residual;
1109 int32_t *frame_end = &sub->residual[s->frame.blocksize];
1111 /* subframe header */
1112 put_bits(&s->pb, 1, 0);
1113 put_bits(&s->pb, 6, sub->type_code);
1114 put_bits(&s->pb, 1, 0); /* no wasted bits */
1117 if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1118 put_sbits(&s->pb, sub->obits, res[0]);
1119 } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1120 while (res < frame_end)
1121 put_sbits(&s->pb, sub->obits, *res++);
1123 /* warm-up samples */
1124 for (i = 0; i < sub->order; i++)
1125 put_sbits(&s->pb, sub->obits, *res++);
1127 /* LPC coefficients */
1128 if (sub->type == FLAC_SUBFRAME_LPC) {
1129 int cbits = s->options.lpc_coeff_precision;
1130 put_bits( &s->pb, 4, cbits-1);
1131 put_sbits(&s->pb, 5, sub->shift);
1132 for (i = 0; i < sub->order; i++)
1133 put_sbits(&s->pb, cbits, sub->coefs[i]);
1136 /* rice-encoded block */
1137 put_bits(&s->pb, 2, 0);
1139 /* partition order */
1140 porder = sub->rc.porder;
1141 psize = s->frame.blocksize >> porder;
1142 put_bits(&s->pb, 4, porder);
1145 part_end = &sub->residual[psize];
1146 for (p = 0; p < 1 << porder; p++) {
1147 int k = sub->rc.params[p];
1148 put_bits(&s->pb, 4, k);
1149 while (res < part_end)
1150 set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1151 part_end = FFMIN(frame_end, part_end + psize);
1158 static void write_frame_footer(FlacEncodeContext *s)
1161 flush_put_bits(&s->pb);
1162 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
1163 put_bits_count(&s->pb)>>3));
1164 put_bits(&s->pb, 16, crc);
1165 flush_put_bits(&s->pb);
1169 static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
1171 init_put_bits(&s->pb, avpkt->data, avpkt->size);
1172 write_frame_header(s);
1174 write_frame_footer(s);
1175 return put_bits_count(&s->pb) >> 3;
1179 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1183 for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1184 int16_t smp = av_le2ne16(samples[i]);
1185 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1188 av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1193 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1194 const AVFrame *frame, int *got_packet_ptr)
1196 FlacEncodeContext *s;
1197 const int16_t *samples;
1198 int frame_bytes, out_bytes, ret;
1200 s = avctx->priv_data;
1202 /* when the last block is reached, update the header in extradata */
1204 s->max_framesize = s->max_encoded_framesize;
1205 av_md5_final(s->md5ctx, s->md5sum);
1206 write_streaminfo(s, avctx->extradata);
1209 samples = (const int16_t *)frame->data[0];
1211 /* change max_framesize for small final frame */
1212 if (frame->nb_samples < s->frame.blocksize) {
1213 s->max_framesize = ff_flac_get_max_frame_size(frame->nb_samples,
1217 init_frame(s, frame->nb_samples);
1219 copy_samples(s, samples);
1221 channel_decorrelation(s);
1223 frame_bytes = encode_frame(s);
1225 /* fallback to verbatim mode if the compressed frame is larger than it
1226 would be if encoded uncompressed. */
1227 if (frame_bytes > s->max_framesize) {
1228 s->frame.verbatim_only = 1;
1229 frame_bytes = encode_frame(s);
1232 if ((ret = ff_alloc_packet(avpkt, frame_bytes))) {
1233 av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
1237 out_bytes = write_frame(s, avpkt);
1240 s->sample_count += frame->nb_samples;
1241 update_md5_sum(s, samples);
1242 if (out_bytes > s->max_encoded_framesize)
1243 s->max_encoded_framesize = out_bytes;
1244 if (out_bytes < s->min_framesize)
1245 s->min_framesize = out_bytes;
1247 avpkt->pts = frame->pts;
1248 avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1249 avpkt->size = out_bytes;
1250 *got_packet_ptr = 1;
1255 static av_cold int flac_encode_close(AVCodecContext *avctx)
1257 if (avctx->priv_data) {
1258 FlacEncodeContext *s = avctx->priv_data;
1259 av_freep(&s->md5ctx);
1260 ff_lpc_end(&s->lpc_ctx);
1262 av_freep(&avctx->extradata);
1263 avctx->extradata_size = 0;
1264 #if FF_API_OLD_ENCODE_AUDIO
1265 av_freep(&avctx->coded_frame);
1270 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1271 static const AVOption options[] = {
1272 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1273 { "lpc_type", "LPC algorithm", offsetof(FlacEncodeContext, options.lpc_type), AV_OPT_TYPE_INT, {.i64 = FF_LPC_TYPE_DEFAULT }, FF_LPC_TYPE_DEFAULT, FF_LPC_TYPE_NB-1, FLAGS, "lpc_type" },
1274 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1275 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1276 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1277 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1278 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes), AV_OPT_TYPE_INT, {.i64 = -1 }, INT_MIN, INT_MAX, FLAGS },
1279 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1280 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1281 { "prediction_order_method", "Search method for selecting prediction order", offsetof(FlacEncodeContext, options.prediction_order_method), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, ORDER_METHOD_LOG, FLAGS, "predm" },
1282 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1283 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1284 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1285 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1286 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1287 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1288 { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
1289 { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1290 { "indep", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1291 { "left_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1292 { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1293 { "mid_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1297 static const AVClass flac_encoder_class = {
1299 av_default_item_name,
1301 LIBAVUTIL_VERSION_INT,
1304 AVCodec ff_flac_encoder = {
1306 .type = AVMEDIA_TYPE_AUDIO,
1307 .id = AV_CODEC_ID_FLAC,
1308 .priv_data_size = sizeof(FlacEncodeContext),
1309 .init = flac_encode_init,
1310 .encode2 = flac_encode_frame,
1311 .close = flac_encode_close,
1312 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1313 .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1314 AV_SAMPLE_FMT_NONE },
1315 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1316 .priv_class = &flac_encoder_class,