Statistics
| Branch: | Revision:

ffmpeg / libavformat / rtmpproto.c @ e6b244a3

History | View | Annotate | Download (23.1 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_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
} ClientState;
54

    
55
/** protocol handler context */
56
typedef struct RTMPContext {
57
    URLContext*   stream;                     ///< TCP stream used in interactions with RTMP server
58
    RTMPPacket    prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
59
    int           chunk_size;                 ///< size of the chunks RTMP packets are divided into
60
    char          playpath[256];              ///< path to filename to play (with possible "mp4:" prefix)
61
    ClientState   state;                      ///< current state
62
    int           main_channel_id;            ///< an additional channel ID which is used for some invocations
63
    uint8_t*      flv_data;                   ///< buffer with data for demuxer
64
    int           flv_size;                   ///< current buffer size
65
    int           flv_off;                    ///< number of bytes read from current buffer
66
} RTMPContext;
67

    
68
#define PLAYER_KEY_OPEN_PART_LEN 30   ///< length of partial key used for first client digest signing
69
/** Client key used for digest signing */
70
static const uint8_t rtmp_player_key[] = {
71
    'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
72
    'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
73

    
74
    0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
75
    0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
76
    0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
77
};
78

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

    
86
    0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
87
    0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
88
    0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
89
};
90

    
91
/**
92
 * Generates 'connect' call and sends it to the server.
93
 */
94
static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
95
                        const char *host, int port, const char *app)
96
{
97
    RTMPPacket pkt;
98
    uint8_t ver[32], *p;
99
    char tcurl[512];
100

    
101
    ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0, 4096);
102
    p = pkt.data;
103

    
104
    snprintf(tcurl, sizeof(tcurl), "%s://%s:%d/%s", proto, host, port, app);
105
    ff_amf_write_string(&p, "connect");
106
    ff_amf_write_number(&p, 1.0);
107
    ff_amf_write_object_start(&p);
108
    ff_amf_write_field_name(&p, "app");
109
    ff_amf_write_string(&p, app);
110

    
111
    snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1,
112
             RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
113
    ff_amf_write_field_name(&p, "flashVer");
114
    ff_amf_write_string(&p, ver);
115
    ff_amf_write_field_name(&p, "tcUrl");
116
    ff_amf_write_string(&p, tcurl);
117
    ff_amf_write_field_name(&p, "fpad");
118
    ff_amf_write_bool(&p, 0);
119
    ff_amf_write_field_name(&p, "capabilities");
120
    ff_amf_write_number(&p, 15.0);
121
    ff_amf_write_field_name(&p, "audioCodecs");
122
    ff_amf_write_number(&p, 1639.0);
123
    ff_amf_write_field_name(&p, "videoCodecs");
124
    ff_amf_write_number(&p, 252.0);
125
    ff_amf_write_field_name(&p, "videoFunction");
126
    ff_amf_write_number(&p, 1.0);
127
    ff_amf_write_object_end(&p);
128

    
129
    pkt.data_size = p - pkt.data;
130

    
131
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
132
}
133

    
134
/**
135
 * Generates 'createStream' call and sends it to the server. It should make
136
 * the server allocate some channel for media streams.
137
 */
138
static void gen_create_stream(URLContext *s, RTMPContext *rt)
139
{
140
    RTMPPacket pkt;
141
    uint8_t *p;
142

    
143
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Creating stream...\n");
144
    ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0, 25);
145

    
146
    p = pkt.data;
147
    ff_amf_write_string(&p, "createStream");
148
    ff_amf_write_number(&p, 3.0);
149
    ff_amf_write_null(&p);
150

    
151
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
152
    ff_rtmp_packet_destroy(&pkt);
153
}
154

    
155
/**
156
 * Generates 'play' call and sends it to the server, then pings the server
157
 * to start actual playing.
158
 */
159
static void gen_play(URLContext *s, RTMPContext *rt)
160
{
161
    RTMPPacket pkt;
162
    uint8_t *p;
163

    
164
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
165
    ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0,
166
                          20 + strlen(rt->playpath));
167
    pkt.extra = rt->main_channel_id;
168

    
169
    p = pkt.data;
170
    ff_amf_write_string(&p, "play");
171
    ff_amf_write_number(&p, 0.0);
172
    ff_amf_write_null(&p);
173
    ff_amf_write_string(&p, rt->playpath);
174

    
175
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
176
    ff_rtmp_packet_destroy(&pkt);
177

    
178
    // set client buffer time disguised in ping packet
179
    ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10);
180

    
181
    p = pkt.data;
182
    bytestream_put_be16(&p, 3);
183
    bytestream_put_be32(&p, 1);
184
    bytestream_put_be32(&p, 256); //TODO: what is a good value here?
185

    
186
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
187
    ff_rtmp_packet_destroy(&pkt);
188
}
189

    
190
/**
191
 * Generates ping reply and sends it to the server.
192
 */
193
static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
194
{
195
    RTMPPacket pkt;
196
    uint8_t *p;
197

    
198
    ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6);
199
    p = pkt.data;
200
    bytestream_put_be16(&p, 7);
201
    bytestream_put_be32(&p, AV_RB32(ppkt->data+2) + 1);
202
    ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
203
    ff_rtmp_packet_destroy(&pkt);
204
}
205

    
206
//TODO: Move HMAC code somewhere. Eventually.
207
#define HMAC_IPAD_VAL 0x36
208
#define HMAC_OPAD_VAL 0x5C
209

    
210
/**
211
 * Calculates HMAC-SHA2 digest for RTMP handshake packets.
212
 *
213
 * @param src    input buffer
214
 * @param len    input buffer length (should be 1536)
215
 * @param gap    offset in buffer where 32 bytes should not be taken into account
216
 *               when calculating digest (since it will be used to store that digest)
217
 * @param key    digest key
218
 * @param keylen digest key length
219
 * @param dst    buffer where calculated digest will be stored (32 bytes)
220
 */
221
static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
222
                             const uint8_t *key, int keylen, uint8_t *dst)
223
{
224
    struct AVSHA *sha;
225
    uint8_t hmac_buf[64+32] = {0};
226
    int i;
227

    
228
    sha = av_mallocz(av_sha_size);
229

    
230
    if (keylen < 64) {
231
        memcpy(hmac_buf, key, keylen);
232
    } else {
233
        av_sha_init(sha, 256);
234
        av_sha_update(sha,key, keylen);
235
        av_sha_final(sha, hmac_buf);
236
    }
237
    for (i = 0; i < 64; i++)
238
        hmac_buf[i] ^= HMAC_IPAD_VAL;
239

    
240
    av_sha_init(sha, 256);
241
    av_sha_update(sha, hmac_buf, 64);
242
    if (gap <= 0) {
243
        av_sha_update(sha, src, len);
244
    } else { //skip 32 bytes used for storing digest
245
        av_sha_update(sha, src, gap);
246
        av_sha_update(sha, src + gap + 32, len - gap - 32);
247
    }
248
    av_sha_final(sha, hmac_buf + 64);
249

    
250
    for (i = 0; i < 64; i++)
251
        hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
252
    av_sha_init(sha, 256);
253
    av_sha_update(sha, hmac_buf, 64+32);
254
    av_sha_final(sha, dst);
255

    
256
    av_free(sha);
257
}
258

    
259
/**
260
 * Puts HMAC-SHA2 digest of packet data (except for the bytes where this digest
261
 * will be stored) into that packet.
262
 *
263
 * @param buf handshake data (1536 bytes)
264
 * @return offset to the digest inside input data
265
 */
266
static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
267
{
268
    int i, digest_pos = 0;
269

    
270
    for (i = 8; i < 12; i++)
271
        digest_pos += buf[i];
272
    digest_pos = (digest_pos % 728) + 12;
273

    
274
    rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
275
                     rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
276
                     buf + digest_pos);
277
    return digest_pos;
278
}
279

    
280
/**
281
 * Verifies that the received server response has the expected digest value.
282
 *
283
 * @param buf handshake data received from the server (1536 bytes)
284
 * @param off position to search digest offset from
285
 * @return 0 if digest is valid, digest position otherwise
286
 */
287
static int rtmp_validate_digest(uint8_t *buf, int off)
288
{
289
    int i, digest_pos = 0;
290
    uint8_t digest[32];
291

    
292
    for (i = 0; i < 4; i++)
293
        digest_pos += buf[i + off];
294
    digest_pos = (digest_pos % 728) + off + 4;
295

    
296
    rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
297
                     rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
298
                     digest);
299
    if (!memcmp(digest, buf + digest_pos, 32))
300
        return digest_pos;
301
    return 0;
302
}
303

    
304
/**
305
 * Performs handshake with the server by means of exchanging pseudorandom data
306
 * signed with HMAC-SHA2 digest.
307
 *
308
 * @return 0 if handshake succeeds, negative value otherwise
309
 */
310
static int rtmp_handshake(URLContext *s, RTMPContext *rt)
311
{
312
    AVLFG rnd;
313
    uint8_t tosend    [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
314
        3,                // unencrypted data
315
        0, 0, 0, 0,       // client uptime
316
        RTMP_CLIENT_VER1,
317
        RTMP_CLIENT_VER2,
318
        RTMP_CLIENT_VER3,
319
        RTMP_CLIENT_VER4,
320
    };
321
    uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
322
    uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
323
    int i;
324
    int server_pos, client_pos;
325
    uint8_t digest[32];
326

    
327
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Handshaking...\n");
328

    
329
    av_lfg_init(&rnd, 0xDEADC0DE);
330
    // generate handshake packet - 1536 bytes of pseudorandom data
331
    for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
332
        tosend[i] = av_lfg_get(&rnd) >> 24;
333
    client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
334

    
335
    url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
336
    i = url_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
337
    if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
338
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
339
        return -1;
340
    }
341
    i = url_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
342
    if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
343
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
344
        return -1;
345
    }
346

    
347
    av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
348
           serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
349

    
350
    server_pos = rtmp_validate_digest(serverdata + 1, 772);
351
    if (!server_pos) {
352
        server_pos = rtmp_validate_digest(serverdata + 1, 8);
353
        if (!server_pos) {
354
            av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server response validating failed\n");
355
            return -1;
356
        }
357
    }
358

    
359
    rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
360
                     rtmp_server_key, sizeof(rtmp_server_key),
361
                     digest);
362
    rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0,
363
                     digest, 32,
364
                     digest);
365
    if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
366
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "Signature mismatch\n");
367
        return -1;
368
    }
369

    
370
    for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
371
        tosend[i] = av_lfg_get(&rnd) >> 24;
372
    rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
373
                     rtmp_player_key, sizeof(rtmp_player_key),
374
                     digest);
375
    rtmp_calc_digest(tosend,  RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
376
                     digest, 32,
377
                     tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
378

    
379
    // write reply back to the server
380
    url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
381
    return 0;
382
}
383

    
384
/**
385
 * Parses received packet and may perform some action depending on
386
 * the packet contents.
387
 * @return 0 for no errors, negative values for serious errors which prevent
388
 *         further communications, positive values for uncritical errors
389
 */
390
static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
391
{
392
    int i, t;
393
    const uint8_t *data_end = pkt->data + pkt->data_size;
394

    
395
    switch (pkt->type) {
396
    case RTMP_PT_CHUNK_SIZE:
397
        if (pkt->data_size != 4) {
398
            av_log(LOG_CONTEXT, AV_LOG_ERROR,
399
                   "Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size);
400
            return -1;
401
        }
402
        rt->chunk_size = AV_RB32(pkt->data);
403
        if (rt->chunk_size <= 0) {
404
            av_log(LOG_CONTEXT, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size);
405
            return -1;
406
        }
407
        av_log(LOG_CONTEXT, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size);
408
        break;
409
    case RTMP_PT_PING:
410
        t = AV_RB16(pkt->data);
411
        if (t == 6)
412
            gen_pong(s, rt, pkt);
413
        break;
414
    case RTMP_PT_INVOKE:
415
        //TODO: check for the messages sent for wrong state?
416
        if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
417
            uint8_t tmpstr[256];
418

    
419
            if (!ff_amf_get_field_value(pkt->data + 9, data_end,
420
                                        "description", tmpstr, sizeof(tmpstr)))
421
                av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
422
            return -1;
423
        } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
424
            switch (rt->state) {
425
            case STATE_HANDSHAKED:
426
                gen_create_stream(s, rt);
427
                rt->state = STATE_CONNECTING;
428
                break;
429
            case STATE_CONNECTING:
430
                //extract a number from the result
431
                if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
432
                    av_log(LOG_CONTEXT, AV_LOG_WARNING, "Unexpected reply on connect()\n");
433
                } else {
434
                    rt->main_channel_id = (int) av_int2dbl(AV_RB64(pkt->data + 21));
435
                }
436
                gen_play(s, rt);
437
                rt->state = STATE_READY;
438
                break;
439
            }
440
        } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
441
            const uint8_t* ptr = pkt->data + 11;
442
            uint8_t tmpstr[256];
443
            int t;
444

    
445
            for (i = 0; i < 2; i++) {
446
                t = ff_amf_tag_size(ptr, data_end);
447
                if (t < 0)
448
                    return 1;
449
                ptr += t;
450
            }
451
            t = ff_amf_get_field_value(ptr, data_end,
452
                                       "level", tmpstr, sizeof(tmpstr));
453
            if (!t && !strcmp(tmpstr, "error")) {
454
                if (!ff_amf_get_field_value(ptr, data_end,
455
                                            "description", tmpstr, sizeof(tmpstr)))
456
                    av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
457
                return -1;
458
            }
459
            t = ff_amf_get_field_value(ptr, data_end,
460
                                       "code", tmpstr, sizeof(tmpstr));
461
            if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) {
462
                rt->state = STATE_PLAYING;
463
                return 0;
464
            }
465
        }
466
        break;
467
    }
468
    return 0;
469
}
470

    
471
/**
472
 * Interacts with the server by receiving and sending RTMP packets until
473
 * there is some significant data (media data or expected status notification).
474
 *
475
 * @param s          reading context
476
 * @param for_header non-zero value tells function to work until it
477
 * gets notification from the server that playing has been started,
478
 * otherwise function will work until some media data is received (or
479
 * an error happens)
480
 * @return 0 for successful operation, negative value in case of error
481
 */
482
static int get_packet(URLContext *s, int for_header)
483
{
484
    RTMPContext *rt = s->priv_data;
485
    int ret;
486

    
487
    for(;;) {
488
        RTMPPacket rpkt;
489
        if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
490
                                       rt->chunk_size, rt->prev_pkt[0])) != 0) {
491
            if (ret > 0) {
492
                return AVERROR(EAGAIN);
493
            } else {
494
                return AVERROR(EIO);
495
            }
496
        }
497

    
498
        ret = rtmp_parse_result(s, rt, &rpkt);
499
        if (ret < 0) {//serious error in current packet
500
            ff_rtmp_packet_destroy(&rpkt);
501
            return -1;
502
        }
503
        if (for_header && rt->state == STATE_PLAYING) {
504
            ff_rtmp_packet_destroy(&rpkt);
505
            return 0;
506
        }
507
        if (!rpkt.data_size) {
508
            ff_rtmp_packet_destroy(&rpkt);
509
            continue;
510
        }
511
        if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
512
           (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) {
513
            uint8_t *p;
514
            uint32_t ts = rpkt.timestamp;
515

    
516
            // generate packet header and put data into buffer for FLV demuxer
517
            rt->flv_off  = 0;
518
            rt->flv_size = rpkt.data_size + 15;
519
            rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
520
            bytestream_put_byte(&p, rpkt.type);
521
            bytestream_put_be24(&p, rpkt.data_size);
522
            bytestream_put_be24(&p, ts);
523
            bytestream_put_byte(&p, ts >> 24);
524
            bytestream_put_be24(&p, 0);
525
            bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
526
            bytestream_put_be32(&p, 0);
527
            ff_rtmp_packet_destroy(&rpkt);
528
            return 0;
529
        } else if (rpkt.type == RTMP_PT_METADATA) {
530
            // we got raw FLV data, make it available for FLV demuxer
531
            rt->flv_off  = 0;
532
            rt->flv_size = rpkt.data_size;
533
            rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
534
            memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
535
            ff_rtmp_packet_destroy(&rpkt);
536
            return 0;
537
        }
538
        ff_rtmp_packet_destroy(&rpkt);
539
    }
540
    return 0;
541
}
542

    
543
static int rtmp_close(URLContext *h)
544
{
545
    RTMPContext *rt = h->priv_data;
546

    
547
    av_freep(&rt->flv_data);
548
    url_close(rt->stream);
549
    av_free(rt);
550
    return 0;
551
}
552

    
553
/**
554
 * Opens RTMP connection and verifies that the stream can be played.
555
 *
556
 * URL syntax: rtmp://server[:port][/app][/playpath]
557
 *             where 'app' is first one or two directories in the path
558
 *             (e.g. /ondemand/, /flash/live/, etc.)
559
 *             and 'playpath' is a file name (the rest of the path,
560
 *             may be prefixed with "mp4:")
561
 */
562
static int rtmp_open(URLContext *s, const char *uri, int flags)
563
{
564
    RTMPContext *rt;
565
    char proto[8], hostname[256], path[1024], app[128], *fname;
566
    uint8_t buf[2048];
567
    int port, is_input;
568
    int ret;
569

    
570
    is_input = !(flags & URL_WRONLY);
571

    
572
    rt = av_mallocz(sizeof(RTMPContext));
573
    if (!rt)
574
        return AVERROR(ENOMEM);
575
    s->priv_data = rt;
576

    
577
    url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
578
              path, sizeof(path), s->filename);
579

    
580
    if (port < 0)
581
        port = RTMP_DEFAULT_PORT;
582
    snprintf(buf, sizeof(buf), "tcp://%s:%d", hostname, port);
583

    
584
    if (url_open(&rt->stream, buf, URL_RDWR) < 0) {
585
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot open connection %s\n", buf);
586
        goto fail;
587
    }
588

    
589
    if (!is_input) {
590
        av_log(LOG_CONTEXT, AV_LOG_ERROR, "RTMP output is not supported yet.\n");
591
        goto fail;
592
    } else {
593
        rt->state = STATE_START;
594
        if (rtmp_handshake(s, rt))
595
            return -1;
596

    
597
        rt->chunk_size = 128;
598
        rt->state = STATE_HANDSHAKED;
599
        //extract "app" part from path
600
        if (!strncmp(path, "/ondemand/", 10)) {
601
            fname = path + 10;
602
            memcpy(app, "ondemand", 9);
603
        } else {
604
            char *p = strchr(path + 1, '/');
605
            if (!p) {
606
                fname = path + 1;
607
                app[0] = '\0';
608
            } else {
609
                char *c = strchr(p + 1, ':');
610
                fname = strchr(p + 1, '/');
611
                if (!fname || c < fname) {
612
                    fname = p + 1;
613
                    av_strlcpy(app, path + 1, p - path);
614
                } else {
615
                    fname++;
616
                    av_strlcpy(app, path + 1, fname - path - 1);
617
                }
618
            }
619
        }
620
        if (!strchr(fname, ':') &&
621
            (!strcmp(fname + strlen(fname) - 4, ".f4v") ||
622
             !strcmp(fname + strlen(fname) - 4, ".mp4"))) {
623
            memcpy(rt->playpath, "mp4:", 5);
624
        } else {
625
            rt->playpath[0] = 0;
626
        }
627
        strncat(rt->playpath, fname, sizeof(rt->playpath) - 5);
628

    
629
        av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
630
               proto, path, app, rt->playpath);
631
        gen_connect(s, rt, proto, hostname, port, app);
632

    
633
        do {
634
            ret = get_packet(s, 1);
635
        } while (ret == EAGAIN);
636
        if (ret < 0)
637
            goto fail;
638
        // generate FLV header for demuxer
639
        rt->flv_size = 13;
640
        rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
641
        rt->flv_off  = 0;
642
        memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
643
    }
644

    
645
    s->max_packet_size = url_get_max_packet_size(rt->stream);
646
    s->is_streamed     = 1;
647
    return 0;
648

    
649
fail:
650
    rtmp_close(s);
651
    return AVERROR(EIO);
652
}
653

    
654
static int rtmp_read(URLContext *s, uint8_t *buf, int size)
655
{
656
    RTMPContext *rt = s->priv_data;
657
    int orig_size = size;
658
    int ret;
659

    
660
    while (size > 0) {
661
        int data_left = rt->flv_size - rt->flv_off;
662

    
663
        if (data_left >= size) {
664
            memcpy(buf, rt->flv_data + rt->flv_off, size);
665
            rt->flv_off += size;
666
            return orig_size;
667
        }
668
        if (data_left > 0) {
669
            memcpy(buf, rt->flv_data + rt->flv_off, data_left);
670
            buf  += data_left;
671
            size -= data_left;
672
            rt->flv_off = rt->flv_size;
673
        }
674
        if ((ret = get_packet(s, 0)) < 0)
675
           return ret;
676
    }
677
    return orig_size;
678
}
679

    
680
static int rtmp_write(URLContext *h, uint8_t *buf, int size)
681
{
682
    return 0;
683
}
684

    
685
URLProtocol rtmp_protocol = {
686
    "rtmp",
687
    rtmp_open,
688
    rtmp_read,
689
    rtmp_write,
690
    NULL, /* seek */
691
    rtmp_close,
692
};