Skip to content

Commit 5d10783

Browse files
authored
Persist video playback speed preference (block#7336)
## Summary - persist the selected desktop video playback speed as a device-level preference - apply the shared preference to inline and review video players, including after a reload - cover persistence, validation, cross-window updates, and the end-to-end playback flow ## Verification - `node --test desktop/src/shared/lib/videoPlaybackSpeedPreference.test.mjs` - `cd desktop && pnpm exec tsc --noEmit` - `cd desktop && pnpm check:px-text` - `cd desktop && pnpm test` - `cd desktop && pnpm build:e2e && pnpm exec playwright test --project=smoke video-attachment.spec.ts` - pre-push: desktop check, file-size check, typecheck, and 6,416 desktop tests --------- Signed-off-by: morgmart <[email protected]>
1 parent e09f715 commit 5d10783

4 files changed

Lines changed: 291 additions & 13 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
const values = new Map();
5+
const windowListeners = new Map();
6+
7+
globalThis.window = {
8+
addEventListener: (type, listener) => windowListeners.set(type, listener),
9+
};
10+
globalThis.localStorage = {
11+
getItem: (key) => values.get(key) ?? null,
12+
setItem: (key, value) => values.set(key, String(value)),
13+
};
14+
15+
values.set("buzz.media.videoPlaybackSpeed", "2");
16+
17+
const preference = await import("./videoPlaybackSpeedPreference.ts");
18+
19+
test("reads the persisted speed as the starting preference", () => {
20+
assert.equal(preference.getVideoPlaybackSpeed(), 2);
21+
});
22+
23+
test("defaults missing and unsupported speeds to 1x", () => {
24+
assert.equal(preference.parseVideoPlaybackSpeed(null), 1);
25+
assert.equal(preference.parseVideoPlaybackSpeed("3"), 1);
26+
assert.equal(preference.parseVideoPlaybackSpeed("fast"), 1);
27+
assert.equal(preference.parseVideoPlaybackSpeed("1.5"), 1.5);
28+
});
29+
30+
test("persists a newly selected speed for later players", () => {
31+
preference.setVideoPlaybackSpeed(1.5);
32+
assert.equal(preference.getVideoPlaybackSpeed(), 1.5);
33+
assert.equal(values.get(preference.VIDEO_PLAYBACK_SPEED_STORAGE_KEY), "1.5");
34+
});
35+
36+
test("ignores speeds the control cannot display", () => {
37+
preference.setVideoPlaybackSpeed(1.5);
38+
preference.setVideoPlaybackSpeed(3);
39+
assert.equal(preference.getVideoPlaybackSpeed(), 1.5);
40+
assert.equal(values.get(preference.VIDEO_PLAYBACK_SPEED_STORAGE_KEY), "1.5");
41+
});
42+
43+
test("notifies subscribers when the speed changes", () => {
44+
let notifications = 0;
45+
const unsubscribe = preference.subscribeToVideoPlaybackSpeed(() => {
46+
notifications += 1;
47+
});
48+
49+
preference.setVideoPlaybackSpeed(2);
50+
assert.equal(notifications, 1);
51+
52+
// Re-selecting the same speed is not a change.
53+
preference.setVideoPlaybackSpeed(2);
54+
assert.equal(notifications, 1);
55+
56+
unsubscribe();
57+
preference.setVideoPlaybackSpeed(1);
58+
assert.equal(notifications, 1);
59+
});
60+
61+
test("notifies mounted consumers when another window changes the speed", () => {
62+
preference.setVideoPlaybackSpeed(1);
63+
let notifications = 0;
64+
const unsubscribe = preference.subscribeToVideoPlaybackSpeed(() => {
65+
notifications += 1;
66+
});
67+
68+
values.set("buzz.media.videoPlaybackSpeed", "0.5");
69+
windowListeners.get("storage")({ key: "buzz.media.videoPlaybackSpeed" });
70+
assert.equal(preference.getVideoPlaybackSpeed(), 0.5);
71+
assert.equal(notifications, 1);
72+
73+
// A redundant storage event must not needlessly re-render every player.
74+
windowListeners.get("storage")({ key: "buzz.media.videoPlaybackSpeed" });
75+
assert.equal(notifications, 1);
76+
unsubscribe();
77+
});
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import * as React from "react";
2+
3+
/**
4+
* Device-level video playback speed. Selecting a speed in any video player
5+
* persists it as the preference every later player starts from, so a viewer
6+
* who watches at 2x does not have to re-select it per video.
7+
*/
8+
export const VIDEO_PLAYBACK_SPEED_STORAGE_KEY = "buzz.media.videoPlaybackSpeed";
9+
10+
/** Selectable speeds, fastest first to match the control's menu order. */
11+
export const VIDEO_PLAYBACK_SPEEDS = [
12+
2, 1.75, 1.5, 1.25, 1, 0.75, 0.5, 0.25,
13+
] as const;
14+
15+
/** Playback speed used when no valid saved preference exists. */
16+
export const DEFAULT_VIDEO_PLAYBACK_SPEED = 1;
17+
18+
const listeners = new Set<() => void>();
19+
let videoPlaybackSpeed: number | null = null;
20+
let listeningForStorageChanges = false;
21+
22+
/** True for speeds the control can actually represent. */
23+
export function isVideoPlaybackSpeed(speed: number): boolean {
24+
return VIDEO_PLAYBACK_SPEEDS.some((option) => option === speed);
25+
}
26+
27+
/** Parse a stored value, falling back when it is missing or unsupported. */
28+
export function parseVideoPlaybackSpeed(
29+
value: string | null | undefined,
30+
): number {
31+
const parsed = Number(value);
32+
return Number.isFinite(parsed) && isVideoPlaybackSpeed(parsed)
33+
? parsed
34+
: DEFAULT_VIDEO_PLAYBACK_SPEED;
35+
}
36+
37+
function readStoredVideoPlaybackSpeed(): number {
38+
try {
39+
return parseVideoPlaybackSpeed(
40+
globalThis.localStorage?.getItem(VIDEO_PLAYBACK_SPEED_STORAGE_KEY),
41+
);
42+
} catch {
43+
return DEFAULT_VIDEO_PLAYBACK_SPEED;
44+
}
45+
}
46+
47+
function notifyListeners(): void {
48+
for (const listener of listeners) listener();
49+
}
50+
51+
function listenForStorageChanges(): void {
52+
if (listeningForStorageChanges || !globalThis.window?.addEventListener) {
53+
return;
54+
}
55+
globalThis.window.addEventListener("storage", (event) => {
56+
if (event.key === VIDEO_PLAYBACK_SPEED_STORAGE_KEY || event.key === null) {
57+
const nextSpeed = readStoredVideoPlaybackSpeed();
58+
if (nextSpeed === videoPlaybackSpeed) return;
59+
videoPlaybackSpeed = nextSpeed;
60+
notifyListeners();
61+
}
62+
});
63+
listeningForStorageChanges = true;
64+
}
65+
66+
/**
67+
* Subscribe to playback-speed changes, including changes made in another
68+
* window. Returns an unsubscribe function.
69+
*/
70+
export function subscribeToVideoPlaybackSpeed(
71+
listener: () => void,
72+
): () => void {
73+
listeners.add(listener);
74+
listenForStorageChanges();
75+
return () => {
76+
listeners.delete(listener);
77+
};
78+
}
79+
80+
/** Return the current device-level playback-speed preference. */
81+
export function getVideoPlaybackSpeed(): number {
82+
listenForStorageChanges();
83+
if (videoPlaybackSpeed === null) {
84+
videoPlaybackSpeed = readStoredVideoPlaybackSpeed();
85+
}
86+
return videoPlaybackSpeed;
87+
}
88+
89+
/**
90+
* Persist the viewer's chosen speed and apply it to every mounted player.
91+
* Unsupported values are ignored so a stale caller cannot strand the control
92+
* on a speed it cannot display.
93+
*/
94+
export function setVideoPlaybackSpeed(speed: number): void {
95+
if (!isVideoPlaybackSpeed(speed)) return;
96+
const changed = getVideoPlaybackSpeed() !== speed;
97+
videoPlaybackSpeed = speed;
98+
try {
99+
globalThis.localStorage?.setItem(
100+
VIDEO_PLAYBACK_SPEED_STORAGE_KEY,
101+
String(speed),
102+
);
103+
} catch {
104+
// Persistence is best-effort; the live preference still applies.
105+
}
106+
if (changed) notifyListeners();
107+
}
108+
109+
/** Subscribe a player to the shared, persisted playback speed. */
110+
export function useVideoPlaybackSpeed(): number {
111+
return React.useSyncExternalStore(
112+
subscribeToVideoPlaybackSpeed,
113+
getVideoPlaybackSpeed,
114+
() => DEFAULT_VIDEO_PLAYBACK_SPEED,
115+
);
116+
}

‎desktop/src/shared/ui/VideoPlayer.tsx‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ import { MessageComposer } from "@/features/messages/ui/MessageComposer";
1818
import type { UserProfileLookup } from "@/features/profile/lib/identity";
1919
import type { ChannelType } from "@/shared/api/types";
2020
import { cn } from "@/shared/lib/cn";
21+
import {
22+
setVideoPlaybackSpeed,
23+
useVideoPlaybackSpeed,
24+
VIDEO_PLAYBACK_SPEEDS,
25+
} from "@/shared/lib/videoPlaybackSpeedPreference";
2126
import { Button } from "@/shared/ui/button";
2227
import { Checkbox } from "@/shared/ui/checkbox";
2328
import { MODAL_BACKDROP_BLUR_CLASS } from "@/shared/ui/modalBackdrop";
@@ -112,9 +117,8 @@ type TimecodedComment = {
112117
text: string;
113118
};
114119
const QUICK_REACTIONS = ["😂", "😍", "😮", "🙌", "👍", "👎"];
115-
const DEFAULT_PLAYBACK_SPEED = 1;
116120
const INLINE_SPEED_CONTROL_MIN_WIDTH = 220;
117-
const PLAYBACK_SPEEDS = [2, 1.75, 1.5, 1.25, 1, 0.75, 0.5, 0.25];
121+
const PLAYBACK_SPEEDS = VIDEO_PLAYBACK_SPEEDS;
118122

119123
/**
120124
* Frosted-glass backing layer for floating media controls. The parent must
@@ -180,10 +184,6 @@ function formatPlaybackSpeed(speed: number): string {
180184
return `${speed}x`;
181185
}
182186

183-
function isPlaybackSpeedOption(speed: number): boolean {
184-
return PLAYBACK_SPEEDS.some((option) => option === speed);
185-
}
186-
187187
function parseTimecodedComment(comment: VideoReviewComment): TimecodedComment {
188188
const parsed = parseVideoReviewTimecode(comment.body);
189189
return parsed
@@ -697,9 +697,9 @@ export function VideoPlayer({
697697
const [duration, setDuration] = React.useState(durationSeconds ?? 0);
698698
const [volume, setVolume] = React.useState(1);
699699
const [muted, setMuted] = React.useState(false);
700-
const [playbackSpeed, setPlaybackSpeed] = React.useState(
701-
DEFAULT_PLAYBACK_SPEED,
702-
);
700+
// Device-level preference, not per-player state: a speed chosen here is the
701+
// speed every later video starts at.
702+
const playbackSpeed = useVideoPlaybackSpeed();
703703
// Cache-seeded so a row evicted by the virtualized timeline remounts at the
704704
// ratio learned on first metadata load, not the 16/9 fallback.
705705
const [naturalAspectRatio, learnNaturalAspectRatio] =
@@ -738,7 +738,6 @@ export function VideoPlayer({
738738
setIsPlaying(false);
739739
setIsBuffering(false);
740740
setHasError(false);
741-
setPlaybackSpeed(DEFAULT_PLAYBACK_SPEED);
742741
setReviewOpenState(isVideoReviewOpen(persistedReviewKey));
743742
setReviewCurrentTimeState(
744743
getReviewPlaybackPosition(persistedReviewKey) ?? 0,
@@ -829,9 +828,7 @@ export function VideoPlayer({
829828
return () => observer.disconnect();
830829
}, []);
831830
const handlePlaybackSpeedChange = React.useCallback((speed: number) => {
832-
if (isPlaybackSpeedOption(speed)) {
833-
setPlaybackSpeed(speed);
834-
}
831+
setVideoPlaybackSpeed(speed);
835832
}, []);
836833

837834
useSmoothPlaybackTime(videoRef, isPlaying && !reviewOpen, setCurrentTime);

‎desktop/tests/e2e/video-attachment.spec.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1579,3 +1579,91 @@ test("right-click menus expose distinct selectors for links, relay video, and of
15791579
offRelayMenu.getByRole("button", { name: "Download video" }),
15801580
).toHaveCount(0);
15811581
});
1582+
1583+
test("playback speed persists across videos and reloads", async ({ page }) => {
1584+
await installVideoReviewHarness(page);
1585+
1586+
const openGeneralWithVideo = async (
1587+
url: string,
1588+
sha: string,
1589+
filename: string,
1590+
) => {
1591+
await page.getByTestId("channel-general").click();
1592+
await expect(page.getByTestId("chat-title")).toHaveText("general");
1593+
await waitForMockLiveSubscription(page, "general");
1594+
const emitted = (await emitMockMessage(
1595+
page,
1596+
"general",
1597+
`![video](${url})`,
1598+
{
1599+
extraTags: [
1600+
[
1601+
"imeta",
1602+
`url ${url}`,
1603+
"m video/mp4",
1604+
`x ${sha}`,
1605+
"size 987654",
1606+
"dim 160x80",
1607+
"duration 12.5",
1608+
`image ${POSTER_DATA_URL}`,
1609+
`filename ${filename}`,
1610+
],
1611+
],
1612+
},
1613+
)) as { id: string };
1614+
const player = page
1615+
.locator(`[data-message-id="${emitted.id}"]`)
1616+
.getByTestId("video-player");
1617+
await expect(player).toBeVisible();
1618+
await player.getByRole("button", { name: "Play video" }).click();
1619+
return player;
1620+
};
1621+
1622+
await page.goto("/");
1623+
const firstPlayer = await openGeneralWithVideo(
1624+
VIDEO_URL,
1625+
VIDEO_SHA,
1626+
"launch-demo.mp4",
1627+
);
1628+
const firstSpeedButton = firstPlayer.getByTestId("video-inline-speed");
1629+
await expect(firstSpeedButton).toHaveText("1x");
1630+
await firstSpeedButton.click();
1631+
await page
1632+
.getByTestId("video-inline-speed-menu")
1633+
.getByRole("button", { name: "2x", exact: true })
1634+
.click();
1635+
await expect(firstSpeedButton).toHaveText("2x");
1636+
1637+
// A different video in the same session starts at the chosen speed.
1638+
const secondPlayer = await openGeneralWithVideo(
1639+
MENU_RELAY_VIDEO_URL,
1640+
MENU_RELAY_VIDEO_SHA,
1641+
"second-demo.mp4",
1642+
);
1643+
const secondVideo = secondPlayer.locator("video");
1644+
await expect(secondPlayer.getByTestId("video-inline-speed")).toHaveText("2x");
1645+
await expect
1646+
.poll(() =>
1647+
secondVideo.evaluate((video) => (video as HTMLVideoElement).playbackRate),
1648+
)
1649+
.toBe(2);
1650+
1651+
// And the preference survives an app restart.
1652+
await page.reload();
1653+
const reloadedPlayer = await openGeneralWithVideo(
1654+
VIDEO_URL,
1655+
VIDEO_SHA,
1656+
"launch-demo.mp4",
1657+
);
1658+
const reloadedVideo = reloadedPlayer.locator("video");
1659+
await expect(reloadedPlayer.getByTestId("video-inline-speed")).toHaveText(
1660+
"2x",
1661+
);
1662+
await expect
1663+
.poll(() =>
1664+
reloadedVideo.evaluate(
1665+
(video) => (video as HTMLVideoElement).playbackRate,
1666+
),
1667+
)
1668+
.toBe(2);
1669+
});

0 commit comments

Comments
 (0)