| … | … | @@ -0,0 +1,212 @@ |
| 1 | import { spawn } from 'bare-subprocess' |
| 2 | import fs from 'bare-fs' |
| 3 | import path from 'bare-path' |
| 4 | import os from 'bare-os' |
| 5 | |
| 6 | // Quality levels for HLS (used later in Task 12) |
| 7 | export const HLS_LEVELS = [ |
| 8 | { name: '480p', height: 480, bitrate: '1000k', maxrate: '1200k', profile: 'baseline' }, |
| 9 | { name: '720p', height: 720, bitrate: '2500k', maxrate: '3000k', profile: 'main' }, |
| 10 | { name: '1080p', height: 1080, bitrate: '5000k', maxrate: '6000k', profile: 'high' } |
| 11 | ] |
| 12 | |
| 13 | export class VideoProcessor { |
| 14 | constructor (mediaStore, opts = {}) { |
| 15 | this.mediaStore = mediaStore |
| 16 | this._queue = [] |
| 17 | this._processing = false |
| 18 | this._tmpBase = opts.tmpDir || path.join(os.tmpdir(), 'hypernote-video') |
| 19 | this._ffmpegPath = opts.ffmpegPath || 'ffmpeg' |
| 20 | this._ffprobePath = opts.ffprobePath || 'ffprobe' |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Run a command and return { stdout, stderr, code } |
| 25 | */ |
| 26 | _exec (cmd, args) { |
| 27 | return new Promise((resolve, reject) => { |
| 28 | const proc = spawn(cmd, args) |
| 29 | const stdout = [] |
| 30 | const stderr = [] |
| 31 | |
| 32 | proc.stdout.on('data', (chunk) => stdout.push(chunk)) |
| 33 | proc.stderr.on('data', (chunk) => stderr.push(chunk)) |
| 34 | |
| 35 | proc.on('exit', (code) => { |
| 36 | resolve({ |
| 37 | code, |
| 38 | stdout: Buffer.concat(stdout).toString(), |
| 39 | stderr: Buffer.concat(stderr).toString() |
| 40 | }) |
| 41 | }) |
| 42 | |
| 43 | proc.on('error', reject) |
| 44 | }) |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Safely parse ffprobe frame rate string like "30/1" or "25" |
| 49 | */ |
| 50 | _parseFps (str) { |
| 51 | if (!str) return 30 |
| 52 | const parts = str.split('/') |
| 53 | const num = Number(parts[0]) |
| 54 | const den = parts.length > 1 ? Number(parts[1]) : 1 |
| 55 | if (!num || !den || !isFinite(num / den)) return 30 |
| 56 | return Math.round(num / den) |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Probe a video file — returns { width, height, duration, codec, fps } |
| 61 | */ |
| 62 | async probe (filePath) { |
| 63 | const result = await this._exec(this._ffprobePath, [ |
| 64 | '-v', 'quiet', |
| 65 | '-print_format', 'json', |
| 66 | '-show_streams', |
| 67 | '-show_format', |
| 68 | filePath |
| 69 | ]) |
| 70 | |
| 71 | if (result.code !== 0) { |
| 72 | throw new Error('ffprobe failed: ' + result.stderr) |
| 73 | } |
| 74 | |
| 75 | const data = JSON.parse(result.stdout) |
| 76 | const video = data.streams.find(s => s.codec_type === 'video') |
| 77 | if (!video) throw new Error('No video stream found') |
| 78 | |
| 79 | const duration = parseFloat(data.format.duration || video.duration || '0') |
| 80 | const fps = this._parseFps(video.r_frame_rate) |
| 81 | |
| 82 | return { |
| 83 | width: video.width, |
| 84 | height: video.height, |
| 85 | duration, |
| 86 | codec: video.codec_name, |
| 87 | fps |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * Extract a poster frame at the given time (seconds) as JPEG buffer. |
| 93 | */ |
| 94 | async extractPoster (filePath, timeSeconds) { |
| 95 | const time = timeSeconds || 2 |
| 96 | const tmpPoster = path.join(this._tmpBase, 'poster-' + Date.now() + '.jpg') |
| 97 | |
| 98 | await fs.promises.mkdir(this._tmpBase, { recursive: true }) |
| 99 | |
| 100 | const result = await this._exec(this._ffmpegPath, [ |
| 101 | '-y', |
| 102 | '-ss', String(time), |
| 103 | '-i', filePath, |
| 104 | '-vframes', '1', |
| 105 | '-q:v', '2', |
| 106 | tmpPoster |
| 107 | ]) |
| 108 | |
| 109 | if (result.code !== 0) { |
| 110 | throw new Error('Poster extraction failed: ' + result.stderr) |
| 111 | } |
| 112 | |
| 113 | const buf = await fs.promises.readFile(tmpPoster) |
| 114 | await fs.promises.unlink(tmpPoster).catch(() => {}) |
| 115 | return buf |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Write a MediaStore blob to a temp file (ffmpeg needs file paths). |
| 120 | * Returns the temp file path. Caller must clean up. |
| 121 | */ |
| 122 | async _writeTempFile (hash, ext) { |
| 123 | const buf = await this.mediaStore.get(hash) |
| 124 | if (!buf) throw new Error('Blob not found: ' + hash) |
| 125 | |
| 126 | await fs.promises.mkdir(this._tmpBase, { recursive: true }) |
| 127 | const tmpPath = path.join(this._tmpBase, hash.substring(0, 16) + (ext || '.mp4')) |
| 128 | await fs.promises.writeFile(tmpPath, buf) |
| 129 | return tmpPath |
| 130 | } |
| 131 | |
| 132 | /** |
| 133 | * Process a video: probe it, extract poster, store poster in MediaStore. |
| 134 | * Returns { probe, posterHash } |
| 135 | */ |
| 136 | async processBasic (originalHash) { |
| 137 | // Write to temp file |
| 138 | const info = await this.mediaStore.getInfo(originalHash) |
| 139 | const ext = info && info.mimeType === 'video/webm' ? '.webm' : '.mp4' |
| 140 | const tmpPath = await this._writeTempFile(originalHash, ext) |
| 141 | |
| 142 | try { |
| 143 | // Probe |
| 144 | const probeResult = await this.probe(tmpPath) |
| 145 | |
| 146 | // Extract poster |
| 147 | const posterTime = Math.min(2, probeResult.duration * 0.1) |
| 148 | const posterBuf = await this.extractPoster(tmpPath, posterTime) |
| 149 | const posterHash = await this.mediaStore.put(posterBuf, 'image/jpeg') |
| 150 | |
| 151 | return { probe: probeResult, posterHash } |
| 152 | } finally { |
| 153 | await fs.promises.unlink(tmpPath).catch(() => {}) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * Enqueue a video for full processing (probe + poster + HLS). |
| 159 | * Returns a promise that resolves when processing is complete. |
| 160 | */ |
| 161 | enqueue (originalHash) { |
| 162 | return new Promise((resolve, reject) => { |
| 163 | this._queue.push({ originalHash, resolve, reject }) |
| 164 | this._processNext() |
| 165 | }) |
| 166 | } |
| 167 | |
| 168 | async _processNext () { |
| 169 | if (this._processing || this._queue.length === 0) return |
| 170 | this._processing = true |
| 171 | |
| 172 | const { originalHash, resolve, reject } = this._queue.shift() |
| 173 | |
| 174 | try { |
| 175 | const result = await this.processBasic(originalHash) |
| 176 | |
| 177 | // Store video index |
| 178 | await this.mediaStore._index.put('video:' + originalHash, { |
| 179 | status: 'ready', |
| 180 | poster: result.posterHash, |
| 181 | width: result.probe.width, |
| 182 | height: result.probe.height, |
| 183 | duration: result.probe.duration, |
| 184 | codec: result.probe.codec, |
| 185 | fps: result.probe.fps, |
| 186 | processedAt: Date.now() |
| 187 | }) |
| 188 | |
| 189 | resolve(result) |
| 190 | } catch (err) { |
| 191 | await this.mediaStore._index.put('video:' + originalHash, { |
| 192 | status: 'failed', |
| 193 | error: err.message, |
| 194 | processedAt: Date.now() |
| 195 | }).catch(() => {}) |
| 196 | reject(err) |
| 197 | } finally { |
| 198 | this._processing = false |
| 199 | this._processNext() |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | /** |
| 204 | * Get video processing status. |
| 205 | */ |
| 206 | async getStatus (originalHash) { |
| 207 | const entry = await this.mediaStore._index.get('video:' + originalHash) |
| 208 | return entry ? entry.value : null |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | export default VideoProcessor |