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