From 4bdd0139bf55e51e0a5d013ddd9580db67038c5f Mon Sep 17 00:00:00 2001 From: 1xDed Date: Sat, 28 Nov 2026 00:31:03 +0300 Subject: [PATCH] feat(playback): keep transfer position and sync devices Transfers now start the current item first in the queue and send a corrective Seek for clients that ignore StartPositionTicks. Adds a Sync playback mode that keeps other sessions playing the same item aligned with the active device. --- src/components/playback/PlaybackSync.tsx | 210 ++++++++++++++++++ .../audioPlayer/components/DeviceMenu.tsx | 34 +++ src/components/playback/audioPlayer/index.tsx | 65 +++++- .../playback/videoPlayer/settingsMenu.tsx | 32 +++ src/components/remoteControl/index.tsx | 18 +- src/routes/__root.tsx | 2 + src/utils/methods/transferPlayback.ts | 91 ++++++++ src/utils/store/syncPlayback.ts | 28 +++ 8 files changed, 461 insertions(+), 19 deletions(-) create mode 100644 src/components/playback/PlaybackSync.tsx create mode 100644 src/utils/store/syncPlayback.ts diff --git a/src/components/playback/PlaybackSync.tsx b/src/components/playback/PlaybackSync.tsx new file mode 100644 index 0000000..332c4bc --- /dev/null +++ b/src/components/playback/PlaybackSync.tsx @@ -0,0 +1,210 @@ +import { + PlaystateCommand, + type SessionInfoDto, +} from "@jellyfin/sdk/lib/generated-client"; +import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api"; +import { useEffect, useRef } from "react"; +import { secToTicks } from "@/utils/date/time"; +import { useApiInContext } from "@/utils/store/api"; +import { useAudioPlayback } from "@/utils/store/audioPlayback"; +import { useCentralStore } from "@/utils/store/central"; +import { usePlaybackStore } from "@/utils/store/playback"; +import useSyncPlayback from "@/utils/store/syncPlayback"; + +const TICKS_PER_SECOND = 10_000_000; +/** How far a device may drift before we send a correcting seek. */ +const DRIFT_TOLERANCE = 2 * TICKS_PER_SECOND; +/** Do not hammer a device that is still catching up. */ +const SEEK_COOLDOWN_MS = 5000; +const TICK_MS = 2000; + +/** Session reports are a few seconds old; extrapolate the live position. */ +const estimateSessionPosition = (session: SessionInfoDto) => { + const paused = Boolean(session.PlayState?.IsPaused); + const base = session.PlayState?.PositionTicks ?? 0; + const lastCheckIn = session.LastPlaybackCheckIn + ? Date.parse(session.LastPlaybackCheckIn) + : Number.NaN; + const elapsed = !paused && Number.isFinite(lastCheckIn) + ? Math.max(0, Date.now() - lastCheckIn) + : 0; + // 1 ms = 10 000 Jellyfin ticks. + return { position: base + elapsed * 10_000, paused }; +}; + +const getLocalState = () => { + const video = usePlaybackStore.getState(); + if (video.metadata.item?.Id && video.playerState.isPlayerReady) { + return { + active: true, + itemId: video.metadata.item.Id, + position: secToTicks(video.getCurrentTime()), + paused: !video.playerState.isPlayerPlaying, + }; + } + + const audio = useAudioPlayback.getState(); + if (audio.display && audio.item?.Id) { + const element = audio.player.ref?.current; + return { + active: true, + itemId: audio.item.Id, + position: element + ? secToTicks(element.currentTime) + : audio.player.currentTick, + paused: !audio.player.playing, + }; + } + + return { active: false, itemId: null as string | null, position: 0, paused: false }; +}; + +/** + * Keeps other Jellyfin sessions aligned with the sync master. This is a + * pragmatic seek-based sync (works with any client that accepts remote + * commands), not Jellyfin SyncPlay: expect sub-second to ~2 s accuracy plus + * the target clients' own buffering. + */ +const PlaybackSync = () => { + const enabled = useSyncPlayback((state) => state.enabled); + const master = useSyncPlayback((state) => state.master); + const stop = useSyncPlayback((state) => state.stop); + const api = useApiInContext((state) => state.api); + const user = useCentralStore((state) => state.currentUser); + const lastSeek = useRef>({}); + const lastPauseCommand = useRef>({}); + const misses = useRef(0); + + useEffect(() => { + if (!enabled || !master || !api || !user?.Id) return; + const userId = user.Id; + const sessionApi = getSessionApi(api); + let cancelled = false; + let busy = false; + + const tick = async () => { + if (busy || cancelled) return; + busy = true; + try { + const sessions = (await sessionApi.getSessions()).data; + let position = 0; + let paused = false; + let masterFound = false; + // The master may move on to the next queue item; follow it. + let itemId = master.itemId; + + if (master.sessionId) { + const session = sessions.find( + (entry) => entry.Id === master.sessionId, + ); + if (session?.NowPlayingItem?.Id) { + itemId = session.NowPlayingItem.Id; + const estimated = estimateSessionPosition(session); + position = estimated.position; + paused = estimated.paused; + masterFound = true; + } + } else { + const local = getLocalState(); + if (local.active && local.itemId) { + itemId = local.itemId; + position = local.position; + paused = local.paused; + masterFound = true; + } + } + + if (!masterFound) { + misses.current += 1; + if (misses.current >= 3) stop(); + return; + } + misses.current = 0; + + const followers = sessions.filter( + (session) => + session.Id && + session.Id !== master.sessionId && + session.UserId === userId && + session.DeviceId !== api.deviceInfo.id && + session.NowPlayingItem?.Id === itemId, + ); + + for (const follower of followers) { + if (!follower.Id) continue; + const playState = follower.PlayState; + const followerPaused = Boolean(playState?.IsPaused); + + if (followerPaused !== paused) { + const now = Date.now(); + if ( + !lastPauseCommand.current[follower.Id] || + now - lastPauseCommand.current[follower.Id] > SEEK_COOLDOWN_MS + ) { + lastPauseCommand.current[follower.Id] = now; + try { + await sessionApi.sendPlaystateCommand({ + sessionId: follower.Id, + command: paused + ? PlaystateCommand.Pause + : PlaystateCommand.Unpause, + controllingUserId: userId, + }); + } catch (error) { + console.warn("Sync pause command failed", error); + } + } + continue; + } + + if (playState?.CanSeek === false) continue; + const estimated = estimateSessionPosition(follower); + if (Math.abs(estimated.position - position) <= DRIFT_TOLERANCE) { + continue; + } + + const now = Date.now(); + if ( + lastSeek.current[follower.Id] && + now - lastSeek.current[follower.Id] < SEEK_COOLDOWN_MS + ) { + continue; + } + lastSeek.current[follower.Id] = now; + + try { + await sessionApi.sendPlaystateCommand({ + sessionId: follower.Id, + command: PlaystateCommand.Seek, + seekPositionTicks: Math.max( + 0, + Math.round( + position + + (paused ? 0 : 0.3 * TICKS_PER_SECOND), + ), + ), + controllingUserId: userId, + }); + } catch (error) { + console.warn("Sync seek failed", error); + } + } + } catch (error) { + console.warn("Playback sync tick failed", error); + } finally { + busy = false; + } + }; + + tick(); + const timer = window.setInterval(tick, TICK_MS); + return () => { + cancelled = true; + window.clearInterval(timer); + }; + }, [enabled, master, api, user?.Id, stop]); + + return null; +}; + +export default PlaybackSync; diff --git a/src/components/playback/audioPlayer/components/DeviceMenu.tsx b/src/components/playback/audioPlayer/components/DeviceMenu.tsx index a88136f..a96b7ce 100644 --- a/src/components/playback/audioPlayer/components/DeviceMenu.tsx +++ b/src/components/playback/audioPlayer/components/DeviceMenu.tsx @@ -7,6 +7,7 @@ import { ListItemText, Menu, MenuItem, + Switch, Tooltip, } from "@mui/material"; import React, { useState } from "react"; @@ -19,6 +20,9 @@ type DeviceMenuProps = { onSelectLocal: () => void; onSelectRemote: (session: SessionInfoDto) => void; onOpenRemoteControl: () => void; + syncEnabled?: boolean; + canSync?: boolean; + onToggleSync?: () => void; }; const DeviceMenu = ({ @@ -29,6 +33,9 @@ const DeviceMenu = ({ onSelectLocal, onSelectRemote, onOpenRemoteControl, + syncEnabled = false, + canSync = false, + onToggleSync, }: DeviceMenuProps) => { const [anchor, setAnchor] = useState(null); @@ -110,6 +117,33 @@ const DeviceMenu = ({ + + { + event.preventDefault(); + onToggleSync?.(); + }} + > + + sync + + + event.stopPropagation()} + onChange={() => onToggleSync?.()} + /> + ); diff --git a/src/components/playback/audioPlayer/index.tsx b/src/components/playback/audioPlayer/index.tsx index 0a2dc2c..c7e0414 100644 --- a/src/components/playback/audioPlayer/index.tsx +++ b/src/components/playback/audioPlayer/index.tsx @@ -25,7 +25,11 @@ import QueueButton from "@/components/buttons/queueButton"; import { secToTicks, ticksToSec } from "@/utils/date/time"; import getImageUrlsApi from "@/utils/methods/getImageUrlsApi"; import { startInstantMix } from "@/utils/methods/instantMix"; -import { transferSessionToLocal } from "@/utils/methods/transferPlayback"; +import { + playOnSession, + queueStartingWith, + transferSessionToLocal, +} from "@/utils/methods/transferPlayback"; import { useApiInContext } from "@/utils/store/api"; import { setAudioRef, @@ -42,6 +46,7 @@ import useQueue, { shuffleUpcoming, } from "@/utils/store/queue"; import useRemoteControlStore from "@/utils/store/remoteControl"; +import useSyncPlayback from "@/utils/store/syncPlayback"; import DeviceMenu from "./components/DeviceMenu"; import PlayerProgress from "./components/PlayerProgress"; @@ -157,6 +162,25 @@ const AudioPlayer = () => { const displayDuration = activeItem?.RunTimeTicks ?? 1; const barVisible = (display && item) || Boolean(remote); + const syncEnabled = useSyncPlayback((state) => state.enabled); + const syncMaster = useSyncPlayback((state) => state.master); + const startSync = useSyncPlayback((state) => state.start); + const stopSync = useSyncPlayback((state) => state.stop); + const canSync = Boolean(activeItem?.Id) && (display || Boolean(remote)); + const syncForThisSession = + syncEnabled && + (remote?.Id + ? syncMaster?.sessionId === remote.Id + : display && syncMaster?.sessionId === null); + const toggleSync = () => { + if (syncForThisSession) { + stopSync(); + return; + } + if (!activeItem?.Id) return; + startSync({ itemId: activeItem.Id, sessionId: remote?.Id ?? null }); + }; + useEffect(() => { if (display) setSelectedRemoteId(null); }, [display, item?.Id]); @@ -360,19 +384,39 @@ const AudioPlayer = () => { // Moving local playback: send the queue/position to the target first. if (display && item?.Id && api && user?.Id) { const queue = useQueue.getState(); - const ids = - queue.tracks - ?.map((track) => track.Id) - .filter((id): id is string => Boolean(id)) ?? []; - await getSessionApi(api).play({ - sessionId: session.Id, - playCommand: "PlayNow", + const ids = queueStartingWith(queue.tracks ?? [], item.Id); + await playOnSession(api, user.Id, session.Id, { itemIds: ids.length > 0 ? ids : [item.Id], - startIndex: queue.currentItemIndex, + startIndex: 0, startPositionTicks: progress, mediaSourceId: item.MediaSources?.[0]?.Id ?? undefined, }); stopPlayback(); + } else if ( + remote?.Id && + remote.Id !== session.Id && + remote.NowPlayingItem?.Id && + api && + user?.Id + ) { + // Moving playback from one remote device to another: hand over the + // queue and current position, then stop the old device. + const remoteItem = remote.NowPlayingItem; + const queueIds = queueStartingWith( + remote.NowPlayingQueue ?? [], + remoteItem.Id ?? undefined, + ); + await playOnSession(api, user.Id, session.Id, { + itemIds: queueIds.length > 0 ? queueIds : [remoteItem.Id as string], + startIndex: 0, + startPositionTicks: remote.PlayState?.PositionTicks ?? 0, + mediaSourceId: remoteItem.MediaSources?.[0]?.Id ?? undefined, + }); + await getSessionApi(api).sendPlaystateCommand({ + sessionId: remote.Id, + command: "Stop", + controllingUserId: user.Id, + }); } setSelectedRemoteId(session.Id); await sessions.refetch(); @@ -658,6 +702,9 @@ const AudioPlayer = () => { onSelectLocal={transferToLocal} onSelectRemote={selectRemote} onOpenRemoteControl={() => openRemoteDialog()} + syncEnabled={syncForThisSession} + canSync={canSync} + onToggleSync={toggleSync} /> diff --git a/src/components/playback/videoPlayer/settingsMenu.tsx b/src/components/playback/videoPlayer/settingsMenu.tsx index 18fec06..3f680a1 100644 --- a/src/components/playback/videoPlayer/settingsMenu.tsx +++ b/src/components/playback/videoPlayer/settingsMenu.tsx @@ -20,6 +20,7 @@ import { changeSubtitleTrack, usePlaybackStore, } from "@/utils/store/playback"; +import useSyncPlayback from "@/utils/store/syncPlayback"; type VideoPlayerSettingsMenuProps = { settingsMenuRef: HTMLButtonElement | null; @@ -41,15 +42,31 @@ const VideoPlayerSettingsMenu = ({ setIsBuffering, showStatsForNerds, toggleShowStatsForNerds, + itemId, } = usePlaybackStore( useShallow((state) => ({ mediaSource: state.mediaSource, setIsBuffering: state.setIsBuffering, showStatsForNerds: state.playerState.showStatsForNerds, toggleShowStatsForNerds: state.toggleShowStatsForNerds, + itemId: state.metadata.item?.Id, })), ); + const syncEnabled = useSyncPlayback((state) => state.enabled); + const syncMaster = useSyncPlayback((state) => state.master); + const startSync = useSyncPlayback((state) => state.start); + const stopSync = useSyncPlayback((state) => state.stop); + const syncForThisVideo = + syncEnabled && syncMaster?.sessionId === null && Boolean(itemId); + const toggleSync = () => { + if (syncForThisVideo) { + stopSync(); + return; + } + if (itemId) startSync({ itemId, sessionId: null }); + }; + const [subtitleIsChanging, startSubtitleChange] = useTransition(); const handleSubtitleChange: ChangeEventHandler< HTMLInputElement | HTMLTextAreaElement @@ -156,6 +173,21 @@ const VideoPlayerSettingsMenu = ({ + + + Sync playback + + event.stopPropagation()} + onChange={toggleSync} + /> + ); diff --git a/src/components/remoteControl/index.tsx b/src/components/remoteControl/index.tsx index c167bad..6488bc3 100644 --- a/src/components/remoteControl/index.tsx +++ b/src/components/remoteControl/index.tsx @@ -1,5 +1,4 @@ import { - PlayCommand, PlaystateCommand, type SessionInfoDto, } from "@jellyfin/sdk/lib/generated-client"; @@ -23,6 +22,10 @@ import { useMutation, useQuery } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; import { useSnackbar } from "notistack"; import React from "react"; +import { + playOnSession, + queueStartingWith, +} from "@/utils/methods/transferPlayback"; import { useApiInContext } from "@/utils/store/api"; import { stopPlayback } from "@/utils/store/audioPlayback"; import { useCentralStore } from "@/utils/store/central"; @@ -90,16 +93,11 @@ 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, + if (!api || !session.Id || !item?.Id || !user?.Id) return; + const queueIds = queueStartingWith(transfer?.queue ?? [], item.Id); + await playOnSession(api, user.Id, session.Id, { itemIds: queueIds.length > 0 ? queueIds : [item.Id], - startIndex: transfer?.startIndex ?? 0, + startIndex: 0, startPositionTicks: transfer?.positionTicks ?? 0, mediaSourceId: item.MediaSources?.[0]?.Id ?? undefined, }); diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 82a1d04..d9a9515 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -25,6 +25,7 @@ import { HTML5Backend } from "react-dnd-html5-backend"; import Backdrop from "@/components/backdrop"; import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice"; import OverlayScrollbar from "@/components/overlayScrollbar"; +import PlaybackSync from "@/components/playback/PlaybackSync"; import RemoteControlDialog from "@/components/remoteControl"; import RouterLoading from "@/components/routerLoading"; import Search from "@/components/search"; @@ -58,6 +59,7 @@ export const Route = createRootRouteWithContext()({ + diff --git a/src/utils/methods/transferPlayback.ts b/src/utils/methods/transferPlayback.ts index 8141039..031bee0 100644 --- a/src/utils/methods/transferPlayback.ts +++ b/src/utils/methods/transferPlayback.ts @@ -3,6 +3,7 @@ import { type BaseItemDto, BaseItemKind, ItemFields, + PlaystateCommand, type SessionInfoDto, } from "@jellyfin/sdk/lib/generated-client"; import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api"; @@ -20,6 +21,96 @@ const fields = [ ItemFields.Overview, ]; +const TICKS_PER_SECOND = 10_000_000; +const sleep = (ms: number) => + new Promise((resolve) => window.setTimeout(resolve, ms)); + +/** + * Some clients ignore StartIndex as well as StartPositionTicks. Put the + * current item first so a transfer always starts with what is playing now. + */ +export const queueStartingWith = ( + items: Array<{ Id?: string | null }>, + currentItemId: string | undefined, +): string[] => { + const ids = items + .map((item) => item.Id) + .filter((id): id is string => Boolean(id)); + if (!currentItemId) return ids; + const index = ids.indexOf(currentItemId); + if (index <= 0) return ids; + return [...ids.slice(index), ...ids.slice(0, index)]; +}; + +export type PlayOnSessionOptions = { + itemIds: string[]; + startIndex?: number; + startPositionTicks?: number; + mediaSourceId?: string; +}; + +/** + * Start playback on another Jellyfin session and make sure it begins at the + * requested position. Some clients accept the Play command but ignore + * StartPositionTicks, so verify the reported position and send a Seek when + * they started from the beginning. + */ +export const playOnSession = async ( + api: Api, + userId: string, + sessionId: string, + options: PlayOnSessionOptions, +): Promise => { + if (options.itemIds.length === 0) return; + + const sessionApi = getSessionApi(api); + const startPositionTicks = Math.max(0, options.startPositionTicks ?? 0); + + await sessionApi.play({ + sessionId, + playCommand: "PlayNow", + itemIds: options.itemIds, + startIndex: options.startIndex ?? 0, + startPositionTicks, + mediaSourceId: options.mediaSourceId, + }); + + if (startPositionTicks <= 0) return; + + // Give the target a moment to load, then correct it if it ignored the + // start position. Tolerance is generous: buffering can take a few seconds. + for (const delay of [900, 1600, 2600]) { + await sleep(delay); + let target: SessionInfoDto | undefined; + try { + target = (await sessionApi.getSessions()).data.find( + (session) => session.Id === sessionId, + ); + } catch (error) { + console.warn("Could not read the target session position", error); + continue; + } + if (!target?.NowPlayingItem) continue; + + const paused = target.PlayState?.IsPaused ?? false; + const expected = + startPositionTicks + (paused ? 0 : delay * (TICKS_PER_SECOND / 1000)); + const actual = target.PlayState?.PositionTicks ?? 0; + if (Math.abs(actual - expected) <= 8 * TICKS_PER_SECOND) return; + + try { + await sessionApi.sendPlaystateCommand({ + sessionId, + command: PlaystateCommand.Seek, + seekPositionTicks: Math.round(expected), + controllingUserId: userId, + }); + } catch (error) { + console.warn("Could not seek the target session", error); + } + } +}; + /** * Spotify-Connect style transfer: take what another Jellyfin session is * playing (at its current position and with its queue) and play it on this diff --git a/src/utils/store/syncPlayback.ts b/src/utils/store/syncPlayback.ts new file mode 100644 index 0000000..7a7dec3 --- /dev/null +++ b/src/utils/store/syncPlayback.ts @@ -0,0 +1,28 @@ +import { create } from "zustand"; + +export type SyncMaster = { + /** Item that all devices should be playing together. */ + itemId: string; + /** Remote session acting as the clock; null means this device. */ + sessionId: string | null; +}; + +type SyncPlaybackState = { + enabled: boolean; + master: SyncMaster | null; + start: (master: SyncMaster) => void; + stop: () => void; +}; + +/** + * Approximate multi-device sync: the master position is periodically pushed + * to every other controllable session playing the same item. + */ +const useSyncPlayback = create((set) => ({ + enabled: false, + master: null, + start: (master) => set({ enabled: true, master }), + stop: () => set({ enabled: false, master: null }), +})); + +export default useSyncPlayback;