FFmpeg
rtmphttp.c
Go to the documentation of this file.
1 /*
2  * RTMP HTTP network protocol
3  * Copyright (c) 2012 Samuel Pitoiset
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
24  * RTMP HTTP protocol
25  */
26 
27 #include "libavutil/avstring.h"
28 #include "libavutil/intfloat.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/time.h"
31 #include "internal.h"
32 #include "http.h"
33 #include "rtmp.h"
34 
35 #define RTMPT_DEFAULT_PORT 80
36 #define RTMPTS_DEFAULT_PORT RTMPS_DEFAULT_PORT
37 
38 /* protocol handler context */
39 typedef struct RTMP_HTTPContext {
40  const AVClass *class;
41  URLContext *stream; ///< HTTP stream
42  char host[256]; ///< hostname of the server
43  int port; ///< port to connect (default is 80)
44  char client_id[64]; ///< client ID used for all requests except the first one
45  int seq; ///< sequence ID used for all requests
46  uint8_t *out_data; ///< output buffer
47  int out_size; ///< current output buffer size
48  int out_capacity; ///< current output buffer capacity
49  int initialized; ///< flag indicating when the http context is initialized
50  int finishing; ///< flag indicating when the client closes the connection
51  int nb_bytes_read; ///< number of bytes read since the last request
52  int tls; ///< use Transport Security Layer (RTMPTS)
54 
55 static int rtmp_http_send_cmd(URLContext *h, const char *cmd)
56 {
57  RTMP_HTTPContext *rt = h->priv_data;
58  char uri[2048];
59  uint8_t c;
60  int ret;
61 
62  ff_url_join(uri, sizeof(uri), "http", NULL, rt->host, rt->port,
63  "/%s/%s/%d", cmd, rt->client_id, rt->seq++);
64 
65  av_opt_set_bin(rt->stream->priv_data, "post_data", rt->out_data,
66  rt->out_size, 0);
67 
68  /* send a new request to the server */
69  if ((ret = ff_http_do_new_request(rt->stream, uri)) < 0)
70  return ret;
71 
72  /* re-init output buffer */
73  rt->out_size = 0;
74 
75  /* read the first byte which contains the polling interval */
76  if ((ret = ffurl_read(rt->stream, &c, 1)) < 0)
77  return ret;
78 
79  /* re-init the number of bytes read */
80  rt->nb_bytes_read = 0;
81 
82  return ret;
83 }
84 
85 static int rtmp_http_write(URLContext *h, const uint8_t *buf, int size)
86 {
87  RTMP_HTTPContext *rt = h->priv_data;
88 
89  if (rt->out_size + size > rt->out_capacity) {
90  int err;
91  rt->out_capacity = (rt->out_size + size) * 2;
92  if ((err = av_reallocp(&rt->out_data, rt->out_capacity)) < 0) {
93  rt->out_size = 0;
94  rt->out_capacity = 0;
95  return err;
96  }
97  }
98 
99  memcpy(rt->out_data + rt->out_size, buf, size);
100  rt->out_size += size;
101 
102  return size;
103 }
104 
105 static int rtmp_http_read(URLContext *h, uint8_t *buf, int size)
106 {
107  RTMP_HTTPContext *rt = h->priv_data;
108  int ret, off = 0;
109 
110  /* try to read at least 1 byte of data */
111  do {
112  ret = ffurl_read(rt->stream, buf + off, size);
113  if (ret < 0 && ret != AVERROR_EOF)
114  return ret;
115 
116  if (!ret || ret == AVERROR_EOF) {
117  if (rt->finishing) {
118  /* Do not send new requests when the client wants to
119  * close the connection. */
120  return AVERROR(EAGAIN);
121  }
122 
123  /* When the client has reached end of file for the last request,
124  * we have to send a new request if we have buffered data.
125  * Otherwise, we have to send an idle POST. */
126  if (rt->out_size > 0) {
127  if ((ret = rtmp_http_send_cmd(h, "send")) < 0)
128  return ret;
129  } else {
130  if (rt->nb_bytes_read == 0) {
131  /* Wait 50ms before retrying to read a server reply in
132  * order to reduce the number of idle requests. */
133  av_usleep(50000);
134  }
135 
136  if ((ret = rtmp_http_write(h, "", 1)) < 0)
137  return ret;
138 
139  if ((ret = rtmp_http_send_cmd(h, "idle")) < 0)
140  return ret;
141  }
142 
143  if (h->flags & AVIO_FLAG_NONBLOCK) {
144  /* no incoming data to handle in nonblocking mode */
145  return AVERROR(EAGAIN);
146  }
147  } else {
148  off += ret;
149  size -= ret;
150  rt->nb_bytes_read += ret;
151  }
152  } while (off <= 0);
153 
154  return off;
155 }
156 
158 {
159  RTMP_HTTPContext *rt = h->priv_data;
160  uint8_t tmp_buf[2048];
161  int ret = 0;
162 
163  if (rt->initialized) {
164  /* client wants to close the connection */
165  rt->finishing = 1;
166 
167  do {
168  ret = rtmp_http_read(h, tmp_buf, sizeof(tmp_buf));
169  } while (ret > 0);
170 
171  /* re-init output buffer before sending the close command */
172  rt->out_size = 0;
173 
174  if ((ret = rtmp_http_write(h, "", 1)) == 1)
175  ret = rtmp_http_send_cmd(h, "close");
176  }
177 
178  av_freep(&rt->out_data);
179  ffurl_closep(&rt->stream);
180 
181  return ret;
182 }
183 
184 static int rtmp_http_open(URLContext *h, const char *uri, int flags)
185 {
186  RTMP_HTTPContext *rt = h->priv_data;
187  char headers[1024], url[1024];
188  int ret, off = 0;
189 
190  av_url_split(NULL, 0, NULL, 0, rt->host, sizeof(rt->host), &rt->port,
191  NULL, 0, uri);
192 
193  /* This is the first request that is sent to the server in order to
194  * register a client on the server and start a new session. The server
195  * replies with a unique id (usually a number) that is used by the client
196  * for all future requests.
197  * Note: the reply doesn't contain a value for the polling interval.
198  * A successful connect resets the consecutive index that is used
199  * in the URLs. */
200  if (rt->tls) {
201  if (rt->port < 0)
203  ff_url_join(url, sizeof(url), "https", NULL, rt->host, rt->port, "/open/1");
204  } else {
205  if (rt->port < 0)
206  rt->port = RTMPT_DEFAULT_PORT;
207  ff_url_join(url, sizeof(url), "http", NULL, rt->host, rt->port, "/open/1");
208  }
209 
210  /* alloc the http context */
211  if ((ret = ffurl_alloc(&rt->stream, url, AVIO_FLAG_READ_WRITE, &h->interrupt_callback)) < 0)
212  goto fail;
213 
214  /* set options */
215  snprintf(headers, sizeof(headers),
216  "Cache-Control: no-cache\r\n"
217  "Content-type: application/x-fcs\r\n"
218  "User-Agent: Shockwave Flash\r\n");
219  av_opt_set(rt->stream->priv_data, "headers", headers, 0);
220  av_opt_set(rt->stream->priv_data, "multiple_requests", "1", 0);
221  av_opt_set_bin(rt->stream->priv_data, "post_data", "", 1, 0);
222 
223  if (!rt->stream->protocol_whitelist && h->protocol_whitelist) {
224  rt->stream->protocol_whitelist = av_strdup(h->protocol_whitelist);
225  if (!rt->stream->protocol_whitelist) {
226  ret = AVERROR(ENOMEM);
227  goto fail;
228  }
229  }
230 
231  /* open the http context */
232  if ((ret = ffurl_connect(rt->stream, NULL)) < 0)
233  goto fail;
234 
235  /* read the server reply which contains a unique ID */
236  for (;;) {
237  ret = ffurl_read(rt->stream, rt->client_id + off, sizeof(rt->client_id) - off);
238  if (!ret || ret == AVERROR_EOF)
239  break;
240  if (ret < 0)
241  goto fail;
242  off += ret;
243  if (off == sizeof(rt->client_id)) {
244  ret = AVERROR(EIO);
245  goto fail;
246  }
247  }
248  while (off > 0 && av_isspace(rt->client_id[off - 1]))
249  off--;
250  rt->client_id[off] = '\0';
251 
252  /* http context is now initialized */
253  rt->initialized = 1;
254  return 0;
255 
256 fail:
258  return ret;
259 }
260 
261 #define OFFSET(x) offsetof(RTMP_HTTPContext, x)
262 #define DEC AV_OPT_FLAG_DECODING_PARAM
263 
264 static const AVOption ffrtmphttp_options[] = {
265  {"ffrtmphttp_tls", "Use a HTTPS tunneling connection (RTMPTS).", OFFSET(tls), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC},
266  { NULL },
267 };
268 
269 static const AVClass ffrtmphttp_class = {
270  .class_name = "ffrtmphttp",
271  .item_name = av_default_item_name,
272  .option = ffrtmphttp_options,
273  .version = LIBAVUTIL_VERSION_INT,
274 };
275 
277  .name = "ffrtmphttp",
278  .url_open = rtmp_http_open,
279  .url_read = rtmp_http_read,
280  .url_write = rtmp_http_write,
281  .url_close = rtmp_http_close,
282  .priv_data_size = sizeof(RTMP_HTTPContext),
284  .priv_data_class= &ffrtmphttp_class,
285  .default_whitelist = "https,http,tcp,tls",
286 };
OFFSET
#define OFFSET(x)
Definition: rtmphttp.c:261
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
URL_PROTOCOL_FLAG_NETWORK
#define URL_PROTOCOL_FLAG_NETWORK
Definition: url.h:33
ffrtmphttp_options
static const AVOption ffrtmphttp_options[]
Definition: rtmphttp.c:264
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
AVIO_FLAG_READ_WRITE
#define AVIO_FLAG_READ_WRITE
read-write pseudo flag
Definition: avio.h:625
av_isspace
static av_const int av_isspace(int c)
Locale-independent conversion of ASCII isspace.
Definition: avstring.h:219
RTMP_HTTPContext::nb_bytes_read
int nb_bytes_read
number of bytes read since the last request
Definition: rtmphttp.c:51
AVOption
AVOption.
Definition: opt.h:251
RTMPT_DEFAULT_PORT
#define RTMPT_DEFAULT_PORT
Definition: rtmphttp.c:35
RTMP_HTTPContext::host
char host[256]
hostname of the server
Definition: rtmphttp.c:42
intfloat.h
URLProtocol
Definition: url.h:53
fail
#define fail()
Definition: checkasm.h:134
ffurl_connect
int ffurl_connect(URLContext *uc, AVDictionary **options)
Connect an URLContext that has been allocated by ffurl_alloc.
Definition: avio.c:166
av_opt_set
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:487
URLContext::priv_data
void * priv_data
Definition: url.h:40
RTMP_HTTPContext::out_capacity
int out_capacity
current output buffer capacity
Definition: rtmphttp.c:48
rtmp_http_close
static int rtmp_http_close(URLContext *h)
Definition: rtmphttp.c:157
RTMP_HTTPContext::initialized
int initialized
flag indicating when the http context is initialized
Definition: rtmphttp.c:49
ff_url_join
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...)
Definition: url.c:38
av_usleep
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition: time.c:84
RTMP_HTTPContext::port
int port
port to connect (default is 80)
Definition: rtmphttp.c:43
ff_http_do_new_request
int ff_http_do_new_request(URLContext *h, const char *uri)
Send a new HTTP request, reusing the old connection.
Definition: http.c:452
internal.h
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:66
URLContext::protocol_whitelist
const char * protocol_whitelist
Definition: url.h:48
NULL
#define NULL
Definition: coverity.c:32
av_opt_set_bin
int av_opt_set_bin(void *obj, const char *name, const uint8_t *val, int len, int search_flags)
Definition: opt.c:639
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:237
time.h
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
RTMP_HTTPContext::seq
int seq
sequence ID used for all requests
Definition: rtmphttp.c:45
RTMPTS_DEFAULT_PORT
#define RTMPTS_DEFAULT_PORT
Definition: rtmphttp.c:36
rtmp_http_send_cmd
static int rtmp_http_send_cmd(URLContext *h, const char *cmd)
Definition: rtmphttp.c:55
size
int size
Definition: twinvq_data.h:10344
av_reallocp
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition: mem.c:186
URLProtocol::name
const char * name
Definition: url.h:54
ffurl_alloc
int ffurl_alloc(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb)
Create a URLContext for accessing to the resource indicated by url, but do not initiate the connectio...
Definition: avio.c:293
URLContext
Definition: url.h:37
av_url_split
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:357
RTMP_HTTPContext::out_data
uint8_t * out_data
output buffer
Definition: rtmphttp.c:46
rtmp.h
rtmp_http_open
static int rtmp_http_open(URLContext *h, const char *uri, int flags)
Definition: rtmphttp.c:184
ffurl_closep
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:438
ret
ret
Definition: filter_design.txt:187
AVClass::class_name
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:71
rtmp_http_write
static int rtmp_http_write(URLContext *h, const uint8_t *buf, int size)
Definition: rtmphttp.c:85
RTMP_HTTPContext::out_size
int out_size
current output buffer size
Definition: rtmphttp.c:47
ffurl_read
int ffurl_read(URLContext *h, unsigned char *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf.
Definition: avio.c:401
ffrtmphttp_class
static const AVClass ffrtmphttp_class
Definition: rtmphttp.c:269
headers
FFmpeg currently uses a custom build this text attempts to document some of its obscure features and options Makefile the full command issued by make and its output will be shown on the screen DBG Preprocess x86 external assembler files to a dbg asm file in the object which then gets compiled Helps in developing those assembler files DESTDIR Destination directory for the install useful to prepare packages or install FFmpeg in cross environments GEN Set to ‘1’ to generate the missing or mismatched references Makefile builds all the libraries and the executables fate Run the fate test note that you must have installed it fate list List all fate regression test targets install Install headers
Definition: build_system.txt:34
RTMP_HTTPContext::stream
URLContext * stream
HTTP stream.
Definition: rtmphttp.c:41
RTMP_HTTPContext
Definition: rtmphttp.c:39
av_strdup
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:270
RTMP_HTTPContext::tls
int tls
use Transport Security Layer (RTMPTS)
Definition: rtmphttp.c:52
rtmp_http_read
static int rtmp_http_read(URLContext *h, uint8_t *buf, int size)
Definition: rtmphttp.c:105
AV_OPT_TYPE_BOOL
@ AV_OPT_TYPE_BOOL
Definition: opt.h:244
AVIO_FLAG_NONBLOCK
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition: avio.h:642
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
ff_ffrtmphttp_protocol
const URLProtocol ff_ffrtmphttp_protocol
Definition: rtmphttp.c:276
RTMP_HTTPContext::client_id
char client_id[64]
client ID used for all requests except the first one
Definition: rtmphttp.c:44
flags
#define flags(name, subs,...)
Definition: cbs_av1.c:561
h
h
Definition: vp9dsp_template.c:2038
avstring.h
http.h
RTMP_HTTPContext::finishing
int finishing
flag indicating when the client closes the connection
Definition: rtmphttp.c:50
snprintf
#define snprintf
Definition: snprintf.h:34
DEC
#define DEC
Definition: rtmphttp.c:262