5l trocadero: don't forget to free packet in gen_connect()
[libav.git] / libavformat / rtmpproto.c
CommitLineData
9fd6b843
KS
1/*
2 * RTMP network protocol
3 * Copyright (c) 2009 Kostya Shishkov
4 *
5 * This file is part of FFmpeg.
6 *
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.
11 *
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.
16 *
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
20 */
21
22/**
23 * @file libavformat/rtmpproto.c
24 * RTMP protocol
25 */
26
27#include "libavcodec/bytestream.h"
28#include "libavutil/avstring.h"
29#include "libavutil/lfg.h"
30#include "libavutil/sha.h"
31#include "avformat.h"
32
33#include "network.h"
34
35#include "flv.h"
36#include "rtmp.h"
37#include "rtmppkt.h"
38
39/* we can't use av_log() with URLContext yet... */
40#if LIBAVFORMAT_VERSION_MAJOR < 53
41#define LOG_CONTEXT NULL
42#else
43#define LOG_CONTEXT s
44#endif
45
46/** RTMP protocol handler state */
47typedef enum {
48 STATE_START, ///< client has not done anything yet
49 STATE_HANDSHAKED, ///< client has performed handshake
6bf22e18
S
50 STATE_RELEASING, ///< client releasing stream before publish it (for output)
51 STATE_FCPUBLISH, ///< client FCPublishing stream (for output)
9fd6b843
KS
52 STATE_CONNECTING, ///< client connected to server successfully
53 STATE_READY, ///< client has sent all needed commands and waits for server reply
54 STATE_PLAYING, ///< client has started receiving multimedia data from server
6bf22e18 55 STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output)
72b870b9 56 STATE_STOPPED, ///< the broadcast has been stopped
9fd6b843
KS
57} ClientState;
58
59/** protocol handler context */
60typedef struct RTMPContext {
61 URLContext* stream; ///< TCP stream used in interactions with RTMP server
62 RTMPPacket prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
63 int chunk_size; ///< size of the chunks RTMP packets are divided into
b316991b 64 int is_input; ///< input/output flag
9fd6b843 65 char playpath[256]; ///< path to filename to play (with possible "mp4:" prefix)
5e9ad759 66 char app[128]; ///< application
9fd6b843
KS
67 ClientState state; ///< current state
68 int main_channel_id; ///< an additional channel ID which is used for some invocations
69 uint8_t* flv_data; ///< buffer with data for demuxer
70 int flv_size; ///< current buffer size
71 int flv_off; ///< number of bytes read from current buffer
6bf22e18 72 RTMPPacket out_pkt; ///< rtmp packet, created from flv a/v or metadata (for output)
9fd6b843
KS
73} RTMPContext;
74
75#define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing
76/** Client key used for digest signing */
77static const uint8_t rtmp_player_key[] = {
78 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
79 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
80
81 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
82 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
83 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
84};
85
86#define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing
87/** Key used for RTMP server digest signing */
88static const uint8_t rtmp_server_key[] = {
89 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
90 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
91 'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',
92
93 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
94 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
95 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
96};
97
98/**
99 * Generates 'connect' call and sends it to the server.
100 */
101static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
5e9ad759 102 const char *host, int port)
9fd6b843
KS
103{
104 RTMPPacket pkt;
6bf22e18 105 uint8_t ver[64], *p;
9fd6b843
KS
106 char tcurl[512];
107
31da5966 108 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 4096);
9fd6b843
KS
109 p = pkt.data;
110
5e9ad759 111 snprintf(tcurl, sizeof(tcurl), "%s://%s:%d/%s", proto, host, port, rt->app);
9fd6b843
KS
112 ff_amf_write_string(&p, "connect");
113 ff_amf_write_number(&p, 1.0);
114 ff_amf_write_object_start(&p);
115 ff_amf_write_field_name(&p, "app");
5e9ad759 116 ff_amf_write_string(&p, rt->app);
9fd6b843 117
6bf22e18 118 if (rt->is_input) {
c7240611
KS
119 snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1,
120 RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
6bf22e18
S
121 } else {
122 snprintf(ver, sizeof(ver), "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);
123 ff_amf_write_field_name(&p, "type");
124 ff_amf_write_string(&p, "nonprivate");
125 }
9fd6b843
KS
126 ff_amf_write_field_name(&p, "flashVer");
127 ff_amf_write_string(&p, ver);
128 ff_amf_write_field_name(&p, "tcUrl");
129 ff_amf_write_string(&p, tcurl);
6bf22e18 130 if (rt->is_input) {
c7240611
KS
131 ff_amf_write_field_name(&p, "fpad");
132 ff_amf_write_bool(&p, 0);
133 ff_amf_write_field_name(&p, "capabilities");
134 ff_amf_write_number(&p, 15.0);
135 ff_amf_write_field_name(&p, "audioCodecs");
136 ff_amf_write_number(&p, 1639.0);
137 ff_amf_write_field_name(&p, "videoCodecs");
138 ff_amf_write_number(&p, 252.0);
139 ff_amf_write_field_name(&p, "videoFunction");
140 ff_amf_write_number(&p, 1.0);
6bf22e18 141 }
9fd6b843
KS
142 ff_amf_write_object_end(&p);
143
144 pkt.data_size = p - pkt.data;
145
146 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
f8caa544 147 ff_rtmp_packet_destroy(&pkt);
9fd6b843
KS
148}
149
150/**
6bf22e18
S
151 * Generates 'releaseStream' call and sends it to the server. It should make
152 * the server release some channel for media streams.
153 */
154static void gen_release_stream(URLContext *s, RTMPContext *rt)
155{
156 RTMPPacket pkt;
157 uint8_t *p;
158
159 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
160 29 + strlen(rt->playpath));
161
162 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Releasing stream...\n");
163 p = pkt.data;
164 ff_amf_write_string(&p, "releaseStream");
165 ff_amf_write_number(&p, 2.0);
166 ff_amf_write_null(&p);
167 ff_amf_write_string(&p, rt->playpath);
168
169 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
170 ff_rtmp_packet_destroy(&pkt);
171}
172
173/**
174 * Generates 'FCPublish' call and sends it to the server. It should make
175 * the server preapare for receiving media streams.
176 */
177static void gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
178{
179 RTMPPacket pkt;
180 uint8_t *p;
181
182 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
183 25 + strlen(rt->playpath));
184
185 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "FCPublish stream...\n");
186 p = pkt.data;
187 ff_amf_write_string(&p, "FCPublish");
188 ff_amf_write_number(&p, 3.0);
189 ff_amf_write_null(&p);
190 ff_amf_write_string(&p, rt->playpath);
191
192 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
193 ff_rtmp_packet_destroy(&pkt);
194}
195
196/**
197 * Generates 'FCUnpublish' call and sends it to the server. It should make
198 * the server destroy stream.
199 */
200static void gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
201{
202 RTMPPacket pkt;
203 uint8_t *p;
204
205 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
206 27 + strlen(rt->playpath));
207
208 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "UnPublishing stream...\n");
209 p = pkt.data;
210 ff_amf_write_string(&p, "FCUnpublish");
211 ff_amf_write_number(&p, 5.0);
212 ff_amf_write_null(&p);
213 ff_amf_write_string(&p, rt->playpath);
214
215 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
216 ff_rtmp_packet_destroy(&pkt);
217}
218
219/**
9fd6b843
KS
220 * Generates 'createStream' call and sends it to the server. It should make
221 * the server allocate some channel for media streams.
222 */
223static void gen_create_stream(URLContext *s, RTMPContext *rt)
224{
225 RTMPPacket pkt;
226 uint8_t *p;
227
228 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Creating stream...\n");
31da5966 229 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 25);
9fd6b843
KS
230
231 p = pkt.data;
232 ff_amf_write_string(&p, "createStream");
6bf22e18
S
233 ff_amf_write_number(&p, rt->is_input ? 3.0 : 4.0);
234 ff_amf_write_null(&p);
235
236 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
237 ff_rtmp_packet_destroy(&pkt);
238}
239
240
241/**
242 * Generates 'deleteStream' call and sends it to the server. It should make
243 * the server remove some channel for media streams.
244 */
245static void gen_delete_stream(URLContext *s, RTMPContext *rt)
246{
247 RTMPPacket pkt;
248 uint8_t *p;
249
250 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Deleting stream...\n");
251 ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 34);
252
253 p = pkt.data;
254 ff_amf_write_string(&p, "deleteStream");
255 ff_amf_write_number(&p, 0.0);
9fd6b843 256 ff_amf_write_null(&p);
6bf22e18 257 ff_amf_write_number(&p, rt->main_channel_id);
9fd6b843
KS
258
259 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
260 ff_rtmp_packet_destroy(&pkt);
261}
262
263/**
264 * Generates 'play' call and sends it to the server, then pings the server
265 * to start actual playing.
266 */
267static void gen_play(URLContext *s, RTMPContext *rt)
268{
269 RTMPPacket pkt;
270 uint8_t *p;
271
272 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
273 ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0,
f836fa17 274 20 + strlen(rt->playpath));
9fd6b843
KS
275 pkt.extra = rt->main_channel_id;
276
277 p = pkt.data;
278 ff_amf_write_string(&p, "play");
279 ff_amf_write_number(&p, 0.0);
280 ff_amf_write_null(&p);
281 ff_amf_write_string(&p, rt->playpath);
9fd6b843
KS
282
283 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
284 ff_rtmp_packet_destroy(&pkt);
285
286 // set client buffer time disguised in ping packet
287 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10);
288
289 p = pkt.data;
290 bytestream_put_be16(&p, 3);
291 bytestream_put_be32(&p, 1);
292 bytestream_put_be32(&p, 256); //TODO: what is a good value here?
293
294 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
295 ff_rtmp_packet_destroy(&pkt);
296}
297
298/**
6bf22e18
S
299 * Generates 'publish' call and sends it to the server.
300 */
301static void gen_publish(URLContext *s, RTMPContext *rt)
302{
303 RTMPPacket pkt;
304 uint8_t *p;
305
306 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
307 ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE, 0,
308 30 + strlen(rt->playpath));
309 pkt.extra = rt->main_channel_id;
310
311 p = pkt.data;
312 ff_amf_write_string(&p, "publish");
313 ff_amf_write_number(&p, 0.0);
314 ff_amf_write_null(&p);
315 ff_amf_write_string(&p, rt->playpath);
316 ff_amf_write_string(&p, "live");
317
318 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
319 ff_rtmp_packet_destroy(&pkt);
320}
321
322/**
9fd6b843
KS
323 * Generates ping reply and sends it to the server.
324 */
325static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
326{
327 RTMPPacket pkt;
328 uint8_t *p;
329
330 ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6);
331 p = pkt.data;
332 bytestream_put_be16(&p, 7);
333 bytestream_put_be32(&p, AV_RB32(ppkt->data+2) + 1);
334 ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
335 ff_rtmp_packet_destroy(&pkt);
336}
337
338//TODO: Move HMAC code somewhere. Eventually.
339#define HMAC_IPAD_VAL 0x36
340#define HMAC_OPAD_VAL 0x5C
341
342/**
343 * Calculates HMAC-SHA2 digest for RTMP handshake packets.
344 *
345 * @param src input buffer
346 * @param len input buffer length (should be 1536)
347 * @param gap offset in buffer where 32 bytes should not be taken into account
348 * when calculating digest (since it will be used to store that digest)
349 * @param key digest key
350 * @param keylen digest key length
351 * @param dst buffer where calculated digest will be stored (32 bytes)
352 */
353static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
354 const uint8_t *key, int keylen, uint8_t *dst)
355{
356 struct AVSHA *sha;
357 uint8_t hmac_buf[64+32] = {0};
358 int i;
359
360 sha = av_mallocz(av_sha_size);
361
362 if (keylen < 64) {
363 memcpy(hmac_buf, key, keylen);
364 } else {
365 av_sha_init(sha, 256);
366 av_sha_update(sha,key, keylen);
367 av_sha_final(sha, hmac_buf);
368 }
369 for (i = 0; i < 64; i++)
370 hmac_buf[i] ^= HMAC_IPAD_VAL;
371
372 av_sha_init(sha, 256);
373 av_sha_update(sha, hmac_buf, 64);
374 if (gap <= 0) {
375 av_sha_update(sha, src, len);
376 } else { //skip 32 bytes used for storing digest
377 av_sha_update(sha, src, gap);
378 av_sha_update(sha, src + gap + 32, len - gap - 32);
379 }
380 av_sha_final(sha, hmac_buf + 64);
381
382 for (i = 0; i < 64; i++)
383 hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
384 av_sha_init(sha, 256);
385 av_sha_update(sha, hmac_buf, 64+32);
386 av_sha_final(sha, dst);
387
388 av_free(sha);
389}
390
391/**
392 * Puts HMAC-SHA2 digest of packet data (except for the bytes where this digest
393 * will be stored) into that packet.
394 *
395 * @param buf handshake data (1536 bytes)
396 * @return offset to the digest inside input data
397 */
398static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
399{
400 int i, digest_pos = 0;
401
402 for (i = 8; i < 12; i++)
403 digest_pos += buf[i];
404 digest_pos = (digest_pos % 728) + 12;
405
406 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
407 rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
408 buf + digest_pos);
409 return digest_pos;
410}
411
412/**
413 * Verifies that the received server response has the expected digest value.
414 *
415 * @param buf handshake data received from the server (1536 bytes)
416 * @param off position to search digest offset from
417 * @return 0 if digest is valid, digest position otherwise
418 */
419static int rtmp_validate_digest(uint8_t *buf, int off)
420{
421 int i, digest_pos = 0;
422 uint8_t digest[32];
423
424 for (i = 0; i < 4; i++)
425 digest_pos += buf[i + off];
426 digest_pos = (digest_pos % 728) + off + 4;
427
428 rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
429 rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
430 digest);
431 if (!memcmp(digest, buf + digest_pos, 32))
432 return digest_pos;
433 return 0;
434}
435
436/**
437 * Performs handshake with the server by means of exchanging pseudorandom data
438 * signed with HMAC-SHA2 digest.
439 *
440 * @return 0 if handshake succeeds, negative value otherwise
441 */
442static int rtmp_handshake(URLContext *s, RTMPContext *rt)
443{
444 AVLFG rnd;
445 uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
446 3, // unencrypted data
447 0, 0, 0, 0, // client uptime
448 RTMP_CLIENT_VER1,
449 RTMP_CLIENT_VER2,
450 RTMP_CLIENT_VER3,
451 RTMP_CLIENT_VER4,
452 };
453 uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
454 uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
455 int i;
456 int server_pos, client_pos;
457 uint8_t digest[32];
458
459 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Handshaking...\n");
460
461 av_lfg_init(&rnd, 0xDEADC0DE);
462 // generate handshake packet - 1536 bytes of pseudorandom data
463 for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
464 tosend[i] = av_lfg_get(&rnd) >> 24;
465 client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
466
467 url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
468 i = url_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
469 if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
470 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
471 return -1;
472 }
473 i = url_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
474 if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
475 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
476 return -1;
477 }
478
479 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
480 serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
481
6bf22e18 482 if (rt->is_input) {
c7240611 483 server_pos = rtmp_validate_digest(serverdata + 1, 772);
9fd6b843 484 if (!server_pos) {
c7240611
KS
485 server_pos = rtmp_validate_digest(serverdata + 1, 8);
486 if (!server_pos) {
487 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server response validating failed\n");
488 return -1;
489 }
9fd6b843 490 }
9fd6b843 491
c7240611
KS
492 rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
493 rtmp_server_key, sizeof(rtmp_server_key),
494 digest);
495 rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0,
496 digest, 32,
497 digest);
498 if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
499 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Signature mismatch\n");
500 return -1;
501 }
9fd6b843 502
c7240611
KS
503 for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
504 tosend[i] = av_lfg_get(&rnd) >> 24;
505 rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
506 rtmp_player_key, sizeof(rtmp_player_key),
507 digest);
508 rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
509 digest, 32,
510 tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
511
512 // write reply back to the server
513 url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
6bf22e18
S
514 } else {
515 url_write(rt->stream, serverdata+1, RTMP_HANDSHAKE_PACKET_SIZE);
516 }
517
9fd6b843
KS
518 return 0;
519}
520
521/**
522 * Parses received packet and may perform some action depending on
523 * the packet contents.
524 * @return 0 for no errors, negative values for serious errors which prevent
525 * further communications, positive values for uncritical errors
526 */
527static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
528{
529 int i, t;
530 const uint8_t *data_end = pkt->data + pkt->data_size;
531
532 switch (pkt->type) {
533 case RTMP_PT_CHUNK_SIZE:
534 if (pkt->data_size != 4) {
535 av_log(LOG_CONTEXT, AV_LOG_ERROR,
536 "Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size);
537 return -1;
538 }
6bf22e18
S
539 if (!rt->is_input)
540 ff_rtmp_packet_write(rt->stream, pkt, rt->chunk_size, rt->prev_pkt[1]);
9fd6b843
KS
541 rt->chunk_size = AV_RB32(pkt->data);
542 if (rt->chunk_size <= 0) {
543 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size);
544 return -1;
545 }
546 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size);
547 break;
548 case RTMP_PT_PING:
549 t = AV_RB16(pkt->data);
550 if (t == 6)
551 gen_pong(s, rt, pkt);
552 break;
553 case RTMP_PT_INVOKE:
554 //TODO: check for the messages sent for wrong state?
555 if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
556 uint8_t tmpstr[256];
557
558 if (!ff_amf_get_field_value(pkt->data + 9, data_end,
559 "description", tmpstr, sizeof(tmpstr)))
560 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
561 return -1;
562 } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
563 switch (rt->state) {
564 case STATE_HANDSHAKED:
6bf22e18
S
565 if (!rt->is_input) {
566 gen_release_stream(s, rt);
567 gen_fcpublish_stream(s, rt);
568 rt->state = STATE_RELEASING;
569 } else {
570 rt->state = STATE_CONNECTING;
571 }
9fd6b843 572 gen_create_stream(s, rt);
6bf22e18
S
573 break;
574 case STATE_FCPUBLISH:
9fd6b843
KS
575 rt->state = STATE_CONNECTING;
576 break;
6bf22e18
S
577 case STATE_RELEASING:
578 rt->state = STATE_FCPUBLISH;
579 /* hack for Wowza Media Server, it does not send result for
580 * releaseStream and FCPublish calls */
581 if (!pkt->data[10]) {
582 int pkt_id = (int) av_int2dbl(AV_RB64(pkt->data + 11));
583 if (pkt_id == 4)
584 rt->state = STATE_CONNECTING;
585 }
e07c92e4 586 if (rt->state != STATE_CONNECTING)
6bf22e18 587 break;
9fd6b843
KS
588 case STATE_CONNECTING:
589 //extract a number from the result
590 if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
591 av_log(LOG_CONTEXT, AV_LOG_WARNING, "Unexpected reply on connect()\n");
592 } else {
593 rt->main_channel_id = (int) av_int2dbl(AV_RB64(pkt->data + 21));
594 }
6bf22e18 595 if (rt->is_input) {
c7240611 596 gen_play(s, rt);
6bf22e18
S
597 } else {
598 gen_publish(s, rt);
599 }
9fd6b843
KS
600 rt->state = STATE_READY;
601 break;
602 }
603 } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
604 const uint8_t* ptr = pkt->data + 11;
605 uint8_t tmpstr[256];
9fd6b843
KS
606
607 for (i = 0; i < 2; i++) {
608 t = ff_amf_tag_size(ptr, data_end);
609 if (t < 0)
610 return 1;
611 ptr += t;
612 }
613 t = ff_amf_get_field_value(ptr, data_end,
614 "level", tmpstr, sizeof(tmpstr));
615 if (!t && !strcmp(tmpstr, "error")) {
616 if (!ff_amf_get_field_value(ptr, data_end,
617 "description", tmpstr, sizeof(tmpstr)))
618 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
619 return -1;
620 }
621 t = ff_amf_get_field_value(ptr, data_end,
622 "code", tmpstr, sizeof(tmpstr));
6bf22e18 623 if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING;
72b870b9
MS
624 if (!t && !strcmp(tmpstr, "NetStream.Play.Stop")) rt->state = STATE_STOPPED;
625 if (!t && !strcmp(tmpstr, "NetStream.Play.UnpublishNotify")) rt->state = STATE_STOPPED;
6bf22e18 626 if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING;
9fd6b843
KS
627 }
628 break;
629 }
630 return 0;
631}
632
633/**
634 * Interacts with the server by receiving and sending RTMP packets until
635 * there is some significant data (media data or expected status notification).
636 *
637 * @param s reading context
1d8041b3
SS
638 * @param for_header non-zero value tells function to work until it
639 * gets notification from the server that playing has been started,
640 * otherwise function will work until some media data is received (or
641 * an error happens)
9fd6b843
KS
642 * @return 0 for successful operation, negative value in case of error
643 */
644static int get_packet(URLContext *s, int for_header)
645{
646 RTMPContext *rt = s->priv_data;
647 int ret;
648
72b870b9
MS
649 if (rt->state == STATE_STOPPED)
650 return AVERROR_EOF;
651
e07c92e4 652 for (;;) {
9fd6b843
KS
653 RTMPPacket rpkt;
654 if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
655 rt->chunk_size, rt->prev_pkt[0])) != 0) {
656 if (ret > 0) {
657 return AVERROR(EAGAIN);
658 } else {
659 return AVERROR(EIO);
660 }
661 }
662
663 ret = rtmp_parse_result(s, rt, &rpkt);
664 if (ret < 0) {//serious error in current packet
665 ff_rtmp_packet_destroy(&rpkt);
666 return -1;
667 }
72b870b9
MS
668 if (rt->state == STATE_STOPPED) {
669 ff_rtmp_packet_destroy(&rpkt);
670 return AVERROR_EOF;
671 }
6bf22e18 672 if (for_header && (rt->state == STATE_PLAYING || rt->state == STATE_PUBLISHING)) {
9fd6b843
KS
673 ff_rtmp_packet_destroy(&rpkt);
674 return 0;
675 }
6bf22e18 676 if (!rpkt.data_size || !rt->is_input) {
9fd6b843
KS
677 ff_rtmp_packet_destroy(&rpkt);
678 continue;
679 }
680 if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
afbacb93 681 (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) {
9fd6b843
KS
682 uint8_t *p;
683 uint32_t ts = rpkt.timestamp;
684
9fd6b843
KS
685 // generate packet header and put data into buffer for FLV demuxer
686 rt->flv_off = 0;
687 rt->flv_size = rpkt.data_size + 15;
688 rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
689 bytestream_put_byte(&p, rpkt.type);
690 bytestream_put_be24(&p, rpkt.data_size);
691 bytestream_put_be24(&p, ts);
692 bytestream_put_byte(&p, ts >> 24);
693 bytestream_put_be24(&p, 0);
694 bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
695 bytestream_put_be32(&p, 0);
696 ff_rtmp_packet_destroy(&rpkt);
697 return 0;
698 } else if (rpkt.type == RTMP_PT_METADATA) {
699 // we got raw FLV data, make it available for FLV demuxer
700 rt->flv_off = 0;
701 rt->flv_size = rpkt.data_size;
702 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
703 memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
704 ff_rtmp_packet_destroy(&rpkt);
705 return 0;
706 }
707 ff_rtmp_packet_destroy(&rpkt);
708 }
709 return 0;
710}
711
712static int rtmp_close(URLContext *h)
713{
714 RTMPContext *rt = h->priv_data;
715
e07c92e4 716 if (!rt->is_input) {
6bf22e18
S
717 rt->flv_data = NULL;
718 if (rt->out_pkt.data_size)
719 ff_rtmp_packet_destroy(&rt->out_pkt);
615c2879
S
720 if (rt->state > STATE_FCPUBLISH)
721 gen_fcunpublish_stream(h, rt);
6bf22e18 722 }
615c2879
S
723 if (rt->state > STATE_HANDSHAKED)
724 gen_delete_stream(h, rt);
6bf22e18 725
9fd6b843
KS
726 av_freep(&rt->flv_data);
727 url_close(rt->stream);
728 av_free(rt);
729 return 0;
730}
731
732/**
733 * Opens RTMP connection and verifies that the stream can be played.
734 *
735 * URL syntax: rtmp://server[:port][/app][/playpath]
736 * where 'app' is first one or two directories in the path
737 * (e.g. /ondemand/, /flash/live/, etc.)
738 * and 'playpath' is a file name (the rest of the path,
739 * may be prefixed with "mp4:")
740 */
741static int rtmp_open(URLContext *s, const char *uri, int flags)
742{
743 RTMPContext *rt;
5e9ad759 744 char proto[8], hostname[256], path[1024], *fname;
9fd6b843 745 uint8_t buf[2048];
b316991b 746 int port;
9fd6b843
KS
747 int ret;
748
9fd6b843
KS
749 rt = av_mallocz(sizeof(RTMPContext));
750 if (!rt)
751 return AVERROR(ENOMEM);
752 s->priv_data = rt;
b316991b 753 rt->is_input = !(flags & URL_WRONLY);
9fd6b843
KS
754
755 url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
756 path, sizeof(path), s->filename);
757
758 if (port < 0)
759 port = RTMP_DEFAULT_PORT;
760 snprintf(buf, sizeof(buf), "tcp://%s:%d", hostname, port);
761
fe523958
KS
762 if (url_open(&rt->stream, buf, URL_RDWR) < 0) {
763 av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot open connection %s\n", buf);
9fd6b843 764 goto fail;
fe523958 765 }
9fd6b843 766
c7240611
KS
767 rt->state = STATE_START;
768 if (rtmp_handshake(s, rt))
769 return -1;
9fd6b843 770
c7240611
KS
771 rt->chunk_size = 128;
772 rt->state = STATE_HANDSHAKED;
773 //extract "app" part from path
774 if (!strncmp(path, "/ondemand/", 10)) {
775 fname = path + 10;
776 memcpy(rt->app, "ondemand", 9);
777 } else {
778 char *p = strchr(path + 1, '/');
779 if (!p) {
780 fname = path + 1;
781 rt->app[0] = '\0';
9fd6b843 782 } else {
c7240611
KS
783 char *c = strchr(p + 1, ':');
784 fname = strchr(p + 1, '/');
785 if (!fname || c < fname) {
786 fname = p + 1;
787 av_strlcpy(rt->app, path + 1, p - path);
9fd6b843 788 } else {
c7240611
KS
789 fname++;
790 av_strlcpy(rt->app, path + 1, fname - path - 1);
9fd6b843
KS
791 }
792 }
c7240611
KS
793 }
794 if (!strchr(fname, ':') &&
795 (!strcmp(fname + strlen(fname) - 4, ".f4v") ||
796 !strcmp(fname + strlen(fname) - 4, ".mp4"))) {
797 memcpy(rt->playpath, "mp4:", 5);
798 } else {
799 rt->playpath[0] = 0;
800 }
801 strncat(rt->playpath, fname, sizeof(rt->playpath) - 5);
9fd6b843 802
c7240611
KS
803 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
804 proto, path, rt->app, rt->playpath);
805 gen_connect(s, rt, proto, hostname, port);
9fd6b843 806
c7240611
KS
807 do {
808 ret = get_packet(s, 1);
809 } while (ret == EAGAIN);
810 if (ret < 0)
811 goto fail;
6bf22e18
S
812
813 if (rt->is_input) {
9fd6b843
KS
814 // generate FLV header for demuxer
815 rt->flv_size = 13;
816 rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
817 rt->flv_off = 0;
818 memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
6bf22e18
S
819 } else {
820 rt->flv_size = 0;
821 rt->flv_data = NULL;
822 rt->flv_off = 0;
9fd6b843
KS
823 }
824
825 s->max_packet_size = url_get_max_packet_size(rt->stream);
826 s->is_streamed = 1;
827 return 0;
828
829fail:
830 rtmp_close(s);
831 return AVERROR(EIO);
832}
833
834static int rtmp_read(URLContext *s, uint8_t *buf, int size)
835{
836 RTMPContext *rt = s->priv_data;
837 int orig_size = size;
838 int ret;
839
840 while (size > 0) {
841 int data_left = rt->flv_size - rt->flv_off;
842
843 if (data_left >= size) {
844 memcpy(buf, rt->flv_data + rt->flv_off, size);
845 rt->flv_off += size;
846 return orig_size;
847 }
848 if (data_left > 0) {
849 memcpy(buf, rt->flv_data + rt->flv_off, data_left);
850 buf += data_left;
851 size -= data_left;
852 rt->flv_off = rt->flv_size;
853 }
854 if ((ret = get_packet(s, 0)) < 0)
855 return ret;
856 }
857 return orig_size;
858}
859
860static int rtmp_write(URLContext *h, uint8_t *buf, int size)
861{
6bf22e18
S
862 RTMPContext *rt = h->priv_data;
863 int size_temp = size;
864 int pktsize, pkttype;
865 uint32_t ts;
866 const uint8_t *buf_temp = buf;
867
868 if (size < 11) {
869 av_log(LOG_CONTEXT, AV_LOG_DEBUG, "FLV packet too small %d\n", size);
870 return 0;
871 }
872
873 do {
874 if (!rt->flv_off) {
875 //skip flv header
876 if (buf_temp[0] == 'F' && buf_temp[1] == 'L' && buf_temp[2] == 'V') {
877 buf_temp += 9 + 4;
878 size_temp -= 9 + 4;
879 }
880
881 pkttype = bytestream_get_byte(&buf_temp);
882 pktsize = bytestream_get_be24(&buf_temp);
883 ts = bytestream_get_be24(&buf_temp);
884 ts |= bytestream_get_byte(&buf_temp) << 24;
885 bytestream_get_be24(&buf_temp);
886 size_temp -= 11;
887 rt->flv_size = pktsize;
888
889 //force 12bytes header
890 if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
891 pkttype == RTMP_PT_NOTIFY) {
892 if (pkttype == RTMP_PT_NOTIFY)
893 pktsize += 16;
894 rt->prev_pkt[1][RTMP_SOURCE_CHANNEL].channel_id = 0;
895 }
896
897 //this can be a big packet, it's better to send it right here
898 ff_rtmp_packet_create(&rt->out_pkt, RTMP_SOURCE_CHANNEL, pkttype, ts, pktsize);
899 rt->out_pkt.extra = rt->main_channel_id;
900 rt->flv_data = rt->out_pkt.data;
901
902 if (pkttype == RTMP_PT_NOTIFY)
903 ff_amf_write_string(&rt->flv_data, "@setDataFrame");
904 }
905
906 if (rt->flv_size - rt->flv_off > size_temp) {
907 bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, size_temp);
908 rt->flv_off += size_temp;
909 } else {
910 bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, rt->flv_size - rt->flv_off);
911 rt->flv_off += rt->flv_size - rt->flv_off;
912 }
913
914 if (rt->flv_off == rt->flv_size) {
915 bytestream_get_be32(&buf_temp);
916
917 ff_rtmp_packet_write(rt->stream, &rt->out_pkt, rt->chunk_size, rt->prev_pkt[1]);
918 ff_rtmp_packet_destroy(&rt->out_pkt);
919 rt->flv_size = 0;
920 rt->flv_off = 0;
921 }
922 } while (buf_temp - buf < size_temp);
923 return size;
9fd6b843
KS
924}
925
926URLProtocol rtmp_protocol = {
927 "rtmp",
928 rtmp_open,
929 rtmp_read,
930 rtmp_write,
931 NULL, /* seek */
932 rtmp_close,
933};