idnits 2.17.1 draft-ietf-codec-oggopus-14.txt: Checking boilerplate required by RFC 5378 and the IETF Trust (see https://trustee.ietf.org/license-info): ---------------------------------------------------------------------------- No issues found here. Checking nits according to https://www.ietf.org/id-info/1id-guidelines.txt: ---------------------------------------------------------------------------- No issues found here. Checking nits according to https://www.ietf.org/id-info/checklist : ---------------------------------------------------------------------------- -- The draft header indicates that this document updates RFC5334, but the abstract doesn't seem to mention this, which it should. Miscellaneous warnings: ---------------------------------------------------------------------------- == The copyright year in the IETF Trust and authors Copyright Line does not match the current year (Using the creation date from RFC5334, updated by this document, for RFC5378 checks: 2007-12-03) -- The document seems to lack a disclaimer for pre-RFC5378 work, but may have content which was first submitted before 10 November 2008. If you have contacted all the original authors and they are all willing to grant the BCP78 rights to the IETF Trust, then this is fine, and you can ignore this comment. If not, you may need to add the pre-RFC5378 disclaimer. (See the Legal Provisions document at https://trustee.ietf.org/license-info for more information.) -- The document date (February 22, 2016) is 2986 days in the past. Is this intentional? Checking references for intended status: Proposed Standard ---------------------------------------------------------------------------- (See RFCs 3967 and 4897 for information about using normative references to lower-maturity documents in RFCs) -- Looks like a reference, but probably isn't: '1' on line 1522 -- Looks like a reference, but probably isn't: '8' on line 1364 == Missing Reference: 'RFCXXXX' is mentioned on line 1398, but not defined ** Downref: Normative reference to an Informational RFC: RFC 3533 ** Obsolete normative reference: RFC 5226 (Obsoleted by RFC 8126) -- Possible downref: Non-RFC (?) normative reference: ref. 'EBU-R128' -- Obsolete informational reference (is this intentional?): RFC 6982 (Obsoleted by RFC 7942) Summary: 2 errors (**), 0 flaws (~~), 2 warnings (==), 7 comments (--). Run idnits with the --verbose option for more detailed information about the items above. -------------------------------------------------------------------------------- 2 codec T. Terriberry 3 Internet-Draft Mozilla Corporation 4 Updates: 5334 (if approved) R. Lee 5 Intended status: Standards Track Voicetronix 6 Expires: August 25, 2016 R. Giles 7 Mozilla Corporation 8 February 22, 2016 10 Ogg Encapsulation for the Opus Audio Codec 11 draft-ietf-codec-oggopus-14 13 Abstract 15 This document defines the Ogg encapsulation for the Opus interactive 16 speech and audio codec. This allows data encoded in the Opus format 17 to be stored in an Ogg logical bitstream. 19 Status of This Memo 21 This Internet-Draft is submitted in full conformance with the 22 provisions of BCP 78 and BCP 79. 24 Internet-Drafts are working documents of the Internet Engineering 25 Task Force (IETF). Note that other groups may also distribute 26 working documents as Internet-Drafts. The list of current Internet- 27 Drafts is at http://datatracker.ietf.org/drafts/current/. 29 Internet-Drafts are draft documents valid for a maximum of six months 30 and may be updated, replaced, or obsoleted by other documents at any 31 time. It is inappropriate to use Internet-Drafts as reference 32 material or to cite them other than as "work in progress." 34 This Internet-Draft will expire on August 25, 2016. 36 Copyright Notice 38 Copyright (c) 2016 IETF Trust and the persons identified as the 39 document authors. All rights reserved. 41 This document is subject to BCP 78 and the IETF Trust's Legal 42 Provisions Relating to IETF Documents 43 (http://trustee.ietf.org/license-info) in effect on the date of 44 publication of this document. Please review these documents 45 carefully, as they describe your rights and restrictions with respect 46 to this document. Code Components extracted from this document must 47 include Simplified BSD License text as described in Section 4.e of 48 the Trust Legal Provisions and are provided without warranty as 49 described in the Simplified BSD License. 51 Table of Contents 53 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2 54 2. Terminology . . . . . . . . . . . . . . . . . . . . . . . . . 3 55 3. Packet Organization . . . . . . . . . . . . . . . . . . . . . 3 56 4. Granule Position . . . . . . . . . . . . . . . . . . . . . . 6 57 4.1. Repairing Gaps in Real-time Streams . . . . . . . . . . . 7 58 4.2. Pre-skip . . . . . . . . . . . . . . . . . . . . . . . . 8 59 4.3. PCM Sample Position . . . . . . . . . . . . . . . . . . . 9 60 4.4. End Trimming . . . . . . . . . . . . . . . . . . . . . . 10 61 4.5. Restrictions on the Initial Granule Position . . . . . . 10 62 4.6. Seeking and Pre-roll . . . . . . . . . . . . . . . . . . 11 63 5. Header Packets . . . . . . . . . . . . . . . . . . . . . . . 11 64 5.1. Identification Header . . . . . . . . . . . . . . . . . . 12 65 5.1.1. Channel Mapping . . . . . . . . . . . . . . . . . . . 16 66 5.2. Comment Header . . . . . . . . . . . . . . . . . . . . . 21 67 5.2.1. Tag Definitions . . . . . . . . . . . . . . . . . . . 24 68 6. Packet Size Limits . . . . . . . . . . . . . . . . . . . . . 26 69 7. Encoder Guidelines . . . . . . . . . . . . . . . . . . . . . 27 70 7.1. LPC Extrapolation . . . . . . . . . . . . . . . . . . . . 27 71 7.2. Continuous Chaining . . . . . . . . . . . . . . . . . . . 28 72 8. Implementation Status . . . . . . . . . . . . . . . . . . . . 28 73 9. Security Considerations . . . . . . . . . . . . . . . . . . . 29 74 10. Content Type . . . . . . . . . . . . . . . . . . . . . . . . 30 75 11. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 30 76 12. Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . 31 77 13. RFC Editor Notes . . . . . . . . . . . . . . . . . . . . . . 31 78 14. References . . . . . . . . . . . . . . . . . . . . . . . . . 32 79 14.1. Normative References . . . . . . . . . . . . . . . . . . 32 80 14.2. Informative References . . . . . . . . . . . . . . . . . 32 81 14.3. URIs . . . . . . . . . . . . . . . . . . . . . . . . . . 34 82 Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . 34 84 1. Introduction 86 The IETF Opus codec is a low-latency audio codec optimized for both 87 voice and general-purpose audio. See [RFC6716] for technical 88 details. This document defines the encapsulation of Opus in a 89 continuous, logical Ogg bitstream [RFC3533]. Ogg encapsulation 90 provides Opus with a long-term storage format supporting all of the 91 essential features, including metadata, fast and accurate seeking, 92 corruption detection, recapture after errors, low overhead, and the 93 ability to multiplex Opus with other codecs (including video) with 94 minimal buffering. It also provides a live streamable format, 95 capable of delivery over a reliable stream-oriented transport, 96 without requiring all the data, or even the total length of the data, 97 up-front, in a form that is identical to the on-disk storage format. 99 Ogg bitstreams are made up of a series of 'pages', each of which 100 contains data from one or more 'packets'. Pages are the fundamental 101 unit of multiplexing in an Ogg stream. Each page is associated with 102 a particular logical stream and contains a capture pattern and 103 checksum, flags to mark the beginning and end of the logical stream, 104 and a 'granule position' that represents an absolute position in the 105 stream, to aid seeking. A single page can contain up to 65,025 106 octets of packet data from up to 255 different packets. Packets can 107 be split arbitrarily across pages, and continued from one page to the 108 next (allowing packets much larger than would fit on a single page). 109 Each page contains 'lacing values' that indicate how the data is 110 partitioned into packets, allowing a demultiplexer (demuxer) to 111 recover the packet boundaries without examining the encoded data. A 112 packet is said to 'complete' on a page when the page contains the 113 final lacing value corresponding to that packet. 115 This encapsulation defines the contents of the packet data, including 116 the necessary headers, the organization of those packets into a 117 logical stream, and the interpretation of the codec-specific granule 118 position field. It does not attempt to describe or specify the 119 existing Ogg container format. Readers unfamiliar with the basic 120 concepts mentioned above are encouraged to review the details in 121 [RFC3533]. 123 2. Terminology 125 The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", 126 "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and 127 "OPTIONAL" in this document are to be interpreted as described in 128 [RFC2119]. 130 3. Packet Organization 132 An Ogg Opus stream is organized as follows (see Figure 1 for an 133 example). 135 Page 0 Pages 1 ... n Pages (n+1) ... 136 +------------+ +---+ +---+ ... +---+ +-----------+ +---------+ +-- 137 | | | | | | | | | | | | | 138 |+----------+| |+-----------------+| |+-------------------+ +----- 139 |||ID Header|| || Comment Header || ||Audio Data Packet 1| | ... 140 |+----------+| |+-----------------+| |+-------------------+ +----- 141 | | | | | | | | | | | | | 142 +------------+ +---+ +---+ ... +---+ +-----------+ +---------+ +-- 143 ^ ^ ^ 144 | | | 145 | | Mandatory Page Break 146 | | 147 | ID header is contained on a single page 148 | 149 'Beginning Of Stream' 151 Figure 1: Example packet organization for a logical Ogg Opus stream 153 There are two mandatory header packets. The first packet in the 154 logical Ogg bitstream MUST contain the identification (ID) header, 155 which uniquely identifies a stream as Opus audio. The format of this 156 header is defined in Section 5.1. It is placed alone (without any 157 other packet data) on the first page of the logical Ogg bitstream, 158 and completes on that page. This page has its 'beginning of stream' 159 flag set. 161 The second packet in the logical Ogg bitstream MUST contain the 162 comment header, which contains user-supplied metadata. The format of 163 this header is defined in Section 5.2. It MAY span multiple pages, 164 beginning on the second page of the logical stream. However many 165 pages it spans, the comment header packet MUST finish the page on 166 which it completes. 168 All subsequent pages are audio data pages, and the Ogg packets they 169 contain are audio data packets. Each audio data packet contains one 170 Opus packet for each of N different streams, where N is typically one 171 for mono or stereo, but MAY be greater than one for multichannel 172 audio. The value N is specified in the ID header (see 173 Section 5.1.1), and is fixed over the entire length of the logical 174 Ogg bitstream. 176 The first (N - 1) Opus packets, if any, are packed one after another 177 into the Ogg packet, using the self-delimiting framing from 178 Appendix B of [RFC6716]. The remaining Opus packet is packed at the 179 end of the Ogg packet using the regular, undelimited framing from 180 Section 3 of [RFC6716]. All of the Opus packets in a single Ogg 181 packet MUST be constrained to have the same duration. An 182 implementation of this specification SHOULD treat any Opus packet 183 whose duration is different from that of the first Opus packet in an 184 Ogg packet as if it were a malformed Opus packet with an invalid 185 Table Of Contents (TOC) sequence. 187 The TOC sequence at the beginning of each Opus packet indicates the 188 coding mode, audio bandwidth, channel count, duration (frame size), 189 and number of frames per packet, as described in Section 3.1 190 of [RFC6716]. The coding mode is one of SILK, Hybrid, or Constrained 191 Energy Lapped Transform (CELT). The combination of coding mode, 192 audio bandwidth, and frame size is referred to as the configuration 193 of an Opus packet. 195 Packets are placed into Ogg pages in order until the end of stream. 196 Audio data packets might span page boundaries. The first audio data 197 page could have the 'continued packet' flag set (indicating the first 198 audio data packet is continued from a previous page) if, for example, 199 it was a live stream joined mid-broadcast, with the headers pasted on 200 the front. If a page has the 'continued packet' flag set and one of 201 the following conditions is also true: 203 o the previous page with packet data does not end in a continued 204 packet (does not end with a lacing value of 255) OR 206 o the page sequence numbers are not consecutive, 208 then a demuxer MUST NOT attempt to decode the data for the first 209 packet on the page unless the demuxer has some special knowledge that 210 would allow it to interpret this data despite the missing pieces. An 211 implementation MUST treat a zero-octet audio data packet as if it 212 were a malformed Opus packet as described in Section 3.4 213 of [RFC6716]. 215 A logical stream ends with a page with the 'end of stream' flag set, 216 but implementations need to be prepared to deal with truncated 217 streams that do not have a page marked 'end of stream'. There is no 218 reason for the final packet on the last page to be a continued 219 packet, i.e., for the final lacing value to be 255. However, 220 demuxers might encounter such streams, possibly as the result of a 221 transfer that did not complete or of corruption. If a packet 222 continues onto a subsequent page (i.e., when the page ends with a 223 lacing value of 255) and one of the following conditions is also 224 true: 226 o the next page with packet data does not have the 'continued 227 packet' flag set OR 229 o there is no next page with packet data OR 230 o the page sequence numbers are not consecutive, 232 then a demuxer MUST NOT attempt to decode the data from that packet 233 unless the demuxer has some special knowledge that would allow it to 234 interpret this data despite the missing pieces. There MUST NOT be 235 any more pages in an Opus logical bitstream after a page marked 'end 236 of stream'. 238 4. Granule Position 240 The granule position MUST be zero for the ID header page and the page 241 where the comment header completes. That is, the first page in the 242 logical stream, and the last header page before the first audio data 243 page both have a granule position of zero. 245 The granule position of an audio data page encodes the total number 246 of PCM samples in the stream up to and including the last fully- 247 decodable sample from the last packet completed on that page. The 248 granule position of the first audio data page will usually be larger 249 than zero, as described in Section 4.5. 251 A page that is entirely spanned by a single packet (that completes on 252 a subsequent page) has no granule position, and the granule position 253 field is set to the special value '-1' in two's complement. 255 The granule position of an audio data page is in units of PCM audio 256 samples at a fixed rate of 48 kHz (per channel; a stereo stream's 257 granule position does not increment at twice the speed of a mono 258 stream). It is possible to run an Opus decoder at other sampling 259 rates, but all Opus packets encode samples at a sampling rate that 260 evenly divides 48 kHz. Therefore, the value in the granule position 261 field always counts samples assuming a 48 kHz decoding rate, and the 262 rest of this specification makes the same assumption. 264 The duration of an Opus packet as defined in [RFC6716] can be any 265 multiple of 2.5 ms, up to a maximum of 120 ms. This duration is 266 encoded in the TOC sequence at the beginning of each packet. The 267 number of samples returned by a decoder corresponds to this duration 268 exactly, even for the first few packets. For example, a 20 ms packet 269 fed to a decoder running at 48 kHz will always return 960 samples. A 270 demuxer can parse the TOC sequence at the beginning of each Ogg 271 packet to work backwards or forwards from a packet with a known 272 granule position (i.e., the last packet completed on some page) in 273 order to assign granule positions to every packet, or even every 274 individual sample. The one exception is the last page in the stream, 275 as described below. 277 All other pages with completed packets after the first MUST have a 278 granule position equal to the number of samples contained in packets 279 that complete on that page plus the granule position of the most 280 recent page with completed packets. This guarantees that a demuxer 281 can assign individual packets the same granule position when working 282 forwards as when working backwards. For this to work, there cannot 283 be any gaps. 285 4.1. Repairing Gaps in Real-time Streams 287 In order to support capturing a real-time stream that has lost or not 288 transmitted packets, a multiplexer (muxer) SHOULD emit packets that 289 explicitly request the use of Packet Loss Concealment (PLC) in place 290 of the missing packets. Implementations that fail to do so still 291 MUST NOT increment the granule position for a page by anything other 292 than the number of samples contained in packets that actually 293 complete on that page. 295 Only gaps that are a multiple of 2.5 ms are repairable, as these are 296 the only durations that can be created by packet loss or 297 discontinuous transmission. Muxers need not handle other gap sizes. 298 Creating the necessary packets involves synthesizing a TOC byte 299 (defined in Section 3.1 of [RFC6716])--and whatever additional 300 internal framing is needed--to indicate the packet duration for each 301 stream. The actual length of each missing Opus frame inside the 302 packet is zero bytes, as defined in Section 3.2.1 of [RFC6716]. 304 Zero-byte frames MAY be packed into packets using any of codes 0, 1, 305 2, or 3. When successive frames have the same configuration, the 306 higher code packings reduce overhead. Likewise, if the TOC 307 configuration matches, the muxer MAY further combine the empty frames 308 with previous or subsequent non-zero-length frames (using code 2 or 309 VBR code 3). 311 [RFC6716] does not impose any requirements on the PLC, but this 312 section outlines choices that are expected to have a positive 313 influence on most PLC implementations, including the reference 314 implementation. Synthesized TOC sequences SHOULD maintain the same 315 mode, audio bandwidth, channel count, and frame size as the previous 316 packet (if any). This is the simplest and usually the most well- 317 tested case for the PLC to handle and it covers all losses that do 318 not include a configuration switch, as defined in Section 4.5 319 of [RFC6716]. 321 When a previous packet is available, keeping the audio bandwidth and 322 channel count the same allows the PLC to provide maximum continuity 323 in the concealment data it generates. However, if the size of the 324 gap is not a multiple of the most recent frame size, then the frame 325 size will have to change for at least some frames. Such changes 326 SHOULD be delayed as long as possible to simplify things for PLC 327 implementations. 329 As an example, a 95 ms gap could be encoded as nineteen 5 ms frames 330 in two bytes with a single CBR code 3 packet. If the previous frame 331 size was 20 ms, using four 20 ms frames followed by three 5 ms frames 332 requires 4 bytes (plus an extra byte of Ogg lacing overhead), but 333 allows the PLC to use its well-tested steady state behavior for as 334 long as possible. The total bitrate of the latter approach, 335 including Ogg overhead, is about 0.4 kbps, so the impact on file size 336 is minimal. 338 Changing modes is discouraged, since this causes some decoder 339 implementations to reset their PLC state. However, SILK and Hybrid 340 mode frames cannot fill gaps that are not a multiple of 10 ms. If 341 switching to CELT mode is needed to match the gap size, a muxer 342 SHOULD do so at the end of the gap to allow the PLC to function for 343 as long as possible. 345 In the example above, if the previous frame was a 20 ms SILK mode 346 frame, the better solution is to synthesize a packet describing four 347 20 ms SILK frames, followed by a packet with a single 10 ms SILK 348 frame, and finally a packet with a 5 ms CELT frame, to fill the 95 ms 349 gap. This also requires four bytes to describe the synthesized 350 packet data (two bytes for a CBR code 3 and one byte each for two 351 code 0 packets) but three bytes of Ogg lacing overhead are needed to 352 mark the packet boundaries. At 0.6 kbps, this is still a minimal 353 bitrate impact over a naive, low quality solution. 355 Since medium-band audio is an option only in the SILK mode, wideband 356 frames SHOULD be generated if switching from that configuration to 357 CELT mode, to ensure that any PLC implementation which does try to 358 migrate state between the modes will be able to preserve all of the 359 available audio bandwidth. 361 4.2. Pre-skip 363 There is some amount of latency introduced during the decoding 364 process, to allow for overlap in the CELT mode, stereo mixing in the 365 SILK mode, and resampling. The encoder might have introduced 366 additional latency through its own resampling and analysis (though 367 the exact amount is not specified). Therefore, the first few samples 368 produced by the decoder do not correspond to real input audio, but 369 are instead composed of padding inserted by the encoder to compensate 370 for this latency. These samples need to be stored and decoded, as 371 Opus is an asymptotically convergent predictive codec, meaning the 372 decoded contents of each frame depend on the recent history of 373 decoder inputs. However, a player will want to skip these samples 374 after decoding them. 376 A 'pre-skip' field in the ID header (see Section 5.1) signals the 377 number of samples that SHOULD be skipped (decoded but discarded) at 378 the beginning of the stream, though some specific applications might 379 have a reason for looking at that data. This amount need not be a 380 multiple of 2.5 ms, MAY be smaller than a single packet, or MAY span 381 the contents of several packets. These samples are not valid audio. 383 For example, if the first Opus frame uses the CELT mode, it will 384 always produce 120 samples of windowed overlap-add data. However, 385 the overlap data is initially all zeros (since there is no prior 386 frame), meaning this cannot, in general, accurately represent the 387 original audio. The SILK mode requires additional delay to account 388 for its analysis and resampling latency. The encoder delays the 389 original audio to avoid this problem. 391 The pre-skip field MAY also be used to perform sample-accurate 392 cropping of already encoded streams. In this case, a value of at 393 least 3840 samples (80 ms) provides sufficient history to the decoder 394 that it will have converged before the stream's output begins. 396 4.3. PCM Sample Position 398 The PCM sample position is determined from the granule position using 399 the formula 401 'PCM sample position' = 'granule position' - 'pre-skip' . 403 For example, if the granule position of the first audio data page is 404 59,971, and the pre-skip is 11,971, then the PCM sample position of 405 the last decoded sample from that page is 48,000. 407 This can be converted into a playback time using the formula 409 'PCM sample position' 410 'playback time' = --------------------- . 411 48000.0 413 The initial PCM sample position before any samples are played is 414 normally '0'. In this case, the PCM sample position of the first 415 audio sample to be played starts at '1', because it marks the time on 416 the clock _after_ that sample has been played, and a stream that is 417 exactly one second long has a final PCM sample position of '48000', 418 as in the example here. 420 Vorbis streams use a granule position smaller than the number of 421 audio samples contained in the first audio data page to indicate that 422 some of those samples are trimmed from the output (see 423 [vorbis-trim]). However, to do so, Vorbis requires that the first 424 audio data page contains exactly two packets, in order to allow the 425 decoder to perform PCM position adjustments before needing to return 426 any PCM data. Opus uses the pre-skip mechanism for this purpose 427 instead, since the encoder might introduce more than a single 428 packet's worth of latency, and since very large packets in streams 429 with a very large number of channels might not fit on a single page. 431 4.4. End Trimming 433 The page with the 'end of stream' flag set MAY have a granule 434 position that indicates the page contains less audio data than would 435 normally be returned by decoding up through the final packet. This 436 is used to end the stream somewhere other than an even frame 437 boundary. The granule position of the most recent audio data page 438 with completed packets is used to make this determination, or '0' is 439 used if there were no previous audio data pages with a completed 440 packet. The difference between these granule positions indicates how 441 many samples to keep after decoding the packets that completed on the 442 final page. The remaining samples are discarded. The number of 443 discarded samples SHOULD be no larger than the number decoded from 444 the last packet. 446 4.5. Restrictions on the Initial Granule Position 448 The granule position of the first audio data page with a completed 449 packet MAY be larger than the number of samples contained in packets 450 that complete on that page, however it MUST NOT be smaller, unless 451 that page has the 'end of stream' flag set. Allowing a granule 452 position larger than the number of samples allows the beginning of a 453 stream to be cropped or a live stream to be joined without rewriting 454 the granule position of all the remaining pages. This means that the 455 PCM sample position just before the first sample to be played MAY be 456 larger than '0'. Synchronization when multiplexing with other 457 logical streams still uses the PCM sample position relative to '0' to 458 compute sample times. This does not affect the behavior of pre-skip: 459 exactly 'pre-skip' samples SHOULD be skipped from the beginning of 460 the decoded output, even if the initial PCM sample position is 461 greater than zero. 463 On the other hand, a granule position that is smaller than the number 464 of decoded samples prevents a demuxer from working backwards to 465 assign each packet or each individual sample a valid granule 466 position, since granule positions are non-negative. An 467 implementation MUST treat any stream as invalid if the granule 468 position is smaller than the number of samples contained in packets 469 that complete on the first audio data page with a completed packet, 470 unless that page has the 'end of stream' flag set. It MAY defer this 471 action until it decodes the last packet completed on that page. 473 If that page has the 'end of stream' flag set, a demuxer MUST treat 474 any stream as invalid if its granule position is smaller than the 475 'pre-skip' amount. This would indicate that there are more samples 476 to be skipped from the initial decoded output than exist in the 477 stream. If the granule position is smaller than the number of 478 decoded samples produced by the packets that complete on that page, 479 then a demuxer MUST use an initial granule position of '0', and can 480 work forwards from '0' to timestamp individual packets. If the 481 granule position is larger than the number of decoded samples 482 available, then the demuxer MUST still work backwards as described 483 above, even if the 'end of stream' flag is set, to determine the 484 initial granule position, and thus the initial PCM sample position. 485 Both of these will be greater than '0' in this case. 487 4.6. Seeking and Pre-roll 489 Seeking in Ogg files is best performed using a bisection search for a 490 page whose granule position corresponds to a PCM position at or 491 before the seek target. With appropriately weighted bisection, 492 accurate seeking can be performed in just one or two bisections on 493 average, even in multi-gigabyte files. See [seeking] for an example 494 of general implementation guidance. 496 When seeking within an Ogg Opus stream, an implementation SHOULD 497 start decoding (and discarding the output) at least 3840 samples 498 (80 ms) prior to the seek target in order to ensure that the output 499 audio is correct by the time it reaches the seek target. This 'pre- 500 roll' is separate from, and unrelated to, the 'pre-skip' used at the 501 beginning of the stream. If the point 80 ms prior to the seek target 502 comes before the initial PCM sample position, an implementation 503 SHOULD start decoding from the beginning of the stream, applying pre- 504 skip as normal, regardless of whether the pre-skip is larger or 505 smaller than 80 ms, and then continue to discard samples to reach the 506 seek target (if any). 508 5. Header Packets 510 An Ogg Opus logical stream contains exactly two mandatory header 511 packets: an identification header and a comment header. 513 5.1. Identification Header 515 0 1 2 3 516 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 517 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 518 | 'O' | 'p' | 'u' | 's' | 519 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 520 | 'H' | 'e' | 'a' | 'd' | 521 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 522 | Version = 1 | Channel Count | Pre-skip | 523 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 524 | Input Sample Rate (Hz) | 525 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 526 | Output Gain (Q7.8 in dB) | Mapping Family| | 527 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ : 528 | | 529 : Optional Channel Mapping Table... : 530 | | 531 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 533 Figure 2: ID Header Packet 535 The fields in the identification (ID) header have the following 536 meaning: 538 1. Magic Signature: 540 This is an 8-octet (64-bit) field that allows codec 541 identification and is human-readable. It contains, in order, the 542 magic numbers: 544 0x4F 'O' 546 0x70 'p' 548 0x75 'u' 550 0x73 's' 552 0x48 'H' 554 0x65 'e' 556 0x61 'a' 558 0x64 'd' 560 Starting with "Op" helps distinguish it from audio data packets, 561 as this is an invalid TOC sequence. 563 2. Version (8 bits, unsigned): 565 The version number MUST always be '1' for this version of the 566 encapsulation specification. Implementations SHOULD treat 567 streams where the upper four bits of the version number match 568 that of a recognized specification as backwards-compatible with 569 that specification. That is, the version number can be split 570 into "major" and "minor" version sub-fields, with changes to the 571 "minor" sub-field (in the lower four bits) signaling compatible 572 changes. For example, an implementation of this specification 573 SHOULD accept any stream with a version number of '15' or less, 574 and SHOULD assume any stream with a version number '16' or 575 greater is incompatible. The initial version '1' was chosen to 576 keep implementations from relying on this octet as a null 577 terminator for the "OpusHead" string. 579 3. Output Channel Count 'C' (8 bits, unsigned): 581 This is the number of output channels. This might be different 582 than the number of encoded channels, which can change on a 583 packet-by-packet basis. This value MUST NOT be zero. The 584 maximum allowable value depends on the channel mapping family, 585 and might be as large as 255. See Section 5.1.1 for details. 587 4. Pre-skip (16 bits, unsigned, little endian): 589 This is the number of samples (at 48 kHz) to discard from the 590 decoder output when starting playback, and also the number to 591 subtract from a page's granule position to calculate its PCM 592 sample position. When cropping the beginning of existing Ogg 593 Opus streams, a pre-skip of at least 3,840 samples (80 ms) is 594 RECOMMENDED to ensure complete convergence in the decoder. 596 5. Input Sample Rate (32 bits, unsigned, little endian): 598 This is the sample rate of the original input (before encoding), 599 in Hz. This field is _not_ the sample rate to use for playback 600 of the encoded data. 602 Opus can switch between internal audio bandwidths of 4, 6, 8, 12, 603 and 20 kHz. Each packet in the stream can have a different audio 604 bandwidth. Regardless of the audio bandwidth, the reference 605 decoder supports decoding any stream at a sample rate of 8, 12, 606 16, 24, or 48 kHz. The original sample rate of the audio passed 607 to the encoder is not preserved by the lossy compression. 609 An Ogg Opus player SHOULD select the playback sample rate 610 according to the following procedure: 612 1. If the hardware supports 48 kHz playback, decode at 48 kHz. 614 2. Otherwise, if the hardware's highest available sample rate is 615 a supported rate, decode at this sample rate. 617 3. Otherwise, if the hardware's highest available sample rate is 618 less than 48 kHz, decode at the next higher Opus supported 619 rate above the highest available hardware rate and resample. 621 4. Otherwise, decode at 48 kHz and resample. 623 However, the 'Input Sample Rate' field allows the muxer to pass 624 the sample rate of the original input stream as metadata. This 625 is useful when the user requires the output sample rate to match 626 the input sample rate. For example, when not playing the output, 627 an implementation writing PCM format samples to disk might choose 628 to resample the audio back to the original input sample rate to 629 reduce surprise to the user, who might reasonably expect to get 630 back a file with the same sample rate. 632 A value of zero indicates 'unspecified'. Muxers SHOULD write the 633 actual input sample rate or zero, but implementations which do 634 something with this field SHOULD take care to behave sanely if 635 given crazy values (e.g., do not actually upsample the output to 636 10 MHz if requested). Implementations SHOULD support input 637 sample rates between 8 kHz and 192 kHz (inclusive). Rates 638 outside this range MAY be ignored by falling back to the default 639 rate of 48 kHz instead. 641 6. Output Gain (16 bits, signed, little endian): 643 This is a gain to be applied when decoding. It is 20*log10 of 644 the factor by which to scale the decoder output to achieve the 645 desired playback volume, stored in a 16-bit, signed, two's 646 complement fixed-point value with 8 fractional bits (i.e., 647 Q7.8 [q-notation]). 649 To apply the gain, an implementation could use 651 sample *= pow(10, output_gain/(20.0*256)) , 653 where output_gain is the raw 16-bit value from the header. 655 Players and media frameworks SHOULD apply it by default. If a 656 player chooses to apply any volume adjustment or gain 657 modification, such as the R128_TRACK_GAIN (see Section 5.2), the 658 adjustment MUST be applied in addition to this output gain in 659 order to achieve playback at the normalized volume. 661 A muxer SHOULD set this field to zero, and instead apply any gain 662 prior to encoding, when this is possible and does not conflict 663 with the user's wishes. A nonzero output gain indicates the gain 664 was adjusted after encoding, or that a user wished to adjust the 665 gain for playback while preserving the ability to recover the 666 original signal amplitude. 668 Although the output gain has enormous range (+/- 128 dB, enough 669 to amplify inaudible sounds to the threshold of physical pain), 670 most applications can only reasonably use a small portion of this 671 range around zero. The large range serves in part to ensure that 672 gain can always be losslessly transferred between OpusHead and 673 R128 gain tags (see below) without saturating. 675 7. Channel Mapping Family (8 bits, unsigned): 677 This octet indicates the order and semantic meaning of the output 678 channels. 680 Each currently specified value of this octet indicates a mapping 681 family, which defines a set of allowed channel counts, and the 682 ordered set of channel names for each allowed channel count. The 683 details are described in Section 5.1.1. 685 8. Channel Mapping Table: This table defines the mapping from 686 encoded streams to output channels. Its contents are specified 687 in Section 5.1.1. 689 All fields in the ID headers are REQUIRED, except for the channel 690 mapping table, which MUST be omitted when the channel mapping family 691 is 0, but is REQUIRED otherwise. Implementations SHOULD treat a 692 stream as invalid if it contains an ID header that does not have 693 enough data for these fields, even if it contain a valid Magic 694 Signature. Future versions of this specification, even backwards- 695 compatible versions, might include additional fields in the ID 696 header. If an ID header has a compatible major version, but a larger 697 minor version, an implementation MUST NOT treat it as invalid for 698 containing additional data not specified here, provided it still 699 completes on the first page. 701 5.1.1. Channel Mapping 703 An Ogg Opus stream allows mapping one number of Opus streams (N) to a 704 possibly larger number of decoded channels (M + N) to yet another 705 number of output channels (C), which might be larger or smaller than 706 the number of decoded channels. The order and meaning of these 707 channels are defined by a channel mapping, which consists of the 708 'channel mapping family' octet and, for channel mapping families 709 other than family 0, a channel mapping table, as illustrated in 710 Figure 3. 712 0 1 2 3 713 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 714 +-+-+-+-+-+-+-+-+ 715 | Stream Count | 716 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 717 | Coupled Count | Channel Mapping... : 718 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 720 Figure 3: Channel Mapping Table 722 The fields in the channel mapping table have the following meaning: 724 1. Stream Count 'N' (8 bits, unsigned): 726 This is the total number of streams encoded in each Ogg packet. 727 This value is necessary to correctly parse the packed Opus 728 packets inside an Ogg packet, as described in Section 3. This 729 value MUST NOT be zero, as without at least one Opus packet with 730 a valid TOC sequence, a demuxer cannot recover the duration of an 731 Ogg packet. 733 For channel mapping family 0, this value defaults to 1, and is 734 not coded. 736 2. Coupled Stream Count 'M' (8 bits, unsigned): This is the number 737 of streams whose decoders are to be configured to produce two 738 channels (stereo). This MUST be no larger than the total number 739 of streams, N. 741 Each packet in an Opus stream has an internal channel count of 1 742 or 2, which can change from packet to packet. This is selected 743 by the encoder depending on the bitrate and the audio being 744 encoded. The original channel count of the audio passed to the 745 encoder is not necessarily preserved by the lossy compression. 747 Regardless of the internal channel count, any Opus stream can be 748 decoded as mono (a single channel) or stereo (two channels) by 749 appropriate initialization of the decoder. The 'coupled stream 750 count' field indicates that the decoders for the first M Opus 751 streams are to be initialized for stereo (two-channel) output, 752 and the remaining (N - M) decoders are to be initialized for mono 753 (a single channel) only. The total number of decoded channels, 754 (M + N), MUST be no larger than 255, as there is no way to index 755 more channels than that in the channel mapping. 757 For channel mapping family 0, this value defaults to (C - 1) 758 (i.e., 0 for mono and 1 for stereo), and is not coded. 760 3. Channel Mapping (8*C bits): This contains one octet per output 761 channel, indicating which decoded channel is to be used for each 762 one. Let 'index' be the value of this octet for a particular 763 output channel. This value MUST either be smaller than (M + N), 764 or be the special value 255. If 'index' is less than 2*M, the 765 output MUST be taken from decoding stream ('index'/2) as stereo 766 and selecting the left channel if 'index' is even, and the right 767 channel if 'index' is odd. If 'index' is 2*M or larger, but less 768 than 255, the output MUST be taken from decoding stream 769 ('index' - M) as mono. If 'index' is 255, the corresponding 770 output channel MUST contain pure silence. 772 The number of output channels, C, is not constrained to match the 773 number of decoded channels (M + N). A single index value MAY 774 appear multiple times, i.e., the same decoded channel might be 775 mapped to multiple output channels. Some decoded channels might 776 not be assigned to any output channel, as well. 778 For channel mapping family 0, the first index defaults to 0, and 779 if C == 2, the second index defaults to 1. Neither index is 780 coded. 782 After producing the output channels, the channel mapping family 783 determines the semantic meaning of each one. There are three defined 784 mapping families in this specification. 786 5.1.1.1. Channel Mapping Family 0 788 Allowed numbers of channels: 1 or 2. RTP mapping. This is the same 789 channel interpretation as [RFC7587]. 791 o 1 channel: monophonic (mono). 793 o 2 channels: stereo (left, right). 795 Special mapping: This channel mapping value also indicates that the 796 contents consists of a single Opus stream that is stereo if and only 797 if C == 2, with stream index 0 mapped to output channel 0 (mono, or 798 left channel) and stream index 1 mapped to output channel 1 (right 799 channel) if stereo. When the 'channel mapping family' octet has this 800 value, the channel mapping table MUST be omitted from the ID header 801 packet. 803 5.1.1.2. Channel Mapping Family 1 805 Allowed numbers of channels: 1...8. Vorbis channel order (see 806 below). 808 Each channel is assigned to a speaker location in a conventional 809 surround arrangement. Specific locations depend on the number of 810 channels, and are given below in order of the corresponding channel 811 indices. 813 o 1 channel: monophonic (mono). 815 o 2 channels: stereo (left, right). 817 o 3 channels: linear surround (left, center, right) 819 o 4 channels: quadraphonic (front left, front right, rear left, 820 rear right). 822 o 5 channels: 5.0 surround (front left, front center, front right, 823 rear left, rear right). 825 o 6 channels: 5.1 surround (front left, front center, front right, 826 rear left, rear right, LFE). 828 o 7 channels: 6.1 surround (front left, front center, front right, 829 side left, side right, rear center, LFE). 831 o 8 channels: 7.1 surround (front left, front center, front right, 832 side left, side right, rear left, rear right, LFE) 834 This set of surround options and speaker location orderings is the 835 same as those used by the Vorbis codec [vorbis-mapping]. The 836 ordering is different from the one used by the WAVE 837 [wave-multichannel] and Free Lossless Audio Codec (FLAC) [flac] 838 formats, so correct ordering requires permutation of the output 839 channels when decoding to or encoding from those formats. 'LFE' here 840 refers to a Low Frequency Effects channel, often mapped to a 841 subwoofer with no particular spatial position. Implementations 842 SHOULD identify 'side' or 'rear' speaker locations with 'surround' 843 and 'back' as appropriate when interfacing with audio formats or 844 systems which prefer that terminology. 846 5.1.1.3. Channel Mapping Family 255 848 Allowed numbers of channels: 1...255. No defined channel meaning. 850 Channels are unidentified. General-purpose players SHOULD NOT 851 attempt to play these streams. Offline implementations MAY 852 deinterleave the output into separate PCM files, one per channel. 853 Implementations SHOULD NOT produce output for channels mapped to 854 stream index 255 (pure silence) unless they have no other way to 855 indicate the index of non-silent channels. 857 5.1.1.4. Undefined Channel Mappings 859 The remaining channel mapping families (2...254) are reserved. A 860 demuxer implementation encountering a reserved channel mapping family 861 value SHOULD act as though the value is 255. 863 5.1.1.5. Downmixing 865 An Ogg Opus player MUST support any valid channel mapping with a 866 channel mapping family of 0 or 1, even if the number of channels does 867 not match the physically connected audio hardware. Players SHOULD 868 perform channel mixing to increase or reduce the number of channels 869 as needed. 871 Implementations MAY use the matrices in Figures 4 through 9 to 872 implement downmixing from multichannel files using Channel Mapping 873 Family 1 (Section 5.1.1.2), which are known to give acceptable 874 results for stereo. Matrices for 3 and 4 channels are normalized so 875 each coefficient row sums to 1 to avoid clipping. For 5 or more 876 channels they are normalized to 2 as a compromise between clipping 877 and dynamic range reduction. 879 In these matrices the front left and front right channels are 880 generally passed through directly. When a surround channel is split 881 between both the left and right stereo channels, coefficients are 882 chosen so their squares sum to 1, which helps preserve the perceived 883 intensity. Rear channels are mixed more diffusely or attenuated to 884 maintain focus on the front channels. 886 L output = ( 0.585786 * left + 0.414214 * center ) 887 R output = ( 0.414214 * center + 0.585786 * right ) 889 Exact coefficient values are 1 and 1/sqrt(2), multiplied by 1/(1 + 1/ 890 sqrt(2)) for normalization. 892 Figure 4: Stereo downmix matrix for the linear surround channel 893 mapping 895 / \ / \ / FL \ 896 | L output | | 0.422650 0.000000 0.366025 0.211325 | | FR | 897 | R output | = | 0.000000 0.422650 0.211325 0.366025 | | RL | 898 \ / \ / \ RR / 900 Exact coefficient values are 1, sqrt(3)/2 and 1/2, multiplied by 901 1/(1 + sqrt(3)/2 + 1/2) for normalization. 903 Figure 5: Stereo downmix matrix for the quadraphonic channel mapping 905 / FL \ 906 / \ / \ | FC | 907 | L | | 0.650802 0.460186 0.000000 0.563611 0.325401 | | FR | 908 | R | = | 0.000000 0.460186 0.650802 0.325401 0.563611 | | RL | 909 \ / \ / | RR | 910 \ / 912 Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, 913 multiplied by 2/(1 + 1/sqrt(2) + sqrt(3)/2 + 1/2) for normalization. 915 Figure 6: Stereo downmix matrix for the 5.0 surround mapping 916 /FL \ 917 / \ / \ |FC | 918 |L| | 0.529067 0.374107 0.000000 0.458186 0.264534 0.374107 | |FR | 919 |R| = | 0.000000 0.374107 0.529067 0.264534 0.458186 0.374107 | |RL | 920 \ / \ / |RR | 921 \LFE/ 923 Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, 924 multiplied by 2/(1 + 1/sqrt(2) + sqrt(3)/2 + 1/2 + 1/sqrt(2)) for 925 normalization. 927 Figure 7: Stereo downmix matrix for the 5.1 surround mapping 929 / \ 930 | 0.455310 0.321953 0.000000 0.394310 0.227655 0.278819 0.321953 | 931 | 0.000000 0.321953 0.455310 0.227655 0.394310 0.278819 0.321953 | 932 \ / 934 Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2, 1/2 and 935 sqrt(3)/2/sqrt(2), multiplied by 2/(1 + 1/sqrt(2) + sqrt(3)/2 + 1/2 + 936 sqrt(3)/2/sqrt(2) + 1/sqrt(2)) for normalization. The coefficients 937 are in the same order as in Section 5.1.1.2, and the matrices above. 939 Figure 8: Stereo downmix matrix for the 6.1 surround mapping 941 / \ 942 | .388631 .274804 .000000 .336565 .194316 .336565 .194316 .274804 | 943 | .000000 .274804 .388631 .194316 .336565 .194316 .336565 .274804 | 944 \ / 946 Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, 947 multiplied by 2/(2 + 2/sqrt(2) + sqrt(3)) for normalization. The 948 coefficients are in the same order as in Section 5.1.1.2, and the 949 matrices above. 951 Figure 9: Stereo downmix matrix for the 7.1 surround mapping 953 5.2. Comment Header 954 0 1 2 3 955 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 956 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 957 | 'O' | 'p' | 'u' | 's' | 958 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 959 | 'T' | 'a' | 'g' | 's' | 960 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 961 | Vendor String Length | 962 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 963 | | 964 : Vendor String... : 965 | | 966 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 967 | User Comment List Length | 968 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 969 | User Comment #0 String Length | 970 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 971 | | 972 : User Comment #0 String... : 973 | | 974 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 975 | User Comment #1 String Length | 976 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 977 : : 979 Figure 10: Comment Header Packet 981 The comment header consists of a 64-bit magic signature, followed by 982 data in the same format as the [vorbis-comment] header used in Ogg 983 Vorbis, except (like Ogg Theora and Speex) the final "framing bit" 984 specified in the Vorbis spec is not present. 986 1. Magic Signature: 988 This is an 8-octet (64-bit) field that allows codec 989 identification and is human-readable. It contains, in order, the 990 magic numbers: 992 0x4F 'O' 994 0x70 'p' 996 0x75 'u' 998 0x73 's' 1000 0x54 'T' 1001 0x61 'a' 1003 0x67 'g' 1005 0x73 's' 1007 Starting with "Op" helps distinguish it from audio data packets, 1008 as this is an invalid TOC sequence. 1010 2. Vendor String Length (32 bits, unsigned, little endian): 1012 This field gives the length of the following vendor string, in 1013 octets. It MUST NOT indicate that the vendor string is longer 1014 than the rest of the packet. 1016 3. Vendor String (variable length, UTF-8 vector): 1018 This is a simple human-readable tag for vendor information, 1019 encoded as a UTF-8 string [RFC3629]. No terminating null octet 1020 is necessary. 1022 This tag is intended to identify the codec encoder and 1023 encapsulation implementations, for tracing differences in 1024 technical behavior. User-facing applications can use the 1025 'ENCODER' user comment tag to identify themselves. 1027 4. User Comment List Length (32 bits, unsigned, little endian): 1029 This field indicates the number of user-supplied comments. It 1030 MAY indicate there are zero user-supplied comments, in which case 1031 there are no additional fields in the packet. It MUST NOT 1032 indicate that there are so many comments that the comment string 1033 lengths would require more data than is available in the rest of 1034 the packet. 1036 5. User Comment #i String Length (32 bits, unsigned, little endian): 1038 This field gives the length of the following user comment string, 1039 in octets. There is one for each user comment indicated by the 1040 'user comment list length' field. It MUST NOT indicate that the 1041 string is longer than the rest of the packet. 1043 6. User Comment #i String (variable length, UTF-8 vector): 1045 This field contains a single user comment encoded as a UTF-8 1046 string [RFC3629]. There is one for each user comment indicated 1047 by the 'user comment list length' field. 1049 The vendor string length and user comment list length are REQUIRED, 1050 and implementations SHOULD treat a stream as invalid if it contains a 1051 comment header that does not have enough data for these fields, or 1052 that does not contain enough data for the corresponding vendor string 1053 or user comments they describe. Making this check before allocating 1054 the associated memory to contain the data helps prevent a possible 1055 Denial-of-Service (DoS) attack from small comment headers that claim 1056 to contain strings longer than the entire packet or more user 1057 comments than than could possibly fit in the packet. 1059 Immediately following the user comment list, the comment header MAY 1060 contain zero-padding or other binary data which is not specified 1061 here. If the least-significant bit of the first byte of this data is 1062 1, then editors SHOULD preserve the contents of this data when 1063 updating the tags, but if this bit is 0, all such data MAY be treated 1064 as padding, and truncated or discarded as desired. This allows 1065 informal experimentation with the format of this binary data until it 1066 can be specified later. 1068 The comment header can be arbitrarily large and might be spread over 1069 a large number of Ogg pages. Implementations MUST avoid attempting 1070 to allocate excessive amounts of memory when presented with a very 1071 large comment header. To accomplish this, implementations MAY treat 1072 a stream as invalid if it has a comment header larger than 1073 125,829,120 octets (120 MB), and MAY ignore individual comments that 1074 are not fully contained within the first 61,440 octets of the comment 1075 header. 1077 5.2.1. Tag Definitions 1079 The user comment strings follow the NAME=value format described by 1080 [vorbis-comment] with the same recommended tag names: ARTIST, TITLE, 1081 DATE, ALBUM, and so on. 1083 Two new comment tags are introduced here: 1085 First, an optional gain for track normalization: 1087 R128_TRACK_GAIN=-573 1089 representing the volume shift needed to normalize the track's volume 1090 during isolated playback, in random shuffle, and so on. The gain is 1091 a Q7.8 fixed point number in dB, as in the ID header's 'output gain' 1092 field. This tag is similar to the REPLAYGAIN_TRACK_GAIN tag in 1093 Vorbis [replay-gain], except that the normal volume reference is the 1094 [EBU-R128] standard. 1096 Second, an optional gain for album normalization: 1098 R128_ALBUM_GAIN=111 1100 representing the volume shift needed to normalize the overall volume 1101 when played as part of a particular collection of tracks. The gain 1102 is also a Q7.8 fixed point number in dB, as in the ID header's 1103 'output gain' field. The values '-573' and '111' given here are just 1104 examples. 1106 An Ogg Opus stream MUST NOT have more than one of each of these tags, 1107 and if present their values MUST be an integer from -32768 to 32767, 1108 inclusive, represented in ASCII as a base 10 number with no 1109 whitespace. A leading '+' or '-' character is valid. Leading zeros 1110 are also permitted, but the value MUST be represented by no more than 1111 6 characters. Other non-digit characters MUST NOT be present. 1113 If present, R128_TRACK_GAIN and R128_ALBUM_GAIN MUST correctly 1114 represent the R128 normalization gain relative to the 'output gain' 1115 field specified in the ID header. If a player chooses to make use of 1116 the R128_TRACK_GAIN tag or the R128_ALBUM_GAIN tag, it MUST apply 1117 those gains _in addition_ to the 'output gain' value. If a tool 1118 modifies the ID header's 'output gain' field, it MUST also update or 1119 remove the R128_TRACK_GAIN and R128_ALBUM_GAIN comment tags if 1120 present. A muxer SHOULD place the gain it wants other tools to use 1121 by default into the 'output gain' field, and not the comment tag. 1123 To avoid confusion with multiple normalization schemes, an Opus 1124 comment header SHOULD NOT contain any of the REPLAYGAIN_TRACK_GAIN, 1125 REPLAYGAIN_TRACK_PEAK, REPLAYGAIN_ALBUM_GAIN, or 1126 REPLAYGAIN_ALBUM_PEAK tags, unless they are only to be used in some 1127 context where there is guaranteed to be no such confusion. 1128 [EBU-R128] normalization is preferred to the earlier REPLAYGAIN 1129 schemes because of its clear definition and adoption by industry. 1130 Peak normalizations are difficult to calculate reliably for lossy 1131 codecs because of variation in excursion heights due to decoder 1132 differences. In the authors' investigations they were not applied 1133 consistently or broadly enough to merit inclusion here. 1135 6. Packet Size Limits 1137 Technically, valid Opus packets can be arbitrarily large due to the 1138 padding format, although the amount of non-padding data they can 1139 contain is bounded. These packets might be spread over a similarly 1140 enormous number of Ogg pages. When encoding, implementations SHOULD 1141 limit the use of padding in audio data packets to no more than is 1142 necessary to make a variable bitrate (VBR) stream constant bitrate 1143 (CBR), unless they have no reasonable way to determine what is 1144 necessary. Demuxers SHOULD treat audio data packets as invalid 1145 (treat them as if they were malformed Opus packets with an invalid 1146 TOC sequence) if they are larger than 61,440 octets per Opus stream, 1147 unless they have a specific reason for allowing extra padding. Such 1148 packets necessarily contain more padding than needed to make a stream 1149 CBR. Demuxers MUST avoid attempting to allocate excessive amounts of 1150 memory when presented with a very large packet. Demuxers MAY treat 1151 audio data packets as invalid or partially process them if they are 1152 larger than 61,440 octets in an Ogg Opus stream with channel mapping 1153 families 0 or 1. Demuxers MAY treat audio data packets as invalid or 1154 partially process them in any Ogg Opus stream if the packet is larger 1155 than 61,440 octets and also larger than 7,680 octets per Opus stream. 1156 The presence of an extremely large packet in the stream could 1157 indicate a memory exhaustion attack or stream corruption. 1159 In an Ogg Opus stream, the largest possible valid packet that does 1160 not use padding has a size of (61,298*N - 2) octets. With 1161 255 streams, this is 15,630,988 octets and can span up to 61,298 Ogg 1162 pages, all but one of which will have a granule position of -1. This 1163 is of course a very extreme packet, consisting of 255 streams, each 1164 containing 120 ms of audio encoded as 2.5 ms frames, each frame using 1165 the maximum possible number of octets (1275) and stored in the least 1166 efficient manner allowed (a VBR code 3 Opus packet). Even in such a 1167 packet, most of the data will be zeros as 2.5 ms frames cannot 1168 actually use all 1275 octets. 1170 The largest packet consisting of entirely useful data is 1171 (15,326*N - 2) octets. This corresponds to 120 ms of audio encoded 1172 as 10 ms frames in either SILK or Hybrid mode, but at a data rate of 1173 over 1 Mbps, which makes little sense for the quality achieved. 1175 A more reasonable limit is (7,664*N - 2) octets. This corresponds to 1176 120 ms of audio encoded as 20 ms stereo CELT mode frames, with a 1177 total bitrate just under 511 kbps (not counting the Ogg encapsulation 1178 overhead). For channel mapping family 1, N=8 provides a reasonable 1179 upper bound, as it allows for each of the 8 possible output channels 1180 to be decoded from a separate stereo Opus stream. This gives a size 1181 of 61,310 octets, which is rounded up to a multiple of 1,024 octets 1182 to yield the audio data packet size of 61,440 octets that any 1183 implementation is expected to be able to process successfully. 1185 7. Encoder Guidelines 1187 When encoding Opus streams, Ogg muxers SHOULD take into account the 1188 algorithmic delay of the Opus encoder. 1190 In encoders derived from the reference implementation [RFC6716], the 1191 number of samples can be queried with: 1193 opus_encoder_ctl(encoder_state, OPUS_GET_LOOKAHEAD(&delay_samples)); 1195 To achieve good quality in the very first samples of a stream, 1196 implementations MAY use linear predictive coding (LPC) extrapolation 1197 to generate at least 120 extra samples at the beginning to avoid the 1198 Opus encoder having to encode a discontinuous signal. For more 1199 information on linear prediction, see [linear-prediction]. For an 1200 input file containing 'length' samples, the implementation SHOULD set 1201 the pre-skip header value to (delay_samples + extra_samples), encode 1202 at least (length + delay_samples + extra_samples) samples, and set 1203 the granule position of the last page to 1204 (length + delay_samples + extra_samples). This ensures that the 1205 encoded file has the same duration as the original, with no time 1206 offset. The best way to pad the end of the stream is to also use LPC 1207 extrapolation, but zero-padding is also acceptable. 1209 7.1. LPC Extrapolation 1211 The first step in LPC extrapolation is to compute linear prediction 1212 coefficients. [lpc-sample] When extending the end of the signal, 1213 order-N (typically with N ranging from 8 to 40) LPC analysis is 1214 performed on a window near the end of the signal. The last N samples 1215 are used as memory to an infinite impulse response (IIR) filter. 1217 The filter is then applied on a zero input to extrapolate the end of 1218 the signal. Let a(k) be the kth LPC coefficient and x(n) be the nth 1219 sample of the signal, each new sample past the end of the signal is 1220 computed as: 1222 N 1223 --- 1224 x(n) = \ a(k)*x(n-k) 1225 / 1226 --- 1227 k=1 1229 The process is repeated independently for each channel. It is 1230 possible to extend the beginning of the signal by applying the same 1231 process backward in time. When extending the beginning of the 1232 signal, it is best to apply a "fade in" to the extrapolated signal, 1233 e.g. by multiplying it by a half-Hanning window [hanning]. 1235 7.2. Continuous Chaining 1237 In some applications, such as Internet radio, it is desirable to cut 1238 a long stream into smaller chains, e.g. so the comment header can be 1239 updated. This can be done simply by separating the input streams 1240 into segments and encoding each segment independently. The drawback 1241 of this approach is that it creates a small discontinuity at the 1242 boundary due to the lossy nature of Opus. A muxer MAY avoid this 1243 discontinuity by using the following procedure: 1245 1. Encode the last frame of the first segment as an independent 1246 frame by turning off all forms of inter-frame prediction. De- 1247 emphasis is allowed. 1249 2. Set the granule position of the last page to a point near the end 1250 of the last frame. 1252 3. Begin the second segment with a copy of the last frame of the 1253 first segment. 1255 4. Set the pre-skip value of the second stream in such a way as to 1256 properly join the two streams. 1258 5. Continue the encoding process normally from there, without any 1259 reset to the encoder. 1261 In encoders derived from the reference implementation, inter-frame 1262 prediction can be turned off by calling: 1264 opus_encoder_ctl(encoder_state, OPUS_SET_PREDICTION_DISABLED(1)); 1266 For best results, this implementation requires that prediction be 1267 explicitly enabled again before resuming normal encoding, even after 1268 a reset. 1270 8. Implementation Status 1272 A brief summary of major implementations of this draft is available 1273 at [1], along with their status. 1275 [Note to RFC Editor: please remove this entire section before final 1276 publication per [RFC6982], along with its references.] 1278 9. Security Considerations 1280 Implementations of the Opus codec need to take appropriate security 1281 considerations into account, as outlined in [RFC4732]. This is just 1282 as much a problem for the container as it is for the codec itself. 1283 Malicious payloads and/or input streams can be used to attack codec 1284 implementations. Implementations MUST NOT overrun their allocated 1285 memory nor consume excessive resources when decoding payloads or 1286 processing input streams. Although problems in encoding applications 1287 are typically rarer, this still applies to a muxer, as 1288 vulnerabilities would allow an attacker to attack transcoding 1289 gateways. 1291 Header parsing code contains the most likely area for potential 1292 overruns. It is important for implementations to ensure their 1293 buffers contain enough data for all of the required fields before 1294 attempting to read it (for example, for all of the channel map data 1295 in the ID header). Implementations would do well to validate the 1296 indices of the channel map, also, to ensure they meet all of the 1297 restrictions outlined in Section 5.1.1, in order to avoid attempting 1298 to read data from channels that do not exist. 1300 To avoid excessive resource usage, we advise implementations to be 1301 especially wary of streams that might cause them to process far more 1302 data than was actually transmitted. For example, a relatively small 1303 comment header may contain values for the string lengths or user 1304 comment list length that imply that it is many gigabytes in size. 1305 Even computing the size of the required buffer could overflow a 1306 32-bit integer, and actually attempting to allocate such a buffer 1307 before verifying it would be a reasonable size is a bad idea. After 1308 reading the user comment list length, implementations might wish to 1309 verify that the header contains at least the minimum amount of data 1310 for that many comments (4 additional octets per comment, to indicate 1311 each has a length of zero) before proceeding any further, again 1312 taking care to avoid overflow in these calculations. If allocating 1313 an array of pointers to point at these strings, the size of the 1314 pointers may be larger than 4 octets, potentially requiring a 1315 separate overflow check. 1317 Another bug in this class we have observed more than once involves 1318 the handling of invalid data at the end of a stream. Often, 1319 implementations will seek to the end of a stream to locate the last 1320 timestamp in order to compute its total duration. If they do not 1321 find a valid capture pattern and Ogg page from the desired logical 1322 stream, they will back up and try again. If care is not taken to 1323 avoid re-scanning data that was already scanned, this search can 1324 quickly devolve into something with a complexity that is quadratic in 1325 the amount of invalid data. 1327 In general when seeking, implementations will wish to be cautious 1328 about the effects of invalid granule position values, and ensure all 1329 algorithms will continue to make progress and eventually terminate, 1330 even if these are missing or out-of-order. 1332 Like most other container formats, Ogg Opus streams SHOULD NOT be 1333 used with insecure ciphers or cipher modes that are vulnerable to 1334 known-plaintext attacks. Elements such as the Ogg page capture 1335 pattern and the magic signatures in the ID header and the comment 1336 header all have easily predictable values, in addition to various 1337 elements of the codec data itself. 1339 10. Content Type 1341 An "Ogg Opus file" consists of one or more sequentially multiplexed 1342 segments, each containing exactly one Ogg Opus stream. The 1343 RECOMMENDED mime-type for Ogg Opus files is "audio/ogg". 1345 If more specificity is desired, one MAY indicate the presence of Opus 1346 streams using the codecs parameter defined in [RFC6381] and 1347 [RFC5334], e.g., 1349 audio/ogg; codecs=opus 1351 for an Ogg Opus file. 1353 The RECOMMENDED filename extension for Ogg Opus files is '.opus'. 1355 When Opus is concurrently multiplexed with other streams in an Ogg 1356 container, one SHOULD use one of the "audio/ogg", "video/ogg", or 1357 "application/ogg" mime-types, as defined in [RFC5334]. Such streams 1358 are not strictly "Ogg Opus files" as described above, since they 1359 contain more than a single Opus stream per sequentially multiplexed 1360 segment, e.g. video or multiple audio tracks. In such cases the the 1361 '.opus' filename extension is NOT RECOMMENDED. 1363 In either case, this document updates [RFC5334] to add 'opus' as a 1364 codecs parameter value with char[8]: 'OpusHead' as Codec Identifier. 1366 11. IANA Considerations 1368 This document updates the IANA Media Types registry to add .opus as a 1369 file extension for "audio/ogg", and to add itself as a reference 1370 alongside [RFC5334] for "audio/ogg", "video/ogg", and "application/ 1371 ogg" Media Types. 1373 This document defines a new registry "Opus Channel Mapping Families" 1374 to indicate how the semantic meanings of the channels in a multi- 1375 channel Opus stream are described. IANA is requested to create a new 1376 name space of "Opus Channel Mapping Families". This will be a new 1377 registry on the IANA Matrix, and not a subregistry of an existing 1378 registry. Modifications to this registry follow the "Specification 1379 Required" registration policy as defined in [RFC5226]. Each registry 1380 entry consists of a Channel Mapping Family Number, which is specified 1381 in decimal in the range 0 to 255, inclusive, and a Reference (or list 1382 of references) Each Reference must point to sufficient documentation 1383 to describe what information is coded in the Opus identification 1384 header for this channel mapping family, how a demuxer determines the 1385 Stream Count ('N') and Coupled Stream Count ('M') from this 1386 information, and how it determines the proper interpretation of each 1387 of the decoded channels. 1389 This document defines three initial assignments for this registry. 1391 +-------+---------------------------+ 1392 | Value | Reference | 1393 +-------+---------------------------+ 1394 | 0 | [RFCXXXX] Section 5.1.1.1 | 1395 | | | 1396 | 1 | [RFCXXXX] Section 5.1.1.2 | 1397 | | | 1398 | 255 | [RFCXXXX] Section 5.1.1.3 | 1399 +-------+---------------------------+ 1401 The designated expert will determine if the Reference points to a 1402 specification that meets the requirements for permanence and ready 1403 availability laid out in [RFC5226] and that it specifies the 1404 information described above with sufficient clarity to allow 1405 interoperable implementations. 1407 12. Acknowledgments 1409 Thanks to Ben Campbell, Joel M. Halpern, Mark Harris, Greg Maxwell, 1410 Christopher "Monty" Montgomery, Jean-Marc Valin, Stephan Wenger, and 1411 Mo Zanaty for their valuable contributions to this document. 1412 Additional thanks to Andrew D'Addesio, Greg Maxwell, and Vincent 1413 Penquerc'h for their feedback based on early implementations. 1415 13. RFC Editor Notes 1417 In Section 11, "RFCXXXX" is to be replaced with the RFC number 1418 assigned to this draft. 1420 14. References 1422 14.1. Normative References 1424 [RFC2119] Bradner, S., "Key words for use in RFCs to Indicate 1425 Requirement Levels", BCP 14, RFC 2119, March 1997. 1427 [RFC3533] Pfeiffer, S., "The Ogg Encapsulation Format Version 0", 1428 RFC 3533, May 2003. 1430 [RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO 1431 10646", STD 63, RFC 3629, November 2003. 1433 [RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an 1434 IANA Considerations Section in RFCs", BCP 26, RFC 5226, 1435 DOI 10.17487/RFC5226, May 2008, 1436 . 1438 [RFC5334] Goncalves, I., Pfeiffer, S., and C. Montgomery, "Ogg Media 1439 Types", RFC 5334, September 2008. 1441 [RFC6381] Gellens, R., Singer, D., and P. Frojdh, "The 'Codecs' and 1442 'Profiles' Parameters for "Bucket" Media Types", RFC 6381, 1443 August 2011. 1445 [RFC6716] Valin, JM., Vos, K., and T. Terriberry, "Definition of the 1446 Opus Audio Codec", RFC 6716, September 2012. 1448 [EBU-R128] 1449 EBU Technical Committee, "Loudness Recommendation EBU 1450 R128", August 2011, . 1452 [vorbis-comment] 1453 Montgomery, C., "Ogg Vorbis I Format Specification: 1454 Comment Field and Header Specification", July 2002, 1455 . 1457 14.2. Informative References 1459 [RFC4732] Handley, M., Rescorla, E., and IAB, "Internet Denial-of- 1460 Service Considerations", RFC 4732, December 2006. 1462 [RFC6982] Sheffer, Y. and A. Farrel, "Improving Awareness of Running 1463 Code: The Implementation Status Section", RFC 6982, July 1464 2013. 1466 [RFC7587] Spittka, J., Vos, K., and JM. Valin, "RTP Payload Format 1467 for the Opus Speech and Audio Codec", RFC 7587, DOI 1468 10.17487/RFC7587, June 2015, 1469 . 1471 [flac] Coalson, J., "FLAC - Free Lossless Audio Codec Format 1472 Description", January 2008, . 1475 [hanning] Wikipedia, "Hann window", February 2016, 1476 . 1479 [linear-prediction] 1480 Wikipedia, "Linear Predictive Coding", October 2015, 1481 . 1484 [lpc-sample] 1485 Degener, J. and C. Bormann, "Autocorrelation LPC coeff 1486 generation algorithm (Vorbis source code)", November 1994, 1487 . 1489 [q-notation] 1490 Wikipedia, "Q (number format)", December 2015, 1491 . 1494 [replay-gain] 1495 Parker, C. and M. Leese, "VorbisComment: Replay Gain", 1496 June 2009, . 1499 [seeking] Pfeiffer, S., Parker, C., and G. Maxwell, "Granulepos 1500 Encoding and How Seeking Really Works", May 2012, 1501 . 1503 [vorbis-mapping] 1504 Montgomery, C., "The Vorbis I Specification, Section 4.3.9 1505 Output Channel Order", January 2010, 1506 . 1509 [vorbis-trim] 1510 Montgomery, C., "The Vorbis I Specification, Appendix A: 1511 Embedding Vorbis into an Ogg stream", November 2008, 1512 . 1515 [wave-multichannel] 1516 Microsoft Corporation, "Multiple Channel Audio Data and 1517 WAVE Files", March 2007, . 1520 14.3. URIs 1522 [1] https://wiki.xiph.org/OggOpusImplementation 1524 Authors' Addresses 1526 Timothy B. Terriberry 1527 Mozilla Corporation 1528 650 Castro Street 1529 Mountain View, CA 94041 1530 USA 1532 Phone: +1 650 903-0800 1533 Email: tterribe@xiph.org 1535 Ron Lee 1536 Voicetronix 1537 246 Pulteney Street, Level 1 1538 Adelaide, SA 5000 1539 Australia 1541 Phone: +61 8 8232 9112 1542 Email: ron@debian.org 1544 Ralph Giles 1545 Mozilla Corporation 1546 163 West Hastings Street 1547 Vancouver, BC V6B 1H5 1548 Canada 1550 Phone: +1 778 785 1540 1551 Email: giles@xiph.org