Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e242bb675 | ||
|
|
849e53096c | ||
|
|
c53ebcc30d | ||
|
|
6896870186 | ||
|
|
9b99283b70 | ||
|
|
cee01bd448 | ||
|
|
3d4843dd0d |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,5 +1,6 @@
|
|||||||
.gradle/
|
.gradle/
|
||||||
build/
|
build/
|
||||||
|
dist/
|
||||||
out/
|
out/
|
||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|||||||
20
README.md
20
README.md
@@ -3,7 +3,7 @@
|
|||||||
마인크래프트 안에서 임의의 동영상 URL을 벽·바닥·천장에 평면으로 재생하는 Fabric 모드.
|
마인크래프트 안에서 임의의 동영상 URL을 벽·바닥·천장에 평면으로 재생하는 Fabric 모드.
|
||||||
|
|
||||||
- 모드 ID: `video_player`
|
- 모드 ID: `video_player`
|
||||||
- 현재 버전: **0.4.8**
|
- 현재 버전: **0.4.12**
|
||||||
- 마인크래프트 버전: **26.1.2**
|
- 마인크래프트 버전: **26.1.2**
|
||||||
- 필요 Java: **25** (마인크래프트 26.x 가 요구함)
|
- 필요 Java: **25** (마인크래프트 26.x 가 요구함)
|
||||||
|
|
||||||
@@ -51,23 +51,23 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
https://cdn.modrinth.com/data/P7dR8mSH/versions/Sy2Bq7Xc/fabric-api-0.149.0%2B26.1.2.jar
|
https://cdn.modrinth.com/data/P7dR8mSH/versions/Sy2Bq7Xc/fabric-api-0.149.0%2B26.1.2.jar
|
||||||
- 더 최신 빌드를 찾을 땐: https://modrinth.com/mod/fabric-api/versions → 페이지에서 게임 버전 필터 `26.1.2` 를 직접 선택. (URL 파라미터 필터가 듣지 않는 경우가 있어서 페이지 안에서 한 번 더 확인하는 게 안전합니다.)
|
- 더 최신 빌드를 찾을 땐: https://modrinth.com/mod/fabric-api/versions → 페이지에서 게임 버전 필터 `26.1.2` 를 직접 선택. (URL 파라미터 필터가 듣지 않는 경우가 있어서 페이지 안에서 한 번 더 확인하는 게 안전합니다.)
|
||||||
- 받은 `fabric-api-0.149.0+26.1.2.jar` 를 `mods` 폴더에 넣습니다.
|
- 받은 `fabric-api-0.149.0+26.1.2.jar` 를 `mods` 폴더에 넣습니다.
|
||||||
2. **video_player** (이 모드, 0.4.8 부터 JavaCV 가 jar 안에 포함됨)
|
2. **video_player** (이 모드, 0.4.12 부터 JavaCV 가 jar 안에 포함됨)
|
||||||
- 다운로드: https://git.tkrmagid.kr/tkrmagid/mc_video_player_mod/releases
|
- 다운로드: https://git.tkrmagid.kr/tkrmagid/mc_video_player_mod/releases
|
||||||
- 자신의 OS·CPU 에 맞는 jar **한 개** 만 받아서 `mods` 폴더에 넣으면 됩니다 (별도 JavaCV 설치 불필요):
|
- 자신의 OS·CPU 에 맞는 jar **한 개** 만 받아서 `mods` 폴더에 넣으면 됩니다 (별도 JavaCV 설치 불필요):
|
||||||
- Windows 64bit: `video_player-windows-x86_64-0.4.8.jar` (~32MB)
|
- Windows 64bit: `video_player-windows-x86_64-0.4.12.jar` (~32MB)
|
||||||
- macOS Intel: `video_player-macosx-x86_64-0.4.8.jar` (~24MB)
|
- macOS Intel: `video_player-macosx-x86_64-0.4.12.jar` (~24MB)
|
||||||
- macOS Apple Silicon (M1/M2/M3/M4): `video_player-macosx-arm64-0.4.8.jar` (~21MB)
|
- macOS Apple Silicon (M1/M2/M3/M4): `video_player-macosx-arm64-0.4.12.jar` (~21MB)
|
||||||
- Linux 64bit: `video_player-linux-x86_64-0.4.8.jar` (~27MB)
|
- Linux 64bit: `video_player-linux-x86_64-0.4.12.jar` (~27MB)
|
||||||
- 자기 OS 가 헷갈리면: Windows 는 거의 다 `windows-x86_64`, 인텔맥은 `macosx-x86_64`, 애플 실리콘 맥은 `macosx-arm64`, 리눅스는 `linux-x86_64`.
|
- 자기 OS 가 헷갈리면: Windows 는 거의 다 `windows-x86_64`, 인텔맥은 `macosx-x86_64`, 애플 실리콘 맥은 `macosx-arm64`, 리눅스는 `linux-x86_64`.
|
||||||
|
|
||||||
이전 버전(`video_player-0.4.0.jar`, `0.4.2.jar`, `0.4.3.jar`, `0.3.x.jar` 등)이 mods 폴더에 남아있다면 **반드시 삭제**하세요. 두 개가 같이 있으면 마인크래프트가 충돌로 켜지지 않습니다. 0.4.7 이하에서 쓰던 JVM 인수(`-Xbootclasspath/a:...javacv...`) 도 0.4.8 부터는 **빼주세요** — 모드 jar 안에 같은 JavaCV 가 들어있어서 부트클래스패스의 것과 충돌해 검은 화면이 날 수 있습니다.
|
이전 버전(`video_player-0.4.0.jar`, `0.4.2.jar`, `0.4.3.jar`, `0.3.x.jar` 등)이 mods 폴더에 남아있다면 **반드시 삭제**하세요. 두 개가 같이 있으면 마인크래프트가 충돌로 켜지지 않습니다. 0.4.7 이하에서 쓰던 JVM 인수(`-Xbootclasspath/a:...javacv...`) 도 0.4.12 부터는 **빼주세요** — 모드 jar 안에 같은 JavaCV 가 들어있어서 부트클래스패스의 것과 충돌해 검은 화면이 날 수 있습니다.
|
||||||
|
|
||||||
### STEP 5. 잘 설치됐는지 확인
|
### STEP 5. 잘 설치됐는지 확인
|
||||||
|
|
||||||
게임 안에서 채팅창에 `/videostick` 을 입력하세요. 정상이라면:
|
게임 안에서 채팅창에 `/videostick` 을 입력하세요. 정상이라면:
|
||||||
|
|
||||||
- 인벤토리에 **비디오 스틱** 아이템이 들어옵니다 (보라/검정 missing-texture 가 아니라 작대기 모양 아이콘).
|
- 인벤토리에 **비디오 스틱** 아이템이 들어옵니다 (보라/검정 missing-texture 가 아니라 작대기 모양 아이콘).
|
||||||
- 보라/검정 missing texture 가 나오면 **STEP 4** 에서 이전 버전 jar(`video_player-0.4.0.jar` / `0.4.1.jar` 등)가 mods 폴더에 같이 남아있는 경우입니다. 다 지우고 `0.4.8` 만 남기고 다시 시작하세요. (0.4.1 이하는 Fabric 26.1.2 model 로더가 unprefixed `item/generated` parent 를 거부해서 스틱 아이콘이 missing-model 큐브로 보입니다 — 0.4.2 에서 수정됨.)
|
- 보라/검정 missing texture 가 나오면 **STEP 4** 에서 이전 버전 jar(`video_player-0.4.0.jar` / `0.4.1.jar` 등)가 mods 폴더에 같이 남아있는 경우입니다. 다 지우고 `0.4.12` 만 남기고 다시 시작하세요. (0.4.1 이하는 Fabric 26.1.2 model 로더가 unprefixed `item/generated` parent 를 거부해서 스틱 아이콘이 missing-model 큐브로 보입니다 — 0.4.2 에서 수정됨.)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -172,7 +172,7 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
```sh
|
```sh
|
||||||
JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64 ./gradlew build
|
JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64 ./gradlew build
|
||||||
```
|
```
|
||||||
산출물: `build/libs/video_player-0.4.8.jar` (~85KB)
|
산출물: `build/libs/video_player-0.4.12.jar` (~85KB)
|
||||||
|
|
||||||
플랫폼별 fat jar (JavaCV 1.5.13 + ffmpeg 8.0.1 네이티브 nested):
|
플랫폼별 fat jar (JavaCV 1.5.13 + ffmpeg 8.0.1 네이티브 nested):
|
||||||
```sh
|
```sh
|
||||||
@@ -181,7 +181,7 @@ JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64 ./gradlew clean build -Pplatform=li
|
|||||||
JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64 ./gradlew clean build -Pplatform=macosx-x86_64
|
JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64 ./gradlew clean build -Pplatform=macosx-x86_64
|
||||||
JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64 ./gradlew clean build -Pplatform=macosx-arm64
|
JAVA_HOME=/usr/lib/jvm/java-25-openjdk-amd64 ./gradlew clean build -Pplatform=macosx-arm64
|
||||||
```
|
```
|
||||||
산출물: `build/libs/video_player-<platform>-0.4.8.jar` (~21-32MB, jar 내부에 nested 로 javacv/javacpp/ffmpeg jar 5개 포함, Fabric loader 가 런타임에 classpath 로 풀어서 로딩)
|
산출물: `build/libs/video_player-<platform>-0.4.12.jar` (~21-32MB, jar 내부에 nested 로 javacv/javacpp/ffmpeg jar 5개 포함, Fabric loader 가 런타임에 classpath 로 풀어서 로딩)
|
||||||
|
|
||||||
JavaCV를 직접 의존성으로 가져오는 경우의 Maven 좌표:
|
JavaCV를 직접 의존성으로 가져오는 경우의 Maven 좌표:
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ org.gradle.configuration-cache=false
|
|||||||
|
|
||||||
# Mod
|
# Mod
|
||||||
mod_id=video_player
|
mod_id=video_player
|
||||||
mod_version=0.4.8
|
mod_version=0.4.15
|
||||||
maven_group=com.ejclaw.videoplayer
|
maven_group=com.ejclaw.videoplayer
|
||||||
archives_base_name=video_player
|
archives_base_name=video_player
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package com.ejclaw.videoplayer;
|
|||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.google.gson.Gson;
|
||||||
import com.google.gson.GsonBuilder;
|
import com.google.gson.GsonBuilder;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
import com.google.gson.JsonObject;
|
import com.google.gson.JsonObject;
|
||||||
import com.google.gson.JsonParser;
|
import com.google.gson.JsonParser;
|
||||||
import net.fabricmc.loader.api.FabricLoader;
|
import net.fabricmc.loader.api.FabricLoader;
|
||||||
@@ -12,88 +14,312 @@ import java.nio.file.Files;
|
|||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Server-side mod config, stored at {@code <gameDir>/config/video_player.json}.
|
* Server-side mod config, stored at {@code <gameDir>/config/video_player.json}.
|
||||||
*
|
*
|
||||||
* <p>Format (auto-generated on first start):
|
* <p>Schema (auto-generated on first start):
|
||||||
* <pre>{@code
|
* <pre>{@code
|
||||||
* {
|
* {
|
||||||
* // List of HTTP(S) video URLs that the server will tell every player to preload
|
* "max_preload_mb": 1024,
|
||||||
* // into their local video_player_cache/ folder when they join. Identical to running
|
|
||||||
* // /videopreload <url> for each joining player.
|
|
||||||
* "preload_urls": [
|
* "preload_urls": [
|
||||||
* "https://example.com/intro.mp4"
|
* "https://example.com/intro.mp4"
|
||||||
|
* ],
|
||||||
|
* "cache_entries": [
|
||||||
|
* { "name": "intro", "url": "https://example.com/intro.mp4" }
|
||||||
* ]
|
* ]
|
||||||
* }
|
* }
|
||||||
* }</pre>
|
* }</pre>
|
||||||
*
|
*
|
||||||
* <p>Why a list and not a dedicated tool: the same {@link
|
* <p>{@code max_preload_mb} is the hard ceiling each client enforces on a single video download
|
||||||
* com.ejclaw.videoplayer.net.PreloadPayload} that powers {@code /videopreload} is reused, so the
|
* (default 1024 MB ≈ 1 GB; enough headroom for ~50 short FHD clips). Pushed to every client on
|
||||||
* client-side cache, chat feedback, and {@code /videoplace} → cache lookup paths all behave
|
* join via {@link com.ejclaw.videoplayer.net.CachePolicyPayload}.
|
||||||
* identically for config-driven and command-driven preloads.
|
*
|
||||||
|
* <p>{@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.
|
||||||
|
*
|
||||||
|
* <p>{@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 {
|
public final class VideoPlayerConfig {
|
||||||
private VideoPlayerConfig() {}
|
private VideoPlayerConfig() {}
|
||||||
|
|
||||||
private static final String FILE_NAME = "video_player.json";
|
private static final String FILE_NAME = "video_player.json";
|
||||||
private static volatile List<String> PRELOAD_URLS = Collections.emptyList();
|
|
||||||
|
/**
|
||||||
|
* Default per-video download cap in MB. Sized to allow a single 4K short clip
|
||||||
|
* (≈25 Mbps × 60 s ≈ 190 MB, with headroom for higher-bitrate sources). Per-video
|
||||||
|
* cap is intentionally separate from the total-cache cap below.
|
||||||
|
*/
|
||||||
|
private static final int DEFAULT_MAX_PRELOAD_MB = 2048;
|
||||||
|
/**
|
||||||
|
* Default total-cache cap in MB. Sized to comfortably fit ~50 short FHD clips:
|
||||||
|
* FHD H.264 at ~5 Mbps × 20 s ≈ 12.5 MB, so 50 × 15 MB ≈ 750 MB with headroom.
|
||||||
|
*/
|
||||||
|
private static final int DEFAULT_MAX_CACHE_MB = 750;
|
||||||
|
/** 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 maxCacheMb = DEFAULT_MAX_CACHE_MB;
|
||||||
|
private static volatile int renderDistanceBlocks = DEFAULT_RENDER_DISTANCE;
|
||||||
|
private static volatile List<String> preloadUrls = Collections.emptyList();
|
||||||
|
/** Insertion-ordered name → url. Mutated only under the class monitor. */
|
||||||
|
private static final Map<String, String> CACHE_ENTRIES = new LinkedHashMap<>();
|
||||||
|
|
||||||
/** Load (or create) the config file. Called once during mod initialization. */
|
/** Load (or create) the config file. Called once during mod initialization. */
|
||||||
public static void load() {
|
public static synchronized void load() {
|
||||||
Path path = FabricLoader.getInstance().getConfigDir().resolve(FILE_NAME);
|
Path path = configPath();
|
||||||
try {
|
try {
|
||||||
if (!Files.exists(path)) {
|
if (!Files.exists(path)) {
|
||||||
writeDefault(path);
|
writeDefault(path);
|
||||||
VideoPlayerMod.LOG.info("[{}] created default config at {}",
|
VideoPlayerMod.LOG.info("[{}] created default config at {}",
|
||||||
VideoPlayerMod.MOD_ID, path);
|
VideoPlayerMod.MOD_ID, path);
|
||||||
PRELOAD_URLS = Collections.emptyList();
|
maxPreloadMb = DEFAULT_MAX_PRELOAD_MB;
|
||||||
|
maxCacheMb = DEFAULT_MAX_CACHE_MB;
|
||||||
|
preloadUrls = Collections.emptyList();
|
||||||
|
CACHE_ENTRIES.clear();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
String raw = Files.readString(path, StandardCharsets.UTF_8);
|
String raw = Files.readString(path, StandardCharsets.UTF_8);
|
||||||
JsonObject json = JsonParser.parseString(raw).getAsJsonObject();
|
JsonObject json = JsonParser.parseString(raw).getAsJsonObject();
|
||||||
|
|
||||||
|
// Track whether any expected key was missing; if so, we rewrite the file at the
|
||||||
|
// end so users don't have to delete their config to pick up new options.
|
||||||
|
boolean augmented = false;
|
||||||
|
|
||||||
|
// max_preload_mb (per-video cap, sanity-clamped to [16, 16384])
|
||||||
|
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();
|
||||||
|
} else {
|
||||||
|
augmented = true;
|
||||||
|
}
|
||||||
|
if (cap < 16) cap = 16;
|
||||||
|
if (cap > 16384) cap = 16384;
|
||||||
|
maxPreloadMb = cap;
|
||||||
|
|
||||||
|
// max_cache_mb (total-cache cap, sanity-clamped to [16, 65536])
|
||||||
|
int total = DEFAULT_MAX_CACHE_MB;
|
||||||
|
if (json.has("max_cache_mb") && json.get("max_cache_mb").isJsonPrimitive()
|
||||||
|
&& json.get("max_cache_mb").getAsJsonPrimitive().isNumber()) {
|
||||||
|
total = json.get("max_cache_mb").getAsInt();
|
||||||
|
} else {
|
||||||
|
augmented = true;
|
||||||
|
}
|
||||||
|
if (total < 16) total = 16;
|
||||||
|
if (total > 65536) total = 65536;
|
||||||
|
maxCacheMb = total;
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
} else {
|
||||||
|
augmented = true;
|
||||||
|
}
|
||||||
|
if (rd < 16) rd = 16;
|
||||||
|
if (rd > 2048) rd = 2048;
|
||||||
|
renderDistanceBlocks = rd;
|
||||||
|
|
||||||
|
// preload_urls (legacy)
|
||||||
List<String> urls = new ArrayList<>();
|
List<String> urls = new ArrayList<>();
|
||||||
if (json.has("preload_urls") && json.get("preload_urls").isJsonArray()) {
|
if (json.has("preload_urls") && json.get("preload_urls").isJsonArray()) {
|
||||||
json.getAsJsonArray("preload_urls").forEach(el -> {
|
json.getAsJsonArray("preload_urls").forEach(el -> {
|
||||||
if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) {
|
if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) {
|
||||||
String u = el.getAsString().trim();
|
String u = sanitizeUrl(el.getAsString());
|
||||||
if (!u.isEmpty() && (u.startsWith("http://") || u.startsWith("https://"))
|
if (u != null) urls.add(u);
|
||||||
&& 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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
PRELOAD_URLS = Collections.unmodifiableList(urls);
|
preloadUrls = Collections.unmodifiableList(urls);
|
||||||
VideoPlayerMod.LOG.info("[{}] config loaded: {} preload url(s)",
|
|
||||||
VideoPlayerMod.MOD_ID, urls.size());
|
// 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: per-video={} MB, total-cache={} MB, render={} blocks, "
|
||||||
|
+ "preload_urls={}, cache_entries={}",
|
||||||
|
VideoPlayerMod.MOD_ID, maxPreloadMb, maxCacheMb, renderDistanceBlocks,
|
||||||
|
urls.size(), CACHE_ENTRIES.size());
|
||||||
|
|
||||||
|
// Auto-augment: rewrite the file once so missing keys appear after a mod update.
|
||||||
|
if (augmented) {
|
||||||
|
VideoPlayerMod.LOG.info(
|
||||||
|
"[{}] config missing one or more keys — rewriting with defaults filled in",
|
||||||
|
VideoPlayerMod.MOD_ID);
|
||||||
|
save();
|
||||||
|
}
|
||||||
} catch (Throwable t) {
|
} 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());
|
VideoPlayerMod.MOD_ID, path, t.toString());
|
||||||
PRELOAD_URLS = Collections.emptyList();
|
maxPreloadMb = DEFAULT_MAX_PRELOAD_MB;
|
||||||
|
maxCacheMb = DEFAULT_MAX_CACHE_MB;
|
||||||
|
renderDistanceBlocks = DEFAULT_RENDER_DISTANCE;
|
||||||
|
preloadUrls = Collections.emptyList();
|
||||||
|
CACHE_ENTRIES.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** URLs to push to each joining player. Never null; possibly empty. */
|
// -- accessors ---------------------------------------------------------------------------
|
||||||
public static List<String> preloadUrls() {
|
|
||||||
return PRELOAD_URLS;
|
/** 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; }
|
||||||
|
|
||||||
|
/** Hard cap on the client-side total cache directory, in MB. */
|
||||||
|
public static int maxCacheMb() { return maxCacheMb; }
|
||||||
|
|
||||||
|
/** Same value in bytes. */
|
||||||
|
public static long maxCacheBytes() { return (long) maxCacheMb * 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<String> preloadUrls() { return preloadUrls; }
|
||||||
|
|
||||||
|
/** Snapshot of name → url, insertion-ordered. Never null. */
|
||||||
|
public static synchronized Map<String, String> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drop every named cache entry and return the URLs that were registered so the caller
|
||||||
|
* can broadcast {@code DeleteCachePayload} for each. Persists on any non-empty removal.
|
||||||
|
*/
|
||||||
|
public static synchronized java.util.List<String> clearCacheEntries() {
|
||||||
|
if (CACHE_ENTRIES.isEmpty()) return java.util.Collections.emptyList();
|
||||||
|
java.util.List<String> urls = new java.util.ArrayList<>(CACHE_ENTRIES.values());
|
||||||
|
CACHE_ENTRIES.clear();
|
||||||
|
save();
|
||||||
|
return urls;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- 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 {
|
private static void writeDefault(Path path) throws IOException {
|
||||||
Files.createDirectories(path.getParent());
|
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();
|
JsonObject root = new JsonObject();
|
||||||
root.addProperty("_comment",
|
root.addProperty("_comment",
|
||||||
"preload_urls: HTTP(S) video URLs broadcast to every player on join. "
|
"max_preload_mb: per-video download cap (each client). "
|
||||||
+ "Equivalent to running /videopreload <url> per joiner. Max 256 chars per url.");
|
+ "max_cache_mb: total cache directory cap (each client). "
|
||||||
root.add("preload_urls", new com.google.gson.JsonArray());
|
+ "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("max_cache_mb", DEFAULT_MAX_CACHE_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();
|
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||||
Files.writeString(path, gson.toJson(root), StandardCharsets.UTF_8);
|
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<String, String> 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
package com.ejclaw.videoplayer;
|
package com.ejclaw.videoplayer;
|
||||||
|
|
||||||
|
import com.ejclaw.videoplayer.command.VideoCacheCommand;
|
||||||
import com.ejclaw.videoplayer.command.VideoDeleteCommand;
|
import com.ejclaw.videoplayer.command.VideoDeleteCommand;
|
||||||
import com.ejclaw.videoplayer.command.VideoMuteCommand;
|
import com.ejclaw.videoplayer.command.VideoMuteCommand;
|
||||||
import com.ejclaw.videoplayer.command.VideoPlaceCommand;
|
import com.ejclaw.videoplayer.command.VideoPlaceCommand;
|
||||||
import com.ejclaw.videoplayer.command.VideoPreloadCommand;
|
|
||||||
import com.ejclaw.videoplayer.command.VideoStickCommand;
|
import com.ejclaw.videoplayer.command.VideoStickCommand;
|
||||||
|
import com.ejclaw.videoplayer.net.CachePolicyPayload;
|
||||||
import com.ejclaw.videoplayer.net.PreloadPayload;
|
import com.ejclaw.videoplayer.net.PreloadPayload;
|
||||||
import com.ejclaw.videoplayer.net.VideoPlayerNetwork;
|
import com.ejclaw.videoplayer.net.VideoPlayerNetwork;
|
||||||
import com.ejclaw.videoplayer.registry.VideoPlayerBlockEntities;
|
import com.ejclaw.videoplayer.registry.VideoPlayerBlockEntities;
|
||||||
@@ -37,20 +38,34 @@ public class VideoPlayerMod implements ModInitializer {
|
|||||||
VideoPlaceCommand.register(dispatcher);
|
VideoPlaceCommand.register(dispatcher);
|
||||||
VideoDeleteCommand.register(dispatcher);
|
VideoDeleteCommand.register(dispatcher);
|
||||||
VideoMuteCommand.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
|
// On join: (1) push the per-video download cap so the client knows whether to abort
|
||||||
// client kicks off the background download. Reuses the same PreloadPayload that
|
// an over-cap stream, (2) replay every legacy preload_urls entry, (3) replay every
|
||||||
// /videopreload sends, so the client-side caching path is identical.
|
// 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) -> {
|
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
|
||||||
java.util.List<String> urls = VideoPlayerConfig.preloadUrls();
|
var player = handler.getPlayer();
|
||||||
if (urls.isEmpty()) return;
|
ServerPlayNetworking.send(player, new CachePolicyPayload(
|
||||||
for (String url : urls) {
|
VideoPlayerConfig.maxPreloadBytes(),
|
||||||
ServerPlayNetworking.send(handler.getPlayer(), new PreloadPayload(url));
|
VideoPlayerConfig.maxCacheBytes(),
|
||||||
|
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);
|
LOG.info("[{}] initialized", MOD_ID);
|
||||||
|
|||||||
@@ -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}.
|
||||||
|
*
|
||||||
|
* <p>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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,12 @@
|
|||||||
package com.ejclaw.videoplayer.client.net;
|
package com.ejclaw.videoplayer.client.net;
|
||||||
|
|
||||||
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
||||||
|
import com.ejclaw.videoplayer.client.ClientPolicy;
|
||||||
import com.ejclaw.videoplayer.client.gui.VideoConfigScreen;
|
import com.ejclaw.videoplayer.client.gui.VideoConfigScreen;
|
||||||
import com.ejclaw.videoplayer.client.playback.VideoCache;
|
import com.ejclaw.videoplayer.client.playback.VideoCache;
|
||||||
import com.ejclaw.videoplayer.client.playback.VideoPlayback;
|
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.OpenScreenPayload;
|
||||||
import com.ejclaw.videoplayer.net.PreloadPayload;
|
import com.ejclaw.videoplayer.net.PreloadPayload;
|
||||||
import com.ejclaw.videoplayer.net.SyncAnchorPayload;
|
import com.ejclaw.videoplayer.net.SyncAnchorPayload;
|
||||||
@@ -40,5 +43,19 @@ public final class ClientNetworking {
|
|||||||
ClientPlayNetworking.registerGlobalReceiver(PreloadPayload.TYPE, (payload, context) -> {
|
ClientPlayNetworking.registerGlobalReceiver(PreloadPayload.TYPE, (payload, context) -> {
|
||||||
VideoCache.preload(payload.url());
|
VideoCache.preload(payload.url());
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Server tells us the per-video and total-cache download caps (bytes). Must arrive
|
||||||
|
// before PreloadPayload (server sends policy first on JOIN) so we don't use stale
|
||||||
|
// defaults.
|
||||||
|
ClientPlayNetworking.registerGlobalReceiver(CachePolicyPayload.TYPE, (payload, context) -> {
|
||||||
|
VideoCache.setMaxBytes(payload.maxPerVideoBytes());
|
||||||
|
VideoCache.setMaxCacheBytes(payload.maxCacheBytes());
|
||||||
|
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());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import com.ejclaw.videoplayer.VideoPlayerMod;
|
|||||||
import net.fabricmc.api.EnvType;
|
import net.fabricmc.api.EnvType;
|
||||||
import net.fabricmc.api.Environment;
|
import net.fabricmc.api.Environment;
|
||||||
|
|
||||||
|
import org.lwjgl.system.MemoryUtil;
|
||||||
|
|
||||||
import javax.sound.sampled.AudioFormat;
|
import javax.sound.sampled.AudioFormat;
|
||||||
import javax.sound.sampled.AudioSystem;
|
import javax.sound.sampled.AudioSystem;
|
||||||
import javax.sound.sampled.SourceDataLine;
|
import javax.sound.sampled.SourceDataLine;
|
||||||
@@ -13,7 +15,7 @@ import java.nio.ByteBuffer;
|
|||||||
import java.nio.ByteOrder;
|
import java.nio.ByteOrder;
|
||||||
import java.nio.ShortBuffer;
|
import java.nio.ShortBuffer;
|
||||||
import java.util.concurrent.atomic.AtomicBoolean;
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
import java.util.concurrent.atomic.AtomicReference;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SPEC §5.3 — fallback mp4/http(s) backend driven by JavaCV's FFmpegFrameGrabber.
|
* SPEC §5.3 — fallback mp4/http(s) backend driven by JavaCV's FFmpegFrameGrabber.
|
||||||
@@ -29,15 +31,45 @@ import java.util.concurrent.atomic.AtomicReference;
|
|||||||
public class JavaCvBackend implements VideoBackend {
|
public class JavaCvBackend implements VideoBackend {
|
||||||
private static final String GRABBER_CLASS = "org.bytedeco.javacv.FFmpegFrameGrabber";
|
private static final String GRABBER_CLASS = "org.bytedeco.javacv.FFmpegFrameGrabber";
|
||||||
private static final String FRAME_CLASS = "org.bytedeco.javacv.Frame";
|
private static final String FRAME_CLASS = "org.bytedeco.javacv.Frame";
|
||||||
private static final String CONVERTER_CLASS = "org.bytedeco.javacv.Java2DFrameConverter";
|
|
||||||
/** {@code AV_SAMPLE_FMT_S16} from {@code org.bytedeco.ffmpeg.global.avutil}. */
|
/** {@code AV_SAMPLE_FMT_S16} from {@code org.bytedeco.ffmpeg.global.avutil}. */
|
||||||
private static final int AV_SAMPLE_FMT_S16 = 1;
|
private static final int AV_SAMPLE_FMT_S16 = 1;
|
||||||
|
/** {@code AV_PIX_FMT_RGBA} from {@code org.bytedeco.ffmpeg.global.avutil}. */
|
||||||
|
private static final int AV_PIX_FMT_RGBA = 26;
|
||||||
|
|
||||||
private final Object lock = new Object();
|
private final Object lock = new Object();
|
||||||
private Thread worker;
|
private Thread worker;
|
||||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||||
private final AtomicBoolean paused = new AtomicBoolean(false);
|
private final AtomicBoolean paused = new AtomicBoolean(false);
|
||||||
private final AtomicReference<ByteBuffer> latest = new AtomicReference<>();
|
/**
|
||||||
|
* Ring buffer of preallocated RGBA staging slots. Decoder thread writes to {@code ringTail}
|
||||||
|
* under {@link #frameLock}; render thread drains the oldest slot via
|
||||||
|
* {@link #consumeFrame(long, long)} under the same lock.
|
||||||
|
*
|
||||||
|
* <p>0.4.10 used a single staging slot and relied on {@link SourceDataLine#write}
|
||||||
|
* backpressure to pace the decoder. That paced only at audio-buffer granularity (~0.5 s):
|
||||||
|
* the decoder burst-produced ~12 video frames into the slot while the audio line drained,
|
||||||
|
* the consumer (60+ Hz polling) saw only the last frame of each burst, then the decoder
|
||||||
|
* stalled until audio drained again — net effect ~2 fps of visible video despite the
|
||||||
|
* decoder producing at the source's 24 fps. The ring absorbs the burst; combined with the
|
||||||
|
* smaller audio buffer (~0.1 s) below the burst collapses to 2–3 frames which fits in
|
||||||
|
* {@link #FRAME_RING_SLOTS}.
|
||||||
|
*
|
||||||
|
* <p>If the ring still fills, the decoder overwrites the oldest slot and increments
|
||||||
|
* {@link #droppedFrames}. Memory cost: {@code 4 × w × h × 4} bytes (32 MB at 1080p,
|
||||||
|
* ~130 MB at 4K).
|
||||||
|
*/
|
||||||
|
private static final int FRAME_RING_SLOTS = 4;
|
||||||
|
private final Object frameLock = new Object();
|
||||||
|
private final ByteBuffer[] ringBufs = new ByteBuffer[FRAME_RING_SLOTS];
|
||||||
|
private final int[] ringBytes = new int[FRAME_RING_SLOTS];
|
||||||
|
private int ringHead = 0; // next slot to consume
|
||||||
|
private int ringTail = 0; // next slot to produce into
|
||||||
|
private int ringCount = 0;
|
||||||
|
|
||||||
|
/** Decoder telemetry (cumulative). Logged ~every 10 s from the decode thread. */
|
||||||
|
private final AtomicLong producedFrames = new AtomicLong();
|
||||||
|
private final AtomicLong consumedFrames = new AtomicLong();
|
||||||
|
private final AtomicLong droppedFrames = new AtomicLong();
|
||||||
private volatile int width = 0;
|
private volatile int width = 0;
|
||||||
private volatile int height = 0;
|
private volatile int height = 0;
|
||||||
private volatile float gain = 1.0F;
|
private volatile float gain = 1.0F;
|
||||||
@@ -87,14 +119,39 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
public int videoHeight() { return height; }
|
public int videoHeight() { return height; }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ByteBuffer pollFrame() {
|
public boolean consumeFrame(long dstAddr, long maxBytes) {
|
||||||
return latest.getAndSet(null);
|
synchronized (frameLock) {
|
||||||
|
if (ringCount <= 0) return false;
|
||||||
|
int idx = ringHead;
|
||||||
|
int n = ringBytes[idx];
|
||||||
|
ByteBuffer buf = ringBufs[idx];
|
||||||
|
// Always advance head regardless of memcpy outcome — otherwise a single oversize
|
||||||
|
// frame (e.g. mid-resize) would jam the ring forever.
|
||||||
|
ringHead = (idx + 1) % FRAME_RING_SLOTS;
|
||||||
|
ringCount--;
|
||||||
|
if (buf == null || n <= 0 || n > maxBytes) {
|
||||||
|
// Texture not yet sized for this frame, or empty slot — skip. ensureTexture()
|
||||||
|
// runs in Entry.tryUpload() before consumeFrame, so n > maxBytes only happens
|
||||||
|
// on the exact tick of a resolution change.
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
MemoryUtil.memCopy(MemoryUtil.memAddress(buf), dstAddr, n);
|
||||||
|
consumedFrames.incrementAndGet();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void close() {
|
public void close() {
|
||||||
closed = true;
|
closed = true;
|
||||||
stopWorker();
|
stopWorker();
|
||||||
|
synchronized (frameLock) {
|
||||||
|
for (int i = 0; i < FRAME_RING_SLOTS; i++) {
|
||||||
|
ringBufs[i] = null;
|
||||||
|
ringBytes[i] = 0;
|
||||||
|
}
|
||||||
|
ringHead = ringTail = ringCount = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void stopWorker() {
|
private void stopWorker() {
|
||||||
@@ -107,16 +164,44 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
try { line.stop(); } catch (Throwable ignored) {}
|
try { line.stop(); } catch (Throwable ignored) {}
|
||||||
try { line.flush(); } catch (Throwable ignored) {}
|
try { line.flush(); } catch (Throwable ignored) {}
|
||||||
}
|
}
|
||||||
// Yank the grabber too so a blocked grab() inside an HTTP read returns promptly.
|
// CRITICAL: we do NOT call grabber.close() from this (caller) thread. The decoder's
|
||||||
// JavaCV's close() is best-effort thread-safe — worst case we trip an AVERROR which
|
// per-frame path is:
|
||||||
// the catch-all in runLoop swallows.
|
//
|
||||||
Object g = grabberHandle;
|
// frame = grab(grabber); // grabber-owned native memory
|
||||||
if (g != null) {
|
// src = frame.image[0]; // DirectByteBuffer over that memory
|
||||||
try { g.getClass().getMethod("close").invoke(g); } catch (Throwable ignored) {}
|
// 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;
|
Thread t = worker;
|
||||||
worker = null;
|
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;
|
ready = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,6 +222,7 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
Method getAudioChannels = grabberCls.getMethod("getAudioChannels");
|
Method getAudioChannels = grabberCls.getMethod("getAudioChannels");
|
||||||
Method setOpt = grabberCls.getMethod("setOption", String.class, String.class);
|
Method setOpt = grabberCls.getMethod("setOption", String.class, String.class);
|
||||||
Method setSampleFormat = grabberCls.getMethod("setSampleFormat", int.class);
|
Method setSampleFormat = grabberCls.getMethod("setSampleFormat", int.class);
|
||||||
|
Method setPixelFormat = grabberCls.getMethod("setPixelFormat", int.class);
|
||||||
|
|
||||||
// HTTP(S) tuning for streaming URLs (webm via Range / chunked transfer).
|
// HTTP(S) tuning for streaming URLs (webm via Range / chunked transfer).
|
||||||
// Lower timeouts → close() snaps shut fast when an anchor is deleted mid-stream;
|
// Lower timeouts → close() snaps shut fast when an anchor is deleted mid-stream;
|
||||||
@@ -157,6 +243,16 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
"video_player/" + com.ejclaw.videoplayer.VideoPlayerMod.MOD_ID); } catch (Throwable ignored) {}
|
"video_player/" + com.ejclaw.videoplayer.VideoPlayerMod.MOD_ID); } catch (Throwable ignored) {}
|
||||||
// Force interleaved signed 16-bit PCM so the audio sink path is single-shape.
|
// Force interleaved signed 16-bit PCM so the audio sink path is single-shape.
|
||||||
try { setSampleFormat.invoke(grabber, AV_SAMPLE_FMT_S16); } catch (Throwable ignored) {}
|
try { setSampleFormat.invoke(grabber, AV_SAMPLE_FMT_S16); } catch (Throwable ignored) {}
|
||||||
|
// Force RGBA output so frame.image[0] is a ByteBuffer we can memcpy straight into
|
||||||
|
// the GPU texture. Without this, frame.image[0] is BGR24 and we'd have to round-trip
|
||||||
|
// through Java2DFrameConverter → BufferedImage.getRGB() → per-pixel ARGB→RGBA loop,
|
||||||
|
// which spends 20-50ms of Java work per 1080p frame and was the dominant stutter
|
||||||
|
// source in 0.4.7/0.4.8: when the decoder fell behind real time, the audio buffer
|
||||||
|
// drained, backpressure vanished, and the decoder burst-fired catch-up frames into
|
||||||
|
// the single-slot AtomicReference (dropping all but the last) before the buffer
|
||||||
|
// refilled and blocked it again. swscale's native SIMD does the same conversion in
|
||||||
|
// <1ms per frame, so the decoder consistently keeps real-time pace.
|
||||||
|
try { setPixelFormat.invoke(grabber, AV_PIX_FMT_RGBA); } catch (Throwable ignored) {}
|
||||||
|
|
||||||
start.invoke(grabber);
|
start.invoke(grabber);
|
||||||
this.width = (int) getW.invoke(grabber);
|
this.width = (int) getW.invoke(grabber);
|
||||||
@@ -168,12 +264,32 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
localAudioLine = openLine(sampleRate, audioChannels);
|
localAudioLine = openLine(sampleRate, audioChannels);
|
||||||
this.audioLine = localAudioLine;
|
this.audioLine = localAudioLine;
|
||||||
|
|
||||||
|
// Decoder spec — printed once per playback so the user log shows what the decoder
|
||||||
|
// actually sees (resolution / frame rate / sample rate). Used to verify our pacing
|
||||||
|
// assumptions (e.g. ring depth, audio buffer length) match the source.
|
||||||
|
double srcFrameRate = 0;
|
||||||
|
try { srcFrameRate = ((Number) grabberCls.getMethod("getFrameRate").invoke(grabber)).doubleValue(); }
|
||||||
|
catch (Throwable ignored) {}
|
||||||
|
VideoPlayerMod.LOG.info(
|
||||||
|
"[{}] decoder started: {}x{} @ {} fps, audio {} Hz x{}, ring={} slots",
|
||||||
|
VideoPlayerMod.MOD_ID, width, height,
|
||||||
|
String.format("%.2f", srcFrameRate),
|
||||||
|
sampleRate, audioChannels, FRAME_RING_SLOTS);
|
||||||
|
|
||||||
Class<?> frameCls = Class.forName(FRAME_CLASS);
|
Class<?> frameCls = Class.forName(FRAME_CLASS);
|
||||||
Field imageField = frameCls.getField("image");
|
Field imageField = frameCls.getField("image");
|
||||||
Field samplesField = frameCls.getField("samples");
|
Field samplesField = frameCls.getField("samples");
|
||||||
Class<?> convCls = Class.forName(CONVERTER_CLASS);
|
// Java2DFrameConverter is no longer used now that we read RGBA bytes directly,
|
||||||
Object converter = convCls.getDeclaredConstructor().newInstance();
|
// but we still resolve its class so a future code path could fall back to it if a
|
||||||
Method toImage = convCls.getMethod("getBufferedImage", frameCls);
|
// grabber refuses setPixelFormat. Keep the lookup defensive.
|
||||||
|
|
||||||
|
// Stats sampling: every 10 s of wall-clock we log produced/consumed/dropped deltas
|
||||||
|
// and the implied fps. Lets us tell from the log whether the decoder is keeping
|
||||||
|
// real-time pace (produced≈source fps) and whether the ring is overflowing
|
||||||
|
// (dropped>0). All counters are cumulative; we keep the previous sample to compute
|
||||||
|
// deltas.
|
||||||
|
long statsLastNs = System.nanoTime();
|
||||||
|
long lastProd = 0, lastCons = 0, lastDrop = 0;
|
||||||
|
|
||||||
while (running.get() && !closed) {
|
while (running.get() && !closed) {
|
||||||
if (paused.get()) { Thread.sleep(20); continue; }
|
if (paused.get()) { Thread.sleep(20); continue; }
|
||||||
@@ -200,13 +316,84 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Object[] images = (Object[]) imageField.get(frame);
|
Object[] images = (Object[]) imageField.get(frame);
|
||||||
if (images != null && images.length > 0) {
|
if (images != null && images.length > 0 && images[0] instanceof ByteBuffer src) {
|
||||||
java.awt.image.BufferedImage img =
|
// frame.image[0] is the swscale-converted RGBA plane, reused by the grabber
|
||||||
(java.awt.image.BufferedImage) toImage.invoke(converter, frame);
|
// across grab() calls. Copy into the next ring slot under frameLock so the
|
||||||
if (img != null) {
|
// render thread's consumeFrame() sees coherent frames in FIFO order.
|
||||||
ByteBuffer buf = toRgba(img);
|
//
|
||||||
if (buf != null) latest.set(buf);
|
// Allocation is one-time per slot, lazily on first use (or on a resolution
|
||||||
|
// upgrade) — never per frame. 0.4.9's per-frame allocateDirect was the
|
||||||
|
// primary memory-churn problem; 0.4.10 fixed that; 0.4.11 adds the ring on
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
long dstAddr = MemoryUtil.memAddress(ringBufs[idx]);
|
||||||
|
MemoryUtil.memCopy(srcAddr, dstAddr, need);
|
||||||
|
ringBytes[idx] = need;
|
||||||
|
ringTail = (idx + 1) % FRAME_RING_SLOTS;
|
||||||
|
if (ringCount < FRAME_RING_SLOTS) {
|
||||||
|
ringCount++;
|
||||||
|
} else {
|
||||||
|
// Ring was full — we overwrote the oldest frame. Advance head
|
||||||
|
// to point at the next-oldest so consume order stays FIFO.
|
||||||
|
ringHead = (ringHead + 1) % FRAME_RING_SLOTS;
|
||||||
|
droppedFrames.incrementAndGet();
|
||||||
|
}
|
||||||
|
producedFrames.incrementAndGet();
|
||||||
|
}
|
||||||
|
src.position(srcPos); // restore — JavaCV reads it on subsequent grabs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Periodic stats — once per ~10 s of wall-clock. Includes ring depth so we can
|
||||||
|
// see whether the consumer is keeping up.
|
||||||
|
long now = System.nanoTime();
|
||||||
|
if (now - statsLastNs > 10_000_000_000L) {
|
||||||
|
long prod = producedFrames.get();
|
||||||
|
long cons = consumedFrames.get();
|
||||||
|
long drop = droppedFrames.get();
|
||||||
|
double elapsedS = (now - statsLastNs) / 1e9;
|
||||||
|
int depth;
|
||||||
|
synchronized (frameLock) { depth = ringCount; }
|
||||||
|
VideoPlayerMod.LOG.info(
|
||||||
|
"[{}] decoder stats: produced={} ({} fps), consumed={} ({} fps), dropped={} (+{}) over {}s, ring={}/{}",
|
||||||
|
VideoPlayerMod.MOD_ID,
|
||||||
|
prod, String.format("%.1f", (prod - lastProd) / elapsedS),
|
||||||
|
cons, String.format("%.1f", (cons - lastCons) / elapsedS),
|
||||||
|
drop, (drop - lastDrop),
|
||||||
|
String.format("%.1f", elapsedS),
|
||||||
|
depth, FRAME_RING_SLOTS);
|
||||||
|
statsLastNs = now;
|
||||||
|
lastProd = prod; lastCons = cons; lastDrop = drop;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we have an open audio line, SourceDataLine.write() blocks for backpressure
|
// If we have an open audio line, SourceDataLine.write() blocks for backpressure
|
||||||
@@ -243,10 +430,17 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
try {
|
try {
|
||||||
AudioFormat fmt = new AudioFormat(sampleRate, 16, channels, true, false); // signed 16-bit LE
|
AudioFormat fmt = new AudioFormat(sampleRate, 16, channels, true, false); // signed 16-bit LE
|
||||||
SourceDataLine line = AudioSystem.getSourceDataLine(fmt);
|
SourceDataLine line = AudioSystem.getSourceDataLine(fmt);
|
||||||
// ~0.5 s of audio buffered in the driver. Smooths over upstream hiccups without
|
// ~0.1 s of audio buffered in the driver. 0.4.10 used 0.5 s, which let the decoder
|
||||||
// delaying close() — stopWorker() calls line.stop() / line.flush() to dump it.
|
// burst ~12 video frames between backpressure stalls — way past the video ring's
|
||||||
|
// capacity and the visible cause of the "2-5 fps" stutter the user saw. With 0.1 s
|
||||||
|
// the audio line refills more often, so the decoder is paced more tightly and
|
||||||
|
// bursts collapse to 2-3 frames (well inside FRAME_RING_SLOTS).
|
||||||
|
//
|
||||||
|
// Floor at frameSizeBytes * 256 keeps the buffer above the typical OS / driver
|
||||||
|
// minimum so we don't get UnsupportedOperationException at line.open() on
|
||||||
|
// exotic sample rates.
|
||||||
int frameSizeBytes = 2 * channels;
|
int frameSizeBytes = 2 * channels;
|
||||||
int bufferBytes = Math.max(sampleRate * frameSizeBytes / 2, frameSizeBytes * 1024);
|
int bufferBytes = Math.max(sampleRate * frameSizeBytes / 10, frameSizeBytes * 256);
|
||||||
line.open(fmt, bufferBytes);
|
line.open(fmt, bufferBytes);
|
||||||
line.start();
|
line.start();
|
||||||
return line;
|
return line;
|
||||||
@@ -293,17 +487,4 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
try { return (int) m.invoke(target); } catch (Throwable t) { return 0; }
|
try { return (int) m.invoke(target); } catch (Throwable t) { return 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ByteBuffer toRgba(java.awt.image.BufferedImage img) {
|
|
||||||
int w = img.getWidth(), h = img.getHeight();
|
|
||||||
int[] argb = img.getRGB(0, 0, w, h, null, 0, w);
|
|
||||||
ByteBuffer buf = ByteBuffer.allocateDirect(w * h * 4).order(ByteOrder.nativeOrder());
|
|
||||||
for (int p : argb) {
|
|
||||||
buf.put((byte) ((p >> 16) & 0xFF)); // R
|
|
||||||
buf.put((byte) ((p >> 8) & 0xFF)); // G
|
|
||||||
buf.put((byte) ( p & 0xFF)); // B
|
|
||||||
buf.put((byte) ((p >> 24) & 0xFF)); // A
|
|
||||||
}
|
|
||||||
buf.flip();
|
|
||||||
return buf;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ package com.ejclaw.videoplayer.client.playback;
|
|||||||
import net.fabricmc.api.EnvType;
|
import net.fabricmc.api.EnvType;
|
||||||
import net.fabricmc.api.Environment;
|
import net.fabricmc.api.Environment;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SPEC §5.3 — minimal playback backend abstraction. Implementations: WatermediaBackend (preferred,
|
* SPEC §5.3 — minimal playback backend abstraction. Implementations: WatermediaBackend (preferred,
|
||||||
* when v2 supports the target MC version) and JavaCvBackend (fallback).
|
* when v2 supports the target MC version) and JavaCvBackend (fallback).
|
||||||
@@ -21,10 +19,19 @@ public interface VideoBackend {
|
|||||||
int videoHeight();
|
int videoHeight();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Poll a new decoded RGBA frame if one is ready.
|
* If a new RGBA frame is ready, memcpy it directly into the GPU texture buffer at
|
||||||
* @return the frame buffer (capacity = w*h*4) or {@code null} if no new frame is ready.
|
* {@code dstAddr} (must have room for at least {@code w*h*4} bytes) and clear the dirty
|
||||||
|
* flag. Returns {@code true} when a frame was written.
|
||||||
|
*
|
||||||
|
* <p>Replaces the prior {@code pollFrame()} which returned a {@link java.nio.ByteBuffer}.
|
||||||
|
* The old contract forced the decoder to either allocate a fresh direct buffer per frame
|
||||||
|
* (huge memory churn at 1080p — see 0.4.10 changelog) or expose a reused buffer whose
|
||||||
|
* memory the decoder could clobber while the renderer was still reading. Pushing the copy
|
||||||
|
* inside the backend lets the decoder hold a single preallocated buffer under its own
|
||||||
|
* lock and copy out to the GPU pointer in one synchronized block — zero allocation, no
|
||||||
|
* race window.
|
||||||
*/
|
*/
|
||||||
ByteBuffer pollFrame();
|
boolean consumeFrame(long dstAddr, long maxBytes);
|
||||||
|
|
||||||
void close();
|
void close();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,8 +41,67 @@ public final class VideoCache {
|
|||||||
/** urls whose download is currently in flight. */
|
/** urls whose download is currently in flight. */
|
||||||
private static final Set<String> IN_FLIGHT = ConcurrentHashMap.newKeySet();
|
private static final Set<String> 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 2 GB sized to allow a single 4K
|
||||||
|
* short clip; overridden per-session by {@link com.ejclaw.videoplayer.net.CachePolicyPayload}
|
||||||
|
* on join, which carries the server's {@code max_preload_mb} config value.
|
||||||
|
*/
|
||||||
|
private static volatile long MAX_BYTES = 2048L * 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hard ceiling on the total cache directory size, in bytes. Default 750 MB sized to fit
|
||||||
|
* ~50 short FHD clips; overridden per-session by {@link com.ejclaw.videoplayer.net.CachePolicyPayload}
|
||||||
|
* on join, which carries the server's {@code max_cache_mb} config value. Enforced
|
||||||
|
* cooperatively at the start of each download — running cache + new download must stay
|
||||||
|
* within this cap.
|
||||||
|
*/
|
||||||
|
private static volatile long MAX_CACHE_BYTES = 750L * 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("[{}] per-video preload cap set to {} MB",
|
||||||
|
VideoPlayerMod.MOD_ID, bytes / (1024 * 1024));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Server-driven override of the total-cache cap. */
|
||||||
|
public static void setMaxCacheBytes(long bytes) {
|
||||||
|
if (bytes < 16L * 1024 * 1024) bytes = 16L * 1024 * 1024;
|
||||||
|
if (bytes > 64L * 1024 * 1024 * 1024) bytes = 64L * 1024 * 1024 * 1024;
|
||||||
|
MAX_CACHE_BYTES = bytes;
|
||||||
|
VideoPlayerMod.LOG.info("[{}] total-cache 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. */
|
/** Kick off a background download. No-op if already cached or in flight. */
|
||||||
public static void preload(String url) {
|
public static void preload(String url) {
|
||||||
@@ -110,6 +169,22 @@ public final class VideoCache {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Total-cache check: refuse to start if the cache directory is already at the cap.
|
||||||
|
// We re-check during the read loop too, since other downloads may be in flight in
|
||||||
|
// parallel. {@code existingCacheBytes} excludes our own .part (which we just wrote 0
|
||||||
|
// bytes to / haven't created yet).
|
||||||
|
long existingCacheBytes = cacheDirSize(cacheDir, partPath);
|
||||||
|
if (existingCacheBytes >= MAX_CACHE_BYTES) {
|
||||||
|
long capMb = MAX_CACHE_BYTES / (1024 * 1024);
|
||||||
|
long usedMb = existingCacheBytes / (1024 * 1024);
|
||||||
|
VideoPlayerMod.LOG.warn(
|
||||||
|
"[{}] preload: total-cache cap reached ({}/{} MB); aborting {}",
|
||||||
|
VideoPlayerMod.MOD_ID, usedMb, capMb, url);
|
||||||
|
notifyChat("[videopreload] 실패 (전체 캐시 " + capMb + "MB 초과 / 현재 "
|
||||||
|
+ usedMb + "MB): " + url, ChatFormatting.RED);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
URLConnection raw = URI.create(url).toURL().openConnection();
|
URLConnection raw = URI.create(url).toURL().openConnection();
|
||||||
raw.setConnectTimeout(10_000);
|
raw.setConnectTimeout(10_000);
|
||||||
raw.setReadTimeout(30_000);
|
raw.setReadTimeout(30_000);
|
||||||
@@ -133,11 +208,24 @@ public final class VideoCache {
|
|||||||
while ((n = in.read(buf)) >= 0) {
|
while ((n = in.read(buf)) >= 0) {
|
||||||
total += n;
|
total += n;
|
||||||
if (total > MAX_BYTES) {
|
if (total > MAX_BYTES) {
|
||||||
|
long capMb = MAX_BYTES / (1024 * 1024);
|
||||||
VideoPlayerMod.LOG.warn(
|
VideoPlayerMod.LOG.warn(
|
||||||
"[{}] preload: {} exceeded {} MB cap; aborting",
|
"[{}] preload: {} exceeded per-video {} MB cap; aborting",
|
||||||
VideoPlayerMod.MOD_ID, url, MAX_BYTES / (1024 * 1024));
|
VideoPlayerMod.MOD_ID, url, capMb);
|
||||||
try { Files.deleteIfExists(partPath); } catch (Throwable ignored) {}
|
try { Files.deleteIfExists(partPath); } catch (Throwable ignored) {}
|
||||||
notifyChat("[videopreload] 실패 (512MB 초과): " + url, ChatFormatting.RED);
|
notifyChat("[videopreload] 실패 (단일 영상 " + capMb + "MB 초과): " + url,
|
||||||
|
ChatFormatting.RED);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (existingCacheBytes + total > MAX_CACHE_BYTES) {
|
||||||
|
long capMb = MAX_CACHE_BYTES / (1024 * 1024);
|
||||||
|
long usedMb = (existingCacheBytes + total) / (1024 * 1024);
|
||||||
|
VideoPlayerMod.LOG.warn(
|
||||||
|
"[{}] preload: total-cache cap exceeded ({}>{} MB); aborting {}",
|
||||||
|
VideoPlayerMod.MOD_ID, usedMb, capMb, url);
|
||||||
|
try { Files.deleteIfExists(partPath); } catch (Throwable ignored) {}
|
||||||
|
notifyChat("[videopreload] 실패 (전체 캐시 " + capMb + "MB 초과): " + url,
|
||||||
|
ChatFormatting.RED);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
out.write(buf, 0, n);
|
out.write(buf, 0, n);
|
||||||
@@ -171,6 +259,32 @@ public final class VideoCache {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sum of regular-file sizes under {@code dir}, skipping {@code excludePart} (the .part file
|
||||||
|
* for the in-flight download — we account for that via the running {@code total} counter).
|
||||||
|
* Best-effort: errors collapse to 0 so a transient FS hiccup doesn't strand a download.
|
||||||
|
*/
|
||||||
|
private static long cacheDirSize(Path dir, Path excludePart) {
|
||||||
|
if (dir == null) return 0L;
|
||||||
|
try {
|
||||||
|
if (!Files.isDirectory(dir)) return 0L;
|
||||||
|
final long[] sum = { 0L };
|
||||||
|
try (var stream = Files.newDirectoryStream(dir)) {
|
||||||
|
for (Path p : stream) {
|
||||||
|
if (excludePart != null && p.equals(excludePart)) continue;
|
||||||
|
try {
|
||||||
|
if (Files.isRegularFile(p)) sum[0] += Files.size(p);
|
||||||
|
} catch (Throwable ignored) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sum[0];
|
||||||
|
} catch (Throwable t) {
|
||||||
|
VideoPlayerMod.LOG.warn("[{}] cacheDirSize failed: {}",
|
||||||
|
VideoPlayerMod.MOD_ID, t.toString());
|
||||||
|
return 0L;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static Path cacheDir() {
|
private static Path cacheDir() {
|
||||||
Minecraft mc = Minecraft.getInstance();
|
Minecraft mc = Minecraft.getInstance();
|
||||||
if (mc == null || mc.gameDirectory == null) return null;
|
if (mc == null || mc.gameDirectory == null) return null;
|
||||||
|
|||||||
@@ -9,9 +9,7 @@ import net.minecraft.client.Minecraft;
|
|||||||
import net.minecraft.client.renderer.texture.DynamicTexture;
|
import net.minecraft.client.renderer.texture.DynamicTexture;
|
||||||
import net.minecraft.core.BlockPos;
|
import net.minecraft.core.BlockPos;
|
||||||
import net.minecraft.resources.Identifier;
|
import net.minecraft.resources.Identifier;
|
||||||
import org.lwjgl.system.MemoryUtil;
|
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
@@ -113,10 +111,8 @@ public final class VideoPlayback {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (!e.backend.isReady()) continue;
|
if (!e.backend.isReady()) continue;
|
||||||
ByteBuffer buf = e.backend.pollFrame();
|
|
||||||
if (buf == null) continue;
|
|
||||||
try {
|
try {
|
||||||
e.upload(buf);
|
e.tryUpload();
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
VideoPlayerMod.LOG.warn("[{}] texture upload failed: {}", VideoPlayerMod.MOD_ID, t.toString());
|
VideoPlayerMod.LOG.warn("[{}] texture upload failed: {}", VideoPlayerMod.MOD_ID, t.toString());
|
||||||
e.close();
|
e.close();
|
||||||
@@ -188,32 +184,45 @@ public final class VideoPlayback {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Copy an incoming RGBA byte buffer into the texture, resizing if dimensions changed. */
|
/**
|
||||||
void upload(ByteBuffer rgba) {
|
* If the backend has a new RGBA frame, copy it straight into the texture's native
|
||||||
|
* pixel buffer and re-upload to GPU. The backend does the memcpy under its own lock
|
||||||
|
* so we never read a half-written frame. RGBA bytes already match NativeImage's
|
||||||
|
* ABGR-int layout in little-endian byte order (byte 0 = R = low byte of the int).
|
||||||
|
*/
|
||||||
|
void tryUpload() {
|
||||||
int w = backend.videoWidth();
|
int w = backend.videoWidth();
|
||||||
int h = backend.videoHeight();
|
int h = backend.videoHeight();
|
||||||
if (w <= 0 || h <= 0) return;
|
if (w <= 0 || h <= 0) return;
|
||||||
ensureTexture(w, h, false);
|
ensureTexture(w, h, false);
|
||||||
NativeImage img = texture.getPixels();
|
NativeImage img = texture.getPixels();
|
||||||
if (img == null) return;
|
if (img == null) return;
|
||||||
|
long maxBytes = (long) w * h * 4L;
|
||||||
// RGBA bytes from the backend already match NativeImage's ABGR-int layout when
|
if (backend.consumeFrame(img.getPointer(), maxBytes)) {
|
||||||
// viewed as little-endian bytes: byte 0 = R (low byte of ABGR int), byte 1 = G,
|
texture.upload();
|
||||||
// byte 2 = B, byte 3 = A. So a flat memcpy works — no per-pixel swap needed.
|
}
|
||||||
// This replaces a 2M-iteration Java loop with one native memcpy for 1080p frames,
|
|
||||||
// cutting upload time from ~20ms to <1ms and removing the main stutter source.
|
|
||||||
long bytes = (long) w * h * 4L;
|
|
||||||
MemoryUtil.memCopy(MemoryUtil.memAddress(rgba), img.getPointer(), bytes);
|
|
||||||
texture.upload();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void close() {
|
void close() {
|
||||||
try { backend.close(); } catch (Throwable ignored) {}
|
try { backend.close(); } catch (Throwable ignored) {}
|
||||||
|
// Unregister from TextureManager BEFORE closing the texture itself, so any
|
||||||
|
// straggler binding by Identifier looks up "no such texture" instead of a closed
|
||||||
|
// GL handle (which crashes the renderer on the next frame). Renderer pipelines
|
||||||
|
// can cache RenderType objects keyed by Identifier across frames, and on delete
|
||||||
|
// the old anchor's frame can still be in flight in the submit buffer when its
|
||||||
|
// texture closes — without this release(), the bind would dereference a freed
|
||||||
|
// GL handle.
|
||||||
|
if (registered) {
|
||||||
|
Minecraft mc = Minecraft.getInstance();
|
||||||
|
if (mc != null) {
|
||||||
|
try { mc.getTextureManager().release(id); } catch (Throwable ignored) {}
|
||||||
|
}
|
||||||
|
registered = false;
|
||||||
|
}
|
||||||
if (texture != null) {
|
if (texture != null) {
|
||||||
try { texture.close(); } catch (Throwable ignored) {}
|
try { texture.close(); } catch (Throwable ignored) {}
|
||||||
texture = null;
|
texture = null;
|
||||||
}
|
}
|
||||||
// texture manager keeps the registration; the texture itself is closed.
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ import com.ejclaw.videoplayer.VideoPlayerMod;
|
|||||||
import net.fabricmc.api.EnvType;
|
import net.fabricmc.api.EnvType;
|
||||||
import net.fabricmc.api.Environment;
|
import net.fabricmc.api.Environment;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SPEC §5.3 / §5.4 — WaterMedia v2 backend. Reflection-only so the mod jar stays clean of
|
* SPEC §5.3 / §5.4 — WaterMedia v2 backend. Reflection-only so the mod jar stays clean of
|
||||||
* compile-time WaterMedia dependencies. Until a v2 build supports 1.21.6+ this returns
|
* compile-time WaterMedia dependencies. Until a v2 build supports 1.21.6+ this returns
|
||||||
@@ -38,8 +36,8 @@ public class WatermediaBackend implements VideoBackend {
|
|||||||
@Override public int videoHeight() { return height; }
|
@Override public int videoHeight() { return height; }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ByteBuffer pollFrame() {
|
public boolean consumeFrame(long dstAddr, long maxBytes) {
|
||||||
return null; // no frames until v2 is wired up
|
return false; // no frames until v2 is wired up
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.ejclaw.videoplayer.client.render;
|
package com.ejclaw.videoplayer.client.render;
|
||||||
|
|
||||||
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
||||||
|
import com.ejclaw.videoplayer.client.ClientPolicy;
|
||||||
import com.ejclaw.videoplayer.client.playback.VideoPlayback;
|
import com.ejclaw.videoplayer.client.playback.VideoPlayback;
|
||||||
import com.mojang.blaze3d.vertex.PoseStack;
|
import com.mojang.blaze3d.vertex.PoseStack;
|
||||||
import com.mojang.math.Axis;
|
import com.mojang.math.Axis;
|
||||||
@@ -76,16 +77,14 @@ public class VideoAnchorRenderer implements BlockEntityRenderer<VideoAnchorBlock
|
|||||||
final Matrix4f mat = new Matrix4f(pose.last().pose());
|
final Matrix4f mat = new Matrix4f(pose.last().pose());
|
||||||
RenderType rt = RenderTypes.entityCutout(tex);
|
RenderType rt = RenderTypes.entityCutout(tex);
|
||||||
collector.submitCustomGeometry(pose, rt, (poseUnused, vc) -> {
|
collector.submitCustomGeometry(pose, rt, (poseUnused, vc) -> {
|
||||||
// Front face (visible from outside, looking back at the wall)
|
// Single-sided: the back of the anchor is by design pressed against the wall the
|
||||||
|
// player clicked, so a back face is pure GPU waste. Halves the fragment shader work
|
||||||
|
// per anchor and removes the mirrored-texture artifact a player would see if they
|
||||||
|
// somehow clipped behind the wall.
|
||||||
emit(vc, mat, 0F, 0F, 0F, 0F, 1F, light);
|
emit(vc, mat, 0F, 0F, 0F, 0F, 1F, light);
|
||||||
emit(vc, mat, w, 0F, 0F, 1F, 1F, light);
|
emit(vc, mat, w, 0F, 0F, 1F, 1F, light);
|
||||||
emit(vc, mat, w, h, 0F, 1F, 0F, light);
|
emit(vc, mat, w, h, 0F, 1F, 0F, light);
|
||||||
emit(vc, mat, 0F, h, 0F, 0F, 0F, light);
|
emit(vc, mat, 0F, h, 0F, 0F, 0F, light);
|
||||||
// Back face (in case the player ends up on the other side, e.g. clipping into the wall)
|
|
||||||
emit(vc, mat, 0F, h, 0F, 0F, 0F, light);
|
|
||||||
emit(vc, mat, w, h, 0F, 1F, 0F, light);
|
|
||||||
emit(vc, mat, w, 0F, 0F, 1F, 1F, light);
|
|
||||||
emit(vc, mat, 0F, 0F, 0F, 0F, 1F, light);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
pose.popPose();
|
pose.popPose();
|
||||||
@@ -126,7 +125,9 @@ public class VideoAnchorRenderer implements BlockEntityRenderer<VideoAnchorBlock
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getViewDistance() {
|
public int getViewDistance() {
|
||||||
return 128;
|
// Driven by server config (video_player.json:render_distance_blocks), pushed to clients
|
||||||
|
// on join. Default 128 = legacy behavior, so an unpaired client behaves identically.
|
||||||
|
return ClientPolicy.renderDistanceBlocks();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Per-frame render data extracted from the BE. */
|
/** Per-frame render data extracted from the BE. */
|
||||||
|
|||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package com.ejclaw.videoplayer.command;
|
||||||
|
|
||||||
|
import com.ejclaw.videoplayer.VideoPlayerConfig;
|
||||||
|
import com.ejclaw.videoplayer.net.DeleteCachePayload;
|
||||||
|
import com.ejclaw.videoplayer.net.PreloadPayload;
|
||||||
|
import com.mojang.brigadier.CommandDispatcher;
|
||||||
|
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||||
|
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||||
|
import com.mojang.brigadier.context.CommandContext;
|
||||||
|
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.ChatFormatting;
|
||||||
|
import net.minecraft.commands.CommandSourceStack;
|
||||||
|
import net.minecraft.commands.Commands;
|
||||||
|
import net.minecraft.network.chat.ClickEvent;
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import net.minecraft.network.chat.MutableComponent;
|
||||||
|
import net.minecraft.network.chat.Style;
|
||||||
|
import net.minecraft.server.MinecraftServer;
|
||||||
|
import net.minecraft.server.level.ServerPlayer;
|
||||||
|
import net.minecraft.server.permissions.Permissions;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@code /videocache add <name> <url>} — name a URL, store it in server config, and broadcast a
|
||||||
|
* preload request to every client.
|
||||||
|
* <br>{@code /videocache list} — print the named index with clickable URLs.
|
||||||
|
* <br>{@code /videocache remove <name>} — drop the entry from server config and tell every client
|
||||||
|
* to delete the matching cache file.
|
||||||
|
*
|
||||||
|
* <p>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<CommandSourceStack> dispatcher) {
|
||||||
|
dispatcher.register(build("videoCache"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LiteralArgumentBuilder<CommandSourceStack> 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)))
|
||||||
|
.then(Commands.literal("clear")
|
||||||
|
.executes(VideoCacheCommand::runClear));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int runAdd(CommandContext<CommandSourceStack> 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<CommandSourceStack> ctx) {
|
||||||
|
CommandSourceStack src = ctx.getSource();
|
||||||
|
Map<String, String> 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<String, String> 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 runClear(CommandContext<CommandSourceStack> ctx) {
|
||||||
|
CommandSourceStack src = ctx.getSource();
|
||||||
|
java.util.List<String> urls = VideoPlayerConfig.clearCacheEntries();
|
||||||
|
if (urls.isEmpty()) {
|
||||||
|
src.sendSuccess(() -> Component.literal("[videocache] 저장된 항목이 없습니다")
|
||||||
|
.withStyle(ChatFormatting.GRAY), false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
MinecraftServer server = src.getServer();
|
||||||
|
int clients = 0;
|
||||||
|
for (ServerPlayer p : PlayerLookup.all(server)) {
|
||||||
|
for (String url : urls) {
|
||||||
|
ServerPlayNetworking.send(p, new DeleteCachePayload(url));
|
||||||
|
}
|
||||||
|
clients++;
|
||||||
|
}
|
||||||
|
final int sentFinal = clients;
|
||||||
|
final int countFinal = urls.size();
|
||||||
|
src.sendSuccess(() -> Component.literal(
|
||||||
|
"[videocache] 전체 삭제: " + countFinal + "개 항목"
|
||||||
|
+ " (" + sentFinal + " 클라이언트에 cache_delete 전송)"), false);
|
||||||
|
return countFinal;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int runRemove(CommandContext<CommandSourceStack> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,6 @@ public final class VideoDeleteCommand {
|
|||||||
|
|
||||||
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
||||||
dispatcher.register(build("videoDelete"));
|
dispatcher.register(build("videoDelete"));
|
||||||
dispatcher.register(build("videodelete"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack>
|
private static com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack>
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ public final class VideoMuteCommand {
|
|||||||
|
|
||||||
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
||||||
dispatcher.register(build("videoMute"));
|
dispatcher.register(build("videoMute"));
|
||||||
dispatcher.register(build("videomute"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack>
|
private static com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.ejclaw.videoplayer.command;
|
package com.ejclaw.videoplayer.command;
|
||||||
|
|
||||||
|
import com.ejclaw.videoplayer.VideoPlayerConfig;
|
||||||
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
||||||
import com.ejclaw.videoplayer.net.SyncAnchorPayload;
|
import com.ejclaw.videoplayer.net.SyncAnchorPayload;
|
||||||
import com.ejclaw.videoplayer.registry.VideoPlayerBlocks;
|
import com.ejclaw.videoplayer.registry.VideoPlayerBlocks;
|
||||||
@@ -27,7 +28,6 @@ public final class VideoPlaceCommand {
|
|||||||
|
|
||||||
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
||||||
dispatcher.register(build("videoPlace"));
|
dispatcher.register(build("videoPlace"));
|
||||||
dispatcher.register(build("videoplace"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack>
|
private static com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack>
|
||||||
@@ -54,9 +54,14 @@ public final class VideoPlaceCommand {
|
|||||||
}
|
}
|
||||||
int width = IntegerArgumentType.getInteger(ctx, "width");
|
int width = IntegerArgumentType.getInteger(ctx, "width");
|
||||||
int height = IntegerArgumentType.getInteger(ctx, "height");
|
int height = IntegerArgumentType.getInteger(ctx, "height");
|
||||||
String url = StringArgumentType.getString(ctx, "url").trim();
|
String raw = StringArgumentType.getString(ctx, "url").trim();
|
||||||
if (!url.isEmpty() && !(url.startsWith("http://") || url.startsWith("https://"))) {
|
// Accept either an http(s) URL or a /videoCache add <name> entry: resolveUrlOrName()
|
||||||
src.sendFailure(Component.literal("url must be http:// or https:// (or empty)"));
|
// 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;
|
return 0;
|
||||||
}
|
}
|
||||||
if (url.length() > 256) url = url.substring(0, 256);
|
if (url.length() > 256) url = url.substring(0, 256);
|
||||||
|
|||||||
@@ -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 <url>} — 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.
|
|
||||||
*
|
|
||||||
* <p>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<CommandSourceStack> dispatcher) {
|
|
||||||
dispatcher.register(build("videoPreload"));
|
|
||||||
dispatcher.register(build("videopreload"));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static com.mojang.brigadier.builder.LiteralArgumentBuilder<CommandSourceStack>
|
|
||||||
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<CommandSourceStack> 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -14,9 +14,6 @@ public final class VideoStickCommand {
|
|||||||
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
|
||||||
dispatcher.register(Commands.literal("videoStick")
|
dispatcher.register(Commands.literal("videoStick")
|
||||||
.executes(ctx -> run(ctx.getSource())));
|
.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) {
|
private static int run(CommandSourceStack source) {
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
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}. Carries: {@code maxPerVideoBytes} (per-video download cap),
|
||||||
|
* {@code maxCacheBytes} (total-cache directory cap), and {@code renderDistanceBlocks}
|
||||||
|
* (anchor BE view-distance cap).
|
||||||
|
*/
|
||||||
|
public record CachePolicyPayload(long maxPerVideoBytes, long maxCacheBytes, int renderDistanceBlocks)
|
||||||
|
implements CustomPacketPayload {
|
||||||
|
public static final CustomPacketPayload.Type<CachePolicyPayload> TYPE =
|
||||||
|
new CustomPacketPayload.Type<>(Identifier.fromNamespaceAndPath(VideoPlayerMod.MOD_ID, "cache_policy"));
|
||||||
|
|
||||||
|
public static final StreamCodec<RegistryFriendlyByteBuf, CachePolicyPayload> CODEC = StreamCodec.composite(
|
||||||
|
ByteBufCodecs.VAR_LONG, CachePolicyPayload::maxPerVideoBytes,
|
||||||
|
ByteBufCodecs.VAR_LONG, CachePolicyPayload::maxCacheBytes,
|
||||||
|
ByteBufCodecs.VAR_INT, CachePolicyPayload::renderDistanceBlocks,
|
||||||
|
CachePolicyPayload::new
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Type<? extends CustomPacketPayload> type() {
|
||||||
|
return TYPE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 <name>}. 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<DeleteCachePayload> TYPE =
|
||||||
|
new CustomPacketPayload.Type<>(Identifier.fromNamespaceAndPath(VideoPlayerMod.MOD_ID, "cache_delete"));
|
||||||
|
|
||||||
|
public static final StreamCodec<RegistryFriendlyByteBuf, DeleteCachePayload> CODEC = StreamCodec.composite(
|
||||||
|
ByteBufCodecs.STRING_UTF8, DeleteCachePayload::url,
|
||||||
|
DeleteCachePayload::new
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Type<? extends CustomPacketPayload> type() {
|
||||||
|
return TYPE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.ejclaw.videoplayer.net;
|
package com.ejclaw.videoplayer.net;
|
||||||
|
|
||||||
|
import com.ejclaw.videoplayer.VideoPlayerConfig;
|
||||||
import com.ejclaw.videoplayer.VideoPlayerMod;
|
import com.ejclaw.videoplayer.VideoPlayerMod;
|
||||||
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
||||||
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
|
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(OpenScreenPayload.TYPE, OpenScreenPayload.CODEC);
|
||||||
PayloadTypeRegistry.clientboundPlay().register(SyncAnchorPayload.TYPE, SyncAnchorPayload.CODEC);
|
PayloadTypeRegistry.clientboundPlay().register(SyncAnchorPayload.TYPE, SyncAnchorPayload.CODEC);
|
||||||
PayloadTypeRegistry.clientboundPlay().register(PreloadPayload.TYPE, PreloadPayload.CODEC);
|
PayloadTypeRegistry.clientboundPlay().register(PreloadPayload.TYPE, PreloadPayload.CODEC);
|
||||||
|
PayloadTypeRegistry.clientboundPlay().register(CachePolicyPayload.TYPE, CachePolicyPayload.CODEC);
|
||||||
|
PayloadTypeRegistry.clientboundPlay().register(DeleteCachePayload.TYPE, DeleteCachePayload.CODEC);
|
||||||
// C2S
|
// C2S
|
||||||
PayloadTypeRegistry.serverboundPlay().register(SaveConfigPayload.TYPE, SaveConfigPayload.CODEC);
|
PayloadTypeRegistry.serverboundPlay().register(SaveConfigPayload.TYPE, SaveConfigPayload.CODEC);
|
||||||
PayloadTypeRegistry.serverboundPlay().register(DeleteAnchorPayload.TYPE, DeleteAnchorPayload.CODEC);
|
PayloadTypeRegistry.serverboundPlay().register(DeleteAnchorPayload.TYPE, DeleteAnchorPayload.CODEC);
|
||||||
@@ -95,13 +98,13 @@ public final class VideoPlayerNetwork {
|
|||||||
|
|
||||||
private static String trimUrl(String s) {
|
private static String trimUrl(String s) {
|
||||||
if (s == null) return "";
|
if (s == null) return "";
|
||||||
String t = s.trim();
|
// GUI / C2S accepts either an http(s) URL or a /videoCache add <name>. Names resolve
|
||||||
if (t.length() > 256) t = t.substring(0, 256);
|
// to their stored URL; URLs pass through verbatim. Anything else collapses to empty
|
||||||
// SPEC §4.4: only https?:// or empty
|
// (SPEC §4.4: anchors with non-URL urls are no-ops).
|
||||||
if (!t.isEmpty() && !(t.startsWith("http://") || t.startsWith("https://"))) {
|
String resolved = VideoPlayerConfig.resolveUrlOrName(s);
|
||||||
return "";
|
if (resolved == null) return "";
|
||||||
}
|
if (resolved.length() > 256) resolved = resolved.substring(0, 256);
|
||||||
return t;
|
return resolved;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int clamp(int v, int lo, int hi) {
|
private static int clamp(int v, int lo, int hi) {
|
||||||
|
|||||||
Reference in New Issue
Block a user