Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

start revising the video preview generation to be frame based

Scott Petrovicdb167ee1c1af
diff --git a/package-lock.json b/package-lock.json
index 9c59fa0..0d15fbd 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,6 +11,7 @@
"@comfyorg/fbx-exporter-three": "^1.0.2",
"file-saver": "^2.0.5",
"jszip": "^3.10.2",
+ "mediabunny": "^1.65.2",
"three": "^0.187.0",
"tippy.js": "^6.3.7",
"vite-plugin-glsl": "^1.6.2",
@@ -1810,6 +1811,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/dom-mediacapture-transform": {
+ "version": "0.1.12",
+ "resolved": "https://registry.npmjs.org/@types/dom-mediacapture-transform/-/dom-mediacapture-transform-0.1.12.tgz",
+ "integrity": "sha512-d7/QsLRwF864A5mgIM/YrfiglHoYn7zgCcAoJgW404r+2DwnNr7EBbLnCWpmOMgH8y0te73L1AV6H1bmauaWFw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/dom-webcodecs": "*"
+ }
+ },
+ "node_modules/@types/dom-webcodecs": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/@types/dom-webcodecs/-/dom-webcodecs-0.1.13.tgz",
+ "integrity": "sha512-O5hkiFIcjjszPIYyUSyvScyvrBoV3NOEEZx/pMlsu44TKzWNkLVBBxnxJz42in5n3QIolYOcBYFCPZZ0h8SkwQ==",
+ "license": "MIT"
+ },
"node_modules/@types/esrecurse": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz",
@@ -1837,6 +1853,7 @@
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
"devOptional": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"undici-types": "~8.9.0"
}
@@ -1854,6 +1871,7 @@
"integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==",
"devOptional": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@dimforge/rapier3d-compat": "~0.12.0",
"@tweenjs/tween.js": "~23.1.3",
@@ -1915,6 +1933,7 @@
"integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.72.1",
"@typescript-eslint/types": "8.72.1",
@@ -2106,6 +2125,7 @@
"integrity": "sha512-OY9aShBQG5KOIw2zCo9fDoCHI9RHliNHJ//nM7m6jGg41Hyke9JOGWmeMlK74xYErsxMoK8mIB3gAeEyFVA7LA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@bcoe/v8-coverage": "^1.0.2",
"@vitest/istanbul-lib-coverage": "^2.1.0",
@@ -2209,6 +2229,7 @@
"integrity": "sha512-00S3x4NRmqIBUiTVWF9/xLaA9EP9KeKv0+1sBO7e2Y4luBISlW+2ttnhlk/zjbTqEvVhJWCCo7MXzu6zNbefqQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@vitest/utils": "5.1.0",
"fflate": "^0.8.3",
@@ -2245,6 +2266,7 @@
"integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -2512,6 +2534,7 @@
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
"hasInstallScript": true,
"license": "MIT",
+ "peer": true,
"bin": {
"esbuild": "bin/esbuild"
},
@@ -2566,6 +2589,7 @@
"integrity": "sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==",
"dev": true,
"license": "MIT",
+ "peer": true,
"workspaces": [
"packages/*"
],
@@ -3103,6 +3127,7 @@
"integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@keyv/serialize": "^1.1.1"
}
@@ -3436,6 +3461,24 @@
"source-map-js": "^1.2.1"
}
},
+ "node_modules/mediabunny": {
+ "version": "1.65.2",
+ "resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.65.2.tgz",
+ "integrity": "sha512-goZpibvo/5hkc/56WVNm93Ini+o7K4y8aXA20c/BN1B+m3L5aHQa8MTvO+S1APg/YI8kMILtrX6QCqUtxLW7bA==",
+ "license": "MPL-2.0",
+ "workspaces": [
+ ".",
+ "packages/*"
+ ],
+ "dependencies": {
+ "@types/dom-mediacapture-transform": "^0.1.11",
+ "@types/dom-webcodecs": "0.1.13"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/Vanilagy"
+ }
+ },
"node_modules/meshoptimizer": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz",
@@ -3939,7 +3982,8 @@
"version": "0.187.0",
"resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz",
"integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==",
- "license": "MIT"
+ "license": "MIT",
+ "peer": true
},
"node_modules/tinybench": {
"version": "6.2.3",
@@ -4091,6 +4135,7 @@
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
"dev": true,
"license": "Apache-2.0",
+ "peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -4144,6 +4189,7 @@
"resolved": "https://registry.npmjs.org/unenv/-/unenv-2.0.0-rc.24.tgz",
"integrity": "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"pathe": "^2.0.3"
}
@@ -4169,6 +4215,7 @@
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.6.tgz",
"integrity": "sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"lightningcss": "^1.33.0",
"picomatch": "^4.0.7",
@@ -4270,6 +4317,7 @@
"integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@types/chai": "^5.2.2",
"@vitest/mocker": "5.1.0",
@@ -4440,6 +4488,7 @@
"integrity": "sha512-JuiKY9k/4V4UE2xsupaTvZ1SF6o2a8sg+/zfq/DaSDwvH+o7t2ZEFuIWNEnryfeFdP47/tz/p828Kvl4ptPlrA==",
"hasInstallScript": true,
"license": "Apache-2.0",
+ "peer": true,
"bin": {
"workerd": "bin/workerd"
},
diff --git a/package.json b/package.json
index 1609957..1500792 100644
--- a/package.json
+++ b/package.json
@@ -30,6 +30,7 @@
"@comfyorg/fbx-exporter-three": "^1.0.2",
"file-saver": "^2.0.5",
"jszip": "^3.10.2",
+ "mediabunny": "^1.65.2",
"three": "^0.187.0",
"tippy.js": "^6.3.7",
"vite-plugin-glsl": "^1.6.2",
diff --git a/src/preview-generator/PreviewClipEncoder.ts b/src/preview-generator/PreviewClipEncoder.ts
new file mode 100644
index 0000000..ea50ea2
--- /dev/null
+++ b/src/preview-generator/PreviewClipEncoder.ts
@@ -0,0 +1,95 @@
+import { BufferTarget, EncodedPacket, EncodedVideoPacketSource, Mp4OutputFormat, Output } from 'mediabunny'
+
+interface EncodedChunkEntry {
+ chunk: EncodedVideoChunk
+ meta: EncodedVideoChunkMetadata | undefined
+}
+
+/**
+ * Encodes one preview clip to an H.264 MP4 with WebCodecs. Frames are given explicit timestamps,
+ * so the output always has a constant frame rate and exactly the frames that were added,
+ * no matter how long rendering takes.
+ */
+export class PreviewClipEncoder {
+ // Constrained Baseline, level 3.1. Plays everywhere H.264 does (Safari/iOS included)
+ public static readonly codec: string = 'avc1.42E01F'
+
+ private readonly width: number
+ private readonly height: number
+ private readonly fps: number
+ private readonly encoder: VideoEncoder
+ private readonly chunks: EncodedChunkEntry[] = []
+ private encoder_error: Error | null = null
+ private frame_index: number = 0
+
+ public static async is_supported (width: number, height: number): Promise<boolean> {
+ if (typeof VideoEncoder === 'undefined') {
+ return false
+ }
+ const support = await VideoEncoder.isConfigSupported({ codec: PreviewClipEncoder.codec, width, height })
+ return support.supported === true
+ }
+
+ constructor (width: number, height: number, fps: number, bitrate: number) {
+ this.width = width
+ this.height = height
+ this.fps = fps
+
+ this.encoder = new VideoEncoder({
+ output: (chunk, meta) => { this.chunks.push({ chunk, meta }) },
+ error: (error) => { this.encoder_error = error }
+ })
+ this.encoder.configure({
+ codec: PreviewClipEncoder.codec,
+ width,
+ height,
+ bitrate,
+ framerate: fps,
+ avc: { format: 'avc' } // length-prefixed NAL units, which is what MP4 expects
+ })
+ }
+
+ /** Encodes a top-down RGBA buffer of width x height as the next frame */
+ public add_frame (rgba_pixels: Uint8Array): void {
+ const frame_duration_us = 1_000_000 / this.fps
+ const frame = new VideoFrame(rgba_pixels, {
+ format: 'RGBA',
+ codedWidth: this.width,
+ codedHeight: this.height,
+ timestamp: Math.round(this.frame_index * frame_duration_us),
+ duration: Math.round(frame_duration_us)
+ })
+ // first frame is a key frame so the video can start (and loop) cleanly
+ this.encoder.encode(frame, { keyFrame: this.frame_index === 0 })
+ frame.close()
+ this.frame_index++
+ }
+
+ /** Finishes encoding and returns the MP4 file */
+ public async finish (file_name: string): Promise<File> {
+ await this.encoder.flush()
+ this.encoder.close()
+ if (this.encoder_error !== null) {
+ throw this.encoder_error
+ }
+
+ const output = new Output({
+ format: new Mp4OutputFormat({ fastStart: 'in-memory' }), // metadata up front so playback can start right away
+ target: new BufferTarget()
+ })
+ const video_source = new EncodedVideoPacketSource('avc')
+ output.addVideoTrack(video_source, { frameRate: this.fps })
+ await output.start()
+
+ for (const { chunk, meta } of this.chunks) {
+ await video_source.add(EncodedPacket.fromEncodedChunk(chunk), meta)
+ }
+ await output.finalize()
+
+ const buffer = (output.target as BufferTarget).buffer
+ if (buffer === null) {
+ throw new Error('MP4 muxer produced no data for ' + file_name)
+ }
+ return new File([buffer], file_name, { type: 'video/mp4' })
+ }
+}
diff --git a/src/preview-generator/PreviewFrameCapture.ts b/src/preview-generator/PreviewFrameCapture.ts
new file mode 100644
index 0000000..4275181
--- /dev/null
+++ b/src/preview-generator/PreviewFrameCapture.ts
@@ -0,0 +1,155 @@
+import * as THREE from 'three'
+
+/**
+ * Renders a scene into a small off-screen canvas and reads the pixels back as RGBA buffers.
+ * The scene is rendered at a supersampled size and box-filtered down on the CPU for smoother edges.
+ *
+ * Why it works this way:
+ * - Pixels are read back instead of creating a VideoFrame from the canvas. Canvas-backed VideoFrames
+ * are paced to the display refresh rate (~16ms each) when encoding, while RGBA buffers encode almost instantly.
+ * - A plain readPixels call waits for a full round trip to the GPU (~7ms). Instead, frames are read into
+ * pixel buffer objects in batches and the GPU is waited on once per batch, which costs well under 1ms per frame.
+ *
+ * Usage: call queue_frame() up to `batch_size` times, then collect_frames() to get the pixels in the same order.
+ */
+export class PreviewFrameCapture {
+ public readonly width: number
+ public readonly height: number
+ public readonly batch_size: number
+
+ private readonly supersample: number
+ private readonly full_width: number
+ private readonly full_height: number
+ private readonly renderer: THREE.WebGLRenderer
+ private readonly gl: WebGL2RenderingContext
+ private readonly pixel_buffers: WebGLBuffer[]
+ private readonly full_pixels: Uint8Array
+ private queued_count: number = 0
+
+ constructor (width: number, height: number, supersample: number = 2, batch_size: number = 32) {
+ this.width = width
+ this.height = height
+ this.supersample = supersample
+ this.batch_size = batch_size
+ this.full_width = width * supersample
+ this.full_height = height * supersample
+
+ const canvas = new OffscreenCanvas(this.full_width, this.full_height)
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true })
+ this.renderer.setPixelRatio(1)
+ this.renderer.setSize(this.full_width, this.full_height, false)
+ this.renderer.shadowMap.enabled = true
+ this.renderer.toneMapping = THREE.ACESFilmicToneMapping
+ this.renderer.toneMappingExposure = 2.0
+
+ this.gl = this.renderer.getContext() as WebGL2RenderingContext
+ const buffer_bytes = this.full_width * this.full_height * 4
+ this.full_pixels = new Uint8Array(buffer_bytes)
+ this.pixel_buffers = []
+ for (let i = 0; i < batch_size; i++) {
+ const buffer = this.gl.createBuffer()
+ this.gl.bindBuffer(this.gl.PIXEL_PACK_BUFFER, buffer)
+ this.gl.bufferData(this.gl.PIXEL_PACK_BUFFER, buffer_bytes, this.gl.STREAM_READ)
+ this.pixel_buffers.push(buffer)
+ }
+ this.gl.bindBuffer(this.gl.PIXEL_PACK_BUFFER, null)
+ }
+
+ /**
+ * The video has no alpha channel, so the canvas is cleared to an opaque color
+ * (the floor color) instead of being transparent.
+ */
+ public set_background_color (color: THREE.ColorRepresentation): void {
+ this.renderer.setClearColor(color, 1)
+ }
+
+ public is_batch_full (): boolean {
+ return this.queued_count >= this.batch_size
+ }
+
+ /** Renders the scene as it is now and queues its pixels to be read back by collect_frames() */
+ public queue_frame (scene: THREE.Scene, camera: THREE.Camera): void {
+ if (this.is_batch_full()) {
+ throw new Error('Frame batch is full. Call collect_frames() first.')
+ }
+ this.renderer.render(scene, camera)
+ this.gl.bindBuffer(this.gl.PIXEL_PACK_BUFFER, this.pixel_buffers[this.queued_count])
+ this.gl.readPixels(0, 0, this.full_width, this.full_height, this.gl.RGBA, this.gl.UNSIGNED_BYTE, 0)
+ this.gl.bindBuffer(this.gl.PIXEL_PACK_BUFFER, null)
+ this.queued_count++
+ }
+
+ /** Waits for the GPU to finish the queued frames and returns them as top-down RGBA buffers of width x height */
+ public async collect_frames (): Promise<Uint8Array[]> {
+ if (this.queued_count === 0) {
+ return []
+ }
+
+ const sync = this.gl.fenceSync(this.gl.SYNC_GPU_COMMANDS_COMPLETE, 0)
+ if (sync === null) {
+ throw new Error('Could not create a WebGL fence to wait for frames')
+ }
+ this.gl.flush()
+ await this.wait_for_sync(sync)
+ this.gl.deleteSync(sync)
+
+ const frames: Uint8Array[] = []
+ for (let i = 0; i < this.queued_count; i++) {
+ this.gl.bindBuffer(this.gl.PIXEL_PACK_BUFFER, this.pixel_buffers[i])
+ this.gl.getBufferSubData(this.gl.PIXEL_PACK_BUFFER, 0, this.full_pixels)
+ frames.push(this.downsample(this.full_pixels))
+ }
+ this.gl.bindBuffer(this.gl.PIXEL_PACK_BUFFER, null)
+ this.queued_count = 0
+ return frames
+ }
+
+ private async wait_for_sync (sync: WebGLSync): Promise<void> {
+ while (true) {
+ const status = this.gl.clientWaitSync(sync, 0, 0)
+ if (status === this.gl.ALREADY_SIGNALED || status === this.gl.CONDITION_SATISFIED) {
+ return
+ }
+ if (status === this.gl.WAIT_FAILED) {
+ throw new Error('Waiting for the GPU to finish rendering preview frames failed')
+ }
+ await new Promise(resolve => setTimeout(resolve, 1))
+ }
+ }
+
+ /**
+ * Box-filters the supersampled frame down to the output size. readPixels rows go bottom-up, so it is
+ * flipped vertically as well. A new buffer is returned since the VideoFrame that wraps it may outlive this call.
+ */
+ private downsample (full_pixels: Uint8Array): Uint8Array {
+ const ss = this.supersample
+ const samples_per_pixel = ss * ss
+ const output = new Uint8Array(this.width * this.height * 4)
+ for (let y = 0; y < this.height; y++) {
+ for (let x = 0; x < this.width; x++) {
+ let r = 0; let g = 0; let b = 0
+ for (let dy = 0; dy < ss; dy++) {
+ const source_row = this.full_height - 1 - (y * ss + dy)
+ let index = (source_row * this.full_width + x * ss) * 4
+ for (let dx = 0; dx < ss; dx++) {
+ r += full_pixels[index]
+ g += full_pixels[index + 1]
+ b += full_pixels[index + 2]
+ index += 4
+ }
+ }
+ const out_index = (y * this.width + x) * 4
+ output[out_index] = r / samples_per_pixel
+ output[out_index + 1] = g / samples_per_pixel
+ output[out_index + 2] = b / samples_per_pixel
+ output[out_index + 3] = 255
+ }
+ }
+ return output
+ }
+
+ public dispose (): void {
+ this.pixel_buffers.forEach((buffer) => { this.gl.deleteBuffer(buffer) })
+ this.renderer.dispose()
+ }
+}
diff --git a/src/preview-generator/README.md b/src/preview-generator/README.md
index a0173df..e14c0ed 100644
--- a/src/preview-generator/README.md
+++ b/src/preview-generator/README.md
@@ -1,20 +1,30 @@
# Preview Generator
-The goal of this preview generator is to create small animated clip previews to use in the animation listing. It is fully done in the web browser. So that is the only "tool" needed.
+The goal of this preview generator is to create small animated clip previews to use in the animation listing. It is fully done in the web browser. So that is the only "tool" needed. It needs a browser with WebCodecs H.264 encoding (Chrome or Edge).
## Workflow
1. Go to the URL manually for the preview generator once the web server is started (command: npm run dev): http://localhost:5173/preview-generator/index.html
2. Select a 3d model that you want to generate animations from the drop-down.
-3. Rotate and position the 3d model
+3. The camera is automatically fit so every pose of every animation stays in view (backflips, jumps, etc.). Rotate or zoom to adjust it if needed. "Fit camera" re-runs the fit from the current viewing angle. The same camera is used for every animation so the previews stay uniform.
4. Press the record button
-5. Wait for all the animations to finish playing/recording. A ZIP file will be downloaded when they are all done
-6. Place the animation preview webm files in the static/animpreviews folder. Each skeleton type has its own folder.
+5. Wait for the status line to say it is done. A ZIP file will be downloaded with a light and dark preview for every animation
+6. Place the animation preview mp4 files in the static/animpreviews folder. Each skeleton type has its own folder.
## Tech talk
In step 1 of the workflow, the model/animation selection pulls the GLB files from the static/animations folder. These files have all the animations as well as a skinned mesh, so we can focus on recording and not skinning.
-The recording is all done with the "MediaRecorder API" that is a vanilla javascript API. The JSZIP javascript package does the zipping behavior.
+Animations are not recorded in real time. For every frame, the animation is posed with `mixer.setTime()`, rendered to an off-screen canvas for each theme, and encoded with the WebCodecs `VideoEncoder` using exact timestamps. The `mediabunny` package writes the MP4 file and JSZip does the zipping. Because of this:
-The canvas size on the preview-generator is hard-coded in the preview-generator.ts file. The display on the preview generator is larger than the result will be, but it is easier to position when the canvas size is larger. The UI in the application expects a certain size the previews will be in. This helps with the lazy loading and the preview sizes are hard-coded in the Mesh2Motion app itself in CSS.
\ No newline at end of file
+- Every preview has exactly the frames of its animation at a constant 24 fps, no matter how fast the computer is or whether the tab is in the background.
+- Looping animations leave out their last frame (it matches the first) so the loop is seamless. One-shot animations keep it.
+- The light and dark previews show the same pose on the same frame.
+- The whole human library (230+ animations, both themes) takes around 20 seconds instead of several minutes.
+
+Implementation notes:
+
+- `PreviewFrameCapture.ts` renders at 2x the preview size and box-filters down for anti-aliasing. Pixels are read back in batches through pixel buffer objects. A plain `readPixels` call waits on the GPU every frame and creating a `VideoFrame` straight from the canvas is limited to the display refresh rate. Both are many times slower.
+- `PreviewClipEncoder.ts` encodes H.264 Constrained Baseline, which plays on every OS and browser.
+
+The canvas size on the preview-generator is hard-coded in the preview-generator.ts file. The display on the preview generator is larger than the result will be, but it is easier to position when the canvas size is larger. The UI in the application expects a certain size the previews will be in. This helps with the lazy loading and the preview sizes are hard-coded in the Mesh2Motion app itself in CSS.
diff --git a/src/preview-generator/index.html b/src/preview-generator/index.html
index efe4c1b..ab63b11 100644
--- a/src/preview-generator/index.html
+++ b/src/preview-generator/index.html
@@ -11,7 +11,12 @@
<script type="module" src="./preview-generator.ts"></script>
<link href="../styles.css" rel="stylesheet" crossorigin="anonymous" />
- <button id="record-button" style="position: absolute; top: 20px; right: 20px;">Record</button>
+ <div style="position: absolute; top: 20px; right: 20px; display: flex; gap: 8px;">
+ <button id="fit-camera-button" title="Zoom the camera so every pose of every animation fits in the preview">Fit camera</button>
+ <button id="record-button">Record</button>
+ </div>
+
+ <div id="record-status" style="position: absolute; bottom: 20px; left: 20px; right: 20px;"></div>
<select id="animation-file-dropdown" style="position: absolute; top: 20px; left: 20px;">
<!-- populated dynamically from RigConfig -->
diff --git a/src/preview-generator/mp4-recorder.ts b/src/preview-generator/mp4-recorder.ts
deleted file mode 100644
index 8a3c604..0000000
--- a/src/preview-generator/mp4-recorder.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import * as THREE from 'three'
-
-export class MP4Recorder {
- public width: number
- public height: number
- public fps: number = 24
- public kbps: number = 2600
-
- public readonly recorded_files: File[] = []
- private readonly renderer_ref: THREE.WebGLRenderer
-
- private old_size: THREE.Vector2 | null = null
- private old_pr: number | null = null
- private recorder: MediaRecorder | null = null
- private chunks: Blob[] = []
- private stopped_promise: Promise<void> | null = null
- private stopped_resolve: (() => void) | null = null
- private file_name: string = ''
- private active_mime_type: string = 'video/mp4'
-
- public static is_mp4_recording_supported (): boolean {
- return MP4Recorder.supported_mp4_mime_type_static() !== null
- }
-
- constructor (renderer: THREE.WebGLRenderer, preview_width: number, preview_height: number) {
- this.renderer_ref = renderer
- this.width = preview_width
- this.height = preview_height
-
- console.log(this.renderer_ref.domElement.height, this.renderer_ref.domElement.width)
- }
-
- public start (saved_name: string): void {
- const mime_type = this.supported_mp4_mime_type()
- if (mime_type === null) {
- throw new Error('MP4 recording is not supported by MediaRecorder in this browser')
- }
-
- this.old_size = this.renderer_ref.getSize(new THREE.Vector2())
- this.old_pr = this.renderer_ref.getPixelRatio()
- this.renderer_ref.setPixelRatio(1)
- this.renderer_ref.setSize(this.width, this.height, false)
- this.file_name = saved_name
- this.active_mime_type = mime_type
-
- const stream: MediaStream = this.renderer_ref.domElement.captureStream(this.fps)
- this.recorder = new MediaRecorder(stream, {
- mimeType: this.active_mime_type,
- videoBitsPerSecond: this.kbps * 1000
- })
- this.chunks = []
- this.recorder.ondataavailable = e => (e.data.size !== 0) && this.chunks.push(e.data)
- this.stopped_promise = new Promise<void>(resolve => {
- this.stopped_resolve = resolve
- this.recorder!.onstop = () => { resolve() }
- })
- this.recorder.start()
- }
-
- public async stop (): Promise<File> {
- if (!this.recorder) throw new Error('Recorder not started')
- this.recorder.stop()
- if (this.stopped_promise) {
- await this.stopped_promise
- }
- // restore the renderer size and pixel ratio
- if (this.old_size && this.old_pr !== null) {
- this.renderer_ref.setSize(this.old_size.x, this.old_size.y, false)
- this.renderer_ref.setPixelRatio(this.old_pr)
- }
- const file = new File(this.chunks, this.file_name, { type: this.active_mime_type })
- this.recorder = null
- this.stopped_promise = null
- this.stopped_resolve = null
- this.chunks = []
- return file
- }
-
- private supported_mp4_mime_type (): string | null {
- return MP4Recorder.supported_mp4_mime_type_static()
- }
-
- private static supported_mp4_mime_type_static (): string | null {
- const prefs = [
- 'video/mp4;codecs=avc1.64001F,mp4a.40.2',
- 'video/mp4;codecs=avc1',
- 'video/mp4'
- ]
- return prefs.find(m => MediaRecorder.isTypeSupported(m)) ?? null
- }
-}
diff --git a/src/preview-generator/preview-generator.ts b/src/preview-generator/preview-generator.ts
index 3c6df4d..9ef1c4e 100644
--- a/src/preview-generator/preview-generator.ts
+++ b/src/preview-generator/preview-generator.ts
@@ -3,18 +3,40 @@ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
-import { WebMRecorder } from './webm-recorder.ts'
-import { MP4Recorder } from './mp4-recorder.ts'
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
+import { PreviewFrameCapture } from './PreviewFrameCapture.ts'
+import { PreviewClipEncoder } from './PreviewClipEncoder.ts'
+
import { Generators } from '../lib/Generators.ts'
import { ThemeManager } from '../lib/ThemeManager.ts'
import { AnimationUtility } from '../lib/processes/animations-listing/AnimationUtility.ts'
import { DOMUtilities } from '../lib/DOMUtilities.ts'
import { SkeletonType } from '../lib/enums/SkeletonType.ts'
-import { RigConfig } from '../lib/RigConfig.ts'
+import { RigConfig, type RigAnimation } from '../lib/RigConfig.ts'
+
+type ThemeName = 'light' | 'dark'
+
+interface ThemeEnvironment {
+ theme: ThemeName
+ container: THREE.Group
+ floor_color: number
+}
+interface PreviewClip {
+ clip: THREE.AnimationClip
+ loop: boolean
+}
+
+/**
+ * Generates the small looping MP4 previews shown in the animation listing.
+ *
+ * Animations are not recorded in real time. Each frame is posed with mixer.setTime(),
+ * rendered off-screen, and handed to a WebCodecs encoder with an exact timestamp. Every
+ * preview gets exactly the frames of its clip at a constant frame rate, both themes are
+ * rendered from the same pose, and generation runs as fast as the GPU allows.
+ */
class PreviewGenerator {
private readonly renderer_: THREE.WebGLRenderer
private readonly scene_: THREE.Scene
@@ -24,89 +46,85 @@ class PreviewGenerator {
private readonly clock_: THREE.Clock
public readonly theme_manager: ThemeManager
- private readonly recorder: WebMRecorder | MP4Recorder
- private readonly recording_extension: string
- private readonly zip: JSZip
+ private readonly theme_environments: ThemeEnvironment[]
- private environment_container: THREE.Group
- private new_skinned_mesh: THREE.SkinnedMesh
- private animation_clips: THREE.AnimationClip[] = []
+ private skinned_mesh: THREE.SkinnedMesh | null = null
+ private preview_clips: PreviewClip[] = []
+ private is_recording: boolean = false
- private current_animation_index_processing: number = 0
-
- private readonly preview_height: number = 120
+ // size of the preview videos. The app's CSS expects this size
private readonly preview_width: number = 100
+ private readonly preview_height: number = 120
+ private readonly preview_fps: number = 24 // the library animations are authored at 24 fps
+ private readonly preview_bitrate: number = 250_000
+
+ private readonly status_element: HTMLElement | null = document.getElementById('record-status')
constructor () {
- // Setup renderer, scene, camera
this.renderer_ = new THREE.WebGLRenderer({ antialias: true, alpha: true })
- this.renderer_.shadowMap.enabled = true // Enable shadows
- if (MP4Recorder.is_mp4_recording_supported()) {
- this.recorder = new MP4Recorder(this.renderer_, this.preview_width, this.preview_height)
- this.recording_extension = 'mp4'
- console.info('Using MP4 preview recorder')
- } else {
- this.recorder = new WebMRecorder(this.renderer_, this.preview_width, this.preview_height)
- this.recording_extension = 'webm'
- console.info('Using WebM preview recorder (MP4 unsupported by this browser)')
- }
-
- // Set Filmic tone mapping for less saturated, more cinematic look
+ this.renderer_.shadowMap.enabled = true
this.renderer_.toneMapping = THREE.ACESFilmicToneMapping // a bit softer of a look
this.renderer_.toneMappingExposure = 2.0 // tweak this value for brightness
-
document.body.appendChild(this.renderer_.domElement)
this.theme_manager = new ThemeManager()
- this.zip = new JSZip()
- this.environment_container = new THREE.Group()
-
this.scene_ = new THREE.Scene()
this.camera_ = Generators.create_camera()
- this.regenerate_floor_grid()
+ // both theme environments live in the scene. Only one is visible at a time
+ this.theme_environments = [this.create_theme_environment('dark'), this.create_theme_environment('light')]
+ this.theme_environments.forEach((environment) => this.scene_.add(environment.container))
+ this.show_theme_environment(this.theme_manager.get_current_theme())
- // set the canvas size and aspect ratio, otherwise distortion happens for models
- // we are adding a multiplier so the preview is higher resolution and easier to position
- const preview_multiplier: number = 4
- this.renderer_.setSize(this.preview_width * preview_multiplier, this.preview_height * preview_multiplier)
- this.camera_.aspect = (this.preview_width * preview_multiplier) / (this.preview_height * preview_multiplier)
+ // the on-screen canvas is a larger version of the preview, with the same aspect ratio, to make positioning easier
+ const display_multiplier: number = 4
+ this.renderer_.setSize(this.preview_width * display_multiplier, this.preview_height * display_multiplier)
+ this.camera_.aspect = this.preview_width / this.preview_height
this.camera_.updateProjectionMatrix()
-
- // Add orbit controls
this.controls_ = new OrbitControls(this.camera_, this.renderer_.domElement)
this.controls_.target.set(0, 0.4, 0)
- this.controls_.minDistance = 5
- this.controls_.maxDistance = 30
+ this.controls_.minDistance = 1
+ this.controls_.maxDistance = 100
this.controls_.update()
this.clock_ = new THREE.Clock()
}
- public regenerate_floor_grid (): void {
- // remove previous setup objects from scene if they exist
- const setup_container = this.scene_.getObjectByName('Setup objects')
- if (setup_container !== null) {
- this.scene_.remove(setup_container)
- }
-
- // change color of grid based on theme
+ private create_theme_environment (theme: ThemeName): ThemeEnvironment {
let grid_color = 0x4b6368
let floor_color = 0x2d4353
let light_strength: number = 10
- if (this.theme_manager.get_current_theme() === 'light') {
- grid_color = 0xcccccc // light theme color
- floor_color = 0xecf0f1 // light theme color
+ if (theme === 'light') {
+ grid_color = 0xcccccc
+ floor_color = 0xecf0f1
light_strength = 14
}
- this.scene_.fog = new THREE.Fog(floor_color, 20, 80)
- this.environment_container = new THREE.Group()
- this.environment_container.name = 'Setup objects'
- this.environment_container.add(...Generators.create_default_lights(light_strength))
- this.environment_container.add(...Generators.create_grid_helper(grid_color, floor_color))
- this.scene_.add(this.environment_container)
+ const container = new THREE.Group()
+ container.name = `Setup objects (${theme})`
+ container.add(...Generators.create_default_lights(light_strength))
+ container.add(...Generators.create_grid_helper(grid_color, floor_color))
+ return { theme, container, floor_color }
+ }
+
+ private show_theme_environment (theme: ThemeName): ThemeEnvironment {
+ let shown: ThemeEnvironment | undefined
+ this.theme_environments.forEach((environment) => {
+ environment.container.visible = environment.theme === theme
+ if (environment.container.visible) {
+ shown = environment
+ }
+ })
+ if (shown === undefined) {
+ throw new Error('No environment for theme ' + theme)
+ }
+ if (this.scene_.fog instanceof THREE.Fog) {
+ this.scene_.fog.color.set(shown.floor_color)
+ } else {
+ this.scene_.fog = new THREE.Fog(shown.floor_color, 20, 80)
+ }
+ return shown
}
public initialize (skeleton_type: SkeletonType): void {
@@ -116,133 +134,215 @@ class PreviewGenerator {
return
}
+ this.set_status('Loading model and animations...')
+
// page lives one folder below the static root
// animation GLBs from the asset library are meshopt compressed
const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder)
- const clip_promises = rig.animations.map(async (animation) => {
+ const clip_promises = rig.animations.map(async (animation: RigAnimation): Promise<PreviewClip | null> => {
const clip_gltf = await loader.loadAsync('../' + animation.file)
- return clip_gltf.animations[0]
+ const clip = clip_gltf.animations[0]
+ return clip === undefined ? null : { clip, loop: animation.loop }
})
- loader.load('../' + rig.model_file, async (gltf) => {
- this.scene_.add(gltf.scene)
- const animation_clips = (await Promise.all(clip_promises)).filter((clip) => clip !== undefined)
-
- // Find the first SkinnedMesh
- gltf.scene.traverse((child: any) => {
- if (child.isSkinnedMesh) {
- this.new_skinned_mesh = child
- this.new_skinned_mesh.castShadow = true // Enable shadow casting for mesh
+ loader.load('../' + rig.model_file, (gltf) => {
+ void (async () => {
+ this.scene_.add(gltf.scene)
+ this.preview_clips = (await Promise.all(clip_promises)).filter((entry) => entry !== null)
+
+ gltf.scene.traverse((child: THREE.Object3D) => {
+ if (child instanceof THREE.SkinnedMesh) {
+ this.skinned_mesh = child
+ child.castShadow = true
+ }
+ if (child instanceof THREE.Mesh) {
+ child.receiveShadow = true
+ }
+ })
+
+ if (this.skinned_mesh === null || this.preview_clips.length === 0) {
+ this.set_status('No skinned mesh or animations found for this rig')
+ return
}
- if (child.isMesh) {
- child.receiveShadow = true // Let all meshes receive shadows (e.g., grid/floor)
- }
- })
-
- if (this.new_skinned_mesh && animation_clips.length > 0) {
- this.mixer_ = new THREE.AnimationMixer(this.new_skinned_mesh)
- this.animation_clips = animation_clips
+ this.mixer_ = new THREE.AnimationMixer(this.skinned_mesh)
- // remove all root motion data.
- // This is the same function that the animation listing done
+ // remove all root motion data. This is the same function that the animation listing uses
// TODO: with cleaning up data, the fox sitting has a weird height offset
// I would think the cleanup should work with all skeleton types
if (skeleton_type === SkeletonType.Human) {
- AnimationUtility.clean_track_data(this.animation_clips, rig.position_tracking_bone_name)
+ AnimationUtility.clean_track_data(this.preview_clips.map(entry => entry.clip), rig.position_tracking_bone_name)
}
- const clip = this.animation_clips[0]
- const action = this.mixer_.clipAction(clip)
- action.reset()
- action.play()
+ this.fit_camera_to_animations()
+ this.play_display_clip()
this.animate_()
- }
- }) // end GLTF loading
+ this.set_status(`${this.preview_clips.length} animations loaded. Adjust the camera, then press Record.`)
+ })()
+ })
- // setup event listener for record button
- const record_button = document.getElementById('record-button')
- record_button?.addEventListener('click', () => {
+ document.getElementById('record-button')?.addEventListener('click', () => {
void this.start_recording()
})
+ document.getElementById('fit-camera-button')?.addEventListener('click', () => {
+ this.fit_camera_to_animations()
+ })
+ }
+
+ private play_display_clip (): void {
+ if (this.mixer_ === null) return
+ this.mixer_.stopAllAction()
+ const action = this.mixer_.clipAction(this.preview_clips[0].clip)
+ action.setLoop(THREE.LoopRepeat, Infinity)
+ action.clampWhenFinished = false
+ action.reset().play()
+ }
+
+ /**
+ * Some animations move far from their starting pose (backflips, jumps, lunges), so the camera is fit to
+ * the bounds of every pose across all animations, not just the rest pose. The current viewing angle is kept,
+ * so the camera can still be orbited after fitting.
+ */
+ private fit_camera_to_animations (): void {
+ if (this.mixer_ === null || this.skinned_mesh === null) return
+
+ const samples_per_clip = 8
+ const all_poses_bounds = new THREE.Box3()
+ const pose_bounds = new THREE.Box3()
+
+ for (const { clip } of this.preview_clips) {
+ this.mixer_.stopAllAction()
+ this.mixer_.clipAction(clip).reset().play()
+ for (let i = 0; i <= samples_per_clip; i++) {
+ this.mixer_.setTime((clip.duration * i) / samples_per_clip)
+ this.skinned_mesh.updateMatrixWorld(true)
+ this.skinned_mesh.computeBoundingBox() // takes the current bone pose into account
+ pose_bounds.copy(this.skinned_mesh.boundingBox!).applyMatrix4(this.skinned_mesh.matrixWorld)
+ all_poses_bounds.union(pose_bounds)
+ }
+ }
+ this.play_display_clip()
+
+ const bounding_sphere = all_poses_bounds.getBoundingSphere(new THREE.Sphere())
+ const vertical_half_fov = THREE.MathUtils.degToRad(this.camera_.fov / 2)
+ const horizontal_half_fov = Math.atan(Math.tan(vertical_half_fov) * this.camera_.aspect)
+ const margin = 1.05
+ const distance = (bounding_sphere.radius * margin) / Math.sin(Math.min(vertical_half_fov, horizontal_half_fov))
+
+ const view_direction = this.camera_.position.clone().sub(this.controls_.target).normalize()
+ this.controls_.target.copy(bounding_sphere.center)
+ this.camera_.position.copy(bounding_sphere.center).addScaledVector(view_direction, distance)
+ this.controls_.update()
}
private async start_recording (): Promise<void> {
- if (this.new_skinned_mesh === null) {
- console.warn('Animation or animations not loaded yet.')
+ if (this.is_recording || this.mixer_ === null || this.skinned_mesh === null) {
+ console.warn('Animations not loaded yet, or already recording.')
+ return
+ }
+ if (!await PreviewClipEncoder.is_supported(this.preview_width, this.preview_height)) {
+ this.set_status('This browser does not support H.264 encoding with WebCodecs. Try Chrome or Edge.')
return
}
- // First pass: current theme
- this.current_animation_index_processing = 0 // reset counter if we do it again
- await this.process_animation_clip()
- // Switch theme and do a second pass
- this.theme_manager.toggle_theme()
- this.regenerate_floor_grid() // update grid/floor colors for new theme
- // Optionally, you may want to force a re-render or update other theme-dependent visuals here
+ this.is_recording = true
+ const start_time = performance.now()
+ const zip = new JSZip()
+ const capture = new PreviewFrameCapture(this.preview_width, this.preview_height)
+ let total_frames = 0
- this.current_animation_index_processing = 0
- await this.process_animation_clip()
+ try {
+ for (let clip_index = 0; clip_index < this.preview_clips.length; clip_index++) {
+ const { clip, loop } = this.preview_clips[clip_index]
+ this.set_status(`Recording ${clip_index + 1} / ${this.preview_clips.length}: ${clip.name}`)
- // zip up all the video results and download everything
- await this.generate_zip()
+ const files = await this.record_clip(capture, clip, loop)
+ files.forEach((file) => zip.file(file.name, file))
+ total_frames += files.length > 0 ? this.frame_count_for_clip(clip, loop) : 0
+ }
- console.log('finished successfully')
+ this.set_status('Zipping...')
+ const blob = await zip.generateAsync({ type: 'blob' })
+ saveAs(blob, 'animation-previews.zip')
+
+ const seconds = ((performance.now() - start_time) / 1000).toFixed(1)
+ this.set_status(`Done: ${this.preview_clips.length * this.theme_environments.length} previews (${total_frames} frames per theme) in ${seconds}s`)
+ } catch (error) {
+ console.error(error)
+ this.set_status('Recording failed: ' + String(error))
+ } finally {
+ capture.dispose()
+ this.show_theme_environment(this.theme_manager.get_current_theme())
+ this.play_display_clip()
+ this.is_recording = false
+ }
}
- private async process_animation_clip (): Promise<void> {
- // load up new animation to play
- const clip = this.animation_clips[this.current_animation_index_processing]
- const action: THREE.AnimationAction = this.mixer_.clipAction(clip)
-
- console.log('processing animation', this.current_animation_index_processing, clip.name)
+ /**
+ * A looping clip's last frame matches its first, so it is left out to keep the loop seamless.
+ * A one-shot clip keeps its last frame so the final pose is shown.
+ */
+ private frame_count_for_clip (clip: THREE.AnimationClip, loop: boolean): number {
+ const frame_intervals = Math.max(1, Math.round(clip.duration * this.preview_fps))
+ return loop ? frame_intervals : frame_intervals + 1
+ }
- action.setLoop(THREE.LoopOnce, 1)
- action.reset()
-
- // wait for the animation to finish
- await new Promise<void>(resolve => {
- const handler = async (e: any) => {
- this.mixer_.removeEventListener('finished', handler)
- // Stop recording after animation ends
- const file = await this.recorder.stop()
-
- // Start recording before playing the animation
- this.zip.file(file.name, file)
- resolve()
- }
- this.mixer_.removeEventListener('finished', handler)
- this.mixer_.addEventListener('finished', handler)
+ /** Records one clip in every theme. Each pose is rendered once per theme, so all themes match frame for frame */
+ private async record_clip (capture: PreviewFrameCapture, clip: THREE.AnimationClip, loop: boolean): Promise<File[]> {
+ if (this.mixer_ === null) return []
- const theme_name: string = this.theme_manager.get_current_theme()
- this.recorder.start(`${theme_name}_${clip.name}.${this.recording_extension}`)
- action.play()
- })
+ const encoders = this.theme_environments.map(() =>
+ new PreviewClipEncoder(this.preview_width, this.preview_height, this.preview_fps, this.preview_bitrate))
- // stop all animations in mixer
+ // play once and hold the last pose. With the default repeat, setTime(duration) wraps back to the first pose
this.mixer_.stopAllAction()
+ const action = this.mixer_.clipAction(clip)
+ action.setLoop(THREE.LoopOnce, 1)
+ action.clampWhenFinished = true
+ action.reset().play()
+
+ // frames are captured in batches. This remembers which theme's encoder each queued frame goes to
+ let queued_encoder_indexes: number[] = []
+ const send_batch_to_encoders = async (): Promise<void> => {
+ const frames = await capture.collect_frames()
+ frames.forEach((pixels, i) => { encoders[queued_encoder_indexes[i]].add_frame(pixels) })
+ queued_encoder_indexes = []
+ }
- this.current_animation_index_processing += 1
-
- // for testing a few, change to something small like 5
- const temp_limit = this.animation_clips.length
+ const frame_count = this.frame_count_for_clip(clip, loop)
+ for (let frame = 0; frame < frame_count; frame++) {
+ this.mixer_.setTime(Math.min(frame / this.preview_fps, clip.duration))
- if (this.current_animation_index_processing < temp_limit) {
- await this.process_animation_clip()
+ for (let index = 0; index < this.theme_environments.length; index++) {
+ if (capture.is_batch_full()) {
+ await send_batch_to_encoders()
+ }
+ const environment = this.theme_environments[index]
+ this.show_theme_environment(environment.theme)
+ capture.set_background_color(environment.floor_color)
+ capture.queue_frame(this.scene_, this.camera_)
+ queued_encoder_indexes.push(index)
+ }
}
+ await send_batch_to_encoders()
+
+ return await Promise.all(this.theme_environments.map(async (environment, index) =>
+ await encoders[index].finish(`${environment.theme}_${clip.name}.mp4`)))
}
- // Generate zip and trigger download
- private async generate_zip (): Promise<void> {
- const blob = await this.zip.generateAsync({ type: 'blob' })
- saveAs(blob, 'animation-previews.zip')
+ private set_status (message: string): void {
+ console.info(message)
+ if (this.status_element !== null) {
+ this.status_element.textContent = message
+ }
}
private readonly animate_ = (): void => {
requestAnimationFrame(this.animate_)
- if (this.mixer_) {
- this.mixer_.update(this.clock_.getDelta())
- }
+ // while recording, the recorder poses the model itself
+ if (this.is_recording) return
+
+ this.mixer_?.update(this.clock_.getDelta())
this.controls_.update()
this.renderer_.render(this.scene_, this.camera_)
}
@@ -256,7 +356,6 @@ if (animation_file_dropdown !== null) {
DOMUtilities.populate_animation_rig_select(animation_file_dropdown)
}
-// look out for select change
// don't start the application logic until we pick a model to use
animation_file_dropdown?.addEventListener('change', (event) => {
const selected_rig = (event.target as HTMLSelectElement).value as SkeletonType
diff --git a/src/preview-generator/webm-recorder.ts b/src/preview-generator/webm-recorder.ts
deleted file mode 100644
index dce3b07..0000000
--- a/src/preview-generator/webm-recorder.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import * as THREE from 'three'
-
-export class WebMRecorder {
- public width: number
- public height: number
- public fps: number = 24
- public kbps: number = 2600
-
- public readonly recorded_files: File[] = []
- private readonly renderer_ref: THREE.WebGLRenderer
-
- private old_size: THREE.Vector2 | null = null
- private old_pr: number | null = null
- private recorder: MediaRecorder | null = null
- private chunks: Blob[] = []
- private stopped_promise: Promise<void> | null = null
- private stopped_resolve: (() => void) | null = null
- private file_name: string = ''
-
- constructor (renderer: THREE.WebGLRenderer, preview_width: number, preview_height: number) {
- this.renderer_ref = renderer
- this.width = preview_width
- this.height = preview_height
-
- console.log(this.renderer_ref.domElement.height, this.renderer_ref.domElement.width)
- }
-
- public start (saved_name: string): void {
- this.old_size = this.renderer_ref.getSize(new THREE.Vector2())
- this.old_pr = this.renderer_ref.getPixelRatio()
- this.renderer_ref.setPixelRatio(1)
- this.renderer_ref.setSize(this.width, this.height, false)
- this.file_name = saved_name
-
- const stream: MediaStream = this.renderer_ref.domElement.captureStream(this.fps)
- this.recorder = new MediaRecorder(stream, {
- mimeType: this.supported_webm_mime_type(),
- videoBitsPerSecond: this.kbps * 1000
- })
- this.chunks = []
- this.recorder.ondataavailable = e => (e.data.size !== 0) && this.chunks.push(e.data)
- this.stopped_promise = new Promise<void>(resolve => {
- this.stopped_resolve = resolve
- this.recorder!.onstop = () => { resolve() }
- })
- this.recorder.start()
- }
-
- public async stop (): Promise<File> {
- if (!this.recorder) throw new Error('Recorder not started')
- this.recorder.stop()
- if (this.stopped_promise) {
- await this.stopped_promise
- }
- // restore the renderer size and pixel ratio
- if (this.old_size && this.old_pr !== null) {
- this.renderer_ref.setSize(this.old_size.x, this.old_size.y, false)
- this.renderer_ref.setPixelRatio(this.old_pr)
- }
- const file = new File(this.chunks, this.file_name, { type: this.supported_webm_mime_type() })
- this.recorder = null
- this.stopped_promise = null
- this.stopped_resolve = null
- this.chunks = []
- return file
- }
-
- private supported_webm_mime_type (): string {
- const prefs = ['video/webm;codecs=av01', 'video/webm;codecs=vp9', 'video/webm;codecs=vp8', 'video/webm']
- return prefs.find(m => MediaRecorder.isTypeSupported(m)) ?? 'video/webm'
- }
-}