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
23 * @file libavformat/rtmpproto.c
27 #include "libavcodec/bytestream.h"
28 #include "libavutil/avstring.h"
29 #include "libavutil/lfg.h"
30 #include "libavutil/sha.h"
39 /* we can't use av_log() with URLContext yet... */
40 #if LIBAVFORMAT_VERSION_MAJOR < 53
41 #define LOG_CONTEXT NULL
46 /** RTMP protocol handler state */
48 STATE_START, ///< client has not done anything yet
49 STATE_HANDSHAKED, ///< client has performed handshake
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
55 /** protocol handler context */
56 typedef struct RTMPContext {
57 URLContext* stream; ///< TCP stream used in interactions with RTMP server
58 RTMPPacket prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
59 int chunk_size; ///< size of the chunks RTMP packets are divided into
60 int is_input; ///< input/output flag
61 char playpath[256]; ///< path to filename to play (with possible "mp4:" prefix)
62 ClientState state; ///< current state
63 int main_channel_id; ///< an additional channel ID which is used for some invocations
64 uint8_t* flv_data; ///< buffer with data for demuxer
65 int flv_size; ///< current buffer size
66 int flv_off; ///< number of bytes read from current buffer
69 #define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing
70 /** Client key used for digest signing */
71 static const uint8_t rtmp_player_key[] = {
72 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
73 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
75 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
76 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
77 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
80 #define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing
81 /** Key used for RTMP server digest signing */
82 static const uint8_t rtmp_server_key[] = {
83 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
84 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
85 'S', 'e', 'r', 'v', '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
93 * Generates 'connect' call and sends it to the server.
95 static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
96 const char *host, int port, const char *app)
102 ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0, 4096);
105 snprintf(tcurl, sizeof(tcurl), "%s://%s:%d/%s", proto, host, port, app);
106 ff_amf_write_string(&p, "connect");
107 ff_amf_write_number(&p, 1.0);
108 ff_amf_write_object_start(&p);
109 ff_amf_write_field_name(&p, "app");
110 ff_amf_write_string(&p, app);
112 snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1,
113 RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
114 ff_amf_write_field_name(&p, "flashVer");
115 ff_amf_write_string(&p, ver);
116 ff_amf_write_field_name(&p, "tcUrl");
117 ff_amf_write_string(&p, tcurl);
118 ff_amf_write_field_name(&p, "fpad");
119 ff_amf_write_bool(&p, 0);
120 ff_amf_write_field_name(&p, "capabilities");
121 ff_amf_write_number(&p, 15.0);
122 ff_amf_write_field_name(&p, "audioCodecs");
123 ff_amf_write_number(&p, 1639.0);
124 ff_amf_write_field_name(&p, "videoCodecs");
125 ff_amf_write_number(&p, 252.0);
126 ff_amf_write_field_name(&p, "videoFunction");
127 ff_amf_write_number(&p, 1.0);
128 ff_amf_write_object_end(&p);
130 pkt.data_size = p - pkt.data;
132 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
136 * Generates 'createStream' call and sends it to the server. It should make
137 * the server allocate some channel for media streams.
139 static void gen_create_stream(URLContext *s, RTMPContext *rt)
144 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Creating stream...\n");
145 ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0, 25);
148 ff_amf_write_string(&p, "createStream");
149 ff_amf_write_number(&p, 3.0);
150 ff_amf_write_null(&p);
152 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
153 ff_rtmp_packet_destroy(&pkt);
157 * Generates 'play' call and sends it to the server, then pings the server
158 * to start actual playing.
160 static void gen_play(URLContext *s, RTMPContext *rt)
165 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
166 ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0,
167 20 + strlen(rt->playpath));
168 pkt.extra = rt->main_channel_id;
171 ff_amf_write_string(&p, "play");
172 ff_amf_write_number(&p, 0.0);
173 ff_amf_write_null(&p);
174 ff_amf_write_string(&p, rt->playpath);
176 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
177 ff_rtmp_packet_destroy(&pkt);
179 // set client buffer time disguised in ping packet
180 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10);
183 bytestream_put_be16(&p, 3);
184 bytestream_put_be32(&p, 1);
185 bytestream_put_be32(&p, 256); //TODO: what is a good value here?
187 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
188 ff_rtmp_packet_destroy(&pkt);
192 * Generates ping reply and sends it to the server.
194 static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
199 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6);
201 bytestream_put_be16(&p, 7);
202 bytestream_put_be32(&p, AV_RB32(ppkt->data+2) + 1);
203 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
204 ff_rtmp_packet_destroy(&pkt);
207 //TODO: Move HMAC code somewhere. Eventually.
208 #define HMAC_IPAD_VAL 0x36
209 #define HMAC_OPAD_VAL 0x5C
212 * Calculates HMAC-SHA2 digest for RTMP handshake packets.
214 * @param src input buffer
215 * @param len input buffer length (should be 1536)
216 * @param gap offset in buffer where 32 bytes should not be taken into account
217 * when calculating digest (since it will be used to store that digest)
218 * @param key digest key
219 * @param keylen digest key length
220 * @param dst buffer where calculated digest will be stored (32 bytes)
222 static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
223 const uint8_t *key, int keylen, uint8_t *dst)
226 uint8_t hmac_buf[64+32] = {0};
229 sha = av_mallocz(av_sha_size);
232 memcpy(hmac_buf, key, keylen);
234 av_sha_init(sha, 256);
235 av_sha_update(sha,key, keylen);
236 av_sha_final(sha, hmac_buf);
238 for (i = 0; i < 64; i++)
239 hmac_buf[i] ^= HMAC_IPAD_VAL;
241 av_sha_init(sha, 256);
242 av_sha_update(sha, hmac_buf, 64);
244 av_sha_update(sha, src, len);
245 } else { //skip 32 bytes used for storing digest
246 av_sha_update(sha, src, gap);
247 av_sha_update(sha, src + gap + 32, len - gap - 32);
249 av_sha_final(sha, hmac_buf + 64);
251 for (i = 0; i < 64; i++)
252 hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
253 av_sha_init(sha, 256);
254 av_sha_update(sha, hmac_buf, 64+32);
255 av_sha_final(sha, dst);
261 * Puts HMAC-SHA2 digest of packet data (except for the bytes where this digest
262 * will be stored) into that packet.
264 * @param buf handshake data (1536 bytes)
265 * @return offset to the digest inside input data
267 static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
269 int i, digest_pos = 0;
271 for (i = 8; i < 12; i++)
272 digest_pos += buf[i];
273 digest_pos = (digest_pos % 728) + 12;
275 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
276 rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
282 * Verifies that the received server response has the expected digest value.
284 * @param buf handshake data received from the server (1536 bytes)
285 * @param off position to search digest offset from
286 * @return 0 if digest is valid, digest position otherwise
288 static int rtmp_validate_digest(uint8_t *buf, int off)
290 int i, digest_pos = 0;
293 for (i = 0; i < 4; i++)
294 digest_pos += buf[i + off];
295 digest_pos = (digest_pos % 728) + off + 4;
297 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
298 rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
300 if (!memcmp(digest, buf + digest_pos, 32))
306 * Performs handshake with the server by means of exchanging pseudorandom data
307 * signed with HMAC-SHA2 digest.
309 * @return 0 if handshake succeeds, negative value otherwise
311 static int rtmp_handshake(URLContext *s, RTMPContext *rt)
314 uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
315 3, // unencrypted data
316 0, 0, 0, 0, // client uptime
322 uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
323 uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
325 int server_pos, client_pos;
328 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Handshaking...\n");
330 av_lfg_init(&rnd, 0xDEADC0DE);
331 // generate handshake packet - 1536 bytes of pseudorandom data
332 for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
333 tosend[i] = av_lfg_get(&rnd) >> 24;
334 client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
336 url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
337 i = url_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
338 if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
339 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
342 i = url_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
343 if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
344 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
348 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
349 serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
351 server_pos = rtmp_validate_digest(serverdata + 1, 772);
353 server_pos = rtmp_validate_digest(serverdata + 1, 8);
355 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server response validating failed\n");
360 rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
361 rtmp_server_key, sizeof(rtmp_server_key),
363 rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0,
366 if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
367 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Signature mismatch\n");
371 for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
372 tosend[i] = av_lfg_get(&rnd) >> 24;
373 rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
374 rtmp_player_key, sizeof(rtmp_player_key),
376 rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
378 tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
380 // write reply back to the server
381 url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
386 * Parses received packet and may perform some action depending on
387 * the packet contents.
388 * @return 0 for no errors, negative values for serious errors which prevent
389 * further communications, positive values for uncritical errors
391 static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
394 const uint8_t *data_end = pkt->data + pkt->data_size;
397 case RTMP_PT_CHUNK_SIZE:
398 if (pkt->data_size != 4) {
399 av_log(LOG_CONTEXT, AV_LOG_ERROR,
400 "Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size);
403 rt->chunk_size = AV_RB32(pkt->data);
404 if (rt->chunk_size <= 0) {
405 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size);
408 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size);
411 t = AV_RB16(pkt->data);
413 gen_pong(s, rt, pkt);
416 //TODO: check for the messages sent for wrong state?
417 if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
420 if (!ff_amf_get_field_value(pkt->data + 9, data_end,
421 "description", tmpstr, sizeof(tmpstr)))
422 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
424 } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
426 case STATE_HANDSHAKED:
427 gen_create_stream(s, rt);
428 rt->state = STATE_CONNECTING;
430 case STATE_CONNECTING:
431 //extract a number from the result
432 if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
433 av_log(LOG_CONTEXT, AV_LOG_WARNING, "Unexpected reply on connect()\n");
435 rt->main_channel_id = (int) av_int2dbl(AV_RB64(pkt->data + 21));
438 rt->state = STATE_READY;
441 } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
442 const uint8_t* ptr = pkt->data + 11;
446 for (i = 0; i < 2; i++) {
447 t = ff_amf_tag_size(ptr, data_end);
452 t = ff_amf_get_field_value(ptr, data_end,
453 "level", tmpstr, sizeof(tmpstr));
454 if (!t && !strcmp(tmpstr, "error")) {
455 if (!ff_amf_get_field_value(ptr, data_end,
456 "description", tmpstr, sizeof(tmpstr)))
457 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
460 t = ff_amf_get_field_value(ptr, data_end,
461 "code", tmpstr, sizeof(tmpstr));
462 if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) {
463 rt->state = STATE_PLAYING;
473 * Interacts with the server by receiving and sending RTMP packets until
474 * there is some significant data (media data or expected status notification).
476 * @param s reading context
477 * @param for_header non-zero value tells function to work until it
478 * gets notification from the server that playing has been started,
479 * otherwise function will work until some media data is received (or
481 * @return 0 for successful operation, negative value in case of error
483 static int get_packet(URLContext *s, int for_header)
485 RTMPContext *rt = s->priv_data;
490 if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
491 rt->chunk_size, rt->prev_pkt[0])) != 0) {
493 return AVERROR(EAGAIN);
499 ret = rtmp_parse_result(s, rt, &rpkt);
500 if (ret < 0) {//serious error in current packet
501 ff_rtmp_packet_destroy(&rpkt);
504 if (for_header && rt->state == STATE_PLAYING) {
505 ff_rtmp_packet_destroy(&rpkt);
508 if (!rpkt.data_size) {
509 ff_rtmp_packet_destroy(&rpkt);
512 if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
513 (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) {
515 uint32_t ts = rpkt.timestamp;
517 // generate packet header and put data into buffer for FLV demuxer
519 rt->flv_size = rpkt.data_size + 15;
520 rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
521 bytestream_put_byte(&p, rpkt.type);
522 bytestream_put_be24(&p, rpkt.data_size);
523 bytestream_put_be24(&p, ts);
524 bytestream_put_byte(&p, ts >> 24);
525 bytestream_put_be24(&p, 0);
526 bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
527 bytestream_put_be32(&p, 0);
528 ff_rtmp_packet_destroy(&rpkt);
530 } else if (rpkt.type == RTMP_PT_METADATA) {
531 // we got raw FLV data, make it available for FLV demuxer
533 rt->flv_size = rpkt.data_size;
534 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
535 memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
536 ff_rtmp_packet_destroy(&rpkt);
539 ff_rtmp_packet_destroy(&rpkt);
544 static int rtmp_close(URLContext *h)
546 RTMPContext *rt = h->priv_data;
548 av_freep(&rt->flv_data);
549 url_close(rt->stream);
555 * Opens RTMP connection and verifies that the stream can be played.
557 * URL syntax: rtmp://server[:port][/app][/playpath]
558 * where 'app' is first one or two directories in the path
559 * (e.g. /ondemand/, /flash/live/, etc.)
560 * and 'playpath' is a file name (the rest of the path,
561 * may be prefixed with "mp4:")
563 static int rtmp_open(URLContext *s, const char *uri, int flags)
566 char proto[8], hostname[256], path[1024], app[128], *fname;
571 rt = av_mallocz(sizeof(RTMPContext));
573 return AVERROR(ENOMEM);
575 rt->is_input = !(flags & URL_WRONLY);
577 url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
578 path, sizeof(path), s->filename);
581 port = RTMP_DEFAULT_PORT;
582 snprintf(buf, sizeof(buf), "tcp://%s:%d", hostname, port);
584 if (url_open(&rt->stream, buf, URL_RDWR) < 0) {
585 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot open connection %s\n", buf);
590 av_log(LOG_CONTEXT, AV_LOG_ERROR, "RTMP output is not supported yet.\n");
593 rt->state = STATE_START;
594 if (rtmp_handshake(s, rt))
597 rt->chunk_size = 128;
598 rt->state = STATE_HANDSHAKED;
599 //extract "app" part from path
600 if (!strncmp(path, "/ondemand/", 10)) {
602 memcpy(app, "ondemand", 9);
604 char *p = strchr(path + 1, '/');
609 char *c = strchr(p + 1, ':');
610 fname = strchr(p + 1, '/');
611 if (!fname || c < fname) {
613 av_strlcpy(app, path + 1, p - path);
616 av_strlcpy(app, path + 1, fname - path - 1);
620 if (!strchr(fname, ':') &&
621 (!strcmp(fname + strlen(fname) - 4, ".f4v") ||
622 !strcmp(fname + strlen(fname) - 4, ".mp4"))) {
623 memcpy(rt->playpath, "mp4:", 5);
627 strncat(rt->playpath, fname, sizeof(rt->playpath) - 5);
629 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
630 proto, path, app, rt->playpath);
631 gen_connect(s, rt, proto, hostname, port, app);
634 ret = get_packet(s, 1);
635 } while (ret == EAGAIN);
638 // generate FLV header for demuxer
640 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
642 memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
645 s->max_packet_size = url_get_max_packet_size(rt->stream);
654 static int rtmp_read(URLContext *s, uint8_t *buf, int size)
656 RTMPContext *rt = s->priv_data;
657 int orig_size = size;
661 int data_left = rt->flv_size - rt->flv_off;
663 if (data_left >= size) {
664 memcpy(buf, rt->flv_data + rt->flv_off, size);
669 memcpy(buf, rt->flv_data + rt->flv_off, data_left);
672 rt->flv_off = rt->flv_size;
674 if ((ret = get_packet(s, 0)) < 0)
680 static int rtmp_write(URLContext *h, uint8_t *buf, int size)
685 URLProtocol rtmp_protocol = {