useVideoPlayer.js 16 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { wxInfo } from "@/utils/tools";
import videojs from "video.js";
import { buildVideoSources, canPlayHlsNatively } from "./videoPlayerSource";
import { useVideoProbe } from "./useVideoProbe";
import { useVideoPlaybackOverlays } from "./useVideoPlaybackOverlays";
// 新增:引入多码率切换插件
import 'videojs-contrib-quality-levels'; // 用于读取 m3u8 中的多码率信息
import 'videojs-hls-quality-selector'; // 用于在播放器控制条显示“清晰度”切换菜单(支持 Auto/720p/480p 等)。
import 'videojs-hls-quality-selector/dist/videojs-hls-quality-selector.css';

/**
 * - 使用方法 :您无需修改业务代码。只要传入的视频 URL 是七牛云生成的多码率 .m3u8 地址,播放器控制条右下角会自动出现“齿轮”图标,用户点击即可切换清晰度(或选择 Auto 自动切换)。
 * - iOS 注意事项 :在 iOS 移动端(尤其是微信),通常使用系统原生播放器,系统会根据网速自动切换码率(ABR),但通常无法显示手动切换菜单,这是 iOS H5 的系统限制。
 * - PC 和 Android 端将正常显示切换菜单。
 */

/**
 * 视频播放核心逻辑 Hook
 * 处理不同环境下的播放器选择、HLS支持、自动播放策略等
 * @description 根据环境选择原生 video 或 video.js,并处理弱网提示、错误重试与清晰度选择等逻辑。
 * @param {any} props 组件 props(需要包含 videoUrl/autoplay/useNativeOnIos/options/debug/videoId 等字段)
 * @param {(event: string, ...args: any[]) => void} emit 组件 emit
 * @param {import("vue").Ref<any>} videoRef videojs-player 组件 ref(用于 dispose)
 * @param {import("vue").Ref<HTMLVideoElement|null>} nativeVideoRef 原生 video 元素 ref(iOS 微信)
 * @returns {{
 *   player: import("vue").Ref<any>,
 *   state: import("vue").Ref<any>,
 *   useNativePlayer: import("vue").ComputedRef<boolean>,
 *   videoUrlValue: import("vue").ComputedRef<string>,
 *   videoOptions: import("vue").ComputedRef<any>,
 *   showErrorOverlay: import("vue").Ref<boolean>,
 *   errorMessage: import("vue").Ref<string>,
 *   showNetworkSpeedOverlay: import("vue").Ref<boolean>,
 *   networkSpeedText: import("vue").Ref<string>,
 *   hlsDownloadSpeedText: import("vue").Ref<string>,
 *   hlsSpeedDebugText: import("vue").Ref<string>,
 *   retryLoad: () => void,
 *   handleVideoJsMounted: (payload: {player: any, state: any}) => void,
 *   tryNativePlay: () => void
 * }}
 */
export function useVideoPlayer(props, emit, videoRef, nativeVideoRef) {
  // 播放器实例
  const player = ref(null);
  const state = ref(null);

  // 错误处理相关
  const showErrorOverlay = ref(false);
  const errorMessage = ref('');
  const retryCount = ref(0);
  const maxRetries = 3;

  const hasEverPlayed = ref(false);
  const hasStartedPlayback = ref(false);

  // 原生播放器状态
  const nativeReady = ref(false);
  let nativeListeners = null;

  // 1. 环境判断与播放器选择
  const useNativePlayer = computed(() => {
    // 如果 props 强制关闭原生播放器,则返回 false (使用 Video.js)
    if (props.useNativeOnIos === false) {
      return false;
    }
    // 默认逻辑:iOS 微信环境下使用原生播放器
    return wxInfo().isIOSWeChat;
  });

  // 2. 视频源处理
  const videoUrlValue = computed(() => {
    return (props.videoUrl || "").trim();
  });

  // 3. HLS 支持判断
  const isM3U8 = computed(() => {
    const url = videoUrlValue.value.toLowerCase();
    return url.includes('.m3u8');
  });

  // 资源探测:只在“同源可探测”时执行,避免跨域 CORS 报错影响体验
  const { probeInfo, probeVideo } = useVideoProbe(videoUrlValue);

  // 视频源构造:尽可能带上 type,老设备/部分内核对 blob/部分后缀会更稳定
  const videoSources = computed(() => buildVideoSources({
    url: videoUrlValue.value,
    video_id: props?.videoId,
    probe_content_type: probeInfo.value.content_type,
  }));

  // 播放叠层:弱网提示 + HLS 速度展示(仅 video.js + m3u8)
  const {
    showNetworkSpeedOverlay,
    networkSpeedText,
    hlsDownloadSpeedText,
    hlsSpeedDebugText,
    setHlsDebug,
    showNetworkSpeed,
    hideNetworkSpeed,
    startHlsDownloadSpeed,
    stopHlsDownloadSpeed,
    disposeOverlays,
  } = useVideoPlaybackOverlays({
    props,
    player,
    is_m3u8: isM3U8,
    use_native_player: useNativePlayer,
    show_error_overlay: showErrorOverlay,
    has_started_playback: hasStartedPlayback,
  });

  // 6. 错误处理逻辑
  const formatBytes = (bytes) => {
    const size = Number(bytes) || 0;
    if (!size) return "";
    const kb = 1024;
    const mb = kb * 1024;
    const gb = mb * 1024;
    if (size >= gb) return (size / gb).toFixed(2) + "GB";
    if (size >= mb) return (size / mb).toFixed(2) + "MB";
    if (size >= kb) return (size / kb).toFixed(2) + "KB";
    return String(size) + "B";
  };

  const getErrorHint = () => {
    if (probeInfo.value.status === 403) return "(403:无权限或已过期)";
    if (probeInfo.value.status === 404) return "(404:资源不存在)";
    if (probeInfo.value.status && probeInfo.value.status >= 500) return `(${probeInfo.value.status}:服务器异常)`;

    const len = probeInfo.value.content_length;
    if (len && len >= 1024 * 1024 * 1024) {
      const text = formatBytes(len);
      return text ? `(文件约${text},建议 WiFi)` : "(文件较大,建议 WiFi)";
    }
    return "";
  };

  // 7. 错误处理逻辑
  const handleError = (code, message = '') => {
    showErrorOverlay.value = true;
    hideNetworkSpeed();
    switch (code) {
      case 4: // MEDIA_ERR_SRC_NOT_SUPPORTED
        errorMessage.value = '视频格式不支持或无法加载,请检查网络连接' + getErrorHint();
        // 旧机型/弱网下可能出现短暂的“无法加载”,这里做有限次数重试
        if (retryCount.value < maxRetries) {
          setTimeout(retryLoad, 1000);
        }
        break;
      case 3: // MEDIA_ERR_DECODE
        errorMessage.value = '视频解码失败,可能是文件损坏';
        break;
      case 2: // MEDIA_ERR_NETWORK
        errorMessage.value = '网络连接错误,请检查网络后重试' + getErrorHint();
        if (retryCount.value < maxRetries) {
          setTimeout(retryLoad, 2000);
        }
        break;
      case 1: // MEDIA_ERR_ABORTED
        errorMessage.value = '视频加载被中止';
        break;
      default:
        errorMessage.value = message || '视频播放出现未知错误';
    }
  };

  // 4. 原生播放器逻辑 (iOS微信)
  const initNativePlayer = () => {
    const videoEl = nativeVideoRef.value;
    if (!videoEl) return;

    setHlsDebug('native:init');

    // 原生播放器走系统内核:事件主要用于控制弱网提示与错误覆盖层
    const onLoadStart = () => {
      showErrorOverlay.value = false;
      nativeReady.value = false;
    };

    const onCanPlay = () => {
      showErrorOverlay.value = false;
      retryCount.value = 0;
      nativeReady.value = true;
    };

    const onError = () => {
      handleError(videoEl.error?.code);
    };

    const onPlay = () => {
      hideNetworkSpeed();
      setHlsDebug('native:play');
    };

    const onPause = () => {
      hideNetworkSpeed();
    };

    const onWaiting = () => {
      if (videoEl.paused) return;
      showNetworkSpeed();
      setHlsDebug('native:waiting');
    };

    const onStalled = () => {
      if (videoEl.paused) return;
      showNetworkSpeed();
      setHlsDebug('native:stalled');
    };

    const onPlaying = () => {
      hasEverPlayed.value = true;
      hasStartedPlayback.value = true;
      hideNetworkSpeed();
      setHlsDebug('native:playing');
    };

    videoEl.addEventListener("loadstart", onLoadStart);
    videoEl.addEventListener("canplay", onCanPlay);
    videoEl.addEventListener("error", onError);
    videoEl.addEventListener("play", onPlay);
    videoEl.addEventListener("pause", onPause);
    videoEl.addEventListener("waiting", onWaiting);
    videoEl.addEventListener("stalled", onStalled);
    videoEl.addEventListener("playing", onPlaying);

    nativeListeners = {
      videoEl,
      onLoadStart,
      onCanPlay,
      onError,
      onPlay,
      onPause,
      onWaiting,
      onStalled,
      onPlaying,
    };

    if (props.autoplay) {
      // iOS 微信 autoplay 需要用户手势/桥接事件配合,先尝试一次,再在 WeixinJSBridgeReady 时再试
      tryNativePlay();
      if (typeof document !== "undefined") {
        document.addEventListener(
          "WeixinJSBridgeReady",
          () => tryNativePlay(),
          { once: true }
        );
      }
    }
  };

  const tryNativePlay = () => {
    const videoEl = nativeVideoRef.value;
    if (!videoEl) return;

    const playPromise = videoEl.play();
    if (playPromise && typeof playPromise.catch === "function") {
      playPromise.catch(() => {
        if (typeof window !== "undefined" && window.WeixinJSBridge) {
          window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
            videoEl.play().catch(() => {});
          });
        }
      });
    }
  };

  // 5. Video.js 播放器逻辑 (PC/Android)
  const shouldOverrideNativeHls = computed(() => {
    if (!isM3U8.value) return false;
    if (videojs.browser.IS_SAFARI) return false;
    // 非 Safari 且不具备原生 HLS 时,强制 video.js 的 VHS 来解 m3u8
    return !canPlayHlsNatively();
  });

  const videoOptions = computed(() => ({
    controls: true,
    preload: "metadata",
    responsive: true,
    autoplay: props.autoplay,
    playsinline: true,
    playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2],
    sources: videoSources.value,
    html5: {
      vhs: {
        overrideNative: shouldOverrideNativeHls.value,
      },
      nativeVideoTracks: false,
      nativeAudioTracks: false,
      nativeTextTracks: false,
      hls: {
        withCredentials: false
      }
    },
    errorDisplay: true,
    techOrder: ['html5'],
    userActions: {
      hotkeys: true,
      doubleClick: true,
    },
    controlBar: {
      progressControl: {
        seekBar: {
          mouseTimeDisplay: {
            keepTooltipsInside: true,
          },
        },
      },
    },
    ...props.options,
  }));

  // 8. Video.js 挂载处理
  const handleVideoJsMounted = (payload) => {
    state.value = payload.state;
    player.value = payload.player;

    if (player.value) {
      setHlsDebug('mounted');

      const quality_selector_inited = { value: false };
      const setupQualitySelector = () => {
        if (quality_selector_inited.value) return;
        if (!isM3U8.value) return;
        const p = player.value;
        if (!p || (typeof p.isDisposed === "function" && p.isDisposed())) return;
        if (typeof p.hlsQualitySelector !== "function") return;
        if (typeof p.qualityLevels !== "function") return;

        let tech = null;
        try {
          tech = typeof p.tech === "function" ? p.tech({ IWillNotUseThisInPlugins: true }) : null;
        } catch (e) {
          tech = null;
        }
        if (!tech) return;
        // videojs-hls-quality-selector 旧版本依赖 tech.hls,而 video.js 7 默认是 tech.vhs,这里做兼容别名
        if (!tech.hls && tech.vhs) {
          try {
            tech.hls = tech.vhs;
          } catch (e) {
            void e;
          }
        }
        if (!tech.hls) return;

        try {
          p.hlsQualitySelector({
            displayCurrentQuality: true,
          });
          quality_selector_inited.value = true;
        } catch (e) {
          void e;
        }
      };

      setupQualitySelector();

      player.value.on('error', () => {
        const err = player.value.error();
        handleError(err?.code, err?.message);
      });

      player.value.on('loadstart', () => {
        showErrorOverlay.value = false;
        setupQualitySelector();
      });

      player.value.on('canplay', () => {
        showErrorOverlay.value = false;
        retryCount.value = 0;
        setupQualitySelector();
      });

      player.value.on('play', () => {
        hideNetworkSpeed();
        startHlsDownloadSpeed();
        setHlsDebug('play');
      });

      player.value.on('pause', () => {
        hideNetworkSpeed();
        stopHlsDownloadSpeed('pause');
        setHlsDebug('pause');
      });

      player.value.on('waiting', () => {
        if (!hasEverPlayed.value) return;
        if (player.value?.paused?.()) return;
        // 已经播放过且当前未暂停,才认为是“卡顿等待”,显示弱网提示
        showNetworkSpeed();
        startHlsDownloadSpeed();
        setHlsDebug('waiting');
      });

      player.value.on('stalled', () => {
        if (!hasEverPlayed.value) return;
        if (player.value?.paused?.()) return;
        showNetworkSpeed();
        startHlsDownloadSpeed();
        setHlsDebug('stalled');
      });

      player.value.on('playing', () => {
        hasEverPlayed.value = true;
        hasStartedPlayback.value = true;
        hideNetworkSpeed();
        setHlsDebug('playing');
      });

      player.value.on('ended', () => {
        stopHlsDownloadSpeed('ended');
        setHlsDebug('ended');
      });

      if (props.autoplay) {
        player.value.play().catch(() => {});
      }
    }
  };

  // 6. 重试逻辑
  const retryLoad = () => {
    if (retryCount.value >= maxRetries) {
      errorMessage.value = '重试次数已达上限,请稍后再试';
      return;
    }

    retryCount.value++;
    showErrorOverlay.value = false;
    hideNetworkSpeed();
    stopHlsDownloadSpeed('retry');

    if (useNativePlayer.value) {
      // 原生 video 需要手动重置 src/load
      const videoEl = nativeVideoRef.value;
      if (videoEl) {
        nativeReady.value = false;
        const currentSrc = videoEl.currentSrc || videoEl.src;
        videoEl.pause();
        videoEl.removeAttribute("src");
        videoEl.load();
        videoEl.src = currentSrc || videoUrlValue.value;
        videoEl.load();
        tryNativePlay();
      }
    } else {
      // video.js 走自身 load 刷新
      if (player.value && !player.value.isDisposed()) {
        player.value.load();
      }
    }
  };

  // 7. 生命周期与监听
  watch(() => videoUrlValue.value, () => {
    retryCount.value = 0;
    showErrorOverlay.value = false;
    hideNetworkSpeed();
    stopHlsDownloadSpeed('url_change');
    hasEverPlayed.value = false;
    hasStartedPlayback.value = false;
    // 地址变更后刷新探测信息,错误提示会基于 probeInfo 补充更准确的原因
    void probeVideo();

    // 如果是原生播放器且 URL 变化,需要手动处理 HLS (如果是非 iOS Safari 环境)
    if (useNativePlayer.value && isM3U8.value) {
       // iOS 原生支持,不需要额外操作
       // 如果未来支持 Android 原生播放器且不支持 HLS,需在此处初始化 hls.js
    }
  });

  onMounted(() => {
    void probeVideo();
    if (useNativePlayer.value) {
      initNativePlayer();
    }
  });

  onBeforeUnmount(() => {
    if (nativeListeners?.videoEl) {
      nativeListeners.videoEl.removeEventListener("loadstart", nativeListeners.onLoadStart);
      nativeListeners.videoEl.removeEventListener("canplay", nativeListeners.onCanPlay);
      nativeListeners.videoEl.removeEventListener("error", nativeListeners.onError);
      nativeListeners.videoEl.removeEventListener("play", nativeListeners.onPlay);
      nativeListeners.videoEl.removeEventListener("pause", nativeListeners.onPause);
      nativeListeners.videoEl.removeEventListener("waiting", nativeListeners.onWaiting);
      nativeListeners.videoEl.removeEventListener("stalled", nativeListeners.onStalled);
      nativeListeners.videoEl.removeEventListener("playing", nativeListeners.onPlaying);
    }

    disposeOverlays();
    if (videoRef.value?.$player) {
      videoRef.value.$player.dispose();
    }
  });

  return {
    player,
    state,
    useNativePlayer,
    videoUrlValue,
    videoOptions,
    showErrorOverlay,
    errorMessage,
    showNetworkSpeedOverlay,
    networkSpeedText,
    hlsDownloadSpeedText,
    hlsSpeedDebugText,
    retryLoad,
    handleVideoJsMounted,
    tryNativePlay
  };
}