RtmpMediaSource.h 4.85 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"
37
#include "RtmpMuxer/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
class RtmpMediaSource: public MediaSource ,public RingDelegate<RtmpPacket::Ptr> {
xzl committed
52 53
public:
	typedef std::shared_ptr<RtmpMediaSource> Ptr;
xiongziliang committed
54
	typedef RingBuffer<RtmpPacket::Ptr> RingType;
55

56 57 58 59
	RtmpMediaSource(const string &vhost,
	                const string &strApp,
	                const string &strId,
	                int ringSize = 0) :
60
			MediaSource(RTMP_SCHEMA,vhost,strApp,strId),
61 62
			_ringSize(ringSize) {}

63 64
	virtual ~RtmpMediaSource() {}

xzl committed
65 66
	const RingType::Ptr &getRing() const {
		//获取媒体源的rtp环形缓冲
67
		return _pRing;
xzl committed
68
	}
69

70
	int readerCount() override {
71
        return _pRing ? _pRing->readerCount() : 0;
72 73
	}

xzl committed
74
	const AMFValue &getMetaData() const {
75 76
		lock_guard<recursive_mutex> lock(_mtxMap);
		return _metadata;
xzl committed
77 78 79
	}
	template<typename FUN>
	void getConfigFrame(const FUN &f) {
80 81
		lock_guard<recursive_mutex> lock(_mtxMap);
		for (auto &pr : _mapCfgFrame) {
xzl committed
82 83 84
			f(pr.second);
		}
	}
85

86 87 88
	virtual void onGetMetaData(const AMFValue &metadata) {
		lock_guard<recursive_mutex> lock(_mtxMap);
		_metadata = metadata;
xzl committed
89
	}
xiongziliang committed
90 91

    void onWrite(const RtmpPacket::Ptr &pkt,bool isKey = true) override {
92
		lock_guard<recursive_mutex> lock(_mtxMap);
93
		if (pkt->isCfgFrame()) {
94
			_mapCfgFrame[pkt->typeId] = pkt;
95
            return;
xzl committed
96
		}
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

        _mapStamp[pkt->typeId] = pkt->timeStamp;

        if(!_pRing){
            weak_ptr<RtmpMediaSource> weakSelf = dynamic_pointer_cast<RtmpMediaSource>(shared_from_this());
            _pRing = std::make_shared<RingType>(_ringSize,[weakSelf](const EventPoller::Ptr &,int size,bool){
                auto strongSelf = weakSelf.lock();
                if(!strongSelf){
                    return;
                }
                strongSelf->onReaderChanged(size);
            });
            onReaderChanged(0);
            regist();
        }
        _pRing->write(pkt,pkt->isVideoKeyFrame());
        checkNoneReader();
    }
115 116 117 118 119 120 121 122 123 124 125 126

	uint32_t getTimeStamp(TrackType trackType) override {
		lock_guard<recursive_mutex> lock(_mtxMap);
		switch (trackType){
			case TrackVideo:
				return _mapStamp[MSG_VIDEO];
			case TrackAudio:
				return _mapStamp[MSG_AUDIO];
			default:
				return MAX(_mapStamp[MSG_VIDEO],_mapStamp[MSG_AUDIO]);
		}
	}
127 128 129

private:
    void onReaderChanged(int size){
130
	    //我们记录最后一次活动时间
131
        _readerTicker.resetTime();
132
        if(size != 0 || readerCount() != 0){
133
            //还有消费者正在观看该流
134 135 136 137 138 139 140
            _asyncEmitNoneReader = false;
            return;
        }
        _asyncEmitNoneReader  = true;
    }

    void checkNoneReader(){
141
        GET_CONFIG(int,stream_none_reader_delay,General::kStreamNoneReaderDelayMS);
142 143
        if(_asyncEmitNoneReader && _readerTicker.elapsedTime() > stream_none_reader_delay){
            _asyncEmitNoneReader = false;
xiongziliang committed
144
            onNoneReader();
145 146
        }
    }
xzl committed
147
protected:
148
	AMFValue _metadata;
149 150
    unordered_map<int, RtmpPacket::Ptr> _mapCfgFrame;
	unordered_map<int,uint32_t> _mapStamp;
151 152
	mutable recursive_mutex _mtxMap;
	RingBuffer<RtmpPacket::Ptr>::Ptr _pRing; //rtp环形缓冲
153 154 155
	int _ringSize;
	Ticker _readerTicker;
    bool _asyncEmitNoneReader = false;
xzl committed
156 157
};

xiongziliang committed
158
} /* namespace mediakit */
xzl committed
159 160

#endif /* SRC_RTMP_RTMPMEDIASOURCE_H_ */