feat(watch): one address and one press start a shared video, and a viewer's route is the software's

A sharer was asked whether an address was a direct link or a webpage, which
of a page's media resources to use, by which method viewers should get it
and which tracks to forward, and a viewer whose site route failed had to
know to ask the sharer for the bytes. Those are the software's to find out.

Sharer. One field and one button: an embeddable page, a media address by its
name, or a webpage the linked App opens (watchTogether). The page's videos
are listed with their length and one press starts the pressed one by the
first offer that works (startPageWatch): the App's bytes with the site's
address beside them, the site's address alone, a manifest with default
tracks, separately loaded tracks, and last the page in each person's App.
When no offer starts, the page's offers stay on screen for a choice by hand,
which is otherwise behind one fold.

Viewer. One action wherever a route exists. A join that names no route takes
the site first and the sharer second, and a route that fails gives its place
to the next one not yet taken; a named route is its person's choice and
stays. The playback settings say when that happened.

The order of offers and of routes is one module (watch-plan). The session's
four selection entries commit through one function, so the choice by hand
and the automatic start cannot drift apart.
This commit is contained in:
AAA committed 2026-11-28 23:45:21 +08:00
1 parent 65bf299b09
commit f8ed4c1c69
19 files changed
+506 -155

No files matched your search

@@ -46,6 +46,8 @@ import { mediaLanguageLabel } from "../../media/media-language";
export interface WatchReceiving {
peerAvailable: boolean; peerSupported: boolean; mode: "direct" | "peer"; browserSource: boolean;
failed?: boolean;
/** This endpoint moved to the sharer's bytes by itself after the site did not play. */
fellBack?: boolean;
pending?: boolean; disabled?: boolean; onPeer(): void; onDirect(): void;
}
@@ -82,7 +84,8 @@ function WatchPlaybackSettings({ receiving, originalPage, playback, children, au
{playback.rates.map(rate => <option key={rate} value={rate}>{rate}×</option>)}
</select></label> : audioAvailable && <p>{t("watch.following")}</p>}
{!audioAvailable && <p>{t("playback.noAudio")}</p>}
{receiving && <><b>{t("watch.forward.viewing")}</b><p>{t("watch.forward.receiveHelp")}</p>
{receiving && <><b>{t("watch.forward.viewing")}</b>
<p role={receiving.fellBack ? "status" : undefined}>{t(receiving.fellBack ? "watch.forward.fallback" : "watch.forward.receiveHelp")}</p>
{(receiving.peerAvailable || receiving.mode === "peer") && (receiving.peerSupported ? <Btn icon="share" title="watch.forward.peer" cap="watch.forward.peer" size="compact"
pressed={receiving.mode === "peer"} disabled={!receiving.peerAvailable || receiving.disabled || receiving.pending
|| receiving.mode === "peer"} busy={receiving.pending} onClick={receiving.onPeer} />
@@ -19,6 +19,7 @@ import type { AppPageMediaSelection, NativeCaptureSources } from "../app-link";
import type { ChannelController } from "../types";
import { directForwardMediaURL, type WatchMediaSources } from "../watch-page-media";
import { screenTitle } from "../presentation";
import { formatMediaTime } from "../../media/media-time";
import { useLayerHistory } from "../../ui/layer-history";
import { channelErrorPresentation } from "../../components/error-presentation";
import { diagnoseChannelFact } from "../../ui/diagnosis";
@@ -496,7 +497,6 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
const validURL = mediaURL !== null && watchSourceSchema.safeParse({ kind: "media", url: mediaURL.href }).success;
const directFile = validURL && directWatchFormat(mediaURL) !== undefined;
const appPageAvailable = channel.appConnected && channel.pagePlayer;
const openPage = appPageAvailable && !portableEmbed && !directFile;
const pageSources = !activityId ? page?.watchSources : undefined;
const sourceCandidate = page?.candidates.find(candidate => candidate.id === pageSources?.candidateId);
type SourceChoice =
@@ -505,10 +505,7 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
| { kind: "indexed"; videoId: string; audioId?: string }
| { kind: "mpd"; selection: Parameters<ChannelController["selectWatchMpdSource"]>[1] };
const [sourceDraft, setSourceDraft] = useState<{ pageId: string; candidateId: string; choice: SourceChoice }>();
const [videoDraft, setVideoDraft] = useState<{ pageId: string; id: string }>();
const videos = page?.candidates ?? [];
const picked = videoDraft?.pageId === page?.pageId ? videoDraft : undefined;
const candidate = picked ? videos.find(video => video.id === picked.id) : videos.length === 1 ? videos[0] : undefined;
const videoName = (video: typeof videos[number], index: number) => video.title || t("watch.videoNumber", { number: String(index + 1) });
const describeChoice = (choice: SourceChoice) => {
switch (choice.kind) {
@@ -580,16 +577,13 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
useEffect(() => {
if (activityId) prepareExistingWatch();
}, [roomId, activityId]);
const singleVideoId = !activityId && !pageSources && videos.length === 1 ? videos[0].id : undefined;
const prepareVideo = (id: string) => run(() => channel.selectWatchPage(roomId, id, undefined, false, "choose-source"));
const automaticPreparation = useRef<{ pageId: string; videoId: string } | null>(null);
useEffect(() => {
if (!page || !singleVideoId || busy) return;
const previous = automaticPreparation.current;
if (previous?.pageId === page.pageId && previous.videoId === singleVideoId) return;
automaticPreparation.current = { pageId: page.pageId, videoId: singleVideoId };
void prepareVideo(singleVideoId);
}, [page?.pageId, singleVideoId, busy]);
// One press on a found video: the sharer's starts by the first offer that works, a viewer's joins with it.
// When no offer starts, the session keeps what the page offered and this dialog shows it for a choice by hand.
const chooseVideo = (id: string) => {
if (activityId) void run(() => channel.selectWatchPage(roomId, id, activityId, false), committed => { if (committed) onClose(); });
else void run(() => channel.startPageWatch(roomId, id, false), onClose);
};
const failure = error ?? pageSources?.error ?? null;
const help = diagnoseChannelFact({ area: "error", code: failure });
const close = () => {
@@ -604,7 +598,7 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
onOriginalPage={appPageAvailable ? () => { void run(async () => {
await channel.cancelScreenSelection(roomId); await channel.prepareWatchPage(roomId, url.trim(), undefined, false);
}); } : undefined} /> : page ? <div className="c3-settings-panels c3-external-input">
<p className="lr-source-option-copy"><small>{t("watch.url")}</small><span>{url}</span></p>
<p className="lr-source-option-copy"><small>{t("watch.url")}</small><span>{page.url}</span></p>
{pageSources ? <>
<h3 ref={pageSourcesHeading} tabIndex={-1}>{sourceTitle}</h3>
{source ? <p className="lr-source-option-copy">{source.name !== sourceTitle && <strong>{source.name}</strong>}<small>{source.capability}</small></p>
@@ -653,26 +647,22 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
</div>
</details>}
</> : <>
<p ref={pageInstruction} tabIndex={-1}>{t(busy && singleVideoId ? "common.loading" : videos.length ? "watch.chooseVideo" : "watch.waitForVideo")}</p>
<p ref={pageInstruction} tabIndex={-1}>{t(busy ? "watch.preparingVideo" : videos.length ? "watch.chooseVideo" : "watch.waitForVideo")}</p>
{videos.length > 0 && <div className="lr-source-picker-list c3-watch-source-list" data-text-list>
{videos.map((video, index) => {
const name = videoName(video, index);
return <CaptureSourceCard key={video.id} title={name} action={t("watch.selectVideoNamed", { name: video.title || String(index + 1) })}
icon="play" selected={candidate?.id === video.id} disabled={busy}
onSelect={() => {
if (activityId) setVideoDraft({ pageId: page.pageId, id: video.id });
else void prepareVideo(video.id);
}} />;
})}
{videos.map((video, index) => <CaptureSourceCard key={video.id} title={videoName(video, index)}
description={video.duration ? formatMediaTime(video.duration) : undefined}
action={t("watch.selectVideoNamed", { name: video.title || String(index + 1) })}
icon="play" disabled={busy} onSelect={() => chooseVideo(video.id)} />)}
</div>}
{activityId && <Btn icon="play" tone="primary" title={confirmLabel} cap={confirmLabel}
busy={busy} disabled={busy || !candidate}
onClick={() => {
if (candidate) void run(() => channel.selectWatchPage(roomId, candidate.id, activityId, false), committed => {
if (committed) onClose();
});
}} />}
{!activityId && videos.length > 0 && <details className="c3-settings-details">
<summary>{t("watch.manual")}</summary>
<p>{t("watch.manualHelp")}</p>
<div className="lr-source-picker-list c3-watch-source-list" data-text-list>
{videos.map((video, index) => <CaptureSourceCard key={video.id} title={videoName(video, index)}
action={t("watch.manualNamed", { name: video.title || String(index + 1) })}
icon="sliders" disabled={busy} onSelect={() => { void prepareVideo(video.id); }} />)}
</div>
</details>}
</>}
<div className="c3-share-title-actions">
<Btn icon="window" quiet size="compact" title="watch.openedPage" cap="watch.openedPage" onClick={() => { void windowAction.run(() => channel.focusWatchPage(roomId, activityId)); }} />
@@ -685,10 +675,10 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
<Btn icon="x" quiet title="common.cancel" cap="common.cancel" onClick={close} />
</div></div> : <form className="c3-settings-panels c3-external-input" onSubmit={event => {
event.preventDefault();
if (!busy && validURL) void run(() => portableEmbed ? channel.prepareWatchEmbed(roomId, url.trim(), false)
: openPage ? channel.prepareWatchPage(roomId, url.trim(), undefined, false) : channel.startWatch(roomId, url.trim(), false), portableEmbed || openPage ? undefined : onClose);
// One address and one press: which kind of address it is, and how it reaches people, is the session's to find out.
if (!busy && validURL) void run(() => channel.watchTogether(roomId, url.trim(), false), outcome => { if (outcome === "started") onClose(); });
}} onKeyDown={event => { if (event.key === "Enter" && event.nativeEvent.isComposing) event.preventDefault(); }}>
<p>{t(portableEmbed ? "watch.embedHelp" : openPage ? "watch.pageHelp" : "watch.urlHelp")}</p>
<p>{t("watch.urlHelp")}</p>
<label className="c3-external-input-field">{t("watch.url")}<span className="lr-input">
<input type="url" required maxLength={MAX_WATCH_URL_LENGTH} value={url} placeholder="https://example.com/video.mp4" disabled={busy}
onChange={event => setURL(event.target.value)} autoComplete="off" />
@@ -696,11 +686,7 @@ export function WatchSourceDialog({ channel, roomId, activityId, replacing = fal
{!channel.pagePlayer && !portableEmbed && !directFile && <p>{t(channel.appConnected ? "watch.pageUnsupported" : "watch.connectApp")}</p>}
<div className="c3-share-title-actions">
<div className="c3-share-title-actions">
<Btn type="submit" icon={openPage ? "globe" : "play"} tone="primary" title={portableEmbed ? "watch.selectVideo" : openPage ? "watch.openPage" : confirmLabel} cap={portableEmbed ? "watch.selectVideo" : openPage ? "watch.openPage" : confirmLabel} busy={busy} disabled={busy || !validURL} />
{appPageAvailable && !portableEmbed && <Btn icon={openPage ? "play" : "globe"} quiet
title={openPage ? "watch.directStart" : "watch.openPage"} cap={openPage ? "watch.directStart" : "watch.openPage"} disabled={busy || !validURL}
onClick={() => { if (openPage) void run(() => channel.startWatch(roomId, url.trim(), false), onClose);
else void run(() => channel.prepareWatchPage(roomId, url.trim(), undefined, false)); }} />}
<Btn type="submit" icon="play" tone="primary" title={confirmLabel} cap={confirmLabel} busy={busy} disabled={busy || !validURL} />
</div>
<div className="c3-share-title-actions">
{onOtherSources && <Btn icon="cast" quiet title="watch.otherSources" cap="watch.otherSources" disabled={busy} onClick={() => {
@@ -171,14 +171,9 @@ function SourceOfferAction({ source, disabled, onWatch }: {
let join = () => onWatch(source.id);
if (source.kind === "watch") {
const { receiving } = source;
if (source.browserSource) join = source.onJoin;
else if (source.onAppWatch) return <>
<ChannelAction icon="window" label={t("watch.openPage")}
disabled={disabled} busy={source.pending} onClick={source.onAppWatch} />
{receiving?.peerAvailable && receiving.peerSupported && <ChannelAction icon="share" label={t("watch.forward.peer")} quiet
disabled={disabled || receiving.disabled} busy={source.pending} onClick={receiving.onPeer} />}
</>;
else if (receiving?.peerAvailable && receiving.peerSupported) join = receiving.onPeer;
if (source.browserSource || receiving?.peerAvailable && receiving.peerSupported) join = source.onJoin;
else if (source.onAppWatch) return <ChannelAction icon="window" label={t("watch.openPage")}
disabled={disabled} busy={source.pending} onClick={source.onAppWatch} />;
else {
const hint = receiving?.peerAvailable ? t("watch.forward.secure")
: source.originalPageUnavailable ?? (source.originalPageAvailable ? t("watch.connectApp") : undefined);
+149 -71
View File
@@ -8,13 +8,14 @@ import { canMoveWatchEmbed, canWatchInBrowser, originalWatchURL, sharedWatchEmbe
import { PageSuppliedMedia, preparePageSuppliedWatchMedia, preparePortableWatchMedia, observeWatchSources, directForwardMediaURL, type WatchMediaSources } from "./watch-page-media";
import { youtubeStartSeconds } from "./watch-youtube-source";
import { indexedMediaSelection } from "./watch-indexed-source";
import { defaultMpdTracks, watchOffers, watchRoutes, type WatchOffer } from "./watch-plan";
import { sameWatchByteSource, WatchBytes } from "./watch-bytes";
import { directWatchFormat } from "../../shared/watch-format";
import { z } from "zod";
import { WatchPlayer } from "./watch-playback";
import { Stage, type SourceSelection, type ScreenShare } from "./stage";
import { HTMLVideoMedia, AppPageMedia, createResourceWatchMedia, waitForWatchMedia, type WatchMedia } from "./watch-media";
import { watchSourceSchema, type WatchPlayback, type WatchSource, type WatchMode, type WatchByteSource, type WatchFormat } from "./protocol";
import { HTMLVideoMedia, AppPageMedia, canReceivePeerWatch, createResourceWatchMedia, waitForWatchMedia, type WatchMedia } from "./watch-media";
import { watchSourceSchema, type WatchActivity, type WatchPlayback, type WatchSource, type WatchMode, type WatchByteSource, type WatchFormat } from "./protocol";
import { PRODUCT_VERSION } from "./product-version";
import { ChannelMedia } from "./media";
import { ChannelInput } from "./input";
@@ -819,6 +820,11 @@ export class ChannelSession {
if (waiting.priorMode === "peer" || !(this.view.pagePlayer && originalWatchURL(next.source)) || next.playback.timeline === "program")
void this.joinWatch(id, "peer").catch(() => {});
}
for (const id of [...this.watchRouting.keys()]) {
const player = this.watchPlayer(id);
if (player) void this.followWatchFailure(id, player);
else if (!state.watchActivities.some(activity => activity.id === id)) this.watchRouting.delete(id);
}
for (const next of nextScreens) {
const socket = this.socket;
void this.watch(next.id, next.roomId).catch(() => {
@@ -2659,7 +2665,7 @@ export class ChannelSession {
}));
};
private makeWatchPlayer(id: string, roomId: string, owner: boolean, media: WatchMedia): WatchPlayer {
const player = new WatchPlayer(roomId, owner, media, () => this.patch({}), () => {
const player = new WatchPlayer(roomId, owner, media, () => { this.patch({}); void this.followWatchFailure(id, player); }, () => {
if (this.watchPlayer(id) === player)
void (owner ? this.stopWatchResource(id, "media-closed") : this.leaveWatchResource(id)).catch(() => {});
else if (this.pendingWatchPlayer(id) === player) this.cancelWatchPage(id);
@@ -2690,6 +2696,15 @@ export class ChannelSession {
const media = new HTMLVideoMedia(source.url, directWatchFormat(new URL(source.url)));
await this.commitWatch(roomId, source, media, selection);
}, reportError);
/** One address and one button: an embeddable page, a media address, or a webpage the linked App opens. */
watchTogether = (roomId: string, rawURL: string, reportError = true): Promise<"started" | "choosing"> => {
const url = rawURL.trim();
if (canMoveWatchEmbed() && watchEmbed(url))
return this.prepareWatchEmbed(roomId, url, reportError).then(() => "choosing" as const);
const page = URL.canParse(url) && directWatchFormat(new URL(url)) === undefined && this.view.appConnected && this.view.pagePlayer;
return page ? this.prepareWatchPage(roomId, url, undefined, reportError).then(() => "choosing" as const)
: this.startWatch(roomId, url, reportError).then(() => "started" as const);
};
private watchSource(rawURL: string): Extract<WatchSource, { kind: "media" }> {
try { return watchSourceSchema.parse({ kind: "media", url: new URL(rawURL).href }) as Extract<WatchSource, { kind: "media" }>; }
catch { throw new Error("invalid_watch_url"); }
@@ -2718,58 +2733,99 @@ export class ChannelSession {
};
selectWatchPage = async (roomId: string, candidateId: string, activityId?: string, reportError = true, mode?: "choose-source" | "original-page"): Promise<boolean> => {
if (activityId) { await this.selectWatchingPage(activityId, candidateId, reportError); return true; }
return this.action(`screen:${roomId}`, async () => {
const selection = this.stages.get(roomId)?.sourceSelection, page = selection?.page;
const candidate = page?.candidates.find(value => value.id === candidateId);
if (!selection || !page || !candidate) throw new Error("watch_page_unavailable");
selection.discovery?.unsubscribe();
if (mode === "original-page") {
await this.commitOriginalPageWatch(roomId, page, selection, candidateId);
return true;
}
delete selection.discovery;
delete selection.watchSources;
if (selection.borrowed) {
if (selection.pendingCandidateId && selection.pendingCandidateId !== candidateId) await page.stopMedia(selection.pendingCandidateId);
selection.pendingCandidateId = candidateId;
} else await page.select(candidateId, false);
selection.controller.signal.throwIfAborted();
const selected = page.candidates.find(value => value.id === candidateId);
if (!selected) throw new Error("watch_page_unavailable");
// Both opaque players and a failed direct URL retain explicit page-source choices.
const discover = async () => {
await waitForWatchMedia({ read: () => page.read(selection.pendingCandidateId), listen: listener => page.listen(listener, selection.pendingCandidateId) }, selection.controller.signal);
selection.controller.signal.throwIfAborted();
const watchSources: NonNullable<SourceSelection["watchSources"]> = selection.watchSources = { candidateId, choices: [], indexed: [], mpd: [] };
this.patch({});
const discovery = selection.discovery = observeWatchSources(page, selection.controller.signal, sources => {
Object.assign(watchSources, sources);
if (!sources.error) delete watchSources.error;
this.patch({});
}, selection.pendingCandidateId);
await discovery.ready;
};
if (!selected.url || mode === "choose-source") { await discover(); return false; }
try {
await this.commitPortableWatch(roomId, page, selection, selected.url);
return true;
} catch (error) {
if (this.stages.get(roomId)?.sourceSelection !== selection || selection.controller.signal.aborted) throw error;
await discover();
throw error;
}
}, reportError);
return this.action(`screen:${roomId}`, () => this.selectPageCandidate(roomId, candidateId, mode), reportError);
};
selectWatchBrowserSource = (roomId: string, choiceId: string | null, reportError = true): Promise<void> => this.action(`screen:${roomId}`, async () => {
private async selectPageCandidate(roomId: string, candidateId: string, mode?: "choose-source" | "original-page"): Promise<boolean> {
const selection = this.stages.get(roomId)?.sourceSelection, page = selection?.page;
const watchSources = selection?.watchSources;
if (!selection || !page || !watchSources || !page.candidates.some(value => value.id === watchSources.candidateId)) throw new Error("watch_page_unavailable");
const candidate = page?.candidates.find(value => value.id === candidateId);
if (!selection || !page || !candidate) throw new Error("watch_page_unavailable");
selection.discovery?.unsubscribe();
if (mode === "original-page") {
await this.commitOriginalPageWatch(roomId, page, selection, candidateId);
return true;
}
delete selection.discovery;
delete selection.watchSources;
if (selection.borrowed) {
if (selection.pendingCandidateId && selection.pendingCandidateId !== candidateId) await page.stopMedia(selection.pendingCandidateId);
selection.pendingCandidateId = candidateId;
} else await page.select(candidateId, false);
selection.controller.signal.throwIfAborted();
const choice = choiceId === null ? undefined : watchSources.choices.find(value => value.id === choiceId);
if (choiceId !== null && !choice) throw new Error("watch_page_unavailable");
if (choice) await this.commitPortableWatch(roomId, page, selection, choice.displayURL, choice.format);
else await this.commitOriginalPageWatch(roomId, page, selection, watchSources.candidateId);
const selected = page.candidates.find(value => value.id === candidateId);
if (!selected) throw new Error("watch_page_unavailable");
// Both opaque players and a failed direct URL retain explicit page-source choices.
const discover = async () => {
await waitForWatchMedia({ read: () => page.read(selection.pendingCandidateId), listen: listener => page.listen(listener, selection.pendingCandidateId) }, selection.controller.signal);
selection.controller.signal.throwIfAborted();
const watchSources: NonNullable<SourceSelection["watchSources"]> = selection.watchSources = { candidateId, choices: [], indexed: [], mpd: [] };
this.patch({});
const discovery = selection.discovery = observeWatchSources(page, selection.controller.signal, sources => {
Object.assign(watchSources, sources);
if (!sources.error) delete watchSources.error;
this.patch({});
}, selection.pendingCandidateId);
await discovery.ready;
};
if (!selected.url || mode === "choose-source") { await discover(); return false; }
try {
await this.commitPortableWatch(roomId, page, selection, selected.url);
return true;
} catch (error) {
if (this.stages.get(roomId)?.sourceSelection !== selection || selection.controller.signal.aborted) throw error;
await discover();
throw error;
}
}
/** From the video its sharer picked on the webpage to a running activity: the first offer that starts. */
startPageWatch = (roomId: string, candidateId: string, reportError = true): Promise<void> => this.action(`screen:${roomId}`, async () => {
await this.selectPageCandidate(roomId, candidateId, "choose-source");
const selection = this.stages.get(roomId)?.sourceSelection, sources = selection?.watchSources;
if (!selection?.page || !sources) throw new Error("watch_page_unavailable");
let failure: unknown = new Error("watch_source_unavailable");
for (const offer of watchOffers(sources, selection.page.candidatePageURL(candidateId))) {
try { return await this.commitWatchOffer(roomId, offer); }
catch (error) {
// A start the room refused or its person cancelled has retired this selection. A source that would not load has not.
if (this.stages.get(roomId)?.sourceSelection !== selection || selection.controller.signal.aborted) throw error;
failure = error;
}
}
throw failure;
}, reportError);
/** Commits one thing the selected webpage can offer. A rejection before the room is asked leaves the selection for another offer. */
private async commitWatchOffer(roomId: string, offer: WatchOffer): Promise<void> {
const selection = this.stages.get(roomId)?.sourceSelection, page = selection?.page, sources = selection?.watchSources;
if (!selection || !page || !sources || !page.candidates.some(value => value.id === sources.candidateId)) throw new Error("watch_page_unavailable");
const signal = selection.controller.signal, candidateId = selection.pendingCandidateId;
signal.throwIfAborted();
switch (offer.kind) {
case "website": return this.commitOriginalPageWatch(roomId, page, selection, sources.candidateId);
case "direct":
case "forward": {
const choice = sources.choices.find(value => value.id === offer.id);
if (!choice) throw new Error("watch_page_unavailable");
if (offer.kind === "direct") return this.commitPortableWatch(roomId, page, selection, choice.displayURL, choice.format);
const source = await page.prepareMedia(offer.id, signal, candidateId);
return this.commitPageSuppliedWatch(roomId, page, selection, source, source.format === choice.format ? directForwardMediaURL(choice) : undefined);
}
case "indexed": {
const video = sources.indexed.find(value => value.candidate.id === offer.videoId)?.inspection;
const audio = offer.audioId ? sources.indexed.find(value => value.candidate.id === offer.audioId)?.inspection : undefined;
if (!video || offer.audioId && !audio) throw new Error("watch_indexed_unsupported");
return this.commitPageSuppliedWatch(roomId, page, selection, await page.prepareMedia(indexedMediaSelection(video, audio), signal, candidateId));
}
case "mpd": {
const catalog = await page.inspectMpd(offer.choiceId, signal, candidateId);
signal.throwIfAborted();
// The sharer's own picture plays first, so a track this browser cannot play is never the default.
const tracks = defaultMpdTracks(catalog, (mimeType, codec) => typeof MediaSource === "undefined" || MediaSource.isTypeSupported(`${mimeType}; codecs="${codec}"`));
if (!tracks) throw new Error("watch_media_unsupported");
return this.commitPageSuppliedWatch(roomId, page, selection, await page.prepareMedia(tracks, signal, candidateId));
}
}
}
selectWatchBrowserSource = (roomId: string, choiceId: string | null, reportError = true): Promise<void> => this.action(`screen:${roomId}`,
() => this.commitWatchOffer(roomId, choiceId === null ? { kind: "website" } : { kind: "direct", id: choiceId }), reportError);
private async commitOriginalPageWatch(roomId: string, page: AppPage, selection: SourceSelection, candidateId: string): Promise<void> {
const confirmPage = () => page.select(candidateId, true);
if (!selection.borrowed) {
@@ -2790,24 +2846,10 @@ export class ChannelSession {
const media = await preparePortableWatchMedia(page, url, selection.controller.signal, format, selection.pendingCandidateId);
await this.commitWatch(roomId, source, media, selection);
}
selectWatchForwardSource = (roomId: string, choiceId: string, reportError = true): Promise<void> => this.action(`screen:${roomId}`, async () => {
const selection = this.stages.get(roomId)?.sourceSelection, page = selection?.page;
const choice = selection?.watchSources?.choices.find(value => value.id === choiceId);
if (!selection || !page || !choice) throw new Error("watch_page_unavailable");
const source = await page.prepareMedia(choiceId, selection.controller.signal, selection.pendingCandidateId);
const mediaUrl = source.format === choice.format ? directForwardMediaURL(choice) : undefined;
await this.commitPageSuppliedWatch(roomId, page, selection, source, mediaUrl);
}, reportError);
selectWatchIndexedSource = (roomId: string, videoId: string, audioId?: string, reportError = true): Promise<void> => this.action(`screen:${roomId}`, async () => {
const selection = this.stages.get(roomId)?.sourceSelection, page = selection?.page;
const sources = selection?.watchSources;
if (!selection || !page || !sources || !page.candidates.some(value => value.id === sources.candidateId)) throw new Error("watch_page_unavailable");
const video = sources.indexed.find(value => value.candidate.id === videoId)?.inspection;
const audio = audioId ? sources.indexed.find(value => value.candidate.id === audioId)?.inspection : undefined;
if (!video || audioId && !audio) throw new Error("watch_indexed_unsupported");
const byteSource = await page.prepareMedia(indexedMediaSelection(video, audio), selection.controller.signal, selection.pendingCandidateId);
await this.commitPageSuppliedWatch(roomId, page, selection, byteSource);
}, reportError);
selectWatchForwardSource = (roomId: string, choiceId: string, reportError = true): Promise<void> => this.action(`screen:${roomId}`,
() => this.commitWatchOffer(roomId, { kind: "forward", id: choiceId }), reportError);
selectWatchIndexedSource = (roomId: string, videoId: string, audioId?: string, reportError = true): Promise<void> => this.action(`screen:${roomId}`,
() => this.commitWatchOffer(roomId, { kind: "indexed", videoId, ...(audioId ? { audioId } : {}) }), reportError);
inspectWatchMpdSource = (roomId: string, choiceId: string, signal: AbortSignal, activityId?: string): Promise<NativePageMpdCatalog> => this.action(activityId ? `watch-source:${activityId}` : `screen:${roomId}`, async () => {
const selection = activityId ? undefined : this.stages.get(roomId)?.sourceSelection;
const player = activityId ? this.watchPlayer(activityId) : undefined;
@@ -3055,7 +3097,41 @@ export class ChannelSession {
} else this.finishSourceSelection(roomId, selection);
}
}
joinWatch = (id: string, mode: WatchMode = "direct", reportError: ReportError = true): Promise<void> => this.action(`watch-video:${id}`, async () => {
/** The routes this endpoint has taken for an activity it joined without naming one. A named route is its person's choice and is not left alone. */
private readonly watchRouting = new Map<string, Set<WatchMode>>();
private async watchRoutesOf(activity: WatchActivity): Promise<WatchMode[]> {
const hls = activity.byteSource?.format === "hls" && !canReceivePeerWatch("hls") && (await import("./watch-hls")).Hls.isSupported();
return watchRoutes(activity, format => canReceivePeerWatch(format, hls), this.watchPlayer(activity.id));
}
/** A route that failed gives its place to the next one this endpoint has not taken for the activity. */
private async followWatchFailure(id: string, player: WatchPlayer): Promise<void> {
const taken = this.watchRouting.get(id), key = `watch-video:${id}`;
const failed = () => !!player.error && player.error !== "watch_update_failed" && player.error !== "watch_live_position_unavailable"
&& this.watchRouting.get(id) === taken && this.watchPlayer(id) === player && !this.pendingActions.has(key);
if (!taken || player.owner || !failed()) return;
const activity = this.view.state?.watchActivities.find(value => value.id === id);
const next = activity && (await this.watchRoutesOf(activity)).find(route => !taken.has(route));
if (!next || !failed()) return;
taken.add(next);
const from = player.mode;
await this.action(key, () => this.joinWatchRoute(id, next), false).catch(() => {});
const successor = this.watchPlayer(id);
if (successor && successor !== player) { successor.fallbackFrom = from; this.patch({}); }
}
joinWatch = (id: string, mode?: WatchMode, reportError: ReportError = true): Promise<void> => this.action(`watch-video:${id}`, async () => {
if (mode) { this.watchRouting.delete(id); return this.joinWatchRoute(id, mode); }
const activity = this.view.state?.watchActivities.find(value => value.id === id);
if (!activity) throw new Error("watch_unavailable");
// The site's route asks nothing; only without it does what this browser can receive matter.
// With no route at all, the direct one names what is missing.
const route = watchRoutes(activity, () => false, this.watchPlayer(id))[0] ?? (await this.watchRoutesOf(activity))[0] ?? "direct";
this.watchRouting.set(id, new Set([route]));
await this.joinWatchRoute(id, route);
}, reportError).finally(() => {
const player = this.watchPlayer(id);
if (player) void this.followWatchFailure(id, player);
});
private async joinWatchRoute(id: string, mode: WatchMode): Promise<void> {
const current = this.watchPlayer(id);
if (current?.mode === mode && !current.error && current.presentation.kind !== "external") return;
const activity = this.view.state?.watchActivities.find(value => value.id === id);
@@ -3078,7 +3154,7 @@ export class ChannelSession {
if (!canWatchInBrowser(activity.source, current)) throw new Error("watch_media_unsupported");
await this.joinWatchMedia(id, embed.provider === "youtube"
? new YouTubeMedia(embed.id, undefined, true) : new PeerTubeMedia(embed.id, true));
}, reportError);
}
private async joinWatchMedia(id: string, media: WatchMedia, mode: WatchMode = "direct"): Promise<void> {
const activity = this.view.state?.watchActivities.find(value => value.id === id);
if (!activity) { media.close(); throw new Error("watch_unavailable"); }
@@ -3123,6 +3199,7 @@ export class ChannelSession {
if (!player.signal.aborted && this.watchPlayer(id) === player) {
player.error = error instanceof Error ? error.message : "watch_media_failed";
this.patch({});
void this.followWatchFailure(id, player);
}
});
try {
@@ -3142,6 +3219,7 @@ export class ChannelSession {
const player = this.watchPlayer(id);
const waiting = this.waitingWatchPages.get(id);
if (player?.owner || (!waiting && !player && !candidate?.mode)) return;
this.watchRouting.delete(id);
this.waitingWatchPages.delete(id);
const roomId = player?.roomId ?? waiting?.roomId ?? candidate!.roomId;
this.declinedSources.set(id, roomId);
+4
View File
@@ -143,6 +143,10 @@ export type HostMediaTarget = "domain" | "app" | "browser";
export interface ChannelActions {
startWatch(roomId: string, url: string, reportError?: boolean): Promise<void>;
/** Starts from one address; "choosing" means its page or embedded player now asks its sharer which video. */
watchTogether(roomId: string, url: string, reportError?: boolean): Promise<"started" | "choosing">;
/** Starts the chosen video of the opened webpage by the first offer that works. */
startPageWatch(roomId: string, candidateId: string, reportError?: boolean): Promise<void>;
prepareWatchEmbed(roomId: string, url: string, reportError?: boolean): Promise<void>;
confirmWatchEmbed(roomId: string, reportError?: boolean): Promise<void>;
watchEmbed(roomId: string): WatchMedia | undefined;
+1 -1
View File
@@ -43,7 +43,7 @@ export function useChannel(): ChannelController {
watchMediaChoices: session.watchMediaChoices, setWatchByteSource: session.setWatchByteSource,
prepareWatchEmbed: session.prepareWatchEmbed, confirmWatchEmbed: session.confirmWatchEmbed, watchEmbed: session.watchEmbed,
watchEmbedPreparation: session.watchEmbedPreparation,
startWatch: session.startWatch, joinWatch: session.joinWatch, leaveWatch: session.leaveWatch, cancelWatchPage: session.cancelWatchPage,
startWatch: session.startWatch, watchTogether: session.watchTogether, startPageWatch: session.startPageWatch, joinWatch: session.joinWatch, leaveWatch: session.leaveWatch, cancelWatchPage: session.cancelWatchPage,
stopWatch: session.stopWatch, setWatchPlayback: session.setWatchPlayback, resumeWatch: session.resumeWatch,
setScreenBufferTarget: session.setScreenBufferTarget,
queryProfiles: session.queryProfiles, loadProfiles: session.loadProfiles,
+92
View File
@@ -0,0 +1,92 @@
import type { NativePageMpdCatalog, NativePageMpdSelection } from "../native/wire";
import type { WatchActivity, WatchFormat, WatchMode } from "./protocol";
import { canWatchInBrowser } from "./watch-embed-source";
import type { WatchMediaSources } from "./watch-page-media";
import type { WatchPlayer } from "./watch-playback";
/**
* The order in which a shared video reaches people is one fact with one owner. A person gives an
* address and presses one button; which resource, which tracks and which route are the software's
* to try in this order, and a way that fails gives its place to the next.
*/
/** One thing the sharer's webpage can offer for a chosen video. */
export type WatchOffer =
/** Bytes read by the sharer's App, with the site's own address beside them when viewers can open it. */
| { kind: "forward"; id: string }
/** The site's address alone, played by each person's browser. */
| { kind: "direct"; id: string }
/** A picture track and a sound track the page loaded as separate files. */
| { kind: "indexed"; videoId: string; audioId?: string }
/** A manifest; its tracks are chosen once it has been read. */
| { kind: "mpd"; choiceId: string }
/** Nothing could be taken out of the page: each person plays it in their own App. */
| { kind: "website" };
/**
* What a start tries, first to last. The App lists the player's own address first and playlists in
* the order the page asked for them, so the first complete source is the one the page is playing.
*/
export function watchOffers(sources: Pick<WatchMediaSources, "choices" | "indexed" | "mpd">, pageURL: string | null): WatchOffer[] {
const offers: WatchOffer[] = sources.choices.flatMap(choice => [
{ kind: "forward" as const, id: choice.id }, { kind: "direct" as const, id: choice.id }]);
for (const choice of sources.mpd) offers.push({ kind: "mpd", choiceId: choice.candidate.id });
const tracks = defaultIndexedTracks(sources.indexed);
if (tracks) offers.push({ kind: "indexed", ...tracks });
if (pageURL) offers.push({ kind: "website" });
return offers;
}
const picture = (track: { width?: number | null; height?: number | null }) => (track.width ?? 0) * (track.height ?? 0);
/** The largest picture the page loaded, and the sound it loaded with it. */
export function defaultIndexedTracks(indexed: WatchMediaSources["indexed"]): { videoId: string; audioId?: string } | undefined {
const read = indexed.flatMap(choice => choice.inspection ? [choice.inspection] : []);
const video = read.filter(track => track.metadata.kind === "video")
.reduce<typeof read[number] | undefined>((best, track) => !best || picture(track.metadata) > picture(best.metadata) ? track : best, undefined);
if (!video) return;
const audio = read.find(track => track.metadata.kind === "audio");
return { videoId: video.candidate.id, ...(audio ? { audioId: audio.candidate.id } : {}) };
}
/** A room of mixed devices decodes these in this order of likelihood. */
const CODEC_REACH = ["avc1", "avc3", "vp09", "vp9", "av01", "hvc1", "hev1"];
const reach = (codec: string) => { const index = CODEC_REACH.indexOf(codec.split(".")[0]); return index < 0 ? CODEC_REACH.length : index; };
/** Above this height the upload of one sharer rarely serves a room. */
const DEFAULT_PICTURE_HEIGHT = 1080;
/**
* The largest picture this browser plays that is not above 1080 lines; among equal pictures the
* codec more devices decode, then the richer one. The sound marked as the main one, else the first.
*/
export function defaultMpdTracks(catalog: NativePageMpdCatalog,
plays: (mimeType: string, codec: string) => boolean = () => true): NativePageMpdSelection | undefined {
const usable = catalog.tracks.filter(track => plays(track.mimeType, track.codec));
const videos = usable.filter(track => track.kind === "video");
const fitting = videos.filter(track => (track.height ?? 0) <= DEFAULT_PICTURE_HEIGHT);
const video = (fitting.length ? fitting : videos).reduce<typeof videos[number] | undefined>((best, track) => {
if (!best) return track;
const size = picture(track) - picture(best);
// With nothing under the limit, the smallest picture above it is the nearest.
if (size) return (size > 0) === fitting.length > 0 ? track : best;
const codec = reach(best.codec) - reach(track.codec);
return codec > 0 || !codec && (track.bandwidth ?? 0) > (best.bandwidth ?? 0) ? track : best;
}, undefined);
if (!video) return;
const sounds = usable.filter(track => track.kind === "audio");
const audio = sounds.find(track => track.role === "main") ?? sounds[0];
return { sourceId: catalog.sourceId, videoId: video.id, ...(audio ? { audioId: audio.id } : {}) };
}
/**
* The routes this endpoint can take to a shared video without asking its person anything, first to
* last: from the site, then from the sharer. Opening the page in one's own App asks for a window
* and a choice on that page, so it is offered and never taken alone.
*/
export function watchRoutes(activity: Pick<WatchActivity, "source" | "byteSource">,
receives: (format: WatchFormat) => boolean, current?: Pick<WatchPlayer, "presentation" | "mode">): WatchMode[] {
const routes: WatchMode[] = [];
if (canWatchInBrowser(activity.source, current)) routes.push("direct");
if (activity.byteSource && receives(activity.byteSource.format)) routes.push("peer");
return routes;
}
+2
View File
@@ -16,6 +16,8 @@ export class WatchPlayer {
get presentation() { return this.media.presentation ?? { kind: "external" as const }; }
get video(): HTMLVideoElement | null { return this.presentation.kind === "video" ? this.presentation.element : null; }
mode: WatchMode | null = null;
/** The route this player took over from when that one failed. */
fallbackFrom: WatchMode | null = null;
stopRequested = false;
blockedReason: "autoplay" | "local-seek" | null = null;
get blocked(): boolean { return this.blockedReason !== null; }
+7 -4
View File
@@ -45,6 +45,7 @@ export const en: Record<CopyKey, string> = {
"watch.forward.receiveHelp": "Requires an available room P2P connection. Changes only how you receive this video.",
"watch.forward.secure": "This browser cannot receive this video on this page. Watch in the App, or open the site at a trusted HTTPS address.",
"watch.forward.viewing": "Receiving method",
"watch.forward.fallback": "It did not play from the site here, so it now comes from the sharer.",
"watch.decodeFailed": "This browser could not decode the video. Try another browser.",
"watch.sourceUnplayable": "Open the original page to check that the video plays, then retry or choose another source.",
"watch.mediaAccessDenied": "The video site denied access. Check your access on the original page, then retry or choose another source.",
@@ -564,12 +565,14 @@ export const en: Record<CopyKey, string> = {
"watch.start": "Watch together",
"watch.sourceHint": "Use a direct video link or select a webpage video in the App. The sharer controls progress.",
"watch.url": "Video or webpage URL",
"watch.urlHelp": "Paste a playable HTTP(S) video URL. Only the sharer controls playback, progress and speed.",
"watch.pageHelp": "Open the webpage, sign in there if needed, and start playback. Then return here to choose its player. The webpage keeps a separate sign-in session.",
"watch.urlHelp": "Paste the address of a video, or of the page it is on. You control play, position and speed.",
"watch.preparingVideo": "Preparing this video. If it does not start, press play on its webpage.",
"watch.manual": "Choose the playback method yourself",
"watch.manualHelp": "Piik picks a method that works. To name the source or the tracks yourself, or to have everyone open this page in their own App, choose the video here.",
"watch.manualNamed": "Choose the playback method for {name}",
"watch.connectApp": "Use the link at the top of the page to connect a Piik App that supports webpage playback.",
"watch.openPage": "Open webpage and select video",
"watch.directStart": "Play direct video URL",
"watch.chooseVideo": "Choose the webpage player for the video you want to watch together.",
"watch.chooseVideo": "Press the video to watch together.",
"watch.video": "Video",
"watch.selectVideo": "Select video",
"watch.waitForVideo": "Start playback on the original webpage and sign in there if needed. Return here to choose the video when it appears.",
+2 -3
View File
@@ -472,11 +472,10 @@ export const ja = {
"watch.start": "一緒に見る",
"watch.sourceHint": "動画の直接リンクを使うか、App でウェブページの動画を選びます。再生位置は共有者が操作します。",
"watch.url": "動画またはウェブページの URL",
"watch.urlHelp": "再生可能な HTTP(S) の動画 URL を貼り付けてください。再生、一時停止、再生位置、速度は共有者だけが操作できます。",
"watch.urlHelp": "動画の URL、またはその動画があるページの URL を貼り付けてください。再生、再生位置、速度はあなたが操作します。",
"watch.connectApp": "ページ上部から、ウェブページの再生に対応した Piik App に接続してください。",
"watch.openPage": "ページを開いて動画を選択",
"watch.directStart": "動画の直接 URL を再生",
"watch.chooseVideo": "一緒に見る動画のプレーヤーを選んでください。",
"watch.chooseVideo": "一緒に見る動画を選んでください。",
"watch.video": "動画",
"watch.selectVideo": "動画を選択",
"watch.waitForVideo": "開いたページで動画を再生すると、ここに表示されます。",
+2 -3
View File
@@ -473,11 +473,10 @@ export const ko = {
"watch.start": "함께 보기",
"watch.sourceHint": "동영상 직접 링크를 사용하거나 App에서 웹페이지 동영상을 선택하세요. 진행은 공유자가 제어해요.",
"watch.url": "동영상 또는 웹페이지 URL",
"watch.urlHelp": "재생 가능한 HTTP(S) 동영상 URL을 붙여 넣으세요. 재생, 진행, 속도는 공유자만 제어해요.",
"watch.urlHelp": "동영상 주소나 동영상이 있는 웹페이지 주소를 붙여 넣으세요. 재생, 진행, 속도는 내가 제어해요.",
"watch.connectApp": "페이지 상단에서 웹페이지 재생을 지원하는 Piik App에 연결하세요.",
"watch.openPage": "웹페이지를 열고 동영상 선택",
"watch.directStart": "동영상 직접 URL 재생",
"watch.chooseVideo": "함께 볼 웹페이지 동영상의 플레이어를 선택하세요.",
"watch.chooseVideo": "함께 볼 동영상을 선택하세요.",
"watch.video": "동영상",
"watch.selectVideo": "동영상 선택",
"watch.waitForVideo": "열린 웹페이지에서 재생을 시작하면 동영상이 여기에 표시돼요.",
+2 -3
View File
@@ -472,11 +472,10 @@ export const zhHant = {
"watch.start": "同步觀看",
"watch.sourceHint": "使用影片直連網址,或在 App 開啟網頁選取影片。播放進度由分享者控制。",
"watch.url": "影片或網頁網址",
"watch.urlHelp": "貼上可直接播放的 HTTP(S) 影片網址。只有分享者可以控制播放、進度和速度。",
"watch.urlHelp": "貼上影片的網址,或它所在網頁的網址。播放、進度和速度由你控制。",
"watch.connectApp": "請用頁面上方的入口連線至支援網頁播放的 Piik App。",
"watch.openPage": "開啟網頁選影片",
"watch.directStart": "播放影片直連網址",
"watch.chooseVideo": "選擇網頁上你想一起看的影片播放器。",
"watch.chooseVideo": "點一下要一起看的影片。",
"watch.video": "影片",
"watch.selectVideo": "選擇影片",
"watch.waitForVideo": "在開啟的網頁中播放影片後,就會出現在這裡。",
+7 -4
View File
@@ -43,6 +43,7 @@ export const zh = {
"watch.forward.receiveHelp": "需要可用的房间 P2P 连接。只更改你的接收方式。",
"watch.forward.secure": "当前浏览器无法在此页面接收这种视频。请在 App 中观看,或通过受信任的 HTTPS 地址打开站点。",
"watch.forward.viewing": "接收方式",
"watch.forward.fallback": "这里从网站播放没成功,已改为从分享者接收。",
"watch.decodeFailed": "浏览器无法解码此视频。请尝试其他浏览器。",
"watch.sourceUnplayable": "无法播放这个来源。请确认原网页能播放,再重试或选择其他来源。",
"watch.mediaAccessDenied": "视频网站拒绝访问。请在原网页确认观看权限,再重试或选择其他来源。",
@@ -562,12 +563,14 @@ export const zh = {
"watch.start": "同步观看",
"watch.sourceHint": "使用视频直链或在 App 打开网页选视频,进度由分享者控制。",
"watch.url": "视频或网页地址",
"watch.urlHelp": "粘贴可直接播放的 HTTP(S) 视频地址。只有分享者可以控制播放、进度和速度。",
"watch.pageHelp": "打开网页,按需登录并开始播放,再回到这里选择播放器。原网页使用独立的登录状态。",
"watch.urlHelp": "粘贴视频的地址,或它所在网页的地址。播放、进度和速度由你控制。",
"watch.preparingVideo": "正在准备这个视频。要是迟迟没有开始,请到原网页里点一下播放。",
"watch.manual": "自己选择播放方式",
"watch.manualHelp": "默认由 Piik 选能用的方式。要自己指定来源或轨道,或者让每个人在自己的 App 里打开这个网页,就从这里选视频。",
"watch.manualNamed": "为 {name} 选择播放方式",
"watch.connectApp": "请用页面顶部的入口连接支持网页播放的 Piik App。",
"watch.openPage": "打开网页选视频",
"watch.directStart": "播放视频直链",
"watch.chooseVideo": "选择网页上你想一起看的视频播放器。",
"watch.chooseVideo": "点一下要一起看的视频。",
"watch.video": "视频",
"watch.selectVideo": "选择视频",
"watch.waitForVideo": "请在原网页中开始播放,需要登录时也在原网页完成。视频出现后,回到这里选择。",
+1
View File
@@ -493,6 +493,7 @@ export function ChannelRoomPage({ channel, selected, onSelect, appControl, layou
owned, awaitingSource: channel.waitingWatchPages?.has(activity.id), subscribed: !!subscription || !!channel.waitingWatchPages?.has(activity.id), audience: state ? watchAudience(state, activity, channel.profiles) : [],
receiving: !owned ? { peerAvailable: !!activity.byteSource, peerSupported: canReceivePeerWatch(activity.byteSource?.format, hlsSupported),
failed: !!player?.error, mode: player?.mode ?? subscription?.mode ?? "direct",
fellBack: player?.mode === "peer" && player.fallbackFrom === "direct",
browserSource, pending: busy("watch-video", activity.id), disabled: !connected,
onPeer: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, report => channel.joinWatch(activity.id, "peer", report)); },
onDirect: () => { showSource(activity.roomId, activity.id); watchAction(activity.id, report => channel.joinWatch(activity.id, "direct", report)); } } : undefined,
+20 -2
View File
@@ -326,6 +326,9 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean })
}, 3500);
return () => window.clearTimeout(timer);
}, [browserSourcePending]);
const sampleCandidates = (url: string) => new URLSearchParams(location.search).has("empty-candidates") ? []
: [{ id: "sample-video", pageURL: url, title: "An evening with friends", url: null, duration: 6127 },
...(new URLSearchParams(location.search).has("many-videos") ? [{ id: "sample-trailer", pageURL: url, title: "Coming next week", url: null, duration: 32 }] : [])];
const commitPageSelection = (roomId: string, activityId?: string, mediaUrl?: string) => {
if (!activityId) setWatchActivity({ id: `sample-watch-${crypto.randomUUID()}`, roomId, viewerSessionIds: [], source: { kind: "website", url: pageSample!.url, ...(mediaUrl ? { mediaUrl } : {}) },
userId: "sample-ada", sessionId: "sample-ada-session", playback: { timeline: "media" as const, position: 42, paused: true, rate: 1, anchorTime: 0 } });
@@ -343,8 +346,23 @@ export function ChannelRoomPreview({ firstUse = false }: { firstUse?: boolean })
setWatchByteSource: async (_id, choiceId) => setForwarding(choiceId !== null),
pagePlayer: new URLSearchParams(location.search).has("page-player"),
watchPage: (_roomId, activityId) => pageSample?.activityId === activityId ? pageSample : undefined,
prepareWatchPage: async (_roomId, url, activityId) => setPageSample({ pageId: crypto.randomUUID(), url, activityId,
candidates: new URLSearchParams(location.search).has("empty-candidates") ? [] : [{ id: "sample-video", pageURL: url, title: "An evening with friends", url: null, duration: 240 }] }),
prepareWatchPage: async (_roomId, url, activityId) => setPageSample({ pageId: crypto.randomUUID(), url, activityId, candidates: sampleCandidates(url) }),
watchTogether: async (roomId, url) => {
if (new URLSearchParams(location.search).has("page-player") && !/\.(?:mp4|webm|ogv|m3u8|mpd)$/i.test(new URL(url).pathname)) {
setPageSample({ pageId: crypto.randomUUID(), url, candidates: sampleCandidates(url) });
return "choosing";
}
setWatchMode("owner"); setWatchActivity({ id: `sample-watch-${crypto.randomUUID()}`, roomId, viewerSessionIds: [], source: { kind: "media", url },
userId: "sample-ada", sessionId: "sample-ada-session", playback: { timeline: "media" as const, position: 0, paused: true, rate: 1, anchorTime: 0 } });
return "started";
},
startPageWatch: async (roomId, candidateId) => {
if (new URLSearchParams(location.search).has("browser-source-failed")) {
setPageSample({ ...pageSample!, watchSources: { candidateId, choices: browserSourceChoices, indexed: [], mpd: [] } });
throw new Error("watch_media_unplayable");
}
setForwarding(true); commitPageSelection(roomId, undefined, browserSourceChoices[0].displayURL);
},
focusWatchPage: async () => sample.received(), focusWatch: async () => { actionFails("watch-focus"); sample.received(); },
cancelScreenSelection: async () => { setCapturePendingSample(false); setBrowserSourcePending(null); setPageSample(undefined); },
selectWatchPage: async (roomId, candidateId, activityId, _reportError, mode) => {
+41
View File
@@ -14011,6 +14011,47 @@ test.each(['activity', 'subscription'] as const)('watch authority %s removal ret
} finally { session.close(); }
});
test.each(['none', 'direct'] as const)('a viewer who named %s route moves to the sharer when the site does not play, and a named route stays', async named => {
const { session, socket } = await setup(1000, false);
const site = new WatchTestVideo(), received = new WatchTestVideo(); site.readyState = 0; received.readyState = 0;
vi.stubGlobal('document', { documentElement: {}, createElement: vi.fn().mockReturnValueOnce(site).mockReturnValue(received) });
vi.stubGlobal('MediaSource', { isTypeSupported: () => true });
const source = { sessionId: crypto.randomUUID(), resourceId: crypto.randomUUID(), format: 'file' as const };
const activity = { id: 'watch-routes', roomId: 'first', viewerSessionIds: [], sessionId: source.sessionId, userId: 'other',
source: { kind: 'media' as const, url: 'https://media.test/owned.mp4' }, byteSource: source,
playback: { timeline: 'media' as const, position: 0, paused: true, rate: 1, anchorTime: 1000 } };
vi.spyOn((session as unknown as { watchBytes: { read: (...args: unknown[]) => Promise<never> } }).watchBytes, 'read')
.mockImplementation((...args) => { const signal = args.at(-1) as AbortSignal;
return new Promise<never>((_resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true })); });
const joins = () => socket.sent.filter(command => command.type === 'join_watch');
const confirm = () => socket.receive({ type: 'reply', roomId: 'first', requestId: joins().at(-1)!.requestId, result: { type: 'watch_ready', serverTime: 1000 } });
try {
socket.receive({ type: 'state', state: { ...session.getSnapshot().state!, watchActivities: [activity] } });
const joining = named === 'none' ? session.joinWatch(activity.id) : session.joinWatch(activity.id, 'direct');
expect(joins().at(-1)!.mode).toBe('direct');
confirm(); await joining;
Object.assign(site, { error: { code: 2, message: '' } }); site.dispatchEvent(new Event('error'));
await vi.waitFor(() => expect(session.getSnapshot().watchPlayers.get(activity.id)?.error).toBe('watch_media_unavailable'), { timeout: 200 }).catch(() => {});
if (named === 'direct') {
await new Promise(resolve => setTimeout(resolve, 20));
expect(joins()).toHaveLength(1);
expect(session.getSnapshot().watchPlayers.get(activity.id)?.error).toBe('watch_media_unavailable');
return;
}
await vi.waitFor(() => expect(joins().at(-1)!.mode).toBe('peer'));
confirm();
await vi.waitFor(() => expect(session.getSnapshot().watchPlayers.get(activity.id)?.fallbackFrom).toBe('direct'));
const player = session.getSnapshot().watchPlayers.get(activity.id)!;
expect(player.mode).toBe('peer');
expect(site.src).toBe('');
// The sharer's bytes are the last route: a second failure stays with its message.
player.error = 'watch_source_unavailable';
socket.receive({ type: 'state', state: { ...session.getSnapshot().state! } });
await new Promise(resolve => setTimeout(resolve, 20));
expect(joins()).toHaveLength(2);
} finally { session.close(); }
});
test.each(['withdrawn', 'replaced', 'activity', 'direct viewer'] as const)('watch source %s retires only the affected media and preserves room participation', async removal => {
const { session, socket } = await setup(1000, false);
const video = new WatchTestVideo(); video.readyState = 0;
+60
View File
@@ -0,0 +1,60 @@
import { expect, test } from "vitest";
import { defaultIndexedTracks, defaultMpdTracks, watchOffers, watchRoutes } from "../src/client/channel/watch-plan";
import type { WatchIndexedChoice } from "../src/client/channel/watch-page-media";
const id = (value: number) => `00000000-0000-4000-8000-${String(value).padStart(12, "0")}`;
function indexed(value: number, kind: "video" | "audio", size?: [number, number]): WatchIndexedChoice {
const candidate = { id: id(value), name: kind, hostname: "media.test", mimeType: `${kind}/mp4`, totalSize: 100 };
return { candidate, inspection: { candidate,
metadata: { kind, codec: kind === "video" ? "avc1.640028" : "mp4a.40.2", duration: 60, firstPTS: 0, timescale: 1000, language: "und",
...(size ? { width: size[0], height: size[1] } : {}) },
recipe: { choiceId: candidate.id, totalSize: 100, codec: "avc1.640028", timescale: 1000, mediaOffset: 40, initBase64: "aW5pdA==", segments: [[60, 1000]] } } };
}
function track(value: number, kind: "video" | "audio", extra: Partial<{ codec: string; height: number; bandwidth: number; role: string }> = {}) {
const height = extra.height ?? null;
return { id: id(value), kind, label: "", mimeType: `${kind}/mp4`, codec: extra.codec ?? (kind === "video" ? "avc1.640028" : "mp4a.40.2"),
language: "und", role: extra.role ?? "", width: height && Math.round(height * 16 / 9), height, bandwidth: extra.bandwidth ?? null, frameRate: null };
}
test("a start tries the page's own source first, with the site's address behind the App's bytes, and the page last", () => {
const choices = [{ id: id(1), displayURL: "https://media.test/master.m3u8", name: "master.m3u8", format: "hls" as const },
{ id: id(2), displayURL: "https://media.test/film.mp4", name: "film.mp4", format: "file" as const }];
const mpd = [{ candidate: { id: id(3), name: "manifest.mpd", hostname: "media.test" } }];
expect(watchOffers({ choices, indexed: [indexed(4, "video", [1280, 720]), indexed(5, "audio")], mpd }, "https://site.test/watch")).toEqual([
{ kind: "forward", id: id(1) }, { kind: "direct", id: id(1) }, { kind: "forward", id: id(2) }, { kind: "direct", id: id(2) },
{ kind: "mpd", choiceId: id(3) }, { kind: "indexed", videoId: id(4), audioId: id(5) }, { kind: "website" }]);
expect(watchOffers({ choices: [], indexed: [], mpd: [] }, null)).toEqual([]);
expect(watchOffers({ choices: [], indexed: [], mpd: [] }, "https://site.test/watch")).toEqual([{ kind: "website" }]);
});
test("separately loaded tracks default to the largest picture and the sound beside it", () => {
expect(defaultIndexedTracks([indexed(1, "video", [1280, 720]), indexed(2, "audio"), indexed(3, "video", [1920, 1080])]))
.toEqual({ videoId: id(3), audioId: id(2) });
expect(defaultIndexedTracks([indexed(1, "video", [1280, 720])])).toEqual({ videoId: id(1) });
// Sound alone, or a track that could not be read, is not a video.
expect(defaultIndexedTracks([indexed(2, "audio"), { candidate: indexed(1, "video").candidate, error: "watch_indexed_unsupported" }])).toBeUndefined();
});
test("a manifest defaults to the largest picture up to 1080 lines, the widest decoded codec among equals, and the main sound", () => {
const catalog = { sourceId: id(9), tracks: [
track(1, "video", { height: 2160, codec: "av01.0.12M.08" }), track(2, "video", { height: 1080, codec: "av01.0.08M.08" }),
track(3, "video", { height: 1080, bandwidth: 4_000_000 }), track(4, "video", { height: 1080, bandwidth: 6_000_000 }), track(5, "video", { height: 720 }),
track(6, "audio", { role: "dub" }), track(7, "audio", { role: "main" })] };
expect(defaultMpdTracks(catalog)).toEqual({ sourceId: id(9), videoId: id(4), audioId: id(7) });
// What this browser cannot play is never the default.
expect(defaultMpdTracks(catalog, (_mime, codec) => !codec.startsWith("avc1"))).toEqual({ sourceId: id(9), videoId: id(2), audioId: id(7) });
// With every picture above the limit the nearest one is taken; with no sound the picture goes alone.
expect(defaultMpdTracks({ sourceId: id(9), tracks: [track(1, "video", { height: 2160 }), track(2, "video", { height: 1440 })] }))
.toEqual({ sourceId: id(9), videoId: id(2) });
expect(defaultMpdTracks({ sourceId: id(9), tracks: [track(6, "audio")] })).toBeUndefined();
});
test("a viewer's endpoint goes to the site first and to the sharer second, and only where it can", () => {
const byteSource = { sessionId: id(1), resourceId: id(2), format: "hls" as const };
const site = { kind: "website" as const, url: "https://site.test/watch", mediaUrl: "https://media.test/film.mp4" };
expect(watchRoutes({ source: site, byteSource }, () => true)).toEqual(["direct", "peer"]);
expect(watchRoutes({ source: site, byteSource }, () => false)).toEqual(["direct"]);
expect(watchRoutes({ source: { kind: "website", url: "https://site.test/watch" }, byteSource }, () => true)).toEqual(["peer"]);
// A page that only its own player can show asks its person: no route is taken alone.
expect(watchRoutes({ source: { kind: "website", url: "https://site.test/watch" } }, () => true)).toEqual([]);
});
+13 -15
View File
@@ -157,8 +157,10 @@ describe("Webpage watch presentation", () => {
watchEmbed: () => undefined, sourceSelectionCommitting: () => false } as unknown as ChannelController;
const html = renderToStaticMarkup(createElement(WatchSourceDialog, { channel, roomId: "room", onClose: vi.fn() }));
expect(html.includes(t("en", "watch.connectApp"))).toBe(connectAdvice);
expect(html.includes('aria-label="Open webpage and select video"')).toBe(pagePlayer);
expect(html).toMatch(pagePlayer ? /type="button"[^>]*aria-label="Play direct video URL"/ : /type="submit"[^>]*aria-label="Start watching together"[^>]*disabled/);
// One action, whatever the address turns out to be: the kind of address is not a question for its person.
expect(html.match(/<button[^>]*type="submit"[^>]*>/g)).toHaveLength(1);
expect(html).toMatch(/type="submit"[^>]*aria-label="Start watching together"[^>]*disabled/);
expect(html).not.toContain("Open webpage and select video");
});
it.each([
@@ -174,13 +176,10 @@ describe("Webpage watch presentation", () => {
const html = renderToStaticMarkup(createElement(WatchSourceDialog, {
channel, roomId: "room", initialURL, onClose: vi.fn(),
}));
expect(html).toMatch(direct ? /type="submit"[^>]*aria-label="Start watching together"/ : /type="submit"[^>]*aria-label="Open webpage and select video"/);
if (appConnected) {
expect(html).toMatch(direct ? /type="button"[^>]*aria-label="Open webpage and select video"/ : /type="button"[^>]*aria-label="Play direct video URL"/);
} else {
expect(html.match(/<button[^>]*aria-label="Start watching together"[^>]*>/)?.[0]).not.toContain("disabled");
expect(html).not.toContain(t("en", "watch.connectApp"));
}
expect(html.match(/<button[^>]*type="submit"[^>]*aria-label="Start watching together"[^>]*>/)?.[0]).not.toContain("disabled");
expect(html).not.toContain('aria-label="Open webpage and select video"');
expect(html).not.toContain(t("en", "watch.connectApp"));
expect(direct || appConnected).toBe(true);
});
it("disables playback for a non-HTTP URL with a playlist extension", () => {
@@ -190,8 +189,7 @@ describe("Webpage watch presentation", () => {
const html = renderToStaticMarkup(createElement(WatchSourceDialog, {
channel, roomId: "room", initialURL: "ftp://video.test/stream.m3u8", onClose: vi.fn(),
}));
expect(html).toMatch(/type="submit"[^>]*aria-label="Open webpage and select video"[^>]*disabled=""/);
expect(html).toMatch(/type="button"[^>]*aria-label="Play direct video URL"[^>]*disabled=""/);
expect(html).toMatch(/type="submit"[^>]*aria-label="Start watching together"[^>]*disabled=""/);
});
it.each([[undefined, true], ["watch", true], [undefined, false]] as const)(
@@ -406,7 +404,7 @@ describe("Webpage watch presentation", () => {
}
});
it("offers direct playback first and keeps the App and sharer paths visible when available", () => {
it("offers a viewer one action wherever a route exists, and the webpage only when it is the one way", () => {
setCopy({ lang: "en" });
const source: WatchStageSource = { kind: "watch", id: "activity", userId: "friend", name: "Bo", title: "video.example/watch/evening",
roomName: "Friday", audience: [], owned: false, subscribed: false, paused: true, website: true, originalPageAvailable: true, browserSource: false,
@@ -441,9 +439,9 @@ describe("Webpage watch presentation", () => {
expect(render({ ...unsupported, browserSource: true })).not.toContain(t("en", "watch.pageUnsupported"));
expect(render({ ...unsupported, receiving })).not.toContain(t("en", "watch.pageUnsupported"));
const appAndForwarded = render({ ...source, receiving });
expect(appAndForwarded).toContain('aria-label="Open webpage and select video"');
expect(appAndForwarded).toContain('aria-label="Receive from sharer"');
expect(appAndForwarded).not.toContain('aria-label="Watch"');
expect(appAndForwarded).toContain('aria-label="Watch"');
expect(appAndForwarded).not.toContain('aria-label="Receive from sharer"');
expect(appAndForwarded).not.toContain('aria-label="Open webpage and select video"');
const forwarded = render({ ...source, onAppWatch: undefined, receiving });
expect(forwarded).toContain('aria-label="Watch"');
expect(forwarded).not.toContain('aria-label="Receive from sharer"');
+70
View File
@@ -103,3 +103,73 @@ test.each(["commit", "cancel", "unknown"] as const)("source discovery survives p
}
expect(dispose).toHaveBeenCalledOnce();
});
function pageSession(pageURL: string | null) {
vi.stubGlobal("window", { localStorage: { getItem: () => null } });
vi.stubGlobal("localStorage", { getItem: () => null });
vi.stubGlobal("location", { origin: "https://source.test", hash: "" });
vi.stubGlobal("history", { state: null });
// This page's own player cannot play the site's address here, so an offer that needs it does not start.
vi.stubGlobal("document", { documentElement: {}, createElement: () => { throw new Error("watch_media_unplayable"); } });
const session = new ChannelSession();
const candidateId = crypto.randomUUID();
const choice = { id: crypto.randomUUID(), displayURL: "https://source.test/film.mp4", name: "film.mp4", format: "file" };
const prepare = vi.fn(async (_id: unknown) => { throw new Error("watch_media_range_unsupported"); });
const dispose = vi.fn();
const request = vi.fn(async (_command: unknown, reply: (event: unknown) => void) => { reply({ type: "watch_ready", serverTime: performance.now() }); });
const page = new AppPage(crypto.randomUUID(), "https://source.test/watch", async command => {
if (command.type === "page_media_sources") return { choices: [choice], indexedCandidates: [], mpdCandidates: [], byteSource: null };
if (command.type === "page_media_prepare") return prepare(command.choiceId);
if (command.type === "page_select" || command.type === "page_read")
return { position: 0, rate: 1, readyState: 4, paused: false, duration: 20, ended: false, buffered: [] };
throw Error("unexpected " + command.type);
}, dispose, () => {});
Object.assign(session, { connectApp: async () => ({ preparePage: async () => page }), request });
const open = async () => {
await session.prepareWatchPage("room", page.url);
page.receive({ type: "page_candidates", pageId: page.id, url: page.url, candidates: [{ pageURL, id: candidateId, url: null, title: "Player", duration: 20 }] });
};
return { session, page, candidateId, choice, prepare, request, open };
}
test("a chosen video starts by the first offer that works: the App's bytes, the site's address, then the page itself", async () => {
const { session, page, candidateId, choice, prepare, request, open } = pageSession("https://source.test/watch");
try {
await open();
await session.startPageWatch("room", candidateId);
// The App could not read the file and this page could not play its address, each tried once and in that order.
expect(prepare.mock.calls).toEqual([[choice.id]]);
expect(request).toHaveBeenCalledTimes(1);
expect(request).toHaveBeenCalledWith(expect.objectContaining({ type: "start_watch", source: { kind: "website", url: page.url } }), expect.any(Function), "room");
expect(session.watchPage("room")).toBeUndefined();
} finally { session.close(); }
});
test("when no offer starts, the start fails with the last reason and the page's offers stay for a choice by hand", async () => {
const { session, candidateId, choice, request, open } = pageSession(null);
try {
await open();
await expect(session.startPageWatch("room", candidateId, false)).rejects.toThrow("watch_media_unplayable");
expect(request).not.toHaveBeenCalled();
expect(session.watchPage("room")?.watchSources?.choices).toEqual([choice]);
expect(session.getSnapshot().pending.has("screen:room")).toBe(false);
} finally { session.close(); }
});
test("one address finds its own way: a media address starts, a webpage opens in the linked App", async () => {
const { session, page } = pageSession("https://source.test/watch");
const started = vi.fn(async (..._call: unknown[]) => {}), opened = vi.fn(async (..._call: unknown[]) => {});
Object.assign(session, { startWatch: started, prepareWatchPage: opened });
const view = (session as unknown as { view: { appConnected: boolean; pagePlayer: boolean } }).view;
try {
expect(await session.watchTogether("room", " https://media.test/film.mp4 ")).toBe("started");
expect(await session.watchTogether("room", page.url)).toBe("started");
expect(started.mock.calls.map(call => call[1])).toEqual(["https://media.test/film.mp4", page.url]);
view.appConnected = true; view.pagePlayer = true;
expect(await session.watchTogether("room", page.url)).toBe("choosing");
expect(opened).toHaveBeenCalledWith("room", page.url, undefined, true);
// A known media address needs no page even with the App.
expect(await session.watchTogether("room", "https://media.test/list.m3u8")).toBe("started");
expect(opened).toHaveBeenCalledTimes(1);
} finally { session.close(); }
});