ffserver.c 155 KB
Newer Older
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
1 2
/*
 * Multiple format streaming server
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
11
 *
12
 * Libav is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
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
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
20
 */
21

22 23
#define _XOPEN_SOURCE 600

24
#include "config.h"
25
#if !HAVE_CLOSESOCKET
26 27 28
#define closesocket close
#endif
#include <string.h>
29
#include <strings.h>
30
#include <stdlib.h>
31
#include "libavformat/avformat.h"
32
#include "libavformat/ffm.h"
33 34
#include "libavformat/network.h"
#include "libavformat/os_support.h"
35
#include "libavformat/rtpdec.h"
36
#include "libavformat/rtsp.h"
37 38
// XXX for ffio_open_dyn_packet_buffer, to be removed
#include "libavformat/avio_internal.h"
39
#include "libavutil/avstring.h"
40 41
#include "libavutil/lfg.h"
#include "libavutil/random_seed.h"
42
#include "libavutil/parseutils.h"
43
#include "libavutil/opt.h"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
44 45 46 47
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
48
#if HAVE_POLL_H
49
#include <poll.h>
50
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
51 52 53
#include <errno.h>
#include <sys/time.h>
#include <time.h>
54
#include <sys/wait.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
55
#include <signal.h>
56
#if HAVE_DLFCN_H
57
#include <dlfcn.h>
58
#endif
59

60
#include "cmdutils.h"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
61

62
const char program_name[] = "FFserver";
63
const int program_birth_year = 2000;
64

65 66
static const OptionDef options[];

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
67 68 69 70
enum HTTPState {
    HTTPSTATE_WAIT_REQUEST,
    HTTPSTATE_SEND_HEADER,
    HTTPSTATE_SEND_DATA_HEADER,
71
    HTTPSTATE_SEND_DATA,          /* sending TCP or UDP data */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
72
    HTTPSTATE_SEND_DATA_TRAILER,
73
    HTTPSTATE_RECEIVE_DATA,
74 75 76 77 78
    HTTPSTATE_WAIT_FEED,          /* wait for data from the feed */
    HTTPSTATE_READY,

    RTSPSTATE_WAIT_REQUEST,
    RTSPSTATE_SEND_REPLY,
79
    RTSPSTATE_SEND_PACKET,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
80 81
};

Baptiste Coudurier's avatar
Baptiste Coudurier committed
82
static const char *http_state[] = {
83 84 85
    "HTTP_WAIT_REQUEST",
    "HTTP_SEND_HEADER",

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
86 87 88 89 90
    "SEND_DATA_HEADER",
    "SEND_DATA",
    "SEND_DATA_TRAILER",
    "RECEIVE_DATA",
    "WAIT_FEED",
91 92 93 94
    "READY",

    "RTSP_WAIT_REQUEST",
    "RTSP_SEND_REPLY",
95
    "RTSP_SEND_PACKET",
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
96 97
};

98 99
#define MAX_STREAMS 20

Philip Gladstone's avatar
Philip Gladstone committed
100
#define IOBUFFER_INIT_SIZE 8192
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
101 102

/* timeouts are in ms */
103 104 105
#define HTTP_REQUEST_TIMEOUT (15 * 1000)
#define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
106 107
#define SYNC_TIMEOUT (10 * 1000)

108 109 110 111 112
typedef struct RTSPActionServerSetup {
    uint32_t ipaddr;
    char transport_option[512];
} RTSPActionServerSetup;

113
typedef struct {
114
    int64_t count1, count2;
115
    int64_t time1, time2;
116 117
} DataRateData;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
118 119 120 121 122 123
/* 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 */
124
    int64_t timeout;
125
    uint8_t *buffer_ptr, *buffer_end;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
126
    int http_error;
127
    int post;
128 129
    int chunked_encoding;
    int chunk_size;               /* 0 if it needs to be read */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
130
    struct HTTPContext *next;
131
    int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
132
    int64_t data_count;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
133 134 135 136
    /* feed input */
    int feed_fd;
    /* input format handling */
    AVFormatContext *fmt_in;
137
    int64_t start_time;            /* In milliseconds - this wraps fairly often */
138
    int64_t first_pts;            /* initial pts value */
139 140 141 142 143 144 145
    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
merge  
Fabrice Bellard committed
146 147
    /* output format handling */
    struct FFStream *stream;
Philip Gladstone's avatar
Philip Gladstone committed
148 149 150 151
    /* -1 is invalid stream */
    int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
    int switch_feed_streams[MAX_STREAMS]; /* index of streams in the feed */
    int switch_pending;
152
    AVFormatContext fmt_ctx; /* instance of FFStream for one user */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
153
    int last_packet_sent; /* true if last data packet was sent */
154
    int suppress_log;
155
    DataRateData datarate;
156
    int wmp_client_id;
157 158 159
    char protocol[16];
    char method[16];
    char url[128];
Philip Gladstone's avatar
Philip Gladstone committed
160
    int buffer_size;
161
    uint8_t *buffer;
162 163
    int is_packetized; /* if true, the stream is packetized */
    int packet_stream_index; /* current stream for output in state machine */
164

165
    /* RTSP state specific */
166
    uint8_t *pb_buffer; /* XXX: use that in all the code */
167
    AVIOContext *pb;
168
    int seq; /* RTSP sequence number */
169

170
    /* RTP state specific */
171
    enum RTSPLowerTransport rtp_protocol;
172 173
    char session_id[32]; /* session id */
    AVFormatContext *rtp_ctx[MAX_STREAMS];
174

175 176 177 178 179 180
    /* RTP/UDP specific */
    URLContext *rtp_handles[MAX_STREAMS];

    /* RTP/TCP specific */
    struct HTTPContext *rtsp_c;
    uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
181 182 183 184 185 186
} HTTPContext;

/* each generated stream is described here */
enum StreamType {
    STREAM_TYPE_LIVE,
    STREAM_TYPE_STATUS,
Philip Gladstone's avatar
Philip Gladstone committed
187
    STREAM_TYPE_REDIRECT,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
188 189
};

190 191 192 193 194 195 196 197
enum IPAddressAction {
    IP_ALLOW = 1,
    IP_DENY,
};

typedef struct IPAddressACL {
    struct IPAddressACL *next;
    enum IPAddressAction action;
198
    /* These are in host order */
199 200 201 202
    struct in_addr first;
    struct in_addr last;
} IPAddressACL;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
203 204 205 206
/* description of each stream of the ffserver.conf file */
typedef struct FFStream {
    enum StreamType stream_type;
    char filename[1024];     /* stream filename */
207 208
    struct FFStream *feed;   /* feed we are using (can be null if
                                coming from file) */
209 210
    AVFormatParameters *ap_in; /* input parameters */
    AVInputFormat *ifmt;       /* if non NULL, force input format */
211
    AVOutputFormat *fmt;
212
    IPAddressACL *acl;
213
    char dynamic_acl[1024];
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
214
    int nb_streams;
215
    int prebuffer;      /* Number of millseconds early to start */
216
    int64_t max_time;      /* Number of milliseconds to run */
217
    int send_on_key;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
218 219 220 221
    AVStream *streams[MAX_STREAMS];
    int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
    char feed_filename[1024]; /* file name of the feed storage, or
                                 input file name for a stream */
222 223 224 225
    char author[512];
    char title[512];
    char copyright[512];
    char comment[512];
Philip Gladstone's avatar
Philip Gladstone committed
226
    pid_t pid;  /* Of ffmpeg process */
227
    time_t pid_start;  /* Of ffmpeg process */
Philip Gladstone's avatar
Philip Gladstone committed
228
    char **child_argv;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
229
    struct FFStream *next;
230
    unsigned bandwidth; /* bandwidth, in kbits/s */
231 232
    /* RTSP options */
    char *rtsp_option;
233 234 235 236
    /* multicast specific */
    int is_multicast;
    struct in_addr multicast_ip;
    int multicast_port; /* first port used for multicast */
237 238
    int multicast_ttl;
    int loop; /* if true, send the stream in loops (only meaningful if file) */
239

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
240
    /* feed specific */
241
    int feed_opened;     /* true if someone is writing to the feed */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
242
    int is_feed;         /* true if it is a feed */
243
    int readonly;        /* True if writing is prohibited to the file */
244
    int truncate;        /* True if feeder connection truncate the feed file */
245
    int conns_served;
246
    int64_t bytes_served;
247
    int64_t feed_max_size;      /* maximum storage size, zero means unlimited */
Diego Biurrun's avatar
Diego Biurrun committed
248
    int64_t feed_write_index;   /* current write position in feed (it wraps around) */
249
    int64_t feed_size;          /* current size of feed */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
250 251 252 253 254
    struct FFStream *next_feed;
} FFStream;

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

258 259
static struct sockaddr_in my_http_addr;
static struct sockaddr_in my_rtsp_addr;
260

261 262 263 264
static char logfilename[1024];
static HTTPContext *first_http_ctx;
static FFStream *first_feed;   /* contains only feeds */
static FFStream *first_stream; /* contains all streams, including feeds */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
265

266 267 268 269 270
static void new_connection(int server_fd, int is_rtsp);
static void close_connection(HTTPContext *c);

/* HTTP handling */
static int handle_connection(HTTPContext *c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
271
static int http_parse_request(HTTPContext *c);
272
static int http_send_data(HTTPContext *c);
273
static void compute_status(HTTPContext *c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
274 275 276
static int open_input_stream(HTTPContext *c, const char *info);
static int http_start_receive_data(HTTPContext *c);
static int http_receive_data(HTTPContext *c);
277 278 279 280

/* RTSP handling */
static int rtsp_parse_request(HTTPContext *c);
static void rtsp_cmd_describe(HTTPContext *c, const char *url);
281
static void rtsp_cmd_options(HTTPContext *c, const char *url);
282 283 284 285
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_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h);
static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h);
286

287
/* SDP handling */
288
static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
289 290
                                   struct in_addr my_ip);

291
/* RTP handling */
292
static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
293
                                       FFStream *stream, const char *session_id,
294
                                       enum RTSPLowerTransport rtp_protocol);
295
static int rtp_new_av_stream(HTTPContext *c,
296 297
                             int stream_index, struct sockaddr_in *dest_addr,
                             HTTPContext *rtsp_c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
298

Philip Gladstone's avatar
Philip Gladstone committed
299
static const char *my_program_name;
300
static const char *my_program_dir;
Philip Gladstone's avatar
Philip Gladstone committed
301

302 303
static const char *config_filename = "/etc/ffserver.conf";

304
static int ffserver_debug;
305
static int ffserver_daemon;
306
static int no_launch;
307
static int need_to_start_children;
308

309 310
/* maximum number of simultaneous HTTP connections */
static unsigned int nb_max_http_connections = 2000;
311 312
static unsigned int nb_max_connections = 5;
static unsigned int nb_connections;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
313

314
static uint64_t max_bandwidth = 1000;
315
static uint64_t current_bandwidth;
316

317
static int64_t cur_time;           // Making this global saves on passing it around everywhere
318

319
static AVLFG random_state;
320

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
321 322
static FILE *logfile = NULL;

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
/* FIXME: make ffserver work with IPv6 */
/* resolve host with also IP address parsing */
static int resolve_host(struct in_addr *sin_addr, const char *hostname)
{

    if (!ff_inet_aton(hostname, sin_addr)) {
#if HAVE_GETADDRINFO
        struct addrinfo *ai, *cur;
        struct addrinfo hints;
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = AF_INET;
        if (getaddrinfo(hostname, NULL, &hints, &ai))
            return -1;
        /* getaddrinfo returns a linked list of addrinfo structs.
         * Even if we set ai_family = AF_INET above, make sure
         * that the returned one actually is of the correct type. */
        for (cur = ai; cur; cur = cur->ai_next) {
            if (cur->ai_family == AF_INET) {
                *sin_addr = ((struct sockaddr_in *)cur->ai_addr)->sin_addr;
                freeaddrinfo(ai);
                return 0;
            }
        }
        freeaddrinfo(ai);
        return -1;
#else
        struct hostent *hp;
        hp = gethostbyname(hostname);
        if (!hp)
            return -1;
        memcpy(sin_addr, hp->h_addr_list[0], sizeof(struct in_addr));
#endif
    }
    return 0;
}

Baptiste Coudurier's avatar
Baptiste Coudurier committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372
static char *ctime1(char *buf2)
{
    time_t ti;
    char *p;

    ti = time(NULL);
    p = ctime(&ti);
    strcpy(buf2, p);
    p = buf2 + strlen(p) - 1;
    if (*p == '\n')
        *p = '\0';
    return buf2;
}

Baptiste Coudurier's avatar
Baptiste Coudurier committed
373
static void http_vlog(const char *fmt, va_list vargs)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
374
{
Baptiste Coudurier's avatar
Baptiste Coudurier committed
375
    static int print_prefix = 1;
376
    if (logfile) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
377
        if (print_prefix) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
378 379 380
            char buf[32];
            ctime1(buf);
            fprintf(logfile, "%s ", buf);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
381 382
        }
        print_prefix = strstr(fmt, "\n") != NULL;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
383
        vfprintf(logfile, fmt, vargs);
384 385
        fflush(logfile);
    }
Baptiste Coudurier's avatar
Baptiste Coudurier committed
386 387
}

388 389 390 391
#ifdef __GNUC__
__attribute__ ((format (printf, 1, 2)))
#endif
static void http_log(const char *fmt, ...)
Baptiste Coudurier's avatar
Baptiste Coudurier committed
392 393 394 395 396 397 398 399 400 401 402
{
    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;
403
    if (level > av_log_get_level())
Baptiste Coudurier's avatar
Baptiste Coudurier committed
404 405
        return;
    if (print_prefix && avc)
406
        http_log("[%s @ %p]", avc->item_name(ptr), ptr);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
407 408
    print_prefix = strstr(fmt, "\n") != NULL;
    http_vlog(fmt, vargs);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
409 410
}

411 412
static void log_connection(HTTPContext *c)
{
413
    if (c->suppress_log)
414 415
        return;

416 417
    http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
             inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
418
             c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
Philip Gladstone's avatar
Philip Gladstone committed
419 420
}

421
static void update_datarate(DataRateData *drd, int64_t count)
422 423 424 425
{
    if (!drd->time1 && !drd->count1) {
        drd->time1 = drd->time2 = cur_time;
        drd->count1 = drd->count2 = count;
426
    } else if (cur_time - drd->time2 > 5000) {
Alex Beregszaszi's avatar
Alex Beregszaszi committed
427 428 429 430
        drd->time1 = drd->time2;
        drd->count1 = drd->count2;
        drd->time2 = cur_time;
        drd->count2 = count;
431 432 433 434
    }
}

/* In bytes per second */
435
static int compute_datarate(DataRateData *drd, int64_t count)
436 437 438
{
    if (cur_time == drd->time1)
        return 0;
439

440 441 442
    return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
}

443

Philip Gladstone's avatar
Philip Gladstone committed
444 445
static void start_children(FFStream *feed)
{
446 447 448
    if (no_launch)
        return;

Philip Gladstone's avatar
Philip Gladstone committed
449
    for (; feed; feed = feed->next) {
450 451 452
        if (feed->child_argv && !feed->pid) {
            feed->pid_start = time(0);

Philip Gladstone's avatar
Philip Gladstone committed
453 454 455
            feed->pid = fork();

            if (feed->pid < 0) {
456
                http_log("Unable to create children\n");
Philip Gladstone's avatar
Philip Gladstone committed
457 458 459 460 461 462 463 464
                exit(1);
            }
            if (!feed->pid) {
                /* In child */
                char pathname[1024];
                char *slash;
                int i;

465 466 467 468 469 470 471 472 473
                av_strlcpy(pathname, my_program_name, sizeof(pathname));

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

Stefano Sabatini's avatar
Stefano Sabatini committed
474 475 476 477 478
                http_log("Launch commandline: ");
                http_log("%s ", pathname);
                for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
                    http_log("%s ", feed->child_argv[i]);
                http_log("\n");
479

480
                for (i = 3; i < 256; i++)
481
                    close(i);
Philip Gladstone's avatar
Philip Gladstone committed
482

483
                if (!ffserver_debug) {
484
                    i = open("/dev/null", O_RDWR);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
485
                    if (i != -1) {
486
                        dup2(i, 0);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
487 488
                        dup2(i, 1);
                        dup2(i, 2);
489
                        close(i);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
490
                    }
491
                }
Philip Gladstone's avatar
Philip Gladstone committed
492

493 494 495
                /* This is needed to make relative pathnames work */
                chdir(my_program_dir);

496 497
                signal(SIGPIPE, SIG_DFL);

Philip Gladstone's avatar
Philip Gladstone committed
498 499 500 501 502 503
                execvp(pathname, feed->child_argv);

                _exit(1);
            }
        }
    }
504 505
}

506 507
/* open a listening socket */
static int socket_open_listen(struct sockaddr_in *my_addr)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
508
{
509
    int server_fd, tmp;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
510 511 512 513 514 515

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
517 518 519
    tmp = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));

520
    if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
521 522 523
        char bindmsg[32];
        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
        perror (bindmsg);
524
        closesocket(server_fd);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
525 526
        return -1;
    }
527

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
528 529
    if (listen (server_fd, 5) < 0) {
        perror ("listen");
530
        closesocket(server_fd);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
531 532
        return -1;
    }
533
    ff_socket_nonblock(server_fd, 1);
534 535 536 537

    return server_fd;
}

538 539 540 541 542 543 544 545 546 547 548 549 550
/* start all multicast streams */
static void start_multicast(void)
{
    FFStream *stream;
    char session_id[32];
    HTTPContext *rtp_c;
    struct sockaddr_in dest_addr;
    int default_port, stream_index;

    default_port = 6000;
    for(stream = first_stream; stream != NULL; stream = stream->next) {
        if (stream->is_multicast) {
            /* open the RTP connection */
551
            snprintf(session_id, sizeof(session_id), "%08x%08x",
552
                     av_lfg_get(&random_state), av_lfg_get(&random_state));
553 554 555 556 557 558 559 560 561 562 563

            /* 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);

564
            rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
565
                                       RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
566
            if (!rtp_c)
567
                continue;
568

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

            /* open each RTP stream */
576
            for(stream_index = 0; stream_index < stream->nb_streams;
577
                stream_index++) {
578
                dest_addr.sin_port = htons(stream->multicast_port +
579
                                           2 * stream_index);
580
                if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
581 582
                    http_log("Could not open output stream '%s/streamid=%d'\n",
                             stream->filename, stream_index);
583
                    exit(1);
584 585 586 587 588 589 590 591
                }
            }

            /* change state to send data */
            rtp_c->state = HTTPSTATE_SEND_DATA;
        }
    }
}
592 593 594 595

/* main loop of the http server */
static int http_server(void)
{
Baptiste Coudurier's avatar
Baptiste Coudurier committed
596 597
    int server_fd = 0, rtsp_server_fd = 0;
    int ret, delay, delay1;
598
    struct pollfd *poll_table, *poll_entry;
599 600
    HTTPContext *c, *c_next;

601
    if(!(poll_table = av_mallocz((nb_max_http_connections + 2)*sizeof(*poll_table)))) {
602 603 604 605
        http_log("Impossible to allocate a poll table handling %d connections.\n", nb_max_http_connections);
        return -1;
    }

Baptiste Coudurier's avatar
Baptiste Coudurier committed
606
    if (my_http_addr.sin_port) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
607 608 609
        server_fd = socket_open_listen(&my_http_addr);
        if (server_fd < 0)
            return -1;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
610
    }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
611

Baptiste Coudurier's avatar
Baptiste Coudurier committed
612
    if (my_rtsp_addr.sin_port) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
613 614 615
        rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
        if (rtsp_server_fd < 0)
            return -1;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
616 617 618 619 620 621
    }

    if (!rtsp_server_fd && !server_fd) {
        http_log("HTTP and RTSP disabled.\n");
        return -1;
    }
622

623
    http_log("FFserver started.\n");
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
624

Philip Gladstone's avatar
Philip Gladstone committed
625 626
    start_children(first_feed);

627 628
    start_multicast();

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
629 630
    for(;;) {
        poll_entry = poll_table;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
631
        if (server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
632 633 634
            poll_entry->fd = server_fd;
            poll_entry->events = POLLIN;
            poll_entry++;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
635 636
        }
        if (rtsp_server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
637 638 639
            poll_entry->fd = rtsp_server_fd;
            poll_entry->events = POLLIN;
            poll_entry++;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
640
        }
641

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
642 643
        /* wait for events on each HTTP handle */
        c = first_http_ctx;
644
        delay = 1000;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
645 646 647 648
        while (c != NULL) {
            int fd;
            fd = c->fd;
            switch(c->state) {
649 650
            case HTTPSTATE_SEND_HEADER:
            case RTSPSTATE_SEND_REPLY:
651
            case RTSPSTATE_SEND_PACKET:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
652 653
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
654
                poll_entry->events = POLLOUT;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
655 656 657 658 659
                poll_entry++;
                break;
            case HTTPSTATE_SEND_DATA_HEADER:
            case HTTPSTATE_SEND_DATA:
            case HTTPSTATE_SEND_DATA_TRAILER:
660 661 662 663 664 665 666
                if (!c->is_packetized) {
                    /* for TCP, we output as much as we can (may need to put a limit) */
                    c->poll_entry = poll_entry;
                    poll_entry->fd = fd;
                    poll_entry->events = POLLOUT;
                    poll_entry++;
                } else {
667 668 669 670 671 672
                    /* when ffserver is doing the timing, we work by
                       looking at which packet need to be sent every
                       10 ms */
                    delay1 = 10; /* one tick wait XXX: 10 ms assumed */
                    if (delay1 < delay)
                        delay = delay1;
673
                }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
674
                break;
675
            case HTTPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
676 677
            case HTTPSTATE_RECEIVE_DATA:
            case HTTPSTATE_WAIT_FEED:
678
            case RTSPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
679 680 681
                /* need to catch errors */
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
682
                poll_entry->events = POLLIN;/* Maybe this will work */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
683 684 685 686 687 688 689 690 691 692 693 694
                poll_entry++;
                break;
            default:
                c->poll_entry = NULL;
                break;
            }
            c = c->next;
        }

        /* wait for an event on one connection. We poll at least every
           second to handle timeouts */
        do {
695
            ret = poll(poll_table, poll_entry - poll_table, delay);
696 697
            if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
                ff_neterrno() != AVERROR(EINTR))
698
                return -1;
699
        } while (ret < 0);
700

701
        cur_time = av_gettime() / 1000;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
702

703 704 705 706 707
        if (need_to_start_children) {
            need_to_start_children = 0;
            start_children(first_feed);
        }

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
708
        /* now handle the events */
709 710 711
        for(c = first_http_ctx; c != NULL; c = c_next) {
            c_next = c->next;
            if (handle_connection(c) < 0) {
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
712
                /* close and free the connection */
713
                log_connection(c);
714
                close_connection(c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
715 716 717 718
            }
        }

        poll_entry = poll_table;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
719
        if (server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
720 721 722 723
            /* new HTTP connection request ? */
            if (poll_entry->revents & POLLIN)
                new_connection(server_fd, 0);
            poll_entry++;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
724 725
        }
        if (rtsp_server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
726 727 728
            /* new RTSP connection request ? */
            if (poll_entry->revents & POLLIN)
                new_connection(rtsp_server_fd, 1);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
729
        }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
730 731 732
    }
}

733 734
/* start waiting for a new HTTP/RTSP request */
static void start_wait_request(HTTPContext *c, int is_rtsp)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
735
{
736 737 738 739 740 741 742 743 744 745 746 747
    c->buffer_ptr = c->buffer;
    c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */

    if (is_rtsp) {
        c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
        c->state = RTSPSTATE_WAIT_REQUEST;
    } else {
        c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
        c->state = HTTPSTATE_WAIT_REQUEST;
    }
}

748 749 750 751
static void http_send_too_busy_reply(int fd)
{
    char buffer[300];
    int len = snprintf(buffer, sizeof(buffer),
Howard Chu's avatar
Howard Chu committed
752
                       "HTTP/1.0 503 Server too busy\r\n"
753 754 755 756 757 758 759 760 761 762 763
                       "Content-type: text/html\r\n"
                       "\r\n"
                       "<html><head><title>Too busy</title></head><body>\r\n"
                       "<p>The server is too busy to serve your request at this time.</p>\r\n"
                       "<p>The number of current connections is %d, and this exceeds the limit of %d.</p>\r\n"
                       "</body></html>\r\n",
                       nb_connections, nb_max_connections);
    send(fd, buffer, len, 0);
}


764 765 766 767 768 769 770
static void new_connection(int server_fd, int is_rtsp)
{
    struct sockaddr_in from_addr;
    int fd, len;
    HTTPContext *c = NULL;

    len = sizeof(from_addr);
771
    fd = accept(server_fd, (struct sockaddr *)&from_addr,
772
                &len);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
773 774
    if (fd < 0) {
        http_log("error during accept %s\n", strerror(errno));
775
        return;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
776
    }
777
    ff_socket_nonblock(fd, 1);
778

779 780
    if (nb_connections >= nb_max_connections) {
        http_send_too_busy_reply(fd);
781
        goto fail;
782
    }
783

784 785 786 787
    /* add a new connection */
    c = av_mallocz(sizeof(HTTPContext));
    if (!c)
        goto fail;
788

789 790 791 792 793 794 795
    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;
796 797 798

    c->next = first_http_ctx;
    first_http_ctx = c;
799
    nb_connections++;
800

801 802 803 804 805 806 807 808 809
    start_wait_request(c, is_rtsp);

    return;

 fail:
    if (c) {
        av_free(c->buffer);
        av_free(c);
    }
810
    closesocket(fd);
811 812 813 814 815 816 817 818 819 820 821 822 823 824
}

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

    /* remove connection from list */
    cp = &first_http_ctx;
    while ((*cp) != NULL) {
        c1 = *cp;
825
        if (c1 == c)
826
            *cp = c->next;
827
        else
828 829 830
            cp = &c1->next;
    }

831 832 833 834 835 836
    /* remove references, if any (XXX: do it faster) */
    for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
        if (c1->rtsp_c == c)
            c1->rtsp_c = NULL;
    }

837 838
    /* remove connection associated resources */
    if (c->fd >= 0)
839
        closesocket(c->fd);
840 841 842 843
    if (c->fmt_in) {
        /* close each frame parser */
        for(i=0;i<c->fmt_in->nb_streams;i++) {
            st = c->fmt_in->streams[i];
844
            if (st->codec->codec)
845
                avcodec_close(st->codec);
846 847 848 849 850 851
        }
        av_close_input_file(c->fmt_in);
    }

    /* free RTP output streams if any */
    nb_streams = 0;