feat(hls): m3u8增加EXT-X-PROGRAM-DATE-TIME标签 (#4831)

按RFC 8216第4.3.2.6节,在每个切片的EXTINF之前写入该切片首帧对应的服务器
系统时间(UTC的ISO 8601格式,含毫秒),供播放器对齐字幕流、标记事件点。
直播m3u8与点播vod.m3u8均已支持。

默认关闭,由hls.programDateTime配置项开启。

时间统一以UTC输出而不采用本地时区偏移,因为ZLToolKit的getGMTOff()不含夏令
时修正、且在夏令时切换后不会刷新,会使标注的偏移与实际时刻相差1小时。

索引文件会被反复重建(点播模式下切片不删除,每次重建都遍历全部切片),故取值
在切片入列时格式化一次并缓存,避免在makeIndexFile()中对全部切片重复格式化。

close #4769
This commit is contained in:
YuLi
2026-09-21 20:54:01 -07:00
committed by GitHub
parent eb2601ee1d
commit 10268396b8
8 changed files with 334 additions and 18 deletions

View File

@@ -289,6 +289,13 @@ fastRegister=0
# File extension for fMP4 HLS segment files, e.g. .mp4 or .m4s (the standard extension for fMP4 media segments).
# The init segment is always init.mp4, and mpegts segments are always .ts.
fmp4SegExt=.mp4
# 是否在m3u8中写入EXT-X-PROGRAM-DATE-TIME标签,标记每个切片首帧对应的服务器系统时间
# 取值为UTC的ISO 8601格式(含毫秒,尾缀Z),播放器可据此对齐字幕流、标记事件点,issue: #4769
# Whether to write the EXT-X-PROGRAM-DATE-TIME tag into the m3u8 playlist, marking the wall-clock time
# of each segment's first sample, as a UTC ISO 8601 value with milliseconds (trailing Z).
# Players can use it to align subtitle streams or mark event points. Refer to issue: #4769.
programDateTime=0
[hook]
# 是否启用hook事件,启用后,推拉流都将进行鉴权
# Whether to enable webhook events. When enabled, pushing and pulling streams requires authentication.

View File

@@ -359,6 +359,7 @@ const string kBroadcastRecordTs = HLS_FIELD "broadcastRecordTs";
const string kDeleteDelaySec = HLS_FIELD "deleteDelaySec";
const string kFastRegister = HLS_FIELD "fastRegister";
const string kFmp4SegExt = HLS_FIELD "fmp4SegExt";
const string kProgramDateTime = HLS_FIELD "programDateTime";
static onceToken token([]() {
mINI::Instance()[kSegmentDuration] = 2;
@@ -371,6 +372,7 @@ static onceToken token([]() {
mINI::Instance()[kDeleteDelaySec] = 10;
mINI::Instance()[kFastRegister] = false;
mINI::Instance()[kFmp4SegExt] = ".mp4";
mINI::Instance()[kProgramDateTime] = false;
});
} // namespace Hls

View File

@@ -544,6 +544,9 @@ extern const std::string kFastRegister;
// fmp4 HLS切片文件的扩展名(例如 .mp4 或 .m4s);mpegts切片始终为.ts
// File extension for fMP4 HLS segment files (e.g. .mp4 or .m4s); mpegts segments are always .ts
extern const std::string kFmp4SegExt;
// 是否在m3u8中写入EXT-X-PROGRAM-DATE-TIME标签,以UTC标记每个切片起始的服务器系统时间
// Whether to write the EXT-X-PROGRAM-DATE-TIME tag in m3u8, marking each segment's start wall-clock time in UTC
extern const std::string kProgramDateTime;
} // namespace Hls
// //////////Rtp代理相关配置/////////// [AUTO-TRANSLATED:7b285587]

View File

@@ -8,14 +8,51 @@
* may be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <ctime>
#include <iomanip>
#include "HlsMaker.h"
#include "Common/config.h"
#include "Util/util.h"
using namespace std;
using namespace toolkit;
namespace mediakit {
namespace {
// 将毫秒级系统时间格式化为EXT-X-PROGRAM-DATE-TIME所需的ISO 8601字符串(UTC)
// 形如 2010-02-19T14:54:23.031Z,格式要求见RFC 8216第4.3.2.6节
// Format wall-clock milliseconds as the ISO 8601 string required by EXT-X-PROGRAM-DATE-TIME (UTC)
// e.g. 2010-02-19T14:54:23.031Z, as specified in RFC 8216 section 4.3.2.6
string toProgramDateTimeStr(uint64_t wall_clock_ms) {
// 统一以UTC输出(尾缀Z),避免依赖进程启动时刻的时区快照:
// ZLToolKit的getGMTOff()不含夏令时修正,且在夏令时切换后不会刷新,会导致标注的偏移与实际时刻错位
// Always emit UTC (with the trailing Z) instead of relying on the timezone snapshot taken at startup:
// ZLToolKit's getGMTOff() excludes the DST correction and is never refreshed across DST transitions,
// which would make the declared offset disagree with the actual instant
auto sec = (time_t)(wall_clock_ms / 1000);
struct tm tm_utc;
#if defined(_WIN32)
gmtime_s(&tm_utc, &sec);
#else
gmtime_r(&sec, &tm_utc);
#endif
char buf[32];
auto len = strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &tm_utc);
if (!len) {
// 理论上不会发生,缓冲区足以容纳固定长度的日期时间
// Should never happen; the buffer is large enough for the fixed-length date-time
return "";
}
char msec[8];
snprintf(msec, sizeof(msec), ".%03dZ", (int)(wall_clock_ms % 1000));
return string(buf, len) + msec;
}
} // namespace
HlsMaker::HlsMaker(bool is_fmp4, float seg_duration, uint32_t seg_number, bool seg_keep) {
_is_fmp4 = is_fmp4;
// 最小允许设置为0,0个切片代表点播 [AUTO-TRANSLATED:19235e8e]
@@ -28,17 +65,16 @@ HlsMaker::HlsMaker(bool is_fmp4, float seg_duration, uint32_t seg_number, bool s
void HlsMaker::makeIndexFile(bool include_delay, bool eof) {
GET_CONFIG(uint32_t, segDelay, Hls::kSegmentDelay);
GET_CONFIG(uint32_t, segRetain, Hls::kSegmentRetain);
std::deque<std::tuple<int, std::string>> temp(_seg_dur_list);
std::deque<HlsSegmentInfo> temp(_seg_dur_list);
if (!include_delay && _seg_number) {
while (temp.size() > _seg_number) {
temp.pop_front();
}
}
int maxSegmentDuration = 0;
for (auto &tp : temp) {
int dur = std::get<0>(tp);
if (dur > maxSegmentDuration) {
maxSegmentDuration = dur;
for (auto &info : temp) {
if (info.duration_ms > maxSegmentDuration) {
maxSegmentDuration = info.duration_ms;
}
}
uint64_t index_seq;
@@ -76,8 +112,13 @@ void HlsMaker::makeIndexFile(bool include_delay, bool eof) {
}
stringstream ss;
for (auto &tp : temp) {
ss << "#EXTINF:" << std::setprecision(3) << std::get<0>(tp) / 1000.0 << ",\n" << std::get<1>(tp) << "\n";
for (auto &info : temp) {
// EXT-X-PROGRAM-DATE-TIME只作用于其后的第一个切片,故每个切片前都写入
// EXT-X-PROGRAM-DATE-TIME applies only to the next segment, so write it before each one
if (!info.program_date_time.empty()) {
ss << "#EXT-X-PROGRAM-DATE-TIME:" << info.program_date_time << "\n";
}
ss << "#EXTINF:" << std::setprecision(3) << info.duration_ms / 1000.0 << ",\n" << info.name << "\n";
}
index_str += ss.str();
@@ -156,6 +197,9 @@ void HlsMaker::addNewSegment(uint64_t stamp) {
// 记录本次切片的起始时间戳 [AUTO-TRANSLATED:8eb776e9]
// Record the starting timestamp of this slice
_last_seg_timestamp = _last_timestamp ? _last_timestamp : stamp;
// 同时记录起始的服务器系统时间,用于生成EXT-X-PROGRAM-DATE-TIME
// Also record the starting wall-clock time, used to generate EXT-X-PROGRAM-DATE-TIME
_last_seg_wall_clock = getCurrentMillisecond(true);
}
void HlsMaker::flushLastSegment(bool eof){
@@ -171,7 +215,9 @@ void HlsMaker::flushLastSegment(bool eof){
if (seg_dur <= 0) {
seg_dur = 100;
}
_seg_dur_list.emplace_back(seg_dur, std::move(_last_file_name));
GET_CONFIG(bool, program_date_time, Hls::kProgramDateTime);
_last_seg_date_time = program_date_time ? toProgramDateTimeStr(_last_seg_wall_clock) : string();
_seg_dur_list.push_back(HlsSegmentInfo { (int)seg_dur, std::move(_last_file_name), _last_seg_date_time });
delOldSegment();
// 先flush ts切片,否则可能存在ts文件未写入完毕就被访问的情况 [AUTO-TRANSLATED:f8d6dc87]
// Flush the ts slice first, otherwise there may be a situation where the ts file is not written completely before it is accessed
@@ -186,6 +232,10 @@ void HlsMaker::flushLastSegment(bool eof){
}
}
const string &HlsMaker::getLastSegmentDateTime() const {
return _last_seg_date_time;
}
bool HlsMaker::isLive() const {
return _seg_number != 0;
}
@@ -202,6 +252,8 @@ void HlsMaker::clear() {
_file_index = 0;
_last_timestamp = 0;
_last_seg_timestamp = 0;
_last_seg_wall_clock = 0;
_last_seg_date_time.clear();
_seg_dur_list.clear();
_last_file_name.clear();
}

View File

@@ -13,11 +13,26 @@
#include <string>
#include <deque>
#include <tuple>
#include <cstdint>
namespace mediakit {
// m3u8索引中单个切片的元信息
// Metadata of a single segment in the m3u8 index
struct HlsSegmentInfo {
// 切片时长,单位毫秒
// Segment duration in milliseconds
int duration_ms;
// 切片文件名(相对m3u8的路径)
// Segment file name (path relative to the m3u8)
std::string name;
// 切片首帧对应的服务器系统时间,已格式化为EXT-X-PROGRAM-DATE-TIME的取值
// 未开启该标签时为空串。索引文件会被反复生成,故在切片入列时只格式化一次
// The segment's first-sample wall-clock time, pre-formatted as the EXT-X-PROGRAM-DATE-TIME value.
// Empty when the tag is disabled. The index is rebuilt repeatedly, so it is formatted once on insert
std::string program_date_time;
};
class HlsMaker {
public:
/**
@@ -170,6 +185,14 @@ protected:
*/
void flushLastSegment(bool eof);
/**
* 获取刚结束切片已格式化的EXT-X-PROGRAM-DATE-TIME取值,未开启该标签时为空串
* 仅在onFlushLastSegment()回调期间有效
* Get the pre-formatted EXT-X-PROGRAM-DATE-TIME value of the segment that just ended;
* empty when the tag is disabled. Only valid during the onFlushLastSegment() callback
*/
const std::string &getLastSegmentDateTime() const;
private:
/**
* 生成m3u8文件
@@ -206,9 +229,16 @@ private:
bool _seg_keep = false;
uint64_t _last_timestamp = 0;
uint64_t _last_seg_timestamp = 0;
// 当前切片首帧对应的服务器系统时间,单位毫秒
// Wall-clock time of the current segment's first sample, in milliseconds
uint64_t _last_seg_wall_clock = 0;
// 刚结束切片已格式化的EXT-X-PROGRAM-DATE-TIME取值,供onFlushLastSegment()期间取用
// Pre-formatted EXT-X-PROGRAM-DATE-TIME value of the segment that just ended,
// consumed during the onFlushLastSegment() callback
std::string _last_seg_date_time;
uint64_t _file_index = 0;
std::string _last_file_name;
std::deque<std::tuple<int,std::string> > _seg_dur_list;
std::deque<HlsSegmentInfo> _seg_dur_list;
};
}//namespace mediakit

View File

@@ -118,10 +118,9 @@ void HlsMakerImp::saveCurrentDir() {
}
int maxSegmentDuration = 0;
for (auto &tp : _current_dir_seg_list) {
int dur = std::get<0>(tp);
if (dur > maxSegmentDuration) {
maxSegmentDuration = dur;
for (auto &info : _current_dir_seg_list) {
if (info.duration_ms > maxSegmentDuration) {
maxSegmentDuration = info.duration_ms;
}
}
@@ -136,8 +135,13 @@ void HlsMakerImp::saveCurrentDir() {
index_str += "#EXT-X-MAP:URI=\"init.mp4\"\n";
}
stringstream ss;
for (auto &t : _current_dir_seg_list) {
ss << "#EXTINF:" << std::setprecision(3) << std::get<0>(t) / 1000.0 << ",\n" << std::get<1>(t) << "\n";
for (auto &info : _current_dir_seg_list) {
// EXT-X-PROGRAM-DATE-TIME只作用于其后的第一个切片,故每个切片前都写入
// EXT-X-PROGRAM-DATE-TIME applies only to the next segment, so write it before each one
if (!info.program_date_time.empty()) {
ss << "#EXT-X-PROGRAM-DATE-TIME:" << info.program_date_time << "\n";
}
ss << "#EXTINF:" << std::setprecision(3) << info.duration_ms / 1000.0 << ",\n" << info.name << "\n";
}
_current_dir_seg_list.clear();
index_str += ss.str();
@@ -237,7 +241,8 @@ void HlsMakerImp::onFlushLastSegment(uint64_t duration_ms) {
// Close and flush file to disk
_file = nullptr;
if (!isLive() || isKeep()) {
_current_dir_seg_list.emplace_back(duration_ms, _info.file_name.erase(0, _current_dir.size()));
_current_dir_seg_list.push_back(
HlsSegmentInfo { (int)duration_ms, _info.file_name.erase(0, _current_dir.size()), getLastSegmentDateTime() });
}
GET_CONFIG(bool, broadcastRecordTs, Hls::kBroadcastRecordTs);
if (broadcastRecordTs) {

View File

@@ -82,7 +82,7 @@ private:
HlsMediaSource::Ptr _media_src;
toolkit::EventPoller::Ptr _poller;
std::map<uint64_t/*index*/,std::string/*file_path*/> _segment_file_paths;
std::deque<std::tuple<int,std::string> > _current_dir_seg_list;
std::deque<HlsSegmentInfo> _current_dir_seg_list;
};
}//namespace mediakit

View File

@@ -0,0 +1,217 @@
/*
* Copyright (c) 2016-present The ZLMediaKit project authors. All Rights Reserved.
*
* This file is part of ZLMediaKit(https://github.com/ZLMediaKit/ZLMediaKit).
*
* Use of this source code is governed by MIT-like license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
*/
#include <cassert>
#include <cstring>
#include <iostream>
#include <regex>
#include <string>
#include <vector>
#include "Common/config.h"
#include "Record/HlsMaker.h"
#include "Util/util.h"
using namespace std;
using namespace toolkit;
using namespace mediakit;
namespace {
size_t g_failed = 0;
// GET_CONFIG将配置值静态缓存,改动后须广播配置重载事件才会刷新
// GET_CONFIG caches config values statically; a reload broadcast is required to refresh them
void setProgramDateTime(bool enabled) {
mINI::Instance()[Hls::kProgramDateTime] = enabled;
NOTICE_EMIT(BroadcastReloadConfigArgs, Broadcast::kBroadcastReloadConfig);
}
void expect(bool ok, const string &what) {
if (!ok) {
++g_failed;
cout << "[FAIL] " << what << endl;
} else {
cout << "[ OK ] " << what << endl;
}
}
// 捕获m3u8输出的HlsMaker,切片直接以序号命名
// HlsMaker that captures the m3u8 output; segments are simply named by index
class TestHlsMaker : public HlsMaker {
public:
TestHlsMaker(float seg_duration, uint32_t seg_number)
: HlsMaker(false, seg_duration, seg_number, false) {}
// 喂入一个关键帧包,触发切片
// Feed one key-frame packet to trigger segmentation
void feedKeyFrame(uint64_t timestamp) {
char payload[188] = { 0 };
inputData(payload, sizeof(payload), timestamp, true);
}
// 喂入一个普通包,推进切片内的时间戳
// Feed a normal packet to advance the timestamp inside the segment
void feedData(uint64_t timestamp) {
char payload[188] = { 0 };
inputData(payload, sizeof(payload), timestamp, false);
}
void finish() { flushLastSegment(true); }
string m3u8;
protected:
string onOpenSegment(uint64_t index) override { return to_string(index) + ".ts"; }
void onDelSegment(uint64_t index) override {}
void onWriteInitSegment(const char *data, size_t len) override {}
void onWriteSegment(const char *data, size_t len) override {}
void onWriteHls(const string &data, bool include_delay) override {
if (!include_delay) {
m3u8 = data;
}
}
};
// 生成一份含3个切片的m3u8
// Produce an m3u8 containing 3 segments
string makeM3u8(float seg_duration = 1) {
TestHlsMaker maker(seg_duration, 3);
uint64_t stamp = 0;
for (int i = 0; i < 3; ++i) {
maker.feedKeyFrame(stamp);
stamp += (uint64_t)(seg_duration * 1000);
maker.feedData(stamp);
}
maker.finish();
return maker.m3u8;
}
void test_tag_present_and_well_formed() {
setProgramDateTime(true);
auto m3u8 = makeM3u8();
expect(m3u8.find("#EXT-X-PROGRAM-DATE-TIME:") != string::npos,
"开启配置时m3u8应包含EXT-X-PROGRAM-DATE-TIME标签");
// RFC 8216要求ISO 8601格式,且SHOULD带时区与毫秒
// RFC 8216 requires ISO 8601, and SHOULD carry timezone and milliseconds
regex re(R"(#EXT-X-PROGRAM-DATE-TIME:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)");
expect(regex_search(m3u8, re), "标签取值应为带毫秒的UTC ISO 8601时间");
}
void test_tag_precedes_its_segment() {
setProgramDateTime(true);
auto m3u8 = makeM3u8();
// 标签只作用于其后的第一个切片,必须紧邻对应的EXTINF之前
// The tag applies only to the next segment, so it must sit right before its EXTINF
size_t pos = 0, pairs = 0;
while ((pos = m3u8.find("#EXT-X-PROGRAM-DATE-TIME:", pos)) != string::npos) {
auto line_end = m3u8.find('\n', pos);
expect(line_end != string::npos, "标签行应以换行结束");
if (line_end == string::npos) {
return;
}
expect(m3u8.compare(line_end + 1, strlen("#EXTINF:"), "#EXTINF:") == 0,
"每个EXT-X-PROGRAM-DATE-TIME之后应紧跟#EXTINF");
++pairs;
pos = line_end + 1;
}
expect(pairs == 3, "3个切片应各带1个EXT-X-PROGRAM-DATE-TIME标签, 实际: " + to_string(pairs));
}
void test_disabled_by_config() {
setProgramDateTime(false);
auto m3u8 = makeM3u8();
expect(m3u8.find("#EXT-X-PROGRAM-DATE-TIME") == string::npos,
"关闭配置时m3u8不应包含EXT-X-PROGRAM-DATE-TIME标签");
expect(m3u8.find("#EXTINF:") != string::npos,
"关闭配置时切片条目仍应正常输出");
setProgramDateTime(true);
}
// 从m3u8中取出首个EXT-X-PROGRAM-DATE-TIME的取值
// Extract the first EXT-X-PROGRAM-DATE-TIME value out of the m3u8
string extractDateTime(const string &m3u8) {
const string tag = "#EXT-X-PROGRAM-DATE-TIME:";
auto pos = m3u8.find(tag);
if (pos == string::npos) {
return "";
}
auto begin = pos + tag.size();
auto end = m3u8.find('\n', begin);
return end == string::npos ? m3u8.substr(begin) : m3u8.substr(begin, end - begin);
}
// 将ISO 8601的UTC字符串解析回epoch秒,解析失败返回-1
// Parse an ISO 8601 UTC string back into epoch seconds; returns -1 on failure
time_t parseUtc(const string &str) {
struct tm t;
memset(&t, 0, sizeof(t));
int msec = 0;
if (sscanf(str.c_str(), "%d-%d-%dT%d:%d:%d.%d", &t.tm_year, &t.tm_mon, &t.tm_mday,
&t.tm_hour, &t.tm_min, &t.tm_sec, &msec) != 7) {
return (time_t)-1;
}
t.tm_year -= 1900;
t.tm_mon -= 1;
#if defined(_WIN32)
return _mkgmtime(&t);
#else
return timegm(&t);
#endif
}
void test_value_is_utc_wall_clock() {
setProgramDateTime(true);
auto before = time(nullptr);
auto m3u8 = makeM3u8();
auto after = time(nullptr);
auto value = extractDateTime(m3u8);
expect(!value.empty(), "应能从m3u8中取到标签取值");
if (value.empty()) {
return;
}
expect(value.back() == 'Z', "取值应以Z结尾表明其为UTC: " + value);
auto parsed = parseUtc(value);
expect(parsed != (time_t)-1, "取值应可按ISO 8601解析: " + value);
// 取值必须落在m3u8生成前后的UTC区间内。若实现把本地时间误标成Z
// (最危险的一种回归),在非UTC时区下偏差恰等于时区偏移,此断言即可捕获
// The value must fall inside the UTC window around m3u8 generation. Should the
// implementation mislabel local time as Z (the worst regression), the deviation equals
// the timezone offset on a non-UTC host, which this assertion catches
expect(parsed >= before - 2 && parsed <= after + 2,
"取值应落在生成时刻的UTC区间内(可捕获把本地时间误标为UTC): " + value);
}
} // namespace
int main(int argc, char *argv[]) {
Logger::Instance().add(std::make_shared<ConsoleChannel>());
Logger::Instance().setLevel(LWarn);
test_value_is_utc_wall_clock();
test_tag_present_and_well_formed();
test_tag_precedes_its_segment();
test_disabled_by_config();
if (g_failed) {
cout << "\n" << g_failed << " check(s) failed" << endl;
return 1;
}
cout << "\nall checks passed" << endl;
return 0;
}