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 * @param {Element} playerContainer Main container.
9 * @param {Element} videoContainer Container for the video element.
10 * @param {Element} controlsContainer Container for video controls.
13 function FullWindowVideoControls(
14 playerContainer, videoContainer, controlsContainer) {
15 VideoControls.call(this,
17 this.onPlaybackError_.wrap(this),
18 loadTimeData.getString.wrap(loadTimeData),
19 this.toggleFullScreen_.wrap(this),
22 this.playerContainer_ = playerContainer;
23 this.decodeErrorOccured = false;
28 window.addEventListener('resize', this.updateStyle.wrap(this));
29 document.addEventListener('keydown', function(e) {
30 switch (e.keyIdentifier) {
31 case 'U+0020': // Space
32 case 'MediaPlayPause':
33 this.togglePlayStateWithFeedback();
35 case 'U+001B': // Escape
36 util.toggleFullScreen(
37 chrome.app.window.current(),
38 false); // Leave the full screen mode.
41 case 'MediaNextTrack':
45 case 'MediaPreviousTrack':
49 // TODO: Define "Stop" behavior.
54 // TODO(mtomasz): Simplify. crbug.com/254318.
55 var clickInProgress = false;
56 videoContainer.addEventListener('click', function(e) {
60 clickInProgress = true;
61 var togglePlayState = function() {
62 clickInProgress = false;
65 this.toggleLoopedModeWithFeedback(true);
66 if (!this.isPlaying())
67 this.togglePlayStateWithFeedback();
69 this.togglePlayStateWithFeedback();
74 player.reloadCurrentVideo(togglePlayState);
76 setTimeout(togglePlayState);
79 this.inactivityWatcher_ = new MouseInactivityWatcher(playerContainer);
80 this.__defineGetter__('inactivityWatcher', function() {
81 return this.inactivityWatcher_;
84 this.inactivityWatcher_.check();
87 FullWindowVideoControls.prototype = { __proto__: VideoControls.prototype };
90 * Displays error message.
92 * @param {string} message Message id.
94 FullWindowVideoControls.prototype.showErrorMessage = function(message) {
95 var errorBanner = document.querySelector('#error');
96 errorBanner.textContent = loadTimeData.getString(message);
97 errorBanner.setAttribute('visible', 'true');
99 // The window is hidden if the video has not loaded yet.
100 chrome.app.window.current().show();
104 * Handles playback (decoder) errors.
105 * @param {MediaError} error Error object.
108 FullWindowVideoControls.prototype.onPlaybackError_ = function(error) {
109 if (error.target && error.target.error &&
110 error.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) {
112 this.showErrorMessage('VIDEO_PLAYER_VIDEO_FILE_UNSUPPORTED_FOR_CAST');
114 this.showErrorMessage('GALLERY_VIDEO_ERROR');
115 this.decodeErrorOccured = false;
117 this.showErrorMessage('GALLERY_VIDEO_DECODING_ERROR');
118 this.decodeErrorOccured = true;
121 // Disable inactivity watcher, and disable the ui, by hiding tools manually.
122 this.inactivityWatcher.disabled = true;
123 document.querySelector('#video-player').setAttribute('disabled', 'true');
125 // Detach the video element, since it may be unreliable and reset stored
126 // current playback time.
130 // Avoid reusing a video element.
131 player.unloadVideo();
135 * Toggles the full screen mode.
138 FullWindowVideoControls.prototype.toggleFullScreen_ = function() {
139 var appWindow = chrome.app.window.current();
140 util.toggleFullScreen(appWindow, !util.isFullScreen(appWindow));
144 * Media completion handler.
146 FullWindowVideoControls.prototype.onMediaComplete = function() {
147 VideoControls.prototype.onMediaComplete.apply(this, arguments);
148 if (!this.getMedia().loop)
155 function VideoPlayer() {
156 this.controls_ = null;
157 this.videoElement_ = null;
159 this.currentPos_ = 0;
161 this.currentSession_ = null;
162 this.currentCast_ = null;
164 this.loadQueue_ = new AsyncUtil.Queue();
166 this.onCastSessionUpdateBound_ = this.onCastSessionUpdate_.wrap(this);
171 VideoPlayer.prototype = {
173 return this.controls_;
178 * Initializes the video player window. This method must be called after DOM
180 * @param {Array.<Object.<string, Object>>} videos List of videos.
182 VideoPlayer.prototype.prepare = function(videos) {
183 this.videos_ = videos;
185 var preventDefault = function(event) { event.preventDefault(); }.wrap(null);
187 document.ondragstart = preventDefault;
189 var maximizeButton = document.querySelector('.maximize-button');
190 maximizeButton.addEventListener(
193 var appWindow = chrome.app.window.current();
194 if (appWindow.isMaximized())
197 appWindow.maximize();
198 event.stopPropagation();
200 maximizeButton.addEventListener('mousedown', preventDefault);
202 var minimizeButton = document.querySelector('.minimize-button');
203 minimizeButton.addEventListener(
206 chrome.app.window.current().minimize();
207 event.stopPropagation();
209 minimizeButton.addEventListener('mousedown', preventDefault);
211 var closeButton = document.querySelector('.close-button');
212 closeButton.addEventListener(
216 event.stopPropagation();
218 closeButton.addEventListener('mousedown', preventDefault);
220 var menu = document.querySelector('#cast-menu');
221 cr.ui.decorate(menu, cr.ui.Menu);
223 this.controls_ = new FullWindowVideoControls(
224 document.querySelector('#video-player'),
225 document.querySelector('#video-container'),
226 document.querySelector('#controls'));
228 var reloadVideo = function(e) {
229 if (this.controls_.decodeErrorOccured &&
230 // Ignore shortcut keys
231 !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {
232 this.reloadCurrentVideo(function() {
233 this.videoElement_.play();
239 var arrowRight = document.querySelector('.arrow-box .arrow.right');
240 arrowRight.addEventListener('click', this.advance_.wrap(this, 1));
241 var arrowLeft = document.querySelector('.arrow-box .arrow.left');
242 arrowLeft.addEventListener('click', this.advance_.wrap(this, 0));
244 var videoPlayerElement = document.querySelector('#video-player');
245 if (videos.length > 1)
246 videoPlayerElement.setAttribute('multiple', true);
248 videoPlayerElement.removeAttribute('multiple');
250 document.addEventListener('keydown', reloadVideo);
251 document.addEventListener('click', reloadVideo);
255 * Unloads the player.
258 // Releases keep awake just in case (should be released on unloading video).
259 chrome.power.releaseKeepAwake();
261 if (!player.controls || !player.controls.getMedia())
264 player.controls.savePosition(true /* exiting */);
265 player.controls.cleanup();
269 * Loads the video file.
270 * @param {Object} video Data of the video file.
271 * @param {function()=} opt_callback Completion callback.
274 VideoPlayer.prototype.loadVideo_ = function(video, opt_callback) {
275 this.unloadVideo(true);
277 this.loadQueue_.run(function(callback) {
278 document.title = video.title;
280 document.querySelector('#title').innerText = video.title;
282 var videoPlayerElement = document.querySelector('#video-player');
283 if (this.currentPos_ === (this.videos_.length - 1))
284 videoPlayerElement.setAttribute('last-video', true);
286 videoPlayerElement.removeAttribute('last-video');
288 if (this.currentPos_ === 0)
289 videoPlayerElement.setAttribute('first-video', true);
291 videoPlayerElement.removeAttribute('first-video');
293 // Re-enables ui and hides error message if already displayed.
294 document.querySelector('#video-player').removeAttribute('disabled');
295 document.querySelector('#error').removeAttribute('visible');
296 this.controls.detachMedia();
297 this.controls.inactivityWatcher.disabled = true;
298 this.controls.decodeErrorOccured = false;
299 this.controls.casting = !!this.currentCast_;
301 videoPlayerElement.setAttribute('loading', true);
303 var media = new MediaManager(video.entry);
305 Promise.all([media.getThumbnail(), media.getToken()])
306 .then(function(results) {
307 var url = results[0];
308 var token = results[1];
310 document.querySelector('#thumbnail').style.backgroundImage =
311 'url(' + url + '&access_token=' + token + ')';
313 document.querySelector('#thumbnail').style.backgroundImage = '';
317 // Shows no image on error.
318 document.querySelector('#thumbnail').style.backgroundImage = '';
321 var videoElementInitializePromise;
322 if (this.currentCast_) {
323 videoPlayerElement.setAttribute('casting', true);
325 document.querySelector('#cast-name').textContent =
326 this.currentCast_.friendlyName;
328 videoPlayerElement.setAttribute('castable', true);
330 videoElementInitializePromise = media.isAvailableForCast()
331 .then(function(result) {
333 return Promise.reject('No casts are available.');
335 return new Promise(function(fulfill, reject) {
336 chrome.cast.requestSession(
337 fulfill, reject, undefined, this.currentCast_.label);
338 }.bind(this)).then(function(session) {
339 session.addUpdateListener(this.onCastSessionUpdateBound_);
341 this.currentSession_ = session;
342 this.videoElement_ = new CastVideoElement(media, session);
343 this.controls.attachMedia(this.videoElement_);
347 videoPlayerElement.removeAttribute('casting');
349 this.videoElement_ = document.createElement('video');
350 document.querySelector('#video-container').appendChild(
353 this.controls.attachMedia(this.videoElement_);
354 this.videoElement_.src = video.url;
356 media.isAvailableForCast().then(function(result) {
358 videoPlayerElement.setAttribute('castable', true);
360 videoPlayerElement.removeAttribute('castable');
361 }).catch(function() {
362 videoPlayerElement.setAttribute('castable', true);
365 videoElementInitializePromise = Promise.resolve();
368 videoElementInitializePromise
370 var handler = function(currentPos) {
371 if (currentPos === this.currentPos_) {
374 videoPlayerElement.removeAttribute('loading');
375 this.controls.inactivityWatcher.disabled = false;
378 this.videoElement_.removeEventListener('loadedmetadata', handler);
379 }.wrap(this, this.currentPos_);
381 this.videoElement_.addEventListener('loadedmetadata', handler);
383 this.videoElement_.addEventListener('play', function() {
384 chrome.power.requestKeepAwake('display');
386 this.videoElement_.addEventListener('pause', function() {
387 chrome.power.releaseKeepAwake();
390 this.videoElement_.load();
394 .catch(function(error) {
395 videoPlayerElement.removeAttribute('loading');
396 console.error('Failed to initialize the video element.',
397 error.stack || error);
398 this.controls_.showErrorMessage('GALLERY_VIDEO_ERROR');
405 * Plays the first video.
407 VideoPlayer.prototype.playFirstVideo = function() {
408 this.currentPos_ = 0;
409 this.reloadCurrentVideo(this.onFirstVideoReady_.wrap(this));
413 * Unloads the current video.
414 * @param {boolean=} opt_keepSession If true, keep using the current session.
415 * Otherwise, discards the session.
417 VideoPlayer.prototype.unloadVideo = function(opt_keepSession) {
418 this.loadQueue_.run(function(callback) {
419 chrome.power.releaseKeepAwake();
421 if (this.videoElement_) {
422 // If the element has dispose method, call it (CastVideoElement has it).
423 if (this.videoElement_.dispose)
424 this.videoElement_.dispose();
425 // Detach the previous video element, if exists.
426 if (this.videoElement_.parentNode)
427 this.videoElement_.parentNode.removeChild(this.videoElement_);
429 this.videoElement_ = null;
431 if (!opt_keepSession && this.currentSession_) {
432 this.currentSession_.stop(callback, callback);
433 this.currentSession_.removeUpdateListener(this.onCastSessionUpdateBound_);
434 this.currentSession_ = null;
442 * Called when the first video is ready after starting to load.
445 VideoPlayer.prototype.onFirstVideoReady_ = function() {
446 var videoWidth = this.videoElement_.videoWidth;
447 var videoHeight = this.videoElement_.videoHeight;
449 var aspect = videoWidth / videoHeight;
450 var newWidth = videoWidth;
451 var newHeight = videoHeight;
453 var shrinkX = newWidth / window.screen.availWidth;
454 var shrinkY = newHeight / window.screen.availHeight;
455 if (shrinkX > 1 || shrinkY > 1) {
456 if (shrinkY > shrinkX) {
457 newHeight = newHeight / shrinkY;
458 newWidth = newHeight * aspect;
460 newWidth = newWidth / shrinkX;
461 newHeight = newWidth / aspect;
465 var oldLeft = window.screenX;
466 var oldTop = window.screenY;
467 var oldWidth = window.outerWidth;
468 var oldHeight = window.outerHeight;
470 if (!oldWidth && !oldHeight) {
471 oldLeft = window.screen.availWidth / 2;
472 oldTop = window.screen.availHeight / 2;
475 var appWindow = chrome.app.window.current();
476 appWindow.resizeTo(newWidth, newHeight);
477 appWindow.moveTo(oldLeft - (newWidth - oldWidth) / 2,
478 oldTop - (newHeight - oldHeight) / 2);
481 this.videoElement_.play();
485 * Advances to the next (or previous) track.
487 * @param {boolean} direction True to the next, false to the previous.
490 VideoPlayer.prototype.advance_ = function(direction) {
491 var newPos = this.currentPos_ + (direction ? 1 : -1);
492 if (0 <= newPos && newPos < this.videos_.length) {
493 this.currentPos_ = newPos;
494 this.reloadCurrentVideo(function() {
495 this.videoElement_.play();
501 * Reloads the current video.
503 * @param {function()=} opt_callback Completion callback.
505 VideoPlayer.prototype.reloadCurrentVideo = function(opt_callback) {
506 var currentVideo = this.videos_[this.currentPos_];
507 this.loadVideo_(currentVideo, opt_callback);
511 * Invokes when a menuitem in the cast menu is selected.
512 * @param {Object} cast Selected element in the list of casts.
515 VideoPlayer.prototype.onCastSelected_ = function(cast) {
516 // If the selected item is same as the current item, do nothing.
517 if ((this.currentCast_ && this.currentCast_.label) === (cast && cast.label))
520 this.unloadVideo(false);
522 // Waits for unloading video.
523 this.loadQueue_.run(function(callback) {
524 this.currentCast_ = cast || null;
525 this.updateCheckOnCastMenu_();
526 this.reloadCurrentVideo();
532 * Set the list of casts.
533 * @param {Array.<Object>} casts List of casts.
535 VideoPlayer.prototype.setCastList = function(casts) {
536 var videoPlayerElement = document.querySelector('#video-player');
537 var menu = document.querySelector('#cast-menu');
540 // TODO(yoshiki): Handle the case that the current cast disappears.
542 if (casts.length === 0) {
543 videoPlayerElement.removeAttribute('cast-available');
544 if (this.currentCast_)
545 this.onCurrentCastDisappear_();
549 if (this.currentCast_) {
550 var currentCastAvailable = casts.some(function(cast) {
551 return this.currentCast_.label === cast.label;
554 if (!currentCastAvailable)
555 this.onCurrentCastDisappear_();
558 var item = new cr.ui.MenuItem();
559 item.label = loadTimeData.getString('VIDEO_PLAYER_PLAY_THIS_COMPUTER');
560 item.setAttribute('aria-label', item.label);
562 item.addEventListener('activate', this.onCastSelected_.wrap(this, null));
563 menu.appendChild(item);
565 for (var i = 0; i < casts.length; i++) {
566 var item = new cr.ui.MenuItem();
567 item.label = casts[i].friendlyName;
568 item.setAttribute('aria-label', item.label);
569 item.castLabel = casts[i].label;
570 item.addEventListener('activate',
571 this.onCastSelected_.wrap(this, casts[i]));
572 menu.appendChild(item);
574 this.updateCheckOnCastMenu_();
575 videoPlayerElement.setAttribute('cast-available', true);
579 * Updates the check status of the cast menu items.
582 VideoPlayer.prototype.updateCheckOnCastMenu_ = function() {
583 var menu = document.querySelector('#cast-menu');
584 var menuItems = menu.menuItems;
585 for (var i = 0; i < menuItems.length; i++) {
586 var item = menuItems[i];
587 if (this.currentCast_ === null) {
588 // Playing on this computer.
589 if (item.castLabel === '')
592 item.checked = false;
594 // Playing on cast device.
595 if (item.castLabel === this.currentCast_.label)
598 item.checked = false;
604 * Called when the current cast is disappear from the cast list.
607 VideoPlayer.prototype.onCurrentCastDisappear_ = function() {
608 this.currentCast_ = null;
609 if (this.currentSession_) {
610 this.currentSession_.removeUpdateListener(this.onCastSessionUpdateBound_);
611 this.currentSession_ = null;
613 this.controls.showErrorMessage('GALLERY_VIDEO_DECODING_ERROR');
618 * This method should be called when the session is updated.
619 * @param {boolean} alive Whether the session is alive or not.
622 VideoPlayer.prototype.onCastSessionUpdate_ = function(alive) {
628 * Initialize the list of videos.
629 * @param {function(Array.<Object>)} callback Called with the video list when
632 function initVideos(callback) {
634 var videos = window.videos;
635 window.videos = null;
640 chrome.runtime.onMessage.addListener(
641 function(request, sender, sendResponse) {
642 var videos = window.videos;
643 window.videos = null;
648 var player = new VideoPlayer();
651 * Initializes the strings.
652 * @param {function()} callback Called when the sting data is ready.
654 function initStrings(callback) {
655 chrome.fileManagerPrivate.getStrings(function(strings) {
656 loadTimeData.data = strings;
657 i18nTemplate.process(document, loadTimeData);
662 var initPromise = Promise.all(
663 [new Promise(initVideos.wrap(null)),
664 new Promise(initStrings.wrap(null)),
665 new Promise(util.addPageLoadHandler.wrap(null))]);
667 initPromise.then(function(results) {
668 var videos = results[0];
669 player.prepare(videos);
670 return new Promise(player.playFirstVideo.wrap(player));