RtmpPlayer.cpp 9.96 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * MIT License
xzl committed
3
 *
xiongziliang committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
xzl committed
25 26 27
 */

#include "RtmpPlayer.h"
xiongzilaing committed
28 29
#include "Rtsp/Rtsp.h"
#include "Rtmp/utils.h"
xzl committed
30 31
#include "Util/util.h"
#include "Util/onceToken.h"
xiongzilaing committed
32 33
#include "Thread/ThreadPool.h"

xzl committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
using namespace ZL::Util;

namespace ZL {
namespace Rtmp {

unordered_map<string, RtmpPlayer::rtmpCMDHandle> RtmpPlayer::g_mapCmd;
RtmpPlayer::RtmpPlayer() {
	static onceToken token([]() {
		g_mapCmd.emplace("_error",&RtmpPlayer::onCmd_result);
		g_mapCmd.emplace("_result",&RtmpPlayer::onCmd_result);
		g_mapCmd.emplace("onStatus",&RtmpPlayer::onCmd_onStatus);
		g_mapCmd.emplace("onMetaData",&RtmpPlayer::onCmd_onMetaData);
		}, []() {});

}

RtmpPlayer::~RtmpPlayer() {
	teardown();
	DebugL << endl;
}
void RtmpPlayer::teardown() {
	if (alive()) {
56 57 58
		_strApp.clear();
		_strStream.clear();
		_strTcUrl.clear();
59 60

		{
61 62
			lock_guard<recursive_mutex> lck(_mtxOnResultCB);
			_mapOnResultCB.clear();
63
		}
xzl committed
64
        {
65 66
            lock_guard<recursive_mutex> lck(_mtxOnStatusCB);
            _dqOnStatusCB.clear();
xzl committed
67
        }
68 69 70 71 72 73
		_pBeatTimer.reset();
		_pPlayTimer.reset();
		_pMediaTimer.reset();
        _fSeekTo = 0;
        CLEAR_ARR(_adFistStamp);
        CLEAR_ARR(_adNowStamp);
xiongziliang committed
74
        reset();
xzl committed
75 76 77
        shutdown();
	}
}
xiongziliang committed
78
void RtmpPlayer::play(const char* strUrl)  {
xzl committed
79 80
	teardown();
	string strHost = FindField(strUrl, "://", "/");
81 82 83
	_strApp = 	FindField(strUrl, (strHost + "/").data(), "/");
    _strStream = FindField(strUrl, (strHost + "/" + _strApp + "/").data(), NULL);
    _strTcUrl = string("rtmp://") + strHost + "/" + _strApp;
xzl committed
84

85
    if (!_strApp.size() || !_strStream.size()) {
xzl committed
86 87 88
        _onPlayResult(SockException(Err_other,"rtmp url非法"));
        return;
    }
89
	DebugL << strHost << " " << _strApp << " " << _strStream;
xzl committed
90 91 92 93 94 95 96 97 98

	auto iPort = atoi(FindField(strHost.c_str(), ":", NULL).c_str());
	if (iPort <= 0) {
        //rtmp 默认端口1935
		iPort = 1935;
	} else {
        //服务器域名
		strHost = FindField(strHost.c_str(), NULL, ":");
	}
99 100 101
	if(!(*this)[PlayerBase::kNetAdapter].empty()){
		setNetAdapter((*this)[PlayerBase::kNetAdapter]);
	}
xzl committed
102 103 104 105 106 107 108 109 110 111 112 113
	startConnect(strHost, iPort);
}
void RtmpPlayer::onErr(const SockException &ex){
	_onShutdown(ex);
}
void RtmpPlayer::onConnect(const SockException &err){
	if(err.getErrCode()!=Err_success) {
		_onPlayResult(err);
		return;
	}

	weak_ptr<RtmpPlayer> weakSelf= dynamic_pointer_cast<RtmpPlayer>(shared_from_this());
114
	_pPlayTimer.reset( new Timer(10, [weakSelf]() {
xzl committed
115 116 117 118 119 120 121
		auto strongSelf=weakSelf.lock();
		if(!strongSelf) {
			return false;
		}
		strongSelf->_onPlayResult(SockException(Err_timeout,"play rtmp timeout"));
		strongSelf->teardown();
		return false;
xiongziliang committed
122
	},getExecutor()));
xzl committed
123 124 125 126 127 128 129 130
	startClientSession([weakSelf](){
        auto strongSelf=weakSelf.lock();
		if(!strongSelf) {
            return;
        }
		strongSelf->send_connect();
	});
}
131
void RtmpPlayer::onRecv(const Buffer::Ptr &pBuf){
xzl committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	try {
		onParseRtmp(pBuf->data(), pBuf->size());
	} catch (exception &e) {
		SockException ex(Err_other, e.what());
		_onPlayResult(ex);
		_onShutdown(ex);
		teardown();
	}
}

void RtmpPlayer::pause(bool bPause) {
	send_pause(bPause);
}

inline void RtmpPlayer::send_connect() {
	AMFValue obj(AMF_OBJECT);
148 149
	obj.set("app", _strApp);
	obj.set("tcUrl", _strTcUrl);
150
	//未使用代理
xzl committed
151
	obj.set("fpad", false);
152
	//参考librtmp,什么作用?
xzl committed
153
	obj.set("capabilities", 15);
154
	//SUPPORT_VID_CLIENT_SEEK 支持seek
xzl committed
155 156
	obj.set("videoFunction", 1);
    //只支持aac
157
    obj.set("audioCodecs", (double)(0x0400));
xzl committed
158
    //只支持H264
159
    obj.set("videoCodecs", (double)(0x0080));
xzl committed
160 161 162 163 164 165 166 167
	sendInvoke("connect", obj);
	addOnResultCB([this](AMFDecoder &dec){
		//TraceL << "connect result";
		dec.load<AMFValue>();
		auto val = dec.load<AMFValue>();
		auto level = val["level"].as_string();
		auto code = val["code"].as_string();
		if(level != "status"){
168
			throw std::runtime_error(StrPrinter <<"connect 失败:" << level << " " << code << endl);
xzl committed
169 170 171 172 173 174 175 176 177 178 179
		}
		send_createStream();
	});
}

inline void RtmpPlayer::send_createStream() {
	AMFValue obj(AMF_NULL);
	sendInvoke("createStream", obj);
	addOnResultCB([this](AMFDecoder &dec){
		//TraceL << "createStream result";
		dec.load<AMFValue>();
180
		_ui32StreamId = dec.load<int>();
xzl committed
181 182 183 184 185 186
		send_play();
	});
}

inline void RtmpPlayer::send_play() {
	AMFEncoder enc;
187
	enc << "play" << ++_iReqID  << nullptr << _strStream << (double)_ui32StreamId;
xzl committed
188 189 190 191 192 193
	sendRequest(MSG_CMD, enc.data());
	auto fun = [this](AMFValue &val){
		//TraceL << "play onStatus";
		auto level = val["level"].as_string();
		auto code = val["code"].as_string();
		if(level != "status"){
194
			throw std::runtime_error(StrPrinter <<"play 失败:" << level << " " << code << endl);
xzl committed
195 196 197 198 199 200 201 202
		}
	};
	addOnStatusCB(fun);
	addOnStatusCB(fun);
}

inline void RtmpPlayer::send_pause(bool bPause) {
	AMFEncoder enc;
203
	enc << "pause" << ++_iReqID  << nullptr << bPause;
xzl committed
204 205 206 207 208 209 210
	sendRequest(MSG_CMD, enc.data());
	auto fun = [this,bPause](AMFValue &val){
        //TraceL << "pause onStatus";
        auto level = val["level"].as_string();
        auto code = val["code"].as_string();
        if(level != "status") {
            if(!bPause){
211
                throw std::runtime_error(StrPrinter <<"pause 恢复播放失败:" << level << " " << code << endl);
xzl committed
212 213
            }
        }else{
214
            _bPaused = bPause;
xzl committed
215 216 217 218
            if(!bPause){
                _onPlayResult(SockException(Err_success, "rtmp resum success"));
            }else{
                //暂停播放
219
                _pMediaTimer.reset();
xzl committed
220 221 222 223 224
            }
        }
	};
	addOnStatusCB(fun);

225
	_pBeatTimer.reset();
xzl committed
226 227
	if(bPause){
		weak_ptr<RtmpPlayer> weakSelf = dynamic_pointer_cast<RtmpPlayer>(shared_from_this());
228
		_pBeatTimer.reset(new Timer(3,[weakSelf](){
xzl committed
229 230 231 232 233 234 235
			auto strongSelf = weakSelf.lock();
			if (!strongSelf){
				return false;
			}
			uint32_t timeStamp = ::time(NULL);
			strongSelf->sendUserControl(CONTROL_PING_REQUEST, timeStamp);
			return true;
xiongziliang committed
236
		},getExecutor()));
xzl committed
237 238 239 240 241
	}
}

void RtmpPlayer::onCmd_result(AMFDecoder &dec){
	auto iReqId = dec.load<int>();
242 243 244
	lock_guard<recursive_mutex> lck(_mtxOnResultCB);
	auto it = _mapOnResultCB.find(iReqId);
	if(it != _mapOnResultCB.end()){
xzl committed
245
		it->second(dec);
246
		_mapOnResultCB.erase(it);
xzl committed
247 248 249 250 251 252 253 254 255 256 257 258 259
	}else{
		WarnL << "unhandled _result";
	}
}
void RtmpPlayer::onCmd_onStatus(AMFDecoder &dec) {
	AMFValue val;
	while(true){
		val = dec.load<AMFValue>();
		if(val.type() == AMF_OBJECT){
			break;
		}
	}
	if(val.type() != AMF_OBJECT){
260
		throw std::runtime_error("onStatus:the result object was not found");
xzl committed
261 262
	}
    
263 264 265 266
    lock_guard<recursive_mutex> lck(_mtxOnStatusCB);
	if(_dqOnStatusCB.size()){
		_dqOnStatusCB.front()(val);
		_dqOnStatusCB.pop_front();
xzl committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
	}else{
		auto level = val["level"];
		auto code = val["code"].as_string();
		if(level.type() == AMF_STRING){
			if(level.as_string() != "status"){
				throw std::runtime_error(StrPrinter <<"onStatus 失败:" << level.as_string() << " " << code << endl);
			}
		}
		//WarnL << "unhandled onStatus:" << code;
    }
}

void RtmpPlayer::onCmd_onMetaData(AMFDecoder &dec) {
	//TraceL;
	auto val = dec.load<AMFValue>();
	if(!onCheckMeta(val)){
		throw std::runtime_error("onCheckMeta faied");
	}
	_onPlayResult(SockException(Err_success,"play rtmp success"));
}

void RtmpPlayer::onStreamDry(uint32_t ui32StreamId) {
	//TraceL << ui32StreamId;
	_onShutdown(SockException(Err_other,"rtmp stream dry"));
}


void RtmpPlayer::onRtmpChunk(RtmpPacket &chunkData) {
	switch (chunkData.typeId) {
		case MSG_CMD:
		case MSG_CMD3:
		case MSG_DATA:
		case MSG_DATA3: {
			AMFDecoder dec(chunkData.strBuf, 0);
			std::string type = dec.load<std::string>();
			auto it = g_mapCmd.find(type);
			if(it != g_mapCmd.end()){
				auto fun = it->second;
				(this->*fun)(dec);
			}else{
				WarnL << "can not support cmd:" << type;
			}
		}
			break;
		case MSG_AUDIO:
		case MSG_VIDEO: {
            auto idx = chunkData.typeId%2;
314 315
            if (_aNowStampTicker[idx].elapsedTime() > 500) {
                _adNowStamp[idx] = chunkData.timeStamp;
xzl committed
316
            }
xiongziliang committed
317
			_onMediaData(std::make_shared<RtmpPacket>(chunkData));
xzl committed
318 319 320 321 322 323 324 325 326 327 328
		}
			break;
		default:
			//WarnL << "unhandled message:" << (int) chunkData.typeId << hexdump(chunkData.strBuf.data(), chunkData.strBuf.size());
			break;
		}
}

float RtmpPlayer::getProgressTime() const{
    double iTime[2] = {0,0};
    for(auto i = 0 ;i < 2 ;i++){
329
        iTime[i] = (_adNowStamp[i] - _adFistStamp[i]) / 1000.0;
xzl committed
330
    }
331
    return _fSeekTo + MAX(iTime[0],iTime[1]);
xzl committed
332 333
}
void RtmpPlayer::seekToTime(float fTime){
334
    if (_bPaused) {
xzl committed
335 336 337
        pause(false);
    }
    AMFEncoder enc;
338
    enc << "seek" << ++_iReqID << nullptr << fTime * 1000.0;
xzl committed
339 340 341
    sendRequest(MSG_CMD, enc.data());
    addOnStatusCB([this,fTime](AMFValue &val) {
        //TraceL << "seek result";
342 343
        _aNowStampTicker[0].resetTime();
        _aNowStampTicker[1].resetTime();
xzl committed
344 345
        float iTimeInc = fTime - getProgressTime();
        for(auto i = 0 ;i < 2 ;i++){
346 347
            _adFistStamp[i] = _adNowStamp[i] + iTimeInc * 1000.0;
            _adNowStamp[i] = _adFistStamp[i];
xzl committed
348
        }
349
        _fSeekTo = fTime;
xzl committed
350 351 352 353 354 355 356
    });

}

} /* namespace Rtmp */
} /* namespace ZL */