summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFrederik M J Vestre <freqmod@gmail.com>2012-07-26 14:38:32 +0200
committerBertrik Sikken <bertrik@sikken.nl>2012-09-20 20:47:44 +0200
commit1b8e3801b2444f6e466e1b7c09cfc51605e80fb3 (patch)
treebd1d6fe08452d388d0d160ec02e03963f3f9525d
parent72ebcbf73b4db911d517a66c820fdceccb8ec798 (diff)
downloadrockbox-1b8e3801b2444f6e466e1b7c09cfc51605e80fb3.tar.gz
rockbox-1b8e3801b2444f6e466e1b7c09cfc51605e80fb3.zip
Initial opus codec support
Synchronised with opus repo on github (https://github.com/freqmod/rockbox-opus) Status: * Seeking ported from speex, but fails on some cases (e.g. seek to granule 0) * ReplayGain parsing needs to be reworked, we do vorbis-style replaygain now. http://wiki.xiph.org/OggOpus#Comment_Header explicitly forbids these in favour of R128_TRACK_GAIN tag. * No optimisation yet, source files still nearly identical to opus upstream * Multi-stream opus files may not be parsed correctly Change-Id: Ia66f1027dc1d288083e3c57b2816700078376f9a Reviewed-on: http://gerrit.rockbox.org/300 Reviewed-by: Bertrik Sikken <bertrik@sikken.nl> Tested-by: Bertrik Sikken <bertrik@sikken.nl>
-rw-r--r--apps/filetypes.c1
-rw-r--r--lib/rbcodec/codecs/SOURCES1
-rw-r--r--lib/rbcodec/codecs/codecs.make3
-rw-r--r--lib/rbcodec/codecs/lib/codeclib.c2
-rw-r--r--lib/rbcodec/codecs/libopus/README.rockbox26
-rw-r--r--lib/rbcodec/codecs/libopus/SOURCES70
-rw-r--r--lib/rbcodec/codecs/libopus/celt/_kiss_fft_guts.h175
-rw-r--r--lib/rbcodec/codecs/libopus/celt/arch.h209
-rw-r--r--lib/rbcodec/codecs/libopus/celt/bands.c1302
-rw-r--r--lib/rbcodec/codecs/libopus/celt/bands.h95
-rw-r--r--lib/rbcodec/codecs/libopus/celt/celt.c2870
-rw-r--r--lib/rbcodec/codecs/libopus/celt/celt.h117
-rw-r--r--lib/rbcodec/codecs/libopus/celt/celt_lpc.c188
-rw-r--r--lib/rbcodec/codecs/libopus/celt/celt_lpc.h53
-rw-r--r--lib/rbcodec/codecs/libopus/celt/cwrs.c645
-rw-r--r--lib/rbcodec/codecs/libopus/celt/cwrs.h48
-rw-r--r--lib/rbcodec/codecs/libopus/celt/ecintrin.h87
-rw-r--r--lib/rbcodec/codecs/libopus/celt/entcode.c88
-rw-r--r--lib/rbcodec/codecs/libopus/celt/entcode.h116
-rw-r--r--lib/rbcodec/codecs/libopus/celt/entdec.c245
-rw-r--r--lib/rbcodec/codecs/libopus/celt/entdec.h100
-rw-r--r--lib/rbcodec/codecs/libopus/celt/entenc.c294
-rw-r--r--lib/rbcodec/codecs/libopus/celt/entenc.h110
-rw-r--r--lib/rbcodec/codecs/libopus/celt/fixed_generic.h129
-rw-r--r--lib/rbcodec/codecs/libopus/celt/float_cast.h140
-rw-r--r--lib/rbcodec/codecs/libopus/celt/kiss_fft.c722
-rw-r--r--lib/rbcodec/codecs/libopus/celt/kiss_fft.h139
-rw-r--r--lib/rbcodec/codecs/libopus/celt/laplace.c134
-rw-r--r--lib/rbcodec/codecs/libopus/celt/laplace.h48
-rw-r--r--lib/rbcodec/codecs/libopus/celt/mathops.c206
-rw-r--r--lib/rbcodec/codecs/libopus/celt/mathops.h237
-rw-r--r--lib/rbcodec/codecs/libopus/celt/mdct.c332
-rw-r--r--lib/rbcodec/codecs/libopus/celt/mdct.h70
-rw-r--r--lib/rbcodec/codecs/libopus/celt/mfrngcod.h48
-rw-r--r--lib/rbcodec/codecs/libopus/celt/modes.c430
-rw-r--r--lib/rbcodec/codecs/libopus/celt/modes.h83
-rw-r--r--lib/rbcodec/codecs/libopus/celt/os_support.h89
-rw-r--r--lib/rbcodec/codecs/libopus/celt/pitch.c410
-rw-r--r--lib/rbcodec/codecs/libopus/celt/pitch.h48
-rw-r--r--lib/rbcodec/codecs/libopus/celt/quant_bands.c567
-rw-r--r--lib/rbcodec/codecs/libopus/celt/quant_bands.h60
-rw-r--r--lib/rbcodec/codecs/libopus/celt/rate.c638
-rw-r--r--lib/rbcodec/codecs/libopus/celt/rate.h101
-rw-r--r--lib/rbcodec/codecs/libopus/celt/stack_alloc.h149
-rw-r--r--lib/rbcodec/codecs/libopus/celt/static_modes_fixed.h595
-rw-r--r--lib/rbcodec/codecs/libopus/celt/vq.c415
-rw-r--r--lib/rbcodec/codecs/libopus/celt/vq.h73
-rw-r--r--lib/rbcodec/codecs/libopus/libopus.make24
-rw-r--r--lib/rbcodec/codecs/libopus/ogg/framing.c1025
-rw-r--r--lib/rbcodec/codecs/libopus/ogg/ogg.h210
-rw-r--r--lib/rbcodec/codecs/libopus/ogg/os_types.h56
-rw-r--r--lib/rbcodec/codecs/libopus/opus.h882
-rw-r--r--lib/rbcodec/codecs/libopus/opus_config.h42
-rw-r--r--lib/rbcodec/codecs/libopus/opus_custom.h329
-rw-r--r--lib/rbcodec/codecs/libopus/opus_decoder.c999
-rw-r--r--lib/rbcodec/codecs/libopus/opus_defines.h644
-rw-r--r--lib/rbcodec/codecs/libopus/opus_header.c286
-rw-r--r--lib/rbcodec/codecs/libopus/opus_header.h51
-rw-r--r--lib/rbcodec/codecs/libopus/opus_private.h85
-rw-r--r--lib/rbcodec/codecs/libopus/opus_types.h159
-rw-r--r--lib/rbcodec/codecs/libopus/silk/API.h132
-rw-r--r--lib/rbcodec/codecs/libopus/silk/CNG.c167
-rw-r--r--lib/rbcodec/codecs/libopus/silk/Inlines.h188
-rw-r--r--lib/rbcodec/codecs/libopus/silk/LPC_analysis_filter.c85
-rw-r--r--lib/rbcodec/codecs/libopus/silk/LPC_inv_pred_gain.c154
-rw-r--r--lib/rbcodec/codecs/libopus/silk/MacroCount.h718
-rw-r--r--lib/rbcodec/codecs/libopus/silk/MacroDebug.h952
-rw-r--r--lib/rbcodec/codecs/libopus/silk/NLSF2A.c178
-rw-r--r--lib/rbcodec/codecs/libopus/silk/NLSF_VQ_weights_laroia.c80
-rw-r--r--lib/rbcodec/codecs/libopus/silk/NLSF_decode.c101
-rw-r--r--lib/rbcodec/codecs/libopus/silk/NLSF_stabilize.c142
-rw-r--r--lib/rbcodec/codecs/libopus/silk/NLSF_unpack.c55
-rw-r--r--lib/rbcodec/codecs/libopus/silk/PLC.c423
-rw-r--r--lib/rbcodec/codecs/libopus/silk/PLC.h61
-rw-r--r--lib/rbcodec/codecs/libopus/silk/SigProc_FIX.h589
-rw-r--r--lib/rbcodec/codecs/libopus/silk/bwexpander.c51
-rw-r--r--lib/rbcodec/codecs/libopus/silk/bwexpander_32.c50
-rw-r--r--lib/rbcodec/codecs/libopus/silk/code_signs.c115
-rw-r--r--lib/rbcodec/codecs/libopus/silk/control.h139
-rw-r--r--lib/rbcodec/codecs/libopus/silk/dec_API.c392
-rw-r--r--lib/rbcodec/codecs/libopus/silk/decode_core.c238
-rw-r--r--lib/rbcodec/codecs/libopus/silk/decode_frame.c128
-rw-r--r--lib/rbcodec/codecs/libopus/silk/decode_indices.c151
-rw-r--r--lib/rbcodec/codecs/libopus/silk/decode_parameters.c115
-rw-r--r--lib/rbcodec/codecs/libopus/silk/decode_pitch.c77
-rw-r--r--lib/rbcodec/codecs/libopus/silk/decode_pulses.c115
-rw-r--r--lib/rbcodec/codecs/libopus/silk/decoder_set_fs.c108
-rw-r--r--lib/rbcodec/codecs/libopus/silk/define.h235
-rw-r--r--lib/rbcodec/codecs/libopus/silk/errors.h98
-rw-r--r--lib/rbcodec/codecs/libopus/silk/gain_quant.c141
-rw-r--r--lib/rbcodec/codecs/libopus/silk/init_decoder.c56
-rw-r--r--lib/rbcodec/codecs/libopus/silk/lin2log.c46
-rw-r--r--lib/rbcodec/codecs/libopus/silk/log2lin.c56
-rw-r--r--lib/rbcodec/codecs/libopus/silk/macros.h135
-rw-r--r--lib/rbcodec/codecs/libopus/silk/main.h434
-rw-r--r--lib/rbcodec/codecs/libopus/silk/pitch_est_defines.h88
-rw-r--r--lib/rbcodec/codecs/libopus/silk/pitch_est_tables.c99
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler.c215
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_private.h88
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_private_AR2.c55
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_private_IIR_FIR.c103
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_private_down_FIR.c189
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_private_up2_HQ.c113
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_rom.c96
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_rom.h68
-rw-r--r--lib/rbcodec/codecs/libopus/silk/resampler_structs.h57
-rw-r--r--lib/rbcodec/codecs/libopus/silk/shell_coder.c151
-rw-r--r--lib/rbcodec/codecs/libopus/silk/sort.c154
-rw-r--r--lib/rbcodec/codecs/libopus/silk/stereo_MS_to_LR.c85
-rw-r--r--lib/rbcodec/codecs/libopus/silk/stereo_decode_pred.c73
-rw-r--r--lib/rbcodec/codecs/libopus/silk/structs.h324
-rw-r--r--lib/rbcodec/codecs/libopus/silk/sum_sqr_shift.c85
-rw-r--r--lib/rbcodec/codecs/libopus/silk/table_LSF_cos.c70
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables.h120
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables_LTP.c272
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_NB_MB.c159
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_WB.c198
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables_gain.c63
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables_other.c138
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables_pitch_lag.c69
-rw-r--r--lib/rbcodec/codecs/libopus/silk/tables_pulses_per_block.c264
-rw-r--r--lib/rbcodec/codecs/libopus/silk/typedef.h77
-rw-r--r--lib/rbcodec/codecs/opus.c461
-rw-r--r--lib/rbcodec/metadata/metadata.c3
-rw-r--r--lib/rbcodec/metadata/metadata.h1
-rw-r--r--lib/rbcodec/metadata/ogg.c14
-rw-r--r--lib/rbcodec/metadata/vorbis.c18
127 files changed, 28373 insertions, 2 deletions
diff --git a/apps/filetypes.c b/apps/filetypes.c
index b765e7a3b0..8a4cedc0ea 100644
--- a/apps/filetypes.c
+++ b/apps/filetypes.c
@@ -80,6 +80,7 @@ static const struct filetype inbuilt_filetypes[] = {
80 { "aif", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA }, 80 { "aif", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA },
81 { "aiff",FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA }, 81 { "aiff",FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA },
82 { "spx" ,FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA }, 82 { "spx" ,FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA },
83 { "opus",FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA },
83 { "sid", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA }, 84 { "sid", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA },
84 { "adx", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA }, 85 { "adx", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA },
85 { "nsf", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA }, 86 { "nsf", FILE_ATTR_AUDIO, Icon_Audio, VOICE_EXT_MPA },
diff --git a/lib/rbcodec/codecs/SOURCES b/lib/rbcodec/codecs/SOURCES
index db6e82c75f..039772cf9a 100644
--- a/lib/rbcodec/codecs/SOURCES
+++ b/lib/rbcodec/codecs/SOURCES
@@ -1,5 +1,6 @@
1/* decoders */ 1/* decoders */
2 2
3opus.c
3vorbis.c 4vorbis.c
4mpa.c 5mpa.c
5flac.c 6flac.c
diff --git a/lib/rbcodec/codecs/codecs.make b/lib/rbcodec/codecs/codecs.make
index 919aef2024..f56c032c60 100644
--- a/lib/rbcodec/codecs/codecs.make
+++ b/lib/rbcodec/codecs/codecs.make
@@ -51,6 +51,7 @@ include $(RBCODECLIB_DIR)/codecs/libgme/libsgc.make
51include $(RBCODECLIB_DIR)/codecs/libgme/libvgm.make 51include $(RBCODECLIB_DIR)/codecs/libgme/libvgm.make
52include $(RBCODECLIB_DIR)/codecs/libgme/libkss.make 52include $(RBCODECLIB_DIR)/codecs/libgme/libkss.make
53include $(RBCODECLIB_DIR)/codecs/libgme/libemu2413.make 53include $(RBCODECLIB_DIR)/codecs/libgme/libemu2413.make
54include $(RBCODECLIB_DIR)/codecs/libopus/libopus.make
54 55
55# compile flags for codecs 56# compile flags for codecs
56CODECFLAGS = $(CFLAGS) $(RBCODEC_CFLAGS) -fstrict-aliasing \ 57CODECFLAGS = $(CFLAGS) $(RBCODEC_CFLAGS) -fstrict-aliasing \
@@ -74,6 +75,7 @@ $(KSSLIB) : CODECFLAGS += -O2
74$(M4ALIB) : CODECFLAGS += -O3 75$(M4ALIB) : CODECFLAGS += -O3
75$(MUSEPACKLIB) : CODECFLAGS += -O1 76$(MUSEPACKLIB) : CODECFLAGS += -O1
76$(NSFLIB) : CODECFLAGS += -O2 77$(NSFLIB) : CODECFLAGS += -O2
78$(OPUSLIB) : CODECFLAGS += -O2
77$(PCMSLIB) : CODECFLAGS += -O1 79$(PCMSLIB) : CODECFLAGS += -O1
78$(RMLIB) : CODECFLAGS += -O3 80$(RMLIB) : CODECFLAGS += -O3
79$(SGCLIB) : CODECFLAGS += -O2 81$(SGCLIB) : CODECFLAGS += -O2
@@ -168,6 +170,7 @@ $(CODECDIR)/nsf.codec : $(CODECDIR)/libnsf.a $(CODECDIR)/libemu2413.a
168$(CODECDIR)/sgc.codec : $(CODECDIR)/libsgc.a $(CODECDIR)/libemu2413.a 170$(CODECDIR)/sgc.codec : $(CODECDIR)/libsgc.a $(CODECDIR)/libemu2413.a
169$(CODECDIR)/vgm.codec : $(CODECDIR)/libvgm.a $(CODECDIR)/libemu2413.a 171$(CODECDIR)/vgm.codec : $(CODECDIR)/libvgm.a $(CODECDIR)/libemu2413.a
170$(CODECDIR)/kss.codec : $(CODECDIR)/libkss.a $(CODECDIR)/libemu2413.a 172$(CODECDIR)/kss.codec : $(CODECDIR)/libkss.a $(CODECDIR)/libemu2413.a
173$(CODECDIR)/opus.codec : $(CODECDIR)/libopus.a
171 174
172$(CODECS): $(CODEC_LIBS) # this must be last in codec dependency list 175$(CODECS): $(CODEC_LIBS) # this must be last in codec dependency list
173 176
diff --git a/lib/rbcodec/codecs/lib/codeclib.c b/lib/rbcodec/codecs/lib/codeclib.c
index 09c96f921c..a12038eeb8 100644
--- a/lib/rbcodec/codecs/lib/codeclib.c
+++ b/lib/rbcodec/codecs/lib/codeclib.c
@@ -91,7 +91,7 @@ void* codec_realloc(void* ptr, size_t size)
91{ 91{
92 void* x; 92 void* x;
93 x = codec_malloc(size); 93 x = codec_malloc(size);
94 memcpy(x, ptr, size); 94 ci->memcpy(x, ptr, size);
95 codec_free(ptr); 95 codec_free(ptr);
96 return(x); 96 return(x);
97} 97}
diff --git a/lib/rbcodec/codecs/libopus/README.rockbox b/lib/rbcodec/codecs/libopus/README.rockbox
new file mode 100644
index 0000000000..8a5ef41fba
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/README.rockbox
@@ -0,0 +1,26 @@
1Libraries: Opus (snapshot) / Opus-tools (snapshot) / libogg 1.3
2Imported: September 15th, 2012
3
4Steps taken to adapt original opus/opus-tool/ogg source files to rockbox
5(useful when for example syncing a new snapshot)
6
7Opus:
8* copied .c/.h files from opus/src lib/rbcodec/codecs/libopus
9* copied .h files from opus/include to lib/rbcodec/codecs/libopus
10* copied .c/.h files from opus/celt to lib/rbcodec/codecs/libopus/celt
11* copied .c/.h files from opus/silk to lib/rbcodec/codecs/libopus/silk
12* renamed opus config.h file to opus_config.h and replaced #include "config.h",
13 for example
14find . -name "*.h" -print | xargs sed -i 's/include "config.h"/include "opus_config.h"/g'
15find . -name "*.c" -print | xargs sed -i 's/include "config.h"/include "opus_config.h"/g'
16
17Opus-tools:
18* copied src/opus_header.h and src/opus_header.c to lib/rbcodec/codecs/libopus
19* changed #include <ogg/ogg.h> to #include "ogg/ogg.h" in opus_header.c
20
21Ogg:
22* copied libogg/src/framing.c to lib/rbcodec/codecs/libopus/ogg
23* copied libogg/include/ogg.h to lib/rbcodec/codecs/libopus/ogg
24* changed #include "ogg/ogg.h" to #include "ogg.h" in framing.c
25* added os_config.h to lib/rbcodec/codecs/libopus/ogg
26
diff --git a/lib/rbcodec/codecs/libopus/SOURCES b/lib/rbcodec/codecs/libopus/SOURCES
new file mode 100644
index 0000000000..df3f014f38
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/SOURCES
@@ -0,0 +1,70 @@
1/* CELT sources */
2celt/bands.c
3celt/celt.c
4celt/celt_lpc.c
5celt/cwrs.c
6celt/entcode.c
7celt/entdec.c
8celt/entenc.c
9celt/kiss_fft.c
10celt/laplace.c
11celt/mathops.c
12celt/mdct.c
13celt/modes.c
14celt/pitch.c
15celt/quant_bands.c
16celt/rate.c
17celt/vq.c
18
19/* SILK sources */
20silk/bwexpander_32.c
21silk/bwexpander.c
22silk/CNG.c
23silk/code_signs.c
24silk/dec_API.c
25silk/decode_core.c
26silk/decode_frame.c
27silk/decode_indices.c
28silk/decode_parameters.c
29silk/decode_pitch.c
30silk/decode_pulses.c
31silk/decoder_set_fs.c
32silk/gain_quant.c
33silk/init_decoder.c
34silk/lin2log.c
35silk/log2lin.c
36silk/LPC_analysis_filter.c
37silk/LPC_inv_pred_gain.c
38silk/NLSF2A.c
39silk/NLSF_decode.c
40silk/NLSF_stabilize.c
41silk/NLSF_unpack.c
42silk/NLSF_VQ_weights_laroia.c
43silk/pitch_est_tables.c
44silk/PLC.c
45silk/resampler.c
46silk/resampler_private_AR2.c
47silk/resampler_private_down_FIR.c
48silk/resampler_private_IIR_FIR.c
49silk/resampler_private_up2_HQ.c
50silk/resampler_rom.c
51silk/shell_coder.c
52silk/sort.c
53silk/stereo_decode_pred.c
54silk/stereo_MS_to_LR.c
55silk/sum_sqr_shift.c
56silk/table_LSF_cos.c
57silk/tables_gain.c
58silk/tables_LTP.c
59silk/tables_NLSF_CB_NB_MB.c
60silk/tables_NLSF_CB_WB.c
61silk/tables_other.c
62silk/tables_pitch_lag.c
63silk/tables_pulses_per_block.c
64
65/* OPUS sources */
66opus_decoder.c
67opus_header.c
68
69/* OGG sources */
70ogg/framing.c
diff --git a/lib/rbcodec/codecs/libopus/celt/_kiss_fft_guts.h b/lib/rbcodec/codecs/libopus/celt/_kiss_fft_guts.h
new file mode 100644
index 0000000000..33e62c6b3d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/_kiss_fft_guts.h
@@ -0,0 +1,175 @@
1/*Copyright (c) 2003-2004, Mark Borgerding
2
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are met:
7
8 * Redistributions of source code must retain the above copyright notice,
9 this list of conditions and the following disclaimer.
10 * Redistributions in binary form must reproduce the above copyright notice,
11 this list of conditions and the following disclaimer in the
12 documentation and/or other materials provided with the distribution.
13
14 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
18 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
19 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
20 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
22 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
23 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24 POSSIBILITY OF SUCH DAMAGE.*/
25
26#ifndef KISS_FFT_GUTS_H
27#define KISS_FFT_GUTS_H
28
29#define MIN(a,b) ((a)<(b) ? (a):(b))
30#define MAX(a,b) ((a)>(b) ? (a):(b))
31
32/* kiss_fft.h
33 defines kiss_fft_scalar as either short or a float type
34 and defines
35 typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; */
36#include "kiss_fft.h"
37
38/*
39 Explanation of macros dealing with complex math:
40
41 C_MUL(m,a,b) : m = a*b
42 C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise
43 C_SUB( res, a,b) : res = a - b
44 C_SUBFROM( res , a) : res -= a
45 C_ADDTO( res , a) : res += a
46 * */
47#ifdef FIXED_POINT
48#include "arch.h"
49
50
51#define SAMP_MAX 2147483647
52#define TWID_MAX 32767
53#define TRIG_UPSCALE 1
54
55#define SAMP_MIN -SAMP_MAX
56
57
58# define S_MUL(a,b) MULT16_32_Q15(b, a)
59
60# define C_MUL(m,a,b) \
61 do{ (m).r = SUB32(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)); \
62 (m).i = ADD32(S_MUL((a).r,(b).i) , S_MUL((a).i,(b).r)); }while(0)
63
64# define C_MULC(m,a,b) \
65 do{ (m).r = ADD32(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)); \
66 (m).i = SUB32(S_MUL((a).i,(b).r) , S_MUL((a).r,(b).i)); }while(0)
67
68# define C_MUL4(m,a,b) \
69 do{ (m).r = SHR32(SUB32(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)),2); \
70 (m).i = SHR32(ADD32(S_MUL((a).r,(b).i) , S_MUL((a).i,(b).r)),2); }while(0)
71
72# define C_MULBYSCALAR( c, s ) \
73 do{ (c).r = S_MUL( (c).r , s ) ;\
74 (c).i = S_MUL( (c).i , s ) ; }while(0)
75
76# define DIVSCALAR(x,k) \
77 (x) = S_MUL( x, (TWID_MAX-((k)>>1))/(k)+1 )
78
79# define C_FIXDIV(c,div) \
80 do { DIVSCALAR( (c).r , div); \
81 DIVSCALAR( (c).i , div); }while (0)
82
83#define C_ADD( res, a,b)\
84 do {(res).r=ADD32((a).r,(b).r); (res).i=ADD32((a).i,(b).i); \
85 }while(0)
86#define C_SUB( res, a,b)\
87 do {(res).r=SUB32((a).r,(b).r); (res).i=SUB32((a).i,(b).i); \
88 }while(0)
89#define C_ADDTO( res , a)\
90 do {(res).r = ADD32((res).r, (a).r); (res).i = ADD32((res).i,(a).i);\
91 }while(0)
92
93#define C_SUBFROM( res , a)\
94 do {(res).r = ADD32((res).r,(a).r); (res).i = SUB32((res).i,(a).i); \
95 }while(0)
96
97#else /* not FIXED_POINT*/
98
99# define S_MUL(a,b) ( (a)*(b) )
100#define C_MUL(m,a,b) \
101 do{ (m).r = (a).r*(b).r - (a).i*(b).i;\
102 (m).i = (a).r*(b).i + (a).i*(b).r; }while(0)
103#define C_MULC(m,a,b) \
104 do{ (m).r = (a).r*(b).r + (a).i*(b).i;\
105 (m).i = (a).i*(b).r - (a).r*(b).i; }while(0)
106
107#define C_MUL4(m,a,b) C_MUL(m,a,b)
108
109# define C_FIXDIV(c,div) /* NOOP */
110# define C_MULBYSCALAR( c, s ) \
111 do{ (c).r *= (s);\
112 (c).i *= (s); }while(0)
113#endif
114
115#ifndef CHECK_OVERFLOW_OP
116# define CHECK_OVERFLOW_OP(a,op,b) /* noop */
117#endif
118
119#ifndef C_ADD
120#define C_ADD( res, a,b)\
121 do { \
122 CHECK_OVERFLOW_OP((a).r,+,(b).r)\
123 CHECK_OVERFLOW_OP((a).i,+,(b).i)\
124 (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \
125 }while(0)
126#define C_SUB( res, a,b)\
127 do { \
128 CHECK_OVERFLOW_OP((a).r,-,(b).r)\
129 CHECK_OVERFLOW_OP((a).i,-,(b).i)\
130 (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \
131 }while(0)
132#define C_ADDTO( res , a)\
133 do { \
134 CHECK_OVERFLOW_OP((res).r,+,(a).r)\
135 CHECK_OVERFLOW_OP((res).i,+,(a).i)\
136 (res).r += (a).r; (res).i += (a).i;\
137 }while(0)
138
139#define C_SUBFROM( res , a)\
140 do {\
141 CHECK_OVERFLOW_OP((res).r,-,(a).r)\
142 CHECK_OVERFLOW_OP((res).i,-,(a).i)\
143 (res).r -= (a).r; (res).i -= (a).i; \
144 }while(0)
145#endif /* C_ADD defined */
146
147#ifdef FIXED_POINT
148/*# define KISS_FFT_COS(phase) TRIG_UPSCALE*floor(MIN(32767,MAX(-32767,.5+32768 * cos (phase))))
149# define KISS_FFT_SIN(phase) TRIG_UPSCALE*floor(MIN(32767,MAX(-32767,.5+32768 * sin (phase))))*/
150# define KISS_FFT_COS(phase) floor(.5+TWID_MAX*cos (phase))
151# define KISS_FFT_SIN(phase) floor(.5+TWID_MAX*sin (phase))
152# define HALF_OF(x) ((x)>>1)
153#elif defined(USE_SIMD)
154# define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) )
155# define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) )
156# define HALF_OF(x) ((x)*_mm_set1_ps(.5f))
157#else
158# define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase)
159# define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase)
160# define HALF_OF(x) ((x)*.5f)
161#endif
162
163#define kf_cexp(x,phase) \
164 do{ \
165 (x)->r = KISS_FFT_COS(phase);\
166 (x)->i = KISS_FFT_SIN(phase);\
167 }while(0)
168
169#define kf_cexp2(x,phase) \
170 do{ \
171 (x)->r = TRIG_UPSCALE*celt_cos_norm((phase));\
172 (x)->i = TRIG_UPSCALE*celt_cos_norm((phase)-32768);\
173}while(0)
174
175#endif /* KISS_FFT_GUTS_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/arch.h b/lib/rbcodec/codecs/libopus/celt/arch.h
new file mode 100644
index 0000000000..03cda40f69
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/arch.h
@@ -0,0 +1,209 @@
1/* Copyright (c) 2003-2008 Jean-Marc Valin
2 Copyright (c) 2007-2008 CSIRO
3 Copyright (c) 2007-2009 Xiph.Org Foundation
4 Written by Jean-Marc Valin */
5/**
6 @file arch.h
7 @brief Various architecture definitions for CELT
8*/
9/*
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions
12 are met:
13
14 - Redistributions of source code must retain the above copyright
15 notice, this list of conditions and the following disclaimer.
16
17 - Redistributions in binary form must reproduce the above copyright
18 notice, this list of conditions and the following disclaimer in the
19 documentation and/or other materials provided with the distribution.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
25 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32*/
33
34#ifndef ARCH_H
35#define ARCH_H
36
37#include "opus_types.h"
38
39# if !defined(__GNUC_PREREQ)
40# if defined(__GNUC__)&&defined(__GNUC_MINOR__)
41# define __GNUC_PREREQ(_maj,_min) \
42 ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
43# else
44# define __GNUC_PREREQ(_maj,_min) 0
45# endif
46# endif
47
48#define CELT_SIG_SCALE 32768.f
49
50#define celt_fatal(str) _celt_fatal(str, __FILE__, __LINE__);
51#ifdef ENABLE_ASSERTIONS
52#include <stdio.h>
53#include <stdlib.h>
54#ifdef __GNUC__
55__attribute__((noreturn))
56#endif
57static inline void _celt_fatal(const char *str, const char *file, int line)
58{
59 fprintf (stderr, "Fatal (internal) error in %s, line %d: %s\n", file, line, str);
60 abort();
61}
62#define celt_assert(cond) {if (!(cond)) {celt_fatal("assertion failed: " #cond);}}
63#define celt_assert2(cond, message) {if (!(cond)) {celt_fatal("assertion failed: " #cond "\n" message);}}
64#else
65#define celt_assert(cond)
66#define celt_assert2(cond, message)
67#endif
68
69#define IMUL32(a,b) ((a)*(b))
70
71#define ABS(x) ((x) < 0 ? (-(x)) : (x)) /**< Absolute integer value. */
72#define ABS16(x) ((x) < 0 ? (-(x)) : (x)) /**< Absolute 16-bit value. */
73#define MIN16(a,b) ((a) < (b) ? (a) : (b)) /**< Minimum 16-bit value. */
74#define MAX16(a,b) ((a) > (b) ? (a) : (b)) /**< Maximum 16-bit value. */
75#define ABS32(x) ((x) < 0 ? (-(x)) : (x)) /**< Absolute 32-bit value. */
76#define MIN32(a,b) ((a) < (b) ? (a) : (b)) /**< Minimum 32-bit value. */
77#define MAX32(a,b) ((a) > (b) ? (a) : (b)) /**< Maximum 32-bit value. */
78#define IMIN(a,b) ((a) < (b) ? (a) : (b)) /**< Minimum int value. */
79#define IMAX(a,b) ((a) > (b) ? (a) : (b)) /**< Maximum int value. */
80#define UADD32(a,b) ((a)+(b))
81#define USUB32(a,b) ((a)-(b))
82
83#define PRINT_MIPS(file)
84
85#ifdef FIXED_POINT
86
87typedef opus_int16 opus_val16;
88typedef opus_int32 opus_val32;
89
90typedef opus_val32 celt_sig;
91typedef opus_val16 celt_norm;
92typedef opus_val32 celt_ener;
93
94#define Q15ONE 32767
95
96#define SIG_SHIFT 12
97
98#define NORM_SCALING 16384
99
100#define DB_SHIFT 10
101
102#define EPSILON 1
103#define VERY_LARGE16 ((opus_val16)32767)
104#define Q15_ONE ((opus_val16)32767)
105
106#define SCALEIN(a) (a)
107#define SCALEOUT(a) (a)
108
109#ifdef FIXED_DEBUG
110#include "fixed_debug.h"
111#else
112
113#include "fixed_generic.h"
114
115#ifdef ARM5E_ASM
116#include "fixed_arm5e.h"
117#elif defined (ARM4_ASM)
118#include "fixed_arm4.h"
119#elif defined (BFIN_ASM)
120#include "fixed_bfin.h"
121#elif defined (TI_C5X_ASM)
122#include "fixed_c5x.h"
123#elif defined (TI_C6X_ASM)
124#include "fixed_c6x.h"
125#endif
126
127#endif
128
129#else /* FIXED_POINT */
130
131typedef float opus_val16;
132typedef float opus_val32;
133
134typedef float celt_sig;
135typedef float celt_norm;
136typedef float celt_ener;
137
138#define Q15ONE 1.0f
139
140#define NORM_SCALING 1.f
141
142#define EPSILON 1e-15f
143#define VERY_LARGE16 1e15f
144#define Q15_ONE ((opus_val16)1.f)
145
146#define QCONST16(x,bits) (x)
147#define QCONST32(x,bits) (x)
148
149#define NEG16(x) (-(x))
150#define NEG32(x) (-(x))
151#define EXTRACT16(x) (x)
152#define EXTEND32(x) (x)
153#define SHR16(a,shift) (a)
154#define SHL16(a,shift) (a)
155#define SHR32(a,shift) (a)
156#define SHL32(a,shift) (a)
157#define PSHR32(a,shift) (a)
158#define VSHR32(a,shift) (a)
159
160#define PSHR(a,shift) (a)
161#define SHR(a,shift) (a)
162#define SHL(a,shift) (a)
163#define SATURATE(x,a) (x)
164
165#define ROUND16(a,shift) (a)
166#define HALF16(x) (.5f*(x))
167#define HALF32(x) (.5f*(x))
168
169#define ADD16(a,b) ((a)+(b))
170#define SUB16(a,b) ((a)-(b))
171#define ADD32(a,b) ((a)+(b))
172#define SUB32(a,b) ((a)-(b))
173#define MULT16_16_16(a,b) ((a)*(b))
174#define MULT16_16(a,b) ((opus_val32)(a)*(opus_val32)(b))
175#define MAC16_16(c,a,b) ((c)+(opus_val32)(a)*(opus_val32)(b))
176
177#define MULT16_32_Q15(a,b) ((a)*(b))
178#define MULT16_32_Q16(a,b) ((a)*(b))
179
180#define MULT32_32_Q31(a,b) ((a)*(b))
181
182#define MAC16_32_Q15(c,a,b) ((c)+(a)*(b))
183
184#define MULT16_16_Q11_32(a,b) ((a)*(b))
185#define MULT16_16_Q13(a,b) ((a)*(b))
186#define MULT16_16_Q14(a,b) ((a)*(b))
187#define MULT16_16_Q15(a,b) ((a)*(b))
188#define MULT16_16_P15(a,b) ((a)*(b))
189#define MULT16_16_P13(a,b) ((a)*(b))
190#define MULT16_16_P14(a,b) ((a)*(b))
191#define MULT16_32_P16(a,b) ((a)*(b))
192
193#define DIV32_16(a,b) (((opus_val32)(a))/(opus_val16)(b))
194#define DIV32(a,b) (((opus_val32)(a))/(opus_val32)(b))
195
196#define SCALEIN(a) ((a)*CELT_SIG_SCALE)
197#define SCALEOUT(a) ((a)*(1/CELT_SIG_SCALE))
198
199#endif /* !FIXED_POINT */
200
201#ifndef GLOBAL_STACK_SIZE
202#ifdef FIXED_POINT
203#define GLOBAL_STACK_SIZE 100000
204#else
205#define GLOBAL_STACK_SIZE 100000
206#endif
207#endif
208
209#endif /* ARCH_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/bands.c b/lib/rbcodec/codecs/libopus/celt/bands.c
new file mode 100644
index 0000000000..6e612980b6
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/bands.c
@@ -0,0 +1,1302 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2008-2009 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifdef HAVE_CONFIG_H
31#include "opus_config.h"
32#endif
33
34#include <math.h>
35#include "bands.h"
36#include "modes.h"
37#include "vq.h"
38#include "cwrs.h"
39#include "stack_alloc.h"
40#include "os_support.h"
41#include "mathops.h"
42#include "rate.h"
43
44opus_uint32 celt_lcg_rand(opus_uint32 seed)
45{
46 return 1664525 * seed + 1013904223;
47}
48
49/* This is a cos() approximation designed to be bit-exact on any platform. Bit exactness
50 with this approximation is important because it has an impact on the bit allocation */
51static opus_int16 bitexact_cos(opus_int16 x)
52{
53 opus_int32 tmp;
54 opus_int16 x2;
55 tmp = (4096+((opus_int32)(x)*(x)))>>13;
56 celt_assert(tmp<=32767);
57 x2 = tmp;
58 x2 = (32767-x2) + FRAC_MUL16(x2, (-7651 + FRAC_MUL16(x2, (8277 + FRAC_MUL16(-626, x2)))));
59 celt_assert(x2<=32766);
60 return 1+x2;
61}
62
63static int bitexact_log2tan(int isin,int icos)
64{
65 int lc;
66 int ls;
67 lc=EC_ILOG(icos);
68 ls=EC_ILOG(isin);
69 icos<<=15-lc;
70 isin<<=15-ls;
71 return (ls-lc)*(1<<11)
72 +FRAC_MUL16(isin, FRAC_MUL16(isin, -2597) + 7932)
73 -FRAC_MUL16(icos, FRAC_MUL16(icos, -2597) + 7932);
74}
75
76#ifdef FIXED_POINT
77/* Compute the amplitude (sqrt energy) in each of the bands */
78void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int M)
79{
80 int i, c, N;
81 const opus_int16 *eBands = m->eBands;
82 N = M*m->shortMdctSize;
83 c=0; do {
84 for (i=0;i<end;i++)
85 {
86 int j;
87 opus_val32 maxval=0;
88 opus_val32 sum = 0;
89
90 j=M*eBands[i]; do {
91 maxval = MAX32(maxval, X[j+c*N]);
92 maxval = MAX32(maxval, -X[j+c*N]);
93 } while (++j<M*eBands[i+1]);
94
95 if (maxval > 0)
96 {
97 int shift = celt_ilog2(maxval)-10;
98 j=M*eBands[i]; do {
99 sum = MAC16_16(sum, EXTRACT16(VSHR32(X[j+c*N],shift)),
100 EXTRACT16(VSHR32(X[j+c*N],shift)));
101 } while (++j<M*eBands[i+1]);
102 /* We're adding one here to ensure the normalized band isn't larger than unity norm */
103 bandE[i+c*m->nbEBands] = EPSILON+VSHR32(EXTEND32(celt_sqrt(sum)),-shift);
104 } else {
105 bandE[i+c*m->nbEBands] = EPSILON;
106 }
107 /*printf ("%f ", bandE[i+c*m->nbEBands]);*/
108 }
109 } while (++c<C);
110 /*printf ("\n");*/
111}
112
113/* Normalise each band such that the energy is one. */
114void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M)
115{
116 int i, c, N;
117 const opus_int16 *eBands = m->eBands;
118 N = M*m->shortMdctSize;
119 c=0; do {
120 i=0; do {
121 opus_val16 g;
122 int j,shift;
123 opus_val16 E;
124 shift = celt_zlog2(bandE[i+c*m->nbEBands])-13;
125 E = VSHR32(bandE[i+c*m->nbEBands], shift);
126 g = EXTRACT16(celt_rcp(SHL32(E,3)));
127 j=M*eBands[i]; do {
128 X[j+c*N] = MULT16_16_Q15(VSHR32(freq[j+c*N],shift-1),g);
129 } while (++j<M*eBands[i+1]);
130 } while (++i<end);
131 } while (++c<C);
132}
133
134#else /* FIXED_POINT */
135/* Compute the amplitude (sqrt energy) in each of the bands */
136void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int M)
137{
138 int i, c, N;
139 const opus_int16 *eBands = m->eBands;
140 N = M*m->shortMdctSize;
141 c=0; do {
142 for (i=0;i<end;i++)
143 {
144 int j;
145 opus_val32 sum = 1e-27f;
146 for (j=M*eBands[i];j<M*eBands[i+1];j++)
147 sum += X[j+c*N]*X[j+c*N];
148 bandE[i+c*m->nbEBands] = celt_sqrt(sum);
149 /*printf ("%f ", bandE[i+c*m->nbEBands]);*/
150 }
151 } while (++c<C);
152 /*printf ("\n");*/
153}
154
155/* Normalise each band such that the energy is one. */
156void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M)
157{
158 int i, c, N;
159 const opus_int16 *eBands = m->eBands;
160 N = M*m->shortMdctSize;
161 c=0; do {
162 for (i=0;i<end;i++)
163 {
164 int j;
165 opus_val16 g = 1.f/(1e-27f+bandE[i+c*m->nbEBands]);
166 for (j=M*eBands[i];j<M*eBands[i+1];j++)
167 X[j+c*N] = freq[j+c*N]*g;
168 }
169 } while (++c<C);
170}
171
172#endif /* FIXED_POINT */
173
174/* De-normalise the energy to produce the synthesis from the unit-energy bands */
175void denormalise_bands(const CELTMode *m, const celt_norm * OPUS_RESTRICT X, celt_sig * OPUS_RESTRICT freq, const celt_ener *bandE, int end, int C, int M)
176{
177 int i, c, N;
178 const opus_int16 *eBands = m->eBands;
179 N = M*m->shortMdctSize;
180 celt_assert2(C<=2, "denormalise_bands() not implemented for >2 channels");
181 c=0; do {
182 celt_sig * OPUS_RESTRICT f;
183 const celt_norm * OPUS_RESTRICT x;
184 f = freq+c*N;
185 x = X+c*N;
186 for (i=0;i<end;i++)
187 {
188 int j, band_end;
189 opus_val32 g = SHR32(bandE[i+c*m->nbEBands],1);
190 j=M*eBands[i];
191 band_end = M*eBands[i+1];
192 do {
193 *f++ = SHL32(MULT16_32_Q15(*x, g),2);
194 x++;
195 } while (++j<band_end);
196 }
197 for (i=M*eBands[end];i<N;i++)
198 *f++ = 0;
199 } while (++c<C);
200}
201
202/* This prevents energy collapse for transients with multiple short MDCTs */
203void anti_collapse(const CELTMode *m, celt_norm *X_, unsigned char *collapse_masks, int LM, int C, int size,
204 int start, int end, opus_val16 *logE, opus_val16 *prev1logE,
205 opus_val16 *prev2logE, int *pulses, opus_uint32 seed)
206{
207 int c, i, j, k;
208 for (i=start;i<end;i++)
209 {
210 int N0;
211 opus_val16 thresh, sqrt_1;
212 int depth;
213#ifdef FIXED_POINT
214 int shift;
215 opus_val32 thresh32;
216#endif
217
218 N0 = m->eBands[i+1]-m->eBands[i];
219 /* depth in 1/8 bits */
220 depth = (1+pulses[i])/((m->eBands[i+1]-m->eBands[i])<<LM);
221
222#ifdef FIXED_POINT
223 thresh32 = SHR32(celt_exp2(-SHL16(depth, 10-BITRES)),1);
224 thresh = MULT16_32_Q15(QCONST16(0.5f, 15), MIN32(32767,thresh32));
225 {
226 opus_val32 t;
227 t = N0<<LM;
228 shift = celt_ilog2(t)>>1;
229 t = SHL32(t, (7-shift)<<1);
230 sqrt_1 = celt_rsqrt_norm(t);
231 }
232#else
233 thresh = .5f*celt_exp2(-.125f*depth);
234 sqrt_1 = celt_rsqrt(N0<<LM);
235#endif
236
237 c=0; do
238 {
239 celt_norm *X;
240 opus_val16 prev1;
241 opus_val16 prev2;
242 opus_val32 Ediff;
243 opus_val16 r;
244 int renormalize=0;
245 prev1 = prev1logE[c*m->nbEBands+i];
246 prev2 = prev2logE[c*m->nbEBands+i];
247 if (C==1)
248 {
249 prev1 = MAX16(prev1,prev1logE[m->nbEBands+i]);
250 prev2 = MAX16(prev2,prev2logE[m->nbEBands+i]);
251 }
252 Ediff = EXTEND32(logE[c*m->nbEBands+i])-EXTEND32(MIN16(prev1,prev2));
253 Ediff = MAX32(0, Ediff);
254
255#ifdef FIXED_POINT
256 if (Ediff < 16384)
257 {
258 opus_val32 r32 = SHR32(celt_exp2(-EXTRACT16(Ediff)),1);
259 r = 2*MIN16(16383,r32);
260 } else {
261 r = 0;
262 }
263 if (LM==3)
264 r = MULT16_16_Q14(23170, MIN32(23169, r));
265 r = SHR16(MIN16(thresh, r),1);
266 r = SHR32(MULT16_16_Q15(sqrt_1, r),shift);
267#else
268 /* r needs to be multiplied by 2 or 2*sqrt(2) depending on LM because
269 short blocks don't have the same energy as long */
270 r = 2.f*celt_exp2(-Ediff);
271 if (LM==3)
272 r *= 1.41421356f;
273 r = MIN16(thresh, r);
274 r = r*sqrt_1;
275#endif
276 X = X_+c*size+(m->eBands[i]<<LM);
277 for (k=0;k<1<<LM;k++)
278 {
279 /* Detect collapse */
280 if (!(collapse_masks[i*C+c]&1<<k))
281 {
282 /* Fill with noise */
283 for (j=0;j<N0;j++)
284 {
285 seed = celt_lcg_rand(seed);
286 X[(j<<LM)+k] = (seed&0x8000 ? r : -r);
287 }
288 renormalize = 1;
289 }
290 }
291 /* We just added some energy, so we need to renormalise */
292 if (renormalize)
293 renormalise_vector(X, N0<<LM, Q15ONE);
294 } while (++c<C);
295 }
296}
297
298static void intensity_stereo(const CELTMode *m, celt_norm *X, celt_norm *Y, const celt_ener *bandE, int bandID, int N)
299{
300 int i = bandID;
301 int j;
302 opus_val16 a1, a2;
303 opus_val16 left, right;
304 opus_val16 norm;
305#ifdef FIXED_POINT
306 int shift = celt_zlog2(MAX32(bandE[i], bandE[i+m->nbEBands]))-13;
307#endif
308 left = VSHR32(bandE[i],shift);
309 right = VSHR32(bandE[i+m->nbEBands],shift);
310 norm = EPSILON + celt_sqrt(EPSILON+MULT16_16(left,left)+MULT16_16(right,right));
311 a1 = DIV32_16(SHL32(EXTEND32(left),14),norm);
312 a2 = DIV32_16(SHL32(EXTEND32(right),14),norm);
313 for (j=0;j<N;j++)
314 {
315 celt_norm r, l;
316 l = X[j];
317 r = Y[j];
318 X[j] = MULT16_16_Q14(a1,l) + MULT16_16_Q14(a2,r);
319 /* Side is not encoded, no need to calculate */
320 }
321}
322
323static void stereo_split(celt_norm *X, celt_norm *Y, int N)
324{
325 int j;
326 for (j=0;j<N;j++)
327 {
328 celt_norm r, l;
329 l = MULT16_16_Q15(QCONST16(.70710678f,15), X[j]);
330 r = MULT16_16_Q15(QCONST16(.70710678f,15), Y[j]);
331 X[j] = l+r;
332 Y[j] = r-l;
333 }
334}
335
336static void stereo_merge(celt_norm *X, celt_norm *Y, opus_val16 mid, int N)
337{
338 int j;
339 opus_val32 xp=0, side=0;
340 opus_val32 El, Er;
341 opus_val16 mid2;
342#ifdef FIXED_POINT
343 int kl, kr;
344#endif
345 opus_val32 t, lgain, rgain;
346
347 /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
348 for (j=0;j<N;j++)
349 {
350 xp = MAC16_16(xp, X[j], Y[j]);
351 side = MAC16_16(side, Y[j], Y[j]);
352 }
353 /* Compensating for the mid normalization */
354 xp = MULT16_32_Q15(mid, xp);
355 /* mid and side are in Q15, not Q14 like X and Y */
356 mid2 = SHR32(mid, 1);
357 El = MULT16_16(mid2, mid2) + side - 2*xp;
358 Er = MULT16_16(mid2, mid2) + side + 2*xp;
359 if (Er < QCONST32(6e-4f, 28) || El < QCONST32(6e-4f, 28))
360 {
361 for (j=0;j<N;j++)
362 Y[j] = X[j];
363 return;
364 }
365
366#ifdef FIXED_POINT
367 kl = celt_ilog2(El)>>1;
368 kr = celt_ilog2(Er)>>1;
369#endif
370 t = VSHR32(El, (kl-7)<<1);
371 lgain = celt_rsqrt_norm(t);
372 t = VSHR32(Er, (kr-7)<<1);
373 rgain = celt_rsqrt_norm(t);
374
375#ifdef FIXED_POINT
376 if (kl < 7)
377 kl = 7;
378 if (kr < 7)
379 kr = 7;
380#endif
381
382 for (j=0;j<N;j++)
383 {
384 celt_norm r, l;
385 /* Apply mid scaling (side is already scaled) */
386 l = MULT16_16_Q15(mid, X[j]);
387 r = Y[j];
388 X[j] = EXTRACT16(PSHR32(MULT16_16(lgain, SUB16(l,r)), kl+1));
389 Y[j] = EXTRACT16(PSHR32(MULT16_16(rgain, ADD16(l,r)), kr+1));
390 }
391}
392
393/* Decide whether we should spread the pulses in the current frame */
394int spreading_decision(const CELTMode *m, celt_norm *X, int *average,
395 int last_decision, int *hf_average, int *tapset_decision, int update_hf,
396 int end, int C, int M)
397{
398 int i, c, N0;
399 int sum = 0, nbBands=0;
400 const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
401 int decision;
402 int hf_sum=0;
403
404 celt_assert(end>0);
405
406 N0 = M*m->shortMdctSize;
407
408 if (M*(eBands[end]-eBands[end-1]) <= 8)
409 return SPREAD_NONE;
410 c=0; do {
411 for (i=0;i<end;i++)
412 {
413 int j, N, tmp=0;
414 int tcount[3] = {0,0,0};
415 celt_norm * OPUS_RESTRICT x = X+M*eBands[i]+c*N0;
416 N = M*(eBands[i+1]-eBands[i]);
417 if (N<=8)
418 continue;
419 /* Compute rough CDF of |x[j]| */
420 for (j=0;j<N;j++)
421 {
422 opus_val32 x2N; /* Q13 */
423
424 x2N = MULT16_16(MULT16_16_Q15(x[j], x[j]), N);
425 if (x2N < QCONST16(0.25f,13))
426 tcount[0]++;
427 if (x2N < QCONST16(0.0625f,13))
428 tcount[1]++;
429 if (x2N < QCONST16(0.015625f,13))
430 tcount[2]++;
431 }
432
433 /* Only include four last bands (8 kHz and up) */
434 if (i>m->nbEBands-4)
435 hf_sum += 32*(tcount[1]+tcount[0])/N;
436 tmp = (2*tcount[2] >= N) + (2*tcount[1] >= N) + (2*tcount[0] >= N);
437 sum += tmp*256;
438 nbBands++;
439 }
440 } while (++c<C);
441
442 if (update_hf)
443 {
444 if (hf_sum)
445 hf_sum /= C*(4-m->nbEBands+end);
446 *hf_average = (*hf_average+hf_sum)>>1;
447 hf_sum = *hf_average;
448 if (*tapset_decision==2)
449 hf_sum += 4;
450 else if (*tapset_decision==0)
451 hf_sum -= 4;
452 if (hf_sum > 22)
453 *tapset_decision=2;
454 else if (hf_sum > 18)
455 *tapset_decision=1;
456 else
457 *tapset_decision=0;
458 }
459 /*printf("%d %d %d\n", hf_sum, *hf_average, *tapset_decision);*/
460 celt_assert(nbBands>0); /*M*(eBands[end]-eBands[end-1]) <= 8 assures this*/
461 sum /= nbBands;
462 /* Recursive averaging */
463 sum = (sum+*average)>>1;
464 *average = sum;
465 /* Hysteresis */
466 sum = (3*sum + (((3-last_decision)<<7) + 64) + 2)>>2;
467 if (sum < 80)
468 {
469 decision = SPREAD_AGGRESSIVE;
470 } else if (sum < 256)
471 {
472 decision = SPREAD_NORMAL;
473 } else if (sum < 384)
474 {
475 decision = SPREAD_LIGHT;
476 } else {
477 decision = SPREAD_NONE;
478 }
479#ifdef FUZZING
480 decision = rand()&0x3;
481 *tapset_decision=rand()%3;
482#endif
483 return decision;
484}
485
486#ifdef MEASURE_NORM_MSE
487
488float MSE[30] = {0};
489int nbMSEBands = 0;
490int MSECount[30] = {0};
491
492void dump_norm_mse(void)
493{
494 int i;
495 for (i=0;i<nbMSEBands;i++)
496 {
497 printf ("%g ", MSE[i]/MSECount[i]);
498 }
499 printf ("\n");
500}
501
502void measure_norm_mse(const CELTMode *m, float *X, float *X0, float *bandE, float *bandE0, int M, int N, int C)
503{
504 static int init = 0;
505 int i;
506 if (!init)
507 {
508 atexit(dump_norm_mse);
509 init = 1;
510 }
511 for (i=0;i<m->nbEBands;i++)
512 {
513 int j;
514 int c;
515 float g;
516 if (bandE0[i]<10 || (C==2 && bandE0[i+m->nbEBands]<1))
517 continue;
518 c=0; do {
519 g = bandE[i+c*m->nbEBands]/(1e-15+bandE0[i+c*m->nbEBands]);
520 for (j=M*m->eBands[i];j<M*m->eBands[i+1];j++)
521 MSE[i] += (g*X[j+c*N]-X0[j+c*N])*(g*X[j+c*N]-X0[j+c*N]);
522 } while (++c<C);
523 MSECount[i]+=C;
524 }
525 nbMSEBands = m->nbEBands;
526}
527
528#endif
529
530/* Indexing table for converting from natural Hadamard to ordery Hadamard
531 This is essentially a bit-reversed Gray, on top of which we've added
532 an inversion of the order because we want the DC at the end rather than
533 the beginning. The lines are for N=2, 4, 8, 16 */
534static const int ordery_table[] = {
535 1, 0,
536 3, 0, 2, 1,
537 7, 0, 4, 3, 6, 1, 5, 2,
538 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5,
539};
540
541static void deinterleave_hadamard(celt_norm *X, int N0, int stride, int hadamard)
542{
543 int i,j;
544 VARDECL(celt_norm, tmp);
545 int N;
546 SAVE_STACK;
547 N = N0*stride;
548 ALLOC(tmp, N, celt_norm);
549 celt_assert(stride>0);
550 if (hadamard)
551 {
552 const int *ordery = ordery_table+stride-2;
553 for (i=0;i<stride;i++)
554 {
555 for (j=0;j<N0;j++)
556 tmp[ordery[i]*N0+j] = X[j*stride+i];
557 }
558 } else {
559 for (i=0;i<stride;i++)
560 for (j=0;j<N0;j++)
561 tmp[i*N0+j] = X[j*stride+i];
562 }
563 for (j=0;j<N;j++)
564 X[j] = tmp[j];
565 RESTORE_STACK;
566}
567
568static void interleave_hadamard(celt_norm *X, int N0, int stride, int hadamard)
569{
570 int i,j;
571 VARDECL(celt_norm, tmp);
572 int N;
573 SAVE_STACK;
574 N = N0*stride;
575 ALLOC(tmp, N, celt_norm);
576 if (hadamard)
577 {
578 const int *ordery = ordery_table+stride-2;
579 for (i=0;i<stride;i++)
580 for (j=0;j<N0;j++)
581 tmp[j*stride+i] = X[ordery[i]*N0+j];
582 } else {
583 for (i=0;i<stride;i++)
584 for (j=0;j<N0;j++)
585 tmp[j*stride+i] = X[i*N0+j];
586 }
587 for (j=0;j<N;j++)
588 X[j] = tmp[j];
589 RESTORE_STACK;
590}
591
592void haar1(celt_norm *X, int N0, int stride)
593{
594 int i, j;
595 N0 >>= 1;
596 for (i=0;i<stride;i++)
597 for (j=0;j<N0;j++)
598 {
599 celt_norm tmp1, tmp2;
600 tmp1 = MULT16_16_Q15(QCONST16(.70710678f,15), X[stride*2*j+i]);
601 tmp2 = MULT16_16_Q15(QCONST16(.70710678f,15), X[stride*(2*j+1)+i]);
602 X[stride*2*j+i] = tmp1 + tmp2;
603 X[stride*(2*j+1)+i] = tmp1 - tmp2;
604 }
605}
606
607static int compute_qn(int N, int b, int offset, int pulse_cap, int stereo)
608{
609 static const opus_int16 exp2_table8[8] =
610 {16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048};
611 int qn, qb;
612 int N2 = 2*N-1;
613 if (stereo && N==2)
614 N2--;
615 /* The upper limit ensures that in a stereo split with itheta==16384, we'll
616 always have enough bits left over to code at least one pulse in the
617 side; otherwise it would collapse, since it doesn't get folded. */
618 qb = IMIN(b-pulse_cap-(4<<BITRES), (b+N2*offset)/N2);
619
620 qb = IMIN(8<<BITRES, qb);
621
622 if (qb<(1<<BITRES>>1)) {
623 qn = 1;
624 } else {
625 qn = exp2_table8[qb&0x7]>>(14-(qb>>BITRES));
626 qn = (qn+1)>>1<<1;
627 }
628 celt_assert(qn <= 256);
629 return qn;
630}
631
632/* This function is responsible for encoding and decoding a band for both
633 the mono and stereo case. Even in the mono case, it can split the band
634 in two and transmit the energy difference with the two half-bands. It
635 can be called recursively so bands can end up being split in 8 parts. */
636static unsigned quant_band(int encode, const CELTMode *m, int i, celt_norm *X, celt_norm *Y,
637 int N, int b, int spread, int B, int intensity, int tf_change, celt_norm *lowband, ec_ctx *ec,
638 opus_int32 *remaining_bits, int LM, celt_norm *lowband_out, const celt_ener *bandE, int level,
639 opus_uint32 *seed, opus_val16 gain, celt_norm *lowband_scratch, int fill)
640{
641 const unsigned char *cache;
642 int q;
643 int curr_bits;
644 int stereo, split;
645 int imid=0, iside=0;
646 int N0=N;
647 int N_B=N;
648 int N_B0;
649 int B0=B;
650 int time_divide=0;
651 int recombine=0;
652 int inv = 0;
653 opus_val16 mid=0, side=0;
654 int longBlocks;
655 unsigned cm=0;
656#ifdef RESYNTH
657 int resynth = 1;
658#else
659 int resynth = !encode;
660#endif
661
662 longBlocks = B0==1;
663
664 N_B /= B;
665 N_B0 = N_B;
666
667 split = stereo = Y != NULL;
668
669 /* Special case for one sample */
670 if (N==1)
671 {
672 int c;
673 celt_norm *x = X;
674 c=0; do {
675 int sign=0;
676 if (*remaining_bits>=1<<BITRES)
677 {
678 if (encode)
679 {
680 sign = x[0]<0;
681 ec_enc_bits(ec, sign, 1);
682 } else {
683 sign = ec_dec_bits(ec, 1);
684 }
685 *remaining_bits -= 1<<BITRES;
686 b-=1<<BITRES;
687 }
688 if (resynth)
689 x[0] = sign ? -NORM_SCALING : NORM_SCALING;
690 x = Y;
691 } while (++c<1+stereo);
692 if (lowband_out)
693 lowband_out[0] = SHR16(X[0],4);
694 return 1;
695 }
696
697 if (!stereo && level == 0)
698 {
699 int k;
700 if (tf_change>0)
701 recombine = tf_change;
702 /* Band recombining to increase frequency resolution */
703
704 if (lowband && (recombine || ((N_B&1) == 0 && tf_change<0) || B0>1))
705 {
706 int j;
707 for (j=0;j<N;j++)
708 lowband_scratch[j] = lowband[j];
709 lowband = lowband_scratch;
710 }
711
712 for (k=0;k<recombine;k++)
713 {
714 static const unsigned char bit_interleave_table[16]={
715 0,1,1,1,2,3,3,3,2,3,3,3,2,3,3,3
716 };
717 if (encode)
718 haar1(X, N>>k, 1<<k);
719 if (lowband)
720 haar1(lowband, N>>k, 1<<k);
721 fill = bit_interleave_table[fill&0xF]|bit_interleave_table[fill>>4]<<2;
722 }
723 B>>=recombine;
724 N_B<<=recombine;
725
726 /* Increasing the time resolution */
727 while ((N_B&1) == 0 && tf_change<0)
728 {
729 if (encode)
730 haar1(X, N_B, B);
731 if (lowband)
732 haar1(lowband, N_B, B);
733 fill |= fill<<B;
734 B <<= 1;
735 N_B >>= 1;
736 time_divide++;
737 tf_change++;
738 }
739 B0=B;
740 N_B0 = N_B;
741
742 /* Reorganize the samples in time order instead of frequency order */
743 if (B0>1)
744 {
745 if (encode)
746 deinterleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
747 if (lowband)
748 deinterleave_hadamard(lowband, N_B>>recombine, B0<<recombine, longBlocks);
749 }
750 }
751
752 /* If we need 1.5 more bit than we can produce, split the band in two. */
753 cache = m->cache.bits + m->cache.index[(LM+1)*m->nbEBands+i];
754 if (!stereo && LM != -1 && b > cache[cache[0]]+12 && N>2)
755 {
756 N >>= 1;
757 Y = X+N;
758 split = 1;
759 LM -= 1;
760 if (B==1)
761 fill = (fill&1)|(fill<<1);
762 B = (B+1)>>1;
763 }
764
765 if (split)
766 {
767 int qn;
768 int itheta=0;
769 int mbits, sbits, delta;
770 int qalloc;
771 int pulse_cap;
772 int offset;
773 int orig_fill;
774 opus_int32 tell;
775
776 /* Decide on the resolution to give to the split parameter theta */
777 pulse_cap = m->logN[i]+LM*(1<<BITRES);
778 offset = (pulse_cap>>1) - (stereo&&N==2 ? QTHETA_OFFSET_TWOPHASE : QTHETA_OFFSET);
779 qn = compute_qn(N, b, offset, pulse_cap, stereo);
780 if (stereo && i>=intensity)
781 qn = 1;
782 if (encode)
783 {
784 /* theta is the atan() of the ratio between the (normalized)
785 side and mid. With just that parameter, we can re-scale both
786 mid and side because we know that 1) they have unit norm and
787 2) they are orthogonal. */
788 itheta = stereo_itheta(X, Y, stereo, N);
789 }
790 tell = ec_tell_frac(ec);
791 if (qn!=1)
792 {
793 if (encode)
794 itheta = (itheta*qn+8192)>>14;
795
796 /* Entropy coding of the angle. We use a uniform pdf for the
797 time split, a step for stereo, and a triangular one for the rest. */
798 if (stereo && N>2)
799 {
800 int p0 = 3;
801 int x = itheta;
802 int x0 = qn/2;
803 int ft = p0*(x0+1) + x0;
804 /* Use a probability of p0 up to itheta=8192 and then use 1 after */
805 if (encode)
806 {
807 ec_encode(ec,x<=x0?p0*x:(x-1-x0)+(x0+1)*p0,x<=x0?p0*(x+1):(x-x0)+(x0+1)*p0,ft);
808 } else {
809 int fs;
810 fs=ec_decode(ec,ft);
811 if (fs<(x0+1)*p0)
812 x=fs/p0;
813 else
814 x=x0+1+(fs-(x0+1)*p0);
815 ec_dec_update(ec,x<=x0?p0*x:(x-1-x0)+(x0+1)*p0,x<=x0?p0*(x+1):(x-x0)+(x0+1)*p0,ft);
816 itheta = x;
817 }
818 } else if (B0>1 || stereo) {
819 /* Uniform pdf */
820 if (encode)
821 ec_enc_uint(ec, itheta, qn+1);
822 else
823 itheta = ec_dec_uint(ec, qn+1);
824 } else {
825 int fs=1, ft;
826 ft = ((qn>>1)+1)*((qn>>1)+1);
827 if (encode)
828 {
829 int fl;
830
831 fs = itheta <= (qn>>1) ? itheta + 1 : qn + 1 - itheta;
832 fl = itheta <= (qn>>1) ? itheta*(itheta + 1)>>1 :
833 ft - ((qn + 1 - itheta)*(qn + 2 - itheta)>>1);
834
835 ec_encode(ec, fl, fl+fs, ft);
836 } else {
837 /* Triangular pdf */
838 int fl=0;
839 int fm;
840 fm = ec_decode(ec, ft);
841
842 if (fm < ((qn>>1)*((qn>>1) + 1)>>1))
843 {
844 itheta = (isqrt32(8*(opus_uint32)fm + 1) - 1)>>1;
845 fs = itheta + 1;
846 fl = itheta*(itheta + 1)>>1;
847 }
848 else
849 {
850 itheta = (2*(qn + 1)
851 - isqrt32(8*(opus_uint32)(ft - fm - 1) + 1))>>1;
852 fs = qn + 1 - itheta;
853 fl = ft - ((qn + 1 - itheta)*(qn + 2 - itheta)>>1);
854 }
855
856 ec_dec_update(ec, fl, fl+fs, ft);
857 }
858 }
859 itheta = (opus_int32)itheta*16384/qn;
860 if (encode && stereo)
861 {
862 if (itheta==0)
863 intensity_stereo(m, X, Y, bandE, i, N);
864 else
865 stereo_split(X, Y, N);
866 }
867 /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
868 Let's do that at higher complexity */
869 } else if (stereo) {
870 if (encode)
871 {
872 inv = itheta > 8192;
873 if (inv)
874 {
875 int j;
876 for (j=0;j<N;j++)
877 Y[j] = -Y[j];
878 }
879 intensity_stereo(m, X, Y, bandE, i, N);
880 }
881 if (b>2<<BITRES && *remaining_bits > 2<<BITRES)
882 {
883 if (encode)
884 ec_enc_bit_logp(ec, inv, 2);
885 else
886 inv = ec_dec_bit_logp(ec, 2);
887 } else
888 inv = 0;
889 itheta = 0;
890 }
891 qalloc = ec_tell_frac(ec) - tell;
892 b -= qalloc;
893
894 orig_fill = fill;
895 if (itheta == 0)
896 {
897 imid = 32767;
898 iside = 0;
899 fill &= (1<<B)-1;
900 delta = -16384;
901 } else if (itheta == 16384)
902 {
903 imid = 0;
904 iside = 32767;
905 fill &= ((1<<B)-1)<<B;
906 delta = 16384;
907 } else {
908 imid = bitexact_cos(itheta);
909 iside = bitexact_cos(16384-itheta);
910 /* This is the mid vs side allocation that minimizes squared error
911 in that band. */
912 delta = FRAC_MUL16((N-1)<<7,bitexact_log2tan(iside,imid));
913 }
914
915#ifdef FIXED_POINT
916 mid = imid;
917 side = iside;
918#else
919 mid = (1.f/32768)*imid;
920 side = (1.f/32768)*iside;
921#endif
922
923 /* This is a special case for N=2 that only works for stereo and takes
924 advantage of the fact that mid and side are orthogonal to encode
925 the side with just one bit. */
926 if (N==2 && stereo)
927 {
928 int c;
929 int sign=0;
930 celt_norm *x2, *y2;
931 mbits = b;
932 sbits = 0;
933 /* Only need one bit for the side */
934 if (itheta != 0 && itheta != 16384)
935 sbits = 1<<BITRES;
936 mbits -= sbits;
937 c = itheta > 8192;
938 *remaining_bits -= qalloc+sbits;
939
940 x2 = c ? Y : X;
941 y2 = c ? X : Y;
942 if (sbits)
943 {
944 if (encode)
945 {
946 /* Here we only need to encode a sign for the side */
947 sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
948 ec_enc_bits(ec, sign, 1);
949 } else {
950 sign = ec_dec_bits(ec, 1);
951 }
952 }
953 sign = 1-2*sign;
954 /* We use orig_fill here because we want to fold the side, but if
955 itheta==16384, we'll have cleared the low bits of fill. */
956 cm = quant_band(encode, m, i, x2, NULL, N, mbits, spread, B, intensity, tf_change, lowband, ec, remaining_bits, LM, lowband_out, NULL, level, seed, gain, lowband_scratch, orig_fill);
957 /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
958 and there's no need to worry about mixing with the other channel. */
959 y2[0] = -sign*x2[1];
960 y2[1] = sign*x2[0];
961 if (resynth)
962 {
963 celt_norm tmp;
964 X[0] = MULT16_16_Q15(mid, X[0]);
965 X[1] = MULT16_16_Q15(mid, X[1]);
966 Y[0] = MULT16_16_Q15(side, Y[0]);
967 Y[1] = MULT16_16_Q15(side, Y[1]);
968 tmp = X[0];
969 X[0] = SUB16(tmp,Y[0]);
970 Y[0] = ADD16(tmp,Y[0]);
971 tmp = X[1];
972 X[1] = SUB16(tmp,Y[1]);
973 Y[1] = ADD16(tmp,Y[1]);
974 }
975 } else {
976 /* "Normal" split code */
977 celt_norm *next_lowband2=NULL;
978 celt_norm *next_lowband_out1=NULL;
979 int next_level=0;
980 opus_int32 rebalance;
981
982 /* Give more bits to low-energy MDCTs than they would otherwise deserve */
983 if (B0>1 && !stereo && (itheta&0x3fff))
984 {
985 if (itheta > 8192)
986 /* Rough approximation for pre-echo masking */
987 delta -= delta>>(4-LM);
988 else
989 /* Corresponds to a forward-masking slope of 1.5 dB per 10 ms */
990 delta = IMIN(0, delta + (N<<BITRES>>(5-LM)));
991 }
992 mbits = IMAX(0, IMIN(b, (b-delta)/2));
993 sbits = b-mbits;
994 *remaining_bits -= qalloc;
995
996 if (lowband && !stereo)
997 next_lowband2 = lowband+N; /* >32-bit split case */
998
999 /* Only stereo needs to pass on lowband_out. Otherwise, it's
1000 handled at the end */
1001 if (stereo)
1002 next_lowband_out1 = lowband_out;
1003 else
1004 next_level = level+1;
1005
1006 rebalance = *remaining_bits;
1007 if (mbits >= sbits)
1008 {
1009 /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
1010 mid for folding later */
1011 cm = quant_band(encode, m, i, X, NULL, N, mbits, spread, B, intensity, tf_change,
1012 lowband, ec, remaining_bits, LM, next_lowband_out1,
1013 NULL, next_level, seed, stereo ? Q15ONE : MULT16_16_P15(gain,mid), lowband_scratch, fill);
1014 rebalance = mbits - (rebalance-*remaining_bits);
1015 if (rebalance > 3<<BITRES && itheta!=0)
1016 sbits += rebalance - (3<<BITRES);
1017
1018 /* For a stereo split, the high bits of fill are always zero, so no
1019 folding will be done to the side. */
1020 cm |= quant_band(encode, m, i, Y, NULL, N, sbits, spread, B, intensity, tf_change,
1021 next_lowband2, ec, remaining_bits, LM, NULL,
1022 NULL, next_level, seed, MULT16_16_P15(gain,side), NULL, fill>>B)<<((B0>>1)&(stereo-1));
1023 } else {
1024 /* For a stereo split, the high bits of fill are always zero, so no
1025 folding will be done to the side. */
1026 cm = quant_band(encode, m, i, Y, NULL, N, sbits, spread, B, intensity, tf_change,
1027 next_lowband2, ec, remaining_bits, LM, NULL,
1028 NULL, next_level, seed, MULT16_16_P15(gain,side), NULL, fill>>B)<<((B0>>1)&(stereo-1));
1029 rebalance = sbits - (rebalance-*remaining_bits);
1030 if (rebalance > 3<<BITRES && itheta!=16384)
1031 mbits += rebalance - (3<<BITRES);
1032 /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
1033 mid for folding later */
1034 cm |= quant_band(encode, m, i, X, NULL, N, mbits, spread, B, intensity, tf_change,
1035 lowband, ec, remaining_bits, LM, next_lowband_out1,
1036 NULL, next_level, seed, stereo ? Q15ONE : MULT16_16_P15(gain,mid), lowband_scratch, fill);
1037 }
1038 }
1039
1040 } else {
1041 /* This is the basic no-split case */
1042 q = bits2pulses(m, i, LM, b);
1043 curr_bits = pulses2bits(m, i, LM, q);
1044 *remaining_bits -= curr_bits;
1045
1046 /* Ensures we can never bust the budget */
1047 while (*remaining_bits < 0 && q > 0)
1048 {
1049 *remaining_bits += curr_bits;
1050 q--;
1051 curr_bits = pulses2bits(m, i, LM, q);
1052 *remaining_bits -= curr_bits;
1053 }
1054
1055 if (q!=0)
1056 {
1057 int K = get_pulses(q);
1058
1059 /* Finally do the actual quantization */
1060 if (encode)
1061 {
1062 cm = alg_quant(X, N, K, spread, B, ec
1063#ifdef RESYNTH
1064 , gain
1065#endif
1066 );
1067 } else {
1068 cm = alg_unquant(X, N, K, spread, B, ec, gain);
1069 }
1070 } else {
1071 /* If there's no pulse, fill the band anyway */
1072 int j;
1073 if (resynth)
1074 {
1075 unsigned cm_mask;
1076 /*B can be as large as 16, so this shift might overflow an int on a
1077 16-bit platform; use a long to get defined behavior.*/
1078 cm_mask = (unsigned)(1UL<<B)-1;
1079 fill &= cm_mask;
1080 if (!fill)
1081 {
1082 for (j=0;j<N;j++)
1083 X[j] = 0;
1084 } else {
1085 if (lowband == NULL)
1086 {
1087 /* Noise */
1088 for (j=0;j<N;j++)
1089 {
1090 *seed = celt_lcg_rand(*seed);
1091 X[j] = (celt_norm)((opus_int32)*seed>>20);
1092 }
1093 cm = cm_mask;
1094 } else {
1095 /* Folded spectrum */
1096 for (j=0;j<N;j++)
1097 {
1098 opus_val16 tmp;
1099 *seed = celt_lcg_rand(*seed);
1100 /* About 48 dB below the "normal" folding level */
1101 tmp = QCONST16(1.0f/256, 10);
1102 tmp = (*seed)&0x8000 ? tmp : -tmp;
1103 X[j] = lowband[j]+tmp;
1104 }
1105 cm = fill;
1106 }
1107 renormalise_vector(X, N, gain);
1108 }
1109 }
1110 }
1111 }
1112
1113 /* This code is used by the decoder and by the resynthesis-enabled encoder */
1114 if (resynth)
1115 {
1116 if (stereo)
1117 {
1118 if (N!=2)
1119 stereo_merge(X, Y, mid, N);
1120 if (inv)
1121 {
1122 int j;
1123 for (j=0;j<N;j++)
1124 Y[j] = -Y[j];
1125 }
1126 } else if (level == 0)
1127 {
1128 int k;
1129
1130 /* Undo the sample reorganization going from time order to frequency order */
1131 if (B0>1)
1132 interleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
1133
1134 /* Undo time-freq changes that we did earlier */
1135 N_B = N_B0;
1136 B = B0;
1137 for (k=0;k<time_divide;k++)
1138 {
1139 B >>= 1;
1140 N_B <<= 1;
1141 cm |= cm>>B;
1142 haar1(X, N_B, B);
1143 }
1144
1145 for (k=0;k<recombine;k++)
1146 {
1147 static const unsigned char bit_deinterleave_table[16]={
1148 0x00,0x03,0x0C,0x0F,0x30,0x33,0x3C,0x3F,
1149 0xC0,0xC3,0xCC,0xCF,0xF0,0xF3,0xFC,0xFF
1150 };
1151 cm = bit_deinterleave_table[cm];
1152 haar1(X, N0>>k, 1<<k);
1153 }
1154 B<<=recombine;
1155
1156 /* Scale output for later folding */
1157 if (lowband_out)
1158 {
1159 int j;
1160 opus_val16 n;
1161 n = celt_sqrt(SHL32(EXTEND32(N0),22));
1162 for (j=0;j<N0;j++)
1163 lowband_out[j] = MULT16_16_Q15(n,X[j]);
1164 }
1165 cm &= (1<<B)-1;
1166 }
1167 }
1168 return cm;
1169}
1170
1171void quant_all_bands(int encode, const CELTMode *m, int start, int end,
1172 celt_norm *X_, celt_norm *Y_, unsigned char *collapse_masks, const celt_ener *bandE, int *pulses,
1173 int shortBlocks, int spread, int dual_stereo, int intensity, int *tf_res,
1174 opus_int32 total_bits, opus_int32 balance, ec_ctx *ec, int LM, int codedBands, opus_uint32 *seed)
1175{
1176 int i;
1177 opus_int32 remaining_bits;
1178 const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
1179 celt_norm * OPUS_RESTRICT norm, * OPUS_RESTRICT norm2;
1180 VARDECL(celt_norm, _norm);
1181 VARDECL(celt_norm, lowband_scratch);
1182 int B;
1183 int M;
1184 int lowband_offset;
1185 int update_lowband = 1;
1186 int C = Y_ != NULL ? 2 : 1;
1187#ifdef RESYNTH
1188 int resynth = 1;
1189#else
1190 int resynth = !encode;
1191#endif
1192 SAVE_STACK;
1193
1194 M = 1<<LM;
1195 B = shortBlocks ? M : 1;
1196 ALLOC(_norm, C*M*eBands[m->nbEBands], celt_norm);
1197 ALLOC(lowband_scratch, M*(eBands[m->nbEBands]-eBands[m->nbEBands-1]), celt_norm);
1198 norm = _norm;
1199 norm2 = norm + M*eBands[m->nbEBands];
1200
1201 lowband_offset = 0;
1202 for (i=start;i<end;i++)
1203 {
1204 opus_int32 tell;
1205 int b;
1206 int N;
1207 opus_int32 curr_balance;
1208 int effective_lowband=-1;
1209 celt_norm * OPUS_RESTRICT X, * OPUS_RESTRICT Y;
1210 int tf_change=0;
1211 unsigned x_cm;
1212 unsigned y_cm;
1213
1214 X = X_+M*eBands[i];
1215 if (Y_!=NULL)
1216 Y = Y_+M*eBands[i];
1217 else
1218 Y = NULL;
1219 N = M*eBands[i+1]-M*eBands[i];
1220 tell = ec_tell_frac(ec);
1221
1222 /* Compute how many bits we want to allocate to this band */
1223 if (i != start)
1224 balance -= tell;
1225 remaining_bits = total_bits-tell-1;
1226 if (i <= codedBands-1)
1227 {
1228 curr_balance = balance / IMIN(3, codedBands-i);
1229 b = IMAX(0, IMIN(16383, IMIN(remaining_bits+1,pulses[i]+curr_balance)));
1230 } else {
1231 b = 0;
1232 }
1233
1234 if (resynth && M*eBands[i]-N >= M*eBands[start] && (update_lowband || lowband_offset==0))
1235 lowband_offset = i;
1236
1237 tf_change = tf_res[i];
1238 if (i>=m->effEBands)
1239 {
1240 X=norm;
1241 if (Y_!=NULL)
1242 Y = norm;
1243 }
1244
1245 /* Get a conservative estimate of the collapse_mask's for the bands we're
1246 going to be folding from. */
1247 if (lowband_offset != 0 && (spread!=SPREAD_AGGRESSIVE || B>1 || tf_change<0))
1248 {
1249 int fold_start;
1250 int fold_end;
1251 int fold_i;
1252 /* This ensures we never repeat spectral content within one band */
1253 effective_lowband = IMAX(M*eBands[start], M*eBands[lowband_offset]-N);
1254 fold_start = lowband_offset;
1255 while(M*eBands[--fold_start] > effective_lowband);
1256 fold_end = lowband_offset-1;
1257 while(M*eBands[++fold_end] < effective_lowband+N);
1258 x_cm = y_cm = 0;
1259 fold_i = fold_start; do {
1260 x_cm |= collapse_masks[fold_i*C+0];
1261 y_cm |= collapse_masks[fold_i*C+C-1];
1262 } while (++fold_i<fold_end);
1263 }
1264 /* Otherwise, we'll be using the LCG to fold, so all blocks will (almost
1265 always) be non-zero.*/
1266 else
1267 x_cm = y_cm = (1<<B)-1;
1268
1269 if (dual_stereo && i==intensity)
1270 {
1271 int j;
1272
1273 /* Switch off dual stereo to do intensity */
1274 dual_stereo = 0;
1275 if (resynth)
1276 for (j=M*eBands[start];j<M*eBands[i];j++)
1277 norm[j] = HALF32(norm[j]+norm2[j]);
1278 }
1279 if (dual_stereo)
1280 {
1281 x_cm = quant_band(encode, m, i, X, NULL, N, b/2, spread, B, intensity, tf_change,
1282 effective_lowband != -1 ? norm+effective_lowband : NULL, ec, &remaining_bits, LM,
1283 norm+M*eBands[i], bandE, 0, seed, Q15ONE, lowband_scratch, x_cm);
1284 y_cm = quant_band(encode, m, i, Y, NULL, N, b/2, spread, B, intensity, tf_change,
1285 effective_lowband != -1 ? norm2+effective_lowband : NULL, ec, &remaining_bits, LM,
1286 norm2+M*eBands[i], bandE, 0, seed, Q15ONE, lowband_scratch, y_cm);
1287 } else {
1288 x_cm = quant_band(encode, m, i, X, Y, N, b, spread, B, intensity, tf_change,
1289 effective_lowband != -1 ? norm+effective_lowband : NULL, ec, &remaining_bits, LM,
1290 norm+M*eBands[i], bandE, 0, seed, Q15ONE, lowband_scratch, x_cm|y_cm);
1291 y_cm = x_cm;
1292 }
1293 collapse_masks[i*C+0] = (unsigned char)x_cm;
1294 collapse_masks[i*C+C-1] = (unsigned char)y_cm;
1295 balance += pulses[i] + tell;
1296
1297 /* Update the folding position only as long as we have 1 bit/sample depth */
1298 update_lowband = b>(N<<BITRES);
1299 }
1300 RESTORE_STACK;
1301}
1302
diff --git a/lib/rbcodec/codecs/libopus/celt/bands.h b/lib/rbcodec/codecs/libopus/celt/bands.h
new file mode 100644
index 0000000000..9ff8ffd7ba
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/bands.h
@@ -0,0 +1,95 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2008-2009 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifndef BANDS_H
31#define BANDS_H
32
33#include "arch.h"
34#include "modes.h"
35#include "entenc.h"
36#include "entdec.h"
37#include "rate.h"
38
39/** Compute the amplitude (sqrt energy) in each of the bands
40 * @param m Mode data
41 * @param X Spectrum
42 * @param bands Square root of the energy for each band (returned)
43 */
44void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int M);
45
46/*void compute_noise_energies(const CELTMode *m, const celt_sig *X, const opus_val16 *tonality, celt_ener *bandE);*/
47
48/** Normalise each band of X such that the energy in each band is
49 equal to 1
50 * @param m Mode data
51 * @param X Spectrum (returned normalised)
52 * @param bands Square root of the energy for each band
53 */
54void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M);
55
56/** Denormalise each band of X to restore full amplitude
57 * @param m Mode data
58 * @param X Spectrum (returned de-normalised)
59 * @param bands Square root of the energy for each band
60 */
61void denormalise_bands(const CELTMode *m, const celt_norm * OPUS_RESTRICT X, celt_sig * OPUS_RESTRICT freq, const celt_ener *bandE, int end, int C, int M);
62
63#define SPREAD_NONE (0)
64#define SPREAD_LIGHT (1)
65#define SPREAD_NORMAL (2)
66#define SPREAD_AGGRESSIVE (3)
67
68int spreading_decision(const CELTMode *m, celt_norm *X, int *average,
69 int last_decision, int *hf_average, int *tapset_decision, int update_hf,
70 int end, int C, int M);
71
72#ifdef MEASURE_NORM_MSE
73void measure_norm_mse(const CELTMode *m, float *X, float *X0, float *bandE, float *bandE0, int M, int N, int C);
74#endif
75
76void haar1(celt_norm *X, int N0, int stride);
77
78/** Quantisation/encoding of the residual spectrum
79 * @param m Mode data
80 * @param X Residual (normalised)
81 * @param total_bits Total number of bits that can be used for the frame (including the ones already spent)
82 * @param enc Entropy encoder
83 */
84void quant_all_bands(int encode, const CELTMode *m, int start, int end,
85 celt_norm * X, celt_norm * Y, unsigned char *collapse_masks, const celt_ener *bandE, int *pulses,
86 int time_domain, int fold, int dual_stereo, int intensity, int *tf_res,
87 opus_int32 total_bits, opus_int32 balance, ec_ctx *ec, int M, int codedBands, opus_uint32 *seed);
88
89void anti_collapse(const CELTMode *m, celt_norm *X_, unsigned char *collapse_masks, int LM, int C, int size,
90 int start, int end, opus_val16 *logE, opus_val16 *prev1logE,
91 opus_val16 *prev2logE, int *pulses, opus_uint32 seed);
92
93opus_uint32 celt_lcg_rand(opus_uint32 seed);
94
95#endif /* BANDS_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/celt.c b/lib/rbcodec/codecs/libopus/celt/celt.c
new file mode 100644
index 0000000000..8d42cc95b3
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/celt.c
@@ -0,0 +1,2870 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2010 Xiph.Org Foundation
3 Copyright (c) 2008 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifdef HAVE_CONFIG_H
31#include "opus_config.h"
32#endif
33
34#define CELT_C
35
36#include "os_support.h"
37#include "mdct.h"
38#include <math.h>
39#include "celt.h"
40#include "pitch.h"
41#include "bands.h"
42#include "modes.h"
43#include "entcode.h"
44#include "quant_bands.h"
45#include "rate.h"
46#include "stack_alloc.h"
47#include "mathops.h"
48#include "float_cast.h"
49#include <stdarg.h>
50#include "celt_lpc.h"
51#include "vq.h"
52
53#ifndef OPUS_VERSION
54#define OPUS_VERSION "unknown"
55#endif
56
57#ifdef CUSTOM_MODES
58#define OPUS_CUSTOM_NOSTATIC
59#else
60#define OPUS_CUSTOM_NOSTATIC static inline
61#endif
62
63static const unsigned char trim_icdf[11] = {126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0};
64/* Probs: NONE: 21.875%, LIGHT: 6.25%, NORMAL: 65.625%, AGGRESSIVE: 6.25% */
65static const unsigned char spread_icdf[4] = {25, 23, 2, 0};
66
67static const unsigned char tapset_icdf[3]={2,1,0};
68
69#ifdef CUSTOM_MODES
70static const unsigned char toOpusTable[20] = {
71 0xE0, 0xE8, 0xF0, 0xF8,
72 0xC0, 0xC8, 0xD0, 0xD8,
73 0xA0, 0xA8, 0xB0, 0xB8,
74 0x00, 0x00, 0x00, 0x00,
75 0x80, 0x88, 0x90, 0x98,
76};
77
78static const unsigned char fromOpusTable[16] = {
79 0x80, 0x88, 0x90, 0x98,
80 0x40, 0x48, 0x50, 0x58,
81 0x20, 0x28, 0x30, 0x38,
82 0x00, 0x08, 0x10, 0x18
83};
84
85static inline int toOpus(unsigned char c)
86{
87 int ret=0;
88 if (c<0xA0)
89 ret = toOpusTable[c>>3];
90 if (ret == 0)
91 return -1;
92 else
93 return ret|(c&0x7);
94}
95
96static inline int fromOpus(unsigned char c)
97{
98 if (c<0x80)
99 return -1;
100 else
101 return fromOpusTable[(c>>3)-16] | (c&0x7);
102}
103#endif /* CUSTOM_MODES */
104
105#define COMBFILTER_MAXPERIOD 1024
106#define COMBFILTER_MINPERIOD 15
107
108static int resampling_factor(opus_int32 rate)
109{
110 int ret;
111 switch (rate)
112 {
113 case 48000:
114 ret = 1;
115 break;
116 case 24000:
117 ret = 2;
118 break;
119 case 16000:
120 ret = 3;
121 break;
122 case 12000:
123 ret = 4;
124 break;
125 case 8000:
126 ret = 6;
127 break;
128 default:
129#ifndef CUSTOM_MODES
130 celt_assert(0);
131#endif
132 ret = 0;
133 break;
134 }
135 return ret;
136}
137
138/** Encoder state
139 @brief Encoder state
140 */
141struct OpusCustomEncoder {
142 const OpusCustomMode *mode; /**< Mode used by the encoder */
143 int overlap;
144 int channels;
145 int stream_channels;
146
147 int force_intra;
148 int clip;
149 int disable_pf;
150 int complexity;
151 int upsample;
152 int start, end;
153
154 opus_int32 bitrate;
155 int vbr;
156 int signalling;
157 int constrained_vbr; /* If zero, VBR can do whatever it likes with the rate */
158 int loss_rate;
159 int lsb_depth;
160
161 /* Everything beyond this point gets cleared on a reset */
162#define ENCODER_RESET_START rng
163
164 opus_uint32 rng;
165 int spread_decision;
166 opus_val32 delayedIntra;
167 int tonal_average;
168 int lastCodedBands;
169 int hf_average;
170 int tapset_decision;
171
172 int prefilter_period;
173 opus_val16 prefilter_gain;
174 int prefilter_tapset;
175#ifdef RESYNTH
176 int prefilter_period_old;
177 opus_val16 prefilter_gain_old;
178 int prefilter_tapset_old;
179#endif
180 int consec_transient;
181
182 opus_val32 preemph_memE[2];
183 opus_val32 preemph_memD[2];
184
185 /* VBR-related parameters */
186 opus_int32 vbr_reservoir;
187 opus_int32 vbr_drift;
188 opus_int32 vbr_offset;
189 opus_int32 vbr_count;
190
191#ifdef RESYNTH
192 celt_sig syn_mem[2][2*MAX_PERIOD];
193#endif
194
195 celt_sig in_mem[1]; /* Size = channels*mode->overlap */
196 /* celt_sig prefilter_mem[], Size = channels*COMBFILTER_PERIOD */
197 /* celt_sig overlap_mem[], Size = channels*mode->overlap */
198 /* opus_val16 oldEBands[], Size = 2*channels*mode->nbEBands */
199};
200
201int celt_encoder_get_size(int channels)
202{
203 CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
204 return opus_custom_encoder_get_size(mode, channels);
205}
206
207OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_get_size(const CELTMode *mode, int channels)
208{
209 int size = sizeof(struct CELTEncoder)
210 + (2*channels*mode->overlap-1)*sizeof(celt_sig)
211 + channels*COMBFILTER_MAXPERIOD*sizeof(celt_sig)
212 + 3*channels*mode->nbEBands*sizeof(opus_val16);
213 return size;
214}
215
216#ifdef CUSTOM_MODES
217CELTEncoder *opus_custom_encoder_create(const CELTMode *mode, int channels, int *error)
218{
219 int ret;
220 CELTEncoder *st = (CELTEncoder *)opus_alloc(opus_custom_encoder_get_size(mode, channels));
221 /* init will handle the NULL case */
222 ret = opus_custom_encoder_init(st, mode, channels);
223 if (ret != OPUS_OK)
224 {
225 opus_custom_encoder_destroy(st);
226 st = NULL;
227 }
228 if (error)
229 *error = ret;
230 return st;
231}
232#endif /* CUSTOM_MODES */
233
234int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels)
235{
236 int ret;
237 ret = opus_custom_encoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
238 if (ret != OPUS_OK)
239 return ret;
240 st->upsample = resampling_factor(sampling_rate);
241 return OPUS_OK;
242}
243
244OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels)
245{
246 if (channels < 0 || channels > 2)
247 return OPUS_BAD_ARG;
248
249 if (st==NULL || mode==NULL)
250 return OPUS_ALLOC_FAIL;
251
252 OPUS_CLEAR((char*)st, opus_custom_encoder_get_size(mode, channels));
253
254 st->mode = mode;
255 st->overlap = mode->overlap;
256 st->stream_channels = st->channels = channels;
257
258 st->upsample = 1;
259 st->start = 0;
260 st->end = st->mode->effEBands;
261 st->signalling = 1;
262
263 st->constrained_vbr = 1;
264 st->clip = 1;
265
266 st->bitrate = OPUS_BITRATE_MAX;
267 st->vbr = 0;
268 st->force_intra = 0;
269 st->complexity = 5;
270 st->lsb_depth=24;
271
272 opus_custom_encoder_ctl(st, OPUS_RESET_STATE);
273
274 return OPUS_OK;
275}
276
277#ifdef CUSTOM_MODES
278void opus_custom_encoder_destroy(CELTEncoder *st)
279{
280 opus_free(st);
281}
282#endif /* CUSTOM_MODES */
283
284static inline opus_val16 SIG2WORD16(celt_sig x)
285{
286#ifdef FIXED_POINT
287 x = PSHR32(x, SIG_SHIFT);
288 x = MAX32(x, -32768);
289 x = MIN32(x, 32767);
290 return EXTRACT16(x);
291#else
292 return (opus_val16)x;
293#endif
294}
295
296static int transient_analysis(const opus_val32 * OPUS_RESTRICT in, int len, int C,
297 int overlap)
298{
299 int i;
300 VARDECL(opus_val16, tmp);
301 opus_val32 mem0=0,mem1=0;
302 int is_transient = 0;
303 int block;
304 int N;
305 VARDECL(opus_val16, bins);
306 SAVE_STACK;
307 ALLOC(tmp, len, opus_val16);
308
309 block = overlap/2;
310 N=len/block;
311 ALLOC(bins, N, opus_val16);
312 if (C==1)
313 {
314 for (i=0;i<len;i++)
315 tmp[i] = SHR32(in[i],SIG_SHIFT);
316 } else {
317 for (i=0;i<len;i++)
318 tmp[i] = SHR32(ADD32(in[i],in[i+len]), SIG_SHIFT+1);
319 }
320
321 /* High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) */
322 for (i=0;i<len;i++)
323 {
324 opus_val32 x,y;
325 x = tmp[i];
326 y = ADD32(mem0, x);
327#ifdef FIXED_POINT
328 mem0 = mem1 + y - SHL32(x,1);
329 mem1 = x - SHR32(y,1);
330#else
331 mem0 = mem1 + y - 2*x;
332 mem1 = x - .5f*y;
333#endif
334 tmp[i] = EXTRACT16(SHR32(y,2));
335 }
336 /* First few samples are bad because we don't propagate the memory */
337 for (i=0;i<12;i++)
338 tmp[i] = 0;
339
340 for (i=0;i<N;i++)
341 {
342 int j;
343 opus_val16 max_abs=0;
344 for (j=0;j<block;j++)
345 max_abs = MAX16(max_abs, ABS16(tmp[i*block+j]));
346 bins[i] = max_abs;
347 }
348 for (i=0;i<N;i++)
349 {
350 int j;
351 int conseq=0;
352 opus_val16 t1, t2, t3;
353
354 t1 = MULT16_16_Q15(QCONST16(.15f, 15), bins[i]);
355 t2 = MULT16_16_Q15(QCONST16(.4f, 15), bins[i]);
356 t3 = MULT16_16_Q15(QCONST16(.15f, 15), bins[i]);
357 for (j=0;j<i;j++)
358 {
359 if (bins[j] < t1)
360 conseq++;
361 if (bins[j] < t2)
362 conseq++;
363 else
364 conseq = 0;
365 }
366 if (conseq>=3)
367 is_transient=1;
368 conseq = 0;
369 for (j=i+1;j<N;j++)
370 {
371 if (bins[j] < t3)
372 conseq++;
373 else
374 conseq = 0;
375 }
376 if (conseq>=7)
377 is_transient=1;
378 }
379 RESTORE_STACK;
380#ifdef FUZZING
381 is_transient = rand()&0x1;
382#endif
383 return is_transient;
384}
385
386/** Apply window and compute the MDCT for all sub-frames and
387 all channels in a frame */
388static void compute_mdcts(const CELTMode *mode, int shortBlocks, celt_sig * OPUS_RESTRICT in, celt_sig * OPUS_RESTRICT out, int C, int LM)
389{
390 if (C==1 && !shortBlocks)
391 {
392 const int overlap = OVERLAP(mode);
393 clt_mdct_forward(&mode->mdct, in, out, mode->window, overlap, mode->maxLM-LM, 1);
394 } else {
395 const int overlap = OVERLAP(mode);
396 int N = mode->shortMdctSize<<LM;
397 int B = 1;
398 int b, c;
399 if (shortBlocks)
400 {
401 N = mode->shortMdctSize;
402 B = shortBlocks;
403 }
404 c=0; do {
405 for (b=0;b<B;b++)
406 {
407 /* Interleaving the sub-frames while doing the MDCTs */
408 clt_mdct_forward(&mode->mdct, in+c*(B*N+overlap)+b*N, &out[b+c*N*B], mode->window, overlap, shortBlocks ? mode->maxLM : mode->maxLM-LM, B);
409 }
410 } while (++c<C);
411 }
412}
413
414/** Compute the IMDCT and apply window for all sub-frames and
415 all channels in a frame */
416static void compute_inv_mdcts(const CELTMode *mode, int shortBlocks, celt_sig *X,
417 celt_sig * OPUS_RESTRICT out_mem[],
418 celt_sig * OPUS_RESTRICT overlap_mem[], int C, int LM)
419{
420 int c;
421 const int N = mode->shortMdctSize<<LM;
422 const int overlap = OVERLAP(mode);
423 VARDECL(opus_val32, x);
424 SAVE_STACK;
425
426 ALLOC(x, N+overlap, opus_val32);
427 c=0; do {
428 int j;
429 int b;
430 int N2 = N;
431 int B = 1;
432
433 if (shortBlocks)
434 {
435 N2 = mode->shortMdctSize;
436 B = shortBlocks;
437 }
438 /* Prevents problems from the imdct doing the overlap-add */
439 OPUS_CLEAR(x, overlap);
440
441 for (b=0;b<B;b++)
442 {
443 /* IMDCT on the interleaved the sub-frames */
444 clt_mdct_backward(&mode->mdct, &X[b+c*N2*B], x+N2*b, mode->window, overlap, shortBlocks ? mode->maxLM : mode->maxLM-LM, B);
445 }
446
447 for (j=0;j<overlap;j++)
448 out_mem[c][j] = x[j] + overlap_mem[c][j];
449 for (;j<N;j++)
450 out_mem[c][j] = x[j];
451 for (j=0;j<overlap;j++)
452 overlap_mem[c][j] = x[N+j];
453 } while (++c<C);
454 RESTORE_STACK;
455}
456
457static void deemphasis(celt_sig *in[], opus_val16 *pcm, int N, int C, int downsample, const opus_val16 *coef, celt_sig *mem)
458{
459 int c;
460 int count=0;
461 c=0; do {
462 int j;
463 celt_sig * OPUS_RESTRICT x;
464 opus_val16 * OPUS_RESTRICT y;
465 celt_sig m = mem[c];
466 x =in[c];
467 y = pcm+c;
468 for (j=0;j<N;j++)
469 {
470 celt_sig tmp = *x + m;
471 m = MULT16_32_Q15(coef[0], tmp)
472 - MULT16_32_Q15(coef[1], *x);
473 tmp = SHL32(MULT16_32_Q15(coef[3], tmp), 2);
474 x++;
475 /* Technically the store could be moved outside of the if because
476 the stores we don't want will just be overwritten */
477 if (count==0)
478 *y = SCALEOUT(SIG2WORD16(tmp));
479 if (++count==downsample)
480 {
481 y+=C;
482 count=0;
483 }
484 }
485 mem[c] = m;
486 } while (++c<C);
487}
488
489static void comb_filter(opus_val32 *y, opus_val32 *x, int T0, int T1, int N,
490 opus_val16 g0, opus_val16 g1, int tapset0, int tapset1,
491 const opus_val16 *window, int overlap)
492{
493 int i;
494 /* printf ("%d %d %f %f\n", T0, T1, g0, g1); */
495 opus_val16 g00, g01, g02, g10, g11, g12;
496 static const opus_val16 gains[3][3] = {
497 {QCONST16(0.3066406250f, 15), QCONST16(0.2170410156f, 15), QCONST16(0.1296386719f, 15)},
498 {QCONST16(0.4638671875f, 15), QCONST16(0.2680664062f, 15), QCONST16(0.f, 15)},
499 {QCONST16(0.7998046875f, 15), QCONST16(0.1000976562f, 15), QCONST16(0.f, 15)}};
500 g00 = MULT16_16_Q15(g0, gains[tapset0][0]);
501 g01 = MULT16_16_Q15(g0, gains[tapset0][1]);
502 g02 = MULT16_16_Q15(g0, gains[tapset0][2]);
503 g10 = MULT16_16_Q15(g1, gains[tapset1][0]);
504 g11 = MULT16_16_Q15(g1, gains[tapset1][1]);
505 g12 = MULT16_16_Q15(g1, gains[tapset1][2]);
506 for (i=0;i<overlap;i++)
507 {
508 opus_val16 f;
509 f = MULT16_16_Q15(window[i],window[i]);
510 y[i] = x[i]
511 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g00),x[i-T0])
512 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g01),x[i-T0-1])
513 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g01),x[i-T0+1])
514 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g02),x[i-T0-2])
515 + MULT16_32_Q15(MULT16_16_Q15((Q15ONE-f),g02),x[i-T0+2])
516 + MULT16_32_Q15(MULT16_16_Q15(f,g10),x[i-T1])
517 + MULT16_32_Q15(MULT16_16_Q15(f,g11),x[i-T1-1])
518 + MULT16_32_Q15(MULT16_16_Q15(f,g11),x[i-T1+1])
519 + MULT16_32_Q15(MULT16_16_Q15(f,g12),x[i-T1-2])
520 + MULT16_32_Q15(MULT16_16_Q15(f,g12),x[i-T1+2]);
521
522 }
523 for (i=overlap;i<N;i++)
524 y[i] = x[i]
525 + MULT16_32_Q15(g10,x[i-T1])
526 + MULT16_32_Q15(g11,x[i-T1-1])
527 + MULT16_32_Q15(g11,x[i-T1+1])
528 + MULT16_32_Q15(g12,x[i-T1-2])
529 + MULT16_32_Q15(g12,x[i-T1+2]);
530}
531
532static const signed char tf_select_table[4][8] = {
533 {0, -1, 0, -1, 0,-1, 0,-1},
534 {0, -1, 0, -2, 1, 0, 1,-1},
535 {0, -2, 0, -3, 2, 0, 1,-1},
536 {0, -2, 0, -3, 3, 0, 1,-1},
537};
538
539static opus_val32 l1_metric(const celt_norm *tmp, int N, int LM, int width)
540{
541 int i, j;
542 static const opus_val16 sqrtM_1[4] = {Q15ONE, QCONST16(.70710678f,15), QCONST16(0.5f,15), QCONST16(0.35355339f,15)};
543 opus_val32 L1;
544 opus_val16 bias;
545 L1=0;
546 for (i=0;i<1<<LM;i++)
547 {
548 opus_val32 L2 = 0;
549 for (j=0;j<N>>LM;j++)
550 L2 = MAC16_16(L2, tmp[(j<<LM)+i], tmp[(j<<LM)+i]);
551 L1 += celt_sqrt(L2);
552 }
553 L1 = MULT16_32_Q15(sqrtM_1[LM], L1);
554 if (width==1)
555 bias = QCONST16(.12f,15)*LM;
556 else if (width==2)
557 bias = QCONST16(.05f,15)*LM;
558 else
559 bias = QCONST16(.02f,15)*LM;
560 L1 = MAC16_32_Q15(L1, bias, L1);
561 return L1;
562}
563
564static int tf_analysis(const CELTMode *m, int len, int C, int isTransient,
565 int *tf_res, int nbCompressedBytes, celt_norm *X, int N0, int LM,
566 int *tf_sum)
567{
568 int i;
569 VARDECL(int, metric);
570 int cost0;
571 int cost1;
572 VARDECL(int, path0);
573 VARDECL(int, path1);
574 VARDECL(celt_norm, tmp);
575 int lambda;
576 int tf_select=0;
577 SAVE_STACK;
578
579 if (nbCompressedBytes<15*C)
580 {
581 *tf_sum = 0;
582 for (i=0;i<len;i++)
583 tf_res[i] = isTransient;
584 return 0;
585 }
586 if (nbCompressedBytes<40)
587 lambda = 12;
588 else if (nbCompressedBytes<60)
589 lambda = 6;
590 else if (nbCompressedBytes<100)
591 lambda = 4;
592 else
593 lambda = 3;
594
595 ALLOC(metric, len, int);
596 ALLOC(tmp, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
597 ALLOC(path0, len, int);
598 ALLOC(path1, len, int);
599
600 *tf_sum = 0;
601 for (i=0;i<len;i++)
602 {
603 int j, k, N;
604 opus_val32 L1, best_L1;
605 int best_level=0;
606 N = (m->eBands[i+1]-m->eBands[i])<<LM;
607 for (j=0;j<N;j++)
608 tmp[j] = X[j+(m->eBands[i]<<LM)];
609 /* Just add the right channel if we're in stereo */
610 if (C==2)
611 for (j=0;j<N;j++)
612 tmp[j] = ADD16(SHR16(tmp[j], 1),SHR16(X[N0+j+(m->eBands[i]<<LM)], 1));
613 L1 = l1_metric(tmp, N, isTransient ? LM : 0, N>>LM);
614 best_L1 = L1;
615 /*printf ("%f ", L1);*/
616 for (k=0;k<LM;k++)
617 {
618 int B;
619
620 if (isTransient)
621 B = (LM-k-1);
622 else
623 B = k+1;
624
625 if (isTransient)
626 haar1(tmp, N>>(LM-k), 1<<(LM-k));
627 else
628 haar1(tmp, N>>k, 1<<k);
629
630 L1 = l1_metric(tmp, N, B, N>>LM);
631
632 if (L1 < best_L1)
633 {
634 best_L1 = L1;
635 best_level = k+1;
636 }
637 }
638 /*printf ("%d ", isTransient ? LM-best_level : best_level);*/
639 if (isTransient)
640 metric[i] = best_level;
641 else
642 metric[i] = -best_level;
643 *tf_sum += metric[i];
644 }
645 /*printf("\n");*/
646 /* NOTE: Future optimized implementations could detect extreme transients and set
647 tf_select = 1 but so far we have not found a reliable way of making this useful */
648 tf_select = 0;
649
650 cost0 = 0;
651 cost1 = isTransient ? 0 : lambda;
652 /* Viterbi forward pass */
653 for (i=1;i<len;i++)
654 {
655 int curr0, curr1;
656 int from0, from1;
657
658 from0 = cost0;
659 from1 = cost1 + lambda;
660 if (from0 < from1)
661 {
662 curr0 = from0;
663 path0[i]= 0;
664 } else {
665 curr0 = from1;
666 path0[i]= 1;
667 }
668
669 from0 = cost0 + lambda;
670 from1 = cost1;
671 if (from0 < from1)
672 {
673 curr1 = from0;
674 path1[i]= 0;
675 } else {
676 curr1 = from1;
677 path1[i]= 1;
678 }
679 cost0 = curr0 + abs(metric[i]-tf_select_table[LM][4*isTransient+2*tf_select+0]);
680 cost1 = curr1 + abs(metric[i]-tf_select_table[LM][4*isTransient+2*tf_select+1]);
681 }
682 tf_res[len-1] = cost0 < cost1 ? 0 : 1;
683 /* Viterbi backward pass to check the decisions */
684 for (i=len-2;i>=0;i--)
685 {
686 if (tf_res[i+1] == 1)
687 tf_res[i] = path1[i+1];
688 else
689 tf_res[i] = path0[i+1];
690 }
691 RESTORE_STACK;
692#ifdef FUZZING
693 tf_select = rand()&0x1;
694 tf_res[0] = rand()&0x1;
695 for (i=1;i<len;i++)
696 tf_res[i] = tf_res[i-1] ^ ((rand()&0xF) == 0);
697#endif
698 return tf_select;
699}
700
701static void tf_encode(int start, int end, int isTransient, int *tf_res, int LM, int tf_select, ec_enc *enc)
702{
703 int curr, i;
704 int tf_select_rsv;
705 int tf_changed;
706 int logp;
707 opus_uint32 budget;
708 opus_uint32 tell;
709 budget = enc->storage*8;
710 tell = ec_tell(enc);
711 logp = isTransient ? 2 : 4;
712 /* Reserve space to code the tf_select decision. */
713 tf_select_rsv = LM>0 && tell+logp+1 <= budget;
714 budget -= tf_select_rsv;
715 curr = tf_changed = 0;
716 for (i=start;i<end;i++)
717 {
718 if (tell+logp<=budget)
719 {
720 ec_enc_bit_logp(enc, tf_res[i] ^ curr, logp);
721 tell = ec_tell(enc);
722 curr = tf_res[i];
723 tf_changed |= curr;
724 }
725 else
726 tf_res[i] = curr;
727 logp = isTransient ? 4 : 5;
728 }
729 /* Only code tf_select if it would actually make a difference. */
730 if (tf_select_rsv &&
731 tf_select_table[LM][4*isTransient+0+tf_changed]!=
732 tf_select_table[LM][4*isTransient+2+tf_changed])
733 ec_enc_bit_logp(enc, tf_select, 1);
734 else
735 tf_select = 0;
736 for (i=start;i<end;i++)
737 tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
738 /*printf("%d %d ", isTransient, tf_select); for(i=0;i<end;i++)printf("%d ", tf_res[i]);printf("\n");*/
739}
740
741static void tf_decode(int start, int end, int isTransient, int *tf_res, int LM, ec_dec *dec)
742{
743 int i, curr, tf_select;
744 int tf_select_rsv;
745 int tf_changed;
746 int logp;
747 opus_uint32 budget;
748 opus_uint32 tell;
749
750 budget = dec->storage*8;
751 tell = ec_tell(dec);
752 logp = isTransient ? 2 : 4;
753 tf_select_rsv = LM>0 && tell+logp+1<=budget;
754 budget -= tf_select_rsv;
755 tf_changed = curr = 0;
756 for (i=start;i<end;i++)
757 {
758 if (tell+logp<=budget)
759 {
760 curr ^= ec_dec_bit_logp(dec, logp);
761 tell = ec_tell(dec);
762 tf_changed |= curr;
763 }
764 tf_res[i] = curr;
765 logp = isTransient ? 4 : 5;
766 }
767 tf_select = 0;
768 if (tf_select_rsv &&
769 tf_select_table[LM][4*isTransient+0+tf_changed] !=
770 tf_select_table[LM][4*isTransient+2+tf_changed])
771 {
772 tf_select = ec_dec_bit_logp(dec, 1);
773 }
774 for (i=start;i<end;i++)
775 {
776 tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
777 }
778}
779
780static void init_caps(const CELTMode *m,int *cap,int LM,int C)
781{
782 int i;
783 for (i=0;i<m->nbEBands;i++)
784 {
785 int N;
786 N=(m->eBands[i+1]-m->eBands[i])<<LM;
787 cap[i] = (m->cache.caps[m->nbEBands*(2*LM+C-1)+i]+64)*C*N>>2;
788 }
789}
790
791static int alloc_trim_analysis(const CELTMode *m, const celt_norm *X,
792 const opus_val16 *bandLogE, int end, int LM, int C, int N0)
793{
794 int i;
795 opus_val32 diff=0;
796 int c;
797 int trim_index = 5;
798 if (C==2)
799 {
800 opus_val16 sum = 0; /* Q10 */
801 /* Compute inter-channel correlation for low frequencies */
802 for (i=0;i<8;i++)
803 {
804 int j;
805 opus_val32 partial = 0;
806 for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
807 partial = MAC16_16(partial, X[j], X[N0+j]);
808 sum = ADD16(sum, EXTRACT16(SHR32(partial, 18)));
809 }
810 sum = MULT16_16_Q15(QCONST16(1.f/8, 15), sum);
811 /*printf ("%f\n", sum);*/
812 if (sum > QCONST16(.995f,10))
813 trim_index-=4;
814 else if (sum > QCONST16(.92f,10))
815 trim_index-=3;
816 else if (sum > QCONST16(.85f,10))
817 trim_index-=2;
818 else if (sum > QCONST16(.8f,10))
819 trim_index-=1;
820 }
821
822 /* Estimate spectral tilt */
823 c=0; do {
824 for (i=0;i<end-1;i++)
825 {
826 diff += bandLogE[i+c*m->nbEBands]*(opus_int32)(2+2*i-m->nbEBands);
827 }
828 } while (++c<C);
829 /* We divide by two here to avoid making the tilt larger for stereo as a
830 result of a bug in the loop above */
831 diff /= 2*C*(end-1);
832 /*printf("%f\n", diff);*/
833 if (diff > QCONST16(2.f, DB_SHIFT))
834 trim_index--;
835 if (diff > QCONST16(8.f, DB_SHIFT))
836 trim_index--;
837 if (diff < -QCONST16(4.f, DB_SHIFT))
838 trim_index++;
839 if (diff < -QCONST16(10.f, DB_SHIFT))
840 trim_index++;
841
842 if (trim_index<0)
843 trim_index = 0;
844 if (trim_index>10)
845 trim_index = 10;
846#ifdef FUZZING
847 trim_index = rand()%11;
848#endif
849 return trim_index;
850}
851
852static int stereo_analysis(const CELTMode *m, const celt_norm *X,
853 int LM, int N0)
854{
855 int i;
856 int thetas;
857 opus_val32 sumLR = EPSILON, sumMS = EPSILON;
858
859 /* Use the L1 norm to model the entropy of the L/R signal vs the M/S signal */
860 for (i=0;i<13;i++)
861 {
862 int j;
863 for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
864 {
865 opus_val32 L, R, M, S;
866 /* We cast to 32-bit first because of the -32768 case */
867 L = EXTEND32(X[j]);
868 R = EXTEND32(X[N0+j]);
869 M = ADD32(L, R);
870 S = SUB32(L, R);
871 sumLR = ADD32(sumLR, ADD32(ABS32(L), ABS32(R)));
872 sumMS = ADD32(sumMS, ADD32(ABS32(M), ABS32(S)));
873 }
874 }
875 sumMS = MULT16_32_Q15(QCONST16(0.707107f, 15), sumMS);
876 thetas = 13;
877 /* We don't need thetas for lower bands with LM<=1 */
878 if (LM<=1)
879 thetas -= 8;
880 return MULT16_32_Q15((m->eBands[13]<<(LM+1))+thetas, sumMS)
881 > MULT16_32_Q15(m->eBands[13]<<(LM+1), sumLR);
882}
883
884int celt_encode_with_ec(CELTEncoder * OPUS_RESTRICT st, const opus_val16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc)
885{
886 int i, c, N;
887 opus_int32 bits;
888 ec_enc _enc;
889 VARDECL(celt_sig, in);
890 VARDECL(celt_sig, freq);
891 VARDECL(celt_norm, X);
892 VARDECL(celt_ener, bandE);
893 VARDECL(opus_val16, bandLogE);
894 VARDECL(int, fine_quant);
895 VARDECL(opus_val16, error);
896 VARDECL(int, pulses);
897 VARDECL(int, cap);
898 VARDECL(int, offsets);
899 VARDECL(int, fine_priority);
900 VARDECL(int, tf_res);
901 VARDECL(unsigned char, collapse_masks);
902 celt_sig *prefilter_mem;
903 opus_val16 *oldBandE, *oldLogE, *oldLogE2;
904 int shortBlocks=0;
905 int isTransient=0;
906 const int CC = st->channels;
907 const int C = st->stream_channels;
908 int LM, M;
909 int tf_select;
910 int nbFilledBytes, nbAvailableBytes;
911 int effEnd;
912 int codedBands;
913 int tf_sum;
914 int alloc_trim;
915 int pitch_index=COMBFILTER_MINPERIOD;
916 opus_val16 gain1 = 0;
917 int intensity=0;
918 int dual_stereo=0;
919 int effectiveBytes;
920 opus_val16 pf_threshold;
921 int dynalloc_logp;
922 opus_int32 vbr_rate;
923 opus_int32 total_bits;
924 opus_int32 total_boost;
925 opus_int32 balance;
926 opus_int32 tell;
927 int prefilter_tapset=0;
928 int pf_on;
929 int anti_collapse_rsv;
930 int anti_collapse_on=0;
931 int silence=0;
932 ALLOC_STACK;
933
934 if (nbCompressedBytes<2 || pcm==NULL)
935 return OPUS_BAD_ARG;
936
937 frame_size *= st->upsample;
938 for (LM=0;LM<=st->mode->maxLM;LM++)
939 if (st->mode->shortMdctSize<<LM==frame_size)
940 break;
941 if (LM>st->mode->maxLM)
942 return OPUS_BAD_ARG;
943 M=1<<LM;
944 N = M*st->mode->shortMdctSize;
945
946 prefilter_mem = st->in_mem+CC*(st->overlap);
947 oldBandE = (opus_val16*)(st->in_mem+CC*(2*st->overlap+COMBFILTER_MAXPERIOD));
948 oldLogE = oldBandE + CC*st->mode->nbEBands;
949 oldLogE2 = oldLogE + CC*st->mode->nbEBands;
950
951 if (enc==NULL)
952 {
953 tell=1;
954 nbFilledBytes=0;
955 } else {
956 tell=ec_tell(enc);
957 nbFilledBytes=(tell+4)>>3;
958 }
959
960#ifdef CUSTOM_MODES
961 if (st->signalling && enc==NULL)
962 {
963 int tmp = (st->mode->effEBands-st->end)>>1;
964 st->end = IMAX(1, st->mode->effEBands-tmp);
965 compressed[0] = tmp<<5;
966 compressed[0] |= LM<<3;
967 compressed[0] |= (C==2)<<2;
968 /* Convert "standard mode" to Opus header */
969 if (st->mode->Fs==48000 && st->mode->shortMdctSize==120)
970 {
971 int c0 = toOpus(compressed[0]);
972 if (c0<0)
973 return OPUS_BAD_ARG;
974 compressed[0] = c0;
975 }
976 compressed++;
977 nbCompressedBytes--;
978 }
979#else
980 celt_assert(st->signalling==0);
981#endif
982
983 /* Can't produce more than 1275 output bytes */
984 nbCompressedBytes = IMIN(nbCompressedBytes,1275);
985 nbAvailableBytes = nbCompressedBytes - nbFilledBytes;
986
987 if (st->vbr && st->bitrate!=OPUS_BITRATE_MAX)
988 {
989 opus_int32 den=st->mode->Fs>>BITRES;
990 vbr_rate=(st->bitrate*frame_size+(den>>1))/den;
991#ifdef CUSTOM_MODES
992 if (st->signalling)
993 vbr_rate -= 8<<BITRES;
994#endif
995 effectiveBytes = vbr_rate>>(3+BITRES);
996 } else {
997 opus_int32 tmp;
998 vbr_rate = 0;
999 tmp = st->bitrate*frame_size;
1000 if (tell>1)
1001 tmp += tell;
1002 if (st->bitrate!=OPUS_BITRATE_MAX)
1003 nbCompressedBytes = IMAX(2, IMIN(nbCompressedBytes,
1004 (tmp+4*st->mode->Fs)/(8*st->mode->Fs)-!!st->signalling));
1005 effectiveBytes = nbCompressedBytes;
1006 }
1007
1008 if (enc==NULL)
1009 {
1010 ec_enc_init(&_enc, compressed, nbCompressedBytes);
1011 enc = &_enc;
1012 }
1013
1014 if (vbr_rate>0)
1015 {
1016 /* Computes the max bit-rate allowed in VBR mode to avoid violating the
1017 target rate and buffering.
1018 We must do this up front so that bust-prevention logic triggers
1019 correctly if we don't have enough bits. */
1020 if (st->constrained_vbr)
1021 {
1022 opus_int32 vbr_bound;
1023 opus_int32 max_allowed;
1024 /* We could use any multiple of vbr_rate as bound (depending on the
1025 delay).
1026 This is clamped to ensure we use at least two bytes if the encoder
1027 was entirely empty, but to allow 0 in hybrid mode. */
1028 vbr_bound = vbr_rate;
1029 max_allowed = IMIN(IMAX(tell==1?2:0,
1030 (vbr_rate+vbr_bound-st->vbr_reservoir)>>(BITRES+3)),
1031 nbAvailableBytes);
1032 if(max_allowed < nbAvailableBytes)
1033 {
1034 nbCompressedBytes = nbFilledBytes+max_allowed;
1035 nbAvailableBytes = max_allowed;
1036 ec_enc_shrink(enc, nbCompressedBytes);
1037 }
1038 }
1039 }
1040 total_bits = nbCompressedBytes*8;
1041
1042 effEnd = st->end;
1043 if (effEnd > st->mode->effEBands)
1044 effEnd = st->mode->effEBands;
1045
1046 ALLOC(in, CC*(N+st->overlap), celt_sig);
1047
1048 /* Find pitch period and gain */
1049 {
1050 VARDECL(celt_sig, _pre);
1051 celt_sig *pre[2];
1052 SAVE_STACK;
1053 ALLOC(_pre, CC*(N+COMBFILTER_MAXPERIOD), celt_sig);
1054
1055 pre[0] = _pre;
1056 pre[1] = _pre + (N+COMBFILTER_MAXPERIOD);
1057
1058 silence = 1;
1059 c=0; do {
1060 int count = 0;
1061 const opus_val16 * OPUS_RESTRICT pcmp = pcm+c;
1062 celt_sig * OPUS_RESTRICT inp = in+c*(N+st->overlap)+st->overlap;
1063
1064 for (i=0;i<N;i++)
1065 {
1066 celt_sig x, tmp;
1067
1068 x = SCALEIN(*pcmp);
1069#ifndef FIXED_POINT
1070 if (!(x==x))
1071 x = 0;
1072 if (st->clip)
1073 x = MAX32(-65536.f, MIN32(65536.f,x));
1074#endif
1075 if (++count==st->upsample)
1076 {
1077 count=0;
1078 pcmp+=CC;
1079 } else {
1080 x = 0;
1081 }
1082 /* Apply pre-emphasis */
1083 tmp = MULT16_16(st->mode->preemph[2], x);
1084 *inp = tmp + st->preemph_memE[c];
1085 st->preemph_memE[c] = MULT16_32_Q15(st->mode->preemph[1], *inp)
1086 - MULT16_32_Q15(st->mode->preemph[0], tmp);
1087 silence = silence && *inp == 0;
1088 inp++;
1089 }
1090 OPUS_COPY(pre[c], prefilter_mem+c*COMBFILTER_MAXPERIOD, COMBFILTER_MAXPERIOD);
1091 OPUS_COPY(pre[c]+COMBFILTER_MAXPERIOD, in+c*(N+st->overlap)+st->overlap, N);
1092 } while (++c<CC);
1093
1094#ifdef FUZZING
1095 if ((rand()&0x3F)==0)
1096 silence = 1;
1097#endif
1098 if (tell==1)
1099 ec_enc_bit_logp(enc, silence, 15);
1100 else
1101 silence=0;
1102 if (silence)
1103 {
1104 /*In VBR mode there is no need to send more than the minimum. */
1105 if (vbr_rate>0)
1106 {
1107 effectiveBytes=nbCompressedBytes=IMIN(nbCompressedBytes, nbFilledBytes+2);
1108 total_bits=nbCompressedBytes*8;
1109 nbAvailableBytes=2;
1110 ec_enc_shrink(enc, nbCompressedBytes);
1111 }
1112 /* Pretend we've filled all the remaining bits with zeros
1113 (that's what the initialiser did anyway) */
1114 tell = nbCompressedBytes*8;
1115 enc->nbits_total+=tell-ec_tell(enc);
1116 }
1117 if (nbAvailableBytes>12*C && st->start==0 && !silence && !st->disable_pf && st->complexity >= 5)
1118 {
1119 VARDECL(opus_val16, pitch_buf);
1120 ALLOC(pitch_buf, (COMBFILTER_MAXPERIOD+N)>>1, opus_val16);
1121
1122 pitch_downsample(pre, pitch_buf, COMBFILTER_MAXPERIOD+N, CC);
1123 pitch_search(pitch_buf+(COMBFILTER_MAXPERIOD>>1), pitch_buf, N,
1124 COMBFILTER_MAXPERIOD-COMBFILTER_MINPERIOD, &pitch_index);
1125 pitch_index = COMBFILTER_MAXPERIOD-pitch_index;
1126
1127 gain1 = remove_doubling(pitch_buf, COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD,
1128 N, &pitch_index, st->prefilter_period, st->prefilter_gain);
1129 if (pitch_index > COMBFILTER_MAXPERIOD-2)
1130 pitch_index = COMBFILTER_MAXPERIOD-2;
1131 gain1 = MULT16_16_Q15(QCONST16(.7f,15),gain1);
1132 if (st->loss_rate>2)
1133 gain1 = HALF32(gain1);
1134 if (st->loss_rate>4)
1135 gain1 = HALF32(gain1);
1136 if (st->loss_rate>8)
1137 gain1 = 0;
1138 prefilter_tapset = st->tapset_decision;
1139 } else {
1140 gain1 = 0;
1141 }
1142
1143 /* Gain threshold for enabling the prefilter/postfilter */
1144 pf_threshold = QCONST16(.2f,15);
1145
1146 /* Adjusting the threshold based on rate and continuity */
1147 if (abs(pitch_index-st->prefilter_period)*10>pitch_index)
1148 pf_threshold += QCONST16(.2f,15);
1149 if (nbAvailableBytes<25)
1150 pf_threshold += QCONST16(.1f,15);
1151 if (nbAvailableBytes<35)
1152 pf_threshold += QCONST16(.1f,15);
1153 if (st->prefilter_gain > QCONST16(.4f,15))
1154 pf_threshold -= QCONST16(.1f,15);
1155 if (st->prefilter_gain > QCONST16(.55f,15))
1156 pf_threshold -= QCONST16(.1f,15);
1157
1158 /* Hard threshold at 0.2 */
1159 pf_threshold = MAX16(pf_threshold, QCONST16(.2f,15));
1160 if (gain1<pf_threshold)
1161 {
1162 if(st->start==0 && tell+16<=total_bits)
1163 ec_enc_bit_logp(enc, 0, 1);
1164 gain1 = 0;
1165 pf_on = 0;
1166 } else {
1167 /*This block is not gated by a total bits check only because
1168 of the nbAvailableBytes check above.*/
1169 int qg;
1170 int octave;
1171
1172 if (ABS16(gain1-st->prefilter_gain)<QCONST16(.1f,15))
1173 gain1=st->prefilter_gain;
1174
1175#ifdef FIXED_POINT
1176 qg = ((gain1+1536)>>10)/3-1;
1177#else
1178 qg = (int)floor(.5f+gain1*32/3)-1;
1179#endif
1180 qg = IMAX(0, IMIN(7, qg));
1181 ec_enc_bit_logp(enc, 1, 1);
1182 pitch_index += 1;
1183 octave = EC_ILOG(pitch_index)-5;
1184 ec_enc_uint(enc, octave, 6);
1185 ec_enc_bits(enc, pitch_index-(16<<octave), 4+octave);
1186 pitch_index -= 1;
1187 ec_enc_bits(enc, qg, 3);
1188 if (ec_tell(enc)+2<=total_bits)
1189 ec_enc_icdf(enc, prefilter_tapset, tapset_icdf, 2);
1190 else
1191 prefilter_tapset = 0;
1192 gain1 = QCONST16(0.09375f,15)*(qg+1);
1193 pf_on = 1;
1194 }
1195 /*printf("%d %f\n", pitch_index, gain1);*/
1196
1197 c=0; do {
1198 int offset = st->mode->shortMdctSize-st->mode->overlap;
1199 st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
1200 OPUS_COPY(in+c*(N+st->overlap), st->in_mem+c*(st->overlap), st->overlap);
1201 if (offset)
1202 comb_filter(in+c*(N+st->overlap)+st->overlap, pre[c]+COMBFILTER_MAXPERIOD,
1203 st->prefilter_period, st->prefilter_period, offset, -st->prefilter_gain, -st->prefilter_gain,
1204 st->prefilter_tapset, st->prefilter_tapset, NULL, 0);
1205
1206 comb_filter(in+c*(N+st->overlap)+st->overlap+offset, pre[c]+COMBFILTER_MAXPERIOD+offset,
1207 st->prefilter_period, pitch_index, N-offset, -st->prefilter_gain, -gain1,
1208 st->prefilter_tapset, prefilter_tapset, st->mode->window, st->mode->overlap);
1209 OPUS_COPY(st->in_mem+c*(st->overlap), in+c*(N+st->overlap)+N, st->overlap);
1210
1211 if (N>COMBFILTER_MAXPERIOD)
1212 {
1213 OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, pre[c]+N, COMBFILTER_MAXPERIOD);
1214 } else {
1215 OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, prefilter_mem+c*COMBFILTER_MAXPERIOD+N, COMBFILTER_MAXPERIOD-N);
1216 OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD+COMBFILTER_MAXPERIOD-N, pre[c]+COMBFILTER_MAXPERIOD, N);
1217 }
1218 } while (++c<CC);
1219
1220 RESTORE_STACK;
1221 }
1222
1223 isTransient = 0;
1224 shortBlocks = 0;
1225 if (LM>0 && ec_tell(enc)+3<=total_bits)
1226 {
1227 if (st->complexity > 1)
1228 {
1229 isTransient = transient_analysis(in, N+st->overlap, CC,
1230 st->overlap);
1231 if (isTransient)
1232 shortBlocks = M;
1233 }
1234 ec_enc_bit_logp(enc, isTransient, 3);
1235 }
1236
1237 ALLOC(freq, CC*N, celt_sig); /**< Interleaved signal MDCTs */
1238 ALLOC(bandE,st->mode->nbEBands*CC, celt_ener);
1239 ALLOC(bandLogE,st->mode->nbEBands*CC, opus_val16);
1240 /* Compute MDCTs */
1241 compute_mdcts(st->mode, shortBlocks, in, freq, CC, LM);
1242
1243 if (CC==2&&C==1)
1244 {
1245 for (i=0;i<N;i++)
1246 freq[i] = ADD32(HALF32(freq[i]), HALF32(freq[N+i]));
1247 }
1248 if (st->upsample != 1)
1249 {
1250 c=0; do
1251 {
1252 int bound = N/st->upsample;
1253 for (i=0;i<bound;i++)
1254 freq[c*N+i] *= st->upsample;
1255 for (;i<N;i++)
1256 freq[c*N+i] = 0;
1257 } while (++c<C);
1258 }
1259 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
1260
1261 compute_band_energies(st->mode, freq, bandE, effEnd, C, M);
1262
1263 amp2Log2(st->mode, effEnd, st->end, bandE, bandLogE, C);
1264
1265 /* Band normalisation */
1266 normalise_bands(st->mode, freq, X, bandE, effEnd, C, M);
1267
1268 ALLOC(tf_res, st->mode->nbEBands, int);
1269 tf_select = tf_analysis(st->mode, effEnd, C, isTransient, tf_res, effectiveBytes, X, N, LM, &tf_sum);
1270 for (i=effEnd;i<st->end;i++)
1271 tf_res[i] = tf_res[effEnd-1];
1272
1273 ALLOC(error, C*st->mode->nbEBands, opus_val16);
1274 quant_coarse_energy(st->mode, st->start, st->end, effEnd, bandLogE,
1275 oldBandE, total_bits, error, enc,
1276 C, LM, nbAvailableBytes, st->force_intra,
1277 &st->delayedIntra, st->complexity >= 4, st->loss_rate);
1278
1279 tf_encode(st->start, st->end, isTransient, tf_res, LM, tf_select, enc);
1280
1281 st->spread_decision = SPREAD_NORMAL;
1282 if (ec_tell(enc)+4<=total_bits)
1283 {
1284 if (shortBlocks || st->complexity < 3 || nbAvailableBytes < 10*C)
1285 {
1286 if (st->complexity == 0)
1287 st->spread_decision = SPREAD_NONE;
1288 } else {
1289 st->spread_decision = spreading_decision(st->mode, X,
1290 &st->tonal_average, st->spread_decision, &st->hf_average,
1291 &st->tapset_decision, pf_on&&!shortBlocks, effEnd, C, M);
1292 }
1293 ec_enc_icdf(enc, st->spread_decision, spread_icdf, 5);
1294 }
1295
1296 ALLOC(cap, st->mode->nbEBands, int);
1297 ALLOC(offsets, st->mode->nbEBands, int);
1298
1299 init_caps(st->mode,cap,LM,C);
1300 for (i=0;i<st->mode->nbEBands;i++)
1301 offsets[i] = 0;
1302 /* Dynamic allocation code */
1303 /* Make sure that dynamic allocation can't make us bust the budget */
1304 if (effectiveBytes > 50 && LM>=1)
1305 {
1306 int t1, t2;
1307 if (LM <= 1)
1308 {
1309 t1 = 3;
1310 t2 = 5;
1311 } else {
1312 t1 = 2;
1313 t2 = 4;
1314 }
1315 for (i=st->start+1;i<st->end-1;i++)
1316 {
1317 opus_val32 d2;
1318 d2 = 2*bandLogE[i]-bandLogE[i-1]-bandLogE[i+1];
1319 if (C==2)
1320 d2 = HALF32(d2 + 2*bandLogE[i+st->mode->nbEBands]-
1321 bandLogE[i-1+st->mode->nbEBands]-bandLogE[i+1+st->mode->nbEBands]);
1322#ifdef FUZZING
1323 if((rand()&0xF)==0)
1324 {
1325 offsets[i] += 1;
1326 if((rand()&0x3)==0)
1327 offsets[i] += 1+(rand()&0x3);
1328 }
1329#else
1330 if (d2 > SHL16(t1,DB_SHIFT))
1331 offsets[i] += 1;
1332 if (d2 > SHL16(t2,DB_SHIFT))
1333 offsets[i] += 1;
1334#endif
1335 }
1336 }
1337 dynalloc_logp = 6;
1338 total_bits<<=BITRES;
1339 total_boost = 0;
1340 tell = ec_tell_frac(enc);
1341 for (i=st->start;i<st->end;i++)
1342 {
1343 int width, quanta;
1344 int dynalloc_loop_logp;
1345 int boost;
1346 int j;
1347 width = C*(st->mode->eBands[i+1]-st->mode->eBands[i])<<LM;
1348 /* quanta is 6 bits, but no more than 1 bit/sample
1349 and no less than 1/8 bit/sample */
1350 quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
1351 dynalloc_loop_logp = dynalloc_logp;
1352 boost = 0;
1353 for (j = 0; tell+(dynalloc_loop_logp<<BITRES) < total_bits-total_boost
1354 && boost < cap[i]; j++)
1355 {
1356 int flag;
1357 flag = j<offsets[i];
1358 ec_enc_bit_logp(enc, flag, dynalloc_loop_logp);
1359 tell = ec_tell_frac(enc);
1360 if (!flag)
1361 break;
1362 boost += quanta;
1363 total_boost += quanta;
1364 dynalloc_loop_logp = 1;
1365 }
1366 /* Making dynalloc more likely */
1367 if (j)
1368 dynalloc_logp = IMAX(2, dynalloc_logp-1);
1369 offsets[i] = boost;
1370 }
1371 alloc_trim = 5;
1372 if (tell+(6<<BITRES) <= total_bits - total_boost)
1373 {
1374 alloc_trim = alloc_trim_analysis(st->mode, X, bandLogE,
1375 st->end, LM, C, N);
1376 ec_enc_icdf(enc, alloc_trim, trim_icdf, 7);
1377 tell = ec_tell_frac(enc);
1378 }
1379
1380 /* Variable bitrate */
1381 if (vbr_rate>0)
1382 {
1383 opus_val16 alpha;
1384 opus_int32 delta;
1385 /* The target rate in 8th bits per frame */
1386 opus_int32 target;
1387 opus_int32 min_allowed;
1388 int lm_diff = st->mode->maxLM - LM;
1389
1390 /* Don't attempt to use more than 510 kb/s, even for frames smaller than 20 ms.
1391 The CELT allocator will just not be able to use more than that anyway. */
1392 nbCompressedBytes = IMIN(nbCompressedBytes,1275>>(3-LM));
1393 target = vbr_rate + (st->vbr_offset>>lm_diff) - ((40*C+20)<<BITRES);
1394
1395 /* Shortblocks get a large boost in bitrate, but since they
1396 are uncommon long blocks are not greatly affected */
1397 if (shortBlocks || tf_sum < -2*(st->end-st->start))
1398 target = 7*target/4;
1399 else if (tf_sum < -(st->end-st->start))
1400 target = 3*target/2;
1401 else if (M > 1)
1402 target-=(target+14)/28;
1403
1404 /* The current offset is removed from the target and the space used
1405 so far is added*/
1406 target=target+tell;
1407
1408 /* In VBR mode the frame size must not be reduced so much that it would
1409 result in the encoder running out of bits.
1410 The margin of 2 bytes ensures that none of the bust-prevention logic
1411 in the decoder will have triggered so far. */
1412 min_allowed = ((tell+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3)) + 2 - nbFilledBytes;
1413
1414 nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3);
1415 nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes);
1416 nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes) - nbFilledBytes;
1417
1418 /* By how much did we "miss" the target on that frame */
1419 delta = target - vbr_rate;
1420
1421 target=nbAvailableBytes<<(BITRES+3);
1422
1423 /*If the frame is silent we don't adjust our drift, otherwise
1424 the encoder will shoot to very high rates after hitting a
1425 span of silence, but we do allow the bitres to refill.
1426 This means that we'll undershoot our target in CVBR/VBR modes
1427 on files with lots of silence. */
1428 if(silence)
1429 {
1430 nbAvailableBytes = 2;
1431 target = 2*8<<BITRES;
1432 delta = 0;
1433 }
1434
1435 if (st->vbr_count < 970)
1436 {
1437 st->vbr_count++;
1438 alpha = celt_rcp(SHL32(EXTEND32(st->vbr_count+20),16));
1439 } else
1440 alpha = QCONST16(.001f,15);
1441 /* How many bits have we used in excess of what we're allowed */
1442 if (st->constrained_vbr)
1443 st->vbr_reservoir += target - vbr_rate;
1444 /*printf ("%d\n", st->vbr_reservoir);*/
1445
1446 /* Compute the offset we need to apply in order to reach the target */
1447 st->vbr_drift += (opus_int32)MULT16_32_Q15(alpha,(delta*(1<<lm_diff))-st->vbr_offset-st->vbr_drift);
1448 st->vbr_offset = -st->vbr_drift;
1449 /*printf ("%d\n", st->vbr_drift);*/
1450
1451 if (st->constrained_vbr && st->vbr_reservoir < 0)
1452 {
1453 /* We're under the min value -- increase rate */
1454 int adjust = (-st->vbr_reservoir)/(8<<BITRES);
1455 /* Unless we're just coding silence */
1456 nbAvailableBytes += silence?0:adjust;
1457 st->vbr_reservoir = 0;
1458 /*printf ("+%d\n", adjust);*/
1459 }
1460 nbCompressedBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes);
1461 /* This moves the raw bits to take into account the new compressed size */
1462 ec_enc_shrink(enc, nbCompressedBytes);
1463 }
1464 if (C==2)
1465 {
1466 int effectiveRate;
1467
1468 /* Always use MS for 2.5 ms frames until we can do a better analysis */
1469 if (LM!=0)
1470 dual_stereo = stereo_analysis(st->mode, X, LM, N);
1471
1472 /* Account for coarse energy */
1473 effectiveRate = (8*effectiveBytes - 80)>>LM;
1474
1475 /* effectiveRate in kb/s */
1476 effectiveRate = 2*effectiveRate/5;
1477 if (effectiveRate<35)
1478 intensity = 8;
1479 else if (effectiveRate<50)
1480 intensity = 12;
1481 else if (effectiveRate<68)
1482 intensity = 16;
1483 else if (effectiveRate<84)
1484 intensity = 18;
1485 else if (effectiveRate<102)
1486 intensity = 19;
1487 else if (effectiveRate<130)
1488 intensity = 20;
1489 else
1490 intensity = 100;
1491 intensity = IMIN(st->end,IMAX(st->start, intensity));
1492 }
1493
1494 /* Bit allocation */
1495 ALLOC(fine_quant, st->mode->nbEBands, int);
1496 ALLOC(pulses, st->mode->nbEBands, int);
1497 ALLOC(fine_priority, st->mode->nbEBands, int);
1498
1499 /* bits = packet size - where we are - safety*/
1500 bits = (((opus_int32)nbCompressedBytes*8)<<BITRES) - ec_tell_frac(enc) - 1;
1501 anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
1502 bits -= anti_collapse_rsv;
1503 codedBands = compute_allocation(st->mode, st->start, st->end, offsets, cap,
1504 alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
1505 fine_quant, fine_priority, C, LM, enc, 1, st->lastCodedBands);
1506 st->lastCodedBands = codedBands;
1507
1508 quant_fine_energy(st->mode, st->start, st->end, oldBandE, error, fine_quant, enc, C);
1509
1510#ifdef MEASURE_NORM_MSE
1511 float X0[3000];
1512 float bandE0[60];
1513 c=0; do
1514 for (i=0;i<N;i++)
1515 X0[i+c*N] = X[i+c*N];
1516 while (++c<C);
1517 for (i=0;i<C*st->mode->nbEBands;i++)
1518 bandE0[i] = bandE[i];
1519#endif
1520
1521 /* Residual quantisation */
1522 ALLOC(collapse_masks, C*st->mode->nbEBands, unsigned char);
1523 quant_all_bands(1, st->mode, st->start, st->end, X, C==2 ? X+N : NULL, collapse_masks,
1524 bandE, pulses, shortBlocks, st->spread_decision, dual_stereo, intensity, tf_res,
1525 nbCompressedBytes*(8<<BITRES)-anti_collapse_rsv, balance, enc, LM, codedBands, &st->rng);
1526
1527 if (anti_collapse_rsv > 0)
1528 {
1529 anti_collapse_on = st->consec_transient<2;
1530#ifdef FUZZING
1531 anti_collapse_on = rand()&0x1;
1532#endif
1533 ec_enc_bits(enc, anti_collapse_on, 1);
1534 }
1535 quant_energy_finalise(st->mode, st->start, st->end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C);
1536
1537 if (silence)
1538 {
1539 for (i=0;i<C*st->mode->nbEBands;i++)
1540 oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
1541 }
1542
1543#ifdef RESYNTH
1544 /* Re-synthesis of the coded audio if required */
1545 {
1546 celt_sig *out_mem[2];
1547 celt_sig *overlap_mem[2];
1548
1549 log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
1550 if (silence)
1551 {
1552 for (i=0;i<C*st->mode->nbEBands;i++)
1553 bandE[i] = 0;
1554 }
1555
1556#ifdef MEASURE_NORM_MSE
1557 measure_norm_mse(st->mode, X, X0, bandE, bandE0, M, N, C);
1558#endif
1559 if (anti_collapse_on)
1560 {
1561 anti_collapse(st->mode, X, collapse_masks, LM, C, N,
1562 st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
1563 }
1564
1565 /* Synthesis */
1566 denormalise_bands(st->mode, X, freq, bandE, effEnd, C, M);
1567
1568 OPUS_MOVE(st->syn_mem[0], st->syn_mem[0]+N, MAX_PERIOD);
1569 if (CC==2)
1570 OPUS_MOVE(st->syn_mem[1], st->syn_mem[1]+N, MAX_PERIOD);
1571
1572 c=0; do
1573 for (i=0;i<M*st->mode->eBands[st->start];i++)
1574 freq[c*N+i] = 0;
1575 while (++c<C);
1576 c=0; do
1577 for (i=M*st->mode->eBands[st->end];i<N;i++)
1578 freq[c*N+i] = 0;
1579 while (++c<C);
1580
1581 if (CC==2&&C==1)
1582 {
1583 for (i=0;i<N;i++)
1584 freq[N+i] = freq[i];
1585 }
1586
1587 out_mem[0] = st->syn_mem[0]+MAX_PERIOD;
1588 if (CC==2)
1589 out_mem[1] = st->syn_mem[1]+MAX_PERIOD;
1590
1591 overlap_mem[0] = prefilter_mem+CC*COMBFILTER_MAXPERIOD;
1592 if (CC==2)
1593 overlap_mem[1] = overlap_mem[0] + st->overlap;
1594
1595 compute_inv_mdcts(st->mode, shortBlocks, freq, out_mem, overlap_mem, CC, LM);
1596
1597 c=0; do {
1598 st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
1599 st->prefilter_period_old=IMAX(st->prefilter_period_old, COMBFILTER_MINPERIOD);
1600 comb_filter(out_mem[c], out_mem[c], st->prefilter_period_old, st->prefilter_period, st->mode->shortMdctSize,
1601 st->prefilter_gain_old, st->prefilter_gain, st->prefilter_tapset_old, st->prefilter_tapset,
1602 st->mode->window, st->overlap);
1603 if (LM!=0)
1604 comb_filter(out_mem[c]+st->mode->shortMdctSize, out_mem[c]+st->mode->shortMdctSize, st->prefilter_period, pitch_index, N-st->mode->shortMdctSize,
1605 st->prefilter_gain, gain1, st->prefilter_tapset, prefilter_tapset,
1606 st->mode->window, st->mode->overlap);
1607 } while (++c<CC);
1608
1609 deemphasis(out_mem, (opus_val16*)pcm, N, CC, st->upsample, st->mode->preemph, st->preemph_memD);
1610 st->prefilter_period_old = st->prefilter_period;
1611 st->prefilter_gain_old = st->prefilter_gain;
1612 st->prefilter_tapset_old = st->prefilter_tapset;
1613 }
1614#endif
1615
1616 st->prefilter_period = pitch_index;
1617 st->prefilter_gain = gain1;
1618 st->prefilter_tapset = prefilter_tapset;
1619#ifdef RESYNTH
1620 if (LM!=0)
1621 {
1622 st->prefilter_period_old = st->prefilter_period;
1623 st->prefilter_gain_old = st->prefilter_gain;
1624 st->prefilter_tapset_old = st->prefilter_tapset;
1625 }
1626#endif
1627
1628 if (CC==2&&C==1) {
1629 for (i=0;i<st->mode->nbEBands;i++)
1630 oldBandE[st->mode->nbEBands+i]=oldBandE[i];
1631 }
1632
1633 if (!isTransient)
1634 {
1635 for (i=0;i<CC*st->mode->nbEBands;i++)
1636 oldLogE2[i] = oldLogE[i];
1637 for (i=0;i<CC*st->mode->nbEBands;i++)
1638 oldLogE[i] = oldBandE[i];
1639 } else {
1640 for (i=0;i<CC*st->mode->nbEBands;i++)
1641 oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
1642 }
1643 /* In case start or end were to change */
1644 c=0; do
1645 {
1646 for (i=0;i<st->start;i++)
1647 {
1648 oldBandE[c*st->mode->nbEBands+i]=0;
1649 oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
1650 }
1651 for (i=st->end;i<st->mode->nbEBands;i++)
1652 {
1653 oldBandE[c*st->mode->nbEBands+i]=0;
1654 oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
1655 }
1656 } while (++c<CC);
1657
1658 if (isTransient)
1659 st->consec_transient++;
1660 else
1661 st->consec_transient=0;
1662 st->rng = enc->rng;
1663
1664 /* If there's any room left (can only happen for very high rates),
1665 it's already filled with zeros */
1666 ec_enc_done(enc);
1667
1668#ifdef CUSTOM_MODES
1669 if (st->signalling)
1670 nbCompressedBytes++;
1671#endif
1672
1673 RESTORE_STACK;
1674 if (ec_get_error(enc))
1675 return OPUS_INTERNAL_ERROR;
1676 else
1677 return nbCompressedBytes;
1678}
1679
1680
1681#ifdef CUSTOM_MODES
1682
1683#ifdef FIXED_POINT
1684int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1685{
1686 return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
1687}
1688
1689#ifndef DISABLE_FLOAT_API
1690int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1691{
1692 int j, ret, C, N;
1693 VARDECL(opus_int16, in);
1694 ALLOC_STACK;
1695
1696 if (pcm==NULL)
1697 return OPUS_BAD_ARG;
1698
1699 C = st->channels;
1700 N = frame_size;
1701 ALLOC(in, C*N, opus_int16);
1702
1703 for (j=0;j<C*N;j++)
1704 in[j] = FLOAT2INT16(pcm[j]);
1705
1706 ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
1707#ifdef RESYNTH
1708 for (j=0;j<C*N;j++)
1709 ((float*)pcm)[j]=in[j]*(1.f/32768.f);
1710#endif
1711 RESTORE_STACK;
1712 return ret;
1713}
1714#endif /* DISABLE_FLOAT_API */
1715#else
1716
1717int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1718{
1719 int j, ret, C, N;
1720 VARDECL(celt_sig, in);
1721 ALLOC_STACK;
1722
1723 if (pcm==NULL)
1724 return OPUS_BAD_ARG;
1725
1726 C=st->channels;
1727 N=frame_size;
1728 ALLOC(in, C*N, celt_sig);
1729 for (j=0;j<C*N;j++) {
1730 in[j] = SCALEOUT(pcm[j]);
1731 }
1732
1733 ret = celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
1734#ifdef RESYNTH
1735 for (j=0;j<C*N;j++)
1736 ((opus_int16*)pcm)[j] = FLOAT2INT16(in[j]);
1737#endif
1738 RESTORE_STACK;
1739 return ret;
1740}
1741
1742int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
1743{
1744 return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
1745}
1746
1747#endif
1748
1749#endif /* CUSTOM_MODES */
1750
1751int opus_custom_encoder_ctl(CELTEncoder * OPUS_RESTRICT st, int request, ...)
1752{
1753 va_list ap;
1754
1755 va_start(ap, request);
1756 switch (request)
1757 {
1758 case OPUS_SET_COMPLEXITY_REQUEST:
1759 {
1760 int value = va_arg(ap, opus_int32);
1761 if (value<0 || value>10)
1762 goto bad_arg;
1763 st->complexity = value;
1764 }
1765 break;
1766 case CELT_SET_START_BAND_REQUEST:
1767 {
1768 opus_int32 value = va_arg(ap, opus_int32);
1769 if (value<0 || value>=st->mode->nbEBands)
1770 goto bad_arg;
1771 st->start = value;
1772 }
1773 break;
1774 case CELT_SET_END_BAND_REQUEST:
1775 {
1776 opus_int32 value = va_arg(ap, opus_int32);
1777 if (value<1 || value>st->mode->nbEBands)
1778 goto bad_arg;
1779 st->end = value;
1780 }
1781 break;
1782 case CELT_SET_PREDICTION_REQUEST:
1783 {
1784 int value = va_arg(ap, opus_int32);
1785 if (value<0 || value>2)
1786 goto bad_arg;
1787 st->disable_pf = value<=1;
1788 st->force_intra = value==0;
1789 }
1790 break;
1791 case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
1792 {
1793 int value = va_arg(ap, opus_int32);
1794 if (value<0 || value>100)
1795 goto bad_arg;
1796 st->loss_rate = value;
1797 }
1798 break;
1799 case OPUS_SET_VBR_CONSTRAINT_REQUEST:
1800 {
1801 opus_int32 value = va_arg(ap, opus_int32);
1802 st->constrained_vbr = value;
1803 }
1804 break;
1805 case OPUS_SET_VBR_REQUEST:
1806 {
1807 opus_int32 value = va_arg(ap, opus_int32);
1808 st->vbr = value;
1809 }
1810 break;
1811 case OPUS_SET_BITRATE_REQUEST:
1812 {
1813 opus_int32 value = va_arg(ap, opus_int32);
1814 if (value<=500 && value!=OPUS_BITRATE_MAX)
1815 goto bad_arg;
1816 value = IMIN(value, 260000*st->channels);
1817 st->bitrate = value;
1818 }
1819 break;
1820 case CELT_SET_CHANNELS_REQUEST:
1821 {
1822 opus_int32 value = va_arg(ap, opus_int32);
1823 if (value<1 || value>2)
1824 goto bad_arg;
1825 st->stream_channels = value;
1826 }
1827 break;
1828 case OPUS_SET_LSB_DEPTH_REQUEST:
1829 {
1830 opus_int32 value = va_arg(ap, opus_int32);
1831 if (value<8 || value>24)
1832 goto bad_arg;
1833 st->lsb_depth=value;
1834 }
1835 break;
1836 case OPUS_GET_LSB_DEPTH_REQUEST:
1837 {
1838 opus_int32 *value = va_arg(ap, opus_int32*);
1839 *value=st->lsb_depth;
1840 }
1841 break;
1842 case OPUS_RESET_STATE:
1843 {
1844 int i;
1845 opus_val16 *oldBandE, *oldLogE, *oldLogE2;
1846 oldBandE = (opus_val16*)(st->in_mem+st->channels*(2*st->overlap+COMBFILTER_MAXPERIOD));
1847 oldLogE = oldBandE + st->channels*st->mode->nbEBands;
1848 oldLogE2 = oldLogE + st->channels*st->mode->nbEBands;
1849 OPUS_CLEAR((char*)&st->ENCODER_RESET_START,
1850 opus_custom_encoder_get_size(st->mode, st->channels)-
1851 ((char*)&st->ENCODER_RESET_START - (char*)st));
1852 for (i=0;i<st->channels*st->mode->nbEBands;i++)
1853 oldLogE[i]=oldLogE2[i]=-QCONST16(28.f,DB_SHIFT);
1854 st->vbr_offset = 0;
1855 st->delayedIntra = 1;
1856 st->spread_decision = SPREAD_NORMAL;
1857 st->tonal_average = 256;
1858 st->hf_average = 0;
1859 st->tapset_decision = 0;
1860 }
1861 break;
1862#ifdef CUSTOM_MODES
1863 case CELT_SET_INPUT_CLIPPING_REQUEST:
1864 {
1865 opus_int32 value = va_arg(ap, opus_int32);
1866 st->clip = value;
1867 }
1868 break;
1869#endif
1870 case CELT_SET_SIGNALLING_REQUEST:
1871 {
1872 opus_int32 value = va_arg(ap, opus_int32);
1873 st->signalling = value;
1874 }
1875 break;
1876 case CELT_GET_MODE_REQUEST:
1877 {
1878 const CELTMode ** value = va_arg(ap, const CELTMode**);
1879 if (value==0)
1880 goto bad_arg;
1881 *value=st->mode;
1882 }
1883 break;
1884 case OPUS_GET_FINAL_RANGE_REQUEST:
1885 {
1886 opus_uint32 * value = va_arg(ap, opus_uint32 *);
1887 if (value==0)
1888 goto bad_arg;
1889 *value=st->rng;
1890 }
1891 break;
1892 default:
1893 goto bad_request;
1894 }
1895 va_end(ap);
1896 return OPUS_OK;
1897bad_arg:
1898 va_end(ap);
1899 return OPUS_BAD_ARG;
1900bad_request:
1901 va_end(ap);
1902 return OPUS_UNIMPLEMENTED;
1903}
1904
1905/**********************************************************************/
1906/* */
1907/* DECODER */
1908/* */
1909/**********************************************************************/
1910#define DECODE_BUFFER_SIZE 2048
1911
1912/** Decoder state
1913 @brief Decoder state
1914 */
1915struct OpusCustomDecoder {
1916 const OpusCustomMode *mode;
1917 int overlap;
1918 int channels;
1919 int stream_channels;
1920
1921 int downsample;
1922 int start, end;
1923 int signalling;
1924
1925 /* Everything beyond this point gets cleared on a reset */
1926#define DECODER_RESET_START rng
1927
1928 opus_uint32 rng;
1929 int error;
1930 int last_pitch_index;
1931 int loss_count;
1932 int postfilter_period;
1933 int postfilter_period_old;
1934 opus_val16 postfilter_gain;
1935 opus_val16 postfilter_gain_old;
1936 int postfilter_tapset;
1937 int postfilter_tapset_old;
1938
1939 celt_sig preemph_memD[2];
1940
1941 celt_sig _decode_mem[1]; /* Size = channels*(DECODE_BUFFER_SIZE+mode->overlap) */
1942 /* opus_val16 lpc[], Size = channels*LPC_ORDER */
1943 /* opus_val16 oldEBands[], Size = 2*mode->nbEBands */
1944 /* opus_val16 oldLogE[], Size = 2*mode->nbEBands */
1945 /* opus_val16 oldLogE2[], Size = 2*mode->nbEBands */
1946 /* opus_val16 backgroundLogE[], Size = 2*mode->nbEBands */
1947};
1948
1949int celt_decoder_get_size(int channels)
1950{
1951 const CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
1952 return opus_custom_decoder_get_size(mode, channels);
1953}
1954
1955OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_get_size(const CELTMode *mode, int channels)
1956{
1957 int size = sizeof(struct CELTDecoder)
1958 + (channels*(DECODE_BUFFER_SIZE+mode->overlap)-1)*sizeof(celt_sig)
1959 + channels*LPC_ORDER*sizeof(opus_val16)
1960 + 4*2*mode->nbEBands*sizeof(opus_val16);
1961 return size;
1962}
1963
1964#ifdef CUSTOM_MODES
1965CELTDecoder *opus_custom_decoder_create(const CELTMode *mode, int channels, int *error)
1966{
1967 int ret;
1968 CELTDecoder *st = (CELTDecoder *)opus_alloc(opus_custom_decoder_get_size(mode, channels));
1969 ret = opus_custom_decoder_init(st, mode, channels);
1970 if (ret != OPUS_OK)
1971 {
1972 opus_custom_decoder_destroy(st);
1973 st = NULL;
1974 }
1975 if (error)
1976 *error = ret;
1977 return st;
1978}
1979#endif /* CUSTOM_MODES */
1980
1981int celt_decoder_init(CELTDecoder *st, opus_int32 sampling_rate, int channels)
1982{
1983 int ret;
1984 ret = opus_custom_decoder_init(st, opus_custom_mode_create(48000, 960, NULL), channels);
1985 if (ret != OPUS_OK)
1986 return ret;
1987 st->downsample = resampling_factor(sampling_rate);
1988 if (st->downsample==0)
1989 return OPUS_BAD_ARG;
1990 else
1991 return OPUS_OK;
1992}
1993
1994OPUS_CUSTOM_NOSTATIC int opus_custom_decoder_init(CELTDecoder *st, const CELTMode *mode, int channels)
1995{
1996 if (channels < 0 || channels > 2)
1997 return OPUS_BAD_ARG;
1998
1999 if (st==NULL)
2000 return OPUS_ALLOC_FAIL;
2001
2002 OPUS_CLEAR((char*)st, opus_custom_decoder_get_size(mode, channels));
2003
2004 st->mode = mode;
2005 st->overlap = mode->overlap;
2006 st->stream_channels = st->channels = channels;
2007
2008 st->downsample = 1;
2009 st->start = 0;
2010 st->end = st->mode->effEBands;
2011 st->signalling = 1;
2012
2013 st->loss_count = 0;
2014
2015 opus_custom_decoder_ctl(st, OPUS_RESET_STATE);
2016
2017 return OPUS_OK;
2018}
2019
2020#ifdef CUSTOM_MODES
2021void opus_custom_decoder_destroy(CELTDecoder *st)
2022{
2023 opus_free(st);
2024}
2025#endif /* CUSTOM_MODES */
2026
2027static void celt_decode_lost(CELTDecoder * OPUS_RESTRICT st, opus_val16 * OPUS_RESTRICT pcm, int N, int LM)
2028{
2029 int c;
2030 int pitch_index;
2031 int overlap = st->mode->overlap;
2032 opus_val16 fade = Q15ONE;
2033 int i, len;
2034 const int C = st->channels;
2035 int offset;
2036 celt_sig *out_mem[2];
2037 celt_sig *decode_mem[2];
2038 celt_sig *overlap_mem[2];
2039 opus_val16 *lpc;
2040 opus_val32 *out_syn[2];
2041 opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
2042 SAVE_STACK;
2043
2044 c=0; do {
2045 decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+st->overlap);
2046 out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
2047 overlap_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE;
2048 } while (++c<C);
2049 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*C);
2050 oldBandE = lpc+C*LPC_ORDER;
2051 oldLogE = oldBandE + 2*st->mode->nbEBands;
2052 oldLogE2 = oldLogE + 2*st->mode->nbEBands;
2053 backgroundLogE = oldLogE2 + 2*st->mode->nbEBands;
2054
2055 out_syn[0] = out_mem[0]+MAX_PERIOD-N;
2056 if (C==2)
2057 out_syn[1] = out_mem[1]+MAX_PERIOD-N;
2058
2059 len = N+st->mode->overlap;
2060
2061 if (st->loss_count >= 5 || st->start!=0)
2062 {
2063 /* Noise-based PLC/CNG */
2064 VARDECL(celt_sig, freq);
2065 VARDECL(celt_norm, X);
2066 VARDECL(celt_ener, bandE);
2067 opus_uint32 seed;
2068 int effEnd;
2069
2070 effEnd = st->end;
2071 if (effEnd > st->mode->effEBands)
2072 effEnd = st->mode->effEBands;
2073
2074 ALLOC(freq, C*N, celt_sig); /**< Interleaved signal MDCTs */
2075 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
2076 ALLOC(bandE, st->mode->nbEBands*C, celt_ener);
2077
2078 if (st->loss_count >= 5)
2079 log2Amp(st->mode, st->start, st->end, bandE, backgroundLogE, C);
2080 else {
2081 /* Energy decay */
2082 opus_val16 decay = st->loss_count==0 ? QCONST16(1.5f, DB_SHIFT) : QCONST16(.5f, DB_SHIFT);
2083 c=0; do
2084 {
2085 for (i=st->start;i<st->end;i++)
2086 oldBandE[c*st->mode->nbEBands+i] -= decay;
2087 } while (++c<C);
2088 log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
2089 }
2090 seed = st->rng;
2091 for (c=0;c<C;c++)
2092 {
2093 for (i=0;i<(st->mode->eBands[st->start]<<LM);i++)
2094 X[c*N+i] = 0;
2095 for (i=st->start;i<st->mode->effEBands;i++)
2096 {
2097 int j;
2098 int boffs;
2099 int blen;
2100 boffs = N*c+(st->mode->eBands[i]<<LM);
2101 blen = (st->mode->eBands[i+1]-st->mode->eBands[i])<<LM;
2102 for (j=0;j<blen;j++)
2103 {
2104 seed = celt_lcg_rand(seed);
2105 X[boffs+j] = (celt_norm)((opus_int32)seed>>20);
2106 }
2107 renormalise_vector(X+boffs, blen, Q15ONE);
2108 }
2109 for (i=(st->mode->eBands[st->end]<<LM);i<N;i++)
2110 X[c*N+i] = 0;
2111 }
2112 st->rng = seed;
2113
2114 denormalise_bands(st->mode, X, freq, bandE, st->mode->effEBands, C, 1<<LM);
2115
2116 c=0; do
2117 for (i=0;i<st->mode->eBands[st->start]<<LM;i++)
2118 freq[c*N+i] = 0;
2119 while (++c<C);
2120 c=0; do {
2121 int bound = st->mode->eBands[effEnd]<<LM;
2122 if (st->downsample!=1)
2123 bound = IMIN(bound, N/st->downsample);
2124 for (i=bound;i<N;i++)
2125 freq[c*N+i] = 0;
2126 } while (++c<C);
2127 compute_inv_mdcts(st->mode, 0, freq, out_syn, overlap_mem, C, LM);
2128 } else {
2129 /* Pitch-based PLC */
2130 if (st->loss_count == 0)
2131 {
2132 opus_val16 pitch_buf[DECODE_BUFFER_SIZE>>1];
2133 /* Corresponds to a min pitch of 67 Hz. It's possible to save CPU in this
2134 search by using only part of the decode buffer */
2135 int poffset = 720;
2136 pitch_downsample(decode_mem, pitch_buf, DECODE_BUFFER_SIZE, C);
2137 /* Max pitch is 100 samples (480 Hz) */
2138 pitch_search(pitch_buf+((poffset)>>1), pitch_buf, DECODE_BUFFER_SIZE-poffset,
2139 poffset-100, &pitch_index);
2140 pitch_index = poffset-pitch_index;
2141 st->last_pitch_index = pitch_index;
2142 } else {
2143 pitch_index = st->last_pitch_index;
2144 fade = QCONST16(.8f,15);
2145 }
2146
2147 c=0; do {
2148 VARDECL(opus_val32, e);
2149 opus_val16 exc[MAX_PERIOD];
2150 opus_val32 ac[LPC_ORDER+1];
2151 opus_val16 decay = 1;
2152 opus_val32 S1=0;
2153 opus_val16 mem[LPC_ORDER]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
2154
2155 ALLOC(e, MAX_PERIOD+2*st->mode->overlap, opus_val32);
2156
2157 offset = MAX_PERIOD-pitch_index;
2158 for (i=0;i<MAX_PERIOD;i++)
2159 exc[i] = ROUND16(out_mem[c][i], SIG_SHIFT);
2160
2161 if (st->loss_count == 0)
2162 {
2163 _celt_autocorr(exc, ac, st->mode->window, st->mode->overlap,
2164 LPC_ORDER, MAX_PERIOD);
2165
2166 /* Noise floor -40 dB */
2167#ifdef FIXED_POINT
2168 ac[0] += SHR32(ac[0],13);
2169#else
2170 ac[0] *= 1.0001f;
2171#endif
2172 /* Lag windowing */
2173 for (i=1;i<=LPC_ORDER;i++)
2174 {
2175 /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
2176#ifdef FIXED_POINT
2177 ac[i] -= MULT16_32_Q15(2*i*i, ac[i]);
2178#else
2179 ac[i] -= ac[i]*(.008f*i)*(.008f*i);
2180#endif
2181 }
2182
2183 _celt_lpc(lpc+c*LPC_ORDER, ac, LPC_ORDER);
2184 }
2185 for (i=0;i<LPC_ORDER;i++)
2186 mem[i] = ROUND16(out_mem[c][MAX_PERIOD-1-i], SIG_SHIFT);
2187 celt_fir(exc, lpc+c*LPC_ORDER, exc, MAX_PERIOD, LPC_ORDER, mem);
2188 /*for (i=0;i<MAX_PERIOD;i++)printf("%d ", exc[i]); printf("\n");*/
2189 /* Check if the waveform is decaying (and if so how fast) */
2190 {
2191 opus_val32 E1=1, E2=1;
2192 int period;
2193 if (pitch_index <= MAX_PERIOD/2)
2194 period = pitch_index;
2195 else
2196 period = MAX_PERIOD/2;
2197 for (i=0;i<period;i++)
2198 {
2199 E1 += SHR32(MULT16_16(exc[MAX_PERIOD-period+i],exc[MAX_PERIOD-period+i]),8);
2200 E2 += SHR32(MULT16_16(exc[MAX_PERIOD-2*period+i],exc[MAX_PERIOD-2*period+i]),8);
2201 }
2202 if (E1 > E2)
2203 E1 = E2;
2204 decay = celt_sqrt(frac_div32(SHR32(E1,1),E2));
2205 }
2206
2207 /* Copy excitation, taking decay into account */
2208 for (i=0;i<len+st->mode->overlap;i++)
2209 {
2210 opus_val16 tmp;
2211 if (offset+i >= MAX_PERIOD)
2212 {
2213 offset -= pitch_index;
2214 decay = MULT16_16_Q15(decay, decay);
2215 }
2216 e[i] = SHL32(EXTEND32(MULT16_16_Q15(decay, exc[offset+i])), SIG_SHIFT);
2217 tmp = ROUND16(out_mem[c][offset+i],SIG_SHIFT);
2218 S1 += SHR32(MULT16_16(tmp,tmp),8);
2219 }
2220 for (i=0;i<LPC_ORDER;i++)
2221 mem[i] = ROUND16(out_mem[c][MAX_PERIOD-1-i], SIG_SHIFT);
2222 for (i=0;i<len+st->mode->overlap;i++)
2223 e[i] = MULT16_32_Q15(fade, e[i]);
2224 celt_iir(e, lpc+c*LPC_ORDER, e, len+st->mode->overlap, LPC_ORDER, mem);
2225
2226 {
2227 opus_val32 S2=0;
2228 for (i=0;i<len+overlap;i++)
2229 {
2230 opus_val16 tmp = ROUND16(e[i],SIG_SHIFT);
2231 S2 += SHR32(MULT16_16(tmp,tmp),8);
2232 }
2233 /* This checks for an "explosion" in the synthesis */
2234#ifdef FIXED_POINT
2235 if (!(S1 > SHR32(S2,2)))
2236#else
2237 /* Float test is written this way to catch NaNs at the same time */
2238 if (!(S1 > 0.2f*S2))
2239#endif
2240 {
2241 for (i=0;i<len+overlap;i++)
2242 e[i] = 0;
2243 } else if (S1 < S2)
2244 {
2245 opus_val16 ratio = celt_sqrt(frac_div32(SHR32(S1,1)+1,S2+1));
2246 for (i=0;i<len+overlap;i++)
2247 e[i] = MULT16_32_Q15(ratio, e[i]);
2248 }
2249 }
2250
2251 /* Apply post-filter to the MDCT overlap of the previous frame */
2252 comb_filter(out_mem[c]+MAX_PERIOD, out_mem[c]+MAX_PERIOD, st->postfilter_period, st->postfilter_period, st->overlap,
2253 st->postfilter_gain, st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
2254 NULL, 0);
2255
2256 for (i=0;i<MAX_PERIOD+st->mode->overlap-N;i++)
2257 out_mem[c][i] = out_mem[c][N+i];
2258
2259 /* Apply TDAC to the concealed audio so that it blends with the
2260 previous and next frames */
2261 for (i=0;i<overlap/2;i++)
2262 {
2263 opus_val32 tmp;
2264 tmp = MULT16_32_Q15(st->mode->window[i], e[N+overlap-1-i]) +
2265 MULT16_32_Q15(st->mode->window[overlap-i-1], e[N+i ]);
2266 out_mem[c][MAX_PERIOD+i] = MULT16_32_Q15(st->mode->window[overlap-i-1], tmp);
2267 out_mem[c][MAX_PERIOD+overlap-i-1] = MULT16_32_Q15(st->mode->window[i], tmp);
2268 }
2269 for (i=0;i<N;i++)
2270 out_mem[c][MAX_PERIOD-N+i] = e[i];
2271
2272 /* Apply pre-filter to the MDCT overlap for the next frame (post-filter will be applied then) */
2273 comb_filter(e, out_mem[c]+MAX_PERIOD, st->postfilter_period, st->postfilter_period, st->overlap,
2274 -st->postfilter_gain, -st->postfilter_gain, st->postfilter_tapset, st->postfilter_tapset,
2275 NULL, 0);
2276 for (i=0;i<overlap;i++)
2277 out_mem[c][MAX_PERIOD+i] = e[i];
2278 } while (++c<C);
2279 }
2280
2281 deemphasis(out_syn, pcm, N, C, st->downsample, st->mode->preemph, st->preemph_memD);
2282
2283 st->loss_count++;
2284
2285 RESTORE_STACK;
2286}
2287
2288int celt_decode_with_ec(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_val16 * OPUS_RESTRICT pcm, int frame_size, ec_dec *dec)
2289{
2290 int c, i, N;
2291 int spread_decision;
2292 opus_int32 bits;
2293 ec_dec _dec;
2294 VARDECL(celt_sig, freq);
2295 VARDECL(celt_norm, X);
2296 VARDECL(celt_ener, bandE);
2297 VARDECL(int, fine_quant);
2298 VARDECL(int, pulses);
2299 VARDECL(int, cap);
2300 VARDECL(int, offsets);
2301 VARDECL(int, fine_priority);
2302 VARDECL(int, tf_res);
2303 VARDECL(unsigned char, collapse_masks);
2304 celt_sig *out_mem[2];
2305 celt_sig *decode_mem[2];
2306 celt_sig *overlap_mem[2];
2307 celt_sig *out_syn[2];
2308 opus_val16 *lpc;
2309 opus_val16 *oldBandE, *oldLogE, *oldLogE2, *backgroundLogE;
2310
2311 int shortBlocks;
2312 int isTransient;
2313 int intra_ener;
2314 const int CC = st->channels;
2315 int LM, M;
2316 int effEnd;
2317 int codedBands;
2318 int alloc_trim;
2319 int postfilter_pitch;
2320 opus_val16 postfilter_gain;
2321 int intensity=0;
2322 int dual_stereo=0;
2323 opus_int32 total_bits;
2324 opus_int32 balance;
2325 opus_int32 tell;
2326 int dynalloc_logp;
2327 int postfilter_tapset;
2328 int anti_collapse_rsv;
2329 int anti_collapse_on=0;
2330 int silence;
2331 int C = st->stream_channels;
2332 ALLOC_STACK;
2333
2334 frame_size *= st->downsample;
2335
2336 c=0; do {
2337 decode_mem[c] = st->_decode_mem + c*(DECODE_BUFFER_SIZE+st->overlap);
2338 out_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE-MAX_PERIOD;
2339 overlap_mem[c] = decode_mem[c]+DECODE_BUFFER_SIZE;
2340 } while (++c<CC);
2341 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*CC);
2342 oldBandE = lpc+CC*LPC_ORDER;
2343 oldLogE = oldBandE + 2*st->mode->nbEBands;
2344 oldLogE2 = oldLogE + 2*st->mode->nbEBands;
2345 backgroundLogE = oldLogE2 + 2*st->mode->nbEBands;
2346
2347#ifdef CUSTOM_MODES
2348 if (st->signalling && data!=NULL)
2349 {
2350 int data0=data[0];
2351 /* Convert "standard mode" to Opus header */
2352 if (st->mode->Fs==48000 && st->mode->shortMdctSize==120)
2353 {
2354 data0 = fromOpus(data0);
2355 if (data0<0)
2356 return OPUS_INVALID_PACKET;
2357 }
2358 st->end = IMAX(1, st->mode->effEBands-2*(data0>>5));
2359 LM = (data0>>3)&0x3;
2360 C = 1 + ((data0>>2)&0x1);
2361 data++;
2362 len--;
2363 if (LM>st->mode->maxLM)
2364 return OPUS_INVALID_PACKET;
2365 if (frame_size < st->mode->shortMdctSize<<LM)
2366 return OPUS_BUFFER_TOO_SMALL;
2367 else
2368 frame_size = st->mode->shortMdctSize<<LM;
2369 } else {
2370#else
2371 {
2372#endif
2373 for (LM=0;LM<=st->mode->maxLM;LM++)
2374 if (st->mode->shortMdctSize<<LM==frame_size)
2375 break;
2376 if (LM>st->mode->maxLM)
2377 return OPUS_BAD_ARG;
2378 }
2379 M=1<<LM;
2380
2381 if (len<0 || len>1275 || pcm==NULL)
2382 return OPUS_BAD_ARG;
2383
2384 N = M*st->mode->shortMdctSize;
2385
2386 effEnd = st->end;
2387 if (effEnd > st->mode->effEBands)
2388 effEnd = st->mode->effEBands;
2389
2390 ALLOC(freq, IMAX(CC,C)*N, celt_sig); /**< Interleaved signal MDCTs */
2391 ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
2392 ALLOC(bandE, st->mode->nbEBands*C, celt_ener);
2393 c=0; do
2394 for (i=0;i<M*st->mode->eBands[st->start];i++)
2395 X[c*N+i] = 0;
2396 while (++c<C);
2397 c=0; do
2398 for (i=M*st->mode->eBands[effEnd];i<N;i++)
2399 X[c*N+i] = 0;
2400 while (++c<C);
2401
2402 if (data == NULL || len<=1)
2403 {
2404 celt_decode_lost(st, pcm, N, LM);
2405 RESTORE_STACK;
2406 return frame_size/st->downsample;
2407 }
2408
2409 if (dec == NULL)
2410 {
2411 ec_dec_init(&_dec,(unsigned char*)data,len);
2412 dec = &_dec;
2413 }
2414
2415 if (C==1)
2416 {
2417 for (i=0;i<st->mode->nbEBands;i++)
2418 oldBandE[i]=MAX16(oldBandE[i],oldBandE[st->mode->nbEBands+i]);
2419 }
2420
2421 total_bits = len*8;
2422 tell = ec_tell(dec);
2423
2424 if (tell >= total_bits)
2425 silence = 1;
2426 else if (tell==1)
2427 silence = ec_dec_bit_logp(dec, 15);
2428 else
2429 silence = 0;
2430 if (silence)
2431 {
2432 /* Pretend we've read all the remaining bits */
2433 tell = len*8;
2434 dec->nbits_total+=tell-ec_tell(dec);
2435 }
2436
2437 postfilter_gain = 0;
2438 postfilter_pitch = 0;
2439 postfilter_tapset = 0;
2440 if (st->start==0 && tell+16 <= total_bits)
2441 {
2442 if(ec_dec_bit_logp(dec, 1))
2443 {
2444 int qg, octave;
2445 octave = ec_dec_uint(dec, 6);
2446 postfilter_pitch = (16<<octave)+ec_dec_bits(dec, 4+octave)-1;
2447 qg = ec_dec_bits(dec, 3);
2448 if (ec_tell(dec)+2<=total_bits)
2449 postfilter_tapset = ec_dec_icdf(dec, tapset_icdf, 2);
2450 postfilter_gain = QCONST16(.09375f,15)*(qg+1);
2451 }
2452 tell = ec_tell(dec);
2453 }
2454
2455 if (LM > 0 && tell+3 <= total_bits)
2456 {
2457 isTransient = ec_dec_bit_logp(dec, 3);
2458 tell = ec_tell(dec);
2459 }
2460 else
2461 isTransient = 0;
2462
2463 if (isTransient)
2464 shortBlocks = M;
2465 else
2466 shortBlocks = 0;
2467
2468 /* Decode the global flags (first symbols in the stream) */
2469 intra_ener = tell+3<=total_bits ? ec_dec_bit_logp(dec, 3) : 0;
2470 /* Get band energies */
2471 unquant_coarse_energy(st->mode, st->start, st->end, oldBandE,
2472 intra_ener, dec, C, LM);
2473
2474 ALLOC(tf_res, st->mode->nbEBands, int);
2475 tf_decode(st->start, st->end, isTransient, tf_res, LM, dec);
2476
2477 tell = ec_tell(dec);
2478 spread_decision = SPREAD_NORMAL;
2479 if (tell+4 <= total_bits)
2480 spread_decision = ec_dec_icdf(dec, spread_icdf, 5);
2481
2482 ALLOC(pulses, st->mode->nbEBands, int);
2483 ALLOC(cap, st->mode->nbEBands, int);
2484 ALLOC(offsets, st->mode->nbEBands, int);
2485 ALLOC(fine_priority, st->mode->nbEBands, int);
2486
2487 init_caps(st->mode,cap,LM,C);
2488
2489 dynalloc_logp = 6;
2490 total_bits<<=BITRES;
2491 tell = ec_tell_frac(dec);
2492 for (i=st->start;i<st->end;i++)
2493 {
2494 int width, quanta;
2495 int dynalloc_loop_logp;
2496 int boost;
2497 width = C*(st->mode->eBands[i+1]-st->mode->eBands[i])<<LM;
2498 /* quanta is 6 bits, but no more than 1 bit/sample
2499 and no less than 1/8 bit/sample */
2500 quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
2501 dynalloc_loop_logp = dynalloc_logp;
2502 boost = 0;
2503 while (tell+(dynalloc_loop_logp<<BITRES) < total_bits && boost < cap[i])
2504 {
2505 int flag;
2506 flag = ec_dec_bit_logp(dec, dynalloc_loop_logp);
2507 tell = ec_tell_frac(dec);
2508 if (!flag)
2509 break;
2510 boost += quanta;
2511 total_bits -= quanta;
2512 dynalloc_loop_logp = 1;
2513 }
2514 offsets[i] = boost;
2515 /* Making dynalloc more likely */
2516 if (boost>0)
2517 dynalloc_logp = IMAX(2, dynalloc_logp-1);
2518 }
2519
2520 ALLOC(fine_quant, st->mode->nbEBands, int);
2521 alloc_trim = tell+(6<<BITRES) <= total_bits ?
2522 ec_dec_icdf(dec, trim_icdf, 7) : 5;
2523
2524 bits = (((opus_int32)len*8)<<BITRES) - ec_tell_frac(dec) - 1;
2525 anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
2526 bits -= anti_collapse_rsv;
2527 codedBands = compute_allocation(st->mode, st->start, st->end, offsets, cap,
2528 alloc_trim, &intensity, &dual_stereo, bits, &balance, pulses,
2529 fine_quant, fine_priority, C, LM, dec, 0, 0);
2530
2531 unquant_fine_energy(st->mode, st->start, st->end, oldBandE, fine_quant, dec, C);
2532
2533 /* Decode fixed codebook */
2534 ALLOC(collapse_masks, C*st->mode->nbEBands, unsigned char);
2535 quant_all_bands(0, st->mode, st->start, st->end, X, C==2 ? X+N : NULL, collapse_masks,
2536 NULL, pulses, shortBlocks, spread_decision, dual_stereo, intensity, tf_res,
2537 len*(8<<BITRES)-anti_collapse_rsv, balance, dec, LM, codedBands, &st->rng);
2538
2539 if (anti_collapse_rsv > 0)
2540 {
2541 anti_collapse_on = ec_dec_bits(dec, 1);
2542 }
2543
2544 unquant_energy_finalise(st->mode, st->start, st->end, oldBandE,
2545 fine_quant, fine_priority, len*8-ec_tell(dec), dec, C);
2546
2547 if (anti_collapse_on)
2548 anti_collapse(st->mode, X, collapse_masks, LM, C, N,
2549 st->start, st->end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
2550
2551 log2Amp(st->mode, st->start, st->end, bandE, oldBandE, C);
2552
2553 if (silence)
2554 {
2555 for (i=0;i<C*st->mode->nbEBands;i++)
2556 {
2557 bandE[i] = 0;
2558 oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
2559 }
2560 }
2561 /* Synthesis */
2562 denormalise_bands(st->mode, X, freq, bandE, effEnd, C, M);
2563
2564 OPUS_MOVE(decode_mem[0], decode_mem[0]+N, DECODE_BUFFER_SIZE-N);
2565 if (CC==2)
2566 OPUS_MOVE(decode_mem[1], decode_mem[1]+N, DECODE_BUFFER_SIZE-N);
2567
2568 c=0; do
2569 for (i=0;i<M*st->mode->eBands[st->start];i++)
2570 freq[c*N+i] = 0;
2571 while (++c<C);
2572 c=0; do {
2573 int bound = M*st->mode->eBands[effEnd];
2574 if (st->downsample!=1)
2575 bound = IMIN(bound, N/st->downsample);
2576 for (i=bound;i<N;i++)
2577 freq[c*N+i] = 0;
2578 } while (++c<C);
2579
2580 out_syn[0] = out_mem[0]+MAX_PERIOD-N;
2581 if (CC==2)
2582 out_syn[1] = out_mem[1]+MAX_PERIOD-N;
2583
2584 if (CC==2&&C==1)
2585 {
2586 for (i=0;i<N;i++)
2587 freq[N+i] = freq[i];
2588 }
2589 if (CC==1&&C==2)
2590 {
2591 for (i=0;i<N;i++)
2592 freq[i] = HALF32(ADD32(freq[i],freq[N+i]));
2593 }
2594
2595 /* Compute inverse MDCTs */
2596 compute_inv_mdcts(st->mode, shortBlocks, freq, out_syn, overlap_mem, CC, LM);
2597
2598 c=0; do {
2599 st->postfilter_period=IMAX(st->postfilter_period, COMBFILTER_MINPERIOD);
2600 st->postfilter_period_old=IMAX(st->postfilter_period_old, COMBFILTER_MINPERIOD);
2601 comb_filter(out_syn[c], out_syn[c], st->postfilter_period_old, st->postfilter_period, st->mode->shortMdctSize,
2602 st->postfilter_gain_old, st->postfilter_gain, st->postfilter_tapset_old, st->postfilter_tapset,
2603 st->mode->window, st->overlap);
2604 if (LM!=0)
2605 comb_filter(out_syn[c]+st->mode->shortMdctSize, out_syn[c]+st->mode->shortMdctSize, st->postfilter_period, postfilter_pitch, N-st->mode->shortMdctSize,
2606 st->postfilter_gain, postfilter_gain, st->postfilter_tapset, postfilter_tapset,
2607 st->mode->window, st->mode->overlap);
2608
2609 } while (++c<CC);
2610 st->postfilter_period_old = st->postfilter_period;
2611 st->postfilter_gain_old = st->postfilter_gain;
2612 st->postfilter_tapset_old = st->postfilter_tapset;
2613 st->postfilter_period = postfilter_pitch;
2614 st->postfilter_gain = postfilter_gain;
2615 st->postfilter_tapset = postfilter_tapset;
2616 if (LM!=0)
2617 {
2618 st->postfilter_period_old = st->postfilter_period;
2619 st->postfilter_gain_old = st->postfilter_gain;
2620 st->postfilter_tapset_old = st->postfilter_tapset;
2621 }
2622
2623 if (C==1) {
2624 for (i=0;i<st->mode->nbEBands;i++)
2625 oldBandE[st->mode->nbEBands+i]=oldBandE[i];
2626 }
2627
2628 /* In case start or end were to change */
2629 if (!isTransient)
2630 {
2631 for (i=0;i<2*st->mode->nbEBands;i++)
2632 oldLogE2[i] = oldLogE[i];
2633 for (i=0;i<2*st->mode->nbEBands;i++)
2634 oldLogE[i] = oldBandE[i];
2635 for (i=0;i<2*st->mode->nbEBands;i++)
2636 backgroundLogE[i] = MIN16(backgroundLogE[i] + M*QCONST16(0.001f,DB_SHIFT), oldBandE[i]);
2637 } else {
2638 for (i=0;i<2*st->mode->nbEBands;i++)
2639 oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
2640 }
2641 c=0; do
2642 {
2643 for (i=0;i<st->start;i++)
2644 {
2645 oldBandE[c*st->mode->nbEBands+i]=0;
2646 oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
2647 }
2648 for (i=st->end;i<st->mode->nbEBands;i++)
2649 {
2650 oldBandE[c*st->mode->nbEBands+i]=0;
2651 oldLogE[c*st->mode->nbEBands+i]=oldLogE2[c*st->mode->nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
2652 }
2653 } while (++c<2);
2654 st->rng = dec->rng;
2655
2656 deemphasis(out_syn, pcm, N, CC, st->downsample, st->mode->preemph, st->preemph_memD);
2657 st->loss_count = 0;
2658 RESTORE_STACK;
2659 if (ec_tell(dec) > 8*len)
2660 return OPUS_INTERNAL_ERROR;
2661 if(ec_get_error(dec))
2662 st->error = 1;
2663 return frame_size/st->downsample;
2664}
2665
2666
2667#ifdef CUSTOM_MODES
2668
2669#ifdef FIXED_POINT
2670int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
2671{
2672 return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL);
2673}
2674
2675#ifndef DISABLE_FLOAT_API
2676int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
2677{
2678 int j, ret, C, N;
2679 VARDECL(opus_int16, out);
2680 ALLOC_STACK;
2681
2682 if (pcm==NULL)
2683 return OPUS_BAD_ARG;
2684
2685 C = st->channels;
2686 N = frame_size;
2687
2688 ALLOC(out, C*N, opus_int16);
2689 ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL);
2690 if (ret>0)
2691 for (j=0;j<C*ret;j++)
2692 pcm[j]=out[j]*(1.f/32768.f);
2693
2694 RESTORE_STACK;
2695 return ret;
2696}
2697#endif /* DISABLE_FLOAT_API */
2698
2699#else
2700
2701int opus_custom_decode_float(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, float * OPUS_RESTRICT pcm, int frame_size)
2702{
2703 return celt_decode_with_ec(st, data, len, pcm, frame_size, NULL);
2704}
2705
2706int opus_custom_decode(CELTDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_int16 * OPUS_RESTRICT pcm, int frame_size)
2707{
2708 int j, ret, C, N;
2709 VARDECL(celt_sig, out);
2710 ALLOC_STACK;
2711
2712 if (pcm==NULL)
2713 return OPUS_BAD_ARG;
2714
2715 C = st->channels;
2716 N = frame_size;
2717 ALLOC(out, C*N, celt_sig);
2718
2719 ret=celt_decode_with_ec(st, data, len, out, frame_size, NULL);
2720
2721 if (ret>0)
2722 for (j=0;j<C*ret;j++)
2723 pcm[j] = FLOAT2INT16 (out[j]);
2724
2725 RESTORE_STACK;
2726 return ret;
2727}
2728
2729#endif
2730#endif /* CUSTOM_MODES */
2731
2732int opus_custom_decoder_ctl(CELTDecoder * OPUS_RESTRICT st, int request, ...)
2733{
2734 va_list ap;
2735
2736 va_start(ap, request);
2737 switch (request)
2738 {
2739 case CELT_SET_START_BAND_REQUEST:
2740 {
2741 opus_int32 value = va_arg(ap, opus_int32);
2742 if (value<0 || value>=st->mode->nbEBands)
2743 goto bad_arg;
2744 st->start = value;
2745 }
2746 break;
2747 case CELT_SET_END_BAND_REQUEST:
2748 {
2749 opus_int32 value = va_arg(ap, opus_int32);
2750 if (value<1 || value>st->mode->nbEBands)
2751 goto bad_arg;
2752 st->end = value;
2753 }
2754 break;
2755 case CELT_SET_CHANNELS_REQUEST:
2756 {
2757 opus_int32 value = va_arg(ap, opus_int32);
2758 if (value<1 || value>2)
2759 goto bad_arg;
2760 st->stream_channels = value;
2761 }
2762 break;
2763 case CELT_GET_AND_CLEAR_ERROR_REQUEST:
2764 {
2765 opus_int32 *value = va_arg(ap, opus_int32*);
2766 if (value==NULL)
2767 goto bad_arg;
2768 *value=st->error;
2769 st->error = 0;
2770 }
2771 break;
2772 case OPUS_GET_LOOKAHEAD_REQUEST:
2773 {
2774 opus_int32 *value = va_arg(ap, opus_int32*);
2775 if (value==NULL)
2776 goto bad_arg;
2777 *value = st->overlap/st->downsample;
2778 }
2779 break;
2780 case OPUS_RESET_STATE:
2781 {
2782 int i;
2783 opus_val16 *lpc, *oldBandE, *oldLogE, *oldLogE2;
2784 lpc = (opus_val16*)(st->_decode_mem+(DECODE_BUFFER_SIZE+st->overlap)*st->channels);
2785 oldBandE = lpc+st->channels*LPC_ORDER;
2786 oldLogE = oldBandE + 2*st->mode->nbEBands;
2787 oldLogE2 = oldLogE + 2*st->mode->nbEBands;
2788 OPUS_CLEAR((char*)&st->DECODER_RESET_START,
2789 opus_custom_decoder_get_size(st->mode, st->channels)-
2790 ((char*)&st->DECODER_RESET_START - (char*)st));
2791 for (i=0;i<2*st->mode->nbEBands;i++)
2792 oldLogE[i]=oldLogE2[i]=-QCONST16(28.f,DB_SHIFT);
2793 }
2794 break;
2795 case OPUS_GET_PITCH_REQUEST:
2796 {
2797 opus_int32 *value = va_arg(ap, opus_int32*);
2798 if (value==NULL)
2799 goto bad_arg;
2800 *value = st->postfilter_period;
2801 }
2802 break;
2803#ifdef OPUS_BUILD
2804 case CELT_GET_MODE_REQUEST:
2805 {
2806 const CELTMode ** value = va_arg(ap, const CELTMode**);
2807 if (value==0)
2808 goto bad_arg;
2809 *value=st->mode;
2810 }
2811 break;
2812 case CELT_SET_SIGNALLING_REQUEST:
2813 {
2814 opus_int32 value = va_arg(ap, opus_int32);
2815 st->signalling = value;
2816 }
2817 break;
2818 case OPUS_GET_FINAL_RANGE_REQUEST:
2819 {
2820 opus_uint32 * value = va_arg(ap, opus_uint32 *);
2821 if (value==0)
2822 goto bad_arg;
2823 *value=st->rng;
2824 }
2825 break;
2826#endif
2827 default:
2828 goto bad_request;
2829 }
2830 va_end(ap);
2831 return OPUS_OK;
2832bad_arg:
2833 va_end(ap);
2834 return OPUS_BAD_ARG;
2835bad_request:
2836 va_end(ap);
2837 return OPUS_UNIMPLEMENTED;
2838}
2839
2840
2841
2842const char *opus_strerror(int error)
2843{
2844 static const char * const error_strings[8] = {
2845 "success",
2846 "invalid argument",
2847 "buffer too small",
2848 "internal error",
2849 "corrupted stream",
2850 "request not implemented",
2851 "invalid state",
2852 "memory allocation failed"
2853 };
2854 if (error > 0 || error < -7)
2855 return "unknown error";
2856 else
2857 return error_strings[-error];
2858}
2859
2860const char *opus_get_version_string(void)
2861{
2862 return "libopus " OPUS_VERSION
2863#ifdef FIXED_POINT
2864 "-fixed"
2865#endif
2866#ifdef FUZZING
2867 "-fuzzing"
2868#endif
2869 ;
2870}
diff --git a/lib/rbcodec/codecs/libopus/celt/celt.h b/lib/rbcodec/codecs/libopus/celt/celt.h
new file mode 100644
index 0000000000..218cd883df
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/celt.h
@@ -0,0 +1,117 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2008 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/**
6 @file celt.h
7 @brief Contains all the functions for encoding and decoding audio
8 */
9
10/*
11 Redistribution and use in source and binary forms, with or without
12 modification, are permitted provided that the following conditions
13 are met:
14
15 - Redistributions of source code must retain the above copyright
16 notice, this list of conditions and the following disclaimer.
17
18 - Redistributions in binary form must reproduce the above copyright
19 notice, this list of conditions and the following disclaimer in the
20 documentation and/or other materials provided with the distribution.
21
22 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
26 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33*/
34
35#ifndef CELT_H
36#define CELT_H
37
38#include "opus_types.h"
39#include "opus_defines.h"
40#include "opus_custom.h"
41#include "entenc.h"
42#include "entdec.h"
43#include "arch.h"
44
45#ifdef __cplusplus
46extern "C" {
47#endif
48
49#define CELTEncoder OpusCustomEncoder
50#define CELTDecoder OpusCustomDecoder
51#define CELTMode OpusCustomMode
52
53#define _celt_check_mode_ptr_ptr(ptr) ((ptr) + ((ptr) - (const CELTMode**)(ptr)))
54
55/* Encoder/decoder Requests */
56
57#define CELT_SET_PREDICTION_REQUEST 10002
58/** Controls the use of interframe prediction.
59 0=Independent frames
60 1=Short term interframe prediction allowed
61 2=Long term prediction allowed
62 */
63#define CELT_SET_PREDICTION(x) CELT_SET_PREDICTION_REQUEST, __opus_check_int(x)
64
65#define CELT_SET_INPUT_CLIPPING_REQUEST 10004
66#define CELT_SET_INPUT_CLIPPING(x) CELT_SET_INPUT_CLIPPING_REQUEST, __opus_check_int(x)
67
68#define CELT_GET_AND_CLEAR_ERROR_REQUEST 10007
69#define CELT_GET_AND_CLEAR_ERROR(x) CELT_GET_AND_CLEAR_ERROR_REQUEST, __opus_check_int_ptr(x)
70
71#define CELT_SET_CHANNELS_REQUEST 10008
72#define CELT_SET_CHANNELS(x) CELT_SET_CHANNELS_REQUEST, __opus_check_int(x)
73
74
75/* Internal */
76#define CELT_SET_START_BAND_REQUEST 10010
77#define CELT_SET_START_BAND(x) CELT_SET_START_BAND_REQUEST, __opus_check_int(x)
78
79#define CELT_SET_END_BAND_REQUEST 10012
80#define CELT_SET_END_BAND(x) CELT_SET_END_BAND_REQUEST, __opus_check_int(x)
81
82#define CELT_GET_MODE_REQUEST 10015
83/** Get the CELTMode used by an encoder or decoder */
84#define CELT_GET_MODE(x) CELT_GET_MODE_REQUEST, _celt_check_mode_ptr_ptr(x)
85
86#define CELT_SET_SIGNALLING_REQUEST 10016
87#define CELT_SET_SIGNALLING(x) CELT_SET_SIGNALLING_REQUEST, __opus_check_int(x)
88
89
90
91/* Encoder stuff */
92
93int celt_encoder_get_size(int channels);
94
95int celt_encode_with_ec(OpusCustomEncoder * OPUS_RESTRICT st, const opus_val16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc);
96
97int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels);
98
99
100
101/* Decoder stuff */
102
103int celt_decoder_get_size(int channels);
104
105
106int celt_decoder_init(CELTDecoder *st, opus_int32 sampling_rate, int channels);
107
108int celt_decode_with_ec(OpusCustomDecoder * OPUS_RESTRICT st, const unsigned char *data, int len, opus_val16 * OPUS_RESTRICT pcm, int frame_size, ec_dec *dec);
109
110#define celt_encoder_ctl opus_custom_encoder_ctl
111#define celt_decoder_ctl opus_custom_decoder_ctl
112
113#ifdef __cplusplus
114}
115#endif
116
117#endif /* CELT_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/celt_lpc.c b/lib/rbcodec/codecs/libopus/celt/celt_lpc.c
new file mode 100644
index 0000000000..66aed1de09
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/celt_lpc.c
@@ -0,0 +1,188 @@
1/* Copyright (c) 2009-2010 Xiph.Org Foundation
2 Written by Jean-Marc Valin */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "celt_lpc.h"
33#include "stack_alloc.h"
34#include "mathops.h"
35
36void _celt_lpc(
37 opus_val16 *_lpc, /* out: [0...p-1] LPC coefficients */
38const opus_val32 *ac, /* in: [0...p] autocorrelation values */
39int p
40)
41{
42 int i, j;
43 opus_val32 r;
44 opus_val32 error = ac[0];
45#ifdef FIXED_POINT
46 opus_val32 lpc[LPC_ORDER];
47#else
48 float *lpc = _lpc;
49#endif
50
51 for (i = 0; i < p; i++)
52 lpc[i] = 0;
53 if (ac[0] != 0)
54 {
55 for (i = 0; i < p; i++) {
56 /* Sum up this iteration's reflection coefficient */
57 opus_val32 rr = 0;
58 for (j = 0; j < i; j++)
59 rr += MULT32_32_Q31(lpc[j],ac[i - j]);
60 rr += SHR32(ac[i + 1],3);
61 r = -frac_div32(SHL32(rr,3), error);
62 /* Update LPC coefficients and total error */
63 lpc[i] = SHR32(r,3);
64 for (j = 0; j < (i+1)>>1; j++)
65 {
66 opus_val32 tmp1, tmp2;
67 tmp1 = lpc[j];
68 tmp2 = lpc[i-1-j];
69 lpc[j] = tmp1 + MULT32_32_Q31(r,tmp2);
70 lpc[i-1-j] = tmp2 + MULT32_32_Q31(r,tmp1);
71 }
72
73 error = error - MULT32_32_Q31(MULT32_32_Q31(r,r),error);
74 /* Bail out once we get 30 dB gain */
75#ifdef FIXED_POINT
76 if (error<SHR32(ac[0],10))
77 break;
78#else
79 if (error<.001f*ac[0])
80 break;
81#endif
82 }
83 }
84#ifdef FIXED_POINT
85 for (i=0;i<p;i++)
86 _lpc[i] = ROUND16(lpc[i],16);
87#endif
88}
89
90void celt_fir(const opus_val16 *x,
91 const opus_val16 *num,
92 opus_val16 *y,
93 int N,
94 int ord,
95 opus_val16 *mem)
96{
97 int i,j;
98
99 for (i=0;i<N;i++)
100 {
101 opus_val32 sum = SHL32(EXTEND32(x[i]), SIG_SHIFT);
102 for (j=0;j<ord;j++)
103 {
104 sum += MULT16_16(num[j],mem[j]);
105 }
106 for (j=ord-1;j>=1;j--)
107 {
108 mem[j]=mem[j-1];
109 }
110 mem[0] = x[i];
111 y[i] = ROUND16(sum, SIG_SHIFT);
112 }
113}
114
115void celt_iir(const opus_val32 *x,
116 const opus_val16 *den,
117 opus_val32 *y,
118 int N,
119 int ord,
120 opus_val16 *mem)
121{
122 int i,j;
123 for (i=0;i<N;i++)
124 {
125 opus_val32 sum = x[i];
126 for (j=0;j<ord;j++)
127 {
128 sum -= MULT16_16(den[j],mem[j]);
129 }
130 for (j=ord-1;j>=1;j--)
131 {
132 mem[j]=mem[j-1];
133 }
134 mem[0] = ROUND16(sum,SIG_SHIFT);
135 y[i] = sum;
136 }
137}
138
139void _celt_autocorr(
140 const opus_val16 *x, /* in: [0...n-1] samples x */
141 opus_val32 *ac, /* out: [0...lag-1] ac values */
142 const opus_val16 *window,
143 int overlap,
144 int lag,
145 int n
146 )
147{
148 opus_val32 d;
149 int i;
150 VARDECL(opus_val16, xx);
151 SAVE_STACK;
152 ALLOC(xx, n, opus_val16);
153 celt_assert(n>0);
154 celt_assert(overlap>=0);
155 for (i=0;i<n;i++)
156 xx[i] = x[i];
157 for (i=0;i<overlap;i++)
158 {
159 xx[i] = MULT16_16_Q15(x[i],window[i]);
160 xx[n-i-1] = MULT16_16_Q15(x[n-i-1],window[i]);
161 }
162#ifdef FIXED_POINT
163 {
164 opus_val32 ac0=0;
165 int shift;
166 for(i=0;i<n;i++)
167 ac0 += SHR32(MULT16_16(xx[i],xx[i]),9);
168 ac0 += 1+n;
169
170 shift = celt_ilog2(ac0)-30+10;
171 shift = (shift+1)/2;
172 for(i=0;i<n;i++)
173 xx[i] = VSHR32(xx[i], shift);
174 }
175#endif
176 while (lag>=0)
177 {
178 for (i = lag, d = 0; i < n; i++)
179 d += xx[i] * xx[i-lag];
180 ac[lag] = d;
181 /*printf ("%f ", ac[lag]);*/
182 lag--;
183 }
184 /*printf ("\n");*/
185 ac[0] += 10;
186
187 RESTORE_STACK;
188}
diff --git a/lib/rbcodec/codecs/libopus/celt/celt_lpc.h b/lib/rbcodec/codecs/libopus/celt/celt_lpc.h
new file mode 100644
index 0000000000..2baa77edf8
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/celt_lpc.h
@@ -0,0 +1,53 @@
1/* Copyright (c) 2009-2010 Xiph.Org Foundation
2 Written by Jean-Marc Valin */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#ifndef PLC_H
29#define PLC_H
30
31#include "arch.h"
32
33#define LPC_ORDER 24
34
35void _celt_lpc(opus_val16 *_lpc, const opus_val32 *ac, int p);
36
37void celt_fir(const opus_val16 *x,
38 const opus_val16 *num,
39 opus_val16 *y,
40 int N,
41 int ord,
42 opus_val16 *mem);
43
44void celt_iir(const opus_val32 *x,
45 const opus_val16 *den,
46 opus_val32 *y,
47 int N,
48 int ord,
49 opus_val16 *mem);
50
51void _celt_autocorr(const opus_val16 *x, opus_val32 *ac, const opus_val16 *window, int overlap, int lag, int n);
52
53#endif /* PLC_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/cwrs.c b/lib/rbcodec/codecs/libopus/celt/cwrs.c
new file mode 100644
index 0000000000..3d5dd790d9
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/cwrs.c
@@ -0,0 +1,645 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2007-2009 Timothy B. Terriberry
4 Written by Timothy B. Terriberry and Jean-Marc Valin */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifdef HAVE_CONFIG_H
31#include "opus_config.h"
32#endif
33
34#include "os_support.h"
35#include "cwrs.h"
36#include "mathops.h"
37#include "arch.h"
38
39#ifdef CUSTOM_MODES
40
41/*Guaranteed to return a conservatively large estimate of the binary logarithm
42 with frac bits of fractional precision.
43 Tested for all possible 32-bit inputs with frac=4, where the maximum
44 overestimation is 0.06254243 bits.*/
45int log2_frac(opus_uint32 val, int frac)
46{
47 int l;
48 l=EC_ILOG(val);
49 if(val&(val-1)){
50 /*This is (val>>l-16), but guaranteed to round up, even if adding a bias
51 before the shift would cause overflow (e.g., for 0xFFFFxxxx).
52 Doesn't work for val=0, but that case fails the test above.*/
53 if(l>16)val=((val-1)>>(l-16))+1;
54 else val<<=16-l;
55 l=(l-1)<<frac;
56 /*Note that we always need one iteration, since the rounding up above means
57 that we might need to adjust the integer part of the logarithm.*/
58 do{
59 int b;
60 b=(int)(val>>16);
61 l+=b<<frac;
62 val=(val+b)>>b;
63 val=(val*val+0x7FFF)>>15;
64 }
65 while(frac-->0);
66 /*If val is not exactly 0x8000, then we have to round up the remainder.*/
67 return l+(val>0x8000);
68 }
69 /*Exact powers of two require no rounding.*/
70 else return (l-1)<<frac;
71}
72#endif
73
74#ifndef SMALL_FOOTPRINT
75
76#define MASK32 (0xFFFFFFFF)
77
78/*INV_TABLE[i] holds the multiplicative inverse of (2*i+1) mod 2**32.*/
79static const opus_uint32 INV_TABLE[53]={
80 0x00000001,0xAAAAAAAB,0xCCCCCCCD,0xB6DB6DB7,
81 0x38E38E39,0xBA2E8BA3,0xC4EC4EC5,0xEEEEEEEF,
82 0xF0F0F0F1,0x286BCA1B,0x3CF3CF3D,0xE9BD37A7,
83 0xC28F5C29,0x684BDA13,0x4F72C235,0xBDEF7BDF,
84 0x3E0F83E1,0x8AF8AF8B,0x914C1BAD,0x96F96F97,
85 0xC18F9C19,0x2FA0BE83,0xA4FA4FA5,0x677D46CF,
86 0x1A1F58D1,0xFAFAFAFB,0x8C13521D,0x586FB587,
87 0xB823EE09,0xA08AD8F3,0xC10C9715,0xBEFBEFBF,
88 0xC0FC0FC1,0x07A44C6B,0xA33F128D,0xE327A977,
89 0xC7E3F1F9,0x962FC963,0x3F2B3885,0x613716AF,
90 0x781948B1,0x2B2E43DB,0xFCFCFCFD,0x6FD0EB67,
91 0xFA3F47E9,0xD2FD2FD3,0x3F4FD3F5,0xD4E25B9F,
92 0x5F02A3A1,0xBF5A814B,0x7C32B16D,0xD3431B57,
93 0xD8FD8FD9,
94};
95
96/*Computes (_a*_b-_c)/(2*_d+1) when the quotient is known to be exact.
97 _a, _b, _c, and _d may be arbitrary so long as the arbitrary precision result
98 fits in 32 bits, but currently the table for multiplicative inverses is only
99 valid for _d<=52.*/
100static inline opus_uint32 imusdiv32odd(opus_uint32 _a,opus_uint32 _b,
101 opus_uint32 _c,int _d){
102 celt_assert(_d<=52);
103 return (_a*_b-_c)*INV_TABLE[_d]&MASK32;
104}
105
106/*Computes (_a*_b-_c)/_d when the quotient is known to be exact.
107 _d does not actually have to be even, but imusdiv32odd will be faster when
108 it's odd, so you should use that instead.
109 _a and _d are assumed to be small (e.g., _a*_d fits in 32 bits; currently the
110 table for multiplicative inverses is only valid for _d<=54).
111 _b and _c may be arbitrary so long as the arbitrary precision reuslt fits in
112 32 bits.*/
113static inline opus_uint32 imusdiv32even(opus_uint32 _a,opus_uint32 _b,
114 opus_uint32 _c,int _d){
115 opus_uint32 inv;
116 int mask;
117 int shift;
118 int one;
119 celt_assert(_d>0);
120 celt_assert(_d<=54);
121 shift=EC_ILOG(_d^(_d-1));
122 inv=INV_TABLE[(_d-1)>>shift];
123 shift--;
124 one=1<<shift;
125 mask=one-1;
126 return (_a*(_b>>shift)-(_c>>shift)+
127 ((_a*(_b&mask)+one-(_c&mask))>>shift)-1)*inv&MASK32;
128}
129
130#endif /* SMALL_FOOTPRINT */
131
132/*Although derived separately, the pulse vector coding scheme is equivalent to
133 a Pyramid Vector Quantizer \cite{Fis86}.
134 Some additional notes about an early version appear at
135 http://people.xiph.org/~tterribe/notes/cwrs.html, but the codebook ordering
136 and the definitions of some terms have evolved since that was written.
137
138 The conversion from a pulse vector to an integer index (encoding) and back
139 (decoding) is governed by two related functions, V(N,K) and U(N,K).
140
141 V(N,K) = the number of combinations, with replacement, of N items, taken K
142 at a time, when a sign bit is added to each item taken at least once (i.e.,
143 the number of N-dimensional unit pulse vectors with K pulses).
144 One way to compute this is via
145 V(N,K) = K>0 ? sum(k=1...K,2**k*choose(N,k)*choose(K-1,k-1)) : 1,
146 where choose() is the binomial function.
147 A table of values for N<10 and K<10 looks like:
148 V[10][10] = {
149 {1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
150 {1, 2, 2, 2, 2, 2, 2, 2, 2, 2},
151 {1, 4, 8, 12, 16, 20, 24, 28, 32, 36},
152 {1, 6, 18, 38, 66, 102, 146, 198, 258, 326},
153 {1, 8, 32, 88, 192, 360, 608, 952, 1408, 1992},
154 {1, 10, 50, 170, 450, 1002, 1970, 3530, 5890, 9290},
155 {1, 12, 72, 292, 912, 2364, 5336, 10836, 20256, 35436},
156 {1, 14, 98, 462, 1666, 4942, 12642, 28814, 59906, 115598},
157 {1, 16, 128, 688, 2816, 9424, 27008, 68464, 157184, 332688},
158 {1, 18, 162, 978, 4482, 16722, 53154, 148626, 374274, 864146}
159 };
160
161 U(N,K) = the number of such combinations wherein N-1 objects are taken at
162 most K-1 at a time.
163 This is given by
164 U(N,K) = sum(k=0...K-1,V(N-1,k))
165 = K>0 ? (V(N-1,K-1) + V(N,K-1))/2 : 0.
166 The latter expression also makes clear that U(N,K) is half the number of such
167 combinations wherein the first object is taken at least once.
168 Although it may not be clear from either of these definitions, U(N,K) is the
169 natural function to work with when enumerating the pulse vector codebooks,
170 not V(N,K).
171 U(N,K) is not well-defined for N=0, but with the extension
172 U(0,K) = K>0 ? 0 : 1,
173 the function becomes symmetric: U(N,K) = U(K,N), with a similar table:
174 U[10][10] = {
175 {1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
176 {0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
177 {0, 1, 3, 5, 7, 9, 11, 13, 15, 17},
178 {0, 1, 5, 13, 25, 41, 61, 85, 113, 145},
179 {0, 1, 7, 25, 63, 129, 231, 377, 575, 833},
180 {0, 1, 9, 41, 129, 321, 681, 1289, 2241, 3649},
181 {0, 1, 11, 61, 231, 681, 1683, 3653, 7183, 13073},
182 {0, 1, 13, 85, 377, 1289, 3653, 8989, 19825, 40081},
183 {0, 1, 15, 113, 575, 2241, 7183, 19825, 48639, 108545},
184 {0, 1, 17, 145, 833, 3649, 13073, 40081, 108545, 265729}
185 };
186
187 With this extension, V(N,K) may be written in terms of U(N,K):
188 V(N,K) = U(N,K) + U(N,K+1)
189 for all N>=0, K>=0.
190 Thus U(N,K+1) represents the number of combinations where the first element
191 is positive or zero, and U(N,K) represents the number of combinations where
192 it is negative.
193 With a large enough table of U(N,K) values, we could write O(N) encoding
194 and O(min(N*log(K),N+K)) decoding routines, but such a table would be
195 prohibitively large for small embedded devices (K may be as large as 32767
196 for small N, and N may be as large as 200).
197
198 Both functions obey the same recurrence relation:
199 V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1),
200 U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1),
201 for all N>0, K>0, with different initial conditions at N=0 or K=0.
202 This allows us to construct a row of one of the tables above given the
203 previous row or the next row.
204 Thus we can derive O(NK) encoding and decoding routines with O(K) memory
205 using only addition and subtraction.
206
207 When encoding, we build up from the U(2,K) row and work our way forwards.
208 When decoding, we need to start at the U(N,K) row and work our way backwards,
209 which requires a means of computing U(N,K).
210 U(N,K) may be computed from two previous values with the same N:
211 U(N,K) = ((2*N-1)*U(N,K-1) - U(N,K-2))/(K-1) + U(N,K-2)
212 for all N>1, and since U(N,K) is symmetric, a similar relation holds for two
213 previous values with the same K:
214 U(N,K>1) = ((2*K-1)*U(N-1,K) - U(N-2,K))/(N-1) + U(N-2,K)
215 for all K>1.
216 This allows us to construct an arbitrary row of the U(N,K) table by starting
217 with the first two values, which are constants.
218 This saves roughly 2/3 the work in our O(NK) decoding routine, but costs O(K)
219 multiplications.
220 Similar relations can be derived for V(N,K), but are not used here.
221
222 For N>0 and K>0, U(N,K) and V(N,K) take on the form of an (N-1)-degree
223 polynomial for fixed N.
224 The first few are
225 U(1,K) = 1,
226 U(2,K) = 2*K-1,
227 U(3,K) = (2*K-2)*K+1,
228 U(4,K) = (((4*K-6)*K+8)*K-3)/3,
229 U(5,K) = ((((2*K-4)*K+10)*K-8)*K+3)/3,
230 and
231 V(1,K) = 2,
232 V(2,K) = 4*K,
233 V(3,K) = 4*K*K+2,
234 V(4,K) = 8*(K*K+2)*K/3,
235 V(5,K) = ((4*K*K+20)*K*K+6)/3,
236 for all K>0.
237 This allows us to derive O(N) encoding and O(N*log(K)) decoding routines for
238 small N (and indeed decoding is also O(N) for N<3).
239
240 @ARTICLE{Fis86,
241 author="Thomas R. Fischer",
242 title="A Pyramid Vector Quantizer",
243 journal="IEEE Transactions on Information Theory",
244 volume="IT-32",
245 number=4,
246 pages="568--583",
247 month=Jul,
248 year=1986
249 }*/
250
251#ifndef SMALL_FOOTPRINT
252/*Compute U(2,_k).
253 Note that this may be called with _k=32768 (maxK[2]+1).*/
254static inline unsigned ucwrs2(unsigned _k){
255 celt_assert(_k>0);
256 return _k+(_k-1);
257}
258
259/*Compute V(2,_k).*/
260static inline opus_uint32 ncwrs2(int _k){
261 celt_assert(_k>0);
262 return 4*(opus_uint32)_k;
263}
264
265/*Compute U(3,_k).
266 Note that this may be called with _k=32768 (maxK[3]+1).*/
267static inline opus_uint32 ucwrs3(unsigned _k){
268 celt_assert(_k>0);
269 return (2*(opus_uint32)_k-2)*_k+1;
270}
271
272/*Compute V(3,_k).*/
273static inline opus_uint32 ncwrs3(int _k){
274 celt_assert(_k>0);
275 return 2*(2*(unsigned)_k*(opus_uint32)_k+1);
276}
277
278/*Compute U(4,_k).*/
279static inline opus_uint32 ucwrs4(int _k){
280 celt_assert(_k>0);
281 return imusdiv32odd(2*_k,(2*_k-3)*(opus_uint32)_k+4,3,1);
282}
283
284/*Compute V(4,_k).*/
285static inline opus_uint32 ncwrs4(int _k){
286 celt_assert(_k>0);
287 return ((_k*(opus_uint32)_k+2)*_k)/3<<3;
288}
289
290#endif /* SMALL_FOOTPRINT */
291
292/*Computes the next row/column of any recurrence that obeys the relation
293 u[i][j]=u[i-1][j]+u[i][j-1]+u[i-1][j-1].
294 _ui0 is the base case for the new row/column.*/
295static inline void unext(opus_uint32 *_ui,unsigned _len,opus_uint32 _ui0){
296 opus_uint32 ui1;
297 unsigned j;
298 /*This do-while will overrun the array if we don't have storage for at least
299 2 values.*/
300 j=1; do {
301 ui1=UADD32(UADD32(_ui[j],_ui[j-1]),_ui0);
302 _ui[j-1]=_ui0;
303 _ui0=ui1;
304 } while (++j<_len);
305 _ui[j-1]=_ui0;
306}
307
308/*Computes the previous row/column of any recurrence that obeys the relation
309 u[i-1][j]=u[i][j]-u[i][j-1]-u[i-1][j-1].
310 _ui0 is the base case for the new row/column.*/
311static inline void uprev(opus_uint32 *_ui,unsigned _n,opus_uint32 _ui0){
312 opus_uint32 ui1;
313 unsigned j;
314 /*This do-while will overrun the array if we don't have storage for at least
315 2 values.*/
316 j=1; do {
317 ui1=USUB32(USUB32(_ui[j],_ui[j-1]),_ui0);
318 _ui[j-1]=_ui0;
319 _ui0=ui1;
320 } while (++j<_n);
321 _ui[j-1]=_ui0;
322}
323
324/*Compute V(_n,_k), as well as U(_n,0..._k+1).
325 _u: On exit, _u[i] contains U(_n,i) for i in [0..._k+1].*/
326static opus_uint32 ncwrs_urow(unsigned _n,unsigned _k,opus_uint32 *_u){
327 opus_uint32 um2;
328 unsigned len;
329 unsigned k;
330 len=_k+2;
331 /*We require storage at least 3 values (e.g., _k>0).*/
332 celt_assert(len>=3);
333 _u[0]=0;
334 _u[1]=um2=1;
335#ifndef SMALL_FOOTPRINT
336 /*_k>52 doesn't work in the false branch due to the limits of INV_TABLE,
337 but _k isn't tested here because k<=52 for n=7*/
338 if(_n<=6)
339#endif
340 {
341 /*If _n==0, _u[0] should be 1 and the rest should be 0.*/
342 /*If _n==1, _u[i] should be 1 for i>1.*/
343 celt_assert(_n>=2);
344 /*If _k==0, the following do-while loop will overflow the buffer.*/
345 celt_assert(_k>0);
346 k=2;
347 do _u[k]=(k<<1)-1;
348 while(++k<len);
349 for(k=2;k<_n;k++)unext(_u+1,_k+1,1);
350 }
351#ifndef SMALL_FOOTPRINT
352 else{
353 opus_uint32 um1;
354 opus_uint32 n2m1;
355 _u[2]=n2m1=um1=(_n<<1)-1;
356 for(k=3;k<len;k++){
357 /*U(N,K) = ((2*N-1)*U(N,K-1)-U(N,K-2))/(K-1) + U(N,K-2)*/
358 _u[k]=um2=imusdiv32even(n2m1,um1,um2,k-1)+um2;
359 if(++k>=len)break;
360 _u[k]=um1=imusdiv32odd(n2m1,um2,um1,(k-1)>>1)+um1;
361 }
362 }
363#endif /* SMALL_FOOTPRINT */
364 return _u[_k]+_u[_k+1];
365}
366
367#ifndef SMALL_FOOTPRINT
368
369/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
370 set of size 1 with associated sign bits.
371 _y: Returns the vector of pulses.*/
372static inline void cwrsi1(int _k,opus_uint32 _i,int *_y){
373 int s;
374 s=-(int)_i;
375 _y[0]=(_k+s)^s;
376}
377
378/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
379 set of size 2 with associated sign bits.
380 _y: Returns the vector of pulses.*/
381static inline void cwrsi2(int _k,opus_uint32 _i,int *_y){
382 opus_uint32 p;
383 int s;
384 int yj;
385 p=ucwrs2(_k+1U);
386 s=-(_i>=p);
387 _i-=p&s;
388 yj=_k;
389 _k=(_i+1)>>1;
390 p=_k?ucwrs2(_k):0;
391 _i-=p;
392 yj-=_k;
393 _y[0]=(yj+s)^s;
394 cwrsi1(_k,_i,_y+1);
395}
396
397/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
398 set of size 3 with associated sign bits.
399 _y: Returns the vector of pulses.*/
400static void cwrsi3(int _k,opus_uint32 _i,int *_y){
401 opus_uint32 p;
402 int s;
403 int yj;
404 p=ucwrs3(_k+1U);
405 s=-(_i>=p);
406 _i-=p&s;
407 yj=_k;
408 /*Finds the maximum _k such that ucwrs3(_k)<=_i (tested for all
409 _i<2147418113=U(3,32768)).*/
410 _k=_i>0?(isqrt32(2*_i-1)+1)>>1:0;
411 p=_k?ucwrs3(_k):0;
412 _i-=p;
413 yj-=_k;
414 _y[0]=(yj+s)^s;
415 cwrsi2(_k,_i,_y+1);
416}
417
418/*Returns the _i'th combination of _k elements (at most 1172) chosen from a set
419 of size 4 with associated sign bits.
420 _y: Returns the vector of pulses.*/
421static void cwrsi4(int _k,opus_uint32 _i,int *_y){
422 opus_uint32 p;
423 int s;
424 int yj;
425 int kl;
426 int kr;
427 p=ucwrs4(_k+1);
428 s=-(_i>=p);
429 _i-=p&s;
430 yj=_k;
431 /*We could solve a cubic for k here, but the form of the direct solution does
432 not lend itself well to exact integer arithmetic.
433 Instead we do a binary search on U(4,K).*/
434 kl=0;
435 kr=_k;
436 for(;;){
437 _k=(kl+kr)>>1;
438 p=_k?ucwrs4(_k):0;
439 if(p<_i){
440 if(_k>=kr)break;
441 kl=_k+1;
442 }
443 else if(p>_i)kr=_k-1;
444 else break;
445 }
446 _i-=p;
447 yj-=_k;
448 _y[0]=(yj+s)^s;
449 cwrsi3(_k,_i,_y+1);
450}
451
452#endif /* SMALL_FOOTPRINT */
453
454/*Returns the _i'th combination of _k elements chosen from a set of size _n
455 with associated sign bits.
456 _y: Returns the vector of pulses.
457 _u: Must contain entries [0..._k+1] of row _n of U() on input.
458 Its contents will be destructively modified.*/
459static void cwrsi(int _n,int _k,opus_uint32 _i,int *_y,opus_uint32 *_u){
460 int j;
461 celt_assert(_n>0);
462 j=0;
463 do{
464 opus_uint32 p;
465 int s;
466 int yj;
467 p=_u[_k+1];
468 s=-(_i>=p);
469 _i-=p&s;
470 yj=_k;
471 p=_u[_k];
472 while(p>_i)p=_u[--_k];
473 _i-=p;
474 yj-=_k;
475 _y[j]=(yj+s)^s;
476 uprev(_u,_k+2,0);
477 }
478 while(++j<_n);
479}
480
481/*Returns the index of the given combination of K elements chosen from a set
482 of size 1 with associated sign bits.
483 _y: The vector of pulses, whose sum of absolute values is K.
484 _k: Returns K.*/
485static inline opus_uint32 icwrs1(const int *_y,int *_k){
486 *_k=abs(_y[0]);
487 return _y[0]<0;
488}
489
490#ifndef SMALL_FOOTPRINT
491
492/*Returns the index of the given combination of K elements chosen from a set
493 of size 2 with associated sign bits.
494 _y: The vector of pulses, whose sum of absolute values is K.
495 _k: Returns K.*/
496static inline opus_uint32 icwrs2(const int *_y,int *_k){
497 opus_uint32 i;
498 int k;
499 i=icwrs1(_y+1,&k);
500 i+=k?ucwrs2(k):0;
501 k+=abs(_y[0]);
502 if(_y[0]<0)i+=ucwrs2(k+1U);
503 *_k=k;
504 return i;
505}
506
507/*Returns the index of the given combination of K elements chosen from a set
508 of size 3 with associated sign bits.
509 _y: The vector of pulses, whose sum of absolute values is K.
510 _k: Returns K.*/
511static inline opus_uint32 icwrs3(const int *_y,int *_k){
512 opus_uint32 i;
513 int k;
514 i=icwrs2(_y+1,&k);
515 i+=k?ucwrs3(k):0;
516 k+=abs(_y[0]);
517 if(_y[0]<0)i+=ucwrs3(k+1U);
518 *_k=k;
519 return i;
520}
521
522/*Returns the index of the given combination of K elements chosen from a set
523 of size 4 with associated sign bits.
524 _y: The vector of pulses, whose sum of absolute values is K.
525 _k: Returns K.*/
526static inline opus_uint32 icwrs4(const int *_y,int *_k){
527 opus_uint32 i;
528 int k;
529 i=icwrs3(_y+1,&k);
530 i+=k?ucwrs4(k):0;
531 k+=abs(_y[0]);
532 if(_y[0]<0)i+=ucwrs4(k+1);
533 *_k=k;
534 return i;
535}
536
537#endif /* SMALL_FOOTPRINT */
538
539/*Returns the index of the given combination of K elements chosen from a set
540 of size _n with associated sign bits.
541 _y: The vector of pulses, whose sum of absolute values must be _k.
542 _nc: Returns V(_n,_k).*/
543static inline opus_uint32 icwrs(int _n,int _k,opus_uint32 *_nc,const int *_y,
544 opus_uint32 *_u){
545 opus_uint32 i;
546 int j;
547 int k;
548 /*We can't unroll the first two iterations of the loop unless _n>=2.*/
549 celt_assert(_n>=2);
550 _u[0]=0;
551 for(k=1;k<=_k+1;k++)_u[k]=(k<<1)-1;
552 i=icwrs1(_y+_n-1,&k);
553 j=_n-2;
554 i+=_u[k];
555 k+=abs(_y[j]);
556 if(_y[j]<0)i+=_u[k+1];
557 while(j-->0){
558 unext(_u,_k+2,0);
559 i+=_u[k];
560 k+=abs(_y[j]);
561 if(_y[j]<0)i+=_u[k+1];
562 }
563 *_nc=_u[k]+_u[k+1];
564 return i;
565}
566
567#ifdef CUSTOM_MODES
568void get_required_bits(opus_int16 *_bits,int _n,int _maxk,int _frac){
569 int k;
570 /*_maxk==0 => there's nothing to do.*/
571 celt_assert(_maxk>0);
572 _bits[0]=0;
573 if (_n==1)
574 {
575 for (k=1;k<=_maxk;k++)
576 _bits[k] = 1<<_frac;
577 }
578 else {
579 VARDECL(opus_uint32,u);
580 SAVE_STACK;
581 ALLOC(u,_maxk+2U,opus_uint32);
582 ncwrs_urow(_n,_maxk,u);
583 for(k=1;k<=_maxk;k++)
584 _bits[k]=log2_frac(u[k]+u[k+1],_frac);
585 RESTORE_STACK;
586 }
587}
588#endif /* CUSTOM_MODES */
589
590void encode_pulses(const int *_y,int _n,int _k,ec_enc *_enc){
591 opus_uint32 i;
592 celt_assert(_k>0);
593#ifndef SMALL_FOOTPRINT
594 switch(_n){
595 case 2:{
596 i=icwrs2(_y,&_k);
597 ec_enc_uint(_enc,i,ncwrs2(_k));
598 }break;
599 case 3:{
600 i=icwrs3(_y,&_k);
601 ec_enc_uint(_enc,i,ncwrs3(_k));
602 }break;
603 case 4:{
604 i=icwrs4(_y,&_k);
605 ec_enc_uint(_enc,i,ncwrs4(_k));
606 }break;
607 default:
608 {
609#endif
610 VARDECL(opus_uint32,u);
611 opus_uint32 nc;
612 SAVE_STACK;
613 ALLOC(u,_k+2U,opus_uint32);
614 i=icwrs(_n,_k,&nc,_y,u);
615 ec_enc_uint(_enc,i,nc);
616 RESTORE_STACK;
617#ifndef SMALL_FOOTPRINT
618 }
619 break;
620 }
621#endif
622}
623
624void decode_pulses(int *_y,int _n,int _k,ec_dec *_dec)
625{
626 celt_assert(_k>0);
627#ifndef SMALL_FOOTPRINT
628 switch(_n){
629 case 2:cwrsi2(_k,ec_dec_uint(_dec,ncwrs2(_k)),_y);break;
630 case 3:cwrsi3(_k,ec_dec_uint(_dec,ncwrs3(_k)),_y);break;
631 case 4:cwrsi4(_k,ec_dec_uint(_dec,ncwrs4(_k)),_y);break;
632 default:
633 {
634#endif
635 VARDECL(opus_uint32,u);
636 SAVE_STACK;
637 ALLOC(u,_k+2U,opus_uint32);
638 cwrsi(_n,_k,ec_dec_uint(_dec,ncwrs_urow(_n,_k,u)),_y,u);
639 RESTORE_STACK;
640#ifndef SMALL_FOOTPRINT
641 }
642 break;
643 }
644#endif
645}
diff --git a/lib/rbcodec/codecs/libopus/celt/cwrs.h b/lib/rbcodec/codecs/libopus/celt/cwrs.h
new file mode 100644
index 0000000000..7dfbd076d1
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/cwrs.h
@@ -0,0 +1,48 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2007-2009 Timothy B. Terriberry
4 Written by Timothy B. Terriberry and Jean-Marc Valin */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifndef CWRS_H
31#define CWRS_H
32
33#include "arch.h"
34#include "stack_alloc.h"
35#include "entenc.h"
36#include "entdec.h"
37
38#ifdef CUSTOM_MODES
39int log2_frac(opus_uint32 val, int frac);
40#endif
41
42void get_required_bits(opus_int16 *bits, int N, int K, int frac);
43
44void encode_pulses(const int *_y, int N, int K, ec_enc *enc);
45
46void decode_pulses(int *_y, int N, int K, ec_dec *dec);
47
48#endif /* CWRS_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/ecintrin.h b/lib/rbcodec/codecs/libopus/celt/ecintrin.h
new file mode 100644
index 0000000000..3dffa5f95c
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/ecintrin.h
@@ -0,0 +1,87 @@
1/* Copyright (c) 2003-2008 Timothy B. Terriberry
2 Copyright (c) 2008 Xiph.Org Foundation */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28/*Some common macros for potential platform-specific optimization.*/
29#include "opus_types.h"
30#include <math.h>
31#include <limits.h>
32#include "arch.h"
33#if !defined(_ecintrin_H)
34# define _ecintrin_H (1)
35
36/*Some specific platforms may have optimized intrinsic or inline assembly
37 versions of these functions which can substantially improve performance.
38 We define macros for them to allow easy incorporation of these non-ANSI
39 features.*/
40
41/*Modern gcc (4.x) can compile the naive versions of min and max with cmov if
42 given an appropriate architecture, but the branchless bit-twiddling versions
43 are just as fast, and do not require any special target architecture.
44 Earlier gcc versions (3.x) compiled both code to the same assembly
45 instructions, because of the way they represented ((_b)>(_a)) internally.*/
46# define EC_MINI(_a,_b) ((_a)+(((_b)-(_a))&-((_b)<(_a))))
47
48/*Count leading zeros.
49 This macro should only be used for implementing ec_ilog(), if it is defined.
50 All other code should use EC_ILOG() instead.*/
51#if defined(_MSC_VER)
52# include <intrin.h>
53/*In _DEBUG mode this is not an intrinsic by default.*/
54# pragma intrinsic(_BitScanReverse)
55
56static __inline int ec_bsr(unsigned long _x){
57 unsigned long ret;
58 _BitScanReverse(&ret,_x);
59 return (int)ret;
60}
61# define EC_CLZ0 (1)
62# define EC_CLZ(_x) (-ec_bsr(_x))
63#elif defined(ENABLE_TI_DSPLIB)
64# include "dsplib.h"
65# define EC_CLZ0 (31)
66# define EC_CLZ(_x) (_lnorm(_x))
67#elif __GNUC_PREREQ(3,4)
68# if INT_MAX>=2147483647
69# define EC_CLZ0 ((int)sizeof(unsigned)*CHAR_BIT)
70# define EC_CLZ(_x) (__builtin_clz(_x))
71# elif LONG_MAX>=2147483647L
72# define EC_CLZ0 ((int)sizeof(unsigned long)*CHAR_BIT)
73# define EC_CLZ(_x) (__builtin_clzl(_x))
74# endif
75#endif
76
77#if defined(EC_CLZ)
78/*Note that __builtin_clz is not defined when _x==0, according to the gcc
79 documentation (and that of the BSR instruction that implements it on x86).
80 The majority of the time we can never pass it zero.
81 When we need to, it can be special cased.*/
82# define EC_ILOG(_x) (EC_CLZ0-EC_CLZ(_x))
83#else
84int ec_ilog(opus_uint32 _v);
85# define EC_ILOG(_x) (ec_ilog(_x))
86#endif
87#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/entcode.c b/lib/rbcodec/codecs/libopus/celt/entcode.c
new file mode 100644
index 0000000000..80e64fefaa
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/entcode.c
@@ -0,0 +1,88 @@
1/* Copyright (c) 2001-2011 Timothy B. Terriberry
2*/
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "entcode.h"
33#include "arch.h"
34
35#if !defined(EC_CLZ)
36int ec_ilog(opus_uint32 _v){
37 /*On a Pentium M, this branchless version tested as the fastest on
38 1,000,000,000 random 32-bit integers, edging out a similar version with
39 branches, and a 256-entry LUT version.*/
40 int ret;
41 int m;
42 ret=!!_v;
43 m=!!(_v&0xFFFF0000)<<4;
44 _v>>=m;
45 ret|=m;
46 m=!!(_v&0xFF00)<<3;
47 _v>>=m;
48 ret|=m;
49 m=!!(_v&0xF0)<<2;
50 _v>>=m;
51 ret|=m;
52 m=!!(_v&0xC)<<1;
53 _v>>=m;
54 ret|=m;
55 ret+=!!(_v&0x2);
56 return ret;
57}
58#endif
59
60opus_uint32 ec_tell_frac(ec_ctx *_this){
61 opus_uint32 nbits;
62 opus_uint32 r;
63 int l;
64 int i;
65 /*To handle the non-integral number of bits still left in the encoder/decoder
66 state, we compute the worst-case number of bits of val that must be
67 encoded to ensure that the value is inside the range for any possible
68 subsequent bits.
69 The computation here is independent of val itself (the decoder does not
70 even track that value), even though the real number of bits used after
71 ec_enc_done() may be 1 smaller if rng is a power of two and the
72 corresponding trailing bits of val are all zeros.
73 If we did try to track that special case, then coding a value with a
74 probability of 1/(1<<n) might sometimes appear to use more than n bits.
75 This may help explain the surprising result that a newly initialized
76 encoder or decoder claims to have used 1 bit.*/
77 nbits=_this->nbits_total<<BITRES;
78 l=EC_ILOG(_this->rng);
79 r=_this->rng>>(l-16);
80 for(i=BITRES;i-->0;){
81 int b;
82 r=r*r>>15;
83 b=(int)(r>>16);
84 l=l<<1|b;
85 r>>=b;
86 }
87 return nbits-l;
88}
diff --git a/lib/rbcodec/codecs/libopus/celt/entcode.h b/lib/rbcodec/codecs/libopus/celt/entcode.h
new file mode 100644
index 0000000000..aebecc0647
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/entcode.h
@@ -0,0 +1,116 @@
1/* Copyright (c) 2001-2011 Timothy B. Terriberry
2 Copyright (c) 2008-2009 Xiph.Org Foundation */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#include "opus_types.h"
29
30#if !defined(_entcode_H)
31# define _entcode_H (1)
32# include <limits.h>
33# include <stddef.h>
34# include "ecintrin.h"
35
36/*OPT: ec_window must be at least 32 bits, but if you have fast arithmetic on a
37 larger type, you can speed up the decoder by using it here.*/
38typedef opus_uint32 ec_window;
39typedef struct ec_ctx ec_ctx;
40typedef struct ec_ctx ec_enc;
41typedef struct ec_ctx ec_dec;
42
43# define EC_WINDOW_SIZE ((int)sizeof(ec_window)*CHAR_BIT)
44
45/*The number of bits to use for the range-coded part of unsigned integers.*/
46# define EC_UINT_BITS (8)
47
48/*The resolution of fractional-precision bit usage measurements, i.e.,
49 3 => 1/8th bits.*/
50# define BITRES 3
51
52/*The entropy encoder/decoder context.
53 We use the same structure for both, so that common functions like ec_tell()
54 can be used on either one.*/
55struct ec_ctx{
56 /*Buffered input/output.*/
57 unsigned char *buf;
58 /*The size of the buffer.*/
59 opus_uint32 storage;
60 /*The offset at which the last byte containing raw bits was read/written.*/
61 opus_uint32 end_offs;
62 /*Bits that will be read from/written at the end.*/
63 ec_window end_window;
64 /*Number of valid bits in end_window.*/
65 int nend_bits;
66 /*The total number of whole bits read/written.
67 This does not include partial bits currently in the range coder.*/
68 int nbits_total;
69 /*The offset at which the next range coder byte will be read/written.*/
70 opus_uint32 offs;
71 /*The number of values in the current range.*/
72 opus_uint32 rng;
73 /*In the decoder: the difference between the top of the current range and
74 the input value, minus one.
75 In the encoder: the low end of the current range.*/
76 opus_uint32 val;
77 /*In the decoder: the saved normalization factor from ec_decode().
78 In the encoder: the number of oustanding carry propagating symbols.*/
79 opus_uint32 ext;
80 /*A buffered input/output symbol, awaiting carry propagation.*/
81 int rem;
82 /*Nonzero if an error occurred.*/
83 int error;
84};
85
86static inline opus_uint32 ec_range_bytes(ec_ctx *_this){
87 return _this->offs;
88}
89
90static inline unsigned char *ec_get_buffer(ec_ctx *_this){
91 return _this->buf;
92}
93
94static inline int ec_get_error(ec_ctx *_this){
95 return _this->error;
96}
97
98/*Returns the number of bits "used" by the encoded or decoded symbols so far.
99 This same number can be computed in either the encoder or the decoder, and is
100 suitable for making coding decisions.
101 Return: The number of bits.
102 This will always be slightly larger than the exact value (e.g., all
103 rounding error is in the positive direction).*/
104static inline int ec_tell(ec_ctx *_this){
105 return _this->nbits_total-EC_ILOG(_this->rng);
106}
107
108/*Returns the number of bits "used" by the encoded or decoded symbols so far.
109 This same number can be computed in either the encoder or the decoder, and is
110 suitable for making coding decisions.
111 Return: The number of bits scaled by 2**BITRES.
112 This will always be slightly larger than the exact value (e.g., all
113 rounding error is in the positive direction).*/
114opus_uint32 ec_tell_frac(ec_ctx *_this);
115
116#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/entdec.c b/lib/rbcodec/codecs/libopus/celt/entdec.c
new file mode 100644
index 0000000000..ff8442d534
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/entdec.c
@@ -0,0 +1,245 @@
1/* Copyright (c) 2001-2011 Timothy B. Terriberry
2 Copyright (c) 2008-2009 Xiph.Org Foundation */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include <stddef.h>
33#include "os_support.h"
34#include "arch.h"
35#include "entdec.h"
36#include "mfrngcod.h"
37
38/*A range decoder.
39 This is an entropy decoder based upon \cite{Mar79}, which is itself a
40 rediscovery of the FIFO arithmetic code introduced by \cite{Pas76}.
41 It is very similar to arithmetic encoding, except that encoding is done with
42 digits in any base, instead of with bits, and so it is faster when using
43 larger bases (i.e.: a byte).
44 The author claims an average waste of $\frac{1}{2}\log_b(2b)$ bits, where $b$
45 is the base, longer than the theoretical optimum, but to my knowledge there
46 is no published justification for this claim.
47 This only seems true when using near-infinite precision arithmetic so that
48 the process is carried out with no rounding errors.
49
50 An excellent description of implementation details is available at
51 http://www.arturocampos.com/ac_range.html
52 A recent work \cite{MNW98} which proposes several changes to arithmetic
53 encoding for efficiency actually re-discovers many of the principles
54 behind range encoding, and presents a good theoretical analysis of them.
55
56 End of stream is handled by writing out the smallest number of bits that
57 ensures that the stream will be correctly decoded regardless of the value of
58 any subsequent bits.
59 ec_tell() can be used to determine how many bits were needed to decode
60 all the symbols thus far; other data can be packed in the remaining bits of
61 the input buffer.
62 @PHDTHESIS{Pas76,
63 author="Richard Clark Pasco",
64 title="Source coding algorithms for fast data compression",
65 school="Dept. of Electrical Engineering, Stanford University",
66 address="Stanford, CA",
67 month=May,
68 year=1976
69 }
70 @INPROCEEDINGS{Mar79,
71 author="Martin, G.N.N.",
72 title="Range encoding: an algorithm for removing redundancy from a digitised
73 message",
74 booktitle="Video & Data Recording Conference",
75 year=1979,
76 address="Southampton",
77 month=Jul
78 }
79 @ARTICLE{MNW98,
80 author="Alistair Moffat and Radford Neal and Ian H. Witten",
81 title="Arithmetic Coding Revisited",
82 journal="{ACM} Transactions on Information Systems",
83 year=1998,
84 volume=16,
85 number=3,
86 pages="256--294",
87 month=Jul,
88 URL="http://www.stanford.edu/class/ee398/handouts/papers/Moffat98ArithmCoding.pdf"
89 }*/
90
91static int ec_read_byte(ec_dec *_this){
92 return _this->offs<_this->storage?_this->buf[_this->offs++]:0;
93}
94
95static int ec_read_byte_from_end(ec_dec *_this){
96 return _this->end_offs<_this->storage?
97 _this->buf[_this->storage-++(_this->end_offs)]:0;
98}
99
100/*Normalizes the contents of val and rng so that rng lies entirely in the
101 high-order symbol.*/
102static void ec_dec_normalize(ec_dec *_this){
103 /*If the range is too small, rescale it and input some bits.*/
104 while(_this->rng<=EC_CODE_BOT){
105 int sym;
106 _this->nbits_total+=EC_SYM_BITS;
107 _this->rng<<=EC_SYM_BITS;
108 /*Use up the remaining bits from our last symbol.*/
109 sym=_this->rem;
110 /*Read the next value from the input.*/
111 _this->rem=ec_read_byte(_this);
112 /*Take the rest of the bits we need from this new symbol.*/
113 sym=(sym<<EC_SYM_BITS|_this->rem)>>(EC_SYM_BITS-EC_CODE_EXTRA);
114 /*And subtract them from val, capped to be less than EC_CODE_TOP.*/
115 _this->val=((_this->val<<EC_SYM_BITS)+(EC_SYM_MAX&~sym))&(EC_CODE_TOP-1);
116 }
117}
118
119void ec_dec_init(ec_dec *_this,unsigned char *_buf,opus_uint32 _storage){
120 _this->buf=_buf;
121 _this->storage=_storage;
122 _this->end_offs=0;
123 _this->end_window=0;
124 _this->nend_bits=0;
125 /*This is the offset from which ec_tell() will subtract partial bits.
126 The final value after the ec_dec_normalize() call will be the same as in
127 the encoder, but we have to compensate for the bits that are added there.*/
128 _this->nbits_total=EC_CODE_BITS+1
129 -((EC_CODE_BITS-EC_CODE_EXTRA)/EC_SYM_BITS)*EC_SYM_BITS;
130 _this->offs=0;
131 _this->rng=1U<<EC_CODE_EXTRA;
132 _this->rem=ec_read_byte(_this);
133 _this->val=_this->rng-1-(_this->rem>>(EC_SYM_BITS-EC_CODE_EXTRA));
134 _this->error=0;
135 /*Normalize the interval.*/
136 ec_dec_normalize(_this);
137}
138
139unsigned ec_decode(ec_dec *_this,unsigned _ft){
140 unsigned s;
141 _this->ext=_this->rng/_ft;
142 s=(unsigned)(_this->val/_this->ext);
143 return _ft-EC_MINI(s+1,_ft);
144}
145
146unsigned ec_decode_bin(ec_dec *_this,unsigned _bits){
147 unsigned s;
148 _this->ext=_this->rng>>_bits;
149 s=(unsigned)(_this->val/_this->ext);
150 return (1U<<_bits)-EC_MINI(s+1U,1U<<_bits);
151}
152
153void ec_dec_update(ec_dec *_this,unsigned _fl,unsigned _fh,unsigned _ft){
154 opus_uint32 s;
155 s=IMUL32(_this->ext,_ft-_fh);
156 _this->val-=s;
157 _this->rng=_fl>0?IMUL32(_this->ext,_fh-_fl):_this->rng-s;
158 ec_dec_normalize(_this);
159}
160
161/*The probability of having a "one" is 1/(1<<_logp).*/
162int ec_dec_bit_logp(ec_dec *_this,unsigned _logp){
163 opus_uint32 r;
164 opus_uint32 d;
165 opus_uint32 s;
166 int ret;
167 r=_this->rng;
168 d=_this->val;
169 s=r>>_logp;
170 ret=d<s;
171 if(!ret)_this->val=d-s;
172 _this->rng=ret?s:r-s;
173 ec_dec_normalize(_this);
174 return ret;
175}
176
177int ec_dec_icdf(ec_dec *_this,const unsigned char *_icdf,unsigned _ftb){
178 opus_uint32 r;
179 opus_uint32 d;
180 opus_uint32 s;
181 opus_uint32 t;
182 int ret;
183 s=_this->rng;
184 d=_this->val;
185 r=s>>_ftb;
186 ret=-1;
187 do{
188 t=s;
189 s=IMUL32(r,_icdf[++ret]);
190 }
191 while(d<s);
192 _this->val=d-s;
193 _this->rng=t-s;
194 ec_dec_normalize(_this);
195 return ret;
196}
197
198opus_uint32 ec_dec_uint(ec_dec *_this,opus_uint32 _ft){
199 unsigned ft;
200 unsigned s;
201 int ftb;
202 /*In order to optimize EC_ILOG(), it is undefined for the value 0.*/
203 celt_assert(_ft>1);
204 _ft--;
205 ftb=EC_ILOG(_ft);
206 if(ftb>EC_UINT_BITS){
207 opus_uint32 t;
208 ftb-=EC_UINT_BITS;
209 ft=(unsigned)(_ft>>ftb)+1;
210 s=ec_decode(_this,ft);
211 ec_dec_update(_this,s,s+1,ft);
212 t=(opus_uint32)s<<ftb|ec_dec_bits(_this,ftb);
213 if(t<=_ft)return t;
214 _this->error=1;
215 return _ft;
216 }
217 else{
218 _ft++;
219 s=ec_decode(_this,(unsigned)_ft);
220 ec_dec_update(_this,s,s+1,(unsigned)_ft);
221 return s;
222 }
223}
224
225opus_uint32 ec_dec_bits(ec_dec *_this,unsigned _bits){
226 ec_window window;
227 int available;
228 opus_uint32 ret;
229 window=_this->end_window;
230 available=_this->nend_bits;
231 if((unsigned)available<_bits){
232 do{
233 window|=(ec_window)ec_read_byte_from_end(_this)<<available;
234 available+=EC_SYM_BITS;
235 }
236 while(available<=EC_WINDOW_SIZE-EC_SYM_BITS);
237 }
238 ret=(opus_uint32)window&(((opus_uint32)1<<_bits)-1U);
239 window>>=_bits;
240 available-=_bits;
241 _this->end_window=window;
242 _this->nend_bits=available;
243 _this->nbits_total+=_bits;
244 return ret;
245}
diff --git a/lib/rbcodec/codecs/libopus/celt/entdec.h b/lib/rbcodec/codecs/libopus/celt/entdec.h
new file mode 100644
index 0000000000..d8ab318730
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/entdec.h
@@ -0,0 +1,100 @@
1/* Copyright (c) 2001-2011 Timothy B. Terriberry
2 Copyright (c) 2008-2009 Xiph.Org Foundation */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#if !defined(_entdec_H)
29# define _entdec_H (1)
30# include <limits.h>
31# include "entcode.h"
32
33/*Initializes the decoder.
34 _buf: The input buffer to use.
35 Return: 0 on success, or a negative value on error.*/
36void ec_dec_init(ec_dec *_this,unsigned char *_buf,opus_uint32 _storage);
37
38/*Calculates the cumulative frequency for the next symbol.
39 This can then be fed into the probability model to determine what that
40 symbol is, and the additional frequency information required to advance to
41 the next symbol.
42 This function cannot be called more than once without a corresponding call to
43 ec_dec_update(), or decoding will not proceed correctly.
44 _ft: The total frequency of the symbols in the alphabet the next symbol was
45 encoded with.
46 Return: A cumulative frequency representing the encoded symbol.
47 If the cumulative frequency of all the symbols before the one that
48 was encoded was fl, and the cumulative frequency of all the symbols
49 up to and including the one encoded is fh, then the returned value
50 will fall in the range [fl,fh).*/
51unsigned ec_decode(ec_dec *_this,unsigned _ft);
52
53/*Equivalent to ec_decode() with _ft==1<<_bits.*/
54unsigned ec_decode_bin(ec_dec *_this,unsigned _bits);
55
56/*Advance the decoder past the next symbol using the frequency information the
57 symbol was encoded with.
58 Exactly one call to ec_decode() must have been made so that all necessary
59 intermediate calculations are performed.
60 _fl: The cumulative frequency of all symbols that come before the symbol
61 decoded.
62 _fh: The cumulative frequency of all symbols up to and including the symbol
63 decoded.
64 Together with _fl, this defines the range [_fl,_fh) in which the value
65 returned above must fall.
66 _ft: The total frequency of the symbols in the alphabet the symbol decoded
67 was encoded in.
68 This must be the same as passed to the preceding call to ec_decode().*/
69void ec_dec_update(ec_dec *_this,unsigned _fl,unsigned _fh,unsigned _ft);
70
71/* Decode a bit that has a 1/(1<<_logp) probability of being a one */
72int ec_dec_bit_logp(ec_dec *_this,unsigned _logp);
73
74/*Decodes a symbol given an "inverse" CDF table.
75 No call to ec_dec_update() is necessary after this call.
76 _icdf: The "inverse" CDF, such that symbol s falls in the range
77 [s>0?ft-_icdf[s-1]:0,ft-_icdf[s]), where ft=1<<_ftb.
78 The values must be monotonically non-increasing, and the last value
79 must be 0.
80 _ftb: The number of bits of precision in the cumulative distribution.
81 Return: The decoded symbol s.*/
82int ec_dec_icdf(ec_dec *_this,const unsigned char *_icdf,unsigned _ftb);
83
84/*Extracts a raw unsigned integer with a non-power-of-2 range from the stream.
85 The bits must have been encoded with ec_enc_uint().
86 No call to ec_dec_update() is necessary after this call.
87 _ft: The number of integers that can be decoded (one more than the max).
88 This must be at least one, and no more than 2**32-1.
89 Return: The decoded bits.*/
90opus_uint32 ec_dec_uint(ec_dec *_this,opus_uint32 _ft);
91
92/*Extracts a sequence of raw bits from the stream.
93 The bits must have been encoded with ec_enc_bits().
94 No call to ec_dec_update() is necessary after this call.
95 _ftb: The number of bits to extract.
96 This must be between 0 and 25, inclusive.
97 Return: The decoded bits.*/
98opus_uint32 ec_dec_bits(ec_dec *_this,unsigned _ftb);
99
100#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/entenc.c b/lib/rbcodec/codecs/libopus/celt/entenc.c
new file mode 100644
index 0000000000..0ec6e91fd7
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/entenc.c
@@ -0,0 +1,294 @@
1/* Copyright (c) 2001-2011 Timothy B. Terriberry
2 Copyright (c) 2008-2009 Xiph.Org Foundation */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#if defined(HAVE_CONFIG_H)
29# include "opus_config.h"
30#endif
31#include "os_support.h"
32#include "arch.h"
33#include "entenc.h"
34#include "mfrngcod.h"
35
36/*A range encoder.
37 See entdec.c and the references for implementation details \cite{Mar79,MNW98}.
38
39 @INPROCEEDINGS{Mar79,
40 author="Martin, G.N.N.",
41 title="Range encoding: an algorithm for removing redundancy from a digitised
42 message",
43 booktitle="Video \& Data Recording Conference",
44 year=1979,
45 address="Southampton",
46 month=Jul
47 }
48 @ARTICLE{MNW98,
49 author="Alistair Moffat and Radford Neal and Ian H. Witten",
50 title="Arithmetic Coding Revisited",
51 journal="{ACM} Transactions on Information Systems",
52 year=1998,
53 volume=16,
54 number=3,
55 pages="256--294",
56 month=Jul,
57 URL="http://www.stanford.edu/class/ee398/handouts/papers/Moffat98ArithmCoding.pdf"
58 }*/
59
60static int ec_write_byte(ec_enc *_this,unsigned _value){
61 if(_this->offs+_this->end_offs>=_this->storage)return -1;
62 _this->buf[_this->offs++]=(unsigned char)_value;
63 return 0;
64}
65
66static int ec_write_byte_at_end(ec_enc *_this,unsigned _value){
67 if(_this->offs+_this->end_offs>=_this->storage)return -1;
68 _this->buf[_this->storage-++(_this->end_offs)]=(unsigned char)_value;
69 return 0;
70}
71
72/*Outputs a symbol, with a carry bit.
73 If there is a potential to propagate a carry over several symbols, they are
74 buffered until it can be determined whether or not an actual carry will
75 occur.
76 If the counter for the buffered symbols overflows, then the stream becomes
77 undecodable.
78 This gives a theoretical limit of a few billion symbols in a single packet on
79 32-bit systems.
80 The alternative is to truncate the range in order to force a carry, but
81 requires similar carry tracking in the decoder, needlessly slowing it down.*/
82static void ec_enc_carry_out(ec_enc *_this,int _c){
83 if(_c!=EC_SYM_MAX){
84 /*No further carry propagation possible, flush buffer.*/
85 int carry;
86 carry=_c>>EC_SYM_BITS;
87 /*Don't output a byte on the first write.
88 This compare should be taken care of by branch-prediction thereafter.*/
89 if(_this->rem>=0)_this->error|=ec_write_byte(_this,_this->rem+carry);
90 if(_this->ext>0){
91 unsigned sym;
92 sym=(EC_SYM_MAX+carry)&EC_SYM_MAX;
93 do _this->error|=ec_write_byte(_this,sym);
94 while(--(_this->ext)>0);
95 }
96 _this->rem=_c&EC_SYM_MAX;
97 }
98 else _this->ext++;
99}
100
101static void ec_enc_normalize(ec_enc *_this){
102 /*If the range is too small, output some bits and rescale it.*/
103 while(_this->rng<=EC_CODE_BOT){
104 ec_enc_carry_out(_this,(int)(_this->val>>EC_CODE_SHIFT));
105 /*Move the next-to-high-order symbol into the high-order position.*/
106 _this->val=(_this->val<<EC_SYM_BITS)&(EC_CODE_TOP-1);
107 _this->rng<<=EC_SYM_BITS;
108 _this->nbits_total+=EC_SYM_BITS;
109 }
110}
111
112void ec_enc_init(ec_enc *_this,unsigned char *_buf,opus_uint32 _size){
113 _this->buf=_buf;
114 _this->end_offs=0;
115 _this->end_window=0;
116 _this->nend_bits=0;
117 /*This is the offset from which ec_tell() will subtract partial bits.*/
118 _this->nbits_total=EC_CODE_BITS+1;
119 _this->offs=0;
120 _this->rng=EC_CODE_TOP;
121 _this->rem=-1;
122 _this->val=0;
123 _this->ext=0;
124 _this->storage=_size;
125 _this->error=0;
126}
127
128void ec_encode(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _ft){
129 opus_uint32 r;
130 r=_this->rng/_ft;
131 if(_fl>0){
132 _this->val+=_this->rng-IMUL32(r,(_ft-_fl));
133 _this->rng=IMUL32(r,(_fh-_fl));
134 }
135 else _this->rng-=IMUL32(r,(_ft-_fh));
136 ec_enc_normalize(_this);
137}
138
139void ec_encode_bin(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _bits){
140 opus_uint32 r;
141 r=_this->rng>>_bits;
142 if(_fl>0){
143 _this->val+=_this->rng-IMUL32(r,((1U<<_bits)-_fl));
144 _this->rng=IMUL32(r,(_fh-_fl));
145 }
146 else _this->rng-=IMUL32(r,((1U<<_bits)-_fh));
147 ec_enc_normalize(_this);
148}
149
150/*The probability of having a "one" is 1/(1<<_logp).*/
151void ec_enc_bit_logp(ec_enc *_this,int _val,unsigned _logp){
152 opus_uint32 r;
153 opus_uint32 s;
154 opus_uint32 l;
155 r=_this->rng;
156 l=_this->val;
157 s=r>>_logp;
158 r-=s;
159 if(_val)_this->val=l+r;
160 _this->rng=_val?s:r;
161 ec_enc_normalize(_this);
162}
163
164void ec_enc_icdf(ec_enc *_this,int _s,const unsigned char *_icdf,unsigned _ftb){
165 opus_uint32 r;
166 r=_this->rng>>_ftb;
167 if(_s>0){
168 _this->val+=_this->rng-IMUL32(r,_icdf[_s-1]);
169 _this->rng=IMUL32(r,_icdf[_s-1]-_icdf[_s]);
170 }
171 else _this->rng-=IMUL32(r,_icdf[_s]);
172 ec_enc_normalize(_this);
173}
174
175void ec_enc_uint(ec_enc *_this,opus_uint32 _fl,opus_uint32 _ft){
176 unsigned ft;
177 unsigned fl;
178 int ftb;
179 /*In order to optimize EC_ILOG(), it is undefined for the value 0.*/
180 celt_assert(_ft>1);
181 _ft--;
182 ftb=EC_ILOG(_ft);
183 if(ftb>EC_UINT_BITS){
184 ftb-=EC_UINT_BITS;
185 ft=(_ft>>ftb)+1;
186 fl=(unsigned)(_fl>>ftb);
187 ec_encode(_this,fl,fl+1,ft);
188 ec_enc_bits(_this,_fl&(((opus_uint32)1<<ftb)-1U),ftb);
189 }
190 else ec_encode(_this,_fl,_fl+1,_ft+1);
191}
192
193void ec_enc_bits(ec_enc *_this,opus_uint32 _fl,unsigned _bits){
194 ec_window window;
195 int used;
196 window=_this->end_window;
197 used=_this->nend_bits;
198 celt_assert(_bits>0);
199 if(used+_bits>EC_WINDOW_SIZE){
200 do{
201 _this->error|=ec_write_byte_at_end(_this,(unsigned)window&EC_SYM_MAX);
202 window>>=EC_SYM_BITS;
203 used-=EC_SYM_BITS;
204 }
205 while(used>=EC_SYM_BITS);
206 }
207 window|=(ec_window)_fl<<used;
208 used+=_bits;
209 _this->end_window=window;
210 _this->nend_bits=used;
211 _this->nbits_total+=_bits;
212}
213
214void ec_enc_patch_initial_bits(ec_enc *_this,unsigned _val,unsigned _nbits){
215 int shift;
216 unsigned mask;
217 celt_assert(_nbits<=EC_SYM_BITS);
218 shift=EC_SYM_BITS-_nbits;
219 mask=((1<<_nbits)-1)<<shift;
220 if(_this->offs>0){
221 /*The first byte has been finalized.*/
222 _this->buf[0]=(unsigned char)((_this->buf[0]&~mask)|_val<<shift);
223 }
224 else if(_this->rem>=0){
225 /*The first byte is still awaiting carry propagation.*/
226 _this->rem=(_this->rem&~mask)|_val<<shift;
227 }
228 else if(_this->rng<=(EC_CODE_TOP>>_nbits)){
229 /*The renormalization loop has never been run.*/
230 _this->val=(_this->val&~((opus_uint32)mask<<EC_CODE_SHIFT))|
231 (opus_uint32)_val<<(EC_CODE_SHIFT+shift);
232 }
233 /*The encoder hasn't even encoded _nbits of data yet.*/
234 else _this->error=-1;
235}
236
237void ec_enc_shrink(ec_enc *_this,opus_uint32 _size){
238 celt_assert(_this->offs+_this->end_offs<=_size);
239 OPUS_MOVE(_this->buf+_size-_this->end_offs,
240 _this->buf+_this->storage-_this->end_offs,_this->end_offs);
241 _this->storage=_size;
242}
243
244void ec_enc_done(ec_enc *_this){
245 ec_window window;
246 int used;
247 opus_uint32 msk;
248 opus_uint32 end;
249 int l;
250 /*We output the minimum number of bits that ensures that the symbols encoded
251 thus far will be decoded correctly regardless of the bits that follow.*/
252 l=EC_CODE_BITS-EC_ILOG(_this->rng);
253 msk=(EC_CODE_TOP-1)>>l;
254 end=(_this->val+msk)&~msk;
255 if((end|msk)>=_this->val+_this->rng){
256 l++;
257 msk>>=1;
258 end=(_this->val+msk)&~msk;
259 }
260 while(l>0){
261 ec_enc_carry_out(_this,(int)(end>>EC_CODE_SHIFT));
262 end=(end<<EC_SYM_BITS)&(EC_CODE_TOP-1);
263 l-=EC_SYM_BITS;
264 }
265 /*If we have a buffered byte flush it into the output buffer.*/
266 if(_this->rem>=0||_this->ext>0)ec_enc_carry_out(_this,0);
267 /*If we have buffered extra bits, flush them as well.*/
268 window=_this->end_window;
269 used=_this->nend_bits;
270 while(used>=EC_SYM_BITS){
271 _this->error|=ec_write_byte_at_end(_this,(unsigned)window&EC_SYM_MAX);
272 window>>=EC_SYM_BITS;
273 used-=EC_SYM_BITS;
274 }
275 /*Clear any excess space and add any remaining extra bits to the last byte.*/
276 if(!_this->error){
277 OPUS_CLEAR(_this->buf+_this->offs,
278 _this->storage-_this->offs-_this->end_offs);
279 if(used>0){
280 /*If there's no range coder data at all, give up.*/
281 if(_this->end_offs>=_this->storage)_this->error=-1;
282 else{
283 l=-l;
284 /*If we've busted, don't add too many extra bits to the last byte; it
285 would corrupt the range coder data, and that's more important.*/
286 if(_this->offs+_this->end_offs>=_this->storage&&l<used){
287 window&=(1<<l)-1;
288 _this->error=-1;
289 }
290 _this->buf[_this->storage-_this->end_offs-1]|=(unsigned char)window;
291 }
292 }
293 }
294}
diff --git a/lib/rbcodec/codecs/libopus/celt/entenc.h b/lib/rbcodec/codecs/libopus/celt/entenc.h
new file mode 100644
index 0000000000..796bc4d572
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/entenc.h
@@ -0,0 +1,110 @@
1/* Copyright (c) 2001-2011 Timothy B. Terriberry
2 Copyright (c) 2008-2009 Xiph.Org Foundation */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#if !defined(_entenc_H)
29# define _entenc_H (1)
30# include <stddef.h>
31# include "entcode.h"
32
33/*Initializes the encoder.
34 _buf: The buffer to store output bytes in.
35 _size: The size of the buffer, in chars.*/
36void ec_enc_init(ec_enc *_this,unsigned char *_buf,opus_uint32 _size);
37/*Encodes a symbol given its frequency information.
38 The frequency information must be discernable by the decoder, assuming it
39 has read only the previous symbols from the stream.
40 It is allowable to change the frequency information, or even the entire
41 source alphabet, so long as the decoder can tell from the context of the
42 previously encoded information that it is supposed to do so as well.
43 _fl: The cumulative frequency of all symbols that come before the one to be
44 encoded.
45 _fh: The cumulative frequency of all symbols up to and including the one to
46 be encoded.
47 Together with _fl, this defines the range [_fl,_fh) in which the
48 decoded value will fall.
49 _ft: The sum of the frequencies of all the symbols*/
50void ec_encode(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _ft);
51
52/*Equivalent to ec_encode() with _ft==1<<_bits.*/
53void ec_encode_bin(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _bits);
54
55/* Encode a bit that has a 1/(1<<_logp) probability of being a one */
56void ec_enc_bit_logp(ec_enc *_this,int _val,unsigned _logp);
57
58/*Encodes a symbol given an "inverse" CDF table.
59 _s: The index of the symbol to encode.
60 _icdf: The "inverse" CDF, such that symbol _s falls in the range
61 [_s>0?ft-_icdf[_s-1]:0,ft-_icdf[_s]), where ft=1<<_ftb.
62 The values must be monotonically non-increasing, and the last value
63 must be 0.
64 _ftb: The number of bits of precision in the cumulative distribution.*/
65void ec_enc_icdf(ec_enc *_this,int _s,const unsigned char *_icdf,unsigned _ftb);
66
67/*Encodes a raw unsigned integer in the stream.
68 _fl: The integer to encode.
69 _ft: The number of integers that can be encoded (one more than the max).
70 This must be at least one, and no more than 2**32-1.*/
71void ec_enc_uint(ec_enc *_this,opus_uint32 _fl,opus_uint32 _ft);
72
73/*Encodes a sequence of raw bits in the stream.
74 _fl: The bits to encode.
75 _ftb: The number of bits to encode.
76 This must be between 1 and 25, inclusive.*/
77void ec_enc_bits(ec_enc *_this,opus_uint32 _fl,unsigned _ftb);
78
79/*Overwrites a few bits at the very start of an existing stream, after they
80 have already been encoded.
81 This makes it possible to have a few flags up front, where it is easy for
82 decoders to access them without parsing the whole stream, even if their
83 values are not determined until late in the encoding process, without having
84 to buffer all the intermediate symbols in the encoder.
85 In order for this to work, at least _nbits bits must have already been
86 encoded using probabilities that are an exact power of two.
87 The encoder can verify the number of encoded bits is sufficient, but cannot
88 check this latter condition.
89 _val: The bits to encode (in the least _nbits significant bits).
90 They will be decoded in order from most-significant to least.
91 _nbits: The number of bits to overwrite.
92 This must be no more than 8.*/
93void ec_enc_patch_initial_bits(ec_enc *_this,unsigned _val,unsigned _nbits);
94
95/*Compacts the data to fit in the target size.
96 This moves up the raw bits at the end of the current buffer so they are at
97 the end of the new buffer size.
98 The caller must ensure that the amount of data that's already been written
99 will fit in the new size.
100 _size: The number of bytes in the new buffer.
101 This must be large enough to contain the bits already written, and
102 must be no larger than the existing size.*/
103void ec_enc_shrink(ec_enc *_this,opus_uint32 _size);
104
105/*Indicates that there are no more symbols to encode.
106 All reamining output bytes are flushed to the output buffer.
107 ec_enc_init() must be called before the encoder can be used again.*/
108void ec_enc_done(ec_enc *_this);
109
110#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/fixed_generic.h b/lib/rbcodec/codecs/libopus/celt/fixed_generic.h
new file mode 100644
index 0000000000..71e28d62a8
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/fixed_generic.h
@@ -0,0 +1,129 @@
1/* Copyright (C) 2007-2009 Xiph.Org Foundation
2 Copyright (C) 2003-2008 Jean-Marc Valin
3 Copyright (C) 2007-2008 CSIRO */
4/**
5 @file fixed_generic.h
6 @brief Generic fixed-point operations
7*/
8/*
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions
11 are met:
12
13 - Redistributions of source code must retain the above copyright
14 notice, this list of conditions and the following disclaimer.
15
16 - Redistributions in binary form must reproduce the above copyright
17 notice, this list of conditions and the following disclaimer in the
18 documentation and/or other materials provided with the distribution.
19
20 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
24 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31*/
32
33#ifndef FIXED_GENERIC_H
34#define FIXED_GENERIC_H
35
36/** Multiply a 16-bit signed value by a 16-bit unsigned value. The result is a 32-bit signed value */
37#define MULT16_16SU(a,b) ((opus_val32)(opus_val16)(a)*(opus_val32)(opus_uint16)(b))
38
39/** 16x32 multiplication, followed by a 16-bit shift right. Results fits in 32 bits */
40#define MULT16_32_Q16(a,b) ADD32(MULT16_16((a),SHR((b),16)), SHR(MULT16_16SU((a),((b)&0x0000ffff)),16))
41
42/** 16x32 multiplication, followed by a 16-bit shift right (round-to-nearest). Results fits in 32 bits */
43#define MULT16_32_P16(a,b) ADD32(MULT16_16((a),SHR((b),16)), PSHR(MULT16_16((a),((b)&0x0000ffff)),16))
44
45/** 16x32 multiplication, followed by a 15-bit shift right. Results fits in 32 bits */
46#define MULT16_32_Q15(a,b) ADD32(SHL(MULT16_16((a),SHR((b),16)),1), SHR(MULT16_16SU((a),((b)&0x0000ffff)),15))
47
48/** 32x32 multiplication, followed by a 31-bit shift right. Results fits in 32 bits */
49#define MULT32_32_Q31(a,b) ADD32(ADD32(SHL(MULT16_16(SHR((a),16),SHR((b),16)),1), SHR(MULT16_16SU(SHR((a),16),((b)&0x0000ffff)),15)), SHR(MULT16_16SU(SHR((b),16),((a)&0x0000ffff)),15))
50
51/** Compile-time conversion of float constant to 16-bit value */
52#define QCONST16(x,bits) ((opus_val16)(.5+(x)*(((opus_val32)1)<<(bits))))
53
54/** Compile-time conversion of float constant to 32-bit value */
55#define QCONST32(x,bits) ((opus_val32)(.5+(x)*(((opus_val32)1)<<(bits))))
56
57/** Negate a 16-bit value */
58#define NEG16(x) (-(x))
59/** Negate a 32-bit value */
60#define NEG32(x) (-(x))
61
62/** Change a 32-bit value into a 16-bit value. The value is assumed to fit in 16-bit, otherwise the result is undefined */
63#define EXTRACT16(x) ((opus_val16)(x))
64/** Change a 16-bit value into a 32-bit value */
65#define EXTEND32(x) ((opus_val32)(x))
66
67/** Arithmetic shift-right of a 16-bit value */
68#define SHR16(a,shift) ((a) >> (shift))
69/** Arithmetic shift-left of a 16-bit value */
70#define SHL16(a,shift) ((opus_int16)((opus_uint16)(a)<<(shift)))
71/** Arithmetic shift-right of a 32-bit value */
72#define SHR32(a,shift) ((a) >> (shift))
73/** Arithmetic shift-left of a 32-bit value */
74#define SHL32(a,shift) ((opus_int32)((opus_uint32)(a)<<(shift)))
75
76/** 32-bit arithmetic shift right with rounding-to-nearest instead of rounding down */
77#define PSHR32(a,shift) (SHR32((a)+((EXTEND32(1)<<((shift))>>1)),shift))
78/** 32-bit arithmetic shift right where the argument can be negative */
79#define VSHR32(a, shift) (((shift)>0) ? SHR32(a, shift) : SHL32(a, -(shift)))
80
81/** "RAW" macros, should not be used outside of this header file */
82#define SHR(a,shift) ((a) >> (shift))
83#define SHL(a,shift) SHL32(a,shift)
84#define PSHR(a,shift) (SHR((a)+((EXTEND32(1)<<((shift))>>1)),shift))
85#define SATURATE(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x)))
86
87/** Shift by a and round-to-neareast 32-bit value. Result is a 16-bit value */
88#define ROUND16(x,a) (EXTRACT16(PSHR32((x),(a))))
89/** Divide by two */
90#define HALF16(x) (SHR16(x,1))
91#define HALF32(x) (SHR32(x,1))
92
93/** Add two 16-bit values */
94#define ADD16(a,b) ((opus_val16)((opus_val16)(a)+(opus_val16)(b)))
95/** Subtract two 16-bit values */
96#define SUB16(a,b) ((opus_val16)(a)-(opus_val16)(b))
97/** Add two 32-bit values */
98#define ADD32(a,b) ((opus_val32)(a)+(opus_val32)(b))
99/** Subtract two 32-bit values */
100#define SUB32(a,b) ((opus_val32)(a)-(opus_val32)(b))
101
102/** 16x16 multiplication where the result fits in 16 bits */
103#define MULT16_16_16(a,b) ((((opus_val16)(a))*((opus_val16)(b))))
104
105/* (opus_val32)(opus_val16) gives TI compiler a hint that it's 16x16->32 multiply */
106/** 16x16 multiplication where the result fits in 32 bits */
107#define MULT16_16(a,b) (((opus_val32)(opus_val16)(a))*((opus_val32)(opus_val16)(b)))
108
109/** 16x16 multiply-add where the result fits in 32 bits */
110#define MAC16_16(c,a,b) (ADD32((c),MULT16_16((a),(b))))
111/** 16x32 multiply-add, followed by a 15-bit shift right. Results fits in 32 bits */
112#define MAC16_32_Q15(c,a,b) ADD32(c,ADD32(MULT16_16((a),SHR((b),15)), SHR(MULT16_16((a),((b)&0x00007fff)),15)))
113
114#define MULT16_16_Q11_32(a,b) (SHR(MULT16_16((a),(b)),11))
115#define MULT16_16_Q13(a,b) (SHR(MULT16_16((a),(b)),13))
116#define MULT16_16_Q14(a,b) (SHR(MULT16_16((a),(b)),14))
117#define MULT16_16_Q15(a,b) (SHR(MULT16_16((a),(b)),15))
118
119#define MULT16_16_P13(a,b) (SHR(ADD32(4096,MULT16_16((a),(b))),13))
120#define MULT16_16_P14(a,b) (SHR(ADD32(8192,MULT16_16((a),(b))),14))
121#define MULT16_16_P15(a,b) (SHR(ADD32(16384,MULT16_16((a),(b))),15))
122
123/** Divide a 32-bit value by a 16-bit value. Result fits in 16 bits */
124#define DIV32_16(a,b) ((opus_val16)(((opus_val32)(a))/((opus_val16)(b))))
125
126/** Divide a 32-bit value by a 32-bit value. Result fits in 32 bits */
127#define DIV32(a,b) (((opus_val32)(a))/((opus_val32)(b)))
128
129#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/float_cast.h b/lib/rbcodec/codecs/libopus/celt/float_cast.h
new file mode 100644
index 0000000000..5ded291599
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/float_cast.h
@@ -0,0 +1,140 @@
1/* Copyright (C) 2001 Erik de Castro Lopo <erikd AT mega-nerd DOT com> */
2/*
3 Redistribution and use in source and binary forms, with or without
4 modification, are permitted provided that the following conditions
5 are met:
6
7 - Redistributions of source code must retain the above copyright
8 notice, this list of conditions and the following disclaimer.
9
10 - Redistributions in binary form must reproduce the above copyright
11 notice, this list of conditions and the following disclaimer in the
12 documentation and/or other materials provided with the distribution.
13
14 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
18 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
22 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25*/
26
27/* Version 1.1 */
28
29#ifndef FLOAT_CAST_H
30#define FLOAT_CAST_H
31
32
33#include "arch.h"
34
35/*============================================================================
36** On Intel Pentium processors (especially PIII and probably P4), converting
37** from float to int is very slow. To meet the C specs, the code produced by
38** most C compilers targeting Pentium needs to change the FPU rounding mode
39** before the float to int conversion is performed.
40**
41** Changing the FPU rounding mode causes the FPU pipeline to be flushed. It
42** is this flushing of the pipeline which is so slow.
43**
44** Fortunately the ISO C99 specifications define the functions lrint, lrintf,
45** llrint and llrintf which fix this problem as a side effect.
46**
47** On Unix-like systems, the configure process should have detected the
48** presence of these functions. If they weren't found we have to replace them
49** here with a standard C cast.
50*/
51
52/*
53** The C99 prototypes for lrint and lrintf are as follows:
54**
55** long int lrintf (float x) ;
56** long int lrint (double x) ;
57*/
58
59/* The presence of the required functions are detected during the configure
60** process and the values HAVE_LRINT and HAVE_LRINTF are set accordingly in
61** the config.h file.
62*/
63
64#if (HAVE_LRINTF)
65
66/* These defines enable functionality introduced with the 1999 ISO C
67** standard. They must be defined before the inclusion of math.h to
68** engage them. If optimisation is enabled, these functions will be
69** inlined. With optimisation switched off, you have to link in the
70** maths library using -lm.
71*/
72
73#define _ISOC9X_SOURCE 1
74#define _ISOC99_SOURCE 1
75
76#define __USE_ISOC9X 1
77#define __USE_ISOC99 1
78
79#include <math.h>
80#define float2int(x) lrintf(x)
81
82#elif (defined(HAVE_LRINT))
83
84#define _ISOC9X_SOURCE 1
85#define _ISOC99_SOURCE 1
86
87#define __USE_ISOC9X 1
88#define __USE_ISOC99 1
89
90#include <math.h>
91#define float2int(x) lrint(x)
92
93#elif (defined(_MSC_VER) && _MSC_VER >= 1400) && (defined (WIN64) || defined (_WIN64))
94 #include <xmmintrin.h>
95
96 __inline long int float2int(float value)
97 {
98 return _mm_cvtss_si32(_mm_load_ss(&value));
99 }
100#elif (defined(_MSC_VER) && _MSC_VER >= 1400) && (defined (WIN32) || defined (_WIN32))
101 #include <math.h>
102
103 /* Win32 doesn't seem to have these functions.
104 ** Therefore implement inline versions of these functions here.
105 */
106
107 __inline long int
108 float2int (float flt)
109 { int intgr;
110
111 _asm
112 { fld flt
113 fistp intgr
114 } ;
115
116 return intgr ;
117 }
118
119#else
120
121#if (defined(__GNUC__) && defined(__STDC__) && __STDC__ && __STDC_VERSION__ >= 199901L)
122 /* supported by gcc in C99 mode, but not by all other compilers */
123 #warning "Don't have the functions lrint() and lrintf ()."
124 #warning "Replacing these functions with a standard C cast."
125#endif /* __STDC_VERSION__ >= 199901L */
126 #include <math.h>
127 #define float2int(flt) ((int)(floor(.5+flt)))
128#endif
129
130#ifndef DISABLE_FLOAT_API
131static inline opus_int16 FLOAT2INT16(float x)
132{
133 x = x*CELT_SIG_SCALE;
134 x = MAX32(x, -32768);
135 x = MIN32(x, 32767);
136 return (opus_int16)float2int(x);
137}
138#endif /* DISABLE_FLOAT_API */
139
140#endif /* FLOAT_CAST_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/kiss_fft.c b/lib/rbcodec/codecs/libopus/celt/kiss_fft.c
new file mode 100644
index 0000000000..3ba075ab0c
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/kiss_fft.c
@@ -0,0 +1,722 @@
1/*Copyright (c) 2003-2004, Mark Borgerding
2 Lots of modifications by Jean-Marc Valin
3 Copyright (c) 2005-2007, Xiph.Org Foundation
4 Copyright (c) 2008, Xiph.Org Foundation, CSIRO
5
6 All rights reserved.
7
8 Redistribution and use in source and binary forms, with or without
9 modification, are permitted provided that the following conditions are met:
10
11 * Redistributions of source code must retain the above copyright notice,
12 this list of conditions and the following disclaimer.
13 * Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.*/
28
29/* This code is originally from Mark Borgerding's KISS-FFT but has been
30 heavily modified to better suit Opus */
31
32#ifndef SKIP_CONFIG_H
33# ifdef HAVE_CONFIG_H
34# include "opus_config.h"
35# endif
36#endif
37
38#include "_kiss_fft_guts.h"
39#include "arch.h"
40#include "os_support.h"
41#include "mathops.h"
42#include "stack_alloc.h"
43#include "os_support.h"
44
45/* The guts header contains all the multiplication and addition macros that are defined for
46 complex numbers. It also delares the kf_ internal functions.
47*/
48
49static void kf_bfly2(
50 kiss_fft_cpx * Fout,
51 const size_t fstride,
52 const kiss_fft_state *st,
53 int m,
54 int N,
55 int mm
56 )
57{
58 kiss_fft_cpx * Fout2;
59 const kiss_twiddle_cpx * tw1;
60 int i,j;
61 kiss_fft_cpx * Fout_beg = Fout;
62 for (i=0;i<N;i++)
63 {
64 Fout = Fout_beg + i*mm;
65 Fout2 = Fout + m;
66 tw1 = st->twiddles;
67 for(j=0;j<m;j++)
68 {
69 kiss_fft_cpx t;
70 Fout->r = SHR32(Fout->r, 1);Fout->i = SHR32(Fout->i, 1);
71 Fout2->r = SHR32(Fout2->r, 1);Fout2->i = SHR32(Fout2->i, 1);
72 C_MUL (t, *Fout2 , *tw1);
73 tw1 += fstride;
74 C_SUB( *Fout2 , *Fout , t );
75 C_ADDTO( *Fout , t );
76 ++Fout2;
77 ++Fout;
78 }
79 }
80}
81
82static void ki_bfly2(
83 kiss_fft_cpx * Fout,
84 const size_t fstride,
85 const kiss_fft_state *st,
86 int m,
87 int N,
88 int mm
89 )
90{
91 kiss_fft_cpx * Fout2;
92 const kiss_twiddle_cpx * tw1;
93 kiss_fft_cpx t;
94 int i,j;
95 kiss_fft_cpx * Fout_beg = Fout;
96 for (i=0;i<N;i++)
97 {
98 Fout = Fout_beg + i*mm;
99 Fout2 = Fout + m;
100 tw1 = st->twiddles;
101 for(j=0;j<m;j++)
102 {
103 C_MULC (t, *Fout2 , *tw1);
104 tw1 += fstride;
105 C_SUB( *Fout2 , *Fout , t );
106 C_ADDTO( *Fout , t );
107 ++Fout2;
108 ++Fout;
109 }
110 }
111}
112
113static void kf_bfly4(
114 kiss_fft_cpx * Fout,
115 const size_t fstride,
116 const kiss_fft_state *st,
117 int m,
118 int N,
119 int mm
120 )
121{
122 const kiss_twiddle_cpx *tw1,*tw2,*tw3;
123 kiss_fft_cpx scratch[6];
124 const size_t m2=2*m;
125 const size_t m3=3*m;
126 int i, j;
127
128 kiss_fft_cpx * Fout_beg = Fout;
129 for (i=0;i<N;i++)
130 {
131 Fout = Fout_beg + i*mm;
132 tw3 = tw2 = tw1 = st->twiddles;
133 for (j=0;j<m;j++)
134 {
135 C_MUL4(scratch[0],Fout[m] , *tw1 );
136 C_MUL4(scratch[1],Fout[m2] , *tw2 );
137 C_MUL4(scratch[2],Fout[m3] , *tw3 );
138
139 Fout->r = PSHR32(Fout->r, 2);
140 Fout->i = PSHR32(Fout->i, 2);
141 C_SUB( scratch[5] , *Fout, scratch[1] );
142 C_ADDTO(*Fout, scratch[1]);
143 C_ADD( scratch[3] , scratch[0] , scratch[2] );
144 C_SUB( scratch[4] , scratch[0] , scratch[2] );
145 Fout[m2].r = PSHR32(Fout[m2].r, 2);
146 Fout[m2].i = PSHR32(Fout[m2].i, 2);
147 C_SUB( Fout[m2], *Fout, scratch[3] );
148 tw1 += fstride;
149 tw2 += fstride*2;
150 tw3 += fstride*3;
151 C_ADDTO( *Fout , scratch[3] );
152
153 Fout[m].r = scratch[5].r + scratch[4].i;
154 Fout[m].i = scratch[5].i - scratch[4].r;
155 Fout[m3].r = scratch[5].r - scratch[4].i;
156 Fout[m3].i = scratch[5].i + scratch[4].r;
157 ++Fout;
158 }
159 }
160}
161
162static void ki_bfly4(
163 kiss_fft_cpx * Fout,
164 const size_t fstride,
165 const kiss_fft_state *st,
166 int m,
167 int N,
168 int mm
169 )
170{
171 const kiss_twiddle_cpx *tw1,*tw2,*tw3;
172 kiss_fft_cpx scratch[6];
173 const size_t m2=2*m;
174 const size_t m3=3*m;
175 int i, j;
176
177 kiss_fft_cpx * Fout_beg = Fout;
178 for (i=0;i<N;i++)
179 {
180 Fout = Fout_beg + i*mm;
181 tw3 = tw2 = tw1 = st->twiddles;
182 for (j=0;j<m;j++)
183 {
184 C_MULC(scratch[0],Fout[m] , *tw1 );
185 C_MULC(scratch[1],Fout[m2] , *tw2 );
186 C_MULC(scratch[2],Fout[m3] , *tw3 );
187
188 C_SUB( scratch[5] , *Fout, scratch[1] );
189 C_ADDTO(*Fout, scratch[1]);
190 C_ADD( scratch[3] , scratch[0] , scratch[2] );
191 C_SUB( scratch[4] , scratch[0] , scratch[2] );
192 C_SUB( Fout[m2], *Fout, scratch[3] );
193 tw1 += fstride;
194 tw2 += fstride*2;
195 tw3 += fstride*3;
196 C_ADDTO( *Fout , scratch[3] );
197
198 Fout[m].r = scratch[5].r - scratch[4].i;
199 Fout[m].i = scratch[5].i + scratch[4].r;
200 Fout[m3].r = scratch[5].r + scratch[4].i;
201 Fout[m3].i = scratch[5].i - scratch[4].r;
202 ++Fout;
203 }
204 }
205}
206
207#ifndef RADIX_TWO_ONLY
208
209static void kf_bfly3(
210 kiss_fft_cpx * Fout,
211 const size_t fstride,
212 const kiss_fft_state *st,
213 int m,
214 int N,
215 int mm
216 )
217{
218 int i;
219 size_t k;
220 const size_t m2 = 2*m;
221 const kiss_twiddle_cpx *tw1,*tw2;
222 kiss_fft_cpx scratch[5];
223 kiss_twiddle_cpx epi3;
224
225 kiss_fft_cpx * Fout_beg = Fout;
226 epi3 = st->twiddles[fstride*m];
227 for (i=0;i<N;i++)
228 {
229 Fout = Fout_beg + i*mm;
230 tw1=tw2=st->twiddles;
231 k=m;
232 do {
233 C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3);
234
235 C_MUL(scratch[1],Fout[m] , *tw1);
236 C_MUL(scratch[2],Fout[m2] , *tw2);
237
238 C_ADD(scratch[3],scratch[1],scratch[2]);
239 C_SUB(scratch[0],scratch[1],scratch[2]);
240 tw1 += fstride;
241 tw2 += fstride*2;
242
243 Fout[m].r = Fout->r - HALF_OF(scratch[3].r);
244 Fout[m].i = Fout->i - HALF_OF(scratch[3].i);
245
246 C_MULBYSCALAR( scratch[0] , epi3.i );
247
248 C_ADDTO(*Fout,scratch[3]);
249
250 Fout[m2].r = Fout[m].r + scratch[0].i;
251 Fout[m2].i = Fout[m].i - scratch[0].r;
252
253 Fout[m].r -= scratch[0].i;
254 Fout[m].i += scratch[0].r;
255
256 ++Fout;
257 } while(--k);
258 }
259}
260
261static void ki_bfly3(
262 kiss_fft_cpx * Fout,
263 const size_t fstride,
264 const kiss_fft_state *st,
265 int m,
266 int N,
267 int mm
268 )
269{
270 int i, k;
271 const size_t m2 = 2*m;
272 const kiss_twiddle_cpx *tw1,*tw2;
273 kiss_fft_cpx scratch[5];
274 kiss_twiddle_cpx epi3;
275
276 kiss_fft_cpx * Fout_beg = Fout;
277 epi3 = st->twiddles[fstride*m];
278 for (i=0;i<N;i++)
279 {
280 Fout = Fout_beg + i*mm;
281 tw1=tw2=st->twiddles;
282 k=m;
283 do{
284
285 C_MULC(scratch[1],Fout[m] , *tw1);
286 C_MULC(scratch[2],Fout[m2] , *tw2);
287
288 C_ADD(scratch[3],scratch[1],scratch[2]);
289 C_SUB(scratch[0],scratch[1],scratch[2]);
290 tw1 += fstride;
291 tw2 += fstride*2;
292
293 Fout[m].r = Fout->r - HALF_OF(scratch[3].r);
294 Fout[m].i = Fout->i - HALF_OF(scratch[3].i);
295
296 C_MULBYSCALAR( scratch[0] , -epi3.i );
297
298 C_ADDTO(*Fout,scratch[3]);
299
300 Fout[m2].r = Fout[m].r + scratch[0].i;
301 Fout[m2].i = Fout[m].i - scratch[0].r;
302
303 Fout[m].r -= scratch[0].i;
304 Fout[m].i += scratch[0].r;
305
306 ++Fout;
307 }while(--k);
308 }
309}
310
311static void kf_bfly5(
312 kiss_fft_cpx * Fout,
313 const size_t fstride,
314 const kiss_fft_state *st,
315 int m,
316 int N,
317 int mm
318 )
319{
320 kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
321 int i, u;
322 kiss_fft_cpx scratch[13];
323 const kiss_twiddle_cpx * twiddles = st->twiddles;
324 const kiss_twiddle_cpx *tw;
325 kiss_twiddle_cpx ya,yb;
326 kiss_fft_cpx * Fout_beg = Fout;
327
328 ya = twiddles[fstride*m];
329 yb = twiddles[fstride*2*m];
330 tw=st->twiddles;
331
332 for (i=0;i<N;i++)
333 {
334 Fout = Fout_beg + i*mm;
335 Fout0=Fout;
336 Fout1=Fout0+m;
337 Fout2=Fout0+2*m;
338 Fout3=Fout0+3*m;
339 Fout4=Fout0+4*m;
340
341 for ( u=0; u<m; ++u ) {
342 C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
343 scratch[0] = *Fout0;
344
345 C_MUL(scratch[1] ,*Fout1, tw[u*fstride]);
346 C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]);
347 C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]);
348 C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]);
349
350 C_ADD( scratch[7],scratch[1],scratch[4]);
351 C_SUB( scratch[10],scratch[1],scratch[4]);
352 C_ADD( scratch[8],scratch[2],scratch[3]);
353 C_SUB( scratch[9],scratch[2],scratch[3]);
354
355 Fout0->r += scratch[7].r + scratch[8].r;
356 Fout0->i += scratch[7].i + scratch[8].i;
357
358 scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r);
359 scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r);
360
361 scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i);
362 scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i);
363
364 C_SUB(*Fout1,scratch[5],scratch[6]);
365 C_ADD(*Fout4,scratch[5],scratch[6]);
366
367 scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r);
368 scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r);
369 scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i);
370 scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i);
371
372 C_ADD(*Fout2,scratch[11],scratch[12]);
373 C_SUB(*Fout3,scratch[11],scratch[12]);
374
375 ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4;
376 }
377 }
378}
379
380static void ki_bfly5(
381 kiss_fft_cpx * Fout,
382 const size_t fstride,
383 const kiss_fft_state *st,
384 int m,
385 int N,
386 int mm
387 )
388{
389 kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
390 int i, u;
391 kiss_fft_cpx scratch[13];
392 const kiss_twiddle_cpx * twiddles = st->twiddles;
393 const kiss_twiddle_cpx *tw;
394 kiss_twiddle_cpx ya,yb;
395 kiss_fft_cpx * Fout_beg = Fout;
396
397 ya = twiddles[fstride*m];
398 yb = twiddles[fstride*2*m];
399 tw=st->twiddles;
400
401 for (i=0;i<N;i++)
402 {
403 Fout = Fout_beg + i*mm;
404 Fout0=Fout;
405 Fout1=Fout0+m;
406 Fout2=Fout0+2*m;
407 Fout3=Fout0+3*m;
408 Fout4=Fout0+4*m;
409
410 for ( u=0; u<m; ++u ) {
411 scratch[0] = *Fout0;
412
413 C_MULC(scratch[1] ,*Fout1, tw[u*fstride]);
414 C_MULC(scratch[2] ,*Fout2, tw[2*u*fstride]);
415 C_MULC(scratch[3] ,*Fout3, tw[3*u*fstride]);
416 C_MULC(scratch[4] ,*Fout4, tw[4*u*fstride]);
417
418 C_ADD( scratch[7],scratch[1],scratch[4]);
419 C_SUB( scratch[10],scratch[1],scratch[4]);
420 C_ADD( scratch[8],scratch[2],scratch[3]);
421 C_SUB( scratch[9],scratch[2],scratch[3]);
422
423 Fout0->r += scratch[7].r + scratch[8].r;
424 Fout0->i += scratch[7].i + scratch[8].i;
425
426 scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r);
427 scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r);
428
429 scratch[6].r = -S_MUL(scratch[10].i,ya.i) - S_MUL(scratch[9].i,yb.i);
430 scratch[6].i = S_MUL(scratch[10].r,ya.i) + S_MUL(scratch[9].r,yb.i);
431
432 C_SUB(*Fout1,scratch[5],scratch[6]);
433 C_ADD(*Fout4,scratch[5],scratch[6]);
434
435 scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r);
436 scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r);
437 scratch[12].r = S_MUL(scratch[10].i,yb.i) - S_MUL(scratch[9].i,ya.i);
438 scratch[12].i = -S_MUL(scratch[10].r,yb.i) + S_MUL(scratch[9].r,ya.i);
439
440 C_ADD(*Fout2,scratch[11],scratch[12]);
441 C_SUB(*Fout3,scratch[11],scratch[12]);
442
443 ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4;
444 }
445 }
446}
447
448#endif
449
450
451#ifdef CUSTOM_MODES
452
453static
454void compute_bitrev_table(
455 int Fout,
456 opus_int16 *f,
457 const size_t fstride,
458 int in_stride,
459 opus_int16 * factors,
460 const kiss_fft_state *st
461 )
462{
463 const int p=*factors++; /* the radix */
464 const int m=*factors++; /* stage's fft length/p */
465
466 /*printf ("fft %d %d %d %d %d %d\n", p*m, m, p, s2, fstride*in_stride, N);*/
467 if (m==1)
468 {
469 int j;
470 for (j=0;j<p;j++)
471 {
472 *f = Fout+j;
473 f += fstride*in_stride;
474 }
475 } else {
476 int j;
477 for (j=0;j<p;j++)
478 {
479 compute_bitrev_table( Fout , f, fstride*p, in_stride, factors,st);
480 f += fstride*in_stride;
481 Fout += m;
482 }
483 }
484}
485
486/* facbuf is populated by p1,m1,p2,m2, ...
487 where
488 p[i] * m[i] = m[i-1]
489 m0 = n */
490static
491int kf_factor(int n,opus_int16 * facbuf)
492{
493 int p=4;
494
495 /*factor out powers of 4, powers of 2, then any remaining primes */
496 do {
497 while (n % p) {
498 switch (p) {
499 case 4: p = 2; break;
500 case 2: p = 3; break;
501 default: p += 2; break;
502 }
503 if (p>32000 || (opus_int32)p*(opus_int32)p > n)
504 p = n; /* no more factors, skip to end */
505 }
506 n /= p;
507#ifdef RADIX_TWO_ONLY
508 if (p!=2 && p != 4)
509#else
510 if (p>5)
511#endif
512 {
513 return 0;
514 }
515 *facbuf++ = p;
516 *facbuf++ = n;
517 } while (n > 1);
518 return 1;
519}
520
521static void compute_twiddles(kiss_twiddle_cpx *twiddles, int nfft)
522{
523 int i;
524#ifdef FIXED_POINT
525 for (i=0;i<nfft;++i) {
526 opus_val32 phase = -i;
527 kf_cexp2(twiddles+i, DIV32(SHL32(phase,17),nfft));
528 }
529#else
530 for (i=0;i<nfft;++i) {
531 const double pi=3.14159265358979323846264338327;
532 double phase = ( -2*pi /nfft ) * i;
533 kf_cexp(twiddles+i, phase );
534 }
535#endif
536}
537
538/*
539 *
540 * Allocates all necessary storage space for the fft and ifft.
541 * The return value is a contiguous block of memory. As such,
542 * It can be freed with free().
543 * */
544kiss_fft_state *opus_fft_alloc_twiddles(int nfft,void * mem,size_t * lenmem, const kiss_fft_state *base)
545{
546 kiss_fft_state *st=NULL;
547 size_t memneeded = sizeof(struct kiss_fft_state); /* twiddle factors*/
548
549 if ( lenmem==NULL ) {
550 st = ( kiss_fft_state*)KISS_FFT_MALLOC( memneeded );
551 }else{
552 if (mem != NULL && *lenmem >= memneeded)
553 st = (kiss_fft_state*)mem;
554 *lenmem = memneeded;
555 }
556 if (st) {
557 opus_int16 *bitrev;
558 kiss_twiddle_cpx *twiddles;
559
560 st->nfft=nfft;
561#ifndef FIXED_POINT
562 st->scale = 1.f/nfft;
563#endif
564 if (base != NULL)
565 {
566 st->twiddles = base->twiddles;
567 st->shift = 0;
568 while (nfft<<st->shift != base->nfft && st->shift < 32)
569 st->shift++;
570 if (st->shift>=32)
571 goto fail;
572 } else {
573 st->twiddles = twiddles = (kiss_twiddle_cpx*)KISS_FFT_MALLOC(sizeof(kiss_twiddle_cpx)*nfft);
574 compute_twiddles(twiddles, nfft);
575 st->shift = -1;
576 }
577 if (!kf_factor(nfft,st->factors))
578 {
579 goto fail;
580 }
581
582 /* bitrev */
583 st->bitrev = bitrev = (opus_int16*)KISS_FFT_MALLOC(sizeof(opus_int16)*nfft);
584 if (st->bitrev==NULL)
585 goto fail;
586 compute_bitrev_table(0, bitrev, 1,1, st->factors,st);
587 }
588 return st;
589fail:
590 opus_fft_free(st);
591 return NULL;
592}
593
594kiss_fft_state *opus_fft_alloc(int nfft,void * mem,size_t * lenmem )
595{
596 return opus_fft_alloc_twiddles(nfft, mem, lenmem, NULL);
597}
598
599void opus_fft_free(const kiss_fft_state *cfg)
600{
601 if (cfg)
602 {
603 opus_free((opus_int16*)cfg->bitrev);
604 if (cfg->shift < 0)
605 opus_free((kiss_twiddle_cpx*)cfg->twiddles);
606 opus_free((kiss_fft_state*)cfg);
607 }
608}
609
610#endif /* CUSTOM_MODES */
611
612void opus_fft(const kiss_fft_state *st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout)
613{
614 int m2, m;
615 int p;
616 int L;
617 int fstride[MAXFACTORS];
618 int i;
619 int shift;
620
621 /* st->shift can be -1 */
622 shift = st->shift>0 ? st->shift : 0;
623
624 celt_assert2 (fin != fout, "In-place FFT not supported");
625 /* Bit-reverse the input */
626 for (i=0;i<st->nfft;i++)
627 {
628 fout[st->bitrev[i]] = fin[i];
629#ifndef FIXED_POINT
630 fout[st->bitrev[i]].r *= st->scale;
631 fout[st->bitrev[i]].i *= st->scale;
632#endif
633 }
634
635 fstride[0] = 1;
636 L=0;
637 do {
638 p = st->factors[2*L];
639 m = st->factors[2*L+1];
640 fstride[L+1] = fstride[L]*p;
641 L++;
642 } while(m!=1);
643 m = st->factors[2*L-1];
644 for (i=L-1;i>=0;i--)
645 {
646 if (i!=0)
647 m2 = st->factors[2*i-1];
648 else
649 m2 = 1;
650 switch (st->factors[2*i])
651 {
652 case 2:
653 kf_bfly2(fout,fstride[i]<<shift,st,m, fstride[i], m2);
654 break;
655 case 4:
656 kf_bfly4(fout,fstride[i]<<shift,st,m, fstride[i], m2);
657 break;
658 #ifndef RADIX_TWO_ONLY
659 case 3:
660 kf_bfly3(fout,fstride[i]<<shift,st,m, fstride[i], m2);
661 break;
662 case 5:
663 kf_bfly5(fout,fstride[i]<<shift,st,m, fstride[i], m2);
664 break;
665 #endif
666 }
667 m = m2;
668 }
669}
670
671void opus_ifft(const kiss_fft_state *st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout)
672{
673 int m2, m;
674 int p;
675 int L;
676 int fstride[MAXFACTORS];
677 int i;
678 int shift;
679
680 /* st->shift can be -1 */
681 shift = st->shift>0 ? st->shift : 0;
682 celt_assert2 (fin != fout, "In-place FFT not supported");
683 /* Bit-reverse the input */
684 for (i=0;i<st->nfft;i++)
685 fout[st->bitrev[i]] = fin[i];
686
687 fstride[0] = 1;
688 L=0;
689 do {
690 p = st->factors[2*L];
691 m = st->factors[2*L+1];
692 fstride[L+1] = fstride[L]*p;
693 L++;
694 } while(m!=1);
695 m = st->factors[2*L-1];
696 for (i=L-1;i>=0;i--)
697 {
698 if (i!=0)
699 m2 = st->factors[2*i-1];
700 else
701 m2 = 1;
702 switch (st->factors[2*i])
703 {
704 case 2:
705 ki_bfly2(fout,fstride[i]<<shift,st,m, fstride[i], m2);
706 break;
707 case 4:
708 ki_bfly4(fout,fstride[i]<<shift,st,m, fstride[i], m2);
709 break;
710#ifndef RADIX_TWO_ONLY
711 case 3:
712 ki_bfly3(fout,fstride[i]<<shift,st,m, fstride[i], m2);
713 break;
714 case 5:
715 ki_bfly5(fout,fstride[i]<<shift,st,m, fstride[i], m2);
716 break;
717#endif
718 }
719 m = m2;
720 }
721}
722
diff --git a/lib/rbcodec/codecs/libopus/celt/kiss_fft.h b/lib/rbcodec/codecs/libopus/celt/kiss_fft.h
new file mode 100644
index 0000000000..66332e3bb9
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/kiss_fft.h
@@ -0,0 +1,139 @@
1/*Copyright (c) 2003-2004, Mark Borgerding
2 Lots of modifications by Jean-Marc Valin
3 Copyright (c) 2005-2007, Xiph.Org Foundation
4 Copyright (c) 2008, Xiph.Org Foundation, CSIRO
5
6 All rights reserved.
7
8 Redistribution and use in source and binary forms, with or without
9 modification, are permitted provided that the following conditions are met:
10
11 * Redistributions of source code must retain the above copyright notice,
12 this list of conditions and the following disclaimer.
13 * Redistributions in binary form must reproduce the above copyright notice,
14 this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 POSSIBILITY OF SUCH DAMAGE.*/
28
29#ifndef KISS_FFT_H
30#define KISS_FFT_H
31
32#include <stdlib.h>
33#include <math.h>
34#include "arch.h"
35
36#ifdef __cplusplus
37extern "C" {
38#endif
39
40#ifdef USE_SIMD
41# include <xmmintrin.h>
42# define kiss_fft_scalar __m128
43#define KISS_FFT_MALLOC(nbytes) memalign(16,nbytes)
44#else
45#define KISS_FFT_MALLOC opus_alloc
46#endif
47
48#ifdef FIXED_POINT
49#include "arch.h"
50
51# define kiss_fft_scalar opus_int32
52# define kiss_twiddle_scalar opus_int16
53
54
55#else
56# ifndef kiss_fft_scalar
57/* default is float */
58# define kiss_fft_scalar float
59# define kiss_twiddle_scalar float
60# define KF_SUFFIX _celt_single
61# endif
62#endif
63
64typedef struct {
65 kiss_fft_scalar r;
66 kiss_fft_scalar i;
67}kiss_fft_cpx;
68
69typedef struct {
70 kiss_twiddle_scalar r;
71 kiss_twiddle_scalar i;
72}kiss_twiddle_cpx;
73
74#define MAXFACTORS 8
75/* e.g. an fft of length 128 has 4 factors
76 as far as kissfft is concerned
77 4*4*4*2
78 */
79
80typedef struct kiss_fft_state{
81 int nfft;
82#ifndef FIXED_POINT
83 kiss_fft_scalar scale;
84#endif
85 int shift;
86 opus_int16 factors[2*MAXFACTORS];
87 const opus_int16 *bitrev;
88 const kiss_twiddle_cpx *twiddles;
89} kiss_fft_state;
90
91/*typedef struct kiss_fft_state* kiss_fft_cfg;*/
92
93/**
94 * opus_fft_alloc
95 *
96 * Initialize a FFT (or IFFT) algorithm's cfg/state buffer.
97 *
98 * typical usage: kiss_fft_cfg mycfg=opus_fft_alloc(1024,0,NULL,NULL);
99 *
100 * The return value from fft_alloc is a cfg buffer used internally
101 * by the fft routine or NULL.
102 *
103 * If lenmem is NULL, then opus_fft_alloc will allocate a cfg buffer using malloc.
104 * The returned value should be free()d when done to avoid memory leaks.
105 *
106 * The state can be placed in a user supplied buffer 'mem':
107 * If lenmem is not NULL and mem is not NULL and *lenmem is large enough,
108 * then the function places the cfg in mem and the size used in *lenmem
109 * and returns mem.
110 *
111 * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough),
112 * then the function returns NULL and places the minimum cfg
113 * buffer size in *lenmem.
114 * */
115
116kiss_fft_state *opus_fft_alloc_twiddles(int nfft,void * mem,size_t * lenmem, const kiss_fft_state *base);
117
118kiss_fft_state *opus_fft_alloc(int nfft,void * mem,size_t * lenmem);
119
120/**
121 * opus_fft(cfg,in_out_buf)
122 *
123 * Perform an FFT on a complex input buffer.
124 * for a forward FFT,
125 * fin should be f[0] , f[1] , ... ,f[nfft-1]
126 * fout will be F[0] , F[1] , ... ,F[nfft-1]
127 * Note that each element is complex and can be accessed like
128 f[k].r and f[k].i
129 * */
130void opus_fft(const kiss_fft_state *cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout);
131void opus_ifft(const kiss_fft_state *cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout);
132
133void opus_fft_free(const kiss_fft_state *cfg);
134
135#ifdef __cplusplus
136}
137#endif
138
139#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/laplace.c b/lib/rbcodec/codecs/libopus/celt/laplace.c
new file mode 100644
index 0000000000..6fa4009d57
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/laplace.c
@@ -0,0 +1,134 @@
1/* Copyright (c) 2007 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29#ifdef HAVE_CONFIG_H
30#include "opus_config.h"
31#endif
32
33#include "laplace.h"
34#include "mathops.h"
35
36/* The minimum probability of an energy delta (out of 32768). */
37#define LAPLACE_LOG_MINP (0)
38#define LAPLACE_MINP (1<<LAPLACE_LOG_MINP)
39/* The minimum number of guaranteed representable energy deltas (in one
40 direction). */
41#define LAPLACE_NMIN (16)
42
43/* When called, decay is positive and at most 11456. */
44static unsigned ec_laplace_get_freq1(unsigned fs0, int decay)
45{
46 unsigned ft;
47 ft = 32768 - LAPLACE_MINP*(2*LAPLACE_NMIN) - fs0;
48 return ft*(opus_int32)(16384-decay)>>15;
49}
50
51void ec_laplace_encode(ec_enc *enc, int *value, unsigned fs, int decay)
52{
53 unsigned fl;
54 int val = *value;
55 fl = 0;
56 if (val)
57 {
58 int s;
59 int i;
60 s = -(val<0);
61 val = (val+s)^s;
62 fl = fs;
63 fs = ec_laplace_get_freq1(fs, decay);
64 /* Search the decaying part of the PDF.*/
65 for (i=1; fs > 0 && i < val; i++)
66 {
67 fs *= 2;
68 fl += fs+2*LAPLACE_MINP;
69 fs = (fs*(opus_int32)decay)>>15;
70 }
71 /* Everything beyond that has probability LAPLACE_MINP. */
72 if (!fs)
73 {
74 int di;
75 int ndi_max;
76 ndi_max = (32768-fl+LAPLACE_MINP-1)>>LAPLACE_LOG_MINP;
77 ndi_max = (ndi_max-s)>>1;
78 di = IMIN(val - i, ndi_max - 1);
79 fl += (2*di+1+s)*LAPLACE_MINP;
80 fs = IMIN(LAPLACE_MINP, 32768-fl);
81 *value = (i+di+s)^s;
82 }
83 else
84 {
85 fs += LAPLACE_MINP;
86 fl += fs&~s;
87 }
88 celt_assert(fl+fs<=32768);
89 celt_assert(fs>0);
90 }
91 ec_encode_bin(enc, fl, fl+fs, 15);
92}
93
94int ec_laplace_decode(ec_dec *dec, unsigned fs, int decay)
95{
96 int val=0;
97 unsigned fl;
98 unsigned fm;
99 fm = ec_decode_bin(dec, 15);
100 fl = 0;
101 if (fm >= fs)
102 {
103 val++;
104 fl = fs;
105 fs = ec_laplace_get_freq1(fs, decay)+LAPLACE_MINP;
106 /* Search the decaying part of the PDF.*/
107 while(fs > LAPLACE_MINP && fm >= fl+2*fs)
108 {
109 fs *= 2;
110 fl += fs;
111 fs = ((fs-2*LAPLACE_MINP)*(opus_int32)decay)>>15;
112 fs += LAPLACE_MINP;
113 val++;
114 }
115 /* Everything beyond that has probability LAPLACE_MINP. */
116 if (fs <= LAPLACE_MINP)
117 {
118 int di;
119 di = (fm-fl)>>(LAPLACE_LOG_MINP+1);
120 val += di;
121 fl += 2*di*LAPLACE_MINP;
122 }
123 if (fm < fl+fs)
124 val = -val;
125 else
126 fl += fs;
127 }
128 celt_assert(fl<32768);
129 celt_assert(fs>0);
130 celt_assert(fl<=fm);
131 celt_assert(fm<IMIN(fl+fs,32768));
132 ec_dec_update(dec, fl, IMIN(fl+fs,32768), 32768);
133 return val;
134}
diff --git a/lib/rbcodec/codecs/libopus/celt/laplace.h b/lib/rbcodec/codecs/libopus/celt/laplace.h
new file mode 100644
index 0000000000..46c14b5da5
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/laplace.h
@@ -0,0 +1,48 @@
1/* Copyright (c) 2007 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29#include "entenc.h"
30#include "entdec.h"
31
32/** Encode a value that is assumed to be the realisation of a
33 Laplace-distributed random process
34 @param enc Entropy encoder state
35 @param value Value to encode
36 @param fs Probability of 0, multiplied by 32768
37 @param decay Probability of the value +/- 1, multiplied by 16384
38*/
39void ec_laplace_encode(ec_enc *enc, int *value, unsigned fs, int decay);
40
41/** Decode a value that is assumed to be the realisation of a
42 Laplace-distributed random process
43 @param dec Entropy decoder state
44 @param fs Probability of 0, multiplied by 32768
45 @param decay Probability of the value +/- 1, multiplied by 16384
46 @return Value decoded
47 */
48int ec_laplace_decode(ec_dec *dec, unsigned fs, int decay);
diff --git a/lib/rbcodec/codecs/libopus/celt/mathops.c b/lib/rbcodec/codecs/libopus/celt/mathops.c
new file mode 100644
index 0000000000..1af6672592
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/mathops.c
@@ -0,0 +1,206 @@
1/* Copyright (c) 2002-2008 Jean-Marc Valin
2 Copyright (c) 2007-2008 CSIRO
3 Copyright (c) 2007-2009 Xiph.Org Foundation
4 Written by Jean-Marc Valin */
5/**
6 @file mathops.h
7 @brief Various math functions
8*/
9/*
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions
12 are met:
13
14 - Redistributions of source code must retain the above copyright
15 notice, this list of conditions and the following disclaimer.
16
17 - Redistributions in binary form must reproduce the above copyright
18 notice, this list of conditions and the following disclaimer in the
19 documentation and/or other materials provided with the distribution.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
25 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32*/
33
34#ifdef HAVE_CONFIG_H
35#include "opus_config.h"
36#endif
37
38#include "mathops.h"
39
40/*Compute floor(sqrt(_val)) with exact arithmetic.
41 This has been tested on all possible 32-bit inputs.*/
42unsigned isqrt32(opus_uint32 _val){
43 unsigned b;
44 unsigned g;
45 int bshift;
46 /*Uses the second method from
47 http://www.azillionmonkeys.com/qed/sqroot.html
48 The main idea is to search for the largest binary digit b such that
49 (g+b)*(g+b) <= _val, and add it to the solution g.*/
50 g=0;
51 bshift=(EC_ILOG(_val)-1)>>1;
52 b=1U<<bshift;
53 do{
54 opus_uint32 t;
55 t=(((opus_uint32)g<<1)+b)<<bshift;
56 if(t<=_val){
57 g+=b;
58 _val-=t;
59 }
60 b>>=1;
61 bshift--;
62 }
63 while(bshift>=0);
64 return g;
65}
66
67#ifdef FIXED_POINT
68
69opus_val32 frac_div32(opus_val32 a, opus_val32 b)
70{
71 opus_val16 rcp;
72 opus_val32 result, rem;
73 int shift = celt_ilog2(b)-29;
74 a = VSHR32(a,shift);
75 b = VSHR32(b,shift);
76 /* 16-bit reciprocal */
77 rcp = ROUND16(celt_rcp(ROUND16(b,16)),3);
78 result = MULT16_32_Q15(rcp, a);
79 rem = PSHR32(a,2)-MULT32_32_Q31(result, b);
80 result = ADD32(result, SHL32(MULT16_32_Q15(rcp, rem),2));
81 if (result >= 536870912) /* 2^29 */
82 return 2147483647; /* 2^31 - 1 */
83 else if (result <= -536870912) /* -2^29 */
84 return -2147483647; /* -2^31 */
85 else
86 return SHL32(result, 2);
87}
88
89/** Reciprocal sqrt approximation in the range [0.25,1) (Q16 in, Q14 out) */
90opus_val16 celt_rsqrt_norm(opus_val32 x)
91{
92 opus_val16 n;
93 opus_val16 r;
94 opus_val16 r2;
95 opus_val16 y;
96 /* Range of n is [-16384,32767] ([-0.5,1) in Q15). */
97 n = x-32768;
98 /* Get a rough initial guess for the root.
99 The optimal minimax quadratic approximation (using relative error) is
100 r = 1.437799046117536+n*(-0.823394375837328+n*0.4096419668459485).
101 Coefficients here, and the final result r, are Q14.*/
102 r = ADD16(23557, MULT16_16_Q15(n, ADD16(-13490, MULT16_16_Q15(n, 6713))));
103 /* We want y = x*r*r-1 in Q15, but x is 32-bit Q16 and r is Q14.
104 We can compute the result from n and r using Q15 multiplies with some
105 adjustment, carefully done to avoid overflow.
106 Range of y is [-1564,1594]. */
107 r2 = MULT16_16_Q15(r, r);
108 y = SHL16(SUB16(ADD16(MULT16_16_Q15(r2, n), r2), 16384), 1);
109 /* Apply a 2nd-order Householder iteration: r += r*y*(y*0.375-0.5).
110 This yields the Q14 reciprocal square root of the Q16 x, with a maximum
111 relative error of 1.04956E-4, a (relative) RMSE of 2.80979E-5, and a
112 peak absolute error of 2.26591/16384. */
113 return ADD16(r, MULT16_16_Q15(r, MULT16_16_Q15(y,
114 SUB16(MULT16_16_Q15(y, 12288), 16384))));
115}
116
117/** Sqrt approximation (QX input, QX/2 output) */
118opus_val32 celt_sqrt(opus_val32 x)
119{
120 int k;
121 opus_val16 n;
122 opus_val32 rt;
123 static const opus_val16 C[5] = {23175, 11561, -3011, 1699, -664};
124 if (x==0)
125 return 0;
126 k = (celt_ilog2(x)>>1)-7;
127 x = VSHR32(x, 2*k);
128 n = x-32768;
129 rt = ADD16(C[0], MULT16_16_Q15(n, ADD16(C[1], MULT16_16_Q15(n, ADD16(C[2],
130 MULT16_16_Q15(n, ADD16(C[3], MULT16_16_Q15(n, (C[4])))))))));
131 rt = VSHR32(rt,7-k);
132 return rt;
133}
134
135#define L1 32767
136#define L2 -7651
137#define L3 8277
138#define L4 -626
139
140static inline opus_val16 _celt_cos_pi_2(opus_val16 x)
141{
142 opus_val16 x2;
143
144 x2 = MULT16_16_P15(x,x);
145 return ADD16(1,MIN16(32766,ADD32(SUB16(L1,x2), MULT16_16_P15(x2, ADD32(L2, MULT16_16_P15(x2, ADD32(L3, MULT16_16_P15(L4, x2
146 ))))))));
147}
148
149#undef L1
150#undef L2
151#undef L3
152#undef L4
153
154opus_val16 celt_cos_norm(opus_val32 x)
155{
156 x = x&0x0001ffff;
157 if (x>SHL32(EXTEND32(1), 16))
158 x = SUB32(SHL32(EXTEND32(1), 17),x);
159 if (x&0x00007fff)
160 {
161 if (x<SHL32(EXTEND32(1), 15))
162 {
163 return _celt_cos_pi_2(EXTRACT16(x));
164 } else {
165 return NEG32(_celt_cos_pi_2(EXTRACT16(65536-x)));
166 }
167 } else {
168 if (x&0x0000ffff)
169 return 0;
170 else if (x&0x0001ffff)
171 return -32767;
172 else
173 return 32767;
174 }
175}
176
177/** Reciprocal approximation (Q15 input, Q16 output) */
178opus_val32 celt_rcp(opus_val32 x)
179{
180 int i;
181 opus_val16 n;
182 opus_val16 r;
183 celt_assert2(x>0, "celt_rcp() only defined for positive values");
184 i = celt_ilog2(x);
185 /* n is Q15 with range [0,1). */
186 n = VSHR32(x,i-15)-32768;
187 /* Start with a linear approximation:
188 r = 1.8823529411764706-0.9411764705882353*n.
189 The coefficients and the result are Q14 in the range [15420,30840].*/
190 r = ADD16(30840, MULT16_16_Q15(-15420, n));
191 /* Perform two Newton iterations:
192 r -= r*((r*n)-1.Q15)
193 = r*((r*n)+(r-1.Q15)). */
194 r = SUB16(r, MULT16_16_Q15(r,
195 ADD16(MULT16_16_Q15(r, n), ADD16(r, -32768))));
196 /* We subtract an extra 1 in the second iteration to avoid overflow; it also
197 neatly compensates for truncation error in the rest of the process. */
198 r = SUB16(r, ADD16(1, MULT16_16_Q15(r,
199 ADD16(MULT16_16_Q15(r, n), ADD16(r, -32768)))));
200 /* r is now the Q15 solution to 2/(n+1), with a maximum relative error
201 of 7.05346E-5, a (relative) RMSE of 2.14418E-5, and a peak absolute
202 error of 1.24665/32768. */
203 return VSHR32(EXTEND32(r),i-16);
204}
205
206#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/mathops.h b/lib/rbcodec/codecs/libopus/celt/mathops.h
new file mode 100644
index 0000000000..4e97795606
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/mathops.h
@@ -0,0 +1,237 @@
1/* Copyright (c) 2002-2008 Jean-Marc Valin
2 Copyright (c) 2007-2008 CSIRO
3 Copyright (c) 2007-2009 Xiph.Org Foundation
4 Written by Jean-Marc Valin */
5/**
6 @file mathops.h
7 @brief Various math functions
8*/
9/*
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions
12 are met:
13
14 - Redistributions of source code must retain the above copyright
15 notice, this list of conditions and the following disclaimer.
16
17 - Redistributions in binary form must reproduce the above copyright
18 notice, this list of conditions and the following disclaimer in the
19 documentation and/or other materials provided with the distribution.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
25 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32*/
33
34#ifndef MATHOPS_H
35#define MATHOPS_H
36
37#include "arch.h"
38#include "entcode.h"
39#include "os_support.h"
40
41/* Multiplies two 16-bit fractional values. Bit-exactness of this macro is important */
42#define FRAC_MUL16(a,b) ((16384+((opus_int32)(opus_int16)(a)*(opus_int16)(b)))>>15)
43
44unsigned isqrt32(opus_uint32 _val);
45
46#ifndef FIXED_POINT
47
48#define PI 3.141592653f
49#define celt_sqrt(x) ((float)sqrt(x))
50#define celt_rsqrt(x) (1.f/celt_sqrt(x))
51#define celt_rsqrt_norm(x) (celt_rsqrt(x))
52#define celt_cos_norm(x) ((float)cos((.5f*PI)*(x)))
53#define celt_rcp(x) (1.f/(x))
54#define celt_div(a,b) ((a)/(b))
55#define frac_div32(a,b) ((float)(a)/(b))
56
57#ifdef FLOAT_APPROX
58
59/* Note: This assumes radix-2 floating point with the exponent at bits 23..30 and an offset of 127
60 denorm, +/- inf and NaN are *not* handled */
61
62/** Base-2 log approximation (log2(x)). */
63static inline float celt_log2(float x)
64{
65 int integer;
66 float frac;
67 union {
68 float f;
69 opus_uint32 i;
70 } in;
71 in.f = x;
72 integer = (in.i>>23)-127;
73 in.i -= integer<<23;
74 frac = in.f - 1.5f;
75 frac = -0.41445418f + frac*(0.95909232f
76 + frac*(-0.33951290f + frac*0.16541097f));
77 return 1+integer+frac;
78}
79
80/** Base-2 exponential approximation (2^x). */
81static inline float celt_exp2(float x)
82{
83 int integer;
84 float frac;
85 union {
86 float f;
87 opus_uint32 i;
88 } res;
89 integer = floor(x);
90 if (integer < -50)
91 return 0;
92 frac = x-integer;
93 /* K0 = 1, K1 = log(2), K2 = 3-4*log(2), K3 = 3*log(2) - 2 */
94 res.f = 0.99992522f + frac * (0.69583354f
95 + frac * (0.22606716f + 0.078024523f*frac));
96 res.i = (res.i + (integer<<23)) & 0x7fffffff;
97 return res.f;
98}
99
100#else
101#define celt_log2(x) ((float)(1.442695040888963387*log(x)))
102#define celt_exp2(x) ((float)exp(0.6931471805599453094*(x)))
103#endif
104
105#endif
106
107#ifdef FIXED_POINT
108
109#include "os_support.h"
110
111#ifndef OVERRIDE_CELT_ILOG2
112/** Integer log in base2. Undefined for zero and negative numbers */
113static inline opus_int16 celt_ilog2(opus_int32 x)
114{
115 celt_assert2(x>0, "celt_ilog2() only defined for strictly positive numbers");
116 return EC_ILOG(x)-1;
117}
118#endif
119
120#ifndef OVERRIDE_CELT_MAXABS16
121static inline opus_val16 celt_maxabs16(opus_val16 *x, int len)
122{
123 int i;
124 opus_val16 maxval = 0;
125 for (i=0;i<len;i++)
126 maxval = MAX16(maxval, ABS16(x[i]));
127 return maxval;
128}
129#endif
130
131#ifndef OVERRIDE_CELT_MAXABS32
132static inline opus_val32 celt_maxabs32(opus_val32 *x, int len)
133{
134 int i;
135 opus_val32 maxval = 0;
136 for (i=0;i<len;i++)
137 maxval = MAX32(maxval, ABS32(x[i]));
138 return maxval;
139}
140#endif
141
142/** Integer log in base2. Defined for zero, but not for negative numbers */
143static inline opus_int16 celt_zlog2(opus_val32 x)
144{
145 return x <= 0 ? 0 : celt_ilog2(x);
146}
147
148opus_val16 celt_rsqrt_norm(opus_val32 x);
149
150opus_val32 celt_sqrt(opus_val32 x);
151
152opus_val16 celt_cos_norm(opus_val32 x);
153
154static inline opus_val16 celt_log2(opus_val32 x)
155{
156 int i;
157 opus_val16 n, frac;
158 /* -0.41509302963303146, 0.9609890551383969, -0.31836011537636605,
159 0.15530808010959576, -0.08556153059057618 */
160 static const opus_val16 C[5] = {-6801+(1<<(13-DB_SHIFT)), 15746, -5217, 2545, -1401};
161 if (x==0)
162 return -32767;
163 i = celt_ilog2(x);
164 n = VSHR32(x,i-15)-32768-16384;
165 frac = ADD16(C[0], MULT16_16_Q15(n, ADD16(C[1], MULT16_16_Q15(n, ADD16(C[2], MULT16_16_Q15(n, ADD16(C[3], MULT16_16_Q15(n, C[4]))))))));
166 return SHL16(i-13,DB_SHIFT)+SHR16(frac,14-DB_SHIFT);
167}
168
169/*
170 K0 = 1
171 K1 = log(2)
172 K2 = 3-4*log(2)
173 K3 = 3*log(2) - 2
174*/
175#define D0 16383
176#define D1 22804
177#define D2 14819
178#define D3 10204
179/** Base-2 exponential approximation (2^x). (Q10 input, Q16 output) */
180static inline opus_val32 celt_exp2(opus_val16 x)
181{
182 int integer;
183 opus_val16 frac;
184 integer = SHR16(x,10);
185 if (integer>14)
186 return 0x7f000000;
187 else if (integer < -15)
188 return 0;
189 frac = SHL16(x-SHL16(integer,10),4);
190 frac = ADD16(D0, MULT16_16_Q15(frac, ADD16(D1, MULT16_16_Q15(frac, ADD16(D2 , MULT16_16_Q15(D3,frac))))));
191 return VSHR32(EXTEND32(frac), -integer-2);
192}
193
194opus_val32 celt_rcp(opus_val32 x);
195
196#define celt_div(a,b) MULT32_32_Q31((opus_val32)(a),celt_rcp(b))
197
198opus_val32 frac_div32(opus_val32 a, opus_val32 b);
199
200#define M1 32767
201#define M2 -21
202#define M3 -11943
203#define M4 4936
204
205/* Atan approximation using a 4th order polynomial. Input is in Q15 format
206 and normalized by pi/4. Output is in Q15 format */
207static inline opus_val16 celt_atan01(opus_val16 x)
208{
209 return MULT16_16_P15(x, ADD32(M1, MULT16_16_P15(x, ADD32(M2, MULT16_16_P15(x, ADD32(M3, MULT16_16_P15(M4, x)))))));
210}
211
212#undef M1
213#undef M2
214#undef M3
215#undef M4
216
217/* atan2() approximation valid for positive input values */
218static inline opus_val16 celt_atan2p(opus_val16 y, opus_val16 x)
219{
220 if (y < x)
221 {
222 opus_val32 arg;
223 arg = celt_div(SHL32(EXTEND32(y),15),x);
224 if (arg >= 32767)
225 arg = 32767;
226 return SHR16(celt_atan01(EXTRACT16(arg)),1);
227 } else {
228 opus_val32 arg;
229 arg = celt_div(SHL32(EXTEND32(x),15),y);
230 if (arg >= 32767)
231 arg = 32767;
232 return 25736-SHR16(celt_atan01(EXTRACT16(arg)),1);
233 }
234}
235
236#endif /* FIXED_POINT */
237#endif /* MATHOPS_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/mdct.c b/lib/rbcodec/codecs/libopus/celt/mdct.c
new file mode 100644
index 0000000000..abf4e79d8d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/mdct.c
@@ -0,0 +1,332 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2008 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29/* This is a simple MDCT implementation that uses a N/4 complex FFT
30 to do most of the work. It should be relatively straightforward to
31 plug in pretty much and FFT here.
32
33 This replaces the Vorbis FFT (and uses the exact same API), which
34 was a bit too messy and that was ending up duplicating code
35 (might as well use the same FFT everywhere).
36
37 The algorithm is similar to (and inspired from) Fabrice Bellard's
38 MDCT implementation in FFMPEG, but has differences in signs, ordering
39 and scaling in many places.
40*/
41
42#ifndef SKIP_CONFIG_H
43#ifdef HAVE_CONFIG_H
44#include "opus_config.h"
45#endif
46#endif
47
48#include "mdct.h"
49#include "kiss_fft.h"
50#include "_kiss_fft_guts.h"
51#include <math.h>
52#include "os_support.h"
53#include "mathops.h"
54#include "stack_alloc.h"
55
56#ifdef CUSTOM_MODES
57
58int clt_mdct_init(mdct_lookup *l,int N, int maxshift)
59{
60 int i;
61 int N4;
62 kiss_twiddle_scalar *trig;
63#if defined(FIXED_POINT)
64 int N2=N>>1;
65#endif
66 l->n = N;
67 N4 = N>>2;
68 l->maxshift = maxshift;
69 for (i=0;i<=maxshift;i++)
70 {
71 if (i==0)
72 l->kfft[i] = opus_fft_alloc(N>>2>>i, 0, 0);
73 else
74 l->kfft[i] = opus_fft_alloc_twiddles(N>>2>>i, 0, 0, l->kfft[0]);
75#ifndef ENABLE_TI_DSPLIB55
76 if (l->kfft[i]==NULL)
77 return 0;
78#endif
79 }
80 l->trig = trig = (kiss_twiddle_scalar*)opus_alloc((N4+1)*sizeof(kiss_twiddle_scalar));
81 if (l->trig==NULL)
82 return 0;
83 /* We have enough points that sine isn't necessary */
84#if defined(FIXED_POINT)
85 for (i=0;i<=N4;i++)
86 trig[i] = TRIG_UPSCALE*celt_cos_norm(DIV32(ADD32(SHL32(EXTEND32(i),17),N2),N));
87#else
88 for (i=0;i<=N4;i++)
89 trig[i] = (kiss_twiddle_scalar)cos(2*PI*i/N);
90#endif
91 return 1;
92}
93
94void clt_mdct_clear(mdct_lookup *l)
95{
96 int i;
97 for (i=0;i<=l->maxshift;i++)
98 opus_fft_free(l->kfft[i]);
99 opus_free((kiss_twiddle_scalar*)l->trig);
100}
101
102#endif /* CUSTOM_MODES */
103
104/* Forward MDCT trashes the input array */
105void clt_mdct_forward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * OPUS_RESTRICT out,
106 const opus_val16 *window, int overlap, int shift, int stride)
107{
108 int i;
109 int N, N2, N4;
110 kiss_twiddle_scalar sine;
111 VARDECL(kiss_fft_scalar, f);
112 SAVE_STACK;
113 N = l->n;
114 N >>= shift;
115 N2 = N>>1;
116 N4 = N>>2;
117 ALLOC(f, N2, kiss_fft_scalar);
118 /* sin(x) ~= x here */
119#ifdef FIXED_POINT
120 sine = TRIG_UPSCALE*(QCONST16(0.7853981f, 15)+N2)/N;
121#else
122 sine = (kiss_twiddle_scalar)2*PI*(.125f)/N;
123#endif
124
125 /* Consider the input to be composed of four blocks: [a, b, c, d] */
126 /* Window, shuffle, fold */
127 {
128 /* Temp pointers to make it really clear to the compiler what we're doing */
129 const kiss_fft_scalar * OPUS_RESTRICT xp1 = in+(overlap>>1);
130 const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+N2-1+(overlap>>1);
131 kiss_fft_scalar * OPUS_RESTRICT yp = f;
132 const opus_val16 * OPUS_RESTRICT wp1 = window+(overlap>>1);
133 const opus_val16 * OPUS_RESTRICT wp2 = window+(overlap>>1)-1;
134 for(i=0;i<(overlap>>2);i++)
135 {
136 /* Real part arranged as -d-cR, Imag part arranged as -b+aR*/
137 *yp++ = MULT16_32_Q15(*wp2, xp1[N2]) + MULT16_32_Q15(*wp1,*xp2);
138 *yp++ = MULT16_32_Q15(*wp1, *xp1) - MULT16_32_Q15(*wp2, xp2[-N2]);
139 xp1+=2;
140 xp2-=2;
141 wp1+=2;
142 wp2-=2;
143 }
144 wp1 = window;
145 wp2 = window+overlap-1;
146 for(;i<N4-(overlap>>2);i++)
147 {
148 /* Real part arranged as a-bR, Imag part arranged as -c-dR */
149 *yp++ = *xp2;
150 *yp++ = *xp1;
151 xp1+=2;
152 xp2-=2;
153 }
154 for(;i<N4;i++)
155 {
156 /* Real part arranged as a-bR, Imag part arranged as -c-dR */
157 *yp++ = -MULT16_32_Q15(*wp1, xp1[-N2]) + MULT16_32_Q15(*wp2, *xp2);
158 *yp++ = MULT16_32_Q15(*wp2, *xp1) + MULT16_32_Q15(*wp1, xp2[N2]);
159 xp1+=2;
160 xp2-=2;
161 wp1+=2;
162 wp2-=2;
163 }
164 }
165 /* Pre-rotation */
166 {
167 kiss_fft_scalar * OPUS_RESTRICT yp = f;
168 const kiss_twiddle_scalar *t = &l->trig[0];
169 for(i=0;i<N4;i++)
170 {
171 kiss_fft_scalar re, im, yr, yi;
172 re = yp[0];
173 im = yp[1];
174 yr = -S_MUL(re,t[i<<shift]) - S_MUL(im,t[(N4-i)<<shift]);
175 yi = -S_MUL(im,t[i<<shift]) + S_MUL(re,t[(N4-i)<<shift]);
176 /* works because the cos is nearly one */
177 *yp++ = yr + S_MUL(yi,sine);
178 *yp++ = yi - S_MUL(yr,sine);
179 }
180 }
181
182 /* N/4 complex FFT, down-scales by 4/N */
183 opus_fft(l->kfft[shift], (kiss_fft_cpx *)f, (kiss_fft_cpx *)in);
184
185 /* Post-rotate */
186 {
187 /* Temp pointers to make it really clear to the compiler what we're doing */
188 const kiss_fft_scalar * OPUS_RESTRICT fp = in;
189 kiss_fft_scalar * OPUS_RESTRICT yp1 = out;
190 kiss_fft_scalar * OPUS_RESTRICT yp2 = out+stride*(N2-1);
191 const kiss_twiddle_scalar *t = &l->trig[0];
192 /* Temp pointers to make it really clear to the compiler what we're doing */
193 for(i=0;i<N4;i++)
194 {
195 kiss_fft_scalar yr, yi;
196 yr = S_MUL(fp[1],t[(N4-i)<<shift]) + S_MUL(fp[0],t[i<<shift]);
197 yi = S_MUL(fp[0],t[(N4-i)<<shift]) - S_MUL(fp[1],t[i<<shift]);
198 /* works because the cos is nearly one */
199 *yp1 = yr - S_MUL(yi,sine);
200 *yp2 = yi + S_MUL(yr,sine);;
201 fp += 2;
202 yp1 += 2*stride;
203 yp2 -= 2*stride;
204 }
205 }
206 RESTORE_STACK;
207}
208
209void clt_mdct_backward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * OPUS_RESTRICT out,
210 const opus_val16 * OPUS_RESTRICT window, int overlap, int shift, int stride)
211{
212 int i;
213 int N, N2, N4;
214 kiss_twiddle_scalar sine;
215 VARDECL(kiss_fft_scalar, f);
216 VARDECL(kiss_fft_scalar, f2);
217 SAVE_STACK;
218 N = l->n;
219 N >>= shift;
220 N2 = N>>1;
221 N4 = N>>2;
222 ALLOC(f, N2, kiss_fft_scalar);
223 ALLOC(f2, N2, kiss_fft_scalar);
224 /* sin(x) ~= x here */
225#ifdef FIXED_POINT
226 sine = TRIG_UPSCALE*(QCONST16(0.7853981f, 15)+N2)/N;
227#else
228 sine = (kiss_twiddle_scalar)2*PI*(.125f)/N;
229#endif
230
231 /* Pre-rotate */
232 {
233 /* Temp pointers to make it really clear to the compiler what we're doing */
234 const kiss_fft_scalar * OPUS_RESTRICT xp1 = in;
235 const kiss_fft_scalar * OPUS_RESTRICT xp2 = in+stride*(N2-1);
236 kiss_fft_scalar * OPUS_RESTRICT yp = f2;
237 const kiss_twiddle_scalar *t = &l->trig[0];
238 for(i=0;i<N4;i++)
239 {
240 kiss_fft_scalar yr, yi;
241 yr = -S_MUL(*xp2, t[i<<shift]) + S_MUL(*xp1,t[(N4-i)<<shift]);
242 yi = -S_MUL(*xp2, t[(N4-i)<<shift]) - S_MUL(*xp1,t[i<<shift]);
243 /* works because the cos is nearly one */
244 *yp++ = yr - S_MUL(yi,sine);
245 *yp++ = yi + S_MUL(yr,sine);
246 xp1+=2*stride;
247 xp2-=2*stride;
248 }
249 }
250
251 /* Inverse N/4 complex FFT. This one should *not* downscale even in fixed-point */
252 opus_ifft(l->kfft[shift], (kiss_fft_cpx *)f2, (kiss_fft_cpx *)f);
253
254 /* Post-rotate */
255 {
256 kiss_fft_scalar * OPUS_RESTRICT fp = f;
257 const kiss_twiddle_scalar *t = &l->trig[0];
258
259 for(i=0;i<N4;i++)
260 {
261 kiss_fft_scalar re, im, yr, yi;
262 re = fp[0];
263 im = fp[1];
264 /* We'd scale up by 2 here, but instead it's done when mixing the windows */
265 yr = S_MUL(re,t[i<<shift]) - S_MUL(im,t[(N4-i)<<shift]);
266 yi = S_MUL(im,t[i<<shift]) + S_MUL(re,t[(N4-i)<<shift]);
267 /* works because the cos is nearly one */
268 *fp++ = yr - S_MUL(yi,sine);
269 *fp++ = yi + S_MUL(yr,sine);
270 }
271 }
272 /* De-shuffle the components for the middle of the window only */
273 {
274 const kiss_fft_scalar * OPUS_RESTRICT fp1 = f;
275 const kiss_fft_scalar * OPUS_RESTRICT fp2 = f+N2-1;
276 kiss_fft_scalar * OPUS_RESTRICT yp = f2;
277 for(i = 0; i < N4; i++)
278 {
279 *yp++ =-*fp1;
280 *yp++ = *fp2;
281 fp1 += 2;
282 fp2 -= 2;
283 }
284 }
285 out -= (N2-overlap)>>1;
286 /* Mirror on both sides for TDAC */
287 {
288 kiss_fft_scalar * OPUS_RESTRICT fp1 = f2+N4-1;
289 kiss_fft_scalar * OPUS_RESTRICT xp1 = out+N2-1;
290 kiss_fft_scalar * OPUS_RESTRICT yp1 = out+N4-overlap/2;
291 const opus_val16 * OPUS_RESTRICT wp1 = window;
292 const opus_val16 * OPUS_RESTRICT wp2 = window+overlap-1;
293 for(i = 0; i< N4-overlap/2; i++)
294 {
295 *xp1 = *fp1;
296 xp1--;
297 fp1--;
298 }
299 for(; i < N4; i++)
300 {
301 kiss_fft_scalar x1;
302 x1 = *fp1--;
303 *yp1++ +=-MULT16_32_Q15(*wp1, x1);
304 *xp1-- += MULT16_32_Q15(*wp2, x1);
305 wp1++;
306 wp2--;
307 }
308 }
309 {
310 kiss_fft_scalar * OPUS_RESTRICT fp2 = f2+N4;
311 kiss_fft_scalar * OPUS_RESTRICT xp2 = out+N2;
312 kiss_fft_scalar * OPUS_RESTRICT yp2 = out+N-1-(N4-overlap/2);
313 const opus_val16 * OPUS_RESTRICT wp1 = window;
314 const opus_val16 * OPUS_RESTRICT wp2 = window+overlap-1;
315 for(i = 0; i< N4-overlap/2; i++)
316 {
317 *xp2 = *fp2;
318 xp2++;
319 fp2++;
320 }
321 for(; i < N4; i++)
322 {
323 kiss_fft_scalar x2;
324 x2 = *fp2++;
325 *yp2-- = MULT16_32_Q15(*wp1, x2);
326 *xp2++ = MULT16_32_Q15(*wp2, x2);
327 wp1++;
328 wp2--;
329 }
330 }
331 RESTORE_STACK;
332}
diff --git a/lib/rbcodec/codecs/libopus/celt/mdct.h b/lib/rbcodec/codecs/libopus/celt/mdct.h
new file mode 100644
index 0000000000..d72182138a
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/mdct.h
@@ -0,0 +1,70 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2008 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29/* This is a simple MDCT implementation that uses a N/4 complex FFT
30 to do most of the work. It should be relatively straightforward to
31 plug in pretty much and FFT here.
32
33 This replaces the Vorbis FFT (and uses the exact same API), which
34 was a bit too messy and that was ending up duplicating code
35 (might as well use the same FFT everywhere).
36
37 The algorithm is similar to (and inspired from) Fabrice Bellard's
38 MDCT implementation in FFMPEG, but has differences in signs, ordering
39 and scaling in many places.
40*/
41
42#ifndef MDCT_H
43#define MDCT_H
44
45#include "opus_defines.h"
46#include "kiss_fft.h"
47#include "arch.h"
48
49typedef struct {
50 int n;
51 int maxshift;
52 const kiss_fft_state *kfft[4];
53 const kiss_twiddle_scalar * OPUS_RESTRICT trig;
54} mdct_lookup;
55
56int clt_mdct_init(mdct_lookup *l,int N, int maxshift);
57void clt_mdct_clear(mdct_lookup *l);
58
59/** Compute a forward MDCT and scale by 4/N, trashes the input array */
60void clt_mdct_forward(const mdct_lookup *l, kiss_fft_scalar *in,
61 kiss_fft_scalar * OPUS_RESTRICT out,
62 const opus_val16 *window, int overlap, int shift, int stride);
63
64/** Compute a backward MDCT (no scaling) and performs weighted overlap-add
65 (scales implicitly by 1/2) */
66void clt_mdct_backward(const mdct_lookup *l, kiss_fft_scalar *in,
67 kiss_fft_scalar * OPUS_RESTRICT out,
68 const opus_val16 * OPUS_RESTRICT window, int overlap, int shift, int stride);
69
70#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/mfrngcod.h b/lib/rbcodec/codecs/libopus/celt/mfrngcod.h
new file mode 100644
index 0000000000..809152a59a
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/mfrngcod.h
@@ -0,0 +1,48 @@
1/* Copyright (c) 2001-2008 Timothy B. Terriberry
2 Copyright (c) 2008-2009 Xiph.Org Foundation */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#if !defined(_mfrngcode_H)
29# define _mfrngcode_H (1)
30# include "entcode.h"
31
32/*Constants used by the entropy encoder/decoder.*/
33
34/*The number of bits to output at a time.*/
35# define EC_SYM_BITS (8)
36/*The total number of bits in each of the state registers.*/
37# define EC_CODE_BITS (32)
38/*The maximum symbol value.*/
39# define EC_SYM_MAX ((1U<<EC_SYM_BITS)-1)
40/*Bits to shift by to move a symbol into the high-order position.*/
41# define EC_CODE_SHIFT (EC_CODE_BITS-EC_SYM_BITS-1)
42/*Carry bit of the high-order range symbol.*/
43# define EC_CODE_TOP (((opus_uint32)1U)<<(EC_CODE_BITS-1))
44/*Low-order bit of the high-order range symbol.*/
45# define EC_CODE_BOT (EC_CODE_TOP>>EC_SYM_BITS)
46/*The number of bits available for the last, partial symbol in the code field.*/
47# define EC_CODE_EXTRA ((EC_CODE_BITS-2)%EC_SYM_BITS+1)
48#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/modes.c b/lib/rbcodec/codecs/libopus/celt/modes.c
new file mode 100644
index 0000000000..d44cb3b9de
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/modes.c
@@ -0,0 +1,430 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2008 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifdef HAVE_CONFIG_H
31#include "opus_config.h"
32#endif
33
34#include "celt.h"
35#include "modes.h"
36#include "rate.h"
37#include "os_support.h"
38#include "stack_alloc.h"
39#include "quant_bands.h"
40
41static const opus_int16 eband5ms[] = {
42/*0 200 400 600 800 1k 1.2 1.4 1.6 2k 2.4 2.8 3.2 4k 4.8 5.6 6.8 8k 9.6 12k 15.6 */
43 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100
44};
45
46/* Alternate tuning (partially derived from Vorbis) */
47#define BITALLOC_SIZE 11
48/* Bit allocation table in units of 1/32 bit/sample (0.1875 dB SNR) */
49static const unsigned char band_allocation[] = {
50/*0 200 400 600 800 1k 1.2 1.4 1.6 2k 2.4 2.8 3.2 4k 4.8 5.6 6.8 8k 9.6 12k 15.6 */
51 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0, 0, 0, 0,
53110,100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0,
54118,110,103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23, 15, 4, 0, 0, 0, 0,
55126,119,112,104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0,
56134,127,120,114,103, 97, 91, 85, 78, 72, 66, 60, 54, 47, 41, 35, 29, 23, 16, 10, 1,
57144,137,130,124,113,107,101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1,
58152,145,138,132,123,117,111,105, 98, 92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1,
59162,155,148,142,133,127,121,115,108,102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1,
60172,165,158,152,143,137,131,125,118,112,106,100, 94, 87, 81, 75, 69, 63, 56, 45, 20,
61200,200,200,200,200,200,200,200,198,193,188,183,178,173,168,163,158,153,148,129,104,
62};
63
64#ifndef CUSTOM_MODES_ONLY
65 #ifdef FIXED_POINT
66 #include "static_modes_fixed.h"
67 #else
68 #include "static_modes_float.h"
69 #endif
70#endif /* CUSTOM_MODES_ONLY */
71
72#ifndef M_PI
73#define M_PI 3.141592653
74#endif
75
76#ifdef CUSTOM_MODES
77
78/* Defining 25 critical bands for the full 0-20 kHz audio bandwidth
79 Taken from http://ccrma.stanford.edu/~jos/bbt/Bark_Frequency_Scale.html */
80#define BARK_BANDS 25
81static const opus_int16 bark_freq[BARK_BANDS+1] = {
82 0, 100, 200, 300, 400,
83 510, 630, 770, 920, 1080,
84 1270, 1480, 1720, 2000, 2320,
85 2700, 3150, 3700, 4400, 5300,
86 6400, 7700, 9500, 12000, 15500,
87 20000};
88
89static opus_int16 *compute_ebands(opus_int32 Fs, int frame_size, int res, int *nbEBands)
90{
91 opus_int16 *eBands;
92 int i, j, lin, low, high, nBark, offset=0;
93
94 /* All modes that have 2.5 ms short blocks use the same definition */
95 if (Fs == 400*(opus_int32)frame_size)
96 {
97 *nbEBands = sizeof(eband5ms)/sizeof(eband5ms[0])-1;
98 eBands = opus_alloc(sizeof(opus_int16)*(*nbEBands+1));
99 for (i=0;i<*nbEBands+1;i++)
100 eBands[i] = eband5ms[i];
101 return eBands;
102 }
103 /* Find the number of critical bands supported by our sampling rate */
104 for (nBark=1;nBark<BARK_BANDS;nBark++)
105 if (bark_freq[nBark+1]*2 >= Fs)
106 break;
107
108 /* Find where the linear part ends (i.e. where the spacing is more than min_width */
109 for (lin=0;lin<nBark;lin++)
110 if (bark_freq[lin+1]-bark_freq[lin] >= res)
111 break;
112
113 low = (bark_freq[lin]+res/2)/res;
114 high = nBark-lin;
115 *nbEBands = low+high;
116 eBands = opus_alloc(sizeof(opus_int16)*(*nbEBands+2));
117
118 if (eBands==NULL)
119 return NULL;
120
121 /* Linear spacing (min_width) */
122 for (i=0;i<low;i++)
123 eBands[i] = i;
124 if (low>0)
125 offset = eBands[low-1]*res - bark_freq[lin-1];
126 /* Spacing follows critical bands */
127 for (i=0;i<high;i++)
128 {
129 int target = bark_freq[lin+i];
130 /* Round to an even value */
131 eBands[i+low] = (target+offset/2+res)/(2*res)*2;
132 offset = eBands[i+low]*res - target;
133 }
134 /* Enforce the minimum spacing at the boundary */
135 for (i=0;i<*nbEBands;i++)
136 if (eBands[i] < i)
137 eBands[i] = i;
138 /* Round to an even value */
139 eBands[*nbEBands] = (bark_freq[nBark]+res)/(2*res)*2;
140 if (eBands[*nbEBands] > frame_size)
141 eBands[*nbEBands] = frame_size;
142 for (i=1;i<*nbEBands-1;i++)
143 {
144 if (eBands[i+1]-eBands[i] < eBands[i]-eBands[i-1])
145 {
146 eBands[i] -= (2*eBands[i]-eBands[i-1]-eBands[i+1])/2;
147 }
148 }
149 /* Remove any empty bands. */
150 for (i=j=0;i<*nbEBands;i++)
151 if(eBands[i+1]>eBands[j])
152 eBands[++j]=eBands[i+1];
153 *nbEBands=j;
154
155 for (i=1;i<*nbEBands;i++)
156 {
157 /* Every band must be smaller than the last band. */
158 celt_assert(eBands[i]-eBands[i-1]<=eBands[*nbEBands]-eBands[*nbEBands-1]);
159 /* Each band must be no larger than twice the size of the previous one. */
160 celt_assert(eBands[i+1]-eBands[i]<=2*(eBands[i]-eBands[i-1]));
161 }
162
163 return eBands;
164}
165
166static void compute_allocation_table(CELTMode *mode)
167{
168 int i, j;
169 unsigned char *allocVectors;
170 int maxBands = sizeof(eband5ms)/sizeof(eband5ms[0])-1;
171
172 mode->nbAllocVectors = BITALLOC_SIZE;
173 allocVectors = opus_alloc(sizeof(unsigned char)*(BITALLOC_SIZE*mode->nbEBands));
174 if (allocVectors==NULL)
175 return;
176
177 /* Check for standard mode */
178 if (mode->Fs == 400*(opus_int32)mode->shortMdctSize)
179 {
180 for (i=0;i<BITALLOC_SIZE*mode->nbEBands;i++)
181 allocVectors[i] = band_allocation[i];
182 mode->allocVectors = allocVectors;
183 return;
184 }
185 /* If not the standard mode, interpolate */
186 /* Compute per-codec-band allocation from per-critical-band matrix */
187 for (i=0;i<BITALLOC_SIZE;i++)
188 {
189 for (j=0;j<mode->nbEBands;j++)
190 {
191 int k;
192 for (k=0;k<maxBands;k++)
193 {
194 if (400*(opus_int32)eband5ms[k] > mode->eBands[j]*(opus_int32)mode->Fs/mode->shortMdctSize)
195 break;
196 }
197 if (k>maxBands-1)
198 allocVectors[i*mode->nbEBands+j] = band_allocation[i*maxBands + maxBands-1];
199 else {
200 opus_int32 a0, a1;
201 a1 = mode->eBands[j]*(opus_int32)mode->Fs/mode->shortMdctSize - 400*(opus_int32)eband5ms[k-1];
202 a0 = 400*(opus_int32)eband5ms[k] - mode->eBands[j]*(opus_int32)mode->Fs/mode->shortMdctSize;
203 allocVectors[i*mode->nbEBands+j] = (a0*band_allocation[i*maxBands+k-1]
204 + a1*band_allocation[i*maxBands+k])/(a0+a1);
205 }
206 }
207 }
208
209 /*printf ("\n");
210 for (i=0;i<BITALLOC_SIZE;i++)
211 {
212 for (j=0;j<mode->nbEBands;j++)
213 printf ("%d ", allocVectors[i*mode->nbEBands+j]);
214 printf ("\n");
215 }
216 exit(0);*/
217
218 mode->allocVectors = allocVectors;
219}
220
221#endif /* CUSTOM_MODES */
222
223CELTMode *opus_custom_mode_create(opus_int32 Fs, int frame_size, int *error)
224{
225 int i;
226#ifdef CUSTOM_MODES
227 CELTMode *mode=NULL;
228 int res;
229 opus_val16 *window;
230 opus_int16 *logN;
231 int LM;
232 ALLOC_STACK;
233#if !defined(VAR_ARRAYS) && !defined(USE_ALLOCA)
234 if (global_stack==NULL)
235 goto failure;
236#endif
237#endif
238
239#ifndef CUSTOM_MODES_ONLY
240 for (i=0;i<TOTAL_MODES;i++)
241 {
242 int j;
243 for (j=0;j<4;j++)
244 {
245 if (Fs == static_mode_list[i]->Fs &&
246 (frame_size<<j) == static_mode_list[i]->shortMdctSize*static_mode_list[i]->nbShortMdcts)
247 {
248 if (error)
249 *error = OPUS_OK;
250 return (CELTMode*)static_mode_list[i];
251 }
252 }
253 }
254#endif /* CUSTOM_MODES_ONLY */
255
256#ifndef CUSTOM_MODES
257 if (error)
258 *error = OPUS_BAD_ARG;
259 return NULL;
260#else
261
262 /* The good thing here is that permutation of the arguments will automatically be invalid */
263
264 if (Fs < 8000 || Fs > 96000)
265 {
266 if (error)
267 *error = OPUS_BAD_ARG;
268 return NULL;
269 }
270 if (frame_size < 40 || frame_size > 1024 || frame_size%2!=0)
271 {
272 if (error)
273 *error = OPUS_BAD_ARG;
274 return NULL;
275 }
276 /* Frames of less than 1ms are not supported. */
277 if ((opus_int32)frame_size*1000 < Fs)
278 {
279 if (error)
280 *error = OPUS_BAD_ARG;
281 return NULL;
282 }
283
284 if ((opus_int32)frame_size*75 >= Fs && (frame_size%16)==0)
285 {
286 LM = 3;
287 } else if ((opus_int32)frame_size*150 >= Fs && (frame_size%8)==0)
288 {
289 LM = 2;
290 } else if ((opus_int32)frame_size*300 >= Fs && (frame_size%4)==0)
291 {
292 LM = 1;
293 } else
294 {
295 LM = 0;
296 }
297
298 /* Shorts longer than 3.3ms are not supported. */
299 if ((opus_int32)(frame_size>>LM)*300 > Fs)
300 {
301 if (error)
302 *error = OPUS_BAD_ARG;
303 return NULL;
304 }
305
306 mode = opus_alloc(sizeof(CELTMode));
307 if (mode==NULL)
308 goto failure;
309 mode->Fs = Fs;
310
311 /* Pre/de-emphasis depends on sampling rate. The "standard" pre-emphasis
312 is defined as A(z) = 1 - 0.85*z^-1 at 48 kHz. Other rates should
313 approximate that. */
314 if(Fs < 12000) /* 8 kHz */
315 {
316 mode->preemph[0] = QCONST16(0.3500061035f, 15);
317 mode->preemph[1] = -QCONST16(0.1799926758f, 15);
318 mode->preemph[2] = QCONST16(0.2719968125f, SIG_SHIFT); /* exact 1/preemph[3] */
319 mode->preemph[3] = QCONST16(3.6765136719f, 13);
320 } else if(Fs < 24000) /* 16 kHz */
321 {
322 mode->preemph[0] = QCONST16(0.6000061035f, 15);
323 mode->preemph[1] = -QCONST16(0.1799926758f, 15);
324 mode->preemph[2] = QCONST16(0.4424998650f, SIG_SHIFT); /* exact 1/preemph[3] */
325 mode->preemph[3] = QCONST16(2.2598876953f, 13);
326 } else if(Fs < 40000) /* 32 kHz */
327 {
328 mode->preemph[0] = QCONST16(0.7799987793f, 15);
329 mode->preemph[1] = -QCONST16(0.1000061035f, 15);
330 mode->preemph[2] = QCONST16(0.7499771125f, SIG_SHIFT); /* exact 1/preemph[3] */
331 mode->preemph[3] = QCONST16(1.3333740234f, 13);
332 } else /* 48 kHz */
333 {
334 mode->preemph[0] = QCONST16(0.8500061035f, 15);
335 mode->preemph[1] = QCONST16(0.0f, 15);
336 mode->preemph[2] = QCONST16(1.f, SIG_SHIFT);
337 mode->preemph[3] = QCONST16(1.f, 13);
338 }
339
340 mode->maxLM = LM;
341 mode->nbShortMdcts = 1<<LM;
342 mode->shortMdctSize = frame_size/mode->nbShortMdcts;
343 res = (mode->Fs+mode->shortMdctSize)/(2*mode->shortMdctSize);
344
345 mode->eBands = compute_ebands(Fs, mode->shortMdctSize, res, &mode->nbEBands);
346 if (mode->eBands==NULL)
347 goto failure;
348
349 mode->effEBands = mode->nbEBands;
350 while (mode->eBands[mode->effEBands] > mode->shortMdctSize)
351 mode->effEBands--;
352
353 /* Overlap must be divisible by 4 */
354 mode->overlap = ((mode->shortMdctSize>>2)<<2);
355
356 compute_allocation_table(mode);
357 if (mode->allocVectors==NULL)
358 goto failure;
359
360 window = (opus_val16*)opus_alloc(mode->overlap*sizeof(opus_val16));
361 if (window==NULL)
362 goto failure;
363
364#ifndef FIXED_POINT
365 for (i=0;i<mode->overlap;i++)
366 window[i] = Q15ONE*sin(.5*M_PI* sin(.5*M_PI*(i+.5)/mode->overlap) * sin(.5*M_PI*(i+.5)/mode->overlap));
367#else
368 for (i=0;i<mode->overlap;i++)
369 window[i] = MIN32(32767,floor(.5+32768.*sin(.5*M_PI* sin(.5*M_PI*(i+.5)/mode->overlap) * sin(.5*M_PI*(i+.5)/mode->overlap))));
370#endif
371 mode->window = window;
372
373 logN = (opus_int16*)opus_alloc(mode->nbEBands*sizeof(opus_int16));
374 if (logN==NULL)
375 goto failure;
376
377 for (i=0;i<mode->nbEBands;i++)
378 logN[i] = log2_frac(mode->eBands[i+1]-mode->eBands[i], BITRES);
379 mode->logN = logN;
380
381 compute_pulse_cache(mode, mode->maxLM);
382
383 if (clt_mdct_init(&mode->mdct, 2*mode->shortMdctSize*mode->nbShortMdcts,
384 mode->maxLM) == 0)
385 goto failure;
386
387 if (error)
388 *error = OPUS_OK;
389
390 return mode;
391failure:
392 if (error)
393 *error = OPUS_ALLOC_FAIL;
394 if (mode!=NULL)
395 opus_custom_mode_destroy(mode);
396 return NULL;
397#endif /* !CUSTOM_MODES */
398}
399
400#ifdef CUSTOM_MODES
401void opus_custom_mode_destroy(CELTMode *mode)
402{
403 if (mode == NULL)
404 return;
405#ifndef CUSTOM_MODES_ONLY
406 {
407 int i;
408 for (i=0;i<TOTAL_MODES;i++)
409 {
410 if (mode == static_mode_list[i])
411 {
412 return;
413 }
414 }
415 }
416#endif /* CUSTOM_MODES_ONLY */
417 opus_free((opus_int16*)mode->eBands);
418 opus_free((opus_int16*)mode->allocVectors);
419
420 opus_free((opus_val16*)mode->window);
421 opus_free((opus_int16*)mode->logN);
422
423 opus_free((opus_int16*)mode->cache.index);
424 opus_free((unsigned char*)mode->cache.bits);
425 opus_free((unsigned char*)mode->cache.caps);
426 clt_mdct_clear(&mode->mdct);
427
428 opus_free((CELTMode *)mode);
429}
430#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/modes.h b/lib/rbcodec/codecs/libopus/celt/modes.h
new file mode 100644
index 0000000000..c8340f9875
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/modes.h
@@ -0,0 +1,83 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2008 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30#ifndef MODES_H
31#define MODES_H
32
33#include "opus_types.h"
34#include "celt.h"
35#include "arch.h"
36#include "mdct.h"
37#include "entenc.h"
38#include "entdec.h"
39
40#define MAX_PERIOD 1024
41
42#ifndef OVERLAP
43#define OVERLAP(mode) ((mode)->overlap)
44#endif
45
46#ifndef FRAMESIZE
47#define FRAMESIZE(mode) ((mode)->mdctSize)
48#endif
49
50typedef struct {
51 int size;
52 const opus_int16 *index;
53 const unsigned char *bits;
54 const unsigned char *caps;
55} PulseCache;
56
57/** Mode definition (opaque)
58 @brief Mode definition
59 */
60struct OpusCustomMode {
61 opus_int32 Fs;
62 int overlap;
63
64 int nbEBands;
65 int effEBands;
66 opus_val16 preemph[4];
67 const opus_int16 *eBands; /**< Definition for each "pseudo-critical band" */
68
69 int maxLM;
70 int nbShortMdcts;
71 int shortMdctSize;
72
73 int nbAllocVectors; /**< Number of lines in the matrix below */
74 const unsigned char *allocVectors; /**< Number of bits in each band for several rates */
75 const opus_int16 *logN;
76
77 const opus_val16 *window;
78 mdct_lookup mdct;
79 PulseCache cache;
80};
81
82
83#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/os_support.h b/lib/rbcodec/codecs/libopus/celt/os_support.h
new file mode 100644
index 0000000000..2484f0b2f7
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/os_support.h
@@ -0,0 +1,89 @@
1/* Copyright (C) 2007 Jean-Marc Valin
2
3 File: os_support.h
4 This is the (tiny) OS abstraction layer. Aside from math.h, this is the
5 only place where system headers are allowed.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are
9 met:
10
11 1. Redistributions of source code must retain the above copyright notice,
12 this list of conditions and the following disclaimer.
13
14 2. Redistributions in binary form must reproduce the above copyright
15 notice, this list of conditions and the following disclaimer in the
16 documentation and/or other materials provided with the distribution.
17
18 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
22 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 POSSIBILITY OF SUCH DAMAGE.
29*/
30
31#ifndef OS_SUPPORT_H
32#define OS_SUPPORT_H
33
34#ifdef CUSTOM_SUPPORT
35# include "custom_support.h"
36#endif
37
38#include <string.h>
39#include <stdio.h>
40#include <stdlib.h>
41
42/** Opus wrapper for malloc(). To do your own dynamic allocation, all you need to do is replace this function and opus_free */
43#ifndef OVERRIDE_OPUS_ALLOC
44static inline void *opus_alloc (size_t size)
45{
46 return malloc(size);
47}
48#endif
49
50/** Same as celt_alloc(), except that the area is only needed inside a CELT call (might cause problem with wideband though) */
51#ifndef OVERRIDE_OPUS_ALLOC_SCRATCH
52static inline void *opus_alloc_scratch (size_t size)
53{
54 /* Scratch space doesn't need to be cleared */
55 return opus_alloc(size);
56}
57#endif
58
59/** Opus wrapper for free(). To do your own dynamic allocation, all you need to do is replace this function and opus_alloc */
60#ifndef OVERRIDE_OPUS_FREE
61static inline void opus_free (void *ptr)
62{
63 free(ptr);
64}
65#endif
66
67/** Copy n bytes of memory from src to dst. The 0* term provides compile-time type checking */
68#ifndef OVERRIDE_OPUS_COPY
69#define OPUS_COPY(dst, src, n) (memcpy((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
70#endif
71
72/** Copy n bytes of memory from src to dst, allowing overlapping regions. The 0* term
73 provides compile-time type checking */
74#ifndef OVERRIDE_OPUS_MOVE
75#define OPUS_MOVE(dst, src, n) (memmove((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
76#endif
77
78/** Set n elements of dst to zero, starting at address s */
79#ifndef OVERRIDE_OPUS_CLEAR
80#define OPUS_CLEAR(dst, n) (memset((dst), 0, (n)*sizeof(*(dst))))
81#endif
82
83/*#ifdef __GNUC__
84#pragma GCC poison printf sprintf
85#pragma GCC poison malloc free realloc calloc
86#endif*/
87
88#endif /* OS_SUPPORT_H */
89
diff --git a/lib/rbcodec/codecs/libopus/celt/pitch.c b/lib/rbcodec/codecs/libopus/celt/pitch.c
new file mode 100644
index 0000000000..3bad8e46a7
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/pitch.c
@@ -0,0 +1,410 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/**
5 @file pitch.c
6 @brief Pitch analysis
7 */
8
9/*
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions
12 are met:
13
14 - Redistributions of source code must retain the above copyright
15 notice, this list of conditions and the following disclaimer.
16
17 - Redistributions in binary form must reproduce the above copyright
18 notice, this list of conditions and the following disclaimer in the
19 documentation and/or other materials provided with the distribution.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
25 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32*/
33
34#ifdef HAVE_CONFIG_H
35#include "opus_config.h"
36#endif
37
38#include "pitch.h"
39#include "os_support.h"
40#include "modes.h"
41#include "stack_alloc.h"
42#include "mathops.h"
43#include "celt_lpc.h"
44
45static void find_best_pitch(opus_val32 *xcorr, opus_val16 *y, int len,
46 int max_pitch, int *best_pitch
47#ifdef FIXED_POINT
48 , int yshift, opus_val32 maxcorr
49#endif
50 )
51{
52 int i, j;
53 opus_val32 Syy=1;
54 opus_val16 best_num[2];
55 opus_val32 best_den[2];
56#ifdef FIXED_POINT
57 int xshift;
58
59 xshift = celt_ilog2(maxcorr)-14;
60#endif
61
62 best_num[0] = -1;
63 best_num[1] = -1;
64 best_den[0] = 0;
65 best_den[1] = 0;
66 best_pitch[0] = 0;
67 best_pitch[1] = 1;
68 for (j=0;j<len;j++)
69 Syy = ADD32(Syy, SHR32(MULT16_16(y[j],y[j]), yshift));
70 for (i=0;i<max_pitch;i++)
71 {
72 if (xcorr[i]>0)
73 {
74 opus_val16 num;
75 opus_val32 xcorr16;
76 xcorr16 = EXTRACT16(VSHR32(xcorr[i], xshift));
77#ifndef FIXED_POINT
78 /* Considering the range of xcorr16, this should avoid both underflows
79 and overflows (inf) when squaring xcorr16 */
80 xcorr16 *= 1e-12;
81#endif
82 num = MULT16_16_Q15(xcorr16,xcorr16);
83 if (MULT16_32_Q15(num,best_den[1]) > MULT16_32_Q15(best_num[1],Syy))
84 {
85 if (MULT16_32_Q15(num,best_den[0]) > MULT16_32_Q15(best_num[0],Syy))
86 {
87 best_num[1] = best_num[0];
88 best_den[1] = best_den[0];
89 best_pitch[1] = best_pitch[0];
90 best_num[0] = num;
91 best_den[0] = Syy;
92 best_pitch[0] = i;
93 } else {
94 best_num[1] = num;
95 best_den[1] = Syy;
96 best_pitch[1] = i;
97 }
98 }
99 }
100 Syy += SHR32(MULT16_16(y[i+len],y[i+len]),yshift) - SHR32(MULT16_16(y[i],y[i]),yshift);
101 Syy = MAX32(1, Syy);
102 }
103}
104
105void pitch_downsample(celt_sig * OPUS_RESTRICT x[], opus_val16 * OPUS_RESTRICT x_lp,
106 int len, int C)
107{
108 int i;
109 opus_val32 ac[5];
110 opus_val16 tmp=Q15ONE;
111 opus_val16 lpc[4], mem[4]={0,0,0,0};
112#ifdef FIXED_POINT
113 int shift;
114 opus_val32 maxabs = celt_maxabs32(x[0], len);
115 if (C==2)
116 {
117 opus_val32 maxabs_1 = celt_maxabs32(x[1], len);
118 maxabs = MAX32(maxabs, maxabs_1);
119 }
120 if (maxabs<1)
121 maxabs=1;
122 shift = celt_ilog2(maxabs)-10;
123 if (shift<0)
124 shift=0;
125 if (C==2)
126 shift++;
127#endif
128 for (i=1;i<len>>1;i++)
129 x_lp[i] = SHR32(HALF32(HALF32(x[0][(2*i-1)]+x[0][(2*i+1)])+x[0][2*i]), shift);
130 x_lp[0] = SHR32(HALF32(HALF32(x[0][1])+x[0][0]), shift);
131 if (C==2)
132 {
133 for (i=1;i<len>>1;i++)
134 x_lp[i] += SHR32(HALF32(HALF32(x[1][(2*i-1)]+x[1][(2*i+1)])+x[1][2*i]), shift);
135 x_lp[0] += SHR32(HALF32(HALF32(x[1][1])+x[1][0]), shift);
136 }
137
138 _celt_autocorr(x_lp, ac, NULL, 0,
139 4, len>>1);
140
141 /* Noise floor -40 dB */
142#ifdef FIXED_POINT
143 ac[0] += SHR32(ac[0],13);
144#else
145 ac[0] *= 1.0001f;
146#endif
147 /* Lag windowing */
148 for (i=1;i<=4;i++)
149 {
150 /*ac[i] *= exp(-.5*(2*M_PI*.002*i)*(2*M_PI*.002*i));*/
151#ifdef FIXED_POINT
152 ac[i] -= MULT16_32_Q15(2*i*i, ac[i]);
153#else
154 ac[i] -= ac[i]*(.008f*i)*(.008f*i);
155#endif
156 }
157
158 _celt_lpc(lpc, ac, 4);
159 for (i=0;i<4;i++)
160 {
161 tmp = MULT16_16_Q15(QCONST16(.9f,15), tmp);
162 lpc[i] = MULT16_16_Q15(lpc[i], tmp);
163 }
164 celt_fir(x_lp, lpc, x_lp, len>>1, 4, mem);
165
166 mem[0]=0;
167 lpc[0]=QCONST16(.8f,12);
168 celt_fir(x_lp, lpc, x_lp, len>>1, 1, mem);
169
170}
171
172void pitch_search(const opus_val16 * OPUS_RESTRICT x_lp, opus_val16 * OPUS_RESTRICT y,
173 int len, int max_pitch, int *pitch)
174{
175 int i, j;
176 int lag;
177 int best_pitch[2]={0,0};
178 VARDECL(opus_val16, x_lp4);
179 VARDECL(opus_val16, y_lp4);
180 VARDECL(opus_val32, xcorr);
181#ifdef FIXED_POINT
182 opus_val32 maxcorr=1;
183 opus_val16 xmax, ymax;
184 int shift=0;
185#endif
186 int offset;
187
188 SAVE_STACK;
189
190 celt_assert(len>0);
191 celt_assert(max_pitch>0);
192 lag = len+max_pitch;
193
194 ALLOC(x_lp4, len>>2, opus_val16);
195 ALLOC(y_lp4, lag>>2, opus_val16);
196 ALLOC(xcorr, max_pitch>>1, opus_val32);
197
198 /* Downsample by 2 again */
199 for (j=0;j<len>>2;j++)
200 x_lp4[j] = x_lp[2*j];
201 for (j=0;j<lag>>2;j++)
202 y_lp4[j] = y[2*j];
203
204#ifdef FIXED_POINT
205 xmax = celt_maxabs16(x_lp4, len>>2);
206 ymax = celt_maxabs16(y_lp4, lag>>2);
207 shift = celt_ilog2(MAX16(1, MAX16(xmax, ymax)))-11;
208 if (shift>0)
209 {
210 for (j=0;j<len>>2;j++)
211 x_lp4[j] = SHR16(x_lp4[j], shift);
212 for (j=0;j<lag>>2;j++)
213 y_lp4[j] = SHR16(y_lp4[j], shift);
214 /* Use double the shift for a MAC */
215 shift *= 2;
216 } else {
217 shift = 0;
218 }
219#endif
220
221 /* Coarse search with 4x decimation */
222
223 for (i=0;i<max_pitch>>2;i++)
224 {
225 opus_val32 sum = 0;
226 for (j=0;j<len>>2;j++)
227 sum = MAC16_16(sum, x_lp4[j],y_lp4[i+j]);
228 xcorr[i] = MAX32(-1, sum);
229#ifdef FIXED_POINT
230 maxcorr = MAX32(maxcorr, sum);
231#endif
232 }
233 find_best_pitch(xcorr, y_lp4, len>>2, max_pitch>>2, best_pitch
234#ifdef FIXED_POINT
235 , 0, maxcorr
236#endif
237 );
238
239 /* Finer search with 2x decimation */
240#ifdef FIXED_POINT
241 maxcorr=1;
242#endif
243 for (i=0;i<max_pitch>>1;i++)
244 {
245 opus_val32 sum=0;
246 xcorr[i] = 0;
247 if (abs(i-2*best_pitch[0])>2 && abs(i-2*best_pitch[1])>2)
248 continue;
249 for (j=0;j<len>>1;j++)
250 sum += SHR32(MULT16_16(x_lp[j],y[i+j]), shift);
251 xcorr[i] = MAX32(-1, sum);
252#ifdef FIXED_POINT
253 maxcorr = MAX32(maxcorr, sum);
254#endif
255 }
256 find_best_pitch(xcorr, y, len>>1, max_pitch>>1, best_pitch
257#ifdef FIXED_POINT
258 , shift+1, maxcorr
259#endif
260 );
261
262 /* Refine by pseudo-interpolation */
263 if (best_pitch[0]>0 && best_pitch[0]<(max_pitch>>1)-1)
264 {
265 opus_val32 a, b, c;
266 a = xcorr[best_pitch[0]-1];
267 b = xcorr[best_pitch[0]];
268 c = xcorr[best_pitch[0]+1];
269 if ((c-a) > MULT16_32_Q15(QCONST16(.7f,15),b-a))
270 offset = 1;
271 else if ((a-c) > MULT16_32_Q15(QCONST16(.7f,15),b-c))
272 offset = -1;
273 else
274 offset = 0;
275 } else {
276 offset = 0;
277 }
278 *pitch = 2*best_pitch[0]-offset;
279
280 RESTORE_STACK;
281}
282
283static const int second_check[16] = {0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2};
284opus_val16 remove_doubling(opus_val16 *x, int maxperiod, int minperiod,
285 int N, int *T0_, int prev_period, opus_val16 prev_gain)
286{
287 int k, i, T, T0;
288 opus_val16 g, g0;
289 opus_val16 pg;
290 opus_val32 xy,xx,yy;
291 opus_val32 xcorr[3];
292 opus_val32 best_xy, best_yy;
293 int offset;
294 int minperiod0;
295
296 minperiod0 = minperiod;
297 maxperiod /= 2;
298 minperiod /= 2;
299 *T0_ /= 2;
300 prev_period /= 2;
301 N /= 2;
302 x += maxperiod;
303 if (*T0_>=maxperiod)
304 *T0_=maxperiod-1;
305
306 T = T0 = *T0_;
307 xx=xy=yy=0;
308 for (i=0;i<N;i++)
309 {
310 xy = MAC16_16(xy, x[i], x[i-T0]);
311 xx = MAC16_16(xx, x[i], x[i]);
312 yy = MAC16_16(yy, x[i-T0],x[i-T0]);
313 }
314 best_xy = xy;
315 best_yy = yy;
316#ifdef FIXED_POINT
317 {
318 opus_val32 x2y2;
319 int sh, t;
320 x2y2 = 1+HALF32(MULT32_32_Q31(xx,yy));
321 sh = celt_ilog2(x2y2)>>1;
322 t = VSHR32(x2y2, 2*(sh-7));
323 g = g0 = VSHR32(MULT16_32_Q15(celt_rsqrt_norm(t), xy),sh+1);
324 }
325#else
326 g = g0 = xy/celt_sqrt(1+xx*yy);
327#endif
328 /* Look for any pitch at T/k */
329 for (k=2;k<=15;k++)
330 {
331 int T1, T1b;
332 opus_val16 g1;
333 opus_val16 cont=0;
334 T1 = (2*T0+k)/(2*k);
335 if (T1 < minperiod)
336 break;
337 /* Look for another strong correlation at T1b */
338 if (k==2)
339 {
340 if (T1+T0>maxperiod)
341 T1b = T0;
342 else
343 T1b = T0+T1;
344 } else
345 {
346 T1b = (2*second_check[k]*T0+k)/(2*k);
347 }
348 xy=yy=0;
349 for (i=0;i<N;i++)
350 {
351 xy = MAC16_16(xy, x[i], x[i-T1]);
352 yy = MAC16_16(yy, x[i-T1], x[i-T1]);
353
354 xy = MAC16_16(xy, x[i], x[i-T1b]);
355 yy = MAC16_16(yy, x[i-T1b], x[i-T1b]);
356 }
357#ifdef FIXED_POINT
358 {
359 opus_val32 x2y2;
360 int sh, t;
361 x2y2 = 1+MULT32_32_Q31(xx,yy);
362 sh = celt_ilog2(x2y2)>>1;
363 t = VSHR32(x2y2, 2*(sh-7));
364 g1 = VSHR32(MULT16_32_Q15(celt_rsqrt_norm(t), xy),sh+1);
365 }
366#else
367 g1 = xy/celt_sqrt(1+2.f*xx*1.f*yy);
368#endif
369 if (abs(T1-prev_period)<=1)
370 cont = prev_gain;
371 else if (abs(T1-prev_period)<=2 && 5*k*k < T0)
372 cont = HALF32(prev_gain);
373 else
374 cont = 0;
375 if (g1 > QCONST16(.3f,15) + MULT16_16_Q15(QCONST16(.4f,15),g0)-cont)
376 {
377 best_xy = xy;
378 best_yy = yy;
379 T = T1;
380 g = g1;
381 }
382 }
383 best_xy = MAX32(0, best_xy);
384 if (best_yy <= best_xy)
385 pg = Q15ONE;
386 else
387 pg = SHR32(frac_div32(best_xy,best_yy+1),16);
388
389 for (k=0;k<3;k++)
390 {
391 int T1 = T+k-1;
392 xy = 0;
393 for (i=0;i<N;i++)
394 xy = MAC16_16(xy, x[i], x[i-T1]);
395 xcorr[k] = xy;
396 }
397 if ((xcorr[2]-xcorr[0]) > MULT16_32_Q15(QCONST16(.7f,15),xcorr[1]-xcorr[0]))
398 offset = 1;
399 else if ((xcorr[0]-xcorr[2]) > MULT16_32_Q15(QCONST16(.7f,15),xcorr[1]-xcorr[2]))
400 offset = -1;
401 else
402 offset = 0;
403 if (pg > g)
404 pg = g;
405 *T0_ = 2*T+offset;
406
407 if (*T0_<minperiod0)
408 *T0_=minperiod0;
409 return pg;
410}
diff --git a/lib/rbcodec/codecs/libopus/celt/pitch.h b/lib/rbcodec/codecs/libopus/celt/pitch.h
new file mode 100644
index 0000000000..2757071a6f
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/pitch.h
@@ -0,0 +1,48 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/**
5 @file pitch.h
6 @brief Pitch analysis
7 */
8
9/*
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions
12 are met:
13
14 - Redistributions of source code must retain the above copyright
15 notice, this list of conditions and the following disclaimer.
16
17 - Redistributions in binary form must reproduce the above copyright
18 notice, this list of conditions and the following disclaimer in the
19 documentation and/or other materials provided with the distribution.
20
21 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
25 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32*/
33
34#ifndef PITCH_H
35#define PITCH_H
36
37#include "modes.h"
38
39void pitch_downsample(celt_sig * OPUS_RESTRICT x[], opus_val16 * OPUS_RESTRICT x_lp,
40 int len, int C);
41
42void pitch_search(const opus_val16 * OPUS_RESTRICT x_lp, opus_val16 * OPUS_RESTRICT y,
43 int len, int max_pitch, int *pitch);
44
45opus_val16 remove_doubling(opus_val16 *x, int maxperiod, int minperiod,
46 int N, int *T0, int prev_period, opus_val16 prev_gain);
47
48#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/quant_bands.c b/lib/rbcodec/codecs/libopus/celt/quant_bands.c
new file mode 100644
index 0000000000..5ad5311f84
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/quant_bands.c
@@ -0,0 +1,567 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29#ifdef HAVE_CONFIG_H
30#include "opus_config.h"
31#endif
32
33#include "quant_bands.h"
34#include "laplace.h"
35#include <math.h>
36#include "os_support.h"
37#include "arch.h"
38#include "mathops.h"
39#include "stack_alloc.h"
40#include "rate.h"
41
42#ifdef FIXED_POINT
43/* Mean energy in each band quantized in Q6 */
44static const signed char eMeans[25] = {
45 103,100, 92, 85, 81,
46 77, 72, 70, 78, 75,
47 73, 71, 78, 74, 69,
48 72, 70, 74, 76, 71,
49 60, 60, 60, 60, 60
50};
51#else
52/* Mean energy in each band quantized in Q6 and converted back to float */
53static const opus_val16 eMeans[25] = {
54 6.437500f, 6.250000f, 5.750000f, 5.312500f, 5.062500f,
55 4.812500f, 4.500000f, 4.375000f, 4.875000f, 4.687500f,
56 4.562500f, 4.437500f, 4.875000f, 4.625000f, 4.312500f,
57 4.500000f, 4.375000f, 4.625000f, 4.750000f, 4.437500f,
58 3.750000f, 3.750000f, 3.750000f, 3.750000f, 3.750000f
59};
60#endif
61/* prediction coefficients: 0.9, 0.8, 0.65, 0.5 */
62#ifdef FIXED_POINT
63static const opus_val16 pred_coef[4] = {29440, 26112, 21248, 16384};
64static const opus_val16 beta_coef[4] = {30147, 22282, 12124, 6554};
65static const opus_val16 beta_intra = 4915;
66#else
67static const opus_val16 pred_coef[4] = {29440/32768., 26112/32768., 21248/32768., 16384/32768.};
68static const opus_val16 beta_coef[4] = {30147/32768., 22282/32768., 12124/32768., 6554/32768.};
69static const opus_val16 beta_intra = 4915/32768.;
70#endif
71
72/*Parameters of the Laplace-like probability models used for the coarse energy.
73 There is one pair of parameters for each frame size, prediction type
74 (inter/intra), and band number.
75 The first number of each pair is the probability of 0, and the second is the
76 decay rate, both in Q8 precision.*/
77static const unsigned char e_prob_model[4][2][42] = {
78 /*120 sample frames.*/
79 {
80 /*Inter*/
81 {
82 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128,
83 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, 116, 41, 115, 40,
84 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11
85 },
86 /*Intra*/
87 {
88 24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132,
89 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66,
90 91, 67, 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50
91 }
92 },
93 /*240 sample frames.*/
94 {
95 /*Inter*/
96 {
97 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74,
98 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18,
99 146, 19, 162, 12, 165, 10, 178, 7, 189, 6, 190, 8, 177, 9
100 },
101 /*Intra*/
102 {
103 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91,
104 73, 91, 78, 89, 86, 80, 92, 66, 93, 64, 102, 59, 103, 60,
105 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45
106 }
107 },
108 /*480 sample frames.*/
109 {
110 /*Inter*/
111 {
112 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38,
113 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, 155, 14, 159, 16,
114 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10
115 },
116 /*Intra*/
117 {
118 21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73,
119 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55,
120 112, 56, 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42
121 }
122 },
123 /*960 sample frames.*/
124 {
125 /*Inter*/
126 {
127 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36,
128 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25,
129 154, 26, 166, 21, 173, 16, 184, 13, 184, 10, 150, 13, 139, 15
130 },
131 /*Intra*/
132 {
133 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72,
134 96, 67, 101, 73, 107, 72, 113, 55, 118, 52, 125, 52, 118, 52,
135 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40
136 }
137 }
138};
139
140static const unsigned char small_energy_icdf[3]={2,1,0};
141
142static opus_val32 loss_distortion(const opus_val16 *eBands, opus_val16 *oldEBands, int start, int end, int len, int C)
143{
144 int c, i;
145 opus_val32 dist = 0;
146 c=0; do {
147 for (i=start;i<end;i++)
148 {
149 opus_val16 d = SUB16(SHR16(eBands[i+c*len], 3), SHR16(oldEBands[i+c*len], 3));
150 dist = MAC16_16(dist, d,d);
151 }
152 } while (++c<C);
153 return MIN32(200,SHR32(dist,2*DB_SHIFT-6));
154}
155
156static int quant_coarse_energy_impl(const CELTMode *m, int start, int end,
157 const opus_val16 *eBands, opus_val16 *oldEBands,
158 opus_int32 budget, opus_int32 tell,
159 const unsigned char *prob_model, opus_val16 *error, ec_enc *enc,
160 int C, int LM, int intra, opus_val16 max_decay)
161{
162 int i, c;
163 int badness = 0;
164 opus_val32 prev[2] = {0,0};
165 opus_val16 coef;
166 opus_val16 beta;
167
168 if (tell+3 <= budget)
169 ec_enc_bit_logp(enc, intra, 3);
170 if (intra)
171 {
172 coef = 0;
173 beta = beta_intra;
174 } else {
175 beta = beta_coef[LM];
176 coef = pred_coef[LM];
177 }
178
179 /* Encode at a fixed coarse resolution */
180 for (i=start;i<end;i++)
181 {
182 c=0;
183 do {
184 int bits_left;
185 int qi, qi0;
186 opus_val32 q;
187 opus_val16 x;
188 opus_val32 f, tmp;
189 opus_val16 oldE;
190 opus_val16 decay_bound;
191 x = eBands[i+c*m->nbEBands];
192 oldE = MAX16(-QCONST16(9.f,DB_SHIFT), oldEBands[i+c*m->nbEBands]);
193#ifdef FIXED_POINT
194 f = SHL32(EXTEND32(x),7) - PSHR32(MULT16_16(coef,oldE), 8) - prev[c];
195 /* Rounding to nearest integer here is really important! */
196 qi = (f+QCONST32(.5f,DB_SHIFT+7))>>(DB_SHIFT+7);
197 decay_bound = EXTRACT16(MAX32(-QCONST16(28.f,DB_SHIFT),
198 SUB32((opus_val32)oldEBands[i+c*m->nbEBands],max_decay)));
199#else
200 f = x-coef*oldE-prev[c];
201 /* Rounding to nearest integer here is really important! */
202 qi = (int)floor(.5f+f);
203 decay_bound = MAX16(-QCONST16(28.f,DB_SHIFT), oldEBands[i+c*m->nbEBands]) - max_decay;
204#endif
205 /* Prevent the energy from going down too quickly (e.g. for bands
206 that have just one bin) */
207 if (qi < 0 && x < decay_bound)
208 {
209 qi += (int)SHR16(SUB16(decay_bound,x), DB_SHIFT);
210 if (qi > 0)
211 qi = 0;
212 }
213 qi0 = qi;
214 /* If we don't have enough bits to encode all the energy, just assume
215 something safe. */
216 tell = ec_tell(enc);
217 bits_left = budget-tell-3*C*(end-i);
218 if (i!=start && bits_left < 30)
219 {
220 if (bits_left < 24)
221 qi = IMIN(1, qi);
222 if (bits_left < 16)
223 qi = IMAX(-1, qi);
224 }
225 if (budget-tell >= 15)
226 {
227 int pi;
228 pi = 2*IMIN(i,20);
229 ec_laplace_encode(enc, &qi,
230 prob_model[pi]<<7, prob_model[pi+1]<<6);
231 }
232 else if(budget-tell >= 2)
233 {
234 qi = IMAX(-1, IMIN(qi, 1));
235 ec_enc_icdf(enc, 2*qi^-(qi<0), small_energy_icdf, 2);
236 }
237 else if(budget-tell >= 1)
238 {
239 qi = IMIN(0, qi);
240 ec_enc_bit_logp(enc, -qi, 1);
241 }
242 else
243 qi = -1;
244 error[i+c*m->nbEBands] = PSHR32(f,7) - SHL16(qi,DB_SHIFT);
245 badness += abs(qi0-qi);
246 q = (opus_val32)SHL32(EXTEND32(qi),DB_SHIFT);
247
248 tmp = PSHR32(MULT16_16(coef,oldE),8) + prev[c] + SHL32(q,7);
249#ifdef FIXED_POINT
250 tmp = MAX32(-QCONST32(28.f, DB_SHIFT+7), tmp);
251#endif
252 oldEBands[i+c*m->nbEBands] = PSHR32(tmp, 7);
253 prev[c] = prev[c] + SHL32(q,7) - MULT16_16(beta,PSHR32(q,8));
254 } while (++c < C);
255 }
256 return badness;
257}
258
259void quant_coarse_energy(const CELTMode *m, int start, int end, int effEnd,
260 const opus_val16 *eBands, opus_val16 *oldEBands, opus_uint32 budget,
261 opus_val16 *error, ec_enc *enc, int C, int LM, int nbAvailableBytes,
262 int force_intra, opus_val32 *delayedIntra, int two_pass, int loss_rate)
263{
264 int intra;
265 opus_val16 max_decay;
266 VARDECL(opus_val16, oldEBands_intra);
267 VARDECL(opus_val16, error_intra);
268 ec_enc enc_start_state;
269 opus_uint32 tell;
270 int badness1=0;
271 opus_int32 intra_bias;
272 opus_val32 new_distortion;
273 SAVE_STACK;
274
275 intra = force_intra || (!two_pass && *delayedIntra>2*C*(end-start) && nbAvailableBytes > (end-start)*C);
276 intra_bias = (opus_int32)((budget**delayedIntra*loss_rate)/(C*512));
277 new_distortion = loss_distortion(eBands, oldEBands, start, effEnd, m->nbEBands, C);
278
279 tell = ec_tell(enc);
280 if (tell+3 > budget)
281 two_pass = intra = 0;
282
283 /* Encode the global flags using a simple probability model
284 (first symbols in the stream) */
285
286#ifdef FIXED_POINT
287 max_decay = MIN32(QCONST16(16.f,DB_SHIFT), SHL32(EXTEND32(nbAvailableBytes),DB_SHIFT-3));
288#else
289 max_decay = MIN32(16.f, .125f*nbAvailableBytes);
290#endif
291
292 enc_start_state = *enc;
293
294 ALLOC(oldEBands_intra, C*m->nbEBands, opus_val16);
295 ALLOC(error_intra, C*m->nbEBands, opus_val16);
296 OPUS_COPY(oldEBands_intra, oldEBands, C*m->nbEBands);
297
298 if (two_pass || intra)
299 {
300 badness1 = quant_coarse_energy_impl(m, start, end, eBands, oldEBands_intra, budget,
301 tell, e_prob_model[LM][1], error_intra, enc, C, LM, 1, max_decay);
302 }
303
304 if (!intra)
305 {
306 unsigned char *intra_buf;
307 ec_enc enc_intra_state;
308 opus_int32 tell_intra;
309 opus_uint32 nstart_bytes;
310 opus_uint32 nintra_bytes;
311 int badness2;
312 VARDECL(unsigned char, intra_bits);
313
314 tell_intra = ec_tell_frac(enc);
315
316 enc_intra_state = *enc;
317
318 nstart_bytes = ec_range_bytes(&enc_start_state);
319 nintra_bytes = ec_range_bytes(&enc_intra_state);
320 intra_buf = ec_get_buffer(&enc_intra_state) + nstart_bytes;
321 ALLOC(intra_bits, nintra_bytes-nstart_bytes, unsigned char);
322 /* Copy bits from intra bit-stream */
323 OPUS_COPY(intra_bits, intra_buf, nintra_bytes - nstart_bytes);
324
325 *enc = enc_start_state;
326
327 badness2 = quant_coarse_energy_impl(m, start, end, eBands, oldEBands, budget,
328 tell, e_prob_model[LM][intra], error, enc, C, LM, 0, max_decay);
329
330 if (two_pass && (badness1 < badness2 || (badness1 == badness2 && ((opus_int32)ec_tell_frac(enc))+intra_bias > tell_intra)))
331 {
332 *enc = enc_intra_state;
333 /* Copy intra bits to bit-stream */
334 OPUS_COPY(intra_buf, intra_bits, nintra_bytes - nstart_bytes);
335 OPUS_COPY(oldEBands, oldEBands_intra, C*m->nbEBands);
336 OPUS_COPY(error, error_intra, C*m->nbEBands);
337 intra = 1;
338 }
339 } else {
340 OPUS_COPY(oldEBands, oldEBands_intra, C*m->nbEBands);
341 OPUS_COPY(error, error_intra, C*m->nbEBands);
342 }
343
344 if (intra)
345 *delayedIntra = new_distortion;
346 else
347 *delayedIntra = ADD32(MULT16_32_Q15(MULT16_16_Q15(pred_coef[LM], pred_coef[LM]),*delayedIntra),
348 new_distortion);
349
350 RESTORE_STACK;
351}
352
353void quant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, ec_enc *enc, int C)
354{
355 int i, c;
356
357 /* Encode finer resolution */
358 for (i=start;i<end;i++)
359 {
360 opus_int16 frac = 1<<fine_quant[i];
361 if (fine_quant[i] <= 0)
362 continue;
363 c=0;
364 do {
365 int q2;
366 opus_val16 offset;
367#ifdef FIXED_POINT
368 /* Has to be without rounding */
369 q2 = (error[i+c*m->nbEBands]+QCONST16(.5f,DB_SHIFT))>>(DB_SHIFT-fine_quant[i]);
370#else
371 q2 = (int)floor((error[i+c*m->nbEBands]+.5f)*frac);
372#endif
373 if (q2 > frac-1)
374 q2 = frac-1;
375 if (q2<0)
376 q2 = 0;
377 ec_enc_bits(enc, q2, fine_quant[i]);
378#ifdef FIXED_POINT
379 offset = SUB16(SHR32(SHL32(EXTEND32(q2),DB_SHIFT)+QCONST16(.5f,DB_SHIFT),fine_quant[i]),QCONST16(.5f,DB_SHIFT));
380#else
381 offset = (q2+.5f)*(1<<(14-fine_quant[i]))*(1.f/16384) - .5f;
382#endif
383 oldEBands[i+c*m->nbEBands] += offset;
384 error[i+c*m->nbEBands] -= offset;
385 /*printf ("%f ", error[i] - offset);*/
386 } while (++c < C);
387 }
388}
389
390void quant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, int *fine_priority, int bits_left, ec_enc *enc, int C)
391{
392 int i, prio, c;
393
394 /* Use up the remaining bits */
395 for (prio=0;prio<2;prio++)
396 {
397 for (i=start;i<end && bits_left>=C ;i++)
398 {
399 if (fine_quant[i] >= MAX_FINE_BITS || fine_priority[i]!=prio)
400 continue;
401 c=0;
402 do {
403 int q2;
404 opus_val16 offset;
405 q2 = error[i+c*m->nbEBands]<0 ? 0 : 1;
406 ec_enc_bits(enc, q2, 1);
407#ifdef FIXED_POINT
408 offset = SHR16(SHL16(q2,DB_SHIFT)-QCONST16(.5f,DB_SHIFT),fine_quant[i]+1);
409#else
410 offset = (q2-.5f)*(1<<(14-fine_quant[i]-1))*(1.f/16384);
411#endif
412 oldEBands[i+c*m->nbEBands] += offset;
413 bits_left--;
414 } while (++c < C);
415 }
416 }
417}
418
419void unquant_coarse_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int intra, ec_dec *dec, int C, int LM)
420{
421 const unsigned char *prob_model = e_prob_model[LM][intra];
422 int i, c;
423 opus_val32 prev[2] = {0, 0};
424 opus_val16 coef;
425 opus_val16 beta;
426 opus_int32 budget;
427 opus_int32 tell;
428
429 if (intra)
430 {
431 coef = 0;
432 beta = beta_intra;
433 } else {
434 beta = beta_coef[LM];
435 coef = pred_coef[LM];
436 }
437
438 budget = dec->storage*8;
439
440 /* Decode at a fixed coarse resolution */
441 for (i=start;i<end;i++)
442 {
443 c=0;
444 do {
445 int qi;
446 opus_val32 q;
447 opus_val32 tmp;
448 /* It would be better to express this invariant as a
449 test on C at function entry, but that isn't enough
450 to make the static analyzer happy. */
451 celt_assert(c<2);
452 tell = ec_tell(dec);
453 if(budget-tell>=15)
454 {
455 int pi;
456 pi = 2*IMIN(i,20);
457 qi = ec_laplace_decode(dec,
458 prob_model[pi]<<7, prob_model[pi+1]<<6);
459 }
460 else if(budget-tell>=2)
461 {
462 qi = ec_dec_icdf(dec, small_energy_icdf, 2);
463 qi = (qi>>1)^-(qi&1);
464 }
465 else if(budget-tell>=1)
466 {
467 qi = -ec_dec_bit_logp(dec, 1);
468 }
469 else
470 qi = -1;
471 q = (opus_val32)SHL32(EXTEND32(qi),DB_SHIFT);
472
473 oldEBands[i+c*m->nbEBands] = MAX16(-QCONST16(9.f,DB_SHIFT), oldEBands[i+c*m->nbEBands]);
474 tmp = PSHR32(MULT16_16(coef,oldEBands[i+c*m->nbEBands]),8) + prev[c] + SHL32(q,7);
475#ifdef FIXED_POINT
476 tmp = MAX32(-QCONST32(28.f, DB_SHIFT+7), tmp);
477#endif
478 oldEBands[i+c*m->nbEBands] = PSHR32(tmp, 7);
479 prev[c] = prev[c] + SHL32(q,7) - MULT16_16(beta,PSHR32(q,8));
480 } while (++c < C);
481 }
482}
483
484void unquant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant, ec_dec *dec, int C)
485{
486 int i, c;
487 /* Decode finer resolution */
488 for (i=start;i<end;i++)
489 {
490 if (fine_quant[i] <= 0)
491 continue;
492 c=0;
493 do {
494 int q2;
495 opus_val16 offset;
496 q2 = ec_dec_bits(dec, fine_quant[i]);
497#ifdef FIXED_POINT
498 offset = SUB16(SHR32(SHL32(EXTEND32(q2),DB_SHIFT)+QCONST16(.5f,DB_SHIFT),fine_quant[i]),QCONST16(.5f,DB_SHIFT));
499#else
500 offset = (q2+.5f)*(1<<(14-fine_quant[i]))*(1.f/16384) - .5f;
501#endif
502 oldEBands[i+c*m->nbEBands] += offset;
503 } while (++c < C);
504 }
505}
506
507void unquant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant, int *fine_priority, int bits_left, ec_dec *dec, int C)
508{
509 int i, prio, c;
510
511 /* Use up the remaining bits */
512 for (prio=0;prio<2;prio++)
513 {
514 for (i=start;i<end && bits_left>=C ;i++)
515 {
516 if (fine_quant[i] >= MAX_FINE_BITS || fine_priority[i]!=prio)
517 continue;
518 c=0;
519 do {
520 int q2;
521 opus_val16 offset;
522 q2 = ec_dec_bits(dec, 1);
523#ifdef FIXED_POINT
524 offset = SHR16(SHL16(q2,DB_SHIFT)-QCONST16(.5f,DB_SHIFT),fine_quant[i]+1);
525#else
526 offset = (q2-.5f)*(1<<(14-fine_quant[i]-1))*(1.f/16384);
527#endif
528 oldEBands[i+c*m->nbEBands] += offset;
529 bits_left--;
530 } while (++c < C);
531 }
532 }
533}
534
535void log2Amp(const CELTMode *m, int start, int end,
536 celt_ener *eBands, const opus_val16 *oldEBands, int C)
537{
538 int c, i;
539 c=0;
540 do {
541 for (i=0;i<start;i++)
542 eBands[i+c*m->nbEBands] = 0;
543 for (;i<end;i++)
544 {
545 opus_val16 lg = ADD16(oldEBands[i+c*m->nbEBands],
546 SHL16((opus_val16)eMeans[i],6));
547 eBands[i+c*m->nbEBands] = PSHR32(celt_exp2(lg),4);
548 }
549 for (;i<m->nbEBands;i++)
550 eBands[i+c*m->nbEBands] = 0;
551 } while (++c < C);
552}
553
554void amp2Log2(const CELTMode *m, int effEnd, int end,
555 celt_ener *bandE, opus_val16 *bandLogE, int C)
556{
557 int c, i;
558 c=0;
559 do {
560 for (i=0;i<effEnd;i++)
561 bandLogE[i+c*m->nbEBands] =
562 celt_log2(SHL32(bandE[i+c*m->nbEBands],2))
563 - SHL16((opus_val16)eMeans[i],6);
564 for (i=effEnd;i<end;i++)
565 bandLogE[c*m->nbEBands+i] = -QCONST16(14.f,DB_SHIFT);
566 } while (++c < C);
567}
diff --git a/lib/rbcodec/codecs/libopus/celt/quant_bands.h b/lib/rbcodec/codecs/libopus/celt/quant_bands.h
new file mode 100644
index 0000000000..bec2855cf0
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/quant_bands.h
@@ -0,0 +1,60 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29#ifndef QUANT_BANDS
30#define QUANT_BANDS
31
32#include "arch.h"
33#include "modes.h"
34#include "entenc.h"
35#include "entdec.h"
36#include "mathops.h"
37
38void amp2Log2(const CELTMode *m, int effEnd, int end,
39 celt_ener *bandE, opus_val16 *bandLogE, int C);
40
41void log2Amp(const CELTMode *m, int start, int end,
42 celt_ener *eBands, const opus_val16 *oldEBands, int C);
43
44void quant_coarse_energy(const CELTMode *m, int start, int end, int effEnd,
45 const opus_val16 *eBands, opus_val16 *oldEBands, opus_uint32 budget,
46 opus_val16 *error, ec_enc *enc, int C, int LM,
47 int nbAvailableBytes, int force_intra, opus_val32 *delayedIntra,
48 int two_pass, int loss_rate);
49
50void quant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, ec_enc *enc, int C);
51
52void quant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, opus_val16 *error, int *fine_quant, int *fine_priority, int bits_left, ec_enc *enc, int C);
53
54void unquant_coarse_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int intra, ec_dec *dec, int C, int LM);
55
56void unquant_fine_energy(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant, ec_dec *dec, int C);
57
58void unquant_energy_finalise(const CELTMode *m, int start, int end, opus_val16 *oldEBands, int *fine_quant, int *fine_priority, int bits_left, ec_dec *dec, int C);
59
60#endif /* QUANT_BANDS */
diff --git a/lib/rbcodec/codecs/libopus/celt/rate.c b/lib/rbcodec/codecs/libopus/celt/rate.c
new file mode 100644
index 0000000000..3b056d8dc7
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/rate.c
@@ -0,0 +1,638 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29#ifdef HAVE_CONFIG_H
30#include "opus_config.h"
31#endif
32
33#include <math.h>
34#include "modes.h"
35#include "cwrs.h"
36#include "arch.h"
37#include "os_support.h"
38
39#include "entcode.h"
40#include "rate.h"
41
42static const unsigned char LOG2_FRAC_TABLE[24]={
43 0,
44 8,13,
45 16,19,21,23,
46 24,26,27,28,29,30,31,32,
47 32,33,34,34,35,36,36,37,37
48};
49
50#ifdef CUSTOM_MODES
51
52/*Determines if V(N,K) fits in a 32-bit unsigned integer.
53 N and K are themselves limited to 15 bits.*/
54static int fits_in32(int _n, int _k)
55{
56 static const opus_int16 maxN[15] = {
57 32767, 32767, 32767, 1476, 283, 109, 60, 40,
58 29, 24, 20, 18, 16, 14, 13};
59 static const opus_int16 maxK[15] = {
60 32767, 32767, 32767, 32767, 1172, 238, 95, 53,
61 36, 27, 22, 18, 16, 15, 13};
62 if (_n>=14)
63 {
64 if (_k>=14)
65 return 0;
66 else
67 return _n <= maxN[_k];
68 } else {
69 return _k <= maxK[_n];
70 }
71}
72
73void compute_pulse_cache(CELTMode *m, int LM)
74{
75 int C;
76 int i;
77 int j;
78 int curr=0;
79 int nbEntries=0;
80 int entryN[100], entryK[100], entryI[100];
81 const opus_int16 *eBands = m->eBands;
82 PulseCache *cache = &m->cache;
83 opus_int16 *cindex;
84 unsigned char *bits;
85 unsigned char *cap;
86
87 cindex = (opus_int16 *)opus_alloc(sizeof(cache->index[0])*m->nbEBands*(LM+2));
88 cache->index = cindex;
89
90 /* Scan for all unique band sizes */
91 for (i=0;i<=LM+1;i++)
92 {
93 for (j=0;j<m->nbEBands;j++)
94 {
95 int k;
96 int N = (eBands[j+1]-eBands[j])<<i>>1;
97 cindex[i*m->nbEBands+j] = -1;
98 /* Find other bands that have the same size */
99 for (k=0;k<=i;k++)
100 {
101 int n;
102 for (n=0;n<m->nbEBands && (k!=i || n<j);n++)
103 {
104 if (N == (eBands[n+1]-eBands[n])<<k>>1)
105 {
106 cindex[i*m->nbEBands+j] = cindex[k*m->nbEBands+n];
107 break;
108 }
109 }
110 }
111 if (cache->index[i*m->nbEBands+j] == -1 && N!=0)
112 {
113 int K;
114 entryN[nbEntries] = N;
115 K = 0;
116 while (fits_in32(N,get_pulses(K+1)) && K<MAX_PSEUDO)
117 K++;
118 entryK[nbEntries] = K;
119 cindex[i*m->nbEBands+j] = curr;
120 entryI[nbEntries] = curr;
121
122 curr += K+1;
123 nbEntries++;
124 }
125 }
126 }
127 bits = (unsigned char *)opus_alloc(sizeof(unsigned char)*curr);
128 cache->bits = bits;
129 cache->size = curr;
130 /* Compute the cache for all unique sizes */
131 for (i=0;i<nbEntries;i++)
132 {
133 unsigned char *ptr = bits+entryI[i];
134 opus_int16 tmp[MAX_PULSES+1];
135 get_required_bits(tmp, entryN[i], get_pulses(entryK[i]), BITRES);
136 for (j=1;j<=entryK[i];j++)
137 ptr[j] = tmp[get_pulses(j)]-1;
138 ptr[0] = entryK[i];
139 }
140
141 /* Compute the maximum rate for each band at which we'll reliably use as
142 many bits as we ask for. */
143 cache->caps = cap = (unsigned char *)opus_alloc(sizeof(cache->caps[0])*(LM+1)*2*m->nbEBands);
144 for (i=0;i<=LM;i++)
145 {
146 for (C=1;C<=2;C++)
147 {
148 for (j=0;j<m->nbEBands;j++)
149 {
150 int N0;
151 int max_bits;
152 N0 = m->eBands[j+1]-m->eBands[j];
153 /* N=1 bands only have a sign bit and fine bits. */
154 if (N0<<i == 1)
155 max_bits = C*(1+MAX_FINE_BITS)<<BITRES;
156 else
157 {
158 const unsigned char *pcache;
159 opus_int32 num;
160 opus_int32 den;
161 int LM0;
162 int N;
163 int offset;
164 int ndof;
165 int qb;
166 int k;
167 LM0 = 0;
168 /* Even-sized bands bigger than N=2 can be split one more time.
169 As of commit 44203907 all bands >1 are even, including custom modes.*/
170 if (N0 > 2)
171 {
172 N0>>=1;
173 LM0--;
174 }
175 /* N0=1 bands can't be split down to N<2. */
176 else if (N0 <= 1)
177 {
178 LM0=IMIN(i,1);
179 N0<<=LM0;
180 }
181 /* Compute the cost for the lowest-level PVQ of a fully split
182 band. */
183 pcache = bits + cindex[(LM0+1)*m->nbEBands+j];
184 max_bits = pcache[pcache[0]]+1;
185 /* Add in the cost of coding regular splits. */
186 N = N0;
187 for(k=0;k<i-LM0;k++){
188 max_bits <<= 1;
189 /* Offset the number of qtheta bits by log2(N)/2
190 + QTHETA_OFFSET compared to their "fair share" of
191 total/N */
192 offset = ((m->logN[j]+((LM0+k)<<BITRES))>>1)-QTHETA_OFFSET;
193 /* The number of qtheta bits we'll allocate if the remainder
194 is to be max_bits.
195 The average measured cost for theta is 0.89701 times qb,
196 approximated here as 459/512. */
197 num=459*(opus_int32)((2*N-1)*offset+max_bits);
198 den=((opus_int32)(2*N-1)<<9)-459;
199 qb = IMIN((num+(den>>1))/den, 57);
200 celt_assert(qb >= 0);
201 max_bits += qb;
202 N <<= 1;
203 }
204 /* Add in the cost of a stereo split, if necessary. */
205 if (C==2)
206 {
207 max_bits <<= 1;
208 offset = ((m->logN[j]+(i<<BITRES))>>1)-(N==2?QTHETA_OFFSET_TWOPHASE:QTHETA_OFFSET);
209 ndof = 2*N-1-(N==2);
210 /* The average measured cost for theta with the step PDF is
211 0.95164 times qb, approximated here as 487/512. */
212 num = (N==2?512:487)*(opus_int32)(max_bits+ndof*offset);
213 den = ((opus_int32)ndof<<9)-(N==2?512:487);
214 qb = IMIN((num+(den>>1))/den, (N==2?64:61));
215 celt_assert(qb >= 0);
216 max_bits += qb;
217 }
218 /* Add the fine bits we'll use. */
219 /* Compensate for the extra DoF in stereo */
220 ndof = C*N + ((C==2 && N>2) ? 1 : 0);
221 /* Offset the number of fine bits by log2(N)/2 + FINE_OFFSET
222 compared to their "fair share" of total/N */
223 offset = ((m->logN[j] + (i<<BITRES))>>1)-FINE_OFFSET;
224 /* N=2 is the only point that doesn't match the curve */
225 if (N==2)
226 offset += 1<<BITRES>>2;
227 /* The number of fine bits we'll allocate if the remainder is
228 to be max_bits. */
229 num = max_bits+ndof*offset;
230 den = (ndof-1)<<BITRES;
231 qb = IMIN((num+(den>>1))/den, MAX_FINE_BITS);
232 celt_assert(qb >= 0);
233 max_bits += C*qb<<BITRES;
234 }
235 max_bits = (4*max_bits/(C*((m->eBands[j+1]-m->eBands[j])<<i)))-64;
236 celt_assert(max_bits >= 0);
237 celt_assert(max_bits < 256);
238 *cap++ = (unsigned char)max_bits;
239 }
240 }
241 }
242}
243
244#endif /* CUSTOM_MODES */
245
246#define ALLOC_STEPS 6
247
248static inline int interp_bits2pulses(const CELTMode *m, int start, int end, int skip_start,
249 const int *bits1, const int *bits2, const int *thresh, const int *cap, opus_int32 total, opus_int32 *_balance,
250 int skip_rsv, int *intensity, int intensity_rsv, int *dual_stereo, int dual_stereo_rsv, int *bits,
251 int *ebits, int *fine_priority, int C, int LM, ec_ctx *ec, int encode, int prev)
252{
253 opus_int32 psum;
254 int lo, hi;
255 int i, j;
256 int logM;
257 int stereo;
258 int codedBands=-1;
259 int alloc_floor;
260 opus_int32 left, percoeff;
261 int done;
262 opus_int32 balance;
263 SAVE_STACK;
264
265 alloc_floor = C<<BITRES;
266 stereo = C>1;
267
268 logM = LM<<BITRES;
269 lo = 0;
270 hi = 1<<ALLOC_STEPS;
271 for (i=0;i<ALLOC_STEPS;i++)
272 {
273 int mid = (lo+hi)>>1;
274 psum = 0;
275 done = 0;
276 for (j=end;j-->start;)
277 {
278 int tmp = bits1[j] + (mid*(opus_int32)bits2[j]>>ALLOC_STEPS);
279 if (tmp >= thresh[j] || done)
280 {
281 done = 1;
282 /* Don't allocate more than we can actually use */
283 psum += IMIN(tmp, cap[j]);
284 } else {
285 if (tmp >= alloc_floor)
286 psum += alloc_floor;
287 }
288 }
289 if (psum > total)
290 hi = mid;
291 else
292 lo = mid;
293 }
294 psum = 0;
295 /*printf ("interp bisection gave %d\n", lo);*/
296 done = 0;
297 for (j=end;j-->start;)
298 {
299 int tmp = bits1[j] + (lo*bits2[j]>>ALLOC_STEPS);
300 if (tmp < thresh[j] && !done)
301 {
302 if (tmp >= alloc_floor)
303 tmp = alloc_floor;
304 else
305 tmp = 0;
306 } else
307 done = 1;
308 /* Don't allocate more than we can actually use */
309 tmp = IMIN(tmp, cap[j]);
310 bits[j] = tmp;
311 psum += tmp;
312 }
313
314 /* Decide which bands to skip, working backwards from the end. */
315 for (codedBands=end;;codedBands--)
316 {
317 int band_width;
318 int band_bits;
319 int rem;
320 j = codedBands-1;
321 /* Never skip the first band, nor a band that has been boosted by
322 dynalloc.
323 In the first case, we'd be coding a bit to signal we're going to waste
324 all the other bits.
325 In the second case, we'd be coding a bit to redistribute all the bits
326 we just signaled should be cocentrated in this band. */
327 if (j<=skip_start)
328 {
329 /* Give the bit we reserved to end skipping back. */
330 total += skip_rsv;
331 break;
332 }
333 /*Figure out how many left-over bits we would be adding to this band.
334 This can include bits we've stolen back from higher, skipped bands.*/
335 left = total-psum;
336 percoeff = left/(m->eBands[codedBands]-m->eBands[start]);
337 left -= (m->eBands[codedBands]-m->eBands[start])*percoeff;
338 rem = IMAX(left-(m->eBands[j]-m->eBands[start]),0);
339 band_width = m->eBands[codedBands]-m->eBands[j];
340 band_bits = (int)(bits[j] + percoeff*band_width + rem);
341 /*Only code a skip decision if we're above the threshold for this band.
342 Otherwise it is force-skipped.
343 This ensures that we have enough bits to code the skip flag.*/
344 if (band_bits >= IMAX(thresh[j], alloc_floor+(1<<BITRES)))
345 {
346 if (encode)
347 {
348 /*This if() block is the only part of the allocation function that
349 is not a mandatory part of the bitstream: any bands we choose to
350 skip here must be explicitly signaled.*/
351 /*Choose a threshold with some hysteresis to keep bands from
352 fluctuating in and out.*/
353#ifdef FUZZING
354 if ((rand()&0x1) == 0)
355#else
356 if (band_bits > ((j<prev?7:9)*band_width<<LM<<BITRES)>>4)
357#endif
358 {
359 ec_enc_bit_logp(ec, 1, 1);
360 break;
361 }
362 ec_enc_bit_logp(ec, 0, 1);
363 } else if (ec_dec_bit_logp(ec, 1)) {
364 break;
365 }
366 /*We used a bit to skip this band.*/
367 psum += 1<<BITRES;
368 band_bits -= 1<<BITRES;
369 }
370 /*Reclaim the bits originally allocated to this band.*/
371 psum -= bits[j]+intensity_rsv;
372 if (intensity_rsv > 0)
373 intensity_rsv = LOG2_FRAC_TABLE[j-start];
374 psum += intensity_rsv;
375 if (band_bits >= alloc_floor)
376 {
377 /*If we have enough for a fine energy bit per channel, use it.*/
378 psum += alloc_floor;
379 bits[j] = alloc_floor;
380 } else {
381 /*Otherwise this band gets nothing at all.*/
382 bits[j] = 0;
383 }
384 }
385
386 celt_assert(codedBands > start);
387 /* Code the intensity and dual stereo parameters. */
388 if (intensity_rsv > 0)
389 {
390 if (encode)
391 {
392 *intensity = IMIN(*intensity, codedBands);
393 ec_enc_uint(ec, *intensity-start, codedBands+1-start);
394 }
395 else
396 *intensity = start+ec_dec_uint(ec, codedBands+1-start);
397 }
398 else
399 *intensity = 0;
400 if (*intensity <= start)
401 {
402 total += dual_stereo_rsv;
403 dual_stereo_rsv = 0;
404 }
405 if (dual_stereo_rsv > 0)
406 {
407 if (encode)
408 ec_enc_bit_logp(ec, *dual_stereo, 1);
409 else
410 *dual_stereo = ec_dec_bit_logp(ec, 1);
411 }
412 else
413 *dual_stereo = 0;
414
415 /* Allocate the remaining bits */
416 left = total-psum;
417 percoeff = left/(m->eBands[codedBands]-m->eBands[start]);
418 left -= (m->eBands[codedBands]-m->eBands[start])*percoeff;
419 for (j=start;j<codedBands;j++)
420 bits[j] += ((int)percoeff*(m->eBands[j+1]-m->eBands[j]));
421 for (j=start;j<codedBands;j++)
422 {
423 int tmp = (int)IMIN(left, m->eBands[j+1]-m->eBands[j]);
424 bits[j] += tmp;
425 left -= tmp;
426 }
427 /*for (j=0;j<end;j++)printf("%d ", bits[j]);printf("\n");*/
428
429 balance = 0;
430 for (j=start;j<codedBands;j++)
431 {
432 int N0, N, den;
433 int offset;
434 int NClogN;
435 opus_int32 excess, bit;
436
437 celt_assert(bits[j] >= 0);
438 N0 = m->eBands[j+1]-m->eBands[j];
439 N=N0<<LM;
440 bit = (opus_int32)bits[j]+balance;
441
442 if (N>1)
443 {
444 excess = MAX32(bit-cap[j],0);
445 bits[j] = bit-excess;
446
447 /* Compensate for the extra DoF in stereo */
448 den=(C*N+ ((C==2 && N>2 && !*dual_stereo && j<*intensity) ? 1 : 0));
449
450 NClogN = den*(m->logN[j] + logM);
451
452 /* Offset for the number of fine bits by log2(N)/2 + FINE_OFFSET
453 compared to their "fair share" of total/N */
454 offset = (NClogN>>1)-den*FINE_OFFSET;
455
456 /* N=2 is the only point that doesn't match the curve */
457 if (N==2)
458 offset += den<<BITRES>>2;
459
460 /* Changing the offset for allocating the second and third
461 fine energy bit */
462 if (bits[j] + offset < den*2<<BITRES)
463 offset += NClogN>>2;
464 else if (bits[j] + offset < den*3<<BITRES)
465 offset += NClogN>>3;
466
467 /* Divide with rounding */
468 ebits[j] = IMAX(0, (bits[j] + offset + (den<<(BITRES-1))) / (den<<BITRES));
469
470 /* Make sure not to bust */
471 if (C*ebits[j] > (bits[j]>>BITRES))
472 ebits[j] = bits[j] >> stereo >> BITRES;
473
474 /* More than that is useless because that's about as far as PVQ can go */
475 ebits[j] = IMIN(ebits[j], MAX_FINE_BITS);
476
477 /* If we rounded down or capped this band, make it a candidate for the
478 final fine energy pass */
479 fine_priority[j] = ebits[j]*(den<<BITRES) >= bits[j]+offset;
480
481 /* Remove the allocated fine bits; the rest are assigned to PVQ */
482 bits[j] -= C*ebits[j]<<BITRES;
483
484 } else {
485 /* For N=1, all bits go to fine energy except for a single sign bit */
486 excess = MAX32(0,bit-(C<<BITRES));
487 bits[j] = bit-excess;
488 ebits[j] = 0;
489 fine_priority[j] = 1;
490 }
491
492 /* Fine energy can't take advantage of the re-balancing in
493 quant_all_bands().
494 Instead, do the re-balancing here.*/
495 if(excess > 0)
496 {
497 int extra_fine;
498 int extra_bits;
499 extra_fine = IMIN(excess>>(stereo+BITRES),MAX_FINE_BITS-ebits[j]);
500 ebits[j] += extra_fine;
501 extra_bits = extra_fine*C<<BITRES;
502 fine_priority[j] = extra_bits >= excess-balance;
503 excess -= extra_bits;
504 }
505 balance = excess;
506
507 celt_assert(bits[j] >= 0);
508 celt_assert(ebits[j] >= 0);
509 }
510 /* Save any remaining bits over the cap for the rebalancing in
511 quant_all_bands(). */
512 *_balance = balance;
513
514 /* The skipped bands use all their bits for fine energy. */
515 for (;j<end;j++)
516 {
517 ebits[j] = bits[j] >> stereo >> BITRES;
518 celt_assert(C*ebits[j]<<BITRES == bits[j]);
519 bits[j] = 0;
520 fine_priority[j] = ebits[j]<1;
521 }
522 RESTORE_STACK;
523 return codedBands;
524}
525
526int compute_allocation(const CELTMode *m, int start, int end, const int *offsets, const int *cap, int alloc_trim, int *intensity, int *dual_stereo,
527 opus_int32 total, opus_int32 *balance, int *pulses, int *ebits, int *fine_priority, int C, int LM, ec_ctx *ec, int encode, int prev)
528{
529 int lo, hi, len, j;
530 int codedBands;
531 int skip_start;
532 int skip_rsv;
533 int intensity_rsv;
534 int dual_stereo_rsv;
535 VARDECL(int, bits1);
536 VARDECL(int, bits2);
537 VARDECL(int, thresh);
538 VARDECL(int, trim_offset);
539 SAVE_STACK;
540
541 total = IMAX(total, 0);
542 len = m->nbEBands;
543 skip_start = start;
544 /* Reserve a bit to signal the end of manually skipped bands. */
545 skip_rsv = total >= 1<<BITRES ? 1<<BITRES : 0;
546 total -= skip_rsv;
547 /* Reserve bits for the intensity and dual stereo parameters. */
548 intensity_rsv = dual_stereo_rsv = 0;
549 if (C==2)
550 {
551 intensity_rsv = LOG2_FRAC_TABLE[end-start];
552 if (intensity_rsv>total)
553 intensity_rsv = 0;
554 else
555 {
556 total -= intensity_rsv;
557 dual_stereo_rsv = total>=1<<BITRES ? 1<<BITRES : 0;
558 total -= dual_stereo_rsv;
559 }
560 }
561 ALLOC(bits1, len, int);
562 ALLOC(bits2, len, int);
563 ALLOC(thresh, len, int);
564 ALLOC(trim_offset, len, int);
565
566 for (j=start;j<end;j++)
567 {
568 /* Below this threshold, we're sure not to allocate any PVQ bits */
569 thresh[j] = IMAX((C)<<BITRES, (3*(m->eBands[j+1]-m->eBands[j])<<LM<<BITRES)>>4);
570 /* Tilt of the allocation curve */
571 trim_offset[j] = C*(m->eBands[j+1]-m->eBands[j])*(alloc_trim-5-LM)*(end-j-1)
572 *(1<<(LM+BITRES))>>6;
573 /* Giving less resolution to single-coefficient bands because they get
574 more benefit from having one coarse value per coefficient*/
575 if ((m->eBands[j+1]-m->eBands[j])<<LM==1)
576 trim_offset[j] -= C<<BITRES;
577 }
578 lo = 1;
579 hi = m->nbAllocVectors - 1;
580 do
581 {
582 int done = 0;
583 int psum = 0;
584 int mid = (lo+hi) >> 1;
585 for (j=end;j-->start;)
586 {
587 int bitsj;
588 int N = m->eBands[j+1]-m->eBands[j];
589 bitsj = C*N*m->allocVectors[mid*len+j]<<LM>>2;
590 if (bitsj > 0)
591 bitsj = IMAX(0, bitsj + trim_offset[j]);
592 bitsj += offsets[j];
593 if (bitsj >= thresh[j] || done)
594 {
595 done = 1;
596 /* Don't allocate more than we can actually use */
597 psum += IMIN(bitsj, cap[j]);
598 } else {
599 if (bitsj >= C<<BITRES)
600 psum += C<<BITRES;
601 }
602 }
603 if (psum > total)
604 hi = mid - 1;
605 else
606 lo = mid + 1;
607 /*printf ("lo = %d, hi = %d\n", lo, hi);*/
608 }
609 while (lo <= hi);
610 hi = lo--;
611 /*printf ("interp between %d and %d\n", lo, hi);*/
612 for (j=start;j<end;j++)
613 {
614 int bits1j, bits2j;
615 int N = m->eBands[j+1]-m->eBands[j];
616 bits1j = C*N*m->allocVectors[lo*len+j]<<LM>>2;
617 bits2j = hi>=m->nbAllocVectors ?
618 cap[j] : C*N*m->allocVectors[hi*len+j]<<LM>>2;
619 if (bits1j > 0)
620 bits1j = IMAX(0, bits1j + trim_offset[j]);
621 if (bits2j > 0)
622 bits2j = IMAX(0, bits2j + trim_offset[j]);
623 if (lo > 0)
624 bits1j += offsets[j];
625 bits2j += offsets[j];
626 if (offsets[j]>0)
627 skip_start = j;
628 bits2j = IMAX(0,bits2j-bits1j);
629 bits1[j] = bits1j;
630 bits2[j] = bits2j;
631 }
632 codedBands = interp_bits2pulses(m, start, end, skip_start, bits1, bits2, thresh, cap,
633 total, balance, skip_rsv, intensity, intensity_rsv, dual_stereo, dual_stereo_rsv,
634 pulses, ebits, fine_priority, C, LM, ec, encode, prev);
635 RESTORE_STACK;
636 return codedBands;
637}
638
diff --git a/lib/rbcodec/codecs/libopus/celt/rate.h b/lib/rbcodec/codecs/libopus/celt/rate.h
new file mode 100644
index 0000000000..e0d5022326
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/rate.h
@@ -0,0 +1,101 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29#ifndef RATE_H
30#define RATE_H
31
32#define MAX_PSEUDO 40
33#define LOG_MAX_PSEUDO 6
34
35#define MAX_PULSES 128
36
37#define MAX_FINE_BITS 8
38
39#define FINE_OFFSET 21
40#define QTHETA_OFFSET 4
41#define QTHETA_OFFSET_TWOPHASE 16
42
43#include "cwrs.h"
44#include "modes.h"
45
46void compute_pulse_cache(CELTMode *m, int LM);
47
48static inline int get_pulses(int i)
49{
50 return i<8 ? i : (8 + (i&7)) << ((i>>3)-1);
51}
52
53static inline int bits2pulses(const CELTMode *m, int band, int LM, int bits)
54{
55 int i;
56 int lo, hi;
57 const unsigned char *cache;
58
59 LM++;
60 cache = m->cache.bits + m->cache.index[LM*m->nbEBands+band];
61
62 lo = 0;
63 hi = cache[0];
64 bits--;
65 for (i=0;i<LOG_MAX_PSEUDO;i++)
66 {
67 int mid = (lo+hi+1)>>1;
68 /* OPT: Make sure this is implemented with a conditional move */
69 if ((int)cache[mid] >= bits)
70 hi = mid;
71 else
72 lo = mid;
73 }
74 if (bits- (lo == 0 ? -1 : (int)cache[lo]) <= (int)cache[hi]-bits)
75 return lo;
76 else
77 return hi;
78}
79
80static inline int pulses2bits(const CELTMode *m, int band, int LM, int pulses)
81{
82 const unsigned char *cache;
83
84 LM++;
85 cache = m->cache.bits + m->cache.index[LM*m->nbEBands+band];
86 return pulses == 0 ? 0 : cache[pulses]+1;
87}
88
89/** Compute the pulse allocation, i.e. how many pulses will go in each
90 * band.
91 @param m mode
92 @param offsets Requested increase or decrease in the number of bits for
93 each band
94 @param total Number of bands
95 @param pulses Number of pulses per band (returned)
96 @return Total number of bits allocated
97*/
98int compute_allocation(const CELTMode *m, int start, int end, const int *offsets, const int *cap, int alloc_trim, int *intensity, int *dual_stero,
99 opus_int32 total, opus_int32 *balance, int *pulses, int *ebits, int *fine_priority, int C, int LM, ec_ctx *ec, int encode, int prev);
100
101#endif
diff --git a/lib/rbcodec/codecs/libopus/celt/stack_alloc.h b/lib/rbcodec/codecs/libopus/celt/stack_alloc.h
new file mode 100644
index 0000000000..a6f06d2263
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/stack_alloc.h
@@ -0,0 +1,149 @@
1/* Copyright (C) 2002-2003 Jean-Marc Valin
2 Copyright (C) 2007-2009 Xiph.Org Foundation */
3/**
4 @file stack_alloc.h
5 @brief Temporary memory allocation on stack
6*/
7/*
8 Redistribution and use in source and binary forms, with or without
9 modification, are permitted provided that the following conditions
10 are met:
11
12 - Redistributions of source code must retain the above copyright
13 notice, this list of conditions and the following disclaimer.
14
15 - Redistributions in binary form must reproduce the above copyright
16 notice, this list of conditions and the following disclaimer in the
17 documentation and/or other materials provided with the distribution.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
23 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30*/
31
32#ifndef STACK_ALLOC_H
33#define STACK_ALLOC_H
34
35#if (!defined (VAR_ARRAYS) && !defined (USE_ALLOCA) && !defined (NONTHREADSAFE_PSEUDOSTACK))
36#error "Opus requires one of VAR_ARRAYS, USE_ALLOCA, or NONTHREADSAFE_PSEUDOSTACK be defined to select the temporary allocation mode."
37#endif
38
39#ifdef USE_ALLOCA
40# ifdef WIN32
41# include <malloc.h>
42# else
43# ifdef HAVE_ALLOCA_H
44# include <alloca.h>
45# else
46# include <stdlib.h>
47# endif
48# endif
49#endif
50
51/**
52 * @def ALIGN(stack, size)
53 *
54 * Aligns the stack to a 'size' boundary
55 *
56 * @param stack Stack
57 * @param size New size boundary
58 */
59
60/**
61 * @def PUSH(stack, size, type)
62 *
63 * Allocates 'size' elements of type 'type' on the stack
64 *
65 * @param stack Stack
66 * @param size Number of elements
67 * @param type Type of element
68 */
69
70/**
71 * @def VARDECL(var)
72 *
73 * Declare variable on stack
74 *
75 * @param var Variable to declare
76 */
77
78/**
79 * @def ALLOC(var, size, type)
80 *
81 * Allocate 'size' elements of 'type' on stack
82 *
83 * @param var Name of variable to allocate
84 * @param size Number of elements
85 * @param type Type of element
86 */
87
88#if defined(VAR_ARRAYS)
89
90#define VARDECL(type, var)
91#define ALLOC(var, size, type) type var[size]
92#define SAVE_STACK
93#define RESTORE_STACK
94#define ALLOC_STACK
95
96#elif defined(USE_ALLOCA)
97
98#define VARDECL(type, var) type *var
99
100# ifdef WIN32
101# define ALLOC(var, size, type) var = ((type*)_alloca(sizeof(type)*(size)))
102# else
103# define ALLOC(var, size, type) var = ((type*)alloca(sizeof(type)*(size)))
104# endif
105
106#define SAVE_STACK
107#define RESTORE_STACK
108#define ALLOC_STACK
109
110#else
111
112#ifdef CELT_C
113char *global_stack=0;
114#else
115extern char *global_stack;
116#endif /* CELT_C */
117
118#ifdef ENABLE_VALGRIND
119
120#include <valgrind/memcheck.h>
121
122#ifdef CELT_C
123char *global_stack_top=0;
124#else
125extern char *global_stack_top;
126#endif /* CELT_C */
127
128#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1))
129#define PUSH(stack, size, type) (VALGRIND_MAKE_MEM_NOACCESS(stack, global_stack_top-stack),ALIGN((stack),sizeof(type)/sizeof(char)),VALGRIND_MAKE_MEM_UNDEFINED(stack, ((size)*sizeof(type)/sizeof(char))),(stack)+=(2*(size)*sizeof(type)/sizeof(char)),(type*)((stack)-(2*(size)*sizeof(type)/sizeof(char))))
130#define RESTORE_STACK ((global_stack = _saved_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack))
131#define ALLOC_STACK char *_saved_stack; ((global_stack = (global_stack==0) ? ((global_stack_top=opus_alloc_scratch(GLOBAL_STACK_SIZE*2)+(GLOBAL_STACK_SIZE*2))-(GLOBAL_STACK_SIZE*2)) : global_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack)); _saved_stack = global_stack;
132
133#else
134
135#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1))
136#define PUSH(stack, size, type) (ALIGN((stack),sizeof(type)/sizeof(char)),(stack)+=(size)*(sizeof(type)/sizeof(char)),(type*)((stack)-(size)*(sizeof(type)/sizeof(char))))
137#define RESTORE_STACK (global_stack = _saved_stack)
138#define ALLOC_STACK char *_saved_stack; (global_stack = (global_stack==0) ? opus_alloc_scratch(GLOBAL_STACK_SIZE) : global_stack); _saved_stack = global_stack;
139
140#endif /* ENABLE_VALGRIND */
141
142#include "os_support.h"
143#define VARDECL(type, var) type *var
144#define ALLOC(var, size, type) var = PUSH(global_stack, size, type)
145#define SAVE_STACK char *_saved_stack = global_stack;
146
147#endif /* VAR_ARRAYS */
148
149#endif /* STACK_ALLOC_H */
diff --git a/lib/rbcodec/codecs/libopus/celt/static_modes_fixed.h b/lib/rbcodec/codecs/libopus/celt/static_modes_fixed.h
new file mode 100644
index 0000000000..216df9e605
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/static_modes_fixed.h
@@ -0,0 +1,595 @@
1/* The contents of this file was automatically generated by dump_modes.c
2 with arguments: 48000 960
3 It contains static definitions for some pre-defined modes. */
4#include "modes.h"
5#include "rate.h"
6
7#ifndef DEF_WINDOW120
8#define DEF_WINDOW120
9static const opus_val16 window120[120] = {
102, 20, 55, 108, 178,
11266, 372, 494, 635, 792,
12966, 1157, 1365, 1590, 1831,
132089, 2362, 2651, 2956, 3276,
143611, 3961, 4325, 4703, 5094,
155499, 5916, 6346, 6788, 7241,
167705, 8179, 8663, 9156, 9657,
1710167, 10684, 11207, 11736, 12271,
1812810, 13353, 13899, 14447, 14997,
1915547, 16098, 16648, 17197, 17744,
2018287, 18827, 19363, 19893, 20418,
2120936, 21447, 21950, 22445, 22931,
2223407, 23874, 24330, 24774, 25208,
2325629, 26039, 26435, 26819, 27190,
2427548, 27893, 28224, 28541, 28845,
2529135, 29411, 29674, 29924, 30160,
2630384, 30594, 30792, 30977, 31151,
2731313, 31463, 31602, 31731, 31849,
2831958, 32057, 32148, 32229, 32303,
2932370, 32429, 32481, 32528, 32568,
3032604, 32634, 32661, 32683, 32701,
3132717, 32729, 32740, 32748, 32754,
3232758, 32762, 32764, 32766, 32767,
3332767, 32767, 32767, 32767, 32767,
34};
35#endif
36
37#ifndef DEF_LOGN400
38#define DEF_LOGN400
39static const opus_int16 logN400[21] = {
400, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36, };
41#endif
42
43#ifndef DEF_PULSE_CACHE50
44#define DEF_PULSE_CACHE50
45static const opus_int16 cache_index50[105] = {
46-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41,
4782, 82, 123, 164, 200, 222, 0, 0, 0, 0, 0, 0, 0, 0, 41,
4841, 41, 41, 123, 123, 123, 164, 164, 240, 266, 283, 295, 41, 41, 41,
4941, 41, 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305,
50318, 328, 336, 123, 123, 123, 123, 123, 123, 123, 123, 240, 240, 240, 240,
51305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240,
52240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, 387,
53};
54static const unsigned char cache_bits50[392] = {
5540, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
567, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
577, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 40, 15, 23, 28,
5831, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50,
5951, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62, 63, 63, 65,
6066, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61,
6164, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92,
6294, 96, 98, 101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123,
63124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94,
6497, 100, 102, 105, 107, 111, 115, 118, 121, 124, 126, 129, 131, 135, 139,
65142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35,
6628, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149,
67153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, 216, 220, 225,
68229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157,
69166, 174, 182, 189, 195, 201, 207, 217, 227, 235, 243, 251, 17, 35, 63,
7086, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250,
7125, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161, 168, 174, 180,
72185, 190, 200, 208, 215, 222, 229, 235, 240, 245, 255, 16, 36, 65, 89,
73110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41,
7474, 103, 128, 151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138,
75163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214,
76228, 241, 253, 9, 44, 81, 113, 142, 168, 192, 214, 235, 255, 7, 49,
7790, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7, 47,
7887, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57,
79106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187,
80224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175, 224, 4, 67, 127,
81182, 234, };
82static const unsigned char cache_caps50[168] = {
83224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185,
84178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240,
85240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160,
86160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172,
87138, 64, 38, 240, 240, 240, 240, 240, 240, 240, 240, 207, 207, 207, 207,
88204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185,
89185, 185, 193, 193, 193, 193, 193, 193, 193, 183, 183, 172, 138, 65, 39,
90207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201,
91188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193,
92193, 193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204,
93204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175,
94140, 66, 40, };
95#endif
96
97#ifndef FFT_TWIDDLES48000_960
98#define FFT_TWIDDLES48000_960
99static const kiss_twiddle_cpx fft_twiddles48000_960[480] = {
100{32767, 0}, {32766, -429},
101{32757, -858}, {32743, -1287},
102{32724, -1715}, {32698, -2143},
103{32667, -2570}, {32631, -2998},
104{32588, -3425}, {32541, -3851},
105{32488, -4277}, {32429, -4701},
106{32364, -5125}, {32295, -5548},
107{32219, -5971}, {32138, -6393},
108{32051, -6813}, {31960, -7231},
109{31863, -7650}, {31760, -8067},
110{31652, -8481}, {31539, -8895},
111{31419, -9306}, {31294, -9716},
112{31165, -10126}, {31030, -10532},
113{30889, -10937}, {30743, -11340},
114{30592, -11741}, {30436, -12141},
115{30274, -12540}, {30107, -12935},
116{29936, -13328}, {29758, -13718},
117{29577, -14107}, {29390, -14493},
118{29197, -14875}, {29000, -15257},
119{28797, -15635}, {28590, -16010},
120{28379, -16384}, {28162, -16753},
121{27940, -17119}, {27714, -17484},
122{27482, -17845}, {27246, -18205},
123{27006, -18560}, {26760, -18911},
124{26510, -19260}, {26257, -19606},
125{25997, -19947}, {25734, -20286},
126{25466, -20621}, {25194, -20952},
127{24918, -21281}, {24637, -21605},
128{24353, -21926}, {24063, -22242},
129{23770, -22555}, {23473, -22865},
130{23171, -23171}, {22866, -23472},
131{22557, -23769}, {22244, -24063},
132{21927, -24352}, {21606, -24636},
133{21282, -24917}, {20954, -25194},
134{20622, -25465}, {20288, -25733},
135{19949, -25997}, {19607, -26255},
136{19261, -26509}, {18914, -26760},
137{18561, -27004}, {18205, -27246},
138{17846, -27481}, {17485, -27713},
139{17122, -27940}, {16755, -28162},
140{16385, -28378}, {16012, -28590},
141{15636, -28797}, {15258, -28999},
142{14878, -29197}, {14494, -29389},
143{14108, -29576}, {13720, -29757},
144{13329, -29934}, {12937, -30107},
145{12540, -30274}, {12142, -30435},
146{11744, -30592}, {11342, -30743},
147{10939, -30889}, {10534, -31030},
148{10127, -31164}, {9718, -31294},
149{9307, -31418}, {8895, -31537},
150{8482, -31652}, {8067, -31759},
151{7650, -31862}, {7233, -31960},
152{6815, -32051}, {6393, -32138},
153{5973, -32219}, {5549, -32294},
154{5127, -32364}, {4703, -32429},
155{4278, -32487}, {3852, -32541},
156{3426, -32588}, {2999, -32630},
157{2572, -32667}, {2144, -32698},
158{1716, -32724}, {1287, -32742},
159{860, -32757}, {430, -32766},
160{0, -32767}, {-429, -32766},
161{-858, -32757}, {-1287, -32743},
162{-1715, -32724}, {-2143, -32698},
163{-2570, -32667}, {-2998, -32631},
164{-3425, -32588}, {-3851, -32541},
165{-4277, -32488}, {-4701, -32429},
166{-5125, -32364}, {-5548, -32295},
167{-5971, -32219}, {-6393, -32138},
168{-6813, -32051}, {-7231, -31960},
169{-7650, -31863}, {-8067, -31760},
170{-8481, -31652}, {-8895, -31539},
171{-9306, -31419}, {-9716, -31294},
172{-10126, -31165}, {-10532, -31030},
173{-10937, -30889}, {-11340, -30743},
174{-11741, -30592}, {-12141, -30436},
175{-12540, -30274}, {-12935, -30107},
176{-13328, -29936}, {-13718, -29758},
177{-14107, -29577}, {-14493, -29390},
178{-14875, -29197}, {-15257, -29000},
179{-15635, -28797}, {-16010, -28590},
180{-16384, -28379}, {-16753, -28162},
181{-17119, -27940}, {-17484, -27714},
182{-17845, -27482}, {-18205, -27246},
183{-18560, -27006}, {-18911, -26760},
184{-19260, -26510}, {-19606, -26257},
185{-19947, -25997}, {-20286, -25734},
186{-20621, -25466}, {-20952, -25194},
187{-21281, -24918}, {-21605, -24637},
188{-21926, -24353}, {-22242, -24063},
189{-22555, -23770}, {-22865, -23473},
190{-23171, -23171}, {-23472, -22866},
191{-23769, -22557}, {-24063, -22244},
192{-24352, -21927}, {-24636, -21606},
193{-24917, -21282}, {-25194, -20954},
194{-25465, -20622}, {-25733, -20288},
195{-25997, -19949}, {-26255, -19607},
196{-26509, -19261}, {-26760, -18914},
197{-27004, -18561}, {-27246, -18205},
198{-27481, -17846}, {-27713, -17485},
199{-27940, -17122}, {-28162, -16755},
200{-28378, -16385}, {-28590, -16012},
201{-28797, -15636}, {-28999, -15258},
202{-29197, -14878}, {-29389, -14494},
203{-29576, -14108}, {-29757, -13720},
204{-29934, -13329}, {-30107, -12937},
205{-30274, -12540}, {-30435, -12142},
206{-30592, -11744}, {-30743, -11342},
207{-30889, -10939}, {-31030, -10534},
208{-31164, -10127}, {-31294, -9718},
209{-31418, -9307}, {-31537, -8895},
210{-31652, -8482}, {-31759, -8067},
211{-31862, -7650}, {-31960, -7233},
212{-32051, -6815}, {-32138, -6393},
213{-32219, -5973}, {-32294, -5549},
214{-32364, -5127}, {-32429, -4703},
215{-32487, -4278}, {-32541, -3852},
216{-32588, -3426}, {-32630, -2999},
217{-32667, -2572}, {-32698, -2144},
218{-32724, -1716}, {-32742, -1287},
219{-32757, -860}, {-32766, -430},
220{-32767, 0}, {-32766, 429},
221{-32757, 858}, {-32743, 1287},
222{-32724, 1715}, {-32698, 2143},
223{-32667, 2570}, {-32631, 2998},
224{-32588, 3425}, {-32541, 3851},
225{-32488, 4277}, {-32429, 4701},
226{-32364, 5125}, {-32295, 5548},
227{-32219, 5971}, {-32138, 6393},
228{-32051, 6813}, {-31960, 7231},
229{-31863, 7650}, {-31760, 8067},
230{-31652, 8481}, {-31539, 8895},
231{-31419, 9306}, {-31294, 9716},
232{-31165, 10126}, {-31030, 10532},
233{-30889, 10937}, {-30743, 11340},
234{-30592, 11741}, {-30436, 12141},
235{-30274, 12540}, {-30107, 12935},
236{-29936, 13328}, {-29758, 13718},
237{-29577, 14107}, {-29390, 14493},
238{-29197, 14875}, {-29000, 15257},
239{-28797, 15635}, {-28590, 16010},
240{-28379, 16384}, {-28162, 16753},
241{-27940, 17119}, {-27714, 17484},
242{-27482, 17845}, {-27246, 18205},
243{-27006, 18560}, {-26760, 18911},
244{-26510, 19260}, {-26257, 19606},
245{-25997, 19947}, {-25734, 20286},
246{-25466, 20621}, {-25194, 20952},
247{-24918, 21281}, {-24637, 21605},
248{-24353, 21926}, {-24063, 22242},
249{-23770, 22555}, {-23473, 22865},
250{-23171, 23171}, {-22866, 23472},
251{-22557, 23769}, {-22244, 24063},
252{-21927, 24352}, {-21606, 24636},
253{-21282, 24917}, {-20954, 25194},
254{-20622, 25465}, {-20288, 25733},
255{-19949, 25997}, {-19607, 26255},
256{-19261, 26509}, {-18914, 26760},
257{-18561, 27004}, {-18205, 27246},
258{-17846, 27481}, {-17485, 27713},
259{-17122, 27940}, {-16755, 28162},
260{-16385, 28378}, {-16012, 28590},
261{-15636, 28797}, {-15258, 28999},
262{-14878, 29197}, {-14494, 29389},
263{-14108, 29576}, {-13720, 29757},
264{-13329, 29934}, {-12937, 30107},
265{-12540, 30274}, {-12142, 30435},
266{-11744, 30592}, {-11342, 30743},
267{-10939, 30889}, {-10534, 31030},
268{-10127, 31164}, {-9718, 31294},
269{-9307, 31418}, {-8895, 31537},
270{-8482, 31652}, {-8067, 31759},
271{-7650, 31862}, {-7233, 31960},
272{-6815, 32051}, {-6393, 32138},
273{-5973, 32219}, {-5549, 32294},
274{-5127, 32364}, {-4703, 32429},
275{-4278, 32487}, {-3852, 32541},
276{-3426, 32588}, {-2999, 32630},
277{-2572, 32667}, {-2144, 32698},
278{-1716, 32724}, {-1287, 32742},
279{-860, 32757}, {-430, 32766},
280{0, 32767}, {429, 32766},
281{858, 32757}, {1287, 32743},
282{1715, 32724}, {2143, 32698},
283{2570, 32667}, {2998, 32631},
284{3425, 32588}, {3851, 32541},
285{4277, 32488}, {4701, 32429},
286{5125, 32364}, {5548, 32295},
287{5971, 32219}, {6393, 32138},
288{6813, 32051}, {7231, 31960},
289{7650, 31863}, {8067, 31760},
290{8481, 31652}, {8895, 31539},
291{9306, 31419}, {9716, 31294},
292{10126, 31165}, {10532, 31030},
293{10937, 30889}, {11340, 30743},
294{11741, 30592}, {12141, 30436},
295{12540, 30274}, {12935, 30107},
296{13328, 29936}, {13718, 29758},
297{14107, 29577}, {14493, 29390},
298{14875, 29197}, {15257, 29000},
299{15635, 28797}, {16010, 28590},
300{16384, 28379}, {16753, 28162},
301{17119, 27940}, {17484, 27714},
302{17845, 27482}, {18205, 27246},
303{18560, 27006}, {18911, 26760},
304{19260, 26510}, {19606, 26257},
305{19947, 25997}, {20286, 25734},
306{20621, 25466}, {20952, 25194},
307{21281, 24918}, {21605, 24637},
308{21926, 24353}, {22242, 24063},
309{22555, 23770}, {22865, 23473},
310{23171, 23171}, {23472, 22866},
311{23769, 22557}, {24063, 22244},
312{24352, 21927}, {24636, 21606},
313{24917, 21282}, {25194, 20954},
314{25465, 20622}, {25733, 20288},
315{25997, 19949}, {26255, 19607},
316{26509, 19261}, {26760, 18914},
317{27004, 18561}, {27246, 18205},
318{27481, 17846}, {27713, 17485},
319{27940, 17122}, {28162, 16755},
320{28378, 16385}, {28590, 16012},
321{28797, 15636}, {28999, 15258},
322{29197, 14878}, {29389, 14494},
323{29576, 14108}, {29757, 13720},
324{29934, 13329}, {30107, 12937},
325{30274, 12540}, {30435, 12142},
326{30592, 11744}, {30743, 11342},
327{30889, 10939}, {31030, 10534},
328{31164, 10127}, {31294, 9718},
329{31418, 9307}, {31537, 8895},
330{31652, 8482}, {31759, 8067},
331{31862, 7650}, {31960, 7233},
332{32051, 6815}, {32138, 6393},
333{32219, 5973}, {32294, 5549},
334{32364, 5127}, {32429, 4703},
335{32487, 4278}, {32541, 3852},
336{32588, 3426}, {32630, 2999},
337{32667, 2572}, {32698, 2144},
338{32724, 1716}, {32742, 1287},
339{32757, 860}, {32766, 430},
340};
341#ifndef FFT_BITREV480
342#define FFT_BITREV480
343static const opus_int16 fft_bitrev480[480] = {
3440, 120, 240, 360, 30, 150, 270, 390, 60, 180, 300, 420, 90, 210, 330,
345450, 15, 135, 255, 375, 45, 165, 285, 405, 75, 195, 315, 435, 105, 225,
346345, 465, 5, 125, 245, 365, 35, 155, 275, 395, 65, 185, 305, 425, 95,
347215, 335, 455, 20, 140, 260, 380, 50, 170, 290, 410, 80, 200, 320, 440,
348110, 230, 350, 470, 10, 130, 250, 370, 40, 160, 280, 400, 70, 190, 310,
349430, 100, 220, 340, 460, 25, 145, 265, 385, 55, 175, 295, 415, 85, 205,
350325, 445, 115, 235, 355, 475, 1, 121, 241, 361, 31, 151, 271, 391, 61,
351181, 301, 421, 91, 211, 331, 451, 16, 136, 256, 376, 46, 166, 286, 406,
35276, 196, 316, 436, 106, 226, 346, 466, 6, 126, 246, 366, 36, 156, 276,
353396, 66, 186, 306, 426, 96, 216, 336, 456, 21, 141, 261, 381, 51, 171,
354291, 411, 81, 201, 321, 441, 111, 231, 351, 471, 11, 131, 251, 371, 41,
355161, 281, 401, 71, 191, 311, 431, 101, 221, 341, 461, 26, 146, 266, 386,
35656, 176, 296, 416, 86, 206, 326, 446, 116, 236, 356, 476, 2, 122, 242,
357362, 32, 152, 272, 392, 62, 182, 302, 422, 92, 212, 332, 452, 17, 137,
358257, 377, 47, 167, 287, 407, 77, 197, 317, 437, 107, 227, 347, 467, 7,
359127, 247, 367, 37, 157, 277, 397, 67, 187, 307, 427, 97, 217, 337, 457,
36022, 142, 262, 382, 52, 172, 292, 412, 82, 202, 322, 442, 112, 232, 352,
361472, 12, 132, 252, 372, 42, 162, 282, 402, 72, 192, 312, 432, 102, 222,
362342, 462, 27, 147, 267, 387, 57, 177, 297, 417, 87, 207, 327, 447, 117,
363237, 357, 477, 3, 123, 243, 363, 33, 153, 273, 393, 63, 183, 303, 423,
36493, 213, 333, 453, 18, 138, 258, 378, 48, 168, 288, 408, 78, 198, 318,
365438, 108, 228, 348, 468, 8, 128, 248, 368, 38, 158, 278, 398, 68, 188,
366308, 428, 98, 218, 338, 458, 23, 143, 263, 383, 53, 173, 293, 413, 83,
367203, 323, 443, 113, 233, 353, 473, 13, 133, 253, 373, 43, 163, 283, 403,
36873, 193, 313, 433, 103, 223, 343, 463, 28, 148, 268, 388, 58, 178, 298,
369418, 88, 208, 328, 448, 118, 238, 358, 478, 4, 124, 244, 364, 34, 154,
370274, 394, 64, 184, 304, 424, 94, 214, 334, 454, 19, 139, 259, 379, 49,
371169, 289, 409, 79, 199, 319, 439, 109, 229, 349, 469, 9, 129, 249, 369,
37239, 159, 279, 399, 69, 189, 309, 429, 99, 219, 339, 459, 24, 144, 264,
373384, 54, 174, 294, 414, 84, 204, 324, 444, 114, 234, 354, 474, 14, 134,
374254, 374, 44, 164, 284, 404, 74, 194, 314, 434, 104, 224, 344, 464, 29,
375149, 269, 389, 59, 179, 299, 419, 89, 209, 329, 449, 119, 239, 359, 479,
376};
377#endif
378
379#ifndef FFT_BITREV240
380#define FFT_BITREV240
381static const opus_int16 fft_bitrev240[240] = {
3820, 60, 120, 180, 15, 75, 135, 195, 30, 90, 150, 210, 45, 105, 165,
383225, 5, 65, 125, 185, 20, 80, 140, 200, 35, 95, 155, 215, 50, 110,
384170, 230, 10, 70, 130, 190, 25, 85, 145, 205, 40, 100, 160, 220, 55,
385115, 175, 235, 1, 61, 121, 181, 16, 76, 136, 196, 31, 91, 151, 211,
38646, 106, 166, 226, 6, 66, 126, 186, 21, 81, 141, 201, 36, 96, 156,
387216, 51, 111, 171, 231, 11, 71, 131, 191, 26, 86, 146, 206, 41, 101,
388161, 221, 56, 116, 176, 236, 2, 62, 122, 182, 17, 77, 137, 197, 32,
38992, 152, 212, 47, 107, 167, 227, 7, 67, 127, 187, 22, 82, 142, 202,
39037, 97, 157, 217, 52, 112, 172, 232, 12, 72, 132, 192, 27, 87, 147,
391207, 42, 102, 162, 222, 57, 117, 177, 237, 3, 63, 123, 183, 18, 78,
392138, 198, 33, 93, 153, 213, 48, 108, 168, 228, 8, 68, 128, 188, 23,
39383, 143, 203, 38, 98, 158, 218, 53, 113, 173, 233, 13, 73, 133, 193,
39428, 88, 148, 208, 43, 103, 163, 223, 58, 118, 178, 238, 4, 64, 124,
395184, 19, 79, 139, 199, 34, 94, 154, 214, 49, 109, 169, 229, 9, 69,
396129, 189, 24, 84, 144, 204, 39, 99, 159, 219, 54, 114, 174, 234, 14,
39774, 134, 194, 29, 89, 149, 209, 44, 104, 164, 224, 59, 119, 179, 239,
398};
399#endif
400
401#ifndef FFT_BITREV120
402#define FFT_BITREV120
403static const opus_int16 fft_bitrev120[120] = {
4040, 30, 60, 90, 15, 45, 75, 105, 5, 35, 65, 95, 20, 50, 80,
405110, 10, 40, 70, 100, 25, 55, 85, 115, 1, 31, 61, 91, 16, 46,
40676, 106, 6, 36, 66, 96, 21, 51, 81, 111, 11, 41, 71, 101, 26,
40756, 86, 116, 2, 32, 62, 92, 17, 47, 77, 107, 7, 37, 67, 97,
40822, 52, 82, 112, 12, 42, 72, 102, 27, 57, 87, 117, 3, 33, 63,
40993, 18, 48, 78, 108, 8, 38, 68, 98, 23, 53, 83, 113, 13, 43,
41073, 103, 28, 58, 88, 118, 4, 34, 64, 94, 19, 49, 79, 109, 9,
41139, 69, 99, 24, 54, 84, 114, 14, 44, 74, 104, 29, 59, 89, 119,
412};
413#endif
414
415#ifndef FFT_BITREV60
416#define FFT_BITREV60
417static const opus_int16 fft_bitrev60[60] = {
4180, 15, 30, 45, 5, 20, 35, 50, 10, 25, 40, 55, 1, 16, 31,
41946, 6, 21, 36, 51, 11, 26, 41, 56, 2, 17, 32, 47, 7, 22,
42037, 52, 12, 27, 42, 57, 3, 18, 33, 48, 8, 23, 38, 53, 13,
42128, 43, 58, 4, 19, 34, 49, 9, 24, 39, 54, 14, 29, 44, 59,
422};
423#endif
424
425#ifndef FFT_STATE48000_960_0
426#define FFT_STATE48000_960_0
427static const kiss_fft_state fft_state48000_960_0 = {
428480, /* nfft */
429-1, /* shift */
430{4, 120, 4, 30, 2, 15, 3, 5, 5, 1, 0, 0, 0, 0, 0, 0, }, /* factors */
431fft_bitrev480, /* bitrev */
432fft_twiddles48000_960, /* bitrev */
433};
434#endif
435
436#ifndef FFT_STATE48000_960_1
437#define FFT_STATE48000_960_1
438static const kiss_fft_state fft_state48000_960_1 = {
439240, /* nfft */
4401, /* shift */
441{4, 60, 4, 15, 3, 5, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, }, /* factors */
442fft_bitrev240, /* bitrev */
443fft_twiddles48000_960, /* bitrev */
444};
445#endif
446
447#ifndef FFT_STATE48000_960_2
448#define FFT_STATE48000_960_2
449static const kiss_fft_state fft_state48000_960_2 = {
450120, /* nfft */
4512, /* shift */
452{4, 30, 2, 15, 3, 5, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, }, /* factors */
453fft_bitrev120, /* bitrev */
454fft_twiddles48000_960, /* bitrev */
455};
456#endif
457
458#ifndef FFT_STATE48000_960_3
459#define FFT_STATE48000_960_3
460static const kiss_fft_state fft_state48000_960_3 = {
46160, /* nfft */
4623, /* shift */
463{4, 15, 3, 5, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, /* factors */
464fft_bitrev60, /* bitrev */
465fft_twiddles48000_960, /* bitrev */
466};
467#endif
468
469#endif
470
471#ifndef MDCT_TWIDDLES960
472#define MDCT_TWIDDLES960
473static const opus_val16 mdct_twiddles960[481] = {
47432767, 32767, 32767, 32767, 32766,
47532763, 32762, 32759, 32757, 32753,
47632751, 32747, 32743, 32738, 32733,
47732729, 32724, 32717, 32711, 32705,
47832698, 32690, 32683, 32676, 32667,
47932658, 32650, 32640, 32631, 32620,
48032610, 32599, 32588, 32577, 32566,
48132554, 32541, 32528, 32515, 32502,
48232487, 32474, 32459, 32444, 32429,
48332413, 32397, 32381, 32364, 32348,
48432331, 32313, 32294, 32277, 32257,
48532239, 32219, 32200, 32180, 32159,
48632138, 32118, 32096, 32074, 32051,
48732029, 32006, 31984, 31960, 31936,
48831912, 31888, 31863, 31837, 31812,
48931786, 31760, 31734, 31707, 31679,
49031652, 31624, 31596, 31567, 31539,
49131508, 31479, 31450, 31419, 31388,
49231357, 31326, 31294, 31262, 31230,
49331198, 31164, 31131, 31097, 31063,
49431030, 30994, 30959, 30924, 30889,
49530853, 30816, 30779, 30743, 30705,
49630668, 30629, 30592, 30553, 30515,
49730475, 30435, 30396, 30356, 30315,
49830274, 30233, 30191, 30149, 30107,
49930065, 30022, 29979, 29936, 29891,
50029847, 29803, 29758, 29713, 29668,
50129622, 29577, 29529, 29483, 29436,
50229390, 29341, 29293, 29246, 29197,
50329148, 29098, 29050, 29000, 28949,
50428899, 28848, 28797, 28746, 28694,
50528642, 28590, 28537, 28485, 28432,
50628378, 28324, 28271, 28217, 28162,
50728106, 28051, 27995, 27940, 27884,
50827827, 27770, 27713, 27657, 27598,
50927540, 27481, 27423, 27365, 27305,
51027246, 27187, 27126, 27066, 27006,
51126945, 26883, 26822, 26760, 26698,
51226636, 26574, 26510, 26448, 26383,
51326320, 26257, 26191, 26127, 26062,
51425997, 25931, 25866, 25800, 25734,
51525667, 25601, 25533, 25466, 25398,
51625330, 25262, 25194, 25125, 25056,
51724987, 24917, 24848, 24778, 24707,
51824636, 24566, 24495, 24424, 24352,
51924280, 24208, 24135, 24063, 23990,
52023917, 23842, 23769, 23695, 23622,
52123546, 23472, 23398, 23322, 23246,
52223171, 23095, 23018, 22942, 22866,
52322788, 22711, 22634, 22557, 22478,
52422400, 22322, 22244, 22165, 22085,
52522006, 21927, 21846, 21766, 21687,
52621606, 21524, 21443, 21363, 21282,
52721199, 21118, 21035, 20954, 20870,
52820788, 20705, 20621, 20538, 20455,
52920371, 20286, 20202, 20118, 20034,
53019947, 19863, 19777, 19692, 19606,
53119520, 19434, 19347, 19260, 19174,
53219088, 18999, 18911, 18825, 18737,
53318648, 18560, 18472, 18384, 18294,
53418205, 18116, 18025, 17936, 17846,
53517757, 17666, 17576, 17485, 17395,
53617303, 17212, 17122, 17030, 16937,
53716846, 16755, 16662, 16569, 16477,
53816385, 16291, 16198, 16105, 16012,
53915917, 15824, 15730, 15636, 15541,
54015447, 15352, 15257, 15162, 15067,
54114973, 14875, 14781, 14685, 14589,
54214493, 14396, 14300, 14204, 14107,
54314010, 13914, 13815, 13718, 13621,
54413524, 13425, 13328, 13230, 13133,
54513033, 12935, 12836, 12738, 12638,
54612540, 12441, 12341, 12241, 12142,
54712044, 11943, 11843, 11744, 11643,
54811542, 11442, 11342, 11241, 11139,
54911039, 10939, 10836, 10736, 10635,
55010534, 10431, 10330, 10228, 10127,
55110024, 9921, 9820, 9718, 9614,
5529512, 9410, 9306, 9204, 9101,
5538998, 8895, 8791, 8689, 8585,
5548481, 8377, 8274, 8171, 8067,
5557962, 7858, 7753, 7650, 7545,
5567441, 7336, 7231, 7129, 7023,
5576917, 6813, 6709, 6604, 6498,
5586393, 6288, 6182, 6077, 5973,
5595867, 5760, 5656, 5549, 5445,
5605339, 5232, 5127, 5022, 4914,
5614809, 4703, 4596, 4490, 4384,
5624278, 4171, 4065, 3958, 3852,
5633745, 3640, 3532, 3426, 3318,
5643212, 3106, 2998, 2891, 2786,
5652679, 2570, 2465, 2358, 2251,
5662143, 2037, 1929, 1823, 1715,
5671609, 1501, 1393, 1287, 1180,
5681073, 964, 858, 751, 644,
569535, 429, 322, 214, 107,
5700, };
571#endif
572
573static const CELTMode mode48000_960_120 = {
57448000, /* Fs */
575120, /* overlap */
57621, /* nbEBands */
57721, /* effEBands */
578{27853, 0, 4096, 8192, }, /* preemph */
579eband5ms, /* eBands */
5803, /* maxLM */
5818, /* nbShortMdcts */
582120, /* shortMdctSize */
58311, /* nbAllocVectors */
584band_allocation, /* allocVectors */
585logN400, /* logN */
586window120, /* window */
587{1920, 3, {&fft_state48000_960_0, &fft_state48000_960_1, &fft_state48000_960_2, &fft_state48000_960_3, }, mdct_twiddles960}, /* mdct */
588{392, cache_index50, cache_bits50, cache_caps50}, /* cache */
589};
590
591/* List of all the available modes */
592#define TOTAL_MODES 1
593static const CELTMode * const static_mode_list[TOTAL_MODES] = {
594&mode48000_960_120,
595};
diff --git a/lib/rbcodec/codecs/libopus/celt/vq.c b/lib/rbcodec/codecs/libopus/celt/vq.c
new file mode 100644
index 0000000000..6a00edf9cd
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/vq.c
@@ -0,0 +1,415 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/*
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8
9 - Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
11
12 - Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in the
14 documentation and/or other materials provided with the distribution.
15
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*/
28
29#ifdef HAVE_CONFIG_H
30#include "opus_config.h"
31#endif
32
33#include "mathops.h"
34#include "cwrs.h"
35#include "vq.h"
36#include "arch.h"
37#include "os_support.h"
38#include "bands.h"
39#include "rate.h"
40
41static void exp_rotation1(celt_norm *X, int len, int stride, opus_val16 c, opus_val16 s)
42{
43 int i;
44 celt_norm *Xptr;
45 Xptr = X;
46 for (i=0;i<len-stride;i++)
47 {
48 celt_norm x1, x2;
49 x1 = Xptr[0];
50 x2 = Xptr[stride];
51 Xptr[stride] = EXTRACT16(SHR32(MULT16_16(c,x2) + MULT16_16(s,x1), 15));
52 *Xptr++ = EXTRACT16(SHR32(MULT16_16(c,x1) - MULT16_16(s,x2), 15));
53 }
54 Xptr = &X[len-2*stride-1];
55 for (i=len-2*stride-1;i>=0;i--)
56 {
57 celt_norm x1, x2;
58 x1 = Xptr[0];
59 x2 = Xptr[stride];
60 Xptr[stride] = EXTRACT16(SHR32(MULT16_16(c,x2) + MULT16_16(s,x1), 15));
61 *Xptr-- = EXTRACT16(SHR32(MULT16_16(c,x1) - MULT16_16(s,x2), 15));
62 }
63}
64
65static void exp_rotation(celt_norm *X, int len, int dir, int stride, int K, int spread)
66{
67 static const int SPREAD_FACTOR[3]={15,10,5};
68 int i;
69 opus_val16 c, s;
70 opus_val16 gain, theta;
71 int stride2=0;
72 int factor;
73
74 if (2*K>=len || spread==SPREAD_NONE)
75 return;
76 factor = SPREAD_FACTOR[spread-1];
77
78 gain = celt_div((opus_val32)MULT16_16(Q15_ONE,len),(opus_val32)(len+factor*K));
79 theta = HALF16(MULT16_16_Q15(gain,gain));
80
81 c = celt_cos_norm(EXTEND32(theta));
82 s = celt_cos_norm(EXTEND32(SUB16(Q15ONE,theta))); /* sin(theta) */
83
84 if (len>=8*stride)
85 {
86 stride2 = 1;
87 /* This is just a simple (equivalent) way of computing sqrt(len/stride) with rounding.
88 It's basically incrementing long as (stride2+0.5)^2 < len/stride. */
89 while ((stride2*stride2+stride2)*stride + (stride>>2) < len)
90 stride2++;
91 }
92 /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
93 extract_collapse_mask().*/
94 len /= stride;
95 for (i=0;i<stride;i++)
96 {
97 if (dir < 0)
98 {
99 if (stride2)
100 exp_rotation1(X+i*len, len, stride2, s, c);
101 exp_rotation1(X+i*len, len, 1, c, s);
102 } else {
103 exp_rotation1(X+i*len, len, 1, c, -s);
104 if (stride2)
105 exp_rotation1(X+i*len, len, stride2, s, -c);
106 }
107 }
108}
109
110/** Takes the pitch vector and the decoded residual vector, computes the gain
111 that will give ||p+g*y||=1 and mixes the residual with the pitch. */
112static void normalise_residual(int * OPUS_RESTRICT iy, celt_norm * OPUS_RESTRICT X,
113 int N, opus_val32 Ryy, opus_val16 gain)
114{
115 int i;
116#ifdef FIXED_POINT
117 int k;
118#endif
119 opus_val32 t;
120 opus_val16 g;
121
122#ifdef FIXED_POINT
123 k = celt_ilog2(Ryy)>>1;
124#endif
125 t = VSHR32(Ryy, 2*(k-7));
126 g = MULT16_16_P15(celt_rsqrt_norm(t),gain);
127
128 i=0;
129 do
130 X[i] = EXTRACT16(PSHR32(MULT16_16(g, iy[i]), k+1));
131 while (++i < N);
132}
133
134static unsigned extract_collapse_mask(int *iy, int N, int B)
135{
136 unsigned collapse_mask;
137 int N0;
138 int i;
139 if (B<=1)
140 return 1;
141 /*NOTE: As a minor optimization, we could be passing around log2(B), not B, for both this and for
142 exp_rotation().*/
143 N0 = N/B;
144 collapse_mask = 0;
145 i=0; do {
146 int j;
147 j=0; do {
148 collapse_mask |= (iy[i*N0+j]!=0)<<i;
149 } while (++j<N0);
150 } while (++i<B);
151 return collapse_mask;
152}
153
154unsigned alg_quant(celt_norm *X, int N, int K, int spread, int B, ec_enc *enc
155#ifdef RESYNTH
156 , opus_val16 gain
157#endif
158 )
159{
160 VARDECL(celt_norm, y);
161 VARDECL(int, iy);
162 VARDECL(opus_val16, signx);
163 int i, j;
164 opus_val16 s;
165 int pulsesLeft;
166 opus_val32 sum;
167 opus_val32 xy;
168 opus_val16 yy;
169 unsigned collapse_mask;
170 SAVE_STACK;
171
172 celt_assert2(K>0, "alg_quant() needs at least one pulse");
173 celt_assert2(N>1, "alg_quant() needs at least two dimensions");
174
175 ALLOC(y, N, celt_norm);
176 ALLOC(iy, N, int);
177 ALLOC(signx, N, opus_val16);
178
179 exp_rotation(X, N, 1, B, K, spread);
180
181 /* Get rid of the sign */
182 sum = 0;
183 j=0; do {
184 if (X[j]>0)
185 signx[j]=1;
186 else {
187 signx[j]=-1;
188 X[j]=-X[j];
189 }
190 iy[j] = 0;
191 y[j] = 0;
192 } while (++j<N);
193
194 xy = yy = 0;
195
196 pulsesLeft = K;
197
198 /* Do a pre-search by projecting on the pyramid */
199 if (K > (N>>1))
200 {
201 opus_val16 rcp;
202 j=0; do {
203 sum += X[j];
204 } while (++j<N);
205
206 /* If X is too small, just replace it with a pulse at 0 */
207#ifdef FIXED_POINT
208 if (sum <= K)
209#else
210 /* Prevents infinities and NaNs from causing too many pulses
211 to be allocated. 64 is an approximation of infinity here. */
212 if (!(sum > EPSILON && sum < 64))
213#endif
214 {
215 X[0] = QCONST16(1.f,14);
216 j=1; do
217 X[j]=0;
218 while (++j<N);
219 sum = QCONST16(1.f,14);
220 }
221 rcp = EXTRACT16(MULT16_32_Q16(K-1, celt_rcp(sum)));
222 j=0; do {
223#ifdef FIXED_POINT
224 /* It's really important to round *towards zero* here */
225 iy[j] = MULT16_16_Q15(X[j],rcp);
226#else
227 iy[j] = (int)floor(rcp*X[j]);
228#endif
229 y[j] = (celt_norm)iy[j];
230 yy = MAC16_16(yy, y[j],y[j]);
231 xy = MAC16_16(xy, X[j],y[j]);
232 y[j] *= 2;
233 pulsesLeft -= iy[j];
234 } while (++j<N);
235 }
236 celt_assert2(pulsesLeft>=1, "Allocated too many pulses in the quick pass");
237
238 /* This should never happen, but just in case it does (e.g. on silence)
239 we fill the first bin with pulses. */
240#ifdef FIXED_POINT_DEBUG
241 celt_assert2(pulsesLeft<=N+3, "Not enough pulses in the quick pass");
242#endif
243 if (pulsesLeft > N+3)
244 {
245 opus_val16 tmp = (opus_val16)pulsesLeft;
246 yy = MAC16_16(yy, tmp, tmp);
247 yy = MAC16_16(yy, tmp, y[0]);
248 iy[0] += pulsesLeft;
249 pulsesLeft=0;
250 }
251
252 s = 1;
253 for (i=0;i<pulsesLeft;i++)
254 {
255 int best_id;
256 opus_val32 best_num = -VERY_LARGE16;
257 opus_val16 best_den = 0;
258#ifdef FIXED_POINT
259 int rshift;
260#endif
261#ifdef FIXED_POINT
262 rshift = 1+celt_ilog2(K-pulsesLeft+i+1);
263#endif
264 best_id = 0;
265 /* The squared magnitude term gets added anyway, so we might as well
266 add it outside the loop */
267 yy = ADD32(yy, 1);
268 j=0;
269 do {
270 opus_val16 Rxy, Ryy;
271 /* Temporary sums of the new pulse(s) */
272 Rxy = EXTRACT16(SHR32(ADD32(xy, EXTEND32(X[j])),rshift));
273 /* We're multiplying y[j] by two so we don't have to do it here */
274 Ryy = ADD16(yy, y[j]);
275
276 /* Approximate score: we maximise Rxy/sqrt(Ryy) (we're guaranteed that
277 Rxy is positive because the sign is pre-computed) */
278 Rxy = MULT16_16_Q15(Rxy,Rxy);
279 /* The idea is to check for num/den >= best_num/best_den, but that way
280 we can do it without any division */
281 /* OPT: Make sure to use conditional moves here */
282 if (MULT16_16(best_den, Rxy) > MULT16_16(Ryy, best_num))
283 {
284 best_den = Ryy;
285 best_num = Rxy;
286 best_id = j;
287 }
288 } while (++j<N);
289
290 /* Updating the sums of the new pulse(s) */
291 xy = ADD32(xy, EXTEND32(X[best_id]));
292 /* We're multiplying y[j] by two so we don't have to do it here */
293 yy = ADD16(yy, y[best_id]);
294
295 /* Only now that we've made the final choice, update y/iy */
296 /* Multiplying y[j] by 2 so we don't have to do it everywhere else */
297 y[best_id] += 2*s;
298 iy[best_id]++;
299 }
300
301 /* Put the original sign back */
302 j=0;
303 do {
304 X[j] = MULT16_16(signx[j],X[j]);
305 if (signx[j] < 0)
306 iy[j] = -iy[j];
307 } while (++j<N);
308 encode_pulses(iy, N, K, enc);
309
310#ifdef RESYNTH
311 normalise_residual(iy, X, N, yy, gain);
312 exp_rotation(X, N, -1, B, K, spread);
313#endif
314
315 collapse_mask = extract_collapse_mask(iy, N, B);
316 RESTORE_STACK;
317 return collapse_mask;
318}
319
320/** Decode pulse vector and combine the result with the pitch vector to produce
321 the final normalised signal in the current band. */
322unsigned alg_unquant(celt_norm *X, int N, int K, int spread, int B,
323 ec_dec *dec, opus_val16 gain)
324{
325 int i;
326 opus_val32 Ryy;
327 unsigned collapse_mask;
328 VARDECL(int, iy);
329 SAVE_STACK;
330
331 celt_assert2(K>0, "alg_unquant() needs at least one pulse");
332 celt_assert2(N>1, "alg_unquant() needs at least two dimensions");
333 ALLOC(iy, N, int);
334 decode_pulses(iy, N, K, dec);
335 Ryy = 0;
336 i=0;
337 do {
338 Ryy = MAC16_16(Ryy, iy[i], iy[i]);
339 } while (++i < N);
340 normalise_residual(iy, X, N, Ryy, gain);
341 exp_rotation(X, N, -1, B, K, spread);
342 collapse_mask = extract_collapse_mask(iy, N, B);
343 RESTORE_STACK;
344 return collapse_mask;
345}
346
347void renormalise_vector(celt_norm *X, int N, opus_val16 gain)
348{
349 int i;
350#ifdef FIXED_POINT
351 int k;
352#endif
353 opus_val32 E = EPSILON;
354 opus_val16 g;
355 opus_val32 t;
356 celt_norm *xptr = X;
357 for (i=0;i<N;i++)
358 {
359 E = MAC16_16(E, *xptr, *xptr);
360 xptr++;
361 }
362#ifdef FIXED_POINT
363 k = celt_ilog2(E)>>1;
364#endif
365 t = VSHR32(E, 2*(k-7));
366 g = MULT16_16_P15(celt_rsqrt_norm(t),gain);
367
368 xptr = X;
369 for (i=0;i<N;i++)
370 {
371 *xptr = EXTRACT16(PSHR32(MULT16_16(g, *xptr), k+1));
372 xptr++;
373 }
374 /*return celt_sqrt(E);*/
375}
376
377int stereo_itheta(celt_norm *X, celt_norm *Y, int stereo, int N)
378{
379 int i;
380 int itheta;
381 opus_val16 mid, side;
382 opus_val32 Emid, Eside;
383
384 Emid = Eside = EPSILON;
385 if (stereo)
386 {
387 for (i=0;i<N;i++)
388 {
389 celt_norm m, s;
390 m = ADD16(SHR16(X[i],1),SHR16(Y[i],1));
391 s = SUB16(SHR16(X[i],1),SHR16(Y[i],1));
392 Emid = MAC16_16(Emid, m, m);
393 Eside = MAC16_16(Eside, s, s);
394 }
395 } else {
396 for (i=0;i<N;i++)
397 {
398 celt_norm m, s;
399 m = X[i];
400 s = Y[i];
401 Emid = MAC16_16(Emid, m, m);
402 Eside = MAC16_16(Eside, s, s);
403 }
404 }
405 mid = celt_sqrt(Emid);
406 side = celt_sqrt(Eside);
407#ifdef FIXED_POINT
408 /* 0.63662 = 2/pi */
409 itheta = MULT16_16_Q15(QCONST16(0.63662f,15),celt_atan2p(side, mid));
410#else
411 itheta = (int)floor(.5f+16384*0.63662f*atan2(side,mid));
412#endif
413
414 return itheta;
415}
diff --git a/lib/rbcodec/codecs/libopus/celt/vq.h b/lib/rbcodec/codecs/libopus/celt/vq.h
new file mode 100644
index 0000000000..1ceeeeb268
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/celt/vq.h
@@ -0,0 +1,73 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Written by Jean-Marc Valin */
4/**
5 @file vq.h
6 @brief Vector quantisation of the residual
7 */
8/*
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions
11 are met:
12
13 - Redistributions of source code must retain the above copyright
14 notice, this list of conditions and the following disclaimer.
15
16 - Redistributions in binary form must reproduce the above copyright
17 notice, this list of conditions and the following disclaimer in the
18 documentation and/or other materials provided with the distribution.
19
20 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
24 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31*/
32
33#ifndef VQ_H
34#define VQ_H
35
36#include "entenc.h"
37#include "entdec.h"
38#include "modes.h"
39
40/** Algebraic pulse-vector quantiser. The signal x is replaced by the sum of
41 * the pitch and a combination of pulses such that its norm is still equal
42 * to 1. This is the function that will typically require the most CPU.
43 * @param x Residual signal to quantise/encode (returns quantised version)
44 * @param W Perceptual weight to use when optimising (currently unused)
45 * @param N Number of samples to encode
46 * @param K Number of pulses to use
47 * @param p Pitch vector (it is assumed that p+x is a unit vector)
48 * @param enc Entropy encoder state
49 * @ret A mask indicating which blocks in the band received pulses
50*/
51unsigned alg_quant(celt_norm *X, int N, int K, int spread, int B,
52 ec_enc *enc
53#ifdef RESYNTH
54 , opus_val16 gain
55#endif
56 );
57
58/** Algebraic pulse decoder
59 * @param x Decoded normalised spectrum (returned)
60 * @param N Number of samples to decode
61 * @param K Number of pulses to use
62 * @param p Pitch vector (automatically added to x)
63 * @param dec Entropy decoder state
64 * @ret A mask indicating which blocks in the band received pulses
65 */
66unsigned alg_unquant(celt_norm *X, int N, int K, int spread, int B,
67 ec_dec *dec, opus_val16 gain);
68
69void renormalise_vector(celt_norm *X, int N, opus_val16 gain);
70
71int stereo_itheta(celt_norm *X, celt_norm *Y, int stereo, int N);
72
73#endif /* VQ_H */
diff --git a/lib/rbcodec/codecs/libopus/libopus.make b/lib/rbcodec/codecs/libopus/libopus.make
new file mode 100644
index 0000000000..1df52dbe4f
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/libopus.make
@@ -0,0 +1,24 @@
1# __________ __ ___.
2# Open \______ \ ____ ____ | | _\_ |__ _______ ___
3# Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
4# Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
5# Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
6# \/ \/ \/ \/ \/
7# $Id$
8#
9
10# libopus
11OPUSLIB := $(CODECDIR)/libopus.a
12OPUSLIB_SRC := $(call preprocess, $(RBCODECLIB_DIR)/codecs/libopus/SOURCES)
13OPUSLIB_OBJ := $(call c2obj, $(OPUSLIB_SRC))
14
15# codec specific compilation flags
16$(OPUSLIB) : CODECFLAGS += -DHAVE_CONFIG_H \
17 -I$(RBCODECLIB_DIR)/codecs/libopus \
18 -I$(RBCODECLIB_DIR)/codecs/libopus/celt \
19 -I$(RBCODECLIB_DIR)/codecs/libopus/silk \
20 -I$(RBCODECLIB_DIR)/codecs/libopus/silk/fixed
21
22$(OPUSLIB): $(OPUSLIB_OBJ)
23 $(SILENT)$(shell rm -f $@)
24 $(call PRINTS,AR $(@F))$(AR) rcs $@ $^ >/dev/null
diff --git a/lib/rbcodec/codecs/libopus/ogg/framing.c b/lib/rbcodec/codecs/libopus/ogg/framing.c
new file mode 100644
index 0000000000..f007de176a
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/ogg/framing.c
@@ -0,0 +1,1025 @@
1/********************************************************************
2 * *
3 * THIS FILE IS PART OF THE Ogg CONTAINER SOURCE CODE. *
4 * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
5 * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
6 * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
7 * *
8 * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2010 *
9 * by the Xiph.Org Foundation http://www.xiph.org/ *
10 * *
11 ********************************************************************
12
13 function: code raw packets into framed OggSquish stream and
14 decode Ogg streams back into raw packets
15 last mod: $Id: framing.c 18052 2011-08-04 17:57:02Z giles $
16
17 note: The CRC code is directly derived from public domain code by
18 Ross Williams (ross@guest.adelaide.edu.au). See docs/framing.html
19 for details.
20
21 ********************************************************************/
22
23#include <stdlib.h>
24#include <string.h>
25#include <ogg/ogg.h>
26
27/* A complete description of Ogg framing exists in docs/framing.html */
28
29int ogg_page_version(const ogg_page *og){
30 return((int)(og->header[4]));
31}
32
33int ogg_page_continued(const ogg_page *og){
34 return((int)(og->header[5]&0x01));
35}
36
37int ogg_page_bos(const ogg_page *og){
38 return((int)(og->header[5]&0x02));
39}
40
41int ogg_page_eos(const ogg_page *og){
42 return((int)(og->header[5]&0x04));
43}
44
45ogg_int64_t ogg_page_granulepos(const ogg_page *og){
46 unsigned char *page=og->header;
47 ogg_int64_t granulepos=page[13]&(0xff);
48 granulepos= (granulepos<<8)|(page[12]&0xff);
49 granulepos= (granulepos<<8)|(page[11]&0xff);
50 granulepos= (granulepos<<8)|(page[10]&0xff);
51 granulepos= (granulepos<<8)|(page[9]&0xff);
52 granulepos= (granulepos<<8)|(page[8]&0xff);
53 granulepos= (granulepos<<8)|(page[7]&0xff);
54 granulepos= (granulepos<<8)|(page[6]&0xff);
55 return(granulepos);
56}
57
58int ogg_page_serialno(const ogg_page *og){
59 return(og->header[14] |
60 (og->header[15]<<8) |
61 (og->header[16]<<16) |
62 (og->header[17]<<24));
63}
64
65long ogg_page_pageno(const ogg_page *og){
66 return(og->header[18] |
67 (og->header[19]<<8) |
68 (og->header[20]<<16) |
69 (og->header[21]<<24));
70}
71
72
73
74/* returns the number of packets that are completed on this page (if
75 the leading packet is begun on a previous page, but ends on this
76 page, it's counted */
77
78/* NOTE:
79 If a page consists of a packet begun on a previous page, and a new
80 packet begun (but not completed) on this page, the return will be:
81 ogg_page_packets(page) ==1,
82 ogg_page_continued(page) !=0
83
84 If a page happens to be a single packet that was begun on a
85 previous page, and spans to the next page (in the case of a three or
86 more page packet), the return will be:
87 ogg_page_packets(page) ==0,
88 ogg_page_continued(page) !=0
89*/
90
91int ogg_page_packets(const ogg_page *og){
92 int i,n=og->header[26],count=0;
93 for(i=0;i<n;i++)
94 if(og->header[27+i]<255)count++;
95 return(count);
96}
97
98
99#if 0
100/* helper to initialize lookup for direct-table CRC (illustrative; we
101 use the static init below) */
102
103static ogg_uint32_t _ogg_crc_entry(unsigned long index){
104 int i;
105 unsigned long r;
106
107 r = index << 24;
108 for (i=0; i<8; i++)
109 if (r & 0x80000000UL)
110 r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
111 polynomial, although we use an
112 unreflected alg and an init/final
113 of 0, not 0xffffffff */
114 else
115 r<<=1;
116 return (r & 0xffffffffUL);
117}
118#endif
119
120static const ogg_uint32_t crc_lookup[256]={
121 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
122 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
123 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
124 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
125 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
126 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
127 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
128 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
129 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
130 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
131 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
132 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
133 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
134 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
135 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
136 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
137 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
138 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
139 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
140 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
141 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
142 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
143 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
144 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
145 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
146 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
147 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
148 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
149 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
150 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
151 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
152 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
153 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
154 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
155 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
156 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
157 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
158 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
159 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
160 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
161 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
162 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
163 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
164 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
165 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
166 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
167 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
168 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
169 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
170 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
171 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
172 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
173 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
174 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
175 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
176 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
177 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
178 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
179 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
180 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
181 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
182 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
183 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
184 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
185
186/* init the encode/decode logical stream state */
187
188int ogg_stream_init(ogg_stream_state *os,int serialno){
189 if(os){
190 memset(os,0,sizeof(*os));
191 os->body_storage=16*1024;
192 os->lacing_storage=1024;
193
194 os->body_data=_ogg_malloc(os->body_storage*sizeof(*os->body_data));
195 os->lacing_vals=_ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
196 os->granule_vals=_ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
197
198 if(!os->body_data || !os->lacing_vals || !os->granule_vals){
199 ogg_stream_clear(os);
200 return -1;
201 }
202
203 os->serialno=serialno;
204
205 return(0);
206 }
207 return(-1);
208}
209
210/* async/delayed error detection for the ogg_stream_state */
211int ogg_stream_check(ogg_stream_state *os){
212 if(!os || !os->body_data) return -1;
213 return 0;
214}
215
216/* _clear does not free os, only the non-flat storage within */
217int ogg_stream_clear(ogg_stream_state *os){
218 if(os){
219 if(os->body_data)_ogg_free(os->body_data);
220 if(os->lacing_vals)_ogg_free(os->lacing_vals);
221 if(os->granule_vals)_ogg_free(os->granule_vals);
222
223 memset(os,0,sizeof(*os));
224 }
225 return(0);
226}
227
228int ogg_stream_destroy(ogg_stream_state *os){
229 if(os){
230 ogg_stream_clear(os);
231 _ogg_free(os);
232 }
233 return(0);
234}
235
236/* Helpers for ogg_stream_encode; this keeps the structure and
237 what's happening fairly clear */
238
239static int _os_body_expand(ogg_stream_state *os,int needed){
240 if(os->body_storage<=os->body_fill+needed){
241 void *ret;
242 ret=_ogg_realloc(os->body_data,(os->body_storage+needed+1024)*
243 sizeof(*os->body_data));
244 if(!ret){
245 ogg_stream_clear(os);
246 return -1;
247 }
248 os->body_storage+=(needed+1024);
249 os->body_data=ret;
250 }
251 return 0;
252}
253
254static int _os_lacing_expand(ogg_stream_state *os,int needed){
255 if(os->lacing_storage<=os->lacing_fill+needed){
256 void *ret;
257 ret=_ogg_realloc(os->lacing_vals,(os->lacing_storage+needed+32)*
258 sizeof(*os->lacing_vals));
259 if(!ret){
260 ogg_stream_clear(os);
261 return -1;
262 }
263 os->lacing_vals=ret;
264 ret=_ogg_realloc(os->granule_vals,(os->lacing_storage+needed+32)*
265 sizeof(*os->granule_vals));
266 if(!ret){
267 ogg_stream_clear(os);
268 return -1;
269 }
270 os->granule_vals=ret;
271 os->lacing_storage+=(needed+32);
272 }
273 return 0;
274}
275
276/* checksum the page */
277/* Direct table CRC; note that this will be faster in the future if we
278 perform the checksum simultaneously with other copies */
279
280void ogg_page_checksum_set(ogg_page *og){
281 if(og){
282 ogg_uint32_t crc_reg=0;
283 int i;
284
285 /* safety; needed for API behavior, but not framing code */
286 og->header[22]=0;
287 og->header[23]=0;
288 og->header[24]=0;
289 og->header[25]=0;
290
291 for(i=0;i<og->header_len;i++)
292 crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
293 for(i=0;i<og->body_len;i++)
294 crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
295
296 og->header[22]=(unsigned char)(crc_reg&0xff);
297 og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
298 og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
299 og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
300 }
301}
302
303/* submit data to the internal buffer of the framing engine */
304int ogg_stream_iovecin(ogg_stream_state *os, ogg_iovec_t *iov, int count,
305 long e_o_s, ogg_int64_t granulepos){
306
307 int bytes = 0, lacing_vals, i;
308
309 if(ogg_stream_check(os)) return -1;
310 if(!iov) return 0;
311
312 for (i = 0; i < count; ++i) bytes += (int)iov[i].iov_len;
313 lacing_vals=bytes/255+1;
314
315 if(os->body_returned){
316 /* advance packet data according to the body_returned pointer. We
317 had to keep it around to return a pointer into the buffer last
318 call */
319
320 os->body_fill-=os->body_returned;
321 if(os->body_fill)
322 memmove(os->body_data,os->body_data+os->body_returned,
323 os->body_fill);
324 os->body_returned=0;
325 }
326
327 /* make sure we have the buffer storage */
328 if(_os_body_expand(os,bytes) || _os_lacing_expand(os,lacing_vals))
329 return -1;
330
331 /* Copy in the submitted packet. Yes, the copy is a waste; this is
332 the liability of overly clean abstraction for the time being. It
333 will actually be fairly easy to eliminate the extra copy in the
334 future */
335
336 for (i = 0; i < count; ++i) {
337 memcpy(os->body_data+os->body_fill, iov[i].iov_base, iov[i].iov_len);
338 os->body_fill += (int)iov[i].iov_len;
339 }
340
341 /* Store lacing vals for this packet */
342 for(i=0;i<lacing_vals-1;i++){
343 os->lacing_vals[os->lacing_fill+i]=255;
344 os->granule_vals[os->lacing_fill+i]=os->granulepos;
345 }
346 os->lacing_vals[os->lacing_fill+i]=bytes%255;
347 os->granulepos=os->granule_vals[os->lacing_fill+i]=granulepos;
348
349 /* flag the first segment as the beginning of the packet */
350 os->lacing_vals[os->lacing_fill]|= 0x100;
351
352 os->lacing_fill+=lacing_vals;
353
354 /* for the sake of completeness */
355 os->packetno++;
356
357 if(e_o_s)os->e_o_s=1;
358
359 return(0);
360}
361
362int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
363 ogg_iovec_t iov;
364 iov.iov_base = op->packet;
365 iov.iov_len = op->bytes;
366 return ogg_stream_iovecin(os, &iov, 1, op->e_o_s, op->granulepos);
367}
368
369/* Conditionally flush a page; force==0 will only flush nominal-size
370 pages, force==1 forces us to flush a page regardless of page size
371 so long as there's any data available at all. */
372static int ogg_stream_flush_i(ogg_stream_state *os,ogg_page *og, int force, int nfill){
373 int i;
374 int vals=0;
375 int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
376 int bytes=0;
377 long acc=0;
378 ogg_int64_t granule_pos=-1;
379
380 if(ogg_stream_check(os)) return(0);
381 if(maxvals==0) return(0);
382
383 /* construct a page */
384 /* decide how many segments to include */
385
386 /* If this is the initial header case, the first page must only include
387 the initial header packet */
388 if(os->b_o_s==0){ /* 'initial header page' case */
389 granule_pos=0;
390 for(vals=0;vals<maxvals;vals++){
391 if((os->lacing_vals[vals]&0x0ff)<255){
392 vals++;
393 break;
394 }
395 }
396 }else{
397
398 /* The extra packets_done, packet_just_done logic here attempts to do two things:
399 1) Don't unneccessarily span pages.
400 2) Unless necessary, don't flush pages if there are less than four packets on
401 them; this expands page size to reduce unneccessary overhead if incoming packets
402 are large.
403 These are not necessary behaviors, just 'always better than naive flushing'
404 without requiring an application to explicitly request a specific optimized
405 behavior. We'll want an explicit behavior setup pathway eventually as well. */
406
407 int packets_done=0;
408 int packet_just_done=0;
409 for(vals=0;vals<maxvals;vals++){
410 if(acc>nfill && packet_just_done>=4){
411 force=1;
412 break;
413 }
414 acc+=os->lacing_vals[vals]&0x0ff;
415 if((os->lacing_vals[vals]&0xff)<255){
416 granule_pos=os->granule_vals[vals];
417 packet_just_done=++packets_done;
418 }else
419 packet_just_done=0;
420 }
421 if(vals==255)force=1;
422 }
423
424 if(!force) return(0);
425
426 /* construct the header in temp storage */
427 memcpy(os->header,"OggS",4);
428
429 /* stream structure version */
430 os->header[4]=0x00;
431
432 /* continued packet flag? */
433 os->header[5]=0x00;
434 if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
435 /* first page flag? */
436 if(os->b_o_s==0)os->header[5]|=0x02;
437 /* last page flag? */
438 if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
439 os->b_o_s=1;
440
441 /* 64 bits of PCM position */
442 for(i=6;i<14;i++){
443 os->header[i]=(unsigned char)(granule_pos&0xff);
444 granule_pos>>=8;
445 }
446
447 /* 32 bits of stream serial number */
448 {
449 long serialno=os->serialno;
450 for(i=14;i<18;i++){
451 os->header[i]=(unsigned char)(serialno&0xff);
452 serialno>>=8;
453 }
454 }
455
456 /* 32 bits of page counter (we have both counter and page header
457 because this val can roll over) */
458 if(os->pageno==-1)os->pageno=0; /* because someone called
459 stream_reset; this would be a
460 strange thing to do in an
461 encode stream, but it has
462 plausible uses */
463 {
464 long pageno=os->pageno++;
465 for(i=18;i<22;i++){
466 os->header[i]=(unsigned char)(pageno&0xff);
467 pageno>>=8;
468 }
469 }
470
471 /* zero for computation; filled in later */
472 os->header[22]=0;
473 os->header[23]=0;
474 os->header[24]=0;
475 os->header[25]=0;
476
477 /* segment table */
478 os->header[26]=(unsigned char)(vals&0xff);
479 for(i=0;i<vals;i++)
480 bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
481
482 /* set pointers in the ogg_page struct */
483 og->header=os->header;
484 og->header_len=os->header_fill=vals+27;
485 og->body=os->body_data+os->body_returned;
486 og->body_len=bytes;
487
488 /* advance the lacing data and set the body_returned pointer */
489
490 os->lacing_fill-=vals;
491 memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
492 memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
493 os->body_returned+=bytes;
494
495 /* calculate the checksum */
496
497 ogg_page_checksum_set(og);
498
499 /* done */
500 return(1);
501}
502
503/* This will flush remaining packets into a page (returning nonzero),
504 even if there is not enough data to trigger a flush normally
505 (undersized page). If there are no packets or partial packets to
506 flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
507 try to flush a normal sized page like ogg_stream_pageout; a call to
508 ogg_stream_flush does not guarantee that all packets have flushed.
509 Only a return value of 0 from ogg_stream_flush indicates all packet
510 data is flushed into pages.
511
512 since ogg_stream_flush will flush the last page in a stream even if
513 it's undersized, you almost certainly want to use ogg_stream_pageout
514 (and *not* ogg_stream_flush) unless you specifically need to flush
515 a page regardless of size in the middle of a stream. */
516
517int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
518 return ogg_stream_flush_i(os,og,1,4096);
519}
520
521/* Like the above, but an argument is provided to adjust the nominal
522 page size for applications which are smart enough to provide their
523 own delay based flushing */
524
525int ogg_stream_flush_fill(ogg_stream_state *os,ogg_page *og, int nfill){
526 return ogg_stream_flush_i(os,og,1,nfill);
527}
528
529/* This constructs pages from buffered packet segments. The pointers
530returned are to static buffers; do not free. The returned buffers are
531good only until the next call (using the same ogg_stream_state) */
532
533int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
534 int force=0;
535 if(ogg_stream_check(os)) return 0;
536
537 if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
538 (os->lacing_fill&&!os->b_o_s)) /* 'initial header page' case */
539 force=1;
540
541 return(ogg_stream_flush_i(os,og,force,4096));
542}
543
544/* Like the above, but an argument is provided to adjust the nominal
545page size for applications which are smart enough to provide their
546own delay based flushing */
547
548int ogg_stream_pageout_fill(ogg_stream_state *os, ogg_page *og, int nfill){
549 int force=0;
550 if(ogg_stream_check(os)) return 0;
551
552 if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
553 (os->lacing_fill&&!os->b_o_s)) /* 'initial header page' case */
554 force=1;
555
556 return(ogg_stream_flush_i(os,og,force,nfill));
557}
558
559int ogg_stream_eos(ogg_stream_state *os){
560 if(ogg_stream_check(os)) return 1;
561 return os->e_o_s;
562}
563
564/* DECODING PRIMITIVES: packet streaming layer **********************/
565
566/* This has two layers to place more of the multi-serialno and paging
567 control in the application's hands. First, we expose a data buffer
568 using ogg_sync_buffer(). The app either copies into the
569 buffer, or passes it directly to read(), etc. We then call
570 ogg_sync_wrote() to tell how many bytes we just added.
571
572 Pages are returned (pointers into the buffer in ogg_sync_state)
573 by ogg_sync_pageout(). The page is then submitted to
574 ogg_stream_pagein() along with the appropriate
575 ogg_stream_state* (ie, matching serialno). We then get raw
576 packets out calling ogg_stream_packetout() with a
577 ogg_stream_state. */
578
579/* initialize the struct to a known state */
580int ogg_sync_init(ogg_sync_state *oy){
581 if(oy){
582 oy->storage = -1; /* used as a readiness flag */
583 memset(oy,0,sizeof(*oy));
584 }
585 return(0);
586}
587
588/* clear non-flat storage within */
589int ogg_sync_clear(ogg_sync_state *oy){
590 if(oy){
591 if(oy->data)_ogg_free(oy->data);
592 memset(oy,0,sizeof(*oy));
593 }
594 return(0);
595}
596
597int ogg_sync_destroy(ogg_sync_state *oy){
598 if(oy){
599 ogg_sync_clear(oy);
600 _ogg_free(oy);
601 }
602 return(0);
603}
604
605int ogg_sync_check(ogg_sync_state *oy){
606 if(oy->storage<0) return -1;
607 return 0;
608}
609
610char *ogg_sync_buffer(ogg_sync_state *oy, long size){
611 if(ogg_sync_check(oy)) return NULL;
612
613 /* first, clear out any space that has been previously returned */
614 if(oy->returned){
615 oy->fill-=oy->returned;
616 if(oy->fill>0)
617 memmove(oy->data,oy->data+oy->returned,oy->fill);
618 oy->returned=0;
619 }
620
621 if(size>oy->storage-oy->fill){
622 /* We need to extend the internal buffer */
623 long newsize=size+oy->fill+4096; /* an extra page to be nice */
624 void *ret;
625
626 if(oy->data)
627 ret=_ogg_realloc(oy->data,newsize);
628 else
629 ret=_ogg_malloc(newsize);
630 if(!ret){
631 ogg_sync_clear(oy);
632 return NULL;
633 }
634 oy->data=ret;
635 oy->storage=newsize;
636 }
637
638 /* expose a segment at least as large as requested at the fill mark */
639 return((char *)oy->data+oy->fill);
640}
641
642int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
643 if(ogg_sync_check(oy))return -1;
644 if(oy->fill+bytes>oy->storage)return -1;
645 oy->fill+=bytes;
646 return(0);
647}
648
649/* sync the stream. This is meant to be useful for finding page
650 boundaries.
651
652 return values for this:
653 -n) skipped n bytes
654 0) page not ready; more data (no bytes skipped)
655 n) page synced at current location; page length n bytes
656
657*/
658
659long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
660 unsigned char *page=oy->data+oy->returned;
661 unsigned char *next;
662 long bytes=oy->fill-oy->returned;
663
664 if(ogg_sync_check(oy))return 0;
665
666 if(oy->headerbytes==0){
667 int headerbytes,i;
668 if(bytes<27)return(0); /* not enough for a header */
669
670 /* verify capture pattern */
671 if(memcmp(page,"OggS",4))goto sync_fail;
672
673 headerbytes=page[26]+27;
674 if(bytes<headerbytes)return(0); /* not enough for header + seg table */
675
676 /* count up body length in the segment table */
677
678 for(i=0;i<page[26];i++)
679 oy->bodybytes+=page[27+i];
680 oy->headerbytes=headerbytes;
681 }
682
683 if(oy->bodybytes+oy->headerbytes>bytes)return(0);
684
685 /* The whole test page is buffered. Verify the checksum */
686 if (0) {
687 /* Grab the checksum bytes, set the header field to zero */
688 char chksum[4];
689 ogg_page log;
690
691 memcpy(chksum,page+22,4);
692 memset(page+22,0,4);
693
694 /* set up a temp page struct and recompute the checksum */
695 log.header=page;
696 log.header_len=oy->headerbytes;
697 log.body=page+oy->headerbytes;
698 log.body_len=oy->bodybytes;
699 ogg_page_checksum_set(&log);
700
701 /* Compare */
702 if(memcmp(chksum,page+22,4)){
703 /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
704 at all) */
705 /* replace the computed checksum with the one actually read in */
706 memcpy(page+22,chksum,4);
707
708 /* Bad checksum. Lose sync */
709 goto sync_fail;
710 }
711 }
712
713 /* yes, have a whole page all ready to go */
714 {
715 unsigned char *page=oy->data+oy->returned;
716 long bytes;
717
718 if(og){
719 og->header=page;
720 og->header_len=oy->headerbytes;
721 og->body=page+oy->headerbytes;
722 og->body_len=oy->bodybytes;
723 }
724
725 oy->unsynced=0;
726 oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
727 oy->headerbytes=0;
728 oy->bodybytes=0;
729 return(bytes);
730 }
731
732 sync_fail:
733
734 oy->headerbytes=0;
735 oy->bodybytes=0;
736
737 /* search for possible capture */
738 next=memchr(page+1,'O',bytes-1);
739 if(!next)
740 next=oy->data+oy->fill;
741
742 oy->returned=(int)(next-oy->data);
743 return((long)-(next-page));
744}
745
746/* sync the stream and get a page. Keep trying until we find a page.
747 Suppress 'sync errors' after reporting the first.
748
749 return values:
750 -1) recapture (hole in data)
751 0) need more data
752 1) page returned
753
754 Returns pointers into buffered data; invalidated by next call to
755 _stream, _clear, _init, or _buffer */
756
757int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
758
759 if(ogg_sync_check(oy))return 0;
760
761 /* all we need to do is verify a page at the head of the stream
762 buffer. If it doesn't verify, we look for the next potential
763 frame */
764
765 for(;;){
766 long ret=ogg_sync_pageseek(oy,og);
767 if(ret>0){
768 /* have a page */
769 return(1);
770 }
771 if(ret==0){
772 /* need more data */
773 return(0);
774 }
775
776 /* head did not start a synced page... skipped some bytes */
777 if(!oy->unsynced){
778 oy->unsynced=1;
779 return(-1);
780 }
781
782 /* loop. keep looking */
783 }
784}
785
786/* add the incoming page to the stream state; we decompose the page
787 into packet segments here as well. */
788
789int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
790 unsigned char *header=og->header;
791 unsigned char *body=og->body;
792 long bodysize=og->body_len;
793 int segptr=0;
794
795 int version=ogg_page_version(og);
796 int continued=ogg_page_continued(og);
797 int bos=ogg_page_bos(og);
798 int eos=ogg_page_eos(og);
799 ogg_int64_t granulepos=ogg_page_granulepos(og);
800 int serialno=ogg_page_serialno(og);
801 long pageno=ogg_page_pageno(og);
802 int segments=header[26];
803
804 if(ogg_stream_check(os)) return -1;
805
806 /* clean up 'returned data' */
807 {
808 long lr=os->lacing_returned;
809 long br=os->body_returned;
810
811 /* body data */
812 if(br){
813 os->body_fill-=br;
814 if(os->body_fill)
815 memmove(os->body_data,os->body_data+br,os->body_fill);
816 os->body_returned=0;
817 }
818
819 if(lr){
820 /* segment table */
821 if(os->lacing_fill-lr){
822 memmove(os->lacing_vals,os->lacing_vals+lr,
823 (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
824 memmove(os->granule_vals,os->granule_vals+lr,
825 (os->lacing_fill-lr)*sizeof(*os->granule_vals));
826 }
827 os->lacing_fill-=lr;
828 os->lacing_packet-=lr;
829 os->lacing_returned=0;
830 }
831 }
832
833 /* check the serial number */
834 if(serialno!=os->serialno)return(-1);
835 if(version>0)return(-1);
836
837 if(_os_lacing_expand(os,segments+1)) return -1;
838
839 /* are we in sequence? */
840 if(pageno!=os->pageno){
841 int i;
842
843 /* unroll previous partial packet (if any) */
844 for(i=os->lacing_packet;i<os->lacing_fill;i++)
845 os->body_fill-=os->lacing_vals[i]&0xff;
846 os->lacing_fill=os->lacing_packet;
847
848 /* make a note of dropped data in segment table */
849 if(os->pageno!=-1){
850 os->lacing_vals[os->lacing_fill++]=0x400;
851 os->lacing_packet++;
852 }
853 }
854
855 /* are we a 'continued packet' page? If so, we may need to skip
856 some segments */
857 if(continued){
858 if(os->lacing_fill<1 ||
859 os->lacing_vals[os->lacing_fill-1]==0x400){
860 bos=0;
861 for(;segptr<segments;segptr++){
862 int val=header[27+segptr];
863 body+=val;
864 bodysize-=val;
865 if(val<255){
866 segptr++;
867 break;
868 }
869 }
870 }
871 }
872
873 if(bodysize){
874 if(_os_body_expand(os,bodysize)) return -1;
875 memcpy(os->body_data+os->body_fill,body,bodysize);
876 os->body_fill+=bodysize;
877 }
878
879 {
880 int saved=-1;
881 while(segptr<segments){
882 int val=header[27+segptr];
883 os->lacing_vals[os->lacing_fill]=val;
884 os->granule_vals[os->lacing_fill]=-1;
885
886 if(bos){
887 os->lacing_vals[os->lacing_fill]|=0x100;
888 bos=0;
889 }
890
891 if(val<255)saved=os->lacing_fill;
892
893 os->lacing_fill++;
894 segptr++;
895
896 if(val<255)os->lacing_packet=os->lacing_fill;
897 }
898
899 /* set the granulepos on the last granuleval of the last full packet */
900 if(saved!=-1){
901 os->granule_vals[saved]=granulepos;
902 }
903
904 }
905
906 if(eos){
907 os->e_o_s=1;
908 if(os->lacing_fill>0)
909 os->lacing_vals[os->lacing_fill-1]|=0x200;
910 }
911
912 os->pageno=pageno+1;
913
914 return(0);
915}
916
917/* clear things to an initial state. Good to call, eg, before seeking */
918int ogg_sync_reset(ogg_sync_state *oy){
919 if(ogg_sync_check(oy))return -1;
920
921 oy->fill=0;
922 oy->returned=0;
923 oy->unsynced=0;
924 oy->headerbytes=0;
925 oy->bodybytes=0;
926 return(0);
927}
928
929int ogg_stream_reset(ogg_stream_state *os){
930 if(ogg_stream_check(os)) return -1;
931
932 os->body_fill=0;
933 os->body_returned=0;
934
935 os->lacing_fill=0;
936 os->lacing_packet=0;
937 os->lacing_returned=0;
938
939 os->header_fill=0;
940
941 os->e_o_s=0;
942 os->b_o_s=0;
943 os->pageno=-1;
944 os->packetno=0;
945 os->granulepos=0;
946
947 return(0);
948}
949
950int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
951 if(ogg_stream_check(os)) return -1;
952 ogg_stream_reset(os);
953 os->serialno=serialno;
954 return(0);
955}
956
957static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
958
959 /* The last part of decode. We have the stream broken into packet
960 segments. Now we need to group them into packets (or return the
961 out of sync markers) */
962
963 int ptr=os->lacing_returned;
964
965 if(os->lacing_packet<=ptr)return(0);
966
967 if(os->lacing_vals[ptr]&0x400){
968 /* we need to tell the codec there's a gap; it might need to
969 handle previous packet dependencies. */
970 os->lacing_returned++;
971 os->packetno++;
972 return(-1);
973 }
974
975 if(!op && !adv)return(1); /* just using peek as an inexpensive way
976 to ask if there's a whole packet
977 waiting */
978
979 /* Gather the whole packet. We'll have no holes or a partial packet */
980 {
981 int size=os->lacing_vals[ptr]&0xff;
982 long bytes=size;
983 int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
984 int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
985
986 while(size==255){
987 int val=os->lacing_vals[++ptr];
988 size=val&0xff;
989 if(val&0x200)eos=0x200;
990 bytes+=size;
991 }
992
993 if(op){
994 op->e_o_s=eos;
995 op->b_o_s=bos;
996 op->packet=os->body_data+os->body_returned;
997 op->packetno=os->packetno;
998 op->granulepos=os->granule_vals[ptr];
999 op->bytes=bytes;
1000 }
1001
1002 if(adv){
1003 os->body_returned+=bytes;
1004 os->lacing_returned=ptr+1;
1005 os->packetno++;
1006 }
1007 }
1008 return(1);
1009}
1010
1011int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
1012 if(ogg_stream_check(os)) return 0;
1013 return _packetout(os,op,1);
1014}
1015
1016int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
1017 if(ogg_stream_check(os)) return 0;
1018 return _packetout(os,op,0);
1019}
1020
1021void ogg_packet_clear(ogg_packet *op) {
1022 _ogg_free(op->packet);
1023 memset(op, 0, sizeof(*op));
1024}
1025
diff --git a/lib/rbcodec/codecs/libopus/ogg/ogg.h b/lib/rbcodec/codecs/libopus/ogg/ogg.h
new file mode 100644
index 0000000000..00975ca354
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/ogg/ogg.h
@@ -0,0 +1,210 @@
1/********************************************************************
2 * *
3 * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
4 * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
5 * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
6 * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
7 * *
8 * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007 *
9 * by the Xiph.Org Foundation http://www.xiph.org/ *
10 * *
11 ********************************************************************
12
13 function: toplevel libogg include
14 last mod: $Id: ogg.h 18044 2011-08-01 17:55:20Z gmaxwell $
15
16 ********************************************************************/
17#ifndef _OGG_H
18#define _OGG_H
19
20#ifdef __cplusplus
21extern "C" {
22#endif
23
24#include <stddef.h>
25#include "os_types.h"
26
27typedef struct {
28 void *iov_base;
29 size_t iov_len;
30} ogg_iovec_t;
31
32typedef struct {
33 long endbyte;
34 int endbit;
35
36 unsigned char *buffer;
37 unsigned char *ptr;
38 long storage;
39} oggpack_buffer;
40
41/* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
42
43typedef struct {
44 unsigned char *header;
45 long header_len;
46 unsigned char *body;
47 long body_len;
48} ogg_page;
49
50/* ogg_stream_state contains the current encode/decode state of a logical
51 Ogg bitstream **********************************************************/
52
53typedef struct {
54 unsigned char *body_data; /* bytes from packet bodies */
55 long body_storage; /* storage elements allocated */
56 long body_fill; /* elements stored; fill mark */
57 long body_returned; /* elements of fill returned */
58
59
60 int *lacing_vals; /* The values that will go to the segment table */
61 ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
62 this way, but it is simple coupled to the
63 lacing fifo */
64 long lacing_storage;
65 long lacing_fill;
66 long lacing_packet;
67 long lacing_returned;
68
69 unsigned char header[282]; /* working space for header encode */
70 int header_fill;
71
72 int e_o_s; /* set when we have buffered the last packet in the
73 logical bitstream */
74 int b_o_s; /* set after we've written the initial page
75 of a logical bitstream */
76 long serialno;
77 long pageno;
78 ogg_int64_t packetno; /* sequence number for decode; the framing
79 knows where there's a hole in the data,
80 but we need coupling so that the codec
81 (which is in a separate abstraction
82 layer) also knows about the gap */
83 ogg_int64_t granulepos;
84
85} ogg_stream_state;
86
87/* ogg_packet is used to encapsulate the data and metadata belonging
88 to a single raw Ogg/Vorbis packet *************************************/
89
90typedef struct {
91 unsigned char *packet;
92 long bytes;
93 long b_o_s;
94 long e_o_s;
95
96 ogg_int64_t granulepos;
97
98 ogg_int64_t packetno; /* sequence number for decode; the framing
99 knows where there's a hole in the data,
100 but we need coupling so that the codec
101 (which is in a separate abstraction
102 layer) also knows about the gap */
103} ogg_packet;
104
105typedef struct {
106 unsigned char *data;
107 int storage;
108 int fill;
109 int returned;
110
111 int unsynced;
112 int headerbytes;
113 int bodybytes;
114} ogg_sync_state;
115
116/* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
117
118extern void oggpack_writeinit(oggpack_buffer *b);
119extern int oggpack_writecheck(oggpack_buffer *b);
120extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
121extern void oggpack_writealign(oggpack_buffer *b);
122extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
123extern void oggpack_reset(oggpack_buffer *b);
124extern void oggpack_writeclear(oggpack_buffer *b);
125extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
126extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
127extern long oggpack_look(oggpack_buffer *b,int bits);
128extern long oggpack_look1(oggpack_buffer *b);
129extern void oggpack_adv(oggpack_buffer *b,int bits);
130extern void oggpack_adv1(oggpack_buffer *b);
131extern long oggpack_read(oggpack_buffer *b,int bits);
132extern long oggpack_read1(oggpack_buffer *b);
133extern long oggpack_bytes(oggpack_buffer *b);
134extern long oggpack_bits(oggpack_buffer *b);
135extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
136
137extern void oggpackB_writeinit(oggpack_buffer *b);
138extern int oggpackB_writecheck(oggpack_buffer *b);
139extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
140extern void oggpackB_writealign(oggpack_buffer *b);
141extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
142extern void oggpackB_reset(oggpack_buffer *b);
143extern void oggpackB_writeclear(oggpack_buffer *b);
144extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
145extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
146extern long oggpackB_look(oggpack_buffer *b,int bits);
147extern long oggpackB_look1(oggpack_buffer *b);
148extern void oggpackB_adv(oggpack_buffer *b,int bits);
149extern void oggpackB_adv1(oggpack_buffer *b);
150extern long oggpackB_read(oggpack_buffer *b,int bits);
151extern long oggpackB_read1(oggpack_buffer *b);
152extern long oggpackB_bytes(oggpack_buffer *b);
153extern long oggpackB_bits(oggpack_buffer *b);
154extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
155
156/* Ogg BITSTREAM PRIMITIVES: encoding **************************/
157
158extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
159extern int ogg_stream_iovecin(ogg_stream_state *os, ogg_iovec_t *iov,
160 int count, long e_o_s, ogg_int64_t granulepos);
161extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
162extern int ogg_stream_pageout_fill(ogg_stream_state *os, ogg_page *og, int nfill);
163extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
164extern int ogg_stream_flush_fill(ogg_stream_state *os, ogg_page *og, int nfill);
165
166/* Ogg BITSTREAM PRIMITIVES: decoding **************************/
167
168extern int ogg_sync_init(ogg_sync_state *oy);
169extern int ogg_sync_clear(ogg_sync_state *oy);
170extern int ogg_sync_reset(ogg_sync_state *oy);
171extern int ogg_sync_destroy(ogg_sync_state *oy);
172extern int ogg_sync_check(ogg_sync_state *oy);
173
174extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
175extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
176extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
177extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
178extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
179extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
180extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
181
182/* Ogg BITSTREAM PRIMITIVES: general ***************************/
183
184extern int ogg_stream_init(ogg_stream_state *os,int serialno);
185extern int ogg_stream_clear(ogg_stream_state *os);
186extern int ogg_stream_reset(ogg_stream_state *os);
187extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
188extern int ogg_stream_destroy(ogg_stream_state *os);
189extern int ogg_stream_check(ogg_stream_state *os);
190extern int ogg_stream_eos(ogg_stream_state *os);
191
192extern void ogg_page_checksum_set(ogg_page *og);
193
194extern int ogg_page_version(const ogg_page *og);
195extern int ogg_page_continued(const ogg_page *og);
196extern int ogg_page_bos(const ogg_page *og);
197extern int ogg_page_eos(const ogg_page *og);
198extern ogg_int64_t ogg_page_granulepos(const ogg_page *og);
199extern int ogg_page_serialno(const ogg_page *og);
200extern long ogg_page_pageno(const ogg_page *og);
201extern int ogg_page_packets(const ogg_page *og);
202
203extern void ogg_packet_clear(ogg_packet *op);
204
205
206#ifdef __cplusplus
207}
208#endif
209
210#endif /* _OGG_H */
diff --git a/lib/rbcodec/codecs/libopus/ogg/os_types.h b/lib/rbcodec/codecs/libopus/ogg/os_types.h
new file mode 100644
index 0000000000..55f0bf559c
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/ogg/os_types.h
@@ -0,0 +1,56 @@
1#include "config.h"
2#include <stdint.h>
3#include "codeclib.h"
4
5#ifdef SIMULATOR
6
7#include <stdio.h>
8
9static inline void* _ogg_malloc(size_t size)
10{
11 void *buf;
12
13 printf("ogg_malloc %d", size);
14 buf = codec_malloc(size);
15 printf(" = %p\n", buf);
16
17 return buf;
18}
19
20static inline void* _ogg_calloc(size_t nmemb, size_t size)
21{
22 printf("ogg_calloc %d %d\n", nmemb, size);
23 return codec_calloc(nmemb, size);
24}
25
26static inline void* _ogg_realloc(void *ptr, size_t size)
27{
28 void *buf;
29
30 printf("ogg_realloc %p %d", ptr, size);
31 buf = codec_realloc(ptr, size);
32 printf(" = %p\n", buf);
33 return buf;
34}
35
36static inline void _ogg_free(void *ptr)
37{
38 printf("ogg_free %p\n", ptr);
39 codec_free(ptr);
40}
41
42#else
43
44#define _ogg_malloc codec_malloc
45#define _ogg_calloc codec_calloc
46#define _ogg_realloc codec_realloc
47#define _ogg_free codec_free
48
49#endif
50
51typedef int16_t ogg_int16_t;
52typedef uint16_t ogg_uint16_t;
53typedef int32_t ogg_int32_t;
54typedef uint32_t ogg_uint32_t;
55typedef int64_t ogg_int64_t;
56
diff --git a/lib/rbcodec/codecs/libopus/opus.h b/lib/rbcodec/codecs/libopus/opus.h
new file mode 100644
index 0000000000..c242fec0e7
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus.h
@@ -0,0 +1,882 @@
1/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
2 Written by Jean-Marc Valin and Koen Vos */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28/**
29 * @file opus.h
30 * @brief Opus reference implementation API
31 */
32
33#ifndef OPUS_H
34#define OPUS_H
35
36#include "opus_types.h"
37#include "opus_defines.h"
38
39#ifdef __cplusplus
40extern "C" {
41#endif
42
43/**
44 * @mainpage Opus
45 *
46 * The Opus codec is designed for interactive speech and audio transmission over the Internet.
47 * It is designed by the IETF Codec Working Group and incorporates technology from
48 * Skype's SILK codec and Xiph.Org's CELT codec.
49 *
50 * The Opus codec is designed to handle a wide range of interactive audio applications,
51 * including Voice over IP, videoconferencing, in-game chat, and even remote live music
52 * performances. It can scale from low bit-rate narrowband speech to very high quality
53 * stereo music. Its main features are:
54
55 * @li Sampling rates from 8 to 48 kHz
56 * @li Bit-rates from 6 kb/s to 510 kb/s
57 * @li Support for both constant bit-rate (CBR) and variable bit-rate (VBR)
58 * @li Audio bandwidth from narrowband to full-band
59 * @li Support for speech and music
60 * @li Support for mono and stereo
61 * @li Support for multichannel (up to 255 channels)
62 * @li Frame sizes from 2.5 ms to 60 ms
63 * @li Good loss robustness and packet loss concealment (PLC)
64 * @li Floating point and fixed-point implementation
65 *
66 * Documentation sections:
67 * @li @ref opus_encoder
68 * @li @ref opus_decoder
69 * @li @ref opus_repacketizer
70 * @li @ref opus_multistream
71 * @li @ref opus_libinfo
72 * @li @ref opus_custom
73 */
74
75/** @defgroup opus_encoder Opus Encoder
76 * @{
77 *
78 * @brief This page describes the process and functions used to encode Opus.
79 *
80 * Since Opus is a stateful codec, the encoding process starts with creating an encoder
81 * state. This can be done with:
82 *
83 * @code
84 * int error;
85 * OpusEncoder *enc;
86 * enc = opus_encoder_create(Fs, channels, application, &error);
87 * @endcode
88 *
89 * From this point, @c enc can be used for encoding an audio stream. An encoder state
90 * @b must @b not be used for more than one stream at the same time. Similarly, the encoder
91 * state @b must @b not be re-initialized for each frame.
92 *
93 * While opus_encoder_create() allocates memory for the state, it's also possible
94 * to initialize pre-allocated memory:
95 *
96 * @code
97 * int size;
98 * int error;
99 * OpusEncoder *enc;
100 * size = opus_encoder_get_size(channels);
101 * enc = malloc(size);
102 * error = opus_encoder_init(enc, Fs, channels, application);
103 * @endcode
104 *
105 * where opus_encoder_get_size() returns the required size for the encoder state. Note that
106 * future versions of this code may change the size, so no assuptions should be made about it.
107 *
108 * The encoder state is always continuous in memory and only a shallow copy is sufficient
109 * to copy it (e.g. memcpy())
110 *
111 * It is possible to change some of the encoder's settings using the opus_encoder_ctl()
112 * interface. All these settings already default to the recommended value, so they should
113 * only be changed when necessary. The most common settings one may want to change are:
114 *
115 * @code
116 * opus_encoder_ctl(enc, OPUS_SET_BITRATE(bitrate));
117 * opus_encoder_ctl(enc, OPUS_SET_COMPLEXITY(complexity));
118 * opus_encoder_ctl(enc, OPUS_SET_SIGNAL(signal_type));
119 * @endcode
120 *
121 * where
122 *
123 * @arg bitrate is in bits per second (b/s)
124 * @arg complexity is a value from 1 to 10, where 1 is the lowest complexity and 10 is the highest
125 * @arg signal_type is either OPUS_AUTO (default), OPUS_SIGNAL_VOICE, or OPUS_SIGNAL_MUSIC
126 *
127 * See @ref opus_encoderctls and @ref opus_genericctls for a complete list of parameters that can be set or queried. Most parameters can be set or changed at any time during a stream.
128 *
129 * To encode a frame, opus_encode() or opus_encode_float() must be called with exactly one frame (2.5, 5, 10, 20, 40 or 60 ms) of audio data:
130 * @code
131 * len = opus_encode(enc, audio_frame, frame_size, packet, max_packet);
132 * @endcode
133 *
134 * where
135 * <ul>
136 * <li>audio_frame is the audio data in opus_int16 (or float for opus_encode_float())</li>
137 * <li>frame_size is the duration of the frame in samples (per channel)</li>
138 * <li>packet is the byte array to which the compressed data is written</li>
139 * <li>max_packet is the maximum number of bytes that can be written in the packet (4000 bytes is recommended)</li>
140 * </ul>
141 *
142 * opus_encode() and opus_encode_frame() return the number of bytes actually written to the packet.
143 * The return value <b>can be negative</b>, which indicates that an error has occurred. If the return value
144 * is 1 byte, then the packet does not need to be transmitted (DTX).
145 *
146 * Once the encoder state if no longer needed, it can be destroyed with
147 *
148 * @code
149 * opus_encoder_destroy(enc);
150 * @endcode
151 *
152 * If the encoder was created with opus_encoder_init() rather than opus_encoder_create(),
153 * then no action is required aside from potentially freeing the memory that was manually
154 * allocated for it (calling free(enc) for the example above)
155 *
156 */
157
158/** Opus encoder state.
159 * This contains the complete state of an Opus encoder.
160 * It is position independent and can be freely copied.
161 * @see opus_encoder_create,opus_encoder_init
162 */
163typedef struct OpusEncoder OpusEncoder;
164
165/** Gets the size of an <code>OpusEncoder</code> structure.
166 * @param[in] channels <tt>int</tt>: Number of channels.
167 * This must be 1 or 2.
168 * @returns The size in bytes.
169 */
170OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_encoder_get_size(int channels);
171
172/**
173 */
174
175/** Allocates and initializes an encoder state.
176 * There are three coding modes:
177 *
178 * @ref OPUS_APPLICATION_VOIP gives best quality at a given bitrate for voice
179 * signals. It enhances the input signal by high-pass filtering and
180 * emphasizing formants and harmonics. Optionally it includes in-band
181 * forward error correction to protect against packet loss. Use this
182 * mode for typical VoIP applications. Because of the enhancement,
183 * even at high bitrates the output may sound different from the input.
184 *
185 * @ref OPUS_APPLICATION_AUDIO gives best quality at a given bitrate for most
186 * non-voice signals like music. Use this mode for music and mixed
187 * (music/voice) content, broadcast, and applications requiring less
188 * than 15 ms of coding delay.
189 *
190 * @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY configures low-delay mode that
191 * disables the speech-optimized mode in exchange for slightly reduced delay.
192 * This mode can only be set on an newly initialized or freshly reset encoder
193 * because it changes the codec delay.
194 *
195 * This is useful when the caller knows that the speech-optimized modes will not be needed (use with caution).
196 * @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)
197 * This must be one of 8000, 12000, 16000,
198 * 24000, or 48000.
199 * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal
200 * @param [in] application <tt>int</tt>: Coding mode (@ref OPUS_APPLICATION_VOIP/@ref OPUS_APPLICATION_AUDIO/@ref OPUS_APPLICATION_RESTRICTED_LOWDELAY)
201 * @param [out] error <tt>int*</tt>: @ref opus_errorcodes
202 * @note Regardless of the sampling rate and number channels selected, the Opus encoder
203 * can switch to a lower audio bandwidth or number of channels if the bitrate
204 * selected is too low. This also means that it is safe to always use 48 kHz stereo input
205 * and let the encoder optimize the encoding.
206 */
207OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusEncoder *opus_encoder_create(
208 opus_int32 Fs,
209 int channels,
210 int application,
211 int *error
212);
213
214/** Initializes a previously allocated encoder state
215 * The memory pointed to by st must be at least the size returned by opus_encoder_get_size().
216 * This is intended for applications which use their own allocator instead of malloc.
217 * @see opus_encoder_create(),opus_encoder_get_size()
218 * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.
219 * @param [in] st <tt>OpusEncoder*</tt>: Encoder state
220 * @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)
221 * This must be one of 8000, 12000, 16000,
222 * 24000, or 48000.
223 * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal
224 * @param [in] application <tt>int</tt>: Coding mode (OPUS_APPLICATION_VOIP/OPUS_APPLICATION_AUDIO/OPUS_APPLICATION_RESTRICTED_LOWDELAY)
225 * @retval #OPUS_OK Success or @ref opus_errorcodes
226 */
227OPUS_EXPORT int opus_encoder_init(
228 OpusEncoder *st,
229 opus_int32 Fs,
230 int channels,
231 int application
232) OPUS_ARG_NONNULL(1);
233
234/** Encodes an Opus frame.
235 * @param [in] st <tt>OpusEncoder*</tt>: Encoder state
236 * @param [in] pcm <tt>opus_int16*</tt>: Input signal (interleaved if 2 channels). length is frame_size*channels*sizeof(opus_int16)
237 * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the
238 * input signal.
239 * This must be an Opus frame size for
240 * the encoder's sampling rate.
241 * For example, at 48 kHz the permitted
242 * values are 120, 240, 480, 960, 1920,
243 * and 2880.
244 * Passing in a duration of less than
245 * 10 ms (480 samples at 48 kHz) will
246 * prevent the encoder from using the LPC
247 * or hybrid modes.
248 * @param [out] data <tt>unsigned char*</tt>: Output payload.
249 * This must contain storage for at
250 * least \a max_data_bytes.
251 * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated
252 * memory for the output
253 * payload. This may be
254 * used to impose an upper limit on
255 * the variable bitrate, but should
256 * not be used as the only bitrate
257 * control.
258 * @returns The length of the encoded packet (in bytes) on success or a
259 * negative error code (see @ref opus_errorcodes) on failure.
260 */
261OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_encode(
262 OpusEncoder *st,
263 const opus_int16 *pcm,
264 int frame_size,
265 unsigned char *data,
266 opus_int32 max_data_bytes
267) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4);
268
269/** Encodes an Opus frame from floating point input.
270 * @param [in] st <tt>OpusEncoder*</tt>: Encoder state
271 * @param [in] pcm <tt>float*</tt>: Input in float format (interleaved if 2 channels), with a normal range of +/-1.0.
272 * Samples with a range beyond +/-1.0 are supported but will
273 * be clipped by decoders using the integer API and should
274 * only be used if it is known that the far end supports
275 * extended dynamic range.
276 * length is frame_size*channels*sizeof(float)
277 * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the
278 * input signal.
279 * This must be an Opus frame size for
280 * the encoder's sampling rate.
281 * For example, at 48 kHz the permitted
282 * values are 120, 240, 480, 960, 1920,
283 * and 2880.
284 * Passing in a duration of less than
285 * 10 ms (480 samples at 48 kHz) will
286 * prevent the encoder from using the LPC
287 * or hybrid modes.
288 * @param [out] data <tt>unsigned char*</tt>: Output payload.
289 * This must contain storage for at
290 * least \a max_data_bytes.
291 * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated
292 * memory for the output
293 * payload. This may be
294 * used to impose an upper limit on
295 * the variable bitrate, but should
296 * not be used as the only bitrate
297 * control.
298 * @returns The length of the encoded packet (in bytes) on success or a
299 * negative error code (see @ref opus_errorcodes) on failure.
300 */
301OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_encode_float(
302 OpusEncoder *st,
303 const float *pcm,
304 int frame_size,
305 unsigned char *data,
306 opus_int32 max_data_bytes
307) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4);
308
309/** Frees an <code>OpusEncoder</code> allocated by opus_encoder_create().
310 * @param[in] st <tt>OpusEncoder*</tt>: State to be freed.
311 */
312OPUS_EXPORT void opus_encoder_destroy(OpusEncoder *st);
313
314/** Perform a CTL function on an Opus encoder.
315 *
316 * Generally the request and subsequent arguments are generated
317 * by a convenience macro.
318 * @param st <tt>OpusEncoder*</tt>: Encoder state.
319 * @param request This and all remaining parameters should be replaced by one
320 * of the convenience macros in @ref opus_genericctls or
321 * @ref opus_encoderctls.
322 * @see opus_genericctls
323 * @see opus_encoderctls
324 */
325OPUS_EXPORT int opus_encoder_ctl(OpusEncoder *st, int request, ...) OPUS_ARG_NONNULL(1);
326/**@}*/
327
328/** @defgroup opus_decoder Opus Decoder
329 * @{
330 *
331 * @brief This page describes the process and functions used to decode Opus.
332 *
333 * The decoding process also starts with creating a decoder
334 * state. This can be done with:
335 * @code
336 * int error;
337 * OpusDecoder *dec;
338 * dec = opus_decoder_create(Fs, channels, &error);
339 * @endcode
340 * where
341 * @li Fs is the sampling rate and must be 8000, 12000, 16000, 24000, or 48000
342 * @li channels is the number of channels (1 or 2)
343 * @li error will hold the error code in case or failure (or #OPUS_OK on success)
344 * @li the return value is a newly created decoder state to be used for decoding
345 *
346 * While opus_decoder_create() allocates memory for the state, it's also possible
347 * to initialize pre-allocated memory:
348 * @code
349 * int size;
350 * int error;
351 * OpusDecoder *dec;
352 * size = opus_decoder_get_size(channels);
353 * dec = malloc(size);
354 * error = opus_decoder_init(dec, Fs, channels);
355 * @endcode
356 * where opus_decoder_get_size() returns the required size for the decoder state. Note that
357 * future versions of this code may change the size, so no assuptions should be made about it.
358 *
359 * The decoder state is always continuous in memory and only a shallow copy is sufficient
360 * to copy it (e.g. memcpy())
361 *
362 * To decode a frame, opus_decode() or opus_decode_float() must be called with a packet of compressed audio data:
363 * @code
364 * frame_size = opus_decode(dec, packet, len, decoded, max_size, 0);
365 * @endcode
366 * where
367 *
368 * @li packet is the byte array containing the compressed data
369 * @li len is the exact number of bytes contained in the packet
370 * @li decoded is the decoded audio data in opus_int16 (or float for opus_decode_float())
371 * @li max_size is the max duration of the frame in samples (per channel) that can fit into the decoded_frame array
372 *
373 * opus_decode() and opus_decode_float() return the number of samples (per channel) decoded from the packet.
374 * If that value is negative, then an error has occured. This can occur if the packet is corrupted or if the audio
375 * buffer is too small to hold the decoded audio.
376 *
377 * Opus is a stateful codec with overlapping blocks and as a result Opus
378 * packets are not coded independently of each other. Packets must be
379 * passed into the decoder serially and in the correct order for a correct
380 * decode. Lost packets can be replaced with loss concealment by calling
381 * the decoder with a null pointer and zero length for the missing packet.
382 *
383 * A single codec state may only be accessed from a single thread at
384 * a time and any required locking must be performed by the caller. Separate
385 * streams must be decoded with separate decoder states and can be decoded
386 * in parallel unless the library was compiled with NONTHREADSAFE_PSEUDOSTACK
387 * defined.
388 *
389 */
390
391/** Opus decoder state.
392 * This contains the complete state of an Opus decoder.
393 * It is position independent and can be freely copied.
394 * @see opus_decoder_create,opus_decoder_init
395 */
396typedef struct OpusDecoder OpusDecoder;
397
398/** Gets the size of an <code>OpusDecoder</code> structure.
399 * @param [in] channels <tt>int</tt>: Number of channels.
400 * This must be 1 or 2.
401 * @returns The size in bytes.
402 */
403OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decoder_get_size(int channels);
404
405/** Allocates and initializes a decoder state.
406 * @param [in] Fs <tt>opus_int32</tt>: Sample rate to decode at (Hz).
407 * This must be one of 8000, 12000, 16000,
408 * 24000, or 48000.
409 * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode
410 * @param [out] error <tt>int*</tt>: #OPUS_OK Success or @ref opus_errorcodes
411 *
412 * Internally Opus stores data at 48000 Hz, so that should be the default
413 * value for Fs. However, the decoder can efficiently decode to buffers
414 * at 8, 12, 16, and 24 kHz so if for some reason the caller cannot use
415 * data at the full sample rate, or knows the compressed data doesn't
416 * use the full frequency range, it can request decoding at a reduced
417 * rate. Likewise, the decoder is capable of filling in either mono or
418 * interleaved stereo pcm buffers, at the caller's request.
419 */
420OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusDecoder *opus_decoder_create(
421 opus_int32 Fs,
422 int channels,
423 int *error
424);
425
426/** Initializes a previously allocated decoder state.
427 * The state must be at least the size returned by opus_decoder_get_size().
428 * This is intended for applications which use their own allocator instead of malloc. @see opus_decoder_create,opus_decoder_get_size
429 * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.
430 * @param [in] st <tt>OpusDecoder*</tt>: Decoder state.
431 * @param [in] Fs <tt>opus_int32</tt>: Sampling rate to decode to (Hz).
432 * This must be one of 8000, 12000, 16000,
433 * 24000, or 48000.
434 * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode
435 * @retval #OPUS_OK Success or @ref opus_errorcodes
436 */
437OPUS_EXPORT int opus_decoder_init(
438 OpusDecoder *st,
439 opus_int32 Fs,
440 int channels
441) OPUS_ARG_NONNULL(1);
442
443/** Decode an Opus packet.
444 * @param [in] st <tt>OpusDecoder*</tt>: Decoder state
445 * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
446 * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload*
447 * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length
448 * is frame_size*channels*sizeof(opus_int16)
449 * @param [in] frame_size Number of samples per channel of available space in \a pcm.
450 * If this is less than the maximum frame size (120 ms), this function will
451 * not be capable of decoding some packets.
452 * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be
453 * decoded. If no such data is available, the frame is decoded as if it were lost.
454 * @returns Number of decoded samples or @ref opus_errorcodes
455 */
456OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decode(
457 OpusDecoder *st,
458 const unsigned char *data,
459 opus_int32 len,
460 opus_int16 *pcm,
461 int frame_size,
462 int decode_fec
463) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4);
464
465/** Decode an Opus packet with floating point output.
466 * @param [in] st <tt>OpusDecoder*</tt>: Decoder state
467 * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
468 * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload
469 * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length
470 * is frame_size*channels*sizeof(float)
471 * @param [in] frame_size Number of samples per channel of available space in *pcm,
472 * if less than the maximum frame size (120ms) some frames can not be decoded
473 * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be
474 * decoded. If no such data is available the frame is decoded as if it were lost.
475 * @returns Number of decoded samples or @ref opus_errorcodes
476 */
477OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decode_float(
478 OpusDecoder *st,
479 const unsigned char *data,
480 opus_int32 len,
481 float *pcm,
482 int frame_size,
483 int decode_fec
484) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4);
485
486/** Perform a CTL function on an Opus decoder.
487 *
488 * Generally the request and subsequent arguments are generated
489 * by a convenience macro.
490 * @param st <tt>OpusDecoder*</tt>: Decoder state.
491 * @param request This and all remaining parameters should be replaced by one
492 * of the convenience macros in @ref opus_genericctls or
493 * @ref opus_decoderctls.
494 * @see opus_genericctls
495 * @see opus_decoderctls
496 */
497OPUS_EXPORT int opus_decoder_ctl(OpusDecoder *st, int request, ...) OPUS_ARG_NONNULL(1);
498
499/** Frees an <code>OpusDecoder</code> allocated by opus_decoder_create().
500 * @param[in] st <tt>OpusDecoder*</tt>: State to be freed.
501 */
502OPUS_EXPORT void opus_decoder_destroy(OpusDecoder *st);
503
504/** Parse an opus packet into one or more frames.
505 * Opus_decode will perform this operation internally so most applications do
506 * not need to use this function.
507 * This function does not copy the frames, the returned pointers are pointers into
508 * the input packet.
509 * @param [in] data <tt>char*</tt>: Opus packet to be parsed
510 * @param [in] len <tt>opus_int32</tt>: size of data
511 * @param [out] out_toc <tt>char*</tt>: TOC pointer
512 * @param [out] frames <tt>char*[48]</tt> encapsulated frames
513 * @param [out] size <tt>short[48]</tt> sizes of the encapsulated frames
514 * @param [out] payload_offset <tt>int*</tt>: returns the position of the payload within the packet (in bytes)
515 * @returns number of frames
516 */
517OPUS_EXPORT int opus_packet_parse(
518 const unsigned char *data,
519 opus_int32 len,
520 unsigned char *out_toc,
521 const unsigned char *frames[48],
522 short size[48],
523 int *payload_offset
524) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4);
525
526/** Gets the bandwidth of an Opus packet.
527 * @param [in] data <tt>char*</tt>: Opus packet
528 * @retval OPUS_BANDWIDTH_NARROWBAND Narrowband (4kHz bandpass)
529 * @retval OPUS_BANDWIDTH_MEDIUMBAND Mediumband (6kHz bandpass)
530 * @retval OPUS_BANDWIDTH_WIDEBAND Wideband (8kHz bandpass)
531 * @retval OPUS_BANDWIDTH_SUPERWIDEBAND Superwideband (12kHz bandpass)
532 * @retval OPUS_BANDWIDTH_FULLBAND Fullband (20kHz bandpass)
533 * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
534 */
535OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_bandwidth(const unsigned char *data) OPUS_ARG_NONNULL(1);
536
537/** Gets the number of samples per frame from an Opus packet.
538 * @param [in] data <tt>char*</tt>: Opus packet.
539 * This must contain at least one byte of
540 * data.
541 * @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz.
542 * This must be a multiple of 400, or
543 * inaccurate results will be returned.
544 * @returns Number of samples per frame.
545 */
546OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_samples_per_frame(const unsigned char *data, opus_int32 Fs) OPUS_ARG_NONNULL(1);
547
548/** Gets the number of channels from an Opus packet.
549 * @param [in] data <tt>char*</tt>: Opus packet
550 * @returns Number of channels
551 * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
552 */
553OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_channels(const unsigned char *data) OPUS_ARG_NONNULL(1);
554
555/** Gets the number of frames in an Opus packet.
556 * @param [in] packet <tt>char*</tt>: Opus packet
557 * @param [in] len <tt>opus_int32</tt>: Length of packet
558 * @returns Number of frames
559 * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
560 */
561OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_packet_get_nb_frames(const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1);
562
563/** Gets the number of samples of an Opus packet.
564 * @param [in] dec <tt>OpusDecoder*</tt>: Decoder state
565 * @param [in] packet <tt>char*</tt>: Opus packet
566 * @param [in] len <tt>opus_int32</tt>: Length of packet
567 * @returns Number of samples
568 * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type
569 */
570OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_decoder_get_nb_samples(const OpusDecoder *dec, const unsigned char packet[], opus_int32 len) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2);
571/**@}*/
572
573/** @defgroup opus_repacketizer Repacketizer
574 * @{
575 *
576 * The repacketizer can be used to merge multiple Opus packets into a single
577 * packet or alternatively to split Opus packets that have previously been
578 * merged. Splitting valid Opus packets is always guaranteed to succeed,
579 * whereas merging valid packets only succeeds if all frames have the same
580 * mode, bandwidth, and frame size, and when the total duration of the merged
581 * packet is no more than 120 ms.
582 * The repacketizer currently only operates on elementary Opus
583 * streams. It will not manipualte multistream packets successfully, except in
584 * the degenerate case where they consist of data from a single stream.
585 *
586 * The repacketizing process starts with creating a repacketizer state, either
587 * by calling opus_repacketizer_create() or by allocating the memory yourself,
588 * e.g.,
589 * @code
590 * OpusRepacketizer *rp;
591 * rp = (OpusRepacketizer*)malloc(opus_repacketizer_get_size());
592 * if (rp != NULL)
593 * opus_repacketizer_init(rp);
594 * @endcode
595 *
596 * Then the application should submit packets with opus_repacketizer_cat(),
597 * extract new packets with opus_repacketizer_out() or
598 * opus_repacketizer_out_range(), and then reset the state for the next set of
599 * input packets via opus_repacketizer_init().
600 *
601 * For example, to split a sequence of packets into individual frames:
602 * @code
603 * unsigned char *data;
604 * int len;
605 * while (get_next_packet(&data, &len))
606 * {
607 * unsigned char out[1276];
608 * opus_int32 out_len;
609 * int nb_frames;
610 * int err;
611 * int i;
612 * err = opus_repacketizer_cat(rp, data, len);
613 * if (err != OPUS_OK)
614 * {
615 * release_packet(data);
616 * return err;
617 * }
618 * nb_frames = opus_repacketizer_get_nb_frames(rp);
619 * for (i = 0; i < nb_frames; i++)
620 * {
621 * out_len = opus_repacketizer_out_range(rp, i, i+1, out, sizeof(out));
622 * if (out_len < 0)
623 * {
624 * release_packet(data);
625 * return (int)out_len;
626 * }
627 * output_next_packet(out, out_len);
628 * }
629 * opus_repacketizer_init(rp);
630 * release_packet(data);
631 * }
632 * @endcode
633 *
634 * Alternatively, to combine a sequence of frames into packets that each
635 * contain up to <code>TARGET_DURATION_MS</code> milliseconds of data:
636 * @code
637 * // The maximum number of packets with duration TARGET_DURATION_MS occurs
638 * // when the frame size is 2.5 ms, for a total of (TARGET_DURATION_MS*2/5)
639 * // packets.
640 * unsigned char *data[(TARGET_DURATION_MS*2/5)+1];
641 * opus_int32 len[(TARGET_DURATION_MS*2/5)+1];
642 * int nb_packets;
643 * unsigned char out[1277*(TARGET_DURATION_MS*2/2)];
644 * opus_int32 out_len;
645 * int prev_toc;
646 * nb_packets = 0;
647 * while (get_next_packet(data+nb_packets, len+nb_packets))
648 * {
649 * int nb_frames;
650 * int err;
651 * nb_frames = opus_packet_get_nb_frames(data[nb_packets], len[nb_packets]);
652 * if (nb_frames < 1)
653 * {
654 * release_packets(data, nb_packets+1);
655 * return nb_frames;
656 * }
657 * nb_frames += opus_repacketizer_get_nb_frames(rp);
658 * // If adding the next packet would exceed our target, or it has an
659 * // incompatible TOC sequence, output the packets we already have before
660 * // submitting it.
661 * // N.B., The nb_packets > 0 check ensures we've submitted at least one
662 * // packet since the last call to opus_repacketizer_init(). Otherwise a
663 * // single packet longer than TARGET_DURATION_MS would cause us to try to
664 * // output an (invalid) empty packet. It also ensures that prev_toc has
665 * // been set to a valid value. Additionally, len[nb_packets] > 0 is
666 * // guaranteed by the call to opus_packet_get_nb_frames() above, so the
667 * // reference to data[nb_packets][0] should be valid.
668 * if (nb_packets > 0 && (
669 * ((prev_toc & 0xFC) != (data[nb_packets][0] & 0xFC)) ||
670 * opus_packet_get_samples_per_frame(data[nb_packets], 48000)*nb_frames >
671 * TARGET_DURATION_MS*48))
672 * {
673 * out_len = opus_repacketizer_out(rp, out, sizeof(out));
674 * if (out_len < 0)
675 * {
676 * release_packets(data, nb_packets+1);
677 * return (int)out_len;
678 * }
679 * output_next_packet(out, out_len);
680 * opus_repacketizer_init(rp);
681 * release_packets(data, nb_packets);
682 * data[0] = data[nb_packets];
683 * len[0] = len[nb_packets];
684 * nb_packets = 0;
685 * }
686 * err = opus_repacketizer_cat(rp, data[nb_packets], len[nb_packets]);
687 * if (err != OPUS_OK)
688 * {
689 * release_packets(data, nb_packets+1);
690 * return err;
691 * }
692 * prev_toc = data[nb_packets][0];
693 * nb_packets++;
694 * }
695 * // Output the final, partial packet.
696 * if (nb_packets > 0)
697 * {
698 * out_len = opus_repacketizer_out(rp, out, sizeof(out));
699 * release_packets(data, nb_packets);
700 * if (out_len < 0)
701 * return (int)out_len;
702 * output_next_packet(out, out_len);
703 * }
704 * @endcode
705 *
706 * An alternate way of merging packets is to simply call opus_repacketizer_cat()
707 * unconditionally until it fails. At that point, the merged packet can be
708 * obtained with opus_repacketizer_out() and the input packet for which
709 * opus_repacketizer_cat() needs to be re-added to a newly reinitialized
710 * repacketizer state.
711 */
712
713typedef struct OpusRepacketizer OpusRepacketizer;
714
715/** Gets the size of an <code>OpusRepacketizer</code> structure.
716 * @returns The size in bytes.
717 */
718OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_repacketizer_get_size(void);
719
720/** (Re)initializes a previously allocated repacketizer state.
721 * The state must be at least the size returned by opus_repacketizer_get_size().
722 * This can be used for applications which use their own allocator instead of
723 * malloc().
724 * It must also be called to reset the queue of packets waiting to be
725 * repacketized, which is necessary if the maximum packet duration of 120 ms
726 * is reached or if you wish to submit packets with a different Opus
727 * configuration (coding mode, audio bandwidth, frame size, or channel count).
728 * Failure to do so will prevent a new packet from being added with
729 * opus_repacketizer_cat().
730 * @see opus_repacketizer_create
731 * @see opus_repacketizer_get_size
732 * @see opus_repacketizer_cat
733 * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to
734 * (re)initialize.
735 * @returns A pointer to the same repacketizer state that was passed in.
736 */
737OPUS_EXPORT OpusRepacketizer *opus_repacketizer_init(OpusRepacketizer *rp) OPUS_ARG_NONNULL(1);
738
739/** Allocates memory and initializes the new repacketizer with
740 * opus_repacketizer_init().
741 */
742OPUS_EXPORT OPUS_WARN_UNUSED_RESULT OpusRepacketizer *opus_repacketizer_create(void);
743
744/** Frees an <code>OpusRepacketizer</code> allocated by
745 * opus_repacketizer_create().
746 * @param[in] rp <tt>OpusRepacketizer*</tt>: State to be freed.
747 */
748OPUS_EXPORT void opus_repacketizer_destroy(OpusRepacketizer *rp);
749
750/** Add a packet to the current repacketizer state.
751 * This packet must match the configuration of any packets already submitted
752 * for repacketization since the last call to opus_repacketizer_init().
753 * This means that it must have the same coding mode, audio bandwidth, frame
754 * size, and channel count.
755 * This can be checked in advance by examining the top 6 bits of the first
756 * byte of the packet, and ensuring they match the top 6 bits of the first
757 * byte of any previously submitted packet.
758 * The total duration of audio in the repacketizer state also must not exceed
759 * 120 ms, the maximum duration of a single packet, after adding this packet.
760 *
761 * The contents of the current repacketizer state can be extracted into new
762 * packets using opus_repacketizer_out() or opus_repacketizer_out_range().
763 *
764 * In order to add a packet with a different configuration or to add more
765 * audio beyond 120 ms, you must clear the repacketizer state by calling
766 * opus_repacketizer_init().
767 * If a packet is too large to add to the current repacketizer state, no part
768 * of it is added, even if it contains multiple frames, some of which might
769 * fit.
770 * If you wish to be able to add parts of such packets, you should first use
771 * another repacketizer to split the packet into pieces and add them
772 * individually.
773 * @see opus_repacketizer_out_range
774 * @see opus_repacketizer_out
775 * @see opus_repacketizer_init
776 * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to which to
777 * add the packet.
778 * @param[in] data <tt>const unsigned char*</tt>: The packet data.
779 * The application must ensure
780 * this pointer remains valid
781 * until the next call to
782 * opus_repacketizer_init() or
783 * opus_repacketizer_destroy().
784 * @param len <tt>opus_int32</tt>: The number of bytes in the packet data.
785 * @returns An error code indicating whether or not the operation succeeded.
786 * @retval #OPUS_OK The packet's contents have been added to the repacketizer
787 * state.
788 * @retval #OPUS_INVALID_PACKET The packet did not have a valid TOC sequence,
789 * the packet's TOC sequence was not compatible
790 * with previously submitted packets (because
791 * the coding mode, audio bandwidth, frame size,
792 * or channel count did not match), or adding
793 * this packet would increase the total amount of
794 * audio stored in the repacketizer state to more
795 * than 120 ms.
796 */
797OPUS_EXPORT int opus_repacketizer_cat(OpusRepacketizer *rp, const unsigned char *data, opus_int32 len) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2);
798
799
800/** Construct a new packet from data previously submitted to the repacketizer
801 * state via opus_repacketizer_cat().
802 * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to
803 * construct the new packet.
804 * @param begin <tt>int</tt>: The index of the first frame in the current
805 * repacketizer state to include in the output.
806 * @param end <tt>int</tt>: One past the index of the last frame in the
807 * current repacketizer state to include in the
808 * output.
809 * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to
810 * store the output packet.
811 * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in
812 * the output buffer. In order to guarantee
813 * success, this should be at least
814 * <code>1276</code> for a single frame,
815 * or for multiple frames,
816 * <code>1277*(end-begin)</code>.
817 * However, <code>1*(end-begin)</code> plus
818 * the size of all packet data submitted to
819 * the repacketizer since the last call to
820 * opus_repacketizer_init() or
821 * opus_repacketizer_create() is also
822 * sufficient, and possibly much smaller.
823 * @returns The total size of the output packet on success, or an error code
824 * on failure.
825 * @retval #OPUS_BAD_ARG <code>[begin,end)</code> was an invalid range of
826 * frames (begin < 0, begin >= end, or end >
827 * opus_repacketizer_get_nb_frames()).
828 * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the
829 * complete output packet.
830 */
831OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_repacketizer_out_range(OpusRepacketizer *rp, int begin, int end, unsigned char *data, opus_int32 maxlen) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4);
832
833/** Return the total number of frames contained in packet data submitted to
834 * the repacketizer state so far via opus_repacketizer_cat() since the last
835 * call to opus_repacketizer_init() or opus_repacketizer_create().
836 * This defines the valid range of packets that can be extracted with
837 * opus_repacketizer_out_range() or opus_repacketizer_out().
838 * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state containing the
839 * frames.
840 * @returns The total number of frames contained in the packet data submitted
841 * to the repacketizer state.
842 */
843OPUS_EXPORT OPUS_WARN_UNUSED_RESULT int opus_repacketizer_get_nb_frames(OpusRepacketizer *rp) OPUS_ARG_NONNULL(1);
844
845/** Construct a new packet from data previously submitted to the repacketizer
846 * state via opus_repacketizer_cat().
847 * This is a convenience routine that returns all the data submitted so far
848 * in a single packet.
849 * It is equivalent to calling
850 * @code
851 * opus_repacketizer_out_range(rp, 0, opus_repacketizer_get_nb_frames(rp),
852 * data, maxlen)
853 * @endcode
854 * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to
855 * construct the new packet.
856 * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to
857 * store the output packet.
858 * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in
859 * the output buffer. In order to guarantee
860 * success, this should be at least
861 * <code>1277*opus_repacketizer_get_nb_frames(rp)</code>.
862 * However,
863 * <code>1*opus_repacketizer_get_nb_frames(rp)</code>
864 * plus the size of all packet data
865 * submitted to the repacketizer since the
866 * last call to opus_repacketizer_init() or
867 * opus_repacketizer_create() is also
868 * sufficient, and possibly much smaller.
869 * @returns The total size of the output packet on success, or an error code
870 * on failure.
871 * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the
872 * complete output packet.
873 */
874OPUS_EXPORT OPUS_WARN_UNUSED_RESULT opus_int32 opus_repacketizer_out(OpusRepacketizer *rp, unsigned char *data, opus_int32 maxlen) OPUS_ARG_NONNULL(1);
875
876/**@}*/
877
878#ifdef __cplusplus
879}
880#endif
881
882#endif /* OPUS_H */
diff --git a/lib/rbcodec/codecs/libopus/opus_config.h b/lib/rbcodec/codecs/libopus/opus_config.h
new file mode 100644
index 0000000000..86210df52b
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_config.h
@@ -0,0 +1,42 @@
1#ifndef CONFIG_H
2#define CONFIG_H
3
4#include "config.h"
5#include "codeclib.h"
6
7/* general stuff */
8#define OPUS_BUILD
9
10/* alloc stuff */
11#define NONTHREADSAFE_PSEUDOSTACK
12
13#define OVERRIDE_OPUS_ALLOC
14#define OVERRIDE_OPUS_FREE
15#define OVERRIDE_OPUS_ALLOC_SCRATCH
16
17#define opus_alloc codec_malloc
18#define opus_free codec_free
19#define opus_alloc_scratch codec_malloc
20
21/* lrint */
22#define HAVE_LRINTF 0
23#define HAVE_LRINT 0
24
25/* embedded stuff */
26#define FIXED_POINT
27#define DISABLE_FLOAT_API
28#define EMBEDDED_ARM 1
29
30/* undefinitions */
31#ifdef ABS
32#undef ABS
33#endif
34#ifdef MIN
35#undef MIN
36#endif
37#ifdef MAX
38#undef MAX
39#endif
40
41#endif /* CONFIG_H */
42
diff --git a/lib/rbcodec/codecs/libopus/opus_custom.h b/lib/rbcodec/codecs/libopus/opus_custom.h
new file mode 100644
index 0000000000..e7861d6f0a
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_custom.h
@@ -0,0 +1,329 @@
1/* Copyright (c) 2007-2008 CSIRO
2 Copyright (c) 2007-2009 Xiph.Org Foundation
3 Copyright (c) 2008-2012 Gregory Maxwell
4 Written by Jean-Marc Valin and Gregory Maxwell */
5/*
6 Redistribution and use in source and binary forms, with or without
7 modification, are permitted provided that the following conditions
8 are met:
9
10 - Redistributions of source code must retain the above copyright
11 notice, this list of conditions and the following disclaimer.
12
13 - Redistributions in binary form must reproduce the above copyright
14 notice, this list of conditions and the following disclaimer in the
15 documentation and/or other materials provided with the distribution.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*/
29
30/**
31 @file opus_custom.h
32 @brief Opus-Custom reference implementation API
33 */
34
35#ifndef OPUS_CUSTOM_H
36#define OPUS_CUSTOM_H
37
38#include "opus_defines.h"
39
40#ifdef __cplusplus
41extern "C" {
42#endif
43
44#ifdef CUSTOM_MODES
45#define OPUS_CUSTOM_EXPORT OPUS_EXPORT
46#define OPUS_CUSTOM_EXPORT_STATIC OPUS_EXPORT
47#else
48#define OPUS_CUSTOM_EXPORT
49#ifdef CELT_C
50#define OPUS_CUSTOM_EXPORT_STATIC static inline
51#else
52#define OPUS_CUSTOM_EXPORT_STATIC
53#endif
54#endif
55
56/** @defgroup opus_custom Opus Custom
57 * @{
58 * Opus Custom is an optional part of the Opus specification and
59 * reference implementation which uses a distinct API from the regular
60 * API and supports frame sizes that are not normally supported.\ Use
61 * of Opus Custom is discouraged for all but very special applications
62 * for which a frame size different from 2.5, 5, 10, or 20 ms is needed
63 * (for either complexity or latency reasons) and where interoperability
64 * is less important.
65 *
66 * In addition to the interoperability limitations the use of Opus custom
67 * disables a substantial chunk of the codec and generally lowers the
68 * quality available at a given bitrate. Normally when an application needs
69 * a different frame size from the codec it should buffer to match the
70 * sizes but this adds a small amount of delay which may be important
71 * in some very low latency applications. Some transports (especially
72 * constant rate RF transports) may also work best with frames of
73 * particular durations.
74 *
75 * Libopus only supports custom modes if they are enabled at compile time.
76 *
77 * The Opus Custom API is similar to the regular API but the
78 * @ref opus_encoder_create and @ref opus_decoder_create calls take
79 * an additional mode parameter which is a structure produced by
80 * a call to @ref opus_custom_mode_create. Both the encoder and decoder
81 * must create a mode using the same sample rate (fs) and frame size
82 * (frame size) so these parameters must either be signaled out of band
83 * or fixed in a particular implementation.
84 *
85 * Similar to regular Opus the custom modes support on the fly frame size
86 * switching, but the sizes available depend on the particular frame size in
87 * use. For some initial frame sizes on a single on the fly size is available.
88 */
89
90/** Contains the state of an encoder. One encoder state is needed
91 for each stream. It is initialized once at the beginning of the
92 stream. Do *not* re-initialize the state for every frame.
93 @brief Encoder state
94 */
95typedef struct OpusCustomEncoder OpusCustomEncoder;
96
97/** State of the decoder. One decoder state is needed for each stream.
98 It is initialized once at the beginning of the stream. Do *not*
99 re-initialize the state for every frame.
100 @brief Decoder state
101 */
102typedef struct OpusCustomDecoder OpusCustomDecoder;
103
104/** The mode contains all the information necessary to create an
105 encoder. Both the encoder and decoder need to be initialized
106 with exactly the same mode, otherwise the output will be
107 corrupted.
108 @brief Mode configuration
109 */
110typedef struct OpusCustomMode OpusCustomMode;
111
112/** Creates a new mode struct. This will be passed to an encoder or
113 * decoder. The mode MUST NOT BE DESTROYED until the encoders and
114 * decoders that use it are destroyed as well.
115 * @param [in] Fs <tt>int</tt>: Sampling rate (8000 to 96000 Hz)
116 * @param [in] frame_size <tt>int</tt>: Number of samples (per channel) to encode in each
117 * packet (64 - 1024, prime factorization must contain zero or more 2s, 3s, or 5s and no other primes)
118 * @param [out] error <tt>int*</tt>: Returned error code (if NULL, no error will be returned)
119 * @return A newly created mode
120 */
121OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomMode *opus_custom_mode_create(opus_int32 Fs, int frame_size, int *error);
122
123/** Destroys a mode struct. Only call this after all encoders and
124 * decoders using this mode are destroyed as well.
125 * @param [in] mode <tt>OpusCustomMode*</tt>: Mode to be freed.
126 */
127OPUS_CUSTOM_EXPORT void opus_custom_mode_destroy(OpusCustomMode *mode);
128
129/* Encoder */
130/** Gets the size of an OpusCustomEncoder structure.
131 * @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration
132 * @param [in] channels <tt>int</tt>: Number of channels
133 * @returns size
134 */
135OPUS_CUSTOM_EXPORT_STATIC OPUS_WARN_UNUSED_RESULT int opus_custom_encoder_get_size(
136 const OpusCustomMode *mode,
137 int channels
138) OPUS_ARG_NONNULL(1);
139
140/** Creates a new encoder state. Each stream needs its own encoder
141 * state (can't be shared across simultaneous streams).
142 * @param [in] mode <tt>OpusCustomMode*</tt>: Contains all the information about the characteristics of
143 * the stream (must be the same characteristics as used for the
144 * decoder)
145 * @param [in] channels <tt>int</tt>: Number of channels
146 * @param [out] error <tt>int*</tt>: Returns an error code
147 * @return Newly created encoder state.
148*/
149OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomEncoder *opus_custom_encoder_create(
150 const OpusCustomMode *mode,
151 int channels,
152 int *error
153) OPUS_ARG_NONNULL(1);
154
155/** Initializes a previously allocated encoder state
156 * The memory pointed to by st must be the size returned by opus_custom_encoder_get_size.
157 * This is intended for applications which use their own allocator instead of malloc.
158 * @see opus_custom_encoder_create(),opus_custom_encoder_get_size()
159 * To reset a previously initialized state use the OPUS_RESET_STATE CTL.
160 * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state
161 * @param [in] mode <tt>OpusCustomMode *</tt>: Contains all the information about the characteristics of
162 * the stream (must be the same characteristics as used for the
163 * decoder)
164 * @param [in] channels <tt>int</tt>: Number of channels
165 * @return OPUS_OK Success or @ref opus_errorcodes
166 */
167OPUS_CUSTOM_EXPORT_STATIC int opus_custom_encoder_init(
168 OpusCustomEncoder *st,
169 const OpusCustomMode *mode,
170 int channels
171) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2);
172
173/** Destroys a an encoder state.
174 * @param[in] st <tt>OpusCustomEncoder*</tt>: State to be freed.
175 */
176OPUS_CUSTOM_EXPORT void opus_custom_encoder_destroy(OpusCustomEncoder *st);
177
178/** Encodes a frame of audio.
179 * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state
180 * @param [in] pcm <tt>float*</tt>: PCM audio in float format, with a normal range of +/-1.0.
181 * Samples with a range beyond +/-1.0 are supported but will
182 * be clipped by decoders using the integer API and should
183 * only be used if it is known that the far end supports
184 * extended dynamic range. There must be exactly
185 * frame_size samples per channel.
186 * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal
187 * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.
188 * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame
189 * (can change from one frame to another)
190 * @return Number of bytes written to "compressed".
191 * If negative, an error has occurred (see error codes). It is IMPORTANT that
192 * the length returned be somehow transmitted to the decoder. Otherwise, no
193 * decoding is possible.
194 */
195OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_encode_float(
196 OpusCustomEncoder *st,
197 const float *pcm,
198 int frame_size,
199 unsigned char *compressed,
200 int maxCompressedBytes
201) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4);
202
203/** Encodes a frame of audio.
204 * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state
205 * @param [in] pcm <tt>opus_int16*</tt>: PCM audio in signed 16-bit format (native endian).
206 * There must be exactly frame_size samples per channel.
207 * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal
208 * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.
209 * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame
210 * (can change from one frame to another)
211 * @return Number of bytes written to "compressed".
212 * If negative, an error has occurred (see error codes). It is IMPORTANT that
213 * the length returned be somehow transmitted to the decoder. Otherwise, no
214 * decoding is possible.
215 */
216OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_encode(
217 OpusCustomEncoder *st,
218 const opus_int16 *pcm,
219 int frame_size,
220 unsigned char *compressed,
221 int maxCompressedBytes
222) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2) OPUS_ARG_NONNULL(4);
223
224/** Perform a CTL function on an Opus custom encoder.
225 *
226 * Generally the request and subsequent arguments are generated
227 * by a convenience macro.
228 * @see opus_encoderctls
229 */
230OPUS_CUSTOM_EXPORT int opus_custom_encoder_ctl(OpusCustomEncoder * OPUS_RESTRICT st, int request, ...) OPUS_ARG_NONNULL(1);
231
232/* Decoder */
233
234/** Gets the size of an OpusCustomDecoder structure.
235 * @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration
236 * @param [in] channels <tt>int</tt>: Number of channels
237 * @returns size
238 */
239OPUS_CUSTOM_EXPORT_STATIC OPUS_WARN_UNUSED_RESULT int opus_custom_decoder_get_size(
240 const OpusCustomMode *mode,
241 int channels
242) OPUS_ARG_NONNULL(1);
243
244/** Creates a new decoder state. Each stream needs its own decoder state (can't
245 * be shared across simultaneous streams).
246 * @param [in] mode <tt>OpusCustomMode</tt>: Contains all the information about the characteristics of the
247 * stream (must be the same characteristics as used for the encoder)
248 * @param [in] channels <tt>int</tt>: Number of channels
249 * @param [out] error <tt>int*</tt>: Returns an error code
250 * @return Newly created decoder state.
251 */
252OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT OpusCustomDecoder *opus_custom_decoder_create(
253 const OpusCustomMode *mode,
254 int channels,
255 int *error
256) OPUS_ARG_NONNULL(1);
257
258/** Initializes a previously allocated decoder state
259 * The memory pointed to by st must be the size returned by opus_custom_decoder_get_size.
260 * This is intended for applications which use their own allocator instead of malloc.
261 * @see opus_custom_decoder_create(),opus_custom_decoder_get_size()
262 * To reset a previously initialized state use the OPUS_RESET_STATE CTL.
263 * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state
264 * @param [in] mode <tt>OpusCustomMode *</tt>: Contains all the information about the characteristics of
265 * the stream (must be the same characteristics as used for the
266 * encoder)
267 * @param [in] channels <tt>int</tt>: Number of channels
268 * @return OPUS_OK Success or @ref opus_errorcodes
269 */
270OPUS_CUSTOM_EXPORT_STATIC int opus_custom_decoder_init(
271 OpusCustomDecoder *st,
272 const OpusCustomMode *mode,
273 int channels
274) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(2);
275
276/** Destroys a an decoder state.
277 * @param[in] st <tt>OpusCustomDecoder*</tt>: State to be freed.
278 */
279OPUS_CUSTOM_EXPORT void opus_custom_decoder_destroy(OpusCustomDecoder *st);
280
281/** Decode an opus custom frame with floating point output
282 * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state
283 * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
284 * @param [in] len <tt>int</tt>: Number of bytes in payload
285 * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length
286 * is frame_size*channels*sizeof(float)
287 * @param [in] frame_size Number of samples per channel of available space in *pcm.
288 * @returns Number of decoded samples or @ref opus_errorcodes
289 */
290OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_decode_float(
291 OpusCustomDecoder *st,
292 const unsigned char *data,
293 int len,
294 float *pcm,
295 int frame_size
296) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4);
297
298/** Decode an opus custom frame
299 * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state
300 * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss
301 * @param [in] len <tt>int</tt>: Number of bytes in payload
302 * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length
303 * is frame_size*channels*sizeof(opus_int16)
304 * @param [in] frame_size Number of samples per channel of available space in *pcm.
305 * @returns Number of decoded samples or @ref opus_errorcodes
306 */
307OPUS_CUSTOM_EXPORT OPUS_WARN_UNUSED_RESULT int opus_custom_decode(
308 OpusCustomDecoder *st,
309 const unsigned char *data,
310 int len,
311 opus_int16 *pcm,
312 int frame_size
313) OPUS_ARG_NONNULL(1) OPUS_ARG_NONNULL(4);
314
315/** Perform a CTL function on an Opus custom decoder.
316 *
317 * Generally the request and subsequent arguments are generated
318 * by a convenience macro.
319 * @see opus_genericctls
320 */
321OPUS_CUSTOM_EXPORT int opus_custom_decoder_ctl(OpusCustomDecoder * OPUS_RESTRICT st, int request, ...) OPUS_ARG_NONNULL(1);
322
323/**@}*/
324
325#ifdef __cplusplus
326}
327#endif
328
329#endif /* OPUS_CUSTOM_H */
diff --git a/lib/rbcodec/codecs/libopus/opus_decoder.c b/lib/rbcodec/codecs/libopus/opus_decoder.c
new file mode 100644
index 0000000000..7103b183b8
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_decoder.c
@@ -0,0 +1,999 @@
1/* Copyright (c) 2010 Xiph.Org Foundation, Skype Limited
2 Written by Jean-Marc Valin and Koen Vos */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#ifndef OPUS_BUILD
33#error "OPUS_BUILD _MUST_ be defined to build Opus and you probably want a decent config.h, see README for more details."
34#endif
35
36#include <stdarg.h>
37#include "celt.h"
38#include "opus.h"
39#include "entdec.h"
40#include "modes.h"
41#include "API.h"
42#include "stack_alloc.h"
43#include "float_cast.h"
44#include "opus_private.h"
45#include "os_support.h"
46#include "structs.h"
47#include "define.h"
48#include "mathops.h"
49
50struct OpusDecoder {
51 int celt_dec_offset;
52 int silk_dec_offset;
53 int channels;
54 opus_int32 Fs; /** Sampling rate (at the API level) */
55 silk_DecControlStruct DecControl;
56 int decode_gain;
57
58 /* Everything beyond this point gets cleared on a reset */
59#define OPUS_DECODER_RESET_START stream_channels
60 int stream_channels;
61
62 int bandwidth;
63 int mode;
64 int prev_mode;
65 int frame_size;
66 int prev_redundancy;
67
68 opus_uint32 rangeFinal;
69};
70
71#ifdef FIXED_POINT
72static inline opus_int16 SAT16(opus_int32 x) {
73 return x > 32767 ? 32767 : x < -32768 ? -32768 : (opus_int16)x;
74}
75#endif
76
77
78int opus_decoder_get_size(int channels)
79{
80 int silkDecSizeBytes, celtDecSizeBytes;
81 int ret;
82 if (channels<1 || channels > 2)
83 return 0;
84 ret = silk_Get_Decoder_Size( &silkDecSizeBytes );
85 if(ret)
86 return 0;
87 silkDecSizeBytes = align(silkDecSizeBytes);
88 celtDecSizeBytes = celt_decoder_get_size(channels);
89 return align(sizeof(OpusDecoder))+silkDecSizeBytes+celtDecSizeBytes;
90}
91
92int opus_decoder_init(OpusDecoder *st, opus_int32 Fs, int channels)
93{
94 void *silk_dec;
95 CELTDecoder *celt_dec;
96 int ret, silkDecSizeBytes;
97
98 if ((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)
99 || (channels!=1&&channels!=2))
100 return OPUS_BAD_ARG;
101
102 OPUS_CLEAR((char*)st, opus_decoder_get_size(channels));
103 /* Initialize SILK encoder */
104 ret = silk_Get_Decoder_Size(&silkDecSizeBytes);
105 if (ret)
106 return OPUS_INTERNAL_ERROR;
107
108 silkDecSizeBytes = align(silkDecSizeBytes);
109 st->silk_dec_offset = align(sizeof(OpusDecoder));
110 st->celt_dec_offset = st->silk_dec_offset+silkDecSizeBytes;
111 silk_dec = (char*)st+st->silk_dec_offset;
112 celt_dec = (CELTDecoder*)((char*)st+st->celt_dec_offset);
113 st->stream_channels = st->channels = channels;
114
115 st->Fs = Fs;
116 st->DecControl.API_sampleRate = st->Fs;
117 st->DecControl.nChannelsAPI = st->channels;
118
119 /* Reset decoder */
120 ret = silk_InitDecoder( silk_dec );
121 if(ret)return OPUS_INTERNAL_ERROR;
122
123 /* Initialize CELT decoder */
124 ret = celt_decoder_init(celt_dec, Fs, channels);
125 if(ret!=OPUS_OK)return OPUS_INTERNAL_ERROR;
126
127 celt_decoder_ctl(celt_dec, CELT_SET_SIGNALLING(0));
128
129 st->prev_mode = 0;
130 st->frame_size = Fs/400;
131 return OPUS_OK;
132}
133
134OpusDecoder *opus_decoder_create(opus_int32 Fs, int channels, int *error)
135{
136 int ret;
137 OpusDecoder *st;
138 if ((Fs!=48000&&Fs!=24000&&Fs!=16000&&Fs!=12000&&Fs!=8000)
139 || (channels!=1&&channels!=2))
140 {
141 if (error)
142 *error = OPUS_BAD_ARG;
143 return NULL;
144 }
145 st = (OpusDecoder *)opus_alloc(opus_decoder_get_size(channels));
146 if (st == NULL)
147 {
148 if (error)
149 *error = OPUS_ALLOC_FAIL;
150 return NULL;
151 }
152 ret = opus_decoder_init(st, Fs, channels);
153 if (error)
154 *error = ret;
155 if (ret != OPUS_OK)
156 {
157 opus_free(st);
158 st = NULL;
159 }
160 return st;
161}
162
163static void smooth_fade(const opus_val16 *in1, const opus_val16 *in2,
164 opus_val16 *out, int overlap, int channels,
165 const opus_val16 *window, opus_int32 Fs)
166{
167 int i, c;
168 int inc = 48000/Fs;
169 for (c=0;c<channels;c++)
170 {
171 for (i=0;i<overlap;i++)
172 {
173 opus_val16 w = MULT16_16_Q15(window[i*inc], window[i*inc]);
174 out[i*channels+c] = SHR32(MAC16_16(MULT16_16(w,in2[i*channels+c]),
175 Q15ONE-w, in1[i*channels+c]), 15);
176 }
177 }
178}
179
180static int opus_packet_get_mode(const unsigned char *data)
181{
182 int mode;
183 if (data[0]&0x80)
184 {
185 mode = MODE_CELT_ONLY;
186 } else if ((data[0]&0x60) == 0x60)
187 {
188 mode = MODE_HYBRID;
189 } else {
190 mode = MODE_SILK_ONLY;
191 }
192 return mode;
193}
194
195static int opus_decode_frame(OpusDecoder *st, const unsigned char *data,
196 opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
197{
198 void *silk_dec;
199 CELTDecoder *celt_dec;
200 int i, silk_ret=0, celt_ret=0;
201 ec_dec dec;
202 opus_int32 silk_frame_size;
203 VARDECL(opus_int16, pcm_silk);
204 VARDECL(opus_val16, pcm_transition);
205 VARDECL(opus_val16, redundant_audio);
206
207 int audiosize;
208 int mode;
209 int transition=0;
210 int start_band;
211 int redundancy=0;
212 int redundancy_bytes = 0;
213 int celt_to_silk=0;
214 int c;
215 int F2_5, F5, F10, F20;
216 const opus_val16 *window;
217 opus_uint32 redundant_rng = 0;
218 ALLOC_STACK;
219
220 silk_dec = (char*)st+st->silk_dec_offset;
221 celt_dec = (CELTDecoder*)((char*)st+st->celt_dec_offset);
222 F20 = st->Fs/50;
223 F10 = F20>>1;
224 F5 = F10>>1;
225 F2_5 = F5>>1;
226 if (frame_size < F2_5)
227 {
228 RESTORE_STACK;
229 return OPUS_BUFFER_TOO_SMALL;
230 }
231 /* Limit frame_size to avoid excessive stack allocations. */
232 frame_size = IMIN(frame_size, st->Fs/25*3);
233 /* Payloads of 1 (2 including ToC) or 0 trigger the PLC/DTX */
234 if (len<=1)
235 {
236 data = NULL;
237 /* In that case, don't conceal more than what the ToC says */
238 frame_size = IMIN(frame_size, st->frame_size);
239 }
240 if (data != NULL)
241 {
242 audiosize = st->frame_size;
243 mode = st->mode;
244 ec_dec_init(&dec,(unsigned char*)data,len);
245 } else {
246 audiosize = frame_size;
247
248 if (st->prev_mode == 0)
249 {
250 /* If we haven't got any packet yet, all we can do is return zeros */
251 for (i=0;i<audiosize*st->channels;i++)
252 pcm[i] = 0;
253 RESTORE_STACK;
254 return audiosize;
255 } else {
256 mode = st->prev_mode;
257 }
258 }
259
260 /* For CELT/hybrid PLC of more than 20 ms, do multiple calls */
261 if (data==NULL && frame_size > F20 && mode != MODE_SILK_ONLY)
262 {
263 int nb_samples = 0;
264 do {
265 int ret = opus_decode_frame(st, NULL, 0, pcm, F20, 0);
266 if (ret != F20)
267 {
268 RESTORE_STACK;
269 return OPUS_INTERNAL_ERROR;
270 }
271 pcm += F20*st->channels;
272 nb_samples += F20;
273 } while (nb_samples < frame_size);
274 RESTORE_STACK;
275 return frame_size;
276 }
277 ALLOC(pcm_transition, F5*st->channels, opus_val16);
278
279 if (data!=NULL && st->prev_mode > 0 && (
280 (mode == MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY && !st->prev_redundancy)
281 || (mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY) )
282 )
283 {
284 transition = 1;
285 if (mode == MODE_CELT_ONLY)
286 opus_decode_frame(st, NULL, 0, pcm_transition, IMIN(F5, audiosize), 0);
287 }
288 if (audiosize > frame_size)
289 {
290 /*fprintf(stderr, "PCM buffer too small: %d vs %d (mode = %d)\n", audiosize, frame_size, mode);*/
291 RESTORE_STACK;
292 return OPUS_BAD_ARG;
293 } else {
294 frame_size = audiosize;
295 }
296
297 ALLOC(pcm_silk, IMAX(F10, frame_size)*st->channels, opus_int16);
298 ALLOC(redundant_audio, F5*st->channels, opus_val16);
299
300 /* SILK processing */
301 if (mode != MODE_CELT_ONLY)
302 {
303 int lost_flag, decoded_samples;
304 opus_int16 *pcm_ptr = pcm_silk;
305
306 if (st->prev_mode==MODE_CELT_ONLY)
307 silk_InitDecoder( silk_dec );
308
309 /* The SILK PLC cannot produce frames of less than 10 ms */
310 st->DecControl.payloadSize_ms = IMAX(10, 1000 * audiosize / st->Fs);
311
312 if (data != NULL)
313 {
314 st->DecControl.nChannelsInternal = st->stream_channels;
315 if( mode == MODE_SILK_ONLY ) {
316 if( st->bandwidth == OPUS_BANDWIDTH_NARROWBAND ) {
317 st->DecControl.internalSampleRate = 8000;
318 } else if( st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND ) {
319 st->DecControl.internalSampleRate = 12000;
320 } else if( st->bandwidth == OPUS_BANDWIDTH_WIDEBAND ) {
321 st->DecControl.internalSampleRate = 16000;
322 } else {
323 st->DecControl.internalSampleRate = 16000;
324 silk_assert( 0 );
325 }
326 } else {
327 /* Hybrid mode */
328 st->DecControl.internalSampleRate = 16000;
329 }
330 }
331
332 lost_flag = data == NULL ? 1 : 2 * decode_fec;
333 decoded_samples = 0;
334 do {
335 /* Call SILK decoder */
336 int first_frame = decoded_samples == 0;
337 silk_ret = silk_Decode( silk_dec, &st->DecControl,
338 lost_flag, first_frame, &dec, pcm_ptr, &silk_frame_size );
339 if( silk_ret ) {
340 if (lost_flag) {
341 /* PLC failure should not be fatal */
342 silk_frame_size = frame_size;
343 for (i=0;i<frame_size*st->channels;i++)
344 pcm_ptr[i] = 0;
345 } else {
346 RESTORE_STACK;
347 return OPUS_INVALID_PACKET;
348 }
349 }
350 pcm_ptr += silk_frame_size * st->channels;
351 decoded_samples += silk_frame_size;
352 } while( decoded_samples < frame_size );
353 }
354
355 start_band = 0;
356 if (!decode_fec && mode != MODE_CELT_ONLY && data != NULL
357 && ec_tell(&dec)+17+20*(st->mode == MODE_HYBRID) <= 8*len)
358 {
359 /* Check if we have a redundant 0-8 kHz band */
360 if (mode == MODE_HYBRID)
361 redundancy = ec_dec_bit_logp(&dec, 12);
362 else
363 redundancy = 1;
364 if (redundancy)
365 {
366 celt_to_silk = ec_dec_bit_logp(&dec, 1);
367 /* redundancy_bytes will be at least two, in the non-hybrid
368 case due to the ec_tell() check above */
369 redundancy_bytes = mode==MODE_HYBRID ?
370 (opus_int32)ec_dec_uint(&dec, 256)+2 :
371 len-((ec_tell(&dec)+7)>>3);
372 len -= redundancy_bytes;
373 /* This is a sanity check. It should never happen for a valid
374 packet, so the exact behaviour is not normative. */
375 if (len*8 < ec_tell(&dec))
376 {
377 len = 0;
378 redundancy_bytes = 0;
379 redundancy = 0;
380 }
381 /* Shrink decoder because of raw bits */
382 dec.storage -= redundancy_bytes;
383 }
384 }
385 if (mode != MODE_CELT_ONLY)
386 start_band = 17;
387
388 {
389 int endband=21;
390
391 switch(st->bandwidth)
392 {
393 case OPUS_BANDWIDTH_NARROWBAND:
394 endband = 13;
395 break;
396 case OPUS_BANDWIDTH_MEDIUMBAND:
397 case OPUS_BANDWIDTH_WIDEBAND:
398 endband = 17;
399 break;
400 case OPUS_BANDWIDTH_SUPERWIDEBAND:
401 endband = 19;
402 break;
403 case OPUS_BANDWIDTH_FULLBAND:
404 endband = 21;
405 break;
406 }
407 celt_decoder_ctl(celt_dec, CELT_SET_END_BAND(endband));
408 celt_decoder_ctl(celt_dec, CELT_SET_CHANNELS(st->stream_channels));
409 }
410
411 if (redundancy)
412 transition = 0;
413
414 if (transition && mode != MODE_CELT_ONLY)
415 opus_decode_frame(st, NULL, 0, pcm_transition, IMIN(F5, audiosize), 0);
416
417 /* 5 ms redundant frame for CELT->SILK*/
418 if (redundancy && celt_to_silk)
419 {
420 celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
421 celt_decode_with_ec(celt_dec, data+len, redundancy_bytes,
422 redundant_audio, F5, NULL);
423 celt_decoder_ctl(celt_dec, OPUS_GET_FINAL_RANGE(&redundant_rng));
424 }
425
426 /* MUST be after PLC */
427 celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(start_band));
428
429 if (mode != MODE_SILK_ONLY)
430 {
431 int celt_frame_size = IMIN(F20, frame_size);
432 /* Make sure to discard any previous CELT state */
433 if (mode != st->prev_mode && st->prev_mode > 0 && !st->prev_redundancy)
434 celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
435 /* Decode CELT */
436 celt_ret = celt_decode_with_ec(celt_dec, decode_fec ? NULL : data,
437 len, pcm, celt_frame_size, &dec);
438 } else {
439 unsigned char silence[2] = {0xFF, 0xFF};
440 for (i=0;i<frame_size*st->channels;i++)
441 pcm[i] = 0;
442 /* For hybrid -> SILK transitions, we let the CELT MDCT
443 do a fade-out by decoding a silence frame */
444 if (st->prev_mode == MODE_HYBRID && !(redundancy && celt_to_silk && st->prev_redundancy) )
445 {
446 celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
447 celt_decode_with_ec(celt_dec, silence, 2, pcm, F2_5, NULL);
448 }
449 }
450
451 if (mode != MODE_CELT_ONLY)
452 {
453#ifdef FIXED_POINT
454 for (i=0;i<frame_size*st->channels;i++)
455 pcm[i] = SAT16(pcm[i] + pcm_silk[i]);
456#else
457 for (i=0;i<frame_size*st->channels;i++)
458 pcm[i] = pcm[i] + (opus_val16)((1.f/32768.f)*pcm_silk[i]);
459#endif
460 }
461
462 {
463 const CELTMode *celt_mode;
464 celt_decoder_ctl(celt_dec, CELT_GET_MODE(&celt_mode));
465 window = celt_mode->window;
466 }
467
468 /* 5 ms redundant frame for SILK->CELT */
469 if (redundancy && !celt_to_silk)
470 {
471 celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
472 celt_decoder_ctl(celt_dec, CELT_SET_START_BAND(0));
473
474 celt_decode_with_ec(celt_dec, data+len, redundancy_bytes, redundant_audio, F5, NULL);
475 celt_decoder_ctl(celt_dec, OPUS_GET_FINAL_RANGE(&redundant_rng));
476 smooth_fade(pcm+st->channels*(frame_size-F2_5), redundant_audio+st->channels*F2_5,
477 pcm+st->channels*(frame_size-F2_5), F2_5, st->channels, window, st->Fs);
478 }
479 if (redundancy && celt_to_silk)
480 {
481 for (c=0;c<st->channels;c++)
482 {
483 for (i=0;i<F2_5;i++)
484 pcm[st->channels*i+c] = redundant_audio[st->channels*i+c];
485 }
486 smooth_fade(redundant_audio+st->channels*F2_5, pcm+st->channels*F2_5,
487 pcm+st->channels*F2_5, F2_5, st->channels, window, st->Fs);
488 }
489 if (transition)
490 {
491 if (audiosize >= F5)
492 {
493 for (i=0;i<st->channels*F2_5;i++)
494 pcm[i] = pcm_transition[i];
495 smooth_fade(pcm_transition+st->channels*F2_5, pcm+st->channels*F2_5,
496 pcm+st->channels*F2_5, F2_5,
497 st->channels, window, st->Fs);
498 } else {
499 /* Not enough time to do a clean transition, but we do it anyway
500 This will not preserve amplitude perfectly and may introduce
501 a bit of temporal aliasing, but it shouldn't be too bad and
502 that's pretty much the best we can do. In any case, generating this
503 transition it pretty silly in the first place */
504 smooth_fade(pcm_transition, pcm,
505 pcm, F2_5,
506 st->channels, window, st->Fs);
507 }
508 }
509
510 if(st->decode_gain)
511 {
512 opus_val32 gain;
513 gain = celt_exp2(MULT16_16_P15(QCONST16(6.48814081e-4f, 25), st->decode_gain));
514 for (i=0;i<frame_size*st->channels;i++)
515 {
516 opus_val32 x;
517 x = MULT16_32_P16(pcm[i],gain);
518 pcm[i] = SATURATE(x, 32767);
519 }
520 }
521
522 if (len <= 1)
523 st->rangeFinal = 0;
524 else
525 st->rangeFinal = dec.rng ^ redundant_rng;
526
527 st->prev_mode = mode;
528 st->prev_redundancy = redundancy && !celt_to_silk;
529 RESTORE_STACK;
530 return celt_ret < 0 ? celt_ret : audiosize;
531
532}
533
534static int parse_size(const unsigned char *data, opus_int32 len, short *size)
535{
536 if (len<1)
537 {
538 *size = -1;
539 return -1;
540 } else if (data[0]<252)
541 {
542 *size = data[0];
543 return 1;
544 } else if (len<2)
545 {
546 *size = -1;
547 return -1;
548 } else {
549 *size = 4*data[1] + data[0];
550 return 2;
551 }
552}
553
554static int opus_packet_parse_impl(const unsigned char *data, opus_int32 len,
555 int self_delimited, unsigned char *out_toc,
556 const unsigned char *frames[48], short size[48], int *payload_offset)
557{
558 int i, bytes;
559 int count;
560 int cbr;
561 unsigned char ch, toc;
562 int framesize;
563 int last_size;
564 const unsigned char *data0 = data;
565
566 if (size==NULL)
567 return OPUS_BAD_ARG;
568
569 framesize = opus_packet_get_samples_per_frame(data, 48000);
570
571 cbr = 0;
572 toc = *data++;
573 len--;
574 last_size = len;
575 switch (toc&0x3)
576 {
577 /* One frame */
578 case 0:
579 count=1;
580 break;
581 /* Two CBR frames */
582 case 1:
583 count=2;
584 cbr = 1;
585 if (!self_delimited)
586 {
587 if (len&0x1)
588 return OPUS_INVALID_PACKET;
589 size[0] = last_size = len/2;
590 }
591 break;
592 /* Two VBR frames */
593 case 2:
594 count = 2;
595 bytes = parse_size(data, len, size);
596 len -= bytes;
597 if (size[0]<0 || size[0] > len)
598 return OPUS_INVALID_PACKET;
599 data += bytes;
600 last_size = len-size[0];
601 break;
602 /* Multiple CBR/VBR frames (from 0 to 120 ms) */
603 default: /*case 3:*/
604 if (len<1)
605 return OPUS_INVALID_PACKET;
606 /* Number of frames encoded in bits 0 to 5 */
607 ch = *data++;
608 count = ch&0x3F;
609 if (count <= 0 || framesize*count > 5760)
610 return OPUS_INVALID_PACKET;
611 len--;
612 /* Padding flag is bit 6 */
613 if (ch&0x40)
614 {
615 int padding=0;
616 int p;
617 do {
618 if (len<=0)
619 return OPUS_INVALID_PACKET;
620 p = *data++;
621 len--;
622 padding += p==255 ? 254: p;
623 } while (p==255);
624 len -= padding;
625 }
626 if (len<0)
627 return OPUS_INVALID_PACKET;
628 /* VBR flag is bit 7 */
629 cbr = !(ch&0x80);
630 if (!cbr)
631 {
632 /* VBR case */
633 last_size = len;
634 for (i=0;i<count-1;i++)
635 {
636 bytes = parse_size(data, len, size+i);
637 len -= bytes;
638 if (size[i]<0 || size[i] > len)
639 return OPUS_INVALID_PACKET;
640 data += bytes;
641 last_size -= bytes+size[i];
642 }
643 if (last_size<0)
644 return OPUS_INVALID_PACKET;
645 } else if (!self_delimited)
646 {
647 /* CBR case */
648 last_size = len/count;
649 if (last_size*count!=len)
650 return OPUS_INVALID_PACKET;
651 for (i=0;i<count-1;i++)
652 size[i] = last_size;
653 }
654 break;
655 }
656 /* Self-delimited framing has an extra size for the last frame. */
657 if (self_delimited)
658 {
659 bytes = parse_size(data, len, size+count-1);
660 len -= bytes;
661 if (size[count-1]<0 || size[count-1] > len)
662 return OPUS_INVALID_PACKET;
663 data += bytes;
664 /* For CBR packets, apply the size to all the frames. */
665 if (cbr)
666 {
667 if (size[count-1]*count > len)
668 return OPUS_INVALID_PACKET;
669 for (i=0;i<count-1;i++)
670 size[i] = size[count-1];
671 } else if(size[count-1] > last_size)
672 return OPUS_INVALID_PACKET;
673 } else
674 {
675 /* Because it's not encoded explicitly, it's possible the size of the
676 last packet (or all the packets, for the CBR case) is larger than
677 1275. Reject them here.*/
678 if (last_size > 1275)
679 return OPUS_INVALID_PACKET;
680 size[count-1] = last_size;
681 }
682
683 if (frames)
684 {
685 for (i=0;i<count;i++)
686 {
687 frames[i] = data;
688 data += size[i];
689 }
690 }
691
692 if (out_toc)
693 *out_toc = toc;
694
695 if (payload_offset)
696 *payload_offset = data-data0;
697
698 return count;
699}
700
701int opus_packet_parse(const unsigned char *data, opus_int32 len,
702 unsigned char *out_toc, const unsigned char *frames[48],
703 short size[48], int *payload_offset)
704{
705 return opus_packet_parse_impl(data, len, 0, out_toc,
706 frames, size, payload_offset);
707}
708
709int opus_decode_native(OpusDecoder *st, const unsigned char *data,
710 opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec,
711 int self_delimited, int *packet_offset)
712{
713 int i, nb_samples;
714 int count, offset;
715 unsigned char toc;
716 int tot_offset;
717 /* 48 x 2.5 ms = 120 ms */
718 short size[48];
719 if (decode_fec<0 || decode_fec>1)
720 return OPUS_BAD_ARG;
721 if (len==0 || data==NULL)
722 return opus_decode_frame(st, NULL, 0, pcm, frame_size, 0);
723 else if (len<0)
724 return OPUS_BAD_ARG;
725
726 tot_offset = 0;
727 st->mode = opus_packet_get_mode(data);
728 st->bandwidth = opus_packet_get_bandwidth(data);
729 st->frame_size = opus_packet_get_samples_per_frame(data, st->Fs);
730 st->stream_channels = opus_packet_get_nb_channels(data);
731
732 count = opus_packet_parse_impl(data, len, self_delimited, &toc, NULL, size, &offset);
733 if (count < 0)
734 return count;
735
736 data += offset;
737 tot_offset += offset;
738
739 if (count*st->frame_size > frame_size)
740 return OPUS_BUFFER_TOO_SMALL;
741 nb_samples=0;
742 for (i=0;i<count;i++)
743 {
744 int ret;
745 ret = opus_decode_frame(st, data, size[i], pcm, frame_size-nb_samples, decode_fec);
746 if (ret<0)
747 return ret;
748 data += size[i];
749 tot_offset += size[i];
750 pcm += ret*st->channels;
751 nb_samples += ret;
752 }
753 if (packet_offset != NULL)
754 *packet_offset = tot_offset;
755 return nb_samples;
756}
757
758#ifdef FIXED_POINT
759
760int opus_decode(OpusDecoder *st, const unsigned char *data,
761 opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
762{
763 return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL);
764}
765
766#ifndef DISABLE_FLOAT_API
767int opus_decode_float(OpusDecoder *st, const unsigned char *data,
768 opus_int32 len, float *pcm, int frame_size, int decode_fec)
769{
770 VARDECL(opus_int16, out);
771 int ret, i;
772 ALLOC_STACK;
773
774 ALLOC(out, frame_size*st->channels, opus_int16);
775
776 ret = opus_decode_native(st, data, len, out, frame_size, decode_fec, 0, NULL);
777 if (ret > 0)
778 {
779 for (i=0;i<ret*st->channels;i++)
780 pcm[i] = (1.f/32768.f)*(out[i]);
781 }
782 RESTORE_STACK;
783 return ret;
784}
785#endif
786
787
788#else
789int opus_decode(OpusDecoder *st, const unsigned char *data,
790 opus_int32 len, opus_int16 *pcm, int frame_size, int decode_fec)
791{
792 VARDECL(float, out);
793 int ret, i;
794 ALLOC_STACK;
795
796 if(frame_size<0)
797 {
798 RESTORE_STACK;
799 return OPUS_BAD_ARG;
800 }
801
802 ALLOC(out, frame_size*st->channels, float);
803
804 ret = opus_decode_native(st, data, len, out, frame_size, decode_fec, 0, NULL);
805 if (ret > 0)
806 {
807 for (i=0;i<ret*st->channels;i++)
808 pcm[i] = FLOAT2INT16(out[i]);
809 }
810 RESTORE_STACK;
811 return ret;
812}
813
814int opus_decode_float(OpusDecoder *st, const unsigned char *data,
815 opus_int32 len, opus_val16 *pcm, int frame_size, int decode_fec)
816{
817 return opus_decode_native(st, data, len, pcm, frame_size, decode_fec, 0, NULL);
818}
819
820#endif
821
822int opus_decoder_ctl(OpusDecoder *st, int request, ...)
823{
824 int ret = OPUS_OK;
825 va_list ap;
826 void *silk_dec;
827 CELTDecoder *celt_dec;
828
829 silk_dec = (char*)st+st->silk_dec_offset;
830 celt_dec = (CELTDecoder*)((char*)st+st->celt_dec_offset);
831
832
833 va_start(ap, request);
834
835 switch (request)
836 {
837 case OPUS_GET_BANDWIDTH_REQUEST:
838 {
839 opus_int32 *value = va_arg(ap, opus_int32*);
840 *value = st->bandwidth;
841 }
842 break;
843 case OPUS_GET_FINAL_RANGE_REQUEST:
844 {
845 opus_uint32 *value = va_arg(ap, opus_uint32*);
846 *value = st->rangeFinal;
847 }
848 break;
849 case OPUS_RESET_STATE:
850 {
851 OPUS_CLEAR((char*)&st->OPUS_DECODER_RESET_START,
852 sizeof(OpusDecoder)-
853 ((char*)&st->OPUS_DECODER_RESET_START - (char*)st));
854
855 celt_decoder_ctl(celt_dec, OPUS_RESET_STATE);
856 silk_InitDecoder( silk_dec );
857 st->stream_channels = st->channels;
858 st->frame_size = st->Fs/400;
859 }
860 break;
861 case OPUS_GET_SAMPLE_RATE_REQUEST:
862 {
863 opus_int32 *value = va_arg(ap, opus_int32*);
864 if (value==NULL)
865 {
866 ret = OPUS_BAD_ARG;
867 break;
868 }
869 *value = st->Fs;
870 }
871 break;
872 case OPUS_GET_PITCH_REQUEST:
873 {
874 opus_int32 *value = va_arg(ap, opus_int32*);
875 if (value==NULL)
876 {
877 ret = OPUS_BAD_ARG;
878 break;
879 }
880 if (st->prev_mode == MODE_CELT_ONLY)
881 celt_decoder_ctl(celt_dec, OPUS_GET_PITCH(value));
882 else
883 *value = st->DecControl.prevPitchLag;
884 }
885 break;
886 case OPUS_GET_GAIN_REQUEST:
887 {
888 opus_int32 *value = va_arg(ap, opus_int32*);
889 if (value==NULL)
890 {
891 ret = OPUS_BAD_ARG;
892 break;
893 }
894 *value = st->decode_gain;
895 }
896 break;
897 case OPUS_SET_GAIN_REQUEST:
898 {
899 opus_int32 value = va_arg(ap, opus_int32);
900 if (value<-32768 || value>32767)
901 {
902 ret = OPUS_BAD_ARG;
903 break;
904 }
905 st->decode_gain = value;
906 }
907 break;
908 default:
909 /*fprintf(stderr, "unknown opus_decoder_ctl() request: %d", request);*/
910 ret = OPUS_UNIMPLEMENTED;
911 break;
912 }
913
914 va_end(ap);
915 return ret;
916}
917
918void opus_decoder_destroy(OpusDecoder *st)
919{
920 opus_free(st);
921}
922
923
924int opus_packet_get_bandwidth(const unsigned char *data)
925{
926 int bandwidth;
927 if (data[0]&0x80)
928 {
929 bandwidth = OPUS_BANDWIDTH_MEDIUMBAND + ((data[0]>>5)&0x3);
930 if (bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
931 bandwidth = OPUS_BANDWIDTH_NARROWBAND;
932 } else if ((data[0]&0x60) == 0x60)
933 {
934 bandwidth = (data[0]&0x10) ? OPUS_BANDWIDTH_FULLBAND :
935 OPUS_BANDWIDTH_SUPERWIDEBAND;
936 } else {
937 bandwidth = OPUS_BANDWIDTH_NARROWBAND + ((data[0]>>5)&0x3);
938 }
939 return bandwidth;
940}
941
942int opus_packet_get_samples_per_frame(const unsigned char *data,
943 opus_int32 Fs)
944{
945 int audiosize;
946 if (data[0]&0x80)
947 {
948 audiosize = ((data[0]>>3)&0x3);
949 audiosize = (Fs<<audiosize)/400;
950 } else if ((data[0]&0x60) == 0x60)
951 {
952 audiosize = (data[0]&0x08) ? Fs/50 : Fs/100;
953 } else {
954 audiosize = ((data[0]>>3)&0x3);
955 if (audiosize == 3)
956 audiosize = Fs*60/1000;
957 else
958 audiosize = (Fs<<audiosize)/100;
959 }
960 return audiosize;
961}
962
963int opus_packet_get_nb_channels(const unsigned char *data)
964{
965 return (data[0]&0x4) ? 2 : 1;
966}
967
968int opus_packet_get_nb_frames(const unsigned char packet[], opus_int32 len)
969{
970 int count;
971 if (len<1)
972 return OPUS_BAD_ARG;
973 count = packet[0]&0x3;
974 if (count==0)
975 return 1;
976 else if (count!=3)
977 return 2;
978 else if (len<2)
979 return OPUS_INVALID_PACKET;
980 else
981 return packet[1]&0x3F;
982}
983
984int opus_decoder_get_nb_samples(const OpusDecoder *dec,
985 const unsigned char packet[], opus_int32 len)
986{
987 int samples;
988 int count = opus_packet_get_nb_frames(packet, len);
989
990 if (count<0)
991 return count;
992
993 samples = count*opus_packet_get_samples_per_frame(packet, dec->Fs);
994 /* Can't have more than 120 ms */
995 if (samples*25 > dec->Fs*3)
996 return OPUS_INVALID_PACKET;
997 else
998 return samples;
999}
diff --git a/lib/rbcodec/codecs/libopus/opus_defines.h b/lib/rbcodec/codecs/libopus/opus_defines.h
new file mode 100644
index 0000000000..830d225f14
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_defines.h
@@ -0,0 +1,644 @@
1/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
2 Written by Jean-Marc Valin and Koen Vos */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28/**
29 * @file opus_defines.h
30 * @brief Opus reference implementation constants
31 */
32
33#ifndef OPUS_DEFINES_H
34#define OPUS_DEFINES_H
35
36#include "opus_types.h"
37
38#ifdef __cplusplus
39extern "C" {
40#endif
41
42/** @defgroup opus_errorcodes Error codes
43 * @{
44 */
45/** No error @hideinitializer*/
46#define OPUS_OK 0
47/** One or more invalid/out of range arguments @hideinitializer*/
48#define OPUS_BAD_ARG -1
49/** The mode struct passed is invalid @hideinitializer*/
50#define OPUS_BUFFER_TOO_SMALL -2
51/** An internal error was detected @hideinitializer*/
52#define OPUS_INTERNAL_ERROR -3
53/** The compressed data passed is corrupted @hideinitializer*/
54#define OPUS_INVALID_PACKET -4
55/** Invalid/unsupported request number @hideinitializer*/
56#define OPUS_UNIMPLEMENTED -5
57/** An encoder or decoder structure is invalid or already freed @hideinitializer*/
58#define OPUS_INVALID_STATE -6
59/** Memory allocation has failed @hideinitializer*/
60#define OPUS_ALLOC_FAIL -7
61/**@}*/
62
63/** @cond OPUS_INTERNAL_DOC */
64/**Export control for opus functions */
65
66#if defined(__GNUC__) && defined(OPUS_BUILD)
67# define OPUS_EXPORT __attribute__ ((visibility ("default")))
68#elif defined(WIN32) && !defined(__MINGW32__)
69# ifdef OPUS_BUILD
70# define OPUS_EXPORT __declspec(dllexport)
71# else
72# define OPUS_EXPORT
73# endif
74#else
75# define OPUS_EXPORT
76#endif
77
78# if !defined(OPUS_GNUC_PREREQ)
79# if defined(__GNUC__)&&defined(__GNUC_MINOR__)
80# define OPUS_GNUC_PREREQ(_maj,_min) \
81 ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
82# else
83# define OPUS_GNUC_PREREQ(_maj,_min) 0
84# endif
85# endif
86
87#if (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L) )
88# if OPUS_GNUC_PREREQ(3,0)
89# define OPUS_RESTRICT __restrict__
90# elif (defined(_MSC_VER) && _MSC_VER >= 1400)
91# define OPUS_RESTRICT __restrict
92# else
93# define OPUS_RESTRICT
94# endif
95#else
96# define OPUS_RESTRICT restrict
97#endif
98
99/**Warning attributes for opus functions
100 * NONNULL is not used in OPUS_BUILD to avoid the compiler optimizing out
101 * some paranoid null checks. */
102#if defined(__GNUC__) && OPUS_GNUC_PREREQ(3, 4)
103# define OPUS_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
104#else
105# define OPUS_WARN_UNUSED_RESULT
106#endif
107#if !defined(OPUS_BUILD) && defined(__GNUC__) && OPUS_GNUC_PREREQ(3, 4)
108# define OPUS_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x)))
109#else
110# define OPUS_ARG_NONNULL(_x)
111#endif
112
113/** These are the actual Encoder CTL ID numbers.
114 * They should not be used directly by applications.
115 * In general, SETs should be even and GETs should be odd.*/
116#define OPUS_SET_APPLICATION_REQUEST 4000
117#define OPUS_GET_APPLICATION_REQUEST 4001
118#define OPUS_SET_BITRATE_REQUEST 4002
119#define OPUS_GET_BITRATE_REQUEST 4003
120#define OPUS_SET_MAX_BANDWIDTH_REQUEST 4004
121#define OPUS_GET_MAX_BANDWIDTH_REQUEST 4005
122#define OPUS_SET_VBR_REQUEST 4006
123#define OPUS_GET_VBR_REQUEST 4007
124#define OPUS_SET_BANDWIDTH_REQUEST 4008
125#define OPUS_GET_BANDWIDTH_REQUEST 4009
126#define OPUS_SET_COMPLEXITY_REQUEST 4010
127#define OPUS_GET_COMPLEXITY_REQUEST 4011
128#define OPUS_SET_INBAND_FEC_REQUEST 4012
129#define OPUS_GET_INBAND_FEC_REQUEST 4013
130#define OPUS_SET_PACKET_LOSS_PERC_REQUEST 4014
131#define OPUS_GET_PACKET_LOSS_PERC_REQUEST 4015
132#define OPUS_SET_DTX_REQUEST 4016
133#define OPUS_GET_DTX_REQUEST 4017
134#define OPUS_SET_VBR_CONSTRAINT_REQUEST 4020
135#define OPUS_GET_VBR_CONSTRAINT_REQUEST 4021
136#define OPUS_SET_FORCE_CHANNELS_REQUEST 4022
137#define OPUS_GET_FORCE_CHANNELS_REQUEST 4023
138#define OPUS_SET_SIGNAL_REQUEST 4024
139#define OPUS_GET_SIGNAL_REQUEST 4025
140#define OPUS_GET_LOOKAHEAD_REQUEST 4027
141/* #define OPUS_RESET_STATE 4028 */
142#define OPUS_GET_SAMPLE_RATE_REQUEST 4029
143#define OPUS_GET_FINAL_RANGE_REQUEST 4031
144#define OPUS_GET_PITCH_REQUEST 4033
145#define OPUS_SET_GAIN_REQUEST 4034
146#define OPUS_GET_GAIN_REQUEST 4045
147#define OPUS_SET_LSB_DEPTH_REQUEST 4036
148#define OPUS_GET_LSB_DEPTH_REQUEST 4037
149
150/* Macros to trigger compilation errors when the wrong types are provided to a CTL */
151#define __opus_check_int(x) (((void)((x) == (opus_int32)0)), (opus_int32)(x))
152#define __opus_check_int_ptr(ptr) ((ptr) + ((ptr) - (opus_int32*)(ptr)))
153#define __opus_check_uint_ptr(ptr) ((ptr) + ((ptr) - (opus_uint32*)(ptr)))
154/** @endcond */
155
156/** @defgroup opus_ctlvalues Pre-defined values for CTL interface
157 * @see opus_genericctls, opus_encoderctls
158 * @{
159 */
160/* Values for the various encoder CTLs */
161#define OPUS_AUTO -1000 /**<Auto/default setting @hideinitializer*/
162#define OPUS_BITRATE_MAX -1 /**<Maximum bitrate @hideinitializer*/
163
164/** Best for most VoIP/videoconference applications where listening quality and intelligibility matter most
165 * @hideinitializer */
166#define OPUS_APPLICATION_VOIP 2048
167/** Best for broadcast/high-fidelity application where the decoded audio should be as close as possible to the input
168 * @hideinitializer */
169#define OPUS_APPLICATION_AUDIO 2049
170/** Only use when lowest-achievable latency is what matters most. Voice-optimized modes cannot be used.
171 * @hideinitializer */
172#define OPUS_APPLICATION_RESTRICTED_LOWDELAY 2051
173
174#define OPUS_SIGNAL_VOICE 3001 /**< Signal being encoded is voice */
175#define OPUS_SIGNAL_MUSIC 3002 /**< Signal being encoded is music */
176#define OPUS_BANDWIDTH_NARROWBAND 1101 /**< 4 kHz bandpass @hideinitializer*/
177#define OPUS_BANDWIDTH_MEDIUMBAND 1102 /**< 6 kHz bandpass @hideinitializer*/
178#define OPUS_BANDWIDTH_WIDEBAND 1103 /**< 8 kHz bandpass @hideinitializer*/
179#define OPUS_BANDWIDTH_SUPERWIDEBAND 1104 /**<12 kHz bandpass @hideinitializer*/
180#define OPUS_BANDWIDTH_FULLBAND 1105 /**<20 kHz bandpass @hideinitializer*/
181
182/**@}*/
183
184
185/** @defgroup opus_encoderctls Encoder related CTLs
186 *
187 * These are convenience macros for use with the \c opus_encode_ctl
188 * interface. They are used to generate the appropriate series of
189 * arguments for that call, passing the correct type, size and so
190 * on as expected for each particular request.
191 *
192 * Some usage examples:
193 *
194 * @code
195 * int ret;
196 * ret = opus_encoder_ctl(enc_ctx, OPUS_SET_BANDWIDTH(OPUS_AUTO));
197 * if (ret != OPUS_OK) return ret;
198 *
199 * opus_int32 rate;
200 * opus_encoder_ctl(enc_ctx, OPUS_GET_BANDWIDTH(&rate));
201 *
202 * opus_encoder_ctl(enc_ctx, OPUS_RESET_STATE);
203 * @endcode
204 *
205 * @see opus_genericctls, opus_encoder
206 * @{
207 */
208
209/** Configures the encoder's computational complexity.
210 * The supported range is 0-10 inclusive with 10 representing the highest complexity.
211 * @see OPUS_GET_COMPLEXITY
212 * @param[in] x <tt>opus_int32</tt>: Allowed values: 0-10, inclusive.
213 *
214 * @hideinitializer */
215#define OPUS_SET_COMPLEXITY(x) OPUS_SET_COMPLEXITY_REQUEST, __opus_check_int(x)
216/** Gets the encoder's complexity configuration.
217 * @see OPUS_SET_COMPLEXITY
218 * @param[out] x <tt>opus_int32 *</tt>: Returns a value in the range 0-10,
219 * inclusive.
220 * @hideinitializer */
221#define OPUS_GET_COMPLEXITY(x) OPUS_GET_COMPLEXITY_REQUEST, __opus_check_int_ptr(x)
222
223/** Configures the bitrate in the encoder.
224 * Rates from 500 to 512000 bits per second are meaningful, as well as the
225 * special values #OPUS_AUTO and #OPUS_BITRATE_MAX.
226 * The value #OPUS_BITRATE_MAX can be used to cause the codec to use as much
227 * rate as it can, which is useful for controlling the rate by adjusting the
228 * output buffer size.
229 * @see OPUS_GET_BITRATE
230 * @param[in] x <tt>opus_int32</tt>: Bitrate in bits per second. The default
231 * is determined based on the number of
232 * channels and the input sampling rate.
233 * @hideinitializer */
234#define OPUS_SET_BITRATE(x) OPUS_SET_BITRATE_REQUEST, __opus_check_int(x)
235/** Gets the encoder's bitrate configuration.
236 * @see OPUS_SET_BITRATE
237 * @param[out] x <tt>opus_int32 *</tt>: Returns the bitrate in bits per second.
238 * The default is determined based on the
239 * number of channels and the input
240 * sampling rate.
241 * @hideinitializer */
242#define OPUS_GET_BITRATE(x) OPUS_GET_BITRATE_REQUEST, __opus_check_int_ptr(x)
243
244/** Enables or disables variable bitrate (VBR) in the encoder.
245 * The configured bitrate may not be met exactly because frames must
246 * be an integer number of bytes in length.
247 * @warning Only the MDCT mode of Opus can provide hard CBR behavior.
248 * @see OPUS_GET_VBR
249 * @see OPUS_SET_VBR_CONSTRAINT
250 * @param[in] x <tt>opus_int32</tt>: Allowed values:
251 * <dl>
252 * <dt>0</dt><dd>Hard CBR. For LPC/hybrid modes at very low bit-rate, this can
253 * cause noticeable quality degradation.</dd>
254 * <dt>1</dt><dd>VBR (default). The exact type of VBR is controlled by
255 * #OPUS_SET_VBR_CONSTRAINT.</dd>
256 * </dl>
257 * @hideinitializer */
258#define OPUS_SET_VBR(x) OPUS_SET_VBR_REQUEST, __opus_check_int(x)
259/** Determine if variable bitrate (VBR) is enabled in the encoder.
260 * @see OPUS_SET_VBR
261 * @see OPUS_GET_VBR_CONSTRAINT
262 * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
263 * <dl>
264 * <dt>0</dt><dd>Hard CBR.</dd>
265 * <dt>1</dt><dd>VBR (default). The exact type of VBR may be retrieved via
266 * #OPUS_GET_VBR_CONSTRAINT.</dd>
267 * </dl>
268 * @hideinitializer */
269#define OPUS_GET_VBR(x) OPUS_GET_VBR_REQUEST, __opus_check_int_ptr(x)
270
271/** Enables or disables constrained VBR in the encoder.
272 * This setting is ignored when the encoder is in CBR mode.
273 * @warning Only the MDCT mode of Opus currently heeds the constraint.
274 * Speech mode ignores it completely, hybrid mode may fail to obey it
275 * if the LPC layer uses more bitrate than the constraint would have
276 * permitted.
277 * @see OPUS_GET_VBR_CONSTRAINT
278 * @see OPUS_SET_VBR
279 * @param[in] x <tt>opus_int32</tt>: Allowed values:
280 * <dl>
281 * <dt>0</dt><dd>Unconstrained VBR.</dd>
282 * <dt>1</dt><dd>Constrained VBR (default). This creates a maximum of one
283 * frame of buffering delay assuming a transport with a
284 * serialization speed of the nominal bitrate.</dd>
285 * </dl>
286 * @hideinitializer */
287#define OPUS_SET_VBR_CONSTRAINT(x) OPUS_SET_VBR_CONSTRAINT_REQUEST, __opus_check_int(x)
288/** Determine if constrained VBR is enabled in the encoder.
289 * @see OPUS_SET_VBR_CONSTRAINT
290 * @see OPUS_GET_VBR
291 * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
292 * <dl>
293 * <dt>0</dt><dd>Unconstrained VBR.</dd>
294 * <dt>1</dt><dd>Constrained VBR (default).</dd>
295 * </dl>
296 * @hideinitializer */
297#define OPUS_GET_VBR_CONSTRAINT(x) OPUS_GET_VBR_CONSTRAINT_REQUEST, __opus_check_int_ptr(x)
298
299/** Configures mono/stereo forcing in the encoder.
300 * This can force the encoder to produce packets encoded as either mono or
301 * stereo, regardless of the format of the input audio. This is useful when
302 * the caller knows that the input signal is currently a mono source embedded
303 * in a stereo stream.
304 * @see OPUS_GET_FORCE_CHANNELS
305 * @param[in] x <tt>opus_int32</tt>: Allowed values:
306 * <dl>
307 * <dt>#OPUS_AUTO</dt><dd>Not forced (default)</dd>
308 * <dt>1</dt> <dd>Forced mono</dd>
309 * <dt>2</dt> <dd>Forced stereo</dd>
310 * </dl>
311 * @hideinitializer */
312#define OPUS_SET_FORCE_CHANNELS(x) OPUS_SET_FORCE_CHANNELS_REQUEST, __opus_check_int(x)
313/** Gets the encoder's forced channel configuration.
314 * @see OPUS_SET_FORCE_CHANNELS
315 * @param[out] x <tt>opus_int32 *</tt>:
316 * <dl>
317 * <dt>#OPUS_AUTO</dt><dd>Not forced (default)</dd>
318 * <dt>1</dt> <dd>Forced mono</dd>
319 * <dt>2</dt> <dd>Forced stereo</dd>
320 * </dl>
321 * @hideinitializer */
322#define OPUS_GET_FORCE_CHANNELS(x) OPUS_GET_FORCE_CHANNELS_REQUEST, __opus_check_int_ptr(x)
323
324/** Configures the maximum bandpass that the encoder will select automatically.
325 * Applications should normally use this instead of #OPUS_SET_BANDWIDTH
326 * (leaving that set to the default, #OPUS_AUTO). This allows the
327 * application to set an upper bound based on the type of input it is
328 * providing, but still gives the encoder the freedom to reduce the bandpass
329 * when the bitrate becomes too low, for better overall quality.
330 * @see OPUS_GET_MAX_BANDWIDTH
331 * @param[in] x <tt>opus_int32</tt>: Allowed values:
332 * <dl>
333 * <dt>OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd>
334 * <dt>OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd>
335 * <dt>OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd>
336 * <dt>OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd>
337 * <dt>OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband (default)</dd>
338 * </dl>
339 * @hideinitializer */
340#define OPUS_SET_MAX_BANDWIDTH(x) OPUS_SET_MAX_BANDWIDTH_REQUEST, __opus_check_int(x)
341
342/** Gets the encoder's configured maximum allowed bandpass.
343 * @see OPUS_SET_MAX_BANDWIDTH
344 * @param[out] x <tt>opus_int32 *</tt>: Allowed values:
345 * <dl>
346 * <dt>#OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd>
347 * <dt>#OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd>
348 * <dt>#OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd>
349 * <dt>#OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd>
350 * <dt>#OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband (default)</dd>
351 * </dl>
352 * @hideinitializer */
353#define OPUS_GET_MAX_BANDWIDTH(x) OPUS_GET_MAX_BANDWIDTH_REQUEST, __opus_check_int_ptr(x)
354
355/** Sets the encoder's bandpass to a specific value.
356 * This prevents the encoder from automatically selecting the bandpass based
357 * on the available bitrate. If an application knows the bandpass of the input
358 * audio it is providing, it should normally use #OPUS_SET_MAX_BANDWIDTH
359 * instead, which still gives the encoder the freedom to reduce the bandpass
360 * when the bitrate becomes too low, for better overall quality.
361 * @see OPUS_GET_BANDWIDTH
362 * @param[in] x <tt>opus_int32</tt>: Allowed values:
363 * <dl>
364 * <dt>#OPUS_AUTO</dt> <dd>(default)</dd>
365 * <dt>#OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd>
366 * <dt>#OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd>
367 * <dt>#OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd>
368 * <dt>#OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd>
369 * <dt>#OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband</dd>
370 * </dl>
371 * @hideinitializer */
372#define OPUS_SET_BANDWIDTH(x) OPUS_SET_BANDWIDTH_REQUEST, __opus_check_int(x)
373
374/** Configures the type of signal being encoded.
375 * This is a hint which helps the encoder's mode selection.
376 * @see OPUS_GET_SIGNAL
377 * @param[in] x <tt>opus_int32</tt>: Allowed values:
378 * <dl>
379 * <dt>#OPUS_AUTO</dt> <dd>(default)</dd>
380 * <dt>#OPUS_SIGNAL_VOICE</dt><dd>Bias thresholds towards choosing LPC or Hybrid modes.</dd>
381 * <dt>#OPUS_SIGNAL_MUSIC</dt><dd>Bias thresholds towards choosing MDCT modes.</dd>
382 * </dl>
383 * @hideinitializer */
384#define OPUS_SET_SIGNAL(x) OPUS_SET_SIGNAL_REQUEST, __opus_check_int(x)
385/** Gets the encoder's configured signal type.
386 * @see OPUS_SET_SIGNAL
387 * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
388 * <dl>
389 * <dt>#OPUS_AUTO</dt> <dd>(default)</dd>
390 * <dt>#OPUS_SIGNAL_VOICE</dt><dd>Bias thresholds towards choosing LPC or Hybrid modes.</dd>
391 * <dt>#OPUS_SIGNAL_MUSIC</dt><dd>Bias thresholds towards choosing MDCT modes.</dd>
392 * </dl>
393 * @hideinitializer */
394#define OPUS_GET_SIGNAL(x) OPUS_GET_SIGNAL_REQUEST, __opus_check_int_ptr(x)
395
396
397/** Configures the encoder's intended application.
398 * The initial value is a mandatory argument to the encoder_create function.
399 * @see OPUS_GET_APPLICATION
400 * @param[in] x <tt>opus_int32</tt>: Returns one of the following values:
401 * <dl>
402 * <dt>#OPUS_APPLICATION_VOIP</dt>
403 * <dd>Process signal for improved speech intelligibility.</dd>
404 * <dt>#OPUS_APPLICATION_AUDIO</dt>
405 * <dd>Favor faithfulness to the original input.</dd>
406 * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt>
407 * <dd>Configure the minimum possible coding delay by disabling certain modes
408 * of operation.</dd>
409 * </dl>
410 * @hideinitializer */
411#define OPUS_SET_APPLICATION(x) OPUS_SET_APPLICATION_REQUEST, __opus_check_int(x)
412/** Gets the encoder's configured application.
413 * @see OPUS_SET_APPLICATION
414 * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
415 * <dl>
416 * <dt>#OPUS_APPLICATION_VOIP</dt>
417 * <dd>Process signal for improved speech intelligibility.</dd>
418 * <dt>#OPUS_APPLICATION_AUDIO</dt>
419 * <dd>Favor faithfulness to the original input.</dd>
420 * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt>
421 * <dd>Configure the minimum possible coding delay by disabling certain modes
422 * of operation.</dd>
423 * </dl>
424 * @hideinitializer */
425#define OPUS_GET_APPLICATION(x) OPUS_GET_APPLICATION_REQUEST, __opus_check_int_ptr(x)
426
427/** Gets the sampling rate the encoder or decoder was initialized with.
428 * This simply returns the <code>Fs</code> value passed to opus_encoder_init()
429 * or opus_decoder_init().
430 * @param[out] x <tt>opus_int32 *</tt>: Sampling rate of encoder or decoder.
431 * @hideinitializer
432 */
433#define OPUS_GET_SAMPLE_RATE(x) OPUS_GET_SAMPLE_RATE_REQUEST, __opus_check_int_ptr(x)
434
435/** Gets the total samples of delay added by the entire codec.
436 * This can be queried by the encoder and then the provided number of samples can be
437 * skipped on from the start of the decoder's output to provide time aligned input
438 * and output. From the perspective of a decoding application the real data begins this many
439 * samples late.
440 *
441 * The decoder contribution to this delay is identical for all decoders, but the
442 * encoder portion of the delay may vary from implementation to implementation,
443 * version to version, or even depend on the encoder's initial configuration.
444 * Applications needing delay compensation should call this CTL rather than
445 * hard-coding a value.
446 * @param[out] x <tt>opus_int32 *</tt>: Number of lookahead samples
447 * @hideinitializer */
448#define OPUS_GET_LOOKAHEAD(x) OPUS_GET_LOOKAHEAD_REQUEST, __opus_check_int_ptr(x)
449
450/** Configures the encoder's use of inband forward error correction (FEC).
451 * @note This is only applicable to the LPC layer
452 * @see OPUS_GET_INBAND_FEC
453 * @param[in] x <tt>opus_int32</tt>: Allowed values:
454 * <dl>
455 * <dt>0</dt><dd>Disable inband FEC (default).</dd>
456 * <dt>1</dt><dd>Enable inband FEC.</dd>
457 * </dl>
458 * @hideinitializer */
459#define OPUS_SET_INBAND_FEC(x) OPUS_SET_INBAND_FEC_REQUEST, __opus_check_int(x)
460/** Gets encoder's configured use of inband forward error correction.
461 * @see OPUS_SET_INBAND_FEC
462 * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
463 * <dl>
464 * <dt>0</dt><dd>Inband FEC disabled (default).</dd>
465 * <dt>1</dt><dd>Inband FEC enabled.</dd>
466 * </dl>
467 * @hideinitializer */
468#define OPUS_GET_INBAND_FEC(x) OPUS_GET_INBAND_FEC_REQUEST, __opus_check_int_ptr(x)
469
470/** Configures the encoder's expected packet loss percentage.
471 * Higher values with trigger progressively more loss resistant behavior in the encoder
472 * at the expense of quality at a given bitrate in the lossless case, but greater quality
473 * under loss.
474 * @see OPUS_GET_PACKET_LOSS_PERC
475 * @param[in] x <tt>opus_int32</tt>: Loss percentage in the range 0-100, inclusive (default: 0).
476 * @hideinitializer */
477#define OPUS_SET_PACKET_LOSS_PERC(x) OPUS_SET_PACKET_LOSS_PERC_REQUEST, __opus_check_int(x)
478/** Gets the encoder's configured packet loss percentage.
479 * @see OPUS_SET_PACKET_LOSS_PERC
480 * @param[out] x <tt>opus_int32 *</tt>: Returns the configured loss percentage
481 * in the range 0-100, inclusive (default: 0).
482 * @hideinitializer */
483#define OPUS_GET_PACKET_LOSS_PERC(x) OPUS_GET_PACKET_LOSS_PERC_REQUEST, __opus_check_int_ptr(x)
484
485/** Configures the encoder's use of discontinuous transmission (DTX).
486 * @note This is only applicable to the LPC layer
487 * @see OPUS_GET_DTX
488 * @param[in] x <tt>opus_int32</tt>: Allowed values:
489 * <dl>
490 * <dt>0</dt><dd>Disable DTX (default).</dd>
491 * <dt>1</dt><dd>Enabled DTX.</dd>
492 * </dl>
493 * @hideinitializer */
494#define OPUS_SET_DTX(x) OPUS_SET_DTX_REQUEST, __opus_check_int(x)
495/** Gets encoder's configured use of discontinuous transmission.
496 * @see OPUS_SET_DTX
497 * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
498 * <dl>
499 * <dt>0</dt><dd>DTX disabled (default).</dd>
500 * <dt>1</dt><dd>DTX enabled.</dd>
501 * </dl>
502 * @hideinitializer */
503#define OPUS_GET_DTX(x) OPUS_GET_DTX_REQUEST, __opus_check_int_ptr(x)
504/**@}*/
505
506/** @defgroup opus_genericctls Generic CTLs
507 *
508 * These macros are used with the \c opus_decoder_ctl and
509 * \c opus_encoder_ctl calls to generate a particular
510 * request.
511 *
512 * When called on an \c OpusDecoder they apply to that
513 * particular decoder instance. When called on an
514 * \c OpusEncoder they apply to the corresponding setting
515 * on that encoder instance, if present.
516 *
517 * Some usage examples:
518 *
519 * @code
520 * int ret;
521 * opus_int32 pitch;
522 * ret = opus_decoder_ctl(dec_ctx, OPUS_GET_PITCH(&pitch));
523 * if (ret == OPUS_OK) return ret;
524 *
525 * opus_encoder_ctl(enc_ctx, OPUS_RESET_STATE);
526 * opus_decoder_ctl(dec_ctx, OPUS_RESET_STATE);
527 *
528 * opus_int32 enc_bw, dec_bw;
529 * opus_encoder_ctl(enc_ctx, OPUS_GET_BANDWIDTH(&enc_bw));
530 * opus_decoder_ctl(dec_ctx, OPUS_GET_BANDWIDTH(&dec_bw));
531 * if (enc_bw != dec_bw) {
532 * printf("packet bandwidth mismatch!\n");
533 * }
534 * @endcode
535 *
536 * @see opus_encoder, opus_decoder_ctl, opus_encoder_ctl, opus_decoderctls, opus_encoderctls
537 * @{
538 */
539
540/** Resets the codec state to be equivalent to a freshly initialized state.
541 * This should be called when switching streams in order to prevent
542 * the back to back decoding from giving different results from
543 * one at a time decoding.
544 * @hideinitializer */
545#define OPUS_RESET_STATE 4028
546
547/** Gets the final state of the codec's entropy coder.
548 * This is used for testing purposes,
549 * The encoder and decoder state should be identical after coding a payload
550 * (assuming no data corruption or software bugs)
551 *
552 * @param[out] x <tt>opus_uint32 *</tt>: Entropy coder state
553 *
554 * @hideinitializer */
555#define OPUS_GET_FINAL_RANGE(x) OPUS_GET_FINAL_RANGE_REQUEST, __opus_check_uint_ptr(x)
556
557/** Gets the pitch of the last decoded frame, if available.
558 * This can be used for any post-processing algorithm requiring the use of pitch,
559 * e.g. time stretching/shortening. If the last frame was not voiced, or if the
560 * pitch was not coded in the frame, then zero is returned.
561 *
562 * This CTL is only implemented for decoder instances.
563 *
564 * @param[out] x <tt>opus_int32 *</tt>: pitch period at 48 kHz (or 0 if not available)
565 *
566 * @hideinitializer */
567#define OPUS_GET_PITCH(x) OPUS_GET_PITCH_REQUEST, __opus_check_int_ptr(x)
568
569/** Gets the encoder's configured bandpass or the decoder's last bandpass.
570 * @see OPUS_SET_BANDWIDTH
571 * @param[out] x <tt>opus_int32 *</tt>: Returns one of the following values:
572 * <dl>
573 * <dt>#OPUS_AUTO</dt> <dd>(default)</dd>
574 * <dt>#OPUS_BANDWIDTH_NARROWBAND</dt> <dd>4 kHz passband</dd>
575 * <dt>#OPUS_BANDWIDTH_MEDIUMBAND</dt> <dd>6 kHz passband</dd>
576 * <dt>#OPUS_BANDWIDTH_WIDEBAND</dt> <dd>8 kHz passband</dd>
577 * <dt>#OPUS_BANDWIDTH_SUPERWIDEBAND</dt><dd>12 kHz passband</dd>
578 * <dt>#OPUS_BANDWIDTH_FULLBAND</dt> <dd>20 kHz passband</dd>
579 * </dl>
580 * @hideinitializer */
581#define OPUS_GET_BANDWIDTH(x) OPUS_GET_BANDWIDTH_REQUEST, __opus_check_int_ptr(x)
582
583/** Configures the depth of signal being encoded.
584 * This is a hint which helps the encoder identify silence and near-silence.
585 * @see OPUS_GET_LSB_DEPTH
586 * @param[in] x <tt>opus_int32</tt>: Input precision in bits, between 8 and 24
587 * (default: 24).
588 * @hideinitializer */
589#define OPUS_SET_LSB_DEPTH(x) OPUS_SET_LSB_DEPTH_REQUEST, __opus_check_int(x)
590/** Gets the encoder's configured signal depth.
591 * @see OPUS_SET_LSB_DEPTH
592 * @param[out] x <tt>opus_int32 *</tt>: Input precision in bits, between 8 and
593 * 24 (default: 24).
594 * @hideinitializer */
595#define OPUS_GET_LSB_DEPTH(x) OPUS_GET_LSB_DEPTH_REQUEST, __opus_check_int_ptr(x)
596/**@}*/
597
598/** @defgroup opus_decoderctls Decoder related CTLs
599 * @see opus_genericctls, opus_encoderctls, opus_decoder
600 * @{
601 */
602
603/** Configures decoder gain adjustment.
604 * Scales the decoded output by a factor specified in Q8 dB units.
605 * This has a maximum range of -32768 to 32767 inclusive, and returns
606 * OPUS_BAD_ARG otherwise. The default is zero indicating no adjustment.
607 * This setting survives decoder reset.
608 *
609 * gain = pow(10, x/(20.0*256))
610 *
611 * @param[in] x <tt>opus_int32</tt>: Amount to scale PCM signal by in Q8 dB units.
612 * @hideinitializer */
613#define OPUS_SET_GAIN(x) OPUS_SET_GAIN_REQUEST, __opus_check_int(x)
614/** Gets the decoder's configured gain adjustment. @see OPUS_SET_GAIN
615 *
616 * @param[out] x <tt>opus_int32 *</tt>: Amount to scale PCM signal by in Q8 dB units.
617 * @hideinitializer */
618#define OPUS_GET_GAIN(x) OPUS_GET_GAIN_REQUEST, __opus_check_int_ptr(x)
619
620/**@}*/
621
622/** @defgroup opus_libinfo Opus library information functions
623 * @{
624 */
625
626/** Converts an opus error code into a human readable string.
627 *
628 * @param[in] error <tt>int</tt>: Error number
629 * @returns Error string
630 */
631OPUS_EXPORT const char *opus_strerror(int error);
632
633/** Gets the libopus version string.
634 *
635 * @returns Version string
636 */
637OPUS_EXPORT const char *opus_get_version_string(void);
638/**@}*/
639
640#ifdef __cplusplus
641}
642#endif
643
644#endif /* OPUS_DEFINES_H */
diff --git a/lib/rbcodec/codecs/libopus/opus_header.c b/lib/rbcodec/codecs/libopus/opus_header.c
new file mode 100644
index 0000000000..ed07c9ab50
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_header.c
@@ -0,0 +1,286 @@
1/* Copyright (C)2012 Xiph.Org Foundation
2 File: opus_header.c
3
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
19 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#ifdef HAVE_CONFIG_H
29# include "opus_config.h"
30#endif
31
32#include "opus_header.h"
33#include <string.h>
34#include <stdio.h>
35
36/* Header contents:
37 - "OpusHead" (64 bits)
38 - version number (8 bits)
39 - Channels C (8 bits)
40 - Pre-skip (16 bits)
41 - Sampling rate (32 bits)
42 - Gain in dB (16 bits, S7.8)
43 - Mapping (8 bits, 0=single stream (mono/stereo) 1=Vorbis mapping,
44 2..254: reserved, 255: multistream with no mapping)
45
46 - if (mapping != 0)
47 - N = totel number of streams (8 bits)
48 - M = number of paired streams (8 bits)
49 - C times channel origin
50 - if (C<2*M)
51 - stream = byte/2
52 - if (byte&0x1 == 0)
53 - left
54 else
55 - right
56 - else
57 - stream = byte-M
58*/
59
60typedef struct {
61 unsigned char *data;
62 int maxlen;
63 int pos;
64} Packet;
65
66typedef struct {
67 const unsigned char *data;
68 int maxlen;
69 int pos;
70} ROPacket;
71
72static int write_uint32(Packet *p, ogg_uint32_t val)
73{
74 if (p->pos>p->maxlen-4)
75 return 0;
76 p->data[p->pos ] = (val ) & 0xFF;
77 p->data[p->pos+1] = (val>> 8) & 0xFF;
78 p->data[p->pos+2] = (val>>16) & 0xFF;
79 p->data[p->pos+3] = (val>>24) & 0xFF;
80 p->pos += 4;
81 return 1;
82}
83
84static int write_uint16(Packet *p, ogg_uint16_t val)
85{
86 if (p->pos>p->maxlen-2)
87 return 0;
88 p->data[p->pos ] = (val ) & 0xFF;
89 p->data[p->pos+1] = (val>> 8) & 0xFF;
90 p->pos += 2;
91 return 1;
92}
93
94static int write_chars(Packet *p, const unsigned char *str, int nb_chars)
95{
96 int i;
97 if (p->pos>p->maxlen-nb_chars)
98 return 0;
99 for (i=0;i<nb_chars;i++)
100 p->data[p->pos++] = str[i];
101 return 1;
102}
103
104static int read_uint32(ROPacket *p, ogg_uint32_t *val)
105{
106 if (p->pos>p->maxlen-4)
107 return 0;
108 *val = (ogg_uint32_t)p->data[p->pos ];
109 *val |= (ogg_uint32_t)p->data[p->pos+1]<< 8;
110 *val |= (ogg_uint32_t)p->data[p->pos+2]<<16;
111 *val |= (ogg_uint32_t)p->data[p->pos+3]<<24;
112 p->pos += 4;
113 return 1;
114}
115
116static int read_uint16(ROPacket *p, ogg_uint16_t *val)
117{
118 if (p->pos>p->maxlen-2)
119 return 0;
120 *val = (ogg_uint16_t)p->data[p->pos ];
121 *val |= (ogg_uint16_t)p->data[p->pos+1]<<8;
122 p->pos += 2;
123 return 1;
124}
125
126static int read_chars(ROPacket *p, unsigned char *str, int nb_chars)
127{
128 int i;
129 if (p->pos>p->maxlen-nb_chars)
130 return 0;
131 for (i=0;i<nb_chars;i++)
132 str[i] = p->data[p->pos++];
133 return 1;
134}
135
136int opus_header_parse(const unsigned char *packet, int len, OpusHeader *h)
137{
138 int i;
139 char str[9];
140 ROPacket p;
141 unsigned char ch;
142 ogg_uint16_t shortval;
143
144 p.data = packet;
145 p.maxlen = len;
146 p.pos = 0;
147 str[8] = 0;
148 if (len<19)return 0;
149 read_chars(&p, (unsigned char*)str, 8);
150 if (memcmp(str, "OpusHead", 8)!=0)
151 return 0;
152
153 if (!read_chars(&p, &ch, 1))
154 return 0;
155 h->version = ch;
156 if((h->version&240) != 0) /* Only major version 0 supported. */
157 return 0;
158
159 if (!read_chars(&p, &ch, 1))
160 return 0;
161 h->channels = ch;
162 if (h->channels == 0)
163 return 0;
164
165 if (!read_uint16(&p, &shortval))
166 return 0;
167 h->preskip = shortval;
168
169 if (!read_uint32(&p, &h->input_sample_rate))
170 return 0;
171
172 if (!read_uint16(&p, &shortval))
173 return 0;
174 h->gain = (short)shortval;
175
176 if (!read_chars(&p, &ch, 1))
177 return 0;
178 h->channel_mapping = ch;
179
180 if (h->channel_mapping != 0)
181 {
182 if (!read_chars(&p, &ch, 1))
183 return 0;
184
185 if (ch<1)
186 return 0;
187 h->nb_streams = ch;
188
189 if (!read_chars(&p, &ch, 1))
190 return 0;
191
192 if (ch>h->nb_streams || (ch+h->nb_streams)>255)
193 return 0;
194 h->nb_coupled = ch;
195
196 /* Multi-stream support */
197 for (i=0;i<h->channels;i++)
198 {
199 if (!read_chars(&p, &h->stream_map[i], 1))
200 return 0;
201 if (h->stream_map[i]>(h->nb_streams+h->nb_coupled) && h->stream_map[i]!=255)
202 return 0;
203 }
204 } else {
205 if(h->channels>2)
206 return 0;
207 h->nb_streams = 1;
208 h->nb_coupled = h->channels>1;
209 h->stream_map[0]=0;
210 h->stream_map[1]=1;
211 }
212 /*For version 0/1 we know there won't be any more data
213 so reject any that have data past the end.*/
214 if ((h->version==0 || h->version==1) && p.pos != len)
215 return 0;
216 return 1;
217}
218
219int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len)
220{
221 int i;
222 Packet p;
223 unsigned char ch;
224
225 p.data = packet;
226 p.maxlen = len;
227 p.pos = 0;
228 if (len<19)return 0;
229 if (!write_chars(&p, (const unsigned char*)"OpusHead", 8))
230 return 0;
231 /* Version is 1 */
232 ch = 1;
233 if (!write_chars(&p, &ch, 1))
234 return 0;
235
236 ch = h->channels;
237 if (!write_chars(&p, &ch, 1))
238 return 0;
239
240 if (!write_uint16(&p, h->preskip))
241 return 0;
242
243 if (!write_uint32(&p, h->input_sample_rate))
244 return 0;
245
246 if (!write_uint16(&p, h->gain))
247 return 0;
248
249 ch = h->channel_mapping;
250 if (!write_chars(&p, &ch, 1))
251 return 0;
252
253 if (h->channel_mapping != 0)
254 {
255 ch = h->nb_streams;
256 if (!write_chars(&p, &ch, 1))
257 return 0;
258
259 ch = h->nb_coupled;
260 if (!write_chars(&p, &ch, 1))
261 return 0;
262
263 /* Multi-stream support */
264 for (i=0;i<h->channels;i++)
265 {
266 if (!write_chars(&p, &h->stream_map[i], 1))
267 return 0;
268 }
269 }
270
271 return p.pos;
272}
273
274/* This is just here because it's a convenient file linked by both opusenc and
275 opusdec (to guarantee this maps stays in sync). */
276const int wav_permute_matrix[8][8] =
277{
278 {0}, /* 1.0 mono */
279 {0,1}, /* 2.0 stereo */
280 {0,2,1}, /* 3.0 channel ('wide') stereo */
281 {0,1,2,3}, /* 4.0 discrete quadraphonic */
282 {0,2,1,3,4}, /* 5.0 surround */
283 {0,2,1,4,5,3}, /* 5.1 surround */
284 {0,2,1,5,6,4,3}, /* 6.1 surround */
285 {0,2,1,6,7,4,5,3} /* 7.1 surround (classic theater 8-track) */
286};
diff --git a/lib/rbcodec/codecs/libopus/opus_header.h b/lib/rbcodec/codecs/libopus/opus_header.h
new file mode 100644
index 0000000000..7bfacfe48c
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_header.h
@@ -0,0 +1,51 @@
1/* Copyright (C)2012 Xiph.Org Foundation
2 File: opus_header.h
3
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
19 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28#ifndef OPUS_HEADER_H
29#define OPUS_HEADER_H
30
31#include "ogg/ogg.h"
32
33typedef struct {
34 int version;
35 int channels; /* Number of channels: 1..255 */
36 int preskip;
37 ogg_uint32_t input_sample_rate;
38 int gain; /* in dB S7.8 should be zero whenever possible */
39 int channel_mapping;
40 /* The rest is only used if channel_mapping != 0 */
41 int nb_streams;
42 int nb_coupled;
43 unsigned char stream_map[255];
44} OpusHeader;
45
46int opus_header_parse(const unsigned char *header, int len, OpusHeader *h);
47int opus_header_to_packet(const OpusHeader *h, unsigned char *packet, int len);
48
49extern const int wav_permute_matrix[8][8];
50
51#endif
diff --git a/lib/rbcodec/codecs/libopus/opus_private.h b/lib/rbcodec/codecs/libopus/opus_private.h
new file mode 100644
index 0000000000..52482bc18c
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_private.h
@@ -0,0 +1,85 @@
1/* Copyright (c) 2012 Xiph.Org Foundation
2 Written by Jean-Marc Valin */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27
28
29#ifndef OPUS_PRIVATE_H
30#define OPUS_PRIVATE_H
31
32#include "arch.h"
33#include "opus.h"
34
35struct OpusRepacketizer {
36 unsigned char toc;
37 int nb_frames;
38 const unsigned char *frames[48];
39 short len[48];
40 int framesize;
41};
42
43
44#define MODE_SILK_ONLY 1000
45#define MODE_HYBRID 1001
46#define MODE_CELT_ONLY 1002
47
48#define OPUS_SET_VOICE_RATIO_REQUEST 11018
49#define OPUS_GET_VOICE_RATIO_REQUEST 11019
50
51/** Configures the encoder's expected percentage of voice
52 * opposed to music or other signals.
53 *
54 * @note This interface is currently more aspiration than actuality. It's
55 * ultimately expected to bias an automatic signal classifier, but it currently
56 * just shifts the static bitrate to mode mapping around a little bit.
57 *
58 * @param[in] x <tt>int</tt>: Voice percentage in the range 0-100, inclusive.
59 * @hideinitializer */
60#define OPUS_SET_VOICE_RATIO(x) OPUS_SET_VOICE_RATIO_REQUEST, __opus_check_int(x)
61/** Gets the encoder's configured voice ratio value, @see OPUS_SET_VOICE_RATIO
62 *
63 * @param[out] x <tt>int*</tt>: Voice percentage in the range 0-100, inclusive.
64 * @hideinitializer */
65#define OPUS_GET_VOICE_RATIO(x) OPUS_GET_VOICE_RATIO_REQUEST, __opus_check_int_ptr(x)
66
67
68#define OPUS_SET_FORCE_MODE_REQUEST 11002
69#define OPUS_SET_FORCE_MODE(x) OPUS_SET_FORCE_MODE_REQUEST, __opus_check_int(x)
70
71
72int encode_size(int size, unsigned char *data);
73
74int opus_decode_native(OpusDecoder *st, const unsigned char *data, opus_int32 len,
75 opus_val16 *pcm, int frame_size, int decode_fec, int self_delimited, int *packet_offset);
76
77/* Make sure everything's aligned to sizeof(void *) bytes */
78static inline int align(int i)
79{
80 return (i+sizeof(void *)-1)&-((int)sizeof(void *));
81}
82
83opus_int32 opus_repacketizer_out_range_impl(OpusRepacketizer *rp, int begin, int end, unsigned char *data, opus_int32 maxlen, int self_delimited);
84
85#endif /* OPUS_PRIVATE_H */
diff --git a/lib/rbcodec/codecs/libopus/opus_types.h b/lib/rbcodec/codecs/libopus/opus_types.h
new file mode 100644
index 0000000000..b28e03aea2
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/opus_types.h
@@ -0,0 +1,159 @@
1/* (C) COPYRIGHT 1994-2002 Xiph.Org Foundation */
2/* Modified by Jean-Marc Valin */
3/*
4 Redistribution and use in source and binary forms, with or without
5 modification, are permitted provided that the following conditions
6 are met:
7
8 - Redistributions of source code must retain the above copyright
9 notice, this list of conditions and the following disclaimer.
10
11 - Redistributions in binary form must reproduce the above copyright
12 notice, this list of conditions and the following disclaimer in the
13 documentation and/or other materials provided with the distribution.
14
15 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
19 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*/
27/* opus_types.h based on ogg_types.h from libogg */
28
29/**
30 @file opus_types.h
31 @brief Opus reference implementation types
32*/
33#ifndef OPUS_TYPES_H
34#define OPUS_TYPES_H
35
36/* Use the real stdint.h if it's there (taken from Paul Hsieh's pstdint.h) */
37#if (defined(__STDC__) && __STDC__ && __STDC_VERSION__ >= 199901L) || (defined(__GNUC__) && (defined(_STDINT_H) || defined(_STDINT_H_)) || defined (HAVE_STDINT_H))
38#include <stdint.h>
39
40 typedef int16_t opus_int16;
41 typedef uint16_t opus_uint16;
42 typedef int32_t opus_int32;
43 typedef uint32_t opus_uint32;
44#elif defined(_WIN32)
45
46# if defined(__CYGWIN__)
47# include <_G_config.h>
48 typedef _G_int32_t opus_int32;
49 typedef _G_uint32_t opus_uint32;
50 typedef _G_int16 opus_int16;
51 typedef _G_uint16 opus_uint16;
52# elif defined(__MINGW32__)
53 typedef short opus_int16;
54 typedef unsigned short opus_uint16;
55 typedef int opus_int32;
56 typedef unsigned int opus_uint32;
57# elif defined(__MWERKS__)
58 typedef int opus_int32;
59 typedef unsigned int opus_uint32;
60 typedef short opus_int16;
61 typedef unsigned short opus_uint16;
62# else
63 /* MSVC/Borland */
64 typedef __int32 opus_int32;
65 typedef unsigned __int32 opus_uint32;
66 typedef __int16 opus_int16;
67 typedef unsigned __int16 opus_uint16;
68# endif
69
70#elif defined(__MACOS__)
71
72# include <sys/types.h>
73 typedef SInt16 opus_int16;
74 typedef UInt16 opus_uint16;
75 typedef SInt32 opus_int32;
76 typedef UInt32 opus_uint32;
77
78#elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */
79
80# include <sys/types.h>
81 typedef int16_t opus_int16;
82 typedef u_int16_t opus_uint16;
83 typedef int32_t opus_int32;
84 typedef u_int32_t opus_uint32;
85
86#elif defined(__BEOS__)
87
88 /* Be */
89# include <inttypes.h>
90 typedef int16 opus_int16;
91 typedef u_int16 opus_uint16;
92 typedef int32_t opus_int32;
93 typedef u_int32_t opus_uint32;
94
95#elif defined (__EMX__)
96
97 /* OS/2 GCC */
98 typedef short opus_int16;
99 typedef unsigned short opus_uint16;
100 typedef int opus_int32;
101 typedef unsigned int opus_uint32;
102
103#elif defined (DJGPP)
104
105 /* DJGPP */
106 typedef short opus_int16;
107 typedef unsigned short opus_uint16;
108 typedef int opus_int32;
109 typedef unsigned int opus_uint32;
110
111#elif defined(R5900)
112
113 /* PS2 EE */
114 typedef int opus_int32;
115 typedef unsigned opus_uint32;
116 typedef short opus_int16;
117 typedef unsigned short opus_uint16;
118
119#elif defined(__SYMBIAN32__)
120
121 /* Symbian GCC */
122 typedef signed short opus_int16;
123 typedef unsigned short opus_uint16;
124 typedef signed int opus_int32;
125 typedef unsigned int opus_uint32;
126
127#elif defined(CONFIG_TI_C54X) || defined (CONFIG_TI_C55X)
128
129 typedef short opus_int16;
130 typedef unsigned short opus_uint16;
131 typedef long opus_int32;
132 typedef unsigned long opus_uint32;
133
134#elif defined(CONFIG_TI_C6X)
135
136 typedef short opus_int16;
137 typedef unsigned short opus_uint16;
138 typedef int opus_int32;
139 typedef unsigned int opus_uint32;
140
141#else
142
143 /* Give up, take a reasonable guess */
144 typedef short opus_int16;
145 typedef unsigned short opus_uint16;
146 typedef int opus_int32;
147 typedef unsigned int opus_uint32;
148
149#endif
150
151#define opus_int int /* used for counters etc; at least 16 bits */
152#define opus_int64 long long
153#define opus_int8 signed char
154
155#define opus_uint unsigned int /* used for counters etc; at least 16 bits */
156#define opus_uint64 unsigned long long
157#define opus_uint8 unsigned char
158
159#endif /* OPUS_TYPES_H */
diff --git a/lib/rbcodec/codecs/libopus/silk/API.h b/lib/rbcodec/codecs/libopus/silk/API.h
new file mode 100644
index 0000000000..4b8ca12ac6
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/API.h
@@ -0,0 +1,132 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_API_H
29#define SILK_API_H
30
31#include "control.h"
32#include "typedef.h"
33#include "errors.h"
34#include "entenc.h"
35#include "entdec.h"
36
37#ifdef __cplusplus
38extern "C"
39{
40#endif
41
42#define SILK_MAX_FRAMES_PER_PACKET 3
43
44/* Struct for TOC (Table of Contents) */
45typedef struct {
46 opus_int VADFlag; /* Voice activity for packet */
47 opus_int VADFlags[ SILK_MAX_FRAMES_PER_PACKET ]; /* Voice activity for each frame in packet */
48 opus_int inbandFECFlag; /* Flag indicating if packet contains in-band FEC */
49} silk_TOC_struct;
50
51/****************************************/
52/* Encoder functions */
53/****************************************/
54
55/***********************************************/
56/* Get size in bytes of the Silk encoder state */
57/***********************************************/
58opus_int silk_Get_Encoder_Size( /* O Returns error code */
59 opus_int *encSizeBytes /* O Number of bytes in SILK encoder state */
60);
61
62/*************************/
63/* Init or reset encoder */
64/*************************/
65opus_int silk_InitEncoder( /* O Returns error code */
66 void *encState, /* I/O State */
67 silk_EncControlStruct *encStatus /* O Encoder Status */
68);
69
70/**************************/
71/* Encode frame with Silk */
72/**************************/
73/* Note: if prefillFlag is set, the input must contain 10 ms of audio, irrespective of what */
74/* encControl->payloadSize_ms is set to */
75opus_int silk_Encode( /* O Returns error code */
76 void *encState, /* I/O State */
77 silk_EncControlStruct *encControl, /* I Control status */
78 const opus_int16 *samplesIn, /* I Speech sample input vector */
79 opus_int nSamplesIn, /* I Number of samples in input vector */
80 ec_enc *psRangeEnc, /* I/O Compressor data structure */
81 opus_int32 *nBytesOut, /* I/O Number of bytes in payload (input: Max bytes) */
82 const opus_int prefillFlag /* I Flag to indicate prefilling buffers no coding */
83);
84
85/****************************************/
86/* Decoder functions */
87/****************************************/
88
89/***********************************************/
90/* Get size in bytes of the Silk decoder state */
91/***********************************************/
92opus_int silk_Get_Decoder_Size( /* O Returns error code */
93 opus_int *decSizeBytes /* O Number of bytes in SILK decoder state */
94);
95
96/*************************/
97/* Init or Reset decoder */
98/*************************/
99opus_int silk_InitDecoder( /* O Returns error code */
100 void *decState /* I/O State */
101);
102
103/******************/
104/* Decode a frame */
105/******************/
106opus_int silk_Decode( /* O Returns error code */
107 void* decState, /* I/O State */
108 silk_DecControlStruct* decControl, /* I/O Control Structure */
109 opus_int lostFlag, /* I 0: no loss, 1 loss, 2 decode fec */
110 opus_int newPacketFlag, /* I Indicates first decoder call for this packet */
111 ec_dec *psRangeDec, /* I/O Compressor data structure */
112 opus_int16 *samplesOut, /* O Decoded output speech vector */
113 opus_int32 *nSamplesOut /* O Number of samples decoded */
114);
115
116#if 0
117/**************************************/
118/* Get table of contents for a packet */
119/**************************************/
120opus_int silk_get_TOC(
121 const opus_uint8 *payload, /* I Payload data */
122 const opus_int nBytesIn, /* I Number of input bytes */
123 const opus_int nFramesPerPayload, /* I Number of SILK frames per payload */
124 silk_TOC_struct *Silk_TOC /* O Type of content */
125);
126#endif
127
128#ifdef __cplusplus
129}
130#endif
131
132#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/CNG.c b/lib/rbcodec/codecs/libopus/silk/CNG.c
new file mode 100644
index 0000000000..fc19391057
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/CNG.c
@@ -0,0 +1,167 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Generates excitation for CNG LPC synthesis */
35static inline void silk_CNG_exc(
36 opus_int32 residual_Q10[], /* O CNG residual signal Q10 */
37 opus_int32 exc_buf_Q14[], /* I Random samples buffer Q10 */
38 opus_int32 Gain_Q16, /* I Gain to apply */
39 opus_int length, /* I Length */
40 opus_int32 *rand_seed /* I/O Seed to random index generator */
41)
42{
43 opus_int32 seed;
44 opus_int i, idx, exc_mask;
45
46 exc_mask = CNG_BUF_MASK_MAX;
47 while( exc_mask > length ) {
48 exc_mask = silk_RSHIFT( exc_mask, 1 );
49 }
50
51 seed = *rand_seed;
52 for( i = 0; i < length; i++ ) {
53 seed = silk_RAND( seed );
54 idx = (opus_int)( silk_RSHIFT( seed, 24 ) & exc_mask );
55 silk_assert( idx >= 0 );
56 silk_assert( idx <= CNG_BUF_MASK_MAX );
57 residual_Q10[ i ] = (opus_int16)silk_SAT16( silk_SMULWW( exc_buf_Q14[ idx ], Gain_Q16 >> 4 ) );
58 }
59 *rand_seed = seed;
60}
61
62void silk_CNG_Reset(
63 silk_decoder_state *psDec /* I/O Decoder state */
64)
65{
66 opus_int i, NLSF_step_Q15, NLSF_acc_Q15;
67
68 NLSF_step_Q15 = silk_DIV32_16( silk_int16_MAX, psDec->LPC_order + 1 );
69 NLSF_acc_Q15 = 0;
70 for( i = 0; i < psDec->LPC_order; i++ ) {
71 NLSF_acc_Q15 += NLSF_step_Q15;
72 psDec->sCNG.CNG_smth_NLSF_Q15[ i ] = NLSF_acc_Q15;
73 }
74 psDec->sCNG.CNG_smth_Gain_Q16 = 0;
75 psDec->sCNG.rand_seed = 3176576;
76}
77
78/* Updates CNG estimate, and applies the CNG when packet was lost */
79void silk_CNG(
80 silk_decoder_state *psDec, /* I/O Decoder state */
81 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
82 opus_int16 frame[], /* I/O Signal */
83 opus_int length /* I Length of residual */
84)
85{
86 opus_int i, subfr;
87 opus_int32 sum_Q6, max_Gain_Q16;
88 opus_int16 A_Q12[ MAX_LPC_ORDER ];
89 opus_int32 CNG_sig_Q10[ MAX_FRAME_LENGTH + MAX_LPC_ORDER ];
90 silk_CNG_struct *psCNG = &psDec->sCNG;
91
92 if( psDec->fs_kHz != psCNG->fs_kHz ) {
93 /* Reset state */
94 silk_CNG_Reset( psDec );
95
96 psCNG->fs_kHz = psDec->fs_kHz;
97 }
98 if( psDec->lossCnt == 0 && psDec->prevSignalType == TYPE_NO_VOICE_ACTIVITY ) {
99 /* Update CNG parameters */
100
101 /* Smoothing of LSF's */
102 for( i = 0; i < psDec->LPC_order; i++ ) {
103 psCNG->CNG_smth_NLSF_Q15[ i ] += silk_SMULWB( (opus_int32)psDec->prevNLSF_Q15[ i ] - (opus_int32)psCNG->CNG_smth_NLSF_Q15[ i ], CNG_NLSF_SMTH_Q16 );
104 }
105 /* Find the subframe with the highest gain */
106 max_Gain_Q16 = 0;
107 subfr = 0;
108 for( i = 0; i < psDec->nb_subfr; i++ ) {
109 if( psDecCtrl->Gains_Q16[ i ] > max_Gain_Q16 ) {
110 max_Gain_Q16 = psDecCtrl->Gains_Q16[ i ];
111 subfr = i;
112 }
113 }
114 /* Update CNG excitation buffer with excitation from this subframe */
115 silk_memmove( &psCNG->CNG_exc_buf_Q14[ psDec->subfr_length ], psCNG->CNG_exc_buf_Q14, ( psDec->nb_subfr - 1 ) * psDec->subfr_length * sizeof( opus_int32 ) );
116 silk_memcpy( psCNG->CNG_exc_buf_Q14, &psDec->exc_Q14[ subfr * psDec->subfr_length ], psDec->subfr_length * sizeof( opus_int32 ) );
117
118 /* Smooth gains */
119 for( i = 0; i < psDec->nb_subfr; i++ ) {
120 psCNG->CNG_smth_Gain_Q16 += silk_SMULWB( psDecCtrl->Gains_Q16[ i ] - psCNG->CNG_smth_Gain_Q16, CNG_GAIN_SMTH_Q16 );
121 }
122 }
123
124 /* Add CNG when packet is lost or during DTX */
125 if( psDec->lossCnt ) {
126
127 /* Generate CNG excitation */
128 silk_CNG_exc( CNG_sig_Q10 + MAX_LPC_ORDER, psCNG->CNG_exc_buf_Q14, psCNG->CNG_smth_Gain_Q16, length, &psCNG->rand_seed );
129
130 /* Convert CNG NLSF to filter representation */
131 silk_NLSF2A( A_Q12, psCNG->CNG_smth_NLSF_Q15, psDec->LPC_order );
132
133 /* Generate CNG signal, by synthesis filtering */
134 silk_memcpy( CNG_sig_Q10, psCNG->CNG_synth_state, MAX_LPC_ORDER * sizeof( opus_int32 ) );
135 for( i = 0; i < length; i++ ) {
136 silk_assert( psDec->LPC_order == 10 || psDec->LPC_order == 16 );
137 /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
138 sum_Q6 = silk_RSHIFT( psDec->LPC_order, 1 );
139 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 1 ], A_Q12[ 0 ] );
140 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 2 ], A_Q12[ 1 ] );
141 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 3 ], A_Q12[ 2 ] );
142 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 4 ], A_Q12[ 3 ] );
143 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 5 ], A_Q12[ 4 ] );
144 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 6 ], A_Q12[ 5 ] );
145 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 7 ], A_Q12[ 6 ] );
146 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 8 ], A_Q12[ 7 ] );
147 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 9 ], A_Q12[ 8 ] );
148 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 10 ], A_Q12[ 9 ] );
149 if( psDec->LPC_order == 16 ) {
150 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 11 ], A_Q12[ 10 ] );
151 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 12 ], A_Q12[ 11 ] );
152 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 13 ], A_Q12[ 12 ] );
153 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 14 ], A_Q12[ 13 ] );
154 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 15 ], A_Q12[ 14 ] );
155 sum_Q6 = silk_SMLAWB( sum_Q6, CNG_sig_Q10[ MAX_LPC_ORDER + i - 16 ], A_Q12[ 15 ] );
156 }
157
158 /* Update states */
159 CNG_sig_Q10[ MAX_LPC_ORDER + i ] = silk_ADD_LSHIFT( CNG_sig_Q10[ MAX_LPC_ORDER + i ], sum_Q6, 4 );
160
161 frame[ i ] = silk_ADD_SAT16( frame[ i ], silk_RSHIFT_ROUND( sum_Q6, 6 ) );
162 }
163 silk_memcpy( psCNG->CNG_synth_state, &CNG_sig_Q10[ length ], MAX_LPC_ORDER * sizeof( opus_int32 ) );
164 } else {
165 silk_memset( psCNG->CNG_synth_state, 0, psDec->LPC_order * sizeof( opus_int32 ) );
166 }
167}
diff --git a/lib/rbcodec/codecs/libopus/silk/Inlines.h b/lib/rbcodec/codecs/libopus/silk/Inlines.h
new file mode 100644
index 0000000000..87ac2e20d6
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/Inlines.h
@@ -0,0 +1,188 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28/*! \file silk_Inlines.h
29 * \brief silk_Inlines.h defines inline signal processing functions.
30 */
31
32#ifndef SILK_FIX_INLINES_H
33#define SILK_FIX_INLINES_H
34
35#ifdef __cplusplus
36extern "C"
37{
38#endif
39
40/* count leading zeros of opus_int64 */
41static inline opus_int32 silk_CLZ64( opus_int64 in )
42{
43 opus_int32 in_upper;
44
45 in_upper = (opus_int32)silk_RSHIFT64(in, 32);
46 if (in_upper == 0) {
47 /* Search in the lower 32 bits */
48 return 32 + silk_CLZ32( (opus_int32) in );
49 } else {
50 /* Search in the upper 32 bits */
51 return silk_CLZ32( in_upper );
52 }
53}
54
55/* get number of leading zeros and fractional part (the bits right after the leading one */
56static inline void silk_CLZ_FRAC(
57 opus_int32 in, /* I input */
58 opus_int32 *lz, /* O number of leading zeros */
59 opus_int32 *frac_Q7 /* O the 7 bits right after the leading one */
60)
61{
62 opus_int32 lzeros = silk_CLZ32(in);
63
64 * lz = lzeros;
65 * frac_Q7 = silk_ROR32(in, 24 - lzeros) & 0x7f;
66}
67
68/* Approximation of square root */
69/* Accuracy: < +/- 10% for output values > 15 */
70/* < +/- 2.5% for output values > 120 */
71static inline opus_int32 silk_SQRT_APPROX( opus_int32 x )
72{
73 opus_int32 y, lz, frac_Q7;
74
75 if( x <= 0 ) {
76 return 0;
77 }
78
79 silk_CLZ_FRAC(x, &lz, &frac_Q7);
80
81 if( lz & 1 ) {
82 y = 32768;
83 } else {
84 y = 46214; /* 46214 = sqrt(2) * 32768 */
85 }
86
87 /* get scaling right */
88 y >>= silk_RSHIFT(lz, 1);
89
90 /* increment using fractional part of input */
91 y = silk_SMLAWB(y, y, silk_SMULBB(213, frac_Q7));
92
93 return y;
94}
95
96/* Divide two int32 values and return result as int32 in a given Q-domain */
97static inline opus_int32 silk_DIV32_varQ( /* O returns a good approximation of "(a32 << Qres) / b32" */
98 const opus_int32 a32, /* I numerator (Q0) */
99 const opus_int32 b32, /* I denominator (Q0) */
100 const opus_int Qres /* I Q-domain of result (>= 0) */
101)
102{
103 opus_int a_headrm, b_headrm, lshift;
104 opus_int32 b32_inv, a32_nrm, b32_nrm, result;
105
106 silk_assert( b32 != 0 );
107 silk_assert( Qres >= 0 );
108
109 /* Compute number of bits head room and normalize inputs */
110 a_headrm = silk_CLZ32( silk_abs(a32) ) - 1;
111 a32_nrm = silk_LSHIFT(a32, a_headrm); /* Q: a_headrm */
112 b_headrm = silk_CLZ32( silk_abs(b32) ) - 1;
113 b32_nrm = silk_LSHIFT(b32, b_headrm); /* Q: b_headrm */
114
115 /* Inverse of b32, with 14 bits of precision */
116 b32_inv = silk_DIV32_16( silk_int32_MAX >> 2, silk_RSHIFT(b32_nrm, 16) ); /* Q: 29 + 16 - b_headrm */
117
118 /* First approximation */
119 result = silk_SMULWB(a32_nrm, b32_inv); /* Q: 29 + a_headrm - b_headrm */
120
121 /* Compute residual by subtracting product of denominator and first approximation */
122 /* It's OK to overflow because the final value of a32_nrm should always be small */
123 a32_nrm = silk_SUB32_ovflw(a32_nrm, silk_LSHIFT_ovflw( silk_SMMUL(b32_nrm, result), 3 )); /* Q: a_headrm */
124
125 /* Refinement */
126 result = silk_SMLAWB(result, a32_nrm, b32_inv); /* Q: 29 + a_headrm - b_headrm */
127
128 /* Convert to Qres domain */
129 lshift = 29 + a_headrm - b_headrm - Qres;
130 if( lshift < 0 ) {
131 return silk_LSHIFT_SAT32(result, -lshift);
132 } else {
133 if( lshift < 32){
134 return silk_RSHIFT(result, lshift);
135 } else {
136 /* Avoid undefined result */
137 return 0;
138 }
139 }
140}
141
142/* Invert int32 value and return result as int32 in a given Q-domain */
143static inline opus_int32 silk_INVERSE32_varQ( /* O returns a good approximation of "(1 << Qres) / b32" */
144 const opus_int32 b32, /* I denominator (Q0) */
145 const opus_int Qres /* I Q-domain of result (> 0) */
146)
147{
148 opus_int b_headrm, lshift;
149 opus_int32 b32_inv, b32_nrm, err_Q32, result;
150
151 silk_assert( b32 != 0 );
152 silk_assert( Qres > 0 );
153
154 /* Compute number of bits head room and normalize input */
155 b_headrm = silk_CLZ32( silk_abs(b32) ) - 1;
156 b32_nrm = silk_LSHIFT(b32, b_headrm); /* Q: b_headrm */
157
158 /* Inverse of b32, with 14 bits of precision */
159 b32_inv = silk_DIV32_16( silk_int32_MAX >> 2, silk_RSHIFT(b32_nrm, 16) ); /* Q: 29 + 16 - b_headrm */
160
161 /* First approximation */
162 result = silk_LSHIFT(b32_inv, 16); /* Q: 61 - b_headrm */
163
164 /* Compute residual by subtracting product of denominator and first approximation from one */
165 err_Q32 = silk_LSHIFT( ((opus_int32)1<<29) - silk_SMULWB(b32_nrm, b32_inv), 3 ); /* Q32 */
166
167 /* Refinement */
168 result = silk_SMLAWW(result, err_Q32, b32_inv); /* Q: 61 - b_headrm */
169
170 /* Convert to Qres domain */
171 lshift = 61 - b_headrm - Qres;
172 if( lshift <= 0 ) {
173 return silk_LSHIFT_SAT32(result, -lshift);
174 } else {
175 if( lshift < 32){
176 return silk_RSHIFT(result, lshift);
177 }else{
178 /* Avoid undefined result */
179 return 0;
180 }
181 }
182}
183
184#ifdef __cplusplus
185}
186#endif
187
188#endif /* SILK_FIX_INLINES_H */
diff --git a/lib/rbcodec/codecs/libopus/silk/LPC_analysis_filter.c b/lib/rbcodec/codecs/libopus/silk/LPC_analysis_filter.c
new file mode 100644
index 0000000000..7d4458a637
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/LPC_analysis_filter.c
@@ -0,0 +1,85 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33
34/*******************************************/
35/* LPC analysis filter */
36/* NB! State is kept internally and the */
37/* filter always starts with zero state */
38/* first d output samples are set to zero */
39/*******************************************/
40
41void silk_LPC_analysis_filter(
42 opus_int16 *out, /* O Output signal */
43 const opus_int16 *in, /* I Input signal */
44 const opus_int16 *B, /* I MA prediction coefficients, Q12 [order] */
45 const opus_int32 len, /* I Signal length */
46 const opus_int32 d /* I Filter order */
47)
48{
49 opus_int ix, j;
50 opus_int32 out32_Q12, out32;
51 const opus_int16 *in_ptr;
52
53 silk_assert( d >= 6 );
54 silk_assert( (d & 1) == 0 );
55 silk_assert( d <= len );
56
57 for( ix = d; ix < len; ix++ ) {
58 in_ptr = &in[ ix - 1 ];
59
60 out32_Q12 = silk_SMULBB( in_ptr[ 0 ], B[ 0 ] );
61 /* Allowing wrap around so that two wraps can cancel each other. The rare
62 cases where the result wraps around can only be triggered by invalid streams*/
63 out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -1 ], B[ 1 ] );
64 out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -2 ], B[ 2 ] );
65 out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -3 ], B[ 3 ] );
66 out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -4 ], B[ 4 ] );
67 out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -5 ], B[ 5 ] );
68 for( j = 6; j < d; j += 2 ) {
69 out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -j ], B[ j ] );
70 out32_Q12 = silk_SMLABB_ovflw( out32_Q12, in_ptr[ -j - 1 ], B[ j + 1 ] );
71 }
72
73 /* Subtract prediction */
74 out32_Q12 = silk_SUB32_ovflw( silk_LSHIFT( (opus_int32)in_ptr[ 1 ], 12 ), out32_Q12 );
75
76 /* Scale to Q0 */
77 out32 = silk_RSHIFT_ROUND( out32_Q12, 12 );
78
79 /* Saturate output */
80 out[ ix ] = (opus_int16)silk_SAT16( out32 );
81 }
82
83 /* Set first d output samples to zero */
84 silk_memset( out, 0, d * sizeof( opus_int16 ) );
85}
diff --git a/lib/rbcodec/codecs/libopus/silk/LPC_inv_pred_gain.c b/lib/rbcodec/codecs/libopus/silk/LPC_inv_pred_gain.c
new file mode 100644
index 0000000000..afbb48ae1d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/LPC_inv_pred_gain.c
@@ -0,0 +1,154 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33
34#define QA 24
35#define A_LIMIT SILK_FIX_CONST( 0.99975, QA )
36
37#define MUL32_FRAC_Q(a32, b32, Q) ((opus_int32)(silk_RSHIFT_ROUND64(silk_SMULL(a32, b32), Q)))
38
39/* Compute inverse of LPC prediction gain, and */
40/* test if LPC coefficients are stable (all poles within unit circle) */
41static opus_int32 LPC_inverse_pred_gain_QA( /* O Returns inverse prediction gain in energy domain, Q30 */
42 opus_int32 A_QA[ 2 ][ SILK_MAX_ORDER_LPC ], /* I Prediction coefficients */
43 const opus_int order /* I Prediction order */
44)
45{
46 opus_int k, n, mult2Q;
47 opus_int32 invGain_Q30, rc_Q31, rc_mult1_Q30, rc_mult2, tmp_QA;
48 opus_int32 *Aold_QA, *Anew_QA;
49
50 Anew_QA = A_QA[ order & 1 ];
51
52 invGain_Q30 = (opus_int32)1 << 30;
53 for( k = order - 1; k > 0; k-- ) {
54 /* Check for stability */
55 if( ( Anew_QA[ k ] > A_LIMIT ) || ( Anew_QA[ k ] < -A_LIMIT ) ) {
56 return 0;
57 }
58
59 /* Set RC equal to negated AR coef */
60 rc_Q31 = -silk_LSHIFT( Anew_QA[ k ], 31 - QA );
61
62 /* rc_mult1_Q30 range: [ 1 : 2^30 ] */
63 rc_mult1_Q30 = ( (opus_int32)1 << 30 ) - silk_SMMUL( rc_Q31, rc_Q31 );
64 silk_assert( rc_mult1_Q30 > ( 1 << 15 ) ); /* reduce A_LIMIT if fails */
65 silk_assert( rc_mult1_Q30 <= ( 1 << 30 ) );
66
67 /* rc_mult2 range: [ 2^30 : silk_int32_MAX ] */
68 mult2Q = 32 - silk_CLZ32( silk_abs( rc_mult1_Q30 ) );
69 rc_mult2 = silk_INVERSE32_varQ( rc_mult1_Q30, mult2Q + 30 );
70
71 /* Update inverse gain */
72 /* invGain_Q30 range: [ 0 : 2^30 ] */
73 invGain_Q30 = silk_LSHIFT( silk_SMMUL( invGain_Q30, rc_mult1_Q30 ), 2 );
74 silk_assert( invGain_Q30 >= 0 );
75 silk_assert( invGain_Q30 <= ( 1 << 30 ) );
76
77 /* Swap pointers */
78 Aold_QA = Anew_QA;
79 Anew_QA = A_QA[ k & 1 ];
80
81 /* Update AR coefficient */
82 for( n = 0; n < k; n++ ) {
83 tmp_QA = Aold_QA[ n ] - MUL32_FRAC_Q( Aold_QA[ k - n - 1 ], rc_Q31, 31 );
84 Anew_QA[ n ] = MUL32_FRAC_Q( tmp_QA, rc_mult2 , mult2Q );
85 }
86 }
87
88 /* Check for stability */
89 if( ( Anew_QA[ 0 ] > A_LIMIT ) || ( Anew_QA[ 0 ] < -A_LIMIT ) ) {
90 return 0;
91 }
92
93 /* Set RC equal to negated AR coef */
94 rc_Q31 = -silk_LSHIFT( Anew_QA[ 0 ], 31 - QA );
95
96 /* Range: [ 1 : 2^30 ] */
97 rc_mult1_Q30 = ( (opus_int32)1 << 30 ) - silk_SMMUL( rc_Q31, rc_Q31 );
98
99 /* Update inverse gain */
100 /* Range: [ 0 : 2^30 ] */
101 invGain_Q30 = silk_LSHIFT( silk_SMMUL( invGain_Q30, rc_mult1_Q30 ), 2 );
102 silk_assert( invGain_Q30 >= 0 );
103 silk_assert( invGain_Q30 <= 1<<30 );
104
105 return invGain_Q30;
106}
107
108/* For input in Q12 domain */
109opus_int32 silk_LPC_inverse_pred_gain( /* O Returns inverse prediction gain in energy domain, Q30 */
110 const opus_int16 *A_Q12, /* I Prediction coefficients, Q12 [order] */
111 const opus_int order /* I Prediction order */
112)
113{
114 opus_int k;
115 opus_int32 Atmp_QA[ 2 ][ SILK_MAX_ORDER_LPC ];
116 opus_int32 *Anew_QA;
117 opus_int32 DC_resp = 0;
118
119 Anew_QA = Atmp_QA[ order & 1 ];
120
121 /* Increase Q domain of the AR coefficients */
122 for( k = 0; k < order; k++ ) {
123 DC_resp += (opus_int32)A_Q12[ k ];
124 Anew_QA[ k ] = silk_LSHIFT32( (opus_int32)A_Q12[ k ], QA - 12 );
125 }
126 /* If the DC is unstable, we don't even need to do the full calculations */
127 if( DC_resp >= 4096 ) {
128 return 0;
129 }
130 return LPC_inverse_pred_gain_QA( Atmp_QA, order );
131}
132
133#ifdef FIXED_POINT
134
135/* For input in Q24 domain */
136opus_int32 silk_LPC_inverse_pred_gain_Q24( /* O Returns inverse prediction gain in energy domain, Q30 */
137 const opus_int32 *A_Q24, /* I Prediction coefficients [order] */
138 const opus_int order /* I Prediction order */
139)
140{
141 opus_int k;
142 opus_int32 Atmp_QA[ 2 ][ SILK_MAX_ORDER_LPC ];
143 opus_int32 *Anew_QA;
144
145 Anew_QA = Atmp_QA[ order & 1 ];
146
147 /* Increase Q domain of the AR coefficients */
148 for( k = 0; k < order; k++ ) {
149 Anew_QA[ k ] = silk_RSHIFT32( A_Q24[ k ], 24 - QA );
150 }
151
152 return LPC_inverse_pred_gain_QA( Atmp_QA, order );
153}
154#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/MacroCount.h b/lib/rbcodec/codecs/libopus/silk/MacroCount.h
new file mode 100644
index 0000000000..2829e8ccb4
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/MacroCount.h
@@ -0,0 +1,718 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SIGPROCFIX_API_MACROCOUNT_H
29#define SIGPROCFIX_API_MACROCOUNT_H
30#include <stdio.h>
31
32#ifdef silk_MACRO_COUNT
33#define varDefine opus_int64 ops_count = 0;
34
35extern opus_int64 ops_count;
36
37static inline opus_int64 silk_SaveCount(){
38 return(ops_count);
39}
40
41static inline opus_int64 silk_SaveResetCount(){
42 opus_int64 ret;
43
44 ret = ops_count;
45 ops_count = 0;
46 return(ret);
47}
48
49static inline silk_PrintCount(){
50 printf("ops_count = %d \n ", (opus_int32)ops_count);
51}
52
53#undef silk_MUL
54static inline opus_int32 silk_MUL(opus_int32 a32, opus_int32 b32){
55 opus_int32 ret;
56 ops_count += 4;
57 ret = a32 * b32;
58 return ret;
59}
60
61#undef silk_MUL_uint
62static inline opus_uint32 silk_MUL_uint(opus_uint32 a32, opus_uint32 b32){
63 opus_uint32 ret;
64 ops_count += 4;
65 ret = a32 * b32;
66 return ret;
67}
68#undef silk_MLA
69static inline opus_int32 silk_MLA(opus_int32 a32, opus_int32 b32, opus_int32 c32){
70 opus_int32 ret;
71 ops_count += 4;
72 ret = a32 + b32 * c32;
73 return ret;
74}
75
76#undef silk_MLA_uint
77static inline opus_int32 silk_MLA_uint(opus_uint32 a32, opus_uint32 b32, opus_uint32 c32){
78 opus_uint32 ret;
79 ops_count += 4;
80 ret = a32 + b32 * c32;
81 return ret;
82}
83
84#undef silk_SMULWB
85static inline opus_int32 silk_SMULWB(opus_int32 a32, opus_int32 b32){
86 opus_int32 ret;
87 ops_count += 5;
88 ret = (a32 >> 16) * (opus_int32)((opus_int16)b32) + (((a32 & 0x0000FFFF) * (opus_int32)((opus_int16)b32)) >> 16);
89 return ret;
90}
91#undef silk_SMLAWB
92static inline opus_int32 silk_SMLAWB(opus_int32 a32, opus_int32 b32, opus_int32 c32){
93 opus_int32 ret;
94 ops_count += 5;
95 ret = ((a32) + ((((b32) >> 16) * (opus_int32)((opus_int16)(c32))) + ((((b32) & 0x0000FFFF) * (opus_int32)((opus_int16)(c32))) >> 16)));
96 return ret;
97}
98
99#undef silk_SMULWT
100static inline opus_int32 silk_SMULWT(opus_int32 a32, opus_int32 b32){
101 opus_int32 ret;
102 ops_count += 4;
103 ret = (a32 >> 16) * (b32 >> 16) + (((a32 & 0x0000FFFF) * (b32 >> 16)) >> 16);
104 return ret;
105}
106#undef silk_SMLAWT
107static inline opus_int32 silk_SMLAWT(opus_int32 a32, opus_int32 b32, opus_int32 c32){
108 opus_int32 ret;
109 ops_count += 4;
110 ret = a32 + ((b32 >> 16) * (c32 >> 16)) + (((b32 & 0x0000FFFF) * ((c32 >> 16)) >> 16));
111 return ret;
112}
113
114#undef silk_SMULBB
115static inline opus_int32 silk_SMULBB(opus_int32 a32, opus_int32 b32){
116 opus_int32 ret;
117 ops_count += 1;
118 ret = (opus_int32)((opus_int16)a32) * (opus_int32)((opus_int16)b32);
119 return ret;
120}
121#undef silk_SMLABB
122static inline opus_int32 silk_SMLABB(opus_int32 a32, opus_int32 b32, opus_int32 c32){
123 opus_int32 ret;
124 ops_count += 1;
125 ret = a32 + (opus_int32)((opus_int16)b32) * (opus_int32)((opus_int16)c32);
126 return ret;
127}
128
129#undef silk_SMULBT
130static inline opus_int32 silk_SMULBT(opus_int32 a32, opus_int32 b32 ){
131 opus_int32 ret;
132 ops_count += 4;
133 ret = ((opus_int32)((opus_int16)a32)) * (b32 >> 16);
134 return ret;
135}
136
137#undef silk_SMLABT
138static inline opus_int32 silk_SMLABT(opus_int32 a32, opus_int32 b32, opus_int32 c32){
139 opus_int32 ret;
140 ops_count += 1;
141 ret = a32 + ((opus_int32)((opus_int16)b32)) * (c32 >> 16);
142 return ret;
143}
144
145#undef silk_SMULTT
146static inline opus_int32 silk_SMULTT(opus_int32 a32, opus_int32 b32){
147 opus_int32 ret;
148 ops_count += 1;
149 ret = (a32 >> 16) * (b32 >> 16);
150 return ret;
151}
152
153#undef silk_SMLATT
154static inline opus_int32 silk_SMLATT(opus_int32 a32, opus_int32 b32, opus_int32 c32){
155 opus_int32 ret;
156 ops_count += 1;
157 ret = a32 + (b32 >> 16) * (c32 >> 16);
158 return ret;
159}
160
161
162/* multiply-accumulate macros that allow overflow in the addition (ie, no asserts in debug mode)*/
163#undef silk_MLA_ovflw
164#define silk_MLA_ovflw silk_MLA
165
166#undef silk_SMLABB_ovflw
167#define silk_SMLABB_ovflw silk_SMLABB
168
169#undef silk_SMLABT_ovflw
170#define silk_SMLABT_ovflw silk_SMLABT
171
172#undef silk_SMLATT_ovflw
173#define silk_SMLATT_ovflw silk_SMLATT
174
175#undef silk_SMLAWB_ovflw
176#define silk_SMLAWB_ovflw silk_SMLAWB
177
178#undef silk_SMLAWT_ovflw
179#define silk_SMLAWT_ovflw silk_SMLAWT
180
181#undef silk_SMULL
182static inline opus_int64 silk_SMULL(opus_int32 a32, opus_int32 b32){
183 opus_int64 ret;
184 ops_count += 8;
185 ret = ((opus_int64)(a32) * /*(opus_int64)*/(b32));
186 return ret;
187}
188
189#undef silk_SMLAL
190static inline opus_int64 silk_SMLAL(opus_int64 a64, opus_int32 b32, opus_int32 c32){
191 opus_int64 ret;
192 ops_count += 8;
193 ret = a64 + ((opus_int64)(b32) * /*(opus_int64)*/(c32));
194 return ret;
195}
196#undef silk_SMLALBB
197static inline opus_int64 silk_SMLALBB(opus_int64 a64, opus_int16 b16, opus_int16 c16){
198 opus_int64 ret;
199 ops_count += 4;
200 ret = a64 + ((opus_int64)(b16) * /*(opus_int64)*/(c16));
201 return ret;
202}
203
204#undef SigProcFIX_CLZ16
205static inline opus_int32 SigProcFIX_CLZ16(opus_int16 in16)
206{
207 opus_int32 out32 = 0;
208 ops_count += 10;
209 if( in16 == 0 ) {
210 return 16;
211 }
212 /* test nibbles */
213 if( in16 & 0xFF00 ) {
214 if( in16 & 0xF000 ) {
215 in16 >>= 12;
216 } else {
217 out32 += 4;
218 in16 >>= 8;
219 }
220 } else {
221 if( in16 & 0xFFF0 ) {
222 out32 += 8;
223 in16 >>= 4;
224 } else {
225 out32 += 12;
226 }
227 }
228 /* test bits and return */
229 if( in16 & 0xC ) {
230 if( in16 & 0x8 )
231 return out32 + 0;
232 else
233 return out32 + 1;
234 } else {
235 if( in16 & 0xE )
236 return out32 + 2;
237 else
238 return out32 + 3;
239 }
240}
241
242#undef SigProcFIX_CLZ32
243static inline opus_int32 SigProcFIX_CLZ32(opus_int32 in32)
244{
245 /* test highest 16 bits and convert to opus_int16 */
246 ops_count += 2;
247 if( in32 & 0xFFFF0000 ) {
248 return SigProcFIX_CLZ16((opus_int16)(in32 >> 16));
249 } else {
250 return SigProcFIX_CLZ16((opus_int16)in32) + 16;
251 }
252}
253
254#undef silk_DIV32
255static inline opus_int32 silk_DIV32(opus_int32 a32, opus_int32 b32){
256 ops_count += 64;
257 return a32 / b32;
258}
259
260#undef silk_DIV32_16
261static inline opus_int32 silk_DIV32_16(opus_int32 a32, opus_int32 b32){
262 ops_count += 32;
263 return a32 / b32;
264}
265
266#undef silk_SAT8
267static inline opus_int8 silk_SAT8(opus_int64 a){
268 opus_int8 tmp;
269 ops_count += 1;
270 tmp = (opus_int8)((a) > silk_int8_MAX ? silk_int8_MAX : \
271 ((a) < silk_int8_MIN ? silk_int8_MIN : (a)));
272 return(tmp);
273}
274
275#undef silk_SAT16
276static inline opus_int16 silk_SAT16(opus_int64 a){
277 opus_int16 tmp;
278 ops_count += 1;
279 tmp = (opus_int16)((a) > silk_int16_MAX ? silk_int16_MAX : \
280 ((a) < silk_int16_MIN ? silk_int16_MIN : (a)));
281 return(tmp);
282}
283#undef silk_SAT32
284static inline opus_int32 silk_SAT32(opus_int64 a){
285 opus_int32 tmp;
286 ops_count += 1;
287 tmp = (opus_int32)((a) > silk_int32_MAX ? silk_int32_MAX : \
288 ((a) < silk_int32_MIN ? silk_int32_MIN : (a)));
289 return(tmp);
290}
291#undef silk_POS_SAT32
292static inline opus_int32 silk_POS_SAT32(opus_int64 a){
293 opus_int32 tmp;
294 ops_count += 1;
295 tmp = (opus_int32)((a) > silk_int32_MAX ? silk_int32_MAX : (a));
296 return(tmp);
297}
298
299#undef silk_ADD_POS_SAT8
300static inline opus_int8 silk_ADD_POS_SAT8(opus_int64 a, opus_int64 b){
301 opus_int8 tmp;
302 ops_count += 1;
303 tmp = (opus_int8)((((a)+(b)) & 0x80) ? silk_int8_MAX : ((a)+(b)));
304 return(tmp);
305}
306#undef silk_ADD_POS_SAT16
307static inline opus_int16 silk_ADD_POS_SAT16(opus_int64 a, opus_int64 b){
308 opus_int16 tmp;
309 ops_count += 1;
310 tmp = (opus_int16)((((a)+(b)) & 0x8000) ? silk_int16_MAX : ((a)+(b)));
311 return(tmp);
312}
313
314#undef silk_ADD_POS_SAT32
315static inline opus_int32 silk_ADD_POS_SAT32(opus_int64 a, opus_int64 b){
316 opus_int32 tmp;
317 ops_count += 1;
318 tmp = (opus_int32)((((a)+(b)) & 0x80000000) ? silk_int32_MAX : ((a)+(b)));
319 return(tmp);
320}
321
322#undef silk_ADD_POS_SAT64
323static inline opus_int64 silk_ADD_POS_SAT64(opus_int64 a, opus_int64 b){
324 opus_int64 tmp;
325 ops_count += 1;
326 tmp = ((((a)+(b)) & 0x8000000000000000LL) ? silk_int64_MAX : ((a)+(b)));
327 return(tmp);
328}
329
330#undef silk_LSHIFT8
331static inline opus_int8 silk_LSHIFT8(opus_int8 a, opus_int32 shift){
332 opus_int8 ret;
333 ops_count += 1;
334 ret = a << shift;
335 return ret;
336}
337#undef silk_LSHIFT16
338static inline opus_int16 silk_LSHIFT16(opus_int16 a, opus_int32 shift){
339 opus_int16 ret;
340 ops_count += 1;
341 ret = a << shift;
342 return ret;
343}
344#undef silk_LSHIFT32
345static inline opus_int32 silk_LSHIFT32(opus_int32 a, opus_int32 shift){
346 opus_int32 ret;
347 ops_count += 1;
348 ret = a << shift;
349 return ret;
350}
351#undef silk_LSHIFT64
352static inline opus_int64 silk_LSHIFT64(opus_int64 a, opus_int shift){
353 ops_count += 1;
354 return a << shift;
355}
356
357#undef silk_LSHIFT_ovflw
358static inline opus_int32 silk_LSHIFT_ovflw(opus_int32 a, opus_int32 shift){
359 ops_count += 1;
360 return a << shift;
361}
362
363#undef silk_LSHIFT_uint
364static inline opus_uint32 silk_LSHIFT_uint(opus_uint32 a, opus_int32 shift){
365 opus_uint32 ret;
366 ops_count += 1;
367 ret = a << shift;
368 return ret;
369}
370
371#undef silk_RSHIFT8
372static inline opus_int8 silk_RSHIFT8(opus_int8 a, opus_int32 shift){
373 ops_count += 1;
374 return a >> shift;
375}
376#undef silk_RSHIFT16
377static inline opus_int16 silk_RSHIFT16(opus_int16 a, opus_int32 shift){
378 ops_count += 1;
379 return a >> shift;
380}
381#undef silk_RSHIFT32
382static inline opus_int32 silk_RSHIFT32(opus_int32 a, opus_int32 shift){
383 ops_count += 1;
384 return a >> shift;
385}
386#undef silk_RSHIFT64
387static inline opus_int64 silk_RSHIFT64(opus_int64 a, opus_int64 shift){
388 ops_count += 1;
389 return a >> shift;
390}
391
392#undef silk_RSHIFT_uint
393static inline opus_uint32 silk_RSHIFT_uint(opus_uint32 a, opus_int32 shift){
394 ops_count += 1;
395 return a >> shift;
396}
397
398#undef silk_ADD_LSHIFT
399static inline opus_int32 silk_ADD_LSHIFT(opus_int32 a, opus_int32 b, opus_int32 shift){
400 opus_int32 ret;
401 ops_count += 1;
402 ret = a + (b << shift);
403 return ret; /* shift >= 0*/
404}
405#undef silk_ADD_LSHIFT32
406static inline opus_int32 silk_ADD_LSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
407 opus_int32 ret;
408 ops_count += 1;
409 ret = a + (b << shift);
410 return ret; /* shift >= 0*/
411}
412#undef silk_ADD_LSHIFT_uint
413static inline opus_uint32 silk_ADD_LSHIFT_uint(opus_uint32 a, opus_uint32 b, opus_int32 shift){
414 opus_uint32 ret;
415 ops_count += 1;
416 ret = a + (b << shift);
417 return ret; /* shift >= 0*/
418}
419#undef silk_ADD_RSHIFT
420static inline opus_int32 silk_ADD_RSHIFT(opus_int32 a, opus_int32 b, opus_int32 shift){
421 opus_int32 ret;
422 ops_count += 1;
423 ret = a + (b >> shift);
424 return ret; /* shift > 0*/
425}
426#undef silk_ADD_RSHIFT32
427static inline opus_int32 silk_ADD_RSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
428 opus_int32 ret;
429 ops_count += 1;
430 ret = a + (b >> shift);
431 return ret; /* shift > 0*/
432}
433#undef silk_ADD_RSHIFT_uint
434static inline opus_uint32 silk_ADD_RSHIFT_uint(opus_uint32 a, opus_uint32 b, opus_int32 shift){
435 opus_uint32 ret;
436 ops_count += 1;
437 ret = a + (b >> shift);
438 return ret; /* shift > 0*/
439}
440#undef silk_SUB_LSHIFT32
441static inline opus_int32 silk_SUB_LSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
442 opus_int32 ret;
443 ops_count += 1;
444 ret = a - (b << shift);
445 return ret; /* shift >= 0*/
446}
447#undef silk_SUB_RSHIFT32
448static inline opus_int32 silk_SUB_RSHIFT32(opus_int32 a, opus_int32 b, opus_int32 shift){
449 opus_int32 ret;
450 ops_count += 1;
451 ret = a - (b >> shift);
452 return ret; /* shift > 0*/
453}
454
455#undef silk_RSHIFT_ROUND
456static inline opus_int32 silk_RSHIFT_ROUND(opus_int32 a, opus_int32 shift){
457 opus_int32 ret;
458 ops_count += 3;
459 ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
460 return ret;
461}
462
463#undef silk_RSHIFT_ROUND64
464static inline opus_int64 silk_RSHIFT_ROUND64(opus_int64 a, opus_int32 shift){
465 opus_int64 ret;
466 ops_count += 6;
467 ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
468 return ret;
469}
470
471#undef silk_abs_int64
472static inline opus_int64 silk_abs_int64(opus_int64 a){
473 ops_count += 1;
474 return (((a) > 0) ? (a) : -(a)); /* Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN*/
475}
476
477#undef silk_abs_int32
478static inline opus_int32 silk_abs_int32(opus_int32 a){
479 ops_count += 1;
480 return silk_abs(a);
481}
482
483
484#undef silk_min
485static silk_min(a, b){
486 ops_count += 1;
487 return (((a) < (b)) ? (a) : (b));
488}
489#undef silk_max
490static silk_max(a, b){
491 ops_count += 1;
492 return (((a) > (b)) ? (a) : (b));
493}
494#undef silk_sign
495static silk_sign(a){
496 ops_count += 1;
497 return ((a) > 0 ? 1 : ( (a) < 0 ? -1 : 0 ));
498}
499
500#undef silk_ADD16
501static inline opus_int16 silk_ADD16(opus_int16 a, opus_int16 b){
502 opus_int16 ret;
503 ops_count += 1;
504 ret = a + b;
505 return ret;
506}
507
508#undef silk_ADD32
509static inline opus_int32 silk_ADD32(opus_int32 a, opus_int32 b){
510 opus_int32 ret;
511 ops_count += 1;
512 ret = a + b;
513 return ret;
514}
515
516#undef silk_ADD64
517static inline opus_int64 silk_ADD64(opus_int64 a, opus_int64 b){
518 opus_int64 ret;
519 ops_count += 2;
520 ret = a + b;
521 return ret;
522}
523
524#undef silk_SUB16
525static inline opus_int16 silk_SUB16(opus_int16 a, opus_int16 b){
526 opus_int16 ret;
527 ops_count += 1;
528 ret = a - b;
529 return ret;
530}
531
532#undef silk_SUB32
533static inline opus_int32 silk_SUB32(opus_int32 a, opus_int32 b){
534 opus_int32 ret;
535 ops_count += 1;
536 ret = a - b;
537 return ret;
538}
539
540#undef silk_SUB64
541static inline opus_int64 silk_SUB64(opus_int64 a, opus_int64 b){
542 opus_int64 ret;
543 ops_count += 2;
544 ret = a - b;
545 return ret;
546}
547
548#undef silk_ADD_SAT16
549static inline opus_int16 silk_ADD_SAT16( opus_int16 a16, opus_int16 b16 ) {
550 opus_int16 res;
551 /* Nb will be counted in AKP_add32 and silk_SAT16*/
552 res = (opus_int16)silk_SAT16( silk_ADD32( (opus_int32)(a16), (b16) ) );
553 return res;
554}
555
556#undef silk_ADD_SAT32
557static inline opus_int32 silk_ADD_SAT32(opus_int32 a32, opus_int32 b32){
558 opus_int32 res;
559 ops_count += 1;
560 res = ((((a32) + (b32)) & 0x80000000) == 0 ? \
561 ((((a32) & (b32)) & 0x80000000) != 0 ? silk_int32_MIN : (a32)+(b32)) : \
562 ((((a32) | (b32)) & 0x80000000) == 0 ? silk_int32_MAX : (a32)+(b32)) );
563 return res;
564}
565
566#undef silk_ADD_SAT64
567static inline opus_int64 silk_ADD_SAT64( opus_int64 a64, opus_int64 b64 ) {
568 opus_int64 res;
569 ops_count += 1;
570 res = ((((a64) + (b64)) & 0x8000000000000000LL) == 0 ? \
571 ((((a64) & (b64)) & 0x8000000000000000LL) != 0 ? silk_int64_MIN : (a64)+(b64)) : \
572 ((((a64) | (b64)) & 0x8000000000000000LL) == 0 ? silk_int64_MAX : (a64)+(b64)) );
573 return res;
574}
575
576#undef silk_SUB_SAT16
577static inline opus_int16 silk_SUB_SAT16( opus_int16 a16, opus_int16 b16 ) {
578 opus_int16 res;
579 silk_assert(0);
580 /* Nb will be counted in sub-macros*/
581 res = (opus_int16)silk_SAT16( silk_SUB32( (opus_int32)(a16), (b16) ) );
582 return res;
583}
584
585#undef silk_SUB_SAT32
586static inline opus_int32 silk_SUB_SAT32( opus_int32 a32, opus_int32 b32 ) {
587 opus_int32 res;
588 ops_count += 1;
589 res = ((((a32)-(b32)) & 0x80000000) == 0 ? \
590 (( (a32) & ((b32)^0x80000000) & 0x80000000) ? silk_int32_MIN : (a32)-(b32)) : \
591 ((((a32)^0x80000000) & (b32) & 0x80000000) ? silk_int32_MAX : (a32)-(b32)) );
592 return res;
593}
594
595#undef silk_SUB_SAT64
596static inline opus_int64 silk_SUB_SAT64( opus_int64 a64, opus_int64 b64 ) {
597 opus_int64 res;
598 ops_count += 1;
599 res = ((((a64)-(b64)) & 0x8000000000000000LL) == 0 ? \
600 (( (a64) & ((b64)^0x8000000000000000LL) & 0x8000000000000000LL) ? silk_int64_MIN : (a64)-(b64)) : \
601 ((((a64)^0x8000000000000000LL) & (b64) & 0x8000000000000000LL) ? silk_int64_MAX : (a64)-(b64)) );
602
603 return res;
604}
605
606#undef silk_SMULWW
607static inline opus_int32 silk_SMULWW(opus_int32 a32, opus_int32 b32){
608 opus_int32 ret;
609 /* Nb will be counted in sub-macros*/
610 ret = silk_MLA(silk_SMULWB((a32), (b32)), (a32), silk_RSHIFT_ROUND((b32), 16));
611 return ret;
612}
613
614#undef silk_SMLAWW
615static inline opus_int32 silk_SMLAWW(opus_int32 a32, opus_int32 b32, opus_int32 c32){
616 opus_int32 ret;
617 /* Nb will be counted in sub-macros*/
618 ret = silk_MLA(silk_SMLAWB((a32), (b32), (c32)), (b32), silk_RSHIFT_ROUND((c32), 16));
619 return ret;
620}
621
622#undef silk_min_int
623static inline opus_int silk_min_int(opus_int a, opus_int b)
624{
625 ops_count += 1;
626 return (((a) < (b)) ? (a) : (b));
627}
628
629#undef silk_min_16
630static inline opus_int16 silk_min_16(opus_int16 a, opus_int16 b)
631{
632 ops_count += 1;
633 return (((a) < (b)) ? (a) : (b));
634}
635#undef silk_min_32
636static inline opus_int32 silk_min_32(opus_int32 a, opus_int32 b)
637{
638 ops_count += 1;
639 return (((a) < (b)) ? (a) : (b));
640}
641#undef silk_min_64
642static inline opus_int64 silk_min_64(opus_int64 a, opus_int64 b)
643{
644 ops_count += 1;
645 return (((a) < (b)) ? (a) : (b));
646}
647
648/* silk_min() versions with typecast in the function call */
649#undef silk_max_int
650static inline opus_int silk_max_int(opus_int a, opus_int b)
651{
652 ops_count += 1;
653 return (((a) > (b)) ? (a) : (b));
654}
655#undef silk_max_16
656static inline opus_int16 silk_max_16(opus_int16 a, opus_int16 b)
657{
658 ops_count += 1;
659 return (((a) > (b)) ? (a) : (b));
660}
661#undef silk_max_32
662static inline opus_int32 silk_max_32(opus_int32 a, opus_int32 b)
663{
664 ops_count += 1;
665 return (((a) > (b)) ? (a) : (b));
666}
667
668#undef silk_max_64
669static inline opus_int64 silk_max_64(opus_int64 a, opus_int64 b)
670{
671 ops_count += 1;
672 return (((a) > (b)) ? (a) : (b));
673}
674
675
676#undef silk_LIMIT_int
677static inline opus_int silk_LIMIT_int(opus_int a, opus_int limit1, opus_int limit2)
678{
679 opus_int ret;
680 ops_count += 6;
681
682 ret = ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
683 : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))));
684
685 return(ret);
686}
687
688#undef silk_LIMIT_16
689static inline opus_int16 silk_LIMIT_16(opus_int16 a, opus_int16 limit1, opus_int16 limit2)
690{
691 opus_int16 ret;
692 ops_count += 6;
693
694 ret = ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
695 : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))));
696
697return(ret);
698}
699
700
701#undef silk_LIMIT_32
702static inline opus_int silk_LIMIT_32(opus_int32 a, opus_int32 limit1, opus_int32 limit2)
703{
704 opus_int32 ret;
705 ops_count += 6;
706
707 ret = ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
708 : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))));
709 return(ret);
710}
711
712#else
713#define varDefine
714#define silk_SaveCount()
715
716#endif
717#endif
718
diff --git a/lib/rbcodec/codecs/libopus/silk/MacroDebug.h b/lib/rbcodec/codecs/libopus/silk/MacroDebug.h
new file mode 100644
index 0000000000..ecd90bc4de
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/MacroDebug.h
@@ -0,0 +1,952 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Copyright (C) 2012 Xiph.Org Foundation
4Redistribution and use in source and binary forms, with or without
5modification, are permitted provided that the following conditions
6are met:
7- Redistributions of source code must retain the above copyright notice,
8this list of conditions and the following disclaimer.
9- Redistributions in binary form must reproduce the above copyright
10notice, this list of conditions and the following disclaimer in the
11documentation and/or other materials provided with the distribution.
12- Neither the name of Internet Society, IETF or IETF Trust, nor the
13names of specific contributors, may be used to endorse or promote
14products derived from this software without specific prior written
15permission.
16THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
17AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26POSSIBILITY OF SUCH DAMAGE.
27***********************************************************************/
28
29#ifndef MACRO_DEBUG_H
30#define MACRO_DEBUG_H
31
32/* Redefine macro functions with extensive assertion in DEBUG mode.
33 As functions can't be undefined, this file can't work with SigProcFIX_MacroCount.h */
34
35#if ( defined (FIXED_DEBUG) || ( 0 && defined (_DEBUG) ) ) && !defined (silk_MACRO_COUNT)
36
37#undef silk_ADD16
38#define silk_ADD16(a,b) silk_ADD16_((a), (b), __FILE__, __LINE__)
39static inline opus_int16 silk_ADD16_(opus_int16 a, opus_int16 b, char *file, int line){
40 opus_int16 ret;
41
42 ret = a + b;
43 if ( ret != silk_ADD_SAT16( a, b ) )
44 {
45 fprintf (stderr, "silk_ADD16(%d, %d) in %s: line %d\n", a, b, file, line);
46#ifdef FIXED_DEBUG_ASSERT
47 silk_assert( 0 );
48#endif
49 }
50 return ret;
51}
52
53#undef silk_ADD32
54#define silk_ADD32(a,b) silk_ADD32_((a), (b), __FILE__, __LINE__)
55static inline opus_int32 silk_ADD32_(opus_int32 a, opus_int32 b, char *file, int line){
56 opus_int32 ret;
57
58 ret = a + b;
59 if ( ret != silk_ADD_SAT32( a, b ) )
60 {
61 fprintf (stderr, "silk_ADD32(%d, %d) in %s: line %d\n", a, b, file, line);
62#ifdef FIXED_DEBUG_ASSERT
63 silk_assert( 0 );
64#endif
65 }
66 return ret;
67}
68
69#undef silk_ADD64
70#define silk_ADD64(a,b) silk_ADD64_((a), (b), __FILE__, __LINE__)
71static inline opus_int64 silk_ADD64_(opus_int64 a, opus_int64 b, char *file, int line){
72 opus_int64 ret;
73
74 ret = a + b;
75 if ( ret != silk_ADD_SAT64( a, b ) )
76 {
77 fprintf (stderr, "silk_ADD64(%lld, %lld) in %s: line %d\n", (long long)a, (long long)b, file, line);
78#ifdef FIXED_DEBUG_ASSERT
79 silk_assert( 0 );
80#endif
81 }
82 return ret;
83}
84
85#undef silk_SUB16
86#define silk_SUB16(a,b) silk_SUB16_((a), (b), __FILE__, __LINE__)
87static inline opus_int16 silk_SUB16_(opus_int16 a, opus_int16 b, char *file, int line){
88 opus_int16 ret;
89
90 ret = a - b;
91 if ( ret != silk_SUB_SAT16( a, b ) )
92 {
93 fprintf (stderr, "silk_SUB16(%d, %d) in %s: line %d\n", a, b, file, line);
94#ifdef FIXED_DEBUG_ASSERT
95 silk_assert( 0 );
96#endif
97 }
98 return ret;
99}
100
101#undef silk_SUB32
102#define silk_SUB32(a,b) silk_SUB32_((a), (b), __FILE__, __LINE__)
103static inline opus_int32 silk_SUB32_(opus_int32 a, opus_int32 b, char *file, int line){
104 opus_int32 ret;
105
106 ret = a - b;
107 if ( ret != silk_SUB_SAT32( a, b ) )
108 {
109 fprintf (stderr, "silk_SUB32(%d, %d) in %s: line %d\n", a, b, file, line);
110#ifdef FIXED_DEBUG_ASSERT
111 silk_assert( 0 );
112#endif
113 }
114 return ret;
115}
116
117#undef silk_SUB64
118#define silk_SUB64(a,b) silk_SUB64_((a), (b), __FILE__, __LINE__)
119static inline opus_int64 silk_SUB64_(opus_int64 a, opus_int64 b, char *file, int line){
120 opus_int64 ret;
121
122 ret = a - b;
123 if ( ret != silk_SUB_SAT64( a, b ) )
124 {
125 fprintf (stderr, "silk_SUB64(%lld, %lld) in %s: line %d\n", (long long)a, (long long)b, file, line);
126#ifdef FIXED_DEBUG_ASSERT
127 silk_assert( 0 );
128#endif
129 }
130 return ret;
131}
132
133#undef silk_ADD_SAT16
134#define silk_ADD_SAT16(a,b) silk_ADD_SAT16_((a), (b), __FILE__, __LINE__)
135static inline opus_int16 silk_ADD_SAT16_( opus_int16 a16, opus_int16 b16, char *file, int line) {
136 opus_int16 res;
137 res = (opus_int16)silk_SAT16( silk_ADD32( (opus_int32)(a16), (b16) ) );
138 if ( res != silk_SAT16( (opus_int32)a16 + (opus_int32)b16 ) )
139 {
140 fprintf (stderr, "silk_ADD_SAT16(%d, %d) in %s: line %d\n", a16, b16, file, line);
141#ifdef FIXED_DEBUG_ASSERT
142 silk_assert( 0 );
143#endif
144 }
145 return res;
146}
147
148#undef silk_ADD_SAT32
149#define silk_ADD_SAT32(a,b) silk_ADD_SAT32_((a), (b), __FILE__, __LINE__)
150static inline opus_int32 silk_ADD_SAT32_(opus_int32 a32, opus_int32 b32, char *file, int line){
151 opus_int32 res;
152 res = ((((opus_uint32)(a32) + (opus_uint32)(b32)) & 0x80000000) == 0 ? \
153 ((((a32) & (b32)) & 0x80000000) != 0 ? silk_int32_MIN : (a32)+(b32)) : \
154 ((((a32) | (b32)) & 0x80000000) == 0 ? silk_int32_MAX : (a32)+(b32)) );
155 if ( res != silk_SAT32( (opus_int64)a32 + (opus_int64)b32 ) )
156 {
157 fprintf (stderr, "silk_ADD_SAT32(%d, %d) in %s: line %d\n", a32, b32, file, line);
158#ifdef FIXED_DEBUG_ASSERT
159 silk_assert( 0 );
160#endif
161 }
162 return res;
163}
164
165#undef silk_ADD_SAT64
166#define silk_ADD_SAT64(a,b) silk_ADD_SAT64_((a), (b), __FILE__, __LINE__)
167static inline opus_int64 silk_ADD_SAT64_( opus_int64 a64, opus_int64 b64, char *file, int line) {
168 opus_int64 res;
169 int fail = 0;
170 res = ((((a64) + (b64)) & 0x8000000000000000LL) == 0 ? \
171 ((((a64) & (b64)) & 0x8000000000000000LL) != 0 ? silk_int64_MIN : (a64)+(b64)) : \
172 ((((a64) | (b64)) & 0x8000000000000000LL) == 0 ? silk_int64_MAX : (a64)+(b64)) );
173 if( res != a64 + b64 ) {
174 /* Check that we saturated to the correct extreme value */
175 if ( !(( res == silk_int64_MAX && ( ( a64 >> 1 ) + ( b64 >> 1 ) > ( silk_int64_MAX >> 3 ) ) ) ||
176 ( res == silk_int64_MIN && ( ( a64 >> 1 ) + ( b64 >> 1 ) < ( silk_int64_MIN >> 3 ) ) ) ) )
177 {
178 fail = 1;
179 }
180 } else {
181 /* Saturation not necessary */
182 fail = res != a64 + b64;
183 }
184 if ( fail )
185 {
186 fprintf (stderr, "silk_ADD_SAT64(%lld, %lld) in %s: line %d\n", (long long)a64, (long long)b64, file, line);
187#ifdef FIXED_DEBUG_ASSERT
188 silk_assert( 0 );
189#endif
190 }
191 return res;
192}
193
194#undef silk_SUB_SAT16
195#define silk_SUB_SAT16(a,b) silk_SUB_SAT16_((a), (b), __FILE__, __LINE__)
196static inline opus_int16 silk_SUB_SAT16_( opus_int16 a16, opus_int16 b16, char *file, int line ) {
197 opus_int16 res;
198 res = (opus_int16)silk_SAT16( silk_SUB32( (opus_int32)(a16), (b16) ) );
199 if ( res != silk_SAT16( (opus_int32)a16 - (opus_int32)b16 ) )
200 {
201 fprintf (stderr, "silk_SUB_SAT16(%d, %d) in %s: line %d\n", a16, b16, file, line);
202#ifdef FIXED_DEBUG_ASSERT
203 silk_assert( 0 );
204#endif
205 }
206 return res;
207}
208
209#undef silk_SUB_SAT32
210#define silk_SUB_SAT32(a,b) silk_SUB_SAT32_((a), (b), __FILE__, __LINE__)
211static inline opus_int32 silk_SUB_SAT32_( opus_int32 a32, opus_int32 b32, char *file, int line ) {
212 opus_int32 res;
213 res = ((((opus_uint32)(a32)-(opus_uint32)(b32)) & 0x80000000) == 0 ? \
214 (( (a32) & ((b32)^0x80000000) & 0x80000000) ? silk_int32_MIN : (a32)-(b32)) : \
215 ((((a32)^0x80000000) & (b32) & 0x80000000) ? silk_int32_MAX : (a32)-(b32)) );
216 if ( res != silk_SAT32( (opus_int64)a32 - (opus_int64)b32 ) )
217 {
218 fprintf (stderr, "silk_SUB_SAT32(%d, %d) in %s: line %d\n", a32, b32, file, line);
219#ifdef FIXED_DEBUG_ASSERT
220 silk_assert( 0 );
221#endif
222 }
223 return res;
224}
225
226#undef silk_SUB_SAT64
227#define silk_SUB_SAT64(a,b) silk_SUB_SAT64_((a), (b), __FILE__, __LINE__)
228static inline opus_int64 silk_SUB_SAT64_( opus_int64 a64, opus_int64 b64, char *file, int line ) {
229 opus_int64 res;
230 int fail = 0;
231 res = ((((a64)-(b64)) & 0x8000000000000000LL) == 0 ? \
232 (( (a64) & ((b64)^0x8000000000000000LL) & 0x8000000000000000LL) ? silk_int64_MIN : (a64)-(b64)) : \
233 ((((a64)^0x8000000000000000LL) & (b64) & 0x8000000000000000LL) ? silk_int64_MAX : (a64)-(b64)) );
234 if( res != a64 - b64 ) {
235 /* Check that we saturated to the correct extreme value */
236 if( !(( res == silk_int64_MAX && ( ( a64 >> 1 ) + ( b64 >> 1 ) > ( silk_int64_MAX >> 3 ) ) ) ||
237 ( res == silk_int64_MIN && ( ( a64 >> 1 ) + ( b64 >> 1 ) < ( silk_int64_MIN >> 3 ) ) ) ))
238 {
239 fail = 1;
240 }
241 } else {
242 /* Saturation not necessary */
243 fail = res != a64 - b64;
244 }
245 if ( fail )
246 {
247 fprintf (stderr, "silk_SUB_SAT64(%lld, %lld) in %s: line %d\n", (long long)a64, (long long)b64, file, line);
248#ifdef FIXED_DEBUG_ASSERT
249 silk_assert( 0 );
250#endif
251 }
252 return res;
253}
254
255#undef silk_MUL
256#define silk_MUL(a,b) silk_MUL_((a), (b), __FILE__, __LINE__)
257static inline opus_int32 silk_MUL_(opus_int32 a32, opus_int32 b32, char *file, int line){
258 opus_int32 ret;
259 opus_int64 ret64;
260 ret = a32 * b32;
261 ret64 = (opus_int64)a32 * (opus_int64)b32;
262 if ( (opus_int64)ret != ret64 )
263 {
264 fprintf (stderr, "silk_MUL(%d, %d) in %s: line %d\n", a32, b32, file, line);
265#ifdef FIXED_DEBUG_ASSERT
266 silk_assert( 0 );
267#endif
268 }
269 return ret;
270}
271
272#undef silk_MUL_uint
273#define silk_MUL_uint(a,b) silk_MUL_uint_((a), (b), __FILE__, __LINE__)
274static inline opus_uint32 silk_MUL_uint_(opus_uint32 a32, opus_uint32 b32, char *file, int line){
275 opus_uint32 ret;
276 ret = a32 * b32;
277 if ( (opus_uint64)ret != (opus_uint64)a32 * (opus_uint64)b32 )
278 {
279 fprintf (stderr, "silk_MUL_uint(%u, %u) in %s: line %d\n", a32, b32, file, line);
280#ifdef FIXED_DEBUG_ASSERT
281 silk_assert( 0 );
282#endif
283 }
284 return ret;
285}
286
287#undef silk_MLA
288#define silk_MLA(a,b,c) silk_MLA_((a), (b), (c), __FILE__, __LINE__)
289static inline opus_int32 silk_MLA_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
290 opus_int32 ret;
291 ret = a32 + b32 * c32;
292 if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (opus_int64)c32 )
293 {
294 fprintf (stderr, "silk_MLA(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
295#ifdef FIXED_DEBUG_ASSERT
296 silk_assert( 0 );
297#endif
298 }
299 return ret;
300}
301
302#undef silk_MLA_uint
303#define silk_MLA_uint(a,b,c) silk_MLA_uint_((a), (b), (c), __FILE__, __LINE__)
304static inline opus_int32 silk_MLA_uint_(opus_uint32 a32, opus_uint32 b32, opus_uint32 c32, char *file, int line){
305 opus_uint32 ret;
306 ret = a32 + b32 * c32;
307 if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (opus_int64)c32 )
308 {
309 fprintf (stderr, "silk_MLA_uint(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
310#ifdef FIXED_DEBUG_ASSERT
311 silk_assert( 0 );
312#endif
313 }
314 return ret;
315}
316
317#undef silk_SMULWB
318#define silk_SMULWB(a,b) silk_SMULWB_((a), (b), __FILE__, __LINE__)
319static inline opus_int32 silk_SMULWB_(opus_int32 a32, opus_int32 b32, char *file, int line){
320 opus_int32 ret;
321 ret = (a32 >> 16) * (opus_int32)((opus_int16)b32) + (((a32 & 0x0000FFFF) * (opus_int32)((opus_int16)b32)) >> 16);
322 if ( (opus_int64)ret != ((opus_int64)a32 * (opus_int16)b32) >> 16 )
323 {
324 fprintf (stderr, "silk_SMULWB(%d, %d) in %s: line %d\n", a32, b32, file, line);
325#ifdef FIXED_DEBUG_ASSERT
326 silk_assert( 0 );
327#endif
328 }
329 return ret;
330}
331
332#undef silk_SMLAWB
333#define silk_SMLAWB(a,b,c) silk_SMLAWB_((a), (b), (c), __FILE__, __LINE__)
334static inline opus_int32 silk_SMLAWB_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
335 opus_int32 ret;
336 ret = silk_ADD32( a32, silk_SMULWB( b32, c32 ) );
337 if ( silk_ADD32( a32, silk_SMULWB( b32, c32 ) ) != silk_ADD_SAT32( a32, silk_SMULWB( b32, c32 ) ) )
338 {
339 fprintf (stderr, "silk_SMLAWB(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
340#ifdef FIXED_DEBUG_ASSERT
341 silk_assert( 0 );
342#endif
343 }
344 return ret;
345}
346
347#undef silk_SMULWT
348#define silk_SMULWT(a,b) silk_SMULWT_((a), (b), __FILE__, __LINE__)
349static inline opus_int32 silk_SMULWT_(opus_int32 a32, opus_int32 b32, char *file, int line){
350 opus_int32 ret;
351 ret = (a32 >> 16) * (b32 >> 16) + (((a32 & 0x0000FFFF) * (b32 >> 16)) >> 16);
352 if ( (opus_int64)ret != ((opus_int64)a32 * (b32 >> 16)) >> 16 )
353 {
354 fprintf (stderr, "silk_SMULWT(%d, %d) in %s: line %d\n", a32, b32, file, line);
355#ifdef FIXED_DEBUG_ASSERT
356 silk_assert( 0 );
357#endif
358 }
359 return ret;
360}
361
362#undef silk_SMLAWT
363#define silk_SMLAWT(a,b,c) silk_SMLAWT_((a), (b), (c), __FILE__, __LINE__)
364static inline opus_int32 silk_SMLAWT_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
365 opus_int32 ret;
366 ret = a32 + ((b32 >> 16) * (c32 >> 16)) + (((b32 & 0x0000FFFF) * ((c32 >> 16)) >> 16));
367 if ( (opus_int64)ret != (opus_int64)a32 + (((opus_int64)b32 * (c32 >> 16)) >> 16) )
368 {
369 fprintf (stderr, "silk_SMLAWT(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
370#ifdef FIXED_DEBUG_ASSERT
371 silk_assert( 0 );
372#endif
373 }
374 return ret;
375}
376
377#undef silk_SMULL
378#define silk_SMULL(a,b) silk_SMULL_((a), (b), __FILE__, __LINE__)
379static inline opus_int64 silk_SMULL_(opus_int64 a64, opus_int64 b64, char *file, int line){
380 opus_int64 ret64;
381 int fail = 0;
382 ret64 = a64 * b64;
383 if( b64 != 0 ) {
384 fail = a64 != (ret64 / b64);
385 } else if( a64 != 0 ) {
386 fail = b64 != (ret64 / a64);
387 }
388 if ( fail )
389 {
390 fprintf (stderr, "silk_SMULL(%lld, %lld) in %s: line %d\n", (long long)a64, (long long)b64, file, line);
391#ifdef FIXED_DEBUG_ASSERT
392 silk_assert( 0 );
393#endif
394 }
395 return ret64;
396}
397
398/* no checking needed for silk_SMULBB */
399#undef silk_SMLABB
400#define silk_SMLABB(a,b,c) silk_SMLABB_((a), (b), (c), __FILE__, __LINE__)
401static inline opus_int32 silk_SMLABB_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
402 opus_int32 ret;
403 ret = a32 + (opus_int32)((opus_int16)b32) * (opus_int32)((opus_int16)c32);
404 if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (opus_int16)c32 )
405 {
406 fprintf (stderr, "silk_SMLABB(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
407#ifdef FIXED_DEBUG_ASSERT
408 silk_assert( 0 );
409#endif
410 }
411 return ret;
412}
413
414/* no checking needed for silk_SMULBT */
415#undef silk_SMLABT
416#define silk_SMLABT(a,b,c) silk_SMLABT_((a), (b), (c), __FILE__, __LINE__)
417static inline opus_int32 silk_SMLABT_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
418 opus_int32 ret;
419 ret = a32 + ((opus_int32)((opus_int16)b32)) * (c32 >> 16);
420 if ( (opus_int64)ret != (opus_int64)a32 + (opus_int64)b32 * (c32 >> 16) )
421 {
422 fprintf (stderr, "silk_SMLABT(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
423#ifdef FIXED_DEBUG_ASSERT
424 silk_assert( 0 );
425#endif
426 }
427 return ret;
428}
429
430/* no checking needed for silk_SMULTT */
431#undef silk_SMLATT
432#define silk_SMLATT(a,b,c) silk_SMLATT_((a), (b), (c), __FILE__, __LINE__)
433static inline opus_int32 silk_SMLATT_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
434 opus_int32 ret;
435 ret = a32 + (b32 >> 16) * (c32 >> 16);
436 if ( (opus_int64)ret != (opus_int64)a32 + (b32 >> 16) * (c32 >> 16) )
437 {
438 fprintf (stderr, "silk_SMLATT(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
439#ifdef FIXED_DEBUG_ASSERT
440 silk_assert( 0 );
441#endif
442 }
443 return ret;
444}
445
446#undef silk_SMULWW
447#define silk_SMULWW(a,b) silk_SMULWW_((a), (b), __FILE__, __LINE__)
448static inline opus_int32 silk_SMULWW_(opus_int32 a32, opus_int32 b32, char *file, int line){
449 opus_int32 ret, tmp1, tmp2;
450 opus_int64 ret64;
451 int fail = 0;
452
453 ret = silk_SMULWB( a32, b32 );
454 tmp1 = silk_RSHIFT_ROUND( b32, 16 );
455 tmp2 = silk_MUL( a32, tmp1 );
456
457 fail |= (opus_int64)tmp2 != (opus_int64) a32 * (opus_int64) tmp1;
458
459 tmp1 = ret;
460 ret = silk_ADD32( tmp1, tmp2 );
461 fail |= silk_ADD32( tmp1, tmp2 ) != silk_ADD_SAT32( tmp1, tmp2 );
462
463 ret64 = silk_RSHIFT64( silk_SMULL( a32, b32 ), 16 );
464 fail |= (opus_int64)ret != ret64;
465
466 if ( fail )
467 {
468 fprintf (stderr, "silk_SMULWT(%d, %d) in %s: line %d\n", a32, b32, file, line);
469#ifdef FIXED_DEBUG_ASSERT
470 silk_assert( 0 );
471#endif
472 }
473
474 return ret;
475}
476
477#undef silk_SMLAWW
478#define silk_SMLAWW(a,b,c) silk_SMLAWW_((a), (b), (c), __FILE__, __LINE__)
479static inline opus_int32 silk_SMLAWW_(opus_int32 a32, opus_int32 b32, opus_int32 c32, char *file, int line){
480 opus_int32 ret, tmp;
481
482 tmp = silk_SMULWW( b32, c32 );
483 ret = silk_ADD32( a32, tmp );
484 if ( ret != silk_ADD_SAT32( a32, tmp ) )
485 {
486 fprintf (stderr, "silk_SMLAWW(%d, %d, %d) in %s: line %d\n", a32, b32, c32, file, line);
487#ifdef FIXED_DEBUG_ASSERT
488 silk_assert( 0 );
489#endif
490 }
491 return ret;
492}
493
494/* Multiply-accumulate macros that allow overflow in the addition (ie, no asserts in debug mode) */
495#undef silk_MLA_ovflw
496#define silk_MLA_ovflw(a32, b32, c32) ((a32) + ((b32) * (c32)))
497#undef silk_SMLABB_ovflw
498#define silk_SMLABB_ovflw(a32, b32, c32) ((a32) + ((opus_int32)((opus_int16)(b32))) * (opus_int32)((opus_int16)(c32)))
499
500/* no checking needed for silk_SMULL
501 no checking needed for silk_SMLAL
502 no checking needed for silk_SMLALBB
503 no checking needed for SigProcFIX_CLZ16
504 no checking needed for SigProcFIX_CLZ32*/
505
506#undef silk_DIV32
507#define silk_DIV32(a,b) silk_DIV32_((a), (b), __FILE__, __LINE__)
508static inline opus_int32 silk_DIV32_(opus_int32 a32, opus_int32 b32, char *file, int line){
509 if ( b32 == 0 )
510 {
511 fprintf (stderr, "silk_DIV32(%d, %d) in %s: line %d\n", a32, b32, file, line);
512#ifdef FIXED_DEBUG_ASSERT
513 silk_assert( 0 );
514#endif
515 }
516 return a32 / b32;
517}
518
519#undef silk_DIV32_16
520#define silk_DIV32_16(a,b) silk_DIV32_16_((a), (b), __FILE__, __LINE__)
521static inline opus_int32 silk_DIV32_16_(opus_int32 a32, opus_int32 b32, char *file, int line){
522 int fail = 0;
523 fail |= b32 == 0;
524 fail |= b32 > silk_int16_MAX;
525 fail |= b32 < silk_int16_MIN;
526 if ( fail )
527 {
528 fprintf (stderr, "silk_DIV32_16(%d, %d) in %s: line %d\n", a32, b32, file, line);
529#ifdef FIXED_DEBUG_ASSERT
530 silk_assert( 0 );
531#endif
532 }
533 return a32 / b32;
534}
535
536/* no checking needed for silk_SAT8
537 no checking needed for silk_SAT16
538 no checking needed for silk_SAT32
539 no checking needed for silk_POS_SAT32
540 no checking needed for silk_ADD_POS_SAT8
541 no checking needed for silk_ADD_POS_SAT16
542 no checking needed for silk_ADD_POS_SAT32
543 no checking needed for silk_ADD_POS_SAT64 */
544
545#undef silk_LSHIFT8
546#define silk_LSHIFT8(a,b) silk_LSHIFT8_((a), (b), __FILE__, __LINE__)
547static inline opus_int8 silk_LSHIFT8_(opus_int8 a, opus_int32 shift, char *file, int line){
548 opus_int8 ret;
549 int fail = 0;
550 ret = a << shift;
551 fail |= shift < 0;
552 fail |= shift >= 8;
553 fail |= (opus_int64)ret != ((opus_int64)a) << shift;
554 if ( fail )
555 {
556 fprintf (stderr, "silk_LSHIFT8(%d, %d) in %s: line %d\n", a, shift, file, line);
557#ifdef FIXED_DEBUG_ASSERT
558 silk_assert( 0 );
559#endif
560 }
561 return ret;
562}
563
564#undef silk_LSHIFT16
565#define silk_LSHIFT16(a,b) silk_LSHIFT16_((a), (b), __FILE__, __LINE__)
566static inline opus_int16 silk_LSHIFT16_(opus_int16 a, opus_int32 shift, char *file, int line){
567 opus_int16 ret;
568 int fail = 0;
569 ret = a << shift;
570 fail |= shift < 0;
571 fail |= shift >= 16;
572 fail |= (opus_int64)ret != ((opus_int64)a) << shift;
573 if ( fail )
574 {
575 fprintf (stderr, "silk_LSHIFT16(%d, %d) in %s: line %d\n", a, shift, file, line);
576#ifdef FIXED_DEBUG_ASSERT
577 silk_assert( 0 );
578#endif
579 }
580 return ret;
581}
582
583#undef silk_LSHIFT32
584#define silk_LSHIFT32(a,b) silk_LSHIFT32_((a), (b), __FILE__, __LINE__)
585static inline opus_int32 silk_LSHIFT32_(opus_int32 a, opus_int32 shift, char *file, int line){
586 opus_int32 ret;
587 int fail = 0;
588 ret = a << shift;
589 fail |= shift < 0;
590 fail |= shift >= 32;
591 fail |= (opus_int64)ret != ((opus_int64)a) << shift;
592 if ( fail )
593 {
594 fprintf (stderr, "silk_LSHIFT32(%d, %d) in %s: line %d\n", a, shift, file, line);
595#ifdef FIXED_DEBUG_ASSERT
596 silk_assert( 0 );
597#endif
598 }
599 return ret;
600}
601
602#undef silk_LSHIFT64
603#define silk_LSHIFT64(a,b) silk_LSHIFT64_((a), (b), __FILE__, __LINE__)
604static inline opus_int64 silk_LSHIFT64_(opus_int64 a, opus_int shift, char *file, int line){
605 opus_int64 ret;
606 int fail = 0;
607 ret = a << shift;
608 fail |= shift < 0;
609 fail |= shift >= 64;
610 fail |= (ret>>shift) != ((opus_int64)a);
611 if ( fail )
612 {
613 fprintf (stderr, "silk_LSHIFT64(%lld, %d) in %s: line %d\n", (long long)a, shift, file, line);
614#ifdef FIXED_DEBUG_ASSERT
615 silk_assert( 0 );
616#endif
617 }
618 return ret;
619}
620
621#undef silk_LSHIFT_ovflw
622#define silk_LSHIFT_ovflw(a,b) silk_LSHIFT_ovflw_((a), (b), __FILE__, __LINE__)
623static inline opus_int32 silk_LSHIFT_ovflw_(opus_int32 a, opus_int32 shift, char *file, int line){
624 if ( (shift < 0) || (shift >= 32) ) /* no check for overflow */
625 {
626 fprintf (stderr, "silk_LSHIFT_ovflw(%d, %d) in %s: line %d\n", a, shift, file, line);
627#ifdef FIXED_DEBUG_ASSERT
628 silk_assert( 0 );
629#endif
630 }
631 return a << shift;
632}
633
634#undef silk_LSHIFT_uint
635#define silk_LSHIFT_uint(a,b) silk_LSHIFT_uint_((a), (b), __FILE__, __LINE__)
636static inline opus_uint32 silk_LSHIFT_uint_(opus_uint32 a, opus_int32 shift, char *file, int line){
637 opus_uint32 ret;
638 ret = a << shift;
639 if ( (shift < 0) || ((opus_int64)ret != ((opus_int64)a) << shift))
640 {
641 fprintf (stderr, "silk_LSHIFT_uint(%u, %d) in %s: line %d\n", a, shift, file, line);
642#ifdef FIXED_DEBUG_ASSERT
643 silk_assert( 0 );
644#endif
645 }
646 return ret;
647}
648
649#undef silk_RSHIFT8
650#define silk_RSHITF8(a,b) silk_RSHIFT8_((a), (b), __FILE__, __LINE__)
651static inline opus_int8 silk_RSHIFT8_(opus_int8 a, opus_int32 shift, char *file, int line){
652 if ( (shift < 0) || (shift>=8) )
653 {
654 fprintf (stderr, "silk_RSHITF8(%d, %d) in %s: line %d\n", a, shift, file, line);
655#ifdef FIXED_DEBUG_ASSERT
656 silk_assert( 0 );
657#endif
658 }
659 return a >> shift;
660}
661
662#undef silk_RSHIFT16
663#define silk_RSHITF16(a,b) silk_RSHIFT16_((a), (b), __FILE__, __LINE__)
664static inline opus_int16 silk_RSHIFT16_(opus_int16 a, opus_int32 shift, char *file, int line){
665 if ( (shift < 0) || (shift>=16) )
666 {
667 fprintf (stderr, "silk_RSHITF16(%d, %d) in %s: line %d\n", a, shift, file, line);
668#ifdef FIXED_DEBUG_ASSERT
669 silk_assert( 0 );
670#endif
671 }
672 return a >> shift;
673}
674
675#undef silk_RSHIFT32
676#define silk_RSHIFT32(a,b) silk_RSHIFT32_((a), (b), __FILE__, __LINE__)
677static inline opus_int32 silk_RSHIFT32_(opus_int32 a, opus_int32 shift, char *file, int line){
678 if ( (shift < 0) || (shift>=32) )
679 {
680 fprintf (stderr, "silk_RSHITF32(%d, %d) in %s: line %d\n", a, shift, file, line);
681#ifdef FIXED_DEBUG_ASSERT
682 silk_assert( 0 );
683#endif
684 }
685 return a >> shift;
686}
687
688#undef silk_RSHIFT64
689#define silk_RSHIFT64(a,b) silk_RSHIFT64_((a), (b), __FILE__, __LINE__)
690static inline opus_int64 silk_RSHIFT64_(opus_int64 a, opus_int64 shift, char *file, int line){
691 if ( (shift < 0) || (shift>=64) )
692 {
693 fprintf (stderr, "silk_RSHITF64(%lld, %lld) in %s: line %d\n", (long long)a, (long long)shift, file, line);
694#ifdef FIXED_DEBUG_ASSERT
695 silk_assert( 0 );
696#endif
697 }
698 return a >> shift;
699}
700
701#undef silk_RSHIFT_uint
702#define silk_RSHIFT_uint(a,b) silk_RSHIFT_uint_((a), (b), __FILE__, __LINE__)
703static inline opus_uint32 silk_RSHIFT_uint_(opus_uint32 a, opus_int32 shift, char *file, int line){
704 if ( (shift < 0) || (shift>32) )
705 {
706 fprintf (stderr, "silk_RSHIFT_uint(%u, %d) in %s: line %d\n", a, shift, file, line);
707#ifdef FIXED_DEBUG_ASSERT
708 silk_assert( 0 );
709#endif
710 }
711 return a >> shift;
712}
713
714#undef silk_ADD_LSHIFT
715#define silk_ADD_LSHIFT(a,b,c) silk_ADD_LSHIFT_((a), (b), (c), __FILE__, __LINE__)
716static inline int silk_ADD_LSHIFT_(int a, int b, int shift, char *file, int line){
717 opus_int16 ret;
718 ret = a + (b << shift);
719 if ( (shift < 0) || (shift>15) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) << shift)) )
720 {
721 fprintf (stderr, "silk_ADD_LSHIFT(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
722#ifdef FIXED_DEBUG_ASSERT
723 silk_assert( 0 );
724#endif
725 }
726 return ret; /* shift >= 0 */
727}
728
729#undef silk_ADD_LSHIFT32
730#define silk_ADD_LSHIFT32(a,b,c) silk_ADD_LSHIFT32_((a), (b), (c), __FILE__, __LINE__)
731static inline opus_int32 silk_ADD_LSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
732 opus_int32 ret;
733 ret = a + (b << shift);
734 if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) << shift)) )
735 {
736 fprintf (stderr, "silk_ADD_LSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
737#ifdef FIXED_DEBUG_ASSERT
738 silk_assert( 0 );
739#endif
740 }
741 return ret; /* shift >= 0 */
742}
743
744#undef silk_ADD_LSHIFT_uint
745#define silk_ADD_LSHIFT_uint(a,b,c) silk_ADD_LSHIFT_uint_((a), (b), (c), __FILE__, __LINE__)
746static inline opus_uint32 silk_ADD_LSHIFT_uint_(opus_uint32 a, opus_uint32 b, opus_int32 shift, char *file, int line){
747 opus_uint32 ret;
748 ret = a + (b << shift);
749 if ( (shift < 0) || (shift>32) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) << shift)) )
750 {
751 fprintf (stderr, "silk_ADD_LSHIFT_uint(%u, %u, %d) in %s: line %d\n", a, b, shift, file, line);
752#ifdef FIXED_DEBUG_ASSERT
753 silk_assert( 0 );
754#endif
755 }
756 return ret; /* shift >= 0 */
757}
758
759#undef silk_ADD_RSHIFT
760#define silk_ADD_RSHIFT(a,b,c) silk_ADD_RSHIFT_((a), (b), (c), __FILE__, __LINE__)
761static inline int silk_ADD_RSHIFT_(int a, int b, int shift, char *file, int line){
762 opus_int16 ret;
763 ret = a + (b >> shift);
764 if ( (shift < 0) || (shift>15) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) >> shift)) )
765 {
766 fprintf (stderr, "silk_ADD_RSHIFT(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
767#ifdef FIXED_DEBUG_ASSERT
768 silk_assert( 0 );
769#endif
770 }
771 return ret; /* shift > 0 */
772}
773
774#undef silk_ADD_RSHIFT32
775#define silk_ADD_RSHIFT32(a,b,c) silk_ADD_RSHIFT32_((a), (b), (c), __FILE__, __LINE__)
776static inline opus_int32 silk_ADD_RSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
777 opus_int32 ret;
778 ret = a + (b >> shift);
779 if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) >> shift)) )
780 {
781 fprintf (stderr, "silk_ADD_RSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
782#ifdef FIXED_DEBUG_ASSERT
783 silk_assert( 0 );
784#endif
785 }
786 return ret; /* shift > 0 */
787}
788
789#undef silk_ADD_RSHIFT_uint
790#define silk_ADD_RSHIFT_uint(a,b,c) silk_ADD_RSHIFT_uint_((a), (b), (c), __FILE__, __LINE__)
791static inline opus_uint32 silk_ADD_RSHIFT_uint_(opus_uint32 a, opus_uint32 b, opus_int32 shift, char *file, int line){
792 opus_uint32 ret;
793 ret = a + (b >> shift);
794 if ( (shift < 0) || (shift>32) || ((opus_int64)ret != (opus_int64)a + (((opus_int64)b) >> shift)) )
795 {
796 fprintf (stderr, "silk_ADD_RSHIFT_uint(%u, %u, %d) in %s: line %d\n", a, b, shift, file, line);
797#ifdef FIXED_DEBUG_ASSERT
798 silk_assert( 0 );
799#endif
800 }
801 return ret; /* shift > 0 */
802}
803
804#undef silk_SUB_LSHIFT32
805#define silk_SUB_LSHIFT32(a,b,c) silk_SUB_LSHIFT32_((a), (b), (c), __FILE__, __LINE__)
806static inline opus_int32 silk_SUB_LSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
807 opus_int32 ret;
808 ret = a - (b << shift);
809 if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a - (((opus_int64)b) << shift)) )
810 {
811 fprintf (stderr, "silk_SUB_LSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
812#ifdef FIXED_DEBUG_ASSERT
813 silk_assert( 0 );
814#endif
815 }
816 return ret; /* shift >= 0 */
817}
818
819#undef silk_SUB_RSHIFT32
820#define silk_SUB_RSHIFT32(a,b,c) silk_SUB_RSHIFT32_((a), (b), (c), __FILE__, __LINE__)
821static inline opus_int32 silk_SUB_RSHIFT32_(opus_int32 a, opus_int32 b, opus_int32 shift, char *file, int line){
822 opus_int32 ret;
823 ret = a - (b >> shift);
824 if ( (shift < 0) || (shift>31) || ((opus_int64)ret != (opus_int64)a - (((opus_int64)b) >> shift)) )
825 {
826 fprintf (stderr, "silk_SUB_RSHIFT32(%d, %d, %d) in %s: line %d\n", a, b, shift, file, line);
827#ifdef FIXED_DEBUG_ASSERT
828 silk_assert( 0 );
829#endif
830 }
831 return ret; /* shift > 0 */
832}
833
834#undef silk_RSHIFT_ROUND
835#define silk_RSHIFT_ROUND(a,b) silk_RSHIFT_ROUND_((a), (b), __FILE__, __LINE__)
836static inline opus_int32 silk_RSHIFT_ROUND_(opus_int32 a, opus_int32 shift, char *file, int line){
837 opus_int32 ret;
838 ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
839 /* the marco definition can't handle a shift of zero */
840 if ( (shift <= 0) || (shift>31) || ((opus_int64)ret != ((opus_int64)a + ((opus_int64)1 << (shift - 1))) >> shift) )
841 {
842 fprintf (stderr, "silk_RSHIFT_ROUND(%d, %d) in %s: line %d\n", a, shift, file, line);
843#ifdef FIXED_DEBUG_ASSERT
844 silk_assert( 0 );
845#endif
846 }
847 return ret;
848}
849
850#undef silk_RSHIFT_ROUND64
851#define silk_RSHIFT_ROUND64(a,b) silk_RSHIFT_ROUND64_((a), (b), __FILE__, __LINE__)
852static inline opus_int64 silk_RSHIFT_ROUND64_(opus_int64 a, opus_int32 shift, char *file, int line){
853 opus_int64 ret;
854 /* the marco definition can't handle a shift of zero */
855 if ( (shift <= 0) || (shift>=64) )
856 {
857 fprintf (stderr, "silk_RSHIFT_ROUND64(%lld, %d) in %s: line %d\n", (long long)a, shift, file, line);
858#ifdef FIXED_DEBUG_ASSERT
859 silk_assert( 0 );
860#endif
861 }
862 ret = shift == 1 ? (a >> 1) + (a & 1) : ((a >> (shift - 1)) + 1) >> 1;
863 return ret;
864}
865
866/* silk_abs is used on floats also, so doesn't work... */
867/*#undef silk_abs
868static inline opus_int32 silk_abs(opus_int32 a){
869 silk_assert(a != 0x80000000);
870 return (((a) > 0) ? (a) : -(a)); // Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN
871}*/
872
873#undef silk_abs_int64
874#define silk_abs_int64(a) silk_abs_int64_((a), __FILE__, __LINE__)
875static inline opus_int64 silk_abs_int64_(opus_int64 a, char *file, int line){
876 if ( a == silk_int64_MIN )
877 {
878 fprintf (stderr, "silk_abs_int64(%lld) in %s: line %d\n", (long long)a, file, line);
879#ifdef FIXED_DEBUG_ASSERT
880 silk_assert( 0 );
881#endif
882 }
883 return (((a) > 0) ? (a) : -(a)); /* Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN */
884}
885
886#undef silk_abs_int32
887#define silk_abs_int32(a) silk_abs_int32_((a), __FILE__, __LINE__)
888static inline opus_int32 silk_abs_int32_(opus_int32 a, char *file, int line){
889 if ( a == silk_int32_MIN )
890 {
891 fprintf (stderr, "silk_abs_int32(%d) in %s: line %d\n", a, file, line);
892#ifdef FIXED_DEBUG_ASSERT
893 silk_assert( 0 );
894#endif
895 }
896 return silk_abs(a);
897}
898
899#undef silk_CHECK_FIT8
900#define silk_CHECK_FIT8(a) silk_CHECK_FIT8_((a), __FILE__, __LINE__)
901static inline opus_int8 silk_CHECK_FIT8_( opus_int64 a, char *file, int line ){
902 opus_int8 ret;
903 ret = (opus_int8)a;
904 if ( (opus_int64)ret != a )
905 {
906 fprintf (stderr, "silk_CHECK_FIT8(%lld) in %s: line %d\n", (long long)a, file, line);
907#ifdef FIXED_DEBUG_ASSERT
908 silk_assert( 0 );
909#endif
910 }
911 return( ret );
912}
913
914#undef silk_CHECK_FIT16
915#define silk_CHECK_FIT16(a) silk_CHECK_FIT16_((a), __FILE__, __LINE__)
916static inline opus_int16 silk_CHECK_FIT16_( opus_int64 a, char *file, int line ){
917 opus_int16 ret;
918 ret = (opus_int16)a;
919 if ( (opus_int64)ret != a )
920 {
921 fprintf (stderr, "silk_CHECK_FIT16(%lld) in %s: line %d\n", (long long)a, file, line);
922#ifdef FIXED_DEBUG_ASSERT
923 silk_assert( 0 );
924#endif
925 }
926 return( ret );
927}
928
929#undef silk_CHECK_FIT32
930#define silk_CHECK_FIT32(a) silk_CHECK_FIT32_((a), __FILE__, __LINE__)
931static inline opus_int32 silk_CHECK_FIT32_( opus_int64 a, char *file, int line ){
932 opus_int32 ret;
933 ret = (opus_int32)a;
934 if ( (opus_int64)ret != a )
935 {
936 fprintf (stderr, "silk_CHECK_FIT32(%lld) in %s: line %d\n", (long long)a, file, line);
937#ifdef FIXED_DEBUG_ASSERT
938 silk_assert( 0 );
939#endif
940 }
941 return( ret );
942}
943
944/* no checking for silk_NSHIFT_MUL_32_32
945 no checking for silk_NSHIFT_MUL_16_16
946 no checking needed for silk_min
947 no checking needed for silk_max
948 no checking needed for silk_sign
949*/
950
951#endif
952#endif /* MACRO_DEBUG_H */
diff --git a/lib/rbcodec/codecs/libopus/silk/NLSF2A.c b/lib/rbcodec/codecs/libopus/silk/NLSF2A.c
new file mode 100644
index 0000000000..ffc2a96939
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/NLSF2A.c
@@ -0,0 +1,178 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32/* conversion between prediction filter coefficients and LSFs */
33/* order should be even */
34/* a piecewise linear approximation maps LSF <-> cos(LSF) */
35/* therefore the result is not accurate LSFs, but the two */
36/* functions are accurate inverses of each other */
37
38#include "SigProc_FIX.h"
39#include "tables.h"
40
41#define QA 16
42
43/* helper function for NLSF2A(..) */
44static inline void silk_NLSF2A_find_poly(
45 opus_int32 *out, /* O intermediate polynomial, QA [dd+1] */
46 const opus_int32 *cLSF, /* I vector of interleaved 2*cos(LSFs), QA [d] */
47 opus_int dd /* I polynomial order (= 1/2 * filter order) */
48)
49{
50 opus_int k, n;
51 opus_int32 ftmp;
52
53 out[0] = silk_LSHIFT( 1, QA );
54 out[1] = -cLSF[0];
55 for( k = 1; k < dd; k++ ) {
56 ftmp = cLSF[2*k]; /* QA*/
57 out[k+1] = silk_LSHIFT( out[k-1], 1 ) - (opus_int32)silk_RSHIFT_ROUND64( silk_SMULL( ftmp, out[k] ), QA );
58 for( n = k; n > 1; n-- ) {
59 out[n] += out[n-2] - (opus_int32)silk_RSHIFT_ROUND64( silk_SMULL( ftmp, out[n-1] ), QA );
60 }
61 out[1] -= ftmp;
62 }
63}
64
65/* compute whitening filter coefficients from normalized line spectral frequencies */
66void silk_NLSF2A(
67 opus_int16 *a_Q12, /* O monic whitening filter coefficients in Q12, [ d ] */
68 const opus_int16 *NLSF, /* I normalized line spectral frequencies in Q15, [ d ] */
69 const opus_int d /* I filter order (should be even) */
70)
71{
72 /* This ordering was found to maximize quality. It improves numerical accuracy of
73 silk_NLSF2A_find_poly() compared to "standard" ordering. */
74 static const unsigned char ordering16[16] = {
75 0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1
76 };
77 static const unsigned char ordering10[10] = {
78 0, 9, 6, 3, 4, 5, 8, 1, 2, 7
79 };
80 const unsigned char *ordering;
81 opus_int k, i, dd;
82 opus_int32 cos_LSF_QA[ SILK_MAX_ORDER_LPC ];
83 opus_int32 P[ SILK_MAX_ORDER_LPC / 2 + 1 ], Q[ SILK_MAX_ORDER_LPC / 2 + 1 ];
84 opus_int32 Ptmp, Qtmp, f_int, f_frac, cos_val, delta;
85 opus_int32 a32_QA1[ SILK_MAX_ORDER_LPC ];
86 opus_int32 maxabs, absval, idx=0, sc_Q16;
87
88 silk_assert( LSF_COS_TAB_SZ_FIX == 128 );
89 silk_assert( d==10||d==16 );
90
91 /* convert LSFs to 2*cos(LSF), using piecewise linear curve from table */
92 ordering = d == 16 ? ordering16 : ordering10;
93 for( k = 0; k < d; k++ ) {
94 silk_assert(NLSF[k] >= 0 );
95
96 /* f_int on a scale 0-127 (rounded down) */
97 f_int = silk_RSHIFT( NLSF[k], 15 - 7 );
98
99 /* f_frac, range: 0..255 */
100 f_frac = NLSF[k] - silk_LSHIFT( f_int, 15 - 7 );
101
102 silk_assert(f_int >= 0);
103 silk_assert(f_int < LSF_COS_TAB_SZ_FIX );
104
105 /* Read start and end value from table */
106 cos_val = silk_LSFCosTab_FIX_Q12[ f_int ]; /* Q12 */
107 delta = silk_LSFCosTab_FIX_Q12[ f_int + 1 ] - cos_val; /* Q12, with a range of 0..200 */
108
109 /* Linear interpolation */
110 cos_LSF_QA[ordering[k]] = silk_RSHIFT_ROUND( silk_LSHIFT( cos_val, 8 ) + silk_MUL( delta, f_frac ), 20 - QA ); /* QA */
111 }
112
113 dd = silk_RSHIFT( d, 1 );
114
115 /* generate even and odd polynomials using convolution */
116 silk_NLSF2A_find_poly( P, &cos_LSF_QA[ 0 ], dd );
117 silk_NLSF2A_find_poly( Q, &cos_LSF_QA[ 1 ], dd );
118
119 /* convert even and odd polynomials to opus_int32 Q12 filter coefs */
120 for( k = 0; k < dd; k++ ) {
121 Ptmp = P[ k+1 ] + P[ k ];
122 Qtmp = Q[ k+1 ] - Q[ k ];
123
124 /* the Ptmp and Qtmp values at this stage need to fit in int32 */
125 a32_QA1[ k ] = -Qtmp - Ptmp; /* QA+1 */
126 a32_QA1[ d-k-1 ] = Qtmp - Ptmp; /* QA+1 */
127 }
128
129 /* Limit the maximum absolute value of the prediction coefficients, so that they'll fit in int16 */
130 for( i = 0; i < 10; i++ ) {
131 /* Find maximum absolute value and its index */
132 maxabs = 0;
133 for( k = 0; k < d; k++ ) {
134 absval = silk_abs( a32_QA1[k] );
135 if( absval > maxabs ) {
136 maxabs = absval;
137 idx = k;
138 }
139 }
140 maxabs = silk_RSHIFT_ROUND( maxabs, QA + 1 - 12 ); /* QA+1 -> Q12 */
141
142 if( maxabs > silk_int16_MAX ) {
143 /* Reduce magnitude of prediction coefficients */
144 maxabs = silk_min( maxabs, 163838 ); /* ( silk_int32_MAX >> 14 ) + silk_int16_MAX = 163838 */
145 sc_Q16 = SILK_FIX_CONST( 0.999, 16 ) - silk_DIV32( silk_LSHIFT( maxabs - silk_int16_MAX, 14 ),
146 silk_RSHIFT32( silk_MUL( maxabs, idx + 1), 2 ) );
147 silk_bwexpander_32( a32_QA1, d, sc_Q16 );
148 } else {
149 break;
150 }
151 }
152
153 if( i == 10 ) {
154 /* Reached the last iteration, clip the coefficients */
155 for( k = 0; k < d; k++ ) {
156 a_Q12[ k ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( a32_QA1[ k ], QA + 1 - 12 ) ); /* QA+1 -> Q12 */
157 a32_QA1[ k ] = silk_LSHIFT( (opus_int32)a_Q12[ k ], QA + 1 - 12 );
158 }
159 } else {
160 for( k = 0; k < d; k++ ) {
161 a_Q12[ k ] = (opus_int16)silk_RSHIFT_ROUND( a32_QA1[ k ], QA + 1 - 12 ); /* QA+1 -> Q12 */
162 }
163 }
164
165 for( i = 0; i < MAX_LPC_STABILIZE_ITERATIONS; i++ ) {
166 if( silk_LPC_inverse_pred_gain( a_Q12, d ) < SILK_FIX_CONST( 1.0 / MAX_PREDICTION_POWER_GAIN, 30 ) ) {
167 /* Prediction coefficients are (too close to) unstable; apply bandwidth expansion */
168 /* on the unscaled coefficients, convert to Q12 and measure again */
169 silk_bwexpander_32( a32_QA1, d, 65536 - silk_LSHIFT( 2, i ) );
170 for( k = 0; k < d; k++ ) {
171 a_Q12[ k ] = (opus_int16)silk_RSHIFT_ROUND( a32_QA1[ k ], QA + 1 - 12 ); /* QA+1 -> Q12 */
172 }
173 } else {
174 break;
175 }
176 }
177}
178
diff --git a/lib/rbcodec/codecs/libopus/silk/NLSF_VQ_weights_laroia.c b/lib/rbcodec/codecs/libopus/silk/NLSF_VQ_weights_laroia.c
new file mode 100644
index 0000000000..a89d6405ac
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/NLSF_VQ_weights_laroia.c
@@ -0,0 +1,80 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "define.h"
33#include "SigProc_FIX.h"
34
35/*
36R. Laroia, N. Phamdo and N. Farvardin, "Robust and Efficient Quantization of Speech LSP
37Parameters Using Structured Vector Quantization", Proc. IEEE Int. Conf. Acoust., Speech,
38Signal Processing, pp. 641-644, 1991.
39*/
40
41/* Laroia low complexity NLSF weights */
42void silk_NLSF_VQ_weights_laroia(
43 opus_int16 *pNLSFW_Q_OUT, /* O Pointer to input vector weights [D] */
44 const opus_int16 *pNLSF_Q15, /* I Pointer to input vector [D] */
45 const opus_int D /* I Input vector dimension (even) */
46)
47{
48 opus_int k;
49 opus_int32 tmp1_int, tmp2_int;
50
51 silk_assert( D > 0 );
52 silk_assert( ( D & 1 ) == 0 );
53
54 /* First value */
55 tmp1_int = silk_max_int( pNLSF_Q15[ 0 ], 1 );
56 tmp1_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp1_int );
57 tmp2_int = silk_max_int( pNLSF_Q15[ 1 ] - pNLSF_Q15[ 0 ], 1 );
58 tmp2_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp2_int );
59 pNLSFW_Q_OUT[ 0 ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
60 silk_assert( pNLSFW_Q_OUT[ 0 ] > 0 );
61
62 /* Main loop */
63 for( k = 1; k < D - 1; k += 2 ) {
64 tmp1_int = silk_max_int( pNLSF_Q15[ k + 1 ] - pNLSF_Q15[ k ], 1 );
65 tmp1_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp1_int );
66 pNLSFW_Q_OUT[ k ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
67 silk_assert( pNLSFW_Q_OUT[ k ] > 0 );
68
69 tmp2_int = silk_max_int( pNLSF_Q15[ k + 2 ] - pNLSF_Q15[ k + 1 ], 1 );
70 tmp2_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp2_int );
71 pNLSFW_Q_OUT[ k + 1 ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
72 silk_assert( pNLSFW_Q_OUT[ k + 1 ] > 0 );
73 }
74
75 /* Last value */
76 tmp1_int = silk_max_int( ( 1 << 15 ) - pNLSF_Q15[ D - 1 ], 1 );
77 tmp1_int = silk_DIV32_16( (opus_int32)1 << ( 15 + NLSF_W_Q ), tmp1_int );
78 pNLSFW_Q_OUT[ D - 1 ] = (opus_int16)silk_min_int( tmp1_int + tmp2_int, silk_int16_MAX );
79 silk_assert( pNLSFW_Q_OUT[ D - 1 ] > 0 );
80}
diff --git a/lib/rbcodec/codecs/libopus/silk/NLSF_decode.c b/lib/rbcodec/codecs/libopus/silk/NLSF_decode.c
new file mode 100644
index 0000000000..6c2db4fd9d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/NLSF_decode.c
@@ -0,0 +1,101 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Predictive dequantizer for NLSF residuals */
35static inline void silk_NLSF_residual_dequant( /* O Returns RD value in Q30 */
36 opus_int16 x_Q10[], /* O Output [ order ] */
37 const opus_int8 indices[], /* I Quantization indices [ order ] */
38 const opus_uint8 pred_coef_Q8[], /* I Backward predictor coefs [ order ] */
39 const opus_int quant_step_size_Q16, /* I Quantization step size */
40 const opus_int16 order /* I Number of input values */
41)
42{
43 opus_int i, out_Q10, pred_Q10;
44
45 out_Q10 = 0;
46 for( i = order-1; i >= 0; i-- ) {
47 pred_Q10 = silk_RSHIFT( silk_SMULBB( out_Q10, (opus_int16)pred_coef_Q8[ i ] ), 8 );
48 out_Q10 = silk_LSHIFT( indices[ i ], 10 );
49 if( out_Q10 > 0 ) {
50 out_Q10 = silk_SUB16( out_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
51 } else if( out_Q10 < 0 ) {
52 out_Q10 = silk_ADD16( out_Q10, SILK_FIX_CONST( NLSF_QUANT_LEVEL_ADJ, 10 ) );
53 }
54 out_Q10 = silk_SMLAWB( pred_Q10, (opus_int32)out_Q10, quant_step_size_Q16 );
55 x_Q10[ i ] = out_Q10;
56 }
57}
58
59
60/***********************/
61/* NLSF vector decoder */
62/***********************/
63void silk_NLSF_decode(
64 opus_int16 *pNLSF_Q15, /* O Quantized NLSF vector [ LPC_ORDER ] */
65 opus_int8 *NLSFIndices, /* I Codebook path vector [ LPC_ORDER + 1 ] */
66 const silk_NLSF_CB_struct *psNLSF_CB /* I Codebook object */
67)
68{
69 opus_int i;
70 opus_uint8 pred_Q8[ MAX_LPC_ORDER ];
71 opus_int16 ec_ix[ MAX_LPC_ORDER ];
72 opus_int16 res_Q10[ MAX_LPC_ORDER ];
73 opus_int16 W_tmp_QW[ MAX_LPC_ORDER ];
74 opus_int32 W_tmp_Q9, NLSF_Q15_tmp;
75 const opus_uint8 *pCB_element;
76
77 /* Decode first stage */
78 pCB_element = &psNLSF_CB->CB1_NLSF_Q8[ NLSFIndices[ 0 ] * psNLSF_CB->order ];
79 for( i = 0; i < psNLSF_CB->order; i++ ) {
80 pNLSF_Q15[ i ] = silk_LSHIFT( (opus_int16)pCB_element[ i ], 7 );
81 }
82
83 /* Unpack entropy table indices and predictor for current CB1 index */
84 silk_NLSF_unpack( ec_ix, pred_Q8, psNLSF_CB, NLSFIndices[ 0 ] );
85
86 /* Predictive residual dequantizer */
87 silk_NLSF_residual_dequant( res_Q10, &NLSFIndices[ 1 ], pred_Q8, psNLSF_CB->quantStepSize_Q16, psNLSF_CB->order );
88
89 /* Weights from codebook vector */
90 silk_NLSF_VQ_weights_laroia( W_tmp_QW, pNLSF_Q15, psNLSF_CB->order );
91
92 /* Apply inverse square-rooted weights and add to output */
93 for( i = 0; i < psNLSF_CB->order; i++ ) {
94 W_tmp_Q9 = silk_SQRT_APPROX( silk_LSHIFT( (opus_int32)W_tmp_QW[ i ], 18 - NLSF_W_Q ) );
95 NLSF_Q15_tmp = silk_ADD32( pNLSF_Q15[ i ], silk_DIV32_16( silk_LSHIFT( (opus_int32)res_Q10[ i ], 14 ), W_tmp_Q9 ) );
96 pNLSF_Q15[ i ] = (opus_int16)silk_LIMIT( NLSF_Q15_tmp, 0, 32767 );
97 }
98
99 /* NLSF stabilization */
100 silk_NLSF_stabilize( pNLSF_Q15, psNLSF_CB->deltaMin_Q15, psNLSF_CB->order );
101}
diff --git a/lib/rbcodec/codecs/libopus/silk/NLSF_stabilize.c b/lib/rbcodec/codecs/libopus/silk/NLSF_stabilize.c
new file mode 100644
index 0000000000..25ec49f4c1
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/NLSF_stabilize.c
@@ -0,0 +1,142 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32/* NLSF stabilizer: */
33/* */
34/* - Moves NLSFs futher apart if they are too close */
35/* - Moves NLSFs away from borders if they are too close */
36/* - High effort to achieve a modification with minimum */
37/* Euclidean distance to input vector */
38/* - Output are sorted NLSF coefficients */
39/* */
40
41#include "SigProc_FIX.h"
42
43/* Constant Definitions */
44#define MAX_LOOPS 20
45
46/* NLSF stabilizer, for a single input data vector */
47void silk_NLSF_stabilize(
48 opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */
49 const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */
50 const opus_int L /* I Number of NLSF parameters in the input vector */
51)
52{
53 opus_int i, I=0, k, loops;
54 opus_int16 center_freq_Q15;
55 opus_int32 diff_Q15, min_diff_Q15, min_center_Q15, max_center_Q15;
56
57 /* This is necessary to ensure an output within range of a opus_int16 */
58 silk_assert( NDeltaMin_Q15[L] >= 1 );
59
60 for( loops = 0; loops < MAX_LOOPS; loops++ ) {
61 /**************************/
62 /* Find smallest distance */
63 /**************************/
64 /* First element */
65 min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0];
66 I = 0;
67 /* Middle elements */
68 for( i = 1; i <= L-1; i++ ) {
69 diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] );
70 if( diff_Q15 < min_diff_Q15 ) {
71 min_diff_Q15 = diff_Q15;
72 I = i;
73 }
74 }
75 /* Last element */
76 diff_Q15 = ( 1 << 15 ) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] );
77 if( diff_Q15 < min_diff_Q15 ) {
78 min_diff_Q15 = diff_Q15;
79 I = L;
80 }
81
82 /***************************************************/
83 /* Now check if the smallest distance non-negative */
84 /***************************************************/
85 if( min_diff_Q15 >= 0 ) {
86 return;
87 }
88
89 if( I == 0 ) {
90 /* Move away from lower limit */
91 NLSF_Q15[0] = NDeltaMin_Q15[0];
92
93 } else if( I == L) {
94 /* Move away from higher limit */
95 NLSF_Q15[L-1] = ( 1 << 15 ) - NDeltaMin_Q15[L];
96
97 } else {
98 /* Find the lower extreme for the location of the current center frequency */
99 min_center_Q15 = 0;
100 for( k = 0; k < I; k++ ) {
101 min_center_Q15 += NDeltaMin_Q15[k];
102 }
103 min_center_Q15 += silk_RSHIFT( NDeltaMin_Q15[I], 1 );
104
105 /* Find the upper extreme for the location of the current center frequency */
106 max_center_Q15 = 1 << 15;
107 for( k = L; k > I; k-- ) {
108 max_center_Q15 -= NDeltaMin_Q15[k];
109 }
110 max_center_Q15 -= silk_RSHIFT( NDeltaMin_Q15[I], 1 );
111
112 /* Move apart, sorted by value, keeping the same center frequency */
113 center_freq_Q15 = (opus_int16)silk_LIMIT_32( silk_RSHIFT_ROUND( (opus_int32)NLSF_Q15[I-1] + (opus_int32)NLSF_Q15[I], 1 ),
114 min_center_Q15, max_center_Q15 );
115 NLSF_Q15[I-1] = center_freq_Q15 - silk_RSHIFT( NDeltaMin_Q15[I], 1 );
116 NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I];
117 }
118 }
119
120 /* Safe and simple fall back method, which is less ideal than the above */
121 if( loops == MAX_LOOPS )
122 {
123 /* Insertion sort (fast for already almost sorted arrays): */
124 /* Best case: O(n) for an already sorted array */
125 /* Worst case: O(n^2) for an inversely sorted array */
126 silk_insertion_sort_increasing_all_values_int16( &NLSF_Q15[0], L );
127
128 /* First NLSF should be no less than NDeltaMin[0] */
129 NLSF_Q15[0] = silk_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] );
130
131 /* Keep delta_min distance between the NLSFs */
132 for( i = 1; i < L; i++ )
133 NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], NLSF_Q15[i-1] + NDeltaMin_Q15[i] );
134
135 /* Last NLSF should be no higher than 1 - NDeltaMin[L] */
136 NLSF_Q15[L-1] = silk_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] );
137
138 /* Keep NDeltaMin distance between the NLSFs */
139 for( i = L-2; i >= 0; i-- )
140 NLSF_Q15[i] = silk_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] );
141 }
142}
diff --git a/lib/rbcodec/codecs/libopus/silk/NLSF_unpack.c b/lib/rbcodec/codecs/libopus/silk/NLSF_unpack.c
new file mode 100644
index 0000000000..5e059f2615
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/NLSF_unpack.c
@@ -0,0 +1,55 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Unpack predictor values and indices for entropy coding tables */
35void silk_NLSF_unpack(
36 opus_int16 ec_ix[], /* O Indices to entropy tables [ LPC_ORDER ] */
37 opus_uint8 pred_Q8[], /* O LSF predictor [ LPC_ORDER ] */
38 const silk_NLSF_CB_struct *psNLSF_CB, /* I Codebook object */
39 const opus_int CB1_index /* I Index of vector in first LSF codebook */
40)
41{
42 opus_int i;
43 opus_uint8 entry;
44 const opus_uint8 *ec_sel_ptr;
45
46 ec_sel_ptr = &psNLSF_CB->ec_sel[ CB1_index * psNLSF_CB->order / 2 ];
47 for( i = 0; i < psNLSF_CB->order; i += 2 ) {
48 entry = *ec_sel_ptr++;
49 ec_ix [ i ] = silk_SMULBB( silk_RSHIFT( entry, 1 ) & 7, 2 * NLSF_QUANT_MAX_AMPLITUDE + 1 );
50 pred_Q8[ i ] = psNLSF_CB->pred_Q8[ i + ( entry & 1 ) * ( psNLSF_CB->order - 1 ) ];
51 ec_ix [ i + 1 ] = silk_SMULBB( silk_RSHIFT( entry, 5 ) & 7, 2 * NLSF_QUANT_MAX_AMPLITUDE + 1 );
52 pred_Q8[ i + 1 ] = psNLSF_CB->pred_Q8[ i + ( silk_RSHIFT( entry, 4 ) & 1 ) * ( psNLSF_CB->order - 1 ) + 1 ];
53 }
54}
55
diff --git a/lib/rbcodec/codecs/libopus/silk/PLC.c b/lib/rbcodec/codecs/libopus/silk/PLC.c
new file mode 100644
index 0000000000..08ae5b7617
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/PLC.c
@@ -0,0 +1,423 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33#include "stack_alloc.h"
34#include "PLC.h"
35
36#define NB_ATT 2
37static const opus_int16 HARM_ATT_Q15[NB_ATT] = { 32440, 31130 }; /* 0.99, 0.95 */
38static const opus_int16 PLC_RAND_ATTENUATE_V_Q15[NB_ATT] = { 31130, 26214 }; /* 0.95, 0.8 */
39static const opus_int16 PLC_RAND_ATTENUATE_UV_Q15[NB_ATT] = { 32440, 29491 }; /* 0.99, 0.9 */
40
41static inline void silk_PLC_update(
42 silk_decoder_state *psDec, /* I/O Decoder state */
43 silk_decoder_control *psDecCtrl /* I/O Decoder control */
44);
45
46static inline void silk_PLC_conceal(
47 silk_decoder_state *psDec, /* I/O Decoder state */
48 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
49 opus_int16 frame[] /* O LPC residual signal */
50);
51
52
53void silk_PLC_Reset(
54 silk_decoder_state *psDec /* I/O Decoder state */
55)
56{
57 psDec->sPLC.pitchL_Q8 = silk_LSHIFT( psDec->frame_length, 8 - 1 );
58 psDec->sPLC.prevGain_Q16[ 0 ] = SILK_FIX_CONST( 1, 16 );
59 psDec->sPLC.prevGain_Q16[ 1 ] = SILK_FIX_CONST( 1, 16 );
60 psDec->sPLC.subfr_length = 20;
61 psDec->sPLC.nb_subfr = 2;
62}
63
64void silk_PLC(
65 silk_decoder_state *psDec, /* I/O Decoder state */
66 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
67 opus_int16 frame[], /* I/O signal */
68 opus_int lost /* I Loss flag */
69)
70{
71 /* PLC control function */
72 if( psDec->fs_kHz != psDec->sPLC.fs_kHz ) {
73 silk_PLC_Reset( psDec );
74 psDec->sPLC.fs_kHz = psDec->fs_kHz;
75 }
76
77 if( lost ) {
78 /****************************/
79 /* Generate Signal */
80 /****************************/
81 silk_PLC_conceal( psDec, psDecCtrl, frame );
82
83 psDec->lossCnt++;
84 } else {
85 /****************************/
86 /* Update state */
87 /****************************/
88 silk_PLC_update( psDec, psDecCtrl );
89 }
90}
91
92/**************************************************/
93/* Update state of PLC */
94/**************************************************/
95static inline void silk_PLC_update(
96 silk_decoder_state *psDec, /* I/O Decoder state */
97 silk_decoder_control *psDecCtrl /* I/O Decoder control */
98)
99{
100 opus_int32 LTP_Gain_Q14, temp_LTP_Gain_Q14;
101 opus_int i, j;
102 silk_PLC_struct *psPLC;
103
104 psPLC = &psDec->sPLC;
105
106 /* Update parameters used in case of packet loss */
107 psDec->prevSignalType = psDec->indices.signalType;
108 LTP_Gain_Q14 = 0;
109 if( psDec->indices.signalType == TYPE_VOICED ) {
110 /* Find the parameters for the last subframe which contains a pitch pulse */
111 for( j = 0; j * psDec->subfr_length < psDecCtrl->pitchL[ psDec->nb_subfr - 1 ]; j++ ) {
112 if( j == psDec->nb_subfr ) {
113 break;
114 }
115 temp_LTP_Gain_Q14 = 0;
116 for( i = 0; i < LTP_ORDER; i++ ) {
117 temp_LTP_Gain_Q14 += psDecCtrl->LTPCoef_Q14[ ( psDec->nb_subfr - 1 - j ) * LTP_ORDER + i ];
118 }
119 if( temp_LTP_Gain_Q14 > LTP_Gain_Q14 ) {
120 LTP_Gain_Q14 = temp_LTP_Gain_Q14;
121 silk_memcpy( psPLC->LTPCoef_Q14,
122 &psDecCtrl->LTPCoef_Q14[ silk_SMULBB( psDec->nb_subfr - 1 - j, LTP_ORDER ) ],
123 LTP_ORDER * sizeof( opus_int16 ) );
124
125 psPLC->pitchL_Q8 = silk_LSHIFT( psDecCtrl->pitchL[ psDec->nb_subfr - 1 - j ], 8 );
126 }
127 }
128
129 silk_memset( psPLC->LTPCoef_Q14, 0, LTP_ORDER * sizeof( opus_int16 ) );
130 psPLC->LTPCoef_Q14[ LTP_ORDER / 2 ] = LTP_Gain_Q14;
131
132 /* Limit LT coefs */
133 if( LTP_Gain_Q14 < V_PITCH_GAIN_START_MIN_Q14 ) {
134 opus_int scale_Q10;
135 opus_int32 tmp;
136
137 tmp = silk_LSHIFT( V_PITCH_GAIN_START_MIN_Q14, 10 );
138 scale_Q10 = silk_DIV32( tmp, silk_max( LTP_Gain_Q14, 1 ) );
139 for( i = 0; i < LTP_ORDER; i++ ) {
140 psPLC->LTPCoef_Q14[ i ] = silk_RSHIFT( silk_SMULBB( psPLC->LTPCoef_Q14[ i ], scale_Q10 ), 10 );
141 }
142 } else if( LTP_Gain_Q14 > V_PITCH_GAIN_START_MAX_Q14 ) {
143 opus_int scale_Q14;
144 opus_int32 tmp;
145
146 tmp = silk_LSHIFT( V_PITCH_GAIN_START_MAX_Q14, 14 );
147 scale_Q14 = silk_DIV32( tmp, silk_max( LTP_Gain_Q14, 1 ) );
148 for( i = 0; i < LTP_ORDER; i++ ) {
149 psPLC->LTPCoef_Q14[ i ] = silk_RSHIFT( silk_SMULBB( psPLC->LTPCoef_Q14[ i ], scale_Q14 ), 14 );
150 }
151 }
152 } else {
153 psPLC->pitchL_Q8 = silk_LSHIFT( silk_SMULBB( psDec->fs_kHz, 18 ), 8 );
154 silk_memset( psPLC->LTPCoef_Q14, 0, LTP_ORDER * sizeof( opus_int16 ));
155 }
156
157 /* Save LPC coeficients */
158 silk_memcpy( psPLC->prevLPC_Q12, psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order * sizeof( opus_int16 ) );
159 psPLC->prevLTP_scale_Q14 = psDecCtrl->LTP_scale_Q14;
160
161 /* Save last two gains */
162 silk_memcpy( psPLC->prevGain_Q16, &psDecCtrl->Gains_Q16[ psDec->nb_subfr - 2 ], 2 * sizeof( opus_int32 ) );
163
164 psPLC->subfr_length = psDec->subfr_length;
165 psPLC->nb_subfr = psDec->nb_subfr;
166}
167
168static inline void silk_PLC_conceal(
169 silk_decoder_state *psDec, /* I/O Decoder state */
170 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
171 opus_int16 frame[] /* O LPC residual signal */
172)
173{
174 opus_int i, j, k;
175 opus_int lag, idx, sLTP_buf_idx, shift1, shift2;
176 opus_int32 rand_seed, harm_Gain_Q15, rand_Gain_Q15, inv_gain_Q30;
177 opus_int32 energy1, energy2, *rand_ptr, *pred_lag_ptr;
178 opus_int32 LPC_pred_Q10, LTP_pred_Q12;
179 opus_int16 rand_scale_Q14;
180 opus_int16 *B_Q14, *exc_buf_ptr;
181 opus_int32 *sLPC_Q14_ptr;
182 VARDECL( opus_int16, exc_buf );
183 opus_int16 A_Q12[ MAX_LPC_ORDER ];
184 VARDECL( opus_int16, sLTP );
185 VARDECL( opus_int32, sLTP_Q14 );
186 silk_PLC_struct *psPLC = &psDec->sPLC;
187 opus_int32 prevGain_Q10[2];
188 SAVE_STACK;
189
190 ALLOC( exc_buf, 2*psPLC->subfr_length, opus_int16 );
191 ALLOC( sLTP, psDec->ltp_mem_length, opus_int16 );
192 ALLOC( sLTP_Q14, psDec->ltp_mem_length + psDec->frame_length, opus_int32 );
193
194 prevGain_Q10[0] = silk_RSHIFT( psPLC->prevGain_Q16[ 0 ], 6);
195 prevGain_Q10[1] = silk_RSHIFT( psPLC->prevGain_Q16[ 1 ], 6);
196
197 if( psDec->first_frame_after_reset ) {
198 silk_memset( psPLC->prevLPC_Q12, 0, sizeof( psPLC->prevLPC_Q12 ) );
199 }
200
201 /* Find random noise component */
202 /* Scale previous excitation signal */
203 exc_buf_ptr = exc_buf;
204 for( k = 0; k < 2; k++ ) {
205 for( i = 0; i < psPLC->subfr_length; i++ ) {
206 exc_buf_ptr[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT(
207 silk_SMULWW( psDec->exc_Q14[ i + ( k + psPLC->nb_subfr - 2 ) * psPLC->subfr_length ], prevGain_Q10[ k ] ), 8 ) );
208 }
209 exc_buf_ptr += psPLC->subfr_length;
210 }
211 /* Find the subframe with lowest energy of the last two and use that as random noise generator */
212 silk_sum_sqr_shift( &energy1, &shift1, exc_buf, psPLC->subfr_length );
213 silk_sum_sqr_shift( &energy2, &shift2, &exc_buf[ psPLC->subfr_length ], psPLC->subfr_length );
214
215 if( silk_RSHIFT( energy1, shift2 ) < silk_RSHIFT( energy2, shift1 ) ) {
216 /* First sub-frame has lowest energy */
217 rand_ptr = &psDec->exc_Q14[ silk_max_int( 0, ( psPLC->nb_subfr - 1 ) * psPLC->subfr_length - RAND_BUF_SIZE ) ];
218 } else {
219 /* Second sub-frame has lowest energy */
220 rand_ptr = &psDec->exc_Q14[ silk_max_int( 0, psPLC->nb_subfr * psPLC->subfr_length - RAND_BUF_SIZE ) ];
221 }
222
223 /* Set up Gain to random noise component */
224 B_Q14 = psPLC->LTPCoef_Q14;
225 rand_scale_Q14 = psPLC->randScale_Q14;
226
227 /* Set up attenuation gains */
228 harm_Gain_Q15 = HARM_ATT_Q15[ silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
229 if( psDec->prevSignalType == TYPE_VOICED ) {
230 rand_Gain_Q15 = PLC_RAND_ATTENUATE_V_Q15[ silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
231 } else {
232 rand_Gain_Q15 = PLC_RAND_ATTENUATE_UV_Q15[ silk_min_int( NB_ATT - 1, psDec->lossCnt ) ];
233 }
234
235 /* LPC concealment. Apply BWE to previous LPC */
236 silk_bwexpander( psPLC->prevLPC_Q12, psDec->LPC_order, SILK_FIX_CONST( BWE_COEF, 16 ) );
237
238 /* Preload LPC coeficients to array on stack. Gives small performance gain */
239 silk_memcpy( A_Q12, psPLC->prevLPC_Q12, psDec->LPC_order * sizeof( opus_int16 ) );
240
241 /* First Lost frame */
242 if( psDec->lossCnt == 0 ) {
243 rand_scale_Q14 = 1 << 14;
244
245 /* Reduce random noise Gain for voiced frames */
246 if( psDec->prevSignalType == TYPE_VOICED ) {
247 for( i = 0; i < LTP_ORDER; i++ ) {
248 rand_scale_Q14 -= B_Q14[ i ];
249 }
250 rand_scale_Q14 = silk_max_16( 3277, rand_scale_Q14 ); /* 0.2 */
251 rand_scale_Q14 = (opus_int16)silk_RSHIFT( silk_SMULBB( rand_scale_Q14, psPLC->prevLTP_scale_Q14 ), 14 );
252 } else {
253 /* Reduce random noise for unvoiced frames with high LPC gain */
254 opus_int32 invGain_Q30, down_scale_Q30;
255
256 invGain_Q30 = silk_LPC_inverse_pred_gain( psPLC->prevLPC_Q12, psDec->LPC_order );
257
258 down_scale_Q30 = silk_min_32( silk_RSHIFT( (opus_int32)1 << 30, LOG2_INV_LPC_GAIN_HIGH_THRES ), invGain_Q30 );
259 down_scale_Q30 = silk_max_32( silk_RSHIFT( (opus_int32)1 << 30, LOG2_INV_LPC_GAIN_LOW_THRES ), down_scale_Q30 );
260 down_scale_Q30 = silk_LSHIFT( down_scale_Q30, LOG2_INV_LPC_GAIN_HIGH_THRES );
261
262 rand_Gain_Q15 = silk_RSHIFT( silk_SMULWB( down_scale_Q30, rand_Gain_Q15 ), 14 );
263 }
264 }
265
266 rand_seed = psPLC->rand_seed;
267 lag = silk_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );
268 sLTP_buf_idx = psDec->ltp_mem_length;
269
270 /* Rewhiten LTP state */
271 idx = psDec->ltp_mem_length - lag - psDec->LPC_order - LTP_ORDER / 2;
272 silk_assert( idx > 0 );
273 silk_LPC_analysis_filter( &sLTP[ idx ], &psDec->outBuf[ idx ], A_Q12, psDec->ltp_mem_length - idx, psDec->LPC_order );
274 /* Scale LTP state */
275 inv_gain_Q30 = silk_INVERSE32_varQ( psPLC->prevGain_Q16[ 1 ], 46 );
276 inv_gain_Q30 = silk_min( inv_gain_Q30, silk_int32_MAX >> 1 );
277 for( i = idx + psDec->LPC_order; i < psDec->ltp_mem_length; i++ ) {
278 sLTP_Q14[ i ] = silk_SMULWB( inv_gain_Q30, sLTP[ i ] );
279 }
280
281 /***************************/
282 /* LTP synthesis filtering */
283 /***************************/
284 for( k = 0; k < psDec->nb_subfr; k++ ) {
285 /* Set up pointer */
286 pred_lag_ptr = &sLTP_Q14[ sLTP_buf_idx - lag + LTP_ORDER / 2 ];
287 for( i = 0; i < psDec->subfr_length; i++ ) {
288 /* Unrolled loop */
289 /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
290 LTP_pred_Q12 = 2;
291 LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ 0 ], B_Q14[ 0 ] );
292 LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -1 ], B_Q14[ 1 ] );
293 LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -2 ], B_Q14[ 2 ] );
294 LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -3 ], B_Q14[ 3 ] );
295 LTP_pred_Q12 = silk_SMLAWB( LTP_pred_Q12, pred_lag_ptr[ -4 ], B_Q14[ 4 ] );
296 pred_lag_ptr++;
297
298 /* Generate LPC excitation */
299 rand_seed = silk_RAND( rand_seed );
300 idx = silk_RSHIFT( rand_seed, 25 ) & RAND_BUF_MASK;
301 sLTP_Q14[ sLTP_buf_idx ] = silk_LSHIFT32( silk_SMLAWB( LTP_pred_Q12, rand_ptr[ idx ], rand_scale_Q14 ), 2 );
302 sLTP_buf_idx++;
303 }
304
305 /* Gradually reduce LTP gain */
306 for( j = 0; j < LTP_ORDER; j++ ) {
307 B_Q14[ j ] = silk_RSHIFT( silk_SMULBB( harm_Gain_Q15, B_Q14[ j ] ), 15 );
308 }
309 /* Gradually reduce excitation gain */
310 rand_scale_Q14 = silk_RSHIFT( silk_SMULBB( rand_scale_Q14, rand_Gain_Q15 ), 15 );
311
312 /* Slowly increase pitch lag */
313 psPLC->pitchL_Q8 = silk_SMLAWB( psPLC->pitchL_Q8, psPLC->pitchL_Q8, PITCH_DRIFT_FAC_Q16 );
314 psPLC->pitchL_Q8 = silk_min_32( psPLC->pitchL_Q8, silk_LSHIFT( silk_SMULBB( MAX_PITCH_LAG_MS, psDec->fs_kHz ), 8 ) );
315 lag = silk_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );
316 }
317
318 /***************************/
319 /* LPC synthesis filtering */
320 /***************************/
321 sLPC_Q14_ptr = &sLTP_Q14[ psDec->ltp_mem_length - MAX_LPC_ORDER ];
322
323 /* Copy LPC state */
324 silk_memcpy( sLPC_Q14_ptr, psDec->sLPC_Q14_buf, MAX_LPC_ORDER * sizeof( opus_int32 ) );
325
326 silk_assert( psDec->LPC_order >= 10 ); /* check that unrolling works */
327 for( i = 0; i < psDec->frame_length; i++ ) {
328 /* partly unrolled */
329 /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
330 LPC_pred_Q10 = silk_RSHIFT( psDec->LPC_order, 1 );
331 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 1 ], A_Q12[ 0 ] );
332 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 2 ], A_Q12[ 1 ] );
333 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 3 ], A_Q12[ 2 ] );
334 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 4 ], A_Q12[ 3 ] );
335 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 5 ], A_Q12[ 4 ] );
336 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 6 ], A_Q12[ 5 ] );
337 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 7 ], A_Q12[ 6 ] );
338 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 8 ], A_Q12[ 7 ] );
339 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 9 ], A_Q12[ 8 ] );
340 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - 10 ], A_Q12[ 9 ] );
341 for( j = 10; j < psDec->LPC_order; j++ ) {
342 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14_ptr[ MAX_LPC_ORDER + i - j - 1 ], A_Q12[ j ] );
343 }
344
345 /* Add prediction to LPC excitation */
346 sLPC_Q14_ptr[ MAX_LPC_ORDER + i ] = silk_ADD_LSHIFT32( sLPC_Q14_ptr[ MAX_LPC_ORDER + i ], LPC_pred_Q10, 4 );
347
348 /* Scale with Gain */
349 frame[ i ] = (opus_int16)silk_SAT16( silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( sLPC_Q14_ptr[ MAX_LPC_ORDER + i ], prevGain_Q10[ 1 ] ), 8 ) ) );
350 }
351
352 /* Save LPC state */
353 silk_memcpy( psDec->sLPC_Q14_buf, &sLPC_Q14_ptr[ psDec->frame_length ], MAX_LPC_ORDER * sizeof( opus_int32 ) );
354
355 /**************************************/
356 /* Update states */
357 /**************************************/
358 psPLC->rand_seed = rand_seed;
359 psPLC->randScale_Q14 = rand_scale_Q14;
360 for( i = 0; i < MAX_NB_SUBFR; i++ ) {
361 psDecCtrl->pitchL[ i ] = lag;
362 }
363 RESTORE_STACK;
364}
365
366/* Glues concealed frames with new good recieved frames */
367void silk_PLC_glue_frames(
368 silk_decoder_state *psDec, /* I/O decoder state */
369 opus_int16 frame[], /* I/O signal */
370 opus_int length /* I length of signal */
371)
372{
373 opus_int i, energy_shift;
374 opus_int32 energy;
375 silk_PLC_struct *psPLC;
376 psPLC = &psDec->sPLC;
377
378 if( psDec->lossCnt ) {
379 /* Calculate energy in concealed residual */
380 silk_sum_sqr_shift( &psPLC->conc_energy, &psPLC->conc_energy_shift, frame, length );
381
382 psPLC->last_frame_lost = 1;
383 } else {
384 if( psDec->sPLC.last_frame_lost ) {
385 /* Calculate residual in decoded signal if last frame was lost */
386 silk_sum_sqr_shift( &energy, &energy_shift, frame, length );
387
388 /* Normalize energies */
389 if( energy_shift > psPLC->conc_energy_shift ) {
390 psPLC->conc_energy = silk_RSHIFT( psPLC->conc_energy, energy_shift - psPLC->conc_energy_shift );
391 } else if( energy_shift < psPLC->conc_energy_shift ) {
392 energy = silk_RSHIFT( energy, psPLC->conc_energy_shift - energy_shift );
393 }
394
395 /* Fade in the energy difference */
396 if( energy > psPLC->conc_energy ) {
397 opus_int32 frac_Q24, LZ;
398 opus_int32 gain_Q16, slope_Q16;
399
400 LZ = silk_CLZ32( psPLC->conc_energy );
401 LZ = LZ - 1;
402 psPLC->conc_energy = silk_LSHIFT( psPLC->conc_energy, LZ );
403 energy = silk_RSHIFT( energy, silk_max_32( 24 - LZ, 0 ) );
404
405 frac_Q24 = silk_DIV32( psPLC->conc_energy, silk_max( energy, 1 ) );
406
407 gain_Q16 = silk_LSHIFT( silk_SQRT_APPROX( frac_Q24 ), 4 );
408 slope_Q16 = silk_DIV32_16( ( (opus_int32)1 << 16 ) - gain_Q16, length );
409 /* Make slope 4x steeper to avoid missing onsets after DTX */
410 slope_Q16 = silk_LSHIFT( slope_Q16, 2 );
411
412 for( i = 0; i < length; i++ ) {
413 frame[ i ] = silk_SMULWB( gain_Q16, frame[ i ] );
414 gain_Q16 += slope_Q16;
415 if( gain_Q16 > (opus_int32)1 << 16 ) {
416 break;
417 }
418 }
419 }
420 }
421 psPLC->last_frame_lost = 0;
422 }
423}
diff --git a/lib/rbcodec/codecs/libopus/silk/PLC.h b/lib/rbcodec/codecs/libopus/silk/PLC.h
new file mode 100644
index 0000000000..1d2d9061d9
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/PLC.h
@@ -0,0 +1,61 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_PLC_H
29#define SILK_PLC_H
30
31#include "main.h"
32
33#define BWE_COEF 0.99
34#define V_PITCH_GAIN_START_MIN_Q14 11469 /* 0.7 in Q14 */
35#define V_PITCH_GAIN_START_MAX_Q14 15565 /* 0.95 in Q14 */
36#define MAX_PITCH_LAG_MS 18
37#define RAND_BUF_SIZE 128
38#define RAND_BUF_MASK ( RAND_BUF_SIZE - 1 )
39#define LOG2_INV_LPC_GAIN_HIGH_THRES 3 /* 2^3 = 8 dB LPC gain */
40#define LOG2_INV_LPC_GAIN_LOW_THRES 8 /* 2^8 = 24 dB LPC gain */
41#define PITCH_DRIFT_FAC_Q16 655 /* 0.01 in Q16 */
42
43void silk_PLC_Reset(
44 silk_decoder_state *psDec /* I/O Decoder state */
45);
46
47void silk_PLC(
48 silk_decoder_state *psDec, /* I/O Decoder state */
49 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
50 opus_int16 frame[], /* I/O signal */
51 opus_int lost /* I Loss flag */
52);
53
54void silk_PLC_glue_frames(
55 silk_decoder_state *psDec, /* I/O decoder state */
56 opus_int16 frame[], /* I/O signal */
57 opus_int length /* I length of signal */
58);
59
60#endif
61
diff --git a/lib/rbcodec/codecs/libopus/silk/SigProc_FIX.h b/lib/rbcodec/codecs/libopus/silk/SigProc_FIX.h
new file mode 100644
index 0000000000..72ec26a67f
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/SigProc_FIX.h
@@ -0,0 +1,589 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_SIGPROC_FIX_H
29#define SILK_SIGPROC_FIX_H
30
31#ifdef __cplusplus
32extern "C"
33{
34#endif
35
36/*#define silk_MACRO_COUNT */ /* Used to enable WMOPS counting */
37
38#define SILK_MAX_ORDER_LPC 16 /* max order of the LPC analysis in schur() and k2a() */
39
40#include <string.h> /* for memset(), memcpy(), memmove() */
41#include "typedef.h"
42#include "resampler_structs.h"
43#include "macros.h"
44
45
46/********************************************************************/
47/* SIGNAL PROCESSING FUNCTIONS */
48/********************************************************************/
49
50/*!
51 * Initialize/reset the resampler state for a given pair of input/output sampling rates
52*/
53opus_int silk_resampler_init(
54 silk_resampler_state_struct *S, /* I/O Resampler state */
55 opus_int32 Fs_Hz_in, /* I Input sampling rate (Hz) */
56 opus_int32 Fs_Hz_out, /* I Output sampling rate (Hz) */
57 opus_int forEnc /* I If 1: encoder; if 0: decoder */
58);
59
60/*!
61 * Resampler: convert from one sampling rate to another
62 */
63opus_int silk_resampler(
64 silk_resampler_state_struct *S, /* I/O Resampler state */
65 opus_int16 out[], /* O Output signal */
66 const opus_int16 in[], /* I Input signal */
67 opus_int32 inLen /* I Number of input samples */
68);
69
70/*!
71* Downsample 2x, mediocre quality
72*/
73void silk_resampler_down2(
74 opus_int32 *S, /* I/O State vector [ 2 ] */
75 opus_int16 *out, /* O Output signal [ len ] */
76 const opus_int16 *in, /* I Input signal [ floor(len/2) ] */
77 opus_int32 inLen /* I Number of input samples */
78);
79
80/*!
81 * Downsample by a factor 2/3, low quality
82*/
83void silk_resampler_down2_3(
84 opus_int32 *S, /* I/O State vector [ 6 ] */
85 opus_int16 *out, /* O Output signal [ floor(2*inLen/3) ] */
86 const opus_int16 *in, /* I Input signal [ inLen ] */
87 opus_int32 inLen /* I Number of input samples */
88);
89
90/*!
91 * second order ARMA filter;
92 * slower than biquad() but uses more precise coefficients
93 * can handle (slowly) varying coefficients
94 */
95void silk_biquad_alt(
96 const opus_int16 *in, /* I input signal */
97 const opus_int32 *B_Q28, /* I MA coefficients [3] */
98 const opus_int32 *A_Q28, /* I AR coefficients [2] */
99 opus_int32 *S, /* I/O State vector [2] */
100 opus_int16 *out, /* O output signal */
101 const opus_int32 len, /* I signal length (must be even) */
102 opus_int stride /* I Operate on interleaved signal if > 1 */
103);
104
105/* Variable order MA prediction error filter. */
106void silk_LPC_analysis_filter(
107 opus_int16 *out, /* O Output signal */
108 const opus_int16 *in, /* I Input signal */
109 const opus_int16 *B, /* I MA prediction coefficients, Q12 [order] */
110 const opus_int32 len, /* I Signal length */
111 const opus_int32 d /* I Filter order */
112);
113
114/* Chirp (bandwidth expand) LP AR filter */
115void silk_bwexpander(
116 opus_int16 *ar, /* I/O AR filter to be expanded (without leading 1) */
117 const opus_int d, /* I Length of ar */
118 opus_int32 chirp_Q16 /* I Chirp factor (typically in the range 0 to 1) */
119);
120
121/* Chirp (bandwidth expand) LP AR filter */
122void silk_bwexpander_32(
123 opus_int32 *ar, /* I/O AR filter to be expanded (without leading 1) */
124 const opus_int d, /* I Length of ar */
125 opus_int32 chirp_Q16 /* I Chirp factor in Q16 */
126);
127
128/* Compute inverse of LPC prediction gain, and */
129/* test if LPC coefficients are stable (all poles within unit circle) */
130opus_int32 silk_LPC_inverse_pred_gain( /* O Returns inverse prediction gain in energy domain, Q30 */
131 const opus_int16 *A_Q12, /* I Prediction coefficients, Q12 [order] */
132 const opus_int order /* I Prediction order */
133);
134
135/* For input in Q24 domain */
136opus_int32 silk_LPC_inverse_pred_gain_Q24( /* O Returns inverse prediction gain in energy domain, Q30 */
137 const opus_int32 *A_Q24, /* I Prediction coefficients [order] */
138 const opus_int order /* I Prediction order */
139);
140
141/* Split signal in two decimated bands using first-order allpass filters */
142void silk_ana_filt_bank_1(
143 const opus_int16 *in, /* I Input signal [N] */
144 opus_int32 *S, /* I/O State vector [2] */
145 opus_int16 *outL, /* O Low band [N/2] */
146 opus_int16 *outH, /* O High band [N/2] */
147 const opus_int32 N /* I Number of input samples */
148);
149
150/********************************************************************/
151/* SCALAR FUNCTIONS */
152/********************************************************************/
153
154/* Approximation of 128 * log2() (exact inverse of approx 2^() below) */
155/* Convert input to a log scale */
156opus_int32 silk_lin2log(
157 const opus_int32 inLin /* I input in linear scale */
158);
159
160/* Approximation of a sigmoid function */
161opus_int silk_sigm_Q15(
162 opus_int in_Q5 /* I */
163);
164
165/* Approximation of 2^() (exact inverse of approx log2() above) */
166/* Convert input to a linear scale */
167opus_int32 silk_log2lin(
168 const opus_int32 inLog_Q7 /* I input on log scale */
169);
170
171/* Function that returns the maximum absolut value of the input vector */
172opus_int16 silk_int16_array_maxabs( /* O Maximum absolute value, max: 2^15-1 */
173 const opus_int16 *vec, /* I Input vector [len] */
174 const opus_int32 len /* I Length of input vector */
175);
176
177/* Compute number of bits to right shift the sum of squares of a vector */
178/* of int16s to make it fit in an int32 */
179void silk_sum_sqr_shift(
180 opus_int32 *energy, /* O Energy of x, after shifting to the right */
181 opus_int *shift, /* O Number of bits right shift applied to energy */
182 const opus_int16 *x, /* I Input vector */
183 opus_int len /* I Length of input vector */
184);
185
186/* Calculates the reflection coefficients from the correlation sequence */
187/* Faster than schur64(), but much less accurate. */
188/* uses SMLAWB(), requiring armv5E and higher. */
189opus_int32 silk_schur( /* O Returns residual energy */
190 opus_int16 *rc_Q15, /* O reflection coefficients [order] Q15 */
191 const opus_int32 *c, /* I correlations [order+1] */
192 const opus_int32 order /* I prediction order */
193);
194
195/* Calculates the reflection coefficients from the correlation sequence */
196/* Slower than schur(), but more accurate. */
197/* Uses SMULL(), available on armv4 */
198opus_int32 silk_schur64( /* O returns residual energy */
199 opus_int32 rc_Q16[], /* O Reflection coefficients [order] Q16 */
200 const opus_int32 c[], /* I Correlations [order+1] */
201 opus_int32 order /* I Prediction order */
202);
203
204/* Step up function, converts reflection coefficients to prediction coefficients */
205void silk_k2a(
206 opus_int32 *A_Q24, /* O Prediction coefficients [order] Q24 */
207 const opus_int16 *rc_Q15, /* I Reflection coefficients [order] Q15 */
208 const opus_int32 order /* I Prediction order */
209);
210
211/* Step up function, converts reflection coefficients to prediction coefficients */
212void silk_k2a_Q16(
213 opus_int32 *A_Q24, /* O Prediction coefficients [order] Q24 */
214 const opus_int32 *rc_Q16, /* I Reflection coefficients [order] Q16 */
215 const opus_int32 order /* I Prediction order */
216);
217
218/* Apply sine window to signal vector. */
219/* Window types: */
220/* 1 -> sine window from 0 to pi/2 */
221/* 2 -> sine window from pi/2 to pi */
222/* every other sample of window is linearly interpolated, for speed */
223void silk_apply_sine_window(
224 opus_int16 px_win[], /* O Pointer to windowed signal */
225 const opus_int16 px[], /* I Pointer to input signal */
226 const opus_int win_type, /* I Selects a window type */
227 const opus_int length /* I Window length, multiple of 4 */
228);
229
230/* Compute autocorrelation */
231void silk_autocorr(
232 opus_int32 *results, /* O Result (length correlationCount) */
233 opus_int *scale, /* O Scaling of the correlation vector */
234 const opus_int16 *inputData, /* I Input data to correlate */
235 const opus_int inputDataSize, /* I Length of input */
236 const opus_int correlationCount /* I Number of correlation taps to compute */
237);
238
239void silk_decode_pitch(
240 opus_int16 lagIndex, /* I */
241 opus_int8 contourIndex, /* O */
242 opus_int pitch_lags[], /* O 4 pitch values */
243 const opus_int Fs_kHz, /* I sampling frequency (kHz) */
244 const opus_int nb_subfr /* I number of sub frames */
245);
246
247opus_int silk_pitch_analysis_core( /* O Voicing estimate: 0 voiced, 1 unvoiced */
248 const opus_int16 *frame, /* I Signal of length PE_FRAME_LENGTH_MS*Fs_kHz */
249 opus_int *pitch_out, /* O 4 pitch lag values */
250 opus_int16 *lagIndex, /* O Lag Index */
251 opus_int8 *contourIndex, /* O Pitch contour Index */
252 opus_int *LTPCorr_Q15, /* I/O Normalized correlation; input: value from previous frame */
253 opus_int prevLag, /* I Last lag of previous frame; set to zero is unvoiced */
254 const opus_int32 search_thres1_Q16, /* I First stage threshold for lag candidates 0 - 1 */
255 const opus_int search_thres2_Q15, /* I Final threshold for lag candidates 0 - 1 */
256 const opus_int Fs_kHz, /* I Sample frequency (kHz) */
257 const opus_int complexity, /* I Complexity setting, 0-2, where 2 is highest */
258 const opus_int nb_subfr /* I number of 5 ms subframes */
259);
260
261/* Compute Normalized Line Spectral Frequencies (NLSFs) from whitening filter coefficients */
262/* If not all roots are found, the a_Q16 coefficients are bandwidth expanded until convergence. */
263void silk_A2NLSF(
264 opus_int16 *NLSF, /* O Normalized Line Spectral Frequencies in Q15 (0..2^15-1) [d] */
265 opus_int32 *a_Q16, /* I/O Monic whitening filter coefficients in Q16 [d] */
266 const opus_int d /* I Filter order (must be even) */
267);
268
269/* compute whitening filter coefficients from normalized line spectral frequencies */
270void silk_NLSF2A(
271 opus_int16 *a_Q12, /* O monic whitening filter coefficients in Q12, [ d ] */
272 const opus_int16 *NLSF, /* I normalized line spectral frequencies in Q15, [ d ] */
273 const opus_int d /* I filter order (should be even) */
274);
275
276void silk_insertion_sort_increasing(
277 opus_int32 *a, /* I/O Unsorted / Sorted vector */
278 opus_int *idx, /* O Index vector for the sorted elements */
279 const opus_int L, /* I Vector length */
280 const opus_int K /* I Number of correctly sorted positions */
281);
282
283void silk_insertion_sort_decreasing_int16(
284 opus_int16 *a, /* I/O Unsorted / Sorted vector */
285 opus_int *idx, /* O Index vector for the sorted elements */
286 const opus_int L, /* I Vector length */
287 const opus_int K /* I Number of correctly sorted positions */
288);
289
290void silk_insertion_sort_increasing_all_values_int16(
291 opus_int16 *a, /* I/O Unsorted / Sorted vector */
292 const opus_int L /* I Vector length */
293);
294
295/* NLSF stabilizer, for a single input data vector */
296void silk_NLSF_stabilize(
297 opus_int16 *NLSF_Q15, /* I/O Unstable/stabilized normalized LSF vector in Q15 [L] */
298 const opus_int16 *NDeltaMin_Q15, /* I Min distance vector, NDeltaMin_Q15[L] must be >= 1 [L+1] */
299 const opus_int L /* I Number of NLSF parameters in the input vector */
300);
301
302/* Laroia low complexity NLSF weights */
303void silk_NLSF_VQ_weights_laroia(
304 opus_int16 *pNLSFW_Q_OUT, /* O Pointer to input vector weights [D] */
305 const opus_int16 *pNLSF_Q15, /* I Pointer to input vector [D] */
306 const opus_int D /* I Input vector dimension (even) */
307);
308
309/* Compute reflection coefficients from input signal */
310void silk_burg_modified(
311 opus_int32 *res_nrg, /* O Residual energy */
312 opus_int *res_nrg_Q, /* O Residual energy Q value */
313 opus_int32 A_Q16[], /* O Prediction coefficients (length order) */
314 const opus_int16 x[], /* I Input signal, length: nb_subfr * ( D + subfr_length ) */
315 const opus_int32 minInvGain_Q30, /* I Inverse of max prediction gain */
316 const opus_int subfr_length, /* I Input signal subframe length (incl. D preceeding samples) */
317 const opus_int nb_subfr, /* I Number of subframes stacked in x */
318 const opus_int D /* I Order */
319);
320
321/* Copy and multiply a vector by a constant */
322void silk_scale_copy_vector16(
323 opus_int16 *data_out,
324 const opus_int16 *data_in,
325 opus_int32 gain_Q16, /* I Gain in Q16 */
326 const opus_int dataSize /* I Length */
327);
328
329/* Some for the LTP related function requires Q26 to work.*/
330void silk_scale_vector32_Q26_lshift_18(
331 opus_int32 *data1, /* I/O Q0/Q18 */
332 opus_int32 gain_Q26, /* I Q26 */
333 opus_int dataSize /* I length */
334);
335
336/********************************************************************/
337/* INLINE ARM MATH */
338/********************************************************************/
339
340/* return sum( inVec1[i] * inVec2[i] ) */
341opus_int32 silk_inner_prod_aligned(
342 const opus_int16 *const inVec1, /* I input vector 1 */
343 const opus_int16 *const inVec2, /* I input vector 2 */
344 const opus_int len /* I vector lengths */
345);
346
347opus_int32 silk_inner_prod_aligned_scale(
348 const opus_int16 *const inVec1, /* I input vector 1 */
349 const opus_int16 *const inVec2, /* I input vector 2 */
350 const opus_int scale, /* I number of bits to shift */
351 const opus_int len /* I vector lengths */
352);
353
354opus_int64 silk_inner_prod16_aligned_64(
355 const opus_int16 *inVec1, /* I input vector 1 */
356 const opus_int16 *inVec2, /* I input vector 2 */
357 const opus_int len /* I vector lengths */
358);
359
360/********************************************************************/
361/* MACROS */
362/********************************************************************/
363
364/* Rotate a32 right by 'rot' bits. Negative rot values result in rotating
365 left. Output is 32bit int.
366 Note: contemporary compilers recognize the C expression below and
367 compile it into a 'ror' instruction if available. No need for inline ASM! */
368static inline opus_int32 silk_ROR32( opus_int32 a32, opus_int rot )
369{
370 opus_uint32 x = (opus_uint32) a32;
371 opus_uint32 r = (opus_uint32) rot;
372 opus_uint32 m = (opus_uint32) -rot;
373 if( rot == 0 ) {
374 return a32;
375 } else if( rot < 0 ) {
376 return (opus_int32) ((x << m) | (x >> (32 - m)));
377 } else {
378 return (opus_int32) ((x << (32 - r)) | (x >> r));
379 }
380}
381
382/* Allocate opus_int16 alligned to 4-byte memory address */
383#if EMBEDDED_ARM
384#define silk_DWORD_ALIGN __attribute__((aligned(4)))
385#else
386#define silk_DWORD_ALIGN
387#endif
388
389/* Useful Macros that can be adjusted to other platforms */
390#define silk_memcpy(dest, src, size) memcpy((dest), (src), (size))
391#define silk_memset(dest, src, size) memset((dest), (src), (size))
392#define silk_memmove(dest, src, size) memmove((dest), (src), (size))
393
394/* Fixed point macros */
395
396/* (a32 * b32) output have to be 32bit int */
397#define silk_MUL(a32, b32) ((a32) * (b32))
398
399/* (a32 * b32) output have to be 32bit uint */
400#define silk_MUL_uint(a32, b32) silk_MUL(a32, b32)
401
402/* a32 + (b32 * c32) output have to be 32bit int */
403#define silk_MLA(a32, b32, c32) silk_ADD32((a32),((b32) * (c32)))
404
405/* a32 + (b32 * c32) output have to be 32bit uint */
406#define silk_MLA_uint(a32, b32, c32) silk_MLA(a32, b32, c32)
407
408/* ((a32 >> 16) * (b32 >> 16)) output have to be 32bit int */
409#define silk_SMULTT(a32, b32) (((a32) >> 16) * ((b32) >> 16))
410
411/* a32 + ((a32 >> 16) * (b32 >> 16)) output have to be 32bit int */
412#define silk_SMLATT(a32, b32, c32) silk_ADD32((a32),((b32) >> 16) * ((c32) >> 16))
413
414#define silk_SMLALBB(a64, b16, c16) silk_ADD64((a64),(opus_int64)((opus_int32)(b16) * (opus_int32)(c16)))
415
416/* (a32 * b32) */
417#define silk_SMULL(a32, b32) ((opus_int64)(a32) * /*(opus_int64)*/(b32))
418
419/* Adds two signed 32-bit values in a way that can overflow, while not relying on undefined behaviour
420 (just standard two's complement implementation-specific behaviour) */
421#define silk_ADD32_ovflw(a, b) ((opus_int32)((opus_uint32)(a) + (opus_uint32)(b)))
422/* Subtractss two signed 32-bit values in a way that can overflow, while not relying on undefined behaviour
423 (just standard two's complement implementation-specific behaviour) */
424#define silk_SUB32_ovflw(a, b) ((opus_int32)((opus_uint32)(a) - (opus_uint32)(b)))
425
426/* Multiply-accumulate macros that allow overflow in the addition (ie, no asserts in debug mode) */
427#define silk_MLA_ovflw(a32, b32, c32) silk_ADD32_ovflw((a32), (opus_uint32)(b32) * (opus_uint32)(c32))
428#define silk_SMLABB_ovflw(a32, b32, c32) (silk_ADD32_ovflw((a32) , ((opus_int32)((opus_int16)(b32))) * (opus_int32)((opus_int16)(c32))))
429
430#define silk_DIV32_16(a32, b16) ((opus_int32)((a32) / (b16)))
431#define silk_DIV32(a32, b32) ((opus_int32)((a32) / (b32)))
432
433/* These macros enables checking for overflow in silk_API_Debug.h*/
434#define silk_ADD16(a, b) ((a) + (b))
435#define silk_ADD32(a, b) ((a) + (b))
436#define silk_ADD64(a, b) ((a) + (b))
437
438#define silk_SUB16(a, b) ((a) - (b))
439#define silk_SUB32(a, b) ((a) - (b))
440#define silk_SUB64(a, b) ((a) - (b))
441
442#define silk_SAT8(a) ((a) > silk_int8_MAX ? silk_int8_MAX : \
443 ((a) < silk_int8_MIN ? silk_int8_MIN : (a)))
444#define silk_SAT16(a) ((a) > silk_int16_MAX ? silk_int16_MAX : \
445 ((a) < silk_int16_MIN ? silk_int16_MIN : (a)))
446#define silk_SAT32(a) ((a) > silk_int32_MAX ? silk_int32_MAX : \
447 ((a) < silk_int32_MIN ? silk_int32_MIN : (a)))
448
449#define silk_CHECK_FIT8(a) (a)
450#define silk_CHECK_FIT16(a) (a)
451#define silk_CHECK_FIT32(a) (a)
452
453#define silk_ADD_SAT16(a, b) (opus_int16)silk_SAT16( silk_ADD32( (opus_int32)(a), (b) ) )
454#define silk_ADD_SAT64(a, b) ((((a) + (b)) & 0x8000000000000000LL) == 0 ? \
455 ((((a) & (b)) & 0x8000000000000000LL) != 0 ? silk_int64_MIN : (a)+(b)) : \
456 ((((a) | (b)) & 0x8000000000000000LL) == 0 ? silk_int64_MAX : (a)+(b)) )
457
458#define silk_SUB_SAT16(a, b) (opus_int16)silk_SAT16( silk_SUB32( (opus_int32)(a), (b) ) )
459#define silk_SUB_SAT64(a, b) ((((a)-(b)) & 0x8000000000000000LL) == 0 ? \
460 (( (a) & ((b)^0x8000000000000000LL) & 0x8000000000000000LL) ? silk_int64_MIN : (a)-(b)) : \
461 ((((a)^0x8000000000000000LL) & (b) & 0x8000000000000000LL) ? silk_int64_MAX : (a)-(b)) )
462
463/* Saturation for positive input values */
464#define silk_POS_SAT32(a) ((a) > silk_int32_MAX ? silk_int32_MAX : (a))
465
466/* Add with saturation for positive input values */
467#define silk_ADD_POS_SAT8(a, b) ((((a)+(b)) & 0x80) ? silk_int8_MAX : ((a)+(b)))
468#define silk_ADD_POS_SAT16(a, b) ((((a)+(b)) & 0x8000) ? silk_int16_MAX : ((a)+(b)))
469#define silk_ADD_POS_SAT32(a, b) ((((a)+(b)) & 0x80000000) ? silk_int32_MAX : ((a)+(b)))
470#define silk_ADD_POS_SAT64(a, b) ((((a)+(b)) & 0x8000000000000000LL) ? silk_int64_MAX : ((a)+(b)))
471
472#define silk_LSHIFT8(a, shift) ((opus_int8)((opus_uint8)(a)<<(shift))) /* shift >= 0, shift < 8 */
473#define silk_LSHIFT16(a, shift) ((opus_int16)((opus_uint16)(a)<<(shift))) /* shift >= 0, shift < 16 */
474#define silk_LSHIFT32(a, shift) ((opus_int32)((opus_uint32)(a)<<(shift))) /* shift >= 0, shift < 32 */
475#define silk_LSHIFT64(a, shift) ((opus_int64)((opus_uint64)(a)<<(shift))) /* shift >= 0, shift < 64 */
476#define silk_LSHIFT(a, shift) silk_LSHIFT32(a, shift) /* shift >= 0, shift < 32 */
477
478#define silk_RSHIFT8(a, shift) ((a)>>(shift)) /* shift >= 0, shift < 8 */
479#define silk_RSHIFT16(a, shift) ((a)>>(shift)) /* shift >= 0, shift < 16 */
480#define silk_RSHIFT32(a, shift) ((a)>>(shift)) /* shift >= 0, shift < 32 */
481#define silk_RSHIFT64(a, shift) ((a)>>(shift)) /* shift >= 0, shift < 64 */
482#define silk_RSHIFT(a, shift) silk_RSHIFT32(a, shift) /* shift >= 0, shift < 32 */
483
484/* saturates before shifting */
485#define silk_LSHIFT_SAT32(a, shift) (silk_LSHIFT32( silk_LIMIT( (a), silk_RSHIFT32( silk_int32_MIN, (shift) ), \
486 silk_RSHIFT32( silk_int32_MAX, (shift) ) ), (shift) ))
487
488#define silk_LSHIFT_ovflw(a, shift) ((opus_int32)((opus_uint32)(a) << (shift))) /* shift >= 0, allowed to overflow */
489#define silk_LSHIFT_uint(a, shift) ((a) << (shift)) /* shift >= 0 */
490#define silk_RSHIFT_uint(a, shift) ((a) >> (shift)) /* shift >= 0 */
491
492#define silk_ADD_LSHIFT(a, b, shift) ((a) + silk_LSHIFT((b), (shift))) /* shift >= 0 */
493#define silk_ADD_LSHIFT32(a, b, shift) silk_ADD32((a), silk_LSHIFT32((b), (shift))) /* shift >= 0 */
494#define silk_ADD_LSHIFT_uint(a, b, shift) ((a) + silk_LSHIFT_uint((b), (shift))) /* shift >= 0 */
495#define silk_ADD_RSHIFT(a, b, shift) ((a) + silk_RSHIFT((b), (shift))) /* shift >= 0 */
496#define silk_ADD_RSHIFT32(a, b, shift) silk_ADD32((a), silk_RSHIFT32((b), (shift))) /* shift >= 0 */
497#define silk_ADD_RSHIFT_uint(a, b, shift) ((a) + silk_RSHIFT_uint((b), (shift))) /* shift >= 0 */
498#define silk_SUB_LSHIFT32(a, b, shift) silk_SUB32((a), silk_LSHIFT32((b), (shift))) /* shift >= 0 */
499#define silk_SUB_RSHIFT32(a, b, shift) silk_SUB32((a), silk_RSHIFT32((b), (shift))) /* shift >= 0 */
500
501/* Requires that shift > 0 */
502#define silk_RSHIFT_ROUND(a, shift) ((shift) == 1 ? ((a) >> 1) + ((a) & 1) : (((a) >> ((shift) - 1)) + 1) >> 1)
503#define silk_RSHIFT_ROUND64(a, shift) ((shift) == 1 ? ((a) >> 1) + ((a) & 1) : (((a) >> ((shift) - 1)) + 1) >> 1)
504
505/* Number of rightshift required to fit the multiplication */
506#define silk_NSHIFT_MUL_32_32(a, b) ( -(31- (32-silk_CLZ32(silk_abs(a)) + (32-silk_CLZ32(silk_abs(b))))) )
507#define silk_NSHIFT_MUL_16_16(a, b) ( -(15- (16-silk_CLZ16(silk_abs(a)) + (16-silk_CLZ16(silk_abs(b))))) )
508
509
510#define silk_min(a, b) (((a) < (b)) ? (a) : (b))
511#define silk_max(a, b) (((a) > (b)) ? (a) : (b))
512
513/* Macro to convert floating-point constants to fixed-point */
514#define SILK_FIX_CONST( C, Q ) ((opus_int32)((C) * ((opus_int64)1 << (Q)) + 0.5))
515
516/* silk_min() versions with typecast in the function call */
517static inline opus_int silk_min_int(opus_int a, opus_int b)
518{
519 return (((a) < (b)) ? (a) : (b));
520}
521static inline opus_int16 silk_min_16(opus_int16 a, opus_int16 b)
522{
523 return (((a) < (b)) ? (a) : (b));
524}
525static inline opus_int32 silk_min_32(opus_int32 a, opus_int32 b)
526{
527 return (((a) < (b)) ? (a) : (b));
528}
529static inline opus_int64 silk_min_64(opus_int64 a, opus_int64 b)
530{
531 return (((a) < (b)) ? (a) : (b));
532}
533
534/* silk_min() versions with typecast in the function call */
535static inline opus_int silk_max_int(opus_int a, opus_int b)
536{
537 return (((a) > (b)) ? (a) : (b));
538}
539static inline opus_int16 silk_max_16(opus_int16 a, opus_int16 b)
540{
541 return (((a) > (b)) ? (a) : (b));
542}
543static inline opus_int32 silk_max_32(opus_int32 a, opus_int32 b)
544{
545 return (((a) > (b)) ? (a) : (b));
546}
547static inline opus_int64 silk_max_64(opus_int64 a, opus_int64 b)
548{
549 return (((a) > (b)) ? (a) : (b));
550}
551
552#define silk_LIMIT( a, limit1, limit2) ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \
553 : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))))
554
555#define silk_LIMIT_int silk_LIMIT
556#define silk_LIMIT_16 silk_LIMIT
557#define silk_LIMIT_32 silk_LIMIT
558
559#define silk_abs(a) (((a) > 0) ? (a) : -(a)) /* Be careful, silk_abs returns wrong when input equals to silk_intXX_MIN */
560#define silk_abs_int(a) (((a) ^ ((a) >> (8 * sizeof(a) - 1))) - ((a) >> (8 * sizeof(a) - 1)))
561#define silk_abs_int32(a) (((a) ^ ((a) >> 31)) - ((a) >> 31))
562#define silk_abs_int64(a) (((a) > 0) ? (a) : -(a))
563
564#define silk_sign(a) ((a) > 0 ? 1 : ( (a) < 0 ? -1 : 0 ))
565
566/* PSEUDO-RANDOM GENERATOR */
567/* Make sure to store the result as the seed for the next call (also in between */
568/* frames), otherwise result won't be random at all. When only using some of the */
569/* bits, take the most significant bits by right-shifting. */
570#define silk_RAND(seed) (silk_MLA_ovflw(907633515, (seed), 196314165))
571
572/* Add some multiplication functions that can be easily mapped to ARM. */
573
574/* silk_SMMUL: Signed top word multiply.
575 ARMv6 2 instruction cycles.
576 ARMv3M+ 3 instruction cycles. use SMULL and ignore LSB registers.(except xM)*/
577/*#define silk_SMMUL(a32, b32) (opus_int32)silk_RSHIFT(silk_SMLAL(silk_SMULWB((a32), (b32)), (a32), silk_RSHIFT_ROUND((b32), 16)), 16)*/
578/* the following seems faster on x86 */
579#define silk_SMMUL(a32, b32) (opus_int32)silk_RSHIFT64(silk_SMULL((a32), (b32)), 32)
580
581#include "Inlines.h"
582#include "MacroCount.h"
583#include "MacroDebug.h"
584
585#ifdef __cplusplus
586}
587#endif
588
589#endif /* SILK_SIGPROC_FIX_H */
diff --git a/lib/rbcodec/codecs/libopus/silk/bwexpander.c b/lib/rbcodec/codecs/libopus/silk/bwexpander.c
new file mode 100644
index 0000000000..9bb5f62810
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/bwexpander.c
@@ -0,0 +1,51 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33
34/* Chirp (bandwidth expand) LP AR filter */
35void silk_bwexpander(
36 opus_int16 *ar, /* I/O AR filter to be expanded (without leading 1) */
37 const opus_int d, /* I Length of ar */
38 opus_int32 chirp_Q16 /* I Chirp factor (typically in the range 0 to 1) */
39)
40{
41 opus_int i;
42 opus_int32 chirp_minus_one_Q16 = chirp_Q16 - 65536;
43
44 /* NB: Dont use silk_SMULWB, instead of silk_RSHIFT_ROUND( silk_MUL(), 16 ), below. */
45 /* Bias in silk_SMULWB can lead to unstable filters */
46 for( i = 0; i < d - 1; i++ ) {
47 ar[ i ] = (opus_int16)silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, ar[ i ] ), 16 );
48 chirp_Q16 += silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, chirp_minus_one_Q16 ), 16 );
49 }
50 ar[ d - 1 ] = (opus_int16)silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, ar[ d - 1 ] ), 16 );
51}
diff --git a/lib/rbcodec/codecs/libopus/silk/bwexpander_32.c b/lib/rbcodec/codecs/libopus/silk/bwexpander_32.c
new file mode 100644
index 0000000000..fe3cc4c9d1
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/bwexpander_32.c
@@ -0,0 +1,50 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33
34/* Chirp (bandwidth expand) LP AR filter */
35void silk_bwexpander_32(
36 opus_int32 *ar, /* I/O AR filter to be expanded (without leading 1) */
37 const opus_int d, /* I Length of ar */
38 opus_int32 chirp_Q16 /* I Chirp factor in Q16 */
39)
40{
41 opus_int i;
42 opus_int32 chirp_minus_one_Q16 = chirp_Q16 - 65536;
43
44 for( i = 0; i < d - 1; i++ ) {
45 ar[ i ] = silk_SMULWW( chirp_Q16, ar[ i ] );
46 chirp_Q16 += silk_RSHIFT_ROUND( silk_MUL( chirp_Q16, chirp_minus_one_Q16 ), 16 );
47 }
48 ar[ d - 1 ] = silk_SMULWW( chirp_Q16, ar[ d - 1 ] );
49}
50
diff --git a/lib/rbcodec/codecs/libopus/silk/code_signs.c b/lib/rbcodec/codecs/libopus/silk/code_signs.c
new file mode 100644
index 0000000000..3903eb1f16
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/code_signs.c
@@ -0,0 +1,115 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/*#define silk_enc_map(a) ((a) > 0 ? 1 : 0)*/
35/*#define silk_dec_map(a) ((a) > 0 ? 1 : -1)*/
36/* shifting avoids if-statement */
37#define silk_enc_map(a) ( silk_RSHIFT( (a), 15 ) + 1 )
38#define silk_dec_map(a) ( silk_LSHIFT( (a), 1 ) - 1 )
39
40/* Encodes signs of excitation */
41void silk_encode_signs(
42 ec_enc *psRangeEnc, /* I/O Compressor data structure */
43 const opus_int8 pulses[], /* I pulse signal */
44 opus_int length, /* I length of input */
45 const opus_int signalType, /* I Signal type */
46 const opus_int quantOffsetType, /* I Quantization offset type */
47 const opus_int sum_pulses[ MAX_NB_SHELL_BLOCKS ] /* I Sum of absolute pulses per block */
48)
49{
50 opus_int i, j, p;
51 opus_uint8 icdf[ 2 ];
52 const opus_int8 *q_ptr;
53 const opus_uint8 *icdf_ptr;
54
55 icdf[ 1 ] = 0;
56 q_ptr = pulses;
57 i = silk_SMULBB( 7, silk_ADD_LSHIFT( quantOffsetType, signalType, 1 ) );
58 icdf_ptr = &silk_sign_iCDF[ i ];
59 length = silk_RSHIFT( length + SHELL_CODEC_FRAME_LENGTH/2, LOG2_SHELL_CODEC_FRAME_LENGTH );
60 for( i = 0; i < length; i++ ) {
61 p = sum_pulses[ i ];
62 if( p > 0 ) {
63 icdf[ 0 ] = icdf_ptr[ silk_min( p & 0x1F, 6 ) ];
64 for( j = 0; j < SHELL_CODEC_FRAME_LENGTH; j++ ) {
65 if( q_ptr[ j ] != 0 ) {
66 ec_enc_icdf( psRangeEnc, silk_enc_map( q_ptr[ j ]), icdf, 8 );
67 }
68 }
69 }
70 q_ptr += SHELL_CODEC_FRAME_LENGTH;
71 }
72}
73
74/* Decodes signs of excitation */
75void silk_decode_signs(
76 ec_dec *psRangeDec, /* I/O Compressor data structure */
77 opus_int pulses[], /* I/O pulse signal */
78 opus_int length, /* I length of input */
79 const opus_int signalType, /* I Signal type */
80 const opus_int quantOffsetType, /* I Quantization offset type */
81 const opus_int sum_pulses[ MAX_NB_SHELL_BLOCKS ] /* I Sum of absolute pulses per block */
82)
83{
84 opus_int i, j, p;
85 opus_uint8 icdf[ 2 ];
86 opus_int *q_ptr;
87 const opus_uint8 *icdf_ptr;
88
89 icdf[ 1 ] = 0;
90 q_ptr = pulses;
91 i = silk_SMULBB( 7, silk_ADD_LSHIFT( quantOffsetType, signalType, 1 ) );
92 icdf_ptr = &silk_sign_iCDF[ i ];
93 length = silk_RSHIFT( length + SHELL_CODEC_FRAME_LENGTH/2, LOG2_SHELL_CODEC_FRAME_LENGTH );
94 for( i = 0; i < length; i++ ) {
95 p = sum_pulses[ i ];
96 if( p > 0 ) {
97 icdf[ 0 ] = icdf_ptr[ silk_min( p & 0x1F, 6 ) ];
98 for( j = 0; j < SHELL_CODEC_FRAME_LENGTH; j++ ) {
99 if( q_ptr[ j ] > 0 ) {
100 /* attach sign */
101#if 0
102 /* conditional implementation */
103 if( ec_dec_icdf( psRangeDec, icdf, 8 ) == 0 ) {
104 q_ptr[ j ] = -q_ptr[ j ];
105 }
106#else
107 /* implementation with shift, subtraction, multiplication */
108 q_ptr[ j ] *= silk_dec_map( ec_dec_icdf( psRangeDec, icdf, 8 ) );
109#endif
110 }
111 }
112 }
113 q_ptr += SHELL_CODEC_FRAME_LENGTH;
114 }
115}
diff --git a/lib/rbcodec/codecs/libopus/silk/control.h b/lib/rbcodec/codecs/libopus/silk/control.h
new file mode 100644
index 0000000000..c52ec3fe38
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/control.h
@@ -0,0 +1,139 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_CONTROL_H
29#define SILK_CONTROL_H
30
31#include "typedef.h"
32
33#ifdef __cplusplus
34extern "C"
35{
36#endif
37
38/* Decoder API flags */
39#define FLAG_DECODE_NORMAL 0
40#define FLAG_PACKET_LOST 1
41#define FLAG_DECODE_LBRR 2
42
43/***********************************************/
44/* Structure for controlling encoder operation */
45/***********************************************/
46typedef struct {
47 /* I: Number of channels; 1/2 */
48 opus_int32 nChannelsAPI;
49
50 /* I: Number of channels; 1/2 */
51 opus_int32 nChannelsInternal;
52
53 /* I: Input signal sampling rate in Hertz; 8000/12000/16000/24000/32000/44100/48000 */
54 opus_int32 API_sampleRate;
55
56 /* I: Maximum internal sampling rate in Hertz; 8000/12000/16000 */
57 opus_int32 maxInternalSampleRate;
58
59 /* I: Minimum internal sampling rate in Hertz; 8000/12000/16000 */
60 opus_int32 minInternalSampleRate;
61
62 /* I: Soft request for internal sampling rate in Hertz; 8000/12000/16000 */
63 opus_int32 desiredInternalSampleRate;
64
65 /* I: Number of samples per packet in milliseconds; 10/20/40/60 */
66 opus_int payloadSize_ms;
67
68 /* I: Bitrate during active speech in bits/second; internally limited */
69 opus_int32 bitRate;
70
71 /* I: Uplink packet loss in percent (0-100) */
72 opus_int packetLossPercentage;
73
74 /* I: Complexity mode; 0 is lowest, 10 is highest complexity */
75 opus_int complexity;
76
77 /* I: Flag to enable in-band Forward Error Correction (FEC); 0/1 */
78 opus_int useInBandFEC;
79
80 /* I: Flag to enable discontinuous transmission (DTX); 0/1 */
81 opus_int useDTX;
82
83 /* I: Flag to use constant bitrate */
84 opus_int useCBR;
85
86 /* I: Maximum number of bits allowed for the frame */
87 opus_int maxBits;
88
89 /* I: Causes a smooth downmix to mono */
90 opus_int toMono;
91
92 /* I: Opus encoder is allowing us to switch bandwidth */
93 opus_int opusCanSwitch;
94
95 /* O: Internal sampling rate used, in Hertz; 8000/12000/16000 */
96 opus_int32 internalSampleRate;
97
98 /* O: Flag that bandwidth switching is allowed (because low voice activity) */
99 opus_int allowBandwidthSwitch;
100
101 /* O: Flag that SILK runs in WB mode without variable LP filter (use for switching between WB/SWB/FB) */
102 opus_int inWBmodeWithoutVariableLP;
103
104 /* O: Stereo width */
105 opus_int stereoWidth_Q14;
106
107 /* O: Tells the Opus encoder we're ready to switch */
108 opus_int switchReady;
109
110} silk_EncControlStruct;
111
112/**************************************************************************/
113/* Structure for controlling decoder operation and reading decoder status */
114/**************************************************************************/
115typedef struct {
116 /* I: Number of channels; 1/2 */
117 opus_int32 nChannelsAPI;
118
119 /* I: Number of channels; 1/2 */
120 opus_int32 nChannelsInternal;
121
122 /* I: Output signal sampling rate in Hertz; 8000/12000/16000/24000/32000/44100/48000 */
123 opus_int32 API_sampleRate;
124
125 /* I: Internal sampling rate used, in Hertz; 8000/12000/16000 */
126 opus_int32 internalSampleRate;
127
128 /* I: Number of samples per packet in milliseconds; 10/20/40/60 */
129 opus_int payloadSize_ms;
130
131 /* O: Pitch lag of previous frame (0 if unvoiced), measured in samples at 48 kHz */
132 opus_int prevPitchLag;
133} silk_DecControlStruct;
134
135#ifdef __cplusplus
136}
137#endif
138
139#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/dec_API.c b/lib/rbcodec/codecs/libopus/silk/dec_API.c
new file mode 100644
index 0000000000..908e6033b1
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/dec_API.c
@@ -0,0 +1,392 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31#include "API.h"
32#include "main.h"
33#include "stack_alloc.h"
34
35/************************/
36/* Decoder Super Struct */
37/************************/
38typedef struct {
39 silk_decoder_state channel_state[ DECODER_NUM_CHANNELS ];
40 stereo_dec_state sStereo;
41 opus_int nChannelsAPI;
42 opus_int nChannelsInternal;
43 opus_int prev_decode_only_middle;
44} silk_decoder;
45
46/*********************/
47/* Decoder functions */
48/*********************/
49
50opus_int silk_Get_Decoder_Size( /* O Returns error code */
51 opus_int *decSizeBytes /* O Number of bytes in SILK decoder state */
52)
53{
54 opus_int ret = SILK_NO_ERROR;
55
56 *decSizeBytes = sizeof( silk_decoder );
57
58 return ret;
59}
60
61/* Reset decoder state */
62opus_int silk_InitDecoder( /* O Returns error code */
63 void *decState /* I/O State */
64)
65{
66 opus_int n, ret = SILK_NO_ERROR;
67 silk_decoder_state *channel_state = ((silk_decoder *)decState)->channel_state;
68
69 for( n = 0; n < DECODER_NUM_CHANNELS; n++ ) {
70 ret = silk_init_decoder( &channel_state[ n ] );
71 }
72
73 return ret;
74}
75
76/* Decode a frame */
77opus_int silk_Decode( /* O Returns error code */
78 void* decState, /* I/O State */
79 silk_DecControlStruct* decControl, /* I/O Control Structure */
80 opus_int lostFlag, /* I 0: no loss, 1 loss, 2 decode fec */
81 opus_int newPacketFlag, /* I Indicates first decoder call for this packet */
82 ec_dec *psRangeDec, /* I/O Compressor data structure */
83 opus_int16 *samplesOut, /* O Decoded output speech vector */
84 opus_int32 *nSamplesOut /* O Number of samples decoded */
85)
86{
87 opus_int i, n, decode_only_middle = 0, ret = SILK_NO_ERROR;
88 opus_int32 nSamplesOutDec, LBRR_symbol;
89 opus_int16 *samplesOut1_tmp[ 2 ];
90 VARDECL( opus_int16, samplesOut1_tmp_storage );
91 VARDECL( opus_int16, samplesOut2_tmp );
92 opus_int32 MS_pred_Q13[ 2 ] = { 0 };
93 opus_int16 *resample_out_ptr;
94 silk_decoder *psDec = ( silk_decoder * )decState;
95 silk_decoder_state *channel_state = psDec->channel_state;
96 opus_int has_side;
97 opus_int stereo_to_mono;
98 SAVE_STACK;
99
100 /**********************************/
101 /* Test if first frame in payload */
102 /**********************************/
103 if( newPacketFlag ) {
104 for( n = 0; n < decControl->nChannelsInternal; n++ ) {
105 channel_state[ n ].nFramesDecoded = 0; /* Used to count frames in packet */
106 }
107 }
108
109 /* If Mono -> Stereo transition in bitstream: init state of second channel */
110 if( decControl->nChannelsInternal > psDec->nChannelsInternal ) {
111 ret += silk_init_decoder( &channel_state[ 1 ] );
112 }
113
114 stereo_to_mono = decControl->nChannelsInternal == 1 && psDec->nChannelsInternal == 2 &&
115 ( decControl->internalSampleRate == 1000*channel_state[ 0 ].fs_kHz );
116
117 if( channel_state[ 0 ].nFramesDecoded == 0 ) {
118 for( n = 0; n < decControl->nChannelsInternal; n++ ) {
119 opus_int fs_kHz_dec;
120 if( decControl->payloadSize_ms == 0 ) {
121 /* Assuming packet loss, use 10 ms */
122 channel_state[ n ].nFramesPerPacket = 1;
123 channel_state[ n ].nb_subfr = 2;
124 } else if( decControl->payloadSize_ms == 10 ) {
125 channel_state[ n ].nFramesPerPacket = 1;
126 channel_state[ n ].nb_subfr = 2;
127 } else if( decControl->payloadSize_ms == 20 ) {
128 channel_state[ n ].nFramesPerPacket = 1;
129 channel_state[ n ].nb_subfr = 4;
130 } else if( decControl->payloadSize_ms == 40 ) {
131 channel_state[ n ].nFramesPerPacket = 2;
132 channel_state[ n ].nb_subfr = 4;
133 } else if( decControl->payloadSize_ms == 60 ) {
134 channel_state[ n ].nFramesPerPacket = 3;
135 channel_state[ n ].nb_subfr = 4;
136 } else {
137 silk_assert( 0 );
138 RESTORE_STACK;
139 return SILK_DEC_INVALID_FRAME_SIZE;
140 }
141 fs_kHz_dec = ( decControl->internalSampleRate >> 10 ) + 1;
142 if( fs_kHz_dec != 8 && fs_kHz_dec != 12 && fs_kHz_dec != 16 ) {
143 silk_assert( 0 );
144 RESTORE_STACK;
145 return SILK_DEC_INVALID_SAMPLING_FREQUENCY;
146 }
147 ret += silk_decoder_set_fs( &channel_state[ n ], fs_kHz_dec, decControl->API_sampleRate );
148 }
149 }
150
151 if( decControl->nChannelsAPI == 2 && decControl->nChannelsInternal == 2 && ( psDec->nChannelsAPI == 1 || psDec->nChannelsInternal == 1 ) ) {
152 silk_memset( psDec->sStereo.pred_prev_Q13, 0, sizeof( psDec->sStereo.pred_prev_Q13 ) );
153 silk_memset( psDec->sStereo.sSide, 0, sizeof( psDec->sStereo.sSide ) );
154 silk_memcpy( &channel_state[ 1 ].resampler_state, &channel_state[ 0 ].resampler_state, sizeof( silk_resampler_state_struct ) );
155 }
156 psDec->nChannelsAPI = decControl->nChannelsAPI;
157 psDec->nChannelsInternal = decControl->nChannelsInternal;
158
159 if( decControl->API_sampleRate > (opus_int32)MAX_API_FS_KHZ * 1000 || decControl->API_sampleRate < 8000 ) {
160 ret = SILK_DEC_INVALID_SAMPLING_FREQUENCY;
161 RESTORE_STACK;
162 return( ret );
163 }
164
165 if( lostFlag != FLAG_PACKET_LOST && channel_state[ 0 ].nFramesDecoded == 0 ) {
166 /* First decoder call for this payload */
167 /* Decode VAD flags and LBRR flag */
168 for( n = 0; n < decControl->nChannelsInternal; n++ ) {
169 for( i = 0; i < channel_state[ n ].nFramesPerPacket; i++ ) {
170 channel_state[ n ].VAD_flags[ i ] = ec_dec_bit_logp(psRangeDec, 1);
171 }
172 channel_state[ n ].LBRR_flag = ec_dec_bit_logp(psRangeDec, 1);
173 }
174 /* Decode LBRR flags */
175 for( n = 0; n < decControl->nChannelsInternal; n++ ) {
176 silk_memset( channel_state[ n ].LBRR_flags, 0, sizeof( channel_state[ n ].LBRR_flags ) );
177 if( channel_state[ n ].LBRR_flag ) {
178 if( channel_state[ n ].nFramesPerPacket == 1 ) {
179 channel_state[ n ].LBRR_flags[ 0 ] = 1;
180 } else {
181 LBRR_symbol = ec_dec_icdf( psRangeDec, silk_LBRR_flags_iCDF_ptr[ channel_state[ n ].nFramesPerPacket - 2 ], 8 ) + 1;
182 for( i = 0; i < channel_state[ n ].nFramesPerPacket; i++ ) {
183 channel_state[ n ].LBRR_flags[ i ] = silk_RSHIFT( LBRR_symbol, i ) & 1;
184 }
185 }
186 }
187 }
188
189 if( lostFlag == FLAG_DECODE_NORMAL ) {
190 /* Regular decoding: skip all LBRR data */
191 for( i = 0; i < channel_state[ 0 ].nFramesPerPacket; i++ ) {
192 for( n = 0; n < decControl->nChannelsInternal; n++ ) {
193 if( channel_state[ n ].LBRR_flags[ i ] ) {
194 opus_int pulses[ MAX_FRAME_LENGTH ];
195 opus_int condCoding;
196
197 if( decControl->nChannelsInternal == 2 && n == 0 ) {
198 silk_stereo_decode_pred( psRangeDec, MS_pred_Q13 );
199 if( channel_state[ 1 ].LBRR_flags[ i ] == 0 ) {
200 silk_stereo_decode_mid_only( psRangeDec, &decode_only_middle );
201 }
202 }
203 /* Use conditional coding if previous frame available */
204 if( i > 0 && channel_state[ n ].LBRR_flags[ i - 1 ] ) {
205 condCoding = CODE_CONDITIONALLY;
206 } else {
207 condCoding = CODE_INDEPENDENTLY;
208 }
209 silk_decode_indices( &channel_state[ n ], psRangeDec, i, 1, condCoding );
210 silk_decode_pulses( psRangeDec, pulses, channel_state[ n ].indices.signalType,
211 channel_state[ n ].indices.quantOffsetType, channel_state[ n ].frame_length );
212 }
213 }
214 }
215 }
216 }
217
218 /* Get MS predictor index */
219 if( decControl->nChannelsInternal == 2 ) {
220 if( lostFlag == FLAG_DECODE_NORMAL ||
221 ( lostFlag == FLAG_DECODE_LBRR && channel_state[ 0 ].LBRR_flags[ channel_state[ 0 ].nFramesDecoded ] == 1 ) )
222 {
223 silk_stereo_decode_pred( psRangeDec, MS_pred_Q13 );
224 /* For LBRR data, decode mid-only flag only if side-channel's LBRR flag is false */
225 if( ( lostFlag == FLAG_DECODE_NORMAL && channel_state[ 1 ].VAD_flags[ channel_state[ 0 ].nFramesDecoded ] == 0 ) ||
226 ( lostFlag == FLAG_DECODE_LBRR && channel_state[ 1 ].LBRR_flags[ channel_state[ 0 ].nFramesDecoded ] == 0 ) )
227 {
228 silk_stereo_decode_mid_only( psRangeDec, &decode_only_middle );
229 } else {
230 decode_only_middle = 0;
231 }
232 } else {
233 for( n = 0; n < 2; n++ ) {
234 MS_pred_Q13[ n ] = psDec->sStereo.pred_prev_Q13[ n ];
235 }
236 }
237 }
238
239 /* Reset side channel decoder prediction memory for first frame with side coding */
240 if( decControl->nChannelsInternal == 2 && decode_only_middle == 0 && psDec->prev_decode_only_middle == 1 ) {
241 silk_memset( psDec->channel_state[ 1 ].outBuf, 0, sizeof(psDec->channel_state[ 1 ].outBuf) );
242 silk_memset( psDec->channel_state[ 1 ].sLPC_Q14_buf, 0, sizeof(psDec->channel_state[ 1 ].sLPC_Q14_buf) );
243 psDec->channel_state[ 1 ].lagPrev = 100;
244 psDec->channel_state[ 1 ].LastGainIndex = 10;
245 psDec->channel_state[ 1 ].prevSignalType = TYPE_NO_VOICE_ACTIVITY;
246 psDec->channel_state[ 1 ].first_frame_after_reset = 1;
247 }
248
249 ALLOC( samplesOut1_tmp_storage,
250 decControl->nChannelsInternal*(
251 channel_state[ 0 ].frame_length + 2 ),
252 opus_int16 );
253 samplesOut1_tmp[ 0 ] = samplesOut1_tmp_storage;
254 samplesOut1_tmp[ 1 ] = samplesOut1_tmp_storage
255 + channel_state[ 0 ].frame_length + 2;
256
257 if( lostFlag == FLAG_DECODE_NORMAL ) {
258 has_side = !decode_only_middle;
259 } else {
260 has_side = !psDec->prev_decode_only_middle
261 || (decControl->nChannelsInternal == 2 && lostFlag == FLAG_DECODE_LBRR && channel_state[1].LBRR_flags[ channel_state[1].nFramesDecoded ] == 1 );
262 }
263 /* Call decoder for one frame */
264 for( n = 0; n < decControl->nChannelsInternal; n++ ) {
265 if( n == 0 || has_side ) {
266 opus_int FrameIndex;
267 opus_int condCoding;
268
269 FrameIndex = channel_state[ 0 ].nFramesDecoded - n;
270 /* Use independent coding if no previous frame available */
271 if( FrameIndex <= 0 ) {
272 condCoding = CODE_INDEPENDENTLY;
273 } else if( lostFlag == FLAG_DECODE_LBRR ) {
274 condCoding = channel_state[ n ].LBRR_flags[ FrameIndex - 1 ] ? CODE_CONDITIONALLY : CODE_INDEPENDENTLY;
275 } else if( n > 0 && psDec->prev_decode_only_middle ) {
276 /* If we skipped a side frame in this packet, we don't
277 need LTP scaling; the LTP state is well-defined. */
278 condCoding = CODE_INDEPENDENTLY_NO_LTP_SCALING;
279 } else {
280 condCoding = CODE_CONDITIONALLY;
281 }
282 ret += silk_decode_frame( &channel_state[ n ], psRangeDec, &samplesOut1_tmp[ n ][ 2 ], &nSamplesOutDec, lostFlag, condCoding);
283 } else {
284 silk_memset( &samplesOut1_tmp[ n ][ 2 ], 0, nSamplesOutDec * sizeof( opus_int16 ) );
285 }
286 channel_state[ n ].nFramesDecoded++;
287 }
288
289 if( decControl->nChannelsAPI == 2 && decControl->nChannelsInternal == 2 ) {
290 /* Convert Mid/Side to Left/Right */
291 silk_stereo_MS_to_LR( &psDec->sStereo, samplesOut1_tmp[ 0 ], samplesOut1_tmp[ 1 ], MS_pred_Q13, channel_state[ 0 ].fs_kHz, nSamplesOutDec );
292 } else {
293 /* Buffering */
294 silk_memcpy( samplesOut1_tmp[ 0 ], psDec->sStereo.sMid, 2 * sizeof( opus_int16 ) );
295 silk_memcpy( psDec->sStereo.sMid, &samplesOut1_tmp[ 0 ][ nSamplesOutDec ], 2 * sizeof( opus_int16 ) );
296 }
297
298 /* Number of output samples */
299 *nSamplesOut = silk_DIV32( nSamplesOutDec * decControl->API_sampleRate, silk_SMULBB( channel_state[ 0 ].fs_kHz, 1000 ) );
300
301 /* Set up pointers to temp buffers */
302 ALLOC( samplesOut2_tmp,
303 decControl->nChannelsAPI == 2 ? *nSamplesOut : 0, opus_int16 );
304 if( decControl->nChannelsAPI == 2 ) {
305 resample_out_ptr = samplesOut2_tmp;
306 } else {
307 resample_out_ptr = samplesOut;
308 }
309
310 for( n = 0; n < silk_min( decControl->nChannelsAPI, decControl->nChannelsInternal ); n++ ) {
311
312 /* Resample decoded signal to API_sampleRate */
313 ret += silk_resampler( &channel_state[ n ].resampler_state, resample_out_ptr, &samplesOut1_tmp[ n ][ 1 ], nSamplesOutDec );
314
315 /* Interleave if stereo output and stereo stream */
316 if( decControl->nChannelsAPI == 2 ) {
317 for( i = 0; i < *nSamplesOut; i++ ) {
318 samplesOut[ n + 2 * i ] = resample_out_ptr[ i ];
319 }
320 }
321 }
322
323 /* Create two channel output from mono stream */
324 if( decControl->nChannelsAPI == 2 && decControl->nChannelsInternal == 1 ) {
325 if ( stereo_to_mono ){
326 /* Resample right channel for newly collapsed stereo just in case
327 we weren't doing collapsing when switching to mono */
328 ret += silk_resampler( &channel_state[ 1 ].resampler_state, resample_out_ptr, &samplesOut1_tmp[ 0 ][ 1 ], nSamplesOutDec );
329
330 for( i = 0; i < *nSamplesOut; i++ ) {
331 samplesOut[ 1 + 2 * i ] = resample_out_ptr[ i ];
332 }
333 } else {
334 for( i = 0; i < *nSamplesOut; i++ ) {
335 samplesOut[ 1 + 2 * i ] = samplesOut[ 0 + 2 * i ];
336 }
337 }
338 }
339
340 /* Export pitch lag, measured at 48 kHz sampling rate */
341 if( channel_state[ 0 ].prevSignalType == TYPE_VOICED ) {
342 int mult_tab[ 3 ] = { 6, 4, 3 };
343 decControl->prevPitchLag = channel_state[ 0 ].lagPrev * mult_tab[ ( channel_state[ 0 ].fs_kHz - 8 ) >> 2 ];
344 } else {
345 decControl->prevPitchLag = 0;
346 }
347
348 if( lostFlag == FLAG_PACKET_LOST ) {
349 /* On packet loss, remove the gain clamping to prevent having the energy "bounce back"
350 if we lose packets when the energy is going down */
351 for ( i = 0; i < psDec->nChannelsInternal; i++ )
352 psDec->channel_state[ i ].LastGainIndex = 10;
353 } else {
354 psDec->prev_decode_only_middle = decode_only_middle;
355 }
356 RESTORE_STACK;
357 return ret;
358}
359
360#if 0
361/* Getting table of contents for a packet */
362opus_int silk_get_TOC(
363 const opus_uint8 *payload, /* I Payload data */
364 const opus_int nBytesIn, /* I Number of input bytes */
365 const opus_int nFramesPerPayload, /* I Number of SILK frames per payload */
366 silk_TOC_struct *Silk_TOC /* O Type of content */
367)
368{
369 opus_int i, flags, ret = SILK_NO_ERROR;
370
371 if( nBytesIn < 1 ) {
372 return -1;
373 }
374 if( nFramesPerPayload < 0 || nFramesPerPayload > 3 ) {
375 return -1;
376 }
377
378 silk_memset( Silk_TOC, 0, sizeof( *Silk_TOC ) );
379
380 /* For stereo, extract the flags for the mid channel */
381 flags = silk_RSHIFT( payload[ 0 ], 7 - nFramesPerPayload ) & ( silk_LSHIFT( 1, nFramesPerPayload + 1 ) - 1 );
382
383 Silk_TOC->inbandFECFlag = flags & 1;
384 for( i = nFramesPerPayload - 1; i >= 0 ; i-- ) {
385 flags = silk_RSHIFT( flags, 1 );
386 Silk_TOC->VADFlags[ i ] = flags & 1;
387 Silk_TOC->VADFlag |= flags & 1;
388 }
389
390 return ret;
391}
392#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/decode_core.c b/lib/rbcodec/codecs/libopus/silk/decode_core.c
new file mode 100644
index 0000000000..f4ed7e0f6d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/decode_core.c
@@ -0,0 +1,238 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33#include "stack_alloc.h"
34
35/**********************************************************/
36/* Core decoder. Performs inverse NSQ operation LTP + LPC */
37/**********************************************************/
38void silk_decode_core(
39 silk_decoder_state *psDec, /* I/O Decoder state */
40 silk_decoder_control *psDecCtrl, /* I Decoder control */
41 opus_int16 xq[], /* O Decoded speech */
42 const opus_int pulses[ MAX_FRAME_LENGTH ] /* I Pulse signal */
43)
44{
45 opus_int i, k, lag = 0, start_idx, sLTP_buf_idx, NLSF_interpolation_flag, signalType;
46 opus_int16 *A_Q12, *B_Q14, *pxq, A_Q12_tmp[ MAX_LPC_ORDER ];
47 VARDECL( opus_int16, sLTP );
48 VARDECL( opus_int32, sLTP_Q15 );
49 opus_int32 LTP_pred_Q13, LPC_pred_Q10, Gain_Q10, inv_gain_Q31, gain_adj_Q16, rand_seed, offset_Q10;
50 opus_int32 *pred_lag_ptr, *pexc_Q14, *pres_Q14;
51 VARDECL( opus_int32, res_Q14 );
52 VARDECL( opus_int32, sLPC_Q14 );
53 SAVE_STACK;
54
55 silk_assert( psDec->prev_gain_Q16 != 0 );
56
57 ALLOC( sLTP, psDec->ltp_mem_length, opus_int16 );
58 ALLOC( sLTP_Q15, psDec->ltp_mem_length + psDec->frame_length, opus_int32 );
59 ALLOC( res_Q14, psDec->subfr_length, opus_int32 );
60 ALLOC( sLPC_Q14, psDec->subfr_length + MAX_LPC_ORDER, opus_int32 );
61
62 offset_Q10 = silk_Quantization_Offsets_Q10[ psDec->indices.signalType >> 1 ][ psDec->indices.quantOffsetType ];
63
64 if( psDec->indices.NLSFInterpCoef_Q2 < 1 << 2 ) {
65 NLSF_interpolation_flag = 1;
66 } else {
67 NLSF_interpolation_flag = 0;
68 }
69
70 /* Decode excitation */
71 rand_seed = psDec->indices.Seed;
72 for( i = 0; i < psDec->frame_length; i++ ) {
73 rand_seed = silk_RAND( rand_seed );
74 psDec->exc_Q14[ i ] = silk_LSHIFT( (opus_int32)pulses[ i ], 14 );
75 if( psDec->exc_Q14[ i ] > 0 ) {
76 psDec->exc_Q14[ i ] -= QUANT_LEVEL_ADJUST_Q10 << 4;
77 } else
78 if( psDec->exc_Q14[ i ] < 0 ) {
79 psDec->exc_Q14[ i ] += QUANT_LEVEL_ADJUST_Q10 << 4;
80 }
81 psDec->exc_Q14[ i ] += offset_Q10 << 4;
82 if( rand_seed < 0 ) {
83 psDec->exc_Q14[ i ] = -psDec->exc_Q14[ i ];
84 }
85
86 rand_seed = silk_ADD32_ovflw( rand_seed, pulses[ i ] );
87 }
88
89 /* Copy LPC state */
90 silk_memcpy( sLPC_Q14, psDec->sLPC_Q14_buf, MAX_LPC_ORDER * sizeof( opus_int32 ) );
91
92 pexc_Q14 = psDec->exc_Q14;
93 pxq = xq;
94 sLTP_buf_idx = psDec->ltp_mem_length;
95 /* Loop over subframes */
96 for( k = 0; k < psDec->nb_subfr; k++ ) {
97 pres_Q14 = res_Q14;
98 A_Q12 = psDecCtrl->PredCoef_Q12[ k >> 1 ];
99
100 /* Preload LPC coeficients to array on stack. Gives small performance gain */
101 silk_memcpy( A_Q12_tmp, A_Q12, psDec->LPC_order * sizeof( opus_int16 ) );
102 B_Q14 = &psDecCtrl->LTPCoef_Q14[ k * LTP_ORDER ];
103 signalType = psDec->indices.signalType;
104
105 Gain_Q10 = silk_RSHIFT( psDecCtrl->Gains_Q16[ k ], 6 );
106 inv_gain_Q31 = silk_INVERSE32_varQ( psDecCtrl->Gains_Q16[ k ], 47 );
107
108 /* Calculate gain adjustment factor */
109 if( psDecCtrl->Gains_Q16[ k ] != psDec->prev_gain_Q16 ) {
110 gain_adj_Q16 = silk_DIV32_varQ( psDec->prev_gain_Q16, psDecCtrl->Gains_Q16[ k ], 16 );
111
112 /* Scale short term state */
113 for( i = 0; i < MAX_LPC_ORDER; i++ ) {
114 sLPC_Q14[ i ] = silk_SMULWW( gain_adj_Q16, sLPC_Q14[ i ] );
115 }
116 } else {
117 gain_adj_Q16 = (opus_int32)1 << 16;
118 }
119
120 /* Save inv_gain */
121 silk_assert( inv_gain_Q31 != 0 );
122 psDec->prev_gain_Q16 = psDecCtrl->Gains_Q16[ k ];
123
124 /* Avoid abrupt transition from voiced PLC to unvoiced normal decoding */
125 if( psDec->lossCnt && psDec->prevSignalType == TYPE_VOICED &&
126 psDec->indices.signalType != TYPE_VOICED && k < MAX_NB_SUBFR/2 ) {
127
128 silk_memset( B_Q14, 0, LTP_ORDER * sizeof( opus_int16 ) );
129 B_Q14[ LTP_ORDER/2 ] = SILK_FIX_CONST( 0.25, 14 );
130
131 signalType = TYPE_VOICED;
132 psDecCtrl->pitchL[ k ] = psDec->lagPrev;
133 }
134
135 if( signalType == TYPE_VOICED ) {
136 /* Voiced */
137 lag = psDecCtrl->pitchL[ k ];
138
139 /* Re-whitening */
140 if( k == 0 || ( k == 2 && NLSF_interpolation_flag ) ) {
141 /* Rewhiten with new A coefs */
142 start_idx = psDec->ltp_mem_length - lag - psDec->LPC_order - LTP_ORDER / 2;
143 silk_assert( start_idx > 0 );
144
145 if( k == 2 ) {
146 silk_memcpy( &psDec->outBuf[ psDec->ltp_mem_length ], xq, 2 * psDec->subfr_length * sizeof( opus_int16 ) );
147 }
148
149 silk_LPC_analysis_filter( &sLTP[ start_idx ], &psDec->outBuf[ start_idx + k * psDec->subfr_length ],
150 A_Q12, psDec->ltp_mem_length - start_idx, psDec->LPC_order );
151
152 /* After rewhitening the LTP state is unscaled */
153 if( k == 0 ) {
154 /* Do LTP downscaling to reduce inter-packet dependency */
155 inv_gain_Q31 = silk_LSHIFT( silk_SMULWB( inv_gain_Q31, psDecCtrl->LTP_scale_Q14 ), 2 );
156 }
157 for( i = 0; i < lag + LTP_ORDER/2; i++ ) {
158 sLTP_Q15[ sLTP_buf_idx - i - 1 ] = silk_SMULWB( inv_gain_Q31, sLTP[ psDec->ltp_mem_length - i - 1 ] );
159 }
160 } else {
161 /* Update LTP state when Gain changes */
162 if( gain_adj_Q16 != (opus_int32)1 << 16 ) {
163 for( i = 0; i < lag + LTP_ORDER/2; i++ ) {
164 sLTP_Q15[ sLTP_buf_idx - i - 1 ] = silk_SMULWW( gain_adj_Q16, sLTP_Q15[ sLTP_buf_idx - i - 1 ] );
165 }
166 }
167 }
168 }
169
170 /* Long-term prediction */
171 if( signalType == TYPE_VOICED ) {
172 /* Set up pointer */
173 pred_lag_ptr = &sLTP_Q15[ sLTP_buf_idx - lag + LTP_ORDER / 2 ];
174 for( i = 0; i < psDec->subfr_length; i++ ) {
175 /* Unrolled loop */
176 /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
177 LTP_pred_Q13 = 2;
178 LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ 0 ], B_Q14[ 0 ] );
179 LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -1 ], B_Q14[ 1 ] );
180 LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -2 ], B_Q14[ 2 ] );
181 LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -3 ], B_Q14[ 3 ] );
182 LTP_pred_Q13 = silk_SMLAWB( LTP_pred_Q13, pred_lag_ptr[ -4 ], B_Q14[ 4 ] );
183 pred_lag_ptr++;
184
185 /* Generate LPC excitation */
186 pres_Q14[ i ] = silk_ADD_LSHIFT32( pexc_Q14[ i ], LTP_pred_Q13, 1 );
187
188 /* Update states */
189 sLTP_Q15[ sLTP_buf_idx ] = silk_LSHIFT( pres_Q14[ i ], 1 );
190 sLTP_buf_idx++;
191 }
192 } else {
193 pres_Q14 = pexc_Q14;
194 }
195
196 for( i = 0; i < psDec->subfr_length; i++ ) {
197 /* Short-term prediction */
198 silk_assert( psDec->LPC_order == 10 || psDec->LPC_order == 16 );
199 /* Avoids introducing a bias because silk_SMLAWB() always rounds to -inf */
200 LPC_pred_Q10 = silk_RSHIFT( psDec->LPC_order, 1 );
201 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 1 ], A_Q12_tmp[ 0 ] );
202 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 2 ], A_Q12_tmp[ 1 ] );
203 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 3 ], A_Q12_tmp[ 2 ] );
204 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 4 ], A_Q12_tmp[ 3 ] );
205 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 5 ], A_Q12_tmp[ 4 ] );
206 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 6 ], A_Q12_tmp[ 5 ] );
207 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 7 ], A_Q12_tmp[ 6 ] );
208 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 8 ], A_Q12_tmp[ 7 ] );
209 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 9 ], A_Q12_tmp[ 8 ] );
210 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 10 ], A_Q12_tmp[ 9 ] );
211 if( psDec->LPC_order == 16 ) {
212 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 11 ], A_Q12_tmp[ 10 ] );
213 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 12 ], A_Q12_tmp[ 11 ] );
214 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 13 ], A_Q12_tmp[ 12 ] );
215 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 14 ], A_Q12_tmp[ 13 ] );
216 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 15 ], A_Q12_tmp[ 14 ] );
217 LPC_pred_Q10 = silk_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 16 ], A_Q12_tmp[ 15 ] );
218 }
219
220 /* Add prediction to LPC excitation */
221 sLPC_Q14[ MAX_LPC_ORDER + i ] = silk_ADD_LSHIFT32( pres_Q14[ i ], LPC_pred_Q10, 4 );
222
223 /* Scale with gain */
224 pxq[ i ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( silk_SMULWW( sLPC_Q14[ MAX_LPC_ORDER + i ], Gain_Q10 ), 8 ) );
225 }
226
227 /* DEBUG_STORE_DATA( dec.pcm, pxq, psDec->subfr_length * sizeof( opus_int16 ) ) */
228
229 /* Update LPC filter state */
230 silk_memcpy( sLPC_Q14, &sLPC_Q14[ psDec->subfr_length ], MAX_LPC_ORDER * sizeof( opus_int32 ) );
231 pexc_Q14 += psDec->subfr_length;
232 pxq += psDec->subfr_length;
233 }
234
235 /* Save LPC state */
236 silk_memcpy( psDec->sLPC_Q14_buf, sLPC_Q14, MAX_LPC_ORDER * sizeof( opus_int32 ) );
237 RESTORE_STACK;
238}
diff --git a/lib/rbcodec/codecs/libopus/silk/decode_frame.c b/lib/rbcodec/codecs/libopus/silk/decode_frame.c
new file mode 100644
index 0000000000..349df506e5
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/decode_frame.c
@@ -0,0 +1,128 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33#include "stack_alloc.h"
34#include "PLC.h"
35
36/****************/
37/* Decode frame */
38/****************/
39opus_int silk_decode_frame(
40 silk_decoder_state *psDec, /* I/O Pointer to Silk decoder state */
41 ec_dec *psRangeDec, /* I/O Compressor data structure */
42 opus_int16 pOut[], /* O Pointer to output speech frame */
43 opus_int32 *pN, /* O Pointer to size of output frame */
44 opus_int lostFlag, /* I 0: no loss, 1 loss, 2 decode fec */
45 opus_int condCoding /* I The type of conditional coding to use */
46)
47{
48 VARDECL( silk_decoder_control, psDecCtrl );
49 opus_int L, mv_len, ret = 0;
50 VARDECL( opus_int, pulses );
51 SAVE_STACK;
52
53 L = psDec->frame_length;
54 ALLOC( psDecCtrl, 1, silk_decoder_control );
55 ALLOC( pulses, (L + SHELL_CODEC_FRAME_LENGTH - 1) &
56 ~(SHELL_CODEC_FRAME_LENGTH - 1), opus_int );
57 psDecCtrl->LTP_scale_Q14 = 0;
58
59 /* Safety checks */
60 silk_assert( L > 0 && L <= MAX_FRAME_LENGTH );
61
62 if( lostFlag == FLAG_DECODE_NORMAL ||
63 ( lostFlag == FLAG_DECODE_LBRR && psDec->LBRR_flags[ psDec->nFramesDecoded ] == 1 ) )
64 {
65 /*********************************************/
66 /* Decode quantization indices of side info */
67 /*********************************************/
68 silk_decode_indices( psDec, psRangeDec, psDec->nFramesDecoded, lostFlag, condCoding );
69
70 /*********************************************/
71 /* Decode quantization indices of excitation */
72 /*********************************************/
73 silk_decode_pulses( psRangeDec, pulses, psDec->indices.signalType,
74 psDec->indices.quantOffsetType, psDec->frame_length );
75
76 /********************************************/
77 /* Decode parameters and pulse signal */
78 /********************************************/
79 silk_decode_parameters( psDec, psDecCtrl, condCoding );
80
81 /********************************************************/
82 /* Run inverse NSQ */
83 /********************************************************/
84 silk_decode_core( psDec, psDecCtrl, pOut, pulses );
85
86 /********************************************************/
87 /* Update PLC state */
88 /********************************************************/
89 silk_PLC( psDec, psDecCtrl, pOut, 0 );
90
91 psDec->lossCnt = 0;
92 psDec->prevSignalType = psDec->indices.signalType;
93 silk_assert( psDec->prevSignalType >= 0 && psDec->prevSignalType <= 2 );
94
95 /* A frame has been decoded without errors */
96 psDec->first_frame_after_reset = 0;
97 } else {
98 /* Handle packet loss by extrapolation */
99 silk_PLC( psDec, psDecCtrl, pOut, 1 );
100 }
101
102 /*************************/
103 /* Update output buffer. */
104 /*************************/
105 silk_assert( psDec->ltp_mem_length >= psDec->frame_length );
106 mv_len = psDec->ltp_mem_length - psDec->frame_length;
107 silk_memmove( psDec->outBuf, &psDec->outBuf[ psDec->frame_length ], mv_len * sizeof(opus_int16) );
108 silk_memcpy( &psDec->outBuf[ mv_len ], pOut, psDec->frame_length * sizeof( opus_int16 ) );
109
110 /****************************************************************/
111 /* Ensure smooth connection of extrapolated and good frames */
112 /****************************************************************/
113 silk_PLC_glue_frames( psDec, pOut, L );
114
115 /************************************************/
116 /* Comfort noise generation / estimation */
117 /************************************************/
118 silk_CNG( psDec, psDecCtrl, pOut, L );
119
120 /* Update some decoder state variables */
121 psDec->lagPrev = psDecCtrl->pitchL[ psDec->nb_subfr - 1 ];
122
123 /* Set output frame length */
124 *pN = L;
125
126 RESTORE_STACK;
127 return ret;
128}
diff --git a/lib/rbcodec/codecs/libopus/silk/decode_indices.c b/lib/rbcodec/codecs/libopus/silk/decode_indices.c
new file mode 100644
index 0000000000..00eef1de52
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/decode_indices.c
@@ -0,0 +1,151 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Decode side-information parameters from payload */
35void silk_decode_indices(
36 silk_decoder_state *psDec, /* I/O State */
37 ec_dec *psRangeDec, /* I/O Compressor data structure */
38 opus_int FrameIndex, /* I Frame number */
39 opus_int decode_LBRR, /* I Flag indicating LBRR data is being decoded */
40 opus_int condCoding /* I The type of conditional coding to use */
41)
42{
43 opus_int i, k, Ix;
44 opus_int decode_absolute_lagIndex, delta_lagIndex;
45 opus_int16 ec_ix[ MAX_LPC_ORDER ];
46 opus_uint8 pred_Q8[ MAX_LPC_ORDER ];
47
48 /*******************************************/
49 /* Decode signal type and quantizer offset */
50 /*******************************************/
51 if( decode_LBRR || psDec->VAD_flags[ FrameIndex ] ) {
52 Ix = ec_dec_icdf( psRangeDec, silk_type_offset_VAD_iCDF, 8 ) + 2;
53 } else {
54 Ix = ec_dec_icdf( psRangeDec, silk_type_offset_no_VAD_iCDF, 8 );
55 }
56 psDec->indices.signalType = (opus_int8)silk_RSHIFT( Ix, 1 );
57 psDec->indices.quantOffsetType = (opus_int8)( Ix & 1 );
58
59 /****************/
60 /* Decode gains */
61 /****************/
62 /* First subframe */
63 if( condCoding == CODE_CONDITIONALLY ) {
64 /* Conditional coding */
65 psDec->indices.GainsIndices[ 0 ] = (opus_int8)ec_dec_icdf( psRangeDec, silk_delta_gain_iCDF, 8 );
66 } else {
67 /* Independent coding, in two stages: MSB bits followed by 3 LSBs */
68 psDec->indices.GainsIndices[ 0 ] = (opus_int8)silk_LSHIFT( ec_dec_icdf( psRangeDec, silk_gain_iCDF[ psDec->indices.signalType ], 8 ), 3 );
69 psDec->indices.GainsIndices[ 0 ] += (opus_int8)ec_dec_icdf( psRangeDec, silk_uniform8_iCDF, 8 );
70 }
71
72 /* Remaining subframes */
73 for( i = 1; i < psDec->nb_subfr; i++ ) {
74 psDec->indices.GainsIndices[ i ] = (opus_int8)ec_dec_icdf( psRangeDec, silk_delta_gain_iCDF, 8 );
75 }
76
77 /**********************/
78 /* Decode LSF Indices */
79 /**********************/
80 psDec->indices.NLSFIndices[ 0 ] = (opus_int8)ec_dec_icdf( psRangeDec, &psDec->psNLSF_CB->CB1_iCDF[ ( psDec->indices.signalType >> 1 ) * psDec->psNLSF_CB->nVectors ], 8 );
81 silk_NLSF_unpack( ec_ix, pred_Q8, psDec->psNLSF_CB, psDec->indices.NLSFIndices[ 0 ] );
82 silk_assert( psDec->psNLSF_CB->order == psDec->LPC_order );
83 for( i = 0; i < psDec->psNLSF_CB->order; i++ ) {
84 Ix = ec_dec_icdf( psRangeDec, &psDec->psNLSF_CB->ec_iCDF[ ec_ix[ i ] ], 8 );
85 if( Ix == 0 ) {
86 Ix -= ec_dec_icdf( psRangeDec, silk_NLSF_EXT_iCDF, 8 );
87 } else if( Ix == 2 * NLSF_QUANT_MAX_AMPLITUDE ) {
88 Ix += ec_dec_icdf( psRangeDec, silk_NLSF_EXT_iCDF, 8 );
89 }
90 psDec->indices.NLSFIndices[ i+1 ] = (opus_int8)( Ix - NLSF_QUANT_MAX_AMPLITUDE );
91 }
92
93 /* Decode LSF interpolation factor */
94 if( psDec->nb_subfr == MAX_NB_SUBFR ) {
95 psDec->indices.NLSFInterpCoef_Q2 = (opus_int8)ec_dec_icdf( psRangeDec, silk_NLSF_interpolation_factor_iCDF, 8 );
96 } else {
97 psDec->indices.NLSFInterpCoef_Q2 = 4;
98 }
99
100 if( psDec->indices.signalType == TYPE_VOICED )
101 {
102 /*********************/
103 /* Decode pitch lags */
104 /*********************/
105 /* Get lag index */
106 decode_absolute_lagIndex = 1;
107 if( condCoding == CODE_CONDITIONALLY && psDec->ec_prevSignalType == TYPE_VOICED ) {
108 /* Decode Delta index */
109 delta_lagIndex = (opus_int16)ec_dec_icdf( psRangeDec, silk_pitch_delta_iCDF, 8 );
110 if( delta_lagIndex > 0 ) {
111 delta_lagIndex = delta_lagIndex - 9;
112 psDec->indices.lagIndex = (opus_int16)( psDec->ec_prevLagIndex + delta_lagIndex );
113 decode_absolute_lagIndex = 0;
114 }
115 }
116 if( decode_absolute_lagIndex ) {
117 /* Absolute decoding */
118 psDec->indices.lagIndex = (opus_int16)ec_dec_icdf( psRangeDec, silk_pitch_lag_iCDF, 8 ) * silk_RSHIFT( psDec->fs_kHz, 1 );
119 psDec->indices.lagIndex += (opus_int16)ec_dec_icdf( psRangeDec, psDec->pitch_lag_low_bits_iCDF, 8 );
120 }
121 psDec->ec_prevLagIndex = psDec->indices.lagIndex;
122
123 /* Get countour index */
124 psDec->indices.contourIndex = (opus_int8)ec_dec_icdf( psRangeDec, psDec->pitch_contour_iCDF, 8 );
125
126 /********************/
127 /* Decode LTP gains */
128 /********************/
129 /* Decode PERIndex value */
130 psDec->indices.PERIndex = (opus_int8)ec_dec_icdf( psRangeDec, silk_LTP_per_index_iCDF, 8 );
131
132 for( k = 0; k < psDec->nb_subfr; k++ ) {
133 psDec->indices.LTPIndex[ k ] = (opus_int8)ec_dec_icdf( psRangeDec, silk_LTP_gain_iCDF_ptrs[ psDec->indices.PERIndex ], 8 );
134 }
135
136 /**********************/
137 /* Decode LTP scaling */
138 /**********************/
139 if( condCoding == CODE_INDEPENDENTLY ) {
140 psDec->indices.LTP_scaleIndex = (opus_int8)ec_dec_icdf( psRangeDec, silk_LTPscale_iCDF, 8 );
141 } else {
142 psDec->indices.LTP_scaleIndex = 0;
143 }
144 }
145 psDec->ec_prevSignalType = psDec->indices.signalType;
146
147 /***************/
148 /* Decode seed */
149 /***************/
150 psDec->indices.Seed = (opus_int8)ec_dec_icdf( psRangeDec, silk_uniform4_iCDF, 8 );
151}
diff --git a/lib/rbcodec/codecs/libopus/silk/decode_parameters.c b/lib/rbcodec/codecs/libopus/silk/decode_parameters.c
new file mode 100644
index 0000000000..f7c6e2f112
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/decode_parameters.c
@@ -0,0 +1,115 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Decode parameters from payload */
35void silk_decode_parameters(
36 silk_decoder_state *psDec, /* I/O State */
37 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
38 opus_int condCoding /* I The type of conditional coding to use */
39)
40{
41 opus_int i, k, Ix;
42 opus_int16 pNLSF_Q15[ MAX_LPC_ORDER ], pNLSF0_Q15[ MAX_LPC_ORDER ];
43 const opus_int8 *cbk_ptr_Q7;
44
45 /* Dequant Gains */
46 silk_gains_dequant( psDecCtrl->Gains_Q16, psDec->indices.GainsIndices,
47 &psDec->LastGainIndex, condCoding == CODE_CONDITIONALLY, psDec->nb_subfr );
48
49 /****************/
50 /* Decode NLSFs */
51 /****************/
52 silk_NLSF_decode( pNLSF_Q15, psDec->indices.NLSFIndices, psDec->psNLSF_CB );
53
54 /* Convert NLSF parameters to AR prediction filter coefficients */
55 silk_NLSF2A( psDecCtrl->PredCoef_Q12[ 1 ], pNLSF_Q15, psDec->LPC_order );
56
57 /* If just reset, e.g., because internal Fs changed, do not allow interpolation */
58 /* improves the case of packet loss in the first frame after a switch */
59 if( psDec->first_frame_after_reset == 1 ) {
60 psDec->indices.NLSFInterpCoef_Q2 = 4;
61 }
62
63 if( psDec->indices.NLSFInterpCoef_Q2 < 4 ) {
64 /* Calculation of the interpolated NLSF0 vector from the interpolation factor, */
65 /* the previous NLSF1, and the current NLSF1 */
66 for( i = 0; i < psDec->LPC_order; i++ ) {
67 pNLSF0_Q15[ i ] = psDec->prevNLSF_Q15[ i ] + silk_RSHIFT( silk_MUL( psDec->indices.NLSFInterpCoef_Q2,
68 pNLSF_Q15[ i ] - psDec->prevNLSF_Q15[ i ] ), 2 );
69 }
70
71 /* Convert NLSF parameters to AR prediction filter coefficients */
72 silk_NLSF2A( psDecCtrl->PredCoef_Q12[ 0 ], pNLSF0_Q15, psDec->LPC_order );
73 } else {
74 /* Copy LPC coefficients for first half from second half */
75 silk_memcpy( psDecCtrl->PredCoef_Q12[ 0 ], psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order * sizeof( opus_int16 ) );
76 }
77
78 silk_memcpy( psDec->prevNLSF_Q15, pNLSF_Q15, psDec->LPC_order * sizeof( opus_int16 ) );
79
80 /* After a packet loss do BWE of LPC coefs */
81 if( psDec->lossCnt ) {
82 silk_bwexpander( psDecCtrl->PredCoef_Q12[ 0 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 );
83 silk_bwexpander( psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 );
84 }
85
86 if( psDec->indices.signalType == TYPE_VOICED ) {
87 /*********************/
88 /* Decode pitch lags */
89 /*********************/
90
91 /* Decode pitch values */
92 silk_decode_pitch( psDec->indices.lagIndex, psDec->indices.contourIndex, psDecCtrl->pitchL, psDec->fs_kHz, psDec->nb_subfr );
93
94 /* Decode Codebook Index */
95 cbk_ptr_Q7 = silk_LTP_vq_ptrs_Q7[ psDec->indices.PERIndex ]; /* set pointer to start of codebook */
96
97 for( k = 0; k < psDec->nb_subfr; k++ ) {
98 Ix = psDec->indices.LTPIndex[ k ];
99 for( i = 0; i < LTP_ORDER; i++ ) {
100 psDecCtrl->LTPCoef_Q14[ k * LTP_ORDER + i ] = silk_LSHIFT( cbk_ptr_Q7[ Ix * LTP_ORDER + i ], 7 );
101 }
102 }
103
104 /**********************/
105 /* Decode LTP scaling */
106 /**********************/
107 Ix = psDec->indices.LTP_scaleIndex;
108 psDecCtrl->LTP_scale_Q14 = silk_LTPScales_table_Q14[ Ix ];
109 } else {
110 silk_memset( psDecCtrl->pitchL, 0, psDec->nb_subfr * sizeof( opus_int ) );
111 silk_memset( psDecCtrl->LTPCoef_Q14, 0, LTP_ORDER * psDec->nb_subfr * sizeof( opus_int16 ) );
112 psDec->indices.PERIndex = 0;
113 psDecCtrl->LTP_scale_Q14 = 0;
114 }
115}
diff --git a/lib/rbcodec/codecs/libopus/silk/decode_pitch.c b/lib/rbcodec/codecs/libopus/silk/decode_pitch.c
new file mode 100644
index 0000000000..8190a19e51
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/decode_pitch.c
@@ -0,0 +1,77 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32/***********************************************************
33* Pitch analyser function
34********************************************************** */
35#include "SigProc_FIX.h"
36#include "pitch_est_defines.h"
37
38void silk_decode_pitch(
39 opus_int16 lagIndex, /* I */
40 opus_int8 contourIndex, /* O */
41 opus_int pitch_lags[], /* O 4 pitch values */
42 const opus_int Fs_kHz, /* I sampling frequency (kHz) */
43 const opus_int nb_subfr /* I number of sub frames */
44)
45{
46 opus_int lag, k, min_lag, max_lag, cbk_size;
47 const opus_int8 *Lag_CB_ptr;
48
49 if( Fs_kHz == 8 ) {
50 if( nb_subfr == PE_MAX_NB_SUBFR ) {
51 Lag_CB_ptr = &silk_CB_lags_stage2[ 0 ][ 0 ];
52 cbk_size = PE_NB_CBKS_STAGE2_EXT;
53 } else {
54 silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1 );
55 Lag_CB_ptr = &silk_CB_lags_stage2_10_ms[ 0 ][ 0 ];
56 cbk_size = PE_NB_CBKS_STAGE2_10MS;
57 }
58 } else {
59 if( nb_subfr == PE_MAX_NB_SUBFR ) {
60 Lag_CB_ptr = &silk_CB_lags_stage3[ 0 ][ 0 ];
61 cbk_size = PE_NB_CBKS_STAGE3_MAX;
62 } else {
63 silk_assert( nb_subfr == PE_MAX_NB_SUBFR >> 1 );
64 Lag_CB_ptr = &silk_CB_lags_stage3_10_ms[ 0 ][ 0 ];
65 cbk_size = PE_NB_CBKS_STAGE3_10MS;
66 }
67 }
68
69 min_lag = silk_SMULBB( PE_MIN_LAG_MS, Fs_kHz );
70 max_lag = silk_SMULBB( PE_MAX_LAG_MS, Fs_kHz );
71 lag = min_lag + lagIndex;
72
73 for( k = 0; k < nb_subfr; k++ ) {
74 pitch_lags[ k ] = lag + matrix_ptr( Lag_CB_ptr, k, contourIndex, cbk_size );
75 pitch_lags[ k ] = silk_LIMIT( pitch_lags[ k ], min_lag, max_lag );
76 }
77}
diff --git a/lib/rbcodec/codecs/libopus/silk/decode_pulses.c b/lib/rbcodec/codecs/libopus/silk/decode_pulses.c
new file mode 100644
index 0000000000..78fc2032e8
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/decode_pulses.c
@@ -0,0 +1,115 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/*********************************************/
35/* Decode quantization indices of excitation */
36/*********************************************/
37void silk_decode_pulses(
38 ec_dec *psRangeDec, /* I/O Compressor data structure */
39 opus_int pulses[], /* O Excitation signal */
40 const opus_int signalType, /* I Sigtype */
41 const opus_int quantOffsetType, /* I quantOffsetType */
42 const opus_int frame_length /* I Frame length */
43)
44{
45 opus_int i, j, k, iter, abs_q, nLS, RateLevelIndex;
46 opus_int sum_pulses[ MAX_NB_SHELL_BLOCKS ], nLshifts[ MAX_NB_SHELL_BLOCKS ];
47 opus_int *pulses_ptr;
48 const opus_uint8 *cdf_ptr;
49
50 /*********************/
51 /* Decode rate level */
52 /*********************/
53 RateLevelIndex = ec_dec_icdf( psRangeDec, silk_rate_levels_iCDF[ signalType >> 1 ], 8 );
54
55 /* Calculate number of shell blocks */
56 silk_assert( 1 << LOG2_SHELL_CODEC_FRAME_LENGTH == SHELL_CODEC_FRAME_LENGTH );
57 iter = silk_RSHIFT( frame_length, LOG2_SHELL_CODEC_FRAME_LENGTH );
58 if( iter * SHELL_CODEC_FRAME_LENGTH < frame_length ) {
59 silk_assert( frame_length == 12 * 10 ); /* Make sure only happens for 10 ms @ 12 kHz */
60 iter++;
61 }
62
63 /***************************************************/
64 /* Sum-Weighted-Pulses Decoding */
65 /***************************************************/
66 cdf_ptr = silk_pulses_per_block_iCDF[ RateLevelIndex ];
67 for( i = 0; i < iter; i++ ) {
68 nLshifts[ i ] = 0;
69 sum_pulses[ i ] = ec_dec_icdf( psRangeDec, cdf_ptr, 8 );
70
71 /* LSB indication */
72 while( sum_pulses[ i ] == MAX_PULSES + 1 ) {
73 nLshifts[ i ]++;
74 /* When we've already got 10 LSBs, we shift the table to not allow (MAX_PULSES + 1) */
75 sum_pulses[ i ] = ec_dec_icdf( psRangeDec,
76 silk_pulses_per_block_iCDF[ N_RATE_LEVELS - 1] + ( nLshifts[ i ] == 10 ), 8 );
77 }
78 }
79
80 /***************************************************/
81 /* Shell decoding */
82 /***************************************************/
83 for( i = 0; i < iter; i++ ) {
84 if( sum_pulses[ i ] > 0 ) {
85 silk_shell_decoder( &pulses[ silk_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ], psRangeDec, sum_pulses[ i ] );
86 } else {
87 silk_memset( &pulses[ silk_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ], 0, SHELL_CODEC_FRAME_LENGTH * sizeof( opus_int ) );
88 }
89 }
90
91 /***************************************************/
92 /* LSB Decoding */
93 /***************************************************/
94 for( i = 0; i < iter; i++ ) {
95 if( nLshifts[ i ] > 0 ) {
96 nLS = nLshifts[ i ];
97 pulses_ptr = &pulses[ silk_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ];
98 for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {
99 abs_q = pulses_ptr[ k ];
100 for( j = 0; j < nLS; j++ ) {
101 abs_q = silk_LSHIFT( abs_q, 1 );
102 abs_q += ec_dec_icdf( psRangeDec, silk_lsb_iCDF, 8 );
103 }
104 pulses_ptr[ k ] = abs_q;
105 }
106 /* Mark the number of pulses non-zero for sign decoding. */
107 sum_pulses[ i ] |= nLS << 5;
108 }
109 }
110
111 /****************************************/
112 /* Decode and add signs to pulse signal */
113 /****************************************/
114 silk_decode_signs( psRangeDec, pulses, frame_length, signalType, quantOffsetType, sum_pulses );
115}
diff --git a/lib/rbcodec/codecs/libopus/silk/decoder_set_fs.c b/lib/rbcodec/codecs/libopus/silk/decoder_set_fs.c
new file mode 100644
index 0000000000..fcc26d7a0e
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/decoder_set_fs.c
@@ -0,0 +1,108 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Set decoder sampling rate */
35opus_int silk_decoder_set_fs(
36 silk_decoder_state *psDec, /* I/O Decoder state pointer */
37 opus_int fs_kHz, /* I Sampling frequency (kHz) */
38 opus_int32 fs_API_Hz /* I API Sampling frequency (Hz) */
39)
40{
41 opus_int frame_length, ret = 0;
42
43 silk_assert( fs_kHz == 8 || fs_kHz == 12 || fs_kHz == 16 );
44 silk_assert( psDec->nb_subfr == MAX_NB_SUBFR || psDec->nb_subfr == MAX_NB_SUBFR/2 );
45
46 /* New (sub)frame length */
47 psDec->subfr_length = silk_SMULBB( SUB_FRAME_LENGTH_MS, fs_kHz );
48 frame_length = silk_SMULBB( psDec->nb_subfr, psDec->subfr_length );
49
50 /* Initialize resampler when switching internal or external sampling frequency */
51 if( psDec->fs_kHz != fs_kHz || psDec->fs_API_hz != fs_API_Hz ) {
52 /* Initialize the resampler for dec_API.c preparing resampling from fs_kHz to API_fs_Hz */
53 ret += silk_resampler_init( &psDec->resampler_state, silk_SMULBB( fs_kHz, 1000 ), fs_API_Hz, 0 );
54
55 psDec->fs_API_hz = fs_API_Hz;
56 }
57
58 if( psDec->fs_kHz != fs_kHz || frame_length != psDec->frame_length ) {
59 if( fs_kHz == 8 ) {
60 if( psDec->nb_subfr == MAX_NB_SUBFR ) {
61 psDec->pitch_contour_iCDF = silk_pitch_contour_NB_iCDF;
62 } else {
63 psDec->pitch_contour_iCDF = silk_pitch_contour_10_ms_NB_iCDF;
64 }
65 } else {
66 if( psDec->nb_subfr == MAX_NB_SUBFR ) {
67 psDec->pitch_contour_iCDF = silk_pitch_contour_iCDF;
68 } else {
69 psDec->pitch_contour_iCDF = silk_pitch_contour_10_ms_iCDF;
70 }
71 }
72 if( psDec->fs_kHz != fs_kHz ) {
73 psDec->ltp_mem_length = silk_SMULBB( LTP_MEM_LENGTH_MS, fs_kHz );
74 if( fs_kHz == 8 || fs_kHz == 12 ) {
75 psDec->LPC_order = MIN_LPC_ORDER;
76 psDec->psNLSF_CB = &silk_NLSF_CB_NB_MB;
77 } else {
78 psDec->LPC_order = MAX_LPC_ORDER;
79 psDec->psNLSF_CB = &silk_NLSF_CB_WB;
80 }
81 if( fs_kHz == 16 ) {
82 psDec->pitch_lag_low_bits_iCDF = silk_uniform8_iCDF;
83 } else if( fs_kHz == 12 ) {
84 psDec->pitch_lag_low_bits_iCDF = silk_uniform6_iCDF;
85 } else if( fs_kHz == 8 ) {
86 psDec->pitch_lag_low_bits_iCDF = silk_uniform4_iCDF;
87 } else {
88 /* unsupported sampling rate */
89 silk_assert( 0 );
90 }
91 psDec->first_frame_after_reset = 1;
92 psDec->lagPrev = 100;
93 psDec->LastGainIndex = 10;
94 psDec->prevSignalType = TYPE_NO_VOICE_ACTIVITY;
95 silk_memset( psDec->outBuf, 0, sizeof(psDec->outBuf));
96 silk_memset( psDec->sLPC_Q14_buf, 0, sizeof(psDec->sLPC_Q14_buf) );
97 }
98
99 psDec->fs_kHz = fs_kHz;
100 psDec->frame_length = frame_length;
101 }
102
103 /* Check that settings are valid */
104 silk_assert( psDec->frame_length > 0 && psDec->frame_length <= MAX_FRAME_LENGTH );
105
106 return ret;
107}
108
diff --git a/lib/rbcodec/codecs/libopus/silk/define.h b/lib/rbcodec/codecs/libopus/silk/define.h
new file mode 100644
index 0000000000..f74f4869c3
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/define.h
@@ -0,0 +1,235 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_DEFINE_H
29#define SILK_DEFINE_H
30
31#include "errors.h"
32#include "typedef.h"
33
34#ifdef __cplusplus
35extern "C"
36{
37#endif
38
39/* Max number of encoder channels (1/2) */
40#define ENCODER_NUM_CHANNELS 2
41/* Number of decoder channels (1/2) */
42#define DECODER_NUM_CHANNELS 2
43
44#define MAX_FRAMES_PER_PACKET 3
45
46/* Limits on bitrate */
47#define MIN_TARGET_RATE_BPS 5000
48#define MAX_TARGET_RATE_BPS 80000
49#define TARGET_RATE_TAB_SZ 8
50
51/* LBRR thresholds */
52#define LBRR_NB_MIN_RATE_BPS 12000
53#define LBRR_MB_MIN_RATE_BPS 14000
54#define LBRR_WB_MIN_RATE_BPS 16000
55
56/* DTX settings */
57#define NB_SPEECH_FRAMES_BEFORE_DTX 10 /* eq 200 ms */
58#define MAX_CONSECUTIVE_DTX 20 /* eq 400 ms */
59
60/* Maximum sampling frequency */
61#define MAX_FS_KHZ 16
62#define MAX_API_FS_KHZ 48
63
64/* Signal types */
65#define TYPE_NO_VOICE_ACTIVITY 0
66#define TYPE_UNVOICED 1
67#define TYPE_VOICED 2
68
69/* Conditional coding types */
70#define CODE_INDEPENDENTLY 0
71#define CODE_INDEPENDENTLY_NO_LTP_SCALING 1
72#define CODE_CONDITIONALLY 2
73
74/* Settings for stereo processing */
75#define STEREO_QUANT_TAB_SIZE 16
76#define STEREO_QUANT_SUB_STEPS 5
77#define STEREO_INTERP_LEN_MS 8 /* must be even */
78#define STEREO_RATIO_SMOOTH_COEF 0.01 /* smoothing coef for signal norms and stereo width */
79
80/* Range of pitch lag estimates */
81#define PITCH_EST_MIN_LAG_MS 2 /* 2 ms -> 500 Hz */
82#define PITCH_EST_MAX_LAG_MS 18 /* 18 ms -> 56 Hz */
83
84/* Maximum number of subframes */
85#define MAX_NB_SUBFR 4
86
87/* Number of samples per frame */
88#define LTP_MEM_LENGTH_MS 20
89#define SUB_FRAME_LENGTH_MS 5
90#define MAX_SUB_FRAME_LENGTH ( SUB_FRAME_LENGTH_MS * MAX_FS_KHZ )
91#define MAX_FRAME_LENGTH_MS ( SUB_FRAME_LENGTH_MS * MAX_NB_SUBFR )
92#define MAX_FRAME_LENGTH ( MAX_FRAME_LENGTH_MS * MAX_FS_KHZ )
93
94/* Milliseconds of lookahead for pitch analysis */
95#define LA_PITCH_MS 2
96#define LA_PITCH_MAX ( LA_PITCH_MS * MAX_FS_KHZ )
97
98/* Order of LPC used in find pitch */
99#define MAX_FIND_PITCH_LPC_ORDER 16
100
101/* Length of LPC window used in find pitch */
102#define FIND_PITCH_LPC_WIN_MS ( 20 + (LA_PITCH_MS << 1) )
103#define FIND_PITCH_LPC_WIN_MS_2_SF ( 10 + (LA_PITCH_MS << 1) )
104#define FIND_PITCH_LPC_WIN_MAX ( FIND_PITCH_LPC_WIN_MS * MAX_FS_KHZ )
105
106/* Milliseconds of lookahead for noise shape analysis */
107#define LA_SHAPE_MS 5
108#define LA_SHAPE_MAX ( LA_SHAPE_MS * MAX_FS_KHZ )
109
110/* Maximum length of LPC window used in noise shape analysis */
111#define SHAPE_LPC_WIN_MAX ( 15 * MAX_FS_KHZ )
112
113/* dB level of lowest gain quantization level */
114#define MIN_QGAIN_DB 2
115/* dB level of highest gain quantization level */
116#define MAX_QGAIN_DB 88
117/* Number of gain quantization levels */
118#define N_LEVELS_QGAIN 64
119/* Max increase in gain quantization index */
120#define MAX_DELTA_GAIN_QUANT 36
121/* Max decrease in gain quantization index */
122#define MIN_DELTA_GAIN_QUANT -4
123
124/* Quantization offsets (multiples of 4) */
125#define OFFSET_VL_Q10 32
126#define OFFSET_VH_Q10 100
127#define OFFSET_UVL_Q10 100
128#define OFFSET_UVH_Q10 240
129
130#define QUANT_LEVEL_ADJUST_Q10 80
131
132/* Maximum numbers of iterations used to stabilize an LPC vector */
133#define MAX_LPC_STABILIZE_ITERATIONS 16
134#define MAX_PREDICTION_POWER_GAIN 1e4f
135#define MAX_PREDICTION_POWER_GAIN_AFTER_RESET 1e2f
136
137#define MAX_LPC_ORDER 16
138#define MIN_LPC_ORDER 10
139
140/* Find Pred Coef defines */
141#define LTP_ORDER 5
142
143/* LTP quantization settings */
144#define NB_LTP_CBKS 3
145
146/* Flag to use harmonic noise shaping */
147#define USE_HARM_SHAPING 1
148
149/* Max LPC order of noise shaping filters */
150#define MAX_SHAPE_LPC_ORDER 16
151
152#define HARM_SHAPE_FIR_TAPS 3
153
154/* Maximum number of delayed decision states */
155#define MAX_DEL_DEC_STATES 4
156
157#define LTP_BUF_LENGTH 512
158#define LTP_MASK ( LTP_BUF_LENGTH - 1 )
159
160#define DECISION_DELAY 32
161#define DECISION_DELAY_MASK ( DECISION_DELAY - 1 )
162
163/* Number of subframes for excitation entropy coding */
164#define SHELL_CODEC_FRAME_LENGTH 16
165#define LOG2_SHELL_CODEC_FRAME_LENGTH 4
166#define MAX_NB_SHELL_BLOCKS ( MAX_FRAME_LENGTH / SHELL_CODEC_FRAME_LENGTH )
167
168/* Number of rate levels, for entropy coding of excitation */
169#define N_RATE_LEVELS 10
170
171/* Maximum sum of pulses per shell coding frame */
172#define MAX_PULSES 16
173
174#define MAX_MATRIX_SIZE MAX_LPC_ORDER /* Max of LPC Order and LTP order */
175
176#if( MAX_LPC_ORDER > DECISION_DELAY )
177# define NSQ_LPC_BUF_LENGTH MAX_LPC_ORDER
178#else
179# define NSQ_LPC_BUF_LENGTH DECISION_DELAY
180#endif
181
182/***************************/
183/* Voice activity detector */
184/***************************/
185#define VAD_N_BANDS 4
186
187#define VAD_INTERNAL_SUBFRAMES_LOG2 2
188#define VAD_INTERNAL_SUBFRAMES ( 1 << VAD_INTERNAL_SUBFRAMES_LOG2 )
189
190#define VAD_NOISE_LEVEL_SMOOTH_COEF_Q16 1024 /* Must be < 4096 */
191#define VAD_NOISE_LEVELS_BIAS 50
192
193/* Sigmoid settings */
194#define VAD_NEGATIVE_OFFSET_Q5 128 /* sigmoid is 0 at -128 */
195#define VAD_SNR_FACTOR_Q16 45000
196
197/* smoothing for SNR measurement */
198#define VAD_SNR_SMOOTH_COEF_Q18 4096
199
200/* Size of the piecewise linear cosine approximation table for the LSFs */
201#define LSF_COS_TAB_SZ_FIX 128
202
203/******************/
204/* NLSF quantizer */
205/******************/
206#define NLSF_W_Q 2
207#define NLSF_VQ_MAX_VECTORS 32
208#define NLSF_VQ_MAX_SURVIVORS 32
209#define NLSF_QUANT_MAX_AMPLITUDE 4
210#define NLSF_QUANT_MAX_AMPLITUDE_EXT 10
211#define NLSF_QUANT_LEVEL_ADJ 0.1
212#define NLSF_QUANT_DEL_DEC_STATES_LOG2 2
213#define NLSF_QUANT_DEL_DEC_STATES ( 1 << NLSF_QUANT_DEL_DEC_STATES_LOG2 )
214
215/* Transition filtering for mode switching */
216#define TRANSITION_TIME_MS 5120 /* 5120 = 64 * FRAME_LENGTH_MS * ( TRANSITION_INT_NUM - 1 ) = 64*(20*4)*/
217#define TRANSITION_NB 3 /* Hardcoded in tables */
218#define TRANSITION_NA 2 /* Hardcoded in tables */
219#define TRANSITION_INT_NUM 5 /* Hardcoded in tables */
220#define TRANSITION_FRAMES ( TRANSITION_TIME_MS / MAX_FRAME_LENGTH_MS )
221#define TRANSITION_INT_STEPS ( TRANSITION_FRAMES / ( TRANSITION_INT_NUM - 1 ) )
222
223/* BWE factors to apply after packet loss */
224#define BWE_AFTER_LOSS_Q16 63570
225
226/* Defines for CN generation */
227#define CNG_BUF_MASK_MAX 255 /* 2^floor(log2(MAX_FRAME_LENGTH))-1 */
228#define CNG_GAIN_SMTH_Q16 4634 /* 0.25^(1/4) */
229#define CNG_NLSF_SMTH_Q16 16348 /* 0.25 */
230
231#ifdef __cplusplus
232}
233#endif
234
235#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/errors.h b/lib/rbcodec/codecs/libopus/silk/errors.h
new file mode 100644
index 0000000000..0591e0091d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/errors.h
@@ -0,0 +1,98 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_ERRORS_H
29#define SILK_ERRORS_H
30
31#ifdef __cplusplus
32extern "C"
33{
34#endif
35
36/******************/
37/* Error messages */
38/******************/
39#define SILK_NO_ERROR 0
40
41/**************************/
42/* Encoder error messages */
43/**************************/
44
45/* Input length is not a multiple of 10 ms, or length is longer than the packet length */
46#define SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES -101
47
48/* Sampling frequency not 8000, 12000 or 16000 Hertz */
49#define SILK_ENC_FS_NOT_SUPPORTED -102
50
51/* Packet size not 10, 20, 40, or 60 ms */
52#define SILK_ENC_PACKET_SIZE_NOT_SUPPORTED -103
53
54/* Allocated payload buffer too short */
55#define SILK_ENC_PAYLOAD_BUF_TOO_SHORT -104
56
57/* Loss rate not between 0 and 100 percent */
58#define SILK_ENC_INVALID_LOSS_RATE -105
59
60/* Complexity setting not valid, use 0...10 */
61#define SILK_ENC_INVALID_COMPLEXITY_SETTING -106
62
63/* Inband FEC setting not valid, use 0 or 1 */
64#define SILK_ENC_INVALID_INBAND_FEC_SETTING -107
65
66/* DTX setting not valid, use 0 or 1 */
67#define SILK_ENC_INVALID_DTX_SETTING -108
68
69/* CBR setting not valid, use 0 or 1 */
70#define SILK_ENC_INVALID_CBR_SETTING -109
71
72/* Internal encoder error */
73#define SILK_ENC_INTERNAL_ERROR -110
74
75/* Internal encoder error */
76#define SILK_ENC_INVALID_NUMBER_OF_CHANNELS_ERROR -111
77
78/**************************/
79/* Decoder error messages */
80/**************************/
81
82/* Output sampling frequency lower than internal decoded sampling frequency */
83#define SILK_DEC_INVALID_SAMPLING_FREQUENCY -200
84
85/* Payload size exceeded the maximum allowed 1024 bytes */
86#define SILK_DEC_PAYLOAD_TOO_LARGE -201
87
88/* Payload has bit errors */
89#define SILK_DEC_PAYLOAD_ERROR -202
90
91/* Payload has bit errors */
92#define SILK_DEC_INVALID_FRAME_SIZE -203
93
94#ifdef __cplusplus
95}
96#endif
97
98#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/gain_quant.c b/lib/rbcodec/codecs/libopus/silk/gain_quant.c
new file mode 100644
index 0000000000..e91ec937e1
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/gain_quant.c
@@ -0,0 +1,141 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34#define OFFSET ( ( MIN_QGAIN_DB * 128 ) / 6 + 16 * 128 )
35#define SCALE_Q16 ( ( 65536 * ( N_LEVELS_QGAIN - 1 ) ) / ( ( ( MAX_QGAIN_DB - MIN_QGAIN_DB ) * 128 ) / 6 ) )
36#define INV_SCALE_Q16 ( ( 65536 * ( ( ( MAX_QGAIN_DB - MIN_QGAIN_DB ) * 128 ) / 6 ) ) / ( N_LEVELS_QGAIN - 1 ) )
37
38/* Gain scalar quantization with hysteresis, uniform on log scale */
39void silk_gains_quant(
40 opus_int8 ind[ MAX_NB_SUBFR ], /* O gain indices */
41 opus_int32 gain_Q16[ MAX_NB_SUBFR ], /* I/O gains (quantized out) */
42 opus_int8 *prev_ind, /* I/O last index in previous frame */
43 const opus_int conditional, /* I first gain is delta coded if 1 */
44 const opus_int nb_subfr /* I number of subframes */
45)
46{
47 opus_int k, double_step_size_threshold;
48
49 for( k = 0; k < nb_subfr; k++ ) {
50 /* Convert to log scale, scale, floor() */
51 ind[ k ] = silk_SMULWB( SCALE_Q16, silk_lin2log( gain_Q16[ k ] ) - OFFSET );
52
53 /* Round towards previous quantized gain (hysteresis) */
54 if( ind[ k ] < *prev_ind ) {
55 ind[ k ]++;
56 }
57 ind[ k ] = silk_LIMIT_int( ind[ k ], 0, N_LEVELS_QGAIN - 1 );
58
59 /* Compute delta indices and limit */
60 if( k == 0 && conditional == 0 ) {
61 /* Full index */
62 ind[ k ] = silk_LIMIT_int( ind[ k ], *prev_ind + MIN_DELTA_GAIN_QUANT, N_LEVELS_QGAIN - 1 );
63 *prev_ind = ind[ k ];
64 } else {
65 /* Delta index */
66 ind[ k ] = ind[ k ] - *prev_ind;
67
68 /* Double the quantization step size for large gain increases, so that the max gain level can be reached */
69 double_step_size_threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind;
70 if( ind[ k ] > double_step_size_threshold ) {
71 ind[ k ] = double_step_size_threshold + silk_RSHIFT( ind[ k ] - double_step_size_threshold + 1, 1 );
72 }
73
74 ind[ k ] = silk_LIMIT_int( ind[ k ], MIN_DELTA_GAIN_QUANT, MAX_DELTA_GAIN_QUANT );
75
76 /* Accumulate deltas */
77 if( ind[ k ] > double_step_size_threshold ) {
78 *prev_ind += silk_LSHIFT( ind[ k ], 1 ) - double_step_size_threshold;
79 } else {
80 *prev_ind += ind[ k ];
81 }
82
83 /* Shift to make non-negative */
84 ind[ k ] -= MIN_DELTA_GAIN_QUANT;
85 }
86
87 /* Scale and convert to linear scale */
88 gain_Q16[ k ] = silk_log2lin( silk_min_32( silk_SMULWB( INV_SCALE_Q16, *prev_ind ) + OFFSET, 3967 ) ); /* 3967 = 31 in Q7 */
89 }
90}
91
92/* Gains scalar dequantization, uniform on log scale */
93void silk_gains_dequant(
94 opus_int32 gain_Q16[ MAX_NB_SUBFR ], /* O quantized gains */
95 const opus_int8 ind[ MAX_NB_SUBFR ], /* I gain indices */
96 opus_int8 *prev_ind, /* I/O last index in previous frame */
97 const opus_int conditional, /* I first gain is delta coded if 1 */
98 const opus_int nb_subfr /* I number of subframes */
99)
100{
101 opus_int k, ind_tmp, double_step_size_threshold;
102
103 for( k = 0; k < nb_subfr; k++ ) {
104 if( k == 0 && conditional == 0 ) {
105 /* Gain index is not allowed to go down more than 16 steps (~21.8 dB) */
106 *prev_ind = silk_max_int( ind[ k ], *prev_ind - 16 );
107 } else {
108 /* Delta index */
109 ind_tmp = ind[ k ] + MIN_DELTA_GAIN_QUANT;
110
111 /* Accumulate deltas */
112 double_step_size_threshold = 2 * MAX_DELTA_GAIN_QUANT - N_LEVELS_QGAIN + *prev_ind;
113 if( ind_tmp > double_step_size_threshold ) {
114 *prev_ind += silk_LSHIFT( ind_tmp, 1 ) - double_step_size_threshold;
115 } else {
116 *prev_ind += ind_tmp;
117 }
118 }
119 *prev_ind = silk_LIMIT_int( *prev_ind, 0, N_LEVELS_QGAIN - 1 );
120
121 /* Scale and convert to linear scale */
122 gain_Q16[ k ] = silk_log2lin( silk_min_32( silk_SMULWB( INV_SCALE_Q16, *prev_ind ) + OFFSET, 3967 ) ); /* 3967 = 31 in Q7 */
123 }
124}
125
126/* Compute unique identifier of gain indices vector */
127opus_int32 silk_gains_ID( /* O returns unique identifier of gains */
128 const opus_int8 ind[ MAX_NB_SUBFR ], /* I gain indices */
129 const opus_int nb_subfr /* I number of subframes */
130)
131{
132 opus_int k;
133 opus_int32 gainsID;
134
135 gainsID = 0;
136 for( k = 0; k < nb_subfr; k++ ) {
137 gainsID = silk_ADD_LSHIFT32( ind[ k ], gainsID, 8 );
138 }
139
140 return gainsID;
141}
diff --git a/lib/rbcodec/codecs/libopus/silk/init_decoder.c b/lib/rbcodec/codecs/libopus/silk/init_decoder.c
new file mode 100644
index 0000000000..139cf02014
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/init_decoder.c
@@ -0,0 +1,56 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/************************/
35/* Init Decoder State */
36/************************/
37opus_int silk_init_decoder(
38 silk_decoder_state *psDec /* I/O Decoder state pointer */
39)
40{
41 /* Clear the entire encoder state, except anything copied */
42 silk_memset( psDec, 0, sizeof( silk_decoder_state ) );
43
44 /* Used to deactivate LSF interpolation */
45 psDec->first_frame_after_reset = 1;
46 psDec->prev_gain_Q16 = 65536;
47
48 /* Reset CNG state */
49 silk_CNG_Reset( psDec );
50
51 /* Reset PLC state */
52 silk_PLC_Reset( psDec );
53
54 return(0);
55}
56
diff --git a/lib/rbcodec/codecs/libopus/silk/lin2log.c b/lib/rbcodec/codecs/libopus/silk/lin2log.c
new file mode 100644
index 0000000000..68ea030c89
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/lin2log.c
@@ -0,0 +1,46 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33/* Approximation of 128 * log2() (very close inverse of silk_log2lin()) */
34/* Convert input to a log scale */
35opus_int32 silk_lin2log(
36 const opus_int32 inLin /* I input in linear scale */
37)
38{
39 opus_int32 lz, frac_Q7;
40
41 silk_CLZ_FRAC( inLin, &lz, &frac_Q7 );
42
43 /* Piece-wise parabolic approximation */
44 return silk_LSHIFT( 31 - lz, 7 ) + silk_SMLAWB( frac_Q7, silk_MUL( frac_Q7, 128 - frac_Q7 ), 179 );
45}
46
diff --git a/lib/rbcodec/codecs/libopus/silk/log2lin.c b/lib/rbcodec/codecs/libopus/silk/log2lin.c
new file mode 100644
index 0000000000..d80472c69f
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/log2lin.c
@@ -0,0 +1,56 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33
34/* Approximation of 2^() (very close inverse of silk_lin2log()) */
35/* Convert input to a linear scale */
36opus_int32 silk_log2lin(
37 const opus_int32 inLog_Q7 /* I input on log scale */
38)
39{
40 opus_int32 out, frac_Q7;
41
42 if( inLog_Q7 < 0 ) {
43 return 0;
44 }
45
46 out = silk_LSHIFT( 1, silk_RSHIFT( inLog_Q7, 7 ) );
47 frac_Q7 = inLog_Q7 & 0x7F;
48 if( inLog_Q7 < 2048 ) {
49 /* Piece-wise parabolic approximation */
50 out = silk_ADD_RSHIFT32( out, silk_MUL( out, silk_SMLAWB( frac_Q7, silk_SMULBB( frac_Q7, 128 - frac_Q7 ), -174 ) ), 7 );
51 } else {
52 /* Piece-wise parabolic approximation */
53 out = silk_MLA( out, silk_RSHIFT( out, 7 ), silk_SMLAWB( frac_Q7, silk_SMULBB( frac_Q7, 128 - frac_Q7 ), -174 ) );
54 }
55 return out;
56}
diff --git a/lib/rbcodec/codecs/libopus/silk/macros.h b/lib/rbcodec/codecs/libopus/silk/macros.h
new file mode 100644
index 0000000000..d84cd73522
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/macros.h
@@ -0,0 +1,135 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_MACROS_H
29#define SILK_MACROS_H
30
31#ifdef HAVE_CONFIG_H
32#include "opus_config.h"
33#endif
34
35/* This is an inline header file for general platform. */
36
37/* (a32 * (opus_int32)((opus_int16)(b32))) >> 16 output have to be 32bit int */
38#define silk_SMULWB(a32, b32) ((((a32) >> 16) * (opus_int32)((opus_int16)(b32))) + ((((a32) & 0x0000FFFF) * (opus_int32)((opus_int16)(b32))) >> 16))
39
40/* a32 + (b32 * (opus_int32)((opus_int16)(c32))) >> 16 output have to be 32bit int */
41#define silk_SMLAWB(a32, b32, c32) ((a32) + ((((b32) >> 16) * (opus_int32)((opus_int16)(c32))) + ((((b32) & 0x0000FFFF) * (opus_int32)((opus_int16)(c32))) >> 16)))
42
43/* (a32 * (b32 >> 16)) >> 16 */
44#define silk_SMULWT(a32, b32) (((a32) >> 16) * ((b32) >> 16) + ((((a32) & 0x0000FFFF) * ((b32) >> 16)) >> 16))
45
46/* a32 + (b32 * (c32 >> 16)) >> 16 */
47#define silk_SMLAWT(a32, b32, c32) ((a32) + (((b32) >> 16) * ((c32) >> 16)) + ((((b32) & 0x0000FFFF) * ((c32) >> 16)) >> 16))
48
49/* (opus_int32)((opus_int16)(a3))) * (opus_int32)((opus_int16)(b32)) output have to be 32bit int */
50#define silk_SMULBB(a32, b32) ((opus_int32)((opus_int16)(a32)) * (opus_int32)((opus_int16)(b32)))
51
52/* a32 + (opus_int32)((opus_int16)(b32)) * (opus_int32)((opus_int16)(c32)) output have to be 32bit int */
53#define silk_SMLABB(a32, b32, c32) ((a32) + ((opus_int32)((opus_int16)(b32))) * (opus_int32)((opus_int16)(c32)))
54
55/* (opus_int32)((opus_int16)(a32)) * (b32 >> 16) */
56#define silk_SMULBT(a32, b32) ((opus_int32)((opus_int16)(a32)) * ((b32) >> 16))
57
58/* a32 + (opus_int32)((opus_int16)(b32)) * (c32 >> 16) */
59#define silk_SMLABT(a32, b32, c32) ((a32) + ((opus_int32)((opus_int16)(b32))) * ((c32) >> 16))
60
61/* a64 + (b32 * c32) */
62#define silk_SMLAL(a64, b32, c32) (silk_ADD64((a64), ((opus_int64)(b32) * (opus_int64)(c32))))
63
64/* (a32 * b32) >> 16 */
65#define silk_SMULWW(a32, b32) silk_MLA(silk_SMULWB((a32), (b32)), (a32), silk_RSHIFT_ROUND((b32), 16))
66
67/* a32 + ((b32 * c32) >> 16) */
68#define silk_SMLAWW(a32, b32, c32) silk_MLA(silk_SMLAWB((a32), (b32), (c32)), (b32), silk_RSHIFT_ROUND((c32), 16))
69
70/* add/subtract with output saturated */
71#define silk_ADD_SAT32(a, b) ((((opus_uint32)(a) + (opus_uint32)(b)) & 0x80000000) == 0 ? \
72 ((((a) & (b)) & 0x80000000) != 0 ? silk_int32_MIN : (a)+(b)) : \
73 ((((a) | (b)) & 0x80000000) == 0 ? silk_int32_MAX : (a)+(b)) )
74
75#define silk_SUB_SAT32(a, b) ((((opus_uint32)(a)-(opus_uint32)(b)) & 0x80000000) == 0 ? \
76 (( (a) & ((b)^0x80000000) & 0x80000000) ? silk_int32_MIN : (a)-(b)) : \
77 ((((a)^0x80000000) & (b) & 0x80000000) ? silk_int32_MAX : (a)-(b)) )
78
79static inline opus_int32 silk_CLZ16(opus_int16 in16)
80{
81 opus_int32 out32 = 0;
82 if( in16 == 0 ) {
83 return 16;
84 }
85 /* test nibbles */
86 if( in16 & 0xFF00 ) {
87 if( in16 & 0xF000 ) {
88 in16 >>= 12;
89 } else {
90 out32 += 4;
91 in16 >>= 8;
92 }
93 } else {
94 if( in16 & 0xFFF0 ) {
95 out32 += 8;
96 in16 >>= 4;
97 } else {
98 out32 += 12;
99 }
100 }
101 /* test bits and return */
102 if( in16 & 0xC ) {
103 if( in16 & 0x8 )
104 return out32 + 0;
105 else
106 return out32 + 1;
107 } else {
108 if( in16 & 0xE )
109 return out32 + 2;
110 else
111 return out32 + 3;
112 }
113}
114
115static inline opus_int32 silk_CLZ32(opus_int32 in32)
116{
117 /* test highest 16 bits and convert to opus_int16 */
118 if( in32 & 0xFFFF0000 ) {
119 return silk_CLZ16((opus_int16)(in32 >> 16));
120 } else {
121 return silk_CLZ16((opus_int16)in32) + 16;
122 }
123}
124
125/* Row based */
126#define matrix_ptr(Matrix_base_adr, row, column, N) *(Matrix_base_adr + ((row)*(N)+(column)))
127#define matrix_adr(Matrix_base_adr, row, column, N) (Matrix_base_adr + ((row)*(N)+(column)))
128
129/* Column based */
130#ifndef matrix_c_ptr
131# define matrix_c_ptr(Matrix_base_adr, row, column, M) *(Matrix_base_adr + ((row)+(M)*(column)))
132#endif
133
134#endif /* SILK_MACROS_H */
135
diff --git a/lib/rbcodec/codecs/libopus/silk/main.h b/lib/rbcodec/codecs/libopus/silk/main.h
new file mode 100644
index 0000000000..32675f6931
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/main.h
@@ -0,0 +1,434 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_MAIN_H
29#define SILK_MAIN_H
30
31#include "SigProc_FIX.h"
32#include "define.h"
33#include "structs.h"
34#include "tables.h"
35#include "PLC.h"
36#include "control.h"
37#include "debug.h"
38#include "entenc.h"
39#include "entdec.h"
40
41/* Convert Left/Right stereo signal to adaptive Mid/Side representation */
42void silk_stereo_LR_to_MS(
43 stereo_enc_state *state, /* I/O State */
44 opus_int16 x1[], /* I/O Left input signal, becomes mid signal */
45 opus_int16 x2[], /* I/O Right input signal, becomes side signal */
46 opus_int8 ix[ 2 ][ 3 ], /* O Quantization indices */
47 opus_int8 *mid_only_flag, /* O Flag: only mid signal coded */
48 opus_int32 mid_side_rates_bps[], /* O Bitrates for mid and side signals */
49 opus_int32 total_rate_bps, /* I Total bitrate */
50 opus_int prev_speech_act_Q8, /* I Speech activity level in previous frame */
51 opus_int toMono, /* I Last frame before a stereo->mono transition */
52 opus_int fs_kHz, /* I Sample rate (kHz) */
53 opus_int frame_length /* I Number of samples */
54);
55
56/* Convert adaptive Mid/Side representation to Left/Right stereo signal */
57void silk_stereo_MS_to_LR(
58 stereo_dec_state *state, /* I/O State */
59 opus_int16 x1[], /* I/O Left input signal, becomes mid signal */
60 opus_int16 x2[], /* I/O Right input signal, becomes side signal */
61 const opus_int32 pred_Q13[], /* I Predictors */
62 opus_int fs_kHz, /* I Samples rate (kHz) */
63 opus_int frame_length /* I Number of samples */
64);
65
66/* Find least-squares prediction gain for one signal based on another and quantize it */
67opus_int32 silk_stereo_find_predictor( /* O Returns predictor in Q13 */
68 opus_int32 *ratio_Q14, /* O Ratio of residual and mid energies */
69 const opus_int16 x[], /* I Basis signal */
70 const opus_int16 y[], /* I Target signal */
71 opus_int32 mid_res_amp_Q0[], /* I/O Smoothed mid, residual norms */
72 opus_int length, /* I Number of samples */
73 opus_int smooth_coef_Q16 /* I Smoothing coefficient */
74);
75
76/* Quantize mid/side predictors */
77void silk_stereo_quant_pred(
78 opus_int32 pred_Q13[], /* I/O Predictors (out: quantized) */
79 opus_int8 ix[ 2 ][ 3 ] /* O Quantization indices */
80);
81
82/* Entropy code the mid/side quantization indices */
83void silk_stereo_encode_pred(
84 ec_enc *psRangeEnc, /* I/O Compressor data structure */
85 opus_int8 ix[ 2 ][ 3 ] /* I Quantization indices */
86);
87
88/* Entropy code the mid-only flag */
89void silk_stereo_encode_mid_only(
90 ec_enc *psRangeEnc, /* I/O Compressor data structure */
91 opus_int8 mid_only_flag
92);
93
94/* Decode mid/side predictors */
95void silk_stereo_decode_pred(
96 ec_dec *psRangeDec, /* I/O Compressor data structure */
97 opus_int32 pred_Q13[] /* O Predictors */
98);
99
100/* Decode mid-only flag */
101void silk_stereo_decode_mid_only(
102 ec_dec *psRangeDec, /* I/O Compressor data structure */
103 opus_int *decode_only_mid /* O Flag that only mid channel has been coded */
104);
105
106/* Encodes signs of excitation */
107void silk_encode_signs(
108 ec_enc *psRangeEnc, /* I/O Compressor data structure */
109 const opus_int8 pulses[], /* I pulse signal */
110 opus_int length, /* I length of input */
111 const opus_int signalType, /* I Signal type */
112 const opus_int quantOffsetType, /* I Quantization offset type */
113 const opus_int sum_pulses[ MAX_NB_SHELL_BLOCKS ] /* I Sum of absolute pulses per block */
114);
115
116/* Decodes signs of excitation */
117void silk_decode_signs(
118 ec_dec *psRangeDec, /* I/O Compressor data structure */
119 opus_int pulses[], /* I/O pulse signal */
120 opus_int length, /* I length of input */
121 const opus_int signalType, /* I Signal type */
122 const opus_int quantOffsetType, /* I Quantization offset type */
123 const opus_int sum_pulses[ MAX_NB_SHELL_BLOCKS ] /* I Sum of absolute pulses per block */
124);
125
126/* Check encoder control struct */
127opus_int check_control_input(
128 silk_EncControlStruct *encControl /* I Control structure */
129);
130
131/* Control internal sampling rate */
132opus_int silk_control_audio_bandwidth(
133 silk_encoder_state *psEncC, /* I/O Pointer to Silk encoder state */
134 silk_EncControlStruct *encControl /* I Control structure */
135);
136
137/* Control SNR of redidual quantizer */
138opus_int silk_control_SNR(
139 silk_encoder_state *psEncC, /* I/O Pointer to Silk encoder state */
140 opus_int32 TargetRate_bps /* I Target max bitrate (bps) */
141);
142
143/***************/
144/* Shell coder */
145/***************/
146
147/* Encode quantization indices of excitation */
148void silk_encode_pulses(
149 ec_enc *psRangeEnc, /* I/O compressor data structure */
150 const opus_int signalType, /* I Signal type */
151 const opus_int quantOffsetType, /* I quantOffsetType */
152 opus_int8 pulses[], /* I quantization indices */
153 const opus_int frame_length /* I Frame length */
154);
155
156/* Shell encoder, operates on one shell code frame of 16 pulses */
157void silk_shell_encoder(
158 ec_enc *psRangeEnc, /* I/O compressor data structure */
159 const opus_int *pulses0 /* I data: nonnegative pulse amplitudes */
160);
161
162/* Shell decoder, operates on one shell code frame of 16 pulses */
163void silk_shell_decoder(
164 opus_int *pulses0, /* O data: nonnegative pulse amplitudes */
165 ec_dec *psRangeDec, /* I/O Compressor data structure */
166 const opus_int pulses4 /* I number of pulses per pulse-subframe */
167);
168
169/* Gain scalar quantization with hysteresis, uniform on log scale */
170void silk_gains_quant(
171 opus_int8 ind[ MAX_NB_SUBFR ], /* O gain indices */
172 opus_int32 gain_Q16[ MAX_NB_SUBFR ], /* I/O gains (quantized out) */
173 opus_int8 *prev_ind, /* I/O last index in previous frame */
174 const opus_int conditional, /* I first gain is delta coded if 1 */
175 const opus_int nb_subfr /* I number of subframes */
176);
177
178/* Gains scalar dequantization, uniform on log scale */
179void silk_gains_dequant(
180 opus_int32 gain_Q16[ MAX_NB_SUBFR ], /* O quantized gains */
181 const opus_int8 ind[ MAX_NB_SUBFR ], /* I gain indices */
182 opus_int8 *prev_ind, /* I/O last index in previous frame */
183 const opus_int conditional, /* I first gain is delta coded if 1 */
184 const opus_int nb_subfr /* I number of subframes */
185);
186
187/* Compute unique identifier of gain indices vector */
188opus_int32 silk_gains_ID( /* O returns unique identifier of gains */
189 const opus_int8 ind[ MAX_NB_SUBFR ], /* I gain indices */
190 const opus_int nb_subfr /* I number of subframes */
191);
192
193/* Interpolate two vectors */
194void silk_interpolate(
195 opus_int16 xi[ MAX_LPC_ORDER ], /* O interpolated vector */
196 const opus_int16 x0[ MAX_LPC_ORDER ], /* I first vector */
197 const opus_int16 x1[ MAX_LPC_ORDER ], /* I second vector */
198 const opus_int ifact_Q2, /* I interp. factor, weight on 2nd vector */
199 const opus_int d /* I number of parameters */
200);
201
202/* LTP tap quantizer */
203void silk_quant_LTP_gains(
204 opus_int16 B_Q14[ MAX_NB_SUBFR * LTP_ORDER ], /* I/O (un)quantized LTP gains */
205 opus_int8 cbk_index[ MAX_NB_SUBFR ], /* O Codebook Index */
206 opus_int8 *periodicity_index, /* O Periodicity Index */
207 const opus_int32 W_Q18[ MAX_NB_SUBFR*LTP_ORDER*LTP_ORDER ], /* I Error Weights in Q18 */
208 opus_int mu_Q9, /* I Mu value (R/D tradeoff) */
209 opus_int lowComplexity, /* I Flag for low complexity */
210 const opus_int nb_subfr /* I number of subframes */
211);
212
213/* Entropy constrained matrix-weighted VQ, for a single input data vector */
214void silk_VQ_WMat_EC(
215 opus_int8 *ind, /* O index of best codebook vector */
216 opus_int32 *rate_dist_Q14, /* O best weighted quant error + mu * rate */
217 const opus_int16 *in_Q14, /* I input vector to be quantized */
218 const opus_int32 *W_Q18, /* I weighting matrix */
219 const opus_int8 *cb_Q7, /* I codebook */
220 const opus_uint8 *cl_Q5, /* I code length for each codebook vector */
221 const opus_int mu_Q9, /* I tradeoff betw. weighted error and rate */
222 opus_int L /* I number of vectors in codebook */
223);
224
225/************************************/
226/* Noise shaping quantization (NSQ) */
227/************************************/
228void silk_NSQ(
229 const silk_encoder_state *psEncC, /* I/O Encoder State */
230 silk_nsq_state *NSQ, /* I/O NSQ state */
231 SideInfoIndices *psIndices, /* I/O Quantization Indices */
232 const opus_int32 x_Q3[], /* I Prefiltered input signal */
233 opus_int8 pulses[], /* O Quantized pulse signal */
234 const opus_int16 PredCoef_Q12[ 2 * MAX_LPC_ORDER ], /* I Short term prediction coefs */
235 const opus_int16 LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ], /* I Long term prediction coefs */
236 const opus_int16 AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs */
237 const opus_int HarmShapeGain_Q14[ MAX_NB_SUBFR ], /* I Long term shaping coefs */
238 const opus_int Tilt_Q14[ MAX_NB_SUBFR ], /* I Spectral tilt */
239 const opus_int32 LF_shp_Q14[ MAX_NB_SUBFR ], /* I Low frequency shaping coefs */
240 const opus_int32 Gains_Q16[ MAX_NB_SUBFR ], /* I Quantization step sizes */
241 const opus_int pitchL[ MAX_NB_SUBFR ], /* I Pitch lags */
242 const opus_int Lambda_Q10, /* I Rate/distortion tradeoff */
243 const opus_int LTP_scale_Q14 /* I LTP state scaling */
244);
245
246/* Noise shaping using delayed decision */
247void silk_NSQ_del_dec(
248 const silk_encoder_state *psEncC, /* I/O Encoder State */
249 silk_nsq_state *NSQ, /* I/O NSQ state */
250 SideInfoIndices *psIndices, /* I/O Quantization Indices */
251 const opus_int32 x_Q3[], /* I Prefiltered input signal */
252 opus_int8 pulses[], /* O Quantized pulse signal */
253 const opus_int16 PredCoef_Q12[ 2 * MAX_LPC_ORDER ], /* I Short term prediction coefs */
254 const opus_int16 LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ], /* I Long term prediction coefs */
255 const opus_int16 AR2_Q13[ MAX_NB_SUBFR * MAX_SHAPE_LPC_ORDER ], /* I Noise shaping coefs */
256 const opus_int HarmShapeGain_Q14[ MAX_NB_SUBFR ], /* I Long term shaping coefs */
257 const opus_int Tilt_Q14[ MAX_NB_SUBFR ], /* I Spectral tilt */
258 const opus_int32 LF_shp_Q14[ MAX_NB_SUBFR ], /* I Low frequency shaping coefs */
259 const opus_int32 Gains_Q16[ MAX_NB_SUBFR ], /* I Quantization step sizes */
260 const opus_int pitchL[ MAX_NB_SUBFR ], /* I Pitch lags */
261 const opus_int Lambda_Q10, /* I Rate/distortion tradeoff */
262 const opus_int LTP_scale_Q14 /* I LTP state scaling */
263);
264
265/************/
266/* Silk VAD */
267/************/
268/* Initialize the Silk VAD */
269opus_int silk_VAD_Init( /* O Return value, 0 if success */
270 silk_VAD_state *psSilk_VAD /* I/O Pointer to Silk VAD state */
271);
272
273/* Get speech activity level in Q8 */
274opus_int silk_VAD_GetSA_Q8( /* O Return value, 0 if success */
275 silk_encoder_state *psEncC, /* I/O Encoder state */
276 const opus_int16 pIn[] /* I PCM input */
277);
278
279/* Low-pass filter with variable cutoff frequency based on */
280/* piece-wise linear interpolation between elliptic filters */
281/* Start by setting transition_frame_no = 1; */
282void silk_LP_variable_cutoff(
283 silk_LP_state *psLP, /* I/O LP filter state */
284 opus_int16 *frame, /* I/O Low-pass filtered output signal */
285 const opus_int frame_length /* I Frame length */
286);
287
288/******************/
289/* NLSF Quantizer */
290/******************/
291/* Limit, stabilize, convert and quantize NLSFs */
292void silk_process_NLSFs(
293 silk_encoder_state *psEncC, /* I/O Encoder state */
294 opus_int16 PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ], /* O Prediction coefficients */
295 opus_int16 pNLSF_Q15[ MAX_LPC_ORDER ], /* I/O Normalized LSFs (quant out) (0 - (2^15-1)) */
296 const opus_int16 prev_NLSFq_Q15[ MAX_LPC_ORDER ] /* I Previous Normalized LSFs (0 - (2^15-1)) */
297);
298
299opus_int32 silk_NLSF_encode( /* O Returns RD value in Q25 */
300 opus_int8 *NLSFIndices, /* I Codebook path vector [ LPC_ORDER + 1 ] */
301 opus_int16 *pNLSF_Q15, /* I/O Quantized NLSF vector [ LPC_ORDER ] */
302 const silk_NLSF_CB_struct *psNLSF_CB, /* I Codebook object */
303 const opus_int16 *pW_QW, /* I NLSF weight vector [ LPC_ORDER ] */
304 const opus_int NLSF_mu_Q20, /* I Rate weight for the RD optimization */
305 const opus_int nSurvivors, /* I Max survivors after first stage */
306 const opus_int signalType /* I Signal type: 0/1/2 */
307);
308
309/* Compute quantization errors for an LPC_order element input vector for a VQ codebook */
310void silk_NLSF_VQ(
311 opus_int32 err_Q26[], /* O Quantization errors [K] */
312 const opus_int16 in_Q15[], /* I Input vectors to be quantized [LPC_order] */
313 const opus_uint8 pCB_Q8[], /* I Codebook vectors [K*LPC_order] */
314 const opus_int K, /* I Number of codebook vectors */
315 const opus_int LPC_order /* I Number of LPCs */
316);
317
318/* Delayed-decision quantizer for NLSF residuals */
319opus_int32 silk_NLSF_del_dec_quant( /* O Returns RD value in Q25 */
320 opus_int8 indices[], /* O Quantization indices [ order ] */
321 const opus_int16 x_Q10[], /* I Input [ order ] */
322 const opus_int16 w_Q5[], /* I Weights [ order ] */
323 const opus_uint8 pred_coef_Q8[], /* I Backward predictor coefs [ order ] */
324 const opus_int16 ec_ix[], /* I Indices to entropy coding tables [ order ] */
325 const opus_uint8 ec_rates_Q5[], /* I Rates [] */
326 const opus_int quant_step_size_Q16, /* I Quantization step size */
327 const opus_int16 inv_quant_step_size_Q6, /* I Inverse quantization step size */
328 const opus_int32 mu_Q20, /* I R/D tradeoff */
329 const opus_int16 order /* I Number of input values */
330);
331
332/* Unpack predictor values and indices for entropy coding tables */
333void silk_NLSF_unpack(
334 opus_int16 ec_ix[], /* O Indices to entropy tables [ LPC_ORDER ] */
335 opus_uint8 pred_Q8[], /* O LSF predictor [ LPC_ORDER ] */
336 const silk_NLSF_CB_struct *psNLSF_CB, /* I Codebook object */
337 const opus_int CB1_index /* I Index of vector in first LSF codebook */
338);
339
340/***********************/
341/* NLSF vector decoder */
342/***********************/
343void silk_NLSF_decode(
344 opus_int16 *pNLSF_Q15, /* O Quantized NLSF vector [ LPC_ORDER ] */
345 opus_int8 *NLSFIndices, /* I Codebook path vector [ LPC_ORDER + 1 ] */
346 const silk_NLSF_CB_struct *psNLSF_CB /* I Codebook object */
347);
348
349/****************************************************/
350/* Decoder Functions */
351/****************************************************/
352opus_int silk_init_decoder(
353 silk_decoder_state *psDec /* I/O Decoder state pointer */
354);
355
356/* Set decoder sampling rate */
357opus_int silk_decoder_set_fs(
358 silk_decoder_state *psDec, /* I/O Decoder state pointer */
359 opus_int fs_kHz, /* I Sampling frequency (kHz) */
360 opus_int32 fs_API_Hz /* I API Sampling frequency (Hz) */
361);
362
363/****************/
364/* Decode frame */
365/****************/
366opus_int silk_decode_frame(
367 silk_decoder_state *psDec, /* I/O Pointer to Silk decoder state */
368 ec_dec *psRangeDec, /* I/O Compressor data structure */
369 opus_int16 pOut[], /* O Pointer to output speech frame */
370 opus_int32 *pN, /* O Pointer to size of output frame */
371 opus_int lostFlag, /* I 0: no loss, 1 loss, 2 decode fec */
372 opus_int condCoding /* I The type of conditional coding to use */
373);
374
375/* Decode indices from bitstream */
376void silk_decode_indices(
377 silk_decoder_state *psDec, /* I/O State */
378 ec_dec *psRangeDec, /* I/O Compressor data structure */
379 opus_int FrameIndex, /* I Frame number */
380 opus_int decode_LBRR, /* I Flag indicating LBRR data is being decoded */
381 opus_int condCoding /* I The type of conditional coding to use */
382);
383
384/* Decode parameters from payload */
385void silk_decode_parameters(
386 silk_decoder_state *psDec, /* I/O State */
387 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
388 opus_int condCoding /* I The type of conditional coding to use */
389);
390
391/* Core decoder. Performs inverse NSQ operation LTP + LPC */
392void silk_decode_core(
393 silk_decoder_state *psDec, /* I/O Decoder state */
394 silk_decoder_control *psDecCtrl, /* I Decoder control */
395 opus_int16 xq[], /* O Decoded speech */
396 const opus_int pulses[ MAX_FRAME_LENGTH ] /* I Pulse signal */
397);
398
399/* Decode quantization indices of excitation (Shell coding) */
400void silk_decode_pulses(
401 ec_dec *psRangeDec, /* I/O Compressor data structure */
402 opus_int pulses[], /* O Excitation signal */
403 const opus_int signalType, /* I Sigtype */
404 const opus_int quantOffsetType, /* I quantOffsetType */
405 const opus_int frame_length /* I Frame length */
406);
407
408/******************/
409/* CNG */
410/******************/
411
412/* Reset CNG */
413void silk_CNG_Reset(
414 silk_decoder_state *psDec /* I/O Decoder state */
415);
416
417/* Updates CNG estimate, and applies the CNG when packet was lost */
418void silk_CNG(
419 silk_decoder_state *psDec, /* I/O Decoder state */
420 silk_decoder_control *psDecCtrl, /* I/O Decoder control */
421 opus_int16 frame[], /* I/O Signal */
422 opus_int length /* I Length of residual */
423);
424
425/* Encoding of various parameters */
426void silk_encode_indices(
427 silk_encoder_state *psEncC, /* I/O Encoder state */
428 ec_enc *psRangeEnc, /* I/O Compressor data structure */
429 opus_int FrameIndex, /* I Frame number */
430 opus_int encode_LBRR, /* I Flag indicating LBRR data is being encoded */
431 opus_int condCoding /* I The type of conditional coding to use */
432);
433
434#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/pitch_est_defines.h b/lib/rbcodec/codecs/libopus/silk/pitch_est_defines.h
new file mode 100644
index 0000000000..0b6770eb91
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/pitch_est_defines.h
@@ -0,0 +1,88 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_PE_DEFINES_H
29#define SILK_PE_DEFINES_H
30
31#include "SigProc_FIX.h"
32
33/********************************************************/
34/* Definitions for pitch estimator */
35/********************************************************/
36
37#define PE_MAX_FS_KHZ 16 /* Maximum sampling frequency used */
38
39#define PE_MAX_NB_SUBFR 4
40#define PE_SUBFR_LENGTH_MS 5 /* 5 ms */
41
42#define PE_LTP_MEM_LENGTH_MS ( 4 * PE_SUBFR_LENGTH_MS )
43
44#define PE_MAX_FRAME_LENGTH_MS ( PE_LTP_MEM_LENGTH_MS + PE_MAX_NB_SUBFR * PE_SUBFR_LENGTH_MS )
45#define PE_MAX_FRAME_LENGTH ( PE_MAX_FRAME_LENGTH_MS * PE_MAX_FS_KHZ )
46#define PE_MAX_FRAME_LENGTH_ST_1 ( PE_MAX_FRAME_LENGTH >> 2 )
47#define PE_MAX_FRAME_LENGTH_ST_2 ( PE_MAX_FRAME_LENGTH >> 1 )
48
49#define PE_MAX_LAG_MS 18 /* 18 ms -> 56 Hz */
50#define PE_MIN_LAG_MS 2 /* 2 ms -> 500 Hz */
51#define PE_MAX_LAG ( PE_MAX_LAG_MS * PE_MAX_FS_KHZ )
52#define PE_MIN_LAG ( PE_MIN_LAG_MS * PE_MAX_FS_KHZ )
53
54#define PE_D_SRCH_LENGTH 24
55
56#define PE_NB_STAGE3_LAGS 5
57
58#define PE_NB_CBKS_STAGE2 3
59#define PE_NB_CBKS_STAGE2_EXT 11
60
61#define PE_NB_CBKS_STAGE3_MAX 34
62#define PE_NB_CBKS_STAGE3_MID 24
63#define PE_NB_CBKS_STAGE3_MIN 16
64
65#define PE_NB_CBKS_STAGE3_10MS 12
66#define PE_NB_CBKS_STAGE2_10MS 3
67
68#define PE_SHORTLAG_BIAS 0.2f /* for logarithmic weighting */
69#define PE_PREVLAG_BIAS 0.2f /* for logarithmic weighting */
70#define PE_FLATCONTOUR_BIAS 0.05f
71
72#define SILK_PE_MIN_COMPLEX 0
73#define SILK_PE_MID_COMPLEX 1
74#define SILK_PE_MAX_COMPLEX 2
75
76/* Tables for 20 ms frames */
77extern const opus_int8 silk_CB_lags_stage2[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE2_EXT ];
78extern const opus_int8 silk_CB_lags_stage3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ];
79extern const opus_int8 silk_Lag_range_stage3[ SILK_PE_MAX_COMPLEX + 1 ] [ PE_MAX_NB_SUBFR ][ 2 ];
80extern const opus_int8 silk_nb_cbk_searchs_stage3[ SILK_PE_MAX_COMPLEX + 1 ];
81
82/* Tables for 10 ms frames */
83extern const opus_int8 silk_CB_lags_stage2_10_ms[ PE_MAX_NB_SUBFR >> 1][ 3 ];
84extern const opus_int8 silk_CB_lags_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ 12 ];
85extern const opus_int8 silk_Lag_range_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ 2 ];
86
87#endif
88
diff --git a/lib/rbcodec/codecs/libopus/silk/pitch_est_tables.c b/lib/rbcodec/codecs/libopus/silk/pitch_est_tables.c
new file mode 100644
index 0000000000..e191686b0e
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/pitch_est_tables.c
@@ -0,0 +1,99 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "typedef.h"
33#include "pitch_est_defines.h"
34
35const opus_int8 silk_CB_lags_stage2_10_ms[ PE_MAX_NB_SUBFR >> 1][ PE_NB_CBKS_STAGE2_10MS ] =
36{
37 {0, 1, 0},
38 {0, 0, 1}
39};
40
41const opus_int8 silk_CB_lags_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ PE_NB_CBKS_STAGE3_10MS ] =
42{
43 { 0, 0, 1,-1, 1,-1, 2,-2, 2,-2, 3,-3},
44 { 0, 1, 0, 1,-1, 2,-1, 2,-2, 3,-2, 3}
45};
46
47const opus_int8 silk_Lag_range_stage3_10_ms[ PE_MAX_NB_SUBFR >> 1 ][ 2 ] =
48{
49 {-3, 7},
50 {-2, 7}
51};
52
53const opus_int8 silk_CB_lags_stage2[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE2_EXT ] =
54{
55 {0, 2,-1,-1,-1, 0, 0, 1, 1, 0, 1},
56 {0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0},
57 {0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0},
58 {0,-1, 2, 1, 0, 1, 1, 0, 0,-1,-1}
59};
60
61const opus_int8 silk_CB_lags_stage3[ PE_MAX_NB_SUBFR ][ PE_NB_CBKS_STAGE3_MAX ] =
62{
63 {0, 0, 1,-1, 0, 1,-1, 0,-1, 1,-2, 2,-2,-2, 2,-3, 2, 3,-3,-4, 3,-4, 4, 4,-5, 5,-6,-5, 6,-7, 6, 5, 8,-9},
64 {0, 0, 1, 0, 0, 0, 0, 0, 0, 0,-1, 1, 0, 0, 1,-1, 0, 1,-1,-1, 1,-1, 2, 1,-1, 2,-2,-2, 2,-2, 2, 2, 3,-3},
65 {0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1,-1, 1, 0, 0, 2, 1,-1, 2,-1,-1, 2,-1, 2, 2,-1, 3,-2,-2,-2, 3},
66 {0, 1, 0, 0, 1, 0, 1,-1, 2,-1, 2,-1, 2, 3,-2, 3,-2,-2, 4, 4,-3, 5,-3,-4, 6,-4, 6, 5,-5, 8,-6,-5,-7, 9}
67};
68
69const opus_int8 silk_Lag_range_stage3[ SILK_PE_MAX_COMPLEX + 1 ] [ PE_MAX_NB_SUBFR ][ 2 ] =
70{
71 /* Lags to search for low number of stage3 cbks */
72 {
73 {-5,8},
74 {-1,6},
75 {-1,6},
76 {-4,10}
77 },
78 /* Lags to search for middle number of stage3 cbks */
79 {
80 {-6,10},
81 {-2,6},
82 {-1,6},
83 {-5,10}
84 },
85 /* Lags to search for max number of stage3 cbks */
86 {
87 {-9,12},
88 {-3,7},
89 {-2,7},
90 {-7,13}
91 }
92};
93
94const opus_int8 silk_nb_cbk_searchs_stage3[ SILK_PE_MAX_COMPLEX + 1 ] =
95{
96 PE_NB_CBKS_STAGE3_MIN,
97 PE_NB_CBKS_STAGE3_MID,
98 PE_NB_CBKS_STAGE3_MAX
99};
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler.c b/lib/rbcodec/codecs/libopus/silk/resampler.c
new file mode 100644
index 0000000000..ab81b6013f
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler.c
@@ -0,0 +1,215 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32/*
33 * Matrix of resampling methods used:
34 * Fs_out (kHz)
35 * 8 12 16 24 48
36 *
37 * 8 C UF U UF UF
38 * 12 AF C UF U UF
39 * Fs_in (kHz) 16 D AF C UF UF
40 * 24 AF D AF C U
41 * 48 AF AF AF D C
42 *
43 * C -> Copy (no resampling)
44 * D -> Allpass-based 2x downsampling
45 * U -> Allpass-based 2x upsampling
46 * UF -> Allpass-based 2x upsampling followed by FIR interpolation
47 * AF -> AR2 filter followed by FIR interpolation
48 */
49
50#include "resampler_private.h"
51
52/* Tables with delay compensation values to equalize total delay for different modes */
53static const opus_int8 delay_matrix_enc[ 5 ][ 3 ] = {
54/* in \ out 8 12 16 */
55/* 8 */ { 6, 0, 3 },
56/* 12 */ { 0, 7, 3 },
57/* 16 */ { 0, 1, 10 },
58/* 24 */ { 0, 2, 6 },
59/* 48 */ { 18, 10, 12 }
60};
61
62static const opus_int8 delay_matrix_dec[ 3 ][ 5 ] = {
63/* in \ out 8 12 16 24 48 */
64/* 8 */ { 4, 0, 2, 0, 0 },
65/* 12 */ { 0, 9, 4, 7, 4 },
66/* 16 */ { 0, 3, 12, 7, 7 }
67};
68
69/* Simple way to make [8000, 12000, 16000, 24000, 48000] to [0, 1, 2, 3, 4] */
70#define rateID(R) ( ( ( ((R)>>12) - ((R)>16000) ) >> ((R)>24000) ) - 1 )
71
72#define USE_silk_resampler_copy (0)
73#define USE_silk_resampler_private_up2_HQ_wrapper (1)
74#define USE_silk_resampler_private_IIR_FIR (2)
75#define USE_silk_resampler_private_down_FIR (3)
76
77/* Initialize/reset the resampler state for a given pair of input/output sampling rates */
78opus_int silk_resampler_init(
79 silk_resampler_state_struct *S, /* I/O Resampler state */
80 opus_int32 Fs_Hz_in, /* I Input sampling rate (Hz) */
81 opus_int32 Fs_Hz_out, /* I Output sampling rate (Hz) */
82 opus_int forEnc /* I If 1: encoder; if 0: decoder */
83)
84{
85 opus_int up2x;
86
87 /* Clear state */
88 silk_memset( S, 0, sizeof( silk_resampler_state_struct ) );
89
90 /* Input checking */
91 if( forEnc ) {
92 if( ( Fs_Hz_in != 8000 && Fs_Hz_in != 12000 && Fs_Hz_in != 16000 && Fs_Hz_in != 24000 && Fs_Hz_in != 48000 ) ||
93 ( Fs_Hz_out != 8000 && Fs_Hz_out != 12000 && Fs_Hz_out != 16000 ) ) {
94 silk_assert( 0 );
95 return -1;
96 }
97 S->inputDelay = delay_matrix_enc[ rateID( Fs_Hz_in ) ][ rateID( Fs_Hz_out ) ];
98 } else {
99 if( ( Fs_Hz_in != 8000 && Fs_Hz_in != 12000 && Fs_Hz_in != 16000 ) ||
100 ( Fs_Hz_out != 8000 && Fs_Hz_out != 12000 && Fs_Hz_out != 16000 && Fs_Hz_out != 24000 && Fs_Hz_out != 48000 ) ) {
101 silk_assert( 0 );
102 return -1;
103 }
104 S->inputDelay = delay_matrix_dec[ rateID( Fs_Hz_in ) ][ rateID( Fs_Hz_out ) ];
105 }
106
107 S->Fs_in_kHz = silk_DIV32_16( Fs_Hz_in, 1000 );
108 S->Fs_out_kHz = silk_DIV32_16( Fs_Hz_out, 1000 );
109
110 /* Number of samples processed per batch */
111 S->batchSize = S->Fs_in_kHz * RESAMPLER_MAX_BATCH_SIZE_MS;
112
113 /* Find resampler with the right sampling ratio */
114 up2x = 0;
115 if( Fs_Hz_out > Fs_Hz_in ) {
116 /* Upsample */
117 if( Fs_Hz_out == silk_MUL( Fs_Hz_in, 2 ) ) { /* Fs_out : Fs_in = 2 : 1 */
118 /* Special case: directly use 2x upsampler */
119 S->resampler_function = USE_silk_resampler_private_up2_HQ_wrapper;
120 } else {
121 /* Default resampler */
122 S->resampler_function = USE_silk_resampler_private_IIR_FIR;
123 up2x = 1;
124 }
125 } else if ( Fs_Hz_out < Fs_Hz_in ) {
126 /* Downsample */
127 S->resampler_function = USE_silk_resampler_private_down_FIR;
128 if( silk_MUL( Fs_Hz_out, 4 ) == silk_MUL( Fs_Hz_in, 3 ) ) { /* Fs_out : Fs_in = 3 : 4 */
129 S->FIR_Fracs = 3;
130 S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR0;
131 S->Coefs = silk_Resampler_3_4_COEFS;
132 } else if( silk_MUL( Fs_Hz_out, 3 ) == silk_MUL( Fs_Hz_in, 2 ) ) { /* Fs_out : Fs_in = 2 : 3 */
133 S->FIR_Fracs = 2;
134 S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR0;
135 S->Coefs = silk_Resampler_2_3_COEFS;
136 } else if( silk_MUL( Fs_Hz_out, 2 ) == Fs_Hz_in ) { /* Fs_out : Fs_in = 1 : 2 */
137 S->FIR_Fracs = 1;
138 S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR1;
139 S->Coefs = silk_Resampler_1_2_COEFS;
140 } else if( silk_MUL( Fs_Hz_out, 3 ) == Fs_Hz_in ) { /* Fs_out : Fs_in = 1 : 3 */
141 S->FIR_Fracs = 1;
142 S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR2;
143 S->Coefs = silk_Resampler_1_3_COEFS;
144 } else if( silk_MUL( Fs_Hz_out, 4 ) == Fs_Hz_in ) { /* Fs_out : Fs_in = 1 : 4 */
145 S->FIR_Fracs = 1;
146 S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR2;
147 S->Coefs = silk_Resampler_1_4_COEFS;
148 } else if( silk_MUL( Fs_Hz_out, 6 ) == Fs_Hz_in ) { /* Fs_out : Fs_in = 1 : 6 */
149 S->FIR_Fracs = 1;
150 S->FIR_Order = RESAMPLER_DOWN_ORDER_FIR2;
151 S->Coefs = silk_Resampler_1_6_COEFS;
152 } else {
153 /* None available */
154 silk_assert( 0 );
155 return -1;
156 }
157 } else {
158 /* Input and output sampling rates are equal: copy */
159 S->resampler_function = USE_silk_resampler_copy;
160 }
161
162 /* Ratio of input/output samples */
163 S->invRatio_Q16 = silk_LSHIFT32( silk_DIV32( silk_LSHIFT32( Fs_Hz_in, 14 + up2x ), Fs_Hz_out ), 2 );
164 /* Make sure the ratio is rounded up */
165 while( silk_SMULWW( S->invRatio_Q16, Fs_Hz_out ) < silk_LSHIFT32( Fs_Hz_in, up2x ) ) {
166 S->invRatio_Q16++;
167 }
168
169 return 0;
170}
171
172/* Resampler: convert from one sampling rate to another */
173/* Input and output sampling rate are at most 48000 Hz */
174opus_int silk_resampler(
175 silk_resampler_state_struct *S, /* I/O Resampler state */
176 opus_int16 out[], /* O Output signal */
177 const opus_int16 in[], /* I Input signal */
178 opus_int32 inLen /* I Number of input samples */
179)
180{
181 opus_int nSamples;
182
183 /* Need at least 1 ms of input data */
184 silk_assert( inLen >= S->Fs_in_kHz );
185 /* Delay can't exceed the 1 ms of buffering */
186 silk_assert( S->inputDelay <= S->Fs_in_kHz );
187
188 nSamples = S->Fs_in_kHz - S->inputDelay;
189
190 /* Copy to delay buffer */
191 silk_memcpy( &S->delayBuf[ S->inputDelay ], in, nSamples * sizeof( opus_int16 ) );
192
193 switch( S->resampler_function ) {
194 case USE_silk_resampler_private_up2_HQ_wrapper:
195 silk_resampler_private_up2_HQ_wrapper( S, out, S->delayBuf, S->Fs_in_kHz );
196 silk_resampler_private_up2_HQ_wrapper( S, &out[ S->Fs_out_kHz ], &in[ nSamples ], inLen - S->Fs_in_kHz );
197 break;
198 case USE_silk_resampler_private_IIR_FIR:
199 silk_resampler_private_IIR_FIR( S, out, S->delayBuf, S->Fs_in_kHz );
200 silk_resampler_private_IIR_FIR( S, &out[ S->Fs_out_kHz ], &in[ nSamples ], inLen - S->Fs_in_kHz );
201 break;
202 case USE_silk_resampler_private_down_FIR:
203 silk_resampler_private_down_FIR( S, out, S->delayBuf, S->Fs_in_kHz );
204 silk_resampler_private_down_FIR( S, &out[ S->Fs_out_kHz ], &in[ nSamples ], inLen - S->Fs_in_kHz );
205 break;
206 default:
207 silk_memcpy( out, S->delayBuf, S->Fs_in_kHz * sizeof( opus_int16 ) );
208 silk_memcpy( &out[ S->Fs_out_kHz ], &in[ nSamples ], ( inLen - S->Fs_in_kHz ) * sizeof( opus_int16 ) );
209 }
210
211 /* Copy to delay buffer */
212 silk_memcpy( S->delayBuf, &in[ inLen - S->inputDelay ], S->inputDelay * sizeof( opus_int16 ) );
213
214 return 0;
215}
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_private.h b/lib/rbcodec/codecs/libopus/silk/resampler_private.h
new file mode 100644
index 0000000000..45d342c78d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_private.h
@@ -0,0 +1,88 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_RESAMPLER_PRIVATE_H
29#define SILK_RESAMPLER_PRIVATE_H
30
31#ifdef __cplusplus
32extern "C" {
33#endif
34
35#include "SigProc_FIX.h"
36#include "resampler_structs.h"
37#include "resampler_rom.h"
38
39/* Number of input samples to process in the inner loop */
40#define RESAMPLER_MAX_BATCH_SIZE_MS 10
41#define RESAMPLER_MAX_FS_KHZ 48
42#define RESAMPLER_MAX_BATCH_SIZE_IN ( RESAMPLER_MAX_BATCH_SIZE_MS * RESAMPLER_MAX_FS_KHZ )
43
44/* Description: Hybrid IIR/FIR polyphase implementation of resampling */
45void silk_resampler_private_IIR_FIR(
46 void *SS, /* I/O Resampler state */
47 opus_int16 out[], /* O Output signal */
48 const opus_int16 in[], /* I Input signal */
49 opus_int32 inLen /* I Number of input samples */
50);
51
52/* Description: Hybrid IIR/FIR polyphase implementation of resampling */
53void silk_resampler_private_down_FIR(
54 void *SS, /* I/O Resampler state */
55 opus_int16 out[], /* O Output signal */
56 const opus_int16 in[], /* I Input signal */
57 opus_int32 inLen /* I Number of input samples */
58);
59
60/* Upsample by a factor 2, high quality */
61void silk_resampler_private_up2_HQ_wrapper(
62 void *SS, /* I/O Resampler state (unused) */
63 opus_int16 *out, /* O Output signal [ 2 * len ] */
64 const opus_int16 *in, /* I Input signal [ len ] */
65 opus_int32 len /* I Number of input samples */
66);
67
68/* Upsample by a factor 2, high quality */
69void silk_resampler_private_up2_HQ(
70 opus_int32 *S, /* I/O Resampler state [ 6 ] */
71 opus_int16 *out, /* O Output signal [ 2 * len ] */
72 const opus_int16 *in, /* I Input signal [ len ] */
73 opus_int32 len /* I Number of input samples */
74);
75
76/* Second order AR filter */
77void silk_resampler_private_AR2(
78 opus_int32 S[], /* I/O State vector [ 2 ] */
79 opus_int32 out_Q8[], /* O Output signal */
80 const opus_int16 in[], /* I Input signal */
81 const opus_int16 A_Q14[], /* I AR coefficients, Q14 */
82 opus_int32 len /* I Signal length */
83);
84
85#ifdef __cplusplus
86}
87#endif
88#endif /* SILK_RESAMPLER_PRIVATE_H */
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_private_AR2.c b/lib/rbcodec/codecs/libopus/silk/resampler_private_AR2.c
new file mode 100644
index 0000000000..2ec7625e7e
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_private_AR2.c
@@ -0,0 +1,55 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33#include "resampler_private.h"
34
35/* Second order AR filter with single delay elements */
36void silk_resampler_private_AR2(
37 opus_int32 S[], /* I/O State vector [ 2 ] */
38 opus_int32 out_Q8[], /* O Output signal */
39 const opus_int16 in[], /* I Input signal */
40 const opus_int16 A_Q14[], /* I AR coefficients, Q14 */
41 opus_int32 len /* I Signal length */
42)
43{
44 opus_int32 k;
45 opus_int32 out32;
46
47 for( k = 0; k < len; k++ ) {
48 out32 = silk_ADD_LSHIFT32( S[ 0 ], (opus_int32)in[ k ], 8 );
49 out_Q8[ k ] = out32;
50 out32 = silk_LSHIFT( out32, 2 );
51 S[ 0 ] = silk_SMLAWB( S[ 1 ], out32, A_Q14[ 0 ] );
52 S[ 1 ] = silk_SMULWB( out32, A_Q14[ 1 ] );
53 }
54}
55
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_private_IIR_FIR.c b/lib/rbcodec/codecs/libopus/silk/resampler_private_IIR_FIR.c
new file mode 100644
index 0000000000..105be35f16
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_private_IIR_FIR.c
@@ -0,0 +1,103 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33#include "resampler_private.h"
34
35static inline opus_int16 *silk_resampler_private_IIR_FIR_INTERPOL(
36 opus_int16 *out,
37 opus_int16 *buf,
38 opus_int32 max_index_Q16,
39 opus_int32 index_increment_Q16
40)
41{
42 opus_int32 index_Q16, res_Q15;
43 opus_int16 *buf_ptr;
44 opus_int32 table_index;
45
46 /* Interpolate upsampled signal and store in output array */
47 for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
48 table_index = silk_SMULWB( index_Q16 & 0xFFFF, 12 );
49 buf_ptr = &buf[ index_Q16 >> 16 ];
50
51 res_Q15 = silk_SMULBB( buf_ptr[ 0 ], silk_resampler_frac_FIR_12[ table_index ][ 0 ] );
52 res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 1 ], silk_resampler_frac_FIR_12[ table_index ][ 1 ] );
53 res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 2 ], silk_resampler_frac_FIR_12[ table_index ][ 2 ] );
54 res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 3 ], silk_resampler_frac_FIR_12[ table_index ][ 3 ] );
55 res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 4 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 3 ] );
56 res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 5 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 2 ] );
57 res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 6 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 1 ] );
58 res_Q15 = silk_SMLABB( res_Q15, buf_ptr[ 7 ], silk_resampler_frac_FIR_12[ 11 - table_index ][ 0 ] );
59 *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q15, 15 ) );
60 }
61 return out;
62}
63/* Upsample using a combination of allpass-based 2x upsampling and FIR interpolation */
64void silk_resampler_private_IIR_FIR(
65 void *SS, /* I/O Resampler state */
66 opus_int16 out[], /* O Output signal */
67 const opus_int16 in[], /* I Input signal */
68 opus_int32 inLen /* I Number of input samples */
69)
70{
71 silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
72 opus_int32 nSamplesIn;
73 opus_int32 max_index_Q16, index_increment_Q16;
74 opus_int16 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + RESAMPLER_ORDER_FIR_12 ];
75
76 /* Copy buffered samples to start of buffer */
77 silk_memcpy( buf, S->sFIR, RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
78
79 /* Iterate over blocks of frameSizeIn input samples */
80 index_increment_Q16 = S->invRatio_Q16;
81 while( 1 ) {
82 nSamplesIn = silk_min( inLen, S->batchSize );
83
84 /* Upsample 2x */
85 silk_resampler_private_up2_HQ( S->sIIR, &buf[ RESAMPLER_ORDER_FIR_12 ], in, nSamplesIn );
86
87 max_index_Q16 = silk_LSHIFT32( nSamplesIn, 16 + 1 ); /* + 1 because 2x upsampling */
88 out = silk_resampler_private_IIR_FIR_INTERPOL( out, buf, max_index_Q16, index_increment_Q16 );
89 in += nSamplesIn;
90 inLen -= nSamplesIn;
91
92 if( inLen > 0 ) {
93 /* More iterations to do; copy last part of filtered signal to beginning of buffer */
94 silk_memcpy( buf, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
95 } else {
96 break;
97 }
98 }
99
100 /* Copy last part of filtered signal to the state for the next call */
101 silk_memcpy( S->sFIR, &buf[ nSamplesIn << 1 ], RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
102}
103
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_private_down_FIR.c b/lib/rbcodec/codecs/libopus/silk/resampler_private_down_FIR.c
new file mode 100644
index 0000000000..5d4cb1f072
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_private_down_FIR.c
@@ -0,0 +1,189 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33#include "resampler_private.h"
34
35static inline opus_int16 *silk_resampler_private_down_FIR_INTERPOL(
36 opus_int16 *out,
37 opus_int32 *buf,
38 const opus_int16 *FIR_Coefs,
39 opus_int FIR_Order,
40 opus_int FIR_Fracs,
41 opus_int32 max_index_Q16,
42 opus_int32 index_increment_Q16
43)
44{
45 opus_int32 index_Q16, res_Q6;
46 opus_int32 *buf_ptr;
47 opus_int32 interpol_ind;
48 const opus_int16 *interpol_ptr;
49
50 switch( FIR_Order ) {
51 case RESAMPLER_DOWN_ORDER_FIR0:
52 for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
53 /* Integer part gives pointer to buffered input */
54 buf_ptr = buf + silk_RSHIFT( index_Q16, 16 );
55
56 /* Fractional part gives interpolation coefficients */
57 interpol_ind = silk_SMULWB( index_Q16 & 0xFFFF, FIR_Fracs );
58
59 /* Inner product */
60 interpol_ptr = &FIR_Coefs[ RESAMPLER_DOWN_ORDER_FIR0 / 2 * interpol_ind ];
61 res_Q6 = silk_SMULWB( buf_ptr[ 0 ], interpol_ptr[ 0 ] );
62 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 1 ], interpol_ptr[ 1 ] );
63 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 2 ], interpol_ptr[ 2 ] );
64 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 3 ], interpol_ptr[ 3 ] );
65 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 4 ], interpol_ptr[ 4 ] );
66 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 5 ], interpol_ptr[ 5 ] );
67 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 6 ], interpol_ptr[ 6 ] );
68 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 7 ], interpol_ptr[ 7 ] );
69 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 8 ], interpol_ptr[ 8 ] );
70 interpol_ptr = &FIR_Coefs[ RESAMPLER_DOWN_ORDER_FIR0 / 2 * ( FIR_Fracs - 1 - interpol_ind ) ];
71 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 17 ], interpol_ptr[ 0 ] );
72 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 16 ], interpol_ptr[ 1 ] );
73 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 15 ], interpol_ptr[ 2 ] );
74 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 14 ], interpol_ptr[ 3 ] );
75 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 13 ], interpol_ptr[ 4 ] );
76 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 12 ], interpol_ptr[ 5 ] );
77 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 11 ], interpol_ptr[ 6 ] );
78 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 10 ], interpol_ptr[ 7 ] );
79 res_Q6 = silk_SMLAWB( res_Q6, buf_ptr[ 9 ], interpol_ptr[ 8 ] );
80
81 /* Scale down, saturate and store in output array */
82 *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
83 }
84 break;
85 case RESAMPLER_DOWN_ORDER_FIR1:
86 for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
87 /* Integer part gives pointer to buffered input */
88 buf_ptr = buf + silk_RSHIFT( index_Q16, 16 );
89
90 /* Inner product */
91 res_Q6 = silk_SMULWB( silk_ADD32( buf_ptr[ 0 ], buf_ptr[ 23 ] ), FIR_Coefs[ 0 ] );
92 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 1 ], buf_ptr[ 22 ] ), FIR_Coefs[ 1 ] );
93 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 2 ], buf_ptr[ 21 ] ), FIR_Coefs[ 2 ] );
94 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 3 ], buf_ptr[ 20 ] ), FIR_Coefs[ 3 ] );
95 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 4 ], buf_ptr[ 19 ] ), FIR_Coefs[ 4 ] );
96 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 5 ], buf_ptr[ 18 ] ), FIR_Coefs[ 5 ] );
97 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 6 ], buf_ptr[ 17 ] ), FIR_Coefs[ 6 ] );
98 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 7 ], buf_ptr[ 16 ] ), FIR_Coefs[ 7 ] );
99 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 8 ], buf_ptr[ 15 ] ), FIR_Coefs[ 8 ] );
100 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 9 ], buf_ptr[ 14 ] ), FIR_Coefs[ 9 ] );
101 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 10 ], buf_ptr[ 13 ] ), FIR_Coefs[ 10 ] );
102 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 11 ], buf_ptr[ 12 ] ), FIR_Coefs[ 11 ] );
103
104 /* Scale down, saturate and store in output array */
105 *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
106 }
107 break;
108 case RESAMPLER_DOWN_ORDER_FIR2:
109 for( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {
110 /* Integer part gives pointer to buffered input */
111 buf_ptr = buf + silk_RSHIFT( index_Q16, 16 );
112
113 /* Inner product */
114 res_Q6 = silk_SMULWB( silk_ADD32( buf_ptr[ 0 ], buf_ptr[ 35 ] ), FIR_Coefs[ 0 ] );
115 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 1 ], buf_ptr[ 34 ] ), FIR_Coefs[ 1 ] );
116 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 2 ], buf_ptr[ 33 ] ), FIR_Coefs[ 2 ] );
117 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 3 ], buf_ptr[ 32 ] ), FIR_Coefs[ 3 ] );
118 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 4 ], buf_ptr[ 31 ] ), FIR_Coefs[ 4 ] );
119 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 5 ], buf_ptr[ 30 ] ), FIR_Coefs[ 5 ] );
120 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 6 ], buf_ptr[ 29 ] ), FIR_Coefs[ 6 ] );
121 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 7 ], buf_ptr[ 28 ] ), FIR_Coefs[ 7 ] );
122 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 8 ], buf_ptr[ 27 ] ), FIR_Coefs[ 8 ] );
123 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 9 ], buf_ptr[ 26 ] ), FIR_Coefs[ 9 ] );
124 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 10 ], buf_ptr[ 25 ] ), FIR_Coefs[ 10 ] );
125 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 11 ], buf_ptr[ 24 ] ), FIR_Coefs[ 11 ] );
126 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 12 ], buf_ptr[ 23 ] ), FIR_Coefs[ 12 ] );
127 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 13 ], buf_ptr[ 22 ] ), FIR_Coefs[ 13 ] );
128 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 14 ], buf_ptr[ 21 ] ), FIR_Coefs[ 14 ] );
129 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 15 ], buf_ptr[ 20 ] ), FIR_Coefs[ 15 ] );
130 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 16 ], buf_ptr[ 19 ] ), FIR_Coefs[ 16 ] );
131 res_Q6 = silk_SMLAWB( res_Q6, silk_ADD32( buf_ptr[ 17 ], buf_ptr[ 18 ] ), FIR_Coefs[ 17 ] );
132
133 /* Scale down, saturate and store in output array */
134 *out++ = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( res_Q6, 6 ) );
135 }
136 break;
137 default:
138 silk_assert( 0 );
139 }
140 return out;
141}
142
143/* Resample with a 2nd order AR filter followed by FIR interpolation */
144void silk_resampler_private_down_FIR(
145 void *SS, /* I/O Resampler state */
146 opus_int16 out[], /* O Output signal */
147 const opus_int16 in[], /* I Input signal */
148 opus_int32 inLen /* I Number of input samples */
149)
150{
151 silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
152 opus_int32 nSamplesIn;
153 opus_int32 max_index_Q16, index_increment_Q16;
154 opus_int32 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + SILK_RESAMPLER_MAX_FIR_ORDER ];
155 const opus_int16 *FIR_Coefs;
156
157 /* Copy buffered samples to start of buffer */
158 silk_memcpy( buf, S->sFIR, S->FIR_Order * sizeof( opus_int32 ) );
159
160 FIR_Coefs = &S->Coefs[ 2 ];
161
162 /* Iterate over blocks of frameSizeIn input samples */
163 index_increment_Q16 = S->invRatio_Q16;
164 while( 1 ) {
165 nSamplesIn = silk_min( inLen, S->batchSize );
166
167 /* Second-order AR filter (output in Q8) */
168 silk_resampler_private_AR2( S->sIIR, &buf[ S->FIR_Order ], in, S->Coefs, nSamplesIn );
169
170 max_index_Q16 = silk_LSHIFT32( nSamplesIn, 16 );
171
172 /* Interpolate filtered signal */
173 out = silk_resampler_private_down_FIR_INTERPOL( out, buf, FIR_Coefs, S->FIR_Order,
174 S->FIR_Fracs, max_index_Q16, index_increment_Q16 );
175
176 in += nSamplesIn;
177 inLen -= nSamplesIn;
178
179 if( inLen > 1 ) {
180 /* More iterations to do; copy last part of filtered signal to beginning of buffer */
181 silk_memcpy( buf, &buf[ nSamplesIn ], S->FIR_Order * sizeof( opus_int32 ) );
182 } else {
183 break;
184 }
185 }
186
187 /* Copy last part of filtered signal to the state for the next call */
188 silk_memcpy( S->sFIR, &buf[ nSamplesIn ], S->FIR_Order * sizeof( opus_int32 ) );
189}
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_private_up2_HQ.c b/lib/rbcodec/codecs/libopus/silk/resampler_private_up2_HQ.c
new file mode 100644
index 0000000000..6479a154da
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_private_up2_HQ.c
@@ -0,0 +1,113 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33#include "resampler_private.h"
34
35/* Upsample by a factor 2, high quality */
36/* Uses 2nd order allpass filters for the 2x upsampling, followed by a */
37/* notch filter just above Nyquist. */
38void silk_resampler_private_up2_HQ(
39 opus_int32 *S, /* I/O Resampler state [ 6 ] */
40 opus_int16 *out, /* O Output signal [ 2 * len ] */
41 const opus_int16 *in, /* I Input signal [ len ] */
42 opus_int32 len /* I Number of input samples */
43)
44{
45 opus_int32 k;
46 opus_int32 in32, out32_1, out32_2, Y, X;
47
48 silk_assert( silk_resampler_up2_hq_0[ 0 ] > 0 );
49 silk_assert( silk_resampler_up2_hq_0[ 1 ] > 0 );
50 silk_assert( silk_resampler_up2_hq_0[ 2 ] < 0 );
51 silk_assert( silk_resampler_up2_hq_1[ 0 ] > 0 );
52 silk_assert( silk_resampler_up2_hq_1[ 1 ] > 0 );
53 silk_assert( silk_resampler_up2_hq_1[ 2 ] < 0 );
54
55 /* Internal variables and state are in Q10 format */
56 for( k = 0; k < len; k++ ) {
57 /* Convert to Q10 */
58 in32 = silk_LSHIFT( (opus_int32)in[ k ], 10 );
59
60 /* First all-pass section for even output sample */
61 Y = silk_SUB32( in32, S[ 0 ] );
62 X = silk_SMULWB( Y, silk_resampler_up2_hq_0[ 0 ] );
63 out32_1 = silk_ADD32( S[ 0 ], X );
64 S[ 0 ] = silk_ADD32( in32, X );
65
66 /* Second all-pass section for even output sample */
67 Y = silk_SUB32( out32_1, S[ 1 ] );
68 X = silk_SMULWB( Y, silk_resampler_up2_hq_0[ 1 ] );
69 out32_2 = silk_ADD32( S[ 1 ], X );
70 S[ 1 ] = silk_ADD32( out32_1, X );
71
72 /* Third all-pass section for even output sample */
73 Y = silk_SUB32( out32_2, S[ 2 ] );
74 X = silk_SMLAWB( Y, Y, silk_resampler_up2_hq_0[ 2 ] );
75 out32_1 = silk_ADD32( S[ 2 ], X );
76 S[ 2 ] = silk_ADD32( out32_2, X );
77
78 /* Apply gain in Q15, convert back to int16 and store to output */
79 out[ 2 * k ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( out32_1, 10 ) );
80
81 /* First all-pass section for odd output sample */
82 Y = silk_SUB32( in32, S[ 3 ] );
83 X = silk_SMULWB( Y, silk_resampler_up2_hq_1[ 0 ] );
84 out32_1 = silk_ADD32( S[ 3 ], X );
85 S[ 3 ] = silk_ADD32( in32, X );
86
87 /* Second all-pass section for odd output sample */
88 Y = silk_SUB32( out32_1, S[ 4 ] );
89 X = silk_SMULWB( Y, silk_resampler_up2_hq_1[ 1 ] );
90 out32_2 = silk_ADD32( S[ 4 ], X );
91 S[ 4 ] = silk_ADD32( out32_1, X );
92
93 /* Third all-pass section for odd output sample */
94 Y = silk_SUB32( out32_2, S[ 5 ] );
95 X = silk_SMLAWB( Y, Y, silk_resampler_up2_hq_1[ 2 ] );
96 out32_1 = silk_ADD32( S[ 5 ], X );
97 S[ 5 ] = silk_ADD32( out32_2, X );
98
99 /* Apply gain in Q15, convert back to int16 and store to output */
100 out[ 2 * k + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( out32_1, 10 ) );
101 }
102}
103
104void silk_resampler_private_up2_HQ_wrapper(
105 void *SS, /* I/O Resampler state (unused) */
106 opus_int16 *out, /* O Output signal [ 2 * len ] */
107 const opus_int16 *in, /* I Input signal [ len ] */
108 opus_int32 len /* I Number of input samples */
109)
110{
111 silk_resampler_state_struct *S = (silk_resampler_state_struct *)SS;
112 silk_resampler_private_up2_HQ( S->sIIR, out, in, len );
113}
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_rom.c b/lib/rbcodec/codecs/libopus/silk/resampler_rom.c
new file mode 100644
index 0000000000..bbbd6d1690
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_rom.c
@@ -0,0 +1,96 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32/* Filter coefficients for IIR/FIR polyphase resampling *
33 * Total size: 179 Words (358 Bytes) */
34
35#include "resampler_private.h"
36
37/* Matlab code for the notch filter coefficients: */
38/* B = [1, 0.147, 1]; A = [1, 0.107, 0.89]; G = 0.93; freqz(G * B, A, 2^14, 16e3); axis([0, 8000, -10, 1]) */
39/* fprintf('\t%6d, %6d, %6d, %6d\n', round(B(2)*2^16), round(-A(2)*2^16), round((1-A(3))*2^16), round(G*2^15)) */
40/* const opus_int16 silk_resampler_up2_hq_notch[ 4 ] = { 9634, -7012, 7209, 30474 }; */
41
42/* Tables with IIR and FIR coefficients for fractional downsamplers (123 Words) */
43silk_DWORD_ALIGN const opus_int16 silk_Resampler_3_4_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ] = {
44 -20694, -13867,
45 -49, 64, 17, -157, 353, -496, 163, 11047, 22205,
46 -39, 6, 91, -170, 186, 23, -896, 6336, 19928,
47 -19, -36, 102, -89, -24, 328, -951, 2568, 15909,
48};
49
50silk_DWORD_ALIGN const opus_int16 silk_Resampler_2_3_COEFS[ 2 + 2 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ] = {
51 -14457, -14019,
52 64, 128, -122, 36, 310, -768, 584, 9267, 17733,
53 12, 128, 18, -142, 288, -117, -865, 4123, 14459,
54};
55
56silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_2_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR1 / 2 ] = {
57 616, -14323,
58 -10, 39, 58, -46, -84, 120, 184, -315, -541, 1284, 5380, 9024,
59};
60
61silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_3_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ] = {
62 16102, -15162,
63 -13, 0, 20, 26, 5, -31, -43, -4, 65, 90, 7, -157, -248, -44, 593, 1583, 2612, 3271,
64};
65
66silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_4_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ] = {
67 22500, -15099,
68 3, -14, -20, -15, 2, 25, 37, 25, -16, -71, -107, -79, 50, 292, 623, 982, 1288, 1464,
69};
70
71silk_DWORD_ALIGN const opus_int16 silk_Resampler_1_6_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ] = {
72 27540, -15257,
73 17, 12, 8, 1, -10, -22, -30, -32, -22, 3, 44, 100, 168, 243, 317, 381, 429, 455,
74};
75
76silk_DWORD_ALIGN const opus_int16 silk_Resampler_2_3_COEFS_LQ[ 2 + 2 * 2 ] = {
77 -2797, -6507,
78 4697, 10739,
79 1567, 8276,
80};
81
82/* Table with interplation fractions of 1/24, 3/24, 5/24, ... , 23/24 : 23/24 (46 Words) */
83silk_DWORD_ALIGN const opus_int16 silk_resampler_frac_FIR_12[ 12 ][ RESAMPLER_ORDER_FIR_12 / 2 ] = {
84 { 189, -600, 617, 30567 },
85 { 117, -159, -1070, 29704 },
86 { 52, 221, -2392, 28276 },
87 { -4, 529, -3350, 26341 },
88 { -48, 758, -3956, 23973 },
89 { -80, 905, -4235, 21254 },
90 { -99, 972, -4222, 18278 },
91 { -107, 967, -3957, 15143 },
92 { -103, 896, -3487, 11950 },
93 { -91, 773, -2865, 8798 },
94 { -71, 611, -2143, 5784 },
95 { -46, 425, -1375, 2996 },
96};
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_rom.h b/lib/rbcodec/codecs/libopus/silk/resampler_rom.h
new file mode 100644
index 0000000000..473b24a2b5
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_rom.h
@@ -0,0 +1,68 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_FIX_RESAMPLER_ROM_H
29#define SILK_FIX_RESAMPLER_ROM_H
30
31#ifdef __cplusplus
32extern "C"
33{
34#endif
35
36#include "typedef.h"
37#include "resampler_structs.h"
38
39#define RESAMPLER_DOWN_ORDER_FIR0 18
40#define RESAMPLER_DOWN_ORDER_FIR1 24
41#define RESAMPLER_DOWN_ORDER_FIR2 36
42#define RESAMPLER_ORDER_FIR_12 8
43
44/* Tables for 2x downsampler */
45static const opus_int16 silk_resampler_down2_0 = 9872;
46static const opus_int16 silk_resampler_down2_1 = 39809 - 65536;
47
48/* Tables for 2x upsampler, high quality */
49static const opus_int16 silk_resampler_up2_hq_0[ 3 ] = { 1746, 14986, 39083 - 65536 };
50static const opus_int16 silk_resampler_up2_hq_1[ 3 ] = { 6854, 25769, 55542 - 65536 };
51
52/* Tables with IIR and FIR coefficients for fractional downsamplers */
53extern const opus_int16 silk_Resampler_3_4_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ];
54extern const opus_int16 silk_Resampler_2_3_COEFS[ 2 + 2 * RESAMPLER_DOWN_ORDER_FIR0 / 2 ];
55extern const opus_int16 silk_Resampler_1_2_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR1 / 2 ];
56extern const opus_int16 silk_Resampler_1_3_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ];
57extern const opus_int16 silk_Resampler_1_4_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ];
58extern const opus_int16 silk_Resampler_1_6_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR2 / 2 ];
59extern const opus_int16 silk_Resampler_2_3_COEFS_LQ[ 2 + 2 * 2 ];
60
61/* Table with interplation fractions of 1/24, 3/24, ..., 23/24 */
62extern const opus_int16 silk_resampler_frac_FIR_12[ 12 ][ RESAMPLER_ORDER_FIR_12 / 2 ];
63
64#ifdef __cplusplus
65}
66#endif
67
68#endif /* SILK_FIX_RESAMPLER_ROM_H */
diff --git a/lib/rbcodec/codecs/libopus/silk/resampler_structs.h b/lib/rbcodec/codecs/libopus/silk/resampler_structs.h
new file mode 100644
index 0000000000..4c28bd0a2f
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/resampler_structs.h
@@ -0,0 +1,57 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_RESAMPLER_STRUCTS_H
29#define SILK_RESAMPLER_STRUCTS_H
30
31#ifdef __cplusplus
32extern "C" {
33#endif
34
35#define SILK_RESAMPLER_MAX_FIR_ORDER 36
36#define SILK_RESAMPLER_MAX_IIR_ORDER 6
37
38typedef struct _silk_resampler_state_struct{
39 opus_int32 sIIR[ SILK_RESAMPLER_MAX_IIR_ORDER ]; /* this must be the first element of this struct */
40 opus_int32 sFIR[ SILK_RESAMPLER_MAX_FIR_ORDER ];
41 opus_int16 delayBuf[ 48 ];
42 opus_int resampler_function;
43 opus_int batchSize;
44 opus_int32 invRatio_Q16;
45 opus_int FIR_Order;
46 opus_int FIR_Fracs;
47 opus_int Fs_in_kHz;
48 opus_int Fs_out_kHz;
49 opus_int inputDelay;
50 const opus_int16 *Coefs;
51} silk_resampler_state_struct;
52
53#ifdef __cplusplus
54}
55#endif
56#endif /* SILK_RESAMPLER_STRUCTS_H */
57
diff --git a/lib/rbcodec/codecs/libopus/silk/shell_coder.c b/lib/rbcodec/codecs/libopus/silk/shell_coder.c
new file mode 100644
index 0000000000..1cc77fd88e
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/shell_coder.c
@@ -0,0 +1,151 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* shell coder; pulse-subframe length is hardcoded */
35
36static inline void combine_pulses(
37 opus_int *out, /* O combined pulses vector [len] */
38 const opus_int *in, /* I input vector [2 * len] */
39 const opus_int len /* I number of OUTPUT samples */
40)
41{
42 opus_int k;
43 for( k = 0; k < len; k++ ) {
44 out[ k ] = in[ 2 * k ] + in[ 2 * k + 1 ];
45 }
46}
47
48static inline void encode_split(
49 ec_enc *psRangeEnc, /* I/O compressor data structure */
50 const opus_int p_child1, /* I pulse amplitude of first child subframe */
51 const opus_int p, /* I pulse amplitude of current subframe */
52 const opus_uint8 *shell_table /* I table of shell cdfs */
53)
54{
55 if( p > 0 ) {
56 ec_enc_icdf( psRangeEnc, p_child1, &shell_table[ silk_shell_code_table_offsets[ p ] ], 8 );
57 }
58}
59
60static inline void decode_split(
61 opus_int *p_child1, /* O pulse amplitude of first child subframe */
62 opus_int *p_child2, /* O pulse amplitude of second child subframe */
63 ec_dec *psRangeDec, /* I/O Compressor data structure */
64 const opus_int p, /* I pulse amplitude of current subframe */
65 const opus_uint8 *shell_table /* I table of shell cdfs */
66)
67{
68 if( p > 0 ) {
69 p_child1[ 0 ] = ec_dec_icdf( psRangeDec, &shell_table[ silk_shell_code_table_offsets[ p ] ], 8 );
70 p_child2[ 0 ] = p - p_child1[ 0 ];
71 } else {
72 p_child1[ 0 ] = 0;
73 p_child2[ 0 ] = 0;
74 }
75}
76
77/* Shell encoder, operates on one shell code frame of 16 pulses */
78void silk_shell_encoder(
79 ec_enc *psRangeEnc, /* I/O compressor data structure */
80 const opus_int *pulses0 /* I data: nonnegative pulse amplitudes */
81)
82{
83 opus_int pulses1[ 8 ], pulses2[ 4 ], pulses3[ 2 ], pulses4[ 1 ];
84
85 /* this function operates on one shell code frame of 16 pulses */
86 silk_assert( SHELL_CODEC_FRAME_LENGTH == 16 );
87
88 /* tree representation per pulse-subframe */
89 combine_pulses( pulses1, pulses0, 8 );
90 combine_pulses( pulses2, pulses1, 4 );
91 combine_pulses( pulses3, pulses2, 2 );
92 combine_pulses( pulses4, pulses3, 1 );
93
94 encode_split( psRangeEnc, pulses3[ 0 ], pulses4[ 0 ], silk_shell_code_table3 );
95
96 encode_split( psRangeEnc, pulses2[ 0 ], pulses3[ 0 ], silk_shell_code_table2 );
97
98 encode_split( psRangeEnc, pulses1[ 0 ], pulses2[ 0 ], silk_shell_code_table1 );
99 encode_split( psRangeEnc, pulses0[ 0 ], pulses1[ 0 ], silk_shell_code_table0 );
100 encode_split( psRangeEnc, pulses0[ 2 ], pulses1[ 1 ], silk_shell_code_table0 );
101
102 encode_split( psRangeEnc, pulses1[ 2 ], pulses2[ 1 ], silk_shell_code_table1 );
103 encode_split( psRangeEnc, pulses0[ 4 ], pulses1[ 2 ], silk_shell_code_table0 );
104 encode_split( psRangeEnc, pulses0[ 6 ], pulses1[ 3 ], silk_shell_code_table0 );
105
106 encode_split( psRangeEnc, pulses2[ 2 ], pulses3[ 1 ], silk_shell_code_table2 );
107
108 encode_split( psRangeEnc, pulses1[ 4 ], pulses2[ 2 ], silk_shell_code_table1 );
109 encode_split( psRangeEnc, pulses0[ 8 ], pulses1[ 4 ], silk_shell_code_table0 );
110 encode_split( psRangeEnc, pulses0[ 10 ], pulses1[ 5 ], silk_shell_code_table0 );
111
112 encode_split( psRangeEnc, pulses1[ 6 ], pulses2[ 3 ], silk_shell_code_table1 );
113 encode_split( psRangeEnc, pulses0[ 12 ], pulses1[ 6 ], silk_shell_code_table0 );
114 encode_split( psRangeEnc, pulses0[ 14 ], pulses1[ 7 ], silk_shell_code_table0 );
115}
116
117
118/* Shell decoder, operates on one shell code frame of 16 pulses */
119void silk_shell_decoder(
120 opus_int *pulses0, /* O data: nonnegative pulse amplitudes */
121 ec_dec *psRangeDec, /* I/O Compressor data structure */
122 const opus_int pulses4 /* I number of pulses per pulse-subframe */
123)
124{
125 opus_int pulses3[ 2 ], pulses2[ 4 ], pulses1[ 8 ];
126
127 /* this function operates on one shell code frame of 16 pulses */
128 silk_assert( SHELL_CODEC_FRAME_LENGTH == 16 );
129
130 decode_split( &pulses3[ 0 ], &pulses3[ 1 ], psRangeDec, pulses4, silk_shell_code_table3 );
131
132 decode_split( &pulses2[ 0 ], &pulses2[ 1 ], psRangeDec, pulses3[ 0 ], silk_shell_code_table2 );
133
134 decode_split( &pulses1[ 0 ], &pulses1[ 1 ], psRangeDec, pulses2[ 0 ], silk_shell_code_table1 );
135 decode_split( &pulses0[ 0 ], &pulses0[ 1 ], psRangeDec, pulses1[ 0 ], silk_shell_code_table0 );
136 decode_split( &pulses0[ 2 ], &pulses0[ 3 ], psRangeDec, pulses1[ 1 ], silk_shell_code_table0 );
137
138 decode_split( &pulses1[ 2 ], &pulses1[ 3 ], psRangeDec, pulses2[ 1 ], silk_shell_code_table1 );
139 decode_split( &pulses0[ 4 ], &pulses0[ 5 ], psRangeDec, pulses1[ 2 ], silk_shell_code_table0 );
140 decode_split( &pulses0[ 6 ], &pulses0[ 7 ], psRangeDec, pulses1[ 3 ], silk_shell_code_table0 );
141
142 decode_split( &pulses2[ 2 ], &pulses2[ 3 ], psRangeDec, pulses3[ 1 ], silk_shell_code_table2 );
143
144 decode_split( &pulses1[ 4 ], &pulses1[ 5 ], psRangeDec, pulses2[ 2 ], silk_shell_code_table1 );
145 decode_split( &pulses0[ 8 ], &pulses0[ 9 ], psRangeDec, pulses1[ 4 ], silk_shell_code_table0 );
146 decode_split( &pulses0[ 10 ], &pulses0[ 11 ], psRangeDec, pulses1[ 5 ], silk_shell_code_table0 );
147
148 decode_split( &pulses1[ 6 ], &pulses1[ 7 ], psRangeDec, pulses2[ 3 ], silk_shell_code_table1 );
149 decode_split( &pulses0[ 12 ], &pulses0[ 13 ], psRangeDec, pulses1[ 6 ], silk_shell_code_table0 );
150 decode_split( &pulses0[ 14 ], &pulses0[ 15 ], psRangeDec, pulses1[ 7 ], silk_shell_code_table0 );
151}
diff --git a/lib/rbcodec/codecs/libopus/silk/sort.c b/lib/rbcodec/codecs/libopus/silk/sort.c
new file mode 100644
index 0000000000..f9886b45b2
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/sort.c
@@ -0,0 +1,154 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32/* Insertion sort (fast for already almost sorted arrays): */
33/* Best case: O(n) for an already sorted array */
34/* Worst case: O(n^2) for an inversely sorted array */
35/* */
36/* Shell short: http://en.wikipedia.org/wiki/Shell_sort */
37
38#include "SigProc_FIX.h"
39
40void silk_insertion_sort_increasing(
41 opus_int32 *a, /* I/O Unsorted / Sorted vector */
42 opus_int *idx, /* O Index vector for the sorted elements */
43 const opus_int L, /* I Vector length */
44 const opus_int K /* I Number of correctly sorted positions */
45)
46{
47 opus_int32 value;
48 opus_int i, j;
49
50 /* Safety checks */
51 silk_assert( K > 0 );
52 silk_assert( L > 0 );
53 silk_assert( L >= K );
54
55 /* Write start indices in index vector */
56 for( i = 0; i < K; i++ ) {
57 idx[ i ] = i;
58 }
59
60 /* Sort vector elements by value, increasing order */
61 for( i = 1; i < K; i++ ) {
62 value = a[ i ];
63 for( j = i - 1; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {
64 a[ j + 1 ] = a[ j ]; /* Shift value */
65 idx[ j + 1 ] = idx[ j ]; /* Shift index */
66 }
67 a[ j + 1 ] = value; /* Write value */
68 idx[ j + 1 ] = i; /* Write index */
69 }
70
71 /* If less than L values are asked for, check the remaining values, */
72 /* but only spend CPU to ensure that the K first values are correct */
73 for( i = K; i < L; i++ ) {
74 value = a[ i ];
75 if( value < a[ K - 1 ] ) {
76 for( j = K - 2; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {
77 a[ j + 1 ] = a[ j ]; /* Shift value */
78 idx[ j + 1 ] = idx[ j ]; /* Shift index */
79 }
80 a[ j + 1 ] = value; /* Write value */
81 idx[ j + 1 ] = i; /* Write index */
82 }
83 }
84}
85
86#ifdef FIXED_POINT
87/* This function is only used by the fixed-point build */
88void silk_insertion_sort_decreasing_int16(
89 opus_int16 *a, /* I/O Unsorted / Sorted vector */
90 opus_int *idx, /* O Index vector for the sorted elements */
91 const opus_int L, /* I Vector length */
92 const opus_int K /* I Number of correctly sorted positions */
93)
94{
95 opus_int i, j;
96 opus_int value;
97
98 /* Safety checks */
99 silk_assert( K > 0 );
100 silk_assert( L > 0 );
101 silk_assert( L >= K );
102
103 /* Write start indices in index vector */
104 for( i = 0; i < K; i++ ) {
105 idx[ i ] = i;
106 }
107
108 /* Sort vector elements by value, decreasing order */
109 for( i = 1; i < K; i++ ) {
110 value = a[ i ];
111 for( j = i - 1; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {
112 a[ j + 1 ] = a[ j ]; /* Shift value */
113 idx[ j + 1 ] = idx[ j ]; /* Shift index */
114 }
115 a[ j + 1 ] = value; /* Write value */
116 idx[ j + 1 ] = i; /* Write index */
117 }
118
119 /* If less than L values are asked for, check the remaining values, */
120 /* but only spend CPU to ensure that the K first values are correct */
121 for( i = K; i < L; i++ ) {
122 value = a[ i ];
123 if( value > a[ K - 1 ] ) {
124 for( j = K - 2; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {
125 a[ j + 1 ] = a[ j ]; /* Shift value */
126 idx[ j + 1 ] = idx[ j ]; /* Shift index */
127 }
128 a[ j + 1 ] = value; /* Write value */
129 idx[ j + 1 ] = i; /* Write index */
130 }
131 }
132}
133#endif
134
135void silk_insertion_sort_increasing_all_values_int16(
136 opus_int16 *a, /* I/O Unsorted / Sorted vector */
137 const opus_int L /* I Vector length */
138)
139{
140 opus_int value;
141 opus_int i, j;
142
143 /* Safety checks */
144 silk_assert( L > 0 );
145
146 /* Sort vector elements by value, increasing order */
147 for( i = 1; i < L; i++ ) {
148 value = a[ i ];
149 for( j = i - 1; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {
150 a[ j + 1 ] = a[ j ]; /* Shift value */
151 }
152 a[ j + 1 ] = value; /* Write value */
153 }
154}
diff --git a/lib/rbcodec/codecs/libopus/silk/stereo_MS_to_LR.c b/lib/rbcodec/codecs/libopus/silk/stereo_MS_to_LR.c
new file mode 100644
index 0000000000..3705b59686
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/stereo_MS_to_LR.c
@@ -0,0 +1,85 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Convert adaptive Mid/Side representation to Left/Right stereo signal */
35void silk_stereo_MS_to_LR(
36 stereo_dec_state *state, /* I/O State */
37 opus_int16 x1[], /* I/O Left input signal, becomes mid signal */
38 opus_int16 x2[], /* I/O Right input signal, becomes side signal */
39 const opus_int32 pred_Q13[], /* I Predictors */
40 opus_int fs_kHz, /* I Samples rate (kHz) */
41 opus_int frame_length /* I Number of samples */
42)
43{
44 opus_int n, denom_Q16, delta0_Q13, delta1_Q13;
45 opus_int32 sum, diff, pred0_Q13, pred1_Q13;
46
47 /* Buffering */
48 silk_memcpy( x1, state->sMid, 2 * sizeof( opus_int16 ) );
49 silk_memcpy( x2, state->sSide, 2 * sizeof( opus_int16 ) );
50 silk_memcpy( state->sMid, &x1[ frame_length ], 2 * sizeof( opus_int16 ) );
51 silk_memcpy( state->sSide, &x2[ frame_length ], 2 * sizeof( opus_int16 ) );
52
53 /* Interpolate predictors and add prediction to side channel */
54 pred0_Q13 = state->pred_prev_Q13[ 0 ];
55 pred1_Q13 = state->pred_prev_Q13[ 1 ];
56 denom_Q16 = silk_DIV32_16( (opus_int32)1 << 16, STEREO_INTERP_LEN_MS * fs_kHz );
57 delta0_Q13 = silk_RSHIFT_ROUND( silk_SMULBB( pred_Q13[ 0 ] - state->pred_prev_Q13[ 0 ], denom_Q16 ), 16 );
58 delta1_Q13 = silk_RSHIFT_ROUND( silk_SMULBB( pred_Q13[ 1 ] - state->pred_prev_Q13[ 1 ], denom_Q16 ), 16 );
59 for( n = 0; n < STEREO_INTERP_LEN_MS * fs_kHz; n++ ) {
60 pred0_Q13 += delta0_Q13;
61 pred1_Q13 += delta1_Q13;
62 sum = silk_LSHIFT( silk_ADD_LSHIFT( x1[ n ] + x1[ n + 2 ], x1[ n + 1 ], 1 ), 9 ); /* Q11 */
63 sum = silk_SMLAWB( silk_LSHIFT( (opus_int32)x2[ n + 1 ], 8 ), sum, pred0_Q13 ); /* Q8 */
64 sum = silk_SMLAWB( sum, silk_LSHIFT( (opus_int32)x1[ n + 1 ], 11 ), pred1_Q13 ); /* Q8 */
65 x2[ n + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( sum, 8 ) );
66 }
67 pred0_Q13 = pred_Q13[ 0 ];
68 pred1_Q13 = pred_Q13[ 1 ];
69 for( n = STEREO_INTERP_LEN_MS * fs_kHz; n < frame_length; n++ ) {
70 sum = silk_LSHIFT( silk_ADD_LSHIFT( x1[ n ] + x1[ n + 2 ], x1[ n + 1 ], 1 ), 9 ); /* Q11 */
71 sum = silk_SMLAWB( silk_LSHIFT( (opus_int32)x2[ n + 1 ], 8 ), sum, pred0_Q13 ); /* Q8 */
72 sum = silk_SMLAWB( sum, silk_LSHIFT( (opus_int32)x1[ n + 1 ], 11 ), pred1_Q13 ); /* Q8 */
73 x2[ n + 1 ] = (opus_int16)silk_SAT16( silk_RSHIFT_ROUND( sum, 8 ) );
74 }
75 state->pred_prev_Q13[ 0 ] = pred_Q13[ 0 ];
76 state->pred_prev_Q13[ 1 ] = pred_Q13[ 1 ];
77
78 /* Convert to left/right signals */
79 for( n = 0; n < frame_length; n++ ) {
80 sum = x1[ n + 1 ] + (opus_int32)x2[ n + 1 ];
81 diff = x1[ n + 1 ] - (opus_int32)x2[ n + 1 ];
82 x1[ n + 1 ] = (opus_int16)silk_SAT16( sum );
83 x2[ n + 1 ] = (opus_int16)silk_SAT16( diff );
84 }
85}
diff --git a/lib/rbcodec/codecs/libopus/silk/stereo_decode_pred.c b/lib/rbcodec/codecs/libopus/silk/stereo_decode_pred.c
new file mode 100644
index 0000000000..8614cb59fb
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/stereo_decode_pred.c
@@ -0,0 +1,73 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "main.h"
33
34/* Decode mid/side predictors */
35void silk_stereo_decode_pred(
36 ec_dec *psRangeDec, /* I/O Compressor data structure */
37 opus_int32 pred_Q13[] /* O Predictors */
38)
39{
40 opus_int n, ix[ 2 ][ 3 ];
41 opus_int32 low_Q13, step_Q13;
42
43 /* Entropy decoding */
44 n = ec_dec_icdf( psRangeDec, silk_stereo_pred_joint_iCDF, 8 );
45 ix[ 0 ][ 2 ] = silk_DIV32_16( n, 5 );
46 ix[ 1 ][ 2 ] = n - 5 * ix[ 0 ][ 2 ];
47 for( n = 0; n < 2; n++ ) {
48 ix[ n ][ 0 ] = ec_dec_icdf( psRangeDec, silk_uniform3_iCDF, 8 );
49 ix[ n ][ 1 ] = ec_dec_icdf( psRangeDec, silk_uniform5_iCDF, 8 );
50 }
51
52 /* Dequantize */
53 for( n = 0; n < 2; n++ ) {
54 ix[ n ][ 0 ] += 3 * ix[ n ][ 2 ];
55 low_Q13 = silk_stereo_pred_quant_Q13[ ix[ n ][ 0 ] ];
56 step_Q13 = silk_SMULWB( silk_stereo_pred_quant_Q13[ ix[ n ][ 0 ] + 1 ] - low_Q13,
57 SILK_FIX_CONST( 0.5 / STEREO_QUANT_SUB_STEPS, 16 ) );
58 pred_Q13[ n ] = silk_SMLABB( low_Q13, step_Q13, 2 * ix[ n ][ 1 ] + 1 );
59 }
60
61 /* Subtract second from first predictor (helps when actually applying these) */
62 pred_Q13[ 0 ] -= pred_Q13[ 1 ];
63}
64
65/* Decode mid-only flag */
66void silk_stereo_decode_mid_only(
67 ec_dec *psRangeDec, /* I/O Compressor data structure */
68 opus_int *decode_only_mid /* O Flag that only mid channel has been coded */
69)
70{
71 /* Decode flag that only mid channel is coded */
72 *decode_only_mid = ec_dec_icdf( psRangeDec, silk_stereo_only_code_mid_iCDF, 8 );
73}
diff --git a/lib/rbcodec/codecs/libopus/silk/structs.h b/lib/rbcodec/codecs/libopus/silk/structs.h
new file mode 100644
index 0000000000..5d37f6605d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/structs.h
@@ -0,0 +1,324 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_STRUCTS_H
29#define SILK_STRUCTS_H
30
31#include "typedef.h"
32#include "SigProc_FIX.h"
33#include "define.h"
34#include "entenc.h"
35#include "entdec.h"
36
37#ifdef __cplusplus
38extern "C"
39{
40#endif
41
42/************************************/
43/* Noise shaping quantization state */
44/************************************/
45typedef struct {
46 opus_int16 xq[ 2 * MAX_FRAME_LENGTH ]; /* Buffer for quantized output signal */
47 opus_int32 sLTP_shp_Q14[ 2 * MAX_FRAME_LENGTH ];
48 opus_int32 sLPC_Q14[ MAX_SUB_FRAME_LENGTH + NSQ_LPC_BUF_LENGTH ];
49 opus_int32 sAR2_Q14[ MAX_SHAPE_LPC_ORDER ];
50 opus_int32 sLF_AR_shp_Q14;
51 opus_int lagPrev;
52 opus_int sLTP_buf_idx;
53 opus_int sLTP_shp_buf_idx;
54 opus_int32 rand_seed;
55 opus_int32 prev_gain_Q16;
56 opus_int rewhite_flag;
57} silk_nsq_state;
58
59/********************************/
60/* VAD state */
61/********************************/
62typedef struct {
63 opus_int32 AnaState[ 2 ]; /* Analysis filterbank state: 0-8 kHz */
64 opus_int32 AnaState1[ 2 ]; /* Analysis filterbank state: 0-4 kHz */
65 opus_int32 AnaState2[ 2 ]; /* Analysis filterbank state: 0-2 kHz */
66 opus_int32 XnrgSubfr[ VAD_N_BANDS ]; /* Subframe energies */
67 opus_int32 NrgRatioSmth_Q8[ VAD_N_BANDS ]; /* Smoothed energy level in each band */
68 opus_int16 HPstate; /* State of differentiator in the lowest band */
69 opus_int32 NL[ VAD_N_BANDS ]; /* Noise energy level in each band */
70 opus_int32 inv_NL[ VAD_N_BANDS ]; /* Inverse noise energy level in each band */
71 opus_int32 NoiseLevelBias[ VAD_N_BANDS ]; /* Noise level estimator bias/offset */
72 opus_int32 counter; /* Frame counter used in the initial phase */
73} silk_VAD_state;
74
75/* Variable cut-off low-pass filter state */
76typedef struct {
77 opus_int32 In_LP_State[ 2 ]; /* Low pass filter state */
78 opus_int32 transition_frame_no; /* Counter which is mapped to a cut-off frequency */
79 opus_int mode; /* Operating mode, <0: switch down, >0: switch up; 0: do nothing */
80} silk_LP_state;
81
82/* Structure containing NLSF codebook */
83typedef struct {
84 const opus_int16 nVectors;
85 const opus_int16 order;
86 const opus_int16 quantStepSize_Q16;
87 const opus_int16 invQuantStepSize_Q6;
88 const opus_uint8 *CB1_NLSF_Q8;
89 const opus_uint8 *CB1_iCDF;
90 const opus_uint8 *pred_Q8;
91 const opus_uint8 *ec_sel;
92 const opus_uint8 *ec_iCDF;
93 const opus_uint8 *ec_Rates_Q5;
94 const opus_int16 *deltaMin_Q15;
95} silk_NLSF_CB_struct;
96
97typedef struct {
98 opus_int16 pred_prev_Q13[ 2 ];
99 opus_int16 sMid[ 2 ];
100 opus_int16 sSide[ 2 ];
101 opus_int32 mid_side_amp_Q0[ 4 ];
102 opus_int16 smth_width_Q14;
103 opus_int16 width_prev_Q14;
104 opus_int16 silent_side_len;
105 opus_int8 predIx[ MAX_FRAMES_PER_PACKET ][ 2 ][ 3 ];
106 opus_int8 mid_only_flags[ MAX_FRAMES_PER_PACKET ];
107} stereo_enc_state;
108
109typedef struct {
110 opus_int16 pred_prev_Q13[ 2 ];
111 opus_int16 sMid[ 2 ];
112 opus_int16 sSide[ 2 ];
113} stereo_dec_state;
114
115typedef struct {
116 opus_int8 GainsIndices[ MAX_NB_SUBFR ];
117 opus_int8 LTPIndex[ MAX_NB_SUBFR ];
118 opus_int8 NLSFIndices[ MAX_LPC_ORDER + 1 ];
119 opus_int16 lagIndex;
120 opus_int8 contourIndex;
121 opus_int8 signalType;
122 opus_int8 quantOffsetType;
123 opus_int8 NLSFInterpCoef_Q2;
124 opus_int8 PERIndex;
125 opus_int8 LTP_scaleIndex;
126 opus_int8 Seed;
127} SideInfoIndices;
128
129/********************************/
130/* Encoder state */
131/********************************/
132typedef struct {
133 opus_int32 In_HP_State[ 2 ]; /* High pass filter state */
134 opus_int32 variable_HP_smth1_Q15; /* State of first smoother */
135 opus_int32 variable_HP_smth2_Q15; /* State of second smoother */
136 silk_LP_state sLP; /* Low pass filter state */
137 silk_VAD_state sVAD; /* Voice activity detector state */
138 silk_nsq_state sNSQ; /* Noise Shape Quantizer State */
139 opus_int16 prev_NLSFq_Q15[ MAX_LPC_ORDER ]; /* Previously quantized NLSF vector */
140 opus_int speech_activity_Q8; /* Speech activity */
141 opus_int allow_bandwidth_switch; /* Flag indicating that switching of internal bandwidth is allowed */
142 opus_int8 LBRRprevLastGainIndex;
143 opus_int8 prevSignalType;
144 opus_int prevLag;
145 opus_int pitch_LPC_win_length;
146 opus_int max_pitch_lag; /* Highest possible pitch lag (samples) */
147 opus_int32 API_fs_Hz; /* API sampling frequency (Hz) */
148 opus_int32 prev_API_fs_Hz; /* Previous API sampling frequency (Hz) */
149 opus_int maxInternal_fs_Hz; /* Maximum internal sampling frequency (Hz) */
150 opus_int minInternal_fs_Hz; /* Minimum internal sampling frequency (Hz) */
151 opus_int desiredInternal_fs_Hz; /* Soft request for internal sampling frequency (Hz) */
152 opus_int fs_kHz; /* Internal sampling frequency (kHz) */
153 opus_int nb_subfr; /* Number of 5 ms subframes in a frame */
154 opus_int frame_length; /* Frame length (samples) */
155 opus_int subfr_length; /* Subframe length (samples) */
156 opus_int ltp_mem_length; /* Length of LTP memory */
157 opus_int la_pitch; /* Look-ahead for pitch analysis (samples) */
158 opus_int la_shape; /* Look-ahead for noise shape analysis (samples) */
159 opus_int shapeWinLength; /* Window length for noise shape analysis (samples) */
160 opus_int32 TargetRate_bps; /* Target bitrate (bps) */
161 opus_int PacketSize_ms; /* Number of milliseconds to put in each packet */
162 opus_int PacketLoss_perc; /* Packet loss rate measured by farend */
163 opus_int32 frameCounter;
164 opus_int Complexity; /* Complexity setting */
165 opus_int nStatesDelayedDecision; /* Number of states in delayed decision quantization */
166 opus_int useInterpolatedNLSFs; /* Flag for using NLSF interpolation */
167 opus_int shapingLPCOrder; /* Filter order for noise shaping filters */
168 opus_int predictLPCOrder; /* Filter order for prediction filters */
169 opus_int pitchEstimationComplexity; /* Complexity level for pitch estimator */
170 opus_int pitchEstimationLPCOrder; /* Whitening filter order for pitch estimator */
171 opus_int32 pitchEstimationThreshold_Q16; /* Threshold for pitch estimator */
172 opus_int LTPQuantLowComplexity; /* Flag for low complexity LTP quantization */
173 opus_int mu_LTP_Q9; /* Rate-distortion tradeoff in LTP quantization */
174 opus_int NLSF_MSVQ_Survivors; /* Number of survivors in NLSF MSVQ */
175 opus_int first_frame_after_reset; /* Flag for deactivating NLSF interpolation, pitch prediction */
176 opus_int controlled_since_last_payload; /* Flag for ensuring codec_control only runs once per packet */
177 opus_int warping_Q16; /* Warping parameter for warped noise shaping */
178 opus_int useCBR; /* Flag to enable constant bitrate */
179 opus_int prefillFlag; /* Flag to indicate that only buffers are prefilled, no coding */
180 const opus_uint8 *pitch_lag_low_bits_iCDF; /* Pointer to iCDF table for low bits of pitch lag index */
181 const opus_uint8 *pitch_contour_iCDF; /* Pointer to iCDF table for pitch contour index */
182 const silk_NLSF_CB_struct *psNLSF_CB; /* Pointer to NLSF codebook */
183 opus_int input_quality_bands_Q15[ VAD_N_BANDS ];
184 opus_int input_tilt_Q15;
185 opus_int SNR_dB_Q7; /* Quality setting */
186
187 opus_int8 VAD_flags[ MAX_FRAMES_PER_PACKET ];
188 opus_int8 LBRR_flag;
189 opus_int LBRR_flags[ MAX_FRAMES_PER_PACKET ];
190
191 SideInfoIndices indices;
192 opus_int8 pulses[ MAX_FRAME_LENGTH ];
193
194 /* Input/output buffering */
195 opus_int16 inputBuf[ MAX_FRAME_LENGTH + 2 ]; /* Buffer containing input signal */
196 opus_int inputBufIx;
197 opus_int nFramesPerPacket;
198 opus_int nFramesEncoded; /* Number of frames analyzed in current packet */
199
200 opus_int nChannelsAPI;
201 opus_int nChannelsInternal;
202 opus_int channelNb;
203
204 /* Parameters For LTP scaling Control */
205 opus_int frames_since_onset;
206
207 /* Specifically for entropy coding */
208 opus_int ec_prevSignalType;
209 opus_int16 ec_prevLagIndex;
210
211 silk_resampler_state_struct resampler_state;
212
213 /* DTX */
214 opus_int useDTX; /* Flag to enable DTX */
215 opus_int inDTX; /* Flag to signal DTX period */
216 opus_int noSpeechCounter; /* Counts concecutive nonactive frames, used by DTX */
217
218 /* Inband Low Bitrate Redundancy (LBRR) data */
219 opus_int useInBandFEC; /* Saves the API setting for query */
220 opus_int LBRR_enabled; /* Depends on useInBandFRC, bitrate and packet loss rate */
221 opus_int LBRR_GainIncreases; /* Gains increment for coding LBRR frames */
222 SideInfoIndices indices_LBRR[ MAX_FRAMES_PER_PACKET ];
223 opus_int8 pulses_LBRR[ MAX_FRAMES_PER_PACKET ][ MAX_FRAME_LENGTH ];
224} silk_encoder_state;
225
226
227/* Struct for Packet Loss Concealment */
228typedef struct {
229 opus_int32 pitchL_Q8; /* Pitch lag to use for voiced concealment */
230 opus_int16 LTPCoef_Q14[ LTP_ORDER ]; /* LTP coeficients to use for voiced concealment */
231 opus_int16 prevLPC_Q12[ MAX_LPC_ORDER ];
232 opus_int last_frame_lost; /* Was previous frame lost */
233 opus_int32 rand_seed; /* Seed for unvoiced signal generation */
234 opus_int16 randScale_Q14; /* Scaling of unvoiced random signal */
235 opus_int32 conc_energy;
236 opus_int conc_energy_shift;
237 opus_int16 prevLTP_scale_Q14;
238 opus_int32 prevGain_Q16[ 2 ];
239 opus_int fs_kHz;
240 opus_int nb_subfr;
241 opus_int subfr_length;
242} silk_PLC_struct;
243
244/* Struct for CNG */
245typedef struct {
246 opus_int32 CNG_exc_buf_Q14[ MAX_FRAME_LENGTH ];
247 opus_int16 CNG_smth_NLSF_Q15[ MAX_LPC_ORDER ];
248 opus_int32 CNG_synth_state[ MAX_LPC_ORDER ];
249 opus_int32 CNG_smth_Gain_Q16;
250 opus_int32 rand_seed;
251 opus_int fs_kHz;
252} silk_CNG_struct;
253
254/********************************/
255/* Decoder state */
256/********************************/
257typedef struct {
258 opus_int32 prev_gain_Q16;
259 opus_int32 exc_Q14[ MAX_FRAME_LENGTH ];
260 opus_int32 sLPC_Q14_buf[ MAX_LPC_ORDER ];
261 opus_int16 outBuf[ MAX_FRAME_LENGTH + 2 * MAX_SUB_FRAME_LENGTH ]; /* Buffer for output signal */
262 opus_int lagPrev; /* Previous Lag */
263 opus_int8 LastGainIndex; /* Previous gain index */
264 opus_int fs_kHz; /* Sampling frequency in kHz */
265 opus_int32 fs_API_hz; /* API sample frequency (Hz) */
266 opus_int nb_subfr; /* Number of 5 ms subframes in a frame */
267 opus_int frame_length; /* Frame length (samples) */
268 opus_int subfr_length; /* Subframe length (samples) */
269 opus_int ltp_mem_length; /* Length of LTP memory */
270 opus_int LPC_order; /* LPC order */
271 opus_int16 prevNLSF_Q15[ MAX_LPC_ORDER ]; /* Used to interpolate LSFs */
272 opus_int first_frame_after_reset; /* Flag for deactivating NLSF interpolation */
273 const opus_uint8 *pitch_lag_low_bits_iCDF; /* Pointer to iCDF table for low bits of pitch lag index */
274 const opus_uint8 *pitch_contour_iCDF; /* Pointer to iCDF table for pitch contour index */
275
276 /* For buffering payload in case of more frames per packet */
277 opus_int nFramesDecoded;
278 opus_int nFramesPerPacket;
279
280 /* Specifically for entropy coding */
281 opus_int ec_prevSignalType;
282 opus_int16 ec_prevLagIndex;
283
284 opus_int VAD_flags[ MAX_FRAMES_PER_PACKET ];
285 opus_int LBRR_flag;
286 opus_int LBRR_flags[ MAX_FRAMES_PER_PACKET ];
287
288 silk_resampler_state_struct resampler_state;
289
290 const silk_NLSF_CB_struct *psNLSF_CB; /* Pointer to NLSF codebook */
291
292 /* Quantization indices */
293 SideInfoIndices indices;
294
295 /* CNG state */
296 silk_CNG_struct sCNG;
297
298 /* Stuff used for PLC */
299 opus_int lossCnt;
300 opus_int prevSignalType;
301
302 silk_PLC_struct sPLC;
303
304} silk_decoder_state;
305
306/************************/
307/* Decoder control */
308/************************/
309typedef struct {
310 /* Prediction and coding parameters */
311 opus_int pitchL[ MAX_NB_SUBFR ];
312 opus_int32 Gains_Q16[ MAX_NB_SUBFR ];
313 /* Holds interpolated and final coefficients, 4-byte aligned */
314 silk_DWORD_ALIGN opus_int16 PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ];
315 opus_int16 LTPCoef_Q14[ LTP_ORDER * MAX_NB_SUBFR ];
316 opus_int LTP_scale_Q14;
317} silk_decoder_control;
318
319
320#ifdef __cplusplus
321}
322#endif
323
324#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/sum_sqr_shift.c b/lib/rbcodec/codecs/libopus/silk/sum_sqr_shift.c
new file mode 100644
index 0000000000..53f70fd8de
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/sum_sqr_shift.c
@@ -0,0 +1,85 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "SigProc_FIX.h"
33
34/* Compute number of bits to right shift the sum of squares of a vector */
35/* of int16s to make it fit in an int32 */
36void silk_sum_sqr_shift(
37 opus_int32 *energy, /* O Energy of x, after shifting to the right */
38 opus_int *shift, /* O Number of bits right shift applied to energy */
39 const opus_int16 *x, /* I Input vector */
40 opus_int len /* I Length of input vector */
41)
42{
43 opus_int i, shft;
44 opus_int32 nrg_tmp, nrg;
45
46 nrg = 0;
47 shft = 0;
48 len--;
49 for( i = 0; i < len; i += 2 ) {
50 nrg = silk_SMLABB_ovflw( nrg, x[ i ], x[ i ] );
51 nrg = silk_SMLABB_ovflw( nrg, x[ i + 1 ], x[ i + 1 ] );
52 if( nrg < 0 ) {
53 /* Scale down */
54 nrg = (opus_int32)silk_RSHIFT_uint( (opus_uint32)nrg, 2 );
55 shft = 2;
56 break;
57 }
58 }
59 for( ; i < len; i += 2 ) {
60 nrg_tmp = silk_SMULBB( x[ i ], x[ i ] );
61 nrg_tmp = silk_SMLABB_ovflw( nrg_tmp, x[ i + 1 ], x[ i + 1 ] );
62 nrg = (opus_int32)silk_ADD_RSHIFT_uint( nrg, (opus_uint32)nrg_tmp, shft );
63 if( nrg < 0 ) {
64 /* Scale down */
65 nrg = (opus_int32)silk_RSHIFT_uint( (opus_uint32)nrg, 2 );
66 shft += 2;
67 }
68 }
69 if( i == len ) {
70 /* One sample left to process */
71 nrg_tmp = silk_SMULBB( x[ i ], x[ i ] );
72 nrg = (opus_int32)silk_ADD_RSHIFT_uint( nrg, nrg_tmp, shft );
73 }
74
75 /* Make sure to have at least one extra leading zero (two leading zeros in total) */
76 if( nrg & 0xC0000000 ) {
77 nrg = silk_RSHIFT_uint( (opus_uint32)nrg, 2 );
78 shft += 2;
79 }
80
81 /* Output arguments */
82 *shift = shft;
83 *energy = nrg;
84}
85
diff --git a/lib/rbcodec/codecs/libopus/silk/table_LSF_cos.c b/lib/rbcodec/codecs/libopus/silk/table_LSF_cos.c
new file mode 100644
index 0000000000..b58e3f4728
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/table_LSF_cos.c
@@ -0,0 +1,70 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "tables.h"
33
34/* Cosine approximation table for LSF conversion */
35/* Q12 values (even) */
36const opus_int16 silk_LSFCosTab_FIX_Q12[ LSF_COS_TAB_SZ_FIX + 1 ] = {
37 8192, 8190, 8182, 8170,
38 8152, 8130, 8104, 8072,
39 8034, 7994, 7946, 7896,
40 7840, 7778, 7714, 7644,
41 7568, 7490, 7406, 7318,
42 7226, 7128, 7026, 6922,
43 6812, 6698, 6580, 6458,
44 6332, 6204, 6070, 5934,
45 5792, 5648, 5502, 5352,
46 5198, 5040, 4880, 4718,
47 4552, 4382, 4212, 4038,
48 3862, 3684, 3502, 3320,
49 3136, 2948, 2760, 2570,
50 2378, 2186, 1990, 1794,
51 1598, 1400, 1202, 1002,
52 802, 602, 402, 202,
53 0, -202, -402, -602,
54 -802, -1002, -1202, -1400,
55 -1598, -1794, -1990, -2186,
56 -2378, -2570, -2760, -2948,
57 -3136, -3320, -3502, -3684,
58 -3862, -4038, -4212, -4382,
59 -4552, -4718, -4880, -5040,
60 -5198, -5352, -5502, -5648,
61 -5792, -5934, -6070, -6204,
62 -6332, -6458, -6580, -6698,
63 -6812, -6922, -7026, -7128,
64 -7226, -7318, -7406, -7490,
65 -7568, -7644, -7714, -7778,
66 -7840, -7896, -7946, -7994,
67 -8034, -8072, -8104, -8130,
68 -8152, -8170, -8182, -8190,
69 -8192
70};
diff --git a/lib/rbcodec/codecs/libopus/silk/tables.h b/lib/rbcodec/codecs/libopus/silk/tables.h
new file mode 100644
index 0000000000..072b7929d5
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables.h
@@ -0,0 +1,120 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_TABLES_H
29#define SILK_TABLES_H
30
31#include "define.h"
32#include "structs.h"
33
34#ifdef __cplusplus
35extern "C"
36{
37#endif
38
39/* Entropy coding tables (with size in bytes indicated) */
40extern const opus_uint8 silk_gain_iCDF[ 3 ][ N_LEVELS_QGAIN / 8 ]; /* 24 */
41extern const opus_uint8 silk_delta_gain_iCDF[ MAX_DELTA_GAIN_QUANT - MIN_DELTA_GAIN_QUANT + 1 ]; /* 41 */
42
43extern const opus_uint8 silk_pitch_lag_iCDF[ 2 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) ];/* 32 */
44extern const opus_uint8 silk_pitch_delta_iCDF[ 21 ]; /* 21 */
45extern const opus_uint8 silk_pitch_contour_iCDF[ 34 ]; /* 34 */
46extern const opus_uint8 silk_pitch_contour_NB_iCDF[ 11 ]; /* 11 */
47extern const opus_uint8 silk_pitch_contour_10_ms_iCDF[ 12 ]; /* 12 */
48extern const opus_uint8 silk_pitch_contour_10_ms_NB_iCDF[ 3 ]; /* 3 */
49
50extern const opus_uint8 silk_pulses_per_block_iCDF[ N_RATE_LEVELS ][ MAX_PULSES + 2 ]; /* 180 */
51extern const opus_uint8 silk_pulses_per_block_BITS_Q5[ N_RATE_LEVELS - 1 ][ MAX_PULSES + 2 ]; /* 162 */
52
53extern const opus_uint8 silk_rate_levels_iCDF[ 2 ][ N_RATE_LEVELS - 1 ]; /* 18 */
54extern const opus_uint8 silk_rate_levels_BITS_Q5[ 2 ][ N_RATE_LEVELS - 1 ]; /* 18 */
55
56extern const opus_uint8 silk_max_pulses_table[ 4 ]; /* 4 */
57
58extern const opus_uint8 silk_shell_code_table0[ 152 ]; /* 152 */
59extern const opus_uint8 silk_shell_code_table1[ 152 ]; /* 152 */
60extern const opus_uint8 silk_shell_code_table2[ 152 ]; /* 152 */
61extern const opus_uint8 silk_shell_code_table3[ 152 ]; /* 152 */
62extern const opus_uint8 silk_shell_code_table_offsets[ MAX_PULSES + 1 ]; /* 17 */
63
64extern const opus_uint8 silk_lsb_iCDF[ 2 ]; /* 2 */
65
66extern const opus_uint8 silk_sign_iCDF[ 42 ]; /* 42 */
67
68extern const opus_uint8 silk_uniform3_iCDF[ 3 ]; /* 3 */
69extern const opus_uint8 silk_uniform4_iCDF[ 4 ]; /* 4 */
70extern const opus_uint8 silk_uniform5_iCDF[ 5 ]; /* 5 */
71extern const opus_uint8 silk_uniform6_iCDF[ 6 ]; /* 6 */
72extern const opus_uint8 silk_uniform8_iCDF[ 8 ]; /* 8 */
73
74extern const opus_uint8 silk_NLSF_EXT_iCDF[ 7 ]; /* 7 */
75
76extern const opus_uint8 silk_LTP_per_index_iCDF[ 3 ]; /* 3 */
77extern const opus_uint8 * const silk_LTP_gain_iCDF_ptrs[ NB_LTP_CBKS ]; /* 3 */
78extern const opus_uint8 * const silk_LTP_gain_BITS_Q5_ptrs[ NB_LTP_CBKS ]; /* 3 */
79extern const opus_int16 silk_LTP_gain_middle_avg_RD_Q14;
80extern const opus_int8 * const silk_LTP_vq_ptrs_Q7[ NB_LTP_CBKS ]; /* 168 */
81extern const opus_int8 silk_LTP_vq_sizes[ NB_LTP_CBKS ]; /* 3 */
82
83extern const opus_uint8 silk_LTPscale_iCDF[ 3 ]; /* 4 */
84extern const opus_int16 silk_LTPScales_table_Q14[ 3 ]; /* 6 */
85
86extern const opus_uint8 silk_type_offset_VAD_iCDF[ 4 ]; /* 4 */
87extern const opus_uint8 silk_type_offset_no_VAD_iCDF[ 2 ]; /* 2 */
88
89extern const opus_int16 silk_stereo_pred_quant_Q13[ STEREO_QUANT_TAB_SIZE ]; /* 32 */
90extern const opus_uint8 silk_stereo_pred_joint_iCDF[ 25 ]; /* 25 */
91extern const opus_uint8 silk_stereo_only_code_mid_iCDF[ 2 ]; /* 2 */
92
93extern const opus_uint8 * const silk_LBRR_flags_iCDF_ptr[ 2 ]; /* 10 */
94
95extern const opus_uint8 silk_NLSF_interpolation_factor_iCDF[ 5 ]; /* 5 */
96
97extern const silk_NLSF_CB_struct silk_NLSF_CB_WB; /* 1040 */
98extern const silk_NLSF_CB_struct silk_NLSF_CB_NB_MB; /* 728 */
99
100/* Piece-wise linear mapping from bitrate in kbps to coding quality in dB SNR */
101extern const opus_int32 silk_TargetRate_table_NB[ TARGET_RATE_TAB_SZ ]; /* 32 */
102extern const opus_int32 silk_TargetRate_table_MB[ TARGET_RATE_TAB_SZ ]; /* 32 */
103extern const opus_int32 silk_TargetRate_table_WB[ TARGET_RATE_TAB_SZ ]; /* 32 */
104extern const opus_int16 silk_SNR_table_Q1[ TARGET_RATE_TAB_SZ ]; /* 32 */
105
106/* Quantization offsets */
107extern const opus_int16 silk_Quantization_Offsets_Q10[ 2 ][ 2 ]; /* 8 */
108
109/* Interpolation points for filter coefficients used in the bandwidth transition smoother */
110extern const opus_int32 silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NB ]; /* 60 */
111extern const opus_int32 silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NA ]; /* 60 */
112
113/* Rom table with cosine values */
114extern const opus_int16 silk_LSFCosTab_FIX_Q12[ LSF_COS_TAB_SZ_FIX + 1 ]; /* 258 */
115
116#ifdef __cplusplus
117}
118#endif
119
120#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/tables_LTP.c b/lib/rbcodec/codecs/libopus/silk/tables_LTP.c
new file mode 100644
index 0000000000..6deb9bc556
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables_LTP.c
@@ -0,0 +1,272 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "tables.h"
33
34const opus_uint8 silk_LTP_per_index_iCDF[3] = {
35 179, 99, 0
36};
37
38static const opus_uint8 silk_LTP_gain_iCDF_0[8] = {
39 71, 56, 43, 30, 21, 12, 6, 0
40};
41
42static const opus_uint8 silk_LTP_gain_iCDF_1[16] = {
43 199, 165, 144, 124, 109, 96, 84, 71,
44 61, 51, 42, 32, 23, 15, 8, 0
45};
46
47static const opus_uint8 silk_LTP_gain_iCDF_2[32] = {
48 241, 225, 211, 199, 187, 175, 164, 153,
49 142, 132, 123, 114, 105, 96, 88, 80,
50 72, 64, 57, 50, 44, 38, 33, 29,
51 24, 20, 16, 12, 9, 5, 2, 0
52};
53
54const opus_int16 silk_LTP_gain_middle_avg_RD_Q14 = 12304;
55
56static const opus_uint8 silk_LTP_gain_BITS_Q5_0[8] = {
57 15, 131, 138, 138, 155, 155, 173, 173
58};
59
60static const opus_uint8 silk_LTP_gain_BITS_Q5_1[16] = {
61 69, 93, 115, 118, 131, 138, 141, 138,
62 150, 150, 155, 150, 155, 160, 166, 160
63};
64
65static const opus_uint8 silk_LTP_gain_BITS_Q5_2[32] = {
66 131, 128, 134, 141, 141, 141, 145, 145,
67 145, 150, 155, 155, 155, 155, 160, 160,
68 160, 160, 166, 166, 173, 173, 182, 192,
69 182, 192, 192, 192, 205, 192, 205, 224
70};
71
72const opus_uint8 * const silk_LTP_gain_iCDF_ptrs[NB_LTP_CBKS] = {
73 silk_LTP_gain_iCDF_0,
74 silk_LTP_gain_iCDF_1,
75 silk_LTP_gain_iCDF_2
76};
77
78const opus_uint8 * const silk_LTP_gain_BITS_Q5_ptrs[NB_LTP_CBKS] = {
79 silk_LTP_gain_BITS_Q5_0,
80 silk_LTP_gain_BITS_Q5_1,
81 silk_LTP_gain_BITS_Q5_2
82};
83
84static const opus_int8 silk_LTP_gain_vq_0[8][5] =
85{
86{
87 4, 6, 24, 7, 5
88},
89{
90 0, 0, 2, 0, 0
91},
92{
93 12, 28, 41, 13, -4
94},
95{
96 -9, 15, 42, 25, 14
97},
98{
99 1, -2, 62, 41, -9
100},
101{
102 -10, 37, 65, -4, 3
103},
104{
105 -6, 4, 66, 7, -8
106},
107{
108 16, 14, 38, -3, 33
109}
110};
111
112static const opus_int8 silk_LTP_gain_vq_1[16][5] =
113{
114{
115 13, 22, 39, 23, 12
116},
117{
118 -1, 36, 64, 27, -6
119},
120{
121 -7, 10, 55, 43, 17
122},
123{
124 1, 1, 8, 1, 1
125},
126{
127 6, -11, 74, 53, -9
128},
129{
130 -12, 55, 76, -12, 8
131},
132{
133 -3, 3, 93, 27, -4
134},
135{
136 26, 39, 59, 3, -8
137},
138{
139 2, 0, 77, 11, 9
140},
141{
142 -8, 22, 44, -6, 7
143},
144{
145 40, 9, 26, 3, 9
146},
147{
148 -7, 20, 101, -7, 4
149},
150{
151 3, -8, 42, 26, 0
152},
153{
154 -15, 33, 68, 2, 23
155},
156{
157 -2, 55, 46, -2, 15
158},
159{
160 3, -1, 21, 16, 41
161}
162};
163
164static const opus_int8 silk_LTP_gain_vq_2[32][5] =
165{
166{
167 -6, 27, 61, 39, 5
168},
169{
170 -11, 42, 88, 4, 1
171},
172{
173 -2, 60, 65, 6, -4
174},
175{
176 -1, -5, 73, 56, 1
177},
178{
179 -9, 19, 94, 29, -9
180},
181{
182 0, 12, 99, 6, 4
183},
184{
185 8, -19, 102, 46, -13
186},
187{
188 3, 2, 13, 3, 2
189},
190{
191 9, -21, 84, 72, -18
192},
193{
194 -11, 46, 104, -22, 8
195},
196{
197 18, 38, 48, 23, 0
198},
199{
200 -16, 70, 83, -21, 11
201},
202{
203 5, -11, 117, 22, -8
204},
205{
206 -6, 23, 117, -12, 3
207},
208{
209 3, -8, 95, 28, 4
210},
211{
212 -10, 15, 77, 60, -15
213},
214{
215 -1, 4, 124, 2, -4
216},
217{
218 3, 38, 84, 24, -25
219},
220{
221 2, 13, 42, 13, 31
222},
223{
224 21, -4, 56, 46, -1
225},
226{
227 -1, 35, 79, -13, 19
228},
229{
230 -7, 65, 88, -9, -14
231},
232{
233 20, 4, 81, 49, -29
234},
235{
236 20, 0, 75, 3, -17
237},
238{
239 5, -9, 44, 92, -8
240},
241{
242 1, -3, 22, 69, 31
243},
244{
245 -6, 95, 41, -12, 5
246},
247{
248 39, 67, 16, -4, 1
249},
250{
251 0, -6, 120, 55, -36
252},
253{
254 -13, 44, 122, 4, -24
255},
256{
257 81, 5, 11, 3, 7
258},
259{
260 2, 0, 9, 10, 88
261}
262};
263
264const opus_int8 * const silk_LTP_vq_ptrs_Q7[NB_LTP_CBKS] = {
265 (opus_int8 *)&silk_LTP_gain_vq_0[0][0],
266 (opus_int8 *)&silk_LTP_gain_vq_1[0][0],
267 (opus_int8 *)&silk_LTP_gain_vq_2[0][0]
268};
269
270const opus_int8 silk_LTP_vq_sizes[NB_LTP_CBKS] = {
271 8, 16, 32
272};
diff --git a/lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_NB_MB.c b/lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_NB_MB.c
new file mode 100644
index 0000000000..201a89d110
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_NB_MB.c
@@ -0,0 +1,159 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "tables.h"
33
34static const opus_uint8 silk_NLSF_CB1_NB_MB_Q8[ 320 ] = {
35 12, 35, 60, 83, 108, 132, 157, 180,
36 206, 228, 15, 32, 55, 77, 101, 125,
37 151, 175, 201, 225, 19, 42, 66, 89,
38 114, 137, 162, 184, 209, 230, 12, 25,
39 50, 72, 97, 120, 147, 172, 200, 223,
40 26, 44, 69, 90, 114, 135, 159, 180,
41 205, 225, 13, 22, 53, 80, 106, 130,
42 156, 180, 205, 228, 15, 25, 44, 64,
43 90, 115, 142, 168, 196, 222, 19, 24,
44 62, 82, 100, 120, 145, 168, 190, 214,
45 22, 31, 50, 79, 103, 120, 151, 170,
46 203, 227, 21, 29, 45, 65, 106, 124,
47 150, 171, 196, 224, 30, 49, 75, 97,
48 121, 142, 165, 186, 209, 229, 19, 25,
49 52, 70, 93, 116, 143, 166, 192, 219,
50 26, 34, 62, 75, 97, 118, 145, 167,
51 194, 217, 25, 33, 56, 70, 91, 113,
52 143, 165, 196, 223, 21, 34, 51, 72,
53 97, 117, 145, 171, 196, 222, 20, 29,
54 50, 67, 90, 117, 144, 168, 197, 221,
55 22, 31, 48, 66, 95, 117, 146, 168,
56 196, 222, 24, 33, 51, 77, 116, 134,
57 158, 180, 200, 224, 21, 28, 70, 87,
58 106, 124, 149, 170, 194, 217, 26, 33,
59 53, 64, 83, 117, 152, 173, 204, 225,
60 27, 34, 65, 95, 108, 129, 155, 174,
61 210, 225, 20, 26, 72, 99, 113, 131,
62 154, 176, 200, 219, 34, 43, 61, 78,
63 93, 114, 155, 177, 205, 229, 23, 29,
64 54, 97, 124, 138, 163, 179, 209, 229,
65 30, 38, 56, 89, 118, 129, 158, 178,
66 200, 231, 21, 29, 49, 63, 85, 111,
67 142, 163, 193, 222, 27, 48, 77, 103,
68 133, 158, 179, 196, 215, 232, 29, 47,
69 74, 99, 124, 151, 176, 198, 220, 237,
70 33, 42, 61, 76, 93, 121, 155, 174,
71 207, 225, 29, 53, 87, 112, 136, 154,
72 170, 188, 208, 227, 24, 30, 52, 84,
73 131, 150, 166, 186, 203, 229, 37, 48,
74 64, 84, 104, 118, 156, 177, 201, 230
75};
76
77static const opus_uint8 silk_NLSF_CB1_iCDF_NB_MB[ 64 ] = {
78 212, 178, 148, 129, 108, 96, 85, 82,
79 79, 77, 61, 59, 57, 56, 51, 49,
80 48, 45, 42, 41, 40, 38, 36, 34,
81 31, 30, 21, 12, 10, 3, 1, 0,
82 255, 245, 244, 236, 233, 225, 217, 203,
83 190, 176, 175, 161, 149, 136, 125, 114,
84 102, 91, 81, 71, 60, 52, 43, 35,
85 28, 20, 19, 18, 12, 11, 5, 0
86};
87
88static const opus_uint8 silk_NLSF_CB2_SELECT_NB_MB[ 160 ] = {
89 16, 0, 0, 0, 0, 99, 66, 36,
90 36, 34, 36, 34, 34, 34, 34, 83,
91 69, 36, 52, 34, 116, 102, 70, 68,
92 68, 176, 102, 68, 68, 34, 65, 85,
93 68, 84, 36, 116, 141, 152, 139, 170,
94 132, 187, 184, 216, 137, 132, 249, 168,
95 185, 139, 104, 102, 100, 68, 68, 178,
96 218, 185, 185, 170, 244, 216, 187, 187,
97 170, 244, 187, 187, 219, 138, 103, 155,
98 184, 185, 137, 116, 183, 155, 152, 136,
99 132, 217, 184, 184, 170, 164, 217, 171,
100 155, 139, 244, 169, 184, 185, 170, 164,
101 216, 223, 218, 138, 214, 143, 188, 218,
102 168, 244, 141, 136, 155, 170, 168, 138,
103 220, 219, 139, 164, 219, 202, 216, 137,
104 168, 186, 246, 185, 139, 116, 185, 219,
105 185, 138, 100, 100, 134, 100, 102, 34,
106 68, 68, 100, 68, 168, 203, 221, 218,
107 168, 167, 154, 136, 104, 70, 164, 246,
108 171, 137, 139, 137, 155, 218, 219, 139
109};
110
111static const opus_uint8 silk_NLSF_CB2_iCDF_NB_MB[ 72 ] = {
112 255, 254, 253, 238, 14, 3, 2, 1,
113 0, 255, 254, 252, 218, 35, 3, 2,
114 1, 0, 255, 254, 250, 208, 59, 4,
115 2, 1, 0, 255, 254, 246, 194, 71,
116 10, 2, 1, 0, 255, 252, 236, 183,
117 82, 8, 2, 1, 0, 255, 252, 235,
118 180, 90, 17, 2, 1, 0, 255, 248,
119 224, 171, 97, 30, 4, 1, 0, 255,
120 254, 236, 173, 95, 37, 7, 1, 0
121};
122
123static const opus_uint8 silk_NLSF_CB2_BITS_NB_MB_Q5[ 72 ] = {
124 255, 255, 255, 131, 6, 145, 255, 255,
125 255, 255, 255, 236, 93, 15, 96, 255,
126 255, 255, 255, 255, 194, 83, 25, 71,
127 221, 255, 255, 255, 255, 162, 73, 34,
128 66, 162, 255, 255, 255, 210, 126, 73,
129 43, 57, 173, 255, 255, 255, 201, 125,
130 71, 48, 58, 130, 255, 255, 255, 166,
131 110, 73, 57, 62, 104, 210, 255, 255,
132 251, 123, 65, 55, 68, 100, 171, 255
133};
134
135static const opus_uint8 silk_NLSF_PRED_NB_MB_Q8[ 18 ] = {
136 179, 138, 140, 148, 151, 149, 153, 151,
137 163, 116, 67, 82, 59, 92, 72, 100,
138 89, 92
139};
140
141static const opus_int16 silk_NLSF_DELTA_MIN_NB_MB_Q15[ 11 ] = {
142 250, 3, 6, 3, 3, 3, 4, 3,
143 3, 3, 461
144};
145
146const silk_NLSF_CB_struct silk_NLSF_CB_NB_MB =
147{
148 32,
149 10,
150 SILK_FIX_CONST( 0.18, 16 ),
151 SILK_FIX_CONST( 1.0 / 0.18, 6 ),
152 silk_NLSF_CB1_NB_MB_Q8,
153 silk_NLSF_CB1_iCDF_NB_MB,
154 silk_NLSF_PRED_NB_MB_Q8,
155 silk_NLSF_CB2_SELECT_NB_MB,
156 silk_NLSF_CB2_iCDF_NB_MB,
157 silk_NLSF_CB2_BITS_NB_MB_Q5,
158 silk_NLSF_DELTA_MIN_NB_MB_Q15,
159};
diff --git a/lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_WB.c b/lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_WB.c
new file mode 100644
index 0000000000..0d9286f39d
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables_NLSF_CB_WB.c
@@ -0,0 +1,198 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "tables.h"
33
34static const opus_uint8 silk_NLSF_CB1_WB_Q8[ 512 ] = {
35 7, 23, 38, 54, 69, 85, 100, 116,
36 131, 147, 162, 178, 193, 208, 223, 239,
37 13, 25, 41, 55, 69, 83, 98, 112,
38 127, 142, 157, 171, 187, 203, 220, 236,
39 15, 21, 34, 51, 61, 78, 92, 106,
40 126, 136, 152, 167, 185, 205, 225, 240,
41 10, 21, 36, 50, 63, 79, 95, 110,
42 126, 141, 157, 173, 189, 205, 221, 237,
43 17, 20, 37, 51, 59, 78, 89, 107,
44 123, 134, 150, 164, 184, 205, 224, 240,
45 10, 15, 32, 51, 67, 81, 96, 112,
46 129, 142, 158, 173, 189, 204, 220, 236,
47 8, 21, 37, 51, 65, 79, 98, 113,
48 126, 138, 155, 168, 179, 192, 209, 218,
49 12, 15, 34, 55, 63, 78, 87, 108,
50 118, 131, 148, 167, 185, 203, 219, 236,
51 16, 19, 32, 36, 56, 79, 91, 108,
52 118, 136, 154, 171, 186, 204, 220, 237,
53 11, 28, 43, 58, 74, 89, 105, 120,
54 135, 150, 165, 180, 196, 211, 226, 241,
55 6, 16, 33, 46, 60, 75, 92, 107,
56 123, 137, 156, 169, 185, 199, 214, 225,
57 11, 19, 30, 44, 57, 74, 89, 105,
58 121, 135, 152, 169, 186, 202, 218, 234,
59 12, 19, 29, 46, 57, 71, 88, 100,
60 120, 132, 148, 165, 182, 199, 216, 233,
61 17, 23, 35, 46, 56, 77, 92, 106,
62 123, 134, 152, 167, 185, 204, 222, 237,
63 14, 17, 45, 53, 63, 75, 89, 107,
64 115, 132, 151, 171, 188, 206, 221, 240,
65 9, 16, 29, 40, 56, 71, 88, 103,
66 119, 137, 154, 171, 189, 205, 222, 237,
67 16, 19, 36, 48, 57, 76, 87, 105,
68 118, 132, 150, 167, 185, 202, 218, 236,
69 12, 17, 29, 54, 71, 81, 94, 104,
70 126, 136, 149, 164, 182, 201, 221, 237,
71 15, 28, 47, 62, 79, 97, 115, 129,
72 142, 155, 168, 180, 194, 208, 223, 238,
73 8, 14, 30, 45, 62, 78, 94, 111,
74 127, 143, 159, 175, 192, 207, 223, 239,
75 17, 30, 49, 62, 79, 92, 107, 119,
76 132, 145, 160, 174, 190, 204, 220, 235,
77 14, 19, 36, 45, 61, 76, 91, 108,
78 121, 138, 154, 172, 189, 205, 222, 238,
79 12, 18, 31, 45, 60, 76, 91, 107,
80 123, 138, 154, 171, 187, 204, 221, 236,
81 13, 17, 31, 43, 53, 70, 83, 103,
82 114, 131, 149, 167, 185, 203, 220, 237,
83 17, 22, 35, 42, 58, 78, 93, 110,
84 125, 139, 155, 170, 188, 206, 224, 240,
85 8, 15, 34, 50, 67, 83, 99, 115,
86 131, 146, 162, 178, 193, 209, 224, 239,
87 13, 16, 41, 66, 73, 86, 95, 111,
88 128, 137, 150, 163, 183, 206, 225, 241,
89 17, 25, 37, 52, 63, 75, 92, 102,
90 119, 132, 144, 160, 175, 191, 212, 231,
91 19, 31, 49, 65, 83, 100, 117, 133,
92 147, 161, 174, 187, 200, 213, 227, 242,
93 18, 31, 52, 68, 88, 103, 117, 126,
94 138, 149, 163, 177, 192, 207, 223, 239,
95 16, 29, 47, 61, 76, 90, 106, 119,
96 133, 147, 161, 176, 193, 209, 224, 240,
97 15, 21, 35, 50, 61, 73, 86, 97,
98 110, 119, 129, 141, 175, 198, 218, 237
99};
100
101static const opus_uint8 silk_NLSF_CB1_iCDF_WB[ 64 ] = {
102 225, 204, 201, 184, 183, 175, 158, 154,
103 153, 135, 119, 115, 113, 110, 109, 99,
104 98, 95, 79, 68, 52, 50, 48, 45,
105 43, 32, 31, 27, 18, 10, 3, 0,
106 255, 251, 235, 230, 212, 201, 196, 182,
107 167, 166, 163, 151, 138, 124, 110, 104,
108 90, 78, 76, 70, 69, 57, 45, 34,
109 24, 21, 11, 6, 5, 4, 3, 0
110};
111
112static const opus_uint8 silk_NLSF_CB2_SELECT_WB[ 256 ] = {
113 0, 0, 0, 0, 0, 0, 0, 1,
114 100, 102, 102, 68, 68, 36, 34, 96,
115 164, 107, 158, 185, 180, 185, 139, 102,
116 64, 66, 36, 34, 34, 0, 1, 32,
117 208, 139, 141, 191, 152, 185, 155, 104,
118 96, 171, 104, 166, 102, 102, 102, 132,
119 1, 0, 0, 0, 0, 16, 16, 0,
120 80, 109, 78, 107, 185, 139, 103, 101,
121 208, 212, 141, 139, 173, 153, 123, 103,
122 36, 0, 0, 0, 0, 0, 0, 1,
123 48, 0, 0, 0, 0, 0, 0, 32,
124 68, 135, 123, 119, 119, 103, 69, 98,
125 68, 103, 120, 118, 118, 102, 71, 98,
126 134, 136, 157, 184, 182, 153, 139, 134,
127 208, 168, 248, 75, 189, 143, 121, 107,
128 32, 49, 34, 34, 34, 0, 17, 2,
129 210, 235, 139, 123, 185, 137, 105, 134,
130 98, 135, 104, 182, 100, 183, 171, 134,
131 100, 70, 68, 70, 66, 66, 34, 131,
132 64, 166, 102, 68, 36, 2, 1, 0,
133 134, 166, 102, 68, 34, 34, 66, 132,
134 212, 246, 158, 139, 107, 107, 87, 102,
135 100, 219, 125, 122, 137, 118, 103, 132,
136 114, 135, 137, 105, 171, 106, 50, 34,
137 164, 214, 141, 143, 185, 151, 121, 103,
138 192, 34, 0, 0, 0, 0, 0, 1,
139 208, 109, 74, 187, 134, 249, 159, 137,
140 102, 110, 154, 118, 87, 101, 119, 101,
141 0, 2, 0, 36, 36, 66, 68, 35,
142 96, 164, 102, 100, 36, 0, 2, 33,
143 167, 138, 174, 102, 100, 84, 2, 2,
144 100, 107, 120, 119, 36, 197, 24, 0
145};
146
147static const opus_uint8 silk_NLSF_CB2_iCDF_WB[ 72 ] = {
148 255, 254, 253, 244, 12, 3, 2, 1,
149 0, 255, 254, 252, 224, 38, 3, 2,
150 1, 0, 255, 254, 251, 209, 57, 4,
151 2, 1, 0, 255, 254, 244, 195, 69,
152 4, 2, 1, 0, 255, 251, 232, 184,
153 84, 7, 2, 1, 0, 255, 254, 240,
154 186, 86, 14, 2, 1, 0, 255, 254,
155 239, 178, 91, 30, 5, 1, 0, 255,
156 248, 227, 177, 100, 19, 2, 1, 0
157};
158
159static const opus_uint8 silk_NLSF_CB2_BITS_WB_Q5[ 72 ] = {
160 255, 255, 255, 156, 4, 154, 255, 255,
161 255, 255, 255, 227, 102, 15, 92, 255,
162 255, 255, 255, 255, 213, 83, 24, 72,
163 236, 255, 255, 255, 255, 150, 76, 33,
164 63, 214, 255, 255, 255, 190, 121, 77,
165 43, 55, 185, 255, 255, 255, 245, 137,
166 71, 43, 59, 139, 255, 255, 255, 255,
167 131, 66, 50, 66, 107, 194, 255, 255,
168 166, 116, 76, 55, 53, 125, 255, 255
169};
170
171static const opus_uint8 silk_NLSF_PRED_WB_Q8[ 30 ] = {
172 175, 148, 160, 176, 178, 173, 174, 164,
173 177, 174, 196, 182, 198, 192, 182, 68,
174 62, 66, 60, 72, 117, 85, 90, 118,
175 136, 151, 142, 160, 142, 155
176};
177
178static const opus_int16 silk_NLSF_DELTA_MIN_WB_Q15[ 17 ] = {
179 100, 3, 40, 3, 3, 3, 5, 14,
180 14, 10, 11, 3, 8, 9, 7, 3,
181 347
182};
183
184const silk_NLSF_CB_struct silk_NLSF_CB_WB =
185{
186 32,
187 16,
188 SILK_FIX_CONST( 0.15, 16 ),
189 SILK_FIX_CONST( 1.0 / 0.15, 6 ),
190 silk_NLSF_CB1_WB_Q8,
191 silk_NLSF_CB1_iCDF_WB,
192 silk_NLSF_PRED_WB_Q8,
193 silk_NLSF_CB2_SELECT_WB,
194 silk_NLSF_CB2_iCDF_WB,
195 silk_NLSF_CB2_BITS_WB_Q5,
196 silk_NLSF_DELTA_MIN_WB_Q15,
197};
198
diff --git a/lib/rbcodec/codecs/libopus/silk/tables_gain.c b/lib/rbcodec/codecs/libopus/silk/tables_gain.c
new file mode 100644
index 0000000000..fe6f912b10
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables_gain.c
@@ -0,0 +1,63 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "tables.h"
33
34#ifdef __cplusplus
35extern "C"
36{
37#endif
38
39const opus_uint8 silk_gain_iCDF[ 3 ][ N_LEVELS_QGAIN / 8 ] =
40{
41{
42 224, 112, 44, 15, 3, 2, 1, 0
43},
44{
45 254, 237, 192, 132, 70, 23, 4, 0
46},
47{
48 255, 252, 226, 155, 61, 11, 2, 0
49}
50};
51
52const opus_uint8 silk_delta_gain_iCDF[ MAX_DELTA_GAIN_QUANT - MIN_DELTA_GAIN_QUANT + 1 ] = {
53 250, 245, 234, 203, 71, 50, 42, 38,
54 35, 33, 31, 29, 28, 27, 26, 25,
55 24, 23, 22, 21, 20, 19, 18, 17,
56 16, 15, 14, 13, 12, 11, 10, 9,
57 8, 7, 6, 5, 4, 3, 2, 1,
58 0
59};
60
61#ifdef __cplusplus
62}
63#endif
diff --git a/lib/rbcodec/codecs/libopus/silk/tables_other.c b/lib/rbcodec/codecs/libopus/silk/tables_other.c
new file mode 100644
index 0000000000..5119ebd39f
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables_other.c
@@ -0,0 +1,138 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "structs.h"
33#include "define.h"
34#include "tables.h"
35
36#ifdef __cplusplus
37extern "C"
38{
39#endif
40
41/* Piece-wise linear mapping from bitrate in kbps to coding quality in dB SNR */
42const opus_int32 silk_TargetRate_table_NB[ TARGET_RATE_TAB_SZ ] = {
43 0, 8000, 9400, 11500, 13500, 17500, 25000, MAX_TARGET_RATE_BPS
44};
45const opus_int32 silk_TargetRate_table_MB[ TARGET_RATE_TAB_SZ ] = {
46 0, 9000, 12000, 14500, 18500, 24500, 35500, MAX_TARGET_RATE_BPS
47};
48const opus_int32 silk_TargetRate_table_WB[ TARGET_RATE_TAB_SZ ] = {
49 0, 10500, 14000, 17000, 21500, 28500, 42000, MAX_TARGET_RATE_BPS
50};
51const opus_int16 silk_SNR_table_Q1[ TARGET_RATE_TAB_SZ ] = {
52 18, 29, 38, 40, 46, 52, 62, 84
53};
54
55/* Tables for stereo predictor coding */
56const opus_int16 silk_stereo_pred_quant_Q13[ STEREO_QUANT_TAB_SIZE ] = {
57 -13732, -10050, -8266, -7526, -6500, -5000, -2950, -820,
58 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732
59};
60const opus_uint8 silk_stereo_pred_joint_iCDF[ 25 ] = {
61 249, 247, 246, 245, 244,
62 234, 210, 202, 201, 200,
63 197, 174, 82, 59, 56,
64 55, 54, 46, 22, 12,
65 11, 10, 9, 7, 0
66};
67const opus_uint8 silk_stereo_only_code_mid_iCDF[ 2 ] = { 64, 0 };
68
69/* Tables for LBRR flags */
70static const opus_uint8 silk_LBRR_flags_2_iCDF[ 3 ] = { 203, 150, 0 };
71static const opus_uint8 silk_LBRR_flags_3_iCDF[ 7 ] = { 215, 195, 166, 125, 110, 82, 0 };
72const opus_uint8 * const silk_LBRR_flags_iCDF_ptr[ 2 ] = {
73 silk_LBRR_flags_2_iCDF,
74 silk_LBRR_flags_3_iCDF
75};
76
77/* Table for LSB coding */
78const opus_uint8 silk_lsb_iCDF[ 2 ] = { 120, 0 };
79
80/* Tables for LTPScale */
81const opus_uint8 silk_LTPscale_iCDF[ 3 ] = { 128, 64, 0 };
82
83/* Tables for signal type and offset coding */
84const opus_uint8 silk_type_offset_VAD_iCDF[ 4 ] = {
85 232, 158, 10, 0
86};
87const opus_uint8 silk_type_offset_no_VAD_iCDF[ 2 ] = {
88 230, 0
89};
90
91/* Tables for NLSF interpolation factor */
92const opus_uint8 silk_NLSF_interpolation_factor_iCDF[ 5 ] = { 243, 221, 192, 181, 0 };
93
94/* Quantization offsets */
95const opus_int16 silk_Quantization_Offsets_Q10[ 2 ][ 2 ] = {
96 { OFFSET_UVL_Q10, OFFSET_UVH_Q10 }, { OFFSET_VL_Q10, OFFSET_VH_Q10 }
97};
98
99/* Table for LTPScale */
100const opus_int16 silk_LTPScales_table_Q14[ 3 ] = { 15565, 12288, 8192 };
101
102/* Uniform entropy tables */
103const opus_uint8 silk_uniform3_iCDF[ 3 ] = { 171, 85, 0 };
104const opus_uint8 silk_uniform4_iCDF[ 4 ] = { 192, 128, 64, 0 };
105const opus_uint8 silk_uniform5_iCDF[ 5 ] = { 205, 154, 102, 51, 0 };
106const opus_uint8 silk_uniform6_iCDF[ 6 ] = { 213, 171, 128, 85, 43, 0 };
107const opus_uint8 silk_uniform8_iCDF[ 8 ] = { 224, 192, 160, 128, 96, 64, 32, 0 };
108
109const opus_uint8 silk_NLSF_EXT_iCDF[ 7 ] = { 100, 40, 16, 7, 3, 1, 0 };
110
111/* Elliptic/Cauer filters designed with 0.1 dB passband ripple,
112 80 dB minimum stopband attenuation, and
113 [0.95 : 0.15 : 0.35] normalized cut off frequencies. */
114
115/* Interpolation points for filter coefficients used in the bandwidth transition smoother */
116const opus_int32 silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NB ] =
117{
118{ 250767114, 501534038, 250767114 },
119{ 209867381, 419732057, 209867381 },
120{ 170987846, 341967853, 170987846 },
121{ 131531482, 263046905, 131531482 },
122{ 89306658, 178584282, 89306658 }
123};
124
125/* Interpolation points for filter coefficients used in the bandwidth transition smoother */
126const opus_int32 silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NA ] =
127{
128{ 506393414, 239854379 },
129{ 411067935, 169683996 },
130{ 306733530, 116694253 },
131{ 185807084, 77959395 },
132{ 35497197, 57401098 }
133};
134
135#ifdef __cplusplus
136}
137#endif
138
diff --git a/lib/rbcodec/codecs/libopus/silk/tables_pitch_lag.c b/lib/rbcodec/codecs/libopus/silk/tables_pitch_lag.c
new file mode 100644
index 0000000000..e795a23cd0
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables_pitch_lag.c
@@ -0,0 +1,69 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "tables.h"
33
34const opus_uint8 silk_pitch_lag_iCDF[ 2 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) ] = {
35 253, 250, 244, 233, 212, 182, 150, 131,
36 120, 110, 98, 85, 72, 60, 49, 40,
37 32, 25, 19, 15, 13, 11, 9, 8,
38 7, 6, 5, 4, 3, 2, 1, 0
39};
40
41const opus_uint8 silk_pitch_delta_iCDF[21] = {
42 210, 208, 206, 203, 199, 193, 183, 168,
43 142, 104, 74, 52, 37, 27, 20, 14,
44 10, 6, 4, 2, 0
45};
46
47const opus_uint8 silk_pitch_contour_iCDF[34] = {
48 223, 201, 183, 167, 152, 138, 124, 111,
49 98, 88, 79, 70, 62, 56, 50, 44,
50 39, 35, 31, 27, 24, 21, 18, 16,
51 14, 12, 10, 8, 6, 4, 3, 2,
52 1, 0
53};
54
55const opus_uint8 silk_pitch_contour_NB_iCDF[11] = {
56 188, 176, 155, 138, 119, 97, 67, 43,
57 26, 10, 0
58};
59
60const opus_uint8 silk_pitch_contour_10_ms_iCDF[12] = {
61 165, 119, 80, 61, 47, 35, 27, 20,
62 14, 9, 4, 0
63};
64
65const opus_uint8 silk_pitch_contour_10_ms_NB_iCDF[3] = {
66 113, 63, 0
67};
68
69
diff --git a/lib/rbcodec/codecs/libopus/silk/tables_pulses_per_block.c b/lib/rbcodec/codecs/libopus/silk/tables_pulses_per_block.c
new file mode 100644
index 0000000000..0c9b18be6c
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/tables_pulses_per_block.c
@@ -0,0 +1,264 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifdef HAVE_CONFIG_H
29#include "opus_config.h"
30#endif
31
32#include "tables.h"
33
34const opus_uint8 silk_max_pulses_table[ 4 ] = {
35 8, 10, 12, 16
36};
37
38const opus_uint8 silk_pulses_per_block_iCDF[ 10 ][ 18 ] = {
39{
40 125, 51, 26, 18, 15, 12, 11, 10,
41 9, 8, 7, 6, 5, 4, 3, 2,
42 1, 0
43},
44{
45 198, 105, 45, 22, 15, 12, 11, 10,
46 9, 8, 7, 6, 5, 4, 3, 2,
47 1, 0
48},
49{
50 213, 162, 116, 83, 59, 43, 32, 24,
51 18, 15, 12, 9, 7, 6, 5, 3,
52 2, 0
53},
54{
55 239, 187, 116, 59, 28, 16, 11, 10,
56 9, 8, 7, 6, 5, 4, 3, 2,
57 1, 0
58},
59{
60 250, 229, 188, 135, 86, 51, 30, 19,
61 13, 10, 8, 6, 5, 4, 3, 2,
62 1, 0
63},
64{
65 249, 235, 213, 185, 156, 128, 103, 83,
66 66, 53, 42, 33, 26, 21, 17, 13,
67 10, 0
68},
69{
70 254, 249, 235, 206, 164, 118, 77, 46,
71 27, 16, 10, 7, 5, 4, 3, 2,
72 1, 0
73},
74{
75 255, 253, 249, 239, 220, 191, 156, 119,
76 85, 57, 37, 23, 15, 10, 6, 4,
77 2, 0
78},
79{
80 255, 253, 251, 246, 237, 223, 203, 179,
81 152, 124, 98, 75, 55, 40, 29, 21,
82 15, 0
83},
84{
85 255, 254, 253, 247, 220, 162, 106, 67,
86 42, 28, 18, 12, 9, 6, 4, 3,
87 2, 0
88}
89};
90
91const opus_uint8 silk_pulses_per_block_BITS_Q5[ 9 ][ 18 ] = {
92{
93 31, 57, 107, 160, 205, 205, 255, 255,
94 255, 255, 255, 255, 255, 255, 255, 255,
95 255, 255
96},
97{
98 69, 47, 67, 111, 166, 205, 255, 255,
99 255, 255, 255, 255, 255, 255, 255, 255,
100 255, 255
101},
102{
103 82, 74, 79, 95, 109, 128, 145, 160,
104 173, 205, 205, 205, 224, 255, 255, 224,
105 255, 224
106},
107{
108 125, 74, 59, 69, 97, 141, 182, 255,
109 255, 255, 255, 255, 255, 255, 255, 255,
110 255, 255
111},
112{
113 173, 115, 85, 73, 76, 92, 115, 145,
114 173, 205, 224, 224, 255, 255, 255, 255,
115 255, 255
116},
117{
118 166, 134, 113, 102, 101, 102, 107, 118,
119 125, 138, 145, 155, 166, 182, 192, 192,
120 205, 150
121},
122{
123 224, 182, 134, 101, 83, 79, 85, 97,
124 120, 145, 173, 205, 224, 255, 255, 255,
125 255, 255
126},
127{
128 255, 224, 192, 150, 120, 101, 92, 89,
129 93, 102, 118, 134, 160, 182, 192, 224,
130 224, 224
131},
132{
133 255, 224, 224, 182, 155, 134, 118, 109,
134 104, 102, 106, 111, 118, 131, 145, 160,
135 173, 131
136}
137};
138
139const opus_uint8 silk_rate_levels_iCDF[ 2 ][ 9 ] =
140{
141{
142 241, 190, 178, 132, 87, 74, 41, 14,
143 0
144},
145{
146 223, 193, 157, 140, 106, 57, 39, 18,
147 0
148}
149};
150
151const opus_uint8 silk_rate_levels_BITS_Q5[ 2 ][ 9 ] =
152{
153{
154 131, 74, 141, 79, 80, 138, 95, 104,
155 134
156},
157{
158 95, 99, 91, 125, 93, 76, 123, 115,
159 123
160}
161};
162
163const opus_uint8 silk_shell_code_table0[ 152 ] = {
164 128, 0, 214, 42, 0, 235, 128, 21,
165 0, 244, 184, 72, 11, 0, 248, 214,
166 128, 42, 7, 0, 248, 225, 170, 80,
167 25, 5, 0, 251, 236, 198, 126, 54,
168 18, 3, 0, 250, 238, 211, 159, 82,
169 35, 15, 5, 0, 250, 231, 203, 168,
170 128, 88, 53, 25, 6, 0, 252, 238,
171 216, 185, 148, 108, 71, 40, 18, 4,
172 0, 253, 243, 225, 199, 166, 128, 90,
173 57, 31, 13, 3, 0, 254, 246, 233,
174 212, 183, 147, 109, 73, 44, 23, 10,
175 2, 0, 255, 250, 240, 223, 198, 166,
176 128, 90, 58, 33, 16, 6, 1, 0,
177 255, 251, 244, 231, 210, 181, 146, 110,
178 75, 46, 25, 12, 5, 1, 0, 255,
179 253, 248, 238, 221, 196, 164, 128, 92,
180 60, 35, 18, 8, 3, 1, 0, 255,
181 253, 249, 242, 229, 208, 180, 146, 110,
182 76, 48, 27, 14, 7, 3, 1, 0
183};
184
185const opus_uint8 silk_shell_code_table1[ 152 ] = {
186 129, 0, 207, 50, 0, 236, 129, 20,
187 0, 245, 185, 72, 10, 0, 249, 213,
188 129, 42, 6, 0, 250, 226, 169, 87,
189 27, 4, 0, 251, 233, 194, 130, 62,
190 20, 4, 0, 250, 236, 207, 160, 99,
191 47, 17, 3, 0, 255, 240, 217, 182,
192 131, 81, 41, 11, 1, 0, 255, 254,
193 233, 201, 159, 107, 61, 20, 2, 1,
194 0, 255, 249, 233, 206, 170, 128, 86,
195 50, 23, 7, 1, 0, 255, 250, 238,
196 217, 186, 148, 108, 70, 39, 18, 6,
197 1, 0, 255, 252, 243, 226, 200, 166,
198 128, 90, 56, 30, 13, 4, 1, 0,
199 255, 252, 245, 231, 209, 180, 146, 110,
200 76, 47, 25, 11, 4, 1, 0, 255,
201 253, 248, 237, 219, 194, 163, 128, 93,
202 62, 37, 19, 8, 3, 1, 0, 255,
203 254, 250, 241, 226, 205, 177, 145, 111,
204 79, 51, 30, 15, 6, 2, 1, 0
205};
206
207const opus_uint8 silk_shell_code_table2[ 152 ] = {
208 129, 0, 203, 54, 0, 234, 129, 23,
209 0, 245, 184, 73, 10, 0, 250, 215,
210 129, 41, 5, 0, 252, 232, 173, 86,
211 24, 3, 0, 253, 240, 200, 129, 56,
212 15, 2, 0, 253, 244, 217, 164, 94,
213 38, 10, 1, 0, 253, 245, 226, 189,
214 132, 71, 27, 7, 1, 0, 253, 246,
215 231, 203, 159, 105, 56, 23, 6, 1,
216 0, 255, 248, 235, 213, 179, 133, 85,
217 47, 19, 5, 1, 0, 255, 254, 243,
218 221, 194, 159, 117, 70, 37, 12, 2,
219 1, 0, 255, 254, 248, 234, 208, 171,
220 128, 85, 48, 22, 8, 2, 1, 0,
221 255, 254, 250, 240, 220, 189, 149, 107,
222 67, 36, 16, 6, 2, 1, 0, 255,
223 254, 251, 243, 227, 201, 166, 128, 90,
224 55, 29, 13, 5, 2, 1, 0, 255,
225 254, 252, 246, 234, 213, 183, 147, 109,
226 73, 43, 22, 10, 4, 2, 1, 0
227};
228
229const opus_uint8 silk_shell_code_table3[ 152 ] = {
230 130, 0, 200, 58, 0, 231, 130, 26,
231 0, 244, 184, 76, 12, 0, 249, 214,
232 130, 43, 6, 0, 252, 232, 173, 87,
233 24, 3, 0, 253, 241, 203, 131, 56,
234 14, 2, 0, 254, 246, 221, 167, 94,
235 35, 8, 1, 0, 254, 249, 232, 193,
236 130, 65, 23, 5, 1, 0, 255, 251,
237 239, 211, 162, 99, 45, 15, 4, 1,
238 0, 255, 251, 243, 223, 186, 131, 74,
239 33, 11, 3, 1, 0, 255, 252, 245,
240 230, 202, 158, 105, 57, 24, 8, 2,
241 1, 0, 255, 253, 247, 235, 214, 179,
242 132, 84, 44, 19, 7, 2, 1, 0,
243 255, 254, 250, 240, 223, 196, 159, 112,
244 69, 36, 15, 6, 2, 1, 0, 255,
245 254, 253, 245, 231, 209, 176, 136, 93,
246 55, 27, 11, 3, 2, 1, 0, 255,
247 254, 253, 252, 239, 221, 194, 158, 117,
248 76, 42, 18, 4, 3, 2, 1, 0
249};
250
251const opus_uint8 silk_shell_code_table_offsets[ 17 ] = {
252 0, 0, 2, 5, 9, 14, 20, 27,
253 35, 44, 54, 65, 77, 90, 104, 119,
254 135
255};
256
257const opus_uint8 silk_sign_iCDF[ 42 ] = {
258 254, 49, 67, 77, 82, 93, 99,
259 198, 11, 18, 24, 31, 36, 45,
260 255, 46, 66, 78, 87, 94, 104,
261 208, 14, 21, 32, 42, 51, 66,
262 255, 94, 104, 109, 112, 115, 118,
263 248, 53, 69, 80, 88, 95, 102
264};
diff --git a/lib/rbcodec/codecs/libopus/silk/typedef.h b/lib/rbcodec/codecs/libopus/silk/typedef.h
new file mode 100644
index 0000000000..da98123701
--- /dev/null
+++ b/lib/rbcodec/codecs/libopus/silk/typedef.h
@@ -0,0 +1,77 @@
1/***********************************************************************
2Copyright (c) 2006-2011, Skype Limited. All rights reserved.
3Redistribution and use in source and binary forms, with or without
4modification, are permitted provided that the following conditions
5are met:
6- Redistributions of source code must retain the above copyright notice,
7this list of conditions and the following disclaimer.
8- Redistributions in binary form must reproduce the above copyright
9notice, this list of conditions and the following disclaimer in the
10documentation and/or other materials provided with the distribution.
11- Neither the name of Internet Society, IETF or IETF Trust, nor the
12names of specific contributors, may be used to endorse or promote
13products derived from this software without specific prior written
14permission.
15THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
16AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
19LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
20CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
21SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
22INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
24ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25POSSIBILITY OF SUCH DAMAGE.
26***********************************************************************/
27
28#ifndef SILK_TYPEDEF_H
29#define SILK_TYPEDEF_H
30
31#include "opus_types.h"
32
33#ifndef FIXED_POINT
34# include <float.h>
35# define silk_float float
36# define silk_float_MAX FLT_MAX
37#endif
38
39#define silk_int64_MAX ((opus_int64)0x7FFFFFFFFFFFFFFFLL) /* 2^63 - 1 */
40#define silk_int64_MIN ((opus_int64)0x8000000000000000LL) /* -2^63 */
41#define silk_int32_MAX 0x7FFFFFFF /* 2^31 - 1 = 2147483647 */
42#define silk_int32_MIN ((opus_int32)0x80000000) /* -2^31 = -2147483648 */
43#define silk_int16_MAX 0x7FFF /* 2^15 - 1 = 32767 */
44#define silk_int16_MIN ((opus_int16)0x8000) /* -2^15 = -32768 */
45#define silk_int8_MAX 0x7F /* 2^7 - 1 = 127 */
46#define silk_int8_MIN ((opus_int8)0x80) /* -2^7 = -128 */
47#define silk_uint8_MAX 0xFF /* 2^8 - 1 = 255 */
48
49#define silk_TRUE 1
50#define silk_FALSE 0
51
52/* assertions */
53#if (defined _WIN32 && !defined _WINCE && !defined(__GNUC__) && !defined(NO_ASSERTS))
54# ifndef silk_assert
55# include <crtdbg.h> /* ASSERTE() */
56# define silk_assert(COND) _ASSERTE(COND)
57# endif
58#else
59# ifdef ENABLE_ASSERTIONS
60# include <stdio.h>
61# include <stdlib.h>
62#define silk_fatal(str) _silk_fatal(str, __FILE__, __LINE__);
63#ifdef __GNUC__
64__attribute__((noreturn))
65#endif
66static inline void _silk_fatal(const char *str, const char *file, int line)
67{
68 fprintf (stderr, "Fatal (internal) error in %s, line %d: %s\n", file, line, str);
69 abort();
70}
71# define silk_assert(COND) {if (!(COND)) {silk_fatal("assertion failed: " #COND);}}
72# else
73# define silk_assert(COND)
74# endif
75#endif
76
77#endif /* SILK_TYPEDEF_H */
diff --git a/lib/rbcodec/codecs/opus.c b/lib/rbcodec/codecs/opus.c
new file mode 100644
index 0000000000..19bdb8daae
--- /dev/null
+++ b/lib/rbcodec/codecs/opus.c
@@ -0,0 +1,461 @@
1/***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
9 *
10 * Copyright (C) 2012 Frederik M.J. Vestre
11 * Based on speex.c codec interface:
12 * Copyright (C) 2006 Frederik M.J. Vestre
13 * Based on vorbis.c codec interface:
14 * Copyright (C) 2002 Björn Stenberg
15 *
16 * This program is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU General Public License
18 * as published by the Free Software Foundation; either version 2
19 * of the License, or (at your option) any later version.
20 *
21 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
22 * KIND, either express or implied.
23 *
24 ****************************************************************************/
25
26#include "codeclib.h"
27#include "inttypes.h"
28#include "libopus/opus.h"
29#include "libopus/opus_header.h"
30
31
32#include "libopus/ogg/ogg.h"
33#ifdef SIMULATOR
34#include <tlsf.h>
35#endif
36
37CODEC_HEADER
38
39#define SEEK_REWIND 3840 /* 80 ms @ 48 kHz */
40
41/* the opus pseudo stack pointer */
42extern char *global_stack;
43
44/* Room for 120 ms of stereo audio at 48 kHz */
45#define MAX_FRAME_SIZE (2*120*48)
46#define CHUNKSIZE (16*1024)
47#define SEEK_CHUNKSIZE 7*CHUNKSIZE
48
49static int get_more_data(ogg_sync_state *oy)
50{
51 int bytes;
52 char *buffer;
53
54 buffer = (char *)ogg_sync_buffer(oy, CHUNKSIZE);
55 bytes = ci->read_filebuf(buffer, CHUNKSIZE);
56 ogg_sync_wrote(oy,bytes);
57
58 return bytes;
59}
60/* The read/seek functions track absolute position within the stream */
61static int64_t get_next_page(ogg_sync_state *oy, ogg_page *og,
62 int64_t boundary)
63{
64 int64_t localoffset = ci->curpos;
65 long more;
66 long ret;
67
68 if (boundary > 0)
69 boundary += ci->curpos;
70
71 while (1) {
72 more = ogg_sync_pageseek(oy,og);
73
74 if (more < 0) {
75 /* skipped n bytes */
76 localoffset-=more;
77 } else {
78 if (more == 0) {
79 /* send more data */
80 if(!boundary)return(-1);
81 {
82 ret = get_more_data(oy);
83 if (ret == 0)
84 return(-2);
85
86 if (ret < 0)
87 return(-3);
88 }
89 } else {
90 /* got a page. Return the offset at the page beginning,
91 advance the internal offset past the page end */
92
93 int64_t ret=localoffset;
94
95 return(ret);
96 }
97 }
98 }
99}
100
101static int64_t seek_backwards(ogg_sync_state *oy, ogg_page *og,
102 int64_t wantedpos)
103{
104 int64_t crofs;
105 int64_t *curoffset=&crofs;
106 *curoffset=ci->curpos;
107 int64_t begin=*curoffset;
108 int64_t end=begin;
109 int64_t ret;
110 int64_t offset=-1;
111 int64_t avgpagelen=-1;
112 int64_t lastgranule=-1;
113
114 short time = -1;
115
116 while (offset == -1) {
117
118 begin -= SEEK_CHUNKSIZE;
119
120 if (begin < 0) {
121 if (time < 0) {
122 begin = 0;
123 time++;
124 } else {
125 LOGF("Can't seek that early:%lld\n",begin);
126 return -3; /* too early */
127 }
128 }
129
130 *curoffset = begin;
131
132 ci->seek_buffer(*curoffset);
133
134 ogg_sync_reset(oy);
135
136 lastgranule = -1;
137
138 while (*curoffset < end) {
139 ret = get_next_page(oy,og,end-*curoffset);
140
141 if (ret > 0) {
142 if (lastgranule != -1) {
143 if (avgpagelen < 0)
144 avgpagelen = (ogg_page_granulepos(og)-lastgranule);
145 else
146 avgpagelen=((ogg_page_granulepos(og)-lastgranule)
147 + avgpagelen) / 2;
148 }
149
150 lastgranule=ogg_page_granulepos(og);
151
152 if ((lastgranule - (avgpagelen/4)) < wantedpos &&
153 (lastgranule + avgpagelen + (avgpagelen/4)) > wantedpos) {
154
155 /*wanted offset found Yeay!*/
156
157 /*LOGF("GnPagefound:%d,%d,%d,%d\n",ret,
158 lastgranule,wantedpos,avgpagelen);*/
159
160 return ret;
161
162 } else if (lastgranule > wantedpos) { /*too late, seek more*/
163 if (offset != -1) {
164 LOGF("Toolate, returnanyway:%lld,%lld,%lld,%lld\n",
165 ret,lastgranule,wantedpos,avgpagelen);
166 return ret;
167 }
168 break;
169 } else{ /*if (ogg_page_granulepos(&og)<wantedpos)*/
170 /*too early*/
171 offset = ret;
172 continue;
173 }
174 } else if (ret == -3)
175 return(-3);
176 else if (ret<=0)
177 break;
178 else if (*curoffset < end) {
179 /*this should not be possible*/
180
181 //LOGF("Seek:get_earlier_page:Offset:not_cached by granule:"\"%d,%d,%d,%d,%d\n",*curoffset,end,begin,wantedpos,curpos);
182
183 offset=ret;
184 }
185 }
186 }
187 return -1;
188}
189
190static int speex_seek_page_granule(int64_t pos, int64_t curpos,
191 ogg_sync_state *oy,
192 int64_t headerssize)
193{
194 /* TODO: Someone may want to try to implement seek to packet,
195 instead of just to page (should be more accurate, not be any
196 faster) */
197
198 int64_t crofs;
199 int64_t *curbyteoffset = &crofs;
200 *curbyteoffset = ci->curpos;
201 int64_t curoffset;
202 curoffset = *curbyteoffset;
203 int64_t offset = 0;
204 ogg_page og = {0,0,0,0};
205 int64_t avgpagelen = -1;
206 int64_t lastgranule = -1;
207
208 if(abs(pos-curpos)>10000 && headerssize>0 && curoffset-headerssize>10000) {
209 /* if seeking for more that 10sec,
210 headersize is known & more than 10kb is played,
211 try to guess a place to seek from the number of
212 bytes playe for this position, this works best when
213 the bitrate is relativly constant.
214 */
215
216 curoffset = (((*curbyteoffset-headerssize) * pos)/curpos)*98/100;
217 if (curoffset < 0)
218 curoffset=0;
219
220 //int64_t toffset=curoffset;
221
222 ci->seek_buffer(curoffset);
223
224 ogg_sync_reset(oy);
225
226 offset = get_next_page(oy,&og,-1);
227
228 if (offset < 0) { /* could not find new page,use old offset */
229 LOGF("Seek/guess/fault:%lld->-<-%d,%lld:%lld,%d,%ld,%d\n",
230 curpos,0,pos,offset,0,
231 ci->curpos,/*stream_length*/0);
232
233 curoffset = *curbyteoffset;
234
235 ci->seek_buffer(curoffset);
236
237 ogg_sync_reset(oy);
238 } else {
239 if (ogg_page_granulepos(&og) == 0 && pos > 5000) {
240 LOGF("SEEK/guess/fault:%lld->-<-%lld,%lld:%lld,%d,%ld,%d\n",
241 curpos,ogg_page_granulepos(&og),pos,
242 offset,0,ci->curpos,/*stream_length*/0);
243
244 curoffset = *curbyteoffset;
245
246 ci->seek_buffer(curoffset);
247
248 ogg_sync_reset(oy);
249 } else {
250 curoffset = offset;
251 curpos = ogg_page_granulepos(&og);
252 }
253 }
254 }
255
256 /* which way do we want to seek? */
257
258 if (curpos > pos) { /* backwards */
259 offset = seek_backwards(oy,&og,pos);
260
261 if (offset > 0) {
262 *curbyteoffset = curoffset;
263 return 1;
264 }
265 } else { /* forwards */
266
267 while ( (offset = get_next_page(oy,&og,-1)) > 0) {
268 if (lastgranule != -1) {
269 if (avgpagelen < 0)
270 avgpagelen = (ogg_page_granulepos(&og) - lastgranule);
271 else
272 avgpagelen = ((ogg_page_granulepos(&og) - lastgranule)
273 + avgpagelen) / 2;
274 }
275
276 lastgranule = ogg_page_granulepos(&og);
277
278 if ( ((lastgranule - (avgpagelen/4)) < pos && ( lastgranule +
279 avgpagelen + (avgpagelen / 4)) > pos) ||
280 lastgranule > pos) {
281
282 /*wanted offset found Yeay!*/
283
284 *curbyteoffset = offset;
285
286 return offset;
287 }
288 }
289 }
290
291 ci->seek_buffer(*curbyteoffset);
292
293 ogg_sync_reset(oy);
294
295 LOGF("Seek failed:%lld\n", offset);
296
297 return -1;
298}
299
300
301/* this is the codec entry point */
302enum codec_status codec_main(enum codec_entry_call_reason reason)
303{
304 (void)reason;
305
306 return CODEC_OK;
307}
308
309/* this is called for each file to process */
310enum codec_status codec_run(void)
311{
312 int error = CODEC_ERROR;
313 intptr_t param;
314 ogg_sync_state oy;
315 ogg_page og;
316 ogg_packet op;
317 ogg_stream_state os;
318 int64_t page_granule = 0;
319 int stream_init = 0;
320 int sample_rate = 48000;
321 OpusDecoder *st = NULL;
322 OpusHeader header;
323 int ret;
324 unsigned long strtoffset = ci->id3->offset;
325 int skip = 0;
326 int64_t seek_target;
327 uint64_t granule_pos;
328
329 /* reset our simple malloc */
330 if (codec_init()) {
331 goto done;
332 }
333 global_stack = 0;
334
335 /* pre-init the ogg_sync_state buffer, so it won't need many reallocs */
336 ogg_sync_init(&oy);
337 oy.storage = 64*1024;
338 oy.data = codec_malloc(oy.storage);
339
340 /* allocate output buffer */
341 uint16_t *output = (uint16_t*) codec_malloc(MAX_FRAME_SIZE*sizeof(uint16_t));
342
343 ci->seek_buffer(0);
344 ci->set_elapsed(0);
345
346 while (1) {
347 enum codec_command_action action = ci->get_command(&param);
348
349 if (action == CODEC_ACTION_HALT)
350 break;
351
352 if (action == CODEC_ACTION_SEEK_TIME) {
353 if (st != NULL) {
354 /* calculate granule to seek to (including seek rewind) */
355 seek_target = (48LL * param) + header.preskip;
356 skip = MIN(seek_target, SEEK_REWIND);
357 seek_target -= skip;
358
359 LOGF("Opus seek page:%lld,%lld,%ld\n",
360 seek_target, page_granule, (long)param);
361 speex_seek_page_granule(seek_target, page_granule, &oy, 0);
362 }
363
364 ci->set_elapsed(param);
365 ci->seek_complete();
366 }
367
368 /*Get the ogg buffer for writing*/
369 if (get_more_data(&oy) < 1) {
370 goto done;
371 }
372
373 /* Loop for all complete pages we got (most likely only one) */
374 while (ogg_sync_pageout(&oy, &og) == 1) {
375 if (stream_init == 0) {
376 ogg_stream_init(&os, ogg_page_serialno(&og));
377 stream_init = 1;
378 }
379
380 /* Add page to the bitstream */
381 ogg_stream_pagein(&os, &og);
382
383 page_granule = ogg_page_granulepos(&og);
384 granule_pos = page_granule;
385
386 while ((ogg_stream_packetout(&os, &op) == 1) && !op.e_o_s) {
387 if (op.packetno == 0){
388 /* identification header */
389
390 if (opus_header_parse(op.packet, op.bytes, &header) == 0) {
391 LOGF("Could not parse header");
392 goto done;
393 }
394 skip = header.preskip;
395
396 st = opus_decoder_create(sample_rate, header.channels, &ret);
397 if (ret != OPUS_OK) {
398 LOGF("opus_decoder_create failed %d", ret);
399 goto done;
400 }
401 LOGF("Decoder inited");
402
403 codec_set_replaygain(ci->id3);
404
405 opus_decoder_ctl(st, OPUS_SET_GAIN(header.gain));
406
407 ci->configure(DSP_SET_FREQUENCY, sample_rate);
408 ci->configure(DSP_SET_SAMPLE_DEPTH, 16);
409 ci->configure(DSP_SET_STEREO_MODE, (header.channels == 2) ?
410 STEREO_INTERLEAVED : STEREO_MONO);
411
412 } else if (op.packetno == 1) {
413 /* Comment header */
414 } else {
415 if (strtoffset) {
416 ci->seek_buffer(strtoffset);
417 ogg_sync_reset(&oy);
418 strtoffset = 0;
419 break;//next page
420 }
421
422 /* report progress */
423 ci->set_elapsed((granule_pos - header.preskip) / 48);
424
425 /* Decode audio packets */
426 ret = opus_decode(st, op.packet, op.bytes, output, MAX_FRAME_SIZE, 0);
427
428 if (ret > 0) {
429 if (skip > 0) {
430 if (ret <= skip) {
431 /* entire output buffer is skipped */
432 skip -= ret;
433 ret = 0;
434 } else {
435 /* part of output buffer is played */
436 ret -= skip;
437 ci->pcmbuf_insert(&output[skip * header.channels], NULL, ret);
438 skip = 0;
439 }
440 } else {
441 /* entire buffer is played */
442 ci->pcmbuf_insert(output, NULL, ret);
443 }
444 granule_pos += ret;
445 } else {
446 if (ret < 0) {
447 LOGF("opus_decode failed %d", ret);
448 goto done;
449 }
450 break;
451 }
452 }
453 }
454 }
455 }
456 LOGF("Returned OK");
457 error = CODEC_OK;
458done:
459 return error;
460}
461
diff --git a/lib/rbcodec/metadata/metadata.c b/lib/rbcodec/metadata/metadata.c
index 668ece97cf..5caf933b55 100644
--- a/lib/rbcodec/metadata/metadata.c
+++ b/lib/rbcodec/metadata/metadata.c
@@ -233,6 +233,9 @@ const struct afmt_entry audio_formats[AFMT_NUM_CODECS] =
233 /* KSS (MSX computer KSS Music File) */ 233 /* KSS (MSX computer KSS Music File) */
234 [AFMT_KSS] = 234 [AFMT_KSS] =
235 AFMT_ENTRY("KSS", "kss", NULL, get_kss_metadata, "kss\0"), 235 AFMT_ENTRY("KSS", "kss", NULL, get_kss_metadata, "kss\0"),
236 /* Opus */
237 [AFMT_OPUS] =
238 AFMT_ENTRY("Opus", "opus", NULL, get_ogg_metadata, "opus\0"),
236#endif 239#endif
237}; 240};
238 241
diff --git a/lib/rbcodec/metadata/metadata.h b/lib/rbcodec/metadata/metadata.h
index 4b4a8337fb..18cfce7523 100644
--- a/lib/rbcodec/metadata/metadata.h
+++ b/lib/rbcodec/metadata/metadata.h
@@ -89,6 +89,7 @@ enum
89 AFMT_SGC, /* SGC (Sega Master System, Game Gear, Coleco Vision Sound Format) */ 89 AFMT_SGC, /* SGC (Sega Master System, Game Gear, Coleco Vision Sound Format) */
90 AFMT_VGM, /* VGM (Video Game Music Format) */ 90 AFMT_VGM, /* VGM (Video Game Music Format) */
91 AFMT_KSS, /* KSS (MSX computer KSS Music File) */ 91 AFMT_KSS, /* KSS (MSX computer KSS Music File) */
92 AFMT_OPUS, /* Opus (see http://www.opus-codec.org ) */
92#endif 93#endif
93 94
94 /* add new formats at any index above this line to have a sensible order - 95 /* add new formats at any index above this line to have a sensible order -
diff --git a/lib/rbcodec/metadata/ogg.c b/lib/rbcodec/metadata/ogg.c
index f3231c6f8a..5d302442ed 100644
--- a/lib/rbcodec/metadata/ogg.c
+++ b/lib/rbcodec/metadata/ogg.c
@@ -102,6 +102,20 @@ bool get_ogg_metadata(int fd, struct mp3entry* id3)
102 return false; 102 return false;
103 } 103 }
104 } 104 }
105 else if (memcmp(&buf[28], "OpusHead", 8) == 0)
106 {
107 id3->codectype = AFMT_OPUS;
108 id3->frequency = 48000;
109 id3->vbr = true;
110
111// FIXME handle an actual channel mapping table
112 /* Comments are in second Ogg page (byte 108 onwards for Speex) */
113 if (lseek(fd, 47, SEEK_SET) < 0)
114 {
115 DEBUGF("Couldnotseektoogg");
116 return false;
117 }
118 }
105 else 119 else
106 { 120 {
107 /* Unsupported format, try to print the marker, catches Ogg/FLAC at least */ 121 /* Unsupported format, try to print the marker, catches Ogg/FLAC at least */
diff --git a/lib/rbcodec/metadata/vorbis.c b/lib/rbcodec/metadata/vorbis.c
index d020808c56..66aa85022f 100644
--- a/lib/rbcodec/metadata/vorbis.c
+++ b/lib/rbcodec/metadata/vorbis.c
@@ -250,7 +250,7 @@ static bool file_init(struct file* file, int fd, int type, int remaining)
250 memset(file, 0, sizeof(*file)); 250 memset(file, 0, sizeof(*file));
251 file->fd = fd; 251 file->fd = fd;
252 252
253 if (type == AFMT_OGG_VORBIS || type == AFMT_SPEEX) 253 if (type == AFMT_OGG_VORBIS || type == AFMT_SPEEX || type == AFMT_OPUS)
254 { 254 {
255 if (!file_read_page_header(file)) 255 if (!file_read_page_header(file))
256 { 256 {
@@ -276,6 +276,22 @@ static bool file_init(struct file* file, int fd, int type, int remaining)
276 return false; 276 return false;
277 } 277 }
278 } 278 }
279 else if (type == AFMT_OPUS)
280 {
281 char buffer[8];
282
283 /* Read comment header */
284 if (file_read(file, buffer, sizeof(buffer)) < (ssize_t) sizeof(buffer))
285 {
286 return false;
287 }
288
289 /* Should be equal to "OpusTags" */
290 if (memcmp(buffer, "OpusTags", 8) != 0)
291 {
292 return false;
293 }
294 }
279 else if (type == AFMT_FLAC) 295 else if (type == AFMT_FLAC)
280 { 296 {
281 file->packet_remaining = remaining; 297 file->packet_remaining = remaining;