Implement Chromecast frontend and DLNA AVTransport casting

Frontend:
- Add castStore for managing cast state (connect, disconnect, play, pause, etc)
- Update CastPicker to use castStore, show connected device banner with disconnect
- Wire isCastConnected to NowPlayingBar and ExpandedPlayer for visual indicator
- Modify playbackService to cast when connected instead of local playback

DLNA Backend:
- Implement full AVTransport SOAP client with:
  - SetAVTransportURI with DIDL-Lite metadata
  - Play, Pause, Stop, Seek actions
  - RenderingControl SetVolume
- Add dlna_play_track command that fetches stream, downloads audio, and serves via media server
- Share media server between Chromecast and DLNA
This commit is contained in:
vicrodh committed 2026-01-12 10:11:09 -06:00
1 parent a4c09041a4
commit 1ac6d15551
8 files changed
+1025 -143

No files matched your search

+183 -95
View File
@@ -1,24 +1,22 @@
<script lang="ts">
import { invoke } from '@tauri-apps/api/core';
import { onMount, onDestroy } from 'svelte';
import { X, Cast, Loader2, Monitor, Wifi, Tv, Speaker } from 'lucide-svelte';
import { X, Cast, Loader2, Monitor, Wifi, Tv, Speaker, Power } from 'lucide-svelte';
import {
subscribe as subscribeCast,
getCastState,
connectToDevice,
disconnect,
type CastProtocol,
type CastDevice
} from '$lib/stores/castStore';
interface Props {
isOpen: boolean;
onClose: () => void;
onConnect: (deviceId: string, protocol: CastProtocol) => void;
}
type CastProtocol = 'chromecast' | 'dlna' | 'airplay';
interface CastDevice {
id: string;
name: string;
ip: string;
port: number;
}
let { isOpen, onClose, onConnect }: Props = $props();
let { isOpen, onClose }: Props = $props();
let activeProtocol = $state<CastProtocol>('chromecast');
let chromecastDevices = $state<CastDevice[]>([]);
@@ -27,6 +25,10 @@
let loading = $state(false);
let error = $state<string | null>(null);
let discoveryStarted = $state(false);
let connecting = $state(false);
// Cast state from store
let castState = $state(getCastState());
const devices = $derived(() => {
switch (activeProtocol) {
@@ -36,13 +38,20 @@
}
});
let unsubscribeCast: (() => void) | null = null;
onMount(() => {
unsubscribeCast = subscribeCast(() => {
castState = getCastState();
});
if (isOpen) {
startDiscovery();
}
});
onDestroy(() => {
unsubscribeCast?.();
if (discoveryStarted) {
stopDiscovery();
}
@@ -122,22 +131,23 @@
}
async function handleConnect(device: CastDevice) {
connecting = true;
error = null;
try {
switch (activeProtocol) {
case 'chromecast':
await invoke('cast_connect', { deviceId: device.id });
break;
case 'dlna':
await invoke('dlna_connect', { deviceId: device.id });
break;
case 'airplay':
await invoke('airplay_connect', { deviceId: device.id });
break;
}
onConnect(device.id, activeProtocol);
await connectToDevice(device, activeProtocol);
onClose();
} catch (err) {
error = String(err);
} finally {
connecting = false;
}
}
async function handleDisconnect() {
try {
await disconnect();
} catch (err) {
error = String(err);
}
}
@@ -149,11 +159,11 @@
}
}
function getDeviceCount(protocol: CastProtocol): number {
function getProtocolLabel(protocol: CastProtocol): string {
switch (protocol) {
case 'chromecast': return chromecastDevices.length;
case 'dlna': return dlnaDevices.length;
case 'airplay': return airplayDevices.length;
case 'chromecast': return 'Chromecast';
case 'dlna': return 'DLNA';
case 'airplay': return 'AirPlay';
}
}
</script>
@@ -168,74 +178,96 @@
</button>
</div>
<!-- Protocol Tabs -->
<div class="protocol-tabs">
<button
class="protocol-tab"
class:active={activeProtocol === 'chromecast'}
onclick={() => activeProtocol = 'chromecast'}
>
<Cast size={16} />
<span>Chromecast</span>
{#if chromecastDevices.length > 0}
<span class="count">{chromecastDevices.length}</span>
{/if}
</button>
<button
class="protocol-tab"
class:active={activeProtocol === 'dlna'}
onclick={() => activeProtocol = 'dlna'}
>
<Tv size={16} />
<span>DLNA</span>
{#if dlnaDevices.length > 0}
<span class="count">{dlnaDevices.length}</span>
{/if}
</button>
<button
class="protocol-tab"
class:active={activeProtocol === 'airplay'}
onclick={() => activeProtocol = 'airplay'}
>
<Speaker size={16} />
<span>AirPlay</span>
{#if airplayDevices.length > 0}
<span class="count">{airplayDevices.length}</span>
{/if}
</button>
</div>
<!-- Connected Device Banner -->
{#if castState.isConnected && castState.device}
<div class="connected-banner">
<div class="connected-info">
<svelte:component this={getProtocolIcon(castState.protocol!)} size={20} />
<div class="connected-text">
<span class="connected-label">Connected to</span>
<span class="connected-name">{castState.device.name}</span>
</div>
</div>
<button class="disconnect-btn" onclick={handleDisconnect}>
<Power size={16} />
<span>Disconnect</span>
</button>
</div>
{:else}
<!-- Protocol Tabs (only show when not connected) -->
<div class="protocol-tabs">
<button
class="protocol-tab"
class:active={activeProtocol === 'chromecast'}
onclick={() => activeProtocol = 'chromecast'}
>
<Cast size={16} />
<span>Chromecast</span>
{#if chromecastDevices.length > 0}
<span class="count">{chromecastDevices.length}</span>
{/if}
</button>
<button
class="protocol-tab"
class:active={activeProtocol === 'dlna'}
onclick={() => activeProtocol = 'dlna'}
>
<Tv size={16} />
<span>DLNA</span>
{#if dlnaDevices.length > 0}
<span class="count">{dlnaDevices.length}</span>
{/if}
</button>
<button
class="protocol-tab"
class:active={activeProtocol === 'airplay'}
onclick={() => activeProtocol = 'airplay'}
>
<Speaker size={16} />
<span>AirPlay</span>
{#if airplayDevices.length > 0}
<span class="count">{airplayDevices.length}</span>
{/if}
</button>
</div>
<div class="content">
{#if loading && devices().length === 0}
<div class="loading">
<Loader2 size={32} class="spin" />
<p>Searching for devices...</p>
</div>
{:else if error}
<div class="error">
<p>{error}</p>
</div>
{:else if devices().length === 0}
<div class="empty">
<Wifi size={32} />
<p>No {activeProtocol === 'chromecast' ? 'Chromecast' : activeProtocol === 'dlna' ? 'DLNA' : 'AirPlay'} devices found</p>
<p class="hint">Make sure devices are on the same network</p>
</div>
{:else}
<div class="devices">
{#each devices() as device}
<button class="device" onclick={() => handleConnect(device)}>
<Monitor size={24} />
<div class="device-info">
<span class="device-name">{device.name}</span>
<span class="device-ip">{device.ip}</span>
</div>
<svelte:component this={getProtocolIcon(activeProtocol)} size={20} class="cast-icon" />
</button>
{/each}
</div>
{/if}
</div>
<div class="content">
{#if connecting}
<div class="loading">
<Loader2 size={32} class="spin" />
<p>Connecting...</p>
</div>
{:else if loading && devices().length === 0}
<div class="loading">
<Loader2 size={32} class="spin" />
<p>Searching for devices...</p>
</div>
{:else if error}
<div class="error">
<p>{error}</p>
</div>
{:else if devices().length === 0}
<div class="empty">
<Wifi size={32} />
<p>No {getProtocolLabel(activeProtocol)} devices found</p>
<p class="hint">Make sure devices are on the same network</p>
</div>
{:else}
<div class="devices">
{#each devices() as device}
<button class="device" onclick={() => handleConnect(device)}>
<Monitor size={24} />
<div class="device-info">
<span class="device-name">{device.name}</span>
<span class="device-ip">{device.ip}</span>
</div>
<svelte:component this={getProtocolIcon(activeProtocol)} size={20} class="cast-icon" />
</button>
{/each}
</div>
{/if}
</div>
{/if}
</div>
</div>
{/if}
@@ -416,4 +448,60 @@
opacity: 1;
color: var(--accent-primary);
}
/* Connected Banner */
.connected-banner {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 20px;
background: linear-gradient(135deg, rgba(34, 197, 94, 0.15) 0%, rgba(34, 197, 94, 0.05) 100%);
border-bottom: 1px solid rgba(34, 197, 94, 0.2);
}
.connected-info {
display: flex;
align-items: center;
gap: 12px;
color: #22c55e;
}
.connected-text {
display: flex;
flex-direction: column;
gap: 2px;
}
.connected-label {
font-size: 11px;
color: rgba(34, 197, 94, 0.8);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.connected-name {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.disconnect-btn {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 12px;
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.3);
border-radius: 6px;
color: #ef4444;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 150ms ease;
}
.disconnect-btn:hover {
background: rgba(239, 68, 68, 0.2);
border-color: rgba(239, 68, 68, 0.5);
}
</style>
+18 -1
View File
@@ -37,6 +37,7 @@
onOpenQueue?: () => void;
onOpenFocusMode?: () => void;
onCast?: () => void;
isCastConnected?: boolean;
// Lyrics props
lyricsLines?: LyricsLine[];
lyricsActiveIndex?: number;
@@ -75,6 +76,7 @@
onOpenQueue,
onOpenFocusMode,
onCast,
isCastConnected = false,
lyricsLines = [],
lyricsActiveIndex = -1,
lyricsActiveProgress = 0,
@@ -285,7 +287,12 @@
<button class="action-btn" onclick={onOpenFocusMode} title="Focus Mode">
<Maximize2 size={22} />
</button>
<button class="action-btn" onclick={onCast} title="Cast to device">
<button
class="action-btn"
class:cast-active={isCastConnected}
onclick={onCast}
title={isCastConnected ? 'Casting - Click to manage' : 'Cast to device'}
>
<Cast size={22} />
</button>
<button
@@ -659,6 +666,16 @@
color: var(--accent-primary);
}
.action-btn.cast-active {
color: #22c55e;
animation: cast-pulse 2s ease-in-out infinite;
}
@keyframes cast-pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.6; }
}
/* Right Section: Lyrics */
.right-section {
flex: 1;
+23 -4
View File
@@ -18,6 +18,13 @@ import {
} from '$lib/stores/playerStore';
import { syncQueueState } from '$lib/stores/queueStore';
import { logRecoEvent } from '$lib/services/recoService';
import {
isCasting,
castTrack,
castPlay,
castPause,
castStop
} from '$lib/stores/castStore';
// ============ Types ============
@@ -66,11 +73,23 @@ export async function playTrack(
showToast(track.title, 'buffering');
}
// Use appropriate playback command
if (isLocal) {
await invoke('library_play_track', { trackId: track.id });
// Check if we're casting to an external device
if (isCasting() && !isLocal) {
// Cast to connected device
await castTrack(track.id, {
title: track.title,
artist: track.artist,
album: track.album,
artworkUrl: track.artwork,
durationSecs: track.duration
});
} else {
await invoke('play_track', { trackId: track.id });
// Use appropriate local playback command
if (isLocal) {
await invoke('library_play_track', { trackId: track.id });
} else {
await invoke('play_track', { trackId: track.id });
}
}
// Dismiss buffering toast and show success
+334
View File
@@ -0,0 +1,334 @@
/**
* Cast Store
*
* Manages casting state across the app.
* Tracks connected device and protocol.
*/
import { invoke } from '@tauri-apps/api/core';
export type CastProtocol = 'chromecast' | 'dlna' | 'airplay';
export interface CastDevice {
id: string;
name: string;
ip: string;
port: number;
}
interface CastState {
isConnected: boolean;
protocol: CastProtocol | null;
device: CastDevice | null;
isPlaying: boolean;
currentTrackId: number | null;
}
let state: CastState = {
isConnected: false,
protocol: null,
device: null,
isPlaying: false,
currentTrackId: null
};
const listeners = new Set<() => void>();
function notifyListeners(): void {
for (const listener of listeners) {
listener();
}
}
/**
* Subscribe to cast state changes
*/
export function subscribe(listener: () => void): () => void {
listeners.add(listener);
listener();
return () => listeners.delete(listener);
}
/**
* Get current cast state
*/
export function getCastState(): CastState {
return { ...state };
}
/**
* Check if currently casting
*/
export function isCasting(): boolean {
return state.isConnected;
}
/**
* Get connected device info
*/
export function getConnectedDevice(): CastDevice | null {
return state.device;
}
/**
* Get connected protocol
*/
export function getConnectedProtocol(): CastProtocol | null {
return state.protocol;
}
/**
* Connect to a cast device
*/
export async function connectToDevice(device: CastDevice, protocol: CastProtocol): Promise<void> {
try {
switch (protocol) {
case 'chromecast':
await invoke('cast_connect', { deviceId: device.id });
break;
case 'dlna':
await invoke('dlna_connect', { deviceId: device.id });
break;
case 'airplay':
await invoke('airplay_connect', { deviceId: device.id });
break;
}
state = {
...state,
isConnected: true,
protocol,
device,
isPlaying: false,
currentTrackId: null
};
notifyListeners();
} catch (err) {
console.error('[CastStore] Failed to connect:', err);
throw err;
}
}
/**
* Disconnect from current device
*/
export async function disconnect(): Promise<void> {
if (!state.isConnected || !state.protocol) return;
try {
switch (state.protocol) {
case 'chromecast':
await invoke('cast_disconnect');
break;
case 'dlna':
await invoke('dlna_disconnect');
break;
case 'airplay':
await invoke('airplay_disconnect');
break;
}
} catch (err) {
console.error('[CastStore] Failed to disconnect:', err);
}
state = {
isConnected: false,
protocol: null,
device: null,
isPlaying: false,
currentTrackId: null
};
notifyListeners();
}
/**
* Cast a track to the connected device
*/
export async function castTrack(
trackId: number,
metadata: {
title: string;
artist: string;
album: string;
artworkUrl?: string;
durationSecs?: number;
}
): Promise<void> {
if (!state.isConnected || !state.protocol) {
throw new Error('Not connected to any cast device');
}
try {
switch (state.protocol) {
case 'chromecast':
await invoke('cast_play_track', {
trackId,
metadata: {
title: metadata.title,
artist: metadata.artist,
album: metadata.album,
artwork_url: metadata.artworkUrl,
duration_secs: metadata.durationSecs
}
});
break;
case 'dlna':
await invoke('dlna_play_track', {
trackId: trackId,
metadata: {
title: metadata.title,
artist: metadata.artist,
album: metadata.album,
artwork_url: metadata.artworkUrl,
duration_secs: metadata.durationSecs
}
});
break;
case 'airplay':
await invoke('airplay_load_media', {
metadata: {
title: metadata.title,
artist: metadata.artist,
album: metadata.album,
artwork_url: metadata.artworkUrl,
duration_secs: metadata.durationSecs
}
});
await invoke('airplay_play');
break;
}
state = {
...state,
isPlaying: true,
currentTrackId: trackId
};
notifyListeners();
} catch (err) {
console.error('[CastStore] Failed to cast track:', err);
throw err;
}
}
/**
* Play/resume on cast device
*/
export async function castPlay(): Promise<void> {
if (!state.isConnected || !state.protocol) return;
try {
switch (state.protocol) {
case 'chromecast':
await invoke('cast_play');
break;
case 'dlna':
await invoke('dlna_play');
break;
case 'airplay':
await invoke('airplay_play');
break;
}
state = { ...state, isPlaying: true };
notifyListeners();
} catch (err) {
console.error('[CastStore] Failed to play:', err);
}
}
/**
* Pause on cast device
*/
export async function castPause(): Promise<void> {
if (!state.isConnected || !state.protocol) return;
try {
switch (state.protocol) {
case 'chromecast':
await invoke('cast_pause');
break;
case 'dlna':
await invoke('dlna_pause');
break;
case 'airplay':
await invoke('airplay_pause');
break;
}
state = { ...state, isPlaying: false };
notifyListeners();
} catch (err) {
console.error('[CastStore] Failed to pause:', err);
}
}
/**
* Stop on cast device
*/
export async function castStop(): Promise<void> {
if (!state.isConnected || !state.protocol) return;
try {
switch (state.protocol) {
case 'chromecast':
await invoke('cast_stop');
break;
case 'dlna':
await invoke('dlna_stop');
break;
case 'airplay':
await invoke('airplay_stop');
break;
}
state = { ...state, isPlaying: false, currentTrackId: null };
notifyListeners();
} catch (err) {
console.error('[CastStore] Failed to stop:', err);
}
}
/**
* Seek on cast device
*/
export async function castSeek(positionSecs: number): Promise<void> {
if (!state.isConnected || !state.protocol) return;
try {
switch (state.protocol) {
case 'chromecast':
await invoke('cast_seek', { positionSecs });
break;
case 'dlna':
// DLNA seek - will implement
break;
case 'airplay':
// AirPlay seek - not implemented
break;
}
} catch (err) {
console.error('[CastStore] Failed to seek:', err);
}
}
/**
* Set volume on cast device
*/
export async function castSetVolume(volume: number): Promise<void> {
if (!state.isConnected || !state.protocol) return;
const normalizedVolume = Math.max(0, Math.min(1, volume / 100));
try {
switch (state.protocol) {
case 'chromecast':
await invoke('cast_set_volume', { volume: normalizedVolume });
break;
case 'dlna':
await invoke('dlna_set_volume', { volume: normalizedVolume });
break;
case 'airplay':
await invoke('airplay_set_volume', { volume: normalizedVolume });
break;
}
} catch (err) {
console.error('[CastStore] Failed to set volume:', err);
}
}