Blame view

trunk/src/rtmp/srs_protocol_rtmp_stack.cpp 106.8 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_rtmp_stack.hpp>
winlin authored
25
26
#include <srs_kernel_log.hpp>
27
#include <srs_protocol_amf0.hpp>
28
#include <srs_kernel_error.hpp>
29
#include <srs_protocol_io.hpp>
30
#include <srs_kernel_buffer.hpp>
winlin authored
31
#include <srs_kernel_stream.hpp>
winlin authored
32 33
#include <srs_core_autofree.hpp>
34 35
using namespace std;
winlin authored
36 37 38 39 40 41 42 43 44 45 46 47
/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
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.
*/
48 49 50 51 52 53
#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
winlin authored
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#define RTMP_MSG_EdgeAndOriginServerCommand 0x07
/**
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.
*/
74 75
#define RTMP_MSG_AMF3CommandMessage         17 // 0x11
#define RTMP_MSG_AMF0CommandMessage         20 // 0x14
winlin authored
76 77 78 79 80 81 82 83
/**
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.        
*/
84 85
#define RTMP_MSG_AMF0DataMessage             18 // 0x12
#define RTMP_MSG_AMF3DataMessage             15 // 0x0F
winlin authored
86 87 88 89 90 91 92 93
/**
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.
*/
94 95
#define RTMP_MSG_AMF3SharedObject             16 // 0x10
#define RTMP_MSG_AMF0SharedObject             19 // 0x13
winlin authored
96 97 98 99 100
/**
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.
*/
101
#define RTMP_MSG_AudioMessage                 8 // 0x08
winlin authored
102 103 104 105 106 107 108 109
/* *
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.
*/
110
#define RTMP_MSG_VideoMessage                 9 // 0x09
winlin authored
111 112 113 114 115 116
/**
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.
*/
117
#define RTMP_MSG_AggregateMessage             22 // 0x16
winlin authored
118 119 120 121 122 123 124 125 126 127 128 129 130

/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* 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).
131
#define RTMP_FMT_TYPE0                         0
winlin authored
132 133 134 135 136 137
// 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.
138
#define RTMP_FMT_TYPE1                         1
winlin authored
139 140 141 142 143 144
// 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.
145
#define RTMP_FMT_TYPE2                         2
winlin authored
146 147 148 149 150 151 152 153 154 155 156 157 158 159
// 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.
160
#define RTMP_FMT_TYPE3                         3
winlin authored
161 162 163 164 165 166 167 168 169 170 171 172 173 174

/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* 6. Chunking
* The chunk size is configurable. It can be set using a control
* message(Set Chunk Size) as described in section 7.1. The maximum
* chunk size can be 65536 bytes and minimum 128 bytes. Larger values
* reduce CPU usage, but also commit to larger writes that can delay
* other content on lower bandwidth connections. Smaller chunks are not
* good for high-bit rate streaming. Chunk size is maintained
* independently for each direction.
*/
175 176 177
#define RTMP_DEFAULT_CHUNK_SIZE             128
#define RTMP_MIN_CHUNK_SIZE                 128
#define RTMP_MAX_CHUNK_SIZE                    65536
winlin authored
178 179 180 181 182 183 184 185 186 187 188 189

/**
* 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.
*/
190
#define RTMP_EXTENDED_TIMESTAMP             0xFFFFFF
winlin authored
191 192 193 194 195 196 197

/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* amf0 command message, command name macros
*/
198 199
#define RTMP_AMF0_COMMAND_CONNECT            "connect"
#define RTMP_AMF0_COMMAND_CREATE_STREAM        "createStream"
200
#define RTMP_AMF0_COMMAND_CLOSE_STREAM      "closeStream"
201 202 203 204 205 206 207 208 209 210 211 212 213
#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
214
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
/**
* 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
#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"

// server publish control
#define SRS_BW_CHECK_START_PUBLISH      "onSrsBandCheckStartPublishBytes"
#define SRS_BW_CHECK_STARTING_PUBLISH   "onSrsBandCheckStartingPublishBytes"
#define SRS_BW_CHECK_STOP_PUBLISH       "onSrsBandCheckStopPublishBytes"
#define SRS_BW_CHECK_STOPPED_PUBLISH    "onSrsBandCheckStoppedPublishBytes"

// EOF control.
#define SRS_BW_CHECK_FINISHED           "onSrsBandCheckFinished"
// for flash, it will sendout a final call, 
// used to confirm got the report.
winlin authored
236 237
// actually, client send out this packet and close the connection,
// so server may cannot got this packet, ignore is ok.
238 239 240 241 242 243
#define SRS_BW_CHECK_FLASH_FINAL        "finalClientPacket"

// client only
#define SRS_BW_CHECK_PLAYING            "onSrsBandCheckPlaying"
#define SRS_BW_CHECK_PUBLISHING         "onSrsBandCheckPublishing"
winlin authored
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
/****************************************************************************
*****************************************************************************
****************************************************************************/
/**
* the chunk stream id used for some under-layer message,
* for example, the PC(protocol control) message.
*/
#define RTMP_CID_ProtocolControl 0x02
/**
* the AMF0/AMF3 command message, invoke method and return the result, over NetConnection.
* generally use 0x03.
*/
#define RTMP_CID_OverConnection 0x03
/**
* 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).
*/
#define RTMP_CID_OverConnection2 0x04
/**
* the stream message(amf0/amf3), over NetStream.
* generally use 0x05.
*/
#define RTMP_CID_OverStream 0x05
/**
* the stream message(amf0/amf3), over NetStream, the midst state(we guess).
* rarely used, e.g. play("mp4:mystram.f4v")
*/
#define RTMP_CID_OverStream2 0x08
/**
* the stream message(video), over NetStream
* generally use 0x06.
*/
#define RTMP_CID_Video 0x06
/**
* the stream message(audio), over NetStream.
* generally use 0x07.
*/
#define RTMP_CID_Audio 0x07

/****************************************************************************
*****************************************************************************
****************************************************************************/

SrsProtocol::AckWindowSize::AckWindowSize()
{
290
    ack_window_size = acked_size = 0;
winlin authored
291 292
}
293
SrsProtocol::SrsProtocol(ISrsProtocolReaderWriter* io)
winlin authored
294
{
295 296 297 298
    buffer = new SrsBuffer();
    skt = io;
    
    in_chunk_size = out_chunk_size = RTMP_DEFAULT_CHUNK_SIZE;
winlin authored
299 300 301 302
}

SrsProtocol::~SrsProtocol()
{
303 304 305 306 307 308
    std::map<int, SrsChunkStream*>::iterator it;
    
    for (it = chunk_streams.begin(); it != chunk_streams.end(); ++it) {
        SrsChunkStream* stream = it->second;
        srs_freep(stream);
    }
winlin authored
309
310 311 312
    chunk_streams.clear();
    
    srs_freep(buffer);
winlin authored
313 314
}
315
string SrsProtocol::get_request_name(double transcationId)
winlin authored
316
{
317 318 319 320 321
    if (requests.find(transcationId) == requests.end()) {
        return "";
    }
    
    return requests[transcationId];
winlin authored
322 323
}
winlin authored
324 325
void SrsProtocol::set_recv_timeout(int64_t timeout_us)
{
326
    return skt->set_recv_timeout(timeout_us);
winlin authored
327 328 329 330
}

int64_t SrsProtocol::get_recv_timeout()
{
331
    return skt->get_recv_timeout();
winlin authored
332 333 334 335
}

void SrsProtocol::set_send_timeout(int64_t timeout_us)
{
336
    return skt->set_send_timeout(timeout_us);
winlin authored
337 338
}
339 340
int64_t SrsProtocol::get_send_timeout()
{
341
    return skt->get_send_timeout();
342 343
}
winlin authored
344 345
int64_t SrsProtocol::get_recv_bytes()
{
346
    return skt->get_recv_bytes();
winlin authored
347 348 349 350
}

int64_t SrsProtocol::get_send_bytes()
{
351
    return skt->get_send_bytes();
winlin authored
352 353 354 355
}

int SrsProtocol::get_recv_kbps()
{
356
    return skt->get_recv_kbps();
winlin authored
357 358 359 360
}

int SrsProtocol::get_send_kbps()
{
361
    return skt->get_send_kbps();
winlin authored
362 363 364 365
}

int SrsProtocol::recv_message(SrsCommonMessage** pmsg)
{
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 399 400 401 402 403 404
    *pmsg = NULL;
    
    int ret = ERROR_SUCCESS;
    
    while (true) {
        SrsCommonMessage* msg = NULL;
        
        if ((ret = recv_interlaced_message(&msg)) != ERROR_SUCCESS) {
            if (ret != ERROR_SOCKET_TIMEOUT && !srs_is_client_gracefully_close(ret)) {
                srs_error("recv interlaced message failed. ret=%d", ret);
            }
            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;
        }
        
        if ((ret = on_recv_message(msg)) != ERROR_SUCCESS) {
            srs_error("hook the received msg failed. ret=%d", ret);
            srs_freep(msg);
            return ret;
        }
        
        srs_verbose("get a msg with raw/undecoded payload");
        *pmsg = msg;
        break;
    }
    
    return ret;
winlin authored
405 406 407 408
}

int SrsProtocol::send_message(ISrsMessage* msg)
{
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 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 482 483 484 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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
    int ret = ERROR_SUCCESS;
    
    // free msg whatever return value.
    SrsAutoFree(ISrsMessage, msg, false);
    
    if ((ret = msg->encode_packet()) != ERROR_SUCCESS) {
        srs_error("encode packet to message payload failed. ret=%d", ret);
        return ret;
    }
    srs_info("encode packet to message payload success");

    // p set to current write position,
    // it's ok when payload is NULL and size is 0.
    char* p = (char*)msg->payload;
    
    // always write the header event payload is empty.
    do {
        // generate the header.
        char* pheader = NULL;
        int header_size = 0;
        
        if (p == (char*)msg->payload) {
            // write new chunk stream header, fmt is 0
            pheader = out_header_fmt0;
            *pheader++ = 0x00 | (msg->get_perfer_cid() & 0x3F);
            
            // chunk message header, 11 bytes
            // timestamp, 3bytes, big-endian
            u_int32_t timestamp = (u_int32_t)msg->header.timestamp;
            if (timestamp >= RTMP_EXTENDED_TIMESTAMP) {
                *pheader++ = 0xFF;
                *pheader++ = 0xFF;
                *pheader++ = 0xFF;
            } else {
                pp = (char*)&timestamp;
                *pheader++ = pp[2];
                *pheader++ = pp[1];
                *pheader++ = pp[0];
            }
            
            // message_length, 3bytes, big-endian
            pp = (char*)&msg->header.payload_length;
            *pheader++ = pp[2];
            *pheader++ = pp[1];
            *pheader++ = pp[0];
            
            // message_type, 1bytes
            *pheader++ = msg->header.message_type;
            
            // message_length, 3bytes, little-endian
            pp = (char*)&msg->header.stream_id;
            *pheader++ = pp[0];
            *pheader++ = pp[1];
            *pheader++ = pp[2];
            *pheader++ = pp[3];
            
            // chunk extended timestamp header, 0 or 4 bytes, big-endian
            if(timestamp >= RTMP_EXTENDED_TIMESTAMP){
                pp = (char*)&timestamp;
                *pheader++ = pp[3];
                *pheader++ = pp[2];
                *pheader++ = pp[1];
                *pheader++ = pp[0];
            }
            
            header_size = pheader - out_header_fmt0;
            pheader = out_header_fmt0;
        } else {
            // write no message header chunk stream, fmt is 3
            pheader = out_header_fmt3;
            *pheader++ = 0xC0 | (msg->get_perfer_cid() & 0x3F);
            
            // 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
            u_int32_t timestamp = (u_int32_t)msg->header.timestamp;
            if(timestamp >= RTMP_EXTENDED_TIMESTAMP){
                pp = (char*)&timestamp; 
                *pheader++ = pp[3];
                *pheader++ = pp[2];
                *pheader++ = pp[1];
                *pheader++ = pp[0];
            }
            
            header_size = pheader - out_header_fmt3;
            pheader = out_header_fmt3;
        }
        
        // sendout header and payload by writev.
        // decrease the sys invoke count to get higher performance.
        int payload_size = msg->size - (p - (char*)msg->payload);
        payload_size = srs_min(payload_size, out_chunk_size);
        
        // send by writev
        iovec iov[2];
        iov[0].iov_base = pheader;
        iov[0].iov_len = header_size;
        iov[1].iov_base = p;
        iov[1].iov_len = payload_size;
        
        ssize_t nwrite;
        if ((ret = skt->writev(iov, 2, &nwrite)) != ERROR_SUCCESS) {
            srs_error("send with writev failed. ret=%d", ret);
            return ret;
        }
        
        // consume sendout bytes when not empty packet.
        if (msg->payload && msg->size > 0) {
            p += payload_size;
        }
    } while (p < (char*)msg->payload + msg->size);
    
    if ((ret = on_send_message(msg)) != ERROR_SUCCESS) {
        srs_error("hook the send message failed. ret=%d", ret);
        return ret;
    }
    
    return ret;
winlin authored
537 538 539 540
}

int SrsProtocol::response_acknowledgement_message()
{
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    int ret = ERROR_SUCCESS;
    
    SrsCommonMessage* msg = new SrsCommonMessage();
    SrsAcknowledgementPacket* pkt = new SrsAcknowledgementPacket();
    
    in_ack_size.acked_size = pkt->sequence_number = skt->get_recv_bytes();
    msg->set_packet(pkt, 0);
    
    if ((ret = send_message(msg)) != ERROR_SUCCESS) {
        srs_error("send acknowledgement failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("send acknowledgement success.");
    
    return ret;
winlin authored
556 557 558 559
}

int SrsProtocol::response_ping_message(int32_t timestamp)
{
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    int ret = ERROR_SUCCESS;
    
    srs_trace("get a ping request, response it. timestamp=%d", timestamp);
    
    SrsCommonMessage* msg = new SrsCommonMessage();
    SrsUserControlPacket* pkt = new SrsUserControlPacket();
    
    pkt->event_type = SrcPCUCPingResponse;
    pkt->event_data = timestamp;
    msg->set_packet(pkt, 0);
    
    if ((ret = send_message(msg)) != ERROR_SUCCESS) {
        srs_error("send ping response failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("send ping response success.");
    
    return ret;
winlin authored
578 579 580 581
}

int SrsProtocol::on_recv_message(SrsCommonMessage* msg)
{
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 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
    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;
        }
    }
    
    switch (msg->header.message_type) {
        case RTMP_MSG_SetChunkSize:
        case RTMP_MSG_UserControlMessage:
        case RTMP_MSG_WindowAcknowledgementSize:
            if ((ret = msg->decode_packet(this)) != ERROR_SUCCESS) {
                srs_error("decode packet from message payload failed. ret=%d", ret);
                return ret;
            }
            srs_verbose("decode packet from message payload success.");
            break;
    }
    
    switch (msg->header.message_type) {
        case RTMP_MSG_WindowAcknowledgementSize: {
            SrsSetWindowAckSizePacket* pkt = dynamic_cast<SrsSetWindowAckSizePacket*>(msg->get_packet());
            srs_assert(pkt != NULL);
            
            if (pkt->ackowledgement_window_size > 0) {
                in_ack_size.ack_window_size = pkt->ackowledgement_window_size;
                srs_trace("set ack window size to %d", pkt->ackowledgement_window_size);
            } else {
                srs_warn("ignored. set ack window size is %d", pkt->ackowledgement_window_size);
            }
            break;
        }
        case RTMP_MSG_SetChunkSize: {
            SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(msg->get_packet());
            srs_assert(pkt != NULL);
            
            in_chunk_size = pkt->chunk_size;
            
            srs_trace("set input chunk size to %d", pkt->chunk_size);
            break;
        }
        case RTMP_MSG_UserControlMessage: {
            SrsUserControlPacket* pkt = dynamic_cast<SrsUserControlPacket*>(msg->get_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;
        }
    }
    
    return ret;
winlin authored
644 645 646 647
}

int SrsProtocol::on_send_message(ISrsMessage* msg)
{
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 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
    int ret = ERROR_SUCCESS;
    
    if (!msg->can_decode()) {
        srs_verbose("ignore the un-decodable message.");
        return ret;
    }
    
    SrsCommonMessage* common_msg = dynamic_cast<SrsCommonMessage*>(msg);
    if (!msg) {
        srs_verbose("ignore the shared ptr message.");
        return ret;
    }
    
    srs_assert(common_msg != NULL);
    
    switch (common_msg->header.message_type) {
        case RTMP_MSG_SetChunkSize: {
            SrsSetChunkSizePacket* pkt = dynamic_cast<SrsSetChunkSizePacket*>(common_msg->get_packet());
            srs_assert(pkt != NULL);
            
            out_chunk_size = pkt->chunk_size;
            
            srs_trace("set output chunk size to %d", pkt->chunk_size);
            break;
        }
        case RTMP_MSG_AMF0CommandMessage:
        case RTMP_MSG_AMF3CommandMessage: {
            if (true) {
                SrsConnectAppPacket* pkt = NULL;
                pkt = dynamic_cast<SrsConnectAppPacket*>(common_msg->get_packet());
                if (pkt) {
                    requests[pkt->transaction_id] = pkt->command_name;
                    break;
                }
            }
            if (true) {
                SrsCreateStreamPacket* pkt = NULL;
                pkt = dynamic_cast<SrsCreateStreamPacket*>(common_msg->get_packet());
                if (pkt) {
                    requests[pkt->transaction_id] = pkt->command_name;
                    break;
                }
            }
            if (true) {
                SrsFMLEStartPacket* pkt = NULL;
                pkt = dynamic_cast<SrsFMLEStartPacket*>(common_msg->get_packet());
                if (pkt) {
                    requests[pkt->transaction_id] = pkt->command_name;
                    break;
                }
            }
            break;
        }
    }
    
    return ret;
winlin authored
704 705 706 707
}

int SrsProtocol::recv_interlaced_message(SrsCommonMessage** pmsg)
{
708 709 710 711 712 713 714 715 716 717 718 719 720 721 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 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
    int ret = ERROR_SUCCESS;
    
    // chunk stream basic header.
    char fmt = 0;
    int cid = 0;
    int bh_size = 0;
    if ((ret = read_basic_header(fmt, cid, bh_size)) != ERROR_SUCCESS) {
        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.
    SrsChunkStream* chunk = NULL;
    
    if (chunk_streams.find(cid) == chunk_streams.end()) {
        chunk = chunk_streams[cid] = new SrsChunkStream(cid);
        srs_verbose("cache new chunk stream: fmt=%d, cid=%d", fmt, cid);
    } else {
        chunk = chunk_streams[cid];
        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;
    if ((ret = read_message_header(chunk, fmt, bh_size, mh_size)) != ERROR_SUCCESS) {
        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.
    SrsCommonMessage* msg = NULL;
    int payload_size = 0;
    if ((ret = read_message_payload(chunk, bh_size, mh_size, payload_size, &msg)) != ERROR_SUCCESS) {
        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;
winlin authored
792 793 794 795
}

int SrsProtocol::read_basic_header(char& fmt, int& cid, int& bh_size)
{
796 797 798 799 800 801 802 803 804 805 806 807
    int ret = ERROR_SUCCESS;
    
    int required_size = 1;
    if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) {
        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;
    }
    
    char* p = buffer->bytes();
    
winlin authored
808 809 810 811 812
    fmt = (*p >> 6) & 0x03;
    cid = *p & 0x3f;
    bh_size = 1;
    
    if (cid > 1) {
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 838 839 840 841 842 843 844 845 846 847 848 849
        srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid);
        return ret;
    }

    if (cid == 0) {
        required_size = 2;
        if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) {
            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;
        cid += *(++p);
        bh_size = 2;
        srs_verbose("%dbytes basic header parsed. fmt=%d, cid=%d", bh_size, fmt, cid);
    } else if (cid == 1) {
        required_size = 3;
        if ((ret = buffer->ensure_buffer_bytes(skt, 3)) != ERROR_SUCCESS) {
            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;
        cid += *(++p);
        cid += *(++p) * 256;
        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;
winlin authored
850 851 852 853
}

int SrsProtocol::read_message_header(SrsChunkStream* chunk, char fmt, int bh_size, int& mh_size)
{
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 880 881 882 883 884 885 886 887 888 889 890 891 892 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 919 920
    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:
    *     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
    * 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.
    bool is_fresh_packet = !chunk->msg;
    
    // 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) {
        ret = ERROR_RTMP_CHUNK_START;
        srs_error("chunk stream is fresh, "
            "fmt must be %d, actual is %d. ret=%d", RTMP_FMT_TYPE0, fmt, ret);
        return ret;
    }

    // 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) {
        chunk->msg = new SrsCommonMessage();
        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;
    if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) {
        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;
    }
    char* p = buffer->bytes() + bh_size;
    
    // parse the message header.
    // see also: ngx_rtmp_recv
    if (fmt <= RTMP_FMT_TYPE2) {
winlin authored
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
        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);
        if (chunk->extended_timestamp) {
            // 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.
950
            //
winlin authored
951 952 953
            // if extended timestamp, the timestamp must >= RTMP_EXTENDED_TIMESTAMP
            // we set the timestamp to RTMP_EXTENDED_TIMESTAMP to identify we
            // got an extended timestamp.
954
            chunk->header.timestamp = RTMP_EXTENDED_TIMESTAMP;
winlin authored
955
        } else {
956 957 958 959 960 961 962 963 964 965 966 967
            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;
            }
winlin authored
968 969 970 971 972 973 974 975 976 977 978 979 980
        }
        
        if (fmt <= RTMP_FMT_TYPE1) {
            pp = (char*)&chunk->header.payload_length;
            pp[2] = *p++;
            pp[1] = *p++;
            pp[0] = *p++;
            pp[3] = 0;
            
            // if msg exists in cache, the size must not changed.
            if (chunk->msg->size > 0 && chunk->msg->size != chunk->header.payload_length) {
                ret = ERROR_RTMP_PACKET_SIZE;
                srs_error("msg exists in chunk cache, "
981 982
                    "size=%d cannot change to %d, ret=%d", 
                    chunk->msg->size, chunk->header.payload_length, ret);
winlin authored
983 984 985 986 987
                return ret;
            }
            
            chunk->header.message_type = *p++;
            
988
            if (fmt == RTMP_FMT_TYPE0) {
winlin authored
989 990 991 992 993
                pp = (char*)&chunk->header.stream_id;
                pp[0] = *p++;
                pp[1] = *p++;
                pp[2] = *p++;
                pp[3] = *p++;
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
                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 {
        // update the timestamp even fmt=3 for first stream
        if (is_fresh_packet && !chunk->extended_timestamp) {
            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);
    }
    
    if (chunk->extended_timestamp) {
        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);
        if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) {
            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;
winlin authored
1027 1028 1029 1030 1031 1032
        char* pp = (char*)&timestamp;
        pp[3] = *p++;
        pp[2] = *p++;
        pp[1] = *p++;
        pp[0] = *p++;
        
1033 1034
        // ffmpeg/librtmp may donot send this filed, need to detect the value.
        // @see also: http://blog.csdn.net/win_lin/article/details/13363699
winlin authored
1035 1036
        // compare to the chunk timestamp, which is set by chunk message header
        // type 0,1 or 2.
1037
        u_int32_t chunk_timestamp = chunk->header.timestamp;
winlin authored
1038 1039 1040 1041 1042 1043
        if (chunk_timestamp > RTMP_EXTENDED_TIMESTAMP && chunk_timestamp != timestamp) {
            mh_size -= 4;
            srs_verbose("ignore the 4bytes extended timestamp. mh_size=%d", mh_size);
        } else {
            chunk->header.timestamp = timestamp;
        }
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
        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.
1066 1067
    // convert extended timestamp to 31bits.
    chunk->header.timestamp &= 0x7fffffff;
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    
    // valid message
    if (chunk->header.payload_length < 0) {
        ret = ERROR_RTMP_MSG_INVLIAD_SIZE;
        srs_error("RTMP message size must not be negative. size=%d, ret=%d", 
            chunk->header.payload_length, ret);
        return ret;
    }
    
    // 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;
winlin authored
1084 1085 1086 1087
}

int SrsProtocol::read_message_payload(SrsChunkStream* chunk, int bh_size, int mh_size, int& payload_size, SrsCommonMessage** pmsg)
{
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    int ret = ERROR_SUCCESS;
    
    // empty message
    if (chunk->header.payload_length <= 0) {
        // need erase the header in buffer.
        buffer->erase(bh_size + mh_size);
        
        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;
    }
    srs_assert(chunk->header.payload_length > 0);
    
    // 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);

    // create msg payload if not initialized
    if (!chunk->msg->payload) {
        chunk->msg->payload = new int8_t[chunk->header.payload_length];
        memset(chunk->msg->payload, 0, chunk->header.payload_length);
        srs_verbose("create empty payload for RTMP message. size=%d", chunk->header.payload_length);
    }
    
    // read payload to buffer
    int required_size = bh_size + mh_size + payload_size;
    if ((ret = buffer->ensure_buffer_bytes(skt, required_size)) != ERROR_SUCCESS) {
        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;
    }
    memcpy(chunk->msg->payload + chunk->msg->size, buffer->bytes() + bh_size + mh_size, payload_size);
    buffer->erase(bh_size + mh_size + payload_size);
    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
1149 1150 1151 1152
}

SrsMessageHeader::SrsMessageHeader()
{
1153 1154 1155 1156 1157 1158
    message_type = 0;
    payload_length = 0;
    timestamp_delta = 0;
    stream_id = 0;
    
    timestamp = 0;
winlin authored
1159 1160 1161 1162 1163 1164 1165 1166
}

SrsMessageHeader::~SrsMessageHeader()
{
}

bool SrsMessageHeader::is_audio()
{
1167
    return message_type == RTMP_MSG_AudioMessage;
winlin authored
1168 1169 1170 1171
}

bool SrsMessageHeader::is_video()
{
1172
    return message_type == RTMP_MSG_VideoMessage;
winlin authored
1173 1174 1175 1176
}

bool SrsMessageHeader::is_amf0_command()
{
1177
    return message_type == RTMP_MSG_AMF0CommandMessage;
winlin authored
1178 1179 1180 1181
}

bool SrsMessageHeader::is_amf0_data()
{
1182
    return message_type == RTMP_MSG_AMF0DataMessage;
winlin authored
1183 1184 1185 1186
}

bool SrsMessageHeader::is_amf3_command()
{
1187
    return message_type == RTMP_MSG_AMF3CommandMessage;
winlin authored
1188 1189 1190 1191
}

bool SrsMessageHeader::is_amf3_data()
{
1192
    return message_type == RTMP_MSG_AMF3DataMessage;
winlin authored
1193 1194 1195 1196
}

bool SrsMessageHeader::is_window_ackledgement_size()
{
1197
    return message_type == RTMP_MSG_WindowAcknowledgementSize;
winlin authored
1198 1199 1200 1201
}

bool SrsMessageHeader::is_set_chunk_size()
{
1202
    return message_type == RTMP_MSG_SetChunkSize;
winlin authored
1203 1204 1205 1206
}

bool SrsMessageHeader::is_user_control_message()
{
1207
    return message_type == RTMP_MSG_UserControlMessage;
winlin authored
1208 1209
}
1210 1211
void SrsMessageHeader::initialize_amf0_script(int size, int stream)
{
1212 1213 1214 1215 1216
    message_type = RTMP_MSG_AMF0DataMessage;
    payload_length = (int32_t)size;
    timestamp_delta = (int32_t)0;
    timestamp = (int64_t)0;
    stream_id = (int32_t)stream;
1217 1218 1219 1220
}

void SrsMessageHeader::initialize_audio(int size, u_int32_t time, int stream)
{
1221 1222 1223 1224 1225
    message_type = RTMP_MSG_AudioMessage;
    payload_length = (int32_t)size;
    timestamp_delta = (int32_t)time;
    timestamp = (int64_t)time;
    stream_id = (int32_t)stream;
1226 1227 1228 1229
}

void SrsMessageHeader::initialize_video(int size, u_int32_t time, int stream)
{
1230 1231 1232 1233 1234
    message_type = RTMP_MSG_VideoMessage;
    payload_length = (int32_t)size;
    timestamp_delta = (int32_t)time;
    timestamp = (int64_t)time;
    stream_id = (int32_t)stream;
1235 1236
}
winlin authored
1237 1238
SrsChunkStream::SrsChunkStream(int _cid)
{
1239 1240 1241 1242 1243
    fmt = 0;
    cid = _cid;
    extended_timestamp = false;
    msg = NULL;
    msg_count = 0;
winlin authored
1244 1245 1246 1247
}

SrsChunkStream::~SrsChunkStream()
{
1248
    srs_freep(msg);
winlin authored
1249 1250 1251 1252
}

ISrsMessage::ISrsMessage()
{
1253 1254
    payload = NULL;
    size = 0;
winlin authored
1255 1256 1257
}

ISrsMessage::~ISrsMessage()
1258
{    
winlin authored
1259 1260 1261 1262
}

SrsCommonMessage::SrsCommonMessage()
{
1263 1264
    stream = NULL;
    packet = NULL;
winlin authored
1265 1266 1267
}

SrsCommonMessage::~SrsCommonMessage()
1268 1269 1270 1271 1272 1273 1274 1275
{    
    // we must directly free the ptrs,
    // nevery use the virtual functions to delete,
    // for in the destructor, the virtual functions is disabled.
    
    srs_freepa(payload);
    srs_freep(packet);
    srs_freep(stream);
winlin authored
1276 1277 1278 1279
}

bool SrsCommonMessage::can_decode()
{
1280
    return true;
winlin authored
1281 1282
}
winlin authored
1283
int SrsCommonMessage::decode_packet(SrsProtocol* protocol)
winlin authored
1284
{
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
    int ret = ERROR_SUCCESS;
    
    srs_assert(payload != NULL);
    srs_assert(size > 0);
    
    if (packet) {
        srs_verbose("msg already decoded");
        return ret;
    }
    
    if (!stream) {
        srs_verbose("create decode stream for message.");
        stream = new SrsStream();
    }
    
    // initialize the decode stream for all message,
    // it's ok for the initialize if fast and without memory copy.
    if ((ret = stream->initialize((char*)payload, size)) != ERROR_SUCCESS) {
        srs_error("initialize stream failed. ret=%d", ret);
        return ret;
    }
    srs_verbose("decode stream initialized success");
    
    // 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.
            stream->reset();
            if (header.is_amf3_command()) {
                stream->skip(1);
            }
            
            std::string request_name = protocol->get_request_name(transactionId);
            if (request_name.empty()) {
                ret = ERROR_RTMP_NO_REQUEST;
                srs_error("decode AMF0/AMF3 request failed. ret=%d", ret);
                return ret;
            }
            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());
                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());
                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());
                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.
        stream->reset();
        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).");
            packet = new SrsConnectAppPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_CREATE_STREAM) {
            srs_info("decode the AMF0/AMF3 command(createStream message).");
            packet = new SrsCreateStreamPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_PLAY) {
            srs_info("decode the AMF0/AMF3 command(paly message).");
            packet = new SrsPlayPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_PAUSE) {
            srs_info("decode the AMF0/AMF3 command(pause message).");
            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).");
            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).");
            packet = new SrsFMLEStartPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_PUBLISH) {
            srs_info("decode the AMF0/AMF3 command(publish message).");
            packet = new SrsPublishPacket();
            return packet->decode(stream);
        } else if(command == RTMP_AMF0_COMMAND_UNPUBLISH) {
            srs_info("decode the AMF0/AMF3 command(unpublish message).");
            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).");
            packet = new SrsOnMetaDataPacket();
            return packet->decode(stream);
1416
        } else if(command == SRS_BW_CHECK_FINISHED
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
            || 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
            || command == SRS_BW_CHECK_FLASH_FINAL)
1428 1429
        {
            srs_info("decode the AMF0/AMF3 band width check message.");
1430
            packet = new SrsBandwidthPacket();
1431
            return packet->decode(stream);
1432 1433 1434 1435
        } else if (command == RTMP_AMF0_COMMAND_CLOSE_STREAM) {
            srs_info("decode the AMF0/AMF3 closeStream message.");
            packet = new SrsCloseStreamPacket();
            return packet->decode(stream);
1436
        }
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
        
        // default packet to drop message.
        srs_trace("drop the AMF0/AMF3 command message, command_name=%s", command.c_str());
        packet = new SrsPacket();
        return ret;
    } else if(header.is_user_control_message()) {
        srs_verbose("start to decode user control message.");
        packet = new SrsUserControlPacket();
        return packet->decode(stream);
    } else if(header.is_window_ackledgement_size()) {
        srs_verbose("start to decode set ack window size message.");
        packet = new SrsSetWindowAckSizePacket();
        return packet->decode(stream);
    } else if(header.is_set_chunk_size()) {
        srs_verbose("start to decode set chunk size message.");
        packet = new SrsSetChunkSizePacket();
        return packet->decode(stream);
    } else {
        // default packet to drop message.
        srs_trace("drop the unknown message, type=%d", header.message_type);
        packet = new SrsPacket();
    }
    
    return ret;
}

SrsPacket* SrsCommonMessage::get_packet()
winlin authored
1464
{
1465 1466 1467 1468 1469 1470
    if (!packet) {
        srs_error("the payload is raw/undecoded, invoke decode_packet to decode it.");
    }
    srs_assert(packet != NULL);
    
    return packet;
winlin authored
1471 1472 1473 1474
}

int SrsCommonMessage::get_perfer_cid()
{
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
    if (!packet) {
        return RTMP_CID_ProtocolControl;
    }
    
    // we donot use the complex basic header,
    // ensure the basic header is 1bytes.
    if (packet->get_perfer_cid() < 2) {
        return packet->get_perfer_cid();
    }
    
    return packet->get_perfer_cid();
winlin authored
1486 1487
}
1488
SrsCommonMessage* SrsCommonMessage::set_packet(SrsPacket* pkt, int stream_id)
winlin authored
1489
{
1490
    srs_freep(packet);
winlin authored
1491
1492 1493 1494 1495 1496 1497 1498
    packet = pkt;
    
    header.message_type = packet->get_message_type();
    header.payload_length = packet->get_payload_length();
    header.stream_id = stream_id;
    
    return this;
winlin authored
1499 1500 1501 1502
}

int SrsCommonMessage::encode_packet()
{
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
    int ret = ERROR_SUCCESS;
    
    if (packet == NULL) {
        srs_warn("packet is empty, send out empty message.");
        return ret;
    }
    // realloc the payload.
    size = 0;
    srs_freepa(payload);
    
    if ((ret = packet->encode(size, (char*&)payload)) != ERROR_SUCCESS) {
        return ret;
    }
    
    header.payload_length = size;
    
    return ret;
winlin authored
1520 1521 1522 1523
}

SrsSharedPtrMessage::SrsSharedPtr::SrsSharedPtr()
{
1524 1525 1526 1527
    payload = NULL;
    size = 0;
    perfer_cid = 0;
    shared_count = 0;
winlin authored
1528 1529 1530 1531
}

SrsSharedPtrMessage::SrsSharedPtr::~SrsSharedPtr()
{
1532
    srs_freepa(payload);
winlin authored
1533 1534 1535 1536
}

SrsSharedPtrMessage::SrsSharedPtrMessage()
{
1537
    ptr = NULL;
winlin authored
1538 1539 1540 1541
}

SrsSharedPtrMessage::~SrsSharedPtrMessage()
{
1542 1543 1544 1545 1546 1547 1548
    if (ptr) {
        if (ptr->shared_count == 0) {
            srs_freep(ptr);
        } else {
            ptr->shared_count--;
        }
    }
winlin authored
1549 1550 1551 1552
}

bool SrsSharedPtrMessage::can_decode()
{
1553
    return false;
winlin authored
1554 1555
}
winlin authored
1556
int SrsSharedPtrMessage::initialize(SrsCommonMessage* source)
winlin authored
1557
{
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    int ret = ERROR_SUCCESS;
    
    if ((ret = initialize(&source->header, (char*)source->payload, source->size)) != ERROR_SUCCESS) {
        return ret;
    }
    
    // detach the payload from source
    source->payload = NULL;
    source->size = 0;
    
    return ret;
winlin authored
1569 1570
}
1571
int SrsSharedPtrMessage::initialize(SrsMessageHeader* source, char* payload, int size)
winlin authored
1572
{
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    int ret = ERROR_SUCCESS;
    
    srs_assert(source != NULL);
    if (ptr) {
        ret = ERROR_SYSTEM_ASSERT_FAILED;
        srs_error("should not set the payload twice. ret=%d", ret);
        srs_assert(false);
        
        return ret;
    }
    
    header = *source;
    header.payload_length = size;
    
    ptr = new SrsSharedPtr();
    
    // direct attach the data of common message.
    ptr->payload = payload;
    ptr->size = size;
    
    if (source->is_video()) {
        ptr->perfer_cid = RTMP_CID_Video;
    } else if (source->is_audio()) {
        ptr->perfer_cid = RTMP_CID_Audio;
    } else {
        ptr->perfer_cid = RTMP_CID_OverConnection2;
    }
    
    super::payload = (int8_t*)ptr->payload;
    super::size = ptr->size;
    
    return ret;
winlin authored
1605 1606 1607 1608
}

SrsSharedPtrMessage* SrsSharedPtrMessage::copy()
{
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
    if (!ptr) {
        srs_error("invoke initialize to initialize the ptr.");
        srs_assert(false);
        return NULL;
    }
    
    SrsSharedPtrMessage* copy = new SrsSharedPtrMessage();
    
    copy->header = header;
    
    copy->ptr = ptr;
    ptr->shared_count++;
    
    copy->payload = (int8_t*)ptr->payload;
    copy->size = ptr->size;
    
    return copy;
winlin authored
1626 1627 1628 1629
}

int SrsSharedPtrMessage::get_perfer_cid()
{
1630 1631 1632 1633 1634
    if (!ptr) {
        return 0;
    }
    
    return ptr->perfer_cid;
winlin authored
1635 1636 1637 1638
}

int SrsSharedPtrMessage::encode_packet()
{
1639 1640
    srs_verbose("shared message ignore the encode method.");
    return ERROR_SUCCESS;
winlin authored
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
}

SrsPacket::SrsPacket()
{
}

SrsPacket::~SrsPacket()
{
}

int SrsPacket::decode(SrsStream* stream)
{
1653 1654 1655
    int ret = ERROR_SUCCESS;
    
    srs_assert(stream != NULL);
winlin authored
1656
1657 1658 1659 1660 1661
    ret = ERROR_SYSTEM_PACKET_INVALID;
    srs_error("current packet is not support to decode. "
        "paket=%s, ret=%d", get_class_name(), ret);
    
    return ret;
winlin authored
1662 1663 1664 1665
}

int SrsPacket::get_perfer_cid()
{
1666
    return 0;
winlin authored
1667 1668 1669 1670
}

int SrsPacket::get_message_type()
{
1671
    return 0;
winlin authored
1672 1673 1674 1675
}

int SrsPacket::get_payload_length()
{
1676
    return get_size();
winlin authored
1677 1678 1679 1680
}

int SrsPacket::encode(int& psize, char*& ppayload)
{
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
    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);
            srs_freepa(payload);
            return ret;
        }
    }
    
    if ((ret = encode_packet(&stream)) != ERROR_SUCCESS) {
        srs_error("encode the packet failed. ret=%d", ret);
        srs_freepa(payload);
        return ret;
    }
    
    psize = size;
    ppayload = payload;
    srs_verbose("encode the packet success. size=%d", size);
    
    return ret;
winlin authored
1709 1710 1711 1712
}

int SrsPacket::get_size()
{
1713
    return 0;
winlin authored
1714 1715 1716 1717
}

int SrsPacket::encode_packet(SrsStream* stream)
{
1718 1719 1720
    int ret = ERROR_SUCCESS;
    
    srs_assert(stream != NULL);
winlin authored
1721
1722 1723 1724 1725 1726
    ret = ERROR_SYSTEM_PACKET_INVALID;
    srs_error("current packet is not support to encode. "
        "paket=%s, ret=%d", get_class_name(), ret);
    
    return ret;
winlin authored
1727 1728 1729 1730
}

SrsConnectAppPacket::SrsConnectAppPacket()
{
1731 1732 1733
    command_name = RTMP_AMF0_COMMAND_CONNECT;
    transaction_id = 1;
    command_object = SrsAmf0Any::object();
winlin authored
1734 1735 1736 1737
}

SrsConnectAppPacket::~SrsConnectAppPacket()
{
1738
    srs_freep(command_object);
winlin authored
1739 1740 1741 1742
}

int SrsConnectAppPacket::decode(SrsStream* stream)
{
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
    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;
    }
    if (transaction_id != 1.0) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode connect transaction_id failed. "
            "required=%.1f, actual=%.1f, ret=%d", 1.0, transaction_id, ret);
        return ret;
    }
    
    if ((ret = command_object->read(stream)) != ERROR_SUCCESS) {
        srs_error("amf0 decode connect command_object failed. ret=%d", ret);
        return ret;
    }
    
    srs_info("amf0 decode connect packet success");
    
    return ret;
winlin authored
1775 1776
}
winlin authored
1777 1778
int SrsConnectAppPacket::get_perfer_cid()
{
1779
    return RTMP_CID_OverConnection;
winlin authored
1780 1781 1782 1783
}

int SrsConnectAppPacket::get_message_type()
{
1784
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
1785 1786 1787 1788
}

int SrsConnectAppPacket::get_size()
{
1789 1790
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::object(command_object);
winlin authored
1791 1792 1793 1794
}

int SrsConnectAppPacket::encode_packet(SrsStream* stream)
{
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
    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.");
    
    srs_info("encode connect app request packet success.");
    
    return ret;
winlin authored
1818 1819
}
winlin authored
1820 1821
SrsConnectAppResPacket::SrsConnectAppResPacket()
{
1822 1823 1824 1825
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = 1;
    props = SrsAmf0Any::object();
    info = SrsAmf0Any::object();
winlin authored
1826 1827 1828 1829
}

SrsConnectAppResPacket::~SrsConnectAppResPacket()
{
1830 1831
    srs_freep(props);
    srs_freep(info);
winlin authored
1832 1833
}
winlin authored
1834 1835
int SrsConnectAppResPacket::decode(SrsStream* stream)
{
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
    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;
    }
    if (transaction_id != 1.0) {
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 decode connect transaction_id failed. "
            "required=%.1f, actual=%.1f, ret=%d", 1.0, transaction_id, ret);
        return ret;
    }
    
    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
1873 1874
}
winlin authored
1875 1876
int SrsConnectAppResPacket::get_perfer_cid()
{
1877
    return RTMP_CID_OverConnection;
winlin authored
1878 1879 1880 1881
}

int SrsConnectAppResPacket::get_message_type()
{
1882
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
1883 1884 1885 1886
}

int SrsConnectAppResPacket::get_size()
{
1887
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number() 
1888
        + SrsAmf0Size::object(props) + SrsAmf0Size::object(info);
winlin authored
1889 1890 1891 1892
}

int SrsConnectAppResPacket::encode_packet(SrsStream* stream)
{
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    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.");
    
1907 1908 1909
    if ((ret = props->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode props failed. ret=%d", ret);
        return ret;
1910 1911
    }
1912 1913
    srs_verbose("encode props success.");
    
1914 1915 1916
    if ((ret = info->write(stream)) != ERROR_SUCCESS) {
        srs_error("encode info failed. ret=%d", ret);
        return ret;
1917 1918
    }
1919 1920 1921 1922 1923
    srs_verbose("encode info success.");
    
    srs_info("encode connect app response packet success.");
    
    return ret;
winlin authored
1924 1925 1926 1927
}

SrsCreateStreamPacket::SrsCreateStreamPacket()
{
1928 1929 1930
    command_name = RTMP_AMF0_COMMAND_CREATE_STREAM;
    transaction_id = 2;
    command_object = SrsAmf0Any::null();
winlin authored
1931 1932 1933 1934
}

SrsCreateStreamPacket::~SrsCreateStreamPacket()
{
1935
    srs_freep(command_object);
winlin authored
1936 1937 1938 1939
}

int SrsCreateStreamPacket::decode(SrsStream* stream)
{
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
    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
1966 1967
}
winlin authored
1968 1969
int SrsCreateStreamPacket::get_perfer_cid()
{
1970
    return RTMP_CID_OverConnection;
winlin authored
1971 1972 1973 1974
}

int SrsCreateStreamPacket::get_message_type()
{
1975
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
1976 1977 1978 1979
}

int SrsCreateStreamPacket::get_size()
{
1980 1981
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null();
winlin authored
1982 1983 1984 1985
}

int SrsCreateStreamPacket::encode_packet(SrsStream* stream)
{
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
    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
2009 2010
}
winlin authored
2011 2012
SrsCreateStreamResPacket::SrsCreateStreamResPacket(double _transaction_id, double _stream_id)
{
2013 2014 2015 2016
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = _transaction_id;
    command_object = SrsAmf0Any::null();
    stream_id = _stream_id;
winlin authored
2017 2018 2019 2020
}

SrsCreateStreamResPacket::~SrsCreateStreamResPacket()
{
2021
    srs_freep(command_object);
winlin authored
2022 2023
}
winlin authored
2024 2025
int SrsCreateStreamResPacket::decode(SrsStream* stream)
{
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
    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
2057 2058
}
winlin authored
2059 2060
int SrsCreateStreamResPacket::get_perfer_cid()
{
2061
    return RTMP_CID_OverConnection;
winlin authored
2062 2063 2064 2065
}

int SrsCreateStreamResPacket::get_message_type()
{
2066
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2067 2068 2069 2070
}

int SrsCreateStreamResPacket::get_size()
{
2071 2072
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::number();
winlin authored
2073 2074 2075 2076
}

int SrsCreateStreamResPacket::encode_packet(SrsStream* stream)
{
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
    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
2107 2108
}
2109 2110 2111 2112
SrsCloseStreamPacket::SrsCloseStreamPacket()
{
    command_name = RTMP_AMF0_COMMAND_CLOSE_STREAM;
    transaction_id = 0;
2113
    command_object = SrsAmf0Any::null();
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
}

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
2144 2145
SrsFMLEStartPacket::SrsFMLEStartPacket()
{
2146 2147 2148
    command_name = RTMP_AMF0_COMMAND_RELEASE_STREAM;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
winlin authored
2149 2150 2151 2152
}

SrsFMLEStartPacket::~SrsFMLEStartPacket()
{
2153
    srs_freep(command_object);
winlin authored
2154 2155 2156 2157
}

int SrsFMLEStartPacket::decode(SrsStream* stream)
{
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 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 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
2193 2194
}
2195 2196
int SrsFMLEStartPacket::get_perfer_cid()
{
2197
    return RTMP_CID_OverConnection;
2198 2199 2200 2201
}

int SrsFMLEStartPacket::get_message_type()
{
2202
    return RTMP_MSG_AMF0CommandMessage;
2203 2204 2205 2206
}

int SrsFMLEStartPacket::get_size()
{
2207 2208
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::str(stream_name);
2209 2210 2211 2212
}

int SrsFMLEStartPacket::encode_packet(SrsStream* stream)
{
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
    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;
2243 2244 2245 2246
}

SrsFMLEStartPacket* SrsFMLEStartPacket::create_release_stream(string stream)
{
2247 2248 2249 2250 2251 2252 2253
    SrsFMLEStartPacket* pkt = new SrsFMLEStartPacket();
    
    pkt->command_name = RTMP_AMF0_COMMAND_RELEASE_STREAM;
    pkt->transaction_id = 2;
    pkt->stream_name = stream;
    
    return pkt;
2254 2255 2256 2257
}

SrsFMLEStartPacket* SrsFMLEStartPacket::create_FC_publish(string stream)
{
2258 2259 2260 2261 2262 2263 2264
    SrsFMLEStartPacket* pkt = new SrsFMLEStartPacket();
    
    pkt->command_name = RTMP_AMF0_COMMAND_FC_PUBLISH;
    pkt->transaction_id = 3;
    pkt->stream_name = stream;
    
    return pkt;
2265 2266
}
winlin authored
2267 2268
SrsFMLEStartResPacket::SrsFMLEStartResPacket(double _transaction_id)
{
2269 2270 2271 2272
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = _transaction_id;
    command_object = SrsAmf0Any::null();
    args = SrsAmf0Any::undefined();
winlin authored
2273 2274 2275 2276
}

SrsFMLEStartResPacket::~SrsFMLEStartResPacket()
{
2277 2278
    srs_freep(command_object);
    srs_freep(args);
winlin authored
2279 2280
}
2281 2282
int SrsFMLEStartResPacket::decode(SrsStream* stream)
{
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
    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;
2314 2315
}
winlin authored
2316 2317
int SrsFMLEStartResPacket::get_perfer_cid()
{
2318
    return RTMP_CID_OverConnection;
winlin authored
2319 2320 2321 2322
}

int SrsFMLEStartResPacket::get_message_type()
{
2323
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2324 2325 2326 2327
}

int SrsFMLEStartResPacket::get_size()
{
2328 2329
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::undefined();
winlin authored
2330 2331 2332 2333
}

int SrsFMLEStartResPacket::encode_packet(SrsStream* stream)
{
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
    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
2364 2365 2366 2367
}

SrsPublishPacket::SrsPublishPacket()
{
2368 2369 2370 2371
    command_name = RTMP_AMF0_COMMAND_PUBLISH;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
    type = "live";
winlin authored
2372 2373 2374 2375
}

SrsPublishPacket::~SrsPublishPacket()
{
2376
    srs_freep(command_object);
winlin authored
2377 2378 2379 2380
}

int SrsPublishPacket::decode(SrsStream* stream)
{
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
    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
2417 2418
}
winlin authored
2419 2420
int SrsPublishPacket::get_perfer_cid()
{
2421
    return RTMP_CID_OverStream;
winlin authored
2422 2423 2424 2425
}

int SrsPublishPacket::get_message_type()
{
2426
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2427 2428 2429 2430
}

int SrsPublishPacket::get_size()
{
2431 2432 2433
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::str(stream_name)
        + SrsAmf0Size::str(type);
winlin authored
2434 2435 2436 2437
}

int SrsPublishPacket::encode_packet(SrsStream* stream)
{
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 2464 2465 2466 2467 2468 2469 2470 2471 2472
    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
2473 2474
}
winlin authored
2475 2476
SrsPausePacket::SrsPausePacket()
{
2477 2478 2479
    command_name = RTMP_AMF0_COMMAND_PAUSE;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
winlin authored
2480
2481 2482
    time_ms = 0;
    is_pause = true;
winlin authored
2483 2484 2485 2486
}

SrsPausePacket::~SrsPausePacket()
{
2487
    srs_freep(command_object);
winlin authored
2488 2489 2490 2491
}

int SrsPausePacket::decode(SrsStream* stream)
{
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    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
2528 2529 2530 2531
}

SrsPlayPacket::SrsPlayPacket()
{
2532 2533 2534
    command_name = RTMP_AMF0_COMMAND_PLAY;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
winlin authored
2535
2536 2537 2538
    start = -2;
    duration = -1;
    reset = true;
winlin authored
2539 2540 2541 2542
}

SrsPlayPacket::~SrsPlayPacket()
{
2543
    srs_freep(command_object);
winlin authored
2544 2545 2546 2547
}

int SrsPlayPacket::decode(SrsStream* stream)
{
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
    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;
    }
2584
2585 2586
    if (stream->empty()) {
        return ret;
2587
    }
2588 2589
    
    SrsAmf0Any* reset_value = NULL;
2590
    if ((ret = srs_amf0_read_any(stream, &reset_value)) != ERROR_SUCCESS) {
2591 2592 2593 2594 2595 2596
        ret = ERROR_RTMP_AMF0_DECODE;
        srs_error("amf0 read play reset marker failed. ret=%d", ret);
        return ret;
    }
    SrsAutoFree(SrsAmf0Any, reset_value, false);
    
2597
    if (reset_value) {
2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
        // 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()) {
            reset = (reset_value->to_number() == 0 ? false : true);
        } else {
            ret = ERROR_RTMP_AMF0_DECODE;
            srs_error("amf0 invalid type=%#x, requires number or bool, ret=%d", reset_value->marker, ret);
            return ret;
        }
2610 2611
    }
2612
    srs_info("amf0 decode play packet success");
2613 2614
    
    return ret;
winlin authored
2615 2616
}
winlin authored
2617 2618
int SrsPlayPacket::get_perfer_cid()
{
2619
    return RTMP_CID_OverStream;
winlin authored
2620 2621 2622 2623
}

int SrsPlayPacket::get_message_type()
{
2624
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2625 2626 2627 2628
}

int SrsPlayPacket::get_size()
{
2629 2630 2631 2632
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::str(stream_name)
        + SrsAmf0Size::number() + SrsAmf0Size::number()
        + SrsAmf0Size::boolean();
winlin authored
2633 2634 2635 2636
}

int SrsPlayPacket::encode_packet(SrsStream* stream)
{
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 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 2682 2683
    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
2684 2685
}
winlin authored
2686 2687
SrsPlayResPacket::SrsPlayResPacket()
{
2688 2689 2690 2691
    command_name = RTMP_AMF0_COMMAND_RESULT;
    transaction_id = 0;
    command_object = SrsAmf0Any::null();
    desc = SrsAmf0Any::object();
winlin authored
2692 2693 2694 2695
}

SrsPlayResPacket::~SrsPlayResPacket()
{
2696 2697
    srs_freep(command_object);
    srs_freep(desc);
winlin authored
2698 2699 2700 2701
}

int SrsPlayResPacket::get_perfer_cid()
{
2702
    return RTMP_CID_OverStream;
winlin authored
2703 2704 2705 2706
}

int SrsPlayResPacket::get_message_type()
{
2707
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2708 2709 2710 2711
}

int SrsPlayResPacket::get_size()
{
2712 2713
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::object(desc);
winlin authored
2714 2715 2716 2717
}

int SrsPlayResPacket::encode_packet(SrsStream* stream)
{
2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
    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
2748 2749 2750 2751
}

SrsOnBWDonePacket::SrsOnBWDonePacket()
{
2752 2753 2754
    command_name = RTMP_AMF0_COMMAND_ON_BW_DONE;
    transaction_id = 0;
    args = SrsAmf0Any::null();
winlin authored
2755 2756 2757 2758
}

SrsOnBWDonePacket::~SrsOnBWDonePacket()
{
2759
    srs_freep(args);
winlin authored
2760 2761 2762 2763
}

int SrsOnBWDonePacket::get_perfer_cid()
{
2764
    return RTMP_CID_OverConnection;
winlin authored
2765 2766 2767 2768
}

int SrsOnBWDonePacket::get_message_type()
{
2769
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2770 2771 2772 2773
}

int SrsOnBWDonePacket::get_size()
{
2774 2775
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null();
winlin authored
2776 2777 2778 2779
}

int SrsOnBWDonePacket::encode_packet(SrsStream* stream)
{
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
    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
2803 2804 2805 2806
}

SrsOnStatusCallPacket::SrsOnStatusCallPacket()
{
2807 2808 2809 2810
    command_name = RTMP_AMF0_COMMAND_ON_STATUS;
    transaction_id = 0;
    args = SrsAmf0Any::null();
    data = SrsAmf0Any::object();
winlin authored
2811 2812 2813 2814
}

SrsOnStatusCallPacket::~SrsOnStatusCallPacket()
{
2815 2816
    srs_freep(args);
    srs_freep(data);
winlin authored
2817 2818 2819 2820
}

int SrsOnStatusCallPacket::get_perfer_cid()
{
2821
    return RTMP_CID_OverStream;
winlin authored
2822 2823 2824 2825
}

int SrsOnStatusCallPacket::get_message_type()
{
2826
    return RTMP_MSG_AMF0CommandMessage;
winlin authored
2827 2828 2829 2830
}

int SrsOnStatusCallPacket::get_size()
{
2831 2832
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::object(data);
winlin authored
2833 2834 2835 2836
}

int SrsOnStatusCallPacket::encode_packet(SrsStream* stream)
{
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
    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
2866 2867
}
2868 2869
SrsBandwidthPacket::SrsBandwidthPacket()
{
2870 2871 2872 2873
    command_name = RTMP_AMF0_COMMAND_ON_STATUS;
    transaction_id = 0;
    args = SrsAmf0Any::null();
    data = SrsAmf0Any::object();
2874 2875 2876 2877
}

SrsBandwidthPacket::~SrsBandwidthPacket()
{
2878 2879
    srs_freep(args);
    srs_freep(data);
2880 2881 2882 2883
}

int SrsBandwidthPacket::get_perfer_cid()
{
2884
    return RTMP_CID_OverStream;
2885 2886 2887 2888
}

int SrsBandwidthPacket::get_message_type()
{
2889
    return RTMP_MSG_AMF0CommandMessage;
2890 2891 2892 2893
}

int SrsBandwidthPacket::get_size()
{
2894 2895
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::number()
        + SrsAmf0Size::null() + SrsAmf0Size::object(data);
2896 2897 2898 2899
}

int SrsBandwidthPacket::encode_packet(SrsStream* stream)
{
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
    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;
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 2955 2956 2957 2958
}

int SrsBandwidthPacket::decode(SrsStream *stream)
{
    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 ((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;
    }
    
    // @remark, for bandwidth test, ignore the data field.

    srs_info("decode SrsBandwidthPacket success.");

    return ret;
}

bool SrsBandwidthPacket::is_starting_play()
{
2959
    return command_name == SRS_BW_CHECK_STARTING_PLAY;
2960 2961 2962 2963
}

bool SrsBandwidthPacket::is_stopped_play()
{
2964
    return command_name == SRS_BW_CHECK_STOPPED_PLAY;
2965 2966 2967 2968
}

bool SrsBandwidthPacket::is_starting_publish()
{
2969
    return command_name == SRS_BW_CHECK_STARTING_PUBLISH;
2970 2971 2972 2973
}

bool SrsBandwidthPacket::is_stopped_publish()
{
2974
    return command_name == SRS_BW_CHECK_STOPPED_PUBLISH;
2975 2976 2977 2978
}

bool SrsBandwidthPacket::is_flash_final()
{
2979
    return command_name == SRS_BW_CHECK_FLASH_FINAL;
2980 2981 2982 2983
}

SrsBandwidthPacket* SrsBandwidthPacket::create_finish()
{
2984 2985
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_FINISHED);
2986 2987 2988 2989
}

SrsBandwidthPacket* SrsBandwidthPacket::create_start_play()
{
2990 2991
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_START_PLAY);
2992 2993 2994 2995
}

SrsBandwidthPacket* SrsBandwidthPacket::create_playing()
{
2996
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
2997
    return pkt->set_command(SRS_BW_CHECK_PLAYING);
2998 2999 3000 3001
}

SrsBandwidthPacket* SrsBandwidthPacket::create_stop_play()
{
3002 3003
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STOP_PLAY);
3004 3005 3006 3007
}

SrsBandwidthPacket* SrsBandwidthPacket::create_start_publish()
{
3008 3009
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_START_PUBLISH);
3010 3011 3012 3013
}

SrsBandwidthPacket* SrsBandwidthPacket::create_stop_publish()
{
3014 3015
    SrsBandwidthPacket* pkt = new SrsBandwidthPacket();
    return pkt->set_command(SRS_BW_CHECK_STOP_PUBLISH);
3016 3017 3018 3019
}

SrsBandwidthPacket* SrsBandwidthPacket::set_command(string command)
{
3020 3021 3022
    command_name = command;
    
    return this;
3023 3024
}
winlin authored
3025 3026
SrsOnStatusDataPacket::SrsOnStatusDataPacket()
{
3027 3028
    command_name = RTMP_AMF0_COMMAND_ON_STATUS;
    data = SrsAmf0Any::object();
winlin authored
3029 3030 3031 3032
}

SrsOnStatusDataPacket::~SrsOnStatusDataPacket()
{
3033
    srs_freep(data);
winlin authored
3034 3035 3036 3037
}

int SrsOnStatusDataPacket::get_perfer_cid()
{
3038
    return RTMP_CID_OverStream;
winlin authored
3039 3040 3041 3042
}

int SrsOnStatusDataPacket::get_message_type()
{
3043
    return RTMP_MSG_AMF0DataMessage;
winlin authored
3044 3045 3046 3047
}

int SrsOnStatusDataPacket::get_size()
{
3048
    return SrsAmf0Size::str(command_name) + SrsAmf0Size::object(data);
winlin authored
3049 3050 3051 3052
}

int SrsOnStatusDataPacket::encode_packet(SrsStream* stream)
{
3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
    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
3070 3071 3072 3073
}

SrsSampleAccessPacket::SrsSampleAccessPacket()
{
3074 3075 3076
    command_name = RTMP_AMF0_DATA_SAMPLE_ACCESS;
    video_sample_access = false;
    audio_sample_access = false;
winlin authored
3077 3078 3079 3080 3081 3082 3083 3084
}

SrsSampleAccessPacket::~SrsSampleAccessPacket()
{
}

int SrsSampleAccessPacket::get_perfer_cid()
{
3085
    return RTMP_CID_OverStream;
winlin authored
3086 3087 3088 3089
}

int SrsSampleAccessPacket::get_message_type()
{
3090
    return RTMP_MSG_AMF0DataMessage;
winlin authored
3091 3092 3093 3094
}

int SrsSampleAccessPacket::get_size()
{
3095 3096
    return SrsAmf0Size::str(command_name)
        + SrsAmf0Size::boolean() + SrsAmf0Size::boolean();
winlin authored
3097 3098 3099 3100
}

int SrsSampleAccessPacket::encode_packet(SrsStream* stream)
{
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123
    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
3124 3125 3126 3127
}

SrsOnMetaDataPacket::SrsOnMetaDataPacket()
{
3128 3129
    name = RTMP_AMF0_DATA_ON_METADATA;
    metadata = SrsAmf0Any::object();
winlin authored
3130 3131 3132 3133
}

SrsOnMetaDataPacket::~SrsOnMetaDataPacket()
{
3134
    srs_freep(metadata);
winlin authored
3135 3136 3137 3138
}

int SrsOnMetaDataPacket::decode(SrsStream* stream)
{
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
    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;
    }
    
    SrsAutoFree(SrsAmf0Any, any, false);
    
    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++) {
            metadata->set(arr->key_at(i), arr->value_at(i));
        }
        
        arr->clear();
        srs_info("decode metadata array success");
    }
    
    return ret;
winlin authored
3186 3187 3188 3189
}

int SrsOnMetaDataPacket::get_perfer_cid()
{
3190
    return RTMP_CID_OverConnection2;
winlin authored
3191 3192 3193 3194
}

int SrsOnMetaDataPacket::get_message_type()
{
3195
    return RTMP_MSG_AMF0DataMessage;
winlin authored
3196 3197 3198 3199
}

int SrsOnMetaDataPacket::get_size()
{
3200
    return SrsAmf0Size::str(name) + SrsAmf0Size::object(metadata);
winlin authored
3201 3202 3203 3204
}

int SrsOnMetaDataPacket::encode_packet(SrsStream* stream)
{
3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220
    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
3221 3222 3223 3224
}

SrsSetWindowAckSizePacket::SrsSetWindowAckSizePacket()
{
3225
    ackowledgement_window_size = 0;
winlin authored
3226 3227 3228 3229 3230 3231 3232 3233
}

SrsSetWindowAckSizePacket::~SrsSetWindowAckSizePacket()
{
}

int SrsSetWindowAckSizePacket::decode(SrsStream* stream)
{
3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245
    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
3246 3247 3248 3249
}

int SrsSetWindowAckSizePacket::get_perfer_cid()
{
3250
    return RTMP_CID_ProtocolControl;
winlin authored
3251 3252 3253 3254
}

int SrsSetWindowAckSizePacket::get_message_type()
{
3255
    return RTMP_MSG_WindowAcknowledgementSize;
winlin authored
3256 3257 3258 3259
}

int SrsSetWindowAckSizePacket::get_size()
{
3260
    return 4;
winlin authored
3261 3262 3263 3264
}

int SrsSetWindowAckSizePacket::encode_packet(SrsStream* stream)
{
3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278
    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
3279 3280 3281 3282
}

SrsAcknowledgementPacket::SrsAcknowledgementPacket()
{
3283
    sequence_number = 0;
winlin authored
3284 3285 3286 3287 3288 3289 3290 3291
}

SrsAcknowledgementPacket::~SrsAcknowledgementPacket()
{
}

int SrsAcknowledgementPacket::get_perfer_cid()
{
3292
    return RTMP_CID_ProtocolControl;
winlin authored
3293 3294 3295 3296
}

int SrsAcknowledgementPacket::get_message_type()
{
3297
    return RTMP_MSG_Acknowledgement;
winlin authored
3298 3299 3300 3301
}

int SrsAcknowledgementPacket::get_size()
{
3302
    return 4;
winlin authored
3303 3304 3305 3306
}

int SrsAcknowledgementPacket::encode_packet(SrsStream* stream)
{
3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
    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
3321 3322 3323 3324
}

SrsSetChunkSizePacket::SrsSetChunkSizePacket()
{
3325
    chunk_size = RTMP_DEFAULT_CHUNK_SIZE;
winlin authored
3326 3327 3328 3329 3330 3331 3332 3333
}

SrsSetChunkSizePacket::~SrsSetChunkSizePacket()
{
}

int SrsSetChunkSizePacket::decode(SrsStream* stream)
{
3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358
    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);
    
    if (chunk_size < RTMP_MIN_CHUNK_SIZE) {
        ret = ERROR_RTMP_CHUNK_SIZE;
        srs_error("invalid chunk size. min=%d, actual=%d, ret=%d", 
            ERROR_RTMP_CHUNK_SIZE, chunk_size, ret);
        return ret;
    }
    if (chunk_size > RTMP_MAX_CHUNK_SIZE) {
        ret = ERROR_RTMP_CHUNK_SIZE;
        srs_error("invalid chunk size. max=%d, actual=%d, ret=%d", 
            RTMP_MAX_CHUNK_SIZE, chunk_size, ret);
        return ret;
    }
    
    return ret;
winlin authored
3359 3360 3361 3362
}

int SrsSetChunkSizePacket::get_perfer_cid()
{
3363
    return RTMP_CID_ProtocolControl;
winlin authored
3364 3365 3366 3367
}

int SrsSetChunkSizePacket::get_message_type()
{
3368
    return RTMP_MSG_SetChunkSize;
winlin authored
3369 3370 3371 3372
}

int SrsSetChunkSizePacket::get_size()
{
3373
    return 4;
winlin authored
3374 3375 3376 3377
}

int SrsSetChunkSizePacket::encode_packet(SrsStream* stream)
{
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390
    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
3391 3392 3393 3394
}

SrsSetPeerBandwidthPacket::SrsSetPeerBandwidthPacket()
{
3395 3396
    bandwidth = 0;
    type = 2;
winlin authored
3397 3398 3399 3400 3401 3402 3403 3404
}

SrsSetPeerBandwidthPacket::~SrsSetPeerBandwidthPacket()
{
}

int SrsSetPeerBandwidthPacket::get_perfer_cid()
{
3405
    return RTMP_CID_ProtocolControl;
winlin authored
3406 3407 3408 3409
}

int SrsSetPeerBandwidthPacket::get_message_type()
{
3410
    return RTMP_MSG_SetPeerBandwidth;
winlin authored
3411 3412 3413 3414
}

int SrsSetPeerBandwidthPacket::get_size()
{
3415
    return 5;
winlin authored
3416 3417 3418 3419
}

int SrsSetPeerBandwidthPacket::encode_packet(SrsStream* stream)
{
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434
    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
3435 3436 3437 3438
}

SrsUserControlPacket::SrsUserControlPacket()
{
3439 3440 3441
    event_type = 0;
    event_data = 0;
    extra_data = 0;
winlin authored
3442 3443 3444 3445 3446 3447 3448 3449
}

SrsUserControlPacket::~SrsUserControlPacket()
{
}

int SrsUserControlPacket::decode(SrsStream* stream)
{
3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
    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
3475 3476 3477 3478
}

int SrsUserControlPacket::get_perfer_cid()
{
3479
    return RTMP_CID_ProtocolControl;
winlin authored
3480 3481 3482 3483
}

int SrsUserControlPacket::get_message_type()
{
3484
    return RTMP_MSG_UserControlMessage;
winlin authored
3485 3486 3487 3488
}

int SrsUserControlPacket::get_size()
{
3489 3490 3491 3492 3493
    if (event_type == SrcPCUCSetBufferLength) {
        return 2 + 4 + 4;
    } else {
        return 2 + 4;
    }
winlin authored
3494 3495 3496 3497
}

int SrsUserControlPacket::encode_packet(SrsStream* stream)
{
3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
    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) {
        stream->write_2bytes(extra_data);
        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
3520
}
3521