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


#include "MediaSource.h"
xiongziliang committed
29
#include "Record/MP4Reader.h"
30
#include "Util/util.h"
31
#include "Network/sockutil.h"
32
#include "Network/TcpSession.h"
33

xiongziliang committed
34
using namespace toolkit;
35

xiongziliang committed
36
namespace mediakit {
37 38 39 40

recursive_mutex MediaSource::g_mtxMediaSrc;
MediaSource::SchemaVhostAppStreamMap MediaSource::g_mapMediaSrc;

xiongziliang committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
MediaSource::MediaSource(const string &strSchema, const string &strVhost, const string &strApp, const string &strId) :
        _strSchema(strSchema),
        _strApp(strApp),
        _strId(strId) {
    if (strVhost.empty()) {
        _strVhost = DEFAULT_VHOST;
    } else {
        _strVhost = strVhost;
    }
}

MediaSource::~MediaSource() {
    unregist();
}

const string& MediaSource::getSchema() const {
    return _strSchema;
}

const string& MediaSource::getVhost() const {
    return _strVhost;
}

const string& MediaSource::getApp() const {
    //获取该源的id
    return _strApp;
}

const string& MediaSource::getId() const {
    return _strId;
}

vector<Track::Ptr> MediaSource::getTracks(bool trackReady) const {
    auto strongPtr = _track_source.lock();
    if(strongPtr){
        return strongPtr->getTracks(trackReady);
    }
    return vector<Track::Ptr>();
}

void MediaSource::setTrackSource(const std::weak_ptr<TrackSource> &track_src) {
    _track_source = track_src;
83 84 85 86 87 88
    weak_ptr<MediaSource> weakPtr = shared_from_this();
    EventPollerPool::Instance().getPoller()->async([weakPtr,this](){
        auto strongPtr = weakPtr.lock();
        if (!strongPtr) {
            return;
        }
xiongziliang committed
89
        NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaResetTracks, *this);
90
    },false);
xiongziliang committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
}

void MediaSource::setListener(const std::weak_ptr<MediaSourceEvent> &listener){
    _listener = listener;
}

const std::weak_ptr<MediaSourceEvent>& MediaSource::getListener() const{
    return _listener;
}

bool MediaSource::seekTo(uint32_t ui32Stamp) {
    auto listener = _listener.lock();
    if(!listener){
        return false;
    }
    return listener->seekTo(*this,ui32Stamp);
}

bool MediaSource::close(bool force) {
    auto listener = _listener.lock();
    if(!listener){
        return false;
    }
    return listener->close(*this,force);
}

void MediaSource::onNoneReader(){
    auto listener = _listener.lock();
    if(!listener){
        return;
    }
    listener->onNoneReader(*this);
}

void MediaSource::for_each_media(const function<void(const MediaSource::Ptr &src)> &cb) {
    lock_guard<recursive_mutex> lock(g_mtxMediaSrc);
    for (auto &pr0 : g_mapMediaSrc) {
        for (auto &pr1 : pr0.second) {
            for (auto &pr2 : pr1.second) {
                for (auto &pr3 : pr2.second) {
                    auto src = pr3.second.lock();
                    if(src){
                        cb(src);
                    }
                }
            }
        }
    }
}

template<typename MAP, typename FUNC>
static bool searchMedia(MAP &map,
                        const string &schema,
                        const string &vhost,
                        const string &app,
                        const string &id,
                        FUNC &&func) {
    auto it0 = map.find(schema);
    if (it0 == map.end()) {
        //未找到协议
        return false;
    }
    auto it1 = it0->second.find(vhost);
    if (it1 == it0->second.end()) {
        //未找到vhost
        return false;
    }
    auto it2 = it1->second.find(app);
    if (it2 == it1->second.end()) {
        //未找到app
        return false;
    }
    auto it3 = it2->second.find(id);
    if (it3 == it2->second.end()) {
        //未找到streamId
        return false;
    }
    return func(it0, it1, it2, it3);
}
170

xiongziliang committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184
template<typename MAP, typename IT0, typename IT1, typename IT2>
static void eraseIfEmpty(MAP &map, IT0 it0, IT1 it1, IT2 it2) {
    if (it2->second.empty()) {
        it1->second.erase(it2);
        if (it1->second.empty()) {
            it0->second.erase(it1);
            if (it0->second.empty()) {
                map.erase(it0);
            }
        }
    }
};

void findAsync_l(const MediaInfo &info,
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
                            const std::shared_ptr<TcpSession> &session,
                            bool retry,
                            const function<void(const MediaSource::Ptr &src)> &cb){

    auto src = MediaSource::find(info._schema,
                                 info._vhost,
                                 info._app,
                                 info._streamid,
                                 true);
    if(src || !retry){
        cb(src);
        return;
    }

    void *listener_tag = session.get();
    weak_ptr<TcpSession> weakSession = session;
    //广播未找到流,此时可以立即去拉流,这样还来得及
xiongziliang committed
202
    NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastNotFoundStream,info,*session);
203

204
    //最多等待一定时间,如果这个时间内,流未注册上,那么返回未找到流
205
    GET_CONFIG(int,maxWaitMS,General::kMaxStreamWaitTimeMS);
206

207
    //若干秒后执行等待媒体注册超时回调
208
    auto onRegistTimeout = session->getPoller()->doDelayTask(maxWaitMS,[cb,listener_tag](){
209 210 211 212 213 214
        //取消监听该事件
        NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);
        cb(nullptr);
        return 0;
    });

215
    auto onRegist = [listener_tag,weakSession,info,cb,onRegistTimeout](BroadcastMediaChangedArgs) {
216 217 218 219 220 221 222 223 224 225
        auto strongSession = weakSession.lock();
        if(!strongSession) {
            //自己已经销毁
            //取消延时任务,防止多次回调
            onRegistTimeout->cancel();
            //取消事件监听
            NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);
            return;
        }

xiongziliang committed
226 227 228 229 230
        if (!bRegist ||
            sender.getSchema() != info._schema ||
            sender.getVhost() != info._vhost ||
            sender.getApp() != info._app ||
            sender.getId() != info._streamid) {
231 232 233 234 235 236
            //不是自己感兴趣的事件,忽略之
            return;
        }

        //取消延时任务,防止多次回调
        onRegistTimeout->cancel();
237 238
        //取消事件监听
        NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);
239

240 241
        //播发器请求的流终于注册上了,切换到自己的线程再回复
        strongSession->async([weakSession,info,cb](){
242 243 244 245 246 247
            auto strongSession = weakSession.lock();
            if(!strongSession) {
                return;
            }
            DebugL << "收到媒体注册事件,回复播放器:" << info._schema << "/" << info._vhost << "/" << info._app << "/" << info._streamid;
            //再找一遍媒体源,一般能找到
xiongziliang committed
248
            findAsync_l(info,strongSession,false,cb);
249 250 251 252 253
        }, false);
    };
    //监听媒体注册事件
    NoticeCenter::Instance().addListener(listener_tag, Broadcast::kBroadcastMediaChanged, onRegist);
}
xiongziliang committed
254 255 256 257 258

void MediaSource::findAsync(const MediaInfo &info, const std::shared_ptr<TcpSession> &session,const function<void(const Ptr &src)> &cb){
    return findAsync_l(info, session, true, cb);
}

259 260 261 262 263 264 265 266 267 268
MediaSource::Ptr MediaSource::find(
        const string &schema,
        const string &vhost_tmp,
        const string &app,
        const string &id,
        bool bMake) {
    string vhost = vhost_tmp;
    if(vhost.empty()){
        vhost = DEFAULT_VHOST;
    }
269 270 271 272 273 274

    GET_CONFIG(bool,enableVhost,General::kEnableVhost);
    if(!enableVhost){
        vhost = DEFAULT_VHOST;
    }

275 276
    lock_guard<recursive_mutex> lock(g_mtxMediaSrc);
    MediaSource::Ptr ret;
3503207480@qq.com committed
277
	//查找某一媒体源,找到后返回
xiongziliang committed
278 279 280 281 282 283 284 285 286 287 288 289 290
    searchMedia(g_mapMediaSrc, schema, vhost, app, id, [&](SchemaVhostAppStreamMap::iterator &it0,
                                                           VhostAppStreamMap::iterator &it1,
                                                           AppStreamMap::iterator &it2,
                                                           StreamMap::iterator &it3) {
        ret = it3->second.lock();
        if (!ret) {
            //该对象已经销毁
            it2->second.erase(it3);
            eraseIfEmpty(g_mapMediaSrc,it0, it1, it2);
            return false;
        }
        return true;
    });
291
    if(!ret && bMake){
3503207480@qq.com committed
292
        //未查找媒体源,则创建一个
xiongziliang committed
293
        ret = MP4Reader::onMakeMediaSource(schema, vhost,app,id);
294 295 296
    }
    return ret;
}
297
void MediaSource::regist() {
298 299 300 301
    GET_CONFIG(bool,enableVhost,General::kEnableVhost);
    if(!enableVhost){
        _strVhost = DEFAULT_VHOST;
    }
302
    //注册该源,注册后服务器才能找到该源
303 304
    {
        lock_guard<recursive_mutex> lock(g_mtxMediaSrc);
305
        g_mapMediaSrc[_strSchema][_strVhost][_strApp][_strId] =  shared_from_this();
306
    }
307
    InfoL << _strSchema << " " << _strVhost << " " << _strApp << " " << _strId;
308 309 310 311 312 313
    weak_ptr<MediaSource> weakPtr = shared_from_this();
    EventPollerPool::Instance().getPoller()->async([weakPtr,this](){
        auto strongPtr = weakPtr.lock();
        if (!strongPtr) {
            return;
        }
xiongziliang committed
314
        NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaChanged, true, *this);
315
    },false);
316 317 318 319
}
bool MediaSource::unregist() {
    //反注册该源
    lock_guard<recursive_mutex> lock(g_mtxMediaSrc);
xiongziliang committed
320 321 322 323
    return searchMedia(g_mapMediaSrc, _strSchema, _strVhost, _strApp, _strId,[&](SchemaVhostAppStreamMap::iterator &it0,
                                                                                 VhostAppStreamMap::iterator &it1,
                                                                                 AppStreamMap::iterator &it2,
                                                                                 StreamMap::iterator &it3) {
324
        auto strongMedia = it3->second.lock();
xiongziliang committed
325
        if (strongMedia && this != strongMedia.get()) {
326 327 328 329
            //不是自己,不允许反注册
            return false;
        }
        it2->second.erase(it3);
xiongziliang committed
330
        eraseIfEmpty(g_mapMediaSrc, it0, it1, it2);
331 332 333 334 335
        unregisted();
        return true;
    });
}
void MediaSource::unregisted(){
336
    InfoL <<  "" <<  _strSchema << " " << _strVhost << " " << _strApp << " " << _strId;
xiongziliang committed
337
    NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastMediaChanged, false, *this);
338 339
}

xiongziliang committed
340 341 342

/////////////////////////////////////MediaInfo//////////////////////////////////////

343 344 345 346
void MediaInfo::parse(const string &url){
    //string url = "rtsp://127.0.0.1:8554/live/id?key=val&a=1&&b=2&vhost=vhost.com";
    auto schema_pos = url.find("://");
    if(schema_pos != string::npos){
347
        _schema = url.substr(0,schema_pos);
348 349 350 351 352 353 354 355
    }else{
        schema_pos = -3;
    }
    auto split_vec = split(url.substr(schema_pos + 3),"/");
    if(split_vec.size() > 0){
        auto vhost = split_vec[0];
        auto pos = vhost.find(":");
        if(pos != string::npos){
356 357
            _host = _vhost = vhost.substr(0,pos);
            _port = vhost.substr(pos + 1);
358
        } else{
359
            _host = _vhost = vhost;
360 361 362
        }
    }
    if(split_vec.size() > 1){
363
        _app = split_vec[1];
364 365 366 367 368 369 370 371 372 373 374
    }
    if(split_vec.size() > 2){
        string steamid;
        for(int i = 2 ; i < split_vec.size() ; ++i){
            steamid.append(split_vec[i] + "/");
        }
        if(steamid.back() == '/'){
            steamid.pop_back();
        }
        auto pos = steamid.find("?");
        if(pos != string::npos){
375
            _streamid = steamid.substr(0,pos);
376 377
            _param_strs = steamid.substr(pos + 1);
            _params = Parser::parseArgs(_param_strs);
378 379
            if(_params.find(VHOST_KEY) != _params.end()){
                _vhost = _params[VHOST_KEY];
380 381
            }
        } else{
382
            _streamid = steamid;
383 384
        }
    }
385 386

    GET_CONFIG(bool,enableVhost,General::kEnableVhost);
387
    if(!enableVhost || _vhost.empty() || _vhost == "localhost" || INADDR_NONE != inet_addr(_vhost.data())){
388
        _vhost = DEFAULT_VHOST;
389 390 391
    }
}

xiongziliang committed
392 393
/////////////////////////////////////MediaSourceEvent//////////////////////////////////////

xiongziliang committed
394 395
void MediaSourceEvent::onNoneReader(MediaSource &sender){
    //没有任何读取器消费该源,表明该源可以关闭了
396 397 398 399 400 401 402 403 404 405
    WarnL << sender.getSchema() << "/" << sender.getVhost() << "/" << sender.getApp() << "/" << sender.getId();
    weak_ptr<MediaSource> weakPtr = sender.shared_from_this();

    //异步广播该事件,防止同步调用sender.close()导致在接收rtp或rtmp包时清空包缓存等操作
    EventPollerPool::Instance().getPoller()->async([weakPtr](){
        auto strongPtr = weakPtr.lock();
        if(strongPtr){
            NoticeCenter::Instance().emitEvent(Broadcast::kBroadcastStreamNoneReader,*strongPtr);
        }
    },false);
xiongziliang committed
406 407
}

408

xiongziliang committed
409
} /* namespace mediakit */