This repository has been archived by the owner on Sep 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
google-castable-video.html
390 lines (359 loc) · 12.9 KB
/
google-castable-video.html
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
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="google-cast-sender-api.html">
<!-- TODO(tschaeff):
- ratechange to change playbackspeed (if even possible)
-->
<script>
(function() {
// Set static variable for the timeupdate delay.
var _GOOGLE_CASTABLE_VIDEO_TIMEUPDATE_DELAY = 250;
/**
The `google-castable-video` element enables your HTML5 videos to be casted to any Chromecast.
It behaves exactly like an HTML5 video element except for some added methods and events.
Instead of listening for the video element's `timeupdate` event please listen for the `google-castable-video-timeupdate` event. This event is fired if the video is playing locally and on the Chromecast device.
##### Example
<video is="google-castable-video">
<source src="video.mp4" type="video/mp4">
</video>
@demo
*/
Polymer({
is: 'google-castable-video',
extends: 'video',
properties: {
/**
* The appId that references which receiver the Chromecast will load.
*
* @default chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID
*/
appId: {
type: String,
value: null
}
},
listeners: {
'seeked': '_onSeeked',
'volumechange': '_onVolumechange',
'timeupdate': '_onTimeupdate'
},
/**
* The real paused state for local and cast playback.
*
* @property bothPaused
* @type bool
* @default true
*/
_bothPaused: true,
get bothPaused() {
return this._bothPaused;
},
/**
* Sets or returns the current playback position (in seconds).
* Since the local video is paused when the video is playing on the Chromecast device
* the objects currentTime property doesn't represent the actual currentTime of the video
* playing on the Chromecast device. To always get the actual position please use bothCurrentTime.
*
* @property bothCurrentTime
* @type number
* @default 0
*/
get bothCurrentTime() {
if (this._casting && this._castMedia) {
return this._castMedia.getEstimatedTime();
} else {
return this.currentTime;
}
},
set bothCurrentTime(val) {
return this.currentTime = val;
},
/**
* The mode state depending on whether the video is playing locally or on the cast device.
*
* @property casting
* @type bool
* @default false
*/
_casting: false,
get casting() {
return this._casting;
},
/**
* Returns if any Chromecast is available.
*
* @property receiverAvailable
* @type bool
* @default false
*/
_receiverAvailable: false,
get receiverAvailable() {
return this._receiverAvailable;
},
/**
* The `chrome.cast.Media` object.
*
* @property castMedia
* @type chrome.cast.Media
* @default null
*/
_castMedia: null,
get castMedia() {
return this._castMedia;
},
/**
* The `chrome.cast.Session` object.
*
* @property session
* @type chrome.cast.Session
* @default null
*/
_session: null,
get session() {
return this._session;
},
ready: function() {
// Initialize the cast api.
window['__onGCastApiAvailable'] = function(loaded, errorInfo) {
if (loaded) {
this._initializeCastApi();
} else {
this._triggerError('INITIALIZE_ERROR');
}
}.bind(this);
},
// Called internally when the cast sender api has been loaded.
_initializeCastApi: function() {
if (this.appId === null || typeof this.appId === "undefined") {
this.appId = chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID;
// TODO ... process for selecting styled media receiver
}
var sessionRequest = new chrome.cast.SessionRequest(this.appId);
var apiConfig = new chrome.cast.ApiConfig(sessionRequest,
function(e){
// The sessionListener.
this._triggerCasting(true);
this._session = e;
if (this._session.media.length) {
this._onMediaDiscovered.call(this, 'onRequestSessionSuccess', this._session.media[0]);
}
// Bind the session update listener.
this._session.addUpdateListener(this._sessionUpdateListener.bind(this));
// Set interval for cast timeupdate.
this._timeupdateInterval = setInterval(function(){
if (this._castMedia && this._castMedia.playerState === 'PLAYING') {
this._triggerTimeupdate(this._castMedia.getEstimatedTime());
this._bothPaused = false;
} else {
this._bothPaused = true;
}
}.bind(this), _GOOGLE_CASTABLE_VIDEO_TIMEUPDATE_DELAY);
// Start playing on cast if playing locally.
if (!this.paused) {
this.play();
this.pause(false);
}
}.bind(this),
function(e){
// The receiverListener
if (e === chrome.cast.ReceiverAvailability.AVAILABLE) {
this._triggerAvailability(true);
} else {
this._triggerAvailability(false);
}
}.bind(this));
chrome.cast.initialize(apiConfig, function(){
// The onInitSuccess method.
/**
* The `google-castable-video-initialized` event is fired when
* the cast client API has been initialized.
*
* @event google-castable-video-initialized
*/
this.fire('google-castable-video-initialized');
}.bind(this), function(){
this._triggerError('INITIALIZE_ERROR');
});
},
/**
* Call this when the user clicks the cast icon.
* Opens the cast extension to create a session with the selected receiver.
*
* @method launchSessionManager
*/
launchSessionManager: function(){
if (this._receiverAvailable) {
// Create the session with the receiver.
chrome.cast.requestSession(function(e){
// The onRequestSessionSuccess handler gets executed when we're connected.
this._triggerCasting(true);
this._session = e;
this._session.addUpdateListener(this._sessionUpdateListener.bind(this));
// If video is playing start playing on chromecast at same position.
if (!this.paused) {
this.play();
this.pause(false);
}
// Set interval for cast timeupdate.
this._timeupdateInterval = setInterval(function(){
if (this._castMedia && this._castMedia.playerState === 'PLAYING') {
this._triggerTimeupdate(this._castMedia.getEstimatedTime());
this._bothPaused = false;
} else {
this._bothPaused = true;
}
}.bind(this), _GOOGLE_CASTABLE_VIDEO_TIMEUPDATE_DELAY);
}.bind(this));
}
},
// Internal method gets called when the cast session status changes.
_sessionUpdateListener: function(isAlive){
if (!isAlive) {
this._triggerCasting(false);
this._synchronizeMedia(true);
// If video was playing on the receiver start playing locally.
if (this._castMedia.playerState === 'PLAYING') {
this.play();
}
this._castMedia = null;
this._session = null;
// The session died so remove the timeupdate interval.
clearInterval(this._timeupdateInterval);
}
},
// Internal method gets called when media was set through `launchsession`
// or was already playing on cast device.
_onMediaDiscovered: function(how, media) {
this._castMedia = media;
if (how === 'loadMedia') {
this._synchronizeMedia(false);
}
},
// Internal method to synchronize the media objects.
_synchronizeMedia: function(castMaster){
if (castMaster) {
var position = this._castMedia.getEstimatedTime();
this.currentTime = position;
} else {
var position = this.currentTime;
var req = new chrome.cast.media.SeekRequest();
req.currentTime = position;
this._castMedia.seek(req);
}
},
/**
* Call the `play` method from your controls.
*
* @method play
*/
play: function(cast){
if ((cast != undefined && !cast) || (!cast && !this._casting)) {
Object.getPrototypeOf(Object.getPrototypeOf(this)).play.call(this);
// this.super();
} else {
// Handle cast media.
if (!this._castMedia) {
var mediaInfo = new chrome.cast.media.MediaInfo(this.currentSrc);
[].forEach.call( // loop through DOM video sources to find the contentType of the current source
document.querySelectorAll("video source"),
function(el) {
// the HTML5 video API resolves the DOM 'src' attribute to an absolute URL for the value of 'currentSrc'; to make it matchable, then, we can only rely on the last segment of the URL
if (el.getAttribute("src").split('/').pop()===this.currentSrc.split('/').pop()) {
mediaInfo.contentType = el.getAttribute('type');
}
}.bind(this)
);
var request = new chrome.cast.media.LoadRequest(mediaInfo);
this._session.loadMedia(request,
this._onMediaDiscovered.bind(this, 'loadMedia'),
function(e){
this._triggerError('LOAD_MEDIA_ERROR');
}.bind(this)
);
} else {
this._castMedia.play();
}
}
},
/**
* Call the `pause` method from your controls.
*
* @method pause
*/
pause: function(cast){
if ((cast != undefined && !cast) || (!cast && !this._casting)) {
Object.getPrototypeOf(Object.getPrototypeOf(this)).pause.call(this);
// this.super();
} else {
this._castMedia.pause();
}
},
/**
* The `google-castable-video-timeupdate` event is fired whenever
* the video's playback position changes.
*
* @event google-castable-video-timeupdate
* @param {Object} detail
* @param {number} detail.currentTime The current video position.
*/
_triggerTimeupdate: function(position) {
this.fire('google-castable-video-timeupdate', { currentTime: position });
},
/**
* The `google-castable-video-error` event is fired whenever
* an error occurs.
*
* @event google-castable-video-error
* @param {Object} detail
* @param {string} detail.error The error type.
*/
_triggerError: function(description) {
this.fire('google-castable-video-error', { error: description });
},
/**
* The `google-castable-video-receiver-status` event is fired whenever
* the availability of Chromecasts changes. Use this to show or hide the cast icon.
*
* @event google-castable-video-receiver-status
* @param {Object} detail
* @param {bool} detail.available Shows if receivers are available.
*/
_triggerAvailability: function(availability) {
this._receiverAvailable = availability;
this.fire('google-castable-video-receiver-status', { available: availability });
},
/**
* The `google-castable-video-casting` event is fired whenever the
* connection status to a Chromecast changes. Use this to change the cast icon.
*
* @event google-castable-video-casting
* @param {Object} detail
* @param {bool} detail.casting True if connected.
*/
_triggerCasting: function(casting) {
this._casting = casting;
this.fire('google-castable-video-casting', { casting: casting });
},
// Redirecting `seeked` event to Chromecast.
_onSeeked: function(){
if (this._casting) {
var req = new chrome.cast.media.SeekRequest();
req.currentTime = this.currentTime;
this._castMedia.seek(req);
}
},
// Redirecting `volumechange` event to Chromecast.
_onVolumechange: function(){
if (this._casting) {
var volume = new chrome.cast.Volume(this.volume, this.muted);
var volumeRequest = new chrome.cast.media.VolumeRequest(volume);
this._castMedia.setVolume(volumeRequest);
}
},
// Redirecting `timeupdate` event to `google-castable-video-timeupdate`.
_onTimeupdate: function(){
this._triggerTimeupdate(this.currentTime);
this._bothPaused = this.paused;
}
});
})();
</script>