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