Source: ui/vr_webgl.js

/*! @license
 * Shaka Player
 * Copyright 2016 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */


goog.provide('shaka.ui.VRWebgl');

goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.Player');
goog.require('shaka.ui.Matrix4x4');
goog.require('shaka.ui.MatrixQuaternion');
goog.require('shaka.ui.VRUtils');
goog.require('shaka.util.EventManager');
goog.require('shaka.util.IReleasable');
goog.require('shaka.util.MediaReadyState');
goog.require('shaka.util.Timer');
goog.require('shaka.util.VideoFrameCallbackHandler');


/**
 * @implements {shaka.util.IReleasable}
 */
shaka.ui.VRWebgl = class {
  /**
   * @param {!HTMLMediaElement} video
   * @param {!shaka.Player} player
   * @param {!HTMLCanvasElement} canvas
   * @param {WebGLRenderingContext} gl
   * @param {string} projectionMode
   * @param {number=} hfov Horizontal field of view of the content, in
   *   degrees. Only used by the fisheye projection.
   */
  constructor(video, player, canvas, gl, projectionMode, hfov = 180) {
    /** @private {!HTMLVideoElement} */
    this.video_ = /** @type {!HTMLVideoElement} */ (video);

    /** @private {shaka.Player} */
    this.player_ = player;

    /** @private {HTMLCanvasElement} */
    this.canvas_ = canvas;

    /** @private {WebGLRenderingContext} */
    this.gl_ = gl;

    /** @private {shaka.util.EventManager} */
    this.eventManager_ = new shaka.util.EventManager();

    /** @private {!Float32Array} */
    this.originalQuaternion_ = shaka.ui.MatrixQuaternion.create();

    /** @private {!Float32Array} */
    this.currentQuaternion_ = shaka.ui.MatrixQuaternion.create();

    /**
     * The direction of the initial view, used as the north.
     * @private {!Array<number>}
     */
    this.initialForward_ = [0, 0, -1];

    /** @private {?WebGLProgram} */
    this.shaderProgram_ = null;

    /** @private {!Array<!WebGLShader>} */
    this.shaders_ = [];

    /** @private {?WebGLBuffer} */
    this.verticesBuffer_ = null;

    /** @private {?WebGLBuffer} */
    this.verticesTextureCoordBuffer_ = null;

    /** @private {?WebGLBuffer} */
    this.verticesIndexBuffer_ = null;

    /** @private {!Float32Array} */
    this.viewMatrix_ = shaka.ui.Matrix4x4.create();

    /** @private {!Float32Array} */
    this.projectionMatrix_ = shaka.ui.Matrix4x4.create();

    /** @private {!Float32Array} */
    this.viewProjectionMatrix_ = shaka.ui.Matrix4x4.create();

    /** @private {!Float32Array} */
    this.identityMatrix_ = shaka.ui.Matrix4x4.create();

    /**
     * Reused by rotateViewGlobal, which runs for every pointer move and
     * device orientation event.
     * @private {!Float32Array}
     */
    this.rotationMatrix_ = shaka.ui.Matrix4x4.create();

    /** @private {?Float32Array} */
    this.diff_ = null;

    /** @private {boolean} */
    this.stereoscopicMode_ = false;

    /**
     * How the views of each eye are stored in the video frames.
     * @private {shaka.ui.VRWebgl.StereoLayout}
     */
    this.stereoLayout_ = shaka.ui.VRWebgl.StereoLayout.MONO;

    /**
     * The animation frame that renders the video while it plays, when the
     * browser does not support requestVideoFrameCallback.
     * @private {?number}
     */
    this.animationFrameId_ = null;

    /**
     * The time of the last frame uploaded by the animation frame loop.
     * @private {number}
     */
    this.lastFrameTime_ = -1;

    /** @private {?shaka.util.Timer} */
    this.resetTimer_ = null;

    /** @private {number} */
    this.previousCanvasWidth_ = 0;

    /** @private {number} */
    this.previousCanvasHeight_ = 0;

    /**
     * @private {?{vertices: !Array<number>, textureCoords: !Array<number>,
     *           indices: !Array<number>}}
     */
    this.geometry_ = null;

    /** @private {?number} */
    this.vertexPositionAttribute_ = null;

    /** @private {?number} */
    this.textureCoordAttribute_ = null;

    /** @private {?WebGLUniformLocation} */
    this.samplerUniform_ = null;

    /** @private {?WebGLUniformLocation} */
    this.eyeRectUniform_ = null;

    /** @private {?WebGLUniformLocation} */
    this.eyeClampUniform_ = null;

    /** @private {?WebGLUniformLocation} */
    this.vpMatrixUniform_ = null;

    /** @private {?WebGLUniformLocation} */
    this.projectionMatrixUniform_ = null;

    /** @private {?WebGLUniformLocation} */
    this.modelViewMatrixUniform_ = null;

    /** @private {?WebGLTexture} */
    this.texture_ = null;

    /** @private {number} */
    this.positionX_ = 0;

    /** @private {number} */
    this.positionY_ = 0;

    /** @private {number} */
    this.fieldOfView_ = 75;

    /** @private {number} */
    this.cont_ = 0;

    /** @private {string} */
    this.projectionMode_ = projectionMode;

    /** @private {number} */
    this.hfov_ = hfov;

    /** @private {?shaka.util.VideoFrameCallbackHandler} */
    this.videoFrameCallbackHandler_ =
        new shaka.util.VideoFrameCallbackHandler(this.video_);

    this.init_();
  }

  /**
   * @override
   */
  release() {
    this.videoFrameCallbackHandler_?.release();
    this.videoFrameCallbackHandler_ = null;

    this.eventManager_?.release();
    this.eventManager_ = null;

    this.stopAnimationFrames_();

    this.resetTimer_?.stop();
    this.resetTimer_ = null;

    // The context is shared with the next instance, so delete the resources
    // of this one.
    this.deleteGLResources_();
  }

  /**
   * Recreates the WebGL resources after the context was restored.  The view
   * (orientation, field of view and stereoscopic mode) is kept.
   */
  restoreContext() {
    // The resources of the lost context are no longer valid.
    this.shaderProgram_ = null;
    this.shaders_ = [];
    this.verticesBuffer_ = null;
    this.verticesTextureCoordBuffer_ = null;
    this.verticesIndexBuffer_ = null;
    this.texture_ = null;
    // Size the canvas and the viewport again.
    this.previousCanvasWidth_ = 0;
    this.previousCanvasHeight_ = 0;
    this.initGLResources_();
    this.renderGL_();
  }

  /**
   * @private
   */
  deleteGLResources_() {
    const gl = this.gl_;
    if (this.shaderProgram_) {
      gl.deleteProgram(this.shaderProgram_);
      this.shaderProgram_ = null;
    }
    for (const shader of this.shaders_) {
      gl.deleteShader(shader);
    }
    this.shaders_ = [];
    for (const buffer of [
      this.verticesBuffer_,
      this.verticesTextureCoordBuffer_,
      this.verticesIndexBuffer_,
    ]) {
      if (buffer) {
        gl.deleteBuffer(buffer);
      }
    }
    this.verticesBuffer_ = null;
    this.verticesTextureCoordBuffer_ = null;
    this.verticesIndexBuffer_ = null;
    if (this.texture_) {
      gl.deleteTexture(this.texture_);
      this.texture_ = null;
    }
  }

  /**
   * @return {string}
   */
  getProjectionMode() {
    return this.projectionMode_;
  }

  /**
   * @return {number}
   */
  getHfov() {
    return this.hfov_;
  }

  /**
   * Toggle stereoscopic mode
   */
  toggleStereoscopicMode() {
    this.stereoscopicMode_ = !this.stereoscopicMode_;
    if (!this.stereoscopicMode_) {
      this.gl_.viewport(0, 0, this.canvas_.width, this.canvas_.height);
    }
    this.renderGL_(false);
  }

  /**
   * Returns true if stereoscopic mode is enabled.
   *
   * @return {boolean}
   */
  isStereoscopicModeEnabled() {
    return this.stereoscopicMode_;
  }

  /**
   * Sets how the views of each eye are stored in the video frames.  In the
   * stereoscopic mode each eye displays its own view.  Otherwise, the left
   * eye view is displayed.
   *
   * @param {shaka.ui.VRWebgl.StereoLayout} stereoLayout
   */
  setStereoLayout(stereoLayout) {
    if (this.stereoLayout_ == stereoLayout) {
      return;
    }
    this.stereoLayout_ = stereoLayout;
    // The insets of the cube faces depend on the size of the views.
    this.previousCanvasWidth_ = 0;
    this.previousCanvasHeight_ = 0;
    this.renderGL_(false);
  }

  /**
   * @return {shaka.ui.VRWebgl.StereoLayout}
   */
  getStereoLayout() {
    return this.stereoLayout_;
  }

  /**
   * Returns the part of the video frame that holds the view of an eye, as
   * [x, y, width, height] in texture coordinates.
   *
   * @param {number} eye 0 for the left eye, 1 for the right eye.
   * @return {!Array<number>}
   * @private
   */
  getEyeRect_(eye) {
    switch (this.stereoLayout_) {
      case shaka.ui.VRWebgl.StereoLayout.TOP_BOTTOM:
        return [0, eye * 0.5, 1, 0.5];
      case shaka.ui.VRWebgl.StereoLayout.LEFT_RIGHT:
        return [eye * 0.5, 0, 0.5, 1];
      default:
        return [0, 0, 1, 1];
    }
  }

  /**
   * @param {number} eye 0 for the left eye, 1 for the right eye.
   * @private
   */
  setEyeUniforms_(eye) {
    const rect = this.getEyeRect_(eye);
    const width = this.video_.videoWidth * rect[2];
    const height = this.video_.videoHeight * rect[3];
    this.gl_.uniform4f(this.eyeRectUniform_,
        rect[0], rect[1], rect[2], rect[3]);
    this.gl_.uniform2f(this.eyeClampUniform_,
        width > 0 ? 0.5 / width : 0, height > 0 ? 0.5 / height : 0);
  }

  /**
   * @private
   */
  init_() {
    this.initMatrices_();
    this.initGLResources_();

    const setupListeners = () => {
      if (this.video_.readyState >= HTMLMediaElement.HAVE_ENOUGH_DATA) {
        this.renderGL_();
      }

      const usingFrames = this.videoFrameCallbackHandler_.start(() => {
        this.renderGL_();
      });
      if (!usingFrames) {
        this.eventManager_.listen(this.video_, 'canplaythrough', () => {
          this.renderGL_();
        });
        this.eventManager_.listen(this.video_, 'playing', () => {
          this.renderGL_();
          this.startAnimationFrames_();
        });
        this.eventManager_.listen(this.video_, 'pause', () => {
          this.stopAnimationFrames_();
          this.renderGL_();
        });
        // The view can be created while the video plays, for example when
        // the projection changes.
        if (!this.video_.paused) {
          this.startAnimationFrames_();
        }
        this.eventManager_.listen(this.video_, 'seeked', () => {
          this.renderGL_();
        });

        this.eventManager_.listen(document, 'visibilitychange', () => {
          this.renderGL_();
        });
      }
    };

    shaka.util.MediaReadyState.waitForReadyState(this.video_,
        HTMLMediaElement.HAVE_CURRENT_DATA,
        this.eventManager_,
        setupListeners);
  }

  /**
   * @private
   */
  initGLResources_() {
    this.initGL_();
    this.initGLShaders_();
    this.initGLBuffers_();
    this.initGLTexture_();
  }

  /**
   * Renders the video in sync with the display, uploading only new frames.
   * @private
   */
  startAnimationFrames_() {
    this.stopAnimationFrames_();
    const loop = () => {
      this.animationFrameId_ = requestAnimationFrame(loop);
      const time = this.video_.currentTime;
      if (time != this.lastFrameTime_) {
        this.lastFrameTime_ = time;
        this.renderGL_();
      }
    };
    this.animationFrameId_ = requestAnimationFrame(loop);
  }

  /**
   * @private
   */
  stopAnimationFrames_() {
    if (this.animationFrameId_ != null) {
      cancelAnimationFrame(this.animationFrameId_);
      this.animationFrameId_ = null;
    }
    this.lastFrameTime_ = -1;
  }

  /**
   * @private
   */
  initMatrices_() {
    // The cube is drawn without a look-at transform, so its initial view is
    // the identity.
    if (this.projectionMode_ != 'cubemap') {
      shaka.ui.Matrix4x4.lookAt(
          this.viewMatrix_, [0, 0, 0], [1, 0, 0], [0, 1, 0]);
    }
    this.initialForward_ = shaka.ui.VRWebgl.getForward_(this.viewMatrix_);
    shaka.ui.Matrix4x4.getRotation(
        this.originalQuaternion_, this.viewMatrix_);
    shaka.ui.Matrix4x4.scale(
        this.identityMatrix_, this.identityMatrix_, [4.0, 4.0, 4.0]);
  }

  /**
   * @private
   */
  initGL_() {
    this.updateViewPort_();
    this.gl_.viewport(
        0, 0, this.gl_.drawingBufferWidth, this.gl_.drawingBufferHeight);
    this.gl_.clearColor(0.0, 0.0, 0.0, 1.0);
    this.gl_.enable(this.gl_.CULL_FACE);
    this.gl_.cullFace(this.gl_.FRONT);
    // Clear the context with the newly set color. This is
    // the function call that actually does the drawing.
    this.gl_.clear(this.gl_.COLOR_BUFFER_BIT);
  }

  /**
   * @private
   */
  initGLShaders_() {
    const vertexShader = this.getGLShader_(this.gl_.VERTEX_SHADER);
    const fragmentShader = this.getGLShader_(this.gl_.FRAGMENT_SHADER);

    // Create program
    this.shaderProgram_ = this.gl_.createProgram();
    this.gl_.attachShader(this.shaderProgram_, vertexShader);
    this.gl_.attachShader(this.shaderProgram_, fragmentShader);
    this.gl_.linkProgram(this.shaderProgram_);
    this.shaders_ = [vertexShader, fragmentShader];

    // If creating the shader program failed, alert
    if (!this.gl_.getProgramParameter(
        this.shaderProgram_, this.gl_.LINK_STATUS)) {
      shaka.log.error('Unable to initialize the shader program: ',
          this.gl_.getProgramInfoLog(this.shaderProgram_));
    }

    // Bind data
    if (this.projectionMode_ == 'cubemap') {
      this.vertexPositionAttribute_ = this.gl_.getAttribLocation(
          this.shaderProgram_, 'aVertexPosition');
      this.textureCoordAttribute_ = this.gl_.getAttribLocation(
          this.shaderProgram_, 'aTextureCoord');
      this.projectionMatrixUniform_ = this.gl_.getUniformLocation(
          this.shaderProgram_, 'uProjectionMatrix');
      this.modelViewMatrixUniform_ = this.gl_.getUniformLocation(
          this.shaderProgram_, 'uModelViewMatrix');
    } else {
      this.vertexPositionAttribute_ = this.gl_.getAttribLocation(
          this.shaderProgram_, 'a_vPosition');
      this.gl_.enableVertexAttribArray(this.vertexPositionAttribute_);
      this.textureCoordAttribute_ = this.gl_.getAttribLocation(
          this.shaderProgram_, 'a_TexCoordinate');
      this.gl_.enableVertexAttribArray(this.textureCoordAttribute_);
      this.vpMatrixUniform_ = this.gl_.getUniformLocation(
          this.shaderProgram_, 'u_VPMatrix');
    }
    this.samplerUniform_ = this.gl_.getUniformLocation(
        this.shaderProgram_, 'uSampler');
    this.eyeRectUniform_ = this.gl_.getUniformLocation(
        this.shaderProgram_, 'uEyeRect');
    this.eyeClampUniform_ = this.gl_.getUniformLocation(
        this.shaderProgram_, 'uEyeClamp');
  }

  /**
   * Read and generate WebGL shader
   *
   * @param {number} glType Type of shader requested.
   * @return {!WebGLShader}
   * @private
   */
  getGLShader_(glType) {
    let source;

    switch (glType) {
      case this.gl_.VERTEX_SHADER:
        if (this.projectionMode_ == 'cubemap') {
          source = shaka.ui.VRUtils.VERTEX_CUBE_SHADER;
        } else {
          source = shaka.ui.VRUtils.VERTEX_SPHERE_SHADER;
        }
        break;
      case this.gl_.FRAGMENT_SHADER:
        switch (this.projectionMode_) {
          case 'cubemap':
            source = shaka.ui.VRUtils.FRAGMENT_CUBE_SHADER;
            break;
          case 'fisheye':
            source = shaka.ui.VRUtils.FRAGMENT_FISHEYE_SHADER;
            break;
          case 'halfequirectangular':
            source = shaka.ui.VRUtils.FRAGMENT_SEMI_SPHERE_SHADER;
            break;
          default:
            source = shaka.ui.VRUtils.FRAGMENT_SPHERE_SHADER;
            break;
        }
        break;
      default:
        goog.asserts.assert(false, 'Unknown shader type!');
        source = '';
        break;
    }

    const shader = this.gl_.createShader(glType);

    this.gl_.shaderSource(shader, source);

    this.gl_.compileShader(shader);

    if (!this.gl_.getShaderParameter(shader, this.gl_.COMPILE_STATUS)) {
      shaka.log.warning('Error in ' + glType + ' shader: ' +
          this.gl_.getShaderInfoLog(shader));
    }

    goog.asserts.assert(shader, 'Should have a shader!');

    return /** @type {!WebGLShader} */ (shader);
  }

  /**
   * @private
   */
  initGLBuffers_() {
    if (this.projectionMode_ == 'cubemap') {
      this.geometry_ = shaka.ui.VRUtils.generateCube(
          this.getCubeInsetU_(), this.getCubeInsetV_());
    } else if (this.projectionMode_ == 'fisheye') {
      this.geometry_ = shaka.ui.VRUtils.generateFisheye(100, this.hfov_);
    } else if (this.projectionMode_ == 'halfequirectangular') {
      this.geometry_ = shaka.ui.VRUtils.generateSphere(
          100, /* isSemiSphere= */ true);
    } else {
      this.geometry_ = shaka.ui.VRUtils.generateSphere(100);
    }
    this.verticesBuffer_ = this.gl_.createBuffer();
    this.gl_.bindBuffer(this.gl_.ARRAY_BUFFER, this.verticesBuffer_);
    this.gl_.bufferData(this.gl_.ARRAY_BUFFER,
        new Float32Array(this.geometry_.vertices), this.gl_.STATIC_DRAW);
    this.verticesTextureCoordBuffer_ = this.gl_.createBuffer();
    this.gl_.bindBuffer(
        this.gl_.ARRAY_BUFFER, this.verticesTextureCoordBuffer_);
    this.gl_.bufferData(this.gl_.ARRAY_BUFFER,
        new Float32Array(this.geometry_.textureCoords), this.gl_.STATIC_DRAW);
    this.verticesIndexBuffer_ = this.gl_.createBuffer();
    this.gl_.bindBuffer(
        this.gl_.ELEMENT_ARRAY_BUFFER, this.verticesIndexBuffer_);
    this.gl_.bufferData(this.gl_.ELEMENT_ARRAY_BUFFER,
        new Uint16Array(this.geometry_.indices), this.gl_.STATIC_DRAW);
  }

  /**
   * @private
   */
  initGLTexture_() {
    this.texture_ = this.gl_.createTexture();
    this.gl_.bindTexture(this.gl_.TEXTURE_2D, this.texture_);

    this.gl_.texParameteri(this.gl_.TEXTURE_2D,
        this.gl_.TEXTURE_WRAP_S, this.gl_.CLAMP_TO_EDGE);
    this.gl_.texParameteri(this.gl_.TEXTURE_2D,
        this.gl_.TEXTURE_WRAP_T, this.gl_.CLAMP_TO_EDGE);
    this.gl_.texParameteri(this.gl_.TEXTURE_2D,
        this.gl_.TEXTURE_MIN_FILTER, this.gl_.LINEAR);
    this.gl_.texParameteri(this.gl_.TEXTURE_2D,
        this.gl_.TEXTURE_MAG_FILTER, this.gl_.LINEAR);
  }

  /**
   * @param {boolean=} textureUpdate
   * @private
   */
  renderGL_(textureUpdate = true) {
    const loadMode = this.player_.getLoadMode();
    const isMSE = loadMode == shaka.Player.LoadMode.MEDIA_SOURCE;
    if (!this.video_ || this.video_.readyState < 2 ||
        (!isMSE && this.video_.playbackRate == 0) ||
        this.gl_.isContextLost()) {
      return;
    }
    // A wider field of view, or a different aspect ratio, can move the view
    // out of the image.
    this.rotateView_(0, 0, 0);
    shaka.ui.Matrix4x4.perspective(this.projectionMatrix_,
        this.fieldOfView_ * Math.PI / 180, this.getAspectRatio_(), 0.1, 100.0);

    this.gl_.useProgram(this.shaderProgram_);

    this.gl_.clear(this.gl_.COLOR_BUFFER_BIT);
    this.updateViewPort_();

    if (textureUpdate) {
      this.gl_.activeTexture(this.gl_.TEXTURE0);
      this.gl_.bindTexture(this.gl_.TEXTURE_2D, this.texture_);
      this.gl_.pixelStorei(this.gl_.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
      this.gl_.texImage2D(this.gl_.TEXTURE_2D, 0, this.gl_.RGBA,
          this.gl_.RGBA, this.gl_.UNSIGNED_BYTE, this.video_);
    }

    // Update matrix
    if (this.projectionMode_ != 'cubemap') {
      shaka.ui.Matrix4x4.multiply(this.viewProjectionMatrix_,
          this.viewMatrix_, this.identityMatrix_);
      shaka.ui.Matrix4x4.multiply(this.viewProjectionMatrix_,
          this.projectionMatrix_, this.viewProjectionMatrix_);
    }

    // Plumbing
    // Vertices
    this.gl_.bindBuffer(this.gl_.ARRAY_BUFFER, this.verticesBuffer_);
    goog.asserts.assert(this.vertexPositionAttribute_ != null,
        'Should have a texture attribute!');
    this.gl_.vertexAttribPointer(
        this.vertexPositionAttribute_, 3, this.gl_.FLOAT, false, 0, 0);
    this.gl_.enableVertexAttribArray(this.vertexPositionAttribute_);

    // UVs
    this.gl_.bindBuffer(
        this.gl_.ARRAY_BUFFER, this.verticesTextureCoordBuffer_);
    goog.asserts.assert(this.textureCoordAttribute_ != null,
        'Should have a texture attribute!');
    this.gl_.vertexAttribPointer(
        this.textureCoordAttribute_, 2, this.gl_.FLOAT, false, 0, 0);
    this.gl_.enableVertexAttribArray(this.textureCoordAttribute_);

    this.gl_.bindBuffer(
        this.gl_.ELEMENT_ARRAY_BUFFER, this.verticesIndexBuffer_);

    this.setMatrixUniforms_();

    this.gl_.uniform1i(this.samplerUniform_, 0);

    if (this.stereoscopicMode_) {
      this.gl_.viewport(0, 0, this.canvas_.width / 2, this.canvas_.height);
    }

    // Draw the left eye, which is also the view of the mono mode.
    this.setEyeUniforms_(0);
    this.gl_.drawElements(this.gl_.TRIANGLES,
        this.geometry_.indices.length, this.gl_.UNSIGNED_SHORT, 0);

    if (this.stereoscopicMode_) {
      this.gl_.viewport(this.canvas_.width / 2, 0,
          this.canvas_.width / 2, this.canvas_.height);
      this.setEyeUniforms_(1);
      this.gl_.drawElements(this.gl_.TRIANGLES,
          this.geometry_.indices.length, this.gl_.UNSIGNED_SHORT, 0);
    }
  }

  /**
   * @private
   */
  setMatrixUniforms_() {
    if (this.projectionMode_ == 'cubemap') {
      this.gl_.uniformMatrix4fv(
          this.projectionMatrixUniform_, false, this.projectionMatrix_);
      this.gl_.uniformMatrix4fv(
          this.modelViewMatrixUniform_, false, this.viewMatrix_);
    } else {
      this.gl_.uniformMatrix4fv(
          this.vpMatrixUniform_, false, this.viewProjectionMatrix_);
    }
  }

  /**
   * Returns the aspect ratio of the displayed viewport, so that the
   * perspective projection does not stretch the image. The canvas is
   * displayed at the size of the video container, so the client size is
   * what the user sees. In stereoscopic mode each eye gets half of the
   * width.
   *
   * @return {number}
   * @private
   */
  getAspectRatio_() {
    let aspectRatio = 0;
    if (this.canvas_.clientHeight) {
      aspectRatio = this.canvas_.clientWidth / this.canvas_.clientHeight;
    } else if (this.video_.videoHeight) {
      aspectRatio = this.video_.videoWidth / this.video_.videoHeight;
    }
    if (!aspectRatio) {
      aspectRatio = 16 / 9;
    }
    if (this.stereoscopicMode_) {
      aspectRatio /= 2;
    }
    return aspectRatio;
  }

  /**
   * @private
   */
  updateViewPort_() {
    let currentWidth = this.video_.videoWidth;
    if (!currentWidth) {
      currentWidth = this.canvas_.scrollWidth;
    }
    let currentHeight = this.video_.videoHeight;
    if (!currentHeight) {
      currentHeight = this.canvas_.scrollHeight;
    }

    if (this.previousCanvasWidth_ !== currentWidth ||
        this.previousCanvasHeight_ !== currentHeight) {
      this.canvas_.width = currentWidth;
      this.canvas_.height = currentHeight;

      this.previousCanvasWidth_ = currentWidth;
      this.previousCanvasHeight_ = currentHeight;

      this.gl_.viewport(0, 0, currentWidth, currentHeight);

      if (this.projectionMode_ == 'cubemap' &&
          this.verticesTextureCoordBuffer_) {
        // The half-texel inset of the cube faces depends on the video
        // dimensions, so recompute the texture coordinates.
        this.geometry_ = shaka.ui.VRUtils.generateCube(
            this.getCubeInsetU_(), this.getCubeInsetV_());
        this.gl_.bindBuffer(
            this.gl_.ARRAY_BUFFER, this.verticesTextureCoordBuffer_);
        this.gl_.bufferData(this.gl_.ARRAY_BUFFER,
            new Float32Array(this.geometry_.textureCoords),
            this.gl_.STATIC_DRAW);
      }
    }
  }

  /**
   * Returns a horizontal inset of half a texel, so that the cube faces are
   * not sampled at the exact edge they share with the adjacent face of the
   * atlas. Otherwise the edges of the cube can become visible while moving
   * the view.
   *
   * @return {number}
   * @private
   */
  getCubeInsetU_() {
    // The inset is relative to the view of an eye.
    const width = (this.video_.videoWidth || this.previousCanvasWidth_) *
        this.getEyeRect_(0)[2];
    return width > 0 ? 0.5 / width : 0;
  }

  /**
   * Returns a vertical inset of half a texel, see getCubeInsetU_.
   *
   * @return {number}
   * @private
   */
  getCubeInsetV_() {
    const height = (this.video_.videoHeight || this.previousCanvasHeight_) *
        this.getEyeRect_(0)[3];
    return height > 0 ? 0.5 / height : 0;
  }

  /**
   * Rotate the view matrix global
   *
   * @param {!number} yaw Yaw.
   * @param {!number} pitch Pitch.
   * @param {!number} roll Roll.
   */
  rotateViewGlobal(yaw, pitch, roll) {
    this.rotateView_(yaw, pitch, roll);
    this.renderGL_(false);
  }

  /**
   * @param {number} yaw
   * @param {number} pitch
   * @param {number} roll
   * @private
   */
  rotateView_(yaw, pitch, roll) {
    const matrix = this.viewMatrix_;
    const rotation = this.rotationMatrix_;
    const identity = shaka.ui.VRWebgl.IDENTITY_MATRIX_;

    // Limit the movement.  A movement that goes past a boundary stops at
    // the boundary, instead of being dropped, so fast drags still reach it.
    const clamp = (value, boundary) =>
      Math.min(Math.max(value, -boundary), boundary);
    const maxAngle = this.getMaxViewAngle_();
    const positionY =
        clamp(this.positionY_ + pitch, Math.min(Math.PI / 2, maxAngle));
    let positionX = this.positionX_ + yaw;
    if (maxAngle < Infinity) {
      // The angle between the center of the view and the center of the
      // content is acos(cos(yaw) * cos(pitch)).  The pitch is already in
      // range, so this keeps the yaw where the angle is not larger than the
      // maximum.
      const cosine = Math.cos(maxAngle) / Math.cos(positionY);
      // Looking straight up or down, the cosine is not a number.
      const yawBoundary = !(cosine < 1) ? 0 :
          cosine <= -1 ? Math.PI : Math.acos(cosine);
      positionX = clamp(positionX, yawBoundary);
    }
    yaw = positionX - this.positionX_;
    pitch = positionY - this.positionY_;
    this.positionX_ = positionX;
    this.positionY_ = positionY;

    if (yaw) {
      // Rotate global axis
      shaka.ui.Matrix4x4.rotateY(matrix, matrix, yaw);
    }

    if (pitch) {
      shaka.ui.Matrix4x4.rotateX(rotation, identity, -1 * pitch);
      // Rotate local axis
      shaka.ui.Matrix4x4.multiply(matrix, rotation, matrix);
    }

    if (roll) {
      shaka.ui.Matrix4x4.rotateZ(rotation, identity, roll);
      // Rotate local axis
      shaka.ui.Matrix4x4.multiply(matrix, rotation, matrix);
    }
  }

  /**
   * Content that does not cover the whole sphere only has an image around
   * its center: a half-equirectangular frame covers the front hemisphere,
   * and a fisheye frame a circle of its field of view.  This returns the
   * largest angle between the center of the view and the center of the
   * content at which the whole view stays inside the image, so that the
   * view never shows the area outside of it.
   *
   * @return {number} In radians, or Infinity if the content covers the
   *   whole sphere.
   * @private
   */
  getMaxViewAngle_() {
    let radius;
    if (this.projectionMode_ == 'halfequirectangular') {
      radius = Math.PI / 2;
    } else if (this.projectionMode_ == 'fisheye') {
      radius = this.hfov_ * Math.PI / 360;
    } else {
      return Infinity;
    }
    // The corners of the view are the farthest points from its center.
    const tanY = Math.tan(this.fieldOfView_ * Math.PI / 360);
    const tanX = tanY * this.getAspectRatio_();
    const corner = Math.atan(Math.sqrt(tanX * tanX + tanY * tanY));
    // When the view is wider than the image, it stays at the center.
    return Math.max(0, radius - corner);
  }

  /**
   * @param {number} amount
   */
  zoom(amount) {
    this.setFieldOfView(this.fieldOfView_ + amount / 50);
  }

  /**
   * @return {number}
   */
  getFieldOfView() {
    return this.fieldOfView_;
  }

  /**
   * @param {number} fieldOfView
   */
  setFieldOfView(fieldOfView) {
    // A field of view of 0 would make the projection degenerate.
    this.fieldOfView_ = Math.min(Math.max(fieldOfView,
        shaka.ui.VRWebgl.MIN_FIELD_OF_VIEW),
    shaka.ui.VRWebgl.MAX_FIELD_OF_VIEW);
    this.renderGL_(false);
  }

  /**
   * @return {number}
   */
  getNorth() {
    const initial = this.initialForward_;
    const current = shaka.ui.VRWebgl.getForward_(this.viewMatrix_);
    // The angle between the horizontal components of both directions, around
    // the vertical axis.  It is positive when the view turns to the right.
    const cross = initial[2] * current[0] - initial[0] * current[2];
    const dot = initial[0] * current[0] + initial[2] * current[2];
    const degrees = Math.atan2(-cross, dot) * 180 / Math.PI;
    return degrees < 0 ? degrees + 360 : degrees;
  }

  /**
   * @param {!Float32Array} viewMatrix
   * @return {!Array<number>} The direction the view looks at, in world
   *   coordinates.
   * @private
   */
  static getForward_(viewMatrix) {
    // The camera looks at -Z in its own space.  The view matrix is a rotation,
    // so its inverse is its transpose.
    return [-viewMatrix[2], -viewMatrix[6], -viewMatrix[10]];
  }

  /**
   * @param {boolean=} firstTime
   */
  reset(firstTime = true) {
    const steps = 20;

    if (firstTime) {
      shaka.ui.Matrix4x4.getRotation(
          this.currentQuaternion_, this.viewMatrix_);
      const current = this.currentQuaternion_;
      const original = this.originalQuaternion_;
      const dot = current[0] * original[0] + current[1] * original[1] +
          current[2] * original[2] + current[3] * original[3];
      if (dot < 0) {
        // q and -q are the same rotation.  Interpolate from the one closer
        // to the original, so the view takes the shortest way back.
        for (let i = 0; i < 4; i++) {
          current[i] = -current[i];
        }
      }
      this.cont_ = 0;
      this.diff_ = shaka.ui.MatrixQuaternion.create();
      this.diff_[0] =
          (this.currentQuaternion_[0] - this.originalQuaternion_[0]) / steps;
      this.diff_[1] =
          (this.currentQuaternion_[1] - this.originalQuaternion_[1]) / steps;
      this.diff_[2] =
          (this.currentQuaternion_[2] - this.originalQuaternion_[2]) / steps;
      this.diff_[3] =
          (this.currentQuaternion_[3] - this.originalQuaternion_[3]) / steps;
    }

    this.currentQuaternion_[0] -= this.diff_[0];
    this.currentQuaternion_[1] -= this.diff_[1];
    this.currentQuaternion_[2] -= this.diff_[2];
    this.currentQuaternion_[3] -= this.diff_[3];

    // Set the view to the original matrix
    shaka.ui.MatrixQuaternion.normalize(
        this.currentQuaternion_, this.currentQuaternion_);

    shaka.ui.Matrix4x4.fromQuat(this.viewMatrix_, this.currentQuaternion_);

    if (this.resetTimer_) {
      this.resetTimer_.stop();
      this.resetTimer_ = null;
    }
    if (this.cont_ < steps) {
      this.resetTimer_ = new shaka.util.Timer(() => {
        this.reset(false);
        this.positionX_ = 0;
        this.positionY_ = 0;
        this.cont_++;
        this.renderGL_(false);
      }).tickAfter(shaka.ui.VRWebgl.ANIMATION_DURATION_ / steps);
    } else {
      shaka.ui.Matrix4x4.fromQuat(this.viewMatrix_, this.originalQuaternion_);
    }
  }
};

/**
 * @const {number}
 * @private
 */
shaka.ui.VRWebgl.ANIMATION_DURATION_ = 0.5;

/**
 * How the views of each eye are stored in the video frames.
 *
 * @enum {string}
 */
shaka.ui.VRWebgl.StereoLayout = {
  // A single view.
  MONO: 'mono',
  // Both views in each frame, the left eye on top.
  TOP_BOTTOM: 'top-bottom',
  // Both views in each frame, the left eye on the left.
  LEFT_RIGHT: 'left-right',
};

/**
 * Never modified.
 *
 * @const {!Float32Array}
 * @private
 */
shaka.ui.VRWebgl.IDENTITY_MATRIX_ = shaka.ui.Matrix4x4.create();

/**
 * The minimum field of view, in degrees.
 *
 * @const {number}
 */
shaka.ui.VRWebgl.MIN_FIELD_OF_VIEW = 20;

/**
 * The maximum field of view, in degrees.
 *
 * @const {number}
 */
shaka.ui.VRWebgl.MAX_FIELD_OF_VIEW = 100;