Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 57 additions & 17 deletions crates/kira/src/sound/streaming/decoder/symphonia.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,23 @@ use symphonia::core::{
units::Timestamp,
};

#[cfg(test)]
mod test;

/// The number of frames to decode before the frame that a seek is
/// targeting. This is more than a packet of AAC (1024 frames) or MP3 (1152
/// frames), so a whole packet is decoded to prepare the decoder.
const SEEK_PREROLL_FRAMES: usize = 2048;

pub(crate) struct SymphoniaDecoder {
format_reader: Box<dyn FormatReader>,
decoder: Box<dyn AudioDecoder>,
sample_rate: u32,
num_frames: usize,
track_id: u32,
/// The frames from the target of the last seek to the end of the packet
/// they were decoded from, which the next call to `decode` returns first.
frames_after_seek: Vec<Frame>,
}

impl SymphoniaDecoder {
Expand Down Expand Up @@ -53,8 +64,32 @@ impl SymphoniaDecoder {
sample_rate,
num_frames,
track_id,
frames_after_seek: vec![],
})
}

/// Decodes the next packet of the track. Returns the index of the first
/// frame of the packet and the decoded frames, or `None` at the end of
/// the file.
///
/// The index comes from the packet because the first packet decoded after
/// a reset can come out empty (Ogg Vorbis), though the file counts frames
/// for it.
fn decode_packet(&mut self) -> Result<Option<(usize, Vec<Frame>)>, FromFileError> {
let packet = loop {
match self.format_reader.next_packet()? {
Some(packet) if packet.track_id == self.track_id => break packet,
Some(_) => continue,
None => return Ok(None),
}
};
let first_frame_index = packet.pts.saturating_add(packet.trim_start).get();
let buffer = self.decoder.decode(&packet)?;
Ok(Some((
first_frame_index.max(0) as usize,
load_frames_from_buffer_ref(&buffer)?,
)))
}
}

impl super::Decoder for SymphoniaDecoder {
Expand All @@ -69,30 +104,35 @@ impl super::Decoder for SymphoniaDecoder {
}

fn decode(&mut self) -> Result<Vec<Frame>, Self::Error> {
let packet = loop {
match self.format_reader.next_packet()? {
Some(packet) if packet.track_id == self.track_id => break packet,
Some(_) => continue,
None => return Ok(vec![]),
}
};
let buffer = self.decoder.decode(&packet)?;
load_frames_from_buffer_ref(&buffer)
if !self.frames_after_seek.is_empty() {
return Ok(std::mem::take(&mut self.frames_after_seek));
}
Ok(self
.decode_packet()?
.map(|(_, frames)| frames)
.unwrap_or_default())
}

fn seek(&mut self, index: usize) -> Result<usize, Self::Error> {
let seeked_to = self.format_reader.seek(
self.frames_after_seek.clear();
// Codecs like AAC, MP3, and Vorbis decode a frame using the frames
// before it, so decoding right from the target gives wrong frames at
// first. Seek earlier, reset the decoder, and decode up to the target
// the way Symphonia leaves to the caller.
self.format_reader.seek(
SeekMode::Accurate,
SeekTo::Timestamp {
ts: Timestamp::new(index as i64),
ts: Timestamp::new(index.saturating_sub(SEEK_PREROLL_FRAMES) as i64),
track_id: self.track_id,
},
)?;
let actual = seeked_to.actual_ts.get();
Ok(if actual < 0 {
0
} else {
(actual as usize).min(self.num_frames)
})
self.decoder.reset();
while let Some((packet_index, mut frames)) = self.decode_packet()? {
if !frames.is_empty() && packet_index + frames.len() > index {
self.frames_after_seek = frames.split_off(index.saturating_sub(packet_index));
return Ok(packet_index.max(index));
}
}
Ok(index.min(self.num_frames))
}
}
102 changes: 102 additions & 0 deletions crates/kira/src/sound/streaming/decoder/symphonia/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
use std::io::Cursor;

use crate::{
frame::Frame,
sound::{streaming::decoder::Decoder, symphonia::load_frames_from_buffer_ref},
};

use super::SymphoniaDecoder;

// Each tone is 0.4 seconds of two sine waves at 16000 frames per second, so
// that no frame is silent. They were made with ffmpeg:
//
// ffmpeg -f lavfi -i 'aevalsrc=0.1*sin(2*PI*440*t)+0.05*sin(2*PI*1330*t):s=16000:d=0.4'
// -ac 1 -fflags +bitexact -flags:a +bitexact -map_metadata -1
// -c:a aac -b:a 12k -movflags +faststart tone.m4a
//
// with `-c:a libmp3lame -b:a 16k` and tone.mp3 for the MP3 tone and
// `-c:a libvorbis -b:a 16k` and tone.ogg for the Ogg Vorbis tone.

/// The number of frames to compare after each seek.
const COMPARED_FRAMES: usize = 1024;

/// The largest difference between two samples that still counts as the same
/// sample. A frame decoded without the frames before it is off by 0.07 or more.
const TOLERANCE: f32 = 1e-5;

fn decoder(bytes: &'static [u8]) -> SymphoniaDecoder {
SymphoniaDecoder::new(Box::new(Cursor::new(bytes))).unwrap()
}

/// Decodes the whole file from the start, without seeking.
///
/// This reads the packets directly instead of calling `decode`, because
/// `decode` returning no frames doesn't always mean the end of the file: the
/// first packet of an Ogg Vorbis file decodes to no frames.
fn decode_straight(bytes: &'static [u8]) -> Vec<Frame> {
let mut decoder = decoder(bytes);
let mut frames = vec![];
while let Some(packet) = decoder.format_reader.next_packet().unwrap() {
if packet.track_id == decoder.track_id {
let buffer = decoder.decoder.decode(&packet).unwrap();
frames.extend(load_frames_from_buffer_ref(&buffer).unwrap());
}
}
frames
}

/// Tests that the frames decoded after a seek are the same as the frames at
/// the same indices when the file is decoded straight through.
///
/// `seek` may land earlier than the requested index, so the first frame that
/// `decode` returns afterwards is the one at the index that `seek` returned.
fn test_seek(bytes: &'static [u8]) {
let straight = decode_straight(bytes);
let mut decoder = decoder(bytes);
// seek from the end backwards so the decoder still holds the state of
// frames far later in the file when a seek lands near the start
for index in (0..straight.len() - COMPARED_FRAMES).rev().step_by(61) {
let seeked_to = decoder.seek(index).unwrap();
assert!(seeked_to <= index);
let mut decoded = vec![];
for _ in 0..64 {
decoded.extend(decoder.decode().unwrap());
if decoded.len() >= COMPARED_FRAMES {
break;
}
}
assert!(decoded.len() >= COMPARED_FRAMES);
for (i, frame) in decoded.iter().take(COMPARED_FRAMES).enumerate() {
let expected = straight[seeked_to + i];
assert!(
(frame.left - expected.left).abs() < TOLERANCE
&& (frame.right - expected.right).abs() < TOLERANCE,
"seek({}) returned {}, and frame {} decoded after it is {:?}, \
but decoding from the start gives {:?}",
index,
seeked_to,
seeked_to + i,
frame,
expected
);
}
}
}

#[test]
#[cfg(all(feature = "aac", feature = "isomp4"))]
fn seek_aac() {
test_seek(include_bytes!("tone.m4a"));
}

#[test]
#[cfg(feature = "mp3")]
fn seek_mp3() {
test_seek(include_bytes!("tone.mp3"));
}

#[test]
#[cfg(all(feature = "ogg", feature = "vorbis"))]
fn seek_ogg_vorbis() {
test_seek(include_bytes!("tone.ogg"));
}
Binary file not shown.
Binary file not shown.
Binary file not shown.