RFC 8251

Updates to the Opus Audio Codec

πŸ“… published October 2017, from ietf

RFC 8251 β€” Updates to the Opus Audio Codec πŸŽ€βœ¨

okay bestie, let's get into it πŸ’– This one is RFC 8251, titled Updates to the Opus Audio Codec. It came out in October 2017 and it's on the Standards Track πŸ‘‘. The authors are JM. Valin (Mozilla Corporation) and K. Vos (vocTone). It is an ISSN 2070-1721 document πŸ¦‹.

The big headline: this RFC updates RFC 6716, which is the original Opus spec 🌈. It doesn't obsolete anything, it just patches the normative decoder code that lives in Appendix A of 6716. So it's a tune-up, not a rewrite, and it stays fully compatible with 6716 🫢.

Status of This Memo πŸ“œ

Okay this part is lowkey the official paperwork. This is an Internet Standards Track document πŸ’… and it's a product of the IETF. It has consensus from the IETF community, it got public review, and the IESG approved it for publication πŸ‘‘. If you want more info on Internet Standards, check Section 2 of RFC 7841. The status, errata, and feedback info all live at https://www.rfc-editor.org/info/rfc8251 πŸ”₯.

Copyright Notice ©️

Copyright (c) 2017 IETF Trust and the persons identified as the document authors. All rights reserved 🌸. This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (https://trustee.ietf.org/license-info) in effect on the date it was published. Read those carefully, because they spell out your rights and restrictions πŸ™ˆ. Code Components pulled out of this document have to include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions, and they come without warranty as described in that license πŸ’œ.

Table of Contents πŸ—ΊοΈ

1.  Introduction  . . . . . . . . . . . . . . . . . . . . . . . .   2
2.  Terminology . . . . . . . . . . . . . . . . . . . . . . . . .   3
3.  Stereo State Reset in SILK  . . . . . . . . . . . . . . . . .   3
4.  Parsing of the Opus Packet Padding  . . . . . . . . . . . . .   4
5.  Resampler Buffer  . . . . . . . . . . . . . . . . . . . . . .   4
6.  Integer Wrap-Around in Inverse Gain Computation . . . . . . .   6
7.  Integer Wrap-Around in LSF Decoding . . . . . . . . . . . . .   7
8.  Cap on Band Energy  . . . . . . . . . . . . . . . . . . . . .   7
9.  Hybrid Folding  . . . . . . . . . . . . . . . . . . . . . . .   8
10. Downmix to Mono . . . . . . . . . . . . . . . . . . . . . . .   9
11. New Test Vectors  . . . . . . . . . . . . . . . . . . . . . .   9
12. Security Considerations . . . . . . . . . . . . . . . . . . .  11
13. IANA Considerations . . . . . . . . . . . . . . . . . . . . .  11
14. Normative References  . . . . . . . . . . . . . . . . . . . .  11
Acknowledgements  . . . . . . . . . . . . . . . . . . . . . . . .  11
Authors' Addresses  . . . . . . . . . . . . . . . . . . . . . . .  12

1. Introduction 🎀

Okay so, this document fixes little issues that were found in the reference implementation of Opus πŸ’…. Here's the tea: most IETF specs describe a codec in plain text, but RFC 6716 [RFC6716] defines Opus using a normative reference decoder implementation instead 🀯. That reference decoder is in Appendix A of 6716, which is why only decoder issues show up here. If you want an up-to-date Opus encoder, go to <https://opus-codec.org/> 🌈.

Some of these changes update normative behavior in a way that needs new test vectors πŸ§ͺ. Only the C implementation is affected, not the English text of the spec ✨. And this spec stays fully compatible with RFC 6716 [RFC6716] 🫢.

Note: because of RFC formatting rules, long lines in the patch get split with a backslash πŸŽ€. The backslashes at line ends and the whitespace at the start of the next line are NOT part of the patch, and the line numbers are approximate πŸ™ˆ. The full, properly formatted patch is at <https://www.ietf.org/proceedings/98/slides/materials-98-codec-opus-update-00.patch> and its SHA-1 hash is 029e3aa88fc342c91e67a21e7bfbc9458661cd5f πŸ”.

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 BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here πŸ’œ.

3. Stereo State Reset in SILK 🎧

Bestie, the reference implementation doesn't reinitialize the stereo state during a mode switch 😭. The old stereo memory can produce a brief impulse (that's a single sample) in the decoded audio, which is so not it πŸ’€. You fix it by changing silk/dec_API.c around line 72 πŸ”§:

     for( n = 0; n < DECODER_NUM_CHANNELS; n++ ) {
         ret  = silk_init_decoder( &channel_state[ n ] );
     }
+    silk_memset(&((silk_decoder *)decState)->sStereo, 0,
+                sizeof(((silk_decoder *)decState)->sStereo));
+    /* Not strictly needed, but it's cleaner that way */
+    ((silk_decoder *)decState)->prev_decode_only_middle = 0;

     return ret;
 }

This change does affect the normative output of the decoder 🌸, but the amount of change is within tolerance and is too small to make the test vector check fail βœ….

4. Parsing of the Opus Packet Padding πŸ“¦

Okay this one is giving main-character drama 😱. Some invalid packets of a very large size could trigger an out-of-bounds read in the Opus packet parsing code that handles padding 🚨. The cause is an integer overflow when the signaled padding goes past 2^31-1 bytes (the actual packet can be smaller) πŸ™€. The fix is to decrement the (signed) len value instead of incrementing a separate padding counter 🧠. You apply these changes around line 596 of src/opus_decoder.c πŸ› οΈ:

       /* Padding flag is bit 6 */
       if (ch&0x40)
       {
-         int padding=0;
          int p;
          do {
             if (len<=0)
                return OPUS_INVALID_PACKET;
             p = *data++;
             len--;
-            padding += p==255 ? 254: p;
+            len -= p==255 ? 254: p;
          } while (p==255);
-         len -= padding;
       }

The read can go up to about 60 KB past the compressed buffer πŸ“. That only gets triggered by a compressed packet more than about 16 MB long, so it's not a problem for RTP πŸ™Œ. In theory it could crash a file decoder (like Opus in Ogg) if the memory right after the incoming packet is out of range 😬, but attempts to trigger that crash in a production app using an affected decoder failed πŸ€.

5. Resampler Buffer πŸ§ƒ

The SILK resampler had a few issues, bestie 😀:

  1. The calls to memcpy() used sizeof(opus_int32), but the local buffer's type was opus_int16 🀦.
  2. Because the size was wrong, the source and destination regions of the memcpy() could overlap on the copy from "buf" to "buf" 😡. We believe nSamplesIn (number of input samples) is at least fs_in_khZ (sampling rate in kHz), which is at least 8. Since RESAMPLER_ORDER_FIR_12 is only 8, that shouldn't be a problem once the type size is fixed 🌟.
  3. The size of the buffer used RESAMPLER_MAX_BATCH_SIZE_IN, but the data stored in it was actually twice the input batch size (nSamplesIn<<1) πŸ“.

You can fix it by applying these changes around line 78 of silk/resampler_private_IIR_FIR.c πŸ”§:

 )
 {
     silk_resampler_state_struct *S = \
(silk_resampler_state_struct *)SS;
     opus_int32 nSamplesIn;
     opus_int32 max_index_Q16, index_increment_Q16;
-    opus_int16 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + \
RESAMPLER_ORDER_FIR_12 ];
+    opus_int16 buf[ 2*RESAMPLER_MAX_BATCH_SIZE_IN + \
RESAMPLER_ORDER_FIR_12 ];

     /* Copy buffered samples to start of buffer */
-    silk_memcpy( buf, S->sFIR, RESAMPLER_ORDER_FIR_12 \
* sizeof( opus_int32 ) );
+    silk_memcpy( buf, S->sFIR, RESAMPLER_ORDER_FIR_12 \
* sizeof( opus_int16 ) );

     /* Iterate over blocks of frameSizeIn input samples */
     index_increment_Q16 = S->invRatio_Q16;
     while( 1 ) {
         nSamplesIn = silk_min( inLen, S->batchSize );

         /* Upsample 2x */
         silk_resampler_private_up2_HQ( S->sIIR, &buf[ \
RESAMPLER_ORDER_FIR_12 ], in, nSamplesIn );

         max_index_Q16 = silk_LSHIFT32( nSamplesIn, 16 + 1 \
);         /* + 1 because 2x upsampling */
         out = silk_resampler_private_IIR_FIR_INTERPOL( out, \
buf, max_index_Q16, index_increment_Q16 );
         in += nSamplesIn;
         inLen -= nSamplesIn;
         if( inLen > 0 ) {
             /* More iterations to do; copy last part of \
filtered signal to beginning of buffer */
-            silk_memcpy( buf, &buf[ nSamplesIn << 1 ], \
RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
+            silk_memmove( buf, &buf[ nSamplesIn << 1 ], \
RESAMPLER_ORDER_FIR_12 * sizeof( opus_int16 ) );
         } else {
             break;
         }
     }

     /* Copy last part of filtered signal to the state for \
the next call */
-    silk_memcpy( S->sFIR, &buf[ nSamplesIn << 1 ], \
RESAMPLER_ORDER_FIR_12 * sizeof( opus_int32 ) );
+    silk_memcpy( S->sFIR, &buf[ nSamplesIn << 1 ], \
RESAMPLER_ORDER_FIR_12 * sizeof( opus_int16 ) );
 }

6. Integer Wrap-Around in Inverse Gain Computation πŸŒ€

Fuzzing the decoder turned up that some bitstreams could make integer values bigger than 32 bits inside LPC_inverse_pred_gain_QA(), which causes a wrap-around πŸ˜΅β€πŸ’«. The C standard says that's undefined behavior, which is NOT a vibe πŸ’€. The patch around line 87 of silk/LPC_inv_pred_gain.c checks for values that don't fit in a 32-bit integer and treats the matching filters as unstable 🚫:

         /* Update AR coefficient */
         for( n = 0; n < k; n++ ) {
-            tmp_QA = Aold_QA[ n ] - MUL32_FRAC_Q( \
Aold_QA[ k - n - 1 ], rc_Q31, 31 );
-            Anew_QA[ n ] = MUL32_FRAC_Q( tmp_QA, rc_mult2 , mult2Q );
+            opus_int64 tmp64;
+            tmp_QA = silk_SUB_SAT32( Aold_QA[ n ], MUL32_FRAC_Q( \
Aold_QA[ k - n - 1 ], rc_Q31, 31 ) );
+            tmp64 = silk_RSHIFT_ROUND64( silk_SMULL( tmp_QA, \
rc_mult2 ), mult2Q);
+            if( tmp64 > silk_int32_MAX || tmp64 < silk_int32_MIN ) {
+               return 0;
+            }
+            Anew_QA[ n ] = ( opus_int32 )tmp64;
         }

Part 1 of 2 is done πŸŽ€ β€” section 7 onward is coming in part 2, so stay tuned, bestie πŸ’–βœ¨

7. Integer Wrap-Around in LSF Decoding ✨

okay so this one is a total plot twist 😭 πŸ”₯ while people were fuzzing the decoder (throwing garbage bitstreams at it on purpose, iykyk), they found that an integer wrap-around could happen when the high Line Spectral Frequency (LSF) parameters were absolutely enormous πŸ’€. The end result is an illegal read access on the stack. The authors don't think anyone can actually exploit it πŸ™ˆ, but it's still a bug and it still needs fixing, no cap.

Here's the patch for silk/NLSF_stabilize.c, around line 137, that makes it go away πŸ’…:

          /* Keep delta_min distance between the NLSFs */
        for( i = 1; i < L; i++ )
-            NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], \
NLSF_Q15[i-1] + NDeltaMin_Q15[i] );
+            NLSF_Q15[i] = silk_max_int( NLSF_Q15[i], \
silk_ADD_SAT16( NLSF_Q15[i-1], NDeltaMin_Q15[i] ) );

        /* Last NLSF should be no higher than 1 - NDeltaMin[L] */

8. Cap on Band Energy πŸŽ€

this one is giving "numbers got too big and turned into NaN" energy 😭. On extreme bitstreams, the log-domain band energy levels can go past the maximum single-precision floating point value once they're converted to a linear scale. That makes the decoded values NaN (not a number), which can cause problems for whatever software is using the PCM values afterward πŸ’€. The fix is a cap, applied around line 552 of celt/quant_bands.c 🧚:

        {
           opus_val16 lg = ADD16(oldEBands[i+c*m->nbEBands],
                           SHL16((opus_val16)eMeans[i],6));
+         lg = MIN32(QCONST32(32.f, 16), lg);
           eBands[i+c*m->nbEBands] = PSHR32(celt_exp2(lg),4);
        }
        for (;i<m->nbEBands;i++)

9. Hybrid Folding πŸ¦‹

okay this one is lowkey the most dramatic 😭. When you're encoding in hybrid mode at a low bitrate, sometimes there are only enough bits to code a single Constrained-Energy Lapped Transform (CELT) band (8 - 9.6 kHz). When that happens, the second band (CELT band 18, from 9.6 - 12 kHz) can't use folding, because it's wider than what's already been coded, so it falls back to white noise. And since this can also happen on transients (like stops), it can cause audible pre-echo πŸ™ˆ.

So the fix is to change the folding behavior so it's never forced to fall back to Linear Congruential Generator (LCG) just because the first band doesn't have enough coefficients to fold onto the second band. The trick is simply to repeat part of the first band while folding the second band 🫢. This changes the code in celt/bands.c around line 1237:

          b = 0;
       }

-      if (resynth && M*eBands[i]-N >= M*eBands[start] && \
(update_lowband || lowband_offset==0))
+      if (resynth && (M*eBands[i]-N >= M*eBands[start] || \
i==start+1) && (update_lowband || lowband_offset==0))
            lowband_offset = i;

+      if (i == start+1)
+      {
+         int n1, n2;
+         int offset;
+         n1 = M*(eBands[start+1]-eBands[start]);
+         n2 = M*(eBands[start+2]-eBands[start+1]);
+         offset = M*eBands[start];
+         /* Duplicate enough of the first band folding data to \
be able to fold the second band.
+            Copies no data for CELT-only mode. */
+         OPUS_COPY(&norm[offset+n1], &norm[offset+2*n1 - n2], n2-n1);
+         if (C==2)
+            OPUS_COPY(&norm2[offset+n1], &norm2[offset+2*n1 - n2], \
n2-n1);
+      }
+
       tf_change = tf_res[i];
       if (i>=m->effEBands)
       {

as well as around line 1260:

          fold_start = lowband_offset;
          while(M*eBands[--fold_start] > effective_lowband);
          fold_end = lowband_offset-1;
-         while(M*eBands[++fold_end] < effective_lowband+N);
+         while(++fold_end < i && M*eBands[fold_end] < \
effective_lowband+N);
          x_cm = y_cm = 0;
          fold_i = fold_start; do {
            x_cm |= collapse_masks[fold_i*C+0];

The fix doesn't break compatibility, because the improvement doesn't depend on the encoder doing anything special. There's also no reasonable way for an encoder to use the original behavior to get better quality than the new version, so nothing is lost πŸ’…βœ¨.

10. Downmix to Mono 🌸

this isn't technically a bug, but people have reported it when downmixing an Opus decoded stream to mono, whether that happens inside the decoder or as a post-processing step on the stereo decoder output πŸ™ˆ. Opus intensity stereo lets you optionally code the two channels 180 degrees out of phase on a per-band basis. That gives you better stereo quality than forcing the channels to be in phase, but when the output gets downmixed to mono, the energy in those bands cancels out, and that can cause audible artifacts 😭.

The work-around is that the decoder MAY choose not to apply the 180-degree phase shift. This can be useful when downmixing to mono inside or outside of the decoder (for example, when it's requested explicitly from an API) πŸ§šπŸ’œ.

11. New Test Vectors πŸ“

okay so Sections 9 and 10 change the test vectors enough that they would fail, so this document also updates the Opus test vectors πŸ’–. The new ones include two decoded outputs for the same bitstream. The outputs with the suffix 'm' don't apply the CELT 180-degree phase shift (which Section 10 allows), and the ones without the suffix do. An implementation is compliant as long as it passes either set 🫢.

Any Opus implementation that passes either the original test vectors from RFC 6716 [RFC6716] or one of the new sets is compliant with the Opus specification ✨. That said, newer implementations SHOULD be based on the new test vectors rather than the old ones πŸ‘‘.

The new test vectors live at <https://www.ietf.org/proceedings/98/slides/materials-98-codec-opus-newvectors-00.tar.gz>. The SHA-1 hashes are:

e49b2862ceec7324790ed8019eb9744596d5be01  testvector01.bit
b809795ae1bcd606049d76de4ad24236257135e0  testvector02.bit
e0c4ecaeab44d35a2f5b6575cd996848e5ee2acc  testvector03.bit
a0f870cbe14ebb71fa9066ef3ee96e59c9a75187  testvector04.bit
9b3d92b48b965dfe9edf7b8a85edd4309f8cf7c8  testvector05.bit
28e66769ab17e17f72875283c14b19690cbc4e57  testvector06.bit
bacf467be3215fc7ec288f29e2477de1192947a6  testvector07.bit
ddbe08b688bbf934071f3893cd0030ce48dba12f  testvector08.bit
3932d9d61944dab1201645b8eeaad595d5705ecb  testvector09.bit
521eb2a1e0cc9c31b8b740673307c2d3b10c1900  testvector10.bit
6bc8f3146fcb96450c901b16c3d464ccdf4d5d96  testvector11.bit
338c3f1b4b97226bc60bc41038becbc6de06b28f  testvector12.bit
f5ef93884da6a814d311027918e9afc6f2e5c2c8  testvector01.dec
48ac1ff1995250a756e1e17bd32acefa8cd2b820  testvector02.dec
d15567e919db2d0e818727092c0af8dd9df23c95  testvector03.dec
1249dd28f5bd1e39a66fd6d99449dca7a8316342  testvector04.dec
b85675d81deef84a112c466cdff3b7aaa1d2fc76  testvector05.dec
55f0b191e90bfa6f98b50d01a64b44255cb4813e  testvector06.dec
61e8b357ab090b1801eeb578a28a6ae935e25b7b  testvector07.dec
a58539ee5321453b2ddf4c0f2500e856b3966862  testvector08.dec
bb96aad2cde188555862b7bbb3af6133851ef8f4  testvector09.dec
1b6cdf0413ac9965b16184b1bea129b5c0b2a37a  testvector10.dec
b1fff72b74666e3027801b29dbc48b31f80dee0d  testvector11.dec
98e09bbafed329e341c3b4052e9c4ba5fc83f9b1  testvector12.dec
1e7d984ea3fbb16ba998aea761f4893fbdb30157  testvector01m.dec
48ac1ff1995250a756e1e17bd32acefa8cd2b820  testvector02m.dec
d15567e919db2d0e818727092c0af8dd9df23c95  testvector03m.dec
1249dd28f5bd1e39a66fd6d99449dca7a8316342  testvector04m.dec
d70b0bad431e7d463bc3da49bd2d49f1c6d0a530  testvector05m.dec
6ac1648c3174c95fada565161a6c78bdbe59c77d  testvector06m.dec
fc5e2f709693738324fb4c8bdc0dad6dda04e713  testvector07m.dec
aad2ba397bf1b6a18e8e09b50e4b19627d479f00  testvector08m.dec
6feb7a7b9d7cdc1383baf8d5739e2a514bd0ba08  testvector09m.dec
1b6cdf0413ac9965b16184b1bea129b5c0b2a37a  testvector10m.dec
fd3d3a7b0dfbdab98d37ed9aa04b659b9fefbd18  testvector11m.dec
98e09bbafed329e341c3b4052e9c4ba5fc83f9b1  testvector12m.dec

Note that the decoder input bitstream files (.bit) are unchanged πŸ’….

12. Security Considerations πŸ”₯

this part is serious, bestie, so listen up πŸ™ˆ. This document fixes two security issues that were reported on Opus and affect the reference implementation in RFC 6716 [RFC6716]: CVE-2013-0899 <https://nvd.nist.gov/vuln/detail/CVE-2013-0899> and CVE-2017-0381 <https://nvd.nist.gov/vuln/detail/CVE-2017-0381>. CVE-2013-0899 could theoretically have caused an information leak. The leaked information would have gone through the decoder process before the attacker could access it. The update in Section 4 fixes this. CVE-2017-0381 could have resulted in a 16-bit out-of-bounds read from a fixed location. The update in Section 7 fixes this 😭. Beyond those two fixed Common Vulnerabilities and Exposures (CVEs), this document adds no new security considerations beyond the ones in RFC 6716 [RFC6716] 🫢.

13. IANA Considerations 🌈

this document does not require any IANA actions πŸ’….

14. 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>.

[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>.

[RFC8174] Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words", BCP 14, RFC 8174, DOI 10.17487/RFC8174, May 2017, <https://www.rfc-editor.org/info/rfc8174>.

Acknowledgements πŸ’œ

we owe a big thank you to Juri Aedla for reporting the issue with parsing the Opus padding πŸ™Œ. Thanks to Felicia Lim for reporting the LSF integer overflow issue 🧚. And thanks to Tina le Grand, Jonathan Lennox, and Mark Harris for their feedback on this document πŸŽ€.

Authors' Addresses πŸ¦‹

Jean-Marc Valin Mozilla Corporation 331 E. Evelyn Avenue Mountain View, CA 94041 United States of America

Phone: +1 650 903-0800 Email: jmvalin@jmvalin.ca

Koen Vos vocTone

Email: koenvos74@gmail.com

πŸ“¦ where this page comes from