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