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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// ══════════════════════════════════════════════════════════════════════════════
// 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 = `

      <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);
  }

  // ════════════════════════════════════════════════════════════════════════════
  // 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);
}