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 {?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;

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

    /** @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.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.activeTimer_?.stop();
    this.activeTimer_ = null;

    this.resetTimer_?.stop();
    this.resetTimer_ = 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_;
  }

  /**
   * @private
   */
  init_() {
    this.initMatrices_();
    this.initGL_();
    this.initGLShaders_();
    this.initGLBuffers_();
    this.initGLTexture_();

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

      const usingFrames = this.videoFrameCallbackHandler_.start(() => {
        this.renderGL_();
      });
      if (!usingFrames) {
        let frameRate;
        this.eventManager_.listen(this.video_, 'canplaythrough', () => {
          this.renderGL_();
        });
        this.eventManager_.listen(this.video_, 'playing', () => {
          if (this.activeTimer_) {
            this.activeTimer_.stop();
          }
          if (!frameRate) {
            const variants = this.player_.getVariantTracks();
            for (const variant of variants) {
              const variantFrameRate = variant.frameRate;
              if (variantFrameRate &&
                  (!frameRate || frameRate < variantFrameRate)) {
                frameRate = variantFrameRate;
              }
            }
          }
          if (!frameRate) {
            frameRate = 60;
          }
          this.renderGL_();
          this.activeTimer_ = new shaka.util.Timer(() => {
            this.renderGL_();
          }).tickNow().tickEvery(1 / frameRate);
        });
        this.eventManager_.listen(this.video_, 'pause', () => {
          if (this.activeTimer_) {
            this.activeTimer_.stop();
          }
          this.activeTimer_ = null;
          this.renderGL_();
        });
        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
   */
  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_);

    // 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');
  }

  /**
   * 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:
        return null;
    }

    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 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)) {
      return;
    }
    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
    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.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_() {
    const width = this.video_.videoWidth || this.previousCanvasWidth_;
    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_;
    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) {
    let yawBoundary = Infinity;
    let pitchBoundary = 90.0 * Math.PI / 180;

    if (this.projectionMode_ == 'halfequirectangular' ||
        this.projectionMode_ == 'fisheye') {
      yawBoundary = 90.0 * Math.PI / 180;
      pitchBoundary /= 2;
    }

    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 positionX = clamp(this.positionX_ + yaw, yawBoundary);
    const positionY = clamp(this.positionY_ + pitch, pitchBoundary);
    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);
    }

    this.renderGL_(false);
  }

  /**
   * @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}
 */
shaka.ui.VRWebgl.ANIMATION_DURATION_ = 0.5;

/**
 * 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;