Compare commits

...
20 Commits
Author SHA1 Message Date
yiling 8446eaba94 fix(webui): fix arrow key frame rounding and duplicate event bubbling
- Use Math.round instead of Math.floor for keyboard arrow frame navigation in ModelViewer
- Add e.stopPropagation() to RulerSlider keyboard events to prevent duplicate bubbling to window listener
2026-10-09 12:25:05 +08:00
yiling 7c264ee447 fix(webui): prevent ruler snap-back caused by floating point second truncation
- Use Math.round instead of Math.floor in secondToDegree to avoid 0.999996 dropping to previous frame
- Ensure final dragDegree is committed on pointer up
2026-10-09 12:18:23 +08:00
yiling 127bd033b3 feat(webui): snap RulerSlider track directly to discrete 15° ticks during drag 2026-10-09 12:13:38 +08:00
yiling e691acc45b fix(webui): prevent RulerSlider from collapsing to 0px width in control bar
- Use flex layout with flex-1 on left and right clusters to preserve center cluster width
- Enforce min-w-[140px] and w-full on RulerSlider
- Fix tooltip positioning and remove outer overflow-hidden
2026-10-09 12:07:46 +08:00
yiling 380c0854f8 feat(webui): unify 3D viewer bottom bar and redesign cyclic ruler slider
- Place RulerSlider in single row with playback and zoom controls, centered with max 320px width
- Flank RulerSlider with minus and plus buttons to step angle by 15°
- Redesign RulerSlider with fixed center indicator and moving cyclic track with continuous 360° wrapping
- Render major ticks longer at 60° intervals without numeric text labels on track
- Display floating degree tooltip above center indicator only during dragging
2026-10-09 11:59:40 +08:00
yiling ae6cdc88da fix(webui): align 3D model viewer layout and full-width control bar with video viewer 2026-10-08 23:47:41 +08:00
yiling 2e24646c8b feat(turntable): increase upload timeout to 15m to support 5GB uploads 2026-10-08 23:28:05 +08:00
yiling e06409690a perf(turntable): stream file via Bun.file and increase upload timeout 2026-10-08 23:20:44 +08:00
yiling 06ea4eed78 feat(transcode): add 3D asset support and turntable viewer 2026-10-08 23:12:09 +08:00
4b1b64fe2b feat(kanban): link related assets to their file or folder (#453)
Related assets in the task edit dialog were plain rows with no way to
open them. Add an opt-in `linkable` prop to TaskRelatedAssets that turns
each row's thumbnail and name into a router Link to the asset in its
project (files -> /projects/$projectId/files/$fileId, folders ->
/projects/$projectId/folders/$folderId), falling back to the task's
project when the asset has none. The edit dialog opts in; the create
dialog does not, so a click cannot discard an unsaved draft.

Co-authored-by: Frederic De Decker <hello@trinity.video>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 20:14:36 +08:00
yiling f8beb195dd Release v0.5.1 2026-10-06 22:29:50 +08:00
yiling a97996cb59 docs(changelog): note clickable notification cards 2026-10-06 22:18:18 +08:00
jorgeandYiling-J f870ca9b49 feat(asset): link to assets on notification cards. (#451)
* feat(asset): link to assets on notification cards.

* Update packages/webui/components/notification-card.tsx

Co-authored-by: Yiling-J <njjyl723@gmail.com>

---------

Co-authored-by: Yiling-J <njjyl723@gmail.com>
2026-10-06 22:14:11 +08:00
Yiling-J 2e5ff281a8 feat(transcode): add hardware decoding support for nvenc, qsv, and rkmpp (#452)
* feat(transcode): add hardware decoding support for nvenc, qsv, and rkmpp

* refactor(transcode): eliminate redundant hardware decode gating and dead condition
2026-10-06 17:35:14 +08:00
yiling de8decf113 fix(ci): prevent tagging main on PR workflow_dispatch docker builds 2026-10-06 11:49:49 +08:00
Cameron HarrisandClaude Opus 5.5 dd57fb9ed2 feat(transcode): decode and scale on the GPU for hardware transcodes (VA-API) (#449)
* feat(transcode): decode and scale on the GPU for VA-API transcodes

When the selected encoder is h264_vaapi, decode with -hwaccel vaapi and
scale with scale_vaapi so frames stay in GPU memory, instead of decoding
and scaling on the CPU and hwupload-ing before the encoder. On a Haswell
iGPU this makes 4K proxy/HLS renditions 3-5x faster.

Fallback order: GPU decode + VA-API encode -> software decode + VA-API
encode (previous behavior) -> libx264. Watermark overlays, HDR sources
and rotated sources skip GPU decode: ffmpeg cannot auto-insert its
rotation filter on hardware frames, so rotated input would otherwise come
out sideways instead of failing. SHUMAI_VAAPI_HW_DECODE=false disables it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(transcode): document VA-API GPU decoding and SHUMAI_VAAPI_HW_DECODE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(transcode): generic hardware decode config, stall watchdog, reuse probed rotation

Follow-ups from comparing with Immich and Jellyfin:

- Replace the VA-API-specific helpers with a per-encoder HW_DECODE_CONFIGS
  table (input args, output args, GPU scale filter) and build the MP4 and
  HLS input/filter graph in one shared method so the paths cannot drift.
  Only h264_vaapi has an entry; other backends can be added once tested on
  real hardware. The opt-out is now SHUMAI_HW_DECODE=false.
- Kill a GPU-decode attempt with SIGKILL when its output stops growing for
  SHUMAI_HW_DECODE_STALL_TIMEOUT (default 120s) and fall back, since some
  VA-API driver failures hang ffmpeg instead of exiting (immich#31933).
- Add -noautoscale on the GPU-decode path so a mid-stream decoder reinit
  (e.g. 1080 -> 1088) cannot auto-insert a software scaler into the GPU
  graph (jellyfin#17133).
- Pass the rotation already probed into MediaMetadata through the workflow
  and activities as sourceRotation; ffprobe only runs when it is missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:00:01 +08:00
Yiling-J 9a640632aa ci(release): allow manual Docker image build from external PR (#450) 2026-10-05 09:48:48 +08:00
yiling e61641d7ec fix(workflow): increase activity startToCloseTimeout to 120 minutes 2026-10-04 10:22:31 +08:00
Yiling-J 7ca8ba8b2a fix(transcode): resolve RAW transcoding hang in Docker deployments (#447) 2026-10-03 12:45:12 +08:00
Yiling-J 8805d5799a feat(transcode): add dcraw_emu fallback for RAW image preview generation (#446) 2026-10-03 11:03:31 +08:00
85 changed files with 6097 additions and 233 deletions
+11 -1
View File
@@ -10,6 +10,10 @@ on:
description: 'Docker image tag (e.g. feature-vaapi)'
required: false
type: string
pr:
description: 'Pull request number (e.g. 449)'
required: false
type: string
jobs:
build-and-push:
@@ -20,7 +24,10 @@ jobs:
steps:
- name: Checkout repository
id: checkout
uses: actions/checkout@v4
with:
ref: ${{ inputs.pr && format('refs/pull/{0}/head', inputs.pr) || github.ref }}
# Set up Docker Buildx
- name: Set up Docker Buildx
@@ -51,8 +58,11 @@ jobs:
crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai
tags: |
type=semver,pattern={{version}}
type=ref,event=branch
type=ref,event=branch,enable=${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && !inputs.pr && !inputs.tag) }}
type=raw,value=pr-${{ inputs.pr }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.pr != '' && inputs.tag == '' }}
type=raw,value=${{ inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' && inputs.tag != '' }}
labels: |
org.opencontainers.image.revision=${{ steps.checkout.outputs.commit }}
# Build and push Docker image
- name: Build and push Docker image
+19
View File
@@ -8,10 +8,29 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
* **3d**: Add support for 3D model files (.glb, .gltf, .obj, .fbx, .stl, .dae, .usd, .usda, .usdc, .usdz) with automated turntable video rendering, hover sprite scrubbing, and an interactive 3D turntable viewer featuring 360° ruler scrubbing and degree-based markup comments
* **settings**: Add Turntable Renderer settings card with server connection testing and environment variable override support
* **kanban**: Related assets on a task are now clickable, taking you directly to that file or folder in its project
### Fixed
### Changed
- **viewer**: Refine the 3D turntable viewer bottom bar into a unified single row with a centered cyclic ruler slider, fixed center indicator, degree tooltip on drag, and ±15° step buttons
## [0.5.1] - 2026-10-06
### Added
* **notification**: Notification cards are now clickable, taking you directly to the relevant file
* **transcode**: Add hardware decoding and GPU scaling support for NVIDIA NVENC, Intel QuickSync Video (QSV), Rockchip (RKMPP), and VA-API (Intel and AMD GPUs), significantly speeding up video proxy and HLS rendition generation across supported platforms. Set `SHUMAI_HW_DECODE=false` to turn hardware decoding off
* **transcode**: Add `dcraw_emu` fallback to generate WebP previews for camera RAW files without embedded JPEG previews
### Fixed
### Changed
## [0.5.0] - 2026-10-02
### Added
+2
View File
@@ -52,6 +52,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
poppler-utils \
imagemagick \
fonts-noto-cjk \
libraw-bin \
libimage-exiftool-perl \
&& . /etc/os-release \
&& TARGETARCH=$(dpkg --print-architecture) \
&& FFMPEG_VERSION="8.1.2-5" \
+6 -4
View File
@@ -162,23 +162,24 @@ Shumai requires the following system packages on Linux:
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
- **`poppler`** (`poppler-utils`) – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
- **`dcraw_emu`** (`libraw` / `libraw-bin`) – Used for camera RAW format image decoding and preview generation.
- **`bubblewrap`**, **`socat`**, and **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`) for process isolation, networking, and workspace search.
Install all required packages with one command:
> Ubuntu/Debian
```bash
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep libraw-bin
```
> Fedora
```bash
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep LibRaw
```
> Arch Linux
```bash
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep libraw
```
> [!NOTE]
@@ -201,12 +202,13 @@ Shumai requires:
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
- **`poppler`** – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
- **`dcraw_emu`** (`libraw`) – Used for camera RAW format image decoding and preview generation.
- **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`).
Install the required packages with Homebrew:
```bash
brew install ffmpeg poppler imagemagick ripgrep
brew install ffmpeg poppler imagemagick ripgrep libraw
```
---
+7 -5
View File
@@ -187,23 +187,24 @@ mkdir shumai && cd shumai
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
- **`poppler`** (`poppler-utils`) —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
- **`dcraw_emu`** (`libraw` / `libraw-bin`) —— 用于相机 RAW 格式图像解码和预览图生成。
- **`bubblewrap`**、**`socat`** 和 **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需,用于进程隔离、网络通信和工作区搜索。
可以使用以下命令一次性安装所有依赖:
> Ubuntu/Debian
```bash
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep libraw-bin
```
> Fedora
```bash
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep LibRaw
```
> Arch Linux
```bash
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep libraw
```
> [!NOTE]
@@ -215,7 +216,7 @@ sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
> ```
>
> 或者,配置 AppArmor Profile,为相关可执行文件授予所需的 `userns` 权限。
> 或者,配置 AppArmor Profile,为相关可执行文件授予所需的 `userns`权限。
---
@@ -226,12 +227,13 @@ sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
- **`poppler`** —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
- **`dcraw_emu`** (`libraw`) —— 用于相机 RAW 格式图像解码和预览图生成。
- **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需。
使用 Homebrew 安装所需依赖:
```bash
brew install ffmpeg poppler imagemagick ripgrep
brew install ffmpeg poppler imagemagick ripgrep libraw
```
---
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent-app",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/cli",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/premiere-uxp",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "commonjs",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode-app",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"bin": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/web-app",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"dependencies": {
+15 -15
View File
@@ -33,7 +33,7 @@
},
"apps/agent": {
"name": "@shumai/agent-app",
"version": "0.5.0",
"version": "0.5.1",
"bin": {
"shumai-agent": "./src/index.ts",
},
@@ -45,7 +45,7 @@
},
"apps/cli": {
"name": "@shumai/cli",
"version": "0.5.0",
"version": "0.5.1",
"bin": {
"shumai-cli": "./src/index.ts",
},
@@ -60,7 +60,7 @@
},
"apps/premiere-uxp": {
"name": "@shumai/premiere-uxp",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@shumai/api": "workspace:*",
"@shumai/dtos": "workspace:*",
@@ -114,7 +114,7 @@
},
"apps/transcode": {
"name": "@shumai/transcode-app",
"version": "0.5.0",
"version": "0.5.1",
"bin": {
"shumai-transcode": "./src/index.ts",
},
@@ -126,7 +126,7 @@
},
"apps/web": {
"name": "@shumai/web-app",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@shumai/agent": "workspace:*",
"@shumai/api": "workspace:*",
@@ -146,7 +146,7 @@
},
"packages/agent": {
"name": "@shumai/agent",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@anthropic-ai/sandbox-runtime": "0.0.74",
"@earendil-works/pi-agent-core": "0.82.1",
@@ -171,7 +171,7 @@
},
"packages/api": {
"name": "@shumai/api",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@hono/zod-validator": "0.7.6",
"@shumai/core": "workspace:*",
@@ -185,7 +185,7 @@
},
"packages/core": {
"name": "@shumai/core",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@ai-sdk/alibaba": "2.0.38",
"@ai-sdk/amazon-bedrock": "5.0.67",
@@ -247,7 +247,7 @@
},
"packages/db": {
"name": "@shumai/db",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@prisma/adapter-pg": "7.10.0",
@@ -263,7 +263,7 @@
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"zod": "4.5.4",
@@ -271,7 +271,7 @@
},
"packages/e2e": {
"name": "@shumai/e2e",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@earendil-works/pi-agent-core": "0.82.1",
"@google/genai": "2.19.0",
@@ -286,11 +286,11 @@
},
"packages/tableprinter": {
"name": "@shumai/tableprinter",
"version": "0.5.0",
"version": "0.5.1",
},
"packages/transcode": {
"name": "@shumai/transcode",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
@@ -304,7 +304,7 @@
},
"packages/webui": {
"name": "@shumai/webui",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@base-ui/react": "1.7.0",
"@dnd-kit/abstract": "0.5.0",
@@ -406,7 +406,7 @@
},
"packages/workflow-core": {
"name": "@shumai/workflow-core",
"version": "0.5.0",
"version": "0.5.1",
"dependencies": {
"@shumai/core": "workspace:*",
"@shumai/db": "workspace:*",
+14
View File
@@ -3,6 +3,20 @@ title: "Changelog"
description: "Recent updates, new features, and improvements in Shumai"
---
<Update label="v0.5.1" description="October 6, 2026">
### Added
* **notification**: Notification cards are now clickable, taking you directly to the relevant file
* **transcode**: Add hardware decoding and GPU scaling support for NVIDIA NVENC, Intel QuickSync Video (QSV), Rockchip (RKMPP), and VA-API (Intel and AMD GPUs), significantly speeding up video proxy and HLS rendition generation across supported platforms. Set `SHUMAI_HW_DECODE=false` to turn hardware decoding off
* **transcode**: Add `dcraw_emu` fallback to generate WebP previews for camera RAW files without embedded JPEG previews
### Fixed
### Changed
</Update>
<Update label="v0.5.0" description="October 2, 2026">
### Added
@@ -55,6 +55,20 @@ Shumai includes a built-in usability probe that tests hardware encoders at start
You should see `card0` and `renderD128` (or similar).
2. Shumai's Docker image automatically adjusts group permissions on container startup so the non-root application user can access host `/dev/dri` devices without permission errors.
#### GPU decoding
With VA-API, Shumai decodes and resizes video on the GPU as well as encoding it, so frames never leave GPU memory. This is much faster than decoding on the CPU, especially for 4K sources on integrated graphics. (Other backends currently decode on the CPU and encode on the GPU.)
Some videos automatically use CPU decoding with GPU encoding instead:
- Codecs your GPU cannot decode, such as HEVC or 10-bit video on older Intel chips. Shumai tries the GPU first and retries on the CPU within a second.
- Rotated videos, such as portrait phone recordings, so they keep the correct orientation.
- Watermarked share links and HDR sources.
If a GPU-decode attempt stops making progress for 2 minutes (some driver bugs make ffmpeg hang instead of failing), Shumai stops it and retries on the CPU. Change the limit with `SHUMAI_HW_DECODE_STALL_TIMEOUT` (in seconds).
To always decode on the CPU, set `SHUMAI_HW_DECODE=false` on the `shumai` service.
### WSL2 (Windows)
- Ensure you are running Windows 11 with WSL2 and have installed the appropriate GPU drivers on the Windows host.
+3
View File
@@ -44,6 +44,9 @@ To handle media processing and security isolation, the host machine must have th
- **FFmpeg & FFprobe**: Required for video transcoding and metadata extraction.
- _macOS_: `brew install ffmpeg`
- _Linux (Ubuntu/Debian)_: `sudo apt-get install ffmpeg`
- **dcraw_emu (LibRaw)**: Required for camera RAW image decoding and preview generation.
- _macOS_: `brew install libraw`
- _Linux (Ubuntu/Debian)_: `sudo apt-get install libraw-bin`
- **Agent Sandbox Utilities**: Used to run custom automation scripts securely.
- _macOS_: `brew install ripgrep`
- _Linux (Ubuntu/Debian)_: `sudo apt-get install bubblewrap socat ripgrep`
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "shumai",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"repository": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/agent",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/api",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+110
View File
@@ -52,6 +52,14 @@ vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
},
}))
vi.mock('@shumai/core/src/turntable/turntable', () => ({
turntableService: {
getSettings: vi.fn(),
updateSettings: vi.fn(),
testConnection: vi.fn(),
},
}))
describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -638,5 +646,107 @@ describe('team api', () => {
}),
)
})
it('GET /teams/:teamId/turntable-settings returns turntable settings', async () => {
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
vi.mocked(turntableService.getSettings).mockResolvedValue({
url: 'http://localhost:3001',
username: 'user',
hasPassword: true,
isEnvConfigured: false,
})
const res = await app.request('/teams/t1/turntable-settings')
expect(res.status).toBe(200)
const data = await res.json()
expect(data).toEqual({
url: 'http://localhost:3001',
username: 'user',
hasPassword: true,
isEnvConfigured: false,
})
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Read,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('PUT /teams/:teamId/turntable-settings updates settings when not env configured', async () => {
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
vi.mocked(turntableService.updateSettings).mockResolvedValue({
url: 'http://custom:3001',
username: 'newuser',
hasPassword: true,
isEnvConfigured: false,
})
const res = await app.request('/teams/t1/turntable-settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: 'http://custom:3001',
username: 'newuser',
password: 'secretpassword',
}),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.url).toBe('http://custom:3001')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
})
it('PUT /teams/:teamId/turntable-settings returns 400 when env configured', async () => {
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
vi.mocked(turntableService.updateSettings).mockRejectedValue(
new Error(
'Turntable settings are configured via environment variables and cannot be edited',
),
)
const res = await app.request('/teams/t1/turntable-settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: 'http://custom:3001',
}),
})
expect(res.status).toBe(400)
const data = await res.json()
expect(data.message).toContain('configured via environment variables')
})
it('POST /teams/:teamId/turntable-settings/test tests connection', async () => {
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
vi.mocked(turntableService.testConnection).mockResolvedValue({
ok: true,
version: '1.0.0',
blender: '5.2.0',
})
const res = await app.request('/teams/t1/turntable-settings/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url: 'http://custom:3001',
}),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.ok).toBe(true)
expect(data.blender).toBe('5.2.0')
})
})
})
+59
View File
@@ -10,6 +10,7 @@ import {
updateTeamSettingsRequestSchema,
listMembersQuerySchema,
updateSandboxSettingsRequestSchema,
updateTurntableSettingsRequestSchema,
updateMeRequestSchema,
updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema,
@@ -23,6 +24,7 @@ import {
import { apiTokenService } from '@shumai/core/src/user/api-token'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { NotificationType } from '@shumai/db'
import type { Prisma } from '@shumai/db'
@@ -265,6 +267,63 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(sandbox)
},
)
.get('/teams/:teamId/turntable-settings', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
const settings = await turntableService.getSettings(teamId)
return c.json(settings)
})
.put(
'/teams/:teamId/turntable-settings',
zValidator('json', updateTurntableSettingsRequestSchema),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
try {
const settings = await turntableService.updateSettings(teamId, req)
return c.json(settings)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
return c.json({ message }, 400)
}
},
)
.post(
'/teams/:teamId/turntable-settings/test',
zValidator('json', updateTurntableSettingsRequestSchema.partial()),
async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const res = await turntableService.testConnection(req, teamId)
return c.json(res)
},
)
.get('/teams/:teamId/user-metadata', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/core",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+30
View File
@@ -1931,6 +1931,36 @@ describe('AssetService', () => {
expect(info.preview?.duration).toBeUndefined()
})
it('toPreviewInfo handles 3d asset with proxyType 3d and omits duration', async () => {
const { project, user } = await setupBasicAssets()
const model = await prisma.asset.create({
data: {
name: 'model.glb',
type: AssetType.file,
projectId: project.id,
creatorId: user.id,
sizeByte: 8000,
mediaType: 'model/gltf-binary',
status: 'processed',
media: {
proxyType: '3d',
poster: { key: 'poster-key' },
sprite: { key: 'sprite-key', frames: 100, tileX: 10, tileY: 10 },
metadata: { originalWidth: 1080, originalHeight: 1080, duration: 4 },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
},
})
const info = await assetService.getAsset({ assetId: model.id })
expect(info.preview).toBeDefined()
expect(info.preview?.proxyType).toBe('3d')
expect(info.preview?.duration).toBeUndefined()
expect(info.preview?.spriteUrl).toBeDefined()
})
it('converts webp thumbnail to jpeg on demand when hasJpegPreview is false', async () => {
vi.mocked(ensureJpegInStorage).mockClear()
const { project, user } = await setupBasicAssets()
+15 -3
View File
@@ -2407,7 +2407,13 @@ export class AssetService {
}
}
const proxyType = (media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
const proxyType = (media?.proxyType || null) as
| 'image'
| 'video'
| 'audio'
| 'pdf'
| '3d'
| null
result.push({
id: a.id,
@@ -2773,7 +2779,13 @@ export class AssetService {
): Promise<PreviewInfo | null> {
if (!asset.media) return null
const proxyType = (asset.media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
const proxyType = (asset.media?.proxyType || null) as
| 'image'
| 'video'
| 'audio'
| 'pdf'
| '3d'
| null
let rawThumbKey: string | undefined
if (proxyType === 'image' && asset.media.thumbnail?.key) {
@@ -2826,7 +2838,7 @@ export class AssetService {
originalHeight: asset.media.metadata?.originalHeight,
originalWidth: asset.media.metadata?.originalWidth,
spriteUrl,
duration: asset.media.metadata?.duration,
duration: proxyType === '3d' ? undefined : asset.media.metadata?.duration,
pageCount: asset.media.metadata?.totalFrames,
}
}
+1
View File
@@ -31,3 +31,4 @@ export * from './kanban/kanban'
export * from './media-generation/media-generation'
export * from './sandbox'
export * from './asset/comments-export'
export * from './turntable/turntable'
+18
View File
@@ -375,6 +375,12 @@ describe('TeamService', () => {
hlsEnabled: false,
hlsResolutions: ['480p', '720p', '1080p'],
},
turntable: {
hasPassword: false,
isEnvConfigured: false,
url: undefined,
username: undefined,
},
appearance: { hideAgent: false },
})
@@ -392,6 +398,12 @@ describe('TeamService', () => {
hlsEnabled: false,
hlsResolutions: ['480p', '720p', '1080p'],
},
turntable: {
hasPassword: false,
isEnvConfigured: false,
url: undefined,
username: undefined,
},
appearance: { hideAgent: false },
})
@@ -418,6 +430,12 @@ describe('TeamService', () => {
hlsEnabled: true,
hlsResolutions: ['720p', '1080p', '2160p'],
},
turntable: {
hasPassword: false,
isEnvConfigured: false,
url: undefined,
username: undefined,
},
appearance: { hideAgent: true },
semanticSearchEnabled: false,
})
+3
View File
@@ -7,6 +7,7 @@ import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import { HTTPException } from 'hono/http-exception'
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import {
ServiceCreateTeamRequest,
ServiceGetUserTeamsRequest,
@@ -343,6 +344,8 @@ export class TeamService {
settings.appearance.hideAgent = false
}
settings.turntable = await turntableService.getSettings(teamId)
return settings
}
+465 -11
View File
@@ -3,8 +3,11 @@ import * as fs from 'fs'
import {
extractEmbeddedJpeg,
validateExtractedJpeg,
validateExtractedImage,
decodeRawWithDcraw,
extractAndValidateRawPreview,
EXIF_ORIENTATION_TO_ROTATION,
withTimeout,
} from './raw-extract'
// Mock exiftool-vendored
@@ -26,13 +29,20 @@ vi.mock('sharp', () => {
return { default: mockSharp }
})
// Mock child_process
vi.mock('child_process', () => ({
execFile: vi.fn(),
}))
import { exiftool } from 'exiftool-vendored'
import sharp from 'sharp'
import { execFile } from 'child_process'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mockMetadata = (sharp as any)._mockMetadata as ReturnType<typeof vi.fn>
const mockExtractBinaryTag = vi.mocked(exiftool.extractBinaryTag)
const mockRead = vi.mocked(exiftool.read)
const mockExecFile = vi.mocked(execFile)
describe('extractEmbeddedJpeg', () => {
beforeEach(() => {
@@ -162,6 +172,29 @@ describe('extractEmbeddedJpeg', () => {
expect(result!.orientation).toBeUndefined()
result!.cleanup()
})
it('skips remaining tags and aborts early when extraction times out', async () => {
const origEnv = process.env.EXIFTOOL_TIMEOUT_MS
try {
process.env.EXIFTOOL_TIMEOUT_MS = '20'
// Hang on first tag
mockExtractBinaryTag.mockImplementationOnce(
() => new Promise((resolve) => setTimeout(resolve, 300)),
)
const result = await extractEmbeddedJpeg('/path/to/photo.cr2')
expect(result).toBeNull()
// Crucial: should break immediately after the first timeout instead of trying remaining 2 tags
expect(mockExtractBinaryTag).toHaveBeenCalledTimes(1)
} finally {
if (origEnv !== undefined) {
process.env.EXIFTOOL_TIMEOUT_MS = origEnv
} else {
delete process.env.EXIFTOOL_TIMEOUT_MS
}
}
})
})
describe('validateExtractedJpeg', () => {
@@ -202,16 +235,265 @@ describe('validateExtractedJpeg', () => {
})
})
describe('validateExtractedImage', () => {
it('is an alias for validateExtractedJpeg', () => {
expect(validateExtractedImage).toBe(validateExtractedJpeg)
})
})
describe('decodeRawWithDcraw', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('decodes RAW using camera white balance, sRGB, and TIFF output without -h when longest dimension <= 8192', async () => {
mockRead.mockResolvedValueOnce({
ImageWidth: 6000,
ImageHeight: 4000,
Orientation: 1,
} as never)
let executedArgs: string[] = []
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
executedArgs = args as string[]
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(fs.existsSync(result!.previewPath)).toBe(true)
expect(result!.orientation).toBeUndefined()
expect(result!.rawWidth).toBe(6000)
expect(result!.rawHeight).toBe(4000)
expect(executedArgs).toContain('-w')
expect(executedArgs).toContain('-o')
expect(executedArgs).toContain('1')
expect(executedArgs).toContain('-T')
expect(executedArgs).toContain('-Z')
expect(executedArgs).not.toContain('-h')
expect(executedArgs[executedArgs.length - 1]).toBe('/path/to/photo.cr2')
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('enables half-size (-h) when longest dimension > 8192px and computes upright raw dimensions', async () => {
mockRead.mockResolvedValueOnce({
ImageWidth: 9504,
ImageHeight: 6336,
Orientation: 6,
} as never)
let executedArgs: string[] = []
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
executedArgs = args as string[]
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.arw')
expect(result).not.toBeNull()
expect(executedArgs).toContain('-h')
expect(result!.orientation).toBeUndefined()
// For orientation 6 (90 CW), upright raw dimensions are swapped
expect(result!.rawWidth).toBe(6336)
expect(result!.rawHeight).toBe(9504)
result!.cleanup()
})
it('omits -h when longest dimension is exactly 8192px', async () => {
mockRead.mockResolvedValueOnce({
ImageWidth: 8192,
ImageHeight: 5464,
Orientation: 1,
} as never)
let executedArgs: string[] = []
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
executedArgs = args as string[]
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.nef')
expect(result).not.toBeNull()
expect(executedArgs).not.toContain('-h')
result!.cleanup()
})
it('defaults to full size without -h when EXIF metadata cannot be read', async () => {
mockRead.mockRejectedValueOnce(new Error('Exif read failure'))
let executedArgs: string[] = []
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
executedArgs = args as string[]
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.dng')
expect(result).not.toBeNull()
expect(executedArgs).not.toContain('-h')
result!.cleanup()
})
it('defaults to full size without -h when EXIF metadata read times out', async () => {
const origEnv = process.env.EXIFTOOL_TIMEOUT_MS
try {
process.env.EXIFTOOL_TIMEOUT_MS = '20'
mockRead.mockImplementationOnce(() => new Promise((resolve) => setTimeout(resolve, 300)))
let executedArgs: string[] = []
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
executedArgs = args as string[]
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.dng')
expect(result).not.toBeNull()
expect(executedArgs).not.toContain('-h')
result!.cleanup()
} finally {
if (origEnv !== undefined) {
process.env.EXIFTOOL_TIMEOUT_MS = origEnv
} else {
delete process.env.EXIFTOOL_TIMEOUT_MS
}
}
})
it('returns null and cleans up when dcraw_emu exits with non-zero code', async () => {
mockRead.mockResolvedValueOnce({ ImageWidth: 6000, ImageHeight: 4000 } as never)
mockExecFile.mockImplementationOnce((_bin, _args, _opts, cb) => {
const callback = typeof _opts === 'function' ? _opts : cb
const err = new Error('Command failed: dcraw_emu')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(err as any).code = 1
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(err)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.cr2')
expect(result).toBeNull()
})
it('returns null and cleans up when dcraw_emu times out', async () => {
mockRead.mockResolvedValueOnce({ ImageWidth: 6000, ImageHeight: 4000 } as never)
mockExecFile.mockImplementationOnce((_bin, _args, _opts, cb) => {
const callback = typeof _opts === 'function' ? _opts : cb
const err = new Error('Process timed out')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(err as any).code = 'ETIMEDOUT'
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(err)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.cr2')
expect(result).toBeNull()
})
it('returns null and cleans up when dcraw_emu is not found (ENOENT)', async () => {
mockRead.mockResolvedValueOnce({ ImageWidth: 6000, ImageHeight: 4000 } as never)
mockExecFile.mockImplementationOnce((_bin, _args, _opts, cb) => {
const callback = typeof _opts === 'function' ? _opts : cb
const err = new Error('spawn dcraw_emu ENOENT')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(err as any).code = 'ENOENT'
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(err)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.cr2')
expect(result).toBeNull()
})
it('returns null and cleans up when output TIFF is missing or empty', async () => {
mockRead.mockResolvedValueOnce({ ImageWidth: 6000, ImageHeight: 4000 } as never)
mockExecFile.mockImplementationOnce((_bin, _args, _opts, cb) => {
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await decodeRawWithDcraw('/path/to/photo.cr2')
expect(result).toBeNull()
})
})
describe('extractAndValidateRawPreview', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns previewPath, dimensions, orientation, and cleanup for valid RAW', async () => {
it('returns previewPath, dimensions, orientation, and cleanup for valid RAW using embedded JPEG first', async () => {
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
fs.writeFileSync(dest, 'jpeg-data')
})
mockRead.mockResolvedValueOnce({ Orientation: 6 } as never)
mockRead.mockResolvedValueOnce({ Orientation: 6, ImageWidth: 4000, ImageHeight: 3000 } as never)
mockMetadata.mockResolvedValueOnce({ width: 4000, height: 3000 })
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
@@ -221,35 +503,207 @@ describe('extractAndValidateRawPreview', () => {
expect(result!.width).toBe(4000)
expect(result!.height).toBe(3000)
expect(result!.orientation).toBe(6)
expect(mockExecFile).not.toHaveBeenCalled()
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('returns null when extraction fails', async () => {
it('falls back to dcraw_emu when embedded preview extraction fails', async () => {
mockExtractBinaryTag
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
mockRead.mockResolvedValueOnce({
ImageWidth: 6000,
ImageHeight: 4000,
Orientation: 1,
} as never)
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
mockMetadata.mockResolvedValueOnce({ width: 6000, height: 4000 })
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(mockExecFile).toHaveBeenCalled()
expect(result!.width).toBe(6000)
expect(result!.height).toBe(4000)
expect(result!.rawWidth).toBe(6000)
expect(result!.rawHeight).toBe(4000)
expect(result!.orientation).toBeUndefined()
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('falls back to dcraw_emu when extracted embedded JPEG is corrupt', async () => {
let createdJpegPath = ''
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
createdJpegPath = dest
fs.writeFileSync(dest, 'corrupt-jpeg')
})
mockRead.mockResolvedValueOnce({ Orientation: 1 } as never)
mockMetadata.mockRejectedValueOnce(new Error('Not a valid image'))
// Fallback dcraw_emu
mockRead.mockResolvedValueOnce({ ImageWidth: 6000, ImageHeight: 4000 } as never)
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
mockMetadata.mockResolvedValueOnce({ width: 6000, height: 4000 })
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(fs.existsSync(createdJpegPath)).toBe(false) // Embedded jpeg was cleaned up
expect(fs.existsSync(result!.previewPath)).toBe(true)
result!.cleanup()
expect(fs.existsSync(result!.previewPath)).toBe(false)
})
it('returns null when both embedded extraction and dcraw_emu fail', async () => {
mockExtractBinaryTag
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
mockRead.mockRejectedValueOnce(new Error('fail'))
mockExecFile.mockImplementationOnce((_bin, _args, _opts, cb) => {
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(new Error('dcraw failed'))
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).toBeNull()
})
it('returns null and cleans up when validation fails', async () => {
let createdPath = ''
mockExtractBinaryTag.mockImplementationOnce(async (_tag, _src, dest) => {
createdPath = dest
fs.writeFileSync(dest, 'bad-jpeg')
it('returns null and cleans up when decoded TIFF is corrupt', async () => {
mockExtractBinaryTag
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
let createdTiff = ''
mockRead.mockResolvedValueOnce({ ImageWidth: 6000, ImageHeight: 4000 } as never)
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
createdTiff = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(createdTiff, 'corrupt-tiff')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
mockRead.mockResolvedValueOnce({ Orientation: 1 } as never)
mockMetadata.mockRejectedValueOnce(new Error('Not a valid image'))
mockMetadata.mockRejectedValueOnce(new Error('Invalid TIFF'))
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).toBeNull()
expect(fs.existsSync(createdPath)).toBe(false)
expect(fs.existsSync(createdTiff)).toBe(false)
})
it('falls back to dcraw_emu when embedded preview extraction times out', async () => {
const origEnv = process.env.EXIFTOOL_TIMEOUT_MS
try {
process.env.EXIFTOOL_TIMEOUT_MS = '20'
// Hang on extractBinaryTag
mockExtractBinaryTag.mockImplementationOnce(
() => new Promise((resolve) => setTimeout(resolve, 300)),
)
mockRead.mockResolvedValueOnce({
ImageWidth: 6000,
ImageHeight: 4000,
Orientation: 1,
} as never)
mockExecFile.mockImplementationOnce((_bin, args, _opts, cb) => {
const tiffDest = (args as string[])[(args as string[]).indexOf('-Z') + 1]
fs.writeFileSync(tiffDest, 'tiff-data')
const callback = typeof _opts === 'function' ? _opts : cb
if (callback) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(callback as any)(null, { stdout: '', stderr: '' })
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return {} as any
})
mockMetadata.mockResolvedValueOnce({ width: 6000, height: 4000 })
const result = await extractAndValidateRawPreview('/path/to/photo.cr2')
expect(result).not.toBeNull()
expect(mockExecFile).toHaveBeenCalled()
expect(result!.width).toBe(6000)
expect(result!.height).toBe(4000)
result!.cleanup()
} finally {
if (origEnv !== undefined) {
process.env.EXIFTOOL_TIMEOUT_MS = origEnv
} else {
delete process.env.EXIFTOOL_TIMEOUT_MS
}
}
})
})
describe('withTimeout', () => {
it('resolves when promise settles before timeout', async () => {
const result = await withTimeout(Promise.resolve('ok'), 1000)
expect(result).toBe('ok')
})
it('rejects with timeout error when promise exceeds timeout', async () => {
const hanging = new Promise((resolve) => setTimeout(resolve, 500))
await expect(withTimeout(hanging, 20, 'TestTask')).rejects.toThrow(
'TestTask timed out after 20ms',
)
})
it('propagates underlying promise rejection before timeout', async () => {
const failing = Promise.reject(new Error('fail fast'))
await expect(withTimeout(failing, 1000, 'TestTask')).rejects.toThrow('fail fast')
})
it('prevents unhandled rejection if promise rejects after timeout', async () => {
const delayedReject = new Promise((_, reject) =>
setTimeout(() => reject(new Error('late error')), 40),
)
await expect(withTimeout(delayedReject, 10, 'TestTask')).rejects.toThrow(
'TestTask timed out after 10ms',
)
await new Promise((resolve) => setTimeout(resolve, 60))
})
})
+265 -29
View File
@@ -1,15 +1,37 @@
import { execFile } from 'child_process'
import { exiftool } from 'exiftool-vendored'
import sharp from 'sharp'
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import sharp from 'sharp'
import { promisify } from 'util'
import { logger } from '@shumai/core/src/logger'
const execFileAsync = promisify(execFile)
export interface RawExtractResult {
previewPath: string
cleanup: () => void
/** EXIF orientation from the RAW container (1–8), or undefined if absent. */
/** EXIF orientation from the RAW container (1–8), or undefined if absent or already applied. */
orientation?: number
/** Original unoriented or oriented image dimensions from EXIF if available */
rawWidth?: number
rawHeight?: number
}
export interface RawPreviewResult {
previewPath: string
cleanup: () => void
width: number
height: number
orientation?: number
rawWidth?: number
rawHeight?: number
}
export interface DecodeRawOptions {
timeoutMs?: number
signal?: AbortSignal
}
/**
@@ -30,6 +52,41 @@ export const EXIF_ORIENTATION_TO_ROTATION: Record<
8: { angle: 270 }, // Rotate 270° CW
}
const DEFAULT_EXIFTOOL_TIMEOUT_MS = 15_000
function getExifToolTimeoutMs(): number {
const envVal = process.env.EXIFTOOL_TIMEOUT_MS
if (envVal) {
const parsed = parseInt(envVal, 10)
if (!isNaN(parsed) && parsed > 0) {
return parsed
}
}
return DEFAULT_EXIFTOOL_TIMEOUT_MS
}
/**
* Wraps a promise with a timeout. If the timeout triggers first,
* the returned promise rejects with a timeout error and attaches a no-op handler
* to the underlying promise to prevent unhandled rejections.
*/
export function withTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
operationName = 'Operation',
): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined
const timeoutPromise = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
reject(new Error(`${operationName} timed out after ${timeoutMs}ms`))
}, timeoutMs)
})
promise.catch(() => {})
return Promise.race([promise, timeoutPromise]).finally(() => {
if (timer) clearTimeout(timer)
})
}
/**
* Attempt to extract an embedded JPEG preview from a camera RAW file to a temporary file.
*
@@ -61,32 +118,58 @@ export async function extractEmbeddedJpeg(
}
}
const exiftoolTimeoutMs = getExifToolTimeoutMs()
for (const tag of tags) {
const candidatePath = path.join(workDir, `preview-${tag}-${Date.now()}.jpg`)
try {
await exiftool.extractBinaryTag(tag, rawFilePath, candidatePath)
await withTimeout(
exiftool.extractBinaryTag(tag, rawFilePath, candidatePath),
exiftoolTimeoutMs,
`exiftool.extractBinaryTag(${tag})`,
)
if (fs.existsSync(candidatePath) && fs.statSync(candidatePath).size > 0) {
logger.debug({ tag, rawFilePath, candidatePath }, 'Extracted embedded JPEG from RAW')
// Read orientation from the RAW container's EXIF metadata.
// The extracted JPEG binary stream often does NOT carry its own
// orientation tag, so we must read it from the parent RAW file
// to avoid incorrectly-rotated previews.
// Read orientation and container dimensions from the RAW container's EXIF metadata.
let orientation: number | undefined
let rawWidth: number | undefined
let rawHeight: number | undefined
try {
const exif = await exiftool.read(rawFilePath)
const exif = await withTimeout(
exiftool.read(rawFilePath),
exiftoolTimeoutMs,
'exiftool.read',
)
const rawOrientation = exif.Orientation
if (typeof rawOrientation === 'number' && rawOrientation >= 1 && rawOrientation <= 8) {
orientation = rawOrientation
}
const w =
typeof exif.ImageWidth === 'number'
? exif.ImageWidth
: typeof exif.ExifImageWidth === 'number'
? exif.ExifImageWidth
: undefined
const h =
typeof exif.ImageHeight === 'number'
? exif.ImageHeight
: typeof exif.ExifImageHeight === 'number'
? exif.ExifImageHeight
: undefined
if (w && h && w > 0 && h > 0) {
rawWidth = w
rawHeight = h
}
} catch {
logger.debug({ rawFilePath }, 'Could not read EXIF orientation from RAW container')
}
return { previewPath: candidatePath, cleanup, orientation }
return { previewPath: candidatePath, cleanup, orientation, rawWidth, rawHeight }
}
} catch {
logger.debug({ tag, rawFilePath }, `Could not extract ${tag} from RAW file`)
} catch (err) {
const isTimeout = err instanceof Error && err.message.includes('timed out')
logger.debug({ tag, rawFilePath, err, isTimeout }, `Could not extract ${tag} from RAW file`)
try {
if (fs.existsSync(candidatePath)) {
fs.rmSync(candidatePath, { force: true })
@@ -94,6 +177,13 @@ export async function extractEmbeddedJpeg(
} catch {
// ignore
}
if (isTimeout) {
logger.warn(
{ rawFilePath, tag, timeoutMs: exiftoolTimeoutMs },
'ExifTool extraction timed out; skipping remaining tags to avoid further delays',
)
break
}
}
}
@@ -103,10 +193,124 @@ export async function extractEmbeddedJpeg(
}
/**
* Validate that an extracted JPEG file is decodable.
* Fallback RAW decoder using dcraw_emu (from LibRaw).
*
* Used when no usable embedded JPEG preview exists in the RAW file.
*
* Decoding options:
* - Camera white balance and sRGB output (-w -o 1)
* - Output temporary TIFF (-T -Z <tempPath>)
* - Half-size processing (-h) enabled only when longest dimension > 8192px
*
* LibRaw auto-rotates the output image to upright orientation based on camera EXIF,
* so the returned orientation is undefined to avoid double-rotation in downstream Sharp.
*/
export async function decodeRawWithDcraw(
rawFilePath: string,
targetDir?: string,
options?: DecodeRawOptions,
): Promise<RawExtractResult | null> {
const ownTempDir = !targetDir
const workDir = targetDir ?? fs.mkdtempSync(path.join(os.tmpdir(), 'raw-decode-'))
const tempTiffPath = path.join(
workDir,
`decoded-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.tiff`,
)
const cleanup = () => {
try {
if (ownTempDir && fs.existsSync(workDir)) {
fs.rmSync(workDir, { recursive: true, force: true })
} else if (fs.existsSync(tempTiffPath)) {
fs.rmSync(tempTiffPath, { force: true })
}
} catch (err) {
logger.warn({ workDir, tempTiffPath, err }, 'Failed to clean up dcraw temporary files')
}
}
// 1. Probe RAW dimensions and orientation via ExifTool to check for 8192px threshold
let useHalfSize = false
let rawWidth: number | undefined
let rawHeight: number | undefined
try {
const exiftoolTimeoutMs = getExifToolTimeoutMs()
const exif = await withTimeout(exiftool.read(rawFilePath), exiftoolTimeoutMs, 'exiftool.read')
const w =
typeof exif.ImageWidth === 'number'
? exif.ImageWidth
: typeof exif.ExifImageWidth === 'number'
? exif.ExifImageWidth
: undefined
const h =
typeof exif.ImageHeight === 'number'
? exif.ImageHeight
: typeof exif.ExifImageHeight === 'number'
? exif.ExifImageHeight
: undefined
if (w && h && w > 0 && h > 0) {
const longest = Math.max(w, h)
if (longest > 8192) {
useHalfSize = true
}
// Compute upright raw dimensions matching dcraw_emu's auto-rotation
const rawOrientation = exif.Orientation
const isSwapped =
typeof rawOrientation === 'number' && rawOrientation >= 5 && rawOrientation <= 8
rawWidth = isSwapped ? h : w
rawHeight = isSwapped ? w : h
}
} catch (err) {
logger.debug({ rawFilePath, err }, 'Could not read EXIF metadata for RAW dimension check')
}
// 2. Build dcraw_emu arguments
const args = ['-w', '-o', '1']
if (useHalfSize) {
args.push('-h')
}
args.push('-T', '-Z', tempTiffPath, rawFilePath)
const dcrawBin = process.env.DCRAW_EMU_PATH || 'dcraw_emu'
const envTimeout = process.env.DCRAW_EMU_TIMEOUT_MS
? parseInt(process.env.DCRAW_EMU_TIMEOUT_MS, 10)
: undefined
const timeoutMs = options?.timeoutMs ?? (envTimeout && !isNaN(envTimeout) ? envTimeout : 60_000)
try {
logger.debug({ dcrawBin, args, rawFilePath }, 'Executing dcraw_emu fallback')
await execFileAsync(dcrawBin, args, {
timeout: timeoutMs,
signal: options?.signal,
})
if (!fs.existsSync(tempTiffPath) || fs.statSync(tempTiffPath).size === 0) {
logger.warn({ rawFilePath, tempTiffPath }, 'dcraw_emu did not produce a valid output TIFF')
cleanup()
return null
}
return {
previewPath: tempTiffPath,
cleanup,
orientation: undefined, // dcraw_emu already auto-rotates upright based on camera EXIF
rawWidth,
rawHeight,
}
} catch (err) {
logger.warn({ rawFilePath, err }, 'dcraw_emu failed to decode RAW file')
cleanup()
return null
}
}
/**
* Validate that an extracted or decoded image file (JPEG, TIFF, etc.) is decodable.
* Returns dimensions if valid, null if corrupt/unusable.
*/
export async function validateExtractedJpeg(
export async function validateExtractedImage(
filePath: string,
): Promise<{ width: number; height: number } | null> {
try {
@@ -120,34 +324,66 @@ export async function validateExtractedJpeg(
}
}
/** Backward compatibility alias */
export const validateExtractedJpeg = validateExtractedImage
/**
* Extract and validate an embedded JPEG from a RAW file to a temporary file.
* Extract and validate a preview from a RAW file to a temporary file.
*
* 1. Attempts ExifTool embedded JPEG extraction first.
* 2. If no embedded preview is available or extraction fails, falls back to dcraw_emu decoding.
*
* Returns a validated file path + dimensions + orientation + cleanup function, or null.
*/
export async function extractAndValidateRawPreview(
rawFilePath: string,
targetDir?: string,
): Promise<{
previewPath: string
cleanup: () => void
width: number
height: number
orientation?: number
} | null> {
): Promise<RawPreviewResult | null> {
// 1. Try ExifTool embedded JPEG extraction first
const extracted = await extractEmbeddedJpeg(rawFilePath, targetDir)
if (!extracted) return null
const dims = await validateExtractedJpeg(extracted.previewPath)
if (!dims) {
logger.warn({ rawFilePath }, 'Extracted JPEG from RAW is not decodable, skipping preview')
if (extracted) {
const dims = await validateExtractedImage(extracted.previewPath)
if (dims) {
return {
previewPath: extracted.previewPath,
cleanup: extracted.cleanup,
orientation: extracted.orientation,
rawWidth: extracted.rawWidth,
rawHeight: extracted.rawHeight,
...dims,
}
}
logger.warn(
{ rawFilePath },
'Extracted JPEG from RAW is not decodable, falling back to dcraw_emu',
)
extracted.cleanup()
} else {
logger.info(
{ rawFilePath },
'No usable embedded JPEG found in RAW file, falling back to dcraw_emu',
)
}
// 2. Fallback to dcraw_emu
const decoded = await decodeRawWithDcraw(rawFilePath, targetDir)
if (!decoded) {
return null
}
const dims = await validateExtractedImage(decoded.previewPath)
if (!dims) {
logger.warn({ rawFilePath }, 'Decoded TIFF from dcraw_emu is not decodable, skipping preview')
decoded.cleanup()
return null
}
return {
previewPath: extracted.previewPath,
cleanup: extracted.cleanup,
orientation: extracted.orientation,
previewPath: decoded.previewPath,
cleanup: decoded.cleanup,
orientation: decoded.orientation,
rawWidth: decoded.rawWidth,
rawHeight: decoded.rawHeight,
...dims,
}
}
+793 -1
View File
@@ -7,7 +7,11 @@ import {
getDefaultBitrateBps,
calculateMaxBitrate,
H264_ENCODER_CONFIGS,
isHwDecodeEnabled,
getHwDecodeStallTimeoutMs,
HW_DECODE_CONFIGS,
buildSdrToneMapFilterChain,
getDriDevice,
getVaapiDevice,
parseBitrateKbps,
buildHlsMasterPlaylist,
@@ -506,6 +510,26 @@ describe('TranscodeService', () => {
expect(info.mimeType).toBe('')
})
it('should prioritize rawWidth and rawHeight in getImageInfo when available', async () => {
const rawPath = path.join(tempDir, 'highres.arw')
const cleanupSpy = vi.fn()
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce({
previewPath: '/tmp/decoded-half.tiff',
cleanup: cleanupSpy,
width: 4752,
height: 3168,
rawWidth: 9504,
rawHeight: 6336,
orientation: undefined,
})
const info = await transcodeService.getImageInfo(rawPath)
expect(info.originalWidth).toBe(9504)
expect(info.originalHeight).toBe(6336)
expect(info.mimeType).toBe('jpeg')
expect(cleanupSpy).toHaveBeenCalled()
})
it('should transcode RAW image by extracting preview to temp file and feeding to sharp', async () => {
const rawPath = path.join(tempDir, 'sample.nef')
const outputFile = path.join(tempDir, 'output-raw.webp')
@@ -528,6 +552,31 @@ describe('TranscodeService', () => {
expect(cleanupSpy).toHaveBeenCalled()
})
it('should transcode RAW image from dcraw_emu fallback TIFF without double-rotating', async () => {
const rawPath = path.join(tempDir, 'fallback.dng')
const outputFile = path.join(tempDir, 'output-fallback.webp')
const cleanupSpy = vi.fn()
vi.spyOn(rawExtract, 'extractAndValidateRawPreview').mockResolvedValueOnce({
previewPath: '/tmp/decoded-dcraw.tiff',
cleanup: cleanupSpy,
width: 3168,
height: 4752,
rawWidth: 6336,
rawHeight: 9504,
orientation: undefined,
})
await transcodeService.transcodeImage(rawPath, outputFile, 1920, 85)
expect(sharp).toHaveBeenCalledWith('/tmp/decoded-dcraw.tiff', { limitInputPixels: false })
const mockSharp = vi.mocked(sharp).mock.results[vi.mocked(sharp).mock.results.length - 1].value
expect(mockSharp.rotate).not.toHaveBeenCalled()
expect(mockSharp.toColorspace).toHaveBeenCalledWith('srgb')
expect(mockSharp.webp).toHaveBeenCalledWith({ quality: 85 })
expect(mockSharp.toFile).toHaveBeenCalledWith(outputFile)
expect(cleanupSpy).toHaveBeenCalled()
})
it('should apply orientation rotation when transcoding RAW image', async () => {
const rawPath = path.join(tempDir, 'rotated.cr3')
const outputFile = path.join(tempDir, 'output-rotated.webp')
@@ -1325,12 +1374,20 @@ describe('TranscodeService', () => {
})
describe('Hardware Acceleration & Encoder Resolution', () => {
let origHwDecode: string | undefined
beforeEach(() => {
transcodeService.clearEncodersCache()
// These tests cover the software-decode VAAPI path; the GPU decode path
// (on by default) is covered in 'Hardware decode' below.
origHwDecode = process.env.SHUMAI_HW_DECODE
process.env.SHUMAI_HW_DECODE = 'false'
})
afterEach(() => {
vi.restoreAllMocks()
if (origHwDecode === undefined) delete process.env.SHUMAI_HW_DECODE
else process.env.SHUMAI_HW_DECODE = origHwDecode
})
it('should return platform candidates correctly', () => {
@@ -1345,21 +1402,31 @@ describe('TranscodeService', () => {
'h264_nvenc',
'h264_vaapi',
'h264_qsv',
'h264_rkmpp',
'h264_amf',
])
})
it('getVaapiDevice should return device from SHUMAI_VAAPI_DEVICE or VAAPI_DEVICE env var', () => {
it('getDriDevice should return device from SHUMAI_HW_DEVICE, SHUMAI_VAAPI_DEVICE, or VAAPI_DEVICE env var', () => {
const origHw = process.env.SHUMAI_HW_DEVICE
const origShumai = process.env.SHUMAI_VAAPI_DEVICE
const origVaapi = process.env.VAAPI_DEVICE
try {
process.env.SHUMAI_HW_DEVICE = '/dev/dri/custom0'
expect(getDriDevice()).toBe('/dev/dri/custom0')
delete process.env.SHUMAI_HW_DEVICE
process.env.SHUMAI_VAAPI_DEVICE = '/dev/dri/custom1'
expect(getDriDevice()).toBe('/dev/dri/custom1')
expect(getVaapiDevice()).toBe('/dev/dri/custom1')
delete process.env.SHUMAI_VAAPI_DEVICE
process.env.VAAPI_DEVICE = '/dev/dri/custom2'
expect(getDriDevice()).toBe('/dev/dri/custom2')
expect(getVaapiDevice()).toBe('/dev/dri/custom2')
} finally {
if (origHw) process.env.SHUMAI_HW_DEVICE = origHw
else delete process.env.SHUMAI_HW_DEVICE
if (origShumai) process.env.SHUMAI_VAAPI_DEVICE = origShumai
else delete process.env.SHUMAI_VAAPI_DEVICE
if (origVaapi) process.env.VAAPI_DEVICE = origVaapi
@@ -2531,6 +2598,731 @@ describe('TranscodeService', () => {
})
})
describe('Hardware decode', () => {
let origHwDecode: string | undefined
let origStall: string | undefined
type FfmpegCallback = (err: Error | null, result: { stdout: string; stderr: string }) => void
// execFile is called as (cmd, args, cb) or (cmd, args, options, cb); the
// GPU-decode attempt always passes options (signal + SIGKILL watchdog).
const callbackOf = (optionsOrCallback: unknown, maybeCallback?: unknown) =>
(typeof optionsOrCallback === 'function'
? optionsOrCallback
: maybeCallback) as FfmpegCallback
const mockFfmpeg = (onCall: (n: number, cb: FfmpegCallback, options: unknown) => void) =>
vi
.mocked(execFile)
.mockImplementation(
(
_cmd: unknown,
_args: unknown,
optionsOrCallback: unknown,
maybeCallback?: unknown,
): ReturnType<typeof child_process.execFile> => {
const n = vi.mocked(execFile).mock.calls.length
onCall(n, callbackOf(optionsOrCallback, maybeCallback), optionsOrCallback)
return {} as ReturnType<typeof child_process.execFile>
},
)
const failOn =
(...failing: number[]) =>
(n: number, cb: FfmpegCallback) =>
failing.includes(n)
? cb(new Error(`ffmpeg failed on call ${n}`), { stdout: '', stderr: '' })
: cb(null, { stdout: '', stderr: '' })
const calls = () => vi.mocked(child_process.execFile).mock.calls.map((c) => c[1] as string[])
const filterOf = (args: string[]) => args[args.indexOf('-filter_complex') + 1]
const vaapiScale = (w: number, h: number) => HW_DECODE_CONFIGS.h264_vaapi!.scaleFilter(w, h)
const nvencScale = (w: number, h: number) => HW_DECODE_CONFIGS.h264_nvenc!.scaleFilter(w, h)
const qsvScale = (w: number, h: number) => HW_DECODE_CONFIGS.h264_qsv!.scaleFilter(w, h)
const rkmppScale = (w: number, h: number) => HW_DECODE_CONFIGS.h264_rkmpp!.scaleFilter(w, h)
beforeEach(() => {
transcodeService.clearEncodersCache()
origHwDecode = process.env.SHUMAI_HW_DECODE
origStall = process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT
delete process.env.SHUMAI_HW_DECODE
delete process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT
vi.spyOn(transcodeService, 'selectH264Encoder').mockResolvedValue(
H264_ENCODER_CONFIGS.h264_vaapi,
)
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue('/dev/dri/renderD128')
vi.spyOn(transcodeService, 'getDriDevice').mockReturnValue('/dev/dri/renderD128')
vi.spyOn(transcodeService, 'getVideoRotation').mockResolvedValue(0)
})
afterEach(() => {
vi.restoreAllMocks()
if (origHwDecode === undefined) delete process.env.SHUMAI_HW_DECODE
else process.env.SHUMAI_HW_DECODE = origHwDecode
if (origStall === undefined) delete process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT
else process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = origStall
})
it('isHwDecodeEnabled should default to true and honor false/0/off', () => {
expect(isHwDecodeEnabled()).toBe(true)
for (const value of ['false', '0', 'off', ' FALSE ']) {
process.env.SHUMAI_HW_DECODE = value
expect(isHwDecodeEnabled()).toBe(false)
}
process.env.SHUMAI_HW_DECODE = 'true'
expect(isHwDecodeEnabled()).toBe(true)
})
it('getHwDecodeStallTimeoutMs should default to 120s and honor SHUMAI_HW_DECODE_STALL_TIMEOUT', () => {
expect(getHwDecodeStallTimeoutMs()).toBe(120_000)
process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = '30'
expect(getHwDecodeStallTimeoutMs()).toBe(30_000)
process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = 'nope'
expect(getHwDecodeStallTimeoutMs()).toBe(120_000)
})
it('should have hardware decode configs for nvenc, qsv, vaapi, and rkmpp', () => {
expect(Object.keys(HW_DECODE_CONFIGS)).toEqual([
'h264_nvenc',
'h264_qsv',
'h264_vaapi',
'h264_rkmpp',
])
expect(nvencScale(1920, 1080)).toBe(
'scale_cuda=w=1920:h=1080:force_original_aspect_ratio=decrease:force_divisible_by=2:format=nv12',
)
expect(qsvScale(1920, 1080)).toBe('scale_qsv=w=1920:h=1080:async_depth=4:mode=hq:format=nv12')
expect(vaapiScale(1920, 1080)).toBe(
'scale_vaapi=w=1920:h=1080:force_original_aspect_ratio=decrease:force_divisible_by=2:format=nv12:mode=hq',
)
expect(rkmppScale(1920, 1080)).toBe(
'scale_rkrga=w=1920:h=1080:format=nv12:afbc=1:async_depth=4',
)
expect(HW_DECODE_CONFIGS.h264_qsv!.getInputArgs!('/dev/dri/renderD128')).toEqual([
'-hwaccel',
'qsv',
'-hwaccel_output_format',
'qsv',
'-async_depth',
'4',
'-threads',
'1',
'-qsv_device',
'/dev/dri/renderD128',
])
expect(HW_DECODE_CONFIGS.h264_qsv!.getInputArgs!()).toEqual([
'-hwaccel',
'qsv',
'-hwaccel_output_format',
'qsv',
'-async_depth',
'4',
'-threads',
'1',
])
})
it('transcodeVideo should decode and scale on the GPU by default with vaapi', async () => {
mockFfmpeg(failOn())
const loggerSpy = vi.spyOn(logger, 'info')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec.mp4'),
width: 1280,
height: 720,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceVideoBitrate: 600_000,
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
const args = calls()[0]
expect(args).toEqual(
expect.arrayContaining([
'-init_hw_device',
'vaapi=accel:/dev/dri/renderD128',
'-hwaccel',
'vaapi',
'-hwaccel_device',
'accel',
'-hwaccel_output_format',
'vaapi',
'-noautoscale',
'-c:v',
'h264_vaapi',
'-rc_mode',
'3',
]),
)
// hwaccel options must precede the input; -noautoscale is an output option
expect(args.indexOf('-hwaccel')).toBeLessThan(args.indexOf('-i'))
expect(args.indexOf('-noautoscale')).toBeGreaterThan(args.indexOf('-filter_complex'))
expect(filterOf(args)).toBe(`[0:V]${vaapiScale(1280, 720)},fps=24[vout]`)
expect(filterOf(args)).not.toContain('hwupload')
expect(args).not.toContain('-pix_fmt')
// the GPU attempt runs under the stall watchdog
expect(vi.mocked(child_process.execFile).mock.calls[0][2]).toEqual(
expect.objectContaining({ killSignal: 'SIGKILL', signal: expect.any(AbortSignal) }),
)
expect(loggerSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_vaapi', hwDecode: true }),
'Starting video transcoding',
)
})
it('transcodeVideo should decode and scale on the GPU by default with nvenc', async () => {
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(
H264_ENCODER_CONFIGS.h264_nvenc,
)
mockFfmpeg(failOn())
const loggerSpy = vi.spyOn(logger, 'info')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_nvenc.mp4'),
width: 1280,
height: 720,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceVideoBitrate: 600_000,
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
const args = calls()[0]
expect(args).toEqual(
expect.arrayContaining([
'-hwaccel',
'cuda',
'-hwaccel_output_format',
'cuda',
'-threads',
'1',
'-noautoscale',
'-c:v',
'h264_nvenc',
]),
)
expect(args.indexOf('-hwaccel')).toBeLessThan(args.indexOf('-i'))
expect(args.indexOf('-noautoscale')).toBeGreaterThan(args.indexOf('-filter_complex'))
expect(filterOf(args)).toBe(`[0:V]${nvencScale(1280, 720)},fps=24[vout]`)
expect(filterOf(args)).not.toContain('hwupload')
expect(args).not.toContain('-pix_fmt')
expect(loggerSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_nvenc', hwDecode: true }),
'Starting video transcoding',
)
})
it('transcodeVideo should decode and scale on the GPU by default with qsv', async () => {
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(H264_ENCODER_CONFIGS.h264_qsv)
mockFfmpeg(failOn())
const loggerSpy = vi.spyOn(logger, 'info')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_qsv.mp4'),
width: 1280,
height: 720,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceVideoBitrate: 600_000,
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
const args = calls()[0]
expect(args).toEqual(
expect.arrayContaining([
'-hwaccel',
'qsv',
'-hwaccel_output_format',
'qsv',
'-async_depth',
'4',
'-threads',
'1',
'-noautoscale',
'-c:v',
'h264_qsv',
]),
)
expect(args).toContain('-qsv_device')
expect(args).toContain('/dev/dri/renderD128')
expect(args.indexOf('-hwaccel')).toBeLessThan(args.indexOf('-i'))
expect(args.indexOf('-noautoscale')).toBeGreaterThan(args.indexOf('-filter_complex'))
expect(filterOf(args)).toBe(`[0:V]${qsvScale(1280, 720)},fps=24[vout]`)
expect(filterOf(args)).not.toContain('hwupload')
expect(args).not.toContain('-pix_fmt')
expect(loggerSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_qsv', hwDecode: true }),
'Starting video transcoding',
)
})
it('transcodeVideo should decode and scale on the GPU by default with rkmpp', async () => {
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(
H264_ENCODER_CONFIGS.h264_rkmpp,
)
mockFfmpeg(failOn())
const loggerSpy = vi.spyOn(logger, 'info')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_rkmpp.mp4'),
width: 1280,
height: 720,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceVideoBitrate: 600_000,
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
const args = calls()[0]
expect(args).toEqual(
expect.arrayContaining([
'-hwaccel',
'rkmpp',
'-hwaccel_output_format',
'drm_prime',
'-afbc',
'rga',
'-noautoscale',
'-c:v',
'h264_rkmpp',
]),
)
expect(args.indexOf('-hwaccel')).toBeLessThan(args.indexOf('-i'))
expect(args.indexOf('-noautoscale')).toBeGreaterThan(args.indexOf('-filter_complex'))
expect(filterOf(args)).toBe(`[0:V]${rkmppScale(1280, 720)},fps=24[vout]`)
expect(filterOf(args)).not.toContain('hwupload')
expect(args).not.toContain('-pix_fmt')
expect(loggerSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_rkmpp', hwDecode: true }),
'Starting video transcoding',
)
})
it('transcodeVideo should fall back to software decode when qsv has no DRI device on Linux', async () => {
const origPlatform = process.platform
try {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true })
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(
H264_ENCODER_CONFIGS.h264_qsv,
)
vi.spyOn(transcodeService, 'getDriDevice').mockReturnValue(null)
vi.spyOn(transcodeService, 'getVaapiDevice').mockReturnValue(null)
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_qsv_no_dri.mp4'),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(1)
expect(calls()[0]).not.toContain('-hwaccel')
expect(calls()[0]).toContain('h264_qsv')
} finally {
Object.defineProperty(process, 'platform', { value: origPlatform, configurable: true })
}
})
it('transcodeVideo should use the provided sourceRotation instead of probing', async () => {
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'portrait.mov',
outputFile: path.join(tempDir, 'out_hwdec_rotation_param.mp4'),
width: 1080,
height: 1920,
hardwareAcceleration: 'auto',
sourceRotation: -90,
})
expect(transcodeService.getVideoRotation).not.toHaveBeenCalled()
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should probe rotation when sourceRotation is not provided', async () => {
vi.mocked(transcodeService.getVideoRotation).mockResolvedValue(90)
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'portrait.mov',
outputFile: path.join(tempDir, 'out_hwdec_rotated.mp4'),
width: 1080,
height: 1920,
hardwareAcceleration: 'auto',
})
expect(transcodeService.getVideoRotation).toHaveBeenCalledWith('portrait.mov', undefined)
expect(calls()).toHaveLength(1)
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should retry with software decode + hardware encode when GPU decode fails', async () => {
const outputFile = path.join(tempDir, 'out_hwdec_retry.mp4')
mockFfmpeg(failOn(1))
const warnSpy = vi.spyOn(logger, 'warn')
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(2)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[1]).not.toContain('-hwaccel')
expect(calls()[1]).not.toContain('-noautoscale')
expect(calls()[1]).toContain('h264_vaapi')
expect(filterOf(calls()[1])).toContain('format=nv12,hwupload=extra_hw_frames=64')
expect(warnSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_vaapi', outputFile }),
'Hardware decode failed; retrying with software decode and hardware encode',
)
})
it('transcodeVideo should kill a stalled GPU decode attempt and fall back', async () => {
process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT = '0.05'
const outputFile = path.join(tempDir, 'out_hwdec_stall.mp4')
const warnSpy = vi.spyOn(logger, 'warn')
let killSignal: unknown
mockFfmpeg((n, cb, options) => {
if (n === 1) {
// simulate a hung ffmpeg: never exits on its own, only when killed
const opts = options as { signal: AbortSignal; killSignal: string }
killSignal = opts.killSignal
opts.signal.addEventListener('abort', () => {
const err = new Error('The operation was aborted')
err.name = 'AbortError'
cb(err, { stdout: '', stderr: '' })
})
} else {
cb(null, { stdout: '', stderr: '' })
}
})
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(killSignal).toBe('SIGKILL')
expect(calls()).toHaveLength(2)
expect(calls()[1]).not.toContain('-hwaccel')
expect(warnSpy).toHaveBeenCalledWith(
expect.objectContaining({
err: expect.objectContaining({ message: expect.stringContaining('made no progress') }),
}),
'Hardware decode failed; retrying with software decode and hardware encode',
)
})
it('transcodeVideo should fall back to libx264 when GPU decode and vaapi encode both fail', async () => {
const outputFile = path.join(tempDir, 'out_hwdec_x264.mp4')
let existedBeforeRetry = true
mockFfmpeg((n, cb) => {
if (n === 1) {
fs.writeFileSync(outputFile, 'partial video data')
cb(new Error('hw decode failed'), { stdout: '', stderr: '' })
} else if (n === 2) {
existedBeforeRetry = fs.existsSync(outputFile)
cb(new Error('vaapi encode failed'), { stdout: '', stderr: '' })
} else {
cb(null, { stdout: '', stderr: '' })
}
})
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(3)
expect(existedBeforeRetry).toBe(false)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[1]).toContain('h264_vaapi')
expect(calls()[1]).not.toContain('-hwaccel')
expect(calls()[2]).toContain('libx264')
})
it('transcodeVideo should not retry when the GPU decode attempt was aborted by the caller', async () => {
const abortController = new AbortController()
mockFfmpeg((_n, cb) => {
abortController.abort()
const abortErr = new Error('The operation was aborted')
abortErr.name = 'AbortError'
cb(abortErr, { stdout: '', stderr: '' })
})
await expect(
transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_abort.mp4'),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
signal: abortController.signal,
}),
).rejects.toThrow('aborted')
expect(vi.mocked(child_process.execFile)).toHaveBeenCalledTimes(1)
})
it('transcodeVideo should keep software decode for watermark overlays', async () => {
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_overlay.mp4'),
width: 1280,
height: 720,
overlayFile: 'overlay.png',
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(1)
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('overlay=0:0')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should keep software decode for HDR sources', async () => {
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mov',
outputFile: path.join(tempDir, 'out_hwdec_hdr.mp4'),
width: 1920,
height: 1080,
sourceHdrType: 'pq',
hardwareAcceleration: 'auto',
})
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should keep software decode when SHUMAI_HW_DECODE=false', async () => {
process.env.SHUMAI_HW_DECODE = 'false'
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, 'out_hwdec_disabled.mp4'),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()[0]).not.toContain('-hwaccel')
expect(filterOf(calls()[0])).toContain('hwupload')
})
it('transcodeVideo should not use GPU decode for encoders without a hardware decode config', async () => {
for (const encoder of ['libx264', 'h264_amf', 'h264_videotoolbox'] as const) {
vi.mocked(child_process.execFile).mockClear()
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(
H264_ENCODER_CONFIGS[encoder],
)
mockFfmpeg(failOn())
await transcodeService.transcodeVideo({
inputFile: 'input.mp4',
outputFile: path.join(tempDir, `out_hwdec_${encoder}.mp4`),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(1)
expect(calls()[0]).not.toContain('-hwaccel')
expect(calls()[0]).toContain(encoder)
}
})
it('transcodeHlsRendition should decode and scale on the GPU by default with vaapi', async () => {
mockFfmpeg(failOn())
const loggerSpy = vi.spyOn(logger, 'info')
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir: path.join(tempDir, 'hls_hwdec'),
width: 1920,
height: 1080,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
const args = calls()[0]
expect(args).toEqual(
expect.arrayContaining([
'-hwaccel',
'vaapi',
'-hwaccel_output_format',
'vaapi',
'-noautoscale',
'-f',
'hls',
]),
)
expect(args.indexOf('-hwaccel')).toBeLessThan(args.indexOf('-i'))
expect(filterOf(args)).toBe(`[0:V]${vaapiScale(1920, 1080)},fps=24[vout]`)
expect(transcodeService.getVideoRotation).not.toHaveBeenCalled()
expect(loggerSpy).toHaveBeenCalledWith(
expect.objectContaining({ encoder: 'h264_vaapi', hwDecode: true }),
'Starting HLS rendition transcoding',
)
})
it('transcodeHlsRendition should decode and scale on the GPU by default with nvenc and qsv', async () => {
// NVENC
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(
H264_ENCODER_CONFIGS.h264_nvenc,
)
mockFfmpeg(failOn())
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir: path.join(tempDir, 'hls_hwdec_nvenc'),
width: 1920,
height: 1080,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[0]).toContain('cuda')
expect(calls()[0]).toContain('-forced-idr')
expect(calls()[0]).toContain('1')
expect(filterOf(calls()[0])).toBe(`[0:V]${nvencScale(1920, 1080)},fps=24[vout]`)
// QSV
vi.mocked(child_process.execFile).mockClear()
vi.mocked(transcodeService.selectH264Encoder).mockResolvedValue(H264_ENCODER_CONFIGS.h264_qsv)
mockFfmpeg(failOn())
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir: path.join(tempDir, 'hls_hwdec_qsv'),
width: 1920,
height: 1080,
frameRate: 24,
hardwareAcceleration: 'auto',
sourceRotation: 0,
})
expect(calls()).toHaveLength(1)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[0]).toContain('qsv')
expect(calls()[0]).toContain('-idr_interval')
expect(calls()[0]).toContain('0')
expect(filterOf(calls()[0])).toBe(`[0:V]${qsvScale(1920, 1080)},fps=24[vout]`)
})
it('transcodeHlsRendition should keep software decode when rotation cannot be determined', async () => {
vi.mocked(transcodeService.getVideoRotation).mockResolvedValue(null)
mockFfmpeg(failOn())
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir: path.join(tempDir, 'hls_hwdec_unknown_rotation'),
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()[0]).not.toContain('-hwaccel')
})
it('transcodeHlsRendition should retry with software decode, then libx264, cleaning the output dir', async () => {
const outputDir = path.join(tempDir, 'hls_hwdec_fallback')
let dirExistedBeforeRetry = true
mockFfmpeg((n, cb) => {
if (n === 1) {
fs.writeFileSync(path.join(outputDir, 'segment_000.m4s'), 'partial')
cb(new Error('hw decode failed'), { stdout: '', stderr: '' })
} else if (n === 2) {
dirExistedBeforeRetry = fs.existsSync(path.join(outputDir, 'segment_000.m4s'))
cb(new Error('vaapi encode failed'), { stdout: '', stderr: '' })
} else {
cb(null, { stdout: '', stderr: '' })
}
})
await transcodeService.transcodeHlsRendition({
inputFile: 'input.mp4',
outputDir,
width: 1280,
height: 720,
hardwareAcceleration: 'auto',
})
expect(calls()).toHaveLength(3)
expect(dirExistedBeforeRetry).toBe(false)
expect(calls()[0]).toContain('-hwaccel')
expect(calls()[1]).not.toContain('-hwaccel')
expect(filterOf(calls()[1])).toContain('hwupload')
expect(calls()[2]).toContain('libx264')
})
it('getVideoRotation should read the display matrix, the rotate tag, and normalize', async () => {
vi.mocked(transcodeService.getVideoRotation).mockRestore()
const probe = (json: unknown) =>
vi
.mocked(execFile)
.mockImplementationOnce(
(
_cmd: unknown,
_args: unknown,
callback: unknown,
): ReturnType<typeof child_process.execFile> => {
;(callback as FfmpegCallback)(null, { stdout: JSON.stringify(json), stderr: '' })
return {} as ReturnType<typeof child_process.execFile>
},
)
/* eslint-disable @typescript-eslint/naming-convention */
probe({
streams: [{ side_data_list: [{ side_data_type: 'Display Matrix', rotation: -90 }] }],
})
/* eslint-enable @typescript-eslint/naming-convention */
expect(await transcodeService.getVideoRotation('a.mov')).toBe(270)
probe({ streams: [{ tags: { rotate: '180' } }] })
expect(await transcodeService.getVideoRotation('b.mp4')).toBe(180)
probe({ streams: [{}] })
expect(await transcodeService.getVideoRotation('c.mp4', 2)).toBe(0)
expect(vi.mocked(child_process.execFile).mock.calls.at(-1)?.[1]).toEqual(
expect.arrayContaining(['-select_streams', '2']),
)
probe({ streams: [] })
expect(await transcodeService.getVideoRotation('d.mp4')).toBeNull()
})
})
describe('HDR detection, tone mapping, and transcoding', () => {
it('buildSdrToneMapFilterChain constructs zscale + tonemap filter chain for PQ and HLG', () => {
const available = new Set(['zscale', 'tonemap'])
+514 -98
View File
@@ -194,6 +194,8 @@ export interface TranscodeVideoParams {
sourceColorTransfer?: string
sourceColorPrimaries?: string
sourceColorSpace?: string
/** Source rotation in degrees from MediaMetadata; probed when omitted. */
sourceRotation?: number
streamIndex?: number
audioStreamIndex?: number
}
@@ -218,6 +220,8 @@ export interface TranscodeHlsRenditionParams {
sourceColorPrimaries?: string
sourceColorSpace?: string
segmentDuration?: number
/** Source rotation in degrees from MediaMetadata; probed when omitted. */
sourceRotation?: number
streamIndex?: number
audioStreamIndex?: number
}
@@ -240,6 +244,10 @@ export const H264_ENCODER_CONFIGS: Record<string, EncoderConfig> = {
name: 'h264_vaapi',
presetArgs: ['-compression_level', '4'],
},
h264_rkmpp: {
name: 'h264_rkmpp',
presetArgs: ['-level', '51', '-rc_mode', 'AVBR'],
},
h264_amf: {
name: 'h264_amf',
presetArgs: ['-quality', 'balanced', '-rc', 'qvbr', '-qvbr_quality_level', '26'],
@@ -254,6 +262,82 @@ export const H264_ENCODER_CONFIGS: Record<string, EncoderConfig> = {
},
}
/**
* How an encoder can also decode and scale on its own device, so frames stay in
* GPU memory instead of being decoded and scaled on the CPU and uploaded.
* Matches Immich's hardware acceleration pipelines for NVENC (CUDA), QSV, VAAPI,
* and RKMPP.
*/
export interface HardwareDecodeConfig {
/** Input options placed before `-i` (after any `-init_hw_device`). */
inputArgs: string[]
/** Dynamic input options generator taking device info if applicable. */
getInputArgs?: (driDevice?: string) => string[]
/** Output options placed after the filter graph. */
outputArgs: string[]
/** GPU filter fitting the frame within width x height with even dimensions. */
scaleFilter: (width: number, height: number) => string
}
export function resolveHwDecodeInputArgs(
config: HardwareDecodeConfig,
driDevice?: string,
): string[] {
return config.getInputArgs ? config.getInputArgs(driDevice) : config.inputArgs
}
export const HW_DECODE_CONFIGS: Partial<Record<string, HardwareDecodeConfig>> = {
h264_nvenc: {
inputArgs: ['-hwaccel', 'cuda', '-hwaccel_output_format', 'cuda', '-threads', '1'],
outputArgs: ['-noautoscale'],
scaleFilter: (width, height) =>
`scale_cuda=w=${width}:h=${height}:force_original_aspect_ratio=decrease:force_divisible_by=2:format=nv12`,
},
h264_qsv: {
inputArgs: [
'-hwaccel',
'qsv',
'-hwaccel_output_format',
'qsv',
'-async_depth',
'4',
'-threads',
'1',
],
getInputArgs: (driDevice?: string) => [
'-hwaccel',
'qsv',
'-hwaccel_output_format',
'qsv',
'-async_depth',
'4',
'-threads',
'1',
...(driDevice ? ['-qsv_device', driDevice] : []),
],
outputArgs: ['-noautoscale'],
scaleFilter: (width, height) =>
`scale_qsv=w=${width}:h=${height}:async_depth=4:mode=hq:format=nv12`,
},
h264_vaapi: {
inputArgs: ['-hwaccel', 'vaapi', '-hwaccel_device', 'accel', '-hwaccel_output_format', 'vaapi'],
// If the decoder reinitializes mid-stream with a different coded size
// (e.g. 1080 -> 1088), ffmpeg would otherwise auto-insert a software
// scaler, which cannot take GPU frames, and fail.
outputArgs: ['-noautoscale'],
// Output range is left as-is (matching the software path): on i965,
// out_range only retags the stream without converting levels.
scaleFilter: (width, height) =>
`scale_vaapi=w=${width}:h=${height}:force_original_aspect_ratio=decrease:force_divisible_by=2:format=nv12:mode=hq`,
},
h264_rkmpp: {
inputArgs: ['-hwaccel', 'rkmpp', '-hwaccel_output_format', 'drm_prime', '-afbc', 'rga'],
outputArgs: ['-noautoscale'],
scaleFilter: (width, height) =>
`scale_rkrga=w=${width}:h=${height}:format=nv12:afbc=1:async_depth=4`,
},
}
export function getPlatformEncoderCandidates(
platform: NodeJS.Platform = process.platform,
): string[] {
@@ -264,12 +348,13 @@ export function getPlatformEncoderCandidates(
return ['h264_nvenc', 'h264_qsv', 'h264_amf']
case 'linux':
default:
return ['h264_nvenc', 'h264_vaapi', 'h264_qsv', 'h264_amf']
return ['h264_nvenc', 'h264_vaapi', 'h264_qsv', 'h264_rkmpp', 'h264_amf']
}
}
export function getVaapiDevice(driDir = '/dev/dri'): string | null {
const envDevice = process.env.SHUMAI_VAAPI_DEVICE || process.env.VAAPI_DEVICE
export function getDriDevice(driDir = '/dev/dri'): string | null {
const envDevice =
process.env.SHUMAI_HW_DEVICE || process.env.SHUMAI_VAAPI_DEVICE || process.env.VAAPI_DEVICE
if (envDevice) {
return envDevice
}
@@ -293,6 +378,47 @@ export function getVaapiDevice(driDir = '/dev/dri'): string | null {
return null
}
export function getVaapiDevice(driDir = '/dev/dri'): string | null {
return getDriDevice(driDir)
}
/**
* Whether hardware encoders with a {@link HW_DECODE_CONFIGS} entry also decode
* and scale on the GPU. Enabled by default; set SHUMAI_HW_DECODE=false to disable.
*/
export function isHwDecodeEnabled(): boolean {
const value = process.env.SHUMAI_HW_DECODE?.trim().toLowerCase()
return value !== 'false' && value !== '0' && value !== 'off'
}
/**
* A GPU-decode attempt whose output stops growing for this long is killed and
* retried with software decode, since some driver failures hang ffmpeg instead
* of exiting. Override with SHUMAI_HW_DECODE_STALL_TIMEOUT (seconds).
*/
export function getHwDecodeStallTimeoutMs(): number {
const seconds = parseFloat(process.env.SHUMAI_HW_DECODE_STALL_TIMEOUT ?? '')
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : 120_000
}
function getPathSize(target: string): number {
try {
const stat = fs.statSync(target)
if (!stat.isDirectory()) {
return stat.size
}
return fs
.readdirSync(target)
.reduce((total, entry) => total + getPathSize(path.join(target, entry)), 0)
} catch {
return 0
}
}
function normalizeRotation(rotation: number): number {
return ((Math.round(rotation) % 360) + 360) % 360
}
export function parseBitrateKbps(bitrate: string | number): number {
if (typeof bitrate === 'number') {
return Math.round(bitrate / 1000)
@@ -784,7 +910,7 @@ export class TranscodeService {
}
}
// RAW branch — extract embedded JPEG for metadata
// RAW branch — extract embedded JPEG or decode RAW for metadata
if (typeof input === 'string' && isRawImage(input)) {
const extracted = await extractAndValidateRawPreview(input)
if (extracted) {
@@ -793,8 +919,10 @@ export class TranscodeService {
extracted.orientation !== undefined &&
extracted.orientation >= 5 &&
extracted.orientation <= 8
const originalWidth = isSwapped ? extracted.height : extracted.width
const originalHeight = isSwapped ? extracted.width : extracted.height
const sourceWidth = extracted.rawWidth ?? extracted.width
const sourceHeight = extracted.rawHeight ?? extracted.height
const originalWidth = isSwapped ? sourceHeight : sourceWidth
const originalHeight = isSwapped ? sourceWidth : sourceHeight
return {
originalWidth,
@@ -898,8 +1026,12 @@ export class TranscodeService {
}
}
getDriDevice(driDir = '/dev/dri'): string | null {
return this.getVaapiDevice(driDir)
}
getVaapiDevice(driDir = '/dev/dri'): string | null {
return getVaapiDevice(driDir)
return getDriDevice(driDir)
}
async isEncoderUsable(encoder: string): Promise<boolean> {
@@ -1007,6 +1139,31 @@ export class TranscodeService {
async transcodeVideo(params: TranscodeVideoParams): Promise<void> {
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
if (await this.canUseHwDecode(params, encoder)) {
try {
await this.executeFfmpegVideoTranscode(params, encoder, { hwDecode: true })
return
} catch (err) {
if (this.isAbortError(err, params.signal)) {
throw err
}
logger.warn(
{
err,
encoder: encoder.name,
inputFile: params.inputFile,
outputFile: params.outputFile,
width: params.width,
height: params.height,
},
'Hardware decode failed; retrying with software decode and hardware encode',
)
this.removeFileIfExists(params.outputFile)
}
}
if (encoder.name !== 'libx264') {
try {
await this.executeFfmpegVideoTranscode(params, encoder)
@@ -1028,13 +1185,7 @@ export class TranscodeService {
'Hardware video transcoding failed; falling back to software transcode (libx264)',
)
if (fs.existsSync(params.outputFile)) {
try {
fs.unlinkSync(params.outputFile)
} catch {
// ignore unlink errors
}
}
this.removeFileIfExists(params.outputFile)
await this.executeFfmpegVideoTranscode(params, H264_ENCODER_CONFIGS.libx264)
return
@@ -1044,9 +1195,217 @@ export class TranscodeService {
await this.executeFfmpegVideoTranscode(params, encoder)
}
/**
* GPU decode + scale is attempted only for plain proxies: watermark overlays,
* HDR sources and rotated sources keep the software decode path. (ffmpeg
* cannot auto-insert its rotation filter on GPU frames, so a rotated phone
* clip would otherwise come out sideways rather than fail.) Sources the GPU
* cannot decode (e.g. HEVC/10-bit on older Intel iGPUs) fail fast and are
* retried with software decode by the caller.
*/
private async canUseHwDecode(
params: Pick<
TranscodeVideoParams,
| 'inputFile'
| 'streamIndex'
| 'overlayFile'
| 'sourceIsHdr'
| 'sourceHdrType'
| 'sourceRotation'
>,
encoder: EncoderConfig,
): Promise<boolean> {
if (!HW_DECODE_CONFIGS[encoder.name] || !isHwDecodeEnabled()) {
return false
}
if (params.overlayFile) {
return false
}
const isSourceHdr =
params.sourceIsHdr ||
params.sourceHdrType === 'pq' ||
params.sourceHdrType === 'hlg' ||
params.sourceHdrType === 'dovi_p5'
if (isSourceHdr) {
return false
}
if (encoder.name === 'h264_vaapi' && !this.getDriDevice()) {
return false
}
if (encoder.name === 'h264_qsv' && process.platform === 'linux' && !this.getDriDevice()) {
return false
}
const rotation =
params.sourceRotation !== undefined
? normalizeRotation(params.sourceRotation)
: await this.getVideoRotation(params.inputFile, params.streamIndex)
return rotation === 0
}
/**
* Rotation of the source video stream in degrees (0, 90, 180 or 270), from
* the display matrix or the legacy `rotate` tag. Returns null if it cannot be
* determined.
*/
async getVideoRotation(inputFile: string, streamIndex?: number): Promise<number | null> {
try {
const { stdout } = await execFileAsync('ffprobe', [
'-v',
'error',
'-select_streams',
streamIndex !== undefined ? String(streamIndex) : 'V:0',
'-show_entries',
'stream_side_data=rotation:stream_tags=rotate',
'-of',
'json',
inputFile,
])
const stream = JSON.parse(stdout)?.streams?.[0]
if (!stream) {
return null
}
let rotation = 0
const sideData = Array.isArray(stream.side_data_list) ? stream.side_data_list : []
const matrix = sideData.find((d: { rotation?: unknown }) => typeof d.rotation === 'number')
if (matrix) {
rotation = matrix.rotation
} else if (stream.tags?.rotate !== undefined) {
rotation = parseFloat(stream.tags.rotate) || 0
}
return normalizeRotation(rotation)
} catch (err) {
logger.debug({ err, inputFile }, 'Failed to probe video rotation')
return null
}
}
private removeFileIfExists(filePath: string): void {
if (fs.existsSync(filePath)) {
try {
fs.unlinkSync(filePath)
} catch {
// ignore unlink errors
}
}
}
/**
* Inputs, video filter graph and `-map [vout]`, shared by the MP4 and HLS
* paths: GPU decode + GPU scale when `hwDecodeConfig` is set, otherwise
* software decode + scale (+ upload for VAAPI encode).
*/
private buildVideoInputArgs(
params: Pick<
TranscodeVideoParams,
'inputFile' | 'overlayFile' | 'streamIndex' | 'width' | 'height'
>,
options: {
isVaapi: boolean
driDevice?: string
hwDecodeConfig?: HardwareDecodeConfig
frameRate?: number | string
},
): string[] {
const { isVaapi, driDevice, hwDecodeConfig, frameRate } = options
const args: string[] = []
if (isVaapi && driDevice) {
args.push('-init_hw_device', `vaapi=accel:${driDevice}`, '-filter_hw_device', 'accel')
}
if (hwDecodeConfig) {
args.push(...resolveHwDecodeInputArgs(hwDecodeConfig, driDevice))
}
args.push('-i', params.inputFile)
const baseScale = hwDecodeConfig
? hwDecodeConfig.scaleFilter(params.width, params.height)
: `scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
const vPad = params.streamIndex !== undefined ? `0:${params.streamIndex}` : '0:V'
let filterComplex: string
if (params.overlayFile) {
args.push('-i', params.overlayFile)
filterComplex = `[${vPad}]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0`
} else {
filterComplex = `[${vPad}]${baseScale}`
}
if (frameRate) {
filterComplex += `,fps=${frameRate}`
}
if (isVaapi && !hwDecodeConfig) {
filterComplex += ',format=nv12,hwupload=extra_hw_frames=64'
}
filterComplex += '[vout]'
args.push('-filter_complex', filterComplex, '-map', '[vout]')
if (hwDecodeConfig) {
args.push(...hwDecodeConfig.outputArgs)
}
return args
}
/**
* Runs ffmpeg. With `stallWatchPath`, ffmpeg is killed (SIGKILL; hung VAAPI
* processes have been seen to ignore SIGTERM) if that output file/directory
* stops growing for {@link getHwDecodeStallTimeoutMs}, and the call rejects
* with a regular error so the caller can fall back.
*/
private async runFfmpeg(
args: string[],
options: { signal?: AbortSignal; stallWatchPath?: string } = {},
): Promise<void> {
const ffmpegArgs = ['-y', '-loglevel', 'warning', ...args]
if (!options.stallWatchPath) {
if (options.signal) {
await execFileAsync('ffmpeg', ffmpegArgs, { signal: options.signal })
} else {
await execFileAsync('ffmpeg', ffmpegArgs)
}
return
}
const stallTimeoutMs = getHwDecodeStallTimeoutMs()
const stall = new AbortController()
const signal = options.signal ? AbortSignal.any([options.signal, stall.signal]) : stall.signal
const watchPath = options.stallWatchPath
let lastSize = -1
let lastProgressAt = Date.now()
const timer = setInterval(
() => {
const size = getPathSize(watchPath)
if (size !== lastSize) {
lastSize = size
lastProgressAt = Date.now()
} else if (Date.now() - lastProgressAt >= stallTimeoutMs) {
stall.abort()
}
},
Math.min(5000, stallTimeoutMs),
)
timer.unref?.()
try {
await execFileAsync('ffmpeg', ffmpegArgs, { signal, killSignal: 'SIGKILL' })
} catch (err) {
if (stall.signal.aborted && !options.signal?.aborted) {
throw new Error(
`ffmpeg made no progress for ${Math.round(stallTimeoutMs / 1000)}s and was killed`,
{ cause: err },
)
}
throw err
} finally {
clearInterval(timer)
}
}
private async executeFfmpegVideoTranscode(
params: TranscodeVideoParams,
encoder: EncoderConfig,
options: { hwDecode?: boolean } = {},
): Promise<void> {
const isSourceHdr =
params.sourceIsHdr ||
@@ -1056,7 +1415,9 @@ export class TranscodeService {
const isHdrOutput = Boolean(params.hdr)
const isVaapi = encoder.name === 'h264_vaapi'
const vaapiDevice = isVaapi ? (this.getVaapiDevice() ?? '/dev/dri/renderD128') : undefined
const driDevice = this.getDriDevice() ?? (isVaapi ? '/dev/dri/renderD128' : undefined)
const hwDecodeConfig = options.hwDecode ? HW_DECODE_CONFIGS[encoder.name] : undefined
const hwDecode = Boolean(hwDecodeConfig)
logger.info(
{
@@ -1064,39 +1425,19 @@ export class TranscodeService {
hardwareAcceleration: params.hardwareAcceleration ?? 'off',
inputFile: params.inputFile,
outputFile: params.outputFile,
vaapiDevice,
vaapiDevice: isVaapi ? driDevice : undefined,
driDevice,
hwDecode,
},
'Starting video transcoding',
)
let filterComplex: string
const args: string[] = []
if (isVaapi && vaapiDevice) {
args.push('-init_hw_device', `vaapi=accel:${vaapiDevice}`, '-filter_hw_device', 'accel')
}
args.push('-i', params.inputFile)
const baseScale = `scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
const vPad = params.streamIndex !== undefined ? `0:${params.streamIndex}` : '0:V'
if (params.overlayFile) {
args.push('-i', params.overlayFile)
filterComplex = `[${vPad}]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0`
} else {
filterComplex = `[${vPad}]${baseScale}`
}
if (params.frameRate) {
filterComplex += `,fps=${params.frameRate}`
}
if (isVaapi) {
filterComplex += ',format=nv12,hwupload=extra_hw_frames=64'
}
filterComplex += '[vout]'
args.push('-filter_complex', filterComplex, '-map', '[vout]')
const args = this.buildVideoInputArgs(params, {
isVaapi,
driDevice,
hwDecodeConfig,
frameRate: params.frameRate,
})
if (params.frameRate) {
let calculatedFps: number
@@ -1171,6 +1512,18 @@ export class TranscodeService {
'-minrate',
`${minKbps}k`,
)
} else if (encoder.name === 'h264_rkmpp') {
if (params.videoBitrate) {
args.push('-b:v', params.videoBitrate)
} else {
const { maxrate } = calculateMaxBitrate(
params.height,
params.width,
params.sourceVideoBitrate,
params.frameRate,
)
args.push('-b:v', maxrate)
}
} else {
if (params.videoBitrate) {
args.push('-b:v', params.videoBitrate)
@@ -1185,7 +1538,7 @@ export class TranscodeService {
}
}
if (!isVaapi) {
if (!hwDecode && !isVaapi) {
args.push('-pix_fmt', 'yuv420p')
}
@@ -1208,18 +1561,40 @@ export class TranscodeService {
args.push('-movflags', '+faststart', '-max_muxing_queue_size', '1024', params.outputFile)
if (params.signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], {
signal: params.signal,
})
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
await this.runFfmpeg(args, {
signal: params.signal,
stallWatchPath: hwDecode ? params.outputFile : undefined,
})
}
async transcodeHlsRendition(params: TranscodeHlsRenditionParams): Promise<void> {
const encoder = await this.selectH264Encoder(params.hardwareAcceleration)
if (await this.canUseHwDecode(params, encoder)) {
try {
await this.executeFfmpegHlsTranscode(params, encoder, { hwDecode: true })
return
} catch (err) {
if (this.isAbortError(err, params.signal)) {
throw err
}
logger.warn(
{
err,
encoder: encoder.name,
inputFile: params.inputFile,
outputDir: params.outputDir,
width: params.width,
height: params.height,
},
'Hardware decode failed for HLS; retrying with software decode and hardware encode',
)
this.removeDirIfExists(params.outputDir)
}
}
if (encoder.name !== 'libx264') {
try {
await this.executeFfmpegHlsTranscode(params, encoder)
@@ -1241,13 +1616,7 @@ export class TranscodeService {
'Hardware HLS transcoding failed; falling back to software transcode (libx264)',
)
if (fs.existsSync(params.outputDir)) {
try {
fs.rmSync(params.outputDir, { recursive: true, force: true })
} catch {
// ignore unlink errors
}
}
this.removeDirIfExists(params.outputDir)
await this.executeFfmpegHlsTranscode(params, H264_ENCODER_CONFIGS.libx264)
return
@@ -1257,9 +1626,20 @@ export class TranscodeService {
await this.executeFfmpegHlsTranscode(params, encoder)
}
private removeDirIfExists(dirPath: string): void {
if (fs.existsSync(dirPath)) {
try {
fs.rmSync(dirPath, { recursive: true, force: true })
} catch {
// ignore unlink errors
}
}
}
private async executeFfmpegHlsTranscode(
params: TranscodeHlsRenditionParams,
encoder: EncoderConfig,
options: { hwDecode?: boolean } = {},
): Promise<void> {
fs.mkdirSync(params.outputDir, { recursive: true })
@@ -1271,7 +1651,9 @@ export class TranscodeService {
const isHdrOutput = Boolean(params.hdr)
const isVaapi = encoder.name === 'h264_vaapi'
const vaapiDevice = isVaapi ? (this.getVaapiDevice() ?? '/dev/dri/renderD128') : undefined
const driDevice = this.getDriDevice() ?? (isVaapi ? '/dev/dri/renderD128' : undefined)
const hwDecodeConfig = options.hwDecode ? HW_DECODE_CONFIGS[encoder.name] : undefined
const hwDecode = Boolean(hwDecodeConfig)
const segmentDuration = params.segmentDuration || 4
let calculatedFps = 30
@@ -1302,37 +1684,17 @@ export class TranscodeService {
height: params.height,
segmentDuration,
gopSize,
hwDecode,
},
'Starting HLS rendition transcoding',
)
let filterComplex: string
const args: string[] = []
if (isVaapi && vaapiDevice) {
args.push('-init_hw_device', `vaapi=accel:${vaapiDevice}`, '-filter_hw_device', 'accel')
}
args.push('-i', params.inputFile)
const baseScale = `scale=w=${params.width}:h=${params.height}:force_original_aspect_ratio=decrease,scale=w='trunc(iw/2)*2':h='trunc(ih/2)*2'`
const vPad = params.streamIndex !== undefined ? `0:${params.streamIndex}` : '0:V'
if (params.overlayFile) {
args.push('-i', params.overlayFile)
filterComplex = `[${vPad}]scale=${params.width}:${params.height}[vscaled];[vscaled][1:v]overlay=0:0`
} else {
filterComplex = `[${vPad}]${baseScale}`
}
filterComplex += `,fps=${calculatedFps}`
if (isVaapi) {
filterComplex += ',format=nv12,hwupload=extra_hw_frames=64'
}
filterComplex += '[vout]'
args.push('-filter_complex', filterComplex, '-map', '[vout]')
const args = this.buildVideoInputArgs(params, {
isVaapi,
driDevice,
hwDecodeConfig,
frameRate: calculatedFps,
})
if (!params.disableAudio) {
const aMap = params.audioStreamIndex !== undefined ? `0:${params.audioStreamIndex}` : '0:a:0?'
@@ -1396,7 +1758,7 @@ export class TranscodeService {
maxKbps = parseInt(maxrate, 10)
}
const targetKbps = Math.max(25, Math.ceil(maxKbps / 1.45))
args.push('-b:v', `${targetKbps}k`, '-maxrate', `${maxKbps}k`)
args.push('-b:v', `${targetKbps}k`, '-maxrate', `${maxKbps}k`, '-idr_interval', '0')
} else if (encoder.name === 'h264_nvenc') {
let maxrateStr: string
let bufsizeStr: string
@@ -1427,7 +1789,23 @@ export class TranscodeService {
'1',
'-temporal-aq',
'1',
'-forced-idr',
'1',
)
} else if (encoder.name === 'h264_rkmpp') {
let maxKbps: number
if (params.videoBitrate) {
maxKbps = parseBitrateKbps(params.videoBitrate)
} else {
const { maxrate } = calculateMaxBitrate(
params.height,
params.width,
params.sourceVideoBitrate,
calculatedFps,
)
maxKbps = parseInt(maxrate, 10)
}
args.push('-b:v', `${maxKbps}k`)
} else {
let maxrateStr: string
let bufsizeStr: string
@@ -1448,7 +1826,7 @@ export class TranscodeService {
args.push('-crf', '23', '-maxrate', maxrateStr, '-bufsize', bufsizeStr)
}
if (!isVaapi) {
if (!hwDecode && !isVaapi) {
args.push('-pix_fmt', 'yuv420p')
}
@@ -1506,13 +1884,10 @@ export class TranscodeService {
playlistFile,
)
if (params.signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], {
signal: params.signal,
})
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
await this.runFfmpeg(args, {
signal: params.signal,
stallWatchPath: hwDecode ? params.outputDir : undefined,
})
}
async transcodeImage(
@@ -1545,13 +1920,15 @@ export class TranscodeService {
input = Buffer.from(await resp.arrayBuffer())
}
// RAW branch — extract embedded JPEG to temporary file + orientation, then treat as normal image
// RAW branch — extract embedded preview or decode RAW to temporary file + orientation, then treat as normal image
let rawOrientation: number | undefined
let rawCleanup: (() => void) | null = null
if (typeof input === 'string' && isRawImage(input)) {
const extracted = await extractAndValidateRawPreview(input)
if (!extracted) {
throw new Error(`Cannot generate preview for RAW file: no usable embedded JPEG in ${input}`)
throw new Error(
`Cannot generate preview for RAW file: no usable embedded preview or decoded image in ${input}`,
)
}
input = extracted.previewPath
rawOrientation = extracted.orientation
@@ -2741,6 +3118,45 @@ export class TranscodeService {
.webp({ quality: 90 })
.toFile(outputPath)
}
async convertImageToWebp(imageBuffer: Buffer, quality = 85): Promise<Buffer> {
return await sharp(imageBuffer, { limitInputPixels: false })
.toColorspace('srgb')
.webp({ quality })
.toBuffer()
}
async generate3dSprite(
inputFile: string,
outputSprite: string,
signal?: AbortSignal,
): Promise<void> {
if (signal?.aborted) {
throw new Error('Sprite generation cancelled')
}
const spriteFps = 100 / 4
const filterComplex = `[0:v]fps=${spriteFps},scale=w=300:h=-2,tile=10x10[sprite_out]`
const args = [
'-i',
inputFile,
'-filter_complex',
filterComplex,
'-map',
'[sprite_out]',
'-frames:v',
'1',
'-c:v',
'libwebp',
'-q:v',
'75',
outputSprite,
]
if (signal) {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args], { signal })
} else {
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
}
}
}
function renderAnnotationsToSvg(
@@ -0,0 +1,237 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { TurntableService } from './turntable'
describe('TurntableService', () => {
setupTestDbHooks()
const originalEnv = process.env
let tmpDir: string
let testFilePath: string
beforeEach(() => {
process.env = { ...originalEnv }
delete process.env.TURNTABLE_RENDERER_URL
delete process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME
delete process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD
delete process.env.TURNTABLE_RENDERER_USERNAME
delete process.env.TURNTABLE_RENDERER_PASSWORD
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'turntable-test-'))
testFilePath = path.join(tmpDir, 'model.glb')
fs.writeFileSync(testFilePath, 'fake glb content')
})
afterEach(() => {
process.env = originalEnv
fs.rmSync(tmpDir, { recursive: true, force: true })
vi.restoreAllMocks()
})
describe('resolveConfig', () => {
it('returns isEnv: false when neither env nor team settings are present', async () => {
const service = new TurntableService()
const config = await service.resolveConfig()
expect(config.url).toBeUndefined()
expect(config.isEnv).toBe(false)
})
it('resolves env configuration with highest priority', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://localhost:3000/'
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME = 'admin'
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD = 'secret'
const service = new TurntableService()
const config = await service.resolveConfig('any-team-id')
expect(config.url).toBe('http://localhost:3000')
expect(config.username).toBe('admin')
expect(config.password).toBe('secret')
expect(config.isEnv).toBe(true)
})
it('falls back to team DB settings when env is not set', async () => {
const team = await prisma.team.create({
data: {
name: 'Test Team 3D',
settings: {
turntable: {
url: 'http://custom-turntable:4000',
username: 'teamUser',
password: 'teamPassword',
},
},
},
})
const service = new TurntableService()
const config = await service.resolveConfig(team.id)
expect(config.url).toBe('http://custom-turntable:4000')
expect(config.username).toBe('teamUser')
expect(config.password).toBe('teamPassword')
expect(config.isEnv).toBe(false)
})
})
describe('isAvailable', () => {
it('returns false if URL is not configured', async () => {
const service = new TurntableService()
expect(await service.isAvailable()).toBe(false)
})
it('returns true when health check returns 200', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
} as Response)
const service = new TurntableService()
expect(await service.isAvailable()).toBe(true)
})
it('returns false when health check fails or throws', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('Connection refused'))
const service = new TurntableService()
expect(await service.isAvailable()).toBe(false)
})
})
describe('testConnection', () => {
it('returns error when url is empty', async () => {
const service = new TurntableService()
const result = await service.testConnection({})
expect(result.ok).toBe(false)
expect(result.error).toBe('URL is required')
})
it('returns version information upon successful connection', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ version: '0.1.0', blender: '5.2.2' }),
} as Response)
const service = new TurntableService()
const result = await service.testConnection({ url: 'http://localhost:3000' })
expect(result.ok).toBe(true)
expect(result.version).toBe('0.1.0')
expect(result.blender).toBe('5.2.2')
})
})
describe('uploadFile', () => {
it('posts file buffer to /v1/files and returns file info', async () => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 201,
json: async () => ({ id: 'f_test123', name: 'model.glb', size: 100 }),
} as Response)
const service = new TurntableService()
const res = await service.uploadFile(testFilePath, 'model.glb')
expect(res.id).toBe('f_test123')
expect(fetchSpy).toHaveBeenCalledWith(
'http://turntable:3000/v1/files',
expect.objectContaining({
method: 'POST',
}),
)
})
})
describe('startRender & getTaskStatus & downloadFile & deleteTask', () => {
beforeEach(() => {
process.env.TURNTABLE_RENDERER_URL = 'http://turntable:3000'
})
it('startRender calls /v1/render and returns sync response', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
json: async () => ({
taskId: 't_test456',
status: 'queued',
poster: {
fileId: 'f_poster',
size: 200,
contentType: 'image/png',
width: 1080,
height: 1080,
},
}),
} as Response)
const service = new TurntableService()
const res = await service.startRender('f_input')
expect(res.taskId).toBe('t_test456')
expect(res.poster.fileId).toBe('f_poster')
})
it('getTaskStatus queries /v1/render/tasks/:id', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
json: async () => ({
taskId: 't_test456',
status: 'completed',
video: {
fileId: 'f_video',
size: 1000,
contentType: 'video/mp4',
width: 1080,
height: 1080,
},
}),
} as Response)
const service = new TurntableService()
const res = await service.getTaskStatus('t_test456')
expect(res.status).toBe('completed')
expect(res.video?.fileId).toBe('f_video')
})
it('downloadFile fetches /v1/files/:id and writes to destination', async () => {
const destPath = path.join(tmpDir, 'downloaded.mp4')
vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
arrayBuffer: async () => Buffer.from('video data').buffer,
} as Response)
const service = new TurntableService()
await service.downloadFile('f_video', destPath)
expect(fs.existsSync(destPath)).toBe(true)
expect(fs.readFileSync(destPath, 'utf8')).toBe('video data')
})
it('deleteTask calls DELETE /v1/render/tasks/:id and returns boolean', async () => {
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
status: 200,
} as Response)
const service = new TurntableService()
const deleted = await service.deleteTask('t_test456')
expect(deleted).toBe(true)
expect(fetchSpy).toHaveBeenCalledWith(
'http://turntable:3000/v1/render/tasks/t_test456',
expect.objectContaining({
method: 'DELETE',
}),
)
})
})
})
+437
View File
@@ -0,0 +1,437 @@
import * as fs from 'fs'
import { prisma } from '@shumai/db'
import type { TurntableSettingsResponse, UpdateTurntableSettingsRequest } from '@shumai/dtos'
import { logger } from '../logger'
export interface TurntableConfig {
url?: string
username?: string
password?: string
isEnv: boolean
}
export interface TurntablePosterOutput {
fileId: string
size: number
contentType: string
width: number
height: number
}
export interface TurntableRenderSyncResponse {
taskId: string
status: 'queued' | 'rendering'
positionInQueue?: number
metadata?: Record<string, unknown>
poster: TurntablePosterOutput
}
export interface TurntableVideoOutput {
fileId: string
size: number
contentType: string
width: number
height: number
}
export interface TurntableRenderStats {
width: number
height: number
frames: number
fps: number
durationSeconds: number
degreesPerFrame: number
startAngle: number
direction: string
includeEndFrame: boolean
engine: string
elapsedMs: number
}
export interface TurntableTaskResponse {
taskId: string
status: 'queued' | 'rendering' | 'completed' | 'failed'
positionInQueue?: number
createdAt: string
startedAt?: string
completedAt?: string
failedAt?: string
render?: TurntableRenderStats
video?: TurntableVideoOutput
error?: {
code: string
message: string
details?: Record<string, unknown>
}
}
export class TurntableService {
async resolveConfig(teamId?: string): Promise<TurntableConfig> {
const envUrl = process.env.TURNTABLE_RENDERER_URL?.trim()
const envUsername =
process.env.TURNTABLE_RENDERER_BASIC_AUTH_USERNAME?.trim() ||
process.env.TURNTABLE_RENDERER_USERNAME?.trim()
const envPassword =
process.env.TURNTABLE_RENDERER_BASIC_AUTH_PASSWORD?.trim() ||
process.env.TURNTABLE_RENDERER_PASSWORD?.trim()
if (envUrl) {
return {
url: envUrl.replace(/\/+$/, ''),
username: envUsername || undefined,
password: envPassword || undefined,
isEnv: true,
}
}
if (teamId) {
try {
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const teamSettings = team?.settings as PrismaJson.Settings | null
const turntable = teamSettings?.turntable
if (turntable?.url?.trim()) {
return {
url: turntable.url.trim().replace(/\/+$/, ''),
username: turntable.username?.trim() || undefined,
password: turntable.password?.trim() || undefined,
isEnv: false,
}
}
} catch (err) {
logger.error({ err, teamId }, 'Failed to load team turntable settings')
}
}
return {
isEnv: false,
}
}
private getAuthHeader(config: TurntableConfig): string | undefined {
if (config.username && config.password) {
const credentials = Buffer.from(`${config.username}:${config.password}`).toString('base64')
return `Basic ${credentials}`
}
return undefined
}
async isAvailable(teamId?: string): Promise<boolean> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
return false
}
try {
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/health`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(3000),
})
return response.ok
} catch {
return false
}
}
async getSettings(teamId: string): Promise<TurntableSettingsResponse> {
const config = await this.resolveConfig(teamId)
return {
url: config.url,
username: config.username,
hasPassword: Boolean(config.password),
isEnvConfigured: config.isEnv,
}
}
async updateSettings(
teamId: string,
req: UpdateTurntableSettingsRequest,
): Promise<TurntableSettingsResponse> {
const currentConfig = await this.resolveConfig(teamId)
if (currentConfig.isEnv) {
throw new Error(
'Turntable settings are configured via environment variables and cannot be edited',
)
}
const team = await prisma.team.findUnique({
where: { id: teamId },
select: { settings: true },
})
const settings = (team?.settings || {}) as PrismaJson.Settings
const prevTurntable = settings.turntable || {}
settings.turntable = {
url: req.url !== undefined ? req.url : prevTurntable.url,
username: req.username !== undefined ? req.username : prevTurntable.username,
password: req.password !== undefined ? req.password : prevTurntable.password,
}
await prisma.team.update({
where: { id: teamId },
data: { settings },
})
return this.getSettings(teamId)
}
async testConnection(
config?: {
url?: string
username?: string
password?: string
},
teamId?: string,
): Promise<{ ok: boolean; version?: string; blender?: string; error?: string }> {
let resolvedUrl = config?.url?.trim()
let resolvedUsername = config?.username?.trim()
let resolvedPassword = config?.password
if (teamId && (!resolvedUrl || resolvedPassword === undefined)) {
const savedConfig = await this.resolveConfig(teamId)
if (!resolvedUrl) {
resolvedUrl = savedConfig.url
}
if (!resolvedUsername && savedConfig.username) {
resolvedUsername = savedConfig.username
}
if (resolvedPassword === undefined) {
resolvedPassword = savedConfig.password
}
}
if (!resolvedUrl) {
return { ok: false, error: 'URL is required' }
}
const cleanUrl = resolvedUrl.replace(/\/+$/, '')
try {
const headers: Record<string, string> = {}
if (resolvedUsername && resolvedPassword) {
const credentials = Buffer.from(`${resolvedUsername}:${resolvedPassword}`).toString(
'base64',
)
headers['Authorization'] = `Basic ${credentials}`
}
const response = await fetch(`${cleanUrl}/version`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(5000),
})
if (!response.ok) {
const errText = await response.text().catch(() => '')
return {
ok: false,
error: `Server returned status ${response.status}: ${errText || response.statusText}`,
}
}
const body = (await response.json()) as { version?: string; blender?: string }
return {
ok: true,
version: body.version,
blender: body.blender,
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
return { ok: false, error: message }
}
}
async uploadFile(
filePath: string,
filename: string,
teamId?: string,
): Promise<{ id: string; name: string; size: number }> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {
'content-type': 'application/octet-stream',
'x-filename': encodeURIComponent(filename),
}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/files`, {
method: 'POST',
headers,
body: Bun.file(filePath),
signal: AbortSignal.timeout(900000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Turntable upload failed with status ${response.status}: ${errorText || response.statusText}`,
)
}
return (await response.json()) as { id: string; name: string; size: number }
}
async startRender(
fileId: string,
options: Record<string, unknown> = {},
teamId?: string,
): Promise<TurntableRenderSyncResponse> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {
'content-type': 'application/json',
}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/render`, {
method: 'POST',
headers,
body: JSON.stringify({
input: { fileId },
options,
}),
signal: AbortSignal.timeout(60000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Turntable render request failed with status ${response.status}: ${errorText || response.statusText}`,
)
}
return (await response.json()) as TurntableRenderSyncResponse
}
async getTaskStatus(taskId: string, teamId?: string): Promise<TurntableTaskResponse> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/render/tasks/${taskId}`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(10000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Failed to fetch task status (${response.status}): ${errorText || response.statusText}`,
)
}
return (await response.json()) as TurntableTaskResponse
}
async downloadFile(fileId: string, targetPath?: string, teamId?: string): Promise<Buffer> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
throw new Error('Turntable renderer URL is not configured.')
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
const response = await fetch(`${config.url}/v1/files/${fileId}`, {
method: 'GET',
headers,
signal: AbortSignal.timeout(120000),
})
if (!response.ok) {
const errorText = await response.text().catch(() => '')
throw new Error(
`Failed to download file ${fileId} (${response.status}): ${errorText || response.statusText}`,
)
}
const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
if (targetPath) {
fs.writeFileSync(targetPath, buffer)
}
return buffer
}
async deleteTask(taskId: string, teamId?: string): Promise<boolean> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
return false
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
try {
const response = await fetch(`${config.url}/v1/render/tasks/${taskId}`, {
method: 'DELETE',
headers,
signal: AbortSignal.timeout(10000),
})
return response.ok
} catch {
return false
}
}
async deleteFile(fileId: string, teamId?: string): Promise<boolean> {
const config = await this.resolveConfig(teamId)
if (!config.url) {
return false
}
const headers: Record<string, string> = {}
const authHeader = this.getAuthHeader(config)
if (authHeader) {
headers['Authorization'] = authHeader
}
try {
const response = await fetch(`${config.url}/v1/files/${fileId}`, {
method: 'DELETE',
headers,
signal: AbortSignal.timeout(10000),
})
return response.ok
} catch {
return false
}
}
}
export const turntableService = new TurntableService()
+71
View File
@@ -3,6 +3,7 @@ import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { uploadService } from './upload'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { s3Service } from '@shumai/core/src/s3/s3'
import { AssetStatus, AssetType, TaskStatus, WorkflowTaskType } from '@shumai/db'
@@ -450,6 +451,76 @@ describe('UploadService', () => {
expect(workflowTask).toBeNull()
})
it('should confirm file upload and create transcode_3d for 3D model when turntable is available', async () => {
vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(true)
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key-3d-1' },
create: { key: 'test-key-3d-1' },
},
},
mediaType: 'model/gltf-binary',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_3d },
})
expect(workflowTask).toBeDefined()
expect(workflowTask?.payload).toEqual({
projectId: projectId,
transcode: {
sprite: true,
poster: true,
},
})
})
it('should mark asset processed without creating transcode_3d for 3D model when turntable is unavailable', async () => {
vi.spyOn(turntableService, 'isAvailable').mockResolvedValue(false)
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
})
const asset = await prisma.asset.create({
data: {
name: 'robot.glb',
type: AssetType.file,
project: { connect: { id: projectId } },
parent: { connect: { id: parentId } },
status: AssetStatus.uploading,
storageKey: {
connectOrCreate: {
where: { key: 'test-key-3d-2' },
create: { key: 'test-key-3d-2' },
},
},
mediaType: 'model/gltf-binary',
},
})
await uploadService.confirmFileUpload(userId, task.id, { fileId: asset.id })
const updatedAsset = await prisma.asset.findUnique({ where: { id: asset.id } })
expect(updatedAsset?.status).toBe(AssetStatus.processed)
const workflowTask = await prisma.workflowTask.findFirst({
where: { assetId: asset.id, type: WorkflowTaskType.transcode_3d },
})
expect(workflowTask).toBeNull()
})
it('should confirm file upload and resolve empty mediaType using Bun resolver for audio', async () => {
const task = await prisma.task.create({
data: { creatorId: userId, total: 1, uploaded: 0, type: 'upload' },
+18 -1
View File
@@ -14,10 +14,11 @@ import {
S3SignResponse,
TaskInfo,
} from '@shumai/dtos'
import { ImageTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
import { ImageTranscoder, ModelTranscoder, PdfTranscoder, VideoTranscoder } from '@shumai/transcode'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { ulid } from 'ulid'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { getProxyType, isHtmlDocument, isOfficeDocument } from '@shumai/core/src/utils/mime'
import { logger } from '@shumai/core/src/logger'
@@ -323,6 +324,7 @@ export class UploadService {
const isImage = proxyType === 'image'
const isAudio = proxyType === 'audio'
const isPdf = proxyType === 'pdf'
const is3D = proxyType === '3d'
if (!proxyType) {
await tx.asset.update({
@@ -376,6 +378,21 @@ export class UploadService {
.withSprite()
.withPoster()
.submit()
} else if (is3D) {
const turntableAvailable = await turntableService.isAvailable(team.id)
if (!turntableAvailable) {
await tx.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
return
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await new ModelTranscoder(tx as any, asset.id, team.id, projectId)
.withSprite()
.withPoster()
.submit()
}
}
}
+18
View File
@@ -126,6 +126,24 @@ describe('getProxyType', () => {
expect(getProxyType(null, 'slides.pptx')).toBe('pdf')
})
it('should detect 3d proxyType for supported 3D models', () => {
expect(getProxyType('model/gltf-binary', 'model.glb')).toBe('3d')
expect(getProxyType('model/gltf+json', 'model.gltf')).toBe('3d')
expect(getProxyType(null, 'model.glb')).toBe('3d')
expect(getProxyType(null, 'model.gltf')).toBe('3d')
expect(getProxyType(null, 'character.fbx')).toBe('3d')
expect(getProxyType('model/obj', 'mesh.obj')).toBe('3d')
expect(getProxyType(null, 'mesh.obj')).toBe('3d')
expect(getProxyType('model/stl', 'part.stl')).toBe('3d')
expect(getProxyType(null, 'part.stl')).toBe('3d')
expect(getProxyType(null, 'scene.usd')).toBe('3d')
expect(getProxyType(null, 'scene.usda')).toBe('3d')
expect(getProxyType(null, 'scene.usdc')).toBe('3d')
expect(getProxyType('model/vnd.usdz+zip', 'scene.usdz')).toBe('3d')
expect(getProxyType('model/vnd.collada+xml', 'model.dae')).toBe('3d')
expect(getProxyType(null, 'MODEL.GLB')).toBe('3d')
})
it('should return null for unsupported files', () => {
expect(getProxyType('application/zip', 'archive.zip')).toBeNull()
expect(getProxyType(null, 'unknown.bin')).toBeNull()
+40 -1
View File
@@ -1,6 +1,41 @@
import { isRawImage } from './raw'
export type ProxyType = 'image' | 'video' | 'audio' | 'pdf'
export type ProxyType = 'image' | 'video' | 'audio' | 'pdf' | '3d'
export function is3dModel(mediaType?: string | null, filename?: string | null): boolean {
const lowerMediaType = mediaType?.toLowerCase() || ''
const lowerFilename = filename?.toLowerCase() || ''
const modelExtensions = [
'.glb',
'.gltf',
'.usd',
'.usda',
'.usdc',
'.usdz',
'.fbx',
'.obj',
'.stl',
'.dae',
]
if (modelExtensions.some((ext) => lowerFilename.endsWith(ext))) {
return true
}
if (
lowerMediaType.startsWith('model/') ||
lowerMediaType === 'model/gltf-binary' ||
lowerMediaType === 'model/gltf+json' ||
lowerMediaType === 'model/obj' ||
lowerMediaType === 'model/stl' ||
lowerMediaType === 'model/vnd.usdz+zip' ||
lowerMediaType === 'model/vnd.collada+xml'
) {
return true
}
return false
}
export function isOfficeDocument(mediaType?: string | null, filename?: string | null): boolean {
const lowerMediaType = mediaType?.toLowerCase() || ''
@@ -97,6 +132,10 @@ export function getProxyType(
return 'pdf'
}
if (is3dModel(mediaType, filename)) {
return '3d'
}
return null
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/db",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "WorkflowTaskType" ADD VALUE 'transcode_3d';
+1
View File
@@ -121,6 +121,7 @@ enum WorkflowTaskType {
transcode_screenshot
transcode_image_annotation
transcode_watermark
transcode_3d
ai_metadata_autofill
chat
ai_embedding
+1
View File
@@ -150,6 +150,7 @@ export const WorkflowTaskType = {
transcode_screenshot: 'transcode_screenshot',
transcode_image_annotation: 'transcode_image_annotation',
transcode_watermark: 'transcode_watermark',
transcode_3d: 'transcode_3d',
ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat',
ai_embedding: 'ai_embedding',
File diff suppressed because one or more lines are too long
+9 -2
View File
@@ -103,8 +103,15 @@ declare global {
replyTo?: string
}
export interface TurntableSettings {
url?: string
username?: string
password?: string
}
export interface Settings {
transcode?: TranscodeSettings
turntable?: TurntableSettings
mediaGeneration?: MediaGenerationSettings
appearance?: AppearanceSettings
emailNotification?: EmailNotificationSettings
@@ -196,7 +203,7 @@ declare global {
duration: number
filesize: number
frames: number
proxyType?: 'image' | 'video' | 'audio' | 'pdf'
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d'
imageTranscodes: ImageTranscode[]
videoTranscodes: VideoTranscode[]
videoPreview?: VideoTranscode
@@ -530,7 +537,7 @@ declare global {
key: string
sizeByte: number
contentType?: string | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
}
export type KanbanCommentAttachmentList = KanbanCommentAttachment[]
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/dtos",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+4 -4
View File
@@ -14,7 +14,7 @@ export const assetInfoPaginatedListSchema = z.object({
export type AssetInfoPaginatedList = z.infer<typeof assetInfoPaginatedListSchema>
export const previewInfoSchema = z.object({
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
thumbnailUrl: z.string().optional(),
originalHeight: z.number().optional(),
originalWidth: z.number().optional(),
@@ -76,7 +76,7 @@ export const assetInfoSchema = z.object({
type: z.string(),
targetType: z.string().optional().nullable(),
status: z.string(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
latestChildren: z.array(childPreviewSchema).optional(),
preview: previewInfoSchema.nullable().optional(),
createdAt: z.string(),
@@ -143,7 +143,7 @@ export const assetInfoSchema = z.object({
.optional(),
})
.optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
metadata: mediaMetadataSchema.optional(),
error: z.string().optional(),
})
@@ -233,7 +233,7 @@ export const attachmentInfoSchema = z.object({
id: z.string(),
assetId: z.string(),
url: z.string(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
})
export type AttachmentInfo = z.infer<typeof attachmentInfoSchema>
+3 -3
View File
@@ -7,7 +7,7 @@ export const kanbanAttachmentPayloadSchema = z.object({
key: z.string(),
sizeByte: z.number(),
contentType: z.string().nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
})
export type KanbanAttachmentPayload = z.infer<typeof kanbanAttachmentPayloadSchema>
@@ -17,7 +17,7 @@ export const kanbanAttachmentInfoSchema = z.object({
sizeByte: z.number(),
contentType: z.string().nullable().optional(),
url: z.string(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
})
export type KanbanAttachmentInfo = z.infer<typeof kanbanAttachmentInfoSchema>
@@ -28,7 +28,7 @@ export const postKanbanAttachmentResponseSchema = z.object({
sizeByte: z.number(),
contentType: z.string().nullable().optional(),
uploadUrl: z.string(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
})
export type PostKanbanAttachmentResponse = z.infer<typeof postKanbanAttachmentResponseSchema>
+1 -1
View File
@@ -92,7 +92,7 @@ export const kanbanTaskAssetInfoSchema = z.object({
id: z.string(),
name: z.string(),
type: z.string(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
thumbnailUrl: z.string().nullable().optional(),
path: z.string(),
creator: kanbanUserInfoSchema.nullable().optional(),
+1 -1
View File
@@ -18,7 +18,7 @@ export type EntityInfo = z.infer<typeof entityInfoSchema>
export const assetPreviewSchema = z.object({
id: z.string().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
proxyType: z.enum(['image', 'video', 'audio', 'pdf', '3d']).nullable().optional(),
name: z.string().optional(),
preview: z.string().optional(),
thumbnailUrl: z.string().optional(),
+16
View File
@@ -142,6 +142,21 @@ export const updateTeamSettingsRequestSchema = z.union([
])
export type UpdateTeamSettingsRequest = z.infer<typeof updateTeamSettingsRequestSchema>
export const turntableSettingsResponseSchema = z.object({
url: z.string().optional(),
username: z.string().optional(),
hasPassword: z.boolean(),
isEnvConfigured: z.boolean(),
})
export type TurntableSettingsResponse = z.infer<typeof turntableSettingsResponseSchema>
export const updateTurntableSettingsRequestSchema = z.object({
url: z.string().optional(),
username: z.string().optional(),
password: z.string().optional(),
})
export type UpdateTurntableSettingsRequest = z.infer<typeof updateTurntableSettingsRequestSchema>
export interface TeamAppearanceSettings {
hideAgent?: boolean
}
@@ -155,6 +170,7 @@ export interface TeamSettingsResponse {
hlsEnabled?: boolean
hlsResolutions?: HlsResolutionLadder[]
}
turntable?: TurntableSettingsResponse
appearance?: TeamAppearanceSettings
semanticSearchEnabled?: boolean
[key: string]: unknown
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/e2e",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"dependencies": {
+206
View File
@@ -0,0 +1,206 @@
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { prisma, AssetStatus } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { workflowService, TaskQueueTranscode } from '@shumai/workflow-core'
import { initTranscodeWorkflows } from '@shumai/transcode'
import { s3Service } from '@shumai/core/src/s3/s3'
import { fileURLToPath } from 'url'
import * as path from 'path'
import * as fs from 'fs'
const currentDir = path.dirname(fileURLToPath(import.meta.url))
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
const fixturesDir = path.resolve(currentDir, '../fixtures')
describe.each(['local', 'temporal'] as const)(
'Workflow E2E - 3D Asset Transcode (executor: %s)',
(mode) => {
setupTestDbHooks()
let transcodeWorkerPromise: Promise<void> | null = null
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mockTurntableServer: any = null
beforeAll(async () => {
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-3d'
const smallPngBuffer = fs.readFileSync(path.join(fixturesDir, 'small.png'))
const smallMp4Buffer = fs.readFileSync(path.join(fixturesDir, 'small.mp4'))
mockTurntableServer = Bun.serve({
port: 0,
fetch(req) {
const url = new URL(req.url)
if (url.pathname === '/version') {
return Response.json({ version: '1.0.0', runtime: 'bun', blender: '5.2.0' })
}
if (url.pathname === '/v1/files' && req.method === 'POST') {
return Response.json({ id: 'f_input3d', name: 'model.glb', size: 100 }, { status: 201 })
}
if (url.pathname === '/v1/render' && req.method === 'POST') {
return Response.json(
{
taskId: 't_render3d',
status: 'completed',
poster: {
fileId: 'f_poster3d',
size: smallPngBuffer.length,
contentType: 'image/png',
width: 1080,
height: 1080,
},
metadata: { format: 'glb' },
},
{ status: 201 },
)
}
if (url.pathname === '/v1/render/tasks/t_render3d') {
if (req.method === 'DELETE') {
return Response.json({ ok: true })
}
return Response.json({
taskId: 't_render3d',
status: 'completed',
posterFileId: 'f_poster3d',
video: {
fileId: 'f_video3d',
size: smallMp4Buffer.length,
contentType: 'video/mp4',
width: 1080,
height: 1080,
},
})
}
if (url.pathname === '/v1/files/f_poster3d') {
return new Response(smallPngBuffer, {
headers: { 'Content-Type': 'image/png' },
})
}
if (url.pathname === '/v1/files/f_video3d') {
return new Response(smallMp4Buffer, {
headers: { 'Content-Type': 'video/mp4' },
})
}
return new Response('Not Found', { status: 404 })
},
})
process.env.TURNTABLE_RENDERER_URL = `http://localhost:${mockTurntableServer.port}`
workflowService.setExecutorType(mode)
initTranscodeWorkflows()
if (mode === 'temporal') {
console.log('Starting background worker for transcode Temporal E2E tests...')
transcodeWorkerPromise = workflowService.startWorkers(TaskQueueTranscode, {
workflowsPath: transcodeWorkflowsPath,
})
await new Promise((resolve) => setTimeout(resolve, 2000))
} else {
console.log('Starting local workflow service polling...')
workflowService.start()
}
}, 120000)
afterAll(async () => {
if (mode === 'temporal') {
console.log('Shutting down Temporal workers...')
await workflowService.shutdownWorkers()
await Promise.all([transcodeWorkerPromise].filter(Boolean))
}
workflowService.close()
vi.restoreAllMocks()
if (mockTurntableServer) {
mockTurntableServer.stop()
}
delete process.env.TURNTABLE_RENDERER_URL
try {
console.log('Cleaning up E2E storage files...')
await s3Service.deletePrefix('shumai-e2e-test-bucket-3d', '')
} catch (err) {
console.error('Failed to clean up E2E storage folder:', err)
}
}, 120000)
it('should process 3D model transcode workflow task', async () => {
const team = await prisma.team.create({
data: { name: 'E2E 3D Transcode Team' },
})
const project = await prisma.project.create({
data: { name: 'E2E 3D Transcode Project', teamId: team.id },
})
const storageKey = await prisma.storageKey.create({
data: {
key: 'projects/e2e/model.glb',
status: 'active',
},
})
const asset = await prisma.asset.create({
data: {
name: 'model.glb',
type: 'file',
status: 'uploaded',
mediaType: 'model/gltf-binary',
projectId: project.id,
storageKeyId: storageKey.id,
},
})
const dummyGlbBuffer = Buffer.from('dummy glb content')
await s3Service.putObject(
'shumai-e2e-test-bucket-3d',
'projects/e2e/model.glb',
dummyGlbBuffer,
dummyGlbBuffer.length,
'model/gltf-binary',
)
const task = await prisma.workflowTask.create({
data: {
type: 'transcode_3d',
status: 'pending',
assetId: asset.id,
projectId: project.id,
teamId: team.id,
payload: {
projectId: project.id,
transcode: {
poster: true,
sprite: true,
},
},
},
})
console.log(
`Submitted E2E 3D Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
)
const completedTask = await workflowService.executeWait(task, 60000)
expect(completedTask.status).toBe('completed')
const updatedAsset = await prisma.asset.findUnique({
where: { id: asset.id },
})
expect(updatedAsset?.status).toBe(AssetStatus.processed)
const mediaInfo = updatedAsset?.media as unknown as {
proxyType?: string
videoPreview?: { key: string }
poster?: { key: string }
sprite?: { key: string }
}
expect(mediaInfo).toBeDefined()
expect(mediaInfo.proxyType).toBe('3d')
expect(mediaInfo.videoPreview?.key).toBe('projects/e2e/turntable.mp4')
expect(mediaInfo.poster?.key).toBe('projects/e2e/poster.webp')
expect(mediaInfo.sprite?.key).toBe('projects/e2e/sprite.webp')
}, 90000)
},
)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/tableprinter",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/transcode",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -0,0 +1,210 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render3dModelActivity, generate3dSpriteActivity } from './transcode'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core/src/transcode/transcode'
import * as fs from 'fs'
vi.mock('@shumai/core/src/turntable/turntable', () => ({
turntableService: {
uploadFile: vi.fn(),
startRender: vi.fn(),
getTaskStatus: vi.fn(),
downloadFile: vi.fn(),
deleteTask: vi.fn(),
deleteFile: vi.fn(),
},
}))
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
putObject: vi.fn(),
},
}))
vi.mock('@shumai/core/src/transcode/transcode', () => ({
transcodeService: {
convertImageToWebp: vi.fn(),
generate3dSprite: vi.fn(),
},
}))
vi.mock('@shumai/core/src/asset/asset', () => ({
assetService: {
isAssetPurging: vi.fn().mockResolvedValue(false),
},
}))
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('fs')>()
return {
...actual,
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
}
})
describe('3D Transcode Activities', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(fs.readFileSync).mockReturnValue(Buffer.from('mock-bytes'))
vi.mocked(transcodeService.convertImageToWebp).mockResolvedValue(Buffer.from('webp-bytes'))
vi.mocked(transcodeService.generate3dSprite).mockResolvedValue()
vi.mocked(s3Service.putObject).mockResolvedValue({} as never)
vi.mocked(turntableService.deleteTask).mockResolvedValue(true)
})
describe('render3dModelActivity', () => {
it('uploads file, starts render, polls until complete, and uploads to S3', async () => {
vi.mocked(turntableService.uploadFile).mockResolvedValue({
id: 'f_input',
name: 'model.glb',
size: 1024,
})
vi.mocked(turntableService.startRender).mockResolvedValue({
taskId: 'task_render_1',
status: 'queued',
poster: {
fileId: 'f_poster',
contentType: 'image/png',
width: 1080,
height: 1080,
size: 5000,
},
metadata: { format: 'glb', vertices: 120 },
})
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
taskId: 'task_render_1',
status: 'completed',
createdAt: new Date().toISOString(),
video: {
fileId: 'f_video',
contentType: 'video/mp4',
width: 1080,
height: 1080,
size: 1000,
},
})
vi.mocked(turntableService.downloadFile).mockResolvedValue(Buffer.from('downloaded-data'))
const res = await render3dModelActivity({
taskId: 'wf-task-1',
teamId: 'team-1',
assetId: 'asset-1',
assetKey: 'files/asset-1/model.glb',
filePath: '/tmp/model.glb',
filename: 'model.glb',
targetVideoKey: 'files/asset-1/turntable.mp4',
targetPosterKey: 'files/asset-1/poster.webp',
})
expect(turntableService.uploadFile).toHaveBeenCalledWith(
'/tmp/model.glb',
'model.glb',
'team-1',
)
expect(turntableService.startRender).toHaveBeenCalledWith('f_input', {}, 'team-1')
expect(turntableService.getTaskStatus).toHaveBeenCalledWith('task_render_1', 'team-1')
expect(turntableService.downloadFile).toHaveBeenCalledWith(
'f_video',
'/tmp/turntable.mp4',
'team-1',
)
expect(turntableService.downloadFile).toHaveBeenCalledWith('f_poster', undefined, 'team-1')
expect(transcodeService.convertImageToWebp).toHaveBeenCalledWith(expect.any(Buffer))
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'files/asset-1/turntable.mp4',
expect.any(Buffer),
expect.any(Number),
'video/mp4',
)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'files/asset-1/poster.webp',
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_1', 'team-1')
expect(res.modelMetadata).toEqual({ format: 'glb', vertices: 120 })
expect(res.videoFilePath).toBe('/tmp/turntable.mp4')
expect(res.posterFilePath).toBe('/tmp/poster.webp')
})
it('throws ApplicationFailure when render fails on turntable-renderer', async () => {
vi.mocked(turntableService.uploadFile).mockResolvedValue({
id: 'f_input',
name: 'model.glb',
size: 1024,
})
vi.mocked(turntableService.startRender).mockResolvedValue({
taskId: 'task_render_2',
status: 'queued',
poster: {
fileId: 'f_poster',
contentType: 'image/png',
width: 1080,
height: 1080,
size: 5000,
},
})
vi.mocked(turntableService.getTaskStatus).mockResolvedValue({
taskId: 'task_render_2',
status: 'failed',
createdAt: new Date().toISOString(),
error: {
code: 'render_failed',
message: 'Blender failed to import model',
},
})
await expect(
render3dModelActivity({
taskId: 'wf-task-2',
teamId: 'team-1',
assetId: 'asset-1',
assetKey: 'files/asset-1/model.glb',
filePath: '/tmp/model.glb',
filename: 'model.glb',
targetVideoKey: 'files/asset-1/turntable.mp4',
targetPosterKey: 'files/asset-1/poster.webp',
}),
).rejects.toThrow('Blender failed to import model')
expect(turntableService.deleteTask).toHaveBeenCalledWith('task_render_2', 'team-1')
})
})
describe('generate3dSpriteActivity', () => {
it('generates 3d sprite sheet and uploads to S3', async () => {
const res = await generate3dSpriteActivity({
taskId: 'wf-task-3',
assetKey: 'files/asset-1/model.glb',
videoFilePath: '/tmp/turntable.mp4',
spriteKey: 'files/asset-1/sprite.webp',
})
expect(transcodeService.generate3dSprite).toHaveBeenCalledWith(
'/tmp/turntable.mp4',
'/tmp/sprite.webp',
undefined,
)
expect(s3Service.putObject).toHaveBeenCalledWith(
'shumai',
'files/asset-1/sprite.webp',
expect.any(Buffer),
expect.any(Number),
'image/webp',
)
expect(res.spriteKey).toBe('files/asset-1/sprite.webp')
})
})
})
@@ -998,6 +998,24 @@ describe('Transcode Activities', () => {
).rejects.toThrowError(/Image transcoding failed/)
})
it('should throw non-retryable ApplicationFailure when transcodeImageActivity fails with dcraw error', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
vi.mocked(transcodeService.transcodeImage).mockRejectedValue(
new Error('dcraw_emu failed to decode RAW file'),
)
await expect(
transcodeImageActivity({
assetKey: 'photo.cr2',
filePath: '/tmp/photo.cr2',
imageSpec: { width: 800, height: 600, quality: 90, format: 'webp' },
}),
).rejects.toMatchObject({
message: expect.stringContaining('Image transcoding failed'),
nonRetryable: true,
})
})
it('should throw non-retryable ApplicationFailure when generateSpriteActivity fails with error', async () => {
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
vi.mocked(transcodeService.generateSprite).mockRejectedValue(new Error('FFmpeg failed'))
@@ -9,6 +9,7 @@ import {
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { parseCsvContent } from '@shumai/core/src/transcode/transcode'
import { resolutionToDimensions } from '../workflows/transcode-utils'
import {
@@ -334,6 +335,7 @@ export interface VideoActivityParams {
sourceColorTransfer?: string
sourceColorPrimaries?: string
sourceColorSpace?: string
sourceRotation?: number
streamIndex?: number
audioStreamIndex?: number
}
@@ -397,6 +399,7 @@ export async function transcodeVideoActivity(
sourceColorTransfer: params.sourceColorTransfer,
sourceColorPrimaries: params.sourceColorPrimaries,
sourceColorSpace: params.sourceColorSpace,
sourceRotation: params.sourceRotation,
streamIndex: params.streamIndex,
audioStreamIndex: params.audioStreamIndex,
})
@@ -464,6 +467,7 @@ export interface HlsActivityParams {
sourceColorTransfer?: string
sourceColorPrimaries?: string
sourceColorSpace?: string
sourceRotation?: number
streamIndex?: number
audioStreamIndex?: number
}
@@ -532,6 +536,7 @@ export async function transcodeHlsActivity(params: HlsActivityParams): Promise<P
sourceColorTransfer: params.sourceColorTransfer,
sourceColorPrimaries: params.sourceColorPrimaries,
sourceColorSpace: params.sourceColorSpace,
sourceRotation: params.sourceRotation,
streamIndex: params.streamIndex,
audioStreamIndex: params.audioStreamIndex,
})
@@ -772,6 +777,8 @@ export async function transcodeImageActivity(
lowerMsg.includes('imagemagick') ||
lowerMsg.includes('magick') ||
lowerMsg.includes('convert') ||
lowerMsg.includes('dcraw') ||
lowerMsg.includes('raw') ||
lowerMsg.includes('spawn') ||
lowerMsg.includes('format')
) {
@@ -1545,3 +1552,215 @@ export async function deleteS3ObjectActivity(params: { key: string }): Promise<v
const bucket = process.env.S3_BUCKET || 'shumai'
await s3Service.deleteObject(bucket, params.key)
}
export interface Render3dModelActivityParams {
taskId: string
teamId: string
assetId: string
assetKey: string
filePath: string
filename: string
targetVideoKey: string
targetPosterKey: string
}
export interface Render3dModelActivityResult {
videoFilePath: string
posterFilePath: string
modelMetadata?: Record<string, unknown>
}
export async function render3dModelActivity(
params: Render3dModelActivityParams,
): Promise<Render3dModelActivityResult> {
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
throw ApplicationFailure.create({
message: 'Render cancelled',
nonRetryable: true,
})
}
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = path.dirname(params.filePath)
const videoFilePath = path.join(tmpDir, 'turntable.mp4')
const posterFilePath = path.join(tmpDir, 'poster.webp')
let renderTaskId: string | undefined
try {
const uploadResult = await turntableService.uploadFile(
params.filePath,
params.filename,
params.teamId,
)
const fileId = uploadResult.id
if (signal?.aborted) {
await turntableService.deleteFile(fileId, params.teamId).catch(() => {})
throw ApplicationFailure.create({
message: 'Render cancelled',
nonRetryable: true,
})
}
const startResult = await turntableService.startRender(fileId, {}, params.teamId)
renderTaskId = startResult.taskId
let finishedStatus: 'completed' | 'failed' | null = null
let taskRecord: Awaited<ReturnType<typeof turntableService.getTaskStatus>> | null = null
for (let i = 0; i < 360; i++) {
if (signal?.aborted) {
if (renderTaskId) {
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
}
throw ApplicationFailure.create({
message: 'Render cancelled',
nonRetryable: true,
})
}
if (i > 0) {
await new Promise((resolve) => setTimeout(resolve, 5000))
}
taskRecord = await turntableService.getTaskStatus(renderTaskId, params.teamId)
if (taskRecord.status === 'completed') {
finishedStatus = 'completed'
break
}
if (taskRecord.status === 'failed') {
finishedStatus = 'failed'
break
}
}
if (finishedStatus !== 'completed' || !taskRecord) {
const errMsg =
finishedStatus === 'failed'
? taskRecord?.error?.message || '3D render failed on turntable server'
: '3D render timed out on turntable server'
throw ApplicationFailure.create({
message: errMsg,
nonRetryable: true,
})
}
const videoFileId = taskRecord.video?.fileId
if (!videoFileId) {
throw ApplicationFailure.create({
message: 'Video file ID missing from turntable render result',
nonRetryable: true,
})
}
const posterFileId = startResult.poster?.fileId
if (!posterFileId) {
throw ApplicationFailure.create({
message: 'Poster file ID missing from turntable render result',
nonRetryable: true,
})
}
const videoBuffer = await turntableService.downloadFile(
videoFileId,
videoFilePath,
params.teamId,
)
const posterBuffer = await turntableService.downloadFile(posterFileId, undefined, params.teamId)
const posterWebpBuffer = await transcodeService.convertImageToWebp(posterBuffer)
fs.writeFileSync(posterFilePath, posterWebpBuffer)
await ensureAssetNotPurging(params.assetKey)
await s3Service.putObject(
bucket,
params.targetVideoKey,
videoBuffer,
videoBuffer.length,
'video/mp4',
)
await s3Service.putObject(
bucket,
params.targetPosterKey,
posterWebpBuffer,
posterWebpBuffer.length,
'image/webp',
)
await turntableService.deleteTask(renderTaskId, params.teamId).catch((err) => {
logger.warn({ err, taskId: renderTaskId }, 'Failed to delete turntable task after completion')
})
renderTaskId = undefined
return {
videoFilePath,
posterFilePath,
modelMetadata: (startResult.metadata as Record<string, unknown>) || {},
}
} catch (err) {
if (renderTaskId) {
await turntableService.deleteTask(renderTaskId, params.teamId).catch(() => {})
}
if (err instanceof ApplicationFailure) {
throw err
}
const errMsg = err instanceof Error ? err.message : String(err)
throw ApplicationFailure.create({
message: `Failed to render 3D model: ${errMsg}`,
nonRetryable: true,
})
}
}
export interface Generate3dSpriteActivityParams {
taskId: string
assetKey: string
videoFilePath: string
spriteKey: string
}
export async function generate3dSpriteActivity(
params: Generate3dSpriteActivityParams,
): Promise<{ spriteKey: string }> {
const signal = getActivityCancellationSignal(params.taskId)
if (signal?.aborted) {
throw ApplicationFailure.create({
message: 'Sprite generation cancelled',
nonRetryable: true,
})
}
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = path.dirname(params.videoFilePath)
const spriteFilePath = path.join(tmpDir, 'sprite.webp')
try {
await transcodeService.generate3dSprite(params.videoFilePath, spriteFilePath, signal)
const spriteBuffer = fs.readFileSync(spriteFilePath)
await ensureAssetNotPurging(params.assetKey)
await s3Service.putObject(
bucket,
params.spriteKey,
spriteBuffer,
spriteBuffer.length,
'image/webp',
)
return { spriteKey: params.spriteKey }
} catch (err) {
if (err instanceof ApplicationFailure) {
throw err
}
const errMsg = err instanceof Error ? err.message : String(err)
throw ApplicationFailure.create({
message: `Failed to generate 3D sprite: ${errMsg}`,
nonRetryable: true,
})
}
}
+3
View File
@@ -9,6 +9,7 @@ import { renderPdfPagesWorkflow } from './workflows/render-pdf-pages'
import { takeVideoScreenshotsWorkflow } from './workflows/take-video-screenshots'
import { overlayImageAnnotationWorkflow } from './workflows/overlay-image-annotation'
import { transcodeWatermarkWorkflow } from './workflows/transcode-watermark'
import { transcode3dWorkflow } from './workflows/transcode-3d'
import { transcodeMedia } from './workflows/transcode'
export function initTranscodeWorkflows() {
@@ -16,6 +17,7 @@ export function initTranscodeWorkflows() {
registerWorkflow(WorkflowTaskType.transcode_video, transcodeVideoWorkflow)
registerWorkflow(WorkflowTaskType.transcode_image, transcodeImageWorkflow)
registerWorkflow(WorkflowTaskType.transcode_pdf, transcodePdfWorkflow)
registerWorkflow(WorkflowTaskType.transcode_3d, transcode3dWorkflow)
registerWorkflow(WorkflowTaskType.transcode_pdf_pages, renderPdfPagesWorkflow)
registerWorkflow(WorkflowTaskType.transcode_screenshot, takeVideoScreenshotsWorkflow)
registerWorkflow(WorkflowTaskType.transcode_image_annotation, overlayImageAnnotationWorkflow)
@@ -26,6 +28,7 @@ export function initTranscodeWorkflows() {
export * from './transcoder'
export * from './workflows/transcode'
export * from './workflows/transcode-3d'
export * from './workflows/transcode-watermark'
export * from './activities/transcode'
export * from './activities/watermark'
+38
View File
@@ -151,3 +151,41 @@ export class PdfTranscoder {
return task.id
}
}
export class ModelTranscoder {
private spec: PrismaJson.TaskSpec = {}
constructor(
private readonly db: TransactionClient,
private readonly assetId: string,
private readonly teamId: string,
private readonly projectId: string,
) {}
withSprite(): this {
this.spec.sprite = true
return this
}
withPoster(): this {
this.spec.poster = true
return this
}
async submit(): Promise<string> {
const task = await this.db.workflowTask.create({
data: {
assetId: this.assetId,
teamId: this.teamId,
projectId: this.projectId,
type: WorkflowTaskType.transcode_3d,
status: WorkflowTaskStatus.pending,
payload: {
projectId: this.projectId,
transcode: this.spec,
},
},
})
return task.id
}
}
@@ -0,0 +1,214 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { transcode3dWorkflow } from './transcode-3d'
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType, AssetStatus } from '@shumai/db'
import * as workflowUtils from '@shumai/workflow-core'
vi.mock('@shumai/workflow-core', async (importOriginal) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const actual = (await importOriginal()) as any
return {
...actual,
getActivities: vi.fn(),
executeActivity: vi.fn(),
sleep: vi.fn(),
}
})
describe('transcode3dWorkflow', () => {
const mockActivities = {
updateTaskStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateTaskStatusActivity',
}),
updateAssetStatusActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetStatusActivity',
}),
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
render3dModelActivity: Object.assign(vi.fn(), { _activityName: 'render3dModelActivity' }),
generate3dSpriteActivity: Object.assign(vi.fn(), { _activityName: 'generate3dSpriteActivity' }),
updateAssetMediaActivity: Object.assign(vi.fn(), {
_activityName: 'updateAssetMediaActivity',
}),
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getTranscodeWorkerQueueActivity',
}),
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
_activityName: 'downloadMediaToTmpActivity',
}),
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
_activityName: 'createEmbeddingTaskIfEnabledActivity',
}),
createAutofillTaskIfEnabledActivity: Object.assign(vi.fn(), {
_activityName: 'createAutofillTaskIfEnabledActivity',
}),
}
beforeEach(() => {
vi.clearAllMocks()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(workflowUtils.executeActivity as any).mockImplementation(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(_queue: string, fn: any, ...args: any[]) => {
if (typeof fn !== 'function') {
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
}
return fn(...args)
},
)
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
filePath: '/tmp/model.glb',
tmpDir: '/tmp',
})
})
it('should process 3D model transcode successfully', async () => {
const task: WorkflowTask = {
id: 'task-3d',
assetId: 'asset-3d',
type: WorkflowTaskType.transcode_3d,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
transcode: {
sprite: true,
poster: true,
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid-3d',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-3d',
name: 'robot.glb',
storageKey: { key: 'files/asset-3d/robot.glb' },
mediaType: 'model/gltf-binary',
sizeByte: BigInt(1024),
})
mockActivities.render3dModelActivity.mockResolvedValue({
videoFilePath: '/tmp/turntable.mp4',
posterFilePath: '/tmp/poster.webp',
modelMetadata: { format: 'glb' },
})
mockActivities.generate3dSpriteActivity.mockResolvedValue({
spriteKey: 'files/asset-3d/sprite.webp',
})
await transcode3dWorkflow(task)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-3d',
status: AssetStatus.processing,
})
expect(mockActivities.render3dModelActivity).toHaveBeenCalledWith({
taskId: 'task-3d',
teamId: 'team-1',
assetId: 'asset-3d',
assetKey: 'files/asset-3d/robot.glb',
filePath: '/tmp/model.glb',
filename: 'robot.glb',
targetVideoKey: 'files/asset-3d/turntable.mp4',
targetPosterKey: 'files/asset-3d/poster.webp',
})
expect(mockActivities.generate3dSpriteActivity).toHaveBeenCalledWith({
taskId: 'task-3d',
assetKey: 'files/asset-3d/robot.glb',
videoFilePath: '/tmp/turntable.mp4',
spriteKey: 'files/asset-3d/sprite.webp',
})
expect(mockActivities.updateAssetMediaActivity).toHaveBeenCalledWith(
expect.objectContaining({
assetId: 'asset-3d',
mediaInfo: expect.objectContaining({
proxyType: '3d',
duration: 4,
frames: 24,
poster: { key: 'files/asset-3d/poster.webp' },
sprite: expect.objectContaining({ key: 'files/asset-3d/sprite.webp' }),
}),
}),
)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith({
assetId: 'asset-3d',
status: AssetStatus.processed,
})
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith(
expect.objectContaining({
taskId: 'task-3d',
status: WorkflowTaskStatus.completed,
}),
)
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
tmpDir: '/tmp',
})
})
it('should fail task when render activity fails', async () => {
const task: WorkflowTask = {
id: 'task-3d-fail',
assetId: 'asset-3d-fail',
type: WorkflowTaskType.transcode_3d,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid-3d-fail',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-3d-fail',
name: 'corrupt.glb',
storageKey: { key: 'files/corrupt.glb' },
mediaType: 'model/gltf-binary',
sizeByte: BigInt(512),
})
mockActivities.render3dModelActivity.mockRejectedValue(new Error('Renderer crashed'))
await expect(transcode3dWorkflow(task)).rejects.toThrow('Renderer crashed')
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith(
expect.objectContaining({
taskId: 'task-3d-fail',
status: WorkflowTaskStatus.failed,
}),
)
expect(mockActivities.updateAssetStatusActivity).toHaveBeenCalledWith(
expect.objectContaining({
assetId: 'asset-3d-fail',
status: AssetStatus.failed,
}),
)
})
})
@@ -0,0 +1,146 @@
import type { WorkflowTask } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { executeActivity, getActivities } from '@shumai/workflow-core'
import {
getWorkerQueueAndStartTask,
fetchAssetWithKey,
completeTask,
failTask,
cleanupTmpDir,
} from './common'
export async function transcode3dWorkflow(task: WorkflowTask): Promise<void> {
let tmpDir: string | undefined
let workerQueue = ''
let mediaProcessed = false
try {
workerQueue = await getWorkerQueueAndStartTask(task)
const {
updateAssetStatusActivity,
downloadMediaToTmpActivity,
render3dModelActivity,
generate3dSpriteActivity,
updateAssetMediaActivity,
createEmbeddingTaskIfEnabledActivity,
createAutofillTaskIfEnabledActivity,
} = getActivities()
await executeActivity(workerQueue, updateAssetStatusActivity, {
assetId: task.assetId,
status: 'processing',
})
const { asset, key } = await fetchAssetWithKey(workerQueue, task.assetId)
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
assetKey: key,
})
const currentFilePath = download.filePath
tmpDir = download.tmpDir
const lastSlashIndex = key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
const videoKey = assetDir ? `${assetDir}/turntable.mp4` : 'turntable.mp4'
const posterKey = assetDir ? `${assetDir}/poster.webp` : 'poster.webp'
const spriteKey = assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp'
const renderResult = await executeActivity(workerQueue, render3dModelActivity, {
taskId: task.id,
teamId: task.teamId,
assetId: asset.id,
assetKey: key,
filePath: currentFilePath,
filename: asset.name || 'model.glb',
targetVideoKey: videoKey,
targetPosterKey: posterKey,
})
await executeActivity(workerQueue, generate3dSpriteActivity, {
taskId: task.id,
assetKey: key,
videoFilePath: renderResult.videoFilePath,
spriteKey,
})
const mediaInfo: PrismaJson.MediaInfo = {
duration: 4,
filesize: 0,
frames: 24,
proxyType: '3d',
imageTranscodes: [],
videoTranscodes: [
{
key: videoKey,
width: 1080,
height: 1080,
resolution: '1080p',
},
],
videoPreview: {
key: videoKey,
width: 1080,
height: 1080,
resolution: '1080p',
},
poster: {
key: posterKey,
},
sprite: {
key: spriteKey,
frames: 100,
tileX: 10,
tileY: 10,
},
finishedAt: new Date().toISOString(),
metadata: {
originalHeight: 1080,
originalWidth: 1080,
hasAudio: false,
duration: 4,
bitRate: 0,
frameRate: 6,
totalFrames: 24,
startTimecode: '00:00:00:00',
format: renderResult.modelMetadata ?? {},
},
original: {
key,
filesizeInBytes: Number(asset.sizeByte || 0),
codec: '',
},
}
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
await executeActivity(workerQueue, updateAssetStatusActivity, {
assetId: asset.id,
status: 'processed',
})
mediaProcessed = true
await executeActivity(workerQueue, createEmbeddingTaskIfEnabledActivity, {
assetId: asset.id,
teamId: task.teamId,
projectId: task.projectId,
})
await executeActivity(workerQueue, createAutofillTaskIfEnabledActivity, {
assetId: asset.id,
teamId: task.teamId,
projectId: task.projectId,
})
await completeTask(workerQueue, task.id)
} catch (err) {
console.error(`transcode3dWorkflow failed for task ${task.id}:`, err)
await failTask(workerQueue, task.id, err, mediaProcessed ? undefined : task.assetId)
throw err
} finally {
await cleanupTmpDir(workerQueue, tmpDir)
}
}
@@ -167,6 +167,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
sourceColorTransfer: metadata.colorTransfer,
sourceColorPrimaries: metadata.colorPrimaries,
sourceColorSpace: metadata.colorSpace,
sourceRotation: metadata.rotation ?? 0,
streamIndex: metadata.videoStreamIndex,
audioStreamIndex: metadata.audioStreamIndex,
})
@@ -197,6 +198,8 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
sourceColorTransfer: metadata.colorTransfer,
sourceColorPrimaries: metadata.colorPrimaries,
sourceColorSpace: metadata.colorSpace,
// rotation is undefined when the probed source has none
sourceRotation: metadata.rotation ?? 0,
streamIndex: metadata.videoStreamIndex,
audioStreamIndex: metadata.audioStreamIndex,
})
@@ -227,6 +230,7 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
sourceColorTransfer: metadata.colorTransfer,
sourceColorPrimaries: metadata.colorPrimaries,
sourceColorSpace: metadata.colorSpace,
sourceRotation: metadata.rotation ?? 0,
streamIndex: metadata.videoStreamIndex,
audioStreamIndex: metadata.audioStreamIndex,
})
@@ -47,5 +47,6 @@ export * from './render-pdf-pages'
export * from './take-video-screenshots'
export * from './overlay-image-annotation'
export * from './transcode-watermark'
export * from './transcode-3d'
export * from './common'
export * from './transcode-utils'
+1 -1
View File
@@ -60,7 +60,7 @@ interface BreadcrumbNavProps {
name?: string
type: 'file' | 'folder'
version?: number
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
}
isRootFolder: boolean
customTerminalBreadcrumb?: string
@@ -4,10 +4,10 @@ import { formatTime } from '../viewers/video/utils'
type FilePreviewItem = {
type?: string | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
preview?: {
mediaType?: string | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
spriteUrl?: string
thumbnailUrl?: string
originalWidth?: number
@@ -27,6 +27,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
const isVideo = proxyType === 'video'
const isAudio = proxyType === 'audio'
const isPdf = proxyType === 'pdf'
const is3D = proxyType === '3d'
const hasDuration = isVideo || isAudio
const duration = item.preview?.duration
const pageCount = item.preview?.pageCount
@@ -43,7 +44,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
) : null
const isMediaWithSprite =
(isVideo || isPdf) &&
(isVideo || isPdf || is3D) &&
item.preview?.spriteUrl &&
item.preview.thumbnailUrl &&
item.preview.originalWidth &&
@@ -445,6 +445,7 @@ export function TaskInfoForm({ teamId, task, canEdit = true }: TaskInfoFormProps
onAddAssets={(newAssets) => linkAssets(newAssets)}
onRemoveAsset={(assetId) => unlinkAsset(assetId)}
disabled={!canEdit}
linkable
/>
</div>
</div>
@@ -59,6 +59,15 @@ vi.mock('@dnd-kit/react', () => ({
KeyboardSensor: {},
}))
// Mock TanStack Router Link as a plain anchor
vi.mock('@tanstack/react-router', () => ({
Link: ({ children, to, ...props }: { children: React.ReactNode; to: string }) => (
<a href={to} {...props}>
{children}
</a>
),
}))
// Mock @dnd-kit/dom
vi.mock('@dnd-kit/dom', () => ({
PointerActivationConstraints: {
@@ -690,6 +699,58 @@ describe('Kanban UI Unit & Component Tests', () => {
fireEvent.click(removeButtons[0])
expect(onRemove).toHaveBeenCalledWith('asset-1')
})
it('does not link asset rows by default', () => {
render(
<TaskRelatedAssets
teamId="team-1"
assets={mockAssets}
onAddAssets={vi.fn()}
onRemoveAsset={vi.fn()}
/>,
)
expect(screen.queryAllByRole('link')).toHaveLength(0)
})
it('links files and folders to their project when linkable', () => {
const onRemove = vi.fn()
render(
<TaskRelatedAssets
teamId="team-1"
projectId="task-proj"
assets={[...mockAssets, { ...mockAssets[0], id: 'asset-3', projectId: null }]}
onAddAssets={vi.fn()}
onRemoveAsset={onRemove}
linkable
/>,
)
const links = screen.getAllByRole('link')
expect(links.map((link) => link.getAttribute('href'))).toEqual([
'/projects/proj-1/files/asset-1',
'/projects/proj-1/folders/asset-2',
// Falls back to the task's project when the asset has none
'/projects/task-proj/files/asset-3',
])
// The remove button stays outside the link
fireEvent.click(screen.getAllByTitle(/Unlink Asset|取消关联资产/i)[1])
expect(onRemove).toHaveBeenCalledWith('asset-2')
})
it('does not link assets when no project is known', () => {
render(
<TaskRelatedAssets
teamId="team-1"
assets={[{ ...mockAssets[0], projectId: null }]}
onAddAssets={vi.fn()}
onRemoveAsset={vi.fn()}
linkable
/>,
)
expect(screen.queryAllByRole('link')).toHaveLength(0)
})
})
describe('KanbanGoalSidebar component', () => {
@@ -1,4 +1,5 @@
import { useState } from 'react'
import { Link } from '@tanstack/react-router'
import { Button } from '@/ui/components/ui/button'
import { Separator } from '@/ui/components/ui/separator'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
@@ -6,6 +7,7 @@ import { m } from '@/ui/paraglide/messages.js'
import type { KanbanTaskAssetInfo } from '@shumai/dtos'
import { AssetPickerDialog } from './asset-picker-dialog'
import { Plus, X, Folder, File, Files } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
interface TaskRelatedAssetsProps {
teamId: string
@@ -14,6 +16,8 @@ interface TaskRelatedAssetsProps {
onAddAssets: (newAssets: KanbanTaskAssetInfo[]) => void
onRemoveAsset: (assetId: string) => void
disabled?: boolean
/** Make each row a link to the asset in its project. Off by default so unsaved drafts are not discarded. */
linkable?: boolean
}
export function TaskRelatedAssets({
@@ -23,6 +27,7 @@ export function TaskRelatedAssets({
onAddAssets,
onRemoveAsset,
disabled = false,
linkable = false,
}: TaskRelatedAssetsProps) {
const [isPickerOpen, setIsPickerOpen] = useState(false)
@@ -69,39 +74,62 @@ export function TaskRelatedAssets({
<div className="space-y-1.5 max-h-48 overflow-y-auto pr-1">
{assets.map((asset) => {
const isFolder = asset.type === 'folder'
const assetProjectId = asset.projectId || projectId
const assetHref =
linkable && assetProjectId
? `/projects/${assetProjectId}/${isFolder ? 'folders' : 'files'}/${asset.id}`
: null
const body = (
<>
{/* Thumbnail / Icon */}
<div className="w-7 h-7 rounded bg-muted border shrink-0 flex items-center justify-center overflow-hidden">
{asset.thumbnailUrl ? (
<img
src={asset.thumbnailUrl}
alt={asset.name}
className="w-full h-full object-cover"
/>
) : isFolder ? (
<Folder className="w-4 h-4 text-primary fill-primary/20" />
) : (
<File className="w-4 h-4 text-muted-foreground" />
)}
</div>
{/* Name & Path */}
<div className="flex-1 min-w-0">
<p
className={cn(
'font-medium truncate text-foreground leading-snug',
assetHref && 'group-hover:underline group-hover:text-primary',
)}
>
{asset.name}
</p>
<p className="text-[10px] text-muted-foreground truncate leading-none mt-0.5">
{asset.path || '/'}
</p>
</div>
</>
)
return (
<div
key={asset.id}
className="flex items-center justify-between gap-2 p-1.5 px-2 rounded-md bg-muted/40 hover:bg-muted/70 transition-colors text-xs border border-border/40"
>
{/* Left: Thumbnail & Names */}
<div className="flex items-center gap-2.5 min-w-0 flex-1">
{/* Thumbnail / Icon */}
<div className="w-7 h-7 rounded bg-muted border shrink-0 flex items-center justify-center overflow-hidden">
{asset.thumbnailUrl ? (
<img
src={asset.thumbnailUrl}
alt={asset.name}
className="w-full h-full object-cover"
/>
) : isFolder ? (
<Folder className="w-4 h-4 text-primary fill-primary/20" />
) : (
<File className="w-4 h-4 text-muted-foreground" />
)}
</div>
{/* Name & Path */}
<div className="flex-1 min-w-0">
<p className="font-medium truncate text-foreground leading-snug">
{asset.name}
</p>
<p className="text-[10px] text-muted-foreground truncate leading-none mt-0.5">
{asset.path || '/'}
</p>
</div>
</div>
{/* Left: Thumbnail & Names (links to the asset when linkable) */}
{assetHref ? (
<Link
to={assetHref}
title={asset.name}
className="group flex items-center gap-2.5 min-w-0 flex-1 rounded-sm cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{body}
</Link>
) : (
<div className="flex items-center gap-2.5 min-w-0 flex-1">{body}</div>
)}
{/* Right: Creator & Remove Button */}
<div className="flex items-center gap-2 shrink-0">
@@ -143,6 +143,12 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
params: { teamId: team.id },
search: { taskId: kanbanTask.id },
})
} else if (project?.id && asset?.id) {
//TODO: Perhaps it should be marked as read too when redirecting to it.
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId: project.id, fileId: asset.id },
})
}
}
@@ -0,0 +1,245 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { TurntableSettingsCard } from './TurntableSettingsCard'
import type { TurntableSettingsResponse } from '@shumai/dtos'
const mockGetSettings = vi.fn()
const mockPutSettings = vi.fn()
const mockTestSettings = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
teams: {
':teamId': {
'turntable-settings': {
$get: () => mockGetSettings(),
$put: (args: unknown) => mockPutSettings(args),
test: {
$post: (args: unknown) => mockTestSettings(args),
},
},
},
},
},
},
}))
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
vi.mock('@/ui/paraglide/messages.js', () => ({
m: {
turntable_settings: () => 'Turntable Renderer Settings',
turntable_settings_description: () => 'Configure external Blender turntable renderer',
turntable_env_configured: () => 'Configured via Environment',
turntable_server_url: () => 'Server URL',
turntable_server_url_placeholder: () => 'http://localhost:3000',
turntable_username: () => 'Username',
turntable_password: () => 'Password',
turntable_password_placeholder: () => 'Saved password',
turntable_test_connection: () => 'Test Connection',
turntable_testing: () => 'Testing...',
turntable_connection_success: () => 'Connection successful',
turntable_connection_failed: () => 'Connection failed',
save: () => 'Save',
settings_updated: () => 'Settings updated',
failed_update_settings: () => 'Failed to update settings',
},
}))
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
}
describe('TurntableSettingsCard', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
cleanup()
})
it('renders loaded settings with URL and username', async () => {
const settings: TurntableSettingsResponse = {
isEnvConfigured: false,
url: 'http://turntable.local:3000',
username: 'render-user',
hasPassword: true,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByDisplayValue('http://turntable.local:3000')).toBeDefined()
expect(screen.getByDisplayValue('render-user')).toBeDefined()
})
})
it('disables inputs and displays badge when configured via environment', async () => {
const settings: TurntableSettingsResponse = {
isEnvConfigured: true,
url: 'http://env-turntable:3000',
username: 'env-user',
hasPassword: true,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByText('Configured via Environment')).toBeDefined()
const urlInput = screen.getByDisplayValue('http://env-turntable:3000') as HTMLInputElement
expect(urlInput.disabled).toBe(true)
const saveBtn = screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement
expect(saveBtn.disabled).toBe(true)
})
})
it('saves updated settings', async () => {
const settings: TurntableSettingsResponse = {
isEnvConfigured: false,
url: '',
username: '',
hasPassword: false,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
mockPutSettings.mockResolvedValueOnce({
ok: true,
json: async () => ({
...settings,
url: 'http://new-turntable:3000',
username: 'alice',
}),
})
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByLabelText('Server URL')).toBeDefined()
})
const urlInput = screen.getByLabelText('Server URL')
fireEvent.change(urlInput, { target: { value: 'http://new-turntable:3000' } })
const usernameInput = screen.getByLabelText('Username')
fireEvent.change(usernameInput, { target: { value: 'alice' } })
const saveBtn = screen.getByRole('button', { name: 'Save' })
fireEvent.click(saveBtn)
await waitFor(() => {
expect(mockPutSettings).toHaveBeenCalledWith(
expect.objectContaining({
param: { teamId: 'team-123' },
json: expect.objectContaining({
url: 'http://new-turntable:3000',
username: 'alice',
}),
}),
)
})
})
it('tests connection successfully and displays version info', async () => {
const settings: TurntableSettingsResponse = {
isEnvConfigured: false,
url: 'http://turntable:3000',
username: 'user',
hasPassword: false,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
mockTestSettings.mockResolvedValueOnce({
ok: true,
json: async () => ({
ok: true,
version: '1.0.0',
blender: '5.2.0',
}),
})
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByDisplayValue('http://turntable:3000')).toBeDefined()
})
const testBtn = screen.getByRole('button', { name: 'Test Connection' })
fireEvent.click(testBtn)
await waitFor(() => {
expect(mockTestSettings).toHaveBeenCalled()
expect(screen.getByText(/Connection successful \(v1\.0\.0, Blender 5\.2\.0\)/)).toBeDefined()
})
})
it('tests connection and displays error when unreachable', async () => {
const settings: TurntableSettingsResponse = {
isEnvConfigured: false,
url: 'http://invalid-url:3000',
username: '',
hasPassword: false,
}
mockGetSettings.mockResolvedValueOnce({
ok: true,
json: async () => settings,
})
mockTestSettings.mockResolvedValueOnce({
ok: true,
json: async () => ({
ok: false,
error: 'ECONNREFUSED',
}),
})
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
await waitFor(() => {
expect(screen.getByDisplayValue('http://invalid-url:3000')).toBeDefined()
})
const testBtn = screen.getByRole('button', { name: 'Test Connection' })
fireEvent.click(testBtn)
await waitFor(() => {
expect(screen.getByText(/Connection failed: ECONNREFUSED/)).toBeDefined()
})
})
})
@@ -0,0 +1,243 @@
import React, { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { client } from '@/ui/api/client'
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
} from '@/ui/components/ui/card'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { Badge } from '@/ui/components/ui/badge'
import { Loader2, CheckCircle2, XCircle, Info } from 'lucide-react'
import { toast } from 'sonner'
import { m } from '@/ui/paraglide/messages.js'
interface TurntableSettingsCardProps {
teamId: string
}
export const TurntableSettingsCard: React.FC<TurntableSettingsCardProps> = ({ teamId }) => {
const queryClient = useQueryClient()
const [url, setUrl] = useState('')
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [testResult, setTestResult] = useState<{
ok: boolean
version?: string
blender?: string
error?: string
} | null>(null)
const [isTesting, setIsTesting] = useState(false)
const { data: turntableSettings, isLoading } = useQuery({
queryKey: ['teams', teamId, 'turntable-settings'],
queryFn: async () => {
const res = await client.api.teams[':teamId']['turntable-settings'].$get({
param: { teamId },
})
if (!res.ok) throw new Error('Failed to load turntable settings')
return await res.json()
},
enabled: !!teamId,
})
useEffect(() => {
if (turntableSettings) {
setUrl(turntableSettings.url || '')
setUsername(turntableSettings.username || '')
setPassword('')
setTestResult(null)
}
}, [turntableSettings])
const { mutateAsync: saveSettings, isPending: isSaving } = useMutation({
mutationFn: async () => {
const res = await client.api.teams[':teamId']['turntable-settings'].$put({
param: { teamId },
json: {
url: url || undefined,
username: username || undefined,
password: password || undefined,
},
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
throw new Error(
(err as { message?: string }).message || 'Failed to update turntable settings',
)
}
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'turntable-settings'],
})
queryClient.invalidateQueries({
queryKey: ['teams', teamId, 'settings'],
})
toast.success(m.settings_updated())
},
onError: (err: Error) => {
toast.error(err.message || m.failed_update_settings())
},
})
const handleTestConnection = async () => {
setIsTesting(true)
setTestResult(null)
try {
const res = await client.api.teams[':teamId']['turntable-settings'].test.$post({
param: { teamId },
json: {
url: url || undefined,
username: username || undefined,
password: password || undefined,
},
})
if (!res.ok) {
const err = await res.json().catch(() => ({}))
const errorMsg = (err as { message?: string }).message || 'Request failed'
setTestResult({ ok: false, error: errorMsg })
toast.error(m.turntable_connection_failed())
return
}
const data = await res.json()
setTestResult(data)
if (data.ok) {
toast.success(m.turntable_connection_success())
} else {
toast.error(data.error || m.turntable_connection_failed())
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
setTestResult({ ok: false, error: msg })
toast.error(m.turntable_connection_failed())
} finally {
setIsTesting(false)
}
}
const isEnvConfigured = Boolean(turntableSettings?.isEnvConfigured)
return (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{m.turntable_settings()}</CardTitle>
{isEnvConfigured && (
<Badge variant="secondary" className="gap-1">
<Info className="w-3 h-3" />
{m.turntable_env_configured()}
</Badge>
)}
</div>
<CardDescription>{m.turntable_settings_description()}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{isLoading ? (
<div className="flex items-center justify-center py-6">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<>
<div className="space-y-1.5">
<label htmlFor="turntable-url" className="text-sm font-medium">
{m.turntable_server_url()}
</label>
<Input
id="turntable-url"
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder={m.turntable_server_url_placeholder()}
disabled={isEnvConfigured || isSaving}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1.5">
<label htmlFor="turntable-username" className="text-sm font-medium">
{m.turntable_username()}
</label>
<Input
id="turntable-username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="admin"
disabled={isEnvConfigured || isSaving}
/>
</div>
<div className="space-y-1.5">
<label htmlFor="turntable-password" className="text-sm font-medium">
{m.turntable_password()}
</label>
<Input
id="turntable-password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={
turntableSettings?.hasPassword ? m.turntable_password_placeholder() : '••••••••'
}
disabled={isEnvConfigured || isSaving}
/>
</div>
</div>
{testResult && (
<div
className={`flex items-center gap-2 p-3 rounded-lg border text-sm ${
testResult.ok
? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
: 'border-destructive/30 bg-destructive/10 text-destructive'
}`}
>
{testResult.ok ? (
<>
<CheckCircle2 className="w-4 h-4 shrink-0" />
<span>
{m.turntable_connection_success()} (v{testResult.version || 'unknown'}
{testResult.blender ? `, Blender ${testResult.blender}` : ''})
</span>
</>
) : (
<>
<XCircle className="w-4 h-4 shrink-0" />
<span>
{m.turntable_connection_failed()}: {testResult.error}
</span>
</>
)}
</div>
)}
</>
)}
</CardContent>
<CardFooter className="flex justify-between border-t border-border pt-4">
<Button
type="button"
variant="outline"
onClick={handleTestConnection}
disabled={isLoading || isTesting || !url.trim()}
>
{isTesting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
{isTesting ? m.turntable_testing() : m.turntable_test_connection()}
</Button>
<Button
type="button"
onClick={() => saveSettings()}
disabled={isEnvConfigured || isSaving || isLoading}
>
{isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
{m.save()}
</Button>
</CardFooter>
</Card>
)
}
@@ -0,0 +1,22 @@
import { FileTypeDefinition } from '../types'
import ModelViewer from './model-viewer'
export function secondToDegree(second: number): number {
const frameIndex = Math.min(Math.max(0, Math.round(second * 6)), 23)
return (frameIndex * 15) % 360
}
export const modelTypeDefinition: FileTypeDefinition = {
id: '3d',
name: '3D Model',
match: (file) => file.proxyType === '3d',
viewer: ModelViewer,
commentsConfig: {
hasTimestamp: true,
hasAnnotations: true,
formatTimestamp: (second: number) => {
const deg = secondToDegree(second)
return `${deg}°`
},
},
}
@@ -0,0 +1,186 @@
import React from 'react'
import { Play, Pause, RotateCcw, Maximize, Minimize, Minus, Plus, Download } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import { RulerSlider } from './ruler-slider'
export interface ModelControlBarProps {
isPlaying: boolean
currentDegree: number
zoom: number
isFullScreen: boolean
allowDownload?: boolean
downloadUrl?: string
fileName?: string
togglePlay: () => void
onSeekDegree: (degree: number) => void
onResetRotation: () => void
onZoomChange: (zoom: number) => void
onZoomReset: () => void
toggleFullScreen: () => void
}
export const ModelControlBar: React.FC<ModelControlBarProps> = ({
isPlaying,
currentDegree,
zoom,
isFullScreen,
allowDownload = true,
downloadUrl,
fileName,
togglePlay,
onSeekDegree,
onResetRotation,
onZoomChange,
onZoomReset,
toggleFullScreen,
}) => {
const handleDownload = () => {
if (!downloadUrl) return
const a = document.createElement('a')
a.href = downloadUrl
a.download = fileName || 'model.glb'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
const handleStepDegree = (delta: number) => {
const next = (((currentDegree + delta) % 360) + 360) % 360
onSeekDegree(next)
}
return (
<div
className={cn(
'transition-all duration-300 ease-in-out z-20 text-foreground',
isFullScreen
? 'absolute bottom-0 left-0 right-0 px-4 py-2.5 bg-card/90 backdrop-blur-md border-t border-border'
: 'relative w-full bg-card border-t border-border px-4 py-2.5 z-10 transition-colors duration-200',
)}
>
{/* Unified Single Row Controls */}
<div className="flex items-center justify-between text-foreground gap-4">
{/* Left Side: Play/Pause, Degree Readout, Reset Rotation */}
<div className="flex items-center gap-3 justify-start min-w-0 flex-1">
<button
type="button"
onClick={togglePlay}
aria-label={isPlaying ? 'Pause' : 'Play'}
className="hover:text-primary transition-colors shrink-0"
data-testid="play-toggle"
data-playing={isPlaying}
>
{isPlaying ? (
<Pause className="w-5 h-5 fill-current" />
) : (
<Play className="w-5 h-5 fill-current" />
)}
</button>
<div
className="flex items-center text-sm font-medium tabular-nums select-none shrink-0"
data-testid="degree-readout"
>
<span className="text-muted-foreground font-mono">{currentDegree}° / 360°</span>
</div>
<button
type="button"
onClick={onResetRotation}
title="Reset to 0°"
aria-label="Reset rotation to 0°"
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
>
<RotateCcw className="w-4 h-4" />
</button>
</div>
{/* Center: RulerSlider with minus & plus buttons */}
<div className="flex items-center gap-1.5 w-full max-w-[320px] justify-center mx-auto shrink-0">
<button
type="button"
onClick={() => handleStepDegree(-15)}
title="Decrease 15°"
aria-label="Decrease 15°"
className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
data-testid="ruler-step-minus"
>
<Minus className="w-3.5 h-3.5" />
</button>
<RulerSlider
currentDegree={currentDegree}
onChange={onSeekDegree}
className="flex-1 min-w-[140px]"
/>
<button
type="button"
onClick={() => handleStepDegree(15)}
title="Increase 15°"
aria-label="Increase 15°"
className="p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
data-testid="ruler-step-plus"
>
<Plus className="w-3.5 h-3.5" />
</button>
</div>
{/* Right Side: Zoom controls, Download, Fullscreen */}
<div className="flex items-center gap-2 justify-end min-w-0 flex-1">
{/* Zoom controls */}
<div className="flex items-center gap-1 bg-muted/60 rounded-lg p-0.5 border border-border/40 shrink-0">
<button
type="button"
onClick={() => onZoomChange(Math.max(0.2, zoom - 0.2))}
aria-label="Zoom out"
className="p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors"
>
<Minus className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={onZoomReset}
aria-label="Reset zoom"
className="px-1.5 py-0.5 text-[11px] font-mono text-muted-foreground hover:text-foreground transition-colors"
>
{Math.round(zoom * 100)}%
</button>
<button
type="button"
onClick={() => onZoomChange(Math.min(5, zoom + 0.2))}
aria-label="Zoom in"
className="p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors"
>
<Plus className="w-3.5 h-3.5" />
</button>
</div>
{/* Download */}
{allowDownload && downloadUrl && (
<button
type="button"
onClick={handleDownload}
title="Download asset"
aria-label="Download asset"
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
>
<Download className="w-4 h-4" />
</button>
)}
{/* Fullscreen */}
<button
type="button"
onClick={toggleFullScreen}
title={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
aria-label={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
>
{isFullScreen ? <Minimize className="w-4 h-4" /> : <Maximize className="w-4 h-4" />}
</button>
</div>
</div>
</div>
)
}
@@ -0,0 +1,200 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render } from '@testing-library/react'
import React, { createRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ModelViewer } from './model-viewer'
import type { MediaController } from '../types'
import type { AssetInfo } from '@shumai/dtos'
vi.mock('@/ui/components/drawing-canvas', () => ({
default: () => <div data-testid="drawing-canvas" />,
}))
vi.mock('@/ui/paraglide/messages.js', () => ({
m: new Proxy({}, { get: () => () => '' }),
}))
class MockResizeObserver {
observe = vi.fn(() => {
// Immediate callback with mock size
this.callback(
[{ contentRect: { width: 800, height: 600 } } as unknown as ResizeObserverEntry],
this,
)
})
unobserve = vi.fn()
disconnect = vi.fn()
constructor(private callback: ResizeObserverCallback) {}
}
const mockAsset: AssetInfo = {
id: 'asset-3d-1',
name: 'robot.glb',
proxyType: '3d',
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-01T00:00:00Z',
type: 'file',
sizeByte: 1024,
fileCount: 1,
status: 'processed',
projectId: 'proj-1',
media: {
videoPreview: {
url: 'https://example.com/robot-turntable.mp4',
},
original: {
key: 'files/robot.glb',
},
metadata: {
originalWidth: 1080,
originalHeight: 1080,
},
},
preview: {
thumbnailUrl: 'https://example.com/robot-poster.webp',
},
} as unknown as AssetInfo
describe('ModelViewer', () => {
beforeEach(() => {
global.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver
vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(() => Promise.resolve())
vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
it('renders model viewer container, surface, video, and control bar', () => {
const { getByTestId, getByText } = render(<ModelViewer file={mockAsset} />)
expect(getByTestId('model-viewer-container')).toBeDefined()
expect(getByTestId('model-viewer-surface')).toBeDefined()
expect(getByTestId('drawing-canvas')).toBeDefined()
// Control bar shows 0° / 360° initially
expect(getByText(/0°\s*\/\s*360°/)).toBeDefined()
})
it('toggles play/pause via spacebar hotkey', () => {
const onPlay = vi.fn()
const onPause = vi.fn()
const { container } = render(<ModelViewer file={mockAsset} onPlay={onPlay} onPause={onPause} />)
const video = container.querySelector('video')
expect(video).toBeDefined()
// Space key triggers togglePlay
fireEvent.keyDown(window, { key: ' ' })
expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
// Simulate video playing event
if (video) {
fireEvent.play(video)
expect(onPlay).toHaveBeenCalled()
}
})
it('seeks frames via arrow hotkeys', () => {
const onTimeUpdate = vi.fn()
render(<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />)
// Press ArrowRight -> advance 1 frame (15 deg = 1/6 sec = ~0.1667)
fireEvent.keyDown(window, { key: 'ArrowRight' })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
// Press ArrowRight second time -> advance to frame 2 (30 deg = 2/6 sec)
fireEvent.keyDown(window, { key: 'ArrowRight' })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
// Press ArrowLeft -> back 1 frame (frame 1 = 1/6 sec)
fireEvent.keyDown(window, { key: 'ArrowLeft' })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
// Press ArrowLeft -> back 1 frame (frame 0 = 0 sec)
fireEvent.keyDown(window, { key: 'ArrowLeft' })
expect(onTimeUpdate).toHaveBeenCalledWith(0)
})
it('handles pointer dragging to rotate 3D asset', () => {
const onTimeUpdate = vi.fn()
const { getByTestId } = render(<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />)
const surface = getByTestId('model-viewer-surface')
// Mock setPointerCapture / releasePointerCapture
surface.setPointerCapture = vi.fn()
surface.releasePointerCapture = vi.fn()
// Start drag at x = 100
fireEvent.pointerDown(surface, { clientX: 100, button: 0, pointerId: 1 })
expect(surface.setPointerCapture).toHaveBeenCalledWith(1)
// Move right by 24px (+2 frames = +30 deg)
fireEvent.pointerMove(surface, { clientX: 124, button: 0, pointerId: 1 })
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
// Release drag
fireEvent.pointerUp(surface, { clientX: 124, button: 0, pointerId: 1 })
expect(surface.releasePointerCapture).toHaveBeenCalledWith(1)
})
it('exposes imperative media controller via ref', () => {
const ref = createRef<MediaController>()
render(<ModelViewer ref={ref} file={mockAsset} />)
expect(ref.current).toBeDefined()
expect(ref.current?.getDuration?.()).toBe(4)
expect(typeof ref.current?.getCurrentTime?.()).toBe('number')
ref.current?.play()
expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
ref.current?.pause()
expect(HTMLMediaElement.prototype.pause).toHaveBeenCalled()
ref.current?.seekTo(1) // 1 second -> frame 6 -> 1 second
expect(ref.current?.getCurrentTime?.()).toBeDefined()
})
it('resets rotation to 0° when reset button is clicked', () => {
const onTimeUpdate = vi.fn()
const { getByRole } = render(
<ModelViewer file={mockAsset} startTime={1} onTimeUpdate={onTimeUpdate} />,
)
// Reset rotation button has aria-label 'Reset rotation to 0°'
const resetBtn = getByRole('button', { name: /Reset rotation/i })
fireEvent.click(resetBtn)
expect(onTimeUpdate).toHaveBeenCalledWith(0)
})
it('renders children alongside viewer surface when provided', () => {
const { getByTestId } = render(
<ModelViewer file={mockAsset}>
<div data-testid="test-sidebar">Sidebar</div>
</ModelViewer>,
)
expect(getByTestId('test-sidebar')).toBeDefined()
expect(getByTestId('model-viewer-surface')).toBeDefined()
})
it('steps rotation by 15° forward and backward via plus and minus buttons', () => {
const onTimeUpdate = vi.fn()
const { getByTestId } = render(
<ModelViewer file={mockAsset} startTime={0} onTimeUpdate={onTimeUpdate} />,
)
const plusBtn = getByTestId('ruler-step-plus')
const minusBtn = getByTestId('ruler-step-minus')
// Click plus button at 0° -> seeks to 15° (frame 1, 1/6s)
fireEvent.click(plusBtn)
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
// Click minus button at 0° (or current) -> wraps backward
fireEvent.click(minusBtn)
expect(onTimeUpdate).toHaveBeenCalledWith(0)
})
})
@@ -0,0 +1,400 @@
import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
import { AlertCircle, Loader2 } from 'lucide-react'
import { cn } from '@/ui/lib/utils'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { FileViewerProps, MediaController } from '../types'
import { centeredPan, fitScale, zoomAtPoint } from '../pan-zoom'
import { ModelControlBar } from './model-control-bar'
import { secondToDegree } from './index'
const TOTAL_FRAMES = 24
const FPS = 6
const FRAME_DURATION = 1 / FPS
export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
(
{
file: data,
onPlay,
onPause,
onTimeUpdate,
annotations,
startTime,
children,
allowDownload = true,
autoPlay = false,
},
ref,
) => {
const rootRef = useRef<HTMLDivElement | null>(null)
const videoRef = useRef<HTMLVideoElement | null>(null)
const containerRef = useRef<HTMLDivElement | null>(null)
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
const [isPlaying, setIsPlaying] = useState(false)
const [currentTime, setCurrentTime] = useState(startTime || 0)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [isFullScreen, setIsFullScreen] = useState(false)
// Pan & Zoom
const [zoom, setZoom] = useState(1)
const [pan, setPan] = useState({ x: 0, y: 0 })
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
// Drag-to-rotate state
const [isDraggingRotation, setIsDraggingRotation] = useState(false)
const dragStartRef = useRef<{ clientX: number; frame: number }>({ clientX: 0, frame: 0 })
const videoSrc = data.media?.videoPreview?.url || data.media?.videoTranscodes?.[0]?.url || ''
const posterUrl = data.preview?.thumbnailUrl || undefined
const downloadUrl = data.media?.original?.key ? videoSrc : undefined
// Drawing Annotation store
const {
isDrawing,
currentTool,
currentColor,
addAnnotation,
annotations: draftAnnotations,
} = useAnnotationStore()
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
const isDrawingMode = isDrawing
const mediaWidth = data.media?.metadata?.originalWidth || 1080
const mediaHeight = data.media?.metadata?.originalHeight || 1080
// Resize observer
useEffect(() => {
if (!containerRef.current) return
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(containerRef.current)
return () => observer.disconnect()
}, [])
// Initial scale and center
useEffect(() => {
if (containerSize.width > 0 && containerSize.height > 0 && !hasManuallyZoomed) {
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
setZoom(scale)
setPan(
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
)
}
}, [containerSize, mediaWidth, mediaHeight, hasManuallyZoomed])
// Current angle
const currentDegree = secondToDegree(currentTime)
// Seek helper
const seekToFrame = useCallback(
(frameIndex: number) => {
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
const targetSec = normalizedFrame * FRAME_DURATION
if (videoRef.current) {
videoRef.current.currentTime = targetSec
}
setCurrentTime(targetSec)
onTimeUpdate?.(targetSec)
},
[onTimeUpdate],
)
const seekToDegree = useCallback(
(degree: number) => {
const frame = Math.round((((degree % 360) + 360) % 360) / 15) % TOTAL_FRAMES
seekToFrame(frame)
},
[seekToFrame],
)
// Play / Pause toggle
const togglePlay = useCallback(() => {
const video = videoRef.current
if (!video) return
if (video.paused || video.ended) {
video.play().catch(() => {})
} else {
video.pause()
}
}, [])
// Video Imperative Controller
useImperativeHandle(
ref,
() => ({
play: () => {
videoRef.current?.play().catch(() => {})
},
pause: () => {
videoRef.current?.pause()
},
seekTo: (second: number) => {
seekToFrame(Math.floor(second * FPS))
},
getCurrentTime: () => videoRef.current?.currentTime || 0,
getDuration: () => 4,
}),
[seekToFrame],
)
// Keyboard Hotkeys
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const active = document.activeElement
if (
active &&
(active.tagName === 'INPUT' ||
active.tagName === 'TEXTAREA' ||
(active instanceof HTMLElement && active.isContentEditable))
) {
return
}
if (e.key === ' ') {
e.preventDefault()
togglePlay()
} else if (e.key === 'ArrowLeft') {
e.preventDefault()
const currentFrame = Math.round(currentTime * FPS)
seekToFrame(currentFrame - 1)
} else if (e.key === 'ArrowRight') {
e.preventDefault()
const currentFrame = Math.round(currentTime * FPS)
seekToFrame(currentFrame + 1)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [currentTime, seekToFrame, togglePlay])
// Pointer events for Drag-to-Rotate
const handleViewerPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (isDrawingMode || e.button !== 0) return
const target = e.currentTarget
target.setPointerCapture(e.pointerId)
videoRef.current?.pause()
const currentFrame = Math.floor(currentTime * FPS)
dragStartRef.current = {
clientX: e.clientX,
frame: currentFrame,
}
setIsDraggingRotation(true)
}
const handleViewerPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!isDraggingRotation) return
const deltaX = e.clientX - dragStartRef.current.clientX
// 12px drag movement corresponds to 1 frame (15°)
const deltaFrames = Math.round(deltaX / 12)
seekToFrame(dragStartRef.current.frame + deltaFrames)
}
const handleViewerPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (!isDraggingRotation) return
setIsDraggingRotation(false)
try {
e.currentTarget.releasePointerCapture(e.pointerId)
} catch {
// pointer may already be released
}
}
// Fullscreen toggle
const toggleFullScreen = () => {
if (!rootRef.current) return
if (!document.fullscreenElement) {
rootRef.current.requestFullscreen().catch(() => {})
} else {
document.exitFullscreen().catch(() => {})
}
}
useEffect(() => {
const onFsChange = () => {
setIsFullScreen(Boolean(document.fullscreenElement))
}
document.addEventListener('fullscreenchange', onFsChange)
return () => document.removeEventListener('fullscreenchange', onFsChange)
}, [])
const handleZoomChange = (newZoom: number) => {
setHasManuallyZoomed(true)
const next = zoomAtPoint(
zoom,
pan,
newZoom / zoom,
containerSize.width / 2,
containerSize.height / 2,
)
setZoom(next.zoom)
setPan(next.pan)
}
const handleZoomReset = () => {
setHasManuallyZoomed(false)
if (containerSize.width > 0 && containerSize.height > 0) {
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
setZoom(scale)
setPan(
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
)
}
}
return (
<div
ref={rootRef}
data-testid="model-viewer-container"
className={cn(
'group shadow-2xl font-sans select-none flex flex-col mx-auto relative',
isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
)}
>
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
{/* Render Carousel/Sidebar here if not fullscreen */}
{!isFullScreen && children}
{/* Interactive Drag Rotation Surface & Model Area */}
<div
ref={containerRef}
data-testid="model-viewer-surface"
onPointerDown={handleViewerPointerDown}
onPointerMove={handleViewerPointerMove}
onPointerUp={handleViewerPointerUp}
onPointerCancel={handleViewerPointerUp}
className={cn(
'flex-1 bg-black relative flex items-center justify-center overflow-hidden min-h-0 touch-none',
isDrawingMode
? 'cursor-crosshair'
: isDraggingRotation
? 'cursor-grabbing'
: 'cursor-grab',
)}
>
{/* Centered Scaled Media Wrapper */}
<div
className="absolute pointer-events-none"
style={{
left: 0,
top: 0,
width: mediaWidth,
height: mediaHeight,
transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
transformOrigin: '0 0',
}}
>
{videoSrc && (
<video
ref={videoRef}
src={videoSrc}
poster={posterUrl}
playsInline
loop
muted
autoPlay={autoPlay}
preload="auto"
onLoadedData={() => {
setIsLoading(false)
if (startTime && startTime > 0) {
seekToFrame(Math.floor(startTime * FPS))
}
}}
onPlay={() => {
setIsPlaying(true)
onPlay?.()
}}
onPause={() => {
setIsPlaying(false)
onPause?.()
}}
onTimeUpdate={() => {
if (videoRef.current && !isDraggingRotation) {
setCurrentTime(videoRef.current.currentTime)
onTimeUpdate?.(videoRef.current.currentTime)
}
}}
onError={() => {
setIsLoading(false)
setError('Failed to load turntable video')
}}
className="w-full h-full block object-contain pointer-events-none"
/>
)}
</div>
{/* Drawing Canvas Overlay */}
{containerSize.width > 0 && containerSize.height > 0 && (
<DrawingCanvas
width={containerSize.width}
height={containerSize.height}
mediaDimensions={{
width: mediaWidth,
height: mediaHeight,
}}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
className="absolute inset-0 pointer-events-none"
isDrawing={isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={addAnnotation}
/>
)}
{/* Loading Spinner */}
{isLoading && !error && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
<div className="w-14 h-14 bg-background/80 backdrop-blur-md rounded-full flex items-center justify-center border border-border shadow-lg">
<Loader2 className="w-7 h-7 text-primary animate-spin" />
</div>
</div>
)}
{/* Error Display */}
{error && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 text-destructive z-10 bg-background/90 p-4 text-center">
<AlertCircle className="w-10 h-10" />
<p className="text-sm font-medium">{error}</p>
</div>
)}
</div>
</div>
{/* Full-width docked bottom control bar */}
<ModelControlBar
isPlaying={isPlaying}
currentDegree={currentDegree}
zoom={zoom}
isFullScreen={isFullScreen}
allowDownload={allowDownload}
downloadUrl={downloadUrl}
fileName={data.name}
togglePlay={togglePlay}
onSeekDegree={seekToDegree}
onResetRotation={() => seekToDegree(0)}
onZoomChange={handleZoomChange}
onZoomReset={handleZoomReset}
toggleFullScreen={toggleFullScreen}
/>
</div>
)
},
)
ModelViewer.displayName = 'ModelViewer'
export default ModelViewer
@@ -0,0 +1,141 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render } from '@testing-library/react'
import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RulerSlider } from './ruler-slider'
describe('RulerSlider', () => {
afterEach(() => {
cleanup()
})
it('renders slider with fixed center indicator and aria values', () => {
const onChange = vi.fn()
const { getByRole, getByTestId, queryByTestId } = render(
<RulerSlider currentDegree={90} onChange={onChange} />,
)
const slider = getByRole('slider')
expect(slider).toBeDefined()
expect(slider.getAttribute('aria-valuenow')).toBe('90')
expect(slider.getAttribute('aria-valuetext')).toBe('90°')
// Fixed center indicator exists
expect(getByTestId('ruler-center-indicator')).toBeDefined()
// Tooltip should not be rendered while not dragging
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
})
it('renders ticks at 15° intervals, longer at 60° intervals, and no numeric tick labels', () => {
const onChange = vi.fn()
const { container, getAllByTestId } = render(
<RulerSlider currentDegree={0} onChange={onChange} />,
)
// Major ticks at multiples of 60°
const ticks0 = getAllByTestId('tick-0')
expect(ticks0.length).toBeGreaterThan(0)
expect(ticks0[0]?.getAttribute('data-major')).toBe('true')
const ticks60 = getAllByTestId('tick-60')
expect(ticks60.length).toBeGreaterThan(0)
expect(ticks60[0]?.getAttribute('data-major')).toBe('true')
// Regular tick at 15° is not major
const ticks15 = getAllByTestId('tick-15')
expect(ticks15.length).toBeGreaterThan(0)
expect(ticks15[0]?.getAttribute('data-major')).toBe('false')
// No numeric degree text inside the slider track
expect(container.textContent).toBe('')
})
it('shows tooltip displaying degree while dragging and hides on pointer up', () => {
const onChange = vi.fn()
const { getByRole, getByTestId, queryByTestId } = render(
<RulerSlider currentDegree={45} onChange={onChange} />,
)
const slider = getByRole('slider')
slider.setPointerCapture = vi.fn()
slider.releasePointerCapture = vi.fn()
// Initially no tooltip
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
// Start dragging
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
const tooltip = getByTestId('ruler-slider-tooltip')
expect(tooltip).toBeDefined()
expect(tooltip.textContent).toBe('45°')
// Release drag
fireEvent.pointerUp(slider, { clientX: 100, button: 0, pointerId: 1 })
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
})
it('handles keyboard navigation with 15 degree stepping and wrapping', () => {
const onChange = vi.fn()
const { getByRole } = render(<RulerSlider currentDegree={45} onChange={onChange} />)
const slider = getByRole('slider')
// 45 + 15 = 60
fireEvent.keyDown(slider, { key: 'ArrowRight' })
expect(onChange).toHaveBeenCalledWith(60)
// 45 - 15 = 30
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
expect(onChange).toHaveBeenCalledWith(30)
// Home -> 0
fireEvent.keyDown(slider, { key: 'Home' })
expect(onChange).toHaveBeenCalledWith(0)
// End -> 345
fireEvent.keyDown(slider, { key: 'End' })
expect(onChange).toHaveBeenCalledWith(345)
})
it('wraps around 0° and 360° on keyboard navigation', () => {
const onChange = vi.fn()
const { getByRole, rerender } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
const slider = getByRole('slider')
// 0 - 15 wraps to 345
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
expect(onChange).toHaveBeenCalledWith(345)
// 345 + 15 wraps to 0
rerender(<RulerSlider currentDegree={345} onChange={onChange} />)
fireEvent.keyDown(slider, { key: 'ArrowRight' })
expect(onChange).toHaveBeenCalledWith(0)
})
it('handles pointer drag interaction with 15 degree snapping and wrapping', () => {
const onChange = vi.fn()
const { getByRole } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
const slider = getByRole('slider')
slider.setPointerCapture = vi.fn()
slider.releasePointerCapture = vi.fn()
// Start drag at x = 100
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
expect(slider.setPointerCapture).toHaveBeenCalledWith(1)
// Drag left by 24px (15° forward: deltaX = -24 => deltaDeg = +15)
fireEvent.pointerMove(slider, { clientX: 76, button: 0, pointerId: 1 })
expect(onChange).toHaveBeenCalledWith(15)
// Drag right by 24px from origin (x=124 => deltaX = +24 => deltaDeg = -15 => wraps to 345)
fireEvent.pointerMove(slider, { clientX: 124, button: 0, pointerId: 1 })
expect(onChange).toHaveBeenCalledWith(345)
// Release pointer
fireEvent.pointerUp(slider, { clientX: 124, button: 0, pointerId: 1 })
expect(slider.releasePointerCapture).toHaveBeenCalledWith(1)
})
})
@@ -0,0 +1,189 @@
import React, { useCallback, useRef, useState } from 'react'
import { cn } from '@/ui/lib/utils'
interface RulerSliderProps {
currentDegree: number // 0 to 360 (or normalized modulo 360)
onChange: (degree: number) => void
className?: string
disabled?: boolean
}
const PX_PER_DEGREE = 1.6 // 24px per 15° step
const STEP = 15
const BUFFER_DEGREE = 240 // Render buffer on each side of the active degree
export const RulerSlider: React.FC<RulerSliderProps> = ({
currentDegree,
onChange,
className,
disabled = false,
}) => {
const containerRef = useRef<HTMLDivElement>(null)
const [isDragging, setIsDragging] = useState(false)
const [dragDegree, setDragDegree] = useState<number | null>(null)
const dragStartRef = useRef<{ clientX: number; startDegree: number }>({
clientX: 0,
startDegree: 0,
})
const normalizedDegree = (((Math.round(currentDegree / STEP) * STEP) % 360) + 360) % 360
const activeDegree = isDragging && dragDegree !== null ? dragDegree : normalizedDegree
const displayedDegree = (((Math.round(activeDegree / STEP) * STEP) % 360) + 360) % 360
const handlePointerDown = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (disabled || e.button !== 0) return
e.preventDefault()
e.stopPropagation()
const target = containerRef.current
if (!target) return
target.setPointerCapture(e.pointerId)
dragStartRef.current = {
clientX: e.clientX,
startDegree: currentDegree,
}
setIsDragging(true)
setDragDegree(currentDegree)
},
[disabled, currentDegree],
)
const handlePointerMove = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (!isDragging || disabled) return
const deltaX = e.clientX - dragStartRef.current.clientX
// Dragging left (deltaX < 0) rotates turntable forward (angle increases)
const nextRawDegree = dragStartRef.current.startDegree - deltaX / PX_PER_DEGREE
const snapped = (((Math.round(nextRawDegree / STEP) * STEP) % 360) + 360) % 360
setDragDegree(snapped)
onChange(snapped)
},
[isDragging, disabled, onChange],
)
const handlePointerUp = useCallback(
(e: React.PointerEvent<HTMLDivElement>) => {
if (!isDragging) return
setIsDragging(false)
if (dragDegree !== null) {
onChange(dragDegree)
}
setDragDegree(null)
try {
containerRef.current?.releasePointerCapture(e.pointerId)
} catch {
// pointer may have already been released
}
},
[isDragging, dragDegree, onChange],
)
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
if (disabled) return
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
onChange((((normalizedDegree - STEP) % 360) + 360) % 360)
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
onChange((normalizedDegree + STEP) % 360)
} else if (e.key === 'Home') {
e.preventDefault()
e.stopPropagation()
onChange(0)
} else if (e.key === 'End') {
e.preventDefault()
e.stopPropagation()
onChange(345)
}
},
[disabled, normalizedDegree, onChange],
)
// Compute visible ticks dynamically around activeDegree for seamless cyclic looping
const minTickIndex = Math.floor((activeDegree - BUFFER_DEGREE) / STEP)
const maxTickIndex = Math.ceil((activeDegree + BUFFER_DEGREE) / STEP)
const ticks: number[] = []
for (let i = minTickIndex; i <= maxTickIndex; i++) {
ticks.push(i * STEP)
}
return (
<div
ref={containerRef}
role="slider"
aria-label="Turntable angle"
aria-valuemin={0}
aria-valuemax={360}
aria-valuenow={displayedDegree}
aria-valuetext={`${displayedDegree}°`}
tabIndex={disabled ? -1 : 0}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onPointerCancel={handlePointerUp}
onKeyDown={handleKeyDown}
className={cn(
'relative select-none cursor-ew-resize flex flex-col justify-end h-9 touch-none w-full min-w-[140px] group',
disabled && 'opacity-50 cursor-not-allowed',
className,
)}
>
{/* Tooltip above center indicator (visible only when dragging) */}
{isDragging && (
<div
data-testid="ruler-slider-tooltip"
className="absolute -top-6 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-primary text-primary-foreground text-[10px] font-mono font-medium shadow-md whitespace-nowrap pointer-events-none z-30 animate-in fade-in zoom-in-95 duration-100"
>
{displayedDegree}°
</div>
)}
{/* Moving Track & Ticks with Edge Mask */}
<div
className="relative w-full h-5 flex items-end overflow-hidden"
style={{
maskImage:
'linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent)',
}}
>
{/* Baseline bar */}
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-muted-foreground/20 rounded-full" />
{/* Cyclic Ticks */}
{ticks.map((tickAngle) => {
const offsetPx = (tickAngle - activeDegree) * PX_PER_DEGREE
const deg = ((tickAngle % 360) + 360) % 360
const isMajor = deg % 60 === 0
return (
<div
key={`tick-${tickAngle}`}
data-testid={`tick-${deg}`}
data-major={isMajor}
className={cn(
'absolute bottom-0 -translate-x-1/2 transition-colors pointer-events-none',
isMajor
? 'w-0.5 h-4 bg-foreground/75'
: 'w-px h-2 bg-muted-foreground/40 group-hover:bg-muted-foreground/60',
)}
style={{ left: `calc(50% + ${offsetPx}px)` }}
/>
)
})}
</div>
{/* Fixed Center Indicator (Pinned at 50% horizontally) */}
<div
data-testid="ruler-center-indicator"
className="absolute bottom-0 left-1/2 -translate-x-1/2 flex flex-col items-center pointer-events-none z-20"
>
<div className="w-0.5 h-5 bg-primary rounded-full shadow-xs ring-1 ring-background/50" />
</div>
</div>
)
}
@@ -3,9 +3,15 @@ import { FileTypeDefinition } from './types'
import { videoTypeDefinition } from './video'
import { imageTypeDefinition } from './image'
import { pdfTypeDefinition } from './pdf'
import { modelTypeDefinition } from './model'
import { defaultTypeDefinition } from './default'
const registry: FileTypeDefinition[] = [pdfTypeDefinition, videoTypeDefinition, imageTypeDefinition]
const registry: FileTypeDefinition[] = [
modelTypeDefinition,
pdfTypeDefinition,
videoTypeDefinition,
imageTypeDefinition,
]
export function getViewerForFile(file: AssetInfo | null | undefined): FileTypeDefinition {
if (!file) return defaultTypeDefinition
+12
View File
@@ -257,6 +257,18 @@
"transcode_settings": "Transcode Settings",
"transcode_description": "Manage your team's video transcoding configurations.",
"transcode_strategy_note": "Strategy: We select the best resolution from your list that supports the input quality. Content is never upscaled.",
"turntable_settings": "3D Turntable Renderer",
"turntable_settings_description": "Configure the external Blender turntable-renderer service for generating 3D asset previews and videos.",
"turntable_server_url": "Server URL",
"turntable_server_url_placeholder": "e.g. http://localhost:3001",
"turntable_username": "Username",
"turntable_password": "Password",
"turntable_password_placeholder": "Leave blank to keep existing password",
"turntable_env_configured": "Configured via environment variables (Read-only)",
"turntable_test_connection": "Test Connection",
"turntable_connection_success": "Connected successfully",
"turntable_connection_failed": "Connection failed",
"turntable_testing": "Testing...",
"hardware_acceleration_section_description": "Configure hardware-accelerated video encoding to offload workloads to GPUs, or use CPU software encoding.",
"mp4_transcoding": "MP4 Transcoding",
"mp4_transcoding_description": "Generate web-compatible MP4 files for file downloads and standard video playback.",
+12
View File
@@ -257,6 +257,18 @@
"transcode_settings": "转码设置",
"transcode_description": "管理团队的视频转码配置。",
"transcode_strategy_note": "策略:我们会从您的列表中选择支持输入质量的最佳分辨率。内容不会被放大。",
"turntable_settings": "3D 转盘渲染服务",
"turntable_settings_description": "配置用于生成 3D 资产预览图与转盘视频的外部 Blender 渲染服务。",
"turntable_server_url": "服务地址",
"turntable_server_url_placeholder": "例如 http://localhost:3001",
"turntable_username": "用户名",
"turntable_password": "密码",
"turntable_password_placeholder": "留空以保留当前密码",
"turntable_env_configured": "已通过环境变量配置(只读)",
"turntable_test_connection": "测试连接",
"turntable_connection_success": "连接成功",
"turntable_connection_failed": "连接失败",
"turntable_testing": "正在测试...",
"hardware_acceleration_section_description": "配置硬件加速视频编码以将工作负载分流至 GPU,或使用 CPU 软件编码。",
"mp4_transcoding": "MP4 转码",
"mp4_transcoding_description": "生成适用于文件下载和标准视频播放的 Web 兼容 MP4 文件。",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/webui",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./index.html",
@@ -23,6 +23,7 @@ import { QuotasSettings } from '@/ui/components/settings/QuotasSettings'
import { AppearanceSettings } from '@/ui/components/settings/AppearanceSettings'
import { EmailNotificationSettings } from '@/ui/components/settings/EmailNotificationSettings'
import { ImageVideoGenerationSettings } from '@/ui/components/settings/ImageVideoGenerationSettings'
import { TurntableSettingsCard } from '@/ui/components/settings/TurntableSettingsCard'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
import { Slider } from '@/ui/components/ui/slider'
import { cn } from '@/ui/lib/utils'
@@ -1147,6 +1148,9 @@ export function TeamSettingsPage() {
</div>
</CardContent>
</Card>
{/* 3D Turntable Renderer Card */}
<TurntableSettingsCard teamId={teamId} />
</div>
)}
+1 -1
View File
@@ -12,7 +12,7 @@ export interface TopNavProjectState {
name?: string
type: 'file' | 'folder'
version?: number
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
}
isRootFolder: boolean
customTerminalBreadcrumb?: string
+1 -1
View File
@@ -1 +1 @@
export const APP_VERSION = '0.5.0'
export const APP_VERSION = '0.5.1'
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@shumai/workflow-core",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"type": "module",
"main": "./src/index.ts",
@@ -66,6 +66,10 @@ export class TemporalExecutor implements Executor {
workflowName = 'transcodeWatermarkWorkflow'
taskQueue = TaskQueueTranscode
break
case WorkflowTaskType.transcode_3d:
workflowName = 'transcode3dWorkflow'
taskQueue = TaskQueueTranscode
break
default:
throw new Error(`Unknown task type: ${task.type}`)
}
+2 -2
View File
@@ -70,7 +70,7 @@ export function getActivities<T = any>(): T {
// Temporal's proxyActivities requires a type parameter, so we use any for generic activities.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
baseProxy = wf.proxyActivities<any>({
startToCloseTimeout: '10 minutes',
startToCloseTimeout: '120 minutes',
retry: {
maximumAttempts: 5,
initialInterval: '10s',
@@ -165,7 +165,7 @@ export async function executeActivity(
if (isTemporal()) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handle = wf.proxyActivities<any>({
startToCloseTimeout: '10 minutes',
startToCloseTimeout: '120 minutes',
taskQueue: queue,
retry: {
maximumAttempts: 5,
+1
View File
@@ -13,6 +13,7 @@ const depsToExtract = [
'@temporalio/client',
'@temporalio/worker',
'@temporalio/workflow',
'exiftool-vendored',
'pdfkit',
'prisma',
'sharp',