/** * EXPERIMENTAL SPIKE CODE - Issue #166 * * Proof of Concept: Publishing custom video frames to LiveKit using @livekit/rtc-node * * This spike demonstrates: * 1. Creating a VideoSource with specific dimensions * 2. Creating a VideoFrame from image buffer data * 3. Publishing frames using captureFrame() * 4. Publishing the video track to a LiveKit room * * Status: This is research code - NOT production ready * * Findings: * - LiveKit SDK DOES support custom video sources from buffers * - No FFmpeg required for frame encoding (SDK handles it internally) * - Supports multiple buffer formats: RGBA, BGRA, RGB24, I420, NV12, etc. * - Simple API similar to audio track publishing */ import { VideoSource, LocalVideoTrack, VideoFrame, VideoBufferType, TrackSource, TrackPublishOptions, type Room } from '@livekit/rtc-node'; import type { Page } from 'playwright'; /** * Spike: Convert Playwright screenshot to VideoFrame and publish to LiveKit */ export class VideoTrackPublishingSpike { private videoSource: VideoSource | null = null; private videoTrack: LocalVideoTrack | null = null; private room: Room | null = null; // Video configuration private readonly WIDTH = 1920; private readonly HEIGHT = 1080; private readonly FPS = 30; /** * Initialize video source and track */ async initialize(room: Room): Promise { this.room = room; // Create VideoSource with dimensions console.log('[Spike] Creating VideoSource:', this.WIDTH, 'x', this.HEIGHT); this.videoSource = new VideoSource(this.WIDTH, this.HEIGHT); // Create LocalVideoTrack from the source console.log('[Spike] Creating LocalVideoTrack'); this.videoTrack = LocalVideoTrack.createVideoTrack('screenshare', this.videoSource); // Publish the track to the room const publishOptions = new TrackPublishOptions({ source: TrackSource.SOURCE_SCREEN_SHARE, // Optional: Configure video encoding // videoCodec: VideoCodec.H264, // videoEncoding: { // maxFramerate: this.FPS, // maxBitrate: 2_000_000n // 2 Mbps // } }); console.log('[Spike] Publishing video track to room'); await this.room.localParticipant.publishTrack(this.videoTrack, publishOptions); console.log('[Spike] Video track published successfully'); } /** * Capture a single frame from Playwright and publish to LiveKit * * This demonstrates the core integration: * 1. Take screenshot from Playwright page * 2. Convert to VideoFrame * 3. Push to VideoSource using captureFrame() */ async captureAndPublishFrame(page: Page): Promise { if (!this.videoSource || !this.videoTrack) { throw new Error('Video source/track not initialized'); } // APPROACH 1: Using PNG screenshot buffer // Get screenshot as buffer from Playwright const _screenshotBuffer = await page.screenshot({ type: 'png', fullPage: false, }); // TODO: Convert PNG to raw RGBA buffer // This requires a library like 'sharp' or 'jimp' to decode PNG // For the spike, we'll demonstrate with a synthetic RGBA buffer // APPROACH 2: Synthetic RGBA buffer (for demonstration) const rgbaBuffer = this.createSyntheticFrame(); // Create VideoFrame from RGBA buffer const videoFrame = new VideoFrame( rgbaBuffer, this.WIDTH, this.HEIGHT, VideoBufferType.RGBA ); // Capture frame to video source // The SDK will handle encoding to H264/VP8/etc. const timestampUs = BigInt(Date.now() * 1000); // Convert ms to microseconds this.videoSource.captureFrame(videoFrame, timestampUs); console.log('[Spike] Frame captured and published'); } /** * Start continuous frame capture loop */ async startContinuousCapture(page: Page): Promise { const intervalMs = 1000 / this.FPS; console.log(`[Spike] Starting continuous capture at ${this.FPS}fps`); setInterval(() => { void (async () => { try { await this.captureAndPublishFrame(page); } catch (error) { console.error('[Spike] Error capturing frame:', error); } })(); }, intervalMs); } /** * Helper: Create synthetic RGBA frame for testing * In production, this would come from PNG decoding */ private createSyntheticFrame(): Uint8Array { const buffer = new Uint8Array(this.WIDTH * this.HEIGHT * 4); // RGBA = 4 bytes per pixel // Fill with a gradient pattern for testing for (let y = 0; y < this.HEIGHT; y++) { for (let x = 0; x < this.WIDTH; x++) { const i = (y * this.WIDTH + x) * 4; buffer[i + 0] = (x / this.WIDTH) * 255; // R buffer[i + 1] = (y / this.HEIGHT) * 255; // G buffer[i + 2] = 128; // B buffer[i + 3] = 255; // A } } return buffer; } /** * Clean up resources */ async cleanup(): Promise { if (this.room && this.videoTrack) { await this.room.localParticipant.unpublishTrack(this.videoTrack.sid); } this.videoSource = null; this.videoTrack = null; } } /** * SPIKE CONCLUSIONS: * * ✅ WORKS: LiveKit SDK supports custom video frames from buffers * ✅ WORKS: Simple API - VideoSource -> VideoFrame -> captureFrame() * ✅ WORKS: SDK handles video encoding internally (no FFmpeg needed) * ✅ WORKS: Supports multiple buffer formats (RGBA, BGRA, I420, etc.) * * ⚠️ ISSUE: Playwright screenshots return PNG buffers * ⚠️ ISSUE: Need to decode PNG to raw RGBA/RGB buffer * * 🔧 SOLUTION OPTIONS: * * Option 1: Use 'sharp' library to decode PNG to raw buffer * - Fast, widely used, supports many formats * - Native dependencies (need to ensure compatibility) * - Example: sharp(buffer).raw().toBuffer() * * Option 2: Use 'jimp' library (pure JavaScript) * - No native dependencies * - Slower than sharp * - Example: Jimp.read(buffer).then(img => img.bitmap.data) * * Option 3: Use 'pngjs' (PNG-specific, pure JS) * - Lightweight, PNG-only * - No native dependencies * - Good for our use case * * RECOMMENDED: Option 1 (sharp) for production performance */