HLS 协议
HLS(HTTP Live Streaming)是 Apple 提出的基于 HTTP 的流媒体协议。通过将直播流切割为 TS 片段并生成 M3U8 播放列表,HLS 具有极佳的 CDN 兼容性和设备覆盖率,是大规模分发的首选协议。
| 属性 | 值 |
|---|---|
| 传输层 | HTTP(共享引擎 HTTP 端口) |
| 推流 | ❌ 不支持 |
| 拉流 | ✅ 支持 |
| 延迟 | 5-30 秒(取决于切片时长) |
| Feature Flag | hls |
Feature 启用
Section titled “Feature 启用”[features]hls = ["dep:plugin-hls"]hls: enable: true segment_duration: 6 max_segments: 5 output_dir: "./hls" write_to_disk: true| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
enable | bool | true | 是否启用 HLS 插件 |
segment_duration | u64 | 6 | TS 切片时长(秒) |
max_segments | usize | 5 | 播放列表保留的最大切片数 |
output_dir | string | "./hls" | 切片文件输出目录 |
write_to_disk | bool | true | 是否将切片写入磁盘 |
URL 格式
Section titled “URL 格式”M3U8 播放列表
Section titled “M3U8 播放列表”http://host:port/hls/{streamPath}/index.m3u8http://host:port/hls/{streamPath}/{sequence}.ts示例:
http://localhost:8080/hls/live/test/index.m3u8http://localhost:8080/hls/live/test/0.ts使用 FFplay
Section titled “使用 FFplay”ffplay http://localhost:8080/hls/live/test/index.m3u8使用 VLC
Section titled “使用 VLC”- 打开 VLC,选择 媒体 → 打开网络串流
- 输入 URL:
http://localhost:8080/hls/live/test/index.m3u8 - 点击 播放
使用 hls.js 在浏览器中播放:
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script><video id="player" controls></video><script> const video = document.getElementById('player'); if (Hls.isSupported()) { const hls = new Hls(); hls.loadSource('http://localhost:8080/hls/live/test/index.m3u8'); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED, () => video.play()); } else if (video.canPlayType('application/vnd.apple.mpegurl')) { // Safari 原生支持 video.src = 'http://localhost:8080/hls/live/test/index.m3u8'; video.play(); }</script>HLS 录制
Section titled “HLS 录制”HLS 插件提供录制 API,可以将流录制为 HLS 格式(M3U8 + TS 文件):
# 开始录制curl -X POST http://localhost:8080/hls/record/start/live/test
# 停止录制curl -X POST http://localhost:8080/hls/record/stop/live/test
# 查看录制列表curl http://localhost:8080/hls/record/list
# 查看录制状态curl http://localhost:8080/hls/record/status/live/test
# 查询历史录像curl http://localhost:8080/hls/record/records- 订阅流:当首次请求 HLS 播放列表时,插件自动订阅对应的流
- 切片生成:从流中持续读取帧数据,按
segment_duration切割为 TS 片段 - 播放列表更新:每生成一个新切片,自动更新 M3U8 播放列表
- 滑动窗口:保留最近
max_segments个切片,旧切片自动清理 - 存储策略:切片同时保存在内存和磁盘(取决于
write_to_disk配置)
HLS 的延迟主要由以下因素决定:
总延迟 ≈ segment_duration × (max_segments - 1) + 播放器缓冲优化建议:
# 低延迟配置hls: segment_duration: 2 max_segments: 3此配置下理论最低延迟约 4-6 秒。
# 1. 通过 RTMP 推流ffmpeg -re -i input.mp4 -c copy -f flv rtmp://localhost:1935/live/test
# 2. 通过 HLS 拉流ffplay http://localhost:8080/hls/live/test/index.m3u8
# 3. 也可以同时通过其他协议拉流ffplay http://localhost:8080/flv/live/test.flv联系我们
微信公众号:不卡科技
腾讯频道:流媒体技术
QQ 频道:p0qq0crz08
QQ 群:751639168