Compare commits

..

1 Commits

Author SHA1 Message Date
Tim
3f35add587 feat: switch video compression to webcodecs 2025-09-11 17:01:54 +08:00
5 changed files with 128 additions and 74 deletions

View File

@@ -16,4 +16,9 @@ NUXT_PUBLIC_GOOGLE_CLIENT_ID=777830451304-nt8afkkap18gui4f9entcha99unal744.apps.
NUXT_PUBLIC_GITHUB_CLIENT_ID=Ov23liVkO1NPAX5JyWxJ
NUXT_PUBLIC_DISCORD_CLIENT_ID=1394985417044000779
NUXT_PUBLIC_TWITTER_CLIENT_ID=ZTRTU05KSk9KTTJrTTdrVC1tc1E6MTpjaQ
NUXT_PUBLIC_TELEGRAM_BOT_ID=8450237135
NUXT_PUBLIC_TELEGRAM_BOT_ID=8450237135
# 视频压缩配置 - FFmpeg.wasm 专用
# 支持 Chrome 60+ 和 Safari 11.1+
NUXT_PUBLIC_VIDEO_MAX_SIZE=52428800 # 50MB (字节)
NUXT_PUBLIC_VIDEO_TARGET_SIZE=20971520 # 20MB (字节)

View File

@@ -1,17 +1,57 @@
/**
* 文件上传配置 - 简化版
* 专注于 WebCodecs + MP4Box.js 视频压缩,支持 Chrome/Safari
* 专注于 FFmpeg.wasm 视频压缩,支持 Chrome/Safari
*/
// 声明全局变量以避免 TypeScript 错误
/* global useRuntimeConfig */
export const UPLOAD_CONFIG = {
VIDEO: {
MAX_SIZE: 20 * 1024 * 1024, // 20mb
TARGET_SIZE: 5 * 1024 * 1024, // 5mb
// 简化的环境变量读取功能
function getEnvNumber(key, defaultValue) {
if (typeof window !== 'undefined') {
// 客户端:尝试从 Nuxt 环境获取
try {
// 使用 globalThis 避免直接引用未定义的变量
const nuxtApp = globalThis.$nuxt || globalThis.nuxtApp
if (nuxtApp && nuxtApp.$config) {
const value = nuxtApp.$config.public?.[key.replace('NUXT_PUBLIC_', '').toLowerCase()]
return value ? Number(value) : defaultValue
}
return defaultValue
} catch {
return defaultValue
}
}
// 服务端:从 process.env 获取
return process.env[key] ? Number(process.env[key]) : defaultValue
}
// 支持的输入格式
function getEnvBoolean(key, defaultValue) {
if (typeof window !== 'undefined') {
try {
// 使用 globalThis 避免直接引用未定义的变量
const nuxtApp = globalThis.$nuxt || globalThis.nuxtApp
if (nuxtApp && nuxtApp.$config) {
const value = nuxtApp.$config.public?.[key.replace('NUXT_PUBLIC_', '').toLowerCase()]
return value === 'true' || value === true
}
return defaultValue
} catch {
return defaultValue
}
}
const envValue = process.env[key]
return envValue ? envValue === 'true' : defaultValue
}
export const UPLOAD_CONFIG = {
// 视频文件配置 - 专为 FFmpeg.wasm 优化
VIDEO: {
// 文件大小限制 (字节)
MAX_SIZE: getEnvNumber('NUXT_PUBLIC_VIDEO_MAX_SIZE', 20 * 1024 * 1024), // 5MB
TARGET_SIZE: getEnvNumber('NUXT_PUBLIC_VIDEO_TARGET_SIZE', 5 * 1024 * 1024), // 5MB
// 支持的输入格式 (FFmpeg.wasm 支持更多格式)
SUPPORTED_FORMATS: ['mp4', 'webm', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'm4v', 'ogv'],
// 输出格式 - MP4 (兼容性最好)

View File

@@ -124,11 +124,10 @@ export function createVditor(editorId, options = {}) {
// 使用 WebCodecs 压缩视频
processedFile = await compressVideo(file, (progress) => {
const messages = {
initializing: '初始化编码器',
initializing: '初始化编码器',
preparing: '准备压缩',
analyzing: '分析视频',
compressing: '压缩中',
finalizing: '完成压缩',
packaging: '封装中',
completed: '压缩完成',
}
const message = messages[progress.stage] || progress.stage

View File

@@ -45,7 +45,7 @@ export async function compressVideo(file, onProgress = () => {}) {
// 检查 WebCodecs 支持
if (!isWebCodecSupported()) {
throw new Error('当前浏览器不支持视频压缩功能,请使用支持 WebCodecs 的浏览器')
throw new Error('当前浏览器不支持视频压缩功能,请使用 Chrome 或 Safari 浏览器')
}
try {
@@ -64,9 +64,9 @@ export async function preloadVideoCompressor() {
if (!isWebCodecSupported()) {
throw new Error('当前浏览器不支持 WebCodecs')
}
return { success: true, message: 'WebCodecs 已就绪' }
return { success: true, message: 'WebCodecs 可用' }
} catch (error) {
console.warn('WebCodecs 检测失败:', error)
console.warn('WebCodecs 预加载失败:', error)
return { success: false, error: error.message }
}
}

View File

@@ -1,98 +1,108 @@
import MP4Box from 'mp4box'
/**
* WebCodecs + MP4Box.js video compressor
* Simplified transcoding using browser WebCodecs API
*/
import { createFile } from 'mp4box'
import { UPLOAD_CONFIG } from '../config/uploadConfig.js'
// 检查 WebCodecs 支持
export function isWebCodecSupported() {
return typeof window !== 'undefined' && typeof window.VideoEncoder !== 'undefined'
return (
typeof window !== 'undefined' &&
'VideoEncoder' in window &&
'MediaStreamTrackProcessor' in window &&
'VideoFrame' in window
)
}
// 使用 WebCodecs + MP4Box.js 压缩视频
export async function compressVideoWithWebCodecs(file, opts = {}) {
const { onProgress = () => {}, width = 720, bitrate = 1_000_000 } = opts
/**
* Compress a video File using WebCodecs and MP4Box.js
* @param {File} file original video file
* @param {Object} options optional callbacks
* @param {Function} options.onProgress progress callback
* @returns {Promise<File>} compressed file
*/
export async function compressVideoWithWebCodecs(file, { onProgress = () => {} } = {}) {
if (!isWebCodecSupported()) {
throw new Error('当前浏览器不支持 WebCodecs')
}
onProgress({ stage: 'initializing', progress: 0 })
// 加载原始视频
const url = URL.createObjectURL(file)
const video = document.createElement('video')
video.src = url
video.muted = true
await video.play().catch(() => {})
await video.play()
video.pause()
await new Promise((resolve) => {
if (video.readyState >= 2) resolve()
else video.onloadedmetadata = () => resolve()
})
const targetWidth = width
const targetHeight = Math.round((video.videoHeight / video.videoWidth) * width)
const canvas = document.createElement('canvas')
canvas.width = targetWidth
canvas.height = targetHeight
const ctx = canvas.getContext('2d')
onProgress({ stage: 'preparing', progress: 10 })
const stream = video.captureStream()
const track = stream.getVideoTracks()[0]
const processor = new MediaStreamTrackProcessor({ track })
const reader = processor.readable.getReader()
const { width, height, frameRate = 30 } = track.getSettings()
const bitrate = UPLOAD_CONFIG.VIDEO.TARGET_BITRATE || 1_000_000
const chunks = []
const encoder = new VideoEncoder({
output: (chunk) => {
chunks.push(chunk)
const copy = new Uint8Array(chunk.byteLength)
chunk.copyTo(copy)
chunks.push({ type: chunk.type, timestamp: chunk.timestamp, data: copy })
},
error: (e) => {
throw e
},
})
encoder.configure({
codec: 'avc1.42001E',
width: targetWidth,
height: targetHeight,
bitrate,
framerate: 30,
error: (e) => console.error('编码失败', e),
})
const duration = video.duration
const frameCount = Math.floor(duration * 30)
for (let i = 0; i < frameCount; i++) {
video.currentTime = i / 30
await new Promise((res) => (video.onseeked = res))
ctx.drawImage(video, 0, 0, targetWidth, targetHeight)
const bitmap = await createImageBitmap(canvas)
const frame = new VideoFrame(bitmap, { timestamp: (i / 30) * 1000000 })
encoder.encode(frame)
frame.close()
bitmap.close()
onProgress({ stage: 'compressing', progress: Math.round(((i + 1) / frameCount) * 80) })
encoder.configure({
codec: 'avc1.42001E',
width,
height,
bitrate,
framerate: frameRate,
})
let processed = 0
const totalFrames = Math.ceil(video.duration * frameRate)
while (true) {
const { done, value } = await reader.read()
if (done) break
encoder.encode(value)
value.close()
processed++
onProgress({ stage: 'compressing', progress: Math.round((processed / totalFrames) * 80) })
}
await encoder.flush()
onProgress({ stage: 'finalizing', progress: 90 })
const mp4box = MP4Box.createFile()
const track = mp4box.addTrack({
timescale: 1000,
width: targetWidth,
height: targetHeight,
onProgress({ stage: 'packaging', progress: 90 })
const mp4 = createFile()
const trackId = mp4.addTrack({
id: 1,
type: 'avc1',
width,
height,
timescale: frameRate,
})
let dts = 0
chunks.forEach((chunk) => {
const data = new Uint8Array(chunk.byteLength)
chunk.copyTo(data)
mp4box.addSample(track, data.buffer, {
duration: chunk.duration ? chunk.duration / 1000 : 33,
dts,
cts: dts,
mp4.addSample(trackId, chunk.data.buffer, {
duration: 1,
dts: chunk.timestamp,
cts: 0,
is_sync: chunk.type === 'key',
})
dts += chunk.duration ? chunk.duration / 1000 : 33
})
const arrayBuffer = mp4box.flush()
const outputFile = new File([arrayBuffer], file.name.replace(/\.[^.]+$/, '.mp4'), {
const streamOut = mp4.getBuffer()
const outBuffer = streamOut.buffer.slice(0, streamOut.position)
const outFile = new File([outBuffer], file.name.replace(/\.[^.]+$/, '.mp4'), {
type: 'video/mp4',
})
onProgress({ stage: 'completed', progress: 100 })
URL.revokeObjectURL(url)
return outputFile
return outFile
}