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"
26 #define FLAC_MIN_BLOCKSIZE 16
27 #define FLAC_MAX_BLOCKSIZE 65535
29 #define FLAC_SUBFRAME_CONSTANT 0
30 #define FLAC_SUBFRAME_VERBATIM 1
31 #define FLAC_SUBFRAME_FIXED 8
32 #define FLAC_SUBFRAME_LPC 32
34 #define FLAC_CHMODE_NOT_STEREO 0
35 #define FLAC_CHMODE_LEFT_RIGHT 1
36 #define FLAC_CHMODE_LEFT_SIDE 8
37 #define FLAC_CHMODE_RIGHT_SIDE 9
38 #define FLAC_CHMODE_MID_SIDE 10
40 #define ORDER_METHOD_EST 0
41 #define ORDER_METHOD_2LEVEL 1
42 #define ORDER_METHOD_4LEVEL 2
43 #define ORDER_METHOD_8LEVEL 3
44 #define ORDER_METHOD_SEARCH 4
46 #define FLAC_STREAMINFO_SIZE 34
48 #define MIN_LPC_ORDER 1
49 #define MAX_LPC_ORDER 32
50 #define MAX_FIXED_ORDER 4
51 #define MAX_PARTITION_ORDER 8
52 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
53 #define MAX_LPC_PRECISION 15
54 #define MAX_LPC_SHIFT 15
55 #define MAX_RICE_PARAM 14
57 typedef struct CompressionOptions {
58 int compression_level;
61 int lpc_coeff_precision;
62 int min_prediction_order;
63 int max_prediction_order;
64 int prediction_order_method;
65 int min_partition_order;
66 int max_partition_order;
69 typedef struct RiceContext {
71 int params[MAX_PARTITIONS];
74 typedef struct FlacSubframe {
79 int32_t coefs[MAX_LPC_ORDER];
82 int32_t samples[FLAC_MAX_BLOCKSIZE];
83 int32_t residual[FLAC_MAX_BLOCKSIZE];
86 typedef struct FlacFrame {
87 FlacSubframe subframes[FLAC_MAX_CH];
94 typedef struct FlacEncodeContext {
102 uint32_t frame_count;
104 CompressionOptions options;
105 AVCodecContext *avctx;
108 static const int flac_samplerates[16] = {
110 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
114 static const int flac_blocksizes[16] = {
117 576, 1152, 2304, 4608,
119 256, 512, 1024, 2048, 4096, 8192, 16384, 32768
123 * Writes streaminfo metadata block to byte array
125 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
129 memset(header, 0, FLAC_STREAMINFO_SIZE);
130 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
132 /* streaminfo metadata block */
133 put_bits(&pb, 16, s->blocksize);
134 put_bits(&pb, 16, s->blocksize);
135 put_bits(&pb, 24, 0);
136 put_bits(&pb, 24, s->max_framesize);
137 put_bits(&pb, 20, s->samplerate);
138 put_bits(&pb, 3, s->channels-1);
139 put_bits(&pb, 5, 15); /* bits per sample - 1 */
141 /* total samples = 0 */
142 /* MD5 signature = 0 */
146 * Sets blocksize based on samplerate
147 * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
149 static int select_blocksize(int samplerate, int block_time_ms)
155 assert(samplerate > 0);
156 blocksize = flac_blocksizes[1];
157 target = (samplerate * block_time_ms) / 1000;
158 for(i=0; i<16; i++) {
159 if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
160 blocksize = flac_blocksizes[i];
166 static int flac_encode_init(AVCodecContext *avctx)
168 int freq = avctx->sample_rate;
169 int channels = avctx->channels;
170 FlacEncodeContext *s = avctx->priv_data;
176 if(avctx->sample_fmt != SAMPLE_FMT_S16) {
180 if(channels < 1 || channels > FLAC_MAX_CH) {
183 s->channels = channels;
184 s->ch_code = s->channels-1;
186 /* find samplerate in table */
189 for(i=4; i<12; i++) {
190 if(freq == flac_samplerates[i]) {
191 s->samplerate = flac_samplerates[i];
197 /* if not in table, samplerate is non-standard */
199 if(freq % 1000 == 0 && freq < 255000) {
201 s->sr_code[1] = freq / 1000;
202 } else if(freq % 10 == 0 && freq < 655350) {
204 s->sr_code[1] = freq / 10;
205 } else if(freq < 65535) {
207 s->sr_code[1] = freq;
211 s->samplerate = freq;
214 /* set compression option defaults based on avctx->compression_level */
215 if(avctx->compression_level < 0) {
216 s->options.compression_level = 5;
218 s->options.compression_level = avctx->compression_level;
220 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
222 if(s->options.compression_level == 0) {
223 s->options.block_time_ms = 27;
224 s->options.use_lpc = 0;
225 s->options.min_prediction_order = 2;
226 s->options.max_prediction_order = 3;
227 s->options.prediction_order_method = ORDER_METHOD_EST;
228 s->options.min_partition_order = 2;
229 s->options.max_partition_order = 2;
230 } else if(s->options.compression_level == 1) {
231 s->options.block_time_ms = 27;
232 s->options.use_lpc = 0;
233 s->options.min_prediction_order = 0;
234 s->options.max_prediction_order = 4;
235 s->options.prediction_order_method = ORDER_METHOD_EST;
236 s->options.min_partition_order = 2;
237 s->options.max_partition_order = 2;
238 } else if(s->options.compression_level == 2) {
239 s->options.block_time_ms = 27;
240 s->options.use_lpc = 0;
241 s->options.min_prediction_order = 0;
242 s->options.max_prediction_order = 4;
243 s->options.prediction_order_method = ORDER_METHOD_EST;
244 s->options.min_partition_order = 0;
245 s->options.max_partition_order = 3;
246 } else if(s->options.compression_level == 3) {
247 s->options.block_time_ms = 105;
248 s->options.use_lpc = 1;
249 s->options.min_prediction_order = 1;
250 s->options.max_prediction_order = 6;
251 s->options.prediction_order_method = ORDER_METHOD_EST;
252 s->options.min_partition_order = 0;
253 s->options.max_partition_order = 3;
254 } else if(s->options.compression_level == 4) {
255 s->options.block_time_ms = 105;
256 s->options.use_lpc = 1;
257 s->options.min_prediction_order = 1;
258 s->options.max_prediction_order = 8;
259 s->options.prediction_order_method = ORDER_METHOD_EST;
260 s->options.min_partition_order = 0;
261 s->options.max_partition_order = 3;
262 } else if(s->options.compression_level == 5) {
263 s->options.block_time_ms = 105;
264 s->options.use_lpc = 1;
265 s->options.min_prediction_order = 1;
266 s->options.max_prediction_order = 8;
267 s->options.prediction_order_method = ORDER_METHOD_EST;
268 s->options.min_partition_order = 0;
269 s->options.max_partition_order = 8;
271 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
272 s->options.compression_level);
276 /* set compression option overrides from AVCodecContext */
277 if(avctx->use_lpc >= 0) {
278 s->options.use_lpc = !!avctx->use_lpc;
280 av_log(avctx, AV_LOG_DEBUG, " use lpc: %s\n",
281 s->options.use_lpc? "yes" : "no");
283 if(avctx->min_prediction_order >= 0) {
284 if(s->options.use_lpc) {
285 if(avctx->min_prediction_order < MIN_LPC_ORDER ||
286 avctx->min_prediction_order > MAX_LPC_ORDER) {
287 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
288 avctx->min_prediction_order);
292 if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
293 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
294 avctx->min_prediction_order);
298 s->options.min_prediction_order = avctx->min_prediction_order;
300 if(avctx->max_prediction_order >= 0) {
301 if(s->options.use_lpc) {
302 if(avctx->max_prediction_order < MIN_LPC_ORDER ||
303 avctx->max_prediction_order > MAX_LPC_ORDER) {
304 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
305 avctx->max_prediction_order);
309 if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
310 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
311 avctx->max_prediction_order);
315 s->options.max_prediction_order = avctx->max_prediction_order;
317 if(s->options.max_prediction_order < s->options.min_prediction_order) {
318 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
319 s->options.min_prediction_order, s->options.max_prediction_order);
322 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
323 s->options.min_prediction_order, s->options.max_prediction_order);
325 if(avctx->prediction_order_method >= 0) {
326 if(avctx->prediction_order_method > ORDER_METHOD_SEARCH) {
327 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
328 avctx->prediction_order_method);
331 s->options.prediction_order_method = avctx->prediction_order_method;
333 switch(avctx->prediction_order_method) {
334 case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
336 case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
338 case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
340 case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
342 case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
343 "full search"); break;
346 if(avctx->min_partition_order >= 0) {
347 if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
348 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
349 avctx->min_partition_order);
352 s->options.min_partition_order = avctx->min_partition_order;
354 if(avctx->max_partition_order >= 0) {
355 if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
356 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
357 avctx->max_partition_order);
360 s->options.max_partition_order = avctx->max_partition_order;
362 if(s->options.max_partition_order < s->options.min_partition_order) {
363 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
364 s->options.min_partition_order, s->options.max_partition_order);
367 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
368 s->options.min_partition_order, s->options.max_partition_order);
370 if(avctx->frame_size > 0) {
371 if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
372 avctx->frame_size > FLAC_MIN_BLOCKSIZE) {
373 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
377 s->blocksize = avctx->frame_size;
379 s->blocksize = select_blocksize(s->samplerate, s->options.block_time_ms);
380 avctx->frame_size = s->blocksize;
382 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->blocksize);
384 /* set LPC precision */
385 if(avctx->lpc_coeff_precision > 0) {
386 if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
387 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
388 avctx->lpc_coeff_precision);
391 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
393 /* select LPC precision based on block size */
394 if( s->blocksize <= 192) s->options.lpc_coeff_precision = 7;
395 else if(s->blocksize <= 384) s->options.lpc_coeff_precision = 8;
396 else if(s->blocksize <= 576) s->options.lpc_coeff_precision = 9;
397 else if(s->blocksize <= 1152) s->options.lpc_coeff_precision = 10;
398 else if(s->blocksize <= 2304) s->options.lpc_coeff_precision = 11;
399 else if(s->blocksize <= 4608) s->options.lpc_coeff_precision = 12;
400 else if(s->blocksize <= 8192) s->options.lpc_coeff_precision = 13;
401 else if(s->blocksize <= 16384) s->options.lpc_coeff_precision = 14;
402 else s->options.lpc_coeff_precision = 15;
404 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
405 s->options.lpc_coeff_precision);
407 /* set maximum encoded frame size in verbatim mode */
408 if(s->channels == 2) {
409 s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
411 s->max_framesize = 14 + (s->blocksize * s->channels * 2);
414 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
415 write_streaminfo(s, streaminfo);
416 avctx->extradata = streaminfo;
417 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
421 avctx->coded_frame = avcodec_alloc_frame();
422 avctx->coded_frame->key_frame = 1;
427 static void init_frame(FlacEncodeContext *s)
434 for(i=0; i<16; i++) {
435 if(s->blocksize == flac_blocksizes[i]) {
436 frame->blocksize = flac_blocksizes[i];
437 frame->bs_code[0] = i;
438 frame->bs_code[1] = 0;
443 frame->blocksize = s->blocksize;
444 if(frame->blocksize <= 256) {
445 frame->bs_code[0] = 6;
446 frame->bs_code[1] = frame->blocksize-1;
448 frame->bs_code[0] = 7;
449 frame->bs_code[1] = frame->blocksize-1;
453 for(ch=0; ch<s->channels; ch++) {
454 frame->subframes[ch].obits = 16;
459 * Copy channel-interleaved input samples into separate subframes
461 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
467 for(i=0,j=0; i<frame->blocksize; i++) {
468 for(ch=0; ch<s->channels; ch++,j++) {
469 frame->subframes[ch].samples[i] = samples[j];
475 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
477 static int find_optimal_param(uint32_t sum, int n)
480 uint32_t nbits[MAX_RICE_PARAM+1];
483 nbits[0] = UINT32_MAX;
484 for(k=0; k<=MAX_RICE_PARAM; k++) {
485 nbits[k] = rice_encode_count(sum, n, k);
486 if(nbits[k] < nbits[k_opt]) {
493 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
494 uint32_t *sums, int n, int pred_order)
500 part = (1 << porder);
503 cnt = (n >> porder) - pred_order;
504 for(i=0; i<part; i++) {
505 if(i == 1) cnt = (n >> porder);
506 k = find_optimal_param(sums[i], cnt);
508 all_bits += rice_encode_count(sums[i], cnt, k);
510 all_bits += (4 * part);
517 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
518 uint32_t sums[][MAX_PARTITIONS])
522 uint32_t *res, *res_end;
524 /* sums for highest level */
526 res = &data[pred_order];
527 res_end = &data[n >> pmax];
528 for(i=0; i<parts; i++) {
530 while(res < res_end){
531 sums[pmax][i] += *(res++);
535 /* sums for lower levels */
536 for(i=pmax-1; i>=pmin; i--) {
538 for(j=0; j<parts; j++) {
539 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
544 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
545 int32_t *data, int n, int pred_order)
548 uint32_t bits[MAX_PARTITION_ORDER+1];
552 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
554 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
555 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
556 assert(pmin <= pmax);
558 udata = av_malloc(n * sizeof(uint32_t));
560 udata[i] = (2*data[i]) ^ (data[i]>>31);
563 calc_sums(pmin, pmax, udata, n, pred_order, sums);
566 bits[pmin] = UINT32_MAX;
567 for(i=pmin; i<=pmax; i++) {
568 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
569 if(bits[i] <= bits[opt_porder]) {
571 memcpy(rc, &tmp_rc, sizeof(RiceContext));
576 return bits[opt_porder];
579 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
580 int32_t *data, int n, int pred_order,
584 bits = pred_order*bps + 6;
585 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
589 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
590 int32_t *data, int n, int pred_order,
591 int bps, int precision)
594 bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
595 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
600 * Apply Welch window function to audio block
602 static void apply_welch_window(const int32_t *data, int len, double *w_data)
609 c = 2.0 / (len - 1.0);
610 for(i=0; i<n2; i++) {
613 w_data[i] = data[i] * w;
614 w_data[len-1-i] = data[len-1-i] * w;
619 * Calculates autocorrelation data from audio samples
620 * A Welch window function is applied before calculation.
622 static void compute_autocorr(const int32_t *data, int len, int lag,
629 data1 = av_malloc(len * sizeof(double));
630 apply_welch_window(data, len, data1);
632 for(i=0; i<lag; i++) autoc[i] = 1.0;
637 while(lag_ptr <= ptr) {
638 autoc[ptr-lag_ptr] += data1[ptr] * data1[lag_ptr];
645 while(lag_ptr <= ptr) {
646 autoc[ptr-lag_ptr] += data1[ptr] * data1[lag_ptr];
656 * Levinson-Durbin recursion.
657 * Produces LPC coefficients from autocorrelation data.
659 static void compute_lpc_coefs(const double *autoc, int max_order,
660 double lpc[][MAX_LPC_ORDER], double *ref)
664 double lpc_tmp[MAX_LPC_ORDER];
666 for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
669 for(i=0; i<max_order; i++) {
672 r -= lpc_tmp[j] * autoc[i-j];
677 err *= 1.0 - (r * r);
681 for(j=0; j<i2; j++) {
683 lpc_tmp[j] += r * lpc_tmp[i-1-j];
684 lpc_tmp[i-1-j] += r * tmp;
687 lpc_tmp[j] += lpc_tmp[j] * r;
690 for(j=0; j<=i; j++) {
691 lpc[i][j] = -lpc_tmp[j];
697 * Quantize LPC coefficients
699 static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
700 int32_t *lpc_out, int *shift)
707 /* define maximum levels */
708 qmax = (1 << (precision - 1)) - 1;
710 /* find maximum coefficient value */
712 for(i=0; i<order; i++) {
719 /* if maximum value quantizes to zero, return all zeros */
720 if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
722 for(i=0; i<order; i++) {
728 /* calculate level shift which scales max coeff to available bits */
730 while((cmax * (1 << sh) > qmax) && (sh > 0)) {
734 /* since negative shift values are unsupported in decoder, scale down
735 coefficients instead */
736 if(sh == 0 && cmax > qmax) {
737 double scale = ((double)qmax) / cmax;
738 for(i=0; i<order; i++) {
743 /* output quantized coefficients and level shift */
744 for(i=0; i<order; i++) {
745 lpc_out[i] = (int32_t)(lpc_in[i] * (1 << sh));
750 static int estimate_best_order(double *ref, int max_order)
755 for(i=max_order-1; i>=0; i--) {
765 * Calculate LPC coefficients for multiple orders
767 static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
768 int precision, int32_t coefs[][MAX_LPC_ORDER],
771 double autoc[MAX_LPC_ORDER+1];
772 double ref[MAX_LPC_ORDER];
773 double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
777 assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
779 compute_autocorr(samples, blocksize, max_order+1, autoc);
781 compute_lpc_coefs(autoc, max_order, lpc, ref);
783 opt_order = estimate_best_order(ref, max_order);
786 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
792 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
795 memcpy(res, smp, n * sizeof(int32_t));
798 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
803 for(i=0; i<order; i++) {
808 for(i=order; i<n; i++)
811 for(i=order; i<n; i++)
812 res[i]= smp[i] - smp[i-1];
814 for(i=order; i<n; i++)
815 res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
817 for(i=order; i<n; i++)
818 res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
820 for(i=order; i<n; i++)
821 res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
825 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
826 int order, const int32_t *coefs, int shift)
831 for(i=0; i<order; i++) {
834 for(i=order; i<n; i++) {
836 for(j=0; j<order; j++) {
837 pred += coefs[j] * smp[i-j-1];
839 res[i] = smp[i] - (pred >> shift);
843 static int get_max_p_order(int max_porder, int n, int order)
845 int porder, max_parts;
849 max_parts = (1 << porder);
850 if(!(n % max_parts) && (n > max_parts*order)) {
858 static int encode_residual(FlacEncodeContext *ctx, int ch)
861 int min_order, max_order, opt_order, precision;
862 int porder, min_porder, max_porder;
865 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
866 int shift[MAX_LPC_ORDER];
870 sub = &frame->subframes[ch];
873 n = frame->blocksize;
877 if(smp[i] != smp[0]) break;
880 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
887 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
888 encode_residual_verbatim(res, smp, n);
889 return sub->obits * n;
892 min_order = ctx->options.min_prediction_order;
893 max_order = ctx->options.max_prediction_order;
894 min_porder = ctx->options.min_partition_order;
895 max_porder = ctx->options.max_partition_order;
896 precision = ctx->options.lpc_coeff_precision;
899 if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
900 uint32_t bits[MAX_FIXED_ORDER+1];
901 if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
903 bits[0] = UINT32_MAX;
904 for(i=min_order; i<=max_order; i++) {
905 encode_residual_fixed(res, smp, n, i);
906 porder = get_max_p_order(max_porder, n, i);
907 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, porder, res,
909 if(bits[i] < bits[opt_order]) {
913 sub->order = opt_order;
914 sub->type = FLAC_SUBFRAME_FIXED;
915 sub->type_code = sub->type | sub->order;
916 if(sub->order != max_order) {
917 encode_residual_fixed(res, smp, n, sub->order);
918 porder = get_max_p_order(max_porder, n, sub->order);
919 return calc_rice_params_fixed(&sub->rc, min_porder, porder, res, n,
920 sub->order, sub->obits);
922 return bits[sub->order];
926 sub->order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift);
927 sub->type = FLAC_SUBFRAME_LPC;
928 sub->type_code = sub->type | (sub->order-1);
929 sub->shift = shift[sub->order-1];
930 for(i=0; i<sub->order; i++) {
931 sub->coefs[i] = coefs[sub->order-1][i];
933 porder = get_max_p_order(max_porder, n, sub->order);
934 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
935 return calc_rice_params_lpc(&sub->rc, 0, porder, res, n, sub->order,
936 sub->obits, precision);
939 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
947 sub = &frame->subframes[ch];
950 n = frame->blocksize;
954 if(smp[i] != smp[0]) break;
957 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
963 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
964 encode_residual_verbatim(res, smp, n);
965 return sub->obits * n;
968 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
976 /* calculate sum of 2nd order residual for each channel */
977 sum[0] = sum[1] = sum[2] = sum[3] = 0;
979 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
980 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
981 sum[2] += ABS((lt + rt) >> 1);
982 sum[3] += ABS(lt - rt);
986 /* estimate bit counts */
988 k = find_optimal_param(2*sum[i], n);
989 sum[i] = rice_encode_count(2*sum[i], n, k);
992 /* calculate score for each mode */
993 score[0] = sum[0] + sum[1];
994 score[1] = sum[0] + sum[3];
995 score[2] = sum[1] + sum[3];
996 score[3] = sum[2] + sum[3];
998 /* return mode with lowest score */
1000 for(i=1; i<4; i++) {
1001 if(score[i] < score[best]) {
1006 return FLAC_CHMODE_LEFT_RIGHT;
1007 } else if(best == 1) {
1008 return FLAC_CHMODE_LEFT_SIDE;
1009 } else if(best == 2) {
1010 return FLAC_CHMODE_RIGHT_SIDE;
1012 return FLAC_CHMODE_MID_SIDE;
1017 * Perform stereo channel decorrelation
1019 static void channel_decorrelation(FlacEncodeContext *ctx)
1022 int32_t *left, *right;
1025 frame = &ctx->frame;
1026 n = frame->blocksize;
1027 left = frame->subframes[0].samples;
1028 right = frame->subframes[1].samples;
1030 if(ctx->channels != 2) {
1031 frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1035 frame->ch_mode = estimate_stereo_mode(left, right, n);
1037 /* perform decorrelation and adjust bits-per-sample */
1038 if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1041 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1043 for(i=0; i<n; i++) {
1045 left[i] = (tmp + right[i]) >> 1;
1046 right[i] = tmp - right[i];
1048 frame->subframes[1].obits++;
1049 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1050 for(i=0; i<n; i++) {
1051 right[i] = left[i] - right[i];
1053 frame->subframes[1].obits++;
1055 for(i=0; i<n; i++) {
1056 left[i] -= right[i];
1058 frame->subframes[0].obits++;
1062 static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1064 assert(bits >= 0 && bits <= 31);
1066 put_bits(pb, bits, val & ((1<<bits)-1));
1069 static void write_utf8(PutBitContext *pb, uint32_t val)
1074 put_bits(pb, 8, val);
1078 bytes= (av_log2(val)+4) / 5;
1079 shift = (bytes - 1) * 6;
1080 put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
1083 put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
1087 static void output_frame_header(FlacEncodeContext *s)
1094 put_bits(&s->pb, 16, 0xFFF8);
1095 put_bits(&s->pb, 4, frame->bs_code[0]);
1096 put_bits(&s->pb, 4, s->sr_code[0]);
1097 if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1098 put_bits(&s->pb, 4, s->ch_code);
1100 put_bits(&s->pb, 4, frame->ch_mode);
1102 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1103 put_bits(&s->pb, 1, 0);
1104 write_utf8(&s->pb, s->frame_count);
1105 if(frame->bs_code[0] == 6) {
1106 put_bits(&s->pb, 8, frame->bs_code[1]);
1107 } else if(frame->bs_code[0] == 7) {
1108 put_bits(&s->pb, 16, frame->bs_code[1]);
1110 if(s->sr_code[0] == 12) {
1111 put_bits(&s->pb, 8, s->sr_code[1]);
1112 } else if(s->sr_code[0] > 12) {
1113 put_bits(&s->pb, 16, s->sr_code[1]);
1115 flush_put_bits(&s->pb);
1116 crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1117 put_bits(&s->pb, 8, crc);
1120 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1125 sub = &s->frame.subframes[ch];
1126 res = sub->residual[0];
1127 put_sbits(&s->pb, sub->obits, res);
1130 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1138 sub = &frame->subframes[ch];
1140 for(i=0; i<frame->blocksize; i++) {
1141 res = sub->residual[i];
1142 put_sbits(&s->pb, sub->obits, res);
1146 static void output_residual(FlacEncodeContext *ctx, int ch)
1148 int i, j, p, n, parts;
1149 int k, porder, psize, res_cnt;
1154 frame = &ctx->frame;
1155 sub = &frame->subframes[ch];
1156 res = sub->residual;
1157 n = frame->blocksize;
1159 /* rice-encoded block */
1160 put_bits(&ctx->pb, 2, 0);
1162 /* partition order */
1163 porder = sub->rc.porder;
1164 psize = n >> porder;
1165 parts = (1 << porder);
1166 put_bits(&ctx->pb, 4, porder);
1167 res_cnt = psize - sub->order;
1171 for(p=0; p<parts; p++) {
1172 k = sub->rc.params[p];
1173 put_bits(&ctx->pb, 4, k);
1174 if(p == 1) res_cnt = psize;
1175 for(i=0; i<res_cnt && j<n; i++, j++) {
1176 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1181 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1187 frame = &ctx->frame;
1188 sub = &frame->subframes[ch];
1190 /* warm-up samples */
1191 for(i=0; i<sub->order; i++) {
1192 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1196 output_residual(ctx, ch);
1199 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1205 frame = &ctx->frame;
1206 sub = &frame->subframes[ch];
1208 /* warm-up samples */
1209 for(i=0; i<sub->order; i++) {
1210 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1213 /* LPC coefficients */
1214 cbits = ctx->options.lpc_coeff_precision;
1215 put_bits(&ctx->pb, 4, cbits-1);
1216 put_sbits(&ctx->pb, 5, sub->shift);
1217 for(i=0; i<sub->order; i++) {
1218 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1222 output_residual(ctx, ch);
1225 static void output_subframes(FlacEncodeContext *s)
1233 for(ch=0; ch<s->channels; ch++) {
1234 sub = &frame->subframes[ch];
1236 /* subframe header */
1237 put_bits(&s->pb, 1, 0);
1238 put_bits(&s->pb, 6, sub->type_code);
1239 put_bits(&s->pb, 1, 0); /* no wasted bits */
1242 if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1243 output_subframe_constant(s, ch);
1244 } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1245 output_subframe_verbatim(s, ch);
1246 } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1247 output_subframe_fixed(s, ch);
1248 } else if(sub->type == FLAC_SUBFRAME_LPC) {
1249 output_subframe_lpc(s, ch);
1254 static void output_frame_footer(FlacEncodeContext *s)
1257 flush_put_bits(&s->pb);
1258 crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1259 put_bits(&s->pb, 16, crc);
1260 flush_put_bits(&s->pb);
1263 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1264 int buf_size, void *data)
1267 FlacEncodeContext *s;
1268 int16_t *samples = data;
1271 s = avctx->priv_data;
1273 s->blocksize = avctx->frame_size;
1276 copy_samples(s, samples);
1278 channel_decorrelation(s);
1280 for(ch=0; ch<s->channels; ch++) {
1281 encode_residual(s, ch);
1283 init_put_bits(&s->pb, frame, buf_size);
1284 output_frame_header(s);
1285 output_subframes(s);
1286 output_frame_footer(s);
1287 out_bytes = put_bits_count(&s->pb) >> 3;
1289 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1290 /* frame too large. use verbatim mode */
1291 for(ch=0; ch<s->channels; ch++) {
1292 encode_residual_v(s, ch);
1294 init_put_bits(&s->pb, frame, buf_size);
1295 output_frame_header(s);
1296 output_subframes(s);
1297 output_frame_footer(s);
1298 out_bytes = put_bits_count(&s->pb) >> 3;
1300 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1301 /* still too large. must be an error. */
1302 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1311 static int flac_encode_close(AVCodecContext *avctx)
1313 av_freep(&avctx->extradata);
1314 avctx->extradata_size = 0;
1315 av_freep(&avctx->coded_frame);
1319 AVCodec flac_encoder = {
1323 sizeof(FlacEncodeContext),
1328 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,