RtmpMediaSource.h 5.84 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * MIT License
xzl committed
3
 *
xiongziliang committed
4
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
xiongziliang committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * 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 28 29
 */

#ifndef SRC_RTMP_RTMPMEDIASOURCE_H_
#define SRC_RTMP_RTMPMEDIASOURCE_H_

xiongzilaing committed
30 31
#include <mutex>
#include <memory>
xzl committed
32 33 34 35 36
#include <string>
#include <functional>
#include <unordered_map>
#include "amf.h"
#include "Rtmp.h"
xiongziliang committed
37
#include "RtmpDemuxer.h"
xiongziliang committed
38
#include "Common/config.h"
39
#include "Common/MediaSource.h"
xiongzilaing committed
40 41 42 43 44 45 46
#include "Util/util.h"
#include "Util/logger.h"
#include "Util/RingBuffer.h"
#include "Util/TimeTicker.h"
#include "Util/ResourcePool.h"
#include "Util/NoticeCenter.h"
#include "Thread/ThreadPool.h"
xiongziliang committed
47
using namespace toolkit;
xzl committed
48

xiongziliang committed
49
namespace mediakit {
xzl committed
50

51 52 53 54 55 56 57 58
/**
 * rtmp媒体源的数据抽象
 * rtmp有关键的三要素,分别是metadata、config帧,普通帧
 * 其中metadata是非必须的,有些编码格式也没有config帧(比如MP3)
 * 只要生成了这三要素,那么要实现rtmp推流、rtmp服务器就很简单了
 * rtmp推拉流协议中,先传递metadata,然后传递config帧,然后一直传递普通帧
 */
class RtmpMediaSource : public MediaSource, public RingDelegate<RtmpPacket::Ptr> {
xzl committed
59 60
public:
	typedef std::shared_ptr<RtmpMediaSource> Ptr;
xiongziliang committed
61
	typedef RingBuffer<RtmpPacket::Ptr> RingType;
62

63 64 65 66 67 68 69
	/**
	 * 构造函数
	 * @param vhost 虚拟主机名
	 * @param app 应用名
	 * @param stream_id 流id
	 * @param ring_size 可以设置固定的环形缓冲大小,0则自适应
	 */
70
	RtmpMediaSource(const string &vhost,
71 72 73 74
					const string &app,
					const string &stream_id,
					int ring_size = 0) :
			MediaSource(RTMP_SCHEMA, vhost, app, stream_id), _ring_size(ring_size) {
75 76
		_metadata = TitleMeta().getMetadata();
	}
77

78 79
	virtual ~RtmpMediaSource() {}

80 81 82
	/**
	 * 	获取媒体源的环形缓冲
	 */
xzl committed
83
	const RingType::Ptr &getRing() const {
84
		return _ring;
xzl committed
85
	}
86

87 88 89 90
	/**
	 * 获取播放器个数
	 * @return
	 */
91
	int readerCount() override {
92
		return _ring ? _ring->readerCount() : 0;
93 94
	}

95 96 97
	/**
	 * 获取metadata
	 */
xzl committed
98
	const AMFValue &getMetaData() const {
99
		lock_guard<recursive_mutex> lock(_mtx);
100
		return _metadata;
xzl committed
101
	}
102 103 104 105 106 107 108 109

	/**
	 * 获取所有的config帧
	 */
	template<typename FUNC>
	void getConfigFrame(const FUNC &f) {
		lock_guard<recursive_mutex> lock(_mtx);
		for (auto &pr : _config_frame_map) {
xzl committed
110 111 112
			f(pr.second);
		}
	}
113

114 115 116 117 118
	/**
	 * 设置metadata
	 */
	virtual void setMetaData(const AMFValue &metadata) {
		lock_guard<recursive_mutex> lock(_mtx);
119
		_metadata = metadata;
xzl committed
120
	}
xiongziliang committed
121

122 123 124
	/**
	 * 输入rtmp包
	 * @param pkt rtmp包
125
	 * @param key 是否为关键帧
126
	 */
127
	void onWrite(const RtmpPacket::Ptr &pkt, bool key = true) override {
128
		lock_guard<recursive_mutex> lock(_mtx);
129
		if (pkt->isCfgFrame()) {
130 131
			_config_frame_map[pkt->typeId] = pkt;
			return;
xzl committed
132
		}
133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
		if (!_ring) {
			weak_ptr<RtmpMediaSource> weakSelf = dynamic_pointer_cast<RtmpMediaSource>(shared_from_this());
			auto lam = [weakSelf](const EventPoller::Ptr &, int size, bool) {
				auto strongSelf = weakSelf.lock();
				if (!strongSelf) {
					return;
				}
				strongSelf->onReaderChanged(size);
			};
			_ring = std::make_shared<RingType>(_ring_size, std::move(lam));
			onReaderChanged(0);

			//如果输入了非config帧,
			//那么说明不再可能获取config帧以及metadata,
			//所以我们强制其为已注册
149 150
			regist();
		}
151 152
		_track_stamps_map[pkt->typeId] = pkt->timeStamp;
		_ring->write(pkt, pkt->isVideoKeyFrame());
153
		checkNoneReader();
154
	}
155

156 157 158
	/**
	 * 获取当前时间戳
	 */
159
	uint32_t getTimeStamp(TrackType trackType) override {
160 161
		lock_guard<recursive_mutex> lock(_mtx);
		switch (trackType) {
162
			case TrackVideo:
163
				return _track_stamps_map[MSG_VIDEO];
164
			case TrackAudio:
165
				return _track_stamps_map[MSG_AUDIO];
166
			default:
167
				return MAX(_track_stamps_map[MSG_VIDEO], _track_stamps_map[MSG_AUDIO]);
168 169
		}
	}
170 171

private:
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
	/**
	 * 每次增减消费者都会触发该函数
	 */
	void onReaderChanged(int size) {
		//我们记录最后一次活动时间
		_reader_changed_ticker.resetTime();
		if (size != 0 || readerCount() != 0) {
			//还有消费者正在观看该流
			_async_emit_none_reader = false;
			return;
		}
		_async_emit_none_reader = true;
	}

	/**
	 * 检查是否无人消费该流,
	 * 如果无人消费且超过一定时间会触发onNoneReader事件
	 */
	void checkNoneReader() {
		GET_CONFIG(int, stream_none_reader_delay, General::kStreamNoneReaderDelayMS);
		if (_async_emit_none_reader && _reader_changed_ticker.elapsedTime() > stream_none_reader_delay) {
			_async_emit_none_reader = false;
			onNoneReader();
		}
	}
xzl committed
197
protected:
198 199 200 201
	int _ring_size;
	bool _async_emit_none_reader = false;
	mutable recursive_mutex _mtx;
	Ticker _reader_changed_ticker;
202
	AMFValue _metadata;
203 204 205
	RingBuffer<RtmpPacket::Ptr>::Ptr _ring;
	unordered_map<int, uint32_t> _track_stamps_map;
	unordered_map<int, RtmpPacket::Ptr> _config_frame_map;
xzl committed
206 207
};

xiongziliang committed
208
} /* namespace mediakit */
xzl committed
209 210

#endif /* SRC_RTMP_RTMPMEDIASOURCE_H_ */