-
Notifications
You must be signed in to change notification settings - Fork 1
/
p2p-media-loader-hlsjs.js
2076 lines (1781 loc) · 66.4 KB
/
p2p-media-loader-hlsjs.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
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/**
* Copyright 2018 Novage LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
if (!window.p2pml) {
window.p2pml = {};
}
window.p2pml.hlsjs = require("p2p-media-loader-hlsjs");
},{"p2p-media-loader-hlsjs":"p2p-media-loader-hlsjs"}],2:[function(require,module,exports){
"use strict";
/**
* Copyright 2018 Novage LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const p2p_media_loader_core_1 = require("p2p-media-loader-core");
const segment_manager_1 = require("./segment-manager");
const hlsjs_loader_1 = require("./hlsjs-loader");
const hlsjs_loader_class_1 = require("./hlsjs-loader-class");
class Engine extends events_1.EventEmitter {
constructor(settings = {}) {
super();
this.loader = new p2p_media_loader_core_1.HybridLoader(settings.loader);
this.segmentManager = new segment_manager_1.SegmentManager(this.loader, settings.segments);
Object.keys(p2p_media_loader_core_1.Events)
.map(eventKey => p2p_media_loader_core_1.Events[eventKey])
.forEach(event => this.loader.on(event, (...args) => this.emit(event, ...args)));
}
static isSupported() {
return p2p_media_loader_core_1.HybridLoader.isSupported();
}
createLoaderClass() {
return hlsjs_loader_class_1.createHlsJsLoaderClass(hlsjs_loader_1.HlsJsLoader, this);
}
async destroy() {
await this.segmentManager.destroy();
}
getSettings() {
return {
segments: this.segmentManager.getSettings(),
loader: this.loader.getSettings()
};
}
getDetails() {
return {
loader: this.loader.getDetails()
};
}
setPlayingSegment(url, byterange, start, duration) {
this.segmentManager.setPlayingSegment(url, byterange, start, duration);
}
setPlayingSegmentByCurrentTime(playheadPosition) {
this.segmentManager.setPlayingSegmentByCurrentTime(playheadPosition);
}
}
exports.Engine = Engine;
},{"./hlsjs-loader":4,"./hlsjs-loader-class":3,"./segment-manager":5,"events":"events","p2p-media-loader-core":"p2p-media-loader-core"}],3:[function(require,module,exports){
/**
* Copyright 2018 Novage LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function createHlsJsLoaderClass(HlsJsLoader, engine) {
function HlsJsLoaderClass() {
this.impl = new HlsJsLoader(engine.segmentManager);
this.stats = this.impl.stats;
}
HlsJsLoaderClass.prototype.load = function (context, config, callbacks) {
this.context = context;
this.impl.load(context, config, callbacks);
};
HlsJsLoaderClass.prototype.abort = function () {
this.impl.abort(this.context);
};
HlsJsLoaderClass.prototype.destroy = function () {
if (this.context) {
this.impl.abort(this.context);
}
};
HlsJsLoaderClass.getEngine = function () {
return engine;
};
return HlsJsLoaderClass;
}
module.exports.createHlsJsLoaderClass = createHlsJsLoaderClass;
},{}],4:[function(require,module,exports){
"use strict";
/**
* Copyright 2018 Novage LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const DEFAULT_DOWNLOAD_LATENCY = 1;
const DEFAULT_DOWNLOAD_BANDWIDTH = 12500; // bytes per millisecond
class HlsJsLoader {
constructor(segmentManager) {
this.stats = {}; // required for older versions of hls.js
this.segmentManager = segmentManager;
}
async load(context, _config, callbacks) {
if (context.type) {
try {
const result = await this.segmentManager.loadPlaylist(context.url);
this.successPlaylist(result, context, callbacks);
}
catch (e) {
this.error(e, context, callbacks);
}
}
else if (context.frag) {
try {
const result = await this.segmentManager.loadSegment(context.url, (context.rangeStart == undefined) || (context.rangeEnd == undefined)
? undefined
: { offset: context.rangeStart, length: context.rangeEnd - context.rangeStart });
if (result.content !== undefined) {
setTimeout(() => this.successSegment(result.content, result.downloadBandwidth, context, callbacks), 0);
}
}
catch (e) {
setTimeout(() => this.error(e, context, callbacks), 0);
}
}
else {
console.warn("Unknown load request", context);
}
}
abort(context) {
this.segmentManager.abortSegment(context.url, (context.rangeStart == undefined) || (context.rangeEnd == undefined)
? undefined
: { offset: context.rangeStart, length: context.rangeEnd - context.rangeStart });
}
successPlaylist(xhr, context, callbacks) {
const now = performance.now();
this.stats.trequest = now - 300;
this.stats.tfirst = now - 200;
this.stats.tload = now;
this.stats.loaded = xhr.response.length;
callbacks.onSuccess({
url: xhr.responseURL,
data: xhr.response
}, this.stats, context);
}
successSegment(content, downloadBandwidth, context, callbacks) {
const now = performance.now();
const downloadTime = content.byteLength / (((downloadBandwidth === undefined) || (downloadBandwidth <= 0)) ? DEFAULT_DOWNLOAD_BANDWIDTH : downloadBandwidth);
this.stats.trequest = now - DEFAULT_DOWNLOAD_LATENCY - downloadTime;
this.stats.tfirst = now - downloadTime;
this.stats.tload = now;
this.stats.loaded = content.byteLength;
callbacks.onSuccess({
url: context.url,
data: content
}, this.stats, context);
}
error(error, context, callbacks) {
callbacks.onError(error, context);
}
}
exports.HlsJsLoader = HlsJsLoader;
},{}],5:[function(require,module,exports){
"use strict";
/**
* Copyright 2018 Novage LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const p2p_media_loader_core_1 = require("p2p-media-loader-core");
const m3u8_parser_1 = require("m3u8-parser");
const defaultSettings = {
forwardSegmentCount: 20,
swarmId: undefined,
assetsStorage: undefined,
};
class SegmentManager {
constructor(loader, settings = {}) {
this.masterPlaylist = null;
this.variantPlaylists = new Map();
this.segmentRequest = null;
this.playQueue = [];
this.onSegmentLoaded = (segment) => {
if (this.segmentRequest && (this.segmentRequest.segmentUrl === segment.url) &&
(byterangeToString(this.segmentRequest.segmentByterange) === segment.range)) {
this.segmentRequest.onSuccess(segment.data.slice(0), segment.downloadBandwidth);
this.segmentRequest = null;
}
};
this.onSegmentError = (segment, error) => {
if (this.segmentRequest && (this.segmentRequest.segmentUrl === segment.url) &&
(byterangeToString(this.segmentRequest.segmentByterange) === segment.range)) {
this.segmentRequest.onError(error);
this.segmentRequest = null;
}
};
this.onSegmentAbort = (segment) => {
if (this.segmentRequest && (this.segmentRequest.segmentUrl === segment.url) &&
(byterangeToString(this.segmentRequest.segmentByterange) === segment.range)) {
this.segmentRequest.onError("Loading aborted: internal abort");
this.segmentRequest = null;
}
};
this.settings = Object.assign(Object.assign({}, defaultSettings), settings);
this.loader = loader;
this.loader.on(p2p_media_loader_core_1.Events.SegmentLoaded, this.onSegmentLoaded);
this.loader.on(p2p_media_loader_core_1.Events.SegmentError, this.onSegmentError);
this.loader.on(p2p_media_loader_core_1.Events.SegmentAbort, this.onSegmentAbort);
}
getSettings() {
return this.settings;
}
processPlaylist(requestUrl, content, responseUrl) {
const parser = new m3u8_parser_1.Parser();
parser.push(content);
parser.end();
const playlist = new Playlist(requestUrl, responseUrl, parser.manifest);
if (playlist.manifest.playlists) {
this.masterPlaylist = playlist;
for (const [key, variantPlaylist] of this.variantPlaylists) {
const { streamSwarmId, found, index } = this.getStreamSwarmId(variantPlaylist.requestUrl);
if (!found) {
this.variantPlaylists.delete(key);
}
else {
variantPlaylist.streamSwarmId = streamSwarmId;
variantPlaylist.streamId = "V" + index.toString();
}
}
}
else {
const { streamSwarmId, found, index } = this.getStreamSwarmId(requestUrl);
if (found || (this.masterPlaylist === null)) { // do not add audio and subtitles to variants
playlist.streamSwarmId = streamSwarmId;
playlist.streamId = (this.masterPlaylist === null ? undefined : "V" + index.toString());
this.variantPlaylists.set(requestUrl, playlist);
this.updateSegments();
}
}
}
async loadPlaylist(url) {
const assetsStorage = this.settings.assetsStorage;
let xhr;
if (assetsStorage !== undefined) {
let masterSwarmId;
masterSwarmId = this.getMasterSwarmId();
if (masterSwarmId === undefined) {
masterSwarmId = url.split("?")[0];
}
const asset = await assetsStorage.getAsset(url, undefined, masterSwarmId);
if (asset !== undefined) {
xhr = {
responseURL: asset.responseUri,
response: asset.data,
};
}
else {
xhr = await this.loadContent(url, "text");
assetsStorage.storeAsset({
masterManifestUri: this.masterPlaylist !== null ? this.masterPlaylist.requestUrl : url,
masterSwarmId: masterSwarmId,
requestUri: url,
responseUri: xhr.responseURL,
data: xhr.response,
});
}
}
else {
xhr = await this.loadContent(url, "text");
}
this.processPlaylist(url, xhr.response, xhr.responseURL);
return xhr;
}
async loadSegment(url, byterange) {
const segmentLocation = this.getSegmentLocation(url, byterange);
const byteRangeString = byterangeToString(byterange);
if (!segmentLocation) {
let content;
// Not a segment from variants; usually can be: init, audio or subtitles segment, encription key etc.
const assetsStorage = this.settings.assetsStorage;
if (assetsStorage !== undefined) {
let masterManifestUri = this.masterPlaylist !== null ? this.masterPlaylist.requestUrl : undefined;
let masterSwarmId;
masterSwarmId = this.getMasterSwarmId();
if (masterSwarmId === undefined && this.variantPlaylists.size === 1) {
masterSwarmId = this.variantPlaylists.values().next().value.requestUrl.split("?")[0];
}
if (masterManifestUri === undefined && this.variantPlaylists.size === 1) {
masterManifestUri = this.variantPlaylists.values().next().value.requestUrl;
}
if (masterSwarmId !== undefined && masterManifestUri !== undefined) {
const asset = await assetsStorage.getAsset(url, byteRangeString, masterSwarmId);
if (asset !== undefined) {
content = asset.data;
}
else {
const xhr = await this.loadContent(url, "arraybuffer", byteRangeString);
content = xhr.response;
assetsStorage.storeAsset({
masterManifestUri: masterManifestUri,
masterSwarmId: masterSwarmId,
requestUri: url,
requestRange: byteRangeString,
responseUri: xhr.responseURL,
data: content,
});
}
}
}
if (content === undefined) {
const xhr = await this.loadContent(url, "arraybuffer", byteRangeString);
content = xhr.response;
}
return { content, downloadBandwidth: 0 };
}
const segmentSequence = (segmentLocation.playlist.manifest.mediaSequence ? segmentLocation.playlist.manifest.mediaSequence : 0)
+ segmentLocation.segmentIndex;
if (this.playQueue.length > 0) {
const previousSegment = this.playQueue[this.playQueue.length - 1];
if (previousSegment.segmentSequence !== segmentSequence - 1) {
// Reset play queue in case of segment loading out of sequence
this.playQueue = [];
}
}
if (this.segmentRequest) {
this.segmentRequest.onError("Cancel segment request: simultaneous segment requests are not supported");
}
const promise = new Promise((resolve, reject) => {
this.segmentRequest = new SegmentRequest(url, byterange, segmentSequence, segmentLocation.playlist.requestUrl, (content, downloadBandwidth) => resolve({ content, downloadBandwidth }), error => reject(error));
});
this.playQueue.push({ segmentUrl: url, segmentByterange: byterange, segmentSequence: segmentSequence });
this.loadSegments(segmentLocation.playlist, segmentLocation.segmentIndex, true);
return promise;
}
setPlayingSegment(url, byterange, start, duration) {
const urlIndex = this.playQueue.findIndex(segment => (segment.segmentUrl == url) && compareByterange(segment.segmentByterange, byterange));
if (urlIndex >= 0) {
this.playQueue = this.playQueue.slice(urlIndex);
this.playQueue[0].playPosition = { start, duration };
this.updateSegments();
}
}
setPlayingSegmentByCurrentTime(playheadPosition) {
if (this.playQueue.length === 0 || !this.playQueue[0].playPosition) {
return;
}
const currentSegmentPosition = this.playQueue[0].playPosition;
const segmentEndTime = currentSegmentPosition.start + currentSegmentPosition.duration;
if (segmentEndTime - playheadPosition < 0.2) {
// means that current segment is (almost) finished playing
// remove it from queue
this.playQueue = this.playQueue.slice(1);
this.updateSegments();
}
}
abortSegment(url, byterange) {
if (this.segmentRequest && (this.segmentRequest.segmentUrl === url) &&
compareByterange(this.segmentRequest.segmentByterange, byterange)) {
this.segmentRequest.onSuccess(undefined, 0);
this.segmentRequest = null;
}
}
async destroy() {
if (this.segmentRequest) {
this.segmentRequest.onError("Loading aborted: object destroyed");
this.segmentRequest = null;
}
this.masterPlaylist = null;
this.variantPlaylists.clear();
this.playQueue = [];
if (this.settings.assetsStorage !== undefined) {
await this.settings.assetsStorage.destroy();
}
await this.loader.destroy();
}
updateSegments() {
if (!this.segmentRequest) {
return;
}
const segmentLocation = this.getSegmentLocation(this.segmentRequest.segmentUrl, this.segmentRequest.segmentByterange);
if (segmentLocation) {
this.loadSegments(segmentLocation.playlist, segmentLocation.segmentIndex, false);
}
}
getSegmentLocation(url, byterange) {
for (const playlist of this.variantPlaylists.values()) {
const segmentIndex = playlist.getSegmentIndex(url, byterange);
if (segmentIndex >= 0) {
return { playlist: playlist, segmentIndex: segmentIndex };
}
}
return undefined;
}
async loadSegments(playlist, segmentIndex, requestFirstSegment) {
const segments = [];
const playlistSegments = playlist.manifest.segments;
const initialSequence = playlist.manifest.mediaSequence ? playlist.manifest.mediaSequence : 0;
let loadSegmentId = null;
let priority = Math.max(0, this.playQueue.length - 1);
const masterSwarmId = this.getMasterSwarmId();
for (let i = segmentIndex; i < playlistSegments.length && segments.length < this.settings.forwardSegmentCount; ++i) {
const segment = playlist.manifest.segments[i];
const url = playlist.getSegmentAbsoluteUrl(segment.uri);
const byterange = segment.byterange;
const id = this.getSegmentId(playlist, initialSequence + i);
segments.push({
id: id,
url: url,
masterSwarmId: masterSwarmId !== undefined ? masterSwarmId : playlist.streamSwarmId,
masterManifestUri: this.masterPlaylist !== null ? this.masterPlaylist.requestUrl : playlist.requestUrl,
streamId: playlist.streamId,
sequence: (initialSequence + i).toString(),
range: byterangeToString(byterange),
priority: priority++,
});
if (requestFirstSegment && !loadSegmentId) {
loadSegmentId = id;
}
}
this.loader.load(segments, playlist.streamSwarmId);
if (loadSegmentId) {
const segment = await this.loader.getSegment(loadSegmentId);
if (segment) { // Segment already loaded by loader
this.onSegmentLoaded(segment);
}
}
}
getSegmentId(playlist, segmentSequence) {
return `${playlist.streamSwarmId}+${segmentSequence}`;
}
getMasterSwarmId() {
const settingsSwarmId = (this.settings.swarmId && (this.settings.swarmId.length !== 0)) ? this.settings.swarmId : undefined;
if (settingsSwarmId !== undefined) {
return settingsSwarmId;
}
return (this.masterPlaylist !== null)
? this.masterPlaylist.requestUrl.split("?")[0]
: undefined;
}
getStreamSwarmId(playlistUrl) {
const masterSwarmId = this.getMasterSwarmId();
if (this.masterPlaylist !== null) {
for (let i = 0; i < this.masterPlaylist.manifest.playlists.length; ++i) {
const url = new URL(this.masterPlaylist.manifest.playlists[i].uri, this.masterPlaylist.responseUrl).toString();
if (url === playlistUrl) {
return { streamSwarmId: `${masterSwarmId}+V${i}`, found: true, index: i };
}
}
}
return {
streamSwarmId: masterSwarmId !== undefined ? masterSwarmId : playlistUrl.split("?")[0],
found: false,
index: -1
};
}
async loadContent(url, responseType, range) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = responseType;
if (range) {
xhr.setRequestHeader("Range", range);
}
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr);
}
else {
reject(xhr.statusText);
}
});
const xhrSetup = this.loader.getSettings().xhrSetup;
if (xhrSetup) {
xhrSetup(xhr, url);
}
xhr.send();
});
}
}
exports.SegmentManager = SegmentManager;
class Playlist {
constructor(requestUrl, responseUrl, manifest) {
this.requestUrl = requestUrl;
this.responseUrl = responseUrl;
this.manifest = manifest;
this.streamSwarmId = "";
}
getSegmentIndex(url, byterange) {
for (let i = 0; i < this.manifest.segments.length; ++i) {
const segment = this.manifest.segments[i];
const segmentUrl = this.getSegmentAbsoluteUrl(segment.uri);
if ((url === segmentUrl) && compareByterange(segment.byterange, byterange)) {
return i;
}
}
return -1;
}
getSegmentAbsoluteUrl(segmentUrl) {
return new URL(segmentUrl, this.responseUrl).toString();
}
}
class SegmentRequest {
constructor(segmentUrl, segmentByterange, segmentSequence, playlistRequestUrl, onSuccess, onError) {
this.segmentUrl = segmentUrl;
this.segmentByterange = segmentByterange;
this.segmentSequence = segmentSequence;
this.playlistRequestUrl = playlistRequestUrl;
this.onSuccess = onSuccess;
this.onError = onError;
}
}
function compareByterange(b1, b2) {
return (b1 === undefined)
? (b2 === undefined)
: ((b2 !== undefined) && (b1.length === b2.length) && (b1.offset === b2.offset));
}
function byterangeToString(byterange) {
if (byterange === undefined) {
return undefined;
}
const end = byterange.offset + byterange.length - 1;
return `bytes=${byterange.offset}-${end}`;
}
},{"m3u8-parser":7,"p2p-media-loader-core":"p2p-media-loader-core"}],6:[function(require,module,exports){
(function (global){
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof global !== "undefined") {
win = global;
} else if (typeof self !== "undefined"){
win = self;
} else {
win = {};
}
module.exports = win;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],7:[function(require,module,exports){
/*! @name m3u8-parser @version 4.4.0 @license Apache-2.0 */
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var window = _interopDefault(require('global/window'));
function _extends() {
_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;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
/**
* @file stream.js
*/
/**
* A lightweight readable stream implementation that handles event dispatching.
*
* @class Stream
*/
var Stream =
/*#__PURE__*/
function () {
function Stream() {
this.listeners = {};
}
/**
* Add a listener for a specified event type.
*
* @param {string} type the event name
* @param {Function} listener the callback to be invoked when an event of
* the specified type occurs
*/
var _proto = Stream.prototype;
_proto.on = function on(type, listener) {
if (!this.listeners[type]) {
this.listeners[type] = [];
}
this.listeners[type].push(listener);
}
/**
* Remove a listener for a specified event type.
*
* @param {string} type the event name
* @param {Function} listener a function previously registered for this
* type of event through `on`
* @return {boolean} if we could turn it off or not
*/
;
_proto.off = function off(type, listener) {
if (!this.listeners[type]) {
return false;
}
var index = this.listeners[type].indexOf(listener);
this.listeners[type].splice(index, 1);
return index > -1;
}
/**
* Trigger an event of the specified type on this stream. Any additional
* arguments to this function are passed as parameters to event listeners.
*
* @param {string} type the event name
*/
;
_proto.trigger = function trigger(type) {
var callbacks = this.listeners[type];
var i;
var length;
var args;
if (!callbacks) {
return;
} // Slicing the arguments on every invocation of this method
// can add a significant amount of overhead. Avoid the
// intermediate object creation for the common case of a
// single callback argument
if (arguments.length === 2) {
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].call(this, arguments[1]);
}
} else {
args = Array.prototype.slice.call(arguments, 1);
length = callbacks.length;
for (i = 0; i < length; ++i) {
callbacks[i].apply(this, args);
}
}
}
/**
* Destroys the stream and cleans up.
*/
;
_proto.dispose = function dispose() {
this.listeners = {};
}
/**
* Forwards all `data` events on this stream to the destination stream. The
* destination stream should provide a method `push` to receive the data
* events as they arrive.
*
* @param {Stream} destination the stream that will receive all `data` events
* @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
*/
;
_proto.pipe = function pipe(destination) {
this.on('data', function (data) {
destination.push(data);
});
};
return Stream;
}();
/**
* A stream that buffers string input and generates a `data` event for each
* line.
*
* @class LineStream
* @extends Stream
*/
var LineStream =
/*#__PURE__*/
function (_Stream) {
_inheritsLoose(LineStream, _Stream);
function LineStream() {
var _this;
_this = _Stream.call(this) || this;
_this.buffer = '';
return _this;
}
/**
* Add new data to be parsed.
*
* @param {string} data the text to process
*/
var _proto = LineStream.prototype;
_proto.push = function push(data) {
var nextNewline;
this.buffer += data;
nextNewline = this.buffer.indexOf('\n');
for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
this.trigger('data', this.buffer.substring(0, nextNewline));
this.buffer = this.buffer.substring(nextNewline + 1);
}
};
return LineStream;
}(Stream);
/**
* "forgiving" attribute list psuedo-grammar:
* attributes -> keyvalue (',' keyvalue)*
* keyvalue -> key '=' value
* key -> [^=]*
* value -> '"' [^"]* '"' | [^,]*
*/
var attributeSeparator = function attributeSeparator() {
var key = '[^=]*';
var value = '"[^"]*"|[^,]*';
var keyvalue = '(?:' + key + ')=(?:' + value + ')';
return new RegExp('(?:^|,)(' + keyvalue + ')');
};
/**
* Parse attributes from a line given the separator
*
* @param {string} attributes the attribute line to parse
*/
var parseAttributes = function parseAttributes(attributes) {
// split the string using attributes as the separator
var attrs = attributes.split(attributeSeparator());
var result = {};
var i = attrs.length;
var attr;
while (i--) {
// filter out unmatched portions of the string
if (attrs[i] === '') {
continue;
} // split the key and value
attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
result[attr[0]] = attr[1];
}
return result;
};
/**
* A line-level M3U8 parser event stream. It expects to receive input one
* line at a time and performs a context-free parse of its contents. A stream
* interpretation of a manifest can be useful if the manifest is expected to
* be too large to fit comfortably into memory or the entirety of the input
* is not immediately available. Otherwise, it's probably much easier to work
* with a regular `Parser` object.
*
* Produces `data` events with an object that captures the parser's
* interpretation of the input. That object has a property `tag` that is one
* of `uri`, `comment`, or `tag`. URIs only have a single additional
* property, `line`, which captures the entirety of the input without
* interpretation. Comments similarly have a single additional property
* `text` which is the input without the leading `#`.
*
* Tags always have a property `tagType` which is the lower-cased version of
* the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
* `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
* tags are given the tag type `unknown` and a single additional property
* `data` with the remainder of the input.
*
* @class ParseStream
* @extends Stream
*/
var ParseStream =
/*#__PURE__*/
function (_Stream) {
_inheritsLoose(ParseStream, _Stream);
function ParseStream() {
var _this;
_this = _Stream.call(this) || this;
_this.customParsers = [];
_this.tagMappers = [];
return _this;
}
/**
* Parses an additional line of input.
*
* @param {string} line a single line of an M3U8 file to parse
*/
var _proto = ParseStream.prototype;
_proto.push = function push(line) {
var _this2 = this;
var match;
var event; // strip whitespace
line = line.trim();
if (line.length === 0) {
// ignore empty lines
return;
} // URIs
if (line[0] !== '#') {
this.trigger('data', {
type: 'uri',
uri: line
});
return;
} // map tags
var newLines = this.tagMappers.reduce(function (acc, mapper) {
var mappedLine = mapper(line); // skip if unchanged
if (mappedLine === line) {
return acc;
}
return acc.concat([mappedLine]);
}, [line]);
newLines.forEach(function (newLine) {
for (var i = 0; i < _this2.customParsers.length; i++) {
if (_this2.customParsers[i].call(_this2, newLine)) {
return;
}
} // Comments
if (newLine.indexOf('#EXT') !== 0) {
_this2.trigger('data', {
type: 'comment',
text: newLine.slice(1)
});
return;
} // strip off any carriage returns here so the regex matching
// doesn't have to account for them.
newLine = newLine.replace('\r', ''); // Tags
match = /^#EXTM3U/.exec(newLine);
if (match) {
_this2.trigger('data', {
type: 'tag',
tagType: 'm3u'
});
return;
}
match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(newLine);
if (match) {
event = {
type: 'tag',
tagType: 'inf'
};
if (match[1]) {
event.duration = parseFloat(match[1]);
}
if (match[2]) {
event.title = match[2];
}
_this2.trigger('data', event);
return;
}
match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(newLine);
if (match) {
event = {
type: 'tag',
tagType: 'targetduration'
};
if (match[1]) {
event.duration = parseInt(match[1], 10);
}