scuffle_mp4/boxes/types/
mdia.rs

1use std::io;
2
3use bytes::{Buf, Bytes};
4
5use super::hdlr::Hdlr;
6use super::mdhd::Mdhd;
7use super::minf::Minf;
8use crate::boxes::DynBox;
9use crate::boxes::header::BoxHeader;
10use crate::boxes::traits::BoxType;
11
12#[derive(Debug, Clone, PartialEq)]
13/// Media Box
14/// ISO/IEC 14496-12:2022(E) - 8.4
15pub struct Mdia {
16    pub header: BoxHeader,
17    pub mdhd: Mdhd,
18    pub hdlr: Hdlr,
19    pub minf: Minf,
20    pub unknown: Vec<DynBox>,
21}
22
23impl Mdia {
24    pub fn new(mdhd: Mdhd, hdlr: Hdlr, minf: Minf) -> Self {
25        Self {
26            header: BoxHeader::new(Self::NAME),
27            mdhd,
28            hdlr,
29            minf,
30            unknown: Vec::new(),
31        }
32    }
33}
34
35impl BoxType for Mdia {
36    const NAME: [u8; 4] = *b"mdia";
37
38    fn demux(header: BoxHeader, data: Bytes) -> io::Result<Self> {
39        let mut reader = io::Cursor::new(data);
40        let mut mdhd = None;
41        let mut hdlr = None;
42        let mut minf = None;
43        let mut unknown = Vec::new();
44
45        while reader.has_remaining() {
46            let dyn_box = DynBox::demux(&mut reader)?;
47
48            match dyn_box {
49                DynBox::Mdhd(b) => {
50                    mdhd = Some(*b);
51                }
52                DynBox::Hdlr(b) => {
53                    hdlr = Some(*b);
54                }
55                DynBox::Minf(b) => {
56                    minf = Some(*b);
57                }
58                _ => {
59                    unknown.push(dyn_box);
60                }
61            }
62        }
63
64        let mdhd = mdhd.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "mdia box is missing mdhd box"))?;
65
66        let hdlr = hdlr.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "mdia box is missing hdlr box"))?;
67
68        let minf = minf.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "mdia box is missing minf box"))?;
69
70        Ok(Self {
71            header,
72            mdhd,
73            hdlr,
74            minf,
75            unknown,
76        })
77    }
78
79    fn primitive_size(&self) -> u64 {
80        self.mdhd.size() // mdhd
81        + self.hdlr.size() // hdlr
82        + self.minf.size() // minf
83        + self.unknown.iter().map(|b| b.size()).sum::<u64>() // unknown boxes
84    }
85
86    fn primitive_mux<W: io::Write>(&self, writer: &mut W) -> io::Result<()> {
87        self.mdhd.mux(writer)?;
88        self.hdlr.mux(writer)?;
89        self.minf.mux(writer)?;
90
91        for b in &self.unknown {
92            b.mux(writer)?;
93        }
94
95        Ok(())
96    }
97}