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
use std::convert::{TryFrom, TryInto};
use ebml_iterable::tools::{self as ebml_tools, Vint};
use super::super::errors::WebmCoercionError;
use super::MatroskaSpec;
#[derive(PartialEq, Debug)]
pub enum BlockLacing {
Xiph,
Ebml,
FixedSize,
}
pub struct Block {
pub payload: Vec<u8>,
pub track: u64,
pub value: i16,
pub invisible: bool,
pub lacing: Option<BlockLacing>,
}
impl TryFrom<&[u8]> for Block {
type Error = WebmCoercionError;
fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
let mut position: usize = 0;
let (track, track_size) = ebml_tools::read_vint(data)
.map_err(|_| WebmCoercionError::BlockCoercionError(String::from("Unable to read track data in Block.")))?
.ok_or_else(|| WebmCoercionError::BlockCoercionError(String::from("Unable to read track data in Block.")))?;
position += track_size;
let value: [u8; 2] = data[position..position + 2].try_into()
.map_err(|_| WebmCoercionError::BlockCoercionError(String::from("Attempting to create Block tag, but binary data length was not 2")))?;
let value = i16::from_be_bytes(value);
position += 2;
let flags: u8 = data[position];
position += 1;
let invisible = (flags & 0x10) == 0x10;
let lacing: Option<BlockLacing>;
if flags & 0x0c == 0x0c {
lacing = Some(BlockLacing::FixedSize);
} else if flags & 0x0c == 0x08 {
lacing = Some(BlockLacing::Ebml);
} else if flags & 0x0c == 0x04 {
lacing = Some(BlockLacing::Xiph);
} else {
lacing = None;
}
let payload = data[position..].to_vec();
Ok(Block {
payload,
track,
value,
invisible,
lacing,
})
}
}
impl TryFrom<MatroskaSpec> for Block {
type Error = WebmCoercionError;
fn try_from(value: MatroskaSpec) -> Result<Self, Self::Error> {
match value {
MatroskaSpec::Block(data) => {
let data: &[u8] = &data;
Block::try_from(data)
}
_ => Err(WebmCoercionError::BlockCoercionError(String::from("Expected binary tag type for Block tag, but received a different type!"))),
}
}
}
impl From<Block> for MatroskaSpec {
fn from(block: Block) -> Self {
let mut result = Vec::with_capacity(block.payload.len() + 11);
result.extend_from_slice(&block.track.as_vint().expect("Unable to convert track value to vint"));
result.extend_from_slice(&block.value.to_be_bytes());
let mut flags: u8 = 0x00;
if block.invisible {
flags |= 0x10;
}
if block.lacing.is_some() {
match block.lacing.unwrap() {
BlockLacing::Xiph => {
flags |= 0x04;
}
BlockLacing::Ebml => {
flags |= 0x08;
}
BlockLacing::FixedSize => {
flags |= 0x0c;
}
}
}
result.extend_from_slice(&flags.to_be_bytes());
result.extend_from_slice(&block.payload);
MatroskaSpec::Block(result)
}
}