www.pudn.com > ffmpeg-0.3.4.rar > ffserver.c
/*
* Multiple format streaming server
* Copyright (c) 2000,2001 Gerard Lantau.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "mpegenc.h"
/* maximum number of simultaneous HTTP connections */
#define HTTP_MAX_CONNECTIONS 2000
enum HTTPState {
HTTPSTATE_WAIT_REQUEST,
HTTPSTATE_SEND_HEADER,
HTTPSTATE_SEND_DATA_HEADER,
HTTPSTATE_SEND_DATA,
HTTPSTATE_SEND_DATA_TRAILER,
};
enum MasterState {
MASTERSTATE_RECEIVE_HEADER,
MASTERSTATE_RECEIVE_DATA,
};
#define IOBUFFER_MAX_SIZE 16384
#define FIFO_MAX_SIZE (1024*1024)
/* coef for exponential mean for bitrate estimation in statistics */
#define AVG_COEF 0.9
/* timeouts are in ms */
#define REQUEST_TIMEOUT (15 * 1000)
#define SYNC_TIMEOUT (10 * 1000)
#define MASTER_CONNECT_TIMEOUT (10 * 1000)
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;
UINT8 buffer[IOBUFFER_MAX_SIZE];
UINT8 *buffer_ptr, *buffer_end;
int http_error;
struct HTTPContext *next;
UINT8 *rptr; /* read pointer in the fifo */
int got_key_frame[2]; /* for each type */
long long data_count;
long long last_http_fifo_write_count; /* used to monitor overflow in the fifo */
/* format handling */
struct FFStream *stream;
AVFormatContext fmt_ctx;
int last_packet_sent; /* true if last data packet was sent */
} HTTPContext;
/* each generated stream is described here */
enum StreamType {
STREAM_TYPE_LIVE,
STREAM_TYPE_MASTER,
STREAM_TYPE_STATUS,
};
typedef struct FFStream {
enum StreamType stream_type;
char filename[1024];
AVFormat *fmt;
AVEncodeContext *audio_enc;
AVEncodeContext *video_enc;
struct FFStream *next;
} FFStream;
typedef struct FifoBuffer {
UINT8 *buffer;
UINT8 *rptr, *wptr, *end;
} FifoBuffer;
/* each codec is here */
typedef struct FFCodec {
struct FFCodec *next;
FifoBuffer fifo; /* for compression: one audio fifo per codec */
ReSampleContext resample; /* for audio resampling */
long long data_count;
float avg_frame_size; /* frame size averraged over last frames with exponential mean */
AVEncodeContext enc;
} FFCodec;
/* packet header */
typedef struct {
UINT8 codec_type;
UINT8 codec_id;
UINT8 data[4];
UINT16 bit_rate;
UINT16 payload_size;
} PacketHeader;
struct sockaddr_in my_addr;
char logfilename[1024];
HTTPContext *first_http_ctx;
FFStream *first_stream;
FFCodec *first_codec;
/* master state */
char master_url[1024];
enum MasterState master_state;
UINT8 *master_wptr;
int master_count;
long long http_fifo_write_count;
static FifoBuffer http_fifo;
static int handle_http(HTTPContext *c, long cur_time);
static int http_parse_request(HTTPContext *c);
static int http_send_data(HTTPContext *c);
static int master_receive(int fd);
static void compute_stats(HTTPContext *c);
int nb_max_connections;
int nb_connections;
/* fifo handling */
int fifo_init(FifoBuffer *f, int size)
{
f->buffer = malloc(size);
if (!f->buffer)
return -1;
f->end = f->buffer + size;
f->wptr = f->rptr = f->buffer;
return 0;
}
static int fifo_size(FifoBuffer *f, UINT8 *rptr)
{
int size;
if (f->wptr >= rptr) {
size = f->wptr - rptr;
} else {
size = (f->end - rptr) + (f->wptr - f->buffer);
}
return size;
}
/* get data from the fifo (return -1 if not enough data) */
static int fifo_read(FifoBuffer *f, UINT8 *buf, int buf_size, UINT8 **rptr_ptr)
{
UINT8 *rptr = *rptr_ptr;
int size, len;
if (f->wptr >= rptr) {
size = f->wptr - rptr;
} else {
size = (f->end - rptr) + (f->wptr - f->buffer);
}
if (size < buf_size)
return -1;
while (buf_size > 0) {
len = f->end - rptr;
if (len > buf_size)
len = buf_size;
memcpy(buf, rptr, len);
buf += len;
rptr += len;
if (rptr >= f->end)
rptr = f->buffer;
buf_size -= len;
}
*rptr_ptr = rptr;
return 0;
}
static void fifo_write(FifoBuffer *f, UINT8 *buf, int size, UINT8 **wptr_ptr)
{
int len;
UINT8 *wptr;
wptr = *wptr_ptr;
while (size > 0) {
len = f->end - wptr;
if (len > size)
len = size;
memcpy(wptr, buf, len);
wptr += len;
if (wptr >= f->end)
wptr = f->buffer;
buf += len;
size -= len;
}
*wptr_ptr = wptr;
}
static long gettime_ms(void)
{
struct timeval tv;
gettimeofday(&tv,NULL);
return (long long)tv.tv_sec * 1000 + (tv.tv_usec / 1000);
}
static FILE *logfile = NULL;
static void http_log(char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (logfile)
vfprintf(logfile, fmt, ap);
va_end(ap);
}
/* connect to url 'url' and return the connected socket ready to read data */
static int url_get(const char *url)
{
struct sockaddr_in dest_addr;
struct hostent *h;
int s, port, size, line_size, len;
char hostname[1024], *q;
const char *p, *path;
char req[1024];
unsigned char ch;
if (!strstart(url, "http://", &p))
return -1;
q = hostname;
while (*p != ':' && *p != '\0' && *p != '/') {
if ((q - hostname) < (sizeof(hostname) - 1))
*q++ = *p;
p++;
}
port = 80;
if (*p == ':') {
p++;
port = strtol(p, (char **)&p, 10);
}
path = p;
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(port);
if (!inet_aton(hostname, &dest_addr.sin_addr)) {
if ((h = gethostbyname(hostname)) == NULL)
return -1;
memcpy(&dest_addr.sin_addr, h->h_addr, sizeof(dest_addr.sin_addr));
}
s=socket(AF_INET, SOCK_STREAM, 0);
if (s < 0)
return -1;
if (connect(s, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0) {
fail:
close(s);
return -1;
}
/* send http request */
snprintf(req, sizeof(req), "GET %s HTTP/1.0\r\n\r\n", path);
p = req;
size = strlen(req);
while (size > 0) {
len = write(s, p, size);
if (len == -1) {
if (errno != EAGAIN && errno != EINTR)
goto fail;
} else {
size -= len;
p += len;
}
}
/* receive answer */
line_size = 0;
for(;;) {
len = read(s, &ch, 1);
if (len == -1) {
if (errno != EAGAIN && errno != EINTR)
goto fail;
} else if (len == 0) {
goto fail;
} else {
if (ch == '\n') {
if (line_size == 0)
break;
line_size = 0;
} else if (ch != '\r') {
line_size++;
}
}
}
return s;
}
/* Each request is served by reading the input FIFO and by adding the
right format headers */
static int http_server(struct sockaddr_in my_addr)
{
int server_fd, tmp, ret;
struct sockaddr_in from_addr;
struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 1], *poll_entry;
HTTPContext *c, **cp;
long cur_time;
int master_fd, master_timeout;
/* will try to connect to master as soon as possible */
master_fd = -1;
master_timeout = gettime_ms();
server_fd = socket(AF_INET,SOCK_STREAM,0);
if (server_fd < 0) {
perror ("socket");
return -1;
}
tmp = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
if (bind (server_fd, (struct sockaddr *) &my_addr, sizeof (my_addr)) < 0) {
perror ("bind");
close(server_fd);
return -1;
}
if (listen (server_fd, 5) < 0) {
perror ("listen");
close(server_fd);
return -1;
}
http_log("ffserver started.\n");
fcntl(server_fd, F_SETFL, O_NONBLOCK);
first_http_ctx = NULL;
nb_connections = 0;
first_http_ctx = NULL;
for(;;) {
poll_entry = poll_table;
poll_entry->fd = server_fd;
poll_entry->events = POLLIN;
poll_entry++;
if (master_fd >= 0) {
poll_entry->fd = master_fd;
poll_entry->events = POLLIN;
poll_entry++;
}
/* wait for events on each HTTP handle */
c = first_http_ctx;
while (c != NULL) {
int fd;
fd = c->fd;
switch(c->state) {
case HTTPSTATE_WAIT_REQUEST:
c->poll_entry = poll_entry;
poll_entry->fd = fd;
poll_entry->events = POLLIN;
poll_entry++;
break;
case HTTPSTATE_SEND_HEADER:
case HTTPSTATE_SEND_DATA_HEADER:
case HTTPSTATE_SEND_DATA:
case HTTPSTATE_SEND_DATA_TRAILER:
c->poll_entry = poll_entry;
poll_entry->fd = fd;
poll_entry->events = POLLOUT;
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 {
ret = poll(poll_table, poll_entry - poll_table, 1000);
} while (ret == -1);
cur_time = gettime_ms();
/* now handle the events */
cp = &first_http_ctx;
while ((*cp) != NULL) {
c = *cp;
if (handle_http (c, cur_time) < 0) {
/* close and free the connection */
close(c->fd);
*cp = c->next;
free(c);
nb_connections--;
} else {
cp = &c->next;
}
}
/* new connection request ? */
poll_entry = poll_table;
if (poll_entry->revents & POLLIN) {
int fd, len;
len = sizeof(from_addr);
fd = accept(server_fd, &from_addr, &len);
if (fd >= 0) {
fcntl(fd, F_SETFL, O_NONBLOCK);
/* XXX: should output a warning page when comming
close to the connection limit */
if (nb_connections >= nb_max_connections) {
close(fd);
} else {
/* add a new connection */
c = malloc(sizeof(HTTPContext));
memset(c, 0, sizeof(*c));
c->next = first_http_ctx;
first_http_ctx = c;
c->fd = fd;
c->poll_entry = NULL;
c->from_addr = from_addr;
c->state = HTTPSTATE_WAIT_REQUEST;
c->buffer_ptr = c->buffer;
c->buffer_end = c->buffer + IOBUFFER_MAX_SIZE;
c->timeout = cur_time + REQUEST_TIMEOUT;
nb_connections++;
}
}
}
poll_entry++;
/* master events */
if (poll_entry->revents & POLLIN) {
if (master_receive(master_fd) < 0) {
close(master_fd);
master_fd = -1;
}
}
/* master (re)connection handling */
if (master_url[0] != '\0' &&
master_fd < 0 && (master_timeout - cur_time) <= 0) {
master_fd = url_get(master_url);
if (master_fd < 0) {
master_timeout = gettime_ms() + MASTER_CONNECT_TIMEOUT;
http_log("Connection to master: '%s' failed\n", master_url);
} else {
fcntl(master_fd, F_SETFL, O_NONBLOCK);
master_state = MASTERSTATE_RECEIVE_HEADER;
master_count = sizeof(PacketHeader);
master_wptr = http_fifo.wptr;
}
}
}
}
static int handle_http(HTTPContext *c, long cur_time)
{
int len;
switch(c->state) {
case HTTPSTATE_WAIT_REQUEST:
/* 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 */
len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
if (len < 0) {
if (errno != EAGAIN && errno != EINTR)
return -1;
} else if (len == 0) {
return -1;
} else {
/* search for end of request. XXX: not fully correct since garbage could come after the end */
UINT8 *ptr;
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 */
if (http_parse_request(c) < 0)
return -1;
} else if (ptr >= c->buffer_end) {
/* request too long: cannot do anything */
return -1;
}
}
break;
case HTTPSTATE_SEND_HEADER:
if (c->poll_entry->revents & (POLLERR | POLLHUP))
return -1;
/* no need to read if no events */
if (!(c->poll_entry->revents & POLLOUT))
return 0;
len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
if (len < 0) {
if (errno != EAGAIN && errno != EINTR) {
/* error : close connection */
return -1;
}
} else {
c->buffer_ptr += len;
if (c->buffer_ptr >= c->buffer_end) {
/* if error, exit */
if (c->http_error)
return -1;
/* all the buffer was send : synchronize to the incoming stream */
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:
/* no need to read if no events */
if (c->poll_entry->revents & (POLLERR | POLLHUP))
return -1;
if (!(c->poll_entry->revents & POLLOUT))
return 0;
if (http_send_data(c) < 0)
return -1;
break;
default:
return -1;
}
return 0;
}
/* parse http request and prepare header */
static int http_parse_request(HTTPContext *c)
{
const char *p;
char cmd[32];
char url[1024], *q;
char protocol[32];
char msg[1024];
char *mime_type;
FFStream *stream;
p = c->buffer;
q = cmd;
while (!isspace(*p) && *p != '\0') {
if ((q - cmd) < sizeof(cmd) - 1)
*q++ = *p;
p++;
}
*q = '\0';
if (strcmp(cmd, "GET"))
return -1;
while (isspace(*p)) p++;
q = url;
while (!isspace(*p) && *p != '\0') {
if ((q - url) < sizeof(url) - 1)
*q++ = *p;
p++;
}
*q = '\0';
while (isspace(*p)) p++;
q = protocol;
while (!isspace(*p) && *p != '\0') {
if ((q - protocol) < sizeof(protocol) - 1)
*q++ = *p;
p++;
}
*q = '\0';
if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
return -1;
/* find the filename in the request */
p = url;
if (*p == '/')
p++;
stream = first_stream;
while (stream != NULL) {
if (!strcmp(stream->filename, p))
break;
stream = stream->next;
}
if (stream == NULL) {
sprintf(msg, "File '%s' not found", url);
goto send_error;
}
c->stream = stream;
/* should do it after so that the size can be computed */
{
char buf1[32], buf2[32], *p;
time_t ti;
/* XXX: reentrant function ? */
p = inet_ntoa(c->from_addr.sin_addr);
strcpy(buf1, p);
ti = time(NULL);
p = ctime(&ti);
strcpy(buf2, p);
p = buf2 + strlen(p) - 1;
if (*p == '\n')
*p = '\0';
http_log("%s - - [%s] \"%s %s %s\" %d %d\n",
buf1, buf2, cmd, url, protocol, 200, 1024);
}
if (c->stream->stream_type == STREAM_TYPE_STATUS)
goto send_stats;
/* prepare http header */
q = c->buffer;
q += sprintf(q, "HTTP/1.0 200 OK\r\n");
mime_type = c->stream->fmt->mime_type;
if (!mime_type)
mime_type = "application/x-octet_stream";
q += sprintf(q, "Content-type: %s\r\n", mime_type);
q += sprintf(q, "Pragma: no-cache\r\n");
/* for asf, we need extra headers */
if (!strcmp(c->stream->fmt->name,"asf")) {
q += sprintf(q, "Pragma: features=broadcast\r\n");
}
q += sprintf(q, "\r\n");
/* prepare output buffer */
c->http_error = 0;
c->buffer_ptr = c->buffer;
c->buffer_end = q;
c->state = HTTPSTATE_SEND_HEADER;
return 0;
send_error:
c->http_error = 404;
q = c->buffer;
q += sprintf(q, "HTTP/1.0 404 Not Found\r\n");
q += sprintf(q, "Content-type: %s\r\n", "text/html");
q += sprintf(q, "\r\n");
q += sprintf(q, "\n");
q += sprintf(q, "404 Not Found\n");
q += sprintf(q, "%s\n", msg);
q += sprintf(q, "\n");
/* prepare output buffer */
c->buffer_ptr = c->buffer;
c->buffer_end = q;
c->state = HTTPSTATE_SEND_HEADER;
return 0;
send_stats:
compute_stats(c);
c->http_error = 200; /* horrible : we use this value to avoid
going to the send data state */
c->state = HTTPSTATE_SEND_HEADER;
return 0;
}
static void compute_stats(HTTPContext *c)
{
AVEncodeContext *enc;
HTTPContext *c1;
FFCodec *ffenc;
FFStream *stream;
float avg;
char buf[1024], *q, *p;
time_t ti;
int i;
q = c->buffer;
q += sprintf(q, "HTTP/1.0 200 OK\r\n");
q += sprintf(q, "Content-type: %s\r\n", "text/html");
q += sprintf(q, "Pragma: no-cache\r\n");
q += sprintf(q, "\r\n");
q += sprintf(q, "FFServer Status\n");
q += sprintf(q, "FFServer Status
\n");
/* format status */
q += sprintf(q, "Available Streams
\n");
q += sprintf(q, "\n");
q += sprintf(q, "| Path | Format | Bit rate (kbits/s) | Video | Audio\n");
stream = first_stream;
while (stream != NULL) {
q += sprintf(q, " |
| %s ",
stream->filename, stream->filename);
switch(stream->stream_type) {
case STREAM_TYPE_LIVE:
{
int audio_bit_rate = 0;
int video_bit_rate = 0;
if (stream->audio_enc)
audio_bit_rate = stream->audio_enc->bit_rate;
if (stream->video_enc)
video_bit_rate = stream->video_enc->bit_rate;
q += sprintf(q, " | %s | %d | %d | %d\n",
stream->fmt->name,
(audio_bit_rate + video_bit_rate) / 1000,
video_bit_rate / 1000, audio_bit_rate / 1000);
}
break;
case STREAM_TYPE_MASTER:
q += sprintf(q, " | %s | - | - | -\n",
"master");
break;
default:
q += sprintf(q, " | - | - | - | -\n");
break;
}
stream = stream->next;
}
q += sprintf(q, " |
\n");
/* codec status */
q += sprintf(q, "Codec Status
\n");
q += sprintf(q, "\n");
q += sprintf(q, "| Parameters | Frame count | Size | Avg bitrate (kbits/s)\n");
ffenc = first_codec;
while (ffenc != NULL) {
enc = &ffenc->enc;
avencoder_string(buf, sizeof(buf), enc);
avg = ffenc->avg_frame_size * (float)enc->rate * 8.0;
if (enc->codec->type == CODEC_TYPE_AUDIO && enc->frame_size > 0)
avg /= enc->frame_size;
q += sprintf(q, " |
| %s | %d | %Ld | %0.1f\n",
buf, enc->frame_number, ffenc->data_count, avg / 1000.0);
ffenc = ffenc->next;
}
q += sprintf(q, " |
\n");
/* exclude the stat connection */
q += sprintf(q, "Number of connections: %d / %d
\n",
nb_connections, nb_max_connections);
/* connection status */
q += sprintf(q, "Connection Status
\n");
q += sprintf(q, "\n");
q += sprintf(q, "| # | File | IP | Size\n");
c1 = first_http_ctx;
i = 0;
while (c1 != NULL) {
i++;
p = inet_ntoa(c1->from_addr.sin_addr);
q += sprintf(q, " |
| %d | %s | %s | %Ld\n",
i, c1->stream->filename, p, c1->data_count);
c1 = c1->next;
}
q += sprintf(q, " |
\n");
/* date */
ti = time(NULL);
p = ctime(&ti);
q += sprintf(q, "
Generated at %s", p);
q += sprintf(q, "\n