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