draft-ietf-codec-opus.xml 49.8 KB
Newer Older
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1
2
3
4
<?xml version='1.0'?>
<!DOCTYPE rfc SYSTEM 'rfc2629.dtd'>
<?rfc toc="yes" symrefs="yes" ?>

5
<rfc ipr="trust200902" category="std" docName="draft-ietf-codec-opus-02">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
6
7

<front>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
8
<title abbrev="Interactive Audio Codec">Definition of the Opus Audio Codec</title>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
9
10
11
12
13
14
15
16
17
18
19
20


<author initials="JM" surname="Valin" fullname="Jean-Marc Valin">
<organization>Octasic Inc.</organization>
<address>
<postal>
<street>4101, Molson Street</street>
<city>Montreal</city>
<region>Quebec</region>
<code></code>
<country>Canada</country>
</postal>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
21
<phone>+1 514 282-8858</phone>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
22
23
24
25
26
<email>jean-marc.valin@octasic.com</email>
</address>
</author>

<author initials="K." surname="Vos" fullname="Koen Vos">
27
<organization>Skype Technologies S.A.</organization>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
28
29
<address>
<postal>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
30
<street>Stadsgarden 6</street>
31
<city>Stockholm</city>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
32
<region></region>
33
34
<code>11645</code>
<country>SE</country>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
35
</postal>
36
<phone>+46 855 921 989</phone>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
37
38
39
40
41
<email>koen.vos@skype.net</email>
</address>
</author>


Jean-Marc Valin's avatar
Jean-Marc Valin committed
42
<date day="14" month="November" year="2010" />
Jean-Marc Valin's avatar
Jean-Marc Valin committed
43
44
45
46
47
48
49

<area>General</area>

<workgroup></workgroup>

<abstract>
<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
50
This document describes the Opus codec, designed for interactive speech and audio 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
51
transmission over the Internet.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
52
53
54
55
56
57
58
59
</t>
</abstract>
</front>

<middle>

<section anchor="introduction" title="Introduction">
<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
60
We propose the Opus codec based on a linear prediction layer (LP) and an
Jean-Marc Valin's avatar
Jean-Marc Valin committed
61
62
63
64
65
MDCT-based enhancement layer. The main idea behind the proposal is that
the speech low frequencies are usually more efficiently coded using
linear prediction codecs (such as CELP variants), while the higher frequencies
are more efficiently coded in the transform domain (e.g. MDCT). For low 
sampling rates, the MDCT layer is not useful and only the LP-based layer is
66
used. On the other hand, non-speech signals are not always adequately coded
Jean-Marc Valin's avatar
Jean-Marc Valin committed
67
68
using linear prediction, so for music only the MDCT-based layer is used.
</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
69

Jean-Marc Valin's avatar
Jean-Marc Valin committed
70
<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
71
72
73
74
In this proposed prototype, the LP layer is based on the 
<eref target='http://developer.skype.com/silk'>SILK</eref> codec 
<xref target="SILK"></xref> and the MDCT layer is based on the 
<eref target='http://www.celt-codec.org/'>CELT</eref>  codec
Jean-Marc Valin's avatar
Jean-Marc Valin committed
75
 <xref target="CELT"></xref>.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
76
77
</t>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
78
<t>This is a work in progress.</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
79
80
</section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
81
<section anchor="hybrid" title="Opus Codec">
82
83
84
85
86
87
88

<t>
In hybrid mode, each frame is coded first by the LP layer and then by the MDCT 
layer. In the current prototype, the cutoff frequency is 8 kHz. In the MDCT
layer, all bands below 8 kHz are discarded, such that there is no coding
redundancy between the two layers. Also both layers use the same instance of 
the range coder to encode the signal, which ensures that no "padding bits" are
Jean-Marc Valin's avatar
Jean-Marc Valin committed
89
90
91
92
wasted. The hybrid approach makes it easy to support both constant bit-rate
(CBR) and varaible bit-rate (VBR) coding. Although the SILK layer used is VBR,
it is easy to make the bit allocation of the CELT layer produce a final stream
that is CBR by using all the bits left unused by the SILK layer.
93
94
</t>

95
96
<t>The implementation of SILK-based LP layer is similar to the description in
the <xref target="SILK">SILK Internet-Draft</xref> with the main exception that 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
97
98
SILK was modified to 
use the same range coder as CELT. The implementation of the CELT-based MDCT
Jean-Marc Valin's avatar
Jean-Marc Valin committed
99
100
layer is available from the CELT website and is a more recent version (0.8.1) 
of the <xref target="CELT">CELT Internet-Draft</xref>. 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
101
102
103
The main changes
include better support for 20 ms frames as well as the ability to encode 
only the higher bands using a range coder partially filled by the SILK layer.</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
104
105
106
107
108
109
110
111
112
113
114

<t>
In addition to their frame size, the SILK and CELT codecs require
a look-ahead of 5.2 ms and 2.5 ms, respectively. SILK's look-ahead is due to
noise shaping estimation (5 ms) and the internal resampling (0.2 ms), while
CELT's look-ahead is due to the overlapping MDCT windows. To compensate for the
difference, the CELT encoder input is delayed by 2.7 ms. This ensures that low
frequencies and high frequencies arrive at the same time.
</t>


115
116
117
118
119
<section title="Source Code">
<t>
The source code is currently available in a
<eref target='git://git.xiph.org/users/jm/ietfcodec.git'>Git repository</eref> 
which references two other
120
121
122
repositories (for SILK and CELT). Some snapshots are provided for 
convenience at <eref target='http://people.xiph.org/~jm/ietfcodec/'/> along
with sample files.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
123
124
Although the build system is very primitive, some instructions are provided 
in the toplevel README file.
125
This is very early development so both the quality and feature set should
Jean-Marc Valin's avatar
Jean-Marc Valin committed
126
127
greatly improve over time. In the current version, only 48 kHz audio is 
supported, but support for all configurations listed in 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
128
<xref target="modes"></xref> is planned. 
129
130
131
132
133
</t>
</section>

</section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
134
135
136
137
138
139
140
141
<section anchor="modes" title="Codec Modes">
<t>
There are three possible operating modes for the proposed prototype:
<list style="numbers">
<t>A linear prediction (LP) mode for use in low bit-rate connections with up to 8 kHz audio bandwidth (16 kHz sampling rate)</t>
<t>A hybrid (LP+MDCT) mode for full-bandwidth speech at medium bitrates</t>
<t>An MDCT-only mode for very low delay speech transmission as well as music transmission.</t>
</list>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
142
143
Each of these modes supports a number of difference frame sizes and sampling
rates. In order to distinguish between the various modes and configurations,
Jean-Marc Valin's avatar
Jean-Marc Valin committed
144
we define a single-byte table-of-contents (TOC) header that can used in the transport layer 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
145
(e.g RTP) to signal this information. The following describes the proposed
Jean-Marc Valin's avatar
Jean-Marc Valin committed
146
TOC byte.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
147
148
149
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
150
The LP mode supports the following configurations (numbered from 0 to 11):
Jean-Marc Valin's avatar
Jean-Marc Valin committed
151
<list style="symbols">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
152
153
154
<t>8 kHz:  10, 20, 40, 60 ms (0..3)</t>
<t>12 kHz: 10, 20, 40, 60 ms (4..7)</t>
<t>16 kHz: 10, 20, 40, 60 ms (8..11)</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
155
156
157
158
159
</list>
for a total of 12 configurations.
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
160
The hybrid mode supports the following configurations (numbered from 12 to 15):
Jean-Marc Valin's avatar
Jean-Marc Valin committed
161
<list style="symbols">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
162
163
<t>32 kHz: 10, 20 ms (12..13)</t>
<t>48 kHz: 10, 20 ms (14..15)</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
164
165
166
167
168
</list>
for a total of 4 configurations.
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
169
The MDCT-only mode supports the following configurations (numbered from 16 to 31):
Jean-Marc Valin's avatar
Jean-Marc Valin committed
170
<list style="symbols">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
171
172
173
174
<t>8 kHz:  2.5, 5, 10, 20 ms (16..19)</t>
<t>16 kHz: 2.5, 5, 10, 20 ms (20..23)</t>
<t>32 kHz: 2.5, 5, 10, 20 ms (24..27)</t>
<t>48 kHz: 2.5, 5, 10, 20 ms (28..31)</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
175
</list>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
176
for a total of 16 configurations.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
177
178
179
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
180
There is thus a total of 32 configurations, encoded in 5 bits. On bit is used to signal mono vs stereo, which leaves 2 bits for the number of frames per packets (codes 0 to 3):
Jean-Marc Valin's avatar
Jean-Marc Valin committed
181
<list style="symbols">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
182
183
<t>0:    1 frames in the packet</t>
<t>1:    2 frames in the packet, each with equal compressed size</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
184
185
<t>2:    2 frames in the packet, with different compressed size</t>
<t>3:    arbitrary number of frames in the packet</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
186
</list>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
187
188
For code 2, the TOC byte is followed by the length of the first frame, encoded as described below.
For code 3, the TOC byte is followed by a byte encoding the number of frames in the packet, with the MSB indicating VBR. In the VBR case, the byte indicating the number of frames is followed by N-1 frame 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
189
190
lengths encoded as described below. As an additional limit, the audio duration contained
within a packet may not exceed 120 ms.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
191
192
193
194
195
</t>

<t>
The compressed size of the frames (if needed) is indicated -- usually -- with one byte, with the following meaning:
<list style="symbols">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
196
<t>0:          No frame (DTX or lost packet)</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
197
198
<t>1-251:      Size of the frame in bytes</t>
<t>252-255:    A second byte is needed. The total size is (size[1]*4)+size[0]</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
199
200
201
202
</list>
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
203
The maximum size representable is 255*4+255=1275 bytes. For 20 ms frames, that 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
204
205
206
207
208
209
represents a bit-rate of 510 kb/s, which is really the highest rate anyone would want 
to use in stereo mode (beyond that point, lossless codecs would be more appropriate).
</t>

<section anchor="examples" title="Examples">
<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
210
Simplest case: one narrowband mono 20-ms SILK frame
Jean-Marc Valin's avatar
Jean-Marc Valin committed
211
212
213
214
215
216
217
218
</t>

<t>
<figure>
<artwork><![CDATA[
 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Marc Valin's avatar
Jean-Marc Valin committed
219
|    1    |0|0|0|               compressed data...              |
Jean-Marc Valin's avatar
Jean-Marc Valin committed
220
221
222
223
224
225
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
226
Two 48 kHz mono 5 ms CELT frames of the same compressed size:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
227
228
229
230
231
232
233
234
</t>

<t>
<figure>
<artwork><![CDATA[
 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Marc Valin's avatar
Jean-Marc Valin committed
235
|    29   |0|0|1|               compressed data...              |
Jean-Marc Valin's avatar
Jean-Marc Valin committed
236
237
238
239
240
241
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
242
Two 48 kHz mono 20-ms hybrid frames of different compressed size:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
243
244
245
246
247
248
249
250
</t>

<t>
<figure>
<artwork><![CDATA[
 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Marc Valin's avatar
Jean-Marc Valin committed
251
252
253
|    15   |0|1|1|       2       |   frame size  |compressed data|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                       compressed data...                      |
Jean-Marc Valin's avatar
Jean-Marc Valin committed
254
255
256
257
258
259
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
</t>

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
260
Four 48 kHz stereo 20-ms CELT frame of the same compressed size:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
261
262
263
264
265
266
267
268
269

</t>

<t>
<figure>
<artwork><![CDATA[
 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Marc Valin's avatar
Jean-Marc Valin committed
270
|    31   |1|1|0|       4       |      compressed data...       |
Jean-Marc Valin's avatar
Jean-Marc Valin committed
271
272
273
274
275
276
277
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
</t>
</section>


278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
</section>

<section title="Codec Encoder">
<t>
Opus encoder block diagram.
</t>

<section anchor="range-encoder" title="Range Coder">
<t>
Opus 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, 
so it is faster when using larger bases (i.e.: an octet). All of the
calculations in the range coder must use bit-exact integer arithmetic.
</t>

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

<t>
The range encoder maintains an internal state vector composed of the
four-tuple (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 carry-propagating output octets. Both rng
and low are 32-bit 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).
</t>

<t>
Each symbol 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 that is
coded.
</t>

<section anchor="encoding-symbols" title="Encoding Symbols">
<t>
   The main encoding function is ec_encode() (rangeenc.c),
   which takes as an argument a three-tuple (fl,fh,ft)
   describing the range of the symbol to be encoded in the current
   context, with 0 &lt;= fl &lt; fh &lt;= ft &lt;= 65535. The values of this tuple
   are derived from the probability model for the symbol. Let f(i) be
   the frequency of the ith symbol in the current context. Then the
   three-tuple corresponding to the kth symbol is given by
   <![CDATA[
fl=sum(f(i),i<k), fh=fl+f(i), and ft=sum(f(i)).
]]>
</t>
<t>
   ec_encode() updates the state of the encoder as follows. If fl is
   greater than zero, then low = low + rng - (rng/ft)*(ft-fl) and 
   rng = (rng/ft)*(fh-fl). Otherwise, low is unchanged and
   rng = rng - (rng/ft)*(fh-fl). The divisions here are exact integer
   division. After this update, the range is normalized.
</t>
<t>
   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 <![CDATA[(low << 8 & 0x7FFFFFFF) and rng
   is set to (rng<<8)]]>. This process is carried out by
   ec_enc_normalize() (rangeenc.c).
</t>
<t>
   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
   (non-propagating) 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.
</t>
<t>
   The function ec_enc_carry_out() (rangeenc.c) performs
   this buffering. It takes a 9-bit input value, c, from the normalization
   8-bit 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.
</t>
<t>
   In the reference implementation, a special version of ec_encode()
   called ec_encode_bin() (rangeenc.c) is defined to
   take a two-tuple (fl,ftb), where <![CDATA[0 <= fl < 2^ftb and ftb < 16. It is
   mathematically equivalent to calling ec_encode() with the three-tuple
   (fl,fl+1,1<<ftb)]]>, but avoids using division.

</t>
</section>

<section anchor="encoding-ints" title="Encoding Uniformly Distributed Integers">
<t>
   Functions ec_enc_uint() or ec_enc_bits() are based on ec_encode() and 
   encode one of N equiprobable symbols, each with a frequency of 1,
   where N may be as large as 2^32-1. Because ec_encode() is limited to
   a total frequency of 2^16-1, this is done by encoding a series of
   symbols in smaller contexts.
</t>
<t>
   ec_enc_bits() (entenc.c) is defined, like
   ec_encode_bin(), to take a two-tuple (fl,ftb), with <![CDATA[0 <= fl < 2^ftb
   and ftb < 32. While ftb is greater than 8, it encodes bits (ftb-8) to
   (ftb-1) of fl, e.g., (fl>>ftb-8&0xFF) using ec_encode_bin() and
   subtracts 8 from ftb. Then, it encodes the remaining bits of fl, e.g.,
   (fl&(1<<ftb)-1)]]>, again using ec_encode_bin().
</t>
<t>
   ec_enc_uint() (entenc.c) takes a two-tuple (fl,ft),
   where ft is not necessarily a power of two. Let ftb be the location
   of the highest 1 bit in the two's-complement representation of
   (ft-1), or -1 if no bits are set. If ftb>8, then the top 8 bits of fl
   are encoded using ec_encode() with the three-tuple
   (fl>>ftb-8,(fl>>ftb-8)+1,(ft-1>>ftb-8)+1), and the remaining bits
   are encoded with ec_enc_bits using the two-tuple
   <![CDATA[(fl&(1<<ftb-8)-1,ftb-8). Otherwise, fl is encoded with ec_encode()
   directly using the three-tuple (fl,fl+1,ft)]]>.
</t>
</section>

<section anchor="encoder-finalizing" title="Finalizing the Stream">
<t>
   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. Then while end is not zero, the top 9 bits of end, e.g.,
   <![CDATA[(end>>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 is padded with zero octets. Finally, rem is set to the
   special value -1. This process is implemented by ec_enc_done()
   (rangeenc.c).
</t>
</section>

<section anchor="encoder-tell" title="Current Bit Usage">
<t>
   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 code will not overflow the
   output buffer. This is computed in the reference implementation to
   fractional bit precision by the function ec_enc_tell() 
   (rangeenc.c).
   Like all operations in the range encoder, it must
   be implemented in a bit-exact manner.
</t>
</section>

</section>

<section title="SILK Encoder">
<t>
Copy from SILK draft.
</t>
</section>

<section title="CELT Encoder">
<t>
Copy from CELT draft.
</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762

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

<t>The MDCT implementation has no special characteristics. 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 algorithmic delay. 
It is derived from a basic (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() (mdct.c), 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 each band has 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">non-quantized</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() (bands.c), respectively.
</t>
</section>

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

<t>
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
coarse-fine strategy for encoding the energy in the base-2 log domain, 
as implemented in quant_bands.c</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 is used.
To minimize 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 time-domain 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). We approximate the ideal 
probability distribution of the prediction error using a Laplace distribution. The
coarse energy quantization is performed by quant_coarse_energy() and 
quant_coarse_energy() (quant_bands.c).
</t>

<t>
The Laplace distribution for each band is defined by a 16-bit (Q15) decay parameter.
Thus, the value 0 has a frequency count of p[0]=2*(16384*(16384-decay)/(16384+decay)). The 
values +/- i each have a frequency count 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 frequency counts), so it is possible
for the sum to be less than 32768. In that case additional values with a frequency count 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() (laplace.c).
</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 refinement is an integer f in the range [0,2^B_i-1]. 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).
</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 are no unused bits. This is implemented in quant_energy_finalise() 
(quant_bands.c).
</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() (rate.c),
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 each have a width of one Bark, this is equivalent to modeling 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>


<t>
For every encoded or decoded frame, a target allocation must be computed
using the projected allocation. In the reference implementation this is
performed by compute_allocation() (rate.c).
The target computation begins by calculating the available space as the
number of whole bits which can be fit in the frame after Q1 is stored according
to the range coder (ec_[enc/dec]_tell()) and then multiplying by 8.
Then the two projected prototype allocations whose sums multiplied by 8 are nearest
to that value are determined. These two projected prototype allocations are then interpolated
by finding the highest integer interpolation coefficient in the range 0-8
such that the sum of the higher prototype times the coefficient, plus the
sum of the lower prototype multiplied by
the difference of 16 and the coefficient, is less than or equal to the
available sixteenth-bits. 
The reference implementation performs this step using a binary search in
interp_bits2pulses() (rate.c). The target  
allocation is the interpolation coefficient times the higher prototype, plus
the lower prototype multiplied by the difference of 16 and the coefficient,
for each of the CELT bands.   
</t>

<t>
Because the computed target will sometimes be somewhat smaller than the
available space, the excess space is divided by the number of bands, and this amount
is added equally to each band. Any remaining space is added to the target one
sixteenth-bit at a time, starting from the first band. The new target now
matches the available space, in sixteenth-bits, exactly. 
</t>

<t>
The allocation target is separated into a portion used for fine energy
and a portion used for the Spherical Vector Quantizer (PVQ). The fine energy
quantizer operates in whole-bit steps. For each band the number of bits per 
channel used for fine energy is calculated by 50 minus the log2_frac(), with
1/16 bit precision, of the number of MDCT bins in the band. That result is multiplied
by the number of bins in the band and again by twice the number of                 
channels, and then the value is set to zero if it is less than zero. Added
to that result is 16 times the number of MDCT bins times the number of
channels,  and it is finally divided by 32 times the number of MDCT bins times the
number of channels. If the result times the number of channels is greater than than the
target divided by 16, the result is set to the target divided by the number of
channels divided by 16. Then if the value is greater than 7 it is reset to 7 because a
larger amount of fine energy resolution was determined not to be make an improvement in
perceived quality.  The resulting number of fine energy bits per channel is
then multiplied by the number of channels and then by 16, and subtracted
from the target allocation. This final target allocation is what is used for the
PVQ.
</t>

</section>

<section anchor="pitch-prediction" title="Pitch Prediction">
<t>
This section needs to be updated.
</t>

</section>

<section anchor="pvq" title="Spherical Vector Quantization">
<t>CELT uses a Pyramid Vector Quantization (PVQ) <xref target="PVQ"></xref>
codebook for quantizing 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. Thus the codebook includes 
all integer codevectors y of N dimensions that satisfy sum(abs(y(j))) = K.
</t>

<t>
In bands where neither pitch nor folding is used, the PVQ is used to encode
the unit vector that results from the normalization in 
<xref target="normalization"></xref> directly. Given a PVQ codevector y, 
the unit vector X is obtained as X = y/||y||, where ||.|| denotes the 
L2 norm.
</t>

<section anchor="bits-pulses" title="Bits to Pulses">
<t>
Although the allocation is performed in 1/16 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 half-way between two values), subject to not exceeding
the total number of bits available. The computation is performed in 1/16 of
bits using log2_frac() and ec_enc_tell(). The number of codebooks entries can
be computed as explained in <xref target="cwrs-encoding"></xref>. The difference
between the number of bits allocated and the number of bits used is accumulated to a
<spanx style="emph">balance</spanx> (initialised to zero) that helps adjusting the
allocation for the next bands. One third of the balance is subtracted from the
bit allocation of the next band to help achieving 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 subtracted, respectively.
</t>
</section>

<section anchor="pvq-search" title="PVQ Search">

<t>
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 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 normalized correlation
between y and R:
</t>

<t>
J = -R^T*y / ||y||
</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>


<section anchor="cwrs-encoding" title="Index Encoding">
<t>
The best PVQ codeword is encoded as a uniformly-distributed integer value
by encode_pulses() (cwrs.c).
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, K != 0. 
There are many different ways to compute V(N,K), including pre-computed 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,
univariate recurrence to initialise an arbitrary line, and direct
polynomial solutions for small N. All of these methods are
equivalent, and have different trade-offs in speed, memory usage, and
code size. Implementations MAY use any methods they like, as long as
they are equivalent to the mathematical definition.
</t>

<t>
The indexing computations are performed using 32-bit unsigned integers. For large codebooks,
32-bit integers are not sufficient. Instead of using 64-bit integers (or more), the encoding
is made slightly sub-optimal by splitting each band into two equal (or near-equal) vectors of
size (N+1)/2 and N/2, respectively. The number of pulses in the first half, K1, is first encoded as an
integer in the range [0,K]. Then, two codebooks are encoded with V((N+1)/2, K1) and V(N/2, K-K1). 
The split operation is performed recursively, in case one (or both) of the split vectors 
still requires more than 32 bits. For compatibility reasons, the handling of codebooks of more 
than 32 bits MUST be implemented with the splitting method, even if 64-bit arithmetic is available.
</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 separately for each channel, or jointly encoded. Only one copy of the flags for the features, transients and pitch (pitch period and gains) 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.
</t>

<t>
The main difference between mono and stereo coding is the PVQ coding of the normalized vectors. In stereo mode, a normalized mid-side (M-S) 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=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. The theta parameter is converted to a Q14 fixed-point parameter itheta, which is quantized on a scale from 0 to 1 with an interval 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 cwrs.c. From here on, the value of itheta MUST be treated in a bit-exact manner since 
both the encoder and decoder rely on it to infer the bit allocation.
</t>
<t>
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. 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>qalloc = log2_frac((1&lt;&lt;qb)+1,4);</t>
<t>mbits = (b-qalloc/2-delta)/2;</t>
</list>
</t>

<t>where bitexact_cos() is a fixed-point cosine approximation that MUST be bit-exact with the reference implementation
in mathops.h. The spectral folding operation is performed independently for the mid and side vectors.</t>
</section>


<section anchor="synthesis" title="Synthesis">
<t>
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 (<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. If the de-emphasis filter (<xref target="inverse-mdct"></xref>) is applied to this resynthesized
signal, then the output will be the same (within numerical precision) as the decoder's output. 
</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). Support for VBR is OPTIONAL for the encoder, but a decoder MUST be prepared to decode a stream that changes its bit-rate dynamically. The method used to vary the bit-rate in VBR mode is left to the implementor, as long as each frame can be decoded by the reference decoder.
</t>
</section>

763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
</section>

</section>

<section title="Codec Decoder">
<t>
Opus decoder block diagram.
</t>

<section anchor="range-decoder" title="Range Decoder">
<t>
The range decoder extracts the symbols and integers encoded using the range encoder in
<xref target="range-encoder"></xref>. The range decoder maintains an internal
state vector composed of the two-tuple (dif,rng), representing the
difference between the high end of the current range and the actual
coded value, and the size of the current range, respectively. Both
dif and rng are 32-bit unsigned integer values. rng is initialized to
2^7. dif is initialized to rng minus the top 7 bits of the first
input octet. Then the range is immediately normalized, using the
procedure described in the following section.
</t>

<section anchor="decoding-symbols" title="Decoding Symbols">
<t>
   Decoding symbols is a two-step process. The first step determines
   a value fs that lies within the range of some symbol in the current
   context. The second step updates the range decoder state with the
   three-tuple (fl,fh,ft) corresponding to that symbol, as defined in
   <xref target="encoding-symbols"></xref>.
</t>
<t>
   The first step is implemented by ec_decode() 
   (rangedec.c), 
   and computes fs = ft-min((dif-1)/(rng/ft)+1,ft), where ft is
   the sum of the frequency counts in the current context, as described
   in <xref target="encoding-symbols"></xref>. The divisions here are exact integer division. 
</t>
<t>
   In the reference implementation, a special version of ec_decode()
   called ec_decode_bin() (rangeenc.c) is defined using
   the parameter ftb instead of ft. It is mathematically equivalent to
   calling ec_decode() with ft = (1&lt;&lt;ftb), but avoids one of the
   divisions.
</t>
<t>
   The decoder then identifies the symbol in the current context
   corresponding to fs; i.e., the one whose three-tuple (fl,fh,ft)
   satisfies fl &lt;= fs &lt; fh. This tuple is used to update the decoder
   state according to dif = dif - (rng/ft)*(ft-fh), and if fl is greater
   than zero, rng = (rng/ft)*(fh-fl), or otherwise rng = rng - (rng/ft)*(ft-fh). After this update, the range is normalized.
</t>
<t>
   To normalize the range, the following process is repeated until
   rng > 2^23. First, rng is set to (rng&lt;8)&amp;0xFFFFFFFF. Then the next
   8 bits of input are read into sym, using the remaining bit from the
   previous input octet as the high bit of sym, and the top 7 bits of the
   next octet for the remaining bits of sym. If no more input octets
   remain, zero bits are used instead. Then, dif is set to
   (dif&lt;&lt;8)-sym&amp;0xFFFFFFFF (i.e., using wrap-around if the subtraction
   overflows a 32-bit register). Finally, if dif is larger than 2^31,
   dif is then set to dif - 2^31. This process is carried out by
   ec_dec_normalize() (rangedec.c).
</t>
</section>

<section anchor="decoding-ints" title="Decoding Uniformly Distributed Integers">
<t>
   Functions ec_dec_uint() or ec_dec_bits() are based on ec_decode() and
   decode one of N equiprobable symbols, each with a frequency of 1,
   where N may be as large as 2^32-1. Because ec_decode() is limited to
   a total frequency of 2^16-1, this is done by decoding a series of
   symbols in smaller contexts.
</t>
<t>
   ec_dec_bits() (entdec.c) is defined, like
   ec_decode_bin(), to take a single parameter ftb, with ftb &lt; 32.
   and ftb &lt; 32, and produces an ftb-bit decoded integer value, t,
   initialized to zero. While ftb is greater than 8, it decodes the next
   8 most significant bits of the integer, s = ec_decode_bin(8), updates
   the decoder state with the 3-tuple (s,s+1,256), adds those bits to
   the current value of t, t = t&lt;&lt;8 | s, and subtracts 8 from ftb. Then
   it decodes the remaining bits of the integer, s = ec_decode_bin(ftb),
   updates the decoder state with the 3 tuple (s,s+1,1&lt;&lt;ftb), and adds
   those bits to the final values of t, t = t&lt;&lt;ftb | s.
</t>
<t>
   ec_dec_uint() (entdec.c) takes a single parameter,
   ft, which is not necessarily a power of two, and returns an integer,
   t, with a value between 0 and ft-1, inclusive, which is initialized to zero. Let
   ftb be the location of the highest 1 bit in the two's-complement
   representation of (ft-1), or -1 if no bits are set. If ftb>8, then
   the top 8 bits of t are decoded using t = ec_decode((ft-1>>ftb-8)+1),
   the decoder state is updated with the three-tuple
   (s,s+1,(ft-1>>ftb-8)+1), and the remaining bits are decoded with
   t = t&lt;&lt;ftb-8|ec_dec_bits(ftb-8). If, at this point, t >= ft, then
   the current frame is corrupt, and decoding should stop. If the
   original value of ftb was not greater than 8, then t is decoded with
   t = ec_decode(ft), and the decoder state is updated with the
   three-tuple (t,t+1,ft).
</t>
</section>

<section anchor="decoder-tell" title="Current Bit Usage">
<t>
   The bit allocation routines in CELT need to be able to determine a
   conservative upper bound on the number of bits that have been used
   to decode from the current frame thus far. This drives allocation
   decisions which must match those made in the encoder. This is
   computed in the reference implementation to fractional bit precision
   by the function ec_dec_tell() (rangedec.c). Like all
   operations in the range decoder, it must be implemented in a
   bit-exact manner, and must produce exactly the same value returned by
   ec_enc_tell() after encoding the same symbols.
</t>
</section>

</section>

<section title="SILK Decoder">
<t>
Copy from SILK draft.
</t>
</section>

<section title="CELT Decoder">
<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
Insert decoder figure.
</t>

<t>
The decoder extracts information from the range-coded bit-stream in the same order
as it was encoded by the encoder. 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.
</t>

<section anchor="energy-decoding" title="Energy Envelope Decoding">
<t>
The energy of each band is extracted from the bit-stream in two steps according
to the same coarse-fine strategy used in the encoder. First, the coarse energy is
decoded in unquant_coarse_energy() (quant_bands.c)
based on the probability of the Laplace model used by the encoder.
</t>

<t>
After the coarse energy is decoded, the same allocation function as used in the
encoder is called. This determines the number of
bits to decode for the fine energy quantization. The decoding of the fine energy bits
is performed by unquant_fine_energy() (quant_bands.c).
Finally, like the encoder, the remaining bits in the stream (that would otherwise go unused)
are decoded using unquant_energy_finalise() (quant_bands.c).
</t>
</section>

<section anchor="pitch-decoding" title="Pitch prediction decoding">
<t>
If the pitch bit is set, then the pitch period is extracted from the bit-stream. The pitch
gain bits are extracted within the PVQ decoding as encoded by the encoder. When the folding
bit is set, the folding prediction is computed in exactly the same way as the encoder, 
with the same gain, by the function intra_fold() (vq.c).
</t>

</section>

<section anchor="PVQ-decoder" title="Spherical VQ Decoder">
<t>
In order to correctly decode the PVQ codewords, the decoder must perform exactly the same
bits to pulses conversion as the encoder.
</t>

<section anchor="cwrs-decoder" title="Index Decoding">
<t>
The decoding of the codeword from the index is performed as specified in 
<xref target="PVQ"></xref>, as implemented in function
decode_pulses() (cwrs.c).
</t>
</section>

<section anchor="normalised-decoding" title="Normalised Vector Decoding">
<t>
The spherical codebook is decoded by alg_unquant() (vq.c).
The index of the PVQ entry is obtained from the range coder and converted to 
a pulse vector by decode_pulses() (cwrs.c).
</t>

<t>The decoded normalized vector for each band is equal to</t>
<t>X' = y/||y||,</t>

<t>
This operation is implemented in mix_pitch_and_residual() (vq.c), 
which is the same function as used in the encoder.
957
958
959
</t>
</section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001

</section>

<section anchor="denormalization" title="Denormalization">
<t>
Just like 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).
</t>
</section>

<section anchor="inverse-mdct" title="Inverse MDCT">
<t>The inverse MDCT implementation has no special characteristics. 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 window 
as the encoder. The IMDCT and windowing are performed by mdct_backward
(mdct.c). If a time-domain pre-emphasis 
window was applied in the encoder, the (inverse) time-domain de-emphasis window
is applied on the IMDCT result. After the overlap-add process, 
the signal is de-emphasized 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() (mdct.c).
</t>
</section>

</section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1002
1003
1004
1005
1006
</section>

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

<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1007
1008
1009
1010
1011
1012
1013
1014
The codec needs to take appropriate security considerations 
into account, as outlined in <xref target="DOS"/> and <xref target="SECGUIDE"/>.
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 much more 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
allow an attacker to attack transcoding gateways.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1015
</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1016
<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1017
In its current version, the Opus codec likely does NOT meet these
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1018
1019
security considerations, so it should be used with caution.
</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
</section> 


<section title="IANA Considerations ">
<t>
This document has no actions for IANA.
</t>
</section>

<section anchor="Acknowledgments" title="Acknowledgments">
<t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1031
Thanks to all other developers, including Raymond Chen, Soeren Skak Jensen, Gregory Maxwell, 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1032
Christopher Montgomery, Karsten Vandborg Soerensen, and Timothy Terriberry.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1033
1034
1035
1036
1037
1038
1039
</t>
</section> 

</middle>

<back>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1040
1041
1042
1043
1044
<references title="Informative References">

<reference anchor='SILK'>
<front>
<title>SILK Speech Codec</title>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1045
<author initials='K.' surname='Vos' fullname='K. Vos'>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1046
<organization /></author>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1047
<author initials='S.' surname='Jensen' fullname='S. Jensen'>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1048
<organization /></author>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1049
<author initials='K.' surname='Soerensen' fullname='K. Soerensen'>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
<organization /></author>
<date year='2010' month='March' />
<abstract>
<t></t>
</abstract></front>
<seriesInfo name='Internet-Draft' value='draft-vos-silk-01' />
<format type='TXT' target='http://tools.ietf.org/html/draft-vos-silk-01' />
</reference>

<reference anchor='CELT'>
<front>
<title>Constrained-Energy Lapped Transform (CELT) Codec</title>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1062
<author initials='J-M.' surname='Valin' fullname='J-M. Valin'>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1063
<organization /></author>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1064
<author initials='T.' surname='Terriberry' fullname='T. Terriberry'>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1065
<organization /></author>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1066
<author initials='G.' surname='Maxwell' fullname='G. Maxwell'>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1067
<organization /></author>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1068
<author initials='C.' surname='Montgomery' fullname='C. Montgomery'>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1069
<organization /></author>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1070
<date year='2010' month='July' />
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1071
1072
1073
<abstract>
<t></t>
</abstract></front>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1074
1075
<seriesInfo name='Internet-Draft' value='draft-valin-celt-codec-02' />
<format type='TXT' target='http://tools.ietf.org/html/draft-valin-celt-codec-02' />
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1076
</reference>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109

<reference anchor='DOS'>
<front>
<title>Internet Denial-of-Service Considerations</title>
<author initials='M.' surname='Handley' fullname='M. Handley'>
<organization /></author>
<author initials='E.' surname='Rescorla' fullname='E. Rescorla'>
<organization /></author>
<author>
<organization>IAB</organization></author>
<date year='2006' month='December' />
<abstract>
<t>This document provides an overview of possible avenues for denial-of-service (DoS) attack on Internet systems.  The aim is to encourage protocol designers and network engineers towards designs that are more robust.  We discuss partial solutions that reduce the effectiveness of attacks, and how some solutions might inadvertently open up alternative vulnerabilities.  This memo provides information for the Internet community.</t></abstract></front>
<seriesInfo name='RFC' value='4732' />
<format type='TXT' octets='91844' target='ftp://ftp.isi.edu/in-notes/rfc4732.txt' />
</reference>

<reference anchor='SECGUIDE'>
<front>
<title>Guidelines for Writing RFC Text on Security Considerations</title>
<author initials='E.' surname='Rescorla' fullname='E. Rescorla'>
<organization /></author>
<author initials='B.' surname='Korver' fullname='B. Korver'>
<organization /></author>
<date year='2003' month='July' />
<abstract>
<t>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.</t></abstract></front>

<seriesInfo name='BCP' value='72' />
<seriesInfo name='RFC' value='3552' />
<format type='TXT' octets='110393' target='ftp://ftp.isi.edu/in-notes/rfc3552.txt' />
</reference>

1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
<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>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1129
1130
1131
1132
1133
1134
1135
1136
<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> 
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1137
1138
1139

</references> 

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
<section anchor="ref-implementation" title="Reference Implementation">

<t>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 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>

<section title="Extracting the source">
<t>
The complete source code can be extracted from this draft, by running the
following command line:

<list style="symbols">
<t><![CDATA[
cat draft-ietf-codec-opus.txt | grep '^   ###' | sed 's/   ###//' | base64 -d > opus_source.tar.gz
]]></t>
<t>
tar xzvf opus_source.tar.gz
</t>
</list>

</t>
</section>

<section title="Base64-encoded source code">
<t>
<?rfc include="opus_source.base64"?>
</t>
</section>

</section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1180
1181
1182
</back>

</rfc>