1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 * Interval for updating media info (in ms).
12 var MEDIA_UPDATE_INTERVAL = 250;
15 * The namespace for communication between the cast and the player.
19 var CAST_MESSAGE_NAMESPACE = 'urn:x-cast:com.google.chromeos.videoplayer';
22 * This class is the dummy class which has same interface as VideoElement. This
23 * behaves like VideoElement, and is used for making Chromecast player
24 * controlled instead of the true Video Element tag.
26 * @param {MediaManager} media Media manager with the media to play.
27 * @param {chrome.cast.Session} session Session to play a video on.
30 function CastVideoElement(media, session) {
31 this.mediaManager_ = media;
32 this.mediaInfo_ = null;
34 this.castMedia_ = null;
35 this.castSession_ = session;
36 this.currentTime_ = null;
40 this.currentMediaPlayerState_ = null;
41 this.currentMediaCurrentTime_ = null;
42 this.currentMediaDuration_ = null;
43 this.playInProgress_ = false;
44 this.pauseInProgress_ = false;
47 this.onMessageBound_ = this.onMessage_.bind(this);
48 this.onCastMediaUpdatedBound_ = this.onCastMediaUpdated_.bind(this);
49 this.castSession_.addMessageListener(
50 CAST_MESSAGE_NAMESPACE, this.onMessageBound_);
53 CastVideoElement.prototype = {
54 __proto__: cr.EventTarget.prototype,
57 * Prepares for unloading this objects.
61 this.castSession_.removeMessageListener(
62 CAST_MESSAGE_NAMESPACE, this.onMessageBound_);
66 * Returns a parent node. This must always be null.
74 * The total time of the video (in sec).
78 return this.currentMediaDuration_;
82 * The current timestamp of the video (in sec).
86 if (this.castMedia_) {
87 if (this.castMedia_.idleReason === chrome.cast.media.IdleReason.FINISHED)
88 return this.currentMediaDuration_; // Returns the duration.
90 return this.castMedia_.getEstimatedTime();
95 set currentTime(currentTime) {
96 var seekRequest = new chrome.cast.media.SeekRequest();
97 seekRequest.currentTime = currentTime;
98 this.castMedia_.seek(seekRequest,
100 this.onCastCommandError_.wrap(this));
104 * If this video is pauses or not.
108 if (!this.castMedia_)
111 return !this.playInProgress_ &&
112 (this.pauseInProgress_ ||
113 this.castMedia_.playerState === chrome.cast.media.PlayerState.PAUSED);
117 * If this video is ended or not.
121 if (!this.castMedia_)
124 return !this.playInProgress &&
125 this.castMedia_.idleReason === chrome.cast.media.IdleReason.FINISHED;
129 * TimeRange object that represents the seekable ranges of the media
136 start: function(index) { return 0; },
137 end: function(index) { return this.currentMediaDuration_; },
142 * Value of the volume
146 return this.castSession_.receiver.volume.muted ?
148 this.castSession_.receiver.volume.level;
151 var VOLUME_EPS = 0.01; // Threshold for ignoring a small change.
154 if (this.castSession_.receiver.volume.muted) {
155 if (volume < VOLUME_EPS)
158 // Unmute before setting volume.
159 this.castSession_.setReceiverMuted(false,
161 this.onCastCommandError_.wrap(this));
163 this.castSession_.setReceiverVolumeLevel(volume,
165 this.onCastCommandError_.wrap(this));
167 // Ignores < 1% change.
168 var diff = this.castSession_.receiver.volume.level - volume;
169 if (Math.abs(diff) < VOLUME_EPS)
172 if (volume < VOLUME_EPS) {
173 this.castSession_.setReceiverMuted(true,
175 this.onCastCommandError_.wrap(this));
179 this.castSession_.setReceiverVolumeLevel(volume,
181 this.onCastCommandError_.wrap(this));
186 * Returns the source of the current video.
197 * Returns the flag if the video loops at end or not.
204 this.loop_ = !!value;
208 * Returns the error object if available.
212 if (this.errorCode_ === 0)
215 return {code: this.errorCode_};
222 var play = function() {
223 this.castMedia_.play(null,
225 this.playInProgress_ = false;
228 this.playInProgress_ = false;
229 this.onCastCommandError_(error);
233 this.playInProgress_ = true;
235 if (!this.castMedia_)
245 if (!this.castMedia_)
248 this.pauseInProgress_ = true;
249 this.castMedia_.pause(null,
251 this.pauseInProgress_ = false;
254 this.pauseInProgress_ = false;
255 this.onCastCommandError_(error);
262 load: function(opt_callback) {
263 var sendTokenPromise = this.mediaManager_.getToken().then(function(token) {
265 this.sendMessage_({message: 'push-token', token: token});
268 // Resets the error code.
273 this.mediaManager_.getUrl(),
274 this.mediaManager_.getMime(),
275 this.mediaManager_.getThumbnail()]).
276 then(function(results) {
277 var url = results[1];
278 var mime = results[2]; // maybe empty
279 var thumbnailUrl = results[3]; // maybe empty
281 this.mediaInfo_ = new chrome.cast.media.MediaInfo(url);
282 this.mediaInfo_.contentType = mime;
283 this.mediaInfo_.customData = {
285 thumbnailUrl: thumbnailUrl,
288 var request = new chrome.cast.media.LoadRequest(this.mediaInfo_);
290 this.castSession_.loadMedia.bind(this.castSession_, request)).
291 then(function(media) {
292 this.onMediaDiscovered_(media);
296 }.bind(this)).catch(function(error) {
298 this.dispatchEvent(new Event('error'));
299 console.error('Cast failed.', error.stack || error);
307 unloadMedia_: function() {
308 if (this.castMedia_) {
309 this.castMedia_.stop(null,
312 // Ignores session error, since session may already be closed.
313 if (error.code !== chrome.cast.ErrorCode.SESSION_ERROR)
314 this.onCastCommandError_(error);
317 this.castMedia_.removeUpdateListener(this.onCastMediaUpdatedBound_);
318 this.castMedia_ = null;
321 clearInterval(this.updateTimerId_);
325 * Sends the message to cast.
326 * @param {Object} message Message to be sent (Must be JSON-able object).
329 sendMessage_: function(message) {
330 this.castSession_.sendMessage(CAST_MESSAGE_NAMESPACE, message);
334 * Invoked when receiving a message from the cast.
335 * @param {string} namespace Namespace of the message.
336 * @param {string} messageAsJson Content of message as json format.
339 onMessage_: function(namespace, messageAsJson) {
340 if (namespace !== CAST_MESSAGE_NAMESPACE || !messageAsJson)
343 var message = JSON.parse(messageAsJson);
344 if (message['message'] === 'request-token') {
345 if (message['previousToken'] === this.token_) {
346 this.mediaManager_.getToken(true).then(function(token) {
348 this.sendMessage_({message: 'push-token', token: token});
349 // TODO(yoshiki): Revokes the previous token.
350 }.bind(this)).catch(function(error) {
351 // Send an empty token as an error.
352 this.sendMessage_({message: 'push-token', token: ''});
353 // TODO(yoshiki): Revokes the previous token.
354 console.error(error.stack || error);
358 'New token is requested, but the previous token mismatches.');
360 } else if (message['message'] === 'playback-error') {
361 if (message['detail'] === 'src-not-supported')
362 this.errorCode_ = MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED;
367 * This method is called periodically to update media information while the
371 onPeriodicalUpdateTimer_: function() {
372 if (!this.castMedia_)
375 if (this.castMedia_.playerState === chrome.cast.media.PlayerState.PLAYING)
376 this.onCastMediaUpdated_(true);
380 * This method should be called when a media file is loaded.
381 * @param {chrome.cast.Media} media Media object which was discovered.
384 onMediaDiscovered_: function(media) {
385 if (this.castMedia_ !== null) {
387 console.info('New media is found and the old media is overridden.');
390 this.castMedia_ = media;
391 this.onCastMediaUpdated_(true);
392 // Notify that the metadata of the video is ready.
393 this.dispatchEvent(new Event('loadedmetadata'));
395 media.addUpdateListener(this.onCastMediaUpdatedBound_);
396 this.updateTimerId_ = setInterval(this.onPeriodicalUpdateTimer_.bind(this),
397 MEDIA_UPDATE_INTERVAL);
401 * This method should be called when a media command to cast is failed.
402 * @param {Object} error Object representing the error.
405 onCastCommandError_: function(error) {
407 this.dispatchEvent(new Event('error'));
408 console.error('Error on sending command to cast.', error.stack || error);
412 * This is called when any media data is updated and by the periodical timer
415 * @param {boolean} alive Media availability. False if it's unavailable.
418 onCastMediaUpdated_: function(alive) {
419 if (!this.castMedia_)
422 var media = this.castMedia_;
424 media.idleReason === chrome.cast.media.IdleReason.FINISHED &&
426 // Resets the previous media silently.
427 this.castMedia_ = null;
429 // Replay the current media.
430 this.currentMediaPlayerState_ = chrome.cast.media.PlayerState.BUFFERING;
431 this.currentMediaCurrentTime_ = 0;
432 this.dispatchEvent(new Event('play'));
433 this.dispatchEvent(new Event('timeupdate'));
438 if (this.currentMediaPlayerState_ !== media.playerState) {
439 var oldPlayState = false;
440 var oldState = this.currentMediaPlayerState_;
441 if (oldState === chrome.cast.media.PlayerState.BUFFERING ||
442 oldState === chrome.cast.media.PlayerState.PLAYING) {
445 var newPlayState = false;
446 var newState = media.playerState;
447 if (newState === chrome.cast.media.PlayerState.BUFFERING ||
448 newState === chrome.cast.media.PlayerState.PLAYING) {
451 if (!oldPlayState && newPlayState)
452 this.dispatchEvent(new Event('play'));
453 if (oldPlayState && !newPlayState)
454 this.dispatchEvent(new Event('pause'));
456 this.currentMediaPlayerState_ = newState;
458 if (this.currentMediaCurrentTime_ !== media.getEstimatedTime()) {
459 this.currentMediaCurrentTime_ = media.getEstimatedTime();
460 this.dispatchEvent(new Event('timeupdate'));
463 if (this.currentMediaDuration_ !== media.media.duration) {
464 this.currentMediaDuration_ = media.media.duration;
465 this.dispatchEvent(new Event('durationchange'));
468 // Media is being unloaded.