2 * Multiple format streaming server
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #define _XOPEN_SOURCE 600
26 #define closesocket close
31 #include "libavformat/avformat.h"
32 #include "libavformat/network.h"
33 #include "libavformat/os_support.h"
34 #include "libavformat/rtpdec.h"
35 #include "libavformat/rtsp.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/lfg.h"
38 #include "libavutil/random_seed.h"
39 #include "libavcodec/opt.h"
43 #include <sys/ioctl.h>
58 const char program_name[] = "FFserver";
59 const int program_birth_year = 2000;
61 static const OptionDef options[];
64 HTTPSTATE_WAIT_REQUEST,
65 HTTPSTATE_SEND_HEADER,
66 HTTPSTATE_SEND_DATA_HEADER,
67 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
68 HTTPSTATE_SEND_DATA_TRAILER,
69 HTTPSTATE_RECEIVE_DATA,
70 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
73 RTSPSTATE_WAIT_REQUEST,
75 RTSPSTATE_SEND_PACKET,
78 static const char *http_state[] = {
94 #define IOBUFFER_INIT_SIZE 8192
96 /* timeouts are in ms */
97 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
98 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
100 #define SYNC_TIMEOUT (10 * 1000)
102 typedef struct RTSPActionServerSetup {
104 char transport_option[512];
105 } RTSPActionServerSetup;
108 int64_t count1, count2;
109 int64_t time1, time2;
112 /* context associated with one connection */
113 typedef struct HTTPContext {
114 enum HTTPState state;
115 int fd; /* socket file descriptor */
116 struct sockaddr_in from_addr; /* origin */
117 struct pollfd *poll_entry; /* used when polling */
119 uint8_t *buffer_ptr, *buffer_end;
122 int chunked_encoding;
123 int chunk_size; /* 0 if it needs to be read */
124 struct HTTPContext *next;
125 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
129 /* input format handling */
130 AVFormatContext *fmt_in;
131 int64_t start_time; /* In milliseconds - this wraps fairly often */
132 int64_t first_pts; /* initial pts value */
133 int64_t cur_pts; /* current pts value from the stream in us */
134 int64_t cur_frame_duration; /* duration of the current frame in us */
135 int cur_frame_bytes; /* output frame size, needed to compute
136 the time at which we send each
138 int pts_stream_index; /* stream we choose as clock reference */
139 int64_t cur_clock; /* current clock reference value in us */
140 /* output format handling */
141 struct FFStream *stream;
142 /* -1 is invalid stream */
143 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
144 int switch_feed_streams[MAX_STREAMS]; /* index of streams in the feed */
146 AVFormatContext fmt_ctx; /* instance of FFStream for one user */
147 int last_packet_sent; /* true if last data packet was sent */
149 DataRateData datarate;
156 int is_packetized; /* if true, the stream is packetized */
157 int packet_stream_index; /* current stream for output in state machine */
159 /* RTSP state specific */
160 uint8_t *pb_buffer; /* XXX: use that in all the code */
162 int seq; /* RTSP sequence number */
164 /* RTP state specific */
165 enum RTSPLowerTransport rtp_protocol;
166 char session_id[32]; /* session id */
167 AVFormatContext *rtp_ctx[MAX_STREAMS];
169 /* RTP/UDP specific */
170 URLContext *rtp_handles[MAX_STREAMS];
172 /* RTP/TCP specific */
173 struct HTTPContext *rtsp_c;
174 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
177 /* each generated stream is described here */
181 STREAM_TYPE_REDIRECT,
184 enum IPAddressAction {
189 typedef struct IPAddressACL {
190 struct IPAddressACL *next;
191 enum IPAddressAction action;
192 /* These are in host order */
193 struct in_addr first;
197 /* description of each stream of the ffserver.conf file */
198 typedef struct FFStream {
199 enum StreamType stream_type;
200 char filename[1024]; /* stream filename */
201 struct FFStream *feed; /* feed we are using (can be null if
203 AVFormatParameters *ap_in; /* input parameters */
204 AVInputFormat *ifmt; /* if non NULL, force input format */
207 char dynamic_acl[1024];
209 int prebuffer; /* Number of millseconds early to start */
210 int64_t max_time; /* Number of milliseconds to run */
212 AVStream *streams[MAX_STREAMS];
213 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
214 char feed_filename[1024]; /* file name of the feed storage, or
215 input file name for a stream */
220 pid_t pid; /* Of ffmpeg process */
221 time_t pid_start; /* Of ffmpeg process */
223 struct FFStream *next;
224 unsigned bandwidth; /* bandwidth, in kbits/s */
227 /* multicast specific */
229 struct in_addr multicast_ip;
230 int multicast_port; /* first port used for multicast */
232 int loop; /* if true, send the stream in loops (only meaningful if file) */
235 int feed_opened; /* true if someone is writing to the feed */
236 int is_feed; /* true if it is a feed */
237 int readonly; /* True if writing is prohibited to the file */
238 int truncate; /* True if feeder connection truncate the feed file */
240 int64_t bytes_served;
241 int64_t feed_max_size; /* maximum storage size, zero means unlimited */
242 int64_t feed_write_index; /* current write position in feed (it wraps around) */
243 int64_t feed_size; /* current size of feed */
244 struct FFStream *next_feed;
247 typedef struct FeedData {
248 long long data_count;
249 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
252 static struct sockaddr_in my_http_addr;
253 static struct sockaddr_in my_rtsp_addr;
255 static char logfilename[1024];
256 static HTTPContext *first_http_ctx;
257 static FFStream *first_feed; /* contains only feeds */
258 static FFStream *first_stream; /* contains all streams, including feeds */
260 static void new_connection(int server_fd, int is_rtsp);
261 static void close_connection(HTTPContext *c);
264 static int handle_connection(HTTPContext *c);
265 static int http_parse_request(HTTPContext *c);
266 static int http_send_data(HTTPContext *c);
267 static void compute_status(HTTPContext *c);
268 static int open_input_stream(HTTPContext *c, const char *info);
269 static int http_start_receive_data(HTTPContext *c);
270 static int http_receive_data(HTTPContext *c);
273 static int rtsp_parse_request(HTTPContext *c);
274 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
275 static void rtsp_cmd_options(HTTPContext *c, const char *url);
276 static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPMessageHeader *h);
277 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h);
278 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h);
279 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h);
282 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
283 struct in_addr my_ip);
286 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
287 FFStream *stream, const char *session_id,
288 enum RTSPLowerTransport rtp_protocol);
289 static int rtp_new_av_stream(HTTPContext *c,
290 int stream_index, struct sockaddr_in *dest_addr,
291 HTTPContext *rtsp_c);
293 static const char *my_program_name;
294 static const char *my_program_dir;
296 static const char *config_filename;
297 static int ffserver_debug;
298 static int ffserver_daemon;
299 static int no_launch;
300 static int need_to_start_children;
302 /* maximum number of simultaneous HTTP connections */
303 static unsigned int nb_max_http_connections = 2000;
304 static unsigned int nb_max_connections = 5;
305 static unsigned int nb_connections;
307 static uint64_t max_bandwidth = 1000;
308 static uint64_t current_bandwidth;
310 static int64_t cur_time; // Making this global saves on passing it around everywhere
312 static AVLFG random_state;
314 static FILE *logfile = NULL;
316 /* FIXME: make ffserver work with IPv6 */
317 /* resolve host with also IP address parsing */
318 static int resolve_host(struct in_addr *sin_addr, const char *hostname)
321 if (!ff_inet_aton(hostname, sin_addr)) {
323 struct addrinfo *ai, *cur;
324 struct addrinfo hints;
325 memset(&hints, 0, sizeof(hints));
326 hints.ai_family = AF_INET;
327 if (getaddrinfo(hostname, NULL, &hints, &ai))
329 /* getaddrinfo returns a linked list of addrinfo structs.
330 * Even if we set ai_family = AF_INET above, make sure
331 * that the returned one actually is of the correct type. */
332 for (cur = ai; cur; cur = cur->ai_next) {
333 if (cur->ai_family == AF_INET) {
334 *sin_addr = ((struct sockaddr_in *)cur->ai_addr)->sin_addr;
343 hp = gethostbyname(hostname);
346 memcpy(sin_addr, hp->h_addr_list[0], sizeof(struct in_addr));
352 static char *ctime1(char *buf2)
360 p = buf2 + strlen(p) - 1;
366 static void http_vlog(const char *fmt, va_list vargs)
368 static int print_prefix = 1;
373 fprintf(logfile, "%s ", buf);
375 print_prefix = strstr(fmt, "\n") != NULL;
376 vfprintf(logfile, fmt, vargs);
381 static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
384 va_start(vargs, fmt);
385 http_vlog(fmt, vargs);
389 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
391 static int print_prefix = 1;
392 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
393 if (level > av_log_get_level())
395 if (print_prefix && avc)
396 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
397 print_prefix = strstr(fmt, "\n") != NULL;
398 http_vlog(fmt, vargs);
401 static void log_connection(HTTPContext *c)
406 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
407 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
408 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
411 static void update_datarate(DataRateData *drd, int64_t count)
413 if (!drd->time1 && !drd->count1) {
414 drd->time1 = drd->time2 = cur_time;
415 drd->count1 = drd->count2 = count;
416 } else if (cur_time - drd->time2 > 5000) {
417 drd->time1 = drd->time2;
418 drd->count1 = drd->count2;
419 drd->time2 = cur_time;
424 /* In bytes per second */
425 static int compute_datarate(DataRateData *drd, int64_t count)
427 if (cur_time == drd->time1)
430 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
434 static void start_children(FFStream *feed)
439 for (; feed; feed = feed->next) {
440 if (feed->child_argv && !feed->pid) {
441 feed->pid_start = time(0);
446 http_log("Unable to create children\n");
455 av_strlcpy(pathname, my_program_name, sizeof(pathname));
457 slash = strrchr(pathname, '/');
462 strcpy(slash, "ffmpeg");
464 http_log("Launch commandline: ");
465 http_log("%s ", pathname);
466 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
467 http_log("%s ", feed->child_argv[i]);
470 for (i = 3; i < 256; i++)
473 if (!ffserver_debug) {
474 i = open("/dev/null", O_RDWR);
483 /* This is needed to make relative pathnames work */
484 chdir(my_program_dir);
486 signal(SIGPIPE, SIG_DFL);
488 execvp(pathname, feed->child_argv);
496 /* open a listening socket */
497 static int socket_open_listen(struct sockaddr_in *my_addr)
501 server_fd = socket(AF_INET,SOCK_STREAM,0);
508 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
510 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
512 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
514 closesocket(server_fd);
518 if (listen (server_fd, 5) < 0) {
520 closesocket(server_fd);
523 ff_socket_nonblock(server_fd, 1);
528 /* start all multicast streams */
529 static void start_multicast(void)
534 struct sockaddr_in dest_addr;
535 int default_port, stream_index;
538 for(stream = first_stream; stream != NULL; stream = stream->next) {
539 if (stream->is_multicast) {
540 /* open the RTP connection */
541 snprintf(session_id, sizeof(session_id), "%08x%08x",
542 av_lfg_get(&random_state), av_lfg_get(&random_state));
544 /* choose a port if none given */
545 if (stream->multicast_port == 0) {
546 stream->multicast_port = default_port;
550 dest_addr.sin_family = AF_INET;
551 dest_addr.sin_addr = stream->multicast_ip;
552 dest_addr.sin_port = htons(stream->multicast_port);
554 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
555 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
559 if (open_input_stream(rtp_c, "") < 0) {
560 http_log("Could not open input stream for stream '%s'\n",
565 /* open each RTP stream */
566 for(stream_index = 0; stream_index < stream->nb_streams;
568 dest_addr.sin_port = htons(stream->multicast_port +
570 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
571 http_log("Could not open output stream '%s/streamid=%d'\n",
572 stream->filename, stream_index);
577 /* change state to send data */
578 rtp_c->state = HTTPSTATE_SEND_DATA;
583 /* main loop of the http server */
584 static int http_server(void)
586 int server_fd = 0, rtsp_server_fd = 0;
587 int ret, delay, delay1;
588 struct pollfd *poll_table, *poll_entry;
589 HTTPContext *c, *c_next;
591 if(!(poll_table = av_mallocz((nb_max_http_connections + 2)*sizeof(*poll_table)))) {
592 http_log("Impossible to allocate a poll table handling %d connections.\n", nb_max_http_connections);
596 if (my_http_addr.sin_port) {
597 server_fd = socket_open_listen(&my_http_addr);
602 if (my_rtsp_addr.sin_port) {
603 rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
604 if (rtsp_server_fd < 0)
608 if (!rtsp_server_fd && !server_fd) {
609 http_log("HTTP and RTSP disabled.\n");
613 http_log("FFserver started.\n");
615 start_children(first_feed);
620 poll_entry = poll_table;
622 poll_entry->fd = server_fd;
623 poll_entry->events = POLLIN;
626 if (rtsp_server_fd) {
627 poll_entry->fd = rtsp_server_fd;
628 poll_entry->events = POLLIN;
632 /* wait for events on each HTTP handle */
639 case HTTPSTATE_SEND_HEADER:
640 case RTSPSTATE_SEND_REPLY:
641 case RTSPSTATE_SEND_PACKET:
642 c->poll_entry = poll_entry;
644 poll_entry->events = POLLOUT;
647 case HTTPSTATE_SEND_DATA_HEADER:
648 case HTTPSTATE_SEND_DATA:
649 case HTTPSTATE_SEND_DATA_TRAILER:
650 if (!c->is_packetized) {
651 /* for TCP, we output as much as we can (may need to put a limit) */
652 c->poll_entry = poll_entry;
654 poll_entry->events = POLLOUT;
657 /* when ffserver is doing the timing, we work by
658 looking at which packet need to be sent every
660 delay1 = 10; /* one tick wait XXX: 10 ms assumed */
665 case HTTPSTATE_WAIT_REQUEST:
666 case HTTPSTATE_RECEIVE_DATA:
667 case HTTPSTATE_WAIT_FEED:
668 case RTSPSTATE_WAIT_REQUEST:
669 /* need to catch errors */
670 c->poll_entry = poll_entry;
672 poll_entry->events = POLLIN;/* Maybe this will work */
676 c->poll_entry = NULL;
682 /* wait for an event on one connection. We poll at least every
683 second to handle timeouts */
685 ret = poll(poll_table, poll_entry - poll_table, delay);
686 if (ret < 0 && ff_neterrno() != FF_NETERROR(EAGAIN) &&
687 ff_neterrno() != FF_NETERROR(EINTR))
691 cur_time = av_gettime() / 1000;
693 if (need_to_start_children) {
694 need_to_start_children = 0;
695 start_children(first_feed);
698 /* now handle the events */
699 for(c = first_http_ctx; c != NULL; c = c_next) {
701 if (handle_connection(c) < 0) {
702 /* close and free the connection */
708 poll_entry = poll_table;
710 /* new HTTP connection request ? */
711 if (poll_entry->revents & POLLIN)
712 new_connection(server_fd, 0);
715 if (rtsp_server_fd) {
716 /* new RTSP connection request ? */
717 if (poll_entry->revents & POLLIN)
718 new_connection(rtsp_server_fd, 1);
723 /* start waiting for a new HTTP/RTSP request */
724 static void start_wait_request(HTTPContext *c, int is_rtsp)
726 c->buffer_ptr = c->buffer;
727 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
730 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
731 c->state = RTSPSTATE_WAIT_REQUEST;
733 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
734 c->state = HTTPSTATE_WAIT_REQUEST;
738 static void http_send_too_busy_reply(int fd)
741 int len = snprintf(buffer, sizeof(buffer),
742 "HTTP/1.0 200 Server too busy\r\n"
743 "Content-type: text/html\r\n"
745 "<html><head><title>Too busy</title></head><body>\r\n"
746 "<p>The server is too busy to serve your request at this time.</p>\r\n"
747 "<p>The number of current connections is %d, and this exceeds the limit of %d.</p>\r\n"
748 "</body></html>\r\n",
749 nb_connections, nb_max_connections);
750 send(fd, buffer, len, 0);
754 static void new_connection(int server_fd, int is_rtsp)
756 struct sockaddr_in from_addr;
758 HTTPContext *c = NULL;
760 len = sizeof(from_addr);
761 fd = accept(server_fd, (struct sockaddr *)&from_addr,
764 http_log("error during accept %s\n", strerror(errno));
767 ff_socket_nonblock(fd, 1);
769 if (nb_connections >= nb_max_connections) {
770 http_send_too_busy_reply(fd);
774 /* add a new connection */
775 c = av_mallocz(sizeof(HTTPContext));
780 c->poll_entry = NULL;
781 c->from_addr = from_addr;
782 c->buffer_size = IOBUFFER_INIT_SIZE;
783 c->buffer = av_malloc(c->buffer_size);
787 c->next = first_http_ctx;
791 start_wait_request(c, is_rtsp);
803 static void close_connection(HTTPContext *c)
805 HTTPContext **cp, *c1;
807 AVFormatContext *ctx;
811 /* remove connection from list */
812 cp = &first_http_ctx;
813 while ((*cp) != NULL) {
821 /* remove references, if any (XXX: do it faster) */
822 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
827 /* remove connection associated resources */
831 /* close each frame parser */
832 for(i=0;i<c->fmt_in->nb_streams;i++) {
833 st = c->fmt_in->streams[i];
834 if (st->codec->codec)
835 avcodec_close(st->codec);
837 av_close_input_file(c->fmt_in);
840 /* free RTP output streams if any */
843 nb_streams = c->stream->nb_streams;
845 for(i=0;i<nb_streams;i++) {
848 av_write_trailer(ctx);
851 h = c->rtp_handles[i];
858 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
861 if (url_open_dyn_buf(&ctx->pb) >= 0) {
862 av_write_trailer(ctx);
863 av_freep(&c->pb_buffer);
864 url_close_dyn_buf(ctx->pb, &c->pb_buffer);
869 for(i=0; i<ctx->nb_streams; i++)
870 av_free(ctx->streams[i]);
872 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
873 current_bandwidth -= c->stream->bandwidth;
875 /* signal that there is no feed if we are the feeder socket */
876 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
877 c->stream->feed_opened = 0;
881 av_freep(&c->pb_buffer);
882 av_freep(&c->packet_buffer);
888 static int handle_connection(HTTPContext *c)
893 case HTTPSTATE_WAIT_REQUEST:
894 case RTSPSTATE_WAIT_REQUEST:
896 if ((c->timeout - cur_time) < 0)
898 if (c->poll_entry->revents & (POLLERR | POLLHUP))
901 /* no need to read if no events */
902 if (!(c->poll_entry->revents & POLLIN))
906 len = recv(c->fd, c->buffer_ptr, 1, 0);
908 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
909 ff_neterrno() != FF_NETERROR(EINTR))
911 } else if (len == 0) {
914 /* search for end of request. */
916 c->buffer_ptr += len;
918 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
919 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
920 /* request found : parse it and reply */
921 if (c->state == HTTPSTATE_WAIT_REQUEST) {
922 ret = http_parse_request(c);
924 ret = rtsp_parse_request(c);
928 } else if (ptr >= c->buffer_end) {
929 /* request too long: cannot do anything */
931 } else goto read_loop;
935 case HTTPSTATE_SEND_HEADER:
936 if (c->poll_entry->revents & (POLLERR | POLLHUP))
939 /* no need to write if no events */
940 if (!(c->poll_entry->revents & POLLOUT))
942 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
944 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
945 ff_neterrno() != FF_NETERROR(EINTR)) {
946 /* error : close connection */
947 av_freep(&c->pb_buffer);
951 c->buffer_ptr += len;
953 c->stream->bytes_served += len;
954 c->data_count += len;
955 if (c->buffer_ptr >= c->buffer_end) {
956 av_freep(&c->pb_buffer);
960 /* all the buffer was sent : synchronize to the incoming stream */
961 c->state = HTTPSTATE_SEND_DATA_HEADER;
962 c->buffer_ptr = c->buffer_end = c->buffer;
967 case HTTPSTATE_SEND_DATA:
968 case HTTPSTATE_SEND_DATA_HEADER:
969 case HTTPSTATE_SEND_DATA_TRAILER:
970 /* for packetized output, we consider we can always write (the
971 input streams sets the speed). It may be better to verify
972 that we do not rely too much on the kernel queues */
973 if (!c->is_packetized) {
974 if (c->poll_entry->revents & (POLLERR | POLLHUP))
977 /* no need to read if no events */
978 if (!(c->poll_entry->revents & POLLOUT))
981 if (http_send_data(c) < 0)
983 /* close connection if trailer sent */
984 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
987 case HTTPSTATE_RECEIVE_DATA:
988 /* no need to read if no events */
989 if (c->poll_entry->revents & (POLLERR | POLLHUP))
991 if (!(c->poll_entry->revents & POLLIN))
993 if (http_receive_data(c) < 0)
996 case HTTPSTATE_WAIT_FEED:
997 /* no need to read if no events */
998 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1001 /* nothing to do, we'll be waken up by incoming feed packets */
1004 case RTSPSTATE_SEND_REPLY:
1005 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1006 av_freep(&c->pb_buffer);
1009 /* no need to write if no events */
1010 if (!(c->poll_entry->revents & POLLOUT))
1012 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1014 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
1015 ff_neterrno() != FF_NETERROR(EINTR)) {
1016 /* error : close connection */
1017 av_freep(&c->pb_buffer);
1021 c->buffer_ptr += len;
1022 c->data_count += len;
1023 if (c->buffer_ptr >= c->buffer_end) {
1024 /* all the buffer was sent : wait for a new request */
1025 av_freep(&c->pb_buffer);
1026 start_wait_request(c, 1);
1030 case RTSPSTATE_SEND_PACKET:
1031 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1032 av_freep(&c->packet_buffer);
1035 /* no need to write if no events */
1036 if (!(c->poll_entry->revents & POLLOUT))
1038 len = send(c->fd, c->packet_buffer_ptr,
1039 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1041 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
1042 ff_neterrno() != FF_NETERROR(EINTR)) {
1043 /* error : close connection */
1044 av_freep(&c->packet_buffer);
1048 c->packet_buffer_ptr += len;
1049 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1050 /* all the buffer was sent : wait for a new request */
1051 av_freep(&c->packet_buffer);
1052 c->state = RTSPSTATE_WAIT_REQUEST;
1056 case HTTPSTATE_READY:
1065 static int extract_rates(char *rates, int ratelen, const char *request)
1069 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1070 if (strncasecmp(p, "Pragma:", 7) == 0) {
1071 const char *q = p + 7;
1073 while (*q && *q != '\n' && isspace(*q))
1076 if (strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1082 memset(rates, 0xff, ratelen);
1085 while (*q && *q != '\n' && *q != ':')
1088 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1092 if (stream_no < ratelen && stream_no >= 0)
1093 rates[stream_no] = rate_no;
1095 while (*q && *q != '\n' && !isspace(*q))
1102 p = strchr(p, '\n');
1112 static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
1115 int best_bitrate = 100000000;
1118 for (i = 0; i < feed->nb_streams; i++) {
1119 AVCodecContext *feed_codec = feed->streams[i]->codec;
1121 if (feed_codec->codec_id != codec->codec_id ||
1122 feed_codec->sample_rate != codec->sample_rate ||
1123 feed_codec->width != codec->width ||
1124 feed_codec->height != codec->height)
1127 /* Potential stream */
1129 /* We want the fastest stream less than bit_rate, or the slowest
1130 * faster than bit_rate
1133 if (feed_codec->bit_rate <= bit_rate) {
1134 if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
1135 best_bitrate = feed_codec->bit_rate;
1139 if (feed_codec->bit_rate < best_bitrate) {
1140 best_bitrate = feed_codec->bit_rate;
1149 static int modify_current_stream(HTTPContext *c, char *rates)
1152 FFStream *req = c->stream;
1153 int action_required = 0;
1155 /* Not much we can do for a feed */
1159 for (i = 0; i < req->nb_streams; i++) {
1160 AVCodecContext *codec = req->streams[i]->codec;
1164 c->switch_feed_streams[i] = req->feed_streams[i];
1167 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1170 /* Wants off or slow */
1171 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1173 /* This doesn't work well when it turns off the only stream! */
1174 c->switch_feed_streams[i] = -2;
1175 c->feed_streams[i] = -2;
1180 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1181 action_required = 1;
1184 return action_required;
1188 static void do_switch_stream(HTTPContext *c, int i)
1190 if (c->switch_feed_streams[i] >= 0) {
1192 c->feed_streams[i] = c->switch_feed_streams[i];
1195 /* Now update the stream */
1197 c->switch_feed_streams[i] = -1;
1200 /* XXX: factorize in utils.c ? */
1201 /* XXX: take care with different space meaning */
1202 static void skip_spaces(const char **pp)
1206 while (*p == ' ' || *p == '\t')
1211 static void get_word(char *buf, int buf_size, const char **pp)
1219 while (!isspace(*p) && *p != '\0') {
1220 if ((q - buf) < buf_size - 1)
1229 static void get_arg(char *buf, int buf_size, const char **pp)
1236 while (isspace(*p)) p++;
1239 if (*p == '\"' || *p == '\'')
1251 if ((q - buf) < buf_size - 1)
1256 if (quote && *p == quote)
1261 static void parse_acl_row(FFStream *stream, FFStream* feed, IPAddressACL *ext_acl,
1262 const char *p, const char *filename, int line_num)
1268 get_arg(arg, sizeof(arg), &p);
1269 if (strcasecmp(arg, "allow") == 0)
1270 acl.action = IP_ALLOW;
1271 else if (strcasecmp(arg, "deny") == 0)
1272 acl.action = IP_DENY;
1274 fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
1275 filename, line_num, arg);
1279 get_arg(arg, sizeof(arg), &p);
1281 if (resolve_host(&acl.first, arg) != 0) {
1282 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
1283 filename, line_num, arg);
1286 acl.last = acl.first;
1288 get_arg(arg, sizeof(arg), &p);
1291 if (resolve_host(&acl.last, arg) != 0) {
1292 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
1293 filename, line_num, arg);
1299 IPAddressACL *nacl = av_mallocz(sizeof(*nacl));
1300 IPAddressACL **naclp = 0;
1306 naclp = &stream->acl;
1312 fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n",
1313 filename, line_num);
1319 naclp = &(*naclp)->next;
1327 static IPAddressACL* parse_dynamic_acl(FFStream *stream, HTTPContext *c)
1332 IPAddressACL *acl = NULL;
1336 f = fopen(stream->dynamic_acl, "r");
1338 perror(stream->dynamic_acl);
1342 acl = av_mallocz(sizeof(IPAddressACL));
1346 if (fgets(line, sizeof(line), f) == NULL)
1352 if (*p == '\0' || *p == '#')
1354 get_arg(cmd, sizeof(cmd), &p);
1356 if (!strcasecmp(cmd, "ACL"))
1357 parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl, line_num);
1364 static void free_acl_list(IPAddressACL *in_acl)
1366 IPAddressACL *pacl,*pacl2;
1376 static int validate_acl_list(IPAddressACL *in_acl, HTTPContext *c)
1378 enum IPAddressAction last_action = IP_DENY;
1380 struct in_addr *src = &c->from_addr.sin_addr;
1381 unsigned long src_addr = src->s_addr;
1383 for (acl = in_acl; acl; acl = acl->next) {
1384 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1385 return (acl->action == IP_ALLOW) ? 1 : 0;
1386 last_action = acl->action;
1389 /* Nothing matched, so return not the last action */
1390 return (last_action == IP_DENY) ? 1 : 0;
1393 static int validate_acl(FFStream *stream, HTTPContext *c)
1399 /* if stream->acl is null validate_acl_list will return 1 */
1400 ret = validate_acl_list(stream->acl, c);
1402 if (stream->dynamic_acl[0]) {
1403 acl = parse_dynamic_acl(stream, c);
1405 ret = validate_acl_list(acl, c);
1413 /* compute the real filename of a file by matching it without its
1414 extensions to all the stream filenames */
1415 static void compute_real_filename(char *filename, int max_size)
1422 /* compute filename by matching without the file extensions */
1423 av_strlcpy(file1, filename, sizeof(file1));
1424 p = strrchr(file1, '.');
1427 for(stream = first_stream; stream != NULL; stream = stream->next) {
1428 av_strlcpy(file2, stream->filename, sizeof(file2));
1429 p = strrchr(file2, '.');
1432 if (!strcmp(file1, file2)) {
1433 av_strlcpy(filename, stream->filename, max_size);
1448 /* parse http request and prepare header */
1449 static int http_parse_request(HTTPContext *c)
1452 enum RedirType redir_type;
1454 char info[1024], filename[1024];
1458 const char *mime_type;
1462 char *useragent = 0;
1465 get_word(cmd, sizeof(cmd), (const char **)&p);
1466 av_strlcpy(c->method, cmd, sizeof(c->method));
1468 if (!strcmp(cmd, "GET"))
1470 else if (!strcmp(cmd, "POST"))
1475 get_word(url, sizeof(url), (const char **)&p);
1476 av_strlcpy(c->url, url, sizeof(c->url));
1478 get_word(protocol, sizeof(protocol), (const char **)&p);
1479 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1482 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1485 http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);
1487 /* find the filename and the optional info string in the request */
1488 p = strchr(url, '?');
1490 av_strlcpy(info, p, sizeof(info));
1495 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1497 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1498 if (strncasecmp(p, "User-Agent:", 11) == 0) {
1500 if (*useragent && *useragent != '\n' && isspace(*useragent))
1504 p = strchr(p, '\n');
1511 redir_type = REDIR_NONE;
1512 if (av_match_ext(filename, "asx")) {
1513 redir_type = REDIR_ASX;
1514 filename[strlen(filename)-1] = 'f';
1515 } else if (av_match_ext(filename, "asf") &&
1516 (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1517 /* if this isn't WMP or lookalike, return the redirector file */
1518 redir_type = REDIR_ASF;
1519 } else if (av_match_ext(filename, "rpm,ram")) {
1520 redir_type = REDIR_RAM;
1521 strcpy(filename + strlen(filename)-2, "m");
1522 } else if (av_match_ext(filename, "rtsp")) {
1523 redir_type = REDIR_RTSP;
1524 compute_real_filename(filename, sizeof(filename) - 1);
1525 } else if (av_match_ext(filename, "sdp")) {
1526 redir_type = REDIR_SDP;
1527 compute_real_filename(filename, sizeof(filename) - 1);
1530 // "redirect" / request to index.html
1531 if (!strlen(filename))
1532 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1534 stream = first_stream;
1535 while (stream != NULL) {
1536 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1538 stream = stream->next;
1540 if (stream == NULL) {
1541 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1542 http_log("File '%s' not found\n", url);
1547 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1548 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1550 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1551 c->http_error = 301;
1553 q += snprintf(q, c->buffer_size,
1554 "HTTP/1.0 301 Moved\r\n"
1556 "Content-type: text/html\r\n"
1558 "<html><head><title>Moved</title></head><body>\r\n"
1559 "You should be <a href=\"%s\">redirected</a>.\r\n"
1560 "</body></html>\r\n", stream->feed_filename, stream->feed_filename);
1561 /* prepare output buffer */
1562 c->buffer_ptr = c->buffer;
1564 c->state = HTTPSTATE_SEND_HEADER;
1568 /* If this is WMP, get the rate information */
1569 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1570 if (modify_current_stream(c, ratebuf)) {
1571 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1572 if (c->switch_feed_streams[i] >= 0)
1573 do_switch_stream(c, i);
1578 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1579 current_bandwidth += stream->bandwidth;
1581 /* If already streaming this feed, do not let start another feeder. */
1582 if (stream->feed_opened) {
1583 snprintf(msg, sizeof(msg), "This feed is already being received.");
1584 http_log("Feed '%s' already being received\n", stream->feed_filename);
1588 if (c->post == 0 && max_bandwidth < current_bandwidth) {
1589 c->http_error = 200;
1591 q += snprintf(q, c->buffer_size,
1592 "HTTP/1.0 200 Server too busy\r\n"
1593 "Content-type: text/html\r\n"
1595 "<html><head><title>Too busy</title></head><body>\r\n"
1596 "<p>The server is too busy to serve your request at this time.</p>\r\n"
1597 "<p>The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "
1598 "and this exceeds the limit of %"PRIu64"kbit/sec.</p>\r\n"
1599 "</body></html>\r\n", current_bandwidth, max_bandwidth);
1600 /* prepare output buffer */
1601 c->buffer_ptr = c->buffer;
1603 c->state = HTTPSTATE_SEND_HEADER;
1607 if (redir_type != REDIR_NONE) {
1610 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1611 if (strncasecmp(p, "Host:", 5) == 0) {
1615 p = strchr(p, '\n');
1626 while (isspace(*hostinfo))
1629 eoh = strchr(hostinfo, '\n');
1631 if (eoh[-1] == '\r')
1634 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1635 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1636 hostbuf[eoh - hostinfo] = 0;
1638 c->http_error = 200;
1640 switch(redir_type) {
1642 q += snprintf(q, c->buffer_size,
1643 "HTTP/1.0 200 ASX Follows\r\n"
1644 "Content-type: video/x-ms-asf\r\n"
1646 "<ASX Version=\"3\">\r\n"
1647 //"<!-- Autogenerated by ffserver -->\r\n"
1648 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1649 "</ASX>\r\n", hostbuf, filename, info);
1652 q += snprintf(q, c->buffer_size,
1653 "HTTP/1.0 200 RAM Follows\r\n"
1654 "Content-type: audio/x-pn-realaudio\r\n"
1656 "# Autogenerated by ffserver\r\n"
1657 "http://%s/%s%s\r\n", hostbuf, filename, info);
1660 q += snprintf(q, c->buffer_size,
1661 "HTTP/1.0 200 ASF Redirect follows\r\n"
1662 "Content-type: video/x-ms-asf\r\n"
1665 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1669 char hostname[256], *p;
1670 /* extract only hostname */
1671 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1672 p = strrchr(hostname, ':');
1675 q += snprintf(q, c->buffer_size,
1676 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1677 /* XXX: incorrect mime type ? */
1678 "Content-type: application/x-rtsp\r\n"
1680 "rtsp://%s:%d/%s\r\n", hostname, ntohs(my_rtsp_addr.sin_port), filename);
1686 int sdp_data_size, len;
1687 struct sockaddr_in my_addr;
1689 q += snprintf(q, c->buffer_size,
1690 "HTTP/1.0 200 OK\r\n"
1691 "Content-type: application/sdp\r\n"
1694 len = sizeof(my_addr);
1695 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
1697 /* XXX: should use a dynamic buffer */
1698 sdp_data_size = prepare_sdp_description(stream,
1701 if (sdp_data_size > 0) {
1702 memcpy(q, sdp_data, sdp_data_size);
1714 /* prepare output buffer */
1715 c->buffer_ptr = c->buffer;
1717 c->state = HTTPSTATE_SEND_HEADER;
1723 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1727 stream->conns_served++;
1729 /* XXX: add there authenticate and IP match */
1732 /* if post, it means a feed is being sent */
1733 if (!stream->is_feed) {
1734 /* However it might be a status report from WMP! Let us log the
1735 * data as it might come in handy one day. */
1739 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1740 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1744 if (strncasecmp(p, "Pragma: client-id=", 18) == 0)
1745 client_id = strtol(p + 18, 0, 10);
1746 p = strchr(p, '\n');
1754 char *eol = strchr(logline, '\n');
1759 if (eol[-1] == '\r')
1761 http_log("%.*s\n", (int) (eol - logline), logline);
1762 c->suppress_log = 1;
1767 http_log("\nGot request:\n%s\n", c->buffer);
1770 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1773 /* Now we have to find the client_id */
1774 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1775 if (wmpc->wmp_client_id == client_id)
1779 if (wmpc && modify_current_stream(wmpc, ratebuf))
1780 wmpc->switch_pending = 1;
1783 snprintf(msg, sizeof(msg), "POST command not handled");
1787 if (http_start_receive_data(c) < 0) {
1788 snprintf(msg, sizeof(msg), "could not open feed");
1792 c->state = HTTPSTATE_RECEIVE_DATA;
1797 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1798 http_log("\nGot request:\n%s\n", c->buffer);
1801 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1804 /* open input stream */
1805 if (open_input_stream(c, info) < 0) {
1806 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1810 /* prepare http header */
1812 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
1813 mime_type = c->stream->fmt->mime_type;
1815 mime_type = "application/x-octet-stream";
1816 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Pragma: no-cache\r\n");
1818 /* for asf, we need extra headers */
1819 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1820 /* Need to allocate a client id */
1822 c->wmp_client_id = av_lfg_get(&random_state);
1824 q += snprintf(q, q - (char *) 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);
1826 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-Type: %s\r\n", mime_type);
1827 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1829 /* prepare output buffer */
1831 c->buffer_ptr = c->buffer;
1833 c->state = HTTPSTATE_SEND_HEADER;
1836 c->http_error = 404;
1838 q += snprintf(q, c->buffer_size,
1839 "HTTP/1.0 404 Not Found\r\n"
1840 "Content-type: text/html\r\n"
1843 "<head><title>404 Not Found</title></head>\n"
1846 /* prepare output buffer */
1847 c->buffer_ptr = c->buffer;
1849 c->state = HTTPSTATE_SEND_HEADER;
1853 c->http_error = 200; /* horrible : we use this value to avoid
1854 going to the send data state */
1855 c->state = HTTPSTATE_SEND_HEADER;
1859 static void fmt_bytecount(ByteIOContext *pb, int64_t count)
1861 static const char *suffix = " kMGTP";
1864 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1866 url_fprintf(pb, "%"PRId64"%c", count, *s);
1869 static void compute_status(HTTPContext *c)
1878 if (url_open_dyn_buf(&pb) < 0) {
1879 /* XXX: return an error ? */
1880 c->buffer_ptr = c->buffer;
1881 c->buffer_end = c->buffer;
1885 url_fprintf(pb, "HTTP/1.0 200 OK\r\n");
1886 url_fprintf(pb, "Content-type: %s\r\n", "text/html");
1887 url_fprintf(pb, "Pragma: no-cache\r\n");
1888 url_fprintf(pb, "\r\n");
1890 url_fprintf(pb, "<html><head><title>%s Status</title>\n", program_name);
1891 if (c->stream->feed_filename[0])
1892 url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
1893 url_fprintf(pb, "</head>\n<body>");
1894 url_fprintf(pb, "<h1>%s Status</h1>\n", program_name);
1896 url_fprintf(pb, "<h2>Available Streams</h2>\n");
1897 url_fprintf(pb, "<table cellspacing=0 cellpadding=4>\n");
1898 url_fprintf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbits/s<th align=left>Video<br>kbits/s<th><br>Codec<th align=left>Audio<br>kbits/s<th><br>Codec<th align=left valign=top>Feed\n");
1899 stream = first_stream;
1900 while (stream != NULL) {
1901 char sfilename[1024];
1904 if (stream->feed != stream) {
1905 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1906 eosf = sfilename + strlen(sfilename);
1907 if (eosf - sfilename >= 4) {
1908 if (strcmp(eosf - 4, ".asf") == 0)
1909 strcpy(eosf - 4, ".asx");
1910 else if (strcmp(eosf - 3, ".rm") == 0)
1911 strcpy(eosf - 3, ".ram");
1912 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1913 /* generate a sample RTSP director if
1914 unicast. Generate an SDP redirector if
1916 eosf = strrchr(sfilename, '.');
1918 eosf = sfilename + strlen(sfilename);
1919 if (stream->is_multicast)
1920 strcpy(eosf, ".sdp");
1922 strcpy(eosf, ".rtsp");
1926 url_fprintf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1927 sfilename, stream->filename);
1928 url_fprintf(pb, "<td align=right> %d <td align=right> ",
1929 stream->conns_served);
1930 fmt_bytecount(pb, stream->bytes_served);
1931 switch(stream->stream_type) {
1932 case STREAM_TYPE_LIVE: {
1933 int audio_bit_rate = 0;
1934 int video_bit_rate = 0;
1935 const char *audio_codec_name = "";
1936 const char *video_codec_name = "";
1937 const char *audio_codec_name_extra = "";
1938 const char *video_codec_name_extra = "";
1940 for(i=0;i<stream->nb_streams;i++) {
1941 AVStream *st = stream->streams[i];
1942 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1943 switch(st->codec->codec_type) {
1944 case AVMEDIA_TYPE_AUDIO:
1945 audio_bit_rate += st->codec->bit_rate;
1947 if (*audio_codec_name)
1948 audio_codec_name_extra = "...";
1949 audio_codec_name = codec->name;
1952 case AVMEDIA_TYPE_VIDEO:
1953 video_bit_rate += st->codec->bit_rate;
1955 if (*video_codec_name)
1956 video_codec_name_extra = "...";
1957 video_codec_name = codec->name;
1960 case AVMEDIA_TYPE_DATA:
1961 video_bit_rate += st->codec->bit_rate;
1967 url_fprintf(pb, "<td align=center> %s <td align=right> %d <td align=right> %d <td> %s %s <td align=right> %d <td> %s %s",
1970 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
1971 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
1973 url_fprintf(pb, "<td>%s", stream->feed->filename);
1975 url_fprintf(pb, "<td>%s", stream->feed_filename);
1976 url_fprintf(pb, "\n");
1980 url_fprintf(pb, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
1984 stream = stream->next;
1986 url_fprintf(pb, "</table>\n");
1988 stream = first_stream;
1989 while (stream != NULL) {
1990 if (stream->feed == stream) {
1991 url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
1993 url_fprintf(pb, "Running as pid %d.\n", stream->pid);
1995 #if defined(linux) && !defined(CONFIG_NOCUTILS)
2000 /* This is somewhat linux specific I guess */
2001 snprintf(ps_cmd, sizeof(ps_cmd),
2002 "ps -o \"%%cpu,cputime\" --no-headers %d",
2005 pid_stat = popen(ps_cmd, "r");
2010 if (fscanf(pid_stat, "%10s %64s", cpuperc,
2012 url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
2020 url_fprintf(pb, "<p>");
2022 url_fprintf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>type<th>kbits/s<th align=left>codec<th align=left>Parameters\n");
2024 for (i = 0; i < stream->nb_streams; i++) {
2025 AVStream *st = stream->streams[i];
2026 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
2027 const char *type = "unknown";
2028 char parameters[64];
2032 switch(st->codec->codec_type) {
2033 case AVMEDIA_TYPE_AUDIO:
2035 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz", st->codec->channels, st->codec->sample_rate);
2037 case AVMEDIA_TYPE_VIDEO:
2039 snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec->width, st->codec->height,
2040 st->codec->qmin, st->codec->qmax, st->codec->time_base.den / st->codec->time_base.num);
2045 url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
2046 i, type, st->codec->bit_rate/1000, codec ? codec->name : "", parameters);
2048 url_fprintf(pb, "</table>\n");
2051 stream = stream->next;
2054 /* connection status */
2055 url_fprintf(pb, "<h2>Connection Status</h2>\n");
2057 url_fprintf(pb, "Number of connections: %d / %d<br>\n",
2058 nb_connections, nb_max_connections);
2060 url_fprintf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2061 current_bandwidth, max_bandwidth);
2063 url_fprintf(pb, "<table>\n");
2064 url_fprintf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
2065 c1 = first_http_ctx;
2067 while (c1 != NULL) {
2073 for (j = 0; j < c1->stream->nb_streams; j++) {
2074 if (!c1->stream->feed)
2075 bitrate += c1->stream->streams[j]->codec->bit_rate;
2076 else if (c1->feed_streams[j] >= 0)
2077 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
2082 p = inet_ntoa(c1->from_addr.sin_addr);
2083 url_fprintf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
2085 c1->stream ? c1->stream->filename : "",
2086 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
2089 http_state[c1->state]);
2090 fmt_bytecount(pb, bitrate);
2091 url_fprintf(pb, "<td align=right>");
2092 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2093 url_fprintf(pb, "<td align=right>");
2094 fmt_bytecount(pb, c1->data_count);
2095 url_fprintf(pb, "\n");
2098 url_fprintf(pb, "</table>\n");
2103 url_fprintf(pb, "<hr size=1 noshade>Generated at %s", p);
2104 url_fprintf(pb, "</body>\n</html>\n");
2106 len = url_close_dyn_buf(pb, &c->pb_buffer);
2107 c->buffer_ptr = c->pb_buffer;
2108 c->buffer_end = c->pb_buffer + len;
2111 /* check if the parser needs to be opened for stream i */
2112 static void open_parser(AVFormatContext *s, int i)
2114 AVStream *st = s->streams[i];
2117 if (!st->codec->codec) {
2118 codec = avcodec_find_decoder(st->codec->codec_id);
2119 if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) {
2120 st->codec->parse_only = 1;
2121 if (avcodec_open(st->codec, codec) < 0)
2122 st->codec->parse_only = 0;
2127 static int open_input_stream(HTTPContext *c, const char *info)
2130 char input_filename[1024];
2132 int buf_size, i, ret;
2135 /* find file name */
2136 if (c->stream->feed) {
2137 strcpy(input_filename, c->stream->feed->feed_filename);
2138 buf_size = FFM_PACKET_SIZE;
2139 /* compute position (absolute time) */
2140 if (find_info_tag(buf, sizeof(buf), "date", info)) {
2141 stream_pos = parse_date(buf, 0);
2142 if (stream_pos == INT64_MIN)
2144 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
2145 int prebuffer = strtol(buf, 0, 10);
2146 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2148 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2150 strcpy(input_filename, c->stream->feed_filename);
2152 /* compute position (relative time) */
2153 if (find_info_tag(buf, sizeof(buf), "date", info)) {
2154 stream_pos = parse_date(buf, 1);
2155 if (stream_pos == INT64_MIN)
2160 if (input_filename[0] == '\0')
2164 if ((ret = av_open_input_file(&s, input_filename, c->stream->ifmt,
2165 buf_size, c->stream->ap_in)) < 0) {
2166 http_log("could not open %s: %d\n", input_filename, ret);
2169 s->flags |= AVFMT_FLAG_GENPTS;
2171 if (strcmp(s->iformat->name, "ffm") && av_find_stream_info(c->fmt_in) < 0) {
2172 http_log("Could not find stream info '%s'\n", input_filename);
2173 av_close_input_file(s);
2177 /* open each parser */
2178 for(i=0;i<s->nb_streams;i++)
2181 /* choose stream as clock source (we favorize video stream if
2182 present) for packet sending */
2183 c->pts_stream_index = 0;
2184 for(i=0;i<c->stream->nb_streams;i++) {
2185 if (c->pts_stream_index == 0 &&
2186 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2187 c->pts_stream_index = i;
2192 if (c->fmt_in->iformat->read_seek)
2193 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2195 /* set the start time (needed for maxtime and RTP packet timing) */
2196 c->start_time = cur_time;
2197 c->first_pts = AV_NOPTS_VALUE;
2201 /* return the server clock (in us) */
2202 static int64_t get_server_clock(HTTPContext *c)
2204 /* compute current pts value from system time */
2205 return (cur_time - c->start_time) * 1000;
2208 /* return the estimated time at which the current packet must be sent
2210 static int64_t get_packet_send_clock(HTTPContext *c)
2212 int bytes_left, bytes_sent, frame_bytes;
2214 frame_bytes = c->cur_frame_bytes;
2215 if (frame_bytes <= 0)
2218 bytes_left = c->buffer_end - c->buffer_ptr;
2219 bytes_sent = frame_bytes - bytes_left;
2220 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2225 static int http_prepare_data(HTTPContext *c)
2228 AVFormatContext *ctx;
2230 av_freep(&c->pb_buffer);
2232 case HTTPSTATE_SEND_DATA_HEADER:
2233 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
2234 av_metadata_set(&c->fmt_ctx.metadata, "author" ,c->stream->author);
2235 av_metadata_set(&c->fmt_ctx.metadata, "comment" ,c->stream->comment);
2236 av_metadata_set(&c->fmt_ctx.metadata, "copyright",c->stream->copyright);
2237 av_metadata_set(&c->fmt_ctx.metadata, "title" ,c->stream->title);
2239 for(i=0;i<c->stream->nb_streams;i++) {
2242 st = av_mallocz(sizeof(AVStream));
2243 c->fmt_ctx.streams[i] = st;
2244 /* if file or feed, then just take streams from FFStream struct */
2245 if (!c->stream->feed ||
2246 c->stream->feed == c->stream)
2247 src = c->stream->streams[i];
2249 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2253 st->codec->frame_number = 0; /* XXX: should be done in
2254 AVStream, not in codec */
2256 /* set output format parameters */
2257 c->fmt_ctx.oformat = c->stream->fmt;
2258 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2260 c->got_key_frame = 0;
2262 /* prepare header and save header data in a stream */
2263 if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2264 /* XXX: potential leak */
2267 c->fmt_ctx.pb->is_streamed = 1;
2270 * HACK to avoid mpeg ps muxer to spit many underflow errors
2271 * Default value from FFmpeg
2272 * Try to set it use configuration option
2274 c->fmt_ctx.preload = (int)(0.5*AV_TIME_BASE);
2275 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2277 av_set_parameters(&c->fmt_ctx, NULL);
2278 if (av_write_header(&c->fmt_ctx) < 0) {
2279 http_log("Error writing output header\n");
2283 len = url_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2284 c->buffer_ptr = c->pb_buffer;
2285 c->buffer_end = c->pb_buffer + len;
2287 c->state = HTTPSTATE_SEND_DATA;
2288 c->last_packet_sent = 0;
2290 case HTTPSTATE_SEND_DATA:
2291 /* find a new packet */
2292 /* read a packet from the input stream */
2293 if (c->stream->feed)
2294 ffm_set_write_index(c->fmt_in,
2295 c->stream->feed->feed_write_index,
2296 c->stream->feed->feed_size);
2298 if (c->stream->max_time &&
2299 c->stream->max_time + c->start_time - cur_time < 0)
2300 /* We have timed out */
2301 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2305 if (av_read_frame(c->fmt_in, &pkt) < 0) {
2306 if (c->stream->feed && c->stream->feed->feed_opened) {
2307 /* if coming from feed, it means we reached the end of the
2308 ffm file, so must wait for more data */
2309 c->state = HTTPSTATE_WAIT_FEED;
2310 return 1; /* state changed */
2312 if (c->stream->loop) {
2313 av_close_input_file(c->fmt_in);
2315 if (open_input_stream(c, "") < 0)
2320 /* must send trailer now because eof or error */
2321 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2325 int source_index = pkt.stream_index;
2326 /* update first pts if needed */
2327 if (c->first_pts == AV_NOPTS_VALUE) {
2328 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2329 c->start_time = cur_time;
2331 /* send it to the appropriate stream */
2332 if (c->stream->feed) {
2333 /* if coming from a feed, select the right stream */
2334 if (c->switch_pending) {
2335 c->switch_pending = 0;
2336 for(i=0;i<c->stream->nb_streams;i++) {
2337 if (c->switch_feed_streams[i] == pkt.stream_index)
2338 if (pkt.flags & AV_PKT_FLAG_KEY)
2339 do_switch_stream(c, i);
2340 if (c->switch_feed_streams[i] >= 0)
2341 c->switch_pending = 1;
2344 for(i=0;i<c->stream->nb_streams;i++) {
2345 if (c->feed_streams[i] == pkt.stream_index) {
2346 AVStream *st = c->fmt_in->streams[source_index];
2347 pkt.stream_index = i;
2348 if (pkt.flags & AV_PKT_FLAG_KEY &&
2349 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2350 c->stream->nb_streams == 1))
2351 c->got_key_frame = 1;
2352 if (!c->stream->send_on_key || c->got_key_frame)
2357 AVCodecContext *codec;
2358 AVStream *ist, *ost;
2360 ist = c->fmt_in->streams[source_index];
2361 /* specific handling for RTP: we use several
2362 output stream (one for each RTP
2363 connection). XXX: need more abstract handling */
2364 if (c->is_packetized) {
2365 /* compute send time and duration */
2366 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2367 if (ist->start_time != AV_NOPTS_VALUE)
2368 c->cur_pts -= av_rescale_q(ist->start_time, ist->time_base, AV_TIME_BASE_Q);
2369 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2370 /* find RTP context */
2371 c->packet_stream_index = pkt.stream_index;
2372 ctx = c->rtp_ctx[c->packet_stream_index];
2374 av_free_packet(&pkt);
2377 codec = ctx->streams[0]->codec;
2378 /* only one stream per RTP connection */
2379 pkt.stream_index = 0;
2383 codec = ctx->streams[pkt.stream_index]->codec;
2386 if (c->is_packetized) {
2387 int max_packet_size;
2388 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2389 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2391 max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]);
2392 ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size);
2394 ret = url_open_dyn_buf(&ctx->pb);
2397 /* XXX: potential leak */
2400 ost = ctx->streams[pkt.stream_index];
2402 ctx->pb->is_streamed = 1;
2403 if (pkt.dts != AV_NOPTS_VALUE)
2404 pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base);
2405 if (pkt.pts != AV_NOPTS_VALUE)
2406 pkt.pts = av_rescale_q(pkt.pts, ist->time_base, ost->time_base);
2407 pkt.duration = av_rescale_q(pkt.duration, ist->time_base, ost->time_base);
2408 if (av_write_frame(ctx, &pkt) < 0) {
2409 http_log("Error writing frame to output\n");
2410 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2413 len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
2414 c->cur_frame_bytes = len;
2415 c->buffer_ptr = c->pb_buffer;
2416 c->buffer_end = c->pb_buffer + len;
2418 codec->frame_number++;
2420 av_free_packet(&pkt);
2424 av_free_packet(&pkt);
2429 case HTTPSTATE_SEND_DATA_TRAILER:
2430 /* last packet test ? */
2431 if (c->last_packet_sent || c->is_packetized)
2434 /* prepare header */
2435 if (url_open_dyn_buf(&ctx->pb) < 0) {
2436 /* XXX: potential leak */
2439 c->fmt_ctx.pb->is_streamed = 1;
2440 av_write_trailer(ctx);
2441 len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
2442 c->buffer_ptr = c->pb_buffer;
2443 c->buffer_end = c->pb_buffer + len;
2445 c->last_packet_sent = 1;
2451 /* should convert the format at the same time */
2452 /* send data starting at c->buffer_ptr to the output connection
2453 (either UDP or TCP connection) */
2454 static int http_send_data(HTTPContext *c)
2459 if (c->buffer_ptr >= c->buffer_end) {
2460 ret = http_prepare_data(c);
2464 /* state change requested */
2467 if (c->is_packetized) {
2468 /* RTP data output */
2469 len = c->buffer_end - c->buffer_ptr;
2471 /* fail safe - should never happen */
2473 c->buffer_ptr = c->buffer_end;
2476 len = (c->buffer_ptr[0] << 24) |
2477 (c->buffer_ptr[1] << 16) |
2478 (c->buffer_ptr[2] << 8) |
2480 if (len > (c->buffer_end - c->buffer_ptr))
2482 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2483 /* nothing to send yet: we can wait */
2487 c->data_count += len;
2488 update_datarate(&c->datarate, c->data_count);
2490 c->stream->bytes_served += len;
2492 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2493 /* RTP packets are sent inside the RTSP TCP connection */
2495 int interleaved_index, size;
2497 HTTPContext *rtsp_c;
2500 /* if no RTSP connection left, error */
2503 /* if already sending something, then wait. */
2504 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2506 if (url_open_dyn_buf(&pb) < 0)
2508 interleaved_index = c->packet_stream_index * 2;
2509 /* RTCP packets are sent at odd indexes */
2510 if (c->buffer_ptr[1] == 200)
2511 interleaved_index++;
2512 /* write RTSP TCP header */
2514 header[1] = interleaved_index;
2515 header[2] = len >> 8;
2517 put_buffer(pb, header, 4);
2518 /* write RTP packet data */
2520 put_buffer(pb, c->buffer_ptr, len);
2521 size = url_close_dyn_buf(pb, &c->packet_buffer);
2522 /* prepare asynchronous TCP sending */
2523 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2524 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2525 c->buffer_ptr += len;
2527 /* send everything we can NOW */
2528 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2529 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2531 rtsp_c->packet_buffer_ptr += len;
2532 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2533 /* if we could not send all the data, we will
2534 send it later, so a new state is needed to
2535 "lock" the RTSP TCP connection */
2536 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2539 /* all data has been sent */
2540 av_freep(&c->packet_buffer);
2542 /* send RTP packet directly in UDP */
2544 url_write(c->rtp_handles[c->packet_stream_index],
2545 c->buffer_ptr, len);
2546 c->buffer_ptr += len;
2547 /* here we continue as we can send several packets per 10 ms slot */
2550 /* TCP data output */
2551 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
2553 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2554 ff_neterrno() != FF_NETERROR(EINTR))
2555 /* error : close connection */
2560 c->buffer_ptr += len;
2562 c->data_count += len;
2563 update_datarate(&c->datarate, c->data_count);
2565 c->stream->bytes_served += len;
2573 static int http_start_receive_data(HTTPContext *c)
2577 if (c->stream->feed_opened)
2580 /* Don't permit writing to this one */
2581 if (c->stream->readonly)
2585 fd = open(c->stream->feed_filename, O_RDWR);
2587 http_log("Error opening feeder file: %s\n", strerror(errno));
2592 if (c->stream->truncate) {
2593 /* truncate feed file */
2594 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2595 ftruncate(c->feed_fd, FFM_PACKET_SIZE);
2596 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2598 if ((c->stream->feed_write_index = ffm_read_write_index(fd)) < 0) {
2599 http_log("Error reading write index from feed file: %s\n", strerror(errno));
2604 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
2605 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2606 lseek(fd, 0, SEEK_SET);
2608 /* init buffer input */
2609 c->buffer_ptr = c->buffer;
2610 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2611 c->stream->feed_opened = 1;
2612 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2616 static int http_receive_data(HTTPContext *c)
2619 int len, loop_run = 0;
2621 while (c->chunked_encoding && !c->chunk_size &&
2622 c->buffer_end > c->buffer_ptr) {
2623 /* read chunk header, if present */
2624 len = recv(c->fd, c->buffer_ptr, 1, 0);
2627 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2628 ff_neterrno() != FF_NETERROR(EINTR))
2629 /* error : close connection */
2631 } else if (len == 0) {
2632 /* end of connection : close it */
2634 } else if (c->buffer_ptr - c->buffer >= 2 &&
2635 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2636 c->chunk_size = strtol(c->buffer, 0, 16);
2637 if (c->chunk_size == 0) // end of stream
2639 c->buffer_ptr = c->buffer;
2641 } else if (++loop_run > 10) {
2642 /* no chunk header, abort */
2649 if (c->buffer_end > c->buffer_ptr) {
2650 len = recv(c->fd, c->buffer_ptr,
2651 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2653 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2654 ff_neterrno() != FF_NETERROR(EINTR))
2655 /* error : close connection */
2657 } else if (len == 0)
2658 /* end of connection : close it */
2661 c->chunk_size -= len;
2662 c->buffer_ptr += len;
2663 c->data_count += len;
2664 update_datarate(&c->datarate, c->data_count);
2668 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2669 if (c->buffer[0] != 'f' ||
2670 c->buffer[1] != 'm') {
2671 http_log("Feed stream has become desynchronized -- disconnecting\n");
2676 if (c->buffer_ptr >= c->buffer_end) {
2677 FFStream *feed = c->stream;
2678 /* a packet has been received : write it in the store, except
2680 if (c->data_count > FFM_PACKET_SIZE) {
2682 // printf("writing pos=0x%"PRIx64" size=0x%"PRIx64"\n", feed->feed_write_index, feed->feed_size);
2683 /* XXX: use llseek or url_seek */
2684 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
2685 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2686 http_log("Error writing to feed file: %s\n", strerror(errno));
2690 feed->feed_write_index += FFM_PACKET_SIZE;
2691 /* update file size */
2692 if (feed->feed_write_index > c->stream->feed_size)
2693 feed->feed_size = feed->feed_write_index;
2695 /* handle wrap around if max file size reached */
2696 if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size)
2697 feed->feed_write_index = FFM_PACKET_SIZE;
2700 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2701 http_log("Error writing index to feed file: %s\n", strerror(errno));
2705 /* wake up any waiting connections */
2706 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2707 if (c1->state == HTTPSTATE_WAIT_FEED &&
2708 c1->stream->feed == c->stream->feed)
2709 c1->state = HTTPSTATE_SEND_DATA;
2712 /* We have a header in our hands that contains useful data */
2713 AVFormatContext *s = NULL;
2715 AVInputFormat *fmt_in;
2718 /* use feed output format name to find corresponding input format */
2719 fmt_in = av_find_input_format(feed->fmt->name);
2723 url_open_buf(&pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
2724 pb->is_streamed = 1;
2726 if (av_open_input_stream(&s, pb, c->stream->feed_filename, fmt_in, NULL) < 0) {
2731 /* Now we have the actual streams */
2732 if (s->nb_streams != feed->nb_streams) {
2733 av_close_input_stream(s);
2735 http_log("Feed '%s' stream number does not match registered feed\n",
2736 c->stream->feed_filename);
2740 for (i = 0; i < s->nb_streams; i++) {
2741 AVStream *fst = feed->streams[i];
2742 AVStream *st = s->streams[i];
2743 memcpy(fst->codec, st->codec, sizeof(AVCodecContext));
2744 if (fst->codec->extradata_size) {
2745 fst->codec->extradata = av_malloc(fst->codec->extradata_size);
2746 if (!fst->codec->extradata)
2748 memcpy(fst->codec->extradata, st->codec->extradata,
2749 fst->codec->extradata_size);
2753 av_close_input_stream(s);
2756 c->buffer_ptr = c->buffer;
2761 c->stream->feed_opened = 0;
2763 /* wake up any waiting connections to stop waiting for feed */
2764 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2765 if (c1->state == HTTPSTATE_WAIT_FEED &&
2766 c1->stream->feed == c->stream->feed)
2767 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2772 /********************************************************************/
2775 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2782 switch(error_number) {
2783 case RTSP_STATUS_OK:
2786 case RTSP_STATUS_METHOD:
2787 str = "Method Not Allowed";
2789 case RTSP_STATUS_BANDWIDTH:
2790 str = "Not Enough Bandwidth";
2792 case RTSP_STATUS_SESSION:
2793 str = "Session Not Found";
2795 case RTSP_STATUS_STATE:
2796 str = "Method Not Valid in This State";
2798 case RTSP_STATUS_AGGREGATE:
2799 str = "Aggregate operation not allowed";
2801 case RTSP_STATUS_ONLY_AGGREGATE:
2802 str = "Only aggregate operation allowed";
2804 case RTSP_STATUS_TRANSPORT:
2805 str = "Unsupported transport";
2807 case RTSP_STATUS_INTERNAL:
2808 str = "Internal Server Error";
2810 case RTSP_STATUS_SERVICE:
2811 str = "Service Unavailable";
2813 case RTSP_STATUS_VERSION:
2814 str = "RTSP Version not supported";
2817 str = "Unknown Error";
2821 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2822 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2824 /* output GMT time */
2828 p = buf2 + strlen(p) - 1;
2831 url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
2834 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2836 rtsp_reply_header(c, error_number);
2837 url_fprintf(c->pb, "\r\n");
2840 static int rtsp_parse_request(HTTPContext *c)
2842 const char *p, *p1, *p2;
2848 RTSPMessageHeader header1, *header = &header1;
2850 c->buffer_ptr[0] = '\0';
2853 get_word(cmd, sizeof(cmd), &p);
2854 get_word(url, sizeof(url), &p);
2855 get_word(protocol, sizeof(protocol), &p);
2857 av_strlcpy(c->method, cmd, sizeof(c->method));
2858 av_strlcpy(c->url, url, sizeof(c->url));
2859 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2861 if (url_open_dyn_buf(&c->pb) < 0) {
2862 /* XXX: cannot do more */
2863 c->pb = NULL; /* safety */
2867 /* check version name */
2868 if (strcmp(protocol, "RTSP/1.0") != 0) {
2869 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2873 /* parse each header line */
2874 memset(header, 0, sizeof(*header));
2875 /* skip to next line */
2876 while (*p != '\n' && *p != '\0')
2880 while (*p != '\0') {
2881 p1 = strchr(p, '\n');
2885 if (p2 > p && p2[-1] == '\r')
2887 /* skip empty line */
2891 if (len > sizeof(line) - 1)
2892 len = sizeof(line) - 1;
2893 memcpy(line, p, len);
2895 ff_rtsp_parse_line(header, line, NULL);
2899 /* handle sequence number */
2900 c->seq = header->seq;
2902 if (!strcmp(cmd, "DESCRIBE"))
2903 rtsp_cmd_describe(c, url);
2904 else if (!strcmp(cmd, "OPTIONS"))
2905 rtsp_cmd_options(c, url);
2906 else if (!strcmp(cmd, "SETUP"))
2907 rtsp_cmd_setup(c, url, header);
2908 else if (!strcmp(cmd, "PLAY"))
2909 rtsp_cmd_play(c, url, header);
2910 else if (!strcmp(cmd, "PAUSE"))
2911 rtsp_cmd_pause(c, url, header);
2912 else if (!strcmp(cmd, "TEARDOWN"))
2913 rtsp_cmd_teardown(c, url, header);
2915 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2918 len = url_close_dyn_buf(c->pb, &c->pb_buffer);
2919 c->pb = NULL; /* safety */
2921 /* XXX: cannot do more */
2924 c->buffer_ptr = c->pb_buffer;
2925 c->buffer_end = c->pb_buffer + len;
2926 c->state = RTSPSTATE_SEND_REPLY;
2930 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
2931 struct in_addr my_ip)
2933 AVFormatContext *avc;
2934 AVStream avs[MAX_STREAMS];
2937 avc = avformat_alloc_context();
2941 av_metadata_set(&avc->metadata, "title",
2942 stream->title[0] ? stream->title : "No Title");
2943 avc->nb_streams = stream->nb_streams;
2944 if (stream->is_multicast) {
2945 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2946 inet_ntoa(stream->multicast_ip),
2947 stream->multicast_port, stream->multicast_ttl);
2950 for(i = 0; i < stream->nb_streams; i++) {
2951 avc->streams[i] = &avs[i];
2952 avc->streams[i]->codec = stream->streams[i]->codec;
2954 *pbuffer = av_mallocz(2048);
2955 avf_sdp_create(&avc, 1, *pbuffer, 2048);
2958 return strlen(*pbuffer);
2961 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2963 // rtsp_reply_header(c, RTSP_STATUS_OK);
2964 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2965 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2966 url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2967 url_fprintf(c->pb, "\r\n");
2970 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2976 int content_length, len;
2977 struct sockaddr_in my_addr;
2979 /* find which url is asked */
2980 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2985 for(stream = first_stream; stream != NULL; stream = stream->next) {
2986 if (!stream->is_feed &&
2987 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
2988 !strcmp(path, stream->filename)) {
2992 /* no stream found */
2993 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2997 /* prepare the media description in sdp format */
2999 /* get the host IP */
3000 len = sizeof(my_addr);
3001 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3002 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
3003 if (content_length < 0) {
3004 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3007 rtsp_reply_header(c, RTSP_STATUS_OK);
3008 url_fprintf(c->pb, "Content-Type: application/sdp\r\n");
3009 url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);
3010 url_fprintf(c->pb, "\r\n");
3011 put_buffer(c->pb, content, content_length);
3014 static HTTPContext *find_rtp_session(const char *session_id)
3018 if (session_id[0] == '\0')
3021 for(c = first_http_ctx; c != NULL; c = c->next) {
3022 if (!strcmp(c->session_id, session_id))
3028 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3030 RTSPTransportField *th;
3033 for(i=0;i<h->nb_transports;i++) {
3034 th = &h->transports[i];
3035 if (th->lower_transport == lower_transport)
3041 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3042 RTSPMessageHeader *h)
3045 int stream_index, port;
3050 RTSPTransportField *th;
3051 struct sockaddr_in dest_addr;
3052 RTSPActionServerSetup setup;
3054 /* find which url is asked */
3055 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3060 /* now check each stream */
3061 for(stream = first_stream; stream != NULL; stream = stream->next) {
3062 if (!stream->is_feed &&
3063 stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3064 /* accept aggregate filenames only if single stream */
3065 if (!strcmp(path, stream->filename)) {
3066 if (stream->nb_streams != 1) {
3067 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3074 for(stream_index = 0; stream_index < stream->nb_streams;
3076 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3077 stream->filename, stream_index);
3078 if (!strcmp(path, buf))
3083 /* no stream found */
3084 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3088 /* generate session id if needed */
3089 if (h->session_id[0] == '\0')
3090 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3091 av_lfg_get(&random_state), av_lfg_get(&random_state));
3093 /* find rtp session, and create it if none found */
3094 rtp_c = find_rtp_session(h->session_id);
3096 /* always prefer UDP */
3097 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3099 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3101 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3106 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3107 th->lower_transport);
3109 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3113 /* open input stream */
3114 if (open_input_stream(rtp_c, "") < 0) {
3115 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3120 /* test if stream is OK (test needed because several SETUP needs
3121 to be done for a given file) */
3122 if (rtp_c->stream != stream) {
3123 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3127 /* test if stream is already set up */
3128 if (rtp_c->rtp_ctx[stream_index]) {
3129 rtsp_reply_error(c, RTSP_STATUS_STATE);
3133 /* check transport */
3134 th = find_transport(h, rtp_c->rtp_protocol);
3135 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3136 th->client_port_min <= 0)) {
3137 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3141 /* setup default options */
3142 setup.transport_option[0] = '\0';
3143 dest_addr = rtp_c->from_addr;
3144 dest_addr.sin_port = htons(th->client_port_min);
3147 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3148 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3152 /* now everything is OK, so we can send the connection parameters */
3153 rtsp_reply_header(c, RTSP_STATUS_OK);
3155 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3157 switch(rtp_c->rtp_protocol) {
3158 case RTSP_LOWER_TRANSPORT_UDP:
3159 port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]);
3160 url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3161 "client_port=%d-%d;server_port=%d-%d",
3162 th->client_port_min, th->client_port_min + 1,
3165 case RTSP_LOWER_TRANSPORT_TCP:
3166 url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3167 stream_index * 2, stream_index * 2 + 1);
3172 if (setup.transport_option[0] != '\0')
3173 url_fprintf(c->pb, ";%s", setup.transport_option);
3174 url_fprintf(c->pb, "\r\n");
3177 url_fprintf(c->pb, "\r\n");
3181 /* find an rtp connection by using the session ID. Check consistency
3183 static HTTPContext *find_rtp_session_with_url(const char *url,
3184 const char *session_id)
3192 rtp_c = find_rtp_session(session_id);
3196 /* find which url is asked */
3197 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3201 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3202 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3203 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3204 rtp_c->stream->filename, s);
3205 if(!strncmp(path, buf, sizeof(buf))) {
3206 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
3213 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3217 rtp_c = find_rtp_session_with_url(url, h->session_id);
3219 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3223 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3224 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3225 rtp_c->state != HTTPSTATE_READY) {
3226 rtsp_reply_error(c, RTSP_STATUS_STATE);
3230 rtp_c->state = HTTPSTATE_SEND_DATA;
3232 /* now everything is OK, so we can send the connection parameters */
3233 rtsp_reply_header(c, RTSP_STATUS_OK);
3235 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3236 url_fprintf(c->pb, "\r\n");
3239 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3243 rtp_c = find_rtp_session_with_url(url, h->session_id);
3245 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3249 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3250 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3251 rtsp_reply_error(c, RTSP_STATUS_STATE);
3255 rtp_c->state = HTTPSTATE_READY;
3256 rtp_c->first_pts = AV_NOPTS_VALUE;
3257 /* now everything is OK, so we can send the connection parameters */
3258 rtsp_reply_header(c, RTSP_STATUS_OK);
3260 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3261 url_fprintf(c->pb, "\r\n");
3264 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3267 char session_id[32];
3269 rtp_c = find_rtp_session_with_url(url, h->session_id);
3271 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3275 av_strlcpy(session_id, rtp_c->session_id, sizeof(session_id));
3277 /* abort the session */
3278 close_connection(rtp_c);
3280 /* now everything is OK, so we can send the connection parameters */
3281 rtsp_reply_header(c, RTSP_STATUS_OK);
3283 url_fprintf(c->pb, "Session: %s\r\n", session_id);
3284 url_fprintf(c->pb, "\r\n");
3288 /********************************************************************/
3291 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3292 FFStream *stream, const char *session_id,
3293 enum RTSPLowerTransport rtp_protocol)
3295 HTTPContext *c = NULL;
3296 const char *proto_str;
3298 /* XXX: should output a warning page when coming
3299 close to the connection limit */
3300 if (nb_connections >= nb_max_connections)
3303 /* add a new connection */
3304 c = av_mallocz(sizeof(HTTPContext));
3309 c->poll_entry = NULL;
3310 c->from_addr = *from_addr;
3311 c->buffer_size = IOBUFFER_INIT_SIZE;
3312 c->buffer = av_malloc(c->buffer_size);
3317 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3318 c->state = HTTPSTATE_READY;
3319 c->is_packetized = 1;
3320 c->rtp_protocol = rtp_protocol;
3322 /* protocol is shown in statistics */
3323 switch(c->rtp_protocol) {
3324 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3325 proto_str = "MCAST";
3327 case RTSP_LOWER_TRANSPORT_UDP:
3330 case RTSP_LOWER_TRANSPORT_TCP:
3337 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3338 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3340 current_bandwidth += stream->bandwidth;
3342 c->next = first_http_ctx;
3354 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3355 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3357 static int rtp_new_av_stream(HTTPContext *c,
3358 int stream_index, struct sockaddr_in *dest_addr,
3359 HTTPContext *rtsp_c)
3361 AVFormatContext *ctx;
3364 URLContext *h = NULL;
3366 int max_packet_size;
3368 /* now we can open the relevant output stream */
3369 ctx = avformat_alloc_context();
3372 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3374 st = av_mallocz(sizeof(AVStream));
3377 st->codec= avcodec_alloc_context();
3378 ctx->nb_streams = 1;
3379 ctx->streams[0] = st;
3381 if (!c->stream->feed ||
3382 c->stream->feed == c->stream)
3383 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3386 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3388 st->priv_data = NULL;
3390 /* build destination RTP address */
3391 ipaddr = inet_ntoa(dest_addr->sin_addr);
3393 switch(c->rtp_protocol) {
3394 case RTSP_LOWER_TRANSPORT_UDP:
3395 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3398 /* XXX: also pass as parameter to function ? */
3399 if (c->stream->is_multicast) {
3401 ttl = c->stream->multicast_ttl;
3404 snprintf(ctx->filename, sizeof(ctx->filename),
3405 "rtp://%s:%d?multicast=1&ttl=%d",
3406 ipaddr, ntohs(dest_addr->sin_port), ttl);
3408 snprintf(ctx->filename, sizeof(ctx->filename),
3409 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3412 if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
3414 c->rtp_handles[stream_index] = h;
3415 max_packet_size = url_get_max_packet_size(h);
3417 case RTSP_LOWER_TRANSPORT_TCP:
3420 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3426 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3427 ipaddr, ntohs(dest_addr->sin_port),
3428 c->stream->filename, stream_index, c->protocol);
3430 /* normally, no packets should be output here, but the packet size may be checked */
3431 if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
3432 /* XXX: close stream */
3435 av_set_parameters(ctx, NULL);
3436 if (av_write_header(ctx) < 0) {
3443 url_close_dyn_buf(ctx->pb, &dummy_buf);
3446 c->rtp_ctx[stream_index] = ctx;
3450 /********************************************************************/
3451 /* ffserver initialization */
3453 static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
3457 fst = av_mallocz(sizeof(AVStream));
3460 fst->codec= avcodec_alloc_context();
3461 fst->priv_data = av_mallocz(sizeof(FeedData));
3462 memcpy(fst->codec, codec, sizeof(AVCodecContext));
3463 fst->index = stream->nb_streams;
3464 av_set_pts_info(fst, 33, 1, 90000);
3465 stream->streams[stream->nb_streams++] = fst;
3469 /* return the stream number in the feed */
3470 static int add_av_stream(FFStream *feed, AVStream *st)
3473 AVCodecContext *av, *av1;
3477 for(i=0;i<feed->nb_streams;i++) {
3478 st = feed->streams[i];
3480 if (av1->codec_id == av->codec_id &&
3481 av1->codec_type == av->codec_type &&
3482 av1->bit_rate == av->bit_rate) {
3484 switch(av->codec_type) {
3485 case AVMEDIA_TYPE_AUDIO:
3486 if (av1->channels == av->channels &&
3487 av1->sample_rate == av->sample_rate)
3490 case AVMEDIA_TYPE_VIDEO:
3491 if (av1->width == av->width &&
3492 av1->height == av->height &&
3493 av1->time_base.den == av->time_base.den &&
3494 av1->time_base.num == av->time_base.num &&
3495 av1->gop_size == av->gop_size)
3504 fst = add_av_stream1(feed, av);
3507 return feed->nb_streams - 1;
3512 static void remove_stream(FFStream *stream)
3516 while (*ps != NULL) {
3524 /* specific mpeg4 handling : we extract the raw parameters */
3525 static void extract_mpeg4_header(AVFormatContext *infile)
3527 int mpeg4_count, i, size;
3533 for(i=0;i<infile->nb_streams;i++) {
3534 st = infile->streams[i];
3535 if (st->codec->codec_id == CODEC_ID_MPEG4 &&
3536 st->codec->extradata_size == 0) {
3543 printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
3544 while (mpeg4_count > 0) {
3545 if (av_read_packet(infile, &pkt) < 0)
3547 st = infile->streams[pkt.stream_index];
3548 if (st->codec->codec_id == CODEC_ID_MPEG4 &&
3549 st->codec->extradata_size == 0) {
3550 av_freep(&st->codec->extradata);
3551 /* fill extradata with the header */
3552 /* XXX: we make hard suppositions here ! */
3554 while (p < pkt.data + pkt.size - 4) {
3555 /* stop when vop header is found */
3556 if (p[0] == 0x00 && p[1] == 0x00 &&
3557 p[2] == 0x01 && p[3] == 0xb6) {
3558 size = p - pkt.data;
3559 // av_hex_dump_log(infile, AV_LOG_DEBUG, pkt.data, size);
3560 st->codec->extradata = av_malloc(size);
3561 st->codec->extradata_size = size;
3562 memcpy(st->codec->extradata, pkt.data, size);
3569 av_free_packet(&pkt);
3573 /* compute the needed AVStream for each file */
3574 static void build_file_streams(void)
3576 FFStream *stream, *stream_next;
3577 AVFormatContext *infile;
3580 /* gather all streams */
3581 for(stream = first_stream; stream != NULL; stream = stream_next) {
3582 stream_next = stream->next;
3583 if (stream->stream_type == STREAM_TYPE_LIVE &&
3585 /* the stream comes from a file */
3586 /* try to open the file */
3588 stream->ap_in = av_mallocz(sizeof(AVFormatParameters));
3589 if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3590 /* specific case : if transport stream output to RTP,
3591 we use a raw transport stream reader */
3592 stream->ap_in->mpeg2ts_raw = 1;
3593 stream->ap_in->mpeg2ts_compute_pcr = 1;
3596 http_log("Opening file '%s'\n", stream->feed_filename);
3597 if ((ret = av_open_input_file(&infile, stream->feed_filename,
3598 stream->ifmt, 0, stream->ap_in)) < 0) {
3599 http_log("Could not open '%s': %d\n", stream->feed_filename, ret);
3600 /* remove stream (no need to spend more time on it) */
3602 remove_stream(stream);
3604 /* find all the AVStreams inside and reference them in
3606 if (av_find_stream_info(infile) < 0) {
3607 http_log("Could not find codec parameters from '%s'\n",
3608 stream->feed_filename);
3609 av_close_input_file(infile);
3612 extract_mpeg4_header(infile);
3614 for(i=0;i<infile->nb_streams;i++)
3615 add_av_stream1(stream, infile->streams[i]->codec);
3617 av_close_input_file(infile);
3623 /* compute the needed AVStream for each feed */
3624 static void build_feed_streams(void)
3626 FFStream *stream, *feed;
3629 /* gather all streams */
3630 for(stream = first_stream; stream != NULL; stream = stream->next) {
3631 feed = stream->feed;
3633 if (!stream->is_feed) {
3634 /* we handle a stream coming from a feed */
3635 for(i=0;i<stream->nb_streams;i++)
3636 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3641 /* gather all streams */
3642 for(stream = first_stream; stream != NULL; stream = stream->next) {
3643 feed = stream->feed;
3645 if (stream->is_feed) {
3646 for(i=0;i<stream->nb_streams;i++)
3647 stream->feed_streams[i] = i;
3652 /* create feed files if needed */
3653 for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
3656 if (url_exist(feed->feed_filename)) {
3657 /* See if it matches */
3661 if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) {
3662 /* Now see if it matches */
3663 if (s->nb_streams == feed->nb_streams) {
3665 for(i=0;i<s->nb_streams;i++) {
3667 sf = feed->streams[i];
3670 if (sf->index != ss->index ||
3672 http_log("Index & Id do not match for stream %d (%s)\n",
3673 i, feed->feed_filename);
3676 AVCodecContext *ccf, *ccs;
3680 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3682 if (CHECK_CODEC(codec) || CHECK_CODEC(codec_type)) {
3683 http_log("Codecs do not match for stream %d\n", i);
3685 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3686 http_log("Codec bitrates do not match for stream %d\n", i);
3688 } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
3689 if (CHECK_CODEC(time_base.den) ||
3690 CHECK_CODEC(time_base.num) ||
3691 CHECK_CODEC(width) ||
3692 CHECK_CODEC(height)) {
3693 http_log("Codec width, height and framerate do not match for stream %d\n", i);
3696 } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
3697 if (CHECK_CODEC(sample_rate) ||
3698 CHECK_CODEC(channels) ||
3699 CHECK_CODEC(frame_size)) {
3700 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3704 http_log("Unknown codec type\n");
3712 http_log("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3713 feed->feed_filename, s->nb_streams, feed->nb_streams);
3715 av_close_input_file(s);
3717 http_log("Deleting feed file '%s' as it appears to be corrupt\n",
3718 feed->feed_filename);
3721 if (feed->readonly) {
3722 http_log("Unable to delete feed file '%s' as it is marked readonly\n",
3723 feed->feed_filename);
3726 unlink(feed->feed_filename);
3729 if (!url_exist(feed->feed_filename)) {
3730 AVFormatContext s1 = {0}, *s = &s1;
3732 if (feed->readonly) {
3733 http_log("Unable to create feed file '%s' as it is marked readonly\n",
3734 feed->feed_filename);
3738 /* only write the header of the ffm file */
3739 if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
3740 http_log("Could not open output feed file '%s'\n",
3741 feed->feed_filename);
3744 s->oformat = feed->fmt;
3745 s->nb_streams = feed->nb_streams;
3746 for(i=0;i<s->nb_streams;i++) {
3748 st = feed->streams[i];
3751 av_set_parameters(s, NULL);
3752 if (av_write_header(s) < 0) {
3753 http_log("Container doesn't supports the required parameters\n");
3756 /* XXX: need better api */
3757 av_freep(&s->priv_data);
3760 /* get feed size and write index */
3761 fd = open(feed->feed_filename, O_RDONLY);
3763 http_log("Could not open output feed file '%s'\n",
3764 feed->feed_filename);
3768 feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
3769 feed->feed_size = lseek(fd, 0, SEEK_END);
3770 /* ensure that we do not wrap before the end of file */
3771 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3772 feed->feed_max_size = feed->feed_size;
3778 /* compute the bandwidth used by each stream */
3779 static void compute_bandwidth(void)
3785 for(stream = first_stream; stream != NULL; stream = stream->next) {
3787 for(i=0;i<stream->nb_streams;i++) {
3788 AVStream *st = stream->streams[i];
3789 switch(st->codec->codec_type) {
3790 case AVMEDIA_TYPE_AUDIO:
3791 case AVMEDIA_TYPE_VIDEO:
3792 bandwidth += st->codec->bit_rate;
3798 stream->bandwidth = (bandwidth + 999) / 1000;
3802 /* add a codec and set the default parameters */
3803 static void add_codec(FFStream *stream, AVCodecContext *av)
3807 /* compute default parameters */
3808 switch(av->codec_type) {
3809 case AVMEDIA_TYPE_AUDIO:
3810 if (av->bit_rate == 0)
3811 av->bit_rate = 64000;
3812 if (av->sample_rate == 0)
3813 av->sample_rate = 22050;
3814 if (av->channels == 0)
3817 case AVMEDIA_TYPE_VIDEO:
3818 if (av->bit_rate == 0)
3819 av->bit_rate = 64000;
3820 if (av->time_base.num == 0){
3821 av->time_base.den = 5;
3822 av->time_base.num = 1;
3824 if (av->width == 0 || av->height == 0) {
3828 /* Bitrate tolerance is less for streaming */
3829 if (av->bit_rate_tolerance == 0)
3830 av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
3831 (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);
3836 if (av->max_qdiff == 0)
3838 av->qcompress = 0.5;
3841 if (!av->nsse_weight)
3842 av->nsse_weight = 8;
3844 av->frame_skip_cmp = FF_CMP_DCTMAX;
3845 av->me_method = ME_EPZS;
3846 av->rc_buffer_aggressivity = 1.0;
3849 av->rc_eq = "tex^qComp";
3850 if (!av->i_quant_factor)
3851 av->i_quant_factor = -0.8;
3852 if (!av->b_quant_factor)
3853 av->b_quant_factor = 1.25;
3854 if (!av->b_quant_offset)
3855 av->b_quant_offset = 1.25;
3856 if (!av->rc_max_rate)
3857 av->rc_max_rate = av->bit_rate * 2;
3859 if (av->rc_max_rate && !av->rc_buffer_size) {
3860 av->rc_buffer_size = av->rc_max_rate;
3869 st = av_mallocz(sizeof(AVStream));
3872 st->codec = avcodec_alloc_context();
3873 stream->streams[stream->nb_streams++] = st;
3874 memcpy(st->codec, av, sizeof(AVCodecContext));
3877 static enum CodecID opt_audio_codec(const char *arg)
3879 AVCodec *p= avcodec_find_encoder_by_name(arg);
3881 if (p == NULL || p->type != AVMEDIA_TYPE_AUDIO)
3882 return CODEC_ID_NONE;
3887 static enum CodecID opt_video_codec(const char *arg)
3889 AVCodec *p= avcodec_find_encoder_by_name(arg);
3891 if (p == NULL || p->type != AVMEDIA_TYPE_VIDEO)
3892 return CODEC_ID_NONE;
3897 /* simplistic plugin support */
3900 static void load_module(const char *filename)
3903 void (*init_func)(void);
3904 dll = dlopen(filename, RTLD_NOW);
3906 fprintf(stderr, "Could not load module '%s' - %s\n",
3907 filename, dlerror());
3911 init_func = dlsym(dll, "ffserver_module_init");
3914 "%s: init function 'ffserver_module_init()' not found\n",
3923 static int ffserver_opt_default(const char *opt, const char *arg,
3924 AVCodecContext *avctx, int type)
3927 const AVOption *o = av_find_opt(avctx, opt, NULL, type, type);
3929 ret = av_set_string3(avctx, opt, arg, 1, NULL);
3933 static AVOutputFormat *ffserver_guess_format(const char *short_name, const char *filename,
3934 const char *mime_type)
3936 AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
3939 AVOutputFormat *stream_fmt;
3940 char stream_format_name[64];
3942 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
3943 stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
3952 static int parse_ffconfig(const char *filename)
3959 int val, errors, line_num;
3960 FFStream **last_stream, *stream, *redirect;
3961 FFStream **last_feed, *feed, *s;
3962 AVCodecContext audio_enc, video_enc;
3963 enum CodecID audio_id, video_id;
3965 f = fopen(filename, "r");
3973 first_stream = NULL;
3974 last_stream = &first_stream;
3976 last_feed = &first_feed;
3980 audio_id = CODEC_ID_NONE;
3981 video_id = CODEC_ID_NONE;
3983 if (fgets(line, sizeof(line), f) == NULL)
3989 if (*p == '\0' || *p == '#')
3992 get_arg(cmd, sizeof(cmd), &p);
3994 if (!strcasecmp(cmd, "Port")) {
3995 get_arg(arg, sizeof(arg), &p);
3997 if (val < 1 || val > 65536) {
3998 fprintf(stderr, "%s:%d: Invalid port: %s\n",
3999 filename, line_num, arg);
4002 my_http_addr.sin_port = htons(val);
4003 } else if (!strcasecmp(cmd, "BindAddress")) {
4004 get_arg(arg, sizeof(arg), &p);
4005 if (resolve_host(&my_http_addr.sin_addr, arg) != 0) {
4006 fprintf(stderr, "%s:%d: Invalid host/IP address: %s\n",
4007 filename, line_num, arg);
4010 } else if (!strcasecmp(cmd, "NoDaemon")) {
4011 ffserver_daemon = 0;
4012 } else if (!strcasecmp(cmd, "RTSPPort")) {
4013 get_arg(arg, sizeof(arg), &p);
4015 if (val < 1 || val > 65536) {
4016 fprintf(stderr, "%s:%d: Invalid port: %s\n",
4017 filename, line_num, arg);
4020 my_rtsp_addr.sin_port = htons(atoi(arg));
4021 } else if (!strcasecmp(cmd, "RTSPBindAddress")) {
4022 get_arg(arg, sizeof(arg), &p);
4023 if (resolve_host(&my_rtsp_addr.sin_addr, arg) != 0) {
4024 fprintf(stderr, "%s:%d: Invalid host/IP address: %s\n",
4025 filename, line_num, arg);
4028 } else if (!strcasecmp(cmd, "MaxHTTPConnections")) {
4029 get_arg(arg, sizeof(arg), &p);
4031 if (val < 1 || val > 65536) {
4032 fprintf(stderr, "%s:%d: Invalid MaxHTTPConnections: %s\n",
4033 filename, line_num, arg);
4036 nb_max_http_connections = val;
4037 } else if (!strcasecmp(cmd, "MaxClients")) {
4038 get_arg(arg, sizeof(arg), &p);
4040 if (val < 1 || val > nb_max_http_connections) {
4041 fprintf(stderr, "%s:%d: Invalid MaxClients: %s\n",
4042 filename, line_num, arg);
4045 nb_max_connections = val;
4047 } else if (!strcasecmp(cmd, "MaxBandwidth")) {
4049 get_arg(arg, sizeof(arg), &p);
4051 if (llval < 10 || llval > 10000000) {
4052 fprintf(stderr, "%s:%d: Invalid MaxBandwidth: %s\n",
4053 filename, line_num, arg);
4056 max_bandwidth = llval;
4057 } else if (!strcasecmp(cmd, "CustomLog")) {
4058 if (!ffserver_debug)
4059 get_arg(logfilename, sizeof(logfilename), &p);
4060 } else if (!strcasecmp(cmd, "<Feed")) {
4061 /*********************************************/
4062 /* Feed related options */
4064 if (stream || feed) {
4065 fprintf(stderr, "%s:%d: Already in a tag\n",
4066 filename, line_num);
4068 feed = av_mallocz(sizeof(FFStream));
4069 get_arg(feed->filename, sizeof(feed->filename), &p);
4070 q = strrchr(feed->filename, '>');
4074 for (s = first_feed; s; s = s->next) {
4075 if (!strcmp(feed->filename, s->filename)) {
4076 fprintf(stderr, "%s:%d: Feed '%s' already registered\n",
4077 filename, line_num, s->filename);
4082 feed->fmt = av_guess_format("ffm", NULL, NULL);
4083 /* defaut feed file */
4084 snprintf(feed->feed_filename, sizeof(feed->feed_filename),
4085 "/tmp/%s.ffm", feed->filename);
4086 feed->feed_max_size = 5 * 1024 * 1024;
4088 feed->feed = feed; /* self feeding :-) */
4090 /* add in stream list */
4091 *last_stream = feed;
4092 last_stream = &feed->next;
4093 /* add in feed list */
4095 last_feed = &feed->next_feed;
4097 } else if (!strcasecmp(cmd, "Launch")) {
4101 feed->child_argv = av_mallocz(64 * sizeof(char *));
4103 for (i = 0; i < 62; i++) {
4104 get_arg(arg, sizeof(arg), &p);
4108 feed->child_argv[i] = av_strdup(arg);
4111 feed->child_argv[i] = av_malloc(30 + strlen(feed->filename));
4113 snprintf(feed->child_argv[i], 30+strlen(feed->filename),
4115 (my_http_addr.sin_addr.s_addr == INADDR_ANY) ? "127.0.0.1" :
4116 inet_ntoa(my_http_addr.sin_addr),
4117 ntohs(my_http_addr.sin_port), feed->filename);
4119 } else if (!strcasecmp(cmd, "ReadOnlyFile")) {
4121 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
4123 } else if (stream) {
4124 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4126 } else if (!strcasecmp(cmd, "File")) {
4128 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
4130 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4131 } else if (!strcasecmp(cmd, "Truncate")) {
4133 get_arg(arg, sizeof(arg), &p);
4134 feed->truncate = strtod(arg, NULL);
4136 } else if (!strcasecmp(cmd, "FileMaxSize")) {
4141 get_arg(arg, sizeof(arg), &p);
4143 fsize = strtod(p1, &p1);
4144 switch(toupper(*p1)) {
4149 fsize *= 1024 * 1024;
4152 fsize *= 1024 * 1024 * 1024;
4155 feed->feed_max_size = (int64_t)fsize;
4156 if (feed->feed_max_size < FFM_PACKET_SIZE*4) {
4157 fprintf(stderr, "%s:%d: Feed max file size is too small, "
4158 "must be at least %d\n", filename, line_num, FFM_PACKET_SIZE*4);
4162 } else if (!strcasecmp(cmd, "</Feed>")) {
4164 fprintf(stderr, "%s:%d: No corresponding <Feed> for </Feed>\n",
4165 filename, line_num);
4169 } else if (!strcasecmp(cmd, "<Stream")) {
4170 /*********************************************/
4171 /* Stream related options */
4173 if (stream || feed) {
4174 fprintf(stderr, "%s:%d: Already in a tag\n",
4175 filename, line_num);
4178 stream = av_mallocz(sizeof(FFStream));
4179 get_arg(stream->filename, sizeof(stream->filename), &p);
4180 q = strrchr(stream->filename, '>');
4184 for (s = first_stream; s; s = s->next) {
4185 if (!strcmp(stream->filename, s->filename)) {
4186 fprintf(stderr, "%s:%d: Stream '%s' already registered\n",
4187 filename, line_num, s->filename);
4192 stream->fmt = ffserver_guess_format(NULL, stream->filename, NULL);
4193 avcodec_get_context_defaults2(&video_enc, AVMEDIA_TYPE_VIDEO);
4194 avcodec_get_context_defaults2(&audio_enc, AVMEDIA_TYPE_AUDIO);
4195 audio_id = CODEC_ID_NONE;
4196 video_id = CODEC_ID_NONE;
4198 audio_id = stream->fmt->audio_codec;
4199 video_id = stream->fmt->video_codec;
4202 *last_stream = stream;
4203 last_stream = &stream->next;
4205 } else if (!strcasecmp(cmd, "Feed")) {
4206 get_arg(arg, sizeof(arg), &p);
4211 while (sfeed != NULL) {
4212 if (!strcmp(sfeed->filename, arg))
4214 sfeed = sfeed->next_feed;
4217 fprintf(stderr, "%s:%d: feed '%s' not defined\n",
4218 filename, line_num, arg);
4220 stream->feed = sfeed;
4222 } else if (!strcasecmp(cmd, "Format")) {
4223 get_arg(arg, sizeof(arg), &p);
4225 if (!strcmp(arg, "status")) {
4226 stream->stream_type = STREAM_TYPE_STATUS;
4229 stream->stream_type = STREAM_TYPE_LIVE;
4230 /* jpeg cannot be used here, so use single frame jpeg */
4231 if (!strcmp(arg, "jpeg"))
4232 strcpy(arg, "mjpeg");
4233 stream->fmt = ffserver_guess_format(arg, NULL, NULL);
4235 fprintf(stderr, "%s:%d: Unknown Format: %s\n",
4236 filename, line_num, arg);
4241 audio_id = stream->fmt->audio_codec;
4242 video_id = stream->fmt->video_codec;
4245 } else if (!strcasecmp(cmd, "InputFormat")) {
4246 get_arg(arg, sizeof(arg), &p);
4248 stream->ifmt = av_find_input_format(arg);
4249 if (!stream->ifmt) {
4250 fprintf(stderr, "%s:%d: Unknown input format: %s\n",
4251 filename, line_num, arg);
4254 } else if (!strcasecmp(cmd, "FaviconURL")) {
4255 if (stream && stream->stream_type == STREAM_TYPE_STATUS) {
4256 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4258 fprintf(stderr, "%s:%d: FaviconURL only permitted for status streams\n",
4259 filename, line_num);
4262 } else if (!strcasecmp(cmd, "Author")) {
4264 get_arg(stream->author, sizeof(stream->author), &p);
4265 } else if (!strcasecmp(cmd, "Comment")) {
4267 get_arg(stream->comment, sizeof(stream->comment), &p);
4268 } else if (!strcasecmp(cmd, "Copyright")) {
4270 get_arg(stream->copyright, sizeof(stream->copyright), &p);
4271 } else if (!strcasecmp(cmd, "Title")) {
4273 get_arg(stream->title, sizeof(stream->title), &p);
4274 } else if (!strcasecmp(cmd, "Preroll")) {
4275 get_arg(arg, sizeof(arg), &p);
4277 stream->prebuffer = atof(arg) * 1000;
4278 } else if (!strcasecmp(cmd, "StartSendOnKey")) {
4280 stream->send_on_key = 1;
4281 } else if (!strcasecmp(cmd, "AudioCodec")) {
4282 get_arg(arg, sizeof(arg), &p);
4283 audio_id = opt_audio_codec(arg);
4284 if (audio_id == CODEC_ID_NONE) {
4285 fprintf(stderr, "%s:%d: Unknown AudioCodec: %s\n",
4286 filename, line_num, arg);
4289 } else if (!strcasecmp(cmd, "VideoCodec")) {
4290 get_arg(arg, sizeof(arg), &p);
4291 video_id = opt_video_codec(arg);
4292 if (video_id == CODEC_ID_NONE) {
4293 fprintf(stderr, "%s:%d: Unknown VideoCodec: %s\n",
4294 filename, line_num, arg);
4297 } else if (!strcasecmp(cmd, "MaxTime")) {
4298 get_arg(arg, sizeof(arg), &p);
4300 stream->max_time = atof(arg) * 1000;
4301 } else if (!strcasecmp(cmd, "AudioBitRate")) {
4302 get_arg(arg, sizeof(arg), &p);
4304 audio_enc.bit_rate = atoi(arg) * 1000;
4305 } else if (!strcasecmp(cmd, "AudioChannels")) {
4306 get_arg(arg, sizeof(arg), &p);
4308 audio_enc.channels = atoi(arg);
4309 } else if (!strcasecmp(cmd, "AudioSampleRate")) {
4310 get_arg(arg, sizeof(arg), &p);
4312 audio_enc.sample_rate = atoi(arg);
4313 } else if (!strcasecmp(cmd, "AudioQuality")) {
4314 get_arg(arg, sizeof(arg), &p);
4316 // audio_enc.quality = atof(arg) * 1000;
4318 } else if (!strcasecmp(cmd, "VideoBitRateRange")) {
4320 int minrate, maxrate;
4322 get_arg(arg, sizeof(arg), &p);
4324 if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {
4325 video_enc.rc_min_rate = minrate * 1000;
4326 video_enc.rc_max_rate = maxrate * 1000;
4328 fprintf(stderr, "%s:%d: Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n",
4329 filename, line_num, arg);
4333 } else if (!strcasecmp(cmd, "Debug")) {
4335 get_arg(arg, sizeof(arg), &p);
4336 video_enc.debug = strtol(arg,0,0);
4338 } else if (!strcasecmp(cmd, "Strict")) {
4340 get_arg(arg, sizeof(arg), &p);
4341 video_enc.strict_std_compliance = atoi(arg);
4343 } else if (!strcasecmp(cmd, "VideoBufferSize")) {
4345 get_arg(arg, sizeof(arg), &p);
4346 video_enc.rc_buffer_size = atoi(arg) * 8*1024;
4348 } else if (!strcasecmp(cmd, "VideoBitRateTolerance")) {
4350 get_arg(arg, sizeof(arg), &p);
4351 video_enc.bit_rate_tolerance = atoi(arg) * 1000;
4353 } else if (!strcasecmp(cmd, "VideoBitRate")) {
4354 get_arg(arg, sizeof(arg), &p);
4356 video_enc.bit_rate = atoi(arg) * 1000;
4358 } else if (!strcasecmp(cmd, "VideoSize")) {
4359 get_arg(arg, sizeof(arg), &p);
4361 av_parse_video_frame_size(&video_enc.width, &video_enc.height, arg);
4362 if ((video_enc.width % 16) != 0 ||
4363 (video_enc.height % 16) != 0) {
4364 fprintf(stderr, "%s:%d: Image size must be a multiple of 16\n",
4365 filename, line_num);
4369 } else if (!strcasecmp(cmd, "VideoFrameRate")) {
4370 get_arg(arg, sizeof(arg), &p);
4372 AVRational frame_rate;
4373 if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
4374 fprintf(stderr, "Incorrect frame rate\n");
4377 video_enc.time_base.num = frame_rate.den;
4378 video_enc.time_base.den = frame_rate.num;
4381 } else if (!strcasecmp(cmd, "VideoGopSize")) {
4382 get_arg(arg, sizeof(arg), &p);
4384 video_enc.gop_size = atoi(arg);
4385 } else if (!strcasecmp(cmd, "VideoIntraOnly")) {
4387 video_enc.gop_size = 1;
4388 } else if (!strcasecmp(cmd, "VideoHighQuality")) {
4390 video_enc.mb_decision = FF_MB_DECISION_BITS;
4391 } else if (!strcasecmp(cmd, "Video4MotionVector")) {
4393 video_enc.mb_decision = FF_MB_DECISION_BITS; //FIXME remove
4394 video_enc.flags |= CODEC_FLAG_4MV;
4396 } else if (!strcasecmp(cmd, "AVOptionVideo") ||
4397 !strcasecmp(cmd, "AVOptionAudio")) {
4399 AVCodecContext *avctx;
4401 get_arg(arg, sizeof(arg), &p);
4402 get_arg(arg2, sizeof(arg2), &p);
4403 if (!strcasecmp(cmd, "AVOptionVideo")) {
4405 type = AV_OPT_FLAG_VIDEO_PARAM;
4408 type = AV_OPT_FLAG_AUDIO_PARAM;
4410 if (ffserver_opt_default(arg, arg2, avctx, type|AV_OPT_FLAG_ENCODING_PARAM)) {
4411 fprintf(stderr, "AVOption error: %s %s\n", arg, arg2);
4414 } else if (!strcasecmp(cmd, "VideoTag")) {
4415 get_arg(arg, sizeof(arg), &p);
4416 if ((strlen(arg) == 4) && stream)
4417 video_enc.codec_tag = MKTAG(arg[0], arg[1], arg[2], arg[3]);
4418 } else if (!strcasecmp(cmd, "BitExact")) {
4420 video_enc.flags |= CODEC_FLAG_BITEXACT;
4421 } else if (!strcasecmp(cmd, "DctFastint")) {
4423 video_enc.dct_algo = FF_DCT_FASTINT;
4424 } else if (!strcasecmp(cmd, "IdctSimple")) {
4426 video_enc.idct_algo = FF_IDCT_SIMPLE;
4427 } else if (!strcasecmp(cmd, "Qscale")) {
4428 get_arg(arg, sizeof(arg), &p);
4430 video_enc.flags |= CODEC_FLAG_QSCALE;
4431 video_enc.global_quality = FF_QP2LAMBDA * atoi(arg);
4433 } else if (!strcasecmp(cmd, "VideoQDiff")) {
4434 get_arg(arg, sizeof(arg), &p);
4436 video_enc.max_qdiff = atoi(arg);
4437 if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) {
4438 fprintf(stderr, "%s:%d: VideoQDiff out of range\n",
4439 filename, line_num);
4443 } else if (!strcasecmp(cmd, "VideoQMax")) {
4444 get_arg(arg, sizeof(arg), &p);
4446 video_enc.qmax = atoi(arg);
4447 if (video_enc.qmax < 1 || video_enc.qmax > 31) {
4448 fprintf(stderr, "%s:%d: VideoQMax out of range\n",
4449 filename, line_num);
4453 } else if (!strcasecmp(cmd, "VideoQMin")) {
4454 get_arg(arg, sizeof(arg), &p);
4456 video_enc.qmin = atoi(arg);
4457 if (video_enc.qmin < 1 || video_enc.qmin > 31) {
4458 fprintf(stderr, "%s:%d: VideoQMin out of range\n",
4459 filename, line_num);
4463 } else if (!strcasecmp(cmd, "LumaElim")) {
4464 get_arg(arg, sizeof(arg), &p);
4466 video_enc.luma_elim_threshold = atoi(arg);
4467 } else if (!strcasecmp(cmd, "ChromaElim")) {
4468 get_arg(arg, sizeof(arg), &p);
4470 video_enc.chroma_elim_threshold = atoi(arg);
4471 } else if (!strcasecmp(cmd, "LumiMask")) {
4472 get_arg(arg, sizeof(arg), &p);
4474 video_enc.lumi_masking = atof(arg);
4475 } else if (!strcasecmp(cmd, "DarkMask")) {
4476 get_arg(arg, sizeof(arg), &p);
4478 video_enc.dark_masking = atof(arg);
4479 } else if (!strcasecmp(cmd, "NoVideo")) {
4480 video_id = CODEC_ID_NONE;
4481 } else if (!strcasecmp(cmd, "NoAudio")) {
4482 audio_id = CODEC_ID_NONE;
4483 } else if (!strcasecmp(cmd, "ACL")) {
4484 parse_acl_row(stream, feed, NULL, p, filename, line_num);
4485 } else if (!strcasecmp(cmd, "DynamicACL")) {
4487 get_arg(stream->dynamic_acl, sizeof(stream->dynamic_acl), &p);
4489 } else if (!strcasecmp(cmd, "RTSPOption")) {
4490 get_arg(arg, sizeof(arg), &p);
4492 av_freep(&stream->rtsp_option);
4493 stream->rtsp_option = av_strdup(arg);
4495 } else if (!strcasecmp(cmd, "MulticastAddress")) {
4496 get_arg(arg, sizeof(arg), &p);
4498 if (resolve_host(&stream->multicast_ip, arg) != 0) {
4499 fprintf(stderr, "%s:%d: Invalid host/IP address: %s\n",
4500 filename, line_num, arg);
4503 stream->is_multicast = 1;
4504 stream->loop = 1; /* default is looping */
4506 } else if (!strcasecmp(cmd, "MulticastPort")) {
4507 get_arg(arg, sizeof(arg), &p);
4509 stream->multicast_port = atoi(arg);
4510 } else if (!strcasecmp(cmd, "MulticastTTL")) {
4511 get_arg(arg, sizeof(arg), &p);
4513 stream->multicast_ttl = atoi(arg);
4514 } else if (!strcasecmp(cmd, "NoLoop")) {
4517 } else if (!strcasecmp(cmd, "</Stream>")) {
4519 fprintf(stderr, "%s:%d: No corresponding <Stream> for </Stream>\n",
4520 filename, line_num);
4523 if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) {
4524 if (audio_id != CODEC_ID_NONE) {
4525 audio_enc.codec_type = AVMEDIA_TYPE_AUDIO;
4526 audio_enc.codec_id = audio_id;
4527 add_codec(stream, &audio_enc);
4529 if (video_id != CODEC_ID_NONE) {
4530 video_enc.codec_type = AVMEDIA_TYPE_VIDEO;
4531 video_enc.codec_id = video_id;
4532 add_codec(stream, &video_enc);
4537 } else if (!strcasecmp(cmd, "<Redirect")) {
4538 /*********************************************/
4540 if (stream || feed || redirect) {
4541 fprintf(stderr, "%s:%d: Already in a tag\n",
4542 filename, line_num);
4545 redirect = av_mallocz(sizeof(FFStream));
4546 *last_stream = redirect;
4547 last_stream = &redirect->next;
4549 get_arg(redirect->filename, sizeof(redirect->filename), &p);
4550 q = strrchr(redirect->filename, '>');
4553 redirect->stream_type = STREAM_TYPE_REDIRECT;
4555 } else if (!strcasecmp(cmd, "URL")) {
4557 get_arg(redirect->feed_filename, sizeof(redirect->feed_filename), &p);
4558 } else if (!strcasecmp(cmd, "</Redirect>")) {
4560 fprintf(stderr, "%s:%d: No corresponding <Redirect> for </Redirect>\n",
4561 filename, line_num);
4564 if (!redirect->feed_filename[0]) {
4565 fprintf(stderr, "%s:%d: No URL found for <Redirect>\n",
4566 filename, line_num);
4571 } else if (!strcasecmp(cmd, "LoadModule")) {
4572 get_arg(arg, sizeof(arg), &p);
4576 fprintf(stderr, "%s:%d: Module support not compiled into this version: '%s'\n",
4577 filename, line_num, arg);
4581 fprintf(stderr, "%s:%d: Incorrect keyword: '%s'\n",
4582 filename, line_num, cmd);
4593 static void handle_child_exit(int sig)
4598 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
4601 for (feed = first_feed; feed; feed = feed->next) {
4602 if (feed->pid == pid) {
4603 int uptime = time(0) - feed->pid_start;
4606 fprintf(stderr, "%s: Pid %d exited with status %d after %d seconds\n", feed->filename, pid, status, uptime);
4609 /* Turn off any more restarts */
4610 feed->child_argv = 0;
4615 need_to_start_children = 1;
4618 static void opt_debug(void)
4621 ffserver_daemon = 0;
4622 logfilename[0] = '-';
4625 static void show_help(void)
4627 printf("usage: ffserver [options]\n"
4628 "Hyper fast multi format Audio/Video streaming server\n");
4630 show_help_options(options, "Main options:\n", 0, 0);
4633 static const OptionDef options[] = {
4634 #include "cmdutils_common_opts.h"
4635 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
4636 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
4637 { "f", HAS_ARG | OPT_STRING, {(void*)&config_filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
4641 int main(int argc, char **argv)
4643 struct sigaction sigact;
4649 config_filename = "/etc/ffserver.conf";
4651 my_program_name = argv[0];
4652 my_program_dir = getcwd(0, 0);
4653 ffserver_daemon = 1;
4655 parse_options(argc, argv, options, NULL);
4657 unsetenv("http_proxy"); /* Kill the http_proxy */
4659 av_lfg_init(&random_state, ff_random_get_seed());
4661 memset(&sigact, 0, sizeof(sigact));
4662 sigact.sa_handler = handle_child_exit;
4663 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
4664 sigaction(SIGCHLD, &sigact, 0);
4666 if (parse_ffconfig(config_filename) < 0) {
4667 fprintf(stderr, "Incorrect config file - exiting.\n");
4671 /* open log file if needed */
4672 if (logfilename[0] != '\0') {
4673 if (!strcmp(logfilename, "-"))
4676 logfile = fopen(logfilename, "a");
4677 av_log_set_callback(http_av_log);
4680 build_file_streams();
4682 build_feed_streams();
4684 compute_bandwidth();
4686 /* put the process in background and detach it from its TTY */
4687 if (ffserver_daemon) {
4694 } else if (pid > 0) {
4701 open("/dev/null", O_RDWR);
4702 if (strcmp(logfilename, "-") != 0) {
4712 signal(SIGPIPE, SIG_IGN);
4714 if (ffserver_daemon)
4717 if (http_server() < 0) {
4718 http_log("Could not start server\n");