feat: add casting module scaffolding (disabled)
Import Chromecast, AirPlay, and DLNA casting scaffolding from separate branches. The module is currently disabled due to: - Thread safety issues: rust_cast uses Rc internally (not Send) - API compatibility: rupnp methods have changed The scaffolding includes: - Chromecast: mDNS discovery, device connection, media server - AirPlay: Discovery scaffolding (RAOP playback pending) - DLNA/UPnP: SSDP discovery scaffolding (playback pending) To enable casting in the future: 1. Fix rust_cast thread safety (or use spawn_blocking) 2. Update rupnp API calls for current version 3. Add Deserialize derive to metadata types 4. Uncomment cast module in lib.rs 5. Wire up commands in invoke_handler
This commit is contained in:
1 parent
e908d334c1
commit
145186a06a
19 files changed
+1966
No files matched your search
@@ -0,0 +1,124 @@
|
||||
//! Tauri commands for AirPlay casting (discovery + connection scaffolding)
|
||||
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::cast::airplay::{
|
||||
AirPlayConnection, AirPlayDiscovery, AirPlayError, AirPlayMetadata, AirPlayStatus,
|
||||
DiscoveredAirPlayDevice,
|
||||
};
|
||||
|
||||
/// AirPlay state shared across commands
|
||||
pub struct AirPlayState {
|
||||
pub discovery: Arc<Mutex<AirPlayDiscovery>>,
|
||||
pub connection: Arc<Mutex<Option<AirPlayConnection>>>,
|
||||
}
|
||||
|
||||
impl AirPlayState {
|
||||
pub fn new() -> Result<Self, AirPlayError> {
|
||||
Ok(Self {
|
||||
discovery: Arc::new(Mutex::new(AirPlayDiscovery::new())),
|
||||
connection: Arc::new(Mutex::new(None)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// === Discovery ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_start_discovery(state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let mut discovery = state.discovery.lock().await;
|
||||
discovery
|
||||
.start_discovery()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_stop_discovery(state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let mut discovery = state.discovery.lock().await;
|
||||
discovery.stop_discovery().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_get_devices(
|
||||
state: State<'_, AirPlayState>,
|
||||
) -> Result<Vec<DiscoveredAirPlayDevice>, String> {
|
||||
let discovery = state.discovery.lock().await;
|
||||
Ok(discovery.get_discovered_devices())
|
||||
}
|
||||
|
||||
// === Connection ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_connect(device_id: String, state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let device = {
|
||||
let discovery = state.discovery.lock().await;
|
||||
discovery
|
||||
.get_device(&device_id)
|
||||
.ok_or_else(|| AirPlayError::DeviceNotFound(device_id.clone()))
|
||||
.map_err(|e| e.to_string())?
|
||||
};
|
||||
|
||||
let connection = AirPlayConnection::connect(device).map_err(|e| e.to_string())?;
|
||||
let mut state_connection = state.connection.lock().await;
|
||||
*state_connection = Some(connection);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_disconnect(state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
if let Some(conn) = connection.as_mut() {
|
||||
conn.disconnect().map_err(|e| e.to_string())?;
|
||||
}
|
||||
*connection = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_get_status(state: State<'_, AirPlayState>) -> Result<AirPlayStatus, String> {
|
||||
let connection = state.connection.lock().await;
|
||||
let conn = connection.as_ref().ok_or_else(|| "Not connected".to_string())?;
|
||||
Ok(conn.get_status())
|
||||
}
|
||||
|
||||
// === Playback (stubs) ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_load_media(
|
||||
metadata: AirPlayMetadata,
|
||||
state: State<'_, AirPlayState>,
|
||||
) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.load_media(metadata).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_play(state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.play().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_pause(state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.pause().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_stop(state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.stop().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn airplay_set_volume(volume: f32, state: State<'_, AirPlayState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.set_volume(volume).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! AirPlay device connection and streaming (placeholder)
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::cast::airplay::{AirPlayError, DiscoveredAirPlayDevice};
|
||||
|
||||
/// Metadata for AirPlay playback
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
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(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
//! 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())
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! 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),
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! AirPlay casting module (discovery + scaffolding)
|
||||
|
||||
pub mod commands;
|
||||
pub mod device;
|
||||
pub mod discovery;
|
||||
pub mod errors;
|
||||
|
||||
pub use commands::AirPlayState;
|
||||
pub use device::{AirPlayConnection, AirPlayMetadata, AirPlayStatus};
|
||||
pub use discovery::{AirPlayDiscovery, DiscoveredAirPlayDevice};
|
||||
pub use errors::AirPlayError;
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Tauri commands for Chromecast casting
|
||||
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::api::models::Quality;
|
||||
use crate::AppState;
|
||||
use crate::cast::{
|
||||
CastDeviceConnection, CastError, CastStatus, DeviceDiscovery, DiscoveredDevice, MediaMetadata,
|
||||
MediaServer,
|
||||
};
|
||||
use crate::library::{AudioFormat, LibraryState};
|
||||
|
||||
/// Cast state shared across commands
|
||||
pub struct CastState {
|
||||
pub discovery: Arc<Mutex<DeviceDiscovery>>,
|
||||
pub connection: Arc<Mutex<Option<CastDeviceConnection>>>,
|
||||
pub media_server: Arc<Mutex<MediaServer>>,
|
||||
}
|
||||
|
||||
impl CastState {
|
||||
pub fn new() -> Result<Self, CastError> {
|
||||
Ok(Self {
|
||||
discovery: Arc::new(Mutex::new(DeviceDiscovery::new())),
|
||||
connection: Arc::new(Mutex::new(None)),
|
||||
media_server: Arc::new(Mutex::new(MediaServer::start()?)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// === Discovery ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_start_discovery(state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut discovery = state.discovery.lock().await;
|
||||
discovery
|
||||
.start_discovery()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_stop_discovery(state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut discovery = state.discovery.lock().await;
|
||||
discovery.stop_discovery().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_get_devices(
|
||||
state: State<'_, CastState>,
|
||||
) -> Result<Vec<DiscoveredDevice>, String> {
|
||||
let discovery = state.discovery.lock().await;
|
||||
Ok(discovery.get_discovered_devices())
|
||||
}
|
||||
|
||||
// === Connection ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_connect(device_id: String, state: State<'_, CastState>) -> Result<(), String> {
|
||||
let device = {
|
||||
let discovery = state.discovery.lock().await;
|
||||
discovery
|
||||
.get_device(&device_id)
|
||||
.ok_or_else(|| CastError::DeviceNotFound(device_id.clone()))
|
||||
.map_err(|e| e.to_string())?
|
||||
};
|
||||
|
||||
let connection = CastDeviceConnection::connect(&device.ip, device.port)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut state_connection = state.connection.lock().await;
|
||||
*state_connection = Some(connection);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_disconnect(state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
if let Some(conn) = connection.as_mut() {
|
||||
conn.disconnect().map_err(|e| e.to_string())?;
|
||||
}
|
||||
*connection = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_get_status(state: State<'_, CastState>) -> Result<CastStatus, String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.get_status().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// === Playback ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_play_track(
|
||||
track_id: u64,
|
||||
metadata: MediaMetadata,
|
||||
state: State<'_, CastState>,
|
||||
app_state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
let stream_url = {
|
||||
let client = app_state.client.lock().await;
|
||||
client
|
||||
.get_stream_url_with_fallback(track_id, Quality::HiRes)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to get stream URL: {}", e))?
|
||||
};
|
||||
|
||||
let content_type = stream_url.mime_type.clone();
|
||||
let cache = app_state.audio_cache.clone();
|
||||
|
||||
let audio_data = if let Some(cached) = cache.get(track_id) {
|
||||
cached.data
|
||||
} else {
|
||||
let data = download_audio(&stream_url.url).await?;
|
||||
cache.insert(track_id, data.clone());
|
||||
data
|
||||
};
|
||||
|
||||
let url = {
|
||||
let mut server = state.media_server.lock().await;
|
||||
server.register_audio(track_id, audio_data, &content_type);
|
||||
server
|
||||
.get_audio_url(track_id)
|
||||
.ok_or_else(|| "Failed to build media URL".to_string())?
|
||||
};
|
||||
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.load_media(&url, &content_type, metadata)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_play_local_track(
|
||||
track_id: i64,
|
||||
state: State<'_, CastState>,
|
||||
library_state: State<'_, LibraryState>,
|
||||
) -> Result<(), String> {
|
||||
let track = {
|
||||
let db = library_state.db.lock().await;
|
||||
db.get_track(track_id)
|
||||
.map_err(|e| e.to_string())?
|
||||
.ok_or_else(|| "Track not found".to_string())?
|
||||
};
|
||||
|
||||
let url = {
|
||||
let mut server = state.media_server.lock().await;
|
||||
server
|
||||
.register_file(track_id as u64, &track.file_path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
server
|
||||
.get_audio_url(track_id as u64)
|
||||
.ok_or_else(|| "Failed to build media URL".to_string())?
|
||||
};
|
||||
|
||||
let metadata = MediaMetadata {
|
||||
title: track.title,
|
||||
artist: track.artist,
|
||||
album: track.album,
|
||||
artwork_url: None,
|
||||
duration_secs: Some(track.duration_secs),
|
||||
};
|
||||
|
||||
let content_type = content_type_from_format(&track.format);
|
||||
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.load_media(&url, content_type, metadata)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_play(state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.play().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_pause(state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.pause().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_stop(state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.stop().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_seek(position_secs: f64, state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.seek(position_secs).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn cast_set_volume(volume: f32, state: State<'_, CastState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.set_volume(volume).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
async fn download_audio(url: &str) -> Result<Vec<u8>, String> {
|
||||
use std::time::Duration;
|
||||
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_secs(120))
|
||||
.connect_timeout(Duration::from_secs(10))
|
||||
.build()
|
||||
.map_err(|e| format!("Failed to create HTTP client: {}", e))?;
|
||||
|
||||
let response = client
|
||||
.get(url)
|
||||
.header("User-Agent", "Mozilla/5.0")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch audio: {}", e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("HTTP error: {}", response.status()));
|
||||
}
|
||||
|
||||
let bytes = response
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to read audio bytes: {}", e))?;
|
||||
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
|
||||
fn content_type_from_format(format: &AudioFormat) -> &'static str {
|
||||
match format {
|
||||
AudioFormat::Flac => "audio/flac",
|
||||
AudioFormat::Alac => "audio/mp4",
|
||||
AudioFormat::Wav => "audio/wav",
|
||||
AudioFormat::Aiff => "audio/aiff",
|
||||
AudioFormat::Ape => "audio/ape",
|
||||
AudioFormat::Unknown => "application/octet-stream",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! Chromecast device connection and media control
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use rust_cast::CastDevice;
|
||||
use rust_cast::channels::media::{Image, Media, Metadata, MusicTrackMediaMetadata, StreamType};
|
||||
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)]
|
||||
pub struct MediaMetadata {
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
pub album: String,
|
||||
pub artwork_url: Option<String>,
|
||||
pub duration_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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(())
|
||||
}
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Chromecast 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::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())
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Tauri commands for DLNA/UPnP casting (discovery + scaffolding)
|
||||
|
||||
use std::sync::Arc;
|
||||
use tauri::State;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::cast::dlna::{
|
||||
DiscoveredDlnaDevice, DlnaConnection, DlnaDiscovery, DlnaError, DlnaMetadata, DlnaStatus,
|
||||
};
|
||||
|
||||
/// DLNA state shared across commands
|
||||
pub struct DlnaState {
|
||||
pub discovery: Arc<Mutex<DlnaDiscovery>>,
|
||||
pub connection: Arc<Mutex<Option<DlnaConnection>>>,
|
||||
}
|
||||
|
||||
impl DlnaState {
|
||||
pub fn new() -> Result<Self, DlnaError> {
|
||||
Ok(Self {
|
||||
discovery: Arc::new(Mutex::new(DlnaDiscovery::new())),
|
||||
connection: Arc::new(Mutex::new(None)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// === Discovery ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_start_discovery(state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let mut discovery = state.discovery.lock().await;
|
||||
discovery
|
||||
.start_discovery()
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_stop_discovery(state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let mut discovery = state.discovery.lock().await;
|
||||
discovery.stop_discovery().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_get_devices(
|
||||
state: State<'_, DlnaState>,
|
||||
) -> Result<Vec<DiscoveredDlnaDevice>, String> {
|
||||
let discovery = state.discovery.lock().await;
|
||||
Ok(discovery.get_discovered_devices())
|
||||
}
|
||||
|
||||
// === Connection ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_connect(device_id: String, state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let device = {
|
||||
let discovery = state.discovery.lock().await;
|
||||
discovery
|
||||
.get_device(&device_id)
|
||||
.ok_or_else(|| DlnaError::DeviceNotFound(device_id.clone()))
|
||||
.map_err(|e| e.to_string())?
|
||||
};
|
||||
|
||||
let connection = DlnaConnection::connect(device).map_err(|e| e.to_string())?;
|
||||
let mut state_connection = state.connection.lock().await;
|
||||
*state_connection = Some(connection);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_disconnect(state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
if let Some(conn) = connection.as_mut() {
|
||||
conn.disconnect().map_err(|e| e.to_string())?;
|
||||
}
|
||||
*connection = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_get_status(state: State<'_, DlnaState>) -> Result<DlnaStatus, String> {
|
||||
let connection = state.connection.lock().await;
|
||||
let conn = connection.as_ref().ok_or_else(|| "Not connected".to_string())?;
|
||||
Ok(conn.get_status())
|
||||
}
|
||||
|
||||
// === Playback (stubs) ===
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_load_media(
|
||||
metadata: DlnaMetadata,
|
||||
state: State<'_, DlnaState>,
|
||||
) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.load_media(metadata).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_play(state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.play().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_pause(state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.pause().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_stop(state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.stop().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn dlna_set_volume(volume: f32, state: State<'_, DlnaState>) -> Result<(), String> {
|
||||
let mut connection = state.connection.lock().await;
|
||||
let conn = connection.as_mut().ok_or_else(|| "Not connected".to_string())?;
|
||||
conn.set_volume(volume).map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//! DLNA device connection and playback (placeholder)
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::cast::dlna::{DiscoveredDlnaDevice, DlnaError};
|
||||
|
||||
/// Metadata for DLNA playback
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DlnaMetadata {
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
pub album: String,
|
||||
pub artwork_url: Option<String>,
|
||||
pub duration_secs: Option<u64>,
|
||||
}
|
||||
|
||||
/// DLNA device status (minimal for now)
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DlnaStatus {
|
||||
pub device_id: String,
|
||||
pub device_name: String,
|
||||
pub is_connected: bool,
|
||||
}
|
||||
|
||||
/// DLNA connection stub (AVTransport integration pending)
|
||||
pub struct DlnaConnection {
|
||||
device: DiscoveredDlnaDevice,
|
||||
connected: bool,
|
||||
}
|
||||
|
||||
impl DlnaConnection {
|
||||
/// Connect to a DLNA device
|
||||
pub fn connect(device: DiscoveredDlnaDevice) -> Result<Self, DlnaError> {
|
||||
Ok(Self {
|
||||
device,
|
||||
connected: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// Disconnect from the device
|
||||
pub fn disconnect(&mut self) -> Result<(), DlnaError> {
|
||||
self.connected = false;
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Load media (requires AVTransport integration)
|
||||
pub fn load_media(&mut self, _metadata: DlnaMetadata) -> Result<(), DlnaError> {
|
||||
Err(DlnaError::NotImplemented(
|
||||
"AVTransport integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Play/pause/stop controls
|
||||
pub fn play(&mut self) -> Result<(), DlnaError> {
|
||||
Err(DlnaError::NotImplemented(
|
||||
"AVTransport integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn pause(&mut self) -> Result<(), DlnaError> {
|
||||
Err(DlnaError::NotImplemented(
|
||||
"AVTransport integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) -> Result<(), DlnaError> {
|
||||
Err(DlnaError::NotImplemented(
|
||||
"AVTransport integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Volume control (0.0 - 1.0)
|
||||
pub fn set_volume(&mut self, _volume: f32) -> Result<(), DlnaError> {
|
||||
Err(DlnaError::NotImplemented(
|
||||
"RenderingControl integration not implemented".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! 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)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! 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),
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! DLNA/UPnP casting module (discovery + scaffolding)
|
||||
|
||||
pub mod commands;
|
||||
pub mod device;
|
||||
pub mod discovery;
|
||||
pub mod errors;
|
||||
|
||||
pub use commands::DlnaState;
|
||||
pub use device::{DlnaConnection, DlnaMetadata, DlnaStatus};
|
||||
pub use discovery::{DiscoveredDlnaDevice, DlnaDiscovery};
|
||||
pub use errors::DlnaError;
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Chromecast casting errors
|
||||
|
||||
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),
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
//! Local HTTP server for Chromecast media streaming
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::net::{IpAddr, 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
|
||||
pub fn start() -> Result<Self, CastError> {
|
||||
let server = 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(|| "127.0.0.1".to_string());
|
||||
let base_url = format!("http://{}:{}", base_ip, port);
|
||||
|
||||
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 handle = thread::spawn(move || {
|
||||
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(_) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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 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<impl Read> {
|
||||
if method != &Method::Get {
|
||||
return Response::new_empty(StatusCode(405));
|
||||
}
|
||||
|
||||
let id = match parse_audio_id(url) {
|
||||
Some(id) => id,
|
||||
None => return Response::new_empty(StatusCode(404)),
|
||||
};
|
||||
|
||||
let entry = match entries.lock().ok().and_then(|map| map.get(&id).cloned()) {
|
||||
Some(entry) => entry,
|
||||
None => return Response::new_empty(StatusCode(404)),
|
||||
};
|
||||
|
||||
let range_header = request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|h| h.field.equiv("Range"))
|
||||
.and_then(|h| Some(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::new_empty(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<String> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
socket.connect("8.8.8.8:80").ok()?;
|
||||
match socket.local_addr().ok()? {
|
||||
SocketAddr::V4(addr) => Some(addr.ip().to_string()),
|
||||
SocketAddr::V6(addr) => Some(addr.ip().to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Casting module (Chromecast-first, designed for future AirPlay/DLNA expansion).
|
||||
|
||||
pub mod commands;
|
||||
pub mod device;
|
||||
pub mod discovery;
|
||||
pub mod errors;
|
||||
pub mod media_server;
|
||||
pub mod airplay;
|
||||
pub mod dlna;
|
||||
|
||||
pub use commands::CastState;
|
||||
pub use device::{CastDeviceConnection, CastStatus, MediaMetadata};
|
||||
pub use discovery::{DeviceDiscovery, DiscoveredDevice};
|
||||
pub use errors::CastError;
|
||||
pub use media_server::MediaServer;
|
||||
pub use airplay::{
|
||||
AirPlayConnection,
|
||||
AirPlayDiscovery,
|
||||
AirPlayError,
|
||||
AirPlayMetadata,
|
||||
AirPlayState,
|
||||
AirPlayStatus,
|
||||
DiscoveredAirPlayDevice,
|
||||
};
|
||||
pub use dlna::{
|
||||
DiscoveredDlnaDevice,
|
||||
DlnaConnection,
|
||||
DlnaDiscovery,
|
||||
DlnaError,
|
||||
DlnaMetadata,
|
||||
DlnaState,
|
||||
DlnaStatus,
|
||||
};
|
||||
|
||||
pub type CastDevice = CastDeviceConnection;
|
||||
Reference in new issue
Block a user