Blame view

trunk/src/app/srs_app_source.cpp 28.1 KB
1 2 3
/*
The MIT License (MIT)
4
Copyright (c) 2013-2014 winlin
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

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.
*/
24
#include <srs_app_source.hpp>
25 26

#include <algorithm>
winlin authored
27
using namespace std;
28
29
#include <srs_kernel_log.hpp>
30
#include <srs_protocol_rtmp_stack.hpp>
31
#include <srs_core_autofree.hpp>
32
#include <srs_protocol_amf0.hpp>
33 34 35 36 37
#include <srs_app_codec.hpp>
#include <srs_app_hls.hpp>
#include <srs_app_forward.hpp>
#include <srs_app_config.hpp>
#include <srs_app_encoder.hpp>
38
#include <srs_protocol_rtmp.hpp>
39
40 41
#define CONST_MAX_JITTER_MS         500
#define DEFAULT_FRAME_TIME_MS         40
42 43 44

SrsRtmpJitter::SrsRtmpJitter()
{
45
    last_pkt_correct_time = last_pkt_time = 0;
46 47 48 49 50 51
}

SrsRtmpJitter::~SrsRtmpJitter()
{
}
52
int SrsRtmpJitter::correct(SrsSharedPtrMessage* msg, int tba, int tbv)
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    int ret = ERROR_SUCCESS;

    // set to 0 for metadata.
    if (!msg->header.is_video() && !msg->header.is_audio()) {
        msg->header.timestamp = 0;
        return ret;
    }
    
    int sample_rate = tba;
    int frame_rate = tbv;
    
    /**
    * we use a very simple time jitter detect/correct algorithm:
    * 1. delta: ensure the delta is positive and valid,
    *     we set the delta to DEFAULT_FRAME_TIME_MS,
    *     if the delta of time is nagative or greater than CONST_MAX_JITTER_MS.
    * 2. last_pkt_time: specifies the original packet time,
    *     is used to detect next jitter.
    * 3. last_pkt_correct_time: simply add the positive delta, 
    *     and enforce the time monotonically.
    */
    int64_t time = msg->header.timestamp;
    int64_t delta = time - last_pkt_time;

    // if jitter detected, reset the delta.
    if (delta < 0 || delta > CONST_MAX_JITTER_MS) {
        // calc the right diff by audio sample rate
        if (msg->header.is_audio() && sample_rate > 0) {
            delta = (int64_t)(delta * 1000.0 / sample_rate);
        } else if (msg->header.is_video() && frame_rate > 0) {
            delta = (int64_t)(delta * 1.0 / frame_rate);
        } else {
            delta = DEFAULT_FRAME_TIME_MS;
        }

        // sometimes, the time is absolute time, so correct it again.
        if (delta < 0 || delta > CONST_MAX_JITTER_MS) {
            delta = DEFAULT_FRAME_TIME_MS;
        }
        
        srs_info("jitter detected, last_pts=%"PRId64", pts=%"PRId64", diff=%"PRId64", last_time=%"PRId64", time=%"PRId64", diff=%"PRId64"",
            last_pkt_time, time, time - last_pkt_time, last_pkt_correct_time, last_pkt_correct_time + delta, delta);
    } else {
        srs_verbose("timestamp no jitter. time=%"PRId64", last_pkt=%"PRId64", correct_to=%"PRId64"", 
            time, last_pkt_time, last_pkt_correct_time + delta);
    }
    
    last_pkt_correct_time = srs_max(0, last_pkt_correct_time + delta);
    
    msg->header.timestamp = last_pkt_correct_time;
    last_pkt_time = time;
    
    return ret;
107 108 109 110
}

int SrsRtmpJitter::get_time()
{
111
    return (int)last_pkt_correct_time;
112 113
}
winlin authored
114
SrsMessageQueue::SrsMessageQueue()
115
{
116 117
    queue_size_ms = 0;
    av_start_time = av_end_time = -1;
118 119
}
winlin authored
120
SrsMessageQueue::~SrsMessageQueue()
121
{
122
    clear();
123 124
}
winlin authored
125
void SrsMessageQueue::set_queue_size(double queue_size)
126
{
127
    queue_size_ms = (int)(queue_size * 1000);
128 129
}
winlin authored
130
int SrsMessageQueue::enqueue(SrsSharedPtrMessage* msg)
131
{
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    int ret = ERROR_SUCCESS;
    
    if (msg->header.is_video() || msg->header.is_audio()) {
        if (av_start_time == -1) {
            av_start_time = msg->header.timestamp;
        }
        
        av_end_time = msg->header.timestamp;
    }
    
    msgs.push_back(msg);

    while (av_end_time - av_start_time > queue_size_ms) {
        shrink();
    }
    
    return ret;
149 150
}
winlin authored
151
int SrsMessageQueue::get_packets(int max_count, SrsSharedPtrMessage**& pmsgs, int& count)
152
{
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    int ret = ERROR_SUCCESS;
    
    if (msgs.empty()) {
        return ret;
    }
    
    if (max_count == 0) {
        count = (int)msgs.size();
    } else {
        count = srs_min(max_count, (int)msgs.size());
    }

    if (count <= 0) {
        return ret;
    }
    
    pmsgs = new SrsSharedPtrMessage*[count];
    
    for (int i = 0; i < count; i++) {
        pmsgs[i] = msgs[i];
    }
    
    SrsSharedPtrMessage* last = msgs[count - 1];
    av_start_time = last->header.timestamp;
    
    if (count == (int)msgs.size()) {
        msgs.clear();
    } else {
        msgs.erase(msgs.begin(), msgs.begin() + count);
    }
    
    return ret;
185 186
}
winlin authored
187
void SrsMessageQueue::shrink()
188
{
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    int iframe_index = -1;
    
    // issue the first iframe.
    // skip the first frame, whatever the type of it,
    // for when we shrinked, the first is the iframe,
    // we will directly remove the gop next time.
    for (int i = 1; i < (int)msgs.size(); i++) {
        SrsSharedPtrMessage* msg = msgs[i];
        
        if (msg->header.is_video()) {
            if (SrsCodec::video_is_keyframe(msg->payload, msg->size)) {
                // the max frame index to remove.
                iframe_index = i;
                
                // set the start time, we will remove until this frame.
                av_start_time = msg->header.timestamp;
                
                break;
            }
        }
    }
    
    // no iframe, clear the queue.
    if (iframe_index < 0) {
        clear();
        return;
    }
    
    srs_trace("shrink the cache queue, size=%d, removed=%d, max=%.2f", 
        (int)msgs.size(), iframe_index, queue_size_ms / 1000.0);
    
    // remove the first gop from the front
    for (int i = 0; i < iframe_index; i++) {
        SrsSharedPtrMessage* msg = msgs[i];
        srs_freep(msg);
    }
    msgs.erase(msgs.begin(), msgs.begin() + iframe_index);
226 227
}
winlin authored
228
void SrsMessageQueue::clear()
229
{
230
    std::vector<SrsSharedPtrMessage*>::iterator it;
winlin authored
231
232 233 234 235
    for (it = msgs.begin(); it != msgs.end(); ++it) {
        SrsSharedPtrMessage* msg = *it;
        srs_freep(msg);
    }
winlin authored
236
237 238 239
    msgs.clear();
    
    av_start_time = av_end_time = -1;
winlin authored
240 241 242 243
}

SrsConsumer::SrsConsumer(SrsSource* _source)
{
244 245 246 247
    source = _source;
    paused = false;
    jitter = new SrsRtmpJitter();
    queue = new SrsMessageQueue();
winlin authored
248 249 250 251
}

SrsConsumer::~SrsConsumer()
{
252 253 254
    source->on_consumer_destroy(this);
    srs_freep(jitter);
    srs_freep(queue);
winlin authored
255 256 257 258
}

void SrsConsumer::set_queue_size(double queue_size)
{
259
    queue->set_queue_size(queue_size);
winlin authored
260 261 262 263
}

int SrsConsumer::get_time()
{
264
    return jitter->get_time();
winlin authored
265 266 267 268
}

int SrsConsumer::enqueue(SrsSharedPtrMessage* msg, int tba, int tbv)
{
269 270
    int ret = ERROR_SUCCESS;
    
271 272 273 274 275
    if (!source->is_atc()) {
        if ((ret = jitter->correct(msg, tba, tbv)) != ERROR_SUCCESS) {
            srs_freep(msg);
            return ret;
        }
276 277 278 279 280 281 282
    }
    
    if ((ret = queue->enqueue(msg)) != ERROR_SUCCESS) {
        return ret;
    }
    
    return ret;
winlin authored
283 284 285 286
}

int SrsConsumer::get_packets(int max_count, SrsSharedPtrMessage**& pmsgs, int& count)
{
287 288 289 290 291 292
    // paused, return nothing.
    if (paused) {
        return ERROR_SUCCESS;
    }
    
    return queue->get_packets(max_count, pmsgs, count);
winlin authored
293 294 295 296
}

int SrsConsumer::on_play_client_pause(bool is_pause)
{
297 298 299 300 301 302
    int ret = ERROR_SUCCESS;
    
    srs_trace("stream consumer change pause state %d=>%d", paused, is_pause);
    paused = is_pause;
    
    return ret;
303 304 305 306
}

SrsGopCache::SrsGopCache()
{
307 308
    cached_video_count = 0;
    enable_gop_cache = true;
309 310 311 312
}

SrsGopCache::~SrsGopCache()
{
313
    clear();
314 315 316 317
}

void SrsGopCache::set(bool enabled)
{
318 319 320 321 322 323 324 325 326
    enable_gop_cache = enabled;
    
    if (!enabled) {
        srs_info("disable gop cache, clear %d packets.", (int)gop_cache.size());
        clear();
        return;
    }
    
    srs_info("enable gop cache");
327 328 329 330
}

int SrsGopCache::cache(SrsSharedPtrMessage* msg)
{
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    int ret = ERROR_SUCCESS;
    
    if (!enable_gop_cache) {
        srs_verbose("gop cache is disabled.");
        return ret;
    }
    
    // got video, update the video count if acceptable
    if (msg->header.is_video()) {
        cached_video_count++;
    }
    
    // no acceptable video or pure audio, disable the cache.
    if (cached_video_count == 0) {
        srs_verbose("ignore any frame util got a h264 video frame.");
        return ret;
    }
    
    // clear gop cache when got key frame
    if (msg->header.is_video() && SrsCodec::video_is_keyframe(msg->payload, msg->size)) {
        srs_info("clear gop cache when got keyframe. vcount=%d, count=%d",
            cached_video_count, (int)gop_cache.size());
            
        clear();
        
        // curent msg is video frame, so we set to 1.
        cached_video_count = 1;
    }
    
    // cache the frame.
    gop_cache.push_back(msg->copy());
    
    return ret;
364 365 366 367
}

void SrsGopCache::clear()
{
368 369 370 371 372 373
    std::vector<SrsSharedPtrMessage*>::iterator it;
    for (it = gop_cache.begin(); it != gop_cache.end(); ++it) {
        SrsSharedPtrMessage* msg = *it;
        srs_freep(msg);
    }
    gop_cache.clear();
374
375
    cached_video_count = 0;
376
}
377
    
378 379
int SrsGopCache::dump(SrsConsumer* consumer, int tba, int tbv)
{
380 381 382 383 384 385 386 387 388 389 390 391 392
    int ret = ERROR_SUCCESS;
    
    std::vector<SrsSharedPtrMessage*>::iterator it;
    for (it = gop_cache.begin(); it != gop_cache.end(); ++it) {
        SrsSharedPtrMessage* msg = *it;
        if ((ret = consumer->enqueue(msg->copy(), tba, tbv)) != ERROR_SUCCESS) {
            srs_error("dispatch cached gop failed. ret=%d", ret);
            return ret;
        }
    }
    srs_trace("dispatch cached gop success. count=%d, duration=%d", (int)gop_cache.size(), consumer->get_time());
    
    return ret;
393 394
}
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
bool SrsGopCache::empty()
{
    return gop_cache.empty();
}

int64_t SrsGopCache::get_start_time()
{
    if (empty()) {
        return 0;
    }
    
    SrsSharedPtrMessage* msg = gop_cache[0];
    srs_assert(msg);
    
    return msg->header.timestamp;
}
412 413
std::map<std::string, SrsSource*> SrsSource::pool;
winlin authored
414
SrsSource* SrsSource::find(SrsRequest* req)
415
{
416 417 418 419 420 421 422 423 424
    string stream_url = req->get_stream_url();
    string vhost = req->vhost;
    
    if (pool.find(stream_url) == pool.end()) {
        pool[stream_url] = new SrsSource(req);
        srs_verbose("create new source for url=%s, vhost=%s", stream_url.c_str(), vhost.c_str());
    }
    
    return pool[stream_url];
425 426
}
winlin authored
427
SrsSource::SrsSource(SrsRequest* _req)
428
{
429 430
    req = _req->copy();
    
431
#ifdef SRS_HLS
432
    hls = new SrsHls(this);
433 434
#endif
#ifdef SRS_FFMPEG
435
    encoder = new SrsEncoder();
436
#endif
437 438 439 440 441 442 443 444 445
    
    cache_metadata = cache_sh_video = cache_sh_audio = NULL;
    
    frame_rate = sample_rate = 0;
    _can_publish = true;
    
    gop_cache = new SrsGopCache();
    
    _srs_config->subscribe(this);
446
    atc = _srs_config->get_atc(req->vhost);
447 448 449 450
}

SrsSource::~SrsSource()
{
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    _srs_config->unsubscribe(this);
    
    if (true) {
        std::vector<SrsConsumer*>::iterator it;
        for (it = consumers.begin(); it != consumers.end(); ++it) {
            SrsConsumer* consumer = *it;
            srs_freep(consumer);
        }
        consumers.clear();
    }

    if (true) {
        std::vector<SrsForwarder*>::iterator it;
        for (it = forwarders.begin(); it != forwarders.end(); ++it) {
            SrsForwarder* forwarder = *it;
            srs_freep(forwarder);
        }
        forwarders.clear();
    }
    
    srs_freep(cache_metadata);
    srs_freep(cache_sh_video);
    srs_freep(cache_sh_audio);
    
    srs_freep(gop_cache);
    
477
#ifdef SRS_HLS
478
    srs_freep(hls);
479 480
#endif
#ifdef SRS_FFMPEG
481
    srs_freep(encoder);
482
#endif
winlin authored
483
484
    srs_freep(req);
485 486
}
winlin authored
487
int SrsSource::on_reload_gop_cache(string vhost)
winlin authored
488
{
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    int ret = ERROR_SUCCESS;
    
    if (req->vhost != vhost) {
        return ret;
    }
    
    // gop cache changed.
    bool enabled_cache = _srs_config->get_gop_cache(vhost);
    
    srs_trace("vhost %s gop_cache changed to %d, source url=%s", 
        vhost.c_str(), enabled_cache, req->get_stream_url().c_str());
    
    set_cache(enabled_cache);
    
    return ret;
winlin authored
504 505
}
winlin authored
506 507
int SrsSource::on_reload_queue_length(string vhost)
{
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    int ret = ERROR_SUCCESS;
    
    if (req->vhost != vhost) {
        return ret;
    }

    double queue_size = _srs_config->get_queue_length(req->vhost);
    
    if (true) {
        std::vector<SrsConsumer*>::iterator it;
        
        for (it = consumers.begin(); it != consumers.end(); ++it) {
            SrsConsumer* consumer = *it;
            consumer->set_queue_size(queue_size);
        }

        srs_trace("consumers reload queue size success.");
    }
    
    if (true) {
        std::vector<SrsForwarder*>::iterator it;
        
        for (it = forwarders.begin(); it != forwarders.end(); ++it) {
            SrsForwarder* forwarder = *it;
            forwarder->set_queue_size(queue_size);
        }

        srs_trace("forwarders reload queue size success.");
    }
    
    return ret;
winlin authored
539 540
}
winlin authored
541 542
int SrsSource::on_reload_forward(string vhost)
{
543 544 545 546 547
    int ret = ERROR_SUCCESS;
    
    if (req->vhost != vhost) {
        return ret;
    }
winlin authored
548
549 550 551 552 553 554
    // forwarders
    destroy_forwarders();
    if ((ret = create_forwarders()) != ERROR_SUCCESS) {
        srs_error("create forwarders failed. ret=%d", ret);
        return ret;
    }
555
556 557 558
    srs_trace("vhost %s forwarders reload success", vhost.c_str());
    
    return ret;
winlin authored
559 560
}
561 562
int SrsSource::on_reload_hls(string vhost)
{
563 564 565 566 567 568
    int ret = ERROR_SUCCESS;
    
    if (req->vhost != vhost) {
        return ret;
    }
    
569
#ifdef SRS_HLS
570 571 572 573 574 575
    hls->on_unpublish();
    if ((ret = hls->on_publish(req)) != ERROR_SUCCESS) {
        srs_error("hls publish failed. ret=%d", ret);
        return ret;
    }
    srs_trace("vhost %s hls reload success", vhost.c_str());
576
#endif
577 578
    
    return ret;
579 580 581 582
}

int SrsSource::on_reload_transcode(string vhost)
{
583 584 585 586 587 588
    int ret = ERROR_SUCCESS;
    
    if (req->vhost != vhost) {
        return ret;
    }
    
589
#ifdef SRS_FFMPEG
590 591 592 593 594 595
    encoder->on_unpublish();
    if ((ret = encoder->on_publish(req)) != ERROR_SUCCESS) {
        srs_error("start encoder failed. ret=%d", ret);
        return ret;
    }
    srs_trace("vhost %s transcode reload success", vhost.c_str());
596
#endif
597 598
    
    return ret;
599 600
}
601 602
int SrsSource::on_forwarder_start(SrsForwarder* forwarder)
{
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    int ret = ERROR_SUCCESS;
        
    // feed the forwarder the metadata/sequence header,
    // when reload to enable the forwarder.
    if (cache_metadata && (ret = forwarder->on_meta_data(cache_metadata->copy())) != ERROR_SUCCESS) {
        srs_error("forwarder process onMetaData message failed. ret=%d", ret);
        return ret;
    }
    if (cache_sh_video && (ret = forwarder->on_video(cache_sh_video->copy())) != ERROR_SUCCESS) {
        srs_error("forwarder process video sequence header message failed. ret=%d", ret);
        return ret;
    }
    if (cache_sh_audio && (ret = forwarder->on_audio(cache_sh_audio->copy())) != ERROR_SUCCESS) {
        srs_error("forwarder process audio sequence header message failed. ret=%d", ret);
        return ret;
    }
    
    return ret;
621 622
}
623 624
int SrsSource::on_hls_start()
{
625 626
    int ret = ERROR_SUCCESS;
    
627
#ifdef SRS_HLS
628 629 630 631 632 633 634 635 636 637 638 639 640
        
    // feed the hls the metadata/sequence header,
    // when reload to enable the hls.
    // TODO: maybe need to decode the metadata?
    if (cache_sh_video && (ret = hls->on_video(cache_sh_video->copy())) != ERROR_SUCCESS) {
        srs_error("hls process video sequence header message failed. ret=%d", ret);
        return ret;
    }
    if (cache_sh_audio && (ret = hls->on_audio(cache_sh_audio->copy())) != ERROR_SUCCESS) {
        srs_error("hls process audio sequence header message failed. ret=%d", ret);
        return ret;
    }
    
641
#endif
642 643
    
    return ret;
644 645
}
646 647
bool SrsSource::can_publish()
{
648
    return _can_publish;
649 650 651 652
}

int SrsSource::on_meta_data(SrsCommonMessage* msg, SrsOnMetaDataPacket* metadata)
{
653 654
    int ret = ERROR_SUCCESS;
    
655
#ifdef SRS_HLS
656 657 658 659
    if (metadata && (ret = hls->on_meta_data(metadata->metadata)) != ERROR_SUCCESS) {
        srs_error("hls process onMetaData message failed. ret=%d", ret);
        return ret;
    }
660
#endif
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    
    metadata->metadata->set("server", SrsAmf0Any::str(RTMP_SIG_SRS_KEY" "RTMP_SIG_SRS_VERSION" ("RTMP_SIG_SRS_URL_SHORT")"));
    metadata->metadata->set("contributor", SrsAmf0Any::str(RTMP_SIG_SRS_PRIMARY_AUTHROS));
    
    SrsAmf0Any* prop = NULL;
    if ((prop = metadata->metadata->get_property("audiosamplerate")) != NULL) {
        if (prop->is_number()) {
            sample_rate = (int)prop->to_number();
        }
    }
    if ((prop = metadata->metadata->get_property("framerate")) != NULL) {
        if (prop->is_number()) {
            frame_rate = (int)prop->to_number();
        }
    }
    
    // encode the metadata to payload
    int size = metadata->get_payload_length();
    if (size <= 0) {
        srs_warn("ignore the invalid metadata. size=%d", size);
        return ret;
    }
    srs_verbose("get metadata size success.");
    
    char* payload = NULL;
    if ((ret = metadata->encode(size, payload)) != ERROR_SUCCESS) {
        srs_error("encode metadata error. ret=%d", ret);
        srs_freepa(payload);
        return ret;
    }
    srs_verbose("encode metadata success.");
    
    // create a shared ptr message.
    srs_freep(cache_metadata);
    cache_metadata = new SrsSharedPtrMessage();
    
    // dump message to shared ptr message.
    if ((ret = cache_metadata->initialize(&msg->header, payload, size)) != ERROR_SUCCESS) {
        srs_error("initialize the cache metadata failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("initialize shared ptr metadata success.");
    
    // copy to all consumer
    if (true) {
        std::vector<SrsConsumer*>::iterator it;
        for (it = consumers.begin(); it != consumers.end(); ++it) {
            SrsConsumer* consumer = *it;
            if ((ret = consumer->enqueue(cache_metadata->copy(), sample_rate, frame_rate)) != ERROR_SUCCESS) {
                srs_error("dispatch the metadata failed. ret=%d", ret);
                return ret;
            }
        }
        srs_trace("dispatch metadata success.");
    }
    
    // copy to all forwarders
    if (true) {
        std::vector<SrsForwarder*>::iterator it;
        for (it = forwarders.begin(); it != forwarders.end(); ++it) {
            SrsForwarder* forwarder = *it;
            if ((ret = forwarder->on_meta_data(cache_metadata->copy())) != ERROR_SUCCESS) {
                srs_error("forwarder process onMetaData message failed. ret=%d", ret);
                return ret;
            }
        }
    }
    
    return ret;
730 731 732 733
}

int SrsSource::on_audio(SrsCommonMessage* audio)
{
734 735 736 737 738 739 740 741 742 743
    int ret = ERROR_SUCCESS;
    
    SrsSharedPtrMessage* msg = new SrsSharedPtrMessage();
    SrsAutoFree(SrsSharedPtrMessage, msg, false);
    if ((ret = msg->initialize(audio)) != ERROR_SUCCESS) {
        srs_error("initialize the audio failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("initialize shared ptr audio success.");
    
744
#ifdef SRS_HLS
745 746 747 748 749 750 751 752 753
    if ((ret = hls->on_audio(msg->copy())) != ERROR_SUCCESS) {
        srs_warn("hls process audio message failed, ignore and disable hls. ret=%d", ret);
        
        // unpublish, ignore ret.
        hls->on_unpublish();
        
        // ignore.
        ret = ERROR_SUCCESS;
    }
754
#endif
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
    
    // copy to all consumer
    if (true) {
        std::vector<SrsConsumer*>::iterator it;
        for (it = consumers.begin(); it != consumers.end(); ++it) {
            SrsConsumer* consumer = *it;
            if ((ret = consumer->enqueue(msg->copy(), sample_rate, frame_rate)) != ERROR_SUCCESS) {
                srs_error("dispatch the audio failed. ret=%d", ret);
                return ret;
            }
        }
        srs_info("dispatch audio success.");
    }

    // copy to all forwarders.
    if (true) {
        std::vector<SrsForwarder*>::iterator it;
        for (it = forwarders.begin(); it != forwarders.end(); ++it) {
            SrsForwarder* forwarder = *it;
            if ((ret = forwarder->on_audio(msg->copy())) != ERROR_SUCCESS) {
                srs_error("forwarder process audio message failed. ret=%d", ret);
                return ret;
            }
        }
    }

    // cache the sequence header if h264
    if (SrsCodec::audio_is_sequence_header(msg->payload, msg->size)) {
        srs_freep(cache_sh_audio);
        cache_sh_audio = msg->copy();
        srs_trace("update audio sequence header success. size=%d", msg->header.payload_length);
        return ret;
    }
    
    // cache the last gop packets
    if ((ret = gop_cache->cache(msg)) != ERROR_SUCCESS) {
        srs_error("shrink gop cache failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("cache gop success.");
    
796 797 798 799 800 801 802 803 804 805
    // if atc, update the sequence header to abs time.
    if (atc) {
        if (cache_sh_audio) {
            cache_sh_audio->header.timestamp = msg->header.timestamp;
        }
        if (cache_metadata) {
            cache_metadata->header.timestamp = msg->header.timestamp;
        }
    }
    
806
    return ret;
807 808 809 810
}

int SrsSource::on_video(SrsCommonMessage* video)
{
811 812 813 814 815 816 817 818 819 820
    int ret = ERROR_SUCCESS;
    
    SrsSharedPtrMessage* msg = new SrsSharedPtrMessage();
    SrsAutoFree(SrsSharedPtrMessage, msg, false);
    if ((ret = msg->initialize(video)) != ERROR_SUCCESS) {
        srs_error("initialize the video failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("initialize shared ptr video success.");
    
821
#ifdef SRS_HLS
822 823 824 825 826 827 828 829 830
    if ((ret = hls->on_video(msg->copy())) != ERROR_SUCCESS) {
        srs_warn("hls process video message failed, ignore and disable hls. ret=%d", ret);
        
        // unpublish, ignore ret.
        hls->on_unpublish();
        
        // ignore.
        ret = ERROR_SUCCESS;
    }
831
#endif
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
    
    // copy to all consumer
    if (true) {
        std::vector<SrsConsumer*>::iterator it;
        for (it = consumers.begin(); it != consumers.end(); ++it) {
            SrsConsumer* consumer = *it;
            if ((ret = consumer->enqueue(msg->copy(), sample_rate, frame_rate)) != ERROR_SUCCESS) {
                srs_error("dispatch the video failed. ret=%d", ret);
                return ret;
            }
        }
        srs_info("dispatch video success.");
    }

    // copy to all forwarders.
    if (true) {
        std::vector<SrsForwarder*>::iterator it;
        for (it = forwarders.begin(); it != forwarders.end(); ++it) {
            SrsForwarder* forwarder = *it;
            if ((ret = forwarder->on_video(msg->copy())) != ERROR_SUCCESS) {
                srs_error("forwarder process video message failed. ret=%d", ret);
                return ret;
            }
        }
    }

    // cache the sequence header if h264
    if (SrsCodec::video_is_sequence_header(msg->payload, msg->size)) {
        srs_freep(cache_sh_video);
        cache_sh_video = msg->copy();
        srs_trace("update video sequence header success. size=%d", msg->header.payload_length);
        return ret;
    }

    // cache the last gop packets
    if ((ret = gop_cache->cache(msg)) != ERROR_SUCCESS) {
        srs_error("gop cache msg failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("cache gop success.");
    
873 874 875 876 877 878 879 880 881 882
    // if atc, update the sequence header to abs time.
    if (atc) {
        if (cache_sh_video) {
            cache_sh_video->header.timestamp = msg->header.timestamp;
        }
        if (cache_metadata) {
            cache_metadata->header.timestamp = msg->header.timestamp;
        }
    }
    
883
    return ret;
884 885
}
winlin authored
886
int SrsSource::on_publish(SrsRequest* _req)
887
{
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    int ret = ERROR_SUCCESS;
    
    // update the request object.
    srs_freep(req);
    req = _req->copy();
    srs_assert(req);
    
    _can_publish = false;
    
    // create forwarders
    if ((ret = create_forwarders()) != ERROR_SUCCESS) {
        srs_error("create forwarders failed. ret=%d", ret);
        return ret;
    }
    
903
#ifdef SRS_FFMPEG
904 905 906 907
    if ((ret = encoder->on_publish(req)) != ERROR_SUCCESS) {
        srs_error("start encoder failed. ret=%d", ret);
        return ret;
    }
908
#endif
909
    
910
#ifdef SRS_HLS
911 912 913 914
    if ((ret = hls->on_publish(req)) != ERROR_SUCCESS) {
        srs_error("start hls failed. ret=%d", ret);
        return ret;
    }
915 916
#endif
917
    return ret;
918 919 920 921
}

void SrsSource::on_unpublish()
{
922 923
    // destroy all forwarders
    destroy_forwarders();
924 925

#ifdef SRS_FFMPEG
926
    encoder->on_unpublish();
927 928
#endif
929
    // TODO: HLS should continue previous sequence and stream.
930
#ifdef SRS_HLS
931
    hls->on_unpublish();
932 933
#endif
934
    gop_cache->clear();
935
936 937 938 939 940 941 942 943 944
    srs_freep(cache_metadata);
    frame_rate = sample_rate = 0;
    
    srs_freep(cache_sh_video);
    srs_freep(cache_sh_audio);
    
    srs_trace("clear cache/metadata/sequence-headers when unpublish.");
    
    _can_publish = true;
945 946 947 948
}

 int SrsSource::create_consumer(SrsConsumer*& consumer)
{
949 950 951 952 953 954 955 956 957 958 959 960 961 962
    int ret = ERROR_SUCCESS;
    
    consumer = new SrsConsumer(this);
    consumers.push_back(consumer);
    
    double queue_size = _srs_config->get_queue_length(req->vhost);
    consumer->set_queue_size(queue_size);

    if (cache_metadata && (ret = consumer->enqueue(cache_metadata->copy(), sample_rate, frame_rate)) != ERROR_SUCCESS) {
        srs_error("dispatch metadata failed. ret=%d", ret);
        return ret;
    }
    srs_info("dispatch metadata success");
    
963 964 965 966 967 968 969 970 971 972 973
    // if atc, update the sequence header to gop cache time.
    if (atc && !gop_cache->empty()) {
        if (cache_sh_video) {
            cache_sh_video->header.timestamp = gop_cache->get_start_time();
        }
        if (cache_sh_audio) {
            cache_sh_audio->header.timestamp = gop_cache->get_start_time();
        }
    }
    
    // copy sequence header
974 975 976 977 978 979 980 981 982 983 984 985
    if (cache_sh_video && (ret = consumer->enqueue(cache_sh_video->copy(), sample_rate, frame_rate)) != ERROR_SUCCESS) {
        srs_error("dispatch video sequence header failed. ret=%d", ret);
        return ret;
    }
    srs_info("dispatch video sequence header success");
    
    if (cache_sh_audio && (ret = consumer->enqueue(cache_sh_audio->copy(), sample_rate, frame_rate)) != ERROR_SUCCESS) {
        srs_error("dispatch audio sequence header failed. ret=%d", ret);
        return ret;
    }
    srs_info("dispatch audio sequence header success");
    
986
    // copy gop cache to client.
987 988 989 990 991 992 993
    if ((ret = gop_cache->dump(consumer, sample_rate, frame_rate)) != ERROR_SUCCESS) {
        return ret;
    }
    
    srs_trace("create consumer, queue_size=%.2f, tba=%d, tbv=%d", queue_size, sample_rate, frame_rate);
    
    return ret;
994 995 996 997
}

void SrsSource::on_consumer_destroy(SrsConsumer* consumer)
{
998 999 1000 1001 1002 1003
    std::vector<SrsConsumer*>::iterator it;
    it = std::find(consumers.begin(), consumers.end(), consumer);
    if (it != consumers.end()) {
        consumers.erase(it);
    }
    srs_info("handle consumer destroy success.");
1004 1005 1006 1007
}

void SrsSource::set_cache(bool enabled)
{
1008
    gop_cache->set(enabled);
1009 1010
}
1011 1012 1013 1014 1015
bool SrsSource::is_atc()
{
    return atc;
}
winlin authored
1016 1017
int SrsSource::create_forwarders()
{
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
    int ret = ERROR_SUCCESS;
    
    SrsConfDirective* conf = _srs_config->get_forward(req->vhost);
    for (int i = 0; conf && i < (int)conf->args.size(); i++) {
        std::string forward_server = conf->args.at(i);
        
        SrsForwarder* forwarder = new SrsForwarder(this);
        forwarders.push_back(forwarder);
    
        double queue_size = _srs_config->get_queue_length(req->vhost);
        forwarder->set_queue_size(queue_size);
        
        if ((ret = forwarder->on_publish(req, forward_server)) != ERROR_SUCCESS) {
            srs_error("start forwarder failed. "
                "vhost=%s, app=%s, stream=%s, forward-to=%s",
                req->vhost.c_str(), req->app.c_str(), req->stream.c_str(),
                forward_server.c_str());
            return ret;
        }
    }

    return ret;
winlin authored
1040 1041 1042 1043
}

void SrsSource::destroy_forwarders()
{
1044 1045 1046 1047 1048 1049 1050
    std::vector<SrsForwarder*>::iterator it;
    for (it = forwarders.begin(); it != forwarders.end(); ++it) {
        SrsForwarder* forwarder = *it;
        forwarder->on_unpublish();
        srs_freep(forwarder);
    }
    forwarders.clear();
winlin authored
1051 1052
}