]> git.sesse.net Git - ffmpeg/blob - libavformat/rtmphttp.c
Add a WebP decoder
[ffmpeg] / libavformat / rtmphttp.c
1 /*
2  * RTMP HTTP network protocol
3  * Copyright (c) 2012 Samuel Pitoiset
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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)
53 } RTMP_HTTPContext;
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             return err;
94     }
95
96     memcpy(rt->out_data + rt->out_size, buf, size);
97     rt->out_size += size;
98
99     return size;
100 }
101
102 static int rtmp_http_read(URLContext *h, uint8_t *buf, int size)
103 {
104     RTMP_HTTPContext *rt = h->priv_data;
105     int ret, off = 0;
106
107     /* try to read at least 1 byte of data */
108     do {
109         ret = ffurl_read(rt->stream, buf + off, size);
110         if (ret < 0 && ret != AVERROR_EOF)
111             return ret;
112
113         if (ret == AVERROR_EOF) {
114             if (rt->finishing) {
115                 /* Do not send new requests when the client wants to
116                  * close the connection. */
117                 return AVERROR(EAGAIN);
118             }
119
120             /* When the client has reached end of file for the last request,
121              * we have to send a new request if we have buffered data.
122              * Otherwise, we have to send an idle POST. */
123             if (rt->out_size > 0) {
124                 if ((ret = rtmp_http_send_cmd(h, "send")) < 0)
125                     return ret;
126             } else {
127                 if (rt->nb_bytes_read == 0) {
128                     /* Wait 50ms before retrying to read a server reply in
129                      * order to reduce the number of idle requets. */
130                     av_usleep(50000);
131                 }
132
133                 if ((ret = rtmp_http_write(h, "", 1)) < 0)
134                     return ret;
135
136                 if ((ret = rtmp_http_send_cmd(h, "idle")) < 0)
137                     return ret;
138             }
139
140             if (h->flags & AVIO_FLAG_NONBLOCK) {
141                 /* no incoming data to handle in nonblocking mode */
142                 return AVERROR(EAGAIN);
143             }
144         } else {
145             off  += ret;
146             size -= ret;
147             rt->nb_bytes_read += ret;
148         }
149     } while (off <= 0);
150
151     return off;
152 }
153
154 static int rtmp_http_close(URLContext *h)
155 {
156     RTMP_HTTPContext *rt = h->priv_data;
157     uint8_t tmp_buf[2048];
158     int ret = 0;
159
160     if (rt->initialized) {
161         /* client wants to close the connection */
162         rt->finishing = 1;
163
164         do {
165             ret = rtmp_http_read(h, tmp_buf, sizeof(tmp_buf));
166         } while (ret > 0);
167
168         /* re-init output buffer before sending the close command */
169         rt->out_size = 0;
170
171         if ((ret = rtmp_http_write(h, "", 1)) == 1)
172             ret = rtmp_http_send_cmd(h, "close");
173     }
174
175     av_freep(&rt->out_data);
176     ffurl_close(rt->stream);
177
178     return ret;
179 }
180
181 static int rtmp_http_open(URLContext *h, const char *uri, int flags)
182 {
183     RTMP_HTTPContext *rt = h->priv_data;
184     char headers[1024], url[1024];
185     int ret, off = 0;
186
187     av_url_split(NULL, 0, NULL, 0, rt->host, sizeof(rt->host), &rt->port,
188                  NULL, 0, uri);
189
190     /* This is the first request that is sent to the server in order to
191      * register a client on the server and start a new session. The server
192      * replies with a unique id (usually a number) that is used by the client
193      * for all future requests.
194      * Note: the reply doesn't contain a value for the polling interval.
195      * A successful connect resets the consecutive index that is used
196      * in the URLs. */
197     if (rt->tls) {
198         if (rt->port < 0)
199             rt->port = RTMPTS_DEFAULT_PORT;
200         ff_url_join(url, sizeof(url), "https", NULL, rt->host, rt->port, "/open/1");
201     } else {
202         if (rt->port < 0)
203             rt->port = RTMPT_DEFAULT_PORT;
204         ff_url_join(url, sizeof(url), "http", NULL, rt->host, rt->port, "/open/1");
205     }
206
207     /* alloc the http context */
208     if ((ret = ffurl_alloc(&rt->stream, url, AVIO_FLAG_READ_WRITE, NULL)) < 0)
209         goto fail;
210
211     /* set options */
212     snprintf(headers, sizeof(headers),
213              "Cache-Control: no-cache\r\n"
214              "Content-type: application/x-fcs\r\n"
215              "User-Agent: Shockwave Flash\r\n");
216     av_opt_set(rt->stream->priv_data, "headers", headers, 0);
217     av_opt_set(rt->stream->priv_data, "multiple_requests", "1", 0);
218     av_opt_set_bin(rt->stream->priv_data, "post_data", "", 1, 0);
219
220     /* open the http context */
221     if ((ret = ffurl_connect(rt->stream, NULL)) < 0)
222         goto fail;
223
224     /* read the server reply which contains a unique ID */
225     for (;;) {
226         ret = ffurl_read(rt->stream, rt->client_id + off, sizeof(rt->client_id) - off);
227         if (ret == AVERROR_EOF)
228             break;
229         if (ret < 0)
230             goto fail;
231         off += ret;
232         if (off == sizeof(rt->client_id)) {
233             ret = AVERROR(EIO);
234             goto fail;
235         }
236     }
237     while (off > 0 && av_isspace(rt->client_id[off - 1]))
238         off--;
239     rt->client_id[off] = '\0';
240
241     /* http context is now initialized */
242     rt->initialized = 1;
243     return 0;
244
245 fail:
246     rtmp_http_close(h);
247     return ret;
248 }
249
250 #define OFFSET(x) offsetof(RTMP_HTTPContext, x)
251 #define DEC AV_OPT_FLAG_DECODING_PARAM
252
253 static const AVOption ffrtmphttp_options[] = {
254     {"ffrtmphttp_tls", "Use a HTTPS tunneling connection (RTMPTS).", OFFSET(tls), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC},
255     { NULL },
256 };
257
258 static const AVClass ffrtmphttp_class = {
259     .class_name = "ffrtmphttp",
260     .item_name  = av_default_item_name,
261     .option     = ffrtmphttp_options,
262     .version    = LIBAVUTIL_VERSION_INT,
263 };
264
265 URLProtocol ff_ffrtmphttp_protocol = {
266     .name           = "ffrtmphttp",
267     .url_open       = rtmp_http_open,
268     .url_read       = rtmp_http_read,
269     .url_write      = rtmp_http_write,
270     .url_close      = rtmp_http_close,
271     .priv_data_size = sizeof(RTMP_HTTPContext),
272     .flags          = URL_PROTOCOL_FLAG_NETWORK,
273     .priv_data_class= &ffrtmphttp_class,
274 };