Statistics
| Branch: | Revision:

ffmpeg / libavformat / rtmpproto.c @ e07c92e4

History | View | Annotate | Download (31 KB)

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 */
47
typedef enum {
48
    STATE_START,      ///< client has not done anything yet
49
    STATE_HANDSHAKED, ///< client has performed handshake
50
    STATE_RELEASING,  ///< client releasing stream before publish it (for output)
51
    STATE_FCPUBLISH,  ///< client FCPublishing stream (for output)
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
55
    STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output)
56
} ClientState;
57

    
58
/** protocol handler context */
59
typedef struct RTMPContext {
60
    URLContext*   stream;                     ///< TCP stream used in interactions with RTMP server
61
    RTMPPacket    prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
62
    int           chunk_size;                 ///< size of the chunks RTMP packets are divided into
63
    int           is_input;                   ///< input/output flag
64
    char          playpath[256];              ///< path to filename to play (with possible "mp4:" prefix)
65
    char          app[128];                   ///< application
66
    ClientState   state;                      ///< current state
67
    int           main_channel_id;            ///< an additional channel ID which is used for some invocations
68
    uint8_t*      flv_data;                   ///< buffer with data for demuxer
69
    int           flv_size;                   ///< current buffer size
70
    int           flv_off;                    ///< number of bytes read from current buffer
71
    RTMPPacket    out_pkt;                    ///< rtmp packet, created from flv a/v or metadata (for output)
72
} RTMPContext;
73

    
74
#define PLAYER_KEY_OPEN_PART_LEN 30   ///< length of partial key used for first client digest signing
75
/** Client key used for digest signing */
76
static const uint8_t rtmp_player_key[] = {
77
    'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
78
    'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
79

    
80
    0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
81
    0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
82
    0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
83
};
84

    
85
#define SERVER_KEY_OPEN_PART_LEN 36   ///< length of partial key used for first server digest signing
86
/** Key used for RTMP server digest signing */
87
static const uint8_t rtmp_server_key[] = {
88
    'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
89
    'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
90
    'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',
91

    
92
    0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
93
    0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
94
    0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
95
};
96

    
97
/**
98
 * Generates 'connect' call and sends it to the server.
99
 */
100
static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
101
                        const char *host, int port)
102
{
103
    RTMPPacket pkt;
104
    uint8_t ver[64], *p;
105
    char tcurl[512];
106

    
107
    ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 4096);
108
    p = pkt.data;
109

    
110
    snprintf(tcurl, sizeof(tcurl), "%s://%s:%d/%s", proto, host, port, rt->app);
111
    ff_amf_write_string(&p, "connect");
112
    ff_amf_write_number(&p, 1.0);
113
    ff_amf_write_object_start(&p);
114
    ff_amf_write_field_name(&p, "app");
115
    ff_amf_write_string(&p, rt->app);
116

    
117
    if (rt->is_input) {
118
        snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1,
119
                 RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
120
    } else {
121
        snprintf(ver, sizeof(ver), "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);
122
        ff_amf_write_field_name(&p, "type");
123
        ff_amf_write_string(&p, "nonprivate");
124
    }
125
    ff_amf_write_field_name(&p, "flashVer");
126
    ff_amf_write_string(&p, ver);
127
    ff_amf_write_field_name(&p, "tcUrl");
128
    ff_amf_write_string(&p, tcurl);
129
    if (rt->is_input) {
130
        ff_amf_write_field_name(&p, "fpad");
131
        ff_amf_write_bool(&p, 0);
132
        ff_amf_write_field_name(&p, "capabilities");
133
        ff_amf_write_number(&p, 15.0);
134
        ff_amf_write_field_name(&p, "audioCodecs");
135
        ff_amf_write_number(&p, 1639.0);
136
        ff_amf_write_field_name(&p, "videoCodecs");
137
        ff_amf_write_number(&p, 252.0);
138
        ff_amf_write_field_name(&p, "videoFunction");
139
        ff_amf_write_number(&p, 1.0);
140
    }
141
    ff_amf_write_object_end(&p);
142

    
143
    pkt.data_size = p - pkt.data;
144

    
145
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
146
}
147

    
148
/**
149
 * Generates 'releaseStream' call and sends it to the server. It should make
150
 * the server release some channel for media streams.
151
 */
152
static void gen_release_stream(URLContext *s, RTMPContext *rt)
153
{
154
    RTMPPacket pkt;
155
    uint8_t *p;
156

    
157
    ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
158
                          29 + strlen(rt->playpath));
159

    
160
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Releasing stream...\n");
161
    p = pkt.data;
162
    ff_amf_write_string(&p, "releaseStream");
163
    ff_amf_write_number(&p, 2.0);
164
    ff_amf_write_null(&p);
165
    ff_amf_write_string(&p, rt->playpath);
166

    
167
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
168
    ff_rtmp_packet_destroy(&pkt);
169
}
170

    
171
/**
172
 * Generates 'FCPublish' call and sends it to the server. It should make
173
 * the server preapare for receiving media streams.
174
 */
175
static void gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
176
{
177
    RTMPPacket pkt;
178
    uint8_t *p;
179

    
180
    ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
181
                          25 + strlen(rt->playpath));
182

    
183
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "FCPublish stream...\n");
184
    p = pkt.data;
185
    ff_amf_write_string(&p, "FCPublish");
186
    ff_amf_write_number(&p, 3.0);
187
    ff_amf_write_null(&p);
188
    ff_amf_write_string(&p, rt->playpath);
189

    
190
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
191
    ff_rtmp_packet_destroy(&pkt);
192
}
193

    
194
/**
195
 * Generates 'FCUnpublish' call and sends it to the server. It should make
196
 * the server destroy stream.
197
 */
198
static void gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
199
{
200
    RTMPPacket pkt;
201
    uint8_t *p;
202

    
203
    ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0,
204
                          27 + strlen(rt->playpath));
205

    
206
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "UnPublishing stream...\n");
207
    p = pkt.data;
208
    ff_amf_write_string(&p, "FCUnpublish");
209
    ff_amf_write_number(&p, 5.0);
210
    ff_amf_write_null(&p);
211
    ff_amf_write_string(&p, rt->playpath);
212

    
213
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
214
    ff_rtmp_packet_destroy(&pkt);
215
}
216

    
217
/**
218
 * Generates 'createStream' call and sends it to the server. It should make
219
 * the server allocate some channel for media streams.
220
 */
221
static void gen_create_stream(URLContext *s, RTMPContext *rt)
222
{
223
    RTMPPacket pkt;
224
    uint8_t *p;
225

    
226
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Creating stream...\n");
227
    ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 25);
228

    
229
    p = pkt.data;
230
    ff_amf_write_string(&p, "createStream");
231
    ff_amf_write_number(&p, rt->is_input ? 3.0 : 4.0);
232
    ff_amf_write_null(&p);
233

    
234
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
235
    ff_rtmp_packet_destroy(&pkt);
236
}
237

    
238

    
239
/**
240
 * Generates 'deleteStream' call and sends it to the server. It should make
241
 * the server remove some channel for media streams.
242
 */
243
static void gen_delete_stream(URLContext *s, RTMPContext *rt)
244
{
245
    RTMPPacket pkt;
246
    uint8_t *p;
247

    
248
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Deleting stream...\n");
249
    ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE, 0, 34);
250

    
251
    p = pkt.data;
252
    ff_amf_write_string(&p, "deleteStream");
253
    ff_amf_write_number(&p, 0.0);
254
    ff_amf_write_null(&p);
255
    ff_amf_write_number(&p, rt->main_channel_id);
256

    
257
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
258
    ff_rtmp_packet_destroy(&pkt);
259
}
260

    
261
/**
262
 * Generates 'play' call and sends it to the server, then pings the server
263
 * to start actual playing.
264
 */
265
static void gen_play(URLContext *s, RTMPContext *rt)
266
{
267
    RTMPPacket pkt;
268
    uint8_t *p;
269

    
270
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
271
    ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0,
272
                          20 + strlen(rt->playpath));
273
    pkt.extra = rt->main_channel_id;
274

    
275
    p = pkt.data;
276
    ff_amf_write_string(&p, "play");
277
    ff_amf_write_number(&p, 0.0);
278
    ff_amf_write_null(&p);
279
    ff_amf_write_string(&p, rt->playpath);
280

    
281
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
282
    ff_rtmp_packet_destroy(&pkt);
283

    
284
    // set client buffer time disguised in ping packet
285
    ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10);
286

    
287
    p = pkt.data;
288
    bytestream_put_be16(&p, 3);
289
    bytestream_put_be32(&p, 1);
290
    bytestream_put_be32(&p, 256); //TODO: what is a good value here?
291

    
292
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
293
    ff_rtmp_packet_destroy(&pkt);
294
}
295

    
296
/**
297
 * Generates 'publish' call and sends it to the server.
298
 */
299
static void gen_publish(URLContext *s, RTMPContext *rt)
300
{
301
    RTMPPacket pkt;
302
    uint8_t *p;
303

    
304
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
305
    ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE, 0,
306
                          30 + strlen(rt->playpath));
307
    pkt.extra = rt->main_channel_id;
308

    
309
    p = pkt.data;
310
    ff_amf_write_string(&p, "publish");
311
    ff_amf_write_number(&p, 0.0);
312
    ff_amf_write_null(&p);
313
    ff_amf_write_string(&p, rt->playpath);
314
    ff_amf_write_string(&p, "live");
315

    
316
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
317
    ff_rtmp_packet_destroy(&pkt);
318
}
319

    
320
/**
321
 * Generates ping reply and sends it to the server.
322
 */
323
static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
324
{
325
    RTMPPacket pkt;
326
    uint8_t *p;
327

    
328
    ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6);
329
    p = pkt.data;
330
    bytestream_put_be16(&p, 7);
331
    bytestream_put_be32(&p, AV_RB32(ppkt->data+2) + 1);
332
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
333
    ff_rtmp_packet_destroy(&pkt);
334
}
335

    
336
//TODO: Move HMAC code somewhere. Eventually.
337
#define HMAC_IPAD_VAL 0x36
338
#define HMAC_OPAD_VAL 0x5C
339

    
340
/**
341
 * Calculates HMAC-SHA2 digest for RTMP handshake packets.
342
 *
343
 * @param src    input buffer
344
 * @param len    input buffer length (should be 1536)
345
 * @param gap    offset in buffer where 32 bytes should not be taken into account
346
 *               when calculating digest (since it will be used to store that digest)
347
 * @param key    digest key
348
 * @param keylen digest key length
349
 * @param dst    buffer where calculated digest will be stored (32 bytes)
350
 */
351
static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
352
                             const uint8_t *key, int keylen, uint8_t *dst)
353
{
354
    struct AVSHA *sha;
355
    uint8_t hmac_buf[64+32] = {0};
356
    int i;
357

    
358
    sha = av_mallocz(av_sha_size);
359

    
360
    if (keylen < 64) {
361
        memcpy(hmac_buf, key, keylen);
362
    } else {
363
        av_sha_init(sha, 256);
364
        av_sha_update(sha,key, keylen);
365
        av_sha_final(sha, hmac_buf);
366
    }
367
    for (i = 0; i < 64; i++)
368
        hmac_buf[i] ^= HMAC_IPAD_VAL;
369

    
370
    av_sha_init(sha, 256);
371
    av_sha_update(sha, hmac_buf, 64);
372
    if (gap <= 0) {
373
        av_sha_update(sha, src, len);
374
    } else { //skip 32 bytes used for storing digest
375
        av_sha_update(sha, src, gap);
376
        av_sha_update(sha, src + gap + 32, len - gap - 32);
377
    }
378
    av_sha_final(sha, hmac_buf + 64);
379

    
380
    for (i = 0; i < 64; i++)
381
        hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
382
    av_sha_init(sha, 256);
383
    av_sha_update(sha, hmac_buf, 64+32);
384
    av_sha_final(sha, dst);
385

    
386
    av_free(sha);
387
}
388

    
389
/**
390
 * Puts HMAC-SHA2 digest of packet data (except for the bytes where this digest
391
 * will be stored) into that packet.
392
 *
393
 * @param buf handshake data (1536 bytes)
394
 * @return offset to the digest inside input data
395
 */
396
static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
397
{
398
    int i, digest_pos = 0;
399

    
400
    for (i = 8; i < 12; i++)
401
        digest_pos += buf[i];
402
    digest_pos = (digest_pos % 728) + 12;
403

    
404
    rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
405
                     rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
406
                     buf + digest_pos);
407
    return digest_pos;
408
}
409

    
410
/**
411
 * Verifies that the received server response has the expected digest value.
412
 *
413
 * @param buf handshake data received from the server (1536 bytes)
414
 * @param off position to search digest offset from
415
 * @return 0 if digest is valid, digest position otherwise
416
 */
417
static int rtmp_validate_digest(uint8_t *buf, int off)
418
{
419
    int i, digest_pos = 0;
420
    uint8_t digest[32];
421

    
422
    for (i = 0; i < 4; i++)
423
        digest_pos += buf[i + off];
424
    digest_pos = (digest_pos % 728) + off + 4;
425

    
426
    rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
427
                     rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
428
                     digest);
429
    if (!memcmp(digest, buf + digest_pos, 32))
430
        return digest_pos;
431
    return 0;
432
}
433

    
434
/**
435
 * Performs handshake with the server by means of exchanging pseudorandom data
436
 * signed with HMAC-SHA2 digest.
437
 *
438
 * @return 0 if handshake succeeds, negative value otherwise
439
 */
440
static int rtmp_handshake(URLContext *s, RTMPContext *rt)
441
{
442
    AVLFG rnd;
443
    uint8_t tosend    [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
444
        3,                // unencrypted data
445
        0, 0, 0, 0,       // client uptime
446
        RTMP_CLIENT_VER1,
447
        RTMP_CLIENT_VER2,
448
        RTMP_CLIENT_VER3,
449
        RTMP_CLIENT_VER4,
450
    };
451
    uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
452
    uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
453
    int i;
454
    int server_pos, client_pos;
455
    uint8_t digest[32];
456

    
457
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Handshaking...\n");
458

    
459
    av_lfg_init(&rnd, 0xDEADC0DE);
460
    // generate handshake packet - 1536 bytes of pseudorandom data
461
    for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
462
        tosend[i] = av_lfg_get(&rnd) >> 24;
463
    client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
464

    
465
    url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
466
    i = url_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
467
    if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
468
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
469
        return -1;
470
    }
471
    i = url_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
472
    if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
473
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
474
        return -1;
475
    }
476

    
477
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
478
           serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
479

    
480
    if (rt->is_input) {
481
        server_pos = rtmp_validate_digest(serverdata + 1, 772);
482
        if (!server_pos) {
483
            server_pos = rtmp_validate_digest(serverdata + 1, 8);
484
            if (!server_pos) {
485
                av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server response validating failed\n");
486
                return -1;
487
            }
488
        }
489

    
490
        rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
491
                         rtmp_server_key, sizeof(rtmp_server_key),
492
                         digest);
493
        rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0,
494
                         digest, 32,
495
                         digest);
496
        if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
497
            av_log(LOG_CONTEXT, AV_LOG_ERROR, "Signature mismatch\n");
498
            return -1;
499
        }
500

    
501
        for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
502
            tosend[i] = av_lfg_get(&rnd) >> 24;
503
        rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
504
                         rtmp_player_key, sizeof(rtmp_player_key),
505
                         digest);
506
        rtmp_calc_digest(tosend,  RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
507
                         digest, 32,
508
                         tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
509

    
510
        // write reply back to the server
511
        url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
512
    } else {
513
        url_write(rt->stream, serverdata+1, RTMP_HANDSHAKE_PACKET_SIZE);
514
    }
515

    
516
    return 0;
517
}
518

    
519
/**
520
 * Parses received packet and may perform some action depending on
521
 * the packet contents.
522
 * @return 0 for no errors, negative values for serious errors which prevent
523
 *         further communications, positive values for uncritical errors
524
 */
525
static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
526
{
527
    int i, t;
528
    const uint8_t *data_end = pkt->data + pkt->data_size;
529

    
530
    switch (pkt->type) {
531
    case RTMP_PT_CHUNK_SIZE:
532
        if (pkt->data_size != 4) {
533
            av_log(LOG_CONTEXT, AV_LOG_ERROR,
534
                   "Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size);
535
            return -1;
536
        }
537
        if (!rt->is_input)
538
            ff_rtmp_packet_write(rt->stream, pkt, rt->chunk_size, rt->prev_pkt[1]);
539
        rt->chunk_size = AV_RB32(pkt->data);
540
        if (rt->chunk_size <= 0) {
541
            av_log(LOG_CONTEXT, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size);
542
            return -1;
543
        }
544
        av_log(LOG_CONTEXT, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size);
545
        break;
546
    case RTMP_PT_PING:
547
        t = AV_RB16(pkt->data);
548
        if (t == 6)
549
            gen_pong(s, rt, pkt);
550
        break;
551
    case RTMP_PT_INVOKE:
552
        //TODO: check for the messages sent for wrong state?
553
        if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
554
            uint8_t tmpstr[256];
555

    
556
            if (!ff_amf_get_field_value(pkt->data + 9, data_end,
557
                                        "description", tmpstr, sizeof(tmpstr)))
558
                av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
559
            return -1;
560
        } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
561
            switch (rt->state) {
562
            case STATE_HANDSHAKED:
563
                if (!rt->is_input) {
564
                    gen_release_stream(s, rt);
565
                    gen_fcpublish_stream(s, rt);
566
                    rt->state = STATE_RELEASING;
567
                } else {
568
                    rt->state = STATE_CONNECTING;
569
                }
570
                gen_create_stream(s, rt);
571
                break;
572
            case STATE_FCPUBLISH:
573
                rt->state = STATE_CONNECTING;
574
                break;
575
            case STATE_RELEASING:
576
                rt->state = STATE_FCPUBLISH;
577
                /* hack for Wowza Media Server, it does not send result for
578
                 * releaseStream and FCPublish calls */
579
                if (!pkt->data[10]) {
580
                    int pkt_id = (int) av_int2dbl(AV_RB64(pkt->data + 11));
581
                    if (pkt_id == 4)
582
                        rt->state = STATE_CONNECTING;
583
                }
584
                if (rt->state != STATE_CONNECTING)
585
                    break;
586
            case STATE_CONNECTING:
587
                //extract a number from the result
588
                if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
589
                    av_log(LOG_CONTEXT, AV_LOG_WARNING, "Unexpected reply on connect()\n");
590
                } else {
591
                    rt->main_channel_id = (int) av_int2dbl(AV_RB64(pkt->data + 21));
592
                }
593
                if (rt->is_input) {
594
                    gen_play(s, rt);
595
                } else {
596
                    gen_publish(s, rt);
597
                }
598
                rt->state = STATE_READY;
599
                break;
600
            }
601
        } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
602
            const uint8_t* ptr = pkt->data + 11;
603
            uint8_t tmpstr[256];
604

    
605
            for (i = 0; i < 2; i++) {
606
                t = ff_amf_tag_size(ptr, data_end);
607
                if (t < 0)
608
                    return 1;
609
                ptr += t;
610
            }
611
            t = ff_amf_get_field_value(ptr, data_end,
612
                                       "level", tmpstr, sizeof(tmpstr));
613
            if (!t && !strcmp(tmpstr, "error")) {
614
                if (!ff_amf_get_field_value(ptr, data_end,
615
                                            "description", tmpstr, sizeof(tmpstr)))
616
                    av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
617
                return -1;
618
            }
619
            t = ff_amf_get_field_value(ptr, data_end,
620
                                       "code", tmpstr, sizeof(tmpstr));
621
            if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING;
622
            if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING;
623
        }
624
        break;
625
    }
626
    return 0;
627
}
628

    
629
/**
630
 * Interacts with the server by receiving and sending RTMP packets until
631
 * there is some significant data (media data or expected status notification).
632
 *
633
 * @param s          reading context
634
 * @param for_header non-zero value tells function to work until it
635
 * gets notification from the server that playing has been started,
636
 * otherwise function will work until some media data is received (or
637
 * an error happens)
638
 * @return 0 for successful operation, negative value in case of error
639
 */
640
static int get_packet(URLContext *s, int for_header)
641
{
642
    RTMPContext *rt = s->priv_data;
643
    int ret;
644

    
645
    for (;;) {
646
        RTMPPacket rpkt;
647
        if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
648
                                       rt->chunk_size, rt->prev_pkt[0])) != 0) {
649
            if (ret > 0) {
650
                return AVERROR(EAGAIN);
651
            } else {
652
                return AVERROR(EIO);
653
            }
654
        }
655

    
656
        ret = rtmp_parse_result(s, rt, &rpkt);
657
        if (ret < 0) {//serious error in current packet
658
            ff_rtmp_packet_destroy(&rpkt);
659
            return -1;
660
        }
661
        if (for_header && (rt->state == STATE_PLAYING || rt->state == STATE_PUBLISHING)) {
662
            ff_rtmp_packet_destroy(&rpkt);
663
            return 0;
664
        }
665
        if (!rpkt.data_size || !rt->is_input) {
666
            ff_rtmp_packet_destroy(&rpkt);
667
            continue;
668
        }
669
        if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
670
           (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) {
671
            uint8_t *p;
672
            uint32_t ts = rpkt.timestamp;
673

    
674
            // generate packet header and put data into buffer for FLV demuxer
675
            rt->flv_off  = 0;
676
            rt->flv_size = rpkt.data_size + 15;
677
            rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
678
            bytestream_put_byte(&p, rpkt.type);
679
            bytestream_put_be24(&p, rpkt.data_size);
680
            bytestream_put_be24(&p, ts);
681
            bytestream_put_byte(&p, ts >> 24);
682
            bytestream_put_be24(&p, 0);
683
            bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
684
            bytestream_put_be32(&p, 0);
685
            ff_rtmp_packet_destroy(&rpkt);
686
            return 0;
687
        } else if (rpkt.type == RTMP_PT_METADATA) {
688
            // we got raw FLV data, make it available for FLV demuxer
689
            rt->flv_off  = 0;
690
            rt->flv_size = rpkt.data_size;
691
            rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
692
            memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
693
            ff_rtmp_packet_destroy(&rpkt);
694
            return 0;
695
        }
696
        ff_rtmp_packet_destroy(&rpkt);
697
    }
698
    return 0;
699
}
700

    
701
static int rtmp_close(URLContext *h)
702
{
703
    RTMPContext *rt = h->priv_data;
704

    
705
    if (!rt->is_input) {
706
        rt->flv_data = NULL;
707
        if (rt->out_pkt.data_size)
708
            ff_rtmp_packet_destroy(&rt->out_pkt);
709
        if (rt->state > STATE_FCPUBLISH)
710
            gen_fcunpublish_stream(h, rt);
711
    }
712
    if (rt->state > STATE_HANDSHAKED)
713
        gen_delete_stream(h, rt);
714

    
715
    av_freep(&rt->flv_data);
716
    url_close(rt->stream);
717
    av_free(rt);
718
    return 0;
719
}
720

    
721
/**
722
 * Opens RTMP connection and verifies that the stream can be played.
723
 *
724
 * URL syntax: rtmp://server[:port][/app][/playpath]
725
 *             where 'app' is first one or two directories in the path
726
 *             (e.g. /ondemand/, /flash/live/, etc.)
727
 *             and 'playpath' is a file name (the rest of the path,
728
 *             may be prefixed with "mp4:")
729
 */
730
static int rtmp_open(URLContext *s, const char *uri, int flags)
731
{
732
    RTMPContext *rt;
733
    char proto[8], hostname[256], path[1024], *fname;
734
    uint8_t buf[2048];
735
    int port;
736
    int ret;
737

    
738
    rt = av_mallocz(sizeof(RTMPContext));
739
    if (!rt)
740
        return AVERROR(ENOMEM);
741
    s->priv_data = rt;
742
    rt->is_input = !(flags & URL_WRONLY);
743

    
744
    url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
745
              path, sizeof(path), s->filename);
746

    
747
    if (port < 0)
748
        port = RTMP_DEFAULT_PORT;
749
    snprintf(buf, sizeof(buf), "tcp://%s:%d", hostname, port);
750

    
751
    if (url_open(&rt->stream, buf, URL_RDWR) < 0) {
752
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot open connection %s\n", buf);
753
        goto fail;
754
    }
755

    
756
    rt->state = STATE_START;
757
    if (rtmp_handshake(s, rt))
758
        return -1;
759

    
760
    rt->chunk_size = 128;
761
    rt->state = STATE_HANDSHAKED;
762
    //extract "app" part from path
763
    if (!strncmp(path, "/ondemand/", 10)) {
764
        fname = path + 10;
765
        memcpy(rt->app, "ondemand", 9);
766
    } else {
767
        char *p = strchr(path + 1, '/');
768
        if (!p) {
769
            fname = path + 1;
770
            rt->app[0] = '\0';
771
        } else {
772
            char *c = strchr(p + 1, ':');
773
            fname = strchr(p + 1, '/');
774
            if (!fname || c < fname) {
775
                fname = p + 1;
776
                av_strlcpy(rt->app, path + 1, p - path);
777
            } else {
778
                fname++;
779
                av_strlcpy(rt->app, path + 1, fname - path - 1);
780
            }
781
        }
782
    }
783
    if (!strchr(fname, ':') &&
784
        (!strcmp(fname + strlen(fname) - 4, ".f4v") ||
785
         !strcmp(fname + strlen(fname) - 4, ".mp4"))) {
786
        memcpy(rt->playpath, "mp4:", 5);
787
    } else {
788
        rt->playpath[0] = 0;
789
    }
790
    strncat(rt->playpath, fname, sizeof(rt->playpath) - 5);
791

    
792
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
793
           proto, path, rt->app, rt->playpath);
794
    gen_connect(s, rt, proto, hostname, port);
795

    
796
    do {
797
        ret = get_packet(s, 1);
798
    } while (ret == EAGAIN);
799
    if (ret < 0)
800
        goto fail;
801

    
802
    if (rt->is_input) {
803
        // generate FLV header for demuxer
804
        rt->flv_size = 13;
805
        rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
806
        rt->flv_off  = 0;
807
        memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
808
    } else {
809
        rt->flv_size = 0;
810
        rt->flv_data = NULL;
811
        rt->flv_off  = 0;
812
    }
813

    
814
    s->max_packet_size = url_get_max_packet_size(rt->stream);
815
    s->is_streamed     = 1;
816
    return 0;
817

    
818
fail:
819
    rtmp_close(s);
820
    return AVERROR(EIO);
821
}
822

    
823
static int rtmp_read(URLContext *s, uint8_t *buf, int size)
824
{
825
    RTMPContext *rt = s->priv_data;
826
    int orig_size = size;
827
    int ret;
828

    
829
    while (size > 0) {
830
        int data_left = rt->flv_size - rt->flv_off;
831

    
832
        if (data_left >= size) {
833
            memcpy(buf, rt->flv_data + rt->flv_off, size);
834
            rt->flv_off += size;
835
            return orig_size;
836
        }
837
        if (data_left > 0) {
838
            memcpy(buf, rt->flv_data + rt->flv_off, data_left);
839
            buf  += data_left;
840
            size -= data_left;
841
            rt->flv_off = rt->flv_size;
842
        }
843
        if ((ret = get_packet(s, 0)) < 0)
844
           return ret;
845
    }
846
    return orig_size;
847
}
848

    
849
static int rtmp_write(URLContext *h, uint8_t *buf, int size)
850
{
851
    RTMPContext *rt = h->priv_data;
852
    int size_temp = size;
853
    int pktsize, pkttype;
854
    uint32_t ts;
855
    const uint8_t *buf_temp = buf;
856

    
857
    if (size < 11) {
858
        av_log(LOG_CONTEXT, AV_LOG_DEBUG, "FLV packet too small %d\n", size);
859
        return 0;
860
    }
861

    
862
    do {
863
        if (!rt->flv_off) {
864
            //skip flv header
865
            if (buf_temp[0] == 'F' && buf_temp[1] == 'L' && buf_temp[2] == 'V') {
866
                buf_temp += 9 + 4;
867
                size_temp -= 9 + 4;
868
            }
869

    
870
            pkttype = bytestream_get_byte(&buf_temp);
871
            pktsize = bytestream_get_be24(&buf_temp);
872
            ts = bytestream_get_be24(&buf_temp);
873
            ts |= bytestream_get_byte(&buf_temp) << 24;
874
            bytestream_get_be24(&buf_temp);
875
            size_temp -= 11;
876
            rt->flv_size = pktsize;
877

    
878
            //force 12bytes header
879
            if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
880
                pkttype == RTMP_PT_NOTIFY) {
881
                if (pkttype == RTMP_PT_NOTIFY)
882
                    pktsize += 16;
883
                rt->prev_pkt[1][RTMP_SOURCE_CHANNEL].channel_id = 0;
884
            }
885

    
886
            //this can be a big packet, it's better to send it right here
887
            ff_rtmp_packet_create(&rt->out_pkt, RTMP_SOURCE_CHANNEL, pkttype, ts, pktsize);
888
            rt->out_pkt.extra = rt->main_channel_id;
889
            rt->flv_data = rt->out_pkt.data;
890

    
891
            if (pkttype == RTMP_PT_NOTIFY)
892
                ff_amf_write_string(&rt->flv_data, "@setDataFrame");
893
        }
894

    
895
        if (rt->flv_size - rt->flv_off > size_temp) {
896
            bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, size_temp);
897
            rt->flv_off += size_temp;
898
        } else {
899
            bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, rt->flv_size - rt->flv_off);
900
            rt->flv_off += rt->flv_size - rt->flv_off;
901
        }
902

    
903
        if (rt->flv_off == rt->flv_size) {
904
            bytestream_get_be32(&buf_temp);
905

    
906
            ff_rtmp_packet_write(rt->stream, &rt->out_pkt, rt->chunk_size, rt->prev_pkt[1]);
907
            ff_rtmp_packet_destroy(&rt->out_pkt);
908
            rt->flv_size = 0;
909
            rt->flv_off = 0;
910
        }
911
    } while (buf_temp - buf < size_temp);
912
    return size;
913
}
914

    
915
URLProtocol rtmp_protocol = {
916
    "rtmp",
917
    rtmp_open,
918
    rtmp_read,
919
    rtmp_write,
920
    NULL, /* seek */
921
    rtmp_close,
922
};