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 = "/etc/ffserver.conf";
298 static int ffserver_debug;
299 static int ffserver_daemon;
300 static int no_launch;
301 static int need_to_start_children;
303 /* maximum number of simultaneous HTTP connections */
304 static unsigned int nb_max_http_connections = 2000;
305 static unsigned int nb_max_connections = 5;
306 static unsigned int nb_connections;
308 static uint64_t max_bandwidth = 1000;
309 static uint64_t current_bandwidth;
311 static int64_t cur_time; // Making this global saves on passing it around everywhere
313 static AVLFG random_state;
315 static FILE *logfile = NULL;
317 /* FIXME: make ffserver work with IPv6 */
318 /* resolve host with also IP address parsing */
319 static int resolve_host(struct in_addr *sin_addr, const char *hostname)
322 if (!ff_inet_aton(hostname, sin_addr)) {
324 struct addrinfo *ai, *cur;
325 struct addrinfo hints;
326 memset(&hints, 0, sizeof(hints));
327 hints.ai_family = AF_INET;
328 if (getaddrinfo(hostname, NULL, &hints, &ai))
330 /* getaddrinfo returns a linked list of addrinfo structs.
331 * Even if we set ai_family = AF_INET above, make sure
332 * that the returned one actually is of the correct type. */
333 for (cur = ai; cur; cur = cur->ai_next) {
334 if (cur->ai_family == AF_INET) {
335 *sin_addr = ((struct sockaddr_in *)cur->ai_addr)->sin_addr;
344 hp = gethostbyname(hostname);
347 memcpy(sin_addr, hp->h_addr_list[0], sizeof(struct in_addr));
353 static char *ctime1(char *buf2)
361 p = buf2 + strlen(p) - 1;
367 static void http_vlog(const char *fmt, va_list vargs)
369 static int print_prefix = 1;
374 fprintf(logfile, "%s ", buf);
376 print_prefix = strstr(fmt, "\n") != NULL;
377 vfprintf(logfile, fmt, vargs);
382 static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
385 va_start(vargs, fmt);
386 http_vlog(fmt, vargs);
390 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
392 static int print_prefix = 1;
393 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
394 if (level > av_log_get_level())
396 if (print_prefix && avc)
397 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
398 print_prefix = strstr(fmt, "\n") != NULL;
399 http_vlog(fmt, vargs);
402 static void log_connection(HTTPContext *c)
407 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
408 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
409 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
412 static void update_datarate(DataRateData *drd, int64_t count)
414 if (!drd->time1 && !drd->count1) {
415 drd->time1 = drd->time2 = cur_time;
416 drd->count1 = drd->count2 = count;
417 } else if (cur_time - drd->time2 > 5000) {
418 drd->time1 = drd->time2;
419 drd->count1 = drd->count2;
420 drd->time2 = cur_time;
425 /* In bytes per second */
426 static int compute_datarate(DataRateData *drd, int64_t count)
428 if (cur_time == drd->time1)
431 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
435 static void start_children(FFStream *feed)
440 for (; feed; feed = feed->next) {
441 if (feed->child_argv && !feed->pid) {
442 feed->pid_start = time(0);
447 http_log("Unable to create children\n");
456 av_strlcpy(pathname, my_program_name, sizeof(pathname));
458 slash = strrchr(pathname, '/');
463 strcpy(slash, "ffmpeg");
465 http_log("Launch commandline: ");
466 http_log("%s ", pathname);
467 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
468 http_log("%s ", feed->child_argv[i]);
471 for (i = 3; i < 256; i++)
474 if (!ffserver_debug) {
475 i = open("/dev/null", O_RDWR);
484 /* This is needed to make relative pathnames work */
485 chdir(my_program_dir);
487 signal(SIGPIPE, SIG_DFL);
489 execvp(pathname, feed->child_argv);
497 /* open a listening socket */
498 static int socket_open_listen(struct sockaddr_in *my_addr)
502 server_fd = socket(AF_INET,SOCK_STREAM,0);
509 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
511 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
513 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
515 closesocket(server_fd);
519 if (listen (server_fd, 5) < 0) {
521 closesocket(server_fd);
524 ff_socket_nonblock(server_fd, 1);
529 /* start all multicast streams */
530 static void start_multicast(void)
535 struct sockaddr_in dest_addr;
536 int default_port, stream_index;
539 for(stream = first_stream; stream != NULL; stream = stream->next) {
540 if (stream->is_multicast) {
541 /* open the RTP connection */
542 snprintf(session_id, sizeof(session_id), "%08x%08x",
543 av_lfg_get(&random_state), av_lfg_get(&random_state));
545 /* choose a port if none given */
546 if (stream->multicast_port == 0) {
547 stream->multicast_port = default_port;
551 dest_addr.sin_family = AF_INET;
552 dest_addr.sin_addr = stream->multicast_ip;
553 dest_addr.sin_port = htons(stream->multicast_port);
555 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
556 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
560 if (open_input_stream(rtp_c, "") < 0) {
561 http_log("Could not open input stream for stream '%s'\n",
566 /* open each RTP stream */
567 for(stream_index = 0; stream_index < stream->nb_streams;
569 dest_addr.sin_port = htons(stream->multicast_port +
571 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
572 http_log("Could not open output stream '%s/streamid=%d'\n",
573 stream->filename, stream_index);
578 /* change state to send data */
579 rtp_c->state = HTTPSTATE_SEND_DATA;
584 /* main loop of the http server */
585 static int http_server(void)
587 int server_fd = 0, rtsp_server_fd = 0;
588 int ret, delay, delay1;
589 struct pollfd *poll_table, *poll_entry;
590 HTTPContext *c, *c_next;
592 if(!(poll_table = av_mallocz((nb_max_http_connections + 2)*sizeof(*poll_table)))) {
593 http_log("Impossible to allocate a poll table handling %d connections.\n", nb_max_http_connections);
597 if (my_http_addr.sin_port) {
598 server_fd = socket_open_listen(&my_http_addr);
603 if (my_rtsp_addr.sin_port) {
604 rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
605 if (rtsp_server_fd < 0)
609 if (!rtsp_server_fd && !server_fd) {
610 http_log("HTTP and RTSP disabled.\n");
614 http_log("FFserver started.\n");
616 start_children(first_feed);
621 poll_entry = poll_table;
623 poll_entry->fd = server_fd;
624 poll_entry->events = POLLIN;
627 if (rtsp_server_fd) {
628 poll_entry->fd = rtsp_server_fd;
629 poll_entry->events = POLLIN;
633 /* wait for events on each HTTP handle */
640 case HTTPSTATE_SEND_HEADER:
641 case RTSPSTATE_SEND_REPLY:
642 case RTSPSTATE_SEND_PACKET:
643 c->poll_entry = poll_entry;
645 poll_entry->events = POLLOUT;
648 case HTTPSTATE_SEND_DATA_HEADER:
649 case HTTPSTATE_SEND_DATA:
650 case HTTPSTATE_SEND_DATA_TRAILER:
651 if (!c->is_packetized) {
652 /* for TCP, we output as much as we can (may need to put a limit) */
653 c->poll_entry = poll_entry;
655 poll_entry->events = POLLOUT;
658 /* when ffserver is doing the timing, we work by
659 looking at which packet need to be sent every
661 delay1 = 10; /* one tick wait XXX: 10 ms assumed */
666 case HTTPSTATE_WAIT_REQUEST:
667 case HTTPSTATE_RECEIVE_DATA:
668 case HTTPSTATE_WAIT_FEED:
669 case RTSPSTATE_WAIT_REQUEST:
670 /* need to catch errors */
671 c->poll_entry = poll_entry;
673 poll_entry->events = POLLIN;/* Maybe this will work */
677 c->poll_entry = NULL;
683 /* wait for an event on one connection. We poll at least every
684 second to handle timeouts */
686 ret = poll(poll_table, poll_entry - poll_table, delay);
687 if (ret < 0 && ff_neterrno() != FF_NETERROR(EAGAIN) &&
688 ff_neterrno() != FF_NETERROR(EINTR))
692 cur_time = av_gettime() / 1000;
694 if (need_to_start_children) {
695 need_to_start_children = 0;
696 start_children(first_feed);
699 /* now handle the events */
700 for(c = first_http_ctx; c != NULL; c = c_next) {
702 if (handle_connection(c) < 0) {
703 /* close and free the connection */
709 poll_entry = poll_table;
711 /* new HTTP connection request ? */
712 if (poll_entry->revents & POLLIN)
713 new_connection(server_fd, 0);
716 if (rtsp_server_fd) {
717 /* new RTSP connection request ? */
718 if (poll_entry->revents & POLLIN)
719 new_connection(rtsp_server_fd, 1);
724 /* start waiting for a new HTTP/RTSP request */
725 static void start_wait_request(HTTPContext *c, int is_rtsp)
727 c->buffer_ptr = c->buffer;
728 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
731 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
732 c->state = RTSPSTATE_WAIT_REQUEST;
734 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
735 c->state = HTTPSTATE_WAIT_REQUEST;
739 static void http_send_too_busy_reply(int fd)
742 int len = snprintf(buffer, sizeof(buffer),
743 "HTTP/1.0 200 Server too busy\r\n"
744 "Content-type: text/html\r\n"
746 "<html><head><title>Too busy</title></head><body>\r\n"
747 "<p>The server is too busy to serve your request at this time.</p>\r\n"
748 "<p>The number of current connections is %d, and this exceeds the limit of %d.</p>\r\n"
749 "</body></html>\r\n",
750 nb_connections, nb_max_connections);
751 send(fd, buffer, len, 0);
755 static void new_connection(int server_fd, int is_rtsp)
757 struct sockaddr_in from_addr;
759 HTTPContext *c = NULL;
761 len = sizeof(from_addr);
762 fd = accept(server_fd, (struct sockaddr *)&from_addr,
765 http_log("error during accept %s\n", strerror(errno));
768 ff_socket_nonblock(fd, 1);
770 if (nb_connections >= nb_max_connections) {
771 http_send_too_busy_reply(fd);
775 /* add a new connection */
776 c = av_mallocz(sizeof(HTTPContext));
781 c->poll_entry = NULL;
782 c->from_addr = from_addr;
783 c->buffer_size = IOBUFFER_INIT_SIZE;
784 c->buffer = av_malloc(c->buffer_size);
788 c->next = first_http_ctx;
792 start_wait_request(c, is_rtsp);
804 static void close_connection(HTTPContext *c)
806 HTTPContext **cp, *c1;
808 AVFormatContext *ctx;
812 /* remove connection from list */
813 cp = &first_http_ctx;
814 while ((*cp) != NULL) {
822 /* remove references, if any (XXX: do it faster) */
823 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
828 /* remove connection associated resources */
832 /* close each frame parser */
833 for(i=0;i<c->fmt_in->nb_streams;i++) {
834 st = c->fmt_in->streams[i];
835 if (st->codec->codec)
836 avcodec_close(st->codec);
838 av_close_input_file(c->fmt_in);
841 /* free RTP output streams if any */
844 nb_streams = c->stream->nb_streams;
846 for(i=0;i<nb_streams;i++) {
849 av_write_trailer(ctx);
850 av_metadata_free(&ctx->metadata);
851 av_free(ctx->streams[0]);
854 h = c->rtp_handles[i];
861 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
864 if (url_open_dyn_buf(&ctx->pb) >= 0) {
865 av_write_trailer(ctx);
866 av_freep(&c->pb_buffer);
867 url_close_dyn_buf(ctx->pb, &c->pb_buffer);
872 for(i=0; i<ctx->nb_streams; i++)
873 av_free(ctx->streams[i]);
875 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
876 current_bandwidth -= c->stream->bandwidth;
878 /* signal that there is no feed if we are the feeder socket */
879 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
880 c->stream->feed_opened = 0;
884 av_freep(&c->pb_buffer);
885 av_freep(&c->packet_buffer);
891 static int handle_connection(HTTPContext *c)
896 case HTTPSTATE_WAIT_REQUEST:
897 case RTSPSTATE_WAIT_REQUEST:
899 if ((c->timeout - cur_time) < 0)
901 if (c->poll_entry->revents & (POLLERR | POLLHUP))
904 /* no need to read if no events */
905 if (!(c->poll_entry->revents & POLLIN))
909 len = recv(c->fd, c->buffer_ptr, 1, 0);
911 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
912 ff_neterrno() != FF_NETERROR(EINTR))
914 } else if (len == 0) {
917 /* search for end of request. */
919 c->buffer_ptr += len;
921 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
922 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
923 /* request found : parse it and reply */
924 if (c->state == HTTPSTATE_WAIT_REQUEST) {
925 ret = http_parse_request(c);
927 ret = rtsp_parse_request(c);
931 } else if (ptr >= c->buffer_end) {
932 /* request too long: cannot do anything */
934 } else goto read_loop;
938 case HTTPSTATE_SEND_HEADER:
939 if (c->poll_entry->revents & (POLLERR | POLLHUP))
942 /* no need to write if no events */
943 if (!(c->poll_entry->revents & POLLOUT))
945 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
947 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
948 ff_neterrno() != FF_NETERROR(EINTR)) {
949 /* error : close connection */
950 av_freep(&c->pb_buffer);
954 c->buffer_ptr += len;
956 c->stream->bytes_served += len;
957 c->data_count += len;
958 if (c->buffer_ptr >= c->buffer_end) {
959 av_freep(&c->pb_buffer);
963 /* all the buffer was sent : synchronize to the incoming stream */
964 c->state = HTTPSTATE_SEND_DATA_HEADER;
965 c->buffer_ptr = c->buffer_end = c->buffer;
970 case HTTPSTATE_SEND_DATA:
971 case HTTPSTATE_SEND_DATA_HEADER:
972 case HTTPSTATE_SEND_DATA_TRAILER:
973 /* for packetized output, we consider we can always write (the
974 input streams sets the speed). It may be better to verify
975 that we do not rely too much on the kernel queues */
976 if (!c->is_packetized) {
977 if (c->poll_entry->revents & (POLLERR | POLLHUP))
980 /* no need to read if no events */
981 if (!(c->poll_entry->revents & POLLOUT))
984 if (http_send_data(c) < 0)
986 /* close connection if trailer sent */
987 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
990 case HTTPSTATE_RECEIVE_DATA:
991 /* no need to read if no events */
992 if (c->poll_entry->revents & (POLLERR | POLLHUP))
994 if (!(c->poll_entry->revents & POLLIN))
996 if (http_receive_data(c) < 0)
999 case HTTPSTATE_WAIT_FEED:
1000 /* no need to read if no events */
1001 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1004 /* nothing to do, we'll be waken up by incoming feed packets */
1007 case RTSPSTATE_SEND_REPLY:
1008 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1009 av_freep(&c->pb_buffer);
1012 /* no need to write if no events */
1013 if (!(c->poll_entry->revents & POLLOUT))
1015 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1017 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
1018 ff_neterrno() != FF_NETERROR(EINTR)) {
1019 /* error : close connection */
1020 av_freep(&c->pb_buffer);
1024 c->buffer_ptr += len;
1025 c->data_count += len;
1026 if (c->buffer_ptr >= c->buffer_end) {
1027 /* all the buffer was sent : wait for a new request */
1028 av_freep(&c->pb_buffer);
1029 start_wait_request(c, 1);
1033 case RTSPSTATE_SEND_PACKET:
1034 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1035 av_freep(&c->packet_buffer);
1038 /* no need to write if no events */
1039 if (!(c->poll_entry->revents & POLLOUT))
1041 len = send(c->fd, c->packet_buffer_ptr,
1042 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1044 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
1045 ff_neterrno() != FF_NETERROR(EINTR)) {
1046 /* error : close connection */
1047 av_freep(&c->packet_buffer);
1051 c->packet_buffer_ptr += len;
1052 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1053 /* all the buffer was sent : wait for a new request */
1054 av_freep(&c->packet_buffer);
1055 c->state = RTSPSTATE_WAIT_REQUEST;
1059 case HTTPSTATE_READY:
1068 static int extract_rates(char *rates, int ratelen, const char *request)
1072 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1073 if (strncasecmp(p, "Pragma:", 7) == 0) {
1074 const char *q = p + 7;
1076 while (*q && *q != '\n' && isspace(*q))
1079 if (strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1085 memset(rates, 0xff, ratelen);
1088 while (*q && *q != '\n' && *q != ':')
1091 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1095 if (stream_no < ratelen && stream_no >= 0)
1096 rates[stream_no] = rate_no;
1098 while (*q && *q != '\n' && !isspace(*q))
1105 p = strchr(p, '\n');
1115 static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
1118 int best_bitrate = 100000000;
1121 for (i = 0; i < feed->nb_streams; i++) {
1122 AVCodecContext *feed_codec = feed->streams[i]->codec;
1124 if (feed_codec->codec_id != codec->codec_id ||
1125 feed_codec->sample_rate != codec->sample_rate ||
1126 feed_codec->width != codec->width ||
1127 feed_codec->height != codec->height)
1130 /* Potential stream */
1132 /* We want the fastest stream less than bit_rate, or the slowest
1133 * faster than bit_rate
1136 if (feed_codec->bit_rate <= bit_rate) {
1137 if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
1138 best_bitrate = feed_codec->bit_rate;
1142 if (feed_codec->bit_rate < best_bitrate) {
1143 best_bitrate = feed_codec->bit_rate;
1152 static int modify_current_stream(HTTPContext *c, char *rates)
1155 FFStream *req = c->stream;
1156 int action_required = 0;
1158 /* Not much we can do for a feed */
1162 for (i = 0; i < req->nb_streams; i++) {
1163 AVCodecContext *codec = req->streams[i]->codec;
1167 c->switch_feed_streams[i] = req->feed_streams[i];
1170 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1173 /* Wants off or slow */
1174 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1176 /* This doesn't work well when it turns off the only stream! */
1177 c->switch_feed_streams[i] = -2;
1178 c->feed_streams[i] = -2;
1183 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1184 action_required = 1;
1187 return action_required;
1191 static void do_switch_stream(HTTPContext *c, int i)
1193 if (c->switch_feed_streams[i] >= 0) {
1195 c->feed_streams[i] = c->switch_feed_streams[i];
1198 /* Now update the stream */
1200 c->switch_feed_streams[i] = -1;
1203 /* XXX: factorize in utils.c ? */
1204 /* XXX: take care with different space meaning */
1205 static void skip_spaces(const char **pp)
1209 while (*p == ' ' || *p == '\t')
1214 static void get_word(char *buf, int buf_size, const char **pp)
1222 while (!isspace(*p) && *p != '\0') {
1223 if ((q - buf) < buf_size - 1)
1232 static void get_arg(char *buf, int buf_size, const char **pp)
1239 while (isspace(*p)) p++;
1242 if (*p == '\"' || *p == '\'')
1254 if ((q - buf) < buf_size - 1)
1259 if (quote && *p == quote)
1264 static void parse_acl_row(FFStream *stream, FFStream* feed, IPAddressACL *ext_acl,
1265 const char *p, const char *filename, int line_num)
1271 get_arg(arg, sizeof(arg), &p);
1272 if (strcasecmp(arg, "allow") == 0)
1273 acl.action = IP_ALLOW;
1274 else if (strcasecmp(arg, "deny") == 0)
1275 acl.action = IP_DENY;
1277 fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
1278 filename, line_num, arg);
1282 get_arg(arg, sizeof(arg), &p);
1284 if (resolve_host(&acl.first, arg) != 0) {
1285 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
1286 filename, line_num, arg);
1289 acl.last = acl.first;
1291 get_arg(arg, sizeof(arg), &p);
1294 if (resolve_host(&acl.last, arg) != 0) {
1295 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
1296 filename, line_num, arg);
1302 IPAddressACL *nacl = av_mallocz(sizeof(*nacl));
1303 IPAddressACL **naclp = 0;
1309 naclp = &stream->acl;
1315 fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n",
1316 filename, line_num);
1322 naclp = &(*naclp)->next;
1330 static IPAddressACL* parse_dynamic_acl(FFStream *stream, HTTPContext *c)
1335 IPAddressACL *acl = NULL;
1339 f = fopen(stream->dynamic_acl, "r");
1341 perror(stream->dynamic_acl);
1345 acl = av_mallocz(sizeof(IPAddressACL));
1349 if (fgets(line, sizeof(line), f) == NULL)
1355 if (*p == '\0' || *p == '#')
1357 get_arg(cmd, sizeof(cmd), &p);
1359 if (!strcasecmp(cmd, "ACL"))
1360 parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl, line_num);
1367 static void free_acl_list(IPAddressACL *in_acl)
1369 IPAddressACL *pacl,*pacl2;
1379 static int validate_acl_list(IPAddressACL *in_acl, HTTPContext *c)
1381 enum IPAddressAction last_action = IP_DENY;
1383 struct in_addr *src = &c->from_addr.sin_addr;
1384 unsigned long src_addr = src->s_addr;
1386 for (acl = in_acl; acl; acl = acl->next) {
1387 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1388 return (acl->action == IP_ALLOW) ? 1 : 0;
1389 last_action = acl->action;
1392 /* Nothing matched, so return not the last action */
1393 return (last_action == IP_DENY) ? 1 : 0;
1396 static int validate_acl(FFStream *stream, HTTPContext *c)
1402 /* if stream->acl is null validate_acl_list will return 1 */
1403 ret = validate_acl_list(stream->acl, c);
1405 if (stream->dynamic_acl[0]) {
1406 acl = parse_dynamic_acl(stream, c);
1408 ret = validate_acl_list(acl, c);
1416 /* compute the real filename of a file by matching it without its
1417 extensions to all the stream filenames */
1418 static void compute_real_filename(char *filename, int max_size)
1425 /* compute filename by matching without the file extensions */
1426 av_strlcpy(file1, filename, sizeof(file1));
1427 p = strrchr(file1, '.');
1430 for(stream = first_stream; stream != NULL; stream = stream->next) {
1431 av_strlcpy(file2, stream->filename, sizeof(file2));
1432 p = strrchr(file2, '.');
1435 if (!strcmp(file1, file2)) {
1436 av_strlcpy(filename, stream->filename, max_size);
1451 /* parse http request and prepare header */
1452 static int http_parse_request(HTTPContext *c)
1455 enum RedirType redir_type;
1457 char info[1024], filename[1024];
1461 const char *mime_type;
1465 char *useragent = 0;
1468 get_word(cmd, sizeof(cmd), (const char **)&p);
1469 av_strlcpy(c->method, cmd, sizeof(c->method));
1471 if (!strcmp(cmd, "GET"))
1473 else if (!strcmp(cmd, "POST"))
1478 get_word(url, sizeof(url), (const char **)&p);
1479 av_strlcpy(c->url, url, sizeof(c->url));
1481 get_word(protocol, sizeof(protocol), (const char **)&p);
1482 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1485 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1488 http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);
1490 /* find the filename and the optional info string in the request */
1491 p = strchr(url, '?');
1493 av_strlcpy(info, p, sizeof(info));
1498 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1500 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1501 if (strncasecmp(p, "User-Agent:", 11) == 0) {
1503 if (*useragent && *useragent != '\n' && isspace(*useragent))
1507 p = strchr(p, '\n');
1514 redir_type = REDIR_NONE;
1515 if (av_match_ext(filename, "asx")) {
1516 redir_type = REDIR_ASX;
1517 filename[strlen(filename)-1] = 'f';
1518 } else if (av_match_ext(filename, "asf") &&
1519 (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1520 /* if this isn't WMP or lookalike, return the redirector file */
1521 redir_type = REDIR_ASF;
1522 } else if (av_match_ext(filename, "rpm,ram")) {
1523 redir_type = REDIR_RAM;
1524 strcpy(filename + strlen(filename)-2, "m");
1525 } else if (av_match_ext(filename, "rtsp")) {
1526 redir_type = REDIR_RTSP;
1527 compute_real_filename(filename, sizeof(filename) - 1);
1528 } else if (av_match_ext(filename, "sdp")) {
1529 redir_type = REDIR_SDP;
1530 compute_real_filename(filename, sizeof(filename) - 1);
1533 // "redirect" / request to index.html
1534 if (!strlen(filename))
1535 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1537 stream = first_stream;
1538 while (stream != NULL) {
1539 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1541 stream = stream->next;
1543 if (stream == NULL) {
1544 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1545 http_log("File '%s' not found\n", url);
1550 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1551 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1553 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1554 c->http_error = 301;
1556 q += snprintf(q, c->buffer_size,
1557 "HTTP/1.0 301 Moved\r\n"
1559 "Content-type: text/html\r\n"
1561 "<html><head><title>Moved</title></head><body>\r\n"
1562 "You should be <a href=\"%s\">redirected</a>.\r\n"
1563 "</body></html>\r\n", stream->feed_filename, stream->feed_filename);
1564 /* prepare output buffer */
1565 c->buffer_ptr = c->buffer;
1567 c->state = HTTPSTATE_SEND_HEADER;
1571 /* If this is WMP, get the rate information */
1572 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1573 if (modify_current_stream(c, ratebuf)) {
1574 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1575 if (c->switch_feed_streams[i] >= 0)
1576 do_switch_stream(c, i);
1581 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1582 current_bandwidth += stream->bandwidth;
1584 /* If already streaming this feed, do not let start another feeder. */
1585 if (stream->feed_opened) {
1586 snprintf(msg, sizeof(msg), "This feed is already being received.");
1587 http_log("Feed '%s' already being received\n", stream->feed_filename);
1591 if (c->post == 0 && max_bandwidth < current_bandwidth) {
1592 c->http_error = 200;
1594 q += snprintf(q, c->buffer_size,
1595 "HTTP/1.0 200 Server too busy\r\n"
1596 "Content-type: text/html\r\n"
1598 "<html><head><title>Too busy</title></head><body>\r\n"
1599 "<p>The server is too busy to serve your request at this time.</p>\r\n"
1600 "<p>The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "
1601 "and this exceeds the limit of %"PRIu64"kbit/sec.</p>\r\n"
1602 "</body></html>\r\n", current_bandwidth, max_bandwidth);
1603 /* prepare output buffer */
1604 c->buffer_ptr = c->buffer;
1606 c->state = HTTPSTATE_SEND_HEADER;
1610 if (redir_type != REDIR_NONE) {
1613 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1614 if (strncasecmp(p, "Host:", 5) == 0) {
1618 p = strchr(p, '\n');
1629 while (isspace(*hostinfo))
1632 eoh = strchr(hostinfo, '\n');
1634 if (eoh[-1] == '\r')
1637 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1638 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1639 hostbuf[eoh - hostinfo] = 0;
1641 c->http_error = 200;
1643 switch(redir_type) {
1645 q += snprintf(q, c->buffer_size,
1646 "HTTP/1.0 200 ASX Follows\r\n"
1647 "Content-type: video/x-ms-asf\r\n"
1649 "<ASX Version=\"3\">\r\n"
1650 //"<!-- Autogenerated by ffserver -->\r\n"
1651 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1652 "</ASX>\r\n", hostbuf, filename, info);
1655 q += snprintf(q, c->buffer_size,
1656 "HTTP/1.0 200 RAM Follows\r\n"
1657 "Content-type: audio/x-pn-realaudio\r\n"
1659 "# Autogenerated by ffserver\r\n"
1660 "http://%s/%s%s\r\n", hostbuf, filename, info);
1663 q += snprintf(q, c->buffer_size,
1664 "HTTP/1.0 200 ASF Redirect follows\r\n"
1665 "Content-type: video/x-ms-asf\r\n"
1668 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1672 char hostname[256], *p;
1673 /* extract only hostname */
1674 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1675 p = strrchr(hostname, ':');
1678 q += snprintf(q, c->buffer_size,
1679 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1680 /* XXX: incorrect mime type ? */
1681 "Content-type: application/x-rtsp\r\n"
1683 "rtsp://%s:%d/%s\r\n", hostname, ntohs(my_rtsp_addr.sin_port), filename);
1689 int sdp_data_size, len;
1690 struct sockaddr_in my_addr;
1692 q += snprintf(q, c->buffer_size,
1693 "HTTP/1.0 200 OK\r\n"
1694 "Content-type: application/sdp\r\n"
1697 len = sizeof(my_addr);
1698 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
1700 /* XXX: should use a dynamic buffer */
1701 sdp_data_size = prepare_sdp_description(stream,
1704 if (sdp_data_size > 0) {
1705 memcpy(q, sdp_data, sdp_data_size);
1717 /* prepare output buffer */
1718 c->buffer_ptr = c->buffer;
1720 c->state = HTTPSTATE_SEND_HEADER;
1726 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1730 stream->conns_served++;
1732 /* XXX: add there authenticate and IP match */
1735 /* if post, it means a feed is being sent */
1736 if (!stream->is_feed) {
1737 /* However it might be a status report from WMP! Let us log the
1738 * data as it might come in handy one day. */
1742 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1743 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1747 if (strncasecmp(p, "Pragma: client-id=", 18) == 0)
1748 client_id = strtol(p + 18, 0, 10);
1749 p = strchr(p, '\n');
1757 char *eol = strchr(logline, '\n');
1762 if (eol[-1] == '\r')
1764 http_log("%.*s\n", (int) (eol - logline), logline);
1765 c->suppress_log = 1;
1770 http_log("\nGot request:\n%s\n", c->buffer);
1773 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1776 /* Now we have to find the client_id */
1777 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1778 if (wmpc->wmp_client_id == client_id)
1782 if (wmpc && modify_current_stream(wmpc, ratebuf))
1783 wmpc->switch_pending = 1;
1786 snprintf(msg, sizeof(msg), "POST command not handled");
1790 if (http_start_receive_data(c) < 0) {
1791 snprintf(msg, sizeof(msg), "could not open feed");
1795 c->state = HTTPSTATE_RECEIVE_DATA;
1800 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1801 http_log("\nGot request:\n%s\n", c->buffer);
1804 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1807 /* open input stream */
1808 if (open_input_stream(c, info) < 0) {
1809 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1813 /* prepare http header */
1815 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
1816 mime_type = c->stream->fmt->mime_type;
1818 mime_type = "application/x-octet-stream";
1819 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Pragma: no-cache\r\n");
1821 /* for asf, we need extra headers */
1822 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1823 /* Need to allocate a client id */
1825 c->wmp_client_id = av_lfg_get(&random_state);
1827 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);
1829 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-Type: %s\r\n", mime_type);
1830 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1832 /* prepare output buffer */
1834 c->buffer_ptr = c->buffer;
1836 c->state = HTTPSTATE_SEND_HEADER;
1839 c->http_error = 404;
1841 q += snprintf(q, c->buffer_size,
1842 "HTTP/1.0 404 Not Found\r\n"
1843 "Content-type: text/html\r\n"
1846 "<head><title>404 Not Found</title></head>\n"
1849 /* prepare output buffer */
1850 c->buffer_ptr = c->buffer;
1852 c->state = HTTPSTATE_SEND_HEADER;
1856 c->http_error = 200; /* horrible : we use this value to avoid
1857 going to the send data state */
1858 c->state = HTTPSTATE_SEND_HEADER;
1862 static void fmt_bytecount(ByteIOContext *pb, int64_t count)
1864 static const char *suffix = " kMGTP";
1867 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1869 url_fprintf(pb, "%"PRId64"%c", count, *s);
1872 static void compute_status(HTTPContext *c)
1881 if (url_open_dyn_buf(&pb) < 0) {
1882 /* XXX: return an error ? */
1883 c->buffer_ptr = c->buffer;
1884 c->buffer_end = c->buffer;
1888 url_fprintf(pb, "HTTP/1.0 200 OK\r\n");
1889 url_fprintf(pb, "Content-type: %s\r\n", "text/html");
1890 url_fprintf(pb, "Pragma: no-cache\r\n");
1891 url_fprintf(pb, "\r\n");
1893 url_fprintf(pb, "<html><head><title>%s Status</title>\n", program_name);
1894 if (c->stream->feed_filename[0])
1895 url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
1896 url_fprintf(pb, "</head>\n<body>");
1897 url_fprintf(pb, "<h1>%s Status</h1>\n", program_name);
1899 url_fprintf(pb, "<h2>Available Streams</h2>\n");
1900 url_fprintf(pb, "<table cellspacing=0 cellpadding=4>\n");
1901 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");
1902 stream = first_stream;
1903 while (stream != NULL) {
1904 char sfilename[1024];
1907 if (stream->feed != stream) {
1908 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1909 eosf = sfilename + strlen(sfilename);
1910 if (eosf - sfilename >= 4) {
1911 if (strcmp(eosf - 4, ".asf") == 0)
1912 strcpy(eosf - 4, ".asx");
1913 else if (strcmp(eosf - 3, ".rm") == 0)
1914 strcpy(eosf - 3, ".ram");
1915 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1916 /* generate a sample RTSP director if
1917 unicast. Generate an SDP redirector if
1919 eosf = strrchr(sfilename, '.');
1921 eosf = sfilename + strlen(sfilename);
1922 if (stream->is_multicast)
1923 strcpy(eosf, ".sdp");
1925 strcpy(eosf, ".rtsp");
1929 url_fprintf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1930 sfilename, stream->filename);
1931 url_fprintf(pb, "<td align=right> %d <td align=right> ",
1932 stream->conns_served);
1933 fmt_bytecount(pb, stream->bytes_served);
1934 switch(stream->stream_type) {
1935 case STREAM_TYPE_LIVE: {
1936 int audio_bit_rate = 0;
1937 int video_bit_rate = 0;
1938 const char *audio_codec_name = "";
1939 const char *video_codec_name = "";
1940 const char *audio_codec_name_extra = "";
1941 const char *video_codec_name_extra = "";
1943 for(i=0;i<stream->nb_streams;i++) {
1944 AVStream *st = stream->streams[i];
1945 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1946 switch(st->codec->codec_type) {
1947 case AVMEDIA_TYPE_AUDIO:
1948 audio_bit_rate += st->codec->bit_rate;
1950 if (*audio_codec_name)
1951 audio_codec_name_extra = "...";
1952 audio_codec_name = codec->name;
1955 case AVMEDIA_TYPE_VIDEO:
1956 video_bit_rate += st->codec->bit_rate;
1958 if (*video_codec_name)
1959 video_codec_name_extra = "...";
1960 video_codec_name = codec->name;
1963 case AVMEDIA_TYPE_DATA:
1964 video_bit_rate += st->codec->bit_rate;
1970 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",
1973 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
1974 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
1976 url_fprintf(pb, "<td>%s", stream->feed->filename);
1978 url_fprintf(pb, "<td>%s", stream->feed_filename);
1979 url_fprintf(pb, "\n");
1983 url_fprintf(pb, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
1987 stream = stream->next;
1989 url_fprintf(pb, "</table>\n");
1991 stream = first_stream;
1992 while (stream != NULL) {
1993 if (stream->feed == stream) {
1994 url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
1996 url_fprintf(pb, "Running as pid %d.\n", stream->pid);
1998 #if defined(linux) && !defined(CONFIG_NOCUTILS)
2003 /* This is somewhat linux specific I guess */
2004 snprintf(ps_cmd, sizeof(ps_cmd),
2005 "ps -o \"%%cpu,cputime\" --no-headers %d",
2008 pid_stat = popen(ps_cmd, "r");
2013 if (fscanf(pid_stat, "%10s %64s", cpuperc,
2015 url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
2023 url_fprintf(pb, "<p>");
2025 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");
2027 for (i = 0; i < stream->nb_streams; i++) {
2028 AVStream *st = stream->streams[i];
2029 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
2030 const char *type = "unknown";
2031 char parameters[64];
2035 switch(st->codec->codec_type) {
2036 case AVMEDIA_TYPE_AUDIO:
2038 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz", st->codec->channels, st->codec->sample_rate);
2040 case AVMEDIA_TYPE_VIDEO:
2042 snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec->width, st->codec->height,
2043 st->codec->qmin, st->codec->qmax, st->codec->time_base.den / st->codec->time_base.num);
2048 url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
2049 i, type, st->codec->bit_rate/1000, codec ? codec->name : "", parameters);
2051 url_fprintf(pb, "</table>\n");
2054 stream = stream->next;
2057 /* connection status */
2058 url_fprintf(pb, "<h2>Connection Status</h2>\n");
2060 url_fprintf(pb, "Number of connections: %d / %d<br>\n",
2061 nb_connections, nb_max_connections);
2063 url_fprintf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2064 current_bandwidth, max_bandwidth);
2066 url_fprintf(pb, "<table>\n");
2067 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");
2068 c1 = first_http_ctx;
2070 while (c1 != NULL) {
2076 for (j = 0; j < c1->stream->nb_streams; j++) {
2077 if (!c1->stream->feed)
2078 bitrate += c1->stream->streams[j]->codec->bit_rate;
2079 else if (c1->feed_streams[j] >= 0)
2080 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
2085 p = inet_ntoa(c1->from_addr.sin_addr);
2086 url_fprintf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
2088 c1->stream ? c1->stream->filename : "",
2089 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
2092 http_state[c1->state]);
2093 fmt_bytecount(pb, bitrate);
2094 url_fprintf(pb, "<td align=right>");
2095 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2096 url_fprintf(pb, "<td align=right>");
2097 fmt_bytecount(pb, c1->data_count);
2098 url_fprintf(pb, "\n");
2101 url_fprintf(pb, "</table>\n");
2106 url_fprintf(pb, "<hr size=1 noshade>Generated at %s", p);
2107 url_fprintf(pb, "</body>\n</html>\n");
2109 len = url_close_dyn_buf(pb, &c->pb_buffer);
2110 c->buffer_ptr = c->pb_buffer;
2111 c->buffer_end = c->pb_buffer + len;
2114 /* check if the parser needs to be opened for stream i */
2115 static void open_parser(AVFormatContext *s, int i)
2117 AVStream *st = s->streams[i];
2120 if (!st->codec->codec) {
2121 codec = avcodec_find_decoder(st->codec->codec_id);
2122 if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) {
2123 st->codec->parse_only = 1;
2124 if (avcodec_open(st->codec, codec) < 0)
2125 st->codec->parse_only = 0;
2130 static int open_input_stream(HTTPContext *c, const char *info)
2133 char input_filename[1024];
2135 int buf_size, i, ret;
2138 /* find file name */
2139 if (c->stream->feed) {
2140 strcpy(input_filename, c->stream->feed->feed_filename);
2141 buf_size = FFM_PACKET_SIZE;
2142 /* compute position (absolute time) */
2143 if (find_info_tag(buf, sizeof(buf), "date", info)) {
2144 stream_pos = parse_date(buf, 0);
2145 if (stream_pos == INT64_MIN)
2147 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
2148 int prebuffer = strtol(buf, 0, 10);
2149 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2151 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2153 strcpy(input_filename, c->stream->feed_filename);
2155 /* compute position (relative time) */
2156 if (find_info_tag(buf, sizeof(buf), "date", info)) {
2157 stream_pos = parse_date(buf, 1);
2158 if (stream_pos == INT64_MIN)
2163 if (input_filename[0] == '\0')
2167 if ((ret = av_open_input_file(&s, input_filename, c->stream->ifmt,
2168 buf_size, c->stream->ap_in)) < 0) {
2169 http_log("could not open %s: %d\n", input_filename, ret);
2172 s->flags |= AVFMT_FLAG_GENPTS;
2174 if (strcmp(s->iformat->name, "ffm") && av_find_stream_info(c->fmt_in) < 0) {
2175 http_log("Could not find stream info '%s'\n", input_filename);
2176 av_close_input_file(s);
2180 /* open each parser */
2181 for(i=0;i<s->nb_streams;i++)
2184 /* choose stream as clock source (we favorize video stream if
2185 present) for packet sending */
2186 c->pts_stream_index = 0;
2187 for(i=0;i<c->stream->nb_streams;i++) {
2188 if (c->pts_stream_index == 0 &&
2189 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2190 c->pts_stream_index = i;
2195 if (c->fmt_in->iformat->read_seek)
2196 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2198 /* set the start time (needed for maxtime and RTP packet timing) */
2199 c->start_time = cur_time;
2200 c->first_pts = AV_NOPTS_VALUE;
2204 /* return the server clock (in us) */
2205 static int64_t get_server_clock(HTTPContext *c)
2207 /* compute current pts value from system time */
2208 return (cur_time - c->start_time) * 1000;
2211 /* return the estimated time at which the current packet must be sent
2213 static int64_t get_packet_send_clock(HTTPContext *c)
2215 int bytes_left, bytes_sent, frame_bytes;
2217 frame_bytes = c->cur_frame_bytes;
2218 if (frame_bytes <= 0)
2221 bytes_left = c->buffer_end - c->buffer_ptr;
2222 bytes_sent = frame_bytes - bytes_left;
2223 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2228 static int http_prepare_data(HTTPContext *c)
2231 AVFormatContext *ctx;
2233 av_freep(&c->pb_buffer);
2235 case HTTPSTATE_SEND_DATA_HEADER:
2236 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
2237 av_metadata_set2(&c->fmt_ctx.metadata, "author" , c->stream->author , 0);
2238 av_metadata_set2(&c->fmt_ctx.metadata, "comment" , c->stream->comment , 0);
2239 av_metadata_set2(&c->fmt_ctx.metadata, "copyright", c->stream->copyright, 0);
2240 av_metadata_set2(&c->fmt_ctx.metadata, "title" , c->stream->title , 0);
2242 for(i=0;i<c->stream->nb_streams;i++) {
2245 st = av_mallocz(sizeof(AVStream));
2246 c->fmt_ctx.streams[i] = st;
2247 /* if file or feed, then just take streams from FFStream struct */
2248 if (!c->stream->feed ||
2249 c->stream->feed == c->stream)
2250 src = c->stream->streams[i];
2252 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2256 st->codec->frame_number = 0; /* XXX: should be done in
2257 AVStream, not in codec */
2259 /* set output format parameters */
2260 c->fmt_ctx.oformat = c->stream->fmt;
2261 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2263 c->got_key_frame = 0;
2265 /* prepare header and save header data in a stream */
2266 if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2267 /* XXX: potential leak */
2270 c->fmt_ctx.pb->is_streamed = 1;
2273 * HACK to avoid mpeg ps muxer to spit many underflow errors
2274 * Default value from FFmpeg
2275 * Try to set it use configuration option
2277 c->fmt_ctx.preload = (int)(0.5*AV_TIME_BASE);
2278 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2280 av_set_parameters(&c->fmt_ctx, NULL);
2281 if (av_write_header(&c->fmt_ctx) < 0) {
2282 http_log("Error writing output header\n");
2285 av_metadata_free(&c->fmt_ctx.metadata);
2287 len = url_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2288 c->buffer_ptr = c->pb_buffer;
2289 c->buffer_end = c->pb_buffer + len;
2291 c->state = HTTPSTATE_SEND_DATA;
2292 c->last_packet_sent = 0;
2294 case HTTPSTATE_SEND_DATA:
2295 /* find a new packet */
2296 /* read a packet from the input stream */
2297 if (c->stream->feed)
2298 ffm_set_write_index(c->fmt_in,
2299 c->stream->feed->feed_write_index,
2300 c->stream->feed->feed_size);
2302 if (c->stream->max_time &&
2303 c->stream->max_time + c->start_time - cur_time < 0)
2304 /* We have timed out */
2305 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2309 if (av_read_frame(c->fmt_in, &pkt) < 0) {
2310 if (c->stream->feed && c->stream->feed->feed_opened) {
2311 /* if coming from feed, it means we reached the end of the
2312 ffm file, so must wait for more data */
2313 c->state = HTTPSTATE_WAIT_FEED;
2314 return 1; /* state changed */
2316 if (c->stream->loop) {
2317 av_close_input_file(c->fmt_in);
2319 if (open_input_stream(c, "") < 0)
2324 /* must send trailer now because eof or error */
2325 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2329 int source_index = pkt.stream_index;
2330 /* update first pts if needed */
2331 if (c->first_pts == AV_NOPTS_VALUE) {
2332 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2333 c->start_time = cur_time;
2335 /* send it to the appropriate stream */
2336 if (c->stream->feed) {
2337 /* if coming from a feed, select the right stream */
2338 if (c->switch_pending) {
2339 c->switch_pending = 0;
2340 for(i=0;i<c->stream->nb_streams;i++) {
2341 if (c->switch_feed_streams[i] == pkt.stream_index)
2342 if (pkt.flags & AV_PKT_FLAG_KEY)
2343 do_switch_stream(c, i);
2344 if (c->switch_feed_streams[i] >= 0)
2345 c->switch_pending = 1;
2348 for(i=0;i<c->stream->nb_streams;i++) {
2349 if (c->stream->feed_streams[i] == pkt.stream_index) {
2350 AVStream *st = c->fmt_in->streams[source_index];
2351 pkt.stream_index = i;
2352 if (pkt.flags & AV_PKT_FLAG_KEY &&
2353 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2354 c->stream->nb_streams == 1))
2355 c->got_key_frame = 1;
2356 if (!c->stream->send_on_key || c->got_key_frame)
2361 AVCodecContext *codec;
2362 AVStream *ist, *ost;
2364 ist = c->fmt_in->streams[source_index];
2365 /* specific handling for RTP: we use several
2366 output stream (one for each RTP
2367 connection). XXX: need more abstract handling */
2368 if (c->is_packetized) {
2369 /* compute send time and duration */
2370 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2371 c->cur_pts -= c->first_pts;
2372 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2373 /* find RTP context */
2374 c->packet_stream_index = pkt.stream_index;
2375 ctx = c->rtp_ctx[c->packet_stream_index];
2377 av_free_packet(&pkt);
2380 codec = ctx->streams[0]->codec;
2381 /* only one stream per RTP connection */
2382 pkt.stream_index = 0;
2386 codec = ctx->streams[pkt.stream_index]->codec;
2389 if (c->is_packetized) {
2390 int max_packet_size;
2391 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2392 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2394 max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]);
2395 ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size);
2397 ret = url_open_dyn_buf(&ctx->pb);
2400 /* XXX: potential leak */
2403 ost = ctx->streams[pkt.stream_index];
2405 ctx->pb->is_streamed = 1;
2406 if (pkt.dts != AV_NOPTS_VALUE)
2407 pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base);
2408 if (pkt.pts != AV_NOPTS_VALUE)
2409 pkt.pts = av_rescale_q(pkt.pts, ist->time_base, ost->time_base);
2410 pkt.duration = av_rescale_q(pkt.duration, ist->time_base, ost->time_base);
2411 if (av_write_frame(ctx, &pkt) < 0) {
2412 http_log("Error writing frame to output\n");
2413 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2416 len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
2417 c->cur_frame_bytes = len;
2418 c->buffer_ptr = c->pb_buffer;
2419 c->buffer_end = c->pb_buffer + len;
2421 codec->frame_number++;
2423 av_free_packet(&pkt);
2427 av_free_packet(&pkt);
2432 case HTTPSTATE_SEND_DATA_TRAILER:
2433 /* last packet test ? */
2434 if (c->last_packet_sent || c->is_packetized)
2437 /* prepare header */
2438 if (url_open_dyn_buf(&ctx->pb) < 0) {
2439 /* XXX: potential leak */
2442 c->fmt_ctx.pb->is_streamed = 1;
2443 av_write_trailer(ctx);
2444 len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
2445 c->buffer_ptr = c->pb_buffer;
2446 c->buffer_end = c->pb_buffer + len;
2448 c->last_packet_sent = 1;
2454 /* should convert the format at the same time */
2455 /* send data starting at c->buffer_ptr to the output connection
2456 (either UDP or TCP connection) */
2457 static int http_send_data(HTTPContext *c)
2462 if (c->buffer_ptr >= c->buffer_end) {
2463 ret = http_prepare_data(c);
2467 /* state change requested */
2470 if (c->is_packetized) {
2471 /* RTP data output */
2472 len = c->buffer_end - c->buffer_ptr;
2474 /* fail safe - should never happen */
2476 c->buffer_ptr = c->buffer_end;
2479 len = (c->buffer_ptr[0] << 24) |
2480 (c->buffer_ptr[1] << 16) |
2481 (c->buffer_ptr[2] << 8) |
2483 if (len > (c->buffer_end - c->buffer_ptr))
2485 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2486 /* nothing to send yet: we can wait */
2490 c->data_count += len;
2491 update_datarate(&c->datarate, c->data_count);
2493 c->stream->bytes_served += len;
2495 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2496 /* RTP packets are sent inside the RTSP TCP connection */
2498 int interleaved_index, size;
2500 HTTPContext *rtsp_c;
2503 /* if no RTSP connection left, error */
2506 /* if already sending something, then wait. */
2507 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2509 if (url_open_dyn_buf(&pb) < 0)
2511 interleaved_index = c->packet_stream_index * 2;
2512 /* RTCP packets are sent at odd indexes */
2513 if (c->buffer_ptr[1] == 200)
2514 interleaved_index++;
2515 /* write RTSP TCP header */
2517 header[1] = interleaved_index;
2518 header[2] = len >> 8;
2520 put_buffer(pb, header, 4);
2521 /* write RTP packet data */
2523 put_buffer(pb, c->buffer_ptr, len);
2524 size = url_close_dyn_buf(pb, &c->packet_buffer);
2525 /* prepare asynchronous TCP sending */
2526 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2527 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2528 c->buffer_ptr += len;
2530 /* send everything we can NOW */
2531 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2532 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2534 rtsp_c->packet_buffer_ptr += len;
2535 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2536 /* if we could not send all the data, we will
2537 send it later, so a new state is needed to
2538 "lock" the RTSP TCP connection */
2539 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2542 /* all data has been sent */
2543 av_freep(&c->packet_buffer);
2545 /* send RTP packet directly in UDP */
2547 url_write(c->rtp_handles[c->packet_stream_index],
2548 c->buffer_ptr, len);
2549 c->buffer_ptr += len;
2550 /* here we continue as we can send several packets per 10 ms slot */
2553 /* TCP data output */
2554 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
2556 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2557 ff_neterrno() != FF_NETERROR(EINTR))
2558 /* error : close connection */
2563 c->buffer_ptr += len;
2565 c->data_count += len;
2566 update_datarate(&c->datarate, c->data_count);
2568 c->stream->bytes_served += len;
2576 static int http_start_receive_data(HTTPContext *c)
2580 if (c->stream->feed_opened)
2583 /* Don't permit writing to this one */
2584 if (c->stream->readonly)
2588 fd = open(c->stream->feed_filename, O_RDWR);
2590 http_log("Error opening feeder file: %s\n", strerror(errno));
2595 if (c->stream->truncate) {
2596 /* truncate feed file */
2597 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2598 ftruncate(c->feed_fd, FFM_PACKET_SIZE);
2599 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2601 if ((c->stream->feed_write_index = ffm_read_write_index(fd)) < 0) {
2602 http_log("Error reading write index from feed file: %s\n", strerror(errno));
2607 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
2608 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2609 lseek(fd, 0, SEEK_SET);
2611 /* init buffer input */
2612 c->buffer_ptr = c->buffer;
2613 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2614 c->stream->feed_opened = 1;
2615 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2619 static int http_receive_data(HTTPContext *c)
2622 int len, loop_run = 0;
2624 while (c->chunked_encoding && !c->chunk_size &&
2625 c->buffer_end > c->buffer_ptr) {
2626 /* read chunk header, if present */
2627 len = recv(c->fd, c->buffer_ptr, 1, 0);
2630 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2631 ff_neterrno() != FF_NETERROR(EINTR))
2632 /* error : close connection */
2635 } else if (len == 0) {
2636 /* end of connection : close it */
2638 } else if (c->buffer_ptr - c->buffer >= 2 &&
2639 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2640 c->chunk_size = strtol(c->buffer, 0, 16);
2641 if (c->chunk_size == 0) // end of stream
2643 c->buffer_ptr = c->buffer;
2645 } else if (++loop_run > 10) {
2646 /* no chunk header, abort */
2653 if (c->buffer_end > c->buffer_ptr) {
2654 len = recv(c->fd, c->buffer_ptr,
2655 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2657 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2658 ff_neterrno() != FF_NETERROR(EINTR))
2659 /* error : close connection */
2661 } else if (len == 0)
2662 /* end of connection : close it */
2665 c->chunk_size -= len;
2666 c->buffer_ptr += len;
2667 c->data_count += len;
2668 update_datarate(&c->datarate, c->data_count);
2672 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2673 if (c->buffer[0] != 'f' ||
2674 c->buffer[1] != 'm') {
2675 http_log("Feed stream has become desynchronized -- disconnecting\n");
2680 if (c->buffer_ptr >= c->buffer_end) {
2681 FFStream *feed = c->stream;
2682 /* a packet has been received : write it in the store, except
2684 if (c->data_count > FFM_PACKET_SIZE) {
2686 // printf("writing pos=0x%"PRIx64" size=0x%"PRIx64"\n", feed->feed_write_index, feed->feed_size);
2687 /* XXX: use llseek or url_seek */
2688 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
2689 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2690 http_log("Error writing to feed file: %s\n", strerror(errno));
2694 feed->feed_write_index += FFM_PACKET_SIZE;
2695 /* update file size */
2696 if (feed->feed_write_index > c->stream->feed_size)
2697 feed->feed_size = feed->feed_write_index;
2699 /* handle wrap around if max file size reached */
2700 if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size)
2701 feed->feed_write_index = FFM_PACKET_SIZE;
2704 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2705 http_log("Error writing index to feed file: %s\n", strerror(errno));
2709 /* wake up any waiting connections */
2710 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2711 if (c1->state == HTTPSTATE_WAIT_FEED &&
2712 c1->stream->feed == c->stream->feed)
2713 c1->state = HTTPSTATE_SEND_DATA;
2716 /* We have a header in our hands that contains useful data */
2717 AVFormatContext *s = NULL;
2719 AVInputFormat *fmt_in;
2722 /* use feed output format name to find corresponding input format */
2723 fmt_in = av_find_input_format(feed->fmt->name);
2727 url_open_buf(&pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
2728 pb->is_streamed = 1;
2730 if (av_open_input_stream(&s, pb, c->stream->feed_filename, fmt_in, NULL) < 0) {
2735 /* Now we have the actual streams */
2736 if (s->nb_streams != feed->nb_streams) {
2737 av_close_input_stream(s);
2739 http_log("Feed '%s' stream number does not match registered feed\n",
2740 c->stream->feed_filename);
2744 for (i = 0; i < s->nb_streams; i++) {
2745 AVStream *fst = feed->streams[i];
2746 AVStream *st = s->streams[i];
2747 memcpy(fst->codec, st->codec, sizeof(AVCodecContext));
2748 if (fst->codec->extradata_size) {
2749 fst->codec->extradata = av_malloc(fst->codec->extradata_size);
2750 if (!fst->codec->extradata)
2752 memcpy(fst->codec->extradata, st->codec->extradata,
2753 fst->codec->extradata_size);
2757 av_close_input_stream(s);
2760 c->buffer_ptr = c->buffer;
2765 c->stream->feed_opened = 0;
2767 /* wake up any waiting connections to stop waiting for feed */
2768 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2769 if (c1->state == HTTPSTATE_WAIT_FEED &&
2770 c1->stream->feed == c->stream->feed)
2771 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2776 /********************************************************************/
2779 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2786 switch(error_number) {
2787 case RTSP_STATUS_OK:
2790 case RTSP_STATUS_METHOD:
2791 str = "Method Not Allowed";
2793 case RTSP_STATUS_BANDWIDTH:
2794 str = "Not Enough Bandwidth";
2796 case RTSP_STATUS_SESSION:
2797 str = "Session Not Found";
2799 case RTSP_STATUS_STATE:
2800 str = "Method Not Valid in This State";
2802 case RTSP_STATUS_AGGREGATE:
2803 str = "Aggregate operation not allowed";
2805 case RTSP_STATUS_ONLY_AGGREGATE:
2806 str = "Only aggregate operation allowed";
2808 case RTSP_STATUS_TRANSPORT:
2809 str = "Unsupported transport";
2811 case RTSP_STATUS_INTERNAL:
2812 str = "Internal Server Error";
2814 case RTSP_STATUS_SERVICE:
2815 str = "Service Unavailable";
2817 case RTSP_STATUS_VERSION:
2818 str = "RTSP Version not supported";
2821 str = "Unknown Error";
2825 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2826 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2828 /* output GMT time */
2831 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2832 url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
2835 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2837 rtsp_reply_header(c, error_number);
2838 url_fprintf(c->pb, "\r\n");
2841 static int rtsp_parse_request(HTTPContext *c)
2843 const char *p, *p1, *p2;
2849 RTSPMessageHeader header1, *header = &header1;
2851 c->buffer_ptr[0] = '\0';
2854 get_word(cmd, sizeof(cmd), &p);
2855 get_word(url, sizeof(url), &p);
2856 get_word(protocol, sizeof(protocol), &p);
2858 av_strlcpy(c->method, cmd, sizeof(c->method));
2859 av_strlcpy(c->url, url, sizeof(c->url));
2860 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2862 if (url_open_dyn_buf(&c->pb) < 0) {
2863 /* XXX: cannot do more */
2864 c->pb = NULL; /* safety */
2868 /* check version name */
2869 if (strcmp(protocol, "RTSP/1.0") != 0) {
2870 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2874 /* parse each header line */
2875 memset(header, 0, sizeof(*header));
2876 /* skip to next line */
2877 while (*p != '\n' && *p != '\0')
2881 while (*p != '\0') {
2882 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2886 if (p2 > p && p2[-1] == '\r')
2888 /* skip empty line */
2892 if (len > sizeof(line) - 1)
2893 len = sizeof(line) - 1;
2894 memcpy(line, p, len);
2896 ff_rtsp_parse_line(header, line, NULL);
2900 /* handle sequence number */
2901 c->seq = header->seq;
2903 if (!strcmp(cmd, "DESCRIBE"))
2904 rtsp_cmd_describe(c, url);
2905 else if (!strcmp(cmd, "OPTIONS"))
2906 rtsp_cmd_options(c, url);
2907 else if (!strcmp(cmd, "SETUP"))
2908 rtsp_cmd_setup(c, url, header);
2909 else if (!strcmp(cmd, "PLAY"))
2910 rtsp_cmd_play(c, url, header);
2911 else if (!strcmp(cmd, "PAUSE"))
2912 rtsp_cmd_pause(c, url, header);
2913 else if (!strcmp(cmd, "TEARDOWN"))
2914 rtsp_cmd_teardown(c, url, header);
2916 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2919 len = url_close_dyn_buf(c->pb, &c->pb_buffer);
2920 c->pb = NULL; /* safety */
2922 /* XXX: cannot do more */
2925 c->buffer_ptr = c->pb_buffer;
2926 c->buffer_end = c->pb_buffer + len;
2927 c->state = RTSPSTATE_SEND_REPLY;
2931 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
2932 struct in_addr my_ip)
2934 AVFormatContext *avc;
2935 AVStream avs[MAX_STREAMS];
2938 avc = avformat_alloc_context();
2942 av_metadata_set2(&avc->metadata, "title",
2943 stream->title[0] ? stream->title : "No Title", 0);
2944 avc->nb_streams = stream->nb_streams;
2945 if (stream->is_multicast) {
2946 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2947 inet_ntoa(stream->multicast_ip),
2948 stream->multicast_port, stream->multicast_ttl);
2950 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
2953 for(i = 0; i < stream->nb_streams; i++) {
2954 avc->streams[i] = &avs[i];
2955 avc->streams[i]->codec = stream->streams[i]->codec;
2957 *pbuffer = av_mallocz(2048);
2958 avf_sdp_create(&avc, 1, *pbuffer, 2048);
2959 av_metadata_free(&avc->metadata);
2962 return strlen(*pbuffer);
2965 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2967 // rtsp_reply_header(c, RTSP_STATUS_OK);
2968 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2969 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2970 url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2971 url_fprintf(c->pb, "\r\n");
2974 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2980 int content_length, len;
2981 struct sockaddr_in my_addr;
2983 /* find which url is asked */
2984 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2989 for(stream = first_stream; stream != NULL; stream = stream->next) {
2990 if (!stream->is_feed &&
2991 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
2992 !strcmp(path, stream->filename)) {
2996 /* no stream found */
2997 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3001 /* prepare the media description in sdp format */
3003 /* get the host IP */
3004 len = sizeof(my_addr);
3005 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3006 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
3007 if (content_length < 0) {
3008 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3011 rtsp_reply_header(c, RTSP_STATUS_OK);
3012 url_fprintf(c->pb, "Content-Base: %s/\r\n", url);
3013 url_fprintf(c->pb, "Content-Type: application/sdp\r\n");
3014 url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);
3015 url_fprintf(c->pb, "\r\n");
3016 put_buffer(c->pb, content, content_length);
3020 static HTTPContext *find_rtp_session(const char *session_id)
3024 if (session_id[0] == '\0')
3027 for(c = first_http_ctx; c != NULL; c = c->next) {
3028 if (!strcmp(c->session_id, session_id))
3034 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3036 RTSPTransportField *th;
3039 for(i=0;i<h->nb_transports;i++) {
3040 th = &h->transports[i];
3041 if (th->lower_transport == lower_transport)
3047 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3048 RTSPMessageHeader *h)
3051 int stream_index, rtp_port, rtcp_port;
3056 RTSPTransportField *th;
3057 struct sockaddr_in dest_addr;
3058 RTSPActionServerSetup setup;
3060 /* find which url is asked */
3061 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3066 /* now check each stream */
3067 for(stream = first_stream; stream != NULL; stream = stream->next) {
3068 if (!stream->is_feed &&
3069 stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3070 /* accept aggregate filenames only if single stream */
3071 if (!strcmp(path, stream->filename)) {
3072 if (stream->nb_streams != 1) {
3073 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3080 for(stream_index = 0; stream_index < stream->nb_streams;
3082 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3083 stream->filename, stream_index);
3084 if (!strcmp(path, buf))
3089 /* no stream found */
3090 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3094 /* generate session id if needed */
3095 if (h->session_id[0] == '\0')
3096 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3097 av_lfg_get(&random_state), av_lfg_get(&random_state));
3099 /* find rtp session, and create it if none found */
3100 rtp_c = find_rtp_session(h->session_id);
3102 /* always prefer UDP */
3103 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3105 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3107 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3112 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3113 th->lower_transport);
3115 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3119 /* open input stream */
3120 if (open_input_stream(rtp_c, "") < 0) {
3121 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3126 /* test if stream is OK (test needed because several SETUP needs
3127 to be done for a given file) */
3128 if (rtp_c->stream != stream) {
3129 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3133 /* test if stream is already set up */
3134 if (rtp_c->rtp_ctx[stream_index]) {
3135 rtsp_reply_error(c, RTSP_STATUS_STATE);
3139 /* check transport */
3140 th = find_transport(h, rtp_c->rtp_protocol);
3141 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3142 th->client_port_min <= 0)) {
3143 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3147 /* setup default options */
3148 setup.transport_option[0] = '\0';
3149 dest_addr = rtp_c->from_addr;
3150 dest_addr.sin_port = htons(th->client_port_min);
3153 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3154 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3158 /* now everything is OK, so we can send the connection parameters */
3159 rtsp_reply_header(c, RTSP_STATUS_OK);
3161 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3163 switch(rtp_c->rtp_protocol) {
3164 case RTSP_LOWER_TRANSPORT_UDP:
3165 rtp_port = rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3166 rtcp_port = rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3167 url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3168 "client_port=%d-%d;server_port=%d-%d",
3169 th->client_port_min, th->client_port_max,
3170 rtp_port, rtcp_port);
3172 case RTSP_LOWER_TRANSPORT_TCP:
3173 url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3174 stream_index * 2, stream_index * 2 + 1);
3179 if (setup.transport_option[0] != '\0')
3180 url_fprintf(c->pb, ";%s", setup.transport_option);
3181 url_fprintf(c->pb, "\r\n");
3184 url_fprintf(c->pb, "\r\n");
3188 /* find an rtp connection by using the session ID. Check consistency
3190 static HTTPContext *find_rtp_session_with_url(const char *url,
3191 const char *session_id)
3199 rtp_c = find_rtp_session(session_id);
3203 /* find which url is asked */
3204 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3208 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3209 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3210 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3211 rtp_c->stream->filename, s);
3212 if(!strncmp(path, buf, sizeof(buf))) {
3213 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
3220 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3224 rtp_c = find_rtp_session_with_url(url, h->session_id);
3226 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3230 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3231 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3232 rtp_c->state != HTTPSTATE_READY) {
3233 rtsp_reply_error(c, RTSP_STATUS_STATE);
3237 rtp_c->state = HTTPSTATE_SEND_DATA;
3239 /* now everything is OK, so we can send the connection parameters */
3240 rtsp_reply_header(c, RTSP_STATUS_OK);
3242 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3243 url_fprintf(c->pb, "\r\n");
3246 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3250 rtp_c = find_rtp_session_with_url(url, h->session_id);
3252 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3256 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3257 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3258 rtsp_reply_error(c, RTSP_STATUS_STATE);
3262 rtp_c->state = HTTPSTATE_READY;
3263 rtp_c->first_pts = AV_NOPTS_VALUE;
3264 /* now everything is OK, so we can send the connection parameters */
3265 rtsp_reply_header(c, RTSP_STATUS_OK);
3267 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3268 url_fprintf(c->pb, "\r\n");
3271 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3274 char session_id[32];
3276 rtp_c = find_rtp_session_with_url(url, h->session_id);
3278 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3282 av_strlcpy(session_id, rtp_c->session_id, sizeof(session_id));
3284 /* abort the session */
3285 close_connection(rtp_c);
3287 /* now everything is OK, so we can send the connection parameters */
3288 rtsp_reply_header(c, RTSP_STATUS_OK);
3290 url_fprintf(c->pb, "Session: %s\r\n", session_id);
3291 url_fprintf(c->pb, "\r\n");
3295 /********************************************************************/
3298 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3299 FFStream *stream, const char *session_id,
3300 enum RTSPLowerTransport rtp_protocol)
3302 HTTPContext *c = NULL;
3303 const char *proto_str;
3305 /* XXX: should output a warning page when coming
3306 close to the connection limit */
3307 if (nb_connections >= nb_max_connections)
3310 /* add a new connection */
3311 c = av_mallocz(sizeof(HTTPContext));
3316 c->poll_entry = NULL;
3317 c->from_addr = *from_addr;
3318 c->buffer_size = IOBUFFER_INIT_SIZE;
3319 c->buffer = av_malloc(c->buffer_size);
3324 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3325 c->state = HTTPSTATE_READY;
3326 c->is_packetized = 1;
3327 c->rtp_protocol = rtp_protocol;
3329 /* protocol is shown in statistics */
3330 switch(c->rtp_protocol) {
3331 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3332 proto_str = "MCAST";
3334 case RTSP_LOWER_TRANSPORT_UDP:
3337 case RTSP_LOWER_TRANSPORT_TCP:
3344 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3345 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3347 current_bandwidth += stream->bandwidth;
3349 c->next = first_http_ctx;
3361 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3362 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3364 static int rtp_new_av_stream(HTTPContext *c,
3365 int stream_index, struct sockaddr_in *dest_addr,
3366 HTTPContext *rtsp_c)
3368 AVFormatContext *ctx;
3371 URLContext *h = NULL;
3373 int max_packet_size;
3375 /* now we can open the relevant output stream */
3376 ctx = avformat_alloc_context();
3379 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3381 st = av_mallocz(sizeof(AVStream));
3384 ctx->nb_streams = 1;
3385 ctx->streams[0] = st;
3387 if (!c->stream->feed ||
3388 c->stream->feed == c->stream)
3389 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3392 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3394 st->priv_data = NULL;
3396 /* build destination RTP address */
3397 ipaddr = inet_ntoa(dest_addr->sin_addr);
3399 switch(c->rtp_protocol) {
3400 case RTSP_LOWER_TRANSPORT_UDP:
3401 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3404 /* XXX: also pass as parameter to function ? */
3405 if (c->stream->is_multicast) {
3407 ttl = c->stream->multicast_ttl;
3410 snprintf(ctx->filename, sizeof(ctx->filename),
3411 "rtp://%s:%d?multicast=1&ttl=%d",
3412 ipaddr, ntohs(dest_addr->sin_port), ttl);
3414 snprintf(ctx->filename, sizeof(ctx->filename),
3415 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3418 if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
3420 c->rtp_handles[stream_index] = h;
3421 max_packet_size = url_get_max_packet_size(h);
3423 case RTSP_LOWER_TRANSPORT_TCP:
3426 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3432 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3433 ipaddr, ntohs(dest_addr->sin_port),
3434 c->stream->filename, stream_index, c->protocol);
3436 /* normally, no packets should be output here, but the packet size may be checked */
3437 if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
3438 /* XXX: close stream */
3441 av_set_parameters(ctx, NULL);
3442 if (av_write_header(ctx) < 0) {
3449 url_close_dyn_buf(ctx->pb, &dummy_buf);
3452 c->rtp_ctx[stream_index] = ctx;
3456 /********************************************************************/
3457 /* ffserver initialization */
3459 static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec, int copy)
3463 fst = av_mallocz(sizeof(AVStream));
3467 fst->codec= avcodec_alloc_context();
3468 memcpy(fst->codec, codec, sizeof(AVCodecContext));
3469 if (codec->extradata_size) {
3470 fst->codec->extradata = av_malloc(codec->extradata_size);
3471 memcpy(fst->codec->extradata, codec->extradata,
3472 codec->extradata_size);
3475 /* live streams must use the actual feed's codec since it may be
3476 * updated later to carry extradata needed by the streams.
3480 fst->priv_data = av_mallocz(sizeof(FeedData));
3481 fst->index = stream->nb_streams;
3482 av_set_pts_info(fst, 33, 1, 90000);
3483 stream->streams[stream->nb_streams++] = fst;
3487 /* return the stream number in the feed */
3488 static int add_av_stream(FFStream *feed, AVStream *st)
3491 AVCodecContext *av, *av1;
3495 for(i=0;i<feed->nb_streams;i++) {
3496 st = feed->streams[i];
3498 if (av1->codec_id == av->codec_id &&
3499 av1->codec_type == av->codec_type &&
3500 av1->bit_rate == av->bit_rate) {
3502 switch(av->codec_type) {
3503 case AVMEDIA_TYPE_AUDIO:
3504 if (av1->channels == av->channels &&
3505 av1->sample_rate == av->sample_rate)
3508 case AVMEDIA_TYPE_VIDEO:
3509 if (av1->width == av->width &&
3510 av1->height == av->height &&
3511 av1->time_base.den == av->time_base.den &&
3512 av1->time_base.num == av->time_base.num &&
3513 av1->gop_size == av->gop_size)
3522 fst = add_av_stream1(feed, av, 0);
3525 return feed->nb_streams - 1;
3530 static void remove_stream(FFStream *stream)
3534 while (*ps != NULL) {
3542 /* specific mpeg4 handling : we extract the raw parameters */
3543 static void extract_mpeg4_header(AVFormatContext *infile)
3545 int mpeg4_count, i, size;
3551 for(i=0;i<infile->nb_streams;i++) {
3552 st = infile->streams[i];
3553 if (st->codec->codec_id == CODEC_ID_MPEG4 &&
3554 st->codec->extradata_size == 0) {
3561 printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
3562 while (mpeg4_count > 0) {
3563 if (av_read_packet(infile, &pkt) < 0)
3565 st = infile->streams[pkt.stream_index];
3566 if (st->codec->codec_id == CODEC_ID_MPEG4 &&
3567 st->codec->extradata_size == 0) {
3568 av_freep(&st->codec->extradata);
3569 /* fill extradata with the header */
3570 /* XXX: we make hard suppositions here ! */
3572 while (p < pkt.data + pkt.size - 4) {
3573 /* stop when vop header is found */
3574 if (p[0] == 0x00 && p[1] == 0x00 &&
3575 p[2] == 0x01 && p[3] == 0xb6) {
3576 size = p - pkt.data;
3577 // av_hex_dump_log(infile, AV_LOG_DEBUG, pkt.data, size);
3578 st->codec->extradata = av_malloc(size);
3579 st->codec->extradata_size = size;
3580 memcpy(st->codec->extradata, pkt.data, size);
3587 av_free_packet(&pkt);
3591 /* compute the needed AVStream for each file */
3592 static void build_file_streams(void)
3594 FFStream *stream, *stream_next;
3595 AVFormatContext *infile;
3598 /* gather all streams */
3599 for(stream = first_stream; stream != NULL; stream = stream_next) {
3600 stream_next = stream->next;
3601 if (stream->stream_type == STREAM_TYPE_LIVE &&
3603 /* the stream comes from a file */
3604 /* try to open the file */
3606 stream->ap_in = av_mallocz(sizeof(AVFormatParameters));
3607 if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3608 /* specific case : if transport stream output to RTP,
3609 we use a raw transport stream reader */
3610 stream->ap_in->mpeg2ts_raw = 1;
3611 stream->ap_in->mpeg2ts_compute_pcr = 1;
3614 http_log("Opening file '%s'\n", stream->feed_filename);
3615 if ((ret = av_open_input_file(&infile, stream->feed_filename,
3616 stream->ifmt, 0, stream->ap_in)) < 0) {
3617 http_log("Could not open '%s': %d\n", stream->feed_filename, ret);
3618 /* remove stream (no need to spend more time on it) */
3620 remove_stream(stream);
3622 /* find all the AVStreams inside and reference them in
3624 if (av_find_stream_info(infile) < 0) {
3625 http_log("Could not find codec parameters from '%s'\n",
3626 stream->feed_filename);
3627 av_close_input_file(infile);
3630 extract_mpeg4_header(infile);
3632 for(i=0;i<infile->nb_streams;i++)
3633 add_av_stream1(stream, infile->streams[i]->codec, 1);
3635 av_close_input_file(infile);
3641 /* compute the needed AVStream for each feed */
3642 static void build_feed_streams(void)
3644 FFStream *stream, *feed;
3647 /* gather all streams */
3648 for(stream = first_stream; stream != NULL; stream = stream->next) {
3649 feed = stream->feed;
3651 if (!stream->is_feed) {
3652 /* we handle a stream coming from a feed */
3653 for(i=0;i<stream->nb_streams;i++)
3654 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3659 /* gather all streams */
3660 for(stream = first_stream; stream != NULL; stream = stream->next) {
3661 feed = stream->feed;
3663 if (stream->is_feed) {
3664 for(i=0;i<stream->nb_streams;i++)
3665 stream->feed_streams[i] = i;
3670 /* create feed files if needed */
3671 for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
3674 if (url_exist(feed->feed_filename)) {
3675 /* See if it matches */
3679 if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) {
3680 /* Now see if it matches */
3681 if (s->nb_streams == feed->nb_streams) {
3683 for(i=0;i<s->nb_streams;i++) {
3685 sf = feed->streams[i];
3688 if (sf->index != ss->index ||
3690 http_log("Index & Id do not match for stream %d (%s)\n",
3691 i, feed->feed_filename);
3694 AVCodecContext *ccf, *ccs;
3698 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3700 if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3701 http_log("Codecs do not match for stream %d\n", i);
3703 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3704 http_log("Codec bitrates do not match for stream %d\n", i);
3706 } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
3707 if (CHECK_CODEC(time_base.den) ||
3708 CHECK_CODEC(time_base.num) ||
3709 CHECK_CODEC(width) ||
3710 CHECK_CODEC(height)) {
3711 http_log("Codec width, height and framerate do not match for stream %d\n", i);
3714 } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
3715 if (CHECK_CODEC(sample_rate) ||
3716 CHECK_CODEC(channels) ||
3717 CHECK_CODEC(frame_size)) {
3718 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3722 http_log("Unknown codec type\n");
3730 http_log("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3731 feed->feed_filename, s->nb_streams, feed->nb_streams);
3733 av_close_input_file(s);
3735 http_log("Deleting feed file '%s' as it appears to be corrupt\n",
3736 feed->feed_filename);
3739 if (feed->readonly) {
3740 http_log("Unable to delete feed file '%s' as it is marked readonly\n",
3741 feed->feed_filename);
3744 unlink(feed->feed_filename);
3747 if (!url_exist(feed->feed_filename)) {
3748 AVFormatContext s1 = {0}, *s = &s1;
3750 if (feed->readonly) {
3751 http_log("Unable to create feed file '%s' as it is marked readonly\n",
3752 feed->feed_filename);
3756 /* only write the header of the ffm file */
3757 if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
3758 http_log("Could not open output feed file '%s'\n",
3759 feed->feed_filename);
3762 s->oformat = feed->fmt;
3763 s->nb_streams = feed->nb_streams;
3764 for(i=0;i<s->nb_streams;i++) {
3766 st = feed->streams[i];
3769 av_set_parameters(s, NULL);
3770 if (av_write_header(s) < 0) {
3771 http_log("Container doesn't supports the required parameters\n");
3774 /* XXX: need better api */
3775 av_freep(&s->priv_data);
3778 /* get feed size and write index */
3779 fd = open(feed->feed_filename, O_RDONLY);
3781 http_log("Could not open output feed file '%s'\n",
3782 feed->feed_filename);
3786 feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
3787 feed->feed_size = lseek(fd, 0, SEEK_END);
3788 /* ensure that we do not wrap before the end of file */
3789 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3790 feed->feed_max_size = feed->feed_size;
3796 /* compute the bandwidth used by each stream */
3797 static void compute_bandwidth(void)
3803 for(stream = first_stream; stream != NULL; stream = stream->next) {
3805 for(i=0;i<stream->nb_streams;i++) {
3806 AVStream *st = stream->streams[i];
3807 switch(st->codec->codec_type) {
3808 case AVMEDIA_TYPE_AUDIO:
3809 case AVMEDIA_TYPE_VIDEO:
3810 bandwidth += st->codec->bit_rate;
3816 stream->bandwidth = (bandwidth + 999) / 1000;
3820 /* add a codec and set the default parameters */
3821 static void add_codec(FFStream *stream, AVCodecContext *av)
3825 /* compute default parameters */
3826 switch(av->codec_type) {
3827 case AVMEDIA_TYPE_AUDIO:
3828 if (av->bit_rate == 0)
3829 av->bit_rate = 64000;
3830 if (av->sample_rate == 0)
3831 av->sample_rate = 22050;
3832 if (av->channels == 0)
3835 case AVMEDIA_TYPE_VIDEO:
3836 if (av->bit_rate == 0)
3837 av->bit_rate = 64000;
3838 if (av->time_base.num == 0){
3839 av->time_base.den = 5;
3840 av->time_base.num = 1;
3842 if (av->width == 0 || av->height == 0) {
3846 /* Bitrate tolerance is less for streaming */
3847 if (av->bit_rate_tolerance == 0)
3848 av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
3849 (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);
3854 if (av->max_qdiff == 0)
3856 av->qcompress = 0.5;
3859 if (!av->nsse_weight)
3860 av->nsse_weight = 8;
3862 av->frame_skip_cmp = FF_CMP_DCTMAX;
3864 av->me_method = ME_EPZS;
3865 av->rc_buffer_aggressivity = 1.0;
3868 av->rc_eq = "tex^qComp";
3869 if (!av->i_quant_factor)
3870 av->i_quant_factor = -0.8;
3871 if (!av->b_quant_factor)
3872 av->b_quant_factor = 1.25;
3873 if (!av->b_quant_offset)
3874 av->b_quant_offset = 1.25;
3875 if (!av->rc_max_rate)
3876 av->rc_max_rate = av->bit_rate * 2;
3878 if (av->rc_max_rate && !av->rc_buffer_size) {
3879 av->rc_buffer_size = av->rc_max_rate;
3888 st = av_mallocz(sizeof(AVStream));
3891 st->codec = avcodec_alloc_context();
3892 stream->streams[stream->nb_streams++] = st;
3893 memcpy(st->codec, av, sizeof(AVCodecContext));
3896 static enum CodecID opt_audio_codec(const char *arg)
3898 AVCodec *p= avcodec_find_encoder_by_name(arg);
3900 if (p == NULL || p->type != AVMEDIA_TYPE_AUDIO)
3901 return CODEC_ID_NONE;
3906 static enum CodecID opt_video_codec(const char *arg)
3908 AVCodec *p= avcodec_find_encoder_by_name(arg);
3910 if (p == NULL || p->type != AVMEDIA_TYPE_VIDEO)
3911 return CODEC_ID_NONE;
3916 /* simplistic plugin support */
3919 static void load_module(const char *filename)
3922 void (*init_func)(void);
3923 dll = dlopen(filename, RTLD_NOW);
3925 fprintf(stderr, "Could not load module '%s' - %s\n",
3926 filename, dlerror());
3930 init_func = dlsym(dll, "ffserver_module_init");
3933 "%s: init function 'ffserver_module_init()' not found\n",
3942 static int ffserver_opt_default(const char *opt, const char *arg,
3943 AVCodecContext *avctx, int type)
3946 const AVOption *o = av_find_opt(avctx, opt, NULL, type, type);
3948 ret = av_set_string3(avctx, opt, arg, 1, NULL);
3952 static AVOutputFormat *ffserver_guess_format(const char *short_name, const char *filename,
3953 const char *mime_type)
3955 AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
3958 AVOutputFormat *stream_fmt;
3959 char stream_format_name[64];
3961 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
3962 stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
3971 static void report_config_error(const char *filename, int line_num, int *errors, const char *fmt, ...)
3975 fprintf(stderr, "%s:%d: ", filename, line_num);
3976 vfprintf(stderr, fmt, vl);
3982 static int parse_ffconfig(const char *filename)
3989 int val, errors, line_num;
3990 FFStream **last_stream, *stream, *redirect;
3991 FFStream **last_feed, *feed, *s;
3992 AVCodecContext audio_enc, video_enc;
3993 enum CodecID audio_id, video_id;
3995 f = fopen(filename, "r");
4003 first_stream = NULL;
4004 last_stream = &first_stream;
4006 last_feed = &first_feed;
4010 audio_id = CODEC_ID_NONE;
4011 video_id = CODEC_ID_NONE;
4013 #define ERROR(...) report_config_error(filename, line_num, &errors, __VA_ARGS__)
4015 if (fgets(line, sizeof(line), f) == NULL)
4021 if (*p == '\0' || *p == '#')
4024 get_arg(cmd, sizeof(cmd), &p);
4026 if (!strcasecmp(cmd, "Port")) {
4027 get_arg(arg, sizeof(arg), &p);
4029 if (val < 1 || val > 65536) {
4030 ERROR("Invalid_port: %s\n", arg);
4032 my_http_addr.sin_port = htons(val);
4033 } else if (!strcasecmp(cmd, "BindAddress")) {
4034 get_arg(arg, sizeof(arg), &p);
4035 if (resolve_host(&my_http_addr.sin_addr, arg) != 0) {
4036 ERROR("%s:%d: Invalid host/IP address: %s\n", arg);
4038 } else if (!strcasecmp(cmd, "NoDaemon")) {
4039 ffserver_daemon = 0;
4040 } else if (!strcasecmp(cmd, "RTSPPort")) {
4041 get_arg(arg, sizeof(arg), &p);
4043 if (val < 1 || val > 65536) {
4044 ERROR("%s:%d: Invalid port: %s\n", arg);
4046 my_rtsp_addr.sin_port = htons(atoi(arg));
4047 } else if (!strcasecmp(cmd, "RTSPBindAddress")) {
4048 get_arg(arg, sizeof(arg), &p);
4049 if (resolve_host(&my_rtsp_addr.sin_addr, arg) != 0) {
4050 ERROR("Invalid host/IP address: %s\n", arg);
4052 } else if (!strcasecmp(cmd, "MaxHTTPConnections")) {
4053 get_arg(arg, sizeof(arg), &p);
4055 if (val < 1 || val > 65536) {
4056 ERROR("Invalid MaxHTTPConnections: %s\n", arg);
4058 nb_max_http_connections = val;
4059 } else if (!strcasecmp(cmd, "MaxClients")) {
4060 get_arg(arg, sizeof(arg), &p);
4062 if (val < 1 || val > nb_max_http_connections) {
4063 ERROR("Invalid MaxClients: %s\n", arg);
4065 nb_max_connections = val;
4067 } else if (!strcasecmp(cmd, "MaxBandwidth")) {
4069 get_arg(arg, sizeof(arg), &p);
4071 if (llval < 10 || llval > 10000000) {
4072 ERROR("Invalid MaxBandwidth: %s\n", arg);
4074 max_bandwidth = llval;
4075 } else if (!strcasecmp(cmd, "CustomLog")) {
4076 if (!ffserver_debug)
4077 get_arg(logfilename, sizeof(logfilename), &p);
4078 } else if (!strcasecmp(cmd, "<Feed")) {
4079 /*********************************************/
4080 /* Feed related options */
4082 if (stream || feed) {
4083 ERROR("Already in a tag\n");
4085 feed = av_mallocz(sizeof(FFStream));
4086 get_arg(feed->filename, sizeof(feed->filename), &p);
4087 q = strrchr(feed->filename, '>');
4091 for (s = first_feed; s; s = s->next) {
4092 if (!strcmp(feed->filename, s->filename)) {
4093 ERROR("Feed '%s' already registered\n", s->filename);
4097 feed->fmt = av_guess_format("ffm", NULL, NULL);
4098 /* defaut feed file */
4099 snprintf(feed->feed_filename, sizeof(feed->feed_filename),
4100 "/tmp/%s.ffm", feed->filename);
4101 feed->feed_max_size = 5 * 1024 * 1024;
4103 feed->feed = feed; /* self feeding :-) */
4105 /* add in stream list */
4106 *last_stream = feed;
4107 last_stream = &feed->next;
4108 /* add in feed list */
4110 last_feed = &feed->next_feed;
4112 } else if (!strcasecmp(cmd, "Launch")) {
4116 feed->child_argv = av_mallocz(64 * sizeof(char *));
4118 for (i = 0; i < 62; i++) {
4119 get_arg(arg, sizeof(arg), &p);
4123 feed->child_argv[i] = av_strdup(arg);
4126 feed->child_argv[i] = av_malloc(30 + strlen(feed->filename));
4128 snprintf(feed->child_argv[i], 30+strlen(feed->filename),
4130 (my_http_addr.sin_addr.s_addr == INADDR_ANY) ? "127.0.0.1" :
4131 inet_ntoa(my_http_addr.sin_addr),
4132 ntohs(my_http_addr.sin_port), feed->filename);
4134 } else if (!strcasecmp(cmd, "ReadOnlyFile")) {
4136 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
4138 } else if (stream) {
4139 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4141 } else if (!strcasecmp(cmd, "File")) {
4143 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
4145 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4146 } else if (!strcasecmp(cmd, "Truncate")) {
4148 get_arg(arg, sizeof(arg), &p);
4149 feed->truncate = strtod(arg, NULL);
4151 } else if (!strcasecmp(cmd, "FileMaxSize")) {
4156 get_arg(arg, sizeof(arg), &p);
4158 fsize = strtod(p1, &p1);
4159 switch(toupper(*p1)) {
4164 fsize *= 1024 * 1024;
4167 fsize *= 1024 * 1024 * 1024;
4170 feed->feed_max_size = (int64_t)fsize;
4171 if (feed->feed_max_size < FFM_PACKET_SIZE*4) {
4172 ERROR("Feed max file size is too small, must be at least %d\n", FFM_PACKET_SIZE*4);
4175 } else if (!strcasecmp(cmd, "</Feed>")) {
4177 ERROR("No corresponding <Feed> for </Feed>\n");
4180 } else if (!strcasecmp(cmd, "<Stream")) {
4181 /*********************************************/
4182 /* Stream related options */
4184 if (stream || feed) {
4185 ERROR("Already in a tag\n");
4188 stream = av_mallocz(sizeof(FFStream));
4189 get_arg(stream->filename, sizeof(stream->filename), &p);
4190 q = strrchr(stream->filename, '>');
4194 for (s = first_stream; s; s = s->next) {
4195 if (!strcmp(stream->filename, s->filename)) {
4196 ERROR("Stream '%s' already registered\n", s->filename);
4200 stream->fmt = ffserver_guess_format(NULL, stream->filename, NULL);
4201 avcodec_get_context_defaults2(&video_enc, AVMEDIA_TYPE_VIDEO);
4202 avcodec_get_context_defaults2(&audio_enc, AVMEDIA_TYPE_AUDIO);
4203 audio_id = CODEC_ID_NONE;
4204 video_id = CODEC_ID_NONE;
4206 audio_id = stream->fmt->audio_codec;
4207 video_id = stream->fmt->video_codec;
4210 *last_stream = stream;
4211 last_stream = &stream->next;
4213 } else if (!strcasecmp(cmd, "Feed")) {
4214 get_arg(arg, sizeof(arg), &p);
4219 while (sfeed != NULL) {
4220 if (!strcmp(sfeed->filename, arg))
4222 sfeed = sfeed->next_feed;
4225 ERROR("feed '%s' not defined\n", arg);
4227 stream->feed = sfeed;
4229 } else if (!strcasecmp(cmd, "Format")) {
4230 get_arg(arg, sizeof(arg), &p);
4232 if (!strcmp(arg, "status")) {
4233 stream->stream_type = STREAM_TYPE_STATUS;
4236 stream->stream_type = STREAM_TYPE_LIVE;
4237 /* jpeg cannot be used here, so use single frame jpeg */
4238 if (!strcmp(arg, "jpeg"))
4239 strcpy(arg, "mjpeg");
4240 stream->fmt = ffserver_guess_format(arg, NULL, NULL);
4242 ERROR("Unknown Format: %s\n", arg);
4246 audio_id = stream->fmt->audio_codec;
4247 video_id = stream->fmt->video_codec;
4250 } else if (!strcasecmp(cmd, "InputFormat")) {
4251 get_arg(arg, sizeof(arg), &p);
4253 stream->ifmt = av_find_input_format(arg);
4254 if (!stream->ifmt) {
4255 ERROR("Unknown input format: %s\n", arg);
4258 } else if (!strcasecmp(cmd, "FaviconURL")) {
4259 if (stream && stream->stream_type == STREAM_TYPE_STATUS) {
4260 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4262 ERROR("FaviconURL only permitted for status streams\n");
4264 } else if (!strcasecmp(cmd, "Author")) {
4266 get_arg(stream->author, sizeof(stream->author), &p);
4267 } else if (!strcasecmp(cmd, "Comment")) {
4269 get_arg(stream->comment, sizeof(stream->comment), &p);
4270 } else if (!strcasecmp(cmd, "Copyright")) {
4272 get_arg(stream->copyright, sizeof(stream->copyright), &p);
4273 } else if (!strcasecmp(cmd, "Title")) {
4275 get_arg(stream->title, sizeof(stream->title), &p);
4276 } else if (!strcasecmp(cmd, "Preroll")) {
4277 get_arg(arg, sizeof(arg), &p);
4279 stream->prebuffer = atof(arg) * 1000;
4280 } else if (!strcasecmp(cmd, "StartSendOnKey")) {
4282 stream->send_on_key = 1;
4283 } else if (!strcasecmp(cmd, "AudioCodec")) {
4284 get_arg(arg, sizeof(arg), &p);
4285 audio_id = opt_audio_codec(arg);
4286 if (audio_id == CODEC_ID_NONE) {
4287 ERROR("Unknown AudioCodec: %s\n", 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 ERROR("Unknown VideoCodec: %s\n", arg);
4295 } else if (!strcasecmp(cmd, "MaxTime")) {
4296 get_arg(arg, sizeof(arg), &p);
4298 stream->max_time = atof(arg) * 1000;
4299 } else if (!strcasecmp(cmd, "AudioBitRate")) {
4300 get_arg(arg, sizeof(arg), &p);
4302 audio_enc.bit_rate = lrintf(atof(arg) * 1000);
4303 } else if (!strcasecmp(cmd, "AudioChannels")) {
4304 get_arg(arg, sizeof(arg), &p);
4306 audio_enc.channels = atoi(arg);
4307 } else if (!strcasecmp(cmd, "AudioSampleRate")) {
4308 get_arg(arg, sizeof(arg), &p);
4310 audio_enc.sample_rate = atoi(arg);
4311 } else if (!strcasecmp(cmd, "AudioQuality")) {
4312 get_arg(arg, sizeof(arg), &p);
4314 // audio_enc.quality = atof(arg) * 1000;
4316 } else if (!strcasecmp(cmd, "VideoBitRateRange")) {
4318 int minrate, maxrate;
4320 get_arg(arg, sizeof(arg), &p);
4322 if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {
4323 video_enc.rc_min_rate = minrate * 1000;
4324 video_enc.rc_max_rate = maxrate * 1000;
4326 ERROR("Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n", arg);
4329 } else if (!strcasecmp(cmd, "Debug")) {
4331 get_arg(arg, sizeof(arg), &p);
4332 video_enc.debug = strtol(arg,0,0);
4334 } else if (!strcasecmp(cmd, "Strict")) {
4336 get_arg(arg, sizeof(arg), &p);
4337 video_enc.strict_std_compliance = atoi(arg);
4339 } else if (!strcasecmp(cmd, "VideoBufferSize")) {
4341 get_arg(arg, sizeof(arg), &p);
4342 video_enc.rc_buffer_size = atoi(arg) * 8*1024;
4344 } else if (!strcasecmp(cmd, "VideoBitRateTolerance")) {
4346 get_arg(arg, sizeof(arg), &p);
4347 video_enc.bit_rate_tolerance = atoi(arg) * 1000;
4349 } else if (!strcasecmp(cmd, "VideoBitRate")) {
4350 get_arg(arg, sizeof(arg), &p);
4352 video_enc.bit_rate = atoi(arg) * 1000;
4354 } else if (!strcasecmp(cmd, "VideoSize")) {
4355 get_arg(arg, sizeof(arg), &p);
4357 av_parse_video_frame_size(&video_enc.width, &video_enc.height, arg);
4358 if ((video_enc.width % 16) != 0 ||
4359 (video_enc.height % 16) != 0) {
4360 ERROR("Image size must be a multiple of 16\n");
4363 } else if (!strcasecmp(cmd, "VideoFrameRate")) {
4364 get_arg(arg, sizeof(arg), &p);
4366 AVRational frame_rate;
4367 if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
4368 ERROR("Incorrect frame rate: %s\n", arg);
4370 video_enc.time_base.num = frame_rate.den;
4371 video_enc.time_base.den = frame_rate.num;
4374 } else if (!strcasecmp(cmd, "VideoGopSize")) {
4375 get_arg(arg, sizeof(arg), &p);
4377 video_enc.gop_size = atoi(arg);
4378 } else if (!strcasecmp(cmd, "VideoIntraOnly")) {
4380 video_enc.gop_size = 1;
4381 } else if (!strcasecmp(cmd, "VideoHighQuality")) {
4383 video_enc.mb_decision = FF_MB_DECISION_BITS;
4384 } else if (!strcasecmp(cmd, "Video4MotionVector")) {
4386 video_enc.mb_decision = FF_MB_DECISION_BITS; //FIXME remove
4387 video_enc.flags |= CODEC_FLAG_4MV;
4389 } else if (!strcasecmp(cmd, "AVOptionVideo") ||
4390 !strcasecmp(cmd, "AVOptionAudio")) {
4392 AVCodecContext *avctx;
4394 get_arg(arg, sizeof(arg), &p);
4395 get_arg(arg2, sizeof(arg2), &p);
4396 if (!strcasecmp(cmd, "AVOptionVideo")) {
4398 type = AV_OPT_FLAG_VIDEO_PARAM;
4401 type = AV_OPT_FLAG_AUDIO_PARAM;
4403 if (ffserver_opt_default(arg, arg2, avctx, type|AV_OPT_FLAG_ENCODING_PARAM)) {
4404 ERROR("AVOption error: %s %s\n", arg, arg2);
4406 } else if (!strcasecmp(cmd, "VideoTag")) {
4407 get_arg(arg, sizeof(arg), &p);
4408 if ((strlen(arg) == 4) && stream)
4409 video_enc.codec_tag = MKTAG(arg[0], arg[1], arg[2], arg[3]);
4410 } else if (!strcasecmp(cmd, "BitExact")) {
4412 video_enc.flags |= CODEC_FLAG_BITEXACT;
4413 } else if (!strcasecmp(cmd, "DctFastint")) {
4415 video_enc.dct_algo = FF_DCT_FASTINT;
4416 } else if (!strcasecmp(cmd, "IdctSimple")) {
4418 video_enc.idct_algo = FF_IDCT_SIMPLE;
4419 } else if (!strcasecmp(cmd, "Qscale")) {
4420 get_arg(arg, sizeof(arg), &p);
4422 video_enc.flags |= CODEC_FLAG_QSCALE;
4423 video_enc.global_quality = FF_QP2LAMBDA * atoi(arg);
4425 } else if (!strcasecmp(cmd, "VideoQDiff")) {
4426 get_arg(arg, sizeof(arg), &p);
4428 video_enc.max_qdiff = atoi(arg);
4429 if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) {
4430 ERROR("VideoQDiff out of range\n");
4433 } else if (!strcasecmp(cmd, "VideoQMax")) {
4434 get_arg(arg, sizeof(arg), &p);
4436 video_enc.qmax = atoi(arg);
4437 if (video_enc.qmax < 1 || video_enc.qmax > 31) {
4438 ERROR("VideoQMax out of range\n");
4441 } else if (!strcasecmp(cmd, "VideoQMin")) {
4442 get_arg(arg, sizeof(arg), &p);
4444 video_enc.qmin = atoi(arg);
4445 if (video_enc.qmin < 1 || video_enc.qmin > 31) {
4446 ERROR("VideoQMin out of range\n");
4449 } else if (!strcasecmp(cmd, "LumaElim")) {
4450 get_arg(arg, sizeof(arg), &p);
4452 video_enc.luma_elim_threshold = atoi(arg);
4453 } else if (!strcasecmp(cmd, "ChromaElim")) {
4454 get_arg(arg, sizeof(arg), &p);
4456 video_enc.chroma_elim_threshold = atoi(arg);
4457 } else if (!strcasecmp(cmd, "LumiMask")) {
4458 get_arg(arg, sizeof(arg), &p);
4460 video_enc.lumi_masking = atof(arg);
4461 } else if (!strcasecmp(cmd, "DarkMask")) {
4462 get_arg(arg, sizeof(arg), &p);
4464 video_enc.dark_masking = atof(arg);
4465 } else if (!strcasecmp(cmd, "NoVideo")) {
4466 video_id = CODEC_ID_NONE;
4467 } else if (!strcasecmp(cmd, "NoAudio")) {
4468 audio_id = CODEC_ID_NONE;
4469 } else if (!strcasecmp(cmd, "ACL")) {
4470 parse_acl_row(stream, feed, NULL, p, filename, line_num);
4471 } else if (!strcasecmp(cmd, "DynamicACL")) {
4473 get_arg(stream->dynamic_acl, sizeof(stream->dynamic_acl), &p);
4475 } else if (!strcasecmp(cmd, "RTSPOption")) {
4476 get_arg(arg, sizeof(arg), &p);
4478 av_freep(&stream->rtsp_option);
4479 stream->rtsp_option = av_strdup(arg);
4481 } else if (!strcasecmp(cmd, "MulticastAddress")) {
4482 get_arg(arg, sizeof(arg), &p);
4484 if (resolve_host(&stream->multicast_ip, arg) != 0) {
4485 ERROR("Invalid host/IP address: %s\n", arg);
4487 stream->is_multicast = 1;
4488 stream->loop = 1; /* default is looping */
4490 } else if (!strcasecmp(cmd, "MulticastPort")) {
4491 get_arg(arg, sizeof(arg), &p);
4493 stream->multicast_port = atoi(arg);
4494 } else if (!strcasecmp(cmd, "MulticastTTL")) {
4495 get_arg(arg, sizeof(arg), &p);
4497 stream->multicast_ttl = atoi(arg);
4498 } else if (!strcasecmp(cmd, "NoLoop")) {
4501 } else if (!strcasecmp(cmd, "</Stream>")) {
4503 ERROR("No corresponding <Stream> for </Stream>\n");
4505 if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) {
4506 if (audio_id != CODEC_ID_NONE) {
4507 audio_enc.codec_type = AVMEDIA_TYPE_AUDIO;
4508 audio_enc.codec_id = audio_id;
4509 add_codec(stream, &audio_enc);
4511 if (video_id != CODEC_ID_NONE) {
4512 video_enc.codec_type = AVMEDIA_TYPE_VIDEO;
4513 video_enc.codec_id = video_id;
4514 add_codec(stream, &video_enc);
4519 } else if (!strcasecmp(cmd, "<Redirect")) {
4520 /*********************************************/
4522 if (stream || feed || redirect) {
4523 ERROR("Already in a tag\n");
4525 redirect = av_mallocz(sizeof(FFStream));
4526 *last_stream = redirect;
4527 last_stream = &redirect->next;
4529 get_arg(redirect->filename, sizeof(redirect->filename), &p);
4530 q = strrchr(redirect->filename, '>');
4533 redirect->stream_type = STREAM_TYPE_REDIRECT;
4535 } else if (!strcasecmp(cmd, "URL")) {
4537 get_arg(redirect->feed_filename, sizeof(redirect->feed_filename), &p);
4538 } else if (!strcasecmp(cmd, "</Redirect>")) {
4540 ERROR("No corresponding <Redirect> for </Redirect>\n");
4542 if (!redirect->feed_filename[0]) {
4543 ERROR("No URL found for <Redirect>\n");
4547 } else if (!strcasecmp(cmd, "LoadModule")) {
4548 get_arg(arg, sizeof(arg), &p);
4552 ERROR("Module support not compiled into this version: '%s'\n", arg);
4555 ERROR("Incorrect keyword: '%s'\n", cmd);
4567 static void handle_child_exit(int sig)
4572 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
4575 for (feed = first_feed; feed; feed = feed->next) {
4576 if (feed->pid == pid) {
4577 int uptime = time(0) - feed->pid_start;
4580 fprintf(stderr, "%s: Pid %d exited with status %d after %d seconds\n", feed->filename, pid, status, uptime);
4583 /* Turn off any more restarts */
4584 feed->child_argv = 0;
4589 need_to_start_children = 1;
4592 static void opt_debug(void)
4595 ffserver_daemon = 0;
4596 logfilename[0] = '-';
4599 static void show_help(void)
4601 printf("usage: ffserver [options]\n"
4602 "Hyper fast multi format Audio/Video streaming server\n");
4604 show_help_options(options, "Main options:\n", 0, 0);
4607 static const OptionDef options[] = {
4608 #include "cmdutils_common_opts.h"
4609 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
4610 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
4611 { "f", HAS_ARG | OPT_STRING, {(void*)&config_filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
4615 int main(int argc, char **argv)
4617 struct sigaction sigact;
4623 my_program_name = argv[0];
4624 my_program_dir = getcwd(0, 0);
4625 ffserver_daemon = 1;
4627 parse_options(argc, argv, options, NULL);
4629 unsetenv("http_proxy"); /* Kill the http_proxy */
4631 av_lfg_init(&random_state, av_get_random_seed());
4633 memset(&sigact, 0, sizeof(sigact));
4634 sigact.sa_handler = handle_child_exit;
4635 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
4636 sigaction(SIGCHLD, &sigact, 0);
4638 if (parse_ffconfig(config_filename) < 0) {
4639 fprintf(stderr, "Incorrect config file - exiting.\n");
4643 /* open log file if needed */
4644 if (logfilename[0] != '\0') {
4645 if (!strcmp(logfilename, "-"))
4648 logfile = fopen(logfilename, "a");
4649 av_log_set_callback(http_av_log);
4652 build_file_streams();
4654 build_feed_streams();
4656 compute_bandwidth();
4658 /* put the process in background and detach it from its TTY */
4659 if (ffserver_daemon) {
4666 } else if (pid > 0) {
4673 open("/dev/null", O_RDWR);
4674 if (strcmp(logfilename, "-") != 0) {
4684 signal(SIGPIPE, SIG_IGN);
4686 if (ffserver_daemon)
4689 if (http_server() < 0) {
4690 http_log("Could not start server\n");