Files
jellytau/src-tauri/src/player/webview_audio_backend.rs
T
dtourolle 8500da1a42 chore(rust): clear the clippy backlog and finish the poison-tolerant lock sweep
`cargo clippy --all-targets` went from 51 warnings (23 in the lib) to zero.
Most were mechanical — needless borrows, `assert_eq!` against a bool literal,
`vec!` where an array does, `or_insert_with(Vec::new)`, a loop index used only
to index — and were applied with `clippy --fix`, then reviewed line by line.
That review caught one auto-fix that was *not* semantically neutral: dropping
the redundant `use hostname;` left its `#[cfg(target_os = "linux")]` orphaned
directly above `SERVICE_NAME`, which would have silently cfg'd the constant out
of every non-Linux build. Removed the stray attribute with the import.

Where a lint asked for a risky change rather than a better one, it is suppressed
with a comment saying why:

- `too_many_arguments` on five `#[tauri::command]` handlers and
  `ThumbnailCache::save_thumbnail` — most of the arity is `State<'_, _>`
  injection, and a parameter struct would change the IPC contract and the
  generated TypeScript for no readability gain.
- `large_enum_variant` on `PlayerStatusEvent` and `AutoplayDecision` — both are
  serde + specta wire types emitted a handful of times a second, never bulk
  allocated; boxing would have to stay invisible to the generated bindings while
  every match arm gained a deref.
- `await_holding_lock` on the `hybrid`/`offline` test modules — the guard is a
  test-only serialisation lock for the process-global `INCLUDE_CATALOG_BROWSE`
  flag, and the await it spans *is* the critical section. Each `#[tokio::test]`
  gets its own single-threaded runtime, so this is not the production deadlock
  class the lint targets; restructuring would reintroduce the flag race.

Real fixes elsewhere: `JellyfinItem::to_media_item` takes `self` by value, so it
is now `into_media_item`; the five-tuple episode row in the download commands
has a named `EpisodeRow` alias; the mpv `PropertyChange` arm matches
`name: "pause"` instead of guarding on it.

Also converted the last 27 raw `.lock().unwrap()` call sites to `lock_safe()`,
completing the `MutexSafe`/`RwLockSafe` convention. All of them turned out to be
in test modules — production code was already clean — so this is consistency
rather than a fix. The two raw locks in `utils/lock.rs` stay raw on purpose:
those tests deliberately poison a mutex to prove the helpers recover from it.

Pure refactoring: all 698 tests still pass.
2026-08-16 23:05:13 +02:00

296 lines
10 KiB
Rust

//! Webview audio backend — audio-only playback for platforms without a native
//! audio backend (currently Windows).
//!
//! ## Why this exists
//! All *video* already renders through the webview HTML5 `<video>` element on
//! every platform (see `VideoPlayer.svelte`); libmpv/ExoPlayer only ever drive
//! *audio-only* (music) playback. On Windows there is no native audio backend,
//! so `create_player_backend()` used to fall back to `NullBackend` and music was
//! silent.
//!
//! This backend fills that gap without any C dependency (so it still
//! cross-compiles from Linux): instead of decoding audio itself, it hands the
//! stream URL to a frontend `<audio>` element via a `WebviewAudioLoad` event and
//! then drives play/pause/seek/stop through `ControlCommand` events — exactly the
//! round-trip the HTML5 video path already uses. The `<audio>` element reports
//! its real state/position back through the `player_report_*` commands, so the
//! Rust `PlayerController` remains the single source of truth (the controller's
//! `report_html5_*` methods fold those reports into the normal event pipeline).
//!
//! Because the reported state flows through the event pipeline (not through this
//! backend's `position()`/`state()` pollers — the timer loop does not poll the
//! backend for HTML5-rendered media), this backend only needs to keep a
//! best-effort local mirror for direct `player_get_state` queries.
//!
//! TRACES: UR-003, UR-004, UR-005 | DR-004
use std::sync::Arc;
use log::{debug, info};
use super::backend::{PlayerBackend, PlayerError};
use super::events::{PlayerEventEmitter, PlayerStatusEvent};
use super::media::{MediaItem, MediaSource};
use super::state::PlayerState;
use crate::settings::AudioSettings;
use crate::utils::lock::MutexSafe;
/// Extract a webview-playable URL from a media item's source.
///
/// Remote/DirectUrl are HTTP(S) URLs the `<audio>` element can play directly.
/// Local files would need the Tauri asset protocol (`convertFileSrc`) on the
/// frontend; for now we pass the path through and let the frontend resolve it.
fn stream_url(media: &MediaItem) -> String {
match &media.source {
MediaSource::Remote { stream_url, .. } => stream_url.clone(),
MediaSource::DirectUrl { url } => url.clone(),
MediaSource::Local { file_path, .. } => file_path.to_string_lossy().to_string(),
}
}
struct InternalState {
current_media: Option<MediaItem>,
volume: f32,
position: f64,
duration: Option<f64>,
state: PlayerState,
audio_settings: AudioSettings,
}
pub struct WebviewAudioBackend {
emitter: Arc<dyn PlayerEventEmitter>,
state: Arc<std::sync::Mutex<InternalState>>,
}
impl WebviewAudioBackend {
pub fn new(emitter: Arc<dyn PlayerEventEmitter>) -> Result<Self, PlayerError> {
info!("[WebviewAudioBackend] Initializing (audio renders in webview <audio>)");
Ok(Self {
emitter,
state: Arc::new(std::sync::Mutex::new(InternalState {
current_media: None,
volume: 1.0,
position: 0.0,
duration: None,
state: PlayerState::Idle,
audio_settings: AudioSettings::default(),
})),
})
}
/// Emit a backend-originated control intent to the active frontend adapter
/// (the webview `<audio>` element, via `playerEvents.ts` -> active adapter).
fn emit_control(&self, action: &str, position: Option<f64>) {
self.emitter.emit(PlayerStatusEvent::ControlCommand {
action: action.to_string(),
position,
});
}
}
impl PlayerBackend for WebviewAudioBackend {
fn load(&mut self, media: &MediaItem) -> Result<(), PlayerError> {
let url = stream_url(media);
info!("[WebviewAudioBackend] load: {} - {}", media.title, url);
{
let mut st = self.state.lock_safe();
st.current_media = Some(media.clone());
st.position = 0.0;
st.duration = media.duration;
st.state = PlayerState::Loading {
media: media.clone(),
};
}
// Hand the URL to the frontend <audio> element. autoplay=true so a plain
// load-then-play (the common queue-advance path) starts immediately; an
// explicit pause afterwards is still honored via ControlCommand.
self.emitter.emit(PlayerStatusEvent::WebviewAudioLoad {
url,
media_id: media.jellyfin_id().map(|s| s.to_string()),
position: 0.0,
autoplay: true,
});
Ok(())
}
fn play(&mut self) -> Result<(), PlayerError> {
debug!("[WebviewAudioBackend] play");
self.emit_control("play", None);
Ok(())
}
fn pause(&mut self) -> Result<(), PlayerError> {
debug!("[WebviewAudioBackend] pause");
self.emit_control("pause", None);
Ok(())
}
fn stop(&mut self) -> Result<(), PlayerError> {
debug!("[WebviewAudioBackend] stop");
{
let mut st = self.state.lock_safe();
st.current_media = None;
st.position = 0.0;
st.duration = None;
st.state = PlayerState::Idle;
}
self.emit_control("stop", None);
Ok(())
}
fn seek(&mut self, position: f64) -> Result<(), PlayerError> {
debug!("[WebviewAudioBackend] seek: {}", position);
self.state.lock_safe().position = position;
self.emit_control("seek", Some(position));
Ok(())
}
fn set_volume(&mut self, volume: f32) -> Result<(), PlayerError> {
let clamped = volume.clamp(0.0, 1.0);
self.state.lock_safe().volume = clamped;
// Volume is applied on the element by the frontend, which observes the
// volume via the player store; no dedicated ControlCommand action yet.
Ok(())
}
fn position(&self) -> f64 {
self.state.lock_safe().position
}
fn duration(&self) -> Option<f64> {
self.state.lock_safe().duration
}
fn state(&self) -> PlayerState {
self.state.lock_safe().state.clone()
}
fn volume(&self) -> f32 {
self.state.lock_safe().volume
}
fn set_audio_settings(&mut self, settings: &AudioSettings) -> Result<(), PlayerError> {
self.state.lock_safe().audio_settings = settings.clone().with_crossfade_clamped();
Ok(())
}
fn audio_settings(&self) -> AudioSettings {
self.state.lock_safe().audio_settings.clone()
}
}
// TRACES: UR-003, UR-004, UR-005 | DR-004
#[cfg(test)]
mod tests {
use super::*;
use crate::player::events::PlayerStatusEvent;
use crate::player::media::{MediaSource, MediaType};
use std::sync::Mutex as StdMutex;
/// Test emitter that records everything emitted.
struct RecordingEmitter {
events: Arc<StdMutex<Vec<PlayerStatusEvent>>>,
}
impl PlayerEventEmitter for RecordingEmitter {
fn emit(&self, event: PlayerStatusEvent) {
self.events.lock_safe().push(event);
}
}
fn test_media() -> MediaItem {
MediaItem {
id: "track1".to_string(),
title: "Song".to_string(),
name: Some("Song".to_string()),
artist: Some("Artist".to_string()),
album: Some("Album".to_string()),
album_name: Some("Album".to_string()),
album_id: None,
artist_items: None,
artists: Some(vec!["Artist".to_string()]),
primary_image_tag: None,
image_id: None,
item_type: Some("Audio".to_string()),
playlist_id: None,
duration: Some(200.0),
artwork_url: None,
media_type: MediaType::Audio,
source: MediaSource::DirectUrl {
url: "http://example.com/song.mp3".to_string(),
},
video_codec: None,
needs_transcoding: false,
video_width: None,
video_height: None,
subtitles: vec![],
series_id: None,
server_id: None,
}
}
fn backend() -> (WebviewAudioBackend, Arc<StdMutex<Vec<PlayerStatusEvent>>>) {
let events = Arc::new(StdMutex::new(Vec::new()));
let emitter = Arc::new(RecordingEmitter {
events: events.clone(),
});
(WebviewAudioBackend::new(emitter).unwrap(), events)
}
#[test]
fn load_emits_webview_audio_load_with_url() {
let (mut b, events) = backend();
b.load(&test_media()).unwrap();
let ev = events.lock_safe();
let load = ev
.iter()
.find(|e| matches!(e, PlayerStatusEvent::WebviewAudioLoad { .. }))
.expect("WebviewAudioLoad emitted");
if let PlayerStatusEvent::WebviewAudioLoad { url, autoplay, .. } = load {
assert_eq!(url, "http://example.com/song.mp3");
assert!(*autoplay);
}
assert!(matches!(b.state(), PlayerState::Loading { .. }));
}
#[test]
fn pause_and_seek_emit_control_commands() {
let (mut b, events) = backend();
b.load(&test_media()).unwrap();
b.pause().unwrap();
b.seek(42.0).unwrap();
let ev = events.lock_safe();
assert!(ev.iter().any(|e| matches!(
e,
PlayerStatusEvent::ControlCommand { action, .. } if action == "pause"
)));
assert!(ev.iter().any(|e| matches!(
e,
PlayerStatusEvent::ControlCommand { action, position: Some(p) }
if action == "seek" && (*p - 42.0).abs() < f64::EPSILON
)));
assert_eq!(b.position(), 42.0);
}
#[test]
fn volume_is_clamped_and_stored() {
let (mut b, _events) = backend();
b.set_volume(1.5).unwrap();
assert_eq!(b.volume(), 1.0);
b.set_volume(-0.2).unwrap();
assert_eq!(b.volume(), 0.0);
}
#[test]
fn stop_resets_to_idle() {
let (mut b, _events) = backend();
b.load(&test_media()).unwrap();
b.stop().unwrap();
assert!(matches!(b.state(), PlayerState::Idle));
}
}