import flvjs from "flv.js";
/**
 * 截取flv视频流第一帧并返回为Data URL
 * @param {string} videoSrc - flv视频流的URL地址
 * @returns {Promise<string>} - 第一帧图片的Base64 数据
 */
export async function captureFirstPicFromFLV(
  videoSrc: string
): Promise<string> {
  return new Promise((resolve, reject) => {
    //创建video元素
    const video = document.createElement("video");
    video.muted = true;
    video.autoplay = false;
    //创建canvas画布
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    //创建FLV播放器
    if (flvjs.isSupported()) {
      const player = flvjs.createPlayer({
        type: "flv",
        url: videoSrc,
      });
      player.attachMediaElement(video);
      player.load();
      player.play();
      player.on(flvjs.Events.ERROR, (errorType, errorDetail) => {
        reject(`FLV.js error: ${errorType},${errorDetail}`);
      });
      //监听数据加载
      video.addEventListener("loadedmetadata", () => {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        video.addEventListener("canplay", () => {
          //捕获第一帧
          video.currentTime = 0;
        });
        video.addEventListener("seeked", () => {
          if (ctx) {
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            const imageData = canvas.toDataURL("image/png");
            resolve(imageData);
            //销毁播放器并清理DOM
            player.destroy();
            video.remove();
            canvas.remove();
          } else {
            reject("无法捕捉关键帧");
          }
        });
        video.addEventListener("error", (err) => {
          reject(`视频加载失败：${err}`);
        });
      });
    } else {
      reject("不支持flv播放");
    }
  });
}
