]> git.sesse.net Git - ffmpeg/blobdiff - ffserver.c
segfault fix
[ffmpeg] / ffserver.c
index c7b2bc590745d9d672c543bebd8502260d9b05ad..265e3ac579ffa7a80d2f5d7355ac392d19a4bcb4 100644 (file)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  */
 #define HAVE_AV_CONFIG_H
+#include "common.h"
 #include "avformat.h"
 
 #include <stdarg.h>
-#include <netinet/in.h>
 #include <unistd.h>
 #include <fcntl.h>
 #include <sys/ioctl.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <sys/wait.h>
+#include <netinet/in.h>
 #include <arpa/inet.h>
 #include <netdb.h>
 #include <ctype.h>
 #include <signal.h>
+#ifdef CONFIG_HAVE_DLFCN
 #include <dlfcn.h>
+#endif
 
 #include "ffserver.h"
 
@@ -88,7 +91,7 @@ const char *http_state[] = {
 #define SYNC_TIMEOUT (10 * 1000)
 
 typedef struct {
-    INT64 count1, count2;
+    int64_t count1, count2;
     long time1, time2;
 } DataRateData;
 
@@ -99,17 +102,17 @@ typedef struct HTTPContext {
     struct sockaddr_in from_addr; /* origin */
     struct pollfd *poll_entry; /* used when polling */
     long timeout;
-    UINT8 *buffer_ptr, *buffer_end;
+    uint8_t *buffer_ptr, *buffer_end;
     int http_error;
     struct HTTPContext *next;
     int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
-    INT64 data_count;
+    int64_t data_count;
     /* feed input */
     int feed_fd;
     /* input format handling */
     AVFormatContext *fmt_in;
     long start_time;            /* In milliseconds - this wraps fairly often */
-    INT64 first_pts;            /* initial pts value */
+    int64_t first_pts;            /* initial pts value */
     int pts_stream_index;       /* stream we choose as clock reference */
     /* output format handling */
     struct FFStream *stream;
@@ -120,19 +123,18 @@ typedef struct HTTPContext {
     AVFormatContext fmt_ctx; /* instance of FFStream for one user */
     int last_packet_sent; /* true if last data packet was sent */
     int suppress_log;
-    int bandwidth;
     DataRateData datarate;
     int wmp_client_id;
     char protocol[16];
     char method[16];
     char url[128];
     int buffer_size;
-    UINT8 *buffer;
+    uint8_t *buffer;
     int is_packetized; /* if true, the stream is packetized */
     int packet_stream_index; /* current stream for output in state machine */
     
     /* RTSP state specific */
-    UINT8 *pb_buffer; /* XXX: use that in all the code */
+    uint8_t *pb_buffer; /* XXX: use that in all the code */
     ByteIOContext *pb;
     int seq; /* RTSP sequence number */
 
@@ -147,6 +149,8 @@ typedef struct HTTPContext {
                                  seconds max) */
 } HTTPContext;
 
+static AVFrame dummy_frame;
+
 /* each generated stream is described here */
 enum StreamType {
     STREAM_TYPE_LIVE,
@@ -154,6 +158,19 @@ enum StreamType {
     STREAM_TYPE_REDIRECT,
 };
 
+enum IPAddressAction {
+    IP_ALLOW = 1,
+    IP_DENY,
+};
+
+typedef struct IPAddressACL {
+    struct IPAddressACL *next;
+    enum IPAddressAction action;
+    /* These are in host order */
+    struct in_addr first;
+    struct in_addr last;
+} IPAddressACL;
+
 /* description of each stream of the ffserver.conf file */
 typedef struct FFStream {
     enum StreamType stream_type;
@@ -161,6 +178,7 @@ typedef struct FFStream {
     struct FFStream *feed;   /* feed we are using (can be null if
                                 coming from file) */
     AVOutputFormat *fmt;
+    IPAddressACL *acl;
     int nb_streams;
     int prebuffer;      /* Number of millseconds early to start */
     long max_time;      /* Number of milliseconds to run */
@@ -177,16 +195,25 @@ typedef struct FFStream {
     time_t pid_start;  /* Of ffmpeg process */
     char **child_argv;
     struct FFStream *next;
+    int bandwidth; /* bandwidth, in kbits/s */
     /* RTSP options */
     char *rtsp_option;
+    /* multicast specific */
+    int is_multicast;
+    struct in_addr multicast_ip;
+    int multicast_port; /* first port used for multicast */
+    int multicast_ttl;
+    int loop; /* if true, send the stream in loops (only meaningful if file) */
+
     /* feed specific */
     int feed_opened;     /* true if someone is writing to the feed */
     int is_feed;         /* true if it is a feed */
+    int readonly;        /* True if writing is prohibited to the file */
     int conns_served;
-    INT64 bytes_served;
-    INT64 feed_max_size;      /* maximum storage size */
-    INT64 feed_write_index;   /* current write position in feed (it wraps round) */
-    INT64 feed_size;          /* current size of feed */
+    int64_t bytes_served;
+    int64_t feed_max_size;      /* maximum storage size */
+    int64_t feed_write_index;   /* current write position in feed (it wraps round) */
+    int64_t feed_size;          /* current size of feed */
     struct FFStream *next_feed;
 } FFStream;
 
@@ -219,18 +246,24 @@ static int compute_send_delay(HTTPContext *c);
 /* RTSP handling */
 static int rtsp_parse_request(HTTPContext *c);
 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
+static void rtsp_cmd_options(HTTPContext *c, const char *url);
 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);
 
+/* SDP handling */
+static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer, 
+                                   struct in_addr my_ip);
+
 /* RTP handling */
-static HTTPContext *rtp_new_connection(HTTPContext *rtsp_c
+static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr
                                        FFStream *stream, const char *session_id);
 static int rtp_new_av_stream(HTTPContext *c, 
                              int stream_index, struct sockaddr_in *dest_addr);
 
 static const char *my_program_name;
+static const char *my_program_dir;
 
 static int ffserver_debug;
 static int ffserver_daemon;
@@ -240,8 +273,8 @@ static int need_to_start_children;
 int nb_max_connections;
 int nb_connections;
 
-int nb_max_bandwidth;
-int nb_bandwidth;
+int max_bandwidth;
+int current_bandwidth;
 
 static long cur_time;           // Making this global saves on passing it around everywhere
 
@@ -255,7 +288,7 @@ static long gettime_ms(void)
 
 static FILE *logfile = NULL;
 
-static void http_log(char *fmt, ...)
+static void http_log(const char *fmt, ...)
 {
     va_list ap;
     va_start(ap, fmt);
@@ -267,28 +300,34 @@ static void http_log(char *fmt, ...)
     va_end(ap);
 }
 
-static void log_connection(HTTPContext *c)
+static char *ctime1(char *buf2)
 {
-    char buf1[32], buf2[32], *p;
     time_t ti;
+    char *p;
 
-    if (c->suppress_log) 
-        return;
-
-    /* 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';
+    return buf2;
+}
+
+static void log_connection(HTTPContext *c)
+{
+    char buf2[32];
+
+    if (c->suppress_log) 
+        return;
+
     http_log("%s - - [%s] \"%s %s %s\" %d %lld\n", 
-             buf1, buf2, c->method, c->url, c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
+             inet_ntoa(c->from_addr.sin_addr), 
+             ctime1(buf2), c->method, c->url, 
+             c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
 }
 
-static void update_datarate(DataRateData *drd, INT64 count)
+static void update_datarate(DataRateData *drd, int64_t count)
 {
     if (!drd->time1 && !drd->count1) {
         drd->time1 = drd->time2 = cur_time;
@@ -304,14 +343,23 @@ static void update_datarate(DataRateData *drd, INT64 count)
 }
 
 /* In bytes per second */
-static int compute_datarate(DataRateData *drd, INT64 count)
+static int compute_datarate(DataRateData *drd, int64_t count)
 {
     if (cur_time == drd->time1)
         return 0;
-
+    
     return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
 }
 
+static int get_longterm_datarate(DataRateData *drd, int64_t count)
+{
+    /* You get the first 3 seconds flat out */
+    if (cur_time - drd->time1 < 3000)
+        return 0;
+    return compute_datarate(drd, count);
+}
+
+
 static void start_children(FFStream *feed)
 {
     if (no_launch)
@@ -357,6 +405,11 @@ static void start_children(FFStream *feed)
                 }
                 strcpy(slash, "ffmpeg");
 
+                /* This is needed to make relative pathnames work */
+                chdir(my_program_dir);
+
+                signal(SIGPIPE, SIG_DFL);
+
                 execvp(pathname, feed->child_argv);
 
                 _exit(1);
@@ -380,7 +433,9 @@ static int socket_open_listen(struct sockaddr_in *my_addr)
     setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
 
     if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
-        perror ("bind");
+        char bindmsg[32];
+        snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
+        perror (bindmsg);
         close(server_fd);
         return -1;
     }
@@ -395,6 +450,61 @@ static int socket_open_listen(struct sockaddr_in *my_addr)
     return server_fd;
 }
 
+/* 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 */
+            snprintf(session_id, sizeof(session_id), 
+                     "%08x%08x", (int)random(), (int)random());
+
+            /* choose a port if none given */
+            if (stream->multicast_port == 0) {
+                stream->multicast_port = default_port;
+                default_port += 100;
+            }
+
+            dest_addr.sin_family = AF_INET;
+            dest_addr.sin_addr = stream->multicast_ip;
+            dest_addr.sin_port = htons(stream->multicast_port);
+
+            rtp_c = rtp_new_connection(&dest_addr, stream, session_id);
+            if (!rtp_c) {
+                continue;
+            }
+            if (open_input_stream(rtp_c, "") < 0) {
+                fprintf(stderr, "Could not open input stream for stream '%s'\n", 
+                        stream->filename);
+                continue;
+            }
+
+            rtp_c->rtp_protocol = RTSP_PROTOCOL_RTP_UDP_MULTICAST;
+
+            /* open each RTP stream */
+            for(stream_index = 0; stream_index < stream->nb_streams; 
+                stream_index++) {
+                dest_addr.sin_port = htons(stream->multicast_port + 
+                                           2 * stream_index);
+                if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr) < 0) {
+                    fprintf(stderr, "Could not open output stream '%s/streamid=%d'\n", 
+                            stream->filename, stream_index);
+                    exit(1);
+                }
+            }
+
+            /* change state to send data */
+            rtp_c->state = HTTPSTATE_SEND_DATA;
+        }
+    }
+}
 
 /* main loop of the http server */
 static int http_server(void)
@@ -418,6 +528,9 @@ static int http_server(void)
     first_http_ctx = NULL;
     nb_connections = 0;
     first_http_ctx = NULL;
+
+    start_multicast();
+
     for(;;) {
         poll_entry = poll_table;
         poll_entry->fd = server_fd;
@@ -633,7 +746,23 @@ static void close_connection(HTTPContext *c)
         }
     }
 
-    nb_bandwidth -= c->bandwidth;
+    ctx = &c->fmt_ctx;
+
+    if (!c->last_packet_sent) {
+        if (ctx->oformat) {
+            /* prepare header */
+            if (url_open_dyn_buf(&ctx->pb) >= 0) {
+                av_write_trailer(ctx);
+                (void) url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
+            }
+        }
+    }
+
+    for(i=0; i<ctx->nb_streams; i++) 
+        av_free(ctx->streams[i]) ; 
+
+    if (c->stream)
+        current_bandwidth -= c->stream->bandwidth;
     av_freep(&c->pb_buffer);
     av_free(c->buffer);
     av_free(c);
@@ -665,7 +794,7 @@ static int handle_connection(HTTPContext *c)
             return -1;
         } else {
             /* search for end of request. XXX: not fully correct since garbage could come after the end */
-            UINT8 *ptr;
+            uint8_t *ptr;
             c->buffer_ptr += len;
             ptr = c->buffer_ptr;
             if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
@@ -887,6 +1016,10 @@ static int modify_current_stream(HTTPContext *c, char *rates)
     FFStream *req = c->stream;
     int action_required = 0;
 
+    /* Not much we can do for a feed */
+    if (!req->feed)
+        return 0;
+
     for (i = 0; i < req->nb_streams; i++) {
         AVCodecContext *codec = &req->streams[i]->codec;
 
@@ -957,15 +1090,65 @@ static void get_word(char *buf, int buf_size, const char **pp)
     *pp = p;
 }
 
+static int validate_acl(FFStream *stream, HTTPContext *c)
+{
+    enum IPAddressAction last_action = IP_DENY;
+    IPAddressACL *acl;
+    struct in_addr *src = &c->from_addr.sin_addr;
+    unsigned long src_addr = ntohl(src->s_addr);
+
+    for (acl = stream->acl; acl; acl = acl->next) {
+        if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr) {
+            return (acl->action == IP_ALLOW) ? 1 : 0;
+        }
+        last_action = acl->action;
+    }
+
+    /* Nothing matched, so return not the last action */
+    return (last_action == IP_DENY) ? 1 : 0;
+}
+
+/* compute the real filename of a file by matching it without its
+   extensions to all the stream filenames */
+static void compute_real_filename(char *filename, int max_size)
+{
+    char file1[1024];
+    char file2[1024];
+    char *p;
+    FFStream *stream;
+
+    /* compute filename by matching without the file extensions */
+    pstrcpy(file1, sizeof(file1), filename);
+    p = strrchr(file1, '.');
+    if (p)
+        *p = '\0';
+    for(stream = first_stream; stream != NULL; stream = stream->next) {
+        pstrcpy(file2, sizeof(file2), stream->filename);
+        p = strrchr(file2, '.');
+        if (p)
+            *p = '\0';
+        if (!strcmp(file1, file2)) {
+            pstrcpy(filename, max_size, stream->filename);
+            break;
+        }
+    }
+}
+
+enum RedirType {
+    REDIR_NONE,
+    REDIR_ASX,
+    REDIR_RAM,
+    REDIR_ASF,
+    REDIR_RTSP,
+    REDIR_SDP,
+};
+
 /* parse http request and prepare header */
 static int http_parse_request(HTTPContext *c)
 {
     char *p;
     int post;
-    int doing_asx;
-    int doing_asf_redirector;
-    int doing_ram;
-    int doing_rtsp_redirector;
+    enum RedirType redir_type;
     char cmd[32];
     char info[1024], *filename;
     char url[1024], *q;
@@ -1024,60 +1207,28 @@ static int http_parse_request(HTTPContext *c)
         p++;
     }
 
-    if (strlen(filename) > 4 && strcmp(".asx", filename + strlen(filename) - 4) == 0) {
-        doing_asx = 1;
+    redir_type = REDIR_NONE;
+    if (match_ext(filename, "asx")) {
+        redir_type = REDIR_ASX;
         filename[strlen(filename)-1] = 'f';
-    } else {
-        doing_asx = 0;
-    }
-
-    if (strlen(filename) > 4 && strcmp(".asf", filename + strlen(filename) - 4) == 0 &&
+    } else if (match_ext(filename, "asf") &&
         (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
         /* if this isn't WMP or lookalike, return the redirector file */
-        doing_asf_redirector = 1;
-    } else {
-        doing_asf_redirector = 0;
-    }
-
-    if (strlen(filename) > 4 && 
-        (strcmp(".rpm", filename + strlen(filename) - 4) == 0 ||
-         strcmp(".ram", filename + strlen(filename) - 4) == 0)) {
-        doing_ram = 1;
+        redir_type = REDIR_ASF;
+    } else if (match_ext(filename, "rpm,ram")) {
+        redir_type = REDIR_RAM;
         strcpy(filename + strlen(filename)-2, "m");
-    } else {
-        doing_ram = 0;
+    } else if (match_ext(filename, "rtsp")) {
+        redir_type = REDIR_RTSP;
+        compute_real_filename(filename, sizeof(url) - 1);
+    } else if (match_ext(filename, "sdp")) {
+        redir_type = REDIR_SDP;
+        compute_real_filename(filename, sizeof(url) - 1);
     }
-
-    if (strlen(filename) > 5 && 
-        strcmp(".rtsp", filename + strlen(filename) - 5) == 0) {
-        char file1[1024];
-        char file2[1024];
-        char *p;
-
-        doing_rtsp_redirector = 1;
-        /* compute filename by matching without the file extensions */
-        pstrcpy(file1, sizeof(file1), filename);
-        p = strrchr(file1, '.');
-        if (p)
-            *p = '\0';
-        for(stream = first_stream; stream != NULL; stream = stream->next) {
-            pstrcpy(file2, sizeof(file2), stream->filename);
-            p = strrchr(file2, '.');
-            if (p)
-                *p = '\0';
-            if (!strcmp(file1, file2)) {
-                pstrcpy(url, sizeof(url), stream->filename);
-                filename = url;
-                break;
-            }
-        }
-    } else {
-        doing_rtsp_redirector = 0;
-    }
-
+    
     stream = first_stream;
     while (stream != NULL) {
-        if (!strcmp(stream->filename, filename))
+        if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
             break;
         stream = stream->next;
     }
@@ -1119,26 +1270,10 @@ static int http_parse_request(HTTPContext *c)
     }
 
     if (post == 0 && stream->stream_type == STREAM_TYPE_LIVE) {
-        /* See if we meet the bandwidth requirements */
-        for(i=0;i<stream->nb_streams;i++) {
-            AVStream *st = stream->streams[i];
-            switch(st->codec.codec_type) {
-            case CODEC_TYPE_AUDIO:
-                c->bandwidth += st->codec.bit_rate;
-                break;
-            case CODEC_TYPE_VIDEO:
-                c->bandwidth += st->codec.bit_rate;
-                break;
-            default:
-                av_abort();
-            }
-        }
+        current_bandwidth += stream->bandwidth;
     }
-
-    c->bandwidth /= 1000;
-    nb_bandwidth += c->bandwidth;
-
-    if (post == 0 && nb_max_bandwidth < nb_bandwidth) {
+    
+    if (post == 0 && max_bandwidth < current_bandwidth) {
         c->http_error = 200;
         q = c->buffer;
         q += sprintf(q, "HTTP/1.0 200 Server too busy\r\n");
@@ -1147,7 +1282,7 @@ static int http_parse_request(HTTPContext *c)
         q += sprintf(q, "<html><head><title>Too busy</title></head><body>\r\n");
         q += sprintf(q, "The server is too busy to serve your request at this time.<p>\r\n");
         q += sprintf(q, "The bandwidth being served (including your stream) is %dkbit/sec, and this exceeds the limit of %dkbit/sec\r\n",
-            nb_bandwidth, nb_max_bandwidth);
+            current_bandwidth, max_bandwidth);
         q += sprintf(q, "</body></html>\r\n");
 
         /* prepare output buffer */
@@ -1157,8 +1292,7 @@ static int http_parse_request(HTTPContext *c)
         return 0;
     }
     
-    if (doing_asx || doing_ram || doing_asf_redirector || 
-        doing_rtsp_redirector) {
+    if (redir_type != REDIR_NONE) {
         char *hostinfo = 0;
         
         for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
@@ -1191,7 +1325,8 @@ static int http_parse_request(HTTPContext *c)
 
                     c->http_error = 200;
                     q = c->buffer;
-                    if (doing_asx) {
+                    switch(redir_type) {
+                    case REDIR_ASX:
                         q += sprintf(q, "HTTP/1.0 200 ASX Follows\r\n");
                         q += sprintf(q, "Content-type: video/x-ms-asf\r\n");
                         q += sprintf(q, "\r\n");
@@ -1200,36 +1335,68 @@ static int http_parse_request(HTTPContext *c)
                         q += sprintf(q, "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n", 
                                 hostbuf, filename, info);
                         q += sprintf(q, "</ASX>\r\n");
-                    } else if (doing_ram) {
+                        break;
+                    case REDIR_RAM:
                         q += sprintf(q, "HTTP/1.0 200 RAM Follows\r\n");
                         q += sprintf(q, "Content-type: audio/x-pn-realaudio\r\n");
                         q += sprintf(q, "\r\n");
                         q += sprintf(q, "# Autogenerated by ffserver\r\n");
                         q += sprintf(q, "http://%s/%s%s\r\n", 
                                 hostbuf, filename, info);
-                    } else if (doing_asf_redirector) {
+                        break;
+                    case REDIR_ASF:
                         q += sprintf(q, "HTTP/1.0 200 ASF Redirect follows\r\n");
                         q += sprintf(q, "Content-type: video/x-ms-asf\r\n");
                         q += sprintf(q, "\r\n");
                         q += sprintf(q, "[Reference]\r\n");
                         q += sprintf(q, "Ref1=http://%s/%s%s\r\n", 
                                 hostbuf, filename, info);
-                    } else if (doing_rtsp_redirector) {
-                        char hostname[256], *p;
-                        /* extract only hostname */
-                        pstrcpy(hostname, sizeof(hostname), hostbuf);
-                        p = strrchr(hostname, ':');
-                        if (p)
-                            *p = '\0';
-                        q += sprintf(q, "HTTP/1.0 200 RTSP Redirect follows\r\n");
-                        /* XXX: incorrect mime type ? */
-                        q += sprintf(q, "Content-type: application/x-rtsp\r\n");
-                        q += sprintf(q, "\r\n");
-                        q += sprintf(q, "rtsp://%s:%d/%s\r\n", 
-                                     hostname, ntohs(my_rtsp_addr.sin_port), 
-                                     filename);
-                    } else {
+                        break;
+                    case REDIR_RTSP:
+                        {
+                            char hostname[256], *p;
+                            /* extract only hostname */
+                            pstrcpy(hostname, sizeof(hostname), hostbuf);
+                            p = strrchr(hostname, ':');
+                            if (p)
+                                *p = '\0';
+                            q += sprintf(q, "HTTP/1.0 200 RTSP Redirect follows\r\n");
+                            /* XXX: incorrect mime type ? */
+                            q += sprintf(q, "Content-type: application/x-rtsp\r\n");
+                            q += sprintf(q, "\r\n");
+                            q += sprintf(q, "rtsp://%s:%d/%s\r\n", 
+                                         hostname, ntohs(my_rtsp_addr.sin_port), 
+                                         filename);
+                        }
+                        break;
+                    case REDIR_SDP:
+                        {
+                            uint8_t *sdp_data;
+                            int sdp_data_size, len;
+                            struct sockaddr_in my_addr;
+
+                            q += sprintf(q, "HTTP/1.0 200 OK\r\n");
+                            q += sprintf(q, "Content-type: application/sdp\r\n");
+                            q += sprintf(q, "\r\n");
+
+                            len = sizeof(my_addr);
+                            getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
+                            
+                            /* XXX: should use a dynamic buffer */
+                            sdp_data_size = prepare_sdp_description(stream, 
+                                                                    &sdp_data, 
+                                                                    my_addr.sin_addr);
+                            if (sdp_data_size > 0) {
+                                memcpy(q, sdp_data, sdp_data_size);
+                                q += sdp_data_size;
+                                *q = '\0';
+                                av_free(sdp_data);
+                            }
+                        }
+                        break;
+                    default:
                         av_abort();
+                        break;
                     }
 
                     /* prepare output buffer */
@@ -1307,6 +1474,7 @@ static int http_parse_request(HTTPContext *c)
             }
             
             sprintf(msg, "POST command not handled");
+            c->stream = 0;
             goto send_error;
         }
         if (http_start_receive_data(c) < 0) {
@@ -1342,17 +1510,12 @@ static int http_parse_request(HTTPContext *c)
     q += sprintf(q, "Pragma: no-cache\r\n");
 
     /* for asf, we need extra headers */
-    if (!strcmp(c->stream->fmt->name,"asf")) {
+    if (!strcmp(c->stream->fmt->name,"asf_stream")) {
         /* Need to allocate a client id */
-        static int wmp_session;
-
-        if (!wmp_session)
-            wmp_session = time(0) & 0xffffff;
 
-        c->wmp_client_id = ++wmp_session;
+        c->wmp_client_id = random() & 0x7fffffff;
 
         q += sprintf(q, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id);
-        mime_type = "application/octet-stream"; 
     }
     q += sprintf(q, "Content-Type: %s\r\n", mime_type);
     q += sprintf(q, "\r\n");
@@ -1387,7 +1550,7 @@ static int http_parse_request(HTTPContext *c)
     return 0;
 }
 
-static void fmt_bytecount(ByteIOContext *pb, INT64 count)
+static void fmt_bytecount(ByteIOContext *pb, int64_t count)
 {
     static const char *suffix = " kMGTP";
     const char *s;
@@ -1443,12 +1606,16 @@ static void compute_stats(HTTPContext *c)
                 } else if (strcmp(eosf - 3, ".rm") == 0) {
                     strcpy(eosf - 3, ".ram");
                 } else if (stream->fmt == &rtp_mux) {
-                    /* generate a sample RTSP director - maybe should
-                       generate a .sdp file ? */
+                    /* generate a sample RTSP director if
+                       unicast. Generate an SDP redirector if
+                       multicast */
                     eosf = strrchr(sfilename, '.');
                     if (!eosf)
                         eosf = sfilename + strlen(sfilename);
-                    strcpy(eosf, ".rtsp");
+                    if (stream->is_multicast)
+                        strcpy(eosf, ".sdp");
+                    else
+                        strcpy(eosf, ".rtsp");
                 }
             }
             
@@ -1462,10 +1629,10 @@ static void compute_stats(HTTPContext *c)
                 {
                     int audio_bit_rate = 0;
                     int video_bit_rate = 0;
-                    char *audio_codec_name = "";
-                    char *video_codec_name = "";
-                    char *audio_codec_name_extra = "";
-                    char *video_codec_name_extra = "";
+                    const char *audio_codec_name = "";
+                    const char *video_codec_name = "";
+                    const char *audio_codec_name_extra = "";
+                    const char *video_codec_name_extra = "";
 
                     for(i=0;i<stream->nb_streams;i++) {
                         AVStream *st = stream->streams[i];
@@ -1493,7 +1660,7 @@ static void compute_stats(HTTPContext *c)
                     }
                     url_fprintf(pb, "<TD align=center> %s <TD align=right> %d <TD align=right> %d <TD> %s %s <TD align=right> %d <TD> %s %s", 
                                  stream->fmt->name,
-                                 (audio_bit_rate + video_bit_rate) / 1000,
+                                 stream->bandwidth,
                                  video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
                                  audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
                     if (stream->feed) {
@@ -1552,7 +1719,7 @@ static void compute_stats(HTTPContext *c)
             for (i = 0; i < stream->nb_streams; i++) {
                 AVStream *st = stream->streams[i];
                 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
-                char *type = "unknown";
+                const char *type = "unknown";
                 char parameters[64];
 
                 parameters[0] = 0;
@@ -1564,7 +1731,7 @@ static void compute_stats(HTTPContext *c)
                 case CODEC_TYPE_VIDEO:
                     type = "video";
                     sprintf(parameters, "%dx%d, q=%d-%d, fps=%d", st->codec.width, st->codec.height,
-                                st->codec.qmin, st->codec.qmax, st->codec.frame_rate / FRAME_RATE_BASE);
+                                st->codec.qmin, st->codec.qmax, st->codec.frame_rate / st->codec.frame_rate_base);
                     break;
                 default:
                     av_abort();
@@ -1615,7 +1782,7 @@ static void compute_stats(HTTPContext *c)
                  nb_connections, nb_max_connections);
 
     url_fprintf(pb, "Bandwidth in use: %dk / %dk<BR>\n",
-                 nb_bandwidth, nb_max_bandwidth);
+                 current_bandwidth, max_bandwidth);
 
     url_fprintf(pb, "<TABLE>\n");
     url_fprintf(pb, "<TR><th>#<th>File<th>IP<th>Proto<th>State<th>Target bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
@@ -1691,7 +1858,7 @@ static int open_input_stream(HTTPContext *c, const char *info)
     char input_filename[1024];
     AVFormatContext *s;
     int buf_size, i;
-    INT64 stream_pos;
+    int64_t stream_pos;
 
     /* find file name */
     if (c->stream->feed) {
@@ -1702,9 +1869,9 @@ static int open_input_stream(HTTPContext *c, const char *info)
             stream_pos = parse_date(buf, 0);
         } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
             int prebuffer = strtol(buf, 0, 10);
-            stream_pos = av_gettime() - prebuffer * 1000000;
+            stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
         } else {
-            stream_pos = av_gettime() - c->stream->prebuffer * 1000;
+            stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
         }
     } else {
         strcpy(input_filename, c->stream->feed_filename);
@@ -1719,6 +1886,12 @@ static int open_input_stream(HTTPContext *c, const char *info)
     if (input_filename[0] == '\0')
         return -1;
 
+#if 0
+    { time_t when = stream_pos / 1000000;
+    http_log("Stream pos = %lld, time=%s", stream_pos, ctime(&when));
+    }
+#endif
+
     /* open stream */
     if (av_open_input_file(&s, input_filename, NULL, buf_size, NULL) < 0) {
         http_log("%s not found", input_filename);
@@ -1746,7 +1919,6 @@ static int open_input_stream(HTTPContext *c, const char *info)
     /* set the start time (needed for maxtime and RTP packet timing) */
     c->start_time = cur_time;
     c->first_pts = AV_NOPTS_VALUE;
-    printf("stream %s opened pos=%0.6f\n", input_filename, stream_pos / 1000000.0);
     return 0;
 }
 
@@ -1779,14 +1951,14 @@ int av_read_frame(AVFormatContext *s, AVPacket *pkt)
                     if (st->pts.den == 0) {
                         switch(st->codec.codec_type) {
                         case CODEC_TYPE_AUDIO:
-                            st->pts_incr = (INT64)s->pts_den;
+                            st->pts_incr = (int64_t)s->pts_den;
                             av_frac_init(&st->pts, st->pts.val, 0, 
-                                         (INT64)s->pts_num * st->codec.sample_rate);
+                                         (int64_t)s->pts_num * st->codec.sample_rate);
                             break;
                         case CODEC_TYPE_VIDEO:
-                            st->pts_incr = (INT64)s->pts_den * FRAME_RATE_BASE;
+                            st->pts_incr = (int64_t)s->pts_den * st->codec.frame_rate_base;
                             av_frac_init(&st->pts, st->pts.val, 0,
-                                         (INT64)s->pts_num * st->codec.frame_rate);
+                                         (int64_t)s->pts_num * st->codec.frame_rate);
                             break;
                         default:
                             av_abort();
@@ -1813,7 +1985,7 @@ int av_read_frame(AVFormatContext *s, AVPacket *pkt)
                     /* we use the codec indication because it is
                        more accurate than the demux flags */
                     pkt->flags = 0;
-                    if (st->codec.key_frame) 
+                    if (st->codec.coded_frame->key_frame) 
                         pkt->flags |= PKT_FLAG_KEY;
                     return 0;
                 }
@@ -1847,14 +2019,14 @@ int av_read_frame(AVFormatContext *s, AVPacket *pkt)
                 if (st->pts.den == 0) {
                     switch(st->codec.codec_type) {
                     case CODEC_TYPE_AUDIO:
-                        st->pts_incr = (INT64)s->pts_den * st->codec.frame_size;
+                        st->pts_incr = (int64_t)s->pts_den * st->codec.frame_size;
                         av_frac_init(&st->pts, st->pts.val, 0, 
-                                     (INT64)s->pts_num * st->codec.sample_rate);
+                                     (int64_t)s->pts_num * st->codec.sample_rate);
                         break;
                     case CODEC_TYPE_VIDEO:
-                        st->pts_incr = (INT64)s->pts_den * FRAME_RATE_BASE;
+                        st->pts_incr = (int64_t)s->pts_den * st->codec.frame_rate_base;
                         av_frac_init(&st->pts, st->pts.val, 0,
-                                     (INT64)s->pts_num * st->codec.frame_rate);
+                                     (int64_t)s->pts_num * st->codec.frame_rate);
                         break;
                     default:
                         av_abort();
@@ -1872,11 +2044,11 @@ int av_read_frame(AVFormatContext *s, AVPacket *pkt)
 
 static int compute_send_delay(HTTPContext *c)
 {
-    INT64 cur_pts, delta_pts, next_pts;
+    int64_t cur_pts, delta_pts, next_pts;
     int delay1;
     
     /* compute current pts value from system time */
-    cur_pts = ((INT64)(cur_time - c->start_time) * c->fmt_in->pts_den) / 
+    cur_pts = ((int64_t)(cur_time - c->start_time) * c->fmt_in->pts_den) / 
         (c->fmt_in->pts_num * 1000LL);
     /* compute the delta from the stream we choose as
        main clock (we do that to avoid using explicit
@@ -1898,13 +2070,18 @@ static int compute_send_delay(HTTPContext *c)
 #else
 
 /* just fall backs */
-int av_read_frame(AVFormatContext *s, AVPacket *pkt)
+static int av_read_frame(AVFormatContext *s, AVPacket *pkt)
 {
     return av_read_packet(s, pkt);
 }
 
 static int compute_send_delay(HTTPContext *c)
 {
+    int datarate = 8 * get_longterm_datarate(&c->datarate, c->data_count); 
+
+    if (datarate > c->stream->bandwidth * 2000) {
+        return 1000;
+    }
     return 0;
 }
 
@@ -1943,6 +2120,10 @@ static int http_prepare_data(HTTPContext *c)
                            sizeof(AVStream));
             st->codec.frame_number = 0; /* XXX: should be done in
                                            AVStream, not in codec */
+            /* I'm pretty sure that this is not correct...
+             * However, without it, we crash
+             */
+            st->codec.coded_frame = &dummy_frame;
         }
         c->got_key_frame = 0;
 
@@ -1953,6 +2134,7 @@ static int http_prepare_data(HTTPContext *c)
         }
         c->fmt_ctx.pb.is_streamed = 1;
 
+        av_set_parameters(&c->fmt_ctx, NULL);
         av_write_header(&c->fmt_ctx);
 
         len = url_close_dyn_buf(&c->fmt_ctx.pb, &c->pb_buffer);
@@ -1979,12 +2161,13 @@ static int http_prepare_data(HTTPContext *c)
                 /* We have timed out */
                 c->state = HTTPSTATE_SEND_DATA_TRAILER;
             } else {
-                if (c->is_packetized) {
+                if (1 || c->is_packetized) {
                     if (compute_send_delay(c) > 0) {
                         c->state = HTTPSTATE_WAIT;
                         return 1; /* state changed */
                     }
                 }
+            redo:
                 if (av_read_frame(c->fmt_in, &pkt) < 0) {
                     if (c->stream->feed && c->stream->feed->feed_opened) {
                         /* if coming from feed, it means we reached the end of the
@@ -1992,8 +2175,17 @@ static int http_prepare_data(HTTPContext *c)
                         c->state = HTTPSTATE_WAIT_FEED;
                         return 1; /* state changed */
                     } else {
-                        /* must send trailer now because eof or error */
-                        c->state = HTTPSTATE_SEND_DATA_TRAILER;
+                        if (c->stream->loop) {
+                            av_close_input_file(c->fmt_in);
+                            c->fmt_in = NULL;
+                            if (open_input_stream(c, "") < 0)
+                                goto no_loop;
+                            goto redo;
+                        } else {
+                        no_loop:
+                            /* must send trailer now because eof or error */
+                            c->state = HTTPSTATE_SEND_DATA_TRAILER;
+                        }
                     }
                 } else {
                     /* update first pts if needed */
@@ -2046,13 +2238,15 @@ static int http_prepare_data(HTTPContext *c)
                             c->packet_stream_index = pkt.stream_index;
                             ctx = c->rtp_ctx[c->packet_stream_index];
                             codec = &ctx->streams[0]->codec;
+                            /* only one stream per RTP connection */
+                            pkt.stream_index = 0;
                         } else {
                             ctx = &c->fmt_ctx;
                             /* Fudge here */
                             codec = &ctx->streams[pkt.stream_index]->codec;
                         }
                         
-                        codec->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);
+                        codec->coded_frame->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);
                         
 #ifdef PJSG
                         if (codec->codec_type == CODEC_TYPE_AUDIO) {
@@ -2073,7 +2267,7 @@ static int http_prepare_data(HTTPContext *c)
                             /* XXX: potential leak */
                             return -1;
                         }
-                        if (av_write_packet(ctx, &pkt, pkt.pts)) {
+                        if (av_write_frame(ctx, pkt.stream_index, pkt.data, pkt.size)) {
                             c->state = HTTPSTATE_SEND_DATA_TRAILER;
                         }
                         
@@ -2155,8 +2349,8 @@ static int http_send_data(HTTPContext *c)
             if (dt < 1)
                 dt = 1;
 
-            if ((c->packet_byte_count + len) * (INT64)1000000 >= 
-                (SHORT_TERM_BANDWIDTH / 8) * (INT64)dt) {
+            if ((c->packet_byte_count + len) * (int64_t)1000000 >= 
+                (SHORT_TERM_BANDWIDTH / 8) * (int64_t)dt) {
                 /* bandwidth overflow : wait at most one tick and retry */
                 c->state = HTTPSTATE_WAIT_SHORT;
                 return 0;
@@ -2196,6 +2390,10 @@ static int http_start_receive_data(HTTPContext *c)
     if (c->stream->feed_opened)
         return -1;
 
+    /* Don't permit writing to this one */
+    if (c->stream->readonly)
+        return -1;
+
     /* open feed */
     fd = open(c->stream->feed_filename, O_RDWR);
     if (fd < 0)
@@ -2284,9 +2482,12 @@ static int http_receive_data(HTTPContext *c)
             if (!fmt_in)
                 goto fail;
 
-            s.priv_data = av_mallocz(fmt_in->priv_data_size);
-            if (!s.priv_data)
-                goto fail;
+            if (fmt_in->priv_data_size > 0) {
+                s.priv_data = av_mallocz(fmt_in->priv_data_size);
+                if (!s.priv_data)
+                    goto fail;
+           } else
+               s.priv_data = NULL;
 
             if (fmt_in->read_header(&s, 0) < 0) {
                 av_freep(&s.priv_data);
@@ -2418,6 +2619,8 @@ static int rtsp_parse_request(HTTPContext *c)
 
     if (!strcmp(cmd, "DESCRIBE")) {
         rtsp_cmd_describe(c, url);
+    } else if (!strcmp(cmd, "OPTIONS")) {
+        rtsp_cmd_options(c, url);
     } else if (!strcmp(cmd, "SETUP")) {
         rtsp_cmd_setup(c, url, header);
     } else if (!strcmp(cmd, "PLAY")) {
@@ -2442,25 +2645,23 @@ static int rtsp_parse_request(HTTPContext *c)
     return 0;
 }
 
-static int prepare_sdp_description(HTTPContext *c, 
-                                   FFStream *stream, UINT8 **pbuffer)
+/* XXX: move that to rtsp.c, but would need to replace FFStream by
+   AVFormatContext */
+static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer, 
+                                   struct in_addr my_ip)
 {
     ByteIOContext pb1, *pb = &pb1;
-    struct sockaddr_in my_addr;
-    int len, i, payload_type;
+    int i, payload_type, port, private_payload_type, j;
     const char *ipstr, *title, *mediatype;
     AVStream *st;
     
-    len = sizeof(my_addr);
-    getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
-    ipstr = inet_ntoa(my_addr.sin_addr);
-
     if (url_open_dyn_buf(pb) < 0)
         return -1;
     
     /* general media info */
 
     url_fprintf(pb, "v=0\n");
+    ipstr = inet_ntoa(my_ip);
     url_fprintf(pb, "o=- 0 0 IN IP4 %s\n", ipstr);
     title = stream->title;
     if (title[0] == '\0')
@@ -2468,8 +2669,11 @@ static int prepare_sdp_description(HTTPContext *c,
     url_fprintf(pb, "s=%s\n", title);
     if (stream->comment[0] != '\0')
         url_fprintf(pb, "i=%s\n", stream->comment);
-    
+    if (stream->is_multicast) {
+        url_fprintf(pb, "c=IN IP4 %s\n", inet_ntoa(stream->multicast_ip));
+    }
     /* for each stream, we output the necessary info */
+    private_payload_type = 96;
     for(i = 0; i < stream->nb_streams; i++) {
         st = stream->streams[i];
         switch(st->codec.codec_type) {
@@ -2483,15 +2687,58 @@ static int prepare_sdp_description(HTTPContext *c,
             mediatype = "application";
             break;
         }
-        /* XXX: the port indication is not correct (but should be correct
-           for broadcast) */
+        /* NOTE: the port indication is not correct in case of
+           unicast. It is not an issue because RTSP gives it */
         payload_type = rtp_get_payload_type(&st->codec);
-
+        if (payload_type < 0)
+            payload_type = private_payload_type++;
+        if (stream->is_multicast) {
+            port = stream->multicast_port + 2 * i;
+        } else {
+            port = 0;
+        }
         url_fprintf(pb, "m=%s %d RTP/AVP %d\n", 
-                    mediatype, 0, payload_type);
+                    mediatype, port, payload_type);
+        if (payload_type >= 96) {
+            /* for private payload type, we need to give more info */
+            switch(st->codec.codec_id) {
+            case CODEC_ID_MPEG4:
+                {
+                    uint8_t *data;
+                    url_fprintf(pb, "a=rtpmap:%d MP4V-ES/%d\n", 
+                                payload_type, 90000);
+                    /* we must also add the mpeg4 header */
+                    data = st->codec.extradata;
+                    if (data) {
+                        url_fprintf(pb, "a=fmtp:%d config=");
+                        for(j=0;j<st->codec.extradata_size;j++) {
+                            url_fprintf(pb, "%02x", data[j]);
+                        }
+                        url_fprintf(pb, "\n");
+                    }
+                }
+                break;
+            default:
+                /* XXX: add other codecs ? */
+                goto fail;
+            }
+        }
         url_fprintf(pb, "a=control:streamid=%d\n", i);
     }
     return url_close_dyn_buf(pb, pbuffer);
+ fail:
+    url_close_dyn_buf(pb, pbuffer);
+    av_free(*pbuffer);
+    return -1;
+}
+
+static void rtsp_cmd_options(HTTPContext *c, const char *url)
+{
+//    rtsp_reply_header(c, RTSP_STATUS_OK);
+    url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
+    url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
+    url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
+    url_fprintf(c->pb, "\r\n");
 }
 
 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
@@ -2499,8 +2746,9 @@ static void rtsp_cmd_describe(HTTPContext *c, const char *url)
     FFStream *stream;
     char path1[1024];
     const char *path;
-    UINT8 *content;
-    int content_length;
+    uint8_t *content;
+    int content_length, len;
+    struct sockaddr_in my_addr;
     
     /* find which url is asked */
     url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
@@ -2520,7 +2768,12 @@ static void rtsp_cmd_describe(HTTPContext *c, const char *url)
 
  found:
     /* prepare the media description in sdp format */
-    content_length = prepare_sdp_description(c, stream, &content);
+
+    /* get the host IP */
+    len = sizeof(my_addr);
+    getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
+    
+    content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
     if (content_length < 0) {
         rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
         return;
@@ -2546,7 +2799,7 @@ static HTTPContext *find_rtp_session(const char *session_id)
     return NULL;
 }
 
-RTSPTransportField *find_transport(RTSPHeader *h, enum RTSPProtocol protocol)
+static RTSPTransportField *find_transport(RTSPHeader *h, enum RTSPProtocol protocol)
 {
     RTSPTransportField *th;
     int i;
@@ -2614,7 +2867,7 @@ static void rtsp_cmd_setup(HTTPContext *c, const char *url,
     /* find rtp session, and create it if none found */
     rtp_c = find_rtp_session(h->session_id);
     if (!rtp_c) {
-        rtp_c = rtp_new_connection(c, stream, h->session_id);
+        rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id);
         if (!rtp_c) {
             rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
             return;
@@ -2816,7 +3069,7 @@ static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h)
 /********************************************************************/
 /* RTP handling */
 
-static HTTPContext *rtp_new_connection(HTTPContext *rtsp_c
+static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr
                                        FFStream *stream, const char *session_id)
 {
     HTTPContext *c = NULL;
@@ -2833,7 +3086,7 @@ static HTTPContext *rtp_new_connection(HTTPContext *rtsp_c,
     
     c->fd = -1;
     c->poll_entry = NULL;
-    c->from_addr = rtsp_c->from_addr;
+    c->from_addr = *from_addr;
     c->buffer_size = IOBUFFER_INIT_SIZE;
     c->buffer = av_malloc(c->buffer_size);
     if (!c->buffer)
@@ -2846,6 +3099,8 @@ static HTTPContext *rtp_new_connection(HTTPContext *rtsp_c,
     /* protocol is shown in statistics */
     pstrcpy(c->protocol, sizeof(c->protocol), "RTP");
 
+    current_bandwidth += stream->bandwidth;
+
     c->next = first_http_ctx;
     first_http_ctx = c;
     return c;
@@ -2868,8 +3123,9 @@ static int rtp_new_av_stream(HTTPContext *c,
     AVStream *st;
     char *ipaddr;
     URLContext *h;
-    UINT8 *dummy_buf;
-
+    uint8_t *dummy_buf;
+    char buf2[32];
+    
     /* now we can open the relevant output stream */
     ctx = av_mallocz(sizeof(AVFormatContext));
     if (!ctx)
@@ -2895,10 +3151,19 @@ static int rtp_new_av_stream(HTTPContext *c,
         /* build destination RTP address */
         ipaddr = inet_ntoa(dest_addr->sin_addr);
         
-        snprintf(ctx->filename, sizeof(ctx->filename),
-                 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
-        
-        printf("open %s\n", ctx->filename);
+        /* XXX: also pass as parameter to function ? */
+        if (c->stream->is_multicast) {
+            int ttl;
+            ttl = c->stream->multicast_ttl;
+            if (!ttl)
+                ttl = 16;
+            snprintf(ctx->filename, sizeof(ctx->filename),
+                     "rtp://%s:%d?multicast=1&ttl=%d", 
+                     ipaddr, ntohs(dest_addr->sin_port), ttl);
+        } else {
+            snprintf(ctx->filename, sizeof(ctx->filename),
+                     "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
+        }
 
         if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
             goto fail;
@@ -2907,12 +3172,18 @@ static int rtp_new_av_stream(HTTPContext *c,
         goto fail;
     }
 
+    http_log("%s:%d - - [%s] \"RTPSTART %s/streamid=%d\"\n",
+             ipaddr, ntohs(dest_addr->sin_port), 
+             ctime1(buf2), 
+             c->stream->filename, stream_index);
+
     /* normally, no packets should be output here, but the packet size may be checked */
     if (url_open_dyn_packet_buf(&ctx->pb, 
                                 url_get_max_packet_size(h)) < 0) {
         /* XXX: close stream */
         goto fail;
     }
+    av_set_parameters(ctx, NULL);
     if (av_write_header(ctx) < 0) {
     fail:
         if (h)
@@ -2930,7 +3201,7 @@ static int rtp_new_av_stream(HTTPContext *c,
 /********************************************************************/
 /* ffserver initialization */
 
-AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
+static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
 {
     AVStream *fst;
 
@@ -2939,13 +3210,13 @@ AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
         return NULL;
     fst->priv_data = av_mallocz(sizeof(FeedData));
     memcpy(&fst->codec, codec, sizeof(AVCodecContext));
+    fst->codec.coded_frame = &dummy_frame;
     stream->streams[stream->nb_streams++] = fst;
     return fst;
 }
 
 /* return the stream number in the feed */
-int add_av_stream(FFStream *feed,
-                  AVStream *st)
+static int add_av_stream(FFStream *feed, AVStream *st)
 {
     AVStream *fst;
     AVCodecContext *av, *av1;
@@ -2969,6 +3240,7 @@ int add_av_stream(FFStream *feed,
                 if (av1->width == av->width &&
                     av1->height == av->height &&
                     av1->frame_rate == av->frame_rate &&
+                    av1->frame_rate_base == av->frame_rate_base &&
                     av1->gop_size == av->gop_size)
                     goto found;
                 break;
@@ -2986,7 +3258,7 @@ int add_av_stream(FFStream *feed,
     return i;
 }
 
-void remove_stream(FFStream *stream)
+static void remove_stream(FFStream *stream)
 {
     FFStream **ps;
     ps = &first_stream;
@@ -2999,8 +3271,56 @@ void remove_stream(FFStream *stream)
     }
 }
 
+/* specific mpeg4 handling : we extract the raw parameters */
+static void extract_mpeg4_header(AVFormatContext *infile)
+{
+    int mpeg4_count, i, size;
+    AVPacket pkt;
+    AVStream *st;
+    const uint8_t *p;
+
+    mpeg4_count = 0;
+    for(i=0;i<infile->nb_streams;i++) {
+        st = infile->streams[i];
+        if (st->codec.codec_id == CODEC_ID_MPEG4 &&
+            st->codec.extradata == NULL) {
+            mpeg4_count++;
+        }
+    }
+    if (!mpeg4_count)
+        return;
+
+    printf("MPEG4 without extra data: trying to find header\n");
+    while (mpeg4_count > 0) {
+        if (av_read_packet(infile, &pkt) < 0)
+            break;
+        st = infile->streams[pkt.stream_index];
+        if (st->codec.codec_id == CODEC_ID_MPEG4 &&
+            st->codec.extradata == NULL) {
+            /* fill extradata with the header */
+            /* XXX: we make hard suppositions here ! */
+            p = pkt.data;
+            while (p < pkt.data + pkt.size - 4) {
+                /* stop when vop header is found */
+                if (p[0] == 0x00 && p[1] == 0x00 && 
+                    p[2] == 0x01 && p[3] == 0xb6) {
+                    size = p - pkt.data;
+                    //                    av_hex_dump(pkt.data, size);
+                    st->codec.extradata = av_malloc(size);
+                    st->codec.extradata_size = size;
+                    memcpy(st->codec.extradata, pkt.data, size);
+                    break;
+                }
+                p++;
+            }
+            mpeg4_count--;
+        }
+        av_free_packet(&pkt);
+    }
+}
+
 /* compute the needed AVStream for each file */
-void build_file_streams(void)
+static void build_file_streams(void)
 {
     FFStream *stream, *stream_next;
     AVFormatContext *infile;
@@ -3029,6 +3349,8 @@ void build_file_streams(void)
                     av_close_input_file(infile);
                     goto fail;
                 }
+                extract_mpeg4_header(infile);
+
                 for(i=0;i<infile->nb_streams;i++) {
                     add_av_stream1(stream, &infile->streams[i]->codec);
                 }
@@ -3039,7 +3361,7 @@ void build_file_streams(void)
 }
 
 /* compute the needed AVStream for each feed */
-void build_feed_streams(void)
+static void build_feed_streams(void)
 {
     FFStream *stream, *feed;
     int i;
@@ -3073,9 +3395,89 @@ void build_feed_streams(void)
     for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
         int fd;
 
+        if (url_exist(feed->feed_filename)) {
+            /* See if it matches */
+            AVFormatContext *s;
+            int matches = 0;
+
+            if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) {
+                /* Now see if it matches */
+                if (s->nb_streams == feed->nb_streams) {
+                    matches = 1;
+                    for(i=0;i<s->nb_streams;i++) {
+                        AVStream *sf, *ss;
+                        sf = feed->streams[i];
+                        ss = s->streams[i];
+
+                        if (sf->index != ss->index ||
+                            sf->id != ss->id) {
+                            printf("Index & Id do not match for stream %d\n", i);
+                            matches = 0;
+                        } else {
+                            AVCodecContext *ccf, *ccs;
+
+                            ccf = &sf->codec;
+                            ccs = &ss->codec;
+#define CHECK_CODEC(x)  (ccf->x != ccs->x)
+
+                            if (CHECK_CODEC(codec) || CHECK_CODEC(codec_type)) {
+                                printf("Codecs do not match for stream %d\n", i);
+                                matches = 0;
+                            } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
+                                printf("Codec bitrates do not match for stream %d\n", i);
+                                matches = 0;
+                            } else if (ccf->codec_type == CODEC_TYPE_VIDEO) {
+                                if (CHECK_CODEC(frame_rate) ||
+                                    CHECK_CODEC(frame_rate_base) ||
+                                    CHECK_CODEC(width) ||
+                                    CHECK_CODEC(height)) {
+                                    printf("Codec width, height and framerate do not match for stream %d\n", i);
+                                    matches = 0;
+                                }
+                            } else if (ccf->codec_type == CODEC_TYPE_AUDIO) {
+                                if (CHECK_CODEC(sample_rate) ||
+                                    CHECK_CODEC(channels) ||
+                                    CHECK_CODEC(frame_size)) {
+                                    printf("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
+                                    matches = 0;
+                                }
+                            } else {
+                                printf("Unknown codec type\n");
+                                matches = 0;
+                            }
+                        }
+                        if (!matches) {
+                            break;
+                        }
+                    }
+                } else {
+                    printf("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
+                        feed->feed_filename, s->nb_streams, feed->nb_streams);
+                }
+
+                av_close_input_file(s);
+            } else {
+                printf("Deleting feed file '%s' as it appears to be corrupt\n",
+                        feed->feed_filename);
+            }
+            if (!matches) {
+                if (feed->readonly) {
+                    printf("Unable to delete feed file '%s' as it is marked readonly\n",
+                        feed->feed_filename);
+                    exit(1);
+                }
+                unlink(feed->feed_filename);
+            }
+        }
         if (!url_exist(feed->feed_filename)) {
             AVFormatContext s1, *s = &s1;
 
+            if (feed->readonly) {
+                printf("Unable to create feed file '%s' as it is marked readonly\n",
+                    feed->feed_filename);
+                exit(1);
+            }
+
             /* only write the header of the ffm file */
             if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
                 fprintf(stderr, "Could not open output feed file '%s'\n",
@@ -3089,6 +3491,7 @@ void build_feed_streams(void)
                 st = feed->streams[i];
                 s->streams[i] = st;
             }
+            av_set_parameters(s, NULL);
             av_write_header(s);
             /* XXX: need better api */
             av_freep(&s->priv_data);
@@ -3112,6 +3515,29 @@ void build_feed_streams(void)
     }
 }
 
+/* compute the bandwidth used by each stream */
+static void compute_bandwidth(void)
+{
+    int bandwidth, i;
+    FFStream *stream;
+    
+    for(stream = first_stream; stream != NULL; stream = stream->next) {
+        bandwidth = 0;
+        for(i=0;i<stream->nb_streams;i++) {
+            AVStream *st = stream->streams[i];
+            switch(st->codec.codec_type) {
+            case CODEC_TYPE_AUDIO:
+            case CODEC_TYPE_VIDEO:
+                bandwidth += st->codec.bit_rate;
+                break;
+            default:
+                break;
+            }
+        }
+        stream->bandwidth = (bandwidth + 999) / 1000;
+    }
+}
+
 static void get_arg(char *buf, int buf_size, const char **pp)
 {
     const char *p;
@@ -3145,7 +3571,7 @@ static void get_arg(char *buf, int buf_size, const char **pp)
 }
 
 /* add a codec and set the default parameters */
-void add_codec(FFStream *stream, AVCodecContext *av)
+static void add_codec(FFStream *stream, AVCodecContext *av)
 {
     AVStream *st;
 
@@ -3162,8 +3588,10 @@ void add_codec(FFStream *stream, AVCodecContext *av)
     case CODEC_TYPE_VIDEO:
         if (av->bit_rate == 0)
             av->bit_rate = 64000;
-        if (av->frame_rate == 0)
-            av->frame_rate = 5 * FRAME_RATE_BASE;
+        if (av->frame_rate == 0){
+            av->frame_rate = 5;
+            av->frame_rate_base = 1;
+        }
         if (av->width == 0 || av->height == 0) {
             av->width = 160;
             av->height = 128;
@@ -3180,6 +3608,19 @@ void add_codec(FFStream *stream, AVCodecContext *av)
         av->qcompress = 0.5;
         av->qblur = 0.5;
 
+        if (!av->rc_eq)
+            av->rc_eq = "tex^qComp";
+        if (!av->i_quant_factor)
+            av->i_quant_factor = -0.8;
+        if (!av->b_quant_factor)
+            av->b_quant_factor = 1.25;
+        if (!av->b_quant_offset)
+            av->b_quant_offset = 1.25;
+        if (!av->rc_min_rate)
+            av->rc_min_rate = av->bit_rate / 2;
+        if (!av->rc_max_rate)
+            av->rc_max_rate = av->bit_rate * 2;
+
         break;
     default:
         av_abort();
@@ -3192,7 +3633,7 @@ void add_codec(FFStream *stream, AVCodecContext *av)
     memcpy(&st->codec, av, sizeof(AVCodecContext));
 }
 
-int opt_audio_codec(const char *arg)
+static int opt_audio_codec(const char *arg)
 {
     AVCodec *p;
 
@@ -3209,7 +3650,7 @@ int opt_audio_codec(const char *arg)
     return p->id;
 }
 
-int opt_video_codec(const char *arg)
+static int opt_video_codec(const char *arg)
 {
     AVCodec *p;
 
@@ -3228,6 +3669,7 @@ int opt_video_codec(const char *arg)
 
 /* simplistic plugin support */
 
+#ifdef CONFIG_HAVE_DLOPEN
 void load_module(const char *filename)
 {
     void *dll;
@@ -3249,8 +3691,9 @@ void load_module(const char *filename)
 
     init_func();
 }
+#endif
 
-int parse_ffconfig(const char *filename)
+static int parse_ffconfig(const char *filename)
 {
     FILE *f;
     char line[1024];
@@ -3332,7 +3775,7 @@ int parse_ffconfig(const char *filename)
                         filename, line_num, arg);
                 errors++;
             } else {
-                nb_max_bandwidth = val;
+                max_bandwidth = val;
             }
         } else if (!strcasecmp(cmd, "CustomLog")) {
             get_arg(logfilename, sizeof(logfilename), &p);
@@ -3380,7 +3823,7 @@ int parse_ffconfig(const char *filename)
                     if (!argbuf[0])
                         break;
 
-                    feed->child_argv[i] = av_malloc(strlen(argbuf + 1));
+                    feed->child_argv[i] = av_malloc(strlen(argbuf) + 1);
                     strcpy(feed->child_argv[i], argbuf);
                 }
 
@@ -3389,6 +3832,13 @@ int parse_ffconfig(const char *filename)
                 snprintf(feed->child_argv[i], 256, "http://127.0.0.1:%d/%s", 
                     ntohs(my_http_addr.sin_port), feed->filename);
             }
+        } else if (!strcasecmp(cmd, "ReadOnlyFile")) {
+            if (feed) {
+                get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
+                feed->readonly = 1;
+            } else if (stream) {
+                get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
+            }
         } else if (!strcasecmp(cmd, "File")) {
             if (feed) {
                 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
@@ -3414,13 +3864,14 @@ int parse_ffconfig(const char *filename)
                     fsize *= 1024 * 1024 * 1024;
                     break;
                 }
-                feed->feed_max_size = (INT64)fsize;
+                feed->feed_max_size = (int64_t)fsize;
             }
         } else if (!strcasecmp(cmd, "</Feed>")) {
             if (!feed) {
                 fprintf(stderr, "%s:%d: No corresponding <Feed> for </Feed>\n",
                         filename, line_num);
                 errors++;
+#if 0
             } else {
                 /* Make sure that we start out clean */
                 if (unlink(feed->feed_filename) < 0 
@@ -3429,6 +3880,7 @@ int parse_ffconfig(const char *filename)
                         filename, line_num, feed->feed_filename, strerror(errno));
                     errors++;
                 }
+#endif
             }
             feed = NULL;
         } else if (!strcasecmp(cmd, "<Stream")) {
@@ -3447,7 +3899,7 @@ int parse_ffconfig(const char *filename)
                 q = strrchr(stream->filename, '>');
                 if (*q)
                     *q = '\0';
-                stream->fmt = guess_format(NULL, stream->filename, NULL);
+                stream->fmt = guess_stream_format(NULL, stream->filename, NULL);
                 memset(&audio_enc, 0, sizeof(AVCodecContext));
                 memset(&video_enc, 0, sizeof(AVCodecContext));
                 audio_id = CODEC_ID_NONE;
@@ -3485,7 +3937,7 @@ int parse_ffconfig(const char *filename)
                 /* jpeg cannot be used here, so use single frame jpeg */
                 if (!strcmp(arg, "jpeg"))
                     strcpy(arg, "singlejpeg");
-                stream->fmt = guess_format(arg, NULL, NULL);
+                stream->fmt = guess_stream_format(arg, NULL, NULL);
                 if (!stream->fmt) {
                     fprintf(stderr, "%s:%d: Unknown Format: %s\n", 
                             filename, line_num, arg);
@@ -3523,7 +3975,7 @@ int parse_ffconfig(const char *filename)
         } else if (!strcasecmp(cmd, "Preroll")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream) {
-                stream->prebuffer = atoi(arg) * 1000;
+                stream->prebuffer = atof(arg) * 1000;
             }
         } else if (!strcasecmp(cmd, "StartSendOnKey")) {
             if (stream) {
@@ -3548,7 +4000,7 @@ int parse_ffconfig(const char *filename)
         } else if (!strcasecmp(cmd, "MaxTime")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream) {
-                stream->max_time = atoi(arg) * 1000;
+                stream->max_time = atof(arg) * 1000;
             }
         } else if (!strcasecmp(cmd, "AudioBitRate")) {
             get_arg(arg, sizeof(arg), &p);
@@ -3565,6 +4017,31 @@ int parse_ffconfig(const char *filename)
             if (stream) {
                 audio_enc.sample_rate = atoi(arg);
             }
+       } else if (!strcasecmp(cmd, "AudioQuality")) {
+           get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+//                audio_enc.quality = atof(arg) * 1000;
+            }
+        } else if (!strcasecmp(cmd, "VideoBitRateRange")) {
+            if (stream) {
+                int minrate, maxrate;
+
+                get_arg(arg, sizeof(arg), &p);
+
+                if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {
+                    video_enc.rc_min_rate = minrate * 1000;
+                    video_enc.rc_max_rate = maxrate * 1000;
+                } else {
+                    fprintf(stderr, "%s:%d: Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n", 
+                            filename, line_num, arg);
+                    errors++;
+                }
+            }
+        } else if (!strcasecmp(cmd, "VideoBitRateTolerance")) {
+            if (stream) {
+                get_arg(arg, sizeof(arg), &p);
+                video_enc.bit_rate_tolerance = atoi(arg) * 1000;
+            }
         } else if (!strcasecmp(cmd, "VideoBitRate")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream) {
@@ -3584,7 +4061,8 @@ int parse_ffconfig(const char *filename)
         } else if (!strcasecmp(cmd, "VideoFrameRate")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream) {
-                video_enc.frame_rate = (int)(strtod(arg, NULL) * FRAME_RATE_BASE);
+                video_enc.frame_rate_base= DEFAULT_FRAME_RATE_BASE;
+                video_enc.frame_rate = (int)(strtod(arg, NULL) * video_enc.frame_rate_base);
             }
         } else if (!strcasecmp(cmd, "VideoGopSize")) {
             get_arg(arg, sizeof(arg), &p);
@@ -3599,7 +4077,13 @@ int parse_ffconfig(const char *filename)
             if (stream) {
                 video_enc.flags |= CODEC_FLAG_HQ;
             }
+        } else if (!strcasecmp(cmd, "Video4MotionVector")) {
+            if (stream) {
+                video_enc.flags |= CODEC_FLAG_HQ;
+                video_enc.flags |= CODEC_FLAG_4MV;
+            }
         } else if (!strcasecmp(cmd, "VideoQDiff")) {
+            get_arg(arg, sizeof(arg), &p);
             if (stream) {
                 video_enc.max_qdiff = atoi(arg);
                 if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) {
@@ -3609,6 +4093,7 @@ int parse_ffconfig(const char *filename)
                 }
             }
         } else if (!strcasecmp(cmd, "VideoQMax")) {
+            get_arg(arg, sizeof(arg), &p);
             if (stream) {
                 video_enc.qmax = atoi(arg);
                 if (video_enc.qmax < 1 || video_enc.qmax > 31) {
@@ -3618,6 +4103,7 @@ int parse_ffconfig(const char *filename)
                 }
             }
         } else if (!strcasecmp(cmd, "VideoQMin")) {
+            get_arg(arg, sizeof(arg), &p);
             if (stream) {
                 video_enc.qmin = atoi(arg);
                 if (video_enc.qmin < 1 || video_enc.qmin > 31) {
@@ -3626,10 +4112,96 @@ int parse_ffconfig(const char *filename)
                     errors++;
                 }
             }
+        } else if (!strcasecmp(cmd, "LumaElim")) {
+            get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+                video_enc.luma_elim_threshold = atoi(arg);
+            }
+        } else if (!strcasecmp(cmd, "ChromaElim")) {
+            get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+                video_enc.chroma_elim_threshold = atoi(arg);
+            }
+        } else if (!strcasecmp(cmd, "LumiMask")) {
+            get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+                video_enc.lumi_masking = atof(arg);
+            }
+        } else if (!strcasecmp(cmd, "DarkMask")) {
+            get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+                video_enc.dark_masking = atof(arg);
+            }
         } else if (!strcasecmp(cmd, "NoVideo")) {
             video_id = CODEC_ID_NONE;
         } else if (!strcasecmp(cmd, "NoAudio")) {
             audio_id = CODEC_ID_NONE;
+        } else if (!strcasecmp(cmd, "ACL")) {
+            IPAddressACL acl;
+            struct hostent *he;
+
+            get_arg(arg, sizeof(arg), &p);
+            if (strcasecmp(arg, "allow") == 0) {
+                acl.action = IP_ALLOW;
+            } else if (strcasecmp(arg, "deny") == 0) {
+                acl.action = IP_DENY;
+            } else {
+                fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
+                        filename, line_num, arg);
+                errors++;
+            }
+
+            get_arg(arg, sizeof(arg), &p);
+
+            he = gethostbyname(arg);
+            if (!he) {
+                fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
+                        filename, line_num, arg);
+                errors++;
+            } else {
+                /* Only take the first */
+                acl.first.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr);
+                acl.last = acl.first;
+            }
+
+            get_arg(arg, sizeof(arg), &p);
+
+            if (arg[0]) {
+                he = gethostbyname(arg);
+                if (!he) {
+                    fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
+                            filename, line_num, arg);
+                    errors++;
+                } else {
+                    /* Only take the first */
+                    acl.last.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr);
+                }
+            }
+
+            if (!errors) {
+                IPAddressACL *nacl = (IPAddressACL *) av_mallocz(sizeof(*nacl));
+                IPAddressACL **naclp = 0;
+
+                *nacl = acl;
+                nacl->next = 0;
+
+                if (stream) {
+                    naclp = &stream->acl;
+                } else if (feed) {
+                    naclp = &feed->acl;
+                } else {
+                    fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n",
+                            filename, line_num);
+                    errors++;
+                }
+
+                if (naclp) {
+                    while (*naclp)
+                        naclp = &(*naclp)->next;
+
+                    *naclp = nacl;
+                }
+            }
         } else if (!strcasecmp(cmd, "RTSPOption")) {
             get_arg(arg, sizeof(arg), &p);
             if (stream) {
@@ -3640,6 +4212,31 @@ int parse_ffconfig(const char *filename)
                     strcpy(stream->rtsp_option, arg);
                 }
             }
+        } else if (!strcasecmp(cmd, "MulticastAddress")) {
+            get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+                if (!inet_aton(arg, &stream->multicast_ip)) {
+                    fprintf(stderr, "%s:%d: Invalid IP address: %s\n", 
+                            filename, line_num, arg);
+                    errors++;
+                }
+                stream->is_multicast = 1;
+                stream->loop = 1; /* default is looping */
+            }
+        } else if (!strcasecmp(cmd, "MulticastPort")) {
+            get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+                stream->multicast_port = atoi(arg);
+            }
+        } else if (!strcasecmp(cmd, "MulticastTTL")) {
+            get_arg(arg, sizeof(arg), &p);
+            if (stream) {
+                stream->multicast_ttl = atoi(arg);
+            }
+        } else if (!strcasecmp(cmd, "NoLoop")) {
+            if (stream) {
+                stream->loop = 0;
+            }
         } else if (!strcasecmp(cmd, "</Stream>")) {
             if (!stream) {
                 fprintf(stderr, "%s:%d: No corresponding <Stream> for </Stream>\n",
@@ -3695,7 +4292,13 @@ int parse_ffconfig(const char *filename)
             redirect = NULL;
         } else if (!strcasecmp(cmd, "LoadModule")) {
             get_arg(arg, sizeof(arg), &p);
+#ifdef CONFIG_HAVE_DLOPEN
             load_module(arg);
+#else
+            fprintf(stderr, "%s:%d: Module support not compiled into this version: '%s'\n", 
+                    filename, line_num, arg);
+            errors++;
+#endif
         } else {
             fprintf(stderr, "%s:%d: Incorrect keyword: '%s'\n", 
                     filename, line_num, cmd);
@@ -3713,14 +4316,14 @@ int parse_ffconfig(const char *filename)
 
 #if 0
 static void write_packet(FFCodec *ffenc,
-                         UINT8 *buf, int size)
+                         uint8_t *buf, int size)
 {
     PacketHeader hdr;
     AVCodecContext *enc = &ffenc->enc;
-    UINT8 *wptr;
+    uint8_t *wptr;
     mk_header(&hdr, enc, size);
     wptr = http_fifo.wptr;
-    fifo_write(&http_fifo, (UINT8 *)&hdr, sizeof(hdr), &wptr);
+    fifo_write(&http_fifo, (uint8_t *)&hdr, sizeof(hdr), &wptr);
     fifo_write(&http_fifo, buf, size, &wptr);
     /* atomic modification of wptr */
     http_fifo.wptr = wptr;
@@ -3729,7 +4332,7 @@ static void write_packet(FFCodec *ffenc,
 }
 #endif
 
-void help(void)
+static void help(void)
 {
     printf("ffserver version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
            "usage: ffserver [-L] [-h] [-f configfile]\n"
@@ -3741,7 +4344,7 @@ void help(void)
            );
 }
 
-void licence(void)
+static void licence(void)
 {
     printf(
     "ffserver version " FFMPEG_VERSION "\n"
@@ -3799,6 +4402,7 @@ int main(int argc, char **argv)
     config_filename = "/etc/ffserver.conf";
 
     my_program_name = argv[0];
+    my_program_dir = getcwd(0, 0);
     ffserver_daemon = 1;
     
     for(;;) {
@@ -3830,6 +4434,8 @@ int main(int argc, char **argv)
 
     putenv("http_proxy");               /* Kill the http_proxy */
 
+    srandom(gettime_ms() + (getpid() << 16));
+
     /* address on which the server will handle HTTP connections */
     my_http_addr.sin_family = AF_INET;
     my_http_addr.sin_port = htons (8080);
@@ -3841,7 +4447,7 @@ int main(int argc, char **argv)
     my_rtsp_addr.sin_addr.s_addr = htonl (INADDR_ANY);
     
     nb_max_connections = 5;
-    nb_max_bandwidth = 1000;
+    max_bandwidth = 1000;
     first_stream = NULL;
     logfilename[0] = '\0';
 
@@ -3859,6 +4465,8 @@ int main(int argc, char **argv)
 
     build_feed_streams();
 
+    compute_bandwidth();
+
     /* put the process in background and detach it from its TTY */
     if (ffserver_daemon) {
         int pid;
@@ -3875,10 +4483,12 @@ int main(int argc, char **argv)
             setsid();
             chdir("/");
             close(0);
-            close(1);
-            close(2);
             open("/dev/null", O_RDWR);
-            dup(0);
+            if (strcmp(logfilename, "-") != 0) {
+                close(1);
+                dup(0);
+            }
+            close(2);
             dup(0);
         }
     }