-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrfc7845.xml
1768 lines (1512 loc) · 77.5 KB
/
rfc7845.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet type='text/xsl' href='rfc2629.xslt' ?>
<!DOCTYPE rfc SYSTEM "rfc2629.dtd" [
<!ENTITY RFC2119 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.2119.xml">
<!ENTITY RFC3533 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.3533.xml">
<!ENTITY RFC3629 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.3629.xml">
<!ENTITY RFC5226 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.5226.xml">
<!ENTITY RFC5334 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.5334.xml">
<!ENTITY RFC6381 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6381.xml">
<!ENTITY RFC6716 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.6716.xml">
<!ENTITY RFC4732 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.4732.xml">
<!ENTITY RFC7587 SYSTEM "https://xml2rfc.ietf.org/public/rfc/bibxml/reference.RFC.7587.xml">
]>
<rfc submissionType="IETF" number="7845" category="std" updates="5334" consensus="yes">
<!-- Generated by id2xml 1.4.4 on 2019-02-23T10:34:17Z -->
<?rfc compact="yes"?>
<?rfc text-list-symbols="o*+-"?>
<?rfc subcompact="no"?>
<?rfc sortrefs="no"?>
<?rfc symrefs="yes"?>
<?rfc strict="yes"?>
<?rfc toc="yes"?>
<front>
<title abbrev="Ogg Opus">Ogg Encapsulation for the Opus Audio Codec</title>
<author fullname="Timothy B. Terriberry" initials="T." surname="Terriberry">
<organization>Mozilla Corporation</organization>
<address><postal><street>331 E. Evelyn Ave.</street>
<street>Mountain View, CA 94041</street>
<street>United States</street>
</postal>
<phone>+1 650 903-0800</phone>
<email>[email protected]</email>
</address>
</author>
<author fullname="Ron Lee" initials="R." surname="Lee">
<organization>Voicetronix</organization>
<address><postal><street>246 Pulteney Street, Level 1</street>
<street>Adelaide, SA 5000</street>
<street>Australia</street>
</postal>
<phone>+61 8 8232 9112</phone>
<email>[email protected]</email>
</address>
</author>
<author fullname="Ralph Giles" initials="R." surname="Giles">
<organization>Mozilla Corporation</organization>
<address><postal><street>163 West Hastings Street</street>
<street>Vancouver, BC V6B 1H5</street>
<street>Canada</street>
</postal>
<phone>+1 778 785 1540</phone>
<email>[email protected]</email>
</address>
</author>
<date month="April" year="2016"/>
<abstract><t>
This document defines the Ogg encapsulation for the Opus interactive
speech and audio codec. This allows data encoded in the Opus format
to be stored in an Ogg logical bitstream.</t>
</abstract>
</front>
<middle>
<section title="Introduction" anchor="section-1"><t>
The IETF Opus codec is a low-latency audio codec optimized for both
voice and general-purpose audio. See <xref target="RFC6716"/> for technical
details. This document defines the encapsulation of Opus in a
continuous, logical Ogg bitstream <xref target="RFC3533"/>. Ogg encapsulation
provides Opus with a long-term storage format supporting all of the
essential features, including metadata, fast and accurate seeking,
corruption detection, recapture after errors, low overhead, and the
ability to multiplex Opus with other codecs (including video) with
minimal buffering. It also provides a live streamable format capable
of delivery over a reliable stream-oriented transport, without
requiring all the data (or even the total length of the data)
up-front, in a form that is identical to the on-disk storage format.</t>
<t>
Ogg bitstreams are made up of a series of "pages", each of which
contains data from one or more "packets". Pages are the fundamental
unit of multiplexing in an Ogg stream. Each page is associated with
a particular logical stream and contains a capture pattern and
checksum, flags to mark the beginning and end of the logical stream,
and a "granule position" that represents an absolute position in the
stream, to aid seeking. A single page can contain 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 (allowing packets much larger than would fit on a single page).
Each page contains "lacing values" that indicate how the data is
partitioned into packets, allowing a demultiplexer (demuxer) to
recover the packet boundaries without examining the encoded data. A
packet is said to "complete" on a page when the page contains the
final lacing value corresponding to that packet.</t>
<t>
This encapsulation defines the contents of the packet data, including
the necessary headers, the organization of those packets into a
logical stream, and the interpretation of the codec-specific granule
position field. It does not attempt to describe or specify the
existing Ogg container format. Readers unfamiliar with the basic
concepts mentioned above are encouraged to review the details in
<xref target="RFC3533"/>.</t>
</section>
<section title="Terminology" anchor="section-2"><t>
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
<xref target="RFC2119"/>.</t>
</section>
<section title="Packet Organization" anchor="section-3"><t>
An Ogg Opus stream is organized as follows (see Figure 1 for an
example).</t>
<figure title="Example Packet Organization for a Logical Ogg Opus Stream" anchor="ref-example-packet-organization-for-a-logical-ogg-opus-stream"><artwork><![CDATA[
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'
]]></artwork>
</figure>
<t>
There are two mandatory header packets. The first packet in the
logical Ogg bitstream MUST contain the identification (ID) header,
which uniquely identifies a stream as Opus audio. The format of this
header is defined in <xref target="section-5.1"/>. It is placed alone (without any
other packet data) on the first page of the logical Ogg bitstream and
completes on that page. This page has its 'beginning of stream' flag
set.</t>
<t>
The second packet in the logical Ogg bitstream MUST contain the
comment header, which contains user-supplied metadata. The format of
this header is defined in <xref target="section-5.2"/>. It MAY span multiple 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 completes.</t>
<t>
All subsequent pages are audio data pages, and the Ogg packets they
contain are audio data packets. Each audio data packet contains one
Opus packet for each of N different streams, where N is typically one
for mono or stereo, but MAY be greater than one for multichannel
audio. The value N is specified in the ID header (see
<xref target="section-5.1.1"/>), and is fixed over the entire length of the logical
Ogg bitstream.</t>
<t>
The first (N - 1) Opus packets, if any, are packed one after another
into the Ogg packet, using the self-delimiting framing from
Appendix B of <xref target="RFC6716"/>. The remaining Opus packet is packed at the
end of the Ogg packet using the regular, undelimited framing from
Section 3 of <xref target="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.</t>
<t>
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 <xref target="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 referred to as the configuration
of an Opus packet.</t>
<t>
Packets are 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 (indicating the first
audio data packet is continued 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:</t>
<t><list style="symbols"><t>the previous page with packet data does not end in a continued
packet (does not end with a lacing value of 255) OR</t>
<t>the page sequence numbers are not consecutive,</t>
</list>
</t>
<t>
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 <xref target="RFC6716"/>.</t>
<t>
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 encounter such streams, possibly as the result of a
transfer that did not complete or of corruption. If a packet</t>
<t>
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:</t>
<t><list style="symbols"><t>the next page with packet data does not have the 'continued
packet' flag set, OR</t>
<t>there is no next page with packet data, OR</t>
<t>the page sequence numbers are not consecutive,</t>
</list>
</t>
<t>
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'.</t>
</section>
<section title="Granule Position" anchor="section-4"><t>
The granule position MUST be zero for the ID header page and the page
where the comment header completes. That is, 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.</t>
<t>
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 <xref target="section-4.5"/>.</t>
<t>
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 is set to the special value '-1' in two's complement.</t>
<t>
The granule position of an audio data 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 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.</t>
<t>
The duration of an Opus packet as defined in <xref target="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) 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.</t>
<t>
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.</t>
<section title="Repairing Gaps in Real-Time Streams" anchor="section-4.1"><t>
In order to support capturing a real-time stream that has lost or not
transmitted packets, a multiplexer (muxer) SHOULD emit packets that
explicitly request the use of Packet Loss Concealment (PLC) in place
of the missing packets. Implementations that fail to do so still
MUST NOT increment the granule position for a page by anything other
than the number of samples contained in packets that actually
complete on that page.</t>
<t>
Only gaps that are a multiple of 2.5 ms are repairable, as these are
the only durations that can be created by packet loss or
discontinuous transmission. Muxers need not handle other gap sizes.
Creating the necessary packets involves synthesizing a TOC byte
(defined in Section 3.1 of <xref target="RFC6716"/>) -- and whatever additional
internal framing is needed -- to indicate the packet duration for
each stream. The actual length of each missing Opus frame inside the
packet is zero bytes, as defined in Section 3.2.1 of <xref target="RFC6716"/>.</t>
<t>
Zero-byte frames MAY be packed into packets using any of codes 0, 1,
2, or 3. When successive frames have the same configuration, the
higher code packings reduce overhead. Likewise, if the TOC
configuration matches, the muxer MAY further combine the empty frames
with previous or subsequent nonzero-length frames (using code 2 or
variable bitrate (VBR) code 3).</t>
<t>
<xref target="RFC6716"/> does not impose any requirements on the PLC, but this
section outlines 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 <xref target="RFC6716"/>.</t>
<t>
When a previous packet is available, keeping the audio bandwidth and
channel count the same allows the PLC to provide maximum continuity
in the concealment data it generates. However, if the size of the
gap is not a multiple of the most recent frame size, then 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.</t>
<t>
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 requires 4 bytes (plus an extra byte of Ogg
lacing overhead), but allows the PLC to 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.</t>
<t>
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 to allow the PLC to function for
as long as possible.</t>
<t>
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, followed by 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 requires 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 over a naive, low-quality solution.</t>
<t>
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, to ensure that any PLC implementation that does try to
migrate state between the modes will be able to preserve all of the
available audio bandwidth.</t>
</section>
<section title="Pre-skip" anchor="section-4.2"><t>
There is some amount of latency introduced during the decoding
process, to allow for overlap in the CELT mode, stereo mixing in the
SILK mode, and resampling. The encoder might have introduced
additional latency through its own resampling and analysis (though
the exact amount is not specified). Therefore, the first few samples
produced by the decoder do not correspond to real input audio, but
are instead composed of padding inserted by the encoder to compensate
for this latency. These samples need to 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. However, a player will want to skip these samples
after decoding them.</t>
<t>
A 'pre-skip' field in the ID header (see <xref target="section-5.1"/>) signals the
number of samples that SHOULD be skipped (decoded but discarded) at
the beginning of the stream, though some specific applications might
have a reason for looking at that data. 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. These samples are not valid audio.</t>
<t>
For example, if the first Opus frame uses the CELT mode, it will
always produce 120 samples of windowed overlap-add data. However,
the overlap data is initially all zeros (since there is no prior
frame), meaning this cannot, in general, accurately represent the
original audio. The SILK mode requires additional delay to account
for its analysis and resampling latency. The encoder delays the
original audio to avoid this problem.</t>
<t>
The 'pre-skip' field MAY also be used to perform sample-accurate
cropping of already encoded streams. In this case, a value of at
least 3840 samples (80 ms) provides sufficient history to the decoder
that it will have converged before the stream's output begins.</t>
</section>
<section title="PCM Sample Position" anchor="section-4.3"><t>
The PCM sample position is determined from the granule position using
the following formula:</t>
<t><list hangIndent="7" style="hanging"><t>
'PCM sample position' = 'granule position' - 'pre-skip'</t>
</list>
</t>
<t>
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.</t>
<t>
This can be converted into a playback time using the following
formula:</t>
<figure><artwork><![CDATA[
'PCM sample position'
'playback time' = ---------------------
48000.0
]]></artwork>
</figure>
<t>
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.</t>
<t>
Vorbis streams use a granule position smaller than the number of
audio samples contained in the first audio data page to indicate that
some of those samples are trimmed from the output (see
<xref target="VORBIS-TRIM"/>). However, to do so, Vorbis requires that the first
audio data 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 might introduce more than a single
packet's worth of latency, and since very large packets in streams
with a very large number of channels might not fit on a single page.</t>
</section>
<section title="End Trimming" anchor="section-4.4"><t>
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 data page
with completed packets is used to make this determination, or '0' is
used if there were no previous audio data 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 no larger than the number decoded from
the last packet.</t>
</section>
<section title="Restrictions on the Initial Granule Position" anchor="section-4.5"><t>
The granule position of the first audio data 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 or a live stream to be joined 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'. Synchronization when multiplexing with other
logical streams still uses the PCM sample position relative to '0' to
compute sample times. 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.</t>
<t>
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 are non-negative. An
implementation MUST treat any stream as invalid if the granule
position is smaller than the number of samples contained 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
action until it decodes the last packet completed on that page.</t>
<t>
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. This would indicate that there are more samples
to be skipped 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,
then a demuxer MUST use an initial granule position of '0', and can
work forwards from '0' to timestamp individual packets. If the
granule position is larger than the number of decoded samples
available, then the demuxer MUST still work backwards as described
above, even if the 'end of stream' flag is set, to determine the
initial granule position, and thus the initial PCM sample position.
Both of these will be greater than '0' in this case.</t>
</section>
<section title="Seeking and Pre-roll" anchor="section-4.6"><t>
Seeking in Ogg files is best performed using a bisection search for a
page whose granule position corresponds to a PCM position at or
before the seek target. With appropriately weighted bisection,
accurate seeking can be performed in just one or two bisections on
average, even in multi-gigabyte files. See <xref target="SEEKING"/> for an example
of general implementation guidance.</t>
<t>
When seeking within an Ogg Opus stream, an implementation SHOULD
start decoding (and discarding the output) at least 3840 samples
(80 ms) prior to the seek target in order to ensure that the output
audio is correct by the time it reaches the seek target. This
"pre-roll" is separate from, and unrelated to, the pre-skip used at
the beginning of the stream. If the point 80 ms prior to the seek
target comes before the initial PCM sample position, an
implementation SHOULD start decoding from the beginning of the
stream, applying pre-skip as normal, regardless of whether the pre-
skip is larger or smaller than 80 ms, and then continue to discard
samples to reach the seek target (if any).</t>
</section>
</section>
<section title="Header Packets" anchor="section-5"><t>
An Ogg Opus logical stream contains exactly two mandatory header
packets: an identification header and a comment header.</t>
<section title="Identification Header" anchor="section-5.1"><figure title="ID Header Packet" anchor="ref-id-header-packet"><artwork><![CDATA[
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... :
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
<t>
The fields in the identification (ID) header have the following
meaning:</t>
<t><list style="numbers"><t>Magic Signature:<vspace blankLines="1"/>
This is an 8-octet (64-bit) field that allows codec
identification and is human readable. It contains, in order, the
magic numbers:
<vspace blankLines="1"/>
0x4F 'O'
<vspace blankLines="1"/>
0x70 'p'
<vspace blankLines="1"/>
0x75 'u'
<vspace blankLines="1"/>
0x73 's'
<vspace blankLines="1"/>
0x48 'H'
<vspace blankLines="1"/>
0x65 'e'
<vspace blankLines="1"/>
0x61 'a'
<vspace blankLines="1"/>
0x64 'd'
<vspace blankLines="1"/>
Starting with "Op" helps distinguish it from audio data packets,
as this is an invalid TOC sequence.
</t>
<t>Version (8 bits, unsigned):<vspace blankLines="1"/>
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
that of a recognized specification as backwards compatible with
that specification. That is, the version number can be 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, 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 '16' or
greater is incompatible. The initial version '1' was chosen to
keep implementations from relying on this octet as a null
terminator for the "OpusHead" string.
</t>
<t>Output Channel Count 'C' (8 bits, unsigned):<vspace blankLines="1"/>
This is the number of output channels. This might be different
than the number of encoded channels, which can change on a
packet-by-packet basis. This value MUST NOT be zero. The
maximum allowable value depends on the channel mapping family,
and might be as large as 255. See <xref target="section-5.1.1"/> for details.
</t>
<t>Pre-skip (16 bits, unsigned, little endian):<vspace blankLines="1"/>
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 cropping the beginning of existing Ogg
Opus streams, a pre-skip of at least 3,840 samples (80 ms) is
RECOMMENDED to ensure complete convergence in the decoder.
</t>
<t>Input Sample Rate (32 bits, unsigned, little endian):<vspace blankLines="1"/>
This is the sample rate of the original input (before encoding),
in Hz. This field is _not_ the sample rate to use for playback
of the encoded data.
<vspace blankLines="1"/>
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. 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 audio passed
to the encoder is not preserved by the lossy compression.
<vspace blankLines="1"/>
An Ogg Opus player SHOULD select the playback sample rate
according to the following procedure:
<list style="numbers"><t>If the hardware supports 48 kHz playback, decode at 48 kHz.</t>
<t>Otherwise, if the hardware's highest available sample rate is
a supported rate, decode at this sample rate.</t>
<t>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.</t>
<t>Otherwise, decode at 48 kHz and resample.<vspace blankLines="1"/>
However, the 'input sample rate' field allows the muxer to pass
the sample rate of the original input stream as metadata. This
is useful when the user requires the output sample rate to match
the input sample rate. For example, when not playing the output,
an implementation writing PCM format samples to disk might choose
to resample the audio back to the original input sample rate to
reduce surprise to the user, who might reasonably expect to get
back a file with the same sample rate.
<vspace blankLines="1"/>
A value of zero indicates "unspecified". Muxers SHOULD write the
actual input sample rate or zero, but implementations that do
something with this field SHOULD take care to behave sanely if
given crazy values (e.g., do not actually upsample the output to
10 MHz if requested). 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.
</t>
</list>
</t>
<t>Output Gain (16 bits, signed, little endian):<vspace blankLines="1"/>
This is a gain to be applied when decoding. It is 20*log10 of
the factor by which to scale the decoder output to achieve the
desired playback volume, stored in a 16-bit, signed, two's
complement fixed-point value with 8 fractional bits (i.e.,
Q7.8 <xref target="Q-NOTATION"/>).
<list style="hanging" hangIndent="10"><t hangText="To apply the gain, an implementation could use the following:">
<vspace blankLines="1"/>
sample *= pow(10, output_gain/(20.0*256))
<vspace blankLines="1"/>
where 'output_gain' is the raw 16-bit value from the header.
<vspace blankLines="1"/>
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 (see <xref target="section-5.2"/>), the
adjustment MUST be applied in addition to this output gain in
order to achieve playback at the normalized volume.
<vspace blankLines="1"/>
A muxer SHOULD set this field to zero, and instead apply any gain
prior to encoding, when this is possible and does not conflict
with the user's wishes. A nonzero output gain indicates the gain
was adjusted after encoding, or that a user wished to adjust the
gain for playback while preserving the ability to recover the
original signal amplitude.
<vspace blankLines="1"/>
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 gain tags (see below) without saturating.
</t>
</list>
</t>
<t>Channel Mapping Family (8 bits, unsigned):<vspace blankLines="1"/>
This octet indicates the order and semantic meaning of the output
channels.
<vspace blankLines="1"/>
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 channel count. The
details are described in <xref target="section-5.1.1"/>.
</t>
<t>Channel Mapping Table:<vspace blankLines="1"/>
This table defines the mapping from encoded streams to output
channels. Its contents are specified in <xref target="section-5.1.1"/>.
</t>
</list>
</t>
<t>
All fields in the ID headers 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 does not have
enough data for these fields, even if it contain a valid 'magic
signature'. Future versions of this specification, even backwards-
compatible versions, might include additional fields in 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 for
containing additional data not specified here, provided it still
completes on the first page.</t>
<section title="Channel Mapping" anchor="section-5.1.1"><t>
An Ogg Opus stream allows mapping one number of Opus streams (N) to a
possibly larger number of decoded channels (M + N) to yet another
number of output channels (C), which might be larger or smaller than
the number of decoded channels. The order and meaning of these
channels are defined by a channel mapping, which consists of the
'channel mapping family' octet and, for channel mapping families
other than family 0, a 'channel mapping table', as illustrated
in Figure 3.</t>
<figure title="Channel Mapping Table" anchor="ref-channel-mapping-table"><artwork><![CDATA[
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... :
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
]]></artwork>
</figure>
<t>
The fields in the channel mapping table have the following meaning:</t>
<t><list style="numbers"><t>Stream Count 'N' (8 bits, unsigned):<vspace blankLines="1"/>
This is the total number of streams encoded in each Ogg packet.
This value is necessary to correctly parse the packed Opus
packets inside an Ogg packet, as described in <xref target="section-3"/>. This
value MUST NOT be zero, as without at least one Opus packet with
a valid TOC sequence, a demuxer cannot recover the duration of an
Ogg packet.
<vspace blankLines="1"/>
For channel mapping family 0, this value defaults to 1, and is
not coded.
</t>
<t>Coupled Stream Count 'M' (8 bits, unsigned):<vspace blankLines="1"/>
This is the number of streams whose decoders are to be configured
to produce two channels (stereo). This MUST be no larger than
the total number of streams, N.
<vspace blankLines="1"/>
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 audio being
encoded. The original channel count of the audio passed to the
encoder is not necessarily preserved by the lossy compression.
<vspace blankLines="1"/>
Regardless of the internal channel count, any Opus stream can be
decoded as mono (a single channel) or stereo (two channels) by
appropriate initialization of the decoder. The 'coupled stream
count' field indicates that the decoders for the first M Opus
streams are to be initialized for stereo (two-channel) output,
and the remaining (N - M) decoders are to be initialized for mono
(a single channel) only. 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.
<vspace blankLines="1"/>
For channel mapping family 0, this value defaults to (C - 1)
(i.e., 0 for mono and 1 for stereo), and is not coded.
</t>
<t>Channel Mapping (8*C bits):<vspace blankLines="1"/>
This contains one octet per output channel, indicating which
decoded channel is to be 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 and 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.
<vspace blankLines="1"/>
The number of output channels, C, is not constrained to match the
number of decoded channels (M + N). A single index value MAY
appear multiple times, i.e., the same decoded channel might be
mapped to multiple output channels. Some decoded channels might
not be assigned to any output channel, as well.
<vspace blankLines="1"/>
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.
</t>
</list>
</t>
<t>
After producing the output channels, the channel mapping family
determines the semantic meaning of each one. There are three defined
mapping families in this specification.</t>
<section title="Channel Mapping Family 0" anchor="section-5.1.1.1"><t>
Allowed numbers of channels: 1 or 2. RTP mapping. This is the same
channel interpretation as <xref target="RFC7587"/>.</t>
<t><list style="symbols"><t>1 channel: monophonic (mono).</t>
<t>2 channels: stereo (left, right).</t>
</list>
</t>
<t>
Special mapping: This channel mapping family also indicates that the
content consists of 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.</t>
</section>
<section title="Channel Mapping Family 1" anchor="section-5.1.1.2"><t>
Allowed numbers of channels: 1...8. Vorbis channel order (see
below).</t>
<t>
Each channel is assigned to a speaker location in a conventional
surround arrangement. Specific locations depend on the number of
channels, and are given below in order of the corresponding channel
indices.</t>
<t><list style="symbols"><t>1 channel: monophonic (mono).</t>
<t>2 channels: stereo (left, right).</t>
<t>3 channels: linear surround (left, center, right).</t>
<t>4 channels: quadraphonic (front left, front right, rear left,
rear right).</t>
<t>5 channels: 5.0 surround (front left, front center, front right,
rear left, rear right).</t>
<t>6 channels: 5.1 surround (front left, front center, front right,
rear left, rear right, LFE).</t>
<t>7 channels: 6.1 surround (front left, front center, front right,
side left, side right, rear center, LFE).</t>
<t>8 channels: 7.1 surround (front left, front center, front right,
side left, side right, rear left, rear right, LFE).</t>
</list>
</t>
<t>
This set of surround options and speaker location orderings is the
same as those used by the Vorbis codec <xref target="VORBIS-MAPPING"/>. The
ordering is different from the one used by the WAVE
<xref target="WAVE-MULTICHANNEL"/> and Free Lossless Audio Codec (FLAC) <xref target="FLAC"/>
formats, so correct ordering requires permutation of 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.</t>
</section>
<section title="Channel Mapping Family 255" anchor="section-5.1.1.3"><t>
Allowed numbers of channels: 1...255. No defined channel meaning.</t>
<t>
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.</t>
</section>
<section title="Undefined Channel Mappings" anchor="section-5.1.1.4"><t>
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.</t>
</section>
<section title="Downmixing" anchor="section-5.1.1.5"><t>
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.</t>
<t>
Implementations MAY use the matrices in Figures 4 through 9 to
implement downmixing from multichannel files using channel mapping
family 1 (<xref target="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.</t>
<t>
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.</t>
<t><list style="hanging" hangIndent="68"><t hangText="L output = ( 0.585786 * left + 0.414214 * center">
)
<vspace blankLines="0"/>
R output = ( 0.414214 * center + 0.585786 * right )
</t>
</list>
</t>
<t>
Exact coefficient values are 1 and 1/sqrt(2), multiplied by
1/(1 + 1/sqrt(2)) for normalization.</t>
<t><list style="empty" hangIndent="15">
<t><list style="hanging" hangIndent="4"><t hangText="Figure 4: Stereo Downmix Matrix for the">
<vspace blankLines="0"/>
Linear Surround Channel Mapping
</t>
</list>
</t>
</list>
</t>
<figure><artwork><![CDATA[
/ \ / \ / FL \
| L output | | 0.422650 0.000000 0.366025 0.211325 | | FR |
| R output | = | 0.000000 0.422650 0.211325 0.366025 | | RL |
\ / \ / \ RR /
]]></artwork>
</figure>
<t>
Exact coefficient values are 1, sqrt(3)/2 and 1/2, multiplied by
1/(1 + sqrt(3)/2 + 1/2) for normalization.</t>
<t><list style="hanging" hangIndent="-1"><t hangText="Figure 5: Stereo Downmix Matrix for the Quadraphonic Channel Mapping">
<vspace blankLines="0"/>
</t>
</list>
</t>