Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4fc7cf46b7 | ||
|
|
0d1f802555 | ||
|
|
8f11fe24bf |
64
README.md
64
README.md
@@ -3,7 +3,7 @@
|
|||||||
마인크래프트 안에서 임의의 동영상 URL을 벽·바닥·천장에 평면으로 재생하는 Fabric 모드.
|
마인크래프트 안에서 임의의 동영상 URL을 벽·바닥·천장에 평면으로 재생하는 Fabric 모드.
|
||||||
|
|
||||||
- 모드 ID: `video_player`
|
- 모드 ID: `video_player`
|
||||||
- 현재 버전: **0.4.1**
|
- 현재 버전: **0.4.4**
|
||||||
- 마인크래프트 버전: **26.1.2**
|
- 마인크래프트 버전: **26.1.2**
|
||||||
- 필요 Java: **25** (마인크래프트 26.x 가 요구함)
|
- 필요 Java: **25** (마인크래프트 26.x 가 요구함)
|
||||||
|
|
||||||
@@ -53,9 +53,9 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
- 받은 `fabric-api-0.149.0+26.1.2.jar` 를 `mods` 폴더에 넣습니다.
|
- 받은 `fabric-api-0.149.0+26.1.2.jar` 를 `mods` 폴더에 넣습니다.
|
||||||
2. **video_player** (이 모드)
|
2. **video_player** (이 모드)
|
||||||
- 다운로드: https://git.tkrmagid.kr/tkrmagid/mc_video_player_mod/releases
|
- 다운로드: https://git.tkrmagid.kr/tkrmagid/mc_video_player_mod/releases
|
||||||
- `video_player-0.4.1.jar` 를 다운로드해서 같은 `mods` 폴더에 넣습니다.
|
- `video_player-0.4.4.jar` 를 다운로드해서 같은 `mods` 폴더에 넣습니다.
|
||||||
|
|
||||||
이전 버전(`video_player-0.4.0.jar`, `0.3.x.jar` 등)이 mods 폴더에 남아있다면 **반드시 삭제**하세요. 두 개가 같이 있으면 마인크래프트가 충돌로 켜지지 않습니다.
|
이전 버전(`video_player-0.4.0.jar`, `0.4.2.jar`, `0.4.3.jar`, `0.3.x.jar` 등)이 mods 폴더에 남아있다면 **반드시 삭제**하세요. 두 개가 같이 있으면 마인크래프트가 충돌로 켜지지 않습니다.
|
||||||
|
|
||||||
### STEP 5. 영상 재생 라이브러리 (JavaCV) 설치
|
### STEP 5. 영상 재생 라이브러리 (JavaCV) 설치
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
1. https://prismlauncher.org/download/ 에서 다운로드 → 설치
|
1. https://prismlauncher.org/download/ 에서 다운로드 → 설치
|
||||||
2. Prism에서 인스턴스 → 마인크래프트 26.1.2 + Fabric Loader 0.19.2 선택해서 생성
|
2. Prism에서 인스턴스 → 마인크래프트 26.1.2 + Fabric Loader 0.19.2 선택해서 생성
|
||||||
3. 인스턴스 우클릭 → **Edit** → 왼쪽의 **Version** 탭 → **Add to Minecraft.jar** 버튼
|
3. 인스턴스 우클릭 → **Edit** → 왼쪽의 **Version** 탭 → **Add to Minecraft.jar** 버튼
|
||||||
4. 아래 STEP 5-B 의 1번 항목에서 받은 JavaCV jar 4개를 한꺼번에 선택해서 추가
|
4. 아래 STEP 5-B 의 1번 항목에서 받은 JavaCV jar 5개를 한꺼번에 선택해서 추가
|
||||||
5. **Launch** 로 실행
|
5. **Launch** 로 실행
|
||||||
|
|
||||||
이 방법이 가장 안정적이고 빠릅니다.
|
이 방법이 가장 안정적이고 빠릅니다.
|
||||||
@@ -81,36 +81,41 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
|
|
||||||
1. **JavaCV 1.5.13 다운로드**
|
1. **JavaCV 1.5.13 다운로드**
|
||||||
- 다운로드 링크: https://github.com/bytedeco/javacv/releases/download/1.5.13/javacv-platform-1.5.13-bin.zip (2026-02-22 릴리스, FFmpeg 8.0.1 동봉)
|
- 다운로드 링크: https://github.com/bytedeco/javacv/releases/download/1.5.13/javacv-platform-1.5.13-bin.zip (2026-02-22 릴리스, FFmpeg 8.0.1 동봉)
|
||||||
- 압축을 풀고 `javacv-platform-1.5.13-bin` 폴더 안에서 **다음 jar 4개**를 골라 둡니다 (다른 파일은 안 씁니다):
|
- 압축을 풀고 `javacv-platform-1.5.13-bin` 폴더 안에서 **다음 jar 5개**를 골라 둡니다 (다른 파일은 안 씁니다):
|
||||||
- `javacv.jar`
|
- `javacv.jar`
|
||||||
- `javacpp.jar`
|
- `javacpp.jar`
|
||||||
|
- 자신의 OS에 맞는 **javacpp 네이티브 jar** (이게 빠지면 검은 화면 — JNI bridge `jnijavacpp` 로딩에 꼭 필요):
|
||||||
|
- Windows 64bit: `javacpp-1.5.13-windows-x86_64.jar`
|
||||||
|
- macOS Intel: `javacpp-1.5.13-macosx-x86_64.jar`
|
||||||
|
- macOS Apple Silicon (M1/M2/M3/M4): `javacpp-1.5.13-macosx-arm64.jar`
|
||||||
|
- Linux 64bit: `javacpp-1.5.13-linux-x86_64.jar`
|
||||||
- `ffmpeg.jar`
|
- `ffmpeg.jar`
|
||||||
- 자신의 OS에 맞는 ffmpeg 네이티브 jar **하나**:
|
- 자신의 OS에 맞는 **ffmpeg 네이티브 jar**:
|
||||||
- Windows 64bit: `ffmpeg-8.0.1-1.5.13-windows-x86_64.jar`
|
- Windows 64bit: `ffmpeg-8.0.1-1.5.13-windows-x86_64.jar`
|
||||||
- macOS Intel: `ffmpeg-8.0.1-1.5.13-macosx-x86_64.jar`
|
- macOS Intel: `ffmpeg-8.0.1-1.5.13-macosx-x86_64.jar`
|
||||||
- macOS Apple Silicon (M1/M2/M3/M4): `ffmpeg-8.0.1-1.5.13-macosx-arm64.jar`
|
- macOS Apple Silicon (M1/M2/M3/M4): `ffmpeg-8.0.1-1.5.13-macosx-arm64.jar`
|
||||||
- Linux 64bit: `ffmpeg-8.0.1-1.5.13-linux-x86_64.jar`
|
- Linux 64bit: `ffmpeg-8.0.1-1.5.13-linux-x86_64.jar`
|
||||||
|
|
||||||
2. **이 4개 jar 를 게임이 읽도록 등록**
|
2. **이 5개 jar 를 게임이 읽도록 등록**
|
||||||
- 가장 안전한 위치: `.minecraft/libraries/javacv/` 폴더를 새로 만들고 4개 jar를 거기에 복사하세요.
|
- 가장 안전한 위치: `.minecraft/libraries/javacv/` 폴더를 새로 만들고 5개 jar를 거기에 복사하세요. (긴 파일명이 부담스러우면 `javacpp-1.5.13-windows-x86_64.jar` → `javacpp-windows-x86_64.jar`, `ffmpeg-8.0.1-1.5.13-windows-x86_64.jar` → `ffmpeg-windows-x86_64.jar` 식으로 짧게 rename해도 됩니다. 아래 예시는 짧은 이름 기준.)
|
||||||
- 그 다음, 공식 런처에서 fabric 프로필 옆 **편집** 또는 **설치 설정** → 화면 아래쪽 **"JVM 인수"** (Java arguments) 칸을 켜고 기존 인수 **끝**에 한 칸 띄우고 다음 한 줄을 추가합니다.
|
- 그 다음, 공식 런처에서 fabric 프로필 옆 **편집** 또는 **설치 설정** → 화면 아래쪽 **"JVM 인수"** (Java arguments) 칸을 켜고 기존 인수 **끝**에 한 칸 띄우고 다음 한 줄을 추가합니다.
|
||||||
|
|
||||||
⚠ **반드시 절대경로(`C:\Users\...`)로 적어주세요.** 마인크래프트 공식 런처는 JVM 인수의 `%APPDATA%`·`%USERPROFILE%` 같은 환경변수를 풀어주지 않고 글자 그대로 Java 에 넘깁니다. 그러면 boot classpath 가 빈 상태가 되어 영상이 안 나옵니다.
|
⚠ **반드시 절대경로(`C:\Users\...`)로 적어주세요.** 마인크래프트 공식 런처는 JVM 인수의 `%APPDATA%`·`%USERPROFILE%` 같은 환경변수를 풀어주지 않고 글자 그대로 Java 에 넘깁니다. 그러면 boot classpath 가 빈 상태가 되어 영상이 안 나옵니다.
|
||||||
|
|
||||||
Windows (사용자명 `홍길동` 예시):
|
Windows (사용자명 `홍길동` 예시):
|
||||||
```
|
```
|
||||||
-Xbootclasspath/a:C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\javacv.jar;C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\javacpp.jar;C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\ffmpeg.jar;C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\ffmpeg-windows-x86_64.jar
|
-Xbootclasspath/a:C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\javacv.jar;C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\javacpp.jar;C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\javacpp-windows-x86_64.jar;C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\ffmpeg.jar;C:\Users\홍길동\AppData\Roaming\.minecraft\libraries\javacv\ffmpeg-windows-x86_64.jar
|
||||||
```
|
```
|
||||||
(`C:\Users\<본인 윈도우 사용자명>\AppData\Roaming\` 부분을 본인 사용자 폴더로 바꾸세요. 윈도우키+R → `cmd` → `echo %APPDATA%` 로 정확한 경로 확인 가능.)
|
(`C:\Users\<본인 윈도우 사용자명>\AppData\Roaming\` 부분을 본인 사용자 폴더로 바꾸세요. 윈도우키+R → `cmd` → `echo %APPDATA%` 로 정확한 경로 확인 가능.)
|
||||||
|
|
||||||
macOS:
|
macOS (Apple Silicon 예시):
|
||||||
```
|
```
|
||||||
-Xbootclasspath/a:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/javacv.jar:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/javacpp.jar:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/ffmpeg.jar:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/ffmpeg-macosx-arm64.jar
|
-Xbootclasspath/a:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/javacv.jar:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/javacpp.jar:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/javacpp-macosx-arm64.jar:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/ffmpeg.jar:/Users/사용자이름/Library/Application Support/minecraft/libraries/javacv/ffmpeg-macosx-arm64.jar
|
||||||
```
|
```
|
||||||
|
|
||||||
Linux:
|
Linux:
|
||||||
```
|
```
|
||||||
-Xbootclasspath/a:/home/사용자이름/.minecraft/libraries/javacv/javacv.jar:/home/사용자이름/.minecraft/libraries/javacv/javacpp.jar:/home/사용자이름/.minecraft/libraries/javacv/ffmpeg.jar:/home/사용자이름/.minecraft/libraries/javacv/ffmpeg-linux-x86_64.jar
|
-Xbootclasspath/a:/home/사용자이름/.minecraft/libraries/javacv/javacv.jar:/home/사용자이름/.minecraft/libraries/javacv/javacpp.jar:/home/사용자이름/.minecraft/libraries/javacv/javacpp-linux-x86_64.jar:/home/사용자이름/.minecraft/libraries/javacv/ffmpeg.jar:/home/사용자이름/.minecraft/libraries/javacv/ffmpeg-linux-x86_64.jar
|
||||||
```
|
```
|
||||||
|
|
||||||
주의:
|
주의:
|
||||||
@@ -118,7 +123,8 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
- macOS/Linux는 **콜론(`:`)** 으로 구분합니다.
|
- macOS/Linux는 **콜론(`:`)** 으로 구분합니다.
|
||||||
- 경로에 띄어쓰기가 있으면(특히 macOS의 `Application Support`) 전체 인수를 큰따옴표로 감싸세요.
|
- 경로에 띄어쓰기가 있으면(특히 macOS의 `Application Support`) 전체 인수를 큰따옴표로 감싸세요.
|
||||||
- `사용자이름` 부분은 실제 자신의 사용자 폴더 이름으로 바꾸세요.
|
- `사용자이름` 부분은 실제 자신의 사용자 폴더 이름으로 바꾸세요.
|
||||||
- ffmpeg-... 부분의 jar 이름은 OS에 맞춰 1번에서 고른 그 파일명 그대로 적습니다 (zip 안에는 `ffmpeg-windows-x86_64.jar` 같은 짧은 이름으로 들어있습니다).
|
- `javacpp-...` 와 `ffmpeg-...` 부분의 jar 이름은 OS에 맞춰 1번에서 고른 그 파일명 그대로 적습니다 (zip 안에는 `javacpp-1.5.13-windows-x86_64.jar`, `ffmpeg-8.0.1-1.5.13-windows-x86_64.jar` 같은 긴 이름으로 들어 있고, 위 예시는 짧게 rename한 것 기준입니다).
|
||||||
|
- **5개 모두** 적어야 합니다. `javacpp-<os>.jar` (네이티브) 가 빠지면 JNI bridge 가 로딩 안 돼서 영상이 검게만 보입니다.
|
||||||
|
|
||||||
3. 저장 후 **플레이** 를 누르면 영상이 재생됩니다.
|
3. 저장 후 **플레이** 를 누르면 영상이 재생됩니다.
|
||||||
|
|
||||||
@@ -129,7 +135,7 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
게임 안에서 채팅창에 `/videostick` 을 입력하세요. 정상이라면:
|
게임 안에서 채팅창에 `/videostick` 을 입력하세요. 정상이라면:
|
||||||
|
|
||||||
- 인벤토리에 **비디오 스틱** 아이템이 들어옵니다 (보라/검정 missing-texture 가 아니라 작대기 모양 아이콘).
|
- 인벤토리에 **비디오 스틱** 아이템이 들어옵니다 (보라/검정 missing-texture 가 아니라 작대기 모양 아이콘).
|
||||||
- 보라/검정 missing texture 가 나오면 **STEP 4** 에서 이전 버전 jar가 mods 폴더에 같이 남아있는 경우입니다. 다 지우고 0.4.1 만 남기고 다시 시작하세요.
|
- 보라/검정 missing texture 가 나오면 **STEP 4** 에서 이전 버전 jar(`video_player-0.4.0.jar` / `0.4.1.jar` 등)가 mods 폴더에 같이 남아있는 경우입니다. 다 지우고 `0.4.4` 만 남기고 다시 시작하세요. (0.4.1 이하는 Fabric 26.1.2 model 로더가 unprefixed `item/generated` parent 를 거부해서 스틱 아이콘이 missing-model 큐브로 보입니다 — 0.4.2 에서 수정됨.)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -158,14 +164,36 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
| 명령 | 설명 |
|
| 명령 | 설명 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `/videostick` | 비디오 스틱 아이템을 인벤토리에 지급 |
|
| `/videostick` | 비디오 스틱 아이템을 인벤토리에 지급 |
|
||||||
| `/videoplace <url> [w] [h] [loop] [autoplay]` | 정조준한 블록 면에 즉시 영상 배치 |
|
| `/videoplace <pos> <facing> <w> <h> <url>` | 좌표에 영상 앵커를 즉시 배치 |
|
||||||
| `/videodelete` | 정조준한 블록 면의 영상 제거 |
|
| `/videodelete <pos>` | 좌표의 영상 앵커 제거 |
|
||||||
|
| `/videomute <pos> <on\|off>` | 영상의 음소거 켜고/끄기 |
|
||||||
|
| `/videopreload <url>` | URL 을 미리 받아 디스크 캐시에 저장 (자세한 내용은 아래) |
|
||||||
|
|
||||||
|
`/videoplace`, `/videodelete`, `/videomute`, `/videopreload` 는 기본적으로 OP(권한 레벨 2) 가 필요하므로 **커맨드 블럭에서도 그대로 호출 가능합니다**. 커맨드 블럭은 기본이 권한 레벨 2 라 별도 설정 없이 동작합니다.
|
||||||
|
|
||||||
|
### `/videopreload` — 영상 미리 로딩 (스터터 제거)
|
||||||
|
|
||||||
|
스트리밍 URL 을 라이브로 받으면서 재생하면 네트워크가 잠깐 느려질 때 끊김이 생깁니다. `/videopreload <url>` 을 미리 한번 실행하면 클라이언트가 백그라운드에서 URL 을 통째로 다운로드해서 `.minecraft/video_player_cache/` 폴더에 저장해 두고, 같은 URL 로 영상이 재생될 때 인터넷이 아니라 그 로컬 파일을 사용합니다 (= 끊김 없음).
|
||||||
|
|
||||||
|
```
|
||||||
|
/videopreload https://video.example.com/foo.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
특징:
|
||||||
|
|
||||||
|
- **커맨드 블럭에서 사용 가능** — 예: 압력판 → 커맨드 블럭 `/videopreload <url>` 으로 트리거하면 플레이어가 영상 영역에 다가가기 전에 미리 다운로드 시작
|
||||||
|
- 명령은 서버에서 실행되지만, 다운로드는 각 **클라이언트**(접속해 있는 모든 플레이어)가 자기 PC 에 받습니다
|
||||||
|
- 이미 받아둔 URL 은 재요청해도 다시 다운로드 안 함 (URL 의 SHA-256 으로 캐싱)
|
||||||
|
- 한 파일당 상한 512 MB
|
||||||
|
- 캐시 폴더가 너무 커지면 직접 `.minecraft/video_player_cache/` 안의 파일을 삭제해도 됩니다 (그러면 다음 사용 시 다시 받아옴)
|
||||||
|
|
||||||
|
> 영상 삭제 시 소리가 안 멎던 문제는 0.4.4 에서 수정되었습니다 (앵커 블록이 사라지면 디코더 / 오디오 라인을 즉시 강제 종료).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 알려진 이슈
|
## 알려진 이슈
|
||||||
|
|
||||||
- JavaCV가 안 잡혀있으면 영상 자리만 잡힐 뿐 검게 보입니다. 로그 파일(`.minecraft/logs/latest.log`)에서 `JavaCV not on classpath` WARN 메시지로 확인 가능합니다.
|
- JavaCV가 안 잡혀있으면 영상 자리만 잡힐 뿐 검게 보입니다. 로그 파일(`.minecraft/logs/latest.log`)에서 `JavaCV not on classpath` WARN 또는 `JavaCV decode error: ...UnsatisfiedLinkError... jnijavacpp` 메시지로 확인 가능합니다. 후자는 `javacpp-<os>.jar` 네이티브 jar 가 빠진 케이스입니다 (STEP 5-B 1번의 5개 jar 모두 등록되어야 함).
|
||||||
- 0.3.x 이하 버전에서 만든 영상은 새 버전(0.4.x) 에서 보이지 않으니 다시 배치해야 합니다.
|
- 0.3.x 이하 버전에서 만든 영상은 새 버전(0.4.x) 에서 보이지 않으니 다시 배치해야 합니다.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -176,7 +204,7 @@ Fabric은 마인크래프트에 모드 기능을 추가해 주는 로더입니
|
|||||||
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.1.jar`
|
산출물: `build/libs/video_player-0.4.4.jar`
|
||||||
|
|
||||||
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.2
|
mod_version=0.4.4
|
||||||
maven_group=com.ejclaw.videoplayer
|
maven_group=com.ejclaw.videoplayer
|
||||||
archives_base_name=video_player
|
archives_base_name=video_player
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import com.ejclaw.videoplayer.registry.VideoPlayerBlockEntities;
|
|||||||
import net.fabricmc.api.ClientModInitializer;
|
import net.fabricmc.api.ClientModInitializer;
|
||||||
import net.fabricmc.api.EnvType;
|
import net.fabricmc.api.EnvType;
|
||||||
import net.fabricmc.api.Environment;
|
import net.fabricmc.api.Environment;
|
||||||
|
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientBlockEntityEvents;
|
||||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||||
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
|
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
|
||||||
import net.fabricmc.fabric.api.client.rendering.v1.BlockEntityRendererRegistry;
|
import net.fabricmc.fabric.api.client.rendering.v1.BlockEntityRendererRegistry;
|
||||||
@@ -62,6 +63,16 @@ public class VideoPlayerClient implements ClientModInitializer {
|
|||||||
// no-op for now
|
// no-op for now
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// When an anchor block is deleted (shift+left-click, /videodelete) or its chunk
|
||||||
|
// unloads (player walks away), Minecraft removes the block entity client-side. Hook
|
||||||
|
// that to stop the decode worker and audio line — otherwise VideoPlayback.ENTRIES
|
||||||
|
// keeps holding the backend and the sound keeps playing.
|
||||||
|
ClientBlockEntityEvents.BLOCK_ENTITY_UNLOAD.register((blockEntity, level) -> {
|
||||||
|
if (blockEntity instanceof VideoAnchorBlockEntity) {
|
||||||
|
VideoPlayback.stop(blockEntity.getBlockPos());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
VideoPlayerMod.LOG.info("[{}] client initialized", VideoPlayerMod.MOD_ID);
|
VideoPlayerMod.LOG.info("[{}] client initialized", VideoPlayerMod.MOD_ID);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.ejclaw.videoplayer;
|
|||||||
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.VideoPlayerNetwork;
|
import com.ejclaw.videoplayer.net.VideoPlayerNetwork;
|
||||||
import com.ejclaw.videoplayer.registry.VideoPlayerBlockEntities;
|
import com.ejclaw.videoplayer.registry.VideoPlayerBlockEntities;
|
||||||
@@ -31,6 +32,7 @@ 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);
|
||||||
});
|
});
|
||||||
|
|
||||||
LOG.info("[{}] initialized", MOD_ID);
|
LOG.info("[{}] initialized", MOD_ID);
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ package com.ejclaw.videoplayer.client.net;
|
|||||||
|
|
||||||
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
import com.ejclaw.videoplayer.block.VideoAnchorBlockEntity;
|
||||||
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.VideoPlayback;
|
import com.ejclaw.videoplayer.client.playback.VideoPlayback;
|
||||||
import com.ejclaw.videoplayer.net.OpenScreenPayload;
|
import com.ejclaw.videoplayer.net.OpenScreenPayload;
|
||||||
|
import com.ejclaw.videoplayer.net.PreloadPayload;
|
||||||
import com.ejclaw.videoplayer.net.SyncAnchorPayload;
|
import com.ejclaw.videoplayer.net.SyncAnchorPayload;
|
||||||
import net.fabricmc.api.EnvType;
|
import net.fabricmc.api.EnvType;
|
||||||
import net.fabricmc.api.Environment;
|
import net.fabricmc.api.Environment;
|
||||||
@@ -31,5 +33,12 @@ public final class ClientNetworking {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Server broadcasts a preload request to all clients; each client downloads to its
|
||||||
|
// own video_player_cache/ folder. Runs entirely off-thread, so we don't bounce through
|
||||||
|
// mc.execute() — VideoCache.preload() is itself non-blocking.
|
||||||
|
ClientPlayNetworking.registerGlobalReceiver(PreloadPayload.TYPE, (payload, context) -> {
|
||||||
|
VideoCache.preload(payload.url());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,20 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
private volatile boolean loop = true;
|
private volatile boolean loop = true;
|
||||||
private volatile boolean ready = false;
|
private volatile boolean ready = false;
|
||||||
private volatile boolean closed = false;
|
private volatile boolean closed = false;
|
||||||
|
/**
|
||||||
|
* Held in a field (not just a local) so {@link #close()} can call
|
||||||
|
* {@link SourceDataLine#stop()} / {@link SourceDataLine#flush()} from outside the worker
|
||||||
|
* thread to unblock any in-flight {@link SourceDataLine#write(byte[], int, int)} call.
|
||||||
|
* Without this, deleting an anchor while audio is buffered would leave the worker stuck
|
||||||
|
* in {@code write()} until the in-driver PCM buffer drained naturally, so the deleted
|
||||||
|
* video would keep audible for ~0.5 s after the anchor disappeared.
|
||||||
|
*/
|
||||||
|
private volatile SourceDataLine audioLine;
|
||||||
|
/**
|
||||||
|
* Worker-side handle to the grabber. Held so {@link #close()} can yank it from another
|
||||||
|
* thread when {@code grab()} is blocked on a slow HTTP read.
|
||||||
|
*/
|
||||||
|
private volatile Object grabberHandle;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void play(String url, boolean loop) {
|
public void play(String url, boolean loop) {
|
||||||
@@ -85,6 +99,21 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
|
|
||||||
private void stopWorker() {
|
private void stopWorker() {
|
||||||
running.set(false);
|
running.set(false);
|
||||||
|
// Unblock the audio sink so the worker's line.write() returns immediately instead of
|
||||||
|
// waiting for the in-driver PCM buffer to drain. Without this the audible tail of a
|
||||||
|
// deleted / unloaded anchor outlives the anchor by ~0.5 s.
|
||||||
|
SourceDataLine line = audioLine;
|
||||||
|
if (line != null) {
|
||||||
|
try { line.stop(); } catch (Throwable ignored) {}
|
||||||
|
try { line.flush(); } catch (Throwable ignored) {}
|
||||||
|
}
|
||||||
|
// Yank the grabber too so a blocked grab() inside an HTTP read returns promptly.
|
||||||
|
// JavaCV's close() is best-effort thread-safe — worst case we trip an AVERROR which
|
||||||
|
// the catch-all in runLoop swallows.
|
||||||
|
Object g = grabberHandle;
|
||||||
|
if (g != null) {
|
||||||
|
try { g.getClass().getMethod("close").invoke(g); } catch (Throwable ignored) {}
|
||||||
|
}
|
||||||
Thread t = worker;
|
Thread t = worker;
|
||||||
worker = null;
|
worker = null;
|
||||||
if (t != null) t.interrupt();
|
if (t != null) t.interrupt();
|
||||||
@@ -94,10 +123,11 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
/** Pure-reflection decode loop. Silent fallback if JavaCV isn't present. */
|
/** Pure-reflection decode loop. Silent fallback if JavaCV isn't present. */
|
||||||
private void runLoop(String url) {
|
private void runLoop(String url) {
|
||||||
Object grabber = null;
|
Object grabber = null;
|
||||||
SourceDataLine audioLine = null;
|
SourceDataLine localAudioLine = null;
|
||||||
try {
|
try {
|
||||||
Class<?> grabberCls = Class.forName(GRABBER_CLASS);
|
Class<?> grabberCls = Class.forName(GRABBER_CLASS);
|
||||||
grabber = grabberCls.getConstructor(String.class).newInstance(url);
|
grabber = grabberCls.getConstructor(String.class).newInstance(url);
|
||||||
|
this.grabberHandle = grabber;
|
||||||
Method start = grabberCls.getMethod("start");
|
Method start = grabberCls.getMethod("start");
|
||||||
Method stop = grabberCls.getMethod("stop");
|
Method stop = grabberCls.getMethod("stop");
|
||||||
Method grab = grabberCls.getMethod("grab");
|
Method grab = grabberCls.getMethod("grab");
|
||||||
@@ -108,12 +138,21 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
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);
|
||||||
|
|
||||||
// HTTP(S) tuning for streaming URLs (e.g. webm via Range / chunked transfer).
|
// HTTP(S) tuning for streaming URLs (webm via Range / chunked transfer).
|
||||||
try { setOpt.invoke(grabber, "rw_timeout", "10000000"); } catch (Throwable ignored) {}
|
// Lower timeouts → close() snaps shut fast when an anchor is deleted mid-stream;
|
||||||
try { setOpt.invoke(grabber, "timeout", "10000000"); } catch (Throwable ignored) {}
|
// larger buffer/probe options → smoother playback when the upstream throttles.
|
||||||
try { setOpt.invoke(grabber, "reconnect", "1"); } catch (Throwable ignored) {}
|
try { setOpt.invoke(grabber, "rw_timeout", "3000000"); } catch (Throwable ignored) {}
|
||||||
try { setOpt.invoke(grabber, "reconnect_streamed", "1"); } catch (Throwable ignored) {}
|
try { setOpt.invoke(grabber, "timeout", "3000000"); } catch (Throwable ignored) {}
|
||||||
try { setOpt.invoke(grabber, "reconnect_at_eof", "1"); } catch (Throwable ignored) {}
|
try { setOpt.invoke(grabber, "reconnect", "1"); } catch (Throwable ignored) {}
|
||||||
|
try { setOpt.invoke(grabber, "reconnect_streamed", "1"); } catch (Throwable ignored) {}
|
||||||
|
try { setOpt.invoke(grabber, "reconnect_at_eof", "1"); } catch (Throwable ignored) {}
|
||||||
|
try { setOpt.invoke(grabber, "reconnect_delay_max", "2"); } catch (Throwable ignored) {}
|
||||||
|
// Bigger network read window so a transient stall doesn't starve the decoder.
|
||||||
|
try { setOpt.invoke(grabber, "buffer_size", "1048576"); } catch (Throwable ignored) {}
|
||||||
|
try { setOpt.invoke(grabber, "probesize", "8388608"); } catch (Throwable ignored) {}
|
||||||
|
try { setOpt.invoke(grabber, "analyzeduration", "2000000"); } catch (Throwable ignored) {}
|
||||||
|
try { setOpt.invoke(grabber, "max_delay", "500000"); } catch (Throwable ignored) {}
|
||||||
|
try { setOpt.invoke(grabber, "fflags", "+genpts"); } catch (Throwable ignored) {}
|
||||||
try { setOpt.invoke(grabber, "user_agent",
|
try { setOpt.invoke(grabber, "user_agent",
|
||||||
"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.
|
||||||
@@ -126,7 +165,8 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
|
|
||||||
int sampleRate = safeInt(getSampleRate, grabber);
|
int sampleRate = safeInt(getSampleRate, grabber);
|
||||||
int audioChannels = safeInt(getAudioChannels, grabber);
|
int audioChannels = safeInt(getAudioChannels, grabber);
|
||||||
audioLine = openLine(sampleRate, audioChannels);
|
localAudioLine = openLine(sampleRate, audioChannels);
|
||||||
|
this.audioLine = localAudioLine;
|
||||||
|
|
||||||
Class<?> frameCls = Class.forName(FRAME_CLASS);
|
Class<?> frameCls = Class.forName(FRAME_CLASS);
|
||||||
Field imageField = frameCls.getField("image");
|
Field imageField = frameCls.getField("image");
|
||||||
@@ -137,9 +177,16 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
|
|
||||||
while (running.get() && !closed) {
|
while (running.get() && !closed) {
|
||||||
if (paused.get()) { Thread.sleep(20); continue; }
|
if (paused.get()) { Thread.sleep(20); continue; }
|
||||||
Object frame = grab.invoke(grabber);
|
Object frame;
|
||||||
|
try {
|
||||||
|
frame = grab.invoke(grabber);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
// grabber.close() from another thread races our grab(); treat as a clean exit.
|
||||||
|
if (!running.get() || closed) break;
|
||||||
|
throw t;
|
||||||
|
}
|
||||||
if (frame == null) {
|
if (frame == null) {
|
||||||
if (loop) {
|
if (loop && running.get() && !closed) {
|
||||||
try { stop.invoke(grabber); } catch (Throwable ignored) {}
|
try { stop.invoke(grabber); } catch (Throwable ignored) {}
|
||||||
try { start.invoke(grabber); } catch (Throwable ignored) {}
|
try { start.invoke(grabber); } catch (Throwable ignored) {}
|
||||||
continue;
|
continue;
|
||||||
@@ -148,8 +195,8 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Object[] samples = (Object[]) samplesField.get(frame);
|
Object[] samples = (Object[]) samplesField.get(frame);
|
||||||
if (samples != null && samples.length > 0 && audioLine != null) {
|
if (samples != null && samples.length > 0 && localAudioLine != null) {
|
||||||
writeAudio(audioLine, samples, this.gain);
|
writeAudio(localAudioLine, samples, this.gain);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object[] images = (Object[]) imageField.get(frame);
|
Object[] images = (Object[]) imageField.get(frame);
|
||||||
@@ -164,7 +211,7 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
|
|
||||||
// If we have an open audio line, SourceDataLine.write() blocks for backpressure
|
// If we have an open audio line, SourceDataLine.write() blocks for backpressure
|
||||||
// and provides natural A/V pacing; otherwise tick ~60fps so we don't busy-loop.
|
// and provides natural A/V pacing; otherwise tick ~60fps so we don't busy-loop.
|
||||||
if (audioLine == null) Thread.sleep(15);
|
if (localAudioLine == null) Thread.sleep(15);
|
||||||
}
|
}
|
||||||
} catch (ClassNotFoundException cnf) {
|
} catch (ClassNotFoundException cnf) {
|
||||||
VideoPlayerMod.LOG.warn(
|
VideoPlayerMod.LOG.warn(
|
||||||
@@ -177,11 +224,13 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
VideoPlayerMod.LOG.warn("[{}] JavaCV decode error: {}", VideoPlayerMod.MOD_ID, t.toString());
|
VideoPlayerMod.LOG.warn("[{}] JavaCV decode error: {}", VideoPlayerMod.MOD_ID, t.toString());
|
||||||
} finally {
|
} finally {
|
||||||
ready = false;
|
ready = false;
|
||||||
if (audioLine != null) {
|
this.audioLine = null;
|
||||||
try { audioLine.drain(); } catch (Throwable ignored) {}
|
if (localAudioLine != null) {
|
||||||
try { audioLine.stop(); } catch (Throwable ignored) {}
|
try { localAudioLine.stop(); } catch (Throwable ignored) {}
|
||||||
try { audioLine.close(); } catch (Throwable ignored) {}
|
try { localAudioLine.flush(); } catch (Throwable ignored) {}
|
||||||
|
try { localAudioLine.close(); } catch (Throwable ignored) {}
|
||||||
}
|
}
|
||||||
|
this.grabberHandle = null;
|
||||||
if (grabber != null) {
|
if (grabber != null) {
|
||||||
try { grabber.getClass().getMethod("close").invoke(grabber); } catch (Throwable ignored) {}
|
try { grabber.getClass().getMethod("close").invoke(grabber); } catch (Throwable ignored) {}
|
||||||
}
|
}
|
||||||
@@ -194,7 +243,11 @@ 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);
|
||||||
line.open(fmt);
|
// ~0.5 s of audio buffered in the driver. Smooths over upstream hiccups without
|
||||||
|
// delaying close() — stopWorker() calls line.stop() / line.flush() to dump it.
|
||||||
|
int frameSizeBytes = 2 * channels;
|
||||||
|
int bufferBytes = Math.max(sampleRate * frameSizeBytes / 2, frameSizeBytes * 1024);
|
||||||
|
line.open(fmt, bufferBytes);
|
||||||
line.start();
|
line.start();
|
||||||
return line;
|
return line;
|
||||||
} catch (Throwable t) {
|
} catch (Throwable t) {
|
||||||
@@ -229,7 +282,11 @@ public class JavaCvBackend implements VideoBackend {
|
|||||||
pcm[idx++] = (byte) ((scaled >> 8) & 0xFF);
|
pcm[idx++] = (byte) ((scaled >> 8) & 0xFF);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
line.write(pcm, 0, pcm.length);
|
try {
|
||||||
|
line.write(pcm, 0, pcm.length);
|
||||||
|
} catch (Throwable ignored) {
|
||||||
|
// line may have been stop()'d from another thread mid-write — treat as a clean exit.
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int safeInt(Method m, Object target) {
|
private static int safeInt(Method m, Object target) {
|
||||||
|
|||||||
@@ -0,0 +1,192 @@
|
|||||||
|
package com.ejclaw.videoplayer.client.playback;
|
||||||
|
|
||||||
|
import com.ejclaw.videoplayer.VideoPlayerMod;
|
||||||
|
import net.fabricmc.api.EnvType;
|
||||||
|
import net.fabricmc.api.Environment;
|
||||||
|
import net.minecraft.client.Minecraft;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URLConnection;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client-side disk cache for preloaded HTTP video URLs. Driven by the {@code /videopreload}
|
||||||
|
* command (routed to clients via {@code PreloadPayload}). Once a URL is fully downloaded into
|
||||||
|
* {@code <gameDir>/video_player_cache/<sha256>.<ext>}, {@link #lookup(String)} returns its local
|
||||||
|
* path so {@link VideoPlayback} can hand FFmpeg a {@code file://} input that doesn't stall on
|
||||||
|
* network hiccups.
|
||||||
|
*
|
||||||
|
* <p>Concurrency model: {@link #preload(String)} returns immediately and downloads on a daemon
|
||||||
|
* background thread. {@link #lookup(String)} only returns once the download has finished
|
||||||
|
* (atomic rename from {@code .part}), so callers never see a half-written file.
|
||||||
|
*/
|
||||||
|
@Environment(EnvType.CLIENT)
|
||||||
|
public final class VideoCache {
|
||||||
|
private VideoCache() {}
|
||||||
|
|
||||||
|
/** url → local absolute path of the fully-downloaded cache file. */
|
||||||
|
private static final Map<String, Path> READY = new ConcurrentHashMap<>();
|
||||||
|
/** urls whose download is currently in flight. */
|
||||||
|
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;
|
||||||
|
|
||||||
|
/** Kick off a background download. No-op if already cached or in flight. */
|
||||||
|
public static void preload(String url) {
|
||||||
|
if (url == null || url.isEmpty()) return;
|
||||||
|
if (!(url.startsWith("http://") || url.startsWith("https://"))) return;
|
||||||
|
if (READY.containsKey(url)) {
|
||||||
|
VideoPlayerMod.LOG.info("[{}] preload: already cached {}", VideoPlayerMod.MOD_ID, url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!IN_FLIGHT.add(url)) {
|
||||||
|
VideoPlayerMod.LOG.info("[{}] preload: already downloading {}", VideoPlayerMod.MOD_ID, url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Thread t = new Thread(() -> download(url), "video_player-preload");
|
||||||
|
t.setDaemon(true);
|
||||||
|
t.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Return the local cached file path for this URL, or {@code null} if not yet ready. */
|
||||||
|
public static Path lookup(String url) {
|
||||||
|
if (url == null) return null;
|
||||||
|
Path p = READY.get(url);
|
||||||
|
if (p != null && Files.exists(p)) return p;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop the in-memory index (does not delete files). Called on disconnect. */
|
||||||
|
public static void clearIndex() {
|
||||||
|
READY.clear();
|
||||||
|
IN_FLIGHT.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Caller-supplied: current set of URLs that are fully cached, for diagnostics. */
|
||||||
|
public static Set<String> readyUrls() {
|
||||||
|
return new HashSet<>(READY.keySet());
|
||||||
|
}
|
||||||
|
|
||||||
|
// -- internals -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static void download(String url) {
|
||||||
|
Path cacheDir = cacheDir();
|
||||||
|
try {
|
||||||
|
if (cacheDir == null) {
|
||||||
|
VideoPlayerMod.LOG.warn("[{}] preload: no game dir, skipping {}",
|
||||||
|
VideoPlayerMod.MOD_ID, url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Files.createDirectories(cacheDir);
|
||||||
|
|
||||||
|
String hash = sha256(url);
|
||||||
|
String ext = extensionFromUrl(url);
|
||||||
|
Path finalPath = cacheDir.resolve(hash + ext);
|
||||||
|
Path partPath = cacheDir.resolve(hash + ext + ".part");
|
||||||
|
|
||||||
|
// Resume-friendly: if the file's already on disk from an earlier session, just
|
||||||
|
// index it without re-downloading.
|
||||||
|
if (Files.exists(finalPath) && Files.size(finalPath) > 0) {
|
||||||
|
READY.put(url, finalPath);
|
||||||
|
VideoPlayerMod.LOG.info("[{}] preload: indexed existing cache {} -> {}",
|
||||||
|
VideoPlayerMod.MOD_ID, url, finalPath.getFileName());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
URLConnection raw = URI.create(url).toURL().openConnection();
|
||||||
|
raw.setConnectTimeout(10_000);
|
||||||
|
raw.setReadTimeout(30_000);
|
||||||
|
raw.setRequestProperty("User-Agent", "video_player/" + VideoPlayerMod.MOD_ID);
|
||||||
|
if (raw instanceof HttpURLConnection http) {
|
||||||
|
http.setInstanceFollowRedirects(true);
|
||||||
|
int code = http.getResponseCode();
|
||||||
|
if (code >= 400) {
|
||||||
|
VideoPlayerMod.LOG.warn("[{}] preload: HTTP {} for {}",
|
||||||
|
VideoPlayerMod.MOD_ID, code, url);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
long total = 0;
|
||||||
|
try (InputStream in = raw.getInputStream();
|
||||||
|
OutputStream out = Files.newOutputStream(partPath)) {
|
||||||
|
byte[] buf = new byte[64 * 1024];
|
||||||
|
int n;
|
||||||
|
while ((n = in.read(buf)) >= 0) {
|
||||||
|
total += n;
|
||||||
|
if (total > MAX_BYTES) {
|
||||||
|
VideoPlayerMod.LOG.warn(
|
||||||
|
"[{}] preload: {} exceeded {} MB cap; aborting",
|
||||||
|
VideoPlayerMod.MOD_ID, url, MAX_BYTES / (1024 * 1024));
|
||||||
|
try { Files.deleteIfExists(partPath); } catch (Throwable ignored) {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
out.write(buf, 0, n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.move(partPath, finalPath, StandardCopyOption.REPLACE_EXISTING,
|
||||||
|
StandardCopyOption.ATOMIC_MOVE);
|
||||||
|
READY.put(url, finalPath);
|
||||||
|
VideoPlayerMod.LOG.info("[{}] preload: cached {} ({} bytes) -> {}",
|
||||||
|
VideoPlayerMod.MOD_ID, url, total, finalPath.getFileName());
|
||||||
|
} catch (Throwable t) {
|
||||||
|
VideoPlayerMod.LOG.warn("[{}] preload failed for {}: {}",
|
||||||
|
VideoPlayerMod.MOD_ID, url, t.toString());
|
||||||
|
} finally {
|
||||||
|
IN_FLIGHT.remove(url);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path cacheDir() {
|
||||||
|
Minecraft mc = Minecraft.getInstance();
|
||||||
|
if (mc == null || mc.gameDirectory == null) return null;
|
||||||
|
return mc.gameDirectory.toPath().resolve("video_player_cache");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SHA-256 of the URL, hex. */
|
||||||
|
private static String sha256(String s) {
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||||
|
byte[] dig = md.digest(s.getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
StringBuilder sb = new StringBuilder(64);
|
||||||
|
for (byte b : dig) sb.append(String.format("%02x", b));
|
||||||
|
return sb.toString();
|
||||||
|
} catch (Throwable t) {
|
||||||
|
// Fallback: tag with identity hash. Still unique within a session.
|
||||||
|
return "h" + Integer.toHexString(s.hashCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Best-effort filename extension from the URL path so FFmpeg's container probe gets a hint
|
||||||
|
* (e.g. {@code .webm} for a webm stream). Falls back to {@code .bin}.
|
||||||
|
*/
|
||||||
|
private static String extensionFromUrl(String url) {
|
||||||
|
try {
|
||||||
|
String path = URI.create(url).getPath();
|
||||||
|
if (path == null) return ".bin";
|
||||||
|
int slash = path.lastIndexOf('/');
|
||||||
|
String tail = slash < 0 ? path : path.substring(slash + 1);
|
||||||
|
int dot = tail.lastIndexOf('.');
|
||||||
|
if (dot <= 0 || dot == tail.length() - 1) return ".bin";
|
||||||
|
String ext = tail.substring(dot).toLowerCase();
|
||||||
|
// Sanity-clamp: only allow short, safe extensions.
|
||||||
|
if (ext.length() > 8 || !ext.matches("\\.[a-z0-9]+")) return ".bin";
|
||||||
|
return ext;
|
||||||
|
} catch (Throwable t) {
|
||||||
|
return ".bin";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import net.minecraft.core.BlockPos;
|
|||||||
import net.minecraft.resources.Identifier;
|
import net.minecraft.resources.Identifier;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.file.Path;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Iterator;
|
import java.util.Iterator;
|
||||||
@@ -58,7 +59,12 @@ public final class VideoPlayback {
|
|||||||
}
|
}
|
||||||
|
|
||||||
VideoBackend backend = WatermediaProbe.isAvailable() ? new WatermediaBackend() : new JavaCvBackend();
|
VideoBackend backend = WatermediaProbe.isAvailable() ? new WatermediaBackend() : new JavaCvBackend();
|
||||||
backend.play(be.getUrl(), be.isLoop());
|
// If /videopreload already cached the URL to disk, hand the local file path to FFmpeg
|
||||||
|
// instead of the HTTP URL — eliminates the network read entirely. Falls back to the
|
||||||
|
// live URL when the cache miss or the download hasn't finished yet.
|
||||||
|
Path cached = VideoCache.lookup(be.getUrl());
|
||||||
|
String source = cached != null ? cached.toAbsolutePath().toString() : be.getUrl();
|
||||||
|
backend.play(source, be.isLoop());
|
||||||
backend.setVolume(be.isMuted() ? 0F : be.getVolume());
|
backend.setVolume(be.isMuted() ? 0F : be.getVolume());
|
||||||
|
|
||||||
Entry created = new Entry(be.getUrl(), backend);
|
Entry created = new Entry(be.getUrl(), backend);
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
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.
|
||||||
|
src.sendSuccess(() -> Component.literal(
|
||||||
|
"preload requested for " + sentFinal + " client(s): " + payload.url()), false);
|
||||||
|
return sent;
|
||||||
|
}
|
||||||
|
}
|
||||||
27
src/main/java/com/ejclaw/videoplayer/net/PreloadPayload.java
Normal file
27
src/main/java/com/ejclaw/videoplayer/net/PreloadPayload.java
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
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 — instruct connected clients to prefetch {@code url} into their local
|
||||||
|
* {@code video_player_cache/} directory. Triggered by {@code /videopreload}.
|
||||||
|
*/
|
||||||
|
public record PreloadPayload(String url) implements CustomPacketPayload {
|
||||||
|
public static final CustomPacketPayload.Type<PreloadPayload> TYPE =
|
||||||
|
new CustomPacketPayload.Type<>(Identifier.fromNamespaceAndPath(VideoPlayerMod.MOD_ID, "preload"));
|
||||||
|
|
||||||
|
public static final StreamCodec<RegistryFriendlyByteBuf, PreloadPayload> CODEC = StreamCodec.composite(
|
||||||
|
ByteBufCodecs.STRING_UTF8, PreloadPayload::url,
|
||||||
|
PreloadPayload::new
|
||||||
|
);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Type<? extends CustomPacketPayload> type() {
|
||||||
|
return TYPE;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -24,6 +24,7 @@ public final class VideoPlayerNetwork {
|
|||||||
// S2C
|
// S2C
|
||||||
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);
|
||||||
// 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);
|
||||||
|
|||||||
Reference in New Issue
Block a user