mp4box 0.8.0

Minimal MP4/ISOBMFF parser with JSON output, box decoding, and UUID support
Documentation
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use crate::{
    boxes::{BoxRef, NodeKind},
    parser::read_box_header,
    registry::{BoxValue, Registry, default_registry},
    util::{hex_dump, read_slice},
};
use byteorder::{BigEndian, ReadBytesExt};
use serde::Serialize;
use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom};

/// A JSON-serializable representation of a single MP4 box.
///
/// This structure contains all the metadata and content information about an MP4 box,
/// making it suitable for serialization to JSON for use in web UIs, CLIs, or APIs.
#[derive(Serialize)]
pub struct Box {
    /// Absolute byte offset of this box in the file
    pub offset: u64,
    /// Total size of this box including header and payload
    pub size: u64,
    /// Size of just the box header (8 bytes for normal boxes, 16+ for large boxes)
    pub header_size: u64,
    /// Absolute offset where payload data starts (None for containers)
    pub payload_offset: Option<u64>,
    /// Size of payload data (None for containers)
    pub payload_size: Option<u64>,

    /// Four-character box type code (e.g., "ftyp", "moov")
    pub typ: String,
    /// UUID for UUID boxes (16-byte hex string)
    pub uuid: Option<String>,
    /// Version field for FullBox types
    pub version: Option<u8>,
    /// Flags field for FullBox types  
    pub flags: Option<u32>,
    /// Box classification: "leaf", "full", "container", or "unknown"
    pub kind: String,
    /// Human-readable box type name (e.g., "File Type Box")
    pub full_name: String,
    /// Decoded box content if decode=true and decoder available
    pub decoded: Option<String>,
    /// Structured data if decode=true and structured decoder available
    pub structured_data: Option<crate::registry::StructuredData>,
    /// Child boxes for container types
    pub children: Option<Vec<Box>>,
}

/// Parse an MP4/ISOBMFF file and return the complete box tree as JSON-serializable structures.
///
/// # Parameters
/// - `r`: A reader that implements `Read + Seek` (e.g., `File`, `Cursor<Vec<u8>>`)
/// - `size`: The total size of the MP4 data to parse (typically file length)  
/// - `decode`: Whether to decode known box types using the default registry
///
/// # Returns
/// A vector of `Box` structs representing the top-level boxes in the file.
/// Each box contains metadata (offset, size, type) and optionally decoded content.
///
/// # Example
/// ```no_run
/// use mp4box::get_boxes;
/// use std::fs::File;
///
/// let mut file = File::open("video.mp4")?;
/// let size = file.metadata()?.len();
/// let boxes = get_boxes(&mut file, size, true)?; // decode known boxes
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn get_boxes<R: Read + Seek>(r: &mut R, size: u64, decode: bool) -> anyhow::Result<Vec<Box>> {
    // let mut f = File::open(&path)?;
    // let file_len = f.metadata()?.len();

    // parse top-level boxes
    let mut boxes = Vec::new();
    while r.stream_position()? < size {
        let h = read_box_header(r)?;
        let box_end = if h.size == 0 { size } else { h.start + h.size };

        let kind = if crate::known_boxes::KnownBox::from(h.typ).is_container() {
            r.seek(SeekFrom::Start(h.start + h.header_size))?;
            NodeKind::Container(crate::parser::parse_children(r, box_end)?)
        } else if crate::known_boxes::KnownBox::from(h.typ).is_full_box() {
            r.seek(SeekFrom::Start(h.start + h.header_size))?;
            let version = r.read_u8()?;
            let mut fl = [0u8; 3];
            r.read_exact(&mut fl)?;
            let flags = ((fl[0] as u32) << 16) | ((fl[1] as u32) << 8) | (fl[2] as u32);
            let data_offset = r.stream_position()?;
            let data_len = box_end.saturating_sub(data_offset);
            NodeKind::FullBox {
                version,
                flags,
                data_offset,
                data_len,
            }
        } else {
            let data_offset = h.start + h.header_size;
            let data_len = box_end.saturating_sub(data_offset);
            if &h.typ.0 == b"uuid" {
                NodeKind::Unknown {
                    data_offset,
                    data_len,
                }
            } else {
                NodeKind::Leaf {
                    data_offset,
                    data_len,
                }
            }
        };

        r.seek(SeekFrom::Start(box_end))?;
        boxes.push(BoxRef { hdr: h, kind });
    }

    // build JSON tree
    let reg = default_registry();
    let json_boxes = boxes
        .iter()
        .map(|b| build_box(r, b, decode, &reg))
        .collect();

    Ok(json_boxes)
}

fn payload_region(b: &BoxRef) -> Option<(crate::boxes::BoxKey, u64, u64)> {
    let key = if &b.hdr.typ.0 == b"uuid" {
        crate::boxes::BoxKey::Uuid(b.hdr.uuid.unwrap())
    } else {
        crate::boxes::BoxKey::FourCC(b.hdr.typ)
    };

    match &b.kind {
        NodeKind::FullBox {
            data_offset,
            data_len,
            ..
        } => Some((key, *data_offset, *data_len)),
        NodeKind::Leaf { .. } | NodeKind::Unknown { .. } => {
            let hdr = &b.hdr;
            if hdr.size == 0 {
                return None;
            }
            let off = hdr.start + hdr.header_size;
            let len = hdr.size.saturating_sub(hdr.header_size);
            if len == 0 {
                return None;
            }
            Some((key, off, len))
        }
        NodeKind::Container(_) => None,
    }
}

fn payload_geometry(b: &BoxRef) -> Option<(u64, u64)> {
    match &b.kind {
        NodeKind::FullBox {
            data_offset,
            data_len,
            ..
        } => Some((*data_offset, *data_len)),
        NodeKind::Leaf { .. } | NodeKind::Unknown { .. } => {
            let hdr = &b.hdr;
            if hdr.size == 0 {
                return None;
            }
            let off = hdr.start + hdr.header_size;
            let len = hdr.size.saturating_sub(hdr.header_size);
            if len == 0 {
                return None;
            }
            Some((off, len))
        }
        NodeKind::Container(_) => None,
    }
}

fn decode_value<R: Read + Seek>(
    r: &mut R,
    b: &BoxRef,
    reg: &Registry,
) -> (Option<String>, Option<crate::registry::StructuredData>) {
    let (key, off, len) = match payload_region(b) {
        Some(region) => region,
        None => return (None, None),
    };
    if len == 0 {
        return (None, None);
    }

    if r.seek(SeekFrom::Start(off)).is_err() {
        return (None, None);
    }
    let mut limited = r.take(len);

    // Extract version and flags from the box if it's a FullBox
    let (version, flags) = match &b.kind {
        crate::boxes::NodeKind::FullBox { version, flags, .. } => (Some(*version), Some(*flags)),
        _ => (None, None),
    };

    if let Some(res) = reg.decode(&key, &mut limited, &b.hdr, version, flags) {
        match res {
            Ok(BoxValue::Text(s)) => (Some(s), None),
            Ok(BoxValue::Bytes(bytes)) => (Some(format!("{} bytes", bytes.len())), None),
            Ok(BoxValue::Structured(data)) => {
                let debug_str = format!("structured: {:?}", data);
                (Some(debug_str), Some(data))
            }
            Err(e) => (Some(format!("[decode error: {}]", e)), None),
        }
    } else {
        (None, None)
    }
}

fn build_box<R: Read + Seek>(r: &mut R, b: &BoxRef, decode: bool, reg: &Registry) -> Box {
    let hdr = &b.hdr;
    let uuid_str = hdr
        .uuid
        .map(|u| u.iter().map(|b| format!("{:02x}", b)).collect::<String>());

    let kb = crate::known_boxes::KnownBox::from(hdr.typ);
    let full_name = kb.full_name().to_string();

    // basic geometry
    let header_size = hdr.header_size;
    let (payload_offset, payload_size) = payload_geometry(b)
        .map(|(off, len)| (Some(off), Some(len)))
        .unwrap_or((None, None));

    let (version, flags, kind_str, children) = match &b.kind {
        NodeKind::FullBox { version, flags, .. } => {
            (Some(*version), Some(*flags), "full".to_string(), None)
        }
        NodeKind::Leaf { .. } => (None, None, "leaf".to_string(), None),
        NodeKind::Unknown { .. } => (None, None, "unknown".to_string(), None),
        NodeKind::Container(kids) => {
            let child_nodes = kids.iter().map(|c| build_box(r, c, decode, reg)).collect();
            (None, None, "container".to_string(), Some(child_nodes))
        }
    };

    let (decoded, structured_data) = if decode {
        decode_value(r, b, reg)
    } else {
        (None, None)
    };

    Box {
        offset: hdr.start,
        size: hdr.size,
        header_size,
        payload_offset,
        payload_size,

        typ: hdr.typ.to_string(),
        uuid: uuid_str,
        version,
        flags,
        kind: kind_str,
        full_name,
        decoded,
        structured_data,
        children,
    }
}

/// Result of a hex dump operation containing the formatted hex output.
#[derive(Serialize)]
pub struct HexDump {
    /// Starting offset of the dumped data
    pub offset: u64,
    /// Actual number of bytes that were read and dumped
    pub length: u64,
    /// Formatted hex dump string with addresses and ASCII representation
    pub hex: String,
}

/// Hex-dump a range of bytes from an MP4 data source.
///
/// # Parameters
/// - `r`: A reader that implements `Read + Seek`
/// - `size`: The total size of the data (typically file length)
/// - `offset`: Byte offset to start reading from
/// - `max_len`: Maximum number of bytes to read
///
/// This function never reads past EOF; if `offset + max_len` goes beyond the data size,
/// the returned length will be smaller than `max_len`.
///
/// This is useful for building a hex viewer UI:
///
/// ```no_run
/// use mp4box::hex_range;
/// use std::fs::File;
///
/// fn main() -> anyhow::Result<()> {
///     let mut file = File::open("video.mp4")?;
///     let size = file.metadata()?.len();
///     let dump = hex_range(&mut file, size, 0, 256)?;
///     println!("{}", dump.hex);
///     Ok(())
/// }
/// ```
pub fn hex_range<R: Read + Seek>(
    r: &mut R,
    size: u64,
    offset: u64,
    max_len: u64,
) -> anyhow::Result<HexDump> {
    use std::cmp::min;

    // let path = path.as_ref().to_path_buf();
    // let mut f = File::open(&path)?;
    // let file_len = f.metadata()?.len();

    // How many bytes are actually available from this offset to EOF.
    let available = size.saturating_sub(offset);

    // Don't read past EOF or more than the caller requested.
    let to_read = min(available, max_len);

    // If nothing is available, just return an empty dump.
    if to_read == 0 {
        return Ok(HexDump {
            offset,
            length: 0,
            hex: String::new(),
        });
    }

    let data = read_slice(r, offset, to_read)?;
    let hex_str = hex_dump(&data, offset);

    Ok(HexDump {
        offset,
        length: to_read, // <-- IMPORTANT: actual bytes read, not max_len
        hex: hex_str,
    })
}

/// Extract iTunes metadata tags from an MP4 file.
///
/// Navigates `moov → udta → meta → ilst` and returns a map of tag name to value
/// for any recognized iTunes metadata atoms (e.g. `©nam`, `©ART`, `©day`).
///
/// Keys returned match ffmpeg's `-metadata` flag names: `title`, `artist`, `album`,
/// `year`, `genre`, `comment`, `description`, `copyright`, `album_artist`.
///
/// Returns an empty map if the file has no iTunes metadata or the box tree is absent.
///
/// # Example
/// ```no_run
/// use mp4box::get_itunes_tags;
/// use std::fs::File;
///
/// let mut file = File::open("video.mp4")?;
/// let size = file.metadata()?.len();
/// let tags = get_itunes_tags(&mut file, size)?;
/// if let Some(title) = tags.get("title") {
///     println!("Title: {}", title);
/// }
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn get_itunes_tags<R: Read + Seek>(
    r: &mut R,
    size: u64,
) -> anyhow::Result<HashMap<String, String>> {
    // moov
    let moov = match find_box_in_range(r, 0, size, b"moov")? {
        Some(h) => h,
        None => return Ok(HashMap::new()),
    };
    let moov_content = moov.start + moov.header_size;
    let moov_end = moov.start + moov.size;

    // udta
    let udta = match find_box_in_range(r, moov_content, moov_end, b"udta")? {
        Some(h) => h,
        None => return Ok(HashMap::new()),
    };
    let udta_content = udta.start + udta.header_size;
    let udta_end = udta.start + udta.size;

    // meta — a FullBox in practice (ffmpeg always writes version+flags), so skip 4 bytes
    let meta = match find_box_in_range(r, udta_content, udta_end, b"meta")? {
        Some(h) => h,
        None => return Ok(HashMap::new()),
    };
    let meta_end = meta.start + meta.size;
    let meta_content = meta.start + meta.header_size + 4; // skip version (1) + flags (3)

    // ilst
    let ilst = match find_box_in_range(r, meta_content, meta_end, b"ilst")? {
        Some(h) => h,
        None => return Ok(HashMap::new()),
    };
    let ilst_content = ilst.start + ilst.header_size;
    let ilst_end = ilst.start + ilst.size;

    // Each child of ilst is a tag atom (e.g. ©nam, ©ART). Unknown to the registry,
    // so we iterate them manually and look for their `data` FullBox child.
    let mut tags = HashMap::new();
    r.seek(SeekFrom::Start(ilst_content))?;

    while r.stream_position()? + 8 <= ilst_end {
        let tag_hdr = read_box_header(r)?;
        let tag_end = if tag_hdr.size == 0 {
            ilst_end
        } else {
            tag_hdr.start + tag_hdr.size
        };

        if let Some(key) = fourcc_to_tag_key(&tag_hdr.typ.0) {
            let tag_content = tag_hdr.start + tag_hdr.header_size;
            if let Some(value) = extract_ilst_data_value(r, tag_content, tag_end)? {
                tags.insert(key.to_string(), value);
            }
        }

        r.seek(SeekFrom::Start(tag_end))?;
    }

    Ok(tags)
}

/// Scan boxes from `start` to `end`, returning the first one whose fourcc matches `target`.
fn find_box_in_range<R: Read + Seek>(
    r: &mut R,
    start: u64,
    end: u64,
    target: &[u8; 4],
) -> anyhow::Result<Option<crate::boxes::BoxHeader>> {
    r.seek(SeekFrom::Start(start))?;
    while r.stream_position()? + 8 <= end {
        let h = read_box_header(r)?;
        let box_end = if h.size == 0 { end } else { h.start + h.size };
        if &h.typ.0 == target {
            return Ok(Some(h));
        }
        r.seek(SeekFrom::Start(box_end))?;
    }
    Ok(None)
}

/// Within a tag atom (e.g. ©nam), find the `data` FullBox and return its UTF-8 value.
fn extract_ilst_data_value<R: Read + Seek>(
    r: &mut R,
    start: u64,
    end: u64,
) -> anyhow::Result<Option<String>> {
    r.seek(SeekFrom::Start(start))?;
    while r.stream_position()? + 8 <= end {
        let h = read_box_header(r)?;
        let box_end = if h.size == 0 { end } else { h.start + h.size };

        if &h.typ.0 == b"data" {
            // FullBox header: version (1 byte) + flags (3 bytes) = type indicator
            let _version = r.read_u8()?;
            let mut fl = [0u8; 3];
            r.read_exact(&mut fl)?;
            let type_code = ((fl[0] as u32) << 16) | ((fl[1] as u32) << 8) | (fl[2] as u32);

            // 4-byte locale field (ignored)
            r.read_u32::<BigEndian>()?;

            let data_start = r.stream_position()?;
            let data_len = box_end.saturating_sub(data_start) as usize;

            // type_code 1 = UTF-8
            if type_code == 1 && data_len > 0 {
                let mut buf = vec![0u8; data_len];
                r.read_exact(&mut buf)?;
                let s = String::from_utf8_lossy(&buf).trim().to_string();
                if !s.is_empty() {
                    return Ok(Some(s));
                }
            }
            return Ok(None);
        }

        r.seek(SeekFrom::Start(box_end))?;
    }
    Ok(None)
}

/// Map iTunes atom fourccs to ffmpeg-compatible metadata key names.
fn fourcc_to_tag_key(fourcc: &[u8; 4]) -> Option<&'static str> {
    match fourcc {
        b"\xa9nam" => Some("title"),
        b"\xa9ART" => Some("artist"),
        b"\xa9alb" => Some("album"),
        b"\xa9day" => Some("year"),
        b"\xa9gen" => Some("genre"),
        b"\xa9cmt" => Some("comment"),
        b"\xa9des" => Some("description"),
        b"desc" => Some("description"),
        b"cprt" => Some("copyright"),
        b"aART" => Some("album_artist"),
        _ => None,
    }
}