avserver.c 154 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
#include "config.h"
23
#if !HAVE_CLOSESOCKET
24 25 26 27
#define closesocket close
#endif
#include <string.h>
#include <stdlib.h>
28
#include <stdio.h>
29
#include "libavformat/avformat.h"
30
// FIXME those are internal headers, avserver _really_ shouldn't use them
31
#include "libavformat/ffm.h"
32 33
#include "libavformat/network.h"
#include "libavformat/os_support.h"
34
#include "libavformat/rtpdec.h"
35
#include "libavformat/rtpproto.h"
36
#include "libavformat/rtsp.h"
37
#include "libavformat/avio_internal.h"
38 39 40
#include "libavformat/internal.h"
#include "libavformat/url.h"

41
#include "libavutil/avstring.h"
42
#include "libavutil/lfg.h"
43
#include "libavutil/dict.h"
44
#include "libavutil/intreadwrite.h"
45
#include "libavutil/mathematics.h"
46
#include "libavutil/random_seed.h"
47
#include "libavutil/parseutils.h"
48
#include "libavutil/opt.h"
49 50
#include "libavutil/time.h"

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
51 52 53 54
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
55
#if HAVE_POLL_H
56
#include <poll.h>
57
#endif
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
58 59
#include <errno.h>
#include <time.h>
60
#include <sys/wait.h>
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
61
#include <signal.h>
62

63
#include "cmdutils.h"
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
64

Anton Khirnov's avatar
Anton Khirnov committed
65
const char program_name[] = "avserver";
66
const int program_birth_year = 2000;
67

68 69
static const OptionDef options[];

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

    RTSPSTATE_WAIT_REQUEST,
    RTSPSTATE_SEND_REPLY,
82
    RTSPSTATE_SEND_PACKET,
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
83 84
};

Baptiste Coudurier's avatar
Baptiste Coudurier committed
85
static const char *http_state[] = {
86 87 88
    "HTTP_WAIT_REQUEST",
    "HTTP_SEND_HEADER",

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
89 90 91 92 93
    "SEND_DATA_HEADER",
    "SEND_DATA",
    "SEND_DATA_TRAILER",
    "RECEIVE_DATA",
    "WAIT_FEED",
94 95 96 97
    "READY",

    "RTSP_WAIT_REQUEST",
    "RTSP_SEND_REPLY",
98
    "RTSP_SEND_PACKET",
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
99 100
};

101 102
#define MAX_STREAMS 20

Philip Gladstone's avatar
Philip Gladstone committed
103
#define IOBUFFER_INIT_SIZE 8192
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
104 105

/* timeouts are in ms */
106 107 108
#define HTTP_REQUEST_TIMEOUT (15 * 1000)
#define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
109 110
#define SYNC_TIMEOUT (10 * 1000)

111 112 113 114 115
typedef struct RTSPActionServerSetup {
    uint32_t ipaddr;
    char transport_option[512];
} RTSPActionServerSetup;

116
typedef struct {
117
    int64_t count1, count2;
118
    int64_t time1, time2;
119 120
} DataRateData;

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

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

173
    /* RTP state specific */
174
    enum RTSPLowerTransport rtp_protocol;
175 176
    char session_id[32]; /* session id */
    AVFormatContext *rtp_ctx[MAX_STREAMS];
177

178 179 180 181 182 183
    /* 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
184 185 186 187 188 189
} HTTPContext;

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

193 194 195 196 197 198 199 200
enum IPAddressAction {
    IP_ALLOW = 1,
    IP_DENY,
};

typedef struct IPAddressACL {
    struct IPAddressACL *next;
    enum IPAddressAction action;
201
    /* These are in host order */
202 203 204 205
    struct in_addr first;
    struct in_addr last;
} IPAddressACL;

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

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

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

261 262
static struct sockaddr_in my_http_addr;
static struct sockaddr_in my_rtsp_addr;
263

264 265 266 267
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
268

269 270 271 272 273
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
274
static int http_parse_request(HTTPContext *c);
275
static int http_send_data(HTTPContext *c);
276
static void compute_status(HTTPContext *c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
277 278 279
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);
280 281 282 283

/* RTSP handling */
static int rtsp_parse_request(HTTPContext *c);
static void rtsp_cmd_describe(HTTPContext *c, const char *url);
284
static void rtsp_cmd_options(HTTPContext *c, const char *url);
285 286 287 288
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);
289

290
/* SDP handling */
291
static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
292 293
                                   struct in_addr my_ip);

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

Philip Gladstone's avatar
Philip Gladstone committed
302 303
static const char *my_program_name;

304
static const char *config_filename;
305

Anton Khirnov's avatar
Anton Khirnov committed
306
static int avserver_debug;
307
static int no_launch;
308
static int need_to_start_children;
309

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

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

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

320
static AVLFG random_state;
321

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

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
static int64_t ffm_read_write_index(int fd)
{
    uint8_t buf[8];

    lseek(fd, 8, SEEK_SET);
    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;
    lseek(fd, 8, SEEK_SET);
    if (write(fd, buf, 8) != 8)
        return AVERROR(EIO);
    return 8;
}

static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
                                int64_t file_size)
{
    FFMContext *ffm = s->priv_data;
    ffm->write_index = pos;
    ffm->file_size = file_size;
}

Anton Khirnov's avatar
Anton Khirnov committed
355
/* FIXME: make avserver work with IPv6 */
356 357 358 359 360 361 362
/* 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;
363
        struct addrinfo hints = { 0 };
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        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
390 391 392 393 394 395 396 397 398 399 400 401 402 403
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
404
static void http_vlog(const char *fmt, va_list vargs)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
405
{
Baptiste Coudurier's avatar
Baptiste Coudurier committed
406
    static int print_prefix = 1;
407
    if (logfile) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
408
        if (print_prefix) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
409 410 411
            char buf[32];
            ctime1(buf);
            fprintf(logfile, "%s ", buf);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
412 413
        }
        print_prefix = strstr(fmt, "\n") != NULL;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
414
        vfprintf(logfile, fmt, vargs);
415 416
        fflush(logfile);
    }
Baptiste Coudurier's avatar
Baptiste Coudurier committed
417 418
}

419 420 421 422
#ifdef __GNUC__
__attribute__ ((format (printf, 1, 2)))
#endif
static void http_log(const char *fmt, ...)
Baptiste Coudurier's avatar
Baptiste Coudurier committed
423 424 425 426 427 428 429 430 431 432 433
{
    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;
434
    if (level > av_log_get_level())
Baptiste Coudurier's avatar
Baptiste Coudurier committed
435 436
        return;
    if (print_prefix && avc)
437
        http_log("[%s @ %p]", avc->item_name(ptr), ptr);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
438 439
    print_prefix = strstr(fmt, "\n") != NULL;
    http_vlog(fmt, vargs);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
440 441
}

442 443
static void log_connection(HTTPContext *c)
{
444
    if (c->suppress_log)
445 446
        return;

447 448
    http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
             inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
449
             c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
Philip Gladstone's avatar
Philip Gladstone committed
450 451
}

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

/* In bytes per second */
466
static int compute_datarate(DataRateData *drd, int64_t count)
467 468 469
{
    if (cur_time == drd->time1)
        return 0;
470

471 472 473
    return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
}

474

Philip Gladstone's avatar
Philip Gladstone committed
475 476
static void start_children(FFStream *feed)
{
477 478 479
    if (no_launch)
        return;

Philip Gladstone's avatar
Philip Gladstone committed
480
    for (; feed; feed = feed->next) {
481 482 483
        if (feed->child_argv && !feed->pid) {
            feed->pid_start = time(0);

Philip Gladstone's avatar
Philip Gladstone committed
484 485 486
            feed->pid = fork();

            if (feed->pid < 0) {
487
                http_log("Unable to create children\n");
Philip Gladstone's avatar
Philip Gladstone committed
488 489 490 491 492 493 494 495
                exit(1);
            }
            if (!feed->pid) {
                /* In child */
                char pathname[1024];
                char *slash;
                int i;

496 497 498 499 500 501 502
                av_strlcpy(pathname, my_program_name, sizeof(pathname));

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

Diego Biurrun's avatar
Diego Biurrun committed
505
                http_log("Launch command line: ");
Stefano Sabatini's avatar
Stefano Sabatini committed
506 507 508 509
                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");
510

511
                for (i = 3; i < 256; i++)
512
                    close(i);
Philip Gladstone's avatar
Philip Gladstone committed
513

Anton Khirnov's avatar
Anton Khirnov committed
514
                if (!avserver_debug) {
515 516 517 518 519 520
                    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;");
521
                }
Philip Gladstone's avatar
Philip Gladstone committed
522

523 524
                signal(SIGPIPE, SIG_DFL);

Philip Gladstone's avatar
Philip Gladstone committed
525 526 527 528 529 530
                execvp(pathname, feed->child_argv);

                _exit(1);
            }
        }
    }
531 532
}

533 534
/* open a listening socket */
static int socket_open_listen(struct sockaddr_in *my_addr)
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
535
{
536
    int server_fd, tmp;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
537 538 539 540 541 542

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

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
544 545 546
    tmp = 1;
    setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));

547
    my_addr->sin_family = AF_INET;
548
    if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
549 550 551
        char bindmsg[32];
        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
        perror (bindmsg);
552
        closesocket(server_fd);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
553 554
        return -1;
    }
555

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
556 557
    if (listen (server_fd, 5) < 0) {
        perror ("listen");
558
        closesocket(server_fd);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
559 560
        return -1;
    }
561
    ff_socket_nonblock(server_fd, 1);
562 563 564 565

    return server_fd;
}

566 567 568 569 570 571 572 573 574 575 576 577 578
/* 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 */
579
            snprintf(session_id, sizeof(session_id), "%08x%08x",
580
                     av_lfg_get(&random_state), av_lfg_get(&random_state));
581 582 583 584 585 586 587 588 589 590 591

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

592
            rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
593
                                       RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
594
            if (!rtp_c)
595
                continue;
596

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

            /* open each RTP stream */
604
            for(stream_index = 0; stream_index < stream->nb_streams;
605
                stream_index++) {
606
                dest_addr.sin_port = htons(stream->multicast_port +
607
                                           2 * stream_index);
608
                if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
609 610
                    http_log("Could not open output stream '%s/streamid=%d'\n",
                             stream->filename, stream_index);
611
                    exit(1);
612 613 614 615 616 617 618 619
                }
            }

            /* change state to send data */
            rtp_c->state = HTTPSTATE_SEND_DATA;
        }
    }
}
620 621 622 623

/* main loop of the http server */
static int http_server(void)
{
Baptiste Coudurier's avatar
Baptiste Coudurier committed
624 625
    int server_fd = 0, rtsp_server_fd = 0;
    int ret, delay, delay1;
626
    struct pollfd *poll_table, *poll_entry;
627 628
    HTTPContext *c, *c_next;

629
    if(!(poll_table = av_mallocz((nb_max_http_connections + 2)*sizeof(*poll_table)))) {
630 631 632 633
        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
634
    if (my_http_addr.sin_port) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
635 636 637
        server_fd = socket_open_listen(&my_http_addr);
        if (server_fd < 0)
            return -1;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
638
    }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
639

Baptiste Coudurier's avatar
Baptiste Coudurier committed
640
    if (my_rtsp_addr.sin_port) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
641 642 643
        rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
        if (rtsp_server_fd < 0)
            return -1;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
644 645 646 647 648 649
    }

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

Anton Khirnov's avatar
Anton Khirnov committed
651
    http_log("AVserver started.\n");
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
652

Philip Gladstone's avatar
Philip Gladstone committed
653 654
    start_children(first_feed);

655 656
    start_multicast();

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
657 658
    for(;;) {
        poll_entry = poll_table;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
659
        if (server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
660 661 662
            poll_entry->fd = server_fd;
            poll_entry->events = POLLIN;
            poll_entry++;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
663 664
        }
        if (rtsp_server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
665 666 667
            poll_entry->fd = rtsp_server_fd;
            poll_entry->events = POLLIN;
            poll_entry++;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
668
        }
669

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
670 671
        /* wait for events on each HTTP handle */
        c = first_http_ctx;
672
        delay = 1000;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
673 674 675 676
        while (c != NULL) {
            int fd;
            fd = c->fd;
            switch(c->state) {
677 678
            case HTTPSTATE_SEND_HEADER:
            case RTSPSTATE_SEND_REPLY:
679
            case RTSPSTATE_SEND_PACKET:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
680 681
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
682
                poll_entry->events = POLLOUT;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
683 684 685 686 687
                poll_entry++;
                break;
            case HTTPSTATE_SEND_DATA_HEADER:
            case HTTPSTATE_SEND_DATA:
            case HTTPSTATE_SEND_DATA_TRAILER:
688 689 690 691 692 693 694
                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 {
Anton Khirnov's avatar
Anton Khirnov committed
695
                    /* when avserver is doing the timing, we work by
696 697 698 699 700
                       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;
701
                }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
702
                break;
703
            case HTTPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
704 705
            case HTTPSTATE_RECEIVE_DATA:
            case HTTPSTATE_WAIT_FEED:
706
            case RTSPSTATE_WAIT_REQUEST:
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
707 708 709
                /* need to catch errors */
                c->poll_entry = poll_entry;
                poll_entry->fd = fd;
710
                poll_entry->events = POLLIN;/* Maybe this will work */
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
711 712 713 714 715 716 717 718 719 720 721 722
                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 {
723
            ret = poll(poll_table, poll_entry - poll_table, delay);
724 725
            if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
                ff_neterrno() != AVERROR(EINTR))
726
                return -1;
727
        } while (ret < 0);
728

729
        cur_time = av_gettime() / 1000;
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
730

731 732 733 734 735
        if (need_to_start_children) {
            need_to_start_children = 0;
            start_children(first_feed);
        }

Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
736
        /* now handle the events */
737 738 739
        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
740
                /* close and free the connection */
741
                log_connection(c);
742
                close_connection(c);
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
743 744 745 746
            }
        }

        poll_entry = poll_table;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
747
        if (server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
748 749 750 751
            /* new HTTP connection request ? */
            if (poll_entry->revents & POLLIN)
                new_connection(server_fd, 0);
            poll_entry++;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
752 753
        }
        if (rtsp_server_fd) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
754 755 756
            /* new RTSP connection request ? */
            if (poll_entry->revents & POLLIN)
                new_connection(rtsp_server_fd, 1);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
757
        }
Fabrice Bellard's avatar
merge  
Fabrice Bellard committed
758 759 760
    }
}

761 762
/* 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
763
{
764 765 766 767 768 769 770 771 772 773 774 775
    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;
    }
}

776 777 778 779
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
780
                       "HTTP/1.0 503 Server too busy\r\n"
781 782 783 784 785 786 787 788 789 790 791
                       "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);
}


792 793 794
static void new_connection(int server_fd, int is_rtsp)
{
    struct sockaddr_in from_addr;
795 796
    socklen_t len;
    int fd;
797 798 799
    HTTPContext *c = NULL;

    len = sizeof(from_addr);
800
    fd = accept(server_fd, (struct sockaddr *)&from_addr,
801
                &len);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
802 803
    if (fd < 0) {
        http_log("error during accept %s\n", strerror(errno));
804
        return;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
805
    }
806
    ff_socket_nonblock(fd, 1);
807

808 809
    if (nb_connections >= nb_max_connections) {
        http_send_too_busy_reply(fd);
810
        goto fail;
811
    }
812

813 814 815 816
    /* add a new connection */
    c = av_mallocz(sizeof(HTTPContext));
    if (!c)
        goto fail;
817

818 819 820 821 822 823 824
    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;
825 826 827

    c->next = first_http_ctx;
    first_http_ctx = c;
828
    nb_connections++;
829

830 831 832 833 834 835 836 837 838
    start_wait_request(c, is_rtsp);

    return;

 fail:
    if (c) {
        av_free(c->buffer);
        av_free(c);
    }
839
    closesocket(fd);
840 841 842 843 844 845 846 847 848 849 850 851 852 853
}

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;
854
        if (c1 == c)
855
            *cp = c->next;
856
        else
857 858 859
            cp = &c1->next;
    }

860 861 862 863 864 865
    /* 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;
    }

866 867
    /* remove connection associated resources */
    if (c->fd >= 0)
868
        closesocket(c->fd);
869 870 871 872
    if (c->fmt_in) {
        /* close each frame parser */
        for(i=0;i<c->fmt_in->nb_streams;i++) {
            st = c->fmt_in->streams[i];
873
            if (st->codec->codec)
874
                avcodec_close(st->codec);
875
        }
876
        avformat_close_input(&c->fmt_in);
877 878 879 880
    }

    /* free RTP output streams if any */
    nb_streams = 0;
881
    if (c->stream)
882
        nb_streams = c->stream->nb_streams;
883

884 885 886 887
    for(i=0;i<nb_streams;i++) {
        ctx = c->rtp_ctx[i];
        if (ctx) {
            av_write_trailer