Split bit allocation search into a separate function.
[ffmpeg.git] / libavcodec / ac3enc.c
index c756016..d2f6042 100644 (file)
@@ -37,6 +37,9 @@
 #define MDCT_NBITS 9
 #define MDCT_SAMPLES (1 << MDCT_NBITS)
 
+/** Maximum number of exponent groups. +1 for separate DC exponent. */
+#define AC3_MAX_EXP_GROUPS 85
+
 /** Scale a float value by 2^bits and convert to an integer. */
 #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
 
@@ -90,11 +93,29 @@ typedef struct AC3EncodeContext {
     int coarse_snr_offset;                  ///< coarse SNR offsets                     (csnroffst)
     int fast_gain_code[AC3_MAX_CHANNELS];   ///< fast gain codes (signal-to-mask ratio) (fgaincod)
     int fine_snr_offset[AC3_MAX_CHANNELS];  ///< fine SNR offsets                       (fsnroffst)
+    int frame_bits;                         ///< all frame bits except exponents and mantissas
+    int exponent_bits;                      ///< number of bits used for exponents
 
     /* mantissa encoding */
     int mant1_cnt, mant2_cnt, mant4_cnt;    ///< mantissa counts for bap=1,2,4
+    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
 
     int16_t last_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE]; ///< last 256 samples from previous frame
+    int16_t planar_samples[AC3_MAX_CHANNELS][AC3_BLOCK_SIZE+AC3_FRAME_SIZE];
+    int16_t windowed_samples[AC3_WINDOW_SIZE];
+    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
+    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
+    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
+    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
+    uint8_t num_exp_groups[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
+    uint8_t grouped_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_EXP_GROUPS];
+    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
+    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
+    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
+    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
+    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
+    int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
+    uint16_t qmant[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
 } AC3EncodeContext;
 
 
@@ -106,6 +127,55 @@ static int16_t xsin1[128];
 
 
 /**
+ * Adjust the frame size to make the average bit rate match the target bit rate.
+ * This is only needed for 11025, 22050, and 44100 sample rates.
+ */
+static void adjust_frame_size(AC3EncodeContext *s)
+{
+    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
+        s->bits_written    -= s->bit_rate;
+        s->samples_written -= s->sample_rate;
+    }
+    s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
+    s->bits_written    += s->frame_size * 8;
+    s->samples_written += AC3_FRAME_SIZE;
+}
+
+
+/**
+ * Deinterleave input samples.
+ * Channels are reordered from FFmpeg's default order to AC-3 order.
+ */
+static void deinterleave_input_samples(AC3EncodeContext *s,
+                                       const int16_t *samples)
+{
+    int ch, i;
+
+    /* deinterleave and remap input samples */
+    for (ch = 0; ch < s->channels; ch++) {
+        const int16_t *sptr;
+        int sinc;
+
+        /* copy last 256 samples of previous frame to the start of the current frame */
+        memcpy(&s->planar_samples[ch][0], s->last_samples[ch],
+               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
+
+        /* deinterleave */
+        sinc = s->channels;
+        sptr = samples + s->channel_map[ch];
+        for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
+            s->planar_samples[ch][i] = *sptr;
+            sptr += sinc;
+        }
+
+        /* save last 256 samples for next frame */
+        memcpy(s->last_samples[ch], &s->planar_samples[ch][6* AC3_BLOCK_SIZE],
+               AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
+    }
+}
+
+
+/**
  * Initialize FFT tables.
  * @param ln log2(FFT size)
  */
@@ -279,6 +349,22 @@ static void mdct512(int32_t *out, int16_t *in)
 
 
 /**
+ * Apply KBD window to input samples prior to MDCT.
+ */
+static void apply_window(int16_t *output, const int16_t *input,
+                         const int16_t *window, int n)
+{
+    int i;
+    int n2 = n >> 1;
+
+    for (i = 0; i < n2; i++) {
+        output[i]     = MUL16(input[i],     window[i]) >> 15;
+        output[n-i-1] = MUL16(input[n-i-1], window[i]) >> 15;
+    }
+}
+
+
+/**
  * Calculate the log2() of the maximum absolute value in an array.
  * @param tab input array
  * @param n   number of values in the array
@@ -318,6 +404,77 @@ static void lshift_tab(int16_t *tab, int n, int lshift)
 
 
 /**
+ * Normalize the input samples to use the maximum available precision.
+ * This assumes signed 16-bit input samples. Exponents are reduced by 9 to
+ * match the 24-bit internal precision for MDCT coefficients.
+ *
+ * @return exponent shift
+ */
+static int normalize_samples(AC3EncodeContext *s)
+{
+    int v = 14 - log2_tab(s->windowed_samples, AC3_WINDOW_SIZE);
+    v = FFMAX(0, v);
+    lshift_tab(s->windowed_samples, AC3_WINDOW_SIZE, v);
+    return v - 9;
+}
+
+
+/**
+ * Apply the MDCT to input samples to generate frequency coefficients.
+ * This applies the KBD window and normalizes the input to reduce precision
+ * loss due to fixed-point calculations.
+ */
+static void apply_mdct(AC3EncodeContext *s)
+{
+    int blk, ch;
+
+    for (ch = 0; ch < s->channels; ch++) {
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+            const int16_t *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
+
+            apply_window(s->windowed_samples, input_samples, ff_ac3_window, AC3_WINDOW_SIZE);
+
+            s->exp_shift[blk][ch] = normalize_samples(s);
+
+            mdct512(s->mdct_coef[blk][ch], s->windowed_samples);
+        }
+    }
+}
+
+
+/**
+ * Extract exponents from the MDCT coefficients.
+ * This takes into account the normalization that was done to the input samples
+ * by adjusting the exponents by the exponent shift values.
+ */
+static void extract_exponents(AC3EncodeContext *s)
+{
+    int blk, ch, i;
+
+    /* extract exponents */
+    for (ch = 0; ch < s->channels; ch++) {
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+            /* compute "exponents". We take into account the normalization there */
+            for (i = 0; i < AC3_MAX_COEFS; i++) {
+                int e;
+                int v = abs(s->mdct_coef[blk][ch][i]);
+                if (v == 0)
+                    e = 24;
+                else {
+                    e = 23 - av_log2(v) + s->exp_shift[blk][ch];
+                    if (e >= 24) {
+                        e = 24;
+                        s->mdct_coef[blk][ch][i] = 0;
+                    }
+                }
+                s->exp[blk][ch][i] = e;
+            }
+        }
+    }
+}
+
+
+/**
  * Calculate the sum of absolute differences (SAD) between 2 sets of exponents.
  */
 static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
@@ -340,38 +497,34 @@ static int calc_exp_diff(uint8_t *exp1, uint8_t *exp2, int n)
 /**
  * Calculate exponent strategies for all blocks in a single channel.
  */
-static void compute_exp_strategy_ch(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
-                                    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                                    int ch, int is_lfe)
+static void compute_exp_strategy_ch(uint8_t *exp_strategy, uint8_t **exp)
 {
     int blk, blk1;
     int exp_diff;
 
     /* estimate if the exponent variation & decide if they should be
        reused in the next frame */
-    exp_strategy[0][ch] = EXP_NEW;
+    exp_strategy[0] = EXP_NEW;
     for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
-        exp_diff = calc_exp_diff(exp[blk][ch], exp[blk-1][ch], AC3_MAX_COEFS);
+        exp_diff = calc_exp_diff(exp[blk], exp[blk-1], AC3_MAX_COEFS);
         if (exp_diff > EXP_DIFF_THRESHOLD)
-            exp_strategy[blk][ch] = EXP_NEW;
+            exp_strategy[blk] = EXP_NEW;
         else
-            exp_strategy[blk][ch] = EXP_REUSE;
+            exp_strategy[blk] = EXP_REUSE;
     }
-    if (is_lfe)
-        return;
 
     /* now select the encoding strategy type : if exponents are often
        recoded, we use a coarse encoding */
     blk = 0;
     while (blk < AC3_MAX_BLOCKS) {
         blk1 = blk + 1;
-        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE)
+        while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
             blk1++;
         switch (blk1 - blk) {
-        case 1:  exp_strategy[blk][ch] = EXP_D45; break;
+        case 1:  exp_strategy[blk] = EXP_D45; break;
         case 2:
-        case 3:  exp_strategy[blk][ch] = EXP_D25; break;
-        default: exp_strategy[blk][ch] = EXP_D15; break;
+        case 3:  exp_strategy[blk] = EXP_D25; break;
+        default: exp_strategy[blk] = EXP_D15; break;
         }
         blk = blk1;
     }
@@ -379,6 +532,36 @@ static void compute_exp_strategy_ch(uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX
 
 
 /**
+ * Calculate exponent strategies for all channels.
+ * Array arrangement is reversed to simplify the per-channel calculation.
+ */
+static void compute_exp_strategy(AC3EncodeContext *s)
+{
+    uint8_t *exp1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
+    uint8_t exp_str1[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS];
+    int ch, blk;
+
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+            exp1[ch][blk]     = s->exp[blk][ch];
+            exp_str1[ch][blk] = s->exp_strategy[blk][ch];
+        }
+
+        compute_exp_strategy_ch(exp_str1[ch], exp1[ch]);
+
+        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
+            s->exp_strategy[blk][ch] = exp_str1[ch][blk];
+    }
+    if (s->lfe_on) {
+        ch = s->lfe_channel;
+        s->exp_strategy[0][ch] = EXP_D15;
+        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
+            s->exp_strategy[blk][ch] = EXP_REUSE;
+    }
+}
+
+
+/**
  * Set each encoded exponent in a block to the minimum of itself and the
  * exponent in the same frequency bin of a following block.
  * exp[i] = min(exp[i], exp1[i]
@@ -395,17 +578,18 @@ static void exponent_min(uint8_t exp[AC3_MAX_COEFS], uint8_t exp1[AC3_MAX_COEFS]
 
 /**
  * Update the exponents so that they are the ones the decoder will decode.
- * @return the number of bits used to encode the exponents.
  */
-static int encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
-                                   uint8_t exp[AC3_MAX_COEFS],
-                                   int nb_exps, int exp_strategy)
+static void encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
+                                    uint8_t exp[AC3_MAX_COEFS],
+                                    int nb_exps, int exp_strategy,
+                                    uint8_t *num_exp_groups)
 {
     int group_size, nb_groups, i, j, k, exp_min;
     uint8_t exp1[AC3_MAX_COEFS];
 
     group_size = exp_strategy + (exp_strategy == EXP_D45);
-    nb_groups = ((nb_exps + (group_size * 3) - 4) / (3 * group_size)) * 3;
+    *num_exp_groups = (nb_exps + (group_size * 3) - 4) / (3 * group_size);
+    nb_groups = *num_exp_groups * 3;
 
     /* for each group, compute the minimum exponent */
     exp1[0] = exp[0]; /* DC exponent is handled separately */
@@ -440,8 +624,192 @@ static int encode_exponents_blk_ch(uint8_t encoded_exp[AC3_MAX_COEFS],
             encoded_exp[k+j] = exp1[i];
         k += group_size;
     }
+}
+
+
+/**
+ * Encode exponents from original extracted form to what the decoder will see.
+ * This copies and groups exponents based on exponent strategy and reduces
+ * deltas between adjacent exponent groups so that they can be differentially
+ * encoded.
+ */
+static void encode_exponents(AC3EncodeContext *s)
+{
+    int blk, blk1, blk2, ch;
+
+    for (ch = 0; ch < s->channels; ch++) {
+        /* for the EXP_REUSE case we select the min of the exponents */
+        blk = 0;
+        while (blk < AC3_MAX_BLOCKS) {
+            blk1 = blk + 1;
+            while (blk1 < AC3_MAX_BLOCKS && s->exp_strategy[blk1][ch] == EXP_REUSE) {
+                exponent_min(s->exp[blk][ch], s->exp[blk1][ch], s->nb_coefs[ch]);
+                blk1++;
+            }
+            encode_exponents_blk_ch(s->encoded_exp[blk][ch],
+                                    s->exp[blk][ch], s->nb_coefs[ch],
+                                    s->exp_strategy[blk][ch],
+                                    &s->num_exp_groups[blk][ch]);
+            /* copy encoded exponents for reuse case */
+            for (blk2 = blk+1; blk2 < blk1; blk2++) {
+                memcpy(s->encoded_exp[blk2][ch], s->encoded_exp[blk][ch],
+                       s->nb_coefs[ch] * sizeof(uint8_t));
+            }
+            blk = blk1;
+        }
+    }
+}
+
+
+/**
+ * Group exponents.
+ * 3 delta-encoded exponents are in each 7-bit group. The number of groups
+ * varies depending on exponent strategy and bandwidth.
+ */
+static void group_exponents(AC3EncodeContext *s)
+{
+    int blk, ch, i;
+    int group_size, bit_count;
+    uint8_t *p;
+    int delta0, delta1, delta2;
+    int exp0, exp1;
+
+    bit_count = 0;
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        for (ch = 0; ch < s->channels; ch++) {
+            if (s->exp_strategy[blk][ch] == EXP_REUSE) {
+                s->num_exp_groups[blk][ch] = 0;
+                continue;
+            }
+            group_size = s->exp_strategy[blk][ch] + (s->exp_strategy[blk][ch] == EXP_D45);
+            bit_count += 4 + (s->num_exp_groups[blk][ch] * 7);
+            p = s->encoded_exp[blk][ch];
+
+            /* DC exponent */
+            exp1 = *p++;
+            s->grouped_exp[blk][ch][0] = exp1;
+
+            /* remaining exponents are delta encoded */
+            for (i = 1; i <= s->num_exp_groups[blk][ch]; i++) {
+                /* merge three delta in one code */
+                exp0   = exp1;
+                exp1   = p[0];
+                p     += group_size;
+                delta0 = exp1 - exp0 + 2;
+
+                exp0   = exp1;
+                exp1   = p[0];
+                p     += group_size;
+                delta1 = exp1 - exp0 + 2;
+
+                exp0   = exp1;
+                exp1   = p[0];
+                p     += group_size;
+                delta2 = exp1 - exp0 + 2;
+
+                s->grouped_exp[blk][ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
+            }
+        }
+    }
+
+    s->exponent_bits = bit_count;
+}
+
+
+/**
+ * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
+ * Extract exponents from MDCT coefficients, calculate exponent strategies,
+ * and encode final exponents.
+ */
+static void process_exponents(AC3EncodeContext *s)
+{
+    extract_exponents(s);
+
+    compute_exp_strategy(s);
+
+    encode_exponents(s);
+
+    group_exponents(s);
+}
+
+
+/**
+ * Initialize bit allocation.
+ * Set default parameter codes and calculate parameter values.
+ */
+static void bit_alloc_init(AC3EncodeContext *s)
+{
+    int ch;
+
+    /* init default parameters */
+    s->slow_decay_code = 2;
+    s->fast_decay_code = 1;
+    s->slow_gain_code  = 1;
+    s->db_per_bit_code = 2;
+    s->floor_code      = 4;
+    for (ch = 0; ch < s->channels; ch++)
+        s->fast_gain_code[ch] = 4;
+
+    /* initial snr offset */
+    s->coarse_snr_offset = 40;
+
+    /* compute real values */
+    /* currently none of these values change during encoding, so we can just
+       set them once at initialization */
+    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
+    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
+    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
+    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
+    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
+}
+
+
+/**
+ * Count the bits used to encode the frame, minus exponents and mantissas.
+ */
+static void count_frame_bits(AC3EncodeContext *s)
+{
+    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
+    int blk, ch;
+    int frame_bits;
+
+    /* header size */
+    frame_bits = 65;
+    frame_bits += frame_bits_inc[s->channel_mode];
+
+    /* audio blocks */
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
+        if (s->channel_mode == AC3_CHMODE_STEREO) {
+            frame_bits++; /* rematstr */
+            if (!blk)
+                frame_bits += 4;
+        }
+        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
+        if (s->lfe_on)
+            frame_bits++; /* lfeexpstr */
+        for (ch = 0; ch < s->fbw_channels; ch++) {
+            if (s->exp_strategy[blk][ch] != EXP_REUSE)
+                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
+        }
+        frame_bits++; /* baie */
+        frame_bits++; /* snr */
+        frame_bits += 2; /* delta / skip */
+    }
+    frame_bits++; /* cplinu for block 0 */
+    /* bit alloc info */
+    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
+    /* csnroffset[6] */
+    /* (fsnoffset[4] + fgaincod[4]) * c */
+    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
+
+    /* auxdatae, crcrsv */
+    frame_bits += 2;
+
+    /* CRC */
+    frame_bits += 16;
 
-    return 4 + (nb_groups / 3) * 7;
+    s->frame_bits = frame_bits;
 }
 
 
@@ -502,30 +870,25 @@ static int compute_mantissa_size(AC3EncodeContext *s, uint8_t *m, int nb_coefs)
  * Calculate masking curve based on the final exponents.
  * Also calculate the power spectral densities to use in future calculations.
  */
-static void bit_alloc_masking(AC3EncodeContext *s,
-                              uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                              uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
-                              int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                              int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS])
+static void bit_alloc_masking(AC3EncodeContext *s)
 {
     int blk, ch;
-    int16_t band_psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
 
     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
         for (ch = 0; ch < s->channels; ch++) {
-            if(exp_strategy[blk][ch] == EXP_REUSE) {
-                memcpy(psd[blk][ch],  psd[blk-1][ch],  AC3_MAX_COEFS*sizeof(psd[0][0][0]));
-                memcpy(mask[blk][ch], mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(mask[0][0][0]));
+            if (s->exp_strategy[blk][ch] == EXP_REUSE) {
+                memcpy(s->psd[blk][ch],  s->psd[blk-1][ch],  AC3_MAX_COEFS*sizeof(s->psd[0][0][0]));
+                memcpy(s->mask[blk][ch], s->mask[blk-1][ch], AC3_CRITICAL_BANDS*sizeof(s->mask[0][0][0]));
             } else {
-                ff_ac3_bit_alloc_calc_psd(encoded_exp[blk][ch], 0,
+                ff_ac3_bit_alloc_calc_psd(s->encoded_exp[blk][ch], 0,
                                           s->nb_coefs[ch],
-                                          psd[blk][ch], band_psd[blk][ch]);
-                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, band_psd[blk][ch],
+                                          s->psd[blk][ch], s->band_psd[blk][ch]);
+                ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, s->band_psd[blk][ch],
                                            0, s->nb_coefs[ch],
                                            ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
                                            ch == s->lfe_channel,
                                            DBA_NONE, 0, NULL, NULL, NULL,
-                                           mask[blk][ch]);
+                                           s->mask[blk][ch]);
             }
         }
     }
@@ -536,37 +899,85 @@ static void bit_alloc_masking(AC3EncodeContext *s,
  * Run the bit allocation with a given SNR offset.
  * This calculates the bit allocation pointers that will be used to determine
  * the quantization of each mantissa.
- * @return the number of remaining bits (positive or negative) if the given
- *         SNR offset is used to quantize the mantissas.
+ * @return the number of bits needed for mantissas if the given SNR offset is
+ *         is used.
  */
 static int bit_alloc(AC3EncodeContext *s,
-                     int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS],
-                     int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
                      uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                     int frame_bits, int coarse_snr_offset, int fine_snr_offset)
+                     int snr_offset)
 {
     int blk, ch;
-    int snr_offset;
+    int mantissa_bits;
 
-    snr_offset = (((coarse_snr_offset - 15) << 4) + fine_snr_offset) << 2;
+    snr_offset = (snr_offset - 240) << 2;
 
+    mantissa_bits = 0;
     for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
         s->mant1_cnt = 0;
         s->mant2_cnt = 0;
         s->mant4_cnt = 0;
         for (ch = 0; ch < s->channels; ch++) {
-            ff_ac3_bit_alloc_calc_bap(mask[blk][ch], psd[blk][ch], 0,
+            ff_ac3_bit_alloc_calc_bap(s->mask[blk][ch], s->psd[blk][ch], 0,
                                       s->nb_coefs[ch], snr_offset,
                                       s->bit_alloc.floor, ff_ac3_bap_tab,
                                       bap[blk][ch]);
-            frame_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
+            mantissa_bits += compute_mantissa_size(s, bap[blk][ch], s->nb_coefs[ch]);
         }
     }
-    return 8 * s->frame_size - frame_bits;
+    return mantissa_bits;
 }
 
 
-#define SNR_INC1 4
+/**
+ * Constant bitrate bit allocation search.
+ * Find the largest SNR offset that will allow data to fit in the frame.
+ */
+static int cbr_bit_allocation(AC3EncodeContext *s)
+{
+    int ch;
+    int bits_left;
+    int snr_offset;
+
+    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
+
+    snr_offset = s->coarse_snr_offset << 4;
+
+    while (snr_offset >= 0 &&
+           bit_alloc(s, s->bap, snr_offset) > bits_left) {
+        snr_offset -= 64;
+    }
+    if (snr_offset < 0) {
+        return AVERROR(EINVAL);
+    }
+
+    while (snr_offset + 64 <= 1023 &&
+           bit_alloc(s, s->bap1, snr_offset + 64) <= bits_left) {
+        snr_offset += 64;
+        memcpy(s->bap, s->bap1, sizeof(s->bap1));
+    }
+    while (snr_offset + 16 <= 1023 &&
+           bit_alloc(s, s->bap1, snr_offset + 16) <= bits_left) {
+        snr_offset += 16;
+        memcpy(s->bap, s->bap1, sizeof(s->bap1));
+    }
+    while (snr_offset + 4 <= 1023 &&
+           bit_alloc(s, s->bap1, snr_offset + 4) <= bits_left) {
+        snr_offset += 4;
+        memcpy(s->bap, s->bap1, sizeof(s->bap1));
+    }
+    while (snr_offset + 1 <= 1023 &&
+           bit_alloc(s, s->bap1, snr_offset + 1) <= bits_left) {
+        snr_offset++;
+        memcpy(s->bap, s->bap1, sizeof(s->bap1));
+    }
+
+    s->coarse_snr_offset = snr_offset >> 4;
+    for (ch = 0; ch < s->channels; ch++)
+        s->fine_snr_offset[ch] = snr_offset & 0xF;
+
+    return 0;
+}
+
 
 /**
  * Perform bit allocation search.
@@ -574,151 +985,15 @@ static int bit_alloc(AC3EncodeContext *s,
  * frame size.  Output is the SNR offset and a set of bit allocation pointers
  * used to quantize the mantissas.
  */
-static int compute_bit_allocation(AC3EncodeContext *s,
-                                  uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                                  uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                                  uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS],
-                                  int frame_bits)
+static int compute_bit_allocation(AC3EncodeContext *s)
 {
-    int blk, ch;
-    int coarse_snr_offset, fine_snr_offset;
-    uint8_t bap1[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
-    int16_t psd[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
-    int16_t mask[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_CRITICAL_BANDS];
-    static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
+    /* count frame bits other than exponents and mantissas */
+    count_frame_bits(s);
 
-    /* init default parameters */
-    s->slow_decay_code = 2;
-    s->fast_decay_code = 1;
-    s->slow_gain_code  = 1;
-    s->db_per_bit_code = 2;
-    s->floor_code      = 4;
-    for (ch = 0; ch < s->channels; ch++)
-        s->fast_gain_code[ch] = 4;
+    /* calculate psd and masking curve before doing bit allocation */
+    bit_alloc_masking(s);
 
-    /* compute real values */
-    s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
-    s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
-    s->bit_alloc.slow_gain  = ff_ac3_slow_gain_tab[s->slow_gain_code];
-    s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
-    s->bit_alloc.floor      = ff_ac3_floor_tab[s->floor_code];
-
-    /* header size */
-    frame_bits += 65;
-    // if (s->channel_mode == 2)
-    //    frame_bits += 2;
-    frame_bits += frame_bits_inc[s->channel_mode];
-
-    /* audio blocks */
-    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
-        frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
-        if (s->channel_mode == AC3_CHMODE_STEREO) {
-            frame_bits++; /* rematstr */
-            if (!blk)
-                frame_bits += 4;
-        }
-        frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
-        if (s->lfe_on)
-            frame_bits++; /* lfeexpstr */
-        for (ch = 0; ch < s->fbw_channels; ch++) {
-            if (exp_strategy[blk][ch] != EXP_REUSE)
-                frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
-        }
-        frame_bits++; /* baie */
-        frame_bits++; /* snr */
-        frame_bits += 2; /* delta / skip */
-    }
-    frame_bits++; /* cplinu for block 0 */
-    /* bit alloc info */
-    /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
-    /* csnroffset[6] */
-    /* (fsnoffset[4] + fgaincod[4]) * c */
-    frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
-
-    /* auxdatae, crcrsv */
-    frame_bits += 2;
-
-    /* CRC */
-    frame_bits += 16;
-
-    /* calculate psd and masking curve before doing bit allocation */
-    bit_alloc_masking(s, encoded_exp, exp_strategy, psd, mask);
-
-    /* now the big work begins : do the bit allocation. Modify the snr
-       offset until we can pack everything in the requested frame size */
-
-    coarse_snr_offset = s->coarse_snr_offset;
-    while (coarse_snr_offset >= 0 &&
-           bit_alloc(s, mask, psd, bap, frame_bits, coarse_snr_offset, 0) < 0)
-        coarse_snr_offset -= SNR_INC1;
-    if (coarse_snr_offset < 0) {
-        av_log(NULL, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
-        return -1;
-    }
-    while (coarse_snr_offset + SNR_INC1 <= 63 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits,
-                     coarse_snr_offset + SNR_INC1, 0) >= 0) {
-        coarse_snr_offset += SNR_INC1;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-    while (coarse_snr_offset + 1 <= 63 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits, coarse_snr_offset + 1, 0) >= 0) {
-        coarse_snr_offset++;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-
-    fine_snr_offset = 0;
-    while (fine_snr_offset + SNR_INC1 <= 15 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits,
-                     coarse_snr_offset, fine_snr_offset + SNR_INC1) >= 0) {
-        fine_snr_offset += SNR_INC1;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-    while (fine_snr_offset + 1 <= 15 &&
-           bit_alloc(s, mask, psd, bap1, frame_bits,
-                     coarse_snr_offset, fine_snr_offset + 1) >= 0) {
-        fine_snr_offset++;
-        memcpy(bap, bap1, sizeof(bap1));
-    }
-
-    s->coarse_snr_offset = coarse_snr_offset;
-    for (ch = 0; ch < s->channels; ch++)
-        s->fine_snr_offset[ch] = fine_snr_offset;
-
-    return 0;
-}
-
-
-/**
- * Write the AC-3 frame header to the output bitstream.
- */
-static void output_frame_header(AC3EncodeContext *s, unsigned char *frame)
-{
-    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
-
-    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
-    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
-    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
-    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
-    put_bits(&s->pb, 5,  s->bitstream_id);
-    put_bits(&s->pb, 3,  s->bitstream_mode);
-    put_bits(&s->pb, 3,  s->channel_mode);
-    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
-        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
-    if (s->channel_mode & 0x04)
-        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
-    if (s->channel_mode == AC3_CHMODE_STEREO)
-        put_bits(&s->pb, 2, 0);     /* surround not indicated */
-    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
-    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
-    put_bits(&s->pb, 1, 0);         /* no compression control word */
-    put_bits(&s->pb, 1, 0);         /* no lang code */
-    put_bits(&s->pb, 1, 0);         /* no audio production info */
-    put_bits(&s->pb, 1, 0);         /* no copyright */
-    put_bits(&s->pb, 1, 1);         /* original bitstream */
-    put_bits(&s->pb, 1, 0);         /* no time code 1 */
-    put_bits(&s->pb, 1, 0);         /* no time code 2 */
-    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
+    return cbr_bit_allocation(s);
 }
 
 
@@ -766,23 +1041,159 @@ static inline int asym_quant(int c, int e, int qbits)
 
 
 /**
+ * Quantize a set of mantissas for a single channel in a single block.
+ */
+static void quantize_mantissas_blk_ch(AC3EncodeContext *s,
+                                      int32_t *mdct_coef, int8_t exp_shift,
+                                      uint8_t *encoded_exp, uint8_t *bap,
+                                      uint16_t *qmant, int n)
+{
+    int i;
+
+    for (i = 0; i < n; i++) {
+        int v;
+        int c = mdct_coef[i];
+        int e = encoded_exp[i] - exp_shift;
+        int b = bap[i];
+        switch (b) {
+        case 0:
+            v = 0;
+            break;
+        case 1:
+            v = sym_quant(c, e, 3);
+            switch (s->mant1_cnt) {
+            case 0:
+                s->qmant1_ptr = &qmant[i];
+                v = 9 * v;
+                s->mant1_cnt = 1;
+                break;
+            case 1:
+                *s->qmant1_ptr += 3 * v;
+                s->mant1_cnt = 2;
+                v = 128;
+                break;
+            default:
+                *s->qmant1_ptr += v;
+                s->mant1_cnt = 0;
+                v = 128;
+                break;
+            }
+            break;
+        case 2:
+            v = sym_quant(c, e, 5);
+            switch (s->mant2_cnt) {
+            case 0:
+                s->qmant2_ptr = &qmant[i];
+                v = 25 * v;
+                s->mant2_cnt = 1;
+                break;
+            case 1:
+                *s->qmant2_ptr += 5 * v;
+                s->mant2_cnt = 2;
+                v = 128;
+                break;
+            default:
+                *s->qmant2_ptr += v;
+                s->mant2_cnt = 0;
+                v = 128;
+                break;
+            }
+            break;
+        case 3:
+            v = sym_quant(c, e, 7);
+            break;
+        case 4:
+            v = sym_quant(c, e, 11);
+            switch (s->mant4_cnt) {
+            case 0:
+                s->qmant4_ptr = &qmant[i];
+                v = 11 * v;
+                s->mant4_cnt = 1;
+                break;
+            default:
+                *s->qmant4_ptr += v;
+                s->mant4_cnt = 0;
+                v = 128;
+                break;
+            }
+            break;
+        case 5:
+            v = sym_quant(c, e, 15);
+            break;
+        case 14:
+            v = asym_quant(c, e, 14);
+            break;
+        case 15:
+            v = asym_quant(c, e, 16);
+            break;
+        default:
+            v = asym_quant(c, e, b - 1);
+            break;
+        }
+        qmant[i] = v;
+    }
+}
+
+
+/**
+ * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
+ */
+static void quantize_mantissas(AC3EncodeContext *s)
+{
+    int blk, ch;
+
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        s->mant1_cnt  = s->mant2_cnt  = s->mant4_cnt  = 0;
+        s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
+
+        for (ch = 0; ch < s->channels; ch++) {
+            quantize_mantissas_blk_ch(s, s->mdct_coef[blk][ch], s->exp_shift[blk][ch],
+                                      s->encoded_exp[blk][ch], s->bap[blk][ch],
+                                      s->qmant[blk][ch], s->nb_coefs[ch]);
+        }
+    }
+}
+
+
+/**
+ * Write the AC-3 frame header to the output bitstream.
+ */
+static void output_frame_header(AC3EncodeContext *s)
+{
+    put_bits(&s->pb, 16, 0x0b77);   /* frame header */
+    put_bits(&s->pb, 16, 0);        /* crc1: will be filled later */
+    put_bits(&s->pb, 2,  s->bit_alloc.sr_code);
+    put_bits(&s->pb, 6,  s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
+    put_bits(&s->pb, 5,  s->bitstream_id);
+    put_bits(&s->pb, 3,  s->bitstream_mode);
+    put_bits(&s->pb, 3,  s->channel_mode);
+    if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
+        put_bits(&s->pb, 2, 1);     /* XXX -4.5 dB */
+    if (s->channel_mode & 0x04)
+        put_bits(&s->pb, 2, 1);     /* XXX -6 dB */
+    if (s->channel_mode == AC3_CHMODE_STEREO)
+        put_bits(&s->pb, 2, 0);     /* surround not indicated */
+    put_bits(&s->pb, 1, s->lfe_on); /* LFE */
+    put_bits(&s->pb, 5, 31);        /* dialog norm: -31 db */
+    put_bits(&s->pb, 1, 0);         /* no compression control word */
+    put_bits(&s->pb, 1, 0);         /* no lang code */
+    put_bits(&s->pb, 1, 0);         /* no audio production info */
+    put_bits(&s->pb, 1, 0);         /* no copyright */
+    put_bits(&s->pb, 1, 1);         /* original bitstream */
+    put_bits(&s->pb, 1, 0);         /* no time code 1 */
+    put_bits(&s->pb, 1, 0);         /* no time code 2 */
+    put_bits(&s->pb, 1, 0);         /* no additional bit stream info */
+}
+
+
+/**
  * Write one audio block to the output bitstream.
  */
 static void output_audio_block(AC3EncodeContext *s,
-                               uint8_t exp_strategy[AC3_MAX_CHANNELS],
-                               uint8_t encoded_exp[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                               uint8_t bap[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                               int32_t mdct_coef[AC3_MAX_CHANNELS][AC3_MAX_COEFS],
-                               int8_t exp_shift[AC3_MAX_CHANNELS],
                                int block_num)
 {
-    int ch, nb_groups, group_size, i, baie, rbnd;
-    uint8_t *p;
-    uint16_t qmant[AC3_MAX_CHANNELS][AC3_MAX_COEFS];
-    int exp0, exp1;
-    int mant1_cnt, mant2_cnt, mant4_cnt;
-    uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr;
-    int delta0, delta1, delta2;
+    int ch, i, baie, rbnd;
 
     for (ch = 0; ch < s->fbw_channels; ch++)
         put_bits(&s->pb, 1, 0); /* no block switching */
@@ -812,49 +1223,28 @@ static void output_audio_block(AC3EncodeContext *s,
 
     /* exponent strategy */
     for (ch = 0; ch < s->fbw_channels; ch++)
-        put_bits(&s->pb, 2, exp_strategy[ch]);
+        put_bits(&s->pb, 2, s->exp_strategy[block_num][ch]);
 
     if (s->lfe_on)
-        put_bits(&s->pb, 1, exp_strategy[s->lfe_channel]);
+        put_bits(&s->pb, 1, s->exp_strategy[block_num][s->lfe_channel]);
 
     /* bandwidth */
     for (ch = 0; ch < s->fbw_channels; ch++) {
-        if (exp_strategy[ch] != EXP_REUSE)
+        if (s->exp_strategy[block_num][ch] != EXP_REUSE)
             put_bits(&s->pb, 6, s->bandwidth_code[ch]);
     }
 
     /* exponents */
     for (ch = 0; ch < s->channels; ch++) {
-        if (exp_strategy[ch] == EXP_REUSE)
+        if (s->exp_strategy[block_num][ch] == EXP_REUSE)
             continue;
-        group_size = exp_strategy[ch] + (exp_strategy[ch] == EXP_D45);
-        nb_groups = (s->nb_coefs[ch] + (group_size * 3) - 4) / (3 * group_size);
-        p = encoded_exp[ch];
 
         /* first exponent */
-        exp1 = *p++;
-        put_bits(&s->pb, 4, exp1);
-
-        /* next ones are delta encoded */
-        for (i = 0; i < nb_groups; i++) {
-            /* merge three delta in one code */
-            exp0   = exp1;
-            exp1   = p[0];
-            p     += group_size;
-            delta0 = exp1 - exp0 + 2;
-
-            exp0   = exp1;
-            exp1   = p[0];
-            p     += group_size;
-            delta1 = exp1 - exp0 + 2;
-
-            exp0   = exp1;
-            exp1   = p[0];
-            p     += group_size;
-            delta2 = exp1 - exp0 + 2;
-
-            put_bits(&s->pb, 7, ((delta0 * 5 + delta1) * 5) + delta2);
-        }
+        put_bits(&s->pb, 4, s->grouped_exp[block_num][ch][0]);
+
+        /* next ones are delta-encoded and grouped */
+        for (i = 1; i <= s->num_exp_groups[block_num][ch]; i++)
+            put_bits(&s->pb, 7, s->grouped_exp[block_num][ch][i]);
 
         if (ch != s->lfe_channel)
             put_bits(&s->pb, 2, 0); /* no gain range info */
@@ -884,107 +1274,13 @@ static void output_audio_block(AC3EncodeContext *s,
     put_bits(&s->pb, 1, 0); /* no delta bit allocation */
     put_bits(&s->pb, 1, 0); /* no data to skip */
 
-    /* mantissa encoding : we use two passes to handle the grouping. A
-       one pass method may be faster, but it would necessitate to
-       modify the output stream. */
-
-    /* first pass: quantize */
-    mant1_cnt = mant2_cnt = mant4_cnt = 0;
-    qmant1_ptr = qmant2_ptr = qmant4_ptr = NULL;
-
-    for (ch = 0; ch < s->channels; ch++) {
-        int b, c, e, v;
-
-        for (i = 0; i < s->nb_coefs[ch]; i++) {
-            c = mdct_coef[ch][i];
-            e = encoded_exp[ch][i] - exp_shift[ch];
-            b = bap[ch][i];
-            switch (b) {
-            case 0:
-                v = 0;
-                break;
-            case 1:
-                v = sym_quant(c, e, 3);
-                switch (mant1_cnt) {
-                case 0:
-                    qmant1_ptr = &qmant[ch][i];
-                    v = 9 * v;
-                    mant1_cnt = 1;
-                    break;
-                case 1:
-                    *qmant1_ptr += 3 * v;
-                    mant1_cnt = 2;
-                    v = 128;
-                    break;
-                default:
-                    *qmant1_ptr += v;
-                    mant1_cnt = 0;
-                    v = 128;
-                    break;
-                }
-                break;
-            case 2:
-                v = sym_quant(c, e, 5);
-                switch (mant2_cnt) {
-                case 0:
-                    qmant2_ptr = &qmant[ch][i];
-                    v = 25 * v;
-                    mant2_cnt = 1;
-                    break;
-                case 1:
-                    *qmant2_ptr += 5 * v;
-                    mant2_cnt = 2;
-                    v = 128;
-                    break;
-                default:
-                    *qmant2_ptr += v;
-                    mant2_cnt = 0;
-                    v = 128;
-                    break;
-                }
-                break;
-            case 3:
-                v = sym_quant(c, e, 7);
-                break;
-            case 4:
-                v = sym_quant(c, e, 11);
-                switch (mant4_cnt) {
-                case 0:
-                    qmant4_ptr = &qmant[ch][i];
-                    v = 11 * v;
-                    mant4_cnt = 1;
-                    break;
-                default:
-                    *qmant4_ptr += v;
-                    mant4_cnt = 0;
-                    v = 128;
-                    break;
-                }
-                break;
-            case 5:
-                v = sym_quant(c, e, 15);
-                break;
-            case 14:
-                v = asym_quant(c, e, 14);
-                break;
-            case 15:
-                v = asym_quant(c, e, 16);
-                break;
-            default:
-                v = asym_quant(c, e, b - 1);
-                break;
-            }
-            qmant[ch][i] = v;
-        }
-    }
-
-    /* second pass : output the values */
+    /* mantissa encoding */
     for (ch = 0; ch < s->channels; ch++) {
         int b, q;
 
         for (i = 0; i < s->nb_coefs[ch]; i++) {
-            q = qmant[ch][i];
-            b = bap[ch][i];
+            q = s->qmant[block_num][ch][i];
+            b = s->bap[block_num][ch][i];
             switch (b) {
             case 0:                                         break;
             case 1: if (q != 128) put_bits(&s->pb,   5, q); break;
@@ -1073,6 +1369,26 @@ static void output_frame_end(AC3EncodeContext *s)
 
 
 /**
+ * Write the frame to the output bitstream.
+ */
+static void output_frame(AC3EncodeContext *s,
+                         unsigned char *frame)
+{
+    int blk;
+
+    init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
+
+    output_frame_header(s);
+
+    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
+        output_audio_block(s, blk);
+    }
+
+    output_frame_end(s);
+}
+
+
+/**
  * Encode a single AC-3 frame.
  */
 static int ac3_encode_frame(AVCodecContext *avctx,
@@ -1080,113 +1396,26 @@ static int ac3_encode_frame(AVCodecContext *avctx,
 {
     AC3EncodeContext *s = avctx->priv_data;
     const int16_t *samples = data;
-    int v;
-    int blk, blk1, blk2, ch, i;
-    int16_t input_samples[AC3_WINDOW_SIZE];
-    int32_t mdct_coef[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
-    uint8_t exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
-    uint8_t exp_strategy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
-    uint8_t encoded_exp[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
-    uint8_t bap[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][AC3_MAX_COEFS];
-    int8_t exp_shift[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS];
-    int frame_bits;
+    int ret;
 
-    frame_bits = 0;
-    for (ch = 0; ch < s->channels; ch++) {
-        int ich = s->channel_map[ch];
-        /* fixed mdct to the six sub blocks & exponent computation */
-        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
-            const int16_t *sptr;
-            int sinc;
-
-            /* compute input samples */
-            memcpy(input_samples, s->last_samples[ich], AC3_BLOCK_SIZE * sizeof(int16_t));
-            sinc = s->channels;
-            sptr = samples + (sinc * AC3_BLOCK_SIZE * blk) + ich;
-            for (i = 0; i < AC3_BLOCK_SIZE; i++) {
-                v = *sptr;
-                input_samples[i + AC3_BLOCK_SIZE] = v;
-                s->last_samples[ich][i] = v;
-                sptr += sinc;
-            }
+    if (s->bit_alloc.sr_code == 1)
+        adjust_frame_size(s);
 
-            /* apply the MDCT window */
-            for (i = 0; i < AC3_BLOCK_SIZE; i++) {
-                input_samples[i]                   = MUL16(input_samples[i],
-                                                           ff_ac3_window[i]) >> 15;
-                input_samples[AC3_WINDOW_SIZE-i-1] = MUL16(input_samples[AC3_WINDOW_SIZE-i-1],
-                                                           ff_ac3_window[i]) >> 15;
-            }
+    deinterleave_input_samples(s, samples);
 
-            /* Normalize the samples to use the maximum available precision */
-            v = 14 - log2_tab(input_samples, AC3_WINDOW_SIZE);
-            if (v < 0)
-                v = 0;
-            exp_shift[blk][ch] = v - 9;
-            lshift_tab(input_samples, AC3_WINDOW_SIZE, v);
+    apply_mdct(s);
 
-            /* do the MDCT */
-            mdct512(mdct_coef[blk][ch], input_samples);
+    process_exponents(s);
 
-            /* compute "exponents". We take into account the normalization there */
-            for (i = 0; i < AC3_MAX_COEFS; i++) {
-                int e;
-                v = abs(mdct_coef[blk][ch][i]);
-                if (v == 0)
-                    e = 24;
-                else {
-                    e = 23 - av_log2(v) + exp_shift[blk][ch];
-                    if (e >= 24) {
-                        e = 24;
-                        mdct_coef[blk][ch][i] = 0;
-                    }
-                }
-                exp[blk][ch][i] = e;
-            }
-        }
-
-        compute_exp_strategy_ch(exp_strategy, exp, ch, ch == s->lfe_channel);
-
-        /* compute the exponents as the decoder will see them. The
-           EXP_REUSE case must be handled carefully : we select the
-           min of the exponents */
-        blk = 0;
-        while (blk < AC3_MAX_BLOCKS) {
-            blk1 = blk + 1;
-            while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1][ch] == EXP_REUSE) {
-                exponent_min(exp[blk][ch], exp[blk1][ch], s->nb_coefs[ch]);
-                blk1++;
-            }
-            frame_bits += encode_exponents_blk_ch(encoded_exp[blk][ch],
-                                                  exp[blk][ch], s->nb_coefs[ch],
-                                                  exp_strategy[blk][ch]);
-            /* copy encoded exponents for reuse case */
-            for (blk2 = blk+1; blk2 < blk1; blk2++) {
-                memcpy(encoded_exp[blk2][ch], encoded_exp[blk][ch],
-                       s->nb_coefs[ch] * sizeof(uint8_t));
-            }
-            blk = blk1;
-        }
+    ret = compute_bit_allocation(s);
+    if (ret) {
+        av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
+        return ret;
     }
 
-    /* adjust for fractional frame sizes */
-    while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
-        s->bits_written    -= s->bit_rate;
-        s->samples_written -= s->sample_rate;
-    }
-    s->frame_size = s->frame_size_min + 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
-    s->bits_written    += s->frame_size * 8;
-    s->samples_written += AC3_FRAME_SIZE;
-
-    compute_bit_allocation(s, bap, encoded_exp, exp_strategy, frame_bits);
-    /* everything is known... let's output the frame */
-    output_frame_header(s, frame);
+    quantize_mantissas(s);
 
-    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
-        output_audio_block(s, exp_strategy[blk], encoded_exp[blk],
-                           bap[blk], mdct_coef[blk], exp_shift[blk], blk);
-    }
-    output_frame_end(s);
+    output_frame(s, frame);
 
     return s->frame_size;
 }
@@ -1211,14 +1440,14 @@ static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
     int ch_layout;
 
     if (channels < 1 || channels > AC3_MAX_CHANNELS)
-        return -1;
+        return AVERROR(EINVAL);
     if ((uint64_t)*channel_layout > 0x7FF)
-        return -1;
+        return AVERROR(EINVAL);
     ch_layout = *channel_layout;
     if (!ch_layout)
         ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
     if (av_get_channel_layout_nb_channels(ch_layout) != channels)
-        return -1;
+        return AVERROR(EINVAL);
 
     s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);
     s->channels     = channels;
@@ -1238,7 +1467,7 @@ static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
     case AV_CH_LAYOUT_5POINT0:
     case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;
     default:
-        return -1;
+        return AVERROR(EINVAL);
     }
 
     s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
@@ -1252,39 +1481,42 @@ static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
 
 static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
 {
-    int i;
+    int i, ret;
 
+    /* validate channel layout */
     if (!avctx->channel_layout) {
         av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
                                       "encoder will guess the layout, but it "
                                       "might be incorrect.\n");
     }
-    if (set_channel_info(s, avctx->channels, &avctx->channel_layout)) {
+    ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
+    if (ret) {
         av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
-        return -1;
+        return ret;
     }
 
-    /* frequency */
+    /* validate sample rate */
     for (i = 0; i < 9; i++) {
         if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
             break;
     }
     if (i == 9) {
-        return -1;
+        av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
+        return AVERROR(EINVAL);
     }
     s->sample_rate        = avctx->sample_rate;
     s->bit_alloc.sr_shift = i % 3;
     s->bit_alloc.sr_code  = i / 3;
-    s->bitstream_id       = 8 + s->bit_alloc.sr_shift;
-    s->bitstream_mode     = 0; /* complete main audio service */
 
-    /* bitrate & frame size */
+    /* validate bit rate */
     for (i = 0; i < 19; i++) {
         if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
             break;
     }
-    if (i == 19)
-        return -1;
+    if (i == 19) {
+        av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
+        return AVERROR(EINVAL);
+    }
     s->bit_rate        = avctx->bit_rate;
     s->frame_size_code = i << 1;
 
@@ -1293,12 +1525,44 @@ static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
 
 
 /**
+ * Set bandwidth for all channels.
+ * The user can optionally supply a cutoff frequency. Otherwise an appropriate
+ * default value will be used.
+ */
+static av_cold void set_bandwidth(AC3EncodeContext *s, int cutoff)
+{
+    int ch, bw_code;
+
+    if (cutoff) {
+        /* calculate bandwidth based on user-specified cutoff frequency */
+        int fbw_coeffs;
+        cutoff         = av_clip(cutoff, 1, s->sample_rate >> 1);
+        fbw_coeffs     = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
+        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
+    } else {
+        /* use default bandwidth setting */
+        /* XXX: should compute the bandwidth according to the frame
+           size, so that we avoid annoying high frequency artifacts */
+        bw_code = 50;
+    }
+
+    /* set number of coefficients for each channel */
+    for (ch = 0; ch < s->fbw_channels; ch++) {
+        s->bandwidth_code[ch] = bw_code;
+        s->nb_coefs[ch]       = bw_code * 3 + 73;
+    }
+    if (s->lfe_on)
+        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
+}
+
+
+/**
  * Initialize the encoder.
  */
 static av_cold int ac3_encode_init(AVCodecContext *avctx)
 {
     AC3EncodeContext *s = avctx->priv_data;
-    int ch, bw_code, ret;
+    int ret;
 
     avctx->frame_size = AC3_FRAME_SIZE;
 
@@ -1308,33 +1572,17 @@ static av_cold int ac3_encode_init(AVCodecContext *avctx)
     if (ret)
         return ret;
 
+    s->bitstream_id   = 8 + s->bit_alloc.sr_shift;
+    s->bitstream_mode = 0; /* complete main audio service */
+
     s->frame_size_min  = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
     s->bits_written    = 0;
     s->samples_written = 0;
     s->frame_size      = s->frame_size_min;
 
-    /* set bandwidth */
-    if (avctx->cutoff) {
-        /* calculate bandwidth based on user-specified cutoff frequency */
-        int cutoff     = av_clip(avctx->cutoff, 1, s->sample_rate >> 1);
-        int fbw_coeffs = cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
-        bw_code        = av_clip((fbw_coeffs - 73) / 3, 0, 60);
-    } else {
-        /* use default bandwidth setting */
-        /* XXX: should compute the bandwidth according to the frame
-           size, so that we avoid annoying high frequency artifacts */
-        bw_code = 50;
-    }
-    for (ch = 0; ch < s->fbw_channels; ch++) {
-        /* bandwidth for each channel */
-        s->bandwidth_code[ch] = bw_code;
-        s->nb_coefs[ch]       = bw_code * 3 + 73;
-    }
-    if (s->lfe_on)
-        s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
+    set_bandwidth(s, avctx->cutoff);
 
-    /* initial snr offset */
-    s->coarse_snr_offset = 40;
+    bit_alloc_init(s);
 
     mdct_init(9);