@gcorevideo/player 0.0.1

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 (192) hide show
  1. package/assets/icons/new/arrow-left.svg +5 -0
  2. package/assets/icons/new/arrow-right.svg +5 -0
  3. package/assets/icons/new/check.svg +5 -0
  4. package/assets/icons/new/close.svg +12 -0
  5. package/assets/icons/new/full.svg +8 -0
  6. package/assets/icons/new/fullscreen-off.svg +14 -0
  7. package/assets/icons/new/fullscreen-on.svg +14 -0
  8. package/assets/icons/new/gear-hd.svg +16 -0
  9. package/assets/icons/new/gear.svg +12 -0
  10. package/assets/icons/new/hd.svg +8 -0
  11. package/assets/icons/new/pause.svg +5 -0
  12. package/assets/icons/new/pip.svg +5 -0
  13. package/assets/icons/new/play.svg +10 -0
  14. package/assets/icons/new/replayleft.svg +5 -0
  15. package/assets/icons/new/replayright.svg +5 -0
  16. package/assets/icons/new/speed.svg +5 -0
  17. package/assets/icons/new/stats.svg +3 -0
  18. package/assets/icons/new/stop.svg +3 -0
  19. package/assets/icons/new/subtitles-off.svg +5 -0
  20. package/assets/icons/new/subtitles-on.svg +6 -0
  21. package/assets/icons/new/volume-max.svg +5 -0
  22. package/assets/icons/new/volume-min.svg +5 -0
  23. package/assets/icons/new/volume-off.svg +5 -0
  24. package/assets/icons/old/cardboard.svg +4 -0
  25. package/assets/icons/old/close-share.svg +13 -0
  26. package/assets/icons/old/close.svg +13 -0
  27. package/assets/icons/old/fb.svg +13 -0
  28. package/assets/icons/old/fullscreen.svg +12 -0
  29. package/assets/icons/old/language.svg +1 -0
  30. package/assets/icons/old/pause.svg +12 -0
  31. package/assets/icons/old/play.svg +12 -0
  32. package/assets/icons/old/quality-arrow.svg +13 -0
  33. package/assets/icons/old/reload.svg +4 -0
  34. package/assets/icons/old/share.svg +13 -0
  35. package/assets/icons/old/sound-off.svg +15 -0
  36. package/assets/icons/old/sound-on.svg +15 -0
  37. package/assets/icons/old/streams.svg +3 -0
  38. package/assets/icons/old/twitter.svg +13 -0
  39. package/assets/icons/old/wn.svg +15 -0
  40. package/assets/icons/standard/01-play.svg +3 -0
  41. package/assets/icons/standard/02-pause.svg +3 -0
  42. package/assets/icons/standard/03-stop.svg +3 -0
  43. package/assets/icons/standard/04-volume.svg +3 -0
  44. package/assets/icons/standard/05-mute.svg +3 -0
  45. package/assets/icons/standard/06-expand.svg +3 -0
  46. package/assets/icons/standard/07-shrink.svg +3 -0
  47. package/assets/icons/standard/08-hd.svg +3 -0
  48. package/assets/icons/standard/09-cc.svg +8 -0
  49. package/assets/icons/standard/10-reload.svg +4 -0
  50. package/assets/style/main.scss +50 -0
  51. package/assets/style/theme.scss +42 -0
  52. package/assets/style/variables.scss +7 -0
  53. package/dist/DashPlayback-6wKK0_pL.js +666 -0
  54. package/dist/DashPlayback-8U6_s4Jc.js +666 -0
  55. package/dist/DashPlayback-BeZz7mN9.js +663 -0
  56. package/dist/DashPlayback-CRdja67F.js +667 -0
  57. package/dist/DashPlayback-D0df6zGg.js +663 -0
  58. package/dist/DashPlayback-D7egS-CZ.js +664 -0
  59. package/dist/DashPlayback-DH5lZMRR.js +663 -0
  60. package/dist/DashPlayback-DZfIc9sK.js +665 -0
  61. package/dist/DashPlayback-VhCxbQhn.js +666 -0
  62. package/dist/HlsPlayback-Avwy8-0O.js +749 -0
  63. package/dist/index.css +125 -0
  64. package/dist/index.js +467 -0
  65. package/lib/Player.d.ts +50 -0
  66. package/lib/Player.d.ts.map +1 -0
  67. package/lib/Player.js +310 -0
  68. package/lib/backend.d.ts +3 -0
  69. package/lib/backend.d.ts.map +1 -0
  70. package/lib/backend.js +10 -0
  71. package/lib/constants.d.ts +19 -0
  72. package/lib/constants.d.ts.map +1 -0
  73. package/lib/constants.js +18 -0
  74. package/lib/index.d.ts +10 -0
  75. package/lib/index.d.ts.map +1 -0
  76. package/lib/index.js +9 -0
  77. package/lib/internal.types.d.ts +105 -0
  78. package/lib/internal.types.d.ts.map +1 -0
  79. package/lib/internal.types.js +1 -0
  80. package/lib/playback.types.d.ts +13 -0
  81. package/lib/playback.types.d.ts.map +1 -0
  82. package/lib/playback.types.js +1 -0
  83. package/lib/plugins/audio-selector/AudioSelector.d.ts +48 -0
  84. package/lib/plugins/audio-selector/AudioSelector.d.ts.map +1 -0
  85. package/lib/plugins/audio-selector/AudioSelector.js +282 -0
  86. package/lib/plugins/big-mute-button/BigMuteButton.d.ts +33 -0
  87. package/lib/plugins/big-mute-button/BigMuteButton.d.ts.map +1 -0
  88. package/lib/plugins/big-mute-button/BigMuteButton.js +148 -0
  89. package/lib/plugins/bottom-gear/BottomGear.d.ts +30 -0
  90. package/lib/plugins/bottom-gear/BottomGear.d.ts.map +1 -0
  91. package/lib/plugins/bottom-gear/BottomGear.js +103 -0
  92. package/lib/plugins/click-to-pause/ClickToPause.d.ts +16 -0
  93. package/lib/plugins/click-to-pause/ClickToPause.d.ts.map +1 -0
  94. package/lib/plugins/click-to-pause/ClickToPause.js +73 -0
  95. package/lib/plugins/dash-playback/DashPlayback.d.ts +81 -0
  96. package/lib/plugins/dash-playback/DashPlayback.d.ts.map +1 -0
  97. package/lib/plugins/dash-playback/DashPlayback.js +658 -0
  98. package/lib/plugins/dash-plugin/DashPlayback.d.ts +86 -0
  99. package/lib/plugins/dash-plugin/DashPlayback.d.ts.map +1 -0
  100. package/lib/plugins/dash-plugin/DashPlayback.js +659 -0
  101. package/lib/plugins/disable-controls/DisableControls.d.ts +15 -0
  102. package/lib/plugins/disable-controls/DisableControls.d.ts.map +1 -0
  103. package/lib/plugins/disable-controls/DisableControls.js +69 -0
  104. package/lib/plugins/dvr-controls/DVRControls.d.ts +27 -0
  105. package/lib/plugins/dvr-controls/DVRControls.d.ts.map +1 -0
  106. package/lib/plugins/dvr-controls/DVRControls.js +110 -0
  107. package/lib/plugins/hls-playback/HlsPlayback.d.ts +102 -0
  108. package/lib/plugins/hls-playback/HlsPlayback.d.ts.map +1 -0
  109. package/lib/plugins/hls-playback/HlsPlayback.js +747 -0
  110. package/lib/plugins/level-selector/LevelSelector.d.ts +48 -0
  111. package/lib/plugins/level-selector/LevelSelector.d.ts.map +1 -0
  112. package/lib/plugins/level-selector/LevelSelector.js +287 -0
  113. package/lib/plugins/media-control/MediaControl.d.ts +186 -0
  114. package/lib/plugins/media-control/MediaControl.d.ts.map +1 -0
  115. package/lib/plugins/media-control/MediaControl.js +1000 -0
  116. package/lib/plugins/poster/Poster.d.ts +41 -0
  117. package/lib/plugins/poster/Poster.d.ts.map +1 -0
  118. package/lib/plugins/poster/Poster.js +186 -0
  119. package/lib/trace/LogTracer.d.ts +12 -0
  120. package/lib/trace/LogTracer.d.ts.map +1 -0
  121. package/lib/trace/LogTracer.js +17 -0
  122. package/lib/trace/SentryTracer.d.ts +11 -0
  123. package/lib/trace/SentryTracer.d.ts.map +1 -0
  124. package/lib/trace/SentryTracer.js +18 -0
  125. package/lib/trace/Tracer.d.ts +13 -0
  126. package/lib/trace/Tracer.d.ts.map +1 -0
  127. package/lib/trace/Tracer.js +15 -0
  128. package/lib/trace/index.d.ts +18 -0
  129. package/lib/trace/index.d.ts.map +1 -0
  130. package/lib/trace/index.js +27 -0
  131. package/lib/trace/types.d.ts +8 -0
  132. package/lib/trace/types.d.ts.map +1 -0
  133. package/lib/trace/types.js +1 -0
  134. package/lib/types.d.ts +82 -0
  135. package/lib/types.d.ts.map +1 -0
  136. package/lib/types.js +1 -0
  137. package/lib/utils/Logger.d.ts +23 -0
  138. package/lib/utils/Logger.d.ts.map +1 -0
  139. package/lib/utils/Logger.js +81 -0
  140. package/lib/utils/canAutoplay.d.ts +6 -0
  141. package/lib/utils/canAutoplay.d.ts.map +1 -0
  142. package/lib/utils/canAutoplay.js +30 -0
  143. package/lib/utils/errors.d.ts +2 -0
  144. package/lib/utils/errors.d.ts.map +1 -0
  145. package/lib/utils/errors.js +6 -0
  146. package/lib/utils/queryParams.d.ts +2 -0
  147. package/lib/utils/queryParams.d.ts.map +1 -0
  148. package/lib/utils/queryParams.js +4 -0
  149. package/lib/utils/scripts-load.d.ts +2 -0
  150. package/lib/utils/scripts-load.d.ts.map +1 -0
  151. package/lib/utils/scripts-load.js +20 -0
  152. package/lib/utils/types.d.ts +4 -0
  153. package/lib/utils/types.d.ts.map +1 -0
  154. package/lib/utils/types.js +1 -0
  155. package/lib/utils/utils.d.ts +7 -0
  156. package/lib/utils/utils.d.ts.map +1 -0
  157. package/lib/utils/utils.js +57 -0
  158. package/package.json +57 -0
  159. package/rollup.config.js +34 -0
  160. package/src/Player.ts +390 -0
  161. package/src/backend.ts +12 -0
  162. package/src/constants.ts +17 -0
  163. package/src/index.ts +9 -0
  164. package/src/internal.types.ts +126 -0
  165. package/src/playback.types.ts +15 -0
  166. package/src/plugins/dash-playback/DashPlayback.ts +808 -0
  167. package/src/plugins/dash-playback/_DashPlayback.js +688 -0
  168. package/src/plugins/hls-playback/HlsPlayback.ts +909 -0
  169. package/src/plugins/hls-playback/hls.js +706 -0
  170. package/src/trace/LogTracer.ts +23 -0
  171. package/src/trace/SentryTracer.ts +18 -0
  172. package/src/trace/Tracer.ts +27 -0
  173. package/src/trace/index.ts +32 -0
  174. package/src/trace/types.ts +7 -0
  175. package/src/types.ts +100 -0
  176. package/src/typings/@clappr/core/error_mixin.d.ts +15 -0
  177. package/src/typings/@clappr/core/events.d.ts +7 -0
  178. package/src/typings/@clappr/core/html5_video.d.ts +28 -0
  179. package/src/typings/@clappr/core/playback.d.ts +5 -0
  180. package/src/typings/@clappr/core/player.d.ts +83 -0
  181. package/src/typings/@clappr/plugins.d.ts +29 -0
  182. package/src/typings/clappr-zepto.xd.xts +44 -0
  183. package/src/typings/globals.d.ts +8 -0
  184. package/src/utils/Logger.ts +107 -0
  185. package/src/utils/canAutoplay.ts +39 -0
  186. package/src/utils/errors.ts +6 -0
  187. package/src/utils/queryParams.ts +5 -0
  188. package/src/utils/scripts-load.ts +26 -0
  189. package/src/utils/types.ts +5 -0
  190. package/src/utils/utils.ts +64 -0
  191. package/tsconfig.json +43 -0
  192. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,667 @@
1
+ import { HTML5Video, Playback, Events, Log, Utils } from '@clappr/core';
2
+ import assert from 'assert';
3
+ import DASHJS from 'dashjs';
4
+ import { trace } from './index.js';
5
+ import 'hls.js';
6
+ import 'event-lite';
7
+
8
+ // Copyright 2014 Globo.com Player authors. All rights reserved.
9
+ // Use of this source code is governed by a BSD-style
10
+ // license that can be found in the LICENSE file.
11
+ const AUTO = -1;
12
+ const { now } = Utils;
13
+ const T = "DashPlayback";
14
+ class DashPlayback extends HTML5Video {
15
+ _levels = null;
16
+ _currentLevel = null;
17
+ _durationExcludesAfterLiveSyncPoint = false;
18
+ _isReadyState = false;
19
+ _playableRegionDuration = 0;
20
+ _playableRegionStartTime = 0;
21
+ _playbackType = Playback.VOD;
22
+ _playlistType = null;
23
+ // #EXT-X-PROGRAM-DATE-TIME
24
+ _programDateTime = 0;
25
+ _dash = null;
26
+ _extrapolatedWindowDuration = 0;
27
+ _extrapolatedWindowNumSegments = 0;
28
+ _lastDuration = null;
29
+ _lastTimeUpdate = { current: 0, total: 0 };
30
+ _localStartTimeCorrelation = null;
31
+ _localEndTimeCorrelation = null;
32
+ _recoverAttemptsRemaining = 0;
33
+ _recoveredAudioCodecError = false;
34
+ _recoveredDecodingError = false;
35
+ startChangeQuality = false;
36
+ manifestInfo = null;
37
+ // #EXT-X-TARGETDURATION
38
+ _segmentTargetDuration = null;
39
+ _timeUpdateTimer = null;
40
+ get name() {
41
+ return 'dash';
42
+ }
43
+ get levels() {
44
+ return this._levels || [];
45
+ }
46
+ get currentLevel() {
47
+ if (this._currentLevel === null) {
48
+ return AUTO;
49
+ }
50
+ // 0 is a valid level ID
51
+ return this._currentLevel;
52
+ }
53
+ get isReady() {
54
+ return this._isReadyState;
55
+ }
56
+ set currentLevel(id) {
57
+ this._currentLevel = id;
58
+ this.trigger(Events.PLAYBACK_LEVEL_SWITCH_START);
59
+ const cfg = {
60
+ streaming: {
61
+ abr: {
62
+ autoSwitchBitrate: {
63
+ video: id === -1,
64
+ },
65
+ ABRStrategy: 'abrL2A'
66
+ }
67
+ },
68
+ };
69
+ assert.ok(this._dash, 'An instance of dashjs MediaPlayer is required to switch levels');
70
+ const dash = this._dash;
71
+ this.options.dash && dash.updateSettings({ ...this.options.dash, ...cfg });
72
+ if (id !== -1) {
73
+ this._dash.setQualityFor('video', id);
74
+ }
75
+ if (this._playbackType === Playback.VOD) {
76
+ const curr_time = this._dash.time();
77
+ this.startChangeQuality = true;
78
+ dash.seek(0);
79
+ setTimeout(() => {
80
+ dash.seek(curr_time);
81
+ dash.play();
82
+ this.startChangeQuality = false;
83
+ }, 100);
84
+ }
85
+ }
86
+ get _startTime() {
87
+ if (this._playbackType === Playback.LIVE && this._playlistType !== 'EVENT') {
88
+ return this._extrapolatedStartTime;
89
+ }
90
+ return this._playableRegionStartTime;
91
+ }
92
+ get _now() {
93
+ return now();
94
+ }
95
+ // the time in the video element which should represent the start of the sliding window
96
+ // extrapolated to increase in real time (instead of jumping as the early segments are removed)
97
+ get _extrapolatedStartTime() {
98
+ if (!this._localStartTimeCorrelation) {
99
+ return this._playableRegionStartTime;
100
+ }
101
+ const corr = this._localStartTimeCorrelation;
102
+ const timePassed = this._now - corr.local;
103
+ const extrapolatedWindowStartTime = (corr.remote + timePassed) / 1000;
104
+ // cap at the end of the extrapolated window duration
105
+ return Math.min(extrapolatedWindowStartTime, this._playableRegionStartTime + this._extrapolatedWindowDuration);
106
+ }
107
+ // the time in the video element which should represent the end of the content
108
+ // extrapolated to increase in real time (instead of jumping as segments are added)
109
+ get _extrapolatedEndTime() {
110
+ const actualEndTime = this._playableRegionStartTime + this._playableRegionDuration;
111
+ if (!this._localEndTimeCorrelation) {
112
+ return actualEndTime;
113
+ }
114
+ const corr = this._localEndTimeCorrelation;
115
+ const timePassed = this._now - corr.local;
116
+ const extrapolatedEndTime = (corr.remote + timePassed) / 1000;
117
+ return Math.max(actualEndTime - this._extrapolatedWindowDuration, Math.min(extrapolatedEndTime, actualEndTime));
118
+ }
119
+ get _duration() {
120
+ if (!this._dash) {
121
+ return null;
122
+ }
123
+ return this._dash.duration();
124
+ }
125
+ constructor(options, i18n, playerError) {
126
+ super(options, i18n, playerError);
127
+ // backwards compatibility (TODO: remove on 0.3.0)
128
+ // this.options.playback || (this.options.playback = this.options);
129
+ // The size of the start time extrapolation window measured as a multiple of segments.
130
+ // Should be 2 or higher, or 0 to disable. Should only need to be increased above 2 if more than one segment is
131
+ // removed from the start of the playlist at a time. E.g if the playlist is cached for 10 seconds and new chunks are
132
+ // added/removed every 5.
133
+ this._extrapolatedWindowNumSegments = this.options.playback?.extrapolatedWindowNumSegments ?? 2;
134
+ if (this.options.playbackType) {
135
+ this._playbackType = this.options.playbackType;
136
+ }
137
+ // this._lastTimeUpdate = { current: 0, total: 0 };
138
+ // this._lastDuration = null;
139
+ // for hls streams which have dvr with a sliding window,
140
+ // the content at the start of the playlist is removed as new
141
+ // content is appended at the end.
142
+ // this means the actual playable start time will increase as the
143
+ // start content is deleted
144
+ // For streams with dvr where the entire recording is kept from the
145
+ // beginning this should stay as 0
146
+ // this._playableRegionStartTime = 0;
147
+ // {local, remote} remote is the time in the video element that should represent 0
148
+ // local is the system time when the 'remote' measurment took place
149
+ // this._localStartTimeCorrelation = null;
150
+ // {local, remote} remote is the time in the video element that should represents the end
151
+ // local is the system time when the 'remote' measurment took place
152
+ // this._localEndTimeCorrelation = null;
153
+ // if content is removed from the beginning then this empty area should
154
+ // be ignored. "playableRegionDuration" excludes the empty area
155
+ // this._playableRegionDuration = 0;
156
+ // #EXT-X-PROGRAM-DATE-TIME
157
+ // this._programDateTime = 0;
158
+ // this.manifestInfo = null;
159
+ // true when the actual duration is longer than hlsjs's live sync point
160
+ // when this is false playableRegionDuration will be the actual duration
161
+ // when this is true playableRegionDuration will exclude the time after the sync point
162
+ // this._durationExcludesAfterLiveSyncPoint = false;
163
+ // // #EXT-X-TARGETDURATION
164
+ // this._segmentTargetDuration = null;
165
+ // #EXT-X-PLAYLIST-TYPE
166
+ // this._playlistType = null;
167
+ if (this.options.hlsRecoverAttempts) {
168
+ this._recoverAttemptsRemaining = this.options.hlsRecoverAttempts;
169
+ }
170
+ }
171
+ _setup() {
172
+ trace(`${T} _setup`, { el: this.el });
173
+ const dash = DASHJS.MediaPlayer().create();
174
+ this._dash = dash;
175
+ this._dash.initialize();
176
+ const cfg = this.options.dash ?? {};
177
+ cfg.streaming = cfg.streaming || {};
178
+ cfg.streaming.text = cfg.streaming.text || { defaultEnabled: false };
179
+ this.options.dash && this._dash.updateSettings(cfg);
180
+ this._dash.attachView(this.el);
181
+ this._dash.setAutoPlay(false);
182
+ this._dash.attachSource(this.options.src);
183
+ this._dash.on(DASHJS.MediaPlayer.events.ERROR, this._onDASHJSSError);
184
+ this._dash.on(DASHJS.MediaPlayer.events.PLAYBACK_ERROR, this._onPlaybackError);
185
+ this._dash.on(DASHJS.MediaPlayer.events.STREAM_INITIALIZED, () => {
186
+ const bitrates = dash.getBitrateInfoListFor('video');
187
+ trace(`${T} STREAM_INITIALIZED`, { bitrates });
188
+ this._updatePlaybackType();
189
+ this._fillLevels(bitrates);
190
+ dash.on(DASHJS.MediaPlayer.events.QUALITY_CHANGE_REQUESTED, (evt) => {
191
+ // TODO
192
+ assert.ok(this._levels, 'An array of levels is required to change quality');
193
+ const newLevel = this._levels.find((level) => level.id === evt.newQuality); // TODO or simply this._levels[evt.newQuality]?
194
+ assert.ok(newLevel, 'A valid level is required to change quality');
195
+ this.onLevelSwitch(newLevel.level);
196
+ });
197
+ });
198
+ this._dash.on(DASHJS.MediaPlayer.events.METRIC_ADDED, (e) => {
199
+ // console.log(`${T} onMetricAdded`, e);
200
+ // TODO
201
+ // Listen for the first manifest request in order to update player UI
202
+ if (e.metric === 'DVRInfo') { // TODO fix typings
203
+ assert.ok(this._dash, 'An instance of dashjs MediaPlayer is required to get metrics');
204
+ const dvrInfo = this._dash.getDashMetrics().getCurrentDVRInfo('video');
205
+ // trace(`${T} onMetricAdded DVRInfo`, {metric: e.metric, dvrInfo});
206
+ if (dvrInfo) {
207
+ // Extract time info
208
+ this.manifestInfo = dvrInfo.manifestInfo;
209
+ }
210
+ }
211
+ });
212
+ this._dash.on(DASHJS.MediaPlayer.events.PLAYBACK_RATE_CHANGED, () => {
213
+ // TODO test
214
+ this.trigger('dash:playback-rate-changed', this.setPlaybackRate);
215
+ });
216
+ }
217
+ setPlaybackRate = (rate) => {
218
+ this._dash?.setPlaybackRate(rate);
219
+ };
220
+ render() {
221
+ this._ready();
222
+ return super.render();
223
+ }
224
+ _ready() {
225
+ this._isReadyState = true;
226
+ this.trigger(Events.PLAYBACK_READY, this.name);
227
+ }
228
+ // TODO
229
+ // _recover(evt, data, error) {
230
+ // console.warn('recover', evt, data, error);
231
+ // assert.ok(this._dash, 'An instance of dashjs MediaPlayer is required to recover');
232
+ // // TODO figure out what's going on here
233
+ // const dash = this._dash;
234
+ // if (!this._recoveredDecodingError) {
235
+ // this._recoveredDecodingError = true;
236
+ // // dash.recoverMediaError();
237
+ // } else if (!this._recoveredAudioCodecError) {
238
+ // this._recoveredAudioCodecError = true;
239
+ // // dash.swapAudioCodec();
240
+ // // dash.recoverMediaError();
241
+ // } else {
242
+ // // TODO what does it have to do with hlsjs?
243
+ // Log.error('hlsjs: failed to recover', { evt, data });
244
+ // error.level = PlayerError.Levels.FATAL;
245
+ // const formattedError = this.createError(error);
246
+ // this.trigger(Events.PLAYBACK_ERROR, formattedError);
247
+ // this.stop();
248
+ // }
249
+ // }
250
+ // override
251
+ _setupSrc() {
252
+ console.log(`${T} _setupSrc`);
253
+ // this playback manages the src on the video element itself
254
+ }
255
+ _startTimeUpdateTimer() {
256
+ this._stopTimeUpdateTimer();
257
+ this._timeUpdateTimer = setInterval(() => {
258
+ this._onDurationChange();
259
+ this._onTimeUpdate();
260
+ }, 100);
261
+ }
262
+ _stopTimeUpdateTimer() {
263
+ if (this._timeUpdateTimer) {
264
+ clearInterval(this._timeUpdateTimer);
265
+ }
266
+ }
267
+ getProgramDateTime() {
268
+ return this._programDateTime;
269
+ }
270
+ // the duration on the video element itself should not be used
271
+ // as this does not necesarily represent the duration of the stream
272
+ // https://github.com/clappr/clappr/issues/668#issuecomment-157036678
273
+ getDuration() {
274
+ assert.ok(this._duration !== null, 'A valid duration is required to get the duration');
275
+ return this._duration;
276
+ }
277
+ getCurrentTime() {
278
+ // e.g. can be < 0 if user pauses near the start
279
+ // eventually they will then be kicked to the end by hlsjs if they run out of buffer
280
+ // before the official start time
281
+ return this._dash ? this._dash.time() : 0;
282
+ }
283
+ // the time that "0" now represents relative to when playback started
284
+ // for a stream with a sliding window this will increase as content is
285
+ // removed from the beginning
286
+ getStartTimeOffset() {
287
+ return this._startTime;
288
+ }
289
+ seekPercentage(percentage) {
290
+ let seekTo = this._duration;
291
+ if (percentage > 0) {
292
+ assert.ok(this._duration !== null, 'A valid duration is required to seek by percentage');
293
+ seekTo = this._duration * (percentage / 100);
294
+ }
295
+ assert.ok(seekTo !== null, 'A valid seek time is required');
296
+ this.seek(seekTo);
297
+ }
298
+ seek(time) {
299
+ if (time < 0) {
300
+ // eslint-disable-next-line max-len
301
+ Log.warn('Attempt to seek to a negative time. Resetting to live point. Use seekToLivePoint() to seek to the live point.');
302
+ time = this.getDuration();
303
+ }
304
+ this.dvrEnabled && this._updateDvr(time < this.getDuration() - 10);
305
+ assert.ok(this._dash, 'An instance of dashjs MediaPlayer is required to seek');
306
+ this._dash.seek(time);
307
+ }
308
+ seekToLivePoint() {
309
+ this.seek(this.getDuration());
310
+ }
311
+ _updateDvr(status) {
312
+ this.trigger(Events.PLAYBACK_DVR, status);
313
+ this.trigger(Events.PLAYBACK_STATS_ADD, { 'dvr': status });
314
+ }
315
+ _updateSettings() {
316
+ if (this._playbackType === Playback.VOD) {
317
+ this.settings.left = ['playpause', 'position', 'duration'];
318
+ // this.settings.left.push('playstop');
319
+ }
320
+ else if (this.dvrEnabled) {
321
+ this.settings.left = ['playpause'];
322
+ }
323
+ else {
324
+ this.settings.left = ['playstop'];
325
+ }
326
+ this.settings.seekEnabled = this.isSeekEnabled();
327
+ this.trigger(Events.PLAYBACK_SETTINGSUPDATE);
328
+ }
329
+ _onPlaybackError = (event) => {
330
+ // TODO
331
+ };
332
+ _onDASHJSSError = (event) => {
333
+ // TODO
334
+ // only report/handle errors if they are fatal
335
+ // hlsjs should automatically handle non fatal errors
336
+ this._stopTimeUpdateTimer();
337
+ if (event.error === 'capability' && event.event === 'mediasource') {
338
+ // No support for MSE
339
+ const formattedError = this.createError(event.error);
340
+ this.trigger(Events.PLAYBACK_ERROR, formattedError);
341
+ Log.error('The media cannot be played because it requires a feature ' +
342
+ 'that your browser does not support.');
343
+ }
344
+ else if (event.error === 'manifestError' && (
345
+ // Manifest type not supported
346
+ (event.event.id === 'createParser') ||
347
+ // Codec(s) not supported
348
+ (event.event.id === 'codec') ||
349
+ // No streams available to stream
350
+ (event.event.id === 'nostreams') ||
351
+ // Error creating Stream object
352
+ (event.event.id === 'nostreamscomposed') ||
353
+ // syntax error parsing the manifest
354
+ (event.event.id === 'parse') ||
355
+ // a stream has multiplexed audio+video
356
+ (event.event.id === 'multiplexedrep'))) {
357
+ // These errors have useful error messages, so we forward it on
358
+ const formattedError = this.createError(event.error);
359
+ this.trigger(Events.PLAYBACK_ERROR, formattedError);
360
+ if (event.error) {
361
+ Log.error(event.event.message);
362
+ }
363
+ }
364
+ else if (event.error === 'mediasource') {
365
+ // This error happens when dash.js fails to allocate a SourceBuffer
366
+ // OR the underlying video element throws a `MediaError`.
367
+ // If it's a buffer allocation fail, the message states which buffer
368
+ // (audio/video/text) failed allocation.
369
+ // If it's a `MediaError`, dash.js inspects the error object for
370
+ // additional information to append to the error type.
371
+ const formattedError = this.createError(event.error);
372
+ this.trigger(Events.PLAYBACK_ERROR, formattedError);
373
+ Log.error(event.event);
374
+ }
375
+ else if (event.error === 'capability' && event.event === 'encryptedmedia') {
376
+ // Browser doesn't support EME
377
+ const formattedError = this.createError(event.error);
378
+ this.trigger(Events.PLAYBACK_ERROR, formattedError);
379
+ Log.error('The media cannot be played because it requires encryption ' +
380
+ 'that your browser does not support.');
381
+ }
382
+ else if (event.error === 'key_session') {
383
+ // This block handles pretty much all errors thrown by the
384
+ // encryption subsystem
385
+ const formattedError = this.createError(event.error);
386
+ this.trigger(Events.PLAYBACK_ERROR, formattedError);
387
+ Log.error(event.event);
388
+ }
389
+ else if (event.error === 'download') {
390
+ const formattedError = this.createError(event.error);
391
+ this.trigger(Events.PLAYBACK_ERROR, formattedError);
392
+ Log.error('The media playback was aborted because too many consecutive ' +
393
+ 'download errors occurred.');
394
+ // } else if (event.error === 'mssError') {
395
+ // const formattedError = this.createError(event.error);
396
+ // this.trigger(Events.PLAYBACK_ERROR, formattedError);
397
+ // if (event.error) {
398
+ // Log.error(event.error.message);
399
+ // }
400
+ }
401
+ else {
402
+ // ignore the error
403
+ if (typeof event.error === "object") {
404
+ const formattedError = this.createError(event.error);
405
+ this.trigger(Events.PLAYBACK_ERROR, formattedError);
406
+ Log.error(event.error.message);
407
+ }
408
+ else {
409
+ Log.error(event.error);
410
+ }
411
+ return;
412
+ }
413
+ // only reset the dash player in 10ms async, so that the rest of the
414
+ // calling function finishes
415
+ setTimeout(() => {
416
+ assert.ok(this._dash, 'An instance of dashjs MediaPlayer is required to reset');
417
+ this._dash.reset();
418
+ }, 10);
419
+ };
420
+ _onTimeUpdate() {
421
+ if (this.startChangeQuality) {
422
+ return;
423
+ }
424
+ const update = {
425
+ current: this.getCurrentTime(),
426
+ total: this.getDuration(),
427
+ firstFragDateTime: this.getProgramDateTime()
428
+ };
429
+ const isSame = this._lastTimeUpdate && (update.current === this._lastTimeUpdate.current &&
430
+ update.total === this._lastTimeUpdate.total);
431
+ if (isSame) {
432
+ return;
433
+ }
434
+ this._lastTimeUpdate = update;
435
+ this.trigger(Events.PLAYBACK_TIMEUPDATE, update, this.name);
436
+ }
437
+ _onDurationChange() {
438
+ const duration = this.getDuration();
439
+ if (this._lastDuration === duration) {
440
+ return;
441
+ }
442
+ this._lastDuration = duration;
443
+ super._onDurationChange();
444
+ }
445
+ get dvrEnabled() {
446
+ assert.ok(this._dash, 'An instance of dashjs MediaPlayer is required to get the DVR status');
447
+ return this._dash?.getDVRWindowSize() >= this._minDvrSize && this.getPlaybackType() === Playback.LIVE;
448
+ }
449
+ _onProgress() {
450
+ if (!this._dash) {
451
+ return;
452
+ }
453
+ let buffer = this._dash.getDashMetrics().getCurrentBufferLevel('video');
454
+ if (!buffer) {
455
+ buffer = this._dash.getDashMetrics().getCurrentBufferLevel('audio');
456
+ }
457
+ const progress = {
458
+ start: this.getCurrentTime(),
459
+ current: this.getCurrentTime() + buffer,
460
+ total: this.getDuration()
461
+ };
462
+ this.trigger(Events.PLAYBACK_PROGRESS, progress, {});
463
+ }
464
+ play() {
465
+ trace(`${T} play`, { dash: !!this._dash });
466
+ if (!this._dash) {
467
+ this._setup();
468
+ }
469
+ super.play();
470
+ this._startTimeUpdateTimer();
471
+ }
472
+ pause() {
473
+ if (!this._dash) {
474
+ return;
475
+ }
476
+ super.pause();
477
+ if (this.dvrEnabled) {
478
+ this._updateDvr(true);
479
+ }
480
+ }
481
+ stop() {
482
+ if (this._dash) {
483
+ this._stopTimeUpdateTimer();
484
+ this._dash.reset();
485
+ super.stop();
486
+ this._dash = null;
487
+ }
488
+ }
489
+ destroy() {
490
+ this._stopTimeUpdateTimer();
491
+ if (this._dash) {
492
+ this._dash.off(DASHJS.MediaPlayer.events.ERROR, this._onDASHJSSError);
493
+ this._dash.off(DASHJS.MediaPlayer.events.PLAYBACK_ERROR, this._onPlaybackError);
494
+ this._dash.off(DASHJS.MediaPlayer.events.MANIFEST_LOADED, this.getDuration);
495
+ this._dash.reset();
496
+ }
497
+ this._dash = null;
498
+ return super.destroy();
499
+ }
500
+ _updatePlaybackType() {
501
+ assert.ok(this._dash, 'An instance of dashjs MediaPlayer is required to update the playback type');
502
+ this._playbackType = this._dash.isDynamic() ? Playback.LIVE : Playback.VOD;
503
+ trace(`${T} _updatePlaybackType`, {
504
+ playbackType: this._playbackType,
505
+ });
506
+ }
507
+ _fillLevels(levels) {
508
+ // trace(`${T} _fillLevels`, {levels});
509
+ // TOOD check that levels[i].qualityIndex === i
510
+ this._levels = levels.map((level) => {
511
+ return { id: level.qualityIndex, level: level };
512
+ });
513
+ this.trigger(Events.PLAYBACK_LEVELS_AVAILABLE, this._levels);
514
+ }
515
+ // _onLevelUpdated(_: any, data) {
516
+ // this._segmentTargetDuration = data.details.targetduration;
517
+ // this._playlistType = data.details.type || null;
518
+ // let startTimeChanged = false;
519
+ // let durationChanged = false;
520
+ // const fragments = data.details.fragments;
521
+ // const previousPlayableRegionStartTime = this._playableRegionStartTime;
522
+ // const previousPlayableRegionDuration = this._playableRegionDuration;
523
+ // if (fragments.length === 0) {
524
+ // return;
525
+ // }
526
+ // // #EXT-X-PROGRAM-DATE-TIME
527
+ // if (fragments[0].rawProgramDateTime) {
528
+ // this._programDateTime = fragments[0].rawProgramDateTime;
529
+ // }
530
+ // if (this._playableRegionStartTime !== fragments[0].start) {
531
+ // startTimeChanged = true;
532
+ // this._playableRegionStartTime = fragments[0].start;
533
+ // }
534
+ // if (startTimeChanged) {
535
+ // if (!this._localStartTimeCorrelation) {
536
+ // // set the correlation to map to middle of the extrapolation window
537
+ // this._localStartTimeCorrelation = {
538
+ // local: this._now,
539
+ // remote: (fragments[0].start + (this._extrapolatedWindowDuration / 2)) * 1000
540
+ // };
541
+ // } else {
542
+ // // check if the correlation still works
543
+ // const corr = this._localStartTimeCorrelation;
544
+ // const timePassed = this._now - corr.local;
545
+ // // this should point to a time within the extrapolation window
546
+ // const startTime = (corr.remote + timePassed) / 1000;
547
+ // if (startTime < fragments[0].start) {
548
+ // // our start time is now earlier than the first chunk
549
+ // // (maybe the chunk was removed early)
550
+ // // reset correlation so that it sits at the beginning of the first available chunk
551
+ // this._localStartTimeCorrelation = {
552
+ // local: this._now,
553
+ // remote: fragments[0].start * 1000
554
+ // };
555
+ // } else if (startTime > previousPlayableRegionStartTime + this._extrapolatedWindowDuration) {
556
+ // // start time was past the end of the old extrapolation window (so would have been capped)
557
+ // // see if now that time would be inside the window, and if it would be set the correlation
558
+ // // so that it resumes from the time it was at at the end of the old window
559
+ // // update the correlation so that the time starts counting again from the value it's on now
560
+ // this._localStartTimeCorrelation = {
561
+ // local: this._now,
562
+ // remote: Math.max(
563
+ // fragments[0].start,
564
+ // previousPlayableRegionStartTime + this._extrapolatedWindowDuration
565
+ // ) * 1000
566
+ // };
567
+ // }
568
+ // }
569
+ // }
570
+ // let newDuration = data.details.totalduration;
571
+ // // if it's a live stream then shorten the duration to remove access
572
+ // // to the area after hlsjs's live sync point
573
+ // // seeks to areas after this point sometimes have issues
574
+ // if (this._playbackType === Playback.LIVE) {
575
+ // const fragmentTargetDuration = data.details.targetduration;
576
+ // const hlsjsConfig = this.options.playback.hlsjsConfig || {};
577
+ // // eslint-disable-next-line no-undef
578
+ // const liveSyncDurationCount = hlsjsConfig.liveSyncDurationCount || HLSJS.DefaultConfig.liveSyncDurationCount;
579
+ // const hiddenAreaDuration = fragmentTargetDuration * liveSyncDurationCount;
580
+ // if (hiddenAreaDuration <= newDuration) {
581
+ // newDuration -= hiddenAreaDuration;
582
+ // this._durationExcludesAfterLiveSyncPoint = true;
583
+ // } else {
584
+ // this._durationExcludesAfterLiveSyncPoint = false;
585
+ // }
586
+ // }
587
+ // if (newDuration !== this._playableRegionDuration) {
588
+ // durationChanged = true;
589
+ // this._playableRegionDuration = newDuration;
590
+ // }
591
+ // // Note the end time is not the playableRegionDuration
592
+ // // The end time will always increase even if content is removed from the beginning
593
+ // const endTime = fragments[0].start + newDuration;
594
+ // const previousEndTime = previousPlayableRegionStartTime + previousPlayableRegionDuration;
595
+ // const endTimeChanged = endTime !== previousEndTime;
596
+ // if (endTimeChanged) {
597
+ // if (!this._localEndTimeCorrelation) {
598
+ // // set the correlation to map to the end
599
+ // this._localEndTimeCorrelation = {
600
+ // local: this._now,
601
+ // remote: endTime * 1000
602
+ // };
603
+ // } else {
604
+ // // check if the correlation still works
605
+ // const corr = this._localEndTimeCorrelation;
606
+ // const timePassed = this._now - corr.local;
607
+ // // this should point to a time within the extrapolation window from the end
608
+ // const extrapolatedEndTime = (corr.remote + timePassed) / 1000;
609
+ // if (extrapolatedEndTime > endTime) {
610
+ // this._localEndTimeCorrelation = {
611
+ // local: this._now,
612
+ // remote: endTime * 1000
613
+ // };
614
+ // } else if (extrapolatedEndTime < endTime - this._extrapolatedWindowDuration) {
615
+ // // our extrapolated end time is now earlier than the extrapolation window from the actual end time
616
+ // // (maybe a chunk became available early)
617
+ // // reset correlation so that it sits at the beginning of the extrapolation window from the end time
618
+ // this._localEndTimeCorrelation = {
619
+ // local: this._now,
620
+ // remote: (endTime - this._extrapolatedWindowDuration) * 1000
621
+ // };
622
+ // } else if (extrapolatedEndTime > previousEndTime) {
623
+ // // end time was past the old end time (so would have been capped)
624
+ // // set the correlation so that it resumes from the time it was at at the end of the old window
625
+ // this._localEndTimeCorrelation = {
626
+ // local: this._now,
627
+ // remote: previousEndTime * 1000
628
+ // };
629
+ // }
630
+ // }
631
+ // }
632
+ // // now that the values have been updated call any methods that use on them so they get the updated values
633
+ // // immediately
634
+ // durationChanged && this._onDurationChange();
635
+ // startTimeChanged && this._onProgress();
636
+ // }
637
+ // _onFragmentLoaded(evt, data) {
638
+ // this.trigger(Events.PLAYBACK_FRAGMENT_LOADED, data);
639
+ // }
640
+ onLevelSwitch(currentLevel) {
641
+ trace(`${T} onLevelSwitch`, { currentLevel });
642
+ this.trigger(Events.PLAYBACK_BITRATE, {
643
+ height: currentLevel.height,
644
+ width: currentLevel.width,
645
+ bitrate: currentLevel.bitrate,
646
+ level: currentLevel.qualityIndex
647
+ });
648
+ }
649
+ getPlaybackType() {
650
+ return this._playbackType;
651
+ }
652
+ isSeekEnabled() {
653
+ return (this._playbackType === Playback.VOD || this.dvrEnabled);
654
+ }
655
+ }
656
+ DashPlayback.canPlay = function (resource, mimeType) {
657
+ console.log(`${T} canPlay resource:%s mimeType:%s`, resource, mimeType);
658
+ const resourceParts = resource.split('?')[0].match(/.*\.(.*)$/) || [];
659
+ const isDash = ((resourceParts.length > 1 && resourceParts[1].toLowerCase() === 'mpd') ||
660
+ mimeType === 'application/dash+xml' || mimeType === 'video/mp4');
661
+ const ctor = window.MediaSource || ('WebKitMediaSource' in window ? window.WebKitMediaSource : undefined);
662
+ const isSupportByBrowser = typeof ctor === 'function';
663
+ console.log(`${T} canPlay isSupportByBrowser:%s isDash:%s`, isSupportByBrowser, isDash);
664
+ return !!(isSupportByBrowser && isDash);
665
+ };
666
+
667
+ export { DashPlayback as default };