diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index 09672376..0edf0fd9 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -1,4 +1,4 @@ -name: C/C++ CI +name: linux C/C++ CI on: [push] diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml new file mode 100644 index 00000000..2a52188a --- /dev/null +++ b/.github/workflows/macos.yml @@ -0,0 +1,39 @@ +name: macos C/C++ CI + +on: [push] + +jobs: + build: + + runs-on: macOS-latest + + steps: + - uses: actions/checkout@v1 + + - name: 下载submodule源码 + run: git submodule update --init + +# - name: 安装brew +# run: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" +# +# - name: brew安装依赖库(非必选) +# run: brew update && brew install cmake openssl sdl2 ffmpeg + +# - name: 下载 SRTP +# uses: actions/checkout@v2 +# with: +# repository: cisco/libsrtp +# fetch-depth: 1 +# ref: v2.3.0 +# path: 3rdpart/libsrtp +# +# - name: 编译 SRTP +# run: cd 3rdpart/libsrtp && ./configure --enable-openssl && make -j4 && sudo make install + + - name: 编译 + run: mkdir -p build && cd build && cmake .. && make -j4 + + - name: 运行MediaServer + run: pwd && cd release/linux/Debug && sudo ./MediaServer -d & + + diff --git a/3rdpart/ZLToolKit b/3rdpart/ZLToolKit index 25062620..b4967605 160000 --- a/3rdpart/ZLToolKit +++ b/3rdpart/ZLToolKit @@ -1 +1 @@ -Subproject commit 25062620233c62475aaffc0a9960e2689d8418ce +Subproject commit b49676057e05bed1b43070c99bc4e541f2302526 diff --git a/api/source/mk_events.cpp b/api/source/mk_events.cpp index 0d5275e8..e8bbe894 100644 --- a/api/source/mk_events.cpp +++ b/api/source/mk_events.cpp @@ -14,6 +14,8 @@ #include "Http/HttpSession.h" #include "Rtsp/RtspSession.h" #include "Record/MP4Recorder.h" + +using namespace toolkit; using namespace mediakit; static void* s_tag; diff --git a/api/source/mk_events_objects.cpp b/api/source/mk_events_objects.cpp index c39a84d6..86fbbfbe 100644 --- a/api/source/mk_events_objects.cpp +++ b/api/source/mk_events_objects.cpp @@ -16,6 +16,8 @@ #include "Http/HttpBody.h" #include "Http/HttpClient.h" #include "Rtsp/RtspSession.h" + +using namespace toolkit; using namespace mediakit; ///////////////////////////////////////////RecordInfo///////////////////////////////////////////// @@ -247,7 +249,7 @@ API_EXPORT mk_http_body API_CALL mk_http_body_from_string(const char *str, size_ if(!len){ len = strlen(str); } - return new HttpBody::Ptr(new HttpStringBody(string(str,len))); + return new HttpBody::Ptr(new HttpStringBody(std::string(str, len))); } API_EXPORT mk_http_body API_CALL mk_http_body_from_file(const char *file_path){ diff --git a/api/source/mk_h264_splitter.cpp b/api/source/mk_h264_splitter.cpp index f764de36..bf548ad1 100644 --- a/api/source/mk_h264_splitter.cpp +++ b/api/source/mk_h264_splitter.cpp @@ -15,7 +15,7 @@ using namespace mediakit; class H264Splitter : public HttpRequestSplitter { public: - using onH264 = function; + using onH264 = std::function; H264Splitter() = default; ~H264Splitter() override; void setOnSplitted(onH264 cb); diff --git a/api/source/mk_proxyplayer.cpp b/api/source/mk_proxyplayer.cpp index f151ceb8..158968a2 100644 --- a/api/source/mk_proxyplayer.cpp +++ b/api/source/mk_proxyplayer.cpp @@ -29,7 +29,7 @@ API_EXPORT void API_CALL mk_proxy_player_release(mk_proxy_player ctx) { API_EXPORT void API_CALL mk_proxy_player_set_option(mk_proxy_player ctx, const char *key, const char *val){ assert(ctx && key && val); PlayerProxy::Ptr &obj = *((PlayerProxy::Ptr *) ctx); - string key_str(key),val_str(val); + std::string key_str(key), val_str(val); obj->getPoller()->async([obj,key_str,val_str](){ //切换线程再操作 (*obj)[key_str] = val_str; @@ -39,7 +39,7 @@ API_EXPORT void API_CALL mk_proxy_player_set_option(mk_proxy_player ctx, const c API_EXPORT void API_CALL mk_proxy_player_play(mk_proxy_player ctx, const char *url) { assert(ctx && url); PlayerProxy::Ptr &obj = *((PlayerProxy::Ptr *) ctx); - string url_str(url); + std::string url_str(url); obj->getPoller()->async([obj,url_str](){ //切换线程再操作 obj->play(url_str); diff --git a/api/source/mk_pusher.cpp b/api/source/mk_pusher.cpp index ae68e12d..a63a7708 100644 --- a/api/source/mk_pusher.cpp +++ b/api/source/mk_pusher.cpp @@ -11,6 +11,8 @@ #include #include "mk_pusher.h" #include "Pusher/MediaPusher.h" + +using namespace toolkit; using namespace mediakit; API_EXPORT mk_pusher API_CALL mk_pusher_create(const char *schema,const char *vhost,const char *app, const char *stream){ @@ -35,7 +37,7 @@ API_EXPORT void API_CALL mk_pusher_release(mk_pusher ctx){ API_EXPORT void API_CALL mk_pusher_set_option(mk_pusher ctx, const char *key, const char *val){ assert(ctx && key && val); MediaPusher::Ptr &obj = *((MediaPusher::Ptr *)ctx); - string key_str(key),val_str(val); + std::string key_str(key), val_str(val); obj->getPoller()->async([obj,key_str,val_str](){ //切换线程再操作 (*obj)[key_str] = val_str; @@ -45,7 +47,7 @@ API_EXPORT void API_CALL mk_pusher_set_option(mk_pusher ctx, const char *key, co API_EXPORT void API_CALL mk_pusher_publish(mk_pusher ctx,const char *url){ assert(ctx && url); MediaPusher::Ptr &obj = *((MediaPusher::Ptr *)ctx); - string url_str(url); + std::string url_str(url); obj->getPoller()->async([obj,url_str](){ //切换线程再操作 obj->publish(url_str); diff --git a/api/source/mk_tcp.cpp b/api/source/mk_tcp.cpp index e707328b..e0493a0d 100644 --- a/api/source/mk_tcp.cpp +++ b/api/source/mk_tcp.cpp @@ -13,6 +13,8 @@ #include "mk_tcp_private.h" #include "Http/WebSocketClient.h" #include "Http/WebSocketSession.h" + +using namespace toolkit; using namespace mediakit; API_EXPORT const char* API_CALL mk_sock_info_peer_ip(const mk_sock_info ctx, char *buf){ @@ -62,19 +64,19 @@ API_EXPORT void API_CALL mk_tcp_session_send(const mk_tcp_session ctx,const char API_EXPORT void API_CALL mk_tcp_session_send_safe(const mk_tcp_session ctx,const char *data,size_t len){ assert(ctx && data); - if(!len){ + if (!len) { len = strlen(data); } try { - weak_ptr weak_session = ((TcpSessionForC *)ctx)->shared_from_this(); - string str = string(data,len); + std::weak_ptr weak_session = ((TcpSessionForC *)ctx)->shared_from_this(); + std::string str = std::string(data,len); ((TcpSessionForC *)ctx)->async([weak_session,str](){ auto session_session = weak_session.lock(); if(session_session){ session_session->SockSender::send(str); } }); - }catch (std::exception &ex){ + } catch (std::exception &ex) { WarnL << "can not got the strong pionter of this mk_tcp_session:" << ex.what(); } } @@ -208,13 +210,13 @@ TcpClientForC::Ptr *mk_tcp_client_create_l(mk_tcp_client_events *events, mk_tcp_ case mk_type_tcp: return new TcpClientForC::Ptr(new TcpClientForC(events)); case mk_type_ssl: - return (TcpClientForC::Ptr *)new shared_ptr >(new TcpSessionWithSSL(events)); + return (TcpClientForC::Ptr *)new std::shared_ptr >(new TcpSessionWithSSL(events)); case mk_type_ws: //此处你也可以修改WebSocketHeader::BINARY - return (TcpClientForC::Ptr *)new shared_ptr >(new WebSocketClient(events)); + return (TcpClientForC::Ptr *)new std::shared_ptr >(new WebSocketClient(events)); case mk_type_wss: //此处你也可以修改WebSocketHeader::BINARY - return (TcpClientForC::Ptr *)new shared_ptr >(new WebSocketClient(events)); + return (TcpClientForC::Ptr *)new std::shared_ptr >(new WebSocketClient(events)); default: return nullptr; } @@ -253,7 +255,7 @@ API_EXPORT void API_CALL mk_tcp_client_send(mk_tcp_client ctx, const char *data, API_EXPORT void API_CALL mk_tcp_client_send_safe(mk_tcp_client ctx, const char *data, int len){ assert(ctx && data); TcpClientForC::Ptr *client = (TcpClientForC::Ptr *)ctx; - weak_ptr weakClient = *client; + std::weak_ptr weakClient = *client; auto buf = BufferRaw::create(); buf->assign(data,len); (*client)->async([weakClient,buf](){ diff --git a/api/source/mk_tcp_private.h b/api/source/mk_tcp_private.h index 5a4090b2..46cdc6f3 100644 --- a/api/source/mk_tcp_private.h +++ b/api/source/mk_tcp_private.h @@ -14,17 +14,16 @@ #include "mk_tcp.h" #include "Network/TcpClient.h" #include "Network/TcpSession.h" -using namespace toolkit; -class TcpClientForC : public TcpClient { +class TcpClientForC : public toolkit::TcpClient { public: typedef std::shared_ptr Ptr; TcpClientForC(mk_tcp_client_events *events) ; ~TcpClientForC() override ; - void onRecv(const Buffer::Ptr &pBuf) override; - void onErr(const SockException &ex) override; + void onRecv(const toolkit::Buffer::Ptr &pBuf) override; + void onErr(const toolkit::SockException &ex) override; void onManager() override; - void onConnect(const SockException &ex) override; + void onConnect(const toolkit::SockException &ex) override; void setClient(mk_tcp_client client); void *_user_data; private: @@ -32,12 +31,12 @@ private: mk_tcp_client _client; }; -class TcpSessionForC : public TcpSession { +class TcpSessionForC : public toolkit::TcpSession { public: - TcpSessionForC(const Socket::Ptr &pSock) ; + TcpSessionForC(const toolkit::Socket::Ptr &pSock) ; ~TcpSessionForC() override = default; - void onRecv(const Buffer::Ptr &buffer) override ; - void onError(const SockException &err) override; + void onRecv(const toolkit::Buffer::Ptr &buffer) override ; + void onError(const toolkit::SockException &err) override; void onManager() override; void *_user_data; uint16_t _local_port; diff --git a/api/source/mk_thread.cpp b/api/source/mk_thread.cpp index 4dce6911..63efb1a3 100644 --- a/api/source/mk_thread.cpp +++ b/api/source/mk_thread.cpp @@ -91,7 +91,7 @@ private: on_mk_timer _cb = nullptr; void *_user_data = nullptr; recursive_mutex _mxt; - DelayTask::Ptr _task; + EventPoller::DelayTask::Ptr _task; }; API_EXPORT mk_timer API_CALL mk_timer_create(mk_thread ctx,uint64_t delay_ms,on_mk_timer cb, void *user_data){ diff --git a/api/source/mk_util.cpp b/api/source/mk_util.cpp index b55855f5..a898b8f5 100644 --- a/api/source/mk_util.cpp +++ b/api/source/mk_util.cpp @@ -8,10 +8,13 @@ * may be found in the AUTHORS file in the root of the source tree. */ +#include +#include + #include "mk_util.h" -#include #include "Util/util.h" #include "Util/logger.h" + using namespace std; using namespace toolkit; diff --git a/player/AudioSRC.h b/player/AudioSRC.h index 3f90126b..0a631750 100644 --- a/player/AudioSRC.h +++ b/player/AudioSRC.h @@ -30,9 +30,6 @@ extern "C" { #include "SDLAudioDevice.h" #include "FFMpegDecoder.h" -using namespace std; -using namespace toolkit; - class AudioSRCDelegate { public: virtual ~AudioSRCDelegate() {}; @@ -58,7 +55,7 @@ private: int _buf_size = 0; std::shared_ptr _buf; AudioSRCDelegate *_delegate = nullptr; - BufferLikeString _target_buf; + toolkit::BufferLikeString _target_buf; SDL_AudioCVT _audio_cvt; }; @@ -79,8 +76,8 @@ private: private: int _sample_rate, _channel; SDL_AudioFormat _format; - mutex _mtx; - BufferLikeString _buffer; + std::mutex _mtx; + toolkit::BufferLikeString _buffer; SDLAudioDevice::Ptr _device; }; diff --git a/player/FFMpegDecoder.cpp b/player/FFMpegDecoder.cpp index d132a060..ae288bac 100644 --- a/player/FFMpegDecoder.cpp +++ b/player/FFMpegDecoder.cpp @@ -12,6 +12,7 @@ #define MAX_DELAY_SECOND 3 using namespace std; +using namespace toolkit; using namespace mediakit; static string ffmpeg_err(int errnum) { diff --git a/player/FFMpegDecoder.h b/player/FFMpegDecoder.h index dba0b2e6..de251f50 100644 --- a/player/FFMpegDecoder.h +++ b/player/FFMpegDecoder.h @@ -60,15 +60,15 @@ public: ~TaskManager(); protected: - void startThread(const string &name); + void startThread(const std::string &name); void stopThread(); - void addEncodeTask(function task); - void addDecodeTask(bool key_frame, function task); + void addEncodeTask(std::function task); + void addDecodeTask(bool key_frame, std::function task); bool isEnabled() const; private: - void onThreadRun(const string &name); + void onThreadRun(const std::string &name); void pushExit(); private: @@ -81,36 +81,36 @@ private: private: bool _decode_drop_start = false; bool _exit = false; - mutex _task_mtx; - semaphore _sem; - List > _task; - std::shared_ptr _thread; + std::mutex _task_mtx; + toolkit::semaphore _sem; + toolkit::List > _task; + std::shared_ptr _thread; }; class FFmpegDecoder : private TaskManager { public: using Ptr = std::shared_ptr; - using onDec = function; + using onDec = std::function; - FFmpegDecoder(const Track::Ptr &track); + FFmpegDecoder(const mediakit::Track::Ptr &track); ~FFmpegDecoder(); - bool inputFrame(const Frame::Ptr &frame, bool may_async = true); + bool inputFrame(const mediakit::Frame::Ptr &frame, bool may_async = true); void setOnDecode(onDec cb); void flush(); const AVCodecContext *getContext() const; private: void onDecode(const FFmpegFrame::Ptr &frame); - bool inputFrame_l(const Frame::Ptr &frame); + bool inputFrame_l(const mediakit::Frame::Ptr &frame); bool decodeFrame(const char *data, size_t size, uint32_t dts, uint32_t pts); private: bool _do_merger = false; - Ticker _ticker; + toolkit::Ticker _ticker; onDec _cb; std::shared_ptr _context; - FrameMerger _merger{FrameMerger::h264_prefix}; + mediakit::FrameMerger _merger { mediakit::FrameMerger::h264_prefix }; }; #endif /* FFMpegDecoder_H_ */ diff --git a/player/SDLAudioDevice.h b/player/SDLAudioDevice.h index 91d92ecf..703ed2ee 100644 --- a/player/SDLAudioDevice.h +++ b/player/SDLAudioDevice.h @@ -21,7 +21,6 @@ #define DEFAULT_CHANNEL 2 #define DEFAULT_SAMPLES 1024 -using namespace std; class AudioSRC; @@ -43,8 +42,8 @@ private: private: std::shared_ptr _play_buf; SDL_AudioSpec _audio_config; - recursive_mutex _channel_mtx; - unordered_set _channels; + std::recursive_mutex _channel_mtx; + std::unordered_set _channels; }; #endif /* SDLAUDIOMIXER_SDLAUDIODEVICE_H_ */ diff --git a/player/YuvDisplayer.h b/player/YuvDisplayer.h index 57fa7816..737350e3 100644 --- a/player/YuvDisplayer.h +++ b/player/YuvDisplayer.h @@ -25,12 +25,8 @@ extern "C" { #pragma comment(lib,"SDL2.lib") #endif //defined(_WIN32) -using namespace toolkit; -using namespace mediakit; - #define REFRESH_EVENT (SDL_USEREVENT + 1) - class SDLDisplayerHelper { public: @@ -44,7 +40,7 @@ public: template void doTask(FUN &&f){ { - lock_guard lck(_mtxTask); + std::lock_guard lck(_mtxTask); _taskList.emplace_back(f); } SDL_Event event; @@ -61,8 +57,8 @@ public: switch (event.type){ case REFRESH_EVENT:{ { - lock_guard lck(_mtxTask); - if(_taskList.empty()){ + std::lock_guard lck(_mtxTask); + if (_taskList.empty()) { //not reachable continue; } @@ -102,17 +98,17 @@ public: using Ptr = std::shared_ptr; YuvDisplayer(void *hwnd = nullptr,const char *title = "untitled"){ - static onceToken token([]() { - if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) == -1) { - string err = "初始化SDL失败:"; + static toolkit::onceToken token([]() { + if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) == -1) { + std::string err = "初始化SDL失败:"; err+= SDL_GetError(); ErrorL << err; throw std::runtime_error(err); } SDL_LogSetAllPriority(SDL_LOG_PRIORITY_CRITICAL); - SDL_LogSetOutputFunction([](void *userdata, int category, SDL_LogPriority priority, const char *message){ + SDL_LogSetOutputFunction([](void *userdata, int category, SDL_LogPriority priority, const char *message) { DebugL << category << " " << priority << message; - },nullptr); + }, nullptr); InfoL << "SDL_Init"; }, []() { SDLDisplayerHelper::Destory(); @@ -194,7 +190,7 @@ public: return false; } private: - string _title; + std::string _title; SDL_Window *_win = nullptr; SDL_Renderer *_render = nullptr; SDL_Texture *_texture = nullptr; diff --git a/player/test_player.cpp b/player/test_player.cpp index bd0c492b..b3ee1891 100644 --- a/player/test_player.cpp +++ b/player/test_player.cpp @@ -116,7 +116,7 @@ int main(int argc, char *argv[]) { WarnL << "play shutdown: " << ex.what(); }); - (*player)[kRtpType] = atoi(argv[2]); + (*player)[Client::kRtpType] = atoi(argv[2]); //不等待track ready再回调播放成功事件,这样可以加快秒开速度 (*player)[Client::kWaitTrackReady] = false; player->play(argv[1]); diff --git a/server/FFmpegSource.cpp b/server/FFmpegSource.cpp index 4619e6f5..2a8d3224 100644 --- a/server/FFmpegSource.cpp +++ b/server/FFmpegSource.cpp @@ -16,6 +16,10 @@ #include "Thread/WorkThreadPool.h" #include "Network/sockutil.h" +using namespace std; +using namespace toolkit; +using namespace mediakit; + namespace FFmpeg { #define FFmpeg_FIELD "ffmpeg." const string kBin = FFmpeg_FIELD"bin"; diff --git a/server/FFmpegSource.h b/server/FFmpegSource.h index 69a653d2..ad27202d 100644 --- a/server/FFmpegSource.h +++ b/server/FFmpegSource.h @@ -19,12 +19,8 @@ #include "Network/Socket.h" #include "Common/MediaSource.h" -using namespace std; -using namespace toolkit; -using namespace mediakit; - namespace FFmpeg { - extern const string kSnap; + extern const std::string kSnap; } class FFmpegSnap { @@ -34,16 +30,16 @@ public: /// \param save_path 截图jpeg文件保存路径 /// \param timeout_sec 生成截图超时时间(防止阻塞太久) /// \param cb 生成截图成功与否回调 - static void makeSnap(const string &play_url, const string &save_path, float timeout_sec, const function &cb); + static void makeSnap(const std::string &play_url, const std::string &save_path, float timeout_sec, const std::function &cb); private: FFmpegSnap() = delete; ~FFmpegSnap() = delete; }; -class FFmpegSource : public std::enable_shared_from_this , public MediaSourceEventInterceptor{ +class FFmpegSource : public std::enable_shared_from_this , public mediakit::MediaSourceEventInterceptor{ public: - typedef shared_ptr Ptr; - typedef function onPlay; + using Ptr = std::shared_ptr; + using onPlay = std::function; FFmpegSource(); ~FFmpegSource(); @@ -51,7 +47,7 @@ public: /** * 设置主动关闭回调 */ - void setOnClose(const function &cb); + void setOnClose(const std::function &cb); /** * 开始播放url @@ -61,7 +57,7 @@ public: * @param timeout_ms 等待结果超时时间,单位毫秒 * @param cb 成功与否回调 */ - void play(const string &ffmpeg_cmd_key, const string &src_url, const string &dst_url, int timeout_ms, const onPlay &cb); + void play(const std::string &ffmpeg_cmd_key, const std::string &src_url, const std::string &dst_url, int timeout_ms, const onPlay &cb); /** * 设置录制 @@ -71,32 +67,32 @@ public: void setupRecordFlag(bool enable_hls, bool enable_mp4); private: - void findAsync(int maxWaitMS ,const function &cb); + void findAsync(int maxWaitMS ,const std::function &cb); void startTimer(int timeout_ms); - void onGetMediaSource(const MediaSource::Ptr &src); + void onGetMediaSource(const mediakit::MediaSource::Ptr &src); ///////MediaSourceEvent override/////// // 关闭 - bool close(MediaSource &sender,bool force) override; + bool close(mediakit::MediaSource &sender,bool force) override; // 获取媒体源类型 - MediaOriginType getOriginType(MediaSource &sender) const override; + mediakit::MediaOriginType getOriginType(mediakit::MediaSource &sender) const override; //获取媒体源url或者文件路径 - string getOriginUrl(MediaSource &sender) const override; + std::string getOriginUrl(mediakit::MediaSource &sender) const override; // 获取媒体源客户端相关信息 - std::shared_ptr getOriginSock(MediaSource &sender) const override; + std::shared_ptr getOriginSock(mediakit::MediaSource &sender) const override; private: bool _enable_hls = false; bool _enable_mp4 = false; Process _process; - Timer::Ptr _timer; - EventPoller::Ptr _poller; - MediaInfo _media_info; - string _src_url; - string _dst_url; - string _ffmpeg_cmd_key; - function _onClose; - Ticker _replay_ticker; + toolkit::Timer::Ptr _timer; + toolkit::EventPoller::Ptr _poller; + mediakit::MediaInfo _media_info; + std::string _src_url; + std::string _dst_url; + std::string _ffmpeg_cmd_key; + std::function _onClose; + toolkit::Ticker _replay_ticker; }; diff --git a/server/Process.cpp b/server/Process.cpp index 6e3e46ad..48f99946 100644 --- a/server/Process.cpp +++ b/server/Process.cpp @@ -28,6 +28,7 @@ #include "Poller/EventPoller.h" #include "Process.h" using namespace toolkit; +using namespace std; void Process::run(const string &cmd, const string &log_file_tmp) { kill(2000); diff --git a/server/Process.h b/server/Process.h index 371b83b7..564c791a 100644 --- a/server/Process.h +++ b/server/Process.h @@ -19,13 +19,12 @@ typedef int pid_t; #include #include -using namespace std; class Process { public: Process(); ~Process(); - void run(const string &cmd,const string &log_file); + void run(const std::string &cmd,const std::string &log_file); void kill(int max_delay,bool force = false); bool wait(bool block = true); int exit_code(); diff --git a/server/System.cpp b/server/System.cpp index 0ca3a807..bffa015f 100644 --- a/server/System.cpp +++ b/server/System.cpp @@ -25,6 +25,7 @@ #include "Util/NoticeCenter.h" #include "Util/uv_errno.h" using namespace toolkit; +using namespace std; const int MAX_STACK_FRAMES = 128; #define BroadcastOnCrashDumpArgs int &sig,const vector > &stack diff --git a/server/System.h b/server/System.h index 58fb59f3..ac679fac 100644 --- a/server/System.h +++ b/server/System.h @@ -12,11 +12,10 @@ #define ZLMEDIAKIT_SYSTEM_H #include -using namespace std; class System { public: - static string execute(const string &cmd); + static std::string execute(const std::string &cmd); static void startDaemon(); static void systemSetup(); }; diff --git a/server/WebApi.cpp b/server/WebApi.cpp index b8434921..e5b2dc55 100755 --- a/server/WebApi.cpp +++ b/server/WebApi.cpp @@ -48,7 +48,8 @@ #include #endif // _WIN32 - +using namespace std; +using namespace Json; using namespace toolkit; using namespace mediakit; @@ -461,11 +462,11 @@ void addStreamProxy(const string &vhost, const string &app, const string &stream s_proxyMap[key] = player; //指定RTP over TCP(播放rtsp时有效) - (*player)[kRtpType] = rtp_type; + (*player)[Client::kRtpType] = rtp_type; if (timeout_sec > 0.1) { //播放握手超时时间 - (*player)[kTimeoutMS] = timeout_sec * 1000; + (*player)[Client::kTimeoutMS] = timeout_sec * 1000; } //开始播放,如果播放失败或者播放中止,将会自动重试若干次,默认一直重试 @@ -839,11 +840,11 @@ void installWebApi() { s_proxyPusherMap[key] = pusher; //指定RTP over TCP(播放rtsp时有效) - (*pusher)[kRtpType] = rtp_type; + (*pusher)[Client::kRtpType] = rtp_type; if (timeout_sec > 0.1) { //推流握手超时时间 - (*pusher)[kTimeoutMS] = timeout_sec * 1000; + (*pusher)[Client::kTimeoutMS] = timeout_sec * 1000; } //开始推流,如果推流失败或者推流中止,将会自动重试若干次,默认一直重试 diff --git a/server/WebApi.h b/server/WebApi.h index 10d2a9a2..cc7cf62e 100755 --- a/server/WebApi.h +++ b/server/WebApi.h @@ -18,23 +18,18 @@ #include "Network/Socket.h" #include "Http/HttpSession.h" -using namespace std; -using namespace Json; -using namespace toolkit; -using namespace mediakit; - //配置文件路径 -extern string g_ini_file; +extern std::string g_ini_file; namespace mediakit { ////////////RTSP服务器配置/////////// namespace Rtsp { -extern const string kPort; +extern const std::string kPort; } //namespace Rtsp ////////////RTMP服务器配置/////////// namespace Rtmp { -extern const string kPort; +extern const std::string kPort; } //namespace RTMP } // namespace mediakit @@ -79,25 +74,25 @@ public: ~SuccessException() = default; }; -using ApiArgsType = map; +using ApiArgsType = std::map; template -string getValue(Args &args, const First &first) { +std::string getValue(Args &args, const First &first) { return args[first]; } template -string getValue(Json::Value &args, const First &first) { +std::string getValue(Json::Value &args, const First &first) { return args[first].asString(); } template -string getValue(string &args, const First &first) { +std::string getValue(std::string &args, const First &first) { return ""; } template -string getValue(const Parser &parser, const First &first) { +std::string getValue(const mediakit::Parser &parser, const First &first) { auto ret = parser.getUrlArgs()[first]; if (!ret.empty()) { return ret; @@ -106,12 +101,12 @@ string getValue(const Parser &parser, const First &first) { } template -string getValue(Parser &parser, const First &first) { - return getValue((const Parser &) parser, first); +std::string getValue(mediakit::Parser &parser, const First &first) { + return getValue((const mediakit::Parser &) parser, first); } template -string getValue(const Parser &parser, Args &args, const First &first) { +std::string getValue(const mediakit::Parser &parser, Args &args, const First &first) { auto ret = getValue(args, first); if (!ret.empty()) { return ret; @@ -122,24 +117,24 @@ string getValue(const Parser &parser, Args &args, const First &first) { template class HttpAllArgs { public: - HttpAllArgs(const Parser &parser, Args &args) { + HttpAllArgs(const mediakit::Parser &parser, Args &args) { _get_args = [&args]() { return (void *) &args; }; - _get_parser = [&parser]() -> const Parser & { + _get_parser = [&parser]() -> const mediakit::Parser & { return parser; }; - _get_value = [](HttpAllArgs &that, const string &key) { + _get_value = [](HttpAllArgs &that, const std::string &key) { return getValue(that.getParser(), that.getArgs(), key); }; _clone = [&](HttpAllArgs &that) { that._get_args = [args]() { return (void *) &args; }; - that._get_parser = [parser]() -> const Parser & { + that._get_parser = [parser]() -> const mediakit::Parser & { return parser; }; - that._get_value = [](HttpAllArgs &that, const string &key) { + that._get_value = [](HttpAllArgs &that, const std::string &key) { return getValue(that.getParser(), that.getArgs(), key); }; that._cache_able = true; @@ -160,11 +155,11 @@ public: ~HttpAllArgs() = default; template - variant operator[](const Key &key) const { - return (variant)_get_value(*(HttpAllArgs*)this, key); + toolkit::variant operator[](const Key &key) const { + return (toolkit::variant)_get_value(*(HttpAllArgs*)this, key); } - const Parser &getParser() const { + const mediakit::Parser &getParser() const { return _get_parser(); } @@ -178,34 +173,34 @@ public: private: bool _cache_able = false; - function _get_args; - function _get_parser; - function _get_value; - function _clone; + std::function _get_args; + std::function _get_parser; + std::function _get_value; + std::function _clone; }; -#define API_ARGS_MAP SockInfo &sender, HttpSession::KeyValue &headerOut, const HttpAllArgs &allArgs, Json::Value &val -#define API_ARGS_MAP_ASYNC API_ARGS_MAP, const HttpSession::HttpResponseInvoker &invoker -#define API_ARGS_JSON SockInfo &sender, HttpSession::KeyValue &headerOut, const HttpAllArgs &allArgs, Json::Value &val -#define API_ARGS_JSON_ASYNC API_ARGS_JSON, const HttpSession::HttpResponseInvoker &invoker -#define API_ARGS_STRING SockInfo &sender, HttpSession::KeyValue &headerOut, const HttpAllArgs &allArgs, Json::Value &val -#define API_ARGS_STRING_ASYNC API_ARGS_STRING, const HttpSession::HttpResponseInvoker &invoker +#define API_ARGS_MAP toolkit::SockInfo &sender, mediakit::HttpSession::KeyValue &headerOut, const HttpAllArgs &allArgs, Json::Value &val +#define API_ARGS_MAP_ASYNC API_ARGS_MAP, const mediakit::HttpSession::HttpResponseInvoker &invoker +#define API_ARGS_JSON toolkit::SockInfo &sender, mediakit::HttpSession::KeyValue &headerOut, const HttpAllArgs &allArgs, Json::Value &val +#define API_ARGS_JSON_ASYNC API_ARGS_JSON, const mediakit::HttpSession::HttpResponseInvoker &invoker +#define API_ARGS_STRING toolkit::SockInfo &sender, mediakit::HttpSession::KeyValue &headerOut, const HttpAllArgs &allArgs, Json::Value &val +#define API_ARGS_STRING_ASYNC API_ARGS_STRING, const mediakit::HttpSession::HttpResponseInvoker &invoker #define API_ARGS_VALUE sender, headerOut, allArgs, val //注册http请求参数是map类型的http api -void api_regist(const string &api_path, const function &func); +void api_regist(const std::string &api_path, const std::function &func); //注册http请求参数是map类型,但是可以异步回复的的http api -void api_regist(const string &api_path, const function &func); +void api_regist(const std::string &api_path, const std::function &func); //注册http请求参数是Json::Value类型的http api(可以支持多级嵌套的json参数对象) -void api_regist(const string &api_path, const function &func); +void api_regist(const std::string &api_path, const std::function &func); //注册http请求参数是Json::Value类型,但是可以异步回复的的http api -void api_regist(const string &api_path, const function &func); +void api_regist(const std::string &api_path, const std::function &func); //注册http请求参数是http原始请求信息的http api -void api_regist(const string &api_path, const function &func); +void api_regist(const std::string &api_path, const std::function &func); //注册http请求参数是http原始请求信息的异步回复的http api -void api_regist(const string &api_path, const function &func); +void api_regist(const std::string &api_path, const std::function &func); template bool checkArgs(Args &args, const First &first) { @@ -234,9 +229,9 @@ bool checkArgs(Args &args, const First &first, const KeyTypes &...keys) { void installWebApi(); void unInstallWebApi(); -Value makeMediaSourceJson(MediaSource &media); -void getStatisticJson(const function &cb); -void addStreamProxy(const string &vhost, const string &app, const string &stream, const string &url, int retry_count, +Json::Value makeMediaSourceJson(mediakit::MediaSource &media); +void getStatisticJson(const std::function &cb); +void addStreamProxy(const std::string &vhost, const std::string &app, const std::string &stream, const std::string &url, int retry_count, bool enable_hls, bool enable_mp4, int rtp_type, float timeout_sec, - const function &cb); + const std::function &cb); #endif //ZLMEDIAKIT_WEBAPI_H diff --git a/server/WebHook.cpp b/server/WebHook.cpp index c33a4998..727fd211 100755 --- a/server/WebHook.cpp +++ b/server/WebHook.cpp @@ -21,6 +21,8 @@ #include "WebHook.h" #include "WebApi.h" +using namespace std; +using namespace Json; using namespace toolkit; using namespace mediakit; diff --git a/server/WebHook.h b/server/WebHook.h index 77093a58..a1adc012 100755 --- a/server/WebHook.h +++ b/server/WebHook.h @@ -14,21 +14,19 @@ #include #include #include "jsoncpp/json.h" -using namespace std; -using namespace Json; //支持json或urlencoded方式传输参数 #define JSON_ARGS #ifdef JSON_ARGS -typedef Value ArgsType; +typedef Json::Value ArgsType; #else -typedef HttpArgs ArgsType; +typedef mediakit::HttpArgs ArgsType; #endif namespace Hook { //web hook回复最大超时时间 -extern const string kTimeoutSec; +extern const std::string kTimeoutSec; }//namespace Hook void installWebHook(); @@ -39,5 +37,5 @@ void unInstallWebHook(); * @param body 请求body * @param func 回调 */ -void do_http_hook(const string &url, const ArgsType &body, const function &func = nullptr); +void do_http_hook(const std::string &url, const ArgsType &body, const std::function &func = nullptr); #endif //ZLMEDIAKIT_WEBHOOK_H diff --git a/src/Common/Device.cpp b/src/Common/Device.cpp index b3384258..6720feb0 100644 --- a/src/Common/Device.cpp +++ b/src/Common/Device.cpp @@ -24,6 +24,7 @@ #include "Codec/H264Encoder.h" #endif //ENABLE_X264 using namespace toolkit; +using namespace std; namespace mediakit { diff --git a/src/Common/Device.h b/src/Common/Device.h index b4d8173b..22b068e9 100644 --- a/src/Common/Device.h +++ b/src/Common/Device.h @@ -17,8 +17,6 @@ #include "Util/util.h" #include "Util/TimeTicker.h" #include "Common/MultiMediaSourceMuxer.h" -using namespace std; -using namespace toolkit; namespace mediakit { @@ -48,7 +46,7 @@ class DevChannel : public MultiMediaSourceMuxer{ public: typedef std::shared_ptr Ptr; //fDuration<=0为直播,否则为点播 - DevChannel(const string &vhost, const string &app, const string &stream_id, + DevChannel(const std::string &vhost, const std::string &app, const std::string &stream_id, float duration = 0, bool enable_hls = true, bool enable_mp4 = false); ~DevChannel() override ; @@ -126,7 +124,7 @@ private: std::shared_ptr _pAacEnc; std::shared_ptr _video; std::shared_ptr _audio; - SmoothTicker _aTicker[2]; + toolkit::SmoothTicker _aTicker[2]; }; } /* namespace mediakit */ diff --git a/src/Common/MediaSink.cpp b/src/Common/MediaSink.cpp index ac7b406b..c11d266e 100644 --- a/src/Common/MediaSink.cpp +++ b/src/Common/MediaSink.cpp @@ -11,6 +11,8 @@ #include "MediaSink.h" #include "Extension/AAC.h" +using namespace std; + namespace mediakit{ bool MediaSink::addTrack(const Track::Ptr &track_in) { diff --git a/src/Common/MediaSink.h b/src/Common/MediaSink.h index 1d29b038..ee6d404a 100644 --- a/src/Common/MediaSink.h +++ b/src/Common/MediaSink.h @@ -17,9 +17,6 @@ #include "Extension/Frame.h" #include "Extension/Track.h" -using namespace std; -using namespace toolkit; - namespace mediakit{ class TrackListener { @@ -106,7 +103,7 @@ public: * 获取所有Track * @param trackReady 是否获取已经准备好的Track */ - vector getTracks(bool trackReady = true) const override; + std::vector getTracks(bool trackReady = true) const override; /** * 返回是否所有track已经准备完成 @@ -154,10 +151,10 @@ private: private: bool _all_track_ready = false; size_t _max_track_size = 2; - unordered_map > _track_map; - unordered_map > _frame_unread; - unordered_map > _track_ready_callback; - Ticker _ticker; + std::unordered_map > _track_map; + std::unordered_map > _frame_unread; + std::unordered_map > _track_ready_callback; + toolkit::Ticker _ticker; MuteAudioMaker::Ptr _mute_audio_maker; }; diff --git a/src/Common/MediaSource.cpp b/src/Common/MediaSource.cpp index 4cd5f90f..126a10df 100644 --- a/src/Common/MediaSource.cpp +++ b/src/Common/MediaSource.cpp @@ -13,6 +13,8 @@ #include "Util/util.h" #include "Network/sockutil.h" #include "Network/TcpSession.h" + +using namespace std; using namespace toolkit; namespace toolkit { diff --git a/src/Common/MediaSource.h b/src/Common/MediaSource.h index fe28f232..7a5b2ebb 100644 --- a/src/Common/MediaSource.h +++ b/src/Common/MediaSource.h @@ -29,9 +29,6 @@ #include "Extension/Track.h" #include "Record/Recorder.h" -using namespace std; -using namespace toolkit; - namespace toolkit{ class Session; }// namespace toolkit @@ -50,7 +47,7 @@ enum class MediaOriginType : uint8_t { rtc_push, }; -string getOriginTypeString(MediaOriginType type); +std::string getOriginTypeString(MediaOriginType type); class MediaSource; class MediaSourceEvent{ @@ -62,9 +59,9 @@ public: // 获取媒体源类型 virtual MediaOriginType getOriginType(MediaSource &sender) const { return MediaOriginType::unknown; } // 获取媒体源url或者文件路径 - virtual string getOriginUrl(MediaSource &sender) const; + virtual std::string getOriginUrl(MediaSource &sender) const; // 获取媒体源客户端相关信息 - virtual std::shared_ptr getOriginSock(MediaSource &sender) const { return nullptr; } + virtual std::shared_ptr getOriginSock(MediaSource &sender) const { return nullptr; } // 通知拖动进度条 virtual bool seekTo(MediaSource &sender, uint32_t stamp) { return false; } @@ -83,18 +80,18 @@ public: ////////////////////////仅供MultiMediaSourceMuxer对象继承//////////////////////// // 开启或关闭录制 - virtual bool setupRecord(MediaSource &sender, Recorder::type type, bool start, const string &custom_path, size_t max_second) { return false; }; + virtual bool setupRecord(MediaSource &sender, Recorder::type type, bool start, const std::string &custom_path, size_t max_second) { return false; }; // 获取录制状态 virtual bool isRecording(MediaSource &sender, Recorder::type type) { return false; }; // 获取所有track相关信息 - virtual vector getMediaTracks(MediaSource &sender, bool trackReady = true) const { return vector(); }; + virtual std::vector getMediaTracks(MediaSource &sender, bool trackReady = true) const { return std::vector(); }; // 开始发送ps-rtp - virtual void startSendRtp(MediaSource &sender, const string &dst_url, uint16_t dst_port, const string &ssrc, bool is_udp, uint16_t src_port, const function &cb) { cb(0, SockException(Err_other, "not implemented"));}; + virtual void startSendRtp(MediaSource &sender, const std::string &dst_url, uint16_t dst_port, const std::string &ssrc, bool is_udp, uint16_t src_port, const std::function &cb) { cb(0, toolkit::SockException(toolkit::Err_other, "not implemented"));}; // 停止发送ps-rtp - virtual bool stopSendRtp(MediaSource &sender, const string &ssrc) {return false; } + virtual bool stopSendRtp(MediaSource &sender, const std::string &ssrc) {return false; } private: - Timer::Ptr _async_close_timer; + toolkit::Timer::Ptr _async_close_timer; }; //该对象用于拦截感兴趣的MediaSourceEvent事件 @@ -107,8 +104,8 @@ public: std::shared_ptr getDelegate() const; MediaOriginType getOriginType(MediaSource &sender) const override; - string getOriginUrl(MediaSource &sender) const override; - std::shared_ptr getOriginSock(MediaSource &sender) const override; + std::string getOriginUrl(MediaSource &sender) const override; + std::shared_ptr getOriginSock(MediaSource &sender) const override; bool seekTo(MediaSource &sender, uint32_t stamp) override; bool pause(MediaSource &sender, bool pause) override; @@ -117,11 +114,11 @@ public: int totalReaderCount(MediaSource &sender) override; void onReaderChanged(MediaSource &sender, int size) override; void onRegist(MediaSource &sender, bool regist) override; - bool setupRecord(MediaSource &sender, Recorder::type type, bool start, const string &custom_path, size_t max_second) override; + bool setupRecord(MediaSource &sender, Recorder::type type, bool start, const std::string &custom_path, size_t max_second) override; bool isRecording(MediaSource &sender, Recorder::type type) override; - vector getMediaTracks(MediaSource &sender, bool trackReady = true) const override; - void startSendRtp(MediaSource &sender, const string &dst_url, uint16_t dst_port, const string &ssrc, bool is_udp, uint16_t src_port, const function &cb) override; - bool stopSendRtp(MediaSource &sender, const string &ssrc) override; + std::vector getMediaTracks(MediaSource &sender, bool trackReady = true) const override; + void startSendRtp(MediaSource &sender, const std::string &dst_url, uint16_t dst_port, const std::string &ssrc, bool is_udp, uint16_t src_port, const std::function &cb) override; + bool stopSendRtp(MediaSource &sender, const std::string &ssrc) override; private: std::weak_ptr _listener; @@ -134,18 +131,18 @@ class MediaInfo{ public: ~MediaInfo() {} MediaInfo() {} - MediaInfo(const string &url) { parse(url); } - void parse(const string &url); + MediaInfo(const std::string &url) { parse(url); } + void parse(const std::string &url); public: - string _full_url; - string _schema; - string _host; - string _port; - string _vhost; - string _app; - string _streamid; - string _param_strs; + std::string _full_url; + std::string _schema; + std::string _host; + std::string _port; + std::string _vhost; + std::string _app; + std::string _streamid; + std::string _param_strs; }; class BytesSpeed { @@ -191,40 +188,40 @@ private: private: int _speed = 0; size_t _bytes = 0; - Ticker _ticker; + toolkit::Ticker _ticker; }; /** * 媒体源,任何rtsp/rtmp的直播流都源自该对象 */ -class MediaSource: public TrackSource, public enable_shared_from_this { +class MediaSource: public TrackSource, public std::enable_shared_from_this { public: static MediaSource * const NullMediaSource; using Ptr = std::shared_ptr; - using StreamMap = unordered_map >; - using AppStreamMap = unordered_map; - using VhostAppStreamMap = unordered_map; - using SchemaVhostAppStreamMap = unordered_map; + using StreamMap = std::unordered_map >; + using AppStreamMap = std::unordered_map; + using VhostAppStreamMap = std::unordered_map; + using SchemaVhostAppStreamMap = std::unordered_map; - MediaSource(const string &schema, const string &vhost, const string &app, const string &stream_id) ; + MediaSource(const std::string &schema, const std::string &vhost, const std::string &app, const std::string &stream_id) ; virtual ~MediaSource(); ////////////////获取MediaSource相关信息//////////////// // 获取协议类型 - const string& getSchema() const; + const std::string& getSchema() const; // 虚拟主机 - const string& getVhost() const; + const std::string& getVhost() const; // 应用名 - const string& getApp() const; + const std::string& getApp() const; // 流id - const string& getId() const; + const std::string& getId() const; //获取对象所有权 std::shared_ptr getOwnership(); // 获取所有Track - vector getTracks(bool ready = true) const override; + std::vector getTracks(bool ready = true) const override; // 获取流当前时间戳 virtual uint32_t getTimeStamp(TrackType type) { return 0; }; @@ -253,9 +250,9 @@ public: // 获取媒体源类型 MediaOriginType getOriginType() const; // 获取媒体源url或者文件路径 - string getOriginUrl() const; + std::string getOriginUrl() const; // 获取媒体源客户端相关信息 - std::shared_ptr getOriginSock() const; + std::shared_ptr getOriginSock() const; // 拖动进度条 bool seekTo(uint32_t stamp); @@ -268,28 +265,28 @@ public: // 该流观看人数变化 void onReaderChanged(int size); // 开启或关闭录制 - bool setupRecord(Recorder::type type, bool start, const string &custom_path, size_t max_second); + bool setupRecord(Recorder::type type, bool start, const std::string &custom_path, size_t max_second); // 获取录制状态 bool isRecording(Recorder::type type); // 开始发送ps-rtp - void startSendRtp(const string &dst_url, uint16_t dst_port, const string &ssrc, bool is_udp, uint16_t src_port, const function &cb); + void startSendRtp(const std::string &dst_url, uint16_t dst_port, const std::string &ssrc, bool is_udp, uint16_t src_port, const std::function &cb); // 停止发送ps-rtp - bool stopSendRtp(const string &ssrc); + bool stopSendRtp(const std::string &ssrc); ////////////////static方法,查找或生成MediaSource//////////////// // 同步查找流 - static Ptr find(const string &schema, const string &vhost, const string &app, const string &id, bool from_mp4 = false); + static Ptr find(const std::string &schema, const std::string &vhost, const std::string &app, const std::string &id, bool from_mp4 = false); // 忽略类型,同步查找流,可能返回rtmp/rtsp/hls类型 - static Ptr find(const string &vhost, const string &app, const string &stream_id, bool from_mp4 = false); + static Ptr find(const std::string &vhost, const std::string &app, const std::string &stream_id, bool from_mp4 = false); // 异步查找流 - static void findAsync(const MediaInfo &info, const std::shared_ptr &session, const function &cb); + static void findAsync(const MediaInfo &info, const std::shared_ptr &session, const std::function &cb); // 遍历所有流 - static void for_each_media(const function &cb, const string &schema = "", const string &vhost = "", const string &app = "", const string &stream = ""); + static void for_each_media(const std::function &cb, const std::string &schema = "", const std::string &vhost = "", const std::string &app = "", const std::string &stream = ""); // 从mp4文件生成MediaSource - static MediaSource::Ptr createFromMP4(const string &schema, const string &vhost, const string &app, const string &stream, const string &file_path = "", bool check_app = true); + static MediaSource::Ptr createFromMP4(const std::string &schema, const std::string &vhost, const std::string &app, const std::string &stream, const std::string &file_path = "", bool check_app = true); protected: //媒体注册 @@ -305,16 +302,16 @@ protected: BytesSpeed _speed[TrackMax]; private: - atomic_flag _owned { false }; + std::atomic_flag _owned { false }; time_t _create_stamp; - Ticker _ticker; - string _schema; - string _vhost; - string _app; - string _stream_id; + toolkit::Ticker _ticker; + std::string _schema; + std::string _vhost; + std::string _app; + std::string _stream_id; std::weak_ptr _listener; //对象个数统计 - ObjectStatistic _statistic; + toolkit::ObjectStatistic _statistic; }; ///缓存刷新策略类 @@ -333,7 +330,7 @@ private: /// \tparam packet 包类型 /// \tparam policy 刷新缓存策略 /// \tparam packet_list 包缓存类型 -template > > +template > > class PacketCache { public: PacketCache(){ diff --git a/src/Common/MultiMediaSourceMuxer.cpp b/src/Common/MultiMediaSourceMuxer.cpp index f60829da..03f9df96 100644 --- a/src/Common/MultiMediaSourceMuxer.cpp +++ b/src/Common/MultiMediaSourceMuxer.cpp @@ -12,6 +12,9 @@ #include "Common/config.h" #include "MultiMediaSourceMuxer.h" +using namespace std; +using namespace toolkit; + namespace toolkit { StatisticImp(mediakit::MultiMediaSourceMuxer); } diff --git a/src/Common/MultiMediaSourceMuxer.h b/src/Common/MultiMediaSourceMuxer.h index 70853ea3..b811315b 100644 --- a/src/Common/MultiMediaSourceMuxer.h +++ b/src/Common/MultiMediaSourceMuxer.h @@ -35,7 +35,7 @@ public: }; ~MultiMediaSourceMuxer() override = default; - MultiMediaSourceMuxer(const string &vhost, const string &app, const string &stream, float dur_sec = 0.0, + MultiMediaSourceMuxer(const std::string &vhost, const std::string &app, const std::string &stream, float dur_sec = 0.0, bool enable_rtsp = true, bool enable_rtmp = true, bool enable_hls = true, bool enable_mp4 = false); /** @@ -87,7 +87,7 @@ public: * @param custom_path 开启录制时,指定自定义路径 * @return 是否设置成功 */ - bool setupRecord(MediaSource &sender, Recorder::type type, bool start, const string &custom_path, size_t max_second) override; + bool setupRecord(MediaSource &sender, Recorder::type type, bool start, const std::string &custom_path, size_t max_second) override; /** * 获取录制状态 @@ -104,20 +104,20 @@ public: * @param is_udp 是否为udp * @param cb 启动成功或失败回调 */ - void startSendRtp(MediaSource &sender, const string &dst_url, uint16_t dst_port, const string &ssrc, bool is_udp, uint16_t src_port, const function &cb) override; + void startSendRtp(MediaSource &sender, const std::string &dst_url, uint16_t dst_port, const std::string &ssrc, bool is_udp, uint16_t src_port, const std::function &cb) override; /** * 停止ps-rtp发送 * @return 是否成功 */ - bool stopSendRtp(MediaSource &sender, const string &ssrc) override; + bool stopSendRtp(MediaSource &sender, const std::string &ssrc) override; /** * 获取所有Track * @param trackReady 是否筛选过滤未就绪的track * @return 所有Track */ - vector getMediaTracks(MediaSource &sender, bool trackReady = true) const override; + std::vector getMediaTracks(MediaSource &sender, bool trackReady = true) const override; protected: /////////////////////////////////MediaSink override///////////////////////////////// @@ -142,13 +142,13 @@ protected: private: bool _is_enable = false; - Ticker _last_check; + toolkit::Ticker _last_check; Stamp _stamp[2]; std::weak_ptr _track_listener; - function _get_origin_url; + std::function _get_origin_url; #if defined(ENABLE_RTPPROXY) - mutex _rtp_sender_mtx; - unordered_map _rtp_sender; + std::mutex _rtp_sender_mtx; + std::unordered_map _rtp_sender; #endif //ENABLE_RTPPROXY #if defined(ENABLE_MP4) @@ -161,7 +161,7 @@ private: HlsRecorder::Ptr _hls; //对象个数统计 - ObjectStatistic _statistic; + toolkit::ObjectStatistic _statistic; }; }//namespace mediakit diff --git a/src/Common/Parser.cpp b/src/Common/Parser.cpp index 14b739d2..669b7798 100644 --- a/src/Common/Parser.cpp +++ b/src/Common/Parser.cpp @@ -10,6 +10,9 @@ #include "Parser.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ string FindField(const char* buf, const char* start, const char *end ,size_t bufSize) { diff --git a/src/Common/Parser.h b/src/Common/Parser.h index 547b6c45..b0c53bb2 100644 --- a/src/Common/Parser.h +++ b/src/Common/Parser.h @@ -15,26 +15,23 @@ #include #include "Util/util.h" -using namespace std; -using namespace toolkit; - namespace mediakit { -string FindField(const char *buf, const char *start, const char *end, size_t bufSize = 0); +std::string FindField(const char *buf, const char *start, const char *end, size_t bufSize = 0); struct StrCaseCompare { - bool operator()(const string &__x, const string &__y) const { + bool operator()(const std::string &__x, const std::string &__y) const { return strcasecmp(__x.data(), __y.data()) < 0; } }; -class StrCaseMap : public multimap { +class StrCaseMap : public std::multimap { public: - using Super = multimap; + using Super = multimap; StrCaseMap() = default; ~StrCaseMap() = default; - string &operator[](const string &k) { + std::string &operator[](const std::string &k) { auto it = find(k); if (it == end()) { it = Super::emplace(k, ""); @@ -43,7 +40,7 @@ public: } template - void emplace(const string &k, V &&v) { + void emplace(const std::string &k, V &&v) { auto it = find(k); if (it != end()) { return; @@ -52,7 +49,7 @@ public: } template - void emplace_force(const string k, V &&v) { + void emplace_force(const std::string k, V &&v) { Super::emplace(k, std::forward(v)); } }; @@ -67,34 +64,34 @@ public: void Parse(const char *buf); //获取命令字 - const string &Method() const; + const std::string &Method() const; //获取中间url,不包含?后面的参数 - const string &Url() const; + const std::string &Url() const; //获取中间url,包含?后面的参数 - string FullUrl() const; + std::string FullUrl() const; //获取命令协议名 - const string &Tail() const; + const std::string &Tail() const; //根据header key名,获取请求header value值 - const string &operator[](const char *name) const; + const std::string &operator[](const char *name) const; //获取http body或sdp - const string &Content() const; + const std::string &Content() const; //清空,为了重用 void Clear(); //获取?后面的参数 - const string &Params() const; + const std::string &Params() const; //重新设置url - void setUrl(string url); + void setUrl(std::string url); //重新设置content - void setContent(string content); + void setContent(std::string content); //获取header列表 StrCaseMap &getHeader() const; @@ -103,15 +100,15 @@ public: StrCaseMap &getUrlArgs() const; //解析?后面的参数 - static StrCaseMap parseArgs(const string &str, const char *pair_delim = "&", const char *key_delim = "="); + static StrCaseMap parseArgs(const std::string &str, const char *pair_delim = "&", const char *key_delim = "="); private: - string _strMethod; - string _strUrl; - string _strTail; - string _strContent; - string _strNull; - string _params; + std::string _strMethod; + std::string _strUrl; + std::string _strTail; + std::string _strContent; + std::string _strNull; + std::string _params; mutable StrCaseMap _mapHeaders; mutable StrCaseMap _mapUrlArgs; }; diff --git a/src/Common/Stamp.cpp b/src/Common/Stamp.cpp index d0729b52..29ee3d89 100644 --- a/src/Common/Stamp.cpp +++ b/src/Common/Stamp.cpp @@ -16,6 +16,8 @@ #define MAX_CTS 500 #define ABS(x) ((x) > 0 ? (x) : (-x)) +using namespace toolkit; + namespace mediakit { int64_t DeltaStamp::deltaStamp(int64_t stamp) { diff --git a/src/Common/Stamp.h b/src/Common/Stamp.h index 1f91b596..85c181fd 100644 --- a/src/Common/Stamp.h +++ b/src/Common/Stamp.h @@ -14,7 +14,6 @@ #include #include #include "Util/TimeTicker.h" -using namespace toolkit; namespace mediakit { @@ -87,7 +86,7 @@ private: int64_t _last_dts_in = 0; int64_t _last_dts_out = 0; int64_t _last_pts_out = 0; - SmoothTicker _ticker; + toolkit::SmoothTicker _ticker; bool _playback = false; Stamp *_sync_master = nullptr; }; @@ -111,7 +110,7 @@ private: size_t _frames_since_last_max_pts = 0; size_t _sorter_max_size = 0; size_t _count_sorter_max_size = 0; - set _pts_sorter; + std::set _pts_sorter; }; class NtpStamp { diff --git a/src/Common/config.cpp b/src/Common/config.cpp index 3256402d..106dd9c0 100644 --- a/src/Common/config.cpp +++ b/src/Common/config.cpp @@ -15,6 +15,7 @@ #include "Util/onceToken.h" #include "Util/NoticeCenter.h" +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Common/config.h b/src/Common/config.h index d2cb9ef5..8793e921 100644 --- a/src/Common/config.h +++ b/src/Common/config.h @@ -18,9 +18,6 @@ #include "Util/NoticeCenter.h" #include "macros.h" -using namespace std; -using namespace toolkit; - namespace mediakit { //加载配置文件,如果配置文件不存在,那么会导出默认配置并生成配置文件 @@ -34,93 +31,93 @@ bool loadIniConfig(const char *ini_path = nullptr); namespace Broadcast { //注册或反注册MediaSource事件广播 -extern const string kBroadcastMediaChanged; +extern const std::string kBroadcastMediaChanged; #define BroadcastMediaChangedArgs const bool &bRegist, MediaSource &sender //录制mp4文件成功后广播 -extern const string kBroadcastRecordMP4; +extern const std::string kBroadcastRecordMP4; #define BroadcastRecordMP4Args const RecordInfo &info // 录制 ts 文件后广播 -extern const string kBroadcastRecordTs; +extern const std::string kBroadcastRecordTs; #define BroadcastRecordTsArgs const RecordInfo &info //收到http api请求广播 -extern const string kBroadcastHttpRequest; +extern const std::string kBroadcastHttpRequest; #define BroadcastHttpRequestArgs const Parser &parser,const HttpSession::HttpResponseInvoker &invoker,bool &consumed,SockInfo &sender //在http文件服务器中,收到http访问文件或目录的广播,通过该事件控制访问http目录的权限 -extern const string kBroadcastHttpAccess; -#define BroadcastHttpAccessArgs const Parser &parser,const string &path,const bool &is_dir,const HttpSession::HttpAccessPathInvoker &invoker,SockInfo &sender +extern const std::string kBroadcastHttpAccess; +#define BroadcastHttpAccessArgs const Parser &parser,const std::string &path,const bool &is_dir,const HttpSession::HttpAccessPathInvoker &invoker,SockInfo &sender //在http文件服务器中,收到http访问文件或目录前的广播,通过该事件可以控制http url到文件路径的映射 //在该事件中通过自行覆盖path参数,可以做到譬如根据虚拟主机或者app选择不同http根目录的目的 -extern const string kBroadcastHttpBeforeAccess; -#define BroadcastHttpBeforeAccessArgs const Parser &parser,string &path,SockInfo &sender +extern const std::string kBroadcastHttpBeforeAccess; +#define BroadcastHttpBeforeAccessArgs const Parser &parser, std::string &path, SockInfo &sender //该流是否需要认证?是的话调用invoker并传入realm,否则传入空的realm.如果该事件不监听则不认证 -extern const string kBroadcastOnGetRtspRealm; +extern const std::string kBroadcastOnGetRtspRealm; #define BroadcastOnGetRtspRealmArgs const MediaInfo &args,const RtspSession::onGetRealm &invoker,SockInfo &sender //请求认证用户密码事件,user_name为用户名,must_no_encrypt如果为true,则必须提供明文密码(因为此时是base64认证方式),否则会导致认证失败 //获取到密码后请调用invoker并输入对应类型的密码和密码类型,invoker执行时会匹配密码 -extern const string kBroadcastOnRtspAuth; -#define BroadcastOnRtspAuthArgs const MediaInfo &args,const string &realm,const string &user_name,const bool &must_no_encrypt,const RtspSession::onAuth &invoker,SockInfo &sender +extern const std::string kBroadcastOnRtspAuth; +#define BroadcastOnRtspAuthArgs const MediaInfo &args,const std::string &realm,const std::string &user_name,const bool &must_no_encrypt,const RtspSession::onAuth &invoker,SockInfo &sender //推流鉴权结果回调对象 //如果errMessage为空则代表鉴权成功 //enableHls: 是否允许转换hls //enableMP4: 是否运行MP4录制 -typedef std::function PublishAuthInvoker; +typedef std::function PublishAuthInvoker; //收到rtsp/rtmp推流事件广播,通过该事件控制推流鉴权 -extern const string kBroadcastMediaPublish; +extern const std::string kBroadcastMediaPublish; #define BroadcastMediaPublishArgs const MediaInfo &args,const Broadcast::PublishAuthInvoker &invoker,SockInfo &sender //播放鉴权结果回调对象 //如果errMessage为空则代表鉴权成功 -typedef std::function AuthInvoker; +typedef std::function AuthInvoker; //播放rtsp/rtmp/http-flv事件广播,通过该事件控制播放鉴权 -extern const string kBroadcastMediaPlayed; +extern const std::string kBroadcastMediaPlayed; #define BroadcastMediaPlayedArgs const MediaInfo &args,const Broadcast::AuthInvoker &invoker,SockInfo &sender //shell登录鉴权 -extern const string kBroadcastShellLogin; -#define BroadcastShellLoginArgs const string &user_name,const string &passwd,const Broadcast::AuthInvoker &invoker,SockInfo &sender +extern const std::string kBroadcastShellLogin; +#define BroadcastShellLoginArgs const std::string &user_name,const std::string &passwd,const Broadcast::AuthInvoker &invoker,SockInfo &sender //停止rtsp/rtmp/http-flv会话后流量汇报事件广播 -extern const string kBroadcastFlowReport; +extern const std::string kBroadcastFlowReport; #define BroadcastFlowReportArgs const MediaInfo &args,const uint64_t &totalBytes,const uint64_t &totalDuration,const bool &isPlayer, SockInfo &sender //未找到流后会广播该事件,请在监听该事件后去拉流或其他方式产生流,这样就能按需拉流了 -extern const string kBroadcastNotFoundStream; -#define BroadcastNotFoundStreamArgs const MediaInfo &args,SockInfo &sender, const function &closePlayer +extern const std::string kBroadcastNotFoundStream; +#define BroadcastNotFoundStreamArgs const MediaInfo &args, SockInfo &sender, const std::function &closePlayer //某个流无人消费时触发,目的为了实现无人观看时主动断开拉流等业务逻辑 -extern const string kBroadcastStreamNoneReader; +extern const std::string kBroadcastStreamNoneReader; #define BroadcastStreamNoneReaderArgs MediaSource &sender //更新配置文件事件广播,执行loadIniConfig函数加载配置文件成功后会触发该广播 -extern const string kBroadcastReloadConfig; +extern const std::string kBroadcastReloadConfig; #define BroadcastReloadConfigArgs void #define ReloadConfigTag ((void *)(0xFF)) -#define RELOAD_KEY(arg,key) \ - do { \ - decltype(arg) arg##_tmp = mINI::Instance()[key]; \ - if (arg == arg##_tmp) { \ - return; \ - } \ - arg = arg##_tmp; \ - InfoL << "reload config:" << key << "=" << arg; \ +#define RELOAD_KEY(arg,key) \ + do { \ + decltype(arg) arg##_tmp = toolkit::mINI::Instance()[key]; \ + if (arg == arg##_tmp) { \ + return; \ + } \ + arg = arg##_tmp; \ + InfoL << "reload config:" << key << "=" << arg; \ } while(0) //监听某个配置发送变更 #define LISTEN_RELOAD_KEY(arg, key, ...) \ do { \ - static onceToken s_token_listen([](){ \ - NoticeCenter::Instance().addListener(ReloadConfigTag, \ + static toolkit::onceToken s_token_listen([](){ \ + toolkit::NoticeCenter::Instance().addListener(ReloadConfigTag, \ Broadcast::kBroadcastReloadConfig,[](BroadcastReloadConfigArgs) { \ __VA_ARGS__; \ }); \ @@ -128,23 +125,23 @@ extern const string kBroadcastReloadConfig; } while(0) #define GET_CONFIG(type, arg, key) \ - static type arg = mINI::Instance()[key]; \ + static type arg = toolkit::mINI::Instance()[key]; \ LISTEN_RELOAD_KEY(arg, key, { \ RELOAD_KEY(arg, key); \ }); -#define GET_CONFIG_FUNC(type, arg, key, ...) \ - static type arg; \ - do { \ - static onceToken s_token_set([](){ \ - static auto lam = __VA_ARGS__ ; \ - static auto arg##_str = mINI::Instance()[key]; \ - arg = lam(arg##_str); \ - LISTEN_RELOAD_KEY(arg, key, { \ - RELOAD_KEY(arg##_str, key); \ - arg = lam(arg##_str); \ - }); \ - }); \ +#define GET_CONFIG_FUNC(type, arg, key, ...) \ + static type arg; \ + do { \ + static toolkit::onceToken s_token_set([](){ \ + static auto lam = __VA_ARGS__ ; \ + static auto arg##_str = toolkit::mINI::Instance()[key]; \ + arg = lam(arg##_str); \ + LISTEN_RELOAD_KEY(arg, key, { \ + RELOAD_KEY(arg##_str, key); \ + arg = lam(arg##_str); \ + }); \ + }); \ } while(0) } //namespace Broadcast @@ -152,168 +149,168 @@ extern const string kBroadcastReloadConfig; ////////////通用配置/////////// namespace General{ //每个流媒体服务器的ID(GUID) -extern const string kMediaServerId; +extern const std::string kMediaServerId; //流量汇报事件流量阈值,单位KB,默认1MB -extern const string kFlowThreshold; +extern const std::string kFlowThreshold; //流无人观看并且超过若干时间后才触发kBroadcastStreamNoneReader事件 //默认连续5秒无人观看然后触发kBroadcastStreamNoneReader事件 -extern const string kStreamNoneReaderDelayMS; +extern const std::string kStreamNoneReaderDelayMS; //等待流注册超时时间,收到播放器后请求后,如果未找到相关流,服务器会等待一定时间, //如果在这个时间内,相关流注册上了,那么服务器会立即响应播放器播放成功, //否则会最多等待kMaxStreamWaitTimeMS毫秒,然后响应播放器播放失败 -extern const string kMaxStreamWaitTimeMS; +extern const std::string kMaxStreamWaitTimeMS; //是否启动虚拟主机 -extern const string kEnableVhost; +extern const std::string kEnableVhost; //拉流代理时是否添加静音音频 -extern const string kAddMuteAudio; +extern const std::string kAddMuteAudio; //拉流代理时如果断流再重连成功是否删除前一次的媒体流数据,如果删除将重新开始, //如果不删除将会接着上一次的数据继续写(录制hls/mp4时会继续在前一个文件后面写) -extern const string kResetWhenRePlay; +extern const std::string kResetWhenRePlay; //是否默认推流时转换成hls,hook接口(on_publish)中可以覆盖该设置 -extern const string kPublishToHls ; +extern const std::string kPublishToHls ; //是否默认推流时mp4录像,hook接口(on_publish)中可以覆盖该设置 -extern const string kPublishToMP4 ; +extern const std::string kPublishToMP4 ; //合并写缓存大小(单位毫秒),合并写指服务器缓存一定的数据后才会一次性写入socket,这样能提高性能,但是会提高延时 //开启后会同时关闭TCP_NODELAY并开启MSG_MORE -extern const string kMergeWriteMS ; +extern const std::string kMergeWriteMS ; //全局的时间戳覆盖开关,在转协议时,对frame进行时间戳覆盖 -extern const string kModifyStamp; +extern const std::string kModifyStamp; //按需转协议的开关 -extern const string kHlsDemand; -extern const string kRtspDemand; -extern const string kRtmpDemand; -extern const string kTSDemand; -extern const string kFMP4Demand; +extern const std::string kHlsDemand; +extern const std::string kRtspDemand; +extern const std::string kRtmpDemand; +extern const std::string kTSDemand; +extern const std::string kFMP4Demand; //转协议是否全局开启或忽略音频 -extern const string kEnableAudio; +extern const std::string kEnableAudio; //最多等待未初始化的Track 10秒,超时之后会忽略未初始化的Track -extern const string kWaitTrackReadyMS; +extern const std::string kWaitTrackReadyMS; //如果直播流只有单Track,最多等待3秒,超时后未收到其他Track的数据,则认为是单Track //如果协议元数据有声明特定track数,那么无此等待时间 -extern const string kWaitAddTrackMS; +extern const std::string kWaitAddTrackMS; //如果track未就绪,我们先缓存帧数据,但是有最大个数限制(100帧时大约4秒),防止内存溢出 -extern const string kUnreadyFrameCache; +extern const std::string kUnreadyFrameCache; //推流断开后可以在超时时间内重新连接上继续推流,这样播放器会接着播放。 //置0关闭此特性(推流断开会导致立即断开播放器) -extern const string kContinuePushMS; +extern const std::string kContinuePushMS; }//namespace General ////////////HTTP配置/////////// namespace Http { //http 文件发送缓存大小 -extern const string kSendBufSize; +extern const std::string kSendBufSize; //http 最大请求字节数 -extern const string kMaxReqSize; +extern const std::string kMaxReqSize; //http keep-alive秒数 -extern const string kKeepAliveSecond; +extern const std::string kKeepAliveSecond; //http 字符编码 -extern const string kCharSet; +extern const std::string kCharSet; //http 服务器根目录 -extern const string kRootPath; +extern const std::string kRootPath; //http 服务器虚拟目录 虚拟目录名和文件路径使用","隔开,多个配置路径间用";"隔开,例如 path_d,d:/record;path_e,e:/record -extern const string kVirtualPath; +extern const std::string kVirtualPath; //http 404错误提示内容 -extern const string kNotFound; +extern const std::string kNotFound; //是否显示文件夹菜单 -extern const string kDirMenu; +extern const std::string kDirMenu; }//namespace Http ////////////SHELL配置/////////// namespace Shell { -extern const string kMaxReqSize; +extern const std::string kMaxReqSize; } //namespace Shell ////////////RTSP服务器配置/////////// namespace Rtsp { //是否优先base64方式认证?默认Md5方式认证 -extern const string kAuthBasic; +extern const std::string kAuthBasic; //握手超时时间,默认15秒 -extern const string kHandshakeSecond; +extern const std::string kHandshakeSecond; //维持链接超时时间,默认15秒 -extern const string kKeepAliveSecond; +extern const std::string kKeepAliveSecond; //rtsp拉流代理是否直接代理 //直接代理后支持任意编码格式,但是会导致GOP缓存无法定位到I帧,可能会导致开播花屏 //并且如果是tcp方式拉流,如果rtp大于mtu会导致无法使用udp方式代理 //假定您的拉流源地址不是264或265或AAC,那么你可以使用直接代理的方式来支持rtsp代理 //默认开启rtsp直接代理,rtmp由于没有这些问题,是强制开启直接代理的 -extern const string kDirectProxy; +extern const std::string kDirectProxy; } //namespace Rtsp ////////////RTMP服务器配置/////////// namespace Rtmp { //rtmp推流时间戳覆盖开关 -extern const string kModifyStamp; +extern const std::string kModifyStamp; //握手超时时间,默认15秒 -extern const string kHandshakeSecond; +extern const std::string kHandshakeSecond; //维持链接超时时间,默认15秒 -extern const string kKeepAliveSecond; +extern const std::string kKeepAliveSecond; } //namespace RTMP ////////////RTP配置/////////// namespace Rtp { //RTP打包最大MTU,公网情况下更小 -extern const string kVideoMtuSize; +extern const std::string kVideoMtuSize; //RTP打包最大MTU,公网情况下更小 -extern const string kAudioMtuSize; +extern const std::string kAudioMtuSize; //rtp包最大长度限制, 单位KB -extern const string kRtpMaxSize; +extern const std::string kRtpMaxSize; } //namespace Rtsp ////////////组播配置/////////// namespace MultiCast { //组播分配起始地址 -extern const string kAddrMin; +extern const std::string kAddrMin; //组播分配截止地址 -extern const string kAddrMax; +extern const std::string kAddrMax; //组播TTL -extern const string kUdpTTL; +extern const std::string kUdpTTL; } //namespace MultiCast ////////////录像配置/////////// namespace Record { //查看录像的应用名称 -extern const string kAppName; +extern const std::string kAppName; //每次流化MP4文件的时长,单位毫秒 -extern const string kSampleMS; +extern const std::string kSampleMS; //MP4文件录制大小,默认一个小时 -extern const string kFileSecond; +extern const std::string kFileSecond; //录制文件路径 -extern const string kFilePath; +extern const std::string kFilePath; //mp4文件写缓存大小 -extern const string kFileBufSize; +extern const std::string kFileBufSize; //mp4录制完成后是否进行二次关键帧索引写入头部 -extern const string kFastStart; +extern const std::string kFastStart; //mp4文件是否重头循环读取 -extern const string kFileRepeat; +extern const std::string kFileRepeat; } //namespace Record ////////////HLS相关配置/////////// namespace Hls { //HLS切片时长,单位秒 -extern const string kSegmentDuration; +extern const std::string kSegmentDuration; //m3u8文件中HLS切片个数,如果设置为0,则不删除切片,而是保存为点播 -extern const string kSegmentNum; +extern const std::string kSegmentNum; //HLS切片从m3u8文件中移除后,继续保留在磁盘上的个数 -extern const string kSegmentRetain; +extern const std::string kSegmentRetain; //HLS文件写缓存大小 -extern const string kFileBufSize; +extern const std::string kFileBufSize; //录制文件路径 -extern const string kFilePath; +extern const std::string kFilePath; // 是否广播 ts 切片完成通知 -extern const string kBroadcastRecordTs; +extern const std::string kBroadcastRecordTs; //hls直播文件删除延时,单位秒 -extern const string kDeleteDelaySec; +extern const std::string kDeleteDelaySec; } //namespace Hls ////////////Rtp代理相关配置/////////// namespace RtpProxy { //rtp调试数据保存目录,置空则不生成 -extern const string kDumpDir; +extern const std::string kDumpDir; //rtp接收超时时间 -extern const string kTimeoutSec; +extern const std::string kTimeoutSec; } //namespace RtpProxy /** @@ -323,26 +320,26 @@ extern const string kTimeoutSec; */ namespace Client { //指定网卡ip -extern const string kNetAdapter; +extern const std::string kNetAdapter; //设置rtp传输类型,可选项有0(tcp,默认)、1(udp)、2(组播) //设置方法:player[PlayerBase::kRtpType] = 0/1/2; -extern const string kRtpType; +extern const std::string kRtpType; //rtsp认证用户名 -extern const string kRtspUser; +extern const std::string kRtspUser; //rtsp认证用用户密码,可以是明文也可以是md5,md5密码生成方式 md5(username:realm:password) -extern const string kRtspPwd; +extern const std::string kRtspPwd; //rtsp认证用用户密码是否为md5类型 -extern const string kRtspPwdIsMD5; +extern const std::string kRtspPwdIsMD5; //握手超时时间,默认10,000 毫秒 -extern const string kTimeoutMS; +extern const std::string kTimeoutMS; //rtp/rtmp包接收超时时间,默认5000秒 -extern const string kMediaTimeoutMS; +extern const std::string kMediaTimeoutMS; //rtsp/rtmp心跳时间,默认5000毫秒 -extern const string kBeatIntervalMS; +extern const std::string kBeatIntervalMS; //是否为性能测试模式,性能测试模式开启后不会解析rtp或rtmp包 -extern const string kBenchmarkMode; +extern const std::string kBenchmarkMode; //播放器在触发播放成功事件时,是否等待所有track ready时再回调 -extern const string kWaitTrackReady; +extern const std::string kWaitTrackReady; } } // namespace mediakit diff --git a/src/Extension/AAC.cpp b/src/Extension/AAC.cpp index bfe4c9db..f06ae715 100644 --- a/src/Extension/AAC.cpp +++ b/src/Extension/AAC.cpp @@ -13,6 +13,9 @@ #include "mpeg4-aac.h" #endif +using namespace std; +using namespace toolkit; + namespace mediakit{ #ifndef ENABLE_MP4 diff --git a/src/Extension/AAC.h b/src/Extension/AAC.h index d467566c..ad7479f6 100644 --- a/src/Extension/AAC.h +++ b/src/Extension/AAC.h @@ -17,10 +17,10 @@ namespace mediakit{ -string makeAacConfig(const uint8_t *hex, size_t length); +std::string makeAacConfig(const uint8_t *hex, size_t length); int getAacFrameLength(const uint8_t *hex, size_t length); -int dumpAacConfig(const string &config, size_t length, uint8_t *out, size_t out_size); -bool parseAacConfig(const string &config, int &samplerate, int &channels); +int dumpAacConfig(const std::string &config, size_t length, uint8_t *out, size_t out_size); +bool parseAacConfig(const std::string &config, int &samplerate, int &channels); /** * aac音频通道 @@ -39,12 +39,12 @@ public: * 构造aac类型的媒体 * @param aac_cfg aac配置信息 */ - AACTrack(const string &aac_cfg); + AACTrack(const std::string &aac_cfg); /** * 获取aac 配置信息 */ - const string &getAacCfg() const; + const std::string &getAacCfg() const; bool ready() override; CodecId getCodecId() const override; @@ -60,7 +60,7 @@ private: bool inputFrame_l(const Frame::Ptr &frame); private: - string _cfg; + std::string _cfg; int _channel = 0; int _sampleRate = 0; int _sampleBit = 16; diff --git a/src/Extension/AACRtmp.cpp b/src/Extension/AACRtmp.cpp index 7012b73d..1454a727 100644 --- a/src/Extension/AACRtmp.cpp +++ b/src/Extension/AACRtmp.cpp @@ -11,7 +11,10 @@ #include "AACRtmp.h" #include "Rtmp/Rtmp.h" -namespace mediakit{ +using namespace std; +using namespace toolkit; + +namespace mediakit { static string getAacCfg(const RtmpPacket &thiz) { string ret; diff --git a/src/Extension/AACRtmp.h b/src/Extension/AACRtmp.h index 56aa3573..41de8805 100644 --- a/src/Extension/AACRtmp.h +++ b/src/Extension/AACRtmp.h @@ -40,7 +40,7 @@ private: void onGetAAC(const char *data, size_t len, uint32_t stamp); private: - string _aac_cfg; + std::string _aac_cfg; }; @@ -77,7 +77,7 @@ private: private: uint8_t _audio_flv_flags; AACTrack::Ptr _track; - string _aac_cfg; + std::string _aac_cfg; }; }//namespace mediakit diff --git a/src/Extension/AACRtp.cpp b/src/Extension/AACRtp.cpp index 58c67934..c9293fc1 100644 --- a/src/Extension/AACRtp.cpp +++ b/src/Extension/AACRtp.cpp @@ -60,7 +60,7 @@ void AACRtpEncoder::makeAACRtp(const void *data, size_t len, bool mark, uint32_t ///////////////////////////////////////////////////////////////////////////////////// AACRtpDecoder::AACRtpDecoder(const Track::Ptr &track) { - auto aacTrack = dynamic_pointer_cast(track); + auto aacTrack = std::dynamic_pointer_cast(track); if (!aacTrack || !aacTrack->ready()) { WarnL << "该aac track无效!"; } else { diff --git a/src/Extension/AACRtp.h b/src/Extension/AACRtp.h index 0a774b4a..1efb2e24 100644 --- a/src/Extension/AACRtp.h +++ b/src/Extension/AACRtp.h @@ -44,7 +44,7 @@ private: private: uint32_t _last_dts = 0; - string _aac_cfg; + std::string _aac_cfg; FrameImp::Ptr _frame; }; diff --git a/src/Extension/CommonRtp.cpp b/src/Extension/CommonRtp.cpp index 45938ddb..64b59ea5 100644 --- a/src/Extension/CommonRtp.cpp +++ b/src/Extension/CommonRtp.cpp @@ -10,6 +10,8 @@ #include "CommonRtp.h" +using namespace mediakit; + CommonRtpDecoder::CommonRtpDecoder(CodecId codec, size_t max_frame_size ){ _codec = codec; _max_frame_size = max_frame_size; diff --git a/src/Extension/Factory.cpp b/src/Extension/Factory.cpp index 9ba2168b..d7757ecb 100644 --- a/src/Extension/Factory.cpp +++ b/src/Extension/Factory.cpp @@ -24,6 +24,8 @@ #include "L16.h" #include "Common/Parser.h" +using namespace std; + namespace mediakit{ Track::Ptr Factory::getTrackBySdp(const SdpTrack::Ptr &track) { diff --git a/src/Extension/Factory.h b/src/Extension/Factory.h index d8265f0b..3e5684f9 100644 --- a/src/Extension/Factory.h +++ b/src/Extension/Factory.h @@ -17,9 +17,6 @@ #include "Rtsp/RtpCodec.h" #include "Rtmp/RtmpCodec.h" -using namespace std; -using namespace toolkit; - namespace mediakit{ class Factory { diff --git a/src/Extension/Frame.h b/src/Extension/Frame.h index 3e865750..46b1b926 100644 --- a/src/Extension/Frame.h +++ b/src/Extension/Frame.h @@ -16,9 +16,6 @@ #include "Util/RingBuffer.h" #include "Network/Socket.h" -using namespace std; -using namespace toolkit; - namespace mediakit{ typedef enum { @@ -53,7 +50,7 @@ typedef enum { /** * 字符串转媒体类型转 */ -TrackType getTrackType(const string &str); +TrackType getTrackType(const std::string &str); /** * 媒体类型转字符串 @@ -65,7 +62,7 @@ const char* getTrackString(TrackType type); * @param str * @return */ -CodecId getCodecId(const string &str); +CodecId getCodecId(const std::string &str); /** * 获取编码器名称 @@ -106,7 +103,7 @@ public: /** * 帧类型的抽象接口 */ -class Frame : public Buffer, public CodecInfo { +class Frame : public toolkit::Buffer, public CodecInfo { public: typedef std::shared_ptr Ptr; virtual ~Frame(){} @@ -171,7 +168,7 @@ public: private: //对象个数统计 - ObjectStatistic _statistic; + toolkit::ObjectStatistic _statistic; }; class FrameImp : public Frame { @@ -233,14 +230,14 @@ public: uint32_t _dts = 0; uint32_t _pts = 0; size_t _prefix_size = 0; - BufferLikeString _buffer; + toolkit::BufferLikeString _buffer; private: //对象个数统计 - ObjectStatistic _statistic; + toolkit::ObjectStatistic _statistic; protected: - friend class ResourcePool_l; + friend class toolkit::ResourcePool_l; FrameImp() = default; }; @@ -323,7 +320,7 @@ public: */ void addDelegate(const FrameWriterInterface::Ptr &delegate){ //_delegates_write可能多线程同时操作 - lock_guard lck(_mtx); + std::lock_guard lck(_mtx); _delegates_write.emplace(delegate.get(),delegate); _need_update = true; } @@ -333,7 +330,7 @@ public: */ void delDelegate(FrameWriterInterface *ptr){ //_delegates_write可能多线程同时操作 - lock_guard lck(_mtx); + std::lock_guard lck(_mtx); _delegates_write.erase(ptr); _need_update = true; } @@ -344,7 +341,7 @@ public: bool inputFrame(const Frame::Ptr &frame) override{ if(_need_update){ //发现代理列表发生变化了,这里同步一次 - lock_guard lck(_mtx); + std::lock_guard lck(_mtx); _delegates_read = _delegates_write; _need_update = false; } @@ -366,9 +363,9 @@ public: return _delegates_write.size(); } private: - mutex _mtx; - map _delegates_read; - map _delegates_write; + std::mutex _mtx; + std::map _delegates_read; + std::map _delegates_write; bool _need_update = false; }; @@ -463,7 +460,7 @@ public: * @param prefix 帧前缀长度 * @param offset buffer有效数据偏移量 */ - FrameWrapper(const Buffer::Ptr &buf, uint32_t dts, uint32_t pts, size_t prefix, size_t offset) : Parent(buf->data() + offset, buf->size() - offset, dts, pts, prefix){ + FrameWrapper(const toolkit::Buffer::Ptr &buf, uint32_t dts, uint32_t pts, size_t prefix, size_t offset) : Parent(buf->data() + offset, buf->size() - offset, dts, pts, prefix){ _buf = buf; } @@ -476,7 +473,7 @@ public: * @param offset buffer有效数据偏移量 * @param codec 帧类型 */ - FrameWrapper(const Buffer::Ptr &buf, uint32_t dts, uint32_t pts, size_t prefix, size_t offset, CodecId codec) : Parent(codec, buf->data() + offset, buf->size() - offset, dts, pts, prefix){ + FrameWrapper(const toolkit::Buffer::Ptr &buf, uint32_t dts, uint32_t pts, size_t prefix, size_t offset, CodecId codec) : Parent(codec, buf->data() + offset, buf->size() - offset, dts, pts, prefix){ _buf = buf; } @@ -488,7 +485,7 @@ public: } private: - Buffer::Ptr _buf; + toolkit::Buffer::Ptr _buf; }; /** @@ -496,7 +493,7 @@ private: */ class FrameMerger { public: - using onOutput = function; + using onOutput = std::function; using Ptr = std::shared_ptr; enum { none = 0, @@ -508,16 +505,16 @@ public: ~FrameMerger() = default; void clear(); - bool inputFrame(const Frame::Ptr &frame, const onOutput &cb, BufferLikeString *buffer = nullptr); + bool inputFrame(const Frame::Ptr &frame, const onOutput &cb, toolkit::BufferLikeString *buffer = nullptr); private: bool willFlush(const Frame::Ptr &frame) const; - void doMerge(BufferLikeString &buffer, const Frame::Ptr &frame) const; + void doMerge(toolkit::BufferLikeString &buffer, const Frame::Ptr &frame) const; private: int _type; bool _have_decode_able_frame = false; - List _frame_cache; + toolkit::List _frame_cache; }; }//namespace mediakit diff --git a/src/Extension/G711.cpp b/src/Extension/G711.cpp index c883a973..6f505bef 100644 --- a/src/Extension/G711.cpp +++ b/src/Extension/G711.cpp @@ -10,6 +10,9 @@ #include "G711.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ /** diff --git a/src/Extension/H264.cpp b/src/Extension/H264.cpp index 7a7f07c0..df113924 100644 --- a/src/Extension/H264.cpp +++ b/src/Extension/H264.cpp @@ -12,6 +12,7 @@ #include "SPSParser.h" #include "Util/logger.h" using namespace toolkit; +using namespace std; namespace mediakit{ diff --git a/src/Extension/H264.h b/src/Extension/H264.h index fb39bcff..13b6096d 100644 --- a/src/Extension/H264.h +++ b/src/Extension/H264.h @@ -14,12 +14,12 @@ #include "Frame.h" #include "Track.h" #include "Util/base64.h" + #define H264_TYPE(v) ((uint8_t)(v) & 0x1F) -using namespace toolkit; namespace mediakit{ -bool getAVCInfo(const string &strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); +bool getAVCInfo(const std::string &strSps,int &iVideoWidth, int &iVideoHeight, float &iVideoFps); void splitH264(const char *ptr, size_t len, size_t prefix, const std::function &cb); size_t prefixSize(const char *ptr, size_t len); @@ -27,7 +27,7 @@ template class H264FrameHelper : public Parent{ public: friend class FrameImp; - friend class ResourcePool_l; + friend class toolkit::ResourcePool_l; using Ptr = std::shared_ptr; enum { @@ -108,7 +108,7 @@ public: * @param sps_prefix_len 264头长度,可以为3个或4个字节,一般为0x00 00 00 01 * @param pps_prefix_len 264头长度,可以为3个或4个字节,一般为0x00 00 00 01 */ - H264Track(const string &sps,const string &pps,int sps_prefix_len = 4,int pps_prefix_len = 4); + H264Track(const std::string &sps,const std::string &pps,int sps_prefix_len = 4,int pps_prefix_len = 4); /** * 构造h264类型的媒体 @@ -120,8 +120,8 @@ public: /** * 返回不带0x00 00 00 01头的sps/pps */ - const string &getSps() const; - const string &getPps() const; + const std::string &getSps() const; + const std::string &getPps() const; bool ready() override; CodecId getCodecId() const override; @@ -142,8 +142,8 @@ private: int _width = 0; int _height = 0; float _fps = 0; - string _sps; - string _pps; + std::string _sps; + std::string _pps; }; }//namespace mediakit diff --git a/src/Extension/H264Rtmp.cpp b/src/Extension/H264Rtmp.cpp index cb26a9ef..8570983c 100644 --- a/src/Extension/H264Rtmp.cpp +++ b/src/Extension/H264Rtmp.cpp @@ -10,7 +10,11 @@ #include "Rtmp/utils.h" #include "H264Rtmp.h" -namespace mediakit{ + +using namespace std; +using namespace toolkit; + +namespace mediakit { H264RtmpDecoder::H264RtmpDecoder() { _h264frame = obtainFrame(); diff --git a/src/Extension/H264Rtmp.h b/src/Extension/H264Rtmp.h index fc69c3fe..c38e667b 100644 --- a/src/Extension/H264Rtmp.h +++ b/src/Extension/H264Rtmp.h @@ -15,7 +15,6 @@ #include "Extension/Track.h" #include "Util/ResourcePool.h" #include "Extension/H264.h" -using namespace toolkit; namespace mediakit{ /** @@ -45,8 +44,8 @@ protected: protected: H264Frame::Ptr _h264frame; - string _sps; - string _pps; + std::string _sps; + std::string _pps; }; /** diff --git a/src/Extension/H264Rtp.h b/src/Extension/H264Rtp.h index 1dc9c39b..cd81abe0 100644 --- a/src/Extension/H264Rtp.h +++ b/src/Extension/H264Rtp.h @@ -15,7 +15,6 @@ #include "Util/ResourcePool.h" #include "Extension/H264.h" #include "Common/Stamp.h" -using namespace toolkit; namespace mediakit{ diff --git a/src/Extension/H265.cpp b/src/Extension/H265.cpp index b4c10ac9..8586c2cc 100644 --- a/src/Extension/H265.cpp +++ b/src/Extension/H265.cpp @@ -11,7 +11,10 @@ #include "H265.h" #include "SPSParser.h" -namespace mediakit{ +using namespace std; +using namespace toolkit; + +namespace mediakit { bool getHEVCInfo(const char * vps, size_t vps_len,const char * sps,size_t sps_len,int &iVideoWidth, int &iVideoHeight, float &iVideoFps){ T_GetBitContext tGetBitBuf; diff --git a/src/Extension/H265.h b/src/Extension/H265.h index ca872b75..59913c81 100644 --- a/src/Extension/H265.h +++ b/src/Extension/H265.h @@ -15,18 +15,18 @@ #include "Track.h" #include "Util/base64.h" #include "H264.h" + #define H265_TYPE(v) (((uint8_t)(v) >> 1) & 0x3f) -using namespace toolkit; namespace mediakit { -bool getHEVCInfo(const string &strVps, const string &strSps, int &iVideoWidth, int &iVideoHeight, float &iVideoFps); +bool getHEVCInfo(const std::string &strVps, const std::string &strSps, int &iVideoWidth, int &iVideoHeight, float &iVideoFps); template class H265FrameHelper : public Parent{ public: friend class FrameImp; - friend class ResourcePool_l; + friend class toolkit::ResourcePool_l; using Ptr = std::shared_ptr; enum { @@ -136,14 +136,14 @@ public: * @param sps_prefix_len 265头长度,可以为3个或4个字节,一般为0x00 00 00 01 * @param pps_prefix_len 265头长度,可以为3个或4个字节,一般为0x00 00 00 01 */ - H265Track(const string &vps,const string &sps, const string &pps,int vps_prefix_len = 4, int sps_prefix_len = 4, int pps_prefix_len = 4); + H265Track(const std::string &vps,const std::string &sps, const std::string &pps,int vps_prefix_len = 4, int sps_prefix_len = 4, int pps_prefix_len = 4); /** * 返回不带0x00 00 00 01头的vps/sps/pps */ - const string &getVps() const; - const string &getSps() const; - const string &getPps() const; + const std::string &getVps() const; + const std::string &getSps() const; + const std::string &getPps() const; bool ready() override; CodecId getCodecId() const override; @@ -164,9 +164,9 @@ private: int _width = 0; int _height = 0; float _fps = 0; - string _vps; - string _sps; - string _pps; + std::string _vps; + std::string _sps; + std::string _pps; }; }//namespace mediakit diff --git a/src/Extension/H265Rtmp.cpp b/src/Extension/H265Rtmp.cpp index 313e5ff8..467be51a 100644 --- a/src/Extension/H265Rtmp.cpp +++ b/src/Extension/H265Rtmp.cpp @@ -14,6 +14,9 @@ #include "mpeg4-hevc.h" #endif//ENABLE_MP4 +using namespace std; +using namespace toolkit; + namespace mediakit{ H265RtmpDecoder::H265RtmpDecoder() { diff --git a/src/Extension/H265Rtmp.h b/src/Extension/H265Rtmp.h index 712612a7..8200ac98 100644 --- a/src/Extension/H265Rtmp.h +++ b/src/Extension/H265Rtmp.h @@ -15,7 +15,6 @@ #include "Extension/Track.h" #include "Util/ResourcePool.h" #include "Extension/H265.h" -using namespace toolkit; namespace mediakit{ /** @@ -79,9 +78,9 @@ private: private: bool _got_config_frame = false; - string _vps; - string _sps; - string _pps; + std::string _vps; + std::string _sps; + std::string _pps; H265Track::Ptr _track; RtmpPacket::Ptr _rtmp_packet; FrameMerger _merger{FrameMerger::mp4_nal_size}; diff --git a/src/Extension/H265Rtp.h b/src/Extension/H265Rtp.h index af9b6247..ad1002e1 100644 --- a/src/Extension/H265Rtp.h +++ b/src/Extension/H265Rtp.h @@ -16,8 +16,6 @@ #include "Extension/H265.h" #include "Common/Stamp.h" -using namespace toolkit; - namespace mediakit{ /** diff --git a/src/Extension/L16.cpp b/src/Extension/L16.cpp index 8194dfa3..dff70a2e 100644 --- a/src/Extension/L16.cpp +++ b/src/Extension/L16.cpp @@ -10,6 +10,9 @@ #include "L16.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ /** diff --git a/src/Extension/Opus.cpp b/src/Extension/Opus.cpp index 03e107a9..0e0100a2 100644 --- a/src/Extension/Opus.cpp +++ b/src/Extension/Opus.cpp @@ -10,6 +10,9 @@ #include "Opus.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ /** diff --git a/src/Extension/Track.h b/src/Extension/Track.h index aa03d8da..0bada492 100644 --- a/src/Extension/Track.h +++ b/src/Extension/Track.h @@ -16,7 +16,6 @@ #include "Frame.h" #include "Util/RingBuffer.h" #include "Rtsp/Rtsp.h" -using namespace toolkit; namespace mediakit{ @@ -186,7 +185,7 @@ public: * 获取全部的Track * @param trackReady 是否获取全部已经准备好的Track */ - virtual vector getTracks(bool trackReady = true) const = 0; + virtual std::vector getTracks(bool trackReady = true) const = 0; /** * 获取特定Track diff --git a/src/FMP4/FMP4MediaSource.h b/src/FMP4/FMP4MediaSource.h index 3a7e66e6..154ad0e9 100644 --- a/src/FMP4/FMP4MediaSource.h +++ b/src/FMP4/FMP4MediaSource.h @@ -12,18 +12,18 @@ #define ZLMEDIAKIT_FMP4MEDIASOURCE_H #include "Common/MediaSource.h" -using namespace toolkit; + #define FMP4_GOP_SIZE 512 namespace mediakit { //FMP4直播数据包 -class FMP4Packet : public BufferString{ +class FMP4Packet : public toolkit::BufferString{ public: using Ptr = std::shared_ptr; template - FMP4Packet(ARGS && ...args) : BufferString(std::forward(args)...) {}; + FMP4Packet(ARGS && ...args) : toolkit::BufferString(std::forward(args)...) {}; ~FMP4Packet() override = default; public: @@ -31,15 +31,15 @@ public: }; //FMP4直播源 -class FMP4MediaSource : public MediaSource, public RingDelegate, private PacketCache{ +class FMP4MediaSource : public MediaSource, public toolkit::RingDelegate, private PacketCache{ public: using Ptr = std::shared_ptr; - using RingDataType = std::shared_ptr >; - using RingType = RingBuffer; + using RingDataType = std::shared_ptr >; + using RingType = toolkit::RingBuffer; - FMP4MediaSource(const string &vhost, - const string &app, - const string &stream_id, + FMP4MediaSource(const std::string &vhost, + const std::string &app, + const std::string &stream_id, int ring_size = FMP4_GOP_SIZE) : MediaSource(FMP4_SCHEMA, vhost, app, stream_id), _ring_size(ring_size) {} ~FMP4MediaSource() override = default; @@ -54,7 +54,7 @@ public: /** * 获取fmp4 init segment */ - const string &getInitSegment() const{ + const std::string &getInitSegment() const{ return _init_segment; } @@ -62,7 +62,7 @@ public: * 设置fmp4 init segment * @param str init segment */ - void setInitSegment(string str) { + void setInitSegment(std::string str) { _init_segment = std::move(str); createRing(); } @@ -101,7 +101,7 @@ public: private: void createRing(){ - weak_ptr weak_self = dynamic_pointer_cast(shared_from_this()); + std::weak_ptr weak_self = std::dynamic_pointer_cast(shared_from_this()); _ring = std::make_shared(_ring_size, [weak_self](int size) { auto strong_self = weak_self.lock(); if (!strong_self) { @@ -120,7 +120,7 @@ private: * @param packet_list 合并写缓存列队 * @param key_pos 是否包含关键帧 */ - void onFlush(std::shared_ptr > packet_list, bool key_pos) override { + void onFlush(std::shared_ptr > packet_list, bool key_pos) override { //如果不存在视频,那么就没有存在GOP缓存的意义,所以确保一直清空GOP缓存 _ring->write(std::move(packet_list), _have_video ? key_pos : true); } @@ -128,7 +128,7 @@ private: private: bool _have_video = false; int _ring_size; - string _init_segment; + std::string _init_segment; RingType::Ptr _ring; }; diff --git a/src/FMP4/FMP4MediaSourceMuxer.h b/src/FMP4/FMP4MediaSourceMuxer.h index 7579934f..bc59c8ce 100644 --- a/src/FMP4/FMP4MediaSourceMuxer.h +++ b/src/FMP4/FMP4MediaSourceMuxer.h @@ -23,9 +23,9 @@ class FMP4MediaSourceMuxer : public MP4MuxerMemory, public MediaSourceEventInter public: using Ptr = std::shared_ptr; - FMP4MediaSourceMuxer(const string &vhost, - const string &app, - const string &stream_id) { + FMP4MediaSourceMuxer(const std::string &vhost, + const std::string &app, + const std::string &stream_id) { _media_src = std::make_shared(vhost, app, stream_id); } @@ -72,7 +72,7 @@ public: } protected: - void onSegmentData(string string, uint32_t stamp, bool key_frame) override { + void onSegmentData(std::string string, uint32_t stamp, bool key_frame) override { if (string.empty()) { return; } diff --git a/src/Http/HlsParser.cpp b/src/Http/HlsParser.cpp index 03c80c6a..bd92cf41 100644 --- a/src/Http/HlsParser.cpp +++ b/src/Http/HlsParser.cpp @@ -13,7 +13,10 @@ #include "HlsParser.h" #include "Util/util.h" #include "Common/Parser.h" + +using namespace std; using namespace toolkit; + namespace mediakit { bool HlsParser::parse(const string &http_url, const string &m3u8) { diff --git a/src/Http/HlsParser.h b/src/Http/HlsParser.h index d3ccbc2c..eafaf338 100644 --- a/src/Http/HlsParser.h +++ b/src/Http/HlsParser.h @@ -14,12 +14,12 @@ #include #include #include -using namespace std; + namespace mediakit { typedef struct{ //url地址 - string url; + std::string url; //ts切片长度 float duration; @@ -38,7 +38,7 @@ class HlsParser { public: HlsParser(){} ~HlsParser(){} - bool parse(const string &http_url,const string &m3u8); + bool parse(const std::string &http_url,const std::string &m3u8); /** * 是否存在#EXTM3U字段,是否为m3u8文件 @@ -82,7 +82,7 @@ public: protected: //解析出ts文件地址回调 - virtual void onParsed(bool is_m3u8_inner,int64_t sequence,const map &ts_list) {}; + virtual void onParsed(bool is_m3u8_inner,int64_t sequence,const std::map &ts_list) {}; private: bool _is_m3u8 = false; diff --git a/src/Http/HlsPlayer.cpp b/src/Http/HlsPlayer.cpp index 3c867acf..a38e28fe 100644 --- a/src/Http/HlsPlayer.cpp +++ b/src/Http/HlsPlayer.cpp @@ -10,6 +10,9 @@ #include "HlsPlayer.h" +using namespace std; +using namespace toolkit; + namespace mediakit { HlsPlayer::HlsPlayer(const EventPoller::Ptr &poller) { @@ -27,8 +30,8 @@ void HlsPlayer::fetchIndexFile() { if (waitResponse()) { return; } - if (!(*this)[kNetAdapter].empty()) { - setNetAdapter((*this)[kNetAdapter]); + if (!(*this)[Client::kNetAdapter].empty()) { + setNetAdapter((*this)[Client::kNetAdapter]); } setCompleteTimeout((*this)[Client::kTimeoutMS].as()); setMethod("GET"); @@ -83,7 +86,7 @@ void HlsPlayer::fetchSegment() { strong_self->onPacket_l(data, len); }); - if (!(*this)[kNetAdapter].empty()) { + if (!(*this)[Client::kNetAdapter].empty()) { _http_ts_player->setNetAdapter((*this)[Client::kNetAdapter]); } } diff --git a/src/Http/HlsPlayer.h b/src/Http/HlsPlayer.h index 7837b614..11f66060 100644 --- a/src/Http/HlsPlayer.h +++ b/src/Http/HlsPlayer.h @@ -17,8 +17,6 @@ #include "HlsParser.h" #include "Rtp/TSDecoder.h" -using namespace toolkit; - namespace mediakit { class HlsDemuxer @@ -29,12 +27,12 @@ public: HlsDemuxer() = default; ~HlsDemuxer() override { _timer = nullptr; } - void start(const EventPoller::Ptr &poller, TrackListener *listener); + void start(const toolkit::EventPoller::Ptr &poller, TrackListener *listener); bool inputFrame(const Frame::Ptr &frame) override; bool addTrack(const Track::Ptr &track) override { return _delegate.addTrack(track); } void addTrackCompleted() override { _delegate.addTrackCompleted(); } void resetTracks() override { ((MediaSink &)_delegate).resetTracks(); } - vector getTracks(bool ready = true) const override { return _delegate.getTracks(ready); } + std::vector getTracks(bool ready = true) const override { return _delegate.getTracks(ready); } private: void onTick(); @@ -44,22 +42,22 @@ private: private: int64_t _ticker_offset = 0; - Ticker _ticker; + toolkit::Ticker _ticker; Stamp _stamp[2]; - Timer::Ptr _timer; + toolkit::Timer::Ptr _timer; MediaSinkDelegate _delegate; - multimap _frame_cache; + std::multimap _frame_cache; }; class HlsPlayer : public HttpClientImp , public PlayerBase , public HlsParser{ public: - HlsPlayer(const EventPoller::Ptr &poller); + HlsPlayer(const toolkit::EventPoller::Ptr &poller); ~HlsPlayer() override = default; /** * 开始播放 */ - void play(const string &url) override; + void play(const std::string &url) override; /** * 停止播放 @@ -76,37 +74,37 @@ protected: private: void onParsed(bool is_m3u8_inner,int64_t sequence,const map &ts_map) override; - void onResponseHeader(const string &status,const HttpHeader &headers) override; + void onResponseHeader(const std::string &status,const HttpHeader &headers) override; void onResponseBody(const char *buf,size_t size) override; - void onResponseCompleted(const SockException &e) override; - bool onRedirectUrl(const string &url,bool temporary) override; + void onResponseCompleted(const toolkit::SockException &e) override; + bool onRedirectUrl(const std::string &url,bool temporary) override; private: void playDelay(); float delaySecond(); void fetchSegment(); - void teardown_l(const SockException &ex); + void teardown_l(const toolkit::SockException &ex); void fetchIndexFile(); void onPacket_l(const char *data, size_t len); private: struct UrlComp { //url忽略?后面的参数 - bool operator()(const string& __x, const string& __y) const { - return split(__x,"?")[0] < split(__y,"?")[0]; + bool operator()(const std::string& __x, const std::string& __y) const { + return toolkit::split(__x,"?")[0] < toolkit::split(__y,"?")[0]; } }; private: bool _play_result = false; int64_t _last_sequence = -1; - string _m3u8; - string _play_url; - Timer::Ptr _timer; - Timer::Ptr _timer_ts; - list _ts_list; - list _ts_url_sort; - set _ts_url_cache; + std::string _m3u8; + std::string _play_url; + toolkit::Timer::Ptr _timer; + toolkit::Timer::Ptr _timer_ts; + std::list _ts_list; + std::list _ts_url_sort; + std::set _ts_url_cache; HttpTSPlayer::Ptr _http_ts_player; TSSegment _segment; }; @@ -114,7 +112,7 @@ private: class HlsPlayerImp : public PlayerImp, private TrackListener { public: typedef std::shared_ptr Ptr; - HlsPlayerImp(const EventPoller::Ptr &poller = nullptr); + HlsPlayerImp(const toolkit::EventPoller::Ptr &poller = nullptr); ~HlsPlayerImp() override = default; private: @@ -123,9 +121,9 @@ private: private: //// PlayerBase override//// - void onPlayResult(const SockException &ex) override; - vector getTracks(bool ready = true) const override; - void onShutdown(const SockException &ex) override; + void onPlayResult(const toolkit::SockException &ex) override; + std::vector getTracks(bool ready = true) const override; + void onShutdown(const toolkit::SockException &ex) override; private: //// TrackListener override//// diff --git a/src/Http/HttpBody.cpp b/src/Http/HttpBody.cpp index 14517c0f..4d9046a3 100644 --- a/src/Http/HttpBody.cpp +++ b/src/Http/HttpBody.cpp @@ -22,6 +22,9 @@ #define ENABLE_MMAP #endif +using namespace std; +using namespace toolkit; + namespace mediakit { HttpStringBody::HttpStringBody(string str){ diff --git a/src/Http/HttpBody.h b/src/Http/HttpBody.h index 5c0de8ec..eb854030 100644 --- a/src/Http/HttpBody.h +++ b/src/Http/HttpBody.h @@ -18,9 +18,6 @@ #include "Util/logger.h" #include "Thread/WorkThreadPool.h" -using namespace std; -using namespace toolkit; - #ifndef MIN #define MIN(a,b) ((a) < (b) ? (a) : (b) ) #endif //MIN @@ -47,14 +44,14 @@ public: * @param size 请求大小 * @return 字节对象,如果读完了,那么请返回nullptr */ - virtual Buffer::Ptr readData(size_t size) { return nullptr;}; + virtual toolkit::Buffer::Ptr readData(size_t size) { return nullptr;}; /** * 异步请求读取一定字节数,返回大小可能小于size * @param size 请求大小 * @param cb 回调函数 */ - virtual void readDataAsync(size_t size,const function &cb){ + virtual void readDataAsync(size_t size,const std::function &cb){ //由于unix和linux是通过mmap的方式读取文件,所以把读文件操作放在后台线程并不能提高性能 //反而会由于频繁的线程切换导致性能降低以及延时增加,所以我们默认同步获取文件内容 //(其实并没有读,拷贝文件数据时在内核态完成文件读) @@ -63,20 +60,20 @@ public: }; /** - * string类型的content + * std::string类型的content */ class HttpStringBody : public HttpBody{ public: typedef std::shared_ptr Ptr; - HttpStringBody(string str); + HttpStringBody(std::string str); ~HttpStringBody() override = default; ssize_t remainSize() override; - Buffer::Ptr readData(size_t size) override ; + toolkit::Buffer::Ptr readData(size_t size) override ; private: size_t _offset = 0; - mutable string _str; + mutable std::string _str; }; /** @@ -85,14 +82,14 @@ private: class HttpBufferBody : public HttpBody{ public: typedef std::shared_ptr Ptr; - HttpBufferBody(Buffer::Ptr buffer); + HttpBufferBody(toolkit::Buffer::Ptr buffer); ~HttpBufferBody() override = default; ssize_t remainSize() override; - Buffer::Ptr readData(size_t size) override; + toolkit::Buffer::Ptr readData(size_t size) override; private: - Buffer::Ptr _buffer; + toolkit::Buffer::Ptr _buffer; }; /** @@ -110,11 +107,11 @@ public: * @param use_mmap 是否使用mmap方式访问文件 */ HttpFileBody(const std::shared_ptr &fp, size_t offset, size_t max_size, bool use_mmap = true); - HttpFileBody(const string &file_path, bool use_mmap = true); + HttpFileBody(const std::string &file_path, bool use_mmap = true); ~HttpFileBody() override = default; ssize_t remainSize() override ; - Buffer::Ptr readData(size_t size) override; + toolkit::Buffer::Ptr readData(size_t size) override; private: void init(const std::shared_ptr &fp,size_t offset,size_t max_size, bool use_mmap); @@ -124,7 +121,7 @@ private: size_t _offset = 0; std::shared_ptr _fp; std::shared_ptr _map_addr; - ResourcePool _pool; + toolkit::ResourcePool _pool; }; class HttpArgs; @@ -142,21 +139,21 @@ public: * @param filePath 文件路径 * @param boundary boundary字符串 */ - HttpMultiFormBody(const HttpArgs &args,const string &filePath,const string &boundary = "0xKhTmLbOuNdArY"); + HttpMultiFormBody(const HttpArgs &args,const std::string &filePath,const std::string &boundary = "0xKhTmLbOuNdArY"); virtual ~HttpMultiFormBody(){} ssize_t remainSize() override ; - Buffer::Ptr readData(size_t size) override; + toolkit::Buffer::Ptr readData(size_t size) override; public: - static string multiFormBodyPrefix(const HttpArgs &args,const string &boundary,const string &fileName); - static string multiFormBodySuffix(const string &boundary); - static string multiFormContentType(const string &boundary); + static std::string multiFormBodyPrefix(const HttpArgs &args,const std::string &boundary,const std::string &fileName); + static std::string multiFormBodySuffix(const std::string &boundary); + static std::string multiFormContentType(const std::string &boundary); private: size_t _offset = 0; size_t _totalSize; - string _bodyPrefix; - string _bodySuffix; + std::string _bodyPrefix; + std::string _bodySuffix; HttpFileBody::Ptr _fileBody; }; diff --git a/src/Http/HttpChunkedSplitter.cpp b/src/Http/HttpChunkedSplitter.cpp index 205bedf3..3083a67f 100644 --- a/src/Http/HttpChunkedSplitter.cpp +++ b/src/Http/HttpChunkedSplitter.cpp @@ -11,6 +11,8 @@ #include #include "HttpChunkedSplitter.h" +using namespace std; + namespace mediakit{ const char *HttpChunkedSplitter::onSearchPacketTail(const char *data, size_t len) { diff --git a/src/Http/HttpClient.cpp b/src/Http/HttpClient.cpp index 18db3f3b..30fe327d 100644 --- a/src/Http/HttpClient.cpp +++ b/src/Http/HttpClient.cpp @@ -13,6 +13,9 @@ #include "HttpClient.h" #include "Common/config.h" +using namespace std; +using namespace toolkit; + namespace mediakit { void HttpClient::sendRequest(const string &url) { diff --git a/src/Http/HttpClient.h b/src/Http/HttpClient.h index 848b12a0..82fc2f9d 100644 --- a/src/Http/HttpClient.h +++ b/src/Http/HttpClient.h @@ -25,18 +25,15 @@ #include "strCoding.h" #include "HttpBody.h" -using namespace std; -using namespace toolkit; - namespace mediakit { -class HttpArgs : public map { +class HttpArgs : public std::map { public: HttpArgs() = default; ~HttpArgs() = default; - string make() const { - string ret; + std::string make() const { + std::string ret; for (auto &pr : *this) { ret.append(pr.first); ret.append("="); @@ -50,7 +47,7 @@ public: } }; -class HttpClient : public TcpClient, public HttpRequestSplitter { +class HttpClient : public toolkit::TcpClient, public HttpRequestSplitter { public: using HttpHeader = StrCaseMap; using Ptr = std::shared_ptr; @@ -62,7 +59,7 @@ public: * 发送http[s]请求 * @param url 请求url */ - virtual void sendRequest(const string &url); + virtual void sendRequest(const std::string &url); /** * 重置对象 @@ -73,7 +70,7 @@ public: * 设置http方法 * @param method GET/POST等 */ - void setMethod(string method); + void setMethod(std::string method); /** * 覆盖http头 @@ -81,13 +78,13 @@ public: */ void setHeader(HttpHeader header); - HttpClient &addHeader(string key, string val, bool force = false); + HttpClient &addHeader(std::string key, std::string val, bool force = false); /** * 设置http content * @param body http content */ - void setBody(string body); + void setBody(std::string body); /** * 设置http content @@ -113,7 +110,7 @@ public: /** * 获取请求url */ - const string &getUrl() const; + const std::string &getUrl() const; /** * 判断是否正在等待响应 @@ -150,7 +147,7 @@ protected: * @param status 状态码,譬如:200 OK * @param headers http头 */ - virtual void onResponseHeader(const string &status, const HttpHeader &headers) = 0; + virtual void onResponseHeader(const std::string &status, const HttpHeader &headers) = 0; /** * 收到http conten数据 @@ -162,7 +159,7 @@ protected: /** * 接收http回复完毕, */ - virtual void onResponseCompleted(const SockException &ex) = 0; + virtual void onResponseCompleted(const toolkit::SockException &ex) = 0; /** * 重定向事件 @@ -170,7 +167,7 @@ protected: * @param temporary 是否为临时重定向 * @return 是否继续 */ - virtual bool onRedirectUrl(const string &url, bool temporary) { return true; }; + virtual bool onRedirectUrl(const std::string &url, bool temporary) { return true; }; protected: //// HttpRequestSplitter override //// @@ -178,15 +175,15 @@ protected: void onRecvContent(const char *data, size_t len) override; //// TcpClient override //// - void onConnect(const SockException &ex) override; - void onRecv(const Buffer::Ptr &pBuf) override; - void onErr(const SockException &ex) override; + void onConnect(const toolkit::SockException &ex) override; + void onRecv(const toolkit::Buffer::Ptr &pBuf) override; + void onErr(const toolkit::SockException &ex) override; void onFlush() override; void onManager() override; private: - void onResponseCompleted_l(const SockException &ex); - void onConnect_l(const SockException &ex); + void onResponseCompleted_l(const toolkit::SockException &ex); + void onConnect_l(const toolkit::SockException &ex); void checkCookie(HttpHeader &headers); void clearResponse(); @@ -201,23 +198,23 @@ private: //for request args bool _is_https; - string _url; + std::string _url; HttpHeader _user_set_header; HttpBody::Ptr _body; - string _method; - string _last_host; + std::string _method; + std::string _last_host; //for this request - string _path; + std::string _path; HttpHeader _header; //for timeout size_t _wait_header_ms = 10 * 1000; size_t _wait_body_ms = 10 * 1000; size_t _wait_complete_ms = 0; - Ticker _wait_header; - Ticker _wait_body; - Ticker _wait_complete; + toolkit::Ticker _wait_header; + toolkit::Ticker _wait_body; + toolkit::Ticker _wait_complete; }; } /* namespace mediakit */ diff --git a/src/Http/HttpClientImp.cpp b/src/Http/HttpClientImp.cpp index da806d38..6dcf8437 100644 --- a/src/Http/HttpClientImp.cpp +++ b/src/Http/HttpClientImp.cpp @@ -10,6 +10,8 @@ #include "Http/HttpClientImp.h" +using namespace toolkit; + namespace mediakit { void HttpClientImp::onConnect(const SockException &ex) { diff --git a/src/Http/HttpClientImp.h b/src/Http/HttpClientImp.h index 1123cbf9..491b594f 100644 --- a/src/Http/HttpClientImp.h +++ b/src/Http/HttpClientImp.h @@ -13,17 +13,17 @@ #include "HttpClient.h" #include "Util/SSLBox.h" -using namespace toolkit; + namespace mediakit { -class HttpClientImp : public TcpClientWithSSL { +class HttpClientImp : public toolkit::TcpClientWithSSL { public: using Ptr = std::shared_ptr; HttpClientImp() = default; ~HttpClientImp() override = default; protected: - void onConnect(const SockException &ex) override; + void onConnect(const toolkit::SockException &ex) override; }; } /* namespace mediakit */ diff --git a/src/Http/HttpConst.cpp b/src/Http/HttpConst.cpp index f0572ea7..3e4116a7 100644 --- a/src/Http/HttpConst.cpp +++ b/src/Http/HttpConst.cpp @@ -13,6 +13,9 @@ #include "Common/Parser.h" #include "Util/onceToken.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ const char *getHttpStatusMessage(int status) { diff --git a/src/Http/HttpConst.h b/src/Http/HttpConst.h index 4c098500..b68f8be5 100644 --- a/src/Http/HttpConst.h +++ b/src/Http/HttpConst.h @@ -12,7 +12,6 @@ #define ZLMEDIAKIT_HTTPCONST_H #include -using namespace std; namespace mediakit{ @@ -28,7 +27,7 @@ const char *getHttpStatusMessage(int status); * @param name 文件后缀,譬如html * @return mime值,譬如text/html */ -const string &getHttpContentType(const char *name); +const std::string &getHttpContentType(const char *name); }//mediakit diff --git a/src/Http/HttpCookie.cpp b/src/Http/HttpCookie.cpp index a9efff73..ce7a0f89 100644 --- a/src/Http/HttpCookie.cpp +++ b/src/Http/HttpCookie.cpp @@ -17,6 +17,8 @@ #endif using namespace toolkit; +using namespace std; + namespace mediakit { void HttpCookie::setPath(const string &path){ diff --git a/src/Http/HttpCookie.h b/src/Http/HttpCookie.h index 8179eaed..728558d5 100644 --- a/src/Http/HttpCookie.h +++ b/src/Http/HttpCookie.h @@ -17,7 +17,6 @@ #include #include #include -using namespace std; namespace mediakit { @@ -31,19 +30,19 @@ public: HttpCookie(){} ~HttpCookie(){} - void setPath(const string &path); - void setHost(const string &host); - void setExpires(const string &expires,const string &server_date); - void setKeyVal(const string &key,const string &val); + void setPath(const std::string &path); + void setHost(const std::string &host); + void setExpires(const std::string &expires,const std::string &server_date); + void setKeyVal(const std::string &key,const std::string &val); operator bool (); - const string &getKey() const ; - const string &getVal() const ; + const std::string &getKey() const ; + const std::string &getVal() const ; private: - string _host; - string _path = "/"; - string _key; - string _val; + std::string _host; + std::string _path = "/"; + std::string _key; + std::string _val; time_t _expire = 0; }; @@ -56,12 +55,12 @@ public: ~HttpCookieStorage(){} static HttpCookieStorage &Instance(); void set(const HttpCookie::Ptr &cookie); - vector get(const string &host,const string &path); + std::vector get(const std::string &host,const std::string &path); private: HttpCookieStorage(){}; private: - unordered_map > > _all_cookie; - mutex _mtx_cookie; + std::unordered_map > > _all_cookie; + std::mutex _mtx_cookie; }; diff --git a/src/Http/HttpCookieManager.cpp b/src/Http/HttpCookieManager.cpp index 4351663f..868dea4b 100644 --- a/src/Http/HttpCookieManager.cpp +++ b/src/Http/HttpCookieManager.cpp @@ -13,6 +13,9 @@ #include "Common/config.h" #include "HttpCookieManager.h" +using namespace std; +using namespace toolkit; + namespace mediakit { //////////////////////////////HttpServerCookie//////////////////////////////////// diff --git a/src/Http/HttpCookieManager.h b/src/Http/HttpCookieManager.h index 260995fb..26e8a3a4 100644 --- a/src/Http/HttpCookieManager.h +++ b/src/Http/HttpCookieManager.h @@ -19,10 +19,6 @@ #include "Network/Socket.h" #include "Common/Parser.h" -using namespace std; -using namespace toolkit; -using namespace mediakit; - #define COOKIE_DEFAULT_LIFE (7 * 24 * 60 * 60) namespace mediakit { @@ -32,7 +28,7 @@ class HttpCookieManager; /** * cookie对象,用于保存cookie的一些相关属性 */ -class HttpServerCookie : public AnyStorage , public noncopyable{ +class HttpServerCookie : public toolkit::AnyStorage , public toolkit::noncopyable{ public: typedef std::shared_ptr Ptr; /** @@ -45,9 +41,9 @@ public: */ HttpServerCookie(const std::shared_ptr &manager, - const string &cookie_name, - const string &uid, - const string &cookie, + const std::string &cookie_name, + const std::string &uid, + const std::string &cookie, uint64_t max_elapsed); ~HttpServerCookie() ; @@ -55,7 +51,7 @@ public: * 获取uid * @return uid */ - const string &getUid() const; + const std::string &getUid() const; /** * 获取http中Set-Cookie字段的值 @@ -63,19 +59,19 @@ public: * @param path http访问路径 * @return 例如 MY_SESSION=XXXXXX;expires=Wed, Jun 12 2019 06:30:48 GMT;path=/index/files/ */ - string getCookie(const string &path) const; + std::string getCookie(const std::string &path) const; /** * 获取cookie随机字符串 * @return cookie随机字符串 */ - const string& getCookie() const; + const std::string& getCookie() const; /** * 获取该cookie名 * @return */ - const string& getCookieName() const; + const std::string& getCookieName() const; /** * 更新该cookie的过期时间,可以让此cookie不失效 @@ -92,16 +88,16 @@ public: * 获取区域锁 * @return */ - std::shared_ptr > getLock(); + std::shared_ptr > getLock(); private: - string cookieExpireTime() const ; + std::string cookieExpireTime() const ; private: - string _uid; - string _cookie_name; - string _cookie_uuid; + std::string _uid; + std::string _cookie_name; + std::string _cookie_uuid; uint64_t _max_elapsed; - Ticker _ticker; - recursive_mutex _mtx; + toolkit::Ticker _ticker; + std::recursive_mutex _mtx; std::weak_ptr _manager; }; @@ -117,18 +113,18 @@ public: * 获取不碰撞的随机字符串 * @return 随机字符串 */ - string obtain(); + std::string obtain(); /** * 释放随机字符串 * @param str 随机字符串 */ - void release(const string &str); + void release(const std::string &str); private: - string obtain_l(); + std::string obtain_l(); private: //碰撞库 - unordered_set _obtained; + std::unordered_set _obtained; //增长index,防止碰撞用 int _index = 0; }; @@ -156,7 +152,7 @@ public: * @param max_elapsed 该cookie过期时间,单位秒 * @return cookie对象 */ - HttpServerCookie::Ptr addCookie(const string &cookie_name,const string &uid, uint64_t max_elapsed = COOKIE_DEFAULT_LIFE,int max_client = 1); + HttpServerCookie::Ptr addCookie(const std::string &cookie_name,const std::string &uid, uint64_t max_elapsed = COOKIE_DEFAULT_LIFE,int max_client = 1); /** * 根据cookie随机字符串查找cookie对象 @@ -164,7 +160,7 @@ public: * @param cookie cookie随机字符串 * @return cookie对象,可以为nullptr */ - HttpServerCookie::Ptr getCookie(const string &cookie_name,const string &cookie); + HttpServerCookie::Ptr getCookie(const std::string &cookie_name,const std::string &cookie); /** * 从http头中获取cookie对象 @@ -172,7 +168,7 @@ public: * @param http_header http头 * @return cookie对象 */ - HttpServerCookie::Ptr getCookie(const string &cookie_name,const StrCaseMap &http_header); + HttpServerCookie::Ptr getCookie(const std::string &cookie_name,const StrCaseMap &http_header); /** * 根据uid获取cookie @@ -180,7 +176,7 @@ public: * @param uid 用户id * @return cookie对象 */ - HttpServerCookie::Ptr getCookieByUid(const string &cookie_name,const string &uid); + HttpServerCookie::Ptr getCookieByUid(const std::string &cookie_name,const std::string &uid); /** * 删除cookie,用户登出时使用 @@ -197,7 +193,7 @@ private: * @param uid 用户id * @param cookie cookie随机字符串 */ - void onAddCookie(const string &cookie_name,const string &uid,const string &cookie); + void onAddCookie(const std::string &cookie_name,const std::string &uid,const std::string &cookie); /** * 析构cookie对象时触发 @@ -205,7 +201,7 @@ private: * @param uid 用户id * @param cookie cookie随机字符串 */ - void onDelCookie(const string &cookie_name,const string &uid,const string &cookie); + void onDelCookie(const std::string &cookie_name,const std::string &uid,const std::string &cookie); /** * 获取某用户名下最先登录时的cookie,目的是实现某用户下最多登录若干个设备 @@ -214,7 +210,7 @@ private: * @param max_client 最多登录的设备个数 * @return 最早的cookie随机字符串 */ - string getOldestCookie(const string &cookie_name,const string &uid, int max_client = 1); + std::string getOldestCookie(const std::string &cookie_name,const std::string &uid, int max_client = 1); /** * 删除cookie @@ -222,12 +218,12 @@ private: * @param cookie cookie随机字符串 * @return 成功true */ - bool delCookie(const string &cookie_name,const string &cookie); + bool delCookie(const std::string &cookie_name,const std::string &cookie); private: - unordered_map >_map_cookie; - unordered_map > >_map_uid_to_cookie; - recursive_mutex _mtx_cookie; - Timer::Ptr _timer; + std::unordered_map >_map_cookie; + std::unordered_map > >_map_uid_to_cookie; + std::recursive_mutex _mtx_cookie; + toolkit::Timer::Ptr _timer; RandStrGeneator _geneator; }; diff --git a/src/Http/HttpDownloader.cpp b/src/Http/HttpDownloader.cpp index c87e9a8a..dcb67ff7 100644 --- a/src/Http/HttpDownloader.cpp +++ b/src/Http/HttpDownloader.cpp @@ -12,6 +12,7 @@ #include "Util/File.h" #include "Util/MD5.h" using namespace toolkit; +using namespace std; namespace mediakit { diff --git a/src/Http/HttpDownloader.h b/src/Http/HttpDownloader.h index a1e26dc6..44a198a6 100644 --- a/src/Http/HttpDownloader.h +++ b/src/Http/HttpDownloader.h @@ -18,7 +18,7 @@ namespace mediakit { class HttpDownloader : public HttpClientImp { public: using Ptr = std::shared_ptr; - using onDownloadResult = std::function; + using onDownloadResult = std::function; HttpDownloader() = default; ~HttpDownloader() override; @@ -29,9 +29,9 @@ public: * @param file_path 文件保存地址,置空则选择默认文件路径 * @param append 如果文件已经存在,是否断点续传方式下载 */ - void startDownload(const string &url, const string &file_path = "", bool append = false); + void startDownload(const std::string &url, const std::string &file_path = "", bool append = false); - void startDownload(const string &url, const onDownloadResult &cb) { + void startDownload(const std::string &url, const onDownloadResult &cb) { setOnResult(cb); startDownload(url, "", false); } @@ -40,15 +40,15 @@ public: protected: void onResponseBody(const char *buf, size_t size) override; - void onResponseHeader(const string &status, const HttpHeader &headers) override; - void onResponseCompleted(const SockException &ex) override; + void onResponseHeader(const std::string &status, const HttpHeader &headers) override; + void onResponseCompleted(const toolkit::SockException &ex) override; private: void closeFile(); private: FILE *_save_file = nullptr; - string _file_path; + std::string _file_path; onDownloadResult _on_result; }; diff --git a/src/Http/HttpFileManager.cpp b/src/Http/HttpFileManager.cpp index 54ebb995..30a70f4b 100644 --- a/src/Http/HttpFileManager.cpp +++ b/src/Http/HttpFileManager.cpp @@ -20,6 +20,9 @@ #include "Record/HlsMediaSource.h" #include "Common/Parser.h" +using namespace std; +using namespace toolkit; + namespace mediakit { // hls的播放cookie缓存时间默认60秒, diff --git a/src/Http/HttpFileManager.h b/src/Http/HttpFileManager.h index 95781888..2e598aae 100644 --- a/src/Http/HttpFileManager.h +++ b/src/Http/HttpFileManager.h @@ -22,20 +22,20 @@ namespace mediakit { class HttpResponseInvokerImp{ public: typedef std::function HttpResponseInvokerLambda0; - typedef std::function HttpResponseInvokerLambda1; + typedef std::function HttpResponseInvokerLambda1; HttpResponseInvokerImp(){} ~HttpResponseInvokerImp(){} template - HttpResponseInvokerImp(const C &c):HttpResponseInvokerImp(typename function_traits::stl_function_type(c)) {} + HttpResponseInvokerImp(const C &c):HttpResponseInvokerImp(typename toolkit::function_traits::stl_function_type(c)) {} HttpResponseInvokerImp(const HttpResponseInvokerLambda0 &lambda); HttpResponseInvokerImp(const HttpResponseInvokerLambda1 &lambda); - void operator()(int code, const StrCaseMap &headerOut, const Buffer::Ptr &body) const; + void operator()(int code, const StrCaseMap &headerOut, const toolkit::Buffer::Ptr &body) const; void operator()(int code, const StrCaseMap &headerOut, const HttpBody::Ptr &body) const; - void operator()(int code, const StrCaseMap &headerOut, const string &body) const; + void operator()(int code, const StrCaseMap &headerOut, const std::string &body) const; - void responseFile(const StrCaseMap &requestHeader,const StrCaseMap &responseHeader,const string &filePath, bool use_mmap = true) const; + void responseFile(const StrCaseMap &requestHeader,const StrCaseMap &responseHeader,const std::string &filePath, bool use_mmap = true) const; operator bool(); private: HttpResponseInvokerLambda0 _lambad; @@ -46,7 +46,7 @@ private: */ class HttpFileManager { public: - typedef function invoker; + typedef std::function invoker; /** * 访问文件或文件夹 @@ -54,14 +54,14 @@ public: * @param parser http请求 * @param cb 回调对象 */ - static void onAccessPath(TcpSession &sender, Parser &parser, const invoker &cb); + static void onAccessPath(toolkit::TcpSession &sender, Parser &parser, const invoker &cb); /** * 获取mime值 * @param name 文件后缀 * @return mime值 */ - static const string &getContentType(const char *name); + static const std::string &getContentType(const char *name); private: HttpFileManager() = delete; ~HttpFileManager() = delete; diff --git a/src/Http/HttpRequestSplitter.cpp b/src/Http/HttpRequestSplitter.cpp index 93bd0dae..4e82b83b 100644 --- a/src/Http/HttpRequestSplitter.cpp +++ b/src/Http/HttpRequestSplitter.cpp @@ -12,6 +12,7 @@ #include "Util/logger.h" #include "Util/util.h" using namespace toolkit; +using namespace std; //协议解析最大缓存1兆数据 static constexpr size_t kMaxCacheSize = 1 * 1024 * 1024; diff --git a/src/Http/HttpRequestSplitter.h b/src/Http/HttpRequestSplitter.h index e7a0846c..a36fdf6b 100644 --- a/src/Http/HttpRequestSplitter.h +++ b/src/Http/HttpRequestSplitter.h @@ -13,8 +13,6 @@ #include #include "Network/Buffer.h" -using namespace std; -using namespace toolkit; namespace mediakit { @@ -83,7 +81,7 @@ protected: private: ssize_t _content_len = 0; size_t _remain_data_size = 0; - BufferLikeString _remain_data; + toolkit::BufferLikeString _remain_data; }; } /* namespace mediakit */ diff --git a/src/Http/HttpRequester.cpp b/src/Http/HttpRequester.cpp index 284252e4..c5ca15d1 100644 --- a/src/Http/HttpRequester.cpp +++ b/src/Http/HttpRequester.cpp @@ -10,6 +10,9 @@ #include "HttpRequester.h" +using namespace std; +using namespace toolkit; + namespace mediakit { void HttpRequester::onResponseHeader(const string &status, const HttpHeader &headers) { diff --git a/src/Http/HttpRequester.h b/src/Http/HttpRequester.h index c314b3f3..69dd05a6 100644 --- a/src/Http/HttpRequester.h +++ b/src/Http/HttpRequester.h @@ -18,22 +18,22 @@ namespace mediakit { class HttpRequester : public HttpClientImp { public: using Ptr = std::shared_ptr; - using HttpRequesterResult = std::function; + using HttpRequesterResult = std::function; HttpRequester() = default; ~HttpRequester() override = default; void setOnResult(const HttpRequesterResult &onResult); - void startRequester(const string &url, const HttpRequesterResult &on_result, float timeout_sec = 10); + void startRequester(const std::string &url, const HttpRequesterResult &on_result, float timeout_sec = 10); void clear() override; private: - void onResponseHeader(const string &status, const HttpHeader &headers) override; + void onResponseHeader(const std::string &status, const HttpHeader &headers) override; void onResponseBody(const char *buf, size_t size) override; - void onResponseCompleted(const SockException &ex) override; + void onResponseCompleted(const toolkit::SockException &ex) override; private: - string _res_body; + std::string _res_body; HttpRequesterResult _on_result; }; diff --git a/src/Http/HttpSession.cpp b/src/Http/HttpSession.cpp index 7b58a232..c1b9655a 100644 --- a/src/Http/HttpSession.cpp +++ b/src/Http/HttpSession.cpp @@ -17,6 +17,8 @@ #include "HttpConst.h" #include "Util/base64.h" #include "Util/SHA1.h" + +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Http/HttpSession.h b/src/Http/HttpSession.h index 0cb4a366..d78dcdc4 100644 --- a/src/Http/HttpSession.h +++ b/src/Http/HttpSession.h @@ -22,12 +22,9 @@ #include "TS/TSMediaSource.h" #include "FMP4/FMP4MediaSource.h" -using namespace std; -using namespace toolkit; - namespace mediakit { -class HttpSession: public TcpSession, +class HttpSession: public toolkit::TcpSession, public FlvMuxer, public HttpRequestSplitter, public WebSocketSplitter { @@ -40,19 +37,19 @@ public: * @param accessPath 运行或禁止访问的根目录 * @param cookieLifeSecond 鉴权cookie有效期 **/ - typedef std::function HttpAccessPathInvoker; + typedef std::function HttpAccessPathInvoker; - HttpSession(const Socket::Ptr &pSock); + HttpSession(const toolkit::Socket::Ptr &pSock); ~HttpSession() override; - void onRecv(const Buffer::Ptr &) override; - void onError(const SockException &err) override; + void onRecv(const toolkit::Buffer::Ptr &) override; + void onError(const toolkit::SockException &err) override; void onManager() override; - static string urlDecode(const string &str); + static std::string urlDecode(const std::string &str); protected: //FlvMuxer override - void onWrite(const Buffer::Ptr &data, bool flush) override ; + void onWrite(const toolkit::Buffer::Ptr &data, bool flush) override ; void onDetach() override; std::shared_ptr getSharedPtr() override; @@ -74,7 +71,7 @@ protected: size_t len, size_t totalSize, size_t recvedSize){ - shutdown(SockException(Err_shutdown,"http post content is too huge,default closed")); + shutdown(toolkit::SockException(toolkit::Err_shutdown,"http post content is too huge,default closed")); } /** @@ -92,7 +89,7 @@ protected: * 发送数据进行websocket协议打包后回调 * @param buffer websocket协议数据 */ - void onWebSocketEncodeData(Buffer::Ptr buffer) override; + void onWebSocketEncodeData(toolkit::Buffer::Ptr buffer) override; /** * 接收到完整的一个webSocket数据包后回调 @@ -107,11 +104,11 @@ private: void Handle_Req_HEAD(ssize_t &content_len); void Handle_Req_OPTIONS(ssize_t &content_len); - bool checkLiveStream(const string &schema, const string &url_suffix, const function &cb); + bool checkLiveStream(const std::string &schema, const std::string &url_suffix, const std::function &cb); - bool checkLiveStreamFlv(const function &cb = nullptr); - bool checkLiveStreamTS(const function &cb = nullptr); - bool checkLiveStreamFMP4(const function &fmp4_list = nullptr); + bool checkLiveStreamFlv(const std::function &cb = nullptr); + bool checkLiveStreamTS(const std::function &cb = nullptr); + bool checkLiveStreamFMP4(const std::function &fmp4_list = nullptr); bool checkWebSocket(); bool emitHttpEvent(bool doInvoke); @@ -129,18 +126,17 @@ private: bool _live_over_websocket = false; //消耗的总流量 uint64_t _total_bytes_usage = 0; - string _origin; + std::string _origin; Parser _parser; - Ticker _ticker; + toolkit::Ticker _ticker; MediaInfo _mediaInfo; TSMediaSource::RingType::RingReader::Ptr _ts_reader; FMP4MediaSource::RingType::RingReader::Ptr _fmp4_reader; //处理content数据的callback - function _contentCallBack; + std::function _contentCallBack; }; - -typedef TcpSessionWithSSL HttpsSession; +using HttpsSession = toolkit::TcpSessionWithSSL; } /* namespace mediakit */ diff --git a/src/Http/HttpTSPlayer.cpp b/src/Http/HttpTSPlayer.cpp index a77de5ce..dbd82cbb 100644 --- a/src/Http/HttpTSPlayer.cpp +++ b/src/Http/HttpTSPlayer.cpp @@ -10,6 +10,9 @@ #include "HttpTSPlayer.h" +using namespace std; +using namespace toolkit; + namespace mediakit { HttpTSPlayer::HttpTSPlayer(const EventPoller::Ptr &poller, bool split_ts) { diff --git a/src/Http/HttpTSPlayer.h b/src/Http/HttpTSPlayer.h index ad7fd9ff..462270b8 100644 --- a/src/Http/HttpTSPlayer.h +++ b/src/Http/HttpTSPlayer.h @@ -15,17 +15,15 @@ #include "Player/MediaPlayer.h" #include "Rtp/TSDecoder.h" -using namespace toolkit; - namespace mediakit { //http-ts播发器,未实现ts解复用 class HttpTSPlayer : public HttpClientImp { public: using Ptr = std::shared_ptr; - using onComplete = std::function; + using onComplete = std::function; - HttpTSPlayer(const EventPoller::Ptr &poller = nullptr, bool split_ts = true); + HttpTSPlayer(const toolkit::EventPoller::Ptr &poller = nullptr, bool split_ts = true); ~HttpTSPlayer() override = default; /** @@ -40,9 +38,9 @@ public: protected: ///HttpClient override/// - void onResponseHeader(const string &status, const HttpHeader &header) override; + void onResponseHeader(const std::string &status, const HttpHeader &header) override; void onResponseBody(const char *buf, size_t size) override; - void onResponseCompleted(const SockException &ex) override; + void onResponseCompleted(const toolkit::SockException &ex) override; protected: /** @@ -51,7 +49,7 @@ protected: virtual void onPacket(const char *data, size_t len); private: - void emitOnComplete(const SockException &ex); + void emitOnComplete(const toolkit::SockException &ex); private: bool _split_ts; diff --git a/src/Http/TsPlayer.cpp b/src/Http/TsPlayer.cpp index b559286d..21b81da4 100644 --- a/src/Http/TsPlayer.cpp +++ b/src/Http/TsPlayer.cpp @@ -10,6 +10,9 @@ #include "TsPlayer.h" +using namespace std; +using namespace toolkit; + namespace mediakit { TsPlayer::TsPlayer(const EventPoller::Ptr &poller) : HttpTSPlayer(poller, true) {} diff --git a/src/Http/TsPlayer.h b/src/Http/TsPlayer.h index 6bb27e19..4b0656f8 100644 --- a/src/Http/TsPlayer.h +++ b/src/Http/TsPlayer.h @@ -14,18 +14,17 @@ #include "HttpTSPlayer.h" #include "Player/PlayerBase.h" -using namespace toolkit; namespace mediakit { class TsPlayer : public HttpTSPlayer , public PlayerBase { public: - TsPlayer(const EventPoller::Ptr &poller); + TsPlayer(const toolkit::EventPoller::Ptr &poller); ~TsPlayer() override = default; /** * 开始播放 */ - void play(const string &url) override; + void play(const std::string &url) override; /** * 停止播放 @@ -34,7 +33,7 @@ public: protected: void onResponseBody(const char *buf, size_t size) override; - void onResponseCompleted(const SockException &ex) override; + void onResponseCompleted(const toolkit::SockException &ex) override; private: bool _play_result = true; diff --git a/src/Http/TsPlayerImp.h b/src/Http/TsPlayerImp.h index 6e3d40b4..98c65ee4 100644 --- a/src/Http/TsPlayerImp.h +++ b/src/Http/TsPlayerImp.h @@ -14,15 +14,13 @@ #include #include "TsPlayer.h" -using namespace toolkit; - namespace mediakit { class TsPlayerImp : public PlayerImp, private TrackListener { public: using Ptr = std::shared_ptr; - TsPlayerImp(const EventPoller::Ptr &poller = nullptr); + TsPlayerImp(const toolkit::EventPoller::Ptr &poller = nullptr); ~TsPlayerImp() override = default; private: @@ -31,9 +29,9 @@ private: private: //// PlayerBase override//// - void onPlayResult(const SockException &ex) override; - vector getTracks(bool ready = true) const override; - void onShutdown(const SockException &ex) override; + void onPlayResult(const toolkit::SockException &ex) override; + std::vector getTracks(bool ready = true) const override; + void onShutdown(const toolkit::SockException &ex) override; private: //// TrackListener override//// diff --git a/src/Http/TsplayerImp.cpp b/src/Http/TsplayerImp.cpp index b44da5c9..b12584bb 100644 --- a/src/Http/TsplayerImp.cpp +++ b/src/Http/TsplayerImp.cpp @@ -11,6 +11,9 @@ #include "TsPlayerImp.h" #include "HlsPlayer.h" +using namespace std; +using namespace toolkit; + namespace mediakit { TsPlayerImp::TsPlayerImp(const EventPoller::Ptr &poller) : PlayerImp(poller) {} diff --git a/src/Http/WebSocketClient.h b/src/Http/WebSocketClient.h index 7fd0b177..69556344 100644 --- a/src/Http/WebSocketClient.h +++ b/src/Http/WebSocketClient.h @@ -17,7 +17,6 @@ #include "Network/TcpClient.h" #include "HttpClientImp.h" #include "WebSocketSplitter.h" -using namespace toolkit; namespace mediakit{ @@ -32,8 +31,9 @@ class HttpWsClient; template class ClientTypeImp : public ClientType { public: - typedef function onBeforeSendCB; - friend class HttpWsClient; + friend class HttpWsClient; + + using onBeforeSendCB = std::function; template ClientTypeImp(ArgsType &&...args): ClientType(std::forward(args)...){} @@ -43,7 +43,7 @@ protected: /** * 发送前拦截并打包为websocket协议 */ - ssize_t send(Buffer::Ptr buf) override{ + ssize_t send(toolkit::Buffer::Ptr buf) override{ if(_beforeSendCB){ return _beforeSendCB(buf); } @@ -70,11 +70,11 @@ private: template class HttpWsClient : public HttpClientImp , public WebSocketSplitter{ public: - typedef shared_ptr Ptr; + typedef std::shared_ptr Ptr; HttpWsClient(const std::shared_ptr > &delegate) : _weak_delegate(delegate), _delegate(*delegate) { - _Sec_WebSocket_Key = encodeBase64(makeRandStr(16, false)); + _Sec_WebSocket_Key = encodeBase64(toolkit::makeRandStr(16, false)); setPoller(_delegate.getPoller()); } ~HttpWsClient(){} @@ -84,10 +84,10 @@ public: * @param ws_url ws连接url * @param fTimeOutSec 超时时间 */ - void startWsClient(const string &ws_url, float fTimeOutSec) { - string http_url = ws_url; - replace(http_url, "ws://", "http://"); - replace(http_url, "wss://", "https://"); + void startWsClient(const std::string &ws_url, float fTimeOutSec) { + std::string http_url = ws_url; + toolkit::replace(http_url, "ws://", "http://"); + toolkit::replace(http_url, "wss://", "https://"); setMethod("GET"); addHeader("Upgrade", "websocket"); addHeader("Connection", "Upgrade"); @@ -120,27 +120,27 @@ protected: * @param status 状态码,譬如:200 OK * @param headers http头 */ - void onResponseHeader(const string &status,const HttpHeader &headers) override { + void onResponseHeader(const std::string &status, const HttpHeader &headers) override { if(status == "101"){ - auto Sec_WebSocket_Accept = encodeBase64(SHA1::encode_bin(_Sec_WebSocket_Key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); + auto Sec_WebSocket_Accept = encodeBase64(toolkit::SHA1::encode_bin(_Sec_WebSocket_Key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); if(Sec_WebSocket_Accept == const_cast(headers)["Sec-WebSocket-Accept"]){ //success - onWebSocketException(SockException()); + onWebSocketException(toolkit::SockException()); //防止ws服务器返回Content-Length const_cast(headers).erase("Content-Length"); return; } - shutdown(SockException(Err_shutdown, StrPrinter << "Sec-WebSocket-Accept mismatch")); + shutdown(toolkit::SockException(toolkit::Err_shutdown, StrPrinter << "Sec-WebSocket-Accept mismatch")); return; } - shutdown(SockException(Err_shutdown,StrPrinter << "bad http status code:" << status)); + shutdown(toolkit::SockException(toolkit::Err_shutdown,StrPrinter << "bad http status code:" << status)); }; /** * 接收http回复完毕, */ - void onResponseCompleted(const SockException &ex) override {} + void onResponseCompleted(const toolkit::SockException &ex) override {} /** * 接收websocket负载数据 @@ -154,7 +154,7 @@ protected: //TcpClient override - void onRecv(const Buffer::Ptr &buf) override { + void onRecv(const toolkit::Buffer::Ptr &buf) override { auto strong_ref = _weak_delegate.lock();; HttpClientImp::onRecv(buf); } @@ -190,7 +190,7 @@ protected: /** * tcp连接结果 */ - void onConnect(const SockException &ex) override { + void onConnect(const toolkit::SockException &ex) override { auto strong_ref = _weak_delegate.lock();; if (ex) { //tcp连接失败,直接返回失败 @@ -204,7 +204,7 @@ protected: /** * tcp连接断开 */ - void onErr(const SockException &ex) override { + void onErr(const toolkit::SockException &ex) override { auto strong_ref = _weak_delegate.lock();; //tcp断开或者shutdown导致的断开 onWebSocketException(ex); @@ -245,14 +245,14 @@ protected: case WebSocketHeader::CLOSE:{ //服务器主动关闭 WebSocketSplitter::encode(header,nullptr); - shutdown(SockException(Err_eof,"websocket server close the connection")); + shutdown(toolkit::SockException(toolkit::Err_eof,"websocket server close the connection")); break; } case WebSocketHeader::PING:{ //心跳包 header._opcode = WebSocketHeader::PONG; - WebSocketSplitter::encode(header,std::make_shared(std::move(_payload_section))); + WebSocketSplitter::encode(header,std::make_shared(std::move(_payload_section))); break; } @@ -294,17 +294,17 @@ protected: * @param ptr 数据指针 * @param len 数据指针长度 */ - void onWebSocketEncodeData(Buffer::Ptr buffer) override{ + void onWebSocketEncodeData(toolkit::Buffer::Ptr buffer) override{ HttpClientImp::send(std::move(buffer)); } private: - void onWebSocketException(const SockException &ex){ + void onWebSocketException(const toolkit::SockException &ex){ if(!ex){ //websocket握手成功 //此处截取TcpClient派生类发送的数据并进行websocket协议打包 - weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); - _delegate.setOnBeforeSendCB([weakSelf](const Buffer::Ptr &buf){ + std::weak_ptr weakSelf = std::dynamic_pointer_cast(shared_from_this()); + _delegate.setOnBeforeSendCB([weakSelf](const toolkit::Buffer::Ptr &buf){ auto strongSelf = weakSelf.lock(); if(strongSelf){ WebSocketHeader header; @@ -343,12 +343,12 @@ private: } private: - string _Sec_WebSocket_Key; - function _onRecv; - weak_ptr > _weak_delegate; - ClientTypeImp &_delegate; - string _payload_section; - string _payload_cache; + std::string _Sec_WebSocket_Key; + std::function _onRecv; + std::weak_ptr> _weak_delegate; + ClientTypeImp &_delegate; + std::string _payload_section; + std::string _payload_cache; }; /** @@ -378,8 +378,8 @@ public: * @param timeout_sec 超时时间 * @param local_port 本地监听端口,此处不起作用 */ - void startConnect(const string &host, uint16_t port, float timeout_sec = 3, uint16_t local_port = 0) override { - string ws_url; + void startConnect(const std::string &host, uint16_t port, float timeout_sec = 3, uint16_t local_port = 0) override { + std::string ws_url; if (useWSS) { //加密的ws ws_url = StrPrinter << "wss://" + host << ":" << port << "/"; @@ -390,9 +390,9 @@ public: startWebSocket(ws_url, timeout_sec); } - void startWebSocket(const string &ws_url,float fTimeOutSec = 3){ - _wsClient = std::make_shared >(static_pointer_cast(this->shared_from_this())); - _wsClient->setOnCreateSocket([this](const EventPoller::Ptr &){ + void startWebSocket(const std::string &ws_url, float fTimeOutSec = 3) { + _wsClient = std::make_shared >(std::static_pointer_cast(this->shared_from_this())); + _wsClient->setOnCreateSocket([this](const toolkit::EventPoller::Ptr &){ return this->createSocket(); }); _wsClient->startWsClient(ws_url,fTimeOutSec); diff --git a/src/Http/WebSocketSession.h b/src/Http/WebSocketSession.h index 03872abf..832fe338 100644 --- a/src/Http/WebSocketSession.h +++ b/src/Http/WebSocketSession.h @@ -19,7 +19,8 @@ */ class SendInterceptor{ public: - typedef function onBeforeSendCB; + using onBeforeSendCB =std::function; + SendInterceptor() = default; virtual ~SendInterceptor() = default; virtual void setOnBeforeSendCB(const onBeforeSendCB &cb) = 0; @@ -34,7 +35,7 @@ class TcpSessionTypeImp : public TcpSessionType, public SendInterceptor{ public: typedef std::shared_ptr Ptr; - TcpSessionTypeImp(const Parser &header, const HttpSession &parent, const Socket::Ptr &pSock) : + TcpSessionTypeImp(const mediakit::Parser &header, const mediakit::HttpSession &parent, const toolkit::Socket::Ptr &pSock) : TcpSessionType(pSock), _identifier(parent.getIdentifier()) {} ~TcpSessionTypeImp() {} @@ -53,19 +54,19 @@ protected: * @param buf 需要截取的数据 * @return 数据字节数 */ - ssize_t send(Buffer::Ptr buf) override { + ssize_t send(toolkit::Buffer::Ptr buf) override { if (_beforeSendCB) { return _beforeSendCB(buf); } return TcpSessionType::send(std::move(buf)); } - string getIdentifier() const override { + std::string getIdentifier() const override { return _identifier; } private: - string _identifier; + std::string _identifier; onBeforeSendCB _beforeSendCB; }; @@ -73,7 +74,7 @@ template class TcpSessionCreator { public: //返回的TcpSession必须派生于SendInterceptor,可以返回null - TcpSession::Ptr operator()(const Parser &header, const HttpSession &parent, const Socket::Ptr &pSock){ + toolkit::TcpSession::Ptr operator()(const mediakit::Parser &header, const mediakit::HttpSession &parent, const toolkit::Socket::Ptr &pSock){ return std::make_shared >(header,parent,pSock); } }; @@ -82,14 +83,14 @@ public: * 通过该模板类可以透明化WebSocket协议, * 用户只要实现WebSock协议下的具体业务协议,譬如基于WebSocket协议的Rtmp协议等 */ -template +template class WebSocketSessionBase : public HttpSessionType { public: - WebSocketSessionBase(const Socket::Ptr &pSock) : HttpSessionType(pSock){} + WebSocketSessionBase(const toolkit::Socket::Ptr &pSock) : HttpSessionType(pSock){} virtual ~WebSocketSessionBase(){} //收到eof或其他导致脱离TcpServer事件的回调 - void onError(const SockException &err) override{ + void onError(const toolkit::SockException &err) override{ HttpSessionType::onError(err); if(_session){ _session->onError(err); @@ -104,9 +105,9 @@ public: } } - void attachServer(const Server &server) override{ + void attachServer(const toolkit::Server &server) override{ HttpSessionType::attachServer(server); - _weak_server = const_cast(server).shared_from_this(); + _weak_server = const_cast(server).shared_from_this(); } protected: @@ -115,7 +116,7 @@ protected: * @param header http头 * @return true代表允许websocket连接,否则拒绝 */ - bool onWebSocketConnect(const Parser &header) override{ + bool onWebSocketConnect(const mediakit::Parser &header) override{ //创建websocket session类 _session = _creator(header, *this,HttpSessionType::getSock()); if(!_session){ @@ -128,16 +129,16 @@ protected: } //此处截取数据并进行websocket协议打包 - weak_ptr weakSelf = dynamic_pointer_cast(HttpSessionType::shared_from_this()); - dynamic_pointer_cast(_session)->setOnBeforeSendCB([weakSelf](const Buffer::Ptr &buf) { + std::weak_ptr weakSelf = std::dynamic_pointer_cast(HttpSessionType::shared_from_this()); + std::dynamic_pointer_cast(_session)->setOnBeforeSendCB([weakSelf](const toolkit::Buffer::Ptr &buf) { auto strongSelf = weakSelf.lock(); if (strongSelf) { - WebSocketHeader header; + mediakit::WebSocketHeader header; header._fin = true; header._reserved = 0; header._opcode = DataType; header._mask_flag = false; - strongSelf->WebSocketSplitter::encode(header, buf); + strongSelf->HttpSessionType::encode(header, buf); } return buf->size(); }); @@ -149,7 +150,7 @@ protected: /** * 开始收到一个webSocket数据包 */ - void onWebSocketDecodeHeader(const WebSocketHeader &packet) override{ + void onWebSocketDecodeHeader(const mediakit::WebSocketHeader &packet) override{ //新包,原来的包残余数据清空掉 _payload_section.clear(); } @@ -157,7 +158,7 @@ protected: /** * 收到websocket数据包负载 */ - void onWebSocketDecodePayload(const WebSocketHeader &packet,const uint8_t *ptr,size_t len,size_t recved) override { + void onWebSocketDecodePayload(const mediakit::WebSocketHeader &packet,const uint8_t *ptr,size_t len,size_t recved) override { _payload_section.append((char *)ptr,len); } @@ -165,27 +166,27 @@ protected: * 接收到完整的一个webSocket数据包后回调 * @param header 数据包包头 */ - void onWebSocketDecodeComplete(const WebSocketHeader &header_in) override { - WebSocketHeader& header = const_cast(header_in); + void onWebSocketDecodeComplete(const mediakit::WebSocketHeader &header_in) override { + auto header = const_cast(header_in); auto flag = header._mask_flag; header._mask_flag = false; switch (header._opcode){ - case WebSocketHeader::CLOSE:{ + case mediakit::WebSocketHeader::CLOSE:{ HttpSessionType::encode(header,nullptr); - HttpSessionType::shutdown(SockException(Err_shutdown, "recv close request from client")); + HttpSessionType::shutdown(toolkit::SockException(toolkit::Err_shutdown, "recv close request from client")); break; } - case WebSocketHeader::PING:{ - header._opcode = WebSocketHeader::PONG; - HttpSessionType::encode(header,std::make_shared(_payload_section)); + case mediakit::WebSocketHeader::PING:{ + header._opcode = mediakit::WebSocketHeader::PONG; + HttpSessionType::encode(header,std::make_shared(_payload_section)); break; } - case WebSocketHeader::CONTINUATION: - case WebSocketHeader::TEXT: - case WebSocketHeader::BINARY:{ + case mediakit::WebSocketHeader::CONTINUATION: + case mediakit::WebSocketHeader::TEXT: + case mediakit::WebSocketHeader::BINARY:{ if (!header._fin) { //还有后续分片数据, 我们先缓存数据,所有分片收集完成才一次性输出 _payload_cache.append(std::move(_payload_section)); @@ -199,13 +200,13 @@ protected: //最后一个包 if (_payload_cache.empty()) { //这个包是唯一个分片 - _session->onRecv(std::make_shared(header._opcode, header._fin, std::move(_payload_section))); + _session->onRecv(std::make_shared(header._opcode, header._fin, std::move(_payload_section))); break; } //这个包由多个分片组成 _payload_cache.append(std::move(_payload_section)); - _session->onRecv(std::make_shared(header._opcode, header._fin, std::move(_payload_cache))); + _session->onRecv(std::make_shared(header._opcode, header._fin, std::move(_payload_cache))); _payload_cache.clear(); break; } @@ -219,23 +220,23 @@ protected: /** * 发送数据进行websocket协议打包后回调 */ - void onWebSocketEncodeData(Buffer::Ptr buffer) override{ + void onWebSocketEncodeData(toolkit::Buffer::Ptr buffer) override{ HttpSessionType::send(std::move(buffer)); } private: - string _payload_cache; - string _payload_section; - weak_ptr _weak_server; - TcpSession::Ptr _session; + std::string _payload_cache; + std::string _payload_section; + std::weak_ptr _weak_server; + toolkit::TcpSession::Ptr _session; Creator _creator; }; -template +template class WebSocketSession : public WebSocketSessionBase,HttpSessionType,DataType>{ public: - WebSocketSession(const Socket::Ptr &pSock) : WebSocketSessionBase,HttpSessionType,DataType>(pSock){} + WebSocketSession(const toolkit::Socket::Ptr &pSock) : WebSocketSessionBase,HttpSessionType,DataType>(pSock){} virtual ~WebSocketSession(){} }; diff --git a/src/Http/WebSocketSplitter.cpp b/src/Http/WebSocketSplitter.cpp index 0efab68c..be760cca 100644 --- a/src/Http/WebSocketSplitter.cpp +++ b/src/Http/WebSocketSplitter.cpp @@ -17,6 +17,8 @@ #include "Util/logger.h" #include "Util/util.h" + +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Http/WebSocketSplitter.h b/src/Http/WebSocketSplitter.h index 8c89d5c7..7e3738d6 100644 --- a/src/Http/WebSocketSplitter.h +++ b/src/Http/WebSocketSplitter.h @@ -16,8 +16,6 @@ #include #include #include "Network/Buffer.h" -using namespace std; -using namespace toolkit; //websocket组合包最大不得超过4MB(防止内存爆炸) #define MAX_WS_PACKET (4 * 1024 * 1024) @@ -61,17 +59,17 @@ public: Type _opcode; bool _mask_flag; size_t _payload_len; - vector _mask; + std::vector _mask; }; //websocket协议收到的字符串类型缓存,用户协议层获取该数据传输的方式 -class WebSocketBuffer : public BufferString { +class WebSocketBuffer : public toolkit::BufferString { public: typedef std::shared_ptr Ptr; template WebSocketBuffer(WebSocketHeader::Type headType, bool fin, ARGS &&...args) - : BufferString(std::forward(args)...), _fin(fin), _head_type(headType){} + : toolkit::BufferString(std::forward(args)...), _fin(fin), _head_type(headType){} ~WebSocketBuffer() override {} @@ -103,7 +101,7 @@ public: * @param header 数据头 * @param buffer 负载数据 */ - void encode(const WebSocketHeader &header,const Buffer::Ptr &buffer); + void encode(const WebSocketHeader &header,const toolkit::Buffer::Ptr &buffer); protected: /** @@ -132,7 +130,7 @@ protected: * @param ptr 数据指针 * @param len 数据指针长度 */ - virtual void onWebSocketEncodeData(Buffer::Ptr buffer){}; + virtual void onWebSocketEncodeData(toolkit::Buffer::Ptr buffer){}; private: void onPayloadData(uint8_t *data, size_t len); @@ -141,7 +139,7 @@ private: bool _got_header = false; int _mask_offset = 0; size_t _payload_offset = 0; - string _remain_data; + std::string _remain_data; }; } /* namespace mediakit */ diff --git a/src/Http/strCoding.cpp b/src/Http/strCoding.cpp index 7c2d27e4..719e90fe 100644 --- a/src/Http/strCoding.cpp +++ b/src/Http/strCoding.cpp @@ -15,6 +15,8 @@ #include #endif//defined(_WIN32) +using namespace std; + namespace mediakit { //////////////////////////通用/////////////////////// diff --git a/src/Http/strCoding.h b/src/Http/strCoding.h index 6a59b154..4be8328e 100644 --- a/src/Http/strCoding.h +++ b/src/Http/strCoding.h @@ -14,17 +14,15 @@ #include #include -using namespace std; - namespace mediakit { class strCoding { public: - static string UrlEncode(const string &str); //urlutf8 编码 - static string UrlDecode(const string &str); //urlutf8解码 + static std::string UrlEncode(const std::string &str); //urlutf8 编码 + static std::string UrlDecode(const std::string &str); //urlutf8解码 #if defined(_WIN32) - static string UTF8ToGB2312(const string &str);//utf_8转为gb2312 - static string GB2312ToUTF8(const string &str); //gb2312 转utf_8 + static std::string UTF8ToGB2312(const std::string &str);//utf_8转为gb2312 + static std::string GB2312ToUTF8(const std::string &str); //gb2312 转utf_8 #endif//defined(_WIN32) private: strCoding(void); diff --git a/src/Player/MediaPlayer.cpp b/src/Player/MediaPlayer.cpp index 8d564bef..1e0fd572 100644 --- a/src/Player/MediaPlayer.cpp +++ b/src/Player/MediaPlayer.cpp @@ -12,6 +12,8 @@ #include "MediaPlayer.h" #include "Rtmp/RtmpPlayerImp.h" #include "Rtsp/RtspPlayerImp.h" + +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Player/MediaPlayer.h b/src/Player/MediaPlayer.h index 47dae5e9..3f983d3d 100644 --- a/src/Player/MediaPlayer.h +++ b/src/Player/MediaPlayer.h @@ -17,7 +17,6 @@ #include "Rtsp/RtspPlayer.h" #include "Rtmp/RtmpPlayer.h" #include "Thread/TaskExecutor.h" -using namespace toolkit; namespace mediakit { @@ -25,16 +24,16 @@ class MediaPlayer : public PlayerImp { public: using Ptr = std::shared_ptr; - MediaPlayer(const EventPoller::Ptr &poller = nullptr); + MediaPlayer(const toolkit::EventPoller::Ptr &poller = nullptr); ~MediaPlayer() override = default; - void play(const string &url) override; - EventPoller::Ptr getPoller(); - void setOnCreateSocket(Socket::onCreateSocket cb); + void play(const std::string &url) override; + toolkit::EventPoller::Ptr getPoller(); + void setOnCreateSocket(toolkit::Socket::onCreateSocket cb); private: - EventPoller::Ptr _poller; - Socket::onCreateSocket _on_create_socket; + toolkit::EventPoller::Ptr _poller; + toolkit::Socket::onCreateSocket _on_create_socket; }; } /* namespace mediakit */ diff --git a/src/Player/PlayerBase.cpp b/src/Player/PlayerBase.cpp index aa8a0f6d..aa2a8720 100644 --- a/src/Player/PlayerBase.cpp +++ b/src/Player/PlayerBase.cpp @@ -14,6 +14,8 @@ #include "Rtmp/RtmpPlayerImp.h" #include "Http/HlsPlayer.h" #include "Http/TsPlayerImp.h" + +using namespace std; using namespace toolkit; namespace mediakit { @@ -61,10 +63,10 @@ PlayerBase::Ptr PlayerBase::createPlayer(const EventPoller::Ptr &poller, const s } PlayerBase::PlayerBase() { - this->mINI::operator[](kTimeoutMS) = 10000; - this->mINI::operator[](kMediaTimeoutMS) = 5000; - this->mINI::operator[](kBeatIntervalMS) = 5000; - this->mINI::operator[](kWaitTrackReady) = true; + this->mINI::operator[](Client::kTimeoutMS) = 10000; + this->mINI::operator[](Client::kMediaTimeoutMS) = 5000; + this->mINI::operator[](Client::kBeatIntervalMS) = 5000; + this->mINI::operator[](Client::kWaitTrackReady) = true; } ///////////////////////////DemuxerSink////////////////////////////// diff --git a/src/Player/PlayerBase.h b/src/Player/PlayerBase.h index 146b4dd5..b6c0d080 100644 --- a/src/Player/PlayerBase.h +++ b/src/Player/PlayerBase.h @@ -23,16 +23,14 @@ #include "Extension/Frame.h" #include "Extension/Track.h" -using namespace toolkit; - namespace mediakit { -class PlayerBase : public TrackSource, public mINI { +class PlayerBase : public TrackSource, public toolkit::mINI { public: using Ptr = std::shared_ptr; - using Event = std::function; + using Event = std::function; - static Ptr createPlayer(const EventPoller::Ptr &poller, const string &strUrl); + static Ptr createPlayer(const toolkit::EventPoller::Ptr &poller, const std::string &strUrl); PlayerBase(); ~PlayerBase() override = default; @@ -41,7 +39,7 @@ public: * 开始播放 * @param url 视频url,支持rtsp/rtmp */ - virtual void play(const string &url) {}; + virtual void play(const std::string &url) {}; /** * 暂停或恢复 @@ -96,7 +94,7 @@ public: /** * 获取所有track */ - vector getTracks(bool ready = true) const override { return vector(); }; + std::vector getTracks(bool ready = true) const override { return std::vector(); }; /** * 设置一个MediaSource,直接生产rtsp/rtmp代理 @@ -116,12 +114,12 @@ public: /** * 设置播放恢复回调 */ - virtual void setOnResume(const function &cb) = 0; + virtual void setOnResume(const std::function &cb) = 0; protected: virtual void onResume() = 0; - virtual void onShutdown(const SockException &ex) = 0; - virtual void onPlayResult(const SockException &ex) = 0; + virtual void onShutdown(const toolkit::SockException &ex) = 0; + virtual void onPlayResult(const toolkit::SockException &ex) = 0; }; template @@ -133,7 +131,7 @@ public: PlayerImp(ArgsType &&...args) : Parent(std::forward(args)...) {} ~PlayerImp() override = default; - void play(const string &url) override { + void play(const std::string &url) override { return _delegate ? _delegate->play(url) : Parent::play(url); } @@ -173,12 +171,12 @@ public: return _delegate ? _delegate->seekTo(pos) : Parent::seekTo(pos); } - vector getTracks(bool ready = true) const override { + std::vector getTracks(bool ready = true) const override { return _delegate ? _delegate->getTracks(ready) : Parent::getTracks(ready); } - std::shared_ptr getSockInfo() const { - return dynamic_pointer_cast(_delegate); + std::shared_ptr getSockInfo() const { + return std::dynamic_pointer_cast(_delegate); } void setMediaSource(const MediaSource::Ptr &src) override { @@ -188,21 +186,21 @@ public: _media_src = src; } - void setOnShutdown(const function &cb) override { + void setOnShutdown(const std::function &cb) override { if (_delegate) { _delegate->setOnShutdown(cb); } _on_shutdown = cb; } - void setOnPlayResult(const function &cb) override { + void setOnPlayResult(const std::function &cb) override { if (_delegate) { _delegate->setOnPlayResult(cb); } _on_play_result = cb; } - void setOnResume(const function &cb) override { + void setOnResume(const std::function &cb) override { if (_delegate) { _delegate->setOnResume(cb); } @@ -210,14 +208,14 @@ public: } protected: - void onShutdown(const SockException &ex) override { + void onShutdown(const toolkit::SockException &ex) override { if (_on_shutdown) { _on_shutdown(ex); _on_shutdown = nullptr; } } - void onPlayResult(const SockException &ex) override { + void onPlayResult(const toolkit::SockException &ex) override { if (_on_play_result) { _on_play_result(ex); _on_play_result = nullptr; @@ -231,7 +229,7 @@ protected: } protected: - function _on_resume; + std::function _on_resume; PlayerBase::Event _on_shutdown; PlayerBase::Event _on_play_result; MediaSource::Ptr _media_src; @@ -263,7 +261,7 @@ public: ~Demuxer() override = default; void setTrackListener(TrackListener *listener, bool wait_track_ready = false); - vector getTracks(bool trackReady = true) const override; + std::vector getTracks(bool trackReady = true) const override; protected: bool addTrack(const Track::Ptr &track) override; @@ -273,7 +271,7 @@ protected: private: MediaSink::Ptr _sink; TrackListener *_listener = nullptr; - vector _origin_track; + std::vector _origin_track; }; } /* namespace mediakit */ diff --git a/src/Player/PlayerProxy.cpp b/src/Player/PlayerProxy.cpp index e1ba0613..73ceef51 100644 --- a/src/Player/PlayerProxy.cpp +++ b/src/Player/PlayerProxy.cpp @@ -16,6 +16,7 @@ #include "Extension/AAC.h" using namespace toolkit; +using namespace std; namespace mediakit { diff --git a/src/Player/PlayerProxy.h b/src/Player/PlayerProxy.h index 613afe4f..455d325e 100644 --- a/src/Player/PlayerProxy.h +++ b/src/Player/PlayerProxy.h @@ -15,8 +15,6 @@ #include "Common/Device.h" #include "Player/MediaPlayer.h" #include "Util/TimeTicker.h" -using namespace std; -using namespace toolkit; namespace mediakit { @@ -26,9 +24,9 @@ public: //如果retry_count<0,则一直重试播放;否则重试retry_count次数 //默认一直重试 - PlayerProxy(const string &vhost, const string &app, const string &stream_id, + PlayerProxy(const std::string &vhost, const std::string &app, const std::string &stream_id, bool enable_hls = true, bool enable_mp4 = false, - int retry_count = -1, const EventPoller::Ptr &poller = nullptr); + int retry_count = -1, const toolkit::EventPoller::Ptr &poller = nullptr); ~PlayerProxy() override; @@ -36,19 +34,19 @@ public: * 设置play结果回调,只触发一次;在play执行之前有效 * @param cb 回调对象 */ - void setPlayCallbackOnce(const function &cb); + void setPlayCallbackOnce(const std::function &cb); /** * 设置主动关闭回调 * @param cb 回调对象 */ - void setOnClose(const function &cb); + void setOnClose(const std::function &cb); /** * 开始拉流播放 * @param strUrl */ - void play(const string &strUrl) override; + void play(const std::string &strUrl) override; /** * 获取观看总人数 @@ -60,10 +58,10 @@ private: bool close(MediaSource &sender,bool force) override; int totalReaderCount(MediaSource &sender) override; MediaOriginType getOriginType(MediaSource &sender) const override; - string getOriginUrl(MediaSource &sender) const override; - std::shared_ptr getOriginSock(MediaSource &sender) const override; + std::string getOriginUrl(MediaSource &sender) const override; + std::shared_ptr getOriginSock(MediaSource &sender) const override; - void rePlay(const string &strUrl,int iFailedCnt); + void rePlay(const std::string &strUrl,int iFailedCnt); void onPlaySuccess(); void setDirectProxy(); @@ -71,13 +69,13 @@ private: bool _enable_hls; bool _enable_mp4; int _retry_count; - string _vhost; - string _app; - string _stream_id; - string _pull_url; - Timer::Ptr _timer; - function _on_close; - function _on_play; + std::string _vhost; + std::string _app; + std::string _stream_id; + std::string _pull_url; + toolkit::Timer::Ptr _timer; + std::function _on_close; + std::function _on_play; MultiMediaSourceMuxer::Ptr _muxer; }; diff --git a/src/Pusher/MediaPusher.cpp b/src/Pusher/MediaPusher.cpp index f6ee013f..865b4d2a 100644 --- a/src/Pusher/MediaPusher.cpp +++ b/src/Pusher/MediaPusher.cpp @@ -12,6 +12,7 @@ #include "MediaPusher.h" #include "PusherBase.h" +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Pusher/MediaPusher.h b/src/Pusher/MediaPusher.h index d2994cc5..123d6c2c 100644 --- a/src/Pusher/MediaPusher.h +++ b/src/Pusher/MediaPusher.h @@ -15,7 +15,6 @@ #include #include "PusherBase.h" #include "Thread/TaskExecutor.h" -using namespace toolkit; namespace mediakit { @@ -23,25 +22,25 @@ class MediaPusher : public PusherImp { public: typedef std::shared_ptr Ptr; - MediaPusher(const string &schema, - const string &vhost, - const string &app, - const string &stream, - const EventPoller::Ptr &poller = nullptr); + MediaPusher(const std::string &schema, + const std::string &vhost, + const std::string &app, + const std::string &stream, + const toolkit::EventPoller::Ptr &poller = nullptr); MediaPusher(const MediaSource::Ptr &src, - const EventPoller::Ptr &poller = nullptr); + const toolkit::EventPoller::Ptr &poller = nullptr); virtual ~MediaPusher(); - void publish(const string &url) override; - EventPoller::Ptr getPoller(); - void setOnCreateSocket(Socket::onCreateSocket cb); + void publish(const std::string &url) override; + toolkit::EventPoller::Ptr getPoller(); + void setOnCreateSocket(toolkit::Socket::onCreateSocket cb); private: std::weak_ptr _src; - EventPoller::Ptr _poller; - Socket::onCreateSocket _on_create_socket; + toolkit::EventPoller::Ptr _poller; + toolkit::Socket::onCreateSocket _on_create_socket; }; } /* namespace mediakit */ diff --git a/src/Pusher/PusherBase.cpp b/src/Pusher/PusherBase.cpp index 2916ec4d..6d195117 100644 --- a/src/Pusher/PusherBase.cpp +++ b/src/Pusher/PusherBase.cpp @@ -14,43 +14,42 @@ #include "Rtmp/RtmpPusher.h" using namespace toolkit; -using namespace mediakit::Client; namespace mediakit { PusherBase::Ptr PusherBase::createPusher(const EventPoller::Ptr &poller, const MediaSource::Ptr &src, - const string & strUrl) { + const std::string & strUrl) { static auto releasePusher = [](PusherBase *ptr){ onceToken token(nullptr,[&](){ delete ptr; }); ptr->teardown(); }; - string prefix = FindField(strUrl.data(), NULL, "://"); + std::string prefix = FindField(strUrl.data(), NULL, "://"); if (strcasecmp("rtsps",prefix.data()) == 0) { - return PusherBase::Ptr(new TcpClientWithSSL(poller,dynamic_pointer_cast(src)),releasePusher); + return PusherBase::Ptr(new TcpClientWithSSL(poller, std::dynamic_pointer_cast(src)), releasePusher); } if (strcasecmp("rtsp",prefix.data()) == 0) { - return PusherBase::Ptr(new RtspPusherImp(poller,dynamic_pointer_cast(src)),releasePusher); + return PusherBase::Ptr(new RtspPusherImp(poller, std::dynamic_pointer_cast(src)), releasePusher); } if (strcasecmp("rtmps",prefix.data()) == 0) { - return PusherBase::Ptr(new TcpClientWithSSL(poller,dynamic_pointer_cast(src)),releasePusher); + return PusherBase::Ptr(new TcpClientWithSSL(poller, std::dynamic_pointer_cast(src)), releasePusher); } if (strcasecmp("rtmp",prefix.data()) == 0) { - return PusherBase::Ptr(new RtmpPusherImp(poller,dynamic_pointer_cast(src)),releasePusher); + return PusherBase::Ptr(new RtmpPusherImp(poller, std::dynamic_pointer_cast(src)), releasePusher); } - return PusherBase::Ptr(new RtspPusherImp(poller,dynamic_pointer_cast(src)),releasePusher); + return PusherBase::Ptr(new RtspPusherImp(poller, std::dynamic_pointer_cast(src)), releasePusher); } PusherBase::PusherBase() { - this->mINI::operator[](kTimeoutMS) = 10000; - this->mINI::operator[](kBeatIntervalMS) = 5000; + this->mINI::operator[](Client::kTimeoutMS) = 10000; + this->mINI::operator[](Client::kBeatIntervalMS) = 5000; } } /* namespace mediakit */ diff --git a/src/Pusher/PusherBase.h b/src/Pusher/PusherBase.h index 6bf70aab..8d97588b 100644 --- a/src/Pusher/PusherBase.h +++ b/src/Pusher/PusherBase.h @@ -18,18 +18,17 @@ #include "Network/Socket.h" #include "Util/mini.h" #include "Common/MediaSource.h" -using namespace toolkit; namespace mediakit { -class PusherBase : public mINI { +class PusherBase : public toolkit::mINI { public: using Ptr = std::shared_ptr; - using Event = std::function; + using Event = std::function; - static Ptr createPusher(const EventPoller::Ptr &poller, + static Ptr createPusher(const toolkit::EventPoller::Ptr &poller, const MediaSource::Ptr &src, - const string &strUrl); + const std::string &strUrl); PusherBase(); virtual ~PusherBase() = default; @@ -38,7 +37,7 @@ public: * 开始推流 * @param strUrl 视频url,支持rtsp/rtmp */ - virtual void publish(const string &strUrl) {}; + virtual void publish(const std::string &strUrl) {}; /** * 中断推流 @@ -56,8 +55,8 @@ public: virtual void setOnShutdown(const Event &cb) = 0; protected: - virtual void onShutdown(const SockException &ex) = 0; - virtual void onPublishResult(const SockException &ex) = 0; + virtual void onShutdown(const toolkit::SockException &ex) = 0; + virtual void onPublishResult(const toolkit::SockException &ex) = 0; }; template @@ -73,7 +72,7 @@ public: * 开始推流 * @param url 推流url,支持rtsp/rtmp */ - void publish(const string &url) override { + void publish(const std::string &url) override { return _delegate ? _delegate->publish(url) : Parent::publish(url); } @@ -84,8 +83,8 @@ public: return _delegate ? _delegate->teardown() : Parent::teardown(); } - std::shared_ptr getSockInfo() const { - return dynamic_pointer_cast(_delegate); + std::shared_ptr getSockInfo() const { + return std::dynamic_pointer_cast(_delegate); } /** @@ -109,14 +108,14 @@ public: } protected: - void onShutdown(const SockException &ex) override { + void onShutdown(const toolkit::SockException &ex) override { if (_on_shutdown) { _on_shutdown(ex); _on_shutdown = nullptr; } } - void onPublishResult(const SockException &ex) override { + void onPublishResult(const toolkit::SockException &ex) override { if (_on_publish) { _on_publish(ex); _on_publish = nullptr; diff --git a/src/Pusher/PusherProxy.cpp b/src/Pusher/PusherProxy.cpp index 66f65024..22a658e7 100644 --- a/src/Pusher/PusherProxy.cpp +++ b/src/Pusher/PusherProxy.cpp @@ -11,6 +11,7 @@ #include "PusherProxy.h" using namespace toolkit; +using namespace std; namespace mediakit { diff --git a/src/Pusher/PusherProxy.h b/src/Pusher/PusherProxy.h index 02c1f5c1..e8558021 100644 --- a/src/Pusher/PusherProxy.h +++ b/src/Pusher/PusherProxy.h @@ -14,9 +14,6 @@ #include "Pusher/MediaPusher.h" #include "Util/TimeTicker.h" -using namespace std; -using namespace toolkit; - namespace mediakit { class PusherProxy : public MediaPusher, public std::enable_shared_from_this { @@ -25,37 +22,37 @@ public: // 如果retry_count<0,则一直重试播放;否则重试retry_count次数 // 默认一直重试,创建此对象时候,需要外部保证MediaSource存在 - PusherProxy(const MediaSource::Ptr &src, int retry_count = -1, const EventPoller::Ptr &poller = nullptr); + PusherProxy(const MediaSource::Ptr &src, int retry_count = -1, const toolkit::EventPoller::Ptr &poller = nullptr); ~PusherProxy() override; /** * 设置push结果回调,只触发一次;在publish执行之前有效 * @param cb 回调对象 */ - void setPushCallbackOnce(const function &cb); + void setPushCallbackOnce(const std::function &cb); /** * 设置主动关闭回调 * @param cb 回调对象 */ - void setOnClose(const function &cb); + void setOnClose(const std::function &cb); /** * 开始拉流播放 * @param dstUrl 目标推流地址 */ - void publish(const string& dstUrl) override; + void publish(const std::string& dstUrl) override; private: // 重推逻辑函数 - void rePublish(const string &dstUrl, int iFailedCnt); + void rePublish(const std::string &dstUrl, int iFailedCnt); private: int _retry_count; - Timer::Ptr _timer; + toolkit::Timer::Ptr _timer; std::weak_ptr _weak_src; - function _on_close; - function _on_publish; + std::function _on_close; + std::function _on_publish; }; } /* namespace mediakit */ diff --git a/src/Record/HlsMaker.cpp b/src/Record/HlsMaker.cpp index f29f55b1..f16f61c0 100644 --- a/src/Record/HlsMaker.cpp +++ b/src/Record/HlsMaker.cpp @@ -9,6 +9,9 @@ */ #include "HlsMaker.h" + +using namespace std; + namespace mediakit { HlsMaker::HlsMaker(float seg_duration, uint32_t seg_number) { diff --git a/src/Record/HlsMaker.h b/src/Record/HlsMaker.h index dcd96c4a..633b1dbd 100644 --- a/src/Record/HlsMaker.h +++ b/src/Record/HlsMaker.h @@ -18,7 +18,6 @@ #include "Util/File.h" #include "Util/util.h" #include "Util/logger.h" -using namespace toolkit; namespace mediakit { @@ -56,7 +55,7 @@ protected: * @param index * @return */ - virtual string onOpenSegment(uint64_t index) = 0; + virtual std::string onOpenSegment(uint64_t index) = 0; /** * 删除ts切片文件回调 @@ -114,8 +113,8 @@ private: uint32_t _last_timestamp = 0; uint32_t _last_seg_timestamp = 0; uint64_t _file_index = 0; - string _last_file_name; - std::deque > _seg_dur_list; + std::string _last_file_name; + std::deque > _seg_dur_list; }; }//namespace mediakit diff --git a/src/Record/HlsMakerImp.cpp b/src/Record/HlsMakerImp.cpp index 04995cb4..db69664a 100644 --- a/src/Record/HlsMakerImp.cpp +++ b/src/Record/HlsMakerImp.cpp @@ -14,6 +14,7 @@ #include "Util/util.h" #include "Util/uv_errno.h" +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Record/HlsMakerImp.h b/src/Record/HlsMakerImp.h index 93d73356..44dea72b 100644 --- a/src/Record/HlsMakerImp.h +++ b/src/Record/HlsMakerImp.h @@ -17,14 +17,12 @@ #include "HlsMaker.h" #include "HlsMediaSource.h" -using namespace std; - namespace mediakit { class HlsMakerImp : public HlsMaker{ public: - HlsMakerImp(const string &m3u8_file, - const string ¶ms, + HlsMakerImp(const std::string &m3u8_file, + const std::string ¶ms, uint32_t bufSize = 64 * 1024, float seg_duration = 5, uint32_t seg_number = 3); @@ -37,7 +35,7 @@ public: * @param app 应用名 * @param stream_id 流id */ - void setMediaSource(const string &vhost, const string &app, const string &stream_id); + void setMediaSource(const std::string &vhost, const std::string &app, const std::string &stream_id); /** * 获取MediaSource @@ -52,26 +50,26 @@ public: void clearCache(bool immediately = true); protected: - string onOpenSegment(uint64_t index) override ; + 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 char *data, size_t len) override; void onFlushLastSegment(uint32_t duration_ms) override; private: - std::shared_ptr makeFile(const string &file,bool setbuf = false); + std::shared_ptr makeFile(const std::string &file,bool setbuf = false); private: int _buf_size; - string _params; - string _path_hls; - string _path_prefix; + 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; - EventPoller::Ptr _poller; - map _segment_file_paths; + toolkit::EventPoller::Ptr _poller; + std::map _segment_file_paths; }; }//namespace mediakit diff --git a/src/Record/HlsMediaSource.cpp b/src/Record/HlsMediaSource.cpp index 0be2ab31..f1684f79 100644 --- a/src/Record/HlsMediaSource.cpp +++ b/src/Record/HlsMediaSource.cpp @@ -10,6 +10,8 @@ #include "HlsMediaSource.h" +using namespace toolkit; + namespace mediakit{ HlsCookieData::HlsCookieData(const MediaInfo &info, const std::shared_ptr &sock_info) { @@ -21,7 +23,7 @@ HlsCookieData::HlsCookieData(const MediaInfo &info, const std::shared_ptr(MediaSource::find(HLS_SCHEMA,_info._vhost,_info._app,_info._streamid)); + auto src = std::dynamic_pointer_cast(MediaSource::find(HLS_SCHEMA,_info._vhost,_info._app,_info._streamid)); if(src){ *_added = true; _ring_reader = src->getRing()->attach(EventPollerPool::Instance().getPoller()); diff --git a/src/Record/HlsMediaSource.h b/src/Record/HlsMediaSource.h index c31d84c0..3a069f7f 100644 --- a/src/Record/HlsMediaSource.h +++ b/src/Record/HlsMediaSource.h @@ -14,14 +14,17 @@ #include #include "Util/TimeTicker.h" #include "Common/MediaSource.h" + namespace mediakit{ class HlsMediaSource : public MediaSource { public: friend class HlsCookieData; - typedef RingBuffer RingType; - typedef std::shared_ptr Ptr; - HlsMediaSource(const string &vhost, const string &app, const string &stream_id) : MediaSource(HLS_SCHEMA, vhost, app, stream_id){} + + using RingType = toolkit::RingBuffer; + using Ptr = std::shared_ptr; + + HlsMediaSource(const std::string &vhost, const std::string &app, const std::string &stream_id) : MediaSource(HLS_SCHEMA, vhost, app, stream_id){} ~HlsMediaSource() override = default; /** @@ -45,7 +48,7 @@ public: void registHls(bool file_created){ if (!_is_regist) { _is_regist = true; - weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); + std::weak_ptr weakSelf = std::dynamic_pointer_cast(shared_from_this()); auto lam = [weakSelf](int size) { auto strongSelf = weakSelf.lock(); if (!strongSelf) { @@ -65,17 +68,17 @@ public: //m3u8文件生成,发送给播放器 decltype(_list_cb) copy; { - lock_guard lck(_mtx_cb); + std::lock_guard lck(_mtx_cb); copy.swap(_list_cb); } - copy.for_each([](const function &cb) { + copy.for_each([](const std::function &cb) { cb(); }); } - void waitForFile(function cb) { + void waitForFile(std::function cb) { //等待生成m3u8文件 - lock_guard lck(_mtx_cb); + std::lock_guard lck(_mtx_cb); _list_cb.emplace_back(std::move(cb)); } @@ -86,14 +89,14 @@ public: private: bool _is_regist = false; RingType::Ptr _ring; - mutex _mtx_cb; - List > _list_cb; + std::mutex _mtx_cb; + toolkit::List > _list_cb; }; class HlsCookieData{ public: typedef std::shared_ptr Ptr; - HlsCookieData(const MediaInfo &info, const std::shared_ptr &sock_info); + HlsCookieData(const MediaInfo &info, const std::shared_ptr &sock_info); ~HlsCookieData(); void addByteUsage(size_t bytes); @@ -101,14 +104,13 @@ private: void addReaderCount(); private: - atomic _bytes {0}; + std::atomic _bytes {0}; MediaInfo _info; std::shared_ptr _added; - Ticker _ticker; - std::shared_ptr _sock_info; + toolkit::Ticker _ticker; + std::shared_ptr _sock_info; HlsMediaSource::RingType::RingReader::Ptr _ring_reader; }; - }//namespace mediakit #endif //ZLMEDIAKIT_HLSMEDIASOURCE_H diff --git a/src/Record/HlsRecorder.h b/src/Record/HlsRecorder.h index 4be987a4..ff038558 100644 --- a/src/Record/HlsRecorder.h +++ b/src/Record/HlsRecorder.h @@ -20,7 +20,7 @@ class HlsRecorder : public MediaSourceEventInterceptor, public MpegMuxer, public public: using Ptr = std::shared_ptr; - HlsRecorder(const string &m3u8_file, const string ¶ms) : MpegMuxer(false) { + HlsRecorder(const std::string &m3u8_file, const std::string ¶ms) : MpegMuxer(false) { GET_CONFIG(uint32_t, hlsNum, Hls::kSegmentNum); GET_CONFIG(uint32_t, hlsBufSize, Hls::kFileBufSize); GET_CONFIG(float, hlsDuration, Hls::kSegmentDuration); @@ -31,7 +31,7 @@ public: ~HlsRecorder() = default; - void setMediaSource(const string &vhost, const string &app, const string &stream_id) { + void setMediaSource(const std::string &vhost, const std::string &app, const std::string &stream_id) { _hls->setMediaSource(vhost, app, stream_id); } @@ -76,7 +76,7 @@ public: } private: - void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) override { + void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) override { if (!buffer) { _hls->inputData(nullptr, 0, timestamp, key_pos); } else { diff --git a/src/Record/MP4.cpp b/src/Record/MP4.cpp index 845f0a0b..8d92c256 100644 --- a/src/Record/MP4.cpp +++ b/src/Record/MP4.cpp @@ -15,6 +15,8 @@ #include "Common/config.h" using namespace toolkit; +using namespace std; + namespace mediakit { static struct mov_buffer_t s_io = { diff --git a/src/Record/MP4.h b/src/Record/MP4.h index 16e91948..14bc1ca7 100644 --- a/src/Record/MP4.h +++ b/src/Record/MP4.h @@ -24,8 +24,6 @@ #include "mov-buffer.h" #include "mov-format.h" -using namespace std; - namespace mediakit { //mp4文件IO的抽象接口类 @@ -124,7 +122,7 @@ public: /** * 获取并清空文件缓存 */ - string getAndClearMemory(); + std::string getAndClearMemory(); protected: uint64_t onTell() override; @@ -134,7 +132,7 @@ protected: private: uint64_t _offset = 0; - string _memory; + std::string _memory; }; }//namespace mediakit diff --git a/src/Record/MP4Demuxer.cpp b/src/Record/MP4Demuxer.cpp index 4db2278b..36d33d15 100644 --- a/src/Record/MP4Demuxer.cpp +++ b/src/Record/MP4Demuxer.cpp @@ -17,6 +17,8 @@ #include "Extension/G711.h" #include "Extension/Opus.h" using namespace toolkit; +using namespace std; + namespace mediakit { MP4Demuxer::MP4Demuxer() {} diff --git a/src/Record/MP4Demuxer.h b/src/Record/MP4Demuxer.h index 9eb64276..9114784c 100644 --- a/src/Record/MP4Demuxer.h +++ b/src/Record/MP4Demuxer.h @@ -30,7 +30,7 @@ public: * 打开文件 * @param file mp4文件路径 */ - void openMP4(const string &file); + void openMP4(const std::string &file); /** * @brief 关闭 mp4 文件 @@ -57,7 +57,7 @@ public: * @param trackReady 是否要求track为就绪状态 * @return 所有Track */ - vector getTracks(bool trackReady) const override; + std::vector getTracks(bool trackReady) const override; /** * 获取文件长度 @@ -69,14 +69,14 @@ private: int getAllTracks(); void onVideoTrack(uint32_t track_id, uint8_t object, int width, int height, const void *extra, size_t bytes); void onAudioTrack(uint32_t track_id, uint8_t object, int channel_count, int bit_per_sample, int sample_rate, const void *extra, size_t bytes); - Frame::Ptr makeFrame(uint32_t track_id, const Buffer::Ptr &buf, int64_t pts, int64_t dts); + Frame::Ptr makeFrame(uint32_t track_id, const toolkit::Buffer::Ptr &buf, int64_t pts, int64_t dts); private: MP4FileDisk::Ptr _mp4_file; MP4FileDisk::Reader _mov_reader; uint64_t _duration_ms = 0; - map _track_to_codec; - ResourcePool _buffer_pool; + std::map _track_to_codec; + toolkit::ResourcePool _buffer_pool; }; diff --git a/src/Record/MP4Muxer.cpp b/src/Record/MP4Muxer.cpp index fb54152b..a3ccf275 100644 --- a/src/Record/MP4Muxer.cpp +++ b/src/Record/MP4Muxer.cpp @@ -14,6 +14,9 @@ #include "Util/File.h" #include "Extension/H264.h" +using namespace std; +using namespace toolkit; + namespace mediakit { MP4Muxer::MP4Muxer() {} diff --git a/src/Record/MP4Muxer.h b/src/Record/MP4Muxer.h index 0705b3b8..50475224 100644 --- a/src/Record/MP4Muxer.h +++ b/src/Record/MP4Muxer.h @@ -72,7 +72,7 @@ private: int track_id = -1; Stamp stamp; }; - unordered_map _codec_to_trackid; + std::unordered_map _codec_to_trackid; FrameMerger _frame_merger{FrameMerger::mp4_nal_size}; }; @@ -92,7 +92,7 @@ public: * 打开mp4 * @param file 文件完整路径 */ - void openMP4(const string &file); + void openMP4(const std::string &file); /** * 手动关闭文件(对象析构时会自动关闭) @@ -103,7 +103,7 @@ protected: MP4FileIO::Writer createWriter() override; private: - string _file_name; + std::string _file_name; MP4FileDisk::Ptr _mp4_file; }; @@ -125,23 +125,23 @@ public: /** * 获取fmp4 init segment */ - const string &getInitSegment(); + const std::string &getInitSegment(); protected: /** * 输出fmp4切片回调函数 - * @param string 切片内容 + * @param std::string 切片内容 * @param stamp 切片末尾时间戳 * @param key_frame 是否有关键帧 */ - virtual void onSegmentData(string string, uint32_t stamp, bool key_frame) = 0; + virtual void onSegmentData(std::string string, uint32_t stamp, bool key_frame) = 0; protected: MP4FileIO::Writer createWriter() override; private: bool _key_frame = false; - string _init_segment; + std::string _init_segment; MP4FileMemory::Ptr _memory_file; }; diff --git a/src/Record/MP4Reader.cpp b/src/Record/MP4Reader.cpp index 38d33a43..457ec040 100644 --- a/src/Record/MP4Reader.cpp +++ b/src/Record/MP4Reader.cpp @@ -14,6 +14,7 @@ #include "Common/config.h" #include "Thread/WorkThreadPool.h" +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Record/MP4Reader.h b/src/Record/MP4Reader.h index fa055387..a0eca1d1 100644 --- a/src/Record/MP4Reader.h +++ b/src/Record/MP4Reader.h @@ -11,9 +11,10 @@ #ifndef SRC_MEDIAFILE_MEDIAREADER_H_ #define SRC_MEDIAFILE_MEDIAREADER_H_ #ifdef ENABLE_MP4 + #include "MP4Demuxer.h" #include "Common/MultiMediaSourceMuxer.h" -using namespace toolkit; + namespace mediakit { class MP4Reader : public std::enable_shared_from_this, public MediaSourceEvent { @@ -27,7 +28,7 @@ public: * @param stream_id 流id,置空时,只解复用mp4,但是不生成MediaSource * @param file_path 文件路径,如果为空则根据配置文件和上面参数自动生成,否则使用指定的文件 */ - MP4Reader(const string &vhost, const string &app, const string &stream_id, const string &file_path = ""); + MP4Reader(const std::string &vhost, const std::string &app, const std::string &stream_id, const std::string &file_path = ""); ~MP4Reader() override = default; /** @@ -37,7 +38,7 @@ public: * @param ref_self 是否让定时器引用此对象本身,如果无其他对象引用本身,在不循环读文件时,读取文件结束后本对象将自动销毁 * @param file_repeat 是否循环读取文件,如果配置文件设置为循环读文件,此参数无效 */ - void startReadMP4(const EventPoller::Ptr &poller = nullptr, uint64_t sample_ms = 0, bool ref_self = true, bool file_repeat = false); + void startReadMP4(const toolkit::EventPoller::Ptr &poller = nullptr, uint64_t sample_ms = 0, bool ref_self = true, bool file_repeat = false); /** * 停止解复用MP4定时器 @@ -58,7 +59,7 @@ private: bool close(MediaSource &sender,bool force) override; int totalReaderCount(MediaSource &sender) override; MediaOriginType getOriginType(MediaSource &sender) const override; - string getOriginUrl(MediaSource &sender) const override; + std::string getOriginUrl(MediaSource &sender) const override; bool readSample(); bool readNextSample(); @@ -73,10 +74,10 @@ private: float _speed = 1.0; uint32_t _last_dts = 0; uint32_t _seek_to = 0; - string _file_path; - recursive_mutex _mtx; - Ticker _seek_ticker; - Timer::Ptr _timer; + std::string _file_path; + std::recursive_mutex _mtx; + toolkit::Ticker _seek_ticker; + toolkit::Timer::Ptr _timer; MP4Demuxer::Ptr _demuxer; MultiMediaSourceMuxer::Ptr _muxer; }; diff --git a/src/Record/MP4Recorder.cpp b/src/Record/MP4Recorder.cpp index 5ae7d807..d5c4ae64 100644 --- a/src/Record/MP4Recorder.cpp +++ b/src/Record/MP4Recorder.cpp @@ -16,6 +16,7 @@ #include "MP4Recorder.h" #include "Thread/WorkThreadPool.h" +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Record/MP4Recorder.h b/src/Record/MP4Recorder.h index 16937f0e..9989d4e4 100644 --- a/src/Record/MP4Recorder.h +++ b/src/Record/MP4Recorder.h @@ -21,8 +21,6 @@ #include "Common/MediaSink.h" #include "MP4Muxer.h" -using namespace toolkit; - namespace mediakit { #ifdef ENABLE_MP4 @@ -30,7 +28,7 @@ class MP4Recorder : public MediaSinkInterface { public: using Ptr = std::shared_ptr; - MP4Recorder(const string &path, const string &vhost, const string &app, const string &stream_id, size_t max_second); + MP4Recorder(const std::string &path, const std::string &vhost, const std::string &app, const std::string &stream_id, size_t max_second); ~MP4Recorder() override; /** @@ -56,12 +54,12 @@ private: private: bool _have_video = false; size_t _max_second; - string _folder_path; - string _full_path; - string _full_path_tmp; + std::string _folder_path; + std::string _full_path; + std::string _full_path_tmp; RecordInfo _info; MP4Muxer::Ptr _muxer; - list _tracks; + std::list _tracks; uint64_t _last_dts = 0; }; diff --git a/src/Record/MPEG.cpp b/src/Record/MPEG.cpp index 6d8d4894..16dd3e4b 100644 --- a/src/Record/MPEG.cpp +++ b/src/Record/MPEG.cpp @@ -13,8 +13,11 @@ #if defined(ENABLE_HLS) || defined(ENABLE_RTPPROXY) +#include "mpeg-ts-proto.h" #include "mpeg-muxer.h" +using namespace toolkit; + namespace mediakit{ MpegMuxer::MpegMuxer(bool is_ps) { @@ -32,7 +35,7 @@ MpegMuxer::~MpegMuxer() { if (mpeg_id == PSI_STREAM_RESERVED) { \ break; \ } \ - _codec_to_trackid[track->getCodecId()] = mpeg_muxer_add_stream(_context, mpeg_id, nullptr, 0); \ + _codec_to_trackid[track->getCodecId()] = mpeg_muxer_add_stream((::mpeg_muxer_t *)_context, mpeg_id, nullptr, 0); \ return true; \ } @@ -65,7 +68,7 @@ bool MpegMuxer::inputFrame(const Frame::Ptr &frame) { //取视频时间戳为TS的时间戳 _timestamp = (uint32_t) dts; _max_cache_size = 512 + 1.2 * buffer->size(); - mpeg_muxer_input(_context, track_id, have_idr ? 0x0001 : 0, pts * 90LL,dts * 90LL, buffer->data(), buffer->size()); + mpeg_muxer_input((::mpeg_muxer_t *)_context, track_id, have_idr ? 0x0001 : 0, pts * 90LL,dts * 90LL, buffer->data(), buffer->size()); flushCache(); }); } @@ -83,7 +86,7 @@ bool MpegMuxer::inputFrame(const Frame::Ptr &frame) { _timestamp = (uint32_t) frame->dts(); } _max_cache_size = 512 + 1.2 * frame->size(); - mpeg_muxer_input(_context, track_id, frame->keyFrame() ? 0x0001 : 0, frame->pts() * 90LL, frame->dts() * 90LL, frame->data(), frame->size()); + mpeg_muxer_input((::mpeg_muxer_t *)_context, track_id, frame->keyFrame() ? 0x0001 : 0, frame->pts() * 90LL, frame->dts() * 90LL, frame->data(), frame->size()); flushCache(); return true; } @@ -127,7 +130,7 @@ void MpegMuxer::createContext() { } }; if (_context == nullptr) { - _context = mpeg_muxer_create(_is_ps, &func, this); + _context = (struct mpeg_muxer_t *)mpeg_muxer_create(_is_ps, &func, this); } } @@ -143,7 +146,7 @@ void MpegMuxer::flushCache() { void MpegMuxer::releaseContext() { if (_context) { - mpeg_muxer_destroy(_context); + mpeg_muxer_destroy((::mpeg_muxer_t *)_context); _context = nullptr; } _codec_to_trackid.clear(); diff --git a/src/Record/MPEG.h b/src/Record/MPEG.h index 3bb41a91..e1e2862a 100644 --- a/src/Record/MPEG.h +++ b/src/Record/MPEG.h @@ -52,7 +52,7 @@ protected: * @param timestamp 时间戳,单位毫秒 * @param key_pos 是否为关键帧的第一个ts/ps包,用于确保ts切片第一帧为关键帧 */ - virtual void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) = 0; + virtual void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) = 0; private: void createContext(); @@ -67,10 +67,10 @@ private: uint32_t _max_cache_size = 0; uint32_t _timestamp = 0; struct mpeg_muxer_t *_context = nullptr; - unordered_map _codec_to_trackid; + std::unordered_map _codec_to_trackid; FrameMerger _frame_merger{FrameMerger::h264_prefix}; - BufferRaw::Ptr _current_buffer; - ResourcePool _buffer_pool; + toolkit::BufferRaw::Ptr _current_buffer; + toolkit::ResourcePool _buffer_pool; }; }//mediakit @@ -90,7 +90,7 @@ public: bool inputFrame(const Frame::Ptr &frame) override { return false; } protected: - virtual void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) = 0; + virtual void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) = 0; }; }//namespace mediakit diff --git a/src/Record/Recorder.cpp b/src/Record/Recorder.cpp index cba7b319..1ef76465 100644 --- a/src/Record/Recorder.cpp +++ b/src/Record/Recorder.cpp @@ -14,6 +14,7 @@ #include "MP4Recorder.h" #include "HlsRecorder.h" +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Record/Recorder.h b/src/Record/Recorder.h index ade8654c..47f36f49 100644 --- a/src/Record/Recorder.h +++ b/src/Record/Recorder.h @@ -12,7 +12,7 @@ #define SRC_MEDIAFILE_RECORDER_H_ #include #include -using namespace std; + namespace mediakit { class MediaSinkInterface; @@ -21,13 +21,13 @@ public: time_t start_time; // GMT 标准时间,单位秒 float time_len; // 录像长度,单位秒 off_t file_size; // 文件大小,单位 BYTE - string file_path; // 文件路径 - string file_name; // 文件名称 - string folder; // 文件夹路径 - string url; // 播放路径 - string app; // 应用名称 - string stream; // 流 ID - string vhost; // 虚拟主机 + std::string file_path; // 文件路径 + std::string file_name; // 文件名称 + std::string folder; // 文件夹路径 + std::string url; // 播放路径 + std::string app; // 应用名称 + std::string stream; // 流 ID + std::string vhost; // 虚拟主机 }; class Recorder{ @@ -48,7 +48,7 @@ public: * @param customized_path 录像文件保存自定义根目录,为空则采用配置文件设置 * @return 录制文件绝对路径 */ - static string getRecordPath(type type, const string &vhost, const string &app, const string &stream_id,const string &customized_path = ""); + static std::string getRecordPath(type type, const std::string &vhost, const std::string &app, const std::string &stream_id,const std::string &customized_path = ""); /** * 创建录制器对象 @@ -60,7 +60,7 @@ public: * @param max_second mp4录制最大切片时间,单位秒,置0则采用配置文件配置 * @return 对象指针,可能为nullptr */ - static std::shared_ptr createRecorder(type type, const string &vhost, const string &app, const string &stream_id, const string &customized_path = "", size_t max_second = 0); + static std::shared_ptr createRecorder(type type, const std::string &vhost, const std::string &app, const std::string &stream_id, const std::string &customized_path = "", size_t max_second = 0); /** * 获取录制状态 @@ -70,7 +70,7 @@ public: * @param stream_id 流id * @return 是否真正录制 */ - static bool isRecording(type type, const string &vhost, const string &app, const string &stream_id); + static bool isRecording(type type, const std::string &vhost, const std::string &app, const std::string &stream_id); /** * 开始录制 @@ -81,7 +81,7 @@ public: * @param customized_path 录像文件保存自定义根目录,为空则采用配置文件设置 * @return 成功与否 */ - static bool startRecord(type type, const string &vhost, const string &app, const string &stream_id,const string &customized_path, size_t max_second); + static bool startRecord(type type, const std::string &vhost, const std::string &app, const std::string &stream_id,const std::string &customized_path, size_t max_second); /** * 停止录制 @@ -90,7 +90,7 @@ public: * @param app 应用名 * @param stream_id 流id */ - static bool stopRecord(type type, const string &vhost, const string &app, const string &stream_id); + static bool stopRecord(type type, const std::string &vhost, const std::string &app, const std::string &stream_id); private: Recorder() = delete; diff --git a/src/Rtcp/Rtcp.cpp b/src/Rtcp/Rtcp.cpp index 33c53e9d..ea6533d3 100644 --- a/src/Rtcp/Rtcp.cpp +++ b/src/Rtcp/Rtcp.cpp @@ -14,6 +14,9 @@ #include "Util/logger.h" #include "RtcpFCI.h" +using namespace std; +using namespace toolkit; + namespace mediakit { const char *rtcpTypeToStr(RtcpType type){ diff --git a/src/Rtcp/Rtcp.h b/src/Rtcp/Rtcp.h index c94ce064..29a334e6 100644 --- a/src/Rtcp/Rtcp.h +++ b/src/Rtcp/Rtcp.h @@ -16,8 +16,6 @@ #include "Util/util.h" #include "Network/Buffer.h" #include "Common/macros.h" -using namespace std; -using namespace toolkit; namespace mediakit { @@ -191,21 +189,21 @@ public: * @param size 数据总长度 * @return rtcp对象列表,无需free */ - static vector loadFromBytes(char *data, size_t size); + static std::vector loadFromBytes(char *data, size_t size); /** * rtcp包转Buffer对象 * @param rtcp rtcp包对象智能指针 * @return Buffer对象 */ - static Buffer::Ptr toBuffer(std::shared_ptr rtcp); + static toolkit::Buffer::Ptr toBuffer(std::shared_ptr rtcp); /** * 打印rtcp相关字段详情(调用派生类的dumpString函数) * 内部会判断是什么类型的派生类 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; /** * 根据length字段获取rtcp总长度 @@ -229,7 +227,7 @@ protected: * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpHeader() const; + std::string dumpHeader() const; private: /** @@ -269,7 +267,7 @@ private: * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; /** * 网络字节序转换为主机字节序 @@ -353,21 +351,21 @@ public: * 返回ntp时间的字符串 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string getNtpStamp() const; + std::string getNtpStamp() const; uint64_t getNtpUnixStampMS() const; /** * 获取ReportItem对象指针列表 * 使用net2Host转换成主机字节序后才可使用此函数 */ - vector getItemList(); + std::vector getItemList(); private: /** * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; /** * 网络字节序转换为主机字节序 @@ -429,7 +427,7 @@ public: * 获取ReportItem对象指针列表 * 使用net2Host转换成主机字节序后才可使用此函数 */ - vector getItemList(); + std::vector getItemList(); private: /** @@ -442,7 +440,7 @@ private: * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; } PACKED; @@ -509,7 +507,7 @@ private: * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; /** * 网络字节序转换为主机字节序 @@ -531,20 +529,20 @@ public: * @param item_text SdesChunk列表,只赋值length和text部分 * @return SDES包 */ - static std::shared_ptr create(const std::vector &item_text); + static std::shared_ptr create(const std::vector &item_text); /** * 获取SdesChunk对象指针列表 * 使用net2Host转换成主机字节序后才可使用此函数 */ - vector getChunkList(); + std::vector getChunkList(); private: /** * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; /** * 网络字节序转换为主机字节序 @@ -617,7 +615,7 @@ private: * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; /** * 网络字节序转换为主机字节序 @@ -663,24 +661,24 @@ public: * @param reason 原因 * @return rtcp bye包 */ - static std::shared_ptr create(const std::vector &ssrc, const string &reason); + static std::shared_ptr create(const std::vector &ssrc, const std::string &reason); /** * 获取ssrc列表 */ - vector getSSRC(); + std::vector getSSRC(); /** * 获取原因 */ - string getReason() const; + std::string getReason() const; private: /** * 打印字段详情 * 使用net2Host转换成主机字节序后才可使用此函数 */ - string dumpString() const; + std::string dumpString() const; /** * 网络字节序转换为主机字节序 diff --git a/src/Rtcp/RtcpContext.h b/src/Rtcp/RtcpContext.h index 6604d5ff..59341b05 100644 --- a/src/Rtcp/RtcpContext.h +++ b/src/Rtcp/RtcpContext.h @@ -53,7 +53,7 @@ public: * @param rtcp_ssrc rtcp的ssrc * @return rtcp包 */ - virtual Buffer::Ptr createRtcpSR(uint32_t rtcp_ssrc); + virtual toolkit::Buffer::Ptr createRtcpSR(uint32_t rtcp_ssrc); /** * 创建RR rtcp包 @@ -61,7 +61,7 @@ public: * @param rtp_ssrc rtp的ssrc * @return rtcp包 */ - virtual Buffer::Ptr createRtcpRR(uint32_t rtcp_ssrc, uint32_t rtp_ssrc); + virtual toolkit::Buffer::Ptr createRtcpRR(uint32_t rtcp_ssrc, uint32_t rtp_ssrc); /** * 上次结果与本次结果间应收包数 @@ -85,7 +85,7 @@ protected: class RtcpContextForSend : public RtcpContext { public: - Buffer::Ptr createRtcpSR(uint32_t rtcp_ssrc) override; + toolkit::Buffer::Ptr createRtcpSR(uint32_t rtcp_ssrc) override; void onRtcp(RtcpHeader *rtcp) override; /** @@ -96,14 +96,14 @@ public: uint32_t getRtt(uint32_t ssrc) const; private: - map _rtt; - map _sender_report_ntp; + std::map _rtt; + std::map _sender_report_ntp; }; class RtcpContextForRecv : public RtcpContext { public: void onRtp(uint16_t seq, uint32_t stamp, uint64_t ntp_stamp_ms, uint32_t sample_rate, size_t bytes) override; - Buffer::Ptr createRtcpRR(uint32_t rtcp_ssrc, uint32_t rtp_ssrc) override; + toolkit::Buffer::Ptr createRtcpRR(uint32_t rtcp_ssrc, uint32_t rtp_ssrc) override; size_t getExpectedPackets() const override; size_t getExpectedPacketsInterval() override; size_t getLost() override; diff --git a/src/Rtcp/RtcpFCI.cpp b/src/Rtcp/RtcpFCI.cpp index f9ff90df..2bc8e27f 100644 --- a/src/Rtcp/RtcpFCI.cpp +++ b/src/Rtcp/RtcpFCI.cpp @@ -10,6 +10,8 @@ #include "RtcpFCI.h" #include "Util/logger.h" + +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Rtcp/RtcpFCI.h b/src/Rtcp/RtcpFCI.h index 9681048b..46ba005a 100644 --- a/src/Rtcp/RtcpFCI.h +++ b/src/Rtcp/RtcpFCI.h @@ -52,7 +52,7 @@ public: uint16_t getFirst() const; uint16_t getNumber() const; uint8_t getPicID() const; - string dumpString() const; + std::string dumpString() const; private: uint32_t data; @@ -118,7 +118,7 @@ public: uint32_t getSSRC() const; uint8_t getSeq() const; uint32_t getReserved() const; - string dumpString() const; + std::string dumpString() const; private: uint32_t ssrc; @@ -215,11 +215,11 @@ class FCI_REMB { public: static size_t constexpr kSize = 8; - static string create(const std::vector &ssrcs, uint32_t bitrate); + static std::string create(const std::vector &ssrcs, uint32_t bitrate); void check(size_t size); - string dumpString() const; + std::string dumpString() const; uint32_t getBitRate() const; - vector getSSRC(); + std::vector getSSRC(); private: //Unique identifier 'R' 'E' 'M' 'B' @@ -245,14 +245,15 @@ public: static constexpr size_t kSize = 4; static constexpr size_t kBitSize = 16; - FCI_NACK(uint16_t pid_h, const vector &type); + FCI_NACK(uint16_t pid_h, const std::vector &type); void check(size_t size); uint16_t getPid() const; uint16_t getBlp() const; //返回丢包列表,总长度17,第一个包必丢 - vector getBitArray() const; - string dumpString() const; + // TODO: replace std::bitset + std::vector getBitArray() const; + std::string dumpString() const; private: // The PID field is used to specify a lost packet. The PID field @@ -346,16 +347,16 @@ enum class SymbolStatus : uint8_t{ class FCI_TWCC{ public: static size_t constexpr kSize = 8; - using TwccPacketStatus = map >; + using TwccPacketStatus = std::map >; void check(size_t size); - string dumpString(size_t total_size) const; + std::string dumpString(size_t total_size) const; uint16_t getBaseSeq() const; //单位64ms uint32_t getReferenceTime() const; uint16_t getPacketCount() const; TwccPacketStatus getPacketChunkList(size_t total_size) const; - static string create(uint32_t ref_time, uint8_t fb_pkt_count, TwccPacketStatus &status); + static std::string create(uint32_t ref_time, uint8_t fb_pkt_count, TwccPacketStatus &status); private: //base sequence number,基础序号,本次反馈的第一个包的序号;也就是RTP扩展头的序列号 diff --git a/src/Rtmp/FlvMuxer.cpp b/src/Rtmp/FlvMuxer.cpp index e59bbaca..a58dd665 100644 --- a/src/Rtmp/FlvMuxer.cpp +++ b/src/Rtmp/FlvMuxer.cpp @@ -14,6 +14,9 @@ #define FILE_BUF_SIZE (64 * 1024) +using namespace std; +using namespace toolkit; + namespace mediakit { FlvMuxer::FlvMuxer(){ diff --git a/src/Rtmp/FlvMuxer.h b/src/Rtmp/FlvMuxer.h index 8c0d63cd..eabbf318 100644 --- a/src/Rtmp/FlvMuxer.h +++ b/src/Rtmp/FlvMuxer.h @@ -15,7 +15,6 @@ #include "Rtmp/RtmpMediaSource.h" #include "Network/Socket.h" #include "Common/Stamp.h" -using namespace toolkit; namespace mediakit { @@ -28,8 +27,8 @@ public: void stop(); protected: - void start(const EventPoller::Ptr &poller, const RtmpMediaSource::Ptr &media, uint32_t start_pts = 0); - virtual void onWrite(const Buffer::Ptr &data, bool flush) = 0; + void start(const toolkit::EventPoller::Ptr &poller, const RtmpMediaSource::Ptr &media, uint32_t start_pts = 0); + virtual void onWrite(const toolkit::Buffer::Ptr &data, bool flush) = 0; virtual void onDetach() = 0; virtual std::shared_ptr getSharedPtr() = 0; @@ -37,12 +36,12 @@ private: void onWriteFlvHeader(const RtmpMediaSource::Ptr &src); void onWriteRtmp(const RtmpPacket::Ptr &pkt, bool flush); void onWriteFlvTag(const RtmpPacket::Ptr &pkt, uint32_t time_stamp, bool flush); - void onWriteFlvTag(uint8_t type, const Buffer::Ptr &buffer, uint32_t time_stamp, bool flush); - BufferRaw::Ptr obtainBuffer(const void *data, size_t len); - BufferRaw::Ptr obtainBuffer(); + void onWriteFlvTag(uint8_t type, const toolkit::Buffer::Ptr &buffer, uint32_t time_stamp, bool flush); + toolkit::BufferRaw::Ptr obtainBuffer(const void *data, size_t len); + toolkit::BufferRaw::Ptr obtainBuffer(); private: - ResourcePool _packet_pool; + toolkit::ResourcePool _packet_pool; RtmpMediaSource::RingType::RingReader::Ptr _ring_reader; }; @@ -52,17 +51,17 @@ public: FlvRecorder() = default; ~FlvRecorder() override = default; - void startRecord(const EventPoller::Ptr &poller, const RtmpMediaSource::Ptr &media, const string &file_path); - void startRecord(const EventPoller::Ptr &poller, const string &vhost, const string &app, const string &stream, const string &file_path); + void startRecord(const toolkit::EventPoller::Ptr &poller, const RtmpMediaSource::Ptr &media, const std::string &file_path); + void startRecord(const toolkit::EventPoller::Ptr &poller, const std::string &vhost, const std::string &app, const std::string &stream, const std::string &file_path); private: - virtual void onWrite(const Buffer::Ptr &data, bool flush) override ; + virtual void onWrite(const toolkit::Buffer::Ptr &data, bool flush) override ; virtual void onDetach() override; virtual std::shared_ptr getSharedPtr() override; private: std::shared_ptr _file; - recursive_mutex _file_mtx; + std::recursive_mutex _file_mtx; }; }//namespace mediakit diff --git a/src/Rtmp/Rtmp.cpp b/src/Rtmp/Rtmp.cpp index 97a5fa6e..85c61643 100644 --- a/src/Rtmp/Rtmp.cpp +++ b/src/Rtmp/Rtmp.cpp @@ -49,7 +49,7 @@ AudioMeta::AudioMeta(const AudioTrack::Ptr &audio){ uint8_t getAudioRtmpFlags(const Track::Ptr &track){ switch (track->getTrackType()){ case TrackAudio : { - auto audioTrack = dynamic_pointer_cast(track); + auto audioTrack = std::dynamic_pointer_cast(track); if (!audioTrack) { WarnL << "获取AudioTrack失败"; return 0; @@ -116,11 +116,11 @@ void Metadata::addTrack(AMFValue &metadata, const Track::Ptr &track) { Metadata::Ptr new_metadata; switch (track->getTrackType()) { case TrackVideo: { - new_metadata = std::make_shared(dynamic_pointer_cast(track)); + new_metadata = std::make_shared(std::dynamic_pointer_cast(track)); } break; case TrackAudio: { - new_metadata = std::make_shared(dynamic_pointer_cast(track)); + new_metadata = std::make_shared(std::dynamic_pointer_cast(track)); } break; default: diff --git a/src/Rtmp/Rtmp.h b/src/Rtmp/Rtmp.h index e197efe8..e8f58401 100644 --- a/src/Rtmp/Rtmp.h +++ b/src/Rtmp/Rtmp.h @@ -21,8 +21,6 @@ #include "amf.h" #include "Extension/Track.h" -using namespace toolkit; - #if !defined(_WIN32) #define PACKED __attribute__((packed)) #else @@ -175,7 +173,7 @@ public: #pragma pack(pop) #endif // defined(_WIN32) -class RtmpPacket : public Buffer{ +class RtmpPacket : public toolkit::Buffer{ public: friend class RtmpProtocol; using Ptr = std::shared_ptr; @@ -186,7 +184,7 @@ public: uint32_t stream_index; uint32_t chunk_id; size_t body_size; - BufferLikeString buffer; + toolkit::BufferLikeString buffer; public: static Ptr create(); @@ -259,7 +257,7 @@ public: } private: - friend class ResourcePool_l; + friend class toolkit::ResourcePool_l; RtmpPacket(){ clear(); } @@ -276,7 +274,7 @@ private: private: //对象个数统计 - ObjectStatistic _statistic; + toolkit::ObjectStatistic _statistic; }; /** @@ -306,7 +304,7 @@ public: TitleMeta(float dur_sec = 0, size_t fileSize = 0, - const map &header = map()){ + const std::map &header = std::map()){ _metadata.set("duration", dur_sec); _metadata.set("fileSize", (int)fileSize); _metadata.set("server",kServerName); diff --git a/src/Rtmp/RtmpCodec.h b/src/Rtmp/RtmpCodec.h index 8e409718..baa61084 100644 --- a/src/Rtmp/RtmpCodec.h +++ b/src/Rtmp/RtmpCodec.h @@ -14,32 +14,29 @@ #include "Rtmp/Rtmp.h" #include "Extension/Frame.h" #include "Util/RingBuffer.h" -using namespace toolkit; namespace mediakit{ -class RtmpRing{ +class RtmpRing { public: - typedef std::shared_ptr Ptr; - typedef RingBuffer RingType; + using Ptr = std::shared_ptr; + using RingType = toolkit::RingBuffer; - RtmpRing() {} - virtual ~RtmpRing() {} + RtmpRing() = default; + virtual ~RtmpRing() = default; /** * 获取rtmp环形缓存 - * @return */ virtual RingType::Ptr getRtmpRing() const { - return _rtmpRing; + return _ring; } /** * 设置rtmp环形缓存 - * @param ring */ virtual void setRtmpRing(const RingType::Ptr &ring) { - _rtmpRing = ring; + _ring = ring; } /** @@ -47,13 +44,13 @@ public: * @param rtmp rtmp包 */ virtual void inputRtmp(const RtmpPacket::Ptr &rtmp) { - if (_rtmpRing) { - _rtmpRing->write(rtmp, rtmp->isVideoKeyFrame()); + if (_ring) { + _ring->write(rtmp, rtmp->isVideoKeyFrame()); } } protected: - RingType::Ptr _rtmpRing; + RingType::Ptr _ring; }; class RtmpCodec : public RtmpRing, public FrameDispatcher , public CodecInfo{ diff --git a/src/Rtmp/RtmpDemuxer.cpp b/src/Rtmp/RtmpDemuxer.cpp index c7c3dd18..f9076f0b 100644 --- a/src/Rtmp/RtmpDemuxer.cpp +++ b/src/Rtmp/RtmpDemuxer.cpp @@ -11,6 +11,8 @@ #include "RtmpDemuxer.h" #include "Extension/Factory.h" +using namespace std; + namespace mediakit { size_t RtmpDemuxer::trackCount(const AMFValue &metadata) { diff --git a/src/Rtmp/RtmpDemuxer.h b/src/Rtmp/RtmpDemuxer.h index cce7cbd5..f9e76a87 100644 --- a/src/Rtmp/RtmpDemuxer.h +++ b/src/Rtmp/RtmpDemuxer.h @@ -19,8 +19,6 @@ #include "Util/TimeTicker.h" #include "RtmpCodec.h" -using namespace toolkit; - namespace mediakit { class RtmpDemuxer : public Demuxer { diff --git a/src/Rtmp/RtmpMediaSource.h b/src/Rtmp/RtmpMediaSource.h index 1c6a302d..a08b4e49 100644 --- a/src/Rtmp/RtmpMediaSource.h +++ b/src/Rtmp/RtmpMediaSource.h @@ -28,9 +28,9 @@ #include "Util/ResourcePool.h" #include "Util/NoticeCenter.h" #include "Thread/ThreadPool.h" -using namespace toolkit; #define RTMP_GOP_SIZE 512 + namespace mediakit { /** @@ -40,11 +40,11 @@ namespace mediakit { * 只要生成了这三要素,那么要实现rtmp推流、rtmp服务器就很简单了 * rtmp推拉流协议中,先传递metadata,然后传递config帧,然后一直传递普通帧 */ -class RtmpMediaSource : public MediaSource, public RingDelegate, private PacketCache{ +class RtmpMediaSource : public MediaSource, public toolkit::RingDelegate, private PacketCache{ public: - typedef std::shared_ptr Ptr; - typedef std::shared_ptr > RingDataType; - typedef RingBuffer RingType; + using Ptr = std::shared_ptr; + using RingDataType = std::shared_ptr >; + using RingType = toolkit::RingBuffer; /** * 构造函数 @@ -53,9 +53,9 @@ public: * @param stream_id 流id * @param ring_size 可以设置固定的环形缓冲大小,0则自适应 */ - RtmpMediaSource(const string &vhost, - const string &app, - const string &stream_id, + RtmpMediaSource(const std::string &vhost, + const std::string &app, + const std::string &stream_id, int ring_size = RTMP_GOP_SIZE) : MediaSource(RTMP_SCHEMA, vhost, app, stream_id), _ring_size(ring_size) { } @@ -81,7 +81,7 @@ public: * 获取metadata */ const AMFValue &getMetaData() const { - lock_guard lock(_mtx); + std::lock_guard lock(_mtx); return _metadata; } @@ -90,7 +90,7 @@ public: */ template void getConfigFrame(const FUNC &f) { - lock_guard lock(_mtx); + std::lock_guard lock(_mtx); for (auto &pr : _config_frame_map) { f(pr.second); } @@ -113,7 +113,7 @@ public: * 更新metadata */ void updateMetaData(const AMFValue &metadata) { - lock_guard lock(_mtx); + std::lock_guard lock(_mtx); _metadata = metadata; } @@ -132,7 +132,7 @@ public: } if (pkt->isCfgFrame()) { - lock_guard lock(_mtx); + std::lock_guard lock(_mtx); _config_frame_map[pkt->type_id] = pkt; if (!_ring) { //注册后收到config帧更新到各播放器 @@ -141,7 +141,7 @@ public: } if (!_ring) { - weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); + std::weak_ptr weakSelf = std::dynamic_pointer_cast(shared_from_this()); auto lam = [weakSelf](int size) { auto strongSelf = weakSelf.lock(); if (!strongSelf) { @@ -203,7 +203,7 @@ private: * @param rtmp_list rtmp包列表 * @param key_pos 是否包含关键帧 */ - void onFlush(std::shared_ptr > rtmp_list, bool key_pos) override { + void onFlush(std::shared_ptr > rtmp_list, bool key_pos) override { //如果不存在视频,那么就没有存在GOP缓存的意义,所以is_key一直为true确保一直清空GOP缓存 _ring->write(std::move(rtmp_list), _have_video ? key_pos : true); } @@ -216,8 +216,8 @@ private: AMFValue _metadata; RingType::Ptr _ring; - mutable recursive_mutex _mtx; - unordered_map _config_frame_map; + mutable std::recursive_mutex _mtx; + std::unordered_map _config_frame_map; }; } /* namespace mediakit */ diff --git a/src/Rtmp/RtmpMediaSourceImp.h b/src/Rtmp/RtmpMediaSourceImp.h index 692a7beb..f03068c6 100644 --- a/src/Rtmp/RtmpMediaSourceImp.h +++ b/src/Rtmp/RtmpMediaSourceImp.h @@ -23,10 +23,9 @@ #include "RtmpMediaSource.h" #include "RtmpDemuxer.h" #include "Common/MultiMediaSourceMuxer.h" -using namespace std; -using namespace toolkit; namespace mediakit { + class RtmpMediaSourceImp: public RtmpMediaSource, private TrackListener, public MultiMediaSourceMuxer::Listener { public: typedef std::shared_ptr Ptr; @@ -38,7 +37,7 @@ public: * @param id 流id * @param ringSize 环形缓存大小 */ - RtmpMediaSourceImp(const string &vhost, const string &app, const string &id, int ringSize = RTMP_GOP_SIZE) : RtmpMediaSource(vhost, app, id, ringSize) { + RtmpMediaSourceImp(const std::string &vhost, const std::string &app, const std::string &id, int ringSize = RTMP_GOP_SIZE) : RtmpMediaSource(vhost, app, id, ringSize) { _demuxer = std::make_shared(); _demuxer->setTrackListener(this); } @@ -84,7 +83,7 @@ public: //不重复生成rtmp _muxer = std::make_shared(getVhost(), getApp(), getId(), _demuxer->getDuration(), true, false, enableHls, enableMP4); _muxer->setMediaListener(getListener()); - _muxer->setTrackListener(static_pointer_cast(shared_from_this())); + _muxer->setTrackListener(std::static_pointer_cast(shared_from_this())); //让_muxer对象拦截一部分事件(比如说录像相关事件) MediaSource::setListener(_muxer); diff --git a/src/Rtmp/RtmpMediaSourceMuxer.h b/src/Rtmp/RtmpMediaSourceMuxer.h index b43eec06..7134c71b 100644 --- a/src/Rtmp/RtmpMediaSourceMuxer.h +++ b/src/Rtmp/RtmpMediaSourceMuxer.h @@ -21,9 +21,9 @@ class RtmpMediaSourceMuxer : public RtmpMuxer, public MediaSourceEventIntercepto public: typedef std::shared_ptr Ptr; - RtmpMediaSourceMuxer(const string &vhost, - const string &strApp, - const string &strId, + RtmpMediaSourceMuxer(const std::string &vhost, + const std::string &strApp, + const std::string &strId, const TitleMeta::Ptr &title = nullptr) : RtmpMuxer(title){ _media_src = std::make_shared(vhost, strApp, strId); getRtmpRing()->setDelegate(_media_src); diff --git a/src/Rtmp/RtmpPlayer.cpp b/src/Rtmp/RtmpPlayer.cpp index 9281f5b4..bc454b49 100644 --- a/src/Rtmp/RtmpPlayer.cpp +++ b/src/Rtmp/RtmpPlayer.cpp @@ -14,7 +14,7 @@ #include "Util/onceToken.h" #include "Thread/ThreadPool.h" using namespace toolkit; -using namespace mediakit::Client; +using namespace std; namespace mediakit { @@ -65,12 +65,12 @@ void RtmpPlayer::play(const string &strUrl) { //服务器域名 host_url = FindField(host_url.data(), NULL, ":"); } - if (!(*this)[kNetAdapter].empty()) { - setNetAdapter((*this)[kNetAdapter]); + if (!(*this)[Client::kNetAdapter].empty()) { + setNetAdapter((*this)[Client::kNetAdapter]); } weak_ptr weak_self = dynamic_pointer_cast(shared_from_this()); - float play_timeout_sec = (*this)[kTimeoutMS].as() / 1000.0f; + float play_timeout_sec = (*this)[Client::kTimeoutMS].as() / 1000.0f; _play_timer.reset(new Timer(play_timeout_sec, [weak_self]() { auto strong_self = weak_self.lock(); if (!strong_self) { @@ -113,7 +113,7 @@ void RtmpPlayer::onPlayResult_l(const SockException &ex, bool handshake_done) { if (!ex) { //播放成功,恢复rtmp接收超时定时器 _rtmp_recv_ticker.resetTime(); - auto timeout_ms = (*this)[kMediaTimeoutMS].as(); + auto timeout_ms = (*this)[Client::kMediaTimeoutMS].as(); weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); auto lam = [weakSelf, timeout_ms]() { auto strongSelf = weakSelf.lock(); @@ -255,7 +255,7 @@ inline void RtmpPlayer::send_pause(bool pause) { _beat_timer.reset(); if (pause) { weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); - _beat_timer.reset(new Timer((*this)[kBeatIntervalMS].as() / 1000.0f, [weakSelf]() { + _beat_timer.reset(new Timer((*this)[Client::kBeatIntervalMS].as() / 1000.0f, [weakSelf]() { auto strongSelf = weakSelf.lock(); if (!strongSelf) { return false; diff --git a/src/Rtmp/RtmpPlayer.h b/src/Rtmp/RtmpPlayer.h index decd56ae..52b27288 100644 --- a/src/Rtmp/RtmpPlayer.h +++ b/src/Rtmp/RtmpPlayer.h @@ -24,19 +24,16 @@ #include "Network/Socket.h" #include "Network/TcpClient.h" -using namespace toolkit; -using namespace mediakit::Client; - namespace mediakit { //实现了rtmp播放器协议部分的功能,及数据接收功能 -class RtmpPlayer : public PlayerBase, public TcpClient, public RtmpProtocol { +class RtmpPlayer : public PlayerBase, public toolkit::TcpClient, public RtmpProtocol { public: typedef std::shared_ptr Ptr; - RtmpPlayer(const EventPoller::Ptr &poller); + RtmpPlayer(const toolkit::EventPoller::Ptr &poller); ~RtmpPlayer() override; - void play(const string &strUrl) override; + void play(const std::string &strUrl) override; void pause(bool bPause) override; void speed(float speed) override; void teardown() override; @@ -50,16 +47,16 @@ protected: protected: void onMediaData_l(RtmpPacket::Ptr chunk_data); //在获取config帧后才触发onPlayResult_l(而不是收到play命令回复),所以此时所有track都初始化完毕了 - void onPlayResult_l(const SockException &ex, bool handshake_done); + void onPlayResult_l(const toolkit::SockException &ex, bool handshake_done); //form Tcpclient - void onRecv(const Buffer::Ptr &buf) override; - void onConnect(const SockException &err) override; - void onErr(const SockException &ex) override; + void onRecv(const toolkit::Buffer::Ptr &buf) override; + void onConnect(const toolkit::SockException &err) override; + void onErr(const toolkit::SockException &ex) override; //from RtmpProtocol void onRtmpChunk(RtmpPacket::Ptr chunk_data) override; void onStreamDry(uint32_t stream_index) override; - void onSendRawData(Buffer::Ptr buffer) override { + void onSendRawData(toolkit::Buffer::Ptr buffer) override { send(std::move(buffer)); } @@ -82,9 +79,9 @@ protected: void send_pause(bool pause); private: - string _app; - string _stream_id; - string _tc_url; + std::string _app; + std::string _stream_id; + std::string _tc_url; bool _paused = false; bool _metadata_got = false; @@ -95,18 +92,18 @@ private: uint32_t _seek_ms = 0; uint32_t _fist_stamp[2] = {0, 0}; uint32_t _now_stamp[2] = {0, 0}; - Ticker _now_stamp_ticker[2]; - deque > _deque_on_status; - unordered_map > _map_on_result; + toolkit::Ticker _now_stamp_ticker[2]; + std::deque > _deque_on_status; + std::unordered_map > _map_on_result; //rtmp接收超时计时器 - Ticker _rtmp_recv_ticker; + toolkit::Ticker _rtmp_recv_ticker; //心跳发送定时器 - std::shared_ptr _beat_timer; + std::shared_ptr _beat_timer; //播放超时定时器 - std::shared_ptr _play_timer; + std::shared_ptr _play_timer; //rtmp接收超时定时器 - std::shared_ptr _rtmp_recv_timer; + std::shared_ptr _rtmp_recv_timer; }; } /* namespace mediakit */ diff --git a/src/Rtmp/RtmpPlayerImp.h b/src/Rtmp/RtmpPlayerImp.h index bea7811b..2eec6435 100644 --- a/src/Rtmp/RtmpPlayerImp.h +++ b/src/Rtmp/RtmpPlayerImp.h @@ -19,8 +19,6 @@ #include "RtmpDemuxer.h" #include "Poller/Timer.h" #include "Util/TimeTicker.h" -using namespace toolkit; -using namespace mediakit::Client; namespace mediakit { @@ -29,10 +27,10 @@ public: using Ptr = std::shared_ptr; using Super = PlayerImp; - RtmpPlayerImp(const EventPoller::Ptr &poller) : Super(poller) {}; + RtmpPlayerImp(const toolkit::EventPoller::Ptr &poller) : Super(poller) {}; ~RtmpPlayerImp() override { - DebugL << endl; + DebugL << std::endl; } float getProgress() const override { @@ -56,7 +54,7 @@ public: return _demuxer ? _demuxer->getDuration() : 0; } - vector getTracks(bool ready = true) const override { + std::vector getTracks(bool ready = true) const override { return _demuxer ? _demuxer->getTracks(ready) : Super::getTracks(ready); } @@ -80,7 +78,7 @@ private: } } - void onPlayResult(const SockException &ex) override { + void onPlayResult(const toolkit::SockException &ex) override { if (!_wait_track_ready || ex) { Super::onPlayResult(ex); return; @@ -91,13 +89,13 @@ private: void addTrackCompleted() override { if (_wait_track_ready) { - Super::onPlayResult(SockException(Err_success, "play success")); + Super::onPlayResult(toolkit::SockException(toolkit::Err_success, "play success")); } } private: void onCheckMeta_l(const AMFValue &val) { - _rtmp_src = dynamic_pointer_cast(_media_src); + _rtmp_src = std::dynamic_pointer_cast(_media_src); if (_rtmp_src) { _rtmp_src->setMetaData(val); } diff --git a/src/Rtmp/RtmpProtocol.cpp b/src/Rtmp/RtmpProtocol.cpp index 6f4c84a2..246734fc 100644 --- a/src/Rtmp/RtmpProtocol.cpp +++ b/src/Rtmp/RtmpProtocol.cpp @@ -12,6 +12,7 @@ #include "Rtmp/utils.h" #include "RtmpMediaSource.h" using namespace toolkit; +using namespace std; #define C1_DIGEST_SIZE 32 #define C1_KEY_SIZE 128 diff --git a/src/Rtmp/RtmpProtocol.h b/src/Rtmp/RtmpProtocol.h index fa51b191..ccd0e4c4 100644 --- a/src/Rtmp/RtmpProtocol.h +++ b/src/Rtmp/RtmpProtocol.h @@ -23,9 +23,6 @@ #include "Util/ResourcePool.h" #include "Http/HttpRequestSplitter.h" -using namespace std; -using namespace toolkit; - namespace mediakit { class RtmpProtocol : public HttpRequestSplitter{ @@ -35,10 +32,10 @@ public: void onParseRtmp(const char *data, size_t size); //作为客户端发送c0c1,等待s0s1s2并且回调 - void startClientSession(const function &cb); + void startClientSession(const std::function &cb); protected: - virtual void onSendRawData(Buffer::Ptr buffer) = 0; + virtual void onSendRawData(toolkit::Buffer::Ptr buffer) = 0; virtual void onRtmpChunk(RtmpPacket::Ptr chunk_data) = 0; virtual void onStreamBegin(uint32_t stream_index){ _stream_index = stream_index; @@ -61,25 +58,25 @@ protected: void sendPingResponse(uint32_t time_stamp = ::time(NULL)); void sendSetBufferLength(uint32_t stream_index, uint32_t len); void sendUserControl(uint16_t event_type, uint32_t event_data); - void sendUserControl(uint16_t event_type, const string &event_data); - void sendInvoke(const string &cmd, const AMFValue &val); - void sendRequest(int cmd, const string &str); - void sendResponse(int type, const string &str); + void sendUserControl(uint16_t event_type, const std::string &event_data); + void sendInvoke(const std::string &cmd, const AMFValue &val); + void sendRequest(int cmd, const std::string &str); + void sendResponse(int type, const std::string &str); void sendRtmp(uint8_t type, uint32_t stream_index, const std::string &buffer, uint32_t stamp, int chunk_id); - void sendRtmp(uint8_t type, uint32_t stream_index, const Buffer::Ptr &buffer, uint32_t stamp, int chunk_id); - BufferRaw::Ptr obtainBuffer(const void *data = nullptr, size_t len = 0); + void sendRtmp(uint8_t type, uint32_t stream_index, const toolkit::Buffer::Ptr &buffer, uint32_t stamp, int chunk_id); + toolkit::BufferRaw::Ptr obtainBuffer(const void *data = nullptr, size_t len = 0); private: void handle_C1_simple(const char *data); #ifdef ENABLE_OPENSSL void handle_C1_complex(const char *data); - string get_C1_digest(const uint8_t *ptr,char **digestPos); - string get_C1_key(const uint8_t *ptr); - void check_C1_Digest(const string &digest,const string &data); - void send_complex_S0S1S2(int schemeType,const string &digest); + std::string get_C1_digest(const uint8_t *ptr,char **digestPos); + std::string get_C1_key(const uint8_t *ptr); + void check_C1_Digest(const std::string &digest,const std::string &data); + void send_complex_S0S1S2(int schemeType,const std::string &digest); #endif //ENABLE_OPENSSL - const char* handle_S0S1S2(const char *data, size_t len, const function &func); + const char* handle_S0S1S2(const char *data, size_t len, const std::function &func); const char* handle_C0C1(const char *data, size_t len); const char* handle_C2(const char *data, size_t len); const char* handle_rtmp(const char *data, size_t len); @@ -104,11 +101,11 @@ private: uint32_t _bandwidth = 2500000; uint8_t _band_limit_type = 2; //////////Rtmp parser////////// - function _next_step_func; + std::function _next_step_func; ////////////Chunk//////////// - unordered_map > _map_chunk_data; + std::unordered_map > _map_chunk_data; //循环池 - ResourcePool _packet_pool; + toolkit::ResourcePool _packet_pool; }; } /* namespace mediakit */ diff --git a/src/Rtmp/RtmpPusher.cpp b/src/Rtmp/RtmpPusher.cpp index a5d05590..016796a8 100644 --- a/src/Rtmp/RtmpPusher.cpp +++ b/src/Rtmp/RtmpPusher.cpp @@ -13,8 +13,9 @@ #include "Util/util.h" #include "Util/onceToken.h" #include "Thread/ThreadPool.h" + +using namespace std; using namespace toolkit; -using namespace mediakit::Client; namespace mediakit { @@ -83,7 +84,7 @@ void RtmpPusher::publish(const string &url) { } weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); - float publishTimeOutSec = (*this)[kTimeoutMS].as() / 1000.0f; + float publishTimeOutSec = (*this)[Client::kTimeoutMS].as() / 1000.0f; _publish_timer.reset(new Timer(publishTimeOutSec, [weakSelf]() { auto strongSelf = weakSelf.lock(); if (!strongSelf) { @@ -93,8 +94,8 @@ void RtmpPusher::publish(const string &url) { return false; }, getPoller())); - if (!(*this)[kNetAdapter].empty()) { - setNetAdapter((*this)[kNetAdapter]); + if (!(*this)[Client::kNetAdapter].empty()) { + setNetAdapter((*this)[Client::kNetAdapter]); } startConnect(host_url, iPort); diff --git a/src/Rtmp/RtmpPusher.h b/src/Rtmp/RtmpPusher.h index 9b8c3604..6cdfebea 100644 --- a/src/Rtmp/RtmpPusher.h +++ b/src/Rtmp/RtmpPusher.h @@ -18,29 +18,29 @@ namespace mediakit { -class RtmpPusher : public RtmpProtocol, public TcpClient, public PusherBase { +class RtmpPusher : public RtmpProtocol, public toolkit::TcpClient, public PusherBase { public: typedef std::shared_ptr Ptr; - RtmpPusher(const EventPoller::Ptr &poller,const RtmpMediaSource::Ptr &src); + RtmpPusher(const toolkit::EventPoller::Ptr &poller,const RtmpMediaSource::Ptr &src); ~RtmpPusher() override; - void publish(const string &url) override ; + void publish(const std::string &url) override ; void teardown() override; protected: //for Tcpclient override - void onRecv(const Buffer::Ptr &buf) override; - void onConnect(const SockException &err) override; - void onErr(const SockException &ex) override; + void onRecv(const toolkit::Buffer::Ptr &buf) override; + void onConnect(const toolkit::SockException &err) override; + void onErr(const toolkit::SockException &ex) override; //for RtmpProtocol override void onRtmpChunk(RtmpPacket::Ptr chunk_data) override; - void onSendRawData(Buffer::Ptr buffer) override{ + void onSendRawData(toolkit::Buffer::Ptr buffer) override{ send(std::move(buffer)); } private: - void onPublishResult_l(const SockException &ex, bool handshake_done); + void onPublishResult_l(const toolkit::SockException &ex, bool handshake_done); template inline void addOnResultCB(const FUN &fun) { @@ -62,14 +62,14 @@ private: void setSocketFlags(); private: - string _app; - string _stream_id; - string _tc_url; - deque > _deque_on_status; - unordered_map > _map_on_result; + std::string _app; + std::string _stream_id; + std::string _tc_url; + std::deque > _deque_on_status; + std::unordered_map > _map_on_result; //推流超时定时器 - std::shared_ptr _publish_timer; + std::shared_ptr _publish_timer; std::weak_ptr _publish_src; RtmpMediaSource::RingType::RingReader::Ptr _rtmp_reader; }; diff --git a/src/Rtmp/RtmpSession.cpp b/src/Rtmp/RtmpSession.cpp index 9cb3d978..34c35d80 100644 --- a/src/Rtmp/RtmpSession.cpp +++ b/src/Rtmp/RtmpSession.cpp @@ -11,6 +11,10 @@ #include "RtmpSession.h" #include "Common/config.h" #include "Util/onceToken.h" + +using namespace std; +using namespace toolkit; + namespace mediakit { RtmpSession::RtmpSession(const Socket::Ptr &sock) : TcpSession(sock) { diff --git a/src/Rtmp/RtmpSession.h b/src/Rtmp/RtmpSession.h index 7e289695..336c8292 100644 --- a/src/Rtmp/RtmpSession.h +++ b/src/Rtmp/RtmpSession.h @@ -23,18 +23,17 @@ #include "Network/TcpSession.h" #include "Common/Stamp.h" -using namespace toolkit; - namespace mediakit { -class RtmpSession: public TcpSession ,public RtmpProtocol , public MediaSourceEvent{ +class RtmpSession : public toolkit::TcpSession, public RtmpProtocol, public MediaSourceEvent { public: - typedef std::shared_ptr Ptr; - RtmpSession(const Socket::Ptr &sock); + using Ptr = std::shared_ptr; + + RtmpSession(const toolkit::Socket::Ptr &sock); ~RtmpSession() override; - void onRecv(const Buffer::Ptr &buf) override; - void onError(const SockException &err) override; + void onRecv(const toolkit::Buffer::Ptr &buf) override; + void onError(const toolkit::SockException &err) override; void onManager() override; private: @@ -48,8 +47,8 @@ private: void onCmd_play(AMFDecoder &dec); void onCmd_play2(AMFDecoder &dec); void doPlay(AMFDecoder &dec); - void doPlayResponse(const string &err,const std::function &cb); - void sendPlayResponse(const string &err,const RtmpMediaSource::Ptr &src); + void doPlayResponse(const std::string &err,const std::function &cb); + void sendPlayResponse(const std::string &err,const RtmpMediaSource::Ptr &src); void onCmd_seek(AMFDecoder &dec); void onCmd_pause(AMFDecoder &dec); @@ -57,7 +56,7 @@ private: void setMetaData(AMFDecoder &dec); void onSendMedia(const RtmpPacket::Ptr &pkt); - void onSendRawData(Buffer::Ptr buffer) override{ + void onSendRawData(toolkit::Buffer::Ptr buffer) override{ _total_bytes += buffer->size(); send(std::move(buffer)); } @@ -78,14 +77,14 @@ private: // 获取媒体源类型 MediaOriginType getOriginType(MediaSource &sender) const override; // 获取媒体源url或者文件路径 - string getOriginUrl(MediaSource &sender) const override; + std::string getOriginUrl(MediaSource &sender) const override; // 获取媒体源客户端相关信息 std::shared_ptr getOriginSock(MediaSource &sender) const override; void setSocketFlags(); - string getStreamId(const string &str); + std::string getStreamId(const std::string &str); void dumpMetadata(const AMFValue &metadata); - void sendStatus(const std::initializer_list &key_value); + void sendStatus(const std::initializer_list &key_value); private: bool _set_meta_data = false; @@ -96,7 +95,7 @@ private: //推流时间戳修整器 Stamp _stamp[2]; //数据接收超时计时器 - Ticker _ticker; + toolkit::Ticker _ticker; MediaInfo _media_info; std::weak_ptr _play_src; AMFValue _push_metadata; @@ -108,7 +107,7 @@ private: /** * 支持ssl加密的rtmp服务器 */ -typedef TcpSessionWithSSL RtmpSessionWithSSL; +using RtmpSessionWithSSL = toolkit::TcpSessionWithSSL; } /* namespace mediakit */ #endif /* SRC_RTMP_RTMPSESSION_H_ */ diff --git a/src/Rtmp/amf.cpp b/src/Rtmp/amf.cpp index 70f68b18..5ade9e8b 100644 --- a/src/Rtmp/amf.cpp +++ b/src/Rtmp/amf.cpp @@ -16,6 +16,8 @@ #include "Util/logger.h" #include "Network/sockutil.h" #include "Util/util.h" + +using namespace std; using namespace toolkit; /////////////////////AMFValue///////////////////////////// diff --git a/src/Rtmp/amf.h b/src/Rtmp/amf.h index 2c5384cd..c6daee70 100644 --- a/src/Rtmp/amf.h +++ b/src/Rtmp/amf.h @@ -19,8 +19,6 @@ #include #include #include "Network/Buffer.h" -using namespace std; -using namespace toolkit; enum AMFType { AMF_NUMBER, @@ -39,8 +37,9 @@ class AMFValue; class AMFValue { public: friend class AMFEncoder; - typedef std::map mapType; - typedef std::vector arrayType; + + using mapType = std::map; + using arrayType = std::vector; ~AMFValue(); AMFValue(AMFType type = AMF_NULL); @@ -58,17 +57,19 @@ public: double as_number() const; int as_integer() const; bool as_boolean() const; - string to_string() const; + std::string to_string() const; const AMFValue &operator[](const char *str) const; - void object_for_each(const function &fun) const ; + void object_for_each(const std::function &fun) const ; operator bool() const; void set(const std::string &s, const AMFValue &val); void add(const AMFValue &val); + private: const mapType &getMap() const; const arrayType &getArr() const; void destroy(); void init(); + private: AMFType _type; union { @@ -83,9 +84,10 @@ private: class AMFDecoder { public: - AMFDecoder(const BufferLikeString &buf, size_t pos, int version = 0); + AMFDecoder(const toolkit::BufferLikeString &buf, size_t pos, int version = 0); template TP load(); + private: std::string load_key(); AMFValue load_object(); @@ -93,8 +95,9 @@ private: AMFValue load_arr(); uint8_t front(); uint8_t pop_front(); + private: - const BufferLikeString &buf; + const toolkit::BufferLikeString &buf; size_t pos; int version; }; @@ -110,9 +113,11 @@ public: AMFEncoder & operator <<(const AMFValue &value); const std::string& data() const ; void clear() ; + private: void write_key(const std::string &s); AMFEncoder &write_undefined(); + private: std::string buf; }; diff --git a/src/Rtmp/utils.cpp b/src/Rtmp/utils.cpp index f57b2c5a..5c251dd9 100644 --- a/src/Rtmp/utils.cpp +++ b/src/Rtmp/utils.cpp @@ -15,6 +15,7 @@ #include #include "Util/util.h" #include "Network/sockutil.h" + using namespace toolkit; /* diff --git a/src/Rtp/Decoder.cpp b/src/Rtp/Decoder.cpp index 68243552..240e09eb 100644 --- a/src/Rtp/Decoder.cpp +++ b/src/Rtp/Decoder.cpp @@ -21,6 +21,8 @@ #include "mpeg-ts-proto.h" #endif +using namespace toolkit; + namespace mediakit { static Decoder::Ptr createDecoder_l(DecoderImp::Type type) { switch (type){ diff --git a/src/Rtp/Decoder.h b/src/Rtp/Decoder.h index 2f69f7c7..66271b8e 100644 --- a/src/Rtp/Decoder.h +++ b/src/Rtp/Decoder.h @@ -16,7 +16,6 @@ #include #include "Common/MediaSink.h" -using namespace std; namespace mediakit { class Decoder { @@ -60,7 +59,7 @@ private: Decoder::Ptr _decoder; MediaSinkInterface *_sink; FrameMerger _merger{FrameMerger::none}; - Ticker _last_unsported_print; + toolkit::Ticker _last_unsported_print; Track::Ptr _tracks[TrackMax]; }; diff --git a/src/Rtp/GB28181Process.cpp b/src/Rtp/GB28181Process.cpp index b85f0abc..f9f98229 100644 --- a/src/Rtp/GB28181Process.cpp +++ b/src/Rtp/GB28181Process.cpp @@ -19,10 +19,13 @@ #include "Extension/G711.h" #include "Extension/H265.h" -namespace mediakit{ +using namespace std; +using namespace toolkit; + +namespace mediakit { //判断是否为ts负载 -static inline bool checkTS(const uint8_t *packet, size_t bytes){ +static inline bool checkTS(const uint8_t *packet, size_t bytes) { return bytes % TS_PACKET_SIZE == 0 && packet[0] == TS_SYNC_BYTE; } diff --git a/src/Rtp/GB28181Process.h b/src/Rtp/GB28181Process.h index 01ffea94..3ad078e6 100644 --- a/src/Rtp/GB28181Process.h +++ b/src/Rtp/GB28181Process.h @@ -47,8 +47,8 @@ private: DecoderImp::Ptr _decoder; MediaSinkInterface *_interface; std::shared_ptr _save_file_ps; - unordered_map > _rtp_decoder; - unordered_map > _rtp_receiver; + std::unordered_map > _rtp_decoder; + std::unordered_map > _rtp_receiver; }; }//namespace mediakit diff --git a/src/Rtp/PSDecoder.cpp b/src/Rtp/PSDecoder.cpp index b0e405e6..4f3249b1 100644 --- a/src/Rtp/PSDecoder.cpp +++ b/src/Rtp/PSDecoder.cpp @@ -9,8 +9,12 @@ */ #if defined(ENABLE_RTPPROXY) + #include "PSDecoder.h" #include "mpeg-ps.h" + +using namespace toolkit; + namespace mediakit{ PSDecoder::PSDecoder() { diff --git a/src/Rtp/PSEncoder.cpp b/src/Rtp/PSEncoder.cpp index 36995279..71ab3171 100644 --- a/src/Rtp/PSEncoder.cpp +++ b/src/Rtp/PSEncoder.cpp @@ -14,6 +14,8 @@ #include "Extension/H264.h" #include "Rtsp/RtspMuxer.h" +using namespace toolkit; + namespace mediakit{ PSEncoderImp::PSEncoderImp(uint32_t ssrc, uint8_t payload_type) : MpegMuxer(true) { diff --git a/src/Rtp/PSEncoder.h b/src/Rtp/PSEncoder.h index 8e09e028..76e7418f 100644 --- a/src/Rtp/PSEncoder.h +++ b/src/Rtp/PSEncoder.h @@ -27,10 +27,10 @@ public: protected: //rtp打包后回调 - virtual void onRTP(Buffer::Ptr rtp) = 0; + virtual void onRTP(toolkit::Buffer::Ptr rtp) = 0; protected: - void onWrite(std::shared_ptr buffer, uint32_t stamp, bool key_pos) override; + void onWrite(std::shared_ptr buffer, uint32_t stamp, bool key_pos) override; private: std::shared_ptr _rtp_encoder; diff --git a/src/Rtp/RtpCache.cpp b/src/Rtp/RtpCache.cpp index 283505da..d65cc049 100644 --- a/src/Rtp/RtpCache.cpp +++ b/src/Rtp/RtpCache.cpp @@ -12,6 +12,8 @@ #if defined(ENABLE_RTPPROXY) +using namespace toolkit; + namespace mediakit{ RtpCache::RtpCache(onFlushed cb) { @@ -27,7 +29,7 @@ void RtpCache::input(uint64_t stamp, Buffer::Ptr buffer) { } void RtpCachePS::onRTP(Buffer::Ptr buffer) { - auto rtp = static_pointer_cast(buffer); + auto rtp = std::static_pointer_cast(buffer); auto stamp = rtp->getStampMS(); input(stamp, std::move(buffer)); } diff --git a/src/Rtp/RtpCache.h b/src/Rtp/RtpCache.h index 7dcba839..474fbbc0 100644 --- a/src/Rtp/RtpCache.h +++ b/src/Rtp/RtpCache.h @@ -18,9 +18,9 @@ namespace mediakit{ -class RtpCache : private PacketCache { +class RtpCache : private PacketCache { public: - using onFlushed = function >)>; + using onFlushed = std::function >)>; RtpCache(onFlushed cb); ~RtpCache() override = default; @@ -29,10 +29,10 @@ protected: * 输入rtp(目的是为了合并写) * @param buffer rtp数据 */ - void input(uint64_t stamp, Buffer::Ptr buffer); + void input(uint64_t stamp, toolkit::Buffer::Ptr buffer); protected: - void onFlush(std::shared_ptr > rtp_list, bool) override; + void onFlush(std::shared_ptr > rtp_list, bool) override; private: onFlushed _cb; @@ -44,7 +44,7 @@ public: ~RtpCachePS() override = default; protected: - void onRTP(Buffer::Ptr rtp) override; + void onRTP(toolkit::Buffer::Ptr rtp) override; }; }//namespace mediakit diff --git a/src/Rtp/RtpProcess.cpp b/src/Rtp/RtpProcess.cpp index cd731d51..982a4f16 100644 --- a/src/Rtp/RtpProcess.cpp +++ b/src/Rtp/RtpProcess.cpp @@ -13,6 +13,9 @@ #include "RtpProcess.h" #include "Http/HttpTSPlayer.h" +using namespace std; +using namespace toolkit; + static constexpr char kRtpAppName[] = "rtp"; //在创建_muxer对象前(也就是推流鉴权成功前),需要先缓存frame,这样可以防止丢包,提高体验 //但是同时需要控制缓冲长度,防止内存溢出。200帧数据,大概有10秒数据,应该足矣等待鉴权hook返回 diff --git a/src/Rtp/RtpProcess.h b/src/Rtp/RtpProcess.h index 84ec3982..c05bed64 100644 --- a/src/Rtp/RtpProcess.h +++ b/src/Rtp/RtpProcess.h @@ -17,11 +17,11 @@ namespace mediakit { -class RtpProcess : public SockInfo, public MediaSinkInterface, public MediaSourceEventInterceptor, public std::enable_shared_from_this{ +class RtpProcess : public toolkit::SockInfo, public MediaSinkInterface, public MediaSourceEventInterceptor, public std::enable_shared_from_this{ public: typedef std::shared_ptr Ptr; friend class RtpProcessHelper; - RtpProcess(const string &stream_id); + RtpProcess(const std::string &stream_id); ~RtpProcess(); /** @@ -34,7 +34,7 @@ public: * @param dts_out 解析出最新的dts * @return 是否解析成功 */ - bool inputRtp(bool is_udp, const Socket::Ptr &sock, const char *data, size_t len, const struct sockaddr *addr , uint32_t *dts_out = nullptr); + bool inputRtp(bool is_udp, const toolkit::Socket::Ptr &sock, const char *data, size_t len, const struct sockaddr *addr , uint32_t *dts_out = nullptr); /** * 是否超时,用于超时移除对象 @@ -49,7 +49,7 @@ public: /** * 设置onDetach事件回调 */ - void setOnDetach(const function &cb); + void setOnDetach(const std::function &cb); /** * 设置onDetach事件回调,false检查RTP超时,true停止 @@ -57,11 +57,11 @@ public: void setStopCheckRtp(bool is_check=false); /// SockInfo override - string get_local_ip() override; + std::string get_local_ip() override; uint16_t get_local_port() override; - string get_peer_ip() override; + std::string get_peer_ip() override; uint16_t get_peer_port() override; - string getIdentifier() const override; + std::string getIdentifier() const override; int getTotalReaderCount(); void setListener(const std::weak_ptr &listener); @@ -74,7 +74,7 @@ protected: //// MediaSourceEvent override //// MediaOriginType getOriginType(MediaSource &sender) const override; - string getOriginUrl(MediaSource &sender) const override; + std::string getOriginUrl(MediaSource &sender) const override; std::shared_ptr getOriginSock(MediaSource &sender) const override; private: @@ -85,19 +85,19 @@ private: uint32_t _dts = 0; uint64_t _total_bytes = 0; struct sockaddr _addr{0}; - Socket::Ptr _sock; + toolkit::Socket::Ptr _sock; MediaInfo _media_info; - Ticker _last_frame_time; - function _on_detach; + toolkit::Ticker _last_frame_time; + std::function _on_detach; std::shared_ptr _save_file_rtp; std::shared_ptr _save_file_video; ProcessInterface::Ptr _process; MultiMediaSourceMuxer::Ptr _muxer; - atomic_bool _stop_rtp_check{false}; - atomic_flag _busy_flag{false}; - Ticker _last_check_alive; - recursive_mutex _func_mtx; - deque > _cached_func; + std::atomic_bool _stop_rtp_check{false}; + std::atomic_flag _busy_flag{false}; + toolkit::Ticker _last_check_alive; + std::recursive_mutex _func_mtx; + std::deque > _cached_func; }; }//namespace mediakit diff --git a/src/Rtp/RtpSelector.cpp b/src/Rtp/RtpSelector.cpp index 71fa02bd..f1c6d423 100644 --- a/src/Rtp/RtpSelector.cpp +++ b/src/Rtp/RtpSelector.cpp @@ -13,6 +13,9 @@ #include "RtpSelector.h" #include "RtpSplitter.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ INSTANCE_IMP(RtpSelector); diff --git a/src/Rtp/RtpSelector.h b/src/Rtp/RtpSelector.h index b37a8b42..70e160a7 100644 --- a/src/Rtp/RtpSelector.h +++ b/src/Rtp/RtpSelector.h @@ -24,7 +24,7 @@ class RtpSelector; class RtpProcessHelper : public MediaSourceEvent , public std::enable_shared_from_this { public: typedef std::shared_ptr Ptr; - RtpProcessHelper(const string &stream_id, const weak_ptr &parent); + RtpProcessHelper(const std::string &stream_id, const std::weak_ptr &parent); ~RtpProcessHelper(); void attachEvent(); RtpProcess::Ptr & getProcess(); @@ -36,9 +36,9 @@ protected: int totalReaderCount(MediaSource &sender) override; private: - weak_ptr _parent; + std::weak_ptr _parent; RtpProcess::Ptr _process; - string _stream_id; + std::string _stream_id; }; class RtpSelector : public std::enable_shared_from_this{ @@ -63,7 +63,7 @@ public: * @param dts_out 解析出最新的dts * @return 是否成功 */ - bool inputRtp(const Socket::Ptr &sock, const char *data, size_t data_len, + bool inputRtp(const toolkit::Socket::Ptr &sock, const char *data, size_t data_len, const struct sockaddr *addr, uint32_t *dts_out = nullptr); /** @@ -72,23 +72,23 @@ public: * @param makeNew 不存在时是否新建 * @return rtp处理器 */ - RtpProcess::Ptr getProcess(const string &stream_id, bool makeNew); + RtpProcess::Ptr getProcess(const std::string &stream_id, bool makeNew); /** * 删除rtp处理器 * @param stream_id 流id * @param ptr rtp处理器指针 */ - void delProcess(const string &stream_id, const RtpProcess *ptr); + void delProcess(const std::string &stream_id, const RtpProcess *ptr); private: void onManager(); void createTimer(); private: - Timer::Ptr _timer; - recursive_mutex _mtx_map; - unordered_map _map_rtp_process; + toolkit::Timer::Ptr _timer; + std::recursive_mutex _mtx_map; + std::unordered_map _map_rtp_process; }; }//namespace mediakit diff --git a/src/Rtp/RtpSender.cpp b/src/Rtp/RtpSender.cpp index 528e1a72..d808f33b 100644 --- a/src/Rtp/RtpSender.cpp +++ b/src/Rtp/RtpSender.cpp @@ -14,6 +14,9 @@ #include "Thread/WorkThreadPool.h" #include "RtpCache.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ RtpSender::RtpSender(uint32_t ssrc, uint8_t payload_type) { @@ -23,8 +26,7 @@ RtpSender::RtpSender(uint32_t ssrc, uint8_t payload_type) { }, ssrc, payload_type); } -RtpSender::~RtpSender() { -} +RtpSender::~RtpSender() {} void RtpSender::startSend(const string &dst_url, uint16_t dst_port, bool is_udp, uint16_t src_port, const function &cb){ _is_udp = is_udp; diff --git a/src/Rtp/RtpSender.h b/src/Rtp/RtpSender.h index b422c85e..b2391ab8 100644 --- a/src/Rtp/RtpSender.h +++ b/src/Rtp/RtpSender.h @@ -37,7 +37,7 @@ public: * @param is_udp 是否采用udp方式发送rtp * @param cb 连接目标端口是否成功的回调 */ - void startSend(const string &dst_url, uint16_t dst_port, bool is_udp, uint16_t src_port, const function &cb); + void startSend(const std::string &dst_url, uint16_t dst_port, bool is_udp, uint16_t src_port, const std::function &cb); /** * 输入帧数据 @@ -63,21 +63,21 @@ public: private: //合并写输出 - void onFlushRtpList(std::shared_ptr > rtp_list); + void onFlushRtpList(std::shared_ptr > rtp_list); //udp/tcp连接成功回调 void onConnect(); //异常断开socket事件 - void onErr(const SockException &ex, bool is_connect = false); + void onErr(const toolkit::SockException &ex, bool is_connect = false); private: bool _is_udp; bool _is_connect = false; - string _dst_url; + std::string _dst_url; uint16_t _dst_port; uint16_t _src_port; - Socket::Ptr _socket; - EventPoller::Ptr _poller; - Timer::Ptr _connect_timer; + toolkit::Socket::Ptr _socket; + toolkit::EventPoller::Ptr _poller; + toolkit::Timer::Ptr _connect_timer; MediaSinkInterface::Ptr _interface; }; diff --git a/src/Rtp/RtpServer.cpp b/src/Rtp/RtpServer.cpp index 5464c091..ea573a16 100644 --- a/src/Rtp/RtpServer.cpp +++ b/src/Rtp/RtpServer.cpp @@ -9,13 +9,17 @@ */ #if defined(ENABLE_RTPPROXY) +#include "Util/uv_errno.h" #include "RtpServer.h" #include "RtpSelector.h" #include "Rtcp/RtcpContext.h" + +using namespace std; +using namespace toolkit; + namespace mediakit{ -RtpServer::RtpServer() { -} +RtpServer::RtpServer() {} RtpServer::~RtpServer() { if(_on_clearup){ @@ -161,8 +165,8 @@ void RtpServer::start(uint16_t local_port, const string &stream_id, bool enable _rtp_process = process; } -void RtpServer::setOnDetach(const function &cb){ - if(_rtp_process){ +void RtpServer::setOnDetach(const function &cb) { + if (_rtp_process) { _rtp_process->setOnDetach(cb); } } diff --git a/src/Rtp/RtpServer.h b/src/Rtp/RtpServer.h index 61dfb825..b9c71533 100644 --- a/src/Rtp/RtpServer.h +++ b/src/Rtp/RtpServer.h @@ -18,9 +18,6 @@ #include "Network/UdpServer.h" #include "RtpSession.h" -using namespace std; -using namespace toolkit; - namespace mediakit{ /** @@ -28,8 +25,8 @@ namespace mediakit{ */ class RtpServer { public: - typedef std::shared_ptr Ptr; - typedef function onRecv; + using Ptr = std::shared_ptr; + using onRecv = std::function; RtpServer(); ~RtpServer(); @@ -41,7 +38,7 @@ public: * @param enable_tcp 是否启用tcp服务器 * @param local_ip 绑定的本地网卡ip */ - void start(uint16_t local_port, const string &stream_id = "", bool enable_tcp = true, const char *local_ip = "0.0.0.0",bool enable_reuse = true); + void start(uint16_t local_port, const std::string &stream_id = "", bool enable_tcp = true, const char *local_ip = "0.0.0.0",bool enable_reuse = true); /** * 获取绑定的本地端口 @@ -51,14 +48,14 @@ public: /** * 设置RtpProcess onDetach事件回调 */ - void setOnDetach(const function &cb); + void setOnDetach(const std::function &cb); protected: - Socket::Ptr _rtp_socket; - UdpServer::Ptr _udp_server; - TcpServer::Ptr _tcp_server; + toolkit::Socket::Ptr _rtp_socket; + toolkit::UdpServer::Ptr _udp_server; + toolkit::TcpServer::Ptr _tcp_server; RtpProcess::Ptr _rtp_process; - function _on_clearup; + std::function _on_clearup; }; }//namespace mediakit diff --git a/src/Rtp/RtpSession.cpp b/src/Rtp/RtpSession.cpp index 2b02471f..fe88d8b5 100644 --- a/src/Rtp/RtpSession.cpp +++ b/src/Rtp/RtpSession.cpp @@ -13,6 +13,10 @@ #include "RtpSelector.h" #include "Network/TcpServer.h" #include "Rtsp/RtpReceiver.h" + +using namespace std; +using namespace toolkit; + namespace mediakit{ const string RtpSession::kStreamID = "stream_id"; diff --git a/src/Rtp/RtpSession.h b/src/Rtp/RtpSession.h index 44565a58..488c4da1 100644 --- a/src/Rtp/RtpSession.h +++ b/src/Rtp/RtpSession.h @@ -12,25 +12,25 @@ #define ZLMEDIAKIT_RTPSESSION_H #if defined(ENABLE_RTPPROXY) + #include "Network/TcpSession.h" #include "RtpSplitter.h" #include "RtpProcess.h" #include "Util/TimeTicker.h" -using namespace toolkit; namespace mediakit{ -class RtpSession : public Session , public RtpSplitter , public MediaSourceEvent{ +class RtpSession : public toolkit::Session, public RtpSplitter, public MediaSourceEvent { public: - static const string kStreamID; - static const string kIsUDP; + static const std::string kStreamID; + static const std::string kIsUDP; - RtpSession(const Socket::Ptr &sock); + RtpSession(const toolkit::Socket::Ptr &sock); ~RtpSession() override; - void onRecv(const Buffer::Ptr &) override; - void onError(const SockException &err) override; + void onRecv(const toolkit::Buffer::Ptr &) override; + void onError(const toolkit::SockException &err) override; void onManager() override; - void attachServer(const Server &server) override; + void attachServer(const toolkit::Server &server) override; protected: // 通知其停止推流 @@ -47,12 +47,12 @@ private: bool _search_rtp = false; bool _search_rtp_finished = false; uint32_t _ssrc = 0; - Ticker _ticker; - string _stream_id; + toolkit::Ticker _ticker; + std::string _stream_id; struct sockaddr _addr; RtpProcess::Ptr _process; - std::shared_ptr > _statistic_tcp; - std::shared_ptr > _statistic_udp; + std::shared_ptr > _statistic_tcp; + std::shared_ptr > _statistic_udp; }; }//namespace mediakit diff --git a/src/Rtp/TSDecoder.h b/src/Rtp/TSDecoder.h index ecaf6b76..25a68412 100644 --- a/src/Rtp/TSDecoder.h +++ b/src/Rtp/TSDecoder.h @@ -15,12 +15,11 @@ #include "Http/HttpRequestSplitter.h" #include "Decoder.h" -using namespace toolkit; -namespace mediakit { - #define TS_PACKET_SIZE 188 #define TS_SYNC_BYTE 0x47 +namespace mediakit { + //TS包分割器,用于split一个一个的ts包 class TSSegment : public HttpRequestSplitter { public: diff --git a/src/Rtsp/RtpCodec.h b/src/Rtsp/RtpCodec.h index 52022cbb..8fe2e7e3 100644 --- a/src/Rtsp/RtpCodec.h +++ b/src/Rtsp/RtpCodec.h @@ -14,32 +14,31 @@ #include #include "Util/RingBuffer.h" #include "Player/PlayerBase.h" -using namespace toolkit; -namespace mediakit{ +namespace mediakit { -class RtpRing{ +class RtpRing { public: - typedef std::shared_ptr Ptr; - typedef RingBuffer RingType; + using Ptr = std::shared_ptr; + using RingType = toolkit::RingBuffer; - RtpRing(){} - virtual ~RtpRing(){} + RtpRing() = default; + virtual ~RtpRing() = default; /** * 获取rtp环形缓存 * @return */ virtual RingType::Ptr getRtpRing() const { - return _rtpRing; + return _ring; } /** * 设置rtp环形缓存 * @param ring */ - virtual void setRtpRing(const RingType::Ptr &ring){ - _rtpRing = ring; + virtual void setRtpRing(const RingType::Ptr &ring) { + _ring = ring; } /** @@ -48,14 +47,15 @@ public: * @param key_pos 是否为关键帧第一个rtp包 * @return 是否为关键帧第一个rtp包 */ - virtual bool inputRtp(const RtpPacket::Ptr &rtp, bool key_pos){ - if(_rtpRing){ - _rtpRing->write(rtp,key_pos); + virtual bool inputRtp(const RtpPacket::Ptr &rtp, bool key_pos) { + if (_ring) { + _ring->write(rtp, key_pos); } return key_pos; } + protected: - RingType::Ptr _rtpRing; + RingType::Ptr _ring; }; class RtpInfo{ @@ -95,11 +95,12 @@ private: size_t _mtu_size; }; -class RtpCodec : public RtpRing, public FrameDispatcher , public CodecInfo{ +class RtpCodec : public RtpRing, public FrameDispatcher, public CodecInfo { public: - typedef std::shared_ptr Ptr; - RtpCodec(){} - virtual ~RtpCodec(){} + using Ptr = std::shared_ptr; + + RtpCodec() = default; + ~RtpCodec() override = default; }; }//namespace mediakit diff --git a/src/Rtsp/RtpMultiCaster.h b/src/Rtsp/RtpMultiCaster.h index 8303ed42..1195a92a 100644 --- a/src/Rtsp/RtpMultiCaster.h +++ b/src/Rtsp/RtpMultiCaster.h @@ -19,8 +19,6 @@ #include "RtspMediaSource.h" #include "Util/mini.h" #include "Network/Socket.h" -using namespace std; -using namespace toolkit; namespace mediakit{ @@ -29,7 +27,7 @@ public: ~MultiCastAddressMaker() {} static MultiCastAddressMaker& Instance(); static bool isMultiCastAddress(uint32_t addr); - static string toString(uint32_t addr); + static std::string toString(uint32_t addr); std::shared_ptr obtain(uint32_t max_try = 10); @@ -39,30 +37,30 @@ private: private: uint32_t _addr = 0; - recursive_mutex _mtx; - unordered_set _used_addr; + std::recursive_mutex _mtx; + std::unordered_set _used_addr; }; class RtpMultiCaster { public: typedef std::shared_ptr Ptr; - typedef function onDetach; + typedef std::function onDetach; ~RtpMultiCaster(); - static Ptr get(SocketHelper &helper, const string &local_ip, const string &vhost, const string &app, const string &stream); + static Ptr get(toolkit::SocketHelper &helper, const std::string &local_ip, const std::string &vhost, const std::string &app, const std::string &stream); void setDetachCB(void *listener,const onDetach &cb); - string getMultiCasterIP(); + std::string getMultiCasterIP(); uint16_t getMultiCasterPort(TrackType trackType); private: - RtpMultiCaster(SocketHelper &helper, const string &local_ip, const string &vhost, const string &app, const string &stream); + RtpMultiCaster(toolkit::SocketHelper &helper, const std::string &local_ip, const std::string &vhost, const std::string &app, const std::string &stream); private: - recursive_mutex _mtx; - Socket::Ptr _udp_sock[2]; + std::recursive_mutex _mtx; + toolkit::Socket::Ptr _udp_sock[2]; std::shared_ptr _multicast_ip; - unordered_map _detach_map; + std::unordered_map _detach_map; RtspMediaSource::RingType::RingReader::Ptr _rtp_reader; }; diff --git a/src/Rtsp/RtpReceiver.h b/src/Rtsp/RtpReceiver.h index 089f36fe..df7de687 100644 --- a/src/Rtsp/RtpReceiver.h +++ b/src/Rtsp/RtpReceiver.h @@ -17,8 +17,6 @@ #include "RtpCodec.h" #include "RtspMediaSource.h" #include "Common/Stamp.h" -using namespace std; -using namespace toolkit; namespace mediakit { @@ -28,7 +26,7 @@ public: PacketSortor() = default; ~PacketSortor() = default; - void setOnSort(function cb) { + void setOnSort(std::function cb) { _cb = std::move(cb); } @@ -116,7 +114,7 @@ private: _pkt_sort_cache_map.erase(it); } - void popIterator(typename map::iterator it) { + void popIterator(typename std::map::iterator it) { auto seq = it->first; auto data = std::move(it->second); _pkt_sort_cache_map.erase(it); @@ -156,14 +154,14 @@ private: //排序缓存长度 size_t _max_sort_size = kMin; //pkt排序缓存,根据seq排序 - map _pkt_sort_cache_map; + std::map _pkt_sort_cache_map; //回调 - function _cb; + std::function _cb; }; class RtpTrack : private PacketSortor{ public: - class BadRtpException : public invalid_argument { + class BadRtpException : public std::invalid_argument { public: template BadRtpException(Type &&type) : invalid_argument(std::forward(type)) {} @@ -185,14 +183,14 @@ protected: private: bool _disable_ntp = false; uint32_t _ssrc = 0; - Ticker _ssrc_alive; + toolkit::Ticker _ssrc_alive; NtpStamp _ntp_stamp; }; class RtpTrackImp : public RtpTrack{ public: - using OnSorted = function; - using BeforeSorted = function; + using OnSorted = std::function; + using BeforeSorted = std::function; RtpTrackImp() = default; ~RtpTrackImp() override = default; diff --git a/src/Rtsp/Rtsp.cpp b/src/Rtsp/Rtsp.cpp index 7dc8456b..b63985a0 100644 --- a/src/Rtsp/Rtsp.cpp +++ b/src/Rtsp/Rtsp.cpp @@ -12,6 +12,9 @@ #include "Rtsp.h" #include "Common/Parser.h" +using namespace std; +using namespace toolkit; + namespace mediakit { int RtpPayload::getClockRate(int pt) { diff --git a/src/Rtsp/Rtsp.h b/src/Rtsp/Rtsp.h index 07f4d161..84db8e84 100644 --- a/src/Rtsp/Rtsp.h +++ b/src/Rtsp/Rtsp.h @@ -20,10 +20,6 @@ #include "Common/macros.h" #include "Extension/Frame.h" -using namespace std; -using namespace toolkit; -using namespace mediakit; - namespace mediakit { namespace Rtsp { @@ -129,7 +125,7 @@ public: //返回有效负载总长度,不包括csrc、ext、padding size_t getPayloadSize(size_t rtp_size) const; //打印调试信息 - string dumpString(size_t rtp_size) const; + std::string dumpString(size_t rtp_size) const; private: //返回有效负载偏移量 @@ -143,7 +139,7 @@ private: #endif // defined(_WIN32) //此rtp为rtp over tcp形式,需要忽略前4个字节 -class RtpPacket : public BufferRaw{ +class RtpPacket : public toolkit::BufferRaw{ public: using Ptr = std::shared_ptr; enum { @@ -157,7 +153,7 @@ public: const RtpHeader* getHeader() const; //打印调试信息 - string dumpString() const; + std::string dumpString() const; //主机字节序的seq uint16_t getSeq() const; @@ -181,12 +177,12 @@ public: static Ptr create(); private: - friend class ResourcePool_l; + friend class toolkit::ResourcePool_l; RtpPacket() = default; private: //对象个数统计 - ObjectStatistic _statistic; + toolkit::ObjectStatistic _statistic; }; class RtpPayload { @@ -205,29 +201,29 @@ private: class SdpTrack { public: using Ptr = std::shared_ptr; - string _t; - string _b; + std::string _t; + std::string _b; uint16_t _port; float _duration = 0; float _start = 0; float _end = 0; - map _other; - multimap _attr; + std::map _other; + std::multimap _attr; - string toString(uint16_t port = 0) const; - string getName() const; - string getControlUrl(const string &base_url) const; + std::string toString(uint16_t port = 0) const; + std::string getName() const; + std::string getControlUrl(const std::string &base_url) const; public: int _pt; int _channel; int _samplerate; TrackType _type; - string _codec; - string _fmtp; - string _control; + std::string _codec; + std::string _fmtp; + std::string _control; public: bool _inited = false; @@ -243,17 +239,17 @@ public: using Ptr = std::shared_ptr; SdpParser() {} - SdpParser(const string &sdp) { load(sdp); } + SdpParser(const std::string &sdp) { load(sdp); } ~SdpParser() {} - void load(const string &sdp); + void load(const std::string &sdp); bool available() const; SdpTrack::Ptr getTrack(TrackType type) const; - vector getAvailableTrack() const; - string toString() const; + std::vector getAvailableTrack() const; + std::string toString() const; private: - vector _track_vec; + std::vector _track_vec; }; /** @@ -263,18 +259,18 @@ class RtspUrl{ public: bool _is_ssl; uint16_t _port; - string _url; - string _user; - string _passwd; - string _host; + std::string _url; + std::string _user; + std::string _passwd; + std::string _host; public: RtspUrl() = default; ~RtspUrl() = default; - bool parse(const string &url); + bool parse(const std::string &url); private: - bool setup(bool,const string &, const string &, const string &); + bool setup(bool,const std::string &, const std::string &, const std::string &); }; /** @@ -300,7 +296,7 @@ public: * 获取sdp字符串 * @return */ - virtual string getSdp() const = 0; + virtual std::string getSdp() const = 0; /** * 获取pt @@ -336,7 +332,7 @@ public: * @param version sdp版本 */ TitleSdp(float dur_sec = 0, - const map &header = map(), + const std::map &header = std::map(), int version = 0) : Sdp(0, 0) { _printer << "v=" << version << "\r\n"; @@ -362,7 +358,7 @@ public: _printer << "a=control:*\r\n"; } - string getSdp() const override { + std::string getSdp() const override { return _printer; } @@ -376,15 +372,15 @@ public: private: float _dur_sec = 0; - _StrPrinter _printer; + toolkit::_StrPrinter _printer; }; //创建rtp over tcp4个字节的头 -Buffer::Ptr makeRtpOverTcpPrefix(uint16_t size, uint8_t interleaved); +toolkit::Buffer::Ptr makeRtpOverTcpPrefix(uint16_t size, uint8_t interleaved); //创建rtp-rtcp端口对 -void makeSockPair(std::pair &pair, const string &local_ip); +void makeSockPair(std::pair &pair, const std::string &local_ip); //十六进制方式打印ssrc -string printSSRC(uint32_t ui32Ssrc); +std::string printSSRC(uint32_t ui32Ssrc); } //namespace mediakit #endif //RTSP_RTSP_H_ diff --git a/src/Rtsp/RtspDemuxer.h b/src/Rtsp/RtspDemuxer.h index 865b84be..7941d919 100644 --- a/src/Rtsp/RtspDemuxer.h +++ b/src/Rtsp/RtspDemuxer.h @@ -16,9 +16,6 @@ #include "Util/TimeTicker.h" #include "RtpCodec.h" -using namespace std; -using namespace toolkit; - namespace mediakit { class RtspDemuxer : public Demuxer { @@ -30,7 +27,7 @@ public: /** * 加载sdp */ - void loadSdp(const string &sdp); + void loadSdp(const std::string &sdp); /** * 开始解复用 diff --git a/src/Rtsp/RtspMediaSource.h b/src/Rtsp/RtspMediaSource.h index d129d712..03fdd1b2 100644 --- a/src/Rtsp/RtspMediaSource.h +++ b/src/Rtsp/RtspMediaSource.h @@ -25,9 +25,9 @@ #include "Util/ResourcePool.h" #include "Util/NoticeCenter.h" #include "Thread/ThreadPool.h" -using namespace std; -using namespace toolkit; + #define RTP_GOP_SIZE 512 + namespace mediakit { /** @@ -36,12 +36,12 @@ namespace mediakit { * 只要生成了这两要素,那么要实现rtsp推流、rtsp服务器就很简单了 * rtsp推拉流协议中,先传递sdp,然后再协商传输方式(tcp/udp/组播),最后一直传递rtp */ -class RtspMediaSource : public MediaSource, public RingDelegate, private PacketCache { +class RtspMediaSource : public MediaSource, public toolkit::RingDelegate, private PacketCache { public: - typedef ResourcePool PoolType; - typedef std::shared_ptr Ptr; - typedef std::shared_ptr > RingDataType; - typedef RingBuffer RingType; + using PoolType = toolkit::ResourcePool; + using Ptr = std::shared_ptr; + using RingDataType = std::shared_ptr >; + using RingType = toolkit::RingBuffer; /** * 构造函数 @@ -50,9 +50,9 @@ public: * @param stream_id 流id * @param ring_size 可以设置固定的环形缓冲大小,0则自适应 */ - RtspMediaSource(const string &vhost, - const string &app, - const string &stream_id, + RtspMediaSource(const std::string &vhost, + const std::string &app, + const std::string &stream_id, int ring_size = RTP_GOP_SIZE) : MediaSource(RTSP_SCHEMA, vhost, app, stream_id), _ring_size(ring_size) {} @@ -75,7 +75,7 @@ public: /** * 获取该源的sdp */ - const string &getSdp() const { + const std::string &getSdp() const { return _sdp; } @@ -140,7 +140,7 @@ public: /** * 设置sdp */ - virtual void setSdp(const string &sdp) { + virtual void setSdp(const std::string &sdp) { SdpParser sdp_parser(sdp); _tracks[TrackVideo] = sdp_parser.getTrack(TrackVideo); _tracks[TrackAudio] = sdp_parser.getTrack(TrackAudio); @@ -167,7 +167,7 @@ public: track->_ssrc = rtp->getSSRC(); } if (!_ring) { - weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); + std::weak_ptr weakSelf = std::dynamic_pointer_cast(shared_from_this()); auto lam = [weakSelf](int size) { auto strongSelf = weakSelf.lock(); if (!strongSelf) { @@ -198,7 +198,7 @@ private: * @param rtp_list rtp包列表 * @param key_pos 是否包含关键帧 */ - void onFlush(std::shared_ptr > rtp_list, bool key_pos) override { + void onFlush(std::shared_ptr > rtp_list, bool key_pos) override { //如果不存在视频,那么就没有存在GOP缓存的意义,所以is_key一直为true确保一直清空GOP缓存 _ring->write(std::move(rtp_list), _have_video ? key_pos : true); } @@ -206,7 +206,7 @@ private: private: bool _have_video = false; int _ring_size; - string _sdp; + std::string _sdp; RingType::Ptr _ring; SdpTrack::Ptr _tracks[TrackMax]; }; diff --git a/src/Rtsp/RtspMediaSourceImp.h b/src/Rtsp/RtspMediaSourceImp.h index cbc1623b..34c82871 100644 --- a/src/Rtsp/RtspMediaSourceImp.h +++ b/src/Rtsp/RtspMediaSourceImp.h @@ -15,7 +15,6 @@ #include "RtspMediaSource.h" #include "RtspDemuxer.h" #include "Common/MultiMediaSourceMuxer.h" -using namespace toolkit; namespace mediakit { class RtspMediaSourceImp : public RtspMediaSource, private TrackListener, public MultiMediaSourceMuxer::Listener { @@ -29,7 +28,7 @@ public: * @param id 流id * @param ringSize 环形缓存大小 */ - RtspMediaSourceImp(const string &vhost, const string &app, const string &id, int ringSize = RTP_GOP_SIZE) : RtspMediaSource(vhost, app, id,ringSize) { + RtspMediaSourceImp(const std::string &vhost, const std::string &app, const std::string &id, int ringSize = RTP_GOP_SIZE) : RtspMediaSource(vhost, app, id,ringSize) { _demuxer = std::make_shared(); _demuxer->setTrackListener(this); } @@ -39,7 +38,7 @@ public: /** * 设置sdp */ - void setSdp(const string &strSdp) override { + void setSdp(const std::string &strSdp) override { if (!getSdp().empty()) { return; } @@ -84,7 +83,7 @@ public: //导致rtc无法播放,所以在rtsp推流rtc播放时,建议关闭直接代理模式 _muxer = std::make_shared(getVhost(), getApp(), getId(), _demuxer->getDuration(), !directProxy, true, enableHls, enableMP4); _muxer->setMediaListener(getListener()); - _muxer->setTrackListener(static_pointer_cast(shared_from_this())); + _muxer->setTrackListener(std::static_pointer_cast(shared_from_this())); //让_muxer对象拦截一部分事件(比如说录像相关事件) MediaSource::setListener(_muxer); diff --git a/src/Rtsp/RtspMediaSourceMuxer.h b/src/Rtsp/RtspMediaSourceMuxer.h index d6cbe3df..539a2011 100644 --- a/src/Rtsp/RtspMediaSourceMuxer.h +++ b/src/Rtsp/RtspMediaSourceMuxer.h @@ -21,9 +21,9 @@ class RtspMediaSourceMuxer : public RtspMuxer, public MediaSourceEventIntercepto public: typedef std::shared_ptr Ptr; - RtspMediaSourceMuxer(const string &vhost, - const string &strApp, - const string &strId, + RtspMediaSourceMuxer(const std::string &vhost, + const std::string &strApp, + const std::string &strId, const TitleSdp::Ptr &title = nullptr) : RtspMuxer(title){ _media_src = std::make_shared(vhost,strApp,strId); getRtpRing()->setDelegate(_media_src); diff --git a/src/Rtsp/RtspMuxer.cpp b/src/Rtsp/RtspMuxer.cpp index 831dd198..890232f4 100644 --- a/src/Rtsp/RtspMuxer.cpp +++ b/src/Rtsp/RtspMuxer.cpp @@ -11,6 +11,9 @@ #include "RtspMuxer.h" #include "Extension/Factory.h" +using namespace std; +using namespace toolkit; + namespace mediakit { void RtspMuxer::onRtp(RtpPacket::Ptr in, bool is_key) { diff --git a/src/Rtsp/RtspMuxer.h b/src/Rtsp/RtspMuxer.h index 8194f1cd..677eaabd 100644 --- a/src/Rtsp/RtspMuxer.h +++ b/src/Rtsp/RtspMuxer.h @@ -18,15 +18,17 @@ namespace mediakit{ -class RingDelegateHelper : public RingDelegate { +class RingDelegateHelper : public toolkit::RingDelegate { public: - typedef function onRtp; + using onRtp = std::function ; - ~RingDelegateHelper() override{} - RingDelegateHelper(onRtp on_rtp){ + ~RingDelegateHelper() override {} + + RingDelegateHelper(onRtp on_rtp) { _on_rtp = std::move(on_rtp); } - void onWrite(RtpPacket::Ptr in, bool is_key) override{ + + void onWrite(RtpPacket::Ptr in, bool is_key) override { _on_rtp(std::move(in), is_key); } @@ -52,7 +54,7 @@ public: * 获取完整的SDP字符串 * @return SDP字符串 */ - string getSdp() ; + std::string getSdp() ; /** * 获取rtp环形缓存 @@ -85,7 +87,7 @@ private: uint32_t _rtp_stamp[TrackMax]{0}; uint64_t _ntp_stamp[TrackMax]{0}; uint64_t _ntp_stamp_start; - string _sdp; + std::string _sdp; Stamp _stamp[TrackMax]; RtpCodec::Ptr _encoder[TrackMax]; RtpRing::RingType::Ptr _rtpRing; diff --git a/src/Rtsp/RtspPlayer.cpp b/src/Rtsp/RtspPlayer.cpp index a358ad28..30c18d7a 100644 --- a/src/Rtsp/RtspPlayer.cpp +++ b/src/Rtsp/RtspPlayer.cpp @@ -18,7 +18,7 @@ #include "Util/base64.h" #include "Rtcp/Rtcp.h" using namespace toolkit; -using namespace mediakit::Client; +using namespace std; namespace mediakit { @@ -74,19 +74,19 @@ void RtspPlayer::play(const string &strUrl){ teardown(); if (url._user.size()) { - (*this)[kRtspUser] = url._user; + (*this)[Client::kRtspUser] = url._user; } if (url._passwd.size()) { - (*this)[kRtspPwd] = url._passwd; - (*this)[kRtspPwdIsMD5] = false; + (*this)[Client::kRtspPwd] = url._passwd; + (*this)[Client::kRtspPwdIsMD5] = false; } _play_url = url._url; - _rtp_type = (Rtsp::eRtpType)(int)(*this)[kRtpType]; + _rtp_type = (Rtsp::eRtpType)(int)(*this)[Client::kRtpType]; DebugL << url._url << " " << (url._user.size() ? url._user : "null") << " " << (url._passwd.size() ? url._passwd : "null") << " " << _rtp_type; weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); - float playTimeOutSec = (*this)[kTimeoutMS].as() / 1000.0f; + float playTimeOutSec = (*this)[Client::kTimeoutMS].as() / 1000.0f; _play_check_timer.reset(new Timer(playTimeOutSec, [weakSelf]() { auto strongSelf=weakSelf.lock(); if(!strongSelf) { @@ -96,8 +96,8 @@ void RtspPlayer::play(const string &strUrl){ return false; }, getPoller())); - if(!(*this)[kNetAdapter].empty()){ - setNetAdapter((*this)[kNetAdapter]); + if(!(*this)[Client::kNetAdapter].empty()){ + setNetAdapter((*this)[Client::kNetAdapter]); } startConnect(url._host, url._port, playTimeOutSec); } @@ -571,7 +571,7 @@ void RtspPlayer::sendRtspRequest(const string &cmd, const string &url,const StrC header.emplace("Session", _session_id); } - if(!_realm.empty() && !(*this)[kRtspUser].empty()){ + if(!_realm.empty() && !(*this)[Client::kRtspUser].empty()){ if(!_md5_nonce.empty()){ //MD5认证 /* @@ -582,22 +582,22 @@ void RtspPlayer::sendRtspRequest(const string &cmd, const string &url,const StrC (2)当password为ANSI字符串,则 response= md5( md5(username:realm:password):nonce:md5(public_method:url) ); */ - string encrypted_pwd = (*this)[kRtspPwd]; - if(!(*this)[kRtspPwdIsMD5].as()){ - encrypted_pwd = MD5((*this)[kRtspUser] + ":" + _realm + ":" + encrypted_pwd).hexdigest(); + string encrypted_pwd = (*this)[Client::kRtspPwd]; + if(!(*this)[Client::kRtspPwdIsMD5].as()){ + encrypted_pwd = MD5((*this)[Client::kRtspUser] + ":" + _realm + ":" + encrypted_pwd).hexdigest(); } auto response = MD5(encrypted_pwd + ":" + _md5_nonce + ":" + MD5(cmd + ":" + url).hexdigest()).hexdigest(); _StrPrinter printer; printer << "Digest "; - printer << "username=\"" << (*this)[kRtspUser] << "\", "; + printer << "username=\"" << (*this)[Client::kRtspUser] << "\", "; printer << "realm=\"" << _realm << "\", "; printer << "nonce=\"" << _md5_nonce << "\", "; printer << "uri=\"" << url << "\", "; printer << "response=\"" << response << "\""; header.emplace("Authorization",printer); - }else if(!(*this)[kRtspPwdIsMD5].as()){ + }else if(!(*this)[Client::kRtspPwdIsMD5].as()){ //base64认证 - string authStr = StrPrinter << (*this)[kRtspUser] << ":" << (*this)[kRtspPwd]; + string authStr = StrPrinter << (*this)[Client::kRtspUser] << ":" << (*this)[Client::kRtspPwd]; char authStrBase64[1024] = {0}; av_base64_encode(authStrBase64, sizeof(authStrBase64), (uint8_t *) authStr.data(), (int) authStr.size()); header.emplace("Authorization",StrPrinter << "Basic " << authStrBase64 ); @@ -685,7 +685,7 @@ void RtspPlayer::onPlayResult_l(const SockException &ex , bool handshake_done) { if (!ex) { //播放成功,恢复rtp接收超时定时器 _rtp_recv_ticker.resetTime(); - auto timeoutMS = (*this)[kMediaTimeoutMS].as(); + auto timeoutMS = (*this)[Client::kMediaTimeoutMS].as(); weak_ptr weakSelf = dynamic_pointer_cast(shared_from_this()); auto lam = [weakSelf, timeoutMS]() { auto strongSelf = weakSelf.lock(); diff --git a/src/Rtsp/RtspPlayer.h b/src/Rtsp/RtspPlayer.h index b624759b..83eb5bfa 100644 --- a/src/Rtsp/RtspPlayer.h +++ b/src/Rtsp/RtspPlayer.h @@ -27,20 +27,17 @@ #include "Common/Stamp.h" #include "Rtcp/RtcpContext.h" -using namespace std; -using namespace toolkit; - namespace mediakit { //实现了rtsp播放器协议部分的功能,及数据接收功能 -class RtspPlayer: public PlayerBase, public TcpClient, public RtspSplitter, public RtpReceiver { +class RtspPlayer : public PlayerBase, public toolkit::TcpClient, public RtspSplitter, public RtpReceiver { public: - typedef std::shared_ptr Ptr; + using Ptr = std::shared_ptr; - RtspPlayer(const EventPoller::Ptr &poller); + RtspPlayer(const toolkit::EventPoller::Ptr &poller); ~RtspPlayer() override; - void play(const string &strUrl) override; + void play(const std::string &strUrl) override; void pause(bool pause) override; void speed(float speed) override; void teardown() override; @@ -48,7 +45,7 @@ public: protected: //派生类回调函数 - virtual bool onCheckSDP(const string &sdp) = 0; + virtual bool onCheckSDP(const std::string &sdp) = 0; virtual void onRecvRTP(RtpPacket::Ptr rtp, const SdpTrack::Ptr &track) = 0; uint32_t getProgressMilliSecond() const; void seekToMilliSecond(uint32_t ms); @@ -90,21 +87,21 @@ protected: virtual void onRtcpPacket(int track_idx, SdpTrack::Ptr &track, uint8_t *data, size_t len); /////////////TcpClient override///////////// - void onConnect(const SockException &err) override; - void onRecv(const Buffer::Ptr &buf) override; - void onErr(const SockException &ex) override; + void onConnect(const toolkit::SockException &err) override; + void onRecv(const toolkit::Buffer::Ptr &buf) override; + void onErr(const toolkit::SockException &ex) override; private: - void onPlayResult_l(const SockException &ex , bool handshake_done); + void onPlayResult_l(const toolkit::SockException &ex , bool handshake_done); int getTrackIndexByInterleaved(int interleaved) const; int getTrackIndexByTrackType(TrackType track_type) const; void handleResSETUP(const Parser &parser, unsigned int track_idx); void handleResDESCRIBE(const Parser &parser); - bool handleAuthenticationFailure(const string &wwwAuthenticateParamsStr); + bool handleAuthenticationFailure(const std::string &wwwAuthenticateParamsStr); void handleResPAUSE(const Parser &parser, int type); - bool handleResponse(const string &cmd, const Parser &parser); + bool handleResponse(const std::string &cmd, const Parser &parser); void sendOptions(); void sendSetup(unsigned int track_idx); @@ -112,8 +109,8 @@ private: void sendDescribe(); void sendTeardown(); void sendKeepAlive(); - void sendRtspRequest(const string &cmd, const string &url ,const StrCaseMap &header = StrCaseMap()); - void sendRtspRequest(const string &cmd, const string &url ,const std::initializer_list &header); + void sendRtspRequest(const std::string &cmd, const std::string &url ,const StrCaseMap &header = StrCaseMap()); + void sendRtspRequest(const std::string &cmd, const std::string &url ,const std::initializer_list &header); void createUdpSockIfNecessary(int track_idx); private: @@ -122,37 +119,37 @@ private: //轮流发送rtcp与GET_PARAMETER保活 bool _send_rtcp[2] = {true, true}; - string _play_url; - vector _sdp_track; - function _on_response; + std::string _play_url; + std::vector _sdp_track; + std::function _on_response; //RTP端口,trackid idx 为数组下标 - Socket::Ptr _rtp_sock[2]; + toolkit::Socket::Ptr _rtp_sock[2]; //RTCP端口,trackid idx 为数组下标 - Socket::Ptr _rtcp_sock[2]; + toolkit::Socket::Ptr _rtcp_sock[2]; //rtsp鉴权相关 - string _md5_nonce; - string _realm; + std::string _md5_nonce; + std::string _realm; //rtsp info - string _session_id; + std::string _session_id; uint32_t _cseq_send = 1; - string _content_base; + std::string _content_base; Rtsp::eRtpType _rtp_type = Rtsp::RTP_TCP; //当前rtp时间戳 uint32_t _stamp[2] = {0, 0}; //超时功能实现 - Ticker _rtp_recv_ticker; - std::shared_ptr _play_check_timer; - std::shared_ptr _rtp_check_timer; + toolkit::Ticker _rtp_recv_ticker; + std::shared_ptr _play_check_timer; + std::shared_ptr _rtp_check_timer; //服务器支持的命令 - set _supported_cmd; + std::set _supported_cmd; ////////// rtcp //////////////// //rtcp发送时间,trackid idx 为数组下标 - Ticker _rtcp_send_ticker[2]; + toolkit::Ticker _rtcp_send_ticker[2]; //统计rtp并发送rtcp - vector _rtcp_context; + std::vector _rtcp_context; }; } /* namespace mediakit */ diff --git a/src/Rtsp/RtspPlayerImp.h b/src/Rtsp/RtspPlayerImp.h index cad54de8..bb3137c3 100644 --- a/src/Rtsp/RtspPlayerImp.h +++ b/src/Rtsp/RtspPlayerImp.h @@ -20,9 +20,6 @@ #include "Poller/Timer.h" #include "Util/TimeTicker.h" -using namespace std; -using namespace toolkit; - namespace mediakit { class RtspPlayerImp : public PlayerImp ,private TrackListener { @@ -30,10 +27,10 @@ public: using Ptr = std::shared_ptr; using Super = PlayerImp; - RtspPlayerImp(const EventPoller::Ptr &poller) : Super(poller) {} + RtspPlayerImp(const toolkit::EventPoller::Ptr &poller) : Super(poller) {} ~RtspPlayerImp() override { - DebugL << endl; + DebugL << std::endl; } float getProgress() const override { @@ -64,14 +61,14 @@ public: return _demuxer ? _demuxer->getDuration() : 0; } - vector getTracks(bool ready = true) const override { + std::vector getTracks(bool ready = true) const override { return _demuxer ? _demuxer->getTracks(ready) : Super::getTracks(ready); } private: //派生类回调函数 - bool onCheckSDP(const string &sdp) override { - _rtsp_media_src = dynamic_pointer_cast(_media_src); + bool onCheckSDP(const std::string &sdp) override { + _rtsp_media_src = std::dynamic_pointer_cast(_media_src); if (_rtsp_media_src) { _rtsp_media_src->setSdp(sdp); } @@ -90,7 +87,7 @@ private: } } - void onPlayResult(const SockException &ex) override { + void onPlayResult(const toolkit::SockException &ex) override { if (!(*this)[Client::kWaitTrackReady].as() || ex) { Super::onPlayResult(ex); return; @@ -101,7 +98,7 @@ private: void addTrackCompleted() override { if ((*this)[Client::kWaitTrackReady].as()) { - Super::onPlayResult(SockException(Err_success, "play success")); + Super::onPlayResult(toolkit::SockException(toolkit::Err_success, "play success")); } } diff --git a/src/Rtsp/RtspPusher.cpp b/src/Rtsp/RtspPusher.cpp index ab628210..942e2cfe 100644 --- a/src/Rtsp/RtspPusher.cpp +++ b/src/Rtsp/RtspPusher.cpp @@ -13,7 +13,8 @@ #include "RtspPusher.h" #include "RtspSession.h" -using namespace mediakit::Client; +using namespace std; +using namespace toolkit; namespace mediakit { @@ -63,20 +64,20 @@ void RtspPusher::publish(const string &url_str) { teardown(); if (url._user.size()) { - (*this)[kRtspUser] = url._user; + (*this)[Client::kRtspUser] = url._user; } if (url._passwd.size()) { - (*this)[kRtspPwd] = url._passwd; - (*this)[kRtspPwdIsMD5] = false; + (*this)[Client::kRtspPwd] = url._passwd; + (*this)[Client::kRtspPwdIsMD5] = false; } _url = url_str; - _rtp_type = (Rtsp::eRtpType) (int) (*this)[kRtpType]; + _rtp_type = (Rtsp::eRtpType) (int) (*this)[Client::kRtpType]; DebugL << url._url << " " << (url._user.size() ? url._user : "null") << " " << (url._passwd.size() ? url._passwd : "null") << " " << _rtp_type; weak_ptr weak_self = dynamic_pointer_cast(shared_from_this()); - float publish_timeout_sec = (*this)[kTimeoutMS].as() / 1000.0f; + float publish_timeout_sec = (*this)[Client::kTimeoutMS].as() / 1000.0f; _publish_timer.reset(new Timer(publish_timeout_sec, [weak_self]() { auto strong_self = weak_self.lock(); if (!strong_self) { @@ -86,8 +87,8 @@ void RtspPusher::publish(const string &url_str) { return false; }, getPoller())); - if (!(*this)[kNetAdapter].empty()) { - setNetAdapter((*this)[kNetAdapter]); + if (!(*this)[Client::kNetAdapter].empty()) { + setNetAdapter((*this)[Client::kNetAdapter]); } startConnect(url._host, url._port, publish_timeout_sec); @@ -467,7 +468,7 @@ void RtspPusher::sendRecord() { }); if (_rtp_type != Rtsp::RTP_TCP) { /////////////////////////心跳///////////////////////////////// - _beat_timer.reset(new Timer((*this)[kBeatIntervalMS].as() / 1000.0f, [weak_self]() { + _beat_timer.reset(new Timer((*this)[Client::kBeatIntervalMS].as() / 1000.0f, [weak_self]() { auto strong_self = weak_self.lock(); if (!strong_self) { return false; @@ -514,7 +515,7 @@ void RtspPusher::sendRtspRequest(const string &cmd, const string &url,const StrC header.emplace("Session", _session_id); } - if (!_realm.empty() && !(*this)[kRtspUser].empty()) { + if (!_realm.empty() && !(*this)[Client::kRtspUser].empty()) { if (!_nonce.empty()) { //MD5认证 /* @@ -525,22 +526,22 @@ void RtspPusher::sendRtspRequest(const string &cmd, const string &url,const StrC (2)当password为ANSI字符串,则 response= md5( md5(username:realm:password):nonce:md5(public_method:url) ); */ - string encrypted_pwd = (*this)[kRtspPwd]; - if (!(*this)[kRtspPwdIsMD5].as()) { - encrypted_pwd = MD5((*this)[kRtspUser] + ":" + _realm + ":" + encrypted_pwd).hexdigest(); + string encrypted_pwd = (*this)[Client::kRtspPwd]; + if (!(*this)[Client::kRtspPwdIsMD5].as()) { + encrypted_pwd = MD5((*this)[Client::kRtspUser] + ":" + _realm + ":" + encrypted_pwd).hexdigest(); } auto response = MD5(encrypted_pwd + ":" + _nonce + ":" + MD5(cmd + ":" + url).hexdigest()).hexdigest(); _StrPrinter printer; printer << "Digest "; - printer << "username=\"" << (*this)[kRtspUser] << "\", "; + printer << "username=\"" << (*this)[Client::kRtspUser] << "\", "; printer << "realm=\"" << _realm << "\", "; printer << "nonce=\"" << _nonce << "\", "; printer << "uri=\"" << url << "\", "; printer << "response=\"" << response << "\""; header.emplace("Authorization", printer); - } else if (!(*this)[kRtspPwdIsMD5].as()) { + } else if (!(*this)[Client::kRtspPwdIsMD5].as()) { //base64认证 - string authStr = StrPrinter << (*this)[kRtspUser] << ":" << (*this)[kRtspPwd]; + string authStr = StrPrinter << (*this)[Client::kRtspUser] << ":" << (*this)[Client::kRtspPwd]; char authStrBase64[1024] = {0}; av_base64_encode(authStrBase64, sizeof(authStrBase64), (uint8_t *) authStr.data(), (int)authStr.size()); header.emplace("Authorization", StrPrinter << "Basic " << authStrBase64); diff --git a/src/Rtsp/RtspPusher.h b/src/Rtsp/RtspPusher.h index 56e8a2b4..ec0087a0 100644 --- a/src/Rtsp/RtspPusher.h +++ b/src/Rtsp/RtspPusher.h @@ -23,24 +23,21 @@ #include "Pusher/PusherBase.h" #include "Rtcp/RtcpContext.h" -using namespace std; -using namespace toolkit; - namespace mediakit { -class RtspPusher : public TcpClient, public RtspSplitter, public PusherBase { +class RtspPusher : public toolkit::TcpClient, public RtspSplitter, public PusherBase { public: typedef std::shared_ptr Ptr; - RtspPusher(const EventPoller::Ptr &poller,const RtspMediaSource::Ptr &src); + RtspPusher(const toolkit::EventPoller::Ptr &poller,const RtspMediaSource::Ptr &src); ~RtspPusher() override; - void publish(const string &url) override; + void publish(const std::string &url) override; void teardown() override; protected: //for Tcpclient override - void onRecv(const Buffer::Ptr &buf) override; - void onConnect(const SockException &err) override; - void onErr(const SockException &ex) override; + void onRecv(const toolkit::Buffer::Ptr &buf) override; + void onConnect(const toolkit::SockException &err) override; + void onErr(const toolkit::SockException &ex) override; //RtspSplitter override void onWholeRtspPacket(Parser &parser) override ; @@ -49,7 +46,7 @@ protected: virtual void onRtcpPacket(int track_idx, SdpTrack::Ptr &track, uint8_t *data, size_t len); private: - void onPublishResult_l(const SockException &ex, bool handshake_done); + void onPublishResult_l(const toolkit::SockException &ex, bool handshake_done); void sendAnnounce(); void sendSetup(unsigned int track_idx); @@ -59,14 +56,14 @@ private: void handleResAnnounce(const Parser &parser); void handleResSetup(const Parser &parser, unsigned int track_idx); - bool handleAuthenticationFailure(const string ¶ms_str); + bool handleAuthenticationFailure(const std::string ¶ms_str); int getTrackIndexByInterleaved(int interleaved) const; int getTrackIndexByTrackType(TrackType type) const; void sendRtpPacket(const RtspMediaSource::RingDataType & pkt) ; - void sendRtspRequest(const string &cmd, const string &url ,const StrCaseMap &header = StrCaseMap(),const string &sdp = "" ); - void sendRtspRequest(const string &cmd, const string &url ,const std::initializer_list &header,const string &sdp = ""); + void sendRtspRequest(const std::string &cmd, const std::string &url ,const StrCaseMap &header = StrCaseMap(),const std::string &sdp = "" ); + void sendRtspRequest(const std::string &cmd, const std::string &url ,const std::initializer_list &header,const std::string &sdp = ""); void createUdpSockIfNecessary(int track_idx); void setSocketFlags(); @@ -77,29 +74,29 @@ private: Rtsp::eRtpType _rtp_type = Rtsp::RTP_TCP; //rtsp鉴权相关 - string _nonce; - string _realm; - string _url; - string _session_id; - string _content_base; + std::string _nonce; + std::string _realm; + std::string _url; + std::string _session_id; + std::string _content_base; SdpParser _sdp_parser; - vector _track_vec; + std::vector _track_vec; //RTP端口,trackid idx 为数组下标 - Socket::Ptr _rtp_sock[2]; + toolkit::Socket::Ptr _rtp_sock[2]; //RTCP端口,trackid idx 为数组下标 - Socket::Ptr _rtcp_sock[2]; + toolkit::Socket::Ptr _rtcp_sock[2]; //超时功能实现 - std::shared_ptr _publish_timer; + std::shared_ptr _publish_timer; //心跳定时器 - std::shared_ptr _beat_timer; + std::shared_ptr _beat_timer; std::weak_ptr _push_src; RtspMediaSource::RingType::RingReader::Ptr _rtsp_reader; - function _on_res_func; + std::function _on_res_func; ////////// rtcp //////////////// //rtcp发送时间,trackid idx 为数组下标 - Ticker _rtcp_send_ticker[2]; + toolkit::Ticker _rtcp_send_ticker[2]; //统计rtp并发送rtcp - vector _rtcp_context; + std::vector _rtcp_context; }; using RtspPusherImp = PusherImp; diff --git a/src/Rtsp/RtspSession.h b/src/Rtsp/RtspSession.h index 87712453..b272d6c8 100644 --- a/src/Rtsp/RtspSession.h +++ b/src/Rtsp/RtspSession.h @@ -28,18 +28,16 @@ #include "Common/Stamp.h" #include "Rtcp/RtcpContext.h" -using namespace std; -using namespace toolkit; - namespace mediakit { class RtspSession; -class BufferRtp : public Buffer{ +class BufferRtp : public toolkit::Buffer{ public: - typedef std::shared_ptr Ptr; - BufferRtp(Buffer::Ptr pkt, size_t offset = 0) : _offset(offset),_rtp(std::move(pkt)) {} - ~BufferRtp() override{} + using Ptr = std::shared_ptr; + + BufferRtp(Buffer::Ptr pkt, size_t offset = 0) : _offset(offset), _rtp(std::move(pkt)) {} + ~BufferRtp() override {} char *data() const override { return (char *)_rtp->data() + _offset; @@ -54,19 +52,19 @@ private: Buffer::Ptr _rtp; }; -class RtspSession: public TcpSession, public RtspSplitter, public RtpReceiver , public MediaSourceEvent{ +class RtspSession : public toolkit::TcpSession, public RtspSplitter, public RtpReceiver, public MediaSourceEvent { public: - typedef std::shared_ptr Ptr; - typedef std::function onGetRealm; + using Ptr = std::shared_ptr; + using onGetRealm = std::function; //encrypted为true是则表明是md5加密的密码,否则是明文密码 //在请求明文密码时如果提供md5密码者则会导致认证失败 - typedef std::function onAuth; + using onAuth = std::function; - RtspSession(const Socket::Ptr &sock); + RtspSession(const toolkit::Socket::Ptr &sock); virtual ~RtspSession(); ////TcpSession override//// - void onRecv(const Buffer::Ptr &buf) override; - void onError(const SockException &err) override; + void onRecv(const toolkit::Buffer::Ptr &buf) override; + void onError(const toolkit::SockException &err) override; void onManager() override; protected: @@ -90,12 +88,12 @@ protected: // 获取媒体源类型 MediaOriginType getOriginType(MediaSource &sender) const override; // 获取媒体源url或者文件路径 - string getOriginUrl(MediaSource &sender) const override; + std::string getOriginUrl(MediaSource &sender) const override; // 获取媒体源客户端相关信息 std::shared_ptr getOriginSock(MediaSource &sender) const override; /////TcpSession override//// - ssize_t send(Buffer::Ptr pkt) override; + ssize_t send(toolkit::Buffer::Ptr pkt) override; //收到RTCP包回调 virtual void onRtcpPacket(int track_idx, SdpTrack::Ptr &track, const char *data, size_t len); @@ -132,23 +130,23 @@ private: void send_NotAcceptable(); //获取track下标 int getTrackIndexByTrackType(TrackType type); - int getTrackIndexByControlUrl(const string &control_url); + int getTrackIndexByControlUrl(const std::string &control_url); int getTrackIndexByInterleaved(int interleaved); //一般用于接收udp打洞包,也用于rtsp推流 - void onRcvPeerUdpData(int interleaved, const Buffer::Ptr &buf, const struct sockaddr &addr); + void onRcvPeerUdpData(int interleaved, const toolkit::Buffer::Ptr &buf, const struct sockaddr &addr); //配合onRcvPeerUdpData使用 void startListenPeerUdpData(int track_idx); ////rtsp专有认证相关//// //认证成功 void onAuthSuccess(); //认证失败 - void onAuthFailed(const string &realm, const string &why, bool close = true); + void onAuthFailed(const std::string &realm, const std::string &why, bool close = true); //开始走rtsp专有认证流程 - void onAuthUser(const string &realm, const string &authorization); + void onAuthUser(const std::string &realm, const std::string &authorization); //校验base64方式的认证加密 - void onAuthBasic(const string &realm, const string &auth_base64); + void onAuthBasic(const std::string &realm, const std::string &auth_base64); //校验md5方式的认证加密 - void onAuthDigest(const string &realm, const string &auth_md5); + void onAuthDigest(const std::string &realm, const std::string &auth_md5); //触发url鉴权事件 void emitOnPlay(); //发送rtp给客户端 @@ -156,8 +154,8 @@ private: //触发rtcp发送 void updateRtcpContext(const RtpPacket::Ptr &rtp); //回复客户端 - bool sendRtspResponse(const string &res_code, const std::initializer_list &header, const string &sdp = "", const char *protocol = "RTSP/1.0"); - bool sendRtspResponse(const string &res_code, const StrCaseMap &header = StrCaseMap(), const string &sdp = "", const char *protocol = "RTSP/1.0"); + bool sendRtspResponse(const std::string &res_code, const std::initializer_list &header, const std::string &sdp = "", const char *protocol = "RTSP/1.0"); + bool sendRtspResponse(const std::string &res_code, const StrCaseMap &header = StrCaseMap(), const std::string &sdp = "", const char *protocol = "RTSP/1.0"); //设置socket标志 void setSocketFlags(); @@ -172,15 +170,15 @@ private: //消耗的总流量 uint64_t _bytes_usage = 0; //ContentBase - string _content_base; + std::string _content_base; //Session号 - string _sessionid; + std::string _sessionid; //记录是否需要rtsp专属鉴权,防止重复触发事件 - string _rtsp_realm; + std::string _rtsp_realm; //登录认证 - string _auth_nonce; + std::string _auth_nonce; //用于判断客户端是否超时 - Ticker _alive_ticker; + toolkit::Ticker _alive_ticker; //url解析后保存的相关信息 MediaInfo _media_info; @@ -193,35 +191,35 @@ private: //直播源读取器 RtspMediaSource::RingType::RingReader::Ptr _play_reader; //sdp里面有效的track,包含音频或视频 - vector _sdp_track; + std::vector _sdp_track; ////////RTP over udp//////// //RTP端口,trackid idx 为数组下标 - Socket::Ptr _rtp_socks[2]; + toolkit::Socket::Ptr _rtp_socks[2]; //RTCP端口,trackid idx 为数组下标 - Socket::Ptr _rtcp_socks[2]; + toolkit::Socket::Ptr _rtcp_socks[2]; //标记是否收到播放的udp打洞包,收到播放的udp打洞包后才能知道其外网udp端口号 - unordered_set _udp_connected_flags; + std::unordered_set _udp_connected_flags; ////////RTP over udp_multicast//////// //共享的rtp组播对象 RtpMultiCaster::Ptr _multicaster; ////////RTSP over HTTP //////// //quicktime 请求rtsp会产生两次tcp连接, //一次发送 get 一次发送post,需要通过x-sessioncookie关联起来 - string _http_x_sessioncookie; - function _on_recv; + std::string _http_x_sessioncookie; + std::function _on_recv; ////////// rtcp //////////////// //rtcp发送时间,trackid idx 为数组下标 - Ticker _rtcp_send_tickers[2]; + toolkit::Ticker _rtcp_send_tickers[2]; //统计rtp并发送rtcp - vector _rtcp_context; + std::vector _rtcp_context; bool _send_sr_rtcp[2] = {true, true}; }; /** * 支持ssl加密的rtsp服务器,可用于诸如亚马逊echo show这样的设备访问 */ -typedef TcpSessionWithSSL RtspSessionWithSSL; +using RtspSessionWithSSL = toolkit::TcpSessionWithSSL; } /* namespace mediakit */ diff --git a/src/Rtsp/RtspSplitter.cpp b/src/Rtsp/RtspSplitter.cpp index 808894d1..a29e1249 100644 --- a/src/Rtsp/RtspSplitter.cpp +++ b/src/Rtsp/RtspSplitter.cpp @@ -13,6 +13,9 @@ #include "Util/logger.h" #include "Util/util.h" +using namespace std; +using namespace toolkit; + namespace mediakit{ const char *RtspSplitter::onSearchPacketTail(const char *data, size_t len) { diff --git a/src/Rtsp/UDPServer.cpp b/src/Rtsp/UDPServer.cpp index d721f9c6..fdf56adc 100644 --- a/src/Rtsp/UDPServer.cpp +++ b/src/Rtsp/UDPServer.cpp @@ -13,6 +13,7 @@ #include "Util/onceToken.h" using namespace toolkit; +using namespace std; namespace mediakit { diff --git a/src/Rtsp/UDPServer.h b/src/Rtsp/UDPServer.h index ec2aa27d..a46cef85 100644 --- a/src/Rtsp/UDPServer.h +++ b/src/Rtsp/UDPServer.h @@ -20,30 +20,27 @@ #include "Util/logger.h" #include "Network/Socket.h" -using namespace std; -using namespace toolkit; - namespace mediakit { class UDPServer : public std::enable_shared_from_this { public: - typedef function< bool(int intervaled, const Buffer::Ptr &buffer, struct sockaddr *peer_addr)> onRecvData; + using onRecvData = std::function ; ~UDPServer(); static UDPServer &Instance(); - Socket::Ptr getSock(SocketHelper &helper, const char *local_ip, int interleaved, uint16_t local_port = 0); + toolkit::Socket::Ptr getSock(toolkit::SocketHelper &helper, const char *local_ip, int interleaved, uint16_t local_port = 0); void listenPeer(const char *peer_ip, void *obj, const onRecvData &cb); void stopListenPeer(const char *peer_ip, void *obj); private: UDPServer(); - void onRecv(int interleaved, const Buffer::Ptr &buf, struct sockaddr *peer_addr); - void onErr(const string &strKey,const SockException &err); + void onRecv(int interleaved, const toolkit::Buffer::Ptr &buf, struct sockaddr *peer_addr); + void onErr(const std::string &strKey, const toolkit::SockException &err); private: - mutex _mtx_udp_sock; - mutex _mtx_on_recv; - unordered_map _udp_sock_map; - unordered_map > _on_recv_map; + std::mutex _mtx_udp_sock; + std::mutex _mtx_on_recv; + std::unordered_map _udp_sock_map; + std::unordered_map > _on_recv_map; }; } /* namespace mediakit */ diff --git a/src/Shell/ShellCMD.h b/src/Shell/ShellCMD.h index 0a089f57..95c99a20 100644 --- a/src/Shell/ShellCMD.h +++ b/src/Shell/ShellCMD.h @@ -13,17 +13,15 @@ #include "Util/CMD.h" #include "Common/MediaSource.h" -using namespace toolkit; namespace mediakit { - -class CMD_media: public CMD { +class CMD_media : public toolkit::CMD { public: - CMD_media(){ - _parser.reset(new OptionParser([](const std::shared_ptr &stream,mINI &ini){ - MediaSource::for_each_media([&](const MediaSource::Ptr &media){ - if(ini.find("list") != ini.end()){ + CMD_media() { + _parser.reset(new toolkit::OptionParser([](const std::shared_ptr &stream, toolkit::mINI &ini) { + MediaSource::for_each_media([&](const MediaSource::Ptr &media) { + if (ini.find("list") != ini.end()) { //列出源 (*stream) << "\t" << media->getSchema() << "/" @@ -34,14 +32,14 @@ public: return; } - EventPollerPool::Instance().getPoller()->async([ini,media,stream](){ - if(ini.find("kick") != ini.end()){ + toolkit::EventPollerPool::Instance().getPoller()->async([ini, media, stream]() { + if (ini.find("kick") != ini.end()) { //踢出源 - do{ - if(!media) { + do { + if (!media) { break; } - if(!media->close(true)) { + if (!media->close(true)) { break; } (*stream) << "\t踢出成功:" @@ -51,7 +49,7 @@ public: << media->getId() << "\r\n"; return; - }while(0); + } while (0); (*stream) << "\t踢出失败:" << media->getSchema() << "/" << media->getVhost() << "/" @@ -59,19 +57,21 @@ public: << media->getId() << "\r\n"; } - },false); + }, false); }, ini["schema"], ini["vhost"], ini["app"], ini["stream"]); })); - (*_parser) << Option('k', "kick", Option::ArgNone,nullptr,false, "踢出媒体源", nullptr); - (*_parser) << Option('l', "list", Option::ArgNone,nullptr,false, "列出媒体源", nullptr); - (*_parser) << Option('S', "schema", Option::ArgRequired,nullptr,false, "协议筛选", nullptr); - (*_parser) << Option('v', "vhost", Option::ArgRequired,nullptr,false, "虚拟主机筛选", nullptr); - (*_parser) << Option('a', "app", Option::ArgRequired,nullptr,false, "应用名筛选", nullptr); - (*_parser) << Option('s', "stream", Option::ArgRequired,nullptr,false, "流id筛选", nullptr); + (*_parser) << toolkit::Option('k', "kick", toolkit::Option::ArgNone, nullptr, false, "踢出媒体源", nullptr); + (*_parser) << toolkit::Option('l', "list", toolkit::Option::ArgNone, nullptr, false, "列出媒体源", nullptr); + (*_parser) << toolkit::Option('S', "schema", toolkit::Option::ArgRequired, nullptr, false, "协议筛选", nullptr); + (*_parser) << toolkit::Option('v', "vhost", toolkit::Option::ArgRequired, nullptr, false, "虚拟主机筛选", nullptr); + (*_parser) << toolkit::Option('a', "app", toolkit::Option::ArgRequired, nullptr, false, "应用名筛选", nullptr); + (*_parser) << toolkit::Option('s', "stream", toolkit::Option::ArgRequired, nullptr, false, "流id筛选", nullptr); } + virtual ~CMD_media() {} + const char *description() const override { return "媒体源相关操作."; } diff --git a/src/Shell/ShellSession.cpp b/src/Shell/ShellSession.cpp index bd5f7fd5..79c7b1b9 100644 --- a/src/Shell/ShellSession.cpp +++ b/src/Shell/ShellSession.cpp @@ -14,6 +14,8 @@ #include "Util/NoticeCenter.h" #include "Common/config.h" #include "ShellCMD.h" + +using namespace std; using namespace toolkit; namespace mediakit { diff --git a/src/Shell/ShellSession.h b/src/Shell/ShellSession.h index 5d38b503..f061a55f 100644 --- a/src/Shell/ShellSession.h +++ b/src/Shell/ShellSession.h @@ -15,29 +15,28 @@ #include "Common/config.h" #include "Util/TimeTicker.h" #include "Network/TcpSession.h" -using namespace toolkit; namespace mediakit { -class ShellSession: public TcpSession { +class ShellSession: public toolkit::TcpSession { public: - ShellSession(const Socket::Ptr &_sock); + ShellSession(const toolkit::Socket::Ptr &_sock); virtual ~ShellSession(); - void onRecv(const Buffer::Ptr &) override; - void onError(const SockException &err) override; + void onRecv(const toolkit::Buffer::Ptr &) override; + void onError(const toolkit::SockException &err) override; void onManager() override; private: - inline bool onCommandLine(const string &); + inline bool onCommandLine(const std::string &); inline void pleaseInputUser(); inline void pleaseInputPasswd(); inline void printShellPrefix(); - function _loginInterceptor; - string _strRecvBuf; - Ticker _beatTicker; - string _strUserName; + std::function _loginInterceptor; + std::string _strRecvBuf; + toolkit::Ticker _beatTicker; + std::string _strUserName; }; } /* namespace mediakit */ diff --git a/src/TS/TSMediaSource.h b/src/TS/TSMediaSource.h index d51dce9e..5d9658b0 100644 --- a/src/TS/TSMediaSource.h +++ b/src/TS/TSMediaSource.h @@ -12,13 +12,13 @@ #define ZLMEDIAKIT_TSMEDIASOURCE_H #include "Common/MediaSource.h" -using namespace toolkit; + #define TS_GOP_SIZE 512 namespace mediakit { //TS直播数据包 -class TSPacket : public BufferOffset{ +class TSPacket : public toolkit::BufferOffset{ public: using Ptr = std::shared_ptr; @@ -31,15 +31,15 @@ public: }; //TS直播源 -class TSMediaSource : public MediaSource, public RingDelegate, private PacketCache{ +class TSMediaSource : public MediaSource, public toolkit::RingDelegate, private PacketCache{ public: using Ptr = std::shared_ptr; - using RingDataType = std::shared_ptr >; - using RingType = RingBuffer; + using RingDataType = std::shared_ptr >; + using RingType = toolkit::RingBuffer; - TSMediaSource(const string &vhost, - const string &app, - const string &stream_id, + TSMediaSource(const std::string &vhost, + const std::string &app, + const std::string &stream_id, int ring_size = TS_GOP_SIZE) : MediaSource(TS_SCHEMA, vhost, app, stream_id), _ring_size(ring_size) {} ~TSMediaSource() override = default; @@ -85,7 +85,7 @@ public: private: void createRing(){ - weak_ptr weak_self = dynamic_pointer_cast(shared_from_this()); + std::weak_ptr weak_self = std::dynamic_pointer_cast(shared_from_this()); _ring = std::make_shared(_ring_size, [weak_self](int size) { auto strong_self = weak_self.lock(); if (!strong_self) { @@ -103,7 +103,7 @@ private: * @param packet_list 合并写缓存列队 * @param key_pos 是否包含关键帧 */ - void onFlush(std::shared_ptr > packet_list, bool key_pos) override { + void onFlush(std::shared_ptr > packet_list, bool key_pos) override { //如果不存在视频,那么就没有存在GOP缓存的意义,所以确保一直清空GOP缓存 _ring->write(std::move(packet_list), _have_video ? key_pos : true); } diff --git a/src/TS/TSMediaSourceMuxer.h b/src/TS/TSMediaSourceMuxer.h index edff41d6..9a96f0c8 100644 --- a/src/TS/TSMediaSourceMuxer.h +++ b/src/TS/TSMediaSourceMuxer.h @@ -21,9 +21,9 @@ class TSMediaSourceMuxer : public MpegMuxer, public MediaSourceEventInterceptor, public: using Ptr = std::shared_ptr; - TSMediaSourceMuxer(const string &vhost, - const string &app, - const string &stream_id) : MpegMuxer(false) { + TSMediaSourceMuxer(const std::string &vhost, + const std::string &app, + const std::string &stream_id) : MpegMuxer(false) { _media_src = std::make_shared(vhost, app, stream_id); } @@ -66,7 +66,7 @@ public: } protected: - void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) override { + void onWrite(std::shared_ptr buffer, uint32_t timestamp, bool key_pos) override { if (!buffer) { return; } diff --git a/tests/tab.cpp b/tests/tab.cpp index c3512fe6..e937330e 100644 --- a/tests/tab.cpp +++ b/tests/tab.cpp @@ -10,6 +10,7 @@ #include #include +#include #include "Util/CMD.h" #include "Util/util.h" #include "Util/logger.h" diff --git a/tests/test_bench_proxy.cpp b/tests/test_bench_proxy.cpp index 33b9a1d3..4a178cea 100644 --- a/tests/test_bench_proxy.cpp +++ b/tests/test_bench_proxy.cpp @@ -135,7 +135,7 @@ int main(int argc, char *argv[]) { for (auto i = 0; i < proxy_count; ++i) { auto stream = to_string(i); PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", stream, false, false)); - (*player)[kRtpType] = rtp_type; + (*player)[Client::kRtpType] = rtp_type; player->play(in_url); proxyMap.emplace(stream, player); //休眠后再启动下一个拉流代理,防止短时间海量链接 diff --git a/tests/test_bench_pull.cpp b/tests/test_bench_pull.cpp index 5df13c41..e5e79eae 100644 --- a/tests/test_bench_pull.cpp +++ b/tests/test_bench_pull.cpp @@ -139,9 +139,9 @@ int main(int argc, char *argv[]) { player_map.erase(tag); }); //设置为性能测试模式 - (*player)[kBenchmarkMode] = true; + (*player)[Client::kBenchmarkMode] = true; //设置rtsp拉流方式(在rtsp拉流时有效) - (*player)[kRtpType] = rtp_type; + (*player)[Client::kRtpType] = rtp_type; //提高压测性能与正确性 (*player)[Client::kWaitTrackReady] = false; //发起播放请求 diff --git a/tests/test_bench_push.cpp b/tests/test_bench_push.cpp index 3ea77fce..8c1046d3 100644 --- a/tests/test_bench_push.cpp +++ b/tests/test_bench_push.cpp @@ -143,7 +143,7 @@ int main(int argc, char *argv[]) { //添加拉流代理 auto proxy = std::make_shared(DEFAULT_VHOST, "app", "test", false, false); //rtsp拉流代理方式 - (*proxy)[kRtpType] = rtp_type; + (*proxy)[Client::kRtpType] = rtp_type; //开始拉流代理 proxy->play(in_url); diff --git a/tests/test_server.cpp b/tests/test_server.cpp index 86506ee5..7cd58026 100644 --- a/tests/test_server.cpp +++ b/tests/test_server.cpp @@ -244,7 +244,7 @@ int main(int argc,char *argv[]) { PlayerProxy::Ptr player(new PlayerProxy(DEFAULT_VHOST, "live", std::string("chn") + to_string(i).data())); //指定RTP over TCP(播放rtsp时有效) - (*player)[kRtpType] = Rtsp::RTP_TCP; + (*player)[Client::kRtpType] = Rtsp::RTP_TCP; //开始播放,如果播放失败或者播放中止,将会自动重试若干次,重试次数在配置文件中配置,默认一直重试 player->play(url); //需要保存PlayerProxy,否则作用域结束就会销毁该对象 diff --git a/tests/test_sortor.cpp b/tests/test_sortor.cpp index 19570706..be153b9c 100644 --- a/tests/test_sortor.cpp +++ b/tests/test_sortor.cpp @@ -13,6 +13,7 @@ #include #include #include "Rtsp/RtpReceiver.h" + using namespace std; using namespace mediakit; diff --git a/tests/test_wsClient.cpp b/tests/test_wsClient.cpp index 57b9e520..fd70eb37 100644 --- a/tests/test_wsClient.cpp +++ b/tests/test_wsClient.cpp @@ -14,6 +14,7 @@ #include "Util/MD5.h" #include "Util/logger.h" #include "Http/WebSocketClient.h" + using namespace std; using namespace toolkit; using namespace mediakit; diff --git a/tests/test_wsServer.cpp b/tests/test_wsServer.cpp index c8e802b5..f3ebda9d 100644 --- a/tests/test_wsServer.cpp +++ b/tests/test_wsServer.cpp @@ -14,6 +14,7 @@ #include "Util/MD5.h" #include "Util/logger.h" #include "Http/WebSocketSession.h" + using namespace std; using namespace toolkit; using namespace mediakit; diff --git a/webrtc/DtlsTransport.cpp b/webrtc/DtlsTransport.cpp index 708b89f6..0e2f160a 100644 --- a/webrtc/DtlsTransport.cpp +++ b/webrtc/DtlsTransport.cpp @@ -30,6 +30,8 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include // std::memcpy(), std::strcmp() #include "Util/util.h" +using namespace std; + #define LOG_OPENSSL_ERROR(desc) \ do \ { \ diff --git a/webrtc/Nack.cpp b/webrtc/Nack.cpp index 91d4026d..6628e507 100644 --- a/webrtc/Nack.cpp +++ b/webrtc/Nack.cpp @@ -10,6 +10,10 @@ #include "Nack.h" +using namespace std; +using namespace toolkit; +using namespace mediakit; + static constexpr uint32_t kMaxNackMS = 10 * 1000; void NackList::push_back(RtpPacket::Ptr rtp) { diff --git a/webrtc/Nack.h b/webrtc/Nack.h index 6d987bfd..bc82eb88 100644 --- a/webrtc/Nack.h +++ b/webrtc/Nack.h @@ -14,30 +14,29 @@ #include "Rtsp/Rtsp.h" #include "Rtcp/RtcpFCI.h" -using namespace mediakit; class NackList { public: NackList() = default; ~NackList() = default; - void push_back(RtpPacket::Ptr rtp); - void for_each_nack(const FCI_NACK &nack, const function &cb); + void push_back(mediakit::RtpPacket::Ptr rtp); + void for_each_nack(const mediakit::FCI_NACK &nack, const std::function &cb); private: void pop_front(); uint32_t get_cache_ms(); - RtpPacket::Ptr *get_rtp(uint16_t seq); + mediakit::RtpPacket::Ptr *get_rtp(uint16_t seq); private: - deque _nack_cache_seq; - unordered_map _nack_cache_pkt; + std::deque _nack_cache_seq; + std::unordered_map _nack_cache_pkt; }; class NackContext { public: using Ptr = std::shared_ptr; - using onNack = function; + using onNack = std::function; //最大保留的rtp丢包状态个数 static constexpr auto kNackMaxSize = 1024; //rtp丢包状态最长保留时间 @@ -56,14 +55,14 @@ public: private: void eraseFrontSeq(); - void doNack(const FCI_NACK &nack, bool record_nack); - void recordNack(const FCI_NACK &nack); + void doNack(const mediakit::FCI_NACK &nack, bool record_nack); + void recordNack(const mediakit::FCI_NACK &nack); void onRtx(uint16_t seq); private: int _rtt = 50; onNack _cb; - set _seq; + std::set _seq; uint16_t _last_max_seq = 0; struct NackStatus{ @@ -71,7 +70,7 @@ private: uint64_t update_stamp; int nack_count = 0; }; - map _nack_send_status; + std::map _nack_send_status; }; #endif //ZLMEDIAKIT_NACK_H diff --git a/webrtc/RtpExt.cpp b/webrtc/RtpExt.cpp index 89e56b00..5cbdbf56 100644 --- a/webrtc/RtpExt.cpp +++ b/webrtc/RtpExt.cpp @@ -15,6 +15,10 @@ #pragma pack(push, 1) #endif // defined(_WIN32) +using namespace std; +using namespace toolkit; +using namespace mediakit; + //https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01 //https://tools.ietf.org/html/rfc5285 diff --git a/webrtc/RtpExt.h b/webrtc/RtpExt.h index b05a8021..89581c88 100644 --- a/webrtc/RtpExt.h +++ b/webrtc/RtpExt.h @@ -17,8 +17,6 @@ #include "Common/macros.h" #include "Rtsp/Rtsp.h" -using namespace std; -using namespace mediakit; #define RTP_EXT_MAP(XX) \ XX(ssrc_audio_level, "urn:ietf:params:rtp-hdrext:ssrc-audio-level") \ @@ -51,25 +49,25 @@ class RtcMedia; class RtpExt { public: template - friend void appendExt(map &ret, uint8_t *ptr, const uint8_t *end); + friend void appendExt(std::map &ret, uint8_t *ptr, const uint8_t *end); friend class RtpExtContext; ~RtpExt() = default; - static map getExtValue(const RtpHeader *header); - static RtpExtType getExtType(const string &url); - static const string& getExtUrl(RtpExtType type); + static std::map getExtValue(const mediakit::RtpHeader *header); + static RtpExtType getExtType(const std::string &url); + static const std::string& getExtUrl(RtpExtType type); static const char *getExtName(RtpExtType type); void setType(RtpExtType type); RtpExtType getType() const; - string dumpString() const; + std::string dumpString() const; uint8_t getAudioLevel(bool *vad) const; uint32_t getAbsSendTime() const; uint16_t getTransportCCSeq() const; - string getSdesMid() const; - string getRtpStreamId() const; - string getRepairedRtpStreamId() const; + std::string getSdesMid() const; + std::string getRtpStreamId() const; + std::string getRepairedRtpStreamId() const; void getVideoTiming(uint8_t &flags, uint16_t &encode_start, @@ -116,27 +114,27 @@ class RtcMedia; class RtpExtContext { public: using Ptr = std::shared_ptr; - using OnGetRtp = function; + using OnGetRtp = std::function; RtpExtContext(const RtcMedia &media); ~RtpExtContext() = default; void setOnGetRtp(OnGetRtp cb); - string getRid(uint32_t ssrc) const; - void setRid(uint32_t ssrc, const string &rid); - RtpExt changeRtpExtId(const RtpHeader *header, bool is_recv, string *rid_ptr = nullptr, RtpExtType type = RtpExtType::padding); + std::string getRid(uint32_t ssrc) const; + void setRid(uint32_t ssrc, const std::string &rid); + RtpExt changeRtpExtId(const mediakit::RtpHeader *header, bool is_recv, std::string *rid_ptr = nullptr, RtpExtType type = RtpExtType::padding); private: - void onGetRtp(uint8_t pt, uint32_t ssrc, const string &rid); + void onGetRtp(uint8_t pt, uint32_t ssrc, const std::string &rid); private: OnGetRtp _cb; //发送rtp时需要修改rtp ext id - map _rtp_ext_type_to_id; + std::map _rtp_ext_type_to_id; //接收rtp时需要修改rtp ext id - unordered_map _rtp_ext_id_to_type; + std::unordered_map _rtp_ext_id_to_type; //ssrc --> rid - unordered_map _ssrc_to_rid; + std::unordered_map _ssrc_to_rid; }; #endif //ZLMEDIAKIT_RTPEXT_H diff --git a/webrtc/Sdp.cpp b/webrtc/Sdp.cpp index 82f28acf..731d79e8 100644 --- a/webrtc/Sdp.cpp +++ b/webrtc/Sdp.cpp @@ -11,6 +11,9 @@ #include "Sdp.h" #include "Rtsp/Rtsp.h" #include + +using namespace std; +using namespace toolkit; using namespace mediakit; namespace RTC { diff --git a/webrtc/Sdp.h b/webrtc/Sdp.h index d75f58e0..f891aee2 100644 --- a/webrtc/Sdp.h +++ b/webrtc/Sdp.h @@ -17,8 +17,6 @@ #include "assert.h" #include "Extension/Frame.h" #include "Common/Parser.h" -using namespace std; -using namespace mediakit; //https://datatracker.ietf.org/doc/rfc4566/?include_text=1 //https://blog.csdn.net/aggresss/article/details/109850434 @@ -81,19 +79,19 @@ enum class SdpType { answer }; -DtlsRole getDtlsRole(const string &str); +DtlsRole getDtlsRole(const std::string &str); const char* getDtlsRoleString(DtlsRole role); -RtpDirection getRtpDirection(const string &str); +RtpDirection getRtpDirection(const std::string &str); const char* getRtpDirectionString(RtpDirection val); class SdpItem { public: using Ptr = std::shared_ptr; virtual ~SdpItem() = default; - virtual void parse(const string &str) { + virtual void parse(const std::string &str) { value = str; } - virtual string toString() const { + virtual std::string toString() const { return value; } virtual const char* getKey() const = 0; @@ -103,23 +101,23 @@ public: } protected: - mutable string value; + mutable std::string value; }; template class SdpString : public SdpItem{ public: SdpString() = default; - SdpString(string val) {value = std::move(val);} + SdpString(std::string val) {value = std::move(val);} // *=* - const char* getKey() const override { static string key(1, KEY); return key.data();} + const char* getKey() const override { static std::string key(1, KEY); return key.data();} }; class SdpCommon : public SdpItem { public: - string key; - SdpCommon(string key) { this->key = std::move(key); } - SdpCommon(string key, string val) { + std::string key; + SdpCommon(std::string key) { this->key = std::move(key); } + SdpCommon(std::string key, std::string val) { this->key = std::move(key); this->value = std::move(val); } @@ -133,8 +131,8 @@ public: // t= uint64_t start {0}; uint64_t stop {0}; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "t";} }; @@ -143,14 +141,14 @@ public: // 5.2. Origin ("o=") // o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5 // o= - string username {"-"}; - string session_id; - string session_version; - string nettype {"IN"}; - string addrtype {"IP4"}; - string address {"0.0.0.0"}; - void parse(const string &str) override; - string toString() const override; + std::string username {"-"}; + std::string session_id; + std::string session_version; + std::string nettype {"IN"}; + std::string addrtype {"IP4"}; + std::string address {"0.0.0.0"}; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "o";} bool empty() const { return username.empty() || session_id.empty() || session_version.empty() @@ -163,11 +161,11 @@ public: // 5.7. Connection Data ("c=") // c=IN IP4 224.2.17.12/127 // c= - string nettype {"IN"}; - string addrtype {"IP4"}; - string address {"0.0.0.0"}; - void parse(const string &str) override; - string toString() const override; + std::string nettype {"IN"}; + std::string addrtype {"IP4"}; + std::string address {"0.0.0.0"}; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "c";} bool empty() const {return address.empty();} }; @@ -178,11 +176,11 @@ public: //b=: //AS、CT - string bwtype {"AS"}; + std::string bwtype {"AS"}; uint32_t bandwidth {0}; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "b";} bool empty() const {return bandwidth == 0;} }; @@ -191,17 +189,17 @@ class SdpMedia : public SdpItem { public: // 5.14. Media Descriptions ("m=") // m= ... - TrackType type; + mediakit::TrackType type; uint16_t port; //RTP/AVP:应用场景为视频/音频的 RTP 协议。参考 RFC 3551 //RTP/SAVP:应用场景为视频/音频的 SRTP 协议。参考 RFC 3711 //RTP/AVPF: 应用场景为视频/音频的 RTP 协议,支持 RTCP-based Feedback。参考 RFC 4585 //RTP/SAVPF: 应用场景为视频/音频的 SRTP 协议,支持 RTCP-based Feedback。参考 RFC 5124 - string proto; - vector fmts; + std::string proto; + std::vector fmts; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "m";} }; @@ -212,8 +210,8 @@ public: //a= //a=: SdpItem::Ptr detail; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "a";} }; @@ -223,10 +221,10 @@ public: // BUNDLE group is included at the session-level. //a=group:LS session level attribute MUST be included wth the 'mid' // identifiers that are part of the same lip sync group. - string type {"BUNDLE"}; - vector mids; - void parse(const string &str) override ; - string toString() const override ; + std::string type {"BUNDLE"}; + std::vector mids; + void parse(const std::string &str) override ; + std::string toString() const override ; const char* getKey() const override { return "group";} }; @@ -252,10 +250,10 @@ public: // "Semantics for the "ssrc-group" SDP Attribute" and "Semantics for the // "group" SDP Attribute". //a=msid-semantic: WMS 616cfbb1-33a3-4d8c-8275-a199d6005549 - string msid{"WMS"}; - string token; - void parse(const string &str) override; - string toString() const override; + std::string msid{"WMS"}; + std::string token; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "msid-semantic";} bool empty() const { return msid.empty(); @@ -266,11 +264,11 @@ class SdpAttrRtcp : public SdpItem { public: // a=rtcp:9 IN IP4 0.0.0.0 uint16_t port{0}; - string nettype {"IN"}; - string addrtype {"IP4"}; - string address {"0.0.0.0"}; - void parse(const string &str) override;; - string toString() const override; + std::string nettype {"IN"}; + std::string addrtype {"IP4"}; + std::string address {"0.0.0.0"}; + void parse(const std::string &str) override;; + std::string toString() const override; const char* getKey() const override { return "rtcp";} bool empty() const { return address.empty() || !port; @@ -280,7 +278,7 @@ public: class SdpAttrIceUfrag : public SdpItem { public: SdpAttrIceUfrag() = default; - SdpAttrIceUfrag(string str) {value = std::move(str);} + SdpAttrIceUfrag(std::string str) {value = std::move(str);} //a=ice-ufrag:sXJ3 const char* getKey() const override { return "ice-ufrag";} }; @@ -288,7 +286,7 @@ public: class SdpAttrIcePwd : public SdpItem { public: SdpAttrIcePwd() = default; - SdpAttrIcePwd(string str) {value = std::move(str);} + SdpAttrIcePwd(std::string str) {value = std::move(str);} //a=ice-pwd:yEclOTrLg1gEubBFefOqtmyV const char* getKey() const override { return "ice-pwd";} }; @@ -298,18 +296,18 @@ public: //a=ice-options:trickle bool trickle{false}; bool renomination{false}; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "ice-options";} }; class SdpAttrFingerprint : public SdpItem { public: //a=fingerprint:sha-256 22:14:B5:AF:66:12:C7:C7:8D:EF:4B:DE:40:25:ED:5D:8F:17:54:DD:88:33:C0:13:2E:FD:1A:FA:7E:7A:1B:79 - string algorithm; - string hash; - void parse(const string &str) override; - string toString() const override; + std::string algorithm; + std::string hash; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "fingerprint";} bool empty() const { return algorithm.empty() || hash.empty(); } }; @@ -320,15 +318,15 @@ public: SdpAttrSetup() = default; SdpAttrSetup(DtlsRole r) { role = r; } DtlsRole role{DtlsRole::actpass}; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "setup";} }; class SdpAttrMid : public SdpItem { public: SdpAttrMid() = default; - SdpAttrMid(string val) { value = std::move(val); } + SdpAttrMid(std::string val) { value = std::move(val); } //a=mid:audio const char* getKey() const override { return "mid";} }; @@ -339,9 +337,9 @@ public: //a=extmap:1[/sendonly] urn:ietf:params:rtp-hdrext:ssrc-audio-level uint8_t id; RtpDirection direction{RtpDirection::invalid}; - string ext; - void parse(const string &str) override; - string toString() const override; + std::string ext; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "extmap";} }; @@ -349,11 +347,11 @@ class SdpAttrRtpMap : public SdpItem { public: //a=rtpmap:111 opus/48000/2 uint8_t pt; - string codec; + std::string codec; uint32_t sample_rate; uint32_t channel {0}; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "rtpmap";} }; @@ -366,9 +364,9 @@ public: //a=rtcp-fb:120 goog-remb 支持 REMB (Receiver Estimated Maximum Bitrate) 。 //a=rtcp-fb:120 transport-cc 支持 TCC (Transport Congest Control) 。 uint8_t pt; - string rtcp_type; - void parse(const string &str) override; - string toString() const override; + std::string rtcp_type; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "rtcp-fb";} }; @@ -376,9 +374,9 @@ class SdpAttrFmtp : public SdpItem { public: //fmtp:96 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f uint8_t pt; - map fmtp; - void parse(const string &str) override; - string toString() const override; + std::map fmtp; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "fmtp";} }; @@ -399,10 +397,10 @@ public: //a=ssrc:3245185839 cname:Cx4i/VTR51etgjT7 uint32_t ssrc; - string attribute; - string attribute_value; - void parse(const string &str) override; - string toString() const override; + std::string attribute; + std::string attribute_value; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "ssrc";} }; @@ -413,13 +411,13 @@ public: // FID (Flow Identification) 最初用在 FEC 的关联中,WebRTC 中通常用于关联一组常规 RTP stream 和 重传 RTP stream 。 //a=ssrc-group:SIM 360918977 360918978 360918980 // 在 Chrome 独有的 SDP munging 风格的 simulcast 中使用,将三组编码质量由低到高的 MediaStreamTrack 关联在一起。 - string type{"FID"}; - vector ssrcs; + std::string type{"FID"}; + std::vector ssrcs; bool isFID() const { return type == "FID"; } bool isSIM() const { return type == "SIM"; } - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "ssrc-group";} }; @@ -429,10 +427,10 @@ public: //a=sctpmap:5000 webrtc-datachannel 1024 //a=sctpmap: sctpmap-number media-subtypes [streams] uint16_t port; - string subtypes; + std::string subtypes; uint32_t streams; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "sctpmap";} }; @@ -443,18 +441,18 @@ public: //15.1. "candidate" Attribute //a=candidate:4 1 udp 2 192.168.1.7 58107 typ host //a=candidate:
typ - string foundation; + std::string foundation; //传输媒体的类型,1代表RTP;2代表 RTCP。 uint32_t component; - string transport {"udp"}; + std::string transport {"udp"}; uint32_t priority; - string address; + std::string address; uint16_t port; - string type; - vector > arr; + std::string type; + std::vector > arr; - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "candidate";} }; @@ -473,56 +471,56 @@ public: //https://www.meetecho.com/blog/simulcast-janus-ssrc/ //https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-14 const char* getKey() const override { return "simulcast";} - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; bool empty() const { return rids.empty(); } - string direction; - vector rids; + std::string direction; + std::vector rids; }; class SdpAttrRid : public SdpItem{ public: - void parse(const string &str) override; - string toString() const override; + void parse(const std::string &str) override; + std::string toString() const override; const char* getKey() const override { return "rid";} - string direction; - string rid; + std::string direction; + std::string rid; }; class RtcSdpBase { public: - vector items; + std::vector items; public: virtual ~RtcSdpBase() = default; - virtual string toString() const; + virtual std::string toString() const; int getVersion() const; SdpOrigin getOrigin() const; - string getSessionName() const; - string getSessionInfo() const; + std::string getSessionName() const; + std::string getSessionInfo() const; SdpTime getSessionTime() const; SdpConnection getConnection() const; SdpBandwidth getBandwidth() const; - string getUri() const; - string getEmail() const; - string getPhone() const; - string getTimeZone() const; - string getEncryptKey() const; - string getRepeatTimes() const; + std::string getUri() const; + std::string getEmail() const; + std::string getPhone() const; + std::string getTimeZone() const; + std::string getEncryptKey() const; + std::string getRepeatTimes() const; RtpDirection getDirection() const; template cls getItemClass(char key, const char *attr_key = nullptr) const{ - auto item = dynamic_pointer_cast(getItem(key, attr_key)); + auto item = std::dynamic_pointer_cast(getItem(key, attr_key)); if (!item) { return cls(); } return *item; } - string getStringItem(char key, const char *attr_key = nullptr) const{ + std::string getStringItem(char key, const char *attr_key = nullptr) const{ auto item = getItem(key, attr_key); if (!item) { return ""; @@ -533,20 +531,20 @@ public: SdpItem::Ptr getItem(char key, const char *attr_key = nullptr) const; template - vector getAllItem(char key_c, const char *attr_key = nullptr) const { - vector ret; + std::vector getAllItem(char key_c, const char *attr_key = nullptr) const { + std::vector ret; for (auto item : items) { - string key(1, key_c); + std::string key(1, key_c); if (strcasecmp(item->getKey(), key.data()) == 0) { if (!attr_key) { - auto c = dynamic_pointer_cast(item); + auto c = std::dynamic_pointer_cast(item); if (c) { ret.emplace_back(*c); } } else { - auto attr = dynamic_pointer_cast(item); + auto attr = std::dynamic_pointer_cast(item); if (attr && !strcasecmp(attr->detail->getKey(), attr_key)) { - auto c = dynamic_pointer_cast(attr->detail); + auto c = std::dynamic_pointer_cast(attr->detail); if (c) { ret.emplace_back(*c); } @@ -562,9 +560,9 @@ class RtcSessionSdp : public RtcSdpBase{ public: using Ptr = std::shared_ptr; - vector medias; - void parse(const string &str); - string toString() const override; + std::vector medias; + void parse(const std::string &str); + std::string toString() const override; }; ////////////////////////////////////////////////////////////////// @@ -574,10 +572,10 @@ class RtcSSRC{ public: uint32_t ssrc {0}; uint32_t rtx_ssrc {0}; - string cname; - string msid; - string mslabel; - string label; + std::string cname; + std::string msid; + std::string mslabel; + std::string label; bool empty() const {return ssrc == 0 && cname.empty();} }; @@ -585,36 +583,36 @@ public: //rtc传输编码方案 class RtcCodecPlan{ public: - using Ptr = shared_ptr; + using Ptr = std::shared_ptr; uint8_t pt; - string codec; + std::string codec; uint32_t sample_rate; //音频时有效 uint32_t channel = 0; //rtcp反馈 - set rtcp_fb; - map fmtp; + std::set rtcp_fb; + std::map fmtp; - string getFmtp(const char *key) const; + std::string getFmtp(const char *key) const; }; //rtc 媒体描述 class RtcMedia{ public: - TrackType type{TrackType::TrackInvalid}; - string mid; + mediakit::TrackType type{mediakit::TrackType::TrackInvalid}; + std::string mid; uint16_t port{0}; SdpConnection addr; - string proto; + std::string proto; RtpDirection direction{RtpDirection::invalid}; - vector plan; + std::vector plan; //////// rtp //////// - vector rtp_rtx_ssrc; + std::vector rtp_rtx_ssrc; //////// simulcast //////// - vector rtp_ssrc_sim; - vector rtp_rids; + std::vector rtp_ssrc_sim; + std::vector rtp_rids; //////// rtcp //////// bool rtcp_mux{false}; @@ -625,8 +623,8 @@ public: bool ice_trickle{false}; bool ice_lite{false}; bool ice_renomination{false}; - string ice_ufrag; - string ice_pwd; + std::string ice_ufrag; + std::string ice_pwd; std::vector candidate; //////// dtls //////// @@ -634,7 +632,7 @@ public: SdpAttrFingerprint fingerprint; //////// extmap //////// - vector extmap; + std::vector extmap; //////// sctp //////////// SdpAttrSctpMap sctpmap; @@ -655,21 +653,21 @@ public: uint32_t version; SdpOrigin origin; - string session_name; - string session_info; + std::string session_name; + std::string session_info; SdpTime time; SdpConnection connection; SdpBandwidth bandwidth; SdpAttrMsidSemantic msid_semantic; - vector media; + std::vector media; SdpAttrGroup group; - void loadFrom(const string &sdp); + void loadFrom(const std::string &sdp); void checkValid() const; - string toString() const; - string toRtspSdp() const; - const RtcMedia *getMedia(TrackType type) const; - bool supportRtcpFb(const string &name, TrackType type = TrackType::TrackVideo) const; + std::string toString() const; + std::string toRtspSdp() const; + const RtcMedia *getMedia(mediakit::TrackType type) const; + bool supportRtcpFb(const std::string &name, mediakit::TrackType type = mediakit::TrackType::TrackVideo) const; bool supportSimulcast() const; private: @@ -690,18 +688,18 @@ public: bool ice_lite; bool ice_trickle; bool ice_renomination; - string ice_ufrag; - string ice_pwd; + std::string ice_ufrag; + std::string ice_pwd; RtpDirection direction{RtpDirection::invalid}; SdpAttrFingerprint fingerprint; - set rtcp_fb; - map extmap; - vector preferred_codec; - vector candidate; + std::set rtcp_fb; + std::map extmap; + std::vector preferred_codec; + std::vector candidate; - void setDefaultSetting(TrackType type); + void setDefaultSetting(mediakit::TrackType type); void enableTWCC(bool enable = true); void enableREMB(bool enable = true); }; @@ -710,20 +708,20 @@ public: RtcTrackConfigure audio; RtcTrackConfigure application; - void setDefaultSetting(string ice_ufrag, string ice_pwd, RtpDirection direction, const SdpAttrFingerprint &fingerprint); - void addCandidate(const SdpAttrCandidate &candidate, TrackType type = TrackInvalid); + void setDefaultSetting(std::string ice_ufrag, std::string ice_pwd, RtpDirection direction, const SdpAttrFingerprint &fingerprint); + void addCandidate(const SdpAttrCandidate &candidate, mediakit::TrackType type = mediakit::TrackInvalid); - shared_ptr createAnswer(const RtcSession &offer); + std::shared_ptr createAnswer(const RtcSession &offer); - void setPlayRtspInfo(const string &sdp); + void setPlayRtspInfo(const std::string &sdp); - void enableTWCC(bool enable = true, TrackType type = TrackInvalid); - void enableREMB(bool enable = true, TrackType type = TrackInvalid); + void enableTWCC(bool enable = true, mediakit::TrackType type = mediakit::TrackInvalid); + void enableREMB(bool enable = true, mediakit::TrackType type = mediakit::TrackInvalid); private: - void matchMedia(const shared_ptr &ret, TrackType type, const vector &medias, const RtcTrackConfigure &configure); - bool onCheckCodecProfile(const RtcCodecPlan &plan, CodecId codec); - void onSelectPlan(RtcCodecPlan &plan, CodecId codec); + void matchMedia(const std::shared_ptr &ret, mediakit::TrackType type, const std::vector &medias, const RtcTrackConfigure &configure); + bool onCheckCodecProfile(const RtcCodecPlan &plan, mediakit::CodecId codec); + void onSelectPlan(RtcCodecPlan &plan, mediakit::CodecId codec); private: RtcCodecPlan::Ptr _rtsp_video_plan; @@ -732,8 +730,8 @@ private: class SdpConst { public: - static string const kTWCCRtcpFb; - static string const kRembRtcpFb; + static std::string const kTWCCRtcpFb; + static std::string const kRembRtcpFb; private: SdpConst() = delete; diff --git a/webrtc/SrtpSession.cpp b/webrtc/SrtpSession.cpp index 4b81efad..93edfb7c 100644 --- a/webrtc/SrtpSession.cpp +++ b/webrtc/SrtpSession.cpp @@ -24,6 +24,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include "logger.h" #include "Util/util.h" #include "Util/logger.h" + using namespace toolkit; namespace RTC diff --git a/webrtc/TwccContext.h b/webrtc/TwccContext.h index 9455508d..26b10fcd 100644 --- a/webrtc/TwccContext.h +++ b/webrtc/TwccContext.h @@ -15,11 +15,10 @@ #include #include #include "Util/TimeTicker.h" -using namespace toolkit; class TwccContext { public: - using onSendTwccCB = function; + using onSendTwccCB = std::function; //每个twcc rtcp包最多表明的rtp ext seq增量 static constexpr size_t kMaxSeqSize = 20; //每个twcc rtcp包发送的最大时间间隔,单位毫秒 diff --git a/webrtc/WebRtcEchoTest.h b/webrtc/WebRtcEchoTest.h index 75feda5e..cdc5d92c 100644 --- a/webrtc/WebRtcEchoTest.h +++ b/webrtc/WebRtcEchoTest.h @@ -26,7 +26,7 @@ protected: void onRtp(const char *buf, size_t len, uint64_t stamp_ms) override; void onRtcp(const char *buf, size_t len) override; - void onRecvRtp(MediaTrack &track, const string &rid, RtpPacket::Ptr rtp) override {}; + void onRecvRtp(MediaTrack &track, const std::string &rid, mediakit::RtpPacket::Ptr rtp) override {}; void onBeforeEncryptRtp(const char *buf, int &len, void *ctx) override {}; void onBeforeEncryptRtcp(const char *buf, int &len, void *ctx) override {}; diff --git a/webrtc/WebRtcPlayer.cpp b/webrtc/WebRtcPlayer.cpp index 4447ab8e..69a595d4 100644 --- a/webrtc/WebRtcPlayer.cpp +++ b/webrtc/WebRtcPlayer.cpp @@ -10,6 +10,9 @@ #include "WebRtcPlayer.h" +using namespace std; +using namespace mediakit; + WebRtcPlayer::Ptr WebRtcPlayer::create(const EventPoller::Ptr &poller, const RtspMediaSource::Ptr &src, const MediaInfo &info) { diff --git a/webrtc/WebRtcPlayer.h b/webrtc/WebRtcPlayer.h index beb25ef2..e2487c67 100644 --- a/webrtc/WebRtcPlayer.h +++ b/webrtc/WebRtcPlayer.h @@ -17,25 +17,25 @@ class WebRtcPlayer : public WebRtcTransportImp { public: using Ptr = std::shared_ptr; ~WebRtcPlayer() override = default; - static Ptr create(const EventPoller::Ptr &poller, const RtspMediaSource::Ptr &src, const MediaInfo &info); + static Ptr create(const EventPoller::Ptr &poller, const mediakit::RtspMediaSource::Ptr &src, const mediakit::MediaInfo &info); protected: ///////WebRtcTransportImp override/////// void onStartWebRTC() override; void onDestory() override; void onRtcConfigure(RtcConfigure &configure) const override; - void onRecvRtp(MediaTrack &track, const string &rid, RtpPacket::Ptr rtp) override {}; + void onRecvRtp(MediaTrack &track, const std::string &rid, mediakit::RtpPacket::Ptr rtp) override {}; private: - WebRtcPlayer(const EventPoller::Ptr &poller, const RtspMediaSource::Ptr &src, const MediaInfo &info); + WebRtcPlayer(const EventPoller::Ptr &poller, const mediakit::RtspMediaSource::Ptr &src, const mediakit::MediaInfo &info); private: //媒体相关元数据 - MediaInfo _media_info; + mediakit::MediaInfo _media_info; //播放的rtsp源 - RtspMediaSource::Ptr _play_src; + mediakit::RtspMediaSource::Ptr _play_src; //播放rtsp源的reader对象 - RtspMediaSource::RingType::RingReader::Ptr _reader; + mediakit::RtspMediaSource::RingType::RingReader::Ptr _reader; }; diff --git a/webrtc/WebRtcPusher.cpp b/webrtc/WebRtcPusher.cpp index c2f0b9a6..c3604cac 100644 --- a/webrtc/WebRtcPusher.cpp +++ b/webrtc/WebRtcPusher.cpp @@ -10,6 +10,9 @@ #include "WebRtcPusher.h" +using namespace std; +using namespace mediakit; + WebRtcPusher::Ptr WebRtcPusher::create(const EventPoller::Ptr &poller, const RtspMediaSource::Ptr &src, const std::shared_ptr &ownership, diff --git a/webrtc/WebRtcPusher.h b/webrtc/WebRtcPusher.h index d2072cb5..ac61484b 100644 --- a/webrtc/WebRtcPusher.h +++ b/webrtc/WebRtcPusher.h @@ -13,48 +13,48 @@ #include "WebRtcTransport.h" -class WebRtcPusher : public WebRtcTransportImp, public MediaSourceEvent { +class WebRtcPusher : public WebRtcTransportImp, public mediakit::MediaSourceEvent { public: using Ptr = std::shared_ptr; ~WebRtcPusher() override = default; - static Ptr create(const EventPoller::Ptr &poller, const RtspMediaSource::Ptr &src, - const std::shared_ptr &ownership, const MediaInfo &info); + static Ptr create(const EventPoller::Ptr &poller, const mediakit::RtspMediaSource::Ptr &src, + const std::shared_ptr &ownership, const mediakit::MediaInfo &info); protected: ///////WebRtcTransportImp override/////// void onStartWebRTC() override; void onDestory() override; void onRtcConfigure(RtcConfigure &configure) const override; - void onRecvRtp(MediaTrack &track, const string &rid, RtpPacket::Ptr rtp) override; + void onRecvRtp(MediaTrack &track, const std::string &rid, mediakit::RtpPacket::Ptr rtp) override; protected: ///////MediaSourceEvent override/////// // 关闭 - bool close(MediaSource &sender, bool force) override; + bool close(mediakit::MediaSource &sender, bool force) override; // 播放总人数 - int totalReaderCount(MediaSource &sender) override; + int totalReaderCount(mediakit::MediaSource &sender) override; // 获取媒体源类型 - MediaOriginType getOriginType(MediaSource &sender) const override; + mediakit::MediaOriginType getOriginType(mediakit::MediaSource &sender) const override; // 获取媒体源url或者文件路径 - string getOriginUrl(MediaSource &sender) const override; + std::string getOriginUrl(mediakit::MediaSource &sender) const override; // 获取媒体源客户端相关信息 - std::shared_ptr getOriginSock(MediaSource &sender) const override; + std::shared_ptr getOriginSock(mediakit::MediaSource &sender) const override; private: - WebRtcPusher(const EventPoller::Ptr &poller, const RtspMediaSource::Ptr &src, - const std::shared_ptr &ownership, const MediaInfo &info); + WebRtcPusher(const EventPoller::Ptr &poller, const mediakit::RtspMediaSource::Ptr &src, + const std::shared_ptr &ownership, const mediakit::MediaInfo &info); private: bool _simulcast = false; //媒体相关元数据 - MediaInfo _media_info; + mediakit::MediaInfo _media_info; //推流的rtsp源 - RtspMediaSource::Ptr _push_src; + mediakit::RtspMediaSource::Ptr _push_src; //推流所有权 std::shared_ptr _push_src_ownership; //推流的rtsp源,支持simulcast - unordered_map _push_src_sim; - unordered_map > _push_src_sim_ownership; + std::unordered_map _push_src_sim; + std::unordered_map > _push_src_sim_ownership; }; #endif //ZLMEDIAKIT_WEBRTCPUSHER_H diff --git a/webrtc/WebRtcSession.cpp b/webrtc/WebRtcSession.cpp index 6a83ac06..ec645c56 100644 --- a/webrtc/WebRtcSession.cpp +++ b/webrtc/WebRtcSession.cpp @@ -11,6 +11,9 @@ #include "WebRtcSession.h" #include "Util/util.h" +using namespace std; +using namespace mediakit; + static string getUserName(const Buffer::Ptr &buffer) { auto buf = buffer->data(); auto len = buffer->size(); diff --git a/webrtc/WebRtcSession.h b/webrtc/WebRtcSession.h index eb141f25..c3cd0290 100644 --- a/webrtc/WebRtcSession.h +++ b/webrtc/WebRtcSession.h @@ -16,8 +16,6 @@ #include "IceServer.hpp" #include "WebRtcTransport.h" -using namespace toolkit; - class WebRtcSession : public UdpSession { public: WebRtcSession(const Socket::Ptr &sock); diff --git a/webrtc/WebRtcTransport.cpp b/webrtc/WebRtcTransport.cpp index ab8903dc..9bf59b13 100644 --- a/webrtc/WebRtcTransport.cpp +++ b/webrtc/WebRtcTransport.cpp @@ -22,6 +22,9 @@ #define RTP_MSLABEL "zlmediakit-mslabel" #define RTP_MSID RTP_MSLABEL " " RTP_LABEL +using namespace std; +using namespace mediakit; + //RTC配置项目 namespace RTC { #define RTC_FIELD "rtc." @@ -564,7 +567,7 @@ private: NackContext _nack_ctx; RtcpContextForRecv _rtcp_context; EventPoller::Ptr _poller; - DelayTask::Ptr _delay_task; + EventPoller::DelayTask::Ptr _delay_task; function _on_nack; }; diff --git a/webrtc/WebRtcTransport.h b/webrtc/WebRtcTransport.h index 981a9ab6..95783c76 100644 --- a/webrtc/WebRtcTransport.h +++ b/webrtc/WebRtcTransport.h @@ -26,32 +26,29 @@ #include "Network/Session.h" #include "TwccContext.h" -using namespace toolkit; -using namespace mediakit; - //RTC配置项目 namespace RTC { -extern const string kPort; -extern const string kTimeOutSec; +extern const std::string kPort; +extern const std::string kTimeOutSec; }//namespace RTC class WebRtcInterface { public: WebRtcInterface() = default; virtual ~WebRtcInterface() = default; - virtual string getAnswerSdp(const string &offer) = 0; - virtual const string &getIdentifier() const = 0; + virtual std::string getAnswerSdp(const std::string &offer) = 0; + virtual const std::string &getIdentifier() const = 0; }; class WebRtcException : public WebRtcInterface { public: WebRtcException(const SockException &ex) : _ex(ex) {}; ~WebRtcException() override = default; - string getAnswerSdp(const string &offer) override { + std::string getAnswerSdp(const std::string &offer) override { throw _ex; } - const string &getIdentifier() const override { - static string s_null; + const std::string &getIdentifier() const override { + static std::string s_null; return s_null; } @@ -80,12 +77,12 @@ public: * @param offer offer sdp * @return answer sdp */ - string getAnswerSdp(const string &offer) override; + std::string getAnswerSdp(const std::string &offer) override; /** * 获取对象唯一id */ - const string& getIdentifier() const override; + const std::string& getIdentifier() const override; /** * socket收到udp数据 @@ -157,7 +154,7 @@ protected: RtcSession::Ptr _answer_sdp; private: - string _identifier; + std::string _identifier; EventPoller::Ptr _poller; std::shared_ptr _ice_server; std::shared_ptr _dtls_transport; @@ -183,10 +180,10 @@ public: //for send rtp NackList nack_list; - RtcpContext::Ptr rtcp_context_send; + mediakit::RtcpContext::Ptr rtcp_context_send; //for recv rtp - unordered_map > rtp_channel; + std::unordered_map > rtp_channel; std::shared_ptr getRtpChannel(uint32_t ssrc) const; }; @@ -194,13 +191,13 @@ struct WrappedMediaTrack { MediaTrack::Ptr track; explicit WrappedMediaTrack(MediaTrack::Ptr ptr): track(ptr) {} virtual ~WrappedMediaTrack() {} - virtual void inputRtp(const char *buf, size_t len, uint64_t stamp_ms, RtpHeader *rtp) = 0; + virtual void inputRtp(const char *buf, size_t len, uint64_t stamp_ms, mediakit::RtpHeader *rtp) = 0; }; struct WrappedRtxTrack: public WrappedMediaTrack { explicit WrappedRtxTrack(MediaTrack::Ptr ptr) : WrappedMediaTrack(std::move(ptr)) {} - void inputRtp(const char *buf, size_t len, uint64_t stamp_ms, RtpHeader *rtp) override; + void inputRtp(const char *buf, size_t len, uint64_t stamp_ms, mediakit::RtpHeader *rtp) override; }; class WebRtcTransportImp; @@ -212,7 +209,7 @@ struct WrappedRtpTrack : public WrappedMediaTrack { , _transport(t) {} TwccContext& _twcc_ctx; WebRtcTransportImp& _transport; - void inputRtp(const char *buf, size_t len, uint64_t stamp_ms, RtpHeader *rtp) override; + void inputRtp(const char *buf, size_t len, uint64_t stamp_ms, mediakit::RtpHeader *rtp) override; }; class WebRtcTransportImp : public WebRtcTransport { @@ -226,9 +223,9 @@ public: uint64_t getDuration() const; bool canSendRtp() const; bool canRecvRtp() const; - void onSendRtp(const RtpPacket::Ptr &rtp, bool flush, bool rtx = false); + void onSendRtp(const mediakit::RtpPacket::Ptr &rtp, bool flush, bool rtx = false); - void createRtpChannel(const string &rid, uint32_t ssrc, MediaTrack &track); + void createRtpChannel(const std::string &rid, uint32_t ssrc, MediaTrack &track); protected: WebRtcTransportImp(const EventPoller::Ptr &poller); @@ -244,14 +241,14 @@ protected: void onCreate() override; void onDestory() override; void onShutdown(const SockException &ex) override; - virtual void onRecvRtp(MediaTrack &track, const string &rid, RtpPacket::Ptr rtp) = 0; + virtual void onRecvRtp(MediaTrack &track, const std::string &rid, mediakit::RtpPacket::Ptr rtp) = 0; void updateTicker(); private: SdpAttrCandidate::Ptr getIceCandidate() const; - void onSortedRtp(MediaTrack &track, const string &rid, RtpPacket::Ptr rtp); - void onSendNack(MediaTrack &track, const FCI_NACK &nack, uint32_t ssrc); - void onSendTwcc(uint32_t ssrc, const string &twcc_fci); + void onSortedRtp(MediaTrack &track, const std::string &rid, mediakit::RtpPacket::Ptr rtp); + void onSendNack(MediaTrack &track, const mediakit::FCI_NACK &nack, uint32_t ssrc); + void onSendTwcc(uint32_t ssrc, const std::string &twcc_fci); void registerSelf(); void unregisterSelf(); @@ -273,31 +270,31 @@ private: //当前选中的udp链接 Session::Ptr _selected_session; //链接迁移前后使用过的udp链接 - unordered_map > _history_sessions; + std::unordered_map > _history_sessions; //twcc rtcp发送上下文对象 TwccContext _twcc_ctx; //根据发送rtp的track类型获取相关信息 MediaTrack::Ptr _type_to_track[2]; //根据rtcp的ssrc获取相关信息,收发rtp和rtx的ssrc都会记录 - unordered_map _ssrc_to_track; + std::unordered_map _ssrc_to_track; //根据接收rtp的pt获取相关信息 - unordered_map> _pt_to_track; + std::unordered_map> _pt_to_track; }; class WebRtcTransportManager { public: friend class WebRtcTransportImp; static WebRtcTransportManager &Instance(); - WebRtcTransportImp::Ptr getItem(const string &key); + WebRtcTransportImp::Ptr getItem(const std::string &key); private: WebRtcTransportManager() = default; - void addItem(const string &key, const WebRtcTransportImp::Ptr &ptr); - void removeItem(const string &key); + void addItem(const std::string &key, const WebRtcTransportImp::Ptr &ptr); + void removeItem(const std::string &key); private: - mutable mutex _mtx; - unordered_map > _map; + mutable std::mutex _mtx; + std::unordered_map > _map; }; class WebRtcArgs { @@ -305,23 +302,23 @@ public: WebRtcArgs() = default; virtual ~WebRtcArgs() = default; - virtual variant operator[](const string &key) const = 0; + virtual variant operator[](const std::string &key) const = 0; }; class WebRtcPluginManager { public: - using onCreateRtc = function; - using Plugin = function; + using onCreateRtc = std::function; + using Plugin = std::function; static WebRtcPluginManager &Instance(); - void registerPlugin(const string &type, Plugin cb); - void getAnswerSdp(Session &sender, const string &type, const string &offer, const WebRtcArgs &args, const onCreateRtc &cb); + void registerPlugin(const std::string &type, Plugin cb); + void getAnswerSdp(Session &sender, const std::string &type, const std::string &offer, const WebRtcArgs &args, const onCreateRtc &cb); private: WebRtcPluginManager() = default; private: - mutable mutex _mtx_creator; - unordered_map _map_creator; + mutable std::mutex _mtx_creator; + std::unordered_map _map_creator; }; \ No newline at end of file diff --git a/webrtc/logger.h b/webrtc/logger.h index 9e2e4481..ef056b61 100644 --- a/webrtc/logger.h +++ b/webrtc/logger.h @@ -1,6 +1,5 @@ #pragma once #include "Util/logger.h" -using namespace toolkit; #define MS_TRACE() #define MS_ERROR PrintE