// 获取 video 元素的宽度和高度
var videoChannelWidth;
var videoChannelHeight;
// 创建 ImageCapture 对象
var videoChannelCapture;
var usVideoElement;
var captureCanvas;

/// 初始化 imageCapture 并返回 video 宽高
/// [channel_id] 传入需要捕获的 channel_id
function initVideoCapture(channel_id) {
  try {
    // 获取video元素
    let videoChannelView = document.getElementById(
      "HTMLID_trtcCloudChannelView" + channel_id
    );

    usVideoElement = videoChannelView.querySelector("video");
    try {
      // 获取video流
      let stream = usVideoElement.captureStream();
      let track = stream.getVideoTracks()[0];
      // 获取video的宽度和高度
      const settings = track.getSettings();
      videoChannelWidth = settings.width;
      videoChannelHeight = settings.height;

      // 创建ImageCapture对象
      videoChannelCapture = new ImageCapture(track);
    } catch (error) {
      videoChannelCapture = null;
      // 获取video元素的宽度和高度
      videoChannelWidth = usVideoElement.videoWidth;
      videoChannelHeight = usVideoElement.videoHeight;
    }

    // 初始化canvas
    captureCanvas = document.createElement("canvas");
    captureCanvas.width = videoChannelWidth;
    captureCanvas.height = videoChannelHeight;
    return [videoChannelWidth, videoChannelHeight];
  } catch (error) {
    return [0, 0];
  }
}

/// 捕获视频帧并转换为二进制数组返回
function captureOneFrame() {
  if (videoChannelCapture == null) {
    const context = captureCanvas.getContext("2d");
    context.drawImage(
      usVideoElement,
      0,
      0,
      videoChannelWidth,
      videoChannelHeight
    );
    const dataUrl = captureCanvas.toDataURL("image/jpeg");
    const binary = atob(dataUrl.split(",")[1]);
    const uint8Array = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      uint8Array[i] = binary.charCodeAt(i);
    }
    return Promise.resolve(uint8Array);
  } else {
    const promise = videoChannelCapture.grabFrame().then((imageBitmap) => {
      const context = captureCanvas.getContext("2d");
      context.drawImage(
        imageBitmap,
        0,
        0,
        videoChannelWidth,
        videoChannelHeight
      );
      const dataUrl = captureCanvas.toDataURL("image/jpeg");
      const binary = atob(dataUrl.split(",")[1]);
      const uint8Array = new Uint8Array(binary.length);
      for (let i = 0; i < binary.length; i++) {
        uint8Array[i] = binary.charCodeAt(i);
      }
      return uint8Array;
    });
    return promise;
  }
}

/// 释放 imageCapture 对象
function disposeVideoCapture() {
  videoChannelCapture = null;
  usVideoElement = null;
  captureCanvas = null;
  console.log("videoChannelCapture has been disposed");
}
