shithub: opus

ref: 7c422653f3fd27efd1b6e40e4f6bb438bc9de2ab
dir: /doc/ietf/draft-valin-celt-codec.xml/

View raw version
<?xml version='1.0'?>
<!DOCTYPE rfc SYSTEM 'rfc2629.dtd'>
<?rfc toc="yes" symrefs="yes" ?>

<rfc ipr="trust200902" category="info" docName="draft-valin-celt-codec-00">

<front>
<title abbrev="CELT codec">Constrained-Energy Lapped Transform (CELT) Codec</title>



<author initials="J-M" surname="Valin" fullname="Jean-Marc Valin">
<organization>Octasic Semiconductor</organization>
<address>
<postal>
<street>4101, Molson Street, suite 300</street>
<city>Montreal</city>
<region>Quebec</region>
<code>H1Y 3L1</code>
<country>Canada</country>
</postal>
<email>[email protected]</email>
</address>
</author>

<author initials="T" surname="Terriberry" fullname="Timothy B. Terriberry">
<organization>Xiph.Org Foundation</organization>
<address>
<postal>
<street></street>
<city></city>
<region></region>
<code></code>
<country></country>
</postal>
<email>[email protected]</email>
</address>
</author>

<author initials="G" surname="Maxwell" fullname="Gregory Maxwell">
<organization>Juniper Networks</organization>
<address>
<postal>
<street>2251 Corporate Park Drive, Suite 100</street>
<city>Herndon</city>
<region>VA</region>
<code>20171-1817</code>
<country>USA</country>
</postal>
<email>[email protected]</email>
</address>
</author>

<!-- <author initials="et" surname="al." fullname="et al.">
<organization></organization>
</author>
-->

<date day="8" month="June" year="2009" />

<area>General</area>

<workgroup>AVT Working Group</workgroup>
<keyword>audio codec</keyword>
<keyword>low delay</keyword>
<keyword>Internet-Draft</keyword>
<keyword>CELT</keyword>

<abstract>
<t>
CELT <xref target="celt-website"/> is an open-source voice codec suitable for use in very low delay 
Voice over IP (VoIP) type applications.  This document describes the encoding
and decoding process. 
</t>
</abstract>
</front>

<middle>

<section anchor="Introduction" title="Introduction">
<t>
This document describes the CELT codec, which is designed for transmitting full-bandwidth
audio with very low delay. It is suitable for encoding both
speech and music and rates starting at 32 kbit/s. It is primarly designed for transmission
over packet networks and protocols such as RTP <xref target="rfc3550"/>, but also includes
a certain amount of robustness to bit errors, where this could be done at no significant
cost. 
</t>

<t>The novel aspect of CELT compared to most other codecs is its very low delay,
below 10 ms. There are two main advantages to having a very low delay audio link.
The lower delay itself is important some interactions, such as playing music
remotely. Another advantage is the behaviour in presence of acoustic echo. When
the round-trip audio delay is sufficiently low, acoustic echo is no longer
perceived as a distinct repetition, but as extra reverberation. Applications
of CELT include:</t>
<t>
<list style="symbols">
<t>Live network music performance</t>
<t>High-quality teleconferencing</t>
<t>Wireless audio equipment</t>
<t>Low-delay links for broadcast applications</t>
</list>
</t>

<t>
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 <xref target="rfc2119"/>.
</t>

</section>

<section anchor="overview" title="Overview of the CELT Codec">

<t>
CELT stands for <spanx style="emph">Constrained Energy Lapped Transform</spanx>. This is
the fundamental princple of the codec: the quantization process is designed in such a way
as to preserve the energy in a certain number of bands. The theoretical aspects of the
codec is described in greater details <xref target="celt-tasl"/> and 
<xref target="celt-eusipco"/>. Although these papers describe a slightly older version of
the codec (version 0.3.2 and 0.5.1, respectively), the principles remain the same.
</t>

<t>CELT is a transform codec, based on the Modified Discrete Cosine Transform 
<xref target="mdct"/>, derived from the DCT-IV, with overlap and time-domain
aliasing calcellation. The main characteristics of CELT are as follows:

<list style="symbols">
<t>Ultra-low algorithmic delay (scalable, typically 3 to 9 ms)</t>
<t>Sampling rates from 32 kHz to 48 kHz and above (full audio bandwidth)</t>
<t>Applicable to both speech and music</t>
<t>Support for mono and stereo</t>
<t>Adaptive bit-rate from 32 kbps to 128 kbps and above</t>
<t>Scalable complexity</t>
<t>Robustness to packet loss (scalable trade-off between quality and loss robustness)</t>
<t>Open source implementation (floating-point and fixed-point)</t>
<t>No known intellectual property issue</t>
</list>
</t>

<section anchor="bitstream" title="Bit-stream definition">

<t>
This document contains a detailed description of both the encoder and the decoder, along with a reference implementation. In most circumstances, and unless otherwise stated, the calculations in other implementations do NOT need to produce results that are bit-identical with the reference implementation, so alternate algorithms can sometimes be used. However, there are a few (clearly identified) cases where bit-exactness is required. An implementation is considered to be compatible if, for any valid bit-stream, the decoder's output is perceptually very close to the output produced by the reference decoder.
</t>

<t>
The CELT codec does not use a standard <spanx style="emph">bit-packer</spanx>, 
but rather uses a range coder to pack both integers and entropy-coded symbols. 
In mono mode, the bit-stream generated by the encoder contains (in the same order) the 
following parameters:
</t>

<t>
<list style="symbols">
<t>Feature flags (2-4 bits)</t>
<t>if P=1
   <list style="symbols">
      <t>Pitch period</t>
   </list></t>
<t>if S=1
   <list style="symbols">
      <t>Transient scalefactor</t>
      <t>if scalefactor=(1 or 2) AND more than 2 short MDCTs
	     <list style="symbols">
		    <t>ID of block before transient</t>
		 </list></t>
      <t>if scalefactor=3
	     <list style="symbols">
		    <t>Transient time</t>
      </list></t>
   </list></t>
<t>Coarse energy encoding (for each band)</t>
<t>Fine energy encoding (for each band)</t>
<t>For each band
   <list style="symbols">
      <t>if P=1 and band is at the beginning of a pitch band
	  <list>
	     <t>Pitch gain bit</t>
	  </list></t>
	  <t>PVQ indices</t>
   </list></t>
<t>More fine energy (using all remaining bits)</t>
</list>
</t>

<t>Note that due to the use of a range coder, all the parameters have to be encoded and decoded in order. </t>

</section>

</section>

<section anchor="CELT Modes" title="CELT Modes">
<t>
The operation of both the encoder and decoder depend on the mode data. A mode
definition can be created by celt_create_mode() (<xref target="modes.c">modes.c</xref>)
based on three parameters:
<list style="symbols">
<t>frame size (number of samples)</t>
<t>sampling rate (samples per second)</t>
<t>number of channels (1 or 2)</t>
</list>
</t>

<t>The mode data that is created defines how the encoder and the decoder operate. More specifically, the following information is contained in the mode object:

<list style="symbols">
<t>Frame size</t>
<t>Sampling rate</t>
<t>Windowing overlap</t>
<t>Number of channels</t>
<t>Definition of the bands</t>
<t>Definition of the <spanx style="emph">pitch bands</spanx></t>
<t>Decay coefficients of the Laplace distributions for coarse energy</t>
<t>Bit allocation matrix</t>
</list>
</t>

<t>
The windowing overlap is the amount of overlap between the frames. CELT uses a low-overlap window that is typically half of the frame size. For a frame size of 256 samples, the overlap is 128 samples, so the total algorithmic delay is 256+128=384. CELT divides the audio into frequency bands, for which the energy is preserved. These bands are chosen to follow the ear's critical bands (Bark scale), with the exception that each band has to contain at least 3 frequency bins. 
</t>

<t>
The bands used for coding in CELT are based on the Bark scale. The Bark band edges (in Hz) are defined as: 
[0, 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270,  1480,  1720,  2000,  2320,
2700, 3150, 3700, 4400, 5300, 6400,  7700, 9500, 12000, 15500, 20000]. The actual bands used by the codec
depend on the sampling rate and the frame size being used. The mapping from Hz to MDCT bins is done by
multiplying by sampling_rate/(2*frame_size) and rounding to the nearest value. An exception is made for
the lower frequencies to ensure that all bands contain at least 3 MDCT bins. The definition of the Bark
bands is computed in compute_ebands() (<xref target="modes.c">modes.c</xref>).
</t>

<t>
CELT includes a pitch predictor for which the gains are defined over 
a set of <spanx style="emph">pitch bands</spanx>. The pitch bands are defined
(in Hz) as [0, 345, 689, 1034, 1378, 2067, 3273, 5340, 6374]. The Hz values
are converted to MDCT bins in the same was as for the Bark bands. The pitch
bands boundaries are aligned to Bark band boundaries. The definition of the pitch
bands is computed in compute_pbands() (<xref target="modes.c">modes.c</xref>).
</t>
</section>

<section anchor="CELT Encoder" title="CELT Encoder">

<t>
The basic block diagram of the CELT encoder is illustrated in <xref target="encoder-diagram"></xref>.
The encoder contains most of the building blocks of the decoder and can,
with very little extra computation, compute the signal that would be decoded by the decoder.
The top-level function for encoding a CELT frame in the reference implementation is
celt_encode() (<xref target="celt.c">celt.c</xref>).
</t>

<figure anchor="encoder-diagram">
<artwork>
<![CDATA[
                  +-----------+       +--+
               +--|  Energy   |-+---->|Q1|--------------+
               |  |computation| |     +--+              |
               |  +-----------+ |                       |
               |          +-----+                       |
               |          v                             v
   +------+  +-+--+     +---+   +---+  +--+  +-----+  +---+  +-----+
-->|Window|->|MDCT|---->| / |-+>| - |->|Q3|->| Mix |->| * |->|IMDCT|-+
   +---+--+  +----+     +---+ | +---+  +--+  +-----+  +---+  +-----+ |
       |                      |   ^      ^      ^                    |
       |                      |   +------+------+                    |
       +-+                    v                 |                    |
         |              +-----------+  +--+   +-+-+                  |
         |              |pitch gains|->|Q2|-->| * |                  |
         |              +-----------+  +--+   +---+                  |
         |                    ^                 ^                    |
         |                    +-----------------+                    |
         v                                      |                    |
   +------------+                        +------+-----+              |
   |Pitch period|                        |Delay, MDCT,|              |
   |estimation  |----------------------->|  Normalize |              |
   +------------+                        +------------+              |
         ^                                      ^                    |
         +--------------------------------------+--------------------+
]]>
</artwork>
<postamble>Block diagram of the CELT encoder</postamble>
</figure>

<!--
<texttable anchor="bitstream">
        <ttcol align='center'>Parameter(s)</ttcol>
        <ttcol align='center'>Condition</ttcol>
        <ttcol align='center'>Synbol(s)</ttcol>
        <c>Feature flags</c><c>Always</c><c>2-4 bits</c>
        <c>Pitch period</c><c>P=1</c><c>1 Integer (8-9 bits)</c>
        <c>Transient scalefactor</c><c>S=1</c><c>2 bits</c>
        <c>Coarse energy</c><c>Always</c><c>one symbol per band</c>
        <c>Fine energy</c><c>Always</c><c>one symbol per band</c>
        <c>PVQ indices</c><c>Always</c><c>one symbol per band</c>
        <c>Remaining fine energy</c><c>bits available</c><c>one bit per band</c>
</texttable>
-->



<!--
<figure>
<artwork>
+-----------------+---------------------+------------------------------+
|  Feature flags  | (pitch period if P) | (transient scalefactor if S) |
+-----------------+---------------------+------------------------------+
|  (transient time if scalefactor == 3) |  coarse energy               |
+----------------+----------------------+-------+----------------------+
|  fine energy   |  PVQ indices  for all bands  |  (more fine energy)  |
+----------------+------------------------------+----------------------+
</artwork>
<postamble>Fields within parentheses are not included in every packet</postamble>
</figure>
-->

<section anchor="pre-emphasis" title="Pre-emphasis">

<t>The input audio first goes through a pre-emphasis filter, which attenuates the
<spanx style="emph">spectral tilt</spanx>. The filter is has the transfer function A(z)=1-alpha_p*z^-1, with
alpha_p=0.8. Although it is not a requirement, no part of the reference encoder operates
on the non-pre-emphasised signal. The inverse of the pre-emphasis is applied at the decoder.</t>

</section> <!-- pre-emphasis -->

<section anchor="range-encoder" title="Range Coder">
<t>
CELT uses an entropy coder based upon <xref target="range-coding"></xref>, 
which is itself a rediscovery of the FIFO arithmetic code introduced by <xref target="coding-thesis"></xref>.
It is very similar to arithmetic encoding, except that encoding is done with
digits in any base, instead of with bits, and so it is faster when using
larger bases (i.e.: a byte).
</t>

<t>
The range coder also acts as the bit-packer for CELT. It is
used in three different ways to encode:
<list style="symbols">
<t>entropy-coded symbols with a fixed probability model using ec_encode() (<xref target="rangedec.c">rangeenc.c</xref>)</t>
<t>integers from 0 to 2^M-1 using ec_enc_uint() or ec_enc_bits() (<xref target="entenc.c">encenc.c</xref>)</t>
<t>integers from 0 to N-1 (where N is not a power of two) using ec_enc_uint() (<xref target="entenc.c">encenc.c</xref>)</t>
</list>
</t>

<t>The main encoding function is ec_encode(), which takes as an argument the range of the symbol to be encoded. [[Describe how ec_encode() works]]
</t>

<t>
Functions ec_enc_uint() or ec_enc_bits() are based on ec_encode() and consider N equiprobable symbols, each with a frequency of 1. [[Describe the handling of larger integers]]
</t>

</section>

<section anchor="Encoder Feature Selection" title="Encoder Feature Selection">

<t>
The CELT codec has several optional features that can be switched on or off, some of which are mutually exclusive. The four main flags are intra-frame energy (I), pitch (P), short blocks (S), and folding (F). Those are described in more details below. There are eight valid combinations of these four features, and they are encoded first into the stream using a variable length code (<xref target="flags-encoding"></xref>). It is left to the implementor to choose to enable each of the flags, with the only restriction that the combination of the four flags needs to correspond to a valid entry in <xref target="flags-encoding"></xref>.
</t>

<texttable anchor="flags-encoding">
        <preamble>Encoding of the feature flags</preamble>
        <ttcol align='center'>I</ttcol>
        <ttcol align='center'>P</ttcol>
        <ttcol align='center'>S</ttcol>
        <ttcol align='center'>F</ttcol>
        <ttcol align='right'>Encoding</ttcol>
        <c>0</c><c>0</c><c>0</c><c>1</c><c>00</c>
        <c>0</c><c>1</c><c>0</c><c>1</c><c>01</c>
        <c>1</c><c>0</c><c>0</c><c>1</c><c>110</c>
        <c>1</c><c>0</c><c>1</c><c>1</c><c>111</c>
		
        <c>0</c><c>0</c><c>0</c><c>0</c><c>1000</c>
        <c>0</c><c>0</c><c>1</c><c>1</c><c>1001</c>
        <c>0</c><c>1</c><c>0</c><c>0</c><c>1010</c>
        <c>1</c><c>0</c><c>0</c><c>0</c><c>1011</c>
</texttable>

<section anchor="intra" title="Intra-frame energy (I)">
<t>
CELT uses prediction to encode the energy in each frequency band. In order to make frames independent, it is however possible to disable the part of the prediction that depends on previous frames. This is called <spanx style="emph">intra-frame energy</spanx> and requires around 12 more bits per frame to achieve when enabled with the <spanx style="emph">I</spanx> bit (Table. <xref target="flags-encoding">flags-encoding</xref>). The use of intra energy is OPTIONAL and the decision method is left to the implementor. The reference code describes one way of deciding which frames would benefit most from having their energy encoded without prediction. The intra_decision() (<xref target="quant_bands.c">quant_bands.c</xref>) function looks for frames where the log-spectral distance between consecutive frames is more than 9 dB. When such a difference is found between two frames, the next frame (not the one for which the difference is detected) is marked encoded with intra energy. The reason for the one-frame delay is to ensure that if the frame where a transient happens is lost, then the next frame will be decoded with no error.
</t>
</section>

<section anchor="pitch" title="Pitch prediction (P)">
<t>
CELT can use a pitch predictor (also known as long-term predictor) to improve the voice quality at lower bit-rate. While pitch period can be estimated in any way, it is RECOMMENDED for performance reasons to estimate it using a frequency-domain correlation between the current frame and the history buffer, as implemented in find_spectral_pitch() (<xref target="pitch.c">pitch.c</xref>). When the <spanx style="emph">P</spanx> bit is set, the pitch period is encoded after the flag bits. The value encoded is an integer in the range [0, 1024-N-overlap-1].
</t>
</section>

<section anchor="short-blocks" title="Short blocks (S)">
<t>
To improve audio quality during transients, CELT can use a <spanx style="emph">short blocks</spanx> multiple-MDCT transform. Unlike other transform codecs, the multiple MDCTs are jointly quantised as if the coefficients were obtained from a single MDCT. For that reason, it is better to consider the short blocks case as using a different transform of the same length rather than as multiple independent MDCTs. In the reference implementation, the decision to use short blocks is made by transient_analysis() (<xref target="celt.c">celt.c</xref>) based on the pre-emphasized signal's peak values, but other methods can be used. When the <spanx style="emph">S</spanx> bit is set, a 2-bit transient scalefactor is encoded directly after the flag bits. If the scalefactor is 0, then the multiple-MDCT output is unmodified. If the scalefactor is 1 or 2, then the output of the MDCTs that follow the transient is scaled down by 2^scalefactor. If the scalefactor is equal to 3, then a time-domain window is applied <spanx style="strong">before</spanx> computing the MDCTs and no further scaling is applied to the MDCTs output. The window value is 1 from the beginning of the frame to 16 samples before the transient time, it is a hanning window from there to the transient time and then 1/8 up to the end of the frame. The hanning window part is is defined as:
</t>

<t>
static const float transientWindow[16] = {
   0.0085135, 0.0337639, 0.0748914, 0.1304955, 
   0.1986827, 0.2771308, 0.3631685, 0.4538658,
   0.5461342, 0.6368315, 0.7228692, 0.8013173, 
   0.8695045, 0.9251086, 0.9662361, 0.9914865};
</t>

<t>When the scalefactor is 3, the transient time is encoded as an integer in the range [0, N+overlap-1] directly after the scalefactor.</t>


<t>
In the case where the scalefactor is 1 or 2 and the mode is defined to use more than 2 MDCTs, then the last MDCT to which the scaling is <spanx style="strong">not</spanx> applied is encoded using an integer in the range [0, B-2], where B is the number of short MDCTs used for the mode. 
</t>
</section>

<section anchor="folding" title="Spectral folding (F)">
<t>
The last encoding feature in CELT is spectral folding. It is designed to prevent <spanx style="emph">birdie</spanx> artefacts caused by the sparse spectra often generated by low-bitrate transform codecs. When folding is enabled, a copy of the low frequency spectrum is added to the higher frequency bands (above ~6400 Hz). The folding operation is decribed in more details in <xref target="pvq"></xref>.
</t>
</section>

</section>

<section anchor="forward-mdct" title="Forward MDCT">

<t>The MDCT implementation has no special characteristic. The
input is a windowed signal (after pre-emphasis) of 2*N samples and the output is N
frequency-domain samples. A <spanx style="emph">low-overlap</spanx> window is used to reduce the algorithmc delay. 
It is derived from a basic (with full overlap) window that is the same as the one used in the Vorbis codec: W(n)=[sin(pi/2*sin(pi/2*(n+.5)/L))]^2. The low-overlap window is created by zero padding 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() (<xref target="mdct.c">mdct.c</xref>), which includes the windowing operation and a scaling of 2/N.
</t>
</section>

<section anchor="normalization" title="Bands and Normalization">
<t>
The MDCT output is divided into bands that are designed to match the ear's critical bands,
with the exception that they have to be at least 3 bins wide. For each band, the encoder
computes the energy, that will later be encoded. Each band is then normalized by the 
square root of the <spanx style="strong">unquantized</spanx> energy, such that each band now forms a unit vector X.
The energy and the normalization are computed by compute_band_energies()
and normalise_bands() (<xref target="bands.c">bands.c</xref>), respectively.
</t>
</section>

<section anchor="energy-quantization" title="Energy Envelope Quantization">

<t>
It is important to quantize the energy with sufficient resolution because
any quantization error in the energy 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. We use a
coarse-fine strategy for encoding the energy in the base-2 log domain, 
as implemented in <xref target="quant_bands.c">quant_bands.c</xref></t>

<section anchor="coarse-energy" title="Coarse energy quantization">
<t>
The coarse quantization of the energy uses a fixed resolution of
6 dB and is the only place where entropy coding are used.
To minimise the bitrate, prediction is applied both in time (using the previous frame)
and in frequency (using the previous bands). The 2-D z-transform of
the prediction filter is: A(z_l, z_b)=(1-a*z_l^-1)*(1-z_b^-1)/(1-b*z_b^-1)
where b is the band index and l is the frame index. The prediction coefficients are
a=0.8 and b=0.7 when not using intra energy and a=b=0 when using intra energy. 
The prediction is applied on the quantized log-energy. We approximate the ideal 
probability distribution of the prediction error using a Laplace distribution. The
coarse energy quantisation is performed by quant_coarse_energy() and 
quant_coarse_energy_mono() (<xref target="quant_bands.c">quant_bands.c</xref>).
</t>

<t>
The Laplace distribution for each band is defined by a 16-bit (Q15) decay parameter.
Thus, the value 0 has a probability of p[0]=2*(16384*(16384-decay)/(16384+decay)). The 
values +/- i each have a probability p[i] = (p[i-1]*decay)>>14. The value of p[i] is always
rounded down (to avoid exceeding 32768 as the sum of all probabilities), so it is possible
for the sum to be less than 32768. In that case additional values with a probability of 1 are encoded. The signed values corresponding to symbols 0, 1, 2, 3, 4, ... 
are [0, +1, -1, +2, -2, ...]. The encoding of the Laplace-distributed values is 
implemented in ec_laplace_encode() (<xref target="laplace.c">laplace.c</xref>).
</t>
<!-- FIXME: bit budget consideration -->
</section> <!-- coarse energy -->

<section anchor="fine-energy" title="Fine energy quantization">
<t>
After the coarse energy quantization and encoding, the bit allocation is computed 
(<xref target="allocation"></xref>) 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 refement is an integer f in the range [0,2^B_i-1]. The mapping between f
and the correction applied to the corse energy is equal to (f+1/2)/2^B_i - 1/2. 
</t>

<t>
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 (<xref target="allocation"></xref>) was rounded
down. At the same level of priority, lower bands are encoded first. Refinement bits
are added until there is no unused bit.
</t>
</section> <!-- fine energy -->


</section> <!-- Energy quant -->

<section anchor="allocation" title="Bit Allocation">
<t>Bit allocation is performed based only on information available to both
the encoder and decoder. The same calculations are performed in a bit-exact
manner in both the encoder and decoder to ensure that the result is always
exactly the same. Any mismatch would cause an error in the decoded output.
The allocation is computed by compute_allocation() (<xref target="rate.c">rate.c</xref>),
which is used in both the encoder and the decoder.</t>

<t>For a given band, the bit allocation is nearly constant across
frames that use the same number of bits for Q1 , yielding a pre-
defined signal-to-mask ratio (SMR) for each band. Because the
bands have a width of one Bark, this is equivalent to modelling the
masking occurring within each critical band, while ignoring inter-
band masking and tone-vs-noise characteristics. While this is not an
optimal bit allocation, it provides good results without requiring the
transmission of any allocation information.
</t>

</section>

<section anchor="pitch-prediction" title="Pitch Prediction">
<t>
The pitch period T is computed in the frequency domain using a generalized 
cross-correlation, as implemented in find_spectral_pitch()
(<xref target="pitch.c">pitch.c</xref>). An MDCT is then computed on the 
synthsis signal memory using the offset T. If there is sufficient energy in this
part of the signal, the pitch gain for each pitch band
is computed as g = X^T*P, where X is the normalised (unquantised) signal and
P is the normalised pitch signal.
The gain is computed by compute_pitch_gain() (<xref target="bands.c">bands.c</xref>)
and if a sufficient number of bands have a high enough gain, then the pitch bit is set.
Otherwise, no use of pitch is made.
</t>

</section>

<section anchor="pvq" title="Spherical Vector Quantization">
<t>CELT uses a Pyramid Vector Quantization (PVQ) <xref target="PVQ"></xref>
codebook for quantising the details of the spectrum in each band that have not
been predicted by the pitch predictor. The PVQ codebook consists of all sums
of K signed pulses in a vector of N samples, where two pulses at the same position
are required to have the same sign. We can thus say that the codebook includes 
all codevectors y of N dimensions that satisfy sum(abs(y(j))) = K.
</t>

<t>
In bands where no pitch and no folding is used, the PVQ is used directly to encode
the unit vector that results from the normalisation in 
<xref target="normalization"></xref>. Given a PVQ codevector y, the unit vector X is
obtained as X = y/||y||. Where ||.|| denotes the L2 norm. In the case where a pitch
prediction or a folding vector P is used, the quantized unit vector X' becomes:
</t>
<t>X' = P + g_f * y,</t>
<t>where g_f = ( sqrt( (y^T*P)^2 + ||y||^2*(1-||P||^2) ) - y^T*P ) / ||y||^2. </t>

<t>The combination of the pitch with the pvq codeword is described in 
mix_pitch_and_residual() (<xref target="vq.c">vq.c</xref>) and is used in
both the encoder and the decoder.
</t>


<t>
The search for the best codevector y is performed by alg_quant()
(<xref target="vq.c">vq.c</xref>). 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 K-1 pulses:
</t>
<t>
y0 = round_towards_zero( (K-1) * R / sum(abs(R)))
</t>

<t>
Depending on N, K and the input data, the initial codeword y0 may contain from 
0 to K-1 non-zero values. All the remaining pulses, with the exception of the last one, 
are found iteratively with a greedy search that minimizes the normalised correlation
between y and R:
</t>

<t>
J = -R^T*y / ||y||
</t>

<t>
The last pulse is the only one considering the pitch and minimizes the cost function <xref target="celt-tasl"></xref>:
</t>

<t>
J = -g_f * R^T*y + (g_f)^2 * ||y||^2
</t>

<t>
The search described above is considered to be a good trade-off between quality
and computational cost. However, there are other possible ways to search the PVQ
codebook and the implementors MAY use any other search methods.
</t>

<section anchor="Index Encoding" title="Index Encoding">
<t>
The best PVQ codeword is encoded by encode_pulses() (<xref target="cwrs.c">cwrs.c</xref>).
The codeword is converted to a unique index in the same way as specified in 
<xref target="PVQ"></xref>. The indexing is based on the calculation of V(N,K) (denoted N(L,K) in <xref target="PVQ"></xref>), which is the number of possible combinations of K pulses 
in N samples. The number of combinations can be computed recursively as 
V(N,K) = V(N+1,K) + V(N,K+1) + V(N+1,K+1), with V(N,0) = 1 and V(0,K) = 0 for K != 0. 
There are many different ways to compute V(N,K), including pre-compute 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.
</t>
</section>

</section>


<section anchor="stereo" title="Stereo support">
<t>
When encoding a stereo stream, some parameters are shared across the left and right channels, while others are transmitted for each channel, or jointly encoded. All the flags for the features, transients and pitch (pitch period and gains) are transmitted only one copy. 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.
</t>

<t>
The main difference between mono and stereo coding is the PVQ coding of the normalised vectors. For bands of N=3 or N=4 samples, the PVQ coding is performed separately for left and right, with only one (joint) pitch bit and the left channel of each band encoded before the right channel of the same band. Each band always uses the same number of pulses for left as for right. For bands of N>=5 samples, a normalised mid-side (M-S) encoding is used. Let L and R be the normalised 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=L-R and no longer have unit norm.
</t>

<t>
From M and S, an angular parameter theta=2/pi*atan2(||S||, ||M||) is computed. It is quantised on a scale from 0 to 1 with an intervals of 2^-qb, where qb = (b-2*(N-1)*(40-log2_frac(N,4)))/(32*(N-1)), b is the number of bits allocated to the band, and log2_frac() is defined in <xref target="cwrs.c">cwrs.c</xref>. Let m=M/||M|| and s=S/||S||, m and s are separately encoded with the PVQ encoder described in <xref target="pvq"></xref>. The number of bits allocated to m and s depends on the value of itheta, which is a fixed-point (Q14) respresentation of theta. The value of itheta needs to be treated in a bit-exact manner since both the encoder and decoder rely on it to infer the bit allocation. The number of bits allocated to coding m is obtained by:
</t>

<t>
<list>
<t>imid = bitexact_cos(itheta);</t>
<t>iside = bitexact_cos(16384-itheta);</t>
<t>delta = (N-1)*(log2_frac(iside,6)-log2_frac(imid,6))>>2;</t>
<t>mbits = (b-qalloc/2-delta)/2;</t>
</list>
</t>

</section>


<section anchor="synthesis" title="Synthesis">
<t>
After all the quantisation is completed, the quantised energy is used along with the 
quantised normalised band data to resynthesise the MDCT spectrum. The inverse MDCT (<xref target="inverse-mdct"></xref>) and the weighted overlap-add are applied and the signal is stored in the <spanx style="emph">synthesis buffer</spanx> so it can be used for pitch prediction. 
The encoder MAY omit this step of the processing if it knows that it will not be using
the pitch predictor for the next few frames.
</t>
</section>

<section anchor="vbr" title="Variable Bitrate (VBR)">
<t>
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 source-controlled variable bitrate (VBR).
</t>
</section>

</section>

<section anchor="CELT-decoder" title="CELT Decoder">

<t>
Like for most audio codecs, the CELT decoder is less complex than the encoder, as can be
observed in the decoder block diagram in <xref target="decoder-diagram"></xref>.
</t>

<figure anchor="decoder-diagram">
<artwork>
<![CDATA[
                            +--+
                            |Q1|-------------+
                            +--+             |
                                             v
                            +--+  +-----+  +---+  +-----+
                            |Q3|->| Mix |->| * |->|IMDCT|-+
                            +--+  +-----+  +---+  +-----+ |
                              ^      ^                    |
                              +------+                    |
                                     |                    |
                            +--+   +-+-+                  |
                            |Q2|-->| * |                  |
                            +--+   +---+                  |
                                     ^                    |
                                     |                    |
                              +------+-----+              |
              +------------+  |Delay, MDCT,|              |
              |Pitch period|->|  Normalize |              |
              +------------+  +------------+              |
                                     ^                    |
                                     +--------------------+
]]>
</artwork>
<postamble>Block diagram of the CELT decoder</postamble>
</figure>

<t>
If during the decoding process a decoded integer value is out of the specified range
(it can happen due to a minimal amount of redundancy when incoding large integers with
the range coder), then the decoder knows 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 occured.
</t>

<section anchor="range-decoder" title="Range Decoder">
<t>
The range decoder extracts the symbols and integers encoded using the range encoder 
<xref target="range-encoder"></xref>. 
</t>
</section>

<section anchor="energy-decoding" title="Energy Envelope Decoding">
<t>

</t>
</section>

<section anchor="PVQ-decoder" title="Spherical VQ Decoder">
<t>
The spherical codebook is decoded by alg_unquant() (<xref target="vq.c">vq.c</xref>).
The index of the PVQ entry is obtained from the range coder and converted to 
a pulse vector by decode_pulses() (<xref target="cwrs.c">cwrs.c</xref>).
</t>

<t>The decoded normalised vector for each band is equal to</t>
<t>X' = P + g_f * y,</t>
<t>where g_f = ( sqrt( (y^T*P)^2 + ||y||^2*(1-||P||^2) ) - y^T*P ) / ||y||^2. </t>

<t>
This operation is implemented in mix_pitch_and_residual() (<xref target="vq.c">vq.c</xref>), 
which is the same function as used in the encoder.
</t>
</section>

<section anchor="denormalization" title="Denormalization">
<t>
Just like each band was normalised 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()
(<xref target="bands.c">bands.c</xref>).
</t>
</section>

<section anchor="inverse-mdct" title="Inverse MDCT">
<t>The inverse MDCT implementation has no special characteristic. The
input is N frequency-domain samples and the output is 2*N time-domain 
samples, while scaling by 1/2. The output is windowed using the same
<spanx style="emph">low-overlap</spanx> window 
as the encoder. The IMDCT and windowing are performed by mdct_backward
(<xref target="mdct.c">mdct.c</xref>). After the overlap-add process, 
the signal is de-emphasised using the inverse of the pre-emphasis filter 
used in the encoder: 1/A(z)=1/(1-alpha_p*z^-1).
</t>
</section>

<section anchor="Packet Loss Concealment" title="Packet Loss Concealment (PLC)">
<t>
Packet loss concealment (PLC) is an optional decoder-side feature which 
SHOULD be included when transmitting over an unreliable channel. Because 
PLC is not part of the bit-stream, there are several possible ways to 
implement PLC with different complexity/quality trade-offs. The PLC in
the reference implementation 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 time-domain aliasing
cancellation with the previous frame and the next frame. This is implemented 
in celt_decode_lost() (<xref target="celt.c">mdct.c</xref>).
</t>
</section>

</section>



<section anchor="Security Considerations" title="Security Considerations">

<t>
A potential denial-of-service threat exists for data encodings using
compression techniques that have non-uniform receiver-end
computational load.  The attacker can inject pathological datagrams
into the stream which are complex to decode and cause the receiver to
be overloaded.  However, this encoding does not exhibit any
significant non-uniformity.
</t>

<t>
With the exception of the first four bits, the bit-stream produced by
CELT for an unknown audio stream is not easily predictable due to the
use of entropy coding. This should make CELT less vulnerable to attacks
based on plaintext guessing when encryption is used. Also, since almost
all possible bit combinations can be interpreted as a valid bit-stream,
it is likely more difficult to determine from the decrypted bit-stream
whether a guessed decryption key is valid.
</t>

<t>
When operating CELT in variable-bitrate (VBR) mode, some of the
properties described above no longer hold. More specifically, the size
of the packet leaks a very small, but non-zero amount of information
about both the original signal and the bit-stream plaintext.
</t>
</section> 

<!--

<section anchor="Evaluation of CELT Implementations" title="Evaluation of CELT Implementations">

<t>
Insert some text here.
</t>

</section>

-->


<section anchor="Acknowledgments" title="Acknowledgments">

<t>
The authors would also like to thank the following members of the 
CELT and AVT communities for their input:
</t>
</section> 

</middle>

<back>

<references title="Normative References">

<reference anchor="rfc2119">
<front>
<title>Key words for use in RFCs to Indicate Requirement Levels </title>
<author initials="S." surname="Bradner" fullname="Scott Bradner"><organization/></author>
</front>
<seriesInfo name="RFC" value="2119" />
</reference> 

<reference anchor="rfc3550">
<front>
<title>RTP: A Transport Protocol for real-time applications</title>
<author initials="H." surname="Schulzrinne" fullname=""><organization/></author>
<author initials="S." surname="Casner" fullname=""><organization/></author>
<author initials="R." surname="Frederick" fullname=""><organization/></author>
<author initials="V." surname="Jacobson" fullname=""><organization/></author>
</front>
<seriesInfo name="RFC" value="3550" />
</reference> 


</references> 

<references title="Informative References">

<reference anchor="celt-tasl">
<front>
<title>A High-Quality Speech and Audio Codec With Less Than 10 ms delay</title>
<author initials="JM" surname="Valin" fullname="Jean-Marc Valin"><organization/></author>
<author initials="T. B." surname="Terriberry" fullname="Timothy Terriberry"><organization/></author>
<author initials="C." surname="Montgomery" fullname="Christopher Montgomery"><organization/></author>
<author initials="G." surname="Maxwell" fullname="Gregory Maxwell"><organization/></author>
</front>
<seriesInfo name="To appear in IEEE Transactions on Audio, Speech and Language Processing" value="2009" />
</reference> 

<reference anchor="celt-eusipco">
<front>
<title>A Full-Bandwidth Audio Codec with Low Complexity and Very Low Delay</title>
<author initials="JM" surname="Valin" fullname="Jean-Marc Valin"><organization/></author>
<author initials="T. B." surname="Terriberry" fullname="Timothy Terriberry"><organization/></author>
<author initials="G." surname="Maxwell" fullname="Gregory Maxwell"><organization/></author>
</front>
<seriesInfo name="Accepted for EUSIPCO" value="2009" />
</reference> 

<reference anchor="celt-website">
<front>
<title>The CELT ultra-low delay audio codec</title>
<author><organization/></author>
</front>
<seriesInfo name="CELT website" value="http://www.celt-codec.org/" />
</reference> 

<reference anchor="mdct">
<front>
<title>Modified Discrete Cosine Transform</title>
<author><organization/></author>
</front>
<seriesInfo name="MDCT" value="http://en.wikipedia.org/wiki/Modified_discrete_cosine_transform" />
</reference> 

<reference anchor="range-coding">
<front>
<title>Range encoding: An algorithm for removing redundancy from a digitised message</title>
<author initials="G." surname="Nigel" fullname=""><organization/></author>
<author initials="N." surname="Martin" fullname=""><organization/></author>
<date year="1979" />
</front>
<seriesInfo name="Proc. Institution of Electronic and Radio Engineers International Conference on Video and Data Recording" value="" />
</reference> 

<reference anchor="coding-thesis">
<front>
<title>Source coding algorithms for fast data compression</title>
<author initials="R." surname="Pasco" fullname=""><organization/></author>
<date month="May" year="1976" />
</front>
<seriesInfo name="Ph.D. thesis" value="Dept. of Electrical Engineering, Stanford University" />
</reference>

<reference anchor="PVQ">
<front>
<title>A Pyramid Vector Quantizer</title>
<author initials="T." surname="Fischer" fullname=""><organization/></author>
<date month="July" year="1986" />
</front>
<seriesInfo name="IEEE Trans. on Information Theory, Vol. 32" value="pp. 568-583" />
</reference> 

</references>

<section anchor="Reference Implementation" title="Reference Implementation">

<t>This appendix contains the complete source code for a reference
implementation of the CELT codec written in C. This floating-point
implementation is derived from the implementation available on the 
<xref target="celt-website"></xref>, which can be compiled for 
either floating-point or fixed-point architectures.
</t>

<t>The implementation can be compiled with either a C89 or a C99
compiler. It is reasonably optimized for most platforms such that
only architecture-specific optimizations are likely to be useful.
The FFT used is a slightly modified version of the KISS-FFT package,
but it is easy to substitute any other FFT library.
</t>

<t>
The testcelt executable can be used to test the encoding and decoding
process:
<list style="empty">
<t><![CDATA[
testcelt <rate> <channels> <frame size> <bytes per packet>
         [<complexity> [packet loss rate]] <input> <output>
]]></t>
</list>
where "rate" is the sampling rate in Hz, "channels" is the number of
channels (1 or 2), "frame size" is the number of samples in a frame 
(64 to 512) and "bytes per packet" is the number of bytes desired for each
compressed frame. The input and output files are assumed to be a 16-bit
PCM file in the machine native endianness. The optional "complexity" argument
can select the quality vs complexity tradeoff (0-10) and the "packet loss rate"
argument simulates random packet loss (argument is in tenths or a percent).
</t>

<?rfc include="xml_source/testcelt.c"?>
<?rfc include="xml_source/celt.h"?>
<?rfc include="xml_source/celt.c"?>
<?rfc include="xml_source/modes.h"?>
<?rfc include="xml_source/modes.c"?>
<?rfc include="xml_source/bands.h"?>
<?rfc include="xml_source/bands.c"?>
<?rfc include="xml_source/cwrs.h"?>
<?rfc include="xml_source/cwrs.c"?>
<?rfc include="xml_source/vq.h"?>
<?rfc include="xml_source/vq.c"?>
<?rfc include="xml_source/pitch.h"?>
<?rfc include="xml_source/pitch.c"?>
<?rfc include="xml_source/rate.h"?>
<?rfc include="xml_source/rate.c"?>
<?rfc include="xml_source/psy.h"?>
<?rfc include="xml_source/psy.c"?>
<?rfc include="xml_source/mdct.h"?>
<?rfc include="xml_source/mdct.c"?>
<?rfc include="xml_source/ecintrin.h"?>
<?rfc include="xml_source/entcode.h"?>
<?rfc include="xml_source/entcode.c"?>
<?rfc include="xml_source/entenc.h"?>
<?rfc include="xml_source/entenc.c"?>
<?rfc include="xml_source/entdec.h"?>
<?rfc include="xml_source/entdec.c"?>
<?rfc include="xml_source/mfrngcod.h"?>
<?rfc include="xml_source/rangeenc.c"?>
<?rfc include="xml_source/rangedec.c"?>
<?rfc include="xml_source/laplace.h"?>
<?rfc include="xml_source/laplace.c"?>
<?rfc include="xml_source/quant_bands.h"?>
<?rfc include="xml_source/quant_bands.c"?>
<?rfc include="xml_source/arch.h"?>
<?rfc include="xml_source/mathops.h"?>
<?rfc include="xml_source/os_support.h"?>
<?rfc include="xml_source/float_cast.h"?>
<?rfc include="xml_source/stack_alloc.h"?>
<?rfc include="xml_source/celt_types.h"?>
<?rfc include="xml_source/_kiss_fft_guts.h"?>
<?rfc include="xml_source/kiss_fft.h"?>
<?rfc include="xml_source/kiss_fft.c"?>
<?rfc include="xml_source/kiss_fftr.h"?>
<?rfc include="xml_source/kiss_fftr.c"?>
<?rfc include="xml_source/kfft_single.h"?>
<?rfc include="xml_source/kfft_double.h"?>
<?rfc include="xml_source/Makefile"?>

</section>


</back>

</rfc>