Difference between revisions of "OggOpus"
(→Ogg Mapping for Opus: mime-type and filename extension)
|Line 10:||Line 10:|
* The stream count and coupling for multichannel audio, and
* The stream count and coupling for multichannel audio, and
* Any metadata or tags.
* Any metadata or tags.
=== Packet Organization ===
=== Packet Organization ===
Revision as of 15:40, 23 May 2012
Ogg Mapping for Opus
The IETF Opus codec is a low-latency audio codec optimized for both voice and general-purpose audio. See the Opus Specification for technical details.
Almost everything about Opus is either fixed or dynamically switchable, so most of the usual ID and setup header parameters in the header packets of an Ogg encapsulation aren't needed. In particular, bitrate, packet duration, mono/stereo flags, and coding modes are all dynamically switchable from packet to packet. The first one or two bytes in each data packet, the start of the 'TOC sequence' that defines the layout of the packet, specifies all of these parameters for that particular packet. See Section 3 of the Opus Specification for the exact format of the TOC sequence.
The remaining parameters that must be signaled are
- The magic number for stream identification,
- The stream count and coupling for multichannel audio, and
- Any metadata or tags.
The recommended mime-type for Ogg Opus files is audio/ogg, defined in RFC 5334.
If more specificity is desired, one can distinguish Opus files as 'audio/ogg; codecs=opus'.
The recommended filename extension for Ogg Opus files is .opus.
Opus is framed in a continuous logical Ogg stream.
There are two mandatory headers. The granule position of the pages containing these headers MUST be zero.
The first packet in the logical Ogg stream MUST contain the identification header, which uniquely identifies a stream as Opus audio. It MUST begin with the 8 bytes "OpusHead". It MUST be placed alone in the first page of the logical Ogg stream. This page MUST have the ’beginning of stream’ flag set.
The second Opus packet MUST contain the comment header. It must begin with the 8 bytes "OpusTags". It MAY span one or more pages, beginning on the second page of the logical stream. However many pages it spans, the comment header packet MUST finish the page on which it ends.
All subsequent pages are audio data pages and the packets they contain are audio data packets. The first audio page SHOULD NOT have the 'continued packet' flag set (which would indicate the first audio packet is continued from a previous page). Packets MUST be placed into Ogg pages in order until the end of stream. Audio packets MAY span page boundaries. A decoder MUST treat a zero-byte audio packet as if it were an Opus packet with an illegal TOC sequence. The last page SHOULD have the 'end of stream' flag set, but implementations should be prepared to deal with truncated streams which do not have a page marked 'end of stream'. The final packet SHOULD complete on the last page, i.e., the final lacing value should be less than 255. There MUST NOT be any more pages in an Opus logical stream after a page marked 'end of stream'.
The granule position of an audio 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. A page that is entirely spanned by a single packet (that completes on a subsequent page) has no granule position, and the granule position field MUST be set to the special value ’-1’ in two's complement.
The granule position of an audio page is in units of PCM audio samples at a fixed rate of 48 kHz (per channel; a stereo stream’s granule position does not increment at twice the speed of a mono stream). It is possible to run a decoder at other sampling rates, but the format and this specification always count samples assuming a 48 kHz decoding rate.
The duration of an Opus packet may 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 these TOC sequences to work backwards or forwards from a packet with a known granule position (i.e., the last packet completed on some page) in order to 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. There must not be any gaps. In order to support capturing a stream that uses discontinuous transmission (DTX), an encoder SHOULD emit packets that explicitly request the use of Packet Loss Concealment (PLC) (i.e., with a frame length of 0, as defined in Section 3.2.1 of the Opus Specification) in place of the packets that were not transmitted.
There is some amount of latency introduced during the decoding process, to allow for overlap in the MDCT modes, stereo mixing in the LP modes, and resampling, and the encoder will introduce even more latency (though the exact amount is not specified). Therefore the first few samples produced by the decoder do not correspond to any real, input audio, but are instead composed of padding inserted by the encoder to compensate for this latency. These samples must be stored and decoded, as Opus is an asymptotically convergent predictive codec, meaning the decoded contents of each frame depend on the recent history of decoder inputs. A 'pre-skip' field in the ID header signals the number of samples which should be skipped at the beginning of the stream. This provides sufficient history to the decoder so that it has already converged before the stream's output begins. It may also be used to perform sample-accurate cropping of existing encoded streams. This 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.
The PCM sample position is determined from the granule position using the formula
'PCM sample position' = 'granule position' - 'pre-skip' .
For example, if the granule position of the first page is 59971, and the pre-skip is 11971, then the PCM sample position of the last decoded sample from the first page is 48000. This may be converted into a playback time using the 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, and 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 contained in the first page to indicate that some of those samples must be trimmed from the output. However, to do so it requires that the first page contains exactly two packets, in order to allow the decoder to perform PCM position adjustments before needing to return any PCM data. Opus uses the pre-skip mechanism for this purpose instead, since the encoder may introduce more than a single packet's worth of latency, and since very large packets in streams with a very large number of channels may not fit on a single page.
The page with the 'end of stream' flag set MAY have a granule position that indicates the page contains less audio data than would normally be returned by decoding up through the final packet. This is used to end the stream somewhere other than an even frame boundary. The granule position of the most recent audio page with completed packets is used to make this determination, or '0' is used if there were no previous audio pages with a completed packet. The difference between these granule positions indicates how many samples to keep after decoding the packets that completed on the final page. The remaining samples are discarded. The number of discarded samples SHOULD be smaller than the number decoded from the last packet.
The granule position of the first audio page with a completed packet MAY be larger than the number of samples contained 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 number of samples allows the beginning of a stream to be cropped without rewriting the granule position of all the remaining pages. This means that the PCM sample position just before the first sample to be played may be larger than '0', but the PCM sample position relative to '0' should still be used for the purposes of synchronization when multiplexing with other logical streams. This does not affect the behavior of pre-skip: exactly 'pre-skip' samples should be skipped from the beginning of the decoded output, even if the initial PCM sample position is greater than zero.
On the other hand, a granule position that is smaller than the number of decoded samples prevents a demuxer from working backwards to assign each packet or each individual sample a valid granule position, since granule positions must be non-negative. A decoder MUST reject as invalid any stream where the granule position is smaller than the number of samples contained in packets that complete on the first page with a completed packet, unless that page has the 'end of stream' flag set. It MAY defer this action until it decodes the last packet completed on that page. If that page has the 'end of stream' flag set, a demuxer can work forwards from the granule position '0', but MUST reject as invalid any stream where the granule position is smaller than the 'pre-skip' amount. This would indicate that more samples should be skipped from the initial decoded output than exist in the stream.
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 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | original input sample rate in Hz | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | output gain Q7.8 in dB | channel map | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ : | | : optional channel mapping table... : | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Brief description of each field:
- Magic signature: "OpusHead" (64 bits) - Version number (8 bits unsigned): 0x01 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)
Detailed definition of each field:
- 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 '1' for this version of the encapsulation specification.
Implementations SHOULD treat streams where the upper four bits of the version number match a recognized specification as backwards-compatible with that specification. That is, the version number can be considered split into "major" and "minor" version sub-fields, with changes to the "minor" sub-field in the lower four bits signaling compatible changes. For example, a decoder implementing this specification SHOULD accept any stream with a version number 15 or less, and SHOULD assume any stream with a version number 16 or greater is incompatible. The initial version '1' was chosen to keep implementations from relying on this byte as a null terminator for the OpusHead string.
- 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 granule position to calculate its PCM sample position.
When constructing cropped Ogg Opus streams, a pre-skip of at least 3840 samples (80 ms) is RECOMMENDED 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 audio bandwidths of 4, 6, 8, 12, and 20 kHz. Each packet in the stream may have a different audio bandwidth. Regardless of 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 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 'input sample rate' field 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'. Encoders SHOULD write the actual input rate or zero, but decoder 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 10 MHz if requested).
- 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.
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.
The gain is the 20 log10 ratio of output to input sample values to be applied to the decoder output. E.g.
sample *= pow(10, header.gain/(20.*256)) where header.gain is the raw 16 bit Q7.8 value from the header.
- 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 channel order)
- 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.
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 MUST be constrained to produce the same number of decoded samples. A decoder SHOULD treat any Opus packet whose duration is different from that of the first Opus packet in an Ogg packet as if it were an Opus packet with an illegal TOC sequence.
- 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 (a 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) - The remaining data follows the vorbis-comment header design used in OggVorbis (without the "framing-bit"), OggTheora, and Speex: * Vendor string (always present). ** 4-byte little-endian length field, followed by length bytes of UTF-8 vendor string. * TAG=value metadata strings (zero or more). ** 4-byte little-endian string count. ** Count strings consisting of 4-byte little-endian length and length bytes of UTF-8 string in "tag=value" form.
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 is similar 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 3840 samples (80 ms) prior to the seek point in order to ensure that the output audio is correct at the seek point.
Technically valid Opus packets can be arbitrarily large due to the padding format, although the amount of non-padding data they can contain is bounded. These packets may be spread over a similarly enormous number of Ogg pages. Encoders SHOULD use no more padding than required to make a variable bitrate (VBR) stream constant bitrate (CBR). 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 (61,298*N - 2) bytes, or about 60 kB per Opus stream. With 255 streams, this is 15,630,988 bytes (14.9 MB) and can span up to 61,298 Ogg pages, all but one of which will have a granulepos of -1. This is of course a very extreme packet, consisting of 255 streams, each containing 120 ms of audio encoded as 2.5 ms frames, each frame using the maximum possible number of bytes (1275) and stored in the least efficient manner allowed (a VBR code 3 Opus packet). Even in such a packet, most of the data will be zeros, as 2.5 ms frames, which are required to run in the MDCT mode, cannot actually use all 1275 bytes. The largest packet consisting entirely of useful data is (15,326*N - 2) bytes, or about 15 kB per stream. This corresponds to 120 ms of audio encoded as 10 ms frames in either LP or Hybrid mode, but at a data rate of over 1 Mbps, which makes little sense for the quality achieved. A more reasonable limit is (7,664*N - 2) bytes, or about 7.5 kB per stream. This corresponds to 120 ms of audio encoded as 20 ms stereo MDCT-mode frames, with a total bitrate just under 511 kbps (not counting the Ogg encapsulation overhead). With N=8, the maximum useful number of streams for the channel meanings currently defined by mapping family 1, this gives a maximum packet size of 61,310 bytes, or just under 60 kB. This is still quite conservative, as it assumes each output channel is taken from one decoded channel of a stereo packet. An implementation could reasonably choose any of these numbers for its internal limits.
- Planned test vectors for OggOpus
- Opus test vectors