feat(playback): keep transfer position and sync devices
Continuous Integration / build_web (push) Failing after 0s
Continuous Integration / build (macos-latest) (push) Skipped
Continuous Integration / build (ubuntu-22.04) (push) Skipped
Continuous Integration / build (windows-11-arm) (push) Skipped
Continuous Integration / build (windows-latest) (push) Skipped
Continuous Integration / nightly_release (push) Skipped

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.
This commit is contained in:
1xDed committed 2026-11-28 00:31:03 +03:00
1 parent df392eb647
commit 4bdd0139bf
8 files changed
+461 -19

No files matched your search

+210
View File
@@ -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<Record<string, number>>({});
const lastPauseCommand = useRef<Record<string, number>>({});
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;
@@ -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<HTMLElement | null>(null);
@@ -110,6 +117,33 @@ const DeviceMenu = ({
</ListItemIcon>
<ListItemText primary="Remote control…" />
</MenuItem>
<Divider />
<MenuItem
disabled={!canSync}
onClick={(event) => {
event.preventDefault();
onToggleSync?.();
}}
>
<ListItemIcon>
<span className="material-symbols-rounded">sync</span>
</ListItemIcon>
<ListItemText
primary="Sync playback"
secondary={
syncEnabled
? "Devices follow this session"
: "Keep devices in step"
}
/>
<Switch
edge="end"
checked={syncEnabled}
disabled={!canSync}
onClick={(event) => event.stopPropagation()}
onChange={() => onToggleSync?.()}
/>
</MenuItem>
</Menu>
</>
);
+56 -9
View File
@@ -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}
/>
<Tooltip title="Open player">
<IconButton size="small" onClick={handleNavigate}>
@@ -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 = ({
</Typography>
<Switch checked={showStatsForNerds} />
</MenuItem>
<MenuItem onClick={toggleSync} disabled={!itemId}>
<Typography
sx={{
flexGrow: 1,
}}
>
Sync playback
</Typography>
<Switch
checked={syncForThisVideo}
disabled={!itemId}
onClick={(event) => event.stopPropagation()}
onChange={toggleSync}
/>
</MenuItem>
</MenuList>
</Popover>
);
+8 -10
View File
@@ -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,
});
+2
View File
@@ -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<ApiContext>()({
<RemoteControlDialog />
<AppBar />
<AudioPlayer />
<PlaybackSync />
<OverlayScrollbar />
<Outlet />
</SnackbarProvider>
+91
View File
@@ -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<void>((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<void> => {
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
+28
View File
@@ -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<SyncPlaybackState>((set) => ({
enabled: false,
master: null,
start: (master) => set({ enabled: true, master }),
stop: () => set({ enabled: false, master: null }),
}));
export default useSyncPlayback;