Quellverzeichnis opus_encoder.c
Interaktion und PortierbarkeitC
/* Copyright (c) 2010-2011 Xiph.Org Foundation, Skype Limited
Written by Jean-Marc Valin and Koen Vos */ /* Redistributionanduseinsourceandbinaryforms,withorwithout modification,arepermittedprovidedthatthefollowingconditions aremet:
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 #ifdef ENABLE_QEXT int enable_qext; #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;
celt_glog * energy_masking;
StereoWidthState width_mem; #ifndef DISABLE_FLOAT_API int detected_bandwidth; #endif int nb_no_activity_ms_Q1;
opus_val32 peak_signal_energy; #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; /* Needs to be the last field because it may be partially or completely omitted. */
opus_res delay_buffer[MAX_ENCODER_BUFFER*2];
};
int opus_encoder_get_size(int channels)
{ int ret;
ret = opus_encoder_init(NULL, 48000, channels, OPUS_APPLICATION_AUDIO); if (ret < 0) return0; else return ret;
}
int opus_encoder_init(OpusEncoder* st, opus_int32 Fs, int channels, int application)
{ void *silk_enc=NULL;
CELTEncoder *celt_enc=NULL; int err; int ret, silkEncSizeBytes, celtEncSizeBytes=0; int tot_size; int base_size;
/* 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;
staticunsignedchar gen_toc(int mode, int framerate, int bandwidth, int channels)
{ int period; unsignedchar toc;
period = 0; while (framerate < 400)
{
framerate <<= 1;
period++;
} if (mode == MODE_SILK_ONLY)
{
toc = (bandwidth-OPUS_BANDWIDTH_NARROWBAND)<<5;
toc |= (period-2)<<3;
} elseif (mode == MODE_CELT_ONLY)
{ int tmp = bandwidth-OPUS_BANDWIDTH_MEDIUMBAND; if (tmp < 0)
tmp = 0;
toc = 0x80;
toc |= tmp << 5;
toc |= period<<3;
} else/* Hybrid */
{
toc = 0x60;
toc |= (bandwidth-OPUS_BANDWIDTH_SUPERWIDEBAND)<<4;
toc |= (period-2)<<3;
}
toc |= (channels==2)<<2; return toc;
}
#ifdef FIXED_POINT /* Second order ARMA filter, alternative implementation */ void silk_biquad_res( const opus_res *in, /* I input signal */ const opus_int32 *B_Q28, /* I MA coefficients [3] */ const opus_int32 *A_Q28, /* I AR coefficients [2] */
opus_int32 *S, /* I/O State vector [2] */
opus_res *out, /* O output signal */ const opus_int32 len, /* I signal length (must be even) */ int stride
)
{ /* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */
opus_int k;
opus_int32 inval, A0_U_Q28, A0_L_Q28, A1_U_Q28, A1_L_Q28, out32_Q14;
/* Negate A_Q28 values and split in two parts */
A0_L_Q28 = ( -A_Q28[ 0 ] ) & 0x00003FFF; /* lower part */
A0_U_Q28 = silk_RSHIFT( -A_Q28[ 0 ], 14 ); /* upper part */
A1_L_Q28 = ( -A_Q28[ 1 ] ) & 0x00003FFF; /* lower part */
A1_U_Q28 = silk_RSHIFT( -A_Q28[ 1 ], 14 ); /* upper part */
#ifndef DISABLE_FLOAT_API 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] = FLOAT2SIG(x[(j+offset)*C+c1]); if (c2>-1)
{ for (j=0;j<subframe;j++)
y[j] += FLOAT2SIG(x[(j+offset)*C+c2]);
} elseif (c2==-2)
{ int c; for (c=1;c<C;c++)
{ for (j=0;j<subframe;j++)
y[j] += FLOAT2SIG(x[(j+offset)*C+c]);
}
} #ifndef FIXED_POINT /* Cap signal to +6 dBFS to avoid problems in the analysis. */ for (j=0;j<subframe;j++)
{ if (y[j] < -65536.f) y[j] = -65536.f; if (y[j] > 65536.f) y[j] = 65536.f; if (celt_isnan(y[j])) y[j] = 0;
} #endif
} #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] = INT16TOSIG(x[(j+offset)*C+c1]); if (c2>-1)
{ for (j=0;j<subframe;j++)
y[j] += INT16TOSIG(x[(j+offset)*C+c2]);
} elseif (c2==-2)
{ int c; for (c=1;c<C;c++)
{ for (j=0;j<subframe;j++)
y[j] += INT16TOSIG(x[(j+offset)*C+c]);
}
}
}
void downmix_int24(constvoid *_x, opus_val32 *y, int subframe, int offset, int c1, int c2, int C)
{ const opus_int32 *x; int j;
x = (const opus_int32 *)_x; for (j=0;j<subframe;j++)
y[j] = INT24TOSIG(x[(j+offset)*C+c1]); if (c2>-1)
{ for (j=0;j<subframe;j++)
y[j] += INT24TOSIG(x[(j+offset)*C+c2]);
} elseif (c2==-2)
{ int c; for (c=1;c<C;c++)
{ for (j=0;j<subframe;j++)
y[j] += INT24TOSIG(x[(j+offset)*C+c]);
}
}
}
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) return0;
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) return1; elseif (PacketLoss_perc <= 5) return0; elseif (*bandwidth > OPUS_BANDWIDTH_NARROWBAND)
(*bandwidth)--; else break;
} /* Couldn't find any bandwidth to enable FEC, keep original bandwidth. */
*bandwidth = orig_bandwidth; return0;
}
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; staticconstint rate_table[][5] = { /* |total| |-------- SILK------------| |--NoFEC-||---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;
}
int is_digital_silence(const opus_res* pcm, int frame_size, int channels, int lsb_depth)
{ int silence = 0;
opus_val32 sample_max = 0; #ifdef MLP_TRAINING return0; #endif
sample_max = celt_maxabs_res(pcm, frame_size*channels);
#ifdef FIXED_POINT static opus_val32 compute_frame_energy(const opus_res *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 = RES2INT16(celt_maxabs_res(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(RES2INT16(pcm[i]), RES2INT16(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 milliseconds in this update, in Q1 */
)
{ if (!activity)
{ /* The number of consecutive DTX frames should be within the allowed bounds. NotethattheallowedboundisdefinedintheSILKheadersandassumes20ms frames.Asthisfunctioncanbecalledwithanyframelength,aconversionto
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! */ return1; else
(*nb_no_activity_ms_Q1) = NB_SPEECH_FRAMES_BEFORE_DTX*20*2;
}
} else
(*nb_no_activity_ms_Q1) = 0;
return0;
}
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_res *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, #endif int is_silence, int redundancy, int celt_to_silk, int prefill,
opus_int32 equiv_rate, int to_celt);
opus_int32 opus_encode_native(OpusEncoder *st, const opus_res *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=NULL;
CELTEncoder *celt_enc=NULL; 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=NULL; int packet_size_cap = 1276; #ifndef DISABLE_FLOAT_API
AnalysisInfo analysis_info; int analysis_read_pos_bak=-1; int analysis_read_subframe_bak=-1; #endif int is_silence = 0; #ifdef ENABLE_DRED
opus_int32 dred_bitrate_bps; #endif
ALLOC_STACK;
#ifdef ENABLE_QEXT if (st->enable_qext) packet_size_cap = QEXT_PACKET_SIZE_CAP; #endif
/* Just avoid insane packet sizes here, but the real bounds are applied later on. */
max_data_bytes = IMIN(packet_size_cap*6, out_data_bytes);
/* 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; #ifndef DISABLE_FLOAT_API
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));
}
/* Track the peak signal energy */ #ifndef DISABLE_FLOAT_API if (!analysis_info.valid || analysis_info.activity_probability > DTX_ACTIVITY_THRESHOLD) #endif
{ if (!is_silence)
{
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));
}
} if (st->channels==2 && st->force_channels!=1)
stereo_width = compute_stereo_width(pcm, frame_size, st->Fs, &st->width_mem); else
stereo_width = 0;
st->bitrate_bps = user_bitrate_to_bitrate(st, frame_size, max_data_bytes);
frame_rate = st->Fs/frame_size; if (!st->use_vbr)
{
cbr_bytes = IMIN((bitrate_to_bits(st->bitrate_bps, st->Fs, frame_size)+4)/8, max_data_bytes);
st->bitrate_bps = bits_to_bitrate(cbr_bytes*8, st->Fs, frame_size); /* 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*(opus_int32)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 && !is_silence; #endif
/* Mode selection depending on application and signal type */ if (st->application == OPUS_APPLICATION_RESTRICTED_SILK)
{
st->mode = MODE_SILK_ONLY;
} elseif (st->application == OPUS_APPLICATION_RESTRICTED_LOWDELAY || st->application == OPUS_APPLICATION_RESTRICTED_CELT)
{
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 < bitrate_to_bits(frame_rate > 50 ? 9000 : 6000, st->Fs, frame_size)/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)
{
celt_assert(st->application != OPUS_APPLICATION_RESTRICTED_SILK);
st->mode = MODE_CELT_ONLY;
} if (st->lfe && st->application != OPUS_APPLICATION_RESTRICTED_SILK)
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 getsitwrongwhenwecouldhavecodedahighbandwidthtransparently. WhenoperatinginSILK/hybridmode,wedon'tgobelowwidebandtoavoid
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;
if (st->application == OPUS_APPLICATION_RESTRICTED_SILK && curr_bandwidth > OPUS_BANDWIDTH_WIDEBAND)
st->bandwidth = curr_bandwidth = OPUS_BANDWIDTH_WIDEBAND; /* 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; int bak_to_mono;
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
/* Worst cases: *2frames:Code2withdifferentcompressedsizes
* >2 frames: Code 3 VBR */
max_header_bytes = nb_frames == 2 ? 3 : (2+(nb_frames-1)*2); #ifdef ENABLE_QEXT /* Cover the use of the separators that are the only thing that can get us over onceweconsiderthatweneedtosubtracttheextensionoverheadineach oftheindividualframes.Alsoconsiderthataseparatorcangetourpadding
from 254 to 255, which costs an extra length byte (at most once). */ if (st->enable_qext) max_header_bytes += (nb_frames-1) + 1; #endif
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(bitrate_to_bits(st->bitrate_bps, st->Fs, enc_frame_size)/8, max_len_sum/nb_frames); #ifdef ENABLE_DRED
curr_max = IMIN(curr_max, (max_len_sum-bitrate_to_bits(dred_bitrate_bps, st->Fs, frame_size)/8)/nb_frames); if (first_frame) curr_max += bitrate_to_bits(dred_bitrate_bps, st->Fs, frame_size)/8; #endif #ifdef ENABLE_QEXT /* Leave room for signaling the extension size once we repacketize. */ if (st->enable_qext)
curr_max -= curr_max/254; #endif
curr_max = IMIN(max_len_sum-tot_size, curr_max); #ifndef DISABLE_FLOAT_API if (analysis_read_pos_bak != -1) { /* Get analysis for current frame. */
tonality_get_info(&st->analysis, &analysis_info, enc_frame_size);
} #endif
is_silence = is_digital_silence(pcm+i*(st->channels*enc_frame_size), enc_frame_size, st->channels, lsb_depth);
static opus_int32 opus_encode_frame_native(OpusEncoder *st, const opus_res *pcm, int frame_size, unsignedchar *data, opus_int32 orig_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, #endif int is_silence, int redundancy, int celt_to_silk, int prefill,
opus_int32 equiv_rate, int to_celt)
{ void *silk_enc=NULL;
CELTEncoder *celt_enc=NULL; const CELTMode *celt_mode=NULL; int i; int ret=0; int max_data_bytes;
opus_int32 nBytes;
ec_enc enc; int bits_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_res, pcm_buf);
VARDECL(opus_res, tmp_prefill);
SAVE_STACK;
if (is_silence)
{
activity = !is_silence;
} #ifndef DISABLE_FLOAT_API 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 elseif (st->mode == MODE_CELT_ONLY) {
opus_val32 noise_energy = compute_frame_energy(pcm, frame_size, st->channels, st->arch); /* Boosting peak energy a bit because we didn't just average the active frames. */
activity = st->peak_signal_energy < (QCONST16(PSEUDO_SNR_THRESHOLD, 0) * (opus_val64)HALF32(noise_energy));
}
/* 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;
} if (st->application == OPUS_APPLICATION_RESTRICTED_SILK)
{
redundancy = 0;
redundancy_bytes = 0;
}
st->silk_mode.maxInternalSampleRate = 16000; if (st->mode == MODE_SILK_ONLY)
{
opus_int32 effective_max_rate = bits_to_bitrate(max_data_bytes*8, st->Fs, frame_size); if (frame_rate > 50)
effective_max_rate = effective_max_rate*2/3; if (effective_max_rate < 8000)
{
st->silk_mode.maxInternalSampleRate = 12000;
st->silk_mode.desiredInternalSampleRate = IMIN(12000, st->silk_mode.desiredInternalSampleRate);
} if (effective_max_rate < 7000)
{
st->silk_mode.maxInternalSampleRate = 8000;
st->silk_mode.desiredInternalSampleRate = IMIN(8000, st->silk_mode.desiredInternalSampleRate);
} #ifdef ENABLE_QEXT /* At 96 kHz, we don't have the input resampler to do 8 or 12 kHz. */ if (st->Fs==96000) st->silk_mode.maxInternalSampleRate = st->silk_mode.desiredInternalSampleRate = 16000; #endif
}
st->silk_mode.useCBR = !st->use_vbr;
/* Call SILK encoder for the low band */
/* Max bits for SILK, counting ToC, redundancy bytes, and optionally redundancy. */
st->silk_mode.maxBits = (max_data_bytes-1)*8; if (redundancy && redundancy_bytes >= 2)
{ /* Counting 1 bit for redundancy position and 20 bits for flag+size (only for hybrid). */
st->silk_mode.maxBits -= redundancy_bytes*8 + 1; if (st->mode == MODE_HYBRID)
st->silk_mode.maxBits -= 20;
} if (st->silk_mode.useCBR)
{ /* When we're in CBR mode, but we have non-SILK data to encode, switch SILK to VBR with cap to saveoncomplexity.AnyvariationswillbeabsorbedbyCELTand/orDREDandwecanstill
produce a constant bitrate without wasting bits. */ #ifdef ENABLE_DRED if (st->mode == MODE_HYBRID || dred_bitrate_bps > 0) #else if (st->mode == MODE_HYBRID) #endif
{ /* Allow SILK to steal up to 25% of the remaining bits */
opus_int16 other_bits = IMAX(0, st->silk_mode.maxBits - st->silk_mode.bitRate * frame_size / st->Fs);
st->silk_mode.maxBits = IMAX(0, st->silk_mode.maxBits - other_bits*3/4);
st->silk_mode.useCBR = 0;
}
} else { /* Constrained VBR. */ if (st->mode == MODE_HYBRID)
{ /* Compute SILK bitrate corresponding to the max total bits available */
opus_int32 maxBitRate = compute_silk_rate_for_hybrid(st->silk_mode.maxBits*st->Fs / frame_size,
curr_bandwidth, st->Fs == 50 * frame_size, st->use_vbr, st->silk_mode.LBRR_coded,
st->stream_channels);
st->silk_mode.maxBits = bitrate_to_bits(maxBitRate, st->Fs, frame_size);
}
}
if (prefill && st->application != OPUS_APPLICATION_RESTRICTED_SILK)
{
opus_int32 zero=0; int prefill_offset; /* Use a smooth onset for the SILK prefill to avoid the encoder trying to encode adiscontinuity.Theexactlocationiswhatweneedtoavoidleavingany"gap" intheaudiowhenmixingwiththeredundantCELTframe.Herewecanaffordto overwritest->delay_bufferbecausetheonlythingthatusesitbeforeitgets rewrittenistmp_prefill[]andeventhenonlythepartaftertherampreally
gets used (rather than sent to the encoder and discarded) */
prefill_offset = st->channels*(st->encoder_buffer-st->delay_compensation-st->Fs/400);
gain_fade(st->delay_buffer+prefill_offset, st->delay_buffer+prefill_offset, 0, Q15ONE, celt_mode->overlap, st->Fs/400, st->channels, celt_mode->window, st->Fs);
OPUS_CLEAR(st->delay_buffer, prefill_offset);
pcm_silk = st->delay_buffer;
silk_Encode( silk_enc, &st->silk_mode, pcm_silk, st->encoder_buffer, NULL, &zero, prefill, activity ); /* Prevent a second switch in the real encode call. */
st->silk_mode.opusCanSwitch = 0;
}
if ( st->mode != MODE_CELT_ONLY && ec_tell(&enc)+17+20*(st->mode == MODE_HYBRID) <= 8*(max_data_bytes-1))
{ /* For SILK mode, the redundancy is inferred from the length */ if (st->mode == MODE_HYBRID)
ec_enc_bit_logp(&enc, redundancy, 12); if (redundancy)
{ int max_redundancy;
ec_enc_bit_logp(&enc, celt_to_silk, 1); if (st->mode == MODE_HYBRID)
{ /* Reserve the 8 bits needed for the redundancy length,
and at least a few bits for CELT if possible */
max_redundancy = (max_data_bytes-1)-((ec_tell(&enc)+8+3+7)>>3);
} else
max_redundancy = (max_data_bytes-1)-((ec_tell(&enc)+7)>>3); /* Target the same bit-rate for redundancy as for the rest,
up to a max of 257 bytes */
redundancy_bytes = IMIN(max_redundancy, redundancy_bytes);
redundancy_bytes = IMIN(257, IMAX(2, redundancy_bytes)); if (st->mode == MODE_HYBRID)
ec_enc_uint(&enc, redundancy_bytes-2, 256);
}
} else {
redundancy = 0;
}
if (!redundancy)
{
st->silk_bw_switch = 0;
redundancy_bytes = 0;
} if (st->mode != MODE_CELT_ONLY)start_band=17;
if (st->mode == MODE_SILK_ONLY)
{
ret = (ec_tell(&enc)+7)>>3;
ec_enc_done(&enc);
nb_compr_bytes = ret;
} else {
nb_compr_bytes = (max_data_bytes-1)-redundancy_bytes; #ifdef ENABLE_QEXT if (st->mode == MODE_CELT_ONLY && st->enable_qext) {
celt_assert(redundancy_bytes==0);
nb_compr_bytes = orig_max_data_bytes-1;
} #endif #ifdef ENABLE_DRED if (st->dred_duration > 0)
{ int max_celt_bytes;
opus_int32 dred_bytes = bitrate_to_bits(dred_bitrate_bps, st->Fs, frame_size)/8; /* Allow CELT to steal up to 25% of the remaining bits. */
max_celt_bytes = nb_compr_bytes - dred_bytes*3/4; /* But try to give CELT at least 5 bytes to prevent a mismatch with
the redundancy signaling. */
max_celt_bytes = IMAX((ec_tell(&enc)+7)/8 + 5, max_celt_bytes); /* Subject to the original max. */
nb_compr_bytes = IMIN(nb_compr_bytes, max_celt_bytes);
} #endif
ec_enc_shrink(&enc, nb_compr_bytes);
}
if (st->mode == MODE_HYBRID)
{ /* Shrink packet to what the encoder actually used. */
nb_compr_bytes = ret;
ec_enc_shrink(&enc, nb_compr_bytes);
} /* NOTE: We could speed this up slightly (at the expense of code size) by just adding a function that prefills the buffer */
celt_encode_with_ec(celt_enc, pcm_buf+st->channels*(frame_size-N2-N4), N4, dummy, 2, NULL);
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.81Angebot
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 2026-09-28)
¤
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.