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+1];
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);
619 for(j=0; j<lag; j+=2){
620 double sum0 = 1.0, sum1 = 1.0;
621 for(i=0; i<len; i++){
622 sum0 += data1[i] * data1[i-j];
623 sum1 += data1[i] * data1[i-j-1];
632 sum += data1[i] * data1[i-j];
638 * Levinson-Durbin recursion.
639 * Produces LPC coefficients from autocorrelation data.
641 static void compute_lpc_coefs(const double *autoc, int max_order,
642 double lpc[][MAX_LPC_ORDER], double *ref)
646 double lpc_tmp[MAX_LPC_ORDER];
648 for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
651 for(i=0; i<max_order; i++) {
654 r -= lpc_tmp[j] * autoc[i-j];
659 err *= 1.0 - (r * r);
663 for(j=0; j<i2; j++) {
665 lpc_tmp[j] += r * lpc_tmp[i-1-j];
666 lpc_tmp[i-1-j] += r * tmp;
669 lpc_tmp[j] += lpc_tmp[j] * r;
672 for(j=0; j<=i; j++) {
673 lpc[i][j] = -lpc_tmp[j];
679 * Quantize LPC coefficients
681 static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
682 int32_t *lpc_out, int *shift)
689 /* define maximum levels */
690 qmax = (1 << (precision - 1)) - 1;
692 /* find maximum coefficient value */
694 for(i=0; i<order; i++) {
695 cmax= FFMAX(cmax, fabs(lpc_in[i]));
698 /* if maximum value quantizes to zero, return all zeros */
699 if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
701 memset(lpc_out, 0, sizeof(int32_t) * order);
705 /* calculate level shift which scales max coeff to available bits */
707 while((cmax * (1 << sh) > qmax) && (sh > 0)) {
711 /* since negative shift values are unsupported in decoder, scale down
712 coefficients instead */
713 if(sh == 0 && cmax > qmax) {
714 double scale = ((double)qmax) / cmax;
715 for(i=0; i<order; i++) {
720 /* output quantized coefficients and level shift */
722 for(i=0; i<order; i++) {
723 error += lpc_in[i] * (1 << sh);
724 lpc_out[i] = av_clip(lrintf(error), -qmax, qmax);
730 static int estimate_best_order(double *ref, int max_order)
735 for(i=max_order-1; i>=0; i--) {
745 * Calculate LPC coefficients for multiple orders
747 static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
748 int precision, int32_t coefs[][MAX_LPC_ORDER],
749 int *shift, int use_lpc, int omethod)
751 double autoc[MAX_LPC_ORDER+1];
752 double ref[MAX_LPC_ORDER];
753 double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
757 assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
760 compute_autocorr(samples, blocksize, max_order+1, autoc);
762 compute_lpc_coefs(autoc, max_order, lpc, ref);
765 double var[MAX_LPC_ORDER+1], eval, weight;
767 for(pass=0; pass<use_lpc-1; pass++){
768 av_init_lls(&m[pass&1], max_order);
771 for(i=max_order; i<blocksize; i++){
772 for(j=0; j<=max_order; j++)
773 var[j]= samples[i-j];
776 eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
777 eval= (512>>pass) + fabs(eval - var[0]);
778 for(j=0; j<=max_order; j++)
784 av_update_lls(&m[pass&1], var, 1.0);
786 av_solve_lls(&m[pass&1], 0.001, 0);
789 for(i=0; i<max_order; i++){
790 for(j=0; j<max_order; j++)
791 lpc[i][j]= m[(pass-1)&1].coeff[i][j];
792 ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
794 for(i=max_order-1; i>0; i--)
795 ref[i] = ref[i-1] - ref[i];
797 opt_order = max_order;
799 if(omethod == ORDER_METHOD_EST) {
800 opt_order = estimate_best_order(ref, max_order);
802 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
804 for(i=0; i<max_order; i++) {
805 quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
813 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
816 memcpy(res, smp, n * sizeof(int32_t));
819 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
824 for(i=0; i<order; i++) {
829 for(i=order; i<n; i++)
832 for(i=order; i<n; i++)
833 res[i]= smp[i] - smp[i-1];
835 for(i=order; i<n; i++)
836 res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
838 for(i=order; i<n; i++)
839 res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
841 for(i=order; i<n; i++)
842 res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
847 int s = smp[i-(x)+1];\
853 static av_always_inline void encode_residual_lpc_unrolled(
854 int32_t *res, const int32_t *smp, int n,
855 int order, const int32_t *coefs, int shift, int big)
858 for(i=order; i<n; i+=2) {
859 int c = coefs[order-1];
860 int p0 = c * smp[i-order];
908 res[i ] = smp[i ] - (p0 >> shift);
909 res[i+1] = smp[i+1] - (p1 >> shift);
913 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
914 int order, const int32_t *coefs, int shift)
917 for(i=0; i<order; i++) {
921 for(i=order; i<n; i+=2) {
923 int32_t c = coefs[0];
924 int32_t p0 = 0, p1 = c*smp[i];
925 for(j=1; j<order; j++) {
926 int32_t s = smp[i-j];
931 p0 += c*smp[i-order];
932 res[i+0] = smp[i+0] - (p0 >> shift);
933 res[i+1] = smp[i+1] - (p1 >> shift);
937 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
938 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
939 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
940 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
941 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
942 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
943 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
944 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
945 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
950 static int encode_residual(FlacEncodeContext *ctx, int ch)
953 int min_order, max_order, opt_order, precision, omethod;
954 int min_porder, max_porder;
957 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
958 int shift[MAX_LPC_ORDER];
962 sub = &frame->subframes[ch];
965 n = frame->blocksize;
969 if(smp[i] != smp[0]) break;
972 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
979 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
980 encode_residual_verbatim(res, smp, n);
981 return sub->obits * n;
984 min_order = ctx->options.min_prediction_order;
985 max_order = ctx->options.max_prediction_order;
986 min_porder = ctx->options.min_partition_order;
987 max_porder = ctx->options.max_partition_order;
988 precision = ctx->options.lpc_coeff_precision;
989 omethod = ctx->options.prediction_order_method;
992 if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
993 uint32_t bits[MAX_FIXED_ORDER+1];
994 if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
996 bits[0] = UINT32_MAX;
997 for(i=min_order; i<=max_order; i++) {
998 encode_residual_fixed(res, smp, n, i);
999 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
1001 if(bits[i] < bits[opt_order]) {
1005 sub->order = opt_order;
1006 sub->type = FLAC_SUBFRAME_FIXED;
1007 sub->type_code = sub->type | sub->order;
1008 if(sub->order != max_order) {
1009 encode_residual_fixed(res, smp, n, sub->order);
1010 return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
1011 sub->order, sub->obits);
1013 return bits[sub->order];
1017 opt_order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
1019 if(omethod == ORDER_METHOD_2LEVEL ||
1020 omethod == ORDER_METHOD_4LEVEL ||
1021 omethod == ORDER_METHOD_8LEVEL) {
1022 int levels = 1 << omethod;
1023 uint32_t bits[levels];
1025 int opt_index = levels-1;
1026 opt_order = max_order-1;
1027 bits[opt_index] = UINT32_MAX;
1028 for(i=levels-1; i>=0; i--) {
1029 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
1030 if(order < 0) order = 0;
1031 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
1032 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1033 res, n, order+1, sub->obits, precision);
1034 if(bits[i] < bits[opt_index]) {
1040 } else if(omethod == ORDER_METHOD_SEARCH) {
1041 // brute-force optimal order search
1042 uint32_t bits[MAX_LPC_ORDER];
1044 bits[0] = UINT32_MAX;
1045 for(i=min_order-1; i<max_order; i++) {
1046 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
1047 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1048 res, n, i+1, sub->obits, precision);
1049 if(bits[i] < bits[opt_order]) {
1054 } else if(omethod == ORDER_METHOD_LOG) {
1055 uint32_t bits[MAX_LPC_ORDER];
1058 opt_order= min_order - 1 + (max_order-min_order)/3;
1059 memset(bits, -1, sizeof(bits));
1061 for(step=16 ;step; step>>=1){
1062 int last= opt_order;
1063 for(i=last-step; i<=last+step; i+= step){
1064 if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
1066 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
1067 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
1068 res, n, i+1, sub->obits, precision);
1069 if(bits[i] < bits[opt_order])
1076 sub->order = opt_order;
1077 sub->type = FLAC_SUBFRAME_LPC;
1078 sub->type_code = sub->type | (sub->order-1);
1079 sub->shift = shift[sub->order-1];
1080 for(i=0; i<sub->order; i++) {
1081 sub->coefs[i] = coefs[sub->order-1][i];
1083 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
1084 return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
1085 sub->obits, precision);
1088 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
1095 frame = &ctx->frame;
1096 sub = &frame->subframes[ch];
1097 res = sub->residual;
1099 n = frame->blocksize;
1102 for(i=1; i<n; i++) {
1103 if(smp[i] != smp[0]) break;
1106 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
1112 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
1113 encode_residual_verbatim(res, smp, n);
1114 return sub->obits * n;
1117 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1125 /* calculate sum of 2nd order residual for each channel */
1126 sum[0] = sum[1] = sum[2] = sum[3] = 0;
1127 for(i=2; i<n; i++) {
1128 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1129 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1130 sum[2] += FFABS((lt + rt) >> 1);
1131 sum[3] += FFABS(lt - rt);
1132 sum[0] += FFABS(lt);
1133 sum[1] += FFABS(rt);
1135 /* estimate bit counts */
1136 for(i=0; i<4; i++) {
1137 k = find_optimal_param(2*sum[i], n);
1138 sum[i] = rice_encode_count(2*sum[i], n, k);
1141 /* calculate score for each mode */
1142 score[0] = sum[0] + sum[1];
1143 score[1] = sum[0] + sum[3];
1144 score[2] = sum[1] + sum[3];
1145 score[3] = sum[2] + sum[3];
1147 /* return mode with lowest score */
1149 for(i=1; i<4; i++) {
1150 if(score[i] < score[best]) {
1155 return FLAC_CHMODE_LEFT_RIGHT;
1156 } else if(best == 1) {
1157 return FLAC_CHMODE_LEFT_SIDE;
1158 } else if(best == 2) {
1159 return FLAC_CHMODE_RIGHT_SIDE;
1161 return FLAC_CHMODE_MID_SIDE;
1166 * Perform stereo channel decorrelation
1168 static void channel_decorrelation(FlacEncodeContext *ctx)
1171 int32_t *left, *right;
1174 frame = &ctx->frame;
1175 n = frame->blocksize;
1176 left = frame->subframes[0].samples;
1177 right = frame->subframes[1].samples;
1179 if(ctx->channels != 2) {
1180 frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1184 frame->ch_mode = estimate_stereo_mode(left, right, n);
1186 /* perform decorrelation and adjust bits-per-sample */
1187 if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1190 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1192 for(i=0; i<n; i++) {
1194 left[i] = (tmp + right[i]) >> 1;
1195 right[i] = tmp - right[i];
1197 frame->subframes[1].obits++;
1198 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1199 for(i=0; i<n; i++) {
1200 right[i] = left[i] - right[i];
1202 frame->subframes[1].obits++;
1204 for(i=0; i<n; i++) {
1205 left[i] -= right[i];
1207 frame->subframes[0].obits++;
1211 static void put_sbits(PutBitContext *pb, int bits, int32_t val)
1213 assert(bits >= 0 && bits <= 31);
1215 put_bits(pb, bits, val & ((1<<bits)-1));
1218 static void write_utf8(PutBitContext *pb, uint32_t val)
1221 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1224 static void output_frame_header(FlacEncodeContext *s)
1231 put_bits(&s->pb, 16, 0xFFF8);
1232 put_bits(&s->pb, 4, frame->bs_code[0]);
1233 put_bits(&s->pb, 4, s->sr_code[0]);
1234 if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1235 put_bits(&s->pb, 4, s->ch_code);
1237 put_bits(&s->pb, 4, frame->ch_mode);
1239 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1240 put_bits(&s->pb, 1, 0);
1241 write_utf8(&s->pb, s->frame_count);
1242 if(frame->bs_code[0] == 6) {
1243 put_bits(&s->pb, 8, frame->bs_code[1]);
1244 } else if(frame->bs_code[0] == 7) {
1245 put_bits(&s->pb, 16, frame->bs_code[1]);
1247 if(s->sr_code[0] == 12) {
1248 put_bits(&s->pb, 8, s->sr_code[1]);
1249 } else if(s->sr_code[0] > 12) {
1250 put_bits(&s->pb, 16, s->sr_code[1]);
1252 flush_put_bits(&s->pb);
1253 crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
1254 put_bits(&s->pb, 8, crc);
1257 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1262 sub = &s->frame.subframes[ch];
1263 res = sub->residual[0];
1264 put_sbits(&s->pb, sub->obits, res);
1267 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1275 sub = &frame->subframes[ch];
1277 for(i=0; i<frame->blocksize; i++) {
1278 res = sub->residual[i];
1279 put_sbits(&s->pb, sub->obits, res);
1283 static void output_residual(FlacEncodeContext *ctx, int ch)
1285 int i, j, p, n, parts;
1286 int k, porder, psize, res_cnt;
1291 frame = &ctx->frame;
1292 sub = &frame->subframes[ch];
1293 res = sub->residual;
1294 n = frame->blocksize;
1296 /* rice-encoded block */
1297 put_bits(&ctx->pb, 2, 0);
1299 /* partition order */
1300 porder = sub->rc.porder;
1301 psize = n >> porder;
1302 parts = (1 << porder);
1303 put_bits(&ctx->pb, 4, porder);
1304 res_cnt = psize - sub->order;
1308 for(p=0; p<parts; p++) {
1309 k = sub->rc.params[p];
1310 put_bits(&ctx->pb, 4, k);
1311 if(p == 1) res_cnt = psize;
1312 for(i=0; i<res_cnt && j<n; i++, j++) {
1313 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1318 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1324 frame = &ctx->frame;
1325 sub = &frame->subframes[ch];
1327 /* warm-up samples */
1328 for(i=0; i<sub->order; i++) {
1329 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1333 output_residual(ctx, ch);
1336 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1342 frame = &ctx->frame;
1343 sub = &frame->subframes[ch];
1345 /* warm-up samples */
1346 for(i=0; i<sub->order; i++) {
1347 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1350 /* LPC coefficients */
1351 cbits = ctx->options.lpc_coeff_precision;
1352 put_bits(&ctx->pb, 4, cbits-1);
1353 put_sbits(&ctx->pb, 5, sub->shift);
1354 for(i=0; i<sub->order; i++) {
1355 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1359 output_residual(ctx, ch);
1362 static void output_subframes(FlacEncodeContext *s)
1370 for(ch=0; ch<s->channels; ch++) {
1371 sub = &frame->subframes[ch];
1373 /* subframe header */
1374 put_bits(&s->pb, 1, 0);
1375 put_bits(&s->pb, 6, sub->type_code);
1376 put_bits(&s->pb, 1, 0); /* no wasted bits */
1379 if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1380 output_subframe_constant(s, ch);
1381 } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1382 output_subframe_verbatim(s, ch);
1383 } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1384 output_subframe_fixed(s, ch);
1385 } else if(sub->type == FLAC_SUBFRAME_LPC) {
1386 output_subframe_lpc(s, ch);
1391 static void output_frame_footer(FlacEncodeContext *s)
1394 flush_put_bits(&s->pb);
1395 crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
1396 put_bits(&s->pb, 16, crc);
1397 flush_put_bits(&s->pb);
1400 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1401 int buf_size, void *data)
1404 FlacEncodeContext *s;
1405 int16_t *samples = data;
1408 s = avctx->priv_data;
1410 s->blocksize = avctx->frame_size;
1413 copy_samples(s, samples);
1415 channel_decorrelation(s);
1417 for(ch=0; ch<s->channels; ch++) {
1418 encode_residual(s, ch);
1420 init_put_bits(&s->pb, frame, buf_size);
1421 output_frame_header(s);
1422 output_subframes(s);
1423 output_frame_footer(s);
1424 out_bytes = put_bits_count(&s->pb) >> 3;
1426 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1427 /* frame too large. use verbatim mode */
1428 for(ch=0; ch<s->channels; ch++) {
1429 encode_residual_v(s, ch);
1431 init_put_bits(&s->pb, frame, buf_size);
1432 output_frame_header(s);
1433 output_subframes(s);
1434 output_frame_footer(s);
1435 out_bytes = put_bits_count(&s->pb) >> 3;
1437 if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
1438 /* still too large. must be an error. */
1439 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1448 static int flac_encode_close(AVCodecContext *avctx)
1450 av_freep(&avctx->extradata);
1451 avctx->extradata_size = 0;
1452 av_freep(&avctx->coded_frame);
1456 AVCodec flac_encoder = {
1460 sizeof(FlacEncodeContext),
1465 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,