From d6694cd8a5fb6f14157b7973087d08ffb03ba0bd Mon Sep 17 00:00:00 2001 From: snylonue Date: Fri, 4 Oct 2024 20:10:48 +0800 Subject: [PATCH] fix(playback): avoid unnecessary boxing Add a helper trait to upcast trait object. see also: https://www.zhihu.com/question/643804984/answer/3393253605 --- anni-playback/src/decoder/decoder.rs | 2 +- anni-playback/src/sources/mod.rs | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/anni-playback/src/decoder/decoder.rs b/anni-playback/src/decoder/decoder.rs index df421dd..fa71d33 100644 --- a/anni-playback/src/decoder/decoder.rs +++ b/anni-playback/src/decoder/decoder.rs @@ -362,7 +362,7 @@ impl Decoder { buffer_signal: Arc, ) -> anyhow::Result { let duration_hint = source.duration_hint(); - let mss = MediaSourceStream::new(Box::new(source), Default::default()); + let mss = MediaSourceStream::new(source.into(), Default::default()); let format_options = FormatOptions { enable_gapless: true, ..Default::default() diff --git a/anni-playback/src/sources/mod.rs b/anni-playback/src/sources/mod.rs index 7d5a317..4e9041a 100644 --- a/anni-playback/src/sources/mod.rs +++ b/anni-playback/src/sources/mod.rs @@ -27,7 +27,7 @@ struct Receiver { receiver: std::sync::mpsc::Receiver<(usize, Vec)>, } -pub trait AnniSource: MediaSource { +pub trait AnniSource: MediaSource + IntoBoxedMediaSource { /// The duration of underlying source in seconds. fn duration_hint(&self) -> Option { None @@ -46,6 +46,23 @@ impl MediaSource for Box { impl AnniSource for std::fs::File {} +// helper trait to do upcasting +pub trait IntoBoxedMediaSource { + fn into_media_source(self: Box) -> Box; +} + +impl IntoBoxedMediaSource for T { + fn into_media_source(self: Box) -> Box { + self + } +} + +impl From> for Box { + fn from(value: Box) -> Self { + value.into_media_source() + } +} + // Specialization is not well-supported so far (even the unstable feature is unstable ww). // Therefore, we do not provide the default implementation below. // Users can use a newtype pattern if needed.