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