Download src/lib/playa.ts from Zero124/VR-MEDIA: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/playa.ts
- Command line
-
hf download hf://spaces/Zero124/VR-MEDIA/src/lib/playa.ts
-
curl -L -o playa.ts https://huggingface.co/spaces/Zero124/VR-MEDIA/resolve/main/src/lib/playa.ts
15.2 kB
| // PLAY'A feed generator. | |
| // | |
| // DESIGN RULE: this file is PURELY ADDITIVE. It does not modify the DeoVR | |
| // implementation in any way -- it consumes `videoToScene()` from ./deovr as a | |
| // read-only building block, so the DeoVR feed keeps its exact current output | |
| // and both players stay in sync automatically (same detection, same | |
| // passthrough decisions, same stream URLs). | |
| // | |
| // WHAT IS VERIFIED (playavr.com FAQ + app store listings): | |
| // * PLAY'A has a BUILT-IN WEB BROWSER, so it can open a URL we host. | |
| // * Passthrough exists on Quest 2 / 3 / Pro. In Passthrough Settings the | |
| // recommended option is "From Video" -- i.e. PLAY'A reads passthrough | |
| // information carried BY THE VIDEO/FEED -- plus a manual "Chroma Key" mode | |
| // with an eyedropper, range and smoothness sliders. | |
| // * "2D, 3D, flat, fisheye, 180 and 360 videos automatically recognized" -- | |
| // PLAY'A auto-detects format, and the de-facto standard signal for that is | |
| // the filename (the same _180_SBS_FISHEYE_ALPHA tokens DeoVR reads). | |
| // * It plays from local files and from network-connected servers, and | |
| // supports per-site custom playlists. | |
| // | |
| // WHAT IS NOT PUBLISHED: PLAY'A has no public JSON schema document (their API | |
| // is a business/contact offering). So we do not invent a proprietary shape. | |
| // Instead every PLAY'A entry point below is a superset of the well-established | |
| // DeoVR-compatible JSON that VR players consume, with extra ALIAS keys | |
| // (video_url / videoUrl / thumbnail_url) and a plain-values `passthrough` | |
| // block added alongside the DeoVR `chromakey` block. Unknown keys are ignored | |
| // by parsers, so this is safe: whichever convention PLAY'A follows, the data is | |
| // present. Three independent entry points are offered for the same library: | |
| // 1. JSON feed /api/feeds/playa (in-app browser / deeplink) | |
| // 2. M3U playlist /api/feeds/playa/playlist (network playlist support) | |
| // 3. HTML gallery /api/feeds/playa/browse (in-app browser, tap to play) | |
| // | |
| // All three reuse the SAME tokenized /api/stream/<id>/<tokens>.mp4 proxy URLs as | |
| // DeoVR, so passthrough, projection and stereo behave identically. | |
| import { db } from "./db"; | |
| import type { Video } from "@prisma/client"; | |
| import { | |
| videoToScene, | |
| isPlayableInDeovr, | |
| passthroughMethod, | |
| validateForDeovr, | |
| type DeovrScene, | |
| } from "./deovr"; | |
| import { resolveChromaColor } from "./passthrough"; | |
| import { getPrimaryApiKey } from "./auth"; | |
| /** Tab name shown inside PLAY'A for the library. */ | |
| export const PLAYA_FEED_NAME = process.env.PLAYA_FEED_NAME || "Offcloud Library"; | |
| export type PlayaProjection = "flat" | "180" | "360" | "fisheye" | "mkx200" | "rf52"; | |
| export type PlayaStereo = "sbs" | "tb" | "mono"; | |
| /** | |
| * Plain-values passthrough block. The DeoVR `chromakey` block (string booleans, | |
| * HSV numbers) is preserved untouched on every scene; this is an additional, | |
| * self-describing view of the same decision for players that prefer plain | |
| * JSON booleans. Both describe the same key color, so "From Video" has the data | |
| * it needs no matter which key a player looks for. | |
| */ | |
| export interface PlayaPassthrough { | |
| enabled: boolean; | |
| /** alpha = packed alpha channel, chroma = solid color background. */ | |
| mode: "alpha" | "chroma" | "none"; | |
| /** true when passthrough should turn on automatically at launch. */ | |
| auto: boolean; | |
| color?: string; | |
| colorHex?: string; | |
| hue?: number; | |
| saturation?: number; | |
| brightness?: number; | |
| /** Color range / tolerance. */ | |
| range?: number; | |
| /** Edge falloff / smoothness. */ | |
| falloff?: number; | |
| } | |
| /** A PLAY'A scene: a DeoVR scene plus aliases and plain passthrough values. */ | |
| export interface PlayaScene extends DeovrScene { | |
| /** Per-video JSON descriptor (DeoVR list convention). */ | |
| video_url: string; | |
| /** camelCase alias of video_url. */ | |
| videoUrl: string; | |
| /** snake_case alias of thumbnailUrl. */ | |
| thumbnail_url?: string | null; | |
| /** Direct playable media URL (same proxy URL DeoVR receives). */ | |
| sourceUrl: string; | |
| /** Human-readable projection hint. */ | |
| projection: PlayaProjection; | |
| /** Human-readable stereo hint. */ | |
| stereo: PlayaStereo; | |
| passthrough: PlayaPassthrough; | |
| } | |
| export interface PlayaSceneGroup { | |
| name: string; | |
| list: PlayaScene[]; | |
| } | |
| export interface PlayaFeed { | |
| scenes: PlayaSceneGroup[]; | |
| /** DeoVR-compatible authorization marker; PLAY'A ignores it harmlessly. */ | |
| authorized: string; | |
| player: "playa"; | |
| generatedAt: string; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Mapping helpers | |
| // --------------------------------------------------------------------------- | |
| /** DeoVR screenType -> PLAY'A-friendly projection label. */ | |
| function screenTypeToProjection(screenType: string): PlayaProjection { | |
| switch (screenType) { | |
| case "flat": | |
| return "flat"; | |
| case "sphere": | |
| return "360"; | |
| case "fisheye": | |
| return "fisheye"; | |
| case "mkx200": | |
| return "mkx200"; | |
| case "rf52": | |
| return "rf52"; | |
| case "dome": | |
| default: | |
| return "180"; | |
| } | |
| } | |
| /** DeoVR stereoMode -> PLAY'A stereo label. */ | |
| function stereoModeToStereo(stereoMode: string): PlayaStereo { | |
| if (stereoMode === "sbs") return "sbs"; | |
| if (stereoMode === "tb") return "tb"; | |
| return "mono"; | |
| } | |
| function tokenQuery(): string { | |
| return "?token=" + encodeURIComponent(getPrimaryApiKey()); | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Scene building | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * Convert a Video row into a PLAY'A scene. | |
| * | |
| * The DeoVR scene is generated first and kept intact (screenType, stereoMode, | |
| * encodings, chromakey, thumbnailUrl, tags), which is what guarantees the two | |
| * players behave the same. PLAY'A extras are layered on top. | |
| */ | |
| export function videoToPlayaScene(v: Video, baseUrl: string = ""): PlayaScene { | |
| const scene = videoToScene(v, baseUrl); | |
| const method = passthroughMethod(v); | |
| const sourceUrl = scene.encodings[0]?.videoSources[0]?.url ?? ""; | |
| const perVideoJson = baseUrl + "/api/feeds/playa/" + v.id + tokenQuery(); | |
| let passthrough: PlayaPassthrough; | |
| if (method === "alpha") { | |
| // Packed alpha channel: no key color needed, the video carries transparency. | |
| passthrough = { enabled: true, mode: "alpha", auto: true }; | |
| } else if (method === "chroma") { | |
| const color = resolveChromaColor(v.name, v.id); | |
| passthrough = { | |
| enabled: true, | |
| mode: "chroma", | |
| auto: true, | |
| color: color.name, | |
| colorHex: color.hex, | |
| hue: color.hue, | |
| saturation: color.saturation, | |
| brightness: color.brightness, | |
| range: scene.chromakey?.threshold, | |
| falloff: scene.chromakey?.opacity, | |
| }; | |
| } else { | |
| passthrough = { enabled: false, mode: "none", auto: false }; | |
| } | |
| return { | |
| ...scene, | |
| video_url: perVideoJson, | |
| videoUrl: perVideoJson, | |
| thumbnail_url: scene.thumbnailUrl ?? null, | |
| sourceUrl, | |
| projection: screenTypeToProjection(scene.screenType), | |
| stereo: stereoModeToStereo(scene.stereoMode), | |
| passthrough, | |
| }; | |
| } | |
| /** All ready, available, playable videos as PLAY'A scenes. */ | |
| export async function buildPlayaScenes(baseUrl: string = ""): Promise<PlayaScene[]> { | |
| const videos = await db.video.findMany({ | |
| where: { status: "ready", availability: "available", streamUrl: { not: "" } }, | |
| orderBy: { createdAt: "desc" }, | |
| }); | |
| return videos.filter((v) => isPlayableInDeovr(v)).map((v) => videoToPlayaScene(v, baseUrl)); | |
| } | |
| /** Full PLAY'A library feed. */ | |
| export async function buildPlayaFeed(baseUrl: string = ""): Promise<PlayaFeed> { | |
| const list = await buildPlayaScenes(baseUrl); | |
| return { | |
| scenes: [{ name: PLAYA_FEED_NAME, list }], | |
| authorized: "1", | |
| player: "playa", | |
| generatedAt: new Date().toISOString(), | |
| }; | |
| } | |
| /** Single-video PLAY'A descriptor, or null when missing / not playable. */ | |
| export async function buildPlayaSingleVideo( | |
| videoId: string, | |
| baseUrl: string = "" | |
| ): Promise<PlayaScene | null> { | |
| const v = await db.video.findUnique({ where: { id: videoId } }); | |
| if (!v) return null; | |
| if (v.availability !== "available") return null; | |
| if (!isPlayableInDeovr(v)) return null; | |
| return videoToPlayaScene(v, baseUrl); | |
| } | |
| // --------------------------------------------------------------------------- | |
| // M3U playlist (PLAY'A network playlist support) | |
| // --------------------------------------------------------------------------- | |
| function sanitizeForM3u(s: string): string { | |
| return s.replace(/[\r\n]+/g, " ").trim(); | |
| } | |
| /** | |
| * Build a plain M3U playlist of the whole library. | |
| * | |
| * Every entry keeps the token-carrying proxy URL whose filename holds the | |
| * projection/stereo/ALPHA tokens, so PLAY'A's automatic format recognition | |
| * works from the playlist exactly as it does from the JSON feed. | |
| */ | |
| export async function buildPlayaPlaylist(baseUrl: string = ""): Promise<string> { | |
| const scenes = await buildPlayaScenes(baseUrl); | |
| const lines: string[] = ["#EXTM3U", "#PLAYLIST:" + sanitizeForM3u(PLAYA_FEED_NAME)]; | |
| for (const scene of scenes) { | |
| const bits: string[] = []; | |
| if (scene.projection !== "flat") bits.push(scene.projection.toUpperCase()); | |
| if (scene.stereo !== "mono") bits.push(scene.stereo.toUpperCase()); | |
| if (scene.passthrough.enabled) bits.push("PASSTHROUGH"); | |
| const suffix = bits.length > 0 ? " [" + bits.join(" ") + "]" : ""; | |
| const seconds = Math.max(0, Math.round(scene.videoLength || 0)); | |
| lines.push("#EXTINF:" + seconds + "," + sanitizeForM3u(scene.title) + suffix); | |
| if (scene.thumbnailUrl) lines.push("#EXTIMG:" + scene.thumbnailUrl); | |
| lines.push(scene.sourceUrl); | |
| } | |
| return lines.join("\n") + "\n"; | |
| } | |
| // --------------------------------------------------------------------------- | |
| // HTML gallery (PLAY'A built-in browser) | |
| // --------------------------------------------------------------------------- | |
| function escapeHtml(s: string): string { | |
| return s | |
| .replace(/&/g, "&") | |
| .replace(/</g, "<") | |
| .replace(/>/g, ">") | |
| .replace(/"/g, """) | |
| .replace(/'/g, "'"); | |
| } | |
| function formatClock(total: number): string { | |
| const s = Math.max(0, Math.round(total || 0)); | |
| const h = Math.floor(s / 3600); | |
| const m = Math.floor((s % 3600) / 60); | |
| const sec = s % 60; | |
| const mm = String(m).padStart(2, "0"); | |
| const ss = String(sec).padStart(2, "0"); | |
| return h > 0 ? h + ":" + mm + ":" + ss : m + ":" + ss; | |
| } | |
| /** | |
| * A dependency-free HTML gallery for PLAY'A's built-in browser: each card links | |
| * straight at the tokenized media URL, so tapping a card starts playback in the | |
| * player with format auto-detection from the filename tokens. | |
| */ | |
| export async function buildPlayaBrowsePage(baseUrl: string = ""): Promise<string> { | |
| const scenes = await buildPlayaScenes(baseUrl); | |
| const feedUrl = baseUrl + "/api/feeds/playa" + tokenQuery(); | |
| const playlistUrl = baseUrl + "/api/feeds/playa/playlist" + tokenQuery(); | |
| const cards = scenes | |
| .map((scene) => { | |
| const tags: string[] = []; | |
| if (scene.projection !== "flat") tags.push(scene.projection.toUpperCase()); | |
| if (scene.stereo !== "mono") tags.push(scene.stereo.toUpperCase()); | |
| if (scene.passthrough.enabled) { | |
| tags.push(scene.passthrough.mode === "alpha" ? "ALPHA PASSTHROUGH" : "PASSTHROUGH"); | |
| } | |
| const thumb = scene.thumbnailUrl | |
| ? '<img class="thumb" src="' + escapeHtml(scene.thumbnailUrl) + '" alt="" loading="lazy">' | |
| : '<div class="thumb"></div>'; | |
| const chips = tags | |
| .map((t) => '<span class="chip">' + escapeHtml(t) + "</span>") | |
| .join(""); | |
| return [ | |
| '<a class="card" href="' + escapeHtml(scene.sourceUrl) + '">', | |
| thumb, | |
| '<div class="meta">', | |
| '<div class="title">' + escapeHtml(scene.title) + "</div>", | |
| '<div class="sub">' + escapeHtml(formatClock(scene.videoLength)) + "</div>", | |
| '<div class="chips">' + chips + "</div>", | |
| "</div>", | |
| "</a>", | |
| ].join(""); | |
| }) | |
| .join("\n"); | |
| const empty = | |
| '<p class="empty">No playable videos yet. Add content in Offcloud -- the library syncs automatically.</p>'; | |
| return [ | |
| "<!doctype html>", | |
| '<html lang="en"><head>', | |
| '<meta charset="utf-8">', | |
| '<meta name="viewport" content="width=device-width, initial-scale=1">', | |
| "<title>" + escapeHtml(PLAYA_FEED_NAME) + " - PLAY'A</title>", | |
| "<style>", | |
| "*{box-sizing:border-box}", | |
| "body{margin:0;background:#0f0f0f;color:#eee;font:16px/1.4 Roboto,system-ui,sans-serif;padding:16px}", | |
| "h1{font-size:22px;font-weight:500;margin:0 0 4px}", | |
| ".lead{color:#aaa;font-size:14px;margin:0 0 16px}", | |
| ".bar{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:20px}", | |
| ".bar a{background:#065fd4;color:#fff;text-decoration:none;padding:10px 16px;border-radius:20px;font-size:14px}", | |
| ".bar a.alt{background:#272727;color:#eee}", | |
| ".grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:16px}", | |
| ".card{display:block;background:#181818;border-radius:4px;overflow:hidden;text-decoration:none;color:inherit}", | |
| ".thumb{display:block;width:100%;aspect-ratio:16/9;object-fit:cover;background:#272727}", | |
| ".meta{padding:10px 12px 12px}", | |
| ".title{font-size:14px;font-weight:500;line-height:20px;word-break:break-word}", | |
| ".sub{color:#aaa;font-size:13px;margin-top:2px}", | |
| ".chips{margin-top:8px;display:flex;flex-wrap:wrap;gap:4px}", | |
| ".chip{background:#272727;color:#3ea6ff;font-size:11px;padding:2px 8px;border-radius:20px}", | |
| ".empty{color:#aaa}", | |
| "</style></head><body>", | |
| "<h1>" + escapeHtml(PLAYA_FEED_NAME) + "</h1>", | |
| '<p class="lead">' + | |
| scenes.length + | |
| " video" + | |
| (scenes.length === 1 ? "" : "s") + | |
| " ready to play. Tap any card to open it in PLAY'A.</p>", | |
| '<div class="bar">', | |
| '<a href="' + escapeHtml(playlistUrl) + '">Open as playlist</a>', | |
| '<a class="alt" href="' + escapeHtml(feedUrl) + '">JSON feed</a>', | |
| "</div>", | |
| scenes.length === 0 ? empty : '<div class="grid">' + cards + "</div>", | |
| "</body></html>", | |
| ].join("\n"); | |
| } | |
| // --------------------------------------------------------------------------- | |
| // Validation (Feed Manager) | |
| // --------------------------------------------------------------------------- | |
| /** | |
| * PLAY'A has the same practical requirements as DeoVR (a reachable stream and a | |
| * known duration), so validation reuses the DeoVR checks rather than inventing | |
| * a second, divergent rule set. | |
| */ | |
| export async function validateLibraryForPlaya(): Promise< | |
| { videoId: string; name: string; valid: boolean; errors: string[] }[] | |
| > { | |
| const videos = await db.video.findMany({ | |
| where: { status: "ready", availability: "available" }, | |
| }); | |
| return videos.map((v) => { | |
| const errors = validateForDeovr(v); | |
| return { videoId: v.id, name: v.name, valid: errors.length === 0, errors }; | |
| }); | |
| } | |