diff --git a/src/components/buttons/castButton.tsx b/src/components/buttons/castButton.tsx index d01e4f2..6faf588 100644 --- a/src/components/buttons/castButton.tsx +++ b/src/components/buttons/castButton.tsx @@ -2,21 +2,36 @@ import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client"; import IconButton from "@mui/material/IconButton"; import Tooltip from "@mui/material/Tooltip"; import React from "react"; -import useRemoteControlStore from "@/utils/store/remoteControl"; +import useRemoteControlStore, { + type RemoteTransfer, +} from "@/utils/store/remoteControl"; type CastButtonProps = { item?: BaseItemDto | null; + transfer?: Omit; + /** Computed on click so playback position/queue are current. */ + getTransfer?: () => Omit; size?: "small" | "medium" | "large"; }; -const CastButton = ({ item, size = "medium" }: CastButtonProps) => { +const CastButton = ({ + item, + transfer, + getTransfer, + size = "medium", +}: CastButtonProps) => { const openDialog = useRemoteControlStore((s) => s.openDialog); return ( openDialog(item ?? null)} + onClick={() => + openDialog({ + ...(getTransfer ? getTransfer() : transfer), + item: item ?? null, + }) + } > cast diff --git a/src/components/playback/audioPlayer/components/PlayerActions.tsx b/src/components/playback/audioPlayer/components/PlayerActions.tsx index ca200e1..20e5fd6 100644 --- a/src/components/playback/audioPlayer/components/PlayerActions.tsx +++ b/src/components/playback/audioPlayer/components/PlayerActions.tsx @@ -12,15 +12,34 @@ interface PlayerActionsProps { onClose: () => void; /** The track currently playing (for cast / instant mix). */ item?: BaseItemDto | null; + positionTicks?: number; + queue?: BaseItemDto[]; + startIndex?: number; /** Volume control, rendered between the queue and expand buttons. */ children?: ReactNode; } -const PlayerActions = ({ onExpand, onClose, item, children }: PlayerActionsProps) => { +const PlayerActions = ({ + onExpand, + onClose, + item, + positionTicks = 0, + queue = [], + startIndex = 0, + children, +}: PlayerActionsProps) => { return (
{item && } - {item && } + {item && }
{children}
diff --git a/src/components/playback/audioPlayer/index.tsx b/src/components/playback/audioPlayer/index.tsx index 55a3477..b49029e 100644 --- a/src/components/playback/audioPlayer/index.tsx +++ b/src/components/playback/audioPlayer/index.tsx @@ -245,7 +245,14 @@ const AudioPlayer = () => { />
- + - + ({ + kind: "video", + positionTicks: secToTicks( + usePlaybackStore.getState().getCurrentTime(), + ), + queue: useQueue.getState().tracks ?? [], + startIndex: useQueue.getState().currentItemIndex, + })} + /> diff --git a/src/components/remoteControl/index.tsx b/src/components/remoteControl/index.tsx index 914610c..eeaa62a 100644 --- a/src/components/remoteControl/index.tsx +++ b/src/components/remoteControl/index.tsx @@ -20,10 +20,14 @@ import { Typography, } from "@mui/material"; import { useMutation, useQuery } from "@tanstack/react-query"; +import { useNavigate } from "@tanstack/react-router"; import { useSnackbar } from "notistack"; import React from "react"; import { useApiInContext } from "@/utils/store/api"; +import { stopPlayback } from "@/utils/store/audioPlayback"; import { useCentralStore } from "@/utils/store/central"; +import { usePlaybackStore } from "@/utils/store/playback"; +import { clearQueue } from "@/utils/store/queue"; import useRemoteControlStore from "@/utils/store/remoteControl"; const TICKS_PER_SECOND = 10_000_000; @@ -42,10 +46,12 @@ const sessionLabel = (session: SessionInfoDto) => session.DeviceName || session.Client || session.DeviceId || "Unknown device"; const RemoteControlDialog = () => { - const { open, item, closeDialog } = useRemoteControlStore(); + const { open, transfer, closeDialog } = useRemoteControlStore(); + const item = transfer?.item; const api = useApiInContext((s) => s.api); const user = useCentralStore((s) => s.currentUser); const { enqueueSnackbar } = useSnackbar(); + const navigate = useNavigate(); const sessions = useQuery({ queryKey: ["remoteSessions"], @@ -87,18 +93,33 @@ const RemoteControlDialog = () => { const playOn = useMutation({ mutationFn: async (session: SessionInfoDto) => { if (!api || !session.Id || !item?.Id) return; + const queueIds = + transfer?.queue + ?.map((queueItem) => queueItem.Id) + .filter((id): id is string => Boolean(id)) ?? []; await getSessionApi(api).play({ sessionId: session.Id, playCommand: PlayCommand.PlayNow, - itemIds: [item.Id], - startPositionTicks: 0, + itemIds: queueIds.length > 0 ? queueIds : [item.Id], + startIndex: transfer?.startIndex ?? 0, + startPositionTicks: transfer?.positionTicks ?? 0, mediaSourceId: item.MediaSources?.[0]?.Id ?? undefined, }); }, onSuccess: (_data, session) => { - enqueueSnackbar(`Playing on ${sessionLabel(session)}`, { - variant: "success", - }); + enqueueSnackbar( + transfer?.kind === "audio" || transfer?.kind === "video" + ? `Playback transferred to ${sessionLabel(session)}` + : `Playing on ${sessionLabel(session)}`, + { variant: "success" }, + ); + if (transfer?.kind === "audio") { + stopPlayback(); + } else if (transfer?.kind === "video") { + usePlaybackStore.setState(usePlaybackStore.getInitialState()); + clearQueue(); + navigate({ to: "/home" }); + } closeDialog(); }, onError: () => diff --git a/src/components/remotePlaybackBar/index.tsx b/src/components/remotePlaybackBar/index.tsx new file mode 100644 index 0000000..c99c18d --- /dev/null +++ b/src/components/remotePlaybackBar/index.tsx @@ -0,0 +1,137 @@ +import { PlaystateCommand, type SessionInfoDto } from "@jellyfin/sdk/lib/generated-client"; +import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api"; +import { Button, IconButton, Tooltip, Typography } from "@mui/material"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { useLocation, useNavigate } from "@tanstack/react-router"; +import { useSnackbar } from "notistack"; +import React from "react"; +import { transferSessionToLocal } from "@/utils/methods/transferPlayback"; +import { useApiInContext } from "@/utils/store/api"; +import { useAudioPlayback } from "@/utils/store/audioPlayback"; +import { useCentralStore } from "@/utils/store/central"; +import useRemoteControlStore from "@/utils/store/remoteControl"; + +import "./remotePlaybackBar.scss"; + +const RemotePlaybackBar = () => { + const api = useApiInContext((s) => s.api); + const user = useCentralStore((s) => s.currentUser); + const location = useLocation(); + const navigate = useNavigate(); + const { enqueueSnackbar } = useSnackbar(); + const openDialog = useRemoteControlStore((s) => s.openDialog); + const audioDisplay = useAudioPlayback((s) => s.display); + + const sessions = useQuery({ + queryKey: ["remoteSessions"], + queryFn: async () => { + if (!api || !user?.Id) return []; + const result = await getSessionApi(api).getSessions({ + controllableByUserId: user.Id, + }); + return result.data; + }, + enabled: !!api && !!user?.Id, + refetchInterval: 5000, + networkMode: "always", + }); + + const remote = (sessions.data ?? []).find( + (session: SessionInfoDto) => + session.Id && + session.DeviceId !== api?.deviceInfo.id && + session.NowPlayingItem, + ); + + const command = useMutation({ + mutationFn: async ({ + session, + command, + }: { + session: SessionInfoDto; + command: PlaystateCommand; + }) => { + if (!api || !session.Id) return; + await getSessionApi(api).sendPlaystateCommand({ + sessionId: session.Id, + command, + controllingUserId: user?.Id, + }); + }, + onSettled: () => sessions.refetch(), + }); + + const transfer = useMutation({ + mutationFn: async (session: SessionInfoDto) => + transferSessionToLocal(api, user?.Id, session), + onSuccess: async (kind) => { + await sessions.refetch(); + if (kind === "none") { + enqueueSnackbar("Could not transfer playback", { variant: "error" }); + return; + } + enqueueSnackbar("Playback transferred to this device", { + variant: "success", + }); + if (kind === "video") { + navigate({ to: "/player" }); + } + }, + onError: () => + enqueueSnackbar("Could not transfer playback", { variant: "error" }), + }); + + if (!remote || location.pathname.startsWith("/player")) { + return null; + } + + const paused = remote.PlayState?.IsPaused; + const title = remote.NowPlayingItem?.Name ?? "Unknown"; + + return ( +
+ openDialog()} + > + cast_connected + +
+ + Playing on {remote.DeviceName || remote.Client || "device"} + + + {title} + +
+ + + command.mutate({ + session: remote, + command: paused + ? PlaystateCommand.Unpause + : PlaystateCommand.Pause, + }) + } + > + + {paused ? "play_arrow" : "pause"} + + + + +
+ ); +}; + +export default React.memo(RemotePlaybackBar); diff --git a/src/components/remotePlaybackBar/remotePlaybackBar.scss b/src/components/remotePlaybackBar/remotePlaybackBar.scss new file mode 100644 index 0000000..a89f485 --- /dev/null +++ b/src/components/remotePlaybackBar/remotePlaybackBar.scss @@ -0,0 +1,42 @@ +.remote-playback-bar { + position: fixed; + left: 50%; + bottom: 1rem; + transform: translateX(-50%); + z-index: 99; + display: flex; + align-items: center; + gap: 0.6rem; + width: min(620px, calc(100% - 2rem)); + padding: 0.4rem 0.4rem 0.4rem 0.6rem; + box-sizing: border-box; + border-radius: 12px; + background: rgb(18 18 24 / 0.97); + border: 1px solid rgb(255 255 255 / 0.1); + box-shadow: 0 10px 30px rgb(0 0 0 / 0.45); + color: white; + + &.with-audio { + bottom: 6.2rem; // above the 80px audio player + } + + .material-symbols-rounded { + color: rgb(255 255 255 / 0.85); + } + + &-info { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + line-height: 1.15; + } + + &-device { + opacity: 0.6; + } + + &-title { + font-weight: 600; + } +} diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 3ce62c8..5c8eb44 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -28,6 +28,7 @@ import { HTML5Backend } from "react-dnd-html5-backend"; import Backdrop from "@/components/backdrop"; import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; import RemoteControlDialog from "@/components/remoteControl"; +import RemotePlaybackBar from "@/components/remotePlaybackBar"; import RouterLoading from "@/components/routerLoading"; import Search from "@/components/search"; import Updater from "@/components/updater"; @@ -58,6 +59,7 @@ export const Route = createRootRouteWithContext()({ + diff --git a/src/routes/_api/player/audio.tsx b/src/routes/_api/player/audio.tsx index 37e6eb9..5cec597 100644 --- a/src/routes/_api/player/audio.tsx +++ b/src/routes/_api/player/audio.tsx @@ -207,7 +207,15 @@ function AudioPlayerRoute() { {item && } {item && } - {item && } + {item && } => { + const item = session.NowPlayingItem; + if (!api || !userId || !item?.Id || !session.Id) { + return "none"; + } + + const positionTicks = session.PlayState?.PositionTicks ?? 0; + + // Rebuild the remote queue when the server reports it. + let queue: BaseItemDto[] = [item]; + let queueIndex = 0; + const queueIds = (session.NowPlayingQueue ?? []) + .map((queueItem) => queueItem.Id) + .filter((id): id is string => Boolean(id)); + if (queueIds.length > 0) { + try { + const result = await getLibraryApi(api).getItems({ + userId, + ids: queueIds, + fields, + enableUserData: true, + }); + const items = result.data.Items ?? []; + if (items.length > 0) { + queue = items; + const index = items.findIndex((entry) => entry.Id === item.Id); + queueIndex = index >= 0 ? index : 0; + } + } catch (error) { + console.warn("Could not restore remote queue", error); + } + } + + let kind: "audio" | "video" = "video"; + if (item.Type === BaseItemKind.Audio || item.Type === BaseItemKind.AudioBook) { + kind = "audio"; + const url = generateAudioStreamUrl( + item.Id, + userId, + api.deviceInfo.id, + api.basePath, + api.accessToken, + positionTicks, + ); + playAudio(url, item, undefined); + setQueue(queue, queueIndex); + } else { + const fullItem = + ( + await getLibraryApi(api).getItems({ + userId, + ids: [item.Id], + fields, + enableUserData: true, + }) + ).data.Items?.[0] ?? item; + const playback = await getPlaybackInfo(api, userId, fullItem); + const queueItems: BaseItemDto[] = playback.item?.Items?.length + ? playback.item.Items + : queue; + const index = Math.max( + 0, + queueItems.findIndex((entry: BaseItemDto) => entry.Id === fullItem.Id), + ); + await initializePlayback({ + api, + userId, + item: fullItem, + mediaSource: playback.mediaSource, + mediaSegments: playback.mediaSegments, + queueItems, + queueIndex: index, + startPositionTicks: positionTicks, + }); + } + + // Transfer, not cast: the remote device should stop. + try { + await getSessionApi(api).sendPlaystateCommand({ + sessionId: session.Id, + command: "Stop", + controllingUserId: userId, + }); + } catch (error) { + console.warn("Could not stop the remote session", error); + } + + return kind; +}; diff --git a/src/utils/store/audioPlayback.ts b/src/utils/store/audioPlayback.ts index 2709722..ba4b008 100644 --- a/src/utils/store/audioPlayback.ts +++ b/src/utils/store/audioPlayback.ts @@ -69,6 +69,7 @@ export const generateAudioStreamUrl = ( deviceId: string, basePath: string, api_key: string, + startTimeTicks = 0, ) => { const transcodingProfile = playbackProfile.TranscodingProfiles?.filter( (val) => val.Type === "Audio" && val.Context === "Streaming", @@ -100,7 +101,7 @@ export const generateAudioStreamUrl = ( transcodingProtocol: transcodingProfile?.Protocol, audioCodec: transcodingProfile?.AudioCodec, playSessionId: Date.now(), - startTimeTicks: 0, + startTimeTicks, enableRemoteMedia: false, enableAudioVbrEncoding: true, }; diff --git a/src/utils/store/remoteControl.ts b/src/utils/store/remoteControl.ts index 8cdfdc7..3fb7cd3 100644 --- a/src/utils/store/remoteControl.ts +++ b/src/utils/store/remoteControl.ts @@ -1,19 +1,36 @@ import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client"; import { create } from "zustand"; +export type RemoteTransfer = { + /** Item to offer for "Play on..." / "Transfer here". */ + item?: BaseItemDto | null; + /** Where the transfer starts from (used when moving local playback). */ + kind?: "audio" | "video" | "item"; + positionTicks?: number; + queue?: BaseItemDto[]; + startIndex?: number; +}; + type RemoteControlState = { open: boolean; - /** Item to offer for "Play on ..." when the dialog is opened from a player. */ - item: BaseItemDto | null; - openDialog: (item?: BaseItemDto | null) => void; + transfer: RemoteTransfer | null; + openDialog: (arg?: BaseItemDto | RemoteTransfer | null) => void; closeDialog: () => void; }; +const toTransfer = ( + arg?: BaseItemDto | RemoteTransfer | null, +): RemoteTransfer | null => { + if (!arg) return null; + if ("Type" in arg) return { item: arg as BaseItemDto }; + return arg as RemoteTransfer; +}; + const useRemoteControlStore = create((set) => ({ open: false, - item: null, - openDialog: (item = null) => set({ open: true, item: item ?? null }), - closeDialog: () => set({ open: false, item: null }), + transfer: null, + openDialog: (arg = null) => set({ open: true, transfer: toTransfer(arg) }), + closeDialog: () => set({ open: false, transfer: null }), })); export default useRemoteControlStore;