From c53ebcc30dc8e761d6394baaabf569d66dffd772 Mon Sep 17 00:00:00 2001 From: tkrmagid Date: Sat, 16 May 2026 04:03:43 +0900 Subject: [PATCH] v0.4.13: fix delete-while-playing race, /videoCache, config additions, name resolution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Crash fix (4K delete EXCEPTION_ACCESS_VIOLATION): - JavaCvBackend.stopWorker() no longer calls grabber.close() from caller thread. Only flips running=false, stops/flushes audio line, then interrupt+join(2s). The worker's own finally still closes grabber from the decoder thread, so the av_frame native plane is never freed mid-memCopy. - Validate memCopy length against ByteBuffer.capacity() AND width*height*4 before copying, and re-check running/closed inside the frameLock. Config: - max_preload_mb (default 1024) — replaces the hard-coded 512 MB cap in VideoCache. Pushed to clients at join via CachePolicyPayload. - render_distance_blocks (default 128) — replaces the hard-coded 128 in VideoAnchorRenderer.getViewDistance(). Mirrored client-side via ClientPolicy. Command rename: /videopreload → /videoCache add|list|remove - Persistent named index in cache_entries (server config). - /videoCache list prints clickable URLs (ClickEvent.OpenUrl). - /videoCache remove broadcasts DeleteCachePayload so each client purges its disk cache file. Name resolution: - /videoPlace ... and the GUI save path both accept a /videoCache name in place of an http(s) URL; VideoPlayerConfig.resolveUrlOrName() does the lookup server-side before persisting to the anchor BE. Cleanup: - Drop the lowercase Brigadier aliases (videoplace, videostick, videodelete, videomute) — keep camelCase only. --- gradle.properties | 2 +- .../ejclaw/videoplayer/VideoPlayerConfig.java | 231 +++++++++++++++--- .../ejclaw/videoplayer/VideoPlayerMod.java | 36 ++- .../videoplayer/client/ClientPolicy.java | 30 +++ .../client/net/ClientNetworking.java | 15 ++ .../client/playback/JavaCvBackend.java | 65 ++++- .../client/playback/VideoCache.java | 50 +++- .../client/render/VideoAnchorRenderer.java | 5 +- .../command/VideoCacheCommand.java | 147 +++++++++++ .../command/VideoDeleteCommand.java | 1 - .../videoplayer/command/VideoMuteCommand.java | 1 - .../command/VideoPlaceCommand.java | 13 +- .../command/VideoPreloadCommand.java | 74 ------ .../command/VideoStickCommand.java | 3 - .../videoplayer/net/CachePolicyPayload.java | 29 +++ .../videoplayer/net/DeleteCachePayload.java | 28 +++ .../videoplayer/net/VideoPlayerNetwork.java | 17 +- 17 files changed, 598 insertions(+), 149 deletions(-) create mode 100644 src/main/java/com/ejclaw/videoplayer/client/ClientPolicy.java create mode 100644 src/main/java/com/ejclaw/videoplayer/command/VideoCacheCommand.java delete mode 100644 src/main/java/com/ejclaw/videoplayer/command/VideoPreloadCommand.java create mode 100644 src/main/java/com/ejclaw/videoplayer/net/CachePolicyPayload.java create mode 100644 src/main/java/com/ejclaw/videoplayer/net/DeleteCachePayload.java diff --git a/gradle.properties b/gradle.properties index fc3bb62..fe2ac98 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,7 +5,7 @@ org.gradle.configuration-cache=false # Mod mod_id=video_player -mod_version=0.4.12 +mod_version=0.4.13 maven_group=com.ejclaw.videoplayer archives_base_name=video_player diff --git a/src/main/java/com/ejclaw/videoplayer/VideoPlayerConfig.java b/src/main/java/com/ejclaw/videoplayer/VideoPlayerConfig.java index 3796897..52e0bf3 100644 --- a/src/main/java/com/ejclaw/videoplayer/VideoPlayerConfig.java +++ b/src/main/java/com/ejclaw/videoplayer/VideoPlayerConfig.java @@ -2,6 +2,8 @@ package com.ejclaw.videoplayer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import net.fabricmc.loader.api.FabricLoader; @@ -12,88 +14,249 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * Server-side mod config, stored at {@code /config/video_player.json}. * - *

Format (auto-generated on first start): + *

Schema (auto-generated on first start): *

{@code
  * {
- *   // List of HTTP(S) video URLs that the server will tell every player to preload
- *   // into their local video_player_cache/ folder when they join. Identical to running
- *   // /videopreload  for each joining player.
+ *   "max_preload_mb": 1024,
  *   "preload_urls": [
  *     "https://example.com/intro.mp4"
+ *   ],
+ *   "cache_entries": [
+ *     { "name": "intro", "url": "https://example.com/intro.mp4" }
  *   ]
  * }
  * }
* - *

Why a list and not a dedicated tool: the same {@link - * com.ejclaw.videoplayer.net.PreloadPayload} that powers {@code /videopreload} is reused, so the - * client-side cache, chat feedback, and {@code /videoplace} → cache lookup paths all behave - * identically for config-driven and command-driven preloads. + *

{@code max_preload_mb} is the hard ceiling each client enforces on a single video download + * (default 1024 MB ≈ 1 GB; enough headroom for ~50 short FHD clips). Pushed to every client on + * join via {@link com.ejclaw.videoplayer.net.CachePolicyPayload}. + * + *

{@code cache_entries} is the named cache index managed by {@code /videocache add|list|remove}. + * Each entry's URL is pushed to clients on join (and immediately on {@code add}). Names are unique. + * + *

{@code preload_urls} is the legacy un-named auto-preload list — same behavior as + * {@code cache_entries} but without a removable handle. Kept for backward-compat. */ public final class VideoPlayerConfig { private VideoPlayerConfig() {} private static final String FILE_NAME = "video_player.json"; - private static volatile List PRELOAD_URLS = Collections.emptyList(); + + private static final int DEFAULT_MAX_PRELOAD_MB = 1024; + /** Default render-distance cap for video anchors, in blocks. 128 = the legacy hard-coded value. */ + private static final int DEFAULT_RENDER_DISTANCE = 128; + + private static volatile int maxPreloadMb = DEFAULT_MAX_PRELOAD_MB; + private static volatile int renderDistanceBlocks = DEFAULT_RENDER_DISTANCE; + private static volatile List preloadUrls = Collections.emptyList(); + /** Insertion-ordered name → url. Mutated only under the class monitor. */ + private static final Map CACHE_ENTRIES = new LinkedHashMap<>(); /** Load (or create) the config file. Called once during mod initialization. */ - public static void load() { - Path path = FabricLoader.getInstance().getConfigDir().resolve(FILE_NAME); + public static synchronized void load() { + Path path = configPath(); try { if (!Files.exists(path)) { writeDefault(path); VideoPlayerMod.LOG.info("[{}] created default config at {}", VideoPlayerMod.MOD_ID, path); - PRELOAD_URLS = Collections.emptyList(); + maxPreloadMb = DEFAULT_MAX_PRELOAD_MB; + preloadUrls = Collections.emptyList(); + CACHE_ENTRIES.clear(); return; } String raw = Files.readString(path, StandardCharsets.UTF_8); JsonObject json = JsonParser.parseString(raw).getAsJsonObject(); + + // max_preload_mb (sanity-clamped to [16, 16384] so a typo can't brick a client) + int cap = DEFAULT_MAX_PRELOAD_MB; + if (json.has("max_preload_mb") && json.get("max_preload_mb").isJsonPrimitive() + && json.get("max_preload_mb").getAsJsonPrimitive().isNumber()) { + cap = json.get("max_preload_mb").getAsInt(); + } + if (cap < 16) cap = 16; + if (cap > 16384) cap = 16384; + maxPreloadMb = cap; + + // render_distance_blocks (sanity-clamped to [16, 2048]) + int rd = DEFAULT_RENDER_DISTANCE; + if (json.has("render_distance_blocks") && json.get("render_distance_blocks").isJsonPrimitive() + && json.get("render_distance_blocks").getAsJsonPrimitive().isNumber()) { + rd = json.get("render_distance_blocks").getAsInt(); + } + if (rd < 16) rd = 16; + if (rd > 2048) rd = 2048; + renderDistanceBlocks = rd; + + // preload_urls (legacy) List urls = new ArrayList<>(); if (json.has("preload_urls") && json.get("preload_urls").isJsonArray()) { json.getAsJsonArray("preload_urls").forEach(el -> { if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) { - String u = el.getAsString().trim(); - if (!u.isEmpty() && (u.startsWith("http://") || u.startsWith("https://")) - && u.length() <= 256) { - urls.add(u); - } else if (!u.isEmpty()) { - VideoPlayerMod.LOG.warn( - "[{}] config: ignoring invalid preload url '{}' (must be http/https, ≤256 chars)", - VideoPlayerMod.MOD_ID, u); - } + String u = sanitizeUrl(el.getAsString()); + if (u != null) urls.add(u); } }); } - PRELOAD_URLS = Collections.unmodifiableList(urls); - VideoPlayerMod.LOG.info("[{}] config loaded: {} preload url(s)", - VideoPlayerMod.MOD_ID, urls.size()); + preloadUrls = Collections.unmodifiableList(urls); + + // cache_entries (named) + CACHE_ENTRIES.clear(); + if (json.has("cache_entries") && json.get("cache_entries").isJsonArray()) { + for (JsonElement el : json.getAsJsonArray("cache_entries")) { + if (!el.isJsonObject()) continue; + JsonObject o = el.getAsJsonObject(); + String name = o.has("name") && o.get("name").isJsonPrimitive() + ? o.get("name").getAsString().trim() : null; + String url = o.has("url") && o.get("url").isJsonPrimitive() + ? sanitizeUrl(o.get("url").getAsString()) : null; + if (name == null || name.isEmpty() || url == null) continue; + if (CACHE_ENTRIES.containsKey(name)) { + VideoPlayerMod.LOG.warn( + "[{}] config: duplicate cache entry name '{}' — keeping first", + VideoPlayerMod.MOD_ID, name); + continue; + } + CACHE_ENTRIES.put(name, url); + } + } + + VideoPlayerMod.LOG.info( + "[{}] config loaded: cap={} MB, render={} blocks, preload_urls={}, cache_entries={}", + VideoPlayerMod.MOD_ID, maxPreloadMb, renderDistanceBlocks, urls.size(), CACHE_ENTRIES.size()); } catch (Throwable t) { - VideoPlayerMod.LOG.warn("[{}] failed to read config {}: {} — using empty list", + VideoPlayerMod.LOG.warn("[{}] failed to read config {}: {} — using defaults", VideoPlayerMod.MOD_ID, path, t.toString()); - PRELOAD_URLS = Collections.emptyList(); + maxPreloadMb = DEFAULT_MAX_PRELOAD_MB; + renderDistanceBlocks = DEFAULT_RENDER_DISTANCE; + preloadUrls = Collections.emptyList(); + CACHE_ENTRIES.clear(); } } - /** URLs to push to each joining player. Never null; possibly empty. */ - public static List preloadUrls() { - return PRELOAD_URLS; + // -- accessors --------------------------------------------------------------------------- + + /** Hard cap on a single client-side video download, in MB. */ + public static int maxPreloadMb() { return maxPreloadMb; } + + /** Same value in bytes. */ + public static long maxPreloadBytes() { return (long) maxPreloadMb * 1024L * 1024L; } + + /** Anchor BE view-distance cap, in blocks. */ + public static int renderDistanceBlocks() { return renderDistanceBlocks; } + + /** Legacy un-named preload list (still pushed at join). Never null. */ + public static List preloadUrls() { return preloadUrls; } + + /** Snapshot of name → url, insertion-ordered. Never null. */ + public static synchronized Map cacheEntries() { + return new LinkedHashMap<>(CACHE_ENTRIES); + } + + /** Lookup a single entry's URL by name. */ + public static synchronized String cacheUrl(String name) { + return CACHE_ENTRIES.get(name); + } + + /** + * Accept either a raw HTTP(S) URL or a previously-registered cache entry name and return + * the canonical URL to store on the anchor. Returns the trimmed input when it's already a + * URL, the looked-up URL when the input matches a cache entry name, or {@code null} if the + * input is neither (caller decides whether to fail or fall through). + */ + public static synchronized String resolveUrlOrName(String input) { + if (input == null) return null; + String t = input.trim(); + if (t.isEmpty()) return ""; + if (t.startsWith("http://") || t.startsWith("https://")) return t; + return CACHE_ENTRIES.get(t); + } + + // -- mutations (driven by /videocache add|remove) ----------------------------------------- + + /** Returns true if added; false if the name already exists. Persists on success. */ + public static synchronized boolean addCacheEntry(String name, String url) { + if (name == null || name.isEmpty() || url == null) return false; + if (CACHE_ENTRIES.containsKey(name)) return false; + CACHE_ENTRIES.put(name, url); + save(); + return true; + } + + /** Returns the removed URL, or null if no entry by that name. Persists on success. */ + public static synchronized String removeCacheEntry(String name) { + if (name == null) return null; + String removed = CACHE_ENTRIES.remove(name); + if (removed != null) save(); + return removed; + } + + // -- io ---------------------------------------------------------------------------------- + + private static Path configPath() { + return FabricLoader.getInstance().getConfigDir().resolve(FILE_NAME); + } + + private static String sanitizeUrl(String s) { + if (s == null) return null; + String t = s.trim(); + if (t.isEmpty() || t.length() > 256) return null; + if (!(t.startsWith("http://") || t.startsWith("https://"))) return null; + return t; } private static void writeDefault(Path path) throws IOException { Files.createDirectories(path.getParent()); - // Hand-rolled rather than Gson-serialized so we can carry a `_comment` field that - // explains the format directly inside the file. JsonObject root = new JsonObject(); root.addProperty("_comment", - "preload_urls: HTTP(S) video URLs broadcast to every player on join. " - + "Equivalent to running /videopreload per joiner. Max 256 chars per url."); - root.add("preload_urls", new com.google.gson.JsonArray()); + "max_preload_mb: per-video download cap (each client). " + + "render_distance_blocks: max distance at which a video anchor still renders. " + + "preload_urls: HTTP(S) videos auto-pushed to every player on join (no name). " + + "cache_entries: named entries managed by /videoCache add|list|remove."); + root.addProperty("max_preload_mb", DEFAULT_MAX_PRELOAD_MB); + root.addProperty("render_distance_blocks", DEFAULT_RENDER_DISTANCE); + root.add("preload_urls", new JsonArray()); + root.add("cache_entries", new JsonArray()); Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); Files.writeString(path, gson.toJson(root), StandardCharsets.UTF_8); } + + /** Persist current in-memory state. Best-effort; logs on failure. */ + private static void save() { + Path path = configPath(); + try { + Files.createDirectories(path.getParent()); + JsonObject root = new JsonObject(); + root.addProperty("_comment", + "max_preload_mb: per-video download cap (each client). " + + "render_distance_blocks: max distance at which a video anchor still renders. " + + "preload_urls: legacy un-named auto-preload list. " + + "cache_entries: managed by /videoCache add|list|remove."); + root.addProperty("max_preload_mb", maxPreloadMb); + root.addProperty("render_distance_blocks", renderDistanceBlocks); + JsonArray legacyArr = new JsonArray(); + for (String u : preloadUrls) legacyArr.add(u); + root.add("preload_urls", legacyArr); + JsonArray entriesArr = new JsonArray(); + for (Map.Entry e : CACHE_ENTRIES.entrySet()) { + JsonObject o = new JsonObject(); + o.addProperty("name", e.getKey()); + o.addProperty("url", e.getValue()); + entriesArr.add(o); + } + root.add("cache_entries", entriesArr); + Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + Files.writeString(path, gson.toJson(root), StandardCharsets.UTF_8); + } catch (Throwable t) { + VideoPlayerMod.LOG.warn("[{}] failed to save config: {}", + VideoPlayerMod.MOD_ID, t.toString()); + } + } } diff --git a/src/main/java/com/ejclaw/videoplayer/VideoPlayerMod.java b/src/main/java/com/ejclaw/videoplayer/VideoPlayerMod.java index 009e007..59b53be 100644 --- a/src/main/java/com/ejclaw/videoplayer/VideoPlayerMod.java +++ b/src/main/java/com/ejclaw/videoplayer/VideoPlayerMod.java @@ -1,10 +1,11 @@ package com.ejclaw.videoplayer; +import com.ejclaw.videoplayer.command.VideoCacheCommand; import com.ejclaw.videoplayer.command.VideoDeleteCommand; import com.ejclaw.videoplayer.command.VideoMuteCommand; import com.ejclaw.videoplayer.command.VideoPlaceCommand; -import com.ejclaw.videoplayer.command.VideoPreloadCommand; import com.ejclaw.videoplayer.command.VideoStickCommand; +import com.ejclaw.videoplayer.net.CachePolicyPayload; import com.ejclaw.videoplayer.net.PreloadPayload; import com.ejclaw.videoplayer.net.VideoPlayerNetwork; import com.ejclaw.videoplayer.registry.VideoPlayerBlockEntities; @@ -37,20 +38,33 @@ public class VideoPlayerMod implements ModInitializer { VideoPlaceCommand.register(dispatcher); VideoDeleteCommand.register(dispatcher); VideoMuteCommand.register(dispatcher); - VideoPreloadCommand.register(dispatcher); + VideoCacheCommand.register(dispatcher); }); - // When a player finishes joining, push every preload URL from the config so their - // client kicks off the background download. Reuses the same PreloadPayload that - // /videopreload sends, so the client-side caching path is identical. + // On join: (1) push the per-video download cap so the client knows whether to abort + // an over-cap stream, (2) replay every legacy preload_urls entry, (3) replay every + // named /videocache entry. Policy must go first so caps are honored before downloads + // start. Each PreloadPayload is fire-and-forget; clients post their own "[videopreload]" + // status lines when downloads finish. ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> { - java.util.List urls = VideoPlayerConfig.preloadUrls(); - if (urls.isEmpty()) return; - for (String url : urls) { - ServerPlayNetworking.send(handler.getPlayer(), new PreloadPayload(url)); + var player = handler.getPlayer(); + ServerPlayNetworking.send(player, new CachePolicyPayload( + VideoPlayerConfig.maxPreloadBytes(), + VideoPlayerConfig.renderDistanceBlocks())); + + int sent = 0; + for (String url : VideoPlayerConfig.preloadUrls()) { + ServerPlayNetworking.send(player, new PreloadPayload(url)); + sent++; + } + for (var e : VideoPlayerConfig.cacheEntries().entrySet()) { + ServerPlayNetworking.send(player, new PreloadPayload(e.getValue())); + sent++; + } + if (sent > 0) { + LOG.info("[{}] sent policy + {} preload(s) to {}", + MOD_ID, sent, player.getName().getString()); } - LOG.info("[{}] sent {} config preload(s) to {}", - MOD_ID, urls.size(), handler.getPlayer().getName().getString()); }); LOG.info("[{}] initialized", MOD_ID); diff --git a/src/main/java/com/ejclaw/videoplayer/client/ClientPolicy.java b/src/main/java/com/ejclaw/videoplayer/client/ClientPolicy.java new file mode 100644 index 0000000..7155d8b --- /dev/null +++ b/src/main/java/com/ejclaw/videoplayer/client/ClientPolicy.java @@ -0,0 +1,30 @@ +package com.ejclaw.videoplayer.client; + +import com.ejclaw.videoplayer.VideoPlayerMod; +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; + +/** + * Client-side mirror of the server's policy bundle (pushed via {@code CachePolicyPayload} + * on join). Currently just the anchor render-distance cap; the per-video download cap lives + * directly on {@link com.ejclaw.videoplayer.client.playback.VideoCache}. + * + *

Default 128 matches the legacy hard-coded value, so unpaired clients (e.g. dev tests + * with no JOIN packet, or older servers without the payload) render identically to before. + */ +@Environment(EnvType.CLIENT) +public final class ClientPolicy { + private ClientPolicy() {} + + private static volatile int renderDistanceBlocks = 128; + + public static int renderDistanceBlocks() { return renderDistanceBlocks; } + + public static void setRenderDistanceBlocks(int blocks) { + if (blocks < 16) blocks = 16; + if (blocks > 2048) blocks = 2048; + renderDistanceBlocks = blocks; + VideoPlayerMod.LOG.info("[{}] anchor render distance set to {} blocks", + VideoPlayerMod.MOD_ID, blocks); + } +} diff --git a/src/main/java/com/ejclaw/videoplayer/client/net/ClientNetworking.java b/src/main/java/com/ejclaw/videoplayer/client/net/ClientNetworking.java index cf80e22..e8ff10c 100644 --- a/src/main/java/com/ejclaw/videoplayer/client/net/ClientNetworking.java +++ b/src/main/java/com/ejclaw/videoplayer/client/net/ClientNetworking.java @@ -1,9 +1,12 @@ package com.ejclaw.videoplayer.client.net; import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity; +import com.ejclaw.videoplayer.client.ClientPolicy; import com.ejclaw.videoplayer.client.gui.VideoConfigScreen; import com.ejclaw.videoplayer.client.playback.VideoCache; import com.ejclaw.videoplayer.client.playback.VideoPlayback; +import com.ejclaw.videoplayer.net.CachePolicyPayload; +import com.ejclaw.videoplayer.net.DeleteCachePayload; import com.ejclaw.videoplayer.net.OpenScreenPayload; import com.ejclaw.videoplayer.net.PreloadPayload; import com.ejclaw.videoplayer.net.SyncAnchorPayload; @@ -40,5 +43,17 @@ public final class ClientNetworking { ClientPlayNetworking.registerGlobalReceiver(PreloadPayload.TYPE, (payload, context) -> { VideoCache.preload(payload.url()); }); + + // Server tells us the per-video download cap (bytes). Must arrive before PreloadPayload + // (the server sends policy first on JOIN), so we don't accidentally use the stale default. + ClientPlayNetworking.registerGlobalReceiver(CachePolicyPayload.TYPE, (payload, context) -> { + VideoCache.setMaxBytes(payload.maxBytes()); + ClientPolicy.setRenderDistanceBlocks(payload.renderDistanceBlocks()); + }); + + // /videocache remove — drop the URL from this client's disk cache. + ClientPlayNetworking.registerGlobalReceiver(DeleteCachePayload.TYPE, (payload, context) -> { + VideoCache.purge(payload.url()); + }); } } diff --git a/src/main/java/com/ejclaw/videoplayer/client/playback/JavaCvBackend.java b/src/main/java/com/ejclaw/videoplayer/client/playback/JavaCvBackend.java index 258b88d..a4bc993 100644 --- a/src/main/java/com/ejclaw/videoplayer/client/playback/JavaCvBackend.java +++ b/src/main/java/com/ejclaw/videoplayer/client/playback/JavaCvBackend.java @@ -164,16 +164,44 @@ public class JavaCvBackend implements VideoBackend { try { line.stop(); } catch (Throwable ignored) {} try { line.flush(); } catch (Throwable ignored) {} } - // Yank the grabber too so a blocked grab() inside an HTTP read returns promptly. - // JavaCV's close() is best-effort thread-safe — worst case we trip an AVERROR which - // the catch-all in runLoop swallows. - Object g = grabberHandle; - if (g != null) { - try { g.getClass().getMethod("close").invoke(g); } catch (Throwable ignored) {} - } + // CRITICAL: we do NOT call grabber.close() from this (caller) thread. The decoder's + // per-frame path is: + // + // frame = grab(grabber); // grabber-owned native memory + // src = frame.image[0]; // DirectByteBuffer over that memory + // need = src.remaining(); // (lock-free) + // srcAddr = MemoryUtil.memAddress(src); // (lock-free) + // synchronized (frameLock) { + // MemoryUtil.memCopy(srcAddr, ...); // reads from grabber-owned memory + // } + // + // Even if we held frameLock while closing the grabber, there's a window between + // grab() returning and entering the synchronized block where the decoder is holding a + // stale srcAddr — closing the grabber there frees the av_frame plane and the next + // memcpy crashes inside StubRoutines::jbyte_disjoint_arraycopy (exactly the 4K-delete + // crash dump we saw). So the safe rule is: only the decoder thread touches the + // grabber. External stop signals `running=false`, stops the audio line, interrupts the + // worker, and joins briefly; the worker's own `finally` calls grabber.close(). Inside + // the loop, grab() unblocks via the rw_timeout/timeout options (3 s, set in runLoop) + // even on a stuck HTTP read, so the join below normally returns within a frame. Thread t = worker; worker = null; - if (t != null) t.interrupt(); + if (t != null) { + t.interrupt(); + try { + t.join(2000); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + if (t.isAlive()) { + // Worker still blocked in native grab() — let it finish on its own. Its + // finally still closes the grabber when grab() eventually returns / throws. + // No native pointers leak in the meantime because we don't touch them here. + VideoPlayerMod.LOG.warn( + "[{}] decoder did not exit within 2 s of stop; orphaning until next grab() returns", + VideoPlayerMod.MOD_ID); + } + } ready = false; } @@ -299,10 +327,31 @@ public class JavaCvBackend implements VideoBackend { // top to absorb the burst-then-stall caused by SourceDataLine backpressure // pacing only at audio-buffer granularity. int need = src.remaining(); + // Reviewer-mandated sanity bounds: memCopy is a raw native copy with no + // fence against overrun. Validate against (a) the source buffer's own + // capacity (so a corrupt plane can't read past it) and (b) the expected + // RGBA frame size (width*height*4) (so an unexpectedly oversized plane + // can't smash the dst slot we'll allocate). If either fails, skip this + // frame and continue — the next grab() will give us a fresh one. + int expected = width * height * 4; + if (need > src.capacity()) { + VideoPlayerMod.LOG.warn("[{}] frame overruns source capacity (need={}, cap={}); skipping", + VideoPlayerMod.MOD_ID, need, src.capacity()); + need = 0; + } else if (need > expected) { + VideoPlayerMod.LOG.warn("[{}] frame larger than expected RGBA size (need={}, expected={}); skipping", + VideoPlayerMod.MOD_ID, need, expected); + need = 0; + } if (need > 0) { int srcPos = src.position(); long srcAddr = MemoryUtil.memAddress(src) + srcPos; synchronized (frameLock) { + // Recheck shutdown inside the lock: stopWorker() flipped running=false + // before signaling, so worker is the only writer here and grabber.close() + // only runs from this thread's finally — but the explicit check keeps + // the contract obvious to future readers. + if (!running.get() || closed) break; int idx = ringTail; if (ringBufs[idx] == null || ringBufs[idx].capacity() < need) { ringBufs[idx] = ByteBuffer.allocateDirect(need).order(ByteOrder.nativeOrder()); diff --git a/src/main/java/com/ejclaw/videoplayer/client/playback/VideoCache.java b/src/main/java/com/ejclaw/videoplayer/client/playback/VideoCache.java index bec767e..832d9bd 100644 --- a/src/main/java/com/ejclaw/videoplayer/client/playback/VideoCache.java +++ b/src/main/java/com/ejclaw/videoplayer/client/playback/VideoCache.java @@ -41,8 +41,49 @@ public final class VideoCache { /** urls whose download is currently in flight. */ private static final Set IN_FLIGHT = ConcurrentHashMap.newKeySet(); - /** Hard ceiling on a single preload — 512 MB. Keeps an accidental giant URL from filling disk. */ - private static final long MAX_BYTES = 512L * 1024 * 1024; + /** + * Hard ceiling on a single preload, in bytes. Default 1 GB so a fresh client without a + * policy packet (e.g. integrated server, dev test) still has a sensible cap. Overridden by + * {@link com.ejclaw.videoplayer.net.CachePolicyPayload} on join. + */ + private static volatile long MAX_BYTES = 1024L * 1024 * 1024; + + /** Server-driven override of the per-video cap. */ + public static void setMaxBytes(long bytes) { + if (bytes < 16L * 1024 * 1024) bytes = 16L * 1024 * 1024; + if (bytes > 16L * 1024 * 1024 * 1024) bytes = 16L * 1024 * 1024 * 1024; + MAX_BYTES = bytes; + VideoPlayerMod.LOG.info("[{}] preload cap set to {} MB", + VideoPlayerMod.MOD_ID, bytes / (1024 * 1024)); + } + + /** Server-driven delete of a cached URL. Removes from READY and from disk. */ + public static void purge(String url) { + if (url == null || url.isEmpty()) return; + Path p = READY.remove(url); + if (p == null) { + // Not in this session's index, but the file may still be on disk from a prior run. + // Reconstruct the path by hash + extension and try to delete it. + try { + Path dir = cacheDir(); + if (dir != null) { + Path guess = dir.resolve(sha256(url) + extensionFromUrl(url)); + if (Files.exists(guess)) p = guess; + } + } catch (Throwable ignored) {} + } + if (p != null) { + try { + boolean gone = Files.deleteIfExists(p); + VideoPlayerMod.LOG.info("[{}] purge: {} -> deleted={} ({})", + VideoPlayerMod.MOD_ID, url, gone, p.getFileName()); + if (gone) notifyChat("[videocache] 캐시 삭제: " + url, ChatFormatting.YELLOW); + } catch (Throwable t) { + VideoPlayerMod.LOG.warn("[{}] purge failed for {}: {}", + VideoPlayerMod.MOD_ID, url, t.toString()); + } + } + } /** Kick off a background download. No-op if already cached or in flight. */ public static void preload(String url) { @@ -133,11 +174,12 @@ public final class VideoCache { while ((n = in.read(buf)) >= 0) { total += n; if (total > MAX_BYTES) { + long capMb = MAX_BYTES / (1024 * 1024); VideoPlayerMod.LOG.warn( "[{}] preload: {} exceeded {} MB cap; aborting", - VideoPlayerMod.MOD_ID, url, MAX_BYTES / (1024 * 1024)); + VideoPlayerMod.MOD_ID, url, capMb); try { Files.deleteIfExists(partPath); } catch (Throwable ignored) {} - notifyChat("[videopreload] 실패 (512MB 초과): " + url, ChatFormatting.RED); + notifyChat("[videopreload] 실패 (" + capMb + "MB 초과): " + url, ChatFormatting.RED); return; } out.write(buf, 0, n); diff --git a/src/main/java/com/ejclaw/videoplayer/client/render/VideoAnchorRenderer.java b/src/main/java/com/ejclaw/videoplayer/client/render/VideoAnchorRenderer.java index c8d300f..e27b238 100644 --- a/src/main/java/com/ejclaw/videoplayer/client/render/VideoAnchorRenderer.java +++ b/src/main/java/com/ejclaw/videoplayer/client/render/VideoAnchorRenderer.java @@ -1,6 +1,7 @@ package com.ejclaw.videoplayer.client.render; import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity; +import com.ejclaw.videoplayer.client.ClientPolicy; import com.ejclaw.videoplayer.client.playback.VideoPlayback; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.math.Axis; @@ -124,7 +125,9 @@ public class VideoAnchorRenderer implements BlockEntityRenderer } — name a URL, store it in server config, and broadcast a + * preload request to every client. + *
{@code /videocache list} — print the named index with clickable URLs. + *
{@code /videocache remove } — drop the entry from server config and tell every client + * to delete the matching cache file. + * + *

Replaces the old {@code /videopreload}. Same permission gate + * ({@link Permissions#COMMANDS_GAMEMASTER}) so command blocks can drive it. + */ +public final class VideoCacheCommand { + private VideoCacheCommand() {} + + public static void register(CommandDispatcher dispatcher) { + dispatcher.register(build("videoCache")); + } + + private static LiteralArgumentBuilder build(String root) { + return Commands.literal(root) + .requires(s -> s.permissions().hasPermission(Permissions.COMMANDS_GAMEMASTER)) + .then(Commands.literal("add") + .then(Commands.argument("name", StringArgumentType.word()) + .then(Commands.argument("url", StringArgumentType.greedyString()) + .executes(VideoCacheCommand::runAdd)))) + .then(Commands.literal("list") + .executes(VideoCacheCommand::runList)) + .then(Commands.literal("remove") + .then(Commands.argument("name", StringArgumentType.word()) + .executes(VideoCacheCommand::runRemove))); + } + + private static int runAdd(CommandContext ctx) throws CommandSyntaxException { + CommandSourceStack src = ctx.getSource(); + String name = StringArgumentType.getString(ctx, "name").trim(); + String url = StringArgumentType.getString(ctx, "url").trim(); + + if (name.isEmpty() || name.length() > 64) { + src.sendFailure(Component.literal("이름은 1~64자여야 합니다")); + return 0; + } + if (url.isEmpty() || !(url.startsWith("http://") || url.startsWith("https://"))) { + src.sendFailure(Component.literal("url 은 http:// 또는 https:// 로 시작해야 합니다")); + return 0; + } + if (url.length() > 256) { + src.sendFailure(Component.literal("url 이 너무 깁니다 (최대 256자)")); + return 0; + } + if (VideoPlayerConfig.cacheUrl(name) != null) { + src.sendFailure(Component.literal("이미 사용 중인 이름입니다: " + name)); + return 0; + } + if (!VideoPlayerConfig.addCacheEntry(name, url)) { + src.sendFailure(Component.literal("저장 실패: 이름 중복 또는 IO 오류")); + return 0; + } + + MinecraftServer server = src.getServer(); + PreloadPayload payload = new PreloadPayload(url); + int sent = 0; + for (ServerPlayer p : PlayerLookup.all(server)) { + ServerPlayNetworking.send(p, payload); + sent++; + } + final int sentFinal = sent; + src.sendSuccess(() -> Component.literal( + "[videocache] 추가됨: " + name + " → " + url + + " (" + sentFinal + " 클라이언트에 preload 전송)"), false); + return 1; + } + + private static int runList(CommandContext ctx) { + CommandSourceStack src = ctx.getSource(); + Map entries = VideoPlayerConfig.cacheEntries(); + if (entries.isEmpty()) { + src.sendSuccess(() -> Component.literal("[videocache] 저장된 항목이 없습니다") + .withStyle(ChatFormatting.GRAY), false); + return 0; + } + src.sendSuccess(() -> Component.literal("[videocache] 저장된 항목 " + entries.size() + "개:") + .withStyle(ChatFormatting.YELLOW), false); + for (Map.Entry e : entries.entrySet()) { + String url = e.getValue(); + ClickEvent click; + try { + click = new ClickEvent.OpenUrl(URI.create(url)); + } catch (Throwable t) { + click = null; // bad URI — show without click action rather than failing the whole list + } + Style urlStyle = Style.EMPTY.withColor(ChatFormatting.AQUA).withUnderlined(true); + if (click != null) urlStyle = urlStyle.withClickEvent(click); + MutableComponent line = Component.literal(" • " + e.getKey() + " : ") + .withStyle(ChatFormatting.WHITE) + .append(Component.literal(url).withStyle(urlStyle)); + src.sendSuccess(() -> line, false); + } + return entries.size(); + } + + private static int runRemove(CommandContext ctx) throws CommandSyntaxException { + CommandSourceStack src = ctx.getSource(); + String name = StringArgumentType.getString(ctx, "name").trim(); + String url = VideoPlayerConfig.removeCacheEntry(name); + if (url == null) { + src.sendFailure(Component.literal("해당 이름의 항목이 없습니다: " + name)); + return 0; + } + MinecraftServer server = src.getServer(); + DeleteCachePayload payload = new DeleteCachePayload(url); + int sent = 0; + for (ServerPlayer p : PlayerLookup.all(server)) { + ServerPlayNetworking.send(p, payload); + sent++; + } + final int sentFinal = sent; + src.sendSuccess(() -> Component.literal( + "[videocache] 삭제됨: " + name + " → " + url + + " (" + sentFinal + " 클라이언트에 cache_delete 전송)"), false); + return 1; + } +} diff --git a/src/main/java/com/ejclaw/videoplayer/command/VideoDeleteCommand.java b/src/main/java/com/ejclaw/videoplayer/command/VideoDeleteCommand.java index be7a787..b2fe6b7 100644 --- a/src/main/java/com/ejclaw/videoplayer/command/VideoDeleteCommand.java +++ b/src/main/java/com/ejclaw/videoplayer/command/VideoDeleteCommand.java @@ -19,7 +19,6 @@ public final class VideoDeleteCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(build("videoDelete")); - dispatcher.register(build("videodelete")); } private static com.mojang.brigadier.builder.LiteralArgumentBuilder diff --git a/src/main/java/com/ejclaw/videoplayer/command/VideoMuteCommand.java b/src/main/java/com/ejclaw/videoplayer/command/VideoMuteCommand.java index ca4a25c..873de63 100644 --- a/src/main/java/com/ejclaw/videoplayer/command/VideoMuteCommand.java +++ b/src/main/java/com/ejclaw/videoplayer/command/VideoMuteCommand.java @@ -22,7 +22,6 @@ public final class VideoMuteCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(build("videoMute")); - dispatcher.register(build("videomute")); } private static com.mojang.brigadier.builder.LiteralArgumentBuilder diff --git a/src/main/java/com/ejclaw/videoplayer/command/VideoPlaceCommand.java b/src/main/java/com/ejclaw/videoplayer/command/VideoPlaceCommand.java index 574b70b..4cfbdf5 100644 --- a/src/main/java/com/ejclaw/videoplayer/command/VideoPlaceCommand.java +++ b/src/main/java/com/ejclaw/videoplayer/command/VideoPlaceCommand.java @@ -1,5 +1,6 @@ package com.ejclaw.videoplayer.command; +import com.ejclaw.videoplayer.VideoPlayerConfig; import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity; import com.ejclaw.videoplayer.net.SyncAnchorPayload; import com.ejclaw.videoplayer.registry.VideoPlayerBlocks; @@ -27,7 +28,6 @@ public final class VideoPlaceCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(build("videoPlace")); - dispatcher.register(build("videoplace")); } private static com.mojang.brigadier.builder.LiteralArgumentBuilder @@ -54,9 +54,14 @@ public final class VideoPlaceCommand { } int width = IntegerArgumentType.getInteger(ctx, "width"); int height = IntegerArgumentType.getInteger(ctx, "height"); - String url = StringArgumentType.getString(ctx, "url").trim(); - if (!url.isEmpty() && !(url.startsWith("http://") || url.startsWith("https://"))) { - src.sendFailure(Component.literal("url must be http:// or https:// (or empty)")); + String raw = StringArgumentType.getString(ctx, "url").trim(); + // Accept either an http(s) URL or a /videoCache add entry: resolveUrlOrName() + // returns the canonical URL in both cases, or null when a non-URL string didn't match + // any named entry. + String url = VideoPlayerConfig.resolveUrlOrName(raw); + if (url == null) { + src.sendFailure(Component.literal( + "url 은 http(s):// 로 시작하거나 /videoCache add 로 등록된 이름이어야 합니다: " + raw)); return 0; } if (url.length() > 256) url = url.substring(0, 256); diff --git a/src/main/java/com/ejclaw/videoplayer/command/VideoPreloadCommand.java b/src/main/java/com/ejclaw/videoplayer/command/VideoPreloadCommand.java deleted file mode 100644 index 27e5f95..0000000 --- a/src/main/java/com/ejclaw/videoplayer/command/VideoPreloadCommand.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.ejclaw.videoplayer.command; - -import com.ejclaw.videoplayer.net.PreloadPayload; -import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.arguments.StringArgumentType; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.fabricmc.fabric.api.networking.v1.PlayerLookup; -import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.network.chat.Component; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.permissions.Permissions; - -/** - * {@code /videoPreload } — broadcast a preload request to every connected client so each - * client fully downloads the URL into its local {@code video_player_cache/} folder. Subsequent - * {@code /videoPlace} calls (or right-click placements) that use the same URL will then play - * from the local file, eliminating mid-stream stutter. - * - *

Uses the same {@link Permissions#COMMANDS_GAMEMASTER} gate as {@code /videoPlace} et al., - * so command blocks (which run at op level 2 by default) can invoke it. - */ -public final class VideoPreloadCommand { - private VideoPreloadCommand() {} - - public static void register(CommandDispatcher dispatcher) { - dispatcher.register(build("videoPreload")); - dispatcher.register(build("videopreload")); - } - - private static com.mojang.brigadier.builder.LiteralArgumentBuilder - build(String name) { - return Commands.literal(name) - .requires(s -> s.permissions().hasPermission(Permissions.COMMANDS_GAMEMASTER)) - .then(Commands.argument("url", StringArgumentType.greedyString()) - .executes(VideoPreloadCommand::run)); - } - - private static int run(com.mojang.brigadier.context.CommandContext ctx) - throws CommandSyntaxException { - CommandSourceStack src = ctx.getSource(); - String url = StringArgumentType.getString(ctx, "url").trim(); - if (url.isEmpty()) { - src.sendFailure(Component.literal("url is required")); - return 0; - } - if (!(url.startsWith("http://") || url.startsWith("https://"))) { - src.sendFailure(Component.literal("url must be http:// or https://")); - return 0; - } - if (url.length() > 256) { - src.sendFailure(Component.literal("url too long (max 256)")); - return 0; - } - - MinecraftServer server = src.getServer(); - PreloadPayload payload = new PreloadPayload(url); - int sent = 0; - for (ServerPlayer p : PlayerLookup.all(server)) { - ServerPlayNetworking.send(p, payload); - sent++; - } - final int sentFinal = sent; - // Use sendSuccess(..., false) so the chat noise is local-only and command blocks don't - // spam every operator on each tick. Be explicit that this is fire-and-forget: each - // client posts its own "[videopreload] 완료" chat line when the download finishes. - src.sendSuccess(() -> Component.literal( - "preload 요청을 " + sentFinal + " 클라이언트에 전송: " + payload.url() - + " (완료 알림 후 재생하세요)"), false); - return sent; - } -} diff --git a/src/main/java/com/ejclaw/videoplayer/command/VideoStickCommand.java b/src/main/java/com/ejclaw/videoplayer/command/VideoStickCommand.java index ffdae75..c5bad18 100644 --- a/src/main/java/com/ejclaw/videoplayer/command/VideoStickCommand.java +++ b/src/main/java/com/ejclaw/videoplayer/command/VideoStickCommand.java @@ -14,9 +14,6 @@ public final class VideoStickCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(Commands.literal("videoStick") .executes(ctx -> run(ctx.getSource()))); - // Lowercase alias — Brigadier is case-sensitive. - dispatcher.register(Commands.literal("videostick") - .executes(ctx -> run(ctx.getSource()))); } private static int run(CommandSourceStack source) { diff --git a/src/main/java/com/ejclaw/videoplayer/net/CachePolicyPayload.java b/src/main/java/com/ejclaw/videoplayer/net/CachePolicyPayload.java new file mode 100644 index 0000000..8a4505e --- /dev/null +++ b/src/main/java/com/ejclaw/videoplayer/net/CachePolicyPayload.java @@ -0,0 +1,29 @@ +package com.ejclaw.videoplayer.net; + +import com.ejclaw.videoplayer.VideoPlayerMod; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; + +/** + * S2C — broadcasts the server-configured client-side policy bundle on join, before any + * {@link PreloadPayload}. Currently carries: {@code maxBytes} (per-video download cap) and + * {@code renderDistanceBlocks} (anchor BE view-distance cap). + */ +public record CachePolicyPayload(long maxBytes, int renderDistanceBlocks) implements CustomPacketPayload { + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(Identifier.fromNamespaceAndPath(VideoPlayerMod.MOD_ID, "cache_policy")); + + public static final StreamCodec CODEC = StreamCodec.composite( + ByteBufCodecs.VAR_LONG, CachePolicyPayload::maxBytes, + ByteBufCodecs.VAR_INT, CachePolicyPayload::renderDistanceBlocks, + CachePolicyPayload::new + ); + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/com/ejclaw/videoplayer/net/DeleteCachePayload.java b/src/main/java/com/ejclaw/videoplayer/net/DeleteCachePayload.java new file mode 100644 index 0000000..ab4232b --- /dev/null +++ b/src/main/java/com/ejclaw/videoplayer/net/DeleteCachePayload.java @@ -0,0 +1,28 @@ +package com.ejclaw.videoplayer.net; + +import com.ejclaw.videoplayer.VideoPlayerMod; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.codec.StreamCodec; +import net.minecraft.network.protocol.common.custom.CustomPacketPayload; +import net.minecraft.resources.Identifier; + +/** + * S2C — tell connected clients to drop a previously preloaded URL from their on-disk cache. + * Sent by {@code /videocache remove }. Each client deletes the matching cache file and + * drops it from {@code VideoCache.READY}. + */ +public record DeleteCachePayload(String url) implements CustomPacketPayload { + public static final CustomPacketPayload.Type TYPE = + new CustomPacketPayload.Type<>(Identifier.fromNamespaceAndPath(VideoPlayerMod.MOD_ID, "cache_delete")); + + public static final StreamCodec CODEC = StreamCodec.composite( + ByteBufCodecs.STRING_UTF8, DeleteCachePayload::url, + DeleteCachePayload::new + ); + + @Override + public Type type() { + return TYPE; + } +} diff --git a/src/main/java/com/ejclaw/videoplayer/net/VideoPlayerNetwork.java b/src/main/java/com/ejclaw/videoplayer/net/VideoPlayerNetwork.java index 5ac52a0..02ac50d 100644 --- a/src/main/java/com/ejclaw/videoplayer/net/VideoPlayerNetwork.java +++ b/src/main/java/com/ejclaw/videoplayer/net/VideoPlayerNetwork.java @@ -1,5 +1,6 @@ package com.ejclaw.videoplayer.net; +import com.ejclaw.videoplayer.VideoPlayerConfig; import com.ejclaw.videoplayer.VideoPlayerMod; import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity; import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; @@ -25,6 +26,8 @@ public final class VideoPlayerNetwork { PayloadTypeRegistry.clientboundPlay().register(OpenScreenPayload.TYPE, OpenScreenPayload.CODEC); PayloadTypeRegistry.clientboundPlay().register(SyncAnchorPayload.TYPE, SyncAnchorPayload.CODEC); PayloadTypeRegistry.clientboundPlay().register(PreloadPayload.TYPE, PreloadPayload.CODEC); + PayloadTypeRegistry.clientboundPlay().register(CachePolicyPayload.TYPE, CachePolicyPayload.CODEC); + PayloadTypeRegistry.clientboundPlay().register(DeleteCachePayload.TYPE, DeleteCachePayload.CODEC); // C2S PayloadTypeRegistry.serverboundPlay().register(SaveConfigPayload.TYPE, SaveConfigPayload.CODEC); PayloadTypeRegistry.serverboundPlay().register(DeleteAnchorPayload.TYPE, DeleteAnchorPayload.CODEC); @@ -95,13 +98,13 @@ public final class VideoPlayerNetwork { private static String trimUrl(String s) { if (s == null) return ""; - String t = s.trim(); - if (t.length() > 256) t = t.substring(0, 256); - // SPEC §4.4: only https?:// or empty - if (!t.isEmpty() && !(t.startsWith("http://") || t.startsWith("https://"))) { - return ""; - } - return t; + // GUI / C2S accepts either an http(s) URL or a /videoCache add . Names resolve + // to their stored URL; URLs pass through verbatim. Anything else collapses to empty + // (SPEC §4.4: anchors with non-URL urls are no-ops). + String resolved = VideoPlayerConfig.resolveUrlOrName(s); + if (resolved == null) return ""; + if (resolved.length() > 256) resolved = resolved.substring(0, 256); + return resolved; } private static int clamp(int v, int lo, int hi) {