npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hq-video-player

v0.5.3

Published

Multi-channel monitor-wall player with structured error codes, deterministic reconnect jitter and ZLMediaKit WebRTC + WS-FLV/MSE pipelines.

Readme

hq-video-player(中文)

单路实例化 Player(jessibuca 风格)+ 结构化错误码 + 确定性重连抖动 + ZLMediaKit WebRTC + WS-FLV/MSE + WebCodecs / WASM 后备渲染 —— 全部封装在极简的 API 之下。

npm license node

English version

主要特性

  • 单路实例化 Player —— new Player({ container }) 即可获得独立生命周期和状态的 播放器实例,截图、录像、水印、全屏和键盘快捷键开箱即用。
  • 多协议播放 —— 通过同一套 API 支持 ws-flv / http-flv / ws-h264 / ws-h265 / webrtc。
  • WebSocket 裸流路由 —— ws-h264、ws-h265 表示 WebSocket 直接承载 H.264/H.265 Annex-B 裸码流,不包含 FLV 容器。在 mse / auto 模式下, 共享传输 Worker 将原始字节交给 JMuxer,由 JMuxer 完成 Annex-B Access Unit 解析、 fMP4 封装和 MSE 缓冲。由于裸流没有容器时间戳,source.frameRate 提供名义帧率 (默认 25 fps)。每个裸流 WebSocket 二进制消息在进入 JMuxer 前会跳过 source.rawPacketHeaderBytes 字节(默认 28;消息直接以 Annex-B 起始码开头时设为 0)。
  • 五种渲染后端 —— MSE(@hq-video/mse-player)、WebCodecs 硬解 / 软解、FFmpeg-WASM、ZLMediaKit WebRTC。
  • 统一 FLV Demux/Remux —— 项目 Worker 与 MSE Player 路线共同使用 @hq-video/fmp4-remuxer 中的流式 FLV demux;H.264/H.265、AAC、G.711 的容器解析只维护一份。 MSE Player 继续负责网络 IO、Worker、SourceBuffer、背压、缓冲清理和直播延迟控制。
  • 结构化错误码 —— 所有传输层 / 渲染管线失败都会被标记为 ErrorCode 枚举 (如 WS_FLV_CONNECT_FAILED、WEBRTC_ICE_FAILED、WEBRTC_SIGNALING_AUTH_FAILED …)并附 严重级别,使告警与自动恢复逻辑可以基于意图分支,而不是正则匹配。
  • 权威状态机 —— 渲染管线统一发出 state 事件;Player 镜像后转发为 jessibuca 风格的 state 事件,消费方只需订阅一次。
  • 每个实例错峰重连 —— 当 32+ 个 Player 实例同时重连时,每个实例的重试窗口会按 playerId 的 FNV-1a 哈希进行偏移,避免雪崩式并发重连。
  • ZLMediaKit WebRTC 回退 —— 不具备 WebRTC HEVC 能力的 H.265 接收端会自动回退到 WS-FLV + MSE。N 个 Player 实例共享 1 个 transport worker + 1 个 decoder worker。

目录

  1. 安装
  2. 单路 Player 快速上手
  3. 单路 Player 全功能示例
  4. 多路墙(多 Player 实例)
  5. Player 配置项
  6. Player API & 事件
  7. 错误码
  8. 状态机
  9. WebRTC + WS-FLV 回退
  10. 重连错峰
  11. 从 0.2.x 升级
  12. 构建与发布
  13. 路线图

安装

npm install hq-video-player

MSE 后端使用私有 workspace 包 @hq-video/mse-player,发布时会打入播放器产物, 使用方不需要单独安装。

默认导出同时面向现代打包器(ESM)与 CommonJS 用户:

// ESM
import { Player } from 'hq-video-player';

// CommonJS
const { Player } = require('hq-video-player');

播放器不再导出单独的样式文件。video/canvas 尺寸和业务控制区样式由宿主应用负责。

Chrome 86+ 兼容方案

项目的应用构建和发布库构建都以 chrome86 为 Vite 目标,并保留 source map:

build: {
  target: 'chrome86',
  sourcemap: true,
}

TypeScript 的检查目标同步为 ES2020,源码中的 Array.prototype.at 等高版本语法已移除; Chrome 86 没有 structuredClone 时,统计快照会自动使用 JSON 降级复制。

运行时能力仍按浏览器实际实现探测:

  • Chrome 86 的 H.264/AAC 播放优先走 MSE;HEVC 是否可用取决于系统解码器和浏览器能力。
  • WebCodecs 只在 VideoDecoder 可用时启用,不可用时自动回退到 MSE/WASM 路径。
  • webrtc、录制和 WebCodecs 渲染需要对应的浏览器 API;显式指定不支持的后端会返回结构化错误。
  • 生产环境若使用跨线程 MSE 或 WASM,需要由静态服务器发送 Cross-Origin-Opener-Policy: same-origin 和 Cross-Origin-Embedder-Policy: require-corp。Vite dev/preview 已内置这两个响应头。

因此,chrome86 表示 JavaScript 语法和打包产物的最低版本;具体编码格式和高级渲染能力仍以运行时能力检测结果为准。


单路 Player 快速上手

import { Player } from 'hq-video-player';

// 1. 创建实例。container 接受 CSS selector 或 HTMLElement。
const player = new Player({
  container: '#app',
  isLive: true,
  : true,           // jessibuca 兼容字段
  useWCS: true,
  decoderMode: 'auto',
  heartbeat: 2000,
  timeout: 5000,
});

// 2. 启动播放(自动跟随 URL 协议推断)
player.play('wss://demo.zlm.example/live/cam01.flv');

// 3. 听事件
player.on('play', () => console.log('playing'));
player.on('error', ({ code, message }) => console.error(code, message));
player.on('stats', (stats) => console.log(stats.decoder?.fps ?? 0, 'fps'));

实例负责播放、截图、录像、水印和键盘交互。


单路 Player 全功能示例

本节覆盖 Player 提供的所有交互能力。每个片段都可以单独运行。

截图

// 点击后从当前帧拍一张 PNG,自动下载;返回详细负载
const result = await player.screenshot('cam01');
//   { blob, url, width, height, capturedAt }

底层用 <video> 走 ctx.drawImage(video),<canvas> 走 canvas.toBlob('image/png'), 无需关心当前后端;Player 内部已经选好。

录像

// 开始录像(MediaRecorder;产物 webm 或 mp4,取决于浏览器支持)
player.startRecord('cam01');
// ... 任意长度 ...
// 停止并下载
const handle = await player.stopRecord();
// handle: { blob, url, durationMs, bytesRecorded, suggestedFilename }

停止录像后返回最终字节数和录像时长。

旋转 / 缩放

player.setRotate(90);    // 0/90/180/270
player.setRotate((player.getRotate() + 90) % 360);  // 一键循环旋转

player.setScale(1.5);    // 1.0 = 原始,最大 4.0

旋转/缩放通过 CSS transform 实现,不影响底层解码/渲染管线。

水印

// 文本水印,可指定位置 + 字号 + 透明度 + 定时刷新
player.setWatermark({
  text: 'CAM-01 · 大厅',
  fontSize: 14,
  color: 'rgba(255,255,255,0.7)',
  alpha: 0.7,
  posx: 0.02,            // 0..1 左对齐
  posy: 0.96,            // 0..1 底对齐
  intervalMs: 1000,      // 每秒刷新一次
  textGenerator: () => `CAM-01 · ${new Date().toLocaleTimeString()}`,
});
player.clearWatermark();

URL 图片水印(url)优先级高于 text,可同时设置。

静音 / 音量

player.mute();                // 静音
player.unmute();              // 取消静音
player.setVolume(0.5);        // 音量 0..1
player.toggleMute();          // 一键切换

每次变化都会触发 volume 事件:{ volume, muted }。

全屏 / 键盘快捷键

await player.fullscreen();
await player.quitFullscreen();
player.isFullscreen();        // 当前是否全屏

播放器可识别以下键:

| 键位 | 行为 | | --- | --- | | space | 播放 / 暂停 | | m | 静音 / 取消静音 | | f | 进入 / 退出全屏 | | ←/→ | 音量 -5% / +5% | | Esc | 退出全屏 |

注意:键盘事件只在容器获得焦点或鼠标悬停时触发,避免抢全局。

WebRTC + 自动回退

const player = new Player({
  container: '#webrtc-cam',
  useMSE: true, useWCS: true,           // 启用 MSE + WebCodecs 双栈
  decoderMode: 'auto',
});

player.play({
  protocol: 'webrtc',
  url: 'webrtc://demo.zlm.example/index/api/webrtc?app=live&stream=cam01',
  signaling: 'zlm-sdk',
  preferredCodec: 'h265',
  iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
  firstFrameTimeoutMs: 8000,
  fallback: {
    protocol: 'ws-flv',
    url: 'wss://demo.zlm.example/live/cam01.flv',
  },
});

player.on('state', (status) => console.log(status));
player.on('error', ({ code }) => {
  if (code === 'WEBRTC_HEVC_UNSUPPORTED') {
    // 用户浏览器不支持 H.265,管线已自动切换到 MSE
  }
});

多路墙(多 Player 实例)

N 路监控墙 = N 个独立 Player 实例。所有实例共享同一个 transport worker + decoder worker(由 TransportWorkerHub.instance() / DecoderWorkerHub.instance() 提供)。 也就是说 64 路 Player ≠ 64 个 Worker。

import { Player } from 'hq-video-player';

// 1. 准备 N 个 DOM 挂点
const grid = document.getElementById('grid')!;
const urls = Array.from({ length: 32 }, (_, i) => `wss://.../cam${i.toString().padStart(2, '0')}.flv`);

// 2. 步进启动:每 250 ms 启动 4 路,错峰降低突发流量
const players: Player[] = [];
const STEP = 4;
let i = 0;
const next = () => {
  if (i >= urls.length) return;
  for (let k = 0; k < STEP && i < urls.length; k++, i++) {
    const cell = document.createElement('div');
    cell.style.cssText = 'position:relative; width:100%; height:100%;';
    grid.appendChild(cell);
    const player = new Player({
      container: cell,
      source: { protocol: 'ws-flv', url: urls[i]!, autoReconnect: true },
      decoderBackend: 'mse',
      muted: true,
    });
    player.play(urls[i]!);
    player.on('stats', (s) => updateTile(s, i));
    players.push(player);
  }
  setTimeout(next, 250);
};
next();

完整的压测示例(/src/main.ts)将 32 个 Player 拼成 8×4 网格,配合 requestVideoFrameCallback 计算每路帧率,并附 PerformanceObserver 长任务面板。

需要注意:

  • Player 实例按需创建;所有实例共享同一传输 / 解码 Worker。 (decoder hub 是 36)。Player 构造时会检查是否已超限。
  • 每个 Player 持有自己的内部播放管线,但所有实例共享 worker。
  • destroy() 必须被调用,否则 Player 的 heartbeat / keyboard listener 不会解绑,会出现内存泄漏。

Player 配置项

完整字段参见 PlayerOptions.ts。下面是 jessibuca 兼容 + 本包扩展的并集:

容器 / 形态

| 字段 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | container | string \| HTMLElement | (必填) | CSS selector 或 HTMLElement。 | | width / height | number | 容器尺寸 | 初始视频窗口;跟随 root.clientWidth。 | | fitMode | 'contain' \| 'stretch' | 'contain' | 与 PlaybackEngine.setFitMode 一致。 |

协议 / 后端

| 字段 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | useMSE | boolean | true | jessibuca 兼容字段。开启则允许 MSE 后端。 | | useWCS | boolean | true | jessibuca 兼容字段。开启则允许 WebCodecs 后端。 | | decoderBackend | 'mse' \| 'webrtc' \| 'webcodecs-hw' \| 'webcodecs-sw' \| 'wasm-ffmpeg' \| 'auto' | 见下 | 显式覆盖;优先级最高。 | | decoderMode | 'auto' \| 'hardware' \| 'software' | 'auto' | WebCodecs 专用。 | | wcsUseVideoRender | boolean | false | WebCodecs 模式下输出 <video>(jessibuca wcsUseVideoRender)。 |

后端解析优先级:decoderBackend 显式值 > (useMSE, useWCS) > 'auto'。

  • 两者都为 true → 'auto',按 MSE → WebCodecs HW → WebCodecs SW → WASM 顺序探测;
  • 仅 useMSE → 'mse';
  • 仅 useWCS → 'webcodecs-hw';
  • 都为 false → 'wasm-ffmpeg'(兜底)。

媒体行为

| 字段 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | source | SourceOptions \| string | — | 初始播放源;如果 autoplay=true,构造后立即 play。 | | autoplay | boolean | false | 部分浏览器会拦截带声音的自动播放。 | | isLive | boolean | true | 是否按直播模式配置 MSE 后端。 | | videoBuffer | number | 0.2 | MSE 直播延迟目标(秒)。 | | liveBufferLatencyChasing | boolean | false | 是否主动追赶 MSE 直播延迟;开启后可能跳到非关键帧,建议确认码流关键帧间隔后使用。 | | mse | MsePlaybackOptions | — | MSE 缓冲/低延迟策略;可设置 autoCleanupMaxBackwardDuration、autoCleanupMinBackwardDuration、liveSync 等。 | | muted | boolean | true | jessibuca 默认静音;中国境内浏览器均不会拦截。 | | volume | number | 1 | 初始音量 0..1。 |

多路监控墙建议显式收紧 MSE 历史缓冲,并用 liveSync 代替直接 seek:

new Player({
  container,
  isLive: true,
  mse: {
    autoCleanupSourceBuffer: true,
    autoCleanupMaxBackwardDuration: 5,   // 秒
    autoCleanupMinBackwardDuration: 2,   // 秒
    liveSync: true,
    liveSyncMaxLatency: 2,
    liveSyncTargetLatency: 0.8,
    liveSyncPlaybackRate: 1.15,
    liveBufferLatencyChasing: false,
    stashInitialSize: 128,               // KB
  },
});

stashInitialSize 以 KB 为单位;不传 mse 时保持原有默认行为。

MSE 播放音频时,只需在 SourceOptions 开启音频;workspace 中的 MSE Player 会根据 FLV 音频 Tag 自动识别 AAC、PCMA 和 PCMU:

player.play({
  protocol: 'ws-flv',
  url: 'wss://example.com/live/camera.flv',
  receiveAudio: true,
});

此模式仍只建立一条 FLV 连接。AAC 继续使用 MSE 原生音轨;PCMA/PCMU 由本地 MSE Player 在解复用阶段输出外部音频包,视频单独进入 MSE。外部音频包进入共享 解码 Worker,由 Jessibuca FFmpeg-WASM 解码并通过 libswresample 重采样,随后按 Jessibuca 的 1024 采样块 ScriptProcessor 队列播放。默认 muted=true;取消静音应由 用户手势触发。

仓库现在是 pnpm workspace:packages/mse-player 保存从 mpegts.js 派生的 MSE 播放包, 根播放器通过 workspace:* 直接依赖它。Vite 会把其源码及 inline worker 与主播放器一起打包。

心跳 / 超时

| 字段 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | heartbeat | number | 2000 | 心跳间隔(ms),0 禁用。 | | timeout | number | 5000 | 心跳超时(ms),超时后状态切到 no-signal。 | | rotate | number | 0 | 0/90/180/270 旋转(CSS transform)。 | | scale | number | 1 | 视频缩放倍数,1..4。 |

录像 / 截图

| 字段 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | screenshot(name?) | Promise<PlayerScreenshotResult> | — | 拍照。返回 { blob, url, width, height, capturedAt }。 | | startRecord(name?) | PlayerRecordHandle \| null | — | 开启录像;返回句柄。 | | stopRecord() | Promise<PlayerRecordResult \| null> | — | 停止并下载。 |

水印

| 字段 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | watermark | PlayerWatermarkOptions | — | 启动时叠加的水印。可后续 setWatermark() 改写。 |

行为开关

| 字段 | 类型 | 默认 | 说明 | | --- | --- | --- | --- | | debug | boolean | false | 控制台输出 listener 异常。 | | zIndex | number | 100 | 容器 z-index。 | | decoder | { decoderUrl?, wasmUrl? } | — | wasm-ffmpeg 后端的 decoder 资源。 |

渲染后端速查

| decoderBackend | 管线是否自带传输? | 渲染目标 | 适用场景 | | --- | --- | --- | --- | | 'mse'(@hq-video/mse-player) | 是(ownsTransport = true) | <video> | Chromium / Firefox 下 CPU 占用最低;具备能力的浏览器可原生 H.265。 | | 'webrtc'(ZLMediaKit) | 是 | <video> | 端到端延迟最低(100~300ms);需 HTTPS / localhost。 | | 'webcodecs-hw' | 否 | <canvas>(或 <video> via wcsUseVideoRender) | WebGL 合成;Chromium / Firefox 硬件解码。 | | 'webcodecs-sw' | 否 | <canvas> | 强制软解。 | | 'wasm-ffmpeg' | 否 | <canvas> | 兜底软解;需要 decoderUrl / wasmUrl。 | | 'auto' | — | — | MSE → WebCodecs HW → WebCodecs SW → WASM。 |


Player API & 事件

// 生命周期
play(url: string | SourceOptions)
pause(): void
resume(): void
destroy(): void
isDestroyed(): boolean

// 视频控制
fullscreen(): Promise<void>
quitFullscreen(): Promise<void>
isFullscreen(): boolean

// 拍照 / 录像
screenshot(name?: string): Promise<PlayerScreenshotResult | null>
startRecord(name?: string): PlayerRecordHandle | null
stopRecord(): Promise<PlayerRecordResult | null>

// 音频
setVolume(volume: number): void
getVolume(): number
mute(): void
unmute(): void
toggleMute(): void
isMuted(): boolean

// 旋转 / 缩放
setRotate(deg: number): void
getRotate(): number
setScale(scale: number): void
getScale(): number

// 水印
setWatermark(options: PlayerWatermarkOptions | null): void
clearWatermark(): void

// 状态查询
getStatus(): PlayerStatus
getStats(): PlayerStats
getSource(): SourceOptions | null
getBackend(): RenderBackend

// 事件订阅(返回 unsubscribe)
on<E>(event: E, listener: PlayerEventListener<E>): () => void
off<E>(event: E, listener: PlayerEventListener<E>): void

事件列表

| 事件 | 触发时机 | payload | | --- | --- | --- | | play | play() 调用 | void | | pause | pause() 调用或状态切到 paused | void | | error | 任何 ErrorCode | { code: ErrorCode, message, cause? } | | stats | stats 更新(1~2 Hz) | PlayerStatsPayload(继承 PlayerStats + currentSource) | | timeUpdate | 显示视频帧时 | { rawFlvPtsMs, displayTimeMs, currentTime, ... } | | rawFlvPts | 每收到一个 FLV 视频包时 | { rawFlvPtsMs }(毫秒) | | state | 状态字符串变化(jessibuca 风格) | PlayerStatus | | fullscreen | 进入 / 退出全屏 | { fullscreen } | | volume | 音量 / 静音变化 | { volume, muted } | | screenshot | 截图完成 | { blob, url, width, height, capturedAt } | | recordStart | 录像开始 | { suggestedFilename, active, bytesRecorded } | | recordStop | 录像停止,blob 准备好 | { blob, url, durationMs, bytesRecorded, suggestedFilename } | | rotate | setRotate() 调用 | { rotate } | | scale | setScale() 调用 | { scale } | | timeout | heartbeat 判定为 no-signal | { code: ErrorCode, message } | | destroy | destroy() 调用 | void |

rawFlvPtsMs 是最新收到的 ZLM FLV 视频包 PTS(毫秒),可能领先于当前画面;非 FLV 源为 null。 displayTimeMs 是当前显示帧的媒体时间轴(毫秒),MSE 路径来自浏览器 mediaTime,不保证与原始 FLV PTS 同一时间基准。getPlaybackTime() 返回同样的快照;逐包排查跳变请监听 rawFlvPts,不要只采样 timeUpdate。

PlayerStatsPayload

interface PlayerStatsPayload extends PlayerStats {
  currentSource: SourceOptions | null;
}

interface PlayerStats {
  playerId: string;
  status: PlayerStatus;
  health: 'healthy' | 'warning' | 'critical';
  transport?: TransportStats;
  decoder?: DecoderStats;
  lastFramePts: number;
  lastFrameAt: number;
  lastError?: PipelineError;
}

interface PipelineError {
  code: ErrorCode;
  severity: 'warning' | 'recoverable' | 'fatal';
  message: string;
  detail?: unknown;
}

键盘快捷键

| 键 | 默认行为 | | --- | --- | | space | 播放 / 暂停 | | m | 静音 / 取消静音 | | f | 进入 / 退出全屏 | | ← / → | 音量 -5% / +5% | | Esc | 退出全屏 |


错误码

所有通过 player.on('error', …) 收到的失败都携带类型化的 ErrorCode 值。完整列表由 error-code.ts 导出,并作为 ErrorCode 常量从包根再次导出。

分类

| 前缀 | 数量 | 来源 | | --- | --- | --- | | WS_FLV_* | 7 | WebSocketFlvTransport 与 MseRendererPipeline。 | | WEBRTC_* | 17 | WebRtcRendererPipeline,涵盖信令、ICE、回退、重连。 | | 通用 | 4 | TARGET_INVALID、PROTOCOL_UNSUPPORTED、MEDIA_SOURCE_UNSUPPORTED、PIPELINE_DISPOSED。 |

严重性

classifyError(code) 返回:

  • 'fatal' — 例如 WEBRTC_SIGNALING_AUTH_FAILED / 资源耗尽 / 能力缺失(WEBRTC_HEVC_UNSUPPORTED、MEDIA_SOURCE_UNSUPPORTED)。永远不会自动重试。
  • 'recoverable' — 管线会自动重试;告警仍可能有用。
  • 'warning' — 例如 WS_FLV_EOF_UNEXPECTED / WS_FLV_DECODE_ERROR。降级但不一定会自动恢复。

常见用法

import { ErrorCode, classifyError } from 'hq-video-player';

player.on('error', ({ code, message }) => {
  if (classifyError(code) === 'fatal') {
    pageOperator({ player: player.playerId, code, message });
  }
});

状态机

管线在每次状态转换时统一发出权威的 state 事件,Player 转发该事件并维护 PlayerStats.status。

       idle ──► connecting ──► buffering ──► playing
                          ╲         ╲          │
                           ╲         ╲         │
                            ╲         ╲        ▼
                             ▼         ▼   reconnecting
                           error    frozen      │
                              ▲                 │
                              └──── playing ◄───┘
                                    (已恢复)

| 状态 | 含义 | 是否携带 lastError | | --- | --- | --- | | idle | 已绑定但尚未启动。 | 否 | | connecting | 正在建立连接或信令握手。 | 否 | | buffering | 连接成功,尚未解码出第一帧。 | 否 | | playing | 已解码至少一帧。 | 否(成功后被清空) | | reconnecting | 连接已断开,退避 + 抖动已就位。 | 是 | | paused | 用户调用 pause() / destroy() 之外的暂停。 | 否 | | frozen | heartbeat 触发 no-signal 后由管线复检切换过来。 | 通常是 | | error | 致命错误,恢复已耗尽。 | 是(fatal) | | no-signal | heartbeat 在 playing 后未在 timeout 时间内收到新帧。 | 偶尔 |

UI 侧只需订阅一次 player.on('state', …),避免再从 buffering / playing 手工推导。


WebRTC + WS-FLV 回退

WebRtcRendererPipeline 直接基于 RTCPeerConnection 完成 SDP/ICE 握手。当浏览器无法接收 HEVC,或所有 ICE 重启都已耗尽时,管线会在 SourceOptions.fallback 上拉起一条 MseRendererPipeline:

player.play({
  protocol: 'webrtc',
  url: 'webrtc://demo.zlm.example/index/api/webrtc?app=live&stream=cam01',
  signaling: 'zlm-sdk',
  preferredCodec: 'h265',
  iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
  iceDisconnectGraceMs: 5000,
  maxIceRestartAttempts: 2,
  firstFrameTimeoutMs: 8000,
  fallback: { protocol: 'ws-flv', url: 'wss://demo.zlm.example/live/cam01.flv' },
});

管线会自动:设置 HEVC 编码偏好、检测浏览器 HEVC 能力并 fallback、ICE restart 与抖动、 把信令端点的 HTTP 401/403 映射为 WEBRTC_SIGNALING_AUTH_FAILED(severity = 'fatal'), 详见 src/renderer/WebRtcRendererPipeline.ts。


重连错峰

Player 内置心跳 + 错峰重连。当大量 Player 实例同时重连时(例如上游服务器重启):

const baseDelay = 2000 * Math.pow(2, attempts);
const jitter = jitterMs(player.playerId);  // 0..500 ms
const delay = baseDelay + jitter;

jitterMs 是对 playerId 字符串做 FNV-1a 32 位哈希——同一 playerId 永远得到同一个偏移, 因此多次重连之间抖动保持稳定。

抖动应用于以下三个调用点:

  • WebSocketFlvTransport.scheduleReconnect — WS-FLV / HTTP-FLV。
  • WebRtcRendererPipeline.scheduleReconnectOrFail — 非 HEVC 重连。
  • WebRtcRendererPipeline.restartIceOrFail — ICE 重启的重试间隔。

从 0.2.x 升级

0.3.0 的主入口从静态类 hqVideoPlayer 迁移到实例化 Player。 旧静态 API 的兼容 shim 现已移除,请使用下表完成迁移:

| 0.2.x | 0.3.0 推荐 | | --- | --- | | hqVideoPlayer.configure(opts) | new Player({ ...opts }) | | hqVideoPlayer.bindVideoChannel(v, src, opt) | new Player({ container: v, source: src }) + player.play() | | hqVideoPlayer.bindCanvasChannel(c, src, opt) | new Player({ container: c, source: src }) + player.play() | | hqVideoPlayer.connect() | 遍历 players[] 调 player.play(src) 或 player.resume() | | hqVideoPlayer.pause() | 遍历 players[] 调 player.pause() | | hqVideoPlayer.clear() | 遍历 players[] 调 player.destroy() | | hqVideoPlayer.create(opts) | new Player(opts) |

迁移步骤:

  1. 把 import { hqVideoPlayer } from 'hq-video-player' 替换为 import { Player } from 'hq-video-player'。
  2. 把 bindVideoChannel(videoEl, source, opts) 替换为 new Player({ container, source, ...opts }).play()。

构建与发布

# 本地开发
npm install
npm run dev                 # http://localhost:5173  (完整 32 通道 demo)

# 类型检查 + 代码风格检查
npm run typecheck
npm run lint

# 打包库(产物输出到 dist/)
npm run build:package

发布流程:

# 1. 干跑,检查发布产物
npm run publish:dry-run

# 2. 升级版本号并发布到 npm
npm run publish:patch      # 0.3.0 → 0.3.1
npm run publish:minor      # 0.3.0 → 0.4.0
npm run publish:major      # 0.3.0 → 1.0.0

# 3. Beta 通道
npm run tag:beta

prepublishOnly 会自动执行 lint → typecheck → build:package,从机制上避免发布出 损坏的版本。

完整的发布流程(含预期的 dist/ 布局、.npmignore 策略与 npm view 示例)见 PUBLISHING.md。


路线图

  • [ ] HTTP-FLV 传输(fetch + ReadableStream)。
  • [ ] HLS 传输(HLS.js 适配)。
  • [ ] WebTransport 传输。
  • [x] AAC / G.711 音频解码与播放。
  • [x] 直播音视频 PTS 同步。
  • [ ] 长时间内存压力测试(24h × 32 通道)。
  • [x] 移除 hqVideoPlayer compat shim。
  • [ ] 0.5.0:自适应码率 (ABR)、字幕轨道 (CEA-608/708)。
  • [ ] 0.6.0:5+ 种皮肤主题、可自定义快捷键。

License

MIT