2 * RTMP network protocol
3 * Copyright (c) 2009 Kostya Shishkov
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavcodec/bytestream.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/intfloat.h"
30 #include "libavutil/lfg.h"
31 #include "libavutil/sha.h"
44 /** RTMP protocol handler state */
46 STATE_START, ///< client has not done anything yet
47 STATE_HANDSHAKED, ///< client has performed handshake
48 STATE_RELEASING, ///< client releasing stream before publish it (for output)
49 STATE_FCPUBLISH, ///< client FCPublishing stream (for output)
50 STATE_CONNECTING, ///< client connected to server successfully
51 STATE_READY, ///< client has sent all needed commands and waits for server reply
52 STATE_PLAYING, ///< client has started receiving multimedia data from server
53 STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output)
54 STATE_STOPPED, ///< the broadcast has been stopped
57 /** protocol handler context */
58 typedef struct RTMPContext {
59 URLContext* stream; ///< TCP stream used in interactions with RTMP server
60 RTMPPacket prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
61 int chunk_size; ///< size of the chunks RTMP packets are divided into
62 int is_input; ///< input/output flag
63 char playpath[256]; ///< path to filename to play (with possible "mp4:" prefix)
64 char app[128]; ///< application
65 ClientState state; ///< current state
66 int main_channel_id; ///< an additional channel ID which is used for some invocations
67 uint8_t* flv_data; ///< buffer with data for demuxer
68 int flv_size; ///< current buffer size
69 int flv_off; ///< number of bytes read from current buffer
70 RTMPPacket out_pkt; ///< rtmp packet, created from flv a/v or metadata (for output)
71 uint32_t client_report_size; ///< number of bytes after which client should report to server
72 uint32_t bytes_read; ///< number of bytes read from server
73 uint32_t last_bytes_read; ///< number of bytes read last reported to server
74 int skip_bytes; ///< number of bytes to skip from the input FLV stream in the next write call
75 uint8_t flv_header[11]; ///< partial incoming flv packet header
76 int flv_header_bytes; ///< number of initialized bytes in flv_header
77 int nb_invokes; ///< keeps track of invoke messages
78 int create_stream_invoke; ///< invoke id for the create stream command
81 #define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing
82 /** Client key used for digest signing */
83 static const uint8_t rtmp_player_key[] = {
84 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
85 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
87 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
88 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
89 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
92 #define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing
93 /** Key used for RTMP server digest signing */
94 static const uint8_t rtmp_server_key[] = {
95 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
96 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
97 'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',
99 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
100 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
101 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
105 * Generate 'connect' call and send it to the server.
107 static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
108 const char *host, int port)
114 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 4096);
117 ff_url_join(tcurl, sizeof(tcurl), proto, NULL, host, port, "/%s", rt->app);
118 ff_amf_write_string(&p, "connect");
119 ff_amf_write_number(&p, ++rt->nb_invokes);
120 ff_amf_write_object_start(&p);
121 ff_amf_write_field_name(&p, "app");
122 ff_amf_write_string(&p, rt->app);
125 snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1,
126 RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
128 snprintf(ver, sizeof(ver), "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);
129 ff_amf_write_field_name(&p, "type");
130 ff_amf_write_string(&p, "nonprivate");
132 ff_amf_write_field_name(&p, "flashVer");
133 ff_amf_write_string(&p, ver);
134 ff_amf_write_field_name(&p, "tcUrl");
135 ff_amf_write_string(&p, tcurl);
137 ff_amf_write_field_name(&p, "fpad");
138 ff_amf_write_bool(&p, 0);
139 ff_amf_write_field_name(&p, "capabilities");
140 ff_amf_write_number(&p, 15.0);
142 /* Tell the server we support all the audio codecs except
143 * SUPPORT_SND_INTEL (0x0008) and SUPPORT_SND_UNUSED (0x0010)
144 * which are unused in the RTMP protocol implementation. */
145 ff_amf_write_field_name(&p, "audioCodecs");
146 ff_amf_write_number(&p, 4071.0);
147 ff_amf_write_field_name(&p, "videoCodecs");
148 ff_amf_write_number(&p, 252.0);
149 ff_amf_write_field_name(&p, "videoFunction");
150 ff_amf_write_number(&p, 1.0);
152 ff_amf_write_object_end(&p);
154 pkt.data_size = p - pkt.data;
156 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
157 ff_rtmp_packet_destroy(&pkt);
161 * Generate 'releaseStream' call and send it to the server. It should make
162 * the server release some channel for media streams.
164 static void gen_release_stream(URLContext *s, RTMPContext *rt)
169 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
170 29 + strlen(rt->playpath));
172 av_log(s, AV_LOG_DEBUG, "Releasing stream...\n");
174 ff_amf_write_string(&p, "releaseStream");
175 ff_amf_write_number(&p, ++rt->nb_invokes);
176 ff_amf_write_null(&p);
177 ff_amf_write_string(&p, rt->playpath);
179 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
180 ff_rtmp_packet_destroy(&pkt);
184 * Generate 'FCPublish' call and send it to the server. It should make
185 * the server preapare for receiving media streams.
187 static void gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
192 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
193 25 + strlen(rt->playpath));
195 av_log(s, AV_LOG_DEBUG, "FCPublish stream...\n");
197 ff_amf_write_string(&p, "FCPublish");
198 ff_amf_write_number(&p, ++rt->nb_invokes);
199 ff_amf_write_null(&p);
200 ff_amf_write_string(&p, rt->playpath);
202 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
203 ff_rtmp_packet_destroy(&pkt);
207 * Generate 'FCUnpublish' call and send it to the server. It should make
208 * the server destroy stream.
210 static void gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
215 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
216 27 + strlen(rt->playpath));
218 av_log(s, AV_LOG_DEBUG, "UnPublishing stream...\n");
220 ff_amf_write_string(&p, "FCUnpublish");
221 ff_amf_write_number(&p, ++rt->nb_invokes);
222 ff_amf_write_null(&p);
223 ff_amf_write_string(&p, rt->playpath);
225 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
226 ff_rtmp_packet_destroy(&pkt);
230 * Generate 'createStream' call and send it to the server. It should make
231 * the server allocate some channel for media streams.
233 static void gen_create_stream(URLContext *s, RTMPContext *rt)
238 av_log(s, AV_LOG_DEBUG, "Creating stream...\n");
239 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 25);
242 ff_amf_write_string(&p, "createStream");
243 ff_amf_write_number(&p, ++rt->nb_invokes);
244 ff_amf_write_null(&p);
245 rt->create_stream_invoke = rt->nb_invokes;
247 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
248 ff_rtmp_packet_destroy(&pkt);
253 * Generate 'deleteStream' call and send it to the server. It should make
254 * the server remove some channel for media streams.
256 static void gen_delete_stream(URLContext *s, RTMPContext *rt)
261 av_log(s, AV_LOG_DEBUG, "Deleting stream...\n");
262 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 34);
265 ff_amf_write_string(&p, "deleteStream");
266 ff_amf_write_number(&p, ++rt->nb_invokes);
267 ff_amf_write_null(&p);
268 ff_amf_write_number(&p, rt->main_channel_id);
270 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
271 ff_rtmp_packet_destroy(&pkt);
275 * Generate 'play' call and send it to the server, then ping the server
276 * to start actual playing.
278 static void gen_play(URLContext *s, RTMPContext *rt)
283 av_log(s, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
284 ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0,
285 20 + strlen(rt->playpath));
286 pkt.extra = rt->main_channel_id;
289 ff_amf_write_string(&p, "play");
290 ff_amf_write_number(&p, ++rt->nb_invokes);
291 ff_amf_write_null(&p);
292 ff_amf_write_string(&p, rt->playpath);
294 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
295 ff_rtmp_packet_destroy(&pkt);
297 // set client buffer time disguised in ping packet
298 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10);
301 bytestream_put_be16(&p, 3);
302 bytestream_put_be32(&p, 1);
303 bytestream_put_be32(&p, 256); //TODO: what is a good value here?
305 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
306 ff_rtmp_packet_destroy(&pkt);
310 * Generate 'publish' call and send it to the server.
312 static void gen_publish(URLContext *s, RTMPContext *rt)
317 av_log(s, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
318 ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE, 0,
319 30 + strlen(rt->playpath));
320 pkt.extra = rt->main_channel_id;
323 ff_amf_write_string(&p, "publish");
324 ff_amf_write_number(&p, ++rt->nb_invokes);
325 ff_amf_write_null(&p);
326 ff_amf_write_string(&p, rt->playpath);
327 ff_amf_write_string(&p, "live");
329 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
330 ff_rtmp_packet_destroy(&pkt);
334 * Generate ping reply and send it to the server.
336 static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
341 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6);
343 bytestream_put_be16(&p, 7);
344 bytestream_put_be32(&p, AV_RB32(ppkt->data+2));
345 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
346 ff_rtmp_packet_destroy(&pkt);
350 * Generate server bandwidth message and send it to the server.
352 static void gen_server_bw(URLContext *s, RTMPContext *rt)
357 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_SERVER_BW, 0, 4);
359 bytestream_put_be32(&p, 2500000);
360 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
361 ff_rtmp_packet_destroy(&pkt);
365 * Generate report on bytes read so far and send it to the server.
367 static void gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
372 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_BYTES_READ, ts, 4);
374 bytestream_put_be32(&p, rt->bytes_read);
375 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
376 ff_rtmp_packet_destroy(&pkt);
379 //TODO: Move HMAC code somewhere. Eventually.
380 #define HMAC_IPAD_VAL 0x36
381 #define HMAC_OPAD_VAL 0x5C
384 * Calculate HMAC-SHA2 digest for RTMP handshake packets.
386 * @param src input buffer
387 * @param len input buffer length (should be 1536)
388 * @param gap offset in buffer where 32 bytes should not be taken into account
389 * when calculating digest (since it will be used to store that digest)
390 * @param key digest key
391 * @param keylen digest key length
392 * @param dst buffer where calculated digest will be stored (32 bytes)
394 static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
395 const uint8_t *key, int keylen, uint8_t *dst)
398 uint8_t hmac_buf[64+32] = {0};
401 sha = av_mallocz(av_sha_size);
404 memcpy(hmac_buf, key, keylen);
406 av_sha_init(sha, 256);
407 av_sha_update(sha,key, keylen);
408 av_sha_final(sha, hmac_buf);
410 for (i = 0; i < 64; i++)
411 hmac_buf[i] ^= HMAC_IPAD_VAL;
413 av_sha_init(sha, 256);
414 av_sha_update(sha, hmac_buf, 64);
416 av_sha_update(sha, src, len);
417 } else { //skip 32 bytes used for storing digest
418 av_sha_update(sha, src, gap);
419 av_sha_update(sha, src + gap + 32, len - gap - 32);
421 av_sha_final(sha, hmac_buf + 64);
423 for (i = 0; i < 64; i++)
424 hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
425 av_sha_init(sha, 256);
426 av_sha_update(sha, hmac_buf, 64+32);
427 av_sha_final(sha, dst);
433 * Put HMAC-SHA2 digest of packet data (except for the bytes where this digest
434 * will be stored) into that packet.
436 * @param buf handshake data (1536 bytes)
437 * @return offset to the digest inside input data
439 static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
441 int i, digest_pos = 0;
443 for (i = 8; i < 12; i++)
444 digest_pos += buf[i];
445 digest_pos = (digest_pos % 728) + 12;
447 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
448 rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
454 * Verify that the received server response has the expected digest value.
456 * @param buf handshake data received from the server (1536 bytes)
457 * @param off position to search digest offset from
458 * @return 0 if digest is valid, digest position otherwise
460 static int rtmp_validate_digest(uint8_t *buf, int off)
462 int i, digest_pos = 0;
465 for (i = 0; i < 4; i++)
466 digest_pos += buf[i + off];
467 digest_pos = (digest_pos % 728) + off + 4;
469 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
470 rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
472 if (!memcmp(digest, buf + digest_pos, 32))
478 * Perform handshake with the server by means of exchanging pseudorandom data
479 * signed with HMAC-SHA2 digest.
481 * @return 0 if handshake succeeds, negative value otherwise
483 static int rtmp_handshake(URLContext *s, RTMPContext *rt)
486 uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
487 3, // unencrypted data
488 0, 0, 0, 0, // client uptime
494 uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
495 uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
497 int server_pos, client_pos;
500 av_log(s, AV_LOG_DEBUG, "Handshaking...\n");
502 av_lfg_init(&rnd, 0xDEADC0DE);
503 // generate handshake packet - 1536 bytes of pseudorandom data
504 for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
505 tosend[i] = av_lfg_get(&rnd) >> 24;
506 client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
508 ffurl_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
509 i = ffurl_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
510 if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
511 av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
514 i = ffurl_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
515 if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
516 av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
520 av_log(s, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
521 serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
523 if (rt->is_input && serverdata[5] >= 3) {
524 server_pos = rtmp_validate_digest(serverdata + 1, 772);
526 server_pos = rtmp_validate_digest(serverdata + 1, 8);
528 av_log(s, AV_LOG_ERROR, "Server response validating failed\n");
533 rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
534 rtmp_server_key, sizeof(rtmp_server_key),
536 rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0,
539 if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
540 av_log(s, AV_LOG_ERROR, "Signature mismatch\n");
544 for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
545 tosend[i] = av_lfg_get(&rnd) >> 24;
546 rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
547 rtmp_player_key, sizeof(rtmp_player_key),
549 rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
551 tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
553 // write reply back to the server
554 ffurl_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
556 ffurl_write(rt->stream, serverdata+1, RTMP_HANDSHAKE_PACKET_SIZE);
563 * Parse received packet and possibly perform some action depending on
564 * the packet contents.
565 * @return 0 for no errors, negative values for serious errors which prevent
566 * further communications, positive values for uncritical errors
568 static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
571 const uint8_t *data_end = pkt->data + pkt->data_size;
574 ff_rtmp_packet_dump(s, pkt);
578 case RTMP_PT_CHUNK_SIZE:
579 if (pkt->data_size != 4) {
580 av_log(s, AV_LOG_ERROR,
581 "Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size);
585 ff_rtmp_packet_write(rt->stream, pkt, rt->chunk_size, rt->prev_pkt[1]);
586 rt->chunk_size = AV_RB32(pkt->data);
587 if (rt->chunk_size <= 0) {
588 av_log(s, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size);
591 av_log(s, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size);
594 t = AV_RB16(pkt->data);
596 gen_pong(s, rt, pkt);
598 case RTMP_PT_CLIENT_BW:
599 if (pkt->data_size < 4) {
600 av_log(s, AV_LOG_ERROR,
601 "Client bandwidth report packet is less than 4 bytes long (%d)\n",
605 av_log(s, AV_LOG_DEBUG, "Client bandwidth = %d\n", AV_RB32(pkt->data));
606 rt->client_report_size = AV_RB32(pkt->data) >> 1;
609 //TODO: check for the messages sent for wrong state?
610 if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
613 if (!ff_amf_get_field_value(pkt->data + 9, data_end,
614 "description", tmpstr, sizeof(tmpstr)))
615 av_log(s, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
617 } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
619 case STATE_HANDSHAKED:
621 gen_release_stream(s, rt);
622 gen_fcpublish_stream(s, rt);
623 rt->state = STATE_RELEASING;
625 gen_server_bw(s, rt);
626 rt->state = STATE_CONNECTING;
628 gen_create_stream(s, rt);
630 case STATE_FCPUBLISH:
631 rt->state = STATE_CONNECTING;
633 case STATE_RELEASING:
634 rt->state = STATE_FCPUBLISH;
635 /* hack for Wowza Media Server, it does not send result for
636 * releaseStream and FCPublish calls */
637 if (!pkt->data[10]) {
638 int pkt_id = av_int2double(AV_RB64(pkt->data + 11));
639 if (pkt_id == rt->create_stream_invoke)
640 rt->state = STATE_CONNECTING;
642 if (rt->state != STATE_CONNECTING)
644 case STATE_CONNECTING:
645 //extract a number from the result
646 if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
647 av_log(s, AV_LOG_WARNING, "Unexpected reply on connect()\n");
649 rt->main_channel_id = av_int2double(AV_RB64(pkt->data + 21));
656 rt->state = STATE_READY;
659 } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
660 const uint8_t* ptr = pkt->data + 11;
663 for (i = 0; i < 2; i++) {
664 t = ff_amf_tag_size(ptr, data_end);
669 t = ff_amf_get_field_value(ptr, data_end,
670 "level", tmpstr, sizeof(tmpstr));
671 if (!t && !strcmp(tmpstr, "error")) {
672 if (!ff_amf_get_field_value(ptr, data_end,
673 "description", tmpstr, sizeof(tmpstr)))
674 av_log(s, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
677 t = ff_amf_get_field_value(ptr, data_end,
678 "code", tmpstr, sizeof(tmpstr));
679 if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING;
680 if (!t && !strcmp(tmpstr, "NetStream.Play.Stop")) rt->state = STATE_STOPPED;
681 if (!t && !strcmp(tmpstr, "NetStream.Play.UnpublishNotify")) rt->state = STATE_STOPPED;
682 if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING;
690 * Interact with the server by receiving and sending RTMP packets until
691 * there is some significant data (media data or expected status notification).
693 * @param s reading context
694 * @param for_header non-zero value tells function to work until it
695 * gets notification from the server that playing has been started,
696 * otherwise function will work until some media data is received (or
698 * @return 0 for successful operation, negative value in case of error
700 static int get_packet(URLContext *s, int for_header)
702 RTMPContext *rt = s->priv_data;
707 uint32_t ts, cts, pts=0;
709 if (rt->state == STATE_STOPPED)
713 RTMPPacket rpkt = { 0 };
714 if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
715 rt->chunk_size, rt->prev_pkt[0])) <= 0) {
717 return AVERROR(EAGAIN);
722 rt->bytes_read += ret;
723 if (rt->bytes_read - rt->last_bytes_read > rt->client_report_size) {
724 av_log(s, AV_LOG_DEBUG, "Sending bytes read report\n");
725 gen_bytes_read(s, rt, rpkt.timestamp + 1);
726 rt->last_bytes_read = rt->bytes_read;
729 ret = rtmp_parse_result(s, rt, &rpkt);
730 if (ret < 0) {//serious error in current packet
731 ff_rtmp_packet_destroy(&rpkt);
734 if (rt->state == STATE_STOPPED) {
735 ff_rtmp_packet_destroy(&rpkt);
738 if (for_header && (rt->state == STATE_PLAYING || rt->state == STATE_PUBLISHING)) {
739 ff_rtmp_packet_destroy(&rpkt);
742 if (!rpkt.data_size || !rt->is_input) {
743 ff_rtmp_packet_destroy(&rpkt);
746 if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
747 (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) {
750 // generate packet header and put data into buffer for FLV demuxer
752 rt->flv_size = rpkt.data_size + 15;
753 rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
754 bytestream_put_byte(&p, rpkt.type);
755 bytestream_put_be24(&p, rpkt.data_size);
756 bytestream_put_be24(&p, ts);
757 bytestream_put_byte(&p, ts >> 24);
758 bytestream_put_be24(&p, 0);
759 bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
760 bytestream_put_be32(&p, 0);
761 ff_rtmp_packet_destroy(&rpkt);
763 } else if (rpkt.type == RTMP_PT_METADATA) {
764 // we got raw FLV data, make it available for FLV demuxer
766 rt->flv_size = rpkt.data_size;
767 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
768 /* rewrite timestamps */
771 while (next - rpkt.data < rpkt.data_size - 11) {
773 data_size = bytestream_get_be24(&next);
775 cts = bytestream_get_be24(&next);
776 cts |= bytestream_get_byte(&next) << 24;
781 bytestream_put_be24(&p, ts);
782 bytestream_put_byte(&p, ts >> 24);
783 next += data_size + 3 + 4;
785 memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
786 ff_rtmp_packet_destroy(&rpkt);
789 ff_rtmp_packet_destroy(&rpkt);
793 static int rtmp_close(URLContext *h)
795 RTMPContext *rt = h->priv_data;
799 if (rt->out_pkt.data_size)
800 ff_rtmp_packet_destroy(&rt->out_pkt);
801 if (rt->state > STATE_FCPUBLISH)
802 gen_fcunpublish_stream(h, rt);
804 if (rt->state > STATE_HANDSHAKED)
805 gen_delete_stream(h, rt);
807 av_freep(&rt->flv_data);
808 ffurl_close(rt->stream);
813 * Open RTMP connection and verify that the stream can be played.
815 * URL syntax: rtmp://server[:port][/app][/playpath]
816 * where 'app' is first one or two directories in the path
817 * (e.g. /ondemand/, /flash/live/, etc.)
818 * and 'playpath' is a file name (the rest of the path,
819 * may be prefixed with "mp4:")
821 static int rtmp_open(URLContext *s, const char *uri, int flags)
823 RTMPContext *rt = s->priv_data;
824 char proto[8], hostname[256], path[1024], *fname;
829 rt->is_input = !(flags & AVIO_FLAG_WRITE);
831 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
832 path, sizeof(path), s->filename);
835 port = RTMP_DEFAULT_PORT;
836 ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
838 if (ffurl_open(&rt->stream, buf, AVIO_FLAG_READ_WRITE,
839 &s->interrupt_callback, NULL) < 0) {
840 av_log(s , AV_LOG_ERROR, "Cannot open connection %s\n", buf);
844 rt->state = STATE_START;
845 if (rtmp_handshake(s, rt))
848 rt->chunk_size = 128;
849 rt->state = STATE_HANDSHAKED;
850 //extract "app" part from path
851 if (!strncmp(path, "/ondemand/", 10)) {
853 memcpy(rt->app, "ondemand", 9);
855 char *p = strchr(path + 1, '/');
860 char *c = strchr(p + 1, ':');
861 fname = strchr(p + 1, '/');
862 if (!fname || c < fname) {
864 av_strlcpy(rt->app, path + 1, p - path);
867 av_strlcpy(rt->app, path + 1, fname - path - 1);
871 if (!strchr(fname, ':') &&
872 (!strcmp(fname + strlen(fname) - 4, ".f4v") ||
873 !strcmp(fname + strlen(fname) - 4, ".mp4"))) {
874 memcpy(rt->playpath, "mp4:", 5);
878 strncat(rt->playpath, fname, sizeof(rt->playpath) - 5);
880 rt->client_report_size = 1048576;
882 rt->last_bytes_read = 0;
884 av_log(s, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
885 proto, path, rt->app, rt->playpath);
886 gen_connect(s, rt, proto, hostname, port);
889 ret = get_packet(s, 1);
890 } while (ret == EAGAIN);
895 // generate FLV header for demuxer
897 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
899 memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
907 s->max_packet_size = rt->stream->max_packet_size;
916 static int rtmp_read(URLContext *s, uint8_t *buf, int size)
918 RTMPContext *rt = s->priv_data;
919 int orig_size = size;
923 int data_left = rt->flv_size - rt->flv_off;
925 if (data_left >= size) {
926 memcpy(buf, rt->flv_data + rt->flv_off, size);
931 memcpy(buf, rt->flv_data + rt->flv_off, data_left);
934 rt->flv_off = rt->flv_size;
937 if ((ret = get_packet(s, 0)) < 0)
943 static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
945 RTMPContext *rt = s->priv_data;
946 int size_temp = size;
947 int pktsize, pkttype;
949 const uint8_t *buf_temp = buf;
952 if (rt->skip_bytes) {
953 int skip = FFMIN(rt->skip_bytes, size_temp);
956 rt->skip_bytes -= skip;
960 if (rt->flv_header_bytes < 11) {
961 const uint8_t *header = rt->flv_header;
962 int copy = FFMIN(11 - rt->flv_header_bytes, size_temp);
963 bytestream_get_buffer(&buf_temp, rt->flv_header + rt->flv_header_bytes, copy);
964 rt->flv_header_bytes += copy;
966 if (rt->flv_header_bytes < 11)
969 pkttype = bytestream_get_byte(&header);
970 pktsize = bytestream_get_be24(&header);
971 ts = bytestream_get_be24(&header);
972 ts |= bytestream_get_byte(&header) << 24;
973 bytestream_get_be24(&header);
974 rt->flv_size = pktsize;
976 //force 12bytes header
977 if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
978 pkttype == RTMP_PT_NOTIFY) {
979 if (pkttype == RTMP_PT_NOTIFY)
981 rt->prev_pkt[1][RTMP_SOURCE_CHANNEL].channel_id = 0;
984 //this can be a big packet, it's better to send it right here
985 ff_rtmp_packet_create(&rt->out_pkt, RTMP_SOURCE_CHANNEL, pkttype, ts, pktsize);
986 rt->out_pkt.extra = rt->main_channel_id;
987 rt->flv_data = rt->out_pkt.data;
989 if (pkttype == RTMP_PT_NOTIFY)
990 ff_amf_write_string(&rt->flv_data, "@setDataFrame");
993 if (rt->flv_size - rt->flv_off > size_temp) {
994 bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, size_temp);
995 rt->flv_off += size_temp;
998 bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, rt->flv_size - rt->flv_off);
999 size_temp -= rt->flv_size - rt->flv_off;
1000 rt->flv_off += rt->flv_size - rt->flv_off;
1003 if (rt->flv_off == rt->flv_size) {
1006 ff_rtmp_packet_write(rt->stream, &rt->out_pkt, rt->chunk_size, rt->prev_pkt[1]);
1007 ff_rtmp_packet_destroy(&rt->out_pkt);
1010 rt->flv_header_bytes = 0;
1012 } while (buf_temp - buf < size);
1016 URLProtocol ff_rtmp_protocol = {
1018 .url_open = rtmp_open,
1019 .url_read = rtmp_read,
1020 .url_write = rtmp_write,
1021 .url_close = rtmp_close,
1022 .priv_data_size = sizeof(RTMPContext),
1023 .flags = URL_PROTOCOL_FLAG_NETWORK,