forked from video-dev/hls.js
-
Notifications
You must be signed in to change notification settings - Fork 90
/
hls-demo.js
1528 lines (1357 loc) · 47.8 KB
/
hls-demo.js
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
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["HlsDemo"] = factory();
else
root["HlsDemo"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__demo_utils__ = __webpack_require__(1);
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var testStreams = __webpack_require__(2);
var defaultTestStreamUrl = testStreams['bbb'].url;
var sourceURL = decodeURIComponent(getURLParam('src', defaultTestStreamUrl));
var demoConfig = getURLParam('demoConfig', null);
if (demoConfig) {
demoConfig = JSON.parse(atob(demoConfig));
} else {
demoConfig = {};
}
var enableStreaming = getDemoConfigPropOrDefault('enableStreaming', true);
var autoRecoverError = getDemoConfigPropOrDefault('autoRecoverError', true);
var enableWorker = getDemoConfigPropOrDefault('enableWorker', true);
var levelCapping = getDemoConfigPropOrDefault('levelCapping', -1);
var limitMetrics = getDemoConfigPropOrDefault('limitMetrics', -1);
var defaultAudioCodec = getDemoConfigPropOrDefault('defaultAudioCodec', undefined);
var widevineLicenseUrl = getDemoConfigPropOrDefault('widevineLicenseURL', undefined);
var dumpfMP4 = getDemoConfigPropOrDefault('dumpfMP4', false);
var bufferingIdx = -1;
var selectedTestStream = null;
var video = $('#video')[0];
var startTime = Date.now();
var lastSeekingIdx = void 0;
var lastStartPosition = void 0;
var lastDuration = void 0;
var lastAudioTrackSwitchingIdx = void 0;
var hls = void 0;
var url = void 0;
var events = void 0;
var stats = void 0;
var tracks = void 0;
var fmp4Data = void 0;
$(document).ready(function () {
Object.keys(testStreams).forEach(function (key) {
var stream = testStreams[key];
var option = new Option(stream.description, key);
$('#streamSelect').append(option);
});
$('#streamSelect').change(function () {
selectedTestStream = testStreams[$('#streamSelect').val()];
var streamUrl = selectedTestStream.url;
$('#streamURL').val(streamUrl);
loadSelectedStream();
});
$('#streamURL').change(function () {
selectedTestStream = null;
loadSelectedStream();
});
$('#videoSize').change(function () {
$('#video').width($('#videoSize').val());
$('#bufferedCanvas').width($('#videoSize').val());
});
$('#enableStreaming').click(function () {
enableStreaming = this.checked;
loadSelectedStream();
});
$('#autoRecoverError').click(function () {
autoRecoverError = this.checked;
onDemoConfigChanged();
});
$('#enableWorker').click(function () {
enableWorker = this.checked;
onDemoConfigChanged();
});
$('#dumpfMP4').click(function () {
dumpfMP4 = this.checked;
onDemoConfigChanged();
});
$('#limitMetrics').change(function () {
limitMetrics = this.value;
onDemoConfigChanged();
});
$('#levelCapping').change(function () {
levelCapping = this.value;
onDemoConfigChanged();
});
$('#defaultAudioCodec').change(function () {
defaultAudioCodec = this.value;
onDemoConfigChanged();
});
$('#limitMetrics').val(limitMetrics);
$('#enableStreaming').prop('checked', enableStreaming);
$('#autoRecoverError').prop('checked', autoRecoverError);
$('#enableWorker').prop('checked', enableWorker);
$('#dumpfMP4').prop('checked', dumpfMP4);
$('#levelCapping').val(levelCapping);
$('#defaultAudioCodec').val(defaultAudioCodec || 'undefined');
$('h2').append(' <a target=_blank href=https://github.com/video-dev/hls.js/releases/tag/v' + Hls.version + '>v' + Hls.version + '</a>');
$('#currentVersion').html('Hls version:' + Hls.version);
$('#streamURL').val(sourceURL);
video.volume = 0.05;
hideAllTabs();
$('#metricsButtonWindow').toggle(windowSliding);
$('#metricsButtonFixed').toggle(!windowSliding);
loadSelectedStream();
});
function setupGlobals() {
window.events = events = {
url: url,
t0: performance.now(),
load: [],
buffer: [],
video: [],
level: [],
bitrate: []
};
// actual values, only on window
window.recoverDecodingErrorDate = null;
window.recoverSwapAudioCodecDate = null;
window.fmp4Data = fmp4Data = {
'audio': [],
'video': []
};
window.onClickBufferedRange = onClickBufferedRange;
window.updateLevelInfo = updateLevelInfo;
window.onDemoConfigChanged = onDemoConfigChanged;
window.createfMP4 = createfMP4;
window.goToMetricsPermaLink = goToMetricsPermaLink;
window.toggleTab = toggleTab;
window.onDemoConfigChanged = onDemoConfigChanged;
}
function trimArray(target, limit) {
if (limit < 0) {
return;
}
while (target.length > limit) {
target.shift();
}
}
function trimEventHistory() {
var x = limitMetrics;
if (x < 0) {
return;
}
trimArray(events.load, x);
trimArray(events.buffer, x);
trimArray(events.video, x);
trimArray(events.level, x);
trimArray(events.bitrate, x);
}
function loadSelectedStream() {
if (!Hls.isSupported()) {
handleUnsupported();
return;
}
url = $('#streamURL').val();
setupGlobals();
hideCanvas();
if (hls) {
hls.destroy();
if (hls.bufferTimer) {
clearInterval(hls.bufferTimer);
hls.bufferTimer = undefined;
}
hls = null;
}
if (!enableStreaming) {
logStatus('Streaming disabled');
return;
}
logStatus('Loading ' + url);
if (widevineLicenseUrl) {
widevineLicenseUrl = unescape(widevineLicenseUrl);
}
var hlsConfig = {
debug: true,
enableWorker: enableWorker,
defaultAudioCodec: defaultAudioCodec,
widevineLicenseUrl: widevineLicenseUrl
};
if (selectedTestStream && selectedTestStream.config) {
_extends(hlsConfig, selectedTestStream.config);
}
if (hlsConfig.widevineLicenseUrl) {
$('#widevineLicenseUrl').val(hlsConfig.widevineLicenseUrl);
}
widevineLicenseUrl = hlsConfig.widevineLicenseUrl = $('#widevineLicenseUrl').val();
if (hlsConfig.widevineLicenseUrl) {
hlsConfig.emeEnabled = true;
}
onDemoConfigChanged();
console.log('Using Hls.js config:', hlsConfig);
window.hls = hls = new Hls(hlsConfig);
logStatus('Loading manifest and attaching video element...');
hls.loadSource(url);
hls.autoLevelCapping = levelCapping;
hls.attachMedia(video);
hls.on(Hls.Events.MEDIA_ATTACHED, function () {
logStatus('Media element attached');
bufferingIdx = -1;
events.video.push({
time: performance.now() - events.t0,
type: 'Media attached'
});
trimEventHistory();
});
hls.on(Hls.Events.MEDIA_DETACHED, function () {
logStatus('Media element detached');
bufferingIdx = -1;
tracks = [];
events.video.push({
time: performance.now() - events.t0,
type: 'Media detached'
});
trimEventHistory();
});
hls.on(Hls.Events.FRAG_PARSING_INIT_SEGMENT, function (event, data) {
showCanvas();
var event = {
time: performance.now() - events.t0,
type: data.id + ' init segment'
};
events.video.push(event);
trimEventHistory();
});
hls.on(Hls.Events.FRAG_PARSING_METADATA, function (event, data) {
//console.log("Id3 samples ", data.samples);
});
hls.on(Hls.Events.LEVEL_SWITCHING, function (event, data) {
events.level.push({
time: performance.now() - events.t0,
id: data.level,
bitrate: Math.round(hls.levels[data.level].bitrate / 1000)
});
trimEventHistory();
updateLevelInfo();
});
hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
var event = {
type: 'manifest',
name: '',
start: 0,
end: data.levels.length,
time: data.stats.trequest - events.t0,
latency: data.stats.tfirst - data.stats.trequest,
load: data.stats.tload - data.stats.tfirst,
duration: data.stats.tload - data.stats.tfirst
};
events.load.push(event);
trimEventHistory();
refreshCanvas();
});
hls.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
logStatus('No of quality levels found: ' + hls.levels.length);
logStatus('Manifest successfully loaded');
stats = {
levelNb: data.levels.length,
levelParsed: 0
};
trimEventHistory();
updateLevelInfo();
});
hls.on(Hls.Events.AUDIO_TRACKS_UPDATED, function (event, data) {
logStatus('No of audio tracks found: ' + data.audioTracks.length);
updateAudioTrackInfo();
});
hls.on(Hls.Events.AUDIO_TRACK_SWITCHING, function (event, data) {
logStatus('Audio track switching...');
updateAudioTrackInfo();
var event = {
time: performance.now() - events.t0,
type: 'audio switching',
name: '@' + data.id
};
events.video.push(event);
trimEventHistory();
lastAudioTrackSwitchingIdx = events.video.length - 1;
});
hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, function (event, data) {
logStatus('Audio track switched');
updateAudioTrackInfo();
var event = {
time: performance.now() - events.t0,
type: 'audio switched',
name: '@' + data.id
};
if (lastAudioTrackSwitchingIdx !== undefined) {
events.video[lastAudioTrackSwitchingIdx].duration = event.time - events.video[lastAudioTrackSwitchingIdx].time;
lastAudioTrackSwitchingIdx = undefined;
}
events.video.push(event);
trimEventHistory();
});
hls.on(Hls.Events.LEVEL_LOADED, function (event, data) {
events.isLive = data.details.live;
var event = {
type: 'level',
id: data.level,
start: data.details.startSN,
end: data.details.endSN,
time: data.stats.trequest - events.t0,
latency: data.stats.tfirst - data.stats.trequest,
load: data.stats.tload - data.stats.tfirst,
parsing: data.stats.tparsed - data.stats.tload,
duration: data.stats.tload - data.stats.tfirst
};
var parsingDuration = data.stats.tparsed - data.stats.tload;
if (stats.levelParsed) {
this.sumLevelParsingMs += parsingDuration;
} else {
this.sumLevelParsingMs = parsingDuration;
}
stats.levelParsed++;
stats.levelParsingUs = Math.round(1000 * this.sumLevelParsingMs / stats.levelParsed);
//console.log('parsing level duration :' + stats.levelParsingUs + 'us,count:' + stats.levelParsed);
events.load.push(event);
trimEventHistory();
refreshCanvas();
});
hls.on(Hls.Events.AUDIO_TRACK_LOADED, function (event, data) {
events.isLive = data.details.live;
var event = {
type: 'audio track',
id: data.id,
start: data.details.startSN,
end: data.details.endSN,
time: data.stats.trequest - events.t0,
latency: data.stats.tfirst - data.stats.trequest,
load: data.stats.tload - data.stats.tfirst,
parsing: data.stats.tparsed - data.stats.tload,
duration: data.stats.tload - data.stats.tfirst
};
events.load.push(event);
trimEventHistory();
refreshCanvas();
});
hls.on(Hls.Events.FRAG_BUFFERED, function (event, data) {
var event = {
type: data.frag.type + ' fragment',
id: data.frag.level,
id2: data.frag.sn,
time: data.stats.trequest - events.t0,
latency: data.stats.tfirst - data.stats.trequest,
load: data.stats.tload - data.stats.tfirst,
parsing: data.stats.tparsed - data.stats.tload,
buffer: data.stats.tbuffered - data.stats.tparsed,
duration: data.stats.tbuffered - data.stats.tfirst,
bw: Math.round(8 * data.stats.total / (data.stats.tbuffered - data.stats.trequest)),
size: data.stats.total
};
events.load.push(event);
events.bitrate.push({
time: performance.now() - events.t0,
bitrate: event.bw,
duration: data.frag.duration,
level: event.id
});
if (hls.bufferTimer === undefined) {
events.buffer.push({
time: 0,
buffer: 0,
pos: 0
});
hls.bufferTimer = window.setInterval(checkBuffer, 100);
}
trimEventHistory();
refreshCanvas();
updateLevelInfo();
var latency = data.stats.tfirst - data.stats.trequest,
parsing = data.stats.tparsed - data.stats.tload,
process = data.stats.tbuffered - data.stats.trequest,
bitrate = Math.round(8 * data.stats.length / (data.stats.tbuffered - data.stats.tfirst));
if (stats.fragBuffered) {
stats.fragMinLatency = Math.min(stats.fragMinLatency, latency);
stats.fragMaxLatency = Math.max(stats.fragMaxLatency, latency);
stats.fragMinProcess = Math.min(stats.fragMinProcess, process);
stats.fragMaxProcess = Math.max(stats.fragMaxProcess, process);
stats.fragMinKbps = Math.min(stats.fragMinKbps, bitrate);
stats.fragMaxKbps = Math.max(stats.fragMaxKbps, bitrate);
stats.autoLevelCappingMin = Math.min(stats.autoLevelCappingMin, hls.autoLevelCapping);
stats.autoLevelCappingMax = Math.max(stats.autoLevelCappingMax, hls.autoLevelCapping);
stats.fragBuffered++;
} else {
stats.fragMinLatency = stats.fragMaxLatency = latency;
stats.fragMinProcess = stats.fragMaxProcess = process;
stats.fragMinKbps = stats.fragMaxKbps = bitrate;
stats.fragBuffered = 1;
stats.fragBufferedBytes = 0;
stats.autoLevelCappingMin = stats.autoLevelCappingMax = hls.autoLevelCapping;
this.sumLatency = 0;
this.sumKbps = 0;
this.sumProcess = 0;
this.sumParsing = 0;
}
stats.fraglastLatency = latency;
this.sumLatency += latency;
stats.fragAvgLatency = Math.round(this.sumLatency / stats.fragBuffered);
stats.fragLastProcess = process;
this.sumProcess += process;
this.sumParsing += parsing;
stats.fragAvgProcess = Math.round(this.sumProcess / stats.fragBuffered);
stats.fragLastKbps = bitrate;
this.sumKbps += bitrate;
stats.fragAvgKbps = Math.round(this.sumKbps / stats.fragBuffered);
stats.fragBufferedBytes += data.stats.total;
stats.fragparsingKbps = Math.round(8 * stats.fragBufferedBytes / this.sumParsing);
stats.fragparsingMs = Math.round(this.sumParsing);
stats.autoLevelCappingLast = hls.autoLevelCapping;
});
hls.on(Hls.Events.LEVEL_SWITCHED, function (event, data) {
var event = {
time: performance.now() - events.t0,
type: 'level switched',
name: data.level
};
events.video.push(event);
trimEventHistory();
refreshCanvas();
updateLevelInfo();
});
hls.on(Hls.Events.FRAG_CHANGED, function (event, data) {
var event = {
time: performance.now() - events.t0,
type: 'frag changed',
name: data.frag.sn + ' @ ' + data.frag.level
};
events.video.push(event);
trimEventHistory();
refreshCanvas();
updateLevelInfo();
stats.tagList = data.frag.tagList;
var level = data.frag.level,
autoLevel = data.frag.autoLevel;
if (stats.levelStart === undefined) {
stats.levelStart = level;
}
if (autoLevel) {
if (stats.fragChangedAuto) {
stats.autoLevelMin = Math.min(stats.autoLevelMin, level);
stats.autoLevelMax = Math.max(stats.autoLevelMax, level);
stats.fragChangedAuto++;
if (this.levelLastAuto && level !== stats.autoLevelLast) {
stats.autoLevelSwitch++;
}
} else {
stats.autoLevelMin = stats.autoLevelMax = level;
stats.autoLevelSwitch = 0;
stats.fragChangedAuto = 1;
this.sumAutoLevel = 0;
}
this.sumAutoLevel += level;
stats.autoLevelAvg = Math.round(1000 * this.sumAutoLevel / stats.fragChangedAuto) / 1000;
stats.autoLevelLast = level;
} else {
if (stats.fragChangedManual) {
stats.manualLevelMin = Math.min(stats.manualLevelMin, level);
stats.manualLevelMax = Math.max(stats.manualLevelMax, level);
stats.fragChangedManual++;
if (!this.levelLastAuto && level !== stats.manualLevelLast) {
stats.manualLevelSwitch++;
}
} else {
stats.manualLevelMin = stats.manualLevelMax = level;
stats.manualLevelSwitch = 0;
stats.fragChangedManual = 1;
}
stats.manualLevelLast = level;
}
this.levelLastAuto = autoLevel;
});
hls.on(Hls.Events.FRAG_LOAD_EMERGENCY_ABORTED, function (event, data) {
if (stats) {
if (stats.fragLoadEmergencyAborted === undefined) {
stats.fragLoadEmergencyAborted = 1;
} else {
stats.fragLoadEmergencyAborted++;
}
}
});
hls.on(Hls.Events.FRAG_DECRYPTED, function (event, data) {
if (!stats.fragDecrypted) {
stats.fragDecrypted = 0;
this.totalDecryptTime = 0;
stats.fragAvgDecryptTime = 0;
}
stats.fragDecrypted++;
this.totalDecryptTime += data.stats.tdecrypt - data.stats.tstart;
stats.fragAvgDecryptTime = this.totalDecryptTime / stats.fragDecrypted;
});
hls.on(Hls.Events.ERROR, function (event, data) {
console.warn('Error event:', data);
switch (data.details) {
case Hls.ErrorDetails.MANIFEST_LOAD_ERROR:
try {
$('#errorOut').html('Cannot load <a href="' + data.context.url + '">' + url + '</a><br>HTTP response code:' + data.response.code + ' <br>' + data.response.text);
if (data.response.code === 0) {
$('#errorOut').append('This might be a CORS issue, consider installing <a href="https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi">Allow-Control-Allow-Origin</a> Chrome Extension');
}
} catch (err) {
$('#errorOut').html('Cannot load <a href="' + data.context.url + '">' + url + '</a><br>Response body: ' + data.response.text);
}
break;
case Hls.ErrorDetails.MANIFEST_LOAD_TIMEOUT:
logError('Timeout while loading manifest');
break;
case Hls.ErrorDetails.MANIFEST_PARSING_ERROR:
logError('Error while parsing manifest:' + data.reason);
break;
case Hls.ErrorDetails.LEVEL_LOAD_ERROR:
logError('Error while loading level playlist');
break;
case Hls.ErrorDetails.LEVEL_LOAD_TIMEOUT:
logError('Timeout while loading level playlist');
break;
case Hls.ErrorDetails.LEVEL_SWITCH_ERROR:
logError('Error while trying to switch to level ' + data.level);
break;
case Hls.ErrorDetails.FRAG_LOAD_ERROR:
logError('Error while loading fragment ' + data.frag.url);
break;
case Hls.ErrorDetails.FRAG_LOAD_TIMEOUT:
logError('Timeout while loading fragment ' + data.frag.url);
break;
case Hls.ErrorDetails.FRAG_LOOP_LOADING_ERROR:
logError('Fragment-loop loading error');
break;
case Hls.ErrorDetails.FRAG_DECRYPT_ERROR:
logError('Decrypting error:' + data.reason);
break;
case Hls.ErrorDetails.FRAG_PARSING_ERROR:
logError('Parsing error:' + data.reason);
break;
case Hls.ErrorDetails.KEY_LOAD_ERROR:
logError('Error while loading key ' + data.frag.decryptdata.uri);
break;
case Hls.ErrorDetails.KEY_LOAD_TIMEOUT:
logError('Timeout while loading key ' + data.frag.decryptdata.uri);
break;
case Hls.ErrorDetails.BUFFER_APPEND_ERROR:
logError('Buffer append error');
break;
case Hls.ErrorDetails.BUFFER_ADD_CODEC_ERROR:
logError('Buffer add codec error for ' + data.mimeType + ':' + data.err.message);
break;
case Hls.ErrorDetails.BUFFER_APPENDING_ERROR:
logError('Buffer appending error');
break;
case Hls.ErrorDetails.BUFFER_STALLED_ERROR:
logError('Buffer stalled error');
break;
default:
break;
}
if (data.fatal) {
console.error('Fatal error :' + data.details);
switch (data.type) {
case Hls.ErrorTypes.MEDIA_ERROR:
handleMediaError();
break;
case Hls.ErrorTypes.NETWORK_ERROR:
logError('A network error occured');
break;
default:
logError('An unrecoverable error occured');
hls.destroy();
break;
}
}
if (!stats) {
stats = {};
}
// track all errors independently
if (stats[data.details] === undefined) {
stats[data.details] = 1;
} else {
stats[data.details] += 1;
}
// track fatal error
if (data.fatal) {
if (stats.fatalError === undefined) {
stats.fatalError = 1;
} else {
stats.fatalError += 1;
}
}
$('#statisticsOut').text(JSON.stringify(Object(__WEBPACK_IMPORTED_MODULE_0__demo_utils__["b" /* sortObject */])(stats), null, '\t'));
});
hls.on(Hls.Events.BUFFER_CREATED, function (event, data) {
tracks = data.tracks;
});
hls.on(Hls.Events.BUFFER_APPENDING, function (event, data) {
if (dumpfMP4) {
fmp4Data[data.type].push(data.data);
}
});
hls.on(Hls.Events.FPS_DROP, function (event, data) {
var evt = {
time: performance.now() - events.t0,
type: 'frame drop',
name: data.currentDropped + '/' + data.currentDecoded
};
events.video.push(evt);
trimEventHistory();
if (stats) {
if (stats.fpsDropEvent === undefined) {
stats.fpsDropEvent = 1;
} else {
stats.fpsDropEvent++;
}
stats.fpsTotalDroppedFrames = data.totalDroppedFrames;
}
});
video.addEventListener('resize', handleVideoEvent);
video.addEventListener('seeking', handleVideoEvent);
video.addEventListener('seeked', handleVideoEvent);
video.addEventListener('pause', handleVideoEvent);
video.addEventListener('play', handleVideoEvent);
video.addEventListener('canplay', handleVideoEvent);
video.addEventListener('canplaythrough', handleVideoEvent);
video.addEventListener('ended', handleVideoEvent);
video.addEventListener('playing', handleVideoEvent);
video.addEventListener('error', handleVideoEvent);
video.addEventListener('loadedmetadata', handleVideoEvent);
video.addEventListener('loadeddata', handleVideoEvent);
video.addEventListener('durationchange', handleVideoEvent);
}
function handleUnsupported() {
if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {
logStatus('You are using Firefox, it looks like MediaSource is not enabled,<br>please ensure the following keys are set appropriately in <b>about:config</b><br>media.mediasource.enabled=true<br>media.mediasource.mp4.enabled=true<br><b>media.mediasource.whitelist=false</b>');
} else {
logStatus('Your Browser does not support MediaSourceExtension / MP4 mediasource');
}
}
function handleVideoEvent(evt) {
var data = '';
switch (evt.type) {
case 'durationchange':
if (evt.target.duration - lastDuration <= 0.5) {
// some browsers report several duration change events with almost the same value ... avoid spamming video events
return;
}
lastDuration = evt.target.duration;
data = Math.round(evt.target.duration * 1000);
break;
case 'resize':
data = evt.target.videoWidth + '/' + evt.target.videoHeight;
break;
case 'loadedmetadata':
case 'loadeddata':
case 'canplay':
case 'canplaythrough':
case 'ended':
case 'seeking':
case 'seeked':
case 'play':
case 'playing':
lastStartPosition = evt.target.currentTime;
case 'pause':
case 'waiting':
case 'stalled':
case 'error':
data = Math.round(evt.target.currentTime * 1000);
if (evt.type === 'error') {
var errorTxt = void 0,
mediaError = evt.currentTarget.error;
switch (mediaError.code) {
case mediaError.MEDIA_ERR_ABORTED:
errorTxt = 'You aborted the video playback';
break;
case mediaError.MEDIA_ERR_DECODE:
errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support';
handleMediaError();
break;
case mediaError.MEDIA_ERR_NETWORK:
errorTxt = 'A network error caused the video download to fail part-way';
break;
case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported';
break;
}
if (mediaError.message) {
errorTxt += ' - ' + mediaError.message;
}
logStatus(errorTxt);
console.error(errorTxt);
}
break;
default:
break;
}
var event = {
time: performance.now() - events.t0,
type: evt.type,
name: data
};
events.video.push(event);
if (evt.type === 'seeking') {
lastSeekingIdx = events.video.length - 1;
}
if (evt.type === 'seeked') {
events.video[lastSeekingIdx].duration = event.time - events.video[lastSeekingIdx].time;
}
trimEventHistory();
}
function handleMediaError() {
if (autoRecoverError) {
var now = performance.now();
if (!recoverDecodingErrorDate || now - recoverDecodingErrorDate > 3000) {
recoverDecodingErrorDate = performance.now();
$('#statusOut').append(', trying to recover media error.');
hls.recoverMediaError();
} else {
if (!recoverSwapAudioCodecDate || now - recoverSwapAudioCodecDate > 3000) {
recoverSwapAudioCodecDate = performance.now();
$('#statusOut').append(', trying to swap audio codec and recover media error.');
hls.swapAudioCodec();
hls.recoverMediaError();
} else {
$('#statusOut').append(', cannot recover. Last media error recovery failed.');
}
}
}
}
function timeRangesToString(r) {
var log = '';
for (var i = 0; i < r.length; i++) {
log += '[' + r.start(i) + ', ' + r.end(i) + ']';
log += ' ';
}
return log;
}
function checkBuffer() {
var v = $('#video')[0];
var canvas = $('#bufferedCanvas')[0];
var ctx = canvas.getContext('2d');
var r = v.buffered;
var bufferingDuration = void 0;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'gray';
if (r) {
if (!canvas.width || canvas.width !== v.clientWidth) {
canvas.width = v.clientWidth;
}
var pos = v.currentTime,
bufferLen;
for (var i = 0, bufferLen = 0; i < r.length; i++) {
var start = r.start(i) / v.duration * canvas.width;
var end = r.end(i) / v.duration * canvas.width;
ctx.fillRect(start, 3, Math.max(2, end - start), 10);
if (pos >= r.start(i) && pos < r.end(i)) {
// play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
bufferLen = r.end(i) - pos;
}
}
// check if we are in buffering / or playback ended state
if (bufferLen <= 0.1 && v.paused === false && pos - lastStartPosition > 0.5) {
// don't create buffering event if we are at the end of the playlist, don't report ended for live playlist
if (lastDuration - pos <= 0.5 && events.isLive === false) {} else {
// we are not at the end of the playlist ... real buffering
if (bufferingIdx !== -1) {
bufferingDuration = performance.now() - events.t0 - events.video[bufferingIdx].time;
events.video[bufferingIdx].duration = bufferingDuration;
events.video[bufferingIdx].name = bufferingDuration;
} else {
events.video.push({
type: 'buffering',
time: performance.now() - events.t0
});
trimEventHistory();
// we are in buffering state
bufferingIdx = events.video.length - 1;
}
}
}
if (bufferLen > 0.1 && bufferingIdx != -1) {
bufferingDuration = performance.now() - events.t0 - events.video[bufferingIdx].time;
events.video[bufferingIdx].duration = bufferingDuration;
events.video[bufferingIdx].name = bufferingDuration;
// we are out of buffering state
bufferingIdx = -1;
}
// update buffer/position for current Time
var event = {
time: performance.now() - events.t0,
buffer: Math.round(bufferLen * 1000),
pos: Math.round(pos * 1000)
};
var bufEvents = events.buffer,
bufEventLen = bufEvents.length;
if (bufEventLen > 1) {
var event0 = bufEvents[bufEventLen - 2],
event1 = bufEvents[bufEventLen - 1];
var slopeBuf0 = (event0.buffer - event1.buffer) / (event0.time - event1.time);
var slopeBuf1 = (event1.buffer - event.buffer) / (event1.time - event.time);
var slopePos0 = (event0.pos - event1.pos) / (event0.time - event1.time);
var slopePos1 = (event1.pos - event.pos) / (event1.time - event.time);
// compute slopes. if less than 30% difference, remove event1
if ((slopeBuf0 === slopeBuf1 || Math.abs(slopeBuf0 / slopeBuf1 - 1) <= 0.3) && (slopePos0 === slopePos1 || Math.abs(slopePos0 / slopePos1 - 1) <= 0.3)) {
bufEvents.pop();
}
}
events.buffer.push(event);
trimEventHistory();
refreshCanvas();
var log = 'Duration: ' + v.duration + '\n' + 'Buffered: ' + timeRangesToString(v.buffered) + '\n' + 'Seekable: ' + timeRangesToString(v.seekable) + '\n' + 'Played: ' + timeRangesToString(v.played) + '\n';
if (hls.media) {
for (var type in tracks) {
log += 'Buffer for ' + type + ' contains: ' + timeRangesToString(tracks[type].buffer.buffered) + '\n';
}
var videoPlaybackQuality = v.getVideoPlaybackQuality;
if (videoPlaybackQuality && (typeof videoPlaybackQuality === 'undefined' ? 'undefined' : _typeof(videoPlaybackQuality)) === (typeof Function === 'undefined' ? 'undefined' : _typeof(Function))) {
log += 'Dropped frames: ' + v.getVideoPlaybackQuality().droppedVideoFrames + '\n';
log += 'Corrupted frames:' + v.getVideoPlaybackQuality().corruptedVideoFrames + '\n';
} else if (v.webkitDroppedFrameCount) {
log += 'Dropped frames:' + v.webkitDroppedFrameCount + '\n';
}
}
$('#bufferedOut').text(log);
$('#statisticsOut').text(JSON.stringify(Object(__WEBPACK_IMPORTED_MODULE_0__demo_utils__["b" /* sortObject */])(stats), null, '\t'));
ctx.fillStyle = 'blue';
var x = v.currentTime / v.duration * canvas.width;
ctx.fillRect(x, 0, 2, 15);