+
+#define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
+
+static int find_optimal_param(uint32_t sum, int n)
+{
+ int k, k_opt;
+ uint32_t nbits[MAX_RICE_PARAM+1];
+
+ k_opt = 0;
+ nbits[0] = UINT32_MAX;
+ for(k=0; k<=MAX_RICE_PARAM; k++) {
+ nbits[k] = rice_encode_count(sum, n, k);
+ if(nbits[k] < nbits[k_opt]) {
+ k_opt = k;
+ }
+ }
+ return k_opt;
+}
+
+static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
+ uint32_t *sums, int n, int pred_order)
+{
+ int i;
+ int k, cnt, part;
+ uint32_t all_bits;
+
+ part = (1 << porder);
+ all_bits = 0;
+
+ cnt = (n >> porder) - pred_order;
+ for(i=0; i<part; i++) {
+ if(i == 1) cnt = (n >> porder);
+ k = find_optimal_param(sums[i], cnt);
+ rc->params[i] = k;
+ all_bits += rice_encode_count(sums[i], cnt, k);
+ }
+ all_bits += (4 * part);
+
+ rc->porder = porder;
+
+ return all_bits;
+}
+
+static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
+ uint32_t sums[][MAX_PARTITIONS])
+{
+ int i, j;
+ int parts;
+ uint32_t *res, *res_end;
+
+ /* sums for highest level */
+ parts = (1 << pmax);
+ res = &data[pred_order];
+ res_end = &data[n >> pmax];
+ for(i=0; i<parts; i++) {
+ sums[pmax][i] = 0;
+ while(res < res_end){
+ sums[pmax][i] += *(res++);
+ }
+ res_end+= n >> pmax;
+ }
+ /* sums for lower levels */
+ for(i=pmax-1; i>=pmin; i--) {
+ parts = (1 << i);
+ for(j=0; j<parts; j++) {
+ sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
+ }
+ }
+}
+
+static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
+ int32_t *data, int n, int pred_order)
+{
+ int i;
+ uint32_t bits[MAX_PARTITION_ORDER+1];
+ int opt_porder;
+ RiceContext tmp_rc;
+ uint32_t *udata;
+ uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
+
+ assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
+ assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
+ assert(pmin <= pmax);
+
+ udata = av_malloc(n * sizeof(uint32_t));
+ for(i=0; i<n; i++) {
+ udata[i] = (2*data[i]) ^ (data[i]>>31);
+ }
+
+ calc_sums(pmin, pmax, udata, n, pred_order, sums);
+
+ opt_porder = pmin;
+ bits[pmin] = UINT32_MAX;
+ for(i=pmin; i<=pmax; i++) {
+ bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
+ if(bits[i] <= bits[opt_porder]) {
+ opt_porder = i;
+ *rc= tmp_rc;
+ }
+ }
+
+ av_freep(&udata);
+ return bits[opt_porder];
+}
+
+static int get_max_p_order(int max_porder, int n, int order)
+{
+ int porder = FFMIN(max_porder, av_log2(n^(n-1)));
+ if(order > 0)
+ porder = FFMIN(porder, av_log2(n/order));
+ return porder;
+}
+
+static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
+ int32_t *data, int n, int pred_order,
+ int bps)
+{
+ uint32_t bits;
+ pmin = get_max_p_order(pmin, n, pred_order);
+ pmax = get_max_p_order(pmax, n, pred_order);
+ bits = pred_order*bps + 6;
+ bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
+ return bits;
+}
+
+static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
+ int32_t *data, int n, int pred_order,
+ int bps, int precision)
+{
+ uint32_t bits;
+ pmin = get_max_p_order(pmin, n, pred_order);
+ pmax = get_max_p_order(pmax, n, pred_order);
+ bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
+ bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
+ return bits;
+}
+
+/**
+ * Apply Welch window function to audio block
+ */
+static void apply_welch_window(const int32_t *data, int len, double *w_data)
+{
+ int i, n2;
+ double w;
+ double c;
+
+ n2 = (len >> 1);
+ c = 2.0 / (len - 1.0);
+ for(i=0; i<n2; i++) {
+ w = c - i - 1.0;
+ w = 1.0 - (w * w);
+ w_data[i] = data[i] * w;
+ w_data[len-1-i] = data[len-1-i] * w;
+ }
+}
+
+/**
+ * Calculates autocorrelation data from audio samples
+ * A Welch window function is applied before calculation.
+ */
+static void compute_autocorr(const int32_t *data, int len, int lag,
+ double *autoc)
+{
+ int i, lag_ptr;
+ double tmp[len + lag];
+ double *data1= tmp + lag;
+
+ apply_welch_window(data, len, data1);
+
+ for(i=0; i<lag; i++){
+ autoc[i] = 1.0;
+ data1[i-lag]= 0.0;
+ }
+
+ for(i=0; i<len; i++){
+ for(lag_ptr= i-lag; lag_ptr<=i; lag_ptr++){
+ autoc[i-lag_ptr] += data1[i] * data1[lag_ptr];
+ }
+ }
+}
+
+/**
+ * Levinson-Durbin recursion.
+ * Produces LPC coefficients from autocorrelation data.
+ */
+static void compute_lpc_coefs(const double *autoc, int max_order,
+ double lpc[][MAX_LPC_ORDER], double *ref)
+{
+ int i, j, i2;
+ double r, err, tmp;
+ double lpc_tmp[MAX_LPC_ORDER];
+
+ for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
+ err = autoc[0];
+
+ for(i=0; i<max_order; i++) {
+ r = -autoc[i+1];
+ for(j=0; j<i; j++) {
+ r -= lpc_tmp[j] * autoc[i-j];
+ }
+ r /= err;
+ ref[i] = fabs(r);
+
+ err *= 1.0 - (r * r);
+
+ i2 = (i >> 1);
+ lpc_tmp[i] = r;
+ for(j=0; j<i2; j++) {
+ tmp = lpc_tmp[j];
+ lpc_tmp[j] += r * lpc_tmp[i-1-j];
+ lpc_tmp[i-1-j] += r * tmp;
+ }
+ if(i & 1) {
+ lpc_tmp[j] += lpc_tmp[j] * r;
+ }
+
+ for(j=0; j<=i; j++) {
+ lpc[i][j] = -lpc_tmp[j];
+ }
+ }
+}
+
+/**
+ * Quantize LPC coefficients
+ */
+static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
+ int32_t *lpc_out, int *shift)
+{
+ int i;
+ double cmax, error;
+ int32_t qmax;
+ int sh;
+
+ /* define maximum levels */
+ qmax = (1 << (precision - 1)) - 1;
+
+ /* find maximum coefficient value */
+ cmax = 0.0;
+ for(i=0; i<order; i++) {
+ cmax= FFMAX(cmax, fabs(lpc_in[i]));
+ }
+
+ /* if maximum value quantizes to zero, return all zeros */
+ if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
+ *shift = 0;
+ memset(lpc_out, 0, sizeof(int32_t) * order);
+ return;
+ }
+
+ /* calculate level shift which scales max coeff to available bits */
+ sh = MAX_LPC_SHIFT;
+ while((cmax * (1 << sh) > qmax) && (sh > 0)) {
+ sh--;
+ }
+
+ /* since negative shift values are unsupported in decoder, scale down
+ coefficients instead */
+ if(sh == 0 && cmax > qmax) {
+ double scale = ((double)qmax) / cmax;
+ for(i=0; i<order; i++) {
+ lpc_in[i] *= scale;
+ }
+ }
+
+ /* output quantized coefficients and level shift */
+ error=0;
+ for(i=0; i<order; i++) {
+ error += lpc_in[i] * (1 << sh);
+ lpc_out[i] = av_clip(lrintf(error), -qmax, qmax);
+ error -= lpc_out[i];
+ }
+ *shift = sh;
+}
+
+static int estimate_best_order(double *ref, int max_order)
+{
+ int i, est;
+
+ est = 1;
+ for(i=max_order-1; i>=0; i--) {
+ if(ref[i] > 0.10) {
+ est = i+1;
+ break;
+ }
+ }
+ return est;
+}
+
+/**
+ * Calculate LPC coefficients for multiple orders
+ */
+static int lpc_calc_coefs(const int32_t *samples, int blocksize, int max_order,
+ int precision, int32_t coefs[][MAX_LPC_ORDER],
+ int *shift, int use_lpc, int omethod)
+{
+ double autoc[MAX_LPC_ORDER+1];
+ double ref[MAX_LPC_ORDER];
+ double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
+ int i, j, pass;
+ int opt_order;
+
+ assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
+
+ if(use_lpc == 1){
+ compute_autocorr(samples, blocksize, max_order+1, autoc);
+
+ compute_lpc_coefs(autoc, max_order, lpc, ref);
+ }else{
+ LLSModel m[2];
+ double var[MAX_LPC_ORDER+1], eval, weight;
+
+ for(pass=0; pass<use_lpc-1; pass++){
+ av_init_lls(&m[pass&1], max_order);
+
+ weight=0;
+ for(i=max_order; i<blocksize; i++){
+ for(j=0; j<=max_order; j++)
+ var[j]= samples[i-j];
+
+ if(pass){
+ eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
+ eval= (512>>pass) + fabs(eval - var[0]);
+ for(j=0; j<=max_order; j++)
+ var[j]/= sqrt(eval);
+ weight += 1/eval;
+ }else
+ weight++;
+
+ av_update_lls(&m[pass&1], var, 1.0);
+ }
+ av_solve_lls(&m[pass&1], 0.001, 0);
+ }
+
+ for(i=0; i<max_order; i++){
+ for(j=0; j<max_order; j++)
+ lpc[i][j]= m[(pass-1)&1].coeff[i][j];
+ ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
+ }
+ for(i=max_order-1; i>0; i--)
+ ref[i] = ref[i-1] - ref[i];
+ }
+ opt_order = max_order;
+
+ if(omethod == ORDER_METHOD_EST) {
+ opt_order = estimate_best_order(ref, max_order);
+ i = opt_order-1;
+ quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
+ } else {
+ for(i=0; i<max_order; i++) {
+ quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
+ }
+ }
+
+ return opt_order;
+}
+
+
+static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
+{
+ assert(n > 0);
+ memcpy(res, smp, n * sizeof(int32_t));
+}
+
+static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
+ int order)
+{
+ int i;
+
+ for(i=0; i<order; i++) {
+ res[i] = smp[i];
+ }
+
+ if(order==0){
+ for(i=order; i<n; i++)
+ res[i]= smp[i];
+ }else if(order==1){
+ for(i=order; i<n; i++)
+ res[i]= smp[i] - smp[i-1];
+ }else if(order==2){
+ for(i=order; i<n; i++)
+ res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
+ }else if(order==3){
+ for(i=order; i<n; i++)
+ res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
+ }else{
+ for(i=order; i<n; i++)
+ res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
+ }
+}
+
+static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
+ int order, const int32_t *coefs, int shift)
+{
+ int i, j;
+ int32_t pred;
+
+ for(i=0; i<order; i++) {
+ res[i] = smp[i];
+ }
+ for(i=order; i<n; i++) {
+ pred = 0;
+ for(j=0; j<order; j++) {
+ pred += coefs[j] * smp[i-j-1];
+ }
+ res[i] = smp[i] - (pred >> shift);
+ }
+}
+
+static int encode_residual(FlacEncodeContext *ctx, int ch)
+{
+ int i, n;
+ int min_order, max_order, opt_order, precision, omethod;
+ int min_porder, max_porder;
+ FlacFrame *frame;
+ FlacSubframe *sub;
+ int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
+ int shift[MAX_LPC_ORDER];
+ int32_t *res, *smp;
+
+ frame = &ctx->frame;
+ sub = &frame->subframes[ch];
+ res = sub->residual;
+ smp = sub->samples;
+ n = frame->blocksize;
+
+ /* CONSTANT */
+ for(i=1; i<n; i++) {
+ if(smp[i] != smp[0]) break;
+ }
+ if(i == n) {
+ sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
+ res[0] = smp[0];
+ return sub->obits;
+ }
+
+ /* VERBATIM */
+ if(n < 5) {
+ sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
+ encode_residual_verbatim(res, smp, n);
+ return sub->obits * n;
+ }
+
+ min_order = ctx->options.min_prediction_order;
+ max_order = ctx->options.max_prediction_order;
+ min_porder = ctx->options.min_partition_order;
+ max_porder = ctx->options.max_partition_order;
+ precision = ctx->options.lpc_coeff_precision;
+ omethod = ctx->options.prediction_order_method;
+
+ /* FIXED */
+ if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
+ uint32_t bits[MAX_FIXED_ORDER+1];
+ if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
+ opt_order = 0;
+ bits[0] = UINT32_MAX;
+ for(i=min_order; i<=max_order; i++) {
+ encode_residual_fixed(res, smp, n, i);
+ bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
+ n, i, sub->obits);
+ if(bits[i] < bits[opt_order]) {
+ opt_order = i;
+ }
+ }
+ sub->order = opt_order;
+ sub->type = FLAC_SUBFRAME_FIXED;
+ sub->type_code = sub->type | sub->order;
+ if(sub->order != max_order) {
+ encode_residual_fixed(res, smp, n, sub->order);
+ return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
+ sub->order, sub->obits);
+ }
+ return bits[sub->order];
+ }
+
+ /* LPC */
+ opt_order = lpc_calc_coefs(smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
+
+ if(omethod == ORDER_METHOD_2LEVEL ||
+ omethod == ORDER_METHOD_4LEVEL ||
+ omethod == ORDER_METHOD_8LEVEL) {
+ int levels = 1 << omethod;
+ uint32_t bits[levels];
+ int order;
+ int opt_index = levels-1;
+ opt_order = max_order-1;
+ bits[opt_index] = UINT32_MAX;
+ for(i=levels-1; i>=0; i--) {
+ order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
+ if(order < 0) order = 0;
+ encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
+ bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
+ res, n, order+1, sub->obits, precision);
+ if(bits[i] < bits[opt_index]) {
+ opt_index = i;
+ opt_order = order;
+ }
+ }
+ opt_order++;
+ } else if(omethod == ORDER_METHOD_SEARCH) {
+ // brute-force optimal order search
+ uint32_t bits[MAX_LPC_ORDER];
+ opt_order = 0;
+ bits[0] = UINT32_MAX;
+ for(i=min_order-1; i<max_order; i++) {
+ encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
+ bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
+ res, n, i+1, sub->obits, precision);
+ if(bits[i] < bits[opt_order]) {
+ opt_order = i;
+ }
+ }
+ opt_order++;
+ } else if(omethod == ORDER_METHOD_LOG) {
+ uint32_t bits[MAX_LPC_ORDER];
+ int step;
+
+ opt_order= min_order - 1 + (max_order-min_order)/3;
+ memset(bits, -1, sizeof(bits));
+
+ for(step=16 ;step; step>>=1){
+ int last= opt_order;
+ for(i=last-step; i<=last+step; i+= step){
+ if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
+ continue;
+ encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
+ bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
+ res, n, i+1, sub->obits, precision);
+ if(bits[i] < bits[opt_order])
+ opt_order= i;
+ }
+ }
+ opt_order++;
+ }
+
+ sub->order = opt_order;
+ sub->type = FLAC_SUBFRAME_LPC;
+ sub->type_code = sub->type | (sub->order-1);
+ sub->shift = shift[sub->order-1];
+ for(i=0; i<sub->order; i++) {
+ sub->coefs[i] = coefs[sub->order-1][i];
+ }
+ encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
+ return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
+ sub->obits, precision);
+}
+
+static int encode_residual_v(FlacEncodeContext *ctx, int ch)
+{
+ int i, n;
+ FlacFrame *frame;
+ FlacSubframe *sub;
+ int32_t *res, *smp;
+
+ frame = &ctx->frame;
+ sub = &frame->subframes[ch];
+ res = sub->residual;
+ smp = sub->samples;
+ n = frame->blocksize;
+
+ /* CONSTANT */
+ for(i=1; i<n; i++) {
+ if(smp[i] != smp[0]) break;
+ }
+ if(i == n) {
+ sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
+ res[0] = smp[0];
+ return sub->obits;
+ }
+
+ /* VERBATIM */
+ sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
+ encode_residual_verbatim(res, smp, n);
+ return sub->obits * n;
+}
+