forked from id-Software/Quake-III-Arena
/
opus_encoder.c
2536 lines (2361 loc) · 83.7 KB
/
opus_encoder.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
Written by Jean-Marc Valin and Koen Vos */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdarg.h>
#include "celt.h"
#include "entenc.h"
#include "modes.h"
#include "API.h"
#include "stack_alloc.h"
#include "float_cast.h"
#include "opus.h"
#include "arch.h"
#include "pitch.h"
#include "opus_private.h"
#include "os_support.h"
#include "cpu_support.h"
#include "analysis.h"
#include "mathops.h"
#include "tuning_parameters.h"
#ifdef FIXED_POINT
#include "fixed/structs_FIX.h"
#else
#include "float/structs_FLP.h"
#endif
#define MAX_ENCODER_BUFFER 480
typedef struct {
opus_val32 XX, XY, YY;
opus_val16 smoothed_width;
opus_val16 max_follower;
} StereoWidthState;
struct OpusEncoder {
int celt_enc_offset;
int silk_enc_offset;
silk_EncControlStruct silk_mode;
int application;
int channels;
int delay_compensation;
int force_channels;
int signal_type;
int user_bandwidth;
int max_bandwidth;
int user_forced_mode;
int voice_ratio;
opus_int32 Fs;
int use_vbr;
int vbr_constraint;
int variable_duration;
opus_int32 bitrate_bps;
opus_int32 user_bitrate_bps;
int lsb_depth;
int encoder_buffer;
int lfe;
int arch;
#ifndef DISABLE_FLOAT_API
TonalityAnalysisState analysis;
#endif
#define OPUS_ENCODER_RESET_START stream_channels
int stream_channels;
opus_int16 hybrid_stereo_width_Q14;
opus_int32 variable_HP_smth2_Q15;
opus_val16 prev_HB_gain;
opus_val32 hp_mem[4];
int mode;
int prev_mode;
int prev_channels;
int prev_framesize;
int bandwidth;
int silk_bw_switch;
/* Sampling rate (at the API level) */
int first;
opus_val16 * energy_masking;
StereoWidthState width_mem;
opus_val16 delay_buffer[MAX_ENCODER_BUFFER*2];
#ifndef DISABLE_FLOAT_API
int detected_bandwidth;
#endif
opus_uint32 rangeFinal;
};
/* Transition tables for the voice and music. First column is the
middle (memoriless) threshold. The second column is the hysteresis
(difference with the middle) */
static const opus_int32 mono_voice_bandwidth_thresholds[8] = {
11000, 1000, /* NB<->MB */
14000, 1000, /* MB<->WB */
17000, 1000, /* WB<->SWB */
21000, 2000, /* SWB<->FB */
};
static const opus_int32 mono_music_bandwidth_thresholds[8] = {
12000, 1000, /* NB<->MB */
15000, 1000, /* MB<->WB */
18000, 2000, /* WB<->SWB */
22000, 2000, /* SWB<->FB */
};
static const opus_int32 stereo_voice_bandwidth_thresholds[8] = {
11000, 1000, /* NB<->MB */
14000, 1000, /* MB<->WB */
21000, 2000, /* WB<->SWB */
28000, 2000, /* SWB<->FB */
};
static const opus_int32 stereo_music_bandwidth_thresholds[8] = {
12000, 1000, /* NB<->MB */
18000, 2000, /* MB<->WB */
21000, 2000, /* WB<->SWB */
30000, 2000, /* SWB<->FB */
};
/* Threshold bit-rates for switching between mono and stereo */
static const opus_int32 stereo_voice_threshold = 30000;
static const opus_int32 stereo_music_threshold = 30000;
/* Threshold bit-rate for switching between SILK/hybrid and CELT-only */
static const opus_int32 mode_thresholds[2][2] = {
/* voice */ /* music */
{ 64000, 16000}, /* mono */
{ 36000, 16000}, /* stereo */
};
int opus_encoder_get_size(int channels)
{
int silkEncSizeBytes, celtEncSizeBytes;
int ret;
if (channels<1 || channels > 2)
return 0;
ret = silk_Get_Encoder_Size( &silkEncSizeBytes );
if (ret)
return 0;
silkEncSizeBytes = align(silkEncSizeBytes);
celtEncSizeBytes = celt_encoder_get_size(channels);
return align(sizeof(OpusEncoder))+silkEncSizeBytes+celtEncSizeBytes;
}
int opus_encoder_init(OpusEncoder* st, opus_int32 Fs, int channels, int application)
{
void *silk_enc;
CELTEncoder *celt_enc;
int err;
int ret, silkEncSizeBytes;
if((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)||(channels!=1&&channels!=2)||
(application != OPUS_APPLICATION_VOIP && application != OPUS_APPLICATION_AUDIO
&& application != OPUS_APPLICATION_RESTRICTED_LOWDELAY))
return OPUS_BAD_ARG;
OPUS_CLEAR((char*)st, opus_encoder_get_size(channels));
/* Create SILK encoder */
ret = silk_Get_Encoder_Size( &silkEncSizeBytes );
if (ret)
return OPUS_BAD_ARG;
silkEncSizeBytes = align(silkEncSizeBytes);
st->silk_enc_offset = align(sizeof(OpusEncoder));
st->celt_enc_offset = st->silk_enc_offset+silkEncSizeBytes;
silk_enc = (char*)st+st->silk_enc_offset;
celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
st->stream_channels = st->channels = channels;
st->Fs = Fs;
st->arch = opus_select_arch();
ret = silk_InitEncoder( silk_enc, st->arch, &st->silk_mode );
if(ret)return OPUS_INTERNAL_ERROR;
/* default SILK parameters */
st->silk_mode.nChannelsAPI = channels;
st->silk_mode.nChannelsInternal = channels;
st->silk_mode.API_sampleRate = st->Fs;
st->silk_mode.maxInternalSampleRate = 16000;
st->silk_mode.minInternalSampleRate = 8000;
st->silk_mode.desiredInternalSampleRate = 16000;
st->silk_mode.payloadSize_ms = 20;
st->silk_mode.bitRate = 25000;
st->silk_mode.packetLossPercentage = 0;
st->silk_mode.complexity = 9;
st->silk_mode.useInBandFEC = 0;
st->silk_mode.useDTX = 0;
st->silk_mode.useCBR = 0;
st->silk_mode.reducedDependency = 0;
/* Create CELT encoder */
/* Initialize CELT encoder */
err = celt_encoder_init(celt_enc, Fs, channels, st->arch);
if(err!=OPUS_OK)return OPUS_INTERNAL_ERROR;
celt_encoder_ctl(celt_enc, CELT_SET_SIGNALLING(0));
celt_encoder_ctl(celt_enc, OPUS_SET_COMPLEXITY(st->silk_mode.complexity));
st->use_vbr = 1;
/* Makes constrained VBR the default (safer for real-time use) */
st->vbr_constraint = 1;
st->user_bitrate_bps = OPUS_AUTO;
st->bitrate_bps = 3000+Fs*channels;
st->application = application;
st->signal_type = OPUS_AUTO;
st->user_bandwidth = OPUS_AUTO;
st->max_bandwidth = OPUS_BANDWIDTH_FULLBAND;
st->force_channels = OPUS_AUTO;
st->user_forced_mode = OPUS_AUTO;
st->voice_ratio = -1;
st->encoder_buffer = st->Fs/100;
st->lsb_depth = 24;
st->variable_duration = OPUS_FRAMESIZE_ARG;
/* Delay compensation of 4 ms (2.5 ms for SILK's extra look-ahead
+ 1.5 ms for SILK resamplers and stereo prediction) */
st->delay_compensation = st->Fs/250;
st->hybrid_stereo_width_Q14 = 1 << 14;
st->prev_HB_gain = Q15ONE;
st->variable_HP_smth2_Q15 = silk_LSHIFT( silk_lin2log( VARIABLE_HP_MIN_CUTOFF_HZ ), 8 );
st->first = 1;
st->mode = MODE_HYBRID;
st->bandwidth = OPUS_BANDWIDTH_FULLBAND;
#ifndef DISABLE_FLOAT_API
tonality_analysis_init(&st->analysis);
#endif
return OPUS_OK;
}
static unsigned char gen_toc(int mode, int framerate, int bandwidth, int channels)
{
int period;
unsigned char toc;
period = 0;
while (framerate < 400)
{
framerate <<= 1;
period++;
}
if (mode == MODE_SILK_ONLY)
{
toc = (bandwidth-OPUS_BANDWIDTH_NARROWBAND)<<5;
toc |= (period-2)<<3;
} else if (mode == MODE_CELT_ONLY)
{
int tmp = bandwidth-OPUS_BANDWIDTH_MEDIUMBAND;
if (tmp < 0)
tmp = 0;
toc = 0x80;
toc |= tmp << 5;
toc |= period<<3;
} else /* Hybrid */
{
toc = 0x60;
toc |= (bandwidth-OPUS_BANDWIDTH_SUPERWIDEBAND)<<4;
toc |= (period-2)<<3;
}
toc |= (channels==2)<<2;
return toc;
}
#ifndef FIXED_POINT
static void silk_biquad_float(
const opus_val16 *in, /* I: Input signal */
const opus_int32 *B_Q28, /* I: MA coefficients [3] */
const opus_int32 *A_Q28, /* I: AR coefficients [2] */
opus_val32 *S, /* I/O: State vector [2] */
opus_val16 *out, /* O: Output signal */
const opus_int32 len, /* I: Signal length (must be even) */
int stride
)
{
/* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */
opus_int k;
opus_val32 vout;
opus_val32 inval;
opus_val32 A[2], B[3];
A[0] = (opus_val32)(A_Q28[0] * (1.f/((opus_int32)1<<28)));
A[1] = (opus_val32)(A_Q28[1] * (1.f/((opus_int32)1<<28)));
B[0] = (opus_val32)(B_Q28[0] * (1.f/((opus_int32)1<<28)));
B[1] = (opus_val32)(B_Q28[1] * (1.f/((opus_int32)1<<28)));
B[2] = (opus_val32)(B_Q28[2] * (1.f/((opus_int32)1<<28)));
/* Negate A_Q28 values and split in two parts */
for( k = 0; k < len; k++ ) {
/* S[ 0 ], S[ 1 ]: Q12 */
inval = in[ k*stride ];
vout = S[ 0 ] + B[0]*inval;
S[ 0 ] = S[1] - vout*A[0] + B[1]*inval;
S[ 1 ] = - vout*A[1] + B[2]*inval + VERY_SMALL;
/* Scale back to Q0 and saturate */
out[ k*stride ] = vout;
}
}
#endif
static void hp_cutoff(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
{
opus_int32 B_Q28[ 3 ], A_Q28[ 2 ];
opus_int32 Fc_Q19, r_Q28, r_Q22;
silk_assert( cutoff_Hz <= silk_int32_MAX / SILK_FIX_CONST( 1.5 * 3.14159 / 1000, 19 ) );
Fc_Q19 = silk_DIV32_16( silk_SMULBB( SILK_FIX_CONST( 1.5 * 3.14159 / 1000, 19 ), cutoff_Hz ), Fs/1000 );
silk_assert( Fc_Q19 > 0 && Fc_Q19 < 32768 );
r_Q28 = SILK_FIX_CONST( 1.0, 28 ) - silk_MUL( SILK_FIX_CONST( 0.92, 9 ), Fc_Q19 );
/* b = r * [ 1; -2; 1 ]; */
/* a = [ 1; -2 * r * ( 1 - 0.5 * Fc^2 ); r^2 ]; */
B_Q28[ 0 ] = r_Q28;
B_Q28[ 1 ] = silk_LSHIFT( -r_Q28, 1 );
B_Q28[ 2 ] = r_Q28;
/* -r * ( 2 - Fc * Fc ); */
r_Q22 = silk_RSHIFT( r_Q28, 6 );
A_Q28[ 0 ] = silk_SMULWW( r_Q22, silk_SMULWW( Fc_Q19, Fc_Q19 ) - SILK_FIX_CONST( 2.0, 22 ) );
A_Q28[ 1 ] = silk_SMULWW( r_Q22, r_Q22 );
#ifdef FIXED_POINT
silk_biquad_alt( in, B_Q28, A_Q28, hp_mem, out, len, channels );
if( channels == 2 ) {
silk_biquad_alt( in+1, B_Q28, A_Q28, hp_mem+2, out+1, len, channels );
}
#else
silk_biquad_float( in, B_Q28, A_Q28, hp_mem, out, len, channels );
if( channels == 2 ) {
silk_biquad_float( in+1, B_Q28, A_Q28, hp_mem+2, out+1, len, channels );
}
#endif
}
#ifdef FIXED_POINT
static void dc_reject(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
{
int c, i;
int shift;
/* Approximates -round(log2(4.*cutoff_Hz/Fs)) */
shift=celt_ilog2(Fs/(cutoff_Hz*3));
for (c=0;c<channels;c++)
{
for (i=0;i<len;i++)
{
opus_val32 x, tmp, y;
x = SHL32(EXTEND32(in[channels*i+c]), 15);
/* First stage */
tmp = x-hp_mem[2*c];
hp_mem[2*c] = hp_mem[2*c] + PSHR32(x - hp_mem[2*c], shift);
/* Second stage */
y = tmp - hp_mem[2*c+1];
hp_mem[2*c+1] = hp_mem[2*c+1] + PSHR32(tmp - hp_mem[2*c+1], shift);
out[channels*i+c] = EXTRACT16(SATURATE(PSHR32(y, 15), 32767));
}
}
}
#else
static void dc_reject(const opus_val16 *in, opus_int32 cutoff_Hz, opus_val16 *out, opus_val32 *hp_mem, int len, int channels, opus_int32 Fs)
{
int c, i;
float coef;
coef = 4.0f*cutoff_Hz/Fs;
for (c=0;c<channels;c++)
{
for (i=0;i<len;i++)
{
opus_val32 x, tmp, y;
x = in[channels*i+c];
/* First stage */
tmp = x-hp_mem[2*c];
hp_mem[2*c] = hp_mem[2*c] + coef*(x - hp_mem[2*c]) + VERY_SMALL;
/* Second stage */
y = tmp - hp_mem[2*c+1];
hp_mem[2*c+1] = hp_mem[2*c+1] + coef*(tmp - hp_mem[2*c+1]) + VERY_SMALL;
out[channels*i+c] = y;
}
}
}
#endif
static void stereo_fade(const opus_val16 *in, opus_val16 *out, opus_val16 g1, opus_val16 g2,
int overlap48, int frame_size, int channels, const opus_val16 *window, opus_int32 Fs)
{
int i;
int overlap;
int inc;
inc = 48000/Fs;
overlap=overlap48/inc;
g1 = Q15ONE-g1;
g2 = Q15ONE-g2;
for (i=0;i<overlap;i++)
{
opus_val32 diff;
opus_val16 g, w;
w = MULT16_16_Q15(window[i*inc], window[i*inc]);
g = SHR32(MAC16_16(MULT16_16(w,g2),
Q15ONE-w, g1), 15);
diff = EXTRACT16(HALF32((opus_val32)in[i*channels] - (opus_val32)in[i*channels+1]));
diff = MULT16_16_Q15(g, diff);
out[i*channels] = out[i*channels] - diff;
out[i*channels+1] = out[i*channels+1] + diff;
}
for (;i<frame_size;i++)
{
opus_val32 diff;
diff = EXTRACT16(HALF32((opus_val32)in[i*channels] - (opus_val32)in[i*channels+1]));
diff = MULT16_16_Q15(g2, diff);
out[i*channels] = out[i*channels] - diff;
out[i*channels+1] = out[i*channels+1] + diff;
}
}
static void gain_fade(const opus_val16 *in, opus_val16 *out, opus_val16 g1, opus_val16 g2,
int overlap48, int frame_size, int channels, const opus_val16 *window, opus_int32 Fs)
{
int i;
int inc;
int overlap;
int c;
inc = 48000/Fs;
overlap=overlap48/inc;
if (channels==1)
{
for (i=0;i<overlap;i++)
{
opus_val16 g, w;
w = MULT16_16_Q15(window[i*inc], window[i*inc]);
g = SHR32(MAC16_16(MULT16_16(w,g2),
Q15ONE-w, g1), 15);
out[i] = MULT16_16_Q15(g, in[i]);
}
} else {
for (i=0;i<overlap;i++)
{
opus_val16 g, w;
w = MULT16_16_Q15(window[i*inc], window[i*inc]);
g = SHR32(MAC16_16(MULT16_16(w,g2),
Q15ONE-w, g1), 15);
out[i*2] = MULT16_16_Q15(g, in[i*2]);
out[i*2+1] = MULT16_16_Q15(g, in[i*2+1]);
}
}
c=0;do {
for (i=overlap;i<frame_size;i++)
{
out[i*channels+c] = MULT16_16_Q15(g2, in[i*channels+c]);
}
}
while (++c<channels);
}
OpusEncoder *opus_encoder_create(opus_int32 Fs, int channels, int application, int *error)
{
int ret;
OpusEncoder *st;
if((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)||(channels!=1&&channels!=2)||
(application != OPUS_APPLICATION_VOIP && application != OPUS_APPLICATION_AUDIO
&& application != OPUS_APPLICATION_RESTRICTED_LOWDELAY))
{
if (error)
*error = OPUS_BAD_ARG;
return NULL;
}
st = (OpusEncoder *)opus_alloc(opus_encoder_get_size(channels));
if (st == NULL)
{
if (error)
*error = OPUS_ALLOC_FAIL;
return NULL;
}
ret = opus_encoder_init(st, Fs, channels, application);
if (error)
*error = ret;
if (ret != OPUS_OK)
{
opus_free(st);
st = NULL;
}
return st;
}
static opus_int32 user_bitrate_to_bitrate(OpusEncoder *st, int frame_size, int max_data_bytes)
{
if(!frame_size)frame_size=st->Fs/400;
if (st->user_bitrate_bps==OPUS_AUTO)
return 60*st->Fs/frame_size + st->Fs*st->channels;
else if (st->user_bitrate_bps==OPUS_BITRATE_MAX)
return max_data_bytes*8*st->Fs/frame_size;
else
return st->user_bitrate_bps;
}
#ifndef DISABLE_FLOAT_API
/* Don't use more than 60 ms for the frame size analysis */
#define MAX_DYNAMIC_FRAMESIZE 24
/* Estimates how much the bitrate will be boosted based on the sub-frame energy */
static float transient_boost(const float *E, const float *E_1, int LM, int maxM)
{
int i;
int M;
float sumE=0, sumE_1=0;
float metric;
M = IMIN(maxM, (1<<LM)+1);
for (i=0;i<M;i++)
{
sumE += E[i];
sumE_1 += E_1[i];
}
metric = sumE*sumE_1/(M*M);
/*if (LM==3)
printf("%f\n", metric);*/
/*return metric>10 ? 1 : 0;*/
/*return MAX16(0,1-exp(-.25*(metric-2.)));*/
return MIN16(1,(float)sqrt(MAX16(0,.05f*(metric-2))));
}
/* Viterbi decoding trying to find the best frame size combination using look-ahead
State numbering:
0: unused
1: 2.5 ms
2: 5 ms (#1)
3: 5 ms (#2)
4: 10 ms (#1)
5: 10 ms (#2)
6: 10 ms (#3)
7: 10 ms (#4)
8: 20 ms (#1)
9: 20 ms (#2)
10: 20 ms (#3)
11: 20 ms (#4)
12: 20 ms (#5)
13: 20 ms (#6)
14: 20 ms (#7)
15: 20 ms (#8)
*/
static int transient_viterbi(const float *E, const float *E_1, int N, int frame_cost, int rate)
{
int i;
float cost[MAX_DYNAMIC_FRAMESIZE][16];
int states[MAX_DYNAMIC_FRAMESIZE][16];
float best_cost;
int best_state;
float factor;
/* Take into account that we damp VBR in the 32 kb/s to 64 kb/s range. */
if (rate<80)
factor=0;
else if (rate>160)
factor=1;
else
factor = (rate-80.f)/80.f;
/* Makes variable framesize less aggressive at lower bitrates, but I can't
find any valid theoretical justification for this (other than it seems
to help) */
for (i=0;i<16;i++)
{
/* Impossible state */
states[0][i] = -1;
cost[0][i] = 1e10;
}
for (i=0;i<4;i++)
{
cost[0][1<<i] = (frame_cost + rate*(1<<i))*(1+factor*transient_boost(E, E_1, i, N+1));
states[0][1<<i] = i;
}
for (i=1;i<N;i++)
{
int j;
/* Follow continuations */
for (j=2;j<16;j++)
{
cost[i][j] = cost[i-1][j-1];
states[i][j] = j-1;
}
/* New frames */
for(j=0;j<4;j++)
{
int k;
float min_cost;
float curr_cost;
states[i][1<<j] = 1;
min_cost = cost[i-1][1];
for(k=1;k<4;k++)
{
float tmp = cost[i-1][(1<<(k+1))-1];
if (tmp < min_cost)
{
states[i][1<<j] = (1<<(k+1))-1;
min_cost = tmp;
}
}
curr_cost = (frame_cost + rate*(1<<j))*(1+factor*transient_boost(E+i, E_1+i, j, N-i+1));
cost[i][1<<j] = min_cost;
/* If part of the frame is outside the analysis window, only count part of the cost */
if (N-i < (1<<j))
cost[i][1<<j] += curr_cost*(float)(N-i)/(1<<j);
else
cost[i][1<<j] += curr_cost;
}
}
best_state=1;
best_cost = cost[N-1][1];
/* Find best end state (doesn't force a frame to end at N-1) */
for (i=2;i<16;i++)
{
if (cost[N-1][i]<best_cost)
{
best_cost = cost[N-1][i];
best_state = i;
}
}
/* Follow transitions back */
for (i=N-1;i>=0;i--)
{
/*printf("%d ", best_state);*/
best_state = states[i][best_state];
}
/*printf("%d\n", best_state);*/
return best_state;
}
static int optimize_framesize(const void *x, int len, int C, opus_int32 Fs,
int bitrate, opus_val16 tonality, float *mem, int buffering,
downmix_func downmix)
{
int N;
int i;
float e[MAX_DYNAMIC_FRAMESIZE+4];
float e_1[MAX_DYNAMIC_FRAMESIZE+3];
opus_val32 memx;
int bestLM=0;
int subframe;
int pos;
int offset;
VARDECL(opus_val32, sub);
subframe = Fs/400;
ALLOC(sub, subframe, opus_val32);
e[0]=mem[0];
e_1[0]=1.f/(EPSILON+mem[0]);
if (buffering)
{
/* Consider the CELT delay when not in restricted-lowdelay */
/* We assume the buffering is between 2.5 and 5 ms */
offset = 2*subframe - buffering;
celt_assert(offset>=0 && offset <= subframe);
len -= offset;
e[1]=mem[1];
e_1[1]=1.f/(EPSILON+mem[1]);
e[2]=mem[2];
e_1[2]=1.f/(EPSILON+mem[2]);
pos = 3;
} else {
pos=1;
offset=0;
}
N=IMIN(len/subframe, MAX_DYNAMIC_FRAMESIZE);
/* Just silencing a warning, it's really initialized later */
memx = 0;
for (i=0;i<N;i++)
{
float tmp;
opus_val32 tmpx;
int j;
tmp=EPSILON;
downmix(x, sub, subframe, i*subframe+offset, 0, -2, C);
if (i==0)
memx = sub[0];
for (j=0;j<subframe;j++)
{
tmpx = sub[j];
tmp += (tmpx-memx)*(float)(tmpx-memx);
memx = tmpx;
}
e[i+pos] = tmp;
e_1[i+pos] = 1.f/tmp;
}
/* Hack to get 20 ms working with APPLICATION_AUDIO
The real problem is that the corresponding memory needs to use 1.5 ms
from this frame and 1 ms from the next frame */
e[i+pos] = e[i+pos-1];
if (buffering)
N=IMIN(MAX_DYNAMIC_FRAMESIZE, N+2);
bestLM = transient_viterbi(e, e_1, N, (int)((1.f+.5f*tonality)*(60*C+40)), bitrate/400);
mem[0] = e[1<<bestLM];
if (buffering)
{
mem[1] = e[(1<<bestLM)+1];
mem[2] = e[(1<<bestLM)+2];
}
return bestLM;
}
#endif
#ifndef DISABLE_FLOAT_API
#ifdef FIXED_POINT
#define PCM2VAL(x) FLOAT2INT16(x)
#else
#define PCM2VAL(x) SCALEIN(x)
#endif
void downmix_float(const void *_x, opus_val32 *sub, int subframe, int offset, int c1, int c2, int C)
{
const float *x;
opus_val32 scale;
int j;
x = (const float *)_x;
for (j=0;j<subframe;j++)
sub[j] = PCM2VAL(x[(j+offset)*C+c1]);
if (c2>-1)
{
for (j=0;j<subframe;j++)
sub[j] += PCM2VAL(x[(j+offset)*C+c2]);
} else if (c2==-2)
{
int c;
for (c=1;c<C;c++)
{
for (j=0;j<subframe;j++)
sub[j] += PCM2VAL(x[(j+offset)*C+c]);
}
}
#ifdef FIXED_POINT
scale = (1<<SIG_SHIFT);
#else
scale = 1.f;
#endif
if (C==-2)
scale /= C;
else
scale /= 2;
for (j=0;j<subframe;j++)
sub[j] *= scale;
}
#endif
void downmix_int(const void *_x, opus_val32 *sub, int subframe, int offset, int c1, int c2, int C)
{
const opus_int16 *x;
opus_val32 scale;
int j;
x = (const opus_int16 *)_x;
for (j=0;j<subframe;j++)
sub[j] = x[(j+offset)*C+c1];
if (c2>-1)
{
for (j=0;j<subframe;j++)
sub[j] += x[(j+offset)*C+c2];
} else if (c2==-2)
{
int c;
for (c=1;c<C;c++)
{
for (j=0;j<subframe;j++)
sub[j] += x[(j+offset)*C+c];
}
}
#ifdef FIXED_POINT
scale = (1<<SIG_SHIFT);
#else
scale = 1.f/32768;
#endif
if (C==-2)
scale /= C;
else
scale /= 2;
for (j=0;j<subframe;j++)
sub[j] *= scale;
}
opus_int32 frame_size_select(opus_int32 frame_size, int variable_duration, opus_int32 Fs)
{
int new_size;
if (frame_size<Fs/400)
return -1;
if (variable_duration == OPUS_FRAMESIZE_ARG)
new_size = frame_size;
else if (variable_duration == OPUS_FRAMESIZE_VARIABLE)
new_size = Fs/50;
else if (variable_duration >= OPUS_FRAMESIZE_2_5_MS && variable_duration <= OPUS_FRAMESIZE_60_MS)
new_size = IMIN(3*Fs/50, (Fs/400)<<(variable_duration-OPUS_FRAMESIZE_2_5_MS));
else
return -1;
if (new_size>frame_size)
return -1;
if (400*new_size!=Fs && 200*new_size!=Fs && 100*new_size!=Fs &&
50*new_size!=Fs && 25*new_size!=Fs && 50*new_size!=3*Fs)
return -1;
return new_size;
}
opus_int32 compute_frame_size(const void *analysis_pcm, int frame_size,
int variable_duration, int C, opus_int32 Fs, int bitrate_bps,
int delay_compensation, downmix_func downmix
#ifndef DISABLE_FLOAT_API
, float *subframe_mem
#endif
)
{
#ifndef DISABLE_FLOAT_API
if (variable_duration == OPUS_FRAMESIZE_VARIABLE && frame_size >= Fs/200)
{
int LM = 3;
LM = optimize_framesize(analysis_pcm, frame_size, C, Fs, bitrate_bps,
0, subframe_mem, delay_compensation, downmix);
while ((Fs/400<<LM)>frame_size)
LM--;
frame_size = (Fs/400<<LM);
} else
#else
(void)analysis_pcm;
(void)C;
(void)bitrate_bps;
(void)delay_compensation;
(void)downmix;
#endif
{
frame_size = frame_size_select(frame_size, variable_duration, Fs);
}
if (frame_size<0)
return -1;
return frame_size;
}
opus_val16 compute_stereo_width(const opus_val16 *pcm, int frame_size, opus_int32 Fs, StereoWidthState *mem)
{
opus_val32 xx, xy, yy;
opus_val16 sqrt_xx, sqrt_yy;
opus_val16 qrrt_xx, qrrt_yy;
int frame_rate;
int i;
opus_val16 short_alpha;
frame_rate = Fs/frame_size;
short_alpha = Q15ONE - MULT16_16(25, Q15ONE)/IMAX(50,frame_rate);
xx=xy=yy=0;
/* Unroll by 4. The frame size is always a multiple of 4 *except* for
2.5 ms frames at 12 kHz. Since this setting is very rare (and very
stupid), we just discard the last two samples. */
for (i=0;i<frame_size-3;i+=4)
{
opus_val32 pxx=0;
opus_val32 pxy=0;
opus_val32 pyy=0;
opus_val16 x, y;
x = pcm[2*i];
y = pcm[2*i+1];
pxx = SHR32(MULT16_16(x,x),2);
pxy = SHR32(MULT16_16(x,y),2);
pyy = SHR32(MULT16_16(y,y),2);
x = pcm[2*i+2];
y = pcm[2*i+3];
pxx += SHR32(MULT16_16(x,x),2);
pxy += SHR32(MULT16_16(x,y),2);
pyy += SHR32(MULT16_16(y,y),2);
x = pcm[2*i+4];
y = pcm[2*i+5];
pxx += SHR32(MULT16_16(x,x),2);
pxy += SHR32(MULT16_16(x,y),2);
pyy += SHR32(MULT16_16(y,y),2);
x = pcm[2*i+6];
y = pcm[2*i+7];
pxx += SHR32(MULT16_16(x,x),2);
pxy += SHR32(MULT16_16(x,y),2);
pyy += SHR32(MULT16_16(y,y),2);
xx += SHR32(pxx, 10);
xy += SHR32(pxy, 10);
yy += SHR32(pyy, 10);
}
mem->XX += MULT16_32_Q15(short_alpha, xx-mem->XX);
mem->XY += MULT16_32_Q15(short_alpha, xy-mem->XY);
mem->YY += MULT16_32_Q15(short_alpha, yy-mem->YY);
mem->XX = MAX32(0, mem->XX);
mem->XY = MAX32(0, mem->XY);
mem->YY = MAX32(0, mem->YY);
if (MAX32(mem->XX, mem->YY)>QCONST16(8e-4f, 18))
{
opus_val16 corr;
opus_val16 ldiff;
opus_val16 width;
sqrt_xx = celt_sqrt(mem->XX);
sqrt_yy = celt_sqrt(mem->YY);
qrrt_xx = celt_sqrt(sqrt_xx);
qrrt_yy = celt_sqrt(sqrt_yy);
/* Inter-channel correlation */
mem->XY = MIN32(mem->XY, sqrt_xx*sqrt_yy);
corr = SHR32(frac_div32(mem->XY,EPSILON+MULT16_16(sqrt_xx,sqrt_yy)),16);
/* Approximate loudness difference */
ldiff = MULT16_16(Q15ONE, ABS16(qrrt_xx-qrrt_yy))/(EPSILON+qrrt_xx+qrrt_yy);
width = MULT16_16_Q15(celt_sqrt(QCONST32(1.f,30)-MULT16_16(corr,corr)), ldiff);
/* Smoothing over one second */
mem->smoothed_width += (width-mem->smoothed_width)/frame_rate;
/* Peak follower */
mem->max_follower = MAX16(mem->max_follower-QCONST16(.02f,15)/frame_rate, mem->smoothed_width);
}
/*printf("%f %f %f %f %f ", corr/(float)Q15ONE, ldiff/(float)Q15ONE, width/(float)Q15ONE, mem->smoothed_width/(float)Q15ONE, mem->max_follower/(float)Q15ONE);*/
return EXTRACT16(MIN32(Q15ONE, MULT16_16(20, mem->max_follower)));
}
opus_int32 opus_encode_native(OpusEncoder *st, const opus_val16 *pcm, int frame_size,
unsigned char *data, opus_int32 out_data_bytes, int lsb_depth,
const void *analysis_pcm, opus_int32 analysis_size, int c1, int c2,
int analysis_channels, downmix_func downmix, int float_api)
{
void *silk_enc;
CELTEncoder *celt_enc;
int i;
int ret=0;
opus_int32 nBytes;
ec_enc enc;
int bytes_target;
int prefill=0;
int start_band = 0;
int redundancy = 0;
int redundancy_bytes = 0; /* Number of bytes to use for redundancy frame */
int celt_to_silk = 0;
VARDECL(opus_val16, pcm_buf);
int nb_compr_bytes;
int to_celt = 0;
opus_uint32 redundant_rng = 0;
int cutoff_Hz, hp_freq_smth1;
int voice_est; /* Probability of voice in Q7 */
opus_int32 equiv_rate;
int delay_compensation;
int frame_rate;
opus_int32 max_rate; /* Max bitrate we're allowed to use */
int curr_bandwidth;
opus_val16 HB_gain;
opus_int32 max_data_bytes; /* Max number of bytes we're allowed to use */
int total_buffer;
opus_val16 stereo_width;
const CELTMode *celt_mode;
#ifndef DISABLE_FLOAT_API
AnalysisInfo analysis_info;
int analysis_read_pos_bak=-1;
int analysis_read_subframe_bak=-1;
#endif
VARDECL(opus_val16, tmp_prefill);
ALLOC_STACK;
max_data_bytes = IMIN(1276, out_data_bytes);
st->rangeFinal = 0;
if ((!st->variable_duration && 400*frame_size != st->Fs && 200*frame_size != st->Fs && 100*frame_size != st->Fs &&
50*frame_size != st->Fs && 25*frame_size != st->Fs && 50*frame_size != 3*st->Fs)
|| (400*frame_size < st->Fs)
|| max_data_bytes<=0
)
{
RESTORE_STACK;
return OPUS_BAD_ARG;
}
silk_enc = (char*)st+st->silk_enc_offset;
celt_enc = (CELTEncoder*)((char*)st+st->celt_enc_offset);
if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
delay_compensation = 0;
else
delay_compensation = st->delay_compensation;
lsb_depth = IMIN(lsb_depth, st->lsb_depth);
celt_encoder_ctl(celt_enc, CELT_GET_MODE(&celt_mode));