XGitUrl: https://git.xiph.org/?p=opus.git;a=blobdiff_plain;f=doc%2Fdraftietfcodecopus.xml;h=334cad97a27d7e7bf1cdd09f4914cb6a96ae4711;hp=61efb11f51248d24be6fb684a0cf0ee703cda9f7;hb=43e8bd46560d1aaf85fd682ab554e1f0753837ef;hpb=fd209c5e72e5569662f6103c9251863c92d46b6d
diff git a/doc/draftietfcodecopus.xml b/doc/draftietfcodecopus.xml
index 61efb11f..334cad97 100644
 a/doc/draftietfcodecopus.xml
+++ b/doc/draftietfcodecopus.xml
@@ 2,23 +2,23 @@

+Definition of the Opus Audio Codec
Octasic Inc.
+Mozilla Corporation
4101, Molson Street
Montreal
Quebec

Canada
+650 Castro Street
+Mountain View
+CA
+94041
+USA
+1 514 2828858
++1 650 9030800jmvalin@jmvalin.ca
@@ 27,18 +27,18 @@
Skype Technologies S.A.
Stadsgarden 6
+Soder Malarstrand 43Stockholm
11645
+11825SE
+46 855 921 989
++46 73 085 7619koen.vos@skype.net

+Mozilla Corporation
@@ 53,7 +53,7 @@

+
General
@@ 61,8 +61,14 @@
This document defines the Opus codec, designed for interactive speech and audio
 transmission over the Internet.
+This document defines the Opus interactive speech and audio codec.
+Opus is designed to handle a wide range of interactive audio applications,
+ including Voice over IP, videoconferencing, ingame chat, and even live,
+ distributed music performances.
+It scales from low bitrate narrowband speech at 6 kb/s to very high quality
+ stereo music at 510 kb/s.
+Opus uses both linear prediction (LP) and the Modified Discrete Cosine
+ Transform (MDCT) to achieve good compression of both speech and music.
@@ 71,11 +77,13 @@ This document defines the Opus codec, designed for interactive speech and audio
The Opus codec is a realtime interactive audio codec composed of a linear
 prediction (LP)based layer and a Modified Discrete Cosine Transform
 (MDCT)based layer.
+The Opus codec is a realtime interactive audio codec designed to meet the requirements
+described in .
+It is composed of a linear
+ prediction (LP)based layer and a Modified Discrete Cosine Transform
+ (MDCT)based layer.
The main idea behind using two layers is that in speech, linear prediction
 techniques (such as CELP) code low frequencies more efficiently than transform
+ techniques (such as CodeExcited Linear Prediction, or CELP) code low frequencies more efficiently than transform
(e.g., MDCT) domain techniques, while the situation is reversed for music and
higher speech frequencies.
Thus a codec with both layers available can operate over a wider range than
@@ 86,13 +94,13 @@ Thus a codec with both layers available can operate over a wider range than
The primary normative part of this specification is provided by the source code
in .
In general, only the decoder portion of this software is normative, though a
+Only the decoder portion of this software is normative, though a
significant amount of code is shared by both the encoder and decoder.

The decoder contains significant amounts of integer and fixedpoint arithmetic
 which must be performed exactly, including all rounding considerations, so any
 useful specification must make extensive use of domainspecific symbolic
 language to adequately define these operations.
+ provides a decoder conformance test.
+The decoder contains a great deal of integer and fixedpoint arithmetic which
+ needs to be performed exactly, including all rounding considerations, so any
+ useful specification requires domainspecific symbolic language to adequately
+ define these operations.
Additionally, any
conflict between the symbolic representation and the included reference
implementation must be resolved. For the practical reasons of compatibility and
@@ 104,7 +112,6 @@ For these reasons this RFC uses the reference implementation as the sole
symbolic representation of the codec.

While the symbolic representation is unambiguous and complete it is not
always the easiest way to understand the codec's operation. For this reason
this document also describes significant parts of the codec in English and
@@ 126,11 +133,11 @@ representation most clearly provides the "how".
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
"SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
 interpreted as described in RFC 2119.
+ interpreted as described in RFC 2119 .
Even when using floatingpoint, various operations in the codec require
 bitexact fixedpoint behavior.
+Various operations in the codec require bitexact fixedpoint behavior, even
+ when writing a floating point implementation.
The notation "Q<n>", where n is an integer, denotes the number of binary
digits to the right of the decimal point in a fixedpoint number.
For example, a signed Q14 value in a 16bit word can represent values from
@@ 142,35 +149,36 @@ E.g., the text will explicitly indicate any shifts required after a
Expressions, where included in the text, follow C operator rules and
 precedence, with the exception that syntax like "2**n" is used to indicate 2
 raised to the power n.
+ precedence, with the exception that the syntax "x**y" indicates x raised to
+ the power y.
The text also makes use of the following functions:

+
The smallest of two values x and y.

+
The largest of two values x and y.

+
With this definition, if lo>hi, the lower bound is the one that is enforced.
+With this definition, if lo > hi, the lower bound is the one that
+ is enforced.

+
The sign of x, i.e.,

+
+
+The absolute value of x, i.e.,
+
+
+
+
+
+
+The largest integer z such that z <= f.
+
+
+
+
+
+The smallest integer z such that z >= f.
+
+
+
+
+
+The integer z nearest to f, with ties rounded towards negative infinity,
+ i.e.,
+
+
+
+
+
The basetwo logarithm of f.

+
The minimum number of bits required to store a positive integer n in two's
complement notation, or 0 for a nonpositive integer n.
@@ 227,44 +270,63 @@ At any given time, either the LP layer, the MDCT layer, or both, may be active.
It can seamlessly switch between all of its various operating modes, giving it
a great deal of flexibility to adapt to varying content and network
conditions without renegotiating the current session.
Internally, the codec always operates at a 48 kHz sampling rate, though it
 allows input and output of various bandwidths, defined as follows:
+The codec allows input and output of various audio bandwidths, defined as
+ follows:

+AbbreviationAudio Bandwidth
Sampling Rate (Effective)
+Sample Rate (Effective)NB (narrowband)4 kHz8 kHzMB (mediumband)6 kHz12 kHzWB (wideband)8 kHz16 kHzSWB (superwideband)12 kHz24 kHz
FB (fullband)20 kHz48 kHz
+FB (fullband)20 kHz (*)48 kHz
These can be chosen independently on the encoder and decoder side, e.g., a
 fullband signal can be decoded as wideband, or vice versa.
This approach ensures a sender and receiver can always interoperate, regardless
 of the capabilities of their actual audio hardware.
+(*) Although the sampling theorem allows a bandwidth as large as half the
+ sampling rate, Opus never codes audio above 20 kHz, as that is the
+ generally accepted upper limit of human hearing.
The LP layer is based on the
 SILK codec
 .
It supports NB, MB, or WB audio and frame sizes from 10 ms to 60 ms,
 and requires an additional 5.2 ms lookahead for noise shaping estimation
 (5 ms) and internal resampling (0.2 ms).
Like Vorbis and many other modern codecs, SILK is inherently designed for
 variablebitrate (VBR) coding, though an encoder can with sufficient effort
 produce constantbitrate (CBR) or nearCBR streams.
+Opus defines superwideband (SWB) with an effective sample rate of 24 kHz,
+ unlike some other audio coding standards that use 32 kHz.
+This was chosen for a number of reasons.
+The band layout in the MDCT layer naturally allows skipping coefficients for
+ frequencies over 12 kHz, but does not allow cleanly dropping just those
+ frequencies over 16 kHz.
+A sample rate of 24 kHz also makes resampling in the MDCT layer easier,
+ as 24 evenly divides 48, and when 24 kHz is sufficient, it can save
+ computation in other processing, such as Acoustic Echo Cancellation (AEC).
+Experimental changes to the band layout to allow a 16 kHz cutoff
+ (32 kHz effective sample rate) showed potential quality degradations at
+ other sample rates, and at typical bitrates the number of bits saved by using
+ such a cutoff instead of coding in fullband (FB) mode is very small.
+Therefore, if an application wishes to process a signal sampled at 32 kHz,
+ it should just use FB.
The MDCT layer is based on the
 CELT codec
 .
It supports sampling NB, WB, SWB, or FB audio and frame sizes from 2.5 ms
 to 20 ms, and requires an additional 2.5 ms lookahead due to the
+The LP layer is based on the SILK codec
+ .
+It supports NB, MB, or WB audio and frame sizes from 10 ms to 60 ms,
+ and requires an additional 5 ms lookahead for noise shaping estimation.
+A small additional delay (up to 1.5 ms) may be required for sampling rate
+ conversion.
+Like Vorbis and many other modern codecs, SILK is inherently designed for
+ variablebitrate (VBR) coding, though the encoder can also produce
+ constantbitrate (CBR) streams.
+The version of SILK used in Opus is substantially modified from, and not
+ compatible with, the standalone SILK codec previously deployed by Skype.
+This document does not serve to define that format, but those interested in the
+ original SILK codec should see instead.
+
+
+
+The MDCT layer is based on the CELT codec .
+It supports NB, WB, SWB, or FB audio and frame sizes from 2.5 ms to
+ 20 ms, and requires an additional 2.5 ms lookahead due to the
overlapping MDCT windows.
The CELT codec is inherently designed for CBR coding, but unlike many CBR
codecs it is not limited to a set of predetermined rates.
@@ 277,22 +339,39 @@ On the other hand, nonspeech signals are not always adequately coded using
A hybrid mode allows the use of both layers simultaneously with a frame size of
 10 or 20 ms and a SWB or FB audio bandwidth.
Each frame is split into a low frequency signal and a high frequency signal,
 with a cutoff of 8 kHz.
The LP layer then codes the low frequency signal, followed by the MDCT layer
 coding the high frequency signal.
+A "Hybrid" mode allows the use of both layers simultaneously with a frame size
+ of 10 or 20 ms and a SWB or FB audio bandwidth.
+The LP layer codes the low frequencies by resampling the signal down to WB.
+The MDCT layer follows, coding the high frequency portion of the signal.
+The cutoff between the two lies at 8 kHz, the maximum WB audio bandwidth.
In the MDCT layer, all bands below 8 kHz are discarded, so there is no
coding redundancy between the two layers.
At the decoder, the two decoder outputs are simply added together.
To compensate for the different lookaheads required by each layer, the CELT
+The sample rate (in contrast to the actual audio bandwidth) can be chosen
+ independently on the encoder and decoder side, e.g., a fullband signal can be
+ decoded as wideband, or vice versa.
+This approach ensures a sender and receiver can always interoperate, regardless
+ of the capabilities of their actual audio hardware.
+Internally, the LP layer always operates at a sample rate of twice the audio
+ bandwidth, up to a maximum of 16 kHz, which it continues to use for SWB
+ and FB.
+The decoder simply resamples its output to support different sample rates.
+The MDCT layer always operates internally at a sample rate of 48 kHz.
+Since all the supported sample rates evenly divide this rate, and since the
+ the decoder may easily zero out the high frequency portion of the spectrum in
+ the frequency domain, it can simply decimate the MDCT layer output to achieve
+ the other supported sample rates very cheaply.
+
+
+
+After conversion to the common, desired output sample rate, the decoder simply
+ adds the output from the two layers together.
+To compensate for the different lookahead required by each layer, the CELT
encoder input is delayed by an additional 2.7 ms.
This ensures that low frequencies and high frequencies arrive at the same time.
This extra delay MAY be reduced by an encoder by using less lookahead for noise
+This extra delay may be reduced by an encoder by using less lookahead for noise
shaping or using a simpler resampler in the LP layer, but this will reduce
quality.
However, the base 2.5 ms lookahead in the CELT layer cannot be reduced in
@@ 308,27 +387,163 @@ Although the LP layer is VBR, the bit allocation of the MDCT layer can produce
a final stream that is CBR by using all the bits left unused by the LP layer.
+
+
+The Opus codec includes a number of control parameters which can be changed dynamically during
+regular operation of the codec, without interrupting the audio stream from the encoder to the decoder.
+These parameters only affect the encoder since any impact they have on the bitstream is signaled
+inband such that a decoder can decode any Opus stream without any outofband signaling. Any Opus
+implementation can add or modify these control parameters without affecting interoperability. The most
+important encoder control parameters in the reference encoder are listed below.
+
+
+
+
+Opus supports all bitrates from 6 kb/s to 510 kb/s. All other parameters being
+equal, higher bitrate results in higher quality. For a frame size of 20 ms, these
+are the bitrate "sweet spots" for Opus in various configurations:
+
+812 kb/s for NB speech,
+1620 kb/s for WB speech,
+2840 kb/s for FB speech,
+4864 kb/s for FB mono music, and
+64128 kb/s for FB stereo music.
+
+
+
+
+
+
+Opus can transmit either mono or stereo frames within a single stream.
+When decoding a mono frame in a stereo decoder, the left and right channels are
+ identical, and when decoding a stereo frame in a mono decoder, the mono output
+ is the average of the left and right channels.
+In some cases, it is desirable to encode a stereo input stream in mono (e.g.,
+ because the bitrate is too low to encode stereo with sufficient quality).
+The number of channels encoded can be selected in realtime, but by default the
+ reference encoder attempts to make the best decision possible given the
+ current bitrate.
+
+
+
+
+
+The audio bandwidths supported by Opus are listed in
+ .
+Just like for the number of channels, any decoder can decode audio encoded at
+ any bandwidth.
+For example, any Opus decoder operating at 8 kHz can decode a FB Opus
+ frame, and any Opus decoder operating at 48 kHz can decode a NB frame.
+Similarly, the reference encoder can take a 48 kHz input signal and
+ encode it as NB.
+The higher the audio bandwidth, the higher the required bitrate to achieve
+ acceptable quality.
+The audio bandwidth can be explicitly specified in realtime, but by default
+ the reference encoder attempts to make the best bandwidth decision possible
+ given the current bitrate.
+
+
+
+
+
+
+Opus can encode frames of 2.5, 5, 10, 20, 40 or 60 ms.
+It can also combine multiple frames into packets of up to 120 ms.
+For realtime applications, sending fewer packets per second reduces the
+ bitrate, since it reduces the overhead from IP, UDP, and RTP headers.
+However, it increases latency and sensitivity to packet losses, as losing one
+ packet constitutes a loss of a bigger chunk of audio.
+Increasing the frame duration also slightly improves coding efficiency, but the
+ gain becomes small for frame sizes above 20 ms.
+For this reason, 20 ms frames are a good choice for most applications.
+

+
As described, the two layers can be combined in three possible operating modes:

A LPonly mode for use in low bitrate connections with an audio bandwidth of
 WB or less,
A hybrid (LP+MDCT) mode for SWB or FB speech at medium bitrates, and
An MDCTonly mode for very low delay speech transmission as well as music
 transmission.
+There are various aspects of the Opus encoding process where tradeoffs
+can be made between CPU complexity and quality/bitrate. In the reference
+encoder, the complexity is selected using an integer from 0 to 10, where
+0 is the lowest complexity and 10 is the highest. Examples of
+computations for which such tradeoffs may occur are:
+
+The order of the pitch analysis whitening filter ,
+The order of the shortterm noise shaping filter,
+The number of states in delayed decision quantization of the
+residual signal, and
+The use of certain bitstream features such as variable timefrequency
+resolution and the pitch postfilter.
+
+
+
+
+Audio codecs often exploit interframe correlations to reduce the
+bitrate at a cost in error propagation: after losing one packet
+several packets need to be received before the decoder is able to
+accurately reconstruct the speech signal. The extent to which Opus
+exploits interframe dependencies can be adjusted on the fly to
+choose a tradeoff between bitrate and amount of error propagation.
+
+
+
+
+
+ Another mechanism providing robustness against packet loss is the inband
+ Forward Error Correction (FEC). Packets that are determined to
+ contain perceptually important speech information, such as onsets or
+ transients, are encoded again at a lower bitrate and this reencoded
+ information is added to a subsequent packet.
+
+
+
+
+
+Opus is more efficient when operating with variable bitrate (VBR), which is
+the default. However, in some (rare) applications, constant bitrate (CBR)
+is required. There are two main reasons to operate in CBR mode:
+
+When the transport only supports a fixed size for each compressed frame
+When encryption is used for an audio stream that is either highly constrained
+ (e.g. yes/no, recorded prompts) or highly sensitive
+
+
+When lowlatency transmission is required over a relatively slow connection, then
+constrained VBR can also be used. This uses VBR in a way that simulates a
+"bit reservoir" and is equivalent to what MP3 (MPEG 1, Layer 3) and
+AAC (Advanced Audio Coding) call CBR (i.e., not true
+CBR due to the bit reservoir).
+
+
+
+
+
+ Discontinuous Transmission (DTX) reduces the bitrate during silence
+ or background noise. When DTX is enabled, only one frame is encoded
+ every 400 milliseconds.
+
+
+
+
+
+
+
+
+
A single packet may contain multiple audio frames, however they must share a
+The Opus encoder produces "packets", which are each a contiguous set of bytes
+ meant to be transmitted as a single unit.
+The packets described here do not include such things as IP, UDP, or RTP
+ headers which are normally found in a transportlayer packet.
+A single packet may contain multiple audio frames, so long as they share a
common set of parameters, including the operating mode, audio bandwidth, frame
 size, and channel count.
+ size, and channel count (mono vs. stereo).
This section describes the possible combinations of these parameters and the
internal framing used to pack multiple frames into a single packet.
This framing is not selfdelimiting.
Instead, it assumes that a higher layer (such as UDP or RTP or Ogg or Matroska)
+Instead, it assumes that a higher layer (such as UDP or RTP
+or Ogg or Matroska )
will communicate the length, in bytes, of the packet, and it uses this
information to reduce the framing overhead in the packet itself.
A decoder implementation MUST support the framing described in this section.
@@ 337,22 +552,33 @@ An alternative, selfdelimiting variant of the framing is described in
Support for that variant is OPTIONAL.

An Opus packet begins with a singlebyte tableofcontents (TOC) header that
 signals which of the various modes and configurations a given packet uses.
It is composed of a frame count code, "c", a stereo flag, "s", and a
 configuration number, "config", arranged as illustrated in
+All bit diagrams in this document number the bits so that bit 0 is the most
+ significant bit of the first byte, and bit 7 is the least significant.
+Bit 8 is thus the most significant bit of the second byte, etc.
+Wellformed Opus packets obey certain requirements, marked [R1] through [R7]
+ below.
+These are summarized in along with
+ appropriate means of handling malformed packets.
+
+
+
+
+A wellformed Opus packet MUST contain at least one byte [R1].
+This byte forms a tableofcontents (TOC) header that signals which of the
+ various modes and configurations a given packet uses.
+It is composed of a configuration number, "config", a stereo flag, "s", and a
+ frame count code, "c", arranged as illustrated in
.
A description of each of these fields follows.

@@ 411,23 +650,25 @@ This section describes how frames are packed according to each possible value
When a packet contains multiple VBR frames, the compressed length of one or
 more of these frames is indicated with a one or two byte sequence, with the
 meaning of the first byte as follows:
+When a packet contains multiple VBR frames (i.e., code 2 or 3), the compressed
+ length of one or more of these frames is indicated with a one or twobyte
+ sequence, with the meaning of the first byte as follows:
0: No frame (DTX or lost packet)

1...251: Size of the frame in bytes
252...255: A second byte is needed. The total size is (size[1]*4)+size[0]
+0: No frame (discontinuous transmission (DTX) or lost packet)
+1...251: Length of the frame in bytes
+252...255: A second byte is needed. The total length is (second_byte*4)+first_byte
The maximum representable size is 255*4+255=1275 bytes. This limit MUST NOT
be exceeded, even when no length field is used.
+The special length 0 indicates that no frame is available, either because it
+ was dropped during transmission by some intermediary or because the encoder
+ chose not to transmit it.
+Any Opus frame in any mode MAY have a length of 0.
+
+
+
+The maximum representable length is 255*4+255=1275 bytes.
For 20 ms frames, this represents a bitrate of 510 kb/s, which is
approximately the highest useful rate for lossily compressed fullband stereo
music.
@@ 437,16 +678,17 @@ It is also roughly the maximum useful rate of the MDCT layer, as shortly
on the codebook sizes.

No length is transmitted for the last frame in a VBR packet, or any of the
+
+No length is transmitted for the last frame in a VBR packet, or for any of the
frames in a CBR packet, as it can be inferred from the total size of the
packet and the size of all other data in the packet.
However, the length of any individual frame MUST NOT exceed 1275 bytes, to
 allow for repacketization by gateways, conference bridges, or other software.
+However, the length of any individual frame MUST NOT exceed
+ 1275 bytes [R2], to allow for repacketization by gateways,
+ conference bridges, or other software.

+
For code 0 packets, the TOC byte is immediately followed by N1 bytes
@@ 458,7 +700,7 @@ For code 0 packets, the TOC byte is immediately followed by N1 bytes
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
00s config  
+ config s00 
+++++++++ 
 Compressed frame 1 (N1 bytes)... :
: 
@@ 468,21 +710,21 @@ For code 0 packets, the TOC byte is immediately followed by N1 bytes


+
+
For code 1 packets, the TOC byte is immediately followed by the
(N1)/2 bytes of compressed data for the first frame, followed by
(N1)/2 bytes of compressed data for the second frame, as illustrated in
.
The number of payload bytes available for compressed data, N1, MUST be even
 for all code 1 packets.
+ for all code 1 packets [R3].


For code 2 packets, the TOC byte is followed by a one or two byte sequence
 indicating the length of the first frame (marked N1 in the figure below),
+
+
+For code 2 packets, the TOC byte is followed by a one or twobyte sequence
+ indicating the length of the first frame (marked N1 in ),
followed by N1 bytes of compressed data for the first frame.
The remaining NN12 or NN13 bytes are the compressed data for the
second frame.
This is illustrated in .
The length of the first frame, N1, MUST be no larger than the size of the
 payload remaining after decoding that length for all code 2 packets.
+A code 2 packet MUST contain enough bytes to represent a valid length.
+For example, a 1byte code 2 packet is always invalid, and a 2byte code 2
+ packet whose second byte is in the range 252...255 is also invalid.
+The length of the first frame, N1, MUST also be no larger than the size of the
+ payload remaining after decoding that length for all code 2 packets [R4].
+This makes, for example, a 2byte code 2 packet with a second byte in the range
+ 1...251 invalid as well (the only valid 2byte code 2 packet is one where the
+ length of both frames is zero).


Code 3 packets may encode an arbitrary number of packets, as well as additional
+
+
+Code 3 packets signal the number of frames, as well as additional
padding, called "Opus padding" to indicate that this padding is added at the
Opus layer, rather than at the transport layer.
For code 3 packets, the TOC byte is followed by a byte encoding the number of
 frames in the packet in bits 0 to 5 (marked "M" in the figure below), with bit
 6 indicating whether or not Opus padding is inserted (marked "p" in the figure
 below), and bit 7 indicating VBR (marked "v" in the figure below).
+Code 3 packets MUST have at least 2 bytes [R6,R7].
+The TOC byte is followed by a byte encoding the number of frames in the packet
+ in bits 2 to 7 (marked "M" in ), with bit 1 indicating whether
+ or not Opus padding is inserted (marked "p" in ), and bit 0
+ indicating VBR (marked "v" in ).
M MUST NOT be zero, and the audio duration contained within a packet MUST NOT
 exceed 120 ms.
+ exceed 120 ms [R5].
This limits the maximum frame count for any frame size to 48 (for 2.5 ms
frames), with lower limits for longer frame sizes.
illustrates the layout of the frame count
@@ 547,7 +796,7 @@ This limits the maximum frame count for any frame size to 48 (for 2.5 ms
0
0 1 2 3 4 5 6 7
+++++++++
 M pv
+vp M 
+++++++++
]]>
@@ 558,22 +807,35 @@ Values from 0...254 indicate that 0...254 bytes of padding are included,
in addition to the byte(s) used to indicate the size of the padding.
If the value is 255, then the size of the additional padding is 254 bytes,
plus the padding value encoded in the next byte.
The additional padding bytes appear at the end of the packet, and SHOULD be set
 to zero by the encoder, however the decoder MUST accept any value for the
 padding bytes.
By using code 255 multiple times, it is possible to create a packet of any
+There MUST be at least one more byte in the packet in this case [R6,R7].
+The additional padding bytes appear at the end of the packet, and MUST be set
+ to zero by the encoder to avoid creating a covert channel.
+The decoder MUST accept any value for the padding bytes, however.
+
+
+Although this encoding provides multiple ways to indicate a given number of
+ padding bytes, each uses a different number of bytes to indicate the padding
+ size, and thus will increase the total packet size by a different amount.
+For example, to add 255 bytes to a packet, set the padding bit, p, to 1, insert
+ a single byte after the frame count byte with a value of 254, and append 254
+ padding bytes with the value zero to the end of the packet.
+To add 256 bytes to a packet, set the padding bit to 1, insert two bytes after
+ the frame count byte with the values 255 and 0, respectively, and append 254
+ padding bytes with the value zero to the end of the packet.
+By using the value 255 multiple times, it is possible to create a packet of any
specific, desired size.
Let P be the total amount of padding, including both the trailing padding bytes
 themselves and the header bytes used to indicate how many there are.
Then P MUST be no more than N2 for CBR packets, or NM1 for VBR packets.
+Let P be the number of header bytes used to indicate the padding size plus the
+ number of padding bytes themselves (i.e., P is the total number of bytes added
+ to the packet).
+Then P MUST be no more than N2 [R6,R7].

In the CBR case, the compressed length of each frame in bytes is equal to the
 number of remaining bytes in the packet after subtracting the (optional)
 padding, (N2P), divided by M.
This number MUST be an integer multiple of M.
The compressed data for all M frames then follows, each of size
 (N2P)/M bytes, as illustrated in .
+
+In the CBR case, let R=N2P be the number of bytes remaining in the packet
+ after subtracting the (optional) padding.
+Then the compressed length of each frame in bytes is equal to R/M.
+The value R MUST be a nonnegative integer multiple of M [R6].
+The compressed data for all M frames follows, each of size
+ R/M bytes, as illustrated in .
@@ 581,14 +843,14 @@ The compressed data for all M frames then follows, each of size
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
11s config  M p0 Padding length (Optional) :
+ config s110p M  Padding length (Optional) :
+++++++++++++++++++++++++++++++++
 
: Compressed frame 1 ((N2P)/M bytes)... :
+: Compressed frame 1 (R/M bytes)... :
 
+++++++++++++++++++++++++++++++++
 
: Compressed frame 2 ((N2P)/M bytes)... :
+: Compressed frame 2 (R/M bytes)... :
 
+++++++++++++++++++++++++++++++++
 
@@ 596,7 +858,7 @@ The compressed data for all M frames then follows, each of size
 
+++++++++++++++++++++++++++++++++
 
: Compressed frame M ((N2P)/M bytes)... :
+: Compressed frame M (R/M bytes)... :
 
+++++++++++++++++++++++++++++++++
: Opus Padding (Optional)... 
@@ 604,19 +866,19 @@ The compressed data for all M frames then follows, each of size
]]>

+
In the VBR case, the (optional) padding length is followed by M1 frame
 lengths (indicated by "N1" to "N[M1]" in the figure below), each encoded in a
 one or two byte sequence as described above.
The packet MUST contain enough data for the M1 lengths after the (optional)
 padding, and the sum of these lengths MUST be no larger than the number of
 bytes remaining in the packet after decoding them.
+ lengths (indicated by "N1" to "N[M1]" in ), each encoded in a
+ one or twobyte sequence as described above.
+The packet MUST contain enough data for the M1 lengths after removing the
+ (optional) padding, and the sum of these lengths MUST be no larger than the
+ number of bytes remaining in the packet after decoding them [R7].
The compressed data for all M frames follows, each frame consisting of the
indicated number of bytes, with the final frame consuming any remaining bytes
before the final padding, as illustrated in .
The number of header bytes (TOC byte, frame count byte, padding length bytes,
 and frame length bytes), plus the length of the first M1 frames themselves,
 plus the length of the padding MUST be no larger than N, the total size of the
+ and frame length bytes), plus the signaled length of the first M1 frames themselves,
+ plus the signaled length of the padding MUST be no larger than N, the total size of the
packet.
@@ 625,7 +887,7 @@ The number of header bytes (TOC byte, frame count byte, padding length bytes,
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
11s config  M p1 Padding length (Optional) :
+ config s111p M  Padding length (Optional) :
+++++++++++++++++++++++++++++++++
: N1 (12 bytes): N2 (12 bytes): ... : N[M1] 
+++++++++++++++++++++++++++++++++
@@ 657,12 +919,12 @@ The number of header bytes (TOC byte, frame count byte, padding length bytes,
Simplest case, one NB mono 20 ms SILK frame:

+
@@ 671,26 +933,26 @@ Simplest case, one NB mono 20 ms SILK frame:
Two FB mono 5 ms CELT frames of the same compressed size:

+
Two FB mono 20 ms hybrid frames of different compressed size:
+Two FB mono 20 ms Hybrid frames of different compressed size:

+

+

+
A receiver MUST NOT process packets which violate the rules above as normal
 Opus packets.
+A receiver MUST NOT process packets which violate any of the rules above as
+ normal Opus packets.
They are reserved for future applications, such as inband headers (containing
 metadata, etc.) or multichannel support.
+ metadata, etc.).
+Packets which violate these constraints may cause implementations of
+ this specification to treat them as malformed, and
+ discard them.
+
+
+These constraints are summarized here for reference:
+
+Packets are at least one byte.
+No implicit frame length is larger than 1275 bytes.
+Code 1 packets have an odd total length, N, so that (N1)/2 is an
+ integer.
+Code 2 packets have enough bytes after the TOC for a valid frame
+ length, and that length is no larger than the number of bytes remaining in the
+ packet.
+Code 3 packets contain at least one frame, but no more than 120 ms
+ of audio total.
+The length of a CBR code 3 packet, N, is at least two bytes, the number of
+ bytes added to indicate the padding size plus the trailing padding bytes
+ themselves, P, is no more than N2, and the frame count, M, satisfies
+ the constraint that (N2P) is a nonnegative integer multiple of M.
+VBR code 3 packets are large enough to contain all the header bytes (TOC
+ byte, frame count byte, any padding length bytes, and any frame length bytes),
+ plus the length of the first M1 frames, plus any trailing padding bytes.
+
@@ 725,37 +1011,40 @@ They are reserved for future applications, such as inband headers (containing
The Opus decoder consists of two main blocks: the SILK decoder and the CELT decoder.
The output of the Opus decode is the sum of the outputs from the SILK and CELT decoders
with proper sample rate conversion and delay compensation as illustrated in the
block diagram below. At any given time, one or both of the SILK and CELT decoders
may be active.
+The Opus decoder consists of two main blocks: the SILK decoder and the CELT
+ decoder.
+At any given time, one or both of the SILK and CELT decoders may be active.
+The output of the Opus decode is the sum of the outputs from the SILK and CELT
+ decoders with proper sample rate conversion and delay compensation on the SILK
+ side, and optional decimation (when decoding to sample rates less than
+ 48 kHz) on the CELT side, as illustrated in the block diagram below.
decoder> rate +
bit ++    conversion v
stream  Range + ++ ++ /\ audio
>decoder  + >
  + ++ ++ \/
 ++   CELT   Delay  ^
 +>decoder compens +
    ation 
 ++ ++
+ ++ ++
+  SILK   Sample 
+ +> Decoder > Rate +
+Bit ++     Conversion  v
+stream  Range + ++ ++ /\ Audio
+> Decoder   + >
+  + ++ ++ \/
+ ++   CELT   Decimation  ^
+ +> Decoder > (Optional) +
+    
+ ++ ++
]]>
Opus uses an entropy coder based on ,
+Opus uses an entropy coder based on range coding
+,
which is itself a rediscovery of the FIFO arithmetic code introduced by .
It is very similar to arithmetic encoding, except that encoding is done with
digits in any base instead of with bits,
so it is faster when using larger bases (i.e., an octet). All of the
+so it is faster when using larger bases (i.e., a byte). All of the
calculations in the range coder must use bitexact integer arithmetic.
@@ 772,16 +1061,16 @@ Raw bits are only used in the CELT layer.
:
+ Range coder data (packed MSB to LSB) > :
+ +
: :
+ ++++++++++++++++++++++++++++++
:  < Boundary occurs at an arbitrary bit position :
++++ +
: < Raw bits data (packed LSb to MSb) 
+: < Raw bits data (packed LSB to MSB) 
+++++++++++++++++++++++++++++++++
]]>
@@ 790,46 +1079,52 @@ Raw bits are only used in the CELT layer.
Each symbol coded by the range coder is drawn from a finite alphabet and coded
in a separate "context", which describes the size of the alphabet and the
relative frequency of each symbol in that alphabet.
Opus only uses static contexts.
They are not adapted to the statistics of the data as it is coded.
Suppose there is a context with n symbols, identified with an index that ranges
from 0 to n1.
The parameters needed to encode or decode a symbol in this context are
+The parameters needed to encode or decode symbol k in this context are
represented by a threetuple (fl[k], fh[k], ft), with
0 <= fl[k] < fh[k] <= ft <= 65535.
The values of this tuple are derived from the probability model for the
 symbol, represented by traditional "frequency counts" (although, since Opus
 uses static contexts, these are not updated as symbols are decoded).
+ symbol, represented by traditional "frequency counts".
+Because Opus uses static contexts these are not updated as symbols are decoded.
Let f[i] be the frequency of symbol i.
Then the threetuple corresponding to symbol k is given by
The range decoder extracts the symbols and integers encoded using the range
encoder in .
The range decoder maintains an internal state vector composed of the twotuple
 (val,rng), representing the difference between the high end of the current
 range and the actual coded value, minus one, and the size of the current
 range, respectively.
+ (val, rng), representing the difference between the high end of the
+ current range and the actual coded value, minus one, and the size of the
+ current range, respectively.
Both val and rng are 32bit unsigned integer values.
The decoder initializes rng to 128 and initializes val to 127 minus the top 7
 bits of the first input octet.
The remaining bit is saved for use in the renormalization procedure described
 in , which the decoder invokes
 immediately after initialization to read additional bits and establish the
 invariant that rng > 2**23.
+
+
+Let b0 be the first input byte (or zero if there are no bytes in this Opus
+ frame).
+The decoder initializes rng to 128 and initializes val to
+ (127  (b0>>1)), where (b0>>1) is the top 7 bits of the
+ first input byte.
+It saves the remaining bit, (b0&1), for use in the renormalization
+ procedure described in , which the
+ decoder invokes immediately after initialization to read additional bits and
+ establish the invariant that rng > 2**23.
+
+
+
Decoding a symbol is a twostep process.
@@ 842,10 +1137,12 @@ The second step updates the range decoder state with the threetuple
The first step is implemented by ec_decode() (entdec.c), which computes
The divisions here are exact integer division.
+The divisions here are integer division.
The decoder then identifies the symbol in the current context corresponding to
@@ 854,25 +1151,31 @@ The decoder then identifies the symbol in the current context corresponding to
It uses this tuple to update val according to
If fl[k] is greater than zero, then the decoder updates rng using
Otherwise, it updates rng using
Using a special case for the first symbol, rather than the last symbol, as is
 commonly done in other arithmetic coders, ensures that all the truncation
+Using a special case for the first symbol (rather than the last symbol, as is
+ commonly done in other arithmetic coders) ensures that all the truncation
error from the finite precision arithmetic accumulates in symbol 0.
This makes the cost of coding a 0 slightly smaller, on average, than its
estimated probability indicates and makes the cost of coding any other symbol
@@ 895,13 +1198,14 @@ To normalize the range, the decoder repeats the following process, implemented
by ec_dec_normalize() (entdec.c), until rng > 2**23.
If rng is already greater than 2**23, the entire process is skipped.
First, it sets rng to (rng<<8).
Then it reads the next octet of the payload and combines it with the leftover
 bit buffered from the previous octet to form the 8bit value sym.
It takes the leftover bit as the high bit (bit 7) of sym, and the top 7 bits
 of the octet it just read as the other 7 bits of sym.
The remaining bit in the octet just read is buffered for use in the next
+Then it reads the next byte of the Opus frame and forms an 8bit value sym,
+ using the leftover bit buffered from the previous byte as the high bit
+ and the top 7 bits of the byte just read as the other 7 bits of sym.
+The remaining bit in the byte just read is buffered for use in the next
iteration.
If no more input octets remain, it uses zero bits instead.
+If no more input bytes remain, it uses zero bits instead.
+See for the initialization used to process
+ the first byte.
Then, it sets
 :
+++++++++++++++++++++++++++++++++
@@ 949,15 +1253,15 @@ The reference implementation uses three additional decoding methods that are
exactly equivalent to the above, but make assumptions and simplifications that
allow for a more efficient implementation.

+
The first is ec_decode_bin() (entdec.c), defined using the parameter ftb
instead of ft.
It is mathematically equivalent to calling ec_decode() with
 ft = (1<<ftb), but avoids one of the divisions.
+ ft = (1<<ftb), but avoids one of the divisions.

+
The next is ec_dec_bit_logp() (entdec.c), which decodes a single binary symbol,
replacing both the ec_decode() and ec_dec_update() steps.
@@ 965,16 +1269,17 @@ The context is described by a single parameter, logp, which is the absolute
value of the base2 logarithm of the probability of a "1".
It is mathematically equivalent to calling ec_decode() with
ft = (1<<logp), followed by ec_dec_update() with
 the 3tuple (fl[k] = 0, fh[k] = (1<<logp)1,
+ the 3tuple (fl[k] = 0,
+ fh[k] = (1<<logp)  1,
ft = (1<<logp)) if the returned value
 of fs is less than (1<<logp)1 (a "0" was decoded), and with
 (fl[k] = (1<<logp)1,
+ of fs is less than (1<<logp)  1 (a "0" was decoded), and with
+ (fl[k] = (1<<logp)  1,
fh[k] = ft = (1<<logp)) otherwise (a "1" was
decoded).
The implementation requires no multiplications or divisions.

+
The last is ec_dec_icdf() (entdec.c), which decodes a single symbol with a
tablebased context of up to 8 bits, also replacing both the ec_decode() and
@@ 983,7 +1288,7 @@ The context is described by two parameters, an icdf
("inverse" cumulative distribution function) table and ftb.
As with ec_decode_bin(), (1<<ftb) is equivalent to ft.
idcf[k], on the other hand, stores (1<<ftb)fh[k], which is equal to
 (1<<ftb)fl[k+1].
+ (1<<ftb)  fl[k+1].
fl[0] is assumed to be 0, and the table is terminated by a value of 0 (where
fh[k] == ft).
@@ 991,9 +1296,10 @@ fl[0] is assumed to be 0, and the table is terminated by a value of 0 (where
The function is mathematically equivalent to calling ec_decode() with
ft = (1<<ftb), using the returned value fs to search the table
for the first entry where fs < (1<<ftb)icdf[k], and
 calling ec_dec_update() with fl[k] = (1<<ftb)icdf[k1] (or 0
 if k == 0), fh[k] = (1<<ftb)idcf[k], and
 ft = (1<<ftb).
+ calling ec_dec_update() with
+ fl[k] = (1<<ftb)  icdf[k1] (or 0
+ if k == 0), fh[k] = (1<<ftb)  idcf[k],
+ and ft = (1<<ftb).
Combining the search with the update allows the division to be replaced by a
series of multiplications (which are usually much cheaper), and using an
inverse CDF allows the use of an ftb as large as 8 in an 8bit table without
@@ 1007,7 +1313,7 @@ Although icdf[k] is more convenient for the code, the frequency counts, f[k],
(PDF) for a given symbol.
Therefore this draft lists the latter, not the former, when describing the
context in which a symbol is coded as a list, e.g., {4, 4, 4, 4}/16 for a
 uniform context with four possible values and ft=16.
+ uniform context with four possible values and ft = 16.
The value of ft after the slash is always the sum of the entries in the PDF,
but is included for convenience.
Contexts with identical probabilities, f[k]/ft, but different values of ft
@@ 1032,50 +1338,62 @@ The raw bits used by the CELT layer are packed at the end of the packet, with
The reference implementation reads them using ec_dec_bits() (entdec.c).
Because the range decoder must read several bytes ahead in the stream, as
described in , the input consumed by the
 raw bits MAY overlap with the input consumed by the range coder, and a decoder
+ raw bits may overlap with the input consumed by the range coder, and a decoder
MUST allow this.
The format should render it impossible to attempt to read more raw bits than
 there are actual bits in the frame, though a decoder MAY wish to check for
+ there are actual bits in the frame, though a decoder may wish to check for
this and report an error.

+
The ec_dec_uint() (entdec.c) function decodes one of ft equiprobable values in
 the range 0 to ft1, inclusive, each with a frequency of 1, where ft may be as
 large as 2**321.
Because ec_decode() is limited to a total frequency of 2**161, this is split
 up into a range coded symbol representing up to 8 of the high bits of the
 value, and, if necessary, raw bits representing the remaining bits.
+The function ec_dec_uint() (entdec.c) decodes one of ft equiprobable values in
+ the range 0 to (ft  1), inclusive, each with a frequency of 1,
+ where ft may be as large as (2**32  1).
+Because ec_decode() is limited to a total frequency of (2**16  1),
+ it splits up the value into a range coded symbol representing up to 8 of the
+ high bits, and, if necessary, raw bits representing the remainder of the
+ value.
The limit of 8 bits in the range coded symbol is a tradeoff between
implementation complexity, modeling error (since the symbols no longer truly
 have equal coding cost) and rounding error introduced by the range coder
+ have equal coding cost), and rounding error introduced by the range coder
itself (which gets larger as more bits are included).
Using raw bits reduces the maximum number of divisions required in the worst
case, but means that it may be possible to decode a value outside the range
 0 to ft1, inclusive.
+ 0 to (ft  1), inclusive.
ec_dec_uint() takes a single, positive parameter, ft, which is not necessarily
a power of two, and returns an integer, t, whose value lies between 0 and
 ft1, inclusive.
Let ftb = ilog(ft1), i.e., the number of bits required to store ft1 in two's
 complement notation.
If ftb is 8 or less, then t is decoded with t = ec_decode(ft), and the range
 coder state is updated using the threetuple (t,t+1,ft).
+ (ft  1), inclusive.
+Let ftb = ilog(ft  1), i.e., the number of bits required
+ to store (ft  1) in two's complement notation.
+If ftb is 8 or less, then t is decoded with t = ec_decode(ft), and
+ the range coder state is updated using the threetuple (t, t + 1,
+ ft).
If ftb is greater than 8, then the top 8 bits of t are decoded using
 t = ec_decode((ft1>>ftb8)+1),
+
+> (ftb  8)) + 1) ,
+]]>
+
the decoder state is updated using the threetuple
 (t,t+1,(ft1>>ftb8)+1), and the remaining bits are decoded as raw bits,
 setting t = t<<ftb8ec_dec_bits(ftb8).
+ (t, t + 1,
+ ((ft  1) >> (ftb  8)) + 1),
+ and the remaining bits are decoded as raw bits, setting
+
+
+
If, at this point, t >= ft, then the current frame is corrupt.
In that case, the decoder should assume there has been an error in the coding,
decoding, or transmission and SHOULD take measures to conceal the
 error and/or report to the application that a problem has occurred.
+ error and/or report to the application that the error has occurred.
@@ 1108,24 +1426,24 @@ In practice, although the number of bits used so far is an upper bound,
However, this error is bounded, and periodic calls to ec_tell() or
ec_tell_frac() at precisely defined points in the decoding process prevent it
from accumulating.
For a symbol that requires a whole number of bits (i.e., ft/(fh[k]fl[k]) is a
 power of two, including values of ft larger than 2**8 with ec_dec_uint()), and
 there are at least p 1/8th bits available, decoding the symbol will never
 advance the decoder past the end of the frame, i.e., will never "bust" the
 budget.
Frames contain a whole number of bits, and the return value of ec_tell_frac()
 will only advance by more than p 1/8th bits in this case if there was a
 fractional number of bits remaining, and by no more than the fractional part.
+For a range coder symbol that requires a whole number of bits (i.e.,
+ for which ft/(fh[k]  fl[k]) is a power of two), where there are at
+ least p 1/8th bits available, decoding the symbol will never cause ec_tell() or
+ ec_tell_frac() to exceed the size of the frame ("bust the budget").
+In this case the return value of ec_tell_frac() will only advance by more than
+ p 1/8th bits if there was an additional, fractional number of bits remaining,
+ and it will never advance beyond the next wholebit boundary, which is safe,
+ since frames always contain a whole number of bits.
However, when p is not a whole number of bits, an extra 1/8th bit is required
 to ensure decoding the symbol will not bust.
+ to ensure that decoding the symbol will not bust the budget.
The reference implementation keeps track of the total number of whole bits that
 have been processed by the decoder so far in a variable nbits_total, including
 the (possibly fractional number of bits) that are currently buffered (but not
 consumed) inside the range coder.
nbits_total is initialized to 33 just after the initial range renormalization
 process completes (or equivalently, it can be initialized to 9 before the
+ have been processed by the decoder so far in the variable nbits_total,
+ including the (possibly fractional) number of bits that are currently
+ buffered, but not consumed, inside the range coder.
+nbits_total is initialized to 9 just before the initial range renormalization
+ process completes (or equivalently, it can be initialized to 33 after the
first renormalization).
The extra two bits over the actual amount buffered by the range coder
guarantees that it is an upper bound and that there is enough room for the
@@ 1137,9 +1455,9 @@ Reading raw bits increases nbits_total by the number of raw bits read.
The whole number of bits buffered in rng may be estimated via l = ilog(rng).
+The whole number of bits buffered in rng may be estimated via lg = ilog(rng).
ec_tell() then becomes a simple matter of removing these bits from the total.
It returns (nbits_total  l).
+It returns (nbits_total  lg).
In a newly initialized decoder, before any symbols have been read, this reports
@@ 1152,19 +1470,44 @@ This is the bit reserved for termination of the encoder.
ec_tell_frac() estimates the number of bits buffered in rng to fractional
precision.
Since rng must be greater than 2**23 after renormalization, l must be at least
+Since rng must be greater than 2**23 after renormalization, lg must be at least
24.
Let r = rng>>(l16), so that 32768 <= r < 65536, an unsigned Q15
 value representing the fractional part of rng.
Then the following procedure can be used to add one bit of precision to l.
First, update r = r*r>>15.
Then add the 16th bit of r to l via l = 2*l + (r>>16).
Finally, if this bit was a 1, reduce r by a factor of two via r = r>>1,
 so that it once again lies in the range 32768 <= r < 65536.
+Let
+
+
+> (lg16) ,
+]]>
+
+ so that 32768 <= r_Q15 < 65536, an unsigned Q15 value representing the
+ fractional part of rng.
+Then the following procedure can be used to add one bit of precision to lg.
+First, update
+
+
+> 15 .
+]]>
+
+Then add the 16th bit of r_Q15 to lg via
+
+
+> 16) .
+]]>
+
+Finally, if this bit was a 1, reduce r_Q15 by a factor of two via
+
+
+> 1 ,
+]]>
+
+ so that it once again lies in the range 32768 <= r_Q15 < 65536.
This procedure is repeated three times to extend l to 1/8th bit precision.
ec_tell_frac() then returns (nbits_total*8  l).
+This procedure is repeated three times to extend lg to 1/8th bit precision.
+ec_tell_frac() then returns (nbits_total*8  lg).
@@ 1172,27 +1515,99 @@ ec_tell_frac() then returns (nbits_total*8  l).

+
The decoder's LP layer uses a modified version of the SILK codec (herein simply
called "SILK"), which runs a decoded excitation signal through adaptive
longterm and shortterm prediction synthesis filters.
It runs in NB, MB, and WB modes internally.
When used in a hybrid frame in SWB or FB mode, the LP layer itself still only
 runs in WB mode.
+It runs at NB, MB, and WB sample rates internally.
+When used in a SWB or FB Hybrid frame, the LP layer itself still only runs in
+ WB.
+
+
+
+
+An overview of the decoder is given in .
+
+
+
+ Range > Decode +
+ 1  Decoder  2  Parameters + 5 
+ ++ ++ 4  
+ 3   
+ \/ \/ \/
+ ++ ++ ++
+  Generate > LTP > LPC 
+  Excitation   Synthesis   Synthesis 
+ ++ ++ ++
+ ^ 
+  
+ +++
+  6
+  ++ ++
+ +> Stereo > Sample Rate >
+  Unmixing  7  Conversion  8
+ ++ ++
+
+1: Range encoded bitstream
+2: Coded parameters
+3: Pulses, LSBs, and signs
+4: Pitch lags, LongTerm Prediction (LTP) coefficients
+5: Linear Predictive Coding (LPC) coefficients and gains
+6: Decoded signal (mono or midside stereo)
+7: Unmixed signal (mono or leftright stereo)
+8: Resampled signal
+]]>
+
+
+
+
+The decoder feeds the bitstream (1) to the range decoder from
+ , and then decodes the parameters in it (2)
+ using the procedures detailed in
+ Sections
+ through .
+These parameters (3, 4, 5) are used to generate an excitation signal (see
+ ), which is fed to an optional
+ longterm prediction (LTP) filter (voiced frames only, see
+ ) and then a shortterm prediction filter
+ (see ), producing the decoded signal (6).
+For stereo streams, the midside representation is converted to separate left
+ and right channels (7).
+The result is finally resampled to the desired output sample rate (e.g.,
+ 48 kHz) so that the resampled signal (8) can be mixed with the CELT
+ layer.
+
+
+
+
+
Internally, the LP layer of a single Opus frame is composed of either a single
 10 ms SILK frame or between one and three 20 ms SILK frames.
Each SILK frame is in turn composed of either two or four 5 ms subframes.
+ 10 ms regular SILK frame or between one and three 20 ms regular SILK
+ frames.
+A stereo Opus frame may double the number of regular SILK frames (up to a total
+ of six), since it includes separate frames for a mid channel and, optionally,
+ a side channel.
Optional Low BitRate Redundancy (LBRR) frames, which are reducedbitrate
 encodings of previous SILK frames, may appear to aid in recovery from packet
 loss.
+ encodings of previous SILK frames, may be included to aid in recovery from
+ packet loss.
If present, these appear before the regular SILK frames.
They are in most respects identical to regular active SILK frames, except that
 they are usually encoded with a lower bitrate, and from here on this draft
 will use "SILK frame" to refer to either one and "regular SILK frame" if it
 needs to draw a distinction between the two.
+They are in most respects identical to regular, active SILK frames, except that
+ they are usually encoded with a lower bitrate.
+This draft uses "SILK frame" to refer to either one and "regular SILK frame" if
+ it needs to draw a distinction between the two.
+
+
+Logically, each SILK frame is in turn composed of either two or four 5 ms
+ subframes.
+Various parameters, such as the quantization gain of the excitation and the
+ pitch lag and filter coefficients can vary on a subframebysubframe basis.
+Physically, the parameters for each subframe are interleaved in the bitstream,
+ as described in the relevant sections for each parameter.
All of these frames and subframes are decoded from the same range coder, with
@@ 1209,146 +1624,145 @@ Stereo support in SILK uses a variant of midside coding, allowing a mono
decoder to simply decode the mid channel.
However, the data for the two channels is interleaved, so a mono decoder must
still unpack the data for the side channel.
It would be required to do so anyway for hybrid Opus frames, or to support
+It would be required to do so anyway for Hybrid Opus frames, or to support
decoding individual 20 ms frames.

+
+ summarizes the overall grouping of the contents of
+ the LP layer.
+Figures
+ and illustrate
+ the ordering of the various SILK frames for a 60 ms Opus frame, for both
+ mono and stereo, respectively.
+
+
+Symbol(s)
PDF
+PDF(s)Condition
VAD flags{1, 1}/2
LBRR flag{1, 1}/2
Perframe LBRR flags
Frame Type
Gain index

Order of the symbols in the SILK section of the bitstream.




An overview of the decoder is given in .



Voice Activity Detection (VAD) flags
+{1, 1}/2
+
 ++ ++
> Range > Decode +
 1  Decoder  2  Parameters + 5 
 ++ ++ 4  
 3   
 \/ \/ \/
 ++ ++ ++
  Generate > LTP > LPC >
  Excitation   Synthesis   Synthesis  6
 ++ ++ ++
+LBRR flag
+{1, 1}/2
+
1: Range encoded bitstream
2: Coded parameters
3: Pulses and gains
4: Pitch lags and LTP coefficients
5: LPC coefficients
6: Decoded signal
]]>

Decoder block diagram.

+Perframe LBRR flags
+
+


 The range decoder decodes the encoded parameters from the received bitstream. Output from this function includes the pulses and gains for the excitation signal generation, as well as LTP and LSF codebook indices, which are needed for decoding LTP and LPC coefficients needed for LTP and LPC synthesis filtering the excitation signal, respectively.





 Pulses and gains are decoded from the parameters that were decoded by the range decoder.



 When a voiced frame is decoded and LTP codebook selection and indices are received, LTP coefficients are decoded using the selected codebook by choosing the vector that corresponds to the given codebook index in that codebook. This is done for each of the four subframes.
 The LPC coefficients are decoded from the LSF codebook by first adding the chosen LSF vector and the decoded LSF residual signal. The resulting LSF vector is stabilized using the same method that was used in the encoder, see
 . The LSF coefficients are then converted to LPC coefficients, and passed on to the LPC synthesis filter.





 The pulses signal is multiplied with the quantization gain to create the excitation signal.





 For voiced speech, the excitation signal e(n) is input to an LTP synthesis filter that will recreate the long term correlation that was removed in the LTP analysis filter and generate an LPC excitation signal e_LPC(n), according to





 using the pitch lag L, and the decoded LTP coefficients b_i.
 The number of LTP coefficients is 5, and thus d = 2.
+LBRR Frame(s)
+
+
 For unvoiced speech, the output signal is simply a copy of the excitation signal, i.e., e_LPC(n) = e(n).


+Regular SILK Frame(s)
+
+


 In a similar manner, the shortterm correlation that was removed in the LPC analysis filter is recreated in the LPC synthesis filter. The LPC excitation signal e_LPC(n) is filtered using the LTP coefficients a_i, according to





 where d_LPC is the LPC synthesis filter order, and y(n) is the decoded output signal.



+
+
+
+
+
+
+
+
+

+

+
The LP layer begins with two to eight header bits, decoded in silk_Decode()
 (silk_dec_API.c).
+ (dec_API.c).
These consist of one Voice Activity Detection (VAD) bit per frame (up to 3),
followed by a single flag indicating the presence of LBRR frames.
For a stereo packet, these flags correspond to the mid channel, and a second
 set of flags is included for the side channel.
+For a stereo packet, these first flags correspond to the mid channel, and a
+ second set of flags is included for the side channel.
Because these are the first symbols decoded by the range coder, they can be
 extracted directly from the upper bits of the first byte of compressed data.
+Because these are the first symbols decoded by the range coder and because they
+ are coded as binary values with uniform probability, they can be extracted
+ directly from the most significant bits of the first byte of compressed data.
Thus, a receiver can determine if an Opus frame contains any active SILK frames
without the overhead of using the range decoder.

+
For Opus frames longer than 20 ms, a set of perframe LBRR flags is
+For Opus frames longer than 20 ms, a set of LBRR flags is
decoded for each channel that has its LBRR flag set.
For 40 ms Opus frames the 2frame LBRR flag PDF from
 is used, and for 60 ms Opus frames
 the 3frame LBRR flag PDF is used.
+Each set contains one flag per 20 ms SILK frame.
+40 ms Opus frames use the 2frame LBRR flag PDF from
+ , and 60 ms Opus frames use the
+ 3frame LBRR flag PDF.
For each channel, the resulting 2 or 3bit integer contains the corresponding
 LBRR flag for each frame, packed in order from the LSb to the MSb.
+ LBRR flag for each frame, packed in order from the LSB to the MSB.
@@ 1359,99 +1773,474 @@ For each channel, the resulting 2 or 3bit integer contains the corresponding
LBRR frames do not include their own separate VAD flags.
An LBRR frame is only meant to be transmitted for active speech, thus all LBRR
 frames are treated as active.
+A 10 or 20 ms Opus frame does not contain any perframe LBRR flags,
+ as there may be at most one LBRR frame per channel.
+The global LBRR flag in the header bits (see )
+ is already sufficient to indicate the presence of that single LBRR frame.
+

+
Each SILK frame includes a set of side information that encodes the frame type,
 quantization type and gains, shortterm prediction filter coefficients, LSF
 interpolation weight, longterm prediction filter lags and gains, and a
 linear congruential generator (LCG) seed.
The quantized excitation signal follows these at the end of the frame.
+The LBRR frames, if present, contain an encoded representation of the signal
+ immediately prior to the current Opus frame as if it were encoded with the
+ current mode, frame size, audio bandwidth, and channel count, even if those
+ differ from the prior Opus frame.
+When one of these parameters changes from one Opus frame to the next, this
+ implies that the LBRR frames of the current Opus frame may not be simple
+ dropin replacements for the contents of the previous Opus frame.

+
Each SILK frame begins with a single "frame type" symbol that jointly codes the
 signal type and quantization offset type of the corresponding frame.
If the current frame is a regular SILK frame whose VAD bit was not set (an
 "inactive" frame), then the frame type symbol takes on the value either 0 or 1
 and is decoded using the first PDF in .
If the frame is an LBRR frame or a regular SILK frame whose VAD flag was set
 (an "active" frame), then the symbol ranges from 2 to 5, inclusive, and is
 decoded using the second PDF in .
 translates between the value of the
 frame type symbol and the corresponding signal type and quantization offset
 type.
+For example, when switching from 20 ms to 60 ms, the 60 ms Opus
+ frame may contain LBRR frames covering up to three prior 20 ms Opus
+ frames, even if those frames already contained LBRR frames covering some of
+ the same time periods.
+When switching from 20 ms to 10 ms, the 10 ms Opus frame can
+ contain an LBRR frame covering at most half the prior 20 ms Opus frame,
+ potentially leaving a hole that needs to be concealed from even a single
+ packet loss (see ).
+When switching from mono to stereo, the LBRR frames in the first stereo Opus
+ frame MAY contain a nontrivial side channel.

VAD Flag
PDF
Inactive{26, 230, 0, 0, 0, 0}/256
Active{0, 0, 24, 74, 148, 10}/256



Frame Type
Signal Type
Quantization Offset Type
0Inactive0
1Inactive1
2Unvoiced0
3Unvoiced1
4Voiced0
5Voiced1



+
+In order to properly produce LBRR frames under all conditions, an encoder might
+ need to buffer up to 60 ms of audio and reencode it during these
+ transitions.
+However, the reference implementation opts to disable LBRR frames at the
+ transition point for simplicity.
+Since transitions are relatively infrequent in normal usage, this does not have
+ a significant impact on packet loss robustness.
+

A separate quantization gain is coded for each 5 ms subframe.
These gains control the step size between quantization levels of the excitation
+The LBRR frames immediately follow the LBRR flags, prior to any regular SILK
+ frames.
+ describes their exact contents.
+LBRR frames do not include their own separate VAD flags.
+LBRR frames are only meant to be transmitted for active speech, thus all LBRR
+ frames are treated as active.
+
+
+
+In a stereo Opus frame longer than 20 ms, although the perframe LBRR
+ flags for the mid channel are coded as a unit before the perframe LBRR flags
+ for the side channel, the LBRR frames themselves are interleaved.
+The decoder parses an LBRR frame for the mid channel of a given 20 ms
+ interval (if present) and then immediately parses the corresponding LBRR
+ frame for the side channel (if present), before proceeding to the next
+ 20 ms interval.
+
+
+
+
+
+The regular SILK frame(s) follow the LBRR frames (if any).
+ describes their contents, as well.
+Unlike the LBRR frames, a regular SILK frame is coded for each time interval in
+ an Opus frame, even if the corresponding VAD flags are unset.
+For stereo Opus frames longer than 20 ms, the regular mid and side SILK
+ frames for each 20 ms interval are interleaved, just as with the LBRR
+ frames.
+The side frame may be skipped by coding an appropriate flag, as detailed in
+ .
+
+
+
+
+
+Each SILK frame includes a set of side information that encodes
+
+The frame type and quantization type (),
+Quantization gains (),
+Shortterm prediction filter coefficients (),
+A Line Spectral Frequencies (LSF) interpolation weight (),
+
+Longterm prediction filter lags and gains (),
+ and
+
+A linear congruential generator (LCG) seed ().
+
+The quantized excitation signal (see ) follows
+ these at the end of the frame.
+ details the overall organization of a
+ SILK frame.
+
+
+
+Symbol(s)
+PDF(s)
+Condition
+
+Stereo Prediction Weights
+
+
+
+Midonly Flag
+
+
+
+Frame Type
+
+
+
+Subframe Gains
+
+
+
+Normalized LSF Stage1 Index
+
+
+
+Normalized LSF Stage2 Residual
+
+
+
+Normalized LSF Interpolation Weight
+
+20 ms frame
+
+Primary Pitch Lag
+
+Voiced frame
+
+Subframe Pitch Contour
+
+Voiced frame
+
+Periodicity Index
+
+Voiced frame
+
+LTP Filter
+
+Voiced frame
+
+LTP Scaling
+
+
+
+LCG Seed
+
+
+
+Excitation Rate Level
+
+
+
+Excitation Pulse Counts
+
+
+
+Excitation Pulse Locations
+
+Nonzero pulse count
+
+Excitation LSBs
+
+
+
+Excitation Signs
+
+
+
+
+
+
+
+A SILK frame corresponding to the mid channel of a stereo Opus frame begins
+ with a pair of side channel prediction weights, designed such that zeros
+ indicate normal midside coupling.
+Since these weights can change on every frame, the first portion of each frame
+ linearly interpolates between the previous weights and the current ones, using
+ zeros for the previous weights if none are available.
+These prediction weights are never included in a mono Opus frame, and the
+ previous weights are reset to zeros on any transition from mono to stereo.
+They are also not included in an LBRR frame for the side channel, even if the
+ LBRR flags indicate the corresponding mid channel was not coded.
+In that case, the previous weights are used, again substituting in zeros if no
+ previous weights are available since the last decoder reset
+ (see ).
+
+
+
+To summarize, these weights are coded if and only if
+
+This is a stereo Opus frame (), and
+The current SILK frame corresponds to the mid channel.
+
+
+
+
+The prediction weights are coded in three separate pieces, which are decoded
+ by silk_stereo_decode_pred() (decode_stereo_pred.c).
+The first piece jointly codes the highorder part of a table index for both
+ weights.
+The second piece codes the loworder part of each table index.
+The third piece codes an offset used to linearly interpolate between table
+ indices.
+The details are as follows.
+
+
+
+Let n be an index decoded with the 25element stage1 PDF in
+ .
+Then let i0 and i1 be indices decoded with the stage2 and stage3 PDFs in
+ , respectively, and let i2 and i3
+ be two more indices decoded with the stage2 and stage3 PDFs, all in that
+ order.
+
+
+
+Stage
+PDF
+Stage 1
+{7, 2, 1, 1, 1,
+ 10, 24, 8, 1, 1,
+ 3, 23, 92, 23, 3,
+ 1, 1, 8, 24, 10,
+ 1, 1, 1, 2, 7}/256
+
+Stage 2
+{85, 86, 85}/256
+
+Stage 3
+{51, 51, 52, 51, 51}/256
+
+
+
+Then use n, i0, and i2 to form two table indices, wi0 and wi1, according to
+
+
+
+ where the division is integer division.
+The range of these indices is 0 to 14, inclusive.
+Let w[i] be the i'th weight from .
+Then the two prediction weights, w0_Q13 and w1_Q13, are
+
+> 16)*(2*i3 + 1)
+
+w0_Q13 = w_Q13[wi0]
+ + ((w_Q13[wi0+1]  w_Q13[wi0])*6554) >> 16)*(2*i1 + 1)
+  w1_Q13
+]]>
+
+N.b., w1_Q13 is computed first here, because w0_Q13 depends on it.
+The constant 6554 is approximately 0.1 in Q16.
+Although wi0 and wi1 only have 15 possible values,
+ contains 16 entries to allow
+ interpolation between entry wi0 and (wi0 + 1) (and likewise for wi1).
+
+
+
+Index
+Weight (Q13)
+ 013732
+ 110050
+ 28266
+ 37526
+ 46500
+ 55000
+ 62950
+ 7820
+ 8820
+ 92950
+105000
+116500
+127526
+138266
+1410050
+1513732
+
+
+
+
+
+
+A flag appears after the stereo prediction weights that indicates if only the
+ mid channel is coded for this time interval.
+It appears only when
+
+This is a stereo Opus frame (see ),
+The current SILK frame corresponds to the mid channel, and
+Either
+
+This is a regular SILK frame where the VAD flags
+ (see ) indicate that the corresponding side
+ channel is not active.
+
+This is an LBRR frame where the LBRR flags
+ (see and )
+ indicate that the corresponding side channel is not coded.
+
+
+
+
+It is omitted when there are no stereo weights, for all of the same reasons.
+It is also omitted for a regular SILK frame when the VAD flag of the
+ corresponding side channel frame is set (indicating it is active).
+The side channel must be coded in this case, making the midonly flag
+ redundant.
+It is also omitted for an LBRR frame when the corresponding LBRR flags
+ indicate the side channel is coded.
+
+
+
+When the flag is present, the decoder reads a single value using the PDF in
+ , as implemented in
+ silk_stereo_decode_mid_only() (decode_stereo_pred.c).
+If the flag is set, then there is no corresponding SILK frame for the side
+ channel, the entire decoding process for the side channel is skipped, and
+ zeros are fed to the stereo unmixing process (see
+ ) instead.
+As stated above, LBRR frames still include this flag when the LBRR flag
+ indicates that the side channel is not coded.
+In that case, if this flag is zero (indicating that there should be a side
+ channel), then Packet Loss Concealment (PLC, see
+ ) SHOULD be invoked to recover a
+ side channel signal.
+Otherwise, the stereo image will collapse.
+
+
+
+PDF
+{192, 64}/256
+
+
+
+
+
+
+Each SILK frame contains a single "frame type" symbol that jointly codes the
+ signal type and quantization offset type of the corresponding frame.
+If the current frame is a regular SILK frame whose VAD bit was not set (an
+ "inactive" frame), then the frame type symbol takes on a value of either 0 or
+ 1 and is decoded using the first PDF in .
+If the frame is an LBRR frame or a regular SILK frame whose VAD flag was set
+ (an "active" frame), then the value of the symbol may range from 2 to 5,
+ inclusive, and is decoded using the second PDF in
+ .
+ translates between the value of the
+ frame type symbol and the corresponding signal type and quantization offset
+ type.
+
+
+
+VAD Flag
+PDF
+Inactive{26, 230, 0, 0, 0, 0}/256
+Active{0, 0, 24, 74, 148, 10}/256
+
+
+
+Frame Type
+Signal Type
+Quantization Offset Type
+0InactiveLow
+1InactiveHigh
+2UnvoicedLow
+3UnvoicedHigh
+4VoicedLow
+5VoicedHigh
+
+
+
+
+
+
+A separate quantization gain is coded for each 5 ms subframe.
+These gains control the step size between quantization levels of the excitation
signal and, therefore, the quality of the reconstruction.
They are independent of the pitch gains coded for voiced frames.
+They are independent of and unrelated to the pitch contours coded for voiced
+ frames.
The quantization gains are themselves uniformly quantized to 6 bits on a
log scale, giving them a resolution of approximately 1.369 dB and a range
of approximately 1.94 dB to 88.21 dB.
For the first LBRR frame, an LBRR frame where the previous LBRR frame was not
 coded, or the first regular SILK frame in an Opus frame, the first subframe
 uses an independent coding method.
The 3 most significant bits of the quantization gain are decoded using a PDF
 selected from based on the
 decoded signal type.
+The subframe gains are either coded independently, or relative to the gain from
+ the most recent coded subframe in the same channel.
+Independent coding is used if and only if
+
+
+This is the first subframe in the current SILK frame, and
+
+Either
+
+
+This is the first SILK frame of its type (LBRR or regular) for this channel in
+ the current Opus frame, or
+
+
+The previous SILK frame of the same type (LBRR or regular) for this channel in
+ the same Opus frame was not coded.
+
+
+
+
+
+
+
+In an independently coded subframe gain, the 3 most significant bits of the
+ quantization gain are decoded using a PDF selected from
+ based on the decoded signal
+ type (see ).
+ title="PDFs for Independent Quantization Gain MSB Coding">
Signal TypePDFInactive{32, 112, 68, 29, 12, 1, 1, 1}/256
Unvoiced{2, 17, 45, 60, 62, 47, 19, 4}/256
Voiced{1, 3, 26, 71, 94, 50, 9, 2}/256
+Unvoiced{2, 17, 45, 60, 62, 47, 19, 4}/256
+Voiced{1, 3, 26, 71, 94, 50, 9, 2}/256
The 3 least significant bits are decoded using a uniform PDF:
+ title="PDF for Independent Quantization Gain LSB Coding">
PDF{32, 32, 32, 32, 32, 32, 32, 32}/256
For all other subframes (including the first subframe of frames not listed as
 using independent coding above), the quantization gain is coded relative to
 the gain from the previous subframe.
The PDF in yields a delta gain index
+These 6 bits are combined to form a value, gain_index, between 0 and 63.
+When the gain for the previous subframe is available, then the current gain is
+ limited as follows:
+
+
+
+This may help some implementations limit the change in precision of their
+ internal LTP history.
+The indices which this clamp applies to cannot simply be removed from the
+ codebook, because previous_log_gain will not be available after packet loss.
+The clamping is skipped after a decoder reset, and in the side channel if the
+ previous frame in the side channel was not coded, since there is no value for
+ previous_log_gain available.
+It MAY also be skipped after packet loss.
+
+
+
+For subframes which do not have an independent gain (including the first
+ subframe of frames not listed as using independent coding above), the
+ quantization gain is coded relative to the gain from the previous subframe (in
+ the same channel).
+The PDF in yields a delta_gain_index value
between 0 and 40, inclusive.
yields a delta gain index
The following formula translates this index into a quantization gain for the
current subframe using the gain from the previous subframe:

+
silk_gains_dequant() (silk_gain_quant.c) dequantizes the gain for the
 k'th subframe and converts it into a linear Q16 scale factor via
+silk_gains_dequant() (gain_quant.c) dequantizes log_gain for the k'th subframe
+ and converts it into a linear Q16 scale factor via
>16) + 2090)
@@ 1483,52 +2272,66 @@ gain_Q16[k] = silk_log2lin((0x1D1C71*log_gain>>16) + 2090)
The function silk_log2lin() (silk_log2lin.c) computes an approximation of
 of 2**(inLog_Q7/128.0), where inLog_Q7 is its Q7 input.
+The function silk_log2lin() (log2lin.c) computes an approximation of
+ 2**(inLog_Q7/128.0), where inLog_Q7 is its Q7 input.
Let i = inLog_Q7>>7 be the integer part of inLogQ7 and
f = inLog_Q7&127 be the fractional part.
Then, if i < 16, then
+Then
>16)+f)>>7)*(1<>16)+f)*((1<>7)
]]>
yields the approximate exponential.
Otherwise, silk_log2lin uses

>16)+f)*((1<>7) .
]]>

+The final Q16 gain values lies between 81920 and 1686110208, inclusive
+ (representing scale factors of 1.25 to 25728, respectively).



Normalized Line Spectral Frequencies (LSFs) follow the quantization gains in
 the bitstream, and represent the Linear Prediction Coefficients (LPCs) for the
 current SILK frame.
Once decoded, they form an increasing list of Q15 values between 0 and 1.
These represent the interleaved zeros on the unit circle between 0 and pi
 (hence "normalized") in the standard decomposition of the LPC filter into a
 symmetric part and an antisymmetric part (P and Q in
 ).
+
+
+A set of normalized Line Spectral Frequency (LSF) coefficients follow the
+ quantization gains in the bitstream, and represent the Linear Predictive
+ Coding (LPC) coefficients for the current SILK frame.
+Once decoded, the normalized LSFs form an increasing list of Q15 values between
+ 0 and 1.
+These represent the interleaved zeros on the upper half of the unit circle
+ (between 0 and pi, hence "normalized") in the standard decomposition
+ of the LPC filter into a symmetric part
+ and an antisymmetric part (P and Q in ).
Because of nonlinear effects in the decoding process, an implementation SHOULD
match the fixedpoint arithmetic described in this section exactly.
An encoder SHOULD also use the same process.
The normalized LSFs are coded using a twostage vector quantizer (VQ).
+The normalized LSFs are coded using a twostage vector quantizer (VQ)
+ ( and ).
NB and MB frames use an order10 predictor, while WB frames use an order16
predictor, and thus have different sets of tables.
+After reconstructing the normalized LSFs
+ (), the decoder runs them through a
+ stabilization process (), interpolates
+ them between frames (), converts them
+ back into LPC coefficients (), and then runs
+ them through further processes to limit the range of the coefficients
+ () and the gain of the filter
+ ().
+All of this is necessary to ensure the reconstruction process is stable.
+
+
+
+
The first VQ stage uses a 32element codebook, coded with one of the PDFs in
, depending on the audio bandwidth and
the signal type of the current SILK frame.
This yields a single index, I1, for the entire frame.
This indexes an element in a coarse codebook, selects the PDFs for the
 second stage of the VQ, and selects the prediction weights used to remove
 intraframe redundancy from the second stage.
+This yields a single index, I1, for the entire frame, which
+
+Indexes an element in a coarse codebook,
+Selects the PDFs for the second stage of the VQ, and
+Selects the prediction weights used to remove intraframe redundancy from
+ the second stage.
+
The actual codebook elements are listed in
and
, but they are not needed until the last
@@ 1536,7 +2339,7 @@ The actual codebook elements are listed in
+ title="PDFs for Normalized LSF Stage1 Index Decoding">
Audio BandwidthSignal TypePDF
@@ 1570,6 +2373,9 @@ The actual codebook elements are listed in
+
+
+
A total of 16 PDFs are available for the LSF residual in the second stage: the
8 (a...h) for NB and MB frames given in
@@ 1583,7 +2389,7 @@ Which PDF is used for which coefficient is driven by the index, I1,
+ title="PDFs for NB/MB Normalized LSF Stage2 Index Decoding">
CodebookPDFa{1, 1, 1, 15, 224, 11, 1, 1, 1}/256
@@ 1597,7 +2403,7 @@ Which PDF is used for which coefficient is driven by the index, I1,
+ title="PDFs for WB Normalized LSF Stage2 Index Decoding">
CodebookPDFi{1, 1, 1, 9, 232, 9, 1, 1, 1}/256
@@ 1611,7 +2417,7 @@ Which PDF is used for which coefficient is driven by the index, I1,
+ title="Codebook Selection for NB/MB Normalized LSF Stage2 Index Decoding">
I1Coefficient
@@ 1683,7 +2489,7 @@ Which PDF is used for which coefficient is driven by the index, I1,
+ title="Codebook Selection for WB Normalized LSF Stage2 Index Decoding">
I1Coefficient
@@ 1708,7 +2514,7 @@ Which PDF is used for which coefficient is driven by the index, I1,
i o k o o m n m o n m m n l l l 9k j i i i i i i i i i i i i i i
j0
+10i j i i i i i i i i i i i i i j11k k l m n l l l l l l l k k j l
@@ 1759,7 +2565,7 @@ Decoding the second stage residual proceeds as follows.
For each coefficient, the decoder reads a symbol using the PDF corresponding to
I1 from either or
, and subtracts 4 from the result
 to given an index in the range 4 to 4, inclusive.
+ to give an index in the range 4 to 4, inclusive.
If the index is either 4 or 4, it reads a second symbol using the PDF in
, and adds the value of this second symbol
to the index, using the same sign.
@@ 1774,7 +2580,7 @@ This gives the index, I2[k], a total range of 10 to 10, inclusive.
The decoded indices from both stages are translated back into normalized LSF
 coefficients in silk_NLSF_decode() (silk_NLSF_decode.c).
+ coefficients in silk_NLSF_decode() (NLSF_decode.c).
The stage2 indices represent residuals after both the first stage of the VQ
and a separate backwardsprediction step.
The backwards prediction process in the encoder subtracts a prediction from
@@ 1812,7 +2618,7 @@ There are two lists for NB and MB, and another two lists for WB, giving two
The prediction is undone using the procedure implemented in
 silk_NLSF_residual_dequant() (silk_NLSF_decode.c), which is as follows.
+ silk_NLSF_residual_dequant() (NLSF_decode.c), which is as follows.
Each coefficient selects its prediction weight from one of the two lists based
on the stage1 index, I1.
gives the selections for each
@@ 1824,8 +2630,8 @@ Let d_LPC be the order of the codebook, i.e., 10 for NB and MB, and 16 for WB,
Then, the stage2 residual for each coefficient is computed via
>8 : 0)
 + ((((I2[k]<<10) + sign(I2[k])*102)*qstep)>>16) ,
+res_Q10[k] = (k+1 < d_LPC ? (res_Q10[k+1]*pred_Q8[k])>>8 : 0)
+ + ((((I2[k]<<10)  sign(I2[k])*102)*qstep)>>16) ,
]]>
where qstep is the Q16 quantization step size, which is 11796 for NB and MB
@@ 1898,7 +2704,7 @@ Then, the stage2 residual for each coefficient is computed via
28A A B A B B A B A29
A A A B A A A A A
+B A A B A A A A A30A A A B B A B A B31
@@ 1922,7 +2728,7 @@ Then, the stage2 residual for each coefficient is computed via
4C D D C D C D D C D D D D D C 5
C D C C C C C C C C C C C C C
+C C D C C C C C C C C C C C C 6D C C C C C C C C C C D C D C 7
@@ 1977,10 +2783,19 @@ Then, the stage2 residual for each coefficient is computed via
C C D C C D D D C C D C C D C
+
+
+
+
+Once the stage1 index I1 and the stage2 residual res_Q10[] have been decoded,
+ the final normalized LSF coefficients can be reconstructed.
+
The spectral distortion introduced by the quantization of each LSF coefficient
varies, so the stage2 residual is weighted accordingly, using the
 lowcomplexity weighting function proposed in .
+ lowcomplexity Inverse Harmonic Mean Weighting (IHMW) function proposed in
+ .
The weights are derived directly from the stage1 codebook vector.
Let cb1_Q8[k] be the k'th entry of the stage1 codebook vector from
or
@@ 1996,7 +2811,7 @@ w2_Q18[k] = (1024/(cb1_Q8[k]  cb1_Q8[k1])
where cb1_Q8[1] = 0 and cb1_Q8[d_LPC] = 256, and the
 division is exact integer division.
+ division is integer division.
This is reduced to an unsquared, Q9 value using the following squareroot
approximation:
@@ 2007,18 +2822,21 @@ y = ((i&1) ? 32768 : 46214) >> ((32i)>>1)
w_Q9[k] = y + ((213*f*y)>>16)
]]>
+The constant 46214 here is approximately the square root of 2 in Q15.
The cb1_Q8[] vector completely determines these weights, and they may be
 tabulated and stored as 13bit unsigned values (with a range of 1819 to 5227)
 to avoid computing them when decoding.
The reference implementation computes them on the fly in
 silk_NLSF_VQ_weights_laroia() (silk_NLSF_VQ_weights_laroia.c) and its
 caller, to reduce the amount of ROM required.
+ tabulated and stored as 13bit unsigned values (with a range of 1819 to 5227,
+ inclusive) to avoid computing them when decoding.
+The reference implementation already requires code to compute these weights on
+ unquantized coefficients in the encoder, in silk_NLSF_VQ_weights_laroia()
+ (NLSF_VQ_weights_laroia.c) and its callers, so it reuses that code in the
+ decoder instead of using a precomputed table to reduce the amount of ROM
+ required.
+ title="NB/MB Normalized LSF Stage1 Codebook Vectors">
I1
Codebook
+Codebook (Q8) 0 1 2 3 4 5 6 7 8 90
@@ 2088,9 +2906,9 @@ The reference implementation computes them on the fly in
+ title="WB Normalized LSF Stage1 Codebook Vectors">
I1
Codebook
+Codebook (Q8) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 150
@@ 2165,22 +2983,26 @@ Given the stage1 codebook entry cb1_Q8[], the stage2 residual res_Q10[], and
coefficients are
 where the division is exact integer division.
However, nothing thus far in the reconstruction process, nor in the
 quantization process in the encoder, guarantees that the coefficients are
 monotonically increasing and separated well enough to ensure a stable filter.
+ where the division is integer division.
+However, nothing in either the reconstruction process or the
+ quantization process in the encoder thus far guarantees that the coefficients
+ are monotonically increasing and separated well enough to ensure a stable
+ filter .
When using the reference encoder, roughly 2% of frames violate this constraint.
The next section describes a stabilization procedure used to make these
guarantees.
+
+
The normalized LSF stabilization procedure is implemented in
 silk_NLSF_stabilize() (silk_NLSF_stabilize.c).
+ silk_NLSF_stabilize() (NLSF_stabilize.c).
This process ensures that consecutive values of the normalized LSF
coefficients, NLSF_Q15[], are spaced some minimum distance apart
(predetermined to be the 0.01 percentile of a large training set).
@@ 2236,16 +3058,16 @@ For all other values of i, both NLSF_Q15[i1] and NLSF_Q15[i] are updated as
follows:
>1) + \ NDeltaMin[k]
 /_
 k=0
 d_LPC
 __
 max_center_Q15 = 32768  (NDeltaMin[i]>>1)  \ NDeltaMin[k]
 /_
 k=i+1
+ i1
+ __
+ min_center_Q15 = (NDeltaMin_Q15[i]>>1) + \ NDeltaMin_Q15[k]
+ /_
+ k=0
+ d_LPC
+ __
+ max_center_Q15 = 32768  (NDeltaMin_Q15[i]>>1)  \ NDeltaMin_Q15[k]
+ /_
+ k=i+1
center_freq_Q15 = clamp(min_center_Q15[i],
(NLSF_Q15[i1] + NLSF_Q15[i] + 1)>>1,
max_center_Q15[i])
@@ 2255,12 +3077,12 @@ center_freq_Q15 = clamp(min_center_Q15[i],
NLSF_Q15[i] = NLSF_Q15[i1] + NDeltaMin_Q15[i] .
]]>
Then the procedure repeats again, until it has executed 20 times, or until
 it stops because the coefficients satisfy all the constraints.
+Then the procedure repeats again, until it has either executed 20 times or
+ has stopped because the coefficients satisfy all the constraints.
After the 20th repetition of the above, the following fallback procedure
 executes once.
+After the 20th repetition of the above procedure, the following fallback
+ procedure executes once.
First, the values of NLSF_Q15[k] for 0 <= k < d_LPC
are sorted in ascending order.
Then for each value of k from 0 to d_LPC1, NLSF_Q15[k] is set to
@@ 2282,14 +3104,19 @@ min(NLSF_Q15[k], NLSF_Q15[k+1]  NDeltaMin_Q15[k+1]) .
For 20 ms SILK frames, the first half of the frame (i.e., the first two
 subframes) may use normalized LSF coefficients that are interpolated between
 the decoded LSFs for the previous frame and the current frame.
+ subframes) may use normalized LSF coefficients that are interpolated between
+ the decoded LSFs for the most recent coded frame (in the same channel) and the
+ current frame.
A Q2 interpolation factor follows the LSF coefficient indices in the bitstream,
which is decoded using the PDF in .
This happens in silk_decode_indices() (silk_decode_indices.c).
For the first frame after a decoder reset, when no prior LSF coefficients are
 available, the decoder still decodes this factor, but ignores its value and
 always uses 4 instead.
+This happens in silk_decode_indices() (decode_indices.c).
+After either
+
+An uncoded regular SILK frame in the side channel, or
+A decoder reset (see ),
+
+ the decoder still decodes this factor, but ignores its value and always uses
+ 4 instead.
For 10 ms SILK frames, this factor is not stored at all.
@@ 2311,12 +3138,12 @@ n1_Q15[k] = n0_Q15[k] + (w_Q2*(n2_Q15[k]  n0_Q15[k]) >> 2) .
]]>
This interpolation is performed in silk_decode_parameters()
 (silk_decode_parameters.c).
+ (decode_parameters.c).
+ title="Converting Normalized LSFs to LPC Coefficients">
Any LPC filter A(z) can be split into a symmetric part P(z) and an
antisymmetric part Q(z) such that
@@ 2363,107 +3190,136 @@ Q(z) = (1  z ) *   (1  2*cos(pi*n[2*k+1])*z + z )
However, SILK performs this reconstruction using a fixedpoint approximation so
that all decoders can reproduce it in a bitexact manner to avoid prediction
drift.
The function silk_NLSF2A() (silk_NLSF2A.c) implements this procedure.
+The function silk_NLSF2A() (NLSF2A.c) implements this procedure.
To start, it approximates cos(pi*n[k]) using a table lookup with linear
interpolation.
The encoder SHOULD use the inverse of this piecewise linear approximation,
 rather than true the inverse of the cosine function, when deriving the
+ rather than the true inverse of the cosine function, when deriving the
normalized LSF coefficients.
+These values are also reordered to improve numerical accuracy when
+ constructing the LPC polynomials.
+
+
+Coefficient
+NB and MB
+WB
+ 000
+ 1915
+ 268
+ 337
+ 444
+ 5511
+ 6812
+ 713
+ 822
+ 9713
+1010
+115
+126
+139
+1414
+151
+
+
The top 7 bits of each normalized LSF coefficient index a value in the table,
and the next 8 bits interpolate between it and the next value.
Let i = n[k]>>8 be the integer index and
 f = n[k]&255 be the fractional part of a given coefficient.
Then the approximated cosine, c_Q17[k], is
+Let i = (n[k] >> 8) be the integer index and
+ f = (n[k] & 255) be the fractional part of a given
+ coefficient.
+Then the reordered, approximated cosine, c_Q17[ordering[k]], is
> 4 ,
+c_Q17[ordering[k]] = (cos_Q12[i]*256
+ + (cos_Q12[i+1]cos_Q12[i])*f + 4) >> 3 ,
]]>
 where cos_Q13[i] is the corresponding entry of
 .
+ where ordering[k] is the k'th entry of the column of
+ corresponding to the current audio
+ bandwidth and cos_Q12[i] is the i'th entry of .

0
1
2
3
+ title="Q12 Cosine Table for LSF Conversion">
+i
++0
++1
++2
++30
 8192819081828170
+ 40964095409140854
 8152813081048072
+ 40764065405240368
 8034799479467896
+ 401739973973394812
 7840777877147644
+ 392038893857382216
 7568749074067318
+ 378437453703365920
 7226712870266922
+ 361335643513346124
 6812669865806458
+ 340633493290322928
 6332620460705934
+ 316631023035296732
 5792564855025352
+ 289628242751267636
 5198504048804718
+ 259925202440235940
 4552438242124038
+ 227621912106201944
 3862368435023320
+ 193118421751166048
 3136294827602570
+ 156814741380128552
 2378218619901794
+ 1189109399589756
 1598140012021002
+ 79970060150160
 802602402202
+ 40130120110164
 0202402602
+ 010120130168
 802100212021400
+ 40150160170072
1598179419902186
+ 799897995109376
2378257027602948
+118912851380147480
3136332035023684
+156816601751184284
3862403842124382
+193120192106219188
4552471848805040
+227623592440252092
5198535255025648
+259926762751282496
5792593460706204
+2896296730353102100
6332645865806698
+3166322932903349104
6812692270267128
+3406346135133564108
7226731874067490
+3613365937033745112
7568764477147778
+3784382238573889116
7840789679467994
+3920394839733997120
8034807281048130
+4017403640524065124
8152817081828190
+4076408540914095128
8192
+4096
Given the list of cosine values, silk_NLSF2A_find_poly() (silk_NLSF2A.c)
+Given the list of cosine values, silk_NLSF2A_find_poly() (NLSF2A.c)
computes the coefficients of P and Q, described here via a simple recurrence.
Let p_Q16[k][j] and q_Q16[k][j] be the coefficients of the products of the
first (k+1) root pairs for P and Q, with j indexing the coefficient number.
@@ 2476,7 +3332,7 @@ As boundary conditions, assume
j < 0.
Also, assume p_Q16[k][k+2] = p_Q16[k][k] and
q_Q16[k][k+2] = q_Q16[k][k] (because of the symmetry).
Then, for 0 <k < d2 and 0 <= j <= k+1,
+Then, for 0 < k < d2 and 0 <= j <= k+1,

The a32_Q17[] coefficients are too large to fit in a 16bit value, which
@@ 2528,7 +3384,7 @@ Even floatingpoint decoders SHOULD perform these steps, to avoid mismatch.
For each round, the process first finds the index k such that abs(a32_Q17[k])
 is the largest, breaking ties by using the lower value of k.
+ is largest, breaking ties by choosing the lowest value of k.
Then, it computes the corresponding Q12 precision value, maxabs_Q12, subject to
an upper bound to avoid overflow in subsequent computations:
@@ 2545,16 +3401,19 @@ sc_Q16[0] = 65470   ,
(maxabs_Q12 * (k+1)) >> 2
]]>
 where the division here is exact integer division.
+ where the division here is integer division.
This is an approximation of the chirp factor needed to reduce the target
coefficient to 32767, though it is both less than 0.999 and, for
k > 0 when maxabs_Q12 is much greater than 32767, still slightly
too large.
+The upper bound on maxabs_Q12, 163838, was chosen because it is equal to
+ ((2**31  1) >> 14) + 32767, i.e., the
+ largest value of maxabs_Q12 that would not overflow the numerator in the
+ equation above when stored in a signed 32bit integer.
silk_bwexpander_32() (silk_bwexpander_32.c) performs the bandwidth expansion
 (again, only when maxabs_Q12 is greater than 32767) using the following
 recurrence:
+silk_bwexpander_32() (bwexpander_32.c) performs the bandwidth expansion (again,
+ only when maxabs_Q12 is greater than 32767) using the following recurrence:
> 16
@@ 2575,29 +3434,32 @@ After 10 rounds of bandwidth expansion are performed, they are simply saturated
to 16 bits:
> 5, 32767) << 5 .
+a32_Q17[k] = clamp(32768, (a32_Q17[k] + 16) >> 5, 32767) << 5 .
]]>
Because this performs the actual saturation in the Q12 domain, but converts the
coefficients back to the Q17 domain for the purposes of prediction gain
limiting, this step must be performed after the 10th round of bandwidth
 expansion, regardless of whether or not the Q12 version of any of the
 coefficients still overflow a 16bit integer.
+ expansion, regardless of whether or not the Q12 version of any coefficient
+ still overflows a 16bit integer.
This saturation is not performed if maxabs_Q12 drops to 32767 or less prior to
the 10th round.

+
+The prediction gain of an LPC synthesis filter is the squareroot of the output
+ energy when the filter is excited by a unitenergy impulse.
Even if the Q12 coefficients would fit, the resulting filter may still have a
significant gain (especially for voiced sounds), making the filter unstable.
silk_NLSF2A() applies up to 18 additional rounds of bandwidth expansion to
limit the prediction gain.
Instead of controlling the amount of bandwidth expansion using the prediction
gain itself (which may diverge to infinity for an unstable filter),
 silk_NLSF2A() uses LPC_inverse_pred_gain_QA() (silk_LPC_inv_pred_gain.c)
 to compute the reflection coefficients associated with the filter.
+ silk_NLSF2A() uses silk_LPC_inverse_pred_gain_QA() (LPC_inv_pred_gain.c) to
+ compute the reflection coefficients associated with the filter.
The filter is stable if and only if the magnitude of these coefficients is
sufficiently less than one.
The reflection coefficients, rc[k], can be computed using a simple Levinson
@@ 2615,99 +3477,129 @@ a[k1][n] =  .
However, LPC_inverse_pred_gain_QA() approximates this using fixedpoint
+However, silk_LPC_inverse_pred_gain_QA() approximates this using fixedpoint
arithmetic to guarantee reproducible results across platforms and
implementations.
It is important to run on the real Q12 coefficients that will be used during
 reconstruction, because small changes in the coefficients can make a stable
 filter unstable, but increasing the precision back to Q16 allows more accurate
 computation of the reflection coefficients.
+Since small changes in the coefficients can make a stable filter unstable, it
+ takes the real Q12 coefficients that will be used during reconstruction as
+ input.
Thus, let
> 5) << 4
+a32_Q12[n] = (a32_Q17[n] + 16) >> 5
+]]>
+
+ be the Q12 version of the LPC coefficients that will eventually be used.
+As a simple initial check, the decoder computes the DC response as
+
+
+
+ and if DC_resp > 4096, the filter is unstable.
+
+
+Increasing the precision of these Q12 coefficients to Q24 for intermediate
+ computations allows more accurate computation of the reflection coefficients,
+ so the decoder initializes the recurrence via
+
+
 be the Q16 representation of the Q12 version of the LPC coefficients that will
 eventually be used.
Then for each k from d_LPC1 down to 0, if
 abs(a32_Q16[k][k]) > 65520, the filter is unstable and the
+ abs(a32_Q24[k][k]) > 16773022, the filter is unstable and the
recurrence stops.
Otherwise, the row k1 of a32_Q16 is computed from row k as
+The constant 16773022 here is approximately 0.99975 in Q24.
+Otherwise, row k1 of a32_Q24 is computed from row k as
> 32) ,
+ div_Q30[k] = (1<<30)  (rc_Q31[k]*rc_Q31[k] >> 32) ,
 b1[k] = ilog(div_Q30[k])  16 ,
+ b1[k] = ilog(div_Q30[k]) ,
+
+ b2[k] = b1[k]  16 ,
(1<<29)  1
 inv_Qb1[k] =  ,
 div_Q30[k] >> (b1[k]+1)
+ inv_Qb2[k] =  ,
+ div_Q30[k] >> (b2[k]+1)
err_Q29[k] = (1<<29)
  ((div_Q30[k]<<(15b1[k]))*inv_Qb1[k] >> 16) ,

 mul_Q16[k] = ((inv_Qb1[k] << 16)
 + (err_Q29[k]*inv_Qb1[k] >> 13)) >> b1[k] ,
+  ((div_Q30[k]<<(15b2[k]))*inv_Qb2[k] >> 16) ,
 b2[k] = ilog(mul_Q16[k])  15 ,
+ gain_Qb1[k] = ((inv_Qb2[k] << 16)
+ + (err_Q29[k]*inv_Qb2[k] >> 13)) ,
 t_Q16[k1][n] = a32_Q16[k][n]
  ((a32_Q16[k][kn1]*rc_Q31[k] >> 32) << 1) ,
+num_Q24[k1][n] = a32_Q24[k][n]
+  ((a32_Q24[k][kn1]*rc_Q31[k] + (1<<30)) >> 31) ,
a32_Q16[k1][n] = ((t_Q16[k1][n] *
 (mul_Q16[k] << (16b2[k]))) >> 32) << b2[k] .
+a32_Q24[k1][n] = (num_Q24[k1][n]*gain_Qb1[k]
+ + (1<<(b1[k]1))) >> b1[k] ,
]]>
+ where 0 <= n < k.
Here, rc_Q30[k] are the reflection coefficients.
div_Q30[k] is the denominator for each iteration, and mul_Q16[k] is its
 multiplicative inverse.
inv_Qb1[k], which ranges from 16384 to 32767, is a lowprecision version of
 that inverse (with b1[k] fractional bits, where b1[k] ranges from 3 to 14).
err_Q29[k] is the residual error, ranging from 32392 to 32763, which is used
+div_Q30[k] is the denominator for each iteration, and gain_Qb1[k] is its
+ multiplicative inverse (with b1[k] fractional bits, where b1[k] ranges from
+ 20 to 31).
+inv_Qb2[k], which ranges from 16384 to 32767, is a lowprecision version of
+ that inverse (with b2[k] fractional bits).
+err_Q29[k] is the residual error, ranging from 32763 to 32392, which is used
to improve the accuracy.
t_Q16[k1][n], 0 <= n < k, are the numerators for the
 next row of coefficients in the recursion, and a32_Q16[k1][n] is the final
 version of that row.
Every multiply in this procedure except the one used to compute mul_Q16[k]
+The values t_Q24[k1][n] for each n are the numerators for the next row of
+ coefficients in the recursion, and a32_Q24[k1][n] is the final version of
+ that row.
+Every multiply in this procedure except the one used to compute gain_Qb1[k]
requires more than 32 bits of precision, but otherwise all intermediate
results fit in 32 bits or less.
In practice, because each row only depends on the next one, an implementation
does not need to store them all.
If abs(a32_Q16[k][k]) <= 65520 for
+
+
+If abs(a32_Q24[k][k]) <= 16773022 for
0 <= k < d_LPC, then the filter is considered stable.
+However, the problem of determining stability is illconditioned when the
+ filter contains several reflection coefficients whose magnitude is very close
+ to one.
+This fixedpoint algorithm is not mathematically guaranteed to correctly
+ classify filters as stable or unstable in this case, though it does very well
+ in practice.
On round i, 1 <= i <= 18, if the filter passes this
 stability check, then this procedure stops, and the final LPC coefficients to
 use for reconstruction are
+On round i, 1 <= i <= 18, if the filter passes these
+ stability checks, then this procedure stops, and the final LPC coefficients to
+ use for reconstruction in are
> 5 .
]]>
Otherwise, a round of bandwidth expansion is applied using the same procedure
 as in , with
+ as in , with
If, after the 18th round, the filter still fails the stability check, then
 a_Q12[k] is set to 0 for all k.
+During the 15th round, sc_Q16[0] becomes 0 in the above equation, so a_Q12[k]
+ is set to 0 for all k, guaranteeing a stable filter.

After the normalized LSF indices and, for 20 ms frames, the LSF
interpolation index, voiced frames (see )
 include additional LongTerm Prediction (LTP) parameters.
+ include additional LTP parameters.
There is one primary lag index for each SILK frame, but this is refined to
produce a separate lag index per subframe using a vector quantizer.
Each subframe also gets its own prediction gain coefficient.
@@ 2716,12 +3608,24 @@ Each subframe also gets its own prediction gain coefficient.
The primary lag index is coded either relative to the primary lag of the prior
 frame or as an absolute index.
Like the quantization gains, the first LBRR frame, an LBRR frame where the
 previous LBRR frame was not coded, or the first regular SILK frame in an Opus
 frame all code the pitch lag as an absolute index.
When the prior frame was not voiced, this also forces absolute coding.
+ frame in the same channel, or as an absolute index.
+Absolute coding is used if and only if
+
+
+This is the first SILK frame of its type (LBRR or regular) for this channel in
+ the current Opus frame,
+
+
+The previous SILK frame of the same type (LBRR or regular) for this channel in
+ the same Opus frame was not coded, or
+
+
+That previous SILK frame was coded, but was not voiced (see
+ ).
+
+
+
With absolute coding, the primary pitch lag may range from 2 ms
(inclusive) up to 18 ms (exclusive), corresponding to pitches from
@@ 2772,11 +3676,11 @@ If the resulting value is zero, it falls back to the absolute coding procedure
Otherwise, the final primary pitch lag is then
 where lag_prev is the primary pitch lag from the previous frame and
 delta_lag_index is the value just decoded.
+ where previous_lag is the primary pitch lag from the most recent frame in the
+ same channel and delta_lag_index is the value just decoded.
This allows a perframe change in the pitch lag of 8 to +11 samples.
The decoder does no clamping at this point, so this value can fall outside the
range of 2 ms to 18 ms, and the decoder must use this unclamped
@@ 2786,7 +3690,7 @@ However, because an Opus frame can use relative coding for at most two
+ title="PDF for Primary Pitch Lag Change">
PDF{46, 2, 2, 3, 4, 6, 10, 15,
26, 38, 30, 22, 15, 10, 7, 6,
@@ 2800,10 +3704,10 @@ After the primary pitch lag, a "pitch contour", stored as a single entry from
The codebook index is decoded using one of the PDFs in
depending on the current frame size
and audio bandwidth.
 through
 give the corresponding offsets
 to apply to the primary pitch lag for each subframe given the decoded codebook
 index.
+Tables
+ through
+ give the corresponding offsets to apply to the primary pitch lag for each
+ subframe given the decoded codebook index.
+ 1, 1}/256
The final pitch lag for each subframe is assembled in silk_decode_pitch()
 (silk_decode_pitch.c).
+ (decode_pitch.c).
Let lag be the primary pitch lag for the current SILK frame, contour_index be
index of the VQ codebook, and lag_cb[contour_index][k] be the corresponding
entry of the codebook from the appropriate table given above for the k'th
@@ 2933,12 +3837,25 @@ pitch_lags[k] = clamp(lag_min, lag + lag_cb[contour_index][k],

+
+
+SILK uses a separate 5tap pitch filter for each subframe, selected from one
+ of three codebooks.
+The three codebooks each represent different ratedistortion tradeoffs, with
+ average rates of 1.61 bits/subframe, 3.68 bits/subframe, and
+ 4.85 bits/subframe, respectively.
+
+
SILK can use a separate 5tap pitch filter for each subframe.
It selects the filter to use from one of three codebooks.
All of the subframes in a SILK frame must choose their filter from the same
 codebook, itself chosen via an explicitlycoded "periodicity index".
+The importance of the filter coefficients generally depends on two factors: the
+ periodicity of the signal and relative energy between the current subframe and
+ the signal from one period earlier.
+Greater periodicity and decaying energy both lead to more important filter
+ coefficients, and thus should be coded with lower distortion and higher rate.
+These properties are relatively stable over the duration of a single SILK
+ frame, hence all of the subframes in a SILK frame choose their filter from the
+ same codebook.
+This is signaled with an explicitlycoded "periodicity index".
This immediately follows the subframe pitch lags, and is coded using the
3entry PDF from .
@@ 2949,15 +3866,15 @@ This immediately follows the subframe pitch lags, and is coded using the
The index of the filter for use for each subframe follows.
+The indices of the filters for each subframe follow.
They are all coded using the PDF from
corresponding to the periodicity index.
 through
 contain the corresponding filter taps
 as signed Q7 integers.
+Tables
+ through
+ contain the corresponding filter taps as signed Q7 integers.

+Periodicity IndexCodebook SizePDF
@@ 3105,23 +4022,45 @@ They are all coded using the PDF from
After the LTP filter coefficients, an LTP scaling parameter may appear.
This allows the encoder to tradeoff the prediction gain between
 packets against the recovery time after packet loss.
Like the quantization gains, only the first LBRR frame in an Opus frame,
 an LBRR frame where the prior LBRR frame was not coded, and the first regular
 SILK frame in an Opus frame include this field, and, like all of the other
 LTP parameters, only for frames that are also voiced.
Unlike absolutecoding for pitch lags, a SILK frame will not include this field
 just because the prior frame was not voiced.
+An LTP scaling parameter appears after the LTP filter coefficients if and only
+ if
+
+This is a voiced frame (see ), and
+Either
+
+
+This SILK frame corresponds to the first time interval of the
+ current Opus frame for its type (LBRR or regular), or
If present, the value is coded using the 3entry PDF in
+This is an LBRR frame where the LBRR flags (see
+ ) indicate the previous LBRR frame in the same
+ channel is not coded.
+
+
+
+
+This allows the encoder to trade off the prediction gain between
+ packets against the recovery time after packet loss.
+Unlike absolutecoding for pitch lags, regular SILK frames that are not at the
+ start of an Opus frame (i.e., that do not correspond to the first 20 ms
+ time interval in Opus frames of 40 or 60 ms) do not include this
+ field, even if the prior frame was not voiced, or (in the case of the side
+ channel) not even coded.
+After an uncoded frame in the side channel, the LTP buffer (see
+ ) is cleared to zero, and is thus in a
+ known state.
+In contrast, LBRR frames do include this field when the prior frame was not
+ coded, since the LTP buffer contains the output of the PLC, which is
+ nonnormative.
+
+
+If present, the decoder reads a value using the 3entry PDF in
.
The three possible values represent Q14 scale factors of 15565, 12288, and
8192, respectively (corresponding to approximately 0.95, 0.75, and 0.5).
Frames that do not code the scaling parameter use the default factor of 15565
 (0.95).
+ (approximately 0.95).

+
SILK uses a linear congruential generator (LCG) to inject pseudorandom noise
 into the quantized excitation.
+As described in , SILK uses a
+ linear congruential generator (LCG) to inject pseudorandom noise into the
+ quantized excitation.
To ensure synchronization of this process between the encoder and decoder, each
SILK frame stores a 2bit seed after the LTP parameters (if any).
The encoder may consider the choice of this seed during quantization, meaning
 the flexibility to choose the LCG seed can reduce distortion.
The seed is decoded with the uniform 4entry PDF in
+The encoder may consider the choice of seed during quantization, and the
+ flexibility of this choice lets it reduce distortion, helping to pay for the
+ bit cost required to signal it.
+The decoder reads the seed using the uniform 4entry PDF in
, yielding a value between 0 and 3, inclusive.
@@ 3154,13 +4096,13 @@ The seed is decoded with the uniform 4entry PDF in

+
SILK codes the excitation using a modified version of the Pyramid Vector
Quantization (PVQ) codebook .
The PVQ codebook consists of all sums of K signed, unit pulses in a vector of
 dimension N, where two pulses at the same position are required to have the
 same sign.
+The PVQ codebook is designed for Laplacedistributed values and consists of all
+ sums of K signed, unit pulses in a vector of dimension N, where two pulses at
+ the same position are required to have the same sign.
Thus the codebook includes all integer codevectors y of dimension N that
satisfy
@@ 3174,14 +4116,14 @@ j=0
Unlike regular PVQ, SILK uses a variablelength, rather than fixedlength,
encoding.
This encoding is more suited to the Gaussianlike distribution of the
+This encoding is better suited to the more Gaussianlike distribution of the
coefficient magnitudes and the nonuniform distribution of their signs (caused
by the quantization offset described below).
SILK also handles large codebooks by coding the least significant bits (LSBs)
of each coefficient directly.
This adds a small coding efficiency loss, but greatly reduces the computation
time and ROM size required for decoding, as implemented in
 silk_decode_pulses() (silk_decode_pulses.c).
+ silk_decode_pulses() (decode_pulses.c).
@@ 3245,17 +4187,25 @@ An encoder should, but is not required to, use the most efficient rate level.
The total number of pulses in each of the shell blocks follows the rate level.
The pulse counts for all of the shell blocks are coded in a row, before the
 content of any of the blocks.
+The pulse counts for all of the shell blocks are coded consecutively, before
+ the content of any of the blocks.
Each block may have anywhere from 0 to 16 pulses, inclusive, coded using the
18entry PDF in corresponding to the
rate level from .
The special value 17 indicates that this block has one or more additional
LSBs to decode for each coefficient.
If it is encountered, another value is decoded using the PDF corresponding to
 the special rate level 9 instead of the normal rate level.
This process repeats until a value less than 17 is decoded, and the number of
 extra LSBs used is set to the number of 17's decoded for that block.
+If the decoder encounters this value, it decodes another value for the actual
+ pulse count of the block, but uses the PDF corresponding to the special rate
+ level 9 instead of the normal rate level.
+This process repeats until the decoder reads a value less than 17, and it then
+ sets the number of extra LSBs used to the number of 17's decoded for that
+ block.
+If it reads the value 17 ten times, then the next iteration uses the special
+ rate level 10 instead of 9.
+The probability of decoding a 17 when using the PDF for rate level 10 is
+ zero, ensuring that the number of LSBs for a block will not exceed 10.
+The cumulative distribution for rate level 10 is just a shifted version of
+ that for 9 and thus does not require any additional storage.
{1, 2, 2, 5, 9, 14, 20, 24, 27, 28, 26, 23, 20, 15, 11, 8, 6, 15}/256
9{1, 1, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2}/256
+10
+{2, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2, 0}/256

+
The locations of the pulses in each shell block follows the pulse counts,
 as decoded by silk_shell_decoder() (silk_shell_coder.c).
+The locations of the pulses in each shell block follow the pulse counts,
+ as decoded by silk_shell_decoder() (shell_coder.c).
As with the pulse counts, these locations are coded for all the shell blocks
before any of the remaining information for each block.
Unlike many other codecs, SILK places no restriction on the distribution of
pulses within a shell block.
All of the pulses may be placed in a single location, or each one in a unique
 location, or anything inbetween.
+ location, or anything in between.
@@ 3306,9 +4258,9 @@ The process then recurses into the left half, and after that returns, the
right half (preorder traversal).
The PDF to use is chosen by the size of the current partition (16, 8, 4, or 2)
and the number of pulses in the partition (1 to 16, inclusive).
 through
 list the PDFs use for each partition
 size and pulse count.
+Tables
+ through list the
+ PDFs used for each partition size and pulse count.
This process skips partitions without any pulses, i.e., where the initial pulse
count from was zero, or where the split in
the prior level indicated that all of the pulses fell on the other side.
@@ 3405,38 +4357,587 @@ These partitions have nothing to code, so they require no PDF.
+
+
+After the decoder reads the pulse locations for all blocks, it reads the LSBs
+ (if any) for each block in turn.
+Inside each block, it reads all the LSBs for each coefficient in turn, even
+ those where no pulses were allocated, before proceeding to the next one.
+For 10 ms MB frames, it reads LSBs even for the extra 8 samples in
+ the last block.
+The LSBs are coded from most significant to least significant, and they all use
+ the PDF in .
+
+
+
+PDF
+{136, 120}/256
+
+
+
+The number of LSBs read for each coefficient in a block is determined in
+ .
+The magnitude of the coefficient is initially equal to the number of pulses
+ placed at that location in .
+As each LSB is decoded, the magnitude is doubled, and then the value of the LSB
+ added to it, to obtain an updated magnitude.
+
+
+
+After decoding the pulse locations and the LSBs, the decoder knows the
+ magnitude of each coefficient in the excitation.
+It then decodes a sign for all coefficients with a nonzero magnitude, using
+ one of the PDFs from .
+If the value decoded is 0, then the coefficient magnitude is negated.
+Otherwise, it remains positive.
+
+
+
+The decoder chooses the PDF for the sign based on the signal type and
+ quantization offset type (from ) and the
+ number of pulses in the block (from ).
+The number of pulses in the block does not take into account any LSBs.
+Most PDFs are skewed towards negative signs because of the quantization offset,
+ but the PDFs for zero pulses are highly skewed towards positive signs.
+If a block contains many positive coefficients, it is sometimes beneficial to
+ code it solely using LSBs (i.e., with zero pulses), since the encoder may be
+ able to save enough bits on the signs to justify the less efficient
+ coefficient magnitude encoding.
+
+
+
+Signal Type
+Quantization Offset Type
+Pulse Count
+PDF
+InactiveLow0{2, 254}/256
+InactiveLow1{207, 49}/256
+InactiveLow2{189, 67}/256
+InactiveLow3{179, 77}/256
+InactiveLow4{174, 82}/256
+InactiveLow5{163, 93}/256
+InactiveLow6 or more{157, 99}/256
+InactiveHigh0{58, 198}/256
+InactiveHigh1{245, 11}/256
+InactiveHigh2{238, 18}/256
+InactiveHigh3{232, 24}/256
+InactiveHigh4{225, 31}/256
+InactiveHigh5{220, 36}/256
+InactiveHigh6 or more{211, 45}/256
+UnvoicedLow0{1, 255}/256
+UnvoicedLow1{210, 46}/256
+UnvoicedLow2{190, 66}/256
+UnvoicedLow3{178, 78}/256
+UnvoicedLow4{169, 87}/256
+UnvoicedLow5{162, 94}/256
+UnvoicedLow6 or more{152, 104}/256
+UnvoicedHigh0{48, 208}/256
+UnvoicedHigh1{242, 14}/256
+UnvoicedHigh2{235, 21}/256
+UnvoicedHigh3{224, 32}/256
+UnvoicedHigh4{214, 42}/256
+UnvoicedHigh5{205, 51}/256
+UnvoicedHigh6 or more{190, 66}/256
+VoicedLow0{1, 255}/256
+VoicedLow1{162, 94}/256
+VoicedLow2{152, 104}/256
+VoicedLow3{147, 109}/256
+VoicedLow4{144, 112}/256
+VoicedLow5{141, 115}/256
+VoicedLow6 or more{138, 118}/256
+VoicedHigh0{8, 248}/256
+VoicedHigh1{203, 53}/256
+VoicedHigh2{187, 69}/256
+VoicedHigh3{176, 80}/256
+VoicedHigh4{168, 88}/256
+VoicedHigh5{161, 95}/256
+VoicedHigh6 or more{154, 102}/256
+
+

+
+
+
+After the signs have been read, there is enough information to reconstruct the
+ complete excitation signal.
+This requires adding a constant quantization offset to each nonzero sample,
+ and then pseudorandomly inverting and offsetting every sample.
+The constant quantization offset varies depending on the signal type and
+ quantization offset type (see ).
+
+
+
+Signal Type
+Quantization Offset Type
+Quantization Offset (Q23)
+InactiveLow25
+InactiveHigh60
+UnvoicedLow25
+UnvoicedHigh60
+VoicedLow8
+VoicedHigh25
+
+
LBRR frames, if present, immediately follow the header bits, prior to any
 regular SILK frames.
Each frame whose LBRR flag was set includes a separate set of data for each
 channel.
+Let e_raw[i] be the raw excitation value at position i, with a magnitude
+ composed of the pulses at that location (see
+ ) combined with any additional LSBs (see
+ ), and with the corresponding sign decoded in
+ .
+Additionally, let seed be the current pseudorandom seed, which is initialized
+ to the value decoded from for the first sample in
+ the current SILK frame, and updated for each subsequent sample according to
+ the procedure below.
+Finally, let offset_Q23 be the quantization offset from
+ .
+Then the following procedure produces the final reconstructed excitation value,
+ e_Q23[i]:
+
+
+
+When e_raw[i] is zero, sign() returns 0 by the definition in
+ , so the factor of 20 does not get added.
+The final e_Q23[i] value may require more than 16 bits per sample, but will not
+ require more than 23, including the sign.
+
+

+
+The remainder of the reconstruction process for the frame does not need to be
+ bitexact, as small errors should only introduce proportionally small
+ distortions.
+Although the reference implementation only includes a fixedpoint version of
+ the remaining steps, this section describes them in terms of a floatingpoint
+ version for simplicity.
+This produces a signal with a nominal range of 1.0 to 1.0.
+
The CELT layer is decoded based on the following symbols and sets of symbols:
+silk_decode_core() (decode_core.c) contains the code for the main
+ reconstruction process.
+It proceeds subframebysubframe, since quantization gains, LTP parameters, and
+ (in 20 ms SILK frames) LPC coefficients can vary from one to the
+ next.

Symbol(s)
PDF
Condition
silence{32767, 1}/32768
postfilter{1, 1}/2
octaveuniform (6)postfilter
periodraw bits (4+octave)postfilter
gainraw bits (3)postfilter
tapset{2, 1, 1}/4postfilter
+
+Let a_Q12[k] be the LPC coefficients for the current subframe.
+If this is the first or second subframe of a 20 ms SILK frame and the LSF
+ interpolation factor, w_Q2 (see ), is
+ less than 4, then these correspond to the final LPC coefficients produced by
+ from the interpolated LSF coefficients,
+ n1_Q15[k] (computed in ).
+Otherwise, they correspond to the final LPC coefficients produced from the
+ uninterpolated LSF coefficients for the current frame, n2_Q15[k].
+
+
+
+Also, let n be the number of samples in a subframe (40 for NB, 60 for MB, and
+ 80 for WB), s be the index of the current subframe in this SILK frame (0 or 1
+ for 10 ms frames, or 0 to 3 for 20 ms frames), and j be the index of
+ the first sample in the residual corresponding to the current subframe.
+
+
+
+
+Voiced SILK frames (see ) pass the excitation
+ through an LTP filter using the parameters decoded in
+ to produce an LPC residual.
+The LTP filter requires LPC residual values from before the current subframe as
+ input.
+However, since the LPC coefficients may have changed, it obtains this residual
+ by "rewhitening" the corresponding output signal using the LPC coefficients
+ from the current subframe.
+Let out[i] for
+ (j  pitch_lags[s]  d_LPC  2) <= i < j
+ be the fully reconstructed output signal from the last
+ (pitch_lags[s] + d_LPC + 2) samples of previous subframes
+ (see ), where pitch_lags[s] is the pitch
+ lag for the current subframe from .
+During reconstruction of the first subframe for this channel after either
+
+An uncoded regular SILK frame (if this is the side channel), or
+A decoder reset (see ),
+
+ out[] is rewhitened into an LPC residual,
+ res[i], via
+
+
+
+This requires storage to buffer up to 306 values of out[i] from previous
+ subframes.
+This corresponds to WB with a maximum pitch lag of
+ 18 ms * 16 kHz samples, plus 16 samples for d_LPC, plus 2
+ samples for the width of the LTP filter.
+
+
+
+Let e_Q23[i] for j <= i < (j + n) be the
+ excitation for the current subframe, and b_Q7[k] for
+ 0 <= k < 5 be the coefficients of the LTP filter
+ taken from the codebook entry in one of
+ Tables
+ through
+ corresponding to the index decoded for the current subframe in
+ .
+Then for i such that j <= i < (j + n),
+ the LPC residual is
+
+
+
+
+
+
+For unvoiced frames, the LPC residual for
+ j <= i < (j + n) is simply a normalized
+ copy of the excitation signal, i.e.,
+
+
+
+
+
+
+
+
+LPC synthesis uses the shortterm LPC filter to predict the next output
+ coefficient.
+For i such that (j  d_LPC) <= i < j, let
+ lpc[i] be the result of LPC synthesis from the last d_LPC samples of the
+ previous subframe, or zeros in the first subframe for this channel after
+ either
+
+An uncoded regular SILK frame (if this is the side channel), or
+A decoder reset (see ).
+
+Then for i such that j <= i < (j + n), the
+ result of LPC synthesis for the current subframe is
+
+
+
+The decoder saves the final d_LPC values, i.e., lpc[i] such that
+ (j + n  d_LPC) <= i < (j + n),
+ to feed into the LPC synthesis of the next subframe.
+This requires storage for up to 16 values of lpc[i] (for WB frames).
+
+
+
+Then, the signal is clamped into the final nominal range:
+
+
+
+This clamping occurs entirely after the LPC synthesis filter has run.
+The decoder saves the unclamped values, lpc[i], to feed into the LPC filter for
+ the next subframe, but saves the clamped values, out[i], for rewhitening in
+ voiced frames.
+
+
+
+
+
+
+
+
+
+For stereo streams, after decoding a frame from each channel, the decoder must
+ convert the midside (MS) representation into a leftright (LR)
+ representation.
+The function silk_stereo_MS_to_LR (stereo_MS_to_LR.c) implements this process.
+In it, the decoder predicts the side channel using a) a simple lowpassed
+ version of the mid channel, and b) the unfiltered mid channel, using the
+ prediction weights decoded in .
+This simple lowpass filter imposes a onesample delay, and the unfiltered
+mid channel is also delayed by one sample.
+In order to allow seamless switching between stereo and mono, mono streams must
+ also impose the same onesample delay.
+The encoder requires an additional onesample delay for both mono and stereo
+ streams, though an encoder may omit the delay for mono if it knows it will
+ never switch to stereo.
+
+
+
+The unmixing process operates in two phases.
+The first phase lasts for 8 ms, during which it interpolates the
+ prediction weights from the previous frame, prev_w0_Q13 and prev_w1_Q13, to
+ the values for the current frame, w0_Q13 and w1_Q13.
+The second phase simply uses these weights for the remainder of the frame.
+
+
+
+Let mid[i] and side[i] be the contents of out[i] (from
+ ) for the current mid and side channels,
+ respectively, and let left[i] and right[i] be the corresponding stereo output
+ channels.
+If the side channel is not coded (see ),
+ then side[i] is set to zero.
+Also let j be defined as in , n1 be
+ the number of samples in phase 1 (64 for NB, 96 for MB, and 128 for WB),
+ and n2 be the total number of samples in the frame.
+Then for i such that j <= i < (j + n2),
+ the left and right channel output is
+
+
+
+These formulas require two samples prior to index j, the start of the
+ frame, for the mid channel, and one prior sample for the side channel.
+For the first frame after a decoder reset, zeros are used instead.
+
+
+
+
+
+
+After stereo unmixing (if any), the decoder applies resampling to convert the
+ decoded SILK output to the sample rate desired by the application.
+This is necessary when decoding a Hybrid frame at SWB or FB sample rates, or
+ whenever the decoder wants the output at a different sample rate than the
+ internal SILK sampling rate (e.g., to allow a constant sample rate when the
+ audio bandwidth changes, or to allow mixing with audio from other
+ applications).
+The resampler itself is nonnormative, and a decoder can use any method it
+ wants to perform the resampling.
+
+
+
+However, a minimum amount of delay is imposed to allow the resampler to
+ operate, and this delay is normative, so that the corresponding delay can be
+ applied to the MDCT layer in the encoder.
+A decoder is always free to use a resampler which requires more delay than
+ allowed for here (e.g., to improve quality), but it must then delay the output
+ of the MDCT layer by this extra amount.
+Keeping as much delay as possible on the encoder side allows an encoder which
+ knows it will never use any of the SILK or Hybrid modes to skip this delay.
+By contrast, if it were all applied by the decoder, then a decoder which
+ processes audio in fixedsize blocks would be forced to delay the output of
+ CELT frames just in case of a later switch to a SILK or Hybrid mode.
+
+
+
+ gives the maximum resampler delay
+ in samples at 48 kHz for each SILK audio bandwidth.
+Because the actual output rate may not be 48 kHz, it may not be possible
+ to achieve exactly these delays while using a whole number of input or output
+ samples.
+The reference implementation is able to resample to any of the supported
+ output sampling rates (8, 12, 16, 24, or 48 kHz) within or near this
+ delay constraint.
+Some resampling filters (including those used by the reference implementation)
+ may add a delay that is not an exact integer, or is not linearphase, and so
+ cannot be represented by a single delay at all frequencies.
+However, such deviations are unlikely to be perceptible, and the comparison
+ tool described in is designed to be relatively
+ insensitive to them.
+The delays listed here are the ones that should be targeted by the encoder.
+
+
+
+Audio Bandwidth
+Delay in millisecond
+NB0.538
+MB0.692
+WB0.706
+
+
+
+NB is given a smaller decoder delay allocation than MB and WB to allow a
+ higherorder filter when resampling to 8 kHz in both the encoder and
+ decoder.
+This implies that the audio content of two SILK frames operating at different
+ bandwidths are not perfectly aligned in time.
+This is not an issue for any transitions described in
+ , because they all involve a SILK decoder reset.
+When the decoder is reset, any samples remaining in the resampling buffer
+ are discarded, and the resampler is reinitialized with silence.
+
+
+
+
+
+
+
+
+
+
+The CELT layer of Opus is based on the Modified Discrete Cosine Transform
+ with partially overlapping windows of 5 to 22.5 ms.
+The main principle behind CELT is that the MDCT spectrum is divided into
+bands that (roughly) follow the Bark scale, i.e., the scale of the ear's
+critical bands . The normal CELT layer uses 21 of those bands, though Opus
+ Custom (see ) may use a different number of bands.
+In Hybrid mode, the first 17 bands (up to 8 kHz) are not coded.
+A band can contain as little as one MDCT bin per channel, and as many as 176
+bins per channel, as detailed in .
+In each band, the gain (energy) is coded separately from
+the shape of the spectrum. Coding the gain explicitly makes it easy to
+preserve the spectral envelope of the signal. The remaining unitnorm shape
+vector is encoded using a Pyramid Vector Quantizer (PVQ) .
+
+
+
+Frame Size:
+2.5 ms
+5 ms
+10 ms
+20 ms
+Start Frequency
+Stop Frequency
+BandBins:
+ 012480 Hz200 Hz
+ 11248200 Hz400 Hz
+ 21248400 Hz600 Hz
+ 31248600 Hz800 Hz
+ 41248800 Hz1000 Hz
+ 512481000 Hz1200 Hz
+ 612481200 Hz1400 Hz
+ 712481400 Hz1600 Hz
+ 8248161600 Hz2000 Hz
+ 9248162000 Hz2400 Hz
+10248162400 Hz2800 Hz
+11248162800 Hz3200 Hz
+124816323200 Hz4000 Hz
+134816324000 Hz4800 Hz
+144816324800 Hz5600 Hz
+1561224485600 Hz6800 Hz
+1661224486800 Hz8000 Hz
+1781632648000 Hz9600 Hz
+18122448969600 Hz12000 Hz
+1918367214412000 Hz15600 Hz
+2022448817615600 Hz20000 Hz
+
+
+
+Transients are notoriously difficult for transform codecs to code.
+CELT uses two different strategies for them:
+
+Using multiple smaller MDCTs instead of a single large MDCT, and
+Dynamic timefrequency resolution changes (See ).
+
+To improve quality on highly tonal and periodic signals, CELT includes
+a prefilter/postfilter combination. The prefilter on the encoder side
+attenuates the signal's harmonics. The postfilter on the decoder side
+restores the original gain of the harmonics, while shaping the coding noise
+to roughly follow the harmonics. Such noise shaping reduces the perception
+of the noise.
+
+
+
+When coding a stereo signal, three coding methods are available:
+
+midside stereo: encodes the mean and the difference of the left and right channels,
+intensity stereo: only encodes the mean of the left and right channels (discards the difference),
+dual stereo: encodes the left and right channels separately.
+
+
+
+
+An overview of the decoder is given in .
+
+
+
+ decoder +
+  ++ 
+  
+  ++ v
+   Fine  ++
+ +> decoder > + 
+  ++ ++
+  ^ 
+++   
+ Range   ++ v
+ Decoder +  Bit  ++
+++  Allocation  2**x 
+  ++ ++
+   
+  v v ++
+  ++ ++ ++  pitch 
+ +> PVQ > * > IMDCT > post >
+   decoder  ++ ++  filter 
+  ++ ++
+  ^
+ ++
+]]>
+
+
+
+The decoder is based on the following symbols and sets of symbols:
+
+
+
+Symbol(s)
+PDF
+Condition
+silence{32767, 1}/32768
+postfilter{1, 1}/2
+octaveuniform (6)postfilter
+periodraw bits (4+octave)postfilter
+gainraw bits (3)postfilter
+tapset{2, 1, 1}/4postfiltertransient{7, 1}/8intra{7, 1}/8coarse energy
@@ 3452,25 +4953,26 @@ The CELT layer is decoded based on the following symbols and sets of symbols:
residualanticollapse{1, 1}/2finalize
Order of the symbols in the CELT section of the bitstream.
The decoder extracts information from the rangecoded bitstream in the order
described in the figure above. In some circumstances, it is
+The decoder extracts information from the rangecoded bitstream in the order
+described in . In some circumstances, it is
possible for a decoded value to be out of range due to a very small amount of redundancy
in the encoding of large integers by the range coder.
In that case, the decoder should assume there has been an error in the coding,
decoding, or transmission and SHOULD take measures to conceal the error and/or report
to the application that a problem has occurred.
+to the application that a problem has occurred. Such out of range errors cannot occur
+in the SILK layer.
The "transient" flag encoded in the bitstream has a probability of 1/8.
+The "transient" flag indicates whether the frame uses a single long MDCT or several short MDCTs.
When it is set, then the MDCT coefficients represent multiple
short MDCTs in the frame. When not set, the coefficients represent a single
long MDCT for the frame. In addition to the global transient flag is a perband
+long MDCT for the frame. The flag is encoded in the bitstream with a probability of 1/8.
+In addition to the global transient flag is a perband
binary flag to change the timefrequency (tf) resolution independently in each band. The
change in tf resolution is defined in tf_select_table[][] in celt.c and depends
on the frame size, whether the transient flag is set, and the value of tf_select.
@@ 3485,7 +4987,7 @@ tf_change flags.
It is important to quantize the energy with sufficient resolution because
any energy quantization error cannot be compensated for at a later
stage. Regardless of the resolution used for encoding the shape of a band,
+stage. Regardless of the resolution used for encoding the spectral shape of a band,
it is perceptually important to preserve the energy in each band. CELT uses a
threestep coarsefinefine strategy for encoding the energy in the base2 log
domain, as implemented in quant_bands.c
@@ 3499,7 +5001,7 @@ bands). The part of the prediction that is based on the
previous frame can be disabled, creating an "intra" frame where the energy
is coded without reference to prior frames. The decoder first reads the intra flag
to determine what prediction is used.
The 2D ztransform of
+The 2D ztransform of
the prediction filter is:
@@ 3553,45 +5057,51 @@ This is implemented in unquant_energy_finalise() (quant_bands.c).

Many codecs transmit significant amounts of side information for
the purpose of controlling bit allocation within a frame. Often this
side information controls bit usage indirectly and must be carefully
selected to achieve the desired rate constraints.

The bandenergy normalized structure of Opus MDCT mode ensures that a
constant bit allocation for the shape content of a band will result in a
roughly constant tone to noise ratio, which provides for fairly consistent
perceptual performance. The effectiveness of this approach is the result of
two factors: The band energy, which is understood to be perceptually
important on its own, is always preserved regardless of the shape precision and because
the constant tonetonoise ratio implies a constant intraband noise to masking ratio.
Intraband masking is the strongest of the perceptual masking effects. This structure
means that the ideal allocation is more consistent from frame to frame than
it is for other codecs without an equivalent structure.

Because the bit allocation is used to drive the decoding of the rangecoder
stream it MUST be recovered exactly so that identical coding decisions are
+
+
+Because the bit allocation drives the decoding of the rangecoder
+stream, it MUST be recovered exactly so that identical coding decisions are
made in the encoder and decoder. Any deviation from the reference's resulting
bit allocation will result in corrupted output, though implementers are
free to implement the procedure in any way which produces identical results.
Because all of the information required to decode a frame must be derived
from that frame alone in order to retain robustness to packet loss the
overhead of explicitly signaling the allocation would be considerable,
especially for lowlatency (small frame size) applications,
even though the allocation is relatively static.
+The perband gainshape structure of the CELT layer ensures that using
+ the same number of bits for the spectral shape of a band in every frame will
+ result in a roughly constant signaltonoise ratio in that band.
+This results in coding noise that has the same spectral envelope as the signal.
+The masking curve produced by a standard psychoacoustic model also closely
+ follows the spectral envelope of the signal.
+This structure means that the ideal allocation is more consistent from frame to
+ frame than it is for other codecs without an equivalent structure, and that a
+ fixed allocation provides fairly consistent perceptual
+ performance .
+
+Many codecs transmit significant amounts of side information to control the
+ bit allocation within a frame.
+Often this control is only indirect, and must be exercised carefully to
+ achieve the desired rate constraints.
+The CELT layer, however, can adapt over a very wide range of rates, and thus
+ has a large number of codebook sizes to choose from for each band.
+Explicitly signaling the size of each of these codebooks would impose
+ considerable overhead, even though the allocation is relatively static from
+ frame to frame.
+This is because all of the information required to compute these codebook sizes
+ must be derived from a single frame by itself, in order to retain robustness
+ to packet loss, so the signaling cannot take advantage of knowledge of the
+ allocation in neighboring frames.
+This problem is exacerbated in lowlatency (small frame size) applications,
+ which would include this overhead in every frame.For this reason, in the MDCT mode Opus uses a primarily implicit bit
allocation. The available bitstream capacity is known in advance to both
+allocation. The available bitstream capacity is known in advance to both
the encoder and decoder without additional signaling, ultimately from the
packet sizes expressed by a higher level protocol. Using this information
+packet sizes expressed by a higherlevel protocol. Using this information,
the codec interpolates an allocation from a hardcoded table.While the bandenergy structure effectively models intraband masking,
it ignores the weaker interband masking, bandtemporal masking, and
other less significant perceptual effects. While these effects can
often be ignored they can become significant for particular samples. One
+often be ignored, they can become significant for particular samples. One
mechanism available to encoders would be to simply increase the overall
rate for these frames, but this is not possible in a constant rate mode
and can be fairly inefficient. As a result three explicitly signaled
@@ 3601,7 +5111,7 @@ mechanisms are provided to alter the implicit allocation:Band boostAllocation trim
band skipping
+Band skipping
@@ 3611,81 +5121,129 @@ biasing the overall allocation towards higher or lower frequency bands. The thir
skipping, selects which lowprecision high frequency bands
will be allocated no shape bits at all.
In stereo mode there are also two additional parameters
+In stereo mode there are two additional parameters
potentially coded as part of the allocation procedure: a parameter to allow the
selective elimination of allocation for the 'side' in jointly coded bands,
and a flag to deactivate joint coding. These values are not signaled if
+selective elimination of allocation for the 'side' (i.e., intensity stereo) in jointly coded bands,
+and a flag to deactivate joint coding (i.e., dual stereo). These values are not signaled if
they would be meaningless in the overall context of the allocation.Because every signaled adjustment increases overhead and implementation
complexity none were included speculatively: The reference encoder makes use
+complexity, none were included speculatively: the reference encoder makes use
of all of these mechanisms. While the decision logic in the reference was
found to be effective enough to justify the overhead and complexity further
+found to be effective enough to justify the overhead and complexity, further
analysis techniques may be discovered which increase the effectiveness of these
parameters. As with other signaled parameters, encoder is free to choose the
values in any manner but unless a technique is known to deliver superior
+parameters. As with other signaled parameters, an encoder is free to choose the
+values in any manner, but unless a technique is known to deliver superior
perceptual results the methods used by the reference implementation should be
used.
The process of allocation consists of the following steps: determining the perband
+The allocation process consists of the following steps: determining the perband
maximum allocation vector, decoding the boosts, decoding the tilt, determining
the remaining capacity the frame, searching the mode table for the
+the remaining capacity of the frame, searching the mode table for the
entry nearest but not exceeding the available space (subject to the tilt, boosts, band
maximums, and band minimums), linear interpolation, reallocation of
unused bits with concurrent skip decoding, determination of the
fineenergy vs shape split, and final reallocation. This process results
in an shape allocation perband (in 1/8th bit units), a perband fineenergy
+fineenergy vs. shape split, and final reallocation. This process results
+in a perband shape allocation (in 1/8th bit units), a perband fineenergy
allocation (in 1 bit per channel units), a set of band priorities for
controlling the use of remaining bits at the end of the frame, and a
remaining balance of unallocated space which is usually zero except
+remaining balance of unallocated space, which is usually zero except
at very high rates.
+
+The "static" bit allocation (in 1/8 bits) for a quality q, excluding the minimums, maximums,
+tilt and boosts, is equal to channels*N*alloc[band][q]<<LM>>2, where
+alloc[][] is given in and LM=log2(frame_size/120). The allocation
+is obtained by linearly interpolating between two values of q (in steps of 1/64) to find the
+highest allocation that does not exceed the number of bits remaining.
+
+
+
+ Rows indicate the MDCT bands, columns are the different quality (q) parameters. The units are 1/32 bit per MDCT bin.
+0
+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+090110118126134144152162172200
+080100110119127137145155165200
+07590103112120130138148158200
+0698493104114124132142152200
+063788695103113123133143200
+05671808997107117127137200
+04965758391101111121131200
+0405870788595105115125200
+034516572788898108118198
+029455966728292102112193
+02039536066768696106188
+01832475460708090100183
+0102640475464748494178
+002031394757677787173
+001223324151617181168
+00015253545556575163
+0004172939495969158
+0000122333435363153
+000011626364656148
+000001015203045129
+00000111120104
+
+
The maximum allocation vector is an approximation of the maximum space
which can be used by each band for a given mode. The value is
+that can be used by each band for a given mode. The value is
approximate because the shape encoding is variable rate (due
to entropy coding of splitting parameters). Setting the maximum too low reduces the
maximum achievable quality in a band while setting it too high
may result in waste: bitstream capacity available at the end
+may result in waste: bitstream capacity available at the end
of the frame which can not be put to any use. The maximums
specified by the codec reflect the average maximum. In the reference
the maximums are provided partially computed form, in order to fit in less
memory, as a static table (XXX cache.caps). Implementations are expected
to simply use the same table data but the procedure for generating
+implementation, the maximums in bits/sample are precomputed in a static table
+(see cache_caps50[] in static_modes_float.h) for each band,
+for each value of LM, and for both mono and stereo.
+
+Implementations are expected
+to simply use the same table data, but the procedure for generating
this table is included in rate.c as part of compute_pulse_cache().
To convert the values in cache.caps into the actual maximums: First
set nbBands to the maximum number of bands for this mode and stereo to
zero if stereo is not in use and one otherwise. For each band assign N
+To convert the values in cache.caps into the actual maximums: first
+set nbBands to the maximum number of bands for this mode, and stereo to
+zero if stereo is not in use and one otherwise. For each band set N
to the number of MDCT bins covered by the band (for one channel), set LM
to the shift value for the frame size (e.g. 0 for 120, 1 for 240, 3 for 480)
+to the shift value for the frame size,
then set i to nbBands*(2*LM+stereo). Then set the maximum for the band to
the ith index of cache.caps + 64 and multiply by the number of channels
in the current frame (one or two) and by N then divide the result by 4
using truncating integer division. The resulting vector will be called
cap[]. The elements fit in signed 16 bit integers but do not fit in 8 bits.
+in the current frame (one or two) and by N, then divide the result by 4
+using integer division. The resulting vector will be called
+cap[]. The elements fit in signed 16bit integers but do not fit in 8 bits.
This procedure is implemented in the reference in the function init_caps() in celt.c.
The band boosts are represented by a series of binary symbols which
are coded with very low probability. Each band can potentially be boosted
+are entropy coded with very low probability. Each band can potentially be boosted
multiple times, subject to the frame actually having enough room to obey
the boost and having enough room to code the boost symbol. The default
coding cost for a boost starts out at six bits, but subsequent boosts
+coding cost for a boost starts out at six bits (probability p=1/64), but subsequent boosts
in a band cost only a single bit and every time a band is boosted the
initial cost is reduced (down to a minimum of two). Since the initial
cost of coding a boost is 6 bits the coding cost of the boost symbols when
+initial cost is reduced (down to a minimum of two bits, or p=1/4). Since the initial
+cost of coding a boost is 6 bits, the coding cost of the boost symbols when
completely unused is 0.48 bits/frame for a 21 band mode (21*log2(11/2**6)).To decode the band boosts: First set 'dynalloc_logp' to 6, the initial
amount of storage required to signal a boost in bits, 'total_bits' to the
size of the frame in 8thbits, 'total_boost' to zero, and 'tell' to the total number
+size of the frame in 8th bits, 'total_boost' to zero, and 'tell' to the total number
of 8th bits decoded
so far. For each band from the coding start (0 normally, but 17 in hybrid mode)
to the coding end (which changes depending on the signaled bandwidth): Set 'width'
to the number of MDCT bins in this band for all channels. Take the larger of width
and 64, then the minimum of that value and the width times eight and set 'quanta'
to the result. This represents a boost step size of six bits subject to limits
of 1/bit/sample and 1/8th bit/sample. Set 'boost' to zero and 'dynalloc_loop_logp'
+so far. For each band from the coding start (0 normally, but 17 in Hybrid mode)
+to the coding end (which changes depending on the signaled bandwidth), the boost quanta
+in units of 1/8 bit is calculated as quanta = min(8*N, max(48, N)).
+This represents a boost step size of six bits, subject to a lower limit of
+1/8th bit/sample and an upper limit of 1 bit/sample.
+Set 'boost' to zero and 'dynalloc_loop_logp'
to dynalloc_logp. While dynalloc_loop_log (the current worst case symbol cost) in
8th bits plus tell is less than total_bits plus total_boost and boost is less than cap[] for this
band: Decode a bit from the bitstream with a with dynalloc_loop_logp as the cost
@@ 3693,16 +5251,16 @@ of a one, update tell to reflect the current used capacity, if the decoded value
is zero break the loop otherwise add quanta to boost and total_boost, subtract quanta from
total_bits, and set dynalloc_loop_log to 1. When the while loop finishes
boost contains the boost for this band. If boost is nonzero and dynalloc_logp
is greater than 2 decrease dynalloc_logp. Once this process has been
execute on all bands the band boosts have been decoded. This procedure
is implemented around line 2352 of celt.c.
+is greater than 2, decrease dynalloc_logp. Once this process has been
+executed on all bands, the band boosts have been decoded. This procedure
+is implemented around line 2474 of celt.c.
At very low rates it's possible that there won't be enough available
+At very low rates it is possible that there won't be enough available
space to execute the inner loop even once. In these cases band boost
is not possible but its overhead is completely eliminated. Because of the
high cost of band boost when activated a reasonable encoder should not be
+high cost of band boost when activated, a reasonable encoder should not be
using it at very low rates. The reference implements its dynalloc decision
logic at around 1269 of celt.c
+logic around line 1304 of celt.c.The allocation trim is a integer value from 010. The default value of
5 indicates no trim. The trim parameter is entropy coded in order to
@@ 3710,57 +5268,67 @@ lower the coding cost of less extreme adjustments. Values lower than
5 bias the allocation towards lower frequencies and values above 5
bias it towards higher frequencies. Like other signaled parameters, signaling
of the trim is gated so that it is not included if there is insufficient space
available in the bitstream. To decode the trim first set
the trim value to 5 then iff the count of decoded 8th bits so far (ec_tell_frac)
+available in the bitstream. To decode the trim, first set
+the trim value to 5, then if and only if the count of decoded 8th bits so far (ec_tell_frac)
plus 48 (6 bits) is less than or equal to the total frame size in 8th
bits minus total_boost (a product of the above band boost procedure) then
decode the trim value using the inverse CDF {127, 126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0}.
+bits minus total_boost (a product of the above band boost procedure),
+decode the trim value using the PDF in .
+
+
+PDF
+{1, 1, 2, 5, 10, 22, 46, 22, 10, 5, 2, 2}/128
+
+
+For 10 ms and 20 ms frames using short blocks and that have at least LM+2 bits left prior to
+the allocation process, then one anticollapse bit is reserved in the allocation process so it can
+be decoded later. Following the the anticollapse reservation, one bit is reserved for skip if available.
Stereo parameters
+For stereo frames, bits are reserved for intensity stereo and for dual stereo. Intensity stereo
+requires ilog2(endstart) bits. Those bits are reserved if there is enough bits left. Following this, one
+bit is reserved for dual stereo if available.
Anticollapse reservation
The allocation computation first begins by setting up some initial conditions.
'total' is set to the available remaining 8th bits, computed by taking the
size of the coded frame times 8 and subtracting ec_tell_frac(). From this value one (8th bit)
is subtracted to assure that the resulting allocation will be conservative. 'anti_collapse_rsv'
is set to 8 (8th bits) iff the frame is a transient, LM is greater than 1, and total is
+The allocation computation begins by setting up some initial conditions.
+'total' is set to the remaining available 8th bits, computed by taking the
+size of the coded frame times 8 and subtracting ec_tell_frac(). From this value, one (8th bit)
+is subtracted to ensure that the resulting allocation will be conservative. 'anti_collapse_rsv'
+is set to 8 (8th bits) if and only if the frame is a transient, LM is greater than 1, and total is
greater than or equal to (LM+2) * 8. Total is then decremented by anti_collapse_rsv and clamped
to be equal to or greater than zero. 'skip_rsv' is set to 8 (8th bits) if total is greater than
8, otherwise it is zero. Total is then decremented by skip_rsv. This reserves space for the
final skipping flag.
If the current frame is stereo intensity_rsv is set to the conservative log2 in 8th bits
of the number of coded bands for this frame (given by the table LOG2_FRAC_TABLE). If
intensity_rsv is greater than total then intensity_rsv is set to zero otherwise total is
decremented by intensity_rsv, and if total is still greater than 8 dual_stereo_rsv is
+If the current frame is stereo, intensity_rsv is set to the conservative log2 in 8th bits
+of the number of coded bands for this frame (given by the table LOG2_FRAC_TABLE in rate.c). If
+intensity_rsv is greater than total then intensity_rsv is set to zero. Otherwise total is
+decremented by intensity_rsv, and if total is still greater than 8, dual_stereo_rsv is
set to 8 and total is decremented by dual_stereo_rsv.The allocation process then computes a vector representing the hard minimum amounts allocation
any band will receive for shape. This minimum is higher than the technical limit of the PVQ
process, but very low rate allocations produce excessively an sparse spectrum and these bands
are better served by having no allocation at all. For each coded band set thresh[band] to
+process, but very low rate allocations produce an excessively sparse spectrum and these bands
+are better served by having no allocation at all. For each coded band, set thresh[band] to
twentyfour times the number of MDCT bins in the band and divide by 16. If 8 times the number
of channels is greater, use that instead. This sets the minimum allocation to one bit per channel
or 48 128th bits per MDCT bin, whichever is greater. The band size dependent part of this
value is not scaled by the channel count because at the very low rates where this limit is
+or 48 128th bits per MDCT bin, whichever is greater. The bandsize dependent part of this
+value is not scaled by the channel count, because at the very low rates where this limit is
applicable there will usually be no bits allocated to the side.The previously decoded allocation trim is used to derive a vector of perband adjustments,
'trim_offsets[]'. For each coded band take the alloc_trim and subtract 5 and LM then multiply
the result by number of channels, the number MDCT bins in the shortest frame size for this mode,
the number remaining bands, 2**LM, and 8. Then divide this value by 64. Finally, if the
number of MDCT bins in the band per channel is only one 8 times the number of channels is subtracted
in order to diminish the allocation by one bit because width 1 bands receive greater benefit
+'trim_offsets[]'. For each coded band take the alloc_trim and subtract 5 and LM. Then multiply
+the result by the number of channels, the number of MDCT bins in the shortest frame size for this mode,
+the number of remaining bands, 2**LM, and 8. Then divide this value by 64. Finally, if the
+number of MDCT bins in the band per channel is only one, 8 times the number of channels is subtracted
+in order to diminish the allocation by one bit, because width 1 bands receive greater benefit
from the coarse energy coding.

+
In each band, the normalized "shape" is encoded
using a vector quantization scheme called a "Pyramid vector quantizer".
+using a vector quantization scheme called a "pyramid vector quantizer".
In
@@ 3778,32 +5346,35 @@ This index is converted into the corresponding vector as explained in
Although the allocation is performed in 1/8th bit units, the quantization requires
an integer number of pulses K. To do this, the encoder searches for the value
of K that produces the number of bits that is the nearest to the allocated value
(rounding down if exactly halfway between two values), subject to not exceeding
the total number of bits available. For efficiency reasons the search is performed against a
+of K that produces the number of bits nearest to the allocated value
+(rounding down if exactly halfway between two values), not to exceed
+the total number of bits available. For efficiency reasons, the search is performed against a
precomputed allocation table which only permits some K values for each N. The number of
codebooks entries can be computed as explained in . The difference
+codebook entries can be computed as explained in . The difference
between the number of bits allocated and the number of bits used is accumulated to a
"balance" (initialized to zero) that helps adjusting the
+"balance" (initialized to zero) that helps adjust the
allocation for the next bands. One third of the balance is applied to the
bit allocation of the each band to help achieving the target allocation. The only
+bit allocation of each band to help achieve the target allocation. The only
exceptions are the band before the last and the last band, for which half the balance
and the whole balance are applied, respectively.

+
The codeword is decoded as a uniformlydistributed integer value
by decode_pulses() (cwrs.c).
The codeword is converted from a unique index in the same way as specified in
+Decoding of PVQ vectors is implemented in decode_pulses() (cwrs.c).
+The unique codeword index is decoded as a uniformlydistributed integer value between 0 and
+V(N,K)1, where V(N,K) is the number of possible combinations of K pulses in
+N samples. The index is then converted to a vector in the same way specified in
. The indexing is based on the calculation of V(N,K)
(denoted N(L,K) in ), which is the number of possible
combinations of K pulses
in N samples. The number of combinations can be computed recursively as
+(denoted N(L,K) in ).
+
+
+
+ The number of combinations can be computed recursively as
V(N,K) = V(N1,K) + V(N,K1) + V(N1,K1), with V(N,0) = 1 and V(0,K) = 0, K != 0.
There are many different ways to compute V(N,K), including precomputed tables and direct
+There are many different ways to compute V(N,K), including precomputed tables and direct
use of the recursive formulation. The reference implementation applies the recursive
formulation one line (or column) at a time to save on memory use,
along with an alternate,
@@ 3815,14 +5386,87 @@ they are equivalent to the mathematical definition.
The decoding of the codeword from the index is performed as specified in
, as implemented in function
decode_pulses() (cwrs.c).
+The decoded vector X is recovered as follows.
+Let i be the index decoded with the procedure in
+ with ft = V(N,K), so that 0 <= i < V(N,K).
+Let k = K.
+Then for j = 0 to (N  1), inclusive, do:
+
+Let p = (V(Nj1,k) + V(Nj,k))/2.
+
+If i < p, then let sgn = 1, else let sgn = 1
+ and set i = i  p.
+
+Let k0 = k and set p = p  V(Nj1,k).
+
+While p > i, set k = k  1 and
+ p = p  V(Nj1,k).
+
+
+Set X[j] = sgn*(k0  k) and i = i  p.
+
+
+
+
+
+The decoded vector X is then normalized such that its
+L2norm equals one.
+The normalized vector decoded in is then rotated
+for the purpose of avoiding tonal artifacts. The rotation gain is equal to
+
+
+
+
+where N is the number of dimensions, K is the number of pulses, and f_r depends on
+the value of the "spread" parameter in the bitstream.
+
+
+
+Spread value
+f_r
+ 0infinite (no rotation)
+ 115
+ 210
+ 35
+
+
+
+The rotation angle is then calculated as
+
+
+
+A 2D rotation R(i,j) between points x_i and x_j is defined as:
+
+
+
+
+An ND rotation is then achieved by applying a series of 2D rotations back and forth, in the
+following order: R(x_1, x_2), R(x_2, x_3), ..., R(x_N2, X_N1), R(x_N1, X_N),
+R(x_N2, X_N1), ..., R(x_1, x_2).
+
+
+
+If the decoded vector represents more
+than one time block, then this spreading process is applied separately on each time block.
+Also, if each block represents 8 samples or more, then another ND rotation, by
+(pi/2theta), is applied before the rotation described above. This
+extra rotation is applied in an interleaved manner with a stride equal to round(sqrt(N/nb_blocks)),
+i.e., it is applied independently for each set of sample S_k = {stride*n + k}, n=0..N/stride1.
@@ 3833,9 +5477,9 @@ the maximum size allowed for codebooks is 32 bits. When larger codebooks are
needed, the vector is instead split in two subvectors of size N/2.
A quantized gain parameter with precision
derived from the current allocation is entropy coded to represent the relative
gains of each side of the split and the entire decoding process is recursively
applied. Multiple levels of splitting may be applied up to a frame size
dependent limit. The same recursive mechanism is applied for the joint coding
+gains of each side of the split, and the entire decoding process is recursively
+applied. Multiple levels of splitting may be applied up to a limit of LM+1 splits.
+The same recursive mechanism is applied for the joint coding
of stereo audio.
@@ 3843,19 +5487,86 @@ of stereo audio.
+The timefrequency (TF) parameters are used to control the timefrequency resolution tradeoff
+in each coded band. For each band, there are two possible TF choices. For the first
+band coded, the PDF is {3, 1}/4 for frames marked as transient and {15, 1}/16 for
+the other frames. For subsequent bands, the TF choice is coded relative to the
+previous TF choice with probability {15, 1}/15 for transient frames and {31, 1}/32
+otherwise. The mapping between the decoded TF choices and the adjustment in TF
+resolution is shown in the tables below.
+
+
+
+Frame size (ms)
+0
+1
+2.501
+501
+1002
+2002
+
+
+
+Frame size (ms)
+0
+1
+2.501
+502
+1003
+2003
+
+
+
+
+Frame size (ms)
+0
+1
+2.501
+510
+1020
+2030
+
+
+
+Frame size (ms)
+0
+1
+2.501
+511
+1011
+2011
+
+
+
+A negative TF adjustment means that the temporal resolution is increased,
+while a positive TF adjustment means that the frequency resolution is increased.
+Changes in TF resolution are implemented using the Hadamard transform . To increase
+the time resolution by N, N "levels" of the Hadamard transform are applied to the
+decoded vector for each interleaved MDCT vector. To increase the frequency resolution
+(assumes a transient frame), then N levels of the Hadamard transform are applied
+across the interleaved MDCT vector. In the case of increased
+time resolution the decoder uses the "sequency order" because the input vector
+is sorted in time.

+
+The anticollapse feature is designed to avoid the situation where the use of multiple
+short MDCTs causes the energy in one or more of the MDCTs to be zero for
+some bands, causing unpleasant artifacts.
When the frame has the transient bit set, an anticollapse bit is decoded.
When anticollapse is set, then the energy in each small MDCT is prevented
+When anticollapse is set, the energy in each small MDCT is prevented
from collapsing to zero. For each band of each MDCT where a collapse is
detected, a pseudorandom signal is inserted with an energy corresponding
to the min energy over the two previous frames. A renormalization step is
+to the minimum energy over the two previous frames. A renormalization step is
then required to ensure that the anticollapse step did not alter the
energy preservation property.
@@ 3863,7 +5574,7 @@ energy preservation property.
Just like each band was normalized in the encoder, the last step of the decoder before
+Just as each band was normalized in the encoder, the last step of the decoder before
the inverse MDCT is to denormalize the bands. Each decoded normalized band is
multiplied by the square root of the decoded energy. This is done by denormalise_bands()
(bands.c).
@@ 3871,13 +5582,24 @@ multiplied by the square root of the decoded energy. This is done by denormalise
+
+
The inverse MDCT implementation has no special characteristics. The
input is N frequencydomain samples and the output is 2*N timedomain
samples, while scaling by 1/2. The output is windowed using the same window
as the encoder. The IMDCT and windowing are performed by mdct_backward
(mdct.c). If a timedomain preemphasis
window was applied in the encoder, the (inverse) timedomain deemphasis window
is applied on the IMDCT result.
+samples, while scaling by 1/2. A "lowoverlap" window reduces the algorithmic delay.
+It is derived from a basic (full overlap) 240sample version of the window used by the Vorbis codec:
+
+
+
+The lowoverlap window is created by zeropadding the basic window and inserting ones in the
+middle, such that the resulting window still satisfies power complementarity .
+The IMDCT and
+windowing are performed by mdct_backward (mdct.c).
@@ 3891,7 +5613,7 @@ between 0 and 6 of uniform probability. Once the octave is known, the fine pitch
within the octave is decoded using 4+octave raw bits. The final pitch period
is equal to (16<<octave)+fine_pitch1 so it is bounded between 15 and 1022,
inclusively. Next, the gain is decoded as three raw bits and is equal to
G=3*(int_gain+1)/32. The set of postfilter taps is decoded last using
+G=3*(int_gain+1)/32. The set of postfilter taps is decoded last, using
a pdf equal to {2, 1, 1}/4. Tapset zero corresponds to the filter coefficients
g0 = 0.3066406250, g1 = 0.2170410156, g2 = 0.1296386719. Tapset one
corresponds to the filter coefficients g0 = 0.4638671875, g1 = 0.2680664062,
@@ 3935,311 +5657,898 @@ where alpha_p=0.8500061035.
+
+
Packet loss concealment (PLC) is an optional decoderside feature which
SHOULD be included when transmitting over an unreliable channel. Because
PLC is not part of the bitstream, there are several possible ways to
implement PLC with different complexity/quality tradeoffs. The PLC in
the reference implementation finds a periodicity in the decoded
+Packet loss concealment (PLC) is an optional decoderside feature that
+SHOULD be included when receiving from an unreliable channel. Because
+PLC is not part of the bitstream, there are many acceptable ways to
+implement PLC with different complexity/quality tradeoffs.
+
+
+
+The PLC in
+the reference implementation depends on the mode of last packet received.
+In CELT mode, the PLC finds a periodicity in the decoded
signal and repeats the windowed waveform using the pitch offset. The windowed
waveform is overlapped in such a way as to preserve the timedomain aliasing
cancellation with the previous frame and the next frame. This is implemented
in celt_decode_lost() (mdct.c).
+in celt_decode_lost() (mdct.c). In SILK mode, the PLC uses LPC extrapolation
+from the previous frame, implemented in silk_PLC() (PLC.c).




+
Switching between the Opus coding modes requires careful consideration. More
specifically, the transitions that cannot be easily handled are the ones where
the lower frequencies have to switch between the SILK LPbased model and the CELT
transform model. If nothing is done, a glitch will occur for these transitions.
On the other hand, switching between the SILKonly modes and the hybrid mode
does not require any special treatment.
+Clock drift refers to the gradual desynchronization of two endpoints
+whose sample clocks run at different frequencies while they are streaming
+live audio. Differences in clock frequencies are generally attributable to
+manufacturing variation in the endpoints' clock hardware. For longlived
+streams, the time difference between sender and receiver can grow without
+bound.
There are two ways to avoid or reduce glitches during the problematic mode
transitions: with, or without side information. Only transitions with side
information are normatively specified. For transitions with no side
information, it is RECOMMENDED for the decoder to use a concealment technique
(e.g. make use of the PLC algorithm) to "fill in"
the gap or the discontinuity caused by the mode transition. Note that this
concealment MUST NOT be applied when switching between the SILK mode and the
hybrid mode or vice versa. Similarly, it MUST NOT be applied when merely
changing the bandwidth within the same mode.
+When the sender's clock runs slower than the receiver's, the effect is similar
+to packet loss: too few packets are received. The receiver can distinguish
+between drift and loss if the transport provides packet timestamps. A receiver
+for live streams SHOULD conceal the effects of drift, and MAY do so by invoking
+the PLC.

Switching with side information involves transmitting inband a 5ms
"redundant" CELT frame within the Opus frame.
This frame is designed to fillin the gap or discontinuity without requiring
the decoder to conceal it. For transitions from a CELTonly frame to a
SILKonly or hybrid frame, the redundant frame is inserted in the frame
following the transition (i.e. the SILKonly/hybrid frame). For transitions
from a SILKonly/hybrid frame to a CELTonly frame, the redundant frame is
inserted in the first frame. For all SILKonly and hybrid frames (not only
those involved in a mode transition), a binary symbol of probability 2^12
needs to be decoded just after the SILK part of the bitstream. When the
symbol value is 1, then the frame includes an embedded redundant frame. The
redundant frame always starts and ends on byte boundaries. For SILKonly
frames, the number of bytes is simply the number of whole remaining bytes.
For hybrid frames, the number of bytes is equal to 2, plus a decoded unsigned
integer (ec_dec_uint()) between 0 and 255. For hybrid frames, the redundant
frame is placed at the end of the frame, after the CELT layer of the
hybrid frame. The redundant frame is decoded like any other CELTonly frame,
with the exception that it does not contain a TOC byte. The bandwidth
is instead set to the same bandwidth of the current frame (for mediumband
frames, the redundant frame is set to wideband).
+When the sender's clock runs faster than the receiver's, too many packets will
+be received. The receiver MAY respond by skipping any packet (i.e., not
+submitting the packet for decoding). This is likely to produce a less severe
+artifact than if the frame were dropped after decoding.
For CELTonly to SILKonly/hybrid transitions, the first
2.5 ms of the redundant frame is used asis for the reconstructed
output. The remaining 2.5 ms is overlapped and added (crossfaded using
the square of the MDCT powercomplementary window) to the decoded SILK/hybrid
signal, ensuring a smooth transition. For SILKonly/hyrid to CELTonly
transitions, only the second half of the 5ms decoded redundant frame is used.
In that case, only a 2.5ms crossfade is applied, still using the
powercomplementary window.
+A decoder MAY employ a more sophisticated drift compensation method. For
+example, the
+NetEQ component
+of the
+Google WebRTC codebase
+compensates for drift by adding or removing
+one period when the signal is highly periodic. The reference implementation of
+Opus allows a caller to learn whether the current frame's signal is highly
+periodic, and if so what the period is, using the OPUS_GET_PITCH() request.






+
+
+
+Switching between the Opus coding modes, audio bandwidths, and channel counts
+ requires careful consideration to avoid audible glitches.
+Switching between any two configurations of the CELTonly mode, any two
+ configurations of the Hybrid mode, or from WB SILK to Hybrid mode does not
+ require any special treatment in the decoder, as the MDCT overlap will smooth
+ the transition.
+Switching from Hybrid mode to WB SILK requires adding in the final contents
+ of the CELT overlap buffer to the first SILKonly packet.
+This can be done by decoding a 2.5 ms silence frame with the CELT decoder
+ using the channel count of the SILKonly packet (and any choice of audio
+ bandwidth), which will correctly handle the cases when the channel count
+ changes as well.
+
+
+
+When changing the channel count for SILKonly or Hybrid packets, the encoder
+ can avoid glitches by smoothly varying the stereo width of the input signal
+ before or after the transition, and SHOULD do so.
+However, other transitions between SILKonly packets or between NB or MB SILK
+ and Hybrid packets may cause glitches, because neither the LSF coefficients
+ nor the LTP, LPC, stereo unmixing, and resampler buffers are available at the
+ new sample rate.
+These switches SHOULD be delayed by the encoder until quiet periods or
+ transients, where the inevitable glitches will be less audible. Additionally,
+ the bitstream MAY include redundant side information ("redundancy"), in the
+ form of additional CELT frames embedded in each of the Opus frames around the
+ transition.
+
+
+
+The other transitions that cannot be easily handled are those where the lower
+ frequencies switch between the SILK LPbased model and the CELT MDCT model.
+However, an encoder may not have an opportunity to delay such a switch to a
+ convenient point.
+For example, if the content switches from speech to music, and the encoder does
+ not have enough latency in its analysis to detect this in advance, there may
+ be no convenient silence period during which to make the transition for quite
+ some time.
+To avoid or reduce glitches during these problematic mode transitions, and
+ also between audio bandwidth changes in the SILKonly modes, transitions MAY
+ include redundant side information ("redundancy"), in the form of an
+ additional CELT frame embedded in the Opus frame.
+
+
+
+A transition between coding the lower frequencies with the LP model and the
+ MDCT model or a transition that involves changing the SILK bandwidth
+ is only normatively specified when it includes redundancy.
+For those without redundancy, it is RECOMMENDED that the decoder use a
+ concealment technique (e.g., make use of a PLC algorithm) to "fill in" the
+ gap or discontinuity caused by the mode transition.
+Therefore, PLC MUST NOT be applied during any normative transition, i.e., when
+
+A packet includes redundancy for this transition (as described below),
+The transition is between any WB SILK packet and any Hybrid packet, or vice
+ versa,
+The transition is between any two Hybrid mode packets, or
+The transition is between any two CELT mode packets,
+
+ unless there is actual packet loss.
+

+
Opus encoder block diagram.


 rate >encoder+
  conversion   
audio  ++ ++  ++
+ +> Range 
  ++ encoder>
   CELT  +>  bitstream
 +>encoder+ ++
  
 ++
]]>


+Transitions with side information include an extra 5 ms "redundant" CELT
+ frame within the Opus frame.
+This frame is designed to fill in the gap or discontinuity in the different
+ layers without requiring the decoder to conceal it.
+For transitions from CELTonly to SILKonly or Hybrid, the redundant frame is
+ inserted in the first Opus frame after the transition (i.e., the first
+ SILKonly or Hybrid frame).
+For transitions from SILKonly or Hybrid to CELTonly, the redundant frame is
+ inserted in the last Opus frame before the transition (i.e., the last
+ SILKonly or Hybrid frame).

+
The range coder also acts as the bitpacker for Opus. It is
used in three different ways, to encode:

entropycoded symbols with a fixed probability model using ec_encode(), (entenc.c)
integers from 0 to 2**M1 using ec_enc_uint() or ec_enc_bits(), (entenc.c)
integers from 0 to N1 (where N is not a power of two) using ec_enc_uint(). (entenc.c)

+The presence of redundancy is signaled in all SILKonly and Hybrid frames, not
+ just those involved in a mode transition.
+This allows the frames to be decoded correctly even if an adjacent frame is
+ lost.
+For SILKonly frames, this signaling is implicit, based on the size of the
+ of the Opus frame and the number of bits consumed decoding the SILK portion of
+ it.
+After decoding the SILK portion of the Opus frame, the decoder uses ec_tell()
+ (see ) to check if there are at least 17 bits
+ remaining.
+If so, then the frame contains redundancy.
The range encoder maintains an internal state vector composed of the
fourtuple (low,rng,rem,ext), representing the low end of the current
range, the size of the current range, a single buffered output octet,
and a count of additional carrypropagating output octets. Both rng
and low are 32bit unsigned integer values, rem is an octet value or
the special value 1, and ext is an integer with at least 16 bits.
This state vector is initialized at the start of each each frame to
the value (0,2**31,1,0). The reference implementation reuses the
'val' field of the entropy coder structure to hold low, in order to
allow the same structure to be used for encoding and decoding, but
we maintain the distinction here for clarity.
+For Hybrid frames, this signaling is explicit.
+After decoding the SILK portion of the Opus frame, the decoder uses ec_tell()
+ (see ) to ensure there are at least 37 bits remaining.
+If so, it reads a symbol with the PDF in
+ , and if the value is 1, then the
+ frame contains redundancy.
+Otherwise (if there were fewer than 37 bits left or the value was 0), the frame
+ does not contain redundancy.

+
+PDF
+{4095, 1}/4096
+
+
+
+
 The main encoding function is ec_encode() (entenc.c),
 which takes as an argument a threetuple (fl,fh,ft)
 describing the range of the symbol to be encoded in the current
 context, with 0 <= fl < fh <= ft <= 65535. The values of this tuple
 are derived from the probability model for the symbol. Let f(i) be
 the frequency of the i'th symbol in the current context. Then the
 threetuple corresponding to the k'th symbol is given by

+Since the current frame is a SILKonly or a Hybrid frame, it must be at least
+ 10 ms.
+Therefore, it needs an additional flag to indicate whether the redundant
+ 5 ms CELT frame should be mixed into the beginning of the current frame,
+ or the end.
+After determining that a frame contains redundancy, the decoder reads a
+ 1 bit symbol with a uniform PDF
+ ().
+
+
+PDF
+{1, 1}/2
+
+
 ec_encode() updates the state of the encoder as follows. If fl is
 greater than zero, then low = low + rng  (rng/ft)*(ftfl) and
 rng = (rng/ft)*(fhfl). Otherwise, low is unchanged and
 rng = rng  (rng/ft)*(fhfl). The divisions here are exact integer
 division. After this update, the range is normalized.
+If the value is zero, this is the first frame in the transition, and the
+ redundancy belongs at the end.
+If the value is one, this is the second frame in the transition, and the
+ redundancy belongs at the beginning.
+There is no way to specify that an Opus frame contains separate redundant CELT
+ frames at both the beginning and the end.
+
+
+
 To normalize the range, the following process is repeated until
 rng > 2**23. First, the top 9 bits of low, (low>>23), are placed into
 a carry buffer. Then, low is set to . This process is carried out by
 ec_enc_normalize() (entenc.c).
+Unlike the CELT portion of a Hybrid frame, the redundant CELT frame does not
+ use the same entropy coder state as the rest of the Opus frame, because this
+ would break the CELT bit allocation mechanism in Hybrid frames.
+Thus, a redundant CELT frame always starts and ends on a byte boundary, even in
+ SILKonly frames, where this is not strictly necessary.
+
 The 9 bits produced in each iteration of the normalization loop
 consist of 8 data bits and a carry flag. The final value of the
 output bits is not determined until carry propagation is accounted
 for. Therefore the reference implementation buffers a single
 (nonpropagating) output octet and keeps a count of additional
 propagating (0xFF) output octets. An implementation MAY choose to use
 any mathematically equivalent scheme to perform carry propagation.
+For SILKonly frames, the number of bytes in the redundant CELT frame is simply
+ the number of whole bytes remaining, which must be at least 2, due to the
+ space check in .
+For Hybrid frames, the number of bytes is equal to 2, plus a decoded unsigned
+ integer less than 256 (see ).
+This may be more than the number of whole bytes remaining in the Opus frame,
+ in which case the frame is invalid.
+However, a decoder is not required to ignore the entire frame, as this may be
+ the result of a bit error that desynchronized the range coder.
+There may still be useful data before the error, and a decoder MAY keep any
+ audio decoded so far instead of invoking the PLC, but it is RECOMMENDED that
+ the decoder stop decoding and discard the rest of the current Opus frame.
+
 The function ec_enc_carry_out() (entenc.c) performs
 this buffering. It takes a 9bit input value, c, from the normalization:
 8 bits of output and a carry bit. If c is 0xFF, then ext is incremented
 and no octets are output. Otherwise, if rem is not the special value
 1, then the octet (rem+(c>>8)) is output. Then ext octets are output
 with the value 0 if the carry bit is set, or 0xFF if it is not, and
 rem is set to the lower 8 bits of c. After this, ext is set to zero.
+It would have been possible to avoid these invalid states in the design of Opus
+ by limiting the range of the explicit length decoded from Hybrid frames by the
+ actual number of whole bytes remaining.
+However, this would require an encoder to determine the rate allocation for the
+ MDCT layer up front, before it began encoding that layer.
+By allowing some invalid sizes, the encoder is able to defer that decision
+ until much later.
+When encoding Hybrid frames which do not include redundancy, the encoder must
+ still decide upfront if it wishes to use the minimum 37 bits required to
+ trigger encoding of the redundancy flag, but this is a much looser
+ restriction.

 In the reference implementation, a special version of ec_encode()
 called ec_encode_bin() (entenc.c) is defined to
 take a twotuple (fl,ftb), where , but avoids using division.
+
+After determining the size of the redundant CELT frame, the decoder reduces
+ the size of the buffer currently in use by the range coder by that amount.
+The CELT layer read any raw bits from the end of this reduced buffer, and all
+ calculations of the number of bits remaining in the buffer must be done using
+ this new, reduced size, rather than the original size of the Opus frame.

+
 The CELT layer also allows directly encoding a series of raw bits, outside
 of the range coder, implemented in ec_enc_bits() (entenc.c).
 The raw bits are packed at the end of the packet, starting by storing the
 least significant bit of the value to be packed in the least significant bit
 of the last byte, filling up to the most significant bit in
 the last byte, and the continuing in the least significant bit of the
 penultimate byte, and so on.
 This packing may continue into the last byte output by the range coder,
 though the format should render it impossible to overwrite any set bit
 produced by the range coder when the procedure in
 is followed to finalize the stream.
+The redundant frame is decoded like any other CELTonly frame, with the
+ exception that it does not contain a TOC byte.
+The frame size is fixed at 5 ms, the channel count is set to that of the
+ current frame, and the audio bandwidth is also set to that of the current
+ frame, with the exception that for MB SILK frames, it is set to WB.


 The function ec_enc_uint() is based on ec_encode() and encodes one of N
 equiprobable symbols, each with a frequency of 1, where N may be as large as
 2**321. Because ec_encode() is limited to a total frequency of 2**161, this
 is done by encoding a series of symbols in smaller contexts.
+If the redundancy belongs at the beginning (in a CELTonly to SILKonly or
+ Hybrid transition), the final reconstructed output uses the first 2.5 ms
+ of audio output by the decoder for the redundant frame asis, discarding
+ the corresponding output from the SILKonly or Hybrid portion of the frame.
+The remaining 2.5 ms is crosslapped with the decoded SILK/Hybrid signal
+ using the CELT's powercomplementary MDCT window to ensure a smooth
+ transition.
+
 ec_enc_uint() (entenc.c) takes a twotuple (fl,ft),
 where ft is not necessarily a power of two. Let ftb be the location
 of the highest 1 bit in the two'scomplement representation of
 (ft1), or 1 if no bits are set. If ftb>8, then the top 8 bits of fl
 are encoded using ec_encode() with the threetuple
 (fl>>ftb8,(fl>>ftb8)+1,(ft1>>ftb8)+1), and the remaining bits
 are encoded as raw bits. Otherwise, fl is encoded with ec_encode() directly
 using the threetuple (fl,fl+1,ft).
+If the redundancy belongs at the end (in a SILKonly or Hybrid to CELTonly
+ transition), only the second half (2.5 ms) of the audio output by the
+ decoder for the redundant frame is used.
+In that case, the second half of the redundant frame is crosslapped with the
+ end of the SILK/Hybrid signal, again using CELT's powercomplementary MDCT
+ window to ensure a smooth transition.


 After all symbols are encoded, the stream must be finalized by
 outputting a value inside the current range. Let end be the integer
 in the interval [low,low+rng) with the largest number of trailing
 zero bits, b, such that end+(1<<b)1 is also in the interval
 [low,low+rng). Then while end is not zero, the top 9 bits of end, e.g.,
 >23), are sent to the carry buffer, and end is replaced by
 (end<<8&0x7FFFFFFF). Finally, if the value in carry buffer, rem, is]]>
 neither zero nor the special value 1, or the carry count, ext, is
 greater than zero, then 9 zero bits are sent to the carry buffer.
 After the carry buffer is finished outputting octets, the rest of the
 output buffer (if any) is padded with zero bits, until it reaches the raw
 bits. Finally, rem is set to the
 special value 1. This process is implemented by ec_enc_done()
 (entenc.c).
+
+
+
+
+When a transition occurs, the state of the SILK or the CELT decoder (or both)
+ may need to be reset before decoding a frame in the new mode.
+This avoids reusing "out of date" memory, which may not have been updated in
+ some time or may not be in a welldefined state due to, e.g., PLC.
+The SILK state is reset before every SILKonly or Hybrid frame where the
+ previous frame was CELTonly.
+The CELT state is reset every time the operating mode changes and the new mode
+ is either Hybrid or CELTonly, except when the transition uses redundancy as
+ described above.
+When switching from SILKonly or Hybrid to CELTonly with redundancy, the CELT
+ state is reset before decoding the redundant CELT frame embedded in the
+ SILKonly or Hybrid frame, but it is not reset before decoding the following
+ CELTonly frame.
+When switching from CELTonly mode to SILKonly or Hybrid mode with redundancy,
+ the CELT decoder is not reset for decoding the redundant CELT frame.

+
+
+
+ illustrates all of the normative
+ transitions involving a mode change, an audio bandwidth change, or both.
+Each one uses an S, H, or C to represent an Opus frame in the corresponding
+ mode.
+In addition, an R indicates the presence of redundancy in the Opus frame it is
+ crosslapped with.
+Its location in the first or last 5 ms is assumed to correspond to whether
+ it is the frame before or after the transition.
+Other uses of redundancy are nonnormative.
+Finally, a c indicates the contents of the CELT overlap buffer after the
+ previously decoded frame (i.e., as extracted by decoding a silence frame).
+
+ S > S
+ &
+ !R > R
+ &
+ ;S > S > S
+
+NB or MB SILK to Hybrid with Redundancy: S > S > S
+ &
+ !R >;H > H > H
+
+WB SILK to Hybrid: S > S > S >!H > H > H
+
+SILK to CELT with Redundancy: S > S > S
+ &
+ !R > C > C > C
+
+Hybrid to NB or MB SILK with Redundancy: H > H > H
+ &
+ !R > R
+ &
+ ;S > S > S
+
+Hybrid to WB SILK: H > H > H > c
+ \ +
+ > S > S > S
+
+Hybrid to CELT with Redundancy: H > H > H
+ &
+ !R > C > C > C
+
+CELT to SILK with Redundancy: C > C > C > R
+ &
+ ;S > S > S
+
+CELT to Hybrid with Redundancy: C > C > C > R
+ &
+ H > H > H
+
+Key:
+S SILKonly frame ; SILK decoder reset
+H Hybrid frame  CELT and SILK decoder resets
+C CELTonly frame ! CELT decoder reset
+c CELT overlap + Direct mixing
+R Redundant CELT frame & Windowed crosslap
+]]>
+
+The first two and the last two Opus frames in each example are illustrative,
+ i.e., there is no requirement that a stream remain in the same configuration
+ for three consecutive frames before or after a switch.
+
+
 The bit allocation routines in Opus need to be able to determine a
 conservative upper bound on the number of bits that have been used
 to encode the current frame thus far. This drives allocation
 decisions and ensures that the range coder and raw bits will not
 overflow the output buffer. This is computed in the
 reference implementation to wholebit precision by
 the function ec_tell() (entcode.h) and to fractional 1/8th bit
 precision by the function ec_tell_frac() (entcode.c).
 Like all operations in the range coder, it must be implemented in a
 bitexact manner, and must produce exactly the same value returned by
 the same functions in the decoder after decoding the same symbols.
+The behavior of transitions without redundancy where PLC is allowed is nonnormative.
+An encoder might still wish to use these transitions if, for example, it
+ doesn't want to add the extra bitrate required for redundancy or if it makes
+ a decision to switch after it has already transmitted the frame that would
+ have had to contain the redundancy.
+ illustrates the recommended
+ crosslapping and decoder resets for these transitions.
+
+ S > S ;S > S > S
+
+NB or MB SILK to Hybrid: S > S > S H > H > H
+
+SILK to CELT without Redundancy: S > S > S > P
+ &
+ !C > C > C
+
+Hybrid to NB or MB SILK: H > H > H > c
+ +
+ ;S > S > S
+
+Hybrid to CELT without Redundancy: H > H > H > P
+ &
+ !C > C > C
+
+CELT to SILK without Redundancy: C > C > C > P
+ &
+ ;S > S > S
+
+CELT to Hybrid without Redundancy: C > C > C > P
+ &
+ H > H > H
+
+Key:
+S SILKonly frame ; SILK decoder reset
+H Hybrid frame  CELT and SILK decoder resets
+C CELTonly frame ! CELT decoder reset
+c CELT overlap + Direct mixing
+P Packet Loss Concealment & Windowed crosslap
+]]>
+
+Encoders SHOULD NOT use other transitions, e.g., those that involve redundancy
+ in ways not illustrated in .
+


 In the following, we focus on the core encoder and describe its components. For simplicity, we will refer to the core encoder simply as the encoder in the remainder of this document. An overview of the encoder is given in .




  
 ++  ++  
 Voice   LTP   
 +>Activity + +>Scaling +> 
  Detector  3   Control <+ 12   
  ++   ++    
    ++    
    Gains   11   
    +>Processor+> R 
           a 
  \/   ++     n 
  ++   ++     g 
  Pitch    LSF      e 
  +>Analysis +  Quantizer> 
    4     8    E >
   ++   ++     n 14
     9/\ 10     c 
      \/     o 
   ++   ++    d 
   Noise  +>Prediction+> e 
  +>Shaping + Analysis  7    r 
   Analysis 5       
   ++   ++    
     /\     
   ++     
    \/ \/ \/ \/ \/  
  ++   ++ ++  
  HighPass     Noise   
+>Filter ++>Prefilter>Shaping > 
1   2   6 Quantization13 
 ++ ++ ++ ++
+
1: Input speech signal
2: High passed input signal
3: Voice activity estimate
4: Pitch lags (per 5 ms) and voicing decision (per 20 ms)
5: Noise shaping quantization coefficients
  Short term synthesis and analysis
 noise shaping coefficients (per 5 ms)
+
+
+
+
+
+
+
+Just like the decoder, the Opus encoder also normally consists of two main blocks: the
+SILK encoder and the CELT encoder. However, unlike the case of the decoder, a valid
+(though potentially suboptimal) Opus encoder is not required to support all modes and
+may thus only include a SILK encoder module or a CELT encoder module.
+The output bitstream of the Opus encoding contains bits from the SILK and CELT
+ encoders, though these are not separable due to the use of a range coder.
+A block diagram of the encoder is illustrated below.
+
+
+
+ Rate > Encoder  V
+ ++   Conversion    ++
+  Optional   ++ ++  Range 
+> Highpass +  Encoder >
+  Filter   ++ ++   Bit
+ ++   Delay   CELT  ++ stream
+ +> Compensation > Encoder  ^
+    +
+ ++ ++
+]]>
+
+
+
+
+
+For a normal encoder where both the SILK and the CELT modules are included, an optimal
+encoder should select which coding mode to use at runtime depending on the conditions.
+In the reference implementation, the frame size is selected by the application, but the
+other configuration parameters (number of channels, bandwidth, mode) are automatically
+selected (unless explicitly overridden by the application) depend on the following:
+
+Requested bitrate
+Input sampling rate
+Type of signal (speech vs music)
+Frame size in use
+
+
+The type of signal currently needs to be provided by the application (though it can be
+changed in realtime). An Opus encoder implementation could also do automatic detection,
+but since Opus is an interactive codec, such an implementation would likely have to either
+delay the signal (for noninteractive applications) or delay the mode switching decisions (for
+interactive applications).
+
+
+
+When the encoder is configured for voice over IP applications, the input signal is
+filtered by a highpass filter to remove the lowest part of the spectrum
+that contains little speech energy and may contain background noise. This is a second order
+Auto Regressive Moving Average (i.e., with poles and zeros) filter with a cutoff frequency around 50 Hz.
+In the future, a music detector may also be used to lower the cutoff frequency when the
+input signal is detected to be music rather than speech.
+
+
+
+
+The range coder acts as the bitpacker for Opus.
+It is used in three different ways: to encode
+
+
+Entropycoded symbols with a fixed probability model using ec_encode()
+ (entenc.c),
+
+
+Integers from 0 to (2**M  1) using ec_enc_uint() or ec_enc_bits()
+ (entenc.c),
+
+Integers from 0 to (ft  1) (where ft is not a power of two) using
+ ec_enc_uint() (entenc.c).
+
+
+
+
+
+The range encoder maintains an internal state vector composed of the fourtuple
+ (val, rng, rem, ext) representing the low end of the current
+ range, the size of the current range, a single buffered output byte, and a
+ count of additional carrypropagating output bytes.
+Both val and rng are 32bit unsigned integer values, rem is a byte value or
+ less than 255 or the special value 1, and ext is an unsigned integer with at
+ least 11 bits.
+This state vector is initialized at the start of each each frame to the value
+ (0, 2**31, 1, 0).
+After encoding a sequence of symbols, the value of rng in the encoder should
+ exactly match the value of rng in the decoder after decoding the same sequence
+ of symbols.
+This is a powerful tool for detecting errors in either an encoder or decoder
+ implementation.
+The value of val, on the other hand, represents different things in the encoder
+ and decoder, and is not expected to match.
+
+
+
+The decoder has no analog for rem and ext.
+These are used to perform carry propagation in the renormalization loop below.
+Each iteration of this loop produces 9 bits of output, consisting of 8 data
+ bits and a carry flag.
+The encoder cannot determine the final value of the output bytes until it
+ propagates these carry flags.
+Therefore the reference implementation buffers a single nonpropagating output
+ byte (i.e., one less than 255) in rem and keeps a count of additional
+ propagating (i.e., 255) output bytes in ext.
+An implementation may choose to use any mathematically equivalent scheme to
+ perform carry propagation.
+
+
+
+
+The main encoding function is ec_encode() (entenc.c), which encodes symbol k in
+ the current context using the same threetuple (fl[k], fh[k], ft)
+ as the decoder to describe the range of the symbol (see
+ ).
+
+
+ec_encode() updates the state of the encoder as follows.
+If fl[k] is greater than zero, then
+
+
+
+Otherwise, val is unchanged and
+
+
+
+The divisions here are integer division.
+
+
+
+
+After this update, the range is normalized using a procedure very similar to
+ that of , implemented by
+ ec_enc_normalize() (entenc.c).
+The following process is repeated until rng > 2**23.
+First, the top 9 bits of val, (val>>23), are sent to the carry buffer,
+ described in .
+Then, the encoder sets
+
+
+
+
+
+
+
+
+The function ec_enc_carry_out() (entenc.c) implements carry propagation and
+ output buffering.
+It takes as input a 9bit value, c, consisting of 8 data bits and an additional
+ carry bit.
+If c is equal to the value 255, then ext is simply incremented, and no other
+ state updates are performed.
+Otherwise, let b = (c>>8) be the carry bit.
+Then,
+
+
+If the buffered byte rem contains a value other than 1, the encoder outputs
+ the byte (rem + b).
+Otherwise, if rem is 1, no byte is output.
+
+
+If ext is nonzero, then the encoder outputs ext bytesall with a value of 0
+ if b is set, or 255 if b is unsetand sets ext to 0.
+
+
+rem is set to the 8 data bits:
+
+
+
+
+
+
+
+
+
+
+
+
+The reference implementation uses three additional encoding methods that are
+ exactly equivalent to the above, but make assumptions and simplifications that
+ allow for a more efficient implementation.
+
+
+
+
+The first is ec_encode_bin() (entenc.c), defined using the parameter ftb
+ instead of ft.
+It is mathematically equivalent to calling ec_encode() with
+ ft = (1<<ftb), but avoids using division.
+
+
+
+
+
+The next is ec_enc_bit_logp() (entenc.c), which encodes a single binary symbol.
+The context is described by a single parameter, logp, which is the absolute
+ value of the base2 logarithm of the probability of a "1".
+It is mathematically equivalent to calling ec_encode() with the 3tuple
+ (fl[k] = 0, fh[k] = (1<<logp)  1,
+ ft = (1<<logp)) if k is 0 and with
+ (fl[k] = (1<<logp)  1,
+ fh[k] = ft = (1<<logp)) if k is 1.
+The implementation requires no multiplications or divisions.
+
+
+
+
+
+The last is ec_enc_icdf() (entenc.c), which encodes a single binary symbol with
+ a tablebased context of up to 8 bits.
+This uses the same icdf table as ec_dec_icdf() from
+ .
+The function is mathematically equivalent to calling ec_encode() with
+ fl[k] = (1<<ftb)  icdf[k1] (or 0 if
+ k == 0), fh[k] = (1<<ftb)  icdf[k], and
+ ft = (1<<ftb).
+This only saves a few arithmetic operations over ec_encode_bin(), but allows
+ the encoder to use the same icdf tables as the decoder.
+
+
+
+
+
+
+
+The raw bits used by the CELT layer are packed at the end of the buffer using
+ ec_enc_bits() (entenc.c).
+Because the raw bits may continue into the last byte output by the range coder
+ if there is room in the loworder bits, the encoder must be prepared to merge
+ these values into a single byte.
+The procedure in does this in a way that
+ ensures both the range coded data and the raw bits can be decoded
+ successfully.
+
+
+
+
+
+The function ec_enc_uint() (entenc.c) encodes one of ft equiprobable symbols in
+ the range 0 to (ft  1), inclusive, each with a frequency of 1,
+ where ft may be as large as (2**32  1).
+Like the decoder (see ), it splits up the
+ value into a range coded symbol representing up to 8 of the high bits, and, if
+ necessary, raw bits representing the remainder of the value.
+
+
+ec_enc_uint() takes a twotuple (t, ft), where t is the value to be
+ encoded, 0 <= t < ft, and ft is not necessarily a
+ power of two.
+Let ftb = ilog(ft  1), i.e., the number of bits required
+ to store (ft  1) in two's complement notation.
+If ftb is 8 or less, then t is encoded directly using ec_encode() with the
+ threetuple (t, t + 1, ft).
+
+
+If ftb is greater than 8, then the top 8 bits of t are encoded using the
+ threetuple (t>>(ftb  8),
+ (t>>(ftb  8)) + 1,
+ ((ft  1)>>(ftb  8)) + 1), and the
+ remaining bits,
+ (t & ((1<<(ftb  8))  1),
+ are encoded as raw bits with ec_enc_bits().
+
+
+
+
+
+After all symbols are encoded, the stream must be finalized by outputting a
+ value inside the current range.
+Let end be the integer in the interval [val, val + rng) with the
+ largest number of trailing zero bits, b, such that
+ (end + (1<<b)  1) is also in the interval
+ [val, val + rng).
+This choice of end allows the maximum number of trailing bits to be set to
+ arbitrary values while still ensuring the range coded part of the buffer can
+ be decoded correctly.
+Then, while end is not zero, the top 9 bits of end, i.e., (end>>23), are
+ passed to the carry buffer in accordance with the procedure in
+ , and end is updated via
+
+
+
+Finally, if the buffered output byte, rem, is neither zero nor the special
+ value 1, or the carry count, ext, is greater than zero, then 9 zero bits are
+ sent to the carry buffer to flush it to the output buffer.
+When outputting the final byte from the range coder, if it would overlap any
+ raw bits already packed into the end of the output buffer, they should be ORed
+ into the same byte.
+The bit allocation routines in the CELT layer should ensure that this can be
+ done without corrupting the range coder data so long as end is chosen as
+ described above.
+If there is any space between the end of the range coder data and the end of
+ the raw bits, it is padded with zero bits.
+This entire process is implemented by ec_enc_done() (entenc.c).
+
+
+
+
+
+ The bit allocation routines in Opus need to be able to determine a
+ conservative upper bound on the number of bits that have been used
+ to encode the current frame thus far. This drives allocation
+ decisions and ensures that the range coder and raw bits will not
+ overflow the output buffer. This is computed in the
+ reference implementation to wholebit precision by
+ the function ec_tell() (entcode.h) and to fractional 1/8th bit
+ precision by the function ec_tell_frac() (entcode.c).
+ Like all operations in the range coder, it must be implemented in a
+ bitexact manner, and must produce exactly the same value returned by
+ the same functions in the decoder after decoding the same symbols.
+
+
+
+
+
+
+
+ In many respects the SILK encoder mirrors the SILK decoder described
+ in .
+ Details such as the quantization and range coder tables can be found
+ there, while this section describes the highlevel design choices that
+ were made.
+ The diagram below shows the basic modules of the SILK encoder.
+
+
+ Rate > Mixing > Core >
+Input Conversion    Encoder  Bitstream
+ ++ ++ ++
+]]>
+
+
+
+
+
+
+The input signal's sampling rate is adjusted by a sample rate conversion
+module so that it matches the SILK internal sampling rate.
+The input to the sample rate converter is delayed by a number of samples
+depending on the sample rate ratio, such that the overall delay is constant
+for all input and output sample rates.
+
+
+
+
+
+The stereo mixer is only used for stereo input signals.
+It converts a stereo left/right signal into an adaptive
+mid/side representation.
+The first step is to compute nonadaptive mid/side signals
+as half the sum and difference between left and right signals.
+The side signal is then minimized in energy by subtracting a
+prediction of it based on the mid signal.
+This prediction works well when the left and right signals
+exhibit linear dependency, for instance for an amplitudepanned
+input signal.
+Like in the decoder, the prediction coefficients are linearly
+interpolated during the first 8 ms of the frame.
+ The mid signal is always encoded, whereas the residual
+ side signal is only encoded if it has sufficient
+ energy compared to the mid signal's energy.
+ If it has not,
+ the "mid_only_flag" is set without encoding the side signal.
+
+
+The predictor coefficients are coded regardless of whether
+the side signal is encoded.
+For each frame, two predictor coefficients are computed, one
+that predicts between lowpassed mid and side channels, and
+one that predicts between highpassed mid and side channels.
+The lowpass filter is a simple threetap filter
+and creates a delay of one sample.
+The highpass filtered signal is the difference between
+the mid signal delayed by one sample and the lowpassed
+signal. Instead of explicitly computing the highpassed
+signal, it is computationally more efficient to transform
+the prediction coefficients before applying them to the
+filtered mid signal, as follows
+
+
+
+
+
+where w0 and w1 are the lowpass and highpass prediction
+coefficients, mid(n1) is the mid signal delayed by one sample,
+LP(n) and HP(n) are the lowpassed and highpassed
+signals and pred(n) is the prediction signal that is subtracted
+from the side signal.
+
+
+
+
+
+What follows is a description of the core encoder and its components.
+For simplicity, the core encoder is referred to simply as the encoder in
+the remainder of this section. An overview of the encoder is given in
+.
+
+
+
+ 
+ ++  ++  
+ Voice   LTP 12  
+ +>Activity + +>Scaling +> 
+  Detector 3   Control <+   
+  ++   ++    
+    ++    
+    Gains     
+    +>Processor+> R 
+      11     a 
+  \/   ++     n 
+  ++   ++     g 
+  Pitch    LSF      e 
+  +>Analysis +  Quantizer> 
+    4    8     E >
+   ++   ++     n  2
+     9/\ 10     c 
+      \/     o 
+   ++   ++     d 
+   Noise  +>Prediction+> e 
+  +>Shaping + Analysis 7     r 
+   Analysis 5         
+   ++   ++     
+     /\     
+   ++     
+    \/ \/ \/ \/ \/  
+    ++ ++  
+      Noise   
++++>Prefilter>Shaping > 
+1   6 Quantization13  
+ ++ ++ ++
+
+1: Input speech signal
+2: Range encoded bitstream
+3: Voice activity estimate
+4: Pitch lags (per 5 ms) and voicing decision (per 20 ms)
+5: Noise shaping quantization coefficients
+  Short term synthesis and analysis
+ noise shaping coefficients (per 5 ms)
 Long term synthesis and analysis noise
shaping coefficients (per 5 ms and for voiced speech only)
 Noise shaping tilt (per 5 ms)
@@ 4254,51 +6563,56 @@ fl=sum(f(i),i

 Encoder block diagram.




 The input signal is processed by a VAD (Voice Activity Detector) to produce a measure of voice activity, and also spectral tilt and signaltonoise estimates, for each frame. The VAD uses a sequence of halfband filterbanks to split the signal in four subbands: 0  Fs/16, Fs/16  Fs/8, Fs/8  Fs/4, and Fs/4  Fs/2, where Fs is the sampling frequency, that is, 8, 12, 16, or 24 kHz. The lowest subband, from 0  Fs/16 is highpass filtered with a firstorder MA (Moving Average) filter (with transfer function H(z) = 1z**(1)) to reduce the energy at the lowest frequencies. For each frame, the signal energy per subband is computed. In each subband, a noise level estimator tracks the background noise level and an SNR (SignaltoNoise Ratio) value is computed as the logarithm of the ratio of energy to noise level. Using these intermediate variables, the following parameters are calculated for use in other SILK modules:


 Average SNR. The average of the subband SNR values.



 Smoothed subband SNRs. Temporally smoothed subband SNR values.



 Speech activity level. Based on the average SNR and a weighted average of the subband energies.



 Spectral tilt. A weighted average of the subband SNRs, with positive weights for the low subbands and negative weights for the high subbands.







 The input signal is filtered by a highpass filter to remove the lowest part of the spectrum that contains little speech energy and may contain background noise. This is a second order ARMA (Auto Regressive Moving Average) filter with a cutoff frequency around 70 Hz.


 In the future, a music detector may also be used to lower the cutoff frequency when the input signal is detected to be music rather than speech.





 The highpassed input signal is processed by the open loop pitch estimator shown in .



+
+
+
+
+The input signal is processed by a Voice Activity Detector (VAD) to produce
+a measure of voice activity, spectral tilt, and signaltonoise estimates for
+each frame. The VAD uses a sequence of halfband filterbanks to split the
+signal into four subbands: 0...Fs/16, Fs/16...Fs/8, Fs/8...Fs/4, and
+Fs/4...Fs/2, where Fs is the sampling frequency (8, 12, 16, or 24 kHz).
+The lowest subband, from 0  Fs/16, is highpass filtered with a firstorder
+moving average (MA) filter (with transfer function H(z) = 1z**(1)) to
+reduce the energy at the lowest frequencies. For each frame, the signal
+energy per subband is computed.
+In each subband, a noise level estimator tracks the background noise level
+and a SignaltoNoise Ratio (SNR) value is computed as the logarithm of the
+ratio of energy to noise level.
+Using these intermediate variables, the following parameters are calculated
+for use in other SILK modules:
+
+
+Average SNR. The average of the subband SNR values.
+
+
+
+Smoothed subband SNRs. Temporally smoothed subband SNR values.
+
+
+
+Speech activity level. Based on the average SNR and a weighted average of the
+subband energies.
+
+
+
+Spectral tilt. A weighted average of the subband SNRs, with positive weights
+for the low subbands and negative weights for the high subbands.
+
+
+
+
+
+
+
+The input signal is processed by the open loop pitch estimator shown in
+.
+
+
+sampling>Correlator 
@@ 4327,49 +6641,99 @@ fl=sum(f(i),i

 Block diagram of the pitch estimator.

 The pitch analysis finds a binary voiced/unvoiced classification, and, for frames classified as voiced, four pitch lags per frame  one for each 5 ms subframe  and a pitch correlation indicating the periodicity of the signal. The input is first whitened using a Linear Prediction (LP) whitening filter, where the coefficients are computed through standard Linear Prediction Coding (LPC) analysis. The order of the whitening filter is 16 for best results, but is reduced to 12 for medium complexity and 8 for low complexity modes. The whitened signal is analyzed to find pitch lags for which the time correlation is high. The analysis consists of three stages for reducing the complexity:

 In the first stage, the whitened signal is downsampled to 4 kHz (from 8 kHz) and the current frame is correlated to a signal delayed by a range of lags, starting from a shortest lag corresponding to 500 Hz, to a longest lag corresponding to 56 Hz.


 The second stage operates on a 8 kHz signal ( downsampled from 12, 16, or 24 kHz ) and measures time correlations only near the lags corresponding to those that had sufficiently high correlations in the first stage. The resulting correlations are adjusted for a small bias towards short lags to avoid ending up with a multiple of the true pitch lag. The highest adjusted correlation is compared to a threshold depending on:


 Whether the previous frame was classified as voiced


 The speech activity level


 The spectral tilt.


 If the threshold is exceeded, the current frame is classified as voiced and the lag with the highest adjusted correlation is stored for a final pitch analysis of the highest precision in the third stage.


 The last stage operates directly on the whitened input signal to compute time correlations for each of the four subframes independently in a narrow range around the lag with highest correlation from the second stage.







 The noise shaping analysis finds gains and filter coefficients used in the prefilter and noise shaping quantizer. These parameters are chosen such that they will fulfill several requirements:

 Balancing quantization noise and bitrate. The quantization gains determine the step size between reconstruction levels of the excitation signal. Therefore, increasing the quantization gain amplifies quantization noise, but also reduces the bitrate by lowering the entropy of the quantization indices.
 Spectral shaping of the quantization noise; the noise shaping quantizer is capable of reducing quantization noise in some parts of the spectrum at the cost of increased noise in other parts without substantially changing the bitrate. By shaping the noise such that it follows the signal spectrum, it becomes less audible. In practice, best results are obtained by making the shape of the noise spectrum slightly flatter than the signal spectrum.
 Deemphasizing spectral valleys; by using different coefficients in the analysis and synthesis part of the prefilter and noise shaping quantizer, the levels of the spectral valleys can be decreased relative to the levels of the spectral peaks such as speech formants and harmonics. This reduces the entropy of the signal, which is the difference between the coded signal and the quantization noise, thus lowering the bitrate.
 Matching the levels of the decoded speech formants to the levels of the original speech formants; an adjustment gain and a first order tilt coefficient are computed to compensate for the effect of the noise shaping quantization on the level and spectral tilt.






+
+The pitch analysis finds a binary voiced/unvoiced classification, and, for
+frames classified as voiced, four pitch lags per frame  one for each
+5 ms subframe  and a pitch correlation indicating the periodicity of
+the signal.
+The input is first whitened using a Linear Prediction (LP) whitening filter,
+where the coefficients are computed through standard Linear Prediction Coding
+(LPC) analysis. The order of the whitening filter is 16 for best results, but
+is reduced to 12 for medium complexity and 8 for low complexity modes.
+The whitened signal is analyzed to find pitch lags for which the time
+correlation is high.
+The analysis consists of three stages for reducing the complexity:
+
+In the first stage, the whitened signal is downsampled to 4 kHz
+(from 8 kHz) and the current frame is correlated to a signal delayed
+by a range of lags, starting from a shortest lag corresponding to
+500 Hz, to a longest lag corresponding to 56 Hz.
+
+
+The second stage operates on an 8 kHz signal (downsampled from 12, 16,
+or 24 kHz) and measures time correlations only near the lags
+corresponding to those that had sufficiently high correlations in the first
+stage. The resulting correlations are adjusted for a small bias towards
+short lags to avoid ending up with a multiple of the true pitch lag.
+The highest adjusted correlation is compared to a threshold depending on:
+
+
+Whether the previous frame was classified as voiced
+
+
+The speech activity level
+
+
+The spectral tilt.
+
+
+If the threshold is exceeded, the current frame is classified as voiced and
+the lag with the highest adjusted correlation is stored for a final pitch
+analysis of the highest precision in the third stage.
+
+
+The last stage operates directly on the whitened input signal to compute time
+correlations for each of the four subframes independently in a narrow range
+around the lag with highest correlation from the second stage.
+
+
+
+
+
+
+
+The noise shaping analysis finds gains and filter coefficients used in the
+prefilter and noise shaping quantizer. These parameters are chosen such that
+they will fulfill several requirements:
+
+
+Balancing quantization noise and bitrate.
+The quantization gains determine the step size between reconstruction levels
+of the excitation signal. Therefore, increasing the quantization gain
+amplifies quantization noise, but also reduces the bitrate by lowering
+the entropy of the quantization indices.
+
+
+Spectral shaping of the quantization noise; the noise shaping quantizer is
+capable of reducing quantization noise in some parts of the spectrum at the
+cost of increased noise in other parts without substantially changing the
+bitrate.
+By shaping the noise such that it follows the signal spectrum, it becomes
+less audible. In practice, best results are obtained by making the shape
+of the noise spectrum slightly flatter than the signal spectrum.
+
+
+Deemphasizing spectral valleys; by using different coefficients in the
+analysis and synthesis part of the prefilter and noise shaping quantizer,
+the levels of the spectral valleys can be decreased relative to the levels
+of the spectral peaks such as speech formants and harmonics.
+This reduces the entropy of the signal, which is the difference between the
+coded signal and the quantization noise, thus lowering the bitrate.
+
+
+Matching the levels of the decoded speech formants to the levels of the
+original speech formants; an adjustment gain and a first order tilt
+coefficient are computed to compensate for the effect of the noise
+shaping quantization on the level and spectral tilt.
+
+
+
+
+
+
+

 Noise shaping and spectral deemphasis illustration.

 shows an example of an input signal spectrum (1). After deemphasis and level matching, the spectrum has deeper valleys (2). The quantization noise spectrum (3) more or less follows the input signal spectrum, while having slightly less pronounced peaks. The entropy, which provides a lower bound on the bitrate for encoding the excitation signal, is proportional to the area between the deemphasized spectrum (2) and the quantization noise spectrum (3). Without deemphasis, the entropy is proportional to the area between input spectrum (1) and quantization noise (3)  clearly higher.

+
+
+ shows an example of an
+input signal spectrum (1).
+After deemphasis and level matching, the spectrum has deeper valleys (2).
+The quantization noise spectrum (3) more or less follows the input signal
+spectrum, while having slightly less pronounced peaks.
+The entropy, which provides a lower bound on the bitrate for encoding the
+excitation signal, is proportional to the area between the deemphasized
+spectrum (2) and the quantization noise spectrum (3). Without deemphasis,
+the entropy is proportional to the area between input spectrum (1) and
+quantization noise (3)  clearly higher.
+

 The transformation from input signal to deemphasized signal can be described as a filtering operation with a filter



+The transformation from input signal to deemphasized signal can be
+described as a filtering operation with a filter
+
+
+


 having an adjustment gain G, a first order tilt adjustment filter with
 tilt coefficient c_tilt, and where



+
+
+having an adjustment gain G, a first order tilt adjustment filter with
+tilt coefficient c_tilt, and where
+
+
+


 is the analysis part of the deemphasis filter, consisting of the shortterm shaping filter with coefficients a_ana(k), and the longterm shaping filter with coefficients b_ana(k) and pitch lag L. The parameter d determines the number of longterm shaping filter taps.

+]]>
+
+
+is the analysis part of the deemphasis filter, consisting of the shortterm
+shaping filter with coefficients a_ana(k), and the longterm shaping filter
+with coefficients b_ana(k) and pitch lag L.
+The parameter d determines the number of longterm shaping filter taps.
+

 Similarly, but without the tilt adjustment, the synthesis part can be written as



+Similarly, but without the tilt adjustment, the synthesis part can be written as
+
+
+




 All noise shaping parameters are computed and applied per subframe of 5 milliseconds. First, an LPC analysis is performed on a windowed signal block of 15 milliseconds. The signal block has a lookahead of 5 milliseconds relative to the current subframe, and the window is an asymmetric sine window. The LPC analysis is done with the autocorrelation method, with an order of 16 for best quality or 12 in low complexity operation. The quantization gain is found as the squareroot of the residual energy from the LPC analysis, multiplied by a value inversely proportional to the coding quality control parameter and the pitch correlation.


 Next we find the two sets of shortterm noise shaping coefficients a_ana(k) and a_syn(k), by applying different amounts of bandwidth expansion to the coefficients found in the LPC analysis. This bandwidth expansion moves the roots of the LPC polynomial towards the origin, using the formulas



+
+
+
+All noise shaping parameters are computed and applied per subframe of 5 ms.
+First, an LPC analysis is performed on a windowed signal block of 15 ms.
+The signal block has a lookahead of 5 ms relative to the current subframe,
+and the window is an asymmetric sine window. The LPC analysis is done with the
+autocorrelation method, with an order of between 8, in lowestcomplexity mode,
+and 16, for best quality.
+
+
+Optionally the LPC analysis and noise shaping filters are warped by replacing
+the delay elements by firstorder allpass filters.
+This increases the frequency resolution at low frequencies and reduces it at
+high ones, which better matches the human auditory system and improves
+quality.
+The warped analysis and filtering comes at a cost in complexity
+and is therefore only done in higher complexity modes.
+
+
+The quantization gain is found by taking the square root of the residual energy
+from the LPC analysis and multiplying it by a value inversely proportional
+to the coding quality control parameter and the pitch correlation.
+
+
+Next the two sets of shortterm noise shaping coefficients a_ana(k) and
+a_syn(k) are obtained by applying different amounts of bandwidth expansion to the
+coefficients found in the LPC analysis.
+This bandwidth expansion moves the roots of the LPC polynomial towards the
+origin, using the formulas
+
+
+


 where a(k) is the k'th LPC coefficient and the bandwidth expansion factors g_ana and g_syn are calculated as



+
+
+where a(k) is the k'th LPC coefficient, and the bandwidth expansion factors
+g_ana and g_syn are calculated as
+
+
+


 where C is the coding quality control parameter between 0 and 1. Applying more bandwidth expansion to the analysis part than to the synthesis part gives the desired deemphasis of spectral valleys in between formants.

+g_syn = 0.95 + 0.01*C,
+]]>
+
+
+where C is the coding quality control parameter between 0 and 1.
+Applying more bandwidth expansion to the analysis part than to the synthesis
+part gives the desired deemphasis of spectral valleys in between formants.
+

 The longterm shaping is applied only during voiced frames. It uses three filter taps, described by



+The longterm shaping is applied only during voiced frames.
+It uses three filter taps, described by
+
+
+


 For unvoiced frames these coefficients are set to 0. The multiplication factors F_ana and F_syn are chosen between 0 and 1, depending on the coding quality control parameter, as well as the calculated pitch correlation and smoothed subband SNR of the lowest subband. By having F_ana less than F_syn, the pitch harmonics are emphasized relative to the valleys in between the harmonics.



 The tilt coefficient c_tilt is for unvoiced frames chosen as



+
+
+For unvoiced frames these coefficients are set to 0. The multiplication factors
+F_ana and F_syn are chosen between 0 and 1, depending on the coding quality
+control parameter, as well as the calculated pitch correlation and smoothed
+subband SNR of the lowest subband. By having F_ana less than F_syn,
+the pitch harmonics are emphasized relative to the valleys in between the
+harmonics.
+
c_tilt = 0.04 + 0.06 * C
 ]]>


 for voiced frames, where C again is the coding quality control parameter and is between 0 and 1.


 The adjustment gain G serves to correct any level mismatch between original and decoded signal that might arise from the noise shaping and deemphasis. This gain is computed as the ratio of the prediction gain of the shortterm analysis and synthesis filter coefficients. The prediction gain of an LPC synthesis filter is the squareroot of the output energy when the filter is excited by a unitenergy impulse on the input. An efficient way to compute the prediction gain is by first computing the reflection coefficients from the LPC coefficients through the stepdown algorithm, and extracting the prediction gain from the reflection coefficients as



+The tilt coefficient c_tilt is for unvoiced frames chosen as
+
+
+
+
+
+and as
+
+
+
+
+
+for voiced frames, where V is the voice activity level between 0 and 1.
+
+
+The adjustment gain G serves to correct any level mismatch between the original
+and decoded signals that might arise from the noise shaping and deemphasis.
+This gain is computed as the ratio of the prediction gain of the shortterm
+analysis and synthesis filter coefficients. The prediction gain of an LPC
+synthesis filter is the square root of the output energy when the filter is
+excited by a unitenergy impulse on the input.
+An efficient way to compute the prediction gain is by first computing the
+reflection coefficients from the LPC coefficients through the stepdown
+algorithm, and extracting the prediction gain from the reflection coefficients
+as
+
+
+


 where r_k is the k'th reflection coefficient.



 Initial values for the quantization gains are computed as the squareroot of the residual energy of the LPC analysis, adjusted by the coding quality control parameter. These quantization gains are later adjusted based on the results of the prediction analysis.





 In the prefilter the input signal is filtered using the spectral valley deemphasis filter coefficients from the noise shaping analysis, see . By applying only the noise shaping analysis filter to the input signal, it provides the input to the noise shaping quantizer.




 The prediction analysis is performed in one of two ways depending on how the pitch estimator classified the frame. The processing for voiced and unvoiced speech are described in and , respectively. Inputs to this function include the prewhitened signal from the pitch estimator, see .




 For a frame of voiced speech the pitch pulses will remain dominant in the prewhitened input signal. Further whitening is desirable as it leads to higher quality at the same available bitrate. To achieve this, a LongTerm Prediction (LTP) analysis is carried out to estimate the coefficients of a fifth order LTP filter for each of four subframes. The LTP coefficients are used to find an LTP residual signal with the simulated output signal as input to obtain better modeling of the output signal. This LTP residual signal is the input to an LPC analysis where the LPCs are estimated using Burgs method, such that the residual energy is minimized. The estimated LPCs are converted to a Line Spectral Frequency (LSF) vector, and quantized as described in . After quantization, the quantized LSF vector is converted to LPC coefficients and hence by using these quantized coefficients the encoder remains fully synchronized with the decoder. The LTP coefficients are quantized using a method described in . The quantized LPC and LTP coefficients are now used to filter the highpass filtered input signal and measure a residual energy for each of the four subframes.




 For a speech signal that has been classified as unvoiced there is no need for LTP filtering as it has already been determined that the prewhitened input signal is not periodic enough within the allowed pitch period range for an LTP analysis to be worthwhile the cost in terms of complexity and rate. Therefore, the prewhitened input signal is discarded and instead the highpass filtered input signal is used for LPC analysis using Burgs method. The resulting LPC coefficients are converted to an LSF vector, quantized as described in the following section and transformed back to obtain quantized LPC coefficients. The quantized LPC coefficients are used to filter the highpass filtered input signal and measure a residual energy for each of the four subframes.





 The purpose of quantization in general is to significantly lower the bit rate at the cost of some introduced distortion. A higher rate should always result in lower distortion, and lowering the rate will generally lead to higher distortion. A commonly used but generally suboptimal approach is to use a quantization method with a constant rate where only the error is minimized when quantizing.

 Instead, we minimize an objective function that consists of a weighted sum of rate and distortion, and use a codebook with an associated nonuniform rate table. Thus, we take into account that the probability mass function for selecting the codebook entries are by no means guaranteed to be uniform in our scenario. The advantage of this approach is that it ensures that rarely used codebook vector centroids, which are modeling statistical outliers in the training set can be quantized with a low error but with a relatively high cost in terms of a high rate. At the same time this approach also provides the advantage that frequently used centroids are modeled with low error and a relatively low rate. This approach will lead to equal or lower distortion than the fixed rate codebook at any given average rate, provided that the data is similar to the data used for training the codebook.




 Instead of minimizing the error in the LSF domain, we map the errors to better approximate spectral distortion by applying an individual weight to each element in the error vector. The weight vectors are calculated for each input vector using the Inverse Harmonic Mean Weighting (IHMW) function proposed by Laroia et al., see .
 Consequently, we solve the following minimization problem, i.e.,





 where LSF_q is the quantized vector, LSF is the input vector to be quantized, and c is the quantized LSF vector candidate taken from the set C of all possible outcomes of the codebook.




 We arrange the codebook in a multiple stage structure to achieve a quantizer that is both memory efficient and highly scalable in terms of computational complexity, see e.g. . In the first stage the input is the LSF vector to be quantized, and in any other stage s > 1, the input is the quantization error from the previous stage, see .



  c_{1,2} > c_{2,2} > ... > c_{S,2} >
 ++ ++ ++ res_S =
 ... ... ... LSFLSF_q
 ++ ++ ++
 c_{1,M11} c_{2,M21} c_{S,MS1}
 ++ ++ ++
  c_{1,M1}   c_{2,M2}   c_{S,MS} 
 ++ ++ ++
]]>

 MultiStage LSF Vector Codebook Structure.



 By storing total of M codebook vectors, i.e.,





 where M_s is the number of vectors in stage s, we obtain a total of





 possible combinations for generating the quantized vector. It is for example possible to represent 2**36 uniquely combined vectors using only 216 vectors in memory, as done in SILK for voiced speech at all sample frequencies above 8 kHz.




 This number of possible combinations is far too high for a full search to be carried out for each frame so for all stages but the last, i.e., s smaller than S, only the best min( L, Ms ) centroids are carried over to stage s+1. In each stage the objective function, i.e., the weighted sum of accumulated bitrate and distortion, is evaluated for each codebook vector entry and the results are sorted. Only the best paths and the corresponding quantization errors are considered in the next stage. In the last stage S the single best path through the multistage codebook is determined. By varying the maximum number of survivors from each stage to the next L, the complexity can be adjusted in realtime at the cost of a potential increase when evaluating the objective function for the resulting quantized vector. This approach scales all the way between the two extremes, L=1 being a greedy search, and the desirable but infeasible full search, L=T/MS. In fact, a performance almost as good as what can be achieved with the infeasible full search can be obtained at a substantially lower complexity by using this approach, see e.g. .



 If the input is stable, finding the best candidate will usually result in the quantized vector also being stable, but due to the multistage approach it could in theory happen that the best quantization candidate is unstable and because of this there is a need to explicitly ensure that the quantized vectors are stable. Therefore we apply a LSF stabilization method which ensures that the LSF parameters are within valid range, increasingly sorted, and have minimum distances between each other and the border values that have been predetermined as the 0.01 percentile distance values from a large training set.



 The vectors and rate tables for the multistage codebook have been trained by minimizing the average of the objective function for LSF vectors from a large training set.






 For voiced frames, the prediction analysis described in resulted in four sets (one set per subframe) of five LTP coefficients, plus four weighting matrices. Also, the LTP coefficients for each subframe are quantized using entropy constrained vector quantization. A total of three vector codebooks are available for quantization, with different ratedistortion tradeoffs. The three codebooks have 10, 20 and 40 vectors and average rates of about 3, 4, and 5 bits per vector, respectively. Consequently, the first codebook has larger average quantization distortion at a lower rate, whereas the last codebook has smaller average quantization distortion at a higher rate. Given the weighting matrix W_ltp and LTP vector b, the weighted ratedistortion measure for a codebook vector cb_i with rate r_i is give by





 where u is a fixed, heuristicallydetermined parameter balancing the distortion and rate. Which codebook gives the best performance for a given LTP vector depends on the weighting matrix for that LTP vector. For example, for a low valued W_ltp, it is advantageous to use the codebook with 10 vectors as it has a lower average rate. For a large W_ltp, on the other hand, it is often better to use the codebook with 40 vectors, as it is more likely to contain the best codebook vector.
 The weighting matrix W_ltp depends mostly on two aspects of the input signal. The first is the periodicity of the signal; the more periodic the larger W_ltp. The second is the change in signal energy in the current subframe, relative to the signal one pitch lag earlier. A decaying energy leads to a larger W_ltp than an increasing energy. Both aspects do not fluctuate very fast which causes the W_ltp matrices for different subframes of one frame often to be similar. As a result, one of the three codebooks typically gives good performance for all subframes. Therefore the codebook search for the subframe LTP vectors is constrained to only allow codebook vectors to be chosen from the same codebook, resulting in a rate reduction.



 To find the best codebook, each of the three vector codebooks is used to quantize all subframe LTP vectors and produce a combined weighted ratedistortion measure for each vector codebook and the vector codebook with the lowest combined ratedistortion over all subframes is chosen. The quantized LTP vectors are used in the noise shaping quantizer, and the index of the codebook plus the four indices for the four subframe codebook vectors are passed on to the range encoder.






 The noise shaping quantizer independently shapes the signal and coding noise spectra to obtain a perceptually higher quality at the same bitrate.


 The prefilter output signal is multiplied with a compensation gain G computed in the noise shaping analysis. Then the output of a synthesis shaping filter is added, and the output of a prediction filter is subtracted to create a residual signal. The residual signal is multiplied by the inverse quantized quantization gain from the noise shaping analysis, and input to a scalar quantizer. The quantization indices of the scalar quantizer represent a signal of pulses that is input to the pyramid range encoder. The scalar quantizer also outputs a quantization signal, which is multiplied by the quantized quantization gain from the noise shaping analysis to create an excitation signal. The output of the prediction filter is added to the excitation signal to form the quantized output signal y(n). The quantized output signal y(n) is input to the synthesis shaping and prediction filters.

+
+
+where r_k is the k'th reflection coefficient.
+

+
+Initial values for the quantization gains are computed as the squareroot of
+the residual energy of the LPC analysis, adjusted by the coding quality control
+parameter.
+These quantization gains are later adjusted based on the results of the
+prediction analysis.
+
+


 Range encoding is a well known method for entropy coding in which a bitstream sequence is continually updated with every new symbol, based on the probability for that symbol. It is similar to arithmetic coding but rather than being restricted to generating binary output symbols, it can generate symbols in any chosen number base. In SILK all side information is range encoded. Each quantized parameter has its own cumulative density function based on histograms for the quantization indices obtained by running a training database.

+
+
+The prediction analysis is performed in one of two ways depending on how
+the pitch estimator classified the frame.
+The processing for voiced and unvoiced speech is described in
+ and
+ , respectively.
+ Inputs to this function include the prewhitened signal from the
+ pitch estimator (see ).
+
+
+
+
+ For a frame of voiced speech the pitch pulses will remain dominant in the
+ prewhitened input signal.
+ Further whitening is desirable as it leads to higher quality at the same
+ available bitrate.
+ To achieve this, a LongTerm Prediction (LTP) analysis is carried out to
+ estimate the coefficients of a fifthorder LTP filter for each of four
+ subframes.
+ The LTP coefficients are quantized using the method described in
+ , and the quantized LTP
+ coefficients are used to compute the LTP residual signal.
+ This LTP residual signal is the input to an LPC analysis where the LPC coefficients are
+ estimated using Burg's method , such that the residual energy is minimized.
+ The estimated LPC coefficients are converted to a Line Spectral Frequency (LSF) vector
+ and quantized as described in .
+After quantization, the quantized LSF vector is converted back to LPC
+coefficients using the full procedure in .
+By using quantized LTP coefficients and LPC coefficients derived from the
+quantized LSF coefficients, the encoder remains fully synchronized with the
+decoder.
+The quantized LPC and LTP coefficients are also used to filter the input
+signal and measure residual energy for each of the four subframes.
+
+
+
+
+For a speech signal that has been classified as unvoiced, there is no need
+for LTP filtering, as it has already been determined that the prewhitened
+input signal is not periodic enough within the allowed pitch period range
+for LTP analysis to be worth the cost in terms of complexity and bitrate.
+The prewhitened input signal is therefore discarded, and instead the input
+signal is used for LPC analysis using Burg's method.
+The resulting LPC coefficients are converted to an LSF vector and quantized
+as described in the following section.
+They are then transformed back to obtain quantized LPC coefficients, which
+are then used to filter the input signal and measure residual energy for
+each of the four subframes.
+
+
+
+The main purpose of linear prediction in SILK is to reduce the bitrate by
+minimizing the residual energy.
+At least at high bitrates, perceptual aspects are handled
+independently by the noise shaping filter.
+Burg's method is used because it provides higher prediction gain
+than the autocorrelation method and, unlike the covariance method,
+produces stable filters (assuming numerical errors don't spoil
+that). SILK's implementation of Burg's method is also computationally
+faster than the autocovariance method.
+The implementation of Burg's method differs from traditional
+implementations in two aspects.
+The first difference is that it
+operates on autocorrelations, similar to the Schur algorithm , but
+with a simple update to the autocorrelations after finding each
+reflection coefficient to make the result identical to Burg's method.
+This brings down the complexity of Burg's method to near that of
+the autocorrelation method.
+The second difference is that the signal in each subframe is scaled
+by the inverse of the residual quantization step size. Subframes with
+a small quantization step size will on average spend more bits for a
+given amount of residual energy than subframes with a large step size.
+Without scaling, Burg's method minimizes the total residual energy in
+all subframes, which doesn't necessarily minimize the total number of
+bits needed for coding the quantized residual. The residual energy
+of the scaled subframes is a better measure for that number of
+bits.
+
+
+
+


 TBD.




+
+
+Unlike many other speech codecs, SILK uses variable bitrate coding
+for the LSFs.
+This improves the average ratedistortion (RD) tradeoff and reduces outliers.
+The variable bitrate coding minimizes a linear combination of the weighted
+quantization errors and the bitrate.
+The weights for the quantization errors are the Inverse
+Harmonic Mean Weighting (IHMW) function proposed by Laroia et al.
+(see ).
+These weights are referred to here as Laroia weights.
+
+
+The LSF quantizer consists of two stages.
+The first stage is an (unweighted) vector quantizer (VQ), with a
+codebook size of 32 vectors.
+The quantization errors for the codebook vector are sorted, and
+for the N best vectors a second stage quantizer is run.
+By varying the number N a tradeoff is made between RD performance
+and computational efficiency.
+For each of the N codebook vectors the Laroia weights corresponding
+to that vector (and not to the input vector) are calculated.
+Then the residual between the input LSF vector and the codebook
+vector is scaled by the square roots of these Laroia weights.
+This scaling partially normalizes error sensitivity for the
+residual vector, so that a uniform quantizer with fixed
+step sizes can be used in the second stage without too much
+performance loss.
+And by scaling with Laroia weights determined from the firststage
+codebook vector, the process can be reversed in the decoder.
+
+
+The second stage uses predictive delayed decision scalar
+quantization.
+The quantization error is weighted by Laroia weights determined
+from the LSF input vector.
+The predictor multiplies the previous quantized residual value
+by a prediction coefficient that depends on the vector index from the
+first stage VQ and on the location in the LSF vector.
+The prediction is subtracted from the LSF residual value before
+quantizing the result, and added back afterwards.
+This subtraction can be interpreted as shifting the quantization levels
+of the scalar quantizer, and as a result the quantization error of
+each value depends on the quantization decision of the previous value.
+This dependency is exploited by the delayed decision mechanism to
+search for a quantization sequency with best RD performance
+with a Viterbilike algorithm .
+The quantizer processes the residual LSF vector in reverse order
+(i.e., it starts with the highest residual LSF value).
+This is done because the prediction works slightly
+better in the reverse direction.
+
+
+The quantization index of the first stage is entropy coded.
+The quantization sequence from the second stage is also entropy
+coded, where for each element the probability table is chosen
+depending on the vector index from the first stage and the location
+of that element in the LSF vector.
+
+
+
+
+If the input is stable, finding the best candidate usually results in a
+quantized vector that is also stable. Because of the twostage approach,
+however, it is possible that the best quantization candidate is unstable.
+The encoder applies the same stabilization procedure applied by the decoder
+ (see to ensure the LSF parameters
+ are within their valid range, increasingly sorted, and have minimum
+ distances between each other and the border values.
+
+
+
+
+
+For voiced frames, the prediction analysis described in
+ resulted in four sets
+(one set per subframe) of five LTP coefficients, plus four weighting matrices.
+The LTP coefficients for each subframe are quantized using entropy constrained
+vector quantization.
+A total of three vector codebooks are available for quantization, with
+different ratedistortion tradeoffs. The three codebooks have 10, 20, and
+40 vectors and average rates of about 3, 4, and 5 bits per vector, respectively.
+Consequently, the first codebook has larger average quantization distortion at
+a lower rate, whereas the last codebook has smaller average quantization
+distortion at a higher rate.
+Given the weighting matrix W_ltp and LTP vector b, the weighted ratedistortion
+measure for a codebook vector cb_i with rate r_i is give by
+
+
+
+
+
+where u is a fixed, heuristicallydetermined parameter balancing the distortion
+and rate.
+Which codebook gives the best performance for a given LTP vector depends on the
+weighting matrix for that LTP vector.
+For example, for a low valued W_ltp, it is advantageous to use the codebook
+with 10 vectors as it has a lower average rate.
+For a large W_ltp, on the other hand, it is often better to use the codebook
+with 40 vectors, as it is more likely to contain the best codebook vector.
+The weighting matrix W_ltp depends mostly on two aspects of the input signal.
+The first is the periodicity of the signal; the more periodic, the larger W_ltp.
+The second is the change in signal energy in the current subframe, relative to
+the signal one pitch lag earlier.
+A decaying energy leads to a larger W_ltp than an increasing energy.
+Both aspects fluctuate relatively slowly, which causes the W_ltp matrices for
+different subframes of one frame often to be similar.
+Because of this, one of the three codebooks typically gives good performance
+for all subframes, and therefore the codebook search for the subframe LTP
+vectors is constrained to only allow codebook vectors to be chosen from the
+same codebook, resulting in a rate reduction.
+
+
+
+To find the best codebook, each of the three vector codebooks is
+used to quantize all subframe LTP vectors and produce a combined
+weighted ratedistortion measure for each vector codebook.
+The vector codebook with the lowest combined ratedistortion
+over all subframes is chosen. The quantized LTP vectors are used
+in the noise shaping quantizer, and the index of the codebook
+plus the four indices for the four subframe codebook vectors
+are passed on to the range encoder.
+
+

+
Copy from CELT draft.
+In the prefilter the input signal is filtered using the spectral valley
+deemphasis filter coefficients from the noise shaping analysis
+(see ).
+By applying only the noise shaping analysis filter to the input signal,
+it provides the input to the noise shaping quantizer.
+

+
+
+The noise shaping quantizer independently shapes the signal and coding noise
+spectra to obtain a perceptually higher quality at the same bitrate.
+
Inverse of the postfilter
+The prefilter output signal is multiplied with a compensation gain G computed
+in the noise shaping analysis. Then the output of a synthesis shaping filter
+is added, and the output of a prediction filter is subtracted to create a
+residual signal.
+The residual signal is multiplied by the inverse quantized quantization gain
+from the noise shaping analysis, and input to a scalar quantizer.
+The quantization indices of the scalar quantizer represent a signal of pulses
+that is input to the pyramid range encoder.
+The scalar quantizer also outputs a quantization signal, which is multiplied
+by the quantized quantization gain from the noise shaping analysis to create
+an excitation signal.
+The output of the prediction filter is added to the excitation signal to form
+the quantized output signal y(n).
+The quantized output signal y(n) is input to the synthesis shaping and
+prediction filters.
+
+
+Optionally the noise shaping quantizer operates in a delayed decision
+mode.
+In this mode it uses a Viterbi algorithm to keep track of
+multiple rounding choices in the quantizer and select the best
+one after a delay of 32 samples. This improves the rate/distortion
+performance of the quantizer.
+
+
+ SILK was designed to run in Variable Bitrate (VBR) mode. However
+ the reference implementation also has a Constant Bitrate (CBR) mode
+ for SILK. In CBR mode SILK will attempt to encode each packet with
+ no more than the allowed number of bits. The Opus wrapper code
+ then pads the bitstream if any unused bits are left in SILK mode, or
+ encodes the high band with the remaining number of bits in Hybrid mode.
+ The number of payload bits is adjusted by changing
+ the quantization gains and the rate/distortion tradeoff in the noise
+ shaping quantizer, in an iterative loop
+ around the noise shaping quantizer and entropy coding.
+ Compared to the SILK VBR mode, the CBR mode has lower
+ audio quality at a given average bitrate, and also has higher
+ computational complexity.
+
+

+
The MDCT implementation has no special characteristics. The
input is a windowed signal (after preemphasis) of 2*N samples and the output is N
frequencydomain samples. A "lowoverlap" window is used to reduce the algorithmic delay.
It is derived from a basic (full overlap) window that is the same as the one used in the Vorbis codec:



The lowoverlap window is created by zeropadding the basic window and inserting ones in the middle, such that the resulting window still satisfies power complementarity. The MDCT is computed in mdct_forward() (mdct.c), which includes the windowing operation and a scaling of 2/N.
+
+
+
+
+
+Most of the aspects of the CELT encoder can be directly derived from the description
+of the decoder. For example, the filters and rotations in the encoder are simply the
+inverse of the operation performed by the decoder. Similarly, the quantizers generally
+optimize for the mean square error (because noise shaping is part of the bitstream itself),
+so no special search is required. For this reason, only the less straightforward aspects of the
+encoder are described here.
+
+
+
+The pitch prefilter is applied after the preemphasis. It is applied
+in such a way as to be the inverse of the decoder's postfilter. The main nonobvious aspect of the
+prefilter is the selection of the pitch period. The pitch search should be optimized for the
+following criteria:
+
+continuity: it is important that the pitch period
+does not change abruptly between frames; and
+avoidance of pitch multiples: when the period used is a multiple of the real period
+(lower frequency fundamental), the postfilter loses most of its ability to reduce noise
+
@@ 4699,7 +7244,7 @@ The lowoverlap window is created by zeropadding the basic window and inserting
The MDCT output is divided into bands that are designed to match the ear's critical
bands for the smallest (2.5 ms) frame size. The larger frame sizes use integer
multiplies of the 2.5 ms layout. For each band, the encoder
+multiples of the 2.5 ms layout. For each band, the encoder
computes the energy that will later be encoded. Each band is then normalized by the
square root of the unquantized energy, such that each band now forms a unit vector X.
The energy and the normalization are computed by compute_band_energies()
@@ 4709,81 +7254,130 @@ and normalise_bands() (bands.c), respectively.

It is important to quantize the energy with sufficient resolution because
any energy quantization error cannot be compensated for at a later
stage. Regardless of the resolution used for encoding the shape of a band,
it is perceptually important to preserve the energy in each band. CELT uses a
coarsefine strategy for encoding the energy in the base2 log domain,
as implemented in quant_bands.c
+
+Energy quantization (both coarse and fine) can be easily understood from the decoding process.
+For all useful bitrates, the coarse quantizer always chooses the quantized log energy value that
+minimizes the error for each band. Only at very low rate does the encoder allow larger errors to
+minimize the rate and avoid using more bits than are available. When the
+available CPU requirements allow it, it is best to try encoding the coarse energy both with and without
+interframe prediction such that the best prediction mode can be selected. The optimal mode depends on
+the coding rate, the available bitrate, and the current rate of packet loss.
+
+
+The fine energy quantizer always chooses the quantized log energy value that
+minimizes the error for each band because the rate of the fine quantization depends only
+on the bit allocation and not on the values that are coded.
+
+
+
+
+The encoder must use exactly the same bit allocation process as used by the decoder
+and described in . The three mechanisms that can be used by the
+encoder to adjust the bitrate on a framebyframe basis are band boost, allocation trim,
+and band skipping.
+
+
+
+The reference encoder makes a decision to boost a band when the energy of that band is significantly
+higher than that of the neighboring bands. Let E_j be the logenergy of band j, we define
+
+D_j = 2*E_j  E_j1  E_j+1
+
+
+The allocation of band j is boosted once if D_j > t1 and twice if D_j > t2. For LM>=1, t1=2 and t2=4,
+while for LM<1, t1=3 and t2=5.
+
+
+
+
+
+The allocation trim is a value between 0 and 10 (inclusively) that controls the allocation
+balance between the low and high frequencies. The encoder starts with a safe "default" of 5
+and deviates from that default in two different ways. First the trim can deviate by +/ 2
+depending on the spectral tilt of the input signal. For signals with more low frequencies, the
+trim is increased by up to 2, while for signals with more high frequencies, the trim is
+decreased by up to 2.
+For stereo inputs, the trim value can
+be decreased by up to 4 when the interchannel correlation at low frequency (first 8 bands)
+is high.
+
+
+
+The encoder uses band skipping to ensure that the shape of the bands is only coded
+if there is at least 1/2 bit per sample available for the PVQ. If not, then no bit is allocated
+and folding is used instead. To ensure continuity in the allocation, some amount of hysteresis is
+added to the process, such that a band that received PVQ bits in the previous frame only needs 7/16
+bit/sample to be coded for the current frame, while a band that did not receive PVQ bits in the
+previous frames needs at least 9/16 bit/sample to be coded.
+
+
+


The coarse quantization of the energy uses a fixed resolution of 6 dB.
To minimize the bitrate, prediction is applied both in time (using the previous frame)
and in frequency (using the previous bands). The prediction using the
previous frame can be disabled, creating an "intra" frame where the energy
is coded without reference to prior frames. An encoder is able to choose the
mode used at will based on both loss robustness and efficiency
considerations.
The 2D ztransform of
the prediction filter is:
+
+Because CELT applies midside stereo coupling in the normalized domain, it does not suffer from
+important stereo image problems even when the two channels are completely uncorrelated. For this reason
+it is always safe to use stereo coupling on any audio frame. That being said, there are some frames
+for which dual (independent) stereo is still more efficient. This decision is made by comparing the estimated
+entropy with and without coupling over the first 13 bands, taking into account the fact that all bands with
+more than two MDCT bins require one extra degree of freedom when coded in midside. Let L1_ms and L1_lr
+be the L1norm of the midside vector and the L1norm of the leftright vector, respectively. The decision
+to use midside is made if and only if
where b is the band index and l is the frame index. The prediction coefficients
applied depend on the frame size in use when not using intra energy and are alpha=0, beta=4915/32768
when using intra energy.
The timedomain prediction is based on the final fine quantization of the previous
frame, while the frequency domain (within the current frame) prediction is based
on coarse quantization only (because the fine quantization has not been computed
yet). The prediction is clamped internally so that fixed point implementations with
limited dynamic range do not suffer desynchronization. Identical prediction
clamping must be implemented in all encoders and decoders.
We approximate the ideal
probability distribution of the prediction error using a Laplace distribution
with separate parameters for each frame size in intra and interframe modes. The
coarse energy quantization is performed by quant_coarse_energy() and
quant_coarse_energy() (quant_bands.c). The encoding of the Laplacedistributed values is
implemented in ec_laplace_encode() (laplace.c).

+where bins is the number of MDCT bins in the first 13 bands and E is the number of extra degrees of
+freedom for midside coding. For LM>1, E=13, otherwise E=5.
+
+
+The reference encoder decides on the intensity stereo threshold based on the bitrate alone. After
+taking into account the frame size by subtracting 80 bits per frame for coarse energy, the first
+band using intensity coding is as follows:
+
+
+
+bitrate (kb/s)
+start band
+<358
+355012
+506816
+848418
+8410219
+10213020
+>130disabled
+
+


+

+
After the coarse energy quantization and encoding, the bit allocation is computed
() and the number of bits to use for refining the
energy quantization is determined for each band. Let B_i be the number of fine energy bits
for band i; the refinement is an integer f in the range [0,2**B_i1]. The mapping between f
and the correction applied to the coarse energy is equal to (f+1/2)/2**B_i  1/2. Fine
energy quantization is implemented in quant_fine_energy()
(quant_bands.c).
+The choice of timefrequency resolution used in is based on
+RD optimization. The distortion is the L1norm (sum of absolute values) of each band
+after each TF resolution under consideration. The L1 norm is used because it represents the entropy
+for a Laplacian source. The number of bits required to code a change in TF resolution between
+two bands is higher than the cost of having those two bands use the same resolution, which is
+what requires the RD optimization. The optimal decision is computed using the Viterbi algorithm.
+See tf_analysis() in celt/celt.c.
+
+
If any bits are unused at the end of the encoding process, these bits are used to
increase the resolution of the fine energy encoding in some bands. Priority is given
to the bands for which the allocation () was rounded
down. At the same level of priority, lower bands are encoded first. Refinement bits
are added until there is no more room for fine energy or until each band
has gained an additional bit of precision or has the maximum fine
energy precision. This is implemented in quant_energy_finalise()
(quant_bands.c).
+The choice of the spreading value in has an
+impact on the nature of the coding noise introduced by CELT. The larger the f_r value, the
+lower the impact of the rotation, and the more tonal the coding noise. The
+more tonal the signal, the more tonal the noise should be, so the CELT encoder determines
+the optimal value for f_r by estimating how tonal the signal is. The tonality estimate
+is based on discrete pdf (4bin histogram) of each band. Bands that have a large number of small
+values are considered more tonal and a decision is made by combining all bands with more than
+8 samples. See spreading_decision() in celt/bands.c.






+CELT uses a Pyramid Vector Quantization (PVQ)
@@ 4795,7 +7389,7 @@ all integer codevectors y of N dimensions that satisfy sum(abs(y(j))) = K.
In bands where there are sufficient bits allocated the PVQ is used to encode
+In bands where there are sufficient bits allocated PVQ is used to encode
the unit vector that results from the normalization in
directly. Given a PVQ codevector y,
the unit vector X is obtained as X = y/y, where . denotes the
@@ 4808,23 +7402,23 @@ L2 norm.
The search for the best codevector y is performed by alg_quant()
(vq.c). There are several possible approaches to the
search with a tradeoff between quality and complexity. The method used in the reference
implementation computes an initial codeword y1 by projecting the residual signal
R = X  p' onto the codebook pyramid of K1 pulses:
+search, with a tradeoff between quality and complexity. The method used in the reference
+implementation computes an initial codeword y1 by projecting the normalized spectrum
+X onto the codebook pyramid of K1 pulses:
y0 = round_towards_zero( (K1) * R / sum(abs(R)))
+y0 = truncate_towards_zero( (K1) * X / sum(abs(X)))
Depending on N, K and the input data, the initial codeword y0 may contain from
0 to K1 nonzero values. All the remaining pulses, with the exception of the last one,
are found iteratively with a greedy search that minimizes the normalized correlation
between y and R:
+between y and X:
@@ 4832,72 +7426,53 @@ J = R * y / y
The search described above is considered to be a good tradeoff between quality
and computational cost. However, there are other possible ways to search the PVQ
codebook and the implementers MAY use any other search methods.
+codebook and the implementers MAY use any other search methods. See alg_quant() in celt/vq.c.
+

The best PVQ codeword is encoded as a uniformlydistributed integer value
by encode_pulses() (cwrs.c).
The codeword is converted from a unique index in the same way as specified in
. The indexing is based on the calculation of V(N,K)
(denoted N(L,K) in ), which is the number of possible
combinations of K pulses in N samples.








+The vector to encode, X, is converted into an index i such that
+ 0 <= i < V(N,K) as follows.
+Let i = 0 and k = 0.
+Then for j = (N  1) down to 0, inclusive, do:
+
When encoding a stereo stream, some parameters are shared across the left and right channels, while others are transmitted separately for each channel, or jointly encoded. Only one copy of the flags for the features, transients and pitch (pitch
period and filter parameters) are transmitted. The coarse and fine energy parameters are transmitted separately for each channel. Both the coarse energy and fine energy (including the remaining fine bits at the end of the stream) have the left and right bands interleaved in the stream, with the left band encoded first.
+If k > 0, set
+ i = i + (V(Nj1,k1) + V(Nj,k1))/2.

+Set k = k + abs(X[j]).
The main difference between mono and stereo coding is the PVQ coding of the normalized vectors. In stereo mode, a normalized midside (MS) encoding is used. Let L and R be the normalized vector of a certain band for the left and right channels, respectively. The mid and side vectors are computed as M=L+R and S=LR and no longer have unit norm.
+If X[j] < 0, set
+ i = i + (V(Nj1,k) + V(Nj,k))/2.


From M and S, an angular parameter theta=2/pi*atan2(S, M) is computed. The theta parameter is converted to a Q14 fixedpoint parameter itheta, which is quantized on a scale from 0 to 1 with an interval of 2**(qb), where qb is
based the number of bits allocated to the band. From here on, the value of itheta MUST be treated in a bitexact manner since both the encoder and decoder rely on it to infer the bit allocation.
+
+
Let m=M/M and s=S/S; m and s are separately encoded with the PVQ encoder described in . The number of bits allocated to m and s depends on the value of itheta.
+The index i is then encoded using the procedure in
+ with ft = V(N,K).



After all the quantization is completed, the quantized energy is used along with the
quantized normalized band data to resynthesize the MDCT spectrum. The inverse MDCT () and the weighted overlapadd are applied and the signal is stored in the "synthesis
buffer".
The encoder MAY omit this step of the processing if it does not need the decoded output.



Each CELT frame can be encoded in a different number of octets, making it possible to vary the bitrate at will. This property can be used to implement sourcecontrolled variable bitrate (VBR). Support for VBR is OPTIONAL for the encoder, but a decoder MUST be prepared to decode a stream that changes its bitrate dynamically. The method used to vary the bitrate in VBR mode is left to the implementer, as long as each frame can be decoded by the reference decoder.


+
+
+

+
It is the intention to allow the greatest possible choice of freedom in
implementing the specification. For this reason, outside of a few exceptions
+It is our intention to allow the greatest possible choice of freedom in
+implementing the specification. For this reason, outside of the exceptions
noted in this section, conformance is defined through the reference
implementation of the decoder provided in .
Although this document includes an English description of the codec, should
@@ 4906,36 +7481,99 @@ the latter shall take precedence.
Compliance with this specification means that a decoder's output MUST be
 within the thresholds specified by the opus_compare.c tool in
 compared to the reference implementation.
+Compliance with this specification means that in addition to following the normative keywords in this document,
+ a decoder's output MUST also be
+ within the thresholds specified by the opus_compare.c tool (included
+ with the code) when compared to the reference implementation for each of the
+ test vectors provided (see ) and for each output
+ sampling rate and channel count supported. In addition, a compliant
+ decoder implementation MUST have the same final range decoder state as that of the
+ reference decoder. It is therefore RECOMMENDED that the
+ decoder implement the same functional behavior as the reference.
+
+ A decoder implementation is not required to support all output sampling
+ rates or all output channel counts.
+
+
+
+
+Using the reference code provided in ,
+a test vector can be decoded with
+
+opus_demo d <rate> <channels> testvectorX.bit testX.out
+
+where <rate> is the sampling rate and can be 8000, 12000, 16000, 24000, or 48000, and
+<channels> is 1 for mono or 2 for stereo.
+
+
+
+If the range decoder state is incorrect for one of the frames, the decoder will exit with
+"Error: Range coder state mismatch between encoder and decoder". If the decoder succeeds, then
+the output can be compared with the "reference" output with
+
+opus_compare s r <rate> testvectorX.dec testX.out
+
+for stereo or
+
+opus_compare r <rate> testvectorX.dec testX.out
+
+for mono.
+
+
+In addition to indicating whether the test vector comparison passes, the opus_compare tool
+outputs an "Opus quality metric" that indicates how well the tested decoder matches the
+reference implementation. A quality of 0 corresponds to the passing threshold, while
+a quality of 100 is the highest possible value and means that the output of the tested decoder is identical to the reference
+implementation. The passing threshold (quality 0) was calibrated in such a way that it corresponds to
+additive white noise with a 48 dB SNR (similar to what can be obtained on a cassette deck).
+It is still possible for an implementation to sound very good with such a low quality measure
+(e.g. if the deviation is due to inaudible phase distortion), but unless this is verified by
+listening tests, it is RECOMMENDED that implementations achieve a quality above 90 for 48 kHz
+decoding. For other sampling rates, it is normal for the quality metric to be lower
+(typically as low as 50 even for a good implementation) because of harmless mismatch with
+the delay and phase of the internal sampling rate conversion.
To complement the Opus specification, the "Opus Custom" codec is defined to
handle special sampling rates and frame rates that are not supported by the
+On POSIX environments, the run_vectors.sh script can be used to verify all test
+vectors. This can be done with
+
+run_vectors.sh <exec path> <vector path> <rate>
+
+where <exec path> is the directory where the opus_demo and opus_compare executables
+are built and <vector path> is the directory containing the test vectors.
+
+
+
+
+
+Opus Custom is an OPTIONAL part of the specification that is defined to
+handle special sample rates and frame rates that are not supported by the
main Opus specification. Use of Opus Custom is discouraged for all but very
special applications for which a frame size different from 2.5, 5, 10, 20 ms is
needed (for either complexity or latency reasons). Such applications will not
be compatible with the "main" Opus codec. In Opus Custom operation,
only the CELT later is available, which is available using the celt_* function
calls in celt.h.
+special applications for which a frame size different from 2.5, 5, 10, or 20 ms is
+needed (for either complexity or latency reasons). Because Opus Custom is
+optional, streams encoded using Opus Custom cannot be expected to be decodable by all Opus
+implementations. Also, because no inband mechanism exists for specifying the sampling
+rate and frame size of Opus Custom streams, outofband signaling is required.
+In Opus Custom operation, only the CELT layer is available, using the opus_custom_* function
+calls in opus_custom.h.
+
The codec needs to take appropriate security considerations
into account, as outlined in and .
+Implementations of the Opus codec need to take appropriate security considerations
+into account, as outlined in .
It is extremely important for the decoder to be robust against malicious
payloads.
Malicious payloads must not cause the decoder to overrun its allocated memory
or to take an excessive amount of resources to decode.
Although problems
in encoders are typically rarer, the same applies to the encoder. Malicious
audio stream must not cause the encoder to misbehave because this would
+audio streams must not cause the encoder to misbehave because this would
allow an attacker to attack transcoding gateways.
@@ 4943,44 +7581,111 @@ The reference implementation contains no known buffer overflow or cases where
a specially crafted packet or audio segment could cause a significant increase
in CPU load.
However, on certain CPU architectures where denormalized floatingpoint
 operations are much slower than normal floatingpoint operations it is
 possible for some audio content (e.g., silence or nearsilence) to cause such
 an increase in CPU load.
+ operations are much slower than normal floatingpoint operations, it is
+ possible for some audio content (e.g., silence or nearsilence) to cause an
+ increase in CPU load.
Denormals can be introduced by reordering operations in the compiler and depend
 on the target architecture, so it is difficult to guarantee an implementation
+ on the target architecture, so it is difficult to guarantee that an implementation
avoids them.
For such architectures, it is RECOMMENDED that one add very small
 floatingpoint offsets to prevent significant numbers of denormalized
 operations or to configure the hardware to treat denormals as zero (DAZ).

+For architectures on which denormals are problematic, adding very small
+ floatingpoint offsets to the affected signals to prevent significant numbers
+ of denormalized operations is RECOMMENDED.
+Alternatively, it is often possible to configure the hardware to treat
+ denormals as zero (DAZ).
No such issue exists for the fixedpoint reference implementation.
+The reference implementation was validated in the following conditions:
+
+
+Sending the decoder valid packets generated by the reference encoder and
+ verifying that the decoder's final range coder state matches that of the
+ encoder.
+
+
+Sending the decoder packets generated by the reference encoder and then
+ subjected to random corruption.
+
+Sending the decoder random packets.
+
+Sending the decoder packets generated by a version of the reference encoder
+ modified to make random coding decisions (internal fuzzing), including mode
+ switching, and verifying that the range coder final states match.
+
+
+In all of the conditions above, both the encoder and the decoder were run
+ inside the Valgrind memory
+ debugger, which tracks reads and writes to invalid memory regions as well as
+ the use of uninitialized memory.
+There were no errors reported on any of the tested conditions.
+

+
This document has no actions for IANA.

+
Thanks to all other developers, including Raymond Chen, Soeren Skak Jensen, Gregory Maxwell,
Christopher Montgomery, and Karsten Vandborg Soerensen. We would also
like to thank Igor Dyakonov, Jan Skoglund for their help with subjective testing of the
Opus codec. Thanks to John Ridges, Keith Yan and many others on the Opus and CELT mailing lists
for their bug reports and feeback.
+like to thank Igor Dyakonov, Jan Skoglund, and Christian Hoene for their help with subjective testing of the
+Opus codec. Thanks to Ralph Giles, John Ridges, Ben Schwartz, Keith Yan, Christian Hoene, Kat Walsh, and many others on the Opus and CELT mailing lists
+for their bug reports and feedback.
+
+The authors agree to grant third parties the irrevocable right to copy, use and distribute
+the work (excluding Code Components available under the simplified BSD license), with or
+without modification, in any medium, without royalty, provided that, unless separate
+permission is granted, redistributed modified works do not contain misleading author, version,
+name of work, or endorsement information.
+
+
+
+
+
+
+Key words for use in RFCs to Indicate Requirement Levels
+
+
+
+
+
+
+

+
+
+Requirements for an Internet Audio Codec
+
+
+
+
+
+IETF
+
+
+This document provides specific requirements for an Internet audio
+ codec. These requirements address quality, sample rate, bitrate,
+ and packetloss robustness, as well as other desirable properties.
+
+
+
+
+
+
+
+
+SILK Speech Codec
@@ 4997,68 +7702,30 @@ for their bug reports and feeback.



 Robust and Efficient Quantization of Speech LSP Parameters Using Structured Vector Quantization
















 Evaluation of Split and Multistage Techniques in LSF Quantization


















 Efficient Search and Design Procedures for Robust MultiStage VQ of LPC Parameters for 4 kb/s Speech Coding

















+
+
+
+Robust and Efficient Quantization of Speech LSP Parameters Using Structured Vector Quantization
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ConstrainedEnergy Lapped Transform (CELT) Codec

+
@@ 5072,6 +7739,21 @@ for their bug reports and feeback.
+
+
+Guidelines for the use of Variable Bit Rate Audio with Secure RTP
+
+
+
+
+
+
+
+
+
+
+
+
Internet DenialofService Considerations
@@ 5088,27 +7770,10 @@ for their bug reports and feeback.


Guidelines for Writing RFC Text on Security Considerations






All RFCs are required to have a Security Considerations section. Historically, such sections have been relatively weak. This document provides guidelines to RFC authors on how to write a good Security Considerations section. This document specifies an Internet Best Current Practices for the Internet Community, and requests discussion and suggestions for improvements.







+Range encoding: An algorithm for removing redundancy from a digitised message


+
@@ 5132,23 +7797,236 @@ for their bug reports and feeback.
+
+
+The Computation of Line Spectral Frequencies Using Chebyshev Polynomials
+
+
+
+
+
+
+
+
+
+
+Valgrind website
+
+
+
+
+
+
+Google NetEQ code
+
+
+
+
+
+
+Google WebRTC code
+
+
+
+
+
+
+
+Opus Git Repository
+
+
+
+
+
+
+Opus website
+
+
+
+
+
+
+Vorbis website
+
+
+
+
+
+
+Matroska website
+
+
+
+
+
+
+Opus Testvectors (webside)
+
+
+
+
+
+
+Opus Testvectors (proceedings)
+
+
+
+
+
+
+Line Spectral Pairs
+Wikipedia
+
+
+
+
+
+Range Coding
+Wikipedia
+
+
+
+
+
+Hadamard Transform
+Wikipedia
+
+
+
+
+
+Viterbi Algorithm
+Wikipedia
+
+
+
+
+
+White Noise
+Wikipedia
+
+
+
+
+
+Linear Prediction
+Wikipedia
+
+
+
+
+
+Modified Discrete Cosine Transform
+Wikipedia
+
+
+
+
+
+Fast Fourier Transform
+Wikipedia
+
+
+
+
+
+Ztransform
+Wikipedia
+
+
+
+
+
+
+Maximum Entropy Spectral Analysis
+
+
+
+
+
+
+A fixed point computation of partial correlation coefficients
+
+
+
+
+
+
+
+
+Analysis/synthesis filter bank design based on time domain aliasing cancellation
+
+
+
+
+
+
+
+
+A HighQuality Speech and Audio Codec With Less Than 10 ms delay
+
+
+
+
+
+
+
+
+
+
+
+
+Subdivision of the audible frequency range into critical bands
+
+
+
+
+
+
+
This appendix contains the complete source code for the
reference implementation of the Opus codec written in C. This
implementation can be compiled for
either floatingpoint or fixedpoint architectures.
+reference implementation of the Opus codec written in C. By default,
+this implementation relies on floatingpoint arithmetic, but it can be
+compiled to use only fixedpoint arithmetic by defining the FIXED_POINT
+macro. Information on building and using the reference implementation is
+available in the README file.
The implementation can be compiled with either a C89 or a C99
compiler. It is reasonably optimized for most platforms such that
only architecturespecific optimizations are likely to be useful.
The FFT used is a slightly modified version of the KISSFFT package,
+The FFT used is a slightly modified version of the KISSFFT library,
but it is easy to substitute any other FFT library.
+
+While the reference implementation does not rely on any
+undefined behavior as defined by C89 or C99,
+it relies on common implementationdefined behavior
+for two's complement architectures:
+
+Right shifts of negative values are consistent with two's complement arithmetic, so that a>>b is equivalent to floor(a/(2**b)),
+For conversion to a signed integer of N bits, the value is reduced modulo 2**N to be within range of the type,
+The result of integer division of a negative value is truncated towards zero, and
+The compiler provides a 64bit integer type (a C99 requirement which is supported by most C89 compilers).
+
+
+
+
+In its current form, the reference implementation also requires the following
+architectural characteristics to obtain acceptable performance:
+
+Two's complement arithmetic,
+At least a 16 bit by 16 bit integer multiplier (32bit result), and
+At least a 32bit adder/accumulator.
+
+
+
+
The complete source code can be extracted from this draft, by running the
@@ 5156,7 +8034,7 @@ following command line:
opus_source.tar.gz
+cat draftietfcodecopus.txt  grep '^\ \ \ ###'  sed e 's/...###//'  base64 d > opus_source.tar.gz
]]>
tar xzvf opus_source.tar.gz
@@ 5164,31 +8042,60 @@ tar xzvf opus_source.tar.gz
cd opus_sourcemake
+On systems where the provided Makefile does not work, the following command line may be used to compile
+the source code:
+
+
+
+
+
+On systems where the base64 utility is not present, the following commands can be used instead:
+
+ opus.b64
+]]>
+openssl base64 d in opus.b64 > opus_source.tar.gz
+

+
The current development version of the source code is available in a
 Git repository.
Development snapshots are provided at
 .
+As of the time of publication of this memo, an uptodate implementation conforming to
+this standard is available in a
+ Git repository.
+Releases and other resources are available at
+ . However, although that implementation is expected to
+ remain conformant with the standard, it is the code in this document that shall
+ remain normative.

+

+
+
+Because of size constraints, the Opus test vectors are not distributed in this
+draft. They are available in the proceedings of the 83th IETF meeting (Paris) and from the Opus codec website at
+. These test vectors were created specifically to exercise
+all aspects of the decoder and therefore the audio quality of the decoded output is
+significantly lower than what Opus can achieve in normal operation.
+


+The SHA1 hash of the files in the test vector package are
+
+
+
+
@@ 5210,7 +8117,7 @@ It is RECOMMENDED that a transport layer choose exactly one framing scheme,
For example, although a regular Opus stream does not support more than two
channels, a multichannel Opus stream may be formed from several one and
twochannel streams.
To pack an Opus packets from each of these streams together in a single packet
+To pack an Opus packet from each of these streams together in a single packet
at the transport layer, one could use the selfdelimiting framing for all but
the last stream, and then the regular, undelimited framing for the last one.
Reverting to the undelimited framing for the last stream saves overhead
@@ 5255,7 +8162,7 @@ CBR Code 3 packets: It is the length used for all of the Opus frames (see
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
00s config  N1 (12 bytes): 
+ config s00 N1 (12 bytes): 
+++++++++++++++++ 
 Compressed frame 1 (N1 bytes)... :
: 
@@ 5270,7 +8177,7 @@ CBR Code 3 packets: It is the length used for all of the Opus frames (see
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
10s config  N1 (12 bytes): 
+ config s01 N1 (12 bytes): 
+++++++++++++++++ :
 Compressed frame 1 (N1 bytes)... 
: +++++++++++++++++
@@ 5289,7 +8196,7 @@ CBR Code 3 packets: It is the length used for all of the Opus frames (see
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
01s config  N1 (12 bytes): N2 (12 bytes : 
+ config s10 N1 (12 bytes): N2 (12 bytes : 
+++++++++++++++++++++++++ :
 Compressed frame 1 (N1 bytes)... 
: +++++++++++++++++
@@ 5308,7 +8215,7 @@ CBR Code 3 packets: It is the length used for all of the Opus frames (see
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
11s config  M p0 Pad len (Opt) : N1 (12 bytes):
+ config s110p M  Pad len (Opt) : N1 (12 bytes):
+++++++++++++++++++++++++++++++++
 
: Compressed frame 1 (N1 bytes)... :
@@ 5337,7 +8244,7 @@ CBR Code 3 packets: It is the length used for all of the Opus frames (see
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+++++++++++++++++++++++++++++++++
11s config  M p1 Padding length (Optional) :
+ config s111p M  Padding length (Optional) :
+++++++++++++++++++++++++++++++++
: N1 (12 bytes): ... : N[M1]  N[M] :
+++++++++++++++++++++++++++++++++