mp4_atom/moov/trak/mdia/minf/stbl/stsd/mp4a/
esds.rs

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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use crate::*;

#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Esds {
    pub es_desc: EsDescriptor,
}

impl AtomExt for Esds {
    type Ext = ();

    const KIND_EXT: FourCC = FourCC::new(b"esds");

    fn decode_body_ext(buf: &mut Bytes, _ext: ()) -> Result<Self> {
        let mut es_desc = None;

        while let Some(desc) = Option::<Descriptor>::decode(buf)? {
            match desc {
                Descriptor::EsDescriptor(desc) => es_desc = Some(desc),
                Descriptor::Unknown(tag, _) => {
                    tracing::warn!("unknown descriptor: {:02X}", tag)
                }
                _ => return Err(Error::UnexpectedDescriptor(desc.tag())),
            }
        }

        Ok(Esds {
            es_desc: es_desc.ok_or(Error::MissingDescriptor(EsDescriptor::TAG))?,
        })
    }

    fn encode_body_ext(&self, buf: &mut BytesMut) -> Result<()> {
        Descriptor::from(self.es_desc).encode(buf)
    }
}

macro_rules! descriptors {
	($($name:ident,)*) => {
		#[derive(Debug, Clone, PartialEq, Eq)]
		pub enum Descriptor {
			$(
				$name($name),
			)*
			Unknown(u8, Bytes),
		}

		impl Decode for Descriptor {
			fn decode(buf: &mut Bytes) -> Result<Self> {
				let tag = u8::decode(buf)?;

				let mut size: u32 = 0;
				for _ in 0..4 {
					let b = u8::decode(buf)?;
					size = (size << 7) | (b & 0x7F) as u32;
					if b & 0x80 == 0 {
						break;
					}
				}

				match tag {
					$(
						$name::TAG => Ok($name::decode_exact(buf, size as _)?.into()),
					)*
					_ => Ok(Descriptor::Unknown(tag, buf.decode_exact(size as _)?)),
				}
			}
		}

		impl Encode for Descriptor {
			fn encode(&self, buf: &mut BytesMut) -> Result<()> {
				// TODO This is inefficient; we could compute the size upfront.
				let mut tmp = BytesMut::new();

				match self {
					$(
						Descriptor::$name(t) => {
							$name::TAG.encode(buf)?;
							t.encode(&mut tmp)?;
						},
					)*
					Descriptor::Unknown(tag, data) => {
						tag.encode(buf)?;
						data.encode(&mut tmp)?;
					},
				};

				let mut size = tmp.len() as u32;
				while size > 0 {
					let mut b = (size & 0x7F) as u8;
					size >>= 7;
					if size > 0 {
						b |= 0x80;
					}
					b.encode(buf)?;
				}

				buf.encode(&tmp.freeze())
			}
		}

		impl Descriptor {
			pub const fn tag(&self) -> u8 {
				match self {
					$(
						Descriptor::$name(_) => $name::TAG,
					)*
					Descriptor::Unknown(tag, _) => *tag,
				}
			}
		}

		$(
			impl From<$name> for Descriptor {
				fn from(desc: $name) -> Self {
					Descriptor::$name(desc)
				}
			}
		)*
	};
}

descriptors! {
    EsDescriptor,
    DecoderConfig,
    DecoderSpecific,
    SLConfig,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EsDescriptor {
    pub es_id: u16,

    pub dec_config: DecoderConfig,
    pub sl_config: SLConfig,
}

impl EsDescriptor {
    pub const TAG: u8 = 0x03;
}

impl Decode for EsDescriptor {
    fn decode(buf: &mut Bytes) -> Result<Self> {
        let es_id = buf.decode()?;
        u8::decode(buf)?; // XXX flags must be 0

        let mut dec_config = None;
        let mut sl_config = None;

        while let Some(desc) = Option::<Descriptor>::decode(buf)? {
            match desc {
                Descriptor::DecoderConfig(desc) => dec_config = Some(desc),
                Descriptor::SLConfig(desc) => sl_config = Some(desc),
                Descriptor::Unknown(tag, _) => tracing::warn!("unknown descriptor: {:02X}", tag),
                desc => return Err(Error::UnexpectedDescriptor(desc.tag())),
            }
        }

        Ok(EsDescriptor {
            es_id,
            dec_config: dec_config.ok_or(Error::MissingDescriptor(DecoderConfig::TAG))?,
            sl_config: sl_config.ok_or(Error::MissingDescriptor(SLConfig::TAG))?,
        })
    }
}

impl Encode for EsDescriptor {
    fn encode(&self, buf: &mut BytesMut) -> Result<()> {
        self.es_id.encode(buf)?;
        0u8.encode(buf)?;

        Descriptor::from(self.dec_config).encode(buf)?;
        Descriptor::from(self.sl_config).encode(buf)?;

        Ok(())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DecoderConfig {
    pub object_type_indication: u8,
    pub stream_type: u8,
    pub up_stream: u8,
    pub buffer_size_db: u24,
    pub max_bitrate: u32,
    pub avg_bitrate: u32,
    pub dec_specific: DecoderSpecific,
}

impl DecoderConfig {
    pub const TAG: u8 = 0x04;
}

impl Decode for DecoderConfig {
    fn decode(buf: &mut Bytes) -> Result<Self> {
        let object_type_indication = u8::decode(buf)?;
        let byte_a = u8::decode(buf)?;
        let stream_type = (byte_a & 0xFC) >> 2;
        let up_stream = byte_a & 0x02;
        let buffer_size_db = u24::decode(buf)?;
        let max_bitrate = u32::decode(buf)?;
        let avg_bitrate = u32::decode(buf)?;

        let mut dec_specific = None;

        while let Some(desc) = Option::<Descriptor>::decode(buf)? {
            match desc {
                Descriptor::DecoderSpecific(desc) => dec_specific = Some(desc),
                Descriptor::Unknown(tag, _) => tracing::warn!("unknown descriptor: {:02X}", tag),
                desc => return Err(Error::UnexpectedDescriptor(desc.tag())),
            }
        }

        Ok(DecoderConfig {
            object_type_indication,
            stream_type,
            up_stream,
            buffer_size_db,
            max_bitrate,
            avg_bitrate,
            dec_specific: dec_specific.ok_or(Error::MissingDescriptor(DecoderSpecific::TAG))?,
        })
    }
}

impl Encode for DecoderConfig {
    fn encode(&self, buf: &mut BytesMut) -> Result<()> {
        self.object_type_indication.encode(buf)?;
        ((self.stream_type << 2) + (self.up_stream & 0x02) + 1).encode(buf)?; // 1 reserved
        self.buffer_size_db.encode(buf)?;
        self.max_bitrate.encode(buf)?;
        self.avg_bitrate.encode(buf)?;

        Descriptor::from(self.dec_specific).encode(buf)?;

        Ok(())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DecoderSpecific {
    pub profile: u8,
    pub freq_index: u8,
    pub chan_conf: u8,
}

impl DecoderSpecific {
    pub const TAG: u8 = 0x05;
}

impl Decode for DecoderSpecific {
    fn decode(buf: &mut Bytes) -> Result<Self> {
        let byte_a = u8::decode(buf)?;
        let byte_b = u8::decode(buf)?;

        let mut profile = byte_a >> 3;
        if profile == 31 {
            profile = 32 + ((byte_a & 7) | (byte_b >> 5));
        }

        let freq_index = if profile > 31 {
            (byte_b >> 1) & 0x0F
        } else {
            ((byte_a & 0x07) << 1) + (byte_b >> 7)
        };

        let chan_conf;
        if freq_index == 15 {
            // Skip the 24 bit sample rate
            // TODO this needs to be implemented in encode
            let sample_rate = u24::decode(buf)?;
            chan_conf = ((u32::from(sample_rate) >> 4) & 0x0F) as u8;
        } else if profile > 31 {
            let byte_c = u8::decode(buf)?;
            chan_conf = (byte_b & 1) | (byte_c & 0xE0);
        } else {
            chan_conf = (byte_b >> 3) & 0x0F;
        }

        Ok(DecoderSpecific {
            profile,
            freq_index,
            chan_conf,
        })
    }
}

impl Encode for DecoderSpecific {
    fn encode(&self, buf: &mut BytesMut) -> Result<()> {
        ((self.profile << 3) + (self.freq_index >> 1)).encode(buf)?;
        ((self.freq_index << 7) + (self.chan_conf << 3)).encode(buf)?;

        Ok(())
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SLConfig {}

impl SLConfig {
    pub const TAG: u8 = 0x06;
}

impl Decode for SLConfig {
    fn decode(buf: &mut Bytes) -> Result<Self> {
        u8::decode(buf)?; // pre-defined
        Ok(SLConfig {})
    }
}

impl Encode for SLConfig {
    fn encode(&self, buf: &mut BytesMut) -> Result<()> {
        2u8.encode(buf)?; // pre-defined
        Ok(())
    }
}