1
0
Fork 0
mirror of https://github.com/alfg/mp4-rust.git synced 2024-05-20 01:08:06 +00:00
mp4-rust/src/reader.rs
oftheforest 7cfdffbd71
Fix several overflows in box and track processing (#94)
* Fix several overflows in box and track processing

* Use size_of::<Type>() instead of magic numbers

* Fix a panic in Mp4Track::read_sample() for one-past-the-end

This appears to be a bug unmasked by other changes. read_sample() calls
sample_offset() then sample_size(), and assumes that if the former returns Ok
then the latter does as well. However, if the sample_id is one past the end,
sample_offset() might succeed (it only checks samples _up to_ the given
sample_id but not _including_ it) while sample_size() fails (because the sample
doesn't exist). read_sample() will then panic.

Fix this by duplicating the error propagation (that is currently done for
sample_offset) for sample_size, instead of unwrapping. This is a cautious
change that fixes the bug; alternatively, having sample_offset() call
sample_size() on the given sample_id and propagate any error might also work.

* Account for header size in box processing overflow fixes

* Ensure that boxes aren't bigger than their containers

Together with the entry_count checks, this eliminates several OOMs when reading
incorrect mp4 files.

* Fix order of arithmetic operations

This was due to an incorrect transcription when switching to checked
arithmetic, and fixes a bug that could cause attempted lookups of the wrong
chunk_id.
2023-02-18 11:46:51 -08:00

187 lines
5.3 KiB
Rust

use std::collections::HashMap;
use std::io::{Read, Seek};
use std::time::Duration;
use crate::meta::MetaBox;
use crate::*;
#[derive(Debug)]
pub struct Mp4Reader<R> {
reader: R,
pub ftyp: FtypBox,
pub moov: MoovBox,
pub moofs: Vec<MoofBox>,
pub emsgs: Vec<EmsgBox>,
tracks: HashMap<u32, Mp4Track>,
size: u64,
}
impl<R: Read + Seek> Mp4Reader<R> {
pub fn read_header(mut reader: R, size: u64) -> Result<Self> {
let start = reader.stream_position()?;
let mut ftyp = None;
let mut moov = None;
let mut moofs = Vec::new();
let mut emsgs = Vec::new();
let mut current = start;
while current < size {
// Get box header.
let header = BoxHeader::read(&mut reader)?;
let BoxHeader { name, size: s } = header;
if s > size {
return Err(Error::InvalidData(
"file contains a box with a larger size than it",
));
}
// Break if size zero BoxHeader, which can result in dead-loop.
if s == 0 {
break;
}
// Match and parse the atom boxes.
match name {
BoxType::FtypBox => {
ftyp = Some(FtypBox::read_box(&mut reader, s)?);
}
BoxType::FreeBox => {
skip_box(&mut reader, s)?;
}
BoxType::MdatBox => {
skip_box(&mut reader, s)?;
}
BoxType::MoovBox => {
moov = Some(MoovBox::read_box(&mut reader, s)?);
}
BoxType::MoofBox => {
let moof = MoofBox::read_box(&mut reader, s)?;
moofs.push(moof);
}
BoxType::EmsgBox => {
let emsg = EmsgBox::read_box(&mut reader, s)?;
emsgs.push(emsg);
}
_ => {
// XXX warn!()
skip_box(&mut reader, s)?;
}
}
current = reader.stream_position()?;
}
if ftyp.is_none() {
return Err(Error::BoxNotFound(BoxType::FtypBox));
}
if moov.is_none() {
return Err(Error::BoxNotFound(BoxType::MoovBox));
}
let size = current - start;
let mut tracks = if let Some(ref moov) = moov {
if moov.traks.iter().any(|trak| trak.tkhd.track_id == 0) {
return Err(Error::InvalidData("illegal track id 0"));
}
moov.traks
.iter()
.map(|trak| (trak.tkhd.track_id, Mp4Track::from(trak)))
.collect()
} else {
HashMap::new()
};
// Update tracks if any fragmented (moof) boxes are found.
if !moofs.is_empty() {
let mut default_sample_duration = 0;
if let Some(ref moov) = moov {
if let Some(ref mvex) = &moov.mvex {
default_sample_duration = mvex.trex.default_sample_duration
}
}
for moof in moofs.iter() {
for traf in moof.trafs.iter() {
let track_id = traf.tfhd.track_id;
if let Some(track) = tracks.get_mut(&track_id) {
track.default_sample_duration = default_sample_duration;
track.trafs.push(traf.clone())
} else {
return Err(Error::TrakNotFound(track_id));
}
}
}
}
Ok(Mp4Reader {
reader,
ftyp: ftyp.unwrap(),
moov: moov.unwrap(),
moofs,
emsgs,
size,
tracks,
})
}
pub fn size(&self) -> u64 {
self.size
}
pub fn major_brand(&self) -> &FourCC {
&self.ftyp.major_brand
}
pub fn minor_version(&self) -> u32 {
self.ftyp.minor_version
}
pub fn compatible_brands(&self) -> &[FourCC] {
&self.ftyp.compatible_brands
}
pub fn duration(&self) -> Duration {
Duration::from_millis(self.moov.mvhd.duration * 1000 / self.moov.mvhd.timescale as u64)
}
pub fn timescale(&self) -> u32 {
self.moov.mvhd.timescale
}
pub fn is_fragmented(&self) -> bool {
!self.moofs.is_empty()
}
pub fn tracks(&self) -> &HashMap<u32, Mp4Track> {
&self.tracks
}
pub fn sample_count(&self, track_id: u32) -> Result<u32> {
if let Some(track) = self.tracks.get(&track_id) {
Ok(track.sample_count())
} else {
Err(Error::TrakNotFound(track_id))
}
}
pub fn read_sample(&mut self, track_id: u32, sample_id: u32) -> Result<Option<Mp4Sample>> {
if let Some(track) = self.tracks.get(&track_id) {
track.read_sample(&mut self.reader, sample_id)
} else {
Err(Error::TrakNotFound(track_id))
}
}
}
impl<R> Mp4Reader<R> {
pub fn metadata(&self) -> impl Metadata<'_> {
self.moov.udta.as_ref().and_then(|udta| {
udta.meta.as_ref().and_then(|meta| match meta {
MetaBox::Mdir { ilst } => ilst.as_ref(),
_ => None,
})
})
}
}