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
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:
1 parent
df392eb647
commit
4bdd0139bf
8 files changed
+461
-19
No files matched your search
@@ -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>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user