refactor(cast): extract qbz-cast crate
Extract casting functionality (Chromecast, AirPlay, DLNA) to standalone qbz-cast crate. This crate is Tauri-agnostic and can be used by TUI/CLI clients. - Move device connection, discovery, threading, and media server to crate - Keep only Tauri commands in src-tauri/src/cast/ - Thin re-exports in src-tauri for backwards compatibility - Remove duplicate dependencies from src-tauri Cargo.toml
This commit is contained in:
1 parent
deece54bcb
commit
63994c0a20
26 files changed
+1481
-1326
No files matched your search
@@ -1,87 +0,0 @@
|
||||
//! AirPlay device connection and streaming (placeholder)
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::cast::airplay::{AirPlayError, DiscoveredAirPlayDevice};
|
||||
|
||||
/// Metadata for AirPlay playback
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AirPlayMetadata {
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
pub album: String,
|
||||
pub artwork_url: Option<String>,
|
||||
pub duration_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// AirPlay device status (minimal for now)
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AirPlayStatus {
|
||||
pub device_id: String,
|
||||
pub device_name: String,
|
||||
pub is_connected: bool,
|
||||
}
|
||||
|
||||
/// AirPlay connection stub (RAOP sender integration pending)
|
||||
pub struct AirPlayConnection {
|
||||
device: DiscoveredAirPlayDevice,
|
||||
connected: bool,
|
||||
}
|
||||
|
||||
impl AirPlayConnection {
|
||||
/// Connect to an AirPlay device
|
||||
pub fn connect(device: DiscoveredAirPlayDevice) -> Result<Self, AirPlayError> {
|
||||
Ok(Self {
|
||||
device,
|
||||
connected: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Disconnect from the device
|
||||
pub fn disconnect(&mut self) -> Result<(), AirPlayError> {
|
||||
self.connected = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Current connection status
|
||||
pub fn get_status(&self) -> AirPlayStatus {
|
||||
AirPlayStatus {
|
||||
device_id: self.device.id.clone(),
|
||||
device_name: self.device.name.clone(),
|
||||
is_connected: self.connected,
|
||||
}
|
||||
}
|
||||
|
||||
/// Load media (requires RAOP sender integration)
|
||||
pub fn load_media(&mut self, _metadata: AirPlayMetadata) -> Result<(), AirPlayError> {
|
||||
Err(AirPlayError::NotImplemented(
|
||||
"RAOP sender integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Play/pause/stop controls
|
||||
pub fn play(&mut self) -> Result<(), AirPlayError> {
|
||||
Err(AirPlayError::NotImplemented(
|
||||
"RAOP sender integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn pause(&mut self) -> Result<(), AirPlayError> {
|
||||
Err(AirPlayError::NotImplemented(
|
||||
"RAOP sender integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) -> Result<(), AirPlayError> {
|
||||
Err(AirPlayError::NotImplemented(
|
||||
"RAOP sender integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Volume control (0.0 - 1.0)
|
||||
pub fn set_volume(&mut self, _volume: f32) -> Result<(), AirPlayError> {
|
||||
Err(AirPlayError::NotImplemented(
|
||||
"RAOP sender integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,220 +0,0 @@
|
||||
//! AirPlay device discovery via mDNS
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
use mdns_sd::{ServiceDaemon, ServiceEvent};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::cast::airplay::AirPlayError;
|
||||
|
||||
const SERVICE_RAOP: &str = "_raop._tcp.local.";
|
||||
const SERVICE_AIRPLAY: &str = "_airplay._tcp.local.";
|
||||
|
||||
/// Discovered AirPlay device
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DiscoveredAirPlayDevice {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub model: String,
|
||||
pub ip: String,
|
||||
pub port: u16,
|
||||
pub service: String,
|
||||
pub requires_password: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DiscoveryState {
|
||||
devices: HashMap<String, DiscoveredAirPlayDevice>,
|
||||
fullname_to_id: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Discovery manager for AirPlay devices
|
||||
pub struct AirPlayDiscovery {
|
||||
state: Arc<Mutex<DiscoveryState>>,
|
||||
running: Arc<AtomicBool>,
|
||||
handles: Vec<JoinHandle<()>>,
|
||||
daemon: Option<ServiceDaemon>,
|
||||
}
|
||||
|
||||
impl AirPlayDiscovery {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(DiscoveryState::default())),
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
handles: Vec::new(),
|
||||
daemon: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start mDNS discovery in background
|
||||
pub fn start_discovery(&mut self) -> Result<(), AirPlayError> {
|
||||
if self.running.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mdns = ServiceDaemon::new()
|
||||
.map_err(|e| AirPlayError::Discovery(format!("Failed to create mDNS daemon: {}", e)))?;
|
||||
|
||||
let raop_rx = mdns
|
||||
.browse(SERVICE_RAOP)
|
||||
.map_err(|e| AirPlayError::Discovery(format!("Failed to browse RAOP services: {}", e)))?;
|
||||
let airplay_rx = mdns
|
||||
.browse(SERVICE_AIRPLAY)
|
||||
.map_err(|e| AirPlayError::Discovery(format!("Failed to browse AirPlay services: {}", e)))?;
|
||||
|
||||
self.running.store(true, Ordering::SeqCst);
|
||||
|
||||
let state = self.state.clone();
|
||||
let running = self.running.clone();
|
||||
self.handles.push(spawn_receiver(
|
||||
"raop",
|
||||
raop_rx,
|
||||
state.clone(),
|
||||
running.clone(),
|
||||
));
|
||||
self.handles.push(spawn_receiver(
|
||||
"airplay",
|
||||
airplay_rx,
|
||||
state,
|
||||
running,
|
||||
));
|
||||
|
||||
self.daemon = Some(mdns);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop discovery and release resources
|
||||
pub fn stop_discovery(&mut self) -> Result<(), AirPlayError> {
|
||||
self.running.store(false, Ordering::SeqCst);
|
||||
|
||||
if let Some(daemon) = self.daemon.take() {
|
||||
daemon
|
||||
.shutdown()
|
||||
.map_err(|e| AirPlayError::Discovery(format!("Failed to shutdown mDNS: {}", e)))?;
|
||||
}
|
||||
|
||||
for handle in self.handles.drain(..) {
|
||||
let _ = handle.join();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return list of discovered devices
|
||||
pub fn get_discovered_devices(&self) -> Vec<DiscoveredAirPlayDevice> {
|
||||
self.state
|
||||
.lock()
|
||||
.map(|state| state.devices.values().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get a specific device by ID
|
||||
pub fn get_device(&self, device_id: &str) -> Option<DiscoveredAirPlayDevice> {
|
||||
self.state
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|state| state.devices.get(device_id).cloned())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AirPlayDiscovery {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_receiver(
|
||||
service_label: &'static str,
|
||||
receiver: mdns_sd::Receiver<ServiceEvent>,
|
||||
state: Arc<Mutex<DiscoveryState>>,
|
||||
running: Arc<AtomicBool>,
|
||||
) -> JoinHandle<()> {
|
||||
thread::spawn(move || {
|
||||
for event in receiver.iter() {
|
||||
if !running.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
|
||||
match event {
|
||||
ServiceEvent::ServiceResolved(info) => {
|
||||
let fullname = info.get_fullname().to_string();
|
||||
let id = device_id_from_info(&fullname, &info);
|
||||
let name = device_name_from_info(&fullname, &info, &id);
|
||||
let model = info
|
||||
.get_property_val_str("am")
|
||||
.or_else(|| info.get_property_val_str("model"))
|
||||
.unwrap_or("Unknown")
|
||||
.to_string();
|
||||
let requires_password = parse_password_required(&info);
|
||||
let ip = pick_ip(info.get_addresses())
|
||||
.unwrap_or_else(|| "127.0.0.1".to_string());
|
||||
|
||||
let device = DiscoveredAirPlayDevice {
|
||||
id: id.clone(),
|
||||
name,
|
||||
model,
|
||||
ip,
|
||||
port: info.get_port(),
|
||||
service: service_label.to_string(),
|
||||
requires_password,
|
||||
};
|
||||
|
||||
let key = format!("{}|{}", service_label, fullname);
|
||||
if let Ok(mut state) = state.lock() {
|
||||
state.fullname_to_id.insert(key, id.clone());
|
||||
state.devices.insert(id, device);
|
||||
}
|
||||
}
|
||||
ServiceEvent::ServiceRemoved(_, fullname) => {
|
||||
let key = format!("{}|{}", service_label, fullname);
|
||||
if let Ok(mut state) = state.lock() {
|
||||
if let Some(id) = state.fullname_to_id.remove(&key) {
|
||||
state.devices.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn device_id_from_info(fullname: &str, info: &mdns_sd::ServiceInfo) -> String {
|
||||
if let Some(id) = info.get_property_val_str("deviceid") {
|
||||
return id.to_string();
|
||||
}
|
||||
if let Some(id) = info.get_property_val_str("id") {
|
||||
return id.to_string();
|
||||
}
|
||||
if let Some((prefix, _)) = fullname.split_once('@') {
|
||||
return prefix.to_string();
|
||||
}
|
||||
fullname.to_string()
|
||||
}
|
||||
|
||||
fn device_name_from_info(fullname: &str, info: &mdns_sd::ServiceInfo, fallback: &str) -> String {
|
||||
if let Some(name) = info.get_property_val_str("fn") {
|
||||
return name.to_string();
|
||||
}
|
||||
if let Some((_, name)) = fullname.split_once('@') {
|
||||
return name.to_string();
|
||||
}
|
||||
fallback.to_string()
|
||||
}
|
||||
|
||||
fn parse_password_required(info: &mdns_sd::ServiceInfo) -> bool {
|
||||
match info.get_property_val_str("pw") {
|
||||
Some(value) => matches!(value, "1" | "true" | "yes" | "on"),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn pick_ip(addresses: &std::collections::HashSet<IpAddr>) -> Option<String> {
|
||||
let ipv4 = addresses.iter().find(|addr| addr.is_ipv4());
|
||||
let ip = ipv4.or_else(|| addresses.iter().next())?;
|
||||
Some(ip.to_string())
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
//! AirPlay casting errors
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum AirPlayError {
|
||||
#[error("Discovery error: {0}")]
|
||||
Discovery(String),
|
||||
|
||||
#[error("Connection error: {0}")]
|
||||
Connection(String),
|
||||
|
||||
#[error("Streaming error: {0}")]
|
||||
Streaming(String),
|
||||
|
||||
#[error("Not connected to an AirPlay device")]
|
||||
NotConnected,
|
||||
|
||||
#[error("Device not found: {0}")]
|
||||
DeviceNotFound(String),
|
||||
|
||||
#[error("Not implemented: {0}")]
|
||||
NotImplemented(String),
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
//! AirPlay casting module (discovery + scaffolding)
|
||||
//!
|
||||
//! Core functionality is in qbz-cast crate, this module provides Tauri commands.
|
||||
|
||||
pub mod commands;
|
||||
pub mod device;
|
||||
pub mod discovery;
|
||||
pub mod errors;
|
||||
|
||||
// Re-export from qbz-cast
|
||||
pub use qbz_cast::{
|
||||
AirPlayConnection, AirPlayMetadata, AirPlayStatus, AirPlayDiscovery, DiscoveredAirPlayDevice,
|
||||
AirPlayError,
|
||||
};
|
||||
|
||||
// Re-export Tauri command state
|
||||
pub use commands::AirPlayState;
|
||||
pub use device::{AirPlayConnection, AirPlayMetadata, AirPlayStatus};
|
||||
pub use discovery::{AirPlayDiscovery, DiscoveredAirPlayDevice};
|
||||
pub use errors::AirPlayError;
|
||||
@@ -1,337 +1,5 @@
|
||||
//! Chromecast connection handler running in a dedicated thread.
|
||||
//!
|
||||
//! Since rust_cast uses Rc (not Arc), it cannot be shared across threads.
|
||||
//! This module provides a thread-safe wrapper using channels.
|
||||
//! Re-exported from qbz-cast crate.
|
||||
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::cast::device::CastDeviceConnection;
|
||||
use crate::cast::errors::CastError;
|
||||
use crate::cast::{CastStatus, MediaMetadata, CastPositionInfo};
|
||||
|
||||
/// Commands sent to the Chromecast thread
|
||||
pub enum CastCommand {
|
||||
Connect {
|
||||
ip: String,
|
||||
port: u16,
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
Disconnect {
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
GetStatus {
|
||||
reply: Sender<Result<CastStatus, CastError>>,
|
||||
},
|
||||
GetMediaPosition {
|
||||
reply: Sender<Result<CastPositionInfo, CastError>>,
|
||||
},
|
||||
LoadMedia {
|
||||
url: String,
|
||||
content_type: String,
|
||||
metadata: MediaMetadata,
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
Play {
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
Pause {
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
Stop {
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
SetVolume {
|
||||
volume: f32,
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
Seek {
|
||||
position_secs: f64,
|
||||
reply: Sender<Result<(), CastError>>,
|
||||
},
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// Thread-safe handle to communicate with the Chromecast thread
|
||||
pub struct ChromecastHandle {
|
||||
sender: Sender<CastCommand>,
|
||||
_thread: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl ChromecastHandle {
|
||||
/// Start the Chromecast handler thread
|
||||
pub fn new() -> Self {
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
let thread = thread::spawn(move || {
|
||||
chromecast_thread_main(receiver);
|
||||
});
|
||||
|
||||
Self {
|
||||
sender,
|
||||
_thread: thread,
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect to a Chromecast device
|
||||
pub fn connect(&self, ip: String, port: u16) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::Connect {
|
||||
ip,
|
||||
port,
|
||||
reply: reply_tx,
|
||||
})
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Disconnect from the current device
|
||||
pub fn disconnect(&self) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::Disconnect { reply: reply_tx })
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Get device status
|
||||
pub fn get_status(&self) -> Result<CastStatus, CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::GetStatus { reply: reply_tx })
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Load media for playback
|
||||
pub fn load_media(
|
||||
&self,
|
||||
url: String,
|
||||
content_type: String,
|
||||
metadata: MediaMetadata,
|
||||
) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::LoadMedia {
|
||||
url,
|
||||
content_type,
|
||||
metadata,
|
||||
reply: reply_tx,
|
||||
})
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Play
|
||||
pub fn play(&self) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::Play { reply: reply_tx })
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Pause
|
||||
pub fn pause(&self) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::Pause { reply: reply_tx })
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Stop
|
||||
pub fn stop(&self) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::Stop { reply: reply_tx })
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Set volume
|
||||
pub fn set_volume(&self, volume: f32) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::SetVolume {
|
||||
volume,
|
||||
reply: reply_tx,
|
||||
})
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Seek
|
||||
pub fn seek(&self, position_secs: f64) -> Result<(), CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::Seek {
|
||||
position_secs,
|
||||
reply: reply_tx,
|
||||
})
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
|
||||
/// Get media position for seekbar updates
|
||||
pub fn get_media_position(&self) -> Result<CastPositionInfo, CastError> {
|
||||
let (reply_tx, reply_rx) = mpsc::channel();
|
||||
self.sender
|
||||
.send(CastCommand::GetMediaPosition { reply: reply_tx })
|
||||
.map_err(|_| CastError::Connection("Thread communication error".to_string()))?;
|
||||
reply_rx
|
||||
.recv()
|
||||
.map_err(|_| CastError::Connection("Thread response error".to_string()))?
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ChromecastHandle {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.sender.send(CastCommand::Shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(25);
|
||||
|
||||
/// Main loop for the Chromecast thread
|
||||
fn chromecast_thread_main(receiver: Receiver<CastCommand>) {
|
||||
let mut connection: Option<CastDeviceConnection> = None;
|
||||
|
||||
loop {
|
||||
let command = match receiver.recv_timeout(HEARTBEAT_INTERVAL) {
|
||||
Ok(cmd) => cmd,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if let Some(conn) = connection.as_ref() {
|
||||
if let Err(err) = conn.heartbeat() {
|
||||
log::warn!("Chromecast heartbeat failed: {}", err);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => break, // Channel closed
|
||||
};
|
||||
|
||||
match command {
|
||||
CastCommand::Connect { ip, port, reply } => {
|
||||
let result = CastDeviceConnection::connect(&ip, port);
|
||||
match result {
|
||||
Ok(conn) => {
|
||||
connection = Some(conn);
|
||||
let _ = reply.send(Ok(()));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = reply.send(Err(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CastCommand::Disconnect { reply } => {
|
||||
let result = if let Some(ref mut conn) = connection {
|
||||
conn.disconnect()
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
connection = None;
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::GetStatus { reply } => {
|
||||
let result = match connection.as_ref() {
|
||||
Some(conn) => conn.get_status(),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::GetMediaPosition { reply } => {
|
||||
let result = match connection.as_mut() {
|
||||
Some(conn) => conn.get_media_position(),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::LoadMedia {
|
||||
url,
|
||||
content_type,
|
||||
metadata,
|
||||
reply,
|
||||
} => {
|
||||
let result = match connection.as_mut() {
|
||||
Some(conn) => conn.load_media(&url, &content_type, metadata),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::Play { reply } => {
|
||||
let result = match connection.as_mut() {
|
||||
Some(conn) => conn.play(),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::Pause { reply } => {
|
||||
let result = match connection.as_mut() {
|
||||
Some(conn) => conn.pause(),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::Stop { reply } => {
|
||||
let result = match connection.as_mut() {
|
||||
Some(conn) => conn.stop(),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::SetVolume { volume, reply } => {
|
||||
let result = match connection.as_mut() {
|
||||
Some(conn) => conn.set_volume(volume),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::Seek {
|
||||
position_secs,
|
||||
reply,
|
||||
} => {
|
||||
let result = match connection.as_mut() {
|
||||
Some(conn) => conn.seek(position_secs),
|
||||
None => Err(CastError::NotConnected),
|
||||
};
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
|
||||
CastCommand::Shutdown => {
|
||||
if let Some(mut conn) = connection.take() {
|
||||
let _ = conn.disconnect();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub use qbz_cast::{CastCommand, ChromecastHandle};
|
||||
@@ -1,352 +1,7 @@
|
||||
//! Chromecast device connection and media control
|
||||
//!
|
||||
//! Re-exported from qbz-cast crate.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use rust_cast::CastDevice;
|
||||
use rust_cast::channels::media::{Image, Media, Metadata, MusicTrackMediaMetadata, StreamType, PlayerState, IdleReason};
|
||||
use rust_cast::channels::receiver::{CastDeviceApp, Status as ReceiverStatus};
|
||||
|
||||
use crate::cast::CastError;
|
||||
|
||||
const DEFAULT_RECEIVER_ID: &str = "receiver-0";
|
||||
|
||||
/// Media metadata for casting
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MediaMetadata {
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
pub album: String,
|
||||
pub artwork_url: Option<String>,
|
||||
pub duration_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// Media position info for seekbar updates
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CastPositionInfo {
|
||||
pub position_secs: f64,
|
||||
pub duration_secs: f64,
|
||||
pub player_state: String,
|
||||
pub idle_reason: Option<String>,
|
||||
}
|
||||
|
||||
/// Device status for frontend
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CastStatus {
|
||||
pub applications: Vec<CastApplication>,
|
||||
pub is_active_input: bool,
|
||||
pub is_stand_by: bool,
|
||||
pub volume_level: Option<f32>,
|
||||
pub volume_muted: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CastApplication {
|
||||
pub app_id: String,
|
||||
pub display_name: String,
|
||||
pub status_text: String,
|
||||
}
|
||||
|
||||
struct CastSession {
|
||||
#[allow(dead_code)]
|
||||
app_id: String,
|
||||
session_id: String,
|
||||
transport_id: String,
|
||||
media_session_id: Option<i32>,
|
||||
}
|
||||
|
||||
/// Wrapper around rust-cast for managing Chromecast devices
|
||||
pub struct CastDeviceConnection {
|
||||
device: CastDevice<'static>,
|
||||
session: Option<CastSession>,
|
||||
}
|
||||
|
||||
impl CastDeviceConnection {
|
||||
/// Connect to a Chromecast by IP and port
|
||||
pub fn connect(ip: &str, port: u16) -> Result<Self, CastError> {
|
||||
let device = CastDevice::connect_without_host_verification(ip.to_string(), port)
|
||||
.map_err(|e| CastError::Connection(e.to_string()))?;
|
||||
|
||||
device
|
||||
.connection
|
||||
.connect(DEFAULT_RECEIVER_ID)
|
||||
.map_err(|e| CastError::Connection(e.to_string()))?;
|
||||
|
||||
let _ = device.heartbeat.ping();
|
||||
|
||||
Ok(Self {
|
||||
device,
|
||||
session: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Keep the connection alive with a heartbeat ping
|
||||
pub fn heartbeat(&self) -> Result<(), CastError> {
|
||||
self.device
|
||||
.heartbeat
|
||||
.ping()
|
||||
.map_err(|e| CastError::Connection(e.to_string()))
|
||||
}
|
||||
|
||||
/// Disconnect from device
|
||||
pub fn disconnect(&mut self) -> Result<(), CastError> {
|
||||
if let Some(session) = &self.session {
|
||||
let _ = self.device.connection.disconnect(session.transport_id.as_str());
|
||||
}
|
||||
let _ = self.device.connection.disconnect(DEFAULT_RECEIVER_ID);
|
||||
self.session = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get device status
|
||||
pub fn get_status(&self) -> Result<CastStatus, CastError> {
|
||||
let status = self
|
||||
.device
|
||||
.receiver
|
||||
.get_status()
|
||||
.map_err(|e| CastError::Connection(e.to_string()))?;
|
||||
Ok(Self::map_status(status))
|
||||
}
|
||||
|
||||
/// Launch media receiver app
|
||||
pub fn launch_media_app(&mut self) -> Result<String, CastError> {
|
||||
let app = self
|
||||
.device
|
||||
.receiver
|
||||
.launch_app(&CastDeviceApp::DefaultMediaReceiver)
|
||||
.map_err(|e| CastError::Connection(e.to_string()))?;
|
||||
|
||||
self.device
|
||||
.connection
|
||||
.connect(app.transport_id.as_str())
|
||||
.map_err(|e| CastError::Connection(e.to_string()))?;
|
||||
|
||||
self.session = Some(CastSession {
|
||||
app_id: app.app_id.clone(),
|
||||
session_id: app.session_id.clone(),
|
||||
transport_id: app.transport_id.clone(),
|
||||
media_session_id: None,
|
||||
});
|
||||
|
||||
Ok(app.session_id)
|
||||
}
|
||||
|
||||
/// Load media URL for playback
|
||||
pub fn load_media(
|
||||
&mut self,
|
||||
url: &str,
|
||||
content_type: &str,
|
||||
metadata: MediaMetadata,
|
||||
) -> Result<(), CastError> {
|
||||
self.ensure_session()?;
|
||||
|
||||
let session = self.session.as_ref().ok_or(CastError::NotConnected)?;
|
||||
let media = Media {
|
||||
content_id: url.to_string(),
|
||||
stream_type: StreamType::Buffered,
|
||||
content_type: content_type.to_string(),
|
||||
duration: metadata.duration_secs.map(|d| d as f32),
|
||||
metadata: Some(Self::map_metadata(metadata)),
|
||||
};
|
||||
|
||||
let status = self
|
||||
.device
|
||||
.media
|
||||
.load(session.transport_id.as_str(), session.session_id.as_str(), &media)
|
||||
.map_err(|e| CastError::Media(e.to_string()))?;
|
||||
|
||||
if let Some(entry) = status.entries.first() {
|
||||
if let Some(session) = self.session.as_mut() {
|
||||
session.media_session_id = Some(entry.media_session_id);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Play current media session
|
||||
pub fn play(&mut self) -> Result<(), CastError> {
|
||||
let (destination, media_session_id) = self.ensure_media_session()?;
|
||||
self.device
|
||||
.media
|
||||
.play(destination.as_str(), media_session_id)
|
||||
.map_err(|e| CastError::Media(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pause current media session
|
||||
pub fn pause(&mut self) -> Result<(), CastError> {
|
||||
let (destination, media_session_id) = self.ensure_media_session()?;
|
||||
self.device
|
||||
.media
|
||||
.pause(destination.as_str(), media_session_id)
|
||||
.map_err(|e| CastError::Media(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop current media session
|
||||
pub fn stop(&mut self) -> Result<(), CastError> {
|
||||
let (destination, media_session_id) = self.ensure_media_session()?;
|
||||
self.device
|
||||
.media
|
||||
.stop(destination.as_str(), media_session_id)
|
||||
.map_err(|e| CastError::Media(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Volume control (0.0 - 1.0)
|
||||
pub fn set_volume(&mut self, volume: f32) -> Result<(), CastError> {
|
||||
let clamped = volume.clamp(0.0, 1.0);
|
||||
self.device
|
||||
.receiver
|
||||
.set_volume(clamped)
|
||||
.map_err(|e| CastError::Connection(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Seek to position
|
||||
pub fn seek(&mut self, position_secs: f64) -> Result<(), CastError> {
|
||||
let (destination, media_session_id) = self.ensure_media_session()?;
|
||||
self.device
|
||||
.media
|
||||
.seek(
|
||||
destination.as_str(),
|
||||
media_session_id,
|
||||
Some(position_secs as f32),
|
||||
None,
|
||||
)
|
||||
.map_err(|e| CastError::Media(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get current media position for seekbar updates
|
||||
pub fn get_media_position(&mut self) -> Result<CastPositionInfo, CastError> {
|
||||
let session = self.session.as_ref().ok_or(CastError::NotConnected)?;
|
||||
let destination = &session.transport_id;
|
||||
|
||||
let status = self
|
||||
.device
|
||||
.media
|
||||
.get_status(destination.as_str(), None)
|
||||
.map_err(|e| CastError::Media(e.to_string()))?;
|
||||
|
||||
// Get the first media entry (current playing item)
|
||||
if let Some(entry) = status.entries.first() {
|
||||
let player_state = match entry.player_state {
|
||||
PlayerState::Idle => "IDLE",
|
||||
PlayerState::Playing => "PLAYING",
|
||||
PlayerState::Paused => "PAUSED",
|
||||
PlayerState::Buffering => "BUFFERING",
|
||||
};
|
||||
|
||||
let idle_reason = entry.idle_reason.as_ref().map(|r| match r {
|
||||
IdleReason::Cancelled => "CANCELLED".to_string(),
|
||||
IdleReason::Interrupted => "INTERRUPTED".to_string(),
|
||||
IdleReason::Finished => "FINISHED".to_string(),
|
||||
IdleReason::Error => "ERROR".to_string(),
|
||||
});
|
||||
|
||||
let duration = entry.media.as_ref()
|
||||
.and_then(|m| m.duration)
|
||||
.unwrap_or(0.0) as f64;
|
||||
|
||||
let position = entry.current_time.unwrap_or(0.0) as f64;
|
||||
|
||||
Ok(CastPositionInfo {
|
||||
position_secs: position,
|
||||
duration_secs: duration,
|
||||
player_state: player_state.to_string(),
|
||||
idle_reason,
|
||||
})
|
||||
} else {
|
||||
// No media playing
|
||||
Ok(CastPositionInfo {
|
||||
position_secs: 0.0,
|
||||
duration_secs: 0.0,
|
||||
player_state: "IDLE".to_string(),
|
||||
idle_reason: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_session(&mut self) -> Result<(), CastError> {
|
||||
if self.session.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
self.launch_media_app().map(|_| ())
|
||||
}
|
||||
|
||||
fn ensure_media_session(&mut self) -> Result<(String, i32), CastError> {
|
||||
self.ensure_session()?;
|
||||
|
||||
let destination = self
|
||||
.session
|
||||
.as_ref()
|
||||
.ok_or(CastError::NotConnected)?
|
||||
.transport_id
|
||||
.clone();
|
||||
|
||||
if let Some(id) = self
|
||||
.session
|
||||
.as_ref()
|
||||
.and_then(|session| session.media_session_id)
|
||||
{
|
||||
return Ok((destination, id));
|
||||
}
|
||||
|
||||
let status = self
|
||||
.device
|
||||
.media
|
||||
.get_status(destination.as_str(), None)
|
||||
.map_err(|e| CastError::Media(e.to_string()))?;
|
||||
|
||||
let entry = status
|
||||
.entries
|
||||
.first()
|
||||
.ok_or_else(|| CastError::Media("No media session available".to_string()))?;
|
||||
|
||||
if let Some(session) = self.session.as_mut() {
|
||||
session.media_session_id = Some(entry.media_session_id);
|
||||
}
|
||||
|
||||
Ok((destination, entry.media_session_id))
|
||||
}
|
||||
|
||||
fn map_status(status: ReceiverStatus) -> CastStatus {
|
||||
let applications = status
|
||||
.applications
|
||||
.iter()
|
||||
.map(|app| CastApplication {
|
||||
app_id: app.app_id.clone(),
|
||||
display_name: app.display_name.clone(),
|
||||
status_text: app.status_text.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
CastStatus {
|
||||
applications,
|
||||
is_active_input: status.is_active_input,
|
||||
is_stand_by: status.is_stand_by,
|
||||
volume_level: status.volume.level,
|
||||
volume_muted: status.volume.muted,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_metadata(metadata: MediaMetadata) -> Metadata {
|
||||
let mut images = Vec::new();
|
||||
if let Some(url) = metadata.artwork_url.clone() {
|
||||
images.push(Image::new(url));
|
||||
}
|
||||
|
||||
Metadata::MusicTrack(MusicTrackMediaMetadata {
|
||||
album_name: Some(metadata.album),
|
||||
title: Some(metadata.title),
|
||||
album_artist: None,
|
||||
artist: Some(metadata.artist),
|
||||
composer: None,
|
||||
track_number: None,
|
||||
disc_number: None,
|
||||
images,
|
||||
release_date: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
pub use qbz_cast::{
|
||||
CastApplication, CastDeviceConnection, CastPositionInfo, CastStatus, MediaMetadata,
|
||||
};
|
||||
@@ -1,166 +1,5 @@
|
||||
//! Chromecast device discovery via mDNS
|
||||
//!
|
||||
//! Re-exported from qbz-cast crate.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
use mdns_sd::{ServiceDaemon, ServiceEvent};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::cast::CastError;
|
||||
|
||||
const SERVICE_TYPE: &str = "_googlecast._tcp.local.";
|
||||
|
||||
/// Discovered Chromecast device
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DiscoveredDevice {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub model: String,
|
||||
pub ip: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DiscoveryState {
|
||||
devices: HashMap<String, DiscoveredDevice>,
|
||||
fullname_to_id: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Discovery manager for Chromecast devices
|
||||
pub struct DeviceDiscovery {
|
||||
state: Arc<Mutex<DiscoveryState>>,
|
||||
running: Arc<AtomicBool>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
daemon: Option<ServiceDaemon>,
|
||||
}
|
||||
|
||||
impl DeviceDiscovery {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(DiscoveryState::default())),
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
handle: None,
|
||||
daemon: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start mDNS discovery in background
|
||||
pub fn start_discovery(&mut self) -> Result<(), CastError> {
|
||||
if self.running.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mdns = ServiceDaemon::new()
|
||||
.map_err(|e| CastError::Discovery(format!("Failed to create mDNS daemon: {}", e)))?;
|
||||
let receiver = mdns
|
||||
.browse(SERVICE_TYPE)
|
||||
.map_err(|e| CastError::Discovery(format!("Failed to browse mDNS services: {}", e)))?;
|
||||
|
||||
let running = self.running.clone();
|
||||
let state = self.state.clone();
|
||||
|
||||
running.store(true, Ordering::SeqCst);
|
||||
|
||||
let handle = thread::spawn(move || {
|
||||
for event in receiver.iter() {
|
||||
if !running.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
|
||||
match event {
|
||||
ServiceEvent::ServiceResolved(info) => {
|
||||
let fullname = info.get_fullname().to_string();
|
||||
let id = info
|
||||
.get_property_val_str("id")
|
||||
.unwrap_or_else(|| fullname.as_str())
|
||||
.to_string();
|
||||
let name = info
|
||||
.get_property_val_str("fn")
|
||||
.unwrap_or_else(|| id.as_str())
|
||||
.to_string();
|
||||
let model = info
|
||||
.get_property_val_str("md")
|
||||
.unwrap_or("Unknown")
|
||||
.to_string();
|
||||
|
||||
let ip = pick_ip(info.get_addresses())
|
||||
.unwrap_or_else(|| "127.0.0.1".to_string());
|
||||
|
||||
let device = DiscoveredDevice {
|
||||
id: id.clone(),
|
||||
name,
|
||||
model,
|
||||
ip,
|
||||
port: info.get_port(),
|
||||
};
|
||||
|
||||
if let Ok(mut state) = state.lock() {
|
||||
state.fullname_to_id.insert(fullname, id.clone());
|
||||
state.devices.insert(id, device);
|
||||
}
|
||||
}
|
||||
ServiceEvent::ServiceRemoved(_, fullname) => {
|
||||
if let Ok(mut state) = state.lock() {
|
||||
if let Some(id) = state.fullname_to_id.remove(&fullname) {
|
||||
state.devices.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
self.daemon = Some(mdns);
|
||||
self.handle = Some(handle);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop discovery and release resources
|
||||
pub fn stop_discovery(&mut self) -> Result<(), CastError> {
|
||||
self.running.store(false, Ordering::SeqCst);
|
||||
|
||||
if let Some(daemon) = self.daemon.take() {
|
||||
daemon
|
||||
.shutdown()
|
||||
.map_err(|e| CastError::Discovery(format!("Failed to shutdown mDNS: {}", e)))?;
|
||||
}
|
||||
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return list of discovered devices
|
||||
pub fn get_discovered_devices(&self) -> Vec<DiscoveredDevice> {
|
||||
self.state
|
||||
.lock()
|
||||
.map(|state| state.devices.values().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get a specific device by ID
|
||||
pub fn get_device(&self, device_id: &str) -> Option<DiscoveredDevice> {
|
||||
self.state
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|state| state.devices.get(device_id).cloned())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DeviceDiscovery {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn pick_ip(addresses: &std::collections::HashSet<IpAddr>) -> Option<String> {
|
||||
let ipv4 = addresses.iter().find(|addr| addr.is_ipv4());
|
||||
let ip = ipv4.or_else(|| addresses.iter().next())?;
|
||||
Some(ip.to_string())
|
||||
}
|
||||
pub use qbz_cast::{DeviceDiscovery, DiscoveredDevice};
|
||||
@@ -1,400 +0,0 @@
|
||||
//! DLNA device connection and playback via AVTransport SOAP
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use rupnp::{Device, Service};
|
||||
use rupnp::http::Uri;
|
||||
use rupnp::ssdp::URN;
|
||||
|
||||
use crate::cast::dlna::{DiscoveredDlnaDevice, DlnaError};
|
||||
|
||||
/// Metadata for DLNA playback
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DlnaMetadata {
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
pub album: String,
|
||||
pub artwork_url: Option<String>,
|
||||
pub duration_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// DLNA playback position info
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DlnaPositionInfo {
|
||||
pub position_secs: u64,
|
||||
pub duration_secs: u64,
|
||||
pub transport_state: String, // PLAYING, PAUSED_PLAYBACK, STOPPED, etc.
|
||||
}
|
||||
|
||||
/// DLNA device status
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DlnaStatus {
|
||||
pub device_id: String,
|
||||
pub device_name: String,
|
||||
pub is_connected: bool,
|
||||
pub is_playing: bool,
|
||||
pub current_uri: Option<String>,
|
||||
}
|
||||
|
||||
/// DLNA connection with AVTransport and RenderingControl support
|
||||
pub struct DlnaConnection {
|
||||
device: DiscoveredDlnaDevice,
|
||||
connected: bool,
|
||||
device_url: Uri,
|
||||
av_transport_service: Option<Service>,
|
||||
rendering_control_service: Option<Service>,
|
||||
// Current media URI
|
||||
current_uri: Option<String>,
|
||||
is_playing: bool,
|
||||
}
|
||||
|
||||
impl DlnaConnection {
|
||||
/// Connect to a DLNA device and discover service URLs
|
||||
pub async fn connect(device: DiscoveredDlnaDevice) -> Result<Self, DlnaError> {
|
||||
let device_url: Uri = device
|
||||
.url
|
||||
.parse()
|
||||
.map_err(|e| DlnaError::Connection(format!("Invalid device URL: {}", e)))?;
|
||||
|
||||
let parsed_device = Device::from_url(device_url.clone())
|
||||
.await
|
||||
.map_err(|e| DlnaError::Connection(format!("Failed to load device description: {}", e)))?;
|
||||
|
||||
let av_transport_service = parsed_device
|
||||
.find_service(&av_transport_urn())
|
||||
.cloned();
|
||||
let rendering_control_service = parsed_device
|
||||
.find_service(&rendering_control_urn())
|
||||
.cloned();
|
||||
|
||||
log::info!(
|
||||
"DLNA: Connected to {} (AVT: {:?}, RC: {:?})",
|
||||
device.name,
|
||||
av_transport_service.is_some(),
|
||||
rendering_control_service.is_some()
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
device,
|
||||
connected: true,
|
||||
device_url,
|
||||
av_transport_service,
|
||||
rendering_control_service,
|
||||
current_uri: None,
|
||||
is_playing: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Disconnect from the device
|
||||
pub fn disconnect(&mut self) -> Result<(), DlnaError> {
|
||||
self.connected = false;
|
||||
self.current_uri = None;
|
||||
self.is_playing = false;
|
||||
log::info!("DLNA: Disconnected from {}", self.device.name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Current connection status
|
||||
pub fn get_status(&self) -> DlnaStatus {
|
||||
DlnaStatus {
|
||||
device_id: self.device.id.clone(),
|
||||
device_name: self.device.name.clone(),
|
||||
is_connected: self.connected,
|
||||
is_playing: self.is_playing,
|
||||
current_uri: self.current_uri.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn device_ip(&self) -> &str {
|
||||
&self.device.ip
|
||||
}
|
||||
|
||||
/// Set the media URI and start playback
|
||||
pub async fn load_media(&mut self, uri: &str, metadata: &DlnaMetadata, content_type: &str) -> Result<(), DlnaError> {
|
||||
if !self.connected {
|
||||
return Err(DlnaError::NotConnected);
|
||||
}
|
||||
|
||||
let av_service = self.av_transport_service.as_ref()
|
||||
.ok_or_else(|| DlnaError::Playback("Device has no AVTransport service".to_string()))?;
|
||||
|
||||
// Build DIDL-Lite metadata with actual content type
|
||||
let didl_metadata = build_didl_metadata(uri, metadata, content_type);
|
||||
|
||||
log::info!("DLNA: Loading media URI: {}", uri);
|
||||
log::info!("DLNA: Content-Type: {}", content_type);
|
||||
log::info!("DLNA: DIDL Metadata:\n{}", didl_metadata);
|
||||
|
||||
let payload = format!(
|
||||
"<InstanceID>0</InstanceID><CurrentURI>{}</CurrentURI><CurrentURIMetaData>{}</CurrentURIMetaData>",
|
||||
xml_escape(uri),
|
||||
xml_escape(&didl_metadata)
|
||||
);
|
||||
|
||||
let response = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
av_service.action(&self.device_url, "SetAVTransportURI", &payload)
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
log::error!("DLNA: SetAVTransportURI timed out after 10s");
|
||||
DlnaError::Playback("SetAVTransportURI timed out".to_string())
|
||||
})?
|
||||
.map_err(|e| {
|
||||
log::error!("DLNA: SetAVTransportURI failed: {}", e);
|
||||
DlnaError::Playback(e.to_string())
|
||||
})?;
|
||||
|
||||
log::info!("DLNA: SetAVTransportURI response: {:?}", response);
|
||||
self.current_uri = Some(uri.to_string());
|
||||
log::info!("DLNA: Set URI to {}", uri);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start/resume playback
|
||||
pub async fn play(&mut self) -> Result<(), DlnaError> {
|
||||
if !self.connected {
|
||||
return Err(DlnaError::NotConnected);
|
||||
}
|
||||
|
||||
let av_service = self.av_transport_service.as_ref()
|
||||
.ok_or_else(|| DlnaError::Playback("Device has no AVTransport service".to_string()))?;
|
||||
|
||||
let response = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
av_service.action(&self.device_url, "Play", "<InstanceID>0</InstanceID><Speed>1</Speed>")
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
log::error!("DLNA: Play action timed out after 10s");
|
||||
DlnaError::Playback("Play action timed out".to_string())
|
||||
})?
|
||||
.map_err(|e| {
|
||||
log::error!("DLNA: Play action failed: {}", e);
|
||||
DlnaError::Playback(e.to_string())
|
||||
})?;
|
||||
|
||||
log::info!("DLNA: Play response: {:?}", response);
|
||||
self.is_playing = true;
|
||||
log::info!("DLNA: Play started successfully");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pause playback
|
||||
pub async fn pause(&mut self) -> Result<(), DlnaError> {
|
||||
if !self.connected {
|
||||
return Err(DlnaError::NotConnected);
|
||||
}
|
||||
|
||||
let av_service = self.av_transport_service.as_ref()
|
||||
.ok_or_else(|| DlnaError::Playback("Device has no AVTransport service".to_string()))?;
|
||||
|
||||
av_service
|
||||
.action(&self.device_url, "Pause", "<InstanceID>0</InstanceID>")
|
||||
.await
|
||||
.map_err(|e| DlnaError::Playback(e.to_string()))?;
|
||||
|
||||
self.is_playing = false;
|
||||
log::info!("DLNA: Pause");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop playback
|
||||
pub async fn stop(&mut self) -> Result<(), DlnaError> {
|
||||
if !self.connected {
|
||||
return Err(DlnaError::NotConnected);
|
||||
}
|
||||
|
||||
let av_service = self.av_transport_service.as_ref()
|
||||
.ok_or_else(|| DlnaError::Playback("Device has no AVTransport service".to_string()))?;
|
||||
|
||||
av_service
|
||||
.action(&self.device_url, "Stop", "<InstanceID>0</InstanceID>")
|
||||
.await
|
||||
.map_err(|e| DlnaError::Playback(e.to_string()))?;
|
||||
|
||||
self.is_playing = false;
|
||||
self.current_uri = None;
|
||||
log::info!("DLNA: Stop");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Seek to position
|
||||
pub async fn seek(&mut self, position_secs: u64) -> Result<(), DlnaError> {
|
||||
if !self.connected {
|
||||
return Err(DlnaError::NotConnected);
|
||||
}
|
||||
|
||||
let hours = position_secs / 3600;
|
||||
let minutes = (position_secs % 3600) / 60;
|
||||
let seconds = position_secs % 60;
|
||||
let time_str = format!("{:02}:{:02}:{:02}", hours, minutes, seconds);
|
||||
|
||||
let av_service = self.av_transport_service.as_ref()
|
||||
.ok_or_else(|| DlnaError::Playback("Device has no AVTransport service".to_string()))?;
|
||||
|
||||
let payload = format!(
|
||||
"<InstanceID>0</InstanceID><Unit>REL_TIME</Unit><Target>{}</Target>",
|
||||
time_str
|
||||
);
|
||||
|
||||
av_service
|
||||
.action(&self.device_url, "Seek", &payload)
|
||||
.await
|
||||
.map_err(|e| DlnaError::Playback(e.to_string()))?;
|
||||
|
||||
log::info!("DLNA: Seek to {}", time_str);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set volume (0.0 - 1.0)
|
||||
pub async fn set_volume(&mut self, volume: f32) -> Result<(), DlnaError> {
|
||||
if !self.connected {
|
||||
return Err(DlnaError::NotConnected);
|
||||
}
|
||||
|
||||
let rc_service = self.rendering_control_service.as_ref()
|
||||
.ok_or_else(|| DlnaError::Playback("Device has no RenderingControl service".to_string()))?;
|
||||
|
||||
// DLNA volume is typically 0-100
|
||||
let dlna_volume = ((volume.clamp(0.0, 1.0) * 100.0) as u32).min(100);
|
||||
|
||||
let payload = format!(
|
||||
"<InstanceID>0</InstanceID><Channel>Master</Channel><DesiredVolume>{}</DesiredVolume>",
|
||||
dlna_volume
|
||||
);
|
||||
|
||||
rc_service
|
||||
.action(&self.device_url, "SetVolume", &payload)
|
||||
.await
|
||||
.map_err(|e| DlnaError::Playback(e.to_string()))?;
|
||||
|
||||
log::info!("DLNA: Set volume to {}", dlna_volume);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get current playback position and transport state
|
||||
pub async fn get_position_info(&self) -> Result<DlnaPositionInfo, DlnaError> {
|
||||
if !self.connected {
|
||||
return Err(DlnaError::NotConnected);
|
||||
}
|
||||
|
||||
let av_service = self.av_transport_service.as_ref()
|
||||
.ok_or_else(|| DlnaError::Playback("Device has no AVTransport service".to_string()))?;
|
||||
|
||||
// Get position info
|
||||
let position_response = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
av_service.action(&self.device_url, "GetPositionInfo", "<InstanceID>0</InstanceID>")
|
||||
)
|
||||
.await
|
||||
.map_err(|_| DlnaError::Playback("GetPositionInfo timed out".to_string()))?
|
||||
.map_err(|e| DlnaError::Playback(e.to_string()))?;
|
||||
|
||||
// Get transport state
|
||||
let transport_response = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
av_service.action(&self.device_url, "GetTransportInfo", "<InstanceID>0</InstanceID>")
|
||||
)
|
||||
.await
|
||||
.map_err(|_| DlnaError::Playback("GetTransportInfo timed out".to_string()))?
|
||||
.map_err(|e| DlnaError::Playback(e.to_string()))?;
|
||||
|
||||
// Parse RelTime (position) - format: "HH:MM:SS" or "H:MM:SS"
|
||||
let rel_time = position_response.get("RelTime")
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("0:00:00");
|
||||
let position_secs = parse_time_string(rel_time);
|
||||
|
||||
// Parse TrackDuration - format: "HH:MM:SS"
|
||||
let track_duration = position_response.get("TrackDuration")
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("0:00:00");
|
||||
let duration_secs = parse_time_string(track_duration);
|
||||
|
||||
// Get transport state (PLAYING, PAUSED_PLAYBACK, STOPPED, etc.)
|
||||
let transport_state = transport_response.get("CurrentTransportState")
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| "UNKNOWN".to_string());
|
||||
|
||||
Ok(DlnaPositionInfo {
|
||||
position_secs,
|
||||
duration_secs,
|
||||
transport_state,
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Parse time string "HH:MM:SS" or "H:MM:SS" to seconds
|
||||
fn parse_time_string(time: &str) -> u64 {
|
||||
let parts: Vec<&str> = time.split(':').collect();
|
||||
if parts.len() != 3 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let hours: u64 = parts[0].parse().unwrap_or(0);
|
||||
let minutes: u64 = parts[1].parse().unwrap_or(0);
|
||||
let seconds: u64 = parts[2].split('.').next()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
hours * 3600 + minutes * 60 + seconds
|
||||
}
|
||||
|
||||
/// Build DIDL-Lite metadata for a track
|
||||
fn build_didl_metadata(uri: &str, metadata: &DlnaMetadata, content_type: &str) -> String {
|
||||
let duration = metadata.duration_secs.map(|d| {
|
||||
let hours = d / 3600;
|
||||
let minutes = (d % 3600) / 60;
|
||||
let seconds = d % 60;
|
||||
format!("{:02}:{:02}:{:02}", hours, minutes, seconds)
|
||||
}).unwrap_or_else(|| "00:00:00".to_string());
|
||||
|
||||
let artwork = metadata.artwork_url.as_ref()
|
||||
.map(|url| format!(r#"<upnp:albumArtURI>{}</upnp:albumArtURI>"#, xml_escape(url)))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Use actual content type for protocolInfo - critical for DLNA compatibility
|
||||
// Many devices reject content if protocolInfo doesn't match actual MIME type
|
||||
let protocol_info = format!("http-get:*:{}:*", content_type);
|
||||
|
||||
format!(
|
||||
r#"<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">
|
||||
<item id="0" parentID="-1" restricted="1">
|
||||
<dc:title>{}</dc:title>
|
||||
<dc:creator>{}</dc:creator>
|
||||
<upnp:album>{}</upnp:album>
|
||||
<upnp:artist>{}</upnp:artist>
|
||||
{}
|
||||
<res duration="{}" protocolInfo="{}">{}</res>
|
||||
<upnp:class>object.item.audioItem.musicTrack</upnp:class>
|
||||
</item>
|
||||
</DIDL-Lite>"#,
|
||||
xml_escape(&metadata.title),
|
||||
xml_escape(&metadata.artist),
|
||||
xml_escape(&metadata.album),
|
||||
xml_escape(&metadata.artist),
|
||||
artwork,
|
||||
duration,
|
||||
protocol_info,
|
||||
xml_escape(uri)
|
||||
)
|
||||
}
|
||||
|
||||
/// Escape special XML characters
|
||||
fn xml_escape(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
fn av_transport_urn() -> URN {
|
||||
URN::Service("schemas-upnp-org".into(), "AVTransport".into(), 1)
|
||||
}
|
||||
|
||||
fn rendering_control_urn() -> URN {
|
||||
URN::Service("schemas-upnp-org".into(), "RenderingControl".into(), 1)
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
//! DLNA/UPnP device discovery via SSDP
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::TryStreamExt;
|
||||
use rupnp::ssdp::{SearchTarget, URN};
|
||||
use serde::Serialize;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::cast::dlna::DlnaError;
|
||||
|
||||
const DISCOVERY_WINDOW_SECS: u64 = 3;
|
||||
const DISCOVERY_SLEEP_SECS: u64 = 5;
|
||||
|
||||
/// Discovered DLNA/UPnP device
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DiscoveredDlnaDevice {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub manufacturer: String,
|
||||
pub model: String,
|
||||
pub ip: String,
|
||||
pub url: String,
|
||||
pub has_av_transport: bool,
|
||||
pub has_rendering_control: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DiscoveryState {
|
||||
devices: HashMap<String, DiscoveredDlnaDevice>,
|
||||
}
|
||||
|
||||
/// Discovery manager for DLNA devices
|
||||
pub struct DlnaDiscovery {
|
||||
state: Arc<Mutex<DiscoveryState>>,
|
||||
running: Arc<AtomicBool>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl DlnaDiscovery {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: Arc::new(Mutex::new(DiscoveryState::default())),
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
handle: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start SSDP discovery in background
|
||||
pub async fn start_discovery(&mut self) -> Result<(), DlnaError> {
|
||||
if self.running.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let running = self.running.clone();
|
||||
let state = self.state.clone();
|
||||
running.store(true, Ordering::SeqCst);
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
while running.load(Ordering::SeqCst) {
|
||||
let target = SearchTarget::URN(media_renderer_urn());
|
||||
let discover = rupnp::discover(&target, Duration::from_secs(DISCOVERY_WINDOW_SECS), None).await;
|
||||
|
||||
if let Ok(stream) = discover {
|
||||
let mut stream = std::pin::pin!(stream);
|
||||
while let Ok(Some(device)) = stream.try_next().await {
|
||||
let id = device.udn().to_string();
|
||||
let name = device.friendly_name().to_string();
|
||||
let manufacturer = device.manufacturer().to_string();
|
||||
let model = device.model_name().to_string();
|
||||
let url = device.url().to_string();
|
||||
let ip = device
|
||||
.url()
|
||||
.host()
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
let mut has_av_transport = false;
|
||||
let mut has_rendering_control = false;
|
||||
|
||||
for service in device.services_iter() {
|
||||
let service_type = service.service_type().to_string();
|
||||
if service_type == av_transport_urn().to_string() {
|
||||
has_av_transport = true;
|
||||
}
|
||||
if service_type == rendering_control_urn().to_string() {
|
||||
has_rendering_control = true;
|
||||
}
|
||||
}
|
||||
|
||||
let discovered = DiscoveredDlnaDevice {
|
||||
id: id.clone(),
|
||||
name,
|
||||
manufacturer,
|
||||
model,
|
||||
ip,
|
||||
url,
|
||||
has_av_transport,
|
||||
has_rendering_control,
|
||||
};
|
||||
|
||||
if let Ok(mut state) = state.lock() {
|
||||
state.devices.insert(id, discovered);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_secs(DISCOVERY_SLEEP_SECS)).await;
|
||||
}
|
||||
});
|
||||
|
||||
self.handle = Some(handle);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop discovery and release resources
|
||||
pub fn stop_discovery(&mut self) -> Result<(), DlnaError> {
|
||||
self.running.store(false, Ordering::SeqCst);
|
||||
if let Some(handle) = self.handle.take() {
|
||||
handle.abort();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return list of discovered devices
|
||||
pub fn get_discovered_devices(&self) -> Vec<DiscoveredDlnaDevice> {
|
||||
self.state
|
||||
.lock()
|
||||
.map(|state| state.devices.values().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get a specific device by ID
|
||||
pub fn get_device(&self, device_id: &str) -> Option<DiscoveredDlnaDevice> {
|
||||
self.state
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|state| state.devices.get(device_id).cloned())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DlnaDiscovery {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn media_renderer_urn() -> URN {
|
||||
URN::Device("schemas-upnp-org".into(), "MediaRenderer".into(), 1)
|
||||
}
|
||||
|
||||
fn av_transport_urn() -> URN {
|
||||
URN::Service("schemas-upnp-org".into(), "AVTransport".into(), 1)
|
||||
}
|
||||
|
||||
fn rendering_control_urn() -> URN {
|
||||
URN::Service("schemas-upnp-org".into(), "RenderingControl".into(), 1)
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
//! DLNA/UPnP casting errors
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum DlnaError {
|
||||
#[error("Discovery error: {0}")]
|
||||
Discovery(String),
|
||||
|
||||
#[error("Connection error: {0}")]
|
||||
Connection(String),
|
||||
|
||||
#[error("Playback error: {0}")]
|
||||
Playback(String),
|
||||
|
||||
#[error("Not connected to a DLNA device")]
|
||||
NotConnected,
|
||||
|
||||
#[error("Device not found: {0}")]
|
||||
DeviceNotFound(String),
|
||||
|
||||
#[error("Not implemented: {0}")]
|
||||
NotImplemented(String),
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
//! DLNA/UPnP casting module (discovery + scaffolding)
|
||||
//! DLNA/UPnP casting module
|
||||
//!
|
||||
//! Core functionality is in qbz-cast crate, this module provides Tauri commands.
|
||||
|
||||
pub mod commands;
|
||||
pub mod device;
|
||||
pub mod discovery;
|
||||
pub mod errors;
|
||||
|
||||
// Re-export from qbz-cast
|
||||
pub use qbz_cast::{
|
||||
DlnaConnection, DlnaMetadata, DlnaPositionInfo, DlnaStatus, DlnaDiscovery,
|
||||
DiscoveredDlnaDevice, DlnaError,
|
||||
};
|
||||
|
||||
// Re-export Tauri command state
|
||||
pub use commands::DlnaState;
|
||||
pub use device::{DlnaConnection, DlnaMetadata, DlnaPositionInfo, DlnaStatus};
|
||||
pub use discovery::{DiscoveredDlnaDevice, DlnaDiscovery};
|
||||
pub use errors::DlnaError;
|
||||
@@ -1,30 +1,5 @@
|
||||
//! Chromecast casting errors
|
||||
//!
|
||||
//! Re-exported from qbz-cast crate.
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum CastError {
|
||||
#[error("Discovery error: {0}")]
|
||||
Discovery(String),
|
||||
|
||||
#[error("Connection error: {0}")]
|
||||
Connection(String),
|
||||
|
||||
#[error("Media error: {0}")]
|
||||
Media(String),
|
||||
|
||||
#[error("Server error: {0}")]
|
||||
Server(String),
|
||||
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
#[error("Not connected to a cast device")]
|
||||
NotConnected,
|
||||
|
||||
#[error("Device not found: {0}")]
|
||||
DeviceNotFound(String),
|
||||
|
||||
#[error("Invalid request: {0}")]
|
||||
InvalidRequest(String),
|
||||
}
|
||||
pub use qbz_cast::{CastError, AirPlayError, DlnaError};
|
||||
@@ -1,354 +1,5 @@
|
||||
//! Local HTTP server for Chromecast media streaming
|
||||
//! Local HTTP server for casting media streaming
|
||||
//!
|
||||
//! Re-exported from qbz-cast crate.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::Duration;
|
||||
|
||||
use tiny_http::{Header, Method, Response, Server, StatusCode};
|
||||
|
||||
use crate::cast::CastError;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MediaEntry {
|
||||
content_type: String,
|
||||
size: u64,
|
||||
source: MediaSource,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum MediaSource {
|
||||
Data(Vec<u8>),
|
||||
File(PathBuf),
|
||||
}
|
||||
|
||||
/// Simple HTTP server for audio streaming
|
||||
pub struct MediaServer {
|
||||
port: u16,
|
||||
base_url: String,
|
||||
entries: Arc<Mutex<HashMap<u64, MediaEntry>>>,
|
||||
shutdown: Arc<AtomicBool>,
|
||||
handle: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl MediaServer {
|
||||
/// Start server on available port
|
||||
/// Uses port 9876 by default for DLNA compatibility, falls back to random port if busy
|
||||
pub fn start() -> Result<Self, CastError> {
|
||||
// Try fixed port first for easier firewall configuration
|
||||
let server = Server::http("0.0.0.0:9876")
|
||||
.or_else(|_| {
|
||||
log::warn!("MediaServer: Port 9876 busy, using random port");
|
||||
Server::http("0.0.0.0:0")
|
||||
})
|
||||
.map_err(|e| CastError::Server(format!("Failed to start HTTP server: {}", e)))?;
|
||||
|
||||
let port = server
|
||||
.server_addr()
|
||||
.to_ip()
|
||||
.map(|addr| addr.port())
|
||||
.ok_or_else(|| CastError::Server("Failed to determine HTTP port".to_string()))?;
|
||||
|
||||
let base_ip = local_ip().unwrap_or_else(|| IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
|
||||
let base_url = format_base_url(base_ip, port);
|
||||
|
||||
log::info!("MediaServer: Started on {}:{} (base_url: {})", base_ip, port, base_url);
|
||||
|
||||
let entries = Arc::new(Mutex::new(HashMap::new()));
|
||||
let shutdown = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let entries_clone = entries.clone();
|
||||
let shutdown_clone = shutdown.clone();
|
||||
let port_for_log = port;
|
||||
|
||||
let handle = thread::spawn(move || {
|
||||
log::info!("MediaServer: Thread started, listening on port {}", port_for_log);
|
||||
while !shutdown_clone.load(Ordering::SeqCst) {
|
||||
match server.recv_timeout(Duration::from_millis(250)) {
|
||||
Ok(Some(request)) => {
|
||||
let response = handle_request(request.method(), request.url(), &request, &entries_clone);
|
||||
let _ = request.respond(response);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
log::error!("MediaServer: Thread error: {:?}, exiting", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
log::info!("MediaServer: Thread exiting");
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
port,
|
||||
base_url,
|
||||
entries,
|
||||
shutdown,
|
||||
handle: Some(handle),
|
||||
})
|
||||
}
|
||||
|
||||
/// Stop server
|
||||
pub fn stop(&mut self) {
|
||||
self.shutdown.store(true, Ordering::SeqCst);
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
|
||||
/// Get base URL (e.g., "http://192.168.1.100:8080")
|
||||
pub fn base_url(&self) -> String {
|
||||
self.base_url.clone()
|
||||
}
|
||||
|
||||
/// Register audio data to serve (returns path like "/audio/123")
|
||||
pub fn register_audio(&mut self, id: u64, data: Vec<u8>, content_type: &str) -> String {
|
||||
let entry = MediaEntry {
|
||||
content_type: content_type.to_string(),
|
||||
size: data.len() as u64,
|
||||
source: MediaSource::Data(data),
|
||||
};
|
||||
|
||||
if let Ok(mut entries) = self.entries.lock() {
|
||||
entries.insert(id, entry);
|
||||
}
|
||||
|
||||
format!("/audio/{}", id)
|
||||
}
|
||||
|
||||
/// Register local file to serve
|
||||
pub fn register_file(&mut self, id: u64, file_path: &str) -> Result<String, CastError> {
|
||||
let path = Path::new(file_path);
|
||||
if !path.exists() {
|
||||
return Err(CastError::InvalidRequest(format!(
|
||||
"File not found: {}",
|
||||
file_path
|
||||
)));
|
||||
}
|
||||
|
||||
let size = path
|
||||
.metadata()
|
||||
.map_err(CastError::Io)?
|
||||
.len();
|
||||
let content_type = content_type_for_path(path);
|
||||
|
||||
let entry = MediaEntry {
|
||||
content_type,
|
||||
size,
|
||||
source: MediaSource::File(path.to_path_buf()),
|
||||
};
|
||||
|
||||
if let Ok(mut entries) = self.entries.lock() {
|
||||
entries.insert(id, entry);
|
||||
}
|
||||
|
||||
Ok(format!("/audio/{}", id))
|
||||
}
|
||||
|
||||
/// Get full URL for registered audio
|
||||
pub fn get_audio_url(&self, id: u64) -> Option<String> {
|
||||
let entries = self.entries.lock().ok()?;
|
||||
if entries.contains_key(&id) {
|
||||
return Some(format!("{}/audio/{}", self.base_url, id));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Get full URL for registered audio using the local IP that can reach target_ip.
|
||||
pub fn get_audio_url_for_target(&self, id: u64, target_ip: &str) -> Option<String> {
|
||||
let entries = self.entries.lock().ok()?;
|
||||
if !entries.contains_key(&id) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let base_url = local_ip_for_target(target_ip)
|
||||
.map(|ip| format_base_url(ip, self.port))
|
||||
.unwrap_or_else(|| self.base_url.clone());
|
||||
|
||||
Some(format!("{}/audio/{}", base_url, id))
|
||||
}
|
||||
|
||||
/// Get server port
|
||||
pub fn port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MediaServer {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_request(
|
||||
method: &Method,
|
||||
url: &str,
|
||||
request: &tiny_http::Request,
|
||||
entries: &Arc<Mutex<HashMap<u64, MediaEntry>>>,
|
||||
) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
// Log all incoming requests for debugging
|
||||
log::info!("MediaServer: {} request from {:?} for {}", method, request.remote_addr(), url);
|
||||
|
||||
if method != &Method::Get {
|
||||
log::warn!("MediaServer: Rejected non-GET request: {}", method);
|
||||
return Response::from_data(Vec::new()).with_status_code(StatusCode(405));
|
||||
}
|
||||
|
||||
let id = match parse_audio_id(url) {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
log::warn!("MediaServer: 404 - Could not parse audio ID from URL: {}", url);
|
||||
return Response::from_data(Vec::new()).with_status_code(StatusCode(404));
|
||||
}
|
||||
};
|
||||
|
||||
let entry = match entries.lock().ok().and_then(|map| map.get(&id).cloned()) {
|
||||
Some(entry) => {
|
||||
log::info!("MediaServer: Found entry for ID {}, content-type: {}, size: {} bytes", id, entry.content_type, entry.size);
|
||||
entry
|
||||
}
|
||||
None => {
|
||||
log::warn!("MediaServer: 404 - No entry found for ID: {}", id);
|
||||
return Response::from_data(Vec::new()).with_status_code(StatusCode(404));
|
||||
}
|
||||
};
|
||||
|
||||
let range_header = request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|h| h.field.equiv("Range"))
|
||||
.map(|h| h.value.as_str());
|
||||
|
||||
let range = range_header.and_then(|header| parse_range(header, entry.size));
|
||||
|
||||
let (data, status_code, content_range) = match read_range(&entry, range) {
|
||||
Ok(result) => result,
|
||||
Err(_) => return Response::from_data(Vec::new()).with_status_code(StatusCode(500)),
|
||||
};
|
||||
|
||||
let mut response = Response::from_data(data)
|
||||
.with_status_code(status_code)
|
||||
.with_header(header("Content-Type", &entry.content_type))
|
||||
.with_header(header("Accept-Ranges", "bytes"));
|
||||
|
||||
if let Some(content_range) = content_range {
|
||||
response = response.with_header(header("Content-Range", &content_range));
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
fn read_range(
|
||||
entry: &MediaEntry,
|
||||
range: Option<(u64, u64)>,
|
||||
) -> Result<(Vec<u8>, StatusCode, Option<String>), std::io::Error> {
|
||||
let (start, end, status_code, content_range) = if let Some((start, end)) = range {
|
||||
let content_range = format!("bytes {}-{}/{}", start, end, entry.size);
|
||||
(start, end, StatusCode(206), Some(content_range))
|
||||
} else {
|
||||
(0, entry.size.saturating_sub(1), StatusCode(200), None)
|
||||
};
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
|
||||
match &entry.source {
|
||||
MediaSource::Data(data) => {
|
||||
let end = end.min(entry.size.saturating_sub(1)) as usize;
|
||||
let start = start.min(end as u64) as usize;
|
||||
buffer.extend_from_slice(&data[start..=end]);
|
||||
}
|
||||
MediaSource::File(path) => {
|
||||
let mut file = File::open(path)?;
|
||||
file.seek(SeekFrom::Start(start))?;
|
||||
let length = (end - start + 1) as usize;
|
||||
buffer.resize(length, 0);
|
||||
file.read_exact(&mut buffer)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok((buffer, status_code, content_range))
|
||||
}
|
||||
|
||||
fn parse_audio_id(url: &str) -> Option<u64> {
|
||||
let path = url.split('?').next().unwrap_or(url);
|
||||
let parts: Vec<&str> = path.trim_matches('/').split('/').collect();
|
||||
if parts.len() != 2 || parts[0] != "audio" {
|
||||
return None;
|
||||
}
|
||||
parts[1].parse().ok()
|
||||
}
|
||||
|
||||
fn parse_range(header: &str, total: u64) -> Option<(u64, u64)> {
|
||||
if !header.starts_with("bytes=") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let range = header.trim_start_matches("bytes=");
|
||||
let mut parts = range.split('-');
|
||||
let start_str = parts.next().unwrap_or("");
|
||||
let end_str = parts.next().unwrap_or("");
|
||||
|
||||
if start_str.is_empty() {
|
||||
let suffix = end_str.parse::<u64>().ok()?;
|
||||
if suffix == 0 {
|
||||
return None;
|
||||
}
|
||||
let start = total.saturating_sub(suffix);
|
||||
let end = total.saturating_sub(1);
|
||||
return Some((start, end));
|
||||
}
|
||||
|
||||
let start = start_str.parse::<u64>().ok()?;
|
||||
if start >= total {
|
||||
return None;
|
||||
}
|
||||
|
||||
let end = if end_str.is_empty() {
|
||||
total.saturating_sub(1)
|
||||
} else {
|
||||
end_str.parse::<u64>().ok()?.min(total.saturating_sub(1))
|
||||
};
|
||||
|
||||
Some((start, end))
|
||||
}
|
||||
|
||||
fn header(name: &str, value: &str) -> Header {
|
||||
Header::from_bytes(name, value).unwrap()
|
||||
}
|
||||
|
||||
fn local_ip() -> Option<IpAddr> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
socket.connect("8.8.8.8:80").ok()?;
|
||||
socket.local_addr().ok().map(|addr| addr.ip())
|
||||
}
|
||||
|
||||
fn local_ip_for_target(target_ip: &str) -> Option<IpAddr> {
|
||||
let ip: IpAddr = target_ip.parse().ok()?;
|
||||
let bind_addr = if ip.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" };
|
||||
let socket = UdpSocket::bind(bind_addr).ok()?;
|
||||
socket.connect(SocketAddr::new(ip, 80)).ok()?;
|
||||
socket.local_addr().ok().map(|addr| addr.ip())
|
||||
}
|
||||
|
||||
fn format_base_url(ip: IpAddr, port: u16) -> String {
|
||||
match ip {
|
||||
IpAddr::V4(addr) => format!("http://{}:{}", addr, port),
|
||||
IpAddr::V6(addr) => format!("http://[{}]:{}", addr, port),
|
||||
}
|
||||
}
|
||||
|
||||
fn content_type_for_path(path: &Path) -> String {
|
||||
match path.extension().and_then(|e| e.to_str()).map(|s| s.to_lowercase()) {
|
||||
Some(ext) if ext == "flac" => "audio/flac".to_string(),
|
||||
Some(ext) if ext == "wav" => "audio/wav".to_string(),
|
||||
Some(ext) if ext == "m4a" => "audio/mp4".to_string(),
|
||||
Some(ext) if ext == "aiff" || ext == "aif" => "audio/aiff".to_string(),
|
||||
Some(ext) if ext == "ape" => "audio/ape".to_string(),
|
||||
_ => "application/octet-stream".to_string(),
|
||||
}
|
||||
}
|
||||
pub use qbz_cast::MediaServer;
|
||||
+13
-21
@@ -1,4 +1,7 @@
|
||||
//! Casting module (Chromecast-first, designed for future AirPlay/DLNA expansion).
|
||||
//!
|
||||
//! This module provides Tauri commands for casting functionality.
|
||||
//! The core casting logic is in the qbz-cast crate.
|
||||
|
||||
pub mod chromecast_thread;
|
||||
pub mod commands;
|
||||
@@ -9,28 +12,17 @@ pub mod media_server;
|
||||
pub mod airplay;
|
||||
pub mod dlna;
|
||||
|
||||
pub use commands::CastState;
|
||||
pub use device::{CastDeviceConnection, CastStatus, MediaMetadata, CastPositionInfo};
|
||||
pub use discovery::{DeviceDiscovery, DiscoveredDevice};
|
||||
pub use errors::CastError;
|
||||
pub use media_server::MediaServer;
|
||||
pub use airplay::{
|
||||
AirPlayConnection,
|
||||
AirPlayDiscovery,
|
||||
AirPlayError,
|
||||
AirPlayMetadata,
|
||||
AirPlayState,
|
||||
AirPlayStatus,
|
||||
// Re-export from qbz-cast for internal use
|
||||
pub use qbz_cast::{
|
||||
CastError, CastDevice, CastDeviceConnection, CastStatus, MediaMetadata, CastPositionInfo,
|
||||
DeviceDiscovery, DiscoveredDevice, MediaServer, ChromecastHandle, CastCommand,
|
||||
AirPlayConnection, AirPlayDiscovery, AirPlayError, AirPlayMetadata, AirPlayStatus,
|
||||
DiscoveredAirPlayDevice,
|
||||
};
|
||||
pub use dlna::{
|
||||
DlnaConnection, DlnaDiscovery, DlnaError, DlnaMetadata, DlnaStatus, DlnaPositionInfo,
|
||||
DiscoveredDlnaDevice,
|
||||
DlnaConnection,
|
||||
DlnaDiscovery,
|
||||
DlnaError,
|
||||
DlnaMetadata,
|
||||
DlnaState,
|
||||
DlnaStatus,
|
||||
};
|
||||
|
||||
pub type CastDevice = CastDeviceConnection;
|
||||
// Re-export Tauri command states
|
||||
pub use commands::CastState;
|
||||
pub use airplay::commands::AirPlayState;
|
||||
pub use dlna::commands::DlnaState;
|
||||
Reference in new issue
Block a user