RFC 7845
Ogg Encapsulation for the Opus Audio Codec
RFC 7845 ๐ Ogg Encapsulation for the Opus Audio Codec
Okay bestie, here's the front page ๐ This one is from the Internet Engineering Task Force (IETF), and it's a Standards Track doc (ISSN 2070-1721). It was published in April 2016 and updates RFC 5334. The authors are T. Terriberry (Mozilla Corporation), R. Lee (Voicetronix), and R. Giles (Mozilla Corporation). Iconic team ๐
Abstract ๐
So this doc defines how to wrap the Opus interactive speech and audio codec in Ogg encapsulation ๐ That means Opus-encoded data can get stored inside an Ogg logical bitstream, and honestly that's the whole vibe โจ
Status of This Memo ๐
Bestie, this is an Internet Standards Track document ๐
This doc comes from the IETF, and it totally represents the consensus of the IETF community. It got public review and was approved for publication by the Internet Engineering Steering Group (IESG). If you want more on Internet Standards, check out Section 2 of RFC 5741. For the current status, any errata, and how to send feedback, go to http://www.rfc-editor.org/info/rfc7845 ๐ฆ
Copyright Notice ๐ซถ
Copyright (c) 2016 IETF Trust and the persons identified as the document authors. All rights reserved.
Okay, legal part but make it cute ๐ This doc is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (http://trustee.ietf.org/license-info) as they were in effect on the publication date. Please actually read those, because they spell out your rights and restrictions for this doc. Any Code Components pulled out of this document must include Simplified BSD License text, as described in Section 4.e of the Trust Legal Provisions, and they come without warranty, as the Simplified BSD License describes ๐
Table of Contents ๐
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 2
2. Terminology . . . . . . . . . . . . . . . . . . . . . . . . . 3
3. Packet Organization . . . . . . . . . . . . . . . . . . . . . 4
4. Granule Position . . . . . . . . . . . . . . . . . . . . . . 6
4.1. Repairing Gaps in Real-Time Streams . . . . . . . . . . . 7
4.2. Pre-skip . . . . . . . . . . . . . . . . . . . . . . . . 9
4.3. PCM Sample Position . . . . . . . . . . . . . . . . . . . 9
4.4. End Trimming . . . . . . . . . . . . . . . . . . . . . . 10
4.5. Restrictions on the Initial Granule Position . . . . . . 10
4.6. Seeking and Pre-roll . . . . . . . . . . . . . . . . . . 11
5. Header Packets . . . . . . . . . . . . . . . . . . . . . . . 12
5.1. Identification Header . . . . . . . . . . . . . . . . . . 12
5.1.1. Channel Mapping . . . . . . . . . . . . . . . . . . . 16
5.2. Comment Header . . . . . . . . . . . . . . . . . . . . . 22
5.2.1. Tag Definitions . . . . . . . . . . . . . . . . . . . 25
6. Packet Size Limits . . . . . . . . . . . . . . . . . . . . . 26
7. Encoder Guidelines . . . . . . . . . . . . . . . . . . . . . 27
7.1. LPC Extrapolation . . . . . . . . . . . . . . . . . . . . 28
7.2. Continuous Chaining . . . . . . . . . . . . . . . . . . . 28
8. Security Considerations . . . . . . . . . . . . . . . . . . . 29
9. Content Type . . . . . . . . . . . . . . . . . . . . . . . . 30
10. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 31
11. References . . . . . . . . . . . . . . . . . . . . . . . . . 32
11.1. Normative References . . . . . . . . . . . . . . . . . . 32
11.2. Informative References . . . . . . . . . . . . . . . . . 33
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . 34
Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . 35
1. Introduction โจ
Okay so the IETF Opus codec is a low-latency audio codec, and it's optimized for both voice and general-purpose audio. Literally iconic ๐ง For the technical deep dive, see [RFC6716]. This doc defines how Opus gets encapsulated in a continuous, logical Ogg bitstream [RFC3533].
Ogg encapsulation gives Opus a long-term storage format with all the essential features ๐ That includes metadata, fast and accurate seeking, corruption detection, recapture after errors, low overhead, and the ability to multiplex Opus with other codecs (video included) with minimal buffering. It's also a live streamable format, so it can be delivered over a reliable stream-oriented transport. You don't need all the data (or even the total length of the data) up-front, and it's the same form as the on-disk storage format. Main character energy ๐ฆ
Ogg bitstreams are made of a series of "pages" ๐ Each page holds data from one or more "packets," and pages are the fundamental unit of multiplexing in an Ogg stream. Every page belongs to a particular logical stream and has a capture pattern and checksum. It also has flags that mark the beginning and end of the logical stream, plus a "granule position" that represents an absolute position in the stream to help with seeking ๐ง
Here's the tea ๐ต A single page can hold up to 65,025 octets of packet data from up to 255 different packets. Packets can be split arbitrarily across pages and continued from one page to the next, which is how you get packets way bigger than one page can hold. Each page also has "lacing values" that say how the data is split into packets. That lets a demultiplexer (demuxer) find the packet boundaries without digging into the encoded data ๐ A packet is said to "complete" on a page when that page contains the final lacing value for that packet.
This encapsulation defines the contents of the packet data, including the necessary headers, how those packets are organized into a logical stream, and how to interpret the codec-specific granule position field. It doesn't try to describe or specify the existing Ogg container format itself. If the basic Ogg concepts are new to you, go check the details in [RFC3533] ๐ No judgment, we all start somewhere ๐ซถ
2. Terminology ๐ฅ
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC2119]. Those are the special words that carry weight in this doc, so keep an eye out for them ๐
3. Packet Organization โจ
okay so here's how an Ogg Opus stream is laid out, bestie ๐ Figure 1 is the visual, and it's giving diagram energy ๐ฆ
Page 0 Pages 1 ... n Pages (n+1) ...
+------------+ +---+ +---+ ... +---+ +-----------+ +---------+ +--
| | | | | | | | | | | | |
|+----------+| |+-----------------+| |+-------------------+ +-----
|||ID Header|| || Comment Header || ||Audio Data Packet 1| | ...
|+----------+| |+-----------------+| |+-------------------+ +-----
| | | | | | | | | | | | |
+------------+ +---+ +---+ ... +---+ +-----------+ +---------+ +--
^ ^ ^
| | |
| | Mandatory Page Break
| |
| ID header is contained on a single page
|
'Beginning Of Stream'
Figure 1: Example Packet Organization for a Logical Ogg Opus Stream
okay so there are two mandatory header packets ๐ฅ The very first packet in the logical Ogg bitstream MUST contain the identification (ID) header, which is the thing that uniquely identifies a stream as Opus audio ๐ง The ID header's format is defined in Section 5.1. It sits all alone (no other packet data riding along ๐ ) on the first page, and it completes on that page. That page gets its 'beginning of stream' flag set โจ
The second packet in the logical Ogg bitstream MUST contain the comment header, which holds the user-supplied metadata ๐ Its format is defined in Section 5.2. It MAY span multiple pages, starting on the second page of the logical stream. However many pages it spans, the comment header packet MUST finish the page on which it completes ๐ซถ
After that, every page is an audio data page, and the Ogg packets on them are audio data packets ๐ Each audio data packet holds one Opus packet for each of N different streams. N is typically one for mono or stereo, but it MAY be greater than one for multichannel audio ๐ The value of N is specified in the ID header (see Section 5.1.1), and it stays fixed over the entire length of the logical Ogg bitstream, so no sudden plot twists ๐
The first (N - 1) Opus packets, if any, get packed one after another into the Ogg packet, using the self-delimiting framing from Appendix B of [RFC6716]. The remaining Opus packet gets packed at the end of the Ogg packet using the regular, undelimited framing from Section 3 of [RFC6716]. All of the Opus packets in a single Ogg packet MUST be constrained to have the same duration โฑ๏ธ An implementation of this specification SHOULD treat any Opus packet whose duration is different from that of the first Opus packet in an Ogg packet as if it were a malformed Opus packet with an invalid Table Of Contents (TOC) sequence ๐
The TOC sequence at the beginning of each Opus packet indicates the coding mode, audio bandwidth, channel count, duration (frame size), and number of frames per packet, as described in Section 3.1 of [RFC6716]. The coding mode is one of SILK, Hybrid, or Constrained Energy Lapped Transform (CELT). The combination of coding mode, audio bandwidth, and frame size is called the configuration of an Opus packet ๐ฆ
Packets get placed into Ogg pages in order until the end of stream. Audio data packets might span page boundaries ๐ The first audio data page could have the 'continued packet' flag set (meaning the first audio data packet continues from a previous page) if, for example, it was a live stream joined mid-broadcast, with the headers pasted on the front ๐ If a page has the 'continued packet' flag set and one of the following conditions is also true:
- the previous page with packet data does not end in a continued packet (does not end with a lacing value of 255) OR
- the page sequence numbers are not consecutive,
then a demuxer MUST NOT attempt to decode the data for the first packet on the page, unless the demuxer has some special knowledge that would allow it to interpret this data despite the missing pieces ๐ An implementation MUST treat a zero-octet audio data packet as if it were a malformed Opus packet, as described in Section 3.4 of [RFC6716].
โ ๏ธ okay bestie, the next bit is about streams that get cut off, so pay attention ๐
A logical stream ends with a page with the 'end of stream' flag set. But implementations need to be prepared to deal with truncated streams that do not have a page marked 'end of stream' ๐ญ There is no reason for the final packet on the last page to be a continued packet, i.e., for the final lacing value to be 255. However, demuxers might still run into such streams, possibly because a transfer did not complete or because of corruption. If a packet continues onto a subsequent page (i.e., when the page ends with a lacing value of 255) and one of the following conditions is also true:
- the next page with packet data does not have the 'continued packet' flag set, OR
- there is no next page with packet data, OR
- the page sequence numbers are not consecutive,
then a demuxer MUST NOT attempt to decode the data from that packet, unless the demuxer has some special knowledge that would allow it to interpret this data despite the missing pieces ๐ โโ๏ธ There MUST NOT be any more pages in an Opus logical bitstream after a page marked 'end of stream' ๐ธ
4. Granule Position ๐
the granule position MUST be zero for the ID header page and the page where the comment header completes ๐ฅ That means the first page in the logical stream and the last header page before the first audio data page both have a granule position of zero โจ
The granule position of an audio data page encodes the total number of PCM samples in the stream, up to and including the last fully decodable sample from the last packet completed on that page ๐ง The granule position of the first audio data page will usually be larger than zero, as described in Section 4.5.
A page that is entirely spanned by a single packet (one that completes on a subsequent page) has no granule position. In that case the granule position field is set to the special value '-1' in two's complement ๐
The granule position of an audio data page is measured in units of PCM audio samples at a fixed rate of 48 kHz (per channel, so a stereo stream's granule position does not increment at twice the speed of a mono stream) ๐ It's possible to run an Opus decoder at other sampling rates, but all Opus packets encode samples at a sampling rate that evenly divides 48 kHz. Therefore, the value in the granule position field always counts samples assuming a 48 kHz decoding rate, and the rest of this specification makes the same assumption ๐
The duration of an Opus packet, as defined in [RFC6716], can be any multiple of 2.5 ms, up to a maximum of 120 ms โฑ๏ธ This duration is encoded in the TOC sequence at the beginning of each packet. The number of samples returned by a decoder corresponds to this duration exactly, even for the first few packets. For example, a 20 ms packet fed to a decoder running at 48 kHz will always return 960 samples ๐ A demuxer can parse the TOC sequence at the beginning of each Ogg packet to work backwards or forwards from a packet with a known granule position (i.e., the last packet completed on some page). That lets it assign granule positions to every packet, or even every individual sample ๐ง The one exception is the last page in the stream, as described below.
All other pages with completed packets after the first MUST have a granule position equal to the number of samples contained in packets that complete on that page, plus the granule position of the most recent page with completed packets ๐ฆ This guarantees that a demuxer can assign individual packets the same granule position when working forwards as when working backwards. For this to work, there cannot be any gaps ๐
4.1. Repairing Gaps in Real-Time Streams
okay so if a real-time stream loses packets or never sends them ๐ญ, a multiplexer (muxer) SHOULD emit packets that explicitly ask for Packet Loss Concealment (PLC) in place of the missing ones โจ. Implementations that skip this step still MUST NOT bump the granule position for a page by anything other than the number of samples in packets that actually complete on that page ๐ .
Only gaps that are a multiple of 2.5 ms are repairable ๐, because those are the only durations that packet loss or discontinuous transmission can create. Muxers need not handle other gap sizes. To build the missing packets, you synthesize a TOC byte (defined in Section 3.1 of [RFC6716]) plus whatever extra internal framing you need ๐ง so each stream knows the packet duration. Each missing Opus frame inside the packet is zero bytes long, as defined in Section 3.2.1 of [RFC6716] ๐ฆ.
Zero-byte frames MAY be packed into packets using any of codes 0, 1, 2, or 3 ๐ธ. When successive frames share the same configuration, the higher code packings cut down on overhead. Likewise, if the TOC configuration matches, the muxer MAY also combine the empty frames with previous or subsequent nonzero-length frames (using code 2 or variable bitrate (VBR) code 3) ๐.
[RFC6716] does not impose any requirements on the PLC ๐, but this section lays out choices that are expected to have a positive influence on most PLC implementations, including the reference implementation โจ. Synthesized TOC sequences SHOULD maintain the same mode, audio bandwidth, channel count, and frame size as the previous packet (if any). This is the simplest and usually the most well-tested case for the PLC to handle, and it covers all losses that do not include a configuration switch, as defined in Section 4.5 of [RFC6716] ๐.
When a previous packet is available, keeping the audio bandwidth and channel count the same lets the PLC give maximum continuity in the concealment data it generates ๐ซถ. However, if the gap is not a multiple of the most recent frame size, the frame size will have to change for at least some frames. Such changes SHOULD be delayed as long as possible to simplify things for PLC implementations ๐ .
As an example, a 95 ms gap could be encoded as nineteen 5 ms frames in two bytes with a single constant bitrate (CBR) code 3 packet ๐. If the previous frame size was 20 ms, using four 20 ms frames followed by three 5 ms frames takes 4 bytes (plus an extra byte of Ogg lacing overhead), but lets the PLC use its well-tested steady state behavior for as long as possible ๐ฅ. The total bitrate of the latter approach, including Ogg overhead, is about 0.4 kbps, so the impact on file size is minimal ๐.
Changing modes is discouraged, since this causes some decoder implementations to reset their PLC state ๐ญ. However, SILK and Hybrid mode frames cannot fill gaps that are not a multiple of 10 ms. If switching to CELT mode is needed to match the gap size, a muxer SHOULD do so at the end of the gap, so the PLC can function for as long as possible ๐ฆ.
In the example above, if the previous frame was a 20 ms SILK mode frame, the better solution is to synthesize a packet describing four 20 ms SILK frames, then a packet with a single 10 ms SILK frame, and finally a packet with a 5 ms CELT frame to fill the 95 ms gap ๐ง. This also takes four bytes to describe the synthesized packet data (two bytes for a CBR code 3 and one byte each for two code 0 packets), but three bytes of Ogg lacing overhead are needed to mark the packet boundaries. At 0.6 kbps, this is still a minimal bitrate impact compared to a naive, low-quality solution ๐.
Since medium-band audio is an option only in the SILK mode, wideband frames SHOULD be generated if switching from that configuration to CELT mode ๐. That way, any PLC implementation that tries to migrate state between the modes can preserve all of the available audio bandwidth ๐.
4.2. Pre-skip
There is some amount of latency introduced during decoding ๐ฐ๏ธ, to allow for overlap in the CELT mode, stereo mixing in the SILK mode, and resampling. The encoder might have added more latency through its own resampling and analysis (though the exact amount is not specified). So the first few samples the decoder produces do not match real input audio. They are padding the encoder inserted to make up for that latency ๐. These samples still need to be stored and decoded, because Opus is an asymptotically convergent predictive codec, which means the decoded contents of each frame depend on the recent history of decoder inputs โจ. A player will still want to skip them after decoding ๐ .
A 'pre-skip' field in the ID header (see Section 5.1) signals the number of samples that SHOULD be skipped (decoded but discarded) at the start of the stream ๐. Some specific applications might have a reason to look at that data anyway. The amount need not be a multiple of 2.5 ms, MAY be smaller than a single packet, or MAY span the contents of several packets ๐ง. These samples are not valid audio ๐ญ.
For example, if the first Opus frame uses the CELT mode, it will always produce 120 samples of windowed overlap-add data ๐ธ. But the overlap data starts out as all zeros (since there is no prior frame), which means it cannot, in general, accurately represent the original audio ๐. The SILK mode needs extra delay to account for its analysis and resampling latency, so the encoder delays the original audio to avoid this problem ๐ซถ.
The 'pre-skip' field MAY also be used to do sample-accurate cropping of already encoded streams ๐ฆ. In this case, a value of at least 3840 samples (80 ms) gives the decoder enough history that it will have converged before the stream's output begins ๐.
4.3. PCM Sample Position
The PCM sample position is determined from the granule position using the following formula ๐:
'PCM sample position' = 'granule position' - 'pre-skip'
For example, if the granule position of the first audio data page is 59,971, and the pre-skip is 11,971, then the PCM sample position of the last decoded sample from that page is 48,000 ๐.
This can be converted into a playback time using the following formula ๐:
'PCM sample position'
'playback time' = ---------------------
48000.0
The initial PCM sample position before any samples are played is normally '0' โจ. In this case, the PCM sample position of the first audio sample to be played starts at '1', because it marks the time on the clock after that sample has been played ๐ฐ๏ธ. A stream that is exactly one second long has a final PCM sample position of '48000', as in the example here ๐.
Vorbis streams use a granule position smaller than the number of audio samples in the first audio data page to signal that some of those samples are trimmed from the output (see [VORBIS-TRIM]) ๐ง. But to do that, Vorbis requires the first audio data page to contain exactly two packets, so the decoder can make PCM position adjustments before it has to return any PCM data ๐. Opus uses the pre-skip mechanism for this instead ๐ . The encoder might introduce more than a single packet's worth of latency, and very large packets in streams with a very large number of channels might not fit on a single page ๐.
4.4. End Trimming
The page with the 'end of stream' flag set MAY have a granule position that shows the page holds less audio data than decoding through the final packet would normally return ๐ฆ. This is how the stream ends somewhere other than an even frame boundary ๐. The granule position of the most recent audio data page with completed packets decides this, or '0' is used if there were no previous audio data pages with a completed packet ๐. The difference between these granule positions tells you how many samples to keep after decoding the packets that completed on the final page, and the remaining samples get discarded ๐ฅ. The number of discarded samples SHOULD be no larger than the number decoded from the last packet ๐ .
4.5. Restrictions on the Initial Granule Position
The granule position of the first audio data page with a completed packet MAY be larger than the number of samples in packets that complete on that page ๐ธ. However, it MUST NOT be smaller, unless that page has the 'end of stream' flag set ๐. Allowing a granule position larger than the sample count lets you crop the beginning of a stream, or join a live stream, without rewriting the granule position of all the remaining pages ๐ซถ. That means the PCM sample position just before the first sample to be played MAY be larger than '0' โจ. Synchronization when multiplexing with other logical streams still uses the PCM sample position relative to '0' to compute sample times ๐ง. This does not change how pre-skip works: exactly 'pre-skip' samples SHOULD be skipped from the start of the decoded output, even if the initial PCM sample position is greater than zero ๐.
On the other hand, a granule position smaller than the number of decoded samples stops a demuxer from working backwards to give each packet or each individual sample a valid granule position, since granule positions are non-negative ๐ญ. An implementation MUST treat any stream as invalid if the granule position is smaller than the number of samples in packets that complete on the first audio data page with a completed packet, unless that page has the 'end of stream' flag set ๐. It MAY defer this check until it decodes the last packet completed on that page ๐ฆ.
If that page has the 'end of stream' flag set, a demuxer MUST treat any stream as invalid if its granule position is smaller than the 'pre-skip' amount ๐ โโ๏ธ. That would mean there are more samples to skip from the initial decoded output than exist in the stream ๐. If the granule position is smaller than the number of decoded samples produced by the packets that complete on that page, a demuxer MUST use an initial granule position of '0', and it can work forwards from '0' to timestamp individual packets ๐. If the granule position is larger than the number of decoded samples available, the demuxer MUST still work backwards as described above, even if the 'end of stream' flag is set, to find the initial granule position and therefore the initial PCM sample position ๐. Both of these will be greater than '0' in this case ๐.
4.6. Seeking and Pre-roll โจ
okay so seeking in Ogg files is best done with a bisection search ๐ hunting for a page whose granule position matches a PCM position at or before where you wanna jump. with appropriately weighted bisection, you get accurate seeks in like one or two bisections on average, even in multi-gigabyte files ๐ญ๐ฅ. see [SEEKING] for an example of general implementation guidance ๐ซถ.
when seeking within an Ogg Opus stream, an implementation SHOULD start decoding (and toss the output) at least 3840 samples (80 ms) before the seek target, so the audio is actually correct by the time it reaches the target ๐ . this "pre-roll" is its own thing, separate from and unrelated to the pre-skip at the start of the stream, so don't mix them up bestie ๐. if the point 80 ms before the seek target lands before the initial PCM sample position, an implementation SHOULD start decoding from the beginning of the stream, applying pre-skip as normal, whether pre-skip is bigger or smaller than 80 ms. then it keeps discarding samples to reach the seek target (if any) โจ.
5. Header Packets ๐
an Ogg Opus logical stream has exactly two mandatory header packets: an identification header and a comment header ๐ง.
5.1. Identification Header ๐
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 'O' | 'p' | 'u' | 's' |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 'H' | 'e' | 'a' | 'd' |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Version = 1 | Channel Count | Pre-skip |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Input Sample Rate (Hz) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Output Gain (Q7.8 in dB) | Mapping Family| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ :
| |
: Optional Channel Mapping Table... :
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Figure 2: ID Header Packet
here's what each field in the identification (ID) header means ๐:
- Magic Signature:
This is an 8-octet (64-bit) field that lets you identify the codec, and it's human readable ๐. it contains, in order, these magic numbers:
0x4F 'O'
0x70 'p'
0x75 'u'
0x73 's'
0x48 'H'
0x65 'e'
0x61 'a'
0x64 'd'
starting with "Op" helps tell it apart from audio data packets, since that's an invalid TOC sequence ๐.
- Version (8 bits, unsigned):
the version number MUST always be '1' for this version of the encapsulation spec ๐. implementations SHOULD treat streams where the upper four bits of the version number match a recognized spec as backwards compatible with that spec ๐ฆ. so the version number can be split into "major" and "minor" version sub-fields, where changes to the minor sub-field (the lower four bits) signal compatible changes โจ. for example, an implementation of this specification SHOULD accept any stream with a version number of '15' or less, and SHOULD assume any stream with a version number of '16' or greater is incompatible ๐ . the initial version '1' was picked so implementations wouldn't rely on this octet as a null terminator for the "OpusHead" string ๐ง.
- Output Channel Count 'C' (8 bits, unsigned):
this is the number of output channels ๐. it might be different from the number of encoded channels, which can change packet by packet ๐. this value MUST NOT be zero ๐ซ. the max allowed value depends on the channel mapping family and might be as large as 255. see Section 5.1.1 for details ๐.
- Pre-skip (16 bits, unsigned, little endian):
this is the number of samples (at 48 kHz) to discard from the decoder output when starting playback ๐ง. it's also the number you subtract from a page's granule position to calculate its PCM sample position โจ. when cropping the beginning of existing Ogg Opus streams, a pre-skip of at least 3,840 samples (80 ms) is RECOMMENDED so the decoder fully converges ๐.
- Input Sample Rate (32 bits, unsigned, little endian):
this is the sample rate of the original input (before encoding), in Hz ๐ต. this field is _not_ the sample rate to use for playing back the encoded data, so don't get it twisted bestie ๐.
Opus can switch between internal audio bandwidths of 4, 6, 8, 12, and 20 kHz ๐ธ. each packet in the stream can have a different audio bandwidth ๐ฆ. no matter the audio bandwidth, the reference decoder supports decoding any stream at a sample rate of 8, 12, 16, 24, or 48 kHz ๐. the original sample rate of the audio passed to the encoder isn't preserved by the lossy compression, so that info is gone ๐ญ.
an Ogg Opus player SHOULD pick its playback sample rate using this procedure ๐:
- If the hardware supports 48 kHz playback, decode at 48 kHz.
- Otherwise, if the hardware's highest available sample rate is a supported rate, decode at this sample rate.
- Otherwise, if the hardware's highest available sample rate is less than 48 kHz, decode at the next higher Opus supported rate above the highest available hardware rate and resample.
- Otherwise, decode at 48 kHz and resample.
but the 'input sample rate' field lets the muxer pass the original input stream's sample rate along as metadata ๐. this is super useful when the user needs the output sample rate to match the input sample rate ๐. like, when you're not playing the output, an implementation writing PCM format samples to disk might choose to resample back to the original input rate to reduce surprise, since the user might reasonably expect a file with the same sample rate ๐ฅบ.
a value of zero means "unspecified" ๐คทโโ๏ธ. muxers SHOULD write the actual input sample rate or zero ๐ . implementations that do something with this field SHOULD take care to behave sanely when given crazy values (for example, don't actually upsample the output to 10 MHz if someone requests it) ๐. implementations SHOULD support input sample rates between 8 kHz and 192 kHz (inclusive) โจ. rates outside this range MAY be ignored by falling back to the default rate of 48 kHz instead ๐.
- Output Gain (16 bits, signed, little endian):
this is a gain to be applied when decoding ๐ฅ. it's 20*log10 of the factor you scale the decoder output by to hit the desired playback volume ๐. it's stored as a 16-bit, signed, two's complement fixed-point value with 8 fractional bits (aka Q7.8 [Q-NOTATION]) ๐งฎ.
to apply the gain, an implementation could use this:
sample *= pow(10, output_gain/(20.0*256))
where 'output_gain' is the raw 16-bit value from the header ๐.
players and media frameworks SHOULD apply it by default ๐ง. if a player chooses to apply any volume adjustment or gain modification, like the R128_TRACK_GAIN (see Section 5.2), the adjustment MUST be applied in addition to this output gain to get playback at the normalized volume ๐.
a muxer SHOULD set this field to zero and instead apply any gain prior to encoding, when that's possible and doesn't clash with the user's wishes ๐ซถ. a nonzero output gain means the gain was adjusted after encoding, or that a user wanted to adjust playback gain while keeping the ability to recover the original signal amplitude ๐ฆ.
the output gain has an enormous range (+/- 128 dB, enough to amplify inaudible sounds to the threshold of physical pain ๐), but most apps can only reasonably use a small slice around zero ๐. the big range mostly exists so gain can always be losslessly transferred between OpusHead and R128 gain tags (see below) without saturating โจ.
- Channel Mapping Family (8 bits, unsigned):
this octet tells you the order and semantic meaning of the output channels ๐๏ธ. each currently specified value of this octet indicates a mapping family, which defines a set of allowed channel counts and the ordered set of channel names for each allowed count ๐ธ. the details are in Section 5.1.1 ๐.
- Channel Mapping Table:
this table defines the mapping from encoded streams to output channels ๐บ๏ธ. its contents are specified in Section 5.1.1 ๐ง.
all fields in the ID header are REQUIRED, except for 'channel mapping table', which MUST be omitted when the channel mapping family is 0 but is REQUIRED otherwise ๐. implementations SHOULD treat a stream as invalid if it contains an ID header that doesn't have enough data for these fields, even if it has a valid 'magic signature' ๐ซ. future versions of this specification, even backwards-compatible ones, might add more fields to the ID header ๐ฎ. if an ID header has a compatible major version but a larger minor version, an implementation MUST NOT treat it as invalid just for containing additional data not specified here, as long as it still completes on the first page ๐ซถ.
5.1.1. Channel Mapping โจ
okay bestie, so an Ogg Opus stream lets you map a number of Opus streams (N) to a possibly bigger number of decoded channels (M + N), and then to yet another number of output channels (C) ๐ฆ. That output count can be bigger or smaller than the decoded count, which is so flexible ๐ . The order and meaning of all these channels comes from a channel mapping. It's made of the 'channel mapping family' octet and, for every family except family 0, a 'channel mapping table' ๐. Check out Figure 3:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+
| Stream Count |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Coupled Count | Channel Mapping... :
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Figure 3: Channel Mapping Table
The fields in the channel mapping table mean the following ๐ธ:
- Stream Count 'N' (8 bits, unsigned):
this is the total number of streams encoded in each Ogg packet ๐ง. It's needed to correctly parse the packed Opus packets inside an Ogg packet, as described in Section 3 โจ. This value MUST NOT be zero, because without at least one Opus packet with a valid TOC sequence, a demuxer can't recover the duration of an Ogg packet ๐.
For channel mapping family 0, this value defaults to 1 and isn't coded ๐.
- Coupled Stream Count 'M' (8 bits, unsigned):
this is the number of streams whose decoders are set up to produce two channels (stereo) ๐ง. This MUST be no larger than the total number of streams, N.
Each packet in an Opus stream has an internal channel count of 1 or 2, and it can change from packet to packet ๐ฅ. The encoder picks it based on the bitrate and the audio being encoded. The original channel count of the audio passed to the encoder isn't necessarily preserved by the lossy compression ๐ญ.
Regardless of the internal channel count, any Opus stream can be decoded as mono (a single channel) or stereo (two channels) by setting up the decoder properly ๐. The 'coupled stream count' field says the decoders for the first M Opus streams are set up for stereo (two-channel) output, and the remaining (N - M) decoders are set up for mono (a single channel) only ๐. The total number of decoded channels, (M + N), MUST be no larger than 255, because there's no way to index more channels than that in the channel mapping ๐ .
For channel mapping family 0, this value defaults to (C - 1) (i.e., 0 for mono and 1 for stereo) and isn't coded.
- Channel Mapping (8*C bits):
this contains one octet per output channel, saying which decoded channel gets used for each one ๐. Let 'index' be the value of this octet for a particular output channel. This value MUST either be smaller than (M + N) or be the special value 255. If 'index' is less than 2*M, the output MUST be taken from decoding stream ('index'/2) as stereo, selecting the left channel if 'index' is even and the right channel if 'index' is odd. If 'index' is 2*M or larger, but less than 255, the output MUST be taken from decoding stream ('index' - M) as mono. If 'index' is 255, the corresponding output channel MUST contain pure silence ๐คซ.
The number of output channels, C, isn't constrained to match the number of decoded channels (M + N) ๐ฆ. A single index value MAY appear multiple times, so the same decoded channel might get mapped to multiple output channels. Some decoded channels might not be assigned to any output channel at all, either ๐ง.
For channel mapping family 0, the first index defaults to 0, and if C == 2, the second index defaults to 1. Neither index is coded.
After producing the output channels, the channel mapping family decides the semantic meaning of each one ๐. There are three defined mapping families in this specification.
5.1.1.1. Channel Mapping Family 0
Allowed numbers of channels: 1 or 2. RTP mapping. This is the same channel interpretation as [RFC7587] ๐.
- 1 channel: monophonic (mono).
- 2 channels: stereo (left, right).
Special mapping: this channel mapping family also says the content is a single Opus stream that is stereo if and only if C == 2, with stream index 0 mapped to output channel 0 (mono, or left channel) and stream index 1 mapped to output channel 1 (right channel) if stereo โจ. When the 'channel mapping family' octet has this value, the channel mapping table MUST be omitted from the ID header packet ๐.
5.1.1.2. Channel Mapping Family 1
Allowed numbers of channels: 1...8. Vorbis channel order (see below) ๐.
Each channel is assigned to a speaker location in a conventional surround arrangement ๐. The specific locations depend on the number of channels, and they're listed below in order of the corresponding channel indices.
- 1 channel: monophonic (mono).
- 2 channels: stereo (left, right).
- 3 channels: linear surround (left, center, right).
- 4 channels: quadraphonic (front left, front right, rear left, rear right).
- 5 channels: 5.0 surround (front left, front center, front right, rear left, rear right).
- 6 channels: 5.1 surround (front left, front center, front right, rear left, rear right, LFE).
- 7 channels: 6.1 surround (front left, front center, front right, side left, side right, rear center, LFE).
- 8 channels: 7.1 surround (front left, front center, front right, side left, side right, rear left, rear right, LFE).
This set of surround options and speaker location orderings is the same as the one used by the Vorbis codec [VORBIS-MAPPING]. The ordering is different from the one used by the WAVE [WAVE-MULTICHANNEL] and Free Lossless Audio Codec (FLAC) [FLAC] formats, so getting the order right means permuting the output channels when decoding to or encoding from those formats ๐ญ. "LFE" here refers to a Low Frequency Effects channel, often mapped to a subwoofer with no particular spatial position ๐ง. Implementations SHOULD identify "side" or "rear" speaker locations with "surround" and "back" as appropriate when interfacing with audio formats or systems that prefer that terminology ๐ .
5.1.1.3. Channel Mapping Family 255
Allowed numbers of channels: 1...255. No defined channel meaning ๐ซถ.
Channels are unidentified. General-purpose players SHOULD NOT attempt to play these streams ๐. Offline implementations MAY deinterleave the output into separate PCM files, one per channel ๐. Implementations SHOULD NOT produce output for channels mapped to stream index 255 (pure silence) unless they have no other way to indicate the index of non-silent channels ๐คซ.
5.1.1.4. Undefined Channel Mappings
The remaining channel mapping families (2...254) are reserved ๐ง. A demuxer implementation encountering a reserved 'channel mapping family' value SHOULD act as though the value is 255 โจ.
5.1.1.5. Downmixing
An Ogg Opus player MUST support any valid channel mapping with a channel mapping family of 0 or 1, even if the number of channels does not match the physically connected audio hardware. Players SHOULD perform channel mixing to increase or reduce the number of channels as needed. ๐งโจ
Implementations MAY use the matrices in Figures 4 through 9 to implement downmixing from multichannel files using channel mapping family 1 (Section 5.1.1.2), which are known to give acceptable results for stereo. Matrices for 3 and 4 channels are normalized so each coefficient row sums to 1 to avoid clipping. For 5 or more channels, they are normalized to 2 as a compromise between clipping and dynamic range reduction. ๐ธ
In these matrices the front-left and front-right channels are generally passed through directly. When a surround channel is split between both the left and right stereo channels, coefficients are chosen so their squares sum to 1, which helps preserve the perceived intensity. Rear channels are mixed more diffusely or attenuated to maintain focus on the front channels. ๐
L output = ( 0.585786 * left + 0.414214 * center )
R output = ( 0.414214 * center + 0.585786 * right )
Exact coefficient values are 1 and 1/sqrt(2), multiplied by 1/(1 + 1/sqrt(2)) for normalization.
Figure 4: Stereo Downmix Matrix for the Linear Surround Channel Mapping
/ \ / \ / FL \
| L output | | 0.422650 0.000000 0.366025 0.211325 | | FR |
| R output | = | 0.000000 0.422650 0.211325 0.366025 | | RL |
\ / \ / \ RR /
Exact coefficient values are 1, sqrt(3)/2 and 1/2, multiplied by 1/(1 + sqrt(3)/2 + 1/2) for normalization.
Figure 5: Stereo Downmix Matrix for the Quadraphonic Channel Mapping
/ FL \
/ \ / \ | FC |
| L | | 0.650802 0.460186 0.000000 0.563611 0.325401 | | FR |
| R | = | 0.000000 0.460186 0.650802 0.325401 0.563611 | | RL |
\ / \ / | RR |
\ /
Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by 2/(1 + 1/sqrt(2) + sqrt(3)/2 + 1/2) for normalization.
Figure 6: Stereo Downmix Matrix for the 5.0 Surround Mapping
/FL \
/ \ / \ |FC |
|L| | 0.529067 0.374107 0.000000 0.458186 0.264534 0.374107 | |FR |
|R| = | 0.000000 0.374107 0.529067 0.264534 0.458186 0.374107 | |RL |
\ / \ / |RR |
\LFE/
Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by 2/(1 + 1/sqrt(2) + sqrt(3)/2 + 1/2 + 1/sqrt(2)) for normalization.
Figure 7: Stereo Downmix Matrix for the 5.1 Surround Mapping
/ \
| 0.455310 0.321953 0.000000 0.394310 0.227655 0.278819 0.321953 |
| 0.000000 0.321953 0.455310 0.227655 0.394310 0.278819 0.321953 |
\ /
Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2, 1/2 and sqrt(3)/2/sqrt(2), multiplied by 2/(1 + 1/sqrt(2) + sqrt(3)/2 + 1/2 + sqrt(3)/2/sqrt(2) + 1/sqrt(2)) for normalization. The coefficients are in the same order as in Section 5.1.1.2 and the matrices above.
Figure 8: Stereo Downmix Matrix for the 6.1 Surround Mapping
/ \
| .388631 .274804 .000000 .336565 .194316 .336565 .194316 .274804 |
| .000000 .274804 .388631 .194316 .336565 .194316 .336565 .274804 |
\ /
Exact coefficient values are 1, 1/sqrt(2), sqrt(3)/2 and 1/2, multiplied by 2/(2 + 2/sqrt(2) + sqrt(3)) for normalization. The coefficients are in the same order as in Section 5.1.1.2 and the matrices above.
Figure 9: Stereo Downmix Matrix for the 7.1 Surround Mapping
5.2. Comment Header โจ
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 'O' | 'p' | 'u' | 's' |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 'T' | 'a' | 'g' | 's' |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Vendor String Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
: Vendor String... :
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| User Comment List Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| User Comment #0 String Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
: User Comment #0 String... :
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| User Comment #1 String Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
: :
Figure 10: Comment Header Packet
The comment header consists of a 64-bit 'magic signature' field, followed by data in the same format as the [VORBIS-COMMENT] header used in Ogg Vorbis, except (like Ogg Theora and Speex) the final 'framing bit' specified in the Vorbis specification is not present. ๐ฆ
5.2.1. Magic Signature ๐
This is an 8-octet (64-bit) field that allows codec identification and is human readable. It contains, in order, the magic numbers:
0x4F 'O'
0x70 'p'
0x75 'u'
0x73 's'
0x54 'T'
0x61 'a'
0x67 'g'
0x73 's'
Starting with "Op" helps distinguish it from audio data packets, as this is an invalid TOC sequence. ๐ง
5.2.2. Vendor String Length ๐
This field gives the length of the following vendor string, in octets. It MUST NOT indicate that the vendor string is longer than the rest of the packet.
Note: this is a 32-bit, unsigned, little-endian field.
5.2.3. Vendor String ๐
This is a simple human-readable tag for vendor information, encoded as a UTF-8 string [RFC3629]. No terminating null octet is necessary.
This tag is intended to identify the codec encoder and encapsulation implementations, for tracing differences in technical behavior. User-facing applications can use the 'ENCODER' user comment tag to identify themselves. ๐
5.2.4. User Comment List Length ๐ธ
This field indicates the number of user-supplied comments. It MAY indicate there are zero user-supplied comments, in which case there are no additional fields in the packet. It MUST NOT indicate that there are so many comments that the comment string lengths would require more data than is available in the rest of the packet.
Note: this is a 32-bit, unsigned, little-endian field.
5.2.5. User Comment #i String Length ๐
This field gives the length of the following user comment string, in octets. There is one for each user comment indicated by the 'user comment list length' field. It MUST NOT indicate that the string is longer than the rest of the packet.
Note: this is a 32-bit, unsigned, little-endian field.
5.2.6. User Comment #i String ๐ซถ
This field contains a single user comment encoded as a UTF-8 string [RFC3629]. There is one for each user comment indicated by the 'user comment list length' field. ๐
The 'vendor string length' and 'user comment list length' fields are REQUIRED, and implementations SHOULD treat a stream as invalid if it contains a comment header that does not have enough data for these fields, or that does not contain enough data for the corresponding vendor string or user comments they describe. Making this check before allocating the associated memory to contain the data helps prevent a possible Denial-of-Service (DoS) attack from small comment headers that claim to contain strings longer than the entire packet or more user comments than could possibly fit in the packet. ๐ญ๐ฅ
Immediately following the user comment list, the comment header MAY contain zero-padding or other binary data that is not specified here. If the least-significant bit of the first byte of this data is 1, then editors SHOULD preserve the contents of this data when updating the tags, but if this bit is 0, all such data MAY be treated as padding, and truncated or discarded as desired. This allows informal experimentation with the format of this binary data until it can be specified later. ๐
The comment header can be arbitrarily large and might be spread over a large number of Ogg pages. Implementations MUST avoid attempting to allocate excessive amounts of memory when presented with a very large comment header. To accomplish this, implementations MAY treat a stream as invalid if it has a comment header larger than 125,829,120 octets (120 MB), and MAY ignore individual comments that are not fully contained within the first 61,440 octets of the comment header. โญ
5.2.1. Tag Definitions ๐
okay so the user comment strings follow the NAME=value format from [VORBIS-COMMENT], with the same recommended tag names you already know: ARTIST, TITLE, DATE, ALBUM, and so on ๐ Two new comment tags get introduced here, and they're both about normalization (aka making tracks play at a chill, consistent volume ๐ฆ).
First up is an optional gain for track normalization:
R128_TRACK_GAIN=-573
This is the volume shift needed to normalize the track's volume during isolated playback, in random shuffle, and so on ๐ถ The gain is a Q7.8 fixed-point number in dB, same as the ID header's 'output gain' field. It's kind of like the REPLAYGAIN_TRACK_GAIN tag in Vorbis [REPLAY-GAIN], except the normal volume reference is the [EBU-R128] standard โจ
Second is an optional gain for album normalization:
R128_ALBUM_GAIN=111
This is the volume shift needed to normalize the overall volume when you're playing a whole collection of tracks together ๐ Same deal: it's a Q7.8 fixed-point number in dB, same as the ID header's 'output gain' field. The values '-573' and '111' are just examples, so don't panic if your album has different numbers ๐
Now the rules, bestie, and they're strict ๐ญ An Ogg Opus stream MUST NOT have more than one of each of these tags. If they're there, their values MUST be an integer from -32768 to 32767, inclusive, written in ASCII as a base 10 number with no whitespace. A leading '+' or '-' is valid. Leading zeros are also allowed, but the value MUST be represented by no more than 6 characters. Other non-digit characters MUST NOT be present ๐
If they're present, R128_TRACK_GAIN and R128_ALBUM_GAIN MUST correctly represent the R128 normalization gain relative to the 'output gain' field in the ID header. If a player decides to use the R128_TRACK_GAIN tag or the R128_ALBUM_GAIN tag, it MUST apply those gains in addition to the 'output gain' value ๐ฅ If a tool changes the ID header's 'output gain' field, it MUST also update or remove the R128_TRACK_GAIN and R128_ALBUM_GAIN comment tags if they're there. And a muxer SHOULD put the gain it wants other tools to use by default into the 'output gain' field, not the comment tag ๐ซถ
To avoid confusion between multiple normalization schemes, an Opus comment header SHOULD NOT contain any of the REPLAYGAIN_TRACK_GAIN, REPLAYGAIN_TRACK_PEAK, REPLAYGAIN_ALBUM_GAIN, or REPLAYGAIN_ALBUM_PEAK tags. The exception is when they're only used in some context where there's guaranteed to be no such confusion ๐ [EBU-R128] normalization is the preferred option over the older REPLAYGAIN schemes, because it's clearly defined and industry-adopted ๐ Peak normalizations are honestly kind of a mess to calculate reliably for lossy codecs, since decoders can vary how big the excursions come out. In the authors' investigations, peak normalizations weren't applied consistently or broadly enough to be worth including here ๐ฅ
6. Packet Size Limits ๐
Technically, valid Opus packets can be arbitrarily large because of the padding format ๐ The amount of non-padding data they can hold is bounded, though. These packets might be spread across a similarly enormous number of Ogg pages ๐ณ When encoding, implementations SHOULD limit padding in audio data packets to no more than is necessary to make a VBR stream CBR, unless they have no reasonable way to figure out what's necessary.
Demuxers SHOULD treat audio data packets as invalid (as if they were malformed Opus packets with an invalid TOC sequence) if they're larger than 61,440 octets per Opus stream, unless they have a specific reason to allow extra padding. Those packets necessarily contain more padding than needed to make a stream CBR ๐ Demuxers MUST avoid trying to allocate excessive amounts of memory when they get a very large packet. Demuxers MAY treat audio data packets as invalid or partially process them if they're larger than 61,440 octets in an Ogg Opus stream with channel mapping families 0 or 1. Demuxers MAY also treat audio data packets as invalid or partially process them in any Ogg Opus stream if the packet is larger than 61,440 octets and also larger than 7,680 octets per Opus stream. A packet this huge could be a memory exhaustion attack or stream corruption, so stay alert ๐จ
In an Ogg Opus stream, the largest possible valid packet that doesn't use padding has a size of (61,298*N - 2) octets. With 255 streams, that's 15,630,988 octets, which can span up to 61,298 Ogg pages, all but one of which will have a granule position of -1 ๐คฏ This is, of course, an extremely dramatic packet, made of 255 streams, each holding 120 ms of audio encoded as 2.5 ms frames. Each frame uses the maximum possible number of octets (1275) and is stored in the least efficient way allowed (a VBR code 3 Opus packet). Even then, most of the data will just be zeros, because 2.5 ms frames can't actually use all 1275 octets ๐
The largest packet made of entirely useful data is (15,326*N - 2) octets. That corresponds to 120 ms of audio encoded as 10 ms frames in either SILK or Hybrid mode, but at a data rate of over 1 Mbps, which makes very little sense for the quality you get back ๐
A more reasonable limit is (7,664*N - 2) octets. That corresponds to 120 ms of audio encoded as 20 ms stereo CELT mode frames, with a total bitrate just under 511 kbps (not counting the Ogg encapsulation overhead) ๐ฆ For channel mapping family 1, N = 8 is a reasonable upper bound, since it lets each of the 8 possible output channels be decoded from a separate stereo Opus stream. That gives a size of 61,310 octets, which gets rounded up to a multiple of 1,024 octets to give the audio data packet size of 61,440 octets. That's the size every implementation is expected to be able to process successfully ๐
7. Encoder Guidelines ๐ง
When encoding Opus streams, Ogg muxers SHOULD take the algorithmic delay of the Opus encoder into account โจ
In encoders derived from the reference implementation [RFC6716], you can query the number of samples with:
opus_encoder_ctl(encoder_state, OPUS_GET_LOOKAHEAD(&delay_samples));
To get good quality in the very first samples of a stream, implementations MAY use linear predictive coding (LPC) extrapolation to generate at least 120 extra samples at the beginning. That way the Opus encoder doesn't have to encode a discontinuous signal ๐ธ For more on linear prediction, see [LINEAR-PREDICTION]. For an input file containing 'length' samples, the implementation SHOULD set the 'pre-skip' header value to (delay_samples + extra_samples), encode at least (length + delay_samples + extra_samples) samples, and set the granule position of the last page to (length + delay_samples + extra_samples). This makes sure the encoded file has the same duration as the original, with no time offset โฑ๏ธ The best way to pad the end of the stream is also LPC extrapolation, but zero-padding is fine too ๐ซง
7.1. LPC Extrapolation ๐
The first step in LPC extrapolation is computing the linear prediction coefficients [LPC-SAMPLE]. When extending the end of the signal, you do order-N LPC analysis (N is typically anywhere from 8 to 40) on a window near the end of the signal ๐ง The last N samples get used as memory for an infinite impulse response (IIR) filter.
The filter is then applied to a zero input to extrapolate the end of the signal. Let 'a(k)' be the kth LPC coefficient and 'x(n)' be the nth sample of the signal. Each new sample past the end of the signal is computed as:
N
---
x(n) = \ a(k)*x(n - k)
/
---
k = 1
The process is repeated independently for each channel. It's also possible to extend the beginning of the signal by applying the same process backward in time ๐ When extending the beginning, it's best to apply a "fade in" to the extrapolated signal, for example by multiplying it by a half-Hanning window [HANNING] ๐
7.2. Continuous Chaining ๐
In some apps, like Internet radio, you might want to cut a long stream into smaller chains, for example so the comment header can be updated ๐ป You can do this by splitting the input streams into segments and encoding each segment on its own. The catch is that it creates a small discontinuity at the boundary because Opus is lossy ๐ฌ A muxer MAY avoid that discontinuity with the following procedure:
- Encode the last frame of the first segment as an independent frame by turning off all forms of inter-frame prediction. De-emphasis is allowed.
- Set the granule position of the last page to a point near the end of the last frame.
- Begin the second segment with a copy of the last frame of the first segment.
- Set the 'pre-skip' value of the second stream so that the two streams join properly.
- Continue the encoding process normally from there, without any reset to the encoder.
In encoders derived from the reference implementation, you can turn off inter-frame prediction by calling:
opus_encoder_ctl(encoder_state, OPUS_SET_PREDICTION_DISABLED(1));
For best results, this implementation requires that prediction be explicitly enabled again before resuming normal encoding, even after a reset ๐ฅนโจ
8. Security Considerations โจ
okay bestie, security is literally where my brain goes into full detective mode ๐ต๏ธโโ๏ธ๐ so let's get into it. The big picture first: Opus implementations need to think about security the way [RFC4732] describes, and that's not just a codec problem. The container matters just as much ๐ซถ Malicious payloads and input streams can be used to attack codec implementations, so implementations MUST NOT overrun their allocated memory and MUST NOT consume excessive resources when decoding payloads or processing input streams. Encoders usually have fewer problems, but this still applies to a muxer, because a vulnerability there would let an attacker go after transcoding gateways. Not cute ๐ญ
The header parsing code is the most likely place for overruns, so be careful there ๐ Make sure your buffers actually contain enough data for every required field before you read it. For example, check all of the channel map data in the ID header first. Validating the channel map indices is also a good move, so you meet every restriction in Section 5.1.1 and don't end up reading from channels that don't exist. Main character energy: buffer checks first, always ๐
Next, resource usage. We advise implementations to be extra wary of streams that could make them process way more data than was ever transmitted ๐ A small comment header can claim string lengths or a user comment list length that implies many gigabytes. Even computing the required buffer size can overflow a 32-bit integer, and allocating that buffer before checking whether it's a reasonable size is a bad idea ๐ After reading the user comment list length, you might want to verify the header holds at least the minimum data for that many comments, which is 4 additional octets per comment to indicate each has a length of zero. Do this before going any further, and be careful about overflow in these calculations too. If you allocate an array of pointers to those strings, the pointers may be larger than 4 octets, which could mean a separate overflow check. Be careful, bestie ๐ง
Another bug in this class that people have spotted more than once is invalid data at the end of a stream โ ๏ธ Implementations often seek to the end to find the last timestamp so they can compute the total duration. If they don't find a valid capture pattern and Ogg page from the desired logical stream, they back up and try again. If you don't avoid re-scanning data you already scanned, the search can get out of hand fast, with complexity that is quadratic in the amount of invalid data. Iconic for all the wrong reasons ๐ญ
When seeking in general, be cautious about invalid granule position values. Make sure all your algorithms keep making progress and eventually terminate, even if granule positions are missing or out of order ๐ธ
Last one: like most container formats, Ogg Opus streams SHOULD NOT be used with insecure ciphers or cipher modes that are vulnerable to known-plaintext attacks. The Ogg page capture pattern and the 'magic signature' fields in the ID header and comment header have really predictable values, and so do various elements of the codec data itself. So yeah, don't rely on those for secrecy ๐๐
9. Content Type ๐
okay so an "Ogg Opus file" is one or more sequentially multiplexed segments, and each one contains exactly one Ogg Opus stream ๐ฆ The RECOMMENDED mime-type for Ogg Opus files is "audio/ogg" ๐
If you want more specificity, one MAY indicate the presence of Opus streams using the codecs parameter defined in [RFC6381] and [RFC5334], for example:
audio/ogg; codecs=opus
and that's for an Ogg Opus file โจ
The RECOMMENDED filename extension for Ogg Opus files is '.opus' ๐
Now, when Opus is multiplexed alongside other streams in an Ogg container, one SHOULD use one of the "audio/ogg", "video/ogg", or "application/ogg" mime-types, as defined in [RFC5334] ๐ These aren't strictly "Ogg Opus files" as described above, since each sequentially multiplexed segment holds more than a single Opus stream, like video or multiple audio tracks. So in those cases the '.opus' filename extension is NOT RECOMMENDED ๐
Either way, this document updates [RFC5334] to add "opus" as a codecs parameter value, with char[8]: 'OpusHead' as the Codec Identifier ๐
10. IANA Considerations ๐
so IANA has updated the "Media Types" registry. They added .opus as a file extension for "audio/ogg", and they added this document as a reference alongside [RFC5334] for the "audio/ogg", "video/ogg", and "application/ogg" Media Types โจ
This document also defines a new registry called "Opus Channel Mapping Families" ๐ฆ It describes how the semantic meanings of the channels in a multichannel Opus stream get described. IANA created a new namespace of "Opus Channel Mapping Families", and this registry is listed on the IANA Matrix. Changes to it follow the "Specification Required" registration policy from [RFC5226] ๐ซถ Each entry has a Channel Mapping Family Number, written in decimal in the range 0 to 255 inclusive, plus a Reference (or list of references). Each Reference must point to enough documentation to describe what information is coded in the Opus identification header for that channel mapping family, how a demuxer works out the stream count ('N') and coupled stream count ('M') from that information, and how it determines the proper interpretation of each decoded channel ๐ธ
This document defines three initial assignments for the registry:
+-------+---------------------------+
| Value | Reference |
+-------+---------------------------+
| 0 | RFC 7845, Section 5.1.1.1 |
| | |
| 1 | RFC 7845, Section 5.1.1.2 |
| | |
| 255 | RFC 7845, Section 5.1.1.3 |
+-------+---------------------------+
The designated expert decides whether the Reference points to a specification that meets the permanence and ready availability requirements laid out in [RFC5226], and whether it specifies the information described above clearly enough for interoperable implementations ๐
11. References ๐
11.1. Normative References ๐
[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
Requirement Levels", BCP 14, RFC 2119,
DOI 10.17487/RFC2119, March 1997,
<https://www.rfc-editor.org/info/rfc2119>.
[RFC3533] Pfeiffer, S., "The Ogg Encapsulation Format Version 0",
RFC 3533, DOI 10.17487/RFC3533, May 2003,
<https://www.rfc-editor.org/info/rfc3533>.
[RFC3629] Yergeau, F., "UTF-8, a transformation format of ISO
10646", STD 63, RFC 3629, DOI 10.17487/RFC3629, November
2003, <https://www.rfc-editor.org/info/rfc3629>.
[RFC5226] Narten, T. and H. Alvestrand, "Guidelines for Writing an
IANA Considerations Section in RFCs", BCP 26, RFC 5226,
DOI 10.17487/RFC5226, May 2008,
<https://www.rfc-editor.org/info/rfc5226>.
[RFC5334] Goncalves, I., Pfeiffer, S., and C. Montgomery, "Ogg Media
Types", RFC 5334, DOI 10.17487/RFC5334, September 2008,
<https://www.rfc-editor.org/info/rfc5334>.
[RFC6381] Gellens, R., Singer, D., and P. Frojdh, "The 'Codecs' and
'Profiles' Parameters for "Bucket" Media Types", RFC 6381,
DOI 10.17487/RFC6381, August 2011,
<https://www.rfc-editor.org/info/rfc6381>.
[RFC6716] Valin, JM., Vos, K., and T. Terriberry, "Definition of the
Opus Audio Codec", RFC 6716, DOI 10.17487/RFC6716,
September 2012, <https://www.rfc-editor.org/info/rfc6716>.
[EBU-R128]
EBU Technical Committee, "Loudness Recommendation EBU
R128", August 2011, <https://tech.ebu.ch/loudness>.
[VORBIS-COMMENT]
Montgomery, C., "Ogg Vorbis I Format Specification:
Comment Field and Header Specification", July 2002,
<https://www.xiph.org/vorbis/doc/v-comment.html>.
11.2. Informative References ๐
[RFC4732] Handley, M., Ed., Rescorla, E., Ed., and IAB, "Internet
Denial-of-Service Considerations", RFC 4732,
DOI 10.17487/RFC4732, December 2006,
<https://www.rfc-editor.org/info/rfc4732>.
[RFC7587] Spittka, J., Vos, K., and JM. Valin, "RTP Payload Format
for the Opus Speech and Audio Codec", RFC 7587,
DOI 10.17487/RFC7587, June 2015,
<https://www.rfc-editor.org/info/rfc7587>.
[FLAC] Coalson, J., "FLAC - Free Lossless Audio Codec Format
Description", January 2008,
<https://xiph.org/flac/format.html>.
[HANNING] Wikipedia, "Hann window", February 2016,
<https://en.wikipedia.org/w/index.php?title=Window_functio
n&oldid=703074467#Hann_.28Hanning.29_window>.
[LINEAR-PREDICTION]
Wikipedia, "Linear Predictive Coding", October 2015,
<https://en.wikipedia.org/w/
index.php?title=Linear_predictive_coding&oldid=687498962>.
[LPC-SAMPLE]
Degener, J. and C. Bormann, "Autocorrelation LPC coeff
generation algorithm (Vorbis source code)", November 1994,
<https://svn.xiph.org/trunk/vorbis/lib/lpc.c>.
[Q-NOTATION]
Wikipedia, "Q (number format)", December 2015,
<https://en.wikipedia.org/w/
index.php?title=Q_%28number_format%29&oldid=697252615>.
[REPLAY-GAIN]
Parker, C. and M. Leese, "VorbisComment: Replay Gain",
June 2009,
<https://wiki.xiph.org/VorbisComment#Replay_Gain>.
[SEEKING] Pfeiffer, S., Parker, C., and G. Maxwell, "Granulepos
Encoding and How Seeking Really Works", May 2012,
<https://wiki.xiph.org/Seeking>.
[VORBIS-MAPPING]
Montgomery, C., "The Vorbis I Specification, Section 4.3.9
Output Channel Order", January 2010,
<https://www.xiph.org/vorbis/doc/
Vorbis_I_spec.html#x1-810004.3.9>.
[VORBIS-TRIM]
Montgomery, C., "The Vorbis I Specification, Appendix A:
Embedding Vorbis into an Ogg stream", November 2008,
<https://xiph.org/vorbis/doc/
Vorbis_I_spec.html#x1-132000A.2>.
[WAVE-MULTICHANNEL]
Microsoft Corporation, "Multiple Channel Audio Data and
WAVE Files", March 2007,
<https://msdn.microsoft.com/en-us/windows/hardware/
gg463006.aspx>.
Acknowledgments ๐ซถ
thanks to Ben Campbell, Joel M. Halpern, Mark Harris, Greg Maxwell, Christopher "Monty" Montgomery, Jean-Marc Valin, Stephan Wenger, and Mo Zanaty for their valuable contributions to this document ๐ Extra thanks to Andrew D'Addesio, Greg Maxwell, and Vincent Penquerc'h for their feedback based on early implementations ๐
Authors' Addresses โจ
okay bestie, this is the part where we find out who wrote the whole thing and how to reach them ๐ three legends, all with their own addresses and phone numbers ๐ซถ
Timothy B. Terriberry ๐
Timothy B. Terriberry
Mozilla Corporation
331 E. Evelyn Ave.
Mountain View, CA 94041
United States
Phone: +1 650 903-0800
Email: tterribe@xiph.org
Ron Lee ๐ฆ
Ron Lee
Voicetronix
246 Pulteney Street, Level 1
Adelaide, SA 5000
Australia
Phone: +61 8 8232 9112
Email: ron@debian.org
Ralph Giles ๐ธ
Ralph Giles
Mozilla Corporation
163 West Hastings Street
Vancouver, BC V6B 1H5
Canada
Phone: +1 778 785 1540
Email: giles@xiph.org
iykyk that the Mozilla and Xiph folks are basically the reason Opus exists, so reaching out to them is giving main character energy ๐๐ โจ
๐ฆ where this page comes from
- ietf: rfc7845 2016-04
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms