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