mp4box 0.10.0

MP4/ISOBMFF parser and editor: box trees, typed decoding, sample tables, fragmented MP4, and non-destructive editing
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
use crate::util::ReadExt;
use crate::{
    boxes::{BoxRef, NodeKind},
    parser::read_box_header,
    registry::{BoxValue, Registry, default_registry},
    util::{hex_dump, read_slice},
};
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>> {
    get_boxes_with_registry(r, size, decode, &default_registry())
}

/// Like [`get_boxes`], but recovers from malformed boxes instead of failing:
/// returns the tree that could be parsed together with a list of
/// [`ParseIssue`](crate::parser::ParseIssue)s (offset + description) for
/// everything that couldn't.
///
/// A clean file returns an empty issue list and the same tree as
/// [`get_boxes`]. Damage is contained to the enclosing container: a corrupt
/// child abandons the rest of *its* container while siblings and ancestors
/// keep parsing, and a box whose interior fails to parse is kept as an
/// opaque leaf.
///
/// ```no_run
/// use mp4box::get_boxes_tolerant;
/// use std::fs::File;
///
/// let mut file = File::open("damaged.mp4")?;
/// let size = file.metadata()?.len();
/// let (boxes, issues) = get_boxes_tolerant(&mut file, size, true)?;
/// println!("parsed {} top-level boxes", boxes.len());
/// for issue in &issues {
///     eprintln!("warning: {}", issue);
/// }
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn get_boxes_tolerant<R: Read + Seek>(
    r: &mut R,
    size: u64,
    decode: bool,
) -> anyhow::Result<(Vec<Box>, Vec<crate::parser::ParseIssue>)> {
    let (boxes, issues) = crate::parser::parse_boxes_tolerant(r, 0, size)?;
    let reg = default_registry();
    let json_boxes = boxes
        .iter()
        .map(|b| build_box(r, b, decode, &reg))
        .collect();
    Ok((json_boxes, issues))
}

/// Like [`get_boxes`], but decodes with a caller-supplied [`Registry`]
/// instead of the default one.
///
/// To *extend* the default registry with custom decoders (rather than
/// replace it), build on [`default_registry`]:
///
/// ```no_run
/// use mp4box::{BoxKey, FourCC, get_boxes_with_registry};
/// use mp4box::registry::{BoxDecoder, BoxValue, default_registry};
/// use std::fs::File;
/// use std::io::Read;
///
/// struct MyDecoder;
/// impl BoxDecoder for MyDecoder {
///     fn decode(
///         &self,
///         r: &mut dyn Read,
///         _hdr: &mp4box::BoxHeader,
///         _version: Option<u8>,
///         _flags: Option<u32>,
///     ) -> anyhow::Result<BoxValue> {
///         let mut buf = Vec::new();
///         r.read_to_end(&mut buf)?;
///         Ok(BoxValue::Text(format!("{} payload bytes", buf.len())))
///     }
/// }
///
/// let reg = default_registry().with_decoder(
///     BoxKey::FourCC(FourCC(*b"xyz ")),
///     "xyz ",
///     Box::new(MyDecoder),
/// );
///
/// let mut file = File::open("video.mp4")?;
/// let size = file.metadata()?.len();
/// let boxes = get_boxes_with_registry(&mut file, size, true, &reg)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn get_boxes_with_registry<R: Read + Seek>(
    r: &mut R,
    size: u64,
    decode: bool,
    reg: &Registry,
) -> anyhow::Result<Vec<Box>> {
    let boxes = crate::parser::parse_boxes(r, 0, size)?;

    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,
            ..
        }
        | NodeKind::FullContainer {
            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,
            ..
        }
        | NodeKind::FullContainer {
            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, .. }
        | crate::boxes::NodeKind::FullContainer { 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)) => (Some(data.summary()), 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))
        }
        NodeKind::FullContainer {
            version,
            flags,
            children: kids,
            ..
        } => {
            let child_nodes = kids.iter().map(|c| build_box(r, c, decode, reg)).collect();
            (
                Some(*version),
                Some(*flags),
                "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_be()?;

            let data_start = r.stream_position()?;
            let data_len = box_end.saturating_sub(data_start) as usize;
            if data_len == 0 {
                return Ok(None);
            }
            let mut buf = vec![0u8; data_len];
            r.read_exact(&mut buf)?;

            return Ok(match type_code {
                // 1 = UTF-8 text
                1 => {
                    let s = String::from_utf8_lossy(&buf).trim().to_string();
                    (!s.is_empty()).then_some(s)
                }
                // 21/22 = signed/unsigned big-endian integer
                21 | 22 => decode_be_int(&buf, type_code == 21),
                // 0 = implicit; trkn/disk use [2 zero bytes][u16 index][u16 total]
                0 if buf.len() >= 6 => {
                    let index = u16::from_be_bytes([buf[2], buf[3]]);
                    let total = u16::from_be_bytes([buf[4], buf[5]]);
                    if index == 0 {
                        None
                    } else if total > 0 {
                        Some(format!("{}/{}", index, total))
                    } else {
                        Some(index.to_string())
                    }
                }
                _ => None,
            });
        }

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

/// Decode a big-endian integer of 1/2/4/8 bytes as written by iTunes
/// `data` atoms (type 21 signed, 22 unsigned).
fn decode_be_int(buf: &[u8], signed: bool) -> Option<String> {
    let v: i64 = match buf.len() {
        1 => {
            if signed {
                buf[0] as i8 as i64
            } else {
                buf[0] as i64
            }
        }
        2 => {
            let raw = u16::from_be_bytes([buf[0], buf[1]]);
            if signed {
                raw as i16 as i64
            } else {
                raw as i64
            }
        }
        4 => {
            let raw = u32::from_be_bytes(buf[..4].try_into().ok()?);
            if signed {
                raw as i32 as i64
            } else {
                raw as i64
            }
        }
        8 => i64::from_be_bytes(buf[..8].try_into().ok()?),
        _ => return None,
    };
    Some(v.to_string())
}

/// 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"gnre" => Some("genre"),
        b"\xa9cmt" => Some("comment"),
        b"\xa9des" => Some("description"),
        b"desc" => Some("description"),
        b"cprt" => Some("copyright"),
        b"aART" => Some("album_artist"),
        b"\xa9too" => Some("encoder"),
        b"\xa9wrt" => Some("composer"),
        b"\xa9lyr" => Some("lyrics"),
        b"\xa9grp" => Some("grouping"),
        b"tmpo" => Some("tempo"),
        b"trkn" => Some("track"),
        b"disk" => Some("disc"),
        _ => None,
    }
}