diff --git a/default.pem b/default.pem index 2cef8d278f916d2f3447d557f419de8a196cab3e..97460132a3e232d2ecaa5895c7ec20dc894fe75e 100644 --- a/default.pem +++ b/default.pem @@ -1,37 +1,64 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAjTFnNz2btUHR/K8TegU2n06lXsQuW4AfsMGthBLvnz2zdgL2 +uVxfRCuleoRpECEV9I80ibTXAJlouRLbnhLHto8gzyLeQue9/DtxTEGcS7y2aMha +0wAoUcOBv7tAITSnFepGHXoYgyU7HOCvn96U1bzqLTOhxOCH/xy003dwoEC7+Pjl +dsWs/16cpvYiZV/dZvzDDKIpHSIvQy1whi6N0SDpzz/ncThn1z8xcJDx0I1jVR76 +juP7TttbyhqJkO+fOlLn4yP9K5wZ/dPFJn2+bQRCrzGc4SM7J5YOq8ckTTTbZtSp +9yPpm7O5QyfdzePhOpRrjWroLsqaDOPV2UQlzwIDAQABAoIBADCWTh8P19vdnR3X +v5uPXLcgkL7WQt+g7Qbd91CKVaRWTsHvDilGVNA4Ntc85oyy3gPNHfa/YPdnU0bQ +6vtwGgLEKTWumY6rgdDhQcFMmLTlaV4QiFSw6q8MWMN6c/yZSmA7wMoXAIVs0/VB +ip44sb4Fpw5MBMCjxZjwL3fP09WJPlUqx09vVo7eH8rFwLBikmn982IzRigAx1I8 +TX0wkdqvv33MSxBXPMQIrwPqjf2arxWFzb6vp6yolYbMZtgORF9gznWABRy3oY50 +9jFkTkbxZFlSMVuF7nlM0WJj5Q9/IelBqpozODWUVvB+6inCqkxNLkbh0ISbpXWC +16gUZfUCgYEAxWo3FRNBrNXhVD5h2N4ApyUXkZ5UYIY5zbsHEJCrPjooh9uHu9kh +xXh5v11J/7TV9BfwLZ4qRbDBH4fq0DKEOXOZRLY5Lo4KbrYmlEDCabuJdmwwHeGh +S5K37F5z/+zPz9KWkKN+9Rg32xdLxh0969O77GnvuBrhzASpVsF6ZFMCgYEAtxf1 +eVg4Kxzuy0AWs+CisSVQc+5CbZ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IqitIELp +HIur2XrRPBJA5XtpDg3AE8bXhRTM8oFMPL0UoSFWyWRYGgBo1Msc10dpXPtmbgIc +pPW8w+2c -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- MIIEqjCCA5KgAwIBAgIQAnmsRYvBskWr+YBTzSybsTANBgkqhkiG9w0BAQsFADBh @@ -59,31 +86,4 @@ M0r5LUvStcr82QDWYNPaUy4taCQmyaJ+VB+6wxHstSigOlSNF2a6vg4rgexixeiV 4YSB03Yqp2t3TeZHM9ESfkus74nQyW7pRGezj+TC44xCagCQQOzzNmzEAP2SnCrJ sNE2DpRVMnL8J6xBRdjmOsC3N6cQuKuRXbzByVBjCqAA8t1L0I+9wXJerLPyErjy rMKWaBFLmfK/AHNF4ZihwPGOc7w6UHczBZXH5RFzJNnww+WnKuTPI0HfnVH8lg== ------END CERTIFICATE----- ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAiTtbBLkfqhvnBehH+4hgdaR+b+Y36YLc6+B9Mrcm3Z400xbL -B79xOkpVQ3XDsikJS3oCTwigBwOco9ulTnkB2zKnWo0WeqBgyoI1g+ukS/Cjmocl -4Pq2bhWWTCHmPqhSkikEHXixfUPHzAUhRDSXnhxFnJX2HW+LyR5rnspw7PkWuhep -urIoLq/tVGKnO5OX/2cOmInAPGjrBG+SFa1Z0+D0lCTextP7CKirMQyoIrUR0ZDw -FTREROjwxYTXrUZw3Wrv2JQI+HW/sf71Mp0b0qwFDA8xBvtn9PBrG83d20GMGoXM -qwa8W4gsevczZxq24fC+W8UEX2YIc+MCOwqxJQIDAQABAoIBABdmIf5brFz+dfVJ -ZmCqn7vfaNmemQD9Wbr0Y5SOqxdVnu8xLzwqdd15CDHA9jW+DoIqkxMzxsl7Ya2E -yZpoQptD90oWzXLqPqa47fQI7VIvfU3fZmOGjC2YC7D+hLpBTBb03GlEB4tyz7Hn -XAU7rHB+pJXu8fCR8PVBdRs1rGyTSlOV/o2Q9dnnoAX6AIDWi63ChEJCrl0Mo9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at end of file diff --git a/server/WebApi.cpp b/server/WebApi.cpp index ad3b8a271dcea45b5bb07f17094b3c26e2bab22d..5d65a593c74a647ae023333ab49827a690a6df73 100755 --- a/server/WebApi.cpp +++ b/server/WebApi.cpp @@ -1471,43 +1471,44 @@ void installWebApi() { auto scan_path = File::absolutePath(MD5(allArgs["url"]).hexdigest(), snap_root) + "/"; string new_snap = StrPrinter << scan_path << time(NULL) << ".jpeg"; - File::scanDir(scan_path, [&](const string &path, bool isDir) { - if (isDir || !end_with(path, ".jpeg")) { - //忽略文件夹或其他类型的文件 - return true; - } + if (expire_sec != 0){ + File::scanDir(scan_path, [&](const string &path, bool isDir) { + if (isDir || !end_with(path, ".jpeg")) { + //忽略文件夹或其他类型的文件 + return true; + } - //找到截图 - auto tm = FindField(path.data() + scan_path.size(), nullptr, ".jpeg"); - if (atoll(tm.data()) + expire_sec < time(NULL)) { - //截图已经过期,改名,以便再次请求时,可以返回老截图 - rename(path.data(), new_snap.data()); - have_old_snap = true; - return true; - } + //找到截图 + auto tm = FindField(path.data() + scan_path.size(), nullptr, ".jpeg"); + if (atoll(tm.data()) + expire_sec < time(NULL)) { + //截图已经过期,改名,以便再次请求时,可以返回老截图 + rename(path.data(), new_snap.data()); + have_old_snap = true; + return true; + } - //截图存在,且未过期,那么返回之 - res_old_snap = true; - responseSnap(path, allArgs.getParser().getHeader(), invoker); - //中断遍历 - return false; - }); + //截图存在,且未过期,那么返回之 + res_old_snap = true; + responseSnap(path, allArgs.getParser().getHeader(), invoker); + //中断遍历 + return false; + }); - if (res_old_snap) { - //已经回复了旧的截图 - return; - } + if (res_old_snap) { + //已经回复了旧的截图 + return; + } - //无截图或者截图已经过期 - if (!have_old_snap) { - //无过期截图,生成一个空文件,目的是顺便创建文件夹路径 - //同时防止在FFmpeg生成截图途中不停的尝试调用该api多次启动FFmpeg进程 - auto file = File::create_file(new_snap.data(), "wb"); - if (file) { - fclose(file); + //无截图或者截图已经过期 + if (!have_old_snap) { + //无过期截图,生成一个空文件,目的是顺便创建文件夹路径 + //同时防止在FFmpeg生成截图途中不停的尝试调用该api多次启动FFmpeg进程 + auto file = File::create_file(new_snap.data(), "wb"); + if (file) { + fclose(file); + } } } - //启动FFmpeg进程,开始截图,生成临时文件,截图成功后替换为正式文件 auto new_snap_tmp = new_snap + ".tmp"; FFmpegSnap::makeSnap(allArgs["url"], new_snap_tmp, allArgs["timeout_sec"], [invoker, allArgs, new_snap, new_snap_tmp](bool success, const string &err_msg) { diff --git a/src/Common/MultiMediaSourceMuxer.cpp b/src/Common/MultiMediaSourceMuxer.cpp index a6118f61ec07ee1f6fd7a9caf93aa1c8caa557b8..3461ab5a1fa292f7c7abb1a79d1094891bb5a50e 100644 --- a/src/Common/MultiMediaSourceMuxer.cpp +++ b/src/Common/MultiMediaSourceMuxer.cpp @@ -202,18 +202,17 @@ int MultiMediaSourceMuxer::totalReaderCount(MediaSource &sender) { bool MultiMediaSourceMuxer::setupRecord(MediaSource &sender, Recorder::type type, bool start, const string &custom_path, size_t max_second) { switch (type) { case Recorder::type_hls : { - if (start && !_hls) { - //开始录制 + if (!_hls) + { + //创建hls对象 auto hls = dynamic_pointer_cast(makeRecorder(sender, getTracks(), type, custom_path, max_second)); if (hls) { //设置HlsMediaSource的事件监听器 hls->setListener(shared_from_this()); } _hls = hls; - } else if (!start && _hls) { - //停止录制 - _hls = nullptr; } + _hls->startRecord(start); return true; } case Recorder::type_mp4 : { @@ -234,7 +233,12 @@ bool MultiMediaSourceMuxer::setupRecord(MediaSource &sender, Recorder::type type bool MultiMediaSourceMuxer::isRecording(MediaSource &sender, Recorder::type type) { switch (type){ case Recorder::type_hls : - return !!_hls; + //return !!_hls; + if (_hls){ + return _hls->getRecordFlag(); + }else{ + return false; + } case Recorder::type_mp4 : return !!_mp4; default: diff --git a/src/Record/HlsMakerImpSub.cpp b/src/Record/HlsMakerImpSub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71ebc1e6707f1eeb62165cefdbf373b4555f5bee --- /dev/null +++ b/src/Record/HlsMakerImpSub.cpp @@ -0,0 +1,184 @@ +/* + * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. + * + * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit). + * + * Use of this source code is governed by MIT 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 +#include +#include "HlsMakerImpSub.h" +#include "Util/util.h" +#include "Util/uv_errno.h" + +using namespace std; +using namespace toolkit; + +namespace mediakit { + +HlsMakerImpSub::HlsMakerImpSub( + const string &m3u8_file, + const string ¶ms, + uint32_t bufSize, + float seg_duration, + uint32_t seg_number, + bool seg_keep):HlsMakerSub(seg_duration, seg_number, seg_keep) { + _poller = EventPollerPool::Instance().getPoller(); + _path_prefix = m3u8_file.substr(0, m3u8_file.rfind('/')); + _path_hls = m3u8_file; + _params = params; + _buf_size = bufSize; + _file_buf.reset(new char[bufSize], [](char *ptr) { + delete[] ptr; + }); + + _info.folder = _path_prefix; +} + +HlsMakerImpSub::~HlsMakerImpSub() { + clearCache(false, true); +} + +void HlsMakerImpSub::clearCache() { + clearCache(true, false); +} + +void HlsMakerImpSub::clearCache(bool immediately, bool eof) { + //录制完了 + flushLastSegment(eof); + if (!isLive()||isKeep()) { + return; + } + + clear(); + _file = nullptr; + _segment_file_paths.clear(); + + //删除缓存的m3u8文件 + File::delete_file((_path_prefix + "/hls.m3u8").data() ); + + ////hls直播才删除文件 + //GET_CONFIG(uint32_t, delay, Hls::kDeleteDelaySec); + //if (!delay || immediately) { + // File::delete_file(_path_prefix.data()); + //} else { + // auto path_prefix = _path_prefix; + // _poller->doDelayTask(delay * 1000, [path_prefix]() { + // File::delete_file(path_prefix.data()); + // return 0; + // }); + //} +} + +string HlsMakerImpSub::onOpenSegment(uint64_t index) { + string segment_name, segment_path; + + auto strDate = getTimeStr("%Y-%m-%d"); + auto strHour = getTimeStr("%H"); + auto strTime = getTimeStr("%M-%S"); + segment_name = StrPrinter << strDate + "_" + strHour + "-" + strTime << ".ts"; + segment_path = _path_prefix + "/" + strDate + "/" + strHour + "/" + segment_name; + if (isLive()) { + + GET_CONFIG(uint32_t, segRetain, Hls::kSegmentRetain); + GET_CONFIG(uint32_t, segNum, Hls::kSegmentNum); + if (_segment_file_paths.size() > segRetain + segNum) { + _segment_file_paths.erase(index - segRetain - segNum - 1); + } + _segment_file_paths.emplace(index, segment_path); + } + + _file = makeFile(segment_path, true); + + //保存本切片的元数据 + _info.start_time = ::time(NULL); + _info.file_name = segment_name; + _info.file_path = segment_path; + _info.url = _info.app + "/" + _info.stream + "/" + segment_name; + + if (!_file) { + WarnL << "create file failed," << segment_path << " " << get_uv_errmsg(); + return ""; + } + if (_params.empty()) { + return strDate + "/" + strHour + "/" + segment_name; + } + return strDate + "/" + strHour + "/" + segment_name + "?" + _params; +} + +void HlsMakerImpSub::onDelSegment(uint64_t index) { + auto it = _segment_file_paths.find(index); + if (it == _segment_file_paths.end()) { + return; + } + File::delete_file(it->second.data()); + _segment_file_paths.erase(it); +} + +void HlsMakerImpSub::onWriteSegment(const char *data, size_t len) { + if (_file) { + fwrite(data, len, 1, _file.get()); + } + if (_media_src) { + _media_src->onSegmentSize(len); + } +} + +void HlsMakerImpSub::onWriteHls(const std::string &data) { + auto hls = makeFile(_path_hls); + if (hls) { + fwrite(data.data(), data.size(), 1, hls.get()); + hls.reset(); + if (_media_src) { + _media_src->setIndexFile(data); + } + } else { + WarnL << "create hls file failed," << _path_hls << " " << get_uv_errmsg(); + } + //DebugL << "\r\n" << string(data,len); +} + +void HlsMakerImpSub::onFlushLastSegment(uint64_t duration_ms) { + //关闭并flush文件到磁盘 + _file = nullptr; + + GET_CONFIG(bool, broadcastRecordTs, Hls::kBroadcastRecordTs); + if (broadcastRecordTs) { + _info.time_len = duration_ms / 1000.0f; + _info.file_size = File::fileSize(_info.file_path.data()); + NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastRecordTs, _info); + } +} + +std::shared_ptr HlsMakerImpSub::makeFile(const string &file, bool setbuf) { + auto file_buf = _file_buf; + auto ret = shared_ptr(File::create_file(file.data(), "wb"), [file_buf](FILE *fp) { + if (fp) { + fclose(fp); + } + }); + if (ret && setbuf) { + setvbuf(ret.get(), _file_buf.get(), _IOFBF, _buf_size); + } + return ret; +} + +void HlsMakerImpSub::setMediaSource(const string &vhost, const string &app, const string &stream_id) { + _media_src = std::make_shared(vhost, app, stream_id); + _info.app = app; + _info.stream = stream_id; + _info.vhost = vhost; +} + +HlsMediaSource::Ptr HlsMakerImpSub::getMediaSource() const { + return _media_src; +} + +std::string HlsMakerImpSub::getPathPrefix() { + return _path_prefix; +} + +}//namespace mediakit \ No newline at end of file diff --git a/src/Record/HlsMakerImpSub.h b/src/Record/HlsMakerImpSub.h new file mode 100644 index 0000000000000000000000000000000000000000..6a9d7fdda8800bcb917b9f69fd885d17b43a1f23 --- /dev/null +++ b/src/Record/HlsMakerImpSub.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. + * + * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit). + * + * Use of this source code is governed by MIT 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 HLSMAKERIMPSUB_H +#define HLSMAKERIMPSUB_H + +#include +#include +#include +#include "HlsMakerSub.h" +#include "HlsMediaSource.h" + +namespace mediakit { + +class HlsMakerImpSub : public HlsMakerSub{ +public: + HlsMakerImpSub( + const std::string &m3u8_file, + const std::string ¶ms, + uint32_t bufSize = 64 * 1024, + float seg_duration = 5, + uint32_t seg_number = 3, + bool seg_keep = false); + + ~HlsMakerImpSub() override; + + /** + * 设置媒体信息 + * @param vhost 虚拟主机 + * @param app 应用名 + * @param stream_id 流id + */ + void setMediaSource(const std::string &vhost, const std::string &app, const std::string &stream_id); + + /** + * 获取MediaSource + * @return + */ + HlsMediaSource::Ptr getMediaSource() const; + + /** + * 清空缓存 + */ + void clearCache(); + +protected: + std::string onOpenSegment(uint64_t index) override ; + void onDelSegment(uint64_t index) override; + void onWriteSegment(const char *data, size_t len) override; + void onWriteHls(const std::string &data) override; + void onFlushLastSegment(uint64_t duration_ms) override; + std::string getPathPrefix() override; + +private: + std::shared_ptr makeFile(const std::string &file,bool setbuf = false); + void clearCache(bool immediately, bool eof); + +private: + int _buf_size; + std::string _params; + std::string _path_hls; + std::string _path_prefix; + RecordInfo _info; + std::shared_ptr _file; + std::shared_ptr _file_buf; + HlsMediaSource::Ptr _media_src; + toolkit::EventPoller::Ptr _poller; + +}; + +}//namespace mediakit +#endif //HLSMAKERIMPSUB_H diff --git a/src/Record/HlsMakerSub.cpp b/src/Record/HlsMakerSub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fb20592fb31f52e2f6228ba362ee52432c0e6ce5 --- /dev/null +++ b/src/Record/HlsMakerSub.cpp @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. + * + * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit). + * + * Use of this source code is governed by MIT 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 "Util/File.h" +#include "HlsMakerSub.h" +#if defined(_WIN32) +#include +#define _access access +#else +#include +#include +#endif // WIN32 + + +using namespace std; +using namespace toolkit; + +namespace mediakit { + +HlsMakerSub::HlsMakerSub(float seg_duration, uint32_t seg_number, bool seg_keep) { + //最小允许设置为0,0个切片代表点播 + _seg_number = seg_number; + _seg_duration = seg_duration; + _seg_keep = seg_keep; + _is_record = false; +} + +HlsMakerSub::~HlsMakerSub() { + + _is_close_stream = true; +} + +void HlsMakerSub::startRecord(bool isRecord) { + if (_is_record) { //检测到上一次是在录像,清空_segment_file_paths + _segment_file_paths.clear(); + } + + if(isRecord) { + _seg_keep = true; + }else{ + _seg_keep = false; + _is_close_stream = true; + } + _is_record = isRecord; +} + + +void HlsMakerSub::makeIndexFile(bool eof) { + char file_content[1024]; + int maxSegmentDuration = 0; + + for (auto &tp : _seg_dur_list) { + int dur = std::get<0>(tp); + if (dur > maxSegmentDuration) { + maxSegmentDuration = dur; + } + } + + auto sequence = _seg_number ? (_file_index > _seg_number ? _file_index - _seg_number : 0LL) : 0LL; + + string m3u8; + if (_seg_number == 0) { + // 录像点播支持时移 + snprintf(file_content, sizeof(file_content), + "#EXTM3U\n" + "#EXT-X-PLAYLIST-TYPE:EVENT\n" + "#EXT-X-VERSION:4\n" + "#EXT-X-TARGETDURATION:%u\n" + "#EXT-X-MEDIA-SEQUENCE:%llu\n", + (maxSegmentDuration + 999) / 1000, + sequence); + } else { + snprintf(file_content, sizeof(file_content), + "#EXTM3U\n" + "#EXT-X-VERSION:3\n" + "#EXT-X-ALLOW-CACHE:NO\n" + "#EXT-X-TARGETDURATION:%u\n" + "#EXT-X-MEDIA-SEQUENCE:%llu\n", + (maxSegmentDuration + 999) / 1000, + sequence); + } + + m3u8.assign(file_content); + + for (auto &tp : _seg_dur_list) { + snprintf(file_content, sizeof(file_content), "#EXTINF:%.3f,\n%s\n", std::get<0>(tp) / 1000.0, std::get<1>(tp).data()); + m3u8.append(file_content); + } + + if (eof) { + snprintf(file_content, sizeof(file_content), "#EXT-X-ENDLIST\n"); + m3u8.append(file_content); + } + onWriteHls(m3u8); +} + + +void HlsMakerSub::inputData(void *data, size_t len, uint64_t timestamp, bool is_idr_fast_packet) { + if (data && len) { + if (timestamp < _last_timestamp) { + //时间戳回退了,切片时长重新计时 + WarnL << "stamp reduce: " << _last_timestamp << " -> " << timestamp; + _last_seg_timestamp = _last_timestamp = timestamp; + } + if (is_idr_fast_packet) { + //尝试切片ts + addNewSegment(timestamp); + } + if (!_last_file_name.empty()) { + //存在切片才写入ts数据 + onWriteSegment((char *) data, len); + _last_timestamp = timestamp; + } + } else { + //resetTracks时触发此逻辑 + flushLastSegment(false); + } +} + +void HlsMakerSub::delOldSegment() { + if (_seg_number == 0) { + //如果设置为保留0个切片,则认为是保存为点播 + return; + } + //在hls m3u8索引文件中,我们保存的切片个数跟_seg_number相关设置一致 + if (_file_index > _seg_number) { + _seg_dur_list.pop_front(); + } + //如果设置为一直保存,就不删除 + if (_seg_keep) { + return; + } + GET_CONFIG(uint32_t, segRetain, Hls::kSegmentRetain); + //但是实际保存的切片个数比m3u8所述多若干个,这样做的目的是防止播放器在切片删除前能下载完毕 + if (_file_index > _seg_number + segRetain) { + onDelSegment(_file_index - _seg_number - segRetain - 1); + } +} + +void HlsMakerSub::addNewSegment(uint64_t stamp) { + if (!_last_file_name.empty() && stamp - _last_seg_timestamp < _seg_duration * 1000) { + //存在上个切片,并且未到分片时间 + return; + } + + //关闭并保存上一个切片,如果_seg_number==0,那么是点播。 + flushLastSegment(false); + + //新增切片 + _last_file_name = onOpenSegment(_file_index++); + //记录本次切片的起始时间戳 + _last_seg_timestamp = _last_timestamp ? _last_timestamp : stamp; + +} + +void HlsMakerSub::flushLastSegment(bool eof) { + if (_last_file_name.empty()) { + //不存在上个切片 + return; + } + //文件创建到最后一次数据写入的时间即为切片长度 + auto seg_dur = _last_timestamp - _last_seg_timestamp; + if (seg_dur <= 0) { + seg_dur = 100; + } + _seg_dur_list.emplace_back(seg_dur, std::move(_last_file_name)); + delOldSegment(); + //先flush ts切片,否则可能存在ts文件未写入完毕就被访问的情况 + onFlushLastSegment(seg_dur); + //然后写m3u8文件 + makeIndexFile(eof); + //判断当前是否在录像,正在录像的话,生成录像的m3u8文件 + if (_is_record) { + createM3u8FileForRecord(); + } + +} + +bool HlsMakerSub::isLive() { + return _seg_number != 0; +} + +bool HlsMakerSub::isKeep() { + return _seg_keep; +} + +void HlsMakerSub::clear() { + _file_index = 0; + _last_timestamp = 0; + _last_seg_timestamp = 0; + _seg_dur_list.clear(); + _last_file_name.clear(); + +} + +std::string HlsMakerSub::getM3u8TSBody(const std::string &file_content) { + + string new_file = file_content; + if (file_content.find("#EXT-X-ENDLIST") != file_content.npos) { + //找到了,则去掉"#EXT-X-ENDLIST" + new_file = file_content.substr(0, file_content.length() - 15); + } + + string body = new_file.substr(new_file.find_last_of("#")); + //此时的body为 + //#EXTINF:4.534, + //2022-09-14/08/2022-09-14_08-35-16.ts + string extinf = body.substr(0, body.find(",")+2); + string tsFile = body.substr(body.find_last_of("/") + 1); + body.append("#EXT-X-ENDLIST\n"); + + return extinf + tsFile + "#EXT-X-ENDLIST\n"; +} + +std::string HlsMakerSub::getTsFile(const std::string &file_content) { + // 最后一个TS的body为 + // 2022-09-13/13/58-13_43.ts + // #EXT-X-ENDLIST + string body = file_content.substr(file_content.find_last_of(",") + 2); + string ts_file_name = body.substr(body.find_last_of("/") + 1); + if (ts_file_name.find("#EXT-X-ENDLIST") == ts_file_name.npos ) { + ts_file_name = ts_file_name.substr(0, ts_file_name.length() - 4); //没找到,去掉“.ts\n”,只留名字 + } else { + ts_file_name = ts_file_name.substr(0, ts_file_name.length() - 19); //找到的话,去掉“.ts\n#EXT-X-ENDLIST\n”,只留名字 + } + + return ts_file_name; +} + +void HlsMakerSub::createM3u8FileForRecord() { + // 1.读取直播目录下的m3u8文件,获取当前的ts文件以及时长,并生成m3u8文件的路径 + string live_file = File::loadFile((getPathPrefix() + "/hls.m3u8").data()); + if (live_file.empty()) { + return; + } + + string body = getM3u8TSBody(live_file); + string ts_file_name = getTsFile(live_file); // ts_file: 2022-09-14_11-06-03 + string m3u8_file = getPathPrefix() + "/" + ts_file_name.substr(0, 10) + "/" + ts_file_name.substr(11, 2) + "/"; + + // 2.判断该目录下有没有m3u8文件,没有的话,生成第一个m3u8文件,有的话,重命名 + int handle = -1; + DIR *dir_info = opendir(m3u8_file.data()); + struct dirent *dir_entry; + if (dir_info) { + while ((dir_entry =readdir(dir_info)) != NULL) { + if (end_with(dir_entry->d_name, ".m3u8")) { + handle = 0; + break; + } + } + closedir(dir_info); + } else { + return; + } + + if (-1 == handle) {//第一次播放流 + _m3u8_file_path = m3u8_file + ts_file_name + ".m3u8"; + _is_close_stream = false; + } else {//断流过,一次以上播放 + if (_is_close_stream) { + _m3u8_file_path = m3u8_file + ts_file_name + ".m3u8"; + _is_close_stream = false; + } + if (_m3u8_file_path.length() == 0) { //服务重启后,进来,_m3u8_file_path为空 + _m3u8_file_path = m3u8_file + ts_file_name + ".m3u8"; + } + } + + if (_m3u8_file_path.empty()) { + WarnL << "create m3u8 file failed, _m3u8_file_path is empty." ; + return; + } + + //3.写m3u8文件 + string m3u8Header = "#EXTM3U\n" + "#EXT-X-PLAYLIST-TYPE:EVENT\n" + "#EXT-X-VERSION:4\n" + "#EXT-X-TARGETDURATION:2\n" + "#EXT-X-MEDIA-SEQUENCE:0\n"; + + if (access(_m3u8_file_path.data(), 0) != 0) { //文件不存在 + auto file = File::create_file(_m3u8_file_path.data(), "wb"); + if (file) { + fwrite(m3u8Header.data(), m3u8Header.size(), 1, file); + fwrite(body.data(), body.size(), 1, file); + fclose(file); + } + } else { + // 第二次进来,去掉 "#EXT-X-ENDLIST\n",再重新追加file_content,保存文件 + auto file = File::create_file(_m3u8_file_path.data(), "r+"); + if (file) { + fseek(file, -15, SEEK_END); + fwrite(body.data(), body.size(), 1, file); + fclose(file); + } + } +} + +}//namespace mediakit diff --git a/src/Record/HlsMakerSub.h b/src/Record/HlsMakerSub.h new file mode 100644 index 0000000000000000000000000000000000000000..f8a244a5cc73cd3c83714f9dfde5df84f948cdd7 --- /dev/null +++ b/src/Record/HlsMakerSub.h @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved. + * + * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit). + * + * Use of this source code is governed by MIT 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 HLSMAKERSUB_H +#define HLSMAKERSUB_H + +#include +#include +#include "Common/config.h" +#include "Util/TimeTicker.h" +#include "Util/File.h" +#include "Util/util.h" +#include "Util/logger.h" + +namespace mediakit { + +class HlsMakerSub { +public: + /** + * @param seg_duration 切片文件长度 + * @param seg_number 切片个数 + * @param seg_keep 是否保留切片文件 + */ + HlsMakerSub(float seg_duration = 5, uint32_t seg_number = 3, bool seg_keep = false); + virtual ~HlsMakerSub(); + + /** + * 写入ts数据 + * @param data 数据 + * @param len 数据长度 + * @param timestamp 毫秒时间戳 + * @param is_idr_fast_packet 是否为关键帧第一个包 + */ + void inputData(void *data, size_t len, uint64_t timestamp, bool is_idr_fast_packet); + + /** + * 是否为直播 + */ + bool isLive(); + + /** + * 是否保留切片文件 + */ + bool isKeep(); + + /** + * 清空记录 + */ + void clear(); + //设置是否录像标志 + void startRecord(bool isRecord); + +protected: + /** + * 创建ts切片文件回调 + * @param index + * @return + */ + virtual std::string onOpenSegment(uint64_t index) = 0; + + /** + * 删除ts切片文件回调 + * @param index + */ + virtual void onDelSegment(uint64_t index) = 0; + + /** + * 写ts切片文件回调 + * @param data + * @param len + */ + virtual void onWriteSegment(const char *data, size_t len) = 0; + + /** + * 写m3u8文件回调 + */ + virtual void onWriteHls(const std::string &data) = 0; + + /** + * 上一个 ts 切片写入完成, 可在这里进行通知处理 + * @param duration_ms 上一个 ts 切片的时长, 单位为毫秒 + */ + virtual void onFlushLastSegment(uint64_t duration_ms) {}; + virtual std::string getPathPrefix() = 0; + + /** + * 关闭上个ts切片并且写入m3u8索引 + * @param eof HLS直播是否已结束 + */ + void flushLastSegment(bool eof); + +private: + /** + * 生成m3u8文件 + * @param eof true代表点播 + */ + void makeIndexFile(bool eof = false); + + /** + * 删除旧的ts切片 + */ + void delOldSegment(); + + /** + * 添加新的ts切片 + * @param timestamp + */ + void addNewSegment(uint64_t timestamp); + + //新增函数,实现录像功能 + std::string getTsFile(const std::string &file_content); + std::string getM3u8TSBody(const std::string &file_content); + void createM3u8FileForRecord(); + +private: + float _seg_duration = 0; + uint32_t _seg_number = 0; + bool _seg_keep = false; + uint64_t _last_timestamp = 0; + uint64_t _last_seg_timestamp = 0; + uint64_t _file_index = 0; + std::string _last_file_name; + std::deque > _seg_dur_list; + bool _is_record = false; + bool _is_close_stream = false; + std::string _m3u8_file_path; + +public: + std::map _segment_file_paths; +}; + +}//namespace mediakit +#endif //HLSMAKERSUB_H diff --git a/src/Record/HlsRecorder.h b/src/Record/HlsRecorder.h index c5b50f453a8842e17d888672ae4d48fae5f85631..f3ddfcc043b5c65930d52af822d2ab235b4b38bf 100644 --- a/src/Record/HlsRecorder.h +++ b/src/Record/HlsRecorder.h @@ -11,7 +11,8 @@ #ifndef HLSRECORDER_H #define HLSRECORDER_H -#include "HlsMakerImp.h" +//#include "HlsMakerImp.h" +#include "HlsMakerImpSub.h" #include "MPEG.h" namespace mediakit { @@ -25,7 +26,8 @@ public: GET_CONFIG(bool, hlsKeep, Hls::kSegmentKeep); GET_CONFIG(uint32_t, hlsBufSize, Hls::kFileBufSize); GET_CONFIG(float, hlsDuration, Hls::kSegmentDuration); - _hls = std::make_shared(m3u8_file, params, hlsBufSize, hlsDuration, hlsNum, hlsKeep); + // _hls = std::make_shared(m3u8_file, params, hlsBufSize, hlsDuration, hlsNum, hlsKeep); + _hls = std::make_shared(m3u8_file, params, hlsBufSize, hlsDuration, hlsNum, hlsKeep); //清空上次的残余文件 _hls->clearCache(); } @@ -73,7 +75,12 @@ public: //缓存尚未清空时,还允许触发inputFrame函数,以便及时清空缓存 return hls_demand ? (_clear_cache ? true : _enabled) : true; } + void startRecord(bool flag) { + _hls->startRecord(flag); + _isRecord = flag; + } + bool getRecordFlag() { return _isRecord; } private: void onWrite(std::shared_ptr buffer, uint64_t timestamp, bool key_pos) override { if (!buffer) { @@ -86,7 +93,9 @@ private: private: bool _enabled = true; bool _clear_cache = false; - std::shared_ptr _hls; + //std::shared_ptr _hls; + std::shared_ptr _hls; + bool _isRecord = false; }; }//namespace mediakit #endif //HLSRECORDER_H diff --git a/src/Record/MP4Recorder.cpp b/src/Record/MP4Recorder.cpp index 35dbeaa0899ffe2fc5760636630bc7a25fd2ee01..af955e7a1bbeb62df23fb541190f87a3ebb9f73f 100644 --- a/src/Record/MP4Recorder.cpp +++ b/src/Record/MP4Recorder.cpp @@ -33,11 +33,11 @@ MP4Recorder::MP4Recorder(const string &path, const string &vhost, const string & } MP4Recorder::~MP4Recorder() { - closeFile(); + //closeFile(); } void MP4Recorder::createFile() { - closeFile(); + //closeFile(); auto date = getTimeStr("%Y-%m-%d"); auto time = getTimeStr("%H-%M-%S"); auto full_path_tmp = _folder_path + date + "/." + time + ".mp4"; @@ -93,7 +93,7 @@ void MP4Recorder::asyncClose() { void MP4Recorder::closeFile() { if (_muxer) { - asyncClose(); + //asyncClose(); _muxer = nullptr; } } @@ -113,7 +113,7 @@ bool MP4Recorder::inputFrame(const Frame::Ptr &frame) { // 2、到了切片时间,并且只有音频 // 3、到了切片时间,有视频并且遇到视频的关键帧 _last_dts = 0; - createFile(); + //createFile(); } } @@ -134,7 +134,7 @@ bool MP4Recorder::addTrack(const Track::Ptr &track) { } void MP4Recorder::resetTracks() { - closeFile(); + //closeFile(); _tracks.clear(); _have_video = false; }