Ogg mapping for Opus
The IETF Opus codec is a low-latency audio codec optimized for both voice and general-purpose audio. See the spec for technical details.
Almost everything about this codec is either fixed or dynamically switchable, so the usual id and setup header parameters in the header packets of an Ogg encapsulation aren't useful. In particular, bitrate, frame size, mono/stereo, and coding modes are all dynamically switchable from packet to packet. A one-byte header on each data packet defines the parameters for that particular packet.
Remaining parameters we need to signal are:
- magic number for stream identification
- stream count and coupling for multichannel audio
- metadata and tags
Opus is framed in a Continuous Ogg stream.
There are two mandatory headers. The granule position of the pages containing these headers is zero.
The first Opus packet (the identification header), which uniquely identifies a stream as Opus audio, is placed alone in the first page of the logical Ogg stream. This page is marked ’beginning of stream’ in the page flags. It must begin with the 8 bytes "OpusHead".
The second Opus packet MUST contain the comment header and may span one or more pages beginning on the second page of the logical stream. However many pages it spans, the comment header packet finishes the page on which it ends. It must begin with the 8 bytes "OpusTags".
The next (first audio) packet of the logical stream MUST begin on a fresh Ogg page.
Packets are placed into Ogg pages in order until the end of stream.
The last page is marked ’end of stream’ in the page flags.
Opus packets may span page boundaries.
The granule position of pages containing Opus audio is in units of PCM audio samples at a fixed rate of 48kHz (per channel; a stereo stream’s granule position does not increment at twice the speed of a mono stream).
The granule position of a page can be used to determine the end PCM sample position of the last packet completed on that page. A page that is entirely spanned by a single packet (that completes on a subsequent page) has no granule position and the granule position is set to ’-1’.
The granule (PCM) position of the first audio page need not indicate that the stream started at position zero, however it MUST be greater than or equal to the number of samples contained in completed packets. ie. negative sample positions are not permitted, but a stream may be cropped from its beginning without rewriting the granule position of all remaining pages.
A decoder MUST reject as invalid any stream with an initial sample time of less than zero. It may defer this action until the last complete packet of the first page has been decoded.
A decoder MUST treat a zero size Ogg packet in the audio stream as if it were an Opus packet with an illegal TOC sequence.
A granule position on the final page in a stream that indicates less audio data than the final packet would normally return is used to end the stream on other than even frame boundaries. The difference between the actual available data returned and the declared amount indicates how many trailing samples to discard from the decoding process.
- Magic signature: "OpusHead" (64 bits) - Version number (8 bits unsigned): zero for this spec - Channel count 'c' (8 bits unsigned): MUST be > 0 - Pre-skip (16 bits unsigned, little endian) - Input sample rate (32 bits unsigned, little endian): informational only - Output gain (16 bits, little endian, signed Q7.8 in dB) to apply when decoding - Channel mapping family (8 bits unsigned) -- 0 = one stream: mono or L,R stereo -- 1 = channels in vorbis spec order: mono or L,R stereo or ... or FL,C,FR,RL,RR,LFE, ... -- 2..254 = reserved (treat as 255) -- 255 = no defined channel meaning If channel mapping family > 0 - Stream count 'N' (8 bits unsigned): MUST be > 0 - Two-channel stream count 'M' (8 bits unsigned): MUST satisfy M <= N, M+N <= 255 - Channel mapping (8*c bits) -- one stream index (8 bits unsigned) per channel (255 means silent throughout the file)
Some discussion is in order.
- Magic signature
The magic signature "OpusHead" allows codec identification and is human readable. Starting with 'Op' helps distinguish it from data packets, as this is an invalid TOC sequence.
The version number must always be zero for this version of the encapsulation spec. We do not plan to revise the spec, but this also acts as a null terminator for the signature bytes and helps align the rest of the fields.
- Channel count 'c'
The number of channels byte specifies the number of output channels (1...255) for this Ogg Opus stream.
This is the number of samples (at 48 kHz) to discard from the decoder output when starting playback, and also the number to subtract from a page's granpos to calculate its end-granule.
The purpose of pre-skip is to allow a time-segment of an existing Opus stream to be saved as an independent Ogg file, with single-sample time granularity, without re-encoding and without rewriting the Ogg pages except at the beginning and end. Opus is an asymptotically convergent predictive codec, so the decoded contents of each frame depend on the recent history of decoder inputs. Pre-skip can be used to provide sufficient history to the decoder so that it has already converged before the stream's output begins.
The granule corresponding to the end time of an Ogg Opus page can be determined by subtracting the pre-skip from the page's granpos value. For example, if the page's granpos is 59971, and the preskip is 11971, then the page provides output audio up to granule 48000, i.e. it completes the first second of absolute time.
When constructing cropped Ogg Opus streams, we recommend a pre-skip of at least FIXME samples to ensure complete convergence.
- Input sample rate
This is not the sample rate to use for playback of the encoded data.
Opus has a handful of coding modes, with internal sample rates of 8, 12, 16, 24, and 48 kHz. Each packet in the stream may have a different internal sample rate. Regardless of the internal sample rate, the reference decoder supports decoding any stream to any of these sample rates. The original sample rate of the encoder input is not preserved by the lossy compression.
An Ogg Opus player SHOULD select the playback sample rate according to the following procedure:
- If the hardware supports 48 kHz playback, decode at 48 kHz
- else if the hardware's highest available sample rate is a supported rate, decode at this sample rate
- else if the hardware's highest available sample rate is less than 48 kHz, decode at the next higher supported rate and resample
- else decode at 48 kHz and resample.
However, the Ogg mapping allows the encoder to pass the sample rate of the original input stream as metadata. This may be useful when the user requires the output sample rate to match the input sample rate. For example, a non-player decoder writing PCM format to disk might choose to resample the output audio back to the original input rate to reduce surprise to the user, who might reasonably expect to get back a file with the same sample rate as the one they fed to the encoder.
A value of zero indicates 'unspecified'. Implementations which do something with this field should take care to behave sanely if given crazy values (e.g. don't actually upsample the output to 10MHz) and encoders should write the actual input rate or zero.
- Output gain
This is a gain to be applied by the decoder. Virtually all players and media frameworks should apply it by default. If a player chooses to apply any volume adjustment or gain modification, such as the R128_TRACK_GAIN or a user-facing volume knob, the adjustment MUST be applied in addition to this output gain in order to achieve playback at the desired volume.
An encoder SHOULD set the output gain to zero, and instead apply any gain prior to encoding, when this is possible and does not conflict with the user's wishes. The output gain should only be nonzero when the gain is adjusted after encoding, or when the user wishes to adjust the gain for playback while preserving the ability to recover the original signal amplitude.
Note that although the output gain has enormous range (+/- 128 dB, enough to amplify inaudible sounds to the threshold of physical pain), most applications can only reasonably use a small portion of this range around zero. The large range serves in part to ensure that gain can always be losslessly transferred between OpusHead and R128_TRACK_GAIN (see below) without saturating.
- Channel mapping family
This byte indicates the order and semantic meaning of the various channels encoded in each Opus packet.
Each possible value of this byte indicates a mapping family, which defines a set of allowed numbers of channels, and the ordered set of channel names for each allowed number of channels. Currently there are three defined mapping families, although more may be added:
- Family 0 (RTP mapping)
- Allowed numbers of channels: 1 or 2
- 1 channel: monophonic (mono)
- 2 channels: stereo (left, right)
- Special mapping: this channel mapping value also indicates that the contents consists of a single Opus stream that is stereo if and only if c==2, with stream index 0 mapped to channel 0, and (if stereo) stream index 1 mapped to channel 1. When the channel mapping byte has this value, no further fields are present in OpusHead.
- Family 1 (Vorbis mapping)
- Allowed numbers of channels: 1 ... 8
- Channel meanings depend on the number of channels, see the Vorbis mapping for details.
- Family 255 (no defined channel meaning)
- Allowed numbers of channels: 1...255
- Channels are unidentified. General-purpose players SHOULD NOT attempt to play these streams, and offline decoders MAY deinterleave the output into separate PCM files, one per channel. Decoders 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.
- Family 0 (RTP mapping)
The remaining channel mapping families (2...254) are reserved. A decoder encountering a reserved mapping byte should act as though the mapping byte is 255.
An Ogg Opus player MUST play any Ogg Opus stream 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.
- Stream count 'N'
This field indicates the total number of streams so the decoder can correctly parse the packed Opus packets inside the Ogg packet.
For channel mapping family 0, this value defaults to 1, and is not coded.
A multi-channel Opus file is composed of one or more individual Opus streams, each of which produce one or two channels of decoded data. Each Ogg packet contains one Opus packet from each stream. The first N-1 Opus packets are packed using the self-delimiting framing from Appendix B of the Opus specification. The remaining Opus packet is packed using the regular, undelimited framing from Section 3 of the Opus specification. All the Opus packets in a single Ogg packet are constrained to produce the same number of decoded samples.
- Two-channel stream count 'M'
Describes the number of streams whose decoders should be configured to produce two channels. This must be no larger than the number of total streams.
For channel mapping family 0, this value defaults to c-1 (i.e., 0 for mono and 1 for stereo), and is not coded.
Each packet in an Opus stream has an internal channel count of 1 or 2, which can change from packet to packet. This is selected by the encoder depending on the bitrate and the contents being encoded. The original channel count of the encoder input is not preserved by the lossy compression.
Regardless of the internal channel count, any Opus stream may be decoded as mono (single channel) or stereo (two channels) by appropriate initialization of the decoder. The "two-channel stream count" field indicates that the first M Opus decoders should be initialized in stereo mode, and the remaining N-M decoders should be initialized in mono mode. The total number of decoded channels (M+N) must be no larger than 255, as there is no way to index more channels than that in the channel mapping.
- Channel mapping
Contains one index per output channel indicating which decoded channel should be used. If the index is less than 2*M, the output MUST be taken from decoding stream (index/2) as stereo and selecting the left channel if index is even, and the right channel if index is odd. If the index is 2*M or larger, the output MUST be taken from decoding stream (index-M) as mono. As a special case, an index of 255 means that the corresponding output channel MUST contain pure silence.
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.
The number of output channels (c) is not constrained to match the number of decoded channels (M+N). A single index MAY appear multiple times, i.e., the same decoded channel may be mapped to multiple output channels. Some decoded channels might not be assigned to any output channel, as well.
- 8 byte 'OpusTags' magic signature (64 bits) - rest follows the vorbis-comment header design used in OggVorbis (without the "framing-bit"), OggTheora, and Speex. ** Vendor string (always present) ** tag=value metadata strings (zero or more)
One new comment field is introduced for Ogg Opus:
representing the volume shift needed to normalize the track's volume. The gain is a Q7.8 fixed point number in dB, as in the OpusHead "output gain" field. This field acts similarly to the REPLAYGAIN_TRACK_GAIN field in Vorbis, although the normal volume reference is the EBU-R128 standard.
An Ogg Opus file MUST NOT have more than one such field, and if present its value MUST be an integer from -32768 to +32767 inclusive, represented in ASCII with no whitespace. If present it MUST correctly represent the R128 normalization gain (relative to the OpusHead output gain). If a player chooses to make use of the TRACK_GAIN, it MUST be applied in addition to the OpusHead output gain. If an encoder populates the TRACK_GAIN field, and the output gain is not otherwise constrained or specified, the encoder SHOULD write the R128 gain into the OpusHead output gain and write "R128_TRACK_GAIN=0". If a tool modifies the OpusHead "output gain" field, it MUST also update or remove the R128_TRACK_GAIN comment field.
There is no comment field corresponding to Replaygain's ALBUM_GAIN; that information should instead be stored in the OpusHead "output gain" field.
To avoid confusion with multiple normalization schemes, an OpusTags packet SHOULD NOT contain any of the REPLAYGAIN_TRACK_GAIN, REPLAYGAIN_TRACK_PEAK, REPLAYGAIN_ALBUM_GAIN, or REPLAYGAIN_ALBUM_PEAK fields.
Other implementation notes
When seeking within an Ogg Opus stream, the decoder should start decoding (and discarding the output) at least FIXME samples prior to the seek point in order to ensure that the output audio is correct at the seek point.
Valid Opus packets can be arbitrarily large due to padding (even larger than 2^64 bytes!). These packets may be spread over a similarly enormous number of Ogg pages. Decoders SHOULD avoid attempting to allocate excessive amounts of memory when presented with a very large packet. The presence of an extremely large packet in the stream could indicate a potential memory exhaustion attack or stream corruption. Decoders should reject a packet that is too large to process, and print a warning message. In an Ogg Opus stream, the largest possible valid packet that does not use padding has a size of 15630988 bytes (14.9 MiB) and can span up to 61298 Ogg Pages, all but one of which will have a granulepos of -1. (This is of course a very extreme packet, consisting of 255 channels, each containing 120ms of audio encoded as 2.5ms frames, each frame using the maximum possible number of bytes and stored in the least efficient manner allowed.) FIXME: should we make an actual recommendation on behavior for decoders running on modern desktops?
- Planned test vectors for OggOpus
- Opus test vectors