Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,27 @@ To avoid re-encoding, keep **Settings → Live recording preset** on **Original

Chaturbate stream extraction uses IPv4 by default to avoid unreachable IPv6 routes in containers. The **Use IPv4 for stream extraction** setting can be disabled on networks requiring IPv6. It applies to yt-dlp's metadata and playlist requests; FFmpeg makes its own connections while capturing. If errors persist, check connectivity from the Open EasyX container and the recording error in Activity.

## Video player gestures and casting

On a phone or tablet the video player supports:

| Gesture | Action |
| --- | --- |
| Tap | show or hide the controls |
| Double tap right / left | skip 10 seconds forward / back (each further quick tap adds 10 seconds) |
| Press and hold on the right | play at 2× while held |
| Pinch with two fingers | zoom in or out (drag with one finger while zoomed; tap the zoom badge to reset) |

With a mouse, a click plays or pauses, a double click toggles fullscreen and holding on the right plays at 2×. The keyboard keeps Space/K, ←/→, M and F.

The cast button sends the video to a TV:

- **Chromecast / Google TV** works in Chrome or Edge when Open EasyX is opened over **HTTPS** (for example through a Synology or Nginx reverse proxy with a certificate); Google only offers its cast API on secure pages. Over plain `http://NAS:3210`, use the browser menu (⋮ → Cast…) to cast the tab.
- **AirPlay** works from Safari on iPhone, iPad and Mac, also over plain HTTP.
- Chrome on Android may also offer its built-in remote playback for the video.

The TV loads the file directly from Open EasyX, so open the app by the NAS address or host name (not `localhost`). Chromecast plays MP4 (H.264/AAC) and WebM; other formats need one of the re-encoding recording presets.

## Local development

Requirements: Node.js 22.5 or newer, Git, FFmpeg, and the downloader helpers used by the plugins you enable.
Expand Down
17 changes: 10 additions & 7 deletions src/Player.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,6 @@ describe("photo player", () => {
});

describe("video player", () => {
it("offers and restores audio amplification up to 300 percent", () => {
vi.stubGlobal("localStorage", { getItem: (key: string) => key === "open-easyx.player-audio-boost" ? "3" : null, setItem: vi.fn() });
const html = renderToStaticMarkup(<PlayerViewer media={video} context={{ ids: ["video-1"] }} close={vi.fn()} favorite={vi.fn()} advance={vi.fn()} setNotice={vi.fn()}/>);
expect(html).toContain('aria-label="Audio boost"');
expect(html).toContain('<option value="3" selected="">Boost 300%</option>');
});

it("asks the browser to autoplay a video reached from the previous item", () => {
vi.stubGlobal("localStorage", { getItem: () => null, setItem: vi.fn() });
const html = renderToStaticMarkup(<PlayerViewer media={video} context={{ ids: ["photo-1", "video-1"] }} autoStart close={vi.fn()} favorite={vi.fn()} advance={vi.fn()} setNotice={vi.fn()}/>);
Expand Down Expand Up @@ -72,3 +65,13 @@ describe("delete from the player", () => {
expect(html).not.toContain("watch-delete");
});
});

describe("video player gestures and casting", () => {
it("renders the gesture surface and a cast button", () => {
vi.stubGlobal("localStorage", { getItem: () => null, setItem: vi.fn() });
const html = renderToStaticMarkup(<PlayerViewer media={video} context={{ ids: ["video-1"] }} close={vi.fn()} favorite={vi.fn()} advance={vi.fn()} setNotice={vi.fn()}/>);
expect(html).toContain('class="player-surface"');
expect(html).toContain('aria-label="Cast to a TV"');
expect(html).not.toContain("player-zoom-reset");
});
});
129 changes: 89 additions & 40 deletions src/Player.tsx

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions src/player-cast.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { chromecastSupported, receiverUrl, unreachableFromTv } from "./player-cast";

const chrome = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36";
const safari = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15";

describe("player casting", () => {
it("offers Chromecast only in Chrome on a secure page", () => {
expect(chromecastSupported({ isSecureContext: true } as never, chrome)).toBe(true);
expect(chromecastSupported({ isSecureContext: false } as never, chrome)).toBe(false);
expect(chromecastSupported({ isSecureContext: true } as never, safari)).toBe(false);
});

it("gives the TV an absolute address it can reach", () => {
expect(receiverUrl("/api/media/abc/stream", "http://192.168.1.20:3210/watch/abc")).toBe("http://192.168.1.20:3210/api/media/abc/stream");
expect(unreachableFromTv("http://192.168.1.20:3210/api/media/abc/stream")).toBe(false);
expect(unreachableFromTv("http://localhost:3210/api/media/abc/stream")).toBe(true);
expect(unreachableFromTv("http://127.0.0.1:3210/x")).toBe(true);
});
});
175 changes: 175 additions & 0 deletions src/player-cast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { useEffect, useRef, useState, type RefObject } from "react";

// Casting from the web player.
//
// - Chromecast / Google TV: the Google Cast Web Sender SDK, loaded on demand. Chrome only
// offers it on a secure page (HTTPS, or localhost), so over plain http://NAS:3210 it is
// not available and the browser's own "Cast…" menu (tab casting) remains the fallback.
// - AirPlay: Safari's own picker for the <video> element; works over plain HTTP.
// - Remote Playback API: Chrome on Android (and other browsers that support it) can send
// the <video> element to a nearby device.
// The receiver fetches the file itself, so the stream URL must be reachable from the TV:
// open Open EasyX by the NAS address or host name, not via localhost.

const CAST_SDK = "https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1";
const SDK_TIMEOUT_MS = 8_000;

type CastMedia = { title: string; performer: string; streamUrl: string; thumbnailUrl: string; mimeType: string; duration: number };
// The Cast SDK has no bundled types; only the members used here are described.
type CastWindow = Window & {
__onGCastApiAvailable?: (available: boolean) => void;
cast?: any; chrome?: any;
WebKitPlaybackTargetAvailabilityEvent?: unknown;
};
type RemoteVideo = HTMLVideoElement & {
remote?: { state: string; prompt: () => Promise<void>; watchAvailability: (callback: (available: boolean) => void) => Promise<number>; cancelWatchAvailability: (id?: number) => Promise<void> };
webkitShowPlaybackTargetPicker?: () => void;
};

let sdk: Promise<boolean> | undefined;

/** Chrome (desktop or Android) on a secure page: the only place the Cast SDK works. */
export function chromecastSupported(win: CastWindow = window as CastWindow, userAgent = navigator.userAgent): boolean {
return Boolean(win.isSecureContext) && /\b(?:Chrome|CriOS|Edg)\//.test(userAgent) && !/\bOPR\//.test(userAgent);
}

export function loadCastSdk(win: CastWindow = window as CastWindow): Promise<boolean> {
if (win.cast?.framework) return Promise.resolve(true);
sdk ??= new Promise<boolean>((resolve) => {
const timer = setTimeout(() => resolve(false), SDK_TIMEOUT_MS);
win.__onGCastApiAvailable = (available) => { clearTimeout(timer); resolve(available && Boolean(win.cast?.framework)); };
const script = document.createElement("script");
script.src = CAST_SDK; script.async = true;
script.onerror = () => { clearTimeout(timer); resolve(false); };
document.head.appendChild(script);
});
return sdk;
}

/** Absolute address of a library URL, as the receiver needs it. */
export function receiverUrl(path: string, base = window.location.href): string {
return new URL(path, base).href;
}

/** A TV cannot reach "localhost" on the computer that opened the page. */
export function unreachableFromTv(url: string): boolean {
try { return ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname); } catch { return true; }
}

export type CastState = {
/** Some cast route exists for this browser and page. */
available: boolean;
/** Playing on a Chromecast; local playback is paused and the controls drive the TV. */
casting: boolean;
device: string;
remoteTime: number; remoteDuration: number; remotePaused: boolean;
start: (localTime: number) => Promise<void>;
stop: () => void;
togglePlay: () => void;
seek: (seconds: number) => void;
};

export function usePlayerCast(video: RefObject<HTMLVideoElement | null>, media: CastMedia, notice: (message: string) => void, resumeLocal: (seconds: number, playing: boolean) => void): CastState {
const [chromecast, setChromecast] = useState(false);
const [airplay, setAirplay] = useState(false);
const [remotePlayback, setRemotePlayback] = useState(false);
const [casting, setCasting] = useState(false);
const [device, setDevice] = useState("");
const [remoteTime, setRemoteTime] = useState(0); const [remoteDuration, setRemoteDuration] = useState(0); const [remotePaused, setRemotePaused] = useState(true);
const remote = useRef<{ player: any; controller: any } | undefined>(undefined);
const last = useRef({ time: 0, paused: true });
const castingNow = useRef(false);
const resume = useRef(resumeLocal); resume.current = resumeLocal;

// Chromecast: load the SDK once on a page where it can work.
useEffect(() => {
const win = window as CastWindow;
if (!chromecastSupported(win)) return;
let active = true;
void loadCastSdk(win).then((ready) => {
if (!ready || !active) return;
const framework = win.cast.framework; const chrome = win.chrome;
const context = framework.CastContext.getInstance();
context.setOptions({ receiverApplicationId: chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID, autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED });
const update = () => setChromecast(context.getCastState() !== framework.CastState.NO_DEVICES_AVAILABLE);
update();
context.addEventListener(framework.CastContextEventType.CAST_STATE_CHANGED, update);
const player = new framework.RemotePlayer(); const controller = new framework.RemotePlayerController(player);
remote.current = { player, controller };
controller.addEventListener(framework.RemotePlayerEventType.ANY_CHANGE, () => {
if (!player.isConnected || !player.isMediaLoaded) {
if (player.isConnected || !castingNow.current) return;
// The session ended: continue locally where the TV stopped.
castingNow.current = false; setCasting(false);
resume.current(last.current.time, !last.current.paused);
return;
}
last.current = { time: player.currentTime, paused: player.isPaused };
castingNow.current = true; setCasting(true); setRemoteTime(player.currentTime); setRemoteDuration(player.duration); setRemotePaused(player.isPaused);
setDevice(context.getCurrentSession()?.getCastDevice()?.friendlyName ?? "TV");
});
});
return () => { active = false; };
}, []);

// AirPlay (Safari) and the Remote Playback API work on the <video> element itself.
useEffect(() => {
const element = video.current as RemoteVideo | null; if (!element) return;
const win = window as CastWindow;
const onAirplay = (event: Event) => setAirplay((event as Event & { availability?: string }).availability === "available");
if (win.WebKitPlaybackTargetAvailabilityEvent) element.addEventListener("webkitplaybacktargetavailabilitychanged", onAirplay);
let watchId: number | undefined;
if (element.remote && !win.WebKitPlaybackTargetAvailabilityEvent) {
element.remote.watchAvailability((available) => setRemotePlayback(available)).then((id) => { watchId = id; }).catch(() => setRemotePlayback(false));
}
return () => {
element.removeEventListener("webkitplaybacktargetavailabilitychanged", onAirplay);
if (watchId !== undefined) void element.remote?.cancelWatchAvailability(watchId).catch(() => {});
};
}, [video.current]);

const start = async (localTime: number) => {
const win = window as CastWindow;
const element = video.current as RemoteVideo | null;
if (chromecast && remote.current) {
const url = receiverUrl(media.streamUrl);
if (unreachableFromTv(url)) { notice("The TV cannot reach this page's address (localhost). Open Open EasyX by the NAS address to cast."); return; }
const framework = win.cast.framework; const chrome = win.chrome;
const context = framework.CastContext.getInstance();
try { await context.requestSession(); }
catch (error) { if (String(error) !== "cancel") notice("No cast session could be started."); return; }
const session = context.getCurrentSession(); if (!session) return;
const info = new chrome.cast.media.MediaInfo(url, media.mimeType || "video/mp4");
info.streamType = chrome.cast.media.StreamType.BUFFERED;
if (media.duration > 0) info.duration = media.duration;
info.metadata = new chrome.cast.media.GenericMediaMetadata();
info.metadata.title = media.title; info.metadata.subtitle = media.performer;
if (media.thumbnailUrl) info.metadata.images = [new chrome.cast.Image(receiverUrl(media.thumbnailUrl))];
const request = new chrome.cast.media.LoadRequest(info);
request.currentTime = localTime; request.autoplay = true;
element?.pause();
try { await session.loadMedia(request); }
catch { notice("The TV could not play this file. Chromecast plays MP4 (H.264/AAC) and WebM; other formats need a re-encoding preset."); }
return;
}
if (element?.webkitShowPlaybackTargetPicker && airplay) { element.webkitShowPlaybackTargetPicker(); return; }
if (element?.remote && remotePlayback) {
try { await element.remote.prompt(); }
catch (error) { if ((error as DOMException)?.name !== "AbortError") notice("This browser could not start casting for this video."); }
return;
}
notice(win.isSecureContext
? "No cast device was found. Make sure the TV or Chromecast is on the same network."
: "Casting from the player needs Chrome over HTTPS (for example via the Synology reverse proxy) or Safari (AirPlay). In Chrome you can also use ⋮ → Cast… to cast this tab.");
};

const stop = () => { (window as CastWindow).cast?.framework?.CastContext.getInstance().endCurrentSession(true); };
const togglePlay = () => remote.current?.controller.playOrPause();
const seek = (seconds: number) => {
const current = remote.current; if (!current) return;
current.player.currentTime = Math.max(0, Math.min(current.player.duration || seconds, seconds));
current.controller.seek(); setRemoteTime(current.player.currentTime);
};

return { available: chromecast || airplay || remotePlayback, casting, device, remoteTime, remoteDuration, remotePaused, start, stop, togglePlay, seek };
}
47 changes: 47 additions & 0 deletions src/player-gestures.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* Touch gestures, zoom and casting on the custom video player. */
.custom-player .player-surface { overflow: hidden; touch-action: pan-y; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
.custom-player.zoomed .player-surface { touch-action: none; cursor: grab; }
.custom-player .player-surface video { will-change: transform; }

.player-seek-flash {
position: absolute; z-index: 6; top: 0; bottom: 0; width: 38%;
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px;
color: #fff; font-size: 13px; font-weight: 750; pointer-events: none;
background: radial-gradient(ellipse at center, rgba(255, 255, 255, .2), rgba(255, 255, 255, 0) 70%);
animation: player-seek-flash .7s ease-out forwards;
}
.player-seek-flash.left { left: 0; border-radius: 0 50% 50% 0; }
.player-seek-flash.right { right: 0; border-radius: 50% 0 0 50%; }
.player-seek-flash svg { width: 34px; height: 34px; }
@keyframes player-seek-flash { 0% { opacity: 0; } 15% { opacity: 1; } 70% { opacity: 1; } 100% { opacity: 0; } }

.player-speed-badge {
position: absolute; z-index: 7; top: 14px; left: 50%; transform: translateX(-50%);
display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 999px;
color: #fff; background: rgba(8, 8, 10, .72); backdrop-filter: blur(10px);
font-size: 12px; font-weight: 750; pointer-events: none;
}
.player-speed-badge svg { width: 14px; height: 14px; }

.player-zoom-reset {
position: absolute; z-index: 9; top: 12px; right: 12px;
display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border: 1px solid rgba(255, 255, 255, .25); border-radius: 999px;
color: #fff; background: rgba(8, 8, 10, .72); font-size: 12px; font-weight: 700; cursor: pointer;
}
.player-zoom-reset svg { width: 14px; height: 14px; }

.player-cast-overlay {
position: absolute; z-index: 6; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
color: #fff; text-align: center; background: rgba(0, 0, 0, .78); pointer-events: none;
}
.player-cast-overlay svg { width: 42px; height: 42px; opacity: .85; }
.player-cast-overlay b { font-size: 15px; }
.player-cast-overlay button { pointer-events: auto; }
.player-cast-button.active { color: var(--player-accent, #fa4058); }
.player-cast-button.unavailable { opacity: .55; }

/* The control bar's gradient covers the lower half of a small (phone) player. Only its
buttons and sliders take touches, so taps and double taps there reach the video. */
.custom-player .player-controls { pointer-events: none; }
.custom-player .player-controls :is(button, input, select, label, .player-timeline, .caption-menu, .player-volume) { pointer-events: auto; }
.custom-player.controls-hidden .player-controls :is(button, input, select, label, .player-timeline, .caption-menu, .player-volume) { pointer-events: none; }
Loading
Loading