blob: 6131e69ed5aaa8179ee6fe6b4b84a747cd26ce3f [file] [log] [blame]
tlegrand@chromium.orge3ea0492013-10-23 09:13:50 +00001<?xml version="1.0" encoding="utf-8"?>
2<!DOCTYPE rfc SYSTEM 'rfc2629.dtd' [
3<!ENTITY rfc2119 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.2119.xml'>
4<!ENTITY rfc3533 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.3533.xml'>
5<!ENTITY rfc3629 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.3629.xml'>
6<!ENTITY rfc4732 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.4732.xml'>
7<!ENTITY rfc5334 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.5334.xml'>
8<!ENTITY rfc6381 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.6381.xml'>
9<!ENTITY rfc6716 PUBLIC '' 'https://xml2rfc.tools.ietf.org/tools/xml2rfc/public/rfc/bibxml/reference.RFC.6716.xml'>
10]>
11<?rfc toc="yes" symrefs="yes" ?>
12
13<rfc ipr="trust200902" category="std" docName="draft-ietf-codec-oggopus-01">
14
15<front>
16<title abbrev="Ogg Opus">Ogg Encapsulation for the Opus Audio Codec</title>
17<author initials="T.B." surname="Terriberry" fullname="Timothy B. Terriberry">
18<organization>Mozilla Corporation</organization>
19<address>
20<postal>
21<street>650 Castro Street</street>
22<city>Mountain View</city>
23<region>CA</region>
24<code>94041</code>
25<country>USA</country>
26</postal>
27<phone>+1 650 903-0800</phone>
28<email>tterribe@xiph.org</email>
29</address>
30</author>
31
32<author initials="R." surname="Lee" fullname="Ron Lee">
33<organization>Voicetronix</organization>
34<address>
35<postal>
36<street>246 Pulteney Street, Level 1</street>
37<city>Adelaide</city>
38<region>SA</region>
39<code>5000</code>
40<country>Australia</country>
41</postal>
42<phone>+61 8 8232 9112</phone>
43<email>ron@debian.org</email>
44</address>
45</author>
46
47<author initials="R." surname="Giles" fullname="Ralph Giles">
48<organization>Mozilla Corporation</organization>
49<address>
50<postal>
51<street>163 West Hastings Street</street>
52<city>Vancouver</city>
53<region>BC</region>
54<code>V6B 1H5</code>
55<country>Canada</country>
56</postal>
57<phone>+1 604 778 1540</phone>
58<email>giles@xiph.org</email>
59</address>
60</author>
61
62<date day="24" month="May" year="2013"/>
63<area>RAI</area>
64<workgroup>codec</workgroup>
65
66<abstract>
67<t>
68This document defines the Ogg encapsulation for the Opus interactive speech and
69 audio codec.
70This allows data encoded in the Opus format to be stored in an Ogg logical
71 bitstream.
72Ogg encapsulation provides Opus with a long-term storage format supporting
73 all of the essential features, including metadata, fast and accurate seeking,
74 corruption detection, recapture after errors, low overhead, and the ability to
75 multiplex Opus with other codecs (including video) with minimal buffering.
76It also provides a live streamable format, capable of delivery over a reliable
77 stream-oriented transport, without requiring all the data, or even the total
78 length of the data, up-front, in a form that is identical to the on-disk
79 storage format.
80</t>
81</abstract>
82</front>
83
84<middle>
85<section anchor="intro" title="Introduction">
86<t>
87The IETF Opus codec is a low-latency audio codec optimized for both voice and
88 general-purpose audio.
89See <xref target="RFC6716"/> for technical details.
90This document defines the encapsulation of Opus in a continuous, logical Ogg
91 bitstream&nbsp;<xref target="RFC3533"/>.
92</t>
93<t>
94Ogg bitstreams are made up of a series of 'pages', each of which contains data
95 from one or more 'packets'.
96Pages are the fundamental unit of multiplexing in an Ogg stream.
97Each page is associated with a particular logical stream and contains a capture
98 pattern and checksum, flags to mark the beginning and end of the logical
99 stream, and a 'granule position' that represents an absolute position in the
100 stream, to aid seeking.
101A single page can contain up to 65,025 octets of packet data from up to 255
102 different packets.
103Packets may be split arbitrarily across pages, and continued from one page to
104 the next (allowing packets much larger than would fit on a single page).
105Each page contains 'lacing values' that indicate how the data is partitioned
106 into packets, allowing a demuxer to recover the packet boundaries without
107 examining the encoded data.
108A packet is said to 'complete' on a page when the page contains the final
109 lacing value corresponding to that packet.
110</t>
111<t>
112This encapsulation defines the required contents of the packet data, including
113 the necessary headers, the organization of those packets into a logical
114 stream, and the interpretation of the codec-specific granule position field.
115It does not attempt to describe or specify the existing Ogg container format.
116Readers unfamiliar with the basic concepts mentioned above are encouraged to
117 review the details in <xref target="RFC3533"/>.
118</t>
119
120</section>
121
122<section anchor="terminology" title="Terminology">
123<t>
124The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD",
125 "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be
126 interpreted as described in <xref target="RFC2119"/>.
127</t>
128
129<t>
130Implementations that fail to satisfy one or more "MUST" requirements are
131 considered non-compliant.
132Implementations that satisfy all "MUST" requirements, but fail to satisfy one
133 or more "SHOULD" requirements are said to be "conditionally compliant".
134All other implementations are "unconditionally compliant".
135</t>
136
137</section>
138
139<section anchor="packet_organization" title="Packet Organization">
140<t>
141An Opus stream is organized as follows.
142</t>
143<t>
144There are two mandatory header packets.
145The granule position of the pages on which these packets complete MUST be zero.
146</t>
147<t>
148The first packet in the logical Ogg bitstream MUST contain the identification
149 (ID) header, which uniquely identifies a stream as Opus audio.
150The format of this header is defined in <xref target="id_header"/>.
151It MUST be placed alone (without any other packet data) on the first page of
152 the logical Ogg bitstream, and must complete on that page.
153This page MUST have its 'beginning of stream' flag set.
154</t>
155<t>
156The second packet in the logical Ogg bitstream MUST contain the comment header,
157 which contains user-supplied metadata.
158The format of this header is defined in <xref target="comment_header"/>.
159It MAY span one or more pages, beginning on the second page of the logical
160 stream.
161However many pages it spans, the comment header packet MUST finish the page on
162 which it completes.
163</t>
164<t>
165All subsequent pages are audio data pages, and the Ogg packets they contain are
166 audio data packets.
167Each audio data packet contains one Opus packet for each of N different
168 streams, where N is typically one for mono or stereo, but may be greater than
169 one for, e.g., multichannel audio.
170The value N is specified in the ID header (see
171 <xref target="channel_mapping"/>), and is fixed over the entire length of the
172 logical Ogg bitstream.
173</t>
174<t>
175The first N-1 Opus packets, if any, are packed one after another into the Ogg
176 packet, using the self-delimiting framing from Appendix&nbsp;B of
177 <xref target="RFC6716"/>.
178The remaining Opus packet is packed at the end of the Ogg packet using the
179 regular, undelimited framing from Section&nbsp;3 of <xref target="RFC6716"/>.
180All of the Opus packets in a single Ogg packet MUST be constrained to have the
181 same duration.
182The duration and coding modes of each Opus packet are contained in the
183 TOC (table of contents) sequence in the first few bytes.
184A decoder SHOULD treat any Opus packet whose duration is different from that of
185 the first Opus packet in an Ogg packet as if it were an Opus packet with an
186 illegal TOC sequence.
187</t>
188<t>
189The first audio data page SHOULD NOT have the 'continued packet' flag set
190 (which would indicate the first audio data packet is continued from a previous
191 page).
192Packets MUST be placed into Ogg pages in order until the end of stream.
193Audio packets MAY span page boundaries.
194A decoder MUST treat a zero-octet audio data packet as if it were an Opus
195 packet with an illegal TOC sequence.
196The last page SHOULD have the 'end of stream' flag set, but implementations
197 should be prepared to deal with truncated streams that do not have a page
198 marked 'end of stream'.
199The final packet on the last page SHOULD NOT be a continued packet, i.e., the
200 final lacing value should be less than 255.
201There MUST NOT be any more pages in an Opus logical bitstream after a page
202 marked 'end of stream'.
203</t>
204</section>
205
206<section anchor="granpos" title="Granule Position">
207<t>
208The granule position of an audio data page encodes the total number of PCM
209 samples in the stream up to and including the last fully-decodable sample from
210 the last packet completed on that page.
211A page that is entirely spanned by a single packet (that completes on a
212 subsequent page) has no granule position, and the granule position field MUST
213 be set to the special value '-1' in two's complement.
214</t>
215
216<t>
217The granule position of an audio data page is in units of PCM audio samples at
218 a fixed rate of 48&nbsp;kHz (per channel; a stereo stream's granule position
219 does not increment at twice the speed of a mono stream).
220It is possible to run an Opus decoder at other sampling rates, but the value
221 in the granule position field always counts samples assuming a 48&nbsp;kHz
222 decoding rate, and the rest of this specification makes the same assumption.
223</t>
224
225<t>
226The duration of an Opus packet may be any multiple of 2.5&nbsp;ms, up to a
227 maximum of 120&nbsp;ms.
228This duration is encoded in the TOC sequence at the beginning of each packet.
229The number of samples returned by a decoder corresponds to this duration
230 exactly, even for the first few packets.
231For example, a 20&nbsp;ms packet fed to a decoder running at 48&nbsp;kHz will
232 always return 960&nbsp;samples.
233A demuxer can parse the TOC sequence at the beginning of each Ogg packet to
234 work backwards or forwards from a packet with a known granule position (i.e.,
235 the last packet completed on some page) in order to assign granule positions
236 to every packet, or even every individual sample.
237The one exception is the last page in the stream, as described below.
238</t>
239
240<t>
241All other pages with completed packets after the first MUST have a granule
242 position equal to the number of samples contained in packets that complete on
243 that page plus the granule position of the most recent page with completed
244 packets.
245This guarantees that a demuxer can assign individual packets the same granule
246 position when working forwards as when working backwards.
247For this to work, there cannot be any gaps.
248In order to support capturing a stream that uses discontinuous transmission
249 (DTX), an encoder SHOULD emit packets that explicitly request the use of
250 Packet Loss Concealment (PLC) (i.e., with a frame length of 0, as defined in
251 Section 3.2.1 of <xref target="RFC6716"/>) in place of the packets that were
252 not transmitted.
253</t>
254
255<section anchor="preskip" title="Pre-skip">
256<t>
257There is some amount of latency introduced during the decoding process, to
258 allow for overlap in the MDCT modes, stereo mixing in the LP modes, and
259 resampling, and the encoder will introduce even more latency (though the exact
260 amount is not specified).
261Therefore, the first few samples produced by the decoder do not correspond to
262 real input audio, but are instead composed of padding inserted by the encoder
263 to compensate for this latency.
264These samples need to be stored and decoded, as Opus is an asymptotically
265 convergent predictive codec, meaning the decoded contents of each frame depend
266 on the recent history of decoder inputs.
267However, a decoder will want to skip these samples after decoding them.
268</t>
269
270<t>
271A 'pre-skip' field in the ID header (see <xref target="id_header"/>) signals
272 the number of samples which SHOULD be skipped (decoded but discarded) at the
273 beginning of the stream.
274This provides sufficient history to the decoder so that it has already
275 converged before the stream's output begins.
276It may also be used to perform sample-accurate cropping of existing encoded
277 streams.
278This amount need not be a multiple of 2.5&nbsp;ms, may be smaller than a single
279 packet, or may span the contents of several packets.
280</t>
281</section>
282
283<section anchor="pcm_sample_position" title="PCM Sample Position">
284<t>
285The PCM sample position is determined from the granule position using the
286 formula
287<figure align="center">
288<artwork align="center"><![CDATA[
289'PCM sample position' = 'granule position' - 'pre-skip' .
290]]></artwork>
291</figure>
292</t>
293
294<t>
295For example, if the granule position of the first audio data page is 59,971,
296 and the pre-skip is 11,971, then the PCM sample position of the last decoded
297 sample from that page is 48,000.
298This can be converted into a playback time using the formula
299<figure align="center">
300<artwork align="center"><![CDATA[
301 'PCM sample position'
302'playback time' = --------------------- .
303 48000.0
304]]></artwork>
305</figure>
306</t>
307
308<t>
309The initial PCM sample position before any samples are played is normally '0'.
310In this case, the PCM sample position of the first audio sample to be played
311 starts at '1', because it marks the time on the clock
312 <spanx style="emph">after</spanx> that sample has been played, and a stream
313 that is exactly one second long has a final PCM sample position of '48000',
314 as in the example here.
315</t>
316
317<t>
318Vorbis streams use a granule position smaller than the number of audio samples
319 contained in the first audio data page to indicate that some of those samples
320 must be trimmed from the output (see <xref target="vorbis-trim"/>).
321However, to do so, Vorbis requires that the first audio data page contains
322 exactly two packets, in order to allow the decoder to perform PCM position
323 adjustments before needing to return any PCM data.
324Opus uses the pre-skip mechanism for this purpose instead, since the encoder
325 may introduce more than a single packet's worth of latency, and since very
326 large packets in streams with a very large number of channels might not fit
327 on a single page.
328</t>
329</section>
330
331<section anchor="end_trimming" title="End Trimming">
332<t>
333The page with the 'end of stream' flag set MAY have a granule position that
334 indicates the page contains less audio data than would normally be returned by
335 decoding up through the final packet.
336This is used to end the stream somewhere other than an even frame boundary.
337The granule position of the most recent audio data page with completed packets
338 is used to make this determination, or '0' is used if there were no previous
339 audio data pages with a completed packet.
340The difference between these granule positions indicates how many samples to
341 keep after decoding the packets that completed on the final page.
342The remaining samples are discarded.
343The number of discarded samples SHOULD be no larger than the number decoded
344 from the last packet.
345</t>
346</section>
347
348<section anchor="start_granpos_restrictions"
349 title="Restrictions on the Initial Granule Position">
350<t>
351The granule position of the first audio data page with a completed packet MAY
352 be larger than the number of samples contained in packets that complete on
353 that page, however it MUST NOT be smaller, unless that page has the 'end of
354 stream' flag set.
355Allowing a granule position larger than the number of samples allows the
356 beginning of a stream to be cropped or a live stream to be joined without
357 rewriting the granule position of all the remaining pages.
358This means that the PCM sample position just before the first sample to be
359 played may be larger than '0'.
360Synchronization when multiplexing with other logical streams still uses the PCM
361 sample position relative to '0' to compute sample times.
362This does not affect the behavior of pre-skip: exactly 'pre-skip' samples
363 should be skipped from the beginning of the decoded output, even if the
364 initial PCM sample position is greater than zero.
365</t>
366
367<t>
368On the other hand, a granule position that is smaller than the number of
369 decoded samples prevents a demuxer from working backwards to assign each
370 packet or each individual sample a valid granule position, since granule
371 positions must be non-negative.
372A decoder MUST reject as invalid any stream where the granule position is
373 smaller than the number of samples contained in packets that complete on the
374 first audio data page with a completed packet, unless that page has the 'end
375 of stream' flag set.
376It MAY defer this action until it decodes the last packet completed on that
377 page.
378</t>
379
380<t>
381If that page has the 'end of stream' flag set, a demuxer MUST reject as invalid
382 any stream where its granule position is smaller than the 'pre-skip' amount.
383This would indicate that more samples should be skipped from the initial
384 decoded output than exist in the stream.
385If the granule position is smaller than the number of decoded samples produced
386 by the packets that complete on that page, then a demuxer MUST use an initial
387 granule position of '0', and can work forwards from '0' to timestamp
388 individual packets.
389If the granule position is larger than the number of decoded samples available,
390 then the demuxer MUST still work backwards as described above, even if the
391 'end of stream' flag is set, to determine the initial granule position, and
392 thus the initial PCM sample position.
393Both of these will be greater than '0' in this case.
394</t>
395</section>
396
397<section anchor="seeking_and_preroll" title="Seeking and Pre-roll">
398<t>
399Seeking in Ogg files is best performed using a bisection search for a page
400 whose granule position corresponds to a PCM position at or before the seek
401 target.
402With appropriately weighted bisection, accurate seeking can be performed with
403 just three or four bisections even in multi-gigabyte files.
404See <xref target="seeking"/> for general implementation guidance.
405</t>
406
407<t>
408When seeking within an Ogg Opus stream, the decoder SHOULD start decoding (and
409 discarding the output) at least 3840&nbsp;samples (80&nbsp;ms) prior to the
410 seek target in order to ensure that the output audio is correct by the time it
411 reaches the seek target.
412This 'pre-roll' is separate from, and unrelated to, the 'pre-skip' used at the
413 beginning of the stream.
414If the point 80&nbsp;ms prior to the seek target comes before the initial PCM
415 sample position, the decoder SHOULD start decoding from the beginning of the
416 stream, applying pre-skip as normal, regardless of whether the pre-skip is
417 larger or smaller than 80&nbsp;ms, and then continue to discard the samples
418 required to reach the seek target (if any).
419</t>
420</section>
421
422</section>
423
424<section anchor="headers" title="Header Packets">
425<t>
426An Opus stream contains exactly two mandatory header packets:
427 an identification header and a comment header.
428</t>
429
430<section anchor="id_header" title="Identification Header">
431
432<figure anchor="id_header_packet" title="ID Header Packet" align="center">
433<artwork align="center"><![CDATA[
434 0 1 2 3
435 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
436+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
437| 'O' | 'p' | 'u' | 's' |
438+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
439| 'H' | 'e' | 'a' | 'd' |
440+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
441| Version = 1 | Channel Count | Pre-skip |
442+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
443| Input Sample Rate (Hz) |
444+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
445| Output Gain (Q7.8 in dB) | Mapping Family| |
446+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ :
447| |
448: Optional Channel Mapping Table... :
449| |
450+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
451]]></artwork>
452</figure>
453
454<t>
455The fields in the identification (ID) header have the following meaning:
456<list style="numbers">
457<t><spanx style="strong">Magic Signature</spanx>:
458<vspace blankLines="1"/>
459This is an 8-octet (64-bit) field that allows codec identification and is
460 human-readable.
461It contains, in order, the magic numbers:
462<list style="empty">
463<t>0x4F 'O'</t>
464<t>0x70 'p'</t>
465<t>0x75 'u'</t>
466<t>0x73 's'</t>
467<t>0x48 'H'</t>
468<t>0x65 'e'</t>
469<t>0x61 'a'</t>
470<t>0x64 'd'</t>
471</list>
472Starting with "Op" helps distinguish it from audio data packets, as this is an
473 invalid TOC sequence.
474<vspace blankLines="1"/>
475</t>
476<t><spanx style="strong">Version</spanx> (8 bits, unsigned):
477<vspace blankLines="1"/>
478The version number MUST always be '1' for this version of the encapsulation
479 specification.
480Implementations SHOULD treat streams where the upper four bits of the version
481 number match that of a recognized specification as backwards-compatible with
482 that specification.
483That is, the version number can be split into "major" and "minor" version
484 sub-fields, with changes to the "minor" sub-field (in the lower four bits)
485 signaling compatible changes.
486For example, a decoder implementing this specification SHOULD accept any stream
487 with a version number of '15' or less, and SHOULD assume any stream with a
488 version number '16' or greater is incompatible.
489The initial version '1' was chosen to keep implementations from relying on this
490 octet as a null terminator for the "OpusHead" string.
491<vspace blankLines="1"/>
492</t>
493<t><spanx style="strong">Output Channel Count</spanx> 'C' (8 bits, unsigned):
494<vspace blankLines="1"/>
495This is the number of output channels.
496This might be different than the number of encoded channels, which can change
497 on a packet-by-packet basis.
498This value MUST NOT be zero.
499The maximum allowable value depends on the channel mapping family, and might be
500 as large as 255.
501See <xref target="channel_mapping"/> for details.
502<vspace blankLines="1"/>
503</t>
504<t><spanx style="strong">Pre-skip</spanx> (16 bits, unsigned, little
505 endian):
506<vspace blankLines="1"/>
507This is the number of samples (at 48&nbsp;kHz) to discard from the decoder
508 output when starting playback, and also the number to subtract from a page's
509 granule position to calculate its PCM sample position.
510When cropping the beginning of existing Ogg Opus streams, a pre-skip of at
511 least 3,840&nbsp;samples (80&nbsp;ms) is RECOMMENDED to ensure complete
512 convergence in the decoder.
513<vspace blankLines="1"/>
514</t>
515<t><spanx style="strong">Input Sample Rate</spanx> (32 bits, unsigned, little
516 endian):
517<vspace blankLines="1"/>
518This field is <spanx style="emph">not</spanx> the sample rate to use for
519 playback of the encoded data.
520<vspace blankLines="1"/>
521Opus has a handful of coding modes, with internal audio bandwidths of 4, 6, 8,
522 12, and 20&nbsp;kHz.
523Each packet in the stream may have a different audio bandwidth.
524Regardless of the audio bandwidth, the reference decoder supports decoding any
525 stream at a sample rate of 8, 12, 16, 24, or 48&nbsp;kHz.
526The original sample rate of the encoder input is not preserved by the lossy
527 compression.
528<vspace blankLines="1"/>
529An Ogg Opus player SHOULD select the playback sample rate according to the
530 following procedure:
531<list style="numbers">
532<t>If the hardware supports 48&nbsp;kHz playback, decode at 48&nbsp;kHz.</t>
533<t>Otherwise, if the hardware's highest available sample rate is a supported
534 rate, decode at this sample rate.</t>
535<t>Otherwise, if the hardware's highest available sample rate is less than
536 48&nbsp;kHz, decode at the highest supported rate above this and resample.</t>
537<t>Otherwise, decode at 48&nbsp;kHz and resample.</t>
538</list>
539However, the 'Input Sample Rate' field allows the encoder to pass the sample
540 rate of the original input stream as metadata.
541This may be useful when the user requires the output sample rate to match the
542 input sample rate.
543For example, a non-player decoder writing PCM format samples to disk might
544 choose to resample the output audio back to the original input sample rate to
545 reduce surprise to the user, who might reasonably expect to get back a file
546 with the same sample rate as the one they fed to the encoder.
547<vspace blankLines="1"/>
548A value of zero indicates 'unspecified'.
549Encoders SHOULD write the actual input sample rate or zero, but decoder
550 implementations which do something with this field SHOULD take care to behave
551 sanely if given crazy values (e.g., do not actually upsample the output to
552 10 MHz if requested).
553<vspace blankLines="1"/>
554</t>
555<t><spanx style="strong">Output Gain</spanx> (16 bits, signed, little
556 endian):
557<vspace blankLines="1"/>
558This is a gain to be applied by the decoder.
559It is 20*log10 of the factor to scale the decoder output by to achieve the
560 desired playback volume, stored in a 16-bit, signed, two's complement
561 fixed-point value with 8 fractional bits (i.e., Q7.8).
562To apply the gain, a decoder could use
563<figure align="center">
564<artwork align="center"><![CDATA[
565sample *= pow(10, output_gain/(20.0*256)) ,
566]]></artwork>
567</figure>
568 where output_gain is the raw 16-bit value from the header.
569<vspace blankLines="1"/>
570Virtually all players and media frameworks should apply it by default.
571If a player chooses to apply any volume adjustment or gain modification, such
572 as the R128_TRACK_GAIN (see <xref target="comment_header"/>) or a user-facing
573 volume knob, the adjustment MUST be applied in addition to this output gain in
574 order to achieve playback at the desired volume.
575<vspace blankLines="1"/>
576An encoder SHOULD set this field to zero, and instead apply any gain prior to
577 encoding, when this is possible and does not conflict with the user's wishes.
578The output gain should only be nonzero when the gain is adjusted after
579 encoding, or when the user wishes to adjust the gain for playback while
580 preserving the ability to recover the original signal amplitude.
581<vspace blankLines="1"/>
582Although the output gain has enormous range (+/- 128 dB, enough to amplify
583 inaudible sounds to the threshold of physical pain), most applications can
584 only reasonably use a small portion of this range around zero.
585The large range serves in part to ensure that gain can always be losslessly
586 transferred between OpusHead and R128_TRACK_GAIN (see below) without
587 saturating.
588<vspace blankLines="1"/>
589</t>
590<t><spanx style="strong">Channel Mapping Family</spanx> (8 bits,
591 unsigned):
592<vspace blankLines="1"/>
593This octet indicates the order and semantic meaning of the various channels
594 encoded in each Ogg packet.
595<vspace blankLines="1"/>
596Each possible value of this octet indicates a mapping family, which defines a
597 set of allowed channel counts, and the ordered set of channel names for each
598 allowed channel count.
599The details are described in <xref target="channel_mapping"/>.
600</t>
601<t><spanx style="strong">Channel Mapping Table</spanx>:
602This table defines the mapping from encoded streams to output channels.
603It is omitted when the channel mapping family is 0, but REQUIRED otherwise.
604Its contents are specified in <xref target="channel_mapping"/>.
605</t>
606</list>
607</t>
608
609<t>
610All fields in the ID headers are REQUIRED, except for the channel mapping
611 table, which is omitted when the channel mapping family is 0.
612Implementations SHOULD reject ID headers which do not contain enough data for
613 these fields, even if they contain a valid Magic Signature.
614Future versions of this specification, even backwards-compatible versions,
615 might include additional fields in the ID header.
616If an ID header has a compatible major version, but a larger minor version,
617 an implementation MUST NOT reject it for containing additional data not
618 specified here.
619However, implementations MAY reject streams in which the ID header does not
620 complete on the first page.
621</t>
622
623<section anchor="channel_mapping" title="Channel Mapping">
624<t>
625An Ogg Opus stream allows mapping one number of Opus streams (N) to a possibly
626 larger number of decoded channels (M+N) to yet another number of output
627 channels (C), which might be larger or smaller than the number of decoded
628 channels.
629The order and meaning of these channels are defined by a channel mapping,
630 which consists of the 'channel mapping family' octet and, for channel mapping
631 families other than family&nbsp;0, a channel mapping table, as illustrated in
632 <xref target="channel_mapping_table"/>.
633</t>
634
635<figure anchor="channel_mapping_table" title="Channel Mapping Table"
636 align="center">
637<artwork align="center"><![CDATA[
638 0 1 2 3
639 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
640 +-+-+-+-+-+-+-+-+
641 | Stream Count |
642+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
643| Coupled Count | Channel Mapping... :
644+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
645]]></artwork>
646</figure>
647
648<t>
649The fields in the channel mapping table have the following meaning:
650<list style="numbers" counter="8">
651<t><spanx style="strong">Stream Count</spanx> 'N' (8 bits, unsigned):
652<vspace blankLines="1"/>
653This is the total number of streams encoded in each Ogg packet.
654This value is required to correctly parse the packed Opus packets inside an
655 Ogg packet, as described in <xref target="packet_organization"/>.
656This value MUST NOT be zero, as without at least one Opus packet with a valid
657 TOC sequence, a demuxer cannot recover the duration of an Ogg packet.
658<vspace blankLines="1"/>
659For channel mapping family&nbsp;0, this value defaults to 1, and is not coded.
660<vspace blankLines="1"/>
661</t>
662<t><spanx style="strong">Coupled Stream Count</spanx> 'M' (8 bits, unsigned):
663This is the number of streams whose decoders should be configured to produce
664 two channels.
665This MUST be no larger than the total number of streams, N.
666<vspace blankLines="1"/>
667Each packet in an Opus stream has an internal channel count of 1 or 2, which
668 can change from packet to packet.
669This is selected by the encoder depending on the bitrate and the audio being
670 encoded.
671The original channel count of the encoder input is not preserved by the lossy
672 compression.
673<vspace blankLines="1"/>
674Regardless of the internal channel count, any Opus stream can be decoded as
675 mono (a single channel) or stereo (two channels) by appropriate initialization
676 of the decoder.
677The 'coupled stream count' field indicates that the first M Opus decoders are
678 to be initialized in stereo mode, and the remaining N-M decoders are to be
679 initialized in mono mode.
680The total number of decoded channels, (M+N), MUST be no larger than 255, as
681 there is no way to index more channels than that in the channel mapping.
682<vspace blankLines="1"/>
683For channel mapping family&nbsp;0, this value defaults to C-1 (i.e., 0 for mono
684 and 1 for stereo), and is not coded.
685<vspace blankLines="1"/>
686</t>
687<t><spanx style="strong">Channel Mapping</spanx> (8*C bits):
688This contains one octet per output channel, indicating which decoded channel
689 should be used for each one.
690Let 'index' be the value of this octet for a particular output channel.
691This value MUST either be smaller than (M+N), or be the special value 255.
692If 'index' is less than 2*M, the output MUST be taken from decoding stream
693 ('index'/2) as stereo and selecting the left channel if 'index' is even, and
694 the right channel if 'index' is odd.
695If 'index' is 2*M or larger, the output MUST be taken from decoding stream
696 ('index'-M) as mono.
697If 'index' is 255, the corresponding output channel MUST contain pure silence.
698<vspace blankLines="1"/>
699The number of output channels, C, is not constrained to match the number of
700 decoded channels (M+N).
701A single index value MAY appear multiple times, i.e., the same decoded channel
702 might be mapped to multiple output channels.
703Some decoded channels might not be assigned to any output channel, as well.
704<vspace blankLines="1"/>
705For channel mapping family&nbsp;0, the first index defaults to 0, and if C==2,
706 the second index defaults to 1.
707Neither index is coded.
708</t>
709</list>
710</t>
711
712<t>
713After producing the output channels, the channel mapping family determines the
714 semantic meaning of each one.
715Currently there are three defined mapping families, although more may be added.
716</t>
717
718<section anchor="channel_mapping_0" title="Channel Mapping Family 0">
719<t>
720Allowed numbers of channels: 1 or 2.
721RTP mapping.
722</t>
723<t>
724<list style="symbols">
725<t>1 channel: monophonic (mono).</t>
726<t>2 channels: stereo (left, right).</t>
727</list>
728<spanx style="strong">Special mapping</spanx>: This channel mapping value also
729 indicates that the contents consists of a single Opus stream that is stereo if
730 and only if C==2, with stream index 0 mapped to output channel 0 (mono, or
731 left channel) and stream index 1 mapped to output channel 1 (right channel)
732 if stereo.
733When the 'channel mapping family' octet has this value, the channel mapping
734 table MUST be omitted from the ID header packet.
735</t>
736</section>
737
738<section anchor="channel_mapping_1" title="Channel Mapping Family 1">
739<t>
740Allowed numbers of channels: 1...8.
741Vorbis channel order.
742</t>
743<t>
744Each channel is assigned to a speaker location in a conventional surround
745 configuration.
746Specific locations depend on the number of channels, and are given below
747 in order of the corresponding channel indicies.
748<list style="symbols">
749 <t>1 channel: monophonic (mono).</t>
750 <t>2 channels: stereo (left, right).</t>
751 <t>3 channels: linear surround (left, center, right)</t>
752 <t>4 channels: quadraphonic (front&nbsp;left, front&nbsp;right, rear&nbsp;left, rear&nbsp;right).</t>
753 <t>5 channels: 5.0 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, rear&nbsp;left, rear&nbsp;right).</t>
754 <t>6 channels: 5.1 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, rear&nbsp;left, rear&nbsp;right, LFE).</t>
755 <t>7 channels: 6.1 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, side&nbsp;left, side&nbsp;right, rear&nbsp;center, LFE).</t>
756 <t>8 channels: 7.1 surround (front&nbsp;left, front&nbsp;center, front&nbsp;right, side&nbsp;left, side&nbsp;right, rear&nbsp;left, rear&nbsp;right, LFE)</t>
757</list>
758This set of surround configurations and speaker location orderings is the same
759 as the one used by the Vorbis codec <xref target="vorbis-mapping"/>.
760The ordering is different from the one used by the
761 WAVE <xref target="wave-multichannel"/> and
762 FLAC <xref target="flac"/> formats,
763 so correct ordering requires permutation of the output channels when encoding
764 from or decoding to those formats.
765'LFE' here refers to a Low Frequency Effects, often mapped to a subwoofer
766 with no particular spacial position.
767Implementations SHOULD identify 'side' or 'rear' speaker locations with
768 'surround' and 'back' as appropriate when interfacing with audio formats
769 or systems which prefer that terminology.
770Speaker configurations other than those described here are not supported.
771</t>
772</section>
773
774<section anchor="channel_mapping_255"
775 title="Channel Mapping Family 255">
776<t>
777Allowed numbers of channels: 1...255.
778No defined channel meaning.
779</t>
780<t>
781Channels are unidentified.
782General-purpose players SHOULD NOT attempt to play these streams, and offline
783 decoders MAY deinterleave the output into separate PCM files, one per channel.
784Decoders SHOULD NOT produce output for channels mapped to stream index 255
785 (pure silence) unless they have no other way to indicate the index of
786 non-silent channels.
787</t>
788</section>
789
790<section anchor="channel_mapping_undefined"
791 title="Undefined Channel Mappings">
792<t>
793The remaining channel mapping families (2...254) are reserved.
794A decoder encountering a reserved channel mapping family value SHOULD act as
795 though the value is 255.
796</t>
797</section>
798
799<section anchor="downmix" title="Downmixing">
800<t>
801An Ogg Opus player MUST play any Ogg Opus stream with a channel mapping family
802 of 0 or 1, even if the number of channels does not match the physically
803 connected audio hardware.
804Players SHOULD perform channel mixing to increase or reduce the number of
805 channels as needed.
806</t>
807
808<t>
809Implementations MAY use the following matricies to implement downmixing from
810 multichannel files using <xref target="channel_mapping_1">Channel Mapping
811 Family 1</xref>, which are known to give acceptable results for stereo.
812Matricies for 3 and 4 channels are normalized so each coefficent row sums
813 to 1 to avoid clipping.
814For 5 or more channels they are normalized to 2 as a compromize between
815 clipping and dynamic range reduction.
816</t>
817<t>
818In these matricies the front left and front right channels are generally
819passed through directly.
820When a surround channel is split between both the left and right stereo
821 channels, coefficients are chosen so their squares sum to 1, which
822 helps preserve the perceived intensity.
823Rear channels are mixed more diffusely or attenuated to maintain focus
824 on the front channels.
825</t>
826
827<figure anchor="downmix-matrix-3"
828 title="Stereo downmix matrix for the linear surround channel mapping"
829 align="center">
830<artwork align="center"><![CDATA[
831 Left output = ( 0.585786 * left + 0.414214 * center )
832Right output = ( 0.414214 * center + 0.585786 * right )
833]]></artwork>
834<postamble>
835Exact coefficient values are 1 and 1/sqrt(2), multiplied by
836 1/(1 + 1/sqrt(2)) for normalization.
837</postamble>
838</figure>
839
840<figure anchor="downmix-matrix-4"
841 title="Stereo downmix matrix for the quadraphonic channel mapping"
842 align="center">
843<artwork align="center"><![CDATA[
844/ \ / \ / FL \
845| L output | | 0.422650 0.000000 0.366025 0.211325 | | FR |
846| R output | = | 0.000000 0.422650 0.211325 0.366025 | | RL |
847\ / \ / \ RR /
848]]></artwork>
849<postamble>
850Exact coefficient values are 1, sqrt(3)/2 and 1/2, multiplied by
851 1/(1&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2) for normalization.
852</postamble>
853</figure>
854
855<figure anchor="downmix-matrix-5"
856 title="Stereo downmix matrix for the 5.0 surround mapping"
857 align="center">
858<artwork align="center"><![CDATA[
859 / FL \
860/ \ / \ | FC |
861| L | | 0.650802 0.460186 0.000000 0.563611 0.325401 | | FR |
862| R | = | 0.000000 0.460186 0.650802 0.325401 0.563611 | | RL |
863\ / \ / | RR |
864 \ /
865]]></artwork>
866<postamble>
867Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by
868 2/(1&nbsp;+&nbsp;1/sqrt(2)&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2)
869 for normalization.
870</postamble>
871</figure>
872
873<figure anchor="downmix-matrix-6"
874 title="Stereo downmix matrix for the 5.1 surround mapping"
875 align="center">
876<artwork align="center"><![CDATA[
877 /FL \
878/ \ / \ |FC |
879|L| | 0.529067 0.374107 0.000000 0.458186 0.264534 0.374107 | |FR |
880|R| = | 0.000000 0.374107 0.529067 0.264534 0.458186 0.374107 | |RL |
881\ / \ / |RR |
882 \LFE/
883]]></artwork>
884<postamble>
885Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by
8862/(1&nbsp;+&nbsp;1/sqrt(2)&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2 + 1/sqrt(2))
887 for normalization.
888</postamble>
889</figure>
890
891<figure anchor="downmix-matrix-7"
892 title="Stereo downmix matrix for the 6.1 surround mapping"
893 align="center">
894<artwork align="center"><![CDATA[
895 / \
896 | 0.455310 0.321953 0.000000 0.394310 0.227655 0.278819 0.321953 |
897 | 0.000000 0.321953 0.455310 0.227655 0.394310 0.278819 0.321953 |
898 \ /
899]]></artwork>
900<postamble>
901Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2, 1/2 and
902 sqrt(3)/2/sqrt(2), multiplied by
903 2/(1&nbsp;+&nbsp;1/sqrt(2)&nbsp;+&nbsp;sqrt(3)/2&nbsp;+&nbsp;1/2 +
904 sqrt(3)/2/sqrt(2) + 1/sqrt(2)) for normalization.
905The coeffients are in the same order as in <xref target="channel_mapping_1" />,
906 and the matricies above.
907</postamble>
908</figure>
909
910<figure anchor="downmix-matrix-8"
911 title="Stereo downmix matrix for the 7.1 surround mapping"
912 align="center">
913<artwork align="center"><![CDATA[
914/ \
915| .388631 .274804 .000000 .336565 .194316 .336565 .194316 .274804 |
916| .000000 .274804 .388631 .194316 .336565 .194316 .336565 .274804 |
917\ /
918]]></artwork>
919<postamble>
920Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by
921 2/(2&nbsp;+&nbsp;2/sqrt(2)&nbsp;+&nbsp;sqrt(3)) for normalization.
922The coeffients are in the same order as in <xref target="channel_mapping_1" />,
923 and the matricies above.
924</postamble>
925</figure>
926
927</section>
928
929</section> <!-- end channel_mapping_table -->
930
931</section> <!-- end id_header -->
932
933<section anchor="comment_header" title="Comment Header">
934
935<figure anchor="comment_header_packet" title="Comment Header Packet"
936 align="center">
937<artwork align="center"><![CDATA[
938 0 1 2 3
939 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
940+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
941| 'O' | 'p' | 'u' | 's' |
942+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
943| 'T' | 'a' | 'g' | 's' |
944+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
945| Vendor String Length |
946+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
947| |
948: Vendor String... :
949| |
950+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
951| User Comment List Length |
952+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
953| User Comment #0 String Length |
954+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
955| |
956: User Comment #0 String... :
957| |
958+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
959| User Comment #1 String Length |
960+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
961: :
962]]></artwork>
963</figure>
964
965<t>
966The comment header consists of a 64-bit magic signature, followed by data in
967 the same format as the <xref target="vorbis-comment"/> header used in Ogg
968 Vorbis (without the final "framing bit"), Ogg Theora, and Speex.
969<list style="numbers">
970<t><spanx style="strong">Magic Signature</spanx>:
971<vspace blankLines="1"/>
972This is an 8-octet (64-bit) field that allows codec identification and is
973 human-readable.
974It contains, in order, the magic numbers:
975<list style="empty">
976<t>0x4F 'O'</t>
977<t>0x70 'p'</t>
978<t>0x75 'u'</t>
979<t>0x73 's'</t>
980<t>0x54 'T'</t>
981<t>0x61 'a'</t>
982<t>0x67 'g'</t>
983<t>0x73 's'</t>
984</list>
985Starting with "Op" helps distinguish it from audio data packets, as this is an
986 invalid TOC sequence.
987<vspace blankLines="1"/>
988</t>
989<t><spanx style="strong">Vendor String Length</spanx> (32 bits, unsigned,
990 little endian):
991<vspace blankLines="1"/>
992This field gives the length of the following vendor string, in octets.
993It MUST NOT indicate that the vendor string is longer than the rest of the
994 packet.
995<vspace blankLines="1"/>
996</t>
997<t><spanx style="strong">Vendor String</spanx> (variable length, UTF-8 vector):
998<vspace blankLines="1"/>
999This is a simple human-readable tag for vendor information, encoded as a UTF-8
1000 string&nbsp;<xref target="RFC3629"/>.
1001No terminating null octet is required.
1002<vspace blankLines="1"/>
1003This tag is intended to identify the codec encoder and encapsulation
1004 implementations, for tracing differences in technical behavior.
1005User-facing encoding applications can use the 'ENCODER' user comment tag
1006 to identify themselves.
1007<vspace blankLines="1"/>
1008</t>
1009<t><spanx style="strong">User Comment List Length</spanx> (32 bits, unsigned,
1010 little endian):
1011<vspace blankLines="1"/>
1012This field indicates the number of user-supplied comments.
1013It MAY indicate there are zero user-supplied comments, in which case there are
1014 no additional fields in the packet.
1015It MUST NOT indicate that there are so many comments that the comment string
1016 lengths would require more data than is available in the rest of the packet.
1017<vspace blankLines="1"/>
1018</t>
1019<t><spanx style="strong">User Comment #i String Length</spanx> (32 bits,
1020 unsigned, little endian):
1021<vspace blankLines="1"/>
1022This field gives the length of the following user comment string, in octets.
1023There is one for each user comment indicated by the 'user comment list length'
1024 field.
1025It MUST NOT indicate that the string is longer than the rest of the packet.
1026<vspace blankLines="1"/>
1027</t>
1028<t><spanx style="strong">User Comment #i String</spanx> (variable length, UTF-8
1029 vector):
1030<vspace blankLines="1"/>
1031This field contains a single user comment string.
1032There is one for each user comment indicated by the 'user comment list length'
1033 field.
1034</t>
1035</list>
1036</t>
1037
1038<t>
1039The vendor string length and user comment list length are REQUIRED, and
1040 implementations SHOULD reject comment headers that do not contain enough data
1041 for these fields, or that do not contain enough data for the corresponding
1042 vendor string or user comments they describe.
1043Making this check before allocating the associated memory to contain the data
1044 may help prevent a possible Denial-of-Service (DoS) attack from small comment
1045 headers that claim to contain strings longer than the entire packet or more
1046 user comments than than could possibly fit in the packet.
1047</t>
1048
1049<t>
1050The user comment strings follow the NAME=value format described by
1051 <xref target="vorbis-comment"/> with the same recommended tag names.
1052One new comment tag is introduced for Ogg Opus:
1053<figure align="center">
1054<artwork align="left"><![CDATA[
1055R128_TRACK_GAIN=-573
1056]]></artwork>
1057</figure>
1058representing the volume shift needed to normalize the track's volume.
1059The gain is a Q7.8 fixed point number in dB, as in the ID header's 'output
1060 gain' field.
1061This tag is similar to the REPLAYGAIN_TRACK_GAIN tag in
1062 Vorbis&nbsp;<xref target="replay-gain"/>, except that the normal volume
1063 reference is the <xref target="EBU-R128"/> standard.
1064</t>
1065<t>
1066An Ogg Opus file MUST NOT have more than one such tag, and if present its
1067 value MUST be an integer from -32768 to 32767, inclusive, represented in
1068 ASCII with no whitespace.
1069If present, it MUST correctly represent the R128 normalization gain relative
1070 to the 'output gain' field specified in the ID header.
1071If a player chooses to make use of the R128_TRACK_GAIN tag, it MUST be
1072 applied <spanx style="emph">in addition</spanx> to the 'output gain' value.
1073If an encoder wishes to use R128 normalization, and the output gain is not
1074 otherwise constrained or specified, the encoder SHOULD write the R128 gain
1075 into the 'output gain' field and store a tag containing "R128_TRACK_GAIN=0".
1076That is, it should assume that by default tools will respect the 'output gain'
1077 field, and not the comment tag.
1078If a tool modifies the ID header's 'output gain' field, it MUST also update or
1079 remove the R128_TRACK_GAIN comment tag.
1080</t>
1081<t>
1082To avoid confusion with multiple normalization schemes, an Opus comment header
1083 SHOULD NOT contain any of the REPLAYGAIN_TRACK_GAIN, REPLAYGAIN_TRACK_PEAK,
1084 REPLAYGAIN_ALBUM_GAIN, or REPLAYGAIN_ALBUM_PEAK tags.
1085</t>
1086<t>
1087There is no Opus comment tag corresponding to REPLAYGAIN_ALBUM_GAIN.
1088That information should instead be stored in the ID header's 'output gain'
1089 field.
1090</t>
1091</section>
1092
1093</section>
1094
1095<section anchor="packet_size_limits" title="Packet Size Limits">
1096<t>
1097Technically valid Opus packets can be arbitrarily large due to the padding
1098 format, although the amount of non-padding data they can contain is bounded.
1099These packets might be spread over a similarly enormous number of Ogg pages.
1100Encoders SHOULD use no more padding than required to make a variable bitrate
1101 (VBR) stream constant bitrate (CBR).
1102Decoders SHOULD avoid attempting to allocate excessive amounts of memory when
1103 presented with a very large packet.
1104The presence of an extremely large packet in the stream could indicate a
1105 memory exhaustion attack or stream corruption.
1106Decoders SHOULD reject a packet that is too large to process, and display a
1107 warning message.
1108</t>
1109<t>
1110In an Ogg Opus stream, the largest possible valid packet that does not use
1111 padding has a size of (61,298*N&nbsp;-&nbsp;2) octets, or about 60&nbsp;kB per
1112 Opus stream.
1113With 255&nbsp;streams, this is 15,630,988&nbsp;octets (14.9&nbsp;MB) and can
1114 span up to 61,298&nbsp;Ogg pages, all but one of which will have a granule
1115 position of -1.
1116This is of course a very extreme packet, consisting of 255&nbsp;streams, each
1117 containing 120&nbsp;ms of audio encoded as 2.5&nbsp;ms frames, each frame
1118 using the maximum possible number of octets (1275) and stored in the least
1119 efficient manner allowed (a VBR code&nbsp;3 Opus packet).
1120Even in such a packet, most of the data will be zeros as 2.5&nbsp;ms frames
1121 cannot actually use all 1275&nbsp;octets.
1122The largest packet consisting of entirely useful data is
1123 (15,326*N&nbsp;-&nbsp;2) octets, or about 15&nbsp;kB per stream.
1124This corresponds to 120&nbsp;ms of audio encoded as 10&nbsp;ms frames in either
1125 LP or Hybrid mode, but at a data rate of over 1&nbsp;Mbps, which makes little
1126 sense for the quality achieved.
1127A more reasonable limit is (7,664*N&nbsp;-&nbsp;2) octets, or about 7.5&nbsp;kB
1128 per stream.
1129This corresponds to 120&nbsp;ms of audio encoded as 20&nbsp;ms stereo MDCT-mode
1130 frames, with a total bitrate just under 511&nbsp;kbps (not counting the Ogg
1131 encapsulation overhead).
1132With N=8, the maximum number of channels currently defined by mapping
1133 family&nbsp;1, this gives a maximum packet size of 61,310&nbsp;octets, or just
1134 under 60&nbsp;kB.
1135This is still quite conservative, as it assumes each output channel is taken
1136 from one decoded channel of a stereo packet.
1137An implementation could reasonably choose any of these numbers for its internal
1138 limits.
1139</t>
1140</section>
1141
1142<section anchor="encoder" title="Encoder Guidelines">
1143<t>
1144When encoding Opus files, Ogg encoders should take into account the
1145 algorithmic delay of the Opus encoder.
1146</t>
1147<figure align="center">
1148<preamble>
1149In encoders derived from the reference implementation, the number of
1150 samples can be queried with:
1151</preamble>
1152<artwork align="center"><![CDATA[
1153 opus_encoder_ctl(encoder_state, OPUS_GET_LOOKAHEAD, &samples_delay);
1154]]></artwork>
1155</figure>
1156<t>
1157To achieve good quality in the very first samples of a stream, the Ogg encoder
1158 MAY use LPC extrapolation to generate at least 120 extra samples
1159 (extra_samples) at the beginning to avoid the Opus encoder having to encode
1160 a discontinuous signal.
1161For an input file containing length samples, the Ogg encoder SHOULD set the
1162 preskip header flag to samples_delay+extra_samples, encode at least
1163 length+samples_delay+extra_samples samples, and set the granulepos of the last
1164 page to length+samples_delay+extra_samples.
1165This ensures that the encoded file has the same duration as the original, with
1166 no time offset. The best way to pad the end of the stream is to also use LPC
1167 extrapolation, but zero-padding is also acceptable.
1168</t>
1169
1170<section anchor="lpc" title="LPC Extrapolation">
1171<t>
1172The first step in LPC extrapolation is to compute linear prediction
1173 coefficients.
1174When extending the end of the signal, order-N (typically with N ranging from 8
1175 to 40) LPC analysis is performed on a window near the end of the signal.
1176The last N samples are used as memory to an infinite impulse response (IIR)
1177 filter.
1178</t>
1179<figure align="center">
1180<preamble>
1181The filter is then applied on a zero input to extrapolate the end of the signal.
1182Let a(k) be the kth LPC coefficient and x(n) be the nth sample of the signal,
1183 each new sample past the end of the signal is computed as:
1184</preamble>
1185<artwork align="center"><![CDATA[
1186 N
1187 ---
1188x(n) = \ a(k)*x(n-k)
1189 /
1190 ---
1191 k=1
1192]]></artwork>
1193</figure>
1194<t>
1195The process is repeated independently for each channel.
1196It is possible to extend the beginning of the signal by applying the same
1197 process backward in time.
1198When extending the beginning of the signal, it is best to apply a "fade in" to
1199 the extrapolated signal, e.g. by multiplying it by a half-Hanning window
1200 <xref target="hanning"/>.
1201</t>
1202
1203</section>
1204
1205<section anchor="continuous_chaining" title="Continuous Chaining">
1206<t>
1207In some applications, such as Internet radio, it is desirable to cut a long
1208 streams into smaller chains, e.g. so the comment header can be updated.
1209This can be done simply by separating the input streams into segments and
1210 encoding each segment independently.
1211The drawback of this approach is that it creates a small discontinuity
1212 at the boundary due to the lossy nature of Opus.
1213An encoder MAY avoid this discontinuity by using the following procedure:
1214<list style="numbers">
1215<t>Encode the last frame of the first segment as an independent frame by
1216 turning off all forms of inter-frame prediction.
1217De-emphasis is allowed.</t>
1218<t>Set the granulepos of the last page to a point near the end of the last
1219 frame.</t>
1220<t>Begin the second segment with a copy of the last frame of the first
1221 segment.</t>
1222<t>Set the preskip flag of the second stream in such a way as to properly
1223 join the two streams.</t>
1224<t>Continue the encoding process normally from there, without any reset to
1225 the encoder.</t>
1226</list>
1227</t>
1228</section>
1229
1230</section>
1231
1232<section anchor="implementation" title="Implementation Status">
1233<t>
1234A brief summary of major implementations of this draft is available
1235 at <eref target="https://wiki.xiph.org/OggOpusImplementation"/>,
1236 along with their status.
1237</t>
1238<t>
1239[Note to RFC Editor: please remove this entire section before
1240 final publication per <xref target="draft-sheffer-running-code"/>.]
1241</t>
1242</section>
1243
1244<section anchor="security" title="Security Considerations">
1245<t>
1246Implementations of the Opus codec need to take appropriate security
1247 considerations into account, as outlined in <xref target="RFC4732"/>.
1248This is just as much a problem for the container as it is for the codec itself.
1249It is extremely important for the decoder to be robust against malicious
1250 payloads.
1251Malicious payloads must not cause the decoder to overrun its allocated memory
1252 or to take an excessive amount of resources to decode.
1253Although problems in encoders are typically rarer, the same applies to the
1254 encoder.
1255Malicious audio streams must not cause the encoder to misbehave because this
1256 would allow an attacker to attack transcoding gateways.
1257</t>
1258
1259<t>
1260Like most other container formats, Ogg Opus files should not be used with
1261 insecure ciphers or cipher modes that are vulnerable to known-plaintext
1262 attacks.
1263Elements such as the Ogg page capture pattern and the magic signatures in the
1264 ID header and the comment header all have easily predictable values, in
1265 addition to various elements of the codec data itself.
1266</t>
1267</section>
1268
1269<section anchor="content_type" title="Content Type">
1270<t>
1271An "Ogg Opus file" consists of one or more sequentially multiplexed segments,
1272 each containing exactly one Ogg Opus stream.
1273The RECOMMENDED mime-type for Ogg Opus files is "audio/ogg".
1274</t>
1275
1276<figure>
1277<preamble>
1278If more specificity is desired, one MAY indicate the presence of Opus streams
1279 using the codecs parameter defined in <xref target="RFC6381"/>, e.g.,
1280</preamble>
1281<artwork align="center"><![CDATA[
1282 audio/ogg; codecs=opus
1283]]></artwork>
1284<postamble>
1285 for an Ogg Opus file.
1286</postamble>
1287</figure>
1288
1289<t>
1290The RECOMMENDED filename extension for Ogg Opus files is '.opus'.
1291</t>
1292
1293<t>
1294When Opus is concurrently multiplexed with other streams in an Ogg container,
1295 one SHOULD use one of the "audio/ogg", "video/ogg", or "application/ogg"
1296 mime-types, as defined in <xref target="RFC5334"/>.
1297Such streams are not strictly "Ogg Opus files" as described above,
1298 since they contain more than a single Opus stream per sequentially
1299 multiplexed segment, e.g. video or multiple audio tracks.
1300In such cases the the '.opus' filename extension is NOT RECOMMENDED.
1301</t>
1302</section>
1303
1304<section title="IANA Considerations">
1305<t>
1306This document has no actions for IANA.
1307</t>
1308</section>
1309
1310<section anchor="Acknowledgments" title="Acknowledgments">
1311<t>
1312Thanks to Greg Maxwell, Christopher "Monty" Montgomery, and Jean-Marc Valin for
1313 their valuable contributions to this document.
1314Additional thanks to Andrew D'Addesio, Greg Maxwell, and Vincent Penqeurc'h for
1315 their feedback based on early implementations.
1316</t>
1317</section>
1318
1319<section title="Copying Conditions">
1320<t>
1321The authors agree to grant third parties the irrevocable right to copy, use,
1322 and distribute the work, with or without modification, in any medium, without
1323 royalty, provided that, unless separate permission is granted, redistributed
1324 modified works do not contain misleading author, version, name of work, or
1325 endorsement information.
1326</t>
1327</section>
1328
1329</middle>
1330<back>
1331<references title="Normative References">
1332 &rfc2119;
1333 &rfc3533;
1334 &rfc3629;
1335 &rfc5334;
1336 &rfc6381;
1337 &rfc6716;
1338
1339<reference anchor="EBU-R128" target="http://tech.ebu.ch/loudness">
1340<front>
1341<title>"Loudness Recommendation EBU R128</title>
1342<author fullname="EBU Technical Committee"/>
1343<date month="August" year="2011"/>
1344</front>
1345</reference>
1346
1347<reference anchor="vorbis-comment"
1348 target="http://www.xiph.org/vorbis/doc/v-comment.html">
1349<front>
1350<title>Ogg Vorbis I Format Specification: Comment Field and Header
1351 Specification</title>
1352<author initials="C." surname="Montgomery"
1353 fullname="Christopher &quot;Monty&quot; Montgomery"/>
1354<date month="July" year="2002"/>
1355</front>
1356</reference>
1357
1358</references>
1359
1360<references title="Informative References">
1361
1362<!--?rfc include="http://xml.resource.org/public/rfc/bibxml/reference.RFC.3550.xml"?-->
1363 &rfc4732;
1364
1365<reference anchor="draft-sheffer-running-code"
1366 target="https://tools.ietf.org/html/draft-sheffer-running-code-05#section-2">
1367 <front>
1368 <title>Improving "Rough Consensus" with Running Code</title>
1369 <author initials="Y." surname="Sheffer" fullname="Yaron Sheffer"/>
1370 <author initials="A." surname="Farrel" fullname="Adrian Farrel"/>
1371 <date month="May" year="2013"/>
1372 </front>
1373</reference>
1374
1375<reference anchor="flac"
1376 target="https://xiph.org/flac/format.html">
1377 <front>
1378 <title>FLAC - Free Lossless Audio Codec Format Description</title>
1379 <author initials="J." surname="Coalson" fullname="Josh Coalson"/>
1380 <date month="January" year="2008"/>
1381 </front>
1382</reference>
1383
1384<reference anchor="hanning"
1385 target="http://en.wikipedia.org/wiki/Hamming_function#Hann_.28Hanning.29_window">
1386 <front>
1387 <title>"Hann window</title>
1388 <author fullname="Wikipedia"/>
1389 <date month="May" year="2013"/>
1390 </front>
1391</reference>
1392
1393<reference anchor="replay-gain"
1394 target="http://wiki.xiph.org/VorbisComment#Replay_Gain">
1395<front>
1396<title>VorbisComment: Replay Gain</title>
1397<author initials="C." surname="Parker" fullname="Conrad Parker"/>
1398<author initials="M." surname="Leese" fullname="Martin Leese"/>
1399<date month="June" year="2009"/>
1400</front>
1401</reference>
1402
1403<reference anchor="seeking"
1404 target="http://wiki.xiph.org/Seeking">
1405<front>
1406<title>Granulepos Encoding and How Seeking Really Works</title>
1407<author initials="S." surname="Pfeiffer" fullname="Silvia Pfeiffer"/>
1408<author initials="C." surname="Parker" fullname="Conrad Parker"/>
1409<author initials="G." surname="Maxwell" fullname="Greg Maxwell"/>
1410<date month="May" year="2012"/>
1411</front>
1412</reference>
1413
1414<reference anchor="vorbis-mapping"
1415 target="http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9">
1416<front>
1417<title>The Vorbis I Specification, Section 4.3.9 Output Channel Order</title>
1418<author initials="C." surname="Montgomery"
1419 fullname="Christopher &quot;Monty&quot; Montgomery"/>
1420<date month="January" year="2010"/>
1421</front>
1422</reference>
1423
1424<reference anchor="vorbis-trim"
1425 target="http://xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-130000A.2">
1426 <front>
1427 <title>The Vorbis I Specification, Appendix&nbsp;A: Embedding Vorbis
1428 into an Ogg stream</title>
1429 <author initials="C." surname="Montgomery"
1430 fullname="Christopher &quot;Monty&quot; Montgomery"/>
1431 <date month="November" year="2008"/>
1432 </front>
1433</reference>
1434
1435<reference anchor="wave-multichannel"
1436 target="http://msdn.microsoft.com/en-us/windows/hardware/gg463006.aspx">
1437 <front>
1438 <title>Multiple Channel Audio Data and WAVE Files</title>
1439 <author fullname="Microsoft Corporation"/>
1440 <date month="March" year="2007"/>
1441 </front>
1442</reference>
1443
1444</references>
1445
1446</back>
1447</rfc>