Repository navigation
Expand file tree
/
Copy pathrate_control_demo.html
More file actions
1189 lines (1090 loc) · 50.7 KB
/
Copy pathrate_control_demo.html
File metadata and controls
1189 lines (1090 loc) · 50.7 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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebCodecs Rate Control Demo</title>
<link rel="icon" href="data:,">
<style>
body {
font-family: sans-serif;
margin: 20px;
background-color: #f4f4f4;
color: #333;
}
h1 {
text-align: center;
color: #0056b3;
}
.videos {
display: flex;
justify-content: space-around;
margin-bottom: 20px;
}
video {
border: 1px solid #ccc;
background-color: #000;
}
#decodedCanvas {
border: 1px solid #ccc;
background-color: #000;
}
#bitrateGraph {
border: 1px solid #ccc;
background-color: #fff;
}
#rawVideo {
transform: scaleX(-1);
}
.layout-container {
display: flex;
justify-content: space-around;
margin-bottom: 20px;
}
.settings {
background-color: #fff;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
width: 48%;
}
.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"], .settings input[type="number"] {
flex-grow: 1;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.settings input[type="range"] {
margin-right: 10px;
}
.settings input[type="number"].invalid {
border-color: red;
}
.graph {
background-color: #fff;
padding: 15px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
width: 48%;
display: flex;
flex-direction: column;
align-items: center;
color: #333;
}
.graph h3 {
margin-top: 0;
margin-bottom: 10px;
color: #0056b3;
}
.graph-legend {
display: flex;
justify-content: center;
margin-top: 10px;
font-size: 12px;
}
.legend-item {
margin: 0 10px;
display: flex;
align-items: center;
}
.legend-color {
width: 12px;
height: 12px;
margin-right: 5px;
border: 1px solid #ccc;
}
.controls {
text-align: center;
}
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;
}
</style>
</head>
<body>
<h1>WebCodecs Rate Control Demo</h1>
<div class="videos">
<video id="rawVideo" width="640" height="480" autoplay muted playsinline></video>
<canvas id="decodedCanvas" width="640" height="480"></canvas>
</div>
<div class="layout-container">
<div class="settings">
<h2>Settings</h2>
<div>
<label for="rateControlMode">Rate Control:</label>
<select id="rateControlMode">
<option value="internal" selected>Internal</option>
<option value="external">External</option>
</select>
</div>
<div>
<label for="codec">Codec:</label>
<select id="codec">
</select>
</div>
<div>
<label for="bitrate">Bitrate (kbps):</label>
<input type="range" id="bitrate" min="100" max="2500" value="500">
<span id="bitrateValue">500 kbps</span>
</div>
<div id="externalRcSettings" style="display: none;">
<div>
<label for="minQp">Min QP:</label>
<input type="number" id="minQp" value="10">
</div>
<div>
<label for="maxQp">Max QP:</label>
<input type="number" id="maxQp" value="50">
</div>
<div>
<label for="alpha">Alpha (EMA):</label>
<input type="range" id="alpha" min="0.01" max="1.0" step="0.01" value="0.65">
<span id="alphaValue">0.65</span>
</div>
<div>
<label for="kpBuffer">Kp Buffer:</label>
<input type="range" id="kpBuffer" min="0.00001" max="0.5" step="0.00001" value="0.25">
<span id="kpBufferValue">0.25000</span>
</div>
<div>
<label for="targetFullness">Target Fullness (%):</label>
<input type="range" id="targetFullness" min="0" max="100" step="1" value="15">
<span id="targetFullnessValue">15%</span>
</div>
<div>
<input type="checkbox" id="enableDropReencode">
<label for="enableDropReencode">Enable Frame Drop/Re-encode</label>
</div>
<div id="dropReencodeSettings" style="display: none;">
<div>
<label for="frameDropThreshold">Drop Threshold (%):</label>
<input type="number" id="frameDropThreshold" value="95" min="0" max="100">
</div>
<div>
<label for="reencodeOvershootPercent">Re-encode Over Margin (+%):</label>
<input type="number" id="reencodeOvershootPercent" value="1" min="0" max="100">
</div>
<div>
<label for="reencodeUndershootPercent">Re-encode Under Margin (-%):</label>
<input type="number" id="reencodeUndershootPercent" value="40" min="0" max="100">
</div>
<div>
<label for="maxReencodeCount">Max Re-encodes:</label>
<input type="number" id="maxReencodeCount" value="5" min="0" max="10">
</div>
</div>
</div>
<div>
<button id="requestKeyframeButton">Request Keyframe</button>
</div>
</div>
<div class="graph">
<canvas id="bitrateGraph" width="600" height="350"></canvas>
<div class="graph-legend">
<div class="legend-item">
<span class="legend-color" style="background-color: blue;"></span> Target
</div>
<div class="legend-item">
<span class="legend-color" style="background-color: red;"></span> Actual
</div>
</div>
</div>
</div>
<div class="controls">
<button id="startButton">Start Demo</button>
<button id="stopButton" disabled>Stop Demo</button>
</div>
<script src="simple_rate_controller.js"></script>
<script src="encoded_frame.js"></script>
<script>
/**
* @fileoverview This script demonstrates and compares internal (browser-managed)
* and external (JavaScript-managed) rate control mechanisms for WebCodecs.
* It allows users to configure various parameters and visualizes the target
* versus actual bitrate on a graph.
*/
const rawVideo = document.getElementById('rawVideo');
const decodedCanvas = document.getElementById('decodedCanvas');
const decodedCtx = decodedCanvas.getContext('2d');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
const rateControlModeSelect = document.getElementById('rateControlMode');
const codecSelect = document.getElementById('codec');
const bitrateSlider = document.getElementById('bitrate');
const bitrateValue = document.getElementById('bitrateValue');
const externalRcSettingsDiv = document.getElementById('externalRcSettings');
const minQpInput = document.getElementById('minQp');
const maxQpInput = document.getElementById('maxQp');
const alphaSlider = document.getElementById('alpha');
const alphaValueSpan = document.getElementById('alphaValue');
const kpBufferSlider = document.getElementById('kpBuffer');
const kpBufferValueSpan = document.getElementById('kpBufferValue');
const targetFullnessSlider = document.getElementById('targetFullness');
const targetFullnessValueSpan = document.getElementById('targetFullnessValue');
const requestKeyframeButton = document.getElementById('requestKeyframeButton');
const graphCanvas = document.getElementById('bitrateGraph');
const graphCtx = graphCanvas.getContext('2d');
// New UI elements for Drop/Re-encode
const enableDropReencodeCheckbox = document.getElementById('enableDropReencode');
const dropReencodeSettingsDiv = document.getElementById('dropReencodeSettings');
const frameDropThresholdInput = document.getElementById('frameDropThreshold');
const reencodeOvershootPercentInput = document.getElementById('reencodeOvershootPercent');
const reencodeUndershootPercentInput = document.getElementById('reencodeUndershootPercent');
const maxReencodeCountInput = document.getElementById('maxReencodeCount');
let mediaStream = null;
let encoder = null;
let decoder = null;
let frameSource = null;
let frameReader = null;
let isProcessingFrame = false;
const framerate = 30;
let lastConfiguredCodec = '';
let needsKeyFrame = false;
let rateController = null;
let lastEncodedDescription = null;
let decoderNeedsKeyFrame = false;
let frameIdCounter = 0;
let lastEncodedFrameId = -1;
let currentQpUsed = -1;
let maxBufferLevelMs = 600;
let targetFullnessPercent = 25;
let buffers = [];
let currentFrame = null;
let inputFrameIndex = 0;
let encodeCount = 0;
let encoderInstanceId = 0;
// Graph variables
let graphData = [];
const maxGraphPoints = 240; // Show last 12 seconds at 50ms interval
let frameSizeData = []; // Array to store {size: bytes, timestamp: ms}
const graphWindowMs = 300; // 0.3 second rolling window
let graphIntervalId = null;
const graphUpdateInterval = 50; // ms
const VIDEO_WIDTH = 640;
const VIDEO_HEIGHT = 480;
/**
* Populates the codec select dropdown with supported codecs and acceleration types.
* @param {string} [bitrateMode="constant"] - The bitrate mode to check support for ('constant' or 'quantizer').
*/
async function populateCodecList(bitrateMode = "constant") {
codecSelect.innerHTML = ''; // Clear existing options
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' },
];
for (const codecInfo of codecs) {
const baseConfig = {
codec: codecInfo.codec,
width: VIDEO_WIDTH,
height: VIDEO_HEIGHT,
bitrateMode: bitrateMode,
};
if (bitrateMode === 'constant') {
baseConfig.bitrate = 500000;
}
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);
}
} catch (e) { console.warn(`Error checking HW support for ${codecInfo.name} (${bitrateMode}): ${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);
}
} catch (e) { console.warn(`Error checking SW support for ${codecInfo.name} (${bitrateMode}): ${e}`); }
}
const av1Hw = codecSelect.querySelector('option[value="av1-hw"]');
const av1Sw = codecSelect.querySelector('option[value="av1-sw"]');
if (av1Hw) av1Hw.selected = true;
else if (av1Sw) av1Sw.selected = true;
}
/**
* Draws the bitrate graph on the canvas, showing target vs. actual bitrate.
*/
function drawGraph() {
const width = graphCanvas.width;
const height = graphCanvas.height;
graphCtx.clearRect(0, 0, width, height);
if (graphData.length === 0) return;
const paddingLeft = 70;
const paddingRight = 10;
const paddingTop = 10;
const paddingBottom = 20;
const graphHeight = height - paddingTop - paddingBottom;
const graphWidth = width - paddingLeft - paddingRight;
graphCtx.strokeStyle = '#ccc';
graphCtx.lineWidth = 1;
graphCtx.font = '12px sans-serif';
graphCtx.fillStyle = '#333';
graphCtx.textAlign = "right";
let maxBitrate = 500000;
graphData.forEach(p => {
maxBitrate = Math.max(maxBitrate, p.target, p.actual);
});
maxBitrate = Math.ceil(maxBitrate / 500000) * 500000;
const scaleY = graphHeight / maxBitrate;
const scaleX = graphWidth / (maxGraphPoints - 1);
const yLabelCount = 5;
for (let i = 0; i <= yLabelCount; i++) {
const val = (maxBitrate / yLabelCount) * i;
const y = paddingTop + graphHeight - val * scaleY;
graphCtx.fillText(`${(val / 1000).toFixed(0)} kbps`, paddingLeft - 10, y + 4);
graphCtx.beginPath();
graphCtx.moveTo(paddingLeft, y);
graphCtx.lineTo(width - paddingRight, y);
graphCtx.stroke();
}
graphCtx.beginPath();
graphCtx.moveTo(paddingLeft, height - paddingBottom);
graphCtx.lineTo(width - paddingRight, height - paddingBottom);
graphCtx.stroke();
const plotX = (index) => paddingLeft + index * scaleX;
const plotY = (bitrate) => paddingTop + graphHeight - bitrate * scaleY;
graphCtx.beginPath();
graphCtx.strokeStyle = 'blue';
graphCtx.lineWidth = 2;
graphData.forEach((point, index) => {
const x = plotX(index);
const y = plotY(point.target);
if (index === 0) graphCtx.moveTo(x, y);
else graphCtx.lineTo(x, y);
});
graphCtx.stroke();
graphCtx.beginPath();
graphCtx.strokeStyle = 'red';
graphCtx.lineWidth = 2;
graphData.forEach((point, index) => {
const x = plotX(index);
const y = plotY(point.actual);
if (index === 0) graphCtx.moveTo(x, y);
else graphCtx.lineTo(x, y);
});
graphCtx.stroke();
}
/**
* Creates the VideoEncoder configuration object based on UI settings.
* @returns {VideoEncoderConfig} The encoder configuration.
*/
function getEncoderConfig() {
const selectedCodecOption = codecSelect.value;
const [type, accel] = selectedCodecOption.split('-');
const bitrate = parseInt(bitrateSlider.value) * 1000;
const rcMode = rateControlModeSelect.value;
let encoderConfig = {
codec: '',
width: VIDEO_WIDTH,
height: VIDEO_HEIGHT,
framerate: framerate,
};
if (rcMode === 'internal') {
encoderConfig.bitrate = bitrate;
encoderConfig.bitrateMode = "constant";
} else { // external
encoderConfig.bitrateMode = "quantizer";
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;
}
/**
* Creates the VideoDecoder configuration object.
* @param {VideoEncoderConfig} encoderConfig - The corresponding encoder configuration.
* @param {ArrayBuffer|null} [description=null] - Optional description for codecs like HEVC.
* @returns {VideoDecoderConfig} The decoder configuration.
*/
function getDecoderConfig(encoderConfig, description = null) {
const decoderConfig = {
codec: encoderConfig.codec,
codedWidth: VIDEO_WIDTH,
codedHeight: VIDEO_HEIGHT
};
if (encoderConfig.codec.startsWith('avc1')) {
decoderConfig.avc = { format: 'annexb' };
decoderConfig.hardwareAcceleration = 'prefer-software';
console.log('Forcing software decode for H.264');
} else if (encoderConfig.codec.startsWith('hev1') && description) {
decoderConfig.description = description;
decoderConfig.hardwareAcceleration = 'prefer-hardware';
decoderConfig.hevc = { format: 'annexb' };
console.log('Using description for HEVC decoder config with hardware acceleration');
}
return decoderConfig;
}
/**
* Returns the valid Quantization Parameter (QP) range for a given codec type.
* @param {string} codecType - The codec type (e.g., 'avc', 'vp9').
* @returns {{min: number, max: number}} The min and max QP values.
*/
function getQpRange(codecType) {
if (codecType === 'avc' || codecType === 'hevc') {
return { min: 0, max: 51 };
}
return { min: 0, max: 63 };
}
/**
* Updates the Min/Max QP input field defaults based on the selected codec.
*/
function updateQpInputDefaults() {
const codecType = codecSelect.value.split('-')[0];
const range = getQpRange(codecType);
minQpInput.value = range.min;
maxQpInput.value = range.max;
validateQpSettings();
updateRateController();
}
/**
* Validates the Min/Max QP input values and highlights them if invalid.
* @returns {boolean} True if the settings are valid, false otherwise.
*/
function validateQpSettings() {
const codecType = codecSelect.value.split('-')[0];
const range = getQpRange(codecType);
let minValid = range.min, maxValid = range.max;
const minQp = parseInt(minQpInput.value);
const maxQp = parseInt(maxQpInput.value);
let isValid = true;
minQpInput.classList.remove('invalid');
maxQpInput.classList.remove('invalid');
if (isNaN(minQp) || minQp < minValid || minQp > maxValid) {
minQpInput.classList.add('invalid');
isValid = false;
}
if (isNaN(maxQp) || maxQp < minValid || maxQp > maxValid) {
maxQpInput.classList.add('invalid');
isValid = false;
}
if (isValid && minQp > maxQp) {
minQpInput.classList.add('invalid');
maxQpInput.classList.add('invalid');
isValid = false;
}
return isValid;
}
/**
* Updates or creates the SimpleRateController instance based on UI settings.
* This is only active when 'External' rate control is selected.
*/
function updateRateController() {
// Always use external rate control parameters if external mode is selected
if (rateControlModeSelect.value === 'external') {
if (!validateQpSettings()) {
rateController = null;
return;
}
const codecType = codecSelect.value.split('-')[0];
const minQp = parseInt(minQpInput.value);
const maxQp = parseInt(maxQpInput.value);
const targetBitrate = parseInt(bitrateSlider.value) * 1000;
const now = performance.now();
const alpha = parseFloat(alphaSlider.value);
const kpBuffer = parseFloat(kpBufferSlider.value);
const targetFullness = parseInt(targetFullnessSlider.value);
maxBufferLevelMs = 600;
targetFullnessPercent = targetFullness;
let frameDropThreshold = -1, reencodeOvershootPercent = -1, reencodeUndershootPercent = -1, maxReencodeCount = -1;
if (enableDropReencodeCheckbox.checked) {
frameDropThreshold = parseInt(frameDropThresholdInput.value);
reencodeOvershootPercent = parseInt(reencodeOvershootPercentInput.value);
reencodeUndershootPercent = parseInt(reencodeUndershootPercentInput.value);
maxReencodeCount = parseInt(maxReencodeCountInput.value);
} else {
// Explicitly set to -1 to disable
frameDropThreshold = -1;
reencodeOvershootPercent = -1;
reencodeUndershootPercent = -1;
maxReencodeCount = -1;
}
if (!rateController || rateController.codecType !== codecType || rateController.minQp !== minQp || rateController.maxQp !== maxQp) {
rateController = new SimpleRateController(codecType, minQp, maxQp, targetBitrate, framerate, now, maxBufferLevelMs, targetFullnessPercent, alpha, kpBuffer, frameDropThreshold, reencodeOvershootPercent, reencodeUndershootPercent, maxReencodeCount);
} else {
rateController.SetRates(targetBitrate, framerate, maxBufferLevelMs, targetFullnessPercent, now, alpha, kpBuffer, frameDropThreshold, reencodeOvershootPercent, reencodeUndershootPercent, maxReencodeCount);
}
} else {
rateController = null;
}
}
/**
* Generates the encode options for the VideoEncoder.encode() call.
* @param {number} frameIndex - The current frame index.
* @param {boolean} keyFrame - Whether to request a key frame.
* @param {number} qp - The Quantization Parameter to use (for external RC).
* @returns {object} The encode options object.
*/
function getEncodeOptions(frameIndex, keyFrame, qp) {
const encodeOptions = { keyFrame: keyFrame };
const codecType = codecSelect.value.split('-')[0];
const encoderConfig = getEncoderConfig();
if (rateControlModeSelect.value === 'external') {
switch (codecType) {
// AV1 and VP9 use the full 0-255 QIndex range in WebCodecs; translate from 0-63.
case 'av1': encodeOptions.av1 = { quantizer: Math.min(255, qp * 4) }; break;
case 'vp9': encodeOptions.vp9 = { quantizer: Math.min(255, qp * 4) }; break;
case 'vp8': encodeOptions.vp8 = { quantizer: qp }; break;
case 'avc': encodeOptions.avc = { quantizer: qp }; break;
case 'hevc': encodeOptions.hevc = { quantizer: qp }; break;
}
if (encoderConfig.scalabilityMode === "manual") {
if (keyFrame) {
encodeOptions.updateBuffer = buffers[0];
encodeOptions.referenceBuffers = [];
} else {
const refIndex = (frameIndex - 1) % 2;
const updateIndex = frameIndex % 2;
encodeOptions.referenceBuffers = [buffers[refIndex]];
encodeOptions.updateBuffer = buffers[updateIndex];
}
}
}
return encodeOptions;
}
/**
* Callback function for the VideoEncoder's output event.
* @param {EncodedVideoChunk} chunk - The encoded video chunk.
* @param {EncodedVideoChunkMetadata} meta - Metadata for the chunk.
* @param {number} instanceId - The encoder instance ID to prevent stale callbacks.
*/
function encoderOutput(chunk, meta, instanceId) {
if (instanceId !== encoderInstanceId) {
// This output is from a previous encoder instance, so ignore it.
// console.log(`encoderOutput: Stale call from instance ${instanceId}, current is ${encoderInstanceId}. Ignoring chunk type ${chunk.type}.`);
return;
}
// console.log(`encoderOutput: Instance ${instanceId}, type: ${chunk.type}`);
if (rateControlModeSelect.value !== 'external' && rateController) {
// This can happen if mode switched back to internal while an external encode was in flight.
// console.warn("encoderOutput called for non-external mode, ignoring.");
if (currentFrame) {
// currentFrame.close(); // This is likely closed by the new encoder's pipeline
// currentFrame = null;
}
return;
}
// Capture decoder description if provided in metadata.
if (meta.decoderConfig && meta.decoderConfig.description) {
lastEncodedDescription = meta.decoderConfig.description;
}
const now = performance.now();
let reEncodeInfo = { reencode: false, qp: -1 };
// If in external mode, notify the rate controller about the encoded frame.
if (rateControlModeSelect.value === 'external' && rateController) {
reEncodeInfo = rateController.OnEncodedFrame(now, chunk.byteLength, currentQpUsed, chunk.type === 'key');
}
// Handle re-encode requests from the rate controller.
if (reEncodeInfo.reencode) {
encodeCount++;
const encodeOptions = getEncodeOptions(inputFrameIndex - 1, false, reEncodeInfo.qp);
currentQpUsed = reEncodeInfo.qp;
// console.log(`[Inst ${instanceId}] Re-encoding frame ${inputFrameIndex - 1}, count: ${encodeCount}`);
encoder.encode(currentFrame, encodeOptions);
} else {
// Frame encoding finished, add to graph data.
frameSizeData.push({ size: chunk.byteLength, timestamp: now });
// Initialize graphData with the first frame
if (frameIdCounter === 0) {
const targetBitrate = parseInt(bitrateSlider.value) * 1000;
const actualBitrate = chunk.byteLength * 8 * framerate; // Estimate for the first frame
graphData.push({ time: now, target: targetBitrate, actual: actualBitrate });
drawGraph();
}
frameIdCounter++;
const isKeyFrame = (chunk.type === 'key');
const dependencies = isKeyFrame ? [] : [lastEncodedFrameId];
const encodedFrame = new EncodedFrame(chunk, frameIdCounter, dependencies);
lastEncodedFrameId = frameIdCounter;
// Feed the encoded chunk to the decoder.
// console.log(`[Inst ${instanceId}] Output chunk type: ${chunk.type}, size: ${chunk.byteLength}`);
if (decoder && decoder.state === 'configured') {
if (decoderNeedsKeyFrame) {
if (encodedFrame.encodedChunk.type === 'key') {
// console.log(`[Inst ${instanceId}] Decoding keyframe ${frameIdCounter}`);
decoder.decode(encodedFrame.encodedChunk);
decoderNeedsKeyFrame = false;
} else {
// console.log(`[Inst ${instanceId}] Skipping non-keyframe ${frameIdCounter}, keyframe needed.`);
}
} else {
// console.log(`[Inst ${instanceId}] Decoding frame ${frameIdCounter}`);
decoder.decode(encodedFrame.encodedChunk);
}
} else {
// console.warn(`[Inst ${instanceId}] Decoder not ready, state: ${decoder ? decoder.state : 'null'}`);
}
// Clean up the frame reference and reset flags for the next processFrame call.
if (currentFrame) {
currentFrame.close();
currentFrame = null;
}
encodeCount = 0;
isProcessingFrame = false;
if (!stopButton.disabled) requestAnimationFrame(processFrame);
}
}
/**
* Callback function for VideoEncoder errors.
* @param {Error} e - The error object.
*/
function encoderError(e) {
console.error('Encoder Error:', e);
if (currentFrame) {
currentFrame.close();
currentFrame = null;
}
encodeCount = 0;
isProcessingFrame = false;
if (!stopButton.disabled) requestAnimationFrame(processFrame);
}
/**
* Reads a frame from the camera, prepares encode options, and calls encoder.encode().
* This function is called repeatedly via requestAnimationFrame.
*/
function processFrame() {
if (!frameReader || isProcessingFrame || stopButton.disabled) return;
isProcessingFrame = true;
frameReader.read().then(({ done, value }) => {
if (done || stopButton.disabled) {
if(value) value.close();
isProcessingFrame = false;
return;
}
currentFrame = value;
if (encoder && encoder.state === 'configured') {
let nextQp = -1;
// Determine QP if using external rate control.
if (rateController) {
nextQp = rateController.GetNextQp(performance.now(), inputFrameIndex === 0 || needsKeyFrame);
if (nextQp === -1) {
// Frame drop scenario.
console.log("Frame dropped by rate controller");
currentFrame.close();
currentFrame = null;
isProcessingFrame = false;
if (!stopButton.disabled) requestAnimationFrame(processFrame);
return;
}
} else {
// Internal rate control, no QP to set in options.
}
currentQpUsed = nextQp;
const keyFrame = inputFrameIndex === 0 || needsKeyFrame;
const encodeOptions = getEncodeOptions(inputFrameIndex, keyFrame, nextQp);
try {
// Encode the frame.
encoder.encode(currentFrame, encodeOptions);
// currentFrame is closed in the encoderOutput/encoderError callback.
} catch (e) {
console.error('Error during encode:', e);
if (currentFrame) {
currentFrame.close();
currentFrame = null;
}
isProcessingFrame = false;
if (!stopButton.disabled) requestAnimationFrame(processFrame);
}
if (keyFrame) needsKeyFrame = false;
inputFrameIndex++;
} else {
// Encoder not ready, close frame and try again.
if (currentFrame) currentFrame.close();
currentFrame = null;
isProcessingFrame = false;
if (!stopButton.disabled) requestAnimationFrame(processFrame);
}
}).catch(e => {
isProcessingFrame = false;
console.error("Error reading frame:", e);
if (currentFrame) {
currentFrame.close();
currentFrame = null;
}
if (!stopButton.disabled) requestAnimationFrame(processFrame);
});
}
/**
* Initializes and starts the encoding process.
* Sets up the encoder, decoder, and graph updates.
*/
async function startEncoding() {
if (!mediaStream) return;
updateRateController();
const track = mediaStream.getVideoTracks()[0];
const processor = new MediaStreamTrackProcessor({ track: track });
frameSource = processor.readable;
frameReader = frameSource.getReader();
const encoderConfig = getEncoderConfig();
lastConfiguredCodec = encoderConfig.codec;
encoderInstanceId++;
const currentInstanceId = encoderInstanceId;
// console.log(`startEncoding: Creating encoder instance ${currentInstanceId}`);
encoder = new VideoEncoder({
output: (chunk, meta) => encoderOutput(chunk, meta, currentInstanceId),
error: encoderError
});
await encoder.configure(encoderConfig);
// console.log(`startEncoding: Encoder instance ${currentInstanceId} configured`);
buffers = encoderConfig.scalabilityMode === "manual" ? await encoder.getAllFrameBuffers() : [];
decoder = new VideoDecoder({
output: (frame) => {
// console.log(`Decoder output: ts ${frame.timestamp}`);
decodedCtx.drawImage(frame, 0, 0, VIDEO_WIDTH, VIDEO_HEIGHT);
frame.close();
},
error: (e) => {
console.error('Decoder Error:', e);
}
});
const decoderConfig = getDecoderConfig(encoderConfig, lastEncodedDescription);
await decoder.configure(decoderConfig);
decoderNeedsKeyFrame = true;
// console.log(`startEncoding: Decoder configured, needsKeyFrame: ${decoderNeedsKeyFrame}`);
frameSizeData = [];
graphData = [];
if (graphIntervalId) clearInterval(graphIntervalId);
// Set up an interval to update the bitrate graph periodically.
graphIntervalId = setInterval(() => {
const now = performance.now();
const windowStart = now - graphWindowMs;
// Remove old data points outside the rolling window.
frameSizeData = frameSizeData.filter(d => d.timestamp >= windowStart);
let totalBytes = 0;
let actualBitrate = 0;
if (frameSizeData.length > 0) {
frameSizeData.forEach(d => totalBytes += d.size);
const firstTime = frameSizeData[0].timestamp;
const lastTime = frameSizeData[frameSizeData.length - 1].timestamp;
let windowDurationMs = 0;
// Calculate the duration of the current window.
if (frameSizeData.length > 1) {
const avgInterval = (lastTime - firstTime) / (frameSizeData.length - 1);
windowDurationMs = (lastTime - firstTime) + avgInterval;
} else {
// Single frame in window, estimate duration based on target framerate.
windowDurationMs = 1000 / framerate;
}
if (windowDurationMs > 0) {
actualBitrate = (totalBytes * 8) / (windowDurationMs / 1000); // bps
} else {
actualBitrate = totalBytes * 8 * framerate; // Fallback estimate
}
} else {
actualBitrate = 0;
}
const targetBitrate = parseInt(bitrateSlider.value) * 1000;
// Add new data point to the graph and remove the oldest if full.
graphData.push({ time: now, target: targetBitrate, actual: actualBitrate });
if (graphData.length > maxGraphPoints) {
graphData.shift();
}
drawGraph();
}, graphUpdateInterval);
inputFrameIndex = 0;
encodeCount = 0;
currentFrame = null;
isProcessingFrame = false;
if (!stopButton.disabled) requestAnimationFrame(processFrame);
}
/**
* Stops the encoding process and cleans up resources.
*/
function stopEncoding() {
if (frameReader) {
try {
frameReader.cancel(); // Attempt to cancel the reader to stop the processFrame loop.
} catch (e) { console.warn("Error cancelling reader:", e); }
try {
if (frameReader) frameReader.releaseLock(); // Release the lock on the stream.
} catch (e) { console.warn("Error releasing reader lock:", e); }
frameReader = null;
}
if (frameSource) {
frameSource = null;
}
// Close encoder and decoder if they are active.
if (encoder && encoder.state !== 'closed') {
encoder.close();
encoder = null;
}
if (decoder && decoder.state !== 'closed') {
decoder.close();
decoder = null;
}
decodedCtx.clearRect(0, 0, decodedCanvas.width, decodedCanvas.height);
// Clear the graph update interval.
if (graphIntervalId) {
clearInterval(graphIntervalId);
graphIntervalId = null;
}
rateController = null;
buffers = [];
}
/**
* Reconfigures the encoder, typically called when codec or bitrate changes.
*/
async function reconfigureRtc() {
if (!encoder || encoder.state !== 'configured') {
console.log("reconfigureRtc: Exiting, encoder not valid or not configured", encoder);
return;
}
updateRateController();
const encoderConfig = getEncoderConfig();
try {
await encoder.configure(encoderConfig);
} catch (e) {
console.error("Error reconfiguring encoder:", e);
throw e; // Re-throw the error to be caught by the listener
}
}
rateControlModeSelect.addEventListener('change', async () => {
const mode = rateControlModeSelect.value;
// console.log(`Switching to ${mode} mode`);
// Disable stop button during transition to prevent race conditions.
stopButton.disabled = true;
if (frameReader) {
// console.log("Cancelling frame reader");
try {
// Cancel and release the existing reader before changing modes.
await frameReader.cancel();
frameReader.releaseLock();
} catch (e) { console.warn("Error cancelling/releasing reader:", e); }
frameReader = null;
}
// Short delay to ensure resources are released.
await new Promise(resolve => setTimeout(resolve, 100));
try {
if (mode === 'external') {
// Show external RC settings and update codec list for 'quantizer' mode.