ffserver.c 152 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 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg 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
 * FFmpeg 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 FFmpeg; 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 HAVE_AV_CONFIG_H
#include "avformat.h"

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
24 25 26 27
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
28
#ifdef HAVE_SYS_POLL_H
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
29
#include <sys/poll.h>
30
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
31 32
#include <errno.h>
#include <sys/time.h>
33
#undef time //needed because HAVE_AV_CONFIG_H is defined on top
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
34 35 36
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
37
#include <sys/wait.h>
38
#include <netinet/in.h>
Michael Niedermayer's avatar
Michael Niedermayer committed
39
#include <arpa/inet.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
40 41
#include <netdb.h>
#include <signal.h>
42
#ifdef HAVE_DLFCN_H
43
#include <dlfcn.h>
44
#endif
45

46
#include "version.h"
47
#include "ffserver.h"
48
#include "random.h"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
49 50 51 52 53 54 55 56

/* maximum number of simultaneous HTTP connections */
#define HTTP_MAX_CONNECTIONS 2000

enum HTTPState {
    HTTPSTATE_WAIT_REQUEST,
    HTTPSTATE_SEND_HEADER,
    HTTPSTATE_SEND_DATA_HEADER,
57
    HTTPSTATE_SEND_DATA,          /* sending TCP or UDP data */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
58
    HTTPSTATE_SEND_DATA_TRAILER,
59
    HTTPSTATE_RECEIVE_DATA,
60 61 62 63 64
    HTTPSTATE_WAIT_FEED,          /* wait for data from the feed */
    HTTPSTATE_READY,

    RTSPSTATE_WAIT_REQUEST,
    RTSPSTATE_SEND_REPLY,
65
    RTSPSTATE_SEND_PACKET,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
66 67 68
};

const char *http_state[] = {
69 70 71
    "HTTP_WAIT_REQUEST",
    "HTTP_SEND_HEADER",

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
72 73 74 75 76
    "SEND_DATA_HEADER",
    "SEND_DATA",
    "SEND_DATA_TRAILER",
    "RECEIVE_DATA",
    "WAIT_FEED",
77 78 79 80
    "READY",

    "RTSP_WAIT_REQUEST",
    "RTSP_SEND_REPLY",
81
    "RTSP_SEND_PACKET",
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
82 83
};

Philip Gladstone's avatar
Philip Gladstone committed
84
#define IOBUFFER_INIT_SIZE 8192
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
85 86 87 88 89

/* coef for exponential mean for bitrate estimation in statistics */
#define AVG_COEF 0.9

/* timeouts are in ms */
90 91 92
#define HTTP_REQUEST_TIMEOUT (15 * 1000)
#define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
93 94
#define SYNC_TIMEOUT (10 * 1000)

95
typedef struct {
96
    int64_t count1, count2;
97 98 99
    long time1, time2;
} DataRateData;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
100 101 102 103 104 105 106
/* 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 */
    long timeout;
107
    uint8_t *buffer_ptr, *buffer_end;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
108
    int http_error;
109
    int post;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
110
    struct HTTPContext *next;
111
    int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
112
    int64_t data_count;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
113 114 115 116
    /* feed input */
    int feed_fd;
    /* input format handling */
    AVFormatContext *fmt_in;
117
    long start_time;            /* In milliseconds - this wraps fairly often */
118
    int64_t first_pts;            /* initial pts value */
119 120 121 122 123 124 125
    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
126 127
    /* output format handling */
    struct FFStream *stream;
Philip Gladstone's avatar
Philip Gladstone committed
128 129 130 131
    /* -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;
132
    AVFormatContext fmt_ctx; /* instance of FFStream for one user */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
133
    int last_packet_sent; /* true if last data packet was sent */
134
    int suppress_log;
135
    DataRateData datarate;
136
    int wmp_client_id;
137 138 139
    char protocol[16];
    char method[16];
    char url[128];
Philip Gladstone's avatar
Philip Gladstone committed
140
    int buffer_size;
141
    uint8_t *buffer;
142 143
    int is_packetized; /* if true, the stream is packetized */
    int packet_stream_index; /* current stream for output in state machine */
144

145
    /* RTSP state specific */
146
    uint8_t *pb_buffer; /* XXX: use that in all the code */
147 148
    ByteIOContext *pb;
    int seq; /* RTSP sequence number */
149

150 151 152 153
    /* RTP state specific */
    enum RTSPProtocol rtp_protocol;
    char session_id[32]; /* session id */
    AVFormatContext *rtp_ctx[MAX_STREAMS];
154

155 156 157 158 159 160
    /* 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
161 162
} HTTPContext;

163 164
static AVFrame dummy_frame;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
165 166 167 168
/* each generated stream is described here */
enum StreamType {
    STREAM_TYPE_LIVE,
    STREAM_TYPE_STATUS,
Philip Gladstone's avatar
Philip Gladstone committed
169
    STREAM_TYPE_REDIRECT,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
170 171
};

172 173 174 175 176 177 178 179
enum IPAddressAction {
    IP_ALLOW = 1,
    IP_DENY,
};

typedef struct IPAddressACL {
    struct IPAddressACL *next;
    enum IPAddressAction action;
180
    /* These are in host order */
181 182 183 184
    struct in_addr first;
    struct in_addr last;
} IPAddressACL;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
185 186 187 188
/* description of each stream of the ffserver.conf file */
typedef struct FFStream {
    enum StreamType stream_type;
    char filename[1024];     /* stream filename */
189 190
    struct FFStream *feed;   /* feed we are using (can be null if
                                coming from file) */
191 192
    AVFormatParameters *ap_in; /* input parameters */
    AVInputFormat *ifmt;       /* if non NULL, force input format */
193
    AVOutputFormat *fmt;
194
    IPAddressACL *acl;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
195
    int nb_streams;
196
    int prebuffer;      /* Number of millseconds early to start */
197
    long max_time;      /* Number of milliseconds to run */
198
    int send_on_key;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
199 200 201 202
    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 */
203 204 205 206
    char author[512];
    char title[512];
    char copyright[512];
    char comment[512];
Philip Gladstone's avatar
Philip Gladstone committed
207
    pid_t pid;  /* Of ffmpeg process */
208
    time_t pid_start;  /* Of ffmpeg process */
Philip Gladstone's avatar
Philip Gladstone committed
209
    char **child_argv;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
210
    struct FFStream *next;
211
    int bandwidth; /* bandwidth, in kbits/s */
212 213
    /* RTSP options */
    char *rtsp_option;
214 215 216 217
    /* multicast specific */
    int is_multicast;
    struct in_addr multicast_ip;
    int multicast_port; /* first port used for multicast */
218 219
    int multicast_ttl;
    int loop; /* if true, send the stream in loops (only meaningful if file) */
220

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
221
    /* feed specific */
222
    int feed_opened;     /* true if someone is writing to the feed */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
223
    int is_feed;         /* true if it is a feed */
224
    int readonly;        /* True if writing is prohibited to the file */
225
    int conns_served;
226
    int64_t bytes_served;
227
    int64_t feed_max_size;      /* maximum storage size, zero means unlimited */
228 229
    int64_t feed_write_index;   /* current write position in feed (it wraps round) */
    int64_t feed_size;          /* current size of feed */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
230 231 232 233 234 235 236 237
    struct FFStream *next_feed;
} FFStream;

typedef struct FeedData {
    long long data_count;
    float avg_frame_size;   /* frame size averraged over last frames with exponential mean */
} FeedData;

238 239 240
struct sockaddr_in my_http_addr;
struct sockaddr_in my_rtsp_addr;

241 242 243 244
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
245

246 247 248 249 250
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
251
static int http_parse_request(HTTPContext *c);
252
static int http_send_data(HTTPContext *c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
253 254 255 256
static void compute_stats(HTTPContext *c);
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);
257 258 259 260

/* RTSP handling */
static int rtsp_parse_request(HTTPContext *c);
static void rtsp_cmd_describe(HTTPContext *c, const char *url);
261
static void rtsp_cmd_options(HTTPContext *c, const char *url);
262 263 264 265 266
static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPHeader *h);
static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h);
static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h);
static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h);

267
/* SDP handling */
268
static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
269 270
                                   struct in_addr my_ip);

271
/* RTP handling */
272
static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
273 274
                                       FFStream *stream, const char *session_id,
                                       enum RTSPProtocol rtp_protocol);
275
static int rtp_new_av_stream(HTTPContext *c,
276 277
                             int stream_index, struct sockaddr_in *dest_addr,
                             HTTPContext *rtsp_c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
278

Philip Gladstone's avatar
Philip Gladstone committed
279
static const char *my_program_name;
280
static const char *my_program_dir;
Philip Gladstone's avatar
Philip Gladstone committed
281

282
static int ffserver_debug;
283
static int ffserver_daemon;
284
static int no_launch;
285
static int need_to_start_children;
286

287 288
static int nb_max_connections;
static int nb_connections;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
289

290 291
static int max_bandwidth;
static int current_bandwidth;
292

293 294
static long cur_time;           // Making this global saves on passing it around everywhere

295 296
static AVRandomState random_state;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
297 298
static FILE *logfile = NULL;

299
static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
300 301 302
{
    va_list ap;
    va_start(ap, fmt);
303

304
    if (logfile) {
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
305
        vfprintf(logfile, fmt, ap);
306 307
        fflush(logfile);
    }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
308 309 310
    va_end(ap);
}

311
static char *ctime1(char *buf2)
312 313
{
    time_t ti;
314
    char *p;
315 316 317 318 319 320 321

    ti = time(NULL);
    p = ctime(&ti);
    strcpy(buf2, p);
    p = buf2 + strlen(p) - 1;
    if (*p == '\n')
        *p = '\0';
322 323 324 325 326 327 328
    return buf2;
}

static void log_connection(HTTPContext *c)
{
    char buf2[32];

329
    if (c->suppress_log)
330 331
        return;

332 333 334
    http_log("%s - - [%s] \"%s %s %s\" %d %"PRId64"\n",
             inet_ntoa(c->from_addr.sin_addr),
             ctime1(buf2), c->method, c->url,
335
             c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
Philip Gladstone's avatar
Philip Gladstone committed
336 337
}

338
static void update_datarate(DataRateData *drd, int64_t count)
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
{
    if (!drd->time1 && !drd->count1) {
        drd->time1 = drd->time2 = cur_time;
        drd->count1 = drd->count2 = count;
    } else {
        if (cur_time - drd->time2 > 5000) {
            drd->time1 = drd->time2;
            drd->count1 = drd->count2;
            drd->time2 = cur_time;
            drd->count2 = count;
        }
    }
}

/* In bytes per second */
354
static int compute_datarate(DataRateData *drd, int64_t count)
355 356 357
{
    if (cur_time == drd->time1)
        return 0;
358

359 360 361
    return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
}

362

Philip Gladstone's avatar
Philip Gladstone committed
363 364
static void start_children(FFStream *feed)
{
365 366 367
    if (no_launch)
        return;

Philip Gladstone's avatar
Philip Gladstone committed
368
    for (; feed; feed = feed->next) {
369 370 371
        if (feed->child_argv && !feed->pid) {
            feed->pid_start = time(0);

Philip Gladstone's avatar
Philip Gladstone committed
372 373 374 375 376 377 378 379 380 381 382 383
            feed->pid = fork();

            if (feed->pid < 0) {
                fprintf(stderr, "Unable to create children\n");
                exit(1);
            }
            if (!feed->pid) {
                /* In child */
                char pathname[1024];
                char *slash;
                int i;

384 385 386
                for (i = 3; i < 256; i++) {
                    close(i);
                }
Philip Gladstone's avatar
Philip Gladstone committed
387

388
                if (!ffserver_debug) {
389 390 391 392 393
                    i = open("/dev/null", O_RDWR);
                    if (i)
                        dup2(i, 0);
                    dup2(i, 1);
                    dup2(i, 2);
394 395
                    if (i)
                        close(i);
396
                }
Philip Gladstone's avatar
Philip Gladstone committed
397 398 399 400 401 402 403 404 405 406 407

                pstrcpy(pathname, sizeof(pathname), my_program_name);

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

408 409 410
                /* This is needed to make relative pathnames work */
                chdir(my_program_dir);

411 412
                signal(SIGPIPE, SIG_DFL);

Philip Gladstone's avatar
Philip Gladstone committed
413 414 415 416 417 418
                execvp(pathname, feed->child_argv);

                _exit(1);
            }
        }
    }
419 420
}

421 422
/* open a listening socket */
static int socket_open_listen(struct sockaddr_in *my_addr)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
423
{
424
    int server_fd, tmp;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
425 426 427 428 429 430

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
432 433 434
    tmp = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));

435
    if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
436 437 438
        char bindmsg[32];
        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
        perror (bindmsg);
439
        closesocket(server_fd);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
440 441
        return -1;
    }
442

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
443 444
    if (listen (server_fd, 5) < 0) {
        perror ("listen");
445
        closesocket(server_fd);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
446 447
        return -1;
    }
448 449 450 451 452
    fcntl(server_fd, F_SETFL, O_NONBLOCK);

    return server_fd;
}

453 454 455 456 457 458 459 460 461 462 463 464 465
/* 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 */
466 467
            snprintf(session_id, sizeof(session_id), "%08x%08x",
                     av_random(&random_state), av_random(&random_state));
468 469 470 471 472 473 474 475 476 477 478

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

479
            rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
480
                                       RTSP_PROTOCOL_RTP_UDP_MULTICAST);
481 482 483 484
            if (!rtp_c) {
                continue;
            }
            if (open_input_stream(rtp_c, "") < 0) {
485
                fprintf(stderr, "Could not open input stream for stream '%s'\n",
486 487 488 489 490
                        stream->filename);
                continue;
            }

            /* open each RTP stream */
491
            for(stream_index = 0; stream_index < stream->nb_streams;
492
                stream_index++) {
493
                dest_addr.sin_port = htons(stream->multicast_port +
494
                                           2 * stream_index);
495
                if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
496
                    fprintf(stderr, "Could not open output stream '%s/streamid=%d'\n",
497 498
                            stream->filename, stream_index);
                    exit(1);
499 500 501 502 503 504 505 506
                }
            }

            /* change state to send data */
            rtp_c->state = HTTPSTATE_SEND_DATA;
        }
    }
}
507 508 509 510 511 512 513 514 515 516 517

/* main loop of the http server */
static int http_server(void)
{
    int server_fd, ret, rtsp_server_fd, delay, delay1;
    struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 2], *poll_entry;
    HTTPContext *c, *c_next;

    server_fd = socket_open_listen(&my_http_addr);
    if (server_fd < 0)
        return -1;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
518

519 520 521
    rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
    if (rtsp_server_fd < 0)
        return -1;
522

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
523 524
    http_log("ffserver started.\n");

Philip Gladstone's avatar
Philip Gladstone committed
525 526
    start_children(first_feed);

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
527 528
    first_http_ctx = NULL;
    nb_connections = 0;
529 530 531

    start_multicast();

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
532 533 534 535 536 537
    for(;;) {
        poll_entry = poll_table;
        poll_entry->fd = server_fd;
        poll_entry->events = POLLIN;
        poll_entry++;

538 539 540 541
        poll_entry->fd = rtsp_server_fd;
        poll_entry->events = POLLIN;
        poll_entry++;

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
542 543
        /* wait for events on each HTTP handle */
        c = first_http_ctx;
544
        delay = 1000;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
545 546 547 548
        while (c != NULL) {
            int fd;
            fd = c->fd;
            switch(c->state) {
549 550
            case HTTPSTATE_SEND_HEADER:
            case RTSPSTATE_SEND_REPLY:
551
            case RTSPSTATE_SEND_PACKET:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
552 553
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
554
                poll_entry->events = POLLOUT;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
555 556 557 558 559
                poll_entry++;
                break;
            case HTTPSTATE_SEND_DATA_HEADER:
            case HTTPSTATE_SEND_DATA:
            case HTTPSTATE_SEND_DATA_TRAILER:
560 561 562 563 564 565 566
                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 {
567 568 569 570 571 572
                    /* 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;
573
                }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
574
                break;
575
            case HTTPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
576 577
            case HTTPSTATE_RECEIVE_DATA:
            case HTTPSTATE_WAIT_FEED:
578
            case RTSPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
579 580 581
                /* need to catch errors */
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
582
                poll_entry->events = POLLIN;/* Maybe this will work */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
583 584 585 586 587 588 589 590 591 592 593 594
                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 {
595
            ret = poll(poll_table, poll_entry - poll_table, delay);
596 597 598
            if (ret < 0 && errno != EAGAIN && errno != EINTR)
                return -1;
        } while (ret <= 0);
599

600
        cur_time = (long)(av_gettime()/1000);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
601

602 603 604 605 606
        if (need_to_start_children) {
            need_to_start_children = 0;
            start_children(first_feed);
        }

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
607
        /* now handle the events */
608 609 610
        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
611
                /* close and free the connection */
612
                log_connection(c);
613
                close_connection(c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
614 615 616 617
            }
        }

        poll_entry = poll_table;
618
        /* new HTTP connection request ? */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
619
        if (poll_entry->revents & POLLIN) {
620
            new_connection(server_fd, 0);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
621 622
        }
        poll_entry++;
623 624 625 626
        /* new RTSP connection request ? */
        if (poll_entry->revents & POLLIN) {
            new_connection(rtsp_server_fd, 1);
        }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
627 628 629
    }
}

630 631
/* 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
632
{
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    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;
    }
}

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);
652
    fd = accept(server_fd, (struct sockaddr *)&from_addr,
653 654 655 656 657 658 659 660 661
                &len);
    if (fd < 0)
        return;
    fcntl(fd, F_SETFL, O_NONBLOCK);

    /* XXX: should output a warning page when coming
       close to the connection limit */
    if (nb_connections >= nb_max_connections)
        goto fail;
662

663 664 665 666
    /* add a new connection */
    c = av_mallocz(sizeof(HTTPContext));
    if (!c)
        goto fail;
667

668 669 670 671 672 673 674
    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;
675 676 677

    c->next = first_http_ctx;
    first_http_ctx = c;
678
    nb_connections++;
679

680 681 682 683 684 685 686 687 688
    start_wait_request(c, is_rtsp);

    return;

 fail:
    if (c) {
        av_free(c->buffer);
        av_free(c);
    }
689
    closesocket(fd);
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
}

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;
        if (c1 == c) {
            *cp = c->next;
        } else {
            cp = &c1->next;
        }
    }

711 712 713 714 715 716
    /* 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;
    }

717 718
    /* remove connection associated resources */
    if (c->fd >= 0)
719
        closesocket(c->fd);
720 721 722 723
    if (c->fmt_in) {
        /* close each frame parser */
        for(i=0;i<c->fmt_in->nb_streams;i++) {
            st = c->fmt_in->streams[i];
724 725
            if (st->codec->codec) {
                avcodec_close(st->codec);
726 727 728 729 730 731 732
            }
        }
        av_close_input_file(c->fmt_in);
    }

    /* free RTP output streams if any */
    nb_streams = 0;
733
    if (c->stream)
734
        nb_streams = c->stream->nb_streams;
735

736 737 738 739 740 741 742 743 744 745 746
    for(i=0;i<nb_streams;i++) {
        ctx = c->rtp_ctx[i];
        if (ctx) {
            av_write_trailer(ctx);
            av_free(ctx);
        }
        h = c->rtp_handles[i];
        if (h) {
            url_close(h);
        }
    }
747

748 749
    ctx = &c->fmt_ctx;

750 751 752 753 754
    if (!c->last_packet_sent) {
        if (ctx->oformat) {
            /* prepare header */
            if (url_open_dyn_buf(&ctx->pb) >= 0) {
                av_write_trailer(ctx);
755
                url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
756 757 758 759
            }
        }
    }

760 761
    for(i=0; i<ctx->nb_streams; i++)
        av_free(ctx->streams[i]) ;
762

763
    if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
764
        current_bandwidth -= c->stream->bandwidth;
765 766 767 768 769 770 771

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

772
    av_freep(&c->pb_buffer);
773
    av_freep(&c->packet_buffer);
774 775 776 777 778 779 780 781
    av_free(c->buffer);
    av_free(c);
    nb_connections--;
}

static int handle_connection(HTTPContext *c)
{
    int len, ret;
782

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
783 784
    switch(c->state) {
    case HTTPSTATE_WAIT_REQUEST:
785
    case RTSPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
786 787 788 789 790 791 792 793 794 795
        /* 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 */
796
    read_loop:
797
        len = recv(c->fd, c->buffer_ptr, 1, 0);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
798 799 800 801 802 803
        if (len < 0) {
            if (errno != EAGAIN && errno != EINTR)
                return -1;
        } else if (len == 0) {
            return -1;
        } else {
Giancarlo Formicuccia's avatar
Giancarlo Formicuccia committed
804
            /* search for end of request. */
805
            uint8_t *ptr;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
806 807 808 809 810
            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 */
811 812 813 814 815 816
                if (c->state == HTTPSTATE_WAIT_REQUEST) {
                    ret = http_parse_request(c);
                } else {
                    ret = rtsp_parse_request(c);
                }
                if (ret < 0)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
817 818 819 820
                    return -1;
            } else if (ptr >= c->buffer_end) {
                /* request too long: cannot do anything */
                return -1;
821
            } else goto read_loop;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
822 823 824 825 826 827 828
        }
        break;

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

829
        /* no need to write if no events */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
830 831
        if (!(c->poll_entry->revents & POLLOUT))
            return 0;
832
        len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
833 834 835
        if (len < 0) {
            if (errno != EAGAIN && errno != EINTR) {
                /* error : close connection */
836
                av_freep(&c->pb_buffer);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
837 838 839 840
                return -1;
            }
        } else {
            c->buffer_ptr += len;
841 842
            if (c->stream)
                c->stream->bytes_served += len;
843
            c->data_count += len;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
844
            if (c->buffer_ptr >= c->buffer_end) {
845
                av_freep(&c->pb_buffer);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
846
                /* if error, exit */
847
                if (c->http_error) {
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
848
                    return -1;
849 850
                }
                /* all the buffer was sent : synchronize to the incoming stream */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
851 852 853 854 855 856 857 858 859
                c->state = HTTPSTATE_SEND_DATA_HEADER;
                c->buffer_ptr = c->buffer_end = c->buffer;
            }
        }
        break;

    case HTTPSTATE_SEND_DATA:
    case HTTPSTATE_SEND_DATA_HEADER:
    case HTTPSTATE_SEND_DATA_TRAILER:
860 861 862 863 864 865
        /* for packetized output, we consider we can always write (the
           input streams sets the speed). It may be better to verify
           that we do not rely too much on the kernel queues */
        if (!c->is_packetized) {
            if (c->poll_entry->revents & (POLLERR | POLLHUP))
                return -1;
866

867 868 869 870
            /* no need to read if no events */
            if (!(c->poll_entry->revents & POLLOUT))
                return 0;
        }
871
        if (http_send_data(c) < 0)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
872
            return -1;
873 874 875
        /* close connection if trailer sent */
        if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
            return -1;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
876 877 878 879 880 881 882 883 884 885 886 887
        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 */
888
        if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
889 890 891 892
            return -1;

        /* nothing to do, we'll be waken up by incoming feed packets */
        break;
893 894 895 896 897 898 899 900 901

    case RTSPSTATE_SEND_REPLY:
        if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
            av_freep(&c->pb_buffer);
            return -1;
        }
        /* no need to write if no events */
        if (!(c->poll_entry->revents & POLLOUT))
            return 0;
902
        len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
        if (len < 0) {
            if (errno != EAGAIN && errno != EINTR) {
                /* error : close connection */
                av_freep(&c->pb_buffer);
                return -1;
            }
        } else {
            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);
            }
        }
        break;
919 920 921 922 923 924 925 926
    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;
927 928
        len = send(c->fd, c->packet_buffer_ptr,
                    c->packet_buffer_end - c->packet_buffer_ptr, 0);
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
        if (len < 0) {
            if (errno != EAGAIN && errno != EINTR) {
                /* error : close connection */
                av_freep(&c->packet_buffer);
                return -1;
            }
        } else {
            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;
            }
        }
        break;
944 945 946
    case HTTPSTATE_READY:
        /* nothing to do */
        break;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
947 948 949 950 951 952
    default:
        return -1;
    }
    return 0;
}

953 954 955 956 957 958 959 960 961 962 963 964 965