3 * Copyright (c) 2006 Justin Ruggles <jruggle@earthlink.net>
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
23 #include "bitstream.h"
29 #define FLAC_MIN_BLOCKSIZE 16
30 #define FLAC_MAX_BLOCKSIZE 65535
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 FLAC_CHMODE_NOT_STEREO 0
38 #define FLAC_CHMODE_LEFT_RIGHT 1
39 #define FLAC_CHMODE_LEFT_SIDE 8
40 #define FLAC_CHMODE_RIGHT_SIDE 9
41 #define FLAC_CHMODE_MID_SIDE 10
43 #define ORDER_METHOD_EST 0
44 #define ORDER_METHOD_2LEVEL 1
45 #define ORDER_METHOD_4LEVEL 2
46 #define ORDER_METHOD_8LEVEL 3
47 #define ORDER_METHOD_SEARCH 4
48 #define ORDER_METHOD_LOG 5
50 #define FLAC_STREAMINFO_SIZE 34
52 #define MIN_LPC_ORDER 1
53 #define MAX_LPC_ORDER 32
54 #define MAX_FIXED_ORDER 4
55 #define MAX_PARTITION_ORDER 8
56 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
57 #define MAX_LPC_PRECISION 15
58 #define MAX_LPC_SHIFT 15
59 #define MAX_RICE_PARAM 14
61 typedef struct CompressionOptions {
62 int compression_level;
65 int lpc_coeff_precision;
66 int min_prediction_order;
67 int max_prediction_order;
68 int prediction_order_method;
69 int min_partition_order;
70 int max_partition_order;
73 typedef struct RiceContext {
75 int params[MAX_PARTITIONS];
78 typedef struct FlacSubframe {
83 int32_t coefs[MAX_LPC_ORDER];
86 int32_t samples[FLAC_MAX_BLOCKSIZE];
87 int32_t residual[FLAC_MAX_BLOCKSIZE];
90 typedef struct FlacFrame {
91 FlacSubframe subframes[FLAC_MAX_CH];
98 typedef struct FlacEncodeContext {
106 uint32_t frame_count;
108 CompressionOptions options;
109 AVCodecContext *avctx;
112 static const int flac_samplerates[16] = {
114 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
118 static const int flac_blocksizes[16] = {
121 576, 1152, 2304, 4608,
123 256, 512, 1024, 2048, 4096, 8192, 16384, 32768
127 * Writes streaminfo metadata block to byte array
129 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
133 memset(header, 0, FLAC_STREAMINFO_SIZE);
134 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
136 /* streaminfo metadata block */
137 put_bits(&pb, 16, s->blocksize);
138 put_bits(&pb, 16, s->blocksize);
139 put_bits(&pb, 24, 0);
140 put_bits(&pb, 24, s->max_framesize);
141 put_bits(&pb, 20, s->samplerate);
142 put_bits(&pb, 3, s->channels-1);
143 put_bits(&pb, 5, 15); /* bits per sample - 1 */
145 /* total samples = 0 */
146 /* MD5 signature = 0 */
150 * Sets blocksize based on samplerate
151 * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
153 static int select_blocksize(int samplerate, int block_time_ms)
159 assert(samplerate > 0);
160 blocksize = flac_blocksizes[1];
161 target = (samplerate * block_time_ms) / 1000;
162 for(i=0; i<16; i++) {
163 if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
164 blocksize = flac_blocksizes[i];
170 static int flac_encode_init(AVCodecContext *avctx)
172 int freq = avctx->sample_rate;
173 int channels = avctx->channels;
174 FlacEncodeContext *s = avctx->priv_data;
180 if(avctx->sample_fmt != SAMPLE_FMT_S16) {
184 if(channels < 1 || channels > FLAC_MAX_CH) {
187 s->channels = channels;
188 s->ch_code = s->channels-1;
190 /* find samplerate in table */
193 for(i=4; i<12; i++) {
194 if(freq == flac_samplerates[i]) {
195 s->samplerate = flac_samplerates[i];
201 /* if not in table, samplerate is non-standard */
203 if(freq % 1000 == 0 && freq < 255000) {
205 s->sr_code[1] = freq / 1000;
206 } else if(freq % 10 == 0 && freq < 655350) {
208 s->sr_code[1] = freq / 10;
209 } else if(freq < 65535) {
211 s->sr_code[1] = freq;
215 s->samplerate = freq;
218 /* set compression option defaults based on avctx->compression_level */
219 if(avctx->compression_level < 0) {
220 s->options.compression_level = 5;
222 s->options.compression_level = avctx->compression_level;
224 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
226 level= s->options.compression_level;
228 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
229 s->options.compression_level);
233 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
234 s->options.use_lpc = ((int[]){ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
235 s->options.min_prediction_order= ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
236 s->options.max_prediction_order= ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
237 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
238 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
239 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
240 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
241 ORDER_METHOD_SEARCH})[level];
242 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
243 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
245 /* set compression option overrides from AVCodecContext */
246 if(avctx->use_lpc >= 0) {
247 s->options.use_lpc = av_clip(avctx->use_lpc, 0, 11);
249 if(s->options.use_lpc == 1)
250 av_log(avctx, AV_LOG_DEBUG, " use lpc: Levinson-Durbin recursion with Welch window\n");
251 else if(s->options.use_lpc > 1)
252 av_log(avctx, AV_LOG_DEBUG, " use lpc: Cholesky factorization\n");
254 if(avctx->min_prediction_order >= 0) {
255 if(s->options.use_lpc) {
256 if(avctx->min_prediction_order < MIN_LPC_ORDER ||
257 avctx->min_prediction_order > MAX_LPC_ORDER) {
258 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
259 avctx->min_prediction_order);
263 if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
264 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
265 avctx->min_prediction_order);
269 s->options.min_prediction_order = avctx->min_prediction_order;
271 if(avctx->max_prediction_order >= 0) {
272 if(s->options.use_lpc) {
273 if(avctx->max_prediction_order < MIN_LPC_ORDER ||
274 avctx->max_prediction_order > MAX_LPC_ORDER) {
275 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
276 avctx->max_prediction_order);
280 if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
281 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
282 avctx->max_prediction_order);
286 s->options.max_prediction_order = avctx->max_prediction_order;
288 if(s->options.max_prediction_order < s->options.min_prediction_order) {
289 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
290 s->options.min_prediction_order, s->options.max_prediction_order);
293 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
294 s->options.min_prediction_order, s->options.max_prediction_order);
296 if(avctx->prediction_order_method >= 0) {
297 if(avctx->prediction_order_method > ORDER_METHOD_LOG) {
298 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
299 avctx->prediction_order_method);
302 s->options.prediction_order_method = avctx->prediction_order_method;
304 switch(s->options.prediction_order_method) {
305 case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
307 case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
309 case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
311 case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
313 case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
314 "full search"); break;
315 case ORDER_METHOD_LOG: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
316 "log search"); break;
319 if(avctx->min_partition_order >= 0) {
320 if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
321 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
322 avctx->min_partition_order);
325 s->options.min_partition_order = avctx->min_partition_order;
327 if(avctx->max_partition_order >= 0) {
328 if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
329 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
330 avctx->max_partition_order);
333 s->options.max_partition_order = avctx->max_partition_order;
335 if(s->options.max_partition_order < s->options.min_partition_order) {
336 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
337 s->options.min_partition_order, s->options.max_partition_order);
340 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
341 s->options.min_partition_order, s->options.max_partition_order);
343 if(avctx->frame_size > 0) {
344 if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
345 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
346 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
350 s->blocksize = avctx->frame_size;
352 s->blocksize = select_blocksize(s->samplerate, s->options.block_time_ms);
353 avctx->frame_size = s->blocksize;
355 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->blocksize);
357 /* set LPC precision */
358 if(avctx->lpc_coeff_precision > 0) {
359 if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
360 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
361 avctx->lpc_coeff_precision);
364 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
366 /* select LPC precision based on block size */
367 if( s->blocksize <= 192) s->options.lpc_coeff_precision = 7;
368 else if(s->blocksize <= 384) s->options.lpc_coeff_precision = 8;
369 else if(s->blocksize <= 576) s->options.lpc_coeff_precision = 9;
370 else if(s->blocksize <= 1152) s->options.lpc_coeff_precision = 10;
371 else if(s->blocksize <= 2304) s->options.lpc_coeff_precision = 11;
372 else if(s->blocksize <= 4608) s->options.lpc_coeff_precision = 12;
373 else if(s->blocksize <= 8192) s->options.lpc_coeff_precision = 13;
374 else if(s->blocksize <= 16384) s->options.lpc_coeff_precision = 14;
375 else s->options.lpc_coeff_precision = 15;
377 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
378 s->options.lpc_coeff_precision);
380 /* set maximum encoded frame size in verbatim mode */
381 if(s->channels == 2) {
382 s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
384 s->max_framesize = 14 + (s->blocksize * s->channels * 2);
387 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
388 write_streaminfo(s, streaminfo);
389 avctx->extradata = streaminfo;
390 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
394 avctx->coded_frame = avcodec_alloc_frame();
395 avctx->coded_frame->key_frame = 1;
400 static void init_frame(FlacEncodeContext *s)
407 for(i=0; i<16; i++) {
408 if(s->blocksize == flac_blocksizes[i]) {
409 frame->blocksize = flac_blocksizes[i];
410 frame->bs_code[0] = i;
411 frame->bs_code[1] = 0;
416 frame->blocksize = s->blocksize;
417 if(frame->blocksize <= 256) {
418 frame->bs_code[0] = 6;
419 frame->bs_code[1] = frame->blocksize-1;
421 frame->bs_code[0] = 7;
422 frame->bs_code[1] = frame->blocksize-1;
426 for(ch=0; ch<s->channels; ch++) {
427 frame->subframes[ch].obits = 16;
432 * Copy channel-interleaved input samples into separate subframes
434 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
440 for(i=0,j=0; i<frame->blocksize; i++) {
441 for(ch=0; ch<s->channels; ch++,j++) {
442 frame->subframes[ch].samples[i] = samples[j];
448 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
450 static int find_optimal_param(uint32_t sum, int n)
453 uint32_t nbits[MAX_RICE_PARAM+1];
456 nbits[0] = UINT32_MAX;
457 for(k=0; k<=MAX_RICE_PARAM; k++) {
458 nbits[k] = rice_encode_count(sum, n, k);
459 if(nbits[k] < nbits[k_opt]) {
466 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
467 uint32_t *sums, int n, int pred_order)
473 part = (1 << porder);
476 cnt = (n >> porder) - pred_order;
477 for(i=0; i<part; i++) {
478 if(i == 1) cnt = (n >> porder);
479 k = find_optimal_param(sums[i], cnt);
481 all_bits += rice_encode_count(sums[i], cnt, k);
483 all_bits += (4 * part);
490 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
491 uint32_t sums[][MAX_PARTITIONS])
495 uint32_t *res, *res_end;
497 /* sums for highest level */
499 res = &data[pred_order];
500 res_end = &data[n >> pmax];
501 for(i=0; i<parts; i++) {
503 while(res < res_end){
504 sums[pmax][i] += *(res++);
508 /* sums for lower levels */
509 for(i=pmax-1; i>=pmin; i--) {
511 for(j=0; j<parts; j++) {
512 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
517 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
518 int32_t *data, int n, int pred_order)
521 uint32_t bits[MAX_PARTITION_ORDER+1];
525 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
527 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
528 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
529 assert(pmin <= pmax);
531 udata = av_malloc(n * sizeof(uint32_t));
533 udata[i] = (2*data[i]) ^ (data[i]>>31);
536 calc_sums(pmin, pmax, udata, n, pred_order, sums);
539 bits[pmin] = UINT32_MAX;
540 for(i=pmin; i<=pmax; i++) {
541 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
542 if(bits[i] <= bits[opt_porder]) {
549 return bits[opt_porder];
552 static int get_max_p_order(int max_porder, int n, int order)
554 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
556 porder = FFMIN(porder, av_log2(n/order));
560 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
561 int32_t *data, int n, int pred_order,
565 pmin = get_max_p_order(pmin, n, pred_order);
566 pmax = get_max_p_order(pmax, n, pred_order);
567 bits = pred_order*bps + 6;
568 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
572 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
573 int32_t *data, int n, int pred_order,
574 int bps, int precision)
577 pmin = get_max_p_order(pmin, n, pred_order);
578 pmax = get_max_p_order(pmax, n, pred_order);
579 bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
580 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
585 * Apply Welch window function to audio block
587 static void apply_welch_window(const int32_t *data, int len, double *w_data)
594 c = 2.0 / (len - 1.0);
595 for(i=0; i<n2; i++) {
598 w_data[i] = data[i] * w;
599 w_data[len-1-i] = data[len-1-i] * w;
604 * Calculates autocorrelation data from audio samples
605 * A Welch window function is applied before calculation.
607 static void compute_autocorr(const int32_t *data, int len, int lag,
611 double tmp[len + lag];
612 double *data1= tmp + lag;
614 apply_welch_window(data, len, data1);
616 for(i=0; i<lag; i++){
621 for(i=0; i<len; i++){
622 for(lag_ptr= i-lag; lag_ptr<=i; lag_ptr++){
623 autoc[i-lag_ptr] += data1[i] * data1[lag_ptr];
629 * Levinson-Durbin recursion.
630 * Produces LPC coefficients from autocorrelation data.
632 static void compute_lpc_coefs(const double *autoc, int max_order,
633 double lpc[][MAX_LPC_ORDER], double *ref)
637 double lpc_tmp[MAX_LPC_ORDER];
639 for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
642 for(i=0; i<max_order; i++) {
645 r -= lpc_tmp[j] * autoc[i-j];
650 err *= 1.0 - (r * r);
654 for(j=0; j<i2; j++) {
656 lpc_tmp[j] += r * lpc_tmp[i-1-j];
657 lpc_tmp[i-1-j] += r * tmp;
660 lpc_tmp[j] += lpc_tmp[j] * r;
663 for(j=0; j<=i; j++) {
664 lpc[i][j] = -lpc_tmp[j];
670 * Quantize LPC coefficients
672 static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
673 int32_t *lpc_out, int *shift)
680 /* define maximum levels */
681 qmax = (1 << (precision - 1)) - 1;
683 /* find maximum coefficient value */
685 for(i=0; i<order; i++) {
686 cmax= FFMAX(cmax, fabs(lpc_in[i]));
689 /* if maximum value quantizes to zero, return all zeros */
690 if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
692 memset(lpc_out, 0, sizeof(int32_t) * order);
696 /* calculate level shift which scales max coeff to available bits */
698 while((cmax * (1 << sh) > qmax) && (sh > 0)) {
702 /* since negative shift values are unsupported in decoder, scale down
703 coefficients instead */
704 if(sh == 0 && cmax > qmax) {
705 double scale = ((double)qmax) / cmax;
706 for(i=0; i<order; i++) {
711 /* output quantized coefficients and level shift */
713 for(i=0; i<order; i++) {
714 error += lpc_in[i] * (1 << sh);
715 lpc_out[i] = av_clip(lrintf(error), -qmax, qmax);
721 static int estimate_best_order(double *ref, int max_order)
726 for(i=max_order-1; i>=0; i--) {
736 * Calculate LPC coefficients for multiple orders
738 static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
739 int precision, int32_t coefs[][MAX_LPC_ORDER],
740 int *shift, int use_lpc, int omethod)
742 double autoc[MAX_LPC_ORDER+1];
743 double ref[MAX_LPC_ORDER];
744 double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
748 assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
751 compute_autocorr(samples, blocksize, max_order+1, autoc);
753 compute_lpc_coefs(autoc, max_order, lpc, ref);
756 double var[MAX_LPC_ORDER+1], eval, weight;
758 for(pass=0; pass<use_lpc-1; pass++){
759 av_init_lls(&m[pass&1], max_order);
762 for(i=max_order; i<blocksize; i++){
763 for(j=0; j<=max_order; j++)
764 var[j]= samples[i-j];
767 eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
768 eval= (512>>pass) + fabs(eval - var[0]);
769 for(j=0; j<=max_order; j++)
775 av_update_lls(&m[pass&1], var, 1.0);
777 av_solve_lls(&m[pass&1], 0.001, 0);
780 for(i=0; i<max_order; i++){
781 for(j=0; j<max_order; j++)
782 lpc[i][j]= m[(pass-1)&1].coeff[i][j];
783 ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
785 for(i=max_order-1; i>0; i--)
786 ref[i] = ref[i-1] - ref[i];
788 opt_order = max_order;
790 if(omethod == ORDER_METHOD_EST) {
791 opt_order = estimate_best_order(ref, max_order);
793 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
795 for(i=0; i<max_order; i++) {
796 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
804 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
807 memcpy(res, smp, n * sizeof(int32_t));
810 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
815 for(i=0; i<order; i++) {
820 for(i=order; i<n; i++)
823 for(i=order; i<n; i++)
824 res[i]= smp[i] - smp[i-1];
826 for(i=order; i<n; i++)
827 res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
829 for(i=order; i<n; i++)
830 res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
832 for(i=order; i<n; i++)
833 res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
837 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
838 int order, const int32_t *coefs, int shift)
843 for(i=0; i<order; i++) {
846 for(i=order; i<n; i++) {
848 for(j=0; j<order; j++) {
849 pred += coefs[j] * smp[i-j-1];
851 res[i] = smp[i] - (pred >> shift);
855 static int encode_residual(FlacEncodeContext *ctx, int ch)
858 int min_order, max_order, opt_order, precision, omethod;
859 int min_porder, max_porder;
862 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
863 int shift[MAX_LPC_ORDER];
867 sub = &frame->subframes[ch];
870 n = frame->blocksize;
874 if(smp[i] != smp[0]) break;
877 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
884 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
885 encode_residual_verbatim(res, smp, n);
886 return sub->obits * n;
889 min_order = ctx->options.min_prediction_order;
890 max_order = ctx->options.max_prediction_order;
891 min_porder = ctx->options.min_partition_order;
892 max_porder = ctx->options.max_partition_order;
893 precision = ctx->options.lpc_coeff_precision;
894 omethod = ctx->options.prediction_order_method;
897 if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
898 uint32_t bits[MAX_FIXED_ORDER+1];
899 if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
901 bits[0] = UINT32_MAX;
902 for(i=min_order; i<=max_order; i++) {
903 encode_residual_fixed(res, smp, n, i);
904 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
906 if(bits[i] < bits[opt_order]) {
910 sub->order = opt_order;
911 sub->type = FLAC_SUBFRAME_FIXED;
912 sub->type_code = sub->type | sub->order;
913 if(sub->order != max_order) {
914 encode_residual_fixed(res, smp, n, sub->order);
915 return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
916 sub->order, sub->obits);
918 return bits[sub->order];
922 opt_order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
924 if(omethod == ORDER_METHOD_2LEVEL ||
925 omethod == ORDER_METHOD_4LEVEL ||
926 omethod == ORDER_METHOD_8LEVEL) {
927 int levels = 1 << omethod;
928 uint32_t bits[levels];
930 int opt_index = levels-1;
931 opt_order = max_order-1;
932 bits[opt_index] = UINT32_MAX;
933 for(i=levels-1; i>=0; i--) {
934 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
935 if(order < 0) order = 0;
936 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
937 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
938 res, n, order+1, sub->obits, precision);
939 if(bits[i] < bits[opt_index]) {
945 } else if(omethod == ORDER_METHOD_SEARCH) {
946 // brute-force optimal order search
947 uint32_t bits[MAX_LPC_ORDER];
949 bits[0] = UINT32_MAX;
950 for(i=min_order-1; i<max_order; i++) {
951 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
952 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
953 res, n, i+1, sub->obits, precision);
954 if(bits[i] < bits[opt_order]) {
959 } else if(omethod == ORDER_METHOD_LOG) {
960 uint32_t bits[MAX_LPC_ORDER];
963 opt_order= min_order - 1 + (max_order-min_order)/3;
964 memset(bits, -1, sizeof(bits));
966 for(step=16 ;step; step>>=1){
968 for(i=last-step; i<=last+step; i+= step){
969 if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
971 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
972 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
973 res, n, i+1, sub->obits, precision);
974 if(bits[i] < bits[opt_order])
981 sub->order = opt_order;
982 sub->type = FLAC_SUBFRAME_LPC;
983 sub->type_code = sub->type | (sub->order-1);
984 sub->shift = shift[sub->order-1];
985 for(i=0; i<sub->order; i++) {
986 sub->coefs[i] = coefs[sub->order-1][i];
988 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
989 return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
990 sub->obits, precision);
993 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
1000 frame = &ctx->frame;
1001 sub = &frame->subframes[ch];
1002 res = sub->residual;
1004 n = frame->blocksize;
1007 for(i=1; i<n; i++) {
1008 if(smp[i] != smp[0]) break;
1011 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
1017 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
1018 encode_residual_verbatim(res, smp, n);
1019 return sub->obits * n;
1022 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1030 /* calculate sum of 2nd order residual for each channel */
1031 sum[0] = sum[1] = sum[2] = sum[3] = 0;
1032 for(i=2; i<n; i++) {
1033 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1034 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1035 sum[2] += FFABS((lt + rt) >> 1);
1036 sum[3] += FFABS(lt - rt);
1037 sum[0] += FFABS(lt);
1038 sum[1] += FFABS(rt);
1040 /* estimate bit counts */
1041 for(i=0; i<4; i++) {
1042 k = find_optimal_param(2*sum[i], n);
1043 sum[i] = rice_encode_count(2*sum[i], n, k);
1046 /* calculate score for each mode */
1047 score[0] = sum[0] + sum[1];
1048 score[1] = sum[0] + sum[3];
1049 score[2] = sum[1] + sum[3];
1050 score[3] = sum[2] + sum[3];
1052 /* return mode with lowest score */
1054 for(i=1; i<4; i++) {
1055 if(score[i] < score[best]) {
1060 return FLAC_CHMODE_LEFT_RIGHT;
1061 } else if(best == 1) {
1062 return FLAC_CHMODE_LEFT_SIDE;
1063 } else if(best == 2) {
1064 return FLAC_CHMODE_RIGHT_SIDE;
1066 return FLAC_CHMODE_MID_SIDE;
1071 * Perform stereo channel decorrelation
1073 static void channel_decorrelation(FlacEncodeContext *ctx)
1076 int32_t *left, *right;
1079 frame = &ctx->frame;
1080 n = frame->blocksize;
1081 left = frame->subframes[0].samples;
1082 right = frame->subframes[1].samples;
1084 if(ctx->channels != 2) {
1085 frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1089 frame->ch_mode = estimate_stereo_mode(left, right, n);
1091 /* perform decorrelation and adjust bits-per-sample */
1092 if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1095 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1097 for(i=0; i<n; i++) {
1099 left[i] = (tmp + right[i]) >> 1;
1100 right[i] = tmp - right[i];
1102 frame->subframes[1].obits++;
1103 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1104 for(i=0; i<n; i++) {
1105 right[i] = left[i] - right[i];
1107 frame->subframes[1].obits++;
1109 for(i=0; i<n; i++) {
1110 left[i] -= right[i];
1112 frame->subframes[0].obits++;
1116 static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1118 assert(bits >= 0 && bits <= 31);
1120 put_bits(pb, bits, val & ((1<<bits)-1));
1123 static void write_utf8(PutBitContext *pb, uint32_t val)
1126 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1129 static void output_frame_header(FlacEncodeContext *s)
1136 put_bits(&s->pb, 16, 0xFFF8);
1137 put_bits(&s->pb, 4, frame->bs_code[0]);
1138 put_bits(&s->pb, 4, s->sr_code[0]);
1139 if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1140 put_bits(&s->pb, 4, s->ch_code);
1142 put_bits(&s->pb, 4, frame->ch_mode);
1144 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1145 put_bits(&s->pb, 1, 0);
1146 write_utf8(&s->pb, s->frame_count);
1147 if(frame->bs_code[0] == 6) {
1148 put_bits(&s->pb, 8, frame->bs_code[1]);
1149 } else if(frame->bs_code[0] == 7) {
1150 put_bits(&s->pb, 16, frame->bs_code[1]);
1152 if(s->sr_code[0] == 12) {
1153 put_bits(&s->pb, 8, s->sr_code[1]);
1154 } else if(s->sr_code[0] > 12) {
1155 put_bits(&s->pb, 16, s->sr_code[1]);
1157 flush_put_bits(&s->pb);
1158 crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1159 put_bits(&s->pb, 8, crc);
1162 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1167 sub = &s->frame.subframes[ch];
1168 res = sub->residual[0];
1169 put_sbits(&s->pb, sub->obits, res);
1172 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1180 sub = &frame->subframes[ch];
1182 for(i=0; i<frame->blocksize; i++) {
1183 res = sub->residual[i];
1184 put_sbits(&s->pb, sub->obits, res);
1188 static void output_residual(FlacEncodeContext *ctx, int ch)
1190 int i, j, p, n, parts;
1191 int k, porder, psize, res_cnt;
1196 frame = &ctx->frame;
1197 sub = &frame->subframes[ch];
1198 res = sub->residual;
1199 n = frame->blocksize;
1201 /* rice-encoded block */
1202 put_bits(&ctx->pb, 2, 0);
1204 /* partition order */
1205 porder = sub->rc.porder;
1206 psize = n >> porder;
1207 parts = (1 << porder);
1208 put_bits(&ctx->pb, 4, porder);
1209 res_cnt = psize - sub->order;
1213 for(p=0; p<parts; p++) {
1214 k = sub->rc.params[p];
1215 put_bits(&ctx->pb, 4, k);
1216 if(p == 1) res_cnt = psize;
1217 for(i=0; i<res_cnt && j<n; i++, j++) {
1218 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1223 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1229 frame = &ctx->frame;
1230 sub = &frame->subframes[ch];
1232 /* warm-up samples */
1233 for(i=0; i<sub->order; i++) {
1234 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1238 output_residual(ctx, ch);
1241 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1247 frame = &ctx->frame;
1248 sub = &frame->subframes[ch];
1250 /* warm-up samples */
1251 for(i=0; i<sub->order; i++) {
1252 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1255 /* LPC coefficients */
1256 cbits = ctx->options.lpc_coeff_precision;
1257 put_bits(&ctx->pb, 4, cbits-1);
1258 put_sbits(&ctx->pb, 5, sub->shift);
1259 for(i=0; i<sub->order; i++) {
1260 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1264 output_residual(ctx, ch);
1267 static void output_subframes(FlacEncodeContext *s)
1275 for(ch=0; ch<s->channels; ch++) {
1276 sub = &frame->subframes[ch];
1278 /* subframe header */
1279 put_bits(&s->pb, 1, 0);
1280 put_bits(&s->pb, 6, sub->type_code);
1281 put_bits(&s->pb, 1, 0); /* no wasted bits */
1284 if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1285 output_subframe_constant(s, ch);
1286 } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1287 output_subframe_verbatim(s, ch);
1288 } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1289 output_subframe_fixed(s, ch);
1290 } else if(sub->type == FLAC_SUBFRAME_LPC) {
1291 output_subframe_lpc(s, ch);
1296 static void output_frame_footer(FlacEncodeContext *s)
1299 flush_put_bits(&s->pb);
1300 crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1301 put_bits(&s->pb, 16, crc);
1302 flush_put_bits(&s->pb);
1305 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1306 int buf_size, void *data)
1309 FlacEncodeContext *s;
1310 int16_t *samples = data;
1313 s = avctx->priv_data;
1315 s->blocksize = avctx->frame_size;
1318 copy_samples(s, samples);
1320 channel_decorrelation(s);
1322 for(ch=0; ch<s->channels; ch++) {
1323 encode_residual(s, ch);
1325 init_put_bits(&s->pb, frame, buf_size);
1326 output_frame_header(s);
1327 output_subframes(s);
1328 output_frame_footer(s);
1329 out_bytes = put_bits_count(&s->pb) >> 3;
1331 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1332 /* frame too large. use verbatim mode */
1333 for(ch=0; ch<s->channels; ch++) {
1334 encode_residual_v(s, ch);
1336 init_put_bits(&s->pb, frame, buf_size);
1337 output_frame_header(s);
1338 output_subframes(s);
1339 output_frame_footer(s);
1340 out_bytes = put_bits_count(&s->pb) >> 3;
1342 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1343 /* still too large. must be an error. */
1344 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1353 static int flac_encode_close(AVCodecContext *avctx)
1355 av_freep(&avctx->extradata);
1356 avctx->extradata_size = 0;
1357 av_freep(&avctx->coded_frame);
1361 AVCodec flac_encoder = {
1365 sizeof(FlacEncodeContext),
1370 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,