// ══════════════════════════════════════════════════════════════════════════════ // Chahua Video Builder - Video Renderer // 100% Native Video Rendering Engine - No External Dependencies // ══════════════════════════════════════════════════════════════════════════════ // Company: Chahua Development Co., Ltd. // Version: 1.0.0 // License: MIT // ══════════════════════════════════════════════════════════════════════════════ export class VideoRenderer { constructor(options = {}) { this.options = { width: options.width || 1920, height: options.height || 1080, fps: options.fps || 60, format: options.format || 'webm', quality: options.quality || 0.95, videoBitsPerSecond: options.videoBitsPerSecond || 8000000, // 8 Mbps ...options }; this.mediaRecorder = null; this.recordedChunks = []; this.isRecording = false; } // ════════════════════════════════════════════════════════════════════════════ // WebM/MP4 Recording using MediaRecorder API // ════════════════════════════════════════════════════════════════════════════ async startRecording(element) { if (this.isRecording) { throw new Error('Recording already in progress'); } try { // Create a canvas to capture the element this.canvas = document.createElement('canvas'); this.canvas.width = this.options.width; this.canvas.height = this.options.height; this.ctx = this.canvas.getContext('2d', { willReadFrequently: true, alpha: false }); // Store element reference this.element = element; // Start capturing frames this.startFrameCapture(); // Get stream from canvas const stream = this.canvas.captureStream(this.options.fps); // Determine MIME type const mimeType = this.getBestMimeType(); console.log('[VideoRenderer] Recording with:', mimeType, 'at', this.options.fps, 'fps'); // Create MediaRecorder this.mediaRecorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: this.options.videoBitsPerSecond }); this.recordedChunks = []; // Handle data available this.mediaRecorder.addEventListener('dataavailable', (event) => { if (event.data && event.data.size > 0) { this.recordedChunks.push(event.data); console.log('[VideoRenderer] Chunk received:', event.data.size, 'bytes'); } }); // Start recording this.mediaRecorder.start(100); // Collect data every 100ms this.isRecording = true; console.log('[VideoRenderer] Recording started successfully'); return { success: true, message: 'Recording started' }; } catch (error) { console.error('[VideoRenderer] Error starting recording:', error); throw error; } } startFrameCapture() { const captureFrame = () => { if (!this.isRecording) { return; } try { // Clear canvas this.ctx.fillStyle = '#000000'; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); // Get element's computed styles const styles = window.getComputedStyle(this.element); // Draw background if (styles.backgroundColor && styles.backgroundColor !== 'rgba(0, 0, 0, 0)') { this.ctx.fillStyle = styles.backgroundColor; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); } // Render element content using DOM to canvas conversion this.renderElementToCanvas(this.element, this.ctx); } catch (error) { console.error('[VideoRenderer] Frame capture error:', error); } if (this.isRecording) { this._frameId = requestAnimationFrame(captureFrame); } }; captureFrame(); } renderElementToCanvas(element, ctx) { // Get all text nodes and render them const walker = document.createTreeWalker( element, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, null ); const texts = []; let node; while (node = walker.nextNode()) { if (node.nodeType === Node.TEXT_NODE && node.textContent.trim()) { const parent = node.parentElement; if (parent && parent.offsetParent !== null) { const rect = parent.getBoundingClientRect(); const elementRect = element.getBoundingClientRect(); const styles = window.getComputedStyle(parent); texts.push({ text: node.textContent, x: rect.left - elementRect.left, y: rect.top - elementRect.top, width: rect.width, height: rect.height, font: styles.font || '16px sans-serif', color: styles.color || '#ffffff', fontSize: styles.fontSize, fontFamily: styles.fontFamily, fontWeight: styles.fontWeight, textAlign: styles.textAlign || 'left', lineHeight: parseFloat(styles.lineHeight) || parseFloat(styles.fontSize) * 1.2 }); } } } // Scale factor const scaleX = this.canvas.width / element.offsetWidth; const scaleY = this.canvas.height / element.offsetHeight; // Render texts texts.forEach(item => { ctx.save(); ctx.fillStyle = item.color; ctx.font = `${item.fontWeight} ${parseFloat(item.fontSize) * scaleY}px ${item.fontFamily}`; ctx.textAlign = item.textAlign; ctx.textBaseline = 'top'; const x = item.x * scaleX; const y = item.y * scaleY + (parseFloat(item.fontSize) * scaleY); ctx.fillText(item.text, x, y); ctx.restore(); }); } async stopRecording() { if (!this.isRecording || !this.mediaRecorder) { throw new Error('No recording in progress'); } return new Promise((resolve, reject) => { this.mediaRecorder.addEventListener('stop', () => { // Stop frame capture if (this._frameId) { cancelAnimationFrame(this._frameId); this._frameId = null; } const blob = new Blob(this.recordedChunks, { type: this.mediaRecorder.mimeType }); this.isRecording = false; console.log('[VideoRenderer] Recording stopped. Total size:', blob.size, 'bytes'); console.log('[VideoRenderer] Total chunks:', this.recordedChunks.length); resolve({ success: true, blob, size: blob.size, mimeType: this.mediaRecorder.mimeType, url: URL.createObjectURL(blob) }); }); this.mediaRecorder.addEventListener('error', (event) => { this.isRecording = false; if (this._frameId) { cancelAnimationFrame(this._frameId); this._frameId = null; } reject(new Error(`Recording error: ${event.error}`)); }); this.mediaRecorder.stop(); }); } // ════════════════════════════════════════════════════════════════════════════ // GIF Rendering using Canvas // ════════════════════════════════════════════════════════════════════════════ async renderGIF(element, duration, fps = 15) { const frames = []; const interval = 1000 / fps; const totalFrames = Math.ceil((duration / 1000) * fps); // Create canvas for capturing const canvas = document.createElement('canvas'); canvas.width = this.options.width; canvas.height = this.options.height; const ctx = canvas.getContext('2d'); // Capture frames for (let i = 0; i < totalFrames; i++) { await this.wait(interval); // Draw element to canvas await this.drawElementToCanvas(element, canvas, ctx); // Get image data const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); frames.push({ data: this.quantizeColors(imageData.data, 256), width: canvas.width, height: canvas.height, delay: Math.round(interval / 10) // Delay in 1/100s }); } // Encode GIF const gifData = this.encodeGIF(frames); return { success: true, frames: frames.length, data: gifData, blob: new Blob([gifData], { type: 'image/gif' }) }; } // ════════════════════════════════════════════════════════════════════════════ // Helper Functions // ════════════════════════════════════════════════════════════════════════════ getBestMimeType() { // Chromium/Electron supports WebM very well, MP4 encoding is not directly supported const types = [ 'video/webm;codecs=vp9,opus', 'video/webm;codecs=vp9', 'video/webm;codecs=vp8,opus', 'video/webm;codecs=vp8', 'video/webm' ]; for (const type of types) { if (MediaRecorder.isTypeSupported(type)) { console.log('[VideoRenderer] Using MIME type:', type); return type; } } console.warn('[VideoRenderer] No preferred MIME type supported, using default'); return 'video/webm'; } async captureElementStream(element) { const canvas = document.createElement('canvas'); canvas.width = this.options.width; canvas.height = this.options.height; const ctx = canvas.getContext('2d'); // Capture frames manually const captureFrame = async () => { await this.drawElementToCanvas(element, canvas, ctx); }; const intervalId = setInterval(captureFrame, 1000 / this.options.fps); // Store interval ID for cleanup this._captureIntervalId = intervalId; return canvas.captureStream(this.options.fps); } async drawElementToCanvas(element, canvas, ctx) { // Use html2canvas-like approach const rect = element.getBoundingClientRect(); // Clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw background ctx.fillStyle = window.getComputedStyle(element).backgroundColor || '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); // For simplicity, we'll use drawImage if element is video/canvas // For other elements, we'd need to serialize to SVG if (element.tagName === 'CANVAS' || element.tagName === 'VIDEO') { ctx.drawImage(element, 0, 0, canvas.width, canvas.height); } else { // Serialize element to data URL and draw const data = await this.elementToDataURL(element); const img = new Image(); await new Promise((resolve, reject) => { img.onload = resolve; img.onerror = reject; img.src = data; }); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); } } async elementToDataURL(element) { // Create SVG foreignObject const rect = element.getBoundingClientRect(); const svg = `
${element.outerHTML}
`; const blob = new Blob([svg], { type: 'image/svg+xml' }); return URL.createObjectURL(blob); } // ════════════════════════════════════════════════════════════════════════════ // GIF Encoding (Simplified LZW Compression) // ════════════════════════════════════════════════════════════════════════════ encodeGIF(frames) { const { width, height } = frames[0]; // GIF Header const header = this.stringToBytes('GIF89a'); // Logical Screen Descriptor const lsd = new Uint8Array(7); lsd[0] = width & 0xFF; lsd[1] = (width >> 8) & 0xFF; lsd[2] = height & 0xFF; lsd[3] = (height >> 8) & 0xFF; lsd[4] = 0xF7; // Global Color Table Flag lsd[5] = 0x00; // Background Color Index lsd[6] = 0x00; // Pixel Aspect Ratio // Global Color Table (256 colors) const gct = this.generateColorTable(256); // Application Extension (for looping) const appExt = new Uint8Array([ 0x21, 0xFF, 0x0B, ...this.stringToBytes('NETSCAPE2.0'), 0x03, 0x01, 0x00, 0x00, 0x00 ]); const frameData = []; for (const frame of frames) { // Graphics Control Extension const gce = new Uint8Array([ 0x21, 0xF9, 0x04, 0x04, // Disposal method frame.delay & 0xFF, (frame.delay >> 8) & 0xFF, 0x00, // Transparent color index 0x00 ]); // Image Descriptor const imgDesc = new Uint8Array(10); imgDesc[0] = 0x2C; // Image separator imgDesc[1] = 0x00; imgDesc[2] = 0x00; // Left imgDesc[3] = 0x00; imgDesc[4] = 0x00; // Top imgDesc[5] = width & 0xFF; imgDesc[6] = (width >> 8) & 0xFF; imgDesc[7] = height & 0xFF; imgDesc[8] = (height >> 8) & 0xFF; imgDesc[9] = 0x00; // Packed fields // Image Data (simplified - use minimal compression) const imageData = this.compressImageData(frame.data); frameData.push(...gce, ...imgDesc, ...imageData); } // Trailer const trailer = new Uint8Array([0x3B]); // Combine all parts return new Uint8Array([ ...header, ...lsd, ...gct, ...appExt, ...frameData, ...trailer ]); } generateColorTable(size) { const table = new Uint8Array(size * 3); for (let i = 0; i < size; i++) { table[i * 3] = i; table[i * 3 + 1] = i; table[i * 3 + 2] = i; } return table; } quantizeColors(imageData, colorCount) { // Simple color quantization const quantized = new Uint8Array(imageData.length / 4); for (let i = 0; i < imageData.length; i += 4) { const r = imageData[i]; const g = imageData[i + 1]; const b = imageData[i + 2]; const gray = Math.floor(0.299 * r + 0.587 * g + 0.114 * b); quantized[i / 4] = Math.floor(gray * (colorCount - 1) / 255); } return quantized; } compressImageData(data) { // Minimal LZW compression (simplified) const lzwMinCodeSize = 8; const compressed = [lzwMinCodeSize]; // Simple run-length encoding as fallback const blocks = []; let currentBlock = []; for (let i = 0; i < data.length; i++) { currentBlock.push(data[i]); if (currentBlock.length === 255) { blocks.push(currentBlock.length, ...currentBlock); currentBlock = []; } } if (currentBlock.length > 0) { blocks.push(currentBlock.length, ...currentBlock); } blocks.push(0); // Block terminator return new Uint8Array([...compressed, ...blocks]); } stringToBytes(str) { return new Uint8Array([...str].map(c => c.charCodeAt(0))); } wait(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // ════════════════════════════════════════════════════════════════════════════ // Cleanup // ════════════════════════════════════════════════════════════════════════════ cleanup() { if (this._captureIntervalId) { clearInterval(this._captureIntervalId); this._captureIntervalId = null; } if (this.mediaRecorder && this.isRecording) { this.mediaRecorder.stop(); } this.recordedChunks = []; this.mediaRecorder = null; this.isRecording = false; } } // ══════════════════════════════════════════════════════════════════════════════ // Export Format Helpers // ══════════════════════════════════════════════════════════════════════════════ export function blobToBase64(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(blob); }); } export function downloadBlob(blob, filename) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }