-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1104 lines (987 loc) · 49.4 KB
/
index.html
File metadata and controls
1104 lines (987 loc) · 49.4 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>Shinra Proxy HLS Test with ArtPlayer</title>
<!-- Bootstrap for styling -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
<!-- HLS.js for HLS playback -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/hls.js/1.4.14/hls.min.js"></script>
<!-- ArtPlayer.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/artplayer/5.0.9/artplayer.min.js"></script>
<style>
.debug-container {
max-height: 300px;
overflow-y: auto;
font-family: monospace;
font-size: 12px;
}
.segment-log {
max-height: 150px;
overflow-y: auto;
}
.buffer-visualization {
width: 100%;
height: 20px;
background-color: #ddd;
border-radius: 3px;
overflow: hidden;
margin-top: 5px;
}
.buffer-filled {
height: 100%;
background-color: #007bff;
transition: width 0.2s ease;
}
.debug-section {
border: 1px solid #dee2e6;
border-radius: 0.25rem;
margin-bottom: 1rem;
}
.debug-section-header {
padding: 0.5rem 1rem;
background-color: #f8f9fa;
border-bottom: 1px solid #dee2e6;
font-weight: bold;
}
.debug-section-body {
padding: 1rem;
}
.log-entry {
margin-bottom: 0.25rem;
}
.log-entry.error {
color: #dc3545;
}
.log-entry.warning {
color: #ffc107;
}
.log-entry.info {
color: #17a2b8;
}
.log-time {
color: #6c757d;
}
#quality-table .active-quality {
background-color: #e2f3ff;
}
.art-container {
aspect-ratio: 16/9;
max-height: 600px;
}
.art-video-player {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<!-- Navigation Bar -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="#">
<span>Shinra Proxy HLS Test with ArtPlayer</span>
</a>
</div>
</nav>
<div class="container mt-4">
<!-- Input Form -->
<div class="card mb-4">
<div class="card-header">
<h4>Proxy Configuration</h4>
</div>
<div class="card-body">
<form id="hls-form" class="row g-3">
<div class="col-md-6">
<label for="proxy-base-url" class="form-label">Proxy Base URL</label>
<input type="text" class="form-control" id="proxy-base-url" value="http://localhost:3000/proxy">
</div>
<div class="col-md-6">
<label for="media-url" class="form-label">HLS Stream URL (Original)</label>
<input type="text" class="form-control" id="media-url" placeholder="Enter HLS .m3u8 URL">
</div>
<div class="col-12">
<div class="form-text mb-2">Sample URLs:</div>
<div class="btn-group mb-3" role="group">
<button type="button" class="btn btn-outline-secondary btn-sm" onclick="setExampleUrl('https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8')">Sintel (HLS)</button>
<button type="button" class="btn btn-outline-secondary btn-sm" onclick="setExampleUrl('https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8')">Mux Test HLS</button>
<button type="button" class="btn btn-outline-secondary btn-sm" onclick="setExampleUrl('https://d2zihajmogu5jn.cloudfront.net/bipbop-advanced/bipbop_16x9_variant.m3u8')">BIPBOP Advanced</button>
</div>
</div>
<div class="col-md-6">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="direct-mode" onchange="updateProxySetting()">
<label class="form-check-label" for="direct-mode">
Direct Mode (Don't use proxy)
</label>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Load Stream</button>
<button type="button" class="btn btn-danger" onclick="stopStream()">Stop Stream</button>
</div>
<div class="col-12">
<div class="alert alert-info mb-0">
<strong>Proxied URL:</strong> <span id="proxied-url">None</span>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<!-- Video Player -->
<div class="col-lg-8">
<div class="card mb-4">
<div class="card-header d-flex justify-content-between align-items-center">
<h4>HLS Player</h4>
<div class="btn-group" role="group">
<button type="button" class="btn btn-sm btn-outline-primary" onclick="togglePlayerSize()">Resize Player</button>
</div>
</div>
<div class="card-body p-0">
<div class="art-container">
<div id="art-player-container" class="art-video-player"></div>
</div>
</div>
</div>
</div>
<!-- Stream Info -->
<div class="col-lg-4">
<div class="card mb-4">
<div class="card-header">
<h4>Stream Information</h4>
</div>
<div class="card-body">
<div id="stream-info">
<p><strong>Status:</strong> <span id="stream-status">Not loaded</span></p>
<p><strong>Type:</strong> <span id="stream-type">-</span></p>
<p><strong>Duration:</strong> <span id="stream-duration">-</span></p>
<p><strong>Current Time:</strong> <span id="stream-current-time">-</span></p>
<p><strong>Resolution:</strong> <span id="stream-resolution">-</span></p>
<p><strong>Video Codec:</strong> <span id="video-codec">-</span></p>
<p><strong>Audio Codec:</strong> <span id="audio-codec">-</span></p>
<div>
<strong>Subtitles:</strong>
<select id="subtitle-tracks" class="form-select form-select-sm mt-1">
<option value="">None</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Debug Information -->
<div class="row">
<!-- Quality Levels -->
<div class="col-lg-6">
<div class="debug-section">
<div class="debug-section-header">
Quality Levels
</div>
<div class="debug-section-body">
<table id="quality-table" class="table table-sm">
<thead>
<tr>
<th>Index</th>
<th>Resolution</th>
<th>Bitrate</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4">No quality levels available</td>
</tr>
</tbody>
</table>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="auto-quality" checked>
<label class="form-check-label" for="auto-quality">
Auto Quality
</label>
</div>
</div>
</div>
</div>
<!-- Buffer Information -->
<div class="col-lg-6">
<div class="debug-section">
<div class="debug-section-header">
Buffer Information
</div>
<div class="debug-section-body">
<div>
<strong>Buffer Length:</strong> <span id="buffer-length">0s</span>
</div>
<div>
<strong>Buffer Size:</strong> <span id="buffer-size">0 KB</span>
</div>
<div>
<strong>Buffer Health:</strong>
<div class="buffer-visualization">
<div id="buffer-filled" class="buffer-filled" style="width: 0%"></div>
</div>
</div>
<div class="mt-3">
<strong>Buffer Target:</strong>
<input type="range" class="form-range" min="1" max="60" value="30" id="buffer-target">
<div class="d-flex justify-content-between">
<span>1s</span>
<span id="buffer-target-value">30s</span>
<span>60s</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-3">
<!-- Network Activity -->
<div class="col-lg-6">
<div class="debug-section">
<div class="debug-section-header">
Network Activity
</div>
<div class="debug-section-body">
<div>
<strong>Bandwidth:</strong> <span id="bandwidth">0 Kbps</span>
</div>
<div>
<strong>Total Downloaded:</strong> <span id="total-downloaded">0 KB</span>
</div>
<div>
<strong>Current Download Speed:</strong> <span id="download-speed">0 Kbps</span>
</div>
<div>
<strong>Latency:</strong> <span id="latency">0 ms</span>
</div>
<div class="mt-3">
<strong>Network Throttling:</strong>
<select id="network-throttle" class="form-select">
<option value="none">None</option>
<option value="fast3g">Fast 3G</option>
<option value="slow3g">Slow 3G</option>
<option value="custom">Custom</option>
</select>
</div>
<div id="custom-throttle" class="mt-2" style="display: none;">
<label for="throttle-speed" class="form-label">Download Speed (Kbps)</label>
<input type="number" class="form-control form-control-sm" id="throttle-speed" value="1000">
<button class="btn btn-sm btn-primary mt-2" onclick="applyCustomThrottle()">Apply</button>
</div>
</div>
</div>
</div>
<!-- Segment Log -->
<div class="col-lg-6">
<div class="debug-section">
<div class="debug-section-header">
Segment Log
</div>
<div class="debug-section-body">
<div class="segment-log" id="segment-log">
<div class="log-entry info">
<span class="log-time">[00:00:00]</span> Waiting for playback to start...
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Error Log -->
<div class="row mt-3 mb-5">
<div class="col-12">
<div class="debug-section">
<div class="debug-section-header">
Debug Log
</div>
<div class="debug-section-body">
<div class="debug-container" id="debug-log">
<div class="log-entry info">
<span class="log-time">[00:00:00]</span> Debug log initialized
</div>
</div>
<div class="mt-2">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="log-errors" checked>
<label class="form-check-label" for="log-errors">Errors</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="log-warnings" checked>
<label class="form-check-label" for="log-warnings">Warnings</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="log-info" checked>
<label class="form-check-label" for="log-info">Info</label>
</div>
<button class="btn btn-sm btn-outline-secondary float-end" onclick="clearLogs()">Clear Logs</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
// Global variables
let art = null;
let hls = null;
let stats = {
totalBytesLoaded: 0,
lastDownloadTime: 0,
currentDownloadBytes: 0,
downloadStartTime: 0,
bufferTarget: 30,
throttleSettings: {
enabled: false,
downloadSpeed: 0
}
};
// Document Ready
document.addEventListener('DOMContentLoaded', function() {
// Initialize buffer target slider
const bufferTargetSlider = document.getElementById('buffer-target');
const bufferTargetValue = document.getElementById('buffer-target-value');
bufferTargetSlider.addEventListener('input', function() {
stats.bufferTarget = parseInt(this.value);
bufferTargetValue.textContent = `${stats.bufferTarget}s`;
if (hls) {
hls.config.maxBufferLength = stats.bufferTarget;
hls.config.maxMaxBufferLength = stats.bufferTarget;
addLog('info', `Buffer target changed to ${stats.bufferTarget}s`);
}
});
// Network throttle dropdown
const networkThrottle = document.getElementById('network-throttle');
const customThrottle = document.getElementById('custom-throttle');
networkThrottle.addEventListener('change', function() {
if (this.value === 'custom') {
customThrottle.style.display = 'block';
} else {
customThrottle.style.display = 'none';
// Apply preset throttling
let throttleSpeed = 0;
switch(this.value) {
case 'fast3g':
throttleSpeed = 1500; // 1.5 Mbps
break;
case 'slow3g':
throttleSpeed = 500; // 500 Kbps
break;
case 'none':
default:
throttleSpeed = 0; // No throttling
break;
}
stats.throttleSettings.enabled = throttleSpeed > 0;
stats.throttleSettings.downloadSpeed = throttleSpeed;
if (stats.throttleSettings.enabled) {
addLog('info', `Network throttling set to ${throttleSpeed} Kbps`);
} else {
addLog('info', 'Network throttling disabled');
}
}
});
// Handle form submission
document.getElementById('hls-form').addEventListener('submit', function(e) {
e.preventDefault();
loadStream();
});
// Auto-quality checkbox
document.getElementById('auto-quality').addEventListener('change', function() {
if (hls) {
if (this.checked) {
hls.currentLevel = -1; // Auto quality
addLog('info', 'Switched to automatic quality selection');
} else {
// Keep current level when disabling auto
addLog('info', 'Disabled automatic quality selection');
}
}
});
addLog('info', 'Page initialized and ready');
});
// Create and initialize ArtPlayer
function initializeArtPlayer(url) {
// Clear previous instance if it exists
if (art) {
art.destroy();
art = null;
}
// Check if HLS.js is supported
if (!Hls.isSupported()) {
addLog('error', 'HLS.js is not supported in this browser');
return;
}
// Create new ArtPlayer instance
art = new Artplayer({
container: '#art-player-container',
url: url,
volume: 0.5,
isLive: false,
muted: false,
autoplay: true,
pip: true,
autoSize: true,
autoMini: true,
screenshot: true,
setting: true,
playbackRate: true,
fullscreen: true,
fullscreenWeb: true,
subtitleOffset: true,
miniProgressBar: true,
mutex: true,
backdrop: true,
playsInline: true,
autoPlayback: true,
airplay: true,
theme: '#007bff',
lang: navigator.language.toLowerCase(),
whitelist: ['*'],
moreVideoAttr: {
crossOrigin: 'anonymous',
},
customType: {
m3u8: function(video, url) {
// Create a new HLS instance with custom config
hls = new Hls({
debug: false,
maxBufferLength: stats.bufferTarget,
maxMaxBufferLength: stats.bufferTarget,
xhrSetup: function(xhr, url) {
// For tracking download stats
const startTime = Date.now();
xhr.addEventListener('loadend', function() {
// Calculate download time
const endTime = Date.now();
const responseSize = xhr.responseText ? xhr.responseText.length : 0;
if (responseSize > 0) {
// Update stats
stats.totalBytesLoaded += responseSize;
stats.currentDownloadBytes = responseSize;
stats.lastDownloadTime = endTime;
// Calculate latency
const latency = endTime - startTime;
document.getElementById('latency').textContent = `${latency} ms`;
// For throttling network requests
if (stats.throttleSettings.enabled) {
const throttleKbps = stats.throttleSettings.downloadSpeed;
const delayMs = Math.floor((responseSize * 8) / throttleKbps);
// Log the throttling
addLog('info', `Throttling: Delaying ${responseSize} bytes by ${delayMs}ms at ${throttleKbps} Kbps`);
}
}
});
}
});
// Log all HLS.js events
Object.keys(Hls.Events).forEach(function(key) {
const eventName = Hls.Events[key];
hls.on(eventName, function(event, data) {
handleHlsEvent(eventName, data);
});
});
// Handle fatal errors
hls.on(Hls.Events.ERROR, function(event, data) {
if (data.fatal) {
switch(data.type) {
case Hls.ErrorTypes.NETWORK_ERROR:
addLog('error', `Fatal network error: ${data.details}`);
hls.startLoad();
break;
case Hls.ErrorTypes.MEDIA_ERROR:
addLog('error', `Fatal media error: ${data.details}`);
hls.recoverMediaError();
break;
default:
addLog('error', `Fatal error: ${data.details}`);
if (art) {
art.notice.show('Fatal playback error: ' + data.details);
}
break;
}
} else {
addLog('warning', `Non-fatal error: ${data.details}`);
}
});
// Attach media and load source
hls.attachMedia(video);
hls.loadSource(url);
// Log when manifest is parsed
hls.on(Hls.Events.MANIFEST_PARSED, function() {
updateQualityLevels();
video.play().catch(e => {
addLog('warning', `Autoplay prevented: ${e.message}`);
});
document.getElementById('stream-status').textContent = 'Playing';
document.getElementById('stream-type').textContent = 'HLS';
});
}
},
subtitle: {
url: '', // Will be populated if subtitles are available
style: {
color: '#ffffff',
fontSize: '20px',
textShadow: '0 0 5px black',
},
},
icons: {
loading: '<svg viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round"><animate attributeName="stroke-dashoffset" dur="2s" repeatCount="indefinite" from="0" to="502"></animate><animate attributeName="stroke-dasharray" dur="2s" repeatCount="indefinite" values="150.6 100.4;1 250;150.6 100.4"></animate></circle></svg>',
},
controls: [
{
position: 'right',
html: 'Debug Info',
click: function() {
const debugInfo = {
hls: hls ? {
version: Hls.version,
levels: hls.levels,
currentLevel: hls.currentLevel,
bandwidthEstimate: hls.bandwidthEstimate
} : 'Not initialized',
art: {
version: art.version,
playing: art.playing,
currentTime: art.currentTime,
duration: art.duration
},
stats: stats
};
console.log('Debug Info:', debugInfo);
addLog('info', 'Debug info logged to console');
art.notice.show('Debug info logged to console');
}
}
]
});
// Add event listeners for ArtPlayer
art.on('video:loadedmetadata', () => {
document.getElementById('stream-duration').textContent = `${art.duration.toFixed(2)}s`;
// Update video info if we can get it
try {
const video = art.template.$video;
if (video) {
const videoWidth = video.videoWidth || 0;
const videoHeight = video.videoHeight || 0;
if (videoWidth && videoHeight) {
document.getElementById('stream-resolution').textContent = `${videoWidth}x${videoHeight}`;
}
}
} catch (e) {
console.error('Error getting video dimensions:', e);
}
});
art.on('video:timeupdate', () => {
document.getElementById('stream-current-time').textContent = `${art.currentTime.toFixed(2)}s`;
updateBufferInfo();
});
art.on('video:ended', () => {
document.getElementById('stream-status').textContent = 'Ended';
});
art.on('video:error', (error) => {
addLog('error', `Video error: ${error.message || 'Unknown error'}`);
document.getElementById('stream-status').textContent = 'Error';
});
// Start stats update interval
startStatsInterval();
addLog('info', 'ArtPlayer initialized');
}
// Update buffer information
function updateBufferInfo() {
const video = art?.template?.$video;
if (!video) return;
if (video.buffered && video.buffered.length > 0) {
const currentTime = video.currentTime;
let bufferLength = 0;
// Find the appropriate buffer range
for (let i = 0; i < video.buffered.length; i++) {
const start = video.buffered.start(i);
const end = video.buffered.end(i);
if (currentTime >= start && currentTime <= end) {
bufferLength = end - currentTime;
break;
}
}
// Update buffer display
document.getElementById('buffer-length').textContent = `${bufferLength.toFixed(2)}s`;
// Calculate buffer health as percentage of target
const bufferPercentage = Math.min(100, (bufferLength / stats.bufferTarget) * 100);
document.getElementById('buffer-filled').style.width = `${bufferPercentage}%`;
}
}
// Apply custom throttle settings
function applyCustomThrottle() {
const throttleSpeed = parseInt(document.getElementById('throttle-speed').value);
if (isNaN(throttleSpeed) || throttleSpeed < 0) {
addLog('error', 'Invalid throttle speed');
return;
}
stats.throttleSettings.enabled = throttleSpeed > 0;
stats.throttleSettings.downloadSpeed = throttleSpeed;
if (stats.throttleSettings.enabled) {
addLog('info', `Custom network throttling set to ${throttleSpeed} Kbps`);
} else {
addLog('info', 'Network throttling disabled');
}
}
// Set example URL
function setExampleUrl(url) {
document.getElementById('media-url').value = url;
}
// Toggle direct mode (without proxy)
function updateProxySetting() {
const directMode = document.getElementById('direct-mode').checked;
const proxyBaseUrlInput = document.getElementById('proxy-base-url');
if (directMode) {
proxyBaseUrlInput.disabled = true;
addLog('info', 'Direct mode enabled - proxy will be bypassed');
} else {
proxyBaseUrlInput.disabled = false;
addLog('info', 'Direct mode disabled - proxy will be used');
}
}
// Toggle player size
function togglePlayerSize() {
const container = document.querySelector('.art-container');
if (container.style.maxHeight === '600px') {
container.style.maxHeight = '400px';
} else {
container.style.maxHeight = '600px';
}
}
// Load the stream
function loadStream() {
const mediaUrl = document.getElementById('media-url').value.trim();
const proxyBaseUrl = document.getElementById('proxy-base-url').value.trim();
const directMode = document.getElementById('direct-mode').checked;
if (!mediaUrl) {
addLog('error', 'No media URL provided');
return;
}
// Stop existing stream if any
stopStream();
// Construct the final URL (direct or proxied)
let finalUrl;
if (directMode) {
finalUrl = mediaUrl;
document.getElementById('proxied-url').textContent = 'Not using proxy (direct mode)';
addLog('info', 'Loading stream directly (no proxy)');
} else {
if (!proxyBaseUrl) {
addLog('error', 'No proxy base URL provided');
return;
}
// Construct the proxied URL
finalUrl = `${proxyBaseUrl}?url=${encodeURIComponent(mediaUrl)}`;
document.getElementById('proxied-url').textContent = finalUrl;
addLog('info', 'Loading stream through proxy');
}
// Initialize the player with the URL
initializeArtPlayer(finalUrl);
addLog('info', 'Stream loading started');
}
// Stop the stream
function stopStream() {
document.getElementById('stream-status').textContent = 'Stopped';
if (hls !== null) {
hls.destroy();
hls = null;
addLog('info', 'HLS.js instance destroyed');
}
if (art !== null) {
art.destroy();
art = null;
addLog('info', 'ArtPlayer instance destroyed');
}
// Reset quality table
document.getElementById('quality-table').querySelector('tbody').innerHTML =
'<tr><td colspan="4">No quality levels available</td></tr>';
// Reset stream info
document.getElementById('stream-duration').textContent = '-';
document.getElementById('stream-current-time').textContent = '-';
document.getElementById('stream-resolution').textContent = '-';
document.getElementById('video-codec').textContent = '-';
document.getElementById('audio-codec').textContent = '-';
// Clear subtitle tracks
const subtitleSelect = document.getElementById('subtitle-tracks');
subtitleSelect.innerHTML = '<option value="">None</option>';
// Reset buffer visualization
document.getElementById('buffer-filled').style.width = '0%';
document.getElementById('buffer-length').textContent = '0s';
document.getElementById('buffer-size').textContent = '0 KB';
// Reset network stats
document.getElementById('bandwidth').textContent = '0 Kbps';
document.getElementById('total-downloaded').textContent = '0 KB';
document.getElementById('download-speed').textContent = '0 Kbps';
document.getElementById('latency').textContent = '0 ms';
// Reset stats
stats.totalBytesLoaded = 0;
stats.lastDownloadTime = 0;
stats.currentDownloadBytes = 0;
}
// Handle HLS.js events
function handleHlsEvent(eventName, data) {
switch(eventName) {
case Hls.Events.MANIFEST_LOADED:
addLog('info', `Manifest loaded: ${data.levels.length} quality levels`);
// Update subtitle tracks if available
if (data.subtitles && data.subtitles.length > 0) {
const subtitleSelect = document.getElementById('subtitle-tracks');
subtitleSelect.innerHTML = '<option value="">None</option>';
data.subtitles.forEach((subtitle, index) => {
const option = document.createElement('option');
option.value = index;
option.textContent = subtitle.name || `Track ${index + 1} (${subtitle.lang || 'unknown'})`;
subtitleSelect.appendChild(option);
});
// Handle subtitle selection
subtitleSelect.addEventListener('change', function() {
if (hls) {
const trackId = this.value === '' ? -1 : parseInt(this.value);
hls.subtitleTrack = trackId;
// Try to set subtitle in ArtPlayer
if (art && trackId >= 0 && data.subtitles[trackId]) {
const subtitle = data.subtitles[trackId];
if (subtitle.url) {
art.subtitle.switch(subtitle.url);
}
} else if (art && trackId === -1) {
art.subtitle.switch('');
}
addLog('info', trackId === -1 ? 'Subtitles disabled' : `Subtitle track ${trackId} selected`);
}
});
addLog('info', `${data.subtitles.length} subtitle tracks available`);
} else {
addLog('info', 'No subtitle tracks available');
}
break;
case Hls.Events.LEVEL_LOADED:
if (art) {
document.getElementById('stream-duration').textContent =
`${art.duration.toFixed(2)}s`;
}
break;
case Hls.Events.LEVEL_SWITCHING:
const newLevel = data.level;
updateActiveQualityLevel(newLevel);
if (hls && hls.levels && hls.levels[newLevel]) {
const level = hls.levels[newLevel];
const resolution = level.width && level.height ?
`${level.width}x${level.height}` : 'Unknown';
const bitrate = level.bitrate ?
`${Math.round(level.bitrate / 1000)} Kbps` : 'Unknown';
document.getElementById('stream-resolution').textContent = resolution;
addLog('info', `Switching to quality level ${newLevel}: ${resolution} @ ${bitrate}`);
}
break;
case Hls.Events.FRAG_LOADED:
// Track downloaded bytes
if (data.frag && data.stats) {
stats.totalBytesLoaded += data.stats.total || 0;
stats.currentDownloadBytes = data.stats.total || 0;
stats.lastDownloadTime = Date.now();
// Add to segment log
const fragType = data.frag.type === 'main' ? 'Video' :
(data.frag.type === 'audio' ? 'Audio' : data.frag.type);
const fragLevel = data.frag.level;
const fragDuration = data.frag.duration ? data.frag.duration.toFixed(2) : '?';
const fragSize = formatBytes(data.stats.total);
const fragUrl = data.frag.url.split('?')[0].split('/').pop();
const segmentLogEntry = document.createElement('div');
segmentLogEntry.className = 'log-entry info';
segmentLogEntry.innerHTML = `
<span class="log-time">[${formatTime(art ? art.currentTime : 0)}]</span>
${fragType} segment loaded (Level ${fragLevel}, ${fragDuration}s, ${fragSize}): ${fragUrl}
`;
const segmentLog = document.getElementById('segment-log');
segmentLog.appendChild(segmentLogEntry);
segmentLog.scrollTop = segmentLog.scrollHeight;
// Keep only the last 50 entries
while (segmentLog.children.length > 50) {
segmentLog.removeChild(segmentLog.firstChild);
}
}
break;
case Hls.Events.MEDIA_ATTACHED:
addLog('info', 'Media attached to HLS.js');
break;
case Hls.Events.BUFFER_CREATED:
if (data.tracks) {
// Extract codec information
for (const trackType in data.tracks) {
const track = data.tracks[trackType];
if (track.codec) {
if (trackType === 'video') {
document.getElementById('video-codec').textContent = track.codec;
} else if (trackType === 'audio') {
document.getElementById('audio-codec').textContent = track.codec;
}
}
}
}
break;
case Hls.Events.ERROR:
// Errors are handled in the main error handler
break;
default:
// For debugging, uncomment this to see all events
// console.log(`HLS.js event: ${eventName}`, data);
break;
}
}
// Update quality levels table
function updateQualityLevels() {
if (!hls || !hls.levels || hls.levels.length === 0) {
return;
}
const tbody = document.getElementById('quality-table').querySelector('tbody');
tbody.innerHTML = '';
hls.levels.forEach((level, index) => {
const row = document.createElement('tr');
row.id = `quality-level-${index}`;
const resolution = level.width && level.height ?
`${level.width}x${level.height}` : 'Audio only';
const bitrate = level.bitrate ?
`${Math.round(level.bitrate / 1000)} Kbps` : 'Unknown';
row.innerHTML = `
<td>${index}</td>
<td>${resolution}</td>
<td>${bitrate}</td>
<td>
<button class="btn btn-sm btn-outline-primary" onclick="selectQualityLevel(${index})">Select</button>
</td>
`;
tbody.appendChild(row);
});
// Add auto quality option
const autoRow = document.createElement('tr');
autoRow.id = 'quality-level-auto';
autoRow.innerHTML = `
<td>Auto</td>
<td colspan="2">Automatic quality selection</td>
<td>
<button class="btn btn-sm btn-outline-primary" onclick="selectQualityLevel(-1)">Select</button>
</td>
`;
tbody.appendChild(autoRow);
// Mark current level as active
updateActiveQualityLevel(hls.currentLevel);
}
// Mark the active quality level in the table
function updateActiveQualityLevel(level) {
// Remove active class from all rows
const rows = document.getElementById('quality-table').querySelectorAll('tbody tr');
rows.forEach(row => row.classList.remove('active-quality'));
// Add active class to current level
if (level === -1) {
document.getElementById('quality-level-auto')?.classList.add('active-quality');
} else {
document.getElementById(`quality-level-${level}`)?.classList.add('active-quality');
}
}
// Manually select a quality level
function selectQualityLevel(level) {
if (hls) {
hls.currentLevel = level;
document.getElementById('auto-quality').checked = (level === -1);
updateActiveQualityLevel(level);
if (level === -1) {
addLog('info', 'Switched to automatic quality selection');
} else {
const qualityInfo = hls.levels[level];
const resolution = qualityInfo.width && qualityInfo.height ?
`${qualityInfo.width}x${qualityInfo.height}` : 'Audio only';
const bitrate = qualityInfo.bitrate ?
`${Math.round(qualityInfo.bitrate / 1000)} Kbps` : 'Unknown';
addLog('info', `Manually selected quality level ${level}: ${resolution} @ ${bitrate}`);