Browse code

opus: add a native Opus encoder

This marks the first time anyone has written an Opus encoder without
using any libopus code. The aim of the encoder is to prove how far
the format can go by writing the craziest encoder for it.

Right now the encoder's basic, it only supports CBR encoding, however
internally every single feature the CELT layer has is implemented
(except the pitch pre-filter which needs to work well with the rest of
whatever gets implemented). Psychoacoustic and rate control systems are
under development.

The encoder takes in frames of 120 samples and depending on the value of
opus_delay the plan is to use the extra buffered frames as lookahead.
Right now the encoder will pick the nearest largest legal frame size and
won't use the lookahead, but that'll change once there's a
psychoacoustic system.

Even though its a pretty basic encoder its already outperforming
any other native encoder FFmpeg has by a huge amount.

The PVQ search algorithm is faster and more accurate than libopus's
algorithm so the encoder's performance is close to that of libopus
at zero complexity (libopus has more SIMD).
The algorithm might be ported to libopus or other codecs using PVQ in
the future.

The encoder still has a few minor bugs, like desyncs at ultra low
bitrates (below 9kbps with 20ms frames).

Signed-off-by: Rostislav Pehlivanov <atomnuker@gmail.com>

Rostislav Pehlivanov authored on 2017/02/11 09:25:08
Showing 7 changed files
... ...
@@ -2492,6 +2492,7 @@ nuv_decoder_select="idctdsp lzo"
2492 2492
 on2avc_decoder_select="mdct"
2493 2493
 opus_decoder_deps="swresample"
2494 2494
 opus_decoder_select="mdct15"
2495
+opus_encoder_select="audio_frame_queue audiodsp mdct15"
2495 2496
 png_decoder_select="zlib"
2496 2497
 png_encoder_select="llvidencdsp zlib"
2497 2498
 prores_decoder_select="blockdsp idctdsp"
... ...
@@ -444,6 +444,7 @@ OBJS-$(CONFIG_NUV_DECODER)             += nuv.o rtjpeg.o
444 444
 OBJS-$(CONFIG_ON2AVC_DECODER)          += on2avc.o on2avcdata.o
445 445
 OBJS-$(CONFIG_OPUS_DECODER)            += opusdec.o opus.o opus_celt.o opus_rc.o \
446 446
                                           opus_pvq.o opus_silk.o opustab.o vorbis_data.o
447
+OBJS-$(CONFIG_OPUS_ENCODER)            += opusenc.o opus_rc.o opustab.o opus_pvq.o
447 448
 OBJS-$(CONFIG_PAF_AUDIO_DECODER)       += pafaudio.o
448 449
 OBJS-$(CONFIG_PAF_VIDEO_DECODER)       += pafvideo.o
449 450
 OBJS-$(CONFIG_PAM_DECODER)             += pnmdec.o pnm.o
... ...
@@ -449,7 +449,7 @@ void avcodec_register_all(void)
449 449
     REGISTER_DECODER(MPC8,              mpc8);
450 450
     REGISTER_ENCDEC (NELLYMOSER,        nellymoser);
451 451
     REGISTER_DECODER(ON2AVC,            on2avc);
452
-    REGISTER_DECODER(OPUS,              opus);
452
+    REGISTER_ENCDEC (OPUS,              opus);
453 453
     REGISTER_DECODER(PAF_AUDIO,         paf_audio);
454 454
     REGISTER_DECODER(QCELP,             qcelp);
455 455
     REGISTER_DECODER(QDM2,              qdm2);
... ...
@@ -61,14 +61,23 @@ enum CeltBlockSize {
61 61
 
62 62
 typedef struct CeltBlock {
63 63
     float energy[CELT_MAX_BANDS];
64
+    float lin_energy[CELT_MAX_BANDS];
65
+    float error_energy[CELT_MAX_BANDS];
64 66
     float prev_energy[2][CELT_MAX_BANDS];
65 67
 
66 68
     uint8_t collapse_masks[CELT_MAX_BANDS];
67 69
 
70
+    int band_bins[CELT_MAX_BANDS]; /* MDCT bins per band */
71
+    float *band_coeffs[CELT_MAX_BANDS];
72
+
68 73
     /* buffer for mdct output + postfilter */
69 74
     DECLARE_ALIGNED(32, float, buf)[2048];
70 75
     DECLARE_ALIGNED(32, float, coeffs)[CELT_MAX_FRAME_SIZE];
71 76
 
77
+    /* Used by the encoder */
78
+    DECLARE_ALIGNED(32, float, overlap)[120];
79
+    DECLARE_ALIGNED(32, float, samples)[CELT_MAX_FRAME_SIZE];
80
+
72 81
     /* postfilter parameters */
73 82
     int   pf_period_new;
74 83
     float pf_gains_new[3];
... ...
@@ -94,6 +103,12 @@ struct CeltFrame {
94 94
     int end_band;
95 95
     int coded_bands;
96 96
     int transient;
97
+    int intra;
98
+    int pfilter;
99
+    int skip_band_floor;
100
+    int tf_select;
101
+    int alloc_trim;
102
+    int alloc_boost[CELT_MAX_BANDS];
97 103
     int blocks;        /* number of iMDCT blocks in the frame, depends on transient */
98 104
     int blocksize;     /* size of each block */
99 105
     int silence;       /* Frame is filled with silence */
... ...
@@ -109,6 +124,7 @@ struct CeltFrame {
109 109
     int framebits;
110 110
     int remaining;
111 111
     int remaining2;
112
+    int caps         [CELT_MAX_BANDS];
112 113
     int fine_bits    [CELT_MAX_BANDS];
113 114
     int fine_priority[CELT_MAX_BANDS];
114 115
     int pulses       [CELT_MAX_BANDS];
... ...
@@ -1,7 +1,7 @@
1 1
 /*
2 2
  * Copyright (c) 2012 Andrew D'Addesio
3 3
  * Copyright (c) 2013-2014 Mozilla Corporation
4
- * Copyright (c) 2016 Rostislav Pehlivanov <atomnuker@gmail.com>
4
+ * Copyright (c) 2017 Rostislav Pehlivanov <atomnuker@gmail.com>
5 5
  *
6 6
  * This file is part of FFmpeg.
7 7
  *
... ...
@@ -78,8 +78,8 @@ static inline void celt_normalize_residual(const int * av_restrict iy, float * a
78 78
         X[i] = g * iy[i];
79 79
 }
80 80
 
81
-static void celt_exp_rotation1(float *X, uint32_t len, uint32_t stride,
82
-                               float c, float s)
81
+static void celt_exp_rotation_impl(float *X, uint32_t len, uint32_t stride,
82
+                                   float c, float s)
83 83
 {
84 84
     float *Xptr;
85 85
     int i;
... ...
@@ -105,7 +105,7 @@ static void celt_exp_rotation1(float *X, uint32_t len, uint32_t stride,
105 105
 
106 106
 static inline void celt_exp_rotation(float *X, uint32_t len,
107 107
                                      uint32_t stride, uint32_t K,
108
-                                     enum CeltSpread spread)
108
+                                     enum CeltSpread spread, const int encode)
109 109
 {
110 110
     uint32_t stride2 = 0;
111 111
     float c, s;
... ...
@@ -133,9 +133,15 @@ static inline void celt_exp_rotation(float *X, uint32_t len,
133 133
     extract_collapse_mask().*/
134 134
     len /= stride;
135 135
     for (i = 0; i < stride; i++) {
136
-        if (stride2)
137
-            celt_exp_rotation1(X + i * len, len, stride2, s, c);
138
-        celt_exp_rotation1(X + i * len, len, 1, c, s);
136
+        if (encode) {
137
+            celt_exp_rotation_impl(X + i * len, len, 1, c, -s);
138
+            if (stride2)
139
+                celt_exp_rotation_impl(X + i * len, len, stride2, s, -c);
140
+        } else {
141
+            if (stride2)
142
+                celt_exp_rotation_impl(X + i * len, len, stride2, s, c);
143
+            celt_exp_rotation_impl(X + i * len, len, 1, c, s);
144
+        }
139 145
     }
140 146
 }
141 147
 
... ...
@@ -270,6 +276,18 @@ static inline int celt_compute_qn(int N, int b, int offset, int pulse_cap,
270 270
     return qn;
271 271
 }
272 272
 
273
+/* Convert the quantized vector to an index */
274
+static inline uint32_t celt_icwrsi(uint32_t N, const int *y)
275
+{
276
+    int i, idx = 0, sum = 0;
277
+    for (i = N - 1; i >= 0; i--) {
278
+        const uint32_t i_s = CELT_PVQ_U(N - i, sum + FFABS(y[i]) + 1);
279
+        idx += CELT_PVQ_U(N - i, sum) + (y[i] < 0)*i_s;
280
+        sum += FFABS(y[i]);
281
+    }
282
+    return idx;
283
+}
284
+
273 285
 // this code was adapted from libopus
274 286
 static inline uint64_t celt_cwrsi(uint32_t N, uint32_t K, uint32_t i, int *y)
275 287
 {
... ...
@@ -356,12 +374,74 @@ static inline uint64_t celt_cwrsi(uint32_t N, uint32_t K, uint32_t i, int *y)
356 356
     return norm;
357 357
 }
358 358
 
359
+static inline void celt_encode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
360
+{
361
+    ff_opus_rc_enc_uint(rc, celt_icwrsi(N, y), CELT_PVQ_V(N, K));
362
+}
363
+
359 364
 static inline float celt_decode_pulses(OpusRangeCoder *rc, int *y, uint32_t N, uint32_t K)
360 365
 {
361 366
     const uint32_t idx = ff_opus_rc_dec_uint(rc, CELT_PVQ_V(N, K));
362 367
     return celt_cwrsi(N, K, idx, y);
363 368
 }
364 369
 
370
+/*
371
+ * Faster than libopus's search, operates entirely in the signed domain.
372
+ * Slightly worse/better depending on N, K and the input vector.
373
+ */
374
+static void celt_pvq_search(float *X, int *y, int K, int N)
375
+{
376
+    int i;
377
+    float res = 0.0f, y_norm = 0.0f, xy_norm = 0.0f;
378
+
379
+    for (i = 0; i < N; i++)
380
+        res += FFABS(X[i]);
381
+
382
+    res = K/res;
383
+
384
+    for (i = 0; i < N; i++) {
385
+        y[i] = lrintf(res*X[i]);
386
+        y_norm  += y[i]*y[i];
387
+        xy_norm += y[i]*X[i];
388
+        K -= FFABS(y[i]);
389
+    }
390
+
391
+    while (K) {
392
+        int max_idx = 0, phase = FFSIGN(K);
393
+        float max_den = 1.0f, max_num = 0.0f;
394
+        y_norm += 1.0f;
395
+
396
+        for (i = 0; i < N; i++) {
397
+            float xy_new = xy_norm + 1*phase*FFABS(X[i]);
398
+            float y_new  = y_norm  + 2*phase*FFABS(y[i]);
399
+            xy_new = xy_new * xy_new;
400
+            if ((max_den*xy_new) > (y_new*max_num)) {
401
+                max_den = y_new;
402
+                max_num = xy_new;
403
+                max_idx = i;
404
+            }
405
+        }
406
+
407
+        K -= phase;
408
+
409
+        phase *= FFSIGN(X[max_idx]);
410
+        xy_norm += 1*phase*X[max_idx];
411
+        y_norm  += 2*phase*y[max_idx];
412
+        y[max_idx] += phase;
413
+    }
414
+}
415
+
416
+static uint32_t celt_alg_quant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
417
+                               enum CeltSpread spread, uint32_t blocks, float gain)
418
+{
419
+    int y[176];
420
+
421
+    celt_exp_rotation(X, N, blocks, K, spread, 1);
422
+    celt_pvq_search(X, y, K, N);
423
+    celt_encode_pulses(rc, y,  N, K);
424
+    return celt_extract_collapse_mask(y, N, blocks);
425
+}
426
+
365 427
 /** Decode pulse vector and combine the result with the pitch vector to produce
366 428
     the final normalised signal in the current band. */
367 429
 static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint32_t K,
... ...
@@ -371,7 +451,7 @@ static uint32_t celt_alg_unquant(OpusRangeCoder *rc, float *X, uint32_t N, uint3
371 371
 
372 372
     gain /= sqrtf(celt_decode_pulses(rc, y, N, K));
373 373
     celt_normalize_residual(y, X, N, gain);
374
-    celt_exp_rotation(X, N, blocks, K, spread);
374
+    celt_exp_rotation(X, N, blocks, K, spread, 0);
375 375
     return celt_extract_collapse_mask(y, N, blocks);
376 376
 }
377 377
 
... ...
@@ -725,5 +805,353 @@ uint32_t ff_celt_decode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
725 725
         }
726 726
         cm = av_mod_uintp2(cm, blocks);
727 727
     }
728
+
729
+    return cm;
730
+}
731
+
732
+/* This has to be, AND MUST BE done by the psychoacoustic system, this has a very
733
+ * big impact on the entire quantization and especially huge on transients */
734
+static int celt_calc_theta(const float *X, const float *Y, int coupling, int N)
735
+{
736
+    int j;
737
+    float e[2] = { 0.0f, 0.0f };
738
+    for (j = 0; j < N; j++) {
739
+        if (coupling) { /* Coupling case */
740
+            e[0] += (X[j] + Y[j])*(X[j] + Y[j]);
741
+            e[1] += (X[j] - Y[j])*(X[j] - Y[j]);
742
+        } else {
743
+            e[0] += X[j]*X[j];
744
+            e[1] += Y[j]*Y[j];
745
+        }
746
+    }
747
+    return lrintf(32768.0f*atan2f(sqrtf(e[1]), sqrtf(e[0]))/M_PI);
748
+}
749
+
750
+static void celt_stereo_is_decouple(float *X, float *Y, float e_l, float e_r, int N)
751
+{
752
+    int i;
753
+    const float energy_n = 1.0f/(sqrtf(e_l*e_l + e_r*e_r) + FLT_EPSILON);
754
+    e_l *= energy_n;
755
+    e_r *= energy_n;
756
+    for (i = 0; i < N; i++)
757
+        X[i] = e_l*X[i] + e_r*Y[i];
758
+}
759
+
760
+static void celt_stereo_ms_decouple(float *X, float *Y, int N)
761
+{
762
+    int i;
763
+    const float decouple_norm = 1.0f/sqrtf(2.0f);
764
+    for (i = 0; i < N; i++) {
765
+        const float Xret = X[i];
766
+        X[i] = (X[i] + Y[i])*decouple_norm;
767
+        Y[i] = (Y[i] - Xret)*decouple_norm;
768
+    }
769
+}
770
+
771
+uint32_t ff_celt_encode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
772
+                             float *X, float *Y, int N, int b, uint32_t blocks,
773
+                             float *lowband, int duration, float *lowband_out, int level,
774
+                             float gain, float *lowband_scratch, int fill)
775
+{
776
+    const uint8_t *cache;
777
+    int dualstereo, split;
778
+    int imid = 0, iside = 0;
779
+    //uint32_t N0 = N;
780
+    int N_B;
781
+    //int N_B0;
782
+    int B0 = blocks;
783
+    int time_divide = 0;
784
+    int recombine = 0;
785
+    int inv = 0;
786
+    float mid = 0, side = 0;
787
+    int longblocks = (B0 == 1);
788
+    uint32_t cm = 0;
789
+
790
+    //N_B0 = N_B = N / blocks;
791
+    split = dualstereo = (Y != NULL);
792
+
793
+    if (N == 1) {
794
+        /* special case for one sample - the decoder's output will be +- 1.0f!!! */
795
+        int i;
796
+        float *x = X;
797
+        for (i = 0; i <= dualstereo; i++) {
798
+            if (f->remaining2 >= 1<<3) {
799
+                ff_opus_rc_put_raw(rc, x[0] < 0, 1);
800
+                f->remaining2 -= 1 << 3;
801
+                b             -= 1 << 3;
802
+            }
803
+            x = Y;
804
+        }
805
+        if (lowband_out)
806
+            lowband_out[0] = X[0];
807
+        return 1;
808
+    }
809
+
810
+    if (!dualstereo && level == 0) {
811
+        int tf_change = f->tf_change[band];
812
+        int k;
813
+        if (tf_change > 0)
814
+            recombine = tf_change;
815
+        /* Band recombining to increase frequency resolution */
816
+
817
+        if (lowband &&
818
+            (recombine || ((N_B & 1) == 0 && tf_change < 0) || B0 > 1)) {
819
+            int j;
820
+            for (j = 0; j < N; j++)
821
+                lowband_scratch[j] = lowband[j];
822
+            lowband = lowband_scratch;
823
+        }
824
+
825
+        for (k = 0; k < recombine; k++) {
826
+            celt_haar1(X, N >> k, 1 << k);
827
+            fill = ff_celt_bit_interleave[fill & 0xF] | ff_celt_bit_interleave[fill >> 4] << 2;
828
+        }
829
+        blocks >>= recombine;
830
+        N_B <<= recombine;
831
+
832
+        /* Increasing the time resolution */
833
+        while ((N_B & 1) == 0 && tf_change < 0) {
834
+            celt_haar1(X, N_B, blocks);
835
+            fill |= fill << blocks;
836
+            blocks <<= 1;
837
+            N_B >>= 1;
838
+            time_divide++;
839
+            tf_change++;
840
+        }
841
+        B0 = blocks;
842
+        //N_B0 = N_B;
843
+
844
+        /* Reorganize the samples in time order instead of frequency order */
845
+        if (B0 > 1)
846
+            celt_deinterleave_hadamard(f->scratch, X, N_B >> recombine,
847
+                                       B0 << recombine, longblocks);
848
+    }
849
+
850
+    /* If we need 1.5 more bit than we can produce, split the band in two. */
851
+    cache = ff_celt_cache_bits +
852
+            ff_celt_cache_index[(duration + 1) * CELT_MAX_BANDS + band];
853
+    if (!dualstereo && duration >= 0 && b > cache[cache[0]] + 12 && N > 2) {
854
+        N >>= 1;
855
+        Y = X + N;
856
+        split = 1;
857
+        duration -= 1;
858
+        if (blocks == 1)
859
+            fill = (fill & 1) | (fill << 1);
860
+        blocks = (blocks + 1) >> 1;
861
+    }
862
+
863
+    if (split) {
864
+        int qn;
865
+        int itheta = celt_calc_theta(X, Y, dualstereo, N);
866
+        int mbits, sbits, delta;
867
+        int qalloc;
868
+        int pulse_cap;
869
+        int offset;
870
+        int orig_fill;
871
+        int tell;
872
+
873
+        /* Decide on the resolution to give to the split parameter theta */
874
+        pulse_cap = ff_celt_log_freq_range[band] + duration * 8;
875
+        offset = (pulse_cap >> 1) - (dualstereo && N == 2 ? CELT_QTHETA_OFFSET_TWOPHASE :
876
+                                                          CELT_QTHETA_OFFSET);
877
+        qn = (dualstereo && band >= f->intensity_stereo) ? 1 :
878
+             celt_compute_qn(N, b, offset, pulse_cap, dualstereo);
879
+        tell = opus_rc_tell_frac(rc);
880
+
881
+        if (qn != 1) {
882
+
883
+            itheta = (itheta*qn + 8192) >> 14;
884
+
885
+            /* Entropy coding of the angle. We use a uniform pdf for the
886
+             * time split, a step for stereo, and a triangular one for the rest. */
887
+            if (dualstereo && N > 2)
888
+                ff_opus_rc_enc_uint_step(rc, itheta, qn / 2);
889
+            else if (dualstereo || B0 > 1)
890
+                ff_opus_rc_enc_uint(rc, itheta, qn + 1);
891
+            else
892
+                ff_opus_rc_enc_uint_tri(rc, itheta, qn);
893
+            itheta = itheta * 16384 / qn;
894
+
895
+            if (dualstereo) {
896
+                if (itheta == 0)
897
+                    celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
898
+                else
899
+                    celt_stereo_ms_decouple(X, Y, N);
900
+            }
901
+        } else if (dualstereo) {
902
+             inv = itheta > 8192;
903
+             if (inv)
904
+             {
905
+                int j;
906
+                for (j=0;j<N;j++)
907
+                   Y[j] = -Y[j];
908
+             }
909
+             celt_stereo_is_decouple(X, Y, f->block[0].lin_energy[band], f->block[1].lin_energy[band], N);
910
+
911
+            if (b > 2 << 3 && f->remaining2 > 2 << 3) {
912
+                ff_opus_rc_enc_log(rc, inv, 2);
913
+            } else {
914
+                inv = 0;
915
+            }
916
+
917
+            itheta = 0;
918
+        }
919
+        qalloc = opus_rc_tell_frac(rc) - tell;
920
+        b -= qalloc;
921
+
922
+        orig_fill = fill;
923
+        if (itheta == 0) {
924
+            imid = 32767;
925
+            iside = 0;
926
+            fill = av_mod_uintp2(fill, blocks);
927
+            delta = -16384;
928
+        } else if (itheta == 16384) {
929
+            imid = 0;
930
+            iside = 32767;
931
+            fill &= ((1 << blocks) - 1) << blocks;
932
+            delta = 16384;
933
+        } else {
934
+            imid = celt_cos(itheta);
935
+            iside = celt_cos(16384-itheta);
936
+            /* This is the mid vs side allocation that minimizes squared error
937
+            in that band. */
938
+            delta = ROUND_MUL16((N - 1) << 7, celt_log2tan(iside, imid));
939
+        }
940
+
941
+        mid  = imid  / 32768.0f;
942
+        side = iside / 32768.0f;
943
+
944
+        /* This is a special case for N=2 that only works for stereo and takes
945
+        advantage of the fact that mid and side are orthogonal to encode
946
+        the side with just one bit. */
947
+        if (N == 2 && dualstereo) {
948
+            int c;
949
+            int sign = 0;
950
+            float tmp;
951
+            float *x2, *y2;
952
+            mbits = b;
953
+            /* Only need one bit for the side */
954
+            sbits = (itheta != 0 && itheta != 16384) ? 1 << 3 : 0;
955
+            mbits -= sbits;
956
+            c = (itheta > 8192);
957
+            f->remaining2 -= qalloc+sbits;
958
+
959
+            x2 = c ? Y : X;
960
+            y2 = c ? X : Y;
961
+            if (sbits) {
962
+                sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
963
+                ff_opus_rc_put_raw(rc, sign, 1);
964
+            }
965
+            sign = 1 - 2 * sign;
966
+            /* We use orig_fill here because we want to fold the side, but if
967
+            itheta==16384, we'll have cleared the low bits of fill. */
968
+            cm = ff_celt_encode_band(f, rc, band, x2, NULL, N, mbits, blocks,
969
+                                     lowband, duration, lowband_out, level, gain,
970
+                                     lowband_scratch, orig_fill);
971
+            /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
972
+            and there's no need to worry about mixing with the other channel. */
973
+            y2[0] = -sign * x2[1];
974
+            y2[1] =  sign * x2[0];
975
+            X[0] *= mid;
976
+            X[1] *= mid;
977
+            Y[0] *= side;
978
+            Y[1] *= side;
979
+            tmp = X[0];
980
+            X[0] = tmp - Y[0];
981
+            Y[0] = tmp + Y[0];
982
+            tmp = X[1];
983
+            X[1] = tmp - Y[1];
984
+            Y[1] = tmp + Y[1];
985
+        } else {
986
+            /* "Normal" split code */
987
+            float *next_lowband2     = NULL;
988
+            float *next_lowband_out1 = NULL;
989
+            int next_level = 0;
990
+            int rebalance;
991
+
992
+            /* Give more bits to low-energy MDCTs than they would
993
+             * otherwise deserve */
994
+            if (B0 > 1 && !dualstereo && (itheta & 0x3fff)) {
995
+                if (itheta > 8192)
996
+                    /* Rough approximation for pre-echo masking */
997
+                    delta -= delta >> (4 - duration);
998
+                else
999
+                    /* Corresponds to a forward-masking slope of
1000
+                     * 1.5 dB per 10 ms */
1001
+                    delta = FFMIN(0, delta + (N << 3 >> (5 - duration)));
1002
+            }
1003
+            mbits = av_clip((b - delta) / 2, 0, b);
1004
+            sbits = b - mbits;
1005
+            f->remaining2 -= qalloc;
1006
+
1007
+            if (lowband && !dualstereo)
1008
+                next_lowband2 = lowband + N; /* >32-bit split case */
1009
+
1010
+            /* Only stereo needs to pass on lowband_out.
1011
+             * Otherwise, it's handled at the end */
1012
+            if (dualstereo)
1013
+                next_lowband_out1 = lowband_out;
1014
+            else
1015
+                next_level = level + 1;
1016
+
1017
+            rebalance = f->remaining2;
1018
+            if (mbits >= sbits) {
1019
+                /* In stereo mode, we do not apply a scaling to the mid
1020
+                 * because we need the normalized mid for folding later */
1021
+                cm = ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1022
+                                         lowband, duration, next_lowband_out1,
1023
+                                         next_level, dualstereo ? 1.0f : (gain * mid),
1024
+                                         lowband_scratch, fill);
1025
+
1026
+                rebalance = mbits - (rebalance - f->remaining2);
1027
+                if (rebalance > 3 << 3 && itheta != 0)
1028
+                    sbits += rebalance - (3 << 3);
1029
+
1030
+                /* For a stereo split, the high bits of fill are always zero,
1031
+                 * so no folding will be done to the side. */
1032
+                cm |= ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1033
+                                          next_lowband2, duration, NULL,
1034
+                                          next_level, gain * side, NULL,
1035
+                                          fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1036
+            } else {
1037
+                /* For a stereo split, the high bits of fill are always zero,
1038
+                 * so no folding will be done to the side. */
1039
+                cm = ff_celt_encode_band(f, rc, band, Y, NULL, N, sbits, blocks,
1040
+                                         next_lowband2, duration, NULL,
1041
+                                         next_level, gain * side, NULL,
1042
+                                         fill >> blocks) << ((B0 >> 1) & (dualstereo - 1));
1043
+
1044
+                rebalance = sbits - (rebalance - f->remaining2);
1045
+                if (rebalance > 3 << 3 && itheta != 16384)
1046
+                    mbits += rebalance - (3 << 3);
1047
+
1048
+                /* In stereo mode, we do not apply a scaling to the mid because
1049
+                 * we need the normalized mid for folding later */
1050
+                cm |= ff_celt_encode_band(f, rc, band, X, NULL, N, mbits, blocks,
1051
+                                          lowband, duration, next_lowband_out1,
1052
+                                          next_level, dualstereo ? 1.0f : (gain * mid),
1053
+                                          lowband_scratch, fill);
1054
+            }
1055
+        }
1056
+    } else {
1057
+        /* This is the basic no-split case */
1058
+        uint32_t q         = celt_bits2pulses(cache, b);
1059
+        uint32_t curr_bits = celt_pulses2bits(cache, q);
1060
+        f->remaining2 -= curr_bits;
1061
+
1062
+        /* Ensures we can never bust the budget */
1063
+        while (f->remaining2 < 0 && q > 0) {
1064
+            f->remaining2 += curr_bits;
1065
+            curr_bits      = celt_pulses2bits(cache, --q);
1066
+            f->remaining2 -= curr_bits;
1067
+        }
1068
+
1069
+        if (q != 0) {
1070
+            /* Finally do the actual quantization */
1071
+            cm = celt_alg_quant(rc, X, N, (q < 8) ? q : (8 + (q & 7)) << ((q >> 3) - 1),
1072
+                                f->spread, blocks, gain);
1073
+        }
1074
+    }
1075
+
728 1076
     return cm;
729 1077
 }
... ...
@@ -32,4 +32,10 @@ uint32_t ff_celt_decode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
32 32
                              float *lowband, int duration, float *lowband_out, int level,
33 33
                              float gain, float *lowband_scratch, int fill);
34 34
 
35
+/* Encodes a band using PVQ */
36
+uint32_t ff_celt_encode_band(CeltFrame *f, OpusRangeCoder *rc, const int band,
37
+                             float *X, float *Y, int N, int b, uint32_t blocks,
38
+                             float *lowband, int duration, float *lowband_out, int level,
39
+                             float gain, float *lowband_scratch, int fill);
40
+
35 41
 #endif /* AVCODEC_OPUS_PVQ_H */
36 42
new file mode 100644
... ...
@@ -0,0 +1,1130 @@
0
+/*
1
+ * Opus encoder
2
+ * Copyright (c) 2017 Rostislav Pehlivanov <atomnuker@gmail.com>
3
+ *
4
+ * This file is part of FFmpeg.
5
+ *
6
+ * FFmpeg is free software; you can redistribute it and/or
7
+ * modify it under the terms of the GNU Lesser General Public
8
+ * License as published by the Free Software Foundation; either
9
+ * version 2.1 of the License, or (at your option) any later version.
10
+ *
11
+ * FFmpeg is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
+ * Lesser General Public License for more details.
15
+ *
16
+ * You should have received a copy of the GNU Lesser General Public
17
+ * License along with FFmpeg; if not, write to the Free Software
18
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
+ */
20
+
21
+#include "opus_celt.h"
22
+#include "opus_pvq.h"
23
+#include "opustab.h"
24
+
25
+#include "libavutil/float_dsp.h"
26
+#include "libavutil/opt.h"
27
+#include "internal.h"
28
+#include "bytestream.h"
29
+#include "audio_frame_queue.h"
30
+
31
+/* Determines the maximum delay the psychoacoustic system will use for lookahead */
32
+#define FF_BUFQUEUE_SIZE 145
33
+#include "libavfilter/bufferqueue.h"
34
+
35
+#define OPUS_MAX_LOOKAHEAD ((FF_BUFQUEUE_SIZE - 1)*2.5f)
36
+
37
+#define OPUS_MAX_CHANNELS 2
38
+
39
+/* 120 ms / 2.5 ms = 48 frames (extremely improbable, but the encoder'll work) */
40
+#define OPUS_MAX_FRAMES_PER_PACKET 48
41
+
42
+#define OPUS_BLOCK_SIZE(x) (2 * 15 * (1 << (x + 2)))
43
+
44
+#define OPUS_SAMPLES_TO_BLOCK_SIZE(x) (ff_log2(x / (2 * 15)) - 2)
45
+
46
+typedef struct OpusEncOptions {
47
+    float max_delay_ms;
48
+} OpusEncOptions;
49
+
50
+typedef struct OpusEncContext {
51
+    AVClass *av_class;
52
+    OpusEncOptions options;
53
+    AVCodecContext *avctx;
54
+    AudioFrameQueue afq;
55
+    AVFloatDSPContext *dsp;
56
+    MDCT15Context *mdct[CELT_BLOCK_NB];
57
+    struct FFBufQueue bufqueue;
58
+
59
+    enum OpusMode mode;
60
+    enum OpusBandwidth bandwidth;
61
+    int pkt_framesize;
62
+    int pkt_frames;
63
+
64
+    int channels;
65
+
66
+    CeltFrame *frame;
67
+    OpusRangeCoder *rc;
68
+
69
+    /* Actual energy the decoder will have */
70
+    float last_quantized_energy[OPUS_MAX_CHANNELS][CELT_MAX_BANDS];
71
+
72
+    DECLARE_ALIGNED(32, float, scratch)[2048];
73
+} OpusEncContext;
74
+
75
+static void opus_write_extradata(AVCodecContext *avctx)
76
+{
77
+    uint8_t *bs = avctx->extradata;
78
+
79
+    bytestream_put_buffer(&bs, "OpusHead", 8);
80
+    bytestream_put_byte  (&bs, 0x1);
81
+    bytestream_put_byte  (&bs, avctx->channels);
82
+    bytestream_put_le16  (&bs, avctx->initial_padding);
83
+    bytestream_put_le32  (&bs, avctx->sample_rate);
84
+    bytestream_put_le16  (&bs, 0x0);
85
+    bytestream_put_byte  (&bs, 0x0); /* Default layout */
86
+}
87
+
88
+static int opus_gen_toc(OpusEncContext *s, uint8_t *toc, int *size, int *fsize_needed)
89
+{
90
+    int i, tmp = 0x0, extended_toc = 0;
91
+    static const int toc_cfg[][OPUS_MODE_NB][OPUS_BANDWITH_NB] = {
92
+        /*  Silk                    Hybrid                  Celt                    Layer     */
93
+        /*  NB  MB  WB SWB  FB      NB  MB  WB SWB  FB      NB  MB  WB SWB  FB      Bandwidth */
94
+        { {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 }, { 17,  0, 21, 25, 29 } }, /* 2.5 ms */
95
+        { {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 }, { 18,  0, 22, 26, 30 } }, /*   5 ms */
96
+        { {  1,  5,  9,  0,  0 }, {  0,  0,  0, 13, 15 }, { 19,  0, 23, 27, 31 } }, /*  10 ms */
97
+        { {  2,  6, 10,  0,  0 }, {  0,  0,  0, 14, 16 }, { 20,  0, 24, 28, 32 } }, /*  20 ms */
98
+        { {  3,  7, 11,  0,  0 }, {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 } }, /*  40 ms */
99
+        { {  4,  8, 12,  0,  0 }, {  0,  0,  0,  0,  0 }, {  0,  0,  0,  0,  0 } }, /*  60 ms */
100
+    };
101
+    int cfg = toc_cfg[s->pkt_framesize][s->mode][s->bandwidth];
102
+    *fsize_needed = 0;
103
+    if (!cfg)
104
+        return 1;
105
+    if (s->pkt_frames == 2) {                                          /* 2 packets */
106
+        if (s->frame[0].framebits == s->frame[1].framebits) {          /* same size */
107
+            tmp = 0x1;
108
+        } else {                                                  /* different size */
109
+            tmp = 0x2;
110
+            *fsize_needed = 1;                     /* put frame sizes in the packet */
111
+        }
112
+    } else if (s->pkt_frames > 2) {
113
+        tmp = 0x3;
114
+        extended_toc = 1;
115
+    }
116
+    tmp |= (s->channels > 1) << 2;                                /* Stereo or mono */
117
+    tmp |= (cfg - 1)         << 3;                           /* codec configuration */
118
+    *toc++ = tmp;
119
+    if (extended_toc) {
120
+        for (i = 0; i < (s->pkt_frames - 1); i++)
121
+            *fsize_needed |= (s->frame[i].framebits != s->frame[i + 1].framebits);
122
+        tmp = (*fsize_needed) << 7;                                     /* vbr flag */
123
+        tmp |= s->pkt_frames;                    /* frame number - can be 0 as well */
124
+        *toc++ = tmp;
125
+    }
126
+    *size = 1 + extended_toc;
127
+    return 0;
128
+}
129
+
130
+static void celt_frame_setup_input(OpusEncContext *s, CeltFrame *f)
131
+{
132
+    int sf, ch;
133
+    AVFrame *cur = NULL;
134
+    const int subframesize = s->avctx->frame_size;
135
+    int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
136
+
137
+    cur = ff_bufqueue_get(&s->bufqueue);
138
+
139
+    for (ch = 0; ch < f->channels; ch++) {
140
+        CeltBlock *b = &f->block[ch];
141
+        const void *input = cur->extended_data[ch];
142
+        size_t bps = av_get_bytes_per_sample(cur->format);
143
+        memcpy(b->overlap, input, bps*cur->nb_samples);
144
+    }
145
+
146
+    av_frame_free(&cur);
147
+
148
+    for (sf = 0; sf < subframes; sf++) {
149
+        if (sf != (subframes - 1))
150
+            cur = ff_bufqueue_get(&s->bufqueue);
151
+        else
152
+            cur = ff_bufqueue_peek(&s->bufqueue, 0);
153
+
154
+        for (ch = 0; ch < f->channels; ch++) {
155
+            CeltBlock *b = &f->block[ch];
156
+            const void *input = cur->extended_data[ch];
157
+            const size_t bps  = av_get_bytes_per_sample(cur->format);
158
+            const size_t left = (subframesize - cur->nb_samples)*bps;
159
+            const size_t len  = FFMIN(subframesize, cur->nb_samples)*bps;
160
+            memcpy(&b->samples[sf*subframesize], input, len);
161
+            memset(&b->samples[cur->nb_samples], 0, left);
162
+        }
163
+
164
+        /* Last frame isn't popped off and freed yet - we need it for overlap */
165
+        if (sf != (subframes - 1))
166
+            av_frame_free(&cur);
167
+    }
168
+}
169
+
170
+/* Apply the pre emphasis filter */
171
+static void celt_apply_preemph_filter(OpusEncContext *s, CeltFrame *f)
172
+{
173
+    int i, sf, ch;
174
+    const int subframesize = s->avctx->frame_size;
175
+    const int subframes = OPUS_BLOCK_SIZE(s->pkt_framesize) / subframesize;
176
+
177
+    /* Filter overlap */
178
+    for (ch = 0; ch < f->channels; ch++) {
179
+        CeltBlock *b = &f->block[ch];
180
+        float m = b->emph_coeff;
181
+        for (i = 0; i < CELT_OVERLAP; i++) {
182
+            float sample = b->overlap[i];
183
+            b->overlap[i] = sample - m;
184
+            m = sample * CELT_EMPH_COEFF;
185
+        }
186
+        b->emph_coeff = m;
187
+    }
188
+
189
+    /* Filter the samples but do not update the last subframe's coeff - overlap ^^^ */
190
+    for (sf = 0; sf < subframes; sf++) {
191
+        for (ch = 0; ch < f->channels; ch++) {
192
+            CeltBlock *b = &f->block[ch];
193
+            float m = b->emph_coeff;
194
+            for (i = 0; i < subframesize; i++) {
195
+                float sample = b->samples[sf*subframesize + i];
196
+                b->samples[sf*subframesize + i] = sample - m;
197
+                m = sample * CELT_EMPH_COEFF;
198
+            }
199
+            if (sf != (subframes - 1))
200
+                b->emph_coeff = m;
201
+        }
202
+    }
203
+}
204
+
205
+/* Create the window and do the mdct */
206
+static void celt_frame_mdct(OpusEncContext *s, CeltFrame *f)
207
+{
208
+    int i, t, ch;
209
+    float *win = s->scratch;
210
+
211
+    /* I think I can use s->dsp->vector_fmul_window for transients at least */
212
+    if (f->transient) {
213
+        for (ch = 0; ch < f->channels; ch++) {
214
+            CeltBlock *b = &f->block[ch];
215
+            float *src1 = b->overlap;
216
+            for (t = 0; t < f->blocks; t++) {
217
+                float *src2 = &b->samples[CELT_OVERLAP*t];
218
+                for (i = 0; i < CELT_OVERLAP; i++) {
219
+                    win[               i] = src1[i]*ff_celt_window[i];
220
+                    win[CELT_OVERLAP + i] = src2[i]*ff_celt_window[CELT_OVERLAP - i - 1];
221
+                }
222
+                src1 = src2;
223
+                s->mdct[0]->mdct(s->mdct[0], b->coeffs + t, win, f->blocks);
224
+            }
225
+        }
226
+    } else {
227
+        int blk_len = OPUS_BLOCK_SIZE(f->size), wlen = OPUS_BLOCK_SIZE(f->size + 1);
228
+        int rwin = blk_len - CELT_OVERLAP, lap_dst = (wlen - blk_len - CELT_OVERLAP) >> 1;
229
+        for (ch = 0; ch < f->channels; ch++) {
230
+            CeltBlock *b = &f->block[ch];
231
+
232
+            memset(win, 0, wlen*sizeof(float));
233
+
234
+            memcpy(&win[lap_dst + CELT_OVERLAP], b->samples, rwin*sizeof(float));
235
+
236
+            /* Alignment fucks me over */
237
+            //s->dsp->vector_fmul(&dst[lap_dst], b->overlap, ff_celt_window, CELT_OVERLAP);
238
+            //s->dsp->vector_fmul_reverse(&dst[lap_dst + blk_len - CELT_OVERLAP], b->samples, ff_celt_window, CELT_OVERLAP);
239
+
240
+            for (i = 0; i < CELT_OVERLAP; i++) {
241
+                win[lap_dst           + i] = b->overlap[i]       *ff_celt_window[i];
242
+                win[lap_dst + blk_len + i] = b->samples[rwin + i]*ff_celt_window[CELT_OVERLAP - i - 1];
243
+            }
244
+
245
+            s->mdct[f->size]->mdct(s->mdct[f->size], b->coeffs, win, 1);
246
+        }
247
+    }
248
+}
249
+
250
+/* Fills the bands and normalizes them */
251
+static int celt_frame_map_norm_bands(OpusEncContext *s, CeltFrame *f)
252
+{
253
+    int i, j, ch, noise = 0;
254
+
255
+    for (ch = 0; ch < f->channels; ch++) {
256
+        CeltBlock *block = &f->block[ch];
257
+        float *start = block->coeffs;
258
+        for (i = 0; i < CELT_MAX_BANDS; i++) {
259
+            float ener = 0.0f;
260
+
261
+            /* Calculate band bins */
262
+            block->band_bins[i] = ff_celt_freq_range[i] << f->size;
263
+            block->band_coeffs[i] = start;
264
+            start += block->band_bins[i];
265
+
266
+            /* Normalize band energy */
267
+            for (j = 0; j < block->band_bins[i]; j++)
268
+                ener += block->band_coeffs[i][j]*block->band_coeffs[i][j];
269
+
270
+            block->lin_energy[i] = sqrtf(ener) + FLT_EPSILON;
271
+            ener = 1.0f/block->lin_energy[i];
272
+
273
+            for (j = 0; j < block->band_bins[i]; j++)
274
+                block->band_coeffs[i][j] *= ener;
275
+
276
+            block->energy[i] = log2f(block->lin_energy[i]) - ff_celt_mean_energy[i];
277
+
278
+            /* CELT_ENERGY_SILENCE is what the decoder uses and its not -infinity */
279
+            block->energy[i] = FFMAX(block->energy[i], CELT_ENERGY_SILENCE);
280
+            noise |= block->energy[i] > CELT_ENERGY_SILENCE;
281
+        }
282
+    }
283
+    return !noise;
284
+}
285
+
286
+static void celt_enc_tf(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
287
+{
288
+    int i, tf_select = 0, diff = 0, tf_changed = 0, tf_select_needed;
289
+    int bits = f->transient ? 2 : 4;
290
+
291
+    tf_select_needed = ((f->size && (opus_rc_tell(rc) + bits + 1) <= f->framebits));
292
+
293
+    for (i = f->start_band; i < f->end_band; i++) {
294
+        if ((opus_rc_tell(rc) + bits + tf_select_needed) <= f->framebits) {
295
+            const int tbit = (diff ^ 1) == f->tf_change[i];
296
+            ff_opus_rc_enc_log(rc, tbit, bits);
297
+            diff ^= tbit;
298
+            tf_changed |= diff;
299
+        }
300
+        bits = f->transient ? 4 : 5;
301
+    }
302
+
303
+    if (tf_select_needed && ff_celt_tf_select[f->size][f->transient][0][tf_changed] !=
304
+                            ff_celt_tf_select[f->size][f->transient][1][tf_changed]) {
305
+        ff_opus_rc_enc_log(rc, f->tf_select, 1);
306
+        tf_select = f->tf_select;
307
+    }
308
+
309
+    for (i = f->start_band; i < f->end_band; i++)
310
+        f->tf_change[i] = ff_celt_tf_select[f->size][f->transient][tf_select][f->tf_change[i]];
311
+}
312
+
313
+static void celt_bitalloc(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
314
+{
315
+    int i, j, low, high, total, done, bandbits, remaining, tbits_8ths;
316
+    int skip_startband      = f->start_band;
317
+    int skip_bit            = 0;
318
+    int intensitystereo_bit = 0;
319
+    int dualstereo_bit      = 0;
320
+    int dynalloc            = 6;
321
+    int extrabits           = 0;
322
+
323
+    int *cap = f->caps;
324
+    int boost[CELT_MAX_BANDS];
325
+    int trim_offset[CELT_MAX_BANDS];
326
+    int threshold[CELT_MAX_BANDS];
327
+    int bits1[CELT_MAX_BANDS];
328
+    int bits2[CELT_MAX_BANDS];
329
+
330
+    /* Tell the spread to the decoder */
331
+    if (opus_rc_tell(rc) + 4 <= f->framebits)
332
+        ff_opus_rc_enc_cdf(rc, f->spread, ff_celt_model_spread);
333
+
334
+    /* Generate static allocation caps */
335
+    for (i = 0; i < CELT_MAX_BANDS; i++) {
336
+        cap[i] = (ff_celt_static_caps[f->size][f->channels - 1][i] + 64)
337
+                 * ff_celt_freq_range[i] << (f->channels - 1) << f->size >> 2;
338
+    }
339
+
340
+    /* Band boosts */
341
+    tbits_8ths = f->framebits << 3;
342
+    for (i = f->start_band; i < f->end_band; i++) {
343
+        int quanta, b_dynalloc, boost_amount = f->alloc_boost[i];
344
+
345
+        boost[i] = 0;
346
+
347
+        quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
348
+        quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
349
+        b_dynalloc = dynalloc;
350
+
351
+        while (opus_rc_tell_frac(rc) + (b_dynalloc << 3) < tbits_8ths && boost[i] < cap[i]) {
352
+            int is_boost = boost_amount--;
353
+
354
+            ff_opus_rc_enc_log(rc, is_boost, b_dynalloc);
355
+            if (!is_boost)
356
+                break;
357
+
358
+            boost[i]   += quanta;
359
+            tbits_8ths -= quanta;
360
+
361
+            b_dynalloc = 1;
362
+        }
363
+
364
+        if (boost[i])
365
+            dynalloc = FFMAX(2, dynalloc - 1);
366
+    }
367
+
368
+    /* Put allocation trim */
369
+    if (opus_rc_tell_frac(rc) + (6 << 3) <= tbits_8ths)
370
+        ff_opus_rc_enc_cdf(rc, f->alloc_trim, ff_celt_model_alloc_trim);
371
+
372
+    /* Anti-collapse bit reservation */
373
+    tbits_8ths = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
374
+    f->anticollapse_needed = 0;
375
+    if (f->transient && f->size >= 2 && tbits_8ths >= ((f->size + 2) << 3))
376
+        f->anticollapse_needed = 1 << 3;
377
+    tbits_8ths -= f->anticollapse_needed;
378
+
379
+    /* Band skip bit reservation */
380
+    if (tbits_8ths >= 1 << 3)
381
+        skip_bit = 1 << 3;
382
+    tbits_8ths -= skip_bit;
383
+
384
+    /* Intensity/dual stereo bit reservation */
385
+    if (f->channels == 2) {
386
+        intensitystereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
387
+        if (intensitystereo_bit <= tbits_8ths) {
388
+            tbits_8ths -= intensitystereo_bit;
389
+            if (tbits_8ths >= 1 << 3) {
390
+                dualstereo_bit = 1 << 3;
391
+                tbits_8ths -= 1 << 3;
392
+            }
393
+        } else {
394
+            intensitystereo_bit = 0;
395
+        }
396
+    }
397
+
398
+    /* Trim offsets */
399
+    for (i = f->start_band; i < f->end_band; i++) {
400
+        int trim     = f->alloc_trim - 5 - f->size;
401
+        int band     = ff_celt_freq_range[i] * (f->end_band - i - 1);
402
+        int duration = f->size + 3;
403
+        int scale    = duration + f->channels - 1;
404
+
405
+        /* PVQ minimum allocation threshold, below this value the band is
406
+         * skipped */
407
+        threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
408
+                             f->channels << 3);
409
+
410
+        trim_offset[i] = trim * (band << scale) >> 6;
411
+
412
+        if (ff_celt_freq_range[i] << f->size == 1)
413
+            trim_offset[i] -= f->channels << 3;
414
+    }
415
+
416
+    /* Bisection */
417
+    low  = 1;
418
+    high = CELT_VECTORS - 1;
419
+    while (low <= high) {
420
+        int center = (low + high) >> 1;
421
+        done = total = 0;
422
+
423
+        for (i = f->end_band - 1; i >= f->start_band; i--) {
424
+            bandbits = ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]
425
+                       << (f->channels - 1) << f->size >> 2;
426
+
427
+            if (bandbits)
428
+                bandbits = FFMAX(0, bandbits + trim_offset[i]);
429
+            bandbits += boost[i];
430
+
431
+            if (bandbits >= threshold[i] || done) {
432
+                done = 1;
433
+                total += FFMIN(bandbits, cap[i]);
434
+            } else if (bandbits >= f->channels << 3)
435
+                total += f->channels << 3;
436
+        }
437
+
438
+        if (total > tbits_8ths)
439
+            high = center - 1;
440
+        else
441
+            low = center + 1;
442
+    }
443
+    high = low--;
444
+
445
+    /* Bisection */
446
+    for (i = f->start_band; i < f->end_band; i++) {
447
+        bits1[i] = ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]
448
+                   << (f->channels - 1) << f->size >> 2;
449
+        bits2[i] = high >= CELT_VECTORS ? cap[i] :
450
+                   ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]
451
+                   << (f->channels - 1) << f->size >> 2;
452
+
453
+        if (bits1[i])
454
+            bits1[i] = FFMAX(0, bits1[i] + trim_offset[i]);
455
+        if (bits2[i])
456
+            bits2[i] = FFMAX(0, bits2[i] + trim_offset[i]);
457
+        if (low)
458
+            bits1[i] += boost[i];
459
+        bits2[i] += boost[i];
460
+
461
+        if (boost[i])
462
+            skip_startband = i;
463
+        bits2[i] = FFMAX(0, bits2[i] - bits1[i]);
464
+    }
465
+
466
+    /* Bisection */
467
+    low  = 0;
468
+    high = 1 << CELT_ALLOC_STEPS;
469
+    for (i = 0; i < CELT_ALLOC_STEPS; i++) {
470
+        int center = (low + high) >> 1;
471
+        done = total = 0;
472
+
473
+        for (j = f->end_band - 1; j >= f->start_band; j--) {
474
+            bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
475
+
476
+            if (bandbits >= threshold[j] || done) {
477
+                done = 1;
478
+                total += FFMIN(bandbits, cap[j]);
479
+            } else if (bandbits >= f->channels << 3)
480
+                total += f->channels << 3;
481
+        }
482
+        if (total > tbits_8ths)
483
+            high = center;
484
+        else
485
+            low = center;
486
+    }
487
+
488
+    /* Bisection */
489
+    done = total = 0;
490
+    for (i = f->end_band - 1; i >= f->start_band; i--) {
491
+        bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
492
+
493
+        if (bandbits >= threshold[i] || done)
494
+            done = 1;
495
+        else
496
+            bandbits = (bandbits >= f->channels << 3) ?
497
+                       f->channels << 3 : 0;
498
+
499
+        bandbits     = FFMIN(bandbits, cap[i]);
500
+        f->pulses[i] = bandbits;
501
+        total      += bandbits;
502
+    }
503
+
504
+    /* Band skipping */
505
+    for (f->coded_bands = f->end_band; ; f->coded_bands--) {
506
+        int allocation;
507
+        j = f->coded_bands - 1;
508
+
509
+        if (j == skip_startband) {
510
+            /* all remaining bands are not skipped */
511
+            tbits_8ths += skip_bit;
512
+            break;
513
+        }
514
+
515
+        /* determine the number of bits available for coding "do not skip" markers */
516
+        remaining   = tbits_8ths - total;
517
+        bandbits    = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
518
+        remaining  -= bandbits  * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
519
+        allocation  = f->pulses[j] + bandbits * ff_celt_freq_range[j]
520
+                      + FFMAX(0, remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]));
521
+
522
+        /* a "do not skip" marker is only coded if the allocation is
523
+           above the chosen threshold */
524
+        if (allocation >= FFMAX(threshold[j], (f->channels + 1) << 3)) {
525
+            const int do_not_skip = f->coded_bands <= f->skip_band_floor;
526
+            ff_opus_rc_enc_log(rc, do_not_skip, 1);
527
+            if (do_not_skip)
528
+                break;
529
+
530
+            total      += 1 << 3;
531
+            allocation -= 1 << 3;
532
+        }
533
+
534
+        /* the band is skipped, so reclaim its bits */
535
+        total -= f->pulses[j];
536
+        if (intensitystereo_bit) {
537
+            total -= intensitystereo_bit;
538
+            intensitystereo_bit = ff_celt_log2_frac[j - f->start_band];
539
+            total += intensitystereo_bit;
540
+        }
541
+
542
+        total += f->pulses[j] = (allocation >= f->channels << 3) ? f->channels << 3 : 0;
543
+    }
544
+
545
+    /* Encode stereo flags */
546
+    if (intensitystereo_bit) {
547
+        f->intensity_stereo = FFMIN(f->intensity_stereo, f->coded_bands);
548
+        ff_opus_rc_enc_uint(rc, f->intensity_stereo, f->coded_bands + 1 - f->start_band);
549
+    }
550
+    if (f->intensity_stereo <= f->start_band)
551
+        tbits_8ths += dualstereo_bit; /* no intensity stereo means no dual stereo */
552
+    else if (dualstereo_bit)
553
+        ff_opus_rc_enc_log(rc, f->dual_stereo, 1);
554
+
555
+    /* Supply the remaining bits in this frame to lower bands */
556
+    remaining = tbits_8ths - total;
557
+    bandbits  = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
558
+    remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
559
+    for (i = f->start_band; i < f->coded_bands; i++) {
560
+        int bits = FFMIN(remaining, ff_celt_freq_range[i]);
561
+
562
+        f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
563
+        remaining    -= bits;
564
+    }
565
+
566
+    /* Finally determine the allocation */
567
+    for (i = f->start_band; i < f->coded_bands; i++) {
568
+        int N = ff_celt_freq_range[i] << f->size;
569
+        int prev_extra = extrabits;
570
+        f->pulses[i] += extrabits;
571
+
572
+        if (N > 1) {
573
+            int dof;        // degrees of freedom
574
+            int temp;       // dof * channels * log(dof)
575
+            int offset;     // fine energy quantization offset, i.e.
576
+                            // extra bits assigned over the standard
577
+                            // totalbits/dof
578
+            int fine_bits, max_bits;
579
+
580
+            extrabits = FFMAX(0, f->pulses[i] - cap[i]);
581
+            f->pulses[i] -= extrabits;
582
+
583
+            /* intensity stereo makes use of an extra degree of freedom */
584
+            dof = N * f->channels + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
585
+            temp = dof * (ff_celt_log_freq_range[i] + (f->size << 3));
586
+            offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
587
+            if (N == 2) /* dof=2 is the only case that doesn't fit the model */
588
+                offset += dof << 1;
589
+
590
+            /* grant an additional bias for the first and second pulses */
591
+            if (f->pulses[i] + offset < 2 * (dof << 3))
592
+                offset += temp >> 2;
593
+            else if (f->pulses[i] + offset < 3 * (dof << 3))
594
+                offset += temp >> 3;
595
+
596
+            fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
597
+            max_bits  = FFMIN((f->pulses[i] >> 3) >> (f->channels - 1), CELT_MAX_FINE_BITS);
598
+
599
+            max_bits  = FFMAX(max_bits, 0);
600
+
601
+            f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
602
+
603
+            /* if fine_bits was rounded down or capped,
604
+               give priority for the final fine energy pass */
605
+            f->fine_priority[i] = (f->fine_bits[i] * (dof << 3) >= f->pulses[i] + offset);
606
+
607
+            /* the remaining bits are assigned to PVQ */
608
+            f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
609
+        } else {
610
+            /* all bits go to fine energy except for the sign bit */
611
+            extrabits = FFMAX(0, f->pulses[i] - (f->channels << 3));
612
+            f->pulses[i] -= extrabits;
613
+            f->fine_bits[i] = 0;
614
+            f->fine_priority[i] = 1;
615
+        }
616
+
617
+        /* hand back a limited number of extra fine energy bits to this band */
618
+        if (extrabits > 0) {
619
+            int fineextra = FFMIN(extrabits >> (f->channels + 2),
620
+                                  CELT_MAX_FINE_BITS - f->fine_bits[i]);
621
+            f->fine_bits[i] += fineextra;
622
+
623
+            fineextra <<= f->channels + 2;
624
+            f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
625
+            extrabits -= fineextra;
626
+        }
627
+    }
628
+    f->remaining = extrabits;
629
+
630
+    /* skipped bands dedicate all of their bits for fine energy */
631
+    for (; i < f->end_band; i++) {
632
+        f->fine_bits[i]     = f->pulses[i] >> (f->channels - 1) >> 3;
633
+        f->pulses[i]        = 0;
634
+        f->fine_priority[i] = f->fine_bits[i] < 1;
635
+    }
636
+}
637
+
638
+static void celt_quant_coarse(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
639
+{
640
+    int i, ch;
641
+    float alpha, beta, prev[2] = { 0, 0 };
642
+    const uint8_t *pmod = ff_celt_coarse_energy_dist[f->size][f->intra];
643
+
644
+    /* Inter is really just differential coding */
645
+    if (opus_rc_tell(rc) + 3 <= f->framebits)
646
+        ff_opus_rc_enc_log(rc, f->intra, 3);
647
+    else
648
+        f->intra = 0;
649
+
650
+    if (f->intra) {
651
+        alpha = 0.0f;
652
+        beta  = 1.0f - 4915.0f/32768.0f;
653
+    } else {
654
+        alpha = ff_celt_alpha_coef[f->size];
655
+        beta  = 1.0f - ff_celt_beta_coef[f->size];
656
+    }
657
+
658
+    for (i = f->start_band; i < f->end_band; i++) {
659
+        for (ch = 0; ch < f->channels; ch++) {
660
+            CeltBlock *block = &f->block[ch];
661
+            const int left = f->framebits - opus_rc_tell(rc);
662
+            const float last = FFMAX(-9.0f, s->last_quantized_energy[ch][i]);
663
+            float diff = block->energy[i] - prev[ch] - last*alpha;
664
+            int q_en = lrintf(diff);
665
+            if (left >= 15) {
666
+                ff_opus_rc_enc_laplace(rc, &q_en, pmod[i << 1] << 7, pmod[(i << 1) + 1] << 6);
667
+            } else if (left >= 2) {
668
+                q_en = av_clip(q_en, -1, 1);
669
+                ff_opus_rc_enc_cdf(rc, ((q_en & 1) << 1) | (q_en < 0), ff_celt_model_energy_small);
670
+            } else if (left >= 1) {
671
+                q_en = av_clip(q_en, -1, 0);
672
+                ff_opus_rc_enc_log(rc, (q_en & 1), 1);
673
+            } else q_en = -1;
674
+
675
+            block->error_energy[i] = q_en - diff;
676
+            prev[ch] += beta * q_en;
677
+        }
678
+    }
679
+}
680
+
681
+static void celt_quant_fine(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
682
+{
683
+    int i, ch;
684
+    for (i = f->start_band; i < f->end_band; i++) {
685
+        if (!f->fine_bits[i])
686
+            continue;
687
+        for (ch = 0; ch < f->channels; ch++) {
688
+            CeltBlock *block = &f->block[ch];
689
+            int quant, lim = (1 << f->fine_bits[i]);
690
+            float offset, diff = 0.5f - block->error_energy[i];
691
+            quant = av_clip(floor(diff*lim), 0, lim - 1);
692
+            ff_opus_rc_put_raw(rc, quant, f->fine_bits[i]);
693
+            offset = 0.5f - ((quant + 0.5f) * (1 << (14 - f->fine_bits[i])) / 16384.0f);
694
+            block->error_energy[i] -= offset;
695
+        }
696
+    }
697
+}
698
+
699
+static void celt_quant_final(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
700
+{
701
+    int i, ch, priority;
702
+    for (priority = 0; priority < 2; priority++) {
703
+        for (i = f->start_band; i < f->end_band && (f->framebits - opus_rc_tell(rc)) >= f->channels; i++) {
704
+            if (f->fine_priority[i] != priority || f->fine_bits[i] >= CELT_MAX_FINE_BITS)
705
+                continue;
706
+            for (ch = 0; ch < f->channels; ch++) {
707
+                CeltBlock *block = &f->block[ch];
708
+                const float err = block->error_energy[i];
709
+                const float offset = 0.5f * (1 << (14 - f->fine_bits[i] - 1)) / 16384.0f;
710
+                const int sign = FFABS(err + offset) < FFABS(err - offset);
711
+                ff_opus_rc_put_raw(rc, sign, 1);
712
+                block->error_energy[i] -= offset*(1 - 2*sign);
713
+            }
714
+        }
715
+    }
716
+}
717
+
718
+static void celt_quant_bands(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
719
+{
720
+    float lowband_scratch[8 * 22];
721
+    float norm[2 * 8 * 100];
722
+
723
+    int totalbits = (f->framebits << 3) - f->anticollapse_needed;
724
+
725
+    int update_lowband = 1;
726
+    int lowband_offset = 0;
727
+
728
+    int i, j;
729
+
730
+    for (i = f->start_band; i < f->end_band; i++) {
731
+        int band_offset = ff_celt_freq_bands[i] << f->size;
732
+        int band_size   = ff_celt_freq_range[i] << f->size;
733
+        float *X = f->block[0].coeffs + band_offset;
734
+        float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
735
+
736
+        int consumed = opus_rc_tell_frac(rc);
737
+        float *norm2 = norm + 8 * 100;
738
+        int effective_lowband = -1;
739
+        unsigned int cm[2];
740
+        int b;
741
+
742
+        /* Compute how many bits we want to allocate to this band */
743
+        if (i != f->start_band)
744
+            f->remaining -= consumed;
745
+        f->remaining2 = totalbits - consumed - 1;
746
+        if (i <= f->coded_bands - 1) {
747
+            int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
748
+            b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
749
+        } else
750
+            b = 0;
751
+
752
+        if (ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] &&
753
+            (update_lowband || lowband_offset == 0))
754
+            lowband_offset = i;
755
+
756
+        /* Get a conservative estimate of the collapse_mask's for the bands we're
757
+        going to be folding from. */
758
+        if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
759
+                                    f->blocks > 1 || f->tf_change[i] < 0)) {
760
+            int foldstart, foldend;
761
+
762
+            /* This ensures we never repeat spectral content within one band */
763
+            effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
764
+                                      ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
765
+            foldstart = lowband_offset;
766
+            while (ff_celt_freq_bands[--foldstart] > effective_lowband);
767
+            foldend = lowband_offset - 1;
768
+            while (ff_celt_freq_bands[++foldend] < effective_lowband + ff_celt_freq_range[i]);
769
+
770
+            cm[0] = cm[1] = 0;
771
+            for (j = foldstart; j < foldend; j++) {
772
+                cm[0] |= f->block[0].collapse_masks[j];
773
+                cm[1] |= f->block[f->channels - 1].collapse_masks[j];
774
+            }
775
+        } else
776
+            /* Otherwise, we'll be using the LCG to fold, so all blocks will (almost
777
+            always) be non-zero.*/
778
+            cm[0] = cm[1] = (1 << f->blocks) - 1;
779
+
780
+        if (f->dual_stereo && i == f->intensity_stereo) {
781
+            /* Switch off dual stereo to do intensity */
782
+            f->dual_stereo = 0;
783
+            for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
784
+                norm[j] = (norm[j] + norm2[j]) / 2;
785
+        }
786
+
787
+        if (f->dual_stereo) {
788
+            cm[0] = ff_celt_encode_band(f, rc, i, X, NULL, band_size, b / 2, f->blocks,
789
+                                        effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
790
+                                        norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]);
791
+
792
+            cm[1] = ff_celt_encode_band(f, rc, i, Y, NULL, band_size, b/2, f->blocks,
793
+                                        effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL, f->size,
794
+                                        norm2 + band_offset, 0, 1.0f, lowband_scratch, cm[1]);
795
+        } else {
796
+            cm[0] = ff_celt_encode_band(f, rc, i, X, Y, band_size, b, f->blocks,
797
+                                        effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
798
+                                        norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]|cm[1]);
799
+            cm[1] = cm[0];
800
+        }
801
+
802
+        f->block[0].collapse_masks[i]               = (uint8_t)cm[0];
803
+        f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
804
+        f->remaining += f->pulses[i] + consumed;
805
+
806
+        /* Update the folding position only as long as we have 1 bit/sample depth */
807
+        update_lowband = (b > band_size << 3);
808
+    }
809
+}
810
+
811
+static void celt_encode_frame(OpusEncContext *s, OpusRangeCoder *rc, CeltFrame *f)
812
+{
813
+    int i, ch;
814
+
815
+    celt_frame_setup_input(s, f);
816
+    celt_apply_preemph_filter(s, f);
817
+    if (f->pfilter) {
818
+        /* Not implemented */
819
+    }
820
+    celt_frame_mdct(s, f);
821
+    f->silence = celt_frame_map_norm_bands(s, f);
822
+    if (f->silence) {
823
+        f->framebits = 1;
824
+        return;
825
+    }
826
+
827
+    ff_opus_rc_enc_log(rc, f->silence, 15);
828
+
829
+    if (!f->start_band && opus_rc_tell(rc) + 16 <= f->framebits)
830
+        ff_opus_rc_enc_log(rc, f->pfilter, 1);
831
+
832
+    if (f->pfilter) {
833
+        /* Not implemented */
834
+    }
835
+
836
+    if (f->size && opus_rc_tell(rc) + 3 <= f->framebits)
837
+        ff_opus_rc_enc_log(rc, f->transient, 3);
838
+
839
+    celt_quant_coarse (s, rc, f);
840
+    celt_enc_tf       (s, rc, f);
841
+    celt_bitalloc     (s, rc, f);
842
+    celt_quant_fine   (s, rc, f);
843
+    celt_quant_bands  (s, rc, f);
844
+
845
+    if (f->anticollapse_needed)
846
+        ff_opus_rc_put_raw(rc, f->anticollapse, 1);
847
+
848
+    celt_quant_final(s, rc, f);
849
+
850
+    for (ch = 0; ch < f->channels; ch++) {
851
+        CeltBlock *block = &f->block[ch];
852
+        for (i = 0; i < CELT_MAX_BANDS; i++)
853
+            s->last_quantized_energy[ch][i] = block->energy[i] + block->error_energy[i];
854
+    }
855
+}
856
+
857
+static void ff_opus_psy_process(OpusEncContext *s, int end, int *need_more)
858
+{
859
+    int max_delay_samples = (s->options.max_delay_ms*s->avctx->sample_rate)/1000;
860
+    int max_bsize = FFMIN(OPUS_SAMPLES_TO_BLOCK_SIZE(max_delay_samples), CELT_BLOCK_960);
861
+
862
+    s->pkt_frames = 1;
863
+    s->pkt_framesize = max_bsize;
864
+    s->mode = OPUS_MODE_CELT;
865
+    s->bandwidth = OPUS_BANDWIDTH_FULLBAND;
866
+
867
+    *need_more = s->bufqueue.available*s->avctx->frame_size < (max_delay_samples + CELT_OVERLAP);
868
+    /* Don't request more if we start being flushed with NULL frames */
869
+    *need_more = !end && *need_more;
870
+}
871
+
872
+static void ff_opus_psy_celt_frame_setup(OpusEncContext *s, CeltFrame *f, int index)
873
+{
874
+    int frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
875
+
876
+    f->avctx = s->avctx;
877
+    f->dsp = s->dsp;
878
+    f->start_band = (s->mode == OPUS_MODE_HYBRID) ? 17 : 0;
879
+    f->end_band = ff_celt_band_end[s->bandwidth];
880
+    f->channels = s->channels;
881
+    f->size = s->pkt_framesize;
882
+
883
+    /* Decisions */
884
+    f->silence = 0;
885
+    f->pfilter = 0;
886
+    f->transient = 0;
887
+    f->intra = 1;
888
+    f->tf_select = 0;
889
+    f->anticollapse = 0;
890
+    f->alloc_trim = 5;
891
+    f->skip_band_floor = f->end_band;
892
+    f->intensity_stereo = f->end_band;
893
+    f->dual_stereo = 0;
894
+    f->spread = CELT_SPREAD_NORMAL;
895
+    memset(f->tf_change, 0, sizeof(int)*CELT_MAX_BANDS);
896
+    memset(f->alloc_boost, 0, sizeof(int)*CELT_MAX_BANDS);
897
+
898
+    f->blocks = f->transient ? frame_size/CELT_OVERLAP : 1;
899
+    f->framebits = FFALIGN(lrintf((double)s->avctx->bit_rate/(s->avctx->sample_rate/frame_size)), 8);
900
+}
901
+
902
+static void opus_packet_assembler(OpusEncContext *s, AVPacket *avpkt)
903
+{
904
+    int i, offset, fsize_needed;
905
+
906
+    /* Write toc */
907
+    opus_gen_toc(s, avpkt->data, &offset, &fsize_needed);
908
+
909
+    for (i = 0; i < s->pkt_frames; i++) {
910
+        ff_opus_rc_enc_end(&s->rc[i], avpkt->data + offset, s->frame[i].framebits >> 3);
911
+        offset += s->frame[i].framebits >> 3;
912
+    }
913
+
914
+    avpkt->size = offset;
915
+}
916
+
917
+/* Used as overlap for the first frame and padding for the last encoded packet */
918
+static AVFrame *spawn_empty_frame(OpusEncContext *s)
919
+{
920
+    int i;
921
+    AVFrame *f = av_frame_alloc();
922
+    if (!f)
923
+        return NULL;
924
+    f->format         = s->avctx->sample_fmt;
925
+    f->nb_samples     = s->avctx->frame_size;
926
+    f->channel_layout = s->avctx->channel_layout;
927
+    if (av_frame_get_buffer(f, 4)) {
928
+        av_frame_free(&f);
929
+        return NULL;
930
+    }
931
+    for (i = 0; i < s->channels; i++) {
932
+        size_t bps = av_get_bytes_per_sample(f->format);
933
+        memset(f->extended_data[i], 0, bps*f->nb_samples);
934
+    }
935
+    return f;
936
+}
937
+
938
+static int opus_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
939
+                             const AVFrame *frame, int *got_packet_ptr)
940
+{
941
+    OpusEncContext *s = avctx->priv_data;
942
+    int i, ret, frame_size, need_more, alloc_size = 0;
943
+
944
+    if (frame) { /* Add new frame to queue */
945
+        if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
946
+            return ret;
947
+        ff_bufqueue_add(avctx, &s->bufqueue, av_frame_clone(frame));
948
+    } else {
949
+        if (!s->afq.remaining_samples)
950
+            return 0; /* We've been flushed and there's nothing left to encode */
951
+    }
952
+
953
+    /* Run the psychoacoustic system */
954
+    ff_opus_psy_process(s, !frame, &need_more);
955
+
956
+    /* Get more samples for lookahead/encoding */
957
+    if (need_more)
958
+        return 0;
959
+
960
+    frame_size = OPUS_BLOCK_SIZE(s->pkt_framesize);
961
+
962
+    if (!frame) {
963
+        /* This can go negative, that's not a problem, we only pad if positive */
964
+        int pad_empty = s->pkt_frames*(frame_size/s->avctx->frame_size) - s->bufqueue.available + 1;
965
+        /* Pad with empty 2.5 ms frames to whatever framesize was decided,
966
+         * this should only happen at the very last flush frame. The frames
967
+         * allocated here will be freed (because they have no other references)
968
+         * after they get used by celt_frame_setup_input() */
969
+        for (i = 0; i < pad_empty; i++) {
970
+            AVFrame *empty = spawn_empty_frame(s);
971
+            if (!empty)
972
+                return AVERROR(ENOMEM);
973
+            ff_bufqueue_add(avctx, &s->bufqueue, empty);
974
+        }
975
+    }
976
+
977
+    for (i = 0; i < s->pkt_frames; i++) {
978
+        ff_opus_rc_enc_init(&s->rc[i]);
979
+        ff_opus_psy_celt_frame_setup(s, &s->frame[i], i);
980
+        celt_encode_frame(s, &s->rc[i], &s->frame[i]);
981
+        alloc_size += s->frame[i].framebits >> 3;
982
+    }
983
+
984
+    /* Worst case toc + the frame lengths if needed */
985
+    alloc_size += 2 + s->pkt_frames*2;
986
+
987
+    if ((ret = ff_alloc_packet2(avctx, avpkt, alloc_size, 0)) < 0)
988
+        return ret;
989
+
990
+    /* Assemble packet */
991
+    opus_packet_assembler(s, avpkt);
992
+
993
+    /* Remove samples from queue and skip if needed */
994
+    ff_af_queue_remove(&s->afq, s->pkt_frames*frame_size, &avpkt->pts, &avpkt->duration);
995
+    if (s->pkt_frames*frame_size > avpkt->duration) {
996
+        uint8_t *side = av_packet_new_side_data(avpkt, AV_PKT_DATA_SKIP_SAMPLES, 10);
997
+        if (!side)
998
+            return AVERROR(ENOMEM);
999
+        AV_WL32(&side[4], s->pkt_frames*frame_size - avpkt->duration + 120);
1000
+    }
1001
+
1002
+    *got_packet_ptr = 1;
1003
+
1004
+    return 0;
1005
+}
1006
+
1007
+static av_cold int opus_encode_end(AVCodecContext *avctx)
1008
+{
1009
+    int i;
1010
+    OpusEncContext *s = avctx->priv_data;
1011
+
1012
+    for (i = 0; i < CELT_BLOCK_NB; i++)
1013
+        ff_mdct15_uninit(&s->mdct[i]);
1014
+
1015
+    av_freep(&s->dsp);
1016
+    av_freep(&s->frame);
1017
+    av_freep(&s->rc);
1018
+    ff_af_queue_close(&s->afq);
1019
+    ff_bufqueue_discard_all(&s->bufqueue);
1020
+    av_freep(&avctx->extradata);
1021
+
1022
+    return 0;
1023
+}
1024
+
1025
+static av_cold int opus_encode_init(AVCodecContext *avctx)
1026
+{
1027
+    int i, ch, ret;
1028
+    OpusEncContext *s = avctx->priv_data;
1029
+
1030
+    s->avctx = avctx;
1031
+    s->channels = avctx->channels;
1032
+
1033
+    /* Opus allows us to change the framesize on each packet (and each packet may
1034
+     * have multiple frames in it) but we can't change the codec's frame size on
1035
+     * runtime, so fix it to the lowest possible number of samples and use a queue
1036
+     * to accumulate AVFrames until we have enough to encode whatever the encoder
1037
+     * decides is the best */
1038
+    avctx->frame_size = 120;
1039
+    /* Initial padding will change if SILK is ever supported */
1040
+    avctx->initial_padding = 120;
1041
+
1042
+    avctx->cutoff = !avctx->cutoff ? 20000 : avctx->cutoff;
1043
+
1044
+    if (!avctx->bit_rate) {
1045
+        int coupled = ff_opus_default_coupled_streams[s->channels - 1];
1046
+        avctx->bit_rate = coupled*(96000) + (s->channels - coupled*2)*(48000);
1047
+    } else if (avctx->bit_rate < 6000 || avctx->bit_rate > 255000 * s->channels) {
1048
+        int64_t clipped_rate = av_clip(avctx->bit_rate, 6000, 255000 * s->channels);
1049
+        av_log(avctx, AV_LOG_ERROR, "Unsupported bitrate %li kbps, clipping to %li kbps\n",
1050
+               avctx->bit_rate/1000, clipped_rate/1000);
1051
+        avctx->bit_rate = clipped_rate;
1052
+    }
1053
+
1054
+    /* Frame structs and range coder buffers */
1055
+    s->frame = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(CeltFrame));
1056
+    if (!s->frame)
1057
+        return AVERROR(ENOMEM);
1058
+    s->rc = av_malloc(OPUS_MAX_FRAMES_PER_PACKET*sizeof(OpusRangeCoder));
1059
+    if (!s->rc)
1060
+        return AVERROR(ENOMEM);
1061
+
1062
+    /* Extradata */
1063
+    avctx->extradata_size = 19;
1064
+    avctx->extradata = av_malloc(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
1065
+    if (!avctx->extradata)
1066
+        return AVERROR(ENOMEM);
1067
+    opus_write_extradata(avctx);
1068
+
1069
+    ff_af_queue_init(avctx, &s->afq);
1070
+
1071
+    if (!(s->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT)))
1072
+        return AVERROR(ENOMEM);
1073
+
1074
+    /* I have no idea why a base scaling factor of 68 works, could be the twiddles */
1075
+    for (i = 0; i < CELT_BLOCK_NB; i++)
1076
+        if ((ret = ff_mdct15_init(&s->mdct[i], 0, i + 3, 68 << (CELT_BLOCK_NB - 1 - i))))
1077
+            return AVERROR(ENOMEM);
1078
+
1079
+    /* Zero out previous energy (matters for inter first frame) */
1080
+    for (ch = 0; ch < s->channels; ch++)
1081
+        for (i = 0; i < CELT_MAX_BANDS; i++)
1082
+            s->last_quantized_energy[ch][i] = 0.0f;
1083
+
1084
+    /* Allocate an empty frame to use as overlap for the first frame of audio */
1085
+    ff_bufqueue_add(avctx, &s->bufqueue, spawn_empty_frame(s));
1086
+    if (!ff_bufqueue_peek(&s->bufqueue, 0))
1087
+        return AVERROR(ENOMEM);
1088
+
1089
+    return 0;
1090
+}
1091
+
1092
+#define OPUSENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1093
+static const AVOption opusenc_options[] = {
1094
+    { "opus_delay", "Maximum delay (and lookahead) in milliseconds", offsetof(OpusEncContext, options.max_delay_ms), AV_OPT_TYPE_FLOAT, { .dbl = OPUS_MAX_LOOKAHEAD }, 2.5f, OPUS_MAX_LOOKAHEAD, OPUSENC_FLAGS },
1095
+    { NULL },
1096
+};
1097
+
1098
+static const AVClass opusenc_class = {
1099
+    .class_name = "Opus encoder",
1100
+    .item_name  = av_default_item_name,
1101
+    .option     = opusenc_options,
1102
+    .version    = LIBAVUTIL_VERSION_INT,
1103
+};
1104
+
1105
+static const AVCodecDefault opusenc_defaults[] = {
1106
+    { "b", "0" },
1107
+    { "compression_level", "10" },
1108
+    { NULL },
1109
+};
1110
+
1111
+AVCodec ff_opus_encoder = {
1112
+    .name           = "opus",
1113
+    .long_name      = NULL_IF_CONFIG_SMALL("Opus"),
1114
+    .type           = AVMEDIA_TYPE_AUDIO,
1115
+    .id             = AV_CODEC_ID_OPUS,
1116
+    .defaults       = opusenc_defaults,
1117
+    .priv_class     = &opusenc_class,
1118
+    .priv_data_size = sizeof(OpusEncContext),
1119
+    .init           = opus_encode_init,
1120
+    .encode2        = opus_encode_frame,
1121
+    .close          = opus_encode_end,
1122
+    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
1123
+    .capabilities   = AV_CODEC_CAP_EXPERIMENTAL | AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY,
1124
+    .supported_samplerates = (const int []){ 48000, 0 },
1125
+    .channel_layouts = (const uint64_t []){ AV_CH_LAYOUT_MONO,
1126
+                                            AV_CH_LAYOUT_STEREO, 0 },
1127
+    .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
1128
+                                                     AV_SAMPLE_FMT_NONE },
1129
+};