3 * Copyright (c) 2006 Justin Ruggles <jruggle@earthlink.net>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #include "bitstream.h"
27 #define FLAC_MIN_BLOCKSIZE 16
28 #define FLAC_MAX_BLOCKSIZE 65535
30 #define FLAC_SUBFRAME_CONSTANT 0
31 #define FLAC_SUBFRAME_VERBATIM 1
32 #define FLAC_SUBFRAME_FIXED 8
33 #define FLAC_SUBFRAME_LPC 32
35 #define FLAC_CHMODE_NOT_STEREO 0
36 #define FLAC_CHMODE_LEFT_RIGHT 1
37 #define FLAC_CHMODE_LEFT_SIDE 8
38 #define FLAC_CHMODE_RIGHT_SIDE 9
39 #define FLAC_CHMODE_MID_SIDE 10
41 #define ORDER_METHOD_EST 0
42 #define ORDER_METHOD_2LEVEL 1
43 #define ORDER_METHOD_4LEVEL 2
44 #define ORDER_METHOD_8LEVEL 3
45 #define ORDER_METHOD_SEARCH 4
47 #define FLAC_STREAMINFO_SIZE 34
49 #define MIN_LPC_ORDER 1
50 #define MAX_LPC_ORDER 32
51 #define MAX_FIXED_ORDER 4
52 #define MAX_PARTITION_ORDER 8
53 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
54 #define MAX_LPC_PRECISION 15
55 #define MAX_LPC_SHIFT 15
56 #define MAX_RICE_PARAM 14
58 typedef struct CompressionOptions {
59 int compression_level;
62 int lpc_coeff_precision;
63 int min_prediction_order;
64 int max_prediction_order;
65 int prediction_order_method;
66 int min_partition_order;
67 int max_partition_order;
70 typedef struct RiceContext {
72 int params[MAX_PARTITIONS];
75 typedef struct FlacSubframe {
80 int32_t coefs[MAX_LPC_ORDER];
83 int32_t samples[FLAC_MAX_BLOCKSIZE];
84 int32_t residual[FLAC_MAX_BLOCKSIZE];
87 typedef struct FlacFrame {
88 FlacSubframe subframes[FLAC_MAX_CH];
95 typedef struct FlacEncodeContext {
103 uint32_t frame_count;
105 CompressionOptions options;
106 AVCodecContext *avctx;
109 static const int flac_samplerates[16] = {
111 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
115 static const int flac_blocksizes[16] = {
118 576, 1152, 2304, 4608,
120 256, 512, 1024, 2048, 4096, 8192, 16384, 32768
124 * Writes streaminfo metadata block to byte array
126 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
130 memset(header, 0, FLAC_STREAMINFO_SIZE);
131 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
133 /* streaminfo metadata block */
134 put_bits(&pb, 16, s->blocksize);
135 put_bits(&pb, 16, s->blocksize);
136 put_bits(&pb, 24, 0);
137 put_bits(&pb, 24, s->max_framesize);
138 put_bits(&pb, 20, s->samplerate);
139 put_bits(&pb, 3, s->channels-1);
140 put_bits(&pb, 5, 15); /* bits per sample - 1 */
142 /* total samples = 0 */
143 /* MD5 signature = 0 */
147 * Sets blocksize based on samplerate
148 * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
150 static int select_blocksize(int samplerate, int block_time_ms)
156 assert(samplerate > 0);
157 blocksize = flac_blocksizes[1];
158 target = (samplerate * block_time_ms) / 1000;
159 for(i=0; i<16; i++) {
160 if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
161 blocksize = flac_blocksizes[i];
167 static int flac_encode_init(AVCodecContext *avctx)
169 int freq = avctx->sample_rate;
170 int channels = avctx->channels;
171 FlacEncodeContext *s = avctx->priv_data;
177 if(avctx->sample_fmt != SAMPLE_FMT_S16) {
181 if(channels < 1 || channels > FLAC_MAX_CH) {
184 s->channels = channels;
185 s->ch_code = s->channels-1;
187 /* find samplerate in table */
190 for(i=4; i<12; i++) {
191 if(freq == flac_samplerates[i]) {
192 s->samplerate = flac_samplerates[i];
198 /* if not in table, samplerate is non-standard */
200 if(freq % 1000 == 0 && freq < 255000) {
202 s->sr_code[1] = freq / 1000;
203 } else if(freq % 10 == 0 && freq < 655350) {
205 s->sr_code[1] = freq / 10;
206 } else if(freq < 65535) {
208 s->sr_code[1] = freq;
212 s->samplerate = freq;
215 /* set compression option defaults based on avctx->compression_level */
216 if(avctx->compression_level < 0) {
217 s->options.compression_level = 5;
219 s->options.compression_level = avctx->compression_level;
221 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
223 level= s->options.compression_level;
225 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
226 s->options.compression_level);
230 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
231 s->options.use_lpc = ((int[]){ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
232 s->options.min_prediction_order= ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
233 s->options.max_prediction_order= ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
234 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
235 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
236 ORDER_METHOD_2LEVEL, ORDER_METHOD_4LEVEL, ORDER_METHOD_4LEVEL,
237 ORDER_METHOD_8LEVEL, ORDER_METHOD_SEARCH, ORDER_METHOD_8LEVEL,
238 ORDER_METHOD_SEARCH})[level];
239 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
240 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
242 /* set compression option overrides from AVCodecContext */
243 if(avctx->use_lpc >= 0) {
244 s->options.use_lpc = clip(avctx->use_lpc, 0, 11);
246 if(s->options.use_lpc == 1)
247 av_log(avctx, AV_LOG_DEBUG, " use lpc: Levinson-Durbin recursion with Welch window\n");
248 else if(s->options.use_lpc > 1)
249 av_log(avctx, AV_LOG_DEBUG, " use lpc: Cholesky factorization\n");
251 if(avctx->min_prediction_order >= 0) {
252 if(s->options.use_lpc) {
253 if(avctx->min_prediction_order < MIN_LPC_ORDER ||
254 avctx->min_prediction_order > MAX_LPC_ORDER) {
255 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
256 avctx->min_prediction_order);
260 if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
261 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
262 avctx->min_prediction_order);
266 s->options.min_prediction_order = avctx->min_prediction_order;
268 if(avctx->max_prediction_order >= 0) {
269 if(s->options.use_lpc) {
270 if(avctx->max_prediction_order < MIN_LPC_ORDER ||
271 avctx->max_prediction_order > MAX_LPC_ORDER) {
272 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
273 avctx->max_prediction_order);
277 if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
278 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
279 avctx->max_prediction_order);
283 s->options.max_prediction_order = avctx->max_prediction_order;
285 if(s->options.max_prediction_order < s->options.min_prediction_order) {
286 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
287 s->options.min_prediction_order, s->options.max_prediction_order);
290 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
291 s->options.min_prediction_order, s->options.max_prediction_order);
293 if(avctx->prediction_order_method >= 0) {
294 if(avctx->prediction_order_method > ORDER_METHOD_SEARCH) {
295 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
296 avctx->prediction_order_method);
299 s->options.prediction_order_method = avctx->prediction_order_method;
301 switch(s->options.prediction_order_method) {
302 case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
304 case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
306 case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
308 case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
310 case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
311 "full search"); break;
314 if(avctx->min_partition_order >= 0) {
315 if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
316 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
317 avctx->min_partition_order);
320 s->options.min_partition_order = avctx->min_partition_order;
322 if(avctx->max_partition_order >= 0) {
323 if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
324 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
325 avctx->max_partition_order);
328 s->options.max_partition_order = avctx->max_partition_order;
330 if(s->options.max_partition_order < s->options.min_partition_order) {
331 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
332 s->options.min_partition_order, s->options.max_partition_order);
335 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
336 s->options.min_partition_order, s->options.max_partition_order);
338 if(avctx->frame_size > 0) {
339 if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
340 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
341 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
345 s->blocksize = avctx->frame_size;
347 s->blocksize = select_blocksize(s->samplerate, s->options.block_time_ms);
348 avctx->frame_size = s->blocksize;
350 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->blocksize);
352 /* set LPC precision */
353 if(avctx->lpc_coeff_precision > 0) {
354 if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
355 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
356 avctx->lpc_coeff_precision);
359 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
361 /* select LPC precision based on block size */
362 if( s->blocksize <= 192) s->options.lpc_coeff_precision = 7;
363 else if(s->blocksize <= 384) s->options.lpc_coeff_precision = 8;
364 else if(s->blocksize <= 576) s->options.lpc_coeff_precision = 9;
365 else if(s->blocksize <= 1152) s->options.lpc_coeff_precision = 10;
366 else if(s->blocksize <= 2304) s->options.lpc_coeff_precision = 11;
367 else if(s->blocksize <= 4608) s->options.lpc_coeff_precision = 12;
368 else if(s->blocksize <= 8192) s->options.lpc_coeff_precision = 13;
369 else if(s->blocksize <= 16384) s->options.lpc_coeff_precision = 14;
370 else s->options.lpc_coeff_precision = 15;
372 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
373 s->options.lpc_coeff_precision);
375 /* set maximum encoded frame size in verbatim mode */
376 if(s->channels == 2) {
377 s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
379 s->max_framesize = 14 + (s->blocksize * s->channels * 2);
382 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
383 write_streaminfo(s, streaminfo);
384 avctx->extradata = streaminfo;
385 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
389 avctx->coded_frame = avcodec_alloc_frame();
390 avctx->coded_frame->key_frame = 1;
395 static void init_frame(FlacEncodeContext *s)
402 for(i=0; i<16; i++) {
403 if(s->blocksize == flac_blocksizes[i]) {
404 frame->blocksize = flac_blocksizes[i];
405 frame->bs_code[0] = i;
406 frame->bs_code[1] = 0;
411 frame->blocksize = s->blocksize;
412 if(frame->blocksize <= 256) {
413 frame->bs_code[0] = 6;
414 frame->bs_code[1] = frame->blocksize-1;
416 frame->bs_code[0] = 7;
417 frame->bs_code[1] = frame->blocksize-1;
421 for(ch=0; ch<s->channels; ch++) {
422 frame->subframes[ch].obits = 16;
427 * Copy channel-interleaved input samples into separate subframes
429 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
435 for(i=0,j=0; i<frame->blocksize; i++) {
436 for(ch=0; ch<s->channels; ch++,j++) {
437 frame->subframes[ch].samples[i] = samples[j];
443 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
445 static int find_optimal_param(uint32_t sum, int n)
448 uint32_t nbits[MAX_RICE_PARAM+1];
451 nbits[0] = UINT32_MAX;
452 for(k=0; k<=MAX_RICE_PARAM; k++) {
453 nbits[k] = rice_encode_count(sum, n, k);
454 if(nbits[k] < nbits[k_opt]) {
461 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
462 uint32_t *sums, int n, int pred_order)
468 part = (1 << porder);
471 cnt = (n >> porder) - pred_order;
472 for(i=0; i<part; i++) {
473 if(i == 1) cnt = (n >> porder);
474 k = find_optimal_param(sums[i], cnt);
476 all_bits += rice_encode_count(sums[i], cnt, k);
478 all_bits += (4 * part);
485 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
486 uint32_t sums[][MAX_PARTITIONS])
490 uint32_t *res, *res_end;
492 /* sums for highest level */
494 res = &data[pred_order];
495 res_end = &data[n >> pmax];
496 for(i=0; i<parts; i++) {
498 while(res < res_end){
499 sums[pmax][i] += *(res++);
503 /* sums for lower levels */
504 for(i=pmax-1; i>=pmin; i--) {
506 for(j=0; j<parts; j++) {
507 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
512 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
513 int32_t *data, int n, int pred_order)
516 uint32_t bits[MAX_PARTITION_ORDER+1];
520 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
522 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
523 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
524 assert(pmin <= pmax);
526 udata = av_malloc(n * sizeof(uint32_t));
528 udata[i] = (2*data[i]) ^ (data[i]>>31);
531 calc_sums(pmin, pmax, udata, n, pred_order, sums);
534 bits[pmin] = UINT32_MAX;
535 for(i=pmin; i<=pmax; i++) {
536 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
537 if(bits[i] <= bits[opt_porder]) {
544 return bits[opt_porder];
547 static int get_max_p_order(int max_porder, int n, int order)
549 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
551 porder = FFMIN(porder, av_log2(n/order));
555 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
556 int32_t *data, int n, int pred_order,
560 pmin = get_max_p_order(pmin, n, pred_order);
561 pmax = get_max_p_order(pmax, n, pred_order);
562 bits = pred_order*bps + 6;
563 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
567 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
568 int32_t *data, int n, int pred_order,
569 int bps, int precision)
572 pmin = get_max_p_order(pmin, n, pred_order);
573 pmax = get_max_p_order(pmax, n, pred_order);
574 bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
575 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
580 * Apply Welch window function to audio block
582 static void apply_welch_window(const int32_t *data, int len, double *w_data)
589 c = 2.0 / (len - 1.0);
590 for(i=0; i<n2; i++) {
593 w_data[i] = data[i] * w;
594 w_data[len-1-i] = data[len-1-i] * w;
599 * Calculates autocorrelation data from audio samples
600 * A Welch window function is applied before calculation.
602 static void compute_autocorr(const int32_t *data, int len, int lag,
606 double tmp[len + lag];
607 double *data1= tmp + lag;
609 apply_welch_window(data, len, data1);
611 for(i=0; i<lag; i++){
616 for(i=0; i<len; i++){
617 for(lag_ptr= i-lag; lag_ptr<=i; lag_ptr++){
618 autoc[i-lag_ptr] += data1[i] * data1[lag_ptr];
624 * Levinson-Durbin recursion.
625 * Produces LPC coefficients from autocorrelation data.
627 static void compute_lpc_coefs(const double *autoc, int max_order,
628 double lpc[][MAX_LPC_ORDER], double *ref)
632 double lpc_tmp[MAX_LPC_ORDER];
634 for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
637 for(i=0; i<max_order; i++) {
640 r -= lpc_tmp[j] * autoc[i-j];
645 err *= 1.0 - (r * r);
649 for(j=0; j<i2; j++) {
651 lpc_tmp[j] += r * lpc_tmp[i-1-j];
652 lpc_tmp[i-1-j] += r * tmp;
655 lpc_tmp[j] += lpc_tmp[j] * r;
658 for(j=0; j<=i; j++) {
659 lpc[i][j] = -lpc_tmp[j];
665 * Quantize LPC coefficients
667 static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
668 int32_t *lpc_out, int *shift)
675 /* define maximum levels */
676 qmax = (1 << (precision - 1)) - 1;
678 /* find maximum coefficient value */
680 for(i=0; i<order; i++) {
681 cmax= FFMAX(cmax, fabs(lpc_in[i]));
684 /* if maximum value quantizes to zero, return all zeros */
685 if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
687 memset(lpc_out, 0, sizeof(int32_t) * order);
691 /* calculate level shift which scales max coeff to available bits */
693 while((cmax * (1 << sh) > qmax) && (sh > 0)) {
697 /* since negative shift values are unsupported in decoder, scale down
698 coefficients instead */
699 if(sh == 0 && cmax > qmax) {
700 double scale = ((double)qmax) / cmax;
701 for(i=0; i<order; i++) {
706 /* output quantized coefficients and level shift */
708 for(i=0; i<order; i++) {
709 error += lpc_in[i] * (1 << sh);
710 lpc_out[i] = clip(lrintf(error), -qmax, qmax);
716 static int estimate_best_order(double *ref, int max_order)
721 for(i=max_order-1; i>=0; i--) {
731 * Calculate LPC coefficients for multiple orders
733 static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
734 int precision, int32_t coefs[][MAX_LPC_ORDER],
735 int *shift, int use_lpc, int omethod)
737 double autoc[MAX_LPC_ORDER+1];
738 double ref[MAX_LPC_ORDER];
739 double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
743 assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
746 compute_autocorr(samples, blocksize, max_order+1, autoc);
748 compute_lpc_coefs(autoc, max_order, lpc, ref);
751 double var[MAX_LPC_ORDER+1], eval, weight;
753 for(pass=0; pass<use_lpc-1; pass++){
754 av_init_lls(&m[pass&1], max_order);
757 for(i=max_order; i<blocksize; i++){
758 for(j=0; j<=max_order; j++)
759 var[j]= samples[i-j];
762 eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
763 eval= (512>>pass) + fabs(eval - var[0]);
764 for(j=0; j<=max_order; j++)
770 av_update_lls(&m[pass&1], var, 1.0);
772 av_solve_lls(&m[pass&1], 0.001, 0);
775 for(i=0; i<max_order; i++){
776 for(j=0; j<max_order; j++)
777 lpc[i][j]= m[(pass-1)&1].coeff[i][j];
778 ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
780 for(i=max_order-1; i>0; i--)
781 ref[i] = ref[i-1] - ref[i];
783 opt_order = max_order;
785 if(omethod == ORDER_METHOD_EST) {
786 opt_order = estimate_best_order(ref, max_order);
788 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
790 for(i=0; i<max_order; i++) {
791 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
799 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
802 memcpy(res, smp, n * sizeof(int32_t));
805 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
810 for(i=0; i<order; i++) {
815 for(i=order; i<n; i++)
818 for(i=order; i<n; i++)
819 res[i]= smp[i] - smp[i-1];
821 for(i=order; i<n; i++)
822 res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
824 for(i=order; i<n; i++)
825 res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
827 for(i=order; i<n; i++)
828 res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
832 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
833 int order, const int32_t *coefs, int shift)
838 for(i=0; i<order; i++) {
841 for(i=order; i<n; i++) {
843 for(j=0; j<order; j++) {
844 pred += coefs[j] * smp[i-j-1];
846 res[i] = smp[i] - (pred >> shift);
850 static int encode_residual(FlacEncodeContext *ctx, int ch)
853 int min_order, max_order, opt_order, precision, omethod;
854 int min_porder, max_porder;
857 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
858 int shift[MAX_LPC_ORDER];
862 sub = &frame->subframes[ch];
865 n = frame->blocksize;
869 if(smp[i] != smp[0]) break;
872 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
879 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
880 encode_residual_verbatim(res, smp, n);
881 return sub->obits * n;
884 min_order = ctx->options.min_prediction_order;
885 max_order = ctx->options.max_prediction_order;
886 min_porder = ctx->options.min_partition_order;
887 max_porder = ctx->options.max_partition_order;
888 precision = ctx->options.lpc_coeff_precision;
889 omethod = ctx->options.prediction_order_method;
892 if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
893 uint32_t bits[MAX_FIXED_ORDER+1];
894 if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
896 bits[0] = UINT32_MAX;
897 for(i=min_order; i<=max_order; i++) {
898 encode_residual_fixed(res, smp, n, i);
899 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
901 if(bits[i] < bits[opt_order]) {
905 sub->order = opt_order;
906 sub->type = FLAC_SUBFRAME_FIXED;
907 sub->type_code = sub->type | sub->order;
908 if(sub->order != max_order) {
909 encode_residual_fixed(res, smp, n, sub->order);
910 return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
911 sub->order, sub->obits);
913 return bits[sub->order];
917 opt_order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
919 if(omethod == ORDER_METHOD_2LEVEL ||
920 omethod == ORDER_METHOD_4LEVEL ||
921 omethod == ORDER_METHOD_8LEVEL) {
922 int levels = 1 << omethod;
923 uint32_t bits[levels];
925 int opt_index = levels-1;
926 opt_order = max_order-1;
927 bits[opt_index] = UINT32_MAX;
928 for(i=levels-1; i>=0; i--) {
929 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
930 if(order < 0) order = 0;
931 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
932 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
933 res, n, order+1, sub->obits, precision);
934 if(bits[i] < bits[opt_index]) {
940 } else if(omethod == ORDER_METHOD_SEARCH) {
941 // brute-force optimal order search
942 uint32_t bits[MAX_LPC_ORDER];
944 bits[0] = UINT32_MAX;
945 for(i=min_order-1; i<max_order; i++) {
946 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
947 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
948 res, n, i+1, sub->obits, precision);
949 if(bits[i] < bits[opt_order]) {
956 sub->order = opt_order;
957 sub->type = FLAC_SUBFRAME_LPC;
958 sub->type_code = sub->type | (sub->order-1);
959 sub->shift = shift[sub->order-1];
960 for(i=0; i<sub->order; i++) {
961 sub->coefs[i] = coefs[sub->order-1][i];
963 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
964 return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
965 sub->obits, precision);
968 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
976 sub = &frame->subframes[ch];
979 n = frame->blocksize;
983 if(smp[i] != smp[0]) break;
986 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
992 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
993 encode_residual_verbatim(res, smp, n);
994 return sub->obits * n;
997 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1005 /* calculate sum of 2nd order residual for each channel */
1006 sum[0] = sum[1] = sum[2] = sum[3] = 0;
1007 for(i=2; i<n; i++) {
1008 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1009 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1010 sum[2] += ABS((lt + rt) >> 1);
1011 sum[3] += ABS(lt - rt);
1015 /* estimate bit counts */
1016 for(i=0; i<4; i++) {
1017 k = find_optimal_param(2*sum[i], n);
1018 sum[i] = rice_encode_count(2*sum[i], n, k);
1021 /* calculate score for each mode */
1022 score[0] = sum[0] + sum[1];
1023 score[1] = sum[0] + sum[3];
1024 score[2] = sum[1] + sum[3];
1025 score[3] = sum[2] + sum[3];
1027 /* return mode with lowest score */
1029 for(i=1; i<4; i++) {
1030 if(score[i] < score[best]) {
1035 return FLAC_CHMODE_LEFT_RIGHT;
1036 } else if(best == 1) {
1037 return FLAC_CHMODE_LEFT_SIDE;
1038 } else if(best == 2) {
1039 return FLAC_CHMODE_RIGHT_SIDE;
1041 return FLAC_CHMODE_MID_SIDE;
1046 * Perform stereo channel decorrelation
1048 static void channel_decorrelation(FlacEncodeContext *ctx)
1051 int32_t *left, *right;
1054 frame = &ctx->frame;
1055 n = frame->blocksize;
1056 left = frame->subframes[0].samples;
1057 right = frame->subframes[1].samples;
1059 if(ctx->channels != 2) {
1060 frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1064 frame->ch_mode = estimate_stereo_mode(left, right, n);
1066 /* perform decorrelation and adjust bits-per-sample */
1067 if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1070 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1072 for(i=0; i<n; i++) {
1074 left[i] = (tmp + right[i]) >> 1;
1075 right[i] = tmp - right[i];
1077 frame->subframes[1].obits++;
1078 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1079 for(i=0; i<n; i++) {
1080 right[i] = left[i] - right[i];
1082 frame->subframes[1].obits++;
1084 for(i=0; i<n; i++) {
1085 left[i] -= right[i];
1087 frame->subframes[0].obits++;
1091 static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1093 assert(bits >= 0 && bits <= 31);
1095 put_bits(pb, bits, val & ((1<<bits)-1));
1098 static void write_utf8(PutBitContext *pb, uint32_t val)
1103 put_bits(pb, 8, val);
1107 bytes= (av_log2(val)+4) / 5;
1108 shift = (bytes - 1) * 6;
1109 put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
1112 put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
1116 static void output_frame_header(FlacEncodeContext *s)
1123 put_bits(&s->pb, 16, 0xFFF8);
1124 put_bits(&s->pb, 4, frame->bs_code[0]);
1125 put_bits(&s->pb, 4, s->sr_code[0]);
1126 if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1127 put_bits(&s->pb, 4, s->ch_code);
1129 put_bits(&s->pb, 4, frame->ch_mode);
1131 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1132 put_bits(&s->pb, 1, 0);
1133 write_utf8(&s->pb, s->frame_count);
1134 if(frame->bs_code[0] == 6) {
1135 put_bits(&s->pb, 8, frame->bs_code[1]);
1136 } else if(frame->bs_code[0] == 7) {
1137 put_bits(&s->pb, 16, frame->bs_code[1]);
1139 if(s->sr_code[0] == 12) {
1140 put_bits(&s->pb, 8, s->sr_code[1]);
1141 } else if(s->sr_code[0] > 12) {
1142 put_bits(&s->pb, 16, s->sr_code[1]);
1144 flush_put_bits(&s->pb);
1145 crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1146 put_bits(&s->pb, 8, crc);
1149 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1154 sub = &s->frame.subframes[ch];
1155 res = sub->residual[0];
1156 put_sbits(&s->pb, sub->obits, res);
1159 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1167 sub = &frame->subframes[ch];
1169 for(i=0; i<frame->blocksize; i++) {
1170 res = sub->residual[i];
1171 put_sbits(&s->pb, sub->obits, res);
1175 static void output_residual(FlacEncodeContext *ctx, int ch)
1177 int i, j, p, n, parts;
1178 int k, porder, psize, res_cnt;
1183 frame = &ctx->frame;
1184 sub = &frame->subframes[ch];
1185 res = sub->residual;
1186 n = frame->blocksize;
1188 /* rice-encoded block */
1189 put_bits(&ctx->pb, 2, 0);
1191 /* partition order */
1192 porder = sub->rc.porder;
1193 psize = n >> porder;
1194 parts = (1 << porder);
1195 put_bits(&ctx->pb, 4, porder);
1196 res_cnt = psize - sub->order;
1200 for(p=0; p<parts; p++) {
1201 k = sub->rc.params[p];
1202 put_bits(&ctx->pb, 4, k);
1203 if(p == 1) res_cnt = psize;
1204 for(i=0; i<res_cnt && j<n; i++, j++) {
1205 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1210 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1216 frame = &ctx->frame;
1217 sub = &frame->subframes[ch];
1219 /* warm-up samples */
1220 for(i=0; i<sub->order; i++) {
1221 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1225 output_residual(ctx, ch);
1228 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1234 frame = &ctx->frame;
1235 sub = &frame->subframes[ch];
1237 /* warm-up samples */
1238 for(i=0; i<sub->order; i++) {
1239 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1242 /* LPC coefficients */
1243 cbits = ctx->options.lpc_coeff_precision;
1244 put_bits(&ctx->pb, 4, cbits-1);
1245 put_sbits(&ctx->pb, 5, sub->shift);
1246 for(i=0; i<sub->order; i++) {
1247 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1251 output_residual(ctx, ch);
1254 static void output_subframes(FlacEncodeContext *s)
1262 for(ch=0; ch<s->channels; ch++) {
1263 sub = &frame->subframes[ch];
1265 /* subframe header */
1266 put_bits(&s->pb, 1, 0);
1267 put_bits(&s->pb, 6, sub->type_code);
1268 put_bits(&s->pb, 1, 0); /* no wasted bits */
1271 if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1272 output_subframe_constant(s, ch);
1273 } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1274 output_subframe_verbatim(s, ch);
1275 } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1276 output_subframe_fixed(s, ch);
1277 } else if(sub->type == FLAC_SUBFRAME_LPC) {
1278 output_subframe_lpc(s, ch);
1283 static void output_frame_footer(FlacEncodeContext *s)
1286 flush_put_bits(&s->pb);
1287 crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1288 put_bits(&s->pb, 16, crc);
1289 flush_put_bits(&s->pb);
1292 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1293 int buf_size, void *data)
1296 FlacEncodeContext *s;
1297 int16_t *samples = data;
1300 s = avctx->priv_data;
1302 s->blocksize = avctx->frame_size;
1305 copy_samples(s, samples);
1307 channel_decorrelation(s);
1309 for(ch=0; ch<s->channels; ch++) {
1310 encode_residual(s, ch);
1312 init_put_bits(&s->pb, frame, buf_size);
1313 output_frame_header(s);
1314 output_subframes(s);
1315 output_frame_footer(s);
1316 out_bytes = put_bits_count(&s->pb) >> 3;
1318 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1319 /* frame too large. use verbatim mode */
1320 for(ch=0; ch<s->channels; ch++) {
1321 encode_residual_v(s, ch);
1323 init_put_bits(&s->pb, frame, buf_size);
1324 output_frame_header(s);
1325 output_subframes(s);
1326 output_frame_footer(s);
1327 out_bytes = put_bits_count(&s->pb) >> 3;
1329 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1330 /* still too large. must be an error. */
1331 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1340 static int flac_encode_close(AVCodecContext *avctx)
1342 av_freep(&avctx->extradata);
1343 avctx->extradata_size = 0;
1344 av_freep(&avctx->coded_frame);
1348 AVCodec flac_encoder = {
1352 sizeof(FlacEncodeContext),
1357 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,