Files
ZLMediaKit/src/Player/PlayerProxy.cpp

521 lines
20 KiB
C++
Raw Normal View History

2017-10-09 22:11:01 +08:00
/*
2023-12-09 16:23:51 +08:00
* Copyright (c) 2016-present The ZLMediaKit project authors. All Rights Reserved.
2017-09-27 16:20:30 +08:00
*
2023-12-09 16:23:51 +08:00
* This file is part of ZLMediaKit(https://github.com/ZLMediaKit/ZLMediaKit).
2017-09-27 16:20:30 +08:00
*
2023-12-09 16:23:51 +08:00
* Use of this source code is governed by MIT-like license that can be found in the
2020-04-04 20:30:09 +08:00
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
2017-04-01 16:35:56 +08:00
*/
#include <cstring>
2017-04-01 16:35:56 +08:00
#include "PlayerProxy.h"
#include "Common/config.h"
#include "Rtmp/RtmpMediaSource.h"
#include "Rtmp/RtmpPlayer.h"
#include "Rtsp/RtspMediaSource.h"
#include "Rtsp/RtspPlayer.h"
2026-08-27 23:17:37 +08:00
#if defined(ENABLE_WEBRTC)
#include "webrtc/WebRtcProxyPlayer.h"
2026-08-27 23:17:37 +08:00
#endif
#include "Util/MD5.h"
#include "Util/logger.h"
#include "Util/mini.h"
2017-04-01 16:35:56 +08:00
2018-10-24 17:17:55 +08:00
using namespace toolkit;
using namespace std;
2017-04-01 16:35:56 +08:00
2018-10-24 17:17:55 +08:00
namespace mediakit {
2017-04-01 16:35:56 +08:00
namespace {
bool isBufferContentEqual(const Buffer::Ptr &lhs, const Buffer::Ptr &rhs) {
if (!lhs || !rhs) {
return !lhs && !rhs;
}
return lhs->size() == rhs->size()
&& (lhs->size() == 0 || memcmp(lhs->data(), rhs->data(), lhs->size()) == 0);
}
bool isConfigFrameContentEqual(const Frame::Ptr &lhs, const Frame::Ptr &rhs) {
if (!lhs || !rhs || lhs->prefixSize() > lhs->size() || rhs->prefixSize() > rhs->size()) {
return false;
}
auto lhs_size = lhs->size() - lhs->prefixSize();
auto rhs_size = rhs->size() - rhs->prefixSize();
return lhs_size == rhs_size
&& (lhs_size == 0
|| memcmp(lhs->data() + lhs->prefixSize(), rhs->data() + rhs->prefixSize(), lhs_size) == 0);
}
bool isTrackConfigCompatible(const Track::Ptr &track, const Track::Ptr &last_track) {
try {
auto video_track = dynamic_pointer_cast<VideoTrack>(track);
auto last_video_track = dynamic_pointer_cast<VideoTrack>(last_track);
if (video_track && last_video_track) {
// H264/H265的配置帧保留原始SPS/PPS/VPS,优先比较它们,避免extra data转换失败造成误判。
// H264/H265 config frames preserve the original SPS/PPS/VPS; compare them first to avoid extra-data conversion failures.
auto frames = video_track->getConfigFrames();
auto last_frames = last_video_track->getConfigFrames();
if (!frames.empty() || !last_frames.empty()) {
if (frames.size() != last_frames.size()) {
return false;
}
for (size_t i = 0; i < frames.size(); ++i) {
if (!isConfigFrameContentEqual(frames[i], last_frames[i])) {
return false;
}
}
return true;
}
}
return isBufferContentEqual(track->getExtraData(), last_track->getExtraData());
} catch (const exception &ex) {
WarnL << "比较重连轨道初始化配置失败: " << ex.what();
return false;
} catch (...) {
WarnL << "比较重连轨道初始化配置失败: unknown exception";
return false;
}
}
} // namespace
PlayerProxy::PlayerProxy(
const MediaTuple &tuple, const ProtocolOption &option, int retry_count,
const EventPoller::Ptr &poller, int reconnect_delay_min, int reconnect_delay_max, int reconnect_delay_step)
: MediaPlayer(poller), _tuple(tuple), _option(option) {
2020-08-01 10:22:12 +08:00
_retry_count = retry_count;
2023-05-13 00:14:35 +08:00
setOnClose(nullptr);
setOnConnect(nullptr);
setOnDisconnect(nullptr);
_reconnect_delay_min = reconnect_delay_min > 0 ? reconnect_delay_min : 2;
_reconnect_delay_max = reconnect_delay_max > 0 ? reconnect_delay_max : 60;
_reconnect_delay_step = reconnect_delay_step > 0 ? reconnect_delay_step : 3;
_live_secs = 0;
_live_status = 1;
_repull_count = 0;
(*this)[Client::kWaitTrackReady] = false;
2017-04-01 16:35:56 +08:00
}
2019-05-20 18:08:55 +08:00
void PlayerProxy::update(const std::string &url, const toolkit::mINI &args) {
CHECK(getPoller()->isCurrentThread());
_pull_url = url;
this->mINI::clear();
(*this)[Client::kWaitTrackReady] = false;
for (auto &pr : args) {
(*this)[pr.first] = pr.second;
}
}
2023-05-13 00:14:35 +08:00
void PlayerProxy::setPlayCallbackOnce(function<void(const SockException &ex)> cb) {
_on_play = std::move(cb);
2019-05-20 18:08:55 +08:00
}
2019-05-27 14:14:42 +08:00
2023-05-13 00:14:35 +08:00
void PlayerProxy::setOnClose(function<void(const SockException &ex)> cb) {
_on_close = cb ? std::move(cb) : [](const SockException &) {};
2019-05-27 14:14:42 +08:00
}
void PlayerProxy::setOnDisconnect(std::function<void()> cb) {
_on_disconnect = cb ? std::move(cb) : []() {};
}
void PlayerProxy::setOnConnect(std::function<void(const TranslationInfo &)> cb) {
_on_connect = cb ? std::move(cb) : [](const TranslationInfo &) {};
}
void PlayerProxy::setTranslationInfo() {
_transtalion_info.byte_speed = _media_src ? _media_src->getBytesSpeed() : -1;
_transtalion_info.start_time_stamp = _media_src ? _media_src->getCreateStamp() : 0;
_transtalion_info.stream_info.clear();
auto tracks = _muxer->getTracks();
for (auto &track : tracks) {
track->update();
_transtalion_info.stream_info.emplace_back();
auto &back = _transtalion_info.stream_info.back();
back.bitrate = track->getBitRate();
back.codec_type = track->getTrackType();
back.codec_name = track->getCodecName();
switch (back.codec_type) {
case TrackAudio: {
auto audio_track = dynamic_pointer_cast<AudioTrack>(track);
back.audio_sample_rate = audio_track->getAudioSampleRate();
back.audio_channel = audio_track->getAudioChannel();
back.audio_sample_bit = audio_track->getAudioSampleBit();
break;
}
case TrackVideo: {
auto video_track = dynamic_pointer_cast<VideoTrack>(track);
back.video_width = video_track->getVideoWidth();
back.video_height = video_track->getVideoHeight();
back.video_fps = video_track->getVideoFps();
break;
}
default: break;
}
}
}
2023-12-09 22:34:22 +08:00
static int getMaxTrackSize(const std::string &url) {
if (url.find(".m3u8") != std::string::npos || url.find(".ts") != std::string::npos) {
// hls和ts协议才开放多track支持 [AUTO-TRANSLATED:6c5f8f04]
// Only hls and ts protocols support multiple tracks
2023-12-09 22:34:22 +08:00
return 16;
}
return 2;
}
void PlayerProxy::play(const string &url) {
_pull_url = url;
_option.max_track = getMaxTrackSize(_pull_url);
2020-03-20 11:51:24 +08:00
weak_ptr<PlayerProxy> weakSelf = shared_from_this();
std::shared_ptr<int> piFailedCnt(new int(0)); // 连续播放失败次数
setOnPlayResult([weakSelf, piFailedCnt](const SockException &err) {
2020-03-20 11:51:24 +08:00
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
2020-03-20 11:51:24 +08:00
return;
}
if (err) {
NOTICE_EMIT(BroadcastPlayerProxyFailedArgs, Broadcast::kBroadcastPlayerProxyFailed, *strongSelf, err);
strongSelf->_status = std::make_shared<std::string>(std::string("play failed: ") + err.what());
}
if (strongSelf->_on_play) {
2020-08-01 10:22:12 +08:00
strongSelf->_on_play(err);
strongSelf->_on_play = nullptr;
2019-05-20 18:08:55 +08:00
}
if (!err) {
// 取消定时器,避免hls拉流索引文件因为网络波动失败重连成功后出现循环重试的情况 [AUTO-TRANSLATED:91e5f0c8]
// Cancel the timer to avoid the situation where the hls stream index file fails to reconnect due to network fluctuations and then retries in a loop
// after successful reconnection
strongSelf->_timer.reset();
strongSelf->_live_ticker.resetTime();
strongSelf->_live_status = 0;
// 播放成功 [AUTO-TRANSLATED:e43f9fb8]
// Play successfully
*piFailedCnt = 0; // 连续播放失败次数清0
2020-03-20 11:51:24 +08:00
strongSelf->onPlaySuccess();
strongSelf->setTranslationInfo();
strongSelf->_on_connect(strongSelf->_transtalion_info);
InfoL << "play " << strongSelf->_pull_url << " success";
strongSelf->_status = std::make_shared<std::string>("playing");
} else if (*piFailedCnt < strongSelf->_retry_count || strongSelf->_retry_count < 0) {
// 播放失败,延时重试播放 [AUTO-TRANSLATED:d7537c9c]
// Play failed, retry playing with delay
strongSelf->_on_disconnect();
strongSelf->rePlay((*piFailedCnt)++);
} else {
// 达到了最大重试次数,回调关闭 [AUTO-TRANSLATED:610f31f3]
// Reached the maximum number of retries, callback to close
strongSelf->_muxer.reset();
strongSelf->_on_close(err);
2020-03-20 11:51:24 +08:00
}
});
setOnShutdown([weakSelf, piFailedCnt](const SockException &err) {
2020-03-20 11:51:24 +08:00
auto strongSelf = weakSelf.lock();
if (!strongSelf) {
2020-03-20 11:51:24 +08:00
return;
}
if (err) {
NOTICE_EMIT(BroadcastPlayerProxyFailedArgs, Broadcast::kBroadcastPlayerProxyFailed, *strongSelf, err);
}
if (strongSelf->_on_play) {
strongSelf->_on_play(err);
strongSelf->_on_play = nullptr;
}
strongSelf->_status = std::make_shared<std::string>(std::string("play shutdown: ") + err.what());
// 注销直接拉流代理产生的流:#532 [AUTO-TRANSLATED:c6343a3b]
// Unregister the stream generated by the direct stream proxy: #532
strongSelf->setMediaSource(nullptr);
const bool can_retry = *piFailedCnt < strongSelf->_retry_count || strongSelf->_retry_count < 0;
if (strongSelf->_muxer) {
2020-09-06 17:54:52 +08:00
auto tracks = strongSelf->MediaPlayer::getTracks(false);
for (auto &track : tracks) {
2020-08-01 10:22:12 +08:00
track->delDelegate(strongSelf->_muxer.get());
2020-03-20 11:51:24 +08:00
}
GET_CONFIG(bool, reset_when_replay, General::kResetWhenRePlay);
// 临时断线且允许保留时,只解除旧播放器输入,避免重置输出媒体源和观看连接。
// On a retryable disconnect, detach the old player input without resetting output media sources or viewers.
if (reset_when_replay || !can_retry) {
2020-08-01 10:22:12 +08:00
strongSelf->_muxer.reset();
2020-03-20 11:51:24 +08:00
}
}
if (*piFailedCnt == 0) {
// 第一次重拉更新时长 [AUTO-TRANSLATED:3c414b08]
// Update the duration for the first time
strongSelf->_live_secs += strongSelf->_live_ticker.elapsedTime() / 1000;
strongSelf->_live_ticker.resetTime();
TraceL << " live secs " << strongSelf->_live_secs;
}
// 播放异常中断,延时重试播放 [AUTO-TRANSLATED:fee316b2]
// Play interrupted abnormally, retry playing with delay
if (can_retry) {
strongSelf->_repull_count++;
strongSelf->rePlay((*piFailedCnt)++);
} else {
// 达到了最大重试次数,回调关闭 [AUTO-TRANSLATED:610f31f3]
// Reached the maximum number of retries, callback to close
strongSelf->_on_close(err);
2020-03-20 11:51:24 +08:00
}
});
try {
_status = std::make_shared<std::string>("connecting");
MediaPlayer::play(_pull_url );
} catch (std::exception &ex) {
_status = std::make_shared<std::string>(std::string("play failed: ") + ex.what());
ErrorL << ex.what();
2023-05-13 00:14:35 +08:00
onPlayResult(SockException(Err_other, ex.what()));
return;
}
2021-01-17 10:22:51 +08:00
setDirectProxy();
}
void PlayerProxy::setDirectProxy() {
2020-03-20 11:51:24 +08:00
MediaSource::Ptr mediaSource;
2026-08-27 23:17:37 +08:00
if (dynamic_pointer_cast<RtspPlayer>(_delegate)
#if defined(ENABLE_WEBRTC)
|| dynamic_pointer_cast<WebRtcProxyPlayer>(_delegate)
#endif
) {
// rtsp拉流 [AUTO-TRANSLATED:189cf691]
// Rtsp stream
2021-01-17 10:22:51 +08:00
GET_CONFIG(bool, directProxy, Rtsp::kDirectProxy);
if (directProxy && _option.enable_rtsp) {
2023-05-25 16:23:24 +08:00
mediaSource = std::make_shared<RtspMediaSource>(_tuple);
2020-03-20 11:51:24 +08:00
}
2021-01-17 10:22:51 +08:00
} else if (dynamic_pointer_cast<RtmpPlayer>(_delegate)) {
// rtmp拉流 [AUTO-TRANSLATED:f70a142c]
// Rtmp stream
2023-12-09 16:23:51 +08:00
GET_CONFIG(bool, directProxy, Rtmp::kDirectProxy);
if (directProxy && _option.enable_rtmp) {
2023-12-09 16:23:51 +08:00
mediaSource = std::make_shared<RtmpMediaSource>(_tuple);
}
2020-03-20 11:51:24 +08:00
}
2021-01-17 10:22:51 +08:00
if (mediaSource) {
2020-10-24 23:30:06 +08:00
setMediaSource(mediaSource);
2020-03-20 11:51:24 +08:00
}
2017-04-01 16:35:56 +08:00
}
PlayerProxy::~PlayerProxy() {
2020-03-20 11:51:24 +08:00
_timer.reset();
// 避免析构时, 忘记回调api请求 [AUTO-TRANSLATED:1ad9ad52]
// Avoid forgetting to callback api request when destructing
if (_on_play) {
try {
_on_play(SockException(Err_shutdown, "player proxy close"));
} catch (std::exception &ex) {
WarnL << "Exception occurred: " << ex.what();
}
_on_play = nullptr;
}
2017-04-01 16:35:56 +08:00
}
2020-08-01 10:22:12 +08:00
void PlayerProxy::rePlay(int iFailedCnt) {
auto iDelay = MAX(_reconnect_delay_min * 1000, MIN(iFailedCnt * _reconnect_delay_step * 1000, _reconnect_delay_max * 1000));
2020-03-20 11:51:24 +08:00
weak_ptr<PlayerProxy> weakSelf = shared_from_this();
_timer = std::make_shared<Timer>(iDelay / 1000.0f, [weakSelf, iFailedCnt]() {
// 播放失败次数越多,则延时越长 [AUTO-TRANSLATED:5af39264]
// The more times the playback fails, the longer the delay
auto strongPlayer = weakSelf.lock();
if (!strongPlayer) {
2020-03-20 11:51:24 +08:00
return false;
}
WarnL << "重试播放[" << iFailedCnt << "]:" << strongPlayer->_pull_url;
strongPlayer->MediaPlayer::play(strongPlayer->_pull_url);
strongPlayer->setDirectProxy();
return false;
}, getPoller());
2017-04-01 16:35:56 +08:00
}
bool PlayerProxy::close(MediaSource &sender) {
// 通知其停止推流 [AUTO-TRANSLATED:d69d10d8]
// Notify it to stop pushing the stream
// 主动关闭必须同时取消等待中的重连,并阻止teardown回调再次安排重拉。
// Active close must cancel pending retries and prevent teardown callbacks from scheduling another pull.
_timer.reset();
setOnShutdown(nullptr);
setOnPlayResult(nullptr);
_muxer = nullptr;
setMediaSource(nullptr);
teardown();
_on_close(SockException(Err_shutdown, "closed by user"));
WarnL << "close media: " << sender.getUrl();
return true;
}
2017-04-01 16:35:56 +08:00
int PlayerProxy::totalReaderCount() {
return (_muxer ? _muxer->totalReaderCount() : 0) + (_media_src ? _media_src->readerCount() : 0);
2019-12-28 16:48:11 +08:00
}
int PlayerProxy::totalReaderCount(MediaSource &sender) {
2020-03-20 11:51:24 +08:00
return totalReaderCount();
2019-12-28 16:48:11 +08:00
}
MediaOriginType PlayerProxy::getOriginType(MediaSource &sender) const {
2020-09-27 11:32:49 +08:00
return MediaOriginType::pull;
}
string PlayerProxy::getOriginUrl(MediaSource &sender) const {
2020-09-27 11:32:49 +08:00
return _pull_url;
}
std::shared_ptr<SockInfo> PlayerProxy::getOriginSock(MediaSource &sender) const {
2020-09-27 11:32:49 +08:00
return getSockInfo();
}
float PlayerProxy::getLossRate(MediaSource &sender, TrackType type) {
return getPacketLossRate(type);
}
toolkit::EventPoller::Ptr PlayerProxy::getOwnerPoller(MediaSource &sender) {
return getPoller();
}
TranslationInfo PlayerProxy::getTranslationInfo() {
return _transtalion_info;
}
2018-10-26 17:14:39 +08:00
void PlayerProxy::onPlaySuccess() {
GET_CONFIG(bool, reset_when_replay, General::kResetWhenRePlay);
bool muxer_created = false;
if (dynamic_pointer_cast<RtspMediaSource>(_media_src)) {
// rtsp拉流代理 [AUTO-TRANSLATED:3935cf68]
// Rtsp stream proxy
if (reset_when_replay || !_muxer) {
auto old = _option.enable_rtsp;
_option.enable_rtsp = false;
2023-05-25 16:23:24 +08:00
_muxer = std::make_shared<MultiMediaSourceMuxer>(_tuple, getDuration(), _option);
_option.enable_rtsp = old;
muxer_created = true;
2020-03-20 11:51:24 +08:00
}
} else if (dynamic_pointer_cast<RtmpMediaSource>(_media_src)) {
// rtmp拉流代理 [AUTO-TRANSLATED:21173335]
// Rtmp stream proxy
if (reset_when_replay || !_muxer) {
auto old = _option.enable_rtmp;
_option.enable_rtmp = false;
2023-05-25 16:23:24 +08:00
_muxer = std::make_shared<MultiMediaSourceMuxer>(_tuple, getDuration(), _option);
_option.enable_rtmp = old;
muxer_created = true;
2020-03-20 11:51:24 +08:00
}
} else {
// 其他拉流代理 [AUTO-TRANSLATED:e5f2e45d]
// Other stream proxies
if (reset_when_replay || !_muxer) {
2023-05-25 16:23:24 +08:00
_muxer = std::make_shared<MultiMediaSourceMuxer>(_tuple, getDuration(), _option);
muxer_created = true;
2020-03-20 11:51:24 +08:00
}
}
2020-08-01 10:22:12 +08:00
_muxer->setMediaListener(shared_from_this());
2018-10-26 17:14:39 +08:00
2020-08-01 10:22:12 +08:00
auto videoTrack = getTrack(TrackVideo, false);
2020-03-20 11:51:24 +08:00
auto audioTrack = getTrack(TrackAudio, false);
2019-12-17 09:05:34 +08:00
bool add_to_muxer = muxer_created;
if (!muxer_created) {
auto last_video_track = _muxer->getTrack(TrackVideo, false);
auto last_audio_track = _muxer->getTrack(TrackAudio, false);
if (shouldResetTracks(videoTrack, audioTrack, last_video_track, last_audio_track)) {
// 编解码结构变化时必须重建封装状态;兼容重连只替换输入delegate。
// Rebuild muxing state only when the codec structure changes; compatible reconnects only replace input delegates.
_muxer->resetTracks();
add_to_muxer = true;
}
}
attachPlayerTracks(videoTrack, audioTrack, add_to_muxer);
if (_media_src) {
// 让_muxer对象拦截一部分事件(比如说录像相关事件) [AUTO-TRANSLATED:7d27c400]
// Let the _muxer object intercept some events (such as recording related events)
_media_src->setListener(_muxer);
2019-12-17 09:05:34 +08:00
}
}
bool PlayerProxy::isTrackCompatible(const Track::Ptr &track, const Track::Ptr &last_track) {
if (!track || !last_track) {
return !track && !last_track;
}
if (track->getIndex() != last_track->getIndex()
|| track->getCodecId() != last_track->getCodecId()
|| track->getTrackType() != last_track->getTrackType()
|| !isTrackConfigCompatible(track, last_track)) {
return false;
}
switch (track->getTrackType()) {
case TrackVideo: {
auto video_track = dynamic_pointer_cast<VideoTrack>(track);
auto last_video_track = dynamic_pointer_cast<VideoTrack>(last_track);
// FPS波动不改变封装结构,因此仅比较视频尺寸。
// FPS changes do not alter the muxing structure, so only video dimensions are compared.
return video_track && last_video_track
&& video_track->getVideoWidth() == last_video_track->getVideoWidth()
&& video_track->getVideoHeight() == last_video_track->getVideoHeight();
}
case TrackAudio: {
auto audio_track = dynamic_pointer_cast<AudioTrack>(track);
auto last_audio_track = dynamic_pointer_cast<AudioTrack>(last_track);
return audio_track && last_audio_track
&& audio_track->getAudioSampleRate() == last_audio_track->getAudioSampleRate()
&& audio_track->getAudioChannel() == last_audio_track->getAudioChannel()
&& audio_track->getAudioSampleBit() == last_audio_track->getAudioSampleBit();
}
default: return true;
}
}
bool PlayerProxy::shouldResetTracks(const Track::Ptr &video_track, const Track::Ptr &audio_track,
const Track::Ptr &last_video_track, const Track::Ptr &last_audio_track) const {
return !isTrackCompatible(video_track, last_video_track)
|| !isTrackCompatible(audio_track, last_audio_track);
}
void PlayerProxy::attachPlayerTracks(const Track::Ptr &video_track, const Track::Ptr &audio_track, bool add_to_muxer) {
for (auto &track : { video_track, audio_track }) {
if (!track) {
continue;
}
if (add_to_muxer) {
_muxer->addTrack(track);
}
track->addDelegate(_muxer);
}
if (add_to_muxer) {
// 显式通知track添加完成,避免单track流等待超时。
// Explicitly complete track addition so a single-track stream does not wait for timeout.
_muxer->addTrackCompleted();
}
}
int PlayerProxy::getStatus() {
return _live_status.load();
}
std::string PlayerProxy::getStatusStr() const {
auto status = _status;
return status ? *status : "unknown";
}
uint64_t PlayerProxy::getLiveSecs() {
if (_live_status == 0) {
return _live_secs + _live_ticker.elapsedTime() / 1000;
}
2023-05-13 00:14:35 +08:00
return _live_secs;
}
uint64_t PlayerProxy::getRePullCount() {
return _repull_count;
}
2018-10-24 17:17:55 +08:00
} /* namespace mediakit */