This repository has been archived by the owner on May 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
castable-video.js
543 lines (463 loc) · 15 KB
/
castable-video.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/* global globalThis, chrome, cast */
class CastableVideoElement extends HTMLVideoElement {
static observedAttributes = ['cast-src'];
static instances = new Set();
static #castElement;
static get castElement() {
return this.#castElement;
}
static #castEnabled = false;
static get castEnabled() {
return this.#castEnabled;
}
static initCast = () => {
if (!this.#isChromeCastAvailable) {
window.__onGCastApiAvailable = () => {
// The window.__onGCastApiAvailable callback alone is not reliable for
// the added cast.framework. It's loaded in a separate JS file.
// http://www.gstatic.com/eureka/clank/101/cast_sender.js
// http://www.gstatic.com/cast/sdk/libs/sender/1.0/cast_framework.js
customElements
.whenDefined('google-cast-button')
.then(() => this.#onSdkLoaded(chrome.cast.isAvailable));
};
} else if (!this.#isCastFrameworkAvailable) {
customElements
.whenDefined('google-cast-button')
.then(() => this.#onSdkLoaded(chrome.cast.isAvailable));
} else {
this.#onSdkLoaded(chrome.cast.isAvailable);
}
};
static async exitCast() {
// Should the receiver application be stopped or just disconnected.
const stopCasting = true;
try {
await this.#castContext.endCurrentSession(stopCasting);
} catch (err) {
console.error(err);
return;
}
}
static #onSdkLoaded = (isAvailable) => {
if (isAvailable) {
this.#castEnabled = true;
for (const video of this.instances) {
video.#init();
}
}
};
static get #isChromeCastAvailable() {
return (
typeof chrome !== 'undefined' && chrome.cast && chrome.cast.isAvailable
);
}
static get #isCastFrameworkAvailable() {
return typeof cast !== 'undefined' && cast.framework;
}
static get #castContext() {
if (this.#isCastFrameworkAvailable) {
return cast.framework.CastContext.getInstance();
}
return undefined;
}
static get #currentSession() {
return this.#castContext?.getCurrentSession();
}
#castAvailable = false;
#localState = { paused: false };
#remoteState = { paused: false, currentTime: 0, muted: false };
#remotePlayer;
#remoteListeners = [];
#textTrackState = new Map();
constructor() {
super();
this.castEnabled = false;
CastableVideoElement.instances.add(this);
this.#init();
}
get castPlayer() {
if (CastableVideoElement.castElement === this) return this.#remotePlayer;
return undefined;
}
get #isMediaLoaded() {
return this.#remotePlayer?.isMediaLoaded;
}
attributeChangedCallback(attrName) {
if (!this.castPlayer) return;
switch (attrName) {
case 'cast-src':
this.load();
break;
}
}
#disconnect() {
if (CastableVideoElement.#castElement !== this) return;
this.#remoteListeners.forEach(([event, listener]) => {
this.#remotePlayer.controller.removeEventListener(event, listener);
});
CastableVideoElement.#castElement = undefined;
this.muted = this.#remoteState.muted;
this.currentTime = this.#remoteState.currentTime;
if (this.#remoteState.paused === false) {
this.play();
}
}
#init() {
if (!CastableVideoElement.#isCastFrameworkAvailable || this.#castAvailable) return;
this.#castAvailable = true;
this.#setOptions();
this.textTracks.addEventListener(
'change',
this.#onLocalTextTracksChange.bind(this)
);
// Cast state: NO_DEVICES_AVAILABLE, NOT_CONNECTED, CONNECTING, CONNECTED
// https://developers.google.com/cast/docs/reference/web_sender/cast.framework#.CastState
const { CAST_STATE_CHANGED } = cast.framework.CastContextEventType;
CastableVideoElement.#castContext.addEventListener(CAST_STATE_CHANGED, () => {
this.dispatchEvent(
new CustomEvent('castchange', {
detail: CastableVideoElement.#castContext.getCastState(),
})
);
});
this.dispatchEvent(
new CustomEvent('castchange', {
detail: CastableVideoElement.#castContext.getCastState(),
})
);
this.#remotePlayer = new cast.framework.RemotePlayer();
new cast.framework.RemotePlayerController(this.#remotePlayer);
this.#remoteListeners = [
[
cast.framework.RemotePlayerEventType.IS_CONNECTED_CHANGED,
({ value }) => {
if (value === false) {
this.#disconnect();
}
this.dispatchEvent(new Event(value ? 'entercast' : 'leavecast'));
},
],
[
cast.framework.RemotePlayerEventType.DURATION_CHANGED,
() => this.dispatchEvent(new Event('durationchange')),
],
[
cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED,
() => this.dispatchEvent(new Event('volumechange')),
],
[
cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED,
() => {
this.#remoteState.muted = this.muted;
this.dispatchEvent(new Event('volumechange'));
},
],
[
cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED,
() => {
if (this.#isMediaLoaded) {
this.#remoteState.currentTime = this.currentTime;
this.dispatchEvent(new Event('timeupdate'));
}
},
],
[
cast.framework.RemotePlayerEventType.VIDEO_INFO_CHANGED,
() => this.dispatchEvent(new Event('resize')),
],
[
cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED,
() => {
this.#remoteState.paused = this.paused;
this.dispatchEvent(new Event(this.paused ? 'pause' : 'play'));
},
],
[
cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED,
() => {
// pause event is handled above.
if (
this.castPlayer?.playerState ===
chrome.cast.media.PlayerState.PAUSED
) {
return;
}
this.dispatchEvent(
new Event(
{
[chrome.cast.media.PlayerState.PLAYING]: 'playing',
[chrome.cast.media.PlayerState.BUFFERING]: 'waiting',
[chrome.cast.media.PlayerState.IDLE]: 'emptied',
}[this.castPlayer?.playerState]
)
);
},
],
];
}
#setOptions(options) {
return CastableVideoElement.#castContext.setOptions({
// Set the receiver application ID to your own (created in the
// Google Cast Developer Console), or optionally
// use the chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID
receiverApplicationId: chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,
// Auto join policy can be one of the following three:
// ORIGIN_SCOPED - Auto connect from same appId and page origin
// TAB_AND_ORIGIN_SCOPED - Auto connect from same appId, page origin, and tab
// PAGE_SCOPED - No auto connect
autoJoinPolicy: chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED,
// The following flag enables Cast Connect(requires Chrome 87 or higher)
// https://developers.googleblog.com/2020/08/introducing-cast-connect-android-tv.html
androidReceiverCompatible: false,
language: 'en-US',
resumeSavedSession: false,
...options,
});
}
#getTrackId(track) {
return this.#textTrackState.get(track)?.trackId;
}
#onLocalTextTracksChange() {
if (!this.castPlayer) return;
// Note this could also include audio or video tracks, diff against local state.
const activeTrackIds =
CastableVideoElement.#currentSession?.getSessionObj().media[0].activeTrackIds;
const subtitles = [...this.textTracks].filter(
({ kind }) => kind === 'subtitles' || kind === 'captions'
);
const hiddenSubtitles = subtitles.filter(({ mode }) => mode !== 'showing');
const hiddenTrackIds = hiddenSubtitles.map(this.#getTrackId, this);
const showingSubtitle = subtitles.find(({ mode }) => mode === 'showing');
let requestTrackIds = activeTrackIds;
if (activeTrackIds.length) {
// Filter out all local hidden subtitle trackId's.
requestTrackIds = requestTrackIds.filter(
(id) => !hiddenTrackIds.includes(id)
);
}
if (!requestTrackIds.includes(showingSubtitle)) {
const showingTrackId = this.#getTrackId(showingSubtitle);
if (showingTrackId) {
requestTrackIds = [...requestTrackIds, showingTrackId];
}
}
const request = new chrome.cast.media.EditTracksInfoRequest(
requestTrackIds
);
CastableVideoElement.#currentSession?.getSessionObj().media[0].editTracksInfo(
request,
() => {},
(error) => console.error(error)
);
}
async requestCast(options = {}) {
this.#setOptions(options);
CastableVideoElement.#castElement = this;
this.#remoteListeners.forEach(([event, listener]) => {
this.#remotePlayer.controller.addEventListener(event, listener);
});
try {
// Open browser cast menu.
await CastableVideoElement.#castContext.requestSession();
} catch (err) {
CastableVideoElement.#castElement = undefined;
// console.error(err); // Don't show an error if dismissing the menu.
return;
}
// Pause locally when the session is created.
this.#localState.paused = super.paused;
super.pause();
// Sync over the muted state but not volume, 100% is different on TV's :P
this.muted = super.muted;
try {
await this.load();
} catch (err) {
console.error(err);
}
}
async load() {
if (!this.castPlayer) return super.load();
const mediaInfo = new chrome.cast.media.MediaInfo(
this.castSrc,
this.contentType
);
mediaInfo.textTrackStyle = new chrome.cast.media.TextTrackStyle();
mediaInfo.textTrackStyle.backgroundColor = '#00000000';
mediaInfo.textTrackStyle.edgeColor = '#000000FF';
mediaInfo.textTrackStyle.edgeType =
chrome.cast.media.TextTrackEdgeType.OUTLINE;
mediaInfo.textTrackStyle.fontScale = 1.0;
mediaInfo.textTrackStyle.foregroundColor = '#FFFFFF';
// First give all text tracks a unique ID and save them in a Map().
[...this.textTracks]
.filter(({ kind }) => kind === 'subtitles' || kind === 'captions')
.forEach((track) => {
if (!this.#textTrackState.has(track)) {
const trackId = this.#textTrackState.size + 1;
this.#textTrackState.set(track, { trackId });
}
});
const subtitles = [...this.querySelectorAll('track')].filter(({ kind }) => {
return kind === 'subtitles' || kind === 'captions';
});
if (subtitles.length) {
mediaInfo.tracks = subtitles.map((trackEl, i) => {
const trackId = this.#getTrackId(subtitles[i].track);
if (!trackId) return;
const track = new chrome.cast.media.Track(
trackId,
chrome.cast.media.TrackType.TEXT
);
track.trackContentId = trackEl.src;
track.trackContentType = 'text/vtt';
track.subtype =
trackEl.kind === 'captions'
? chrome.cast.media.TextTrackType.CAPTIONS
: chrome.cast.media.TextTrackType.SUBTITLES;
track.name = trackEl.label;
track.language = trackEl.srclang;
return track;
});
}
if (this.streamType?.includes('live')) {
mediaInfo.streamType = chrome.cast.media.StreamType.LIVE;
} else {
mediaInfo.streamType = chrome.cast.media.StreamType.BUFFERED;
}
mediaInfo.metadata = new chrome.cast.media.GenericMediaMetadata();
mediaInfo.metadata.title = this.title;
mediaInfo.metadata.images = [
{
url: this.poster,
},
];
const request = new chrome.cast.media.LoadRequest(mediaInfo);
request.currentTime = super.currentTime ?? 0;
request.autoplay = !this.#localState.paused;
for (let i = 0; i < subtitles.length; i++) {
const trackId = this.#getTrackId(subtitles[i].track);
if (subtitles[i].track.mode === 'showing' && trackId) {
request.activeTrackIds = [trackId];
break;
}
}
await CastableVideoElement.#currentSession?.loadMedia(request);
this.dispatchEvent(new Event('volumechange'));
}
play() {
if (this.castPlayer) {
if (this.castPlayer.isPaused) {
this.castPlayer.controller?.playOrPause();
}
return;
}
super.play();
}
pause() {
if (this.castPlayer) {
if (!this.castPlayer.isPaused) {
this.castPlayer.controller?.playOrPause();
}
return;
}
super.pause();
}
// Allow the cast source url to be different than <video src>, could be a blob.
get castSrc() {
// Try the first <source src> for usage with even more native markup.
return (
this.getAttribute('cast-src') ??
this.querySelector('source')?.src ??
this.currentSrc
);
}
set castSrc(val) {
if (this.castSrc == val) return;
this.setAttribute('cast-src', `${val}`);
}
get contentType() {
return this.getAttribute('content-type') ?? undefined;
}
set contentType(val) {
this.setAttribute('content-type', `${val}`);
}
get streamType() {
return this.getAttribute('stream-type') ?? undefined;
}
set streamType(val) {
this.setAttribute('stream-type', `${val}`);
}
get readyState() {
if (this.castPlayer) {
switch (this.castPlayer.playerState) {
case chrome.cast.media.PlayerState.IDLE:
return 0;
case chrome.cast.media.PlayerState.BUFFERING:
return 2;
default:
return 3;
}
}
return super.readyState;
}
get paused() {
if (this.castPlayer) return this.castPlayer.isPaused;
return super.paused;
}
get muted() {
if (this.castPlayer) return this.castPlayer?.isMuted;
return super.muted;
}
set muted(val) {
if (this.castPlayer) {
if (
(val && !this.castPlayer.isMuted) ||
(!val && this.castPlayer.isMuted)
) {
this.castPlayer.controller?.muteOrUnmute();
}
return;
}
super.muted = val;
}
get volume() {
if (this.castPlayer) return this.castPlayer?.volumeLevel ?? 1;
return super.volume;
}
set volume(val) {
if (this.castPlayer) {
this.castPlayer.volumeLevel = val;
this.castPlayer.controller?.setVolumeLevel();
return;
}
super.volume = val;
}
get duration() {
// castPlayer duration returns `0` when no media is loaded.
if (this.castPlayer && this.#isMediaLoaded) {
return this.castPlayer?.duration ?? NaN;
}
return super.duration;
}
get currentTime() {
if (this.castPlayer && this.#isMediaLoaded) {
return this.castPlayer?.currentTime ?? 0;
}
return super.currentTime;
}
set currentTime(val) {
if (this.castPlayer) {
this.castPlayer.currentTime = val;
this.castPlayer.controller?.seek();
return;
}
super.currentTime = val;
}
}
if (!customElements.get('castable-video')) {
customElements.define('castable-video', CastableVideoElement, { extends: 'video' });
globalThis.CastableVideoElement = CastableVideoElement;
}
CastableVideoElement.initCast();
export default CastableVideoElement;