ffserver.c 126 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
2
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
3
 *
4 5 6
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
7 8
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Fabrice Bellard's avatar
Fabrice Bellard committed
19
 */
20

21 22 23 24 25
/**
 * @file
 * multiple format streaming server based on the FFmpeg libraries
 */

26
#include "config.h"
27
#if !HAVE_CLOSESOCKET
28 29 30 31
#define closesocket close
#endif
#include <string.h>
#include <stdlib.h>
32
#include <stdio.h>
33
#include "libavformat/avformat.h"
34
/* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
35
#include "libavformat/ffm.h"
36 37
#include "libavformat/network.h"
#include "libavformat/os_support.h"
38
#include "libavformat/rtpdec.h"
39
#include "libavformat/rtpproto.h"
40
#include "libavformat/rtsp.h"
41
#include "libavformat/rtspcodes.h"
42
#include "libavformat/avio_internal.h"
43 44 45
#include "libavformat/internal.h"
#include "libavformat/url.h"

46
#include "libavutil/avassert.h"
47
#include "libavutil/avstring.h"
48
#include "libavutil/lfg.h"
49
#include "libavutil/dict.h"
50
#include "libavutil/intreadwrite.h"
51
#include "libavutil/mathematics.h"
52
#include "libavutil/random_seed.h"
53
#include "libavutil/parseutils.h"
54
#include "libavutil/opt.h"
55 56
#include "libavutil/time.h"

Fabrice Bellard's avatar
Fabrice Bellard committed
57
#include <stdarg.h>
58
#if HAVE_UNISTD_H
Fabrice Bellard's avatar
Fabrice Bellard committed
59
#include <unistd.h>
60
#endif
Fabrice Bellard's avatar
Fabrice Bellard committed
61 62
#include <fcntl.h>
#include <sys/ioctl.h>
63
#if HAVE_POLL_H
64
#include <poll.h>
65
#endif
Fabrice Bellard's avatar
Fabrice Bellard committed
66 67
#include <errno.h>
#include <time.h>
68
#include <sys/wait.h>
Fabrice Bellard's avatar
Fabrice Bellard committed
69
#include <signal.h>
70

71
#include "cmdutils.h"
72
#include "ffserver_config.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
73

74 75
#define PATH_LENGTH 1024

76
const char program_name[] = "ffserver";
77
const int program_birth_year = 2000;
78

79 80
static const OptionDef options[];

Fabrice Bellard's avatar
Fabrice Bellard committed
81 82 83 84
enum HTTPState {
    HTTPSTATE_WAIT_REQUEST,
    HTTPSTATE_SEND_HEADER,
    HTTPSTATE_SEND_DATA_HEADER,
85
    HTTPSTATE_SEND_DATA,          /* sending TCP or UDP data */
Fabrice Bellard's avatar
Fabrice Bellard committed
86
    HTTPSTATE_SEND_DATA_TRAILER,
87
    HTTPSTATE_RECEIVE_DATA,
88 89 90 91 92
    HTTPSTATE_WAIT_FEED,          /* wait for data from the feed */
    HTTPSTATE_READY,

    RTSPSTATE_WAIT_REQUEST,
    RTSPSTATE_SEND_REPLY,
93
    RTSPSTATE_SEND_PACKET,
Fabrice Bellard's avatar
Fabrice Bellard committed
94 95
};

96
static const char * const http_state[] = {
97 98 99
    "HTTP_WAIT_REQUEST",
    "HTTP_SEND_HEADER",

Fabrice Bellard's avatar
Fabrice Bellard committed
100 101 102 103 104
    "SEND_DATA_HEADER",
    "SEND_DATA",
    "SEND_DATA_TRAILER",
    "RECEIVE_DATA",
    "WAIT_FEED",
105 106 107 108
    "READY",

    "RTSP_WAIT_REQUEST",
    "RTSP_SEND_REPLY",
109
    "RTSP_SEND_PACKET",
Fabrice Bellard's avatar
Fabrice Bellard committed
110 111
};

112
#define IOBUFFER_INIT_SIZE 8192
Fabrice Bellard's avatar
Fabrice Bellard committed
113 114

/* timeouts are in ms */
115 116 117
#define HTTP_REQUEST_TIMEOUT (15 * 1000)
#define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)

Fabrice Bellard's avatar
Fabrice Bellard committed
118 119
#define SYNC_TIMEOUT (10 * 1000)

120 121 122 123 124
typedef struct RTSPActionServerSetup {
    uint32_t ipaddr;
    char transport_option[512];
} RTSPActionServerSetup;

125
typedef struct {
126
    int64_t count1, count2;
127
    int64_t time1, time2;
128 129
} DataRateData;

Fabrice Bellard's avatar
Fabrice Bellard committed
130 131 132 133 134 135
/* context associated with one connection */
typedef struct HTTPContext {
    enum HTTPState state;
    int fd; /* socket file descriptor */
    struct sockaddr_in from_addr; /* origin */
    struct pollfd *poll_entry; /* used when polling */
136
    int64_t timeout;
137
    uint8_t *buffer_ptr, *buffer_end;
Fabrice Bellard's avatar
Fabrice Bellard committed
138
    int http_error;
139
    int post;
140 141
    int chunked_encoding;
    int chunk_size;               /* 0 if it needs to be read */
Fabrice Bellard's avatar
Fabrice Bellard committed
142
    struct HTTPContext *next;
143
    int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
144
    int64_t data_count;
Fabrice Bellard's avatar
Fabrice Bellard committed
145 146 147 148
    /* feed input */
    int feed_fd;
    /* input format handling */
    AVFormatContext *fmt_in;
149
    int64_t start_time;            /* In milliseconds - this wraps fairly often */
150
    int64_t first_pts;            /* initial pts value */
151 152 153 154 155 156 157
    int64_t cur_pts;             /* current pts value from the stream in us */
    int64_t cur_frame_duration;  /* duration of the current frame in us */
    int cur_frame_bytes;       /* output frame size, needed to compute
                                  the time at which we send each
                                  packet */
    int pts_stream_index;        /* stream we choose as clock reference */
    int64_t cur_clock;           /* current clock reference value in us */
Fabrice Bellard's avatar
Fabrice Bellard committed
158
    /* output format handling */
159
    struct FFServerStream *stream;
160
    /* -1 is invalid stream */
161 162
    int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
    int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
163
    int switch_pending;
164
    AVFormatContext fmt_ctx; /* instance of FFServerStream for one user */
Fabrice Bellard's avatar
Fabrice Bellard committed
165
    int last_packet_sent; /* true if last data packet was sent */
166
    int suppress_log;
167
    DataRateData datarate;
168
    int wmp_client_id;
169 170 171
    char protocol[16];
    char method[16];
    char url[128];
172
    int buffer_size;
173
    uint8_t *buffer;
174 175
    int is_packetized; /* if true, the stream is packetized */
    int packet_stream_index; /* current stream for output in state machine */
176

177
    /* RTSP state specific */
178
    uint8_t *pb_buffer; /* XXX: use that in all the code */
179
    AVIOContext *pb;
180
    int seq; /* RTSP sequence number */
181

182
    /* RTP state specific */
183
    enum RTSPLowerTransport rtp_protocol;
184
    char session_id[32]; /* session id */
185
    AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
186

187
    /* RTP/UDP specific */
188
    URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
189 190 191 192

    /* RTP/TCP specific */
    struct HTTPContext *rtsp_c;
    uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
Fabrice Bellard's avatar
Fabrice Bellard committed
193 194 195 196
} HTTPContext;

typedef struct FeedData {
    long long data_count;
Diego Biurrun's avatar
Diego Biurrun committed
197
    float avg_frame_size;   /* frame size averaged over last frames with exponential mean */
Fabrice Bellard's avatar
Fabrice Bellard committed
198 199
} FeedData;

200
static HTTPContext *first_http_ctx;
201 202 203 204 205

static FFServerConfig config = {
    .nb_max_http_connections = 2000,
    .nb_max_connections = 5,
    .max_bandwidth = 1000,
206
    .use_defaults = 1,
207
};
Fabrice Bellard's avatar
Fabrice Bellard committed
208

209 210 211 212 213
static void new_connection(int server_fd, int is_rtsp);
static void close_connection(HTTPContext *c);

/* HTTP handling */
static int handle_connection(HTTPContext *c);
214
static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
215
static void compute_status(HTTPContext *c);
Fabrice Bellard's avatar
Fabrice Bellard committed
216
static int open_input_stream(HTTPContext *c, const char *info);
217 218
static int http_parse_request(HTTPContext *c);
static int http_send_data(HTTPContext *c);
Fabrice Bellard's avatar
Fabrice Bellard committed
219 220
static int http_start_receive_data(HTTPContext *c);
static int http_receive_data(HTTPContext *c);
221 222 223 224

/* RTSP handling */
static int rtsp_parse_request(HTTPContext *c);
static void rtsp_cmd_describe(HTTPContext *c, const char *url);
225
static void rtsp_cmd_options(HTTPContext *c, const char *url);
226 227 228 229 230 231
static void rtsp_cmd_setup(HTTPContext *c, const char *url,
                           RTSPMessageHeader *h);
static void rtsp_cmd_play(HTTPContext *c, const char *url,
                          RTSPMessageHeader *h);
static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
                               RTSPMessageHeader *h, int pause_only);
232

233
/* SDP handling */
234
static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
235 236
                                   struct in_addr my_ip);

237
/* RTP handling */
238
static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
239 240
                                       FFServerStream *stream,
                                       const char *session_id,
241
                                       enum RTSPLowerTransport rtp_protocol);
242
static int rtp_new_av_stream(HTTPContext *c,
243 244
                             int stream_index, struct sockaddr_in *dest_addr,
                             HTTPContext *rtsp_c);
245
/* utils */
246 247
static size_t htmlencode (const char *src, char **dest);
static inline void cp_html_entity (char *buffer, const char *entity);
248 249
static inline int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs,
                                    int stream);
Fabrice Bellard's avatar
Fabrice Bellard committed
250

251 252
static const char *my_program_name;

253
static int no_launch;
254
static int need_to_start_children;
255

256
/* maximum number of simultaneous HTTP connections */
257
static unsigned int nb_connections;
Fabrice Bellard's avatar
Fabrice Bellard committed
258

259
static uint64_t current_bandwidth;
260

261 262
/* Making this global saves on passing it around everywhere */
static int64_t cur_time;
263

264
static AVLFG random_state;
265

Fabrice Bellard's avatar
Fabrice Bellard committed
266 267
static FILE *logfile = NULL;

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
static inline void cp_html_entity (char *buffer, const char *entity) {
    if (!buffer || !entity)
        return;
    while (*entity)
        *buffer++ = *entity++;
}

/**
 * Substitutes known conflicting chars on a text string with
 * their corresponding HTML entities.
 *
 * Returns the number of bytes in the 'encoded' representation
 * not including the terminating NUL.
 */
static size_t htmlencode (const char *src, char **dest) {
    const char *amp = "&amp;";
    const char *lt  = "&lt;";
    const char *gt  = "&gt;";
    const char *start;
    char *tmp;
    size_t final_size = 0;

    if (!src)
        return 0;

    start = src;

    /* Compute needed dest size */
    while (*src != '\0') {
        switch(*src) {
            case 38: /* & */
                final_size += 5;
                break;
            case 60: /* < */
            case 62: /* > */
                final_size += 4;
                break;
            default:
                final_size++;
        }
        src++;
    }

    src = start;
    *dest = av_mallocz(final_size + 1);
    if (!*dest)
        return 0;

    /* Build dest */
    tmp = *dest;
    while (*src != '\0') {
        switch(*src) {
            case 38: /* & */
                cp_html_entity (tmp, amp);
                tmp += 5;
                break;
            case 60: /* < */
                cp_html_entity (tmp, lt);
                tmp += 4;
                break;
            case 62: /* > */
                cp_html_entity (tmp, gt);
                tmp += 4;
                break;
            default:
                *tmp = *src;
                tmp += 1;
        }
        src++;
337
    }
338 339 340
    *tmp = '\0';

    return final_size;
341 342
}

343 344 345 346
static int64_t ffm_read_write_index(int fd)
{
    uint8_t buf[8];

347 348
    if (lseek(fd, 8, SEEK_SET) < 0)
        return AVERROR(EIO);
349 350 351 352 353 354 355 356 357 358 359 360
    if (read(fd, buf, 8) != 8)
        return AVERROR(EIO);
    return AV_RB64(buf);
}

static int ffm_write_write_index(int fd, int64_t pos)
{
    uint8_t buf[8];
    int i;

    for(i=0;i<8;i++)
        buf[i] = (pos >> (56 - i * 8)) & 0xff;
361
    if (lseek(fd, 8, SEEK_SET) < 0)
362
        goto bail_eio;
363
    if (write(fd, buf, 8) != 8)
364 365
        goto bail_eio;

366
    return 8;
367 368 369

bail_eio:
    return AVERROR(EIO);
370 371 372 373 374
}

static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
                                int64_t file_size)
{
375
    av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
376 377
    av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
    av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
378 379
}

380
static char *ctime1(char *buf2, size_t buf_size)
Baptiste Coudurier's avatar
Baptiste Coudurier committed
381 382 383 384 385 386
{
    time_t ti;
    char *p;

    ti = time(NULL);
    p = ctime(&ti);
387 388 389 390
    if (!p || !*p) {
        *buf2 = '\0';
        return buf2;
    }
391
    av_strlcpy(buf2, p, buf_size);
392
    p = buf2 + strlen(buf2) - 1;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
393 394 395 396 397
    if (*p == '\n')
        *p = '\0';
    return buf2;
}

398
static void http_vlog(const char *fmt, va_list vargs)
Fabrice Bellard's avatar
Fabrice Bellard committed
399
{
400
    static int print_prefix = 1;
401
    char buf[32];
402 403 404 405

    if (!logfile)
        return;

406 407 408 409 410 411 412
    if (print_prefix) {
        ctime1(buf, sizeof(buf));
        fprintf(logfile, "%s ", buf);
    }
    print_prefix = strstr(fmt, "\n") != NULL;
    vfprintf(logfile, fmt, vargs);
    fflush(logfile);
413 414
}

415 416 417 418
#ifdef __GNUC__
__attribute__ ((format (printf, 1, 2)))
#endif
static void http_log(const char *fmt, ...)
419 420 421 422 423 424 425 426 427 428 429
{
    va_list vargs;
    va_start(vargs, fmt);
    http_vlog(fmt, vargs);
    va_end(vargs);
}

static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
{
    static int print_prefix = 1;
    AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
430
    if (level > av_log_get_level())
431 432
        return;
    if (print_prefix && avc)
433
        http_log("[%s @ %p]", avc->item_name(ptr), ptr);
434 435
    print_prefix = strstr(fmt, "\n") != NULL;
    http_vlog(fmt, vargs);
Fabrice Bellard's avatar
Fabrice Bellard committed
436 437
}

438 439
static void log_connection(HTTPContext *c)
{
440
    if (c->suppress_log)
441 442
        return;

443 444
    http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
             inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
445
             c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
446 447
}

448
static void update_datarate(DataRateData *drd, int64_t count)
449 450 451 452
{
    if (!drd->time1 && !drd->count1) {
        drd->time1 = drd->time2 = cur_time;
        drd->count1 = drd->count2 = count;
453
    } else if (cur_time - drd->time2 > 5000) {
Alex Beregszaszi's avatar
Alex Beregszaszi committed
454 455 456 457
        drd->time1 = drd->time2;
        drd->count1 = drd->count2;
        drd->time2 = cur_time;
        drd->count2 = count;
458 459 460 461
    }
}

/* In bytes per second */
462
static int compute_datarate(DataRateData *drd, int64_t count)
463 464 465
{
    if (cur_time == drd->time1)
        return 0;
466

467 468 469
    return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
}

470

471
static void start_children(FFServerStream *feed)
472
{
473
    char *pathname;
474 475
    char *slash;
    int i;
476
    size_t cmd_length;
477

478 479 480
    if (no_launch)
        return;

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    cmd_length = strlen(my_program_name);

   /**
    * FIXME: WIP Safeguard. Remove after clearing all harcoded
    * '1024' path lengths
    */
    if (cmd_length > PATH_LENGTH - 1) {
        http_log("Could not start children. Command line: '%s' exceeds "
                    "path length limit (%d)\n", my_program_name, PATH_LENGTH);
        return;
    }

    pathname = av_strdup (my_program_name);
    if (!pathname) {
        http_log("Could not allocate memory for children cmd line\n");
        return;
    }
498 499 500 501 502 503 504 505 506 507
   /* replace "ffserver" with "ffmpeg" in the path of current
    * program. Ignore user provided path */

    slash = strrchr(pathname, '/');
    if (!slash)
        slash = pathname;
    else
        slash++;
    strcpy(slash, "ffmpeg");

508
    for (; feed; feed = feed->next) {
509 510 511 512

        if (!feed->child_argv || feed->pid)
            continue;

513
        feed->pid_start = time(0);
514

515 516
        feed->pid = fork();
        if (feed->pid < 0) {
517
            http_log("Unable to create children: %s\n", strerror(errno));
518
            av_free (pathname);
519
            exit(EXIT_FAILURE);
520
        }
521

522 523
        if (feed->pid)
            continue;
524

525
        /* In child */
526

527 528
        http_log("Launch command line: ");
        http_log("%s ", pathname);
529

530 531 532
        for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
            http_log("%s ", feed->child_argv[i]);
        http_log("\n");
533

534 535
        for (i = 3; i < 256; i++)
            close(i);
536

537 538 539 540 541 542 543 544
        if (!config.debug) {
            if (!freopen("/dev/null", "r", stdin))
                http_log("failed to redirect STDIN to /dev/null\n;");
            if (!freopen("/dev/null", "w", stdout))
                http_log("failed to redirect STDOUT to /dev/null\n;");
            if (!freopen("/dev/null", "w", stderr))
                http_log("failed to redirect STDERR to /dev/null\n;");
        }
545

546 547
        signal(SIGPIPE, SIG_DFL);
        execvp(pathname, feed->child_argv);
548
        av_free (pathname);
549
        _exit(1);
550
    }
551
    av_free (pathname);
552 553
}

554 555
/* open a listening socket */
static int socket_open_listen(struct sockaddr_in *my_addr)
Fabrice Bellard's avatar
Fabrice Bellard committed
556
{
557
    int server_fd, tmp;
Fabrice Bellard's avatar
Fabrice Bellard committed
558 559 560 561 562 563

    server_fd = socket(AF_INET,SOCK_STREAM,0);
    if (server_fd < 0) {
        perror ("socket");
        return -1;
    }
564

Fabrice Bellard's avatar
Fabrice Bellard committed
565
    tmp = 1;
566 567
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
        av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
568

569
    my_addr->sin_family = AF_INET;
570
    if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
571
        char bindmsg[32];
572 573
        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
                 ntohs(my_addr->sin_port));
574
        perror (bindmsg);
575
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
576
    }
577

Fabrice Bellard's avatar
Fabrice Bellard committed
578 579
    if (listen (server_fd, 5) < 0) {
        perror ("listen");
580
        goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
581
    }
582 583 584

    if (ff_socket_nonblock(server_fd, 1) < 0)
        av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
585 586

    return server_fd;
587 588 589 590

fail:
    closesocket(server_fd);
    return -1;
591 592
}

593 594 595
/* start all multicast streams */
static void start_multicast(void)
{
596
    FFServerStream *stream;
597 598
    char session_id[32];
    HTTPContext *rtp_c;
599
    struct sockaddr_in dest_addr = {0};
600
    int default_port, stream_index;
601
    unsigned int random0, random1;
602 603

    default_port = 6000;
604
    for(stream = config.first_stream; stream; stream = stream->next) {
605

606 607
        if (!stream->is_multicast)
            continue;
608

609 610 611 612
        random0 = av_lfg_get(&random_state);
        random1 = av_lfg_get(&random_state);

        /* open the RTP connection */
613
        snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

        /* choose a port if none given */
        if (stream->multicast_port == 0) {
            stream->multicast_port = default_port;
            default_port += 100;
        }

        dest_addr.sin_family = AF_INET;
        dest_addr.sin_addr = stream->multicast_ip;
        dest_addr.sin_port = htons(stream->multicast_port);

        rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
                                   RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
        if (!rtp_c)
            continue;

        if (open_input_stream(rtp_c, "") < 0) {
            http_log("Could not open input stream for stream '%s'\n",
                     stream->filename);
            continue;
        }

        /* open each RTP stream */
        for(stream_index = 0; stream_index < stream->nb_streams;
            stream_index++) {
            dest_addr.sin_port = htons(stream->multicast_port +
                                       2 * stream_index);
            if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
642
                continue;
643 644 645 646 647 648 649

            http_log("Could not open output stream '%s/streamid=%d'\n",
                     stream->filename, stream_index);
            exit(1);
        }

        rtp_c->state = HTTPSTATE_SEND_DATA;
650 651
    }
}
652

653
/* main loop of the HTTP server */
654 655
static int http_server(void)
{
656
    int server_fd = 0, rtsp_server_fd = 0;
657
    int ret, delay;
658
    struct pollfd *poll_table, *poll_entry;
659 660
    HTTPContext *c, *c_next;

661 662 663 664 665
    poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
                                  sizeof(*poll_table));
    if(!poll_table) {
        http_log("Impossible to allocate a poll table handling %d "
                 "connections.\n", config.nb_max_http_connections);
666 667 668
        return -1;
    }

669 670
    if (config.http_addr.sin_port) {
        server_fd = socket_open_listen(&config.http_addr);
671 672
        if (server_fd < 0)
            goto quit;
673
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
674

675 676
    if (config.rtsp_addr.sin_port) {
        rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
677 678
        if (rtsp_server_fd < 0) {
            closesocket(server_fd);
679
            goto quit;
680
        }
681 682 683 684
    }

    if (!rtsp_server_fd && !server_fd) {
        http_log("HTTP and RTSP disabled.\n");
685
        goto quit;
686
    }
687

688
    http_log("FFserver started.\n");
Fabrice Bellard's avatar
Fabrice Bellard committed
689

690
    start_children(config.first_feed);
691

692 693
    start_multicast();

Fabrice Bellard's avatar
Fabrice Bellard committed
694 695
    for(;;) {
        poll_entry = poll_table;
696
        if (server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
697 698 699
            poll_entry->fd = server_fd;
            poll_entry->events = POLLIN;
            poll_entry++;
700 701
        }
        if (rtsp_server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
702 703 704
            poll_entry->fd = rtsp_server_fd;
            poll_entry->events = POLLIN;
            poll_entry++;
705
        }
706

Fabrice Bellard's avatar
Fabrice Bellard committed
707 708
        /* wait for events on each HTTP handle */
        c = first_http_ctx;
709
        delay = 1000;
710
        while (c) {
Fabrice Bellard's avatar
Fabrice Bellard committed
711 712 713
            int fd;
            fd = c->fd;
            switch(c->state) {
714 715
            case HTTPSTATE_SEND_HEADER:
            case RTSPSTATE_SEND_REPLY:
716
            case RTSPSTATE_SEND_PACKET:
Fabrice Bellard's avatar
Fabrice Bellard committed
717 718
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
719
                poll_entry->events = POLLOUT;
Fabrice Bellard's avatar
Fabrice Bellard committed
720 721 722 723 724
                poll_entry++;
                break;
            case HTTPSTATE_SEND_DATA_HEADER:
            case HTTPSTATE_SEND_DATA:
            case HTTPSTATE_SEND_DATA_TRAILER:
725
                if (!c->is_packetized) {
726 727
                    /* for TCP, we output as much as we can
                     * (may need to put a limit) */
728 729 730 731 732
                    c->poll_entry = poll_entry;
                    poll_entry->fd = fd;
                    poll_entry->events = POLLOUT;
                    poll_entry++;
                } else {
733
                    /* when ffserver is doing the timing, we work by
734 735
                     * looking at which packet needs to be sent every
                     * 10 ms (one tick wait XXX: 10 ms assumed) */
736 737
                    if (delay > 10)
                        delay = 10;
738
                }
Fabrice Bellard's avatar
Fabrice Bellard committed
739
                break;
740
            case HTTPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
Fabrice Bellard committed
741 742
            case HTTPSTATE_RECEIVE_DATA:
            case HTTPSTATE_WAIT_FEED:
743
            case RTSPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
Fabrice Bellard committed
744 745 746
                /* need to catch errors */
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
747
                poll_entry->events = POLLIN;/* Maybe this will work */
Fabrice Bellard's avatar
Fabrice Bellard committed
748 749 750 751 752 753 754 755 756 757
                poll_entry++;
                break;
            default:
                c->poll_entry = NULL;
                break;
            }
            c = c->next;
        }

        /* wait for an event on one connection. We poll at least every
758
         * second to handle timeouts */
Fabrice Bellard's avatar
Fabrice Bellard committed
759
        do {
760
            ret = poll(poll_table, poll_entry - poll_table, delay);
761
            if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
762
                ff_neterrno() != AVERROR(EINTR)) {
763
                goto quit;
764
            }
765
        } while (ret < 0);
766

767
        cur_time = av_gettime() / 1000;
Fabrice Bellard's avatar
Fabrice Bellard committed
768

769 770
        if (need_to_start_children) {
            need_to_start_children = 0;
771
            start_children(config.first_feed);
772 773
        }

Fabrice Bellard's avatar
Fabrice Bellard committed
774
        /* now handle the events */
775
        for(c = first_http_ctx; c; c = c_next) {
776 777
            c_next = c->next;
            if (handle_connection(c) < 0) {
778
                log_connection(c);
779
                /* close and free the connection */
780
                close_connection(c);
Fabrice Bellard's avatar
Fabrice Bellard committed
781 782 783 784
            }
        }

        poll_entry = poll_table;
785
        if (server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
786 787 788 789
            /* new HTTP connection request ? */
            if (poll_entry->revents & POLLIN)
                new_connection(server_fd, 0);
            poll_entry++;
790 791
        }
        if (rtsp_server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
792 793 794
            /* new RTSP connection request ? */
            if (poll_entry->revents & POLLIN)
                new_connection(rtsp_server_fd, 1);
795
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
796
    }
797 798 799 800

quit:
    av_free(poll_table);
    return -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
801 802
}

803 804
/* start waiting for a new HTTP/RTSP request */
static void start_wait_request(HTTPContext *c, int is_rtsp)
Fabrice Bellard's avatar
Fabrice Bellard committed
805
{
806 807 808
    c->buffer_ptr = c->buffer;
    c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */

809 810
    c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
    c->timeout = cur_time +
811
                 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
812 813
}

814 815
static void http_send_too_busy_reply(int fd)
{
816
    char buffer[400];
817
    int len = snprintf(buffer, sizeof(buffer),
818
                       "HTTP/1.0 503 Server too busy\r\n"
819 820
                       "Content-type: text/html\r\n"
                       "\r\n"
821
                       "<!DOCTYPE html>\n"
822
                       "<html><head><title>Too busy</title></head><body>\r\n"
823 824 825 826
                       "<p>The server is too busy to serve your request at "
                       "this time.</p>\r\n"
                       "<p>The number of current connections is %u, and this "
                       "exceeds the limit of %u.</p>\r\n"
827
                       "</body></html>\r\n",
828
                       nb_connections, config.nb_max_connections);
829
    av_assert0(len < sizeof(buffer));
830
    if (send(fd, buffer, len, 0) < len)
831 832
        av_log(NULL, AV_LOG_WARNING,
               "Could not send too-busy reply, send() failed\n");
833 834 835
}


836 837 838
static void new_connection(int server_fd, int is_rtsp)
{
    struct sockaddr_in from_addr;
839 840
    socklen_t len;
    int fd;
841 842 843
    HTTPContext *c = NULL;

    len = sizeof(from_addr);
844
    fd = accept(server_fd, (struct sockaddr *)&from_addr,
845
                &len);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
846 847
    if (fd < 0) {
        http_log("error during accept %s\n", strerror(errno));
848
        return;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
849
    }
850 851
    if (ff_socket_nonblock(fd, 1) < 0)
        av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
852

853
    if (nb_connections >= config.nb_max_connections) {
854
        http_send_too_busy_reply(fd);
855
        goto fail;
856
    }
857

858 859 860 861
    /* add a new connection */
    c = av_mallocz(sizeof(HTTPContext));
    if (!c)
        goto fail;
862

863 864 865 866 867 868 869
    c->fd = fd;
    c->poll_entry = NULL;
    c->from_addr = from_addr;
    c->buffer_size = IOBUFFER_INIT_SIZE;
    c->buffer = av_malloc(c->buffer_size);
    if (!c->buffer)
        goto fail;
870 871 872

    c->next = first_http_ctx;
    first_http_ctx = c;
873
    nb_connections++;
874

875 876 877 878 879 880
    start_wait_request(c, is_rtsp);

    return;

 fail:
    if (c) {
881
        av_freep(&c->buffer);
882 883
        av_free(c);
    }
884
    closesocket(fd);
885 886 887 888 889 890 891 892 893 894 895
}

static void close_connection(HTTPContext *c)
{
    HTTPContext **cp, *c1;
    int i, nb_streams;
    AVFormatContext *ctx;
    AVStream *st;

    /* remove connection from list */
    cp = &first_http_ctx;
896
    while (*cp) {
897
        c1 = *cp;
898
        if (c1 == c)
899
            *cp = c->next;
900
        else
901 902 903
            cp = &c1->next;
    }

904
    /* remove references, if any (XXX: do it faster) */
905
    for(c1 = first_http_ctx; c1; c1 = c1->next) {
906 907 908 909
        if (c1->rtsp_c == c)
            c1->rtsp_c = NULL;
    }

910 911
    /* remove connection associated resources */
    if (c->fd >= 0)
912
        closesocket(c->fd);
913 914 915 916
    if (c->fmt_in) {
        /* close each frame parser */
        for(i=0;i<c->fmt_in->nb_streams;i++) {
            st = c->fmt_in->streams[i];
917
            if (st->codec->codec)
918
                avcodec_close(st->codec);
919
        }
920
        avformat_close_input(&c->fmt_in);
921 922 923 924
    }

    /* free RTP output streams if any */
    nb_streams = 0;
925
    if (c->stream)
926
        nb_streams = c->stream->nb_streams;
927

928 929 930 931
    for(i=0;i<nb_streams;i++) {
        ctx = c->rtp_ctx[i];
        if (ctx) {
            av_write_trailer(ctx);
932
            av_dict_free(&ctx->metadata);
933 934
            av_freep(&ctx->streams[0]);
            av_freep(&ctx);
935
        }
936
        ffurl_close(c->rtp_handles[i]);
937
    }
938

939 940
    ctx = &c->fmt_ctx;

941
    if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
942 943 944 945 946
        /* prepare header */
        if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
            av_write_trailer(ctx);
            av_freep(&c->pb_buffer);
            avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
947 948 949
        }
    }

950
    for(i=0; i<ctx->nb_streams; i++)
951
        av_freep(&ctx->streams[i]);
952 953
    av_freep(&ctx->streams);
    av_freep(&ctx->priv_data);
954

955
    if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
956
        current_bandwidth -= c->stream->bandwidth;
957 958 959 960 961 962 963

    /* signal that there is no feed if we are the feeder socket */
    if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
        c->stream->feed_opened = 0;
        close(c->feed_fd);
    }

964
    av_freep(&c->pb_buffer);
965
    av_freep(&c->packet_buffer);
966
    av_freep(&c->buffer);
967 968 969 970 971 972 973
    av_free(c);
    nb_connections--;
}

static int handle_connection(HTTPContext *c)
{
    int len, ret;
974
    uint8_t *ptr;
975

Fabrice Bellard's avatar
Fabrice Bellard committed
976 977
    switch(c->state) {
    case HTTPSTATE_WAIT_REQUEST:
978
    case RTSPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
Fabrice Bellard committed
979 980 981 982 983 984 985 986 987 988
        /* timeout ? */
        if ((c->timeout - cur_time) < 0)
            return -1;
        if (c->poll_entry->revents & (POLLERR | POLLHUP))
            return -1;

        /* no need to read if no events */
        if (!(c->poll_entry->revents & POLLIN))
            return 0;
        /* read the data */
989
    read_loop:
990 991 992
        if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
            return -1;

Fabrice Bellard's avatar
Fabrice Bellard committed
993
        if (len < 0) {
994 995
            if (ff_neterrno() != AVERROR(EAGAIN) &&
                ff_neterrno() != AVERROR(EINTR))
Fabrice Bellard's avatar
Fabrice Bellard committed
996
                return -1;
997 998
            break;
        }
999 1000 1001 1002 1003 1004
        /* search for end of request. */
        c->buffer_ptr += len;
        ptr = c->buffer_ptr;
        if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
            (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
            /* request found : parse it and reply */
1005
            if (c->state == HTTPSTATE_WAIT_REQUEST)
1006
                ret = http_parse_request(c);
1007
            else
1008
                ret = rtsp_parse_request(c);
1009

1010
            if (ret < 0)
Fabrice Bellard's avatar
Fabrice Bellard committed
1011
                return -1;
1012 1013 1014 1015
        } else if (ptr >= c->buffer_end) {
            /* request too long: cannot do anything */
            return -1;
        } else goto read_loop;
1016

Fabrice Bellard's avatar
Fabrice Bellard committed
1017 1018 1019 1020 1021 1022
        break;

    case HTTPSTATE_SEND_HEADER:
        if (c->poll_entry->revents & (POLLERR | POLLHUP))
            return -1;

1023
        /* no need to write if no events */
Fabrice Bellard's avatar
Fabrice Bellard committed
1024 1025
        if (!(c->poll_entry->revents & POLLOUT))
            return 0;
1026
        len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
1027
        if (len < 0) {
1028 1029
            if (ff_neterrno() != AVERROR(EAGAIN) &&
                ff_neterrno() != AVERROR(EINTR)) {
1030
                goto close_connection;
Fabrice Bellard's avatar
Fabrice Bellard committed
1031
            }
1032 1033
            break;
        }
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        c->buffer_ptr += len;
        if (c->stream)
            c->stream->bytes_served += len;
        c->data_count += len;
        if (c->buffer_ptr >= c->buffer_end) {
            av_freep(&c->pb_buffer);
            /* if error, exit */
            if (c->http_error)
                return -1;
            /* all the buffer was sent : synchronize to the incoming
             * stream */
            c->state = HTTPSTATE_SEND_DATA_HEADER;
            c->buffer_ptr = c->buffer_end = c->buffer;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
1048 1049 1050 1051 1052
        break;

    case HTTPSTATE_SEND_DATA:
    case HTTPSTATE_SEND_DATA_HEADER:
    case HTTPSTATE_SEND_DATA_TRAILER:
1053
        /* for packetized output, we consider we can always write (the
1054 1055
         * input streams set the speed). It may be better to verify
         * that we do not rely too much on the kernel queues */
1056 1057 1058
        if (!c->is_packetized) {
            if (c->poll_entry->revents & (POLLERR | POLLHUP))
                return -1;
1059

1060 1061 1062 1063
            /* no need to read if no events */
            if (!(c->poll_entry->revents & POLLOUT))
                return 0;
        }
1064
        if (http_send_data(c) < 0)
Fabrice Bellard's avatar
Fabrice Bellard committed
1065
            return -1;
1066 1067 1068
        /* close connection if trailer sent */
        if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
            return -1;
1069 1070 1071 1072
        /* Check if it is a single jpeg frame 123 */
        if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
            close_connection(c);
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        break;
    case HTTPSTATE_RECEIVE_DATA:
        /* no need to read if no events */
        if (c->poll_entry->revents & (POLLERR | POLLHUP))
            return -1;
        if (!(c->poll_entry->revents & POLLIN))
            return 0;
        if (http_receive_data(c) < 0)
            return -1;
        break;
    case HTTPSTATE_WAIT_FEED:
        /* no need to read if no events */
1085
        if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
Fabrice Bellard's avatar
Fabrice Bellard committed
1086 1087 1088 1089
            return -1;

        /* nothing to do, we'll be waken up by incoming feed packets */
        break;
1090 1091

    case RTSPSTATE_SEND_REPLY:
1092 1093
        if (c->poll_entry->revents & (POLLERR | POLLHUP))
            goto close_connection;
1094 1095 1096
        /* no need to write if no events */
        if (!(c->poll_entry->revents & POLLOUT))
            return 0;
1097
        len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1098
        if (len < 0) {
1099 1100
            if (ff_neterrno() != AVERROR(EAGAIN) &&
                ff_neterrno() != AVERROR(EINTR)) {
1101
                goto close_connection;
1102
            }
1103 1104
            break;
        }
1105 1106 1107 1108 1109 1110 1111
        c->buffer_ptr += len;
        c->data_count += len;
        if (c->buffer_ptr >= c->buffer_end) {
            /* all the buffer was sent : wait for a new request */
            av_freep(&c->pb_buffer);
            start_wait_request(c, 1);
        }
1112
        break;
1113 1114 1115 1116 1117 1118 1119 1120
    case RTSPSTATE_SEND_PACKET:
        if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
            av_freep(&c->packet_buffer);
            return -1;
        }
        /* no need to write if no events */
        if (!(c->poll_entry->revents & POLLOUT))
            return 0;
1121 1122
        len = send(c->fd, c->packet_buffer_ptr,
                    c->packet_buffer_end - c->packet_buffer_ptr, 0);
1123
        if (len < 0) {
1124 1125
            if (ff_neterrno() != AVERROR(EAGAIN) &&
                ff_neterrno() != AVERROR(EINTR)) {
1126 1127 1128 1129
                /* error : close connection */
                av_freep(&c->packet_buffer);
                return -1;
            }
1130 1131
            break;
        }
1132 1133 1134 1135 1136 1137
        c->packet_buffer_ptr += len;
        if (c->packet_buffer_ptr >= c->packet_buffer_end) {
            /* all the buffer was sent : wait for a new request */
            av_freep(&c->packet_buffer);
            c->state = RTSPSTATE_WAIT_REQUEST;
        }
1138
        break;
1139 1140 1141
    case HTTPSTATE_READY:
        /* nothing to do */
        break;
Fabrice Bellard's avatar
Fabrice Bellard committed
1142 1143 1144 1145
    default:
        return -1;
    }
    return 0;
1146 1147 1148 1149

close_connection:
    av_freep(&c->pb_buffer);
    return -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
1150 1151
}

1152 1153 1154 1155 1156
static int extract_rates(char *rates, int ratelen, const char *request)
{
    const char *p;

    for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1157
        if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1158 1159
            const char *q = p + 7;

1160
            while