Blame view

trunk/src/rtmp/srs_protocol_rtmp_stack.hpp 40.7 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 25
#ifndef SRS_RTMP_PROTOCOL_RTMP_STACK_HPP
#define SRS_RTMP_PROTOCOL_RTMP_STACK_HPP
winlin authored
26 27

/*
28
#include <srs_protocol_rtmp_stack.hpp>
winlin authored
29 30 31 32 33 34 35
*/

#include <srs_core.hpp>

#include <map>
#include <string>
36
#include <srs_kernel_log.hpp>
37
#include <srs_kernel_error.hpp>
winlin authored
38 39 40 41 42 43 44

class ISrsProtocolReaderWriter;
class SrsBuffer;
class SrsPacket;
class SrsStream;
class SrsAmf0Object;
class SrsAmf0Any;
45
class SrsMessageHeader;
46 47
class SrsMessage;
class SrsChunkStream;
48
 
49 50 51 52 53
// the following is the timeout for rtmp protocol, 
// to avoid death connection.

// the timeout to wait client data,
// if timeout, close the connection.
54
#define SRS_SEND_TIMEOUT_US (int64_t)(30*1000*1000LL)
55 56 57

// the timeout to send data to client,
// if timeout, close the connection.
58
#define SRS_RECV_TIMEOUT_US (int64_t)(30*1000*1000LL)
59
winlin authored
60 61 62 63
// the timeout to wait for client control message,
// if timeout, we generally ignore and send the data to client,
// generally, it's the pulse time for data seding.
#define SRS_PULSE_TIMEOUT_US (int64_t)(200*1000LL)
winlin authored
64 65 66

/**
* max rtmp header size:
67 68 69
*     1bytes basic header,
*     11bytes message header,
*     4bytes timestamp header,
winlin authored
70 71 72 73 74
* that is, 1+11+4=16bytes.
*/
#define RTMP_MAX_FMT0_HEADER_SIZE 16
/**
* max rtmp header size:
75 76
*     1bytes basic header,
*     4bytes timestamp header,
winlin authored
77 78
* that is, 1+4=5bytes.
*/
79 80
// always use fmt0 as cache.
//#define RTMP_MAX_FMT3_HEADER_SIZE 5
winlin authored
81 82 83 84 85 86 87 88 89

/**
* the protocol provides the rtmp-message-protocol services,
* to recv RTMP message from RTMP chunk stream,
* and to send out RTMP message over RTMP chunk stream.
*/
class SrsProtocol
{
private:
90
    class AckWindowSize
91
    {
92
    public:
93 94 95 96 97
        int ack_window_size;
        int64_t acked_size;
        
        AckWindowSize();
    };
winlin authored
98 99
// peer in/out
private:
100 101 102 103 104 105 106 107
    ISrsProtocolReaderWriter* skt;
    char* pp;
    /**
    * requests sent out, used to build the response.
    * key: transactionId
    * value: the request command name
    */
    std::map<double, std::string> requests;
winlin authored
108 109
// peer in
private:
110
    std::map<int, SrsChunkStream*> chunk_streams;
111
    SrsStream* decode_stream;
112 113 114
    SrsBuffer* buffer;
    int32_t in_chunk_size;
    AckWindowSize in_ack_size;
winlin authored
115 116
// peer out
private:
117
    char out_header_cache[RTMP_MAX_FMT0_HEADER_SIZE];
118 119 120 121 122 123 124 125 126
    int32_t out_chunk_size;
public:
    /**
    * use io to create the protocol stack,
    * @param io, provides io interfaces, user must free it.
    */
    SrsProtocol(ISrsProtocolReaderWriter* io);
    virtual ~SrsProtocol();
public:
127
    // TODO: FIXME: to private.
128 129 130 131 132 133 134 135 136 137 138
    std::string get_request_name(double transcationId);
    /**
    * set the timeout in us.
    * if timeout, recv/send message return ERROR_SOCKET_TIMEOUT.
    */
    virtual void set_recv_timeout(int64_t timeout_us);
    virtual int64_t get_recv_timeout();
    virtual void set_send_timeout(int64_t timeout_us);
    virtual int64_t get_send_timeout();
    virtual int64_t get_recv_bytes();
    virtual int64_t get_send_bytes();
139 140 141 142 143 144 145 146 147
public:
    /**
    * recv a RTMP message, which is bytes oriented.
    * user can use decode_message to get the decoded RTMP packet.
    * @param pmsg, set the received message, 
    *       always NULL if error, 
    *       NULL for unknown packet but return success.
    *       never NULL if decode success.
    */
148
    virtual int recv_message(SrsMessage** pmsg);
149 150 151 152 153 154
    /**
    * decode bytes oriented RTMP message to RTMP packet,
    * @param ppacket, output decoded packet, 
    *       always NULL if error, never NULL if success.
    * @return error when unknown packet, error when decode failed.
    */
155
    virtual int decode_message(SrsMessage* msg, SrsPacket** ppacket);
156 157 158 159 160
    /**
    * send the RTMP message and always free it.
    * user must never free or use the msg after this method,
    * for it will always free the msg.
    * @param msg, the msg to send out, never be NULL.
161
    * @param stream_id, the stream id of packet to send over, 0 for control message.
162
    */
163
    virtual int send_and_free_message(SrsMessage* msg, int stream_id);
164 165 166 167 168 169 170
    /**
    * send the RTMP packet and always free it.
    * user must never free or use the packet after this method,
    * for it will always free the packet.
    * @param packet, the packet to send out, never be NULL.
    * @param stream_id, the stream id of packet to send over, 0 for control message.
    */
171
    virtual int send_and_free_packet(SrsPacket* packet, int stream_id);
172 173
private:
    /**
174
    * send out the message, donot free it, the caller must free the param msg.
175 176
    * @param packet the packet of message, NULL for raw message.
    */
177
    virtual int do_send_message(SrsMessage* msg, SrsPacket* packet);
178
    /**
179
    * imp for decode_message
180
    */
181
    virtual int do_decode_message(SrsMessageHeader& header, SrsStream* stream, SrsPacket** ppacket);
182 183 184 185 186 187
    /**
    * recv bytes oriented RTMP message from protocol stack.
    * return error if error occur and nerver set the pmsg,
    * return success and pmsg set to NULL if no entire message got,
    * return success and pmsg set to entire message if got one.
    */
188
    virtual int recv_interlaced_message(SrsMessage** pmsg);
189 190 191 192 193
    /**
    * read the chunk basic header(fmt, cid) from chunk stream.
    * user can discovery a SrsChunkStream by cid.
    * @bh_size return the chunk basic header size, to remove the used bytes when finished.
    */
194
    virtual int read_basic_header(char& fmt, int& cid, int& bh_size);
195 196 197 198 199
    /**
    * read the chunk message header(timestamp, payload_length, message_type, stream_id) 
    * from chunk stream and save to SrsChunkStream.
    * @mh_size return the chunk message header size, to remove the used bytes when finished.
    */
200
    virtual int read_message_header(SrsChunkStream* chunk, char fmt, int bh_size, int& mh_size);
201 202 203 204 205
    /**
    * read the chunk payload, remove the used bytes in buffer,
    * if got entire message, set the pmsg.
    * @payload_size read size in this roundtrip, generally a chunk size or left message size.
    */
206
    virtual int read_message_payload(SrsChunkStream* chunk, int bh_size, int mh_size, int& payload_size, SrsMessage** pmsg);
207 208 209
    /**
    * when recv message, update the context.
    */
210
    virtual int on_recv_message(SrsMessage* msg);
211 212 213
    /**
    * when message sentout, update the context.
    */
214
    virtual int on_send_message(SrsMessage* msg, SrsPacket* packet);
winlin authored
215
private:
216 217
    virtual int response_acknowledgement_message();
    virtual int response_ping_message(int32_t timestamp);
winlin authored
218 219 220 221 222
};

/**
* 4.1. Message Header
*/
223
class SrsMessageHeader
winlin authored
224
{
225
public:
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    /**
    * One byte field to represent the message type. A range of type IDs
    * (1-7) are reserved for protocol control messages.
    */
    int8_t message_type;
    /**
    * Three-byte field that represents the size of the payload in bytes.
    * It is set in big-endian format.
    */
    int32_t payload_length;
    /**
    * Three-byte field that contains a timestamp delta of the message.
    * The 4 bytes are packed in the big-endian order.
    * @remark, only used for decoding message from chunk stream.
    */
    int32_t timestamp_delta;
    /**
    * Three-byte field that identifies the stream of the message. These
    * bytes are set in big-endian format.
    */
    int32_t stream_id;
    
    /**
    * Four-byte field that contains a timestamp of the message.
    * The 4 bytes are packed in the big-endian order.
    * @remark, used as calc timestamp when decode and encode time.
    * @remark, we use 64bits for large time for jitter detect and hls.
    */
    int64_t timestamp;
    
256 257 258 259 260 261 262 263 264
public:
    /**
    * get the perfered cid(chunk stream id) which sendout over.
    * set at decoding, and canbe used for directly send message,
    * for example, dispatch to all connections.
    */
    int perfer_cid;
    
public:
265 266
    SrsMessageHeader();
    virtual ~SrsMessageHeader();
winlin authored
267
268 269 270 271 272 273 274
    bool is_audio();
    bool is_video();
    bool is_amf0_command();
    bool is_amf0_data();
    bool is_amf3_command();
    bool is_amf3_data();
    bool is_window_ackledgement_size();
275
    bool is_ackledgement();
276 277
    bool is_set_chunk_size();
    bool is_user_control_message();
winlin authored
278
    bool is_set_peer_bandwidth();
279
    bool is_aggregate();
280 281 282 283
    
    void initialize_amf0_script(int size, int stream);
    void initialize_audio(int size, u_int32_t time, int stream);
    void initialize_video(int size, u_int32_t time, int stream);
winlin authored
284 285 286 287 288 289
};

/**
* incoming chunk stream maybe interlaced,
* use the chunk stream to cache the input RTMP chunk streams.
*/
290
class SrsChunkStream
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
{
public:
    /**
    * represents the basic header fmt,
    * which used to identify the variant message header type.
    */
    char fmt;
    /**
    * represents the basic header cid,
    * which is the chunk stream id.
    */
    int cid;
    /**
    * cached message header
    */
    SrsMessageHeader header;
    /**
    * whether the chunk message header has extended timestamp.
    */
    bool extended_timestamp;
    /**
    * partially read message.
    */
314
    SrsMessage* msg;
315 316 317 318 319
    /**
    * decoded msg count, to identify whether the chunk stream is fresh.
    */
    int64_t msg_count;
public:
320 321
    SrsChunkStream(int _cid);
    virtual ~SrsChunkStream();
322 323 324 325 326 327
};

/**
* message is raw data RTMP message, bytes oriented,
* protcol always recv RTMP message, and can send RTMP message or RTMP packet.
* the shared-ptr message is a special RTMP message, use ref-count for performance issue.
328 329 330 331 332 333
* 
* @remark, never directly new SrsMessage, the constructor is protected,
* for in the SrsMessage, we never know whether we should free the message,
* for SrsCommonMessage, we should free the payload,
* while for SrsSharedPtrMessage, we should use ref-count to free it.
* so, use these two concrete message, SrsCommonMessage or SrsSharedPtrMessage instread.
334
*/
335
class SrsMessage
336 337 338 339 340 341 342 343 344 345 346 347 348 349
{
// 4.1. Message Header
public:
    SrsMessageHeader header;
// 4.2. Message Payload
public:
    /**
    * The other part which is the payload is the actual data that is
    * contained in the message. For example, it could be some audio samples
    * or compressed video data. The payload format and interpretation are
    * beyond the scope of this document.
    */
    int32_t size;
    int8_t* payload;
350
protected:
351
    SrsMessage();
352
public:
353
    virtual ~SrsMessage();
354 355 356
};

/**
357 358 359 360 361 362 363 364 365 366
* the common message used free the payload in common way.
*/
class SrsCommonMessage : public SrsMessage
{
public:
    SrsCommonMessage();
    virtual ~SrsCommonMessage();
};

/**
367 368 369
* shared ptr message.
* for audio/video/data message that need less memory copy.
* and only for output.
370 371 372 373 374 375 376
*
* create first object by constructor and create(),
* use copy if need reference count message.
* 
* Usage:
*       SrsSharedPtrMessage msg;
*       
377
*/
378
class SrsSharedPtrMessage : public SrsMessage
379 380
{
private:
381
    class __SrsSharedPtr
382
    {
383
    public:
384 385 386 387 388 389 390 391 392
        char* payload;
        int size;
        int shared_count;
        
        __SrsSharedPtr();
        virtual ~__SrsSharedPtr();
    };
    __SrsSharedPtr* ptr;
public:
393 394
    SrsSharedPtrMessage();
    virtual ~SrsSharedPtrMessage();
395 396
public:
    /**
397 398 399 400 401 402 403 404 405 406
    * create shared ptr message, 
    * copy header, manage the payload of msg,
    * set the payload to NULL to prevent double free.
    * @remark payload of msg set to NULL if success.
    */
    virtual int create(SrsMessage* msg);
    /**
    * create shared ptr message,
    * from the header and payload.
    * @remark user should never free the payload.
407
    */
408
    virtual int create(SrsMessageHeader* pheader, char* payload, int size);
409
    /**
410 411 412 413 414
    * get current reference count.
    * when this object created, count set to 0.
    * if copy() this object, count increase 1.
    * if this or copy deleted, free payload when count is 0, or count--.
    * @remark, assert object is created.
415
    */
416
    virtual int count();
417 418 419
public:
    /**
    * copy current shared ptr message, use ref-count.
420
    * @remark, assert object is created.
421
    */
422
    virtual SrsSharedPtrMessage* copy();
423 424 425
};

/**
winlin authored
426 427
* the decoded message payload.
* @remark we seperate the packet from message,
428 429 430 431
*        for the packet focus on logic and domain data,
*        the message bind to the protocol and focus on protocol, such as header.
*         we can merge the message and packet, using OOAD hierachy, packet extends from message,
*         it's better for me to use components -- the message use the packet as payload.
winlin authored
432 433 434
*/
class SrsPacket
{
435 436 437
public:
    SrsPacket();
    virtual ~SrsPacket();
438 439 440 441 442 443 444 445 446
public:
    /**
    * the subpacket can override this encode,
    * for example, video and audio will directly set the payload withou memory copy,
    * other packet which need to serialize/encode to bytes by override the 
    * get_size and encode_packet.
    */
    virtual int encode(int& size, char*& payload);
// decode functions for concrete packet to override.
winlin authored
447
public:
448 449 450 451 452
    /**
    * subpacket must override to decode packet from stream.
    * @remark never invoke the super.decode, it always failed.
    */
    virtual int decode(SrsStream* stream);
453
// encode functions for concrete packet to override.
winlin authored
454
public:
455 456 457 458 459 460
    /**
    * the cid(chunk id) specifies the chunk to send data over.
    * generally, each message perfer some cid, for example, 
    * all protocol control messages perfer RTMP_CID_ProtocolControl,
    * SrsSetWindowAckSizePacket is protocol control message.
    */
461 462 463
    virtual int get_perfer_cid();
    /**
    * subpacket must override to provide the right message type.
464
    * the message type set the RTMP message type in header.
465 466
    */
    virtual int get_message_type();
winlin authored
467
protected:
468 469 470 471 472 473 474 475 476
    /**
    * subpacket can override to calc the packet size.
    */
    virtual int get_size();
    /**
    * subpacket can override to encode the payload to stream.
    * @remark never invoke the super.encode_packet, it always failed.
    */
    virtual int encode_packet(SrsStream* stream);
winlin authored
477 478 479 480 481 482 483 484 485 486
};

/**
* 4.1.1. connect
* The client sends the connect command to the server to request
* connection to a server application instance.
*/
class SrsConnectAppPacket : public SrsPacket
{
public:
487 488 489
    /**
    * Name of the command. Set to “connect”.
    */
490
    std::string command_name;
491 492 493
    /**
    * Always set to 1.
    */
494
    double transaction_id;
495
    /**
496 497 498
    * Command information object which has the name-value pairs.
    * @remark: alloc in packet constructor, user can directly use it, 
    *       user should never alloc it again which will cause memory leak.
499
    */
500
    SrsAmf0Object* command_object;
501 502 503 504
    /**
    * Any optional information
    */
    SrsAmf0Object* args;
winlin authored
505
public:
506 507
    SrsConnectAppPacket();
    virtual ~SrsConnectAppPacket();
508
// decode functions for concrete packet to override.
winlin authored
509
public:
510
    virtual int decode(SrsStream* stream);
511
// encode functions for concrete packet to override.
winlin authored
512
public:
513 514
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
515
protected:
516 517
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
518 519 520 521 522 523 524
};
/**
* response for SrsConnectAppPacket.
*/
class SrsConnectAppResPacket : public SrsPacket
{
public:
525 526 527
    /**
    * _result or _error; indicates whether the response is result or error.
    */
528
    std::string command_name;
529 530 531
    /**
    * Transaction ID is 1 for call connect responses
    */
532
    double transaction_id;
533 534 535
    /**
    * Name-value pairs that describe the properties(fmsver etc.) of the connection.
    */
536
    SrsAmf0Object* props;
537 538 539 540
    /**
    * Name-value pairs that describe the response from|the server. ‘code’,
    * ‘level’, ‘description’ are names of few among such information.
    */
541
    SrsAmf0Object* info;
winlin authored
542
public:
543 544
    SrsConnectAppResPacket();
    virtual ~SrsConnectAppResPacket();
545
// decode functions for concrete packet to override.
winlin authored
546
public:
547
    virtual int decode(SrsStream* stream);
548
// encode functions for concrete packet to override.
winlin authored
549
public:
550 551
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
552
protected:
553 554
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
555 556 557
};

/**
558 559 560 561 562 563 564 565
* 4.1.2. Call
* The call method of the NetConnection object runs remote procedure
* calls (RPC) at the receiving end. The called RPC name is passed as a
* parameter to the call command.
*/
class SrsCallPacket : public SrsPacket
{
public:
566 567 568
    /**
    * Name of the remote procedure that is called.
    */
569
    std::string command_name;
570 571 572
    /**
    * If a response is expected we give a transaction Id. Else we pass a value of 0
    */
573 574 575 576 577 578
    double transaction_id;
    /**
    * If there exists any command info this
    * is set, else this is set to null type.
    */
    SrsAmf0Any* command_object;
579 580 581
    /**
    * Any optional arguments to be provided
    */
582 583 584 585
    SrsAmf0Any* arguments;
public:
    SrsCallPacket();
    virtual ~SrsCallPacket();
586
// decode functions for concrete packet to override.
587 588
public:
    virtual int decode(SrsStream* stream);
589
// encode functions for concrete packet to override.
590 591 592 593 594 595 596 597 598 599 600 601 602
public:
    virtual int get_perfer_cid();
    virtual int get_message_type();
protected:
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
};
/**
* response for SrsCallPacket.
*/
class SrsCallResPacket : public SrsPacket
{
public:
603 604 605
    /**
    * Name of the command. 
    */
606
    std::string command_name;
607 608 609
    /**
    * ID of the command, to which the response belongs to
    */
610
    double transaction_id;
611 612 613
    /**
    * If there exists any command info this is set, else this is set to null type.
    */
614
    SrsAmf0Any* command_object;
615 616 617
    /**
    * Response from the method that was called.
    */
618 619 620 621
    SrsAmf0Any* response;
public:
    SrsCallResPacket(double _transaction_id);
    virtual ~SrsCallResPacket();
622
// encode functions for concrete packet to override.
623 624 625 626 627 628 629 630 631
public:
    virtual int get_perfer_cid();
    virtual int get_message_type();
protected:
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
};

/**
winlin authored
632 633 634 635 636 637 638 639 640
* 4.1.3. createStream
* The client sends this command to the server to create a logical
* channel for message communication The publishing of audio, video, and
* metadata is carried out over stream channel created using the
* createStream command.
*/
class SrsCreateStreamPacket : public SrsPacket
{
public:
641 642 643
    /**
    * Name of the command. Set to “createStream”.
    */
644
    std::string command_name;
645 646 647
    /**
    * Transaction ID of the command.
    */
648
    double transaction_id;
649 650 651
    /**
    * If there exists any command info this is set, else this is set to null type.
    */
652
    SrsAmf0Any* command_object; // null
winlin authored
653
public:
654 655
    SrsCreateStreamPacket();
    virtual ~SrsCreateStreamPacket();
656
// decode functions for concrete packet to override.
winlin authored
657
public:
658
    virtual int decode(SrsStream* stream);
659
// encode functions for concrete packet to override.
winlin authored
660
public:
661 662
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
663
protected:
664 665
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
666 667 668 669 670 671 672
};
/**
* response for SrsCreateStreamPacket.
*/
class SrsCreateStreamResPacket : public SrsPacket
{
public:
673 674 675
    /**
    * _result or _error; indicates whether the response is result or error.
    */
676
    std::string command_name;
677 678 679
    /**
    * ID of the command that response belongs to.
    */
680
    double transaction_id;
681 682 683
    /**
    * If there exists any command info this is set, else this is set to null type.
    */
684
    SrsAmf0Any* command_object; // null
685 686 687
    /**
    * The return value is either a stream ID or an error information object.
    */
688
    double stream_id;
winlin authored
689
public:
690 691
    SrsCreateStreamResPacket(double _transaction_id, double _stream_id);
    virtual ~SrsCreateStreamResPacket();
692
// decode functions for concrete packet to override.
winlin authored
693
public:
694
    virtual int decode(SrsStream* stream);
695
// encode functions for concrete packet to override.
winlin authored
696
public:
697 698
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
699
protected:
700 701
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
702
};
703
704 705 706 707 708 709
/**
* client close stream packet.
*/
class SrsCloseStreamPacket : public SrsPacket
{
public:
710 711 712
    /**
    * Name of the command, set to “closeStream”.
    */
713
    std::string command_name;
714 715 716
    /**
    * Transaction ID set to 0.
    */
717
    double transaction_id;
718 719 720
    /**
    * Command information object does not exist. Set to null type.
    */
721
    SrsAmf0Any* command_object; // null
722 723 724
public:
    SrsCloseStreamPacket();
    virtual ~SrsCloseStreamPacket();
725
// decode functions for concrete packet to override.
726 727 728
public:
    virtual int decode(SrsStream* stream);
};
winlin authored
729 730 731 732 733 734 735

/**
* FMLE start publish: ReleaseStream/PublishStream
*/
class SrsFMLEStartPacket : public SrsPacket
{
public:
736 737 738
    /**
    * Name of the command
    */
739
    std::string command_name;
740 741 742
    /**
    * the transaction ID to get the response.
    */
743
    double transaction_id;
744 745 746
    /**
    * If there exists any command info this is set, else this is set to null type.
    */
747
    SrsAmf0Any* command_object; // null
748 749 750
    /**
    * the stream name to start publish or release.
    */
751
    std::string stream_name;
winlin authored
752
public:
753 754
    SrsFMLEStartPacket();
    virtual ~SrsFMLEStartPacket();
755
// decode functions for concrete packet to override.
winlin authored
756
public:
757
    virtual int decode(SrsStream* stream);
758
// encode functions for concrete packet to override.
759
public:
760 761
    virtual int get_perfer_cid();
    virtual int get_message_type();
762
protected:
763 764
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
765
// factory method to create specified FMLE packet.
766
public:
767 768
    static SrsFMLEStartPacket* create_release_stream(std::string stream);
    static SrsFMLEStartPacket* create_FC_publish(std::string stream);
winlin authored
769 770 771 772 773 774 775
};
/**
* response for SrsFMLEStartPacket.
*/
class SrsFMLEStartResPacket : public SrsPacket
{
public:
776 777 778
    /**
    * Name of the command
    */
779
    std::string command_name;
780 781 782
    /**
    * the transaction ID to get the response.
    */
783
    double transaction_id;
784 785 786
    /**
    * If there exists any command info this is set, else this is set to null type.
    */
787
    SrsAmf0Any* command_object; // null
788 789 790
    /**
    * the optional args, set to undefined.
    */
791
    SrsAmf0Any* args; // undefined
winlin authored
792
public:
793 794
    SrsFMLEStartResPacket(double _transaction_id);
    virtual ~SrsFMLEStartResPacket();
795
// decode functions for concrete packet to override.
winlin authored
796
public:
797
    virtual int decode(SrsStream* stream);
798
// encode functions for concrete packet to override.
799
public:
800 801
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
802
protected:
803 804
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
805 806 807 808 809 810 811 812 813 814 815 816
};

/**
* FMLE/flash publish
* 4.2.6. Publish
* The client sends the publish command to publish a named stream to the
* server. Using this name, any client can play this stream and receive
* the published audio, video, and data messages.
*/
class SrsPublishPacket : public SrsPacket
{
public:
817 818 819
    /**
    * Name of the command, set to “publish”.
    */
820
    std::string command_name;
821 822 823
    /**
    * Transaction ID set to 0.
    */
824
    double transaction_id;
825 826 827
    /**
    * Command information object does not exist. Set to null type.
    */
828
    SrsAmf0Any* command_object; // null
829 830 831
    /**
    * Name with which the stream is published.
    */
832
    std::string stream_name;
833 834 835 836 837 838 839 840 841 842 843 844
    /**
    * Type of publishing. Set to “live”, “record”, or “append”.
    *   record: The stream is published and the data is recorded to a new file.The file
    *           is stored on the server in a subdirectory within the directory that
    *           contains the server application. If the file already exists, it is 
    *           overwritten.
    *   append: The stream is published and the data is appended to a file. If no file
    *           is found, it is created.
    *   live: Live data is published without recording it in a file.
    * @remark, SRS only support live.
    * @remark, optional, default to live.
    */
845
    std::string type;
winlin authored
846
public:
847 848
    SrsPublishPacket();
    virtual ~SrsPublishPacket();
849
// decode functions for concrete packet to override.
winlin authored
850
public:
851
    virtual int decode(SrsStream* stream);
852
// encode functions for concrete packet to override.
winlin authored
853
public:
854 855
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
856
protected:
857 858
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
859 860 861 862 863 864 865 866 867 868
};

/**
* 4.2.8. pause
* The client sends the pause command to tell the server to pause or
* start playing.
*/
class SrsPausePacket : public SrsPacket
{
public:
869 870 871
    /**
    * Name of the command, set to “pause”.
    */
872
    std::string command_name;
873 874 875
    /**
    * There is no transaction ID for this command. Set to 0.
    */
876
    double transaction_id;
877 878 879
    /**
    * Command information object does not exist. Set to null type.
    */
880
    SrsAmf0Any* command_object; // null
881 882 883
    /**
    * true or false, to indicate pausing or resuming play
    */
884
    bool is_pause;
885 886 887 888 889 890
    /**
    * Number of milliseconds at which the the stream is paused or play resumed.
    * This is the current stream time at the Client when stream was paused. When the
    * playback is resumed, the server will only send messages with timestamps
    * greater than this value.
    */
891
    double time_ms;
winlin authored
892
public:
893 894
    SrsPausePacket();
    virtual ~SrsPausePacket();
895
// decode functions for concrete packet to override.
winlin authored
896
public:
897
    virtual int decode(SrsStream* stream);
winlin authored
898 899 900 901 902 903 904 905 906
};

/**
* 4.2.1. play
* The client sends this command to the server to play a stream.
*/
class SrsPlayPacket : public SrsPacket
{
public:
907 908 909
    /**
    * Name of the command. Set to “play”.
    */
910
    std::string command_name;
911 912 913
    /**
    * Transaction ID set to 0.
    */
914
    double transaction_id;
915 916 917
    /**
    * Command information does not exist. Set to null type.
    */
918
    SrsAmf0Any* command_object; // null
919 920 921 922 923 924 925 926 927 928
    /**
    * Name of the stream to play.
    * To play video (FLV) files, specify the name of the stream without a file
    *       extension (for example, "sample").
    * To play back MP3 or ID3 tags, you must precede the stream name with mp3:
    *       (for example, "mp3:sample".)
    * To play H.264/AAC files, you must precede the stream name with mp4: and specify the
    *       file extension. For example, to play the file sample.m4v, specify 
    *       "mp4:sample.m4v"
    */
929
    std::string stream_name;
930 931 932 933 934 935 936 937 938 939 940 941
    /**
    * An optional parameter that specifies the start time in seconds.
    * The default value is -2, which means the subscriber first tries to play the live 
    *       stream specified in the Stream Name field. If a live stream of that name is 
    *       not found, it plays the recorded stream specified in the Stream Name field.
    * If you pass -1 in the Start field, only the live stream specified in the Stream 
    *       Name field is played.
    * If you pass 0 or a positive number in the Start field, a recorded stream specified 
    *       in the Stream Name field is played beginning from the time specified in the 
    *       Start field.
    * If no recorded stream is found, the next item in the playlist is played.
    */
942
    double start;
943 944 945 946 947 948 949 950 951 952 953 954 955 956
    /**
    * An optional parameter that specifies the duration of playback in seconds.
    * The default value is -1. The -1 value means a live stream is played until it is no
    *       longer available or a recorded stream is played until it ends.
    * If u pass 0, it plays the single frame since the time specified in the Start field 
    *       from the beginning of a recorded stream. It is assumed that the value specified 
    *       in the Start field is equal to or greater than 0.
    * If you pass a positive number, it plays a live stream for the time period specified 
    *       in the Duration field. After that it becomes available or plays a recorded 
    *       stream for the time specified in the Duration field. (If a stream ends before the
    *       time specified in the Duration field, playback ends when the stream ends.)
    * If you pass a negative number other than -1 in the Duration field, it interprets the 
    *       value as if it were -1.
    */
957
    double duration;
958 959 960 961
    /**
    * An optional Boolean value or number that specifies whether to flush any
    * previous playlist.
    */
962
    bool reset;
winlin authored
963
public:
964 965
    SrsPlayPacket();
    virtual ~SrsPlayPacket();
966
// decode functions for concrete packet to override.
winlin authored
967
public:
968
    virtual int decode(SrsStream* stream);
969
// encode functions for concrete packet to override.
winlin authored
970
public:
971 972
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
973
protected:
974 975
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
976 977 978 979 980 981 982 983
};
/**
* response for SrsPlayPacket.
* @remark, user must set the stream_id in header.
*/
class SrsPlayResPacket : public SrsPacket
{
public:
984 985 986 987
    /**
    * Name of the command. If the play command is successful, the command
    * name is set to onStatus.
    */
988
    std::string command_name;
989 990 991
    /**
    * Transaction ID set to 0.
    */
992
    double transaction_id;
993 994 995
    /**
    * Command information does not exist. Set to null type.
    */
996
    SrsAmf0Any* command_object; // null
997 998 999 1000 1001
    /**
    * If the play command is successful, the client receives OnStatus message from
    * server which is NetStream.Play.Start. If the specified stream is not found,
    * NetStream.Play.StreamNotFound is received.
    */
1002
    SrsAmf0Object* desc;
winlin authored
1003
public:
1004 1005
    SrsPlayResPacket();
    virtual ~SrsPlayResPacket();
1006
// encode functions for concrete packet to override.
winlin authored
1007
public:
1008 1009
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1010
protected:
1011 1012
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1013 1014 1015 1016 1017 1018 1019 1020
};

/**
* when bandwidth test done, notice client.
*/
class SrsOnBWDonePacket : public SrsPacket
{
public:
1021 1022 1023
    /**
    * Name of command. Set to "onBWDone"
    */
1024
    std::string command_name;
1025 1026 1027
    /**
    * Transaction ID set to 0.
    */
1028
    double transaction_id;
1029 1030 1031
    /**
    * Command information does not exist. Set to null type.
    */
1032
    SrsAmf0Any* args; // null
winlin authored
1033
public:
1034 1035
    SrsOnBWDonePacket();
    virtual ~SrsOnBWDonePacket();
1036
// encode functions for concrete packet to override.
winlin authored
1037
public:
1038 1039
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1040
protected:
1041 1042
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1043 1044 1045 1046 1047 1048 1049 1050 1051
};

/**
* onStatus command, AMF0 Call
* @remark, user must set the stream_id by SrsMessage.set_packet().
*/
class SrsOnStatusCallPacket : public SrsPacket
{
public:
1052 1053 1054
    /**
    * Name of command. Set to "onStatus"
    */
1055
    std::string command_name;
1056 1057 1058
    /**
    * Transaction ID set to 0.
    */
1059
    double transaction_id;
1060 1061 1062
    /**
    * Command information does not exist. Set to null type.
    */
1063
    SrsAmf0Any* args; // null
1064 1065 1066 1067
    /**
    * Name-value pairs that describe the response from the server. 
    * ‘code’,‘level’, ‘description’ are names of few among such information.
    */
1068
    SrsAmf0Object* data;
winlin authored
1069
public:
1070 1071
    SrsOnStatusCallPacket();
    virtual ~SrsOnStatusCallPacket();
1072
// encode functions for concrete packet to override.
winlin authored
1073
public:
1074 1075
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1076
protected:
1077 1078
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1079 1080 1081
};

/**
1082 1083 1084 1085 1086 1087 1088 1089
* the special packet for the bandwidth test.
* actually, it's a SrsOnStatusCallPacket, but
* 1. encode with data field, to send data to client.
* 2. decode ignore the data field, donot care.
*/
class SrsBandwidthPacket : public SrsPacket
{
private:
1090
    disable_default_copy(SrsBandwidthPacket);
1091
public:
1092 1093 1094
    /**
    * Name of command. 
    */
1095
    std::string command_name;
1096 1097 1098
    /**
    * Transaction ID set to 0.
    */
1099
    double transaction_id;
1100 1101 1102
    /**
    * Command information does not exist. Set to null type.
    */
1103
    SrsAmf0Any* args; // null
1104 1105 1106 1107
    /**
    * Name-value pairs that describe the response from the server.
    * ‘code’,‘level’, ‘description’ are names of few among such information.
    */
1108
    SrsAmf0Object* data;
1109
public:
1110 1111
    SrsBandwidthPacket();
    virtual ~SrsBandwidthPacket();
1112
// decode functions for concrete packet to override.
1113
public:
1114 1115
    virtual int decode(SrsStream* stream);
// encode functions for concrete packet to override.
1116
public:
1117
    virtual int get_perfer_cid();
1118
    virtual int get_message_type();
1119
protected:
1120 1121
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
1122
// help function for bandwidth packet.
1123
public:
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    virtual bool is_starting_play();
    virtual bool is_stopped_play();
    virtual bool is_starting_publish();
    virtual bool is_stopped_publish();
    virtual bool is_flash_final();
    static SrsBandwidthPacket* create_finish();
    static SrsBandwidthPacket* create_start_play();
    static SrsBandwidthPacket* create_playing();
    static SrsBandwidthPacket* create_stop_play();
    static SrsBandwidthPacket* create_start_publish();
    static SrsBandwidthPacket* create_stop_publish();
1135
private:
1136
    virtual SrsBandwidthPacket* set_command(std::string command);
1137 1138 1139
};

/**
winlin authored
1140 1141 1142 1143 1144 1145
* onStatus data, AMF0 Data
* @remark, user must set the stream_id by SrsMessage.set_packet().
*/
class SrsOnStatusDataPacket : public SrsPacket
{
public:
1146 1147 1148
    /**
    * Name of command. Set to "onStatus"
    */
1149
    std::string command_name;
1150 1151 1152 1153
    /**
    * Name-value pairs that describe the response from the server.
    * ‘code’, are names of few among such information.
    */
1154
    SrsAmf0Object* data;
winlin authored
1155
public:
1156 1157
    SrsOnStatusDataPacket();
    virtual ~SrsOnStatusDataPacket();
1158
// encode functions for concrete packet to override.
winlin authored
1159
public:
1160 1161
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1162
protected:
1163 1164
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1165 1166 1167 1168 1169 1170 1171 1172 1173
};

/**
* AMF0Data RtmpSampleAccess
* @remark, user must set the stream_id by SrsMessage.set_packet().
*/
class SrsSampleAccessPacket : public SrsPacket
{
public:
1174 1175 1176
    /**
    * 
    */
1177
    std::string command_name;
1178 1179 1180
    /**
    * 
    */
1181
    bool video_sample_access;
1182 1183 1184
    /**
    * 
    */
1185
    bool audio_sample_access;
winlin authored
1186
public:
1187 1188
    SrsSampleAccessPacket();
    virtual ~SrsSampleAccessPacket();
1189
// encode functions for concrete packet to override.
winlin authored
1190
public:
1191 1192
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1193
protected:
1194 1195
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
};

/**
* the stream metadata.
* FMLE: @setDataFrame
* others: onMetaData
*/
class SrsOnMetaDataPacket : public SrsPacket
{
public:
1206 1207
    std::string name;
    SrsAmf0Object* metadata;
winlin authored
1208
public:
1209 1210
    SrsOnMetaDataPacket();
    virtual ~SrsOnMetaDataPacket();
1211
// decode functions for concrete packet to override.
winlin authored
1212
public:
1213
    virtual int decode(SrsStream* stream);
1214
// encode functions for concrete packet to override.
winlin authored
1215
public:
1216 1217
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1218
protected:
1219 1220
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
};

/**
* 5.5. Window Acknowledgement Size (5)
* The client or the server sends this message to inform the peer which
* window size to use when sending acknowledgment.
*/
class SrsSetWindowAckSizePacket : public SrsPacket
{
public:
1231
    int32_t ackowledgement_window_size;
winlin authored
1232
public:
1233 1234
    SrsSetWindowAckSizePacket();
    virtual ~SrsSetWindowAckSizePacket();
1235
// decode functions for concrete packet to override.
winlin authored
1236
public:
1237
    virtual int decode(SrsStream* stream);
1238
// encode functions for concrete packet to override.
winlin authored
1239
public:
1240 1241
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1242
protected:
1243 1244
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
};

/**
* 5.3. Acknowledgement (3)
* The client or the server sends the acknowledgment to the peer after
* receiving bytes equal to the window size.
*/
class SrsAcknowledgementPacket : public SrsPacket
{
public:
1255
    int32_t sequence_number;
winlin authored
1256
public:
1257 1258
    SrsAcknowledgementPacket();
    virtual ~SrsAcknowledgementPacket();
1259
// encode functions for concrete packet to override.
winlin authored
1260
public:
1261 1262
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1263
protected:
1264 1265
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
};

/**
* 7.1. Set Chunk Size
* Protocol control message 1, Set Chunk Size, is used to notify the
* peer about the new maximum chunk size.
*/
class SrsSetChunkSizePacket : public SrsPacket
{
public:
1276
    int32_t chunk_size;
winlin authored
1277
public:
1278 1279
    SrsSetChunkSizePacket();
    virtual ~SrsSetChunkSizePacket();
1280
// decode functions for concrete packet to override.
winlin authored
1281
public:
1282
    virtual int decode(SrsStream* stream);
1283
// encode functions for concrete packet to override.
winlin authored
1284
public:
1285 1286
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1287
protected:
1288 1289
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
};

/**
* 5.6. Set Peer Bandwidth (6)
* The client or the server sends this message to update the output
* bandwidth of the peer.
*/
class SrsSetPeerBandwidthPacket : public SrsPacket
{
public:
1300 1301
    int32_t bandwidth;
    int8_t type;
winlin authored
1302
public:
1303 1304
    SrsSetPeerBandwidthPacket();
    virtual ~SrsSetPeerBandwidthPacket();
1305
// encode functions for concrete packet to override.
winlin authored
1306
public:
1307 1308
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1309
protected:
1310 1311
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1312 1313 1314 1315 1316
};

// 3.7. User Control message
enum SrcPCUCEventType
{
1317 1318 1319 1320 1321 1322 1323 1324
     // generally, 4bytes event-data
    SrcPCUCStreamBegin             = 0x00,
    SrcPCUCStreamEOF             = 0x01,
    SrcPCUCStreamDry             = 0x02,
    SrcPCUCSetBufferLength         = 0x03, // 8bytes event-data
    SrcPCUCStreamIsRecorded     = 0x04,
    SrcPCUCPingRequest             = 0x06,
    SrcPCUCPingResponse         = 0x07,
winlin authored
1325 1326 1327 1328
};

/**
* for the EventData is 4bytes.
1329 1330 1331 1332 1333 1334 1335
* Stream Begin(=0)            4-bytes stream ID
* Stream EOF(=1)            4-bytes stream ID
* StreamDry(=2)                4-bytes stream ID
* SetBufferLength(=3)        8-bytes 4bytes stream ID, 4bytes buffer length.
* StreamIsRecorded(=4)        4-bytes stream ID
* PingRequest(=6)            4-bytes timestamp local server time
* PingResponse(=7)            4-bytes timestamp received ping request.
winlin authored
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
* 
* 3.7. User Control message
* +------------------------------+-------------------------
* | Event Type ( 2- bytes ) | Event Data
* +------------------------------+-------------------------
* Figure 5 Pay load for the ‘User Control Message’.
*/
class SrsUserControlPacket : public SrsPacket
{
public:
1346 1347 1348 1349 1350 1351 1352
    // @see: SrcPCUCEventType
    int16_t event_type;
    int32_t event_data;
    /**
    * 4bytes if event_type is SetBufferLength; otherwise 0.
    */
    int32_t extra_data;
winlin authored
1353
public:
1354 1355
    SrsUserControlPacket();
    virtual ~SrsUserControlPacket();
1356
// decode functions for concrete packet to override.
winlin authored
1357
public:
1358
    virtual int decode(SrsStream* stream);
1359
// encode functions for concrete packet to override.
winlin authored
1360
public:
1361 1362
    virtual int get_perfer_cid();
    virtual int get_message_type();
winlin authored
1363
protected:
1364 1365
    virtual int get_size();
    virtual int encode_packet(SrsStream* stream);
winlin authored
1366 1367 1368 1369 1370 1371 1372
};

/**
* expect a specified message, drop others util got specified one.
* @pmsg, user must free it. NULL if not success.
* @ppacket, store in the pmsg, user must never free it. NULL if not success.
* @remark, only when success, user can use and must free the pmsg/ppacket.
1373
* for example:
1374 1375 1376 1377 1378 1379
         SrsCommonMessage* msg = NULL;
        SrsConnectAppResPacket* pkt = NULL;
        if ((ret = srs_rtmp_expect_message<SrsConnectAppResPacket>(protocol, &msg, &pkt)) != ERROR_SUCCESS) {
            return ret;
        }
        // use pkt
1380 1381
* user should never recv message and convert it, use this method instead.
* if need to set timeout, use set timeout of SrsProtocol.
winlin authored
1382 1383
*/
template<class T>
1384
int srs_rtmp_expect_message(SrsProtocol* protocol, SrsMessage** pmsg, T** ppacket)
1385 1386 1387 1388 1389 1390 1391
{
    *pmsg = NULL;
    *ppacket = NULL;
    
    int ret = ERROR_SUCCESS;
    
    while (true) {
1392 1393
        SrsMessage* msg = NULL;
        if ((ret = protocol->recv_message(&msg)) != ERROR_SUCCESS) {
1394 1395 1396 1397 1398 1399
            srs_error("recv message failed. ret=%d", ret);
            return ret;
        }
        srs_verbose("recv message success.");
        
        SrsPacket* packet = NULL;
1400
        if ((ret = protocol->decode_message(msg, &packet)) != ERROR_SUCCESS) {
1401 1402
            srs_error("decode message failed. ret=%d", ret);
            srs_freep(msg);
1403
            srs_freep(packet);
1404 1405 1406 1407 1408
            return ret;
        }
        
        T* pkt = dynamic_cast<T*>(packet);
        if (!pkt) {
winlin authored
1409
            srs_info("drop message(type=%d, size=%d, time=%"PRId64", sid=%d).", 
1410 1411 1412
                msg->header.message_type, msg->header.payload_length,
                msg->header.timestamp, msg->header.stream_id);
            srs_freep(msg);
1413
            srs_freep(packet);
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
            continue;
        }
        
        *pmsg = msg;
        *ppacket = pkt;
        break;
    }
    
    return ret;
}
winlin authored
1424
1425
#endif