diff --git a/src/Http/HttpConst.cpp b/src/Http/HttpConst.cpp index 240057d3..f0f347d1 100644 --- a/src/Http/HttpConst.cpp +++ b/src/Http/HttpConst.cpp @@ -130,6 +130,7 @@ static const char *s_mime_src[][2] = { {"ai", "application/postscript"}, {"rtf", "application/rtf"}, {"m3u8", "application/vnd.apple.mpegurl"}, + {"mpd", "application/dash+xml"}, {"xls", "application/vnd.ms-excel"}, {"eot", "application/vnd.ms-fontobject"}, {"ppt", "application/vnd.ms-powerpoint"}, diff --git a/src/Http/HttpFileManager.cpp b/src/Http/HttpFileManager.cpp index a659cadf..54cb34a8 100644 --- a/src/Http/HttpFileManager.cpp +++ b/src/Http/HttpFileManager.cpp @@ -35,6 +35,9 @@ static size_t kFindSrcIntervalSecond = 3; static const string kCookieName = "ZLM_HTTP_COOKIE"; static const string kHlsSuffix = "/hls.m3u8"; static const string kHlsFMP4Suffix = "/hls.fmp4.m3u8"; +// dash mpd请求后缀, 它与hls.fmp4共用同一个MediaSource与fmp4分片 +// Dash mpd request suffix, it shares the hls.fmp4 media source and fmp4 segments +static const string kDashSuffix = "/dash.mpd"; struct HttpCookieAttachment { // 是否已经查找到过MediaSource [AUTO-TRANSLATED:b5b9922a] @@ -494,23 +497,30 @@ static string getFilePath(const Parser &parser,const MediaInfo &media_info, Sess * [AUTO-TRANSLATED:2d840fe6] */ static void accessFile(Session &sender, const Parser &parser, const MediaInfo &media_info, const string &file_path, const HttpFileManager::invoker &cb) { - bool is_hls = end_with(file_path, kHlsSuffix) || end_with(file_path, kHlsFMP4Suffix); + bool is_dash = end_with(file_path, kDashSuffix); + bool is_hls = is_dash || end_with(file_path, kHlsSuffix) || end_with(file_path, kHlsFMP4Suffix); if (is_hls) { - // hls,那么移除掉后缀获取真实的stream_id并且修改协议为HLS [AUTO-TRANSLATED:94b5818a] - // hls, then remove the suffix to get the real stream_id and change the protocol to HLS + // hls或dash,那么移除掉后缀获取真实的stream_id并且修改协议为HLS [AUTO-TRANSLATED:94b5818a] + // hls or dash, then remove the suffix to get the real stream_id and change the protocol to HLS if (end_with(file_path, kHlsSuffix)) { const_cast(media_info.schema) = HLS_SCHEMA; replace(const_cast(media_info.stream), kHlsSuffix, ""); } else { + // dash共用hls.fmp4的MediaSource + // Dash shares the hls.fmp4 media source const_cast(media_info.schema) = HLS_FMP4_SCHEMA; - replace(const_cast(media_info.stream), kHlsFMP4Suffix, ""); + if (is_dash) { + replace(const_cast(media_info.stream), kDashSuffix, ""); + } else { + replace(const_cast(media_info.stream), kHlsFMP4Suffix, ""); + } } } weak_ptr weakSession = static_pointer_cast(sender.shared_from_this()); // 判断是否有权限访问该文件 [AUTO-TRANSLATED:b7f595f5] // Determine whether you have permission to access this file - canAccessPath(sender, parser, media_info, file_path, false, [cb, file_path, parser, is_hls, media_info, weakSession](const string &err_msg, const HttpServerCookie::Ptr &cookie) { + canAccessPath(sender, parser, media_info, file_path, false, [cb, file_path, parser, is_hls, is_dash, media_info, weakSession](const string &err_msg, const HttpServerCookie::Ptr &cookie) { auto strongSession = weakSession.lock(); if (!strongSession) { // http客户端已经断开,不需要回复 [AUTO-TRANSLATED:9a252e21] @@ -563,11 +573,11 @@ static void accessFile(Session &sender, const Parser &parser, const MediaInfo &m } } if (!is_hls || !cookie) { - // 不是hls或访问m3u8文件不带cookie, 直接回复文件或404 [AUTO-TRANSLATED:64e5d19b] - // Not hls or accessing m3u8 files without cookies, directly reply to the file or 404 + // 不是hls/dash或访问m3u8/mpd文件不带cookie, 直接回复文件或404 [AUTO-TRANSLATED:64e5d19b] + // Not hls/dash or accessing m3u8/mpd files without cookies, directly reply to the file or 404 response_file(cookie, cb, file_path, parser); if (is_hls) { - WarnL << "access m3u8 file without cookie:" << file_path; + WarnL << "access m3u8/mpd file without cookie:" << file_path; } return; } @@ -575,9 +585,9 @@ static void accessFile(Session &sender, const Parser &parser, const MediaInfo &m auto &attach = cookie->getAttach(); auto src = attach._hls_data->getMediaSource(); if (src) { - // 直接从内存获取m3u8索引文件(而不是从文件系统) [AUTO-TRANSLATED:c772e342] - // Get the m3u8 index file directly from memory (instead of from the file system) - response_file(cookie, cb, file_path, parser, src->getIndexFile()); + // 直接从内存获取m3u8/mpd索引文件(而不是从文件系统) [AUTO-TRANSLATED:c772e342] + // Get the m3u8/mpd index file directly from memory (instead of from the file system) + response_file(cookie, cb, file_path, parser, is_dash ? src->getMpdFile() : src->getIndexFile()); return; } if (attach._find_src && attach._find_src_ticker.elapsedTime() < kFindSrcIntervalSecond * 1000) { @@ -589,7 +599,7 @@ static void accessFile(Session &sender, const Parser &parser, const MediaInfo &m // hls流可能未注册,MediaSource::findAsync可以触发not_found事件,然后再按需推拉流 [AUTO-TRANSLATED:f4acd717] // The hls stream may not be registered, MediaSource::findAsync can trigger the not_found event, and then push and pull the stream on demand - MediaSource::findAsync(media_info, strongSession, [response_file, cookie, cb, file_path, parser](const MediaSource::Ptr &src) { + MediaSource::findAsync(media_info, strongSession, [response_file, cookie, cb, file_path, parser, is_dash](const MediaSource::Ptr &src) { auto hls = dynamic_pointer_cast(src); if (!hls) { // 流不在线 [AUTO-TRANSLATED:5a6a5695] @@ -615,11 +625,18 @@ static void accessFile(Session &sender, const Parser &parser, const MediaInfo &m if (muxer) { attach._hls_root_path = muxer->getOption().hls_save_path; } - // m3u8文件可能不存在, 等待m3u8索引文件按需生成 [AUTO-TRANSLATED:0dbd4df2] - // The m3u8 file may not exist, wait for the m3u8 index file to be generated on demand - hls->getIndexFile([response_file, file_path, cookie, cb, parser](const string &file) { + auto on_index_file = [response_file, file_path, cookie, cb, parser](const string &file) { response_file(cookie, cb, file_path, parser, file); - }); + }; + if (is_dash) { + // mpd文件可能不存在, 等待dash mpd文件按需生成 + // The mpd file may not exist, wait for the dash mpd file to be generated on demand + hls->getMpdFile(on_index_file); + } else { + // m3u8文件可能不存在, 等待m3u8索引文件按需生成 [AUTO-TRANSLATED:0dbd4df2] + // The m3u8 file may not exist, wait for the m3u8 index file to be generated on demand + hls->getIndexFile(on_index_file); + } }); }); } diff --git a/src/Record/DashCodec.h b/src/Record/DashCodec.h new file mode 100644 index 00000000..e554d54b --- /dev/null +++ b/src/Record/DashCodec.h @@ -0,0 +1,147 @@ +/* + * 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. + */ + +#ifndef ZLMEDIAKIT_DASHCODEC_H +#define ZLMEDIAKIT_DASHCODEC_H + +#include +#include +#include +#include "Extension/Track.h" + +namespace mediakit { + +/** + * 由Track的extra data生成真实的RFC 6381 codecs字符串 + * dash.js用它做MediaSource.isTypeSupported()能力检查,必须给出真实值 + * Generate a real RFC 6381 codec string from the Track's extra data. + * dash.js requires the codecs attribute on to select decoders. + * + * H.264 → avc1.XXYYZZ (from avcC: profile_idc, compat, level_idc) + * H.265 → hvc1.X.Y.LZ.W (from hvcC: profile_space+id, compat, tier+level, constraints) + * AAC → mp4a.40.N (from AudioSpecificConfig: audio object type) + * VP8/9 → vp8 / vp9 + * AV1 → av01.P.LLT.C (from AV1CodecConfigurationRecord) + * Opus → opus + * G.711 → pcma / pcmu + * MP3 → mp4a.6b + */ +inline std::string getDashCodecString(const Track::Ptr &track) { + auto id = track->getCodecId(); + auto extra = track->getExtraData(); + const uint8_t *data = extra ? (const uint8_t *)extra->data() : nullptr; + size_t size = extra ? extra->size() : 0; + char buf[64]; + + switch (id) { + case CodecH264: { + // avcC body: version(1) profile_idc(1) compat(1) level_idc(1) ... + if (data && size >= 4) { + snprintf(buf, sizeof(buf), "avc1.%02x%02x%02x", data[1], data[2], data[3]); + return buf; + } + return "avc1.4d001f"; // fallback: Main Profile Level 3.1 + } + + case CodecH265: { + // hvcC body per ISO 14496-15 HEVCDecoderConfigurationRecord: + // byte 0 = configurationVersion + // byte 1 = [profile_space(2) | tier_flag(1) | profile_idc(5)] + // bytes 2-5 = profile_compatibility_flags + // bytes 6-11 = constraint_indicator (48-bit) + // byte 12 = general_level_idc + if (data && size >= 13) { + uint8_t ps = (data[1] >> 6) & 0x03; // general_profile_space + uint8_t pid = data[1] & 0x1f; // general_profile_idc + uint32_t pcf = ((uint32_t)data[2] << 24) | ((uint32_t)data[3] << 16) | ((uint32_t)data[4] << 8) | (uint32_t)data[5]; + char tier = ((data[1] >> 5) & 0x01) ? 'H' : 'L'; + uint8_t level = data[12]; // general_level_idc + uint64_t cons = 0; // constraint_indicator (48-bit) + for (int k = 6; k < 12; ++k) { + cons = (cons << 8) | data[k]; + } + // RFC 6381 HEVC codec string: + // hvc1.... + // The compat/constraint fields are hex with trailing zeros trimmed + // (0x60000000 -> "6") and the level is decimal (L150, not L96), + // otherwise Chrome's MediaSource.isTypeSupported() rejects it. + auto hextrim = [](uint64_t v) -> std::string { + if (v == 0) { + return "0"; + } + char b[24]; + snprintf(b, sizeof(b), "%llX", (unsigned long long)v); + std::string s = b; + while (s.size() > 1 && s.back() == '0') { + s.pop_back(); + } + return s; + }; + std::string cs = "hvc1."; + if (ps) { + cs += static_cast('A' + ps - 1); + } + cs += std::to_string((unsigned)pid); + cs += '.' + hextrim(pcf); + cs += '.'; + cs += tier; + cs += std::to_string((unsigned)level); + cs += '.' + hextrim(cons); + return cs; + } + return "hvc1.1.6.L120.B0"; // fallback: Main Profile + } + + case CodecAAC: { + // AudioSpecificConfig: 2 bytes + // bits 0-4: audioObjectType (5 bits for values 1-31) + // bits 5-8: samplingFrequencyIndex + // bits 9-12: channelConfiguration + if (data && size >= 2) { + uint8_t aot = (data[0] >> 3) & 0x1f; + snprintf(buf, sizeof(buf), "mp4a.40.%u", aot); + return buf; + } + return "mp4a.40.2"; // fallback: AAC-LC + } + + case CodecVP8: return "vp8"; + case CodecVP9: return "vp9"; + + case CodecAV1: { + // AV1CodecConfigurationRecord: + // byte 0: marker(1) | version(7) = 0x81 + // byte 1: seq_profile(3) | seq_level_idx_0(5) + // byte 2: seq_tier_0(1) | high_bitdepth(1) | twelve_bit(1) | + // monochrome(1) | chroma_subsampling_x(1) | + // chroma_subsampling_y(1) | chroma_sample_position(2) + if (data && size >= 3) { + uint8_t profile = (data[1] >> 5) & 0x07; + uint8_t level = data[1] & 0x1f; + uint8_t tier = (data[2] >> 7) & 0x01; + uint8_t bitdepth = 8 + 2 * ((data[2] >> 6) & 0x01) + 2 * ((data[2] >> 5) & 0x01); + snprintf(buf, sizeof(buf), "av01.%u.%02u%c.%02u", profile, level, tier ? 'H' : 'M', bitdepth); + return buf; + } + return "av01.0.01M.08"; + } + + case CodecOpus: return "opus"; + case CodecMP3: return "mp4a.6b"; + + case CodecG711A: return "pcma"; + case CodecG711U: return "pcmu"; + + default: return ""; + } +} + +} // namespace mediakit +#endif // ZLMEDIAKIT_DASHCODEC_H diff --git a/src/Record/HlsMaker.cpp b/src/Record/HlsMaker.cpp index 5f84008a..9bef12f1 100644 --- a/src/Record/HlsMaker.cpp +++ b/src/Record/HlsMaker.cpp @@ -53,6 +53,34 @@ string toProgramDateTimeStr(uint64_t wall_clock_ms) { } // namespace +// 由切片数据流驱动的两次mpd重发布之间的最小间隔(ms) +// Minimum interval(ms) between two mpd republish driven by the segment data flow +static const uint64_t kDashRefreshMs = 500; + +// 输出dash的xs:duration,形如 PT10.500S +// Emit a dash xs:duration, e.g. PT10.500S +static string dashDuration(double seconds) { + char buf[64]; + snprintf(buf, sizeof(buf), "PT%.3fS", seconds); + return buf; +} + +static string dashXmlEscape(const string &str) { + string ret; + ret.reserve(str.size()); + for (auto &ch : str) { + switch (ch) { + case '&': ret += "&"; break; + case '<': ret += "<"; break; + case '>': ret += ">"; break; + case '"': ret += """; break; + case '\'': ret += "'"; break; + default: ret += ch; break; + } + } + return ret; +} + HlsMaker::HlsMaker(bool is_fmp4, float seg_duration, uint32_t seg_number, bool seg_keep) { _is_fmp4 = is_fmp4; // 最小允许设置为0,0个切片代表点播 [AUTO-TRANSLATED:19235e8e] @@ -128,6 +156,243 @@ void HlsMaker::makeIndexFile(bool include_delay, bool eof) { onWriteHls(index_str, include_delay); } +void HlsMaker::makeDashFile(bool eof, bool memory_only) { + if (!_is_fmp4) { + // dash依赖fmp4切片,仅在fmp4模式下生成 + // Dash relies on the fmp4 segments, only generated in fmp4 mode + return; + } + + std::deque temp(_seg_dur_list); + // 首个列出切片在dash媒体时间轴上的起始时间 + // Start time of the first listed segment on the dash media timeline + uint64_t time_offset = _dash_timeline_offset_ms; + if (_seg_number) { + while (temp.size() > _seg_number) { + time_offset += (uint64_t)temp.front().duration_ms; + temp.pop_front(); + } + } + if (temp.empty()) { + return; + } + + uint64_t total_dur_ms = 0; + uint64_t total_bytes = 0; + uint64_t max_seg_ms = 0; + for (auto &info : temp) { + total_dur_ms += (uint64_t)info.duration_ms; + total_bytes += (uint64_t)info.bytes; + if ((uint64_t)info.duration_ms > max_seg_ms) { + max_seg_ms = (uint64_t)info.duration_ms; + } + } + // 在窗分片的平均码率,作为Representation的bandwidth + // Average bitrate of the listed segments, used as the representation bandwidth + uint64_t bandwidth = total_dur_ms ? (total_bytes * 8 * 1000 / total_dur_ms) : 0; + + bool is_live = isLive() && !eof; + // 最后一个可用分片在dash媒体时间轴上的末尾 + // End of the last available segment on the dash media timeline + uint64_t media_end_ms = time_offset + total_dur_ms; + uint64_t now_ms = getCurrentMillisecond(true); + + // dash媒体时间轴到墙钟的映射为: + // wall_clock(presentation_time) = availabilityStartTime + presentation_time + // 把availabilityStartTime锚定到(now - media_end),live edge正好落在最后一个可用分片的末尾 + // + // 媒体时间轴的推进速度通常并不等于墙钟(丢帧、源端抖动、时钟校正),所以锚点每次发布都要修正。 + // 一次性对齐全部偏差会让live edge阶跃:播放器测到延迟跳变后用live catch-up变速(0.5x/1.5x)追赶, + // 1.5倍速消费必然快于分片生产,缓冲被吃光后waiting,延迟又变大,形成自激振荡。 + // 因此把修正限制在"流逝时间的一个比例"内,由周期性刷新把余量摊平 + // The dash media timeline is mapped to the wall clock by: + // wall_clock(presentation_time) = availabilityStartTime + presentation_time + // Anchoring availabilityStartTime to (now - media_end) puts the live edge + // exactly at the end of the last available segment. + // + // The media timeline usually does NOT advance at exactly the wall clock rate + // (lost frames, source jitter, wall clock corrections), so the anchor has to + // be corrected on every publish. Correcting the whole difference at once + // makes the live edge step: the player measures a latency jump and answers + // with a live catch-up playback rate change (0.5x/1.5x), which consumes the + // buffer faster than the segments are produced and ends up starving it on + // every segment. Limit the correction to a fraction of the elapsed time and + // let the periodic mpd refresh spread the rest, the live edge then advances + // smoothly at the media rate. + uint64_t target_ast_ms = now_ms > media_end_ms ? now_ms - media_end_ms : 0; + int64_t ast_diff = (int64_t)target_ast_ms - (int64_t)_ast_wall_ms; + if (_ast_wall_ms == 0 || _dash_last_emit_ms == 0 || now_ms <= _dash_last_emit_ms) { + // 首次发布(或reset后): 直接对齐 + // First publish (or after a reset): align right away + _ast_wall_ms = target_ast_ms; + } else if ((uint64_t)(ast_diff < 0 ? -ast_diff : ast_diff) > max_seg_ms * 3) { + // 偏差过大,限速器永远追不上: 直接对齐 + // Way out of sync, the rate limiter would never catch up: realign + _ast_wall_ms = target_ast_ms; + } else { + uint64_t max_step_ms = (now_ms - _dash_last_emit_ms) / 4; + if (max_step_ms < 50) { + max_step_ms = 50; + } + if (ast_diff > (int64_t)max_step_ms) { + ast_diff = (int64_t)max_step_ms; + } else if (ast_diff < -(int64_t)max_step_ms) { + ast_diff = -(int64_t)max_step_ms; + } + _ast_wall_ms += (uint64_t)ast_diff; + } + _dash_last_emit_ms = now_ms; + string ast_iso = toProgramDateTimeStr(_ast_wall_ms); + string now_iso = toProgramDateTimeStr(now_ms); + + // 播放器至少要能缓冲一个完整分片 + // The player must be able to buffer at least one full segment + uint64_t min_buffer_ms = max_seg_ms > 2000 ? max_seg_ms : 2000; + // 让播放点落后live edge: 2倍最大分片时长,至少4秒。同时必须高出滑动窗口底部至少一个整片, + // 否则正在播放的就是即将过期的那一片,dash.js拒拉后停顿,等窗口滑动才恢复(周期性顿挫) + // Keep the play head behind the live edge: 2x the max segment duration, at + // least 4 seconds. It must also stay at least one full segment above the + // bottom of the sliding window, otherwise the segment being played is the + // one that is about to expire and dash.js refuses to fetch it: the player + // then stalls until the window slides and it recovers (periodic stalls). + uint64_t suggested_delay_ms = max_seg_ms * 2; + if (suggested_delay_ms < 4000) { + suggested_delay_ms = 4000; + } + uint64_t max_delay_ms = total_dur_ms > max_seg_ms ? total_dur_ms - max_seg_ms : total_dur_ms / 2; + if (suggested_delay_ms > max_delay_ms) { + suggested_delay_ms = max_delay_ms; + } + // minimumUpdatePeriod必须远小于分片周期。播放器只有在重新拉取mpd时才知道有新分片, + // 这期间它的live edge随墙钟前进而内容不动,播放点前方缓冲 = suggestedPresentationDelay + // - 距上次flush的时间 - mpd更新周期。按分片周期采样会与分片产出混叠,播放器周期性无片可拉而停顿 + // minimumUpdatePeriod MUST be far smaller than the segment period. The player + // only learns about a new segment when it re-fetches the mpd, and until then + // its live edge keeps moving while the content does not: the buffer ahead of + // the play head is (suggestedPresentationDelay - time since the last flush - + // mpd update period). Sampling at the segment period aliases with the segment + // production, the player periodically finds nothing to fetch and stalls until + // the next successful update. + uint64_t update_ms = max_seg_ms / 3; + if (update_ms < 1000) { + update_ms = 1000; + } else if (update_ms > 2000) { + update_ms = 2000; + } + // minBufferTime不得超过播放点前方实际可交付的缓冲(suggestedPresentationDelay + // - 一个分片周期 - minimumUpdatePeriod),否则播放器会一直等一个永远填不满的目标, + // 延迟随之超过目标值,live catch-up启动后消费快于生产,每个分片周期饿死一次 + // Never ask the player to buffer more than the stream can actually deliver + // ahead of the play head (suggestedPresentationDelay minus one segment period + // minus the mpd update period): a minBufferTime that cannot be reached makes + // the player wait for buffer that never comes, the latency then grows past the + // target and the live catch-up starts consuming faster than the segments are + // produced, which starves the buffer on every segment. + uint64_t ahead_ms = suggested_delay_ms > max_seg_ms + update_ms ? suggested_delay_ms - max_seg_ms - update_ms : 0; + if (min_buffer_ms > ahead_ms) { + min_buffer_ms = ahead_ms > 1000 ? ahead_ms : 1000; + } + // live edge由播放器自己的时钟推算,可能比最后一个列出分片领先最多一个分片, + // 窗口留出余量,避免最老的分片提前"过期" + // The live edge is computed from the player's own clock, so it can sit up to + // one segment ahead of the last listed segment. Keep a margin on the window + // so the oldest listed segment does not fall out of it ahead of time. + uint64_t window_margin_ms = max_seg_ms / 2; + if (window_margin_ms > 2000) { + window_margin_ms = 2000; + } + + string mpd; + mpd.reserve(4096); + mpd += "\n"; + mpd += "\n"; + } + // Period恒从0开始,滑动窗口只体现在SegmentTimeline的绝对@t上, + // 播放器在整个直播会话中看到的是稳定的单Period时间轴 + // The period always starts at 0, the sliding window is expressed by the + // absolute @t of the segment timeline: the player keeps a single stable + // period for the whole live session + mpd += " \n"; + mpd += string(" \n"; + mpd += " \n"; + mpd += " \n"; + mpd += " \n"; + uint64_t seg_t_ms = time_offset; + for (auto &info : temp) { + mpd += " \n"; + seg_t_ms += (uint64_t)info.duration_ms; + } + mpd += " \n"; + for (auto &info : temp) { + mpd += " \n"; + } + mpd += " \n"; + mpd += " \n"; + mpd += " \n"; + mpd += " \n"; + mpd += "\n"; + onWriteDash(mpd, memory_only); +} + +void HlsMaker::refreshDashFile() { + if (!_is_fmp4 || !isLive() || _seg_dur_list.empty() || _dash_last_emit_ms == 0) { + // 尚未发布过,或非fmp4直播流 + // Nothing published yet, or not a live fmp4 stream + return; + } + auto now_ms = getCurrentMillisecond(true); + if (now_ms <= _dash_last_emit_ms || now_ms - _dash_last_emit_ms < kDashRefreshMs) { + // 节流: 每个分片fragment都会调用到这里 + // Throttled: this is called for every segment fragment + return; + } + // 内容与上次发布相同,但availabilityStartTime与publishTime是新的, + // 播放器的live edge得以随媒体速率持续前进 + // Same content as the last publish but with a fresh availabilityStartTime + // and publishTime, so the player's live edge keeps moving with the media + makeDashFile(false, true); +} + void HlsMaker::inputInitSegment(const char *data, size_t len) { if (!_is_fmp4) { throw std::invalid_argument("Only fmp4-hls can input init segment"); @@ -153,6 +418,7 @@ void HlsMaker::inputData(const char *data, size_t len, uint64_t timestamp, bool // Write ts data only if there are slices onWriteSegment(data, len); _last_timestamp = timestamp; + _current_seg_bytes += len; } } else { // resetTracks时触发此逻辑 [AUTO-TRANSLATED:0ba915ed] @@ -171,6 +437,9 @@ void HlsMaker::delOldSegment() { // 在hls m3u8索引文件中,我们保存的切片个数跟_seg_number相关设置一致 [AUTO-TRANSLATED:b14b5b98] // In the hls m3u8 index file, the number of slices we save is consistent with the _seg_number setting if (_file_index > _seg_number + segDelay) { + // 保持dash媒体时间轴连续: 累加被移除切片的时长 + // Keep the dash media timeline stable: remember the duration of the removed segment + _dash_timeline_offset_ms += (uint64_t)_seg_dur_list.front().duration_ms; _seg_dur_list.pop_front(); } GET_CONFIG(uint32_t, segRetain, Hls::kSegmentRetain); @@ -217,7 +486,8 @@ void HlsMaker::flushLastSegment(bool eof){ } 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 }); + _seg_dur_list.push_back(HlsSegmentInfo { (int)seg_dur, std::move(_last_file_name), _last_seg_date_time, _current_seg_bytes }); + _current_seg_bytes = 0; 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 @@ -230,6 +500,9 @@ void HlsMaker::flushLastSegment(bool eof){ if (segDelay) { makeIndexFile(true, eof); } + // 写dash mpd文件, 与m3u8共用同一套fmp4分片 + // Write the dash mpd file, sharing the same fmp4 segments + makeDashFile(eof); } const string &HlsMaker::getLastSegmentDateTime() const { @@ -256,6 +529,10 @@ void HlsMaker::clear() { _last_seg_date_time.clear(); _seg_dur_list.clear(); _last_file_name.clear(); + _dash_timeline_offset_ms = 0; + _ast_wall_ms = 0; + _dash_last_emit_ms = 0; + _current_seg_bytes = 0; } }//namespace mediakit diff --git a/src/Record/HlsMaker.h b/src/Record/HlsMaker.h index d46ea5cd..c5401ed5 100644 --- a/src/Record/HlsMaker.h +++ b/src/Record/HlsMaker.h @@ -31,6 +31,13 @@ struct HlsSegmentInfo { // 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; + // 切片累计字节数,用于计算dash mpd的bandwidth + // 注意: 本结构体使用聚合初始化(C++11下不能带默认成员初始化器), + // 初始化列表未覆盖的成员会被值初始化为0 + // Bytes accumulated for this segment, used to compute the dash mpd bandwidth + // Note: this struct uses aggregate initialization (no default member + // initializers under C++11), members left out of the init list are value initialized to 0 + size_t bytes; }; class HlsMaker { @@ -102,6 +109,18 @@ public: */ bool isFmp4() const; + /** + * 设置是否包含视频,决定dash mpd中的mimeType + * Set whether the stream contains video, it decides the mimeType in the dash mpd file + */ + void setHaveVideo(bool have_video) { _have_video = have_video; } + + /** + * 设置RFC 6381 codec字符串(例如 "avc1.640029,mp4a.40.2"), 用于dash mpd文件 + * Set the RFC 6381 codec string (e.g. "avc1.640029,mp4a.40.2") used in the dash mpd file + */ + void setDashCodec(std::string codecs) { _dash_codecs = std::move(codecs); } + /** * 清空记录 * Clear records @@ -110,6 +129,17 @@ public: */ void clear(); + /** + * 若上一份mpd已足够陈旧,则重新发布一份(仅内存) + * 由切片数据流驱动(HlsMakerImp::onWriteSegment),使得availabilityStartTime的修正 + * 摊平到整个切片周期,而不是每次flush时阶跃一次 + * Publish a fresh mpd (memory only) if the last one is old enough. + * Driven by the segment data flow (HlsMakerImp::onWriteSegment) so that the + * availabilityStartTime correction is spread over the whole segment period + * instead of stepping at every flush. + */ + void refreshDashFile(); + protected: /** * 创建ts切片文件回调 @@ -165,6 +195,16 @@ protected: */ virtual void onWriteHls(const std::string &data, bool include_delay) = 0; + /** + * 写dash mpd文件回调, 仅fmp4模式触发 + * @param data mpd文件内容 + * @param memory_only 只刷新内存中的副本, 不落盘 + * Write dash mpd file callback, only triggered in fmp4 mode + * @param data mpd file content + * @param memory_only Only refresh the copy kept in memory, do not touch the disk + */ + virtual void onWriteDash(const std::string &data, bool memory_only = false) {} + /** * 上一个 ts 切片写入完成, 可在这里进行通知处理 * @param duration_ms 上一个 ts 切片的时长, 单位为毫秒 @@ -204,6 +244,16 @@ private: */ void makeIndexFile(bool include_delay, bool eof = false); + /** + * 生成dash mpd文件, 仅fmp4模式 + * @param eof true代表直播已结束 + * @param memory_only 只刷新内存中的副本, 不落盘 + * Generate dash mpd file, fmp4 mode only + * @param eof true represents the live stream has ended + * @param memory_only Only refresh the copy kept in memory, do not touch the disk + */ + void makeDashFile(bool eof = false, bool memory_only = false); + /** * 删除旧的ts切片 * Delete old ts segments @@ -224,6 +274,7 @@ private: private: bool _is_fmp4 = false; + bool _have_video = true; float _seg_duration = 0; uint32_t _seg_number = 0; bool _seg_keep = false; @@ -239,6 +290,28 @@ private: uint64_t _file_index = 0; std::string _last_file_name; std::deque _seg_dur_list; + // 已从_seg_dur_list中移除的切片时长累计(ms),作为首个在窗切片在dash媒体时间轴上的起始时间 + // Total duration(ms) of the segments already removed from _seg_dur_list, + // used as the start time on the dash media timeline of the first listed segment + uint64_t _dash_timeline_offset_ms = 0; + // dash媒体时间轴原点对应的墙钟时间(ms),即dash availabilityStartTime; + // 每次发布mpd时修正一次,使live edge正好落在最后一个可用分片的末尾。 + // 修正限速(见makeDashFile)以避免live edge阶跃 + // Wall clock time(ms) mapping to the origin of the dash media timeline, used + // as dash availabilityStartTime; it is corrected on every mpd publish so that + // the live edge ends at the last available segment. The correction is rate + // limited (see makeDashFile) to keep the live edge from stepping. + uint64_t _ast_wall_ms = 0; + // 上次发布mpd的墙钟时间(ms),用于给availabilityStartTime修正限速 + // Wall clock time(ms) of the last mpd publish, used to rate limit the + // availabilityStartTime correction + uint64_t _dash_last_emit_ms = 0; + // 当前正在写入的切片累计字节数 + // Bytes accumulated for the segment currently being written + size_t _current_seg_bytes = 0; + // dash mpd文件使用的RFC 6381 codec字符串 + // RFC 6381 codec string for the dash mpd file + std::string _dash_codecs; }; }//namespace mediakit diff --git a/src/Record/HlsMakerImp.cpp b/src/Record/HlsMakerImp.cpp index 5b19c4bc..c8d22e69 100644 --- a/src/Record/HlsMakerImp.cpp +++ b/src/Record/HlsMakerImp.cpp @@ -36,6 +36,7 @@ HlsMakerImp::HlsMakerImp(bool is_fmp4, const string &m3u8_file, const string &pa _path_prefix = m3u8_file.substr(0, m3u8_file.rfind('/')); _path_hls = m3u8_file; _path_hls_delay = getDelayPath(m3u8_file); + _path_dash = _path_prefix + "/dash.mpd"; _params = params; _buf_size = bufSize; // 兼容用户配置不带前导点的扩展名(例如 m4s),统一补上"." [AUTO-TRANSLATED] @@ -82,6 +83,7 @@ void HlsMakerImp::clearCache(bool immediately, bool eof) { std::list lst; lst.emplace_back(_path_hls); lst.emplace_back(_path_hls_delay); + lst.emplace_back(_path_dash); if (!_path_init.empty() && eof) { lst.emplace_back(_path_init); } @@ -220,6 +222,12 @@ void HlsMakerImp::onWriteSegment(const char *data, size_t len) { if (_media_src) { _media_src->onSegmentSize(len); } + // 由数据流驱动: 在两次分片flush之间用新的availabilityStartTime/publishTime + // 重新发布mpd(仅内存), 使播放器的live edge随媒体速率前进而不是阶跃 + // Driven by the data flow: republish the mpd (memory only) with a fresh + // availabilityStartTime/publishTime between two segment flushes, so the + // player's live edge keeps advancing at the media rate instead of stepping + refreshDashFile(); } void HlsMakerImp::onWriteHls(const std::string &data, bool include_delay) { @@ -236,6 +244,21 @@ void HlsMakerImp::onWriteHls(const std::string &data, bool include_delay) { } } +void HlsMakerImp::onWriteDash(const std::string &data, bool memory_only) { + if (!memory_only) { + auto mpd = makeFile(_path_dash); + if (mpd) { + fwrite(data.data(), data.size(), 1, mpd.get()); + mpd.reset(); + } else { + WarnL << "Create dash mpd file failed," << _path_dash << " " << get_uv_errmsg(); + } + } + if (_media_src) { + _media_src->setMpdFile(data); + } +} + void HlsMakerImp::onFlushLastSegment(uint64_t duration_ms) { // 关闭并flush文件到磁盘 [AUTO-TRANSLATED:9798ec4d] // Close and flush file to disk diff --git a/src/Record/HlsMakerImp.h b/src/Record/HlsMakerImp.h index c3241adc..3596d030 100644 --- a/src/Record/HlsMakerImp.h +++ b/src/Record/HlsMakerImp.h @@ -19,6 +19,11 @@ namespace mediakit { +// availabilityStartTime的修正由onWriteSegment(数据流)驱动而非定时器驱动: +// 这样它总是在生产分片的那个线程上执行,流停了也就自动停了 +// The availabilityStartTime correction is driven from onWriteSegment (data flow), +// not from a timer: it is then always executed on the thread that produces the +// segments and stops by itself when the stream stalls. class HlsMakerImp : public HlsMaker { public: HlsMakerImp(bool is_fmp4, const std::string &m3u8_file, const std::string ¶ms, uint32_t bufSize = 64 * 1024, @@ -59,6 +64,7 @@ protected: void onWriteInitSegment(const char *data, size_t len) override; void onWriteSegment(const char *data, size_t len) override; void onWriteHls(const std::string &data, bool include_delay) override; + void onWriteDash(const std::string &data, bool memory_only) override; void onFlushLastSegment(uint64_t duration_ms) override; private: @@ -72,6 +78,7 @@ private: std::string _fmp4_seg_ext; std::string _path_hls; std::string _path_hls_delay; + std::string _path_dash; std::string _path_init; std::string _path_prefix; std::string _current_dir; diff --git a/src/Record/HlsMediaSource.cpp b/src/Record/HlsMediaSource.cpp index 9a40e770..a7ccf4be 100644 --- a/src/Record/HlsMediaSource.cpp +++ b/src/Record/HlsMediaSource.cpp @@ -108,20 +108,26 @@ HlsMediaSource::Ptr HlsCookieData::getMediaSource() const { return _src.lock(); } +void HlsMediaSource::registRing() +{ + if (_ring) { + return; + } + std::weak_ptr weakSelf = std::static_pointer_cast(shared_from_this()); + auto lam = [weakSelf](int size) { + auto strongSelf = weakSelf.lock(); + if (!strongSelf) { + return; + } + strongSelf->onReaderChanged(size); + }; + _ring = std::make_shared(0, std::move(lam)); + regist(); +} + void HlsMediaSource::setIndexFile(std::string index_file) { - if (!_ring) { - std::weak_ptr weakSelf = std::static_pointer_cast(shared_from_this()); - auto lam = [weakSelf](int size) { - auto strongSelf = weakSelf.lock(); - if (!strongSelf) { - return; - } - strongSelf->onReaderChanged(size); - }; - _ring = std::make_shared(0, std::move(lam)); - regist(); - } + registRing(); // 赋值m3u8索引文件内容 [AUTO-TRANSLATED:c11882b5] // Assign m3u8 index file content @@ -146,4 +152,31 @@ void HlsMediaSource::getIndexFile(std::function cb _list_cb.emplace_back(std::move(cb)); } +void HlsMediaSource::setMpdFile(std::string mpd_file) +{ + registRing(); + + // 赋值dash mpd文件内容 + // Assign dash mpd file content + std::lock_guard lck(_mtx_mpd); + _mpd_file = std::move(mpd_file); + + if (!_mpd_file.empty()) { + _list_mpd_cb.for_each([&](const std::function& cb) { cb(_mpd_file); }); + _list_mpd_cb.clear(); + } +} + +void HlsMediaSource::getMpdFile(std::function cb) +{ + std::lock_guard lck(_mtx_mpd); + if (!_mpd_file.empty()) { + cb(_mpd_file); + return; + } + // 等待生成dash mpd文件 + // Waiting for mpd file generation + _list_mpd_cb.emplace_back(std::move(cb)); +} + } // namespace mediakit diff --git a/src/Record/HlsMediaSource.h b/src/Record/HlsMediaSource.h index ef5f165c..04ac6198 100644 --- a/src/Record/HlsMediaSource.h +++ b/src/Record/HlsMediaSource.h @@ -72,6 +72,27 @@ public: return _index_file; } + /** + * 设置或清空dash mpd文件内容, 仅fmp4模式 + * Set or clear the dash mpd file content, fmp4 mode only + */ + void setMpdFile(std::string mpd_file); + + /** + * 异步获取dash mpd文件 + * Asynchronously get the dash mpd file + */ + void getMpdFile(std::function cb); + + /** + * 同步获取dash mpd文件 + * Synchronously get the dash mpd file + */ + std::string getMpdFile() const { + std::lock_guard lck(_mtx_mpd); + return _mpd_file; + } + void onSegmentSize(size_t bytes) { _speed[TrackVideo] += bytes; } void getPlayerList(const std::function &info_list)> &cb, @@ -79,11 +100,19 @@ public: _ring->getInfoList(cb, on_change); } +private: + // 创建环形缓冲并注册MediaSource(幂等) + // Create the ring buffer and register the MediaSource (idempotent) + void registRing(); + private: RingType::Ptr _ring; std::string _index_file; mutable std::mutex _mtx_index; toolkit::List> _list_cb; + std::string _mpd_file; + mutable std::mutex _mtx_mpd; + toolkit::List> _list_mpd_cb; }; class HlsCookieData { diff --git a/src/Record/HlsRecorder.h b/src/Record/HlsRecorder.h index 21992059..df0317f2 100644 --- a/src/Record/HlsRecorder.h +++ b/src/Record/HlsRecorder.h @@ -12,6 +12,7 @@ #define HLSRECORDER_H #include "HlsMakerImp.h" +#include "DashCodec.h" #include "MPEG.h" #include "MP4Muxer.h" #include "Common/config.h" @@ -61,10 +62,11 @@ public: bool inputFrame(const Frame::Ptr &frame) override { if (_clear_cache && _option.hls_demand) { _clear_cache = false; - // 清空旧的m3u8索引文件于ts切片 [AUTO-TRANSLATED:a4ce0664] - // Clear the old m3u8 index file and ts slices + // 清空旧的m3u8/mpd索引文件于ts切片 [AUTO-TRANSLATED:a4ce0664] + // Clear the old m3u8/mpd index file and ts slices _hls->clearCache(); _hls->getMediaSource()->setIndexFile(""); + _hls->getMediaSource()->setMpdFile(""); } if (_enabled || !_option.hls_demand) { return Muxer::inputFrame(frame); @@ -113,6 +115,12 @@ private: } }; +/** + * 基于fmp4的录制器, 同时生成hls-fmp4(m3u8)与dash(mpd)直播流, + * 两个协议共用同一套init.mp4与fmp4分片 + * Fmp4 based recorder, it generates hls-fmp4 (m3u8) and dash (mpd) live streams + * at the same time, both protocols share the same init.mp4 and fmp4 segments + */ class HlsFMP4Recorder final : public HlsRecorderBase { public: using Ptr = std::shared_ptr; @@ -126,12 +134,41 @@ public: } } + bool addTrack(const Track::Ptr &track) override { + // 累加dash codecs属性, 在addTrackCompleted()中定稿 + // 未ready的track没有extra data(AAC/H265的getExtraData会抛异常), 跳过 + // Accumulate the dash codecs attribute, finalized in addTrackCompleted(). + // A track that is not ready has no extra data (AAC/H265 getExtraData throws), skip it + if (track->ready()) { + auto cs = getDashCodecString(track); + if (!cs.empty()) { + if (!_dash_codecs.empty()) { + _dash_codecs += ","; + } + _dash_codecs += cs; + } + } + return HlsRecorderBase::addTrack(track); + } + + void resetTracks() override { + HlsRecorderBase::resetTracks(); + _dash_codecs.clear(); + } + void addTrackCompleted() override { HlsRecorderBase::addTrackCompleted(); + // 让dash mpd文件带上正确的mimeType与codecs + // Let the dash mpd file carry the right mimeType and codecs + _hls->setHaveVideo(haveVideo()); + _hls->setDashCodec(_dash_codecs); auto data = getInitSegment(); _hls->inputInitSegment(data.data(), data.size()); } +private: + std::string _dash_codecs; + private: void onSegmentData(std::string buffer, uint64_t timestamp, bool key_pos) override { if (buffer.empty()) { diff --git a/src/Record/MP4Muxer.h b/src/Record/MP4Muxer.h index 1a143d6f..242eb2ca 100644 --- a/src/Record/MP4Muxer.h +++ b/src/Record/MP4Muxer.h @@ -214,6 +214,7 @@ class MP4MuxerMemory : public MediaSinkInterface { public: bool addTrack(const Track::Ptr & track) override { return false; } bool inputFrame(const Frame::Ptr &frame) override { return false; } + bool haveVideo() const { return false; } const std::string &getInitSegment() { static std::string kNull; return kNull; }; protected: