1
0
mirror of https://github.com/FFmpeg/FFmpeg.git synced 2024-12-23 12:43:46 +02:00

RTMP protocol support (as a client)

Originally committed as revision 19556 to svn://svn.ffmpeg.org/ffmpeg/trunk
This commit is contained in:
Kostya Shishkov 2009-07-31 06:49:36 +00:00
parent abbe30ad89
commit 9fd6b84360
9 changed files with 1219 additions and 1 deletions

View File

@ -29,6 +29,7 @@ version <next>:
- nonfree libamr support for AMR-NB/WB decoding/encoding removed
- Experimental AAC encoder
- RTP depacketization of ASF and RTSP from WMS servers
- RTMP support in libavformat

View File

@ -195,6 +195,7 @@ library:
@item RL2 @tab @tab X
@tab Audio and video format used in some games by Entertainment Software Partners.
@item RPL/ARMovie @tab @tab X
@item RTMP @tab @tab X
@item RTP @tab @tab X
@item RTSP @tab @tab X
@item SDP @tab @tab X

View File

@ -237,6 +237,7 @@ OBJS-$(CONFIG_FILE_PROTOCOL) += file.o
OBJS-$(CONFIG_GOPHER_PROTOCOL) += gopher.o
OBJS-$(CONFIG_HTTP_PROTOCOL) += http.o
OBJS-$(CONFIG_PIPE_PROTOCOL) += file.o
OBJS-$(CONFIG_RTMP_PROTOCOL) += rtmpproto.o rtmppkt.o
OBJS-$(CONFIG_RTP_PROTOCOL) += rtpproto.o
OBJS-$(CONFIG_TCP_PROTOCOL) += tcp.o
OBJS-$(CONFIG_UDP_PROTOCOL) += udp.o

View File

@ -209,6 +209,7 @@ void av_register_all(void)
REGISTER_PROTOCOL (GOPHER, gopher);
REGISTER_PROTOCOL (HTTP, http);
REGISTER_PROTOCOL (PIPE, pipe);
REGISTER_PROTOCOL (RTMP, rtmp);
REGISTER_PROTOCOL (RTP, rtp);
REGISTER_PROTOCOL (TCP, tcp);
REGISTER_PROTOCOL (UDP, udp);

View File

@ -22,7 +22,7 @@
#define AVFORMAT_AVFORMAT_H
#define LIBAVFORMAT_VERSION_MAJOR 52
#define LIBAVFORMAT_VERSION_MINOR 36
#define LIBAVFORMAT_VERSION_MINOR 37
#define LIBAVFORMAT_VERSION_MICRO 0
#define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \

42
libavformat/rtmp.h Normal file
View File

@ -0,0 +1,42 @@
/*
* RTMP definitions
* Copyright (c) 2009 Kostya Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVFORMAT_RTMP_H
#define AVFORMAT_RTMP_H
#include "avformat.h"
#define RTMP_DEFAULT_PORT 1935
#define RTMP_HANDSHAKE_PACKET_SIZE 1536
/**
* emulated Flash client version - 9.0.124.2 on Linux
* @{
*/
#define RTMP_CLIENT_PLATFORM "LNX"
#define RTMP_CLIENT_VER1 9
#define RTMP_CLIENT_VER2 0
#define RTMP_CLIENT_VER3 124
#define RTMP_CLIENT_VER4 2
/** @} */ //version defines
#endif /* AVFORMAT_RTMP_H */

265
libavformat/rtmppkt.c Normal file
View File

@ -0,0 +1,265 @@
/*
* RTMP input format
* Copyright (c) 2009 Kostya Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavcodec/bytestream.h"
#include "libavutil/avstring.h"
#include "avformat.h"
#include "rtmppkt.h"
#include "flv.h"
void ff_amf_write_bool(uint8_t **dst, int val)
{
bytestream_put_byte(dst, AMF_DATA_TYPE_BOOL);
bytestream_put_byte(dst, val);
}
void ff_amf_write_number(uint8_t **dst, double val)
{
bytestream_put_byte(dst, AMF_DATA_TYPE_NUMBER);
bytestream_put_be64(dst, av_dbl2int(val));
}
void ff_amf_write_string(uint8_t **dst, const char *str)
{
bytestream_put_byte(dst, AMF_DATA_TYPE_STRING);
bytestream_put_be16(dst, strlen(str));
bytestream_put_buffer(dst, str, strlen(str));
}
void ff_amf_write_null(uint8_t **dst)
{
bytestream_put_byte(dst, AMF_DATA_TYPE_NULL);
}
void ff_amf_write_object_start(uint8_t **dst)
{
bytestream_put_byte(dst, AMF_DATA_TYPE_OBJECT);
}
void ff_amf_write_field_name(uint8_t **dst, const char *str)
{
bytestream_put_be16(dst, strlen(str));
bytestream_put_buffer(dst, str, strlen(str));
}
void ff_amf_write_object_end(uint8_t **dst)
{
/* first two bytes are field name length = 0,
* AMF object should end with it and end marker
*/
bytestream_put_be24(dst, AMF_DATA_TYPE_OBJECT_END);
}
int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p,
int chunk_size, RTMPPacket *prev_pkt)
{
uint8_t hdr, t, buf[16];
int channel_id, timestamp, data_size, offset = 0;
uint32_t extra = 0;
uint8_t type;
if (url_read(h, &hdr, 1) != 1)
return AVERROR(EIO);
channel_id = hdr & 0x3F;
data_size = prev_pkt[channel_id].data_size;
type = prev_pkt[channel_id].type;
extra = prev_pkt[channel_id].extra;
hdr >>= 6;
if (hdr == RTMP_PS_ONEBYTE) {
//todo
return -1;
} else {
if (url_read_complete(h, buf, 3) != 3)
return AVERROR(EIO);
timestamp = AV_RB24(buf);
if (hdr != RTMP_PS_FOURBYTES) {
if (url_read_complete(h, buf, 3) != 3)
return AVERROR(EIO);
data_size = AV_RB24(buf);
if (url_read_complete(h, &type, 1) != 1)
return AVERROR(EIO);
if (hdr == RTMP_PS_TWELVEBYTES) {
if (url_read_complete(h, buf, 4) != 4)
return AVERROR(EIO);
extra = AV_RL32(buf);
}
}
}
if (ff_rtmp_packet_create(p, channel_id, type, timestamp, data_size))
return -1;
p->extra = extra;
// save history
prev_pkt[channel_id].channel_id = channel_id;
prev_pkt[channel_id].type = type;
prev_pkt[channel_id].data_size = data_size;
prev_pkt[channel_id].timestamp = timestamp;
prev_pkt[channel_id].extra = extra;
while (data_size > 0) {
int toread = FFMIN(data_size, chunk_size);
if (url_read_complete(h, p->data + offset, toread) != toread) {
ff_rtmp_packet_destroy(p);
return AVERROR(EIO);
}
data_size -= chunk_size;
offset += chunk_size;
if (data_size > 0) {
url_read_complete(h, &t, 1); //marker
if (t != (0xC0 + channel_id))
return -1;
}
}
return 0;
}
int ff_rtmp_packet_write(URLContext *h, RTMPPacket *pkt,
int chunk_size, RTMPPacket *prev_pkt)
{
uint8_t pkt_hdr[16], *p = pkt_hdr;
int mode = RTMP_PS_TWELVEBYTES;
int off = 0;
//TODO: header compression
bytestream_put_byte(&p, pkt->channel_id | (mode << 6));
if (mode != RTMP_PS_ONEBYTE) {
bytestream_put_be24(&p, pkt->timestamp);
if (mode != RTMP_PS_FOURBYTES) {
bytestream_put_be24(&p, pkt->data_size);
bytestream_put_byte(&p, pkt->type);
if (mode == RTMP_PS_TWELVEBYTES)
bytestream_put_le32(&p, pkt->extra);
}
}
url_write(h, pkt_hdr, p-pkt_hdr);
while (off < pkt->data_size) {
int towrite = FFMIN(chunk_size, pkt->data_size - off);
url_write(h, pkt->data + off, towrite);
off += towrite;
if (off < pkt->data_size) {
uint8_t marker = 0xC0 | pkt->channel_id;
url_write(h, &marker, 1);
}
}
return 0;
}
int ff_rtmp_packet_create(RTMPPacket *pkt, int channel_id, RTMPPacketType type,
int timestamp, int size)
{
pkt->data = av_malloc(size);
if (!pkt->data)
return AVERROR(ENOMEM);
pkt->data_size = size;
pkt->channel_id = channel_id;
pkt->type = type;
pkt->timestamp = timestamp;
pkt->extra = 0;
return 0;
}
void ff_rtmp_packet_destroy(RTMPPacket *pkt)
{
if (!pkt)
return;
av_freep(&pkt->data);
pkt->data_size = 0;
}
int ff_amf_tag_size(const uint8_t *data, const uint8_t *data_end)
{
const uint8_t *base = data;
if (data >= data_end)
return -1;
switch (*data++) {
case AMF_DATA_TYPE_NUMBER: return 9;
case AMF_DATA_TYPE_BOOL: return 2;
case AMF_DATA_TYPE_STRING: return 3 + AV_RB16(data);
case AMF_DATA_TYPE_LONG_STRING: return 5 + AV_RB32(data);
case AMF_DATA_TYPE_NULL: return 1;
case AMF_DATA_TYPE_ARRAY:
data += 4;
case AMF_DATA_TYPE_OBJECT:
for (;;) {
int size = bytestream_get_be16(&data);
int t;
if (!size) {
data++;
break;
}
if (data + size >= data_end || data + size < data)
return -1;
data += size;
t = ff_amf_tag_size(data, data_end);
if (t < 0 || data + t >= data_end)
return -1;
data += t;
}
return data - base;
case AMF_DATA_TYPE_OBJECT_END: return 1;
default: return -1;
}
}
int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
const uint8_t *name, uint8_t *dst, int dst_size)
{
int namelen = strlen(name);
int len;
if (data_end - data < 3)
return -1;
if (*data++ != AMF_DATA_TYPE_OBJECT)
return -1;
for (;;) {
int size = bytestream_get_be16(&data);
if (!size)
break;
if (data + size >= data_end || data + size < data)
return -1;
data += size;
if (size == namelen && !memcmp(data-size, name, namelen)) {
switch (*data++) {
case AMF_DATA_TYPE_NUMBER:
snprintf(dst, dst_size, "%g", av_int2dbl(AV_RB64(data)));
break;
case AMF_DATA_TYPE_BOOL:
snprintf(dst, dst_size, "%s", *data ? "true" : "false");
break;
case AMF_DATA_TYPE_STRING:
len = bytestream_get_be16(&data);
av_strlcpy(dst, data, FFMIN(len+1, dst_size));
break;
default:
return -1;
}
return 0;
}
len = ff_amf_tag_size(data, data_end);
if (len < 0 || data + len >= data_end || data + len < data)
return -1;
data += len;
}
return -1;
}

212
libavformat/rtmppkt.h Normal file
View File

@ -0,0 +1,212 @@
/*
* RTMP packet utilities
* Copyright (c) 2009 Kostya Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVFORMAT_RTMPPKT_H
#define AVFORMAT_RTMPPKT_H
#include "avformat.h"
/** maximum possible number of different RTMP channels */
#define RTMP_CHANNELS 64
/**
* channels used to for RTMP packets with different purposes (i.e. data, network
* control, remote procedure calls, etc.)
*/
enum RTMPChannel {
RTMP_NETWORK_CHANNEL = 2, ///< channel for network-related messages (bandwidth report, ping, etc)
RTMP_SYSTEM_CHANNEL, ///< channel for sending server control messages
RTMP_VIDEO_CHANNEL = 8, ///< channel for video data
RTMP_AUDIO_CHANNEL, ///< channel for audio data
};
/**
* known RTMP packet types
*/
typedef enum RTMPPacketType {
RTMP_PT_CHUNK_SIZE = 1, ///< chunk size change
RTMP_PT_BYTES_READ = 3, ///< number of bytes read
RTMP_PT_PING, ///< ping
RTMP_PT_SERVER_BW, ///< server bandwidth
RTMP_PT_CLIENT_BW, ///< client bandwidth
RTMP_PT_AUDIO = 8, ///< audio packet
RTMP_PT_VIDEO, ///< video packet
RTMP_PT_FLEX_STREAM = 15, ///< Flex shared stream
RTMP_PT_FLEX_OBJECT, ///< Flex shared object
RTMP_PT_FLEX_MESSAGE, ///< Flex shared message
RTMP_PT_NOTIFY, ///< some notification
RTMP_PT_SHARED_OBJ, ///< shared object
RTMP_PT_INVOKE, ///< invoke some stream action
RTMP_PT_METADATA = 22, ///< FLV metadata
} RTMPPacketType;
/**
* possible RTMP packet header sizes
*/
enum RTMPPacketSize {
RTMP_PS_TWELVEBYTES = 0, ///< packet has 12-byte header
RTMP_PS_EIGHTBYTES, ///< packet has 8-byte header
RTMP_PS_FOURBYTES, ///< packet has 4-byte header
RTMP_PS_ONEBYTE ///< packet is really a next chunk of a packet
};
/**
* structure for holding RTMP packets
*/
typedef struct RTMPPacket {
uint8_t channel_id; ///< RTMP channel ID (nothing to do with audio/video channels though)
RTMPPacketType type; ///< packet payload type
uint32_t timestamp; ///< packet full timestamp or timestamp increment to the previous one in milliseconds (latter only for media packets)
uint32_t extra; ///< probably an additional channel ID used during streaming data
uint8_t *data; ///< packet payload
int data_size; ///< packet payload size
} RTMPPacket;
/**
* Creates new RTMP packet with given attributes.
*
* @param pkt packet
* @param channel_id packet channel ID
* @param type packet type
* @param timestamp packet timestamp
* @param size packet size
* @return zero on success, negative value otherwise
*/
int ff_rtmp_packet_create(RTMPPacket *pkt, int channel_id, RTMPPacketType type,
int timestamp, int size);
/**
* Frees RTMP packet.
*
* @param pkt packet
*/
void ff_rtmp_packet_destroy(RTMPPacket *pkt);
/**
* Reads RTMP packet sent by the server.
*
* @param h reader context
* @param p packet
* @param chunk_size current chunk size
* @param prev_pkt previously read packet headers for all channels
* (may be needed for restoring incomplete packet header)
* @return zero on success, negative value otherwise
*/
int ff_rtmp_packet_read(URLContext *h, RTMPPacket *p,
int chunk_size, RTMPPacket *prev_pkt);
/**
* Sends RTMP packet to the server.
*
* @param h reader context
* @param p packet to send
* @param chunk_size current chunk size
* @param prev_pkt previously sent packet headers for all channels
* (may be used for packet header compressing)
* @return zero on success, negative value otherwise
*/
int ff_rtmp_packet_write(URLContext *h, RTMPPacket *p,
int chunk_size, RTMPPacket *prev_pkt);
/**
* @defgroup amffuncs functions used to work with AMF format (which is also used in .flv)
* @see amf_* funcs in libavformat/flvdec.c
* @{
*/
/**
* Calculates number of bytes taken by first AMF entry in data.
*
* @param data input data
* @param data_end input buffer end
* @return number of bytes used by first AMF entry
*/
int ff_amf_tag_size(const uint8_t *data, const uint8_t *data_end);
/**
* Retrieves value of given AMF object field in string form.
*
* @param data AMF object data
* @param data_end input buffer end
* @param name name of field to retrieve
* @param dst buffer for storing result
* @param dst_size output buffer size
* @return 0 if search and retrieval succeeded, negative value otherwise
*/
int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,
const uint8_t *name, uint8_t *dst, int dst_size);
/**
* Writes boolean value in AMF format to buffer.
*
* @param dst pointer to the input buffer (will be modified)
* @param val value to write
*/
void ff_amf_write_bool(uint8_t **dst, int val);
/**
* Writes number in AMF format to buffer.
*
* @param dst pointer to the input buffer (will be modified)
* @param num value to write
*/
void ff_amf_write_number(uint8_t **dst, double num);
/**
* Writes string in AMF format to buffer.
*
* @param dst pointer to the input buffer (will be modified)
* @param str string to write
*/
void ff_amf_write_string(uint8_t **dst, const char *str);
/**
* Writes AMF NULL value to buffer.
*
* @param dst pointer to the input buffer (will be modified)
*/
void ff_amf_write_null(uint8_t **dst);
/**
* Writes marker for AMF object to buffer.
*
* @param dst pointer to the input buffer (will be modified)
*/
void ff_amf_write_object_start(uint8_t **dst);
/**
* Writes string used as field name in AMF object to buffer.
*
* @param dst pointer to the input buffer (will be modified)
* @param str string to write
*/
void ff_amf_write_field_name(uint8_t **dst, const char *str);
/**
* Writes marker for end of AMF object to buffer.
*
* @param dst pointer to the input buffer (will be modified)
*/
void ff_amf_write_object_end(uint8_t **dst);
/** @} */ // AMF funcs
#endif /* AVFORMAT_RTMPPKT_H */

695
libavformat/rtmpproto.c Normal file
View File

@ -0,0 +1,695 @@
/*
* RTMP network protocol
* Copyright (c) 2009 Kostya Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file libavformat/rtmpproto.c
* RTMP protocol
*/
#include "libavcodec/bytestream.h"
#include "libavutil/avstring.h"
#include "libavutil/lfg.h"
#include "libavutil/sha.h"
#include "avformat.h"
#include "network.h"
#include "flv.h"
#include "rtmp.h"
#include "rtmppkt.h"
/* we can't use av_log() with URLContext yet... */
#if LIBAVFORMAT_VERSION_MAJOR < 53
#define LOG_CONTEXT NULL
#else
#define LOG_CONTEXT s
#endif
/** RTMP protocol handler state */
typedef enum {
STATE_START, ///< client has not done anything yet
STATE_HANDSHAKED, ///< client has performed handshake
STATE_CONNECTING, ///< client connected to server successfully
STATE_READY, ///< client has sent all needed commands and waits for server reply
STATE_PLAYING, ///< client has started receiving multimedia data from server
} ClientState;
/** protocol handler context */
typedef struct RTMPContext {
URLContext* stream; ///< TCP stream used in interactions with RTMP server
RTMPPacket prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
int chunk_size; ///< size of the chunks RTMP packets are divided into
char playpath[256]; ///< path to filename to play (with possible "mp4:" prefix)
ClientState state; ///< current state
int main_channel_id; ///< an additional channel ID which is used for some invocations
uint8_t* flv_data; ///< buffer with data for demuxer
int flv_size; ///< current buffer size
int flv_off; ///< number of bytes read from current buffer
uint32_t video_ts; ///< current video timestamp in milliseconds
uint32_t audio_ts; ///< current audio timestamp in milliseconds
} RTMPContext;
#define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing
/** Client key used for digest signing */
static const uint8_t rtmp_player_key[] = {
'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
};
#define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing
/** Key used for RTMP server digest signing */
static const uint8_t rtmp_server_key[] = {
'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',
0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
};
/**
* Generates 'connect' call and sends it to the server.
*/
static void gen_connect(URLContext *s, RTMPContext *rt, const char *proto,
const char *host, int port, const char *app)
{
RTMPPacket pkt;
uint8_t ver[32], *p;
char tcurl[512];
ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0, 4096);
p = pkt.data;
snprintf(tcurl, sizeof(tcurl), "%s://%s:%d/%s", proto, host, port, app);
ff_amf_write_string(&p, "connect");
ff_amf_write_number(&p, 1.0);
ff_amf_write_object_start(&p);
ff_amf_write_field_name(&p, "app");
ff_amf_write_string(&p, app);
snprintf(ver, sizeof(ver), "%s %d,%d,%d,%d", RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1,
RTMP_CLIENT_VER2, RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
ff_amf_write_field_name(&p, "flashVer");
ff_amf_write_string(&p, ver);
ff_amf_write_field_name(&p, "tcUrl");
ff_amf_write_string(&p, tcurl);
ff_amf_write_field_name(&p, "fpad");
ff_amf_write_bool(&p, 0);
ff_amf_write_field_name(&p, "capabilities");
ff_amf_write_number(&p, 15.0);
ff_amf_write_field_name(&p, "audioCodecs");
ff_amf_write_number(&p, 1639.0);
ff_amf_write_field_name(&p, "videoCodecs");
ff_amf_write_number(&p, 252.0);
ff_amf_write_field_name(&p, "videoFunction");
ff_amf_write_number(&p, 1.0);
ff_amf_write_object_end(&p);
pkt.data_size = p - pkt.data;
ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
}
/**
* Generates 'createStream' call and sends it to the server. It should make
* the server allocate some channel for media streams.
*/
static void gen_create_stream(URLContext *s, RTMPContext *rt)
{
RTMPPacket pkt;
uint8_t *p;
av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Creating stream...\n");
ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0, 25);
p = pkt.data;
ff_amf_write_string(&p, "createStream");
ff_amf_write_number(&p, 3.0);
ff_amf_write_null(&p);
ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
ff_rtmp_packet_destroy(&pkt);
}
/**
* Generates 'play' call and sends it to the server, then pings the server
* to start actual playing.
*/
static void gen_play(URLContext *s, RTMPContext *rt)
{
RTMPPacket pkt;
uint8_t *p;
av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE, 0,
29 + strlen(rt->playpath));
pkt.extra = rt->main_channel_id;
p = pkt.data;
ff_amf_write_string(&p, "play");
ff_amf_write_number(&p, 0.0);
ff_amf_write_null(&p);
ff_amf_write_string(&p, rt->playpath);
ff_amf_write_number(&p, 0.0);
ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
ff_rtmp_packet_destroy(&pkt);
// set client buffer time disguised in ping packet
ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, 1, 10);
p = pkt.data;
bytestream_put_be16(&p, 3);
bytestream_put_be32(&p, 1);
bytestream_put_be32(&p, 256); //TODO: what is a good value here?
ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
ff_rtmp_packet_destroy(&pkt);
}
/**
* Generates ping reply and sends it to the server.
*/
static void gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
{
RTMPPacket pkt;
uint8_t *p;
ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING, ppkt->timestamp + 1, 6);
p = pkt.data;
bytestream_put_be16(&p, 7);
bytestream_put_be32(&p, AV_RB32(ppkt->data+2) + 1);
ff_rtmp_packet_write(rt->stream, &pkt, rt->chunk_size, rt->prev_pkt[1]);
ff_rtmp_packet_destroy(&pkt);
}
//TODO: Move HMAC code somewhere. Eventually.
#define HMAC_IPAD_VAL 0x36
#define HMAC_OPAD_VAL 0x5C
/**
* Calculates HMAC-SHA2 digest for RTMP handshake packets.
*
* @param src input buffer
* @param len input buffer length (should be 1536)
* @param gap offset in buffer where 32 bytes should not be taken into account
* when calculating digest (since it will be used to store that digest)
* @param key digest key
* @param keylen digest key length
* @param dst buffer where calculated digest will be stored (32 bytes)
*/
static void rtmp_calc_digest(const uint8_t *src, int len, int gap,
const uint8_t *key, int keylen, uint8_t *dst)
{
struct AVSHA *sha;
uint8_t hmac_buf[64+32] = {0};
int i;
sha = av_mallocz(av_sha_size);
if (keylen < 64) {
memcpy(hmac_buf, key, keylen);
} else {
av_sha_init(sha, 256);
av_sha_update(sha,key, keylen);
av_sha_final(sha, hmac_buf);
}
for (i = 0; i < 64; i++)
hmac_buf[i] ^= HMAC_IPAD_VAL;
av_sha_init(sha, 256);
av_sha_update(sha, hmac_buf, 64);
if (gap <= 0) {
av_sha_update(sha, src, len);
} else { //skip 32 bytes used for storing digest
av_sha_update(sha, src, gap);
av_sha_update(sha, src + gap + 32, len - gap - 32);
}
av_sha_final(sha, hmac_buf + 64);
for (i = 0; i < 64; i++)
hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
av_sha_init(sha, 256);
av_sha_update(sha, hmac_buf, 64+32);
av_sha_final(sha, dst);
av_free(sha);
}
/**
* Puts HMAC-SHA2 digest of packet data (except for the bytes where this digest
* will be stored) into that packet.
*
* @param buf handshake data (1536 bytes)
* @return offset to the digest inside input data
*/
static int rtmp_handshake_imprint_with_digest(uint8_t *buf)
{
int i, digest_pos = 0;
for (i = 8; i < 12; i++)
digest_pos += buf[i];
digest_pos = (digest_pos % 728) + 12;
rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
buf + digest_pos);
return digest_pos;
}
/**
* Verifies that the received server response has the expected digest value.
*
* @param buf handshake data received from the server (1536 bytes)
* @param off position to search digest offset from
* @return 0 if digest is valid, digest position otherwise
*/
static int rtmp_validate_digest(uint8_t *buf, int off)
{
int i, digest_pos = 0;
uint8_t digest[32];
for (i = 0; i < 4; i++)
digest_pos += buf[i + off];
digest_pos = (digest_pos % 728) + off + 4;
rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
digest);
if (!memcmp(digest, buf + digest_pos, 32))
return digest_pos;
return 0;
}
/**
* Performs handshake with the server by means of exchanging pseudorandom data
* signed with HMAC-SHA2 digest.
*
* @return 0 if handshake succeeds, negative value otherwise
*/
static int rtmp_handshake(URLContext *s, RTMPContext *rt)
{
AVLFG rnd;
uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
3, // unencrypted data
0, 0, 0, 0, // client uptime
RTMP_CLIENT_VER1,
RTMP_CLIENT_VER2,
RTMP_CLIENT_VER3,
RTMP_CLIENT_VER4,
};
uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
int i;
int server_pos, client_pos;
uint8_t digest[32];
av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Handshaking...\n");
av_lfg_init(&rnd, 0xDEADC0DE);
// generate handshake packet - 1536 bytes of pseudorandom data
for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
tosend[i] = av_lfg_get(&rnd) >> 24;
client_pos = rtmp_handshake_imprint_with_digest(tosend + 1);
url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE + 1);
i = url_read_complete(rt->stream, serverdata, RTMP_HANDSHAKE_PACKET_SIZE + 1);
if (i != RTMP_HANDSHAKE_PACKET_SIZE + 1) {
av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
return -1;
}
i = url_read_complete(rt->stream, clientdata, RTMP_HANDSHAKE_PACKET_SIZE);
if (i != RTMP_HANDSHAKE_PACKET_SIZE) {
av_log(LOG_CONTEXT, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
return -1;
}
av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
server_pos = rtmp_validate_digest(serverdata + 1, 772);
if (!server_pos) {
server_pos = rtmp_validate_digest(serverdata + 1, 8);
if (!server_pos) {
av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server response validating failed\n");
return -1;
}
}
rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
rtmp_server_key, sizeof(rtmp_server_key),
digest);
rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE-32, 0,
digest, 32,
digest);
if (memcmp(digest, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
av_log(LOG_CONTEXT, AV_LOG_ERROR, "Signature mismatch\n");
return -1;
}
for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
tosend[i] = av_lfg_get(&rnd) >> 24;
rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
rtmp_player_key, sizeof(rtmp_player_key),
digest);
rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
digest, 32,
tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
// write reply back to the server
url_write(rt->stream, tosend, RTMP_HANDSHAKE_PACKET_SIZE);
return 0;
}
/**
* Parses received packet and may perform some action depending on
* the packet contents.
* @return 0 for no errors, negative values for serious errors which prevent
* further communications, positive values for uncritical errors
*/
static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
{
int i, t;
const uint8_t *data_end = pkt->data + pkt->data_size;
switch (pkt->type) {
case RTMP_PT_CHUNK_SIZE:
if (pkt->data_size != 4) {
av_log(LOG_CONTEXT, AV_LOG_ERROR,
"Chunk size change packet is not 4 bytes long (%d)\n", pkt->data_size);
return -1;
}
rt->chunk_size = AV_RB32(pkt->data);
if (rt->chunk_size <= 0) {
av_log(LOG_CONTEXT, AV_LOG_ERROR, "Incorrect chunk size %d\n", rt->chunk_size);
return -1;
}
av_log(LOG_CONTEXT, AV_LOG_DEBUG, "New chunk size = %d\n", rt->chunk_size);
break;
case RTMP_PT_PING:
t = AV_RB16(pkt->data);
if (t == 6)
gen_pong(s, rt, pkt);
break;
case RTMP_PT_INVOKE:
//TODO: check for the messages sent for wrong state?
if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
uint8_t tmpstr[256];
if (!ff_amf_get_field_value(pkt->data + 9, data_end,
"description", tmpstr, sizeof(tmpstr)))
av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
return -1;
} else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
switch (rt->state) {
case STATE_HANDSHAKED:
gen_create_stream(s, rt);
rt->state = STATE_CONNECTING;
break;
case STATE_CONNECTING:
//extract a number from the result
if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
av_log(LOG_CONTEXT, AV_LOG_WARNING, "Unexpected reply on connect()\n");
} else {
rt->main_channel_id = (int) av_int2dbl(AV_RB64(pkt->data + 21));
}
gen_play(s, rt);
rt->state = STATE_READY;
break;
}
} else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
const uint8_t* ptr = pkt->data + 11;
uint8_t tmpstr[256];
int t;
for (i = 0; i < 2; i++) {
t = ff_amf_tag_size(ptr, data_end);
if (t < 0)
return 1;
ptr += t;
}
t = ff_amf_get_field_value(ptr, data_end,
"level", tmpstr, sizeof(tmpstr));
if (!t && !strcmp(tmpstr, "error")) {
if (!ff_amf_get_field_value(ptr, data_end,
"description", tmpstr, sizeof(tmpstr)))
av_log(LOG_CONTEXT, AV_LOG_ERROR, "Server error: %s\n",tmpstr);
return -1;
}
t = ff_amf_get_field_value(ptr, data_end,
"code", tmpstr, sizeof(tmpstr));
if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) {
rt->state = STATE_PLAYING;
return 0;
}
}
break;
}
return 0;
}
/**
* Interacts with the server by receiving and sending RTMP packets until
* there is some significant data (media data or expected status notification).
*
* @param s reading context
* @param for_header non-zero value tells function to work until it gets notification from the server that playing has been started, otherwise function will work until some media data is received (or an error happens)
* @return 0 for successful operation, negative value in case of error
*/
static int get_packet(URLContext *s, int for_header)
{
RTMPContext *rt = s->priv_data;
int ret;
for(;;) {
RTMPPacket rpkt;
if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
rt->chunk_size, rt->prev_pkt[0])) != 0) {
if (ret > 0) {
return AVERROR(EAGAIN);
} else {
return AVERROR(EIO);
}
}
ret = rtmp_parse_result(s, rt, &rpkt);
if (ret < 0) {//serious error in current packet
ff_rtmp_packet_destroy(&rpkt);
return -1;
}
if (for_header && rt->state == STATE_PLAYING) {
ff_rtmp_packet_destroy(&rpkt);
return 0;
}
if (!rpkt.data_size) {
ff_rtmp_packet_destroy(&rpkt);
continue;
}
if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
rpkt.type == RTMP_PT_NOTIFY) {
uint8_t *p;
uint32_t ts = rpkt.timestamp;
if (rpkt.type == RTMP_PT_VIDEO) {
rt->video_ts += rpkt.timestamp;
ts = rt->video_ts;
} else if (rpkt.type == RTMP_PT_AUDIO) {
rt->audio_ts += rpkt.timestamp;
ts = rt->audio_ts;
}
// generate packet header and put data into buffer for FLV demuxer
rt->flv_off = 0;
rt->flv_size = rpkt.data_size + 15;
rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
bytestream_put_byte(&p, rpkt.type);
bytestream_put_be24(&p, rpkt.data_size);
bytestream_put_be24(&p, ts);
bytestream_put_byte(&p, ts >> 24);
bytestream_put_be24(&p, 0);
bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
bytestream_put_be32(&p, 0);
ff_rtmp_packet_destroy(&rpkt);
return 0;
} else if (rpkt.type == RTMP_PT_METADATA) {
// we got raw FLV data, make it available for FLV demuxer
rt->flv_off = 0;
rt->flv_size = rpkt.data_size;
rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
ff_rtmp_packet_destroy(&rpkt);
return 0;
}
ff_rtmp_packet_destroy(&rpkt);
}
return 0;
}
static int rtmp_close(URLContext *h)
{
RTMPContext *rt = h->priv_data;
av_freep(&rt->flv_data);
url_close(rt->stream);
av_free(rt);
return 0;
}
/**
* Opens RTMP connection and verifies that the stream can be played.
*
* URL syntax: rtmp://server[:port][/app][/playpath]
* where 'app' is first one or two directories in the path
* (e.g. /ondemand/, /flash/live/, etc.)
* and 'playpath' is a file name (the rest of the path,
* may be prefixed with "mp4:")
*/
static int rtmp_open(URLContext *s, const char *uri, int flags)
{
RTMPContext *rt;
char proto[8], hostname[256], path[1024], app[128], *fname;
uint8_t buf[2048];
int port, is_input;
int ret;
is_input = !(flags & URL_WRONLY);
rt = av_mallocz(sizeof(RTMPContext));
if (!rt)
return AVERROR(ENOMEM);
s->priv_data = rt;
url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
path, sizeof(path), s->filename);
if (port < 0)
port = RTMP_DEFAULT_PORT;
snprintf(buf, sizeof(buf), "tcp://%s:%d", hostname, port);
if (url_open(&rt->stream, buf, URL_RDWR) < 0)
goto fail;
if (!is_input) {
av_log(LOG_CONTEXT, AV_LOG_ERROR, "RTMP output is not supported yet.\n");
goto fail;
} else {
rt->state = STATE_START;
if (rtmp_handshake(s, rt))
return -1;
rt->chunk_size = 128;
rt->state = STATE_HANDSHAKED;
//extract "app" part from path
if (!strncmp(path, "/ondemand/", 10)) {
fname = path + 10;
memcpy(app, "ondemand", 9);
} else {
char *p = strchr(path + 1, '/');
if (!p) {
fname = path + 1;
app[0] = '\0';
} else {
fname = strchr(p + 1, '/');
if (!fname) {
fname = p + 1;
av_strlcpy(app, path + 1, p - path);
} else {
fname++;
av_strlcpy(app, path + 1, fname - path - 1);
}
}
}
if (!strcmp(fname + strlen(fname) - 4, ".f4v") ||
!strcmp(fname + strlen(fname) - 4, ".mp4")) {
memcpy(rt->playpath, "mp4:", 5);
} else {
rt->playpath[0] = 0;
}
strncat(rt->playpath, fname, sizeof(rt->playpath) - 5);
av_log(LOG_CONTEXT, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
proto, path, app, rt->playpath);
gen_connect(s, rt, proto, hostname, port, app);
do {
ret = get_packet(s, 1);
} while (ret == EAGAIN);
if (ret < 0)
goto fail;
// generate FLV header for demuxer
rt->flv_size = 13;
rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
rt->flv_off = 0;
memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
}
s->max_packet_size = url_get_max_packet_size(rt->stream);
s->is_streamed = 1;
return 0;
fail:
rtmp_close(s);
return AVERROR(EIO);
}
static int rtmp_read(URLContext *s, uint8_t *buf, int size)
{
RTMPContext *rt = s->priv_data;
int orig_size = size;
int ret;
while (size > 0) {
int data_left = rt->flv_size - rt->flv_off;
if (data_left >= size) {
memcpy(buf, rt->flv_data + rt->flv_off, size);
rt->flv_off += size;
return orig_size;
}
if (data_left > 0) {
memcpy(buf, rt->flv_data + rt->flv_off, data_left);
buf += data_left;
size -= data_left;
rt->flv_off = rt->flv_size;
}
if ((ret = get_packet(s, 0)) < 0)
return ret;
}
return orig_size;
}
static int rtmp_write(URLContext *h, uint8_t *buf, int size)
{
return 0;
}
URLProtocol rtmp_protocol = {
"rtmp",
rtmp_open,
rtmp_read,
rtmp_write,
NULL, /* seek */
rtmp_close,
};