]> git.sesse.net Git - ffmpeg/blob - ffserver.c
Merge commit '80fbb7becae530167373fe5178966b7d7604306e'
[ffmpeg] / ffserver.c
1 /*
2  * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * multiple format streaming server based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27 #if !HAVE_CLOSESOCKET
28 #define closesocket close
29 #endif
30 #include <string.h>
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include "libavformat/avformat.h"
34 /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
35 #include "libavformat/rtpproto.h"
36 #include "libavformat/rtsp.h"
37 #include "libavformat/avio_internal.h"
38 #include "libavformat/internal.h"
39
40 #include "libavutil/avassert.h"
41 #include "libavutil/avstring.h"
42 #include "libavutil/lfg.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/mathematics.h"
46 #include "libavutil/random_seed.h"
47 #include "libavutil/rational.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/time.h"
51
52 #include <stdarg.h>
53 #if HAVE_UNISTD_H
54 #include <unistd.h>
55 #endif
56 #include <fcntl.h>
57 #include <sys/ioctl.h>
58 #if HAVE_POLL_H
59 #include <poll.h>
60 #endif
61 #include <errno.h>
62 #include <time.h>
63 #include <sys/wait.h>
64 #include <signal.h>
65
66 #include "cmdutils.h"
67 #include "ffserver_config.h"
68
69 #define PATH_LENGTH 1024
70
71 const char program_name[] = "ffserver";
72 const int program_birth_year = 2000;
73
74 static const OptionDef options[];
75
76 enum HTTPState {
77     HTTPSTATE_WAIT_REQUEST,
78     HTTPSTATE_SEND_HEADER,
79     HTTPSTATE_SEND_DATA_HEADER,
80     HTTPSTATE_SEND_DATA,          /* sending TCP or UDP data */
81     HTTPSTATE_SEND_DATA_TRAILER,
82     HTTPSTATE_RECEIVE_DATA,
83     HTTPSTATE_WAIT_FEED,          /* wait for data from the feed */
84     HTTPSTATE_READY,
85
86     RTSPSTATE_WAIT_REQUEST,
87     RTSPSTATE_SEND_REPLY,
88     RTSPSTATE_SEND_PACKET,
89 };
90
91 static const char * const http_state[] = {
92     "HTTP_WAIT_REQUEST",
93     "HTTP_SEND_HEADER",
94
95     "SEND_DATA_HEADER",
96     "SEND_DATA",
97     "SEND_DATA_TRAILER",
98     "RECEIVE_DATA",
99     "WAIT_FEED",
100     "READY",
101
102     "RTSP_WAIT_REQUEST",
103     "RTSP_SEND_REPLY",
104     "RTSP_SEND_PACKET",
105 };
106
107 #define IOBUFFER_INIT_SIZE 8192
108
109 /* timeouts are in ms */
110 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
111 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
112
113 #define SYNC_TIMEOUT (10 * 1000)
114
115 typedef struct RTSPActionServerSetup {
116     uint32_t ipaddr;
117     char transport_option[512];
118 } RTSPActionServerSetup;
119
120 typedef struct {
121     int64_t count1, count2;
122     int64_t time1, time2;
123 } DataRateData;
124
125 /* context associated with one connection */
126 typedef struct HTTPContext {
127     enum HTTPState state;
128     int fd; /* socket file descriptor */
129     struct sockaddr_in from_addr; /* origin */
130     struct pollfd *poll_entry; /* used when polling */
131     int64_t timeout;
132     uint8_t *buffer_ptr, *buffer_end;
133     int http_error;
134     int post;
135     int chunked_encoding;
136     int chunk_size;               /* 0 if it needs to be read */
137     struct HTTPContext *next;
138     int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
139     int64_t data_count;
140     /* feed input */
141     int feed_fd;
142     /* input format handling */
143     AVFormatContext *fmt_in;
144     int64_t start_time;            /* In milliseconds - this wraps fairly often */
145     int64_t first_pts;            /* initial pts value */
146     int64_t cur_pts;             /* current pts value from the stream in us */
147     int64_t cur_frame_duration;  /* duration of the current frame in us */
148     int cur_frame_bytes;       /* output frame size, needed to compute
149                                   the time at which we send each
150                                   packet */
151     int pts_stream_index;        /* stream we choose as clock reference */
152     int64_t cur_clock;           /* current clock reference value in us */
153     /* output format handling */
154     struct FFServerStream *stream;
155     /* -1 is invalid stream */
156     int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
157     int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
158     int switch_pending;
159     AVFormatContext *pfmt_ctx; /* instance of FFServerStream for one user */
160     int last_packet_sent; /* true if last data packet was sent */
161     int suppress_log;
162     DataRateData datarate;
163     int wmp_client_id;
164     char protocol[16];
165     char method[16];
166     char url[128];
167     int buffer_size;
168     uint8_t *buffer;
169     int is_packetized; /* if true, the stream is packetized */
170     int packet_stream_index; /* current stream for output in state machine */
171
172     /* RTSP state specific */
173     uint8_t *pb_buffer; /* XXX: use that in all the code */
174     AVIOContext *pb;
175     int seq; /* RTSP sequence number */
176
177     /* RTP state specific */
178     enum RTSPLowerTransport rtp_protocol;
179     char session_id[32]; /* session id */
180     AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
181
182     /* RTP/UDP specific */
183     URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
184
185     /* RTP/TCP specific */
186     struct HTTPContext *rtsp_c;
187     uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
188 } HTTPContext;
189
190 typedef struct FeedData {
191     long long data_count;
192     float avg_frame_size;   /* frame size averaged over last frames with exponential mean */
193 } FeedData;
194
195 static HTTPContext *first_http_ctx;
196
197 static FFServerConfig config = {
198     .nb_max_http_connections = 2000,
199     .nb_max_connections = 5,
200     .max_bandwidth = 1000,
201     .use_defaults = 1,
202 };
203
204 static void new_connection(int server_fd, int is_rtsp);
205 static void close_connection(HTTPContext *c);
206
207 /* HTTP handling */
208 static int handle_connection(HTTPContext *c);
209 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
210 static void compute_status(HTTPContext *c);
211 static int open_input_stream(HTTPContext *c, const char *info);
212 static int http_parse_request(HTTPContext *c);
213 static int http_send_data(HTTPContext *c);
214 static int http_start_receive_data(HTTPContext *c);
215 static int http_receive_data(HTTPContext *c);
216
217 /* RTSP handling */
218 static int rtsp_parse_request(HTTPContext *c);
219 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
220 static void rtsp_cmd_options(HTTPContext *c, const char *url);
221 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
222                            RTSPMessageHeader *h);
223 static void rtsp_cmd_play(HTTPContext *c, const char *url,
224                           RTSPMessageHeader *h);
225 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
226                                RTSPMessageHeader *h, int pause_only);
227
228 /* SDP handling */
229 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
230                                    struct in_addr my_ip);
231
232 /* RTP handling */
233 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
234                                        FFServerStream *stream,
235                                        const char *session_id,
236                                        enum RTSPLowerTransport rtp_protocol);
237 static int rtp_new_av_stream(HTTPContext *c,
238                              int stream_index, struct sockaddr_in *dest_addr,
239                              HTTPContext *rtsp_c);
240 /* utils */
241 static size_t htmlencode (const char *src, char **dest);
242 static inline void cp_html_entity (char *buffer, const char *entity);
243 static inline int check_codec_match(AVStream *ccf, AVStream *ccs, int stream);
244
245 static const char *my_program_name;
246
247 static int no_launch;
248 static int need_to_start_children;
249
250 /* maximum number of simultaneous HTTP connections */
251 static unsigned int nb_connections;
252
253 static uint64_t current_bandwidth;
254
255 /* Making this global saves on passing it around everywhere */
256 static int64_t cur_time;
257
258 static AVLFG random_state;
259
260 static FILE *logfile = NULL;
261
262 static inline void cp_html_entity (char *buffer, const char *entity) {
263     if (!buffer || !entity)
264         return;
265     while (*entity)
266         *buffer++ = *entity++;
267 }
268
269 /**
270  * Substitutes known conflicting chars on a text string with
271  * their corresponding HTML entities.
272  *
273  * Returns the number of bytes in the 'encoded' representation
274  * not including the terminating NUL.
275  */
276 static size_t htmlencode (const char *src, char **dest) {
277     const char *amp = "&amp;";
278     const char *lt  = "&lt;";
279     const char *gt  = "&gt;";
280     const char *start;
281     char *tmp;
282     size_t final_size = 0;
283
284     if (!src)
285         return 0;
286
287     start = src;
288
289     /* Compute needed dest size */
290     while (*src != '\0') {
291         switch(*src) {
292             case 38: /* & */
293                 final_size += 5;
294                 break;
295             case 60: /* < */
296             case 62: /* > */
297                 final_size += 4;
298                 break;
299             default:
300                 final_size++;
301         }
302         src++;
303     }
304
305     src = start;
306     *dest = av_mallocz(final_size + 1);
307     if (!*dest)
308         return 0;
309
310     /* Build dest */
311     tmp = *dest;
312     while (*src != '\0') {
313         switch(*src) {
314             case 38: /* & */
315                 cp_html_entity (tmp, amp);
316                 tmp += 5;
317                 break;
318             case 60: /* < */
319                 cp_html_entity (tmp, lt);
320                 tmp += 4;
321                 break;
322             case 62: /* > */
323                 cp_html_entity (tmp, gt);
324                 tmp += 4;
325                 break;
326             default:
327                 *tmp = *src;
328                 tmp += 1;
329         }
330         src++;
331     }
332     *tmp = '\0';
333
334     return final_size;
335 }
336
337 static int64_t ffm_read_write_index(int fd)
338 {
339     uint8_t buf[8];
340
341     if (lseek(fd, 8, SEEK_SET) < 0)
342         return AVERROR(EIO);
343     if (read(fd, buf, 8) != 8)
344         return AVERROR(EIO);
345     return AV_RB64(buf);
346 }
347
348 static int ffm_write_write_index(int fd, int64_t pos)
349 {
350     uint8_t buf[8];
351     int i;
352
353     for(i=0;i<8;i++)
354         buf[i] = (pos >> (56 - i * 8)) & 0xff;
355     if (lseek(fd, 8, SEEK_SET) < 0)
356         goto bail_eio;
357     if (write(fd, buf, 8) != 8)
358         goto bail_eio;
359
360     return 8;
361
362 bail_eio:
363     return AVERROR(EIO);
364 }
365
366 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
367                                 int64_t file_size)
368 {
369     av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
370     av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
371     av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
372 }
373
374 static char *ctime1(char *buf2, size_t buf_size)
375 {
376     time_t ti;
377     char *p;
378
379     ti = time(NULL);
380     p = ctime(&ti);
381     if (!p || !*p) {
382         *buf2 = '\0';
383         return buf2;
384     }
385     av_strlcpy(buf2, p, buf_size);
386     p = buf2 + strlen(buf2) - 1;
387     if (*p == '\n')
388         *p = '\0';
389     return buf2;
390 }
391
392 static void http_vlog(const char *fmt, va_list vargs)
393 {
394     static int print_prefix = 1;
395     char buf[32];
396
397     if (!logfile)
398         return;
399
400     if (print_prefix) {
401         ctime1(buf, sizeof(buf));
402         fprintf(logfile, "%s ", buf);
403     }
404     print_prefix = strstr(fmt, "\n") != NULL;
405     vfprintf(logfile, fmt, vargs);
406     fflush(logfile);
407 }
408
409 #ifdef __GNUC__
410 __attribute__ ((format (printf, 1, 2)))
411 #endif
412 static void http_log(const char *fmt, ...)
413 {
414     va_list vargs;
415     va_start(vargs, fmt);
416     http_vlog(fmt, vargs);
417     va_end(vargs);
418 }
419
420 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
421 {
422     static int print_prefix = 1;
423     AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
424     if (level > av_log_get_level())
425         return;
426     if (print_prefix && avc)
427         http_log("[%s @ %p]", avc->item_name(ptr), ptr);
428     print_prefix = strstr(fmt, "\n") != NULL;
429     http_vlog(fmt, vargs);
430 }
431
432 static void log_connection(HTTPContext *c)
433 {
434     if (c->suppress_log)
435         return;
436
437     http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
438              inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
439              c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
440 }
441
442 static void update_datarate(DataRateData *drd, int64_t count)
443 {
444     if (!drd->time1 && !drd->count1) {
445         drd->time1 = drd->time2 = cur_time;
446         drd->count1 = drd->count2 = count;
447     } else if (cur_time - drd->time2 > 5000) {
448         drd->time1 = drd->time2;
449         drd->count1 = drd->count2;
450         drd->time2 = cur_time;
451         drd->count2 = count;
452     }
453 }
454
455 /* In bytes per second */
456 static int compute_datarate(DataRateData *drd, int64_t count)
457 {
458     if (cur_time == drd->time1)
459         return 0;
460
461     return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
462 }
463
464
465 static void start_children(FFServerStream *feed)
466 {
467     char *pathname;
468     char *slash;
469     int i;
470     size_t cmd_length;
471
472     if (no_launch)
473         return;
474
475     cmd_length = strlen(my_program_name);
476
477    /**
478     * FIXME: WIP Safeguard. Remove after clearing all harcoded
479     * '1024' path lengths
480     */
481     if (cmd_length > PATH_LENGTH - 1) {
482         http_log("Could not start children. Command line: '%s' exceeds "
483                     "path length limit (%d)\n", my_program_name, PATH_LENGTH);
484         return;
485     }
486
487     pathname = av_strdup (my_program_name);
488     if (!pathname) {
489         http_log("Could not allocate memory for children cmd line\n");
490         return;
491     }
492    /* replace "ffserver" with "ffmpeg" in the path of current
493     * program. Ignore user provided path */
494
495     slash = strrchr(pathname, '/');
496     if (!slash)
497         slash = pathname;
498     else
499         slash++;
500     strcpy(slash, "ffmpeg");
501
502     for (; feed; feed = feed->next) {
503
504         if (!feed->child_argv || feed->pid)
505             continue;
506
507         feed->pid_start = time(0);
508
509         feed->pid = fork();
510         if (feed->pid < 0) {
511             http_log("Unable to create children: %s\n", strerror(errno));
512             av_free (pathname);
513             exit(EXIT_FAILURE);
514         }
515
516         if (feed->pid)
517             continue;
518
519         /* In child */
520
521         http_log("Launch command line: ");
522         http_log("%s ", pathname);
523
524         for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
525             http_log("%s ", feed->child_argv[i]);
526         http_log("\n");
527
528         for (i = 3; i < 256; i++)
529             close(i);
530
531         if (!config.debug) {
532             if (!freopen("/dev/null", "r", stdin))
533                 http_log("failed to redirect STDIN to /dev/null\n;");
534             if (!freopen("/dev/null", "w", stdout))
535                 http_log("failed to redirect STDOUT to /dev/null\n;");
536             if (!freopen("/dev/null", "w", stderr))
537                 http_log("failed to redirect STDERR to /dev/null\n;");
538         }
539
540         signal(SIGPIPE, SIG_DFL);
541         execvp(pathname, feed->child_argv);
542         av_free (pathname);
543         _exit(1);
544     }
545     av_free (pathname);
546 }
547
548 /* open a listening socket */
549 static int socket_open_listen(struct sockaddr_in *my_addr)
550 {
551     int server_fd, tmp;
552
553     server_fd = socket(AF_INET,SOCK_STREAM,0);
554     if (server_fd < 0) {
555         perror ("socket");
556         return -1;
557     }
558
559     tmp = 1;
560     if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
561         av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
562
563     my_addr->sin_family = AF_INET;
564     if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
565         char bindmsg[32];
566         snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
567                  ntohs(my_addr->sin_port));
568         perror (bindmsg);
569         goto fail;
570     }
571
572     if (listen (server_fd, 5) < 0) {
573         perror ("listen");
574         goto fail;
575     }
576
577     if (ff_socket_nonblock(server_fd, 1) < 0)
578         av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
579
580     return server_fd;
581
582 fail:
583     closesocket(server_fd);
584     return -1;
585 }
586
587 /* start all multicast streams */
588 static void start_multicast(void)
589 {
590     FFServerStream *stream;
591     char session_id[32];
592     HTTPContext *rtp_c;
593     struct sockaddr_in dest_addr = {0};
594     int default_port, stream_index;
595     unsigned int random0, random1;
596
597     default_port = 6000;
598     for(stream = config.first_stream; stream; stream = stream->next) {
599
600         if (!stream->is_multicast)
601             continue;
602
603         random0 = av_lfg_get(&random_state);
604         random1 = av_lfg_get(&random_state);
605
606         /* open the RTP connection */
607         snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
608
609         /* choose a port if none given */
610         if (stream->multicast_port == 0) {
611             stream->multicast_port = default_port;
612             default_port += 100;
613         }
614
615         dest_addr.sin_family = AF_INET;
616         dest_addr.sin_addr = stream->multicast_ip;
617         dest_addr.sin_port = htons(stream->multicast_port);
618
619         rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
620                                    RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
621         if (!rtp_c)
622             continue;
623
624         if (open_input_stream(rtp_c, "") < 0) {
625             http_log("Could not open input stream for stream '%s'\n",
626                      stream->filename);
627             continue;
628         }
629
630         /* open each RTP stream */
631         for(stream_index = 0; stream_index < stream->nb_streams;
632             stream_index++) {
633             dest_addr.sin_port = htons(stream->multicast_port +
634                                        2 * stream_index);
635             if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
636                 continue;
637
638             http_log("Could not open output stream '%s/streamid=%d'\n",
639                      stream->filename, stream_index);
640             exit(1);
641         }
642
643         rtp_c->state = HTTPSTATE_SEND_DATA;
644     }
645 }
646
647 /* main loop of the HTTP server */
648 static int http_server(void)
649 {
650     int server_fd = 0, rtsp_server_fd = 0;
651     int ret, delay;
652     struct pollfd *poll_table, *poll_entry;
653     HTTPContext *c, *c_next;
654
655     poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
656                                   sizeof(*poll_table));
657     if(!poll_table) {
658         http_log("Impossible to allocate a poll table handling %d "
659                  "connections.\n", config.nb_max_http_connections);
660         return -1;
661     }
662
663     if (config.http_addr.sin_port) {
664         server_fd = socket_open_listen(&config.http_addr);
665         if (server_fd < 0)
666             goto quit;
667     }
668
669     if (config.rtsp_addr.sin_port) {
670         rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
671         if (rtsp_server_fd < 0) {
672             closesocket(server_fd);
673             goto quit;
674         }
675     }
676
677     if (!rtsp_server_fd && !server_fd) {
678         http_log("HTTP and RTSP disabled.\n");
679         goto quit;
680     }
681
682     http_log("FFserver started.\n");
683
684     start_children(config.first_feed);
685
686     start_multicast();
687
688     for(;;) {
689         poll_entry = poll_table;
690         if (server_fd) {
691             poll_entry->fd = server_fd;
692             poll_entry->events = POLLIN;
693             poll_entry++;
694         }
695         if (rtsp_server_fd) {
696             poll_entry->fd = rtsp_server_fd;
697             poll_entry->events = POLLIN;
698             poll_entry++;
699         }
700
701         /* wait for events on each HTTP handle */
702         c = first_http_ctx;
703         delay = 1000;
704         while (c) {
705             int fd;
706             fd = c->fd;
707             switch(c->state) {
708             case HTTPSTATE_SEND_HEADER:
709             case RTSPSTATE_SEND_REPLY:
710             case RTSPSTATE_SEND_PACKET:
711                 c->poll_entry = poll_entry;
712                 poll_entry->fd = fd;
713                 poll_entry->events = POLLOUT;
714                 poll_entry++;
715                 break;
716             case HTTPSTATE_SEND_DATA_HEADER:
717             case HTTPSTATE_SEND_DATA:
718             case HTTPSTATE_SEND_DATA_TRAILER:
719                 if (!c->is_packetized) {
720                     /* for TCP, we output as much as we can
721                      * (may need to put a limit) */
722                     c->poll_entry = poll_entry;
723                     poll_entry->fd = fd;
724                     poll_entry->events = POLLOUT;
725                     poll_entry++;
726                 } else {
727                     /* when ffserver is doing the timing, we work by
728                      * looking at which packet needs to be sent every
729                      * 10 ms (one tick wait XXX: 10 ms assumed) */
730                     if (delay > 10)
731                         delay = 10;
732                 }
733                 break;
734             case HTTPSTATE_WAIT_REQUEST:
735             case HTTPSTATE_RECEIVE_DATA:
736             case HTTPSTATE_WAIT_FEED:
737             case RTSPSTATE_WAIT_REQUEST:
738                 /* need to catch errors */
739                 c->poll_entry = poll_entry;
740                 poll_entry->fd = fd;
741                 poll_entry->events = POLLIN;/* Maybe this will work */
742                 poll_entry++;
743                 break;
744             default:
745                 c->poll_entry = NULL;
746                 break;
747             }
748             c = c->next;
749         }
750
751         /* wait for an event on one connection. We poll at least every
752          * second to handle timeouts */
753         do {
754             ret = poll(poll_table, poll_entry - poll_table, delay);
755             if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
756                 ff_neterrno() != AVERROR(EINTR)) {
757                 goto quit;
758             }
759         } while (ret < 0);
760
761         cur_time = av_gettime() / 1000;
762
763         if (need_to_start_children) {
764             need_to_start_children = 0;
765             start_children(config.first_feed);
766         }
767
768         /* now handle the events */
769         for(c = first_http_ctx; c; c = c_next) {
770             c_next = c->next;
771             if (handle_connection(c) < 0) {
772                 log_connection(c);
773                 /* close and free the connection */
774                 close_connection(c);
775             }
776         }
777
778         poll_entry = poll_table;
779         if (server_fd) {
780             /* new HTTP connection request ? */
781             if (poll_entry->revents & POLLIN)
782                 new_connection(server_fd, 0);
783             poll_entry++;
784         }
785         if (rtsp_server_fd) {
786             /* new RTSP connection request ? */
787             if (poll_entry->revents & POLLIN)
788                 new_connection(rtsp_server_fd, 1);
789         }
790     }
791
792 quit:
793     av_free(poll_table);
794     return -1;
795 }
796
797 /* start waiting for a new HTTP/RTSP request */
798 static void start_wait_request(HTTPContext *c, int is_rtsp)
799 {
800     c->buffer_ptr = c->buffer;
801     c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
802
803     c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
804     c->timeout = cur_time +
805                  (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
806 }
807
808 static void http_send_too_busy_reply(int fd)
809 {
810     char buffer[400];
811     int len = snprintf(buffer, sizeof(buffer),
812                        "HTTP/1.0 503 Server too busy\r\n"
813                        "Content-type: text/html\r\n"
814                        "\r\n"
815                        "<!DOCTYPE html>\n"
816                        "<html><head><title>Too busy</title></head><body>\r\n"
817                        "<p>The server is too busy to serve your request at "
818                        "this time.</p>\r\n"
819                        "<p>The number of current connections is %u, and this "
820                        "exceeds the limit of %u.</p>\r\n"
821                        "</body></html>\r\n",
822                        nb_connections, config.nb_max_connections);
823     av_assert0(len < sizeof(buffer));
824     if (send(fd, buffer, len, 0) < len)
825         av_log(NULL, AV_LOG_WARNING,
826                "Could not send too-busy reply, send() failed\n");
827 }
828
829
830 static void new_connection(int server_fd, int is_rtsp)
831 {
832     struct sockaddr_in from_addr;
833     socklen_t len;
834     int fd;
835     HTTPContext *c = NULL;
836
837     len = sizeof(from_addr);
838     fd = accept(server_fd, (struct sockaddr *)&from_addr,
839                 &len);
840     if (fd < 0) {
841         http_log("error during accept %s\n", strerror(errno));
842         return;
843     }
844     if (ff_socket_nonblock(fd, 1) < 0)
845         av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
846
847     if (nb_connections >= config.nb_max_connections) {
848         http_send_too_busy_reply(fd);
849         goto fail;
850     }
851
852     /* add a new connection */
853     c = av_mallocz(sizeof(HTTPContext));
854     if (!c)
855         goto fail;
856
857     c->fd = fd;
858     c->poll_entry = NULL;
859     c->from_addr = from_addr;
860     c->buffer_size = IOBUFFER_INIT_SIZE;
861     c->buffer = av_malloc(c->buffer_size);
862     if (!c->buffer)
863         goto fail;
864
865     c->next = first_http_ctx;
866     first_http_ctx = c;
867     nb_connections++;
868
869     start_wait_request(c, is_rtsp);
870
871     return;
872
873  fail:
874     if (c) {
875         av_freep(&c->buffer);
876         av_free(c);
877     }
878     closesocket(fd);
879 }
880
881 static void close_connection(HTTPContext *c)
882 {
883     HTTPContext **cp, *c1;
884     int i, nb_streams;
885     AVFormatContext *ctx;
886     AVStream *st;
887
888     /* remove connection from list */
889     cp = &first_http_ctx;
890     while (*cp) {
891         c1 = *cp;
892         if (c1 == c)
893             *cp = c->next;
894         else
895             cp = &c1->next;
896     }
897
898     /* remove references, if any (XXX: do it faster) */
899     for(c1 = first_http_ctx; c1; c1 = c1->next) {
900         if (c1->rtsp_c == c)
901             c1->rtsp_c = NULL;
902     }
903
904     /* remove connection associated resources */
905     if (c->fd >= 0)
906         closesocket(c->fd);
907     if (c->fmt_in) {
908         /* close each frame parser */
909         for(i=0;i<c->fmt_in->nb_streams;i++) {
910             st = c->fmt_in->streams[i];
911             if (st->codec->codec)
912                 avcodec_close(st->codec);
913         }
914         avformat_close_input(&c->fmt_in);
915     }
916
917     /* free RTP output streams if any */
918     nb_streams = 0;
919     if (c->stream)
920         nb_streams = c->stream->nb_streams;
921
922     for(i=0;i<nb_streams;i++) {
923         ctx = c->rtp_ctx[i];
924         if (ctx) {
925             av_write_trailer(ctx);
926             av_dict_free(&ctx->metadata);
927             av_freep(&ctx->streams[0]);
928             av_freep(&ctx);
929         }
930         ffurl_close(c->rtp_handles[i]);
931     }
932
933     ctx = c->pfmt_ctx;
934
935     if (ctx) {
936         if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
937             /* prepare header */
938             if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
939                 av_write_trailer(ctx);
940                 av_freep(&c->pb_buffer);
941                 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
942             }
943         }
944         for(i=0; i<ctx->nb_streams; i++)
945             av_freep(&ctx->streams[i]);
946         av_freep(&ctx->streams);
947         av_freep(&ctx->priv_data);
948         }
949
950     if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
951         current_bandwidth -= c->stream->bandwidth;
952
953     /* signal that there is no feed if we are the feeder socket */
954     if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
955         c->stream->feed_opened = 0;
956         close(c->feed_fd);
957     }
958
959     av_freep(&c->pb_buffer);
960     av_freep(&c->packet_buffer);
961     av_freep(&c->buffer);
962     av_free(c);
963     nb_connections--;
964 }
965
966 static int handle_connection(HTTPContext *c)
967 {
968     int len, ret;
969     uint8_t *ptr;
970
971     switch(c->state) {
972     case HTTPSTATE_WAIT_REQUEST:
973     case RTSPSTATE_WAIT_REQUEST:
974         /* timeout ? */
975         if ((c->timeout - cur_time) < 0)
976             return -1;
977         if (c->poll_entry->revents & (POLLERR | POLLHUP))
978             return -1;
979
980         /* no need to read if no events */
981         if (!(c->poll_entry->revents & POLLIN))
982             return 0;
983         /* read the data */
984     read_loop:
985         if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
986             return -1;
987
988         if (len < 0) {
989             if (ff_neterrno() != AVERROR(EAGAIN) &&
990                 ff_neterrno() != AVERROR(EINTR))
991                 return -1;
992             break;
993         }
994         /* search for end of request. */
995         c->buffer_ptr += len;
996         ptr = c->buffer_ptr;
997         if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
998             (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
999             /* request found : parse it and reply */
1000             if (c->state == HTTPSTATE_WAIT_REQUEST)
1001                 ret = http_parse_request(c);
1002             else
1003                 ret = rtsp_parse_request(c);
1004
1005             if (ret < 0)
1006                 return -1;
1007         } else if (ptr >= c->buffer_end) {
1008             /* request too long: cannot do anything */
1009             return -1;
1010         } else goto read_loop;
1011
1012         break;
1013
1014     case HTTPSTATE_SEND_HEADER:
1015         if (c->poll_entry->revents & (POLLERR | POLLHUP))
1016             return -1;
1017
1018         /* no need to write if no events */
1019         if (!(c->poll_entry->revents & POLLOUT))
1020             return 0;
1021         len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1022         if (len < 0) {
1023             if (ff_neterrno() != AVERROR(EAGAIN) &&
1024                 ff_neterrno() != AVERROR(EINTR)) {
1025                 goto close_connection;
1026             }
1027             break;
1028         }
1029         c->buffer_ptr += len;
1030         if (c->stream)
1031             c->stream->bytes_served += len;
1032         c->data_count += len;
1033         if (c->buffer_ptr >= c->buffer_end) {
1034             av_freep(&c->pb_buffer);
1035             /* if error, exit */
1036             if (c->http_error)
1037                 return -1;
1038             /* all the buffer was sent : synchronize to the incoming
1039              * stream */
1040             c->state = HTTPSTATE_SEND_DATA_HEADER;
1041             c->buffer_ptr = c->buffer_end = c->buffer;
1042         }
1043         break;
1044
1045     case HTTPSTATE_SEND_DATA:
1046     case HTTPSTATE_SEND_DATA_HEADER:
1047     case HTTPSTATE_SEND_DATA_TRAILER:
1048         /* for packetized output, we consider we can always write (the
1049          * input streams set the speed). It may be better to verify
1050          * that we do not rely too much on the kernel queues */
1051         if (!c->is_packetized) {
1052             if (c->poll_entry->revents & (POLLERR | POLLHUP))
1053                 return -1;
1054
1055             /* no need to read if no events */
1056             if (!(c->poll_entry->revents & POLLOUT))
1057                 return 0;
1058         }
1059         if (http_send_data(c) < 0)
1060             return -1;
1061         /* close connection if trailer sent */
1062         if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
1063             return -1;
1064         /* Check if it is a single jpeg frame 123 */
1065         if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
1066             close_connection(c);
1067         }
1068         break;
1069     case HTTPSTATE_RECEIVE_DATA:
1070         /* no need to read if no events */
1071         if (c->poll_entry->revents & (POLLERR | POLLHUP))
1072             return -1;
1073         if (!(c->poll_entry->revents & POLLIN))
1074             return 0;
1075         if (http_receive_data(c) < 0)
1076             return -1;
1077         break;
1078     case HTTPSTATE_WAIT_FEED:
1079         /* no need to read if no events */
1080         if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1081             return -1;
1082
1083         /* nothing to do, we'll be waken up by incoming feed packets */
1084         break;
1085
1086     case RTSPSTATE_SEND_REPLY:
1087         if (c->poll_entry->revents & (POLLERR | POLLHUP))
1088             goto close_connection;
1089         /* no need to write if no events */
1090         if (!(c->poll_entry->revents & POLLOUT))
1091             return 0;
1092         len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1093         if (len < 0) {
1094             if (ff_neterrno() != AVERROR(EAGAIN) &&
1095                 ff_neterrno() != AVERROR(EINTR)) {
1096                 goto close_connection;
1097             }
1098             break;
1099         }
1100         c->buffer_ptr += len;
1101         c->data_count += len;
1102         if (c->buffer_ptr >= c->buffer_end) {
1103             /* all the buffer was sent : wait for a new request */
1104             av_freep(&c->pb_buffer);
1105             start_wait_request(c, 1);
1106         }
1107         break;
1108     case RTSPSTATE_SEND_PACKET:
1109         if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1110             av_freep(&c->packet_buffer);
1111             return -1;
1112         }
1113         /* no need to write if no events */
1114         if (!(c->poll_entry->revents & POLLOUT))
1115             return 0;
1116         len = send(c->fd, c->packet_buffer_ptr,
1117                     c->packet_buffer_end - c->packet_buffer_ptr, 0);
1118         if (len < 0) {
1119             if (ff_neterrno() != AVERROR(EAGAIN) &&
1120                 ff_neterrno() != AVERROR(EINTR)) {
1121                 /* error : close connection */
1122                 av_freep(&c->packet_buffer);
1123                 return -1;
1124             }
1125             break;
1126         }
1127         c->packet_buffer_ptr += len;
1128         if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1129             /* all the buffer was sent : wait for a new request */
1130             av_freep(&c->packet_buffer);
1131             c->state = RTSPSTATE_WAIT_REQUEST;
1132         }
1133         break;
1134     case HTTPSTATE_READY:
1135         /* nothing to do */
1136         break;
1137     default:
1138         return -1;
1139     }
1140     return 0;
1141
1142 close_connection:
1143     av_freep(&c->pb_buffer);
1144     return -1;
1145 }
1146
1147 static int extract_rates(char *rates, int ratelen, const char *request)
1148 {
1149     const char *p;
1150
1151     for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1152         if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1153             const char *q = p + 7;
1154
1155             while (*q && *q != '\n' && av_isspace(*q))
1156                 q++;
1157
1158             if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1159                 int stream_no;
1160                 int rate_no;
1161
1162                 q += 20;
1163
1164                 memset(rates, 0xff, ratelen);
1165
1166                 while (1) {
1167                     while (*q && *q != '\n' && *q != ':')
1168                         q++;
1169
1170                     if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1171                         break;
1172
1173                     stream_no--;
1174                     if (stream_no < ratelen && stream_no >= 0)
1175                         rates[stream_no] = rate_no;
1176
1177                     while (*q && *q != '\n' && !av_isspace(*q))
1178                         q++;
1179                 }
1180
1181                 return 1;
1182             }
1183         }
1184         p = strchr(p, '\n');
1185         if (!p)
1186             break;
1187
1188         p++;
1189     }
1190
1191     return 0;
1192 }
1193
1194 static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec,
1195                                int bit_rate)
1196 {
1197     int i;
1198     int best_bitrate = 100000000;
1199     int best = -1;
1200
1201     for (i = 0; i < feed->nb_streams; i++) {
1202         AVCodecParameters *feed_codec = feed->streams[i]->codecpar;
1203
1204         if (feed_codec->codec_id != codec->codec_id ||
1205             feed_codec->sample_rate != codec->sample_rate ||
1206             feed_codec->width != codec->width ||
1207             feed_codec->height != codec->height)
1208             continue;
1209
1210         /* Potential stream */
1211
1212         /* We want the fastest stream less than bit_rate, or the slowest
1213          * faster than bit_rate
1214          */
1215
1216         if (feed_codec->bit_rate <= bit_rate) {
1217             if (best_bitrate > bit_rate ||
1218                 feed_codec->bit_rate > best_bitrate) {
1219                 best_bitrate = feed_codec->bit_rate;
1220                 best = i;
1221             }
1222             continue;
1223         }
1224         if (feed_codec->bit_rate < best_bitrate) {
1225             best_bitrate = feed_codec->bit_rate;
1226             best = i;
1227         }
1228     }
1229     return best;
1230 }
1231
1232 static int modify_current_stream(HTTPContext *c, char *rates)
1233 {
1234     int i;
1235     FFServerStream *req = c->stream;
1236     int action_required = 0;
1237
1238     /* Not much we can do for a feed */
1239     if (!req->feed)
1240         return 0;
1241
1242     for (i = 0; i < req->nb_streams; i++) {
1243         AVCodecParameters *codec = req->streams[i]->codecpar;
1244
1245         switch(rates[i]) {
1246             case 0:
1247                 c->switch_feed_streams[i] = req->feed_streams[i];
1248                 break;
1249             case 1:
1250                 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1251                 break;
1252             case 2:
1253                 /* Wants off or slow */
1254                 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1255 #ifdef WANTS_OFF
1256                 /* This doesn't work well when it turns off the only stream! */
1257                 c->switch_feed_streams[i] = -2;
1258                 c->feed_streams[i] = -2;
1259 #endif
1260                 break;
1261         }
1262
1263         if (c->switch_feed_streams[i] >= 0 &&
1264             c->switch_feed_streams[i] != c->feed_streams[i]) {
1265             action_required = 1;
1266         }
1267     }
1268
1269     return action_required;
1270 }
1271
1272 static void get_word(char *buf, int buf_size, const char **pp)
1273 {
1274     const char *p;
1275     char *q;
1276
1277 #define SPACE_CHARS " \t\r\n"
1278
1279     p = *pp;
1280     p += strspn(p, SPACE_CHARS);
1281     q = buf;
1282     while (!av_isspace(*p) && *p != '\0') {
1283         if ((q - buf) < buf_size - 1)
1284             *q++ = *p;
1285         p++;
1286     }
1287     if (buf_size > 0)
1288         *q = '\0';
1289     *pp = p;
1290 }
1291
1292 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1293                                                HTTPContext *c)
1294 {
1295     FILE* f;
1296     char line[1024];
1297     char  cmd[1024];
1298     FFServerIPAddressACL *acl = NULL;
1299     int line_num = 0;
1300     const char *p;
1301
1302     f = fopen(stream->dynamic_acl, "r");
1303     if (!f) {
1304         perror(stream->dynamic_acl);
1305         return NULL;
1306     }
1307
1308     acl = av_mallocz(sizeof(FFServerIPAddressACL));
1309     if (!acl) {
1310         fclose(f);
1311         return NULL;
1312     }
1313
1314     /* Build ACL */
1315     while (fgets(line, sizeof(line), f)) {
1316         line_num++;
1317         p = line;
1318         while (av_isspace(*p))
1319             p++;
1320         if (*p == '\0' || *p == '#')
1321             continue;
1322         ffserver_get_arg(cmd, sizeof(cmd), &p);
1323
1324         if (!av_strcasecmp(cmd, "ACL"))
1325             ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1326                                    line_num);
1327     }
1328     fclose(f);
1329     return acl;
1330 }
1331
1332
1333 static void free_acl_list(FFServerIPAddressACL *in_acl)
1334 {
1335     FFServerIPAddressACL *pacl, *pacl2;
1336
1337     pacl = in_acl;
1338     while(pacl) {
1339         pacl2 = pacl;
1340         pacl = pacl->next;
1341         av_freep(pacl2);
1342     }
1343 }
1344
1345 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1346 {
1347     enum FFServerIPAddressAction last_action = IP_DENY;
1348     FFServerIPAddressACL *acl;
1349     struct in_addr *src = &c->from_addr.sin_addr;
1350     unsigned long src_addr = src->s_addr;
1351
1352     for (acl = in_acl; acl; acl = acl->next) {
1353         if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1354             return (acl->action == IP_ALLOW) ? 1 : 0;
1355         last_action = acl->action;
1356     }
1357
1358     /* Nothing matched, so return not the last action */
1359     return (last_action == IP_DENY) ? 1 : 0;
1360 }
1361
1362 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1363 {
1364     int ret = 0;
1365     FFServerIPAddressACL *acl;
1366
1367     /* if stream->acl is null validate_acl_list will return 1 */
1368     ret = validate_acl_list(stream->acl, c);
1369
1370     if (stream->dynamic_acl[0]) {
1371         acl = parse_dynamic_acl(stream, c);
1372         ret = validate_acl_list(acl, c);
1373         free_acl_list(acl);
1374     }
1375
1376     return ret;
1377 }
1378
1379 /**
1380  * compute the real filename of a file by matching it without its
1381  * extensions to all the stream's filenames
1382  */
1383 static void compute_real_filename(char *filename, int max_size)
1384 {
1385     char file1[1024];
1386     char file2[1024];
1387     char *p;
1388     FFServerStream *stream;
1389
1390     av_strlcpy(file1, filename, sizeof(file1));
1391     p = strrchr(file1, '.');
1392     if (p)
1393         *p = '\0';
1394     for(stream = config.first_stream; stream; stream = stream->next) {
1395         av_strlcpy(file2, stream->filename, sizeof(file2));
1396         p = strrchr(file2, '.');
1397         if (p)
1398             *p = '\0';
1399         if (!strcmp(file1, file2)) {
1400             av_strlcpy(filename, stream->filename, max_size);
1401             break;
1402         }
1403     }
1404 }
1405
1406 enum RedirType {
1407     REDIR_NONE,
1408     REDIR_ASX,
1409     REDIR_RAM,
1410     REDIR_ASF,
1411     REDIR_RTSP,
1412     REDIR_SDP,
1413 };
1414
1415 /* parse HTTP request and prepare header */
1416 static int http_parse_request(HTTPContext *c)
1417 {
1418     const char *p;
1419     char *p1;
1420     enum RedirType redir_type;
1421     char cmd[32];
1422     char info[1024], filename[1024];
1423     char url[1024], *q;
1424     char protocol[32];
1425     char msg[1024];
1426     char *encoded_msg = NULL;
1427     const char *mime_type;
1428     FFServerStream *stream;
1429     int i;
1430     char ratebuf[32];
1431     const char *useragent = 0;
1432
1433     p = c->buffer;
1434     get_word(cmd, sizeof(cmd), &p);
1435     av_strlcpy(c->method, cmd, sizeof(c->method));
1436
1437     if (!strcmp(cmd, "GET"))
1438         c->post = 0;
1439     else if (!strcmp(cmd, "POST"))
1440         c->post = 1;
1441     else
1442         return -1;
1443
1444     get_word(url, sizeof(url), &p);
1445     av_strlcpy(c->url, url, sizeof(c->url));
1446
1447     get_word(protocol, sizeof(protocol), (const char **)&p);
1448     if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1449         return -1;
1450
1451     av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1452
1453     if (config.debug)
1454         http_log("%s - - New connection: %s %s\n",
1455                  inet_ntoa(c->from_addr.sin_addr), cmd, url);
1456
1457     /* find the filename and the optional info string in the request */
1458     p1 = strchr(url, '?');
1459     if (p1) {
1460         av_strlcpy(info, p1, sizeof(info));
1461         *p1 = '\0';
1462     } else
1463         info[0] = '\0';
1464
1465     av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1466
1467     for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1468         if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1469             useragent = p + 11;
1470             if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1471                 useragent++;
1472             break;
1473         }
1474         p = strchr(p, '\n');
1475         if (!p)
1476             break;
1477
1478         p++;
1479     }
1480
1481     redir_type = REDIR_NONE;
1482     if (av_match_ext(filename, "asx")) {
1483         redir_type = REDIR_ASX;
1484         filename[strlen(filename)-1] = 'f';
1485     } else if (av_match_ext(filename, "asf") &&
1486         (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1487         /* if this isn't WMP or lookalike, return the redirector file */
1488         redir_type = REDIR_ASF;
1489     } else if (av_match_ext(filename, "rpm,ram")) {
1490         redir_type = REDIR_RAM;
1491         strcpy(filename + strlen(filename)-2, "m");
1492     } else if (av_match_ext(filename, "rtsp")) {
1493         redir_type = REDIR_RTSP;
1494         compute_real_filename(filename, sizeof(filename) - 1);
1495     } else if (av_match_ext(filename, "sdp")) {
1496         redir_type = REDIR_SDP;
1497         compute_real_filename(filename, sizeof(filename) - 1);
1498     }
1499
1500     /* "redirect" request to index.html */
1501     if (!strlen(filename))
1502         av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1503
1504     stream = config.first_stream;
1505     while (stream) {
1506         if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1507             break;
1508         stream = stream->next;
1509     }
1510     if (!stream) {
1511         snprintf(msg, sizeof(msg), "File '%s' not found", url);
1512         http_log("File '%s' not found\n", url);
1513         goto send_error;
1514     }
1515
1516     c->stream = stream;
1517     memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1518     memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1519
1520     if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1521         c->http_error = 301;
1522         q = c->buffer;
1523         snprintf(q, c->buffer_size,
1524                       "HTTP/1.0 301 Moved\r\n"
1525                       "Location: %s\r\n"
1526                       "Content-type: text/html\r\n"
1527                       "\r\n"
1528                       "<!DOCTYPE html>\n"
1529                       "<html><head><title>Moved</title></head><body>\r\n"
1530                       "You should be <a href=\"%s\">redirected</a>.\r\n"
1531                       "</body></html>\r\n",
1532                  stream->feed_filename, stream->feed_filename);
1533         q += strlen(q);
1534         /* prepare output buffer */
1535         c->buffer_ptr = c->buffer;
1536         c->buffer_end = q;
1537         c->state = HTTPSTATE_SEND_HEADER;
1538         return 0;
1539     }
1540
1541     /* If this is WMP, get the rate information */
1542     if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1543         if (modify_current_stream(c, ratebuf)) {
1544             for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1545                 if (c->switch_feed_streams[i] >= 0)
1546                     c->switch_feed_streams[i] = -1;
1547             }
1548         }
1549     }
1550
1551     if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1552         current_bandwidth += stream->bandwidth;
1553
1554     /* If already streaming this feed, do not let another feeder start */
1555     if (stream->feed_opened) {
1556         snprintf(msg, sizeof(msg), "This feed is already being received.");
1557         http_log("Feed '%s' already being received\n", stream->feed_filename);
1558         goto send_error;
1559     }
1560
1561     if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1562         c->http_error = 503;
1563         q = c->buffer;
1564         snprintf(q, c->buffer_size,
1565                       "HTTP/1.0 503 Server too busy\r\n"
1566                       "Content-type: text/html\r\n"
1567                       "\r\n"
1568                       "<!DOCTYPE html>\n"
1569                       "<html><head><title>Too busy</title></head><body>\r\n"
1570                       "<p>The server is too busy to serve your request at "
1571                       "this time.</p>\r\n"
1572                       "<p>The bandwidth being served (including your stream) "
1573                       "is %"PRIu64"kbit/s, and this exceeds the limit of "
1574                       "%"PRIu64"kbit/s.</p>\r\n"
1575                       "</body></html>\r\n",
1576                  current_bandwidth, config.max_bandwidth);
1577         q += strlen(q);
1578         /* prepare output buffer */
1579         c->buffer_ptr = c->buffer;
1580         c->buffer_end = q;
1581         c->state = HTTPSTATE_SEND_HEADER;
1582         return 0;
1583     }
1584
1585     if (redir_type != REDIR_NONE) {
1586         const char *hostinfo = 0;
1587
1588         for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1589             if (av_strncasecmp(p, "Host:", 5) == 0) {
1590                 hostinfo = p + 5;
1591                 break;
1592             }
1593             p = strchr(p, '\n');
1594             if (!p)
1595                 break;
1596
1597             p++;
1598         }
1599
1600         if (hostinfo) {
1601             char *eoh;
1602             char hostbuf[260];
1603
1604             while (av_isspace(*hostinfo))
1605                 hostinfo++;
1606
1607             eoh = strchr(hostinfo, '\n');
1608             if (eoh) {
1609                 if (eoh[-1] == '\r')
1610                     eoh--;
1611
1612                 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1613                     memcpy(hostbuf, hostinfo, eoh - hostinfo);
1614                     hostbuf[eoh - hostinfo] = 0;
1615
1616                     c->http_error = 200;
1617                     q = c->buffer;
1618                     switch(redir_type) {
1619                     case REDIR_ASX:
1620                         snprintf(q, c->buffer_size,
1621                                       "HTTP/1.0 200 ASX Follows\r\n"
1622                                       "Content-type: video/x-ms-asf\r\n"
1623                                       "\r\n"
1624                                       "<ASX Version=\"3\">\r\n"
1625                                       //"<!-- Autogenerated by ffserver -->\r\n"
1626                                       "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1627                                       "</ASX>\r\n", hostbuf, filename, info);
1628                         q += strlen(q);
1629                         break;
1630                     case REDIR_RAM:
1631                         snprintf(q, c->buffer_size,
1632                                       "HTTP/1.0 200 RAM Follows\r\n"
1633                                       "Content-type: audio/x-pn-realaudio\r\n"
1634                                       "\r\n"
1635                                       "# Autogenerated by ffserver\r\n"
1636                                       "http://%s/%s%s\r\n", hostbuf, filename, info);
1637                         q += strlen(q);
1638                         break;
1639                     case REDIR_ASF:
1640                         snprintf(q, c->buffer_size,
1641                                       "HTTP/1.0 200 ASF Redirect follows\r\n"
1642                                       "Content-type: video/x-ms-asf\r\n"
1643                                       "\r\n"
1644                                       "[Reference]\r\n"
1645                                       "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1646                         q += strlen(q);
1647                         break;
1648                     case REDIR_RTSP:
1649                         {
1650                             char hostname[256], *p;
1651                             /* extract only hostname */
1652                             av_strlcpy(hostname, hostbuf, sizeof(hostname));
1653                             p = strrchr(hostname, ':');
1654                             if (p)
1655                                 *p = '\0';
1656                             snprintf(q, c->buffer_size,
1657                                           "HTTP/1.0 200 RTSP Redirect follows\r\n"
1658                                           /* XXX: incorrect MIME type ? */
1659                                           "Content-type: application/x-rtsp\r\n"
1660                                           "\r\n"
1661                                           "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1662                             q += strlen(q);
1663                         }
1664                         break;
1665                     case REDIR_SDP:
1666                         {
1667                             uint8_t *sdp_data;
1668                             int sdp_data_size;
1669                             socklen_t len;
1670                             struct sockaddr_in my_addr;
1671
1672                             snprintf(q, c->buffer_size,
1673                                           "HTTP/1.0 200 OK\r\n"
1674                                           "Content-type: application/sdp\r\n"
1675                                           "\r\n");
1676                             q += strlen(q);
1677
1678                             len = sizeof(my_addr);
1679
1680                             /* XXX: Should probably fail? */
1681                             if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1682                                 http_log("getsockname() failed\n");
1683
1684                             /* XXX: should use a dynamic buffer */
1685                             sdp_data_size = prepare_sdp_description(stream,
1686                                                                     &sdp_data,
1687                                                                     my_addr.sin_addr);
1688                             if (sdp_data_size > 0) {
1689                                 memcpy(q, sdp_data, sdp_data_size);
1690                                 q += sdp_data_size;
1691                                 *q = '\0';
1692                                 av_freep(&sdp_data);
1693                             }
1694                         }
1695                         break;
1696                     default:
1697                         abort();
1698                         break;
1699                     }
1700
1701                     /* prepare output buffer */
1702                     c->buffer_ptr = c->buffer;
1703                     c->buffer_end = q;
1704                     c->state = HTTPSTATE_SEND_HEADER;
1705                     return 0;
1706                 }
1707             }
1708         }
1709
1710         snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1711         goto send_error;
1712     }
1713
1714     stream->conns_served++;
1715
1716     /* XXX: add there authenticate and IP match */
1717
1718     if (c->post) {
1719         /* if post, it means a feed is being sent */
1720         if (!stream->is_feed) {
1721             /* However it might be a status report from WMP! Let us log the
1722              * data as it might come handy one day. */
1723             const char *logline = 0;
1724             int client_id = 0;
1725
1726             for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1727                 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1728                     logline = p;
1729                     break;
1730                 }
1731                 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1732                     client_id = strtol(p + 18, 0, 10);
1733                 p = strchr(p, '\n');
1734                 if (!p)
1735                     break;
1736
1737                 p++;
1738             }
1739
1740             if (logline) {
1741                 char *eol = strchr(logline, '\n');
1742
1743                 logline += 17;
1744
1745                 if (eol) {
1746                     if (eol[-1] == '\r')
1747                         eol--;
1748                     http_log("%.*s\n", (int) (eol - logline), logline);
1749                     c->suppress_log = 1;
1750                 }
1751             }
1752
1753 #ifdef DEBUG
1754             http_log("\nGot request:\n%s\n", c->buffer);
1755 #endif
1756
1757             if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1758                 HTTPContext *wmpc;
1759
1760                 /* Now we have to find the client_id */
1761                 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1762                     if (wmpc->wmp_client_id == client_id)
1763                         break;
1764                 }
1765
1766                 if (wmpc && modify_current_stream(wmpc, ratebuf))
1767                     wmpc->switch_pending = 1;
1768             }
1769
1770             snprintf(msg, sizeof(msg), "POST command not handled");
1771             c->stream = 0;
1772             goto send_error;
1773         }
1774         if (http_start_receive_data(c) < 0) {
1775             snprintf(msg, sizeof(msg), "could not open feed");
1776             goto send_error;
1777         }
1778         c->http_error = 0;
1779         c->state = HTTPSTATE_RECEIVE_DATA;
1780         return 0;
1781     }
1782
1783 #ifdef DEBUG
1784     if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1785         http_log("\nGot request:\n%s\n", c->buffer);
1786 #endif
1787
1788     if (c->stream->stream_type == STREAM_TYPE_STATUS)
1789         goto send_status;
1790
1791     /* open input stream */
1792     if (open_input_stream(c, info) < 0) {
1793         snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1794         goto send_error;
1795     }
1796
1797     /* prepare HTTP header */
1798     c->buffer[0] = 0;
1799     av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1800     mime_type = c->stream->fmt->mime_type;
1801     if (!mime_type)
1802         mime_type = "application/x-octet-stream";
1803     av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1804
1805     /* for asf, we need extra headers */
1806     if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1807         /* Need to allocate a client id */
1808
1809         c->wmp_client_id = av_lfg_get(&random_state);
1810
1811         av_strlcatf(c->buffer, c->buffer_size, "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);
1812     }
1813     av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1814     av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1815     q = c->buffer + strlen(c->buffer);
1816
1817     /* prepare output buffer */
1818     c->http_error = 0;
1819     c->buffer_ptr = c->buffer;
1820     c->buffer_end = q;
1821     c->state = HTTPSTATE_SEND_HEADER;
1822     return 0;
1823  send_error:
1824     c->http_error = 404;
1825     q = c->buffer;
1826     if (!htmlencode(msg, &encoded_msg)) {
1827         http_log("Could not encode filename '%s' as HTML\n", msg);
1828     }
1829     snprintf(q, c->buffer_size,
1830                   "HTTP/1.0 404 Not Found\r\n"
1831                   "Content-type: text/html\r\n"
1832                   "\r\n"
1833                   "<!DOCTYPE html>\n"
1834                   "<html>\n"
1835                   "<head>\n"
1836                   "<meta charset=\"UTF-8\">\n"
1837                   "<title>404 Not Found</title>\n"
1838                   "</head>\n"
1839                   "<body>%s</body>\n"
1840                   "</html>\n", encoded_msg? encoded_msg : "File not found");
1841     q += strlen(q);
1842     /* prepare output buffer */
1843     c->buffer_ptr = c->buffer;
1844     c->buffer_end = q;
1845     c->state = HTTPSTATE_SEND_HEADER;
1846     av_freep(&encoded_msg);
1847     return 0;
1848  send_status:
1849     compute_status(c);
1850     /* horrible: we use this value to avoid
1851      * going to the send data state */
1852     c->http_error = 200;
1853     c->state = HTTPSTATE_SEND_HEADER;
1854     return 0;
1855 }
1856
1857 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1858 {
1859     static const char suffix[] = " kMGTP";
1860     const char *s;
1861
1862     for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1863
1864     avio_printf(pb, "%"PRId64"%c", count, *s);
1865 }
1866
1867 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1868 {
1869     int i, stream_no;
1870     const char *type = "unknown";
1871     char parameters[64];
1872     AVStream *st;
1873     AVCodec *codec;
1874
1875     stream_no = stream->nb_streams;
1876
1877     avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
1878                     "type<th>kbit/s<th align=left>codec<th align=left>"
1879                     "Parameters\n");
1880
1881     for (i = 0; i < stream_no; i++) {
1882         st = stream->streams[i];
1883         codec = avcodec_find_encoder(st->codecpar->codec_id);
1884
1885         parameters[0] = 0;
1886
1887         switch(st->codecpar->codec_type) {
1888         case AVMEDIA_TYPE_AUDIO:
1889             type = "audio";
1890             snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1891                      st->codecpar->channels, st->codecpar->sample_rate);
1892             break;
1893         case AVMEDIA_TYPE_VIDEO:
1894             type = "video";
1895             snprintf(parameters, sizeof(parameters),
1896                      "%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
1897                      st->codecpar->height, st->codec->qmin, st->codec->qmax,
1898                      st->time_base.den / st->time_base.num);
1899             break;
1900         default:
1901             abort();
1902         }
1903
1904         avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
1905                         "<td>%s<td>%s\n",
1906                     i, type, (int64_t)st->codecpar->bit_rate/1000,
1907                     codec ? codec->name : "", parameters);
1908      }
1909
1910      avio_printf(pb, "</table>\n");
1911 }
1912
1913 static void compute_status(HTTPContext *c)
1914 {
1915     HTTPContext *c1;
1916     FFServerStream *stream;
1917     char *p;
1918     time_t ti;
1919     int i, len;
1920     AVIOContext *pb;
1921
1922     if (avio_open_dyn_buf(&pb) < 0) {
1923         /* XXX: return an error ? */
1924         c->buffer_ptr = c->buffer;
1925         c->buffer_end = c->buffer;
1926         return;
1927     }
1928
1929     avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1930     avio_printf(pb, "Content-type: text/html\r\n");
1931     avio_printf(pb, "Pragma: no-cache\r\n");
1932     avio_printf(pb, "\r\n");
1933
1934     avio_printf(pb, "<!DOCTYPE html>\n");
1935     avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1936     if (c->stream->feed_filename[0])
1937         avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1938                     c->stream->feed_filename);
1939     avio_printf(pb, "</head>\n<body>");
1940     avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1941     /* format status */
1942     avio_printf(pb, "<h2>Available Streams</h2>\n");
1943     avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
1944     avio_printf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbit/s<th align=left>Video<br>kbit/s<th><br>Codec<th align=left>Audio<br>kbit/s<th><br>Codec<th align=left valign=top>Feed\n");
1945     stream = config.first_stream;
1946     while (stream) {
1947         char sfilename[1024];
1948         char *eosf;
1949
1950         if (stream->feed == stream) {
1951             stream = stream->next;
1952             continue;
1953         }
1954
1955         av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1956         eosf = sfilename + strlen(sfilename);
1957         if (eosf - sfilename >= 4) {
1958             if (strcmp(eosf - 4, ".asf") == 0)
1959                 strcpy(eosf - 4, ".asx");
1960             else if (strcmp(eosf - 3, ".rm") == 0)
1961                 strcpy(eosf - 3, ".ram");
1962             else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1963                 /* generate a sample RTSP director if
1964                  * unicast. Generate an SDP redirector if
1965                  * multicast */
1966                 eosf = strrchr(sfilename, '.');
1967                 if (!eosf)
1968                     eosf = sfilename + strlen(sfilename);
1969                 if (stream->is_multicast)
1970                     strcpy(eosf, ".sdp");
1971                 else
1972                     strcpy(eosf, ".rtsp");
1973             }
1974         }
1975
1976         avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1977                     sfilename, stream->filename);
1978         avio_printf(pb, "<td align=right> %d <td align=right> ",
1979                     stream->conns_served);
1980         fmt_bytecount(pb, stream->bytes_served);
1981
1982         switch(stream->stream_type) {
1983         case STREAM_TYPE_LIVE: {
1984             int audio_bit_rate = 0;
1985             int video_bit_rate = 0;
1986             const char *audio_codec_name = "";
1987             const char *video_codec_name = "";
1988             const char *audio_codec_name_extra = "";
1989             const char *video_codec_name_extra = "";
1990
1991             for(i=0;i<stream->nb_streams;i++) {
1992                 AVStream *st = stream->streams[i];
1993                 AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id);
1994
1995                 switch(st->codecpar->codec_type) {
1996                 case AVMEDIA_TYPE_AUDIO:
1997                     audio_bit_rate += st->codecpar->bit_rate;
1998                     if (codec) {
1999                         if (*audio_codec_name)
2000                             audio_codec_name_extra = "...";
2001                         audio_codec_name = codec->name;
2002                     }
2003                     break;
2004                 case AVMEDIA_TYPE_VIDEO:
2005                     video_bit_rate += st->codecpar->bit_rate;
2006                     if (codec) {
2007                         if (*video_codec_name)
2008                             video_codec_name_extra = "...";
2009                         video_codec_name = codec->name;
2010                     }
2011                     break;
2012                 case AVMEDIA_TYPE_DATA:
2013                     video_bit_rate += st->codecpar->bit_rate;
2014                     break;
2015                 default:
2016                     abort();
2017                 }
2018             }
2019
2020             avio_printf(pb, "<td align=center> %s <td align=right> %d "
2021                             "<td align=right> %d <td> %s %s <td align=right> "
2022                             "%d <td> %s %s",
2023                         stream->fmt->name, stream->bandwidth,
2024                         video_bit_rate / 1000, video_codec_name,
2025                         video_codec_name_extra, audio_bit_rate / 1000,
2026                         audio_codec_name, audio_codec_name_extra);
2027
2028             if (stream->feed)
2029                 avio_printf(pb, "<td>%s", stream->feed->filename);
2030             else
2031                 avio_printf(pb, "<td>%s", stream->feed_filename);
2032             avio_printf(pb, "\n");
2033         }
2034             break;
2035         default:
2036             avio_printf(pb, "<td align=center> - <td align=right> - "
2037                             "<td align=right> - <td><td align=right> - <td>\n");
2038             break;
2039         }
2040         stream = stream->next;
2041     }
2042     avio_printf(pb, "</table>\n");
2043
2044     stream = config.first_stream;
2045     while (stream) {
2046
2047         if (stream->feed != stream) {
2048             stream = stream->next;
2049             continue;
2050         }
2051
2052         avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
2053         if (stream->pid) {
2054             avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
2055
2056 #if defined(linux)
2057             {
2058                 FILE *pid_stat;
2059                 char ps_cmd[64];
2060
2061                 /* This is somewhat linux specific I guess */
2062                 snprintf(ps_cmd, sizeof(ps_cmd),
2063                          "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
2064                          (int64_t) stream->pid);
2065
2066                  pid_stat = popen(ps_cmd, "r");
2067                  if (pid_stat) {
2068                      char cpuperc[10];
2069                      char cpuused[64];
2070
2071                      if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
2072                          avio_printf(pb, "Currently using %s%% of the cpu. "
2073                                          "Total time used %s.\n",
2074                                      cpuperc, cpuused);
2075                      }
2076                      fclose(pid_stat);
2077                  }
2078             }
2079 #endif
2080
2081             avio_printf(pb, "<p>");
2082         }
2083
2084         print_stream_params(pb, stream);
2085         stream = stream->next;
2086     }
2087
2088     /* connection status */
2089     avio_printf(pb, "<h2>Connection Status</h2>\n");
2090
2091     avio_printf(pb, "Number of connections: %d / %d<br>\n",
2092                 nb_connections, config.nb_max_connections);
2093
2094     avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2095                 current_bandwidth, config.max_bandwidth);
2096
2097     avio_printf(pb, "<table>\n");
2098     avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
2099                     "bit/s<th>Actual bit/s<th>Bytes transferred\n");
2100     c1 = first_http_ctx;
2101     i = 0;
2102     while (c1) {
2103         int bitrate;
2104         int j;
2105
2106         bitrate = 0;
2107         if (c1->stream) {
2108             for (j = 0; j < c1->stream->nb_streams; j++) {
2109                 if (!c1->stream->feed)
2110                     bitrate += c1->stream->streams[j]->codecpar->bit_rate;
2111                 else if (c1->feed_streams[j] >= 0)
2112                     bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate;
2113             }
2114         }
2115
2116         i++;
2117         p = inet_ntoa(c1->from_addr.sin_addr);
2118         avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
2119                         "<td align=right>",
2120                     i, c1->stream ? c1->stream->filename : "",
2121                     c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
2122                     c1->protocol, http_state[c1->state]);
2123         fmt_bytecount(pb, bitrate);
2124         avio_printf(pb, "<td align=right>");
2125         fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2126         avio_printf(pb, "<td align=right>");
2127         fmt_bytecount(pb, c1->data_count);
2128         avio_printf(pb, "\n");
2129         c1 = c1->next;
2130     }
2131     avio_printf(pb, "</table>\n");
2132
2133     /* date */
2134     ti = time(NULL);
2135     p = ctime(&ti);
2136     avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
2137     avio_printf(pb, "</body>\n</html>\n");
2138
2139     len = avio_close_dyn_buf(pb, &c->pb_buffer);
2140     c->buffer_ptr = c->pb_buffer;
2141     c->buffer_end = c->pb_buffer + len;
2142 }
2143
2144 static int open_input_stream(HTTPContext *c, const char *info)
2145 {
2146     char buf[128];
2147     char input_filename[1024];
2148     AVFormatContext *s = NULL;
2149     int buf_size, i, ret;
2150     int64_t stream_pos;
2151
2152     /* find file name */
2153     if (c->stream->feed) {
2154         strcpy(input_filename, c->stream->feed->feed_filename);
2155         buf_size = FFM_PACKET_SIZE;
2156         /* compute position (absolute time) */
2157         if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2158             if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2159                 http_log("Invalid date specification '%s' for stream\n", buf);
2160                 return ret;
2161             }
2162         } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2163             int prebuffer = strtol(buf, 0, 10);
2164             stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2165         } else
2166             stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2167     } else {
2168         strcpy(input_filename, c->stream->feed_filename);
2169         buf_size = 0;
2170         /* compute position (relative time) */
2171         if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2172             if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2173                 http_log("Invalid date specification '%s' for stream\n", buf);
2174                 return ret;
2175             }
2176         } else
2177             stream_pos = 0;
2178     }
2179     if (!input_filename[0]) {
2180         http_log("No filename was specified for stream\n");
2181         return AVERROR(EINVAL);
2182     }
2183
2184     /* open stream */
2185     ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2186                               &c->stream->in_opts);
2187     if (ret < 0) {
2188         http_log("Could not open input '%s': %s\n",
2189                  input_filename, av_err2str(ret));
2190         return ret;
2191     }
2192
2193     /* set buffer size */
2194     if (buf_size > 0) {
2195         ret = ffio_set_buf_size(s->pb, buf_size);
2196         if (ret < 0) {
2197             http_log("Failed to set buffer size\n");
2198             return ret;
2199         }
2200     }
2201
2202     s->flags |= AVFMT_FLAG_GENPTS;
2203     c->fmt_in = s;
2204     if (strcmp(s->iformat->name, "ffm") &&
2205         (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2206         http_log("Could not find stream info for input '%s'\n", input_filename);
2207         avformat_close_input(&s);
2208         return ret;
2209     }
2210
2211     /* choose stream as clock source (we favor the video stream if
2212      * present) for packet sending */
2213     c->pts_stream_index = 0;
2214     for(i=0;i<c->stream->nb_streams;i++) {
2215         if (c->pts_stream_index == 0 &&
2216             c->stream->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2217             c->pts_stream_index = i;
2218         }
2219     }
2220
2221     if (c->fmt_in->iformat->read_seek)
2222         av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2223     /* set the start time (needed for maxtime and RTP packet timing) */
2224     c->start_time = cur_time;
2225     c->first_pts = AV_NOPTS_VALUE;
2226     return 0;
2227 }
2228
2229 /* return the server clock (in us) */
2230 static int64_t get_server_clock(HTTPContext *c)
2231 {
2232     /* compute current pts value from system time */
2233     return (cur_time - c->start_time) * 1000;
2234 }
2235
2236 /* return the estimated time (in us) at which the current packet must be sent */
2237 static int64_t get_packet_send_clock(HTTPContext *c)
2238 {
2239     int bytes_left, bytes_sent, frame_bytes;
2240
2241     frame_bytes = c->cur_frame_bytes;
2242     if (frame_bytes <= 0)
2243         return c->cur_pts;
2244
2245     bytes_left = c->buffer_end - c->buffer_ptr;
2246     bytes_sent = frame_bytes - bytes_left;
2247     return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2248 }
2249
2250
2251 static int http_prepare_data(HTTPContext *c)
2252 {
2253     int i, len, ret;
2254     AVFormatContext *ctx;
2255
2256     av_freep(&c->pb_buffer);
2257     switch(c->state) {
2258     case HTTPSTATE_SEND_DATA_HEADER:
2259         ctx = avformat_alloc_context();
2260         if (!ctx)
2261             return AVERROR(ENOMEM);
2262         c->pfmt_ctx = ctx;
2263         av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0);
2264         c->pfmt_ctx->streams = av_mallocz_array(c->stream->nb_streams,
2265                                               sizeof(AVStream *));
2266         if (!c->pfmt_ctx->streams)
2267             return AVERROR(ENOMEM);
2268
2269         for(i=0;i<c->stream->nb_streams;i++) {
2270             AVStream *src;
2271             c->pfmt_ctx->streams[i] = av_mallocz(sizeof(AVStream));
2272
2273             /* if file or feed, then just take streams from FFServerStream
2274              * struct */
2275             if (!c->stream->feed ||
2276                 c->stream->feed == c->stream)
2277                 src = c->stream->streams[i];
2278             else
2279                 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2280
2281             *(c->pfmt_ctx->streams[i]) = *src;
2282             c->pfmt_ctx->streams[i]->priv_data = 0;
2283             /* XXX: should be done in AVStream, not in codec */
2284             c->pfmt_ctx->streams[i]->codec->frame_number = 0;
2285         }
2286         /* set output format parameters */
2287         c->pfmt_ctx->oformat = c->stream->fmt;
2288         c->pfmt_ctx->nb_streams = c->stream->nb_streams;
2289
2290         c->got_key_frame = 0;
2291
2292         /* prepare header and save header data in a stream */
2293         if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) {
2294             /* XXX: potential leak */
2295             return -1;
2296         }
2297         c->pfmt_ctx->pb->seekable = 0;
2298
2299         /*
2300          * HACK to avoid MPEG-PS muxer to spit many underflow errors
2301          * Default value from FFmpeg
2302          * Try to set it using configuration option
2303          */
2304         c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE);
2305
2306         if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) {
2307             http_log("Error writing output header for stream '%s': %s\n",
2308                      c->stream->filename, av_err2str(ret));
2309             return ret;
2310         }
2311         av_dict_free(&c->pfmt_ctx->metadata);
2312
2313         len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer);
2314         c->buffer_ptr = c->pb_buffer;
2315         c->buffer_end = c->pb_buffer + len;
2316
2317         c->state = HTTPSTATE_SEND_DATA;
2318         c->last_packet_sent = 0;
2319         break;
2320     case HTTPSTATE_SEND_DATA:
2321         /* find a new packet */
2322         /* read a packet from the input stream */
2323         if (c->stream->feed)
2324             ffm_set_write_index(c->fmt_in,
2325                                 c->stream->feed->feed_write_index,
2326                                 c->stream->feed->feed_size);
2327
2328         if (c->stream->max_time &&
2329             c->stream->max_time + c->start_time - cur_time < 0)
2330             /* We have timed out */
2331             c->state = HTTPSTATE_SEND_DATA_TRAILER;
2332         else {
2333             AVPacket pkt;
2334         redo:
2335             ret = av_read_frame(c->fmt_in, &pkt);
2336             if (ret < 0) {
2337                 if (c->stream->feed) {
2338                     /* if coming from feed, it means we reached the end of the
2339                      * ffm file, so must wait for more data */
2340                     c->state = HTTPSTATE_WAIT_FEED;
2341                     return 1; /* state changed */
2342                 }
2343                 if (ret == AVERROR(EAGAIN)) {
2344                     /* input not ready, come back later */
2345                     return 0;
2346                 }
2347                 if (c->stream->loop) {
2348                     avformat_close_input(&c->fmt_in);
2349                     if (open_input_stream(c, "") < 0)
2350                         goto no_loop;
2351                     goto redo;
2352                 } else {
2353                     no_loop:
2354                         /* must send trailer now because EOF or error */
2355                         c->state = HTTPSTATE_SEND_DATA_TRAILER;
2356                 }
2357             } else {
2358                 int source_index = pkt.stream_index;
2359                 /* update first pts if needed */
2360                 if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
2361                     c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2362                     c->start_time = cur_time;
2363                 }
2364                 /* send it to the appropriate stream */
2365                 if (c->stream->feed) {
2366                     /* if coming from a feed, select the right stream */
2367                     if (c->switch_pending) {
2368                         c->switch_pending = 0;
2369                         for(i=0;i<c->stream->nb_streams;i++) {
2370                             if (c->switch_feed_streams[i] == pkt.stream_index)
2371                                 if (pkt.flags & AV_PKT_FLAG_KEY)
2372                                     c->switch_feed_streams[i] = -1;
2373                             if (c->switch_feed_streams[i] >= 0)
2374                                 c->switch_pending = 1;
2375                         }
2376                     }
2377                     for(i=0;i<c->stream->nb_streams;i++) {
2378                         if (c->stream->feed_streams[i] == pkt.stream_index) {
2379                             AVStream *st = c->fmt_in->streams[source_index];
2380                             pkt.stream_index = i;
2381                             if (pkt.flags & AV_PKT_FLAG_KEY &&
2382                                 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2383                                  c->stream->nb_streams == 1))
2384                                 c->got_key_frame = 1;
2385                             if (!c->stream->send_on_key || c->got_key_frame)
2386                                 goto send_it;
2387                         }
2388                     }
2389                 } else {
2390                     AVCodecContext *codec;
2391                     AVStream *ist, *ost;
2392                 send_it:
2393                     ist = c->fmt_in->streams[source_index];
2394                     /* specific handling for RTP: we use several
2395                      * output streams (one for each RTP connection).
2396                      * XXX: need more abstract handling */
2397                     if (c->is_packetized) {
2398                         /* compute send time and duration */
2399                         if (pkt.dts != AV_NOPTS_VALUE) {
2400                             c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2401                             c->cur_pts -= c->first_pts;
2402                         }
2403                         c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2404                         /* find RTP context */
2405                         c->packet_stream_index = pkt.stream_index;
2406                         ctx = c->rtp_ctx[c->packet_stream_index];
2407                         if(!ctx) {
2408                             av_packet_unref(&pkt);
2409                             break;
2410                         }
2411                         codec = ctx->streams[0]->codec;
2412                         /* only one stream per RTP connection */
2413                         pkt.stream_index = 0;
2414                     } else {
2415                         ctx = c->pfmt_ctx;
2416                         /* Fudge here */
2417                         codec = ctx->streams[pkt.stream_index]->codec;
2418                     }
2419
2420                     if (c->is_packetized) {
2421                         int max_packet_size;
2422                         if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2423                             max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2424                         else
2425                             max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2426                         ret = ffio_open_dyn_packet_buf(&ctx->pb,
2427                                                        max_packet_size);
2428                     } else
2429                         ret = avio_open_dyn_buf(&ctx->pb);
2430
2431                     if (ret < 0) {
2432                         /* XXX: potential leak */
2433                         return -1;
2434                     }
2435                     ost = ctx->streams[pkt.stream_index];
2436
2437                     ctx->pb->seekable = 0;
2438                     if (pkt.dts != AV_NOPTS_VALUE)
2439                         pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2440                                                ost->time_base);
2441                     if (pkt.pts != AV_NOPTS_VALUE)
2442                         pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2443                                                ost->time_base);
2444                     pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2445                                                 ost->time_base);
2446                     if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2447                         http_log("Error writing frame to output for stream '%s': %s\n",
2448                                  c->stream->filename, av_err2str(ret));
2449                         c->state = HTTPSTATE_SEND_DATA_TRAILER;
2450                     }
2451
2452                     av_freep(&c->pb_buffer);
2453                     len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2454                     ctx->pb = NULL;
2455                     c->cur_frame_bytes = len;
2456                     c->buffer_ptr = c->pb_buffer;
2457                     c->buffer_end = c->pb_buffer + len;
2458
2459                     codec->frame_number++;
2460                     if (len == 0) {
2461                         av_packet_unref(&pkt);
2462                         goto redo;
2463                     }
2464                 }
2465                 av_packet_unref(&pkt);
2466             }
2467         }
2468         break;
2469     default:
2470     case HTTPSTATE_SEND_DATA_TRAILER:
2471         /* last packet test ? */
2472         if (c->last_packet_sent || c->is_packetized)
2473             return -1;
2474         ctx = c->pfmt_ctx;
2475         /* prepare header */
2476         if (avio_open_dyn_buf(&ctx->pb) < 0) {
2477             /* XXX: potential leak */
2478             return -1;
2479         }
2480         c->pfmt_ctx->pb->seekable = 0;
2481         av_write_trailer(ctx);
2482         len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2483         c->buffer_ptr = c->pb_buffer;
2484         c->buffer_end = c->pb_buffer + len;
2485
2486         c->last_packet_sent = 1;
2487         break;
2488     }
2489     return 0;
2490 }
2491
2492 /* should convert the format at the same time */
2493 /* send data starting at c->buffer_ptr to the output connection
2494  * (either UDP or TCP)
2495  */
2496 static int http_send_data(HTTPContext *c)
2497 {
2498     int len, ret;
2499
2500     for(;;) {
2501         if (c->buffer_ptr >= c->buffer_end) {
2502             ret = http_prepare_data(c);
2503             if (ret < 0)
2504                 return -1;
2505             else if (ret)
2506                 /* state change requested */
2507                 break;
2508         } else {
2509             if (c->is_packetized) {
2510                 /* RTP data output */
2511                 len = c->buffer_end - c->buffer_ptr;
2512                 if (len < 4) {
2513                     /* fail safe - should never happen */
2514                 fail1:
2515                     c->buffer_ptr = c->buffer_end;
2516                     return 0;
2517                 }
2518                 len = (c->buffer_ptr[0] << 24) |
2519                     (c->buffer_ptr[1] << 16) |
2520                     (c->buffer_ptr[2] << 8) |
2521                     (c->buffer_ptr[3]);
2522                 if (len > (c->buffer_end - c->buffer_ptr))
2523                     goto fail1;
2524                 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2525                     /* nothing to send yet: we can wait */
2526                     return 0;
2527                 }
2528
2529                 c->data_count += len;
2530                 update_datarate(&c->datarate, c->data_count);
2531                 if (c->stream)
2532                     c->stream->bytes_served += len;
2533
2534                 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2535                     /* RTP packets are sent inside the RTSP TCP connection */
2536                     AVIOContext *pb;
2537                     int interleaved_index, size;
2538                     uint8_t header[4];
2539                     HTTPContext *rtsp_c;
2540
2541                     rtsp_c = c->rtsp_c;
2542                     /* if no RTSP connection left, error */
2543                     if (!rtsp_c)
2544                         return -1;
2545                     /* if already sending something, then wait. */
2546                     if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2547                         break;
2548                     if (avio_open_dyn_buf(&pb) < 0)
2549                         goto fail1;
2550                     interleaved_index = c->packet_stream_index * 2;
2551                     /* RTCP packets are sent at odd indexes */
2552                     if (c->buffer_ptr[1] == 200)
2553                         interleaved_index++;
2554                     /* write RTSP TCP header */
2555                     header[0] = '$';
2556                     header[1] = interleaved_index;
2557                     header[2] = len >> 8;
2558                     header[3] = len;
2559                     avio_write(pb, header, 4);
2560                     /* write RTP packet data */
2561                     c->buffer_ptr += 4;
2562                     avio_write(pb, c->buffer_ptr, len);
2563                     size = avio_close_dyn_buf(pb, &c->packet_buffer);
2564                     /* prepare asynchronous TCP sending */
2565                     rtsp_c->packet_buffer_ptr = c->packet_buffer;
2566                     rtsp_c->packet_buffer_end = c->packet_buffer + size;
2567                     c->buffer_ptr += len;
2568
2569                     /* send everything we can NOW */
2570                     len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2571                                rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2572                     if (len > 0)
2573                         rtsp_c->packet_buffer_ptr += len;
2574                     if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2575                         /* if we could not send all the data, we will
2576                          * send it later, so a new state is needed to
2577                          * "lock" the RTSP TCP connection */
2578                         rtsp_c->state = RTSPSTATE_SEND_PACKET;
2579                         break;
2580                     } else
2581                         /* all data has been sent */
2582                         av_freep(&c->packet_buffer);
2583                 } else {
2584                     /* send RTP packet directly in UDP */
2585                     c->buffer_ptr += 4;
2586                     ffurl_write(c->rtp_handles[c->packet_stream_index],
2587                                 c->buffer_ptr, len);
2588                     c->buffer_ptr += len;
2589                     /* here we continue as we can send several packets
2590                      * per 10 ms slot */
2591                 }
2592             } else {
2593                 /* TCP data output */
2594                 len = send(c->fd, c->buffer_ptr,
2595                            c->buffer_end - c->buffer_ptr, 0);
2596                 if (len < 0) {
2597                     if (ff_neterrno() != AVERROR(EAGAIN) &&
2598                         ff_neterrno() != AVERROR(EINTR))
2599                         /* error : close connection */
2600                         return -1;
2601                     else
2602                         return 0;
2603                 }
2604                 c->buffer_ptr += len;
2605
2606                 c->data_count += len;
2607                 update_datarate(&c->datarate, c->data_count);
2608                 if (c->stream)
2609                     c->stream->bytes_served += len;
2610                 break;
2611             }
2612         }
2613     } /* for(;;) */
2614     return 0;
2615 }
2616
2617 static int http_start_receive_data(HTTPContext *c)
2618 {
2619     int fd;
2620     int ret;
2621     int64_t ret64;
2622
2623     if (c->stream->feed_opened) {
2624         http_log("Stream feed '%s' was not opened\n",
2625                  c->stream->feed_filename);
2626         return AVERROR(EINVAL);
2627     }
2628
2629     /* Don't permit writing to this one */
2630     if (c->stream->readonly) {
2631         http_log("Cannot write to read-only file '%s'\n",
2632                  c->stream->feed_filename);
2633         return AVERROR(EINVAL);
2634     }
2635
2636     /* open feed */
2637     fd = open(c->stream->feed_filename, O_RDWR);
2638     if (fd < 0) {
2639         ret = AVERROR(errno);
2640         http_log("Could not open feed file '%s': %s\n",
2641                  c->stream->feed_filename, strerror(errno));
2642         return ret;
2643     }
2644     c->feed_fd = fd;
2645
2646     if (c->stream->truncate) {
2647         /* truncate feed file */
2648         ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2649         http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2650         if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2651             ret = AVERROR(errno);
2652             http_log("Error truncating feed file '%s': %s\n",
2653                      c->stream->feed_filename, strerror(errno));
2654             return ret;
2655         }
2656     } else {
2657         ret64 = ffm_read_write_index(fd);
2658         if (ret64 < 0) {
2659             http_log("Error reading write index from feed file '%s': %s\n",
2660                      c->stream->feed_filename, strerror(errno));
2661             return ret64;
2662         }
2663         c->stream->feed_write_index = ret64;
2664     }
2665
2666     c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2667                                         FFM_PACKET_SIZE);
2668     c->stream->feed_size = lseek(fd, 0, SEEK_END);
2669     lseek(fd, 0, SEEK_SET);
2670
2671     /* init buffer input */
2672     c->buffer_ptr = c->buffer;
2673     c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2674     c->stream->feed_opened = 1;
2675     c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2676     return 0;
2677 }
2678
2679 static int http_receive_data(HTTPContext *c)
2680 {
2681     HTTPContext *c1;
2682     int len, loop_run = 0;
2683
2684     while (c->chunked_encoding && !c->chunk_size &&
2685            c->buffer_end > c->buffer_ptr) {
2686         /* read chunk header, if present */
2687         len = recv(c->fd, c->buffer_ptr, 1, 0);
2688
2689         if (len < 0) {
2690             if (ff_neterrno() != AVERROR(EAGAIN) &&
2691                 ff_neterrno() != AVERROR(EINTR))
2692                 /* error : close connection */
2693                 goto fail;
2694             return 0;
2695         } else if (len == 0) {
2696             /* end of connection : close it */
2697             goto fail;
2698         } else if (c->buffer_ptr - c->buffer >= 2 &&
2699                    !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2700             c->chunk_size = strtol(c->buffer, 0, 16);
2701             if (c->chunk_size == 0) // end of stream
2702                 goto fail;
2703             c->buffer_ptr = c->buffer;
2704             break;
2705         } else if (++loop_run > 10)
2706             /* no chunk header, abort */
2707             goto fail;
2708         else
2709             c->buffer_ptr++;
2710     }
2711
2712     if (c->buffer_end > c->buffer_ptr) {
2713         len = recv(c->fd, c->buffer_ptr,
2714                    FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2715         if (len < 0) {
2716             if (ff_neterrno() != AVERROR(EAGAIN) &&
2717                 ff_neterrno() != AVERROR(EINTR))
2718                 /* error : close connection */
2719                 goto fail;
2720         } else if (len == 0)
2721             /* end of connection : close it */
2722             goto fail;
2723         else {
2724             c->chunk_size -= len;
2725             c->buffer_ptr += len;
2726             c->data_count += len;
2727             update_datarate(&c->datarate, c->data_count);
2728         }
2729     }
2730
2731     if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2732         if (c->buffer[0] != 'f' ||
2733             c->buffer[1] != 'm') {
2734             http_log("Feed stream has become desynchronized -- disconnecting\n");
2735             goto fail;
2736         }
2737     }
2738
2739     if (c->buffer_ptr >= c->buffer_end) {
2740         FFServerStream *feed = c->stream;
2741         /* a packet has been received : write it in the store, except
2742          * if header */
2743         if (c->data_count > FFM_PACKET_SIZE) {
2744             /* XXX: use llseek or url_seek
2745              * XXX: Should probably fail? */
2746             if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2747                 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2748
2749             if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2750                 http_log("Error writing to feed file: %s\n", strerror(errno));
2751                 goto fail;
2752             }
2753
2754             feed->feed_write_index += FFM_PACKET_SIZE;
2755             /* update file size */
2756             if (feed->feed_write_index > c->stream->feed_size)
2757                 feed->feed_size = feed->feed_write_index;
2758
2759             /* handle wrap around if max file size reached */
2760             if (c->stream->feed_max_size &&
2761                 feed->feed_write_index >= c->stream->feed_max_size)
2762                 feed->feed_write_index = FFM_PACKET_SIZE;
2763
2764             /* write index */
2765             if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2766                 http_log("Error writing index to feed file: %s\n",
2767                          strerror(errno));
2768                 goto fail;
2769             }
2770
2771             /* wake up any waiting connections */
2772             for(c1 = first_http_ctx; c1; c1 = c1->next) {
2773                 if (c1->state == HTTPSTATE_WAIT_FEED &&
2774                     c1->stream->feed == c->stream->feed)
2775                     c1->state = HTTPSTATE_SEND_DATA;
2776             }
2777         } else {
2778             /* We have a header in our hands that contains useful data */
2779             AVFormatContext *s = avformat_alloc_context();
2780             AVIOContext *pb;
2781             AVInputFormat *fmt_in;
2782             int i;
2783
2784             if (!s)
2785                 goto fail;
2786
2787             /* use feed output format name to find corresponding input format */
2788             fmt_in = av_find_input_format(feed->fmt->name);
2789             if (!fmt_in)
2790                 goto fail;
2791
2792             pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2793                                     0, NULL, NULL, NULL, NULL);
2794             if (!pb)
2795                 goto fail;
2796
2797             pb->seekable = 0;
2798
2799             s->pb = pb;
2800             if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2801                 av_freep(&pb);
2802                 goto fail;
2803             }
2804
2805             /* Now we have the actual streams */
2806             if (s->nb_streams != feed->nb_streams) {
2807                 avformat_close_input(&s);
2808                 av_freep(&pb);
2809                 http_log("Feed '%s' stream number does not match registered feed\n",
2810                          c->stream->feed_filename);
2811                 goto fail;
2812             }
2813
2814             for (i = 0; i < s->nb_streams; i++) {
2815                 AVStream *fst = feed->streams[i];
2816                 AVStream *st = s->streams[i];
2817                 avcodec_copy_context(fst->codec, st->codec);
2818             }
2819
2820             avformat_close_input(&s);
2821             av_freep(&pb);
2822         }
2823         c->buffer_ptr = c->buffer;
2824     }
2825
2826     return 0;
2827  fail:
2828     c->stream->feed_opened = 0;
2829     close(c->feed_fd);
2830     /* wake up any waiting connections to stop waiting for feed */
2831     for(c1 = first_http_ctx; c1; c1 = c1->next) {
2832         if (c1->state == HTTPSTATE_WAIT_FEED &&
2833             c1->stream->feed == c->stream->feed)
2834             c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2835     }
2836     return -1;
2837 }
2838
2839 /********************************************************************/
2840 /* RTSP handling */
2841
2842 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2843 {
2844     const char *str;
2845     time_t ti;
2846     struct tm *tm;
2847     char buf2[32];
2848
2849     str = RTSP_STATUS_CODE2STRING(error_number);
2850     if (!str)
2851         str = "Unknown Error";
2852
2853     avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2854     avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2855
2856     /* output GMT time */
2857     ti = time(NULL);
2858     tm = gmtime(&ti);
2859     strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2860     avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2861 }
2862
2863 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2864 {
2865     rtsp_reply_header(c, error_number);
2866     avio_printf(c->pb, "\r\n");
2867 }
2868
2869 static int rtsp_parse_request(HTTPContext *c)
2870 {
2871     const char *p, *p1, *p2;
2872     char cmd[32];
2873     char url[1024];
2874     char protocol[32];
2875     char line[1024];
2876     int len;
2877     RTSPMessageHeader header1 = { 0 }, *header = &header1;
2878
2879     c->buffer_ptr[0] = '\0';
2880     p = c->buffer;
2881
2882     get_word(cmd, sizeof(cmd), &p);
2883     get_word(url, sizeof(url), &p);
2884     get_word(protocol, sizeof(protocol), &p);
2885
2886     av_strlcpy(c->method, cmd, sizeof(c->method));
2887     av_strlcpy(c->url, url, sizeof(c->url));
2888     av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2889
2890     if (avio_open_dyn_buf(&c->pb) < 0) {
2891         /* XXX: cannot do more */
2892         c->pb = NULL; /* safety */
2893         return -1;
2894     }
2895
2896     /* check version name */
2897     if (strcmp(protocol, "RTSP/1.0")) {
2898         rtsp_reply_error(c, RTSP_STATUS_VERSION);
2899         goto the_end;
2900     }
2901
2902     /* parse each header line */
2903     /* skip to next line */
2904     while (*p != '\n' && *p != '\0')
2905         p++;
2906     if (*p == '\n')
2907         p++;
2908     while (*p != '\0') {
2909         p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2910         if (!p1)
2911             break;
2912         p2 = p1;
2913         if (p2 > p && p2[-1] == '\r')
2914             p2--;
2915         /* skip empty line */
2916         if (p2 == p)
2917             break;
2918         len = p2 - p;
2919         if (len > sizeof(line) - 1)
2920             len = sizeof(line) - 1;
2921         memcpy(line, p, len);
2922         line[len] = '\0';
2923         ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
2924         p = p1 + 1;
2925     }
2926
2927     /* handle sequence number */
2928     c->seq = header->seq;
2929
2930     if (!strcmp(cmd, "DESCRIBE"))
2931         rtsp_cmd_describe(c, url);
2932     else if (!strcmp(cmd, "OPTIONS"))
2933         rtsp_cmd_options(c, url);
2934     else if (!strcmp(cmd, "SETUP"))
2935         rtsp_cmd_setup(c, url, header);
2936     else if (!strcmp(cmd, "PLAY"))
2937         rtsp_cmd_play(c, url, header);
2938     else if (!strcmp(cmd, "PAUSE"))
2939         rtsp_cmd_interrupt(c, url, header, 1);
2940     else if (!strcmp(cmd, "TEARDOWN"))
2941         rtsp_cmd_interrupt(c, url, header, 0);
2942     else
2943         rtsp_reply_error(c, RTSP_STATUS_METHOD);
2944
2945  the_end:
2946     len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2947     c->pb = NULL; /* safety */
2948     if (len < 0)
2949         /* XXX: cannot do more */
2950         return -1;
2951
2952     c->buffer_ptr = c->pb_buffer;
2953     c->buffer_end = c->pb_buffer + len;
2954     c->state = RTSPSTATE_SEND_REPLY;
2955     return 0;
2956 }
2957
2958 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
2959                                    struct in_addr my_ip)
2960 {
2961     AVFormatContext *avc;
2962     AVStream *avs = NULL;
2963     AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
2964     AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
2965     int i;
2966
2967     *pbuffer = NULL;
2968
2969     avc =  avformat_alloc_context();
2970     if (!avc || !rtp_format)
2971         return -1;
2972
2973     avc->oformat = rtp_format;
2974     av_dict_set(&avc->metadata, "title",
2975                 entry ? entry->value : "No Title", 0);
2976     avc->nb_streams = stream->nb_streams;
2977     if (stream->is_multicast) {
2978         snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2979                  inet_ntoa(stream->multicast_ip),
2980                  stream->multicast_port, stream->multicast_ttl);
2981     } else
2982         snprintf(avc->filename, 1024, "rtp://0.0.0.0");
2983
2984     avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
2985     if (!avc->streams)
2986         goto sdp_done;
2987
2988     avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
2989     if (!avs)
2990         goto sdp_done;
2991
2992     for(i = 0; i < stream->nb_streams; i++) {
2993         avc->streams[i] = &avs[i];
2994         avc->streams[i]->codec = stream->streams[i]->codec;
2995         avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
2996         avc->streams[i]->codecpar = stream->streams[i]->codecpar;
2997     }
2998 #define PBUFFER_SIZE 2048
2999     *pbuffer = av_mallocz(PBUFFER_SIZE);
3000     if (!*pbuffer)
3001         goto sdp_done;
3002     av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
3003
3004  sdp_done:
3005     av_freep(&avc->streams);
3006     av_dict_free(&avc->metadata);
3007     av_free(avc);
3008     av_free(avs);
3009
3010     return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
3011 }
3012
3013 static void rtsp_cmd_options(HTTPContext *c, const char *url)
3014 {
3015     /* rtsp_reply_header(c, RTSP_STATUS_OK); */
3016     avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
3017     avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
3018     avio_printf(c->pb, "Public: %s\r\n",
3019                 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
3020     avio_printf(c->pb, "\r\n");
3021 }
3022
3023 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
3024 {
3025     FFServerStream *stream;
3026     char path1[1024];
3027     const char *path;
3028     uint8_t *content;
3029     int content_length;
3030     socklen_t len;
3031     struct sockaddr_in my_addr;
3032
3033     /* find which URL is asked */
3034     av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3035     path = path1;
3036     if (*path == '/')
3037         path++;
3038
3039     for(stream = config.first_stream; stream; stream = stream->next) {
3040         if (!stream->is_feed &&
3041             stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
3042             !strcmp(path, stream->filename)) {
3043             goto found;
3044         }
3045     }
3046     /* no stream found */
3047     rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
3048     return;
3049
3050  found:
3051     /* prepare the media description in SDP format */
3052
3053     /* get the host IP */
3054     len = sizeof(my_addr);
3055     getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3056     content_length = prepare_sdp_description(stream, &content,
3057                                              my_addr.sin_addr);
3058     if (content_length < 0) {
3059         rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3060         return;
3061     }
3062     rtsp_reply_header(c, RTSP_STATUS_OK);
3063     avio_printf(c->pb, "Content-Base: %s/\r\n", url);
3064     avio_printf(c->pb, "Content-Type: application/sdp\r\n");
3065     avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
3066     avio_printf(c->pb, "\r\n");
3067     avio_write(c->pb, content, content_length);
3068     av_free(content);
3069 }
3070
3071 static HTTPContext *find_rtp_session(const char *session_id)
3072 {
3073     HTTPContext *c;
3074
3075     if (session_id[0] == '\0')
3076         return NULL;
3077
3078     for(c = first_http_ctx; c; c = c->next) {
3079         if (!strcmp(c->session_id, session_id))
3080             return c;
3081     }
3082     return NULL;
3083 }
3084
3085 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3086 {
3087     RTSPTransportField *th;
3088     int i;
3089
3090     for(i=0;i<h->nb_transports;i++) {
3091         th = &h->transports[i];
3092         if (th->lower_transport == lower_transport)
3093             return th;
3094     }
3095     return NULL;
3096 }
3097
3098 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3099                            RTSPMessageHeader *h)
3100 {
3101     FFServerStream *stream;
3102     int stream_index, rtp_port, rtcp_port;
3103     char buf[1024];
3104     char path1[1024];
3105     const char *path;
3106     HTTPContext *rtp_c;
3107     RTSPTransportField *th;
3108     struct sockaddr_in dest_addr;
3109     RTSPActionServerSetup setup;
3110
3111     /* find which URL is asked */
3112     av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3113     path = path1;
3114     if (*path == '/')
3115         path++;
3116
3117     /* now check each stream */
3118     for(stream = config.first_stream; stream; stream = stream->next) {
3119         if (stream->is_feed || !stream->fmt ||
3120             strcmp(stream->fmt->name, "rtp")) {
3121             continue;
3122         }
3123         /* accept aggregate filenames only if single stream */
3124         if (!strcmp(path, stream->filename)) {
3125             if (stream->nb_streams != 1) {
3126                 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3127                 return;
3128             }
3129             stream_index = 0;
3130             goto found;
3131         }
3132
3133         for(stream_index = 0; stream_index < stream->nb_streams;
3134             stream_index++) {
3135             snprintf(buf, sizeof(buf), "%s/streamid=%d",
3136                      stream->filename, stream_index);
3137             if (!strcmp(path, buf))
3138                 goto found;
3139         }
3140     }
3141     /* no stream found */
3142     rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3143     return;
3144  found:
3145
3146     /* generate session id if needed */
3147     if (h->session_id[0] == '\0') {
3148         unsigned random0 = av_lfg_get(&random_state);
3149         unsigned random1 = av_lfg_get(&random_state);
3150         snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3151                  random0, random1);
3152     }
3153
3154     /* find RTP session, and create it if none found */
3155     rtp_c = find_rtp_session(h->session_id);
3156     if (!rtp_c) {
3157         /* always prefer UDP */
3158         th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3159         if (!th) {
3160             th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3161             if (!th) {
3162                 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3163                 return;
3164             }
3165         }
3166
3167         rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3168                                    th->lower_transport);
3169         if (!rtp_c) {
3170             rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3171             return;
3172         }
3173
3174         /* open input stream */
3175         if (open_input_stream(rtp_c, "") < 0) {
3176             rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3177             return;
3178         }
3179     }
3180
3181     /* test if stream is OK (test needed because several SETUP needs
3182      * to be done for a given file) */
3183     if (rtp_c->stream != stream) {
3184         rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3185         return;
3186     }
3187
3188     /* test if stream is already set up */
3189     if (rtp_c->rtp_ctx[stream_index]) {
3190         rtsp_reply_error(c, RTSP_STATUS_STATE);
3191         return;
3192     }
3193
3194     /* check transport */
3195     th = find_transport(h, rtp_c->rtp_protocol);
3196     if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3197                 th->client_port_min <= 0)) {
3198         rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3199         return;
3200     }
3201
3202     /* setup default options */
3203     setup.transport_option[0] = '\0';
3204     dest_addr = rtp_c->from_addr;
3205     dest_addr.sin_port = htons(th->client_port_min);
3206
3207     /* setup stream */
3208     if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3209         rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3210         return;
3211     }
3212
3213     /* now everything is OK, so we can send the connection parameters */
3214     rtsp_reply_header(c, RTSP_STATUS_OK);
3215     /* session ID */
3216     avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3217
3218     switch(rtp_c->rtp_protocol) {
3219     case RTSP_LOWER_TRANSPORT_UDP:
3220         rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3221         rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3222         avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3223                     "client_port=%d-%d;server_port=%d-%d",
3224                     th->client_port_min, th->client_port_max,
3225                     rtp_port, rtcp_port);
3226         break;
3227     case RTSP_LOWER_TRANSPORT_TCP:
3228         avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3229                     stream_index * 2, stream_index * 2 + 1);
3230         break;
3231     default:
3232         break;
3233     }
3234     if (setup.transport_option[0] != '\0')
3235         avio_printf(c->pb, ";%s", setup.transport_option);
3236     avio_printf(c->pb, "\r\n");
3237
3238
3239     avio_printf(c->pb, "\r\n");
3240 }
3241
3242
3243 /**
3244  * find an RTP connection by using the session ID. Check consistency
3245  * with filename
3246  */
3247 static HTTPContext *find_rtp_session_with_url(const char *url,
3248                                               const char *session_id)
3249 {
3250     HTTPContext *rtp_c;
3251     char path1[1024];
3252     const char *path;
3253     char buf[1024];
3254     int s, len;
3255
3256     rtp_c = find_rtp_session(session_id);
3257     if (!rtp_c)
3258         return NULL;
3259
3260     /* find which URL is asked */
3261     av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3262     path = path1;
3263     if (*path == '/')
3264         path++;
3265     if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3266     for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3267       snprintf(buf, sizeof(buf), "%s/streamid=%d",
3268         rtp_c->stream->filename, s);
3269       if(!strncmp(path, buf, sizeof(buf)))
3270         /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3271          * if nb_streams>1? */
3272         return rtp_c;
3273     }
3274     len = strlen(path);
3275     if (len > 0 && path[len - 1] == '/' &&
3276         !strncmp(path, rtp_c->stream->filename, len - 1))
3277         return rtp_c;
3278     return NULL;
3279 }
3280
3281 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3282 {
3283     HTTPContext *rtp_c;
3284
3285     rtp_c = find_rtp_session_with_url(url, h->session_id);
3286     if (!rtp_c) {
3287         rtsp_reply_error(c, RTSP_STATUS_SESSION);
3288         return;
3289     }
3290
3291     if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3292         rtp_c->state != HTTPSTATE_WAIT_FEED &&
3293         rtp_c->state != HTTPSTATE_READY) {
3294         rtsp_reply_error(c, RTSP_STATUS_STATE);
3295         return;
3296     }
3297
3298     rtp_c->state = HTTPSTATE_SEND_DATA;
3299
3300     /* now everything is OK, so we can send the connection parameters */
3301     rtsp_reply_header(c, RTSP_STATUS_OK);
3302     /* session ID */
3303     avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3304     avio_printf(c->pb, "\r\n");
3305 }
3306
3307 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3308                                RTSPMessageHeader *h, int pause_only)
3309 {
3310     HTTPContext *rtp_c;
3311
3312     rtp_c = find_rtp_session_with_url(url, h->session_id);
3313     if (!rtp_c) {
3314         rtsp_reply_error(c, RTSP_STATUS_SESSION);
3315         return;
3316     }
3317
3318     if (pause_only) {
3319         if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3320             rtp_c->state != HTTPSTATE_WAIT_FEED) {
3321             rtsp_reply_error(c, RTSP_STATUS_STATE);
3322             return;
3323         }
3324         rtp_c->state = HTTPSTATE_READY;
3325         rtp_c->first_pts = AV_NOPTS_VALUE;
3326     }
3327
3328     /* now everything is OK, so we can send the connection parameters */
3329     rtsp_reply_header(c, RTSP_STATUS_OK);
3330     /* session ID */
3331     avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3332     avio_printf(c->pb, "\r\n");
3333
3334     if (!pause_only)
3335         close_connection(rtp_c);
3336 }
3337
3338 /********************************************************************/
3339 /* RTP handling */
3340
3341 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3342                                        FFServerStream *stream,
3343                                        const char *session_id,
3344                                        enum RTSPLowerTransport rtp_protocol)
3345 {
3346     HTTPContext *c = NULL;
3347     const char *proto_str;
3348
3349     /* XXX: should output a warning page when coming
3350      * close to the connection limit */
3351     if (nb_connections >= config.nb_max_connections)
3352         goto fail;
3353
3354     /* add a new connection */
3355     c = av_mallocz(sizeof(HTTPContext));
3356     if (!c)
3357         goto fail;
3358
3359     c->fd = -1;
3360     c->poll_entry = NULL;
3361     c->from_addr = *from_addr;
3362     c->buffer_size = IOBUFFER_INIT_SIZE;
3363     c->buffer = av_malloc(c->buffer_size);
3364     if (!c->buffer)
3365         goto fail;
3366     nb_connections++;
3367     c->stream = stream;
3368     av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3369     c->state = HTTPSTATE_READY;
3370     c->is_packetized = 1;
3371     c->rtp_protocol = rtp_protocol;
3372
3373     /* protocol is shown in statistics */
3374     switch(c->rtp_protocol) {
3375     case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3376         proto_str = "MCAST";
3377         break;
3378     case RTSP_LOWER_TRANSPORT_UDP:
3379         proto_str = "UDP";
3380         break;
3381     case RTSP_LOWER_TRANSPORT_TCP:
3382         proto_str = "TCP";
3383         break;
3384     default:
3385         proto_str = "???";
3386         break;
3387     }
3388     av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3389     av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3390
3391     current_bandwidth += stream->bandwidth;
3392
3393     c->next = first_http_ctx;
3394     first_http_ctx = c;
3395     return c;
3396
3397  fail:
3398     if (c) {
3399         av_freep(&c->buffer);
3400         av_free(c);
3401     }
3402     return NULL;
3403 }
3404
3405 /**
3406  * add a new RTP stream in an RTP connection (used in RTSP SETUP
3407  * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3408  * used.
3409  */
3410 static int rtp_new_av_stream(HTTPContext *c,
3411                              int stream_index, struct sockaddr_in *dest_addr,
3412                              HTTPContext *rtsp_c)
3413 {
3414     AVFormatContext *ctx;
3415     AVStream *st;
3416     char *ipaddr;
3417     URLContext *h = NULL;
3418     uint8_t *dummy_buf;
3419     int max_packet_size;
3420     void *st_internal;
3421
3422     /* now we can open the relevant output stream */
3423     ctx = avformat_alloc_context();
3424     if (!ctx)
3425         return -1;
3426     ctx->oformat = av_guess_format("rtp", NULL, NULL);
3427
3428     st = avformat_new_stream(ctx, NULL);
3429     if (!st)
3430         goto fail;
3431
3432     av_freep(&st->codec);
3433     av_freep(&st->info);
3434     st_internal = st->internal;
3435
3436     if (!c->stream->feed ||
3437         c->stream->feed == c->stream)
3438         memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3439     else
3440         memcpy(st,
3441                c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3442                sizeof(AVStream));
3443     st->priv_data = NULL;
3444     st->internal = st_internal;
3445
3446     /* build destination RTP address */
3447     ipaddr = inet_ntoa(dest_addr->sin_addr);
3448
3449     switch(c->rtp_protocol) {
3450     case RTSP_LOWER_TRANSPORT_UDP:
3451     case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3452         /* RTP/UDP case */
3453
3454         /* XXX: also pass as parameter to function ? */
3455         if (c->stream->is_multicast) {
3456             int ttl;
3457             ttl = c->stream->multicast_ttl;
3458             if (!ttl)
3459                 ttl = 16;
3460             snprintf(ctx->filename, sizeof(ctx->filename),
3461                      "rtp://%s:%d?multicast=1&ttl=%d",
3462                      ipaddr, ntohs(dest_addr->sin_port), ttl);
3463         } else {
3464             snprintf(ctx->filename, sizeof(ctx->filename),
3465                      "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3466         }
3467
3468         if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3469             goto fail;
3470         c->rtp_handles[stream_index] = h;
3471         max_packet_size = h->max_packet_size;
3472         break;
3473     case RTSP_LOWER_TRANSPORT_TCP:
3474         /* RTP/TCP case */
3475         c->rtsp_c = rtsp_c;
3476         max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3477         break;
3478     default:
3479         goto fail;
3480     }
3481
3482     http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3483              ipaddr, ntohs(dest_addr->sin_port),
3484              c->stream->filename, stream_index, c->protocol);
3485
3486     /* normally, no packets should be output here, but the packet size may
3487      * be checked */
3488     if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3489         /* XXX: close stream */
3490         goto fail;
3491
3492     if (avformat_write_header(ctx, NULL) < 0) {
3493     fail:
3494         if (h)
3495             ffurl_close(h);
3496         av_free(st);
3497         av_free(ctx);
3498         return -1;
3499     }
3500     avio_close_dyn_buf(ctx->pb, &dummy_buf);
3501     ctx->pb = NULL;
3502     av_free(dummy_buf);
3503
3504     c->rtp_ctx[stream_index] = ctx;
3505     return 0;
3506 }
3507
3508 /********************************************************************/
3509 /* ffserver initialization */
3510
3511 /* FIXME: This code should use avformat_new_stream() */
3512 static AVStream *add_av_stream1(FFServerStream *stream,
3513                                 AVCodecContext *codec, int copy)
3514 {
3515     AVStream *fst;
3516
3517     if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3518         return NULL;
3519
3520     fst = av_mallocz(sizeof(AVStream));
3521     if (!fst)
3522         return NULL;
3523     if (copy) {
3524         fst->codec = avcodec_alloc_context3(codec->codec);
3525         if (!fst->codec) {
3526             av_free(fst);
3527             return NULL;
3528         }
3529         avcodec_copy_context(fst->codec, codec);
3530     } else
3531         /* live streams must use the actual feed's codec since it may be
3532          * updated later to carry extradata needed by them.
3533          */
3534         fst->codec = codec;
3535
3536     fst->priv_data = av_mallocz(sizeof(FeedData));
3537     fst->internal = av_mallocz(sizeof(*fst->internal));
3538     fst->internal->avctx = avcodec_alloc_context3(NULL);
3539     fst->codecpar = avcodec_parameters_alloc();
3540     fst->index = stream->nb_streams;
3541     avpriv_set_pts_info(fst, 33, 1, 90000);
3542     fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3543     stream->streams[stream->nb_streams++] = fst;
3544     return fst;
3545 }
3546
3547 /* return the stream number in the feed */
3548 static int add_av_stream(FFServerStream *feed, AVStream *st)
3549 {
3550     AVStream *fst;
3551     AVCodecContext *av, *av1;
3552     int i;
3553
3554     av = st->codec;
3555     for(i=0;i<feed->nb_streams;i++) {
3556         av1 = feed->streams[i]->codec;
3557         if (av1->codec_id == av->codec_id &&
3558             av1->codec_type == av->codec_type &&
3559             av1->bit_rate == av->bit_rate) {
3560
3561             switch(av->codec_type) {
3562             case AVMEDIA_TYPE_AUDIO:
3563                 if (av1->channels == av->channels &&
3564                     av1->sample_rate == av->sample_rate)
3565                     return i;
3566                 break;
3567             case AVMEDIA_TYPE_VIDEO:
3568                 if (av1->width == av->width &&
3569                     av1->height == av->height &&
3570                     av1->time_base.den == av->time_base.den &&
3571                     av1->time_base.num == av->time_base.num &&
3572                     av1->gop_size == av->gop_size)
3573                     return i;
3574                 break;
3575             default:
3576                 abort();
3577             }
3578         }
3579     }
3580
3581     fst = add_av_stream1(feed, av, 0);
3582     if (!fst)
3583         return -1;
3584     if (av_stream_get_recommended_encoder_configuration(st))
3585         av_stream_set_recommended_encoder_configuration(fst,
3586             av_strdup(av_stream_get_recommended_encoder_configuration(st)));
3587     return feed->nb_streams - 1;
3588 }
3589
3590 static void remove_stream(FFServerStream *stream)
3591 {
3592     FFServerStream **ps;
3593     ps = &config.first_stream;
3594     while (*ps) {
3595         if (*ps == stream)
3596             *ps = (*ps)->next;
3597         else
3598             ps = &(*ps)->next;
3599     }
3600 }
3601
3602 /* specific MPEG4 handling : we extract the raw parameters */
3603 static void extract_mpeg4_header(AVFormatContext *infile)
3604 {
3605     int mpeg4_count, i, size;
3606     AVPacket pkt;
3607     AVStream *st;
3608     const uint8_t *p;
3609
3610     infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
3611
3612     mpeg4_count = 0;
3613     for(i=0;i<infile->nb_streams;i++) {
3614         st = infile->streams[i];
3615         if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3616             st->codec->extradata_size == 0) {
3617             mpeg4_count++;
3618         }
3619     }
3620     if (!mpeg4_count)
3621         return;
3622
3623     printf("MPEG4 without extra data: trying to find header in %s\n",
3624            infile->filename);
3625     while (mpeg4_count > 0) {
3626         if (av_read_frame(infile, &pkt) < 0)
3627             break;
3628         st = infile->streams[pkt.stream_index];
3629         if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3630             st->codec->extradata_size == 0) {
3631             av_freep(&st->codec->extradata);
3632             /* fill extradata with the header */
3633             /* XXX: we make hard suppositions here ! */
3634             p = pkt.data;
3635             while (p < pkt.data + pkt.size - 4) {
3636                 /* stop when vop header is found */
3637                 if (p[0] == 0x00 && p[1] == 0x00 &&
3638                     p[2] == 0x01 && p[3] == 0xb6) {
3639                     size = p - pkt.data;
3640                     st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
3641                     st->codec->extradata_size = size;
3642                     memcpy(st->codec->extradata, pkt.data, size);
3643                     break;
3644                 }
3645                 p++;
3646             }
3647             mpeg4_count--;
3648         }
3649         av_packet_unref(&pkt);
3650     }
3651 }
3652
3653 /* compute the needed AVStream for each file */
3654 static void build_file_streams(void)
3655 {
3656     FFServerStream *stream;
3657     AVFormatContext *infile;
3658     int i, ret;
3659
3660     /* gather all streams */
3661     for(stream = config.first_stream; stream; stream = stream->next) {
3662         infile = NULL;
3663
3664         if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
3665             continue;
3666
3667         /* the stream comes from a file */
3668         /* try to open the file */
3669         /* open stream */
3670
3671
3672         /* specific case: if transport stream output to RTP,
3673          * we use a raw transport stream reader */
3674         if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
3675             av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3676
3677         if (!stream->feed_filename[0]) {
3678             http_log("Unspecified feed file for stream '%s'\n",
3679                      stream->filename);
3680             goto fail;
3681         }
3682
3683         http_log("Opening feed file '%s' for stream '%s'\n",
3684                  stream->feed_filename, stream->filename);
3685
3686         ret = avformat_open_input(&infile, stream->feed_filename,
3687                                   stream->ifmt, &stream->in_opts);
3688         if (ret < 0) {
3689             http_log("Could not open '%s': %s\n", stream->feed_filename,
3690                      av_err2str(ret));
3691             /* remove stream (no need to spend more time on it) */
3692         fail:
3693             remove_stream(stream);
3694         } else {
3695             /* find all the AVStreams inside and reference them in
3696              * 'stream' */
3697             if (avformat_find_stream_info(infile, NULL) < 0) {
3698                 http_log("Could not find codec parameters from '%s'\n",
3699                          stream->feed_filename);
3700                 avformat_close_input(&infile);
3701                 goto fail;
3702             }
3703             extract_mpeg4_header(infile);
3704
3705             for(i=0;i<infile->nb_streams;i++)
3706                 add_av_stream1(stream, infile->streams[i]->codec, 1);
3707
3708             avformat_close_input(&infile);
3709         }
3710     }
3711 }
3712
3713 static inline
3714 int check_codec_match(AVStream *ccf, AVStream *ccs, int stream)
3715 {
3716     int matches = 1;
3717
3718 /* FIXME: Missed check on AVCodecContext.flags */
3719 #define CHECK_CODEC(x)  (ccf->codecpar->x != ccs->codecpar->x)
3720     if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3721         http_log("Codecs do not match for stream %d\n", stream);
3722         matches = 0;
3723     } else if (CHECK_CODEC(bit_rate)) {
3724         http_log("Codec bitrates do not match for stream %d\n", stream);
3725         matches = 0;
3726     } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3727         if (av_cmp_q(ccf->time_base, ccs->time_base) ||
3728             CHECK_CODEC(width) || CHECK_CODEC(height)) {
3729             http_log("Codec width, height or framerate do not match for stream %d\n", stream);
3730             matches = 0;
3731         }
3732     } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3733         if (CHECK_CODEC(sample_rate) ||
3734             CHECK_CODEC(channels) ||
3735             CHECK_CODEC(frame_size)) {
3736             http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
3737             matches = 0;
3738         }
3739     } else {
3740         http_log("Unknown codec type for stream %d\n", stream);
3741         matches = 0;
3742     }
3743
3744     return matches;
3745 }
3746
3747 /* compute the needed AVStream for each feed */
3748 static int build_feed_streams(void)
3749 {
3750     FFServerStream *stream, *feed;
3751     int i, fd;
3752
3753     /* gather all streams */
3754     for(stream = config.first_stream; stream; stream = stream->next) {
3755         feed = stream->feed;
3756         if (!feed)
3757             continue;
3758
3759         if (stream->is_feed) {
3760             for(i=0;i<stream->nb_streams;i++)
3761                 stream->feed_streams[i] = i;
3762             continue;
3763         }
3764         /* we handle a stream coming from a feed */
3765         for(i=0;i<stream->nb_streams;i++)
3766             stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3767     }
3768
3769     /* create feed files if needed */
3770     for(feed = config.first_feed; feed; feed = feed->next_feed) {
3771
3772         if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
3773             AVFormatContext *s = NULL;
3774             int matches = 0;
3775
3776             /* See if it matches */
3777
3778             if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
3779                 http_log("Deleting feed file '%s' as it appears "
3780                             "to be corrupt\n",
3781                          feed->feed_filename);
3782                 goto drop;
3783             }
3784
3785             /* set buffer size */
3786             if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
3787                 http_log("Failed to set buffer size\n");
3788                 avformat_close_input(&s);
3789                 goto bail;
3790             }
3791
3792             /* Now see if it matches */
3793             if (s->nb_streams != feed->nb_streams) {
3794                 http_log("Deleting feed file '%s' as stream counts "
3795                             "differ (%d != %d)\n",
3796                          feed->feed_filename, s->nb_streams, feed->nb_streams);
3797                 goto drop;
3798             }
3799
3800             matches = 1;
3801             for(i=0;i<s->nb_streams;i++) {
3802                 AVStream *sf, *ss;
3803
3804                 sf = feed->streams[i];
3805                 ss = s->streams[i];
3806
3807                 if (sf->index != ss->index || sf->id != ss->id) {
3808                     http_log("Index & Id do not match for stream %d (%s)\n",
3809                              i, feed->feed_filename);
3810                     matches = 0;
3811                     break;
3812                 }
3813
3814                 matches = check_codec_match (sf, ss, i);
3815                 if (!matches)
3816                     break;
3817             }
3818
3819 drop:
3820             if (s)
3821                 avformat_close_input(&s);
3822
3823             if (!matches) {
3824                 if (feed->readonly) {
3825                     http_log("Unable to delete read-only feed file '%s'\n",
3826                              feed->feed_filename);
3827                     goto bail;
3828                 }
3829                 unlink(feed->feed_filename);
3830             }
3831         }
3832
3833         if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
3834             AVFormatContext *s = avformat_alloc_context();
3835
3836             if (!s) {
3837                 http_log("Failed to allocate context\n");
3838                 goto bail;
3839             }
3840
3841             if (feed->readonly) {
3842                 http_log("Unable to create feed file '%s' as it is "
3843                             "marked readonly\n",
3844                          feed->feed_filename);
3845                 avformat_free_context(s);
3846                 goto bail;
3847             }
3848
3849             /* only write the header of the ffm file */
3850             if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
3851                 http_log("Could not open output feed file '%s'\n",
3852                          feed->feed_filename);
3853                 avformat_free_context(s);
3854                 goto bail;
3855             }
3856             s->oformat = feed->fmt;
3857             s->nb_streams = feed->nb_streams;
3858             s->streams = feed->streams;
3859             if (avformat_write_header(s, NULL) < 0) {
3860                 http_log("Container doesn't support the required parameters\n");
3861                 avio_closep(&s->pb);
3862                 s->streams = NULL;
3863                 s->nb_streams = 0;
3864                 avformat_free_context(s);
3865                 goto bail;
3866             }
3867             /* XXX: need better API */
3868             av_freep(&s->priv_data);
3869             avio_closep(&s->pb);
3870             s->streams = NULL;
3871             s->nb_streams = 0;
3872             avformat_free_context(s);
3873         }
3874
3875         /* get feed size and write index */
3876         fd = open(feed->feed_filename, O_RDONLY);
3877         if (fd < 0) {
3878             http_log("Could not open output feed file '%s'\n",
3879                     feed->feed_filename);
3880             goto bail;
3881         }
3882
3883         feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
3884                                        FFM_PACKET_SIZE);
3885         feed->feed_size = lseek(fd, 0, SEEK_END);
3886         /* ensure that we do not wrap before the end of file */
3887         if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3888             feed->feed_max_size = feed->feed_size;
3889
3890         close(fd);
3891     }
3892     return 0;
3893
3894 bail:
3895     return -1;
3896 }
3897
3898 /* compute the bandwidth used by each stream */
3899 static void compute_bandwidth(void)
3900 {
3901     unsigned bandwidth;
3902     int i;
3903     FFServerStream *stream;
3904
3905     for(stream = config.first_stream; stream; stream = stream->next) {
3906         bandwidth = 0;
3907         for(i=0;i<stream->nb_streams;i++) {
3908             AVStream *st = stream->streams[i];
3909             switch(st->codec->codec_type) {
3910             case AVMEDIA_TYPE_AUDIO:
3911             case AVMEDIA_TYPE_VIDEO:
3912                 bandwidth += st->codec->bit_rate;
3913                 break;
3914             default:
3915                 break;
3916             }
3917         }
3918         stream->bandwidth = (bandwidth + 999) / 1000;
3919     }
3920 }
3921
3922 static void handle_child_exit(int sig)
3923 {
3924     pid_t pid;
3925     int status;
3926     time_t uptime;
3927
3928     while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3929         FFServerStream *feed;
3930
3931         for (feed = config.first_feed; feed; feed = feed->next) {
3932             if (feed->pid != pid)
3933                 continue;
3934
3935             uptime = time(0) - feed->pid_start;
3936             feed->pid = 0;
3937             fprintf(stderr,
3938                     "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
3939                         "seconds\n",
3940                     feed->filename, (int64_t) pid, status, (int64_t)uptime);
3941
3942             if (uptime < 30)
3943                 /* Turn off any more restarts */
3944                 ffserver_free_child_args(&feed->child_argv);
3945         }
3946     }
3947
3948     need_to_start_children = 1;
3949 }
3950
3951 static void opt_debug(void)
3952 {
3953     config.debug = 1;
3954     snprintf(config.logfilename, sizeof(config.logfilename), "-");
3955 }
3956
3957 void show_help_default(const char *opt, const char *arg)
3958 {
3959     printf("usage: ffserver [options]\n"
3960            "Hyper fast multi format Audio/Video streaming server\n");
3961     printf("\n");
3962     show_help_options(options, "Main options:", 0, 0, 0);
3963 }
3964
3965 static const OptionDef options[] = {
3966 #include "cmdutils_common_opts.h"
3967     { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
3968     { "d", 0, {(void*)opt_debug}, "enable debug mode" },
3969     { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
3970     { NULL },
3971 };
3972
3973 int main(int argc, char **argv)
3974 {
3975     struct sigaction sigact = { { 0 } };
3976     int cfg_parsed;
3977     int ret = EXIT_FAILURE;
3978
3979     init_dynload();
3980
3981     config.filename = av_strdup("/etc/ffserver.conf");
3982
3983     parse_loglevel(argc, argv, options);
3984     av_register_all();
3985     avformat_network_init();
3986
3987     show_banner(argc, argv, options);
3988
3989     my_program_name = argv[0];
3990
3991     parse_options(NULL, argc, argv, options, NULL);
3992
3993     unsetenv("http_proxy");             /* Kill the http_proxy */
3994
3995     av_lfg_init(&random_state, av_get_random_seed());
3996
3997     sigact.sa_handler = handle_child_exit;
3998     sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
3999     sigaction(SIGCHLD, &sigact, 0);
4000
4001     if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
4002         fprintf(stderr, "Error reading configuration file '%s': %s\n",
4003                 config.filename, av_err2str(cfg_parsed));
4004         goto bail;
4005     }
4006
4007     /* open log file if needed */
4008     if (config.logfilename[0] != '\0') {
4009         if (!strcmp(config.logfilename, "-"))
4010             logfile = stdout;
4011         else
4012             logfile = fopen(config.logfilename, "a");
4013         av_log_set_callback(http_av_log);
4014     }
4015
4016     build_file_streams();
4017
4018     if (build_feed_streams() < 0) {
4019         http_log("Could not setup feed streams\n");
4020         goto bail;
4021     }
4022
4023     compute_bandwidth();
4024
4025     /* signal init */
4026     signal(SIGPIPE, SIG_IGN);
4027
4028     if (http_server() < 0) {
4029         http_log("Could not start server\n");
4030         goto bail;
4031     }
4032
4033     ret=EXIT_SUCCESS;
4034
4035 bail:
4036     av_freep (&config.filename);
4037     avformat_network_deinit();
4038     return ret;
4039 }