async_mp4/mp4box/
stsz.rs

1use crate::bytes_read::ReadMp4;
2use crate::bytes_reserve::Mp4Reservable;
3use crate::bytes_write::{Mp4VersionedWritable, Mp4Writable, WriteMp4};
4use crate::error::MP4Error;
5use crate::id::BoxId;
6use crate::mp4box::box_full::{FullBox, FullBoxData, FullBoxInfo};
7use crate::mp4box::box_root::MP4Box;
8use crate::mp4box::box_trait::{PartialBox, PartialBoxRead, PartialBoxWrite};
9use crate::r#type::BoxType;
10use crate::types::array::Mp4Array;
11
12
13pub type StszBox = MP4Box<FullBox<Stsz, u32>>;
14
15#[derive(Debug, Clone, Eq, PartialEq, Hash)]
16pub enum Stsz {
17    Simple {
18        sample_size: u32,
19        sample_count: u32,
20    },
21    Advanced {
22        sample_sizes: Mp4Array<u32, u32>
23    }
24}
25
26impl FullBoxInfo for Stsz {
27    type Flag = u32;
28}
29
30impl PartialBox for Stsz {
31    type ParentData = FullBoxData<u32>;
32    type ThisData = ();
33
34    fn byte_size(&self) -> usize {
35        match self {
36            Stsz::Simple { sample_size, sample_count } => {
37                sample_size.byte_size() + sample_count.byte_size()
38            }
39            Stsz::Advanced { sample_sizes } => {
40                u32::BYTE_SIZE + sample_sizes.byte_size()
41            }
42        }
43    }
44
45    const ID: BoxType = BoxType::Id(BoxId(*b"stsz"));
46}
47
48#[async_trait::async_trait]
49impl PartialBoxRead for Stsz {
50    async fn read_data<R: ReadMp4>(parent: Self::ParentData, reader: &mut R) -> Result<Self, MP4Error> {
51        let version = parent.version;
52        let flags = parent.flags;
53        let sample_size = reader.versioned_read(version, flags).await?;
54        Ok(if sample_size == 0u32 {
55            Self::Advanced {
56                sample_sizes: reader.versioned_read(version, flags).await?
57            }
58        } else {
59            Self::Simple {
60                sample_size,
61                sample_count: reader.versioned_read(version, flags).await?,
62            }
63        })
64    }
65}
66
67impl PartialBoxWrite for Stsz {
68    fn write_data<W: WriteMp4>(&self, writer: &mut W) -> Result<usize, MP4Error> {
69        let version = self.version();
70        let flags = self.flags();
71        let mut count = 0;
72        match self {
73            Stsz::Simple { sample_size, sample_count } => {
74                count += sample_size.versioned_write(version, flags, writer)?;
75                count += sample_count.versioned_write(version, flags, writer)?;
76            }
77            Stsz::Advanced { sample_sizes } => {
78                count += 0u32.versioned_write(version, flags, writer)?;
79                count += sample_sizes.versioned_write(version, flags, writer)?;
80            }
81        }
82        Ok(count)
83    }
84}
85
86impl Default for Stsz {
87    fn default() -> Self {
88        Self::Simple {
89            sample_size: 0,
90            sample_count: 0
91        }
92    }
93}