void re_update(int64_t re, int32_t starttime, u_int32_t time) {
    // send by pulse algorithm.
    int64_t now = srs_utils_time_ms();
    int64_t diff = time - starttime - (now - re);
    if (diff > RE_PULSE_MS) {
        usleep(diff * 1000);
    }
}
void re_cleanup(int64_t re, int32_t starttime, u_int32_t time) {
    // for the last pulse, always sleep.
    // for the virtual live encoder long time publishing.
    int64_t now = srs_utils_time_ms();
    int64_t diff = time - starttime - (now - re);
    if (diff > 0) {
        srs_human_trace("re_cleanup, diff=%d, start=%d, last=%d ms",
                        (int) diff, starttime, time);
        usleep(diff * 1000);
    }
}
int64_t re_create() {
    // if not very precise, we can directly use this as re.
    int64_t re = srs_utils_time_ms();

    // use the starttime to get the deviation
    int64_t deviation = re - tools_main_entrance_startup_time;
    srs_human_trace("deviation is %d ms, pulse is %d ms", (int) (deviation), (int) (RE_PULSE_MS));

    // so, we adjust time to max(0, deviation)
    // because the last pulse, we already sleeped
    int adjust = (int) (deviation);
    if (adjust > 0) {
        srs_human_trace("adjust re time for %d ms", adjust);
        re -= adjust;
    } else {
        srs_human_trace("no need to adjust re time");
    }

    return re;
}
int main(int argc, char **argv) {
    int ret = 0;

    // main function
    tools_main_entrance_startup_time = srs_utils_time_ms();

    // user option parse index.
    int opt = 0;
    // user options.
    char *in_flv_file = NULL;
    char *out_rtmp_url = NULL;
    // rtmp handler
    srs_rtmp_t ortmp;
    // flv handler
    srs_flv_t flv;

    printf("ingest flv file and publish to RTMP server like FFMPEG.\n");
    printf("srs(simple-rtmp-server) client librtmp library.\n");
    printf("version: %d.%d.%d\n", srs_version_major(), srs_version_minor(), srs_version_revision());

    if (argc <= 2) {
        printf("ingest flv file and publish to RTMP server\n"
                       "Usage: %s <-i in_flv_file> <-y out_rtmp_url>\n"
                       "   in_flv_file     input flv file, ingest from this file.\n"
                       "   out_rtmp_url    output rtmp url, publish to this url.\n"
                       "For example:\n"
                       "   %s -i doc/source.200kbps.768x320.flv -y rtmp://127.0.0.1/live/livestream\n"
                       "   %s -i ../../doc/source.200kbps.768x320.flv -y rtmp://127.0.0.1/live/livestream\n",
               argv[0], argv[0], argv[0]);
        exit(-1);
    }

    for (opt = 0; opt < argc; opt++) {
        srs_human_trace("argv[%d]=%s", opt, argv[opt]);
    }

    // fill the options for mac
    for (opt = 0; opt < argc - 1; opt++) {
        // ignore all options except -i and -y.
        char *p = argv[opt];

        // only accept -x
        if (p[0] != '-' || p[1] == 0 || p[2] != 0) {
            continue;
        }

        // parse according the option name.
        switch (p[1]) {
            case 'i':
                in_flv_file = argv[opt + 1];
                break;
            case 'y':
                out_rtmp_url = argv[opt + 1];
                break;
            default:
                break;
        }
    }

    if (!in_flv_file) {
        srs_human_trace("input invalid, use -i <input>");
        return -1;
    }
    if (!out_rtmp_url) {
        srs_human_trace("output invalid, use -y <output>");
        return -1;
    }

    srs_human_trace("input:  %s", in_flv_file);
    srs_human_trace("output: %s", out_rtmp_url);

    if ((flv = srs_flv_open_read(in_flv_file)) == NULL) {
        ret = 2;
        srs_human_trace("open flv file failed. ret=%d", ret);
        return ret;
    }

    ortmp = srs_rtmp_create(out_rtmp_url);

    ret = proxy(flv, ortmp);
    srs_human_trace("ingest flv to RTMP completed");

    srs_rtmp_destroy(ortmp);
    srs_flv_close(flv);

    return ret;
}
int main(int argc, char **argv) {
    int ret = 0;
    srs_rtmp_t rtmp;

    // time
    int64_t time_startup = srs_utils_time_ms();
    int64_t time_dns_resolve = 0;
    int64_t time_socket_connect = 0;
    int64_t time_play_stream = 0;
    int64_t time_first_packet = 0;
    int64_t time_cleanup = 0;
    // delay = actual - expect time when quit.
    int delay = 0;
    // bytes
    int64_t bytes_nsend = 0;
    int time_duration = 0;
    int64_t bytes_nrecv = 0;

    // packet data
    int size;
    char type;
    char *data;
    u_int32_t timestamp;
    u_int32_t basetime = 0;

    // user options
    const char *rtmp_url = NULL;
    int duration = 0;
    int timeout = 0;

    printf("detect rtmp stream\n");
    printf("srs(simple-rtmp-server) client librtmp library.\n");
    printf("version: %d.%d.%d\n", srs_version_major(), srs_version_minor(), srs_version_revision());

    if (argc <= 3) {
        printf("detect stream on RTMP server, print result to stderr.\n"
                       "Usage: %s <rtmp_url> <duration> <timeout>\n"
                       "   rtmp_url     RTMP stream url to play\n"
                       "   duration     how long to play, in seconds, stream time.\n"
                       "   timeout      how long to timeout, in seconds, system time.\n"
                       "For example:\n"
                       "   %s rtmp://127.0.0.1:1935/live/livestream 3 10\n",
               argv[0], argv[0]);
        exit(-1);
    }

    rtmp_url = argv[1];
    duration = atoi(argv[2]);
    timeout = atoi(argv[3]);

    srs_human_trace("rtmp url: %s", rtmp_url);
    srs_human_trace("duration: %ds, timeout:%ds", duration, timeout);

    if (duration <= 0 || timeout <= 0) {
        srs_human_trace("duration and timeout must be positive.");
        exit(-2);
    }

    rtmp = srs_rtmp_create(rtmp_url);

    if ((ret = __srs_rtmp_dns_resolve(rtmp)) != 0) {
        srs_human_trace("dns resolve failed. ret=%d", ret);
        goto rtmp_destroy;
    }
    srs_human_trace("dns resolve success");
    time_dns_resolve = srs_utils_time_ms();

    if ((ret = __srs_rtmp_connect_server(rtmp)) != 0) {
        srs_human_trace("socket connect failed. ret=%d", ret);
        goto rtmp_destroy;
    }
    srs_human_trace("socket connect success");
    time_socket_connect = srs_utils_time_ms();

    if ((ret = __srs_rtmp_do_simple_handshake(rtmp)) != 0) {
        srs_human_trace("do simple handshake failed. ret=%d", ret);
        goto rtmp_destroy;
    }
    srs_human_trace("do simple handshake success");

    if ((ret = srs_rtmp_connect_app(rtmp)) != 0) {
        srs_human_trace("connect vhost/app failed. ret=%d", ret);
        goto rtmp_destroy;
    }
    srs_human_trace("connect vhost/app success");

    if ((ret = srs_rtmp_play_stream(rtmp)) != 0) {
        srs_human_trace("play stream failed. ret=%d", ret);
        goto rtmp_destroy;
    }
    srs_human_trace("play stream success");
    time_play_stream = srs_utils_time_ms();

    for (; ;) {
        if ((ret = srs_rtmp_read_packet(rtmp, &type, &timestamp, &data, &size)) != 0) {
            srs_human_trace("read packet failed. ret=%d", ret);
            goto rtmp_destroy;
        }
        srs_human_trace("got packet: type=%s, time=%d, size=%d",
                        srs_human_flv_tag_type2string(type), timestamp, size);

        if (SRS_RTMP_TYPE_VIDEO == type || SRS_RTMP_TYPE_AUDIO == type) {
            if (time_first_packet <= 0) {
                time_first_packet = srs_utils_time_ms();
            }
            if (basetime <= 0) {
                basetime = timestamp;
            }
        }

        free(data);

        if (srs_utils_time_ms() - time_startup > timeout * 1000) {
            srs_human_trace("timeout, terminate.");
            goto rtmp_destroy;
        }

        if ((timestamp - basetime) > duration * 1000) {
            srs_human_trace("duration exceed, terminate.");
            goto rtmp_destroy;
        }
    }

    rtmp_destroy:
    bytes_nsend = srs_utils_send_bytes(rtmp);
    bytes_nrecv = srs_utils_recv_bytes(rtmp);

    srs_rtmp_destroy(rtmp);
    time_cleanup = srs_utils_time_ms();
    time_duration = (int) (time_cleanup - time_startup);

    // print result to stderr.
    fprintf(stderr, "{"
                    "\"%s\":%d, " //#0
                    "\"%s\":%d, " //#1
                    "\"%s\":%d, " // #2
                    "\"%s\":%d, " // #3
                    "\"%s\":%d, " // #4
                    "\"%s\":%d, " // #5
                    "\"%s\":%d, " // #6
                    "\"%s\":%d, " // #7
                    "\"%s\":%d, " // #8
                    "\"%s\":%d, " // #9
                    "\"%s\":%d, " // #10
                    "%s,%s,%s,%s}",
            "code", ret, //#0
            // total = dns + tcp_connect + start_play + first_packet + last_packet
            "total", time_duration, //#1
            "dns", (int) (time_dns_resolve - time_startup), //#2
            "tcp_connect", (int) (time_socket_connect - time_dns_resolve), //#3
            "start_play", (int) (time_play_stream - time_socket_connect), //#4
            "first_packet", (int) (time_first_packet - time_play_stream), //#5
            "last_packet", (int) (time_cleanup - time_first_packet), //#6
            "stream", (int) (timestamp - basetime), //#7
            // expect = time_cleanup - time_first_packet
            // actual = stream
            // delay = actual - expect
            "delay", (int) (timestamp - basetime - (time_cleanup - time_first_packet)), //#8
            "publish_kbps", (int) ((time_duration <= 0) ? 0 : (bytes_nsend * 8 / time_duration)), //#9
            "play_kbps", (int) ((time_duration <= 0) ? 0 : (bytes_nrecv * 8 / time_duration)), //#10
            // unit in ms.
            "\"unit\": \"ms\"",
            "\"remark0\": \"total = dns + tcp_connect + start_play + first_packet + last_packet\"",
            "\"remark1\": \"delay = stream - (time_cleanup - time_first_packet)\"",
            "\"remark2\": \"if code is not 0, user must ignore all data\""
    );

    srs_human_trace(" ");
    srs_human_trace("completed");

    return ret;
}
Exemple #6
0
void PushEngine::run(){
    while(1){
        int64_t currentTime = srs_utils_time_ms();
        
        if(currentTime - m_timeTick > 1000){
            m_timeTick = currentTime;
#if 0
            for(std::list<OneStream*>::iterator it = m_streamList.begin(); it != m_streamList.end(); it++){
                m_logger.information("==> current publish [rtmp://%s/live/%s%d] size[%d]", (*it)->ipPort, \
                            (*it)->prefixName, (*it)->randNum, (*it)->receiveSize/1000);
                (*it)->receiveSize = 0;
            }
#endif
        }
        
        if(m_jobQueue.size() > 0){
            OneStreamSharePtr node = m_jobQueue.get();
            if(node.get() != NULL){
                node->setExpiredTime(currentTime);
                node->m_sendIndex = 0;
                m_streamList.push_back(node);
            }
            
            std::string url = node->getURL();
            node->rtmp = srs_rtmp_create(url.c_str());
            m_logger.information("begin publish to [%s].", url);

            if (srs_rtmp_handshake(node->rtmp) != 0) {
                srs_rtmp_destroy(node->rtmp);       // 析构rtmp
                m_streamEventQueue.put(StreamEventSharePtr(new StreamEvent(node, currentTime, HANDSHAKE_FAIL)));    // 发送握手失败事件
                m_logger.error("simple handshake to [%s] failed.", url);
            }
                
            if (srs_rtmp_connect_app(node->rtmp) != 0) {
                srs_rtmp_destroy(node->rtmp);       // 析构rtmp
                m_streamEventQueue.put(StreamEventSharePtr(new StreamEvent(node, currentTime, CONNECT_FAIL)));      // 发送连接失败事件
                m_logger.error("connect [%s] vhost/app failed.", url);
                continue;
            }

            if (srs_rtmp_publish_stream(node->rtmp) != 0) {
                srs_rtmp_destroy(node->rtmp);       // 析构rtmp
                m_streamEventQueue.put(StreamEventSharePtr(new StreamEvent(node, currentTime, PUBLIC_FAIL)));       // 发送public失败事件
                m_logger.error("publish stream [%s] failed.", url);
                continue;
            }

            m_streamEventQueue.put(StreamEventSharePtr(new StreamEvent(node, currentTime, START_STREAM)));          // 发送开始推流事件
        }
        
        //  发送当前时间片的帧到所有链接
        for(std::list<OneStreamSharePtr>::iterator it = m_streamList.begin(); it != m_streamList.end(); ){
            bool endThisStream = false;
            if((*it)->m_sendIndex == 0 || (*it)->m_sendIndex + 1 > m_flvFrame.size()){
                (*it)->m_baseTimestamp = currentTime;
                (*it)->m_sendIndex = 0;
            }
            
            if(((*it)->m_baseTimestamp + m_flvFrame[(*it)->m_sendIndex].timestamp) <= currentTime){
                Frame f = m_flvFrame[((*it)->m_sendIndex)++];
                char* data = (char*)malloc(f.size);
                memcpy(data, f.data, f.size);
                if (srs_rtmp_write_packet((*it)->rtmp, f.type, ((*it)->m_baseTimestamp + f.timestamp) % 10000000, data, f.size) != 0) {
                    endThisStream = true;
                    m_streamEventQueue.put(StreamEventSharePtr(new StreamEvent((*it), currentTime, PUSH_STREAM_FAIL)));       // 发送推流失败事件
                    m_logger.error("error to publish [%s].", (*it)->getURL());                    
                }
                (*it)->addReceiveSize(f.size);
            }
            
            // 推流时间到
            if(currentTime > (*it)->getExpiredTime()){
                endThisStream = true;
                m_streamEventQueue.put(StreamEventSharePtr(new StreamEvent((*it), currentTime, END_STREAM)));            // 发送推流结束事件
                m_logger.information("stop to publish [%s].", (*it)->getURL());
            }
            
            if(endThisStream){
                srs_rtmp_destroy((*it)->rtmp);      // 析构rtmp
                it = m_streamList.erase(it);        // 从链表中删除
                continue;
            }
            else{
                it++;
            }
        }

        usleep(10 * 1000);
    }
}