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-mixin.js
300 lines (252 loc) · 8.26 KB
/
castable-mixin.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
/* global chrome */
import { RemotePlayback } from './castable-remote-playback.js';
import {
privateProps,
requiresCastFramework,
loadCastFramework,
currentSession,
getDefaultCastOptions
} from './castable-utils.js';
/**
* CastableMediaMixin
*
* This mixin function provides a way to compose multiple classes.
* @see https://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/
*
* @param {HTMLMediaElement} superclass - HTMLMediaElement or an extended class of it.
* @return {CastableMedia}
*/
export const CastableMediaMixin = (superclass) =>
class CastableMedia extends superclass {
static observedAttributes = [
...(superclass.observedAttributes ?? []),
'cast-src',
'cast-content-type',
'cast-stream-type',
'cast-receiver',
];
#localState = { paused: false };
#castOptions = getDefaultCastOptions();
#remote;
get remote() {
if (this.#remote) return this.#remote;
if (requiresCastFramework()) {
loadCastFramework();
privateProps.set(this, {
loadOnPrompt: () => this.#loadOnPrompt()
});
return (this.#remote = new RemotePlayback(this));
}
return super.remote;
}
get #castPlayer() {
return privateProps.get(this.remote)?.getCastPlayer?.();
}
attributeChangedCallback(attrName, oldValue, newValue) {
super.attributeChangedCallback(attrName, oldValue, newValue);
if (attrName === 'cast-receiver' && newValue) {
this.#castOptions.receiverApplicationId = newValue;
return;
}
if (!this.#castPlayer) return;
switch (attrName) {
case 'cast-stream-type':
case 'cast-src':
this.load();
break;
}
}
async #loadOnPrompt() {
// 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.castContentType);
// Manually add text tracks with a `src` attribute.
// M3U8's load text tracks in the receiver, handle these in the media loaded event.
const subtitles = [...this.querySelectorAll('track')].filter(
({ kind, src }) => src && (kind === 'subtitles' || kind === 'captions')
);
const activeTrackIds = [];
let textTrackIdCount = 0;
if (subtitles.length) {
mediaInfo.tracks = subtitles.map((trackEl) => {
const trackId = ++textTrackIdCount;
// only activate 1 subtitle text track.
if (activeTrackIds.length === 0 && trackEl.track.mode === 'showing') {
activeTrackIds.push(trackId);
}
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.castStreamType === '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;
request.activeTrackIds = activeTrackIds;
await currentSession()?.loadMedia(request);
this.dispatchEvent(new Event('volumechange'));
}
play() {
if (this.#castPlayer) {
if (this.#castPlayer.isPaused) {
this.#castPlayer.controller?.playOrPause();
}
return;
}
return super.play();
}
pause() {
if (this.#castPlayer) {
if (!this.#castPlayer.isPaused) {
this.#castPlayer.controller?.playOrPause();
}
return;
}
super.pause();
}
/**
* @see https://developers.google.com/cast/docs/reference/web_sender/cast.framework.CastOptions
* @readonly
*
* @typedef {Object} CastOptions
* @property {string} [receiverApplicationId='CC1AD845'] - The app id of the cast receiver.
* @property {string} [autoJoinPolicy='origin_scoped'] - The auto join policy.
* @property {string} [language='en-US'] - The language to use for the cast receiver.
* @property {boolean} [androidReceiverCompatible=false] - Whether to use the Cast Connect.
* @property {boolean} [resumeSavedSession=true] - Whether to resume the last session.
*
* @return {CastOptions}
*/
get castOptions() {
return this.#castOptions;
}
get castReceiver() {
return this.getAttribute('cast-receiver') ?? undefined;
}
set castReceiver(val) {
if (this.castReceiver == val) return;
this.setAttribute('cast-receiver', `${val}`);
}
// 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 castContentType() {
return this.getAttribute('cast-content-type') ?? undefined;
}
set castContentType(val) {
this.setAttribute('cast-content-type', `${val}`);
}
get castStreamType() {
// NOTE: Per https://github.com/video-dev/media-ui-extensions/issues/3 `streamType` may yield `"unknown"`
return this.getAttribute('cast-stream-type') ?? this.streamType ?? undefined;
}
set castStreamType(val) {
this.setAttribute('cast-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.#castPlayer?.isMediaLoaded) {
return this.#castPlayer?.duration ?? NaN;
}
return super.duration;
}
get currentTime() {
if (this.#castPlayer && this.#castPlayer?.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;
}
};
export const CastableVideoMixin = CastableMediaMixin;