async_mp4/mp4box/
box_trait.rs

1use async_trait::async_trait;
2use crate::bytes_read::ReadMp4;
3use crate::bytes_write::WriteMp4;
4use crate::error::MP4Error;
5use crate::header::BoxHeader;
6use crate::r#type::BoxType;
7
8pub trait IBox {
9    fn byte_size(&self) -> usize;
10    const ID: BoxType;
11}
12
13impl<T: IBox> IBox for Vec<T> {
14    fn byte_size(&self) -> usize {
15        self.iter().map(IBox::byte_size).sum()
16    }
17
18    const ID: BoxType = T::ID;
19}
20
21impl<T: IBox> IBox for Option<T> {
22    fn byte_size(&self) -> usize {
23        self.iter().map(IBox::byte_size).sum()
24    }
25
26    const ID: BoxType = T::ID;
27}
28
29#[async_trait]
30pub trait BoxRead: IBox + Sized {
31    async fn read<R: ReadMp4>(header: BoxHeader, reader: &mut R) -> Result<Self, MP4Error>;
32}
33
34pub trait BoxWrite: IBox {
35    fn write<W: WriteMp4>(&self, writer: &mut W) -> Result<usize, MP4Error>;
36}
37
38impl<T: BoxWrite> BoxWrite for Vec<T> {
39    fn write<W: WriteMp4>(&self, writer: &mut W) -> Result<usize, MP4Error> {
40        let mut count = 0;
41        for item in self {
42            count += item.write(writer)?;
43        }
44        Ok(count)
45    }
46}
47
48impl<T: BoxWrite> BoxWrite for Option<T> {
49    fn write<W: WriteMp4>(&self, writer: &mut W) -> Result<usize, MP4Error> {
50        let mut count = 0;
51        if let Some(item) = self {
52            count += item.write(writer)?;
53        }
54        Ok(count)
55    }
56}
57
58pub trait PartialBox {
59    type ParentData;
60    type ThisData;
61    fn byte_size(&self) -> usize;
62    const ID: BoxType;
63}
64
65#[async_trait]
66pub trait PartialBoxRead: PartialBox + Sized {
67    async fn read_data<R: ReadMp4>(parent_data: Self::ParentData, reader: &mut R) -> Result<Self, MP4Error>;
68    async fn read_child<R: ReadMp4>(&mut self, _header: BoxHeader, _reader: &mut R) -> Result<(), MP4Error> {
69        Ok(())
70    }
71}
72
73pub trait PartialBoxWrite: PartialBox {
74    fn write_data<W: WriteMp4>(&self, _writer: &mut W) -> Result<usize, MP4Error> {Ok(0)}
75    fn write_children<W: WriteMp4>(&self, _writer: &mut W) -> Result<usize, MP4Error> {Ok(0)}
76}