Bug 1323390 - Support audio profile in mp4 rust parser. r=kinetik draft
authorAlfredo.Yang <ayang@mozilla.com>
Wed, 14 Dec 2016 16:01:43 +0800
changeset 452719 ac9b059759f73c92f7678ed137f0366e35fdc800
parent 452718 f179934df0c1bab590c558485d419c7910e41325
child 540277 c6bb215fb091ec279e68755fede65b28173edb23
push id39460
push userbmo:ayang@mozilla.com
push dateThu, 22 Dec 2016 01:47:45 +0000
reviewerskinetik
bugs1323390
milestone53.0a1
Bug 1323390 - Support audio profile in mp4 rust parser. r=kinetik MozReview-Commit-ID: DLfLdgvc7B1
media/libstagefright/binding/DecoderData.cpp
media/libstagefright/binding/MP4Metadata.cpp
media/libstagefright/binding/mp4parse-cargo.patch
media/libstagefright/binding/mp4parse/Cargo.toml
media/libstagefright/binding/mp4parse/src/lib.rs
third_party/rust/bitreader/.cargo-checksum.json
third_party/rust/bitreader/.cargo-ok
third_party/rust/bitreader/.gitignore
third_party/rust/bitreader/Cargo.toml
third_party/rust/bitreader/LICENSE
third_party/rust/bitreader/README.md
third_party/rust/bitreader/src/lib.rs
third_party/rust/bitreader/src/tests.rs
toolkit/library/gtest/rust/Cargo.lock
toolkit/library/rust/Cargo.lock
--- a/media/libstagefright/binding/DecoderData.cpp
+++ b/media/libstagefright/binding/DecoderData.cpp
@@ -225,35 +225,31 @@ MP4AudioInfo::Update(const mp4parse_trac
     mMimeType = MEDIA_MIMETYPE_AUDIO_FLAC;
   } else if (track->codec == MP4PARSE_CODEC_MP3) {
     mMimeType = MEDIA_MIMETYPE_AUDIO_MPEG;
   }
 
   mRate = audio->sample_rate;
   mChannels = audio->channels;
   mBitDepth = audio->bit_depth;
+  mExtendedProfile = audio->profile;
   mDuration = track->duration;
   mMediaTime = track->media_time;
   mTrackId = track->track_id;
 
-  // TODO: mProfile (kKeyAACProfile in stagefright)
+  // In stagefright, mProfile is kKeyAACProfile, mExtendedProfile is kKeyAACAOT.
+  // Both are from audioObjectType in AudioSpecificConfig.
+  if (audio->profile <= 4) {
+    mProfile = audio->profile;
+  }
 
   const uint8_t* cdata = audio->codec_specific_config.data;
   size_t size = audio->codec_specific_config.length;
   if (size > 0) {
     mCodecSpecificConfig->AppendElements(cdata, size);
-
-    if (size > 1) {
-      ABitReader br(cdata, size);
-      mExtendedProfile = br.getBits(5);
-
-      if (mExtendedProfile == 31) {  // AAC-ELD => additional 6 bits
-        mExtendedProfile = 32 + br.getBits(6);
-      }
-    }
   }
 }
 
 void
 MP4VideoInfo::Update(const mp4parse_track_info* track,
                      const mp4parse_track_video_info* video)
 {
   UpdateTrackProtectedInfo(*this, video->protected_data);
--- a/media/libstagefright/binding/MP4Metadata.cpp
+++ b/media/libstagefright/binding/MP4Metadata.cpp
@@ -297,18 +297,17 @@ MP4Metadata::GetTrackInfo(mozilla::Track
     MOZ_DIAGNOSTIC_ASSERT(infoRust->mCrypto.mIVSize == info->mCrypto.mIVSize);
     MOZ_DIAGNOSTIC_ASSERT(infoRust->mCrypto.mKeyId == info->mCrypto.mKeyId);
     switch (aType) {
     case mozilla::TrackInfo::kAudioTrack: {
       AudioInfo *audioRust = infoRust->GetAsAudioInfo(), *audio = info->GetAsAudioInfo();
       MOZ_DIAGNOSTIC_ASSERT(audioRust->mRate == audio->mRate);
       MOZ_DIAGNOSTIC_ASSERT(audioRust->mChannels == audio->mChannels);
       MOZ_DIAGNOSTIC_ASSERT(audioRust->mBitDepth == audio->mBitDepth);
-      // TODO: These fields aren't implemented in the Rust demuxer yet.
-      //MOZ_DIAGNOSTIC_ASSERT(audioRust->mProfile != audio->mProfile);
+      MOZ_DIAGNOSTIC_ASSERT(audioRust->mProfile == audio->mProfile);
       MOZ_DIAGNOSTIC_ASSERT(audioRust->mExtendedProfile == audio->mExtendedProfile);
       break;
     }
     case mozilla::TrackInfo::kVideoTrack: {
       VideoInfo *videoRust = infoRust->GetAsVideoInfo(), *video = info->GetAsVideoInfo();
       MOZ_DIAGNOSTIC_ASSERT(videoRust->mDisplay == video->mDisplay);
       MOZ_DIAGNOSTIC_ASSERT(videoRust->mImage == video->mImage);
       MOZ_DIAGNOSTIC_ASSERT(*videoRust->mExtraData == *video->mExtraData);
--- a/media/libstagefright/binding/mp4parse-cargo.patch
+++ b/media/libstagefright/binding/mp4parse-cargo.patch
@@ -1,22 +1,24 @@
 diff --git a/media/libstagefright/binding/mp4parse/Cargo.toml b/media/libstagefright/binding/mp4parse/Cargo.toml
 index ff9422c..814c4c6 100644
 --- a/media/libstagefright/binding/mp4parse/Cargo.toml
 +++ b/media/libstagefright/binding/mp4parse/Cargo.toml
-@@ -18,17 +18,11 @@ exclude = [
+@@ -18,18 +18,12 @@ exclude = [
  ]
  
  [dependencies]
 -byteorder = "0.5.0"
 -afl = { version = "0.1.1", optional = true }
 -afl-plugin = { version = "0.1.1", optional = true }
 -abort_on_panic = { version = "1.0.0", optional = true }
+-bitreader = { version = "0.1.0" }
 +byteorder = "0.5.0"
- 
++bitreader = { version = "0.1.0" }
+
  [dev-dependencies]
  test-assembler = "0.1.2"
  
 -[features]
 -fuzz = ["afl", "afl-plugin", "abort_on_panic"]
 -
  # Somewhat heavy-handed, but we want at least -Z force-overflow-checks=on.
  [profile.release]
--- a/media/libstagefright/binding/mp4parse/Cargo.toml
+++ b/media/libstagefright/binding/mp4parse/Cargo.toml
@@ -15,15 +15,16 @@ repository = "https://github.com/mozilla
 
 # Avoid complaints about trying to package test files.
 exclude = [
   "*.mp4",
 ]
 
 [dependencies]
 byteorder = "0.5.0"
+bitreader = { version = "0.1.0" }
 
 [dev-dependencies]
 test-assembler = "0.1.2"
 
 # Somewhat heavy-handed, but we want at least -Z force-overflow-checks=on.
 [profile.release]
 debug-assertions = true
--- a/media/libstagefright/binding/mp4parse/src/lib.rs
+++ b/media/libstagefright/binding/mp4parse/src/lib.rs
@@ -4,17 +4,19 @@
 // License, v. 2.0. If a copy of the MPL was not distributed with this
 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
 #![cfg_attr(feature = "fuzz", feature(plugin))]
 #![cfg_attr(feature = "fuzz", plugin(afl_plugin))]
 #[cfg(feature = "fuzz")]
 extern crate afl;
 
 extern crate byteorder;
+extern crate bitreader;
 use byteorder::{ReadBytesExt, WriteBytesExt};
+use bitreader::{BitReader, ReadInto};
 use std::io::{Read, Take};
 use std::io::Cursor;
 use std::cmp;
 
 mod boxes;
 use boxes::BoxType;
 
 // Unit tests.
@@ -56,16 +58,22 @@ pub enum Error {
     /// Reflect `std::io::ErrorKind::UnexpectedEof` for short data.
     UnexpectedEOF,
     /// Propagate underlying errors from `std::io`.
     Io(std::io::Error),
     /// read_mp4 terminated without detecting a moov box.
     NoMoov,
 }
 
+impl From<bitreader::BitReaderError> for Error {
+    fn from(_: bitreader::BitReaderError) -> Error {
+        Error::InvalidData("invalid data")
+    }
+}
+
 impl From<std::io::Error> for Error {
     fn from(err: std::io::Error) -> Error {
         match err.kind() {
             std::io::ErrorKind::UnexpectedEof => Error::UnexpectedEOF,
             _ => Error::Io(err),
         }
     }
 }
@@ -1240,28 +1248,40 @@ fn find_descriptor(data: &[u8], esds: &m
 
 fn read_ds_descriptor(data: &[u8], esds: &mut ES_Descriptor) -> Result<()> {
     let frequency_table =
         vec![(0x1, 96000), (0x1, 88200), (0x2, 64000), (0x3, 48000),
              (0x4, 44100), (0x5, 32000), (0x6, 24000), (0x7, 22050),
              (0x8, 16000), (0x9, 12000), (0xa, 11025), (0xb, 8000),
              (0xc, 7350)];
 
-    let des = &mut Cursor::new(data);
+    let bit_reader = &mut BitReader::new(data);
+
+    let mut audio_object_type: u16 = ReadInto::read(bit_reader, 5)?;
 
-    let audio_specific_config = be_u16(des)?;
+    // Extend audio object type, for example, HE-AAC.
+    if audio_object_type == 31 {
+        let audio_object_type_ext: u16 = ReadInto::read(bit_reader, 6)?;
+        audio_object_type = 32 + audio_object_type_ext;
+    }
 
-    let audio_object_type = audio_specific_config >> 11;
+    let sample_index: u32 = ReadInto::read(bit_reader, 4)?;
 
-    let sample_index = (audio_specific_config & 0x07FF) >> 7;
+    // Sample frequency could be from table, or retrieved from stream directly
+    // if index is 0x0f.
+    let sample_frequency = match sample_index {
+        0x0F => {
+            Some(ReadInto::read(bit_reader, 24)?)
+        },
+        _ => {
+            frequency_table.iter().find(|item| item.0 == sample_index).map(|x| x.1)
+        },
+    };
 
-    let channel_counts = (audio_specific_config & 0x007F) >> 3;
-
-    let sample_frequency =
-        frequency_table.iter().find(|item| item.0 == sample_index).map(|x| x.1);
+    let channel_counts: u16 = ReadInto::read(bit_reader, 4)?;
 
     esds.audio_object_type = Some(audio_object_type);
     esds.audio_sample_rate = sample_frequency;
     esds.audio_channel_count = Some(channel_counts);
 
     Ok(())
 }
 
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bitreader/.cargo-checksum.json
@@ -0,0 +1,1 @@
+{"files":{".cargo-ok":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",".gitignore":"f9b1ca6ae27d1c18215265024629a8960c31379f206d9ed20f64e0b2dcf79805","Cargo.toml":"958f2305ab8afcf59f3eeef619f95e511ee2721654417784bbec5ef135fe608b","LICENSE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","README.md":"dc19fd728ea91808d5f4109b9343f6a6bfb931f20a3094f4d5d77f9343b09579","src/lib.rs":"343e09a0e40a7d88e69e346bcc0816260e91abafbc9fe854b3aae16305cb717e","src/tests.rs":"bf0d60d6b70f79eb36a394ba51eae7c36e185778f31ef9bfba12399ec60b6e75"},"package":"b245039eddbd1a051b8bfa5d5b6afaad6d34d172057a15d561e80b50b4978e8d"}
\ No newline at end of file
new file mode 100644
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bitreader/.gitignore
@@ -0,0 +1,2 @@
+target
+Cargo.lock
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bitreader/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "bitreader"
+version = "0.1.0"
+authors = ["Ilkka Rauta <ilkka.rauta@gmail.com>"]
+
+description = """
+BitReader helps reading individual bits from a slice of bytes.
+
+You can read "unusual" numbers of bits from the byte slice, for example 13 bits
+at once. The reader internally keeps track of position within the buffer.
+"""
+
+homepage = "https://github.com/irauta/bitreader"
+repository = "https://github.com/irauta/bitreader"
+
+keywords = ["bit", "bits", "bitstream"]
+
+license = "Apache-2.0"
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bitreader/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bitreader/README.md
@@ -0,0 +1,19 @@
+# BitReader
+
+BitReader is a helper type to extract strings of bits from a slice of bytes.
+
+Here is how you read first a single bit, then three bits and finally four bits from a byte buffer:
+
+    use bitreader::BitReader;
+
+    let slice_of_u8 = &[0b1000_1111];
+    let mut reader = BitReader::new(slice_of_u8);
+
+    // You obviously should use try! or some other error handling mechanism here
+    let a_single_bit = reader.read_u8(1).unwrap(); // 1
+    let more_bits = reader.read_u8(3).unwrap(); // 0
+    let last_bits_of_byte = reader.read_u8(4).unwrap(); // 0b1111
+
+You can naturally read bits from longer buffer of data than just a single byte.
+
+As you read bits, the internal cursor of BitReader moves on along the stream of bits. Little endian format is assumed when reading the multi-byte values. BitReader supports reading maximum of 64 bits at a time (with read_u64). Reading signed values directly is not supported at the moment.
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bitreader/src/lib.rs
@@ -0,0 +1,330 @@
+// Copyright 2015 Ilkka Rauta
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! BitReader is a helper type to extract strings of bits from a slice of bytes.
+//!
+//! Here is how you read first a single bit, then three bits and finally four bits from a byte
+//! buffer:
+//!
+//! ```
+//! use bitreader::BitReader;
+//!
+//! let slice_of_u8 = &[0b1000_1111];
+//! let mut reader = BitReader::new(slice_of_u8);
+//!
+//! // You probably should use try! or some other error handling mechanism in real code if the
+//! // length of the input is not known in advance.
+//! let a_single_bit = reader.read_u8(1).unwrap();
+//! assert_eq!(a_single_bit, 1);
+//!
+//! let more_bits = reader.read_u8(3).unwrap();
+//! assert_eq!(more_bits, 0);
+//!
+//! let last_bits_of_byte = reader.read_u8(4).unwrap();
+//! assert_eq!(last_bits_of_byte, 0b1111);
+//! ```
+//! You can naturally read bits from longer buffer of data than just a single byte.
+//!
+//! As you read bits, the internal cursor of BitReader moves on along the stream of bits. Little
+//! endian format is assumed when reading the multi-byte values. BitReader supports reading maximum
+//! of 64 bits at a time (with read_u64). Reading signed values directly is not supported at the
+//! moment.
+//!
+//! The reads do not need to be aligned in any particular way.
+//!
+//! Reading zero bits is a no-op.
+//!
+//! You can also skip over a number of bits, in which case there is no arbitrary small limits like
+//! when reading the values to a variable. However, you can not seek past the end of the slice,
+//! either when reading or when skipping bits.
+//!
+//! Note that the code will likely not work correctly if the slice is longer than 2^61 bytes, but
+//! exceeding that should be pretty unlikely. Let's get back to this when people read exabytes of
+//! information one bit at a time.
+
+use std::fmt;
+use std::error::Error;
+use std::result;
+
+#[cfg(test)]
+mod tests;
+
+/// BitReader reads data from a byte slice at the granularity of a single bit.
+pub struct BitReader<'a> {
+    bytes: &'a [u8],
+    /// Position from the start of the slice, counted as bits instead of bytes
+    position: u64,
+    relative_offset: u64,
+}
+
+impl<'a> BitReader<'a> {
+    /// Construct a new BitReader from a byte slice. The returned reader lives at most as long as
+    /// the slice given to is valid.
+    pub fn new(bytes: &'a [u8]) -> BitReader<'a> {
+        BitReader {
+            bytes: bytes,
+            position: 0,
+            relative_offset: 0,
+        }
+    }
+
+    /// Returns a copy of current BitReader, with the difference that its position() returns
+    /// positions relative to the position of the original BitReader at the construction time.
+    /// After construction, both readers are otherwise completely independent, except of course
+    /// for sharing the same source data.
+    ///
+    /// ```
+    /// use bitreader::BitReader;
+    ///
+    /// let bytes = &[0b11110000, 0b00001111];
+    /// let mut original = BitReader::new(bytes);
+    /// assert_eq!(original.read_u8(4).unwrap(), 0b1111);
+    /// assert_eq!(original.position(), 4);
+    ///
+    /// let mut relative = original.relative_reader();
+    /// assert_eq!(relative.position(), 0);
+    ///
+    /// assert_eq!(original.read_u8(8).unwrap(), 0);
+    /// assert_eq!(relative.read_u8(8).unwrap(), 0);
+    ///
+    /// assert_eq!(original.position(), 12);
+    /// assert_eq!(relative.position(), 8);
+    /// ```
+    pub fn relative_reader(&self) -> BitReader<'a> {
+        BitReader {
+            bytes: self.bytes,
+            position: self.position,
+            relative_offset: self.position,
+        }
+    }
+
+    /// Read at most 8 bits into a u8.
+    pub fn read_u8(&mut self, bit_count: u8) -> Result<u8> {
+        let value = try!(self.read_value(bit_count, 8));
+        Ok((value & 0xff) as u8)
+    }
+
+    /// Read at most 16 bits into a u16.
+    pub fn read_u16(&mut self, bit_count: u8) -> Result<u16> {
+        let value = try!(self.read_value(bit_count, 16));
+        Ok((value & 0xffff) as u16)
+    }
+
+    /// Read at most 32 bits into a u32.
+    pub fn read_u32(&mut self, bit_count: u8) -> Result<u32> {
+        let value = try!(self.read_value(bit_count, 32));
+        Ok((value & 0xffffffff) as u32)
+    }
+
+    /// Read at most 64 bits into a u64.
+    pub fn read_u64(&mut self, bit_count: u8) -> Result<u64> {
+        let value = try!(self.read_value(bit_count, 64));
+        Ok(value)
+    }
+
+    /// Read at most 8 bits into a i8.
+    /// Assumes the bits are stored in two's complement format.
+    pub fn read_i8(&mut self, bit_count: u8) -> Result<i8> {
+        let value = try!(self.read_signed_value(bit_count, 8));
+        Ok((value & 0xff) as i8)
+    }
+
+    /// Read at most 16 bits into a i16.
+    /// Assumes the bits are stored in two's complement format.
+    pub fn read_i16(&mut self, bit_count: u8) -> Result<i16> {
+        let value = try!(self.read_signed_value(bit_count, 16));
+        Ok((value & 0xffff) as i16)
+    }
+
+    /// Read at most 32 bits into a i32.
+    /// Assumes the bits are stored in two's complement format.
+    pub fn read_i32(&mut self, bit_count: u8) -> Result<i32> {
+        let value = try!(self.read_signed_value(bit_count, 32));
+        Ok((value & 0xffffffff) as i32)
+    }
+
+    /// Read at most 64 bits into a i64.
+    /// Assumes the bits are stored in two's complement format.
+    pub fn read_i64(&mut self, bit_count: u8) -> Result<i64> {
+        let value = try!(self.read_signed_value(bit_count, 64));
+        Ok(value)
+    }
+
+    /// Skip arbitrary number of bits. However, you can skip at most to the end of the byte slice.
+    pub fn skip(&mut self, bit_count: u64) -> Result<()> {
+        let end_position = self.position + bit_count;
+        if end_position > self.bytes.len() as u64 * 8 {
+            return Err(BitReaderError::NotEnoughData {
+                position: self.position,
+                length: (self.bytes.len() * 8) as u64,
+                requested: bit_count,
+            });
+        }
+        self.position = end_position;
+        Ok(())
+    }
+
+    /// Returns the position of the cursor, or how many bits have been read so far.
+    pub fn position(&self) -> u64 {
+        self.position - self.relative_offset
+    }
+
+    /// Helper to make sure the "bit cursor" is exactly at the beginning of a byte, or at specific
+    /// multi-byte alignment position.
+    ///
+    /// For example `reader.is_aligned(1)` returns true if exactly n bytes, or n * 8 bits, has been
+    /// read. Similarly, `reader.is_aligned(4)` returns true if exactly n * 32 bits, or n 4-byte
+    /// sequences has been read.
+    ///
+    /// This function can be used to validate the data is being read properly, for example by
+    /// adding invocations wrapped into `debug_assert!()` to places where it is known the data
+    /// should be n-byte aligned.
+    pub fn is_aligned(&self, alignment_bytes: u32) -> bool {
+        self.position % (alignment_bytes as u64 * 8) == 0
+    }
+
+    fn read_signed_value(&mut self, bit_count: u8, maximum_count: u8) -> Result<i64> {
+        let unsigned = try!(self.read_value(bit_count, maximum_count));
+        // Fill the bits above the requested bits with all ones or all zeros,
+        // depending on the sign bit.
+        let sign_bit = unsigned >> (bit_count - 1) & 1;
+        let high_bits = if sign_bit == 1 { -1 } else { 0 };
+        Ok(high_bits << bit_count | unsigned as i64)
+    }
+
+    fn read_value(&mut self, bit_count: u8, maximum_count: u8) -> Result<u64> {
+        if bit_count == 0 {
+            return Ok(0);
+        }
+        if bit_count > maximum_count {
+            return Err(BitReaderError::TooManyBitsForType {
+                position: self.position,
+                requested: bit_count,
+                allowed: maximum_count,
+            });
+        }
+        let start_position = self.position;
+        let end_position = self.position + bit_count as u64;
+        if end_position > self.bytes.len() as u64 * 8 {
+            return Err(BitReaderError::NotEnoughData {
+                position: self.position,
+                length: (self.bytes.len() * 8) as u64,
+                requested: bit_count as u64,
+            });
+        }
+
+        let mut value: u64 = 0;
+
+        for i in start_position..end_position {
+            let byte_index = (i / 8) as usize;
+            let byte = self.bytes[byte_index];
+            let shift = 7 - (i % 8);
+            let bit = (byte >> shift) as u64 & 1;
+            value = (value << 1) | bit;
+        }
+
+        self.position = end_position;
+        Ok(value)
+    }
+}
+
+/// Result type for those BitReader operations that can fail.
+pub type Result<T> = result::Result<T, BitReaderError>;
+
+/// Error enumeration of BitReader errors.
+#[derive(Debug,PartialEq,Copy,Clone)]
+pub enum BitReaderError {
+    /// Requested more bits than there are left in the byte slice at the current position.
+    NotEnoughData {
+        position: u64,
+        length: u64,
+        requested: u64,
+    },
+    /// Requested more bits than the returned variable can hold, for example more than 8 bits when
+    /// reading into a u8.
+    TooManyBitsForType {
+        position: u64,
+        requested: u8,
+        allowed: u8,
+    }
+}
+
+impl Error for BitReaderError {
+    fn description(&self) -> &str {
+        match *self {
+            BitReaderError::NotEnoughData {..} => "Requested more bits than the byte slice has left",
+            BitReaderError::TooManyBitsForType {..} => "Requested more bits than the requested integer type can hold",
+        }
+    }
+}
+
+impl fmt::Display for BitReaderError {
+    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+        //self.description().fmt(fmt)
+        match *self {
+            BitReaderError::NotEnoughData { position, length, requested } => write!(fmt, "BitReader: Requested {} bits with only {}/{} bits left (position {})", requested, length - position, length, position),
+            BitReaderError::TooManyBitsForType { position, requested, allowed } => write!(fmt, "BitReader: Requested {} bits while the type can only hold {} (position {})", requested, allowed, position),
+        }
+    }
+}
+
+/// Helper trait to allow reading bits into a variable without explicitly mentioning its type.
+///
+/// If you can't or want, for some reason, to use BitReader's read methods (`read_u8` etc.) but
+/// want to rely on type inference instead, you can use the ReadInto trait. The trait is
+/// implemented for all basic integer types (8/16/32/64 bits, signed/unsigned).
+///
+/// ```
+/// use bitreader::{BitReader,ReadInto};
+///
+/// let slice_of_u8 = &[0b1100_0000];
+/// let mut reader = BitReader::new(slice_of_u8);
+///
+/// struct Foo {
+///     bar: u8
+/// }
+///
+/// // No type mentioned here, instead the type of bits is inferred from the type of Foo::bar,
+/// // and consequently the correct "overload" is used.
+/// let bits = ReadInto::read(&mut reader, 2).unwrap();
+///
+/// let foo = Foo { bar: bits };
+/// assert_eq!(foo.bar, 3)
+/// ```
+pub trait ReadInto
+    where Self: Sized
+{
+    fn read(reader: &mut BitReader, bits: u8) -> Result<Self>;
+}
+
+// There's eight almost identical implementations, let's make this easier.
+macro_rules! impl_read_into {
+    ($T:ty, $method:ident) => (
+        impl ReadInto for $T {
+            fn read(reader: &mut BitReader, bits: u8) -> Result<Self> {
+                reader.$method(bits)
+            }
+        }
+    )
+}
+
+impl_read_into!(u8, read_u8);
+impl_read_into!(u16, read_u16);
+impl_read_into!(u32, read_u32);
+impl_read_into!(u64, read_u64);
+
+impl_read_into!(i8, read_i8);
+impl_read_into!(i16, read_i16);
+impl_read_into!(i32, read_i32);
+impl_read_into!(i64, read_i64);
new file mode 100644
--- /dev/null
+++ b/third_party/rust/bitreader/src/tests.rs
@@ -0,0 +1,140 @@
+// Copyright 2015 Ilkka Rauta
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use super::*;
+
+#[test]
+fn read_buffer() {
+    let bytes = &[
+        0b1011_0101, 0b0110_1010, 0b1010_1100, 0b1001_1001,
+        0b1001_1001, 0b1001_1001, 0b1001_1001, 0b1110_0111,
+    ];
+
+    let mut reader = BitReader::new(bytes);
+
+    assert_eq!(reader.read_u8(1).unwrap(), 0b1);
+    assert_eq!(reader.read_u8(1).unwrap(), 0b0);
+    assert_eq!(reader.read_u8(2).unwrap(), 0b11);
+
+    assert_eq!(reader.read_u8(4).unwrap(), 0b0101);
+
+    assert!(reader.is_aligned(1));
+
+    assert_eq!(reader.read_u8(3).unwrap(), 0b11);
+    assert_eq!(reader.read_u16(10).unwrap(), 0b01_0101_0101);
+    assert_eq!(reader.read_u8(3).unwrap(), 0b100);
+
+    assert!(reader.is_aligned(1));
+
+    assert_eq!(reader.read_u32(32).unwrap(), 0b1001_1001_1001_1001_1001_1001_1001_1001);
+
+    assert_eq!(reader.read_u8(4).unwrap(), 0b1110);
+    assert_eq!(reader.read_u8(3).unwrap(), 0b011);
+    assert_eq!(reader.read_u8(1).unwrap(), 0b1);
+
+    // Could also be 8 at this point!
+    assert!(reader.is_aligned(4));
+}
+
+#[test]
+fn try_all_sizes() {
+    let bytes = &[
+        0x4a, 0x1e, 0x39, 0xbb, 0xd0, 0x07, 0xca, 0x9a,
+        0xa6, 0xba, 0x25, 0x52, 0x6f, 0x0a, 0x6a, 0xba,
+    ];
+
+    let mut reader = BitReader::new(bytes);
+    assert_eq!(reader.read_u64(64).unwrap(), 0x4a1e39bbd007ca9a);
+    assert_eq!(reader.read_u64(64).unwrap(), 0xa6ba25526f0a6aba);
+
+    let mut reader = BitReader::new(bytes);
+    assert_eq!(reader.read_u32(32).unwrap(), 0x4a1e39bb);
+    assert_eq!(reader.read_u32(32).unwrap(), 0xd007ca9a);
+    assert_eq!(reader.read_u32(32).unwrap(), 0xa6ba2552);
+    assert_eq!(reader.read_u32(32).unwrap(), 0x6f0a6aba);
+
+    let mut reader = BitReader::new(bytes);
+    assert_eq!(reader.read_u16(16).unwrap(), 0x4a1e);
+    assert_eq!(reader.read_u16(16).unwrap(), 0x39bb);
+    assert_eq!(reader.read_u16(16).unwrap(), 0xd007);
+    assert_eq!(reader.read_u16(16).unwrap(), 0xca9a);
+    assert_eq!(reader.read_u16(16).unwrap(), 0xa6ba);
+    assert_eq!(reader.read_u16(16).unwrap(), 0x2552);
+    assert_eq!(reader.read_u16(16).unwrap(), 0x6f0a);
+    assert_eq!(reader.read_u16(16).unwrap(), 0x6aba);
+
+    let mut reader = BitReader::new(&bytes[..]);
+    for byte in bytes {
+        assert_eq!(reader.read_u8(8).unwrap(), *byte);
+    }
+}
+
+#[test]
+fn skipping_and_zero_reads() {
+    let bytes = &[
+        0b1011_0101, 0b1110_1010, 0b1010_1100,
+    ];
+
+    let mut reader = BitReader::new(bytes);
+
+    assert_eq!(reader.read_u8(4).unwrap(), 0b1011);
+    // Reading zero bits should be a no-op
+    assert_eq!(reader.read_u8(0).unwrap(), 0b0);
+    assert_eq!(reader.read_u8(4).unwrap(), 0b0101);
+    reader.skip(3).unwrap(); // 0b111
+    assert_eq!(reader.read_u16(10).unwrap(), 0b0101010101);
+    assert_eq!(reader.read_u8(3).unwrap(), 0b100);
+}
+
+#[test]
+fn errors() {
+    let bytes = &[
+        0b1011_0101, 0b1110_1010, 0b1010_1100,
+    ];
+
+    let mut reader = BitReader::new(bytes);
+    assert_eq!(reader.read_u8(4).unwrap(), 0b1011);
+    assert_eq!(reader.read_u8(9).unwrap_err(), BitReaderError::TooManyBitsForType {
+        position: 4,
+        requested: 9,
+        allowed: 8
+    });
+    // If an error happens, it should be possible to resume as if nothing had happened
+    assert_eq!(reader.read_u8(4).unwrap(), 0b0101);
+
+    let mut reader = BitReader::new(bytes);
+    assert_eq!(reader.read_u8(4).unwrap(), 0b1011);
+    // Same with this error
+    assert_eq!(reader.read_u32(21).unwrap_err(), BitReaderError::NotEnoughData {
+        position: 4,
+        length: (bytes.len() * 8) as u64,
+        requested: 21
+    });
+    assert_eq!(reader.read_u8(4).unwrap(), 0b0101);
+}
+
+#[test]
+fn signed_values() {
+    let from = -2048;
+    let to = 2048;
+    for x in from..to {
+        let bytes = &[
+            (x >> 8) as u8,
+            x as u8,
+        ];
+        let mut reader = BitReader::new(bytes);
+        assert_eq!(reader.read_u8(4).unwrap(), if x < 0 { 0b1111 } else { 0 });
+        assert_eq!(reader.read_i16(12).unwrap(), x);
+    }
+}
--- a/toolkit/library/gtest/rust/Cargo.lock
+++ b/toolkit/library/gtest/rust/Cargo.lock
@@ -3,16 +3,21 @@ name = "gkrust-gtest"
 version = "0.1.0"
 dependencies = [
  "gkrust-shared 0.1.0",
  "mp4parse-gtest 0.1.0",
  "nsstring-gtest 0.1.0",
 ]
 
 [[package]]
+name = "bitreader"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
 name = "byteorder"
 version = "0.5.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "gkrust-shared"
 version = "0.1.0"
 dependencies = [
@@ -40,16 +45,17 @@ source = "registry+https://github.com/ru
 name = "matches"
 version = "0.1.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "mp4parse"
 version = "0.6.0"
 dependencies = [
+ "bitreader 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "mp4parse-gtest"
 version = "0.1.0"
 
 [[package]]
@@ -98,15 +104,16 @@ name = "url"
 version = "1.2.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "idna 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [metadata]
+"checksum bitreader 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b245039eddbd1a051b8bfa5d5b6afaad6d34d172057a15d561e80b50b4978e8d"
 "checksum byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855"
 "checksum idna 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1053236e00ce4f668aeca4a769a09b3bf5a682d802abd6f3cb39374f6b162c11"
 "checksum libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)" = "408014cace30ee0f767b1c4517980646a573ec61a57957aeeabcac8ac0a02e8d"
 "checksum matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bcc3ad8109fa4b522f9b0cd81440422781f564aaf8c195de6b9d6642177ad0dd"
 "checksum unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c1f7ceb96afdfeedee42bade65a0d585a6a0106f681b6749c8ff4daa8df30b3f"
 "checksum unicode-normalization 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "26643a2f83bac55f1976fb716c10234485f9202dcd65cfbdf9da49867b271172"
 "checksum url 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f024e241a55f5c88401595adc1d4af0c9649e91da82d0e190fe55950231ae575"
--- a/toolkit/library/rust/Cargo.lock
+++ b/toolkit/library/rust/Cargo.lock
@@ -1,16 +1,21 @@
 [root]
 name = "gkrust"
 version = "0.1.0"
 dependencies = [
  "gkrust-shared 0.1.0",
 ]
 
 [[package]]
+name = "bitreader"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
 name = "byteorder"
 version = "0.5.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "gkrust-shared"
 version = "0.1.0"
 dependencies = [
@@ -38,16 +43,17 @@ source = "registry+https://github.com/ru
 name = "matches"
 version = "0.1.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 
 [[package]]
 name = "mp4parse"
 version = "0.6.0"
 dependencies = [
+ "bitreader 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [[package]]
 name = "mp4parse_capi"
 version = "0.6.0"
 dependencies = [
  "byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -85,15 +91,16 @@ name = "url"
 version = "1.2.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "idna 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
  "matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
 ]
 
 [metadata]
+"checksum bitreader 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b245039eddbd1a051b8bfa5d5b6afaad6d34d172057a15d561e80b50b4978e8d"
 "checksum byteorder 0.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0fc10e8cc6b2580fda3f36eb6dc5316657f812a3df879a44a66fc9f0fdbc4855"
 "checksum idna 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1053236e00ce4f668aeca4a769a09b3bf5a682d802abd6f3cb39374f6b162c11"
 "checksum libc 0.2.16 (registry+https://github.com/rust-lang/crates.io-index)" = "408014cace30ee0f767b1c4517980646a573ec61a57957aeeabcac8ac0a02e8d"
 "checksum matches 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bcc3ad8109fa4b522f9b0cd81440422781f564aaf8c195de6b9d6642177ad0dd"
 "checksum unicode-bidi 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c1f7ceb96afdfeedee42bade65a0d585a6a0106f681b6749c8ff4daa8df30b3f"
 "checksum unicode-normalization 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "26643a2f83bac55f1976fb716c10234485f9202dcd65cfbdf9da49867b271172"
 "checksum url 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f024e241a55f5c88401595adc1d4af0c9649e91da82d0e190fe55950231ae575"