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