Skip to content

Commit

Permalink
Merge pull request alfg#27 from alfg/fragmented-boxes
Browse files Browse the repository at this point in the history
Add support for reading/writing fragmented mp4 (fMP4) boxes.
  • Loading branch information
alfg authored Sep 4, 2020
2 parents fc7a165 + 92b50b3 commit a54b823
Show file tree
Hide file tree
Showing 10 changed files with 402 additions and 16 deletions.
11 changes: 11 additions & 0 deletions examples/mp4dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,17 @@ fn get_boxes(file: File) -> Result<Vec<Box>> {
boxes.push(build_box(co64));
}
}

// If fragmented, add moof boxes.
for moof in mp4.moofs.iter() {
boxes.push(build_box(moof));
boxes.push(build_box(&moof.mfhd));
for traf in moof.trafs.iter() {
boxes.push(build_box(traf));
boxes.push(build_box(&traf.tfhd));
}
}

Ok(boxes)
}

Expand Down
6 changes: 3 additions & 3 deletions examples/mp4info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ fn info<P: AsRef<Path>>(filename: &P) -> Result<()> {
println!(" version: {}", mp4.moov.mvhd.version);
println!(" creation time: {}", creation_time(mp4.moov.mvhd.creation_time));
println!(" duration: {:?}", mp4.duration());
println!(" fragments: {:?}", mp4.is_fragmented());
println!(" timescale: {:?}\n", mp4.timescale());

println!("Found {} Tracks", mp4.tracks().len());
Expand All @@ -56,7 +57,6 @@ fn info<P: AsRef<Path>>(filename: &P) -> Result<()> {
media_info
);
}

Ok(())
}

Expand All @@ -70,7 +70,7 @@ fn video_info(track: &Mp4Track) -> Result<String> {
track.width(),
track.height(),
track.bitrate() / 1000,
track.frame_rate_f64()
track.frame_rate()
))
} else {
Ok(format!(
Expand All @@ -80,7 +80,7 @@ fn video_info(track: &Mp4Track) -> Result<String> {
track.width(),
track.height(),
track.bitrate() / 1000,
track.frame_rate_f64()
track.frame_rate()
))
}
}
Expand Down
97 changes: 97 additions & 0 deletions src/mp4box/mfhd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::{Read, Seek, Write};

use crate::mp4box::*;

#[derive(Debug, Clone, PartialEq)]
pub struct MfhdBox {
pub version: u8,
pub flags: u32,
pub sequence_number: u32,
}

impl Default for MfhdBox {
fn default() -> Self {
MfhdBox {
version: 0,
flags: 0,
sequence_number: 1,
}
}
}

impl MfhdBox {
pub fn get_type(&self) -> BoxType {
BoxType::MfhdBox
}

pub fn get_size(&self) -> u64 {
HEADER_SIZE + HEADER_EXT_SIZE + 4
}
}

impl Mp4Box for MfhdBox {
fn box_type(&self) -> BoxType {
return self.get_type();
}

fn box_size(&self) -> u64 {
return self.get_size();
}
}

impl<R: Read + Seek> ReadBox<&mut R> for MfhdBox {
fn read_box(reader: &mut R, size: u64) -> Result<Self> {
let start = box_start(reader)?;

let (version, flags) = read_box_header_ext(reader)?;
let sequence_number = reader.read_u32::<BigEndian>()?;

skip_bytes_to(reader, start + size)?;

Ok(MfhdBox {
version,
flags,
sequence_number,
})
}
}

impl<W: Write> WriteBox<&mut W> for MfhdBox {
fn write_box(&self, writer: &mut W) -> Result<u64> {
let size = self.box_size();
BoxHeader::new(self.box_type(), size).write(writer)?;

write_box_header_ext(writer, self.version, self.flags)?;
writer.write_u32::<BigEndian>(self.sequence_number)?;

Ok(size)
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::mp4box::BoxHeader;
use std::io::Cursor;

#[test]
fn test_mfhd() {
let src_box = MfhdBox {
version: 0,
flags: 0,
sequence_number: 1,
};
let mut buf = Vec::new();
src_box.write_box(&mut buf).unwrap();
assert_eq!(buf.len(), src_box.box_size() as usize);

let mut reader = Cursor::new(&buf);
let header = BoxHeader::read(&mut reader).unwrap();
assert_eq!(header.name, BoxType::MfhdBox);
assert_eq!(src_box.box_size(), header.size);

let dst_box = MfhdBox::read_box(&mut reader, header.size).unwrap();
assert_eq!(src_box, dst_box);
}
}
8 changes: 8 additions & 0 deletions src/mp4box/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ pub(crate) mod mdhd;
pub(crate) mod mdia;
pub(crate) mod minf;
pub(crate) mod moov;
pub(crate) mod moof;
pub(crate) mod mp4a;
pub(crate) mod mvhd;
pub(crate) mod mfhd;
pub(crate) mod smhd;
pub(crate) mod stbl;
pub(crate) mod stco;
Expand All @@ -27,11 +29,14 @@ pub(crate) mod stss;
pub(crate) mod stsz;
pub(crate) mod stts;
pub(crate) mod tkhd;
pub(crate) mod tfhd;
pub(crate) mod trak;
pub(crate) mod traf;
pub(crate) mod vmhd;

pub use ftyp::FtypBox;
pub use moov::MoovBox;
pub use moof::MoofBox;

pub const HEADER_SIZE: u64 = 8;
// const HEADER_LARGE_SIZE: u64 = 16;
Expand Down Expand Up @@ -68,11 +73,13 @@ macro_rules! boxtype {
boxtype! {
FtypBox => 0x66747970,
MvhdBox => 0x6d766864,
MfhdBox => 0x6d666864,
FreeBox => 0x66726565,
MdatBox => 0x6d646174,
MoovBox => 0x6d6f6f76,
MoofBox => 0x6d6f6f66,
TkhdBox => 0x746b6864,
TfhdBox => 0x74666864,
EdtsBox => 0x65647473,
MdiaBox => 0x6d646961,
ElstBox => 0x656c7374,
Expand All @@ -90,6 +97,7 @@ boxtype! {
StcoBox => 0x7374636F,
Co64Box => 0x636F3634,
TrakBox => 0x7472616b,
TrafBox => 0x74726166,
UdtaBox => 0x75647461,
DinfBox => 0x64696e66,
SmhdBox => 0x736d6864,
Expand Down
90 changes: 90 additions & 0 deletions src/mp4box/moof.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use std::io::{Read, Seek, SeekFrom, Write};

use crate::mp4box::*;
use crate::mp4box::{mfhd::MfhdBox, traf::TrafBox};

#[derive(Debug, Clone, PartialEq, Default)]
pub struct MoofBox {
pub mfhd: MfhdBox,
pub trafs: Vec<TrafBox>,
}

impl MoofBox {
pub fn get_type(&self) -> BoxType {
BoxType::MoofBox
}

pub fn get_size(&self) -> u64 {
let mut size = HEADER_SIZE + self.mfhd.box_size();
for traf in self.trafs.iter() {
size += traf.box_size();
}
size
}
}

impl Mp4Box for MoofBox {
fn box_type(&self) -> BoxType {
return self.get_type();
}

fn box_size(&self) -> u64 {
return self.get_size();
}
}

impl<R: Read + Seek> ReadBox<&mut R> for MoofBox {
fn read_box(reader: &mut R, size: u64) -> Result<Self> {
let start = box_start(reader)?;

let mut mfhd = None;
let mut trafs = Vec::new();

let mut current = reader.seek(SeekFrom::Current(0))?;
let end = start + size;
while current < end {
// Get box header.
let header = BoxHeader::read(reader)?;
let BoxHeader { name, size: s } = header;

match name {
BoxType::MfhdBox => {
mfhd = Some(MfhdBox::read_box(reader, s)?);
}
BoxType::TrafBox => {
let traf = TrafBox::read_box(reader, s)?;
trafs.push(traf);
}
_ => {
// XXX warn!()
skip_box(reader, s)?;
}
}
current = reader.seek(SeekFrom::Current(0))?;
}

if mfhd.is_none() {
return Err(Error::BoxNotFound(BoxType::MfhdBox));
}

skip_bytes_to(reader, start + size)?;

Ok(MoofBox {
mfhd: mfhd.unwrap(),
trafs,
})
}
}

impl<W: Write> WriteBox<&mut W> for MoofBox {
fn write_box(&self, writer: &mut W) -> Result<u64> {
let size = self.box_size();
BoxHeader::new(self.box_type(), size).write(writer)?;

self.mfhd.write_box(writer)?;
for traf in self.trafs.iter() {
traf.write_box(writer)?;
}
Ok(0)
}
}
97 changes: 97 additions & 0 deletions src/mp4box/tfhd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::{Read, Seek, Write};

use crate::mp4box::*;

#[derive(Debug, Clone, PartialEq)]
pub struct TfhdBox {
pub version: u8,
pub flags: u32,
pub track_id: u32,
}

impl Default for TfhdBox {
fn default() -> Self {
TfhdBox {
version: 0,
flags: 0,
track_id: 0,
}
}
}

impl TfhdBox {
pub fn get_type(&self) -> BoxType {
BoxType::TfhdBox
}

pub fn get_size(&self) -> u64 {
HEADER_SIZE + HEADER_EXT_SIZE + 4
}
}

impl Mp4Box for TfhdBox {
fn box_type(&self) -> BoxType {
return self.get_type();
}

fn box_size(&self) -> u64 {
return self.get_size();
}
}

impl<R: Read + Seek> ReadBox<&mut R> for TfhdBox {
fn read_box(reader: &mut R, size: u64) -> Result<Self> {
let start = box_start(reader)?;

let (version, flags) = read_box_header_ext(reader)?;
let track_id = reader.read_u32::<BigEndian>()?;

skip_bytes_to(reader, start + size)?;

Ok(TfhdBox {
version,
flags,
track_id,
})
}
}

impl<W: Write> WriteBox<&mut W> for TfhdBox {
fn write_box(&self, writer: &mut W) -> Result<u64> {
let size = self.box_size();
BoxHeader::new(self.box_type(), size).write(writer)?;

write_box_header_ext(writer, self.version, self.flags)?;
writer.write_u32::<BigEndian>(self.track_id)?;

Ok(size)
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::mp4box::BoxHeader;
use std::io::Cursor;

#[test]
fn test_tfhd() {
let src_box = TfhdBox {
version: 0,
flags: 0,
track_id: 1,
};
let mut buf = Vec::new();
src_box.write_box(&mut buf).unwrap();
assert_eq!(buf.len(), src_box.box_size() as usize);

let mut reader = Cursor::new(&buf);
let header = BoxHeader::read(&mut reader).unwrap();
assert_eq!(header.name, BoxType::TfhdBox);
assert_eq!(src_box.box_size(), header.size);

let dst_box = TfhdBox::read_box(&mut reader, header.size).unwrap();
assert_eq!(src_box, dst_box);
}
}
Loading

0 comments on commit a54b823

Please sign in to comment.