@antmedia/web_player 2.8.0-SNAPSHOT

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.project +17 -0
  2. package/.settings/.jsdtscope +7 -0
  3. package/.settings/org.eclipse.wst.jsdt.ui.superType.container +1 -0
  4. package/.settings/org.eclipse.wst.jsdt.ui.superType.name +1 -0
  5. package/LICENSE +201 -0
  6. package/README.md +1 -0
  7. package/api-extractor.json +38 -0
  8. package/codecov.yml +6 -0
  9. package/dist/_commonjsHelpers-ed042b00.js +10 -0
  10. package/dist/aframe-master-42bb78a9.js +7139 -0
  11. package/dist/browser/web_player.js +976 -0
  12. package/dist/dash.all.min-84806d51.js +36 -0
  13. package/dist/es/_commonjsHelpers-7d1333e8.js +7 -0
  14. package/dist/es/aframe-master-a6146619.js +7137 -0
  15. package/dist/es/dash.all.min-4a2772b6.js +34 -0
  16. package/dist/es/index.d.ts +227 -0
  17. package/dist/es/index.js +1 -0
  18. package/dist/es/video-js.min-8b4dfe88.js +3 -0
  19. package/dist/es/video.es-22056625.js +31061 -0
  20. package/dist/es/videojs-contrib-quality-levels.es-5f5b5f23.js +287 -0
  21. package/dist/es/videojs-hls-quality-selector.es-3c54e1cd.js +391 -0
  22. package/dist/es/videojs-webrtc-plugin-b9e4da27.js +3 -0
  23. package/dist/es/videojs-webrtc-plugin.es-f41400f7.js +7649 -0
  24. package/dist/es/web_player.js +1262 -0
  25. package/dist/index.d.ts +227 -0
  26. package/dist/index.js +7 -0
  27. package/dist/video-js.min-7e4ae47a.js +5 -0
  28. package/dist/video.es-72122d04.js +31067 -0
  29. package/dist/videojs-contrib-quality-levels.es-ef3cec9e.js +289 -0
  30. package/dist/videojs-hls-quality-selector.es-562309df.js +393 -0
  31. package/dist/videojs-webrtc-plugin-d30c3e7a.js +5 -0
  32. package/dist/videojs-webrtc-plugin.es-ac81d249.js +7651 -0
  33. package/dist/web_player.js +1265 -0
  34. package/karma.conf.cjs +74 -0
  35. package/package.json +68 -0
  36. package/rollup.config.browser.cjs +16 -0
  37. package/rollup.config.module.cjs +42 -0
  38. package/src/index.js +1 -0
  39. package/src/web_player.js +1133 -0
  40. package/test/embedded-player.test.js +864 -0
  41. package/tsconfig.json +24 -0
@@ -0,0 +1,976 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@antmedia/webrtc_adaptor/dist/fetch.stream'), require('@antmedia/webrtc_adaptor/dist/loglevel.min')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@antmedia/webrtc_adaptor/dist/fetch.stream', '@antmedia/webrtc_adaptor/dist/loglevel.min'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.web_player = {}, global.fetch_stream, global.loglevel_min));
5
+ })(this, (function (exports, fetch_stream, loglevel_min) { 'use strict';
6
+
7
+ const STATIC_VIDEO_HTML = "<video id='video-player' class='video-js vjs-default-skin vjs-big-play-centered' controls playsinline></video>";
8
+ class WebPlayer {
9
+ static DEFAULT_PLAY_ORDER = ["webrtc", "hls"];
10
+ static DEFAULT_PLAY_TYPE = ["mp4", "webm"];
11
+ static HLS_EXTENSION = "m3u8";
12
+ static WEBRTC_EXTENSION = "webrtc";
13
+ static DASH_EXTENSION = "mpd";
14
+
15
+ /**
16
+ * streamsFolder: streams folder. Optional. Default value is "streams"
17
+ */
18
+ static STREAMS_FOLDER = "streams";
19
+
20
+ /**
21
+ * Video HTML content. It's by default STATIC_VIDEO_HTML
22
+ */
23
+ videoHTMLContent;
24
+
25
+ /**
26
+ * video player Id. It's by default "video-player"
27
+ */
28
+ videoPlayerId;
29
+
30
+ /**
31
+ * "playOrder": the order which technologies is used in playing. Optional. Default value is "webrtc,hls".
32
+ * possible values are "hls,webrtc","webrtc","hls","vod","dash"
33
+ * It will be taken from url parameter "playOrder".
34
+ */
35
+ playOrder;
36
+
37
+ /**
38
+ * currentPlayType: current play type in playOrder
39
+ */
40
+ currentPlayType;
41
+
42
+ /**
43
+ * "is360": if true, player will be 360 degree player. Optional. Default value is false.
44
+ * It will be taken from url parameter "is360".
45
+ */
46
+ is360 = false;
47
+
48
+ /**
49
+ * "streamId": stream id. Mandatory. If it is not set, it will be taken from url parameter "id".
50
+ * It will be taken from url parameter "id".
51
+ */
52
+ streamId;
53
+
54
+ /**
55
+ * "playType": play type. Optional. It's used for vod. Default value is "mp4,webm".
56
+ * It can be "mp4,webm","webm,mp4","mp4","webm","mov" and it's used for vod.
57
+ * It will be taken from url parameter "playType".
58
+ */
59
+ playType;
60
+
61
+ /**
62
+ * "token": token. It's required when stream security for playback is enabled .
63
+ * It will be taken from url parameter "token".
64
+ */
65
+ token;
66
+
67
+ /**
68
+ * autoplay: if true, player will be started automatically. Optional. Default value is true.
69
+ * autoplay is false by default for mobile devices because of mobile browser's autoplay policy.
70
+ * It will be taken from url parameter "autoplay".
71
+ */
72
+ autoPlay = true;
73
+
74
+ /**
75
+ * mute: if true, player will be started muted. Optional. Default value is true.
76
+ * default value is true because of browser's autoplay policy.
77
+ * It will be taken from url parameter "mute".
78
+ */
79
+ mute = true;
80
+
81
+ /**
82
+ * targetLatency: target latency in seconds. Optional. Default value is 3.
83
+ * It will be taken from url parameter "targetLatency".
84
+ * It's used for dash(cmaf) playback.
85
+ */
86
+ targetLatency = 3;
87
+
88
+ /**
89
+ * subscriberId: subscriber id. Optional. It will be taken from url parameter "subscriberId".
90
+ */
91
+ subscriberId;
92
+
93
+ /**
94
+ * subscriberCode: subscriber code. Optional. It will be taken from url parameter "subscriberCode".
95
+ */
96
+ subscriberCode;
97
+
98
+ /**
99
+ * window: window object
100
+ */
101
+ window;
102
+
103
+ /**
104
+ * video player container element
105
+ */
106
+ containerElement;
107
+
108
+ /**
109
+ * player placeholder element
110
+ */
111
+ placeHolderElement;
112
+
113
+ /**
114
+ * videojs player
115
+ */
116
+ videojsPlayer;
117
+
118
+ /**
119
+ * dash player
120
+ */
121
+ dashPlayer;
122
+
123
+ /**
124
+ * Ice servers for webrtc
125
+ */
126
+ iceServers;
127
+
128
+ /**
129
+ * ice connection state
130
+ */
131
+ iceConnected;
132
+
133
+ /**
134
+ * flag to check if error callback is called
135
+ */
136
+ errorCalled;
137
+
138
+ /**
139
+ * scene for 360 degree player
140
+ */
141
+ aScene;
142
+
143
+ /**
144
+ * player listener
145
+ */
146
+ playerListener;
147
+
148
+ /**
149
+ * webRTCDataListener
150
+ */
151
+ webRTCDataListener;
152
+
153
+ /**
154
+ * Field to keep if tryNextMethod is already called
155
+ */
156
+ tryNextTechTimer;
157
+ constructor(configOrWindow, containerElement, placeHolderElement) {
158
+ WebPlayer.DEFAULT_PLAY_ORDER = ["webrtc", "hls"];
159
+ WebPlayer.DEFAULT_PLAY_TYPE = ["mp4", "webm"];
160
+ WebPlayer.HLS_EXTENSION = "m3u8";
161
+ WebPlayer.WEBRTC_EXTENSION = "webrtc";
162
+ WebPlayer.DASH_EXTENSION = "mpd";
163
+
164
+ /**
165
+ * streamsFolder: streams folder. Optional. Default value is "streams"
166
+ */
167
+ WebPlayer.STREAMS_FOLDER = "streams";
168
+ WebPlayer.VIDEO_PLAYER_ID = "video-player";
169
+
170
+ // Initialize default values
171
+ this.setDefaults();
172
+
173
+ // Check if the first argument is a config object or a Window object
174
+ if (!this.isWindow(configOrWindow)) {
175
+ // New config object mode
176
+ loglevel_min.Logger.info("config object mode");
177
+ Object.assign(this, configOrWindow);
178
+ this.window = window;
179
+ } else {
180
+ // Backward compatibility mode
181
+ loglevel_min.Logger.info("getting from url mode");
182
+ this.window = configOrWindow;
183
+
184
+ // Use getUrlParameter for backward compatibility
185
+ this.initializeFromUrlParams();
186
+ }
187
+ this.containerElement = containerElement;
188
+ this.placeHolderElement = placeHolderElement;
189
+ if (this.streamId == null) {
190
+ var message = "Stream id is not set.Please add your stream id to the url as a query parameter such as ?id={STREAM_ID} to the url";
191
+ loglevel_min.Logger.error(message);
192
+ //TODO: we may need to show this message on directly page
193
+ alert(message);
194
+ throw new Error(message);
195
+ }
196
+ if (!this.httpBaseURL) {
197
+ let appName = this.window.location.pathname.substring(0, this.window.location.pathname.lastIndexOf("/") + 1);
198
+ let path = this.window.location.hostname + ":" + this.window.location.port + appName + this.streamId + ".webrtc";
199
+ this.websocketURL = "ws://" + path;
200
+ if (location.protocol.startsWith("https")) {
201
+ this.websocketURL = "wss://" + path;
202
+ }
203
+ this.httpBaseURL = location.protocol + "//" + this.window.location.hostname + ":" + this.window.location.port + appName;
204
+ } else if (!this.websocketURL) {
205
+ this.websocketURL = this.httpBaseURL.replace("http", "ws");
206
+ if (!this.websocketURL.endsWith("/")) {
207
+ this.websocketURL += "/";
208
+ }
209
+ this.websocketURL += this.streamId + ".webrtc";
210
+ }
211
+ this.dom = this.window.document;
212
+ this.containerElement.innerHTML = this.videoHTMLContent;
213
+ this.setPlayerVisible(false);
214
+ }
215
+ isWindow(configOrWindow) {
216
+ //accept that it's a window if it's a Window instance or it has location.href
217
+ //location.href is used in test environment
218
+ return configOrWindow instanceof Window || configOrWindow.location && configOrWindow.location.href;
219
+ }
220
+ initialize() {
221
+ return this.loadVideoJSComponents().then(() => {
222
+ return this.loadDashScript();
223
+ }).then(() => {
224
+ if (this.is360 && !window.AFRAME) {
225
+ return import('aframe');
226
+ }
227
+ }).catch(e => {
228
+ loglevel_min.Logger.error("Scripts are not loaded. The error is " + e);
229
+ throw e;
230
+ });
231
+ }
232
+ loadDashScript() {
233
+ if (this.playOrder.includes("dash") && !this.dashjsLoaded) {
234
+ return import('dashjs/dist/dash.all.min.js').then(dashjs => {
235
+ window.dashjs = dashjs.default;
236
+ this.dashjsLoaded = true;
237
+ console.log("dash.all.min.js is loaded");
238
+ });
239
+ } else {
240
+ return Promise.resolve();
241
+ }
242
+ }
243
+ setDefaults() {
244
+ this.playOrder = WebPlayer.DEFAULT_PLAY_ORDER;
245
+ this.currentPlayType = null;
246
+ this.is360 = false;
247
+ this.streamId = null;
248
+ this.playType = WebPlayer.DEFAULT_PLAY_TYPE;
249
+ this.token = null;
250
+ this.autoPlay = true;
251
+ this.mute = true;
252
+ this.targetLatency = 3;
253
+ this.subscriberId = null;
254
+ this.subscriberCode = null;
255
+ this.window = null;
256
+ this.containerElement = null;
257
+ this.placeHolderElement = null;
258
+ this.videojsPlayer = null;
259
+ this.dashPlayer = null;
260
+ this.iceServers = '[ { "urls": "stun:stun1.l.google.com:19302" } ]';
261
+ this.iceConnected = false;
262
+ this.errorCalled = false;
263
+ this.tryNextTechTimer = -1;
264
+ this.aScene = null;
265
+ this.playerListener = null;
266
+ this.webRTCDataListener = null;
267
+ this.websocketURL = null;
268
+ this.httpBaseURL = null;
269
+ this.videoHTMLContent = STATIC_VIDEO_HTML;
270
+ this.videoPlayerId = "video-player";
271
+ this.videojsLoaded = false;
272
+ this.dashjsLoaded = false;
273
+ }
274
+ initializeFromUrlParams() {
275
+ // Fetch parameters from URL and set to class properties
276
+ this.streamId = fetch_stream.getUrlParameter("id", this.window.location.search) || this.streamId;
277
+ if (this.streamId == null) {
278
+ //check name variable for compatibility with older versions
279
+
280
+ this.streamId = fetch_stream.getUrlParameter("name", this.window.location.search) || this.streamId;
281
+ if (this.streamId == null) {
282
+ loglevel_min.Logger.warn("Please use id parameter instead of name parameter.");
283
+ }
284
+ }
285
+ this.is360 = fetch_stream.getUrlParameter("is360", this.window.location.search) === "true" || this.is360;
286
+ this.playType = fetch_stream.getUrlParameter("playType", this.window.location.search)?.split(',') || this.playType;
287
+ this.token = fetch_stream.getUrlParameter("token", this.window.location.search) || this.token;
288
+ let autoPlayLocal = fetch_stream.getUrlParameter("autoplay", this.window.location.search);
289
+ if (autoPlayLocal === "false") {
290
+ this.autoPlay = false;
291
+ } else {
292
+ this.autoPlay = true;
293
+ }
294
+ let muteLocal = fetch_stream.getUrlParameter("mute", this.window.location.search);
295
+ if (muteLocal === "false") {
296
+ this.mute = false;
297
+ } else {
298
+ this.mute = true;
299
+ }
300
+ let localTargetLatency = fetch_stream.getUrlParameter("targetLatency", this.window.location.search);
301
+ if (localTargetLatency != null) {
302
+ let latencyInNumber = Number(localTargetLatency);
303
+ if (!isNaN(latencyInNumber)) {
304
+ this.targetLatency = latencyInNumber;
305
+ } else {
306
+ loglevel_min.Logger.warn("targetLatency parameter is not a number. It will be ignored.");
307
+ this.targetLatency = this.targetLatency || 3; // Default value or existing value
308
+ }
309
+ }
310
+ this.subscriberId = fetch_stream.getUrlParameter("subscriberId", this.window.location.search) || this.subscriberId;
311
+ this.subscriberCode = fetch_stream.getUrlParameter("subscriberCode", this.window.location.search) || this.subscriberCode;
312
+ let playOrder = fetch_stream.getUrlParameter("playOrder", this.window.location.search);
313
+ this.playOrder = playOrder ? playOrder.split(',') : this.playOrder;
314
+ }
315
+ loadWebRTCComponents() {
316
+ if (this.playOrder.includes("webrtc")) {
317
+ return import('@antmedia/videojs-webrtc-plugin/dist/videojs-webrtc-plugin.css').then(css => {
318
+ loglevel_min.Logger.info("videojs-webrtc-plugin.css is loaded");
319
+ const styleElement = this.dom.createElement('style');
320
+ styleElement.textContent = css.default.toString(); // Assuming css module exports a string
321
+ this.dom.head.appendChild(styleElement);
322
+ return import('@antmedia/videojs-webrtc-plugin').then(videojsWebrtcPluginLocal => {
323
+ loglevel_min.Logger.info("videojs-webrtc-plugin is loaded");
324
+ });
325
+ });
326
+ } else {
327
+ return Promise.resolve();
328
+ }
329
+ }
330
+ /**
331
+ * load scripts dynamically
332
+ */
333
+ loadVideoJSComponents() {
334
+ if (this.playOrder.includes("hls") || this.playOrder.includes("vod") || this.playOrder.includes("webrtc")) {
335
+ //it means we're going to use videojs
336
+ //load videojs css
337
+ if (!this.videojsLoaded) {
338
+ return import('video.js/dist/video-js.min.css').then(css => {
339
+ const styleElement = this.dom.createElement('style');
340
+ styleElement.textContent = css.default.toString(); // Assuming css module exports a string
341
+ this.dom.head.appendChild(styleElement);
342
+ }).then(() => {
343
+ return import('video.js');
344
+ }).then(videojs => {
345
+ window.videojs = videojs.default;
346
+ this.videojsLoaded = true;
347
+ }).then(() => {
348
+ return import('videojs-contrib-quality-levels');
349
+ }).then(() => {
350
+ return import('videojs-hls-quality-selector');
351
+ }).then(() => {
352
+ return this.loadWebRTCComponents();
353
+ });
354
+ } else {
355
+ return Promise.resolve();
356
+ }
357
+ } else {
358
+ return Promise.resolve();
359
+ }
360
+ }
361
+
362
+ /**
363
+ * enable 360 player
364
+ */
365
+ enable360Player() {
366
+ this.aScene = this.dom.createElement("a-scene");
367
+ var elementId = this.dom.getElementsByTagName("video")[0].id;
368
+ this.aScene.innerHTML = "<a-videosphere src=\"#" + elementId + "\" rotation=\"0 180 0\" style=\"background-color: antiquewhite\"></a-videosphere>";
369
+ this.dom.body.appendChild(this.aScene);
370
+ }
371
+
372
+ /**
373
+ * set player visibility
374
+ * @param {boolean} visible
375
+ */
376
+ setPlayerVisible(visible) {
377
+ this.containerElement.style.display = visible ? "block" : "none";
378
+ if (this.placeHolderElement) {
379
+ this.placeHolderElement.style.display = visible ? "none" : "block";
380
+ }
381
+ if (this.is360) {
382
+ if (visible) {
383
+ this.enable360Player();
384
+ } else if (this.aScene != null) {
385
+ var elements = this.dom.getElementsByTagName("a-scene");
386
+ while (elements.length > 0) {
387
+ this.dom.body.removeChild(elements[0]);
388
+ elements = this.dom.getElementsByTagName("a-scene");
389
+ }
390
+ this.aScene = null;
391
+ }
392
+ }
393
+ }
394
+ handleWebRTCInfoMessages(infos) {
395
+ if (infos["info"] == "ice_connection_state_changed") {
396
+ loglevel_min.Logger.debug("ice connection state changed to " + infos["obj"].state);
397
+ if (infos["obj"].state == "completed" || infos["obj"].state == "connected") {
398
+ this.iceConnected = true;
399
+ } else if (infos["obj"].state == "failed" || infos["obj"].state == "disconnected" || infos["obj"].state == "closed") {
400
+ //
401
+ loglevel_min.Logger.warn("Ice connection is not connected. tryNextTech to replay");
402
+ this.tryNextTech();
403
+ }
404
+ } else if (infos["info"] == "closed") {
405
+ //this means websocket is closed and it stops the playback - tryNextTech
406
+ loglevel_min.Logger.warn("Websocket is closed. tryNextTech to replay");
407
+ this.tryNextTech();
408
+ } else if (infos["info"] == "resolutionChangeInfo") {
409
+ loglevel_min.Logger.info("Resolution is changing");
410
+ this.videojsPlayer.pause();
411
+ setTimeout(() => {
412
+ this.videojsPlayer.play();
413
+ }, 1000);
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Play the stream via videojs
419
+ * @param {*} streamUrl
420
+ * @param {*} extension
421
+ * @returns
422
+ */
423
+ playWithVideoJS(streamUrl, extension) {
424
+ var type;
425
+ if (extension == "mp4") {
426
+ type = "video/mp4";
427
+ } else if (extension == "webm") {
428
+ type = "video/webm";
429
+ } else if (extension == "mov") {
430
+ type = "video/mp4";
431
+ alert("Browsers do not support to play mov format");
432
+ } else if (extension == "avi") {
433
+ type = "video/mp4";
434
+ alert("Browsers do not support to play avi format");
435
+ } else if (extension == "m3u8") {
436
+ type = "application/x-mpegURL";
437
+ } else if (extension == "mpd") {
438
+ type = "application/dash+xml";
439
+ } else if (extension == "webrtc") {
440
+ type = "video/webrtc";
441
+ } else {
442
+ loglevel_min.Logger.warn("Unknown extension: " + extension);
443
+ return;
444
+ }
445
+ var preview = this.streamId;
446
+ if (this.streamId.endsWith("_adaptive")) {
447
+ preview = streamId.substring(0, streamId.indexOf("_adaptive"));
448
+ }
449
+
450
+ //same videojs is being use for hls, vod and webrtc streams
451
+ this.videojsPlayer = videojs(this.videoPlayerId, {
452
+ poster: "previews/" + preview + ".png",
453
+ liveui: extension == "m3u8" ? true : false,
454
+ liveTracker: {
455
+ trackingThreshold: 0
456
+ },
457
+ html5: {
458
+ vhs: {
459
+ limitRenditionByPlayerDimensions: false
460
+ }
461
+ },
462
+ controls: true,
463
+ class: 'video-js vjs-default-skin vjs-big-play-centered',
464
+ muted: this.mute,
465
+ preload: "auto",
466
+ autoplay: this.autoPlay
467
+ });
468
+ this.videojsPlayer.on('error', e => {
469
+ loglevel_min.Logger.warn("There is an error in playback: " + e);
470
+ // We need to add this kind of check. If we don't add this kind of checkpoint, it will create an infinite loop
471
+ if (!this.errorCalled) {
472
+ this.errorCalled = true;
473
+ setTimeout(() => {
474
+ this.tryNextTech();
475
+ this.errorCalled = false;
476
+ }, 2500);
477
+ }
478
+ });
479
+
480
+ //webrtc specific events
481
+ if (extension == "webrtc") {
482
+ this.videojsPlayer.on('webrtc-info', (event, infos) => {
483
+ //Logger.warn("info callback: " + JSON.stringify(infos));
484
+ this.handleWebRTCInfoMessages(infos);
485
+ });
486
+ this.videojsPlayer.on('webrtc-error', (event, errors) => {
487
+ //some of the possible errors, NotFoundError, SecurityError,PermissionDeniedError
488
+ loglevel_min.Logger.warn("error callback: " + JSON.stringify(errors));
489
+ if (errors["error"] == "no_stream_exist" || errors["error"] == "WebSocketNotConnected" || errors["error"] == "not_initialized_yet" || errors["error"] == "data_store_not_available" || errors["error"] == "highResourceUsage" || errors["error"] == "unauthorized_access" || errors["error"] == "user_blocked") {
490
+ //handle high resource usage and not authroized errors && websocket disconnected
491
+ //Even if webrtc adaptor has auto reconnect scenario, we dispose the videojs immediately in tryNextTech
492
+ // so that reconnect scenario is managed here
493
+
494
+ this.tryNextTech();
495
+ } else if (errors["error"] == "notSetRemoteDescription") {
496
+ /*
497
+ * If getting codec incompatible or remote description error, it will redirect HLS player.
498
+ */
499
+ loglevel_min.Logger.warn("notSetRemoteDescription error. Redirecting to HLS player.");
500
+ this.playIfExists("hls");
501
+ }
502
+ });
503
+ this.videojsPlayer.on("webrtc-data-received", (event, obj) => {
504
+ loglevel_min.Logger.warn("webrtc-data-received: " + JSON.stringify(obj));
505
+ if (this.webRTCDataListener != null) {
506
+ this.webRTCDataListener(obj);
507
+ }
508
+ });
509
+ }
510
+
511
+ //hls specific calls
512
+ if (extension == "m3u8") {
513
+ videojs.Vhs.xhr.beforeRequest = options => {
514
+ let securityParams = this.getSecurityQueryParams();
515
+ if (!options.uri.includes(securityParams)) {
516
+ if (!options.uri.endsWith("?")) {
517
+ options.uri = options.uri + "?";
518
+ }
519
+ options.uri += securityParams;
520
+ }
521
+ loglevel_min.Logger.debug("hls request: " + options.uri);
522
+ return options;
523
+ };
524
+ this.videojsPlayer.ready(() => {
525
+ // If it's already added to player, no need to add again
526
+ if (typeof this.videojsPlayer.hlsQualitySelector === "function") {
527
+ this.videojsPlayer.hlsQualitySelector({
528
+ displayCurrentQuality: true
529
+ });
530
+ }
531
+
532
+ // If there is no adaptive option in m3u8 no need to show quality selector
533
+ let qualityLevels = this.videojsPlayer.qualityLevels();
534
+ qualityLevels.on('addqualitylevel', function (event) {
535
+ let qualityLevel = event.qualityLevel;
536
+ if (qualityLevel.height) {
537
+ qualityLevel.enabled = true;
538
+ } else {
539
+ qualityLevels.removeQualityLevel(qualityLevel);
540
+ qualityLevel.enabled = false;
541
+ }
542
+ });
543
+ });
544
+ }
545
+
546
+ //videojs is being used to play mp4, webm, m3u8 and webrtc
547
+ //make the videoJS visible when ready is called except for webrtc
548
+ //webrtc fires ready event all cases so we use "play" event to make the player visible
549
+
550
+ //this setting is critical to play in mobile
551
+ if (extension == "mp4" || extension == "webm" || extension == "m3u8") {
552
+ this.makeVideoJSVisibleWhenReady();
553
+ }
554
+ this.videojsPlayer.on('ended', () => {
555
+ //reinit to play after it ends
556
+ loglevel_min.Logger.warn("stream is ended");
557
+ this.setPlayerVisible(false);
558
+ //for webrtc, this event can be called by two reasons
559
+ //1. ice connection is not established, it means that there is a networking issug
560
+ //2. stream is ended
561
+ if (this.currentPlayType != "vod") {
562
+ //if it's vod, it means that stream is ended and no need to replay
563
+
564
+ if (this.iceConnected) {
565
+ //if iceConnected is true, it means that stream is really ended for webrtc
566
+
567
+ //initialize to play again if the publishing starts again
568
+ this.playIfExists(this.playOrder[0]);
569
+ } else if (this.currentPlayType == "hls") {
570
+ //if it's hls, it means that stream is ended
571
+
572
+ this.setPlayerVisible(false);
573
+ if (this.playOrder[0] = "hls") {
574
+ //do not play again if it's hls because it play last seconds again, let the server clear it
575
+ setTimeout(() => {
576
+ this.playIfExists(this.playOrder[0]);
577
+ }, 10000);
578
+ } else {
579
+ this.playIfExists(this.playOrder[0]);
580
+ }
581
+ //TODO: what if the stream is hls vod then it always re-play
582
+ } else {
583
+ //if iceConnected is false, it means that there is a networking issue for webrtc
584
+ this.tryNextTech();
585
+ }
586
+ }
587
+ if (this.playerListener != null) {
588
+ this.playerListener("ended");
589
+ }
590
+ });
591
+
592
+ //webrtc plugin sends play event. On the other hand, webrtc plugin sends ready event for every scenario.
593
+ //so no need to trust ready event for webrt play
594
+ this.videojsPlayer.on("play", () => {
595
+ this.setPlayerVisible(true);
596
+ if (this.playerListener != null) {
597
+ this.playerListener("play");
598
+ }
599
+ });
600
+ this.iceConnected = false;
601
+ this.videojsPlayer.src({
602
+ src: streamUrl,
603
+ type: type,
604
+ withCredentials: true,
605
+ iceServers: this.iceServers,
606
+ reconnect: false //webrtc adaptor has auto reconnect scenario, just disable it, we manage it here
607
+ });
608
+ if (this.autoPlay) {
609
+ this.videojsPlayer.play().catch(e => {
610
+ loglevel_min.Logger.warn("Problem in playback. The error is " + e);
611
+ });
612
+ }
613
+ }
614
+ makeVideoJSVisibleWhenReady() {
615
+ this.videojsPlayer.ready(() => {
616
+ this.setPlayerVisible(true);
617
+ });
618
+ }
619
+
620
+ /**
621
+ * check if stream exists via http
622
+ * @param {*} streamsfolder
623
+ * @param {*} streamId
624
+ * @param {*} extension
625
+ * @returns
626
+ */
627
+ checkStreamExistsViaHttp(streamsfolder, streamId, extension) {
628
+ var streamPath = this.httpBaseURL;
629
+ if (!streamId.startsWith(streamsfolder)) {
630
+ streamPath += streamsfolder + "/";
631
+ }
632
+ streamPath += streamId;
633
+ if (extension != null && extension != "") {
634
+ //if there is extension, add it and try if _adaptive exists
635
+ streamPath += "_adaptive" + "." + extension;
636
+ }
637
+ streamPath = this.addSecurityParams(streamPath);
638
+ return fetch(streamPath, {
639
+ method: 'HEAD'
640
+ }).then(response => {
641
+ if (response.status == 200) {
642
+ // adaptive m3u8 & mpd exists,play it
643
+ return new Promise(function (resolve, reject) {
644
+ resolve(streamPath);
645
+ });
646
+ } else {
647
+ //adaptive not exists, try mpd or m3u8 exists.
648
+ streamPath = this.httpBaseURL + streamsfolder + "/" + streamId + "." + extension;
649
+ streamPath = this.addSecurityParams(streamPath);
650
+ return fetch(streamPath, {
651
+ method: 'HEAD'
652
+ }).then(response => {
653
+ if (response.status == 200) {
654
+ return new Promise(function (resolve, reject) {
655
+ resolve(streamPath);
656
+ });
657
+ } else {
658
+ loglevel_min.Logger.warn("No stream found");
659
+ return new Promise(function (resolve, reject) {
660
+ reject("resource_is_not_available");
661
+ });
662
+ }
663
+ });
664
+ }
665
+ });
666
+ }
667
+ addSecurityParams(streamPath) {
668
+ var securityParams = this.getSecurityQueryParams();
669
+ if (securityParams != null && securityParams != "") {
670
+ streamPath += "?" + securityParams;
671
+ }
672
+ return streamPath;
673
+ }
674
+
675
+ /**
676
+ * try next tech if current tech is not working
677
+ */
678
+ tryNextTech() {
679
+ if (this.tryNextTechTimer == -1) {
680
+ this.destroyDashPlayer();
681
+ this.destroyVideoJSPlayer();
682
+ this.setPlayerVisible(false);
683
+ var index = this.playOrder.indexOf(this.currentPlayType);
684
+ if (index == -1 || index == this.playOrder.length - 1) {
685
+ index = 0;
686
+ } else {
687
+ index++;
688
+ }
689
+ this.tryNextTechTimer = setTimeout(() => {
690
+ this.tryNextTechTimer = -1;
691
+ this.playIfExists(this.playOrder[index]);
692
+ }, 3000);
693
+ } else {
694
+ loglevel_min.Logger.debug("tryNextTech is already scheduled no need to schedule again");
695
+ }
696
+ }
697
+
698
+ /**
699
+ * play stream throgugh dash player
700
+ * @param {string"} streamUrl
701
+ */
702
+ playViaDash(streamUrl) {
703
+ this.destroyDashPlayer();
704
+ this.dashPlayer = dashjs.MediaPlayer().create();
705
+ this.dashPlayer.extend("RequestModifier", () => {
706
+ return {
707
+ modifyRequestHeader: function (xhr, {
708
+ url
709
+ }) {
710
+ return xhr;
711
+ },
712
+ modifyRequestURL: url => {
713
+ var modifiedUrl = "";
714
+ var securityParams = this.getSecurityQueryParams();
715
+ if (!url.includes(securityParams)) {
716
+ if (!url.endsWith("?")) {
717
+ url += "?";
718
+ }
719
+ modifiedUrl = url + securityParams;
720
+ loglevel_min.Logger.warn(modifiedUrl);
721
+ return modifiedUrl;
722
+ }
723
+ return url;
724
+ },
725
+ modifyRequest(request) {}
726
+ };
727
+ });
728
+ this.dashPlayer.updateSettings({
729
+ streaming: {
730
+ delay: {
731
+ liveDelay: this.targetLatency
732
+ },
733
+ liveCatchup: {
734
+ maxDrift: 0.5,
735
+ playbackRate: 0.5,
736
+ latencyThreshold: 60
737
+ }
738
+ }
739
+ });
740
+ this.dashPlayer.initialize(this.containerElement.firstChild, streamUrl, this.autoPlay);
741
+ this.dashPlayer.setMute(this.mute);
742
+ this.dashLatencyTimer = setInterval(() => {
743
+ loglevel_min.Logger.warn("live latency: " + this.dashPlayer.getCurrentLiveLatency());
744
+ }, 2000);
745
+ this.makeDashPlayerVisibleWhenInitialized();
746
+ this.dashPlayer.on(dashjs.MediaPlayer.events.PLAYBACK_PLAYING, event => {
747
+ loglevel_min.Logger.warn("playback started");
748
+ this.setPlayerVisible(true);
749
+ if (this.playerListener != null) {
750
+ this.playerListener("play");
751
+ }
752
+ });
753
+ this.dashPlayer.on(dashjs.MediaPlayer.events.PLAYBACK_ENDED, () => {
754
+ loglevel_min.Logger.warn("playback ended");
755
+ this.destroyDashPlayer();
756
+ this.setPlayerVisible(false);
757
+ //streaming can be started again so try to play again with preferred tech
758
+ if (this.playOrder[0] = "dash") {
759
+ //do not play again if it's dash because it play last seconds again, let the server clear it
760
+ setTimeout(() => {
761
+ this.playIfExists(this.playOrder[0]);
762
+ }, 10000);
763
+ } else {
764
+ this.playIfExists(this.playOrder[0]);
765
+ }
766
+ if (this.playerListener != null) {
767
+ this.playerListener("ended");
768
+ }
769
+ });
770
+ this.dashPlayer.on(dashjs.MediaPlayer.events.PLAYBACK_ERROR, event => {
771
+ this.tryNextTech();
772
+ });
773
+ this.dashPlayer.on(dashjs.MediaPlayer.events.ERROR, event => {
774
+ this.tryNextTech();
775
+ });
776
+ }
777
+ makeDashPlayerVisibleWhenInitialized() {
778
+ this.dashPlayer.on(dashjs.MediaPlayer.events.STREAM_INITIALIZED, event => {
779
+ loglevel_min.Logger.warn("Stream initialized");
780
+ //make the player visible in mobile devices
781
+ this.setPlayerVisible(true);
782
+ });
783
+ }
784
+
785
+ /**
786
+ * destroy the dash player
787
+ */
788
+ destroyDashPlayer() {
789
+ if (this.dashPlayer) {
790
+ this.dashPlayer.destroy();
791
+ this.dashPlayer = null;
792
+ clearInterval(this.dashLatencyTimer);
793
+ }
794
+ }
795
+
796
+ /**
797
+ * destroy the videojs player
798
+ */
799
+ destroyVideoJSPlayer() {
800
+ if (this.videojsPlayer) {
801
+ this.videojsPlayer.dispose();
802
+ this.videojsPlayer = null;
803
+ }
804
+ }
805
+
806
+ /**
807
+ * Destory the player
808
+ */
809
+ destroy() {
810
+ this.destroyVideoJSPlayer();
811
+ this.destroyDashPlayer();
812
+ }
813
+
814
+ /**
815
+ * play the stream with the given tech
816
+ * @param {string} tech
817
+ */
818
+ async playIfExists(tech) {
819
+ this.currentPlayType = tech;
820
+ this.destroyVideoJSPlayer();
821
+ this.destroyDashPlayer();
822
+ this.setPlayerVisible(false);
823
+ this.containerElement.innerHTML = this.videoHTMLContent;
824
+ loglevel_min.Logger.warn("Try to play the stream " + this.streamId + " with " + this.currentPlayType);
825
+ switch (this.currentPlayType) {
826
+ case "hls":
827
+ //TODO: Test case for hls
828
+ //1. Play stream with adaptive m3u8 for live and VoD
829
+ //2. Play stream with m3u8 for live and VoD
830
+ //3. if files are not available check nextTech is being called
831
+ return this.checkStreamExistsViaHttp(WebPlayer.STREAMS_FOLDER, this.streamId, WebPlayer.HLS_EXTENSION).then(streamPath => {
832
+ this.playWithVideoJS(streamPath, WebPlayer.HLS_EXTENSION);
833
+ loglevel_min.Logger.warn("incoming stream path: " + streamPath);
834
+ }).catch(error => {
835
+ loglevel_min.Logger.warn("HLS stream resource not available for stream:" + this.streamId + " error is " + error + ". Try next play tech");
836
+ this.tryNextTech();
837
+ });
838
+ case "dash":
839
+ return this.checkStreamExistsViaHttp(WebPlayer.STREAMS_FOLDER, this.streamId + "/" + this.streamId, WebPlayer.DASH_EXTENSION).then(streamPath => {
840
+ this.playViaDash(streamPath);
841
+ }).catch(error => {
842
+ loglevel_min.Logger.warn("DASH stream resource not available for stream:" + this.streamId + " error is " + error + ". Try next play tech");
843
+ this.tryNextTech();
844
+ });
845
+ case "webrtc":
846
+ return this.playWithVideoJS(this.addSecurityParams(this.websocketURL), WebPlayer.WEBRTC_EXTENSION);
847
+ case "vod":
848
+ //TODO: Test case for vod
849
+ //1. Play stream with mp4 for VoD
850
+ //2. Play stream with webm for VoD
851
+ //3. Play stream with playOrder type
852
+
853
+ var lastIndexOfDot = this.streamId.lastIndexOf(".");
854
+ var extension;
855
+ if (lastIndexOfDot != -1) {
856
+ //if there is a dot in the streamId, it means that this is extension, use it. make the extension empty
857
+ this.playType[0] = "";
858
+ extension = this.streamId.substring(lastIndexOfDot + 1);
859
+ } else {
860
+ //we need to give extension to playWithVideoJS
861
+ extension = this.playType[0];
862
+ }
863
+ return this.checkStreamExistsViaHttp(WebPlayer.STREAMS_FOLDER, this.streamId, this.playType[0]).then(streamPath => {
864
+ //we need to give extension to playWithVideoJS
865
+ this.playWithVideoJS(streamPath, extension);
866
+ }).catch(error => {
867
+ loglevel_min.Logger.warn("VOD stream resource not available for stream:" + this.streamId + " and play type " + this.playType[0] + ". Error is " + error);
868
+ if (this.playType.length > 1) {
869
+ loglevel_min.Logger.warn("Try next play type which is " + this.playType[1] + ".");
870
+ this.checkStreamExistsViaHttp(WebPlayer.STREAMS_FOLDER, this.streamId, this.playType[1]).then(streamPath => {
871
+ this.playWithVideoJS(streamPath, this.playType[1]);
872
+ }).catch(error => {
873
+ loglevel_min.Logger.warn("VOD stream resource not available for stream:" + this.streamId + " and play type error is " + error);
874
+ });
875
+ }
876
+ });
877
+ }
878
+ }
879
+
880
+ /**
881
+ *
882
+ * @returns {String} query string for security
883
+ */
884
+ getSecurityQueryParams() {
885
+ var queryString = "";
886
+ if (this.token != null) {
887
+ queryString += "&token=" + this.token;
888
+ }
889
+ if (this.subscriberId != null) {
890
+ queryString += "&subscriberId=" + this.subscriberId;
891
+ }
892
+ if (this.subscriberCode != null) {
893
+ queryString += "&subscriberCode=" + this.subscriberCode;
894
+ }
895
+ return queryString;
896
+ }
897
+
898
+ /**
899
+ * play the stream with videojs player or dash player
900
+ */
901
+ play() {
902
+ if (this.streamId.startsWith(WebPlayer.STREAMS_FOLDER)) {
903
+ //start videojs player because it directly try to play stream from streams folder
904
+ var lastIndexOfDot = this.streamId.lastIndexOf(".");
905
+ var extension = this.streamId.substring(lastIndexOfDot + 1);
906
+ this.playOrder = ["vod"];
907
+ if (!this.httpBaseURL.endsWith("/")) {
908
+ this.httpBaseURL += "/";
909
+ }
910
+ this.containerElement.innerHTML = this.videoHTMLContent;
911
+ if (extension == WebPlayer.DASH_EXTENSION) {
912
+ this.playViaDash(this.httpBaseURL + this.addSecurityParams(this.streamId), extension);
913
+ } else {
914
+ this.playWithVideoJS(this.httpBaseURL + this.addSecurityParams(this.streamId), extension);
915
+ }
916
+ } else {
917
+ this.playIfExists(this.playOrder[0]);
918
+ }
919
+ }
920
+
921
+ /**
922
+ * mute or unmute the player
923
+ * @param {boolean} mutestatus true to mute the player
924
+ */
925
+ mutePlayer(mutestatus) {
926
+ this.mute = mutestatus;
927
+ if (this.videojsPlayer) {
928
+ this.videojsPlayer.muted(mutestatus);
929
+ }
930
+ if (this.dashPlayer) {
931
+ this.dashPlayer.setMute(mutestatus);
932
+ }
933
+ }
934
+
935
+ /**
936
+ *
937
+ * @returns {boolean} true if player is muted
938
+ */
939
+ isMuted() {
940
+ return this.mute;
941
+ }
942
+ addPlayerListener(playerListener) {
943
+ this.playerListener = playerListener;
944
+ }
945
+
946
+ /**
947
+ * WebRTC data listener
948
+ * @param {*} webRTCDataListener
949
+ */
950
+ addWebRTCDataListener(webRTCDataListener) {
951
+ this.webRTCDataListener = webRTCDataListener;
952
+ }
953
+
954
+ /**
955
+ *
956
+ * @param {*} data
957
+ */
958
+ sendWebRTCData(data) {
959
+ try {
960
+ if (this.videojsPlayer && this.currentPlayType == "webrtc") {
961
+ this.videojsPlayer.sendDataViaWebRTC(data);
962
+ return true;
963
+ } else {
964
+ loglevel_min.Logger.warn("Player is not ready or playType is not WebRTC");
965
+ }
966
+ } catch (error) {
967
+ // Handle the error here
968
+ loglevel_min.Logger.error("An error occurred while sending WebRTC data: ", error);
969
+ }
970
+ return false;
971
+ }
972
+ }
973
+
974
+ exports.WebPlayer = WebPlayer;
975
+
976
+ }));