-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathltr_demo.html
More file actions
784 lines (712 loc) · 35.1 KB
/
Copy pathltr_demo.html
File metadata and controls
784 lines (712 loc) · 35.1 KB
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebCodecs LTR Demo</title>
<link rel="icon" href="data:,">
<style>
body {
font-family: sans-serif;
margin: 1em;
background-color: #f4f4f4;
color: #333;
}
h1 {
text-align: center;
color: #0056b3;
}
.main-container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 1em;
height: 85vh; /* Reduced height to prevent videos from being too large */
}
.quadrant {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #fff;
padding: 1em;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
video, canvas {
border: 1px solid #ccc;
background-color: #000;
width: 100%;
height: auto;
max-height: 100%;
}
#rawVideo {
transform: scaleX(-1);
}
.settings {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
.settings h2 {
margin-top: 0;
color: #0056b3;
}
.settings > div {
margin-bottom: 10px;
display: flex;
align-items: center;
}
.settings label {
margin-right: 10px;
width: 120px;
}
.settings select, .settings input[type="range"] {
flex-grow: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.controls {
text-align: center;
margin-top: 1em; /* Add margin to separate from the grid */
}
button {
padding: 10px 20px;
font-size: 1em;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.view-label {
position: absolute;
top: 5px;
left: 5px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
padding: 2px 5px;
border-radius: 3px;
font-size: 0.9em;
}
.highlight-warning {
background-color: red;
color: white;
padding: 10px;
border-radius: 4px;
text-align: center;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>WebCodecs LTR Demo</h1>
<div class="main-container">
<div class="quadrant">
<video id="rawVideo" autoplay muted playsinline></video>
<div class="view-label">Self View</div>
</div>
<div class="quadrant">
<canvas id="standardCanvas"></canvas>
<div class="view-label">Standard View</div>
</div>
<div class="quadrant">
<div class="settings">
<h2>Settings</h2>
<div>
<label for="codec">Codec:</label>
<select id="codec"></select>
</div>
<div>
<label for="encoderBitrate">Encoder Target Bitrate (kbps):</label>
<input type="range" id="encoderBitrate" min="100" max="2500" value="1000">
<span id="encoderBitrateValue">1000 kbps</span>
</div>
<div>
<label for="transportBitrate">Transport Limit (kbps):</label>
<input type="range" id="transportBitrate" min="100" max="2500" value="1500">
<span id="transportBitrateValue">1500 kbps</span>
</div>
<div>
<label for="rttDelay">RTT Delay (ms):</label>
<input type="range" id="rttDelay" min="0" max="500" value="300">
<span id="rttDelayValue">300 ms</span>
</div>
<div>
<label for="lossPercent">Loss Percent:</label>
<input type="range" id="lossPercent" min="0" max="100" value="12">
<span id="lossPercentValue">12%</span>
</div>
<div>
<button id="requestKeyframeButton">Request Keyframe</button>
</div>
</div>
</div>
<div class="quadrant">
<canvas id="decodedCanvas"></canvas>
<div class="view-label">LTR View</div>
</div>
</div>
<div class="controls">
<button id="startButton">Start Demo</button>
<button id="stopButton" disabled>Stop Demo</button>
</div>
<div id="warningMessage">
This demo uses experimental WebCodecs features for manual reference frame control. It is currently best supported in Chromium-based browsers with the <code>chrome://flags/#enable-experimental-web-platform-features</code> flag enabled.
</div>
<script src="simple_rate_controller.js"></script>
<script src="ltr_reference_controller.js"></script>
<script src="simulated_frame_transport.js"></script>
<script src="frame_assembler.js"></script>
<script src="encoded_frame.js"></script>
<script src="frame_metadata_store.js"></script>
<script>
/**
* @fileoverview LTR Demo main script.
* This script sets up two WebCodecs pipelines: one standard and one LTR-enabled.
* It simulates network conditions and visualizes the output of both pipelines.
*/
const rawVideo = document.getElementById('rawVideo');
const decodedCanvas = document.getElementById('decodedCanvas');
const decodedCtx = decodedCanvas.getContext('2d');
const standardCanvas = document.getElementById('standardCanvas');
const standardCtx = standardCanvas.getContext('2d');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
const codecSelect = document.getElementById('codec');
const transportBitrateSlider = document.getElementById('transportBitrate');
const transportBitrateValue = document.getElementById('transportBitrateValue');
const encoderBitrateSlider = document.getElementById('encoderBitrate');
const encoderBitrateValue = document.getElementById('encoderBitrateValue');
const requestKeyframeButton = document.getElementById('requestKeyframeButton');
const rttDelaySlider = document.getElementById('rttDelay');
const rttDelayValue = document.getElementById('rttDelayValue');
const lossPercentSlider = document.getElementById('lossPercent');
const lossPercentValue = document.getElementById('lossPercentValue');
let currentTransportBitrate = parseInt(transportBitrateSlider.value) * 1000;
let currentRttDelay = parseInt(rttDelaySlider.value);
let currentLossPercent = parseInt(lossPercentSlider.value);
let mediaStream = null;
let encoder = null; // Standard pipeline encoder
let decoder = null; // Standard pipeline decoder
let transport = null; // Standard pipeline simulated transport
let frameAssembler = null; // Standard pipeline frame assembler
let rateController = null; // Standard pipeline rate controller
let frameMetadataStore = null; // Standard pipeline metadata store
let currentQpUsed = -1; // QP used for the last standard frame
let encoderLtr = null; // LTR pipeline encoder
let decoderLtr = null; // LTR pipeline decoder
let transportLtr = null; // LTR pipeline simulated transport
let frameAssemblerLtr = null; // LTR pipeline frame assembler
let rateControllerLtr = null; // LTR pipeline rate controller
let frameMetadataStoreLtr = null; // LTR pipeline metadata store
let currentQpUsedLtr = -1; // QP used for the last LTR frame
let ltrController = null; // LTR reference frame controller
let frameSource = null;
let frameReader = null; // Store the reader instance
const framerate = 30;
let lastConfiguredCodec = '';
let needsKeyFrame = false;
let frameIdCounter = 0;
let frameIdCounterLtr = 0;
// Hardcoded Rate Control Parameters
const RC_MIN_QP = 10;
const RC_MAX_QP = 50;
const RC_ALPHA = 0.5;
const RC_KP_BUFFER = 0.1;
const RC_TARGET_FULLNESS = 30;
const RC_MAX_BUFFER_LEVEL_MS = 600;
/**
* Updates the bitrate for both rate controllers based on the slider value.
*/
function updateRateController() {
const newBitrate = parseInt(encoderBitrateSlider.value) * 1000;
if (rateController) {
rateController.SetRates(newBitrate, framerate, RC_MAX_BUFFER_LEVEL_MS, RC_TARGET_FULLNESS, performance.now(), RC_ALPHA, RC_KP_BUFFER);
}
if (rateControllerLtr) {
rateControllerLtr.SetRates(newBitrate, framerate, RC_MAX_BUFFER_LEVEL_MS, RC_TARGET_FULLNESS, performance.now(), RC_ALPHA, RC_KP_BUFFER);
}
}
/**
* Populates the codec dropdown list with supported codecs found on the system.
* Checks for both hardware and software encoder support for manual scalability mode.
*/
async function populateCodecList() {
codecSelect.innerHTML = ''; // Clear existing options
const warningMessage = document.getElementById('warningMessage');
warningMessage.classList.remove('highlight-warning');
const codecs = [
{ name: 'H.264', codec: 'avc1.42001E', type: 'avc' },
{ name: 'H.265', codec: 'hev1.1.6.L93.B0', type: 'hevc' },
{ name: 'VP8', codec: 'vp8', type: 'vp8' },
{ name: 'VP9', codec: 'vp09.00.10.08', type: 'vp9' },
{ name: 'AV1', codec: 'av01.0.04M.08', type: 'av1' },
];
let foundCodec = false;
for (const codecInfo of codecs) {
const baseConfig = {
codec: codecInfo.codec,
width: 640,
height: 480,
bitrateMode: "quantizer",
scalabilityMode: "manual",
};
let hwConfig = { ...baseConfig, hardwareAcceleration: 'prefer-hardware' };
try {
const hwSupport = await VideoEncoder.isConfigSupported(hwConfig);
if (hwSupport.supported) {
const option = document.createElement('option');
option.value = `${codecInfo.type}-hw`;
option.textContent = `${codecInfo.name} (HW)`;
codecSelect.appendChild(option);
foundCodec = true;
}
} catch (e) { console.warn(`Error checking HW support for ${codecInfo.name}: ${e}`); }
let swConfig = { ...baseConfig, hardwareAcceleration: 'prefer-software' };
try {
const swSupport = await VideoEncoder.isConfigSupported(swConfig);
if (swSupport.supported) {
const option = document.createElement('option');
option.value = `${codecInfo.type}-sw`;
option.textContent = `${codecInfo.name} (SW)`;
codecSelect.appendChild(option);
foundCodec = true;
}
} catch (e) { console.warn(`Error checking SW support for ${codecInfo.name}: ${e}`); }
}
if (!foundCodec) {
warningMessage.classList.add('highlight-warning');
const option = document.createElement('option');
option.textContent = "No codecs with manual mode support found";
codecSelect.appendChild(option);
codecSelect.disabled = true;
startButton.disabled = true;
} else {
codecSelect.disabled = false;
const av1Sw = codecSelect.querySelector ('option[value="av1-sw"]');
if (av1Sw) av1Sw.selected = true; // Default to AV1 SW if available
}
}
/**
* Generates the VideoEncoder configuration object.
* @param {boolean} isLtr - True if configuring for the LTR pipeline.
* @returns {VideoEncoderConfig} The encoder configuration.
*/
function getEncoderConfig(isLtr) {
const selectedCodecOption = codecSelect.value;
const [type, accel] = selectedCodecOption.split('-');
let encoderConfig = {
codec: '',
width: rawVideo.videoWidth,
height: rawVideo.videoHeight,
framerate: framerate,
bitrateMode: "quantizer",
};
if (isLtr) {
encoderConfig.scalabilityMode = "manual";
}
if (accel === 'hw') {
encoderConfig.hardwareAcceleration = 'prefer-hardware';
} else if (accel === 'sw') {
encoderConfig.hardwareAcceleration = 'prefer-software';
}
switch (type) {
case 'avc':
encoderConfig.codec = 'avc1.42001E';
encoderConfig.avc = { format: 'annexb' };
break;
case 'hevc':
encoderConfig.codec = 'hev1.1.6.L93.B0';
encoderConfig.hevc = { format: 'annexb' };
break;
case 'vp8': encoderConfig.codec = 'vp8'; break;
case 'vp9': encoderConfig.codec = 'vp09.00.10.08'; break;
case 'av1': encoderConfig.codec = 'av01.0.04M.08'; break;
}
return encoderConfig;
}
/**
* Generates the VideoDecoder configuration object.
* @param {VideoEncoderConfig} encoderConfig - The corresponding encoder configuration.
* @param {ArrayBuffer} [description=null] - Optional decoder description from encoder metadata.
* @returns {VideoDecoderConfig} The decoder configuration.
*/
function getDecoderConfig(encoderConfig, description = null) {
const decoderConfig = {
codec: encoderConfig.codec,
codedWidth: encoderConfig.width,
codedHeight: encoderConfig.height,
hardwareAcceleration: 'prefer-software' // Force software decoding for stability
};
if (encoderConfig.avc) decoderConfig.avc = { ...encoderConfig.avc };
if (encoderConfig.hevc) decoderConfig.hevc = { ...encoderConfig.hevc };
if (description) decoderConfig.description = description;
return decoderConfig;
}
/**
* Sets the quantizer parameter in the encode options based on the codec type.
* @param {object} encodeOptions - The base encode options object.
* @param {number} qp - The quantization parameter.
* @param {string} codecType - The codec type (e.g., 'av1', 'vp9').
*/
function setQpEncodeOptions(encodeOptions, qp, codecType) {
switch (codecType) {
// AV1 uses full 0-255 QP range, but for simplicity just translate from the 0-63 assumed in this demo.
case 'av1': encodeOptions.av1 = { quantizer: qp * 4 }; break;
case 'vp9': encodeOptions.vp9 = { quantizer: qp }; break;
case 'vp8': encodeOptions.vp8 = { quantizer: qp }; break;
case 'avc': encodeOptions.avc = { quantizer: qp }; break;
case 'hevc': encodeOptions.hevc = { quantizer: qp }; break;
}
}
/**
* Creates and configures a full encoding/decoding pipeline.
* @param {boolean} isLtr - Whether this is the LTR-enabled pipeline.
* @param {CanvasRenderingContext2D} drawCtx - The canvas context to render decoded frames to.
* @returns {Promise<object>} The pipeline components.
*/
async function createPipeline(isLtr, drawCtx) {
const pipeline = {
encoder: null,
decoder: null,
transport: null,
frameAssembler: null,
rateController: null,
frameMetadataStore: new FrameMetadataStore(),
currentQpUsed: -1,
lastEncodedDescription: null,
decoderConfiguredWithDescription: false,
frameIdCounter: 0,
lastEncodedFrameId: -1,
isLtr: isLtr,
name: isLtr ? "LTR" : "Standard",
lastDisplayedTimestamp: -1
};
// Initialize SimulatedFrameTransport
pipeline.transport = new SimulatedFrameTransport(async (encodedFrame, meta) => {
if (pipeline.frameAssembler) pipeline.frameAssembler.OnFrameReceived(encodedFrame);
else console.warn(`[${pipeline.name}] FrameAssembler not ready on transport receipt`);
}, currentRttDelay, currentLossPercent);
pipeline.transport.SetRate(currentTransportBitrate);
// Initialize FrameAssembler
pipeline.frameAssembler = new FrameAssembler((encodedFrame) => {
if (pipeline.decoder && pipeline.decoder.state === 'configured') {
try { pipeline.decoder.decode(encodedFrame.encodedChunk); }
catch (e) { console.error(`[${pipeline.name}] decoder.decode error:`, e); }
} else { console.warn(`[${pipeline.name}] Decoder not configured, skipping decode.`); }
});
pipeline.frameAssembler.decoderNeedsKeyFrame = true;
const encoderConfig = getEncoderConfig(isLtr);
if (isLtr) lastConfiguredCodec = encoderConfig.codec;
// Initialize SimpleRateController
pipeline.rateController = new SimpleRateController(
encoderConfig.codec.split('.')[0], // codecType
RC_MIN_QP, RC_MAX_QP,
parseInt(encoderBitrateSlider.value) * 1000, framerate, performance.now(),
RC_MAX_BUFFER_LEVEL_MS, RC_TARGET_FULLNESS, RC_ALPHA, RC_KP_BUFFER,
-1, -1, -1 // Disable drop/re-encode for this demo
);
// Initialize VideoEncoder
pipeline.encoder = new VideoEncoder({
output: async (chunk, meta) => {
const frameMetadata = pipeline.frameMetadataStore.getFrameMetadata(chunk.timestamp);
pipeline.frameMetadataStore.pruneOldMetadata(chunk.timestamp);
let isLtrFrame = false;
// Initialize VideoDecoder if not already done
if (!pipeline.decoder) {
console.log(`[${pipeline.name}] Initializing decoder.`);
pipeline.lastEncodedDescription = meta.decoderConfig?.description || null;
const currentEncoderConfig = getEncoderConfig(pipeline.isLtr);
const decoderConfig = getDecoderConfig(currentEncoderConfig, pipeline.lastEncodedDescription);
pipeline.decoder = new VideoDecoder({
output: (frame) => {
const ts = frame.timestamp;
try {
if (ts > pipeline.lastDisplayedTimestamp) {
drawCtx.drawImage(frame, 0, 0, drawCtx.canvas.width, drawCtx.canvas.height);
pipeline.lastDisplayedTimestamp = ts;
}
} catch (e) { console.error(`[${pipeline.name}] Decoder drawImage error:`, e); }
finally { frame.close(); }
},
error: (e) => {
console.error(`[${pipeline.name}] Decoder Error:`, e);
needsKeyFrame = true;
if (pipeline.frameAssembler) pipeline.frameAssembler.decoderNeedsKeyFrame = true;
}
});
try {
await pipeline.decoder.configure(decoderConfig);
pipeline.decoderConfiguredWithDescription = pipeline.lastEncodedDescription != null;
} catch (e) {
console.error(`[${pipeline.name}] Error configuring decoder:`, e);
pipeline.decoder = null; return;
}
} else if (!pipeline.decoderConfiguredWithDescription && meta.decoderConfig && meta.decoderConfig.description) {
// Reconfigure decoder if description appears later
pipeline.lastEncodedDescription = meta.decoderConfig.description;
const currentEncoderConfig = getEncoderConfig(pipeline.isLtr);
const decoderConfig = getDecoderConfig(currentEncoderConfig, pipeline.lastEncodedDescription);
if (pipeline.decoder && pipeline.decoder.state !== 'closed') {
try {
await pipeline.decoder.configure(decoderConfig);
pipeline.decoderConfiguredWithDescription = true;
if (pipeline.frameAssembler) pipeline.frameAssembler.decoderNeedsKeyFrame = true;
} catch (e) { console.error(`[${pipeline.name}] Error reconfiguring decoder:`, e); }
}
}
if (!pipeline.decoderConfiguredWithDescription && chunk.type === 'key') {
pipeline.decoderConfiguredWithDescription = true;
}
pipeline.frameIdCounter++;
const isKeyFrame = (chunk.type === 'key');
let dependencies = [];
if (!isKeyFrame) {
if (pipeline.isLtr && ltrController) {
dependencies = ltrController.GetLastGoodFrameIds();
} else {
dependencies = [pipeline.lastEncodedFrameId];
}
}
let frameId = -1;
if (frameMetadata) {
isLtrFrame = frameMetadata.isLtr || false;
frameId = frameMetadata.frameId || pipeline.frameIdCounter;
} else {
console.warn(`[${pipeline.name}] No frame metadata found for ts: ${chunk.timestamp}`);
frameId = pipeline.frameIdCounter;
}
const encodedFrame = new EncodedFrame(chunk, frameId, dependencies, chunk.timestamp, isLtrFrame);
pipeline.lastEncodedFrameId = frameId;
pipeline.rateController.OnEncodedFrame(performance.now(), chunk.byteLength, pipeline.currentQpUsed, isKeyFrame);
if (pipeline.transport) {
pipeline.transport.SendFrame(encodedFrame, meta);
}
},
error: (e) => { console.error(`[${pipeline.name}] Encoder Error:`, e); }
});
await pipeline.encoder.configure(encoderConfig);
return pipeline;
}
/**
* Starts the video encoding process for both pipelines.
*/
async function startEncoding() {
if (!mediaStream) return;
const track = mediaStream.getVideoTracks()[0];
const processor = new MediaStreamTrackProcessor({ track: track });
frameSource = processor.readable;
// Create Standard Pipeline
const standardPipeline = await createPipeline(false, standardCtx);
encoder = standardPipeline.encoder;
decoder = standardPipeline.decoder;
transport = standardPipeline.transport;
frameAssembler = standardPipeline.frameAssembler;
rateController = standardPipeline.rateController;
frameMetadataStore = standardPipeline.frameMetadataStore;
// Create LTR Pipeline
const ltrPipeline = await createPipeline(true, decodedCtx);
encoderLtr = ltrPipeline.encoder;
decoderLtr = ltrPipeline.decoder;
transportLtr = ltrPipeline.transport;
frameAssemblerLtr = ltrPipeline.frameAssembler;
rateControllerLtr = ltrPipeline.rateController;
frameMetadataStoreLtr = ltrPipeline.frameMetadataStore;
const buffers = await encoderLtr.getAllFrameBuffers();
ltrController = new LtrReferenceController(buffers, rateControllerLtr);
transportLtr.ltrController = ltrController; // Give transport access to LTR controller for feedback
console.log('Number of available frame buffers for LTR:', buffers.length);
frameReader = frameSource.getReader(); // Store the reader
needsKeyFrame = true; // Request key frame at the start
/**
* Reads frames from the camera, encodes them with both pipelines, and schedules the next frame.
*/
function processFrame() {
if (stopButton.disabled) return;
frameReader.read().then(({ done, value }) => { // Use the stored reader
if (done || stopButton.disabled) {
if(value) value.close();
return;
}
const frame = value;
const timestamp = frame.timestamp;
const keyFrame = needsKeyFrame;
// Standard Encoding
if (encoder && encoder.state === 'configured' && rateController) {
frameIdCounter++;
const qp = rateController.GetNextQp(performance.now(), keyFrame);
currentQpUsed = qp;
const encodeOptions = { keyFrame: keyFrame };
const codecType = codecSelect.value.split('-')[0];
setQpEncodeOptions(encodeOptions, qp, codecType);
frameMetadataStore.addFrameMetadata(timestamp, { qp: currentQpUsed, encodeOptions: { ...encodeOptions }, frameId: frameIdCounter });
encoder.encode(frame, encodeOptions);
}
// LTR Encoding
if (encoderLtr && encoderLtr.state === 'configured' && ltrController && rateControllerLtr) {
frameIdCounterLtr++;
const ltrResult = ltrController.GetNextEncodeOptions(keyFrame, frameIdCounterLtr);
let encodeOptionsLtr = ltrResult.encodeOptions;
const isLtr = ltrResult.isLtr;
const qpLtr = rateControllerLtr.GetNextQp(performance.now(), keyFrame);
currentQpUsedLtr = qpLtr;
const codecType = codecSelect.value.split('-')[0];
setQpEncodeOptions(encodeOptionsLtr, qpLtr, codecType);
frameMetadataStoreLtr.addFrameMetadata(timestamp, { qp: currentQpUsedLtr, encodeOptions: { ...encodeOptionsLtr }, frameId: frameIdCounterLtr, isLtr: isLtr });
encoderLtr.encode(frame, encodeOptionsLtr);
}
frame.close(); // Close frame after both encode calls
if (needsKeyFrame) needsKeyFrame = false;
if (!stopButton.disabled) {
requestAnimationFrame(processFrame);
}
}).catch(e => {
console.error("Error in processFrame reader.read():", e);
if (!stopButton.disabled) requestAnimationFrame(processFrame);
});
}
requestAnimationFrame(processFrame);
}
/**
* Stops the encoding process and cleans up resources.
*/
async function stopEncoding() {
if (frameReader) {
try {
await frameReader.cancel();
} catch (e) {
console.warn("Error cancelling frameReader:", e);
}
frameReader = null;
}
if (frameSource) {
frameSource = null;
}
const cleanupPipeline = async (pipe, name) => {
if (pipe.encoder && pipe.encoder.state !== 'closed') {
try { await pipe.encoder.flush(); } catch (e) { console.error(`Error flushing ${name} encoder:`, e); }
pipe.encoder.close();
}
if (pipe.decoder && pipe.decoder.state !== 'closed') {
try { await pipe.decoder.flush(); } catch (e) { console.error(`Error flushing ${name} decoder:`, e); }
pipe.decoder.close();
}
if (pipe.transport) pipe.transport.Stop();
if (pipe.frameAssembler) pipe.frameAssembler.reset();
if (pipe.frameMetadataStore) pipe.frameMetadataStore.clear();
};
await cleanupPipeline({encoder, decoder, transport, frameAssembler, frameMetadataStore}, "Standard");
encoder = decoder = transport = frameAssembler = rateController = frameMetadataStore = null;
await cleanupPipeline({encoder: encoderLtr, decoder: decoderLtr, transport: transportLtr, frameAssembler: frameAssemblerLtr, frameMetadataStore: frameMetadataStoreLtr}, "LTR");
encoderLtr = decoderLtr = transportLtr = frameAssemblerLtr = rateControllerLtr = frameMetadataStoreLtr = null;
ltrController = null;
decodedCtx.clearRect(0, 0, decodedCanvas.width, decodedCanvas.height);
standardCtx.clearRect(0, 0, standardCanvas.width, standardCanvas.height);
needsKeyFrame = false;
}
/**
* Reconfigures the encoders if the codec selection changes.
*/
async function reconfigureEncoder() {
const reconfig = async (enc, isLtr, dec, assembler) => {
if (!enc || enc.state !== 'configured') return false;
const encoderConfig = getEncoderConfig(isLtr);
await enc.configure(encoderConfig);
if (encoderConfig.codec !== lastConfiguredCodec) {
if (dec && dec.state !== 'closed') {
const decoderConfig = getDecoderConfig(encoderConfig, null);
try { await dec.configure(decoderConfig); } catch (e) { console.error(`Error reconfiguring decoder:`, e); }
}
if (assembler) {
assembler.decoderNeedsKeyFrame = true;
assembler.reset();
}
return true;
}
return false;
};
const standardChanged = await reconfig(encoder, false, decoder, frameAssembler);
const ltrChanged = await reconfig(encoderLtr, true, decoderLtr, frameAssemblerLtr);
if (standardChanged || ltrChanged) {
console.log('Codec changed, reconfiguring decoders and requesting key frame');
lastConfiguredCodec = getEncoderConfig(false).codec;
needsKeyFrame = true;
}
}
// Event Listeners
transportBitrateSlider.addEventListener('input', () => {
transportBitrateValue.textContent = transportBitrateSlider.value + ' kbps';
currentTransportBitrate = parseInt(transportBitrateSlider.value) * 1000;
if (transport) transport.SetRate(currentTransportBitrate);
if (transportLtr) transportLtr.SetRate(currentTransportBitrate);
});
encoderBitrateSlider.addEventListener('input', () => {
encoderBitrateValue.textContent = encoderBitrateSlider.value + ' kbps';
updateRateController();
});
rttDelaySlider.addEventListener('input', () => {
rttDelayValue.textContent = rttDelaySlider.value + ' ms';
currentRttDelay = parseInt(rttDelaySlider.value);
if (transport) transport.SetRttDelay(currentRttDelay);
if (transportLtr) transportLtr.SetRttDelay(currentRttDelay);
});
lossPercentSlider.addEventListener('input', () => {
lossPercentValue.textContent = lossPercentSlider.value + '%';
currentLossPercent = parseInt(lossPercentSlider.value);
if (transport) transport.SetLossPercent(currentLossPercent);
if (transportLtr) transportLtr.SetLossPercent(currentLossPercent);
});
codecSelect.addEventListener('change', () => reconfigureEncoder());
requestKeyframeButton.addEventListener('click', () => {
if ((encoder && encoder.state === 'configured') || (encoderLtr && encoderLtr.state === 'configured')) {
needsKeyFrame = true;
console.log("Keyframe requested for next frame");
}
});
startButton.addEventListener('click', async () => {
startButton.disabled = true;
stopButton.disabled = true;
try {
mediaStream = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 360 }, audio: false });
rawVideo.srcObject = mediaStream;
await rawVideo.play();
const videoWidth = rawVideo.videoWidth;
const videoHeight = rawVideo.videoHeight;
[decodedCanvas, standardCanvas].forEach(canvas => {
canvas.width = videoWidth;
canvas.height = videoHeight;
});
stopButton.disabled = false;
await startEncoding();
} catch (err) {
console.error("Error accessing camera: ", err);
alert("Could not access camera. Please ensure permission is granted.");
startButton.disabled = false;
}
});
stopButton.addEventListener('click', async () => {
stopButton.disabled = true;
await stopEncoding();
if (mediaStream) {
mediaStream.getTracks().forEach(track => track.stop());
mediaStream = null;
rawVideo.srcObject = null;
}
startButton.disabled = false;
});
window.addEventListener('load', () => populateCodecList());
</script>
</body>
</html>