feat: lossless (FLAC) streaming

Adds a Lossless streaming quality that asks /get-file-info for FLAC and
decrypts its encraw stream in memory. FLAC and FLAC-in-MP4 decode
through symphonia. When Yandex grants no FLAC, its lossy reply is played
as is, except HE-AAC, which falls back to the MP3 path. The player bar
badge shows the codec actually served and turns accent-coloured for
FLAC. Adds a read-only stream_probe example.
This commit is contained in:
Yuriy Panov committed 2026-10-15 18:33:04 +06:00
1 parent c85f5785fd
commit 24ff874d34
8 files changed
+175 -24

No files matched your search

+25 -4
View File
@@ -7,7 +7,7 @@ use crate::library::{
};
use crate::edit::{LikedIds, Lyrics, QueueContext};
use crate::discover::{ChartEntry, Genre, Home, SearchKind, SearchResults};
use crate::models::{Stream, Track, best_variant};
use crate::models::{Stream, Track, best_variant, file_info_stream};
use crate::wave::{PlayReport, Station, WaveBatch, WaveEvent, WaveSettings, iso_millis, numeric_id};
use crate::{Error, Result};
@@ -145,16 +145,37 @@ impl YmClient {
.ok_or_else(|| Error::Api(format!("no playable variant for track {track_id}")))?;
let url = variant.direct_link(self.inner.transport()).await?;
Ok(Stream {
url,
urls: vec![url],
codec: variant.codec.clone().unwrap_or_default(),
bitrate_kbps: variant.bitrate_in_kbps.unwrap_or(0).max(0) as u32,
preview: variant.preview.unwrap_or(false),
key: None,
})
}
/// Downloads a whole stream into memory (a 320 kbps track is about 10 MB).
/// FLAC when Yandex grants it for this track and account. Otherwise Yandex
/// answers with the best lossy file it allows (often AAC 192), which is played
/// as is unless it's HE-AAC, which the decoder can't do justice; then the MP3
/// path, as [`stream`](Self::stream) with no cap.
pub async fn lossless_stream(&self, track_id: &str) -> Result<Stream> {
match self.inner.track_lossless_info(track_id, "lossless").await.map_err(Error::from) {
Ok(info) => {
if let Some(stream) = file_info_stream(info) {
return Ok(stream);
}
}
Err(e @ (Error::Unauthorized(_) | Error::Network(_))) => return Err(e),
// An API refusal (region, rights) still leaves the MP3 path.
Err(_) => {}
}
self.stream(track_id, None).await
}
/// Downloads a whole stream into memory, decrypting it when it is encrypted
/// (MP3 320 is about 10 MB a track, FLAC 30–60 MB).
pub async fn fetch(&self, stream: &Stream) -> Result<Arc<[u8]>> {
let bytes = yamuse::download::Downloader::new(self.inner.transport(), [stream.url.clone()])
let bytes = yamuse::download::Downloader::new(self.inner.transport(), stream.urls.iter().cloned())
.maybe_encraw_key(stream.key.clone())
.to_bytes()
.await?;
Ok(bytes.into())
+68 -5
View File
@@ -122,21 +122,64 @@ pub(crate) fn hues_for(seed: u64) -> (f32, f32) {
}
/// Where a track's audio comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Clone, PartialEq, Eq)]
pub struct Stream {
pub url: String,
/// "mp3" or "aac".
/// Mirrors of the same file; any one works.
pub urls: Vec<String>,
/// "mp3", "aac", "flac" or "flac-mp4".
pub codec: String,
/// 0 when Yandex doesn't say (lossless).
pub bitrate_kbps: u32,
/// True when only a 30-second preview is available (no Plus).
pub preview: bool,
/// Hex AES-CTR key for an encrypted (`encraw`) lossless file.
pub key: Option<String>,
}
impl Stream {
/// "MP3 320", shown in the player bar.
/// "MP3 320" or "FLAC", shown in the player bar.
pub fn label(&self) -> String {
format!("{} {}", self.codec.to_ascii_uppercase(), self.bitrate_kbps)
let name = self.codec.trim_end_matches("-mp4").to_ascii_uppercase();
if self.lossless() || self.bitrate_kbps == 0 { name } else { format!("{name} {}", self.bitrate_kbps) }
}
pub fn lossless(&self) -> bool {
matches!(self.codec.as_str(), "flac" | "flac-mp4")
}
/// The file format, for the decoder: "flac-mp4" is FLAC inside an MP4 container.
pub fn container(&self) -> &str {
if self.codec.ends_with("-mp4") { "mp4" } else { &self.codec }
}
}
/// Signed URLs and the key stay out of logs.
impl std::fmt::Debug for Stream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Stream")
.field("codec", &self.codec)
.field("bitrate_kbps", &self.bitrate_kbps)
.field("preview", &self.preview)
.field("mirrors", &self.urls.len())
.field("encrypted", &self.key.is_some())
.finish()
}
}
/// Builds a stream from a `/get-file-info` reply, when it's a codec we decode well.
pub(crate) fn file_info_stream(info: yamuse::models::LosslessDownloadInfo) -> Option<Stream> {
let urls = info.links();
let playable = matches!(info.codec.as_deref(), Some("flac" | "flac-mp4" | "mp3" | "aac" | "aac-mp4"));
if !playable || urls.is_empty() {
return None;
}
Some(Stream {
urls,
codec: info.codec.unwrap_or_default(),
bitrate_kbps: info.bitrate.unwrap_or(0).max(0) as u32,
preview: false,
key: info.key.filter(|k| !k.is_empty()),
})
}
/// Picks the variant to play: full tracks over previews, then the highest bitrate
@@ -224,4 +267,24 @@ mod tests {
assert!(best_variant(&previews, None).unwrap().preview.unwrap());
assert!(best_variant(&[], None).is_none());
}
#[test]
fn file_info_replies_become_streams_except_he_aac() {
let info = |json: &str| serde_json::from_str::<yamuse::models::LosslessDownloadInfo>(json).unwrap();
let flac = file_info_stream(info(
r#"{"codec":"flac-mp4","bitrate":0,"transport":"encraw","key":"00ff","urls":["https://a","https://b"]}"#,
))
.unwrap();
assert_eq!(flac.urls, ["https://a", "https://b"]);
assert_eq!((flac.label().as_str(), flac.container()), ("FLAC", "mp4"));
assert_eq!(flac.key.as_deref(), Some("00ff"));
assert!(!format!("{flac:?}").contains("00ff"), "key leaked into Debug");
assert!(flac.lossless());
let aac = file_info_stream(info(r#"{"codec":"aac-mp4","quality":"nq","bitrate":192,"key":"00ff","urls":["https://a"]}"#)).unwrap();
assert_eq!((aac.label().as_str(), aac.container(), aac.lossless()), ("AAC 192", "mp4", false));
assert!(file_info_stream(info(r#"{"codec":"he-aac-mp4","bitrate":64,"urls":["https://a"]}"#)).is_none());
assert!(file_info_stream(info(r#"{"codec":"flac","urls":[]}"#)).is_none());
let mp3 = Stream { urls: vec![], codec: "mp3".into(), bitrate_kbps: 320, preview: false, key: None };
assert_eq!((mp3.label().as_str(), mp3.container()), ("MP3 320", "mp3"));
}
}