/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
Written by Jean-Marc Valin and Koen Vos */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
struct OpusEncoder { int celt_enc_offset; int silk_enc_offset;
silk_EncControlStruct silk_mode; #ifdef ENABLE_DRED
DREDEnc dred_encoder; #endif int application; int channels; int delay_compensation; int force_channels; int signal_type; int user_bandwidth; int max_bandwidth; int user_forced_mode; int voice_ratio;
opus_int32 Fs; int use_vbr; int vbr_constraint; int variable_duration;
opus_int32 bitrate_bps;
opus_int32 user_bitrate_bps; int lsb_depth; int encoder_buffer; int lfe; int arch; int use_dtx; /* general DTX for both SILK and CELT */ int fec_config; #ifndef DISABLE_FLOAT_API
TonalityAnalysisState analysis; #endif
#define OPUS_ENCODER_RESET_START stream_channels int stream_channels;
opus_int16 hybrid_stereo_width_Q14;
opus_int32 variable_HP_smth2_Q15;
opus_val16 prev_HB_gain;
opus_val32 hp_mem[4]; int mode; int prev_mode; int prev_channels; int prev_framesize; int bandwidth; /* Bandwidth determined automatically from the rate (before any other adjustment) */ int auto_bandwidth; int silk_bw_switch; /* Sampling rate (at the API level) */ int first;
opus_val16 * energy_masking;
StereoWidthState width_mem;
opus_val16 delay_buffer[MAX_ENCODER_BUFFER*2]; #ifndef DISABLE_FLOAT_API int detected_bandwidth; int nb_no_activity_ms_Q1;
opus_val32 peak_signal_energy; #endif #ifdef ENABLE_DRED int dred_duration; int dred_q0; int dred_dQ; int dred_qmax; int dred_target_chunks; unsignedchar activity_mem[DRED_MAX_FRAMES*4]; /* 2.5ms resolution*/ #endif int nonfinal_frame; /* current frame is not the final in a packet */
opus_uint32 rangeFinal;
};
/* Transition tables for the voice and music. First column is the middle (memoriless) threshold. The second column is the hysteresis
(difference with the middle) */ staticconst opus_int32 mono_voice_bandwidth_thresholds[8] = {
9000, 700, /* NB<->MB */
9000, 700, /* MB<->WB */
13500, 1000, /* WB<->SWB */
14000, 2000, /* SWB<->FB */
}; staticconst opus_int32 mono_music_bandwidth_thresholds[8] = {
9000, 700, /* NB<->MB */
9000, 700, /* MB<->WB */
11000, 1000, /* WB<->SWB */
12000, 2000, /* SWB<->FB */
}; staticconst opus_int32 stereo_voice_bandwidth_thresholds[8] = {
9000, 700, /* NB<->MB */
9000, 700, /* MB<->WB */
13500, 1000, /* WB<->SWB */
14000, 2000, /* SWB<->FB */
}; staticconst opus_int32 stereo_music_bandwidth_thresholds[8] = {
9000, 700, /* NB<->MB */
9000, 700, /* MB<->WB */
11000, 1000, /* WB<->SWB */
12000, 2000, /* SWB<->FB */
}; /* Threshold bit-rates for switching between mono and stereo */ staticconst opus_int32 stereo_voice_threshold = 19000; staticconst opus_int32 stereo_music_threshold = 17000;
/* Threshold bit-rate for switching between SILK/hybrid and CELT-only */ staticconst opus_int32 mode_thresholds[2][2] = { /* voice */ /* music */
{ 64000, 10000}, /* mono */
{ 44000, 10000}, /* stereo */
};
int opus_encoder_get_size(int channels)
{ int silkEncSizeBytes, celtEncSizeBytes; int ret; if (channels<1 || channels > 2) return 0;
ret = silk_Get_Encoder_Size( &silkEncSizeBytes ); if (ret) return 0;
silkEncSizeBytes = align(silkEncSizeBytes);
celtEncSizeBytes = celt_encoder_get_size(channels); return align(sizeof(OpusEncoder))+silkEncSizeBytes+celtEncSizeBytes;
}
int opus_encoder_init(OpusEncoder* st, opus_int32 Fs, int channels, int application)
{ void *silk_enc;
CELTEncoder *celt_enc; int err; int ret, silkEncSizeBytes;
/* Delay compensation of 4 ms (2.5 ms for SILK's extra look-ahead
+ 1.5 ms for SILK resamplers and stereo prediction) */
st->delay_compensation = st->Fs/250;
void downmix_float(constvoid *_x, opus_val32 *y, int subframe, int offset, int c1, int c2, int C)
{ constfloat *x; int j;
x = (constfloat *)_x; for (j=0;j<subframe;j++)
y[j] = PCM2VAL(x[(j+offset)*C+c1]); if (c2>-1)
{ for (j=0;j<subframe;j++)
y[j] += PCM2VAL(x[(j+offset)*C+c2]);
} elseif (c2==-2)
{ int c; for (c=1;c<C;c++)
{ for (j=0;j<subframe;j++)
y[j] += PCM2VAL(x[(j+offset)*C+c]);
}
}
} #endif
void downmix_int(constvoid *_x, opus_val32 *y, int subframe, int offset, int c1, int c2, int C)
{ const opus_int16 *x; int j;
x = (const opus_int16 *)_x; for (j=0;j<subframe;j++)
y[j] = x[(j+offset)*C+c1]; if (c2>-1)
{ for (j=0;j<subframe;j++)
y[j] += x[(j+offset)*C+c2];
} elseif (c2==-2)
{ int c; for (c=1;c<C;c++)
{ for (j=0;j<subframe;j++)
y[j] += x[(j+offset)*C+c];
}
}
}
opus_val16 compute_stereo_width(const opus_val16 *pcm, int frame_size, opus_int32 Fs, StereoWidthState *mem)
{
opus_val32 xx, xy, yy;
opus_val16 sqrt_xx, sqrt_yy;
opus_val16 qrrt_xx, qrrt_yy; int frame_rate; int i;
opus_val16 short_alpha;
frame_rate = Fs/frame_size;
short_alpha = Q15ONE - MULT16_16(25, Q15ONE)/IMAX(50,frame_rate);
xx=xy=yy=0; /* Unroll by 4. The frame size is always a multiple of 4 *except* for 2.5 ms frames at 12 kHz. Since this setting is very rare (and very
stupid), we just discard the last two samples. */ for (i=0;i<frame_size-3;i+=4)
{
opus_val32 pxx=0;
opus_val32 pxy=0;
opus_val32 pyy=0;
opus_val16 x, y;
x = pcm[2*i];
y = pcm[2*i+1];
pxx = SHR32(MULT16_16(x,x),2);
pxy = SHR32(MULT16_16(x,y),2);
pyy = SHR32(MULT16_16(y,y),2);
x = pcm[2*i+2];
y = pcm[2*i+3];
pxx += SHR32(MULT16_16(x,x),2);
pxy += SHR32(MULT16_16(x,y),2);
pyy += SHR32(MULT16_16(y,y),2);
x = pcm[2*i+4];
y = pcm[2*i+5];
pxx += SHR32(MULT16_16(x,x),2);
pxy += SHR32(MULT16_16(x,y),2);
pyy += SHR32(MULT16_16(y,y),2);
x = pcm[2*i+6];
y = pcm[2*i+7];
pxx += SHR32(MULT16_16(x,x),2);
pxy += SHR32(MULT16_16(x,y),2);
pyy += SHR32(MULT16_16(y,y),2);
staticint decide_fec(int useInBandFEC, int PacketLoss_perc, int last_fec, int mode, int *bandwidth, opus_int32 rate)
{ int orig_bandwidth; if (!useInBandFEC || PacketLoss_perc == 0 || mode == MODE_CELT_ONLY) return 0;
orig_bandwidth = *bandwidth; for (;;)
{
opus_int32 hysteresis;
opus_int32 LBRR_rate_thres_bps; /* Compute threshold for using FEC at the current bandwidth setting */
LBRR_rate_thres_bps = fec_thresholds[2*(*bandwidth - OPUS_BANDWIDTH_NARROWBAND)];
hysteresis = fec_thresholds[2*(*bandwidth - OPUS_BANDWIDTH_NARROWBAND) + 1]; if (last_fec == 1) LBRR_rate_thres_bps -= hysteresis; if (last_fec == 0) LBRR_rate_thres_bps += hysteresis;
LBRR_rate_thres_bps = silk_SMULWB( silk_MUL( LBRR_rate_thres_bps,
125 - silk_min( PacketLoss_perc, 25 ) ), SILK_FIX_CONST( 0.01, 16 ) ); /* If loss <= 5%, we look at whether we have enough rate to enable FEC.
If loss > 5%, we decrease the bandwidth until we can enable FEC. */ if (rate > LBRR_rate_thres_bps) return 1; elseif (PacketLoss_perc <= 5) return 0; elseif (*bandwidth > OPUS_BANDWIDTH_NARROWBAND)
(*bandwidth)--; else break;
} /* Couldn't find any bandwidth to enable FEC, keep original bandwidth. */
*bandwidth = orig_bandwidth; return 0;
}
staticint compute_silk_rate_for_hybrid(int rate, int bandwidth, int frame20ms, int vbr, int fec, int channels) { int entry; int i; int N; int silk_rate; staticint rate_table[][5] = { /* |total| |-------- SILK------------| |-- No FEC -| |--- FEC ---|
10ms 20ms 10ms 20ms */
{ 0, 0, 0, 0, 0},
{12000, 10000, 10000, 11000, 11000},
{16000, 13500, 13500, 15000, 15000},
{20000, 16000, 16000, 18000, 18000},
{24000, 18000, 18000, 21000, 21000},
{32000, 22000, 22000, 28000, 28000},
{64000, 38000, 38000, 50000, 50000}
}; /* Do the allocation per-channel. */
rate /= channels;
entry = 1 + frame20ms + 2*fec;
N = sizeof(rate_table)/sizeof(rate_table[0]); for (i=1;i<N;i++)
{ if (rate_table[i][0] > rate) break;
} if (i == N)
{
silk_rate = rate_table[i-1][entry]; /* For now, just give 50% of the extra bits to SILK. */
silk_rate += (rate-rate_table[i-1][0])/2;
} else {
opus_int32 lo, hi, x0, x1;
lo = rate_table[i-1][entry];
hi = rate_table[i][entry];
x0 = rate_table[i-1][0];
x1 = rate_table[i][0];
silk_rate = (lo*(x1-rate) + hi*(rate-x0))/(x1-x0);
} if (!vbr)
{ /* Tiny boost to SILK for CBR. We should probably tune this better. */
silk_rate += 100;
} if (bandwidth==OPUS_BANDWIDTH_SUPERWIDEBAND)
silk_rate += 300;
silk_rate *= channels; /* Small adjustment for stereo (calibrated for 32 kb/s, haven't tried other bitrates). */ if (channels == 2 && rate >= 12000)
silk_rate -= 1000; return silk_rate;
}
/* Returns the equivalent bitrate corresponding to 20 ms frames,
complexity 10 VBR operation. */ static opus_int32 compute_equiv_rate(opus_int32 bitrate, int channels, int frame_rate, int vbr, int mode, int complexity, int loss)
{
opus_int32 equiv;
equiv = bitrate; /* Take into account overhead from smaller frames. */ if (frame_rate > 50)
equiv -= (40*channels+20)*(frame_rate - 50); /* CBR is about a 8% penalty for both SILK and CELT. */ if (!vbr)
equiv -= equiv/12; /* Complexity makes about 10% difference (from 0 to 10) in general. */
equiv = equiv * (90+complexity)/100; if (mode == MODE_SILK_ONLY || mode == MODE_HYBRID)
{ /* SILK complexity 0-1 uses the non-delayed-decision NSQ, which
costs about 20%. */ if (complexity<2)
equiv = equiv*4/5;
equiv -= equiv*loss/(6*loss + 10);
} elseif (mode == MODE_CELT_ONLY) { /* CELT complexity 0-4 doesn't have the pitch filter, which costs
about 10%. */ if (complexity<5)
equiv = equiv*9/10;
} else { /* Mode not known yet */ /* Half the SILK loss*/
equiv -= equiv*loss/(12*loss + 20);
} return equiv;
}
#ifndef DISABLE_FLOAT_API
int is_digital_silence(const opus_val16* pcm, int frame_size, int channels, int lsb_depth)
{ int silence = 0;
opus_val32 sample_max = 0; #ifdef MLP_TRAINING return 0; #endif
sample_max = celt_maxabs16(pcm, frame_size*channels);
#ifdef FIXED_POINT static opus_val32 compute_frame_energy(const opus_val16 *pcm, int frame_size, int channels, int arch)
{ int i;
opus_val32 sample_max; int max_shift; int shift;
opus_val32 energy = 0; int len = frame_size*channels;
(void)arch; /* Max amplitude in the signal */
sample_max = celt_maxabs16(pcm, len);
/* Compute the right shift required in the MAC to avoid an overflow */
max_shift = celt_ilog2(len);
shift = IMAX(0, (celt_ilog2(1+sample_max) << 1) + max_shift - 28);
/* Compute the energy */ for (i=0; i<len; i++)
energy += SHR32(MULT16_16(pcm[i], pcm[i]), shift);
/* Normalize energy by the frame size and left-shift back to the original position */
energy /= len;
energy = SHL32(energy, shift);
return energy;
} #else static opus_val32 compute_frame_energy(const opus_val16 *pcm, int frame_size, int channels, int arch)
{ int len = frame_size*channels; return celt_inner_prod(pcm, pcm, len, arch)/len;
} #endif
/* Decides if DTX should be turned on (=1) or off (=0) */ staticint decide_dtx_mode(opus_int activity, /* indicates if this frame contains speech/music */ int *nb_no_activity_ms_Q1, /* number of consecutive milliseconds with no activity, in Q1 */ int frame_size_ms_Q1 /* number of miliseconds in this update, in Q1 */
)
{ if (!activity)
{ /* The number of consecutive DTX frames should be within the allowed bounds. Note that the allowed bound is defined in the SILK headers and assumes 20 ms frames. As this function can be called with any frame length, a conversion to
milliseconds is done before the comparisons. */
(*nb_no_activity_ms_Q1) += frame_size_ms_Q1; if (*nb_no_activity_ms_Q1 > NB_SPEECH_FRAMES_BEFORE_DTX*20*2)
{ if (*nb_no_activity_ms_Q1 <= (NB_SPEECH_FRAMES_BEFORE_DTX + MAX_CONSECUTIVE_DTX)*20*2) /* Valid frame for DTX! */ return 1; else
(*nb_no_activity_ms_Q1) = NB_SPEECH_FRAMES_BEFORE_DTX*20*2;
}
} else
(*nb_no_activity_ms_Q1) = 0;
return 0;
}
#endif
staticint compute_redundancy_bytes(opus_int32 max_data_bytes, opus_int32 bitrate_bps, int frame_rate, int channels)
{ int redundancy_bytes_cap; int redundancy_bytes;
opus_int32 redundancy_rate; int base_bits;
opus_int32 available_bits;
base_bits = (40*channels+20);
/* Equivalent rate for 5 ms frames. */
redundancy_rate = bitrate_bps + base_bits*(200 - frame_rate); /* For VBR, further increase the bitrate if we can afford it. It's pretty short
and we'll avoid artefacts. */
redundancy_rate = 3*redundancy_rate/2;
redundancy_bytes = redundancy_rate/1600;
/* Compute the max rate we can use given CBR or VBR with cap. */
available_bits = max_data_bytes*8 - 2*base_bits;
redundancy_bytes_cap = (available_bits*240/(240+48000/frame_rate) + base_bits)/8;
redundancy_bytes = IMIN(redundancy_bytes, redundancy_bytes_cap); /* It we can't get enough bits for redundancy to be worth it, rely on the decoder PLC. */ if (redundancy_bytes > 4 + 8*channels)
redundancy_bytes = IMIN(257, redundancy_bytes); else
redundancy_bytes = 0; return redundancy_bytes;
}
static opus_int32 opus_encode_frame_native(OpusEncoder *st, const opus_val16 *pcm, int frame_size, unsignedchar *data, opus_int32 max_data_bytes, int float_api, int first_frame, #ifdef ENABLE_DRED
opus_int32 dred_bitrate_bps, #endif #ifndef DISABLE_FLOAT_API
AnalysisInfo *analysis_info, int is_silence, #endif int redundancy, int celt_to_silk, int prefill,
opus_int32 equiv_rate, int to_celt);
opus_int32 opus_encode_native(OpusEncoder *st, const opus_val16 *pcm, int frame_size, unsignedchar *data, opus_int32 out_data_bytes, int lsb_depth, constvoid *analysis_pcm, opus_int32 analysis_size, int c1, int c2, int analysis_channels, downmix_func downmix, int float_api)
{ void *silk_enc;
CELTEncoder *celt_enc; int i; int ret=0; int prefill=0; int redundancy = 0; int celt_to_silk = 0; int to_celt = 0; int voice_est; /* Probability of voice in Q7 */
opus_int32 equiv_rate; int frame_rate;
opus_int32 max_rate; /* Max bitrate we're allowed to use */ int curr_bandwidth;
opus_int32 max_data_bytes; /* Max number of bytes we're allowed to use */
opus_int32 cbr_bytes=-1;
opus_val16 stereo_width; const CELTMode *celt_mode; #ifndef DISABLE_FLOAT_API
AnalysisInfo analysis_info; int analysis_read_pos_bak=-1; int analysis_read_subframe_bak=-1; int is_silence = 0; #endif #ifdef ENABLE_DRED
opus_int32 dred_bitrate_bps; #endif
ALLOC_STACK;
/* Track the peak signal energy */ if (!is_silence && analysis_info.activity_probability > DTX_ACTIVITY_THRESHOLD)
st->peak_signal_energy = MAX32(MULT16_32_Q15(QCONST16(0.999f, 15), st->peak_signal_energy),
compute_frame_energy(pcm, frame_size, st->channels, st->arch));
} elseif (st->analysis.initialized) {
tonality_analysis_reset(&st->analysis);
} #else
(void)analysis_pcm;
(void)analysis_size;
(void)c1;
(void)c2;
(void)analysis_channels;
(void)downmix; #endif
#ifndef DISABLE_FLOAT_API /* Reset voice_ratio if this frame is not silent or if analysis is disabled.
* Otherwise, preserve voice_ratio from the last non-silent frame */ if (!is_silence)
st->voice_ratio = -1;
st->detected_bandwidth = 0; if (analysis_info.valid)
{ int analysis_bandwidth; if (st->signal_type == OPUS_AUTO)
{ float prob; if (st->prev_mode == 0)
prob = analysis_info.music_prob; elseif (st->prev_mode == MODE_CELT_ONLY)
prob = analysis_info.music_prob_max; else
prob = analysis_info.music_prob_min;
st->voice_ratio = (int)floor(.5+100*(1-prob));
}
frame_rate = st->Fs/frame_size; if (!st->use_vbr)
{ /* Multiply by 12 to make sure the division is exact. */ int frame_rate12 = 12*st->Fs/frame_size; /* We need to make sure that "int" values always fit in 16 bits. */
cbr_bytes = IMIN( (12*st->bitrate_bps/8 + frame_rate12/2)/frame_rate12, max_data_bytes);
st->bitrate_bps = cbr_bytes*(opus_int32)frame_rate12*8/12; /* Make sure we provide at least one byte to avoid failing. */
max_data_bytes = IMAX(1, cbr_bytes);
} #ifdef ENABLE_DRED /* Allocate some of the bits to DRED if needed. */
dred_bitrate_bps = compute_dred_bitrate(st, st->bitrate_bps, frame_size);
st->bitrate_bps -= dred_bitrate_bps; #endif if (max_data_bytes<3 || st->bitrate_bps < 3*frame_rate*8
|| (frame_rate<50 && (max_data_bytes*frame_rate<300 || st->bitrate_bps < 2400)))
{ /*If the space is too low to do something useful, emit 'PLC' frames.*/ int tocmode = st->mode; int bw = st->bandwidth == 0 ? OPUS_BANDWIDTH_NARROWBAND : st->bandwidth; int packet_code = 0; int num_multiframes = 0;
if (tocmode==0)
tocmode = MODE_SILK_ONLY; if (frame_rate>100)
tocmode = MODE_CELT_ONLY; /* 40 ms -> 2 x 20 ms if in CELT_ONLY or HYBRID mode */ if (frame_rate==25 && tocmode!=MODE_SILK_ONLY)
{
frame_rate = 50;
packet_code = 1;
}
/* >= 60 ms frames */ if (frame_rate<=16)
{ /* 1 x 60 ms, 2 x 40 ms, 2 x 60 ms */ if (out_data_bytes==1 || (tocmode==MODE_SILK_ONLY && frame_rate!=10))
{
tocmode = MODE_SILK_ONLY;
/* Allow SILK DTX if DTX is enabled but the generalized DTX cannot be used,
e.g. because of the complexity setting or sample rate. */ #ifndef DISABLE_FLOAT_API
st->silk_mode.useDTX = st->use_dtx && !(analysis_info.valid || is_silence); #else
st->silk_mode.useDTX = st->use_dtx; #endif
/* Mode selection depending on application and signal type */ if (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY)
{
st->mode = MODE_CELT_ONLY;
} elseif (st->user_forced_mode == OPUS_AUTO)
{ #ifdef FUZZING
(void)stereo_width;
(void)mode_thresholds; /* Random mode switching */ if ((rand()&0xF)==0)
{ if ((rand()&0x1)==0)
st->mode = MODE_CELT_ONLY; else
st->mode = MODE_SILK_ONLY;
} else { if (st->prev_mode==MODE_CELT_ONLY)
st->mode = MODE_CELT_ONLY; else
st->mode = MODE_SILK_ONLY;
} #else
opus_int32 mode_voice, mode_music;
opus_int32 threshold;
/* Interpolate based on stereo width */
mode_voice = (opus_int32)(MULT16_32_Q15(Q15ONE-stereo_width,mode_thresholds[0][0])
+ MULT16_32_Q15(stereo_width,mode_thresholds[1][0]));
mode_music = (opus_int32)(MULT16_32_Q15(Q15ONE-stereo_width,mode_thresholds[1][1])
+ MULT16_32_Q15(stereo_width,mode_thresholds[1][1])); /* Interpolate based on speech/music probability */
threshold = mode_music + ((voice_est*voice_est*(mode_voice-mode_music))>>14); /* Bias towards SILK for VoIP because of some useful features */ if (st->application == OPUS_APPLICATION_VOIP)
threshold += 8000;
/* When FEC is enabled and there's enough packet loss, use SILK.
Unless the FEC is set to 2, in which case we don't switch to SILK if we're confident we have music. */ if (st->silk_mode.useInBandFEC && st->silk_mode.packetLossPercentage > (128-voice_est)>>4 && (st->fec_config != 2 || voice_est > 25))
st->mode = MODE_SILK_ONLY; /* When encoding voice and DTX is enabled but the generalized DTX cannot be used,
use SILK in order to make use of its DTX. */ if (st->silk_mode.useDTX && voice_est > 100)
st->mode = MODE_SILK_ONLY; #endif
/* If max_data_bytes represents less than 6 kb/s, switch to CELT-only mode */ if (max_data_bytes < (frame_rate > 50 ? 9000 : 6000)*frame_size / (st->Fs * 8))
st->mode = MODE_CELT_ONLY;
} else {
st->mode = st->user_forced_mode;
}
/* Override the chosen mode to make sure we meet the requested frame size */ if (st->mode != MODE_CELT_ONLY && frame_size < st->Fs/100)
st->mode = MODE_CELT_ONLY; if (st->lfe)
st->mode = MODE_CELT_ONLY;
if (st->prev_mode > 0 &&
((st->mode != MODE_CELT_ONLY && st->prev_mode == MODE_CELT_ONLY) ||
(st->mode == MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY)))
{
redundancy = 1;
celt_to_silk = (st->mode != MODE_CELT_ONLY); if (!celt_to_silk)
{ /* Switch to SILK/hybrid if frame size is 10 ms or more*/ if (frame_size >= st->Fs/100)
{
st->mode = st->prev_mode;
to_celt = 1;
} else {
redundancy=0;
}
}
}
/* When encoding multiframes, we can ask for a switch to CELT only in the last frame. This switch
* is processed above as the requested mode shouldn't interrupt stereo->mono transition. */ if (st->stream_channels == 1 && st->prev_channels ==2 && st->silk_mode.toMono==0
&& st->mode != MODE_CELT_ONLY && st->prev_mode != MODE_CELT_ONLY)
{ /* Delay stereo->mono transition by two frames so that SILK can do a smooth downmix */
st->silk_mode.toMono = 1;
st->stream_channels = 2;
} else {
st->silk_mode.toMono = 0;
}
if (st->channels==2 && st->force_channels!=1)
{
voice_bandwidth_thresholds = stereo_voice_bandwidth_thresholds;
music_bandwidth_thresholds = stereo_music_bandwidth_thresholds;
} else {
voice_bandwidth_thresholds = mono_voice_bandwidth_thresholds;
music_bandwidth_thresholds = mono_music_bandwidth_thresholds;
} /* Interpolate bandwidth thresholds depending on voice estimation */ for (i=0;i<8;i++)
{
bandwidth_thresholds[i] = music_bandwidth_thresholds[i]
+ ((voice_est*voice_est*(voice_bandwidth_thresholds[i]-music_bandwidth_thresholds[i]))>>14);
} do { int threshold, hysteresis;
threshold = bandwidth_thresholds[2*(bandwidth-OPUS_BANDWIDTH_MEDIUMBAND)];
hysteresis = bandwidth_thresholds[2*(bandwidth-OPUS_BANDWIDTH_MEDIUMBAND)+1]; if (!st->first)
{ if (st->auto_bandwidth >= bandwidth)
threshold -= hysteresis; else
threshold += hysteresis;
} if (equiv_rate >= threshold) break;
} while (--bandwidth>OPUS_BANDWIDTH_NARROWBAND); /* We don't use mediumband anymore, except when explicitly requested or during
mode transitions. */ if (bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
bandwidth = OPUS_BANDWIDTH_WIDEBAND;
st->bandwidth = st->auto_bandwidth = bandwidth; /* Prevents any transition to SWB/FB until the SILK layer has fully
switched to WB mode and turned the variable LP filter off */ if (!st->first && st->mode != MODE_CELT_ONLY && !st->silk_mode.inWBmodeWithoutVariableLP && st->bandwidth > OPUS_BANDWIDTH_WIDEBAND)
st->bandwidth = OPUS_BANDWIDTH_WIDEBAND;
}
if (st->bandwidth>st->max_bandwidth)
st->bandwidth = st->max_bandwidth;
if (st->user_bandwidth != OPUS_AUTO)
st->bandwidth = st->user_bandwidth;
/* This prevents us from using hybrid at unsafe CBR/max rates */ if (st->mode != MODE_CELT_ONLY && max_rate < 15000)
{
st->bandwidth = IMIN(st->bandwidth, OPUS_BANDWIDTH_WIDEBAND);
}
/* Prevents Opus from wasting bits on frequencies that are above
the Nyquist rate of the input signal */ if (st->Fs <= 24000 && st->bandwidth > OPUS_BANDWIDTH_SUPERWIDEBAND)
st->bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND; if (st->Fs <= 16000 && st->bandwidth > OPUS_BANDWIDTH_WIDEBAND)
st->bandwidth = OPUS_BANDWIDTH_WIDEBAND; if (st->Fs <= 12000 && st->bandwidth > OPUS_BANDWIDTH_MEDIUMBAND)
st->bandwidth = OPUS_BANDWIDTH_MEDIUMBAND; if (st->Fs <= 8000 && st->bandwidth > OPUS_BANDWIDTH_NARROWBAND)
st->bandwidth = OPUS_BANDWIDTH_NARROWBAND; #ifndef DISABLE_FLOAT_API /* Use detected bandwidth to reduce the encoded bandwidth. */ if (st->detected_bandwidth && st->user_bandwidth == OPUS_AUTO)
{ int min_detected_bandwidth; /* Makes bandwidth detection more conservative just in case the detector gets it wrong when we could have coded a high bandwidth transparently. When operating in SILK/hybrid mode, we don't go below wideband to avoid
more complicated switches that require redundancy. */ if (equiv_rate <= 18000*st->stream_channels && st->mode == MODE_CELT_ONLY)
min_detected_bandwidth = OPUS_BANDWIDTH_NARROWBAND; elseif (equiv_rate <= 24000*st->stream_channels && st->mode == MODE_CELT_ONLY)
min_detected_bandwidth = OPUS_BANDWIDTH_MEDIUMBAND; elseif (equiv_rate <= 30000*st->stream_channels)
min_detected_bandwidth = OPUS_BANDWIDTH_WIDEBAND; elseif (equiv_rate <= 44000*st->stream_channels)
min_detected_bandwidth = OPUS_BANDWIDTH_SUPERWIDEBAND; else
min_detected_bandwidth = OPUS_BANDWIDTH_FULLBAND;
/* CELT mode doesn't support mediumband, use wideband instead */ if (st->mode == MODE_CELT_ONLY && st->bandwidth == OPUS_BANDWIDTH_MEDIUMBAND)
st->bandwidth = OPUS_BANDWIDTH_WIDEBAND; if (st->lfe)
st->bandwidth = OPUS_BANDWIDTH_NARROWBAND;
curr_bandwidth = st->bandwidth;
/* Chooses the appropriate mode for speech
*NEVER* switch to/from CELT-only mode here as this will invalidate some assumptions */ if (st->mode == MODE_SILK_ONLY && curr_bandwidth > OPUS_BANDWIDTH_WIDEBAND)
st->mode = MODE_HYBRID; if (st->mode == MODE_HYBRID && curr_bandwidth <= OPUS_BANDWIDTH_WIDEBAND)
st->mode = MODE_SILK_ONLY;
/* Can't support higher than >60 ms frames, and >20 ms when in Hybrid or CELT-only modes */ if ((frame_size > st->Fs/50 && (st->mode != MODE_SILK_ONLY)) || frame_size > 3*st->Fs/50)
{ int enc_frame_size; int nb_frames;
VARDECL(unsignedchar, tmp_data);
VARDECL(OpusRepacketizer, rp); int max_header_bytes;
opus_int32 repacketize_len;
opus_int32 max_len_sum;
opus_int32 tot_size=0; unsignedchar *curr_data; int tmp_len; int dtx_count = 0;
if (st->mode == MODE_SILK_ONLY)
{ if (frame_size == 2*st->Fs/25) /* 80 ms -> 2x 40 ms */
enc_frame_size = st->Fs/25; elseif (frame_size == 3*st->Fs/25) /* 120 ms -> 2x 60 ms */
enc_frame_size = 3*st->Fs/50; else/* 100 ms -> 5x 20 ms */
enc_frame_size = st->Fs/50;
} else
enc_frame_size = st->Fs/50;
nb_frames = frame_size/enc_frame_size;
#ifndef DISABLE_FLOAT_API if (analysis_read_pos_bak!= -1)
{ /* Reset analysis position to the beginning of the first frame so we
can use it one frame at a time. */
st->analysis.read_pos = analysis_read_pos_bak;
st->analysis.read_subframe = analysis_read_subframe_bak;
} #endif
int bak_to_mono = st->silk_mode.toMono; if (bak_to_mono)
st->force_channels = 1; else
st->prev_channels = st->stream_channels;
for (i=0;i<nb_frames;i++)
{ int first_frame; int frame_to_celt; int frame_redundancy;
opus_int32 curr_max; /* Attempt DRED encoding until we have a non-DTX frame. In case of DTX refresh,
that allows for DRED not to be in the first frame. */
first_frame = (i == 0) || (i == dtx_count);
st->silk_mode.toMono = 0;
st->nonfinal_frame = i<(nb_frames-1);
/* When switching from SILK/Hybrid to CELT, only ask for a switch at the last frame */
frame_to_celt = to_celt && i==nb_frames-1;
frame_redundancy = redundancy && (frame_to_celt || (!to_celt && i==0));
curr_max = IMIN(3*st->bitrate_bps/(3*8*st->Fs/enc_frame_size), max_len_sum/nb_frames); #ifdef ENABLE_DRED
curr_max = IMIN(curr_max, (max_len_sum-3*dred_bitrate_bps/(3*8*st->Fs/frame_size))/nb_frames); if (first_frame) curr_max += 3*dred_bitrate_bps/(3*8*st->Fs/frame_size); #endif
curr_max = IMIN(max_len_sum-tot_size, curr_max); #ifndef DISABLE_FLOAT_API if (analysis_read_pos_bak != -1) {
is_silence = is_digital_silence(pcm, frame_size, st->channels, lsb_depth); /* Get analysis for current frame. */
tonality_get_info(&st->analysis, &analysis_info, enc_frame_size);
} #endif
static opus_int32 opus_encode_frame_native(OpusEncoder *st, const opus_val16 *pcm, int frame_size, unsignedchar *data, opus_int32 max_data_bytes, int float_api, int first_frame, #ifdef ENABLE_DRED
opus_int32 dred_bitrate_bps, #endif #ifndef DISABLE_FLOAT_API
AnalysisInfo *analysis_info, int is_silence, #endif int redundancy, int celt_to_silk, int prefill,
opus_int32 equiv_rate, int to_celt)
{ void *silk_enc;
CELTEncoder *celt_enc; const CELTMode *celt_mode; int i; int ret=0;
opus_int32 nBytes;
ec_enc enc; int bytes_target; int start_band = 0; int redundancy_bytes = 0; /* Number of bytes to use for redundancy frame */ int nb_compr_bytes;
opus_uint32 redundant_rng = 0; int cutoff_Hz; int hp_freq_smth1;
opus_val16 HB_gain; int apply_padding; int frame_rate; int curr_bandwidth; int delay_compensation; int total_buffer;
opus_int activity = VAD_NO_DECISION;
VARDECL(opus_val16, pcm_buf);
VARDECL(opus_val16, tmp_prefill);
SAVE_STACK;
#ifndef DISABLE_FLOAT_API if (is_silence)
{
activity = !is_silence;
} elseif (analysis_info->valid)
{
activity = analysis_info->activity_probability >= DTX_ACTIVITY_THRESHOLD; if (!activity)
{ /* Mark as active if this noise frame is sufficiently loud */
opus_val32 noise_energy = compute_frame_energy(pcm, frame_size, st->channels, st->arch);
activity = st->peak_signal_energy < (PSEUDO_SNR_THRESHOLD * noise_energy);
}
} #endif
/* For the first frame at a new SILK bandwidth */ if (st->silk_bw_switch)
{
redundancy = 1;
celt_to_silk = 1;
st->silk_bw_switch = 0; /* Do a prefill without resetting the sampling rate control. */
prefill=2;
}
/* If we decided to go with CELT, make sure redundancy is off, no matter what
we decided earlier. */ if (st->mode == MODE_CELT_ONLY)
redundancy = 0;
if (redundancy)
{
redundancy_bytes = compute_redundancy_bytes(max_data_bytes, st->bitrate_bps, frame_rate, st->stream_channels); if (redundancy_bytes == 0)
redundancy = 0;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.