Commit 33eb7ef3 by xiongziliang

整体替换HLS生成代码,支持265

parent d1f72293
[submodule "ZLToolKit"]
path = ZLToolKit
path = 3rdpart/ZLToolKit
url = https://github.com/xiongziliang/ZLToolKit.git
[submodule "3rdpart/media-server"]
path = 3rdpart/media-server
url = https://github.com/xiongziliang/media-server
Subproject commit e79d24b51051ed9b3bd9c66b9d8ace3c76a0411a
Subproject commit 6ae6ece439e54252116e418179bc84e6a0189f67
......@@ -11,7 +11,8 @@ set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
#设置工程源码根目录
set(ToolKit_Root ${CMAKE_SOURCE_DIR}/ZLToolKit/src)
set(ToolKit_Root ${CMAKE_SOURCE_DIR}/3rdpart/ZLToolKit/src)
set(MediaServer_Root ${CMAKE_SOURCE_DIR}/3rdpart/media-server)
set(MediaKit_Root ${CMAKE_SOURCE_DIR}/src)
#设置头文件目录
......@@ -84,6 +85,13 @@ add_definitions(-DENABLE_RING_USEBUF)
add_library(zltoolkit STATIC ${ToolKit_src_list})
add_library(zlmediakit STATIC ${MediaKit_src_list})
#libmpeg
aux_source_directory(${MediaServer_Root}/libmpeg/include src_mpeg)
aux_source_directory(${MediaServer_Root}/libmpeg/source src_mpeg)
include_directories(${MediaServer_Root}/libmpeg/include)
add_library(mpeg STATIC ${src_mpeg})
if (WIN32)
list(APPEND LINK_LIB_LIST WS2_32 Iphlpapi shlwapi)
elseif(NOT ANDROID OR IOS)
......
Subproject commit e79d24b51051ed9b3bd9c66b9d8ace3c76a0411a
/*
/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
......@@ -24,194 +24,80 @@
* SOFTWARE.
*/
#include "HLSMaker.h"
#include "Util/File.h"
#include "Util/uv_errno.h"
#include "Extension/H264.h"
using namespace toolkit;
#include "HlsMaker.h"
namespace mediakit {
HLSMaker::HLSMaker(const string& strM3u8File,
uint32_t ui32BufSize,
uint32_t ui32Duration,
uint32_t ui32Num) {
if (ui32BufSize < 16 * 1024) {
ui32BufSize = 16 * 1024;
}
if(ui32Num < 1){
ui32Num = 1;
}
_ui32BufSize = ui32BufSize;
_ui64TsCnt = 0;
_strM3u8File = strM3u8File;
_ui32NumSegments = ui32Num;
_ui32SegmentDuration = ui32Duration;
_ui32LastStamp = 0;
_strOutputPrefix = strM3u8File.substr(0, strM3u8File.rfind('.'));
_strFileName = _strOutputPrefix.substr(_strOutputPrefix.rfind('/') + 1);
_ts.init(_strOutputPrefix + "-0.ts", _ui32BufSize);
HlsMaker::HlsMaker(float seg_duration, uint32_t seg_number) {
seg_number = MAX(1,seg_number);
seg_duration = MAX(1,seg_duration);
_seg_number = seg_number;
_seg_duration = seg_duration;
}
HLSMaker::~HLSMaker() {
_ts.clear();
string strDir = _strOutputPrefix.substr(0,_strOutputPrefix.rfind('/'));
File::delete_file(strDir.data());
HlsMaker::~HlsMaker() {
}
bool HLSMaker::write_index_file(int iFirstSegment, unsigned int uiLastSegment, int iEnd) {
char acWriteBuf[1024];
std::shared_ptr<FILE> pM3u8File(File::createfile_file(_strM3u8File.data(), "w"),[](FILE *fp){
if(fp){
fflush(fp);
fclose(fp);
}
});
if (!pM3u8File) {
WarnL << "Could not open temporary m3u8 index file (" << _strM3u8File << "), no index file will be created";
return false;
}
if (iFirstSegment < 0) {
iFirstSegment = 0;
}
#define PRINT(...) file_size += snprintf(file_content + file_size,sizeof(file_content) - file_size, ##__VA_ARGS__)
void HlsMaker::makeIndexFile(bool eof) {
char file_content[4 * 1024];
int file_size = 0;
//最少1秒
int maxSegmentDuration = 0;
for (auto dur : _iDurations) {
dur /=1000;
if(dur > maxSegmentDuration){
for (auto &tp : _seg_dur_list) {
int dur = std::get<0>(tp);
if (dur > maxSegmentDuration) {
maxSegmentDuration = dur;
}
}
if (_ui32NumSegments) {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTM3U\r\n"
"#EXT-X-VERSION:3\r\n"
"#EXT-X-ALLOW-CACHE:NO\r\n"
"#EXT-X-TARGETDURATION:%u\r\n"
"#EXT-X-MEDIA-SEQUENCE:%u\r\n",
maxSegmentDuration + 1,
iFirstSegment);
} else {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTM3U\r\n"
"#EXT-X-VERSION:3\r\n"
"#EXT-X-ALLOW-CACHE:NO\r\n"
"#EXT-X-TARGETDURATION:%u\r\n",
maxSegmentDuration);
}
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write to m3u8 index file, will not continue writing to index file";
return false;
}
for (unsigned int i = iFirstSegment; i < uiLastSegment; i++) {
snprintf(acWriteBuf,
sizeof(acWriteBuf),
"#EXTINF:%.3f,\r\n%s-%u.ts\r\n",
_iDurations[i-iFirstSegment]/1000.0,
_strFileName.data(),
i);
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write to m3u8 index file, will not continue writing to index file";
return false;
}
}
if (iEnd) {
snprintf(acWriteBuf, sizeof(acWriteBuf), "#EXT-X-ENDLIST\r\n");
if (fwrite(acWriteBuf, strlen(acWriteBuf), 1, pM3u8File.get()) != 1) {
WarnL << "Could not write last file and endlist tag to m3u8 index file";
return false;
}
}
return true;
}
void HLSMaker::inputH264(const Frame::Ptr &frame) {
auto dts = frame->dts();
if(_ui32LastStamp == 0){
_ui32LastStamp = dts;
PRINT("#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,
_file_index);
for (auto &tp : _seg_dur_list) {
PRINT("#EXTINF:%.3f,\n%s\n", std::get<0>(tp) / 1000.0, std::get<1>(tp).data());
}
int stampInc = dts - _ui32LastStamp;
auto type = H264_TYPE(((uint8_t*)(frame->data() + frame->prefixSize()))[0]);
switch (type) {
case H264Frame::NAL_SPS: //SPS
if (stampInc >= _ui32SegmentDuration * 1000) {
_ui32LastStamp = dts;
//关闭文件
_ts.clear();
auto strTmpFileName = StrPrinter << _strOutputPrefix << '-' << (++_ui64TsCnt) << ".ts" << endl;
if (!_ts.init(strTmpFileName, _ui32BufSize)) {
//创建文件失败
return;
}
//记录切片时间
_iDurations.push_back(stampInc);
if(removets()){
//删除老的时间戳
_iDurations.pop_front();
}
write_index_file(_ui64TsCnt - _ui32NumSegments, _ui64TsCnt, 0);
}
case H264Frame::NAL_B_P: //P
//insert aud frame before p and SPS frame
if(dts != _ui32LastFrameStamp){
_ts.inputH264("\x0\x0\x0\x1\x9\xf0", 6, dts * 90LL , frame->pts() * 90LL);
}
case H264Frame::NAL_IDR: //IDR
case H264Frame::NAL_PPS: //PPS
_ts.inputH264(frame->data(), frame->size(), dts * 90LL , frame->pts() * 90LL);
break;
default:
break;
}
_ui32LastFrameStamp = dts;
if (eof) {
PRINT("#EXT-X-ENDLIST\n");
}
onWriteHls(file_content, file_size);
}
void HLSMaker::inputAAC(const Frame::Ptr &frame) {
_ts.inputAAC(frame->data(), frame->size(), frame->dts() * 90LL , frame->pts() * 90LL);
}
bool HLSMaker::removets() {
if (_ui64TsCnt < _ui32NumSegments + 2) {
return false;
}
File::delete_file((StrPrinter << _strOutputPrefix << "-"
<< _ui64TsCnt - _ui32NumSegments - 2
<< ".ts" << endl).data());
return true;
void HlsMaker::inputData(void *data, uint32_t len, uint32_t timestamp) {
addNewFile(timestamp);
onWriteFile((char *) data, len);
}
void HLSMaker::onTrackFrame(const Frame::Ptr &frame) {
switch (frame->getCodecId()){
case CodecH264:{
if( frame->prefixSize() != 0){
inputH264(frame);
}else{
WarnL << "h264必须要有头4个或3个字节的前缀";
}
}
break;
case CodecAAC:{
if( frame->prefixSize() == 7) {
inputAAC(frame);
}else{
WarnL << "adts必须要有头7个字节的adts头";
}
}
break;
void HlsMaker::delOldFile() {
//在hls m3u8索引文件中,我们保存的切片个数跟_seg_number相关设置一致
if (_file_index >= _seg_number + 2) {
_seg_dur_list.pop_front();
}
default:
break;
}
//但是实际保存的切片个数比m3u8所述多两个,这样做的目的是防止播放器在切片删除前能下载完毕
if (_file_index >= _seg_number + 4) {
onDelFile(_file_index - _seg_number - 4);
}
}
} /* namespace mediakit */
void HlsMaker::addNewFile(uint32_t timestamp) {
int stampInc = timestamp - _stamp_last;
if (stampInc >= _seg_duration * 1000) {
_stamp_last = timestamp;
auto file_name = onOpenFile(_file_index);
if (_file_index++ > 0) {
_seg_dur_list.push_back(std::make_tuple(stampInc, _last_file_name));
delOldFile();
makeIndexFile();
}
_last_file_name = file_name;
}
}
}//namespace mediakit
\ No newline at end of file
/*
/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
......@@ -24,63 +24,76 @@
* SOFTWARE.
*/
#ifndef HLSMAKER_H_
#define HLSMAKER_H_
#ifndef HLSMAKER_H
#define HLSMAKER_H
#include <deque>
#include "TSMaker.h"
#include <tuple>
#include "Common/config.h"
#include "Util/TimeTicker.h"
#include "Util/File.h"
#include "Util/util.h"
#include "Util/logger.h"
#include "Common/config.h"
#include "Common/MediaSink.h"
#include "Extension/Frame.h"
using namespace toolkit;
namespace mediakit {
class HLSMaker : public MediaSink{
class HlsMaker {
public:
HLSMaker(const string &strM3u8File,
uint32_t ui32BufSize = 64 * 1024,
uint32_t ui32Duration = 5,
uint32_t ui32Num = 3);
virtual ~HLSMaker();
/**
* @param seg_duration 切片文件长度
* @param seg_number 切片个数
*/
HlsMaker(float seg_duration = 5, uint32_t seg_number = 3);
virtual ~HlsMaker();
/**
* 写入ts数据
* @param data 数据
* @param len 数据长度
* @param timestamp 毫秒时间戳
*/
void inputData(void *data, uint32_t len, uint32_t timestamp);
protected:
/**
* 某Track输出frame,在onAllTrackReady触发后才会调用此方法
* @param frame
/**
* 创建ts切片文件回调
* @param index
* @return
*/
void onTrackFrame(const Frame::Ptr &frame) override ;
private:
void inputH264(const Frame::Ptr &frame);
void inputAAC(const Frame::Ptr &frame);
bool write_index_file(int iFirstSegment,
unsigned int uiLastSegment,
int iEnd);
virtual string onOpenFile(int index) = 0;
bool removets();
private:
TSMaker _ts;
string _strM3u8File;
string _strFileName;
string _strOutputPrefix;
uint32_t _ui32SegmentDuration;
uint32_t _ui32NumSegments;
uint64_t _ui64TsCnt;
uint32_t _ui32BufSize;
uint32_t _ui32LastStamp;
uint32_t _ui32LastFrameStamp = 0;
std::deque<int> _iDurations;
/**
* 删除ts切片文件回调
* @param index
*/
virtual void onDelFile(int index) = 0;
/**
* 写ts切片文件回调
* @param data
* @param len
*/
virtual void onWriteFile(const char *data, int len) = 0;
/**
* 写m3u8文件回调
* @param data
* @param len
*/
virtual void onWriteHls(const char *data, int len) = 0;
private:
void delOldFile();
void addNewFile(uint32_t timestamp);
void makeIndexFile(bool eof = false);
private:
string _file_prefix;
float _seg_duration = 0;
uint32_t _seg_number = 0;
uint64_t _file_index = 0;
uint32_t _stamp_last = 0;
string _last_file_name;
std::deque<tuple<int,string> > _seg_dur_list;
};
} /* namespace mediakit */
#endif /* HLSMAKER_H_ */
}//namespace mediakit
#endif //HLSMAKER_H
/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "HlsMakerImp.h"
#include "Util/util.h"
#include "Util/uv_errno.h"
using namespace toolkit;
namespace mediakit {
HlsMakerImp::HlsMakerImp(const string &m3u8_file,
const string &params,
uint32_t bufSize,
float seg_duration,
uint32_t seg_number) : HlsMaker(seg_duration, seg_number) {
_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;
});
}
HlsMakerImp::~HlsMakerImp() {
_file.reset();
File::delete_file(_path_prefix.data());
}
string HlsMakerImp::onOpenFile(int index) {
auto full_path = fullPath(index);
_file = makeFile(full_path, true);
if(!_file){
WarnL << "create file falied," << full_path << " " << get_uv_errmsg();
}
//DebugL << index << " " << full_path;
if(_params.empty()){
return StrPrinter << index << ".ts";
}
return StrPrinter << index << ".ts" << "?" << _params;
}
void HlsMakerImp::onDelFile(int index) {
//WarnL << index;
File::delete_file(fullPath(index).data());
}
void HlsMakerImp::onWriteFile(const char *data, int len) {
if (_file) {
fwrite(data, len, 1, _file.get());
}
}
void HlsMakerImp::onWriteHls(const char *data, int len) {
auto hls = makeFile(_path_hls);
if(hls){
fwrite(data,len,1,hls.get());
hls.reset();
} else{
WarnL << "create hls file falied," << _path_hls << " " << get_uv_errmsg();
}
//DebugL << "\r\n" << string(data,len);
}
string HlsMakerImp::fullPath(int index) {
return StrPrinter << _path_prefix << "/" << index << ".ts";
}
std::shared_ptr<FILE> HlsMakerImp::makeFile(const string &file,bool setbuf) {
auto ret= shared_ptr<FILE>(File::createfile_file(file.data(), "wb"), [](FILE *fp) {
if (fp) {
fclose(fp);
}
});
if(ret && setbuf){
setvbuf(ret.get(), _file_buf.get(), _IOFBF, _buf_size);
}
return ret;
}
}//namespace mediakit
\ No newline at end of file
/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef HLSMAKERIMP_H
#define HLSMAKERIMP_H
#include <memory>
#include <string>
#include <stdlib.h>
#include "HlsMaker.h"
using namespace std;
namespace mediakit {
class HlsMakerImp : public HlsMaker{
public:
HlsMakerImp(const string &m3u8_file,
const string &params,
uint32_t bufSize = 64 * 1024,
float seg_duration = 5,
uint32_t seg_number = 3);
virtual ~HlsMakerImp();
protected:
string onOpenFile(int index) override ;
void onDelFile(int index) override;
void onWriteFile(const char *data, int len) override;
void onWriteHls(const char *data, int len) override;
private:
string fullPath(int index);
std::shared_ptr<FILE> makeFile(const string &file,bool setbuf = false);
private:
std::shared_ptr<FILE> _file;
std::shared_ptr<char> _file_buf;
string _path_prefix;
string _path_hls;
string _params;
int _buf_size;
};
}//namespace mediakit
#endif //HLSMAKERIMP_H
/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef HLSRECORDER_H
#define HLSRECORDER_H
#include "HlsMakerImp.h"
#include "TsMuxer.h"
namespace mediakit {
class HlsRecorder : public HlsMakerImp , public TsMuxer {
public:
template<typename ...ArgsType>
HlsRecorder(ArgsType &&...args):HlsMakerImp(std::forward<ArgsType>(args)...){}
~HlsRecorder(){};
protected:
void onTs(const void *packet, int bytes,uint32_t timestamp,int flags) override {
inputData((char *)packet,bytes,timestamp);
};
};
}//namespace mediakit
#endif //HLSRECORDER_H
......@@ -30,6 +30,7 @@
#include "Util/util.h"
#include "Util/mini.h"
#include "Network/sockutil.h"
#include "HlsMakerImp.h"
using namespace toolkit;
namespace mediakit {
......@@ -53,7 +54,7 @@ MediaRecorder::MediaRecorder(const string &strVhost_tmp,
if(enableHls) {
auto m3u8FilePath = hlsPath + "/" + strVhost + "/" + strApp + "/" + strId + "/hls.m3u8";
_hlsMaker.reset(new HLSMaker(m3u8FilePath,hlsBufSize, hlsDuration, hlsNum));
_hlsMaker.reset(new HlsRecorder(m3u8FilePath,string(VHOST_KEY) + "=" + strVhost ,hlsBufSize, hlsDuration, hlsNum));
}
#ifdef ENABLE_MP4V2
......
......@@ -34,7 +34,7 @@
#include "Mp4Maker.h"
#endif //ENABLE_MP4V2
#include "HLSMaker.h"
#include "HlsRecorder.h"
using namespace toolkit;
namespace mediakit {
......@@ -62,7 +62,7 @@ public:
*/
void addTrack(const Track::Ptr & track) override;
private:
std::shared_ptr<HLSMaker> _hlsMaker;
std::shared_ptr<HlsRecorder> _hlsMaker;
#ifdef ENABLE_MP4V2
std::shared_ptr<Mp4Maker> _mp4Maker;
#endif //ENABLE_MP4V2
......
/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "TsMuxer.h"
#include <assert.h>
#include "mpeg-ts-proto.h"
namespace mediakit {
TsMuxer::TsMuxer() {
init();
}
TsMuxer::~TsMuxer() {
uninit();
}
void TsMuxer::addTrack(const Track::Ptr &track) {
switch (track->getCodecId()){
case CodecH264:
_codecid_to_stream_id[CodecH264] = mpeg_ts_add_stream(_context,PSI_STREAM_H264, nullptr,0);
break;
case CodecH265:
_codecid_to_stream_id[CodecH265] = mpeg_ts_add_stream(_context,PSI_STREAM_H265, nullptr,0);
break;
case CodecAAC:
_codecid_to_stream_id[CodecAAC] = mpeg_ts_add_stream(_context,PSI_STREAM_AAC, nullptr,0);
break;
default:
break;
}
}
void TsMuxer::inputFrame(const Frame::Ptr &frame) {
auto it = _codecid_to_stream_id.find(frame->getCodecId());
if(it == _codecid_to_stream_id.end()){
return;
}
switch (frame->getCodecId()){
case CodecH265:
case CodecH264: {
//这里的代码逻辑是让SPS、PPS、IDR这些时间戳相同的帧打包到一起当做一个帧处理,
if (!_frameCached.empty() && _frameCached.back()->dts() != frame->dts()) {
Frame::Ptr back = _frameCached.back();
Buffer::Ptr merged_frame = back;
if(_frameCached.size() != 1){
string merged;
_frameCached.for_each([&](const Frame::Ptr &frame){
merged.append(frame->data(),frame->size());
});
merged_frame = std::make_shared<BufferString>(std::move(merged));
}
_timestamp = back->dts();
mpeg_ts_write(_context, it->second, back->keyFrame() ? 0x0001 : 0, back->pts() * 90LL, back->dts() * 90LL, merged_frame->data(), merged_frame->size());
_frameCached.clear();
}
_frameCached.emplace_back(frame);
}
break;
default: {
_timestamp = frame->dts();
mpeg_ts_write(_context, it->second, frame->keyFrame() ? 0x0001 : 0, frame->pts() * 90LL, frame->dts() * 90LL, frame->data(), frame->size());
}
break;
}
}
void TsMuxer::resetTracks() {
uninit();
init();
}
void TsMuxer::init() {
static mpeg_ts_func_t s_func= {
[](void* param, size_t bytes){
TsMuxer *muxer = (TsMuxer *)param;
assert(sizeof(TsMuxer::_tsbuf) >= bytes);
return (void *)muxer->_tsbuf;
},
[](void* param, void* packet){
//do nothing
},
[](void* param, const void* packet, size_t bytes){
TsMuxer *muxer = (TsMuxer *)param;
muxer->onTs(packet, bytes,muxer->_timestamp,0);
}
};
if(_context == nullptr){
_context = mpeg_ts_create(&s_func,this);
}
}
void TsMuxer::uninit() {
if(_context){
mpeg_ts_destroy(_context);
_context = nullptr;
}
_codecid_to_stream_id.clear();
}
}//namespace mediakit
\ No newline at end of file
/*
* MIT License
*
* Copyright (c) 2016 xiongziliang <771730766@qq.com>
*
* This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef TSMUXER_H
#define TSMUXER_H
#include <unordered_map>
#include "mpeg-ts.h"
#include "Extension/Frame.h"
#include "Extension/Track.h"
#include "Util/File.h"
using namespace toolkit;
namespace mediakit {
class TsMuxer {
public:
TsMuxer();
virtual ~TsMuxer();
void addTrack(const Track::Ptr &track);
void inputFrame(const Frame::Ptr &frame);
protected:
virtual void onTs(const void *packet, int bytes,uint32_t timestamp,int flags) = 0;
void resetTracks();
private:
void init();
void uninit();
private:
void *_context = nullptr;
char *_tsbuf[188];
uint32_t _timestamp = 0;
unordered_map<int,int > _codecid_to_stream_id;
List<Frame::Ptr> _frameCached;
};
class TsMuxer2{
public:
typedef function<void(const void *packet, int bytes)> onTsCallback;
TsMuxer2(){
init();
}
~TsMuxer2(){
uninit();
}
bool addTrack(int track,int codec_id){
lock_guard<recursive_mutex> lck(_mtx);
auto it = _allTrackMap.find(track);
if(it != _allTrackMap.end()){
// WarnL << "Track:" << track << "已经存在!";
return false;
}
_allTrackMap[track] = codec_id;
resetAllTracks();
return true;
}
bool removeTrack(int track){
lock_guard<recursive_mutex> lck(_mtx);
auto it = _allTrackMap.find(track);
if(it == _allTrackMap.end()){
// WarnL << "Track:" << track << "不存在!";
return false;
}
DebugL << "删除Track:" << track;
_allTrackMap.erase(it);
resetAllTracks();
return true;
}
bool inputTrackData(int track, const char *data, int length, int64_t pts, int64_t dts, int flags){
lock_guard<recursive_mutex> lck(_mtx);
auto it = _track_id_to_stream_id.find(track);
if(it == _track_id_to_stream_id.end()){
WarnL << "Track:" << track << "不存在!";
return false;
}
mpeg_ts_write(_context,it->second,flags,pts,dts,data,length);
return true;
}
void setOnTsCallback(const onTsCallback &cb) {
lock_guard<recursive_mutex> lck(_mtx);
_onts = cb;
}
bool saveToFile(const string &file){
lock_guard<recursive_mutex> lck(_mtx);
FILE *fp = File::createfile_file(file.data(),"ab");
if(!fp){
WarnL << "打开文件失败:" << file << " " << get_uv_errmsg();
return false;
}
setvbuf(fp, _file_buf, _IOFBF, sizeof(_file_buf));
_file.reset(fp,[](FILE *fp){
fclose(fp);
});
return true;
}
private:
void init() {
lock_guard<recursive_mutex> lck(_mtx);
static mpeg_ts_func_t s_func= {
[](void* param, size_t bytes){
TsMuxer2 *muxer = (TsMuxer2 *)param;
assert(sizeof(TsMuxer2::_tsbuf) >= bytes);
return (void *)muxer->_tsbuf;
},
[](void* param, void* packet){
//do nothing
},
[](void* param, const void* packet, size_t bytes){
TsMuxer2 *muxer = (TsMuxer2 *)param;
muxer->onTs(packet, bytes);
}
};
if(_context == nullptr){
_context = mpeg_ts_create(&s_func,this);
}
}
void uninit() {
lock_guard<recursive_mutex> lck(_mtx);
if(_context){
mpeg_ts_destroy(_context);
_context = nullptr;
}
_track_id_to_stream_id.clear();
}
void resetAllTracks(){
lock_guard<recursive_mutex> lck(_mtx);
uninit();
init();
//添加Track
for (auto &pr : _allTrackMap){
InfoL << "添加Track:" << pr.first << " " << pr.second;
_track_id_to_stream_id[pr.first] = mpeg_ts_add_stream(_context,pr.second, nullptr,0);
}
}
void onTs(const void *packet, int bytes) {
lock_guard<recursive_mutex> lck(_mtx);
if(_onts){
_onts(packet,bytes);
}
if(_file){
fwrite(packet,bytes,1,_file.get());
}
}
private:
void *_context = nullptr;
char *_tsbuf[188];
unordered_map<int,int > _track_id_to_stream_id;
unordered_map<int,int > _allTrackMap;
recursive_mutex _mtx;
onTsCallback _onts;
char _file_buf[64 * 1024];
std::shared_ptr<FILE> _file;
};
}//namespace mediakit
#endif //TSMUXER_H
#include "crc32.h"
#define BSWAP16C(x) (((x) << 8 & 0xff00) | ((x) >> 8 & 0x00ff))
#define BSWAP32C(x) (BSWAP16C(x) << 16 | BSWAP16C((x) >> 16))
#define BSWAP64C(x) (BSWAP32C(x) << 32 | BSWAP32C((x) >> 32))
static const unsigned int crc_tab[256] = {
0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,
0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7,
0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3,
0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef,
0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb,
0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,
0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4,
0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08,
0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc,
0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050,
0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,
0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1,
0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5,
0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9,
0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd,
0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,
0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2,
0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e,
0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a,
0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676,
0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,
0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
unsigned int calc_crc32 (unsigned char *data, unsigned int datalen)
{
unsigned int i;
unsigned int crc = 0xffffffff;
for (i=0; i<datalen; i++)
{
crc = (crc << 8) ^ crc_tab[((crc >> 24) ^ *data++) & 0xff];
}
return crc;
}
unsigned int Zwg_ntohl(unsigned int s)
{
union
{
int i;
char buf;
}a;
a.i = 0x01;
if(a.buf)
{
// 小端
s = BSWAP32C(s);
}
return s;
}
#ifndef CRC32_H_
#define CRC32_H_
unsigned int calc_crc32 (unsigned char *data, unsigned int datalen);
unsigned int Zwg_ntohl(unsigned int s);
#endif /* CRC32_H_ */
......@@ -37,7 +37,7 @@ foreach(TEST_SRC ${TEST_SRC_LIST})
STRING(REGEX REPLACE "^\\./|\\.c[a-zA-Z0-9_]*$" "" TEST_EXE_NAME ${TEST_SRC})
message(STATUS "add test:${TEST_EXE_NAME}")
add_executable(${TEST_EXE_NAME} ${TEST_SRC})
target_link_libraries(${TEST_EXE_NAME} ${LINK_LIB_LIST})
target_link_libraries(${TEST_EXE_NAME} mpeg ${LINK_LIB_LIST})
endforeach()
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论