|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|
| ...options
|
| };
|
|
|
| this.mediaRecorder = null;
|
| this.recordedChunks = [];
|
| this.isRecording = false;
|
| }
|
|
|
|
|
|
|
|
|
|
|
| async startRecording(element) {
|
| if (this.isRecording) {
|
| throw new Error('Recording already in progress');
|
| }
|
|
|
| try {
|
|
|
| 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
|
| });
|
|
|
|
|
| this.element = element;
|
|
|
|
|
| this.startFrameCapture();
|
|
|
|
|
| const stream = this.canvas.captureStream(this.options.fps);
|
|
|
|
|
| const mimeType = this.getBestMimeType();
|
| console.log('[VideoRenderer] Recording with:', mimeType, 'at', this.options.fps, 'fps');
|
|
|
|
|
| this.mediaRecorder = new MediaRecorder(stream, {
|
| mimeType,
|
| videoBitsPerSecond: this.options.videoBitsPerSecond
|
| });
|
|
|
| this.recordedChunks = [];
|
|
|
|
|
| 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');
|
| }
|
| });
|
|
|
|
|
| this.mediaRecorder.start(100);
|
| 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 {
|
|
|
| this.ctx.fillStyle = '#000000';
|
| this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
|
|
|
|
|
| const styles = window.getComputedStyle(this.element);
|
|
|
|
|
| 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);
|
| }
|
|
|
|
|
| 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) {
|
|
|
| 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
|
| });
|
| }
|
| }
|
| }
|
|
|
|
|
| const scaleX = this.canvas.width / element.offsetWidth;
|
| const scaleY = this.canvas.height / element.offsetHeight;
|
|
|
|
|
| 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', () => {
|
|
|
| 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();
|
| });
|
| }
|
|
|
|
|
|
|
|
|
|
|
| async renderGIF(element, duration, fps = 15) {
|
| const frames = [];
|
| const interval = 1000 / fps;
|
| const totalFrames = Math.ceil((duration / 1000) * fps);
|
|
|
|
|
| const canvas = document.createElement('canvas');
|
| canvas.width = this.options.width;
|
| canvas.height = this.options.height;
|
| const ctx = canvas.getContext('2d');
|
|
|
|
|
| for (let i = 0; i < totalFrames; i++) {
|
| await this.wait(interval);
|
|
|
|
|
| await this.drawElementToCanvas(element, canvas, ctx);
|
|
|
|
|
| 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)
|
| });
|
| }
|
|
|
|
|
| const gifData = this.encodeGIF(frames);
|
|
|
| return {
|
| success: true,
|
| frames: frames.length,
|
| data: gifData,
|
| blob: new Blob([gifData], { type: 'image/gif' })
|
| };
|
| }
|
|
|
|
|
|
|
|
|
|
|
| getBestMimeType() {
|
|
|
| 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');
|
|
|
|
|
| const captureFrame = async () => {
|
| await this.drawElementToCanvas(element, canvas, ctx);
|
| };
|
|
|
| const intervalId = setInterval(captureFrame, 1000 / this.options.fps);
|
|
|
|
|
| this._captureIntervalId = intervalId;
|
|
|
| return canvas.captureStream(this.options.fps);
|
| }
|
|
|
| async drawElementToCanvas(element, canvas, ctx) {
|
|
|
| const rect = element.getBoundingClientRect();
|
|
|
|
|
| ctx.clearRect(0, 0, canvas.width, canvas.height);
|
|
|
|
|
| ctx.fillStyle = window.getComputedStyle(element).backgroundColor || '#000';
|
| ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
|
|
|
|
|
| if (element.tagName === 'CANVAS' || element.tagName === 'VIDEO') {
|
| ctx.drawImage(element, 0, 0, canvas.width, canvas.height);
|
| } else {
|
|
|
| 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) {
|
|
|
| const rect = element.getBoundingClientRect();
|
| const svg = `
|
| <svg xmlns="http://www.w3.org/2000/svg" width="${rect.width}" height="${rect.height}">
|
| <foreignObject width="100%" height="100%">
|
| <div xmlns="http://www.w3.org/1999/xhtml">
|
| ${element.outerHTML}
|
| </div>
|
| </foreignObject>
|
| </svg>
|
| `;
|
|
|
| const blob = new Blob([svg], { type: 'image/svg+xml' });
|
| return URL.createObjectURL(blob);
|
| }
|
|
|
|
|
|
|
|
|
|
|
| encodeGIF(frames) {
|
| const { width, height } = frames[0];
|
|
|
|
|
| const header = this.stringToBytes('GIF89a');
|
|
|
|
|
| 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;
|
| lsd[5] = 0x00;
|
| lsd[6] = 0x00;
|
|
|
|
|
| const gct = this.generateColorTable(256);
|
|
|
|
|
| const appExt = new Uint8Array([
|
| 0x21, 0xFF, 0x0B,
|
| ...this.stringToBytes('NETSCAPE2.0'),
|
| 0x03, 0x01, 0x00, 0x00, 0x00
|
| ]);
|
|
|
| const frameData = [];
|
|
|
| for (const frame of frames) {
|
|
|
| const gce = new Uint8Array([
|
| 0x21, 0xF9, 0x04,
|
| 0x04,
|
| frame.delay & 0xFF, (frame.delay >> 8) & 0xFF,
|
| 0x00,
|
| 0x00
|
| ]);
|
|
|
|
|
| const imgDesc = new Uint8Array(10);
|
| imgDesc[0] = 0x2C;
|
| imgDesc[1] = 0x00; imgDesc[2] = 0x00;
|
| imgDesc[3] = 0x00; imgDesc[4] = 0x00;
|
| imgDesc[5] = width & 0xFF; imgDesc[6] = (width >> 8) & 0xFF;
|
| imgDesc[7] = height & 0xFF; imgDesc[8] = (height >> 8) & 0xFF;
|
| imgDesc[9] = 0x00;
|
|
|
|
|
| const imageData = this.compressImageData(frame.data);
|
|
|
| frameData.push(...gce, ...imgDesc, ...imageData);
|
| }
|
|
|
|
|
| const trailer = new Uint8Array([0x3B]);
|
|
|
|
|
| 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) {
|
|
|
| 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) {
|
|
|
| const lzwMinCodeSize = 8;
|
| const compressed = [lzwMinCodeSize];
|
|
|
|
|
| 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);
|
|
|
| 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() {
|
| 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 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);
|
| }
|
|
|