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