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})[level];
231 s->options.use_lpc = ((int[]){ 0, 0, 0, 1, 1, 1})[level];
232 s->options.min_prediction_order= ((int[]){ 2, 0, 0, 1, 1, 1})[level];
233 s->options.max_prediction_order= ((int[]){ 3, 4, 4, 6, 8, 8})[level];
234 s->options.prediction_order_method = ORDER_METHOD_EST;
235 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0})[level];
236 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8})[level];
238 /* set compression option overrides from AVCodecContext */
239 if(avctx->use_lpc >= 0) {
240 s->options.use_lpc = clip(avctx->use_lpc, 0, 11);
242 if(s->options.use_lpc == 1)
243 av_log(avctx, AV_LOG_DEBUG, " use lpc: Levinson-Durbin recursion with Welch window\n");
244 else if(s->options.use_lpc > 1)
245 av_log(avctx, AV_LOG_DEBUG, " use lpc: Cholesky factorization\n");
247 if(avctx->min_prediction_order >= 0) {
248 if(s->options.use_lpc) {
249 if(avctx->min_prediction_order < MIN_LPC_ORDER ||
250 avctx->min_prediction_order > MAX_LPC_ORDER) {
251 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
252 avctx->min_prediction_order);
256 if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
257 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
258 avctx->min_prediction_order);
262 s->options.min_prediction_order = avctx->min_prediction_order;
264 if(avctx->max_prediction_order >= 0) {
265 if(s->options.use_lpc) {
266 if(avctx->max_prediction_order < MIN_LPC_ORDER ||
267 avctx->max_prediction_order > MAX_LPC_ORDER) {
268 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
269 avctx->max_prediction_order);
273 if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
274 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
275 avctx->max_prediction_order);
279 s->options.max_prediction_order = avctx->max_prediction_order;
281 if(s->options.max_prediction_order < s->options.min_prediction_order) {
282 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
283 s->options.min_prediction_order, s->options.max_prediction_order);
286 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
287 s->options.min_prediction_order, s->options.max_prediction_order);
289 if(avctx->prediction_order_method >= 0) {
290 if(avctx->prediction_order_method > ORDER_METHOD_SEARCH) {
291 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
292 avctx->prediction_order_method);
295 s->options.prediction_order_method = avctx->prediction_order_method;
297 switch(avctx->prediction_order_method) {
298 case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
300 case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
302 case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
304 case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
306 case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
307 "full search"); break;
310 if(avctx->min_partition_order >= 0) {
311 if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
312 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
313 avctx->min_partition_order);
316 s->options.min_partition_order = avctx->min_partition_order;
318 if(avctx->max_partition_order >= 0) {
319 if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
320 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
321 avctx->max_partition_order);
324 s->options.max_partition_order = avctx->max_partition_order;
326 if(s->options.max_partition_order < s->options.min_partition_order) {
327 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
328 s->options.min_partition_order, s->options.max_partition_order);
331 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
332 s->options.min_partition_order, s->options.max_partition_order);
334 if(avctx->frame_size > 0) {
335 if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
336 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
337 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
341 s->blocksize = avctx->frame_size;
343 s->blocksize = select_blocksize(s->samplerate, s->options.block_time_ms);
344 avctx->frame_size = s->blocksize;
346 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->blocksize);
348 /* set LPC precision */
349 if(avctx->lpc_coeff_precision > 0) {
350 if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
351 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
352 avctx->lpc_coeff_precision);
355 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
357 /* select LPC precision based on block size */
358 if( s->blocksize <= 192) s->options.lpc_coeff_precision = 7;
359 else if(s->blocksize <= 384) s->options.lpc_coeff_precision = 8;
360 else if(s->blocksize <= 576) s->options.lpc_coeff_precision = 9;
361 else if(s->blocksize <= 1152) s->options.lpc_coeff_precision = 10;
362 else if(s->blocksize <= 2304) s->options.lpc_coeff_precision = 11;
363 else if(s->blocksize <= 4608) s->options.lpc_coeff_precision = 12;
364 else if(s->blocksize <= 8192) s->options.lpc_coeff_precision = 13;
365 else if(s->blocksize <= 16384) s->options.lpc_coeff_precision = 14;
366 else s->options.lpc_coeff_precision = 15;
368 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
369 s->options.lpc_coeff_precision);
371 /* set maximum encoded frame size in verbatim mode */
372 if(s->channels == 2) {
373 s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
375 s->max_framesize = 14 + (s->blocksize * s->channels * 2);
378 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
379 write_streaminfo(s, streaminfo);
380 avctx->extradata = streaminfo;
381 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
385 avctx->coded_frame = avcodec_alloc_frame();
386 avctx->coded_frame->key_frame = 1;
391 static void init_frame(FlacEncodeContext *s)
398 for(i=0; i<16; i++) {
399 if(s->blocksize == flac_blocksizes[i]) {
400 frame->blocksize = flac_blocksizes[i];
401 frame->bs_code[0] = i;
402 frame->bs_code[1] = 0;
407 frame->blocksize = s->blocksize;
408 if(frame->blocksize <= 256) {
409 frame->bs_code[0] = 6;
410 frame->bs_code[1] = frame->blocksize-1;
412 frame->bs_code[0] = 7;
413 frame->bs_code[1] = frame->blocksize-1;
417 for(ch=0; ch<s->channels; ch++) {
418 frame->subframes[ch].obits = 16;
423 * Copy channel-interleaved input samples into separate subframes
425 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
431 for(i=0,j=0; i<frame->blocksize; i++) {
432 for(ch=0; ch<s->channels; ch++,j++) {
433 frame->subframes[ch].samples[i] = samples[j];
439 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
441 static int find_optimal_param(uint32_t sum, int n)
444 uint32_t nbits[MAX_RICE_PARAM+1];
447 nbits[0] = UINT32_MAX;
448 for(k=0; k<=MAX_RICE_PARAM; k++) {
449 nbits[k] = rice_encode_count(sum, n, k);
450 if(nbits[k] < nbits[k_opt]) {
457 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
458 uint32_t *sums, int n, int pred_order)
464 part = (1 << porder);
467 cnt = (n >> porder) - pred_order;
468 for(i=0; i<part; i++) {
469 if(i == 1) cnt = (n >> porder);
470 k = find_optimal_param(sums[i], cnt);
472 all_bits += rice_encode_count(sums[i], cnt, k);
474 all_bits += (4 * part);
481 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
482 uint32_t sums[][MAX_PARTITIONS])
486 uint32_t *res, *res_end;
488 /* sums for highest level */
490 res = &data[pred_order];
491 res_end = &data[n >> pmax];
492 for(i=0; i<parts; i++) {
494 while(res < res_end){
495 sums[pmax][i] += *(res++);
499 /* sums for lower levels */
500 for(i=pmax-1; i>=pmin; i--) {
502 for(j=0; j<parts; j++) {
503 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
508 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
509 int32_t *data, int n, int pred_order)
512 uint32_t bits[MAX_PARTITION_ORDER+1];
516 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
518 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
519 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
520 assert(pmin <= pmax);
522 udata = av_malloc(n * sizeof(uint32_t));
524 udata[i] = (2*data[i]) ^ (data[i]>>31);
527 calc_sums(pmin, pmax, udata, n, pred_order, sums);
530 bits[pmin] = UINT32_MAX;
531 for(i=pmin; i<=pmax; i++) {
532 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
533 if(bits[i] <= bits[opt_porder]) {
540 return bits[opt_porder];
543 static int get_max_p_order(int max_porder, int n, int order)
545 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
547 porder = FFMIN(porder, av_log2(n/order));
551 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
552 int32_t *data, int n, int pred_order,
556 pmin = get_max_p_order(pmin, n, pred_order);
557 pmax = get_max_p_order(pmax, n, pred_order);
558 bits = pred_order*bps + 6;
559 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
563 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
564 int32_t *data, int n, int pred_order,
565 int bps, int precision)
568 pmin = get_max_p_order(pmin, n, pred_order);
569 pmax = get_max_p_order(pmax, n, pred_order);
570 bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
571 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
576 * Apply Welch window function to audio block
578 static void apply_welch_window(const int32_t *data, int len, double *w_data)
585 c = 2.0 / (len - 1.0);
586 for(i=0; i<n2; i++) {
589 w_data[i] = data[i] * w;
590 w_data[len-1-i] = data[len-1-i] * w;
595 * Calculates autocorrelation data from audio samples
596 * A Welch window function is applied before calculation.
598 static void compute_autocorr(const int32_t *data, int len, int lag,
602 double tmp[len + lag];
603 double *data1= tmp + lag;
605 apply_welch_window(data, len, data1);
607 for(i=0; i<lag; i++){
612 for(i=0; i<len; i++){
613 for(lag_ptr= i-lag; lag_ptr<=i; lag_ptr++){
614 autoc[i-lag_ptr] += data1[i] * data1[lag_ptr];
620 * Levinson-Durbin recursion.
621 * Produces LPC coefficients from autocorrelation data.
623 static void compute_lpc_coefs(const double *autoc, int max_order,
624 double lpc[][MAX_LPC_ORDER], double *ref)
628 double lpc_tmp[MAX_LPC_ORDER];
630 for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
633 for(i=0; i<max_order; i++) {
636 r -= lpc_tmp[j] * autoc[i-j];
641 err *= 1.0 - (r * r);
645 for(j=0; j<i2; j++) {
647 lpc_tmp[j] += r * lpc_tmp[i-1-j];
648 lpc_tmp[i-1-j] += r * tmp;
651 lpc_tmp[j] += lpc_tmp[j] * r;
654 for(j=0; j<=i; j++) {
655 lpc[i][j] = -lpc_tmp[j];
661 * Quantize LPC coefficients
663 static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
664 int32_t *lpc_out, int *shift)
671 /* define maximum levels */
672 qmax = (1 << (precision - 1)) - 1;
674 /* find maximum coefficient value */
676 for(i=0; i<order; i++) {
677 cmax= FFMAX(cmax, fabs(lpc_in[i]));
680 /* if maximum value quantizes to zero, return all zeros */
681 if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
683 memset(lpc_out, 0, sizeof(int32_t) * order);
687 /* calculate level shift which scales max coeff to available bits */
689 while((cmax * (1 << sh) > qmax) && (sh > 0)) {
693 /* since negative shift values are unsupported in decoder, scale down
694 coefficients instead */
695 if(sh == 0 && cmax > qmax) {
696 double scale = ((double)qmax) / cmax;
697 for(i=0; i<order; i++) {
702 /* output quantized coefficients and level shift */
704 for(i=0; i<order; i++) {
705 error += lpc_in[i] * (1 << sh);
706 lpc_out[i] = clip(lrintf(error), -qmax, qmax);
712 static int estimate_best_order(double *ref, int max_order)
717 for(i=max_order-1; i>=0; i--) {
727 * Calculate LPC coefficients for multiple orders
729 static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
730 int precision, int32_t coefs[][MAX_LPC_ORDER],
731 int *shift, int use_lpc)
733 double autoc[MAX_LPC_ORDER+1];
734 double ref[MAX_LPC_ORDER];
735 double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
739 assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
742 compute_autocorr(samples, blocksize, max_order+1, autoc);
744 compute_lpc_coefs(autoc, max_order, lpc, ref);
746 opt_order = estimate_best_order(ref, max_order);
749 double var[MAX_LPC_ORDER+1], eval;
751 for(pass=0; pass<use_lpc-1; pass++){
752 av_init_lls(&m[pass&1], max_order);
754 for(i=max_order; i<blocksize; i++){
755 for(j=0; j<=max_order; j++)
756 var[j]= samples[i-j];
759 eval= av_evaluate_lls(&m[(pass-1)&1], var+1);
760 eval= (512>>pass) + fabs(eval - var[0]);
761 for(j=0; j<=max_order; j++)
765 av_update_lls(&m[pass&1], var, 1.0);
767 av_solve_lls(&m[pass&1], 0.001);
768 opt_order= max_order; //FIXME
771 for(i=0; i<opt_order; i++)
772 lpc[opt_order-1][i]= m[(pass-1)&1].coeff[i];
776 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
782 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
785 memcpy(res, smp, n * sizeof(int32_t));
788 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
793 for(i=0; i<order; i++) {
798 for(i=order; i<n; i++)
801 for(i=order; i<n; i++)
802 res[i]= smp[i] - smp[i-1];
804 for(i=order; i<n; i++)
805 res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
807 for(i=order; i<n; i++)
808 res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
810 for(i=order; i<n; i++)
811 res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
815 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
816 int order, const int32_t *coefs, int shift)
821 for(i=0; i<order; i++) {
824 for(i=order; i<n; i++) {
826 for(j=0; j<order; j++) {
827 pred += coefs[j] * smp[i-j-1];
829 res[i] = smp[i] - (pred >> shift);
833 static int encode_residual(FlacEncodeContext *ctx, int ch)
836 int min_order, max_order, opt_order, precision;
837 int min_porder, max_porder;
840 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
841 int shift[MAX_LPC_ORDER];
845 sub = &frame->subframes[ch];
848 n = frame->blocksize;
852 if(smp[i] != smp[0]) break;
855 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
862 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
863 encode_residual_verbatim(res, smp, n);
864 return sub->obits * n;
867 min_order = ctx->options.min_prediction_order;
868 max_order = ctx->options.max_prediction_order;
869 min_porder = ctx->options.min_partition_order;
870 max_porder = ctx->options.max_partition_order;
871 precision = ctx->options.lpc_coeff_precision;
874 if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
875 uint32_t bits[MAX_FIXED_ORDER+1];
876 if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
878 bits[0] = UINT32_MAX;
879 for(i=min_order; i<=max_order; i++) {
880 encode_residual_fixed(res, smp, n, i);
881 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
883 if(bits[i] < bits[opt_order]) {
887 sub->order = opt_order;
888 sub->type = FLAC_SUBFRAME_FIXED;
889 sub->type_code = sub->type | sub->order;
890 if(sub->order != max_order) {
891 encode_residual_fixed(res, smp, n, sub->order);
892 return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
893 sub->order, sub->obits);
895 return bits[sub->order];
899 sub->order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc);
900 sub->type = FLAC_SUBFRAME_LPC;
901 sub->type_code = sub->type | (sub->order-1);
902 sub->shift = shift[sub->order-1];
903 for(i=0; i<sub->order; i++) {
904 sub->coefs[i] = coefs[sub->order-1][i];
906 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
907 return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
908 sub->obits, precision);
911 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
919 sub = &frame->subframes[ch];
922 n = frame->blocksize;
926 if(smp[i] != smp[0]) break;
929 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
935 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
936 encode_residual_verbatim(res, smp, n);
937 return sub->obits * n;
940 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
948 /* calculate sum of 2nd order residual for each channel */
949 sum[0] = sum[1] = sum[2] = sum[3] = 0;
951 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
952 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
953 sum[2] += ABS((lt + rt) >> 1);
954 sum[3] += ABS(lt - rt);
958 /* estimate bit counts */
960 k = find_optimal_param(2*sum[i], n);
961 sum[i] = rice_encode_count(2*sum[i], n, k);
964 /* calculate score for each mode */
965 score[0] = sum[0] + sum[1];
966 score[1] = sum[0] + sum[3];
967 score[2] = sum[1] + sum[3];
968 score[3] = sum[2] + sum[3];
970 /* return mode with lowest score */
973 if(score[i] < score[best]) {
978 return FLAC_CHMODE_LEFT_RIGHT;
979 } else if(best == 1) {
980 return FLAC_CHMODE_LEFT_SIDE;
981 } else if(best == 2) {
982 return FLAC_CHMODE_RIGHT_SIDE;
984 return FLAC_CHMODE_MID_SIDE;
989 * Perform stereo channel decorrelation
991 static void channel_decorrelation(FlacEncodeContext *ctx)
994 int32_t *left, *right;
998 n = frame->blocksize;
999 left = frame->subframes[0].samples;
1000 right = frame->subframes[1].samples;
1002 if(ctx->channels != 2) {
1003 frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1007 frame->ch_mode = estimate_stereo_mode(left, right, n);
1009 /* perform decorrelation and adjust bits-per-sample */
1010 if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1013 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1015 for(i=0; i<n; i++) {
1017 left[i] = (tmp + right[i]) >> 1;
1018 right[i] = tmp - right[i];
1020 frame->subframes[1].obits++;
1021 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1022 for(i=0; i<n; i++) {
1023 right[i] = left[i] - right[i];
1025 frame->subframes[1].obits++;
1027 for(i=0; i<n; i++) {
1028 left[i] -= right[i];
1030 frame->subframes[0].obits++;
1034 static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1036 assert(bits >= 0 && bits <= 31);
1038 put_bits(pb, bits, val & ((1<<bits)-1));
1041 static void write_utf8(PutBitContext *pb, uint32_t val)
1046 put_bits(pb, 8, val);
1050 bytes= (av_log2(val)+4) / 5;
1051 shift = (bytes - 1) * 6;
1052 put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
1055 put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
1059 static void output_frame_header(FlacEncodeContext *s)
1066 put_bits(&s->pb, 16, 0xFFF8);
1067 put_bits(&s->pb, 4, frame->bs_code[0]);
1068 put_bits(&s->pb, 4, s->sr_code[0]);
1069 if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1070 put_bits(&s->pb, 4, s->ch_code);
1072 put_bits(&s->pb, 4, frame->ch_mode);
1074 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1075 put_bits(&s->pb, 1, 0);
1076 write_utf8(&s->pb, s->frame_count);
1077 if(frame->bs_code[0] == 6) {
1078 put_bits(&s->pb, 8, frame->bs_code[1]);
1079 } else if(frame->bs_code[0] == 7) {
1080 put_bits(&s->pb, 16, frame->bs_code[1]);
1082 if(s->sr_code[0] == 12) {
1083 put_bits(&s->pb, 8, s->sr_code[1]);
1084 } else if(s->sr_code[0] > 12) {
1085 put_bits(&s->pb, 16, s->sr_code[1]);
1087 flush_put_bits(&s->pb);
1088 crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1089 put_bits(&s->pb, 8, crc);
1092 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1097 sub = &s->frame.subframes[ch];
1098 res = sub->residual[0];
1099 put_sbits(&s->pb, sub->obits, res);
1102 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1110 sub = &frame->subframes[ch];
1112 for(i=0; i<frame->blocksize; i++) {
1113 res = sub->residual[i];
1114 put_sbits(&s->pb, sub->obits, res);
1118 static void output_residual(FlacEncodeContext *ctx, int ch)
1120 int i, j, p, n, parts;
1121 int k, porder, psize, res_cnt;
1126 frame = &ctx->frame;
1127 sub = &frame->subframes[ch];
1128 res = sub->residual;
1129 n = frame->blocksize;
1131 /* rice-encoded block */
1132 put_bits(&ctx->pb, 2, 0);
1134 /* partition order */
1135 porder = sub->rc.porder;
1136 psize = n >> porder;
1137 parts = (1 << porder);
1138 put_bits(&ctx->pb, 4, porder);
1139 res_cnt = psize - sub->order;
1143 for(p=0; p<parts; p++) {
1144 k = sub->rc.params[p];
1145 put_bits(&ctx->pb, 4, k);
1146 if(p == 1) res_cnt = psize;
1147 for(i=0; i<res_cnt && j<n; i++, j++) {
1148 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1153 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1159 frame = &ctx->frame;
1160 sub = &frame->subframes[ch];
1162 /* warm-up samples */
1163 for(i=0; i<sub->order; i++) {
1164 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1168 output_residual(ctx, ch);
1171 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1177 frame = &ctx->frame;
1178 sub = &frame->subframes[ch];
1180 /* warm-up samples */
1181 for(i=0; i<sub->order; i++) {
1182 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1185 /* LPC coefficients */
1186 cbits = ctx->options.lpc_coeff_precision;
1187 put_bits(&ctx->pb, 4, cbits-1);
1188 put_sbits(&ctx->pb, 5, sub->shift);
1189 for(i=0; i<sub->order; i++) {
1190 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1194 output_residual(ctx, ch);
1197 static void output_subframes(FlacEncodeContext *s)
1205 for(ch=0; ch<s->channels; ch++) {
1206 sub = &frame->subframes[ch];
1208 /* subframe header */
1209 put_bits(&s->pb, 1, 0);
1210 put_bits(&s->pb, 6, sub->type_code);
1211 put_bits(&s->pb, 1, 0); /* no wasted bits */
1214 if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1215 output_subframe_constant(s, ch);
1216 } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1217 output_subframe_verbatim(s, ch);
1218 } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1219 output_subframe_fixed(s, ch);
1220 } else if(sub->type == FLAC_SUBFRAME_LPC) {
1221 output_subframe_lpc(s, ch);
1226 static void output_frame_footer(FlacEncodeContext *s)
1229 flush_put_bits(&s->pb);
1230 crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1231 put_bits(&s->pb, 16, crc);
1232 flush_put_bits(&s->pb);
1235 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1236 int buf_size, void *data)
1239 FlacEncodeContext *s;
1240 int16_t *samples = data;
1243 s = avctx->priv_data;
1245 s->blocksize = avctx->frame_size;
1248 copy_samples(s, samples);
1250 channel_decorrelation(s);
1252 for(ch=0; ch<s->channels; ch++) {
1253 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 || out_bytes >= buf_size) {
1262 /* frame too large. use verbatim mode */
1263 for(ch=0; ch<s->channels; ch++) {
1264 encode_residual_v(s, ch);
1266 init_put_bits(&s->pb, frame, buf_size);
1267 output_frame_header(s);
1268 output_subframes(s);
1269 output_frame_footer(s);
1270 out_bytes = put_bits_count(&s->pb) >> 3;
1272 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1273 /* still too large. must be an error. */
1274 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1283 static int flac_encode_close(AVCodecContext *avctx)
1285 av_freep(&avctx->extradata);
1286 avctx->extradata_size = 0;
1287 av_freep(&avctx->coded_frame);
1291 AVCodec flac_encoder = {
1295 sizeof(FlacEncodeContext),
1300 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,