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

Jean-Marc Valin's avatar
Jean-Marc Valin committed
5
<rfc ipr="trust200902" category="std" docName="draft-ietf-codec-opus-06">
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
<email>jmvalin@jmvalin.ca</email>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
23
24
25
26
</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
<email>koen.vos@skype.net</email>
</address>
</author>

41
42
43
44
45
46
47
48
49
50
51
52
53
54
<author initials="T." surname="Terriberry" fullname="Timothy Terriberry">
<organization>Mozilla Corporation</organization>
<address>
<postal>
<street></street>
<city></city>
<region></region>
<code></code>
<country></country>
</postal>
<phone></phone>
<email>tterriberry@mozilla.com</email>
</address>
</author>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
55

56
<date day="16" month="June" year="2011" />
Jean-Marc Valin's avatar
Jean-Marc Valin committed
57
58
59
60
61
62
63

<area>General</area>

<workgroup></workgroup>

<abstract>
<t>
64
65
This document defines the Opus codec, designed for interactive speech and audio
 transmission over the Internet.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
66
67
68
69
70
71
72
73
</t>
</abstract>
</front>

<middle>

<section anchor="introduction" title="Introduction">
<t>
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
The Opus codec is a real-time interactive audio codec composed of a linear
 prediction (LP)-based layer and a Modified Discrete Cosine Transform
 (MDCT)-based layer.
The main idea behind using two layers is that in speech, linear prediction
 techniques (such as CELP) code low frequencies more efficiently than transform
 (e.g., MDCT) domain techniques, while the situation is reversed for music and
 higher speech frequencies.
Thus a codec with both layers available can operate over a wider range than
 either one alone and, by combining them, achieve better quality than either
 one individually.
</t>

<t>
The primary normative part of this specification is provided by the source code
 in <xref target="ref-implementation"></xref>.
89
90
91
92
In general, only the decoder portion of this software is normative, though a
 significant amount of code is shared by both the encoder and decoder.
<!--TODO: Forward reference conformance test-->
The decoder contains significant amounts of integer and fixed-point arithmetic
93
94
95
96
 which must be performed exactly, including all rounding considerations, so any
 useful specification must make extensive use of domain-specific symbolic
 language to adequately define these operations.
Additionally, any
Gregory Maxwell's avatar
Gregory Maxwell committed
97
98
99
100
101
conflict between the symbolic representation and the included reference
implementation must be resolved. For the practical reasons of compatibility and
testability it would be advantageous to give the reference implementation to
have priority in any disagreement. The C language is also one of the most
widely understood human-readable symbolic representations for machine
102
103
104
105
behavior.
For these reasons this RFC uses the reference implementation as the sole
 symbolic representation of the codec.
</t>
Gregory Maxwell's avatar
Gregory Maxwell committed
106

107
<!--TODO: C is not unambiguous; many parts are implementation-defined-->
Gregory Maxwell's avatar
Gregory Maxwell committed
108
109
<t>While the symbolic representation is unambiguous and complete it is not
always the easiest way to understand the codec's operation. For this reason
110
111
this document also describes significant parts of the codec in English and
takes the opportunity to explain the rationale behind many of the more
Gregory Maxwell's avatar
Gregory Maxwell committed
112
surprising elements of the design. These descriptions are intended to be
113
114
accurate and informative, but the limitations of common English sometimes
result in ambiguity, so it is expected that the reader will always read
Gregory Maxwell's avatar
Gregory Maxwell committed
115
116
them alongside the symbolic representation. Numerous references to the
implementation are provided for this purpose. The descriptions sometimes
117
differ from the reference in ordering or through mathematical simplification
118
wherever such deviation makes an explanation easier to understand.
Gregory Maxwell's avatar
Gregory Maxwell committed
119
120
For example, the right shift and left shift operations in the reference
implementation are often described using division and multiplication in the text.
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
In general, the text is focused on the "what" and "why" while the symbolic
representation most clearly provides the "how".
</t>

<section anchor="notation" title="Notation and Conventions">
<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.
</t>
<t>
Even when using floating-point, various operations in the codec require
 bit-exact fixed-point behavior.
The notation "Q<spanx style="emph">n</spanx>", where
 <spanx style="emph">n</spanx> is an integer, denotes the number of binary
 digits to the right of the decimal point in a fixed-point number.
For example, a signed Q14 value in a 16-bit word can represent values from
 -2.0 to 1.99993896484375, inclusive.
This notation is for informational purposes only.
Arithmetic, when described, always operates on the underlying integer.
E.g., the text will explicitly indicate any shifts required after a
 multiplication.
</t>
<t>
Expressions, where included in the text, follow C operator rules and
 precedence, with the exception that syntax like "2**n" is used to indicate 2
 raised to the power n.
The text also makes use of the following functions:
Gregory Maxwell's avatar
Gregory Maxwell committed
149
150
</t>

151
152
153
154
<section anchor="min" title="min(x,y)">
<t>
The smallest of two values x and y.
</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
155
156
</section>

157
158
159
160
161
<section anchor="max" title="max(x,y)">
<t>
The largest of two values x and y.
</t>
</section>
162

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
<section anchor="clamp" title="clamp(lo,x,hi)">
<figure align="center">
<artwork align="center"><![CDATA[
clamp(lo,x,hi) = max(lo,min(x,hi))
]]></artwork>
</figure>
<t>
With this definition, if lo&gt;hi, the lower bound is the one that is enforced.
</t>
</section>

<section anchor="sign" title="sign(x)">
<t>
The sign of x, i.e.,
<figure align="center">
<artwork align="center"><![CDATA[
          ( -1,  x < 0 ,
sign(x) = <  0,  x == 0 ,
          (  1,  x > 0 .
]]></artwork>
</figure>
</t>
</section>

187
<section anchor="log2" title="log2(f)">
188
<t>
189
The base-two logarithm of f.
190
</t>
191
</section>
192

193
194
195
196
197
198
199
200
201
<section anchor="ilog" title="ilog(n)">
<t>
The minimum number of bits required to store a positive integer n in two's
 complement notation, or 0 for a non-positive integer n.
<figure align="center">
<artwork align="center"><![CDATA[
          ( 0,                 n <= 0,
ilog(n) = <
          ( floor(log2(n))+1,  n > 0
202
]]></artwork>
203
204
205
206
207
208
209
210
211
212
213
</figure>
Examples:
<list style="symbols">
<t>ilog(-1) = 0</t>
<t>ilog(0) = 0</t>
<t>ilog(1) = 1</t>
<t>ilog(2) = 2</t>
<t>ilog(3) = 2</t>
<t>ilog(4) = 3</t>
<t>ilog(7) = 3</t>
</list>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
214
</t>
215
216
217
</section>

</section>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
218

219
</section>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
220

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<section anchor="overview" title="Opus Codec Overview">

<t>
The Opus codec scales from 6&nbsp;kb/s narrowband mono speech to 510&nbsp;kb/s
 fullband stereo music, with algorithmic delays ranging from 5&nbsp;ms to
 65.2&nbsp;ms.
At any given time, either the LP layer, the MDCT layer, or both, may be active.
It can seamlessly switch between all of its various operating modes, giving it
 a great deal of flexibility to adapt to varying content and network
 conditions without renegotiating the current session.
Internally, the codec always operates at a 48&nbsp;kHz sampling rate, though it
 allows input and output of various bandwidths, defined as follows:
</t>
<texttable>
<ttcol>Abbreviation</ttcol>
<ttcol align="right">Audio Bandwidth</ttcol>
<ttcol align="right">Sampling Rate (Effective)</ttcol>
<c>NB (narrowband)</c>       <c>4&nbsp;kHz</c>  <c>8&nbsp;kHz</c>
<c>MB (medium-band)</c>      <c>6&nbsp;kHz</c> <c>12&nbsp;kHz</c>
<c>WB (wideband)</c>         <c>8&nbsp;kHz</c> <c>16&nbsp;kHz</c>
<c>SWB (super-wideband)</c> <c>12&nbsp;kHz</c> <c>24&nbsp;kHz</c>
<c>FB (fullband)</c>        <c>20&nbsp;kHz</c> <c>48&nbsp;kHz</c>
</texttable>
244
<t>
245
246
247
248
249
These can be chosen independently on the encoder and decoder side, e.g., a
 fullband signal can be decoded as wideband, or vice versa.
This approach ensures a sender and receiver can always interoperate, regardless
 of the capabilities of their actual audio hardware.
</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
250

251
252
253
254
255
256
257
258
259
260
<t>
The LP layer is based on the
 <eref target='http://developer.skype.com/silk'>SILK</eref> codec
 <xref target="SILK"></xref>.
It supports NB, MB, or WB audio and frame sizes from 10&nbsp;ms to 60&nbsp;ms,
 and requires an additional 5.2&nbsp;ms look-ahead for noise shaping estimation
 (5&nbsp;ms) and internal resampling (0.2&nbsp;ms).
Like Vorbis and many other modern codecs, SILK is inherently designed for
 variable-bitrate (VBR) coding, though an encoder can with sufficient effort
 produce constant-bitrate (CBR) or near-CBR streams.
261
262
</t>

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<t>
The MDCT layer is based on the
 <eref target='http://www.celt-codec.org/'>CELT</eref>  codec
 <xref target="CELT"></xref>.
It supports sampling NB, WB, SWB, or FB audio and frame sizes from 2.5&nbsp;ms
 to 20&nbsp;ms, and requires an additional 2.5&nbsp;ms look-ahead due to the
 overlapping MDCT windows.
The CELT codec is inherently designed for CBR coding, but unlike many CBR
 codecs it is not limited to a set of predetermined rates.
It internally allocates bits to exactly fill any given target budget, and an
 encoder can produce a VBR stream by varying the target on a per-frame basis.
The MDCT layer is not used for speech when the audio bandwidth is WB or less,
 as it is not useful there.
On the other hand, non-speech signals are not always adequately coded using
 linear prediction, so for music only the MDCT layer should be used.
</t>
279

Jean-Marc Valin's avatar
Jean-Marc Valin committed
280
<t>
281
282
283
284
285
286
287
288
A hybrid mode allows the use of both layers simultaneously with a frame size of
 10 or 20&nbsp;ms and a SWB or FB audio bandwidth.
Each frame is split into a low frequency signal and a high frequency signal,
 with a cutoff of 8&nbsp;kHz.
The LP layer then codes the low frequency signal, followed by the MDCT layer
 coding the high frequency signal.
In the MDCT layer, all bands below 8&nbsp;kHz are discarded, so there is no
 coding redundancy between the two layers.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
289
290
291
</t>

<t>
292
293
294
295
At the decoder, the two decoder outputs are simply added together.
To compensate for the different look-aheads required by each layer, the CELT
 encoder input is delayed by an additional 2.7&nbsp;ms.
This ensures that low frequencies and high frequencies arrive at the same time.
296
297
298
299
300
301
This extra delay MAY be reduced by an encoder by using less lookahead for noise
 shaping or using a simpler resampler in the LP layer, but this will reduce
 quality.
However, the base 2.5&nbsp;ms look-ahead in the CELT layer cannot be reduced in
 the encoder because it is needed for the MDCT overlap, whose size is fixed by
 the decoder.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
302
303
304
</t>

<t>
305
306
307
308
309
Both layers use the same entropy coder, avoiding any waste from "padding bits"
 between them.
The hybrid approach makes it easy to support both CBR and VBR coding.
Although the LP layer is VBR, the bit allocation of the MDCT layer can produce
 a final stream that is CBR by using all the bits left unused by the LP layer.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
310
311
</t>

312
313
314
</section>

<section anchor="modes" title="Codec Modes">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
315
<t>
316
317
318
319
320
321
322
As described, the two layers can be combined in three possible operating modes:
<list style="numbers">
<t>A LP-only mode for use in low bitrate connections with an audio bandwidth of
 WB or less,</t>
<t>A hybrid (LP+MDCT) mode for SWB or FB speech at medium bitrates, and</t>
<t>An MDCT-only mode for very low delay speech transmission as well as music
 transmission.</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
323
</list>
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
A single packet may contain multiple audio frames, however they must share a
 common set of parameters, including the operating mode, audio bandwidth, frame
 size, and channel count.
A single-byte table-of-contents (TOC) header signals which of the various modes
 and configurations a given packet uses.
It is composed of a frame count code, "c", a stereo flag, "s", and a
 configuration number, "config", arranged as illustrated in
 <xref target="toc_byte"/>.
A description of each of these fields follows.
</t>

<figure anchor="toc_byte" title="The TOC byte">
<artwork align="center"><![CDATA[
 0
 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
| c |s| config  |
+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
344
345

<t>
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
The top five bits of the TOC byte, labeled "config", encode one of 32 possible
 configurations of operating mode, audio bandwidth, and frame size.
<xref target="config_bits"/> lists the parameters for each configuration.
</t>
<texttable anchor="config_bits" title="TOC Byte Configuration Parameters">
<ttcol>Configuration Number(s)</ttcol>
<ttcol>Mode</ttcol>
<ttcol>Bandwidth</ttcol>
<ttcol>Frame Size(s)</ttcol>
<c>0...3</c>   <c>LP-only</c>   <c>NB</c>  <c>10, 20, 40, 60&nbsp;ms</c>
<c>4...7</c>   <c>LP-only</c>   <c>MB</c>  <c>10, 20, 40, 60&nbsp;ms</c>
<c>8...11</c>  <c>LP-only</c>   <c>WB</c>  <c>10, 20, 40, 60&nbsp;ms</c>
<c>12...13</c> <c>Hybrid</c>    <c>SWB</c> <c>10, 20&nbsp;ms</c>
<c>14...15</c> <c>Hybrid</c>    <c>FB</c>  <c>10, 20&nbsp;ms</c>
<c>16...19</c> <c>MDCT-only</c> <c>NB</c>  <c>2.5, 5, 10, 20&nbsp;ms</c>
<c>20...23</c> <c>MDCT-only</c> <c>WB</c>  <c>2.5, 5, 10, 20&nbsp;ms</c>
<c>24...27</c> <c>MDCT-only</c> <c>SWB</c> <c>2.5, 5, 10, 20&nbsp;ms</c>
<c>28...31</c> <c>MDCT-only</c> <c>FB</c>  <c>2.5, 5, 10, 20&nbsp;ms</c>
</texttable>

<t>
One additional bit, labeled "s", is used to signal mono vs. stereo, with 0
 indicating mono and 1 indicating stereo.
The remaining two bits, labeled "c", code the number of frames per packet
 (codes 0 to 3) as follows:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
371
<list style="symbols">
372
<t>0:    1 frame in the packet</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
373
<t>1:    2 frames in the packet, each with equal compressed size</t>
374
375
<t>2:    2 frames in the packet, with different compressed sizes</t>
<t>3:    an arbitrary number of frames in the packet</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
376
377
378
</list>
</t>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
379
<t>
380
381
382
383
384
385
386
387
A well-formed Opus packet MUST contain at least one byte with the TOC
 information, though the frame(s) within a packet MAY be zero bytes long.
It must also obey various additional rules indicated by "MUST", "MUST NOT",
 etc., in this section.
A receiver MUST NOT process packets which violate these rules as normal Opus
 packets.
They are reserved for future applications, such as in-band headers (containing
 metadata, etc.) or multichannel support.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
388
389
</t>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
390
<t>
391
392
393
When a packet contains multiple VBR frames, the compressed length of one or
 more of these frames is indicated with a one or two byte sequence, with the
 meaning of the first byte as follows:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
394
<list style="symbols">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
395
<t>0:          No frame (DTX or lost packet)</t>
396
397
398
399
<!--TODO: Would be nice to be clearer about the distinction between "frame
 size" (in samples or ms) and "the compressed size of the frame" (in bytes).
"the compressed length of the frame" is maybe a little better, but not when we
 jump back and forth to talking about sizes.-->
400
401
<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
402
403
404
405
</list>
</t>

<t>
406
407
408
409
The maximum representable size is 255*4+255=1275&nbsp;bytes.
For 20&nbsp;ms frames, this represents a bitrate of 510&nbsp;kb/s, which is
 approximately the highest useful rate for lossily compressed fullband stereo
 music.
410
411
Beyond that point, lossless codecs would be more appropriate.
It is also roughly the maximum useful rate of the MDCT layer, as shortly
412
413
414
415
416
417
418
 thereafter additional bits no longer improve quality due to limitations on the
 codebook sizes.
No length is transmitted for the last frame in a VBR packet, or any of the
 frames in a CBR packet, as it can be inferred from the total size of the
 packet and the size of all other data in the packet.
However, it MUST NOT exceed 1275&nbsp;bytes, to allow for repacketization by
 gateways, conference bridges, or other software.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
419
420
421
</t>

<t>
422
423
424
For code 0 packets, the TOC byte is immediately followed by N-1&nbsp;bytes of
 compressed data for a single frame (where N is the size of the packet),
 as illustrated in <xref target="code0_packet"/>.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
425
</t>
426
427
428
429
430
431
432
433
434
435
436
437
438
<figure anchor="code0_packet" title="A Code 0 Packet" align="center">
<artwork align="center"><![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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0|0|s| config  |                                               |
+-+-+-+-+-+-+-+-+                                               |
|                    Compressed frame 1 (N-1 bytes)...          :
:                                                               |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
439
440

<t>
441
442
443
444
445
446
447
448
449
For code 1 packets, the TOC byte is immediately followed by the
 (N-1)/2&nbsp;bytes of compressed data for the first frame, followed by
 (N-1)/2&nbsp;bytes of compressed data for the second frame, as illustrated in
 <xref target="code1_packet"/>.
The number of payload bytes available for compressed data, N-1, MUST be even
 for all code 1 packets.
</t>
<figure anchor="code1_packet" title="A Code 1 Packet" align="center">
<artwork align="center"><![CDATA[
Jean-Marc Valin's avatar
Jean-Marc Valin committed
450
451
452
 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
453
454
455
456
457
458
459
460
461
462
|1|0|s| config  |                                               |
+-+-+-+-+-+-+-+-+                                               :
|             Compressed frame 1 ((N-1)/2 bytes)...             |
:                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               :
|             Compressed frame 2 ((N-1)/2 bytes)...             |
:                                               +-+-+-+-+-+-+-+-+
|                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Jean-Marc Valin's avatar
Jean-Marc Valin committed
463
464
]]></artwork>
</figure>
465
466
467
468
469
470
471
472
473
474

<t>
For code 2 packets, the TOC byte is followed by a one or two byte sequence
 indicating the the length of the first frame (marked N1 in the figure below),
 followed by N1 bytes of compressed data for the first frame.
The remaining N-N1-2 or N-N1-3&nbsp;bytes are the compressed data for the
 second frame.
This is illustrated in <xref target="code2_packet"/>.
The length of the first frame, N1, MUST be no larger than the size of the
 payload remaining after decoding that length for all code 2 packets.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
475
</t>
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
<figure anchor="code2_packet" title="A Code 2 Packet" align="center">
<artwork align="center"><![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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|0|1|s| config  | N1 (1-2 bytes):                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               :
|               Compressed frame 1 (N1 bytes)...                |
:                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                               |                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
|                     Compressed frame 2...                     :
:                                                               |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
493
494

<t>
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
For code 3 packets, the TOC byte is followed by a byte encoding the number of
 frames in the packet in bits 0 to 5 (marked "M" in the figure below), with bit
 6 indicating whether or not padding is inserted (marked "p" in the figure
 below), and bit 7 indicating VBR (marked "v" in the figure below).
M MUST NOT be zero, and the audio duration contained within a packet MUST NOT
 exceed 120&nbps;ms.
This limits the maximum frame count for any frame size to 48 (for 2.5&nbsp;ms
 frames), with lower limits for longer frame sizes.
<xref target="frame_count_byte"/> illustrates the layout of the frame count
 byte.
</t>
<figure anchor="frame_count_byte" title="The frame count byte">
<artwork align="center"><![CDATA[
 0
 0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
|     M     |p|v|
+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
<t>
When padding is used, the number of bytes of padding is encoded in the
 bytes following the frame count byte.
Values from 0...254 indicate that 0...254&nbsp;bytes of padding are included,
 in addition to the byte(s) used to indicate the size of the padding.
If the value is 255, then the size of the additional padding is 254&nbsp;bytes,
 plus the padding value encoded in the next byte.
The additional padding bytes appear at the end of the packet, and SHOULD be set
 to zero by the encoder, however the decoder MUST accept any value for the
 padding bytes.
By using code 255 multiple times, it is possible to create a packet of any
 specific, desired size.
Let P be the total amount of padding, including both the trailing padding bytes
 themselves and the header bytes used to indicate how many there are.
Then P MUST be no more than N-2 for CBR packets, or N-M-1 for VBR packets.
</t>
<t>
In the CBR case, the compressed length of each frame in bytes is equal to the
 number of remaining bytes in the packet after subtracting the (optional)
 padding, (N-2-P), divided by M.
This number MUST be an integer multiple of M.
The compressed data for all M frames then follows, each of size
 (N-2-P)/M&nbsp;bytes, as illustrated in <xref target="code3cbr_packet"/>.
</t>

<figure anchor="code3cbr_packet" title="A CBR Code 3 Packet" align="center">
<artwork align="center"><![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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1|1|s| config  |     M     |p|0|  Padding length (Optional)    :
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:            Compressed frame 1 ((N-2-P)/M bytes)...            :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:            Compressed frame 2 ((N-2-P)/M bytes)...            :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:                              ...                              :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:            Compressed frame M ((N-2-P)/M bytes)...            :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
:                     Padding (Optional)...                     |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>

<t>
In the VBR case, the (optional) padding length is followed by M-1 frame
 lengths (indicated by "N1" to "N[M-1]" in the figure below), each encoded in a
 one or two byte sequence as described above.
The packet MUST contain enough data for the M-1 lengths after the (optional)
 padding, and the sum of these lengths MUST be no larger than the number of
 bytes remaining in the packet after decoding them.
The compressed data for all M frames follows, each frame consisting of the
 indicated number of bytes, with the final frame consuming any remaining bytes
 before the final padding, as illustrated in <xref target="code3cbr_packet"/>.
The number of header bytes (TOC byte, frame count byte, padding length bytes,
 and frame length bytes), plus the length of the first M-1 frames themselves,
 plus the length of the padding MUST be no larger than N, the total size of the
 packet.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
582
583
</t>

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
<figure anchor="code3vbr_packet" title="A VBR Code 3 Packet" align="center">
<artwork align="center"><![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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1|1|s| config  |     M     |p|1| Padding length (Optional)     :
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
: N1 (1-2 bytes): N2 (1-2 bytes):     ...       : N[M-1]        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:               Compressed frame 1 (N1 bytes)...                :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:               Compressed frame 2 (N2 bytes)...                :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:                              ...                              :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
:                     Compressed frame M...                     :
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
:                     Padding (Optional)...                     |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>

<section anchor="examples" title="Examples">
Jean-Marc Valin's avatar
Jean-Marc Valin committed
615
<t>
616
617
618
Simplest case, one NB mono 20&nbsp;ms SILK frame:
</t>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
619
620
621
622
623
<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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
624
|0|0|0|    1    |               compressed data...              :
Jean-Marc Valin's avatar
Jean-Marc Valin committed
625
626
627
628
629
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>

<t>
630
Two FB mono 5&nbsp;ms CELT frames of the same compressed size:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
631
632
633
634
635
636
637
</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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
638
|1|0|0|   29    |               compressed data...              :
Jean-Marc Valin's avatar
Jean-Marc Valin committed
639
640
641
642
643
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>

<t>
644
Two FB mono 20&nbsp;ms hybrid frames of different compressed size:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
645
646
647
648
649
650
651
</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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
652
653
654
|1|1|0|   15    |     2     |0|1|      N1       |               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+               |
|                       compressed data...                      :
Jean-Marc Valin's avatar
Jean-Marc Valin committed
655
656
657
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
658
659
660

<t>
Four FB stereo 20&nbsp;ms CELT frames of the same compressed size:
Jean-Marc Valin's avatar
Jean-Marc Valin committed
661
</t>
662
663
664
665
666
667
668
669
670
671

<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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1|1|1|   31    |     4     |0|0|      compressed data...       :
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
672
673
674
</section>


675
676
</section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
677
<section title="Opus Decoder">
678
<t>
679
The Opus decoder consists of two main blocks: the SILK decoder and the CELT decoder.
Jean-Marc Valin's avatar
Jean-Marc Valin committed
680
681
682
The output of the Opus decode is the sum of the outputs from the SILK and CELT decoders
with proper sample rate conversion and delay compensation as illustrated in the
block diagram below. At any given time, one or both of the SILK and CELT decoders
683
684
may be active.
</t>
685
686
<figure>
<artwork>
687
<![CDATA[
Jean-Marc Valin's avatar
Jean-Marc Valin committed
688
689
690
691
692
693
694
695
696
697
698
                       +-------+    +----------+
                       | SILK  |    |  sample  |
                    +->|encoder|--->|   rate   |----+
bit-    +-------+   |  |       |    |conversion|    v
stream  | Range |---+  +-------+    +----------+  /---\  audio
------->|decoder|                                 | + |------>
        |       |---+  +-------+    +----------+  \---/
        +-------+   |  | CELT  |    | Delay    |    ^
                    +->|decoder|----| compens- |----+
                       |       |    | ation    |
                       +-------+    +----------+
699
700
701
]]>
</artwork>
</figure>
702

Jean-Marc Valin's avatar
Jean-Marc Valin committed
703
<section anchor="range-decoder" title="Range Decoder">
704
<t>
705
Opus uses an entropy coder based on <xref target="range-coding"></xref>,
706
707
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
708
digits in any base instead of with bits,
709
710
711
712
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>
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
Symbols may also be coded as <spanx style="emph">raw bits</spanx> packed
 directly into the bitstream, bypassing the range coder.
These are packed backwards starting at the end of the frame.
This reduces complexity and makes the stream more resilient to bit errors, as
 corruption in the raw bits will not desynchronize the decoding process, unlike
 corruption in the input to the range decoder.
Raw bits are only used in the CELT layer.
</t>
<t>
Each symbol coded by the range coder is drawn from a finite alphabet and coded
 in a separate <spanx style="emph">context</spanx>, which describes the size of
 the alphabet and the relative frequency of each symbol in that alphabet.
Opus only uses static contexts.
They are not adapted to the statistics of the data as it is coded.
</t>
<t>
The parameters needed to encode or decode a symbol in a given context are
 represented by a three-tuple (fl,fh,ft), with
 0 &lt;= fl &lt; fh &lt;= ft &lt;= 65535.
The values of this tuple are derived from the probability model for the
 symbol, represented by traditional <spanx style="emph">frequency counts</spanx>
 (although, since Opus uses static contexts, these are not updated as symbols
 are decoded).
Let f[i] be the frequency of the <spanx style="emph">i</spanx>th symbol in a
 context with <spanx style="emph">n</spanx> symbols total.
Then the three-tuple corresponding to the <spanx style="emph">k</spanx>th
 symbol is given by
</t>
<figure align="center">
742
<artwork align="center"><![CDATA[
743
744
745
746
747
     k-1                             n-1
     __                              __
fl = \  f[i],  fh = fl + f[k],  ft = \  f[i]
     /_                              /_
     i=0                             i=0
748
]]></artwork>
749
</figure>
750
<t>
751
752
753
754
755
756
757
758
759
760
761
The range decoder extracts the symbols and integers encoded using the range
 encoder in <xref target="range-encoder"/>.
The range decoder maintains an internal state vector composed of the two-tuple
 (val,rng), representing the difference between the high end of the current
 range and the actual coded value, minus one, and the size of the current
 range, respectively.
Both val and rng are 32-bit unsigned integer values.
The decoder initializes rng to 128 and initializes val to 127 minus the top 7
 bits of the first input octet.
It then immediately normalizes the range using the procedure described in
 <xref target="range-decoder-renorm"/>.
762
763
</t>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
764
<section anchor="decoding-symbols" title="Decoding Symbols">
765
<t>
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
Decoding a symbol is a two-step process.
The first step determines a 16-bit unsigned value fs, which 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.
</t>
<t>
The first step is implemented by ec_decode() (entdec.c), which computes
 fs = ft - min(val/(rng/ft)+1, ft).
The divisions here are exact integer division.
</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.
It uses this tuple to update val according to
 val = val - (rng/ft)*(ft-fh).
If fl is greater than zero, then the decoder updates rng using
 rng = (rng/ft)*(fh-fl).
Otherwise, it updates rng using rng = rng - (rng/ft)*(ft-fh).
After these updates, implemented by ec_dec_update() (entdec.c), it normalizes
 the range using the procedure in the next section, and returns the index of
 the identified symbol.
</t>
<t>
With this formulation, all the truncation error from using finite precision
 arithmetic accumulates in symbol 0.
This makes the cost of coding a 0 slightly smaller, on average, than the
 negative log of its estimated probability and makes the cost of coding any
 other symbol slightly larger.
When contexts are designed so that 0 is the most probable symbol, which is
 often the case, this strategy minimizes the inefficiency introduced by the
 finite precision.
</t>

<section anchor="range-decoder-renorm" title="Renormalization">
<t>
To normalize the range, the decoder repeats the following process, implemented
 by ec_dec_normalize() (entdec.c), until rng > 2**23.
If rng is already greater than 2**23, the entire process is skipped.
First, it sets rng to (rng&lt;&lt;8).
Then it reads the next 8 bits of input 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 as the remaining bits of sym.
If no more input octets remain, it uses zero bits instead.
Then, it sets val to (val&lt;&lt;8)+(255-sym)&amp;0x7FFFFFFF.
</t>
<t>
It is normal and expected that the range decoder will read several bytes
 into the raw bits data (if any) at the end of the packet by the time the frame
 is completely decoded, as illustrated in <xref target="finalize-example"/>.
This same data MUST also be returned as raw bits when requested.
The encoder is expected to terminate the stream in such a way that the decoder
 will decode the intended values regardless of the data contained in the raw
 bits.
<xref target="encoder-finalizing"/> describes a procedure for doing this.
If the range decoder consumes all of the bytes belonging to the current frame,
 it MUST continue to use zero when any further input bytes are required, even
 if there is additional data in the current packet from padding or other
 frames.
</t>

<figure anchor="finalize-example" title="Illustrative example of raw bits
 overlapping range coder data">
<artwork align="center"><![CDATA[
 n               n+1             n+2             n+3
 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
:     | <----------- Overlap region ------------> |             :
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
      ^                                           ^
      |   End of data buffered by the range coder |
...-----------------------------------------------+
      |
      | End of data consumed by raw bits
      +-------------------------------------------------------...
]]></artwork>
</figure>
</section>
</section>

<section anchor="decoding-alternate" title="Alternate Decoding Methods">
847
<t>
848
849
850
The reference implementation uses three additional decoding methods that are
 exactly equivalent to the above, but make assumptions and simplifications that
 allow for a more efficient implementation.
851
</t>
852
<section title="ec_decode_bin()">
853
<t>
854
855
The first is ec_decode_bin() (entdec.c), defined using the parameter ftb
 instead of ft.
856
857
It is mathematically equivalent to calling ec_decode() with
 ft = (1&lt;&lt;ftb), but avoids one of the divisions.
858
</t>
859
860
861
862
863
864
865
866
867
868
869
870
871
872
</section>
<section title="ec_dec_bit_logp()">
<t>
The next is ec_dec_bit_logp() (entdec.c), which decodes a single binary symbol,
 replacing both the ec_decode() and ec_dec_update() steps.
The context is described by a single parameter, logp, which is the absolute
 value of the base-2 logarithm of the probability of a "1".
It is mathematically equivalent to calling ec_decode() with
 ft = (1&lt;&lt;logp), followed by ec_dec_update() with
 fl = 0, fh = (1&lt;&lt;logp)-1, ft = (1&lt;&lt;logp) if the returned value
 of fs is less than (1&lt;&lt;logp)-1 (a "0" was decoded), and with
 fl = (1&lt;&lt;logp)-1, fh = ft = (1&lt;&lt;logp) otherwise (a "1" was
 decoded).
The implementation requires no multiplications or divisions.
873
874
</t>
</section>
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
<section title="ec_dec_icdf()">
<t>
The last is ec_dec_icdf() (entdec.c), which decodes a single symbol with a
 table-based context of up to 8 bits, also replacing both the ec_decode() and
 ec_dec_update() steps, as well as the search for the decoded symbol in between.
The context is described by two parameters, an icdf
 (<spanx style="emph">inverse</spanx> cumulative distribution function)
 table and ftb.
As with ec_decode_bin(), (1&lt;&lt;ftb) is equivalent to ft.
idcf[k], on the other hand, stores (1&lt;&lt;ftb)-fh for the kth symbol in
 the context, which is equal to (1&lt;&lt;ftb)-fl for the (k+1)st symbol.
fl for the 0th symbol is assumed to be 0, and the table is terminated by a
 value of 0 (where fh == ft).
</t>
<t>
The function is mathematically equivalent to calling ec_decode() with
 ft = (1&lt;&lt;ftb), using the returned value fs to search the table for the
 first entry where fs &lt; (1&lt;&lt;ftb)-icdf[k], and calling
 ec_dec_update() with fl = (1&lt;&lt;ftb)-icdf[k-1] (or 0 if k == 0),
 fh = (1&lt;&lt;ftb)-idcf[k], and ft = (1&lt;&lt;ftb).
Combining the search with the update allows the division to be replaced by a
 series of multiplications (which are usually much cheaper), and using an
 inverse CDF allows the use of an ftb as large as 8 in an 8-bit table without
 any special cases.
This is the primary interface with the range decoder in the SILK layer, though
 it is used in a few places in the CELT layer as well.
901
</t>
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
<t>
Although icdf[k] is more convenient for the code, the frequency counts, f[k],
 are a more natural representation of the probability distribution function
 (PDF) for a given symbol.
Therefore this draft lists the latter, not the former, when describing the
 context in which a symbol is coded as a list, e.g., {4, 4, 4, 4}/16 for a
 uniform context with four possible values and ft=16.
The value of ft after the slash is always the sum of the entries in the PDF,
 but is included for convenience.
Contexts with identical probabilities, f[k]/ft, but different values of ft
 (or equivalently, ftb) are not the same, and cannot, in general, be used in
 place of one another.
An icdf table is also not capable of representing a PDF where the first symbol
 has 0 probability.
In such contexts, ec_dec_icdf() can decode the symbol by using a table that
 drops the entries for any initial zero-probability values and adding the
 constant offset of the first value with a non-zero probability to its return
 value.
</t>
921
</section>
922
</section>
923
924
925

<section anchor="decoding-bits" title="Decoding Raw Bits">
<t>
926
927
928
929
930
931
932
933
934
935
936
937
938
The raw bits used by the CELT layer are packed at the end of the packet, with
 the least significant bit of the first value to be packed in the least
 significant bit of the last byte, filling up to the most significant bit in
 the last byte, and continuing on to the least significant bit of the
 penultimate byte, and so on.
The reference implementation reads them using ec_dec_bits() (entdec.c).
Because the range decoder must read several bytes ahead in the stream, as
 described in <xref target="range-decoder-renorm"/>, the input consumed by the
 raw bits MAY overlap with the input consumed by the range coder, and a decoder
 MUST allow this.
The format should render it impossible to attempt to read more raw bits than
 there are actual bits in the frame, though a decoder MAY wish to check for
 this and report an error.
939
</t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
940
</section>
941
942

<section anchor="decoding-ints" title="Decoding Uniformly Distributed Integers">
943
<t>
944
945
946
947
948
949
950
951
952
953
954
955
The ec_dec_uint() (entdec.c) function decodes one of ft equiprobable values in
 the range 0 to ft-1, inclusive, each with a frequency of 1, where ft may be as
 large as 2**32-1.
Because ec_decode() is limited to a total frequency of 2**16-1, this is split
 up into a range coded symbol representing up to 8 of the high bits of the
 value, and, if necessary, raw bits representing the remaining bits.
The limit of 8 bits in the range coded symbol is a trade-off between
 implementation complexity, modeling error (since the symbols no longer truly
 have equal coding cost) and rounding error introduced by the range coder
 itself (which gets larger as more bits are included).
Using raw bits reduces the maximum number of divisions required in the worst
 case, but means that it may be possible to decode a value outside the range
956
 0 to ft-1, inclusive.
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
</t>

<t>
ec_dec_uint() takes a single, positive parameter, ft, which is not necessarily
 a power of two, and returns an integer, t, whose value lies between 0 and
 ft-1, inclusive.
Let ftb = ilog(ft-1), i.e., the number of bits required to store ft-1 in two's
 complement notation.
If ftb is 8 or less, then t is decoded with t = ec_decode(ft), and the range
 coder state is updated using the three-tuple (t,t+1,ft).
</t>
<t>
If ftb is greater than 8, then the top 8 bits of t are decoded using
 t = ec_decode((ft-1&gt;&gt;ftb-8)+1),
 the decoder state is updated using the three-tuple
 (t,t+1,(ft-1&gt;&gt;ftb-8)+1), and the remaining bits are decoded as raw bits,
 setting t = t&lt;&lt;ftb-8|ec_dec_bits(ftb-8).
If, at this point, t >= ft, then the current frame is corrupt.
In that case, the decoder should assume there has been an error in the coding,
 decoding, or transmission and SHOULD take measures to conceal the
 error and/or report to the application that a problem has occurred.
978
</t>
979

980
981
982
</section>

<section anchor="decoder-tell" title="Current Bit Usage">
983
<t>
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
The bit allocation routines in the CELT decoder need a conservative upper bound
 on the number of bits that have been used from the current frame thus far,
 including both range coder bits and raw bits.
This drives allocation decisions that must match those made in the encoder.
The upper bound is computed in the reference implementation to whole-bit
 precision by the function ec_tell() (entcode.h) and to fractional 1/8th bit
 precision by the function ec_tell_frac() (entcode.c).
Like all operations in the range coder, it must be implemented in a bit-exact
 manner, and must produce exactly the same value returned by the same functions
 in the encoder after encoding the same symbols.
</t>
<t>
ec_tell() is guaranteed to return ceil(ec_tell_frac()/8.0).
In various places the codec will check to ensure there is enough room to
 contain a symbol before attempting to decode it.
In practice, although the number of bits used so far is an upper bound,
 decoding a symbol whose probability model suggests it has a worst-case cost of
 p 1/8th bits may actually advance the return value of ec_tell_frac() by
 p-1, p, or p+1 1/8th bits, due to approximation error in that upper bound,
 truncation error in the range coder, and for large values of ft, modeling
 error in ec_dec_uint().
</t>
<t>
However, this error is bounded, and periodic calls to ec_tell() or
 ec_tell_frac() at precisely defined points in the decoding process prevent it
 from accumulating.
For a symbol that requires a whole number of bits (i.e., ft/(fh-fl) is a power
 of two, including values of ft larger than 2**8 with ec_dec_uint()), and there
 are at least p 1/8th bits available, decoding the symbol will never advance
 the decoder past the end of the frame, i.e., will never
 <spanx style="emph">bust</spanx> the budget.
Frames contain a whole number of bits, and the return value of ec_tell_frac()
 will only advance by more than p 1/8th bits in this case if there was a
 fractional number of bits remaining, and by no more than the fractional part.
However, when p is not a whole number of bits, an extra 1/8th bit is required
 to ensure decoding the symbol will not bust.
</t>
<t>
The reference implementation keeps track of the total number of whole bits that
 have been processed by the decoder so far in a variable nbits_total, including
 the (possibly fractional number of bits) that are currently buffered (but not
 consumed) inside the range coder.
nbits_total is initialized to 33 just after the initial range renormalization
 process completes (or equivalently, it can be initialized to 9 before the
 first renormalization).
The extra two bits over the actual amount buffered by the range coder
 guarantees that it is an upper bound and that there is enough room for the
 encoder to terminate the stream.
Each iteration through the range coder's renormalization loop increases
 nbits_total by 8.
Reading raw bits increases nbits_total by the number of raw bits read.
</t>

<section anchor="ec_tell" title="ec_tell()">
<t>
The whole number of bits buffered in rng may be estimated via l = ilog(rng).
ec_tell() then becomes a simple matter of removing these bits from the total.
It returns (nbits_total - l).
</t>
<t>
In a newly initialized decoder, before any symbols have been read, this reports
 that 1 bit has been used.
This is the bit reserved for termination of the encoder.
1047
1048
1049
</t>
</section>

1050
<section anchor="ec_tell_frac" title="ec_tell_frac()">
1051
<t>
1052
1053
ec_tell_frac() estimates the number of bits buffered in rng to fractional
 precision.
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
Since rng must be greater than 2**23 after renormalization, l must be at least
 24.
Let r = rng&gt;&gt;(l-16), so that 32768 &lt;= r &lt; 65536, an unsigned Q15
 value representing the fractional part of rng.
Then the following procedure can be used to add one bit of precision to l.
First, update r = r*r&gt;&gt;15.
Then add the 16th bit of r to l via l = 2*l + (r&gt;&gt;16).
Finally, if this bit was a 1, reduce r by a factor of two via r = r&gt;&gt;1,
 so that it once again lies in the range 32768 &lt;= r &lt; 65536.
</t>
<t>
This procedure is repeated three times to extend l to 1/8th bit precision.
ec_tell_frac() then returns (nbits_total*8 - l).
1067
1068
1069
</t>
</section>

1070
1071
</section>

1072
1073
</section>

1074
1075
1076
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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
<section anchor='outline_decoder' title='SILK Decoder'>
<t>
The LP layer uses a modified version of the SILK codec (herein simply called
 "SILK"), which has a relatively traditional Code-Excited Linear Prediction
 (CELP) structure.
It runs in NB, MB, and WB modes internally.
When used in a hybrid frame in SWB or FB mode, the LP layer itself still only
 runs in WB mode.
</t>
<t>
Internally, the LP layer of a single Opus frame is composed of either a single
 10&nbsp;ms SILK frame or between one and three 20&nbsp;ms SILK frames.
Each SILK frame is in turn composed of either two or four 5&nbsp;ms subframes.
Optional Low Bit-Rate Redundancy (LBRR) frames, which are redundant copies of
 the previous SILK frames, may appear to aid in recovery from packet loss.
If present, these appear before the regular SILK frames.
All of these frames and subframes are decoded from the same range coder, with
 no padding between them.
Thus packing multiple SILK frames in a single Opus frame saves, on average,
 half a byte per SILK frame.
It also allows some parameters to be predicted from prior SILK frames in the
 same Opus frame, since this does not degrade packet loss robustness (beyond
 any penalty for merely using larger packets).
</t>

<t>
Stereo support in SILK uses a variant of mid-side coding, allowing a mono
 decoder to simply decode the mid channel.
However, the data for the two channels is interleaved, so a mono decoder must
 still unpack the data for the side channel.
It would be required to do so anyway for hybrid Opus frames, or to support
 decoding individual 20&nbsp;ms frames.
</t>

<texttable anchor="silk_symbols">
<ttcol align="center">Symbol(s)</ttcol>
<ttcol align="center">PDF</ttcol>
<ttcol align="center">Condition</ttcol>
<c>VAD flags</c>     <c>{1, 1}/2</c>                    <c></c>
<c>LBRR flag</c>     <c>{1, 1}/2</c>                    <c></c>
<c>Per-frame LBRR flags</c> <c><xref target="silk_lbrr_flags"/></c> <c><xref target="silk_lbrr_flags"/></c>
<c>Frame Type</c>    <c><xref target="silk_frame_type"/></c>    <c></c>
<c>Gain index</c>    <c><xref target="silk_gains"/></c> <c></c>
<postamble>
Order of the symbols in the SILK section of the bit-stream.
</postamble>
</texttable>

<section title="Decoder Modules">
<t>
An overview of the decoder is given in <xref target="decoder_figure"/>.
</t>
<figure align="center" anchor="decoder_figure">
<artwork align="center">
<![CDATA[
1129
1130

   +---------+    +------------+
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
-->| Range   |--->| Decode     |---------------------------+
 1 | Decoder | 2  | Parameters |----------+       5        |
   +---------+    +------------+     4    |                |
                       3 |                |                |
                        \/               \/               \/
                  +------------+   +------------+   +------------+
                  | Generate   |-->| LTP        |-->| LPC        |-->
                  | Excitation |   | Synthesis  |   | Synthesis  | 6
                  +------------+   +------------+   +------------+

1: Range encoded bitstream
2: Coded parameters
3: Pulses and gains
4: Pitch lags and LTP coefficients
5: LPC coefficients
6: Decoded signal
]]>
1148
1149
1150
</artwork>
<postamble>Decoder block diagram.</postamble>
</figure>
1151

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1152
          <section title='Range Decoder'>
1153
            <t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1154
              The range decoder decodes the encoded parameters from the received bitstream. Output from this function includes the pulses and gains for the excitation signal generation, as well as LTP and LSF codebook indices, which are needed for decoding LTP and LPC coefficients needed for LTP and LPC synthesis filtering the excitation signal, respectively.
1155
1156
1157
            </t>
          </section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1158
          <section title='Decode Parameters'>
1159
            <t>
1160
              Pulses and gains are decoded from the parameters that were decoded by the range decoder.
1161
            </t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1162

1163
            <t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1164
1165
1166
              When a voiced frame is decoded and LTP codebook selection and indices are received, LTP coefficients are decoded using the selected codebook by choosing the vector that corresponds to the given codebook index in that codebook. This is done for each of the four subframes.
              The LPC coefficients are decoded from the LSF codebook by first adding the chosen vectors, one vector from each stage of the codebook. The resulting LSF vector is stabilized using the same method that was used in the encoder, see
              <xref target='lsf_stabilizer_overview_section' />. The LSF coefficients are then converted to LPC coefficients, and passed on to the LPC synthesis filter.
1167
1168
1169
            </t>
          </section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1170
          <section title='Generate Excitation'>
1171
            <t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1172
              The pulses signal is multiplied with the quantization gain to create the excitation signal.
1173
1174
1175
            </t>
          </section>

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1176
          <section title='LTP Synthesis'>
1177
            <t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1178
1179
              For voiced speech, the excitation signal e(n) is input to an LTP synthesis filter that will recreate the long term correlation that was removed in the LTP analysis filter and generate an LPC excitation signal e_LPC(n), according to
              <figure align="center">
1180
1181
                <artwork align="center">
                  <![CDATA[
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1182
1183
                   d
                  __
1184
e_LPC(n) = e(n) + \  e_LPC(n - L - i) * b_i,
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1185
1186
                  /_
                 i=-d
1187
1188
1189
]]>
                </artwork>
              </figure>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1190
              using the pitch lag L, and the decoded LTP coefficients b_i.
1191

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1192
              For unvoiced speech, the output signal is simply a copy of the excitation signal, i.e., e_LPC(n) = e(n).
1193
            </t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1194
          </section>
1195

Jean-Marc Valin's avatar
Jean-Marc Valin committed
1196
          <section title='LPC Synthesis'>
1197
            <t>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1198
              In a similar manner, the short-term correlation that was removed in the LPC analysis filter is recreated in the LPC synthesis filter. The LPC excitation signal e_LPC(n) is filtered using the LTP coefficients a_i, according to
1199
1200
1201
              <figure align="center">
                <artwork align="center">
                  <![CDATA[
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1202
1203
                 d_LPC
                  __
1204
y(n) = e_LPC(n) + \  y(n - i) * a_i,
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1205
1206
1207
                  /_
                  i=1
]]>
1208
1209
                </artwork>
              </figure>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1210
              where d_LPC is the LPC synthesis filter order, and y(n) is the decoded output signal.
1211
1212
            </t>
          </section>
Jean-Marc Valin's avatar
Jean-Marc Valin committed
1213
        </section>
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614

<!--TODO: Document mandated decoder resets-->

<section title="Header Bits">
<t>
The LP layer begins with two to eight header bits, decoded in silk_Decode()
 (silk_dec_API.c).
These consist of one Voice Activity Detection (VAD) bit per frame (up to 3),
 followed by a single flag indicating the presence of LBRR frames.
For a stereo packet, these flags correspond to the mid channel, and a second
 set of flags is included for the side channel.
</t>
<t>
Because these are the first symbols decoded by the range coder, they can be
 extracted directly from the upper bits of the first byte of compressed data.
Thus, a receiver can determine if an Opus frame contains any active SILK frames
 or if it contains LBRR frames without the overhead of using the range decoder.
</t>
</section>

<section anchor="silk_lbrr_flags" title="LBRR Flags">
<t>
If an Opus frame contains more than one SILK frame, then for each channel that
 has its LBRR flag set, a set of per-frame LBRR flags is decoded.
When there are two SILK frames present, the 2-frame LBRR flag PDF from
 <xref target="silk_symbols"/> is used, and when there are three SILK frames
 the 3-frame LBRR flag PDF is used.
For each channel, the resulting 2- or 3-bit integer contains the corresponding
 LBRR flag for each frame, packed in order from the LSb to the MSb.
</t>
<t>
LBRR frames do not include their own separate VAD flags.
An LBRR frame is only meant to be transmitted for active speech, thus all LBRR
 frames are treated as active.
</t>
</section>

<section title="SILK/LBRR Frame Contents">
<t>
<!--TODO:-->
Each SILK frame or LBRR frame includes a set of side information...
</t>
<section anchor="silk_frame_type" title="Frame Type">
<t>
Each SILK frame or LBRR frame begins with a single
 <spanx style="emph">frame type</spanx> symbol that jointly codes the signal
 type and quantization offset type of the corresponding frame.
If the current frame is an normal SILK frame whose VAD bit was not set (an
 <spanx style="emph">inactive</spanx> frame), then the frame type symbol takes
 on the value either 0 or 1 and is decoded using the first PDF in
 <xref target="silk_frame_type_pdfs"/>.
If the frame is an LBRR frame or a normal SILK frame whose VAD flag was set (an
 <spanx style="emph">active</spanx> frame), then the symbol ranges from 2 to 5,
 inclusive, and is decoded using the second PDF in
 <xref target="silk_frame_type_pdfs"/>.
<xref target="silk_frame_type_table"/> translates between the value of the
 frame type symbol and the corresponding signal type and quantization offset
 type.
</t>

<texttable anchor="silk_frame_type_pdfs" title="Frame Type PDFs">
<ttcol>VAD Flag</ttcol>
<ttcol>PDF</ttcol>
<c>Inactive</c>       <c>{26, 230, 0, 0, 0, 0}/256</c>
<c>Active or LBRR</c> <c>{0, 0, 24, 74, 148, 10}/256</c>
</texttable>

<texttable anchor="silk_frame_type_table"
 title="Signal Type and Quantization Offset Type from Frame Type">
<ttcol>Frame Type</ttcol>
<ttcol>Signal Type</ttcol>
<ttcol align="right">Quantization Offset Type</ttcol>
<c>0</c> <c>Non-speech</c> <c>0</c>
<c>1</c> <c>Non-speech</c> <c>1</c>
<c>2</c> <c>Unvoiced</c>   <c>0</c>
<c>3</c> <c>Unvoiced</c>   <c>1</c>
<c>4</c> <c>Voiced</c>     <c>0</c>
<c>5</c> <c>Voiced</c>     <c>1</c>
</texttable>

</section>

<section anchor="silk_gains" title="Sub-Frame Gains">
<t>
A separate quantization gain is coded for each 5&nbsp;ms subframe.
These gains control the step size between quantization levels of the excitation
 signal and, therefore, the quality of the reconstruction.
They are independent of the pitch gains coded for voiced frames.
The quantization gains are themselves uniformly quantized to 6&nbsp;bits on a
 log scale, giving them a resolution of approximately 1.369&nbsp;dB and a range
 of approximately 1.94&nbsp;dB to 88.21&nbsp;dB.
For the first SILK frame, the first LBRR frame, or an LBRR frame where the
 previous LBRR frame was not coded, an independent coding method is used for
 the first subframe.
The 3 most significant bits of the quantization gain are decoded using a PDF
 selected from <xref target="silk_independent_gain_msb_pdfs"/> based on the
 decoded signal type.
</t>

<texttable anchor="silk_independent_gain_msb_pdfs"
 title="PDFs for Independent Quantization Gain MSb Coding">
<ttcol align="left">Signal Type</ttcol>
<ttcol align="left">PDF</ttcol>
<c>Non-speech</c> <c>{32, 112, 68, 29, 12,  1,  1, 1}/256</c>
<c>Unvoiced</c>   <c>{2,   17, 45, 60, 62, 47, 19, 4}/256</c>
<c>Voiced</c>     <c>{1,    3, 26, 71, 94, 50,  9, 2}/256</c>
</texttable>

<t>
The 3 least significant bits are decoded using a uniform PDF:
</t>
<texttable anchor="silk_independent_gain_lsb_pdf"
 title="PDF for Independent Quantization Gain LSb Coding">
<ttcol align="left">PDF</ttcol>
<c>{32, 32, 32, 32, 32, 32, 32, 32}/256</c>
</texttable>

<t>
For all other subframes (including the first subframe of the frame when
 not using independent coding), the quantization gain is coded relative to the
 gain from the previous subframe.
The PDF in <xref target="silk_delta_gain_pdf"/> yields a delta gain index
 between 0 and 40, inclusive.
</t>
<texttable anchor="silk_delta_gain_pdf"
 title="PDF for Delta Quantization Gain Coding">
<ttcol align="left">PDF</ttcol>
<c>{6,   5,  11,  31, 132,  21,   8,   4,
    3,   2,   2,   2,   1,   1,   1,   1,
    1,   1,   1,   1,   1,   1,   1,   1,
    1,   1,   1,   1,   1,   1,   1,   1,
    1,   1,   1,   1,   1,   1,   1,   1,   1}/256</c>
</texttable>
<t>
The following formula translates this index into a quantization gain for the
 current subframe using the gain from the previous subframe:
</t>
<figure align="center">
<artwork align="center"><![CDATA[
log_gain = min(max(2*gain_index - 16,
                   previous_log_gain + gain_index - 4), 63)
]]></artwork>
</figure>
<t>
silk_gains_dequant() (silk_gain_quant.c) dequantizes the gain for the
 <spanx style="emph">k</spanx>th subframe and converts it into a linear Q16
 scale factor via
</t>
<figure align="center">
<artwork align="center"><![CDATA[
 gain_Q16[k] = silk_log2lin((0x1D1C71*log_gain>>16) + 2090)
]]></artwork>
</figure>
<t>
The function silk_log2lin() (silk_log2lin.c) computes an approximation of
 of 2**(inLog_Q7/128.0), where inLog_Q7 is its Q7 input.
Let i = inLog_Q7&gt;&gt;7 be the integer part of inLogQ7 and
 f = inLog_Q7&amp;127 be the fractional part.
Then, if i &lt; 16, then
<figure align="center">
<artwork align="center"><![CDATA[
 (1<<i) + (((-174*f*(128-f)>>16)+f)>>7)*(1<<i)
]]></artwork>
</figure>
 yields the approximate exponential.
Otherwise, silk_log2lin uses
<figure align="center">
<artwork align="center"><![CDATA[
 (1<<i) + ((-174*f*(128-f)>>16)+f)*((1<<i)>>7) .
]]></artwork>
</figure>
</t>
</section>

<section anchor="silk_nlsfs" title="Normalized Line Spectral Frequencies">

<t>
Normalized Line Spectral Frequencies (LSFs) follow the quantization gains in
 the bitstream, and represent the Linear Prediction Coefficients (LPCs) for the
 current SILK frame.
Once decoded, they form an increasing list of Q15 values between 0 and 1.
These represent the interleaved zeros on the unit circle between 0 and pi
 (hence "normalized") in the standard decomposition of the LPC filter into a
 symmetric part and an anti-symmetric part (P and Q in
 <xref target="silk_nlsf2lpc"/>).
Because of non-linear effects in the decoding process, an implementation SHOULD
 match the fixed-point arithmetic described in this section exactly.
The reference decoder uses fixed-point arithmetic for this even when running in
 floating point mode, for this reason.
An encoder SHOULD also use the same process.
</t>
<t>
The normalized LSFs are coded using a two-stage vector quantizer (VQ).
NB and MB frames use an order-10 predictor, while WB frames use an order-16
 predictor, and thus have different sets of tables.
The first VQ stage uses a 32-element codebook, coded with one of the PDFs in
 <xref target="silk_nlsf_stage1_pdfs"/>, depending on the audio bandwidth and
 the signal type of the current SILK or LBRR frame.
This yields a single index, <spanx style="emph">I1</spanx>, for the entire
 frame.
This indexes an element in a coarse codebook, selects the PDFs for the
 second stage of the VQ, and selects the prediction weights used to remove
 intra-frame redundancy from the second stage.
The actual codebook elements are listed in
 <xref target="silk_nlsf_nbmb_codebook"/> and
 <xref target="silk_nlsf_wb_codebook"/>, but they are not needed until the last
 stages of reconstructing the LSF coefficients.
</t>

<texttable anchor="silk_nlsf_stage1_pdfs"
 title="PDFs for Normalized LSF Index Stage-1 Decoding">
<ttcol align="left">Audio Bandwidth</ttcol>
<ttcol align="left">Signal Type</ttcol>
<ttcol align="left">PDF</ttcol>
<c>NB or MB</c> <c>Non-speech or unvoiced</c>
<c>
{44, 34, 30, 19, 21, 12, 11,  3,
  3,  2, 16,  2,  2,  1,  5,  2,
  1,  3,  3,  1,  1,  2,  2,  2,
  3,  1,  9,  9,  2,  7,  2,  1}/256
</c>
<c>NB or MB</c> <c>Voiced</c>
<c>
{1, 10,  1,  8,  3,  8,  8, 14,
13, 14,  1, 14, 12, 13, 11, 11,
12, 11, 10, 10, 11,  8,  9,  8,
 7,  8,  1,  1,  6,  1,  6,  5}/256
</c>
<c>WB</c> <c>Non-speech or unvoiced</c>
<c>
{31, 21,  3, 17,  1,  8, 17,  4,
  1, 18, 16,  4,  2,  3,  1, 10,
  1,  3, 16, 11, 16,  2,  2,  3,
  2, 11,  1,  4,  9,  8,  7,  3}/256
</c>
<c>WB</c> <c>Voiced</c>
<c>
{1,  4, 16,  5, 18, 11,  5, 14,
15,  1,  3, 12, 13, 14, 14,  6,
14, 12,  2,  6,  1, 12, 12, 11,
10,  3, 10,  5,  1,  1,  1,  3}/256
</c>
</texttable>

<t>
A total of 16 PDFs, each with a different PDF, are available for the LSF
 residual in the second stage: the 8 (a...h) for NB and MB frames given in
 <xref target="silk_nlsf_stage2_nbmb_pdfs"/>, and the 8 (i...p) for WB frames
 given in <xref target="silk_nlsf_stage2_wb_pdfs"/>.
Which PDF is used for which coefficient is driven by the index, I1,
 decoded in the first stage.
<xref target="silk_nlsf_nbmb_stage2_cb_sel"/> lists the letter of the
 corresponding PDF for each normalized LSF coefficient for NB and MB, and
 <xref target="silk_nlsf_wb_stage2_cb_sel"/> lists them for WB.
</t>

<texttable anchor="silk_nlsf_stage2_nbmb_pdfs"
 title="PDFs for NB/MB Normalized LSF Index Stage-2 Decoding">
<ttcol align="left">Codebook</ttcol>
<ttcol align="left">PDF</ttcol>
<c>a</c> <c>{1,   1,   1,  15, 224,  11,   1,   1,   1}/256</c>
<c>b</c> <c>{1,   1,   2,  34, 183,  32,   1,   1,   1}/256</c>
<c>c</c> <c>{1,   1,   4,  42, 149,  55,   2,   1,   1}/256</c>
<c>d</c> <c>{1,   1,   8,  52, 123,  61,   8,   1,   1}/256</c>
<c>e</c> <c>{1,   3,  16,  53, 101,  74,   6,   1,   1}/256</c>
<c>f</c> <c>{1,   3,  17,  55,  90,  73,  15,   1,   1}/256</c>
<c>g</c> <c>{1,   7,  24,  53,  74,  67,  26,   3,   1}/256</c>
<c>h</c> <c>{1,   1,  18,  63,  78,  58,  30,   6,   1}/256</c>
</texttable>

<texttable anchor="silk_nlsf_stage2_wb_pdfs"
 title="PDFs for WB Normalized LSF Index Stage-2 Decoding">
<ttcol align="left">Codebook</ttcol>
<ttcol align="left">PDF</ttcol>
<c>i</c> <c>{1,   1,   1,   9, 232,   9,   1,   1,   1}/256</c>
<c>j</c> <c>{1,   1,   2,  28, 186,  35,   1,   1,   1}/256</c>
<c>k</c> <c>{1,   1,   3,  42, 152,  53,   2,   1,   1}/256</c>
<c>l</c> <c>{1,   1,  10,  49, 126,  65,   2,   1,   1}/256</c>
<c>m</c> <c>{1,   4,  19,  48, 100,  77,   5,   1,   1}/256</c>
<c>n</c> <c>{1,   1,  14,  54, 100,  72,  12,   1,   1}/256</c>
<c>o</c> <c>{1,   1,  15,  61,  87,  61,  25,   4,   1}/256</c>
<c>p</c> <c>{1,   7,  21,  50,  77,  81,  17,   1,   1}/256</c>
</texttable>

<texttable anchor="silk_nlsf_nbmb_stage2_cb_sel"
 title="Codebook Selection for NB/MB Normalized LSF Index Stage 2 Decoding">
<ttcol>I1</ttcol>
<ttcol>Coefficient</ttcol>
<c/>
<c><spanx style="vbare">0&nbsp;1&nbsp;2&nbsp;3&nbsp;4&nbsp;5&nbsp;6&nbsp;7&nbsp;8&nbsp;9</spanx></c>
<c> 0</c>
<c><spanx style="vbare">a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a&nbsp;a</spanx></c>
<c> 1</c>
<c><spanx style="vbare">b&nbsp;d&nbsp;b&nbsp;c&nbsp;c&nbsp;b&nbsp;c&nbsp;b&nbsp;b&nbsp;b</spanx></c>
<c> 2</c>
<c><spanx style="vbare">c&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b&nbsp;b</spanx></c>
<c> 3</c>
<c><spanx style="vbare">b&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;b&nbsp;c&nbsp;b&nbsp;b&nbsp;b</spanx></c>
<c> 4</c>
<c><spanx style="vbare">c&nbsp;d&nbsp;d&nbsp;d&nbsp;d&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c</spanx></c>
<c> 5</c>
<c><spanx style="vbare">a&nbsp;f&nbsp;d&nbsp;d&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;b&nbsp;b</spanx></c>
<c> g</c>
<c><spanx style="vbare">a&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;b</spanx></c>
<c> 7</c>
<c><spanx style="vbare">c&nbsp;d&nbsp;g&nbsp;e&nbsp;e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f</spanx></c>
<c> 8</c>
<c><spanx style="vbare">c&nbsp;e&nbsp;f&nbsp;f&nbsp;e&nbsp;f&nbsp;e&nbsp;g&nbsp;e&nbsp;e</spanx></c>
<c> 9</c>
<c><spanx style="vbare">c&nbsp;e&nbsp;e&nbsp;h&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;e</spanx></c>
<c>10</c>
<c><spanx style="vbare">e&nbsp;d&nbsp;d&nbsp;d&nbsp;c&nbsp;d&nbsp;c&nbsp;c&nbsp;c&nbsp;c</spanx></c>
<c>11</c>
<c><spanx style="vbare">b&nbsp;f&nbsp;f&nbsp;g&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;f</spanx></c>
<c>12</c>
<c><spanx style="vbare">c&nbsp;h&nbsp;e&nbsp;g&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;f</spanx></c>
<c>13</c>
<c><spanx style="vbare">c&nbsp;h&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
<c>14</c>
<c><spanx style="vbare">d&nbsp;d&nbsp;f&nbsp;e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;e&nbsp;e</spanx></c>
<c>15</c>
<c><spanx style="vbare">c&nbsp;d&nbsp;d&nbsp;f&nbsp;f&nbsp;e&nbsp;e&nbsp;e&nbsp;e&nbsp;e</spanx></c>
<c>16</c>
<c><spanx style="vbare">c&nbsp;e&nbsp;e&nbsp;g&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;f</spanx></c>
<c>17</c>
<c><spanx style="vbare">c&nbsp;f&nbsp;e&nbsp;g&nbsp;f&nbsp;f&nbsp;f&nbsp;e&nbsp;f&nbsp;e</spanx></c>
<c>18</c>
<c><spanx style="vbare">c&nbsp;h&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f&nbsp;f</spanx></c>
<c>19</c>
<c><spanx style="vbare">c&nbsp;f&nbsp;e&nbsp;g&nbsp;h&nbsp;g&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
<c>20</c>
<c><spanx style="vbare">d&nbsp;g&nbsp;h&nbsp;e&nbsp;g&nbsp;f&nbsp;f&nbsp;g&nbsp;e&nbsp;f</spanx></c>
<c>21</c>
<c><spanx style="vbare">c&nbsp;h&nbsp;g&nbsp;e&nbsp;e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;f</spanx></c>
<c>22</c>
<c><spanx style="vbare">e&nbsp;f&nbsp;f&nbsp;e&nbsp;g&nbsp;g&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
<c>23</c>
<c><spanx style="vbare">c&nbsp;f&nbsp;f&nbsp;g&nbsp;f&nbsp;g&nbsp;e&nbsp;g&nbsp;e&nbsp;e</spanx></c>
<c>24</c>
<c><spanx style="vbare">e&nbsp;f&nbsp;f&nbsp;f&nbsp;d&nbsp;h&nbsp;e&nbsp;f&nbsp;f&nbsp;e</spanx></c>
<c>25</c>
<c><spanx style="vbare">c&nbsp;d&nbsp;e&nbsp;f&nbsp;f&nbsp;g&nbsp;e&nbsp;f&nbsp;f&nbsp;e</spanx></c>
<c>26</c>
<c><spanx style="vbare">c&nbsp;d&nbsp;c&nbsp;d&nbsp;d&nbsp;e&nbsp;c&nbsp;d&nbsp;d&nbsp;d</spanx></c>
<c>27</c>
<c><spanx style="vbare">b&nbsp;b&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;c&nbsp;d&nbsp;c&nbsp;c</spanx></c>
<c>28</c>
<c><spanx style="vbare">e&nbsp;f&nbsp;f&nbsp;g&nbsp;g&nbsp;g&nbsp;f&nbsp;g&nbsp;e&nbsp;f</spanx></c>
<c>29</c>
<c><spanx style="vbare">d&nbsp;f&nbsp;f&nbsp;e&nbsp;e&nbsp;e&nbsp;e&nbsp;d&nbsp;d&nbsp;c</spanx></c>
<c>30</c>
<c><spanx style="vbare">c&nbsp;f&nbsp;d&nbsp;h&nbsp;f&nbsp;f&nbsp;e&nbsp;e&nbsp;f&nbsp;e</spanx></c>
<c>31</c>
<c><spanx style="vbare">e&nbsp;e&nbsp;f&nbsp;e&nbsp;f&nbsp;g&nbsp;f&nbsp;g&nbsp;f&nbsp;e</spanx></c>
</texttable>

<texttable anchor="silk_nlsf_wb_stage2_cb_sel"
 title="Codebook Selection for WB Normalized LSF Index Stage 2 Decoding">
<ttcol>I1</ttcol>
<ttcol>Coefficient</ttcol>
<c/>
<c><spanx style="vbare">0&nbsp;&nbsp;1&nbsp;&nbsp;2&nbsp;&nbsp;3&nbsp;&nbsp;4&nbsp;&nbsp;5&nbsp;&nbsp;6&nbsp;&nbsp;7&nbsp;&nbsp;8&nbsp;&nbsp;9&nbsp;10&nbsp;11&nbsp;12&nbsp;13&nbsp;14&nbsp;15</spanx></c>