Enable Chromecast casting with thread-safe architecture
- Add ChromecastHandle with dedicated thread for rust_cast operations - Fix thread safety issue (rust_cast uses Rc, not Arc) using channels - Enable rupnp full_device_spec feature for DLNA discovery - Fix media_server response type consistency - Register all cast commands in lib.rs - Add Deserialize to MediaMetadata for Tauri command args
This commit is contained in:
1 parent
2e0aaa4296
commit
8b10a47a03
7 files changed
+361
-68
No files matched your search
@@ -0,0 +1,304 @@
|
||||
//! 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.
|
||||
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::thread::{self, JoinHandle};
|
||||
|
||||
use crate::cast::device::CastDeviceConnection;
|
||||
use crate::cast::errors::CastError;
|
||||
use crate::cast::{CastStatus, MediaMetadata};
|
||||
|
||||
/// 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>>,
|
||||
},
|
||||
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()))?
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ChromecastHandle {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.sender.send(CastCommand::Shutdown);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
Ok(cmd) => cmd,
|
||||
Err(_) => 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::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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,15 +7,16 @@ use tokio::sync::Mutex;
|
||||
use crate::api::models::Quality;
|
||||
use crate::AppState;
|
||||
use crate::cast::{
|
||||
CastDeviceConnection, CastError, CastStatus, DeviceDiscovery, DiscoveredDevice, MediaMetadata,
|
||||
MediaServer,
|
||||
CastError, CastStatus, DeviceDiscovery, DiscoveredDevice, MediaMetadata, MediaServer,
|
||||
};
|
||||
use crate::cast::chromecast_thread::ChromecastHandle;
|
||||
use crate::library::{AudioFormat, LibraryState};
|
||||
|
||||
/// Cast state shared across commands
|
||||
/// Uses a dedicated thread for Chromecast operations since rust_cast is not thread-safe
|
||||
pub struct CastState {
|
||||
pub discovery: Arc<Mutex<DeviceDiscovery>>,
|
||||
pub connection: Arc<Mutex<Option<CastDeviceConnection>>>,
|
||||
pub chromecast: ChromecastHandle,
|
||||
pub media_server: Arc<Mutex<MediaServer>>,
|
||||
}
|
||||
|
||||
@@ -23,7 +24,7 @@ impl CastState {
|
||||
pub fn new() -> Result<Self, CastError> {
|
||||
Ok(Self {
|
||||
discovery: Arc::new(Mutex::new(DeviceDiscovery::new())),
|
||||
connection: Arc::new(Mutex::new(None)),
|
||||
chromecast: ChromecastHandle::new(),
|
||||
media_server: Arc::new(Mutex::new(MediaServer::start()?)),
|
||||
})
|
||||
}
|
||||
@@ -65,29 +66,20 @@ pub async fn cast_connect(device_id: String, state: State<'_, CastState>) -> Res
|
||||
.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(())
|
||||
state
|
||||
.chromecast
|
||||
.connect(device.ip.clone(), device.port)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[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(())
|
||||
state.chromecast.disconnect().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[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())
|
||||
state.chromecast.get_status().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// === Playback ===
|
||||
@@ -126,9 +118,9 @@ pub async fn cast_play_track(
|
||||
.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)
|
||||
state
|
||||
.chromecast
|
||||
.load_media(url, content_type, metadata)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
@@ -163,47 +155,37 @@ pub async fn cast_play_local_track(
|
||||
duration_secs: Some(track.duration_secs),
|
||||
};
|
||||
|
||||
let content_type = content_type_from_format(&track.format);
|
||||
let content_type = content_type_from_format(&track.format).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)
|
||||
state
|
||||
.chromecast
|
||||
.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())
|
||||
state.chromecast.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())
|
||||
state.chromecast.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())
|
||||
state.chromecast.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())
|
||||
state.chromecast.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())
|
||||
state.chromecast.set_volume(volume).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
async fn download_audio(url: &str) -> Result<Vec<u8>, String> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Chromecast device connection and media control
|
||||
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use rust_cast::CastDevice;
|
||||
use rust_cast::channels::media::{Image, Media, Metadata, MusicTrackMediaMetadata, StreamType};
|
||||
@@ -11,7 +11,7 @@ use crate::cast::CastError;
|
||||
const DEFAULT_RECEIVER_ID: &str = "receiver-0";
|
||||
|
||||
/// Media metadata for casting
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct MediaMetadata {
|
||||
pub title: String,
|
||||
pub artist: String,
|
||||
|
||||
@@ -162,32 +162,32 @@ fn handle_request(
|
||||
url: &str,
|
||||
request: &tiny_http::Request,
|
||||
entries: &Arc<Mutex<HashMap<u64, MediaEntry>>>,
|
||||
) -> Response<impl Read> {
|
||||
) -> Response<std::io::Cursor<Vec<u8>>> {
|
||||
if method != &Method::Get {
|
||||
return Response::new_empty(StatusCode(405));
|
||||
return Response::from_data(Vec::new()).with_status_code(StatusCode(405));
|
||||
}
|
||||
|
||||
let id = match parse_audio_id(url) {
|
||||
Some(id) => id,
|
||||
None => return Response::new_empty(StatusCode(404)),
|
||||
None => 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) => entry,
|
||||
None => return Response::new_empty(StatusCode(404)),
|
||||
None => return Response::from_data(Vec::new()).with_status_code(StatusCode(404)),
|
||||
};
|
||||
|
||||
let range_header = request
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|h| h.field.equiv("Range"))
|
||||
.and_then(|h| Some(h.value.as_str()));
|
||||
.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::new_empty(StatusCode(500)),
|
||||
Err(_) => return Response::from_data(Vec::new()).with_status_code(StatusCode(500)),
|
||||
};
|
||||
|
||||
let mut response = Response::from_data(data)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Casting module (Chromecast-first, designed for future AirPlay/DLNA expansion).
|
||||
|
||||
pub mod chromecast_thread;
|
||||
pub mod commands;
|
||||
pub mod device;
|
||||
pub mod discovery;
|
||||
|
||||
Reference in new issue
Block a user