1use crate::audio::{AudioEdit, AudioPacketProvider, AudioTrackTiming, EncodedAudioSample};
12use crate::codec::{EncodedVideoSample, SampleDependency, SampleProvider, TrackKind};
13use crate::io::ByteSource;
14use crate::media::{Codec, VideoDimensions};
15use crate::mp4_demux::{AacTrackConfig, parse_aac_config};
16use crate::opus::{OPUS_SAMPLE_RATE, OpusHead};
17use crate::timeline::FrameIndex;
18use crate::vorbis::VorbisConfig;
19use crate::{Error, ErrorKind, Limits, Result};
20use std::borrow::Cow;
21use std::future::Future;
22
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct EditMapping {
26 pub segment_duration: u64,
27 pub media_time: i64,
28 pub media_rate_integer: i16,
29 pub media_rate_fraction: i16,
30}
31
32#[derive(Clone, Debug, Eq, PartialEq)]
34pub struct TrackSample {
35 pub offset: u64,
36 pub size: u32,
37 pub dts: u64,
38 pub pts: i64,
39 pub duration: u32,
40 pub dependency: SampleDependency,
41 pub is_sync: bool,
42}
43
44#[derive(Clone, Debug, Eq, PartialEq)]
46pub struct Track {
47 pub id: u32,
48 pub kind: TrackKind,
49 pub codec: Codec,
50 pub timescale: u32,
51 pub duration: u64,
52 pub dimensions: Option<VideoDimensions>,
53 pub channels: Option<u16>,
54 pub sample_rate: Option<u32>,
55 pub language: Option<String>,
60 pub decoder_config: Vec<u8>,
63 pub edits: Vec<EditMapping>,
64 pub samples: Vec<TrackSample>,
66 pub presentation_order: Vec<usize>,
71 pub vorbis_packet_heads: Vec<u8>,
77}
78
79impl Track {
80 pub fn presentation_sample(&self, index: usize) -> Option<&TrackSample> {
82 self.presentation_order
83 .get(index)
84 .and_then(|&decode_index| self.samples.get(decode_index))
85 }
86
87 pub async fn read_sample_into<S: ByteSource + ?Sized>(
89 &self,
90 source: &S,
91 decode_index: usize,
92 destination: &mut [u8],
93 ) -> Result<()> {
94 let sample = self
95 .samples
96 .get(decode_index)
97 .ok_or_else(|| invalid("sample index is out of range"))?;
98 if destination.len() != sample.size as usize {
99 return Err(invalid("sample destination size does not match the index"));
100 }
101 read_exact(source, sample.offset, destination).await
102 }
103
104 pub(crate) fn presentation_index_by_decode(&self) -> Result<Vec<u64>> {
110 let mut presentation_index_by_decode = vec![None; self.samples.len()];
111 for (presentation_index, &decode_index) in self.presentation_order.iter().enumerate() {
112 let presentation_index = u64::try_from(presentation_index)
113 .map_err(|_| limit("presentation index overflow"))?;
114 *presentation_index_by_decode
115 .get_mut(decode_index)
116 .ok_or_else(|| malformed("presentation order references a missing sample"))? =
117 Some(presentation_index);
118 }
119 let mut next_decode_only = self.presentation_order.len() as u64;
120 Ok(presentation_index_by_decode
121 .into_iter()
122 .map(|index| {
123 index.unwrap_or_else(|| {
124 next_decode_only += 1;
125 next_decode_only - 1
126 })
127 })
128 .collect())
129 }
130
131 pub async fn to_encoded_video_samples<S: ByteSource + ?Sized>(
143 &self,
144 source: &S,
145 limits: &Limits,
146 ) -> Result<Vec<EncodedVideoSample>> {
147 if self.kind != TrackKind::Video {
148 return Err(unsupported("encoded video samples require a video track"));
149 }
150 let presentation_index_by_decode = self.presentation_index_by_decode()?;
151
152 let mut total_bytes = 0_u64;
153 let mut samples = Vec::with_capacity(self.samples.len());
154 for (decode_index, sample) in self.samples.iter().enumerate() {
155 total_bytes = total_bytes
156 .checked_add(u64::from(sample.size))
157 .ok_or_else(|| limit("encoded sample allocation overflow"))?;
158 if total_bytes > limits.max_allocation_bytes {
159 return Err(limit(
160 "encoded video samples exceed the configured allocation limit",
161 ));
162 }
163 let mut data = vec![0_u8; sample.size as usize];
164 self.read_sample_into(source, decode_index, &mut data)
165 .await?;
166 samples.push(EncodedVideoSample {
167 presentation_index: FrameIndex(presentation_index_by_decode[decode_index]),
168 random_access: sample.is_sync,
169 data,
170 });
171 }
172 Ok(samples)
173 }
174
175 pub fn aac_config(&self) -> Result<AacTrackConfig> {
177 if self.kind != TrackKind::Audio || self.codec != Codec::Aac {
178 return Err(unsupported("AAC configuration requires an AAC audio track"));
179 }
180 let sample_rate = self
181 .sample_rate
182 .ok_or_else(|| malformed("AAC sample rate is missing"))?;
183 let channels = self
184 .channels
185 .ok_or_else(|| malformed("AAC channel count is missing"))?;
186 parse_aac_config(&self.decoder_config, sample_rate, channels)
187 }
188
189 pub fn opus_config(&self) -> Result<OpusHead> {
192 if self.kind != TrackKind::Audio || self.codec != Codec::Opus {
193 return Err(unsupported(
194 "Opus configuration requires an Opus audio track",
195 ));
196 }
197 let head = OpusHead::from_dops(&self.decoder_config)?;
198 if self.channels != Some(u16::from(head.channels)) {
199 return Err(malformed(
200 "Opus dOps channel count disagrees with the sample entry",
201 ));
202 }
203 Ok(head)
204 }
205
206 pub fn vorbis_config(&self) -> Result<VorbisConfig> {
210 if self.kind != TrackKind::Audio || self.codec != Codec::Vorbis {
211 return Err(unsupported(
212 "Vorbis configuration requires a Vorbis audio track",
213 ));
214 }
215 VorbisConfig::from_codec_private(&self.decoder_config)
216 }
217
218 pub fn audio_sample_rate(&self) -> Result<u32> {
222 match self.codec {
223 Codec::Aac => Ok(self.aac_config()?.sample_rate),
224 Codec::Opus => {
225 self.opus_config()?;
226 Ok(OPUS_SAMPLE_RATE)
227 }
228 Codec::Vorbis => Ok(self.vorbis_config()?.sample_rate),
229 _ => Err(unsupported(
230 "audio packets require an AAC, Opus or Vorbis track",
231 )),
232 }
233 }
234
235 pub async fn to_encoded_audio_samples<S: ByteSource + ?Sized>(
241 &self,
242 source: &S,
243 limits: &Limits,
244 ) -> Result<Vec<EncodedAudioSample>> {
245 let sample_rate = self.audio_sample_rate()?;
246 let vorbis = if self.codec == Codec::Vorbis {
249 Some(self.vorbis_config()?)
250 } else {
251 None
252 };
253 let aac_ranges = if self.codec == Codec::Aac {
255 Some(self.aac_decoded_ranges(sample_rate)?)
256 } else {
257 None
258 };
259 let mut total_bytes = 0_u64;
260 let mut decoded_start = 0_u64;
261 let mut packets = Vec::with_capacity(self.samples.len());
262 for (decode_index, sample) in self.samples.iter().enumerate() {
263 total_bytes = total_bytes
264 .checked_add(u64::from(sample.size))
265 .ok_or_else(|| limit("encoded audio allocation overflow"))?;
266 if total_bytes > limits.max_allocation_bytes {
267 return Err(limit(
268 "encoded audio samples exceed the configured allocation limit",
269 ));
270 }
271 let mut data = vec![0_u8; sample.size as usize];
272 self.read_sample_into(source, decode_index, &mut data)
273 .await?;
274 if vorbis.is_some() {
275 packets.push(EncodedAudioSample {
276 decoded_range: crate::SampleRange::new(0, 0)?,
277 data,
278 });
279 continue;
280 }
281 if let Some(ranges) = &aac_ranges {
282 packets.push(EncodedAudioSample {
283 decoded_range: ranges[decode_index],
284 data,
285 });
286 continue;
287 }
288 let decoded_end = decoded_start
292 .checked_add(u64::from(crate::opus::opus_packet_samples(&data)?))
293 .ok_or_else(|| limit("audio track timing overflow"))?;
294 if decoded_end <= decoded_start {
295 return Err(malformed("audio packet has an empty decoded interval"));
296 }
297 packets.push(EncodedAudioSample {
298 decoded_range: crate::SampleRange::new(decoded_start, decoded_end)?,
299 data,
300 });
301 decoded_start = decoded_end;
302 }
303 if packets.is_empty() {
304 return Err(malformed("audio track contains no samples"));
305 }
306 if let Some(vorbis) = vorbis {
307 return vorbis.encoded_samples(packets.into_iter().map(|packet| packet.data).collect());
308 }
309 Ok(packets)
310 }
311
312 pub(crate) fn aac_decoded_ranges(&self, sample_rate: u32) -> Result<Vec<crate::SampleRange>> {
315 self.table_decoded_ranges(&self.samples, sample_rate)
316 }
317
318 pub(crate) fn opus_decoded_ranges(
325 &self,
326 last_packet_samples: u32,
327 ) -> Result<Vec<crate::SampleRange>> {
328 let (_, leading) = self
329 .samples
330 .split_last()
331 .ok_or_else(|| malformed("audio track contains no samples"))?;
332 let mut ranges = self.table_decoded_ranges(leading, OPUS_SAMPLE_RATE)?;
333 let start = ranges.last().map_or(0, |range| range.end);
334 let end = start
335 .checked_add(u64::from(last_packet_samples))
336 .ok_or_else(|| limit("audio track timing overflow"))?;
337 if end <= start {
338 return Err(malformed("audio packet has an empty decoded interval"));
339 }
340 ranges.push(crate::SampleRange::new(start, end)?);
341 Ok(ranges)
342 }
343
344 pub(crate) fn vorbis_decoded_ranges(&self) -> Result<Vec<crate::SampleRange>> {
351 let config = self.vorbis_config()?;
352 if self.samples.is_empty() {
353 return Err(malformed("audio track contains no samples"));
354 }
355 if self.vorbis_packet_heads.len() != self.samples.len() {
356 return Err(unsupported(
357 "a Vorbis track's packet intervals need the first byte of every packet, which \
358 the WebM demuxer records",
359 ));
360 }
361 let block_sizes = self
362 .vorbis_packet_heads
363 .iter()
364 .map(|&head| config.packet_block_size(&[head]))
365 .collect::<Result<Vec<_>>>()?;
366 VorbisConfig::decoded_ranges(block_sizes)
367 }
368
369 fn table_decoded_ranges(
372 &self,
373 samples: &[TrackSample],
374 sample_rate: u32,
375 ) -> Result<Vec<crate::SampleRange>> {
376 let mut decoded_start = 0_u64;
377 let mut track_ticks = 0_u64;
378 let mut ranges = Vec::with_capacity(samples.len());
379 for sample in samples {
380 track_ticks = track_ticks
381 .checked_add(u64::from(sample.duration))
382 .ok_or_else(|| limit("audio track timing overflow"))?;
383 let decoded_end = scale_time(track_ticks, self.timescale, sample_rate)?;
384 if decoded_end <= decoded_start {
385 return Err(malformed("audio packet has an empty decoded interval"));
386 }
387 ranges.push(crate::SampleRange::new(decoded_start, decoded_end)?);
388 decoded_start = decoded_end;
389 }
390 Ok(ranges)
391 }
392
393 pub fn audio_timing(&self, movie_timescale: u32) -> Result<AudioTrackTiming> {
402 let sample_rate = self.audio_sample_rate()?;
403 let decoded_length = scale_time(self.duration, self.timescale, sample_rate)?;
404 if self.edits.is_empty() {
405 if self.codec != Codec::Opus {
406 return Ok(AudioTrackTiming::default());
407 }
408 let priming = self.opus_config()?.pre_skip;
409 let length = decoded_length
410 .checked_sub(u64::from(priming))
411 .filter(|&length| length > 0)
412 .ok_or_else(|| malformed("Opus pre-skip covers the whole track"))?;
413 return Ok(AudioTrackTiming {
414 priming: u32::from(priming),
415 padding: 0,
416 track_offset: 0,
417 edits: vec![AudioEdit {
418 presentation: crate::SampleRange::new(0, length)?,
419 media_start: Some(u64::from(priming)),
420 }],
421 });
422 }
423 let mut presentation_start = 0_u64;
424 let mut edits = Vec::with_capacity(self.edits.len());
425 let mut first_media = None;
426 let mut last_media_end = 0_u64;
427 for edit in &self.edits {
428 if edit.media_rate_integer != 1 || edit.media_rate_fraction != 0 {
429 return Err(unsupported(
430 "audio edit rates other than 1.0 are unsupported",
431 ));
432 }
433 let length = scale_time(edit.segment_duration, movie_timescale, sample_rate)?;
434 if length == 0 {
435 return Err(malformed("audio edit has an empty presentation interval"));
436 }
437 let presentation_end = presentation_start
438 .checked_add(length)
439 .ok_or_else(|| limit("audio edit presentation overflow"))?;
440 let media_start = if edit.media_time == -1 {
441 None
442 } else {
443 if edit.media_time < 0 {
444 return Err(malformed("audio edit has an invalid negative media time"));
445 }
446 let start = scale_time(edit.media_time as u64, self.timescale, sample_rate)?;
447 let end = start
448 .checked_add(length)
449 .ok_or_else(|| limit("audio edit media range overflow"))?;
450 first_media = Some(first_media.map_or(start, |value: u64| value.min(start)));
451 last_media_end = last_media_end.max(end);
452 Some(start)
453 };
454 edits.push(AudioEdit {
455 presentation: crate::SampleRange::new(presentation_start, presentation_end)?,
456 media_start,
457 });
458 presentation_start = presentation_end;
459 }
460 let priming = u32::try_from(first_media.unwrap_or(0))
461 .map_err(|_| limit("audio priming exceeds the supported range"))?;
462 let padding = u32::try_from(decoded_length.saturating_sub(last_media_end))
463 .map_err(|_| limit("audio padding exceeds the supported range"))?;
464 Ok(AudioTrackTiming {
465 priming,
466 padding,
467 track_offset: 0,
468 edits,
469 })
470 }
471}
472
473pub struct TrackSampleProvider<S> {
492 track: Track,
493 source: S,
494 presentation_index_by_decode: Vec<u64>,
495}
496
497impl<S: ByteSource + Send> TrackSampleProvider<S> {
498 pub fn new(track: Track, source: S) -> Result<Self> {
500 if track.kind != TrackKind::Video {
501 return Err(unsupported("a sample provider requires a video track"));
502 }
503 let presentation_index_by_decode = track.presentation_index_by_decode()?;
504 Ok(Self {
505 track,
506 source,
507 presentation_index_by_decode,
508 })
509 }
510
511 pub fn track(&self) -> &Track {
512 &self.track
513 }
514
515 pub fn source(&self) -> &S {
516 &self.source
517 }
518
519 pub fn into_source(self) -> S {
520 self.source
521 }
522}
523
524impl<S: ByteSource + Send> SampleProvider for TrackSampleProvider<S> {
525 fn len(&self) -> usize {
526 self.track.samples.len()
527 }
528
529 fn is_random_access(&self, decode_index: usize) -> bool {
530 self.track.samples[decode_index].is_sync
531 }
532
533 fn presentation_index(&self, decode_index: usize) -> FrameIndex {
534 FrameIndex(self.presentation_index_by_decode[decode_index])
535 }
536
537 fn read(&self, decode_index: usize) -> Result<Cow<'_, [u8]>> {
538 let size = self
539 .track
540 .samples
541 .get(decode_index)
542 .ok_or_else(|| invalid("sample index is out of range"))?
543 .size as usize;
544 let mut data = vec![0_u8; size];
545 poll_once(
546 self.track
547 .read_sample_into(&self.source, decode_index, &mut data),
548 )
549 .ok_or_else(|| {
550 unsupported(
551 "TrackSampleProvider requires a byte source whose reads complete \
552 synchronously; it cannot drive one that suspends",
553 )
554 })??;
555 Ok(Cow::Owned(data))
556 }
557}
558
559pub struct TrackAudioPacketProvider<S> {
576 track: Track,
577 source: S,
578 decoded_ranges: Vec<crate::SampleRange>,
579}
580
581impl<S: ByteSource + Send> TrackAudioPacketProvider<S> {
582 pub fn new(track: Track, source: S) -> Result<Self> {
585 if track.kind != TrackKind::Audio || !matches!(track.codec, Codec::Aac | Codec::Vorbis) {
586 return Err(unsupported(
587 "an on-demand audio packet provider requires an AAC or Vorbis audio track",
588 ));
589 }
590 if track.samples.is_empty() {
591 return Err(malformed("audio track contains no samples"));
592 }
593 let decoded_ranges = if track.codec == Codec::Vorbis {
594 track.vorbis_decoded_ranges()?
595 } else {
596 track.aac_decoded_ranges(track.audio_sample_rate()?)?
597 };
598 Ok(Self {
599 track,
600 source,
601 decoded_ranges,
602 })
603 }
604
605 pub fn track(&self) -> &Track {
606 &self.track
607 }
608
609 pub fn source(&self) -> &S {
610 &self.source
611 }
612
613 pub fn into_source(self) -> S {
614 self.source
615 }
616}
617
618impl<S: ByteSource + Send> AudioPacketProvider for TrackAudioPacketProvider<S> {
619 fn len(&self) -> usize {
620 self.decoded_ranges.len()
621 }
622
623 fn decoded_range(&self, index: usize) -> crate::SampleRange {
624 self.decoded_ranges[index]
625 }
626
627 fn read(&self, index: usize) -> Result<Cow<'_, [u8]>> {
628 let size = self
629 .track
630 .samples
631 .get(index)
632 .ok_or_else(|| invalid("sample index is out of range"))?
633 .size as usize;
634 let mut data = vec![0_u8; size];
635 poll_once(self.track.read_sample_into(&self.source, index, &mut data)).ok_or_else(
636 || {
637 unsupported(
638 "TrackAudioPacketProvider requires a byte source whose reads complete \
639 synchronously; it cannot drive one that suspends",
640 )
641 },
642 )??;
643 Ok(Cow::Owned(data))
644 }
645}
646
647fn poll_once<T>(future: impl Future<Output = T>) -> Option<T> {
652 let mut future = std::pin::pin!(future);
653 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
654 match future.as_mut().poll(&mut context) {
655 std::task::Poll::Ready(value) => Some(value),
656 std::task::Poll::Pending => None,
657 }
658}
659
660pub(crate) async fn read_exact<S: ByteSource + ?Sized>(
661 source: &S,
662 mut offset: u64,
663 mut output: &mut [u8],
664) -> Result<()> {
665 while !output.is_empty() {
666 let read = source.read_at(offset, output).await?;
667 if read == 0 {
668 return Err(malformed("unexpected end of media source"));
669 }
670 offset = offset
671 .checked_add(read as u64)
672 .ok_or_else(|| malformed("read offset overflow"))?;
673 output = &mut output[read..];
674 }
675 Ok(())
676}
677
678pub(crate) fn scale_time(value: u64, source_timescale: u32, destination_rate: u32) -> Result<u64> {
679 if source_timescale == 0 || destination_rate == 0 {
680 return Err(malformed("media timescale and sample rate must be nonzero"));
681 }
682 let numerator = u128::from(value)
683 .checked_mul(u128::from(destination_rate))
684 .ok_or_else(|| limit("media time scaling overflow"))?;
685 let rounded = numerator
686 .checked_add(u128::from(source_timescale) / 2)
687 .ok_or_else(|| limit("media time rounding overflow"))?
688 / u128::from(source_timescale);
689 u64::try_from(rounded).map_err(|_| limit("scaled media time cannot be represented"))
690}
691
692fn invalid(m: impl Into<String>) -> Error {
693 Error::new(ErrorKind::InvalidInput, m)
694}
695fn malformed(m: impl Into<String>) -> Error {
696 Error::new(ErrorKind::MalformedMedia, m)
697}
698fn limit(m: impl Into<String>) -> Error {
699 Error::new(ErrorKind::ResourceLimit, m)
700}
701fn unsupported(m: impl Into<String>) -> Error {
702 Error::new(ErrorKind::Unsupported, m)
703}