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
extern crate byteorder;
use std::io::prelude::*;
use std::io::{BufReader, Read, SeekFrom};
use std::fs::File;
use std::convert::TryInto;
mod atoms;
use crate::atoms::*;
const HEADER_SIZE: u32 = 8;
#[derive(Debug)]
pub enum Error {
InvalidData(&'static str),
}
#[derive(Debug, PartialEq)]
pub enum TrackType {
Audio,
Video,
Metadata,
Unknown,
}
#[derive(Debug, Default)]
pub struct BMFF {
pub ftyp: FtypBox,
pub moov: Option<MoovBox>,
pub size: u64,
}
impl BMFF {
fn new() -> BMFF {
Default::default()
}
}
#[derive(Debug, Clone, Copy)]
struct BoxHeader {
name: BoxType,
size: u64,
offset: u64,
}
pub fn read_mp4(f: File) -> Result<BMFF> {
let bmff = read_boxes(f).unwrap();
Ok(bmff)
}
fn read_boxes(f: File) -> Result<BMFF> {
let filesize = f.metadata().unwrap().len();
let mut reader = BufReader::new(f);
let mut bmff = BMFF::new();
bmff.size = filesize;
let mut start = 0u64;
while start < filesize {
let header = read_box_header(&mut reader, start).unwrap();
let BoxHeader{ name, size, offset: _ } = header;
match name {
BoxType::FtypBox => {
let ftyp = parse_ftyp_box(&mut reader, 0, size as u32).unwrap();
bmff.ftyp = ftyp;
}
BoxType::FreeBox => {
start = 0;
}
BoxType::MdatBox => {
start = (size as u32 - HEADER_SIZE) as u64;
}
BoxType::MoovBox => {
let moov = parse_moov_box(&mut reader, 0, size as u32).unwrap();
bmff.moov = Some(moov);
}
BoxType::MoofBox => {
start = (size as u32 - HEADER_SIZE) as u64;
}
_ => break
};
}
Ok(bmff)
}
fn read_box_header(reader: &mut BufReader<File>, start: u64) -> Result<BoxHeader> {
let _r = reader.seek(SeekFrom::Current(start as i64));
let mut buf = [0u8;8];
reader.read(&mut buf).unwrap();
let s = buf[0..4].try_into().unwrap();
let size = u32::from_be_bytes(s);
let t = buf[4..8].try_into().unwrap();
let typ = u32::from_be_bytes(t);
let offset = match size {
1 => 4 + 4 + 8,
_ => 4 + 4,
};
Ok(BoxHeader {
name: BoxType::from(typ),
size: size as u64,
offset: offset as u64,
})
}