Blame view

trunk/src/rtmp/srs_protocol_stack.cpp 125.4 KB
winlin authored
1 2 3
/*
The MIT License (MIT)
4
Copyright (c) 2013-2014 winlin
winlin authored
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_protocol_stack.hpp>
winlin authored
25
26
#include <srs_protocol_amf0.hpp>
27
#include <srs_protocol_io.hpp>
winlin authored
28
#include <srs_kernel_stream.hpp>
winlin authored
29
#include <srs_core_autofree.hpp>
30
#include <srs_kernel_utility.hpp>
31
#include <srs_protocol_buffer.hpp>
winlin authored
32
33
#include <stdlib.h>
34 35
using namespace std;
winlin authored
36 37 38 39
// when got a messae header, there must be some data,
// increase recv timeout to got an entire message.
#define SRS_MIN_RECV_TIMEOUT_US (int64_t)(60*1000*1000LL)
winlin authored
40 41 42 43 44 45 46 47 48 49 50 51
/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
5. Protocol Control Messages
RTMP reserves message type IDs 1-7 for protocol control messages.
These messages contain information needed by the RTM Chunk Stream
protocol or RTMP itself. Protocol messages with IDs 1 & 2 are
reserved for usage with RTM Chunk Stream protocol. Protocol messages
with IDs 3-6 are reserved for usage of RTMP. Protocol message with ID
7 is used between edge server and origin server.
*/
52 53 54 55 56 57 58
#define RTMP_MSG_SetChunkSize                   0x01
#define RTMP_MSG_AbortMessage                   0x02
#define RTMP_MSG_Acknowledgement                0x03
#define RTMP_MSG_UserControlMessage             0x04
#define RTMP_MSG_WindowAcknowledgementSize      0x05
#define RTMP_MSG_SetPeerBandwidth               0x06
#define RTMP_MSG_EdgeAndOriginServerCommand     0x07
winlin authored
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
/**
3. Types of messages
The server and the client send messages over the network to
communicate with each other. The messages can be of any type which
includes audio messages, video messages, command messages, shared
object messages, data messages, and user control messages.
3.1. Command message
Command messages carry the AMF-encoded commands between the client
and the server. These messages have been assigned message type value
of 20 for AMF0 encoding and message type value of 17 for AMF3
encoding. These messages are sent to perform some operations like
connect, createStream, publish, play, pause on the peer. Command
messages like onstatus, result etc. are used to inform the sender
about the status of the requested commands. A command message
consists of command name, transaction ID, and command object that
contains related parameters. A client or a server can request Remote
Procedure Calls (RPC) over streams that are communicated using the
command messages to the peer.
*/
78 79
#define RTMP_MSG_AMF3CommandMessage             17 // 0x11
#define RTMP_MSG_AMF0CommandMessage             20 // 0x14
winlin authored
80 81 82 83 84 85 86 87
/**
3.2. Data message
The client or the server sends this message to send Metadata or any
user data to the peer. Metadata includes details about the
data(audio, video etc.) like creation time, duration, theme and so
on. These messages have been assigned message type value of 18 for
AMF0 and message type value of 15 for AMF3.        
*/
88 89
#define RTMP_MSG_AMF0DataMessage                18 // 0x12
#define RTMP_MSG_AMF3DataMessage                15 // 0x0F
winlin authored
90 91 92 93 94 95 96 97
/**
3.3. Shared object message
A shared object is a Flash object (a collection of name value pairs)
that are in synchronization across multiple clients, instances, and
so on. The message types kMsgContainer=19 for AMF0 and
kMsgContainerEx=16 for AMF3 are reserved for shared object events.
Each message can contain multiple events.
*/
98 99
#define RTMP_MSG_AMF3SharedObject               16 // 0x10
#define RTMP_MSG_AMF0SharedObject               19 // 0x13
winlin authored
100 101 102 103 104
/**
3.4. Audio message
The client or the server sends this message to send audio data to the
peer. The message type value of 8 is reserved for audio messages.
*/
105
#define RTMP_MSG_AudioMessage                   8 // 0x08
winlin authored
106 107 108 109 110 111 112 113
/* *
3.5. Video message
The client or the server sends this message to send video data to the
peer. The message type value of 9 is reserved for video messages.
These messages are large and can delay the sending of other type of
messages. To avoid such a situation, the video message is assigned
the lowest priority.
*/
114
#define RTMP_MSG_VideoMessage                   9 // 0x09
winlin authored
115 116 117 118 119 120
/**
3.6. Aggregate message
An aggregate message is a single message that contains a list of submessages.
The message type value of 22 is reserved for aggregate
messages.
*/
121
#define RTMP_MSG_AggregateMessage               22 // 0x16
winlin authored
122 123 124 125 126 127 128 129 130 131 132 133 134

/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* 6.1.2. Chunk Message Header
* There are four different formats for the chunk message header,
* selected by the "fmt" field in the chunk basic header.
*/
// 6.1.2.1. Type 0
// Chunks of Type 0 are 11 bytes long. This type MUST be used at the
// start of a chunk stream, and whenever the stream timestamp goes
// backward (e.g., because of a backward seek).
135
#define RTMP_FMT_TYPE0                          0
winlin authored
136 137 138 139 140 141
// 6.1.2.2. Type 1
// Chunks of Type 1 are 7 bytes long. The message stream ID is not
// included; this chunk takes the same stream ID as the preceding chunk.
// Streams with variable-sized messages (for example, many video
// formats) SHOULD use this format for the first chunk of each new
// message after the first.
142
#define RTMP_FMT_TYPE1                          1
winlin authored
143 144 145 146 147 148
// 6.1.2.3. Type 2
// Chunks of Type 2 are 3 bytes long. Neither the stream ID nor the
// message length is included; this chunk has the same stream ID and
// message length as the preceding chunk. Streams with constant-sized
// messages (for example, some audio and data formats) SHOULD use this
// format for the first chunk of each message after the first.
149
#define RTMP_FMT_TYPE2                          2
winlin authored
150 151 152 153 154 155 156 157 158 159 160 161 162 163
// 6.1.2.4. Type 3
// Chunks of Type 3 have no header. Stream ID, message length and
// timestamp delta are not present; chunks of this type take values from
// the preceding chunk. When a single message is split into chunks, all
// chunks of a message except the first one, SHOULD use this type. Refer
// to example 2 in section 6.2.2. Stream consisting of messages of
// exactly the same size, stream ID and spacing in time SHOULD use this
// type for all chunks after chunk of Type 2. Refer to example 1 in
// section 6.2.1. If the delta between the first message and the second
// message is same as the time stamp of first message, then chunk of
// type 3 would immediately follow the chunk of type 0 as there is no
// need for a chunk of type 2 to register the delta. If Type 3 chunk
// follows a Type 0 chunk, then timestamp delta for this Type 3 chunk is
// the same as the timestamp of Type 0 chunk.
164
#define RTMP_FMT_TYPE3                          3
winlin authored
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* 6.1. Chunk Format
* Extended timestamp: 0 or 4 bytes
* This field MUST be sent when the normal timsestamp is set to
* 0xffffff, it MUST NOT be sent if the normal timestamp is set to
* anything else. So for values less than 0xffffff the normal
* timestamp field SHOULD be used in which case the extended timestamp
* MUST NOT be present. For values greater than or equal to 0xffffff
* the normal timestamp field MUST NOT be used and MUST be set to
* 0xffffff and the extended timestamp MUST be sent.
*/
180
#define RTMP_EXTENDED_TIMESTAMP                 0xFFFFFF
winlin authored
181 182 183 184 185 186 187

/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* amf0 command message, command name macros
*/
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
#define RTMP_AMF0_COMMAND_CONNECT               "connect"
#define RTMP_AMF0_COMMAND_CREATE_STREAM         "createStream"
#define RTMP_AMF0_COMMAND_CLOSE_STREAM          "closeStream"
#define RTMP_AMF0_COMMAND_PLAY                  "play"
#define RTMP_AMF0_COMMAND_PAUSE                 "pause"
#define RTMP_AMF0_COMMAND_ON_BW_DONE            "onBWDone"
#define RTMP_AMF0_COMMAND_ON_STATUS             "onStatus"
#define RTMP_AMF0_COMMAND_RESULT                "_result"
#define RTMP_AMF0_COMMAND_ERROR                 "_error"
#define RTMP_AMF0_COMMAND_RELEASE_STREAM        "releaseStream"
#define RTMP_AMF0_COMMAND_FC_PUBLISH            "FCPublish"
#define RTMP_AMF0_COMMAND_UNPUBLISH             "FCUnpublish"
#define RTMP_AMF0_COMMAND_PUBLISH               "publish"
#define RTMP_AMF0_DATA_SAMPLE_ACCESS            "|RtmpSampleAccess"
#define RTMP_AMF0_DATA_SET_DATAFRAME            "@setDataFrame"
#define RTMP_AMF0_DATA_ON_METADATA              "onMetaData"
winlin authored
204
205 206 207 208 209 210
/**
* band width check method name, which will be invoked by client.
* band width check mothods use SrsBandwidthPacket as its internal packet type,
* so ensure you set command name when you use it.
*/
// server play control
211 212 213 214
#define SRS_BW_CHECK_START_PLAY                 "onSrsBandCheckStartPlayBytes"
#define SRS_BW_CHECK_STARTING_PLAY              "onSrsBandCheckStartingPlayBytes"
#define SRS_BW_CHECK_STOP_PLAY                  "onSrsBandCheckStopPlayBytes"
#define SRS_BW_CHECK_STOPPED_PLAY               "onSrsBandCheckStoppedPlayBytes"
215 216

// server publish control
217 218 219
#define SRS_BW_CHECK_START_PUBLISH              "onSrsBandCheckStartPublishBytes"
#define SRS_BW_CHECK_STARTING_PUBLISH           "onSrsBandCheckStartingPublishBytes"
#define SRS_BW_CHECK_STOP_PUBLISH               "onSrsBandCheckStopPublishBytes"
220
// @remark, flash never send out this packet, for its queue is full.
221
#define SRS_BW_CHECK_STOPPED_PUBLISH            "onSrsBandCheckStoppedPublishBytes"
222 223

// EOF control.
224
// the report packet when check finished.
225
#define SRS_BW_CHECK_FINISHED                   "onSrsBandCheckFinished"
226 227
// @remark, flash never send out this packet, for its queue is full.
#define SRS_BW_CHECK_FINAL                      "finalClientPacket"
228
229
// data packets
230 231
#define SRS_BW_CHECK_PLAYING                    "onSrsBandCheckPlaying"
#define SRS_BW_CHECK_PUBLISHING                 "onSrsBandCheckPublishing"
232
winlin authored
233 234 235 236 237 238 239
/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* the chunk stream id used for some under-layer message,
* for example, the PC(protocol control) message.
*/
240
#define RTMP_CID_ProtocolControl                0x02
winlin authored
241 242 243 244
/**
* the AMF0/AMF3 command message, invoke method and return the result, over NetConnection.
* generally use 0x03.
*/
245
#define RTMP_CID_OverConnection                 0x03
winlin authored
246 247 248 249 250
/**
* the AMF0/AMF3 command message, invoke method and return the result, over NetConnection, 
* the midst state(we guess).
* rarely used, e.g. onStatus(NetStream.Play.Reset).
*/
251
#define RTMP_CID_OverConnection2                0x04
winlin authored
252 253 254 255
/**
* the stream message(amf0/amf3), over NetStream.
* generally use 0x05.
*/
256
#define RTMP_CID_OverStream                     0x05
winlin authored
257 258 259 260
/**
* the stream message(amf0/amf3), over NetStream, the midst state(we guess).
* rarely used, e.g. play("mp4:mystram.f4v")
*/
261
#define RTMP_CID_OverStream2                    0x08
winlin authored
262 263 264 265
/**
* the stream message(video), over NetStream
* generally use 0x06.
*/
266
#define RTMP_CID_Video                          0x06
winlin authored
267 268 269 270
/**
* the stream message(audio), over NetStream.
* generally use 0x07.
*/
271
#define RTMP_CID_Audio                          0x07
winlin authored
272 273 274 275 276

/****************************************************************************
*****************************************************************************
****************************************************************************/
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
SrsMessageHeader::SrsMessageHeader()
{
    message_type = 0;
    payload_length = 0;
    timestamp_delta = 0;
    stream_id = 0;
    
    timestamp = 0;
    // we always use the connection chunk-id
    perfer_cid = RTMP_CID_OverConnection;
}

SrsMessageHeader::~SrsMessageHeader()
{
}

bool SrsMessageHeader::is_audio()
{
    return message_type == RTMP_MSG_AudioMessage;
}

bool SrsMessageHeader::is_video()
{
    return message_type == RTMP_MSG_VideoMessage;
}

bool SrsMessageHeader::is_amf0_command()
{
    return message_type == RTMP_MSG_AMF0CommandMessage;
}

bool SrsMessageHeader::is_amf0_data()
{
    return message_type == RTMP_MSG_AMF0DataMessage;
}

bool SrsMessageHeader::is_amf3_command()
{
    return message_type == RTMP_MSG_AMF3CommandMessage;
}

bool SrsMessageHeader::is_amf3_data()
{
    return message_type == RTMP_MSG_AMF3DataMessage;
}

bool SrsMessageHeader::is_window_ackledgement_size()
{
    return message_type == RTMP_MSG_WindowAcknowledgementSize;
}

bool SrsMessageHeader::is_ackledgement()
{
    return message_type == RTMP_MSG_Acknowledgement;
}

bool SrsMessageHeader::is_set_chunk_size()
{
    return message_type == RTMP_MSG_SetChunkSize;
}

bool SrsMessageHeader::is_user_control_message()
{
    return message_type == RTMP_MSG_UserControlMessage;
}

bool SrsMessageHeader::is_set_peer_bandwidth()
{
    return message_type == RTMP_MSG_SetPeerBandwidth;
}

bool SrsMessageHeader::is_aggregate()
{
    return message_type == RTMP_MSG_AggregateMessage;
}

void SrsMessageHeader::initialize_amf0_script(int size, int stream)
{
    message_type = RTMP_MSG_AMF0DataMessage;
    payload_length = (int32_t)size;
    timestamp_delta = (int32_t)0;
    timestamp = (int64_t)0;
    stream_id = (int32_t)stream;
    
    // amf0 script use connection2 chunk-id
    perfer_cid = RTMP_CID_OverConnection2;
}

void SrsMessageHeader::initialize_audio(int size, u_int32_t time, int stream)
{
    message_type = RTMP_MSG_AudioMessage;
    payload_length = (int32_t)size;
    timestamp_delta = (int32_t)time;
    timestamp = (int64_t)time;
    stream_id = (int32_t)stream;
    
    // audio chunk-id
    perfer_cid = RTMP_CID_Audio;
}

void SrsMessageHeader::initialize_video(int size, u_int32_t time, int stream)
{
    message_type = RTMP_MSG_VideoMessage;
    payload_length = (int32_t)size;
    timestamp_delta = (int32_t)time;
    timestamp = (int64_t)time;
    stream_id = (int32_t)stream;
    
    // video chunk-id
    perfer_cid = RTMP_CID_Video;
}

SrsMessage::SrsMessage()
{
    payload = NULL;
    size = 0;
}

SrsMessage::~SrsMessage()
{
}
winlin authored
399 400
SrsProtocol::AckWindowSize::AckWindowSize()
{
401 402
    ack_window_size = 0;
    acked_size = 0;
winlin authored
403 404
}
405
SrsProtocol::SrsProtocol(ISrsProtocolReaderWriter* io)
winlin authored
406
{
407
    in_buffer = new SrsBuffer();
408 409
    skt = io;
    
410 411 412 413 414 415 416 417
    in_chunk_size = SRS_CONSTS_RTMP_PROTOCOL_CHUNK_SIZE;
    out_chunk_size = SRS_CONSTS_RTMP_PROTOCOL_CHUNK_SIZE;
    
    nb_out_iovs = SRS_CONSTS_IOVS_MAX;
    out_iovs = (iovec*)malloc(sizeof(iovec) * nb_out_iovs);
    // each chunk consumers atleast 2 iovs
    srs_assert(nb_out_iovs >= 2);
    
winlin authored
418
    warned_c0c3_cache_dry = false;
419
    auto_response_when_recv = true;
winlin authored
420 421 422 423
}

SrsProtocol::~SrsProtocol()
{
424
    if (true) {
425
        std::map<int, SrsChunkStream*>::iterator it;
426
        
427 428
        for (it = chunk_streams.begin(); it != chunk_streams.end(); ++it) {
            SrsChunkStream* stream = it->second;
429 430 431
            srs_freep(stream);
        }
    
432
        chunk_streams.clear();
433 434
    }
    
435 436 437 438 439 440 441 442 443
    if (true) {
        std::vector<SrsPacket*>::iterator it;
        for (it = manual_response_queue.begin(); it != manual_response_queue.end(); ++it) {
            SrsPacket* pkt = *it;
            srs_freep(pkt);
        }
        manual_response_queue.clear();
    }
    
444
    srs_freep(in_buffer);
445 446 447 448 449 450
    
    // alloc by malloc, use free directly.
    if (out_iovs) {
        free(out_iovs);
        out_iovs = NULL;
    }
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 477 478 479 480 481
void SrsProtocol::set_auto_response(bool v)
{
    auto_response_when_recv = v;
}

int SrsProtocol::manual_response_flush()
{
    int ret = ERROR_SUCCESS;
    
    if (manual_response_queue.empty()) {
        return ret;
    }
    
    std::vector<SrsPacket*>::iterator it;
    for (it = manual_response_queue.begin(); it != manual_response_queue.end();) {
        SrsPacket* pkt = *it;
        
        // erase this packet, the send api always free it.
        it = manual_response_queue.erase(it);
        
        // use underlayer api to send, donot flush again.
        if ((ret = do_send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
            return ret;
        }
    }
    
    return ret;
}
482
void SrsProtocol::set_merge_read(bool v, int max_buffer, IMergeReadHandler* handler)
483
{
484
    in_buffer->set_merge_read(v, max_buffer, handler);
485 486
}
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
void SrsProtocol::set_recv_timeout(int64_t timeout_us)
{
    return skt->set_recv_timeout(timeout_us);
}

int64_t SrsProtocol::get_recv_timeout()
{
    return skt->get_recv_timeout();
}

void SrsProtocol::set_send_timeout(int64_t timeout_us)
{
    return skt->set_send_timeout(timeout_us);
}

int64_t SrsProtocol::get_send_timeout()
{
    return skt->get_send_timeout();
}

int64_t SrsProtocol::get_recv_bytes()
{
    return skt->get_recv_bytes();
}

int64_t SrsProtocol::get_send_bytes()
{
    return skt->get_send_bytes();
}
517
int SrsProtocol::recv_message(SrsMessage** pmsg)
518 519 520 521 522 523
{
    *pmsg = NULL;
    
    int ret = ERROR_SUCCESS;
    
    while (true) {
524
        SrsMessage* msg = NULL;
525
        
526
        if ((ret = recv_interlaced_message(&msg)) != ERROR_SUCCESS) {
527 528 529
            if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
                srs_error("recv interlaced message failed. ret=%d", ret);
            }
530
            srs_freep(msg);
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
            return ret;
        }
        srs_verbose("entire msg received");
        
        if (!msg) {
            continue;
        }
        
        if (msg->size <= 0 || msg->header.payload_length <= 0) {
            srs_trace("ignore empty message(type=%d, size=%d, time=%"PRId64", sid=%d).",
                msg->header.message_type, msg->header.payload_length,
                msg->header.timestamp, msg->header.stream_id);
            srs_freep(msg);
            continue;
        }
        
547
        if ((ret = on_recv_message(msg)) != ERROR_SUCCESS) {
548 549 550 551 552
            srs_error("hook the received msg failed. ret=%d", ret);
            srs_freep(msg);
            return ret;
        }
        
winlin authored
553
        srs_verbose("got a msg, cid=%d, type=%d, size=%d, time=%"PRId64, 
winlin authored
554 555
            msg->header.perfer_cid, msg->header.message_type, msg->header.payload_length, 
            msg->header.timestamp);
556 557 558 559 560 561 562
        *pmsg = msg;
        break;
    }
    
    return ret;
}
563
int SrsProtocol::decode_message(SrsMessage* msg, SrsPacket** ppacket)
564 565 566 567 568 569 570 571
{
    *ppacket = NULL;
    
    int ret = ERROR_SUCCESS;
    
    srs_assert(msg != NULL);
    srs_assert(msg->payload != NULL);
    srs_assert(msg->size > 0);
572 573
    
    SrsStream stream;
574 575 576

    // initialize the decode stream for all message,
    // it's ok for the initialize if fast and without memory copy.
577
    if ((ret = stream.initialize(msg->payload, msg->size)) != ERROR_SUCCESS) {
578 579 580 581 582 583 584
        srs_error("initialize stream failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("decode stream initialized success");
    
    // decode the packet.
    SrsPacket* packet = NULL;
585
    if ((ret = do_decode_message(msg->header, &stream, &packet)) != ERROR_SUCCESS) {
586 587 588 589 590 591 592 593 594 595
        srs_freep(packet);
        return ret;
    }
    
    // set to output ppacket only when success.
    *ppacket = packet;
    
    return ret;
}
596
int SrsProtocol::do_send_messages(SrsMessage** msgs, int nb_msgs)
597
{
598 599 600 601 602 603 604 605 606 607 608 609 610
    int ret = ERROR_SUCCESS;
    
    // TODO: FIXME: use cache system instead.
    int iov_index = 0;
    iovec* iov = out_iovs + iov_index;
    
    int c0c3_cache_index = 0;
    char* c0c3_cache = out_c0c3_caches + c0c3_cache_index;

    // try to send use the c0c3 header cache,
    // if cache is consumed, try another loop.
    for (int i = 0; i < nb_msgs; i++) {
        SrsMessage* msg = msgs[i];
611
    
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
        // ignore empty message.
        if (!msg->payload || msg->size <= 0) {
            srs_info("ignore empty message.");
            continue;
        }
        
        // we donot use the complex basic header,
        // ensure the basic header is 1bytes.
        if (msg->header.perfer_cid < 2) {
            srs_warn("change the chunk_id=%d to default=%d", 
                msg->header.perfer_cid, RTMP_CID_ProtocolControl);
            msg->header.perfer_cid = RTMP_CID_ProtocolControl;
        }
    
        // p set to current write position,
        // it's ok when payload is NULL and size is 0.
        char* p = msg->payload;
        char* pend = msg->payload + msg->size;
        
        // always write the header event payload is empty.
        while (p < pend) {
            // always has header
            int nbh = 0;
            char* header = NULL;
            generate_chunk_header(c0c3_cache, &msg->header, p == msg->payload, &nbh, &header);
            srs_assert(nbh > 0);
            
            // header iov
            iov[0].iov_base = header;
            iov[0].iov_len = nbh;
            
            // payload iov
            int payload_size = pend - p;
            if (payload_size > out_chunk_size) {
                payload_size = out_chunk_size;
            }
            iov[1].iov_base = p;
            iov[1].iov_len = payload_size;
            
            // consume sendout bytes.
            p += payload_size;
            
            // realloc the iovs if exceed,
            // for we donot know how many messges maybe to send entirely,
            // we just alloc the iovs, it's ok.
            if (iov_index >= nb_out_iovs - 2) {
                nb_out_iovs += SRS_CONSTS_IOVS_MAX;
                int realloc_size = sizeof(iovec) * nb_out_iovs;
                out_iovs = (iovec*)realloc(out_iovs, realloc_size);
            }
            
            // to next pair of iovs
            iov_index += 2;
            iov = out_iovs + iov_index;

            // to next c0c3 header cache
            c0c3_cache_index += nbh;
            c0c3_cache = out_c0c3_caches + c0c3_cache_index;
            
            // the cache header should never be realloc again,
            // for the ptr is set to iovs, so we just warn user to set larger
            // and use another loop to send again.
            int c0c3_left = SRS_CONSTS_C0C3_HEADERS_MAX - c0c3_cache_index;
            if (c0c3_left < SRS_CONSTS_RTMP_MAX_FMT0_HEADER_SIZE) {
                // only warn once for a connection.
winlin authored
677
                if (!warned_c0c3_cache_dry) {
678 679
                    srs_warn("c0c3 cache header too small, recoment to %d", 
                        SRS_CONSTS_C0C3_HEADERS_MAX + SRS_CONSTS_RTMP_MAX_FMT0_HEADER_SIZE);
winlin authored
680
                    warned_c0c3_cache_dry = true;
681 682 683 684 685
                }
                
                // when c0c3 cache dry,
                // sendout all messages and reset the cache, then send again.
                if ((ret = skt->writev(out_iovs, iov_index, NULL)) != ERROR_SUCCESS) {
686 687 688
                    if (!srs_is_client_gracefully_close(ret)) {
                        srs_error("send with writev failed. ret=%d", ret);
                    }
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
                    return ret;
                }
    
                // reset caches, while these cache ensure 
                // atleast we can sendout a chunk.
                iov_index = 0;
                iov = out_iovs + iov_index;
                
                c0c3_cache_index = 0;
                c0c3_cache = out_c0c3_caches + c0c3_cache_index;
            }
        }
    }
    
    // maybe the iovs already sendout when c0c3 cache dry,
    // so just ignore when no iovs to send.
    if (iov_index <= 0) {
        return ret;
    }
    
    // send by writev
    // sendout header and payload by writev.
    // decrease the sys invoke count to get higher performance.
    if ((ret = skt->writev(out_iovs, iov_index, NULL)) != ERROR_SUCCESS) {
713 714 715
        if (!srs_is_client_gracefully_close(ret)) {
            srs_error("send with writev failed. ret=%d", ret);
        }
716 717 718 719 720 721
        return ret;
    }
    
    return ret;
}
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
int SrsProtocol::do_send_and_free_packet(SrsPacket* packet, int stream_id)
{
    int ret = ERROR_SUCCESS;
    
    srs_assert(packet);
    SrsAutoFree(SrsPacket, packet);
    
    int size = 0;
    char* payload = NULL;
    if ((ret = packet->encode(size, payload)) != ERROR_SUCCESS) {
        srs_error("encode RTMP packet to bytes oriented RTMP message failed. ret=%d", ret);
        return ret;
    }
    
    // encode packet to payload and size.
    if (size <= 0 || payload == NULL) {
        srs_warn("packet is empty, ignore empty message.");
        return ret;
    }
    
    // to message
    SrsMessage* msg = new SrsCommonMessage();
    
    msg->payload = payload;
    msg->size = size;
    
    msg->header.payload_length = size;
    msg->header.message_type = packet->get_message_type();
    msg->header.stream_id = stream_id;
    msg->header.perfer_cid = packet->get_prefer_cid();

    // donot use the auto free to free the msg,
    // for performance issue.
    ret = do_send_messages(&msg, 1);
    if (ret == ERROR_SUCCESS) {
        ret = on_send_packet(msg, packet);
    }
    srs_freep(msg);
    
    return ret;
}
764 765
void SrsProtocol::generate_chunk_header(char* cache, SrsMessageHeader* mh, bool c0, int* pnbh, char** ph) 
{
766 767 768 769 770 771
    // to directly set the field.
    char* pp = NULL;
    
    // generate the header.
    char* p = cache;
    
772 773 774
    // timestamp for c0/c3
    u_int32_t timestamp = (u_int32_t)mh->timestamp;
    
775 776 777
    if (c0) {
        // write new chunk stream header, fmt is 0
        *p++ = 0x00 | (mh->perfer_cid & 0x3F);
778
        
779 780 781 782 783 784 785 786 787 788 789 790
        // chunk message header, 11 bytes
        // timestamp, 3bytes, big-endian
        if (timestamp < RTMP_EXTENDED_TIMESTAMP) {
            pp = (char*)&timestamp;
            *p++ = pp[2];
            *p++ = pp[1];
            *p++ = pp[0];
        } else {
            *p++ = 0xFF;
            *p++ = 0xFF;
            *p++ = 0xFF;
        }
791
        
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
        // message_length, 3bytes, big-endian
        pp = (char*)&mh->payload_length;
        *p++ = pp[2];
        *p++ = pp[1];
        *p++ = pp[0];
        
        // message_type, 1bytes
        *p++ = mh->message_type;
        
        // message_length, 3bytes, little-endian
        pp = (char*)&mh->stream_id;
        *p++ = pp[0];
        *p++ = pp[1];
        *p++ = pp[2];
        *p++ = pp[3];
    } else {
        // write no message header chunk stream, fmt is 3
        // @remark, if perfer_cid > 0x3F, that is, use 2B/3B chunk header,
        // SRS will rollback to 1B chunk header.
        *p++ = 0xC0 | (mh->perfer_cid & 0x3F);
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
    }
    
    // for c0
    // chunk extended timestamp header, 0 or 4 bytes, big-endian
    // 
    // for c3:
    // chunk extended timestamp header, 0 or 4 bytes, big-endian
    // 6.1.3. Extended Timestamp
    // This field is transmitted only when the normal time stamp in the
    // chunk message header is set to 0x00ffffff. If normal time stamp is
    // set to any value less than 0x00ffffff, this field MUST NOT be
    // present. This field MUST NOT be present if the timestamp field is not
    // present. Type 3 chunks MUST NOT have this field.
    // adobe changed for Type3 chunk:
    //        FMLE always sendout the extended-timestamp,
    //        must send the extended-timestamp to FMS,
    //        must send the extended-timestamp to flash-player.
    // @see: ngx_rtmp_prepare_message
    // @see: http://blog.csdn.net/win_lin/article/details/13363699
    // TODO: FIXME: extract to outer.
    if (timestamp >= RTMP_EXTENDED_TIMESTAMP) {
        pp = (char*)&timestamp;
        *p++ = pp[3];
        *p++ = pp[2];
        *p++ = pp[1];
        *p++ = pp[0];
838 839
    }
    
840 841 842
    // always has header
    *pnbh = p - cache;
    *ph = cache;
843 844
}
845
int SrsProtocol::do_decode_message(SrsMessageHeader& header, SrsStream* stream, SrsPacket** ppacket)
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 873 874 875 876 877 878 879
{
    int ret = ERROR_SUCCESS;
    
    SrsPacket* packet = NULL;
    
    // decode specified packet type
    if (header.is_amf0_command() || header.is_amf3_command() || header.is_amf0_data() || header.is_amf3_data()) {
        srs_verbose("start to decode AMF0/AMF3 command message.");
        
        // skip 1bytes to decode the amf3 command.
        if (header.is_amf3_command() && stream->require(1)) {
            srs_verbose("skip 1bytes to decode AMF3 command");
            stream->skip(1);
        }
        
        // amf0 command message.
        // need to read the command name.
        std::string command;
        if ((ret = srs_amf0_read_string(stream, command)) != ERROR_SUCCESS) {
            srs_error("decode AMF0/AMF3 command name failed. ret=%d", ret);
            return ret;
        }
        srs_verbose("AMF0/AMF3 command message, command_name=%s", command.c_str());
        
        // result/error packet
        if (command == RTMP_AMF0_COMMAND_RESULT || command == RTMP_AMF0_COMMAND_ERROR) {
            double transactionId = 0.0;
            if ((ret = srs_amf0_read_number(stream, transactionId)) != ERROR_SUCCESS) {
                srs_error("decode AMF0/AMF3 transcationId failed. ret=%d", ret);
                return ret;
            }
            srs_verbose("AMF0/AMF3 command id, transcationId=%.2f", transactionId);
            
            // reset stream, for header read completed.
880
            stream->skip(-1 * stream->pos());
881 882 883 884
            if (header.is_amf3_command()) {
                stream->skip(1);
            }
            
885 886
            // find the call name
            if (requests.find(transactionId) == requests.end()) {
887 888 889 890
                ret = ERROR_RTMP_NO_REQUEST;
                srs_error("decode AMF0/AMF3 request failed. ret=%d", ret);
                return ret;
            }
891 892
            
            std::string request_name = requests[transactionId];
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
            srs_verbose("AMF0/AMF3 request parsed. request_name=%s", request_name.c_str());

            if (request_name == RTMP_AMF0_COMMAND_CONNECT) {
                srs_info("decode the AMF0/AMF3 response command(%s message).", request_name.c_str());
                *ppacket = packet = new SrsConnectAppResPacket();
                return packet->decode(stream);
            } else if (request_name == RTMP_AMF0_COMMAND_CREATE_STREAM) {
                srs_info("decode the AMF0/AMF3 response command(%s message).", request_name.c_str());
                *ppacket = packet = new SrsCreateStreamResPacket(0, 0);
                return packet->decode(stream);
            } else if (request_name == RTMP_AMF0_COMMAND_RELEASE_STREAM
                || request_name == RTMP_AMF0_COMMAND_FC_PUBLISH
                || request_name == RTMP_AMF0_COMMAND_UNPUBLISH) {
                srs_info("decode the AMF0/AMF3 response command(%s message).", request_name.c_str());
                *ppacket = packet = new SrsFMLEStartResPacket(0);
                return packet->decode(stream);
            } else {
                ret = ERROR_RTMP_NO_REQUEST;
                srs_error("decode AMF0/AMF3 request failed. "
                    "request_name=%s, transactionId=%.2f, ret=%d", 
                    request_name.c_str(), transactionId, ret);
                return ret;
            }
        }
        
        // reset to zero(amf3 to 1) to restart decode.
919
        stream->skip(-1 * stream->pos());
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
        if (header.is_amf3_command()) {
            stream->skip(1);
        }
        
        // decode command object.
        if (command == RTMP_AMF0_COMMAND_CONNECT) {
            srs_info("decode the AMF0/AMF3 command(connect vhost/app message).");
            *ppacket = packet = new SrsConnectAppPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_CREATE_STREAM) {
            srs_info("decode the AMF0/AMF3 command(createStream message).");
            *ppacket = packet = new SrsCreateStreamPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_PLAY) {
            srs_info("decode the AMF0/AMF3 command(paly message).");
            *ppacket = packet = new SrsPlayPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_PAUSE) {
            srs_info("decode the AMF0/AMF3 command(pause message).");
            *ppacket = packet = new SrsPausePacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_RELEASE_STREAM) {
            srs_info("decode the AMF0/AMF3 command(FMLE releaseStream message).");
            *ppacket = packet = new SrsFMLEStartPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_FC_PUBLISH) {
            srs_info("decode the AMF0/AMF3 command(FMLE FCPublish message).");
            *ppacket = packet = new SrsFMLEStartPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_PUBLISH) {
            srs_info("decode the AMF0/AMF3 command(publish message).");
            *ppacket = packet = new SrsPublishPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_UNPUBLISH) {
            srs_info("decode the AMF0/AMF3 command(unpublish message).");
            *ppacket = packet = new SrsFMLEStartPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_DATA_SET_DATAFRAME || command == RTMP_AMF0_DATA_ON_METADATA) {
            srs_info("decode the AMF0/AMF3 data(onMetaData message).");
            *ppacket = packet = new SrsOnMetaDataPacket();
            return packet->decode(stream);
        } else if(command == SRS_BW_CHECK_FINISHED
            || command == SRS_BW_CHECK_PLAYING
            || command == SRS_BW_CHECK_PUBLISHING
            || command == SRS_BW_CHECK_STARTING_PLAY
            || command == SRS_BW_CHECK_STARTING_PUBLISH
            || command == SRS_BW_CHECK_START_PLAY
            || command == SRS_BW_CHECK_START_PUBLISH
            || command == SRS_BW_CHECK_STOPPED_PLAY
            || command == SRS_BW_CHECK_STOP_PLAY
            || command == SRS_BW_CHECK_STOP_PUBLISH
            || command == SRS_BW_CHECK_STOPPED_PUBLISH
972
            || command == SRS_BW_CHECK_FINAL)
973 974 975 976 977 978 979 980
        {
            srs_info("decode the AMF0/AMF3 band width check message.");
            *ppacket = packet = new SrsBandwidthPacket();
            return packet->decode(stream);
        } else if (command == RTMP_AMF0_COMMAND_CLOSE_STREAM) {
            srs_info("decode the AMF0/AMF3 closeStream message.");
            *ppacket = packet = new SrsCloseStreamPacket();
            return packet->decode(stream);
981 982 983 984
        } else if (header.is_amf0_command() || header.is_amf3_command()) {
            srs_info("decode the AMF0/AMF3 call message.");
            *ppacket = packet = new SrsCallPacket();
            return packet->decode(stream);
985 986 987
        }
        
        // default packet to drop message.
winlin authored
988
        srs_info("drop the AMF0/AMF3 command message, command_name=%s", command.c_str());
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
        *ppacket = packet = new SrsPacket();
        return ret;
    } else if(header.is_user_control_message()) {
        srs_verbose("start to decode user control message.");
        *ppacket = packet = new SrsUserControlPacket();
        return packet->decode(stream);
    } else if(header.is_window_ackledgement_size()) {
        srs_verbose("start to decode set ack window size message.");
        *ppacket = packet = new SrsSetWindowAckSizePacket();
        return packet->decode(stream);
    } else if(header.is_set_chunk_size()) {
        srs_verbose("start to decode set chunk size message.");
        *ppacket = packet = new SrsSetChunkSizePacket();
        return packet->decode(stream);
    } else {
1004
        if (!header.is_set_peer_bandwidth() && !header.is_ackledgement()) {
winlin authored
1005 1006
            srs_trace("drop unknown message, type=%d", header.message_type);
        }
1007 1008 1009 1010 1011
    }
    
    return ret;
}
1012
int SrsProtocol::send_and_free_message(SrsMessage* msg, int stream_id)
1013
{
1014
    return send_and_free_messages(&msg, 1, stream_id);
1015 1016
}
1017
int SrsProtocol::send_and_free_messages(SrsMessage** msgs, int nb_msgs, int stream_id)
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
{
    // always not NULL msg.
    srs_assert(msgs);
    srs_assert(nb_msgs > 0);
    
    // update the stream id in header.
    for (int i = 0; i < nb_msgs; i++) {
        SrsMessage* msg = msgs[i];
        // we assume that the stream_id in a group must be the same.
        if (msg->header.stream_id == stream_id) {
            break;
        }
        msg->header.stream_id = stream_id;
    }
    
    // donot use the auto free to free the msg,
    // for performance issue.
    int ret = do_send_messages(msgs, nb_msgs);
    
    for (int i = 0; i < nb_msgs; i++) {
        SrsMessage* msg = msgs[i];
        srs_freep(msg);
    }
    
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    // donot flush when send failed
    if (ret != ERROR_SUCCESS) {
        return ret;
    }
    
    // flush messages in manual queue
    if ((ret = manual_response_flush()) != ERROR_SUCCESS) {
        return ret;
    }
    
1052 1053 1054
    return ret;
}
1055
int SrsProtocol::send_and_free_packet(SrsPacket* packet, int stream_id)
1056 1057 1058
{
    int ret = ERROR_SUCCESS;
    
1059
    if ((ret = do_send_and_free_packet(packet, stream_id)) != ERROR_SUCCESS) {
1060 1061 1062
        return ret;
    }
    
1063 1064
    // flush messages in manual queue
    if ((ret = manual_response_flush()) != ERROR_SUCCESS) {
1065 1066 1067 1068 1069 1070
        return ret;
    }
    
    return ret;
}
1071
int SrsProtocol::recv_interlaced_message(SrsMessage** pmsg)
1072 1073 1074 1075 1076 1077 1078
{
    int ret = ERROR_SUCCESS;
    
    // chunk stream basic header.
    char fmt = 0;
    int cid = 0;
    int bh_size = 0;
1079
    if ((ret = read_basic_header(fmt, cid, bh_size)) != ERROR_SUCCESS) {
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
            srs_error("read basic header failed. ret=%d", ret);
        }
        return ret;
    }
    srs_verbose("read basic header success. fmt=%d, cid=%d, bh_size=%d", fmt, cid, bh_size);
    
    // once we got the chunk message header, 
    // that is there is a real message in cache,
    // increase the timeout to got it.
    // For example, in the play loop, we set timeout to 100ms,
    // when we got a chunk header, we should increase the timeout,
    // or we maybe timeout and disconnect the client.
    int64_t timeout_us = skt->get_recv_timeout();
    if (!skt->is_never_timeout(timeout_us)) {
        int64_t pkt_timeout_us = srs_max(timeout_us, SRS_MIN_RECV_TIMEOUT_US);
        skt->set_recv_timeout(pkt_timeout_us);
        srs_verbose("change recv timeout_us "
            "from %"PRId64" to %"PRId64"", timeout_us, pkt_timeout_us);
    }
    
    // get the cached chunk stream.
1102
    SrsChunkStream* chunk = NULL;
1103
    
1104 1105
    if (chunk_streams.find(cid) == chunk_streams.end()) {
        chunk = chunk_streams[cid] = new SrsChunkStream(cid);
winlin authored
1106 1107 1108
        // set the perfer cid of chunk,
        // which will copy to the message received.
        chunk->header.perfer_cid = cid;
1109 1110
        srs_verbose("cache new chunk stream: fmt=%d, cid=%d", fmt, cid);
    } else {
1111
        chunk = chunk_streams[cid];
1112 1113 1114 1115 1116 1117 1118
        srs_verbose("cached chunk stream: fmt=%d, cid=%d, size=%d, message(type=%d, size=%d, time=%"PRId64", sid=%d)",
            chunk->fmt, chunk->cid, (chunk->msg? chunk->msg->size : 0), chunk->header.message_type, chunk->header.payload_length,
            chunk->header.timestamp, chunk->header.stream_id);
    }

    // chunk stream message header
    int mh_size = 0;
1119
    if ((ret = read_message_header(chunk, fmt, bh_size, mh_size)) != ERROR_SUCCESS) {
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
        if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
            srs_error("read message header failed. ret=%d", ret);
        }
        return ret;
    }
    srs_verbose("read message header success. "
            "fmt=%d, mh_size=%d, ext_time=%d, size=%d, message(type=%d, size=%d, time=%"PRId64", sid=%d)", 
            fmt, mh_size, chunk->extended_timestamp, (chunk->msg? chunk->msg->size : 0), chunk->header.message_type, 
            chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id);
    
    // read msg payload from chunk stream.
1131
    SrsMessage* msg = NULL;
1132
    int payload_size = 0;
1133
    if ((ret = read_message_payload(chunk, bh_size, mh_size, payload_size, &msg)) != ERROR_SUCCESS) {
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
        if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
            srs_error("read message payload failed. ret=%d", ret);
        }
        return ret;
    }
    
    // reset the recv timeout
    if (!skt->is_never_timeout(timeout_us)) {
        skt->set_recv_timeout(timeout_us);
        srs_verbose("reset recv timeout_us to %"PRId64"", timeout_us);
    }
    
    // not got an entire RTMP message, try next chunk.
    if (!msg) {
        srs_verbose("get partial message success. chunk_payload_size=%d, size=%d, message(type=%d, size=%d, time=%"PRId64", sid=%d)",
                payload_size, (msg? msg->size : (chunk->msg? chunk->msg->size : 0)), chunk->header.message_type, chunk->header.payload_length,
                chunk->header.timestamp, chunk->header.stream_id);
        return ret;
    }
    
    *pmsg = msg;
    srs_info("get entire message success. chunk_payload_size=%d, size=%d, message(type=%d, size=%d, time=%"PRId64", sid=%d)",
            payload_size, (msg? msg->size : (chunk->msg? chunk->msg->size : 0)), chunk->header.message_type, chunk->header.payload_length,
            chunk->header.timestamp, chunk->header.stream_id);
            
    return ret;
}
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
/**
* 6.1.1. Chunk Basic Header
* The Chunk Basic Header encodes the chunk stream ID and the chunk
* type(represented by fmt field in the figure below). Chunk type
* determines the format of the encoded message header. Chunk Basic
* Header field may be 1, 2, or 3 bytes, depending on the chunk stream
* ID.
* 
* The bits 0–5 (least significant) in the chunk basic header represent
* the chunk stream ID.
*
* Chunk stream IDs 2-63 can be encoded in the 1-byte version of this
* field.
*    0 1 2 3 4 5 6 7
*   +-+-+-+-+-+-+-+-+
*   |fmt|   cs id   |
*   +-+-+-+-+-+-+-+-+
*   Figure 6 Chunk basic header 1
*
* Chunk stream IDs 64-319 can be encoded in the 2-byte version of this
* field. ID is computed as (the second byte + 64).
*   0                   1
*   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
*   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*   |fmt|    0      | cs id - 64    |
*   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*   Figure 7 Chunk basic header 2
*
* Chunk stream IDs 64-65599 can be encoded in the 3-byte version of
* this field. ID is computed as ((the third byte)*256 + the second byte
* + 64).
*    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
*   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*   |fmt|     1     |         cs id - 64            |
*   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*   Figure 8 Chunk basic header 3
*
* cs id: 6 bits
* fmt: 2 bits
* cs id - 64: 8 or 16 bits
* 
* Chunk stream IDs with values 64-319 could be represented by both 2-
* byte version and 3-byte version of this field.
*/
1206
int SrsProtocol::read_basic_header(char& fmt, int& cid, int& bh_size)
1207 1208 1209 1210
{
    int ret = ERROR_SUCCESS;
    
    int required_size = 1;
1211
    if ((ret = in_buffer->grow(skt, required_size)) != ERROR_SUCCESS) {
1212 1213 1214 1215 1216 1217
        if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
            srs_error("read 1bytes basic header failed. required_size=%d, ret=%d", required_size, ret);
        }
        return ret;
    }
    
1218
    char* p = in_buffer->bytes();
1219 1220 1221 1222 1223
    
    fmt = (*p >> 6) & 0x03;
    cid = *p & 0x3f;
    bh_size = 1;
    
1224
    // 2-63, 1B chunk header
1225 1226 1227 1228 1229
    if (cid > 1) {
        srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid);
        return ret;
    }
1230
    // 64-319, 2B chunk header
1231 1232
    if (cid == 0) {
        required_size = 2;
1233
        if ((ret = in_buffer->grow(skt, required_size)) != ERROR_SUCCESS) {
1234 1235 1236 1237 1238 1239 1240
            if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
                srs_error("read 2bytes basic header failed. required_size=%d, ret=%d", required_size, ret);
            }
            return ret;
        }
        
        cid = 64;
1241
        cid += (u_int8_t)*(++p);
1242 1243
        bh_size = 2;
        srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid);
1244
    // 64-65599, 3B chunk header
1245 1246
    } else if (cid == 1) {
        required_size = 3;
1247
        if ((ret = in_buffer->grow(skt, 3)) != ERROR_SUCCESS) {
1248 1249 1250 1251 1252 1253 1254
            if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
                srs_error("read 3bytes basic header failed. required_size=%d, ret=%d", required_size, ret);
            }
            return ret;
        }
        
        cid = 64;
1255 1256
        cid += (u_int8_t)*(++p);
        cid += ((u_int8_t)*(++p)) * 256;
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
        bh_size = 3;
        srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid);
    } else {
        srs_error("invalid path, impossible basic header.");
        srs_assert(false);
    }
    
    return ret;
}
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
/**
* parse the message header.
*   3bytes: timestamp delta,    fmt=0,1,2
*   3bytes: payload length,     fmt=0,1
*   1bytes: message type,       fmt=0,1
*   4bytes: stream id,          fmt=0
* where:
*   fmt=0, 0x0X
*   fmt=1, 0x4X
*   fmt=2, 0x8X
*   fmt=3, 0xCX
*/
1279
int SrsProtocol::read_message_header(SrsChunkStream* chunk, char fmt, int bh_size, int& mh_size)
1280 1281 1282 1283 1284 1285 1286 1287
{
    int ret = ERROR_SUCCESS;
    
    /**
    * we should not assert anything about fmt, for the first packet.
    * (when first packet, the chunk->msg is NULL).
    * the fmt maybe 0/1/2/3, the FMLE will send a 0xC4 for some audio packet.
    * the previous packet is:
1288 1289 1290 1291 1292
    *     04                // fmt=0, cid=4
    *     00 00 1a          // timestamp=26
    *     00 00 9d          // payload_length=157
    *     08                // message_type=8(audio)
    *     01 00 00 00       // stream_id=1
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
    * the current packet maybe:
    *     c4             // fmt=3, cid=4
    * it's ok, for the packet is audio, and timestamp delta is 26.
    * the current packet must be parsed as:
    *     fmt=0, cid=4
    *     timestamp=26+26=52
    *     payload_length=157
    *     message_type=8(audio)
    *     stream_id=1
    * so we must update the timestamp even fmt=3 for first packet.
    */
    // fresh packet used to update the timestamp even fmt=3 for first packet.
1305 1306
    // fresh packet always means the chunk is the first one of message.
    bool is_first_chunk_of_msg = !chunk->msg;
1307 1308 1309 1310
    
    // but, we can ensure that when a chunk stream is fresh, 
    // the fmt must be 0, a new stream.
    if (chunk->msg_count == 0 && fmt != RTMP_FMT_TYPE0) {
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
        // for librtmp, if ping, it will send a fresh stream with fmt=1,
        // 0x42             where: fmt=1, cid=2, protocol contorl user-control message
        // 0x00 0x00 0x00   where: timestamp=0
        // 0x00 0x00 0x06   where: payload_length=6
        // 0x04             where: message_type=4(protocol control user-control message)
        // 0x00 0x06            where: event Ping(0x06)
        // 0x00 0x00 0x0d 0x0f  where: event data 4bytes ping timestamp.
        // @see: https://github.com/winlinvip/simple-rtmp-server/issues/98
        if (chunk->cid == RTMP_CID_ProtocolControl && fmt == RTMP_FMT_TYPE1) {
            srs_warn("accept cid=2, fmt=1 to make librtmp happy.");
        } else {
            // must be a RTMP protocol level error.
            ret = ERROR_RTMP_CHUNK_START;
            srs_error("chunk stream is fresh, fmt must be %d, actual is %d. cid=%d, ret=%d", 
                RTMP_FMT_TYPE0, fmt, chunk->cid, ret);
            return ret;
        }
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    }

    // when exists cache msg, means got an partial message,
    // the fmt must not be type0 which means new message.
    if (chunk->msg && fmt == RTMP_FMT_TYPE0) {
        ret = ERROR_RTMP_CHUNK_START;
        srs_error("chunk stream exists, "
            "fmt must not be %d, actual is %d. ret=%d", RTMP_FMT_TYPE0, fmt, ret);
        return ret;
    }
    
    // create msg when new chunk stream start
    if (!chunk->msg) {
1341
        chunk->msg = new SrsCommonMessage();
1342 1343 1344 1345 1346 1347 1348 1349 1350
        srs_verbose("create message for new chunk, fmt=%d, cid=%d", fmt, chunk->cid);
    }

    // read message header from socket to buffer.
    static char mh_sizes[] = {11, 7, 3, 0};
    mh_size = mh_sizes[(int)fmt];
    srs_verbose("calc chunk message header size. fmt=%d, mh_size=%d", fmt, mh_size);
    
    int required_size = bh_size + mh_size;
1351
    if ((ret = in_buffer->grow(skt, required_size)) != ERROR_SUCCESS) {
1352 1353 1354 1355 1356
        if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
            srs_error("read %dbytes message header failed. required_size=%d, ret=%d", mh_size, required_size, ret);
        }
        return ret;
    }
1357
    char* p = in_buffer->bytes() + bh_size;
1358
    
1359 1360 1361 1362 1363 1364
    /**
    * parse the message header.
    *   3bytes: timestamp delta,    fmt=0,1,2
    *   3bytes: payload length,     fmt=0,1
    *   1bytes: message type,       fmt=0,1
    *   4bytes: stream id,          fmt=0
1365 1366 1367 1368 1369
    * where:
    *   fmt=0, 0x0X
    *   fmt=1, 0x4X
    *   fmt=2, 0x8X
    *   fmt=3, 0xCX
1370
    */
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    // see also: ngx_rtmp_recv
    if (fmt <= RTMP_FMT_TYPE2) {
        char* pp = (char*)&chunk->header.timestamp_delta;
        pp[2] = *p++;
        pp[1] = *p++;
        pp[0] = *p++;
        pp[3] = 0;
        
        // fmt: 0
        // timestamp: 3 bytes
        // If the timestamp is greater than or equal to 16777215
        // (hexadecimal 0x00ffffff), this value MUST be 16777215, and the
        // ‘extended timestamp header’ MUST be present. Otherwise, this value
        // SHOULD be the entire timestamp.
        //
        // fmt: 1 or 2
        // timestamp delta: 3 bytes
        // If the delta is greater than or equal to 16777215 (hexadecimal
        // 0x00ffffff), this value MUST be 16777215, and the ‘extended
        // timestamp header’ MUST be present. Otherwise, this value SHOULD be
        // the entire delta.
        chunk->extended_timestamp = (chunk->header.timestamp_delta >= RTMP_EXTENDED_TIMESTAMP);
1393
        if (!chunk->extended_timestamp) {
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
            // Extended timestamp: 0 or 4 bytes
            // This field MUST be sent when the normal timsestamp is set to
            // 0xffffff, it MUST NOT be sent if the normal timestamp is set to
            // anything else. So for values less than 0xffffff the normal
            // timestamp field SHOULD be used in which case the extended timestamp
            // MUST NOT be present. For values greater than or equal to 0xffffff
            // the normal timestamp field MUST NOT be used and MUST be set to
            // 0xffffff and the extended timestamp MUST be sent.
            if (fmt == RTMP_FMT_TYPE0) {
                // 6.1.2.1. Type 0
                // For a type-0 chunk, the absolute timestamp of the message is sent
                // here.
                chunk->header.timestamp = chunk->header.timestamp_delta;
            } else {
                // 6.1.2.2. Type 1
                // 6.1.2.3. Type 2
                // For a type-1 or type-2 chunk, the difference between the previous
                // chunk's timestamp and the current chunk's timestamp is sent here.
                chunk->header.timestamp += chunk->header.timestamp_delta;
            }
        }
        
        if (fmt <= RTMP_FMT_TYPE1) {
1417 1418
            int32_t payload_length = 0;
            pp = (char*)&payload_length;
1419 1420 1421 1422 1423
            pp[2] = *p++;
            pp[1] = *p++;
            pp[0] = *p++;
            pp[3] = 0;
            
1424 1425 1426 1427 1428
            // for a message, if msg exists in cache, the size must not changed.
            // always use the actual msg size to compare, for the cache payload length can changed,
            // for the fmt type1(stream_id not changed), user can change the payload 
            // length(it's not allowed in the continue chunks).
            if (!is_first_chunk_of_msg && chunk->header.payload_length != payload_length) {
1429 1430 1431
                ret = ERROR_RTMP_PACKET_SIZE;
                srs_error("msg exists in chunk cache, "
                    "size=%d cannot change to %d, ret=%d", 
1432
                    chunk->header.payload_length, payload_length, ret);
1433 1434 1435
                return ret;
            }
            
1436
            chunk->header.payload_length = payload_length;
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
            chunk->header.message_type = *p++;
            
            if (fmt == RTMP_FMT_TYPE0) {
                pp = (char*)&chunk->header.stream_id;
                pp[0] = *p++;
                pp[1] = *p++;
                pp[2] = *p++;
                pp[3] = *p++;
                srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%"PRId64", payload=%d, type=%d, sid=%d", 
                    fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp, chunk->header.payload_length, 
                    chunk->header.message_type, chunk->header.stream_id);
            } else {
                srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%"PRId64", payload=%d, type=%d", 
                    fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp, chunk->header.payload_length, 
                    chunk->header.message_type);
            }
        } else {
            srs_verbose("header read completed. fmt=%d, mh_size=%d, ext_time=%d, time=%"PRId64"", 
                fmt, mh_size, chunk->extended_timestamp, chunk->header.timestamp);
        }
    } else {
1458 1459
        // update the timestamp even fmt=3 for first chunk packet
        if (is_first_chunk_of_msg && !chunk->extended_timestamp) {
1460 1461 1462 1463 1464 1465
            chunk->header.timestamp += chunk->header.timestamp_delta;
        }
        srs_verbose("header read completed. fmt=%d, size=%d, ext_time=%d", 
            fmt, mh_size, chunk->extended_timestamp);
    }
    
1466
    // read extended-timestamp
1467
    if (chunk->extended_timestamp) {
1468 1469 1470
        mh_size += 4;
        required_size = bh_size + mh_size;
        srs_verbose("read header ext time. fmt=%d, ext_time=%d, mh_size=%d", fmt, chunk->extended_timestamp, mh_size);
1471
        if ((ret = in_buffer->grow(skt, required_size)) != ERROR_SUCCESS) {
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
            if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
                srs_error("read %dbytes message header failed. required_size=%d, ret=%d", mh_size, required_size, ret);
            }
            return ret;
        }

        u_int32_t timestamp = 0x00;
        char* pp = (char*)&timestamp;
        pp[3] = *p++;
        pp[2] = *p++;
        pp[1] = *p++;
        pp[0] = *p++;
1484 1485 1486 1487

        // always use 31bits timestamp, for some server may use 32bits extended timestamp.
        // @see https://github.com/winlinvip/simple-rtmp-server/issues/111
        timestamp &= 0x7fffffff;
1488
        
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
        /**
        * RTMP specification and ffmpeg/librtmp is false,
        * but, adobe changed the specification, so flash/FMLE/FMS always true.
        * default to true to support flash/FMLE/FMS.
        * 
        * ffmpeg/librtmp may donot send this filed, need to detect the value.
        * @see also: http://blog.csdn.net/win_lin/article/details/13363699
        * compare to the chunk timestamp, which is set by chunk message header
        * type 0,1 or 2.
        *
        * @remark, nginx send the extended-timestamp in sequence-header,
        * and timestamp delta in continue C1 chunks, and so compatible with ffmpeg,
        * that is, there is no continue chunks and extended-timestamp in nginx-rtmp.
        *
        * @remark, srs always send the extended-timestamp, to keep simple,
        * and compatible with adobe products.
        */
1506
        u_int32_t chunk_timestamp = (u_int32_t)chunk->header.timestamp;
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
        
        /**
        * if chunk_timestamp<=0, the chunk previous packet has no extended-timestamp,
        * always use the extended timestamp.
        */
        /**
        * about the is_first_chunk_of_msg.
        * @remark, for the first chunk of message, always use the extended timestamp.
        */
        if (!is_first_chunk_of_msg && chunk_timestamp > 0 && chunk_timestamp != timestamp) {
1517
            mh_size -= 4;
1518
            srs_info("no 4bytes extended timestamp in the continued chunk");
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
        } else {
            chunk->header.timestamp = timestamp;
        }
        srs_verbose("header read ext_time completed. time=%"PRId64"", chunk->header.timestamp);
    }
    
    // the extended-timestamp must be unsigned-int,
    //         24bits timestamp: 0xffffff = 16777215ms = 16777.215s = 4.66h
    //         32bits timestamp: 0xffffffff = 4294967295ms = 4294967.295s = 1193.046h = 49.71d
    // because the rtmp protocol says the 32bits timestamp is about "50 days":
    //         3. Byte Order, Alignment, and Time Format
    //                Because timestamps are generally only 32 bits long, they will roll
    //                over after fewer than 50 days.
    // 
    // but, its sample says the timestamp is 31bits:
    //         An application could assume, for example, that all 
    //        adjacent timestamps are within 2^31 milliseconds of each other, so
    //        10000 comes after 4000000000, while 3000000000 comes before
    //        4000000000.
    // and flv specification says timestamp is 31bits:
    //        Extension of the Timestamp field to form a SI32 value. This
    //        field represents the upper 8 bits, while the previous
    //        Timestamp field represents the lower 24 bits of the time in
    //        milliseconds.
    // in a word, 31bits timestamp is ok.
    // convert extended timestamp to 31bits.
    chunk->header.timestamp &= 0x7fffffff;
    
1547 1548 1549
    // valid message, the payload_length is 24bits,
    // so it should never be negative.
    srs_assert(chunk->header.payload_length >= 0);
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
    
    // copy header to msg
    chunk->msg->header = chunk->header;
    
    // increase the msg count, the chunk stream can accept fmt=1/2/3 message now.
    chunk->msg_count++;
    
    return ret;
}
1560
int SrsProtocol::read_message_payload(SrsChunkStream* chunk, int bh_size, int mh_size, int& payload_size, SrsMessage** pmsg)
1561 1562
{
    int ret = ERROR_SUCCESS;
1563
    
1564 1565 1566
    // empty message
    if (chunk->header.payload_length <= 0) {
        // need erase the header in buffer.
1567
        in_buffer->erase(bh_size + mh_size);
1568 1569 1570 1571 1572 1573 1574 1575 1576
        
        srs_trace("get an empty RTMP "
                "message(type=%d, size=%d, time=%"PRId64", sid=%d)", chunk->header.message_type, 
                chunk->header.payload_length, chunk->header.timestamp, chunk->header.stream_id);
        
        *pmsg = chunk->msg;
        chunk->msg = NULL;
                
        return ret;
1577
    }
1578
    srs_assert(chunk->header.payload_length > 0);
1579
    
1580 1581 1582 1583 1584
    // the chunk payload size.
    payload_size = chunk->header.payload_length - chunk->msg->size;
    payload_size = srs_min(payload_size, in_chunk_size);
    srs_verbose("chunk payload size is %d, message_size=%d, received_size=%d, in_chunk_size=%d", 
        payload_size, chunk->header.payload_length, chunk->msg->size, in_chunk_size);
winlin authored
1585
1586 1587
    // create msg payload if not initialized
    if (!chunk->msg->payload) {
1588
        chunk->msg->payload = new char[chunk->header.payload_length];
1589 1590
        memset(chunk->msg->payload, 0, chunk->header.payload_length);
        srs_verbose("create empty payload for RTMP message. size=%d", chunk->header.payload_length);
1591 1592
    }
    
1593 1594
    // read payload to buffer
    int required_size = bh_size + mh_size + payload_size;
1595
    if ((ret = in_buffer->grow(skt, required_size)) != ERROR_SUCCESS) {
1596 1597 1598 1599 1600
        if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
            srs_error("read payload failed. required_size=%d, ret=%d", required_size, ret);
        }
        return ret;
    }
1601 1602
    memcpy(chunk->msg->payload + chunk->msg->size, in_buffer->bytes() + bh_size + mh_size, payload_size);
    in_buffer->erase(bh_size + mh_size + payload_size);
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    chunk->msg->size += payload_size;
    
    srs_verbose("chunk payload read completed. bh_size=%d, mh_size=%d, payload_size=%d", bh_size, mh_size, payload_size);
    
    // got entire RTMP message?
    if (chunk->header.payload_length == chunk->msg->size) {
        *pmsg = chunk->msg;
        chunk->msg = NULL;
        srs_verbose("get entire RTMP message(type=%d, size=%d, time=%"PRId64", sid=%d)", 
                chunk->header.message_type, chunk->header.payload_length, 
                chunk->header.timestamp, chunk->header.stream_id);
        return ret;
    }
    
    srs_verbose("get partial RTMP message(type=%d, size=%d, time=%"PRId64", sid=%d), partial size=%d", 
            chunk->header.message_type, chunk->header.payload_length, 
            chunk->header.timestamp, chunk->header.stream_id,
            chunk->msg->size);
            
    return ret;
winlin authored
1623 1624
}
1625
int SrsProtocol::on_recv_message(SrsMessage* msg)
winlin authored
1626
{
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
    int ret = ERROR_SUCCESS;
    
    srs_assert(msg != NULL);
        
    // acknowledgement
    if (in_ack_size.ack_window_size > 0 
        && skt->get_recv_bytes() - in_ack_size.acked_size > in_ack_size.ack_window_size
    ) {
        if ((ret = response_acknowledgement_message()) != ERROR_SUCCESS) {
            return ret;
        }
    }
    
    SrsPacket* packet = NULL;
    switch (msg->header.message_type) {
        case RTMP_MSG_SetChunkSize:
        case RTMP_MSG_UserControlMessage:
        case RTMP_MSG_WindowAcknowledgementSize:
1645
            if ((ret = decode_message(msg, &packet)) != ERROR_SUCCESS) {
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
                srs_error("decode packet from message payload failed. ret=%d", ret);
                return ret;
            }
            srs_verbose("decode packet from message payload success.");
            break;
        default:
            return ret;
    }
    
    srs_assert(packet);
    
    // always free the packet.
1658
    SrsAutoFree(SrsPacket, packet);
1659 1660 1661 1662 1663 1664 1665 1666
    
    switch (msg->header.message_type) {
        case RTMP_MSG_WindowAcknowledgementSize: {
            SrsSetWindowAckSizePacket* pkt = dynamic_cast<SrsSetWindowAckSizePacket*>(packet);
            srs_assert(pkt != NULL);
            
            if (pkt->ackowledgement_window_size > 0) {
                in_ack_size.ack_window_size = pkt->ackowledgement_window_size;
winlin authored
1667 1668 1669 1670
                // @remakr, we ignore this message, for user noneed to care.
                // but it's important for dev, for client/server will block if required 
                // ack msg not arrived.
                srs_info("set ack window size to %d", pkt->ackowledgement_window_size);
1671 1672 1673 1674 1675 1676 1677 1678
            } else {
                srs_warn("ignored. set ack window size is %d", pkt->ackowledgement_window_size);
            }
            break;
        }
        case RTMP_MSG_SetChunkSize: {
            SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(packet);
            srs_assert(pkt != NULL);
1679 1680 1681 1682 1683 1684 1685

            // for some server, the actual chunk size can greater than the max value(65536),
            // so we just warning the invalid chunk size, and actually use it is ok,
            // @see: https://github.com/winlinvip/simple-rtmp-server/issues/160
            if (pkt->chunk_size < SRS_CONSTS_RTMP_MIN_CHUNK_SIZE 
                || pkt->chunk_size > SRS_CONSTS_RTMP_MAX_CHUNK_SIZE) 
            {
1686 1687
                srs_warn("accept chunk size %d, but should in [%d, %d], "
                    "@see: https://github.com/winlinvip/simple-rtmp-server/issues/160",
1688 1689 1690
                    pkt->chunk_size, SRS_CONSTS_RTMP_MIN_CHUNK_SIZE, 
                    SRS_CONSTS_RTMP_MAX_CHUNK_SIZE);
            }
1691 1692

            int sock_buffer = in_buffer->buffer_size();
1693
            in_chunk_size = pkt->chunk_size;
1694 1695 1696 1697
            in_buffer->on_chunk_size(pkt->chunk_size);
            srs_trace("input chunk size to %d, sock buf %d=>%d",
                pkt->chunk_size, sock_buffer, in_buffer->buffer_size());
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
            break;
        }
        case RTMP_MSG_UserControlMessage: {
            SrsUserControlPacket* pkt = dynamic_cast<SrsUserControlPacket*>(packet);
            srs_assert(pkt != NULL);
            
            if (pkt->event_type == SrcPCUCSetBufferLength) {
                srs_trace("ignored. set buffer length to %d", pkt->extra_data);
            }
            if (pkt->event_type == SrcPCUCPingRequest) {
                if ((ret = response_ping_message(pkt->event_data)) != ERROR_SUCCESS) {
                    return ret;
                }
            }
            break;
        }
1714 1715
        default:
            break;
1716 1717 1718
    }
    
    return ret;
winlin authored
1719 1720
}
1721
int SrsProtocol::on_send_packet(SrsMessage* msg, SrsPacket* packet)
winlin authored
1722
{
1723 1724
    int ret = ERROR_SUCCESS;
    
1725 1726 1727 1728
    // ignore raw bytes oriented RTMP message.
    if (packet == NULL) {
        return ret;
    }
1729 1730 1731 1732 1733 1734 1735 1736
    
    switch (msg->header.message_type) {
        case RTMP_MSG_SetChunkSize: {
            SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(packet);
            srs_assert(pkt != NULL);
            
            out_chunk_size = pkt->chunk_size;
            
winlin authored
1737
            srs_trace("out chunk size to %d", pkt->chunk_size);
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
            break;
        }
        case RTMP_MSG_AMF0CommandMessage:
        case RTMP_MSG_AMF3CommandMessage: {
            if (true) {
                SrsConnectAppPacket* pkt = dynamic_cast<SrsConnectAppPacket*>(packet);
                if (pkt) {
                    requests[pkt->transaction_id] = pkt->command_name;
                    break;
                }
            }
            if (true) {
                SrsCreateStreamPacket* pkt = dynamic_cast<SrsCreateStreamPacket*>(packet);
                if (pkt) {
                    requests[pkt->transaction_id] = pkt->command_name;
                    break;
                }
            }
            if (true) {
                SrsFMLEStartPacket* pkt = dynamic_cast<SrsFMLEStartPacket*>(packet);
                if (pkt) {
                    requests[pkt->transaction_id] = pkt->command_name;
                    break;
                }
            }
            break;
        }
1765 1766
        default:
            break;
1767 1768 1769
    }
    
    return ret;
winlin authored
1770 1771 1772 1773
}

int SrsProtocol::response_acknowledgement_message()
{
1774 1775 1776
    int ret = ERROR_SUCCESS;
    
    SrsAcknowledgementPacket* pkt = new SrsAcknowledgementPacket();
1777 1778
    in_ack_size.acked_size = skt->get_recv_bytes();
    pkt->sequence_number = (int32_t)in_ack_size.acked_size;
1779 1780 1781 1782 1783 1784 1785 1786 1787
    
    // cache the message and use flush to send.
    if (!auto_response_when_recv) {
        manual_response_queue.push_back(pkt);
        return ret;
    }
    
    // use underlayer api to send, donot flush again.
    if ((ret = do_send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1788 1789 1790 1791 1792 1793
        srs_error("send acknowledgement failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("send acknowledgement success.");
    
    return ret;
winlin authored
1794 1795 1796 1797
}

int SrsProtocol::response_ping_message(int32_t timestamp)
{
1798 1799 1800 1801 1802 1803 1804 1805 1806
    int ret = ERROR_SUCCESS;
    
    srs_trace("get a ping request, response it. timestamp=%d", timestamp);
    
    SrsUserControlPacket* pkt = new SrsUserControlPacket();
    
    pkt->event_type = SrcPCUCPingResponse;
    pkt->event_data = timestamp;
    
1807 1808 1809 1810 1811 1812 1813 1814
    // cache the message and use flush to send.
    if (!auto_response_when_recv) {
        manual_response_queue.push_back(pkt);
        return ret;
    }
    
    // use underlayer api to send, donot flush again.
    if ((ret = do_send_and_free_packet(pkt, 0)) != ERROR_SUCCESS) {
1815 1816 1817 1818 1819 1820
        srs_error("send ping response failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("send ping response success.");
    
    return ret;
winlin authored
1821 1822
}
1823
SrsChunkStream::SrsChunkStream(int _cid)
winlin authored
1824
{
winlin authored
1825 1826 1827 1828 1829 1830
    fmt = 0;
    cid = _cid;
    extended_timestamp = false;
    msg = NULL;
    msg_count = 0;
}
winlin authored
1831
1832
SrsChunkStream::~SrsChunkStream()
winlin authored
1833 1834
{
    srs_freep(msg);
winlin authored
1835 1836
}
1837 1838 1839 1840 1841 1842
SrsCommonMessage::SrsCommonMessage()
{
}

SrsCommonMessage::~SrsCommonMessage()
{
1843
    srs_freep(payload);
winlin authored
1844 1845
}
1846
SrsSharedPtrMessage::__SrsSharedPtr::__SrsSharedPtr()
winlin authored
1847
{
1848 1849 1850
    payload = NULL;
    size = 0;
    shared_count = 0;
winlin authored
1851 1852
}
1853
SrsSharedPtrMessage::__SrsSharedPtr::~__SrsSharedPtr()
winlin authored
1854
{
1855
    srs_freep(payload);
winlin authored
1856 1857
}
1858
SrsSharedPtrMessage::SrsSharedPtrMessage()
winlin authored
1859
{
1860
    ptr = NULL;
winlin authored
1861 1862
}
1863
SrsSharedPtrMessage::~SrsSharedPtrMessage()
winlin authored
1864
{
1865 1866 1867 1868 1869 1870 1871
    if (ptr) {
        if (ptr->shared_count == 0) {
            srs_freep(ptr);
        } else {
            ptr->shared_count--;
        }
    }
winlin authored
1872 1873
}
1874
int SrsSharedPtrMessage::create(SrsMessage* msg)
winlin authored
1875
{
1876 1877
    int ret = ERROR_SUCCESS;
    
1878
    if ((ret = create(&msg->header, msg->payload, msg->size)) != ERROR_SUCCESS) {
1879 1880 1881
        return ret;
    }
    
1882 1883 1884 1885 1886
    // to prevent double free of payload:
    // initialize already attach the payload of msg,
    // detach the payload to transfer the owner to shared ptr.
    msg->payload = NULL;
    msg->size = 0;
1887 1888
    
    return ret;
winlin authored
1889 1890
}
1891
int SrsSharedPtrMessage::create(SrsMessageHeader* pheader, char* payload, int size)
winlin authored
1892
{
1893 1894
    int ret = ERROR_SUCCESS;
    
1895
    srs_assert(pheader != NULL);
1896 1897 1898 1899 1900 1901 1902 1903
    if (ptr) {
        ret = ERROR_SYSTEM_ASSERT_FAILED;
        srs_error("should not set the payload twice. ret=%d", ret);
        srs_assert(false);
        
        return ret;
    }
    
1904
    header = *pheader;
1905 1906
    header.payload_length = size;
    
winlin authored
1907
    ptr = new __SrsSharedPtr();
1908
    
1909
    // direct attach the data.
1910 1911 1912
    ptr->payload = payload;
    ptr->size = size;
    
1913
    // message can access it.
1914
    SrsMessage::payload = ptr->payload;
1915
    SrsMessage::size = ptr->size;
1916 1917
    
    return ret;
winlin authored
1918 1919
}
1920 1921 1922 1923 1924 1925
int SrsSharedPtrMessage::count()
{
    srs_assert(ptr);
    return ptr->shared_count;
}
1926
SrsSharedPtrMessage* SrsSharedPtrMessage::copy()
winlin authored
1927
{
1928
    srs_assert(ptr);
1929
    
1930
    SrsSharedPtrMessage* copy = new SrsSharedPtrMessage();
1931 1932 1933 1934 1935 1936
    
    copy->header = header;
    
    copy->ptr = ptr;
    ptr->shared_count++;
    
1937
    copy->payload = ptr->payload;
1938 1939 1940
    copy->size = ptr->size;
    
    return copy;
winlin authored
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
}

SrsPacket::SrsPacket()
{
}

SrsPacket::~SrsPacket()
{
}

int SrsPacket::encode(int& psize, char*& ppayload)
{
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964
    int ret = ERROR_SUCCESS;
    
    int size = get_size();
    char* payload = NULL;
    
    SrsStream stream;
    
    if (size > 0) {
        payload = new char[size];
        
        if ((ret = stream.initialize(payload, size)) != ERROR_SUCCESS) {
            srs_error("initialize the stream failed. ret=%d", ret);
1965
            srs_freep(payload);
1966 1967 1968 1969 1970 1971
            return ret;
        }
    }
    
    if ((ret = encode_packet(&stream)) != ERROR_SUCCESS) {
        srs_error("encode the packet failed. ret=%d", ret);
1972
        srs_freep(payload);
1973 1974 1975 1976 1977 1978 1979 1980
        return ret;
    }
    
    psize = size;
    ppayload = payload;
    srs_verbose("encode the packet success. size=%d", size);
    
    return ret;
winlin authored
1981 1982
}
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
int SrsPacket::decode(SrsStream* stream)
{
    int ret = ERROR_SUCCESS;
    
    srs_assert(stream != NULL);

    ret = ERROR_SYSTEM_PACKET_INVALID;
    srs_error("current packet is not support to decode. ret=%d", ret);
    
    return ret;
}
1995
int SrsPacket::get_prefer_cid()
1996 1997 1998 1999 2000 2001 2002 2003 2004
{
    return 0;
}

int SrsPacket::get_message_type()
{
    return 0;
}
winlin authored
2005 2006
int SrsPacket::get_size()
{
2007
    return 0;
winlin authored
2008 2009 2010 2011
}

int SrsPacket::encode_packet(SrsStream* stream)
{
2012 2013 2014
    int ret = ERROR_SUCCESS;
    
    srs_assert(stream != NULL);
winlin authored
2015
2016
    ret = ERROR_SYSTEM_PACKET_INVALID;
2017
    srs_error("current packet is not support to encode. ret=%d", ret);
2018 2019
    
    return ret;
winlin authored
2020 2021 2022 2023
}

SrsConnectAppPacket::SrsConnectAppPacket()
{
2024 2025 2026
    command_name = RTMP_AMF0_COMMAND_CONNECT;
    transaction_id = 1;
    command_object = SrsAmf0Any::object();
2027 2028
    // optional
    args = NULL;
winlin authored
2029 2030 2031 2032
}

SrsConnectAppPacket::~SrsConnectAppPacket()
{
2033
    srs_freep(command_object);
2034
    srs_freep(args);
winlin authored
2035 2036 2037 2038
}

int SrsConnectAppPacket::decode(SrsStream* stream)
{
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_CONNECT) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode connect command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect transaction_id failed. ret=%d", ret);
        return ret;
    }
2056 2057
    
    // some client donot send id=1.0, so we only warn user if not match.
2058 2059
    if (transaction_id != 1.0) {
        ret = ERROR_RTMP_AMF0_DECODE;
2060
        srs_warn("amf0 decode connect transaction_id failed. "
2061
            "required=%.1f, actual=%.1f, ret=%d", 1.0, transaction_id, ret);
2062
        ret = ERROR_SUCCESS;
2063 2064 2065 2066 2067 2068 2069
    }
    
    if ((ret = command_object->read(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect command_object failed. ret=%d", ret);
        return ret;
    }
    
2070 2071
    if (!stream->empty()) {
        srs_freep(args);
2072 2073 2074 2075 2076
        
        // see: https://github.com/winlinvip/simple-rtmp-server/issues/186
        // the args maybe any amf0, for instance, a string. we should drop if not object.
        SrsAmf0Any* any = NULL;
        if ((ret = SrsAmf0Any::discovery(stream, &any)) != ERROR_SUCCESS) {
2077
            srs_error("amf0 find connect args failed. ret=%d", ret);
2078 2079
            return ret;
        }
2080 2081
        srs_assert(any);
        
2082 2083 2084
        // read the instance
        if ((ret = any->read(stream)) != ERROR_SUCCESS) {
            srs_error("amf0 decode connect args failed. ret=%d", ret);
2085
            srs_freep(any);
2086 2087 2088
            return ret;
        }
        
2089 2090 2091 2092 2093 2094 2095
        // drop when not an AMF0 object.
        if (!any->is_object()) {
            srs_warn("drop the args, see: '4.1.1. connect', marker=%#x", any->marker);
            srs_freep(any);
        } else {
            args = any->to_object();
        }
2096 2097
    }
    
2098 2099 2100
    srs_info("amf0 decode connect packet success");
    
    return ret;
winlin authored
2101 2102
}
2103
int SrsConnectAppPacket::get_prefer_cid()
winlin authored
2104
{
2105
    return RTMP_CID_OverConnection;
winlin authored
2106 2107 2108 2109
}

int SrsConnectAppPacket::get_message_type()
{
2110
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2111 2112 2113 2114
}

int SrsConnectAppPacket::get_size()
{
2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
    int size = 0;
    
    size += SrsAmf0Size::str(command_name);
    size += SrsAmf0Size::number();
    size += SrsAmf0Size::object(command_object);
    if (args) {
        size += SrsAmf0Size::object(args);
    }
    
    return size;
winlin authored
2125 2126 2127 2128
}

int SrsConnectAppPacket::encode_packet(SrsStream* stream)
{
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = command_object->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
2149 2150 2151 2152 2153 2154
    if (args && (ret = args->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode args failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode args success.");
    
2155 2156 2157
    srs_info("encode connect app request packet success.");
    
    return ret;
winlin authored
2158 2159
}
winlin authored
2160 2161
SrsConnectAppResPacket::SrsConnectAppResPacket()
{
2162 2163 2164 2165
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = 1;
    props = SrsAmf0Any::object();
    info = SrsAmf0Any::object();
winlin authored
2166 2167 2168 2169
}

SrsConnectAppResPacket::~SrsConnectAppResPacket()
{
2170 2171
    srs_freep(props);
    srs_freep(info);
winlin authored
2172 2173
}
winlin authored
2174 2175
int SrsConnectAppResPacket::decode(SrsStream* stream)
{
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_RESULT) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode connect command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect transaction_id failed. ret=%d", ret);
        return ret;
    }
2193 2194
    
    // some client donot send id=1.0, so we only warn user if not match.
2195 2196
    if (transaction_id != 1.0) {
        ret = ERROR_RTMP_AMF0_DECODE;
2197
        srs_warn("amf0 decode connect transaction_id failed. "
2198
            "required=%.1f, actual=%.1f, ret=%d", 1.0, transaction_id, ret);
2199
        ret = ERROR_SUCCESS;
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214
    }
    
    if ((ret = props->read(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect props failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = info->read(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect info failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode connect response packet success");
    
    return ret;
winlin authored
2215 2216
}
2217
int SrsConnectAppResPacket::get_prefer_cid()
winlin authored
2218
{
2219
    return RTMP_CID_OverConnection;
winlin authored
2220 2221 2222 2223
}

int SrsConnectAppResPacket::get_message_type()
{
2224
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2225 2226 2227 2228
}

int SrsConnectAppResPacket::get_size()
{
2229
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number() 
2230
        + SrsAmf0Size::object(props) + SrsAmf0Size::object(info);
winlin authored
2231 2232 2233 2234
}

int SrsConnectAppResPacket::encode_packet(SrsStream* stream)
{
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
2249 2250 2251
    if ((ret = props->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode props failed. ret=%d", ret);
        return ret;
2252 2253
    }
2254 2255
    srs_verbose("encode props success.");
    
2256 2257 2258
    if ((ret = info->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode info failed. ret=%d", ret);
        return ret;
2259 2260
    }
2261 2262 2263 2264 2265
    srs_verbose("encode info success.");
    
    srs_info("encode connect app response packet success.");
    
    return ret;
winlin authored
2266 2267
}
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
SrsCallPacket::SrsCallPacket()
{
    command_name = "";
    transaction_id = 0;
    command_object = NULL;
    arguments = NULL;
}

SrsCallPacket::~SrsCallPacket()
{
    srs_freep(command_object);
    srs_freep(arguments);
}

int SrsCallPacket::decode(SrsStream* stream)
{
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode call command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty()) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode call command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode call transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    srs_freep(command_object);
    if ((ret = SrsAmf0Any::discovery(stream, &command_object)) != ERROR_SUCCESS) {
        srs_error("amf0 discovery call command_object failed. ret=%d", ret);
        return ret;
    }
    if ((ret = command_object->read(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode call command_object failed. ret=%d", ret);
        return ret;
    }
    
    if (!stream->empty()) {
        srs_freep(arguments);
        if ((ret = SrsAmf0Any::discovery(stream, &arguments)) != ERROR_SUCCESS) {
            srs_error("amf0 discovery call arguments failed. ret=%d", ret);
            return ret;
        }
        if ((ret = arguments->read(stream)) != ERROR_SUCCESS) {
            srs_error("amf0 decode call arguments failed. ret=%d", ret);
            return ret;
        }
    }
    
    srs_info("amf0 decode call packet success");
    
    return ret;
}
2329
int SrsCallPacket::get_prefer_cid()
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
{
    return RTMP_CID_OverConnection;
}

int SrsCallPacket::get_message_type()
{
    return RTMP_MSG_AMF0CommandMessage;
}

int SrsCallPacket::get_size()
{
    int size = 0;
    
    size += SrsAmf0Size::str(command_name) + SrsAmf0Size::number();
    
    if (command_object) {
        size += command_object->total_size();
    }
    
    if (arguments) {
        size += arguments->total_size();
    }
    
    return size;
}

int SrsCallPacket::encode_packet(SrsStream* stream)
{
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if (command_object && (ret = command_object->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if (arguments && (ret = arguments->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode arguments failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode arguments success.");
    
    srs_info("encode create stream request packet success.");
    
    return ret;
}

SrsCallResPacket::SrsCallResPacket(double _transaction_id)
{
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = _transaction_id;
    command_object = NULL;
    response = NULL;
}

SrsCallResPacket::~SrsCallResPacket()
{
    srs_freep(command_object);
    srs_freep(response);
}
2403
int SrsCallResPacket::get_prefer_cid()
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
{
    return RTMP_CID_OverConnection;
}

int SrsCallResPacket::get_message_type()
{
    return RTMP_MSG_AMF0CommandMessage;
}

int SrsCallResPacket::get_size()
{
    int size = 0;
    
    size += SrsAmf0Size::str(command_name) + SrsAmf0Size::number();
    
    if (command_object) {
        size += command_object->total_size();
    }
    
    if (response) {
        size += response->total_size();
    }
    
    return size;
}

int SrsCallResPacket::encode_packet(SrsStream* stream)
{
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if (command_object && (ret = command_object->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if (response && (ret = response->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode response failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode response success.");
    
    
    srs_info("encode call response packet success.");
    
    return ret;
}
winlin authored
2464 2465
SrsCreateStreamPacket::SrsCreateStreamPacket()
{
2466 2467 2468
    command_name = RTMP_AMF0_COMMAND_CREATE_STREAM;
    transaction_id = 2;
    command_object = SrsAmf0Any::null();
winlin authored
2469 2470 2471 2472
}

SrsCreateStreamPacket::~SrsCreateStreamPacket()
{
2473
    srs_freep(command_object);
winlin authored
2474 2475 2476 2477
}

int SrsCreateStreamPacket::decode(SrsStream* stream)
{
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode createStream command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_CREATE_STREAM) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode createStream command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode createStream transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode createStream command_object failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode createStream packet success");
    
    return ret;
winlin authored
2504 2505
}
2506
int SrsCreateStreamPacket::get_prefer_cid()
winlin authored
2507
{
2508
    return RTMP_CID_OverConnection;
winlin authored
2509 2510 2511 2512
}

int SrsCreateStreamPacket::get_message_type()
{
2513
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2514 2515 2516 2517
}

int SrsCreateStreamPacket::get_size()
{
2518 2519
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null();
winlin authored
2520 2521 2522 2523
}

int SrsCreateStreamPacket::encode_packet(SrsStream* stream)
{
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    srs_info("encode create stream request packet success.");
    
    return ret;
winlin authored
2547 2548
}
winlin authored
2549 2550
SrsCreateStreamResPacket::SrsCreateStreamResPacket(double _transaction_id, double _stream_id)
{
2551 2552 2553 2554
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = _transaction_id;
    command_object = SrsAmf0Any::null();
    stream_id = _stream_id;
winlin authored
2555 2556 2557 2558
}

SrsCreateStreamResPacket::~SrsCreateStreamResPacket()
{
2559
    srs_freep(command_object);
winlin authored
2560 2561
}
winlin authored
2562 2563
int SrsCreateStreamResPacket::decode(SrsStream* stream)
{
2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode createStream command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_RESULT) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode createStream command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode createStream transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode createStream command_object failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, stream_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode createStream stream_id failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode createStream response packet success");
    
    return ret;
winlin authored
2595 2596
}
2597
int SrsCreateStreamResPacket::get_prefer_cid()
winlin authored
2598
{
2599
    return RTMP_CID_OverConnection;
winlin authored
2600 2601 2602 2603
}

int SrsCreateStreamResPacket::get_message_type()
{
2604
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2605 2606 2607 2608
}

int SrsCreateStreamResPacket::get_size()
{
2609 2610
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::number();
winlin authored
2611 2612 2613 2614
}

int SrsCreateStreamResPacket::encode_packet(SrsStream* stream)
{
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if ((ret = srs_amf0_write_number(stream, stream_id)) != ERROR_SUCCESS) {
        srs_error("encode stream_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode stream_id success.");
    
    
    srs_info("encode createStream response packet success.");
    
    return ret;
winlin authored
2645 2646
}
2647 2648 2649 2650
SrsCloseStreamPacket::SrsCloseStreamPacket()
{
    command_name = RTMP_AMF0_COMMAND_CLOSE_STREAM;
    transaction_id = 0;
2651
    command_object = SrsAmf0Any::null();
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681
}

SrsCloseStreamPacket::~SrsCloseStreamPacket()
{
    srs_freep(command_object);
}

int SrsCloseStreamPacket::decode(SrsStream* stream)
{
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode closeStream command_name failed. ret=%d", ret);
        return ret;
    }

    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode closeStream transaction_id failed. ret=%d", ret);
        return ret;
    }

    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode closeStream command_object failed. ret=%d", ret);
        return ret;
    }
    srs_info("amf0 decode closeStream packet success");

    return ret;
}
winlin authored
2682 2683
SrsFMLEStartPacket::SrsFMLEStartPacket()
{
2684 2685 2686
    command_name = RTMP_AMF0_COMMAND_RELEASE_STREAM;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
winlin authored
2687 2688 2689 2690
}

SrsFMLEStartPacket::~SrsFMLEStartPacket()
{
2691
    srs_freep(command_object);
winlin authored
2692 2693 2694 2695
}

int SrsFMLEStartPacket::decode(SrsStream* stream)
{
2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() 
        || (command_name != RTMP_AMF0_COMMAND_RELEASE_STREAM 
        && command_name != RTMP_AMF0_COMMAND_FC_PUBLISH
        && command_name != RTMP_AMF0_COMMAND_UNPUBLISH)
    ) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode FMLE start command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start command_object failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start stream_name failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode FMLE start packet success");
    
    return ret;
winlin authored
2731 2732
}
2733
int SrsFMLEStartPacket::get_prefer_cid()
2734
{
2735
    return RTMP_CID_OverConnection;
2736 2737 2738 2739
}

int SrsFMLEStartPacket::get_message_type()
{
2740
    return RTMP_MSG_AMF0CommandMessage;
2741 2742 2743 2744
}

int SrsFMLEStartPacket::get_size()
{
2745 2746
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::str(stream_name);
2747 2748 2749 2750
}

int SrsFMLEStartPacket::encode_packet(SrsStream* stream)
{
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if ((ret = srs_amf0_write_string(stream, stream_name)) != ERROR_SUCCESS) {
        srs_error("encode stream_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode stream_name success.");
    
    
    srs_info("encode FMLE start response packet success.");
    
    return ret;
2781 2782 2783 2784
}

SrsFMLEStartPacket* SrsFMLEStartPacket::create_release_stream(string stream)
{
2785 2786 2787 2788 2789 2790 2791
    SrsFMLEStartPacket* pkt = new SrsFMLEStartPacket();
    
    pkt->command_name = RTMP_AMF0_COMMAND_RELEASE_STREAM;
    pkt->transaction_id = 2;
    pkt->stream_name = stream;
    
    return pkt;
2792 2793 2794 2795
}

SrsFMLEStartPacket* SrsFMLEStartPacket::create_FC_publish(string stream)
{
2796 2797 2798 2799 2800 2801 2802
    SrsFMLEStartPacket* pkt = new SrsFMLEStartPacket();
    
    pkt->command_name = RTMP_AMF0_COMMAND_FC_PUBLISH;
    pkt->transaction_id = 3;
    pkt->stream_name = stream;
    
    return pkt;
2803 2804
}
winlin authored
2805 2806
SrsFMLEStartResPacket::SrsFMLEStartResPacket(double _transaction_id)
{
2807 2808 2809 2810
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = _transaction_id;
    command_object = SrsAmf0Any::null();
    args = SrsAmf0Any::undefined();
winlin authored
2811 2812 2813 2814
}

SrsFMLEStartResPacket::~SrsFMLEStartResPacket()
{
2815 2816
    srs_freep(command_object);
    srs_freep(args);
winlin authored
2817 2818
}
2819 2820
int SrsFMLEStartResPacket::decode(SrsStream* stream)
{
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start response command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_RESULT) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode FMLE start response command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start response transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start response command_object failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_undefined(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode FMLE start response stream_id failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode FMLE start packet success");
    
    return ret;
2852 2853
}
2854
int SrsFMLEStartResPacket::get_prefer_cid()
winlin authored
2855
{
2856
    return RTMP_CID_OverConnection;
winlin authored
2857 2858 2859 2860
}

int SrsFMLEStartResPacket::get_message_type()
{
2861
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2862 2863 2864 2865
}

int SrsFMLEStartResPacket::get_size()
{
2866 2867
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::undefined();
winlin authored
2868 2869 2870 2871
}

int SrsFMLEStartResPacket::encode_packet(SrsStream* stream)
{
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if ((ret = srs_amf0_write_undefined(stream)) != ERROR_SUCCESS) {
        srs_error("encode args failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode args success.");
    
    
    srs_info("encode FMLE start response packet success.");
    
    return ret;
winlin authored
2902 2903 2904 2905
}

SrsPublishPacket::SrsPublishPacket()
{
2906 2907 2908 2909
    command_name = RTMP_AMF0_COMMAND_PUBLISH;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
    type = "live";
winlin authored
2910 2911 2912 2913
}

SrsPublishPacket::~SrsPublishPacket()
{
2914
    srs_freep(command_object);
winlin authored
2915 2916 2917 2918
}

int SrsPublishPacket::decode(SrsStream* stream)
{
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode publish command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_PUBLISH) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode publish command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode publish transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode publish command_object failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode publish stream_name failed. ret=%d", ret);
        return ret;
    }
    
    if (!stream->empty() && (ret = srs_amf0_read_string(stream, type)) != ERROR_SUCCESS) {
        srs_error("amf0 decode publish type failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode publish packet success");
    
    return ret;
winlin authored
2955 2956
}
2957
int SrsPublishPacket::get_prefer_cid()
winlin authored
2958
{
2959
    return RTMP_CID_OverStream;
winlin authored
2960 2961 2962 2963
}

int SrsPublishPacket::get_message_type()
{
2964
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2965 2966 2967 2968
}

int SrsPublishPacket::get_size()
{
2969 2970 2971
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::str(stream_name)
        + SrsAmf0Size::str(type);
winlin authored
2972 2973 2974 2975
}

int SrsPublishPacket::encode_packet(SrsStream* stream)
{
2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if ((ret = srs_amf0_write_string(stream, stream_name)) != ERROR_SUCCESS) {
        srs_error("encode stream_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode stream_name success.");
    
    if ((ret = srs_amf0_write_string(stream, type)) != ERROR_SUCCESS) {
        srs_error("encode type failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode type success.");
    
    srs_info("encode play request packet success.");
    
    return ret;
winlin authored
3011 3012
}
winlin authored
3013 3014
SrsPausePacket::SrsPausePacket()
{
3015 3016 3017
    command_name = RTMP_AMF0_COMMAND_PAUSE;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
winlin authored
3018
3019 3020
    time_ms = 0;
    is_pause = true;
winlin authored
3021 3022 3023 3024
}

SrsPausePacket::~SrsPausePacket()
{
3025
    srs_freep(command_object);
winlin authored
3026 3027 3028 3029
}

int SrsPausePacket::decode(SrsStream* stream)
{
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode pause command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_PAUSE) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode pause command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode pause transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode pause command_object failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_boolean(stream, is_pause)) != ERROR_SUCCESS) {
        srs_error("amf0 decode pause is_pause failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, time_ms)) != ERROR_SUCCESS) {
        srs_error("amf0 decode pause time_ms failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode pause packet success");
    
    return ret;
winlin authored
3066 3067 3068 3069
}

SrsPlayPacket::SrsPlayPacket()
{
3070 3071 3072
    command_name = RTMP_AMF0_COMMAND_PLAY;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
winlin authored
3073
3074 3075 3076
    start = -2;
    duration = -1;
    reset = true;
winlin authored
3077 3078 3079 3080
}

SrsPlayPacket::~SrsPlayPacket()
{
3081
    srs_freep(command_object);
winlin authored
3082 3083 3084 3085
}

int SrsPlayPacket::decode(SrsStream* stream)
{
3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode play command_name failed. ret=%d", ret);
        return ret;
    }
    if (command_name.empty() || command_name != RTMP_AMF0_COMMAND_PLAY) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode play command_name failed. "
            "command_name=%s, ret=%d", command_name.c_str(), ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("amf0 decode play transaction_id failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode play command_object failed. ret=%d", ret);
        return ret;
    }
    
    if ((ret = srs_amf0_read_string(stream, stream_name)) != ERROR_SUCCESS) {
        srs_error("amf0 decode play stream_name failed. ret=%d", ret);
        return ret;
    }
    
    if (!stream->empty() && (ret = srs_amf0_read_number(stream, start)) != ERROR_SUCCESS) {
        srs_error("amf0 decode play start failed. ret=%d", ret);
        return ret;
    }
    if (!stream->empty() && (ret = srs_amf0_read_number(stream, duration)) != ERROR_SUCCESS) {
        srs_error("amf0 decode play duration failed. ret=%d", ret);
        return ret;
    }
3122
3123 3124
    if (stream->empty()) {
        return ret;
3125
    }
3126 3127
    
    SrsAmf0Any* reset_value = NULL;
3128
    if ((ret = srs_amf0_read_any(stream, &reset_value)) != ERROR_SUCCESS) {
3129 3130 3131 3132
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 read play reset marker failed. ret=%d", ret);
        return ret;
    }
3133
    SrsAutoFree(SrsAmf0Any, reset_value);
3134
    
3135
    if (reset_value) {
3136 3137 3138 3139 3140 3141
        // check if the value is bool or number
        // An optional Boolean value or number that specifies whether
        // to flush any previous playlist
        if (reset_value->is_boolean()) {
            reset = reset_value->to_boolean();
        } else if (reset_value->is_number()) {
3142
            reset = (reset_value->to_number() != 0);
3143 3144 3145 3146 3147
        } else {
            ret = ERROR_RTMP_AMF0_DECODE;
            srs_error("amf0 invalid type=%#x, requires number or bool, ret=%d", reset_value->marker, ret);
            return ret;
        }
3148 3149
    }
3150
    srs_info("amf0 decode play packet success");
3151 3152
    
    return ret;
winlin authored
3153 3154
}
3155
int SrsPlayPacket::get_prefer_cid()
winlin authored
3156
{
3157
    return RTMP_CID_OverStream;
winlin authored
3158 3159 3160 3161
}

int SrsPlayPacket::get_message_type()
{
3162
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
3163 3164 3165 3166
}

int SrsPlayPacket::get_size()
{
3167 3168 3169 3170
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::str(stream_name)
        + SrsAmf0Size::number() + SrsAmf0Size::number()
        + SrsAmf0Size::boolean();
winlin authored
3171 3172 3173 3174
}

int SrsPlayPacket::encode_packet(SrsStream* stream)
{
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if ((ret = srs_amf0_write_string(stream, stream_name)) != ERROR_SUCCESS) {
        srs_error("encode stream_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode stream_name success.");
    
    if ((ret = srs_amf0_write_number(stream, start)) != ERROR_SUCCESS) {
        srs_error("encode start failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode start success.");
    
    if ((ret = srs_amf0_write_number(stream, duration)) != ERROR_SUCCESS) {
        srs_error("encode duration failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode duration success.");
    
    if ((ret = srs_amf0_write_boolean(stream, reset)) != ERROR_SUCCESS) {
        srs_error("encode reset failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode reset success.");
    
    srs_info("encode play request packet success.");
    
    return ret;
winlin authored
3222 3223
}
winlin authored
3224 3225
SrsPlayResPacket::SrsPlayResPacket()
{
3226 3227 3228 3229
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
    desc = SrsAmf0Any::object();
winlin authored
3230 3231 3232 3233
}

SrsPlayResPacket::~SrsPlayResPacket()
{
3234 3235
    srs_freep(command_object);
    srs_freep(desc);
winlin authored
3236 3237
}
3238
int SrsPlayResPacket::get_prefer_cid()
winlin authored
3239
{
3240
    return RTMP_CID_OverStream;
winlin authored
3241 3242 3243 3244
}

int SrsPlayResPacket::get_message_type()
{
3245
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
3246 3247 3248 3249
}

int SrsPlayResPacket::get_size()
{
3250 3251
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::object(desc);
winlin authored
3252 3253 3254 3255
}

int SrsPlayResPacket::encode_packet(SrsStream* stream)
{
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode command_object failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_object success.");
    
    if ((ret = desc->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode desc failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode desc success.");
    
    
    srs_info("encode play response packet success.");
    
    return ret;
winlin authored
3286 3287 3288 3289
}

SrsOnBWDonePacket::SrsOnBWDonePacket()
{
3290 3291 3292
    command_name = RTMP_AMF0_COMMAND_ON_BW_DONE;
    transaction_id = 0;
    args = SrsAmf0Any::null();
winlin authored
3293 3294 3295 3296
}

SrsOnBWDonePacket::~SrsOnBWDonePacket()
{
3297
    srs_freep(args);
winlin authored
3298 3299
}
3300
int SrsOnBWDonePacket::get_prefer_cid()
winlin authored
3301
{
3302
    return RTMP_CID_OverConnection;
winlin authored
3303 3304 3305 3306
}

int SrsOnBWDonePacket::get_message_type()
{
3307
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
3308 3309 3310 3311
}

int SrsOnBWDonePacket::get_size()
{
3312 3313
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null();
winlin authored
3314 3315 3316 3317
}

int SrsOnBWDonePacket::encode_packet(SrsStream* stream)
{
3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode args failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode args success.");
    
    srs_info("encode onBWDone packet success.");
    
    return ret;
winlin authored
3341 3342 3343 3344
}

SrsOnStatusCallPacket::SrsOnStatusCallPacket()
{
3345 3346 3347 3348
    command_name = RTMP_AMF0_COMMAND_ON_STATUS;
    transaction_id = 0;
    args = SrsAmf0Any::null();
    data = SrsAmf0Any::object();
winlin authored
3349 3350 3351 3352
}

SrsOnStatusCallPacket::~SrsOnStatusCallPacket()
{
3353 3354
    srs_freep(args);
    srs_freep(data);
winlin authored
3355 3356
}
3357
int SrsOnStatusCallPacket::get_prefer_cid()
winlin authored
3358
{
3359
    return RTMP_CID_OverStream;
winlin authored
3360 3361 3362 3363
}

int SrsOnStatusCallPacket::get_message_type()
{
3364
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
3365 3366 3367 3368
}

int SrsOnStatusCallPacket::get_size()
{
3369 3370
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::object(data);
winlin authored
3371 3372 3373 3374
}

int SrsOnStatusCallPacket::encode_packet(SrsStream* stream)
{
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode args failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode args success.");;
    
    if ((ret = data->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode data failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode data success.");
    
    srs_info("encode onStatus(Call) packet success.");
    
    return ret;
winlin authored
3404 3405
}
3406 3407
SrsBandwidthPacket::SrsBandwidthPacket()
{
3408 3409 3410 3411
    command_name = RTMP_AMF0_COMMAND_ON_STATUS;
    transaction_id = 0;
    args = SrsAmf0Any::null();
    data = SrsAmf0Any::object();
3412 3413 3414 3415
}

SrsBandwidthPacket::~SrsBandwidthPacket()
{
3416 3417
    srs_freep(args);
    srs_freep(data);
3418 3419
}
3420 3421 3422 3423 3424
int SrsBandwidthPacket::decode(SrsStream *stream)
{
    int ret = ERROR_SUCCESS;

    if ((ret = srs_amf0_read_string(stream, command_name)) != ERROR_SUCCESS) {
3425
        srs_error("amf0 decode bwtc command_name failed. ret=%d", ret);
3426 3427 3428 3429
        return ret;
    }

    if ((ret = srs_amf0_read_number(stream, transaction_id)) != ERROR_SUCCESS) {
3430
        srs_error("amf0 decode bwtc transaction_id failed. ret=%d", ret);
3431 3432 3433 3434
        return ret;
    }

    if ((ret = srs_amf0_read_null(stream)) != ERROR_SUCCESS) {
3435
        srs_error("amf0 decode bwtc command_object failed. ret=%d", ret);
3436 3437 3438 3439
        return ret;
    }
    
    // @remark, for bandwidth test, ignore the data field.
3440 3441 3442 3443 3444 3445 3446
    // only decode the stop-play, start-publish and finish packet.
    if (is_stop_play() || is_start_publish() || is_finish()) {
        if ((ret = data->read(stream)) != ERROR_SUCCESS) {
            srs_error("amf0 decode bwtc command_object failed. ret=%d", ret);
            return ret;
        }
    }
3447 3448 3449 3450 3451 3452

    srs_info("decode SrsBandwidthPacket success.");

    return ret;
}
3453
int SrsBandwidthPacket::get_prefer_cid()
3454
{
3455
    return RTMP_CID_OverStream;
3456 3457 3458 3459
}

int SrsBandwidthPacket::get_message_type()
{
3460
    return RTMP_MSG_AMF0CommandMessage;
3461 3462 3463 3464
}

int SrsBandwidthPacket::get_size()
{
3465 3466
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::object(data);
3467 3468 3469 3470
}

int SrsBandwidthPacket::encode_packet(SrsStream* stream)
{
3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_number(stream, transaction_id)) != ERROR_SUCCESS) {
        srs_error("encode transaction_id failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode transaction_id success.");
    
    if ((ret = srs_amf0_write_null(stream)) != ERROR_SUCCESS) {
        srs_error("encode args failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode args success.");;
    
    if ((ret = data->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode data failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode data success.");
    
    srs_info("encode onStatus(Call) packet success.");
    
    return ret;
3500 3501
}
3502 3503 3504 3505 3506
bool SrsBandwidthPacket::is_start_play()
{
    return command_name == SRS_BW_CHECK_START_PLAY;
}
3507 3508
bool SrsBandwidthPacket::is_starting_play()
{
3509
    return command_name == SRS_BW_CHECK_STARTING_PLAY;
3510 3511
}
3512 3513 3514 3515 3516
bool SrsBandwidthPacket::is_stop_play()
{
    return command_name == SRS_BW_CHECK_STOP_PLAY;
}
3517 3518
bool SrsBandwidthPacket::is_stopped_play()
{
3519
    return command_name == SRS_BW_CHECK_STOPPED_PLAY;
3520 3521
}
3522 3523 3524 3525 3526
bool SrsBandwidthPacket::is_start_publish()
{
    return command_name == SRS_BW_CHECK_START_PUBLISH;
}
3527 3528
bool SrsBandwidthPacket::is_starting_publish()
{
3529
    return command_name == SRS_BW_CHECK_STARTING_PUBLISH;
3530 3531
}
3532 3533 3534 3535 3536
bool SrsBandwidthPacket::is_stop_publish()
{
    return command_name == SRS_BW_CHECK_STOP_PUBLISH;
}
3537 3538
bool SrsBandwidthPacket::is_stopped_publish()
{
3539
    return command_name == SRS_BW_CHECK_STOPPED_PUBLISH;
3540 3541
}
3542
bool SrsBandwidthPacket::is_finish()
3543
{
3544
    return command_name == SRS_BW_CHECK_FINISHED;
3545 3546
}
3547
bool SrsBandwidthPacket::is_final()
3548
{
3549
    return command_name == SRS_BW_CHECK_FINAL;
3550 3551 3552 3553
}

SrsBandwidthPacket* SrsBandwidthPacket::create_start_play()
{
3554 3555
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_START_PLAY);
3556 3557
}
3558 3559 3560 3561 3562 3563
SrsBandwidthPacket* SrsBandwidthPacket::create_starting_play()
{
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STARTING_PLAY);
}
3564 3565
SrsBandwidthPacket* SrsBandwidthPacket::create_playing()
{
3566
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
3567
    return pkt->set_command(SRS_BW_CHECK_PLAYING);
3568 3569 3570 3571
}

SrsBandwidthPacket* SrsBandwidthPacket::create_stop_play()
{
3572 3573
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STOP_PLAY);
3574 3575
}
3576 3577 3578 3579 3580 3581
SrsBandwidthPacket* SrsBandwidthPacket::create_stopped_play()
{
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STOPPED_PLAY);
}
3582 3583
SrsBandwidthPacket* SrsBandwidthPacket::create_start_publish()
{
3584 3585
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_START_PUBLISH);
3586 3587
}
3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599
SrsBandwidthPacket* SrsBandwidthPacket::create_starting_publish()
{
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STARTING_PUBLISH);
}

SrsBandwidthPacket* SrsBandwidthPacket::create_publishing()
{
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_PUBLISHING);
}
3600 3601
SrsBandwidthPacket* SrsBandwidthPacket::create_stop_publish()
{
3602 3603
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STOP_PUBLISH);
3604 3605
}
3606 3607 3608 3609 3610 3611
SrsBandwidthPacket* SrsBandwidthPacket::create_stopped_publish()
{
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STOPPED_PUBLISH);
}
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623
SrsBandwidthPacket* SrsBandwidthPacket::create_finish()
{
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_FINISHED);
}

SrsBandwidthPacket* SrsBandwidthPacket::create_final()
{
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_FINAL);
}
3624 3625
SrsBandwidthPacket* SrsBandwidthPacket::set_command(string command)
{
3626 3627 3628
    command_name = command;
    
    return this;
3629 3630
}
winlin authored
3631 3632
SrsOnStatusDataPacket::SrsOnStatusDataPacket()
{
3633 3634
    command_name = RTMP_AMF0_COMMAND_ON_STATUS;
    data = SrsAmf0Any::object();
winlin authored
3635 3636 3637 3638
}

SrsOnStatusDataPacket::~SrsOnStatusDataPacket()
{
3639
    srs_freep(data);
winlin authored
3640 3641
}
3642
int SrsOnStatusDataPacket::get_prefer_cid()
winlin authored
3643
{
3644
    return RTMP_CID_OverStream;
winlin authored
3645 3646 3647 3648
}

int SrsOnStatusDataPacket::get_message_type()
{
3649
    return RTMP_MSG_AMF0DataMessage;
winlin authored
3650 3651 3652 3653
}

int SrsOnStatusDataPacket::get_size()
{
3654
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::object(data);
winlin authored
3655 3656 3657 3658
}

int SrsOnStatusDataPacket::encode_packet(SrsStream* stream)
{
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = data->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode data failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode data success.");
    
    srs_info("encode onStatus(Data) packet success.");
    
    return ret;
winlin authored
3676 3677 3678 3679
}

SrsSampleAccessPacket::SrsSampleAccessPacket()
{
3680 3681 3682
    command_name = RTMP_AMF0_DATA_SAMPLE_ACCESS;
    video_sample_access = false;
    audio_sample_access = false;
winlin authored
3683 3684 3685 3686 3687 3688
}

SrsSampleAccessPacket::~SrsSampleAccessPacket()
{
}
3689
int SrsSampleAccessPacket::get_prefer_cid()
winlin authored
3690
{
3691
    return RTMP_CID_OverStream;
winlin authored
3692 3693 3694 3695
}

int SrsSampleAccessPacket::get_message_type()
{
3696
    return RTMP_MSG_AMF0DataMessage;
winlin authored
3697 3698 3699 3700
}

int SrsSampleAccessPacket::get_size()
{
3701 3702
    return SrsAmf0Size::str(command_name)
        + SrsAmf0Size::boolean() + SrsAmf0Size::boolean();
winlin authored
3703 3704 3705 3706
}

int SrsSampleAccessPacket::encode_packet(SrsStream* stream)
{
3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, command_name)) != ERROR_SUCCESS) {
        srs_error("encode command_name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode command_name success.");
    
    if ((ret = srs_amf0_write_boolean(stream, video_sample_access)) != ERROR_SUCCESS) {
        srs_error("encode video_sample_access failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode video_sample_access success.");
    
    if ((ret = srs_amf0_write_boolean(stream, audio_sample_access)) != ERROR_SUCCESS) {
        srs_error("encode audio_sample_access failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode audio_sample_access success.");;
    
    srs_info("encode |RtmpSampleAccess packet success.");
    
    return ret;
winlin authored
3730 3731 3732 3733
}

SrsOnMetaDataPacket::SrsOnMetaDataPacket()
{
3734 3735
    name = RTMP_AMF0_DATA_ON_METADATA;
    metadata = SrsAmf0Any::object();
winlin authored
3736 3737 3738 3739
}

SrsOnMetaDataPacket::~SrsOnMetaDataPacket()
{
3740
    srs_freep(metadata);
winlin authored
3741 3742 3743 3744
}

int SrsOnMetaDataPacket::decode(SrsStream* stream)
{
3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_read_string(stream, name)) != ERROR_SUCCESS) {
        srs_error("decode metadata name failed. ret=%d", ret);
        return ret;
    }

    // ignore the @setDataFrame
    if (name == RTMP_AMF0_DATA_SET_DATAFRAME) {
        if ((ret = srs_amf0_read_string(stream, name)) != ERROR_SUCCESS) {
            srs_error("decode metadata name failed. ret=%d", ret);
            return ret;
        }
    }
    
    srs_verbose("decode metadata name success. name=%s", name.c_str());
    
    // the metadata maybe object or ecma array
    SrsAmf0Any* any = NULL;
    if ((ret = srs_amf0_read_any(stream, &any)) != ERROR_SUCCESS) {
        srs_error("decode metadata metadata failed. ret=%d", ret);
        return ret;
    }
    
    srs_assert(any);
    if (any->is_object()) {
        srs_freep(metadata);
        metadata = any->to_object();
        srs_info("decode metadata object success");
        return ret;
    }
    
3777
    SrsAutoFree(SrsAmf0Any, any);
3778 3779 3780 3781 3782 3783
    
    if (any->is_ecma_array()) {
        SrsAmf0EcmaArray* arr = any->to_ecma_array();
    
        // if ecma array, copy to object.
        for (int i = 0; i < arr->count(); i++) {
3784
            metadata->set(arr->key_at(i), arr->value_at(i)->copy());
3785 3786 3787 3788 3789 3790
        }
        
        srs_info("decode metadata array success");
    }
    
    return ret;
winlin authored
3791 3792
}
3793
int SrsOnMetaDataPacket::get_prefer_cid()
winlin authored
3794
{
3795
    return RTMP_CID_OverConnection2;
winlin authored
3796 3797 3798 3799
}

int SrsOnMetaDataPacket::get_message_type()
{
3800
    return RTMP_MSG_AMF0DataMessage;
winlin authored
3801 3802 3803 3804
}

int SrsOnMetaDataPacket::get_size()
{
3805
    return SrsAmf0Size::str(name) + SrsAmf0Size::object(metadata);
winlin authored
3806 3807 3808 3809
}

int SrsOnMetaDataPacket::encode_packet(SrsStream* stream)
{
3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
    int ret = ERROR_SUCCESS;
    
    if ((ret = srs_amf0_write_string(stream, name)) != ERROR_SUCCESS) {
        srs_error("encode name failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode name success.");
    
    if ((ret = metadata->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode metadata failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("encode metadata success.");
    
    srs_info("encode onMetaData packet success.");
    return ret;
winlin authored
3826 3827 3828 3829
}

SrsSetWindowAckSizePacket::SrsSetWindowAckSizePacket()
{
3830
    ackowledgement_window_size = 0;
winlin authored
3831 3832 3833 3834 3835 3836 3837 3838
}

SrsSetWindowAckSizePacket::~SrsSetWindowAckSizePacket()
{
}

int SrsSetWindowAckSizePacket::decode(SrsStream* stream)
{
3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(4)) {
        ret = ERROR_RTMP_MESSAGE_DECODE;
        srs_error("decode ack window size failed. ret=%d", ret);
        return ret;
    }
    
    ackowledgement_window_size = stream->read_4bytes();
    srs_info("decode ack window size success");
    
    return ret;
winlin authored
3851 3852
}
3853
int SrsSetWindowAckSizePacket::get_prefer_cid()
winlin authored
3854
{
3855
    return RTMP_CID_ProtocolControl;
winlin authored
3856 3857 3858 3859
}

int SrsSetWindowAckSizePacket::get_message_type()
{
3860
    return RTMP_MSG_WindowAcknowledgementSize;
winlin authored
3861 3862 3863 3864
}

int SrsSetWindowAckSizePacket::get_size()
{
3865
    return 4;
winlin authored
3866 3867 3868 3869
}

int SrsSetWindowAckSizePacket::encode_packet(SrsStream* stream)
{
3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(4)) {
        ret = ERROR_RTMP_MESSAGE_ENCODE;
        srs_error("encode ack size packet failed. ret=%d", ret);
        return ret;
    }
    
    stream->write_4bytes(ackowledgement_window_size);
    
    srs_verbose("encode ack size packet "
        "success. ack_size=%d", ackowledgement_window_size);
    
    return ret;
winlin authored
3884 3885 3886 3887
}

SrsAcknowledgementPacket::SrsAcknowledgementPacket()
{
3888
    sequence_number = 0;
winlin authored
3889 3890 3891 3892 3893 3894
}

SrsAcknowledgementPacket::~SrsAcknowledgementPacket()
{
}
3895
int SrsAcknowledgementPacket::get_prefer_cid()
winlin authored
3896
{
3897
    return RTMP_CID_ProtocolControl;
winlin authored
3898 3899 3900 3901
}

int SrsAcknowledgementPacket::get_message_type()
{
3902
    return RTMP_MSG_Acknowledgement;
winlin authored
3903 3904 3905 3906
}

int SrsAcknowledgementPacket::get_size()
{
3907
    return 4;
winlin authored
3908 3909 3910 3911
}

int SrsAcknowledgementPacket::encode_packet(SrsStream* stream)
{
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(4)) {
        ret = ERROR_RTMP_MESSAGE_ENCODE;
        srs_error("encode acknowledgement packet failed. ret=%d", ret);
        return ret;
    }
    
    stream->write_4bytes(sequence_number);
    
    srs_verbose("encode acknowledgement packet "
        "success. sequence_number=%d", sequence_number);
    
    return ret;
winlin authored
3926 3927 3928 3929
}

SrsSetChunkSizePacket::SrsSetChunkSizePacket()
{
3930
    chunk_size = SRS_CONSTS_RTMP_PROTOCOL_CHUNK_SIZE;
winlin authored
3931 3932 3933 3934 3935 3936 3937 3938
}

SrsSetChunkSizePacket::~SrsSetChunkSizePacket()
{
}

int SrsSetChunkSizePacket::decode(SrsStream* stream)
{
3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(4)) {
        ret = ERROR_RTMP_MESSAGE_DECODE;
        srs_error("decode chunk size failed. ret=%d", ret);
        return ret;
    }
    
    chunk_size = stream->read_4bytes();
    srs_info("decode chunk size success. chunk_size=%d", chunk_size);
    
    return ret;
winlin authored
3951 3952
}
3953
int SrsSetChunkSizePacket::get_prefer_cid()
winlin authored
3954
{
3955
    return RTMP_CID_ProtocolControl;
winlin authored
3956 3957 3958 3959
}

int SrsSetChunkSizePacket::get_message_type()
{
3960
    return RTMP_MSG_SetChunkSize;
winlin authored
3961 3962 3963 3964
}

int SrsSetChunkSizePacket::get_size()
{
3965
    return 4;
winlin authored
3966 3967 3968 3969
}

int SrsSetChunkSizePacket::encode_packet(SrsStream* stream)
{
3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(4)) {
        ret = ERROR_RTMP_MESSAGE_ENCODE;
        srs_error("encode chunk packet failed. ret=%d", ret);
        return ret;
    }
    
    stream->write_4bytes(chunk_size);
    
    srs_verbose("encode chunk packet success. ack_size=%d", chunk_size);
    
    return ret;
winlin authored
3983 3984 3985 3986
}

SrsSetPeerBandwidthPacket::SrsSetPeerBandwidthPacket()
{
3987
    bandwidth = 0;
3988
    type = SrsPeerBandwidthDynamic;
winlin authored
3989 3990 3991 3992 3993 3994
}

SrsSetPeerBandwidthPacket::~SrsSetPeerBandwidthPacket()
{
}
3995
int SrsSetPeerBandwidthPacket::get_prefer_cid()
winlin authored
3996
{
3997
    return RTMP_CID_ProtocolControl;
winlin authored
3998 3999 4000 4001
}

int SrsSetPeerBandwidthPacket::get_message_type()
{
4002
    return RTMP_MSG_SetPeerBandwidth;
winlin authored
4003 4004 4005 4006
}

int SrsSetPeerBandwidthPacket::get_size()
{
4007
    return 5;
winlin authored
4008 4009 4010 4011
}

int SrsSetPeerBandwidthPacket::encode_packet(SrsStream* stream)
{
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(5)) {
        ret = ERROR_RTMP_MESSAGE_ENCODE;
        srs_error("encode set bandwidth packet failed. ret=%d", ret);
        return ret;
    }
    
    stream->write_4bytes(bandwidth);
    stream->write_1bytes(type);
    
    srs_verbose("encode set bandwidth packet "
        "success. bandwidth=%d, type=%d", bandwidth, type);
    
    return ret;
winlin authored
4027 4028 4029 4030
}

SrsUserControlPacket::SrsUserControlPacket()
{
4031 4032 4033
    event_type = 0;
    event_data = 0;
    extra_data = 0;
winlin authored
4034 4035 4036 4037 4038 4039 4040 4041
}

SrsUserControlPacket::~SrsUserControlPacket()
{
}

int SrsUserControlPacket::decode(SrsStream* stream)
{
4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(6)) {
        ret = ERROR_RTMP_MESSAGE_DECODE;
        srs_error("decode user control failed. ret=%d", ret);
        return ret;
    }
    
    event_type = stream->read_2bytes();
    event_data = stream->read_4bytes();
    
    if (event_type == SrcPCUCSetBufferLength) {
        if (!stream->require(4)) {
            ret = ERROR_RTMP_MESSAGE_ENCODE;
            srs_error("decode user control packet failed. ret=%d", ret);
            return ret;
        }
        extra_data = stream->read_4bytes();
    }
    
    srs_info("decode user control success. "
        "event_type=%d, event_data=%d, extra_data=%d", 
        event_type, event_data, extra_data);
    
    return ret;
winlin authored
4067 4068
}
4069
int SrsUserControlPacket::get_prefer_cid()
winlin authored
4070
{
4071
    return RTMP_CID_ProtocolControl;
winlin authored
4072 4073 4074 4075
}

int SrsUserControlPacket::get_message_type()
{
4076
    return RTMP_MSG_UserControlMessage;
winlin authored
4077 4078 4079 4080
}

int SrsUserControlPacket::get_size()
{
4081 4082 4083 4084 4085
    if (event_type == SrcPCUCSetBufferLength) {
        return 2 + 4 + 4;
    } else {
        return 2 + 4;
    }
winlin authored
4086 4087 4088 4089
}

int SrsUserControlPacket::encode_packet(SrsStream* stream)
{
4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
    int ret = ERROR_SUCCESS;
    
    if (!stream->require(get_size())) {
        ret = ERROR_RTMP_MESSAGE_ENCODE;
        srs_error("encode user control packet failed. ret=%d", ret);
        return ret;
    }
    
    stream->write_2bytes(event_type);
    stream->write_4bytes(event_data);

    // when event type is set buffer length,
    // write the extra buffer length.
    if (event_type == SrcPCUCSetBufferLength) {
4104
        stream->write_4bytes(extra_data);
4105 4106 4107 4108 4109 4110 4111
        srs_verbose("user control message, buffer_length=%d", extra_data);
    }
    
    srs_verbose("encode user control packet success. "
        "event_type=%d, event_data=%d", event_type, event_data);
    
    return ret;
winlin authored
4112
}
4113
4114