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;
102 * Write streaminfo metadata block to byte array
104 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
108 memset(header, 0, FLAC_STREAMINFO_SIZE);
109 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
111 /* streaminfo metadata block */
112 put_bits(&pb, 16, s->max_blocksize);
113 put_bits(&pb, 16, s->max_blocksize);
114 put_bits(&pb, 24, s->min_framesize);
115 put_bits(&pb, 24, s->max_framesize);
116 put_bits(&pb, 20, s->samplerate);
117 put_bits(&pb, 3, s->channels-1);
118 put_bits(&pb, 5, 15); /* bits per sample - 1 */
119 /* write 36-bit sample count in 2 put_bits() calls */
120 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
121 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
123 memcpy(&header[18], s->md5sum, 16);
127 * Set blocksize based on samplerate
128 * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
130 static int select_blocksize(int samplerate, int block_time_ms)
136 assert(samplerate > 0);
137 blocksize = ff_flac_blocksize_table[1];
138 target = (samplerate * block_time_ms) / 1000;
139 for(i=0; i<16; i++) {
140 if(target >= ff_flac_blocksize_table[i] && ff_flac_blocksize_table[i] > blocksize) {
141 blocksize = ff_flac_blocksize_table[i];
147 static av_cold int flac_encode_init(AVCodecContext *avctx)
149 int freq = avctx->sample_rate;
150 int channels = avctx->channels;
151 FlacEncodeContext *s = avctx->priv_data;
157 dsputil_init(&s->dsp, avctx);
159 if(avctx->sample_fmt != SAMPLE_FMT_S16) {
163 if(channels < 1 || channels > FLAC_MAX_CHANNELS) {
166 s->channels = channels;
168 /* find samplerate in table */
171 for(i=4; i<12; i++) {
172 if(freq == ff_flac_sample_rate_table[i]) {
173 s->samplerate = ff_flac_sample_rate_table[i];
179 /* if not in table, samplerate is non-standard */
181 if(freq % 1000 == 0 && freq < 255000) {
183 s->sr_code[1] = freq / 1000;
184 } else if(freq % 10 == 0 && freq < 655350) {
186 s->sr_code[1] = freq / 10;
187 } else if(freq < 65535) {
189 s->sr_code[1] = freq;
193 s->samplerate = freq;
196 /* set compression option defaults based on avctx->compression_level */
197 if(avctx->compression_level < 0) {
198 s->options.compression_level = 5;
200 s->options.compression_level = avctx->compression_level;
202 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
204 level= s->options.compression_level;
206 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
207 s->options.compression_level);
211 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
212 s->options.lpc_type = ((int[]){ AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED, AV_LPC_TYPE_FIXED,
213 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
214 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
215 AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON, AV_LPC_TYPE_LEVINSON,
216 AV_LPC_TYPE_LEVINSON})[level];
217 s->options.min_prediction_order= ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
218 s->options.max_prediction_order= ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
219 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
220 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
221 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
222 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
223 ORDER_METHOD_SEARCH})[level];
224 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
225 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
227 /* set compression option overrides from AVCodecContext */
228 #if LIBAVCODEC_VERSION_MAJOR < 53
229 /* for compatibility with deprecated AVCodecContext.use_lpc */
230 if (avctx->use_lpc == 0) {
231 s->options.lpc_type = AV_LPC_TYPE_FIXED;
232 } else if (avctx->use_lpc == 1) {
233 s->options.lpc_type = AV_LPC_TYPE_LEVINSON;
234 } else if (avctx->use_lpc > 1) {
235 s->options.lpc_type = AV_LPC_TYPE_CHOLESKY;
236 s->options.lpc_passes = avctx->use_lpc - 1;
239 if (avctx->lpc_type > AV_LPC_TYPE_DEFAULT) {
240 if (avctx->lpc_type > AV_LPC_TYPE_CHOLESKY) {
241 av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
244 s->options.lpc_type = avctx->lpc_type;
245 if (s->options.lpc_type == AV_LPC_TYPE_CHOLESKY) {
246 if (avctx->lpc_passes < 0) {
247 // default number of passes for Cholesky
248 s->options.lpc_passes = 2;
249 } else if (avctx->lpc_passes == 0) {
250 av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
254 s->options.lpc_passes = avctx->lpc_passes;
258 switch (s->options.lpc_type) {
259 case AV_LPC_TYPE_NONE:
260 av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
262 case AV_LPC_TYPE_FIXED:
263 av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
265 case AV_LPC_TYPE_LEVINSON:
266 av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
268 case AV_LPC_TYPE_CHOLESKY:
269 av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
270 s->options.lpc_passes, s->options.lpc_passes==1?"":"es");
274 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
275 s->options.min_prediction_order = 0;
276 } else if (avctx->min_prediction_order >= 0) {
277 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
278 if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
279 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
280 avctx->min_prediction_order);
283 } else if(avctx->min_prediction_order < MIN_LPC_ORDER ||
284 avctx->min_prediction_order > MAX_LPC_ORDER) {
285 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
286 avctx->min_prediction_order);
289 s->options.min_prediction_order = avctx->min_prediction_order;
291 if (s->options.lpc_type == AV_LPC_TYPE_NONE) {
292 s->options.max_prediction_order = 0;
293 } else if (avctx->max_prediction_order >= 0) {
294 if (s->options.lpc_type == AV_LPC_TYPE_FIXED) {
295 if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
296 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
297 avctx->max_prediction_order);
300 } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
301 avctx->max_prediction_order > MAX_LPC_ORDER) {
302 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
303 avctx->max_prediction_order);
306 s->options.max_prediction_order = avctx->max_prediction_order;
308 if(s->options.max_prediction_order < s->options.min_prediction_order) {
309 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
310 s->options.min_prediction_order, s->options.max_prediction_order);
313 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
314 s->options.min_prediction_order, s->options.max_prediction_order);
316 if(avctx->prediction_order_method >= 0) {
317 if(avctx->prediction_order_method > ORDER_METHOD_LOG) {
318 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
319 avctx->prediction_order_method);
322 s->options.prediction_order_method = avctx->prediction_order_method;
324 switch(s->options.prediction_order_method) {
325 case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
327 case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
329 case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
331 case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
333 case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
334 "full search"); break;
335 case ORDER_METHOD_LOG: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
336 "log search"); break;
339 if(avctx->min_partition_order >= 0) {
340 if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
341 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
342 avctx->min_partition_order);
345 s->options.min_partition_order = avctx->min_partition_order;
347 if(avctx->max_partition_order >= 0) {
348 if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
349 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
350 avctx->max_partition_order);
353 s->options.max_partition_order = avctx->max_partition_order;
355 if(s->options.max_partition_order < s->options.min_partition_order) {
356 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
357 s->options.min_partition_order, s->options.max_partition_order);
360 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
361 s->options.min_partition_order, s->options.max_partition_order);
363 if(avctx->frame_size > 0) {
364 if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
365 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
366 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
371 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
373 s->max_blocksize = s->avctx->frame_size;
374 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->avctx->frame_size);
376 /* set LPC precision */
377 if(avctx->lpc_coeff_precision > 0) {
378 if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
379 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
380 avctx->lpc_coeff_precision);
383 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
385 /* default LPC precision */
386 s->options.lpc_coeff_precision = 15;
388 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
389 s->options.lpc_coeff_precision);
391 /* set maximum encoded frame size in verbatim mode */
392 s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
395 /* initialize MD5 context */
396 s->md5ctx = av_malloc(av_md5_size);
398 return AVERROR(ENOMEM);
399 av_md5_init(s->md5ctx);
401 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
402 write_streaminfo(s, streaminfo);
403 avctx->extradata = streaminfo;
404 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
407 s->min_framesize = s->max_framesize;
409 avctx->coded_frame = avcodec_alloc_frame();
410 avctx->coded_frame->key_frame = 1;
415 static void init_frame(FlacEncodeContext *s)
422 for(i=0; i<16; i++) {
423 if(s->avctx->frame_size == ff_flac_blocksize_table[i]) {
424 frame->blocksize = ff_flac_blocksize_table[i];
425 frame->bs_code[0] = i;
426 frame->bs_code[1] = 0;
431 frame->blocksize = s->avctx->frame_size;
432 if(frame->blocksize <= 256) {
433 frame->bs_code[0] = 6;
434 frame->bs_code[1] = frame->blocksize-1;
436 frame->bs_code[0] = 7;
437 frame->bs_code[1] = frame->blocksize-1;
441 for(ch=0; ch<s->channels; ch++) {
442 frame->subframes[ch].obits = 16;
447 * Copy channel-interleaved input samples into separate subframes
449 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
455 for(i=0,j=0; i<frame->blocksize; i++) {
456 for(ch=0; ch<s->channels; ch++,j++) {
457 frame->subframes[ch].samples[i] = samples[j];
463 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
466 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0
468 static int find_optimal_param(uint32_t sum, int n)
476 k = av_log2(n<256 ? FASTDIV(sum2,n) : sum2/n);
477 return FFMIN(k, MAX_RICE_PARAM);
480 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
481 uint32_t *sums, int n, int pred_order)
487 part = (1 << porder);
490 cnt = (n >> porder) - pred_order;
491 for(i=0; i<part; i++) {
492 k = find_optimal_param(sums[i], cnt);
494 all_bits += rice_encode_count(sums[i], cnt, k);
503 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
504 uint32_t sums[][MAX_PARTITIONS])
508 uint32_t *res, *res_end;
510 /* sums for highest level */
512 res = &data[pred_order];
513 res_end = &data[n >> pmax];
514 for(i=0; i<parts; i++) {
516 while(res < res_end){
522 /* sums for lower levels */
523 for(i=pmax-1; i>=pmin; i--) {
525 for(j=0; j<parts; j++) {
526 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
531 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
532 int32_t *data, int n, int pred_order)
535 uint32_t bits[MAX_PARTITION_ORDER+1];
539 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
541 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
542 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
543 assert(pmin <= pmax);
545 udata = av_malloc(n * sizeof(uint32_t));
547 udata[i] = (2*data[i]) ^ (data[i]>>31);
550 calc_sums(pmin, pmax, udata, n, pred_order, sums);
553 bits[pmin] = UINT32_MAX;
554 for(i=pmin; i<=pmax; i++) {
555 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
556 if(bits[i] <= bits[opt_porder]) {
563 return bits[opt_porder];
566 static int get_max_p_order(int max_porder, int n, int order)
568 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
570 porder = FFMIN(porder, av_log2(n/order));
574 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
575 int32_t *data, int n, int pred_order,
579 pmin = get_max_p_order(pmin, n, pred_order);
580 pmax = get_max_p_order(pmax, n, pred_order);
581 bits = pred_order*bps + 6;
582 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
586 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
587 int32_t *data, int n, int pred_order,
588 int bps, int precision)
591 pmin = get_max_p_order(pmin, n, pred_order);
592 pmax = get_max_p_order(pmax, n, pred_order);
593 bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
594 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
598 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
601 memcpy(res, smp, n * sizeof(int32_t));
604 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
609 for(i=0; i<order; i++) {
614 for(i=order; i<n; i++)
617 for(i=order; i<n; i++)
618 res[i]= smp[i] - smp[i-1];
620 int a = smp[order-1] - smp[order-2];
621 for(i=order; i<n; i+=2) {
622 int b = smp[i] - smp[i-1];
624 a = smp[i+1] - smp[i];
628 int a = smp[order-1] - smp[order-2];
629 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
630 for(i=order; i<n; i+=2) {
631 int b = smp[i] - smp[i-1];
634 a = smp[i+1] - smp[i];
639 int a = smp[order-1] - smp[order-2];
640 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
641 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
642 for(i=order; i<n; i+=2) {
643 int b = smp[i] - smp[i-1];
647 a = smp[i+1] - smp[i];
656 int c = coefs[(x)-1];\
662 static av_always_inline void encode_residual_lpc_unrolled(
663 int32_t *res, const int32_t *smp, int n,
664 int order, const int32_t *coefs, int shift, int big)
667 for(i=order; i<n; i+=2) {
668 int s = smp[i-order];
717 res[i ] = smp[i ] - (p0 >> shift);
718 res[i+1] = smp[i+1] - (p1 >> shift);
722 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
723 int order, const int32_t *coefs, int shift)
726 for(i=0; i<order; i++) {
730 for(i=order; i<n; i+=2) {
734 for(j=0; j<order; j++) {
740 res[i ] = smp[i ] - (p0 >> shift);
741 res[i+1] = smp[i+1] - (p1 >> shift);
745 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
746 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
747 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
748 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
749 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
750 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
751 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
752 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
753 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
758 static int encode_residual(FlacEncodeContext *ctx, int ch)
761 int min_order, max_order, opt_order, precision, omethod;
762 int min_porder, max_porder;
765 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
766 int shift[MAX_LPC_ORDER];
770 sub = &frame->subframes[ch];
773 n = frame->blocksize;
777 if(smp[i] != smp[0]) break;
780 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
787 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
788 encode_residual_verbatim(res, smp, n);
789 return sub->obits * n;
792 min_order = ctx->options.min_prediction_order;
793 max_order = ctx->options.max_prediction_order;
794 min_porder = ctx->options.min_partition_order;
795 max_porder = ctx->options.max_partition_order;
796 precision = ctx->options.lpc_coeff_precision;
797 omethod = ctx->options.prediction_order_method;
800 if (ctx->options.lpc_type == AV_LPC_TYPE_NONE ||
801 ctx->options.lpc_type == AV_LPC_TYPE_FIXED || n <= max_order) {
802 uint32_t bits[MAX_FIXED_ORDER+1];
803 if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
805 bits[0] = UINT32_MAX;
806 for(i=min_order; i<=max_order; i++) {
807 encode_residual_fixed(res, smp, n, i);
808 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
810 if(bits[i] < bits[opt_order]) {
814 sub->order = opt_order;
815 sub->type = FLAC_SUBFRAME_FIXED;
816 sub->type_code = sub->type | sub->order;
817 if(sub->order != max_order) {
818 encode_residual_fixed(res, smp, n, sub->order);
819 return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
820 sub->order, sub->obits);
822 return bits[sub->order];
826 opt_order = ff_lpc_calc_coefs(&ctx->dsp, smp, n, min_order, max_order,
827 precision, coefs, shift, ctx->options.lpc_type,
828 ctx->options.lpc_passes, omethod,
831 if(omethod == ORDER_METHOD_2LEVEL ||
832 omethod == ORDER_METHOD_4LEVEL ||
833 omethod == ORDER_METHOD_8LEVEL) {
834 int levels = 1 << omethod;
835 uint32_t bits[1 << ORDER_METHOD_8LEVEL];
837 int opt_index = levels-1;
838 opt_order = max_order-1;
839 bits[opt_index] = UINT32_MAX;
840 for(i=levels-1; i>=0; i--) {
841 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
842 if(order < 0) order = 0;
843 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
844 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
845 res, n, order+1, sub->obits, precision);
846 if(bits[i] < bits[opt_index]) {
852 } else if(omethod == ORDER_METHOD_SEARCH) {
853 // brute-force optimal order search
854 uint32_t bits[MAX_LPC_ORDER];
856 bits[0] = UINT32_MAX;
857 for(i=min_order-1; i<max_order; i++) {
858 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
859 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
860 res, n, i+1, sub->obits, precision);
861 if(bits[i] < bits[opt_order]) {
866 } else if(omethod == ORDER_METHOD_LOG) {
867 uint32_t bits[MAX_LPC_ORDER];
870 opt_order= min_order - 1 + (max_order-min_order)/3;
871 memset(bits, -1, sizeof(bits));
873 for(step=16 ;step; step>>=1){
875 for(i=last-step; i<=last+step; i+= step){
876 if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
878 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
879 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
880 res, n, i+1, sub->obits, precision);
881 if(bits[i] < bits[opt_order])
888 sub->order = opt_order;
889 sub->type = FLAC_SUBFRAME_LPC;
890 sub->type_code = sub->type | (sub->order-1);
891 sub->shift = shift[sub->order-1];
892 for(i=0; i<sub->order; i++) {
893 sub->coefs[i] = coefs[sub->order-1][i];
895 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
896 return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
897 sub->obits, precision);
900 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
908 sub = &frame->subframes[ch];
911 n = frame->blocksize;
915 if(smp[i] != smp[0]) break;
918 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
924 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
925 encode_residual_verbatim(res, smp, n);
926 return sub->obits * n;
929 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
937 /* calculate sum of 2nd order residual for each channel */
938 sum[0] = sum[1] = sum[2] = sum[3] = 0;
940 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
941 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
942 sum[2] += FFABS((lt + rt) >> 1);
943 sum[3] += FFABS(lt - rt);
947 /* estimate bit counts */
949 k = find_optimal_param(2*sum[i], n);
950 sum[i] = rice_encode_count(2*sum[i], n, k);
953 /* calculate score for each mode */
954 score[0] = sum[0] + sum[1];
955 score[1] = sum[0] + sum[3];
956 score[2] = sum[1] + sum[3];
957 score[3] = sum[2] + sum[3];
959 /* return mode with lowest score */
962 if(score[i] < score[best]) {
967 return FLAC_CHMODE_INDEPENDENT;
968 } else if(best == 1) {
969 return FLAC_CHMODE_LEFT_SIDE;
970 } else if(best == 2) {
971 return FLAC_CHMODE_RIGHT_SIDE;
973 return FLAC_CHMODE_MID_SIDE;
978 * Perform stereo channel decorrelation
980 static void channel_decorrelation(FlacEncodeContext *ctx)
983 int32_t *left, *right;
987 n = frame->blocksize;
988 left = frame->subframes[0].samples;
989 right = frame->subframes[1].samples;
991 if(ctx->channels != 2) {
992 frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
996 frame->ch_mode = estimate_stereo_mode(left, right, n);
998 /* perform decorrelation and adjust bits-per-sample */
999 if(frame->ch_mode == FLAC_CHMODE_INDEPENDENT) {
1002 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1004 for(i=0; i<n; i++) {
1006 left[i] = (tmp + right[i]) >> 1;
1007 right[i] = tmp - right[i];
1009 frame->subframes[1].obits++;
1010 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1011 for(i=0; i<n; i++) {
1012 right[i] = left[i] - right[i];
1014 frame->subframes[1].obits++;
1016 for(i=0; i<n; i++) {
1017 left[i] -= right[i];
1019 frame->subframes[0].obits++;
1023 static void write_utf8(PutBitContext *pb, uint32_t val)
1026 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1029 static void output_frame_header(FlacEncodeContext *s)
1036 put_bits(&s->pb, 16, 0xFFF8);
1037 put_bits(&s->pb, 4, frame->bs_code[0]);
1038 put_bits(&s->pb, 4, s->sr_code[0]);
1039 if(frame->ch_mode == FLAC_CHMODE_INDEPENDENT) {
1040 put_bits(&s->pb, 4, s->channels-1);
1042 put_bits(&s->pb, 4, frame->ch_mode);
1044 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1045 put_bits(&s->pb, 1, 0);
1046 write_utf8(&s->pb, s->frame_count);
1047 if(frame->bs_code[0] == 6) {
1048 put_bits(&s->pb, 8, frame->bs_code[1]);
1049 } else if(frame->bs_code[0] == 7) {
1050 put_bits(&s->pb, 16, frame->bs_code[1]);
1052 if(s->sr_code[0] == 12) {
1053 put_bits(&s->pb, 8, s->sr_code[1]);
1054 } else if(s->sr_code[0] > 12) {
1055 put_bits(&s->pb, 16, s->sr_code[1]);
1057 flush_put_bits(&s->pb);
1058 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
1059 s->pb.buf, put_bits_count(&s->pb)>>3);
1060 put_bits(&s->pb, 8, crc);
1063 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1068 sub = &s->frame.subframes[ch];
1069 res = sub->residual[0];
1070 put_sbits(&s->pb, sub->obits, res);
1073 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1081 sub = &frame->subframes[ch];
1083 for(i=0; i<frame->blocksize; i++) {
1084 res = sub->residual[i];
1085 put_sbits(&s->pb, sub->obits, res);
1089 static void output_residual(FlacEncodeContext *ctx, int ch)
1091 int i, j, p, n, parts;
1092 int k, porder, psize, res_cnt;
1097 frame = &ctx->frame;
1098 sub = &frame->subframes[ch];
1099 res = sub->residual;
1100 n = frame->blocksize;
1102 /* rice-encoded block */
1103 put_bits(&ctx->pb, 2, 0);
1105 /* partition order */
1106 porder = sub->rc.porder;
1107 psize = n >> porder;
1108 parts = (1 << porder);
1109 put_bits(&ctx->pb, 4, porder);
1110 res_cnt = psize - sub->order;
1114 for(p=0; p<parts; p++) {
1115 k = sub->rc.params[p];
1116 put_bits(&ctx->pb, 4, k);
1117 if(p == 1) res_cnt = psize;
1118 for(i=0; i<res_cnt && j<n; i++, j++) {
1119 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1124 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1130 frame = &ctx->frame;
1131 sub = &frame->subframes[ch];
1133 /* warm-up samples */
1134 for(i=0; i<sub->order; i++) {
1135 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1139 output_residual(ctx, ch);
1142 static void output_subframe_lpc(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 /* LPC coefficients */
1157 cbits = ctx->options.lpc_coeff_precision;
1158 put_bits(&ctx->pb, 4, cbits-1);
1159 put_sbits(&ctx->pb, 5, sub->shift);
1160 for(i=0; i<sub->order; i++) {
1161 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1165 output_residual(ctx, ch);
1168 static void output_subframes(FlacEncodeContext *s)
1176 for(ch=0; ch<s->channels; ch++) {
1177 sub = &frame->subframes[ch];
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 output_subframe_constant(s, ch);
1187 } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1188 output_subframe_verbatim(s, ch);
1189 } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1190 output_subframe_fixed(s, ch);
1191 } else if(sub->type == FLAC_SUBFRAME_LPC) {
1192 output_subframe_lpc(s, ch);
1197 static void output_frame_footer(FlacEncodeContext *s)
1200 flush_put_bits(&s->pb);
1201 crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1202 s->pb.buf, put_bits_count(&s->pb)>>3));
1203 put_bits(&s->pb, 16, crc);
1204 flush_put_bits(&s->pb);
1207 static void update_md5_sum(FlacEncodeContext *s, int16_t *samples)
1211 for(i = 0; i < s->frame.blocksize*s->channels; i++) {
1212 int16_t smp = av_le2ne16(samples[i]);
1213 av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1216 av_md5_update(s->md5ctx, (uint8_t *)samples, s->frame.blocksize*s->channels*2);
1220 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1221 int buf_size, void *data)
1224 FlacEncodeContext *s;
1225 int16_t *samples = data;
1229 s = avctx->priv_data;
1231 if(buf_size < s->max_framesize*2) {
1232 av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1236 /* when the last block is reached, update the header in extradata */
1238 s->max_framesize = s->max_encoded_framesize;
1239 av_md5_final(s->md5ctx, s->md5sum);
1240 write_streaminfo(s, avctx->extradata);
1246 copy_samples(s, samples);
1248 channel_decorrelation(s);
1250 for(ch=0; ch<s->channels; ch++) {
1251 encode_residual(s, ch);
1255 init_put_bits(&s->pb, frame, buf_size);
1256 output_frame_header(s);
1257 output_subframes(s);
1258 output_frame_footer(s);
1259 out_bytes = put_bits_count(&s->pb) >> 3;
1261 if(out_bytes > s->max_framesize) {
1263 /* still too large. must be an error. */
1264 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1268 /* frame too large. use verbatim mode */
1269 for(ch=0; ch<s->channels; ch++) {
1270 encode_residual_v(s, ch);
1277 s->sample_count += avctx->frame_size;
1278 update_md5_sum(s, samples);
1279 if (out_bytes > s->max_encoded_framesize)
1280 s->max_encoded_framesize = out_bytes;
1281 if (out_bytes < s->min_framesize)
1282 s->min_framesize = out_bytes;
1287 static av_cold int flac_encode_close(AVCodecContext *avctx)
1289 if (avctx->priv_data) {
1290 FlacEncodeContext *s = avctx->priv_data;
1291 av_freep(&s->md5ctx);
1293 av_freep(&avctx->extradata);
1294 avctx->extradata_size = 0;
1295 av_freep(&avctx->coded_frame);
1299 AVCodec flac_encoder = {
1303 sizeof(FlacEncodeContext),
1308 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1309 .sample_fmts = (const enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
1310 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),