Blame view

trunk/src/rtmp/srs_protocol_rtmp.cpp 47.3 KB
winlin authored
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

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_protocol_rtmp.hpp>
winlin authored
25
26
#include <srs_core_autofree.hpp>
27
#include <srs_protocol_io.hpp>
28
#include <srs_protocol_amf0.hpp>
29 30
#include <srs_protocol_handshake.hpp>
#include <srs_protocol_utility.hpp>
31
#include <srs_kernel_stream.hpp>
32
#include <srs_kernel_utility.hpp>
winlin authored
33
34 35
// for srs-librtmp, @see https://github.com/winlinvip/simple-rtmp-server/issues/213
#ifndef _WIN32
36
#include <unistd.h>
37 38
#endif
winlin authored
39 40 41 42 43
using namespace std;

/**
* the signature for packets to client.
*/
44 45 46
#define RTMP_SIG_FMS_VER                        "3,5,3,888"
#define RTMP_SIG_AMF0_VER                       0
#define RTMP_SIG_CLIENT_ID                      "ASAICiss"
winlin authored
47 48 49 50

/**
* onStatus consts.
*/
51 52 53 54 55
#define StatusLevel                             "level"
#define StatusCode                              "code"
#define StatusDescription                       "description"
#define StatusDetails                           "details"
#define StatusClientId                          "clientid"
winlin authored
56
// status value
57
#define StatusLevelStatus                       "status"
winlin authored
58
// status error
59
#define StatusLevelError                        "error"
winlin authored
60
// code value
61 62 63 64 65 66 67 68 69
#define StatusCodeConnectSuccess                "NetConnection.Connect.Success"
#define StatusCodeConnectRejected               "NetConnection.Connect.Rejected"
#define StatusCodeStreamReset                   "NetStream.Play.Reset"
#define StatusCodeStreamStart                   "NetStream.Play.Start"
#define StatusCodeStreamPause                   "NetStream.Pause.Notify"
#define StatusCodeStreamUnpause                 "NetStream.Unpause.Notify"
#define StatusCodePublishStart                  "NetStream.Publish.Start"
#define StatusCodeDataStart                     "NetStream.Data.Start"
#define StatusCodeUnpublishSuccess              "NetStream.Unpublish.Success"
winlin authored
70 71

// FMLE
72 73
#define RTMP_AMF0_COMMAND_ON_FC_PUBLISH         "onFCPublish"
#define RTMP_AMF0_COMMAND_ON_FC_UNPUBLISH       "onFCUnpublish"
winlin authored
74 75

// default stream id for response the createStream request.
76
#define SRS_DEFAULT_SID                         1
winlin authored
77 78 79

SrsRequest::SrsRequest()
{
80
    objectEncoding = RTMP_SIG_AMF0_VER;
81
    duration = -1;
82
    args = NULL;
winlin authored
83 84 85 86
}

SrsRequest::~SrsRequest()
{
87
    srs_freep(args);
winlin authored
88 89 90 91
}

SrsRequest* SrsRequest::copy()
{
92 93 94 95 96
    SrsRequest* cp = new SrsRequest();
    
    cp->app = app;
    cp->objectEncoding = objectEncoding;
    cp->pageUrl = pageUrl;
97
    cp->host = host;
98
    cp->port = port;
99
    cp->param = param;
100 101 102 103 104
    cp->schema = schema;
    cp->stream = stream;
    cp->swfUrl = swfUrl;
    cp->tcUrl = tcUrl;
    cp->vhost = vhost;
105
    cp->duration = duration;
106 107 108
    if (args) {
        cp->args = args->copy()->to_object();
    }
109 110
    
    return cp;
winlin authored
111 112
}
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
void SrsRequest::update_auth(SrsRequest* req)
{
    pageUrl = req->pageUrl;
    swfUrl = req->swfUrl;
    tcUrl = req->tcUrl;
    
    if (args) {
        srs_freep(args);
    }
    if (req->args) {
        args = req->args->copy()->to_object();
    }
    
    srs_info("update req of soruce for auth ok");
}
winlin authored
129 130
string SrsRequest::get_stream_url()
{
131 132 133 134 135 136 137 138 139
    std::string url = "";
    
    url += vhost;
    url += "/";
    url += app;
    url += "/";
    url += stream;

    return url;
winlin authored
140 141
}
142 143 144
void SrsRequest::strip()
{
    // remove the unsupported chars in names.
145
    host = srs_string_remove(host, "/ \n\r\t");
146 147 148 149 150 151 152 153 154 155 156 157 158
    vhost = srs_string_remove(vhost, "/ \n\r\t");
    app = srs_string_remove(app, " \n\r\t");
    stream = srs_string_remove(stream, " \n\r\t");
    
    // remove end slash of app/stream
    app = srs_string_trim_end(app, "/");
    stream = srs_string_trim_end(stream, "/");
    
    // remove start slash of app/stream
    app = srs_string_trim_start(app, "/");
    stream = srs_string_trim_start(stream, "/");
}
winlin authored
159 160
SrsResponse::SrsResponse()
{
161
    stream_id = SRS_DEFAULT_SID;
winlin authored
162 163 164 165 166 167
}

SrsResponse::~SrsResponse()
{
}
168
string srs_client_type_string(SrsRtmpConnType type)
169
{
170
    switch (type) {
171
        case SrsRtmpConnPlay: return "Play";
172 173
        case SrsRtmpConnFlashPublish: return "publish(FlashPublish)";
        case SrsRtmpConnFMLEPublish: return "publish(FMLEPublish)";
174 175
        default: return "Unknown";
    }
176 177
}
178 179 180 181 182 183 184
SrsHandshakeBytes::SrsHandshakeBytes() 
{
    c0c1 = s0s1s2 = c2 = NULL;
}

SrsHandshakeBytes::~SrsHandshakeBytes() 
{
185 186 187
    srs_freep(c0c1);
    srs_freep(s0s1s2);
    srs_freep(c2);
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
}

int SrsHandshakeBytes::read_c0c1(ISrsProtocolReaderWriter* io)
{
    int ret = ERROR_SUCCESS;
    
    if (c0c1) {
        return ret;
    }
    
    ssize_t nsize;
    
    c0c1 = new char[1537];
    if ((ret = io->read_fully(c0c1, 1537, &nsize)) != ERROR_SUCCESS) {
        srs_warn("read c0c1 failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("read c0c1 success.");
    
    return ret;
}

int SrsHandshakeBytes::read_s0s1s2(ISrsProtocolReaderWriter* io)
{
    int ret = ERROR_SUCCESS;
    
    if (s0s1s2) {
        return ret;
    }
    
    ssize_t nsize;
    
winlin authored
220
    s0s1s2 = new char[3073];
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    if ((ret = io->read_fully(s0s1s2, 3073, &nsize)) != ERROR_SUCCESS) {
        srs_warn("read s0s1s2 failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("read s0s1s2 success.");
    
    return ret;
}

int SrsHandshakeBytes::read_c2(ISrsProtocolReaderWriter* io)
{
    int ret = ERROR_SUCCESS;
    
    if (c2) {
        return ret;
    }
    
    ssize_t nsize;
    
    c2 = new char[1536];
    if ((ret = io->read_fully(c2, 1536, &nsize)) != ERROR_SUCCESS) {
        srs_warn("read c2 failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("read c2 success.");
    
    return ret;
}

int SrsHandshakeBytes::create_c0c1()
{
    int ret = ERROR_SUCCESS;
    
    if (c0c1) {
        return ret;
    }
    
    c0c1 = new char[1537];
    srs_random_generate(c0c1, 1537);
    
261
    // plain text required.
262 263 264 265 266
    static SrsStream stream;
    if ((ret = stream.initialize(c0c1, 9)) != ERROR_SUCCESS) {
        return ret;
    }
    stream.write_1bytes(0x03);
267
    stream.write_4bytes((int32_t)::time(NULL));
268
    stream.write_4bytes(0x00);
269
    
270 271 272
    return ret;
}
273
int SrsHandshakeBytes::create_s0s1s2(const char* c1)
274 275 276 277 278 279 280 281 282 283
{
    int ret = ERROR_SUCCESS;
    
    if (s0s1s2) {
        return ret;
    }
    
    s0s1s2 = new char[3073];
    srs_random_generate(s0s1s2, 3073);
    
284
    // plain text required.
285 286 287 288 289
    SrsStream stream;
    if ((ret = stream.initialize(s0s1s2, 9)) != ERROR_SUCCESS) {
        return ret;
    }
    stream.write_1bytes(0x03);
290
    stream.write_4bytes((int32_t)::time(NULL));
291 292
    // s2 time2 copy from c1
    if (c0c1) {
293
        stream.write_bytes(c0c1 + 1, 4);
294 295
    }
    
296 297 298 299 300 301
    // if c1 specified, copy c1 to s2.
    // @see: https://github.com/winlinvip/simple-rtmp-server/issues/46
    if (c1) {
        memcpy(s0s1s2 + 1537, c1, 1536);
    }
    
302 303 304 305 306 307 308 309 310 311 312 313 314 315
    return ret;
}

int SrsHandshakeBytes::create_c2()
{
    int ret = ERROR_SUCCESS;
    
    if (c2) {
        return ret;
    }
    
    c2 = new char[1536];
    srs_random_generate(c2, 1536);
    
316
    // time
317 318 319 320
    SrsStream stream;
    if ((ret = stream.initialize(c2, 8)) != ERROR_SUCCESS) {
        return ret;
    }
321
    stream.write_4bytes((int32_t)::time(NULL));
322 323
    // c2 time2 copy from s1
    if (s0s1s2) {
324
        stream.write_bytes(s0s1s2 + 1, 4);
325 326
    }
    
327 328 329
    return ret;
}
330
SrsRtmpClient::SrsRtmpClient(ISrsProtocolReaderWriter* skt)
winlin authored
331
{
332 333
    io = skt;
    protocol = new SrsProtocol(skt);
334
    hs_bytes = new SrsHandshakeBytes();
winlin authored
335 336 337 338
}

SrsRtmpClient::~SrsRtmpClient()
{
339
    srs_freep(protocol);
340
    srs_freep(hs_bytes);
winlin authored
341 342 343 344
}

void SrsRtmpClient::set_recv_timeout(int64_t timeout_us)
{
345
    protocol->set_recv_timeout(timeout_us);
winlin authored
346 347 348 349
}

void SrsRtmpClient::set_send_timeout(int64_t timeout_us)
{
350
    protocol->set_send_timeout(timeout_us);
winlin authored
351 352 353 354
}

int64_t SrsRtmpClient::get_recv_bytes()
{
355
    return protocol->get_recv_bytes();
winlin authored
356 357 358 359
}

int64_t SrsRtmpClient::get_send_bytes()
{
360
    return protocol->get_send_bytes();
winlin authored
361 362
}
363
int SrsRtmpClient::recv_message(SrsMessage** pmsg)
364
{
365
    return protocol->recv_message(pmsg);
366 367
}
368
int SrsRtmpClient::decode_message(SrsMessage* msg, SrsPacket** ppacket)
369
{
370
    return protocol->decode_message(msg, ppacket);
371 372
}
373
int SrsRtmpClient::send_and_free_message(SrsMessage* msg, int stream_id)
374
{
375
    return protocol->send_and_free_message(msg, stream_id);
376 377
}
378 379 380 381 382
int SrsRtmpClient::send_and_free_messages(SrsMessage** msgs, int nb_msgs, int stream_id)
{
    return protocol->send_and_free_messages(msgs, nb_msgs, stream_id);
}
383
int SrsRtmpClient::send_and_free_packet(SrsPacket* packet, int stream_id)
384
{
385
    return protocol->send_and_free_packet(packet, stream_id);
386 387
}
winlin authored
388 389
int SrsRtmpClient::handshake()
{
390
    int ret = ERROR_SUCCESS;
winlin authored
391
    
392 393
    srs_assert(hs_bytes);
    
winlin authored
394
    SrsComplexHandshake complex_hs;
395 396 397 398 399 400 401
    if ((ret = complex_hs.handshake_with_server(hs_bytes, io)) != ERROR_SUCCESS) {
        if (ret == ERROR_RTMP_TRY_SIMPLE_HS) {
            SrsSimpleHandshake simple_hs;
            if ((ret = simple_hs.handshake_with_server(hs_bytes, io)) != ERROR_SUCCESS) {
                return ret;
            }
        }
winlin authored
402 403 404
        return ret;
    }
    
405 406
    srs_freep(hs_bytes);
    
winlin authored
407 408 409
    return ret;
}
410 411
int SrsRtmpClient::simple_handshake()
{
412
    int ret = ERROR_SUCCESS;
413
    
414 415
    srs_assert(hs_bytes);
    
416
    SrsSimpleHandshake simple_hs;
417
    if ((ret = simple_hs.handshake_with_server(hs_bytes, io)) != ERROR_SUCCESS) {
418 419 420
        return ret;
    }
    
421 422
    srs_freep(hs_bytes);
    
423 424 425 426 427
    return ret;
}

int SrsRtmpClient::complex_handshake()
{
428 429 430 431 432 433 434 435 436 437 438 439
    int ret = ERROR_SUCCESS;
    
    srs_assert(hs_bytes);
    
    SrsComplexHandshake complex_hs;
    if ((ret = complex_hs.handshake_with_server(hs_bytes, io)) != ERROR_SUCCESS) {
        return ret;
    }
    
    srs_freep(hs_bytes);
    
    return ret;
440 441
}
442 443
int SrsRtmpClient::connect_app(string app, string tc_url, 
    SrsRequest* req, bool debug_srs_upnode)
winlin authored
444
{
445 446
    std::string srs_server_ip;
    std::string srs_server;
447 448
    std::string srs_primary;
    std::string srs_authors;
449 450 451 452
    std::string srs_version;
    int srs_id = 0;
    int srs_pid = 0;
    
453
    return connect_app2(app, tc_url, req, debug_srs_upnode,
454
        srs_server_ip, srs_server, srs_primary, srs_authors,
455 456 457 458
        srs_version, srs_id, srs_pid);
}

int SrsRtmpClient::connect_app2(
459
    string app, string tc_url, SrsRequest* req, bool debug_srs_upnode,
460 461 462
    string& srs_server_ip, string& srs_server, string& srs_primary, 
    string& srs_authors, string& srs_version, int& srs_id, 
    int& srs_pid
463 464 465
){
    int ret = ERROR_SUCCESS;
    
466 467 468 469 470
    // Connect(vhost, app)
    if (true) {
        SrsConnectAppPacket* pkt = new SrsConnectAppPacket();
        
        pkt->command_object->set("app", SrsAmf0Any::str(app.c_str()));
471
        pkt->command_object->set("flashVer", SrsAmf0Any::str("WIN 12,0,0,41"));
472 473 474 475 476
        if (req) {
            pkt->command_object->set("swfUrl", SrsAmf0Any::str(req->swfUrl.c_str()));
        } else {
            pkt->command_object->set("swfUrl", SrsAmf0Any::str());
        }
477 478 479 480 481 482
        pkt->command_object->set("tcUrl", SrsAmf0Any::str(tc_url.c_str()));
        pkt->command_object->set("fpad", SrsAmf0Any::boolean(false));
        pkt->command_object->set("capabilities", SrsAmf0Any::number(239));
        pkt->command_object->set("audioCodecs", SrsAmf0Any::number(3575));
        pkt->command_object->set("videoCodecs", SrsAmf0Any::number(252));
        pkt->command_object->set("videoFunction", SrsAmf0Any::number(1));
483 484 485 486 487
        if (req) {
            pkt->command_object->set("pageUrl", SrsAmf0Any::str(req->pageUrl.c_str()));
        } else {
            pkt->command_object->set("pageUrl", SrsAmf0Any::str());
        }
488 489
        pkt->command_object->set("objectEncoding", SrsAmf0Any::number(0));
        
490 491 492
        // @see https://github.com/winlinvip/simple-rtmp-server/issues/160
        // the debug_srs_upnode is config in vhost and default to true.
        if (debug_srs_upnode && req && req->args) {
493 494 495 496
            srs_freep(pkt->args);
            pkt->args = req->args->copy()->to_object();
        }
        
497
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
498 499 500 501 502 503 504 505
            return ret;
        }
    }
    
    // Set Window Acknowledgement size(2500000)
    if (true) {
        SrsSetWindowAckSizePacket* pkt = new SrsSetWindowAckSizePacket();
        pkt->ackowledgement_window_size = 2500000;
506
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
507 508 509 510 511
            return ret;
        }
    }
    
    // expect connect _result
512
    SrsMessage* msg = NULL;
513
    SrsConnectAppResPacket* pkt = NULL;
514
    if ((ret = expect_message<SrsConnectAppResPacket>(&msg, &pkt)) != ERROR_SUCCESS) {
515 516 517
        srs_error("expect connect app response message failed. ret=%d", ret);
        return ret;
    }
518 519
    SrsAutoFree(SrsMessage, msg);
    SrsAutoFree(SrsConnectAppResPacket, pkt);
520 521 522 523 524 525 526
    
    // server info
    SrsAmf0Any* data = pkt->info->get_property("data");
    if (data && data->is_ecma_array()) {
        SrsAmf0EcmaArray* arr = data->to_ecma_array();
        
        SrsAmf0Any* prop = NULL;
527 528 529 530 531
        if ((prop = arr->ensure_property_string("srs_primary")) != NULL) {
            srs_primary = prop->to_str();
        }
        if ((prop = arr->ensure_property_string("srs_authors")) != NULL) {
            srs_authors = prop->to_str();
532
        }
533 534 535 536 537 538
        if ((prop = arr->ensure_property_string("srs_version")) != NULL) {
            srs_version = prop->to_str();
        }
        if ((prop = arr->ensure_property_string("srs_server_ip")) != NULL) {
            srs_server_ip = prop->to_str();
        }
539 540 541
        if ((prop = arr->ensure_property_string("srs_server")) != NULL) {
            srs_server = prop->to_str();
        }
542 543 544 545 546 547 548
        if ((prop = arr->ensure_property_number("srs_id")) != NULL) {
            srs_id = (int)prop->to_number();
        }
        if ((prop = arr->ensure_property_number("srs_pid")) != NULL) {
            srs_pid = (int)prop->to_number();
        }
    }
549 550
    srs_trace("connected, version=%s, ip=%s, pid=%d, id=%d, dsu=%d", 
        srs_version.c_str(), srs_server_ip.c_str(), srs_pid, srs_id, debug_srs_upnode);
551
    
winlin authored
552 553 554 555 556
    return ret;
}

int SrsRtmpClient::create_stream(int& stream_id)
{
557 558 559 560 561
    int ret = ERROR_SUCCESS;
    
    // CreateStream
    if (true) {
        SrsCreateStreamPacket* pkt = new SrsCreateStreamPacket();
562
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
563 564 565 566 567 568
            return ret;
        }
    }

    // CreateStream _result.
    if (true) {
569
        SrsMessage* msg = NULL;
570
        SrsCreateStreamResPacket* pkt = NULL;
571
        if ((ret = expect_message<SrsCreateStreamResPacket>(&msg, &pkt)) != ERROR_SUCCESS) {
572 573 574
            srs_error("expect create stream response message failed. ret=%d", ret);
            return ret;
        }
575 576
        SrsAutoFree(SrsMessage, msg);
        SrsAutoFree(SrsCreateStreamResPacket, pkt);
577 578 579 580 581 582
        srs_info("get create stream response message");

        stream_id = (int)pkt->stream_id;
    }
    
    return ret;
winlin authored
583 584 585 586
}

int SrsRtmpClient::play(string stream, int stream_id)
{
587 588 589 590 591 592
    int ret = ERROR_SUCCESS;

    // Play(stream)
    if (true) {
        SrsPlayPacket* pkt = new SrsPlayPacket();
        pkt->stream_name = stream;
593
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
            srs_error("send play stream failed. "
                "stream=%s, stream_id=%d, ret=%d", 
                stream.c_str(), stream_id, ret);
            return ret;
        }
    }
    
    // SetBufferLength(1000ms)
    int buffer_length_ms = 1000;
    if (true) {
        SrsUserControlPacket* pkt = new SrsUserControlPacket();
    
        pkt->event_type = SrcPCUCSetBufferLength;
        pkt->event_data = stream_id;
        pkt->extra_data = buffer_length_ms;
        
610
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
611 612 613 614 615 616 617 618 619 620
            srs_error("send set buffer length failed. "
                "stream=%s, stream_id=%d, bufferLength=%d, ret=%d", 
                stream.c_str(), stream_id, buffer_length_ms, ret);
            return ret;
        }
    }
    
    // SetChunkSize
    if (true) {
        SrsSetChunkSizePacket* pkt = new SrsSetChunkSizePacket();
621
        pkt->chunk_size = SRS_CONSTS_RTMP_SRS_CHUNK_SIZE;
622
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
623 624
            srs_error("send set chunk size failed. "
                "stream=%s, chunk_size=%d, ret=%d", 
625
                stream.c_str(), SRS_CONSTS_RTMP_SRS_CHUNK_SIZE, ret);
626 627 628 629 630
            return ret;
        }
    }
    
    return ret;
winlin authored
631 632 633 634
}

int SrsRtmpClient::publish(string stream, int stream_id)
{
635 636 637 638 639
    int ret = ERROR_SUCCESS;
    
    // SetChunkSize
    if (true) {
        SrsSetChunkSizePacket* pkt = new SrsSetChunkSizePacket();
640
        pkt->chunk_size = SRS_CONSTS_RTMP_SRS_CHUNK_SIZE;
641
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
642 643
            srs_error("send set chunk size failed. "
                "stream=%s, chunk_size=%d, ret=%d", 
644
                stream.c_str(), SRS_CONSTS_RTMP_SRS_CHUNK_SIZE, ret);
645 646 647 648 649 650 651 652
            return ret;
        }
    }

    // publish(stream)
    if (true) {
        SrsPublishPacket* pkt = new SrsPublishPacket();
        pkt->stream_name = stream;
653
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
654 655 656 657 658 659 660 661
            srs_error("send publish message failed. "
                "stream=%s, stream_id=%d, ret=%d", 
                stream.c_str(), stream_id, ret);
            return ret;
        }
    }
    
    return ret;
winlin authored
662 663
}
664 665
int SrsRtmpClient::fmle_publish(string stream, int& stream_id)
{
666 667 668 669 670 671 672
    stream_id = 0;
    
    int ret = ERROR_SUCCESS;
    
    // SrsFMLEStartPacket
    if (true) {
        SrsFMLEStartPacket* pkt = SrsFMLEStartPacket::create_release_stream(stream);
673
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
674 675 676 677 678 679 680 681 682
            srs_error("send FMLE publish "
                "release stream failed. stream=%s, ret=%d", stream.c_str(), ret);
            return ret;
        }
    }
    
    // FCPublish
    if (true) {
        SrsFMLEStartPacket* pkt = SrsFMLEStartPacket::create_FC_publish(stream);
683
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
684 685 686 687 688 689 690 691 692 693
            srs_error("send FMLE publish "
                "FCPublish failed. stream=%s, ret=%d", stream.c_str(), ret);
            return ret;
        }
    }
    
    // CreateStream
    if (true) {
        SrsCreateStreamPacket* pkt = new SrsCreateStreamPacket();
        pkt->transaction_id = 4;
694
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
695 696 697 698 699 700 701 702
            srs_error("send FMLE publish "
                "createStream failed. stream=%s, ret=%d", stream.c_str(), ret);
            return ret;
        }
    }
    
    // expect result of CreateStream
    if (true) {
703
        SrsMessage* msg = NULL;
704
        SrsCreateStreamResPacket* pkt = NULL;
705
        if ((ret = expect_message<SrsCreateStreamResPacket>(&msg, &pkt)) != ERROR_SUCCESS) {
706 707 708
            srs_error("expect create stream response message failed. ret=%d", ret);
            return ret;
        }
709 710
        SrsAutoFree(SrsMessage, msg);
        SrsAutoFree(SrsCreateStreamResPacket, pkt);
711 712 713 714 715 716 717 718 719
        srs_info("get create stream response message");

        stream_id = (int)pkt->stream_id;
    }

    // publish(stream)
    if (true) {
        SrsPublishPacket* pkt = new SrsPublishPacket();
        pkt->stream_name = stream;
720
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
721 722 723 724 725 726 727
            srs_error("send FMLE publish publish failed. "
                "stream=%s, stream_id=%d, ret=%d", stream.c_str(), stream_id, ret);
            return ret;
        }
    }
    
    return ret;
728 729
}
730
SrsRtmpServer::SrsRtmpServer(ISrsProtocolReaderWriter* skt)
winlin authored
731
{
732 733
    io = skt;
    protocol = new SrsProtocol(skt);
734
    hs_bytes = new SrsHandshakeBytes();
winlin authored
735 736
}
737
SrsRtmpServer::~SrsRtmpServer()
winlin authored
738
{
739
    srs_freep(protocol);
740
    srs_freep(hs_bytes);
winlin authored
741 742
}
743 744 745 746 747
void SrsRtmpServer::set_auto_response(bool v)
{
    protocol->set_auto_response(v);
}
748 749 750 751 752
void SrsRtmpServer::set_merge_read(bool v, IMergeReadHandler* handler)
{
    protocol->set_merge_read(v, handler);
}
753
void SrsRtmpServer::set_recv_timeout(int64_t timeout_us)
winlin authored
754
{
755
    protocol->set_recv_timeout(timeout_us);
winlin authored
756 757
}
758
int64_t SrsRtmpServer::get_recv_timeout()
winlin authored
759
{
760
    return protocol->get_recv_timeout();
winlin authored
761 762
}
763
void SrsRtmpServer::set_send_timeout(int64_t timeout_us)
winlin authored
764
{
765
    protocol->set_send_timeout(timeout_us);
winlin authored
766 767
}
768
int64_t SrsRtmpServer::get_send_timeout()
winlin authored
769
{
770
    return protocol->get_send_timeout();
winlin authored
771 772
}
773
int64_t SrsRtmpServer::get_recv_bytes()
winlin authored
774
{
775
    return protocol->get_recv_bytes();
winlin authored
776 777
}
778
int64_t SrsRtmpServer::get_send_bytes()
winlin authored
779
{
780
    return protocol->get_send_bytes();
winlin authored
781 782
}
783
int SrsRtmpServer::recv_message(SrsMessage** pmsg)
784
{
785
    return protocol->recv_message(pmsg);
786 787
}
788
int SrsRtmpServer::decode_message(SrsMessage* msg, SrsPacket** ppacket)
789
{
790
    return protocol->decode_message(msg, ppacket);
791 792
}
793
int SrsRtmpServer::send_and_free_message(SrsMessage* msg, int stream_id)
794
{
795
    return protocol->send_and_free_message(msg, stream_id);
796 797
}
798
int SrsRtmpServer::send_and_free_messages(SrsMessage** msgs, int nb_msgs, int stream_id)
799 800 801 802
{
    return protocol->send_and_free_messages(msgs, nb_msgs, stream_id);
}
803
int SrsRtmpServer::send_and_free_packet(SrsPacket* packet, int stream_id)
804
{
805
    return protocol->send_and_free_packet(packet, stream_id);
806 807
}
808
int SrsRtmpServer::handshake()
winlin authored
809
{
810
    int ret = ERROR_SUCCESS;
winlin authored
811
    
812 813
    srs_assert(hs_bytes);
    
winlin authored
814
    SrsComplexHandshake complex_hs;
815 816 817 818 819 820 821
    if ((ret = complex_hs.handshake_with_client(hs_bytes, io)) != ERROR_SUCCESS) {
        if (ret == ERROR_RTMP_TRY_SIMPLE_HS) {
            SrsSimpleHandshake simple_hs;
            if ((ret = simple_hs.handshake_with_client(hs_bytes, io)) != ERROR_SUCCESS) {
                return ret;
            }
        }
winlin authored
822 823 824
        return ret;
    }
    
825 826
    srs_freep(hs_bytes);
    
winlin authored
827 828 829
    return ret;
}
830
int SrsRtmpServer::connect_app(SrsRequest* req)
winlin authored
831
{
832 833
    int ret = ERROR_SUCCESS;
    
834
    SrsMessage* msg = NULL;
835
    SrsConnectAppPacket* pkt = NULL;
836
    if ((ret = expect_message<SrsConnectAppPacket>(&msg, &pkt)) != ERROR_SUCCESS) {
837 838 839
        srs_error("expect connect app message failed. ret=%d", ret);
        return ret;
    }
840 841
    SrsAutoFree(SrsMessage, msg);
    SrsAutoFree(SrsConnectAppPacket, pkt);
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    srs_info("get connect app message");
    
    SrsAmf0Any* prop = NULL;
    
    if ((prop = pkt->command_object->ensure_property_string("tcUrl")) == NULL) {
        ret = ERROR_RTMP_REQ_CONNECT;
        srs_error("invalid request, must specifies the tcUrl. ret=%d", ret);
        return ret;
    }
    req->tcUrl = prop->to_str();
    
    if ((prop = pkt->command_object->ensure_property_string("pageUrl")) != NULL) {
        req->pageUrl = prop->to_str();
    }
    
    if ((prop = pkt->command_object->ensure_property_string("swfUrl")) != NULL) {
        req->swfUrl = prop->to_str();
    }
    
    if ((prop = pkt->command_object->ensure_property_number("objectEncoding")) != NULL) {
        req->objectEncoding = prop->to_number();
    }
    
865 866 867 868 869 870
    if (pkt->args) {
        srs_freep(req->args);
        req->args = pkt->args->copy()->to_object();
        srs_info("copy edge traverse to origin auth args.");
    }
    
871 872
    srs_info("get connect app message params success.");
    
873 874 875
    srs_discovery_tc_url(req->tcUrl, 
        req->schema, req->host, req->vhost, req->app, req->port,
        req->param);
876 877 878
    req->strip();
    
    return ret;
winlin authored
879 880
}
881
int SrsRtmpServer::set_window_ack_size(int ack_size)
winlin authored
882
{
883 884 885 886
    int ret = ERROR_SUCCESS;
    
    SrsSetWindowAckSizePacket* pkt = new SrsSetWindowAckSizePacket();
    pkt->ackowledgement_window_size = ack_size;
887
    if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
888 889 890 891 892 893
        srs_error("send ack size message failed. ret=%d", ret);
        return ret;
    }
    srs_info("send ack size message success. ack_size=%d", ack_size);
    
    return ret;
winlin authored
894 895
}
896
int SrsRtmpServer::set_peer_bandwidth(int bandwidth, int type)
winlin authored
897
{
898 899 900 901 902
    int ret = ERROR_SUCCESS;
    
    SrsSetPeerBandwidthPacket* pkt = new SrsSetPeerBandwidthPacket();
    pkt->bandwidth = bandwidth;
    pkt->type = type;
903
    if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
904 905 906 907 908 909 910
        srs_error("send set bandwidth message failed. ret=%d", ret);
        return ret;
    }
    srs_info("send set bandwidth message "
        "success. bandwidth=%d, type=%d", bandwidth, type);
    
    return ret;
winlin authored
911 912
}
913
int SrsRtmpServer::response_connect_app(SrsRequest *req, const char* server_ip)
winlin authored
914
{
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
    int ret = ERROR_SUCCESS;
    
    SrsConnectAppResPacket* pkt = new SrsConnectAppResPacket();
    
    pkt->props->set("fmsVer", SrsAmf0Any::str("FMS/"RTMP_SIG_FMS_VER));
    pkt->props->set("capabilities", SrsAmf0Any::number(127));
    pkt->props->set("mode", SrsAmf0Any::number(1));
    
    pkt->info->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
    pkt->info->set(StatusCode, SrsAmf0Any::str(StatusCodeConnectSuccess));
    pkt->info->set(StatusDescription, SrsAmf0Any::str("Connection succeeded"));
    pkt->info->set("objectEncoding", SrsAmf0Any::number(req->objectEncoding));
    SrsAmf0EcmaArray* data = SrsAmf0Any::ecma_array();
    pkt->info->set("data", data);
    
    data->set("version", SrsAmf0Any::str(RTMP_SIG_FMS_VER));
    data->set("srs_sig", SrsAmf0Any::str(RTMP_SIG_SRS_KEY));
    data->set("srs_server", SrsAmf0Any::str(RTMP_SIG_SRS_KEY" "RTMP_SIG_SRS_VERSION" ("RTMP_SIG_SRS_URL_SHORT")"));
    data->set("srs_license", SrsAmf0Any::str(RTMP_SIG_SRS_LICENSE));
    data->set("srs_role", SrsAmf0Any::str(RTMP_SIG_SRS_ROLE));
    data->set("srs_url", SrsAmf0Any::str(RTMP_SIG_SRS_URL));
    data->set("srs_version", SrsAmf0Any::str(RTMP_SIG_SRS_VERSION));
    data->set("srs_site", SrsAmf0Any::str(RTMP_SIG_SRS_WEB));
    data->set("srs_email", SrsAmf0Any::str(RTMP_SIG_SRS_EMAIL));
    data->set("srs_copyright", SrsAmf0Any::str(RTMP_SIG_SRS_COPYRIGHT));
940 941
    data->set("srs_primary", SrsAmf0Any::str(RTMP_SIG_SRS_PRIMARY));
    data->set("srs_authors", SrsAmf0Any::str(RTMP_SIG_SRS_AUTHROS));
942
    
winlin authored
943
    if (server_ip) {
944
        data->set("srs_server_ip", SrsAmf0Any::str(server_ip));
winlin authored
945
    }
946
    // for edge to directly get the id of client.
947
    data->set("srs_pid", SrsAmf0Any::number(getpid()));
948
    data->set("srs_id", SrsAmf0Any::number(_srs_context->get_id()));
949
    
950
    if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
951 952 953 954 955
        srs_error("send connect app response message failed. ret=%d", ret);
        return ret;
    }
    srs_info("send connect app response message success.");
    
winlin authored
956 957 958
    return ret;
}
959
void SrsRtmpServer::response_connect_reject(SrsRequest* /*req*/, const char* desc)
winlin authored
960 961 962
{
    int ret = ERROR_SUCCESS;
963 964 965 966
    SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
    pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelError));
    pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeConnectRejected));
    pkt->data->set(StatusDescription, SrsAmf0Any::str(desc));
winlin authored
967
968
    if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
winlin authored
969 970 971 972 973 974 975 976
        srs_error("send connect app response rejected message failed. ret=%d", ret);
        return;
    }
    srs_info("send connect app response rejected message success.");

    return;
}
977
int SrsRtmpServer::on_bw_done()
winlin authored
978
{
979 980 981
    int ret = ERROR_SUCCESS;
    
    SrsOnBWDonePacket* pkt = new SrsOnBWDonePacket();
982
    if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
983 984 985 986 987 988
        srs_error("send onBWDone message failed. ret=%d", ret);
        return ret;
    }
    srs_info("send onBWDone message success.");
    
    return ret;
winlin authored
989 990
}
991
int SrsRtmpServer::identify_client(int stream_id, SrsRtmpConnType& type, string& stream_name, double& duration)
winlin authored
992
{
993
    type = SrsRtmpConnUnknown;
994 995 996
    int ret = ERROR_SUCCESS;
    
    while (true) {
997 998
        SrsMessage* msg = NULL;
        if ((ret = protocol->recv_message(&msg)) != ERROR_SUCCESS) {
winlin authored
999 1000 1001
            if (!srs_is_client_gracefully_close(ret)) {
                srs_error("recv identify client message failed. ret=%d", ret);
            }
1002 1003 1004
            return ret;
        }
1005
        SrsAutoFree(SrsMessage, msg);
winlin authored
1006 1007 1008 1009 1010 1011 1012
        SrsMessageHeader& h = msg->header;
        
        if (h.is_ackledgement() || h.is_set_chunk_size() || h.is_window_ackledgement_size() || h.is_user_control_message()) {
            continue;
        }
        
        if (!h.is_amf0_command() && !h.is_amf3_command()) {
1013
            srs_trace("identify ignore messages except "
winlin authored
1014
                "AMF0/AMF3 command message. type=%#x", h.message_type);
1015 1016 1017
            continue;
        }
        
1018
        SrsPacket* pkt = NULL;
1019
        if ((ret = protocol->decode_message(msg, &pkt)) != ERROR_SUCCESS) {
1020 1021 1022 1023
            srs_error("identify decode message failed. ret=%d", ret);
            return ret;
        }
        
1024
        SrsAutoFree(SrsPacket, pkt);
1025
        
1026 1027
        if (dynamic_cast<SrsCreateStreamPacket*>(pkt)) {
            srs_info("identify client by create stream, play or flash publish.");
1028
            return identify_create_stream_client(dynamic_cast<SrsCreateStreamPacket*>(pkt), stream_id, type, stream_name, duration);
1029 1030 1031 1032 1033 1034 1035
        }
        if (dynamic_cast<SrsFMLEStartPacket*>(pkt)) {
            srs_info("identify client by releaseStream, fmle publish.");
            return identify_fmle_publish_client(dynamic_cast<SrsFMLEStartPacket*>(pkt), type, stream_name);
        }
        if (dynamic_cast<SrsPlayPacket*>(pkt)) {
            srs_info("level0 identify client by play.");
1036
            return identify_play_client(dynamic_cast<SrsPlayPacket*>(pkt), type, stream_name, duration);
1037
        }
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
        // call msg,
        // support response null first,
        // @see https://github.com/winlinvip/simple-rtmp-server/issues/106
        // TODO: FIXME: response in right way, or forward in edge mode.
        SrsCallPacket* call = dynamic_cast<SrsCallPacket*>(pkt);
        if (call) {
            SrsCallResPacket* res = new SrsCallResPacket(call->transaction_id);
            res->command_object = SrsAmf0Any::null();
            res->response = SrsAmf0Any::null();
            if ((ret = protocol->send_and_free_packet(res, 0)) != ERROR_SUCCESS) {
                srs_warn("response call failed. ret=%d", ret);
                return ret;
            }
            continue;
        }
1053 1054 1055 1056 1057
        
        srs_trace("ignore AMF0/AMF3 command message.");
    }
    
    return ret;
winlin authored
1058 1059
}
1060
int SrsRtmpServer::set_chunk_size(int chunk_size)
winlin authored
1061
{
1062 1063 1064 1065
    int ret = ERROR_SUCCESS;
    
    SrsSetChunkSizePacket* pkt = new SrsSetChunkSizePacket();
    pkt->chunk_size = chunk_size;
1066
    if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1067 1068 1069 1070 1071 1072
        srs_error("send set chunk size message failed. ret=%d", ret);
        return ret;
    }
    srs_info("send set chunk size message success. chunk_size=%d", chunk_size);
    
    return ret;
winlin authored
1073 1074
}
1075
int SrsRtmpServer::start_play(int stream_id)
winlin authored
1076
{
1077 1078 1079 1080 1081 1082 1083
    int ret = ERROR_SUCCESS;
    
    // StreamBegin
    if (true) {
        SrsUserControlPacket* pkt = new SrsUserControlPacket();
        pkt->event_type = SrcPCUCStreamBegin;
        pkt->event_data = stream_id;
1084
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
            srs_error("send PCUC(StreamBegin) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send PCUC(StreamBegin) message success.");
    }
    
    // onStatus(NetStream.Play.Reset)
    if (true) {
        SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
        
        pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeStreamReset));
        pkt->data->set(StatusDescription, SrsAmf0Any::str("Playing and resetting stream."));
        pkt->data->set(StatusDetails, SrsAmf0Any::str("stream"));
        pkt->data->set(StatusClientId, SrsAmf0Any::str(RTMP_SIG_CLIENT_ID));
        
1101
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
            srs_error("send onStatus(NetStream.Play.Reset) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onStatus(NetStream.Play.Reset) message success.");
    }
    
    // onStatus(NetStream.Play.Start)
    if (true) {
        SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
        
        pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeStreamStart));
        pkt->data->set(StatusDescription, SrsAmf0Any::str("Started playing stream."));
        pkt->data->set(StatusDetails, SrsAmf0Any::str("stream"));
        pkt->data->set(StatusClientId, SrsAmf0Any::str(RTMP_SIG_CLIENT_ID));
        
1118
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1119 1120 1121 1122 1123 1124 1125 1126 1127
            srs_error("send onStatus(NetStream.Play.Reset) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onStatus(NetStream.Play.Reset) message success.");
    }
    
    // |RtmpSampleAccess(false, false)
    if (true) {
        SrsSampleAccessPacket* pkt = new SrsSampleAccessPacket();
1128 1129 1130 1131 1132 1133

        // allow audio/video sample.
        // @see: https://github.com/winlinvip/simple-rtmp-server/issues/49
        pkt->audio_sample_access = true;
        pkt->video_sample_access = true;
        
1134
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
            srs_error("send |RtmpSampleAccess(false, false) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send |RtmpSampleAccess(false, false) message success.");
    }
    
    // onStatus(NetStream.Data.Start)
    if (true) {
        SrsOnStatusDataPacket* pkt = new SrsOnStatusDataPacket();
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeDataStart));
1145
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1146 1147 1148 1149 1150 1151 1152 1153 1154
            srs_error("send onStatus(NetStream.Data.Start) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onStatus(NetStream.Data.Start) message success.");
    }
    
    srs_info("start play success.");
    
    return ret;
winlin authored
1155 1156
}
1157
int SrsRtmpServer::on_play_client_pause(int stream_id, bool is_pause)
winlin authored
1158
{
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
    int ret = ERROR_SUCCESS;
    
    if (is_pause) {
        // onStatus(NetStream.Pause.Notify)
        if (true) {
            SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
            
            pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
            pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeStreamPause));
            pkt->data->set(StatusDescription, SrsAmf0Any::str("Paused stream."));
            
1170
            if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
                srs_error("send onStatus(NetStream.Pause.Notify) message failed. ret=%d", ret);
                return ret;
            }
            srs_info("send onStatus(NetStream.Pause.Notify) message success.");
        }
        // StreamEOF
        if (true) {
            SrsUserControlPacket* pkt = new SrsUserControlPacket();
            
            pkt->event_type = SrcPCUCStreamEOF;
            pkt->event_data = stream_id;
            
1183
            if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
                srs_error("send PCUC(StreamEOF) message failed. ret=%d", ret);
                return ret;
            }
            srs_info("send PCUC(StreamEOF) message success.");
        }
    } else {
        // onStatus(NetStream.Unpause.Notify)
        if (true) {
            SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
            
            pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
            pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeStreamUnpause));
            pkt->data->set(StatusDescription, SrsAmf0Any::str("Unpaused stream."));
            
1198
            if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
                srs_error("send onStatus(NetStream.Unpause.Notify) message failed. ret=%d", ret);
                return ret;
            }
            srs_info("send onStatus(NetStream.Unpause.Notify) message success.");
        }
        // StreanBegin
        if (true) {
            SrsUserControlPacket* pkt = new SrsUserControlPacket();
            
            pkt->event_type = SrcPCUCStreamBegin;
            pkt->event_data = stream_id;
            
1211
            if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1212 1213 1214 1215 1216 1217 1218 1219
                srs_error("send PCUC(StreanBegin) message failed. ret=%d", ret);
                return ret;
            }
            srs_info("send PCUC(StreanBegin) message success.");
        }
    }
    
    return ret;
winlin authored
1220 1221
}
1222
int SrsRtmpServer::start_fmle_publish(int stream_id)
winlin authored
1223
{
1224 1225 1226 1227 1228
    int ret = ERROR_SUCCESS;
    
    // FCPublish
    double fc_publish_tid = 0;
    if (true) {
1229
        SrsMessage* msg = NULL;
1230
        SrsFMLEStartPacket* pkt = NULL;
1231
        if ((ret = expect_message<SrsFMLEStartPacket>(&msg, &pkt)) != ERROR_SUCCESS) {
1232 1233 1234 1235 1236
            srs_error("recv FCPublish message failed. ret=%d", ret);
            return ret;
        }
        srs_info("recv FCPublish request message success.");
        
1237 1238
        SrsAutoFree(SrsMessage, msg);
        SrsAutoFree(SrsFMLEStartPacket, pkt);
winlin authored
1239
    
1240 1241 1242 1243 1244
        fc_publish_tid = pkt->transaction_id;
    }
    // FCPublish response
    if (true) {
        SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(fc_publish_tid);
1245
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1246 1247 1248 1249 1250 1251 1252 1253 1254
            srs_error("send FCPublish response message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send FCPublish response message success.");
    }
    
    // createStream
    double create_stream_tid = 0;
    if (true) {
1255
        SrsMessage* msg = NULL;
1256
        SrsCreateStreamPacket* pkt = NULL;
1257
        if ((ret = expect_message<SrsCreateStreamPacket>(&msg, &pkt)) != ERROR_SUCCESS) {
1258 1259 1260 1261 1262
            srs_error("recv createStream message failed. ret=%d", ret);
            return ret;
        }
        srs_info("recv createStream request message success.");
        
1263 1264
        SrsAutoFree(SrsMessage, msg);
        SrsAutoFree(SrsCreateStreamPacket, pkt);
winlin authored
1265
        
1266 1267 1268 1269 1270
        create_stream_tid = pkt->transaction_id;
    }
    // createStream response
    if (true) {
        SrsCreateStreamResPacket* pkt = new SrsCreateStreamResPacket(create_stream_tid, stream_id);
1271
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1272 1273 1274 1275 1276 1277 1278 1279
            srs_error("send createStream response message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send createStream response message success.");
    }
    
    // publish
    if (true) {
1280
        SrsMessage* msg = NULL;
1281
        SrsPublishPacket* pkt = NULL;
1282
        if ((ret = expect_message<SrsPublishPacket>(&msg, &pkt)) != ERROR_SUCCESS) {
1283 1284 1285 1286 1287
            srs_error("recv publish message failed. ret=%d", ret);
            return ret;
        }
        srs_info("recv publish request message success.");
        
1288 1289
        SrsAutoFree(SrsMessage, msg);
        SrsAutoFree(SrsPublishPacket, pkt);
1290 1291 1292 1293 1294 1295 1296 1297 1298
    }
    // publish response onFCPublish(NetStream.Publish.Start)
    if (true) {
        SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
        
        pkt->command_name = RTMP_AMF0_COMMAND_ON_FC_PUBLISH;
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodePublishStart));
        pkt->data->set(StatusDescription, SrsAmf0Any::str("Started publishing stream."));
        
1299
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
            srs_error("send onFCPublish(NetStream.Publish.Start) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onFCPublish(NetStream.Publish.Start) message success.");
    }
    // publish response onStatus(NetStream.Publish.Start)
    if (true) {
        SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
        
        pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodePublishStart));
        pkt->data->set(StatusDescription, SrsAmf0Any::str("Started publishing stream."));
        pkt->data->set(StatusClientId, SrsAmf0Any::str(RTMP_SIG_CLIENT_ID));
        
1314
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1315 1316 1317 1318 1319 1320 1321 1322 1323
            srs_error("send onStatus(NetStream.Publish.Start) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onStatus(NetStream.Publish.Start) message success.");
    }
    
    srs_info("FMLE publish success.");
    
    return ret;
winlin authored
1324 1325
}
1326
int SrsRtmpServer::fmle_unpublish(int stream_id, double unpublish_tid)
winlin authored
1327
{
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
    int ret = ERROR_SUCCESS;
    
    // publish response onFCUnpublish(NetStream.unpublish.Success)
    if (true) {
        SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
        
        pkt->command_name = RTMP_AMF0_COMMAND_ON_FC_UNPUBLISH;
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeUnpublishSuccess));
        pkt->data->set(StatusDescription, SrsAmf0Any::str("Stop publishing stream."));
        
1338
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1339 1340 1341 1342 1343 1344 1345 1346
            srs_error("send onFCUnpublish(NetStream.unpublish.Success) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onFCUnpublish(NetStream.unpublish.Success) message success.");
    }
    // FCUnpublish response
    if (true) {
        SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(unpublish_tid);
1347
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
            srs_error("send FCUnpublish response message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send FCUnpublish response message success.");
    }
    // publish response onStatus(NetStream.Unpublish.Success)
    if (true) {
        SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
        
        pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodeUnpublishSuccess));
        pkt->data->set(StatusDescription, SrsAmf0Any::str("Stream is now unpublished"));
        pkt->data->set(StatusClientId, SrsAmf0Any::str(RTMP_SIG_CLIENT_ID));
        
1362
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1363 1364 1365 1366 1367 1368 1369 1370 1371
            srs_error("send onStatus(NetStream.Unpublish.Success) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onStatus(NetStream.Unpublish.Success) message success.");
    }
    
    srs_info("FMLE unpublish success.");
    
    return ret;
winlin authored
1372 1373
}
1374
int SrsRtmpServer::start_flash_publish(int stream_id)
winlin authored
1375
{
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
    int ret = ERROR_SUCCESS;
    
    // publish response onStatus(NetStream.Publish.Start)
    if (true) {
        SrsOnStatusCallPacket* pkt = new SrsOnStatusCallPacket();
        
        pkt->data->set(StatusLevel, SrsAmf0Any::str(StatusLevelStatus));
        pkt->data->set(StatusCode, SrsAmf0Any::str(StatusCodePublishStart));
        pkt->data->set(StatusDescription, SrsAmf0Any::str("Started publishing stream."));
        pkt->data->set(StatusClientId, SrsAmf0Any::str(RTMP_SIG_CLIENT_ID));
        
1387
        if ((ret = protocol->send_and_free_packet(pkt, stream_id)) != ERROR_SUCCESS) {
1388 1389 1390 1391 1392 1393 1394 1395 1396
            srs_error("send onStatus(NetStream.Publish.Start) message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send onStatus(NetStream.Publish.Start) message success.");
    }
    
    srs_info("flash publish success.");
    
    return ret;
winlin authored
1397 1398
}
1399
int SrsRtmpServer::identify_create_stream_client(SrsCreateStreamPacket* req, int stream_id, SrsRtmpConnType& type, string& stream_name, double& duration)
winlin authored
1400
{
1401 1402 1403 1404
    int ret = ERROR_SUCCESS;
    
    if (true) {
        SrsCreateStreamResPacket* pkt = new SrsCreateStreamResPacket(req->transaction_id, stream_id);
1405
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1406 1407 1408 1409 1410 1411 1412
            srs_error("send createStream response message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send createStream response message success.");
    }
    
    while (true) {
1413 1414
        SrsMessage* msg = NULL;
        if ((ret = protocol->recv_message(&msg)) != ERROR_SUCCESS) {
winlin authored
1415 1416 1417
            if (!srs_is_client_gracefully_close(ret)) {
                srs_error("recv identify client message failed. ret=%d", ret);
            }
1418 1419 1420
            return ret;
        }
1421
        SrsAutoFree(SrsMessage, msg);
winlin authored
1422 1423 1424 1425 1426 1427 1428
        SrsMessageHeader& h = msg->header;
        
        if (h.is_ackledgement() || h.is_set_chunk_size() || h.is_window_ackledgement_size() || h.is_user_control_message()) {
            continue;
        }
    
        if (!h.is_amf0_command() && !h.is_amf3_command()) {
1429
            srs_trace("identify ignore messages except "
winlin authored
1430
                "AMF0/AMF3 command message. type=%#x", h.message_type);
1431 1432 1433
            continue;
        }
        
1434
        SrsPacket* pkt = NULL;
1435
        if ((ret = protocol->decode_message(msg, &pkt)) != ERROR_SUCCESS) {
1436 1437 1438
            srs_error("identify decode message failed. ret=%d", ret);
            return ret;
        }
1439
1440
        SrsAutoFree(SrsPacket, pkt);
1441 1442 1443
        
        if (dynamic_cast<SrsPlayPacket*>(pkt)) {
            srs_info("level1 identify client by play.");
1444
            return identify_play_client(dynamic_cast<SrsPlayPacket*>(pkt), type, stream_name, duration);
1445 1446 1447 1448 1449
        }
        if (dynamic_cast<SrsPublishPacket*>(pkt)) {
            srs_info("identify client by publish, falsh publish.");
            return identify_flash_publish_client(dynamic_cast<SrsPublishPacket*>(pkt), type, stream_name);
        }
1450 1451 1452 1453
        if (dynamic_cast<SrsCreateStreamPacket*>(pkt)) {
            srs_info("identify client by create stream, play or flash publish.");
            return identify_create_stream_client(dynamic_cast<SrsCreateStreamPacket*>(pkt), stream_id, type, stream_name, duration);
        }
1454 1455 1456 1457 1458
        
        srs_trace("ignore AMF0/AMF3 command message.");
    }
    
    return ret;
winlin authored
1459 1460
}
1461
int SrsRtmpServer::identify_fmle_publish_client(SrsFMLEStartPacket* req, SrsRtmpConnType& type, string& stream_name)
winlin authored
1462
{
1463 1464
    int ret = ERROR_SUCCESS;
    
1465
    type = SrsRtmpConnFMLEPublish;
1466 1467 1468 1469 1470
    stream_name = req->stream_name;
    
    // releaseStream response
    if (true) {
        SrsFMLEStartResPacket* pkt = new SrsFMLEStartResPacket(req->transaction_id);
1471
        if ((ret = protocol->send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1472 1473 1474 1475 1476 1477 1478
            srs_error("send releaseStream response message failed. ret=%d", ret);
            return ret;
        }
        srs_info("send releaseStream response message success.");
    }
    
    return ret;
winlin authored
1479 1480
}
1481
int SrsRtmpServer::identify_flash_publish_client(SrsPublishPacket* req, SrsRtmpConnType& type, string& stream_name)
winlin authored
1482
{
1483 1484
    int ret = ERROR_SUCCESS;
    
1485
    type = SrsRtmpConnFlashPublish;
1486 1487 1488
    stream_name = req->stream_name;
    
    return ret;
winlin authored
1489
}
1490
1491
int SrsRtmpServer::identify_play_client(SrsPlayPacket* req, SrsRtmpConnType& type, string& stream_name, double& duration)
1492
{
1493 1494
    int ret = ERROR_SUCCESS;
    
1495
    type = SrsRtmpConnPlay;
1496
    stream_name = req->stream_name;
1497
    duration = req->duration;
1498
    
winlin authored
1499
    srs_info("identity client type=play, stream_name=%s, duration=%.2f", stream_name.c_str(), duration);
1500 1501

    return ret;
1502 1503
}
1504