1
2use uuid::Uuid;
3use crate::bytes_read::{Mp4Readable, ReadMp4};
4use crate::bytes_write::{Mp4Writable, WriteMp4};
5use crate::error::MP4Error;
6use crate::id::BoxId;
7use crate::r#type::BoxType;
8use crate::size::BoxSize;
9use crate::size::BoxSize::Known;
10use crate::size::BoxSize::Unknown;
11use async_trait::async_trait;
12
13#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
14pub struct BoxHeader {
15 pub size: BoxSize,
16 pub id: BoxType
17}
18
19impl BoxHeader {
20
21 pub fn from_id_and_inner_size(id: BoxType, inner_size: usize) -> Self {
22 Self {
23 size: BoxSize::from_size_without_self(inner_size + id.byte_size()),
24 id
25 }
26 }
27
28 pub fn size_minus_self(&self) -> BoxSize {
29 match self.size {
30 Known(size) => Known(self.byte_size() - size),
31 Unknown => Unknown
32 }
33 }
34
35}
36
37#[async_trait]
38impl Mp4Readable for BoxHeader {
39 async fn read<R: ReadMp4>(reader: &mut R) -> Result<Self, MP4Error> {
40 let size: u32 = reader.read().await?;
41 let id = BoxId::read(reader).await?;
42 let size = match size {
43 0 => Unknown,
44 1 => {
45 let size: u64 = reader.read().await?;
46 Known(size as _)
47 }
48 _ => Known(size as _)
49 };
50 let id = if id == b"uuid" {
51 BoxType::UUID(reader.read().await?)
52 } else {
53 BoxType::Id(id)
54 };
55 Ok(Self {
56 size, id
57 })
58 }
59}
60
61impl Mp4Writable for BoxHeader {
62 fn byte_size(&self) -> usize {
63 self.size.byte_size() + self.id.byte_size()
64 }
65
66
67 fn write<W: WriteMp4>(&self, writer: &mut W) -> Result<usize, MP4Error> {
68 let (id, uuid) = match self.id {
69 BoxType::Id(id) => (id, None),
70 BoxType::UUID(uuid) => (BoxId(*b"uuid"), Some(uuid))
71 };
72 let (size, big_size) = match self.size {
73 Known(size) => {
74 if cfg!(target_pointer_width = "64") {
75 if size > u32::MAX as usize {
76 (1, Some(size as u64))
77 } else {
78 (size as u32, None)
79 }
80 } else {
81 (size as u32, None)
82 }
83 }
84 Unknown => (0, None)
85 };
86 let mut count = 0;
87 count += size.write(writer)?;
88 count += id.write(writer)?;
89 count += big_size.write(writer)?;
90 count += uuid.write(writer)?;
91 Ok(count)
92 }
93}
94
95#[async_trait]
96impl Mp4Readable for Uuid {
97 async fn read<R: ReadMp4>(reader: &mut R) -> Result<Self, MP4Error> {
98 Ok(Uuid::from_bytes(reader.read().await?))
99 }
100}
101
102impl Mp4Writable for Uuid {
103 fn byte_size(&self) -> usize {
104 self.as_bytes().byte_size()
105 }
106
107 fn write<W: WriteMp4>(&self, writer: &mut W) -> Result<usize, MP4Error> {
108 self.as_bytes().write(writer)
109 }
110}