Files
Thing/src-tauri/src/music/audio/source.rs
T
2026-09-23 18:29:20 +08:00

179 lines
7.0 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 音频字节源:给 symphonia 提供同步的 [`MediaSource`](`Read` + `Seek`)。
//!
//! 两类来源:
//! - **本地文件**:直接交给 `std::fs::File`(symphonia 已为它实现 `MediaSource`)。
//! - **飞牛流**:复用**现有的本地流代理** `http://127.0.0.1:<port>/feiniu/stream?guid=...`。
//! 代理已经处理好登录态 / Cookie / 安全码 / Range 透传,这里只按 Range 拉取即可。
//!
//! 为什么走本地代理而不让引擎直连 NAS:鉴权(连接选择、token、安全码)全在代理里,
//! 复制一份到引擎会立刻产生两套会漂移的逻辑;代理就在 localhost,额外一跳代价可忽略。
//!
//! # 为什么是同步 I/O
//!
//! `MediaSource` 要求 `Read + Seek`,即同步接口。整个播放线程是**独立的 std 线程**
//! (不是 tokio 运行时线程),因此这里用 `reqwest::blocking` 是安全的;若在 tokio
//! 运行时线程上调用会 panic,这一点在改动线程归属时必须留意。
use std::io::{self, Read, Seek, SeekFrom};
use std::time::Duration;
use symphonia::core::io::MediaSource;
/// NAS 流的超时策略:只在**连接**阶段设超时。
///
/// 音频是长时间连续读,一旦给整请求设 timeout,会在播到中途时被掐断(表现为
/// 「播一半突然断流」);而不设连接超时又会在服务器无响应时永久挂住播放线程。
///
/// # 已知限制:读阶段的卡死不设上限
///
/// 想给「连接建立后数据不再来」也加个上限,但 reqwest 的 `read_timeout` 只在**异步**
/// builder 上(blocking 侧没有),而总 timeout 又会掐断长音频。因此链路彻底卡死时
/// 解码线程会停在那次读上(界面表现为一直加载),要等 TCP 自身超时才会报错。
/// 真要兜住它,得在会话上加一个「位置长时间不前进」的看门狗,或让 HttpSource 自己能
/// 被从外部关闭 —— 目前没做。
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// 按规格打开字节源:`http(s)://` 走网络协议,其余一律按本地文件路径处理。
pub fn open(spec: &str) -> Result<Box<dyn MediaSource>, String> {
if spec.starts_with("http://") || spec.starts_with("https://") {
Ok(Box::new(HttpSource::new(spec)?))
} else {
let file = std::fs::File::open(spec).map_err(|e| format!("打开本地音频失败({spec}): {e}"))?;
Ok(Box::new(file))
}
}
/// 走 HTTP 的流式音源,支持按 `Range` 定位。
pub struct HttpSource {
url: String,
client: reqwest::blocking::Client,
/// 已建立的响应体。定位后置空,下次读取时按新位置重新发 Range 请求。
body: Option<reqwest::blocking::Response>,
/// 当前读取位置(字节)
pos: u64,
/// 总字节数(服务端给出 Content-Range / Content-Length 时才有)
len: Option<u64>,
/// 服务端是否支持 Range。不支持时无法定位,引擎会退化为「只能从头顺序播」。
range_ok: bool,
}
impl HttpSource {
fn new(url: &str) -> Result<Self, String> {
let client = reqwest::blocking::Client::builder()
.connect_timeout(CONNECT_TIMEOUT)
.timeout(None)
.build()
.map_err(|e| format!("创建音频 HTTP 客户端失败: {e}"))?;
// 探测总长度与 Range 支持:只取 0-0 一个字节。
// 支持 Range 时服务端回 `206 Partial Content` + `Content-Range: bytes 0-0/<total>`;
// 不支持则回 `200` + `Content-Length`。两种情况都能拿到总长度。
let probe = client
.get(url)
.header(reqwest::header::RANGE, "bytes=0-0")
.send()
.map_err(|e| format!("音频源探测失败: {e}"))?;
let status = probe.status();
if !status.is_success() {
return Err(format!("音频源探测失败: HTTP {status}"));
}
let range_ok = status == reqwest::StatusCode::PARTIAL_CONTENT
|| probe
.headers()
.get(reqwest::header::ACCEPT_RANGES)
.is_some();
let len = parse_content_range_total(&probe)
.or_else(|| probe.content_length().map(|n| n.max(1)));
Ok(Self {
url: url.to_string(),
client,
body: None,
pos: 0,
len,
range_ok,
})
}
/// 打开(或按当前 `pos` 重开)响应体。
fn ensure_body(&mut self) -> io::Result<()> {
if self.body.is_some() {
return Ok(());
}
let mut req = self.client.get(&self.url);
if self.pos > 0 {
if !self.range_ok {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"音频源不支持 Range,无法定位",
));
}
req = req.header(reqwest::header::RANGE, format!("bytes={}-", self.pos));
}
let resp = req.send().map_err(to_io_err)?;
if !resp.status().is_success() {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("音频流请求失败: HTTP {}", resp.status()),
));
}
self.body = Some(resp);
Ok(())
}
}
impl Read for HttpSource {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.ensure_body()?;
let body = self.body.as_mut().expect("ensure_body 已建立响应体");
let n = body.read(buf)?;
self.pos += n as u64;
Ok(n)
}
}
impl Seek for HttpSource {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
let target = match pos {
SeekFrom::Start(p) => p,
SeekFrom::End(off) => {
let len = self.len.ok_or_else(|| {
io::Error::new(io::ErrorKind::Unsupported, "总长度未知,无法从末尾定位")
})?;
(len as i64 + off).max(0) as u64
}
SeekFrom::Current(off) => (self.pos as i64 + off).max(0) as u64,
};
// 丢弃当前响应体,下次读取按新位置重发 Range —— 这样定位既不需要缓存整段音频,
// 也不会把已读过的字节再拉一遍。
self.body = None;
self.pos = target;
Ok(target)
}
}
impl MediaSource for HttpSource {
fn is_seekable(&self) -> bool {
self.range_ok
}
fn byte_len(&self) -> Option<u64> {
self.len
}
}
/// 解析 `Content-Range: bytes 0-0/12345` 里的总长度。
fn parse_content_range_total(resp: &reqwest::blocking::Response) -> Option<u64> {
let raw = resp.headers().get(reqwest::header::CONTENT_RANGE)?.to_str().ok()?;
let total = raw.rsplit('/').next()?.trim();
if total == "*" {
return None;
}
total.parse::<u64>().ok()
}
/// reqwest 的 `Error` → `io::Error`(symphonia 只认 io 错误)。
fn to_io_err(e: reqwest::Error) -> io::Error {
io::Error::new(io::ErrorKind::Other, e.to_string())
}