rtmphttp.c 8.74 KB
Newer Older
Samuel Pitoiset's avatar
Samuel Pitoiset committed
1 2 3 4
/*
 * RTMP HTTP network protocol
 * Copyright (c) 2012 Samuel Pitoiset
 *
5
 * This file is part of FFmpeg.
Samuel Pitoiset's avatar
Samuel Pitoiset committed
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
Samuel Pitoiset's avatar
Samuel Pitoiset committed
8 9 10 11
 * 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.
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
Samuel Pitoiset's avatar
Samuel Pitoiset committed
13 14 15 16 17
 * 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
18
 * License along with FFmpeg; if not, write to the Free Software
Samuel Pitoiset's avatar
Samuel Pitoiset committed
19 20 21 22 23 24 25 26 27 28 29
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * @file
 * RTMP HTTP protocol
 */

#include "libavutil/avstring.h"
#include "libavutil/intfloat.h"
#include "libavutil/opt.h"
30
#include "libavutil/time.h"
Samuel Pitoiset's avatar
Samuel Pitoiset committed
31 32
#include "internal.h"
#include "http.h"
33
#include "rtmp.h"
Samuel Pitoiset's avatar
Samuel Pitoiset committed
34 35

#define RTMPT_DEFAULT_PORT 80
36
#define RTMPTS_DEFAULT_PORT RTMPS_DEFAULT_PORT
Samuel Pitoiset's avatar
Samuel Pitoiset committed
37 38 39

/* protocol handler context */
typedef struct RTMP_HTTPContext {
40
    const AVClass *class;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
41 42 43 44 45 46 47 48 49 50
    URLContext   *stream;           ///< HTTP stream
    char         host[256];         ///< hostname of the server
    int          port;              ///< port to connect (default is 80)
    char         client_id[64];     ///< client ID used for all requests except the first one
    int          seq;               ///< sequence ID used for all requests
    uint8_t      *out_data;         ///< output buffer
    int          out_size;          ///< current output buffer size
    int          out_capacity;      ///< current output buffer capacity
    int          initialized;       ///< flag indicating when the http context is initialized
    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)
Samuel Pitoiset's avatar
Samuel Pitoiset committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
} RTMP_HTTPContext;

static int rtmp_http_send_cmd(URLContext *h, const char *cmd)
{
    RTMP_HTTPContext *rt = h->priv_data;
    char uri[2048];
    uint8_t c;
    int ret;

    ff_url_join(uri, sizeof(uri), "http", NULL, rt->host, rt->port,
                "/%s/%s/%d", cmd, rt->client_id, rt->seq++);

    av_opt_set_bin(rt->stream->priv_data, "post_data", rt->out_data,
                   rt->out_size, 0);

    /* send a new request to the server */
    if ((ret = ff_http_do_new_request(rt->stream, uri)) < 0)
        return ret;

    /* re-init output buffer */
    rt->out_size = 0;

    /* read the first byte which contains the polling interval */
    if ((ret = ffurl_read(rt->stream, &c, 1)) < 0)
        return ret;

79 80 81
    /* re-init the number of bytes read */
    rt->nb_bytes_read = 0;

Samuel Pitoiset's avatar
Samuel Pitoiset committed
82 83 84 85 86 87 88 89
    return ret;
}

static int rtmp_http_write(URLContext *h, const uint8_t *buf, int size)
{
    RTMP_HTTPContext *rt = h->priv_data;

    if (rt->out_size + size > rt->out_capacity) {
90
        int err;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
91
        rt->out_capacity = (rt->out_size + size) * 2;
92 93 94
        if ((err = av_reallocp(&rt->out_data, rt->out_capacity)) < 0) {
            rt->out_size = 0;
            rt->out_capacity = 0;
95
            return err;
96
        }
Samuel Pitoiset's avatar
Samuel Pitoiset committed
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
    }

    memcpy(rt->out_data + rt->out_size, buf, size);
    rt->out_size += size;

    return size;
}

static int rtmp_http_read(URLContext *h, uint8_t *buf, int size)
{
    RTMP_HTTPContext *rt = h->priv_data;
    int ret, off = 0;

    /* try to read at least 1 byte of data */
    do {
        ret = ffurl_read(rt->stream, buf + off, size);
        if (ret < 0 && ret != AVERROR_EOF)
            return ret;

116
        if (!ret || ret == AVERROR_EOF) {
Samuel Pitoiset's avatar
Samuel Pitoiset committed
117 118 119 120 121 122 123 124 125 126 127 128 129
            if (rt->finishing) {
                /* Do not send new requests when the client wants to
                 * close the connection. */
                return AVERROR(EAGAIN);
            }

            /* When the client has reached end of file for the last request,
             * we have to send a new request if we have buffered data.
             * Otherwise, we have to send an idle POST. */
            if (rt->out_size > 0) {
                if ((ret = rtmp_http_send_cmd(h, "send")) < 0)
                    return ret;
            } else {
130 131 132
                if (rt->nb_bytes_read == 0) {
                    /* Wait 50ms before retrying to read a server reply in
                     * order to reduce the number of idle requets. */
133
                    av_usleep(50000);
134 135
                }

Samuel Pitoiset's avatar
Samuel Pitoiset committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149
                if ((ret = rtmp_http_write(h, "", 1)) < 0)
                    return ret;

                if ((ret = rtmp_http_send_cmd(h, "idle")) < 0)
                    return ret;
            }

            if (h->flags & AVIO_FLAG_NONBLOCK) {
                /* no incoming data to handle in nonblocking mode */
                return AVERROR(EAGAIN);
            }
        } else {
            off  += ret;
            size -= ret;
150
            rt->nb_bytes_read += ret;
Samuel Pitoiset's avatar
Samuel Pitoiset committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        }
    } while (off <= 0);

    return off;
}

static int rtmp_http_close(URLContext *h)
{
    RTMP_HTTPContext *rt = h->priv_data;
    uint8_t tmp_buf[2048];
    int ret = 0;

    if (rt->initialized) {
        /* client wants to close the connection */
        rt->finishing = 1;

        do {
            ret = rtmp_http_read(h, tmp_buf, sizeof(tmp_buf));
        } while (ret > 0);

        /* re-init output buffer before sending the close command */
        rt->out_size = 0;

        if ((ret = rtmp_http_write(h, "", 1)) == 1)
            ret = rtmp_http_send_cmd(h, "close");
    }

    av_freep(&rt->out_data);
    ffurl_close(rt->stream);

    return ret;
}

static int rtmp_http_open(URLContext *h, const char *uri, int flags)
{
    RTMP_HTTPContext *rt = h->priv_data;
    char headers[1024], url[1024];
    int ret, off = 0;

    av_url_split(NULL, 0, NULL, 0, rt->host, sizeof(rt->host), &rt->port,
                 NULL, 0, uri);

    /* This is the first request that is sent to the server in order to
     * register a client on the server and start a new session. The server
     * replies with a unique id (usually a number) that is used by the client
     * for all future requests.
     * Note: the reply doesn't contain a value for the polling interval.
     * A successful connect resets the consecutive index that is used
     * in the URLs. */
200 201 202 203 204 205 206 207 208
    if (rt->tls) {
        if (rt->port < 0)
            rt->port = RTMPTS_DEFAULT_PORT;
        ff_url_join(url, sizeof(url), "https", NULL, rt->host, rt->port, "/open/1");
    } else {
        if (rt->port < 0)
            rt->port = RTMPT_DEFAULT_PORT;
        ff_url_join(url, sizeof(url), "http", NULL, rt->host, rt->port, "/open/1");
    }
Samuel Pitoiset's avatar
Samuel Pitoiset committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

    /* alloc the http context */
    if ((ret = ffurl_alloc(&rt->stream, url, AVIO_FLAG_READ_WRITE, NULL)) < 0)
        goto fail;

    /* set options */
    snprintf(headers, sizeof(headers),
             "Cache-Control: no-cache\r\n"
             "Content-type: application/x-fcs\r\n"
             "User-Agent: Shockwave Flash\r\n");
    av_opt_set(rt->stream->priv_data, "headers", headers, 0);
    av_opt_set(rt->stream->priv_data, "multiple_requests", "1", 0);
    av_opt_set_bin(rt->stream->priv_data, "post_data", "", 1, 0);

    /* open the http context */
    if ((ret = ffurl_connect(rt->stream, NULL)) < 0)
        goto fail;

    /* read the server reply which contains a unique ID */
    for (;;) {
        ret = ffurl_read(rt->stream, rt->client_id + off, sizeof(rt->client_id) - off);
230
        if (!ret || ret == AVERROR_EOF)
Samuel Pitoiset's avatar
Samuel Pitoiset committed
231 232 233 234 235 236 237 238 239
            break;
        if (ret < 0)
            goto fail;
        off += ret;
        if (off == sizeof(rt->client_id)) {
            ret = AVERROR(EIO);
            goto fail;
        }
    }
240
    while (off > 0 && av_isspace(rt->client_id[off - 1]))
Samuel Pitoiset's avatar
Samuel Pitoiset committed
241 242 243 244 245 246 247 248 249 250 251 252
        off--;
    rt->client_id[off] = '\0';

    /* http context is now initialized */
    rt->initialized = 1;
    return 0;

fail:
    rtmp_http_close(h);
    return ret;
}

253 254 255 256
#define OFFSET(x) offsetof(RTMP_HTTPContext, x)
#define DEC AV_OPT_FLAG_DECODING_PARAM

static const AVOption ffrtmphttp_options[] = {
257
    {"ffrtmphttp_tls", "Use a HTTPS tunneling connection (RTMPTS).", OFFSET(tls), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC},
258 259 260 261 262 263 264 265 266 267
    { NULL },
};

static const AVClass ffrtmphttp_class = {
    .class_name = "ffrtmphttp",
    .item_name  = av_default_item_name,
    .option     = ffrtmphttp_options,
    .version    = LIBAVUTIL_VERSION_INT,
};

268
const URLProtocol ff_ffrtmphttp_protocol = {
269
    .name           = "ffrtmphttp",
Samuel Pitoiset's avatar
Samuel Pitoiset committed
270 271 272 273 274 275
    .url_open       = rtmp_http_open,
    .url_read       = rtmp_http_read,
    .url_write      = rtmp_http_write,
    .url_close      = rtmp_http_close,
    .priv_data_size = sizeof(RTMP_HTTPContext),
    .flags          = URL_PROTOCOL_FLAG_NETWORK,
276
    .priv_data_class= &ffrtmphttp_class,
Samuel Pitoiset's avatar
Samuel Pitoiset committed
277
};