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 /* avformat.h defines LIBAVFORMAT_BUILD, include it before all the other libav* headers which use it */
32 #include "libavformat/avformat.h"
33 #include "libavformat/network.h"
34 #include "libavformat/os_support.h"
35 #include "libavformat/rtpdec.h"
36 #include "libavformat/rtsp.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/lfg.h"
39 #include "libavutil/random_seed.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavcodec/opt.h"
45 #include <sys/ioctl.h>
51 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
63 const char program_name[] = "FFserver";
64 const int program_birth_year = 2000;
66 static const OptionDef options[];
69 HTTPSTATE_WAIT_REQUEST,
70 HTTPSTATE_SEND_HEADER,
71 HTTPSTATE_SEND_DATA_HEADER,
72 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
73 HTTPSTATE_SEND_DATA_TRAILER,
74 HTTPSTATE_RECEIVE_DATA,
75 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
78 RTSPSTATE_WAIT_REQUEST,
80 RTSPSTATE_SEND_PACKET,
83 static const char *http_state[] = {
99 #define IOBUFFER_INIT_SIZE 8192
101 /* timeouts are in ms */
102 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
103 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
105 #define SYNC_TIMEOUT (10 * 1000)
107 typedef struct RTSPActionServerSetup {
109 char transport_option[512];
110 } RTSPActionServerSetup;
113 int64_t count1, count2;
114 int64_t time1, time2;
117 /* context associated with one connection */
118 typedef struct HTTPContext {
119 enum HTTPState state;
120 int fd; /* socket file descriptor */
121 struct sockaddr_in from_addr; /* origin */
122 struct pollfd *poll_entry; /* used when polling */
124 uint8_t *buffer_ptr, *buffer_end;
127 struct HTTPContext *next;
128 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
132 /* input format handling */
133 AVFormatContext *fmt_in;
134 int64_t start_time; /* In milliseconds - this wraps fairly often */
135 int64_t first_pts; /* initial pts value */
136 int64_t cur_pts; /* current pts value from the stream in us */
137 int64_t cur_frame_duration; /* duration of the current frame in us */
138 int cur_frame_bytes; /* output frame size, needed to compute
139 the time at which we send each
141 int pts_stream_index; /* stream we choose as clock reference */
142 int64_t cur_clock; /* current clock reference value in us */
143 /* output format handling */
144 struct FFStream *stream;
145 /* -1 is invalid stream */
146 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
147 int switch_feed_streams[MAX_STREAMS]; /* index of streams in the feed */
149 AVFormatContext fmt_ctx; /* instance of FFStream for one user */
150 int last_packet_sent; /* true if last data packet was sent */
152 DataRateData datarate;
159 int is_packetized; /* if true, the stream is packetized */
160 int packet_stream_index; /* current stream for output in state machine */
162 /* RTSP state specific */
163 uint8_t *pb_buffer; /* XXX: use that in all the code */
165 int seq; /* RTSP sequence number */
167 /* RTP state specific */
168 enum RTSPLowerTransport rtp_protocol;
169 char session_id[32]; /* session id */
170 AVFormatContext *rtp_ctx[MAX_STREAMS];
172 /* RTP/UDP specific */
173 URLContext *rtp_handles[MAX_STREAMS];
175 /* RTP/TCP specific */
176 struct HTTPContext *rtsp_c;
177 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
180 /* each generated stream is described here */
184 STREAM_TYPE_REDIRECT,
187 enum IPAddressAction {
192 typedef struct IPAddressACL {
193 struct IPAddressACL *next;
194 enum IPAddressAction action;
195 /* These are in host order */
196 struct in_addr first;
200 /* description of each stream of the ffserver.conf file */
201 typedef struct FFStream {
202 enum StreamType stream_type;
203 char filename[1024]; /* stream filename */
204 struct FFStream *feed; /* feed we are using (can be null if
206 AVFormatParameters *ap_in; /* input parameters */
207 AVInputFormat *ifmt; /* if non NULL, force input format */
211 int prebuffer; /* Number of millseconds early to start */
212 int64_t max_time; /* Number of milliseconds to run */
214 AVStream *streams[MAX_STREAMS];
215 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
216 char feed_filename[1024]; /* file name of the feed storage, or
217 input file name for a stream */
222 pid_t pid; /* Of ffmpeg process */
223 time_t pid_start; /* Of ffmpeg process */
225 struct FFStream *next;
226 unsigned bandwidth; /* bandwidth, in kbits/s */
229 /* multicast specific */
231 struct in_addr multicast_ip;
232 int multicast_port; /* first port used for multicast */
234 int loop; /* if true, send the stream in loops (only meaningful if file) */
237 int feed_opened; /* true if someone is writing to the feed */
238 int is_feed; /* true if it is a feed */
239 int readonly; /* True if writing is prohibited to the file */
240 int truncate; /* True if feeder connection truncate the feed file */
242 int64_t bytes_served;
243 int64_t feed_max_size; /* maximum storage size, zero means unlimited */
244 int64_t feed_write_index; /* current write position in feed (it wraps around) */
245 int64_t feed_size; /* current size of feed */
246 struct FFStream *next_feed;
249 typedef struct FeedData {
250 long long data_count;
251 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
254 static struct sockaddr_in my_http_addr;
255 static struct sockaddr_in my_rtsp_addr;
257 static char logfilename[1024];
258 static HTTPContext *first_http_ctx;
259 static FFStream *first_feed; /* contains only feeds */
260 static FFStream *first_stream; /* contains all streams, including feeds */
262 static void new_connection(int server_fd, int is_rtsp);
263 static void close_connection(HTTPContext *c);
266 static int handle_connection(HTTPContext *c);
267 static int http_parse_request(HTTPContext *c);
268 static int http_send_data(HTTPContext *c);
269 static void compute_status(HTTPContext *c);
270 static int open_input_stream(HTTPContext *c, const char *info);
271 static int http_start_receive_data(HTTPContext *c);
272 static int http_receive_data(HTTPContext *c);
275 static int rtsp_parse_request(HTTPContext *c);
276 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
277 static void rtsp_cmd_options(HTTPContext *c, const char *url);
278 static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPMessageHeader *h);
279 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h);
280 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h);
281 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h);
284 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
285 struct in_addr my_ip);
288 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
289 FFStream *stream, const char *session_id,
290 enum RTSPLowerTransport rtp_protocol);
291 static int rtp_new_av_stream(HTTPContext *c,
292 int stream_index, struct sockaddr_in *dest_addr,
293 HTTPContext *rtsp_c);
295 static const char *my_program_name;
296 static const char *my_program_dir;
298 static const char *config_filename;
299 static int ffserver_debug;
300 static int ffserver_daemon;
301 static int no_launch;
302 static int need_to_start_children;
304 /* maximum number of simultaneous HTTP connections */
305 static unsigned int nb_max_http_connections = 2000;
306 static unsigned int nb_max_connections = 5;
307 static unsigned int nb_connections;
309 static uint64_t max_bandwidth = 1000;
310 static uint64_t current_bandwidth;
312 static int64_t cur_time; // Making this global saves on passing it around everywhere
314 static AVLFG random_state;
316 static FILE *logfile = NULL;
318 static char *ctime1(char *buf2)
326 p = buf2 + strlen(p) - 1;
332 static void http_vlog(const char *fmt, va_list vargs)
334 static int print_prefix = 1;
339 fprintf(logfile, "%s ", buf);
341 print_prefix = strstr(fmt, "\n") != NULL;
342 vfprintf(logfile, fmt, vargs);
347 static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
350 va_start(vargs, fmt);
351 http_vlog(fmt, vargs);
355 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
357 static int print_prefix = 1;
358 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
359 if (level > av_log_get_level())
361 if (print_prefix && avc)
362 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
363 print_prefix = strstr(fmt, "\n") != NULL;
364 http_vlog(fmt, vargs);
367 static void log_connection(HTTPContext *c)
372 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
373 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
374 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
377 static void update_datarate(DataRateData *drd, int64_t count)
379 if (!drd->time1 && !drd->count1) {
380 drd->time1 = drd->time2 = cur_time;
381 drd->count1 = drd->count2 = count;
382 } else if (cur_time - drd->time2 > 5000) {
383 drd->time1 = drd->time2;
384 drd->count1 = drd->count2;
385 drd->time2 = cur_time;
390 /* In bytes per second */
391 static int compute_datarate(DataRateData *drd, int64_t count)
393 if (cur_time == drd->time1)
396 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
400 static void start_children(FFStream *feed)
405 for (; feed; feed = feed->next) {
406 if (feed->child_argv && !feed->pid) {
407 feed->pid_start = time(0);
412 http_log("Unable to create children\n");
421 av_strlcpy(pathname, my_program_name, sizeof(pathname));
423 slash = strrchr(pathname, '/');
428 strcpy(slash, "ffmpeg");
430 http_log("Launch commandline: ");
431 http_log("%s ", pathname);
432 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
433 http_log("%s ", feed->child_argv[i]);
436 for (i = 3; i < 256; i++)
439 if (!ffserver_debug) {
440 i = open("/dev/null", O_RDWR);
449 /* This is needed to make relative pathnames work */
450 chdir(my_program_dir);
452 signal(SIGPIPE, SIG_DFL);
454 execvp(pathname, feed->child_argv);
462 /* open a listening socket */
463 static int socket_open_listen(struct sockaddr_in *my_addr)
467 server_fd = socket(AF_INET,SOCK_STREAM,0);
474 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
476 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
478 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
480 closesocket(server_fd);
484 if (listen (server_fd, 5) < 0) {
486 closesocket(server_fd);
489 ff_socket_nonblock(server_fd, 1);
494 /* start all multicast streams */
495 static void start_multicast(void)
500 struct sockaddr_in dest_addr;
501 int default_port, stream_index;
504 for(stream = first_stream; stream != NULL; stream = stream->next) {
505 if (stream->is_multicast) {
506 /* open the RTP connection */
507 snprintf(session_id, sizeof(session_id), "%08x%08x",
508 av_lfg_get(&random_state), av_lfg_get(&random_state));
510 /* choose a port if none given */
511 if (stream->multicast_port == 0) {
512 stream->multicast_port = default_port;
516 dest_addr.sin_family = AF_INET;
517 dest_addr.sin_addr = stream->multicast_ip;
518 dest_addr.sin_port = htons(stream->multicast_port);
520 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
521 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
525 if (open_input_stream(rtp_c, "") < 0) {
526 http_log("Could not open input stream for stream '%s'\n",
531 /* open each RTP stream */
532 for(stream_index = 0; stream_index < stream->nb_streams;
534 dest_addr.sin_port = htons(stream->multicast_port +
536 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
537 http_log("Could not open output stream '%s/streamid=%d'\n",
538 stream->filename, stream_index);
543 /* change state to send data */
544 rtp_c->state = HTTPSTATE_SEND_DATA;
549 /* main loop of the http server */
550 static int http_server(void)
552 int server_fd = 0, rtsp_server_fd = 0;
553 int ret, delay, delay1;
554 struct pollfd *poll_table, *poll_entry;
555 HTTPContext *c, *c_next;
557 if(!(poll_table = av_mallocz((nb_max_http_connections + 2)*sizeof(*poll_table)))) {
558 http_log("Impossible to allocate a poll table handling %d connections.\n", nb_max_http_connections);
562 if (my_http_addr.sin_port) {
563 server_fd = socket_open_listen(&my_http_addr);
568 if (my_rtsp_addr.sin_port) {
569 rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
570 if (rtsp_server_fd < 0)
574 if (!rtsp_server_fd && !server_fd) {
575 http_log("HTTP and RTSP disabled.\n");
579 http_log("FFserver started.\n");
581 start_children(first_feed);
586 poll_entry = poll_table;
588 poll_entry->fd = server_fd;
589 poll_entry->events = POLLIN;
592 if (rtsp_server_fd) {
593 poll_entry->fd = rtsp_server_fd;
594 poll_entry->events = POLLIN;
598 /* wait for events on each HTTP handle */
605 case HTTPSTATE_SEND_HEADER:
606 case RTSPSTATE_SEND_REPLY:
607 case RTSPSTATE_SEND_PACKET:
608 c->poll_entry = poll_entry;
610 poll_entry->events = POLLOUT;
613 case HTTPSTATE_SEND_DATA_HEADER:
614 case HTTPSTATE_SEND_DATA:
615 case HTTPSTATE_SEND_DATA_TRAILER:
616 if (!c->is_packetized) {
617 /* for TCP, we output as much as we can (may need to put a limit) */
618 c->poll_entry = poll_entry;
620 poll_entry->events = POLLOUT;
623 /* when ffserver is doing the timing, we work by
624 looking at which packet need to be sent every
626 delay1 = 10; /* one tick wait XXX: 10 ms assumed */
631 case HTTPSTATE_WAIT_REQUEST:
632 case HTTPSTATE_RECEIVE_DATA:
633 case HTTPSTATE_WAIT_FEED:
634 case RTSPSTATE_WAIT_REQUEST:
635 /* need to catch errors */
636 c->poll_entry = poll_entry;
638 poll_entry->events = POLLIN;/* Maybe this will work */
642 c->poll_entry = NULL;
648 /* wait for an event on one connection. We poll at least every
649 second to handle timeouts */
651 ret = poll(poll_table, poll_entry - poll_table, delay);
652 if (ret < 0 && ff_neterrno() != FF_NETERROR(EAGAIN) &&
653 ff_neterrno() != FF_NETERROR(EINTR))
657 cur_time = av_gettime() / 1000;
659 if (need_to_start_children) {
660 need_to_start_children = 0;
661 start_children(first_feed);
664 /* now handle the events */
665 for(c = first_http_ctx; c != NULL; c = c_next) {
667 if (handle_connection(c) < 0) {
668 /* close and free the connection */
674 poll_entry = poll_table;
676 /* new HTTP connection request ? */
677 if (poll_entry->revents & POLLIN)
678 new_connection(server_fd, 0);
681 if (rtsp_server_fd) {
682 /* new RTSP connection request ? */
683 if (poll_entry->revents & POLLIN)
684 new_connection(rtsp_server_fd, 1);
689 /* start waiting for a new HTTP/RTSP request */
690 static void start_wait_request(HTTPContext *c, int is_rtsp)
692 c->buffer_ptr = c->buffer;
693 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
696 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
697 c->state = RTSPSTATE_WAIT_REQUEST;
699 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
700 c->state = HTTPSTATE_WAIT_REQUEST;
704 static void http_send_too_busy_reply(int fd)
707 int len = snprintf(buffer, sizeof(buffer),
708 "HTTP/1.0 200 Server too busy\r\n"
709 "Content-type: text/html\r\n"
711 "<html><head><title>Too busy</title></head><body>\r\n"
712 "<p>The server is too busy to serve your request at this time.</p>\r\n"
713 "<p>The number of current connections is %d, and this exceeds the limit of %d.</p>\r\n"
714 "</body></html>\r\n",
715 nb_connections, nb_max_connections);
716 send(fd, buffer, len, 0);
720 static void new_connection(int server_fd, int is_rtsp)
722 struct sockaddr_in from_addr;
724 HTTPContext *c = NULL;
726 len = sizeof(from_addr);
727 fd = accept(server_fd, (struct sockaddr *)&from_addr,
730 http_log("error during accept %s\n", strerror(errno));
733 ff_socket_nonblock(fd, 1);
735 if (nb_connections >= nb_max_connections) {
736 http_send_too_busy_reply(fd);
740 /* add a new connection */
741 c = av_mallocz(sizeof(HTTPContext));
746 c->poll_entry = NULL;
747 c->from_addr = from_addr;
748 c->buffer_size = IOBUFFER_INIT_SIZE;
749 c->buffer = av_malloc(c->buffer_size);
753 c->next = first_http_ctx;
757 start_wait_request(c, is_rtsp);
769 static void close_connection(HTTPContext *c)
771 HTTPContext **cp, *c1;
773 AVFormatContext *ctx;
777 /* remove connection from list */
778 cp = &first_http_ctx;
779 while ((*cp) != NULL) {
787 /* remove references, if any (XXX: do it faster) */
788 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
793 /* remove connection associated resources */
797 /* close each frame parser */
798 for(i=0;i<c->fmt_in->nb_streams;i++) {
799 st = c->fmt_in->streams[i];
800 if (st->codec->codec)
801 avcodec_close(st->codec);
803 av_close_input_file(c->fmt_in);
806 /* free RTP output streams if any */
809 nb_streams = c->stream->nb_streams;
811 for(i=0;i<nb_streams;i++) {
814 av_write_trailer(ctx);
817 h = c->rtp_handles[i];
824 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
827 if (url_open_dyn_buf(&ctx->pb) >= 0) {
828 av_write_trailer(ctx);
829 av_freep(&c->pb_buffer);
830 url_close_dyn_buf(ctx->pb, &c->pb_buffer);
835 for(i=0; i<ctx->nb_streams; i++)
836 av_free(ctx->streams[i]);
838 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
839 current_bandwidth -= c->stream->bandwidth;
841 /* signal that there is no feed if we are the feeder socket */
842 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
843 c->stream->feed_opened = 0;
847 av_freep(&c->pb_buffer);
848 av_freep(&c->packet_buffer);
854 static int handle_connection(HTTPContext *c)
859 case HTTPSTATE_WAIT_REQUEST:
860 case RTSPSTATE_WAIT_REQUEST:
862 if ((c->timeout - cur_time) < 0)
864 if (c->poll_entry->revents & (POLLERR | POLLHUP))
867 /* no need to read if no events */
868 if (!(c->poll_entry->revents & POLLIN))
872 len = recv(c->fd, c->buffer_ptr, 1, 0);
874 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
875 ff_neterrno() != FF_NETERROR(EINTR))
877 } else if (len == 0) {
880 /* search for end of request. */
882 c->buffer_ptr += len;
884 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
885 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
886 /* request found : parse it and reply */
887 if (c->state == HTTPSTATE_WAIT_REQUEST) {
888 ret = http_parse_request(c);
890 ret = rtsp_parse_request(c);
894 } else if (ptr >= c->buffer_end) {
895 /* request too long: cannot do anything */
897 } else goto read_loop;
901 case HTTPSTATE_SEND_HEADER:
902 if (c->poll_entry->revents & (POLLERR | POLLHUP))
905 /* no need to write if no events */
906 if (!(c->poll_entry->revents & POLLOUT))
908 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
910 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
911 ff_neterrno() != FF_NETERROR(EINTR)) {
912 /* error : close connection */
913 av_freep(&c->pb_buffer);
917 c->buffer_ptr += len;
919 c->stream->bytes_served += len;
920 c->data_count += len;
921 if (c->buffer_ptr >= c->buffer_end) {
922 av_freep(&c->pb_buffer);
926 /* all the buffer was sent : synchronize to the incoming stream */
927 c->state = HTTPSTATE_SEND_DATA_HEADER;
928 c->buffer_ptr = c->buffer_end = c->buffer;
933 case HTTPSTATE_SEND_DATA:
934 case HTTPSTATE_SEND_DATA_HEADER:
935 case HTTPSTATE_SEND_DATA_TRAILER:
936 /* for packetized output, we consider we can always write (the
937 input streams sets the speed). It may be better to verify
938 that we do not rely too much on the kernel queues */
939 if (!c->is_packetized) {
940 if (c->poll_entry->revents & (POLLERR | POLLHUP))
943 /* no need to read if no events */
944 if (!(c->poll_entry->revents & POLLOUT))
947 if (http_send_data(c) < 0)
949 /* close connection if trailer sent */
950 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
953 case HTTPSTATE_RECEIVE_DATA:
954 /* no need to read if no events */
955 if (c->poll_entry->revents & (POLLERR | POLLHUP))
957 if (!(c->poll_entry->revents & POLLIN))
959 if (http_receive_data(c) < 0)
962 case HTTPSTATE_WAIT_FEED:
963 /* no need to read if no events */
964 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
967 /* nothing to do, we'll be waken up by incoming feed packets */
970 case RTSPSTATE_SEND_REPLY:
971 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
972 av_freep(&c->pb_buffer);
975 /* no need to write if no events */
976 if (!(c->poll_entry->revents & POLLOUT))
978 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
980 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
981 ff_neterrno() != FF_NETERROR(EINTR)) {
982 /* error : close connection */
983 av_freep(&c->pb_buffer);
987 c->buffer_ptr += len;
988 c->data_count += len;
989 if (c->buffer_ptr >= c->buffer_end) {
990 /* all the buffer was sent : wait for a new request */
991 av_freep(&c->pb_buffer);
992 start_wait_request(c, 1);
996 case RTSPSTATE_SEND_PACKET:
997 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
998 av_freep(&c->packet_buffer);
1001 /* no need to write if no events */
1002 if (!(c->poll_entry->revents & POLLOUT))
1004 len = send(c->fd, c->packet_buffer_ptr,
1005 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1007 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
1008 ff_neterrno() != FF_NETERROR(EINTR)) {
1009 /* error : close connection */
1010 av_freep(&c->packet_buffer);
1014 c->packet_buffer_ptr += len;
1015 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1016 /* all the buffer was sent : wait for a new request */
1017 av_freep(&c->packet_buffer);
1018 c->state = RTSPSTATE_WAIT_REQUEST;
1022 case HTTPSTATE_READY:
1031 static int extract_rates(char *rates, int ratelen, const char *request)
1035 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1036 if (strncasecmp(p, "Pragma:", 7) == 0) {
1037 const char *q = p + 7;
1039 while (*q && *q != '\n' && isspace(*q))
1042 if (strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1048 memset(rates, 0xff, ratelen);
1051 while (*q && *q != '\n' && *q != ':')
1054 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1058 if (stream_no < ratelen && stream_no >= 0)
1059 rates[stream_no] = rate_no;
1061 while (*q && *q != '\n' && !isspace(*q))
1068 p = strchr(p, '\n');
1078 static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
1081 int best_bitrate = 100000000;
1084 for (i = 0; i < feed->nb_streams; i++) {
1085 AVCodecContext *feed_codec = feed->streams[i]->codec;
1087 if (feed_codec->codec_id != codec->codec_id ||
1088 feed_codec->sample_rate != codec->sample_rate ||
1089 feed_codec->width != codec->width ||
1090 feed_codec->height != codec->height)
1093 /* Potential stream */
1095 /* We want the fastest stream less than bit_rate, or the slowest
1096 * faster than bit_rate
1099 if (feed_codec->bit_rate <= bit_rate) {
1100 if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
1101 best_bitrate = feed_codec->bit_rate;
1105 if (feed_codec->bit_rate < best_bitrate) {
1106 best_bitrate = feed_codec->bit_rate;
1115 static int modify_current_stream(HTTPContext *c, char *rates)
1118 FFStream *req = c->stream;
1119 int action_required = 0;
1121 /* Not much we can do for a feed */
1125 for (i = 0; i < req->nb_streams; i++) {
1126 AVCodecContext *codec = req->streams[i]->codec;
1130 c->switch_feed_streams[i] = req->feed_streams[i];
1133 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1136 /* Wants off or slow */
1137 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1139 /* This doesn't work well when it turns off the only stream! */
1140 c->switch_feed_streams[i] = -2;
1141 c->feed_streams[i] = -2;
1146 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1147 action_required = 1;
1150 return action_required;
1154 static void do_switch_stream(HTTPContext *c, int i)
1156 if (c->switch_feed_streams[i] >= 0) {
1158 c->feed_streams[i] = c->switch_feed_streams[i];
1161 /* Now update the stream */
1163 c->switch_feed_streams[i] = -1;
1166 /* XXX: factorize in utils.c ? */
1167 /* XXX: take care with different space meaning */
1168 static void skip_spaces(const char **pp)
1172 while (*p == ' ' || *p == '\t')
1177 static void get_word(char *buf, int buf_size, const char **pp)
1185 while (!isspace(*p) && *p != '\0') {
1186 if ((q - buf) < buf_size - 1)
1195 static void get_arg(char *buf, int buf_size, const char **pp)
1202 while (isspace(*p)) p++;
1205 if (*p == '\"' || *p == '\'')
1217 if ((q - buf) < buf_size - 1)
1222 if (quote && *p == quote)
1227 static int validate_acl(FFStream *stream, HTTPContext *c)
1229 enum IPAddressAction last_action = IP_DENY;
1231 struct in_addr *src = &c->from_addr.sin_addr;
1232 unsigned long src_addr = src->s_addr;
1234 for (acl = stream->acl; acl; acl = acl->next) {
1235 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1236 return (acl->action == IP_ALLOW) ? 1 : 0;
1237 last_action = acl->action;
1240 /* Nothing matched, so return not the last action */
1241 return (last_action == IP_DENY) ? 1 : 0;
1244 /* compute the real filename of a file by matching it without its
1245 extensions to all the stream filenames */
1246 static void compute_real_filename(char *filename, int max_size)
1253 /* compute filename by matching without the file extensions */
1254 av_strlcpy(file1, filename, sizeof(file1));
1255 p = strrchr(file1, '.');
1258 for(stream = first_stream; stream != NULL; stream = stream->next) {
1259 av_strlcpy(file2, stream->filename, sizeof(file2));
1260 p = strrchr(file2, '.');
1263 if (!strcmp(file1, file2)) {
1264 av_strlcpy(filename, stream->filename, max_size);
1279 /* parse http request and prepare header */
1280 static int http_parse_request(HTTPContext *c)
1283 enum RedirType redir_type;
1285 char info[1024], filename[1024];
1289 const char *mime_type;
1293 char *useragent = 0;
1296 get_word(cmd, sizeof(cmd), (const char **)&p);
1297 av_strlcpy(c->method, cmd, sizeof(c->method));
1299 if (!strcmp(cmd, "GET"))
1301 else if (!strcmp(cmd, "POST"))
1306 get_word(url, sizeof(url), (const char **)&p);
1307 av_strlcpy(c->url, url, sizeof(c->url));
1309 get_word(protocol, sizeof(protocol), (const char **)&p);
1310 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1313 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1316 http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);
1318 /* find the filename and the optional info string in the request */
1319 p = strchr(url, '?');
1321 av_strlcpy(info, p, sizeof(info));
1326 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1328 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1329 if (strncasecmp(p, "User-Agent:", 11) == 0) {
1331 if (*useragent && *useragent != '\n' && isspace(*useragent))
1335 p = strchr(p, '\n');
1342 redir_type = REDIR_NONE;
1343 if (av_match_ext(filename, "asx")) {
1344 redir_type = REDIR_ASX;
1345 filename[strlen(filename)-1] = 'f';
1346 } else if (av_match_ext(filename, "asf") &&
1347 (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1348 /* if this isn't WMP or lookalike, return the redirector file */
1349 redir_type = REDIR_ASF;
1350 } else if (av_match_ext(filename, "rpm,ram")) {
1351 redir_type = REDIR_RAM;
1352 strcpy(filename + strlen(filename)-2, "m");
1353 } else if (av_match_ext(filename, "rtsp")) {
1354 redir_type = REDIR_RTSP;
1355 compute_real_filename(filename, sizeof(filename) - 1);
1356 } else if (av_match_ext(filename, "sdp")) {
1357 redir_type = REDIR_SDP;
1358 compute_real_filename(filename, sizeof(filename) - 1);
1361 // "redirect" / request to index.html
1362 if (!strlen(filename))
1363 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1365 stream = first_stream;
1366 while (stream != NULL) {
1367 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1369 stream = stream->next;
1371 if (stream == NULL) {
1372 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1373 http_log("File '%s' not found\n", url);
1378 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1379 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1381 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1382 c->http_error = 301;
1384 q += snprintf(q, c->buffer_size,
1385 "HTTP/1.0 301 Moved\r\n"
1387 "Content-type: text/html\r\n"
1389 "<html><head><title>Moved</title></head><body>\r\n"
1390 "You should be <a href=\"%s\">redirected</a>.\r\n"
1391 "</body></html>\r\n", stream->feed_filename, stream->feed_filename);
1392 /* prepare output buffer */
1393 c->buffer_ptr = c->buffer;
1395 c->state = HTTPSTATE_SEND_HEADER;
1399 /* If this is WMP, get the rate information */
1400 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1401 if (modify_current_stream(c, ratebuf)) {
1402 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1403 if (c->switch_feed_streams[i] >= 0)
1404 do_switch_stream(c, i);
1409 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1410 current_bandwidth += stream->bandwidth;
1412 /* If already streaming this feed, do not let start another feeder. */
1413 if (stream->feed_opened) {
1414 snprintf(msg, sizeof(msg), "This feed is already being received.");
1415 http_log("Feed '%s' already being received\n", stream->feed_filename);
1419 if (c->post == 0 && max_bandwidth < current_bandwidth) {
1420 c->http_error = 200;
1422 q += snprintf(q, c->buffer_size,
1423 "HTTP/1.0 200 Server too busy\r\n"
1424 "Content-type: text/html\r\n"
1426 "<html><head><title>Too busy</title></head><body>\r\n"
1427 "<p>The server is too busy to serve your request at this time.</p>\r\n"
1428 "<p>The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "
1429 "and this exceeds the limit of %"PRIu64"kbit/sec.</p>\r\n"
1430 "</body></html>\r\n", current_bandwidth, max_bandwidth);
1431 /* prepare output buffer */
1432 c->buffer_ptr = c->buffer;
1434 c->state = HTTPSTATE_SEND_HEADER;
1438 if (redir_type != REDIR_NONE) {
1441 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1442 if (strncasecmp(p, "Host:", 5) == 0) {
1446 p = strchr(p, '\n');
1457 while (isspace(*hostinfo))
1460 eoh = strchr(hostinfo, '\n');
1462 if (eoh[-1] == '\r')
1465 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1466 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1467 hostbuf[eoh - hostinfo] = 0;
1469 c->http_error = 200;
1471 switch(redir_type) {
1473 q += snprintf(q, c->buffer_size,
1474 "HTTP/1.0 200 ASX Follows\r\n"
1475 "Content-type: video/x-ms-asf\r\n"
1477 "<ASX Version=\"3\">\r\n"
1478 //"<!-- Autogenerated by ffserver -->\r\n"
1479 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1480 "</ASX>\r\n", hostbuf, filename, info);
1483 q += snprintf(q, c->buffer_size,
1484 "HTTP/1.0 200 RAM Follows\r\n"
1485 "Content-type: audio/x-pn-realaudio\r\n"
1487 "# Autogenerated by ffserver\r\n"
1488 "http://%s/%s%s\r\n", hostbuf, filename, info);
1491 q += snprintf(q, c->buffer_size,
1492 "HTTP/1.0 200 ASF Redirect follows\r\n"
1493 "Content-type: video/x-ms-asf\r\n"
1496 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1500 char hostname[256], *p;
1501 /* extract only hostname */
1502 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1503 p = strrchr(hostname, ':');
1506 q += snprintf(q, c->buffer_size,
1507 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1508 /* XXX: incorrect mime type ? */
1509 "Content-type: application/x-rtsp\r\n"
1511 "rtsp://%s:%d/%s\r\n", hostname, ntohs(my_rtsp_addr.sin_port), filename);
1517 int sdp_data_size, len;
1518 struct sockaddr_in my_addr;
1520 q += snprintf(q, c->buffer_size,
1521 "HTTP/1.0 200 OK\r\n"
1522 "Content-type: application/sdp\r\n"
1525 len = sizeof(my_addr);
1526 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
1528 /* XXX: should use a dynamic buffer */
1529 sdp_data_size = prepare_sdp_description(stream,
1532 if (sdp_data_size > 0) {
1533 memcpy(q, sdp_data, sdp_data_size);
1545 /* prepare output buffer */
1546 c->buffer_ptr = c->buffer;
1548 c->state = HTTPSTATE_SEND_HEADER;
1554 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1558 stream->conns_served++;
1560 /* XXX: add there authenticate and IP match */
1563 /* if post, it means a feed is being sent */
1564 if (!stream->is_feed) {
1565 /* However it might be a status report from WMP! Let us log the
1566 * data as it might come in handy one day. */
1570 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1571 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1575 if (strncasecmp(p, "Pragma: client-id=", 18) == 0)
1576 client_id = strtol(p + 18, 0, 10);
1577 p = strchr(p, '\n');
1585 char *eol = strchr(logline, '\n');
1590 if (eol[-1] == '\r')
1592 http_log("%.*s\n", (int) (eol - logline), logline);
1593 c->suppress_log = 1;
1598 http_log("\nGot request:\n%s\n", c->buffer);
1601 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1604 /* Now we have to find the client_id */
1605 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1606 if (wmpc->wmp_client_id == client_id)
1610 if (wmpc && modify_current_stream(wmpc, ratebuf))
1611 wmpc->switch_pending = 1;
1614 snprintf(msg, sizeof(msg), "POST command not handled");
1618 if (http_start_receive_data(c) < 0) {
1619 snprintf(msg, sizeof(msg), "could not open feed");
1623 c->state = HTTPSTATE_RECEIVE_DATA;
1628 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1629 http_log("\nGot request:\n%s\n", c->buffer);
1632 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1635 /* open input stream */
1636 if (open_input_stream(c, info) < 0) {
1637 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1641 /* prepare http header */
1643 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
1644 mime_type = c->stream->fmt->mime_type;
1646 mime_type = "application/x-octet-stream";
1647 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Pragma: no-cache\r\n");
1649 /* for asf, we need extra headers */
1650 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1651 /* Need to allocate a client id */
1653 c->wmp_client_id = av_lfg_get(&random_state);
1655 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);
1657 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-Type: %s\r\n", mime_type);
1658 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1660 /* prepare output buffer */
1662 c->buffer_ptr = c->buffer;
1664 c->state = HTTPSTATE_SEND_HEADER;
1667 c->http_error = 404;
1669 q += snprintf(q, c->buffer_size,
1670 "HTTP/1.0 404 Not Found\r\n"
1671 "Content-type: text/html\r\n"
1674 "<head><title>404 Not Found</title></head>\n"
1677 /* prepare output buffer */
1678 c->buffer_ptr = c->buffer;
1680 c->state = HTTPSTATE_SEND_HEADER;
1684 c->http_error = 200; /* horrible : we use this value to avoid
1685 going to the send data state */
1686 c->state = HTTPSTATE_SEND_HEADER;
1690 static void fmt_bytecount(ByteIOContext *pb, int64_t count)
1692 static const char *suffix = " kMGTP";
1695 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1697 url_fprintf(pb, "%"PRId64"%c", count, *s);
1700 static void compute_status(HTTPContext *c)
1709 if (url_open_dyn_buf(&pb) < 0) {
1710 /* XXX: return an error ? */
1711 c->buffer_ptr = c->buffer;
1712 c->buffer_end = c->buffer;
1716 url_fprintf(pb, "HTTP/1.0 200 OK\r\n");
1717 url_fprintf(pb, "Content-type: %s\r\n", "text/html");
1718 url_fprintf(pb, "Pragma: no-cache\r\n");
1719 url_fprintf(pb, "\r\n");
1721 url_fprintf(pb, "<html><head><title>%s Status</title>\n", program_name);
1722 if (c->stream->feed_filename[0])
1723 url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
1724 url_fprintf(pb, "</head>\n<body>");
1725 url_fprintf(pb, "<h1>%s Status</h1>\n", program_name);
1727 url_fprintf(pb, "<h2>Available Streams</h2>\n");
1728 url_fprintf(pb, "<table cellspacing=0 cellpadding=4>\n");
1729 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");
1730 stream = first_stream;
1731 while (stream != NULL) {
1732 char sfilename[1024];
1735 if (stream->feed != stream) {
1736 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1737 eosf = sfilename + strlen(sfilename);
1738 if (eosf - sfilename >= 4) {
1739 if (strcmp(eosf - 4, ".asf") == 0)
1740 strcpy(eosf - 4, ".asx");
1741 else if (strcmp(eosf - 3, ".rm") == 0)
1742 strcpy(eosf - 3, ".ram");
1743 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1744 /* generate a sample RTSP director if
1745 unicast. Generate an SDP redirector if
1747 eosf = strrchr(sfilename, '.');
1749 eosf = sfilename + strlen(sfilename);
1750 if (stream->is_multicast)
1751 strcpy(eosf, ".sdp");
1753 strcpy(eosf, ".rtsp");
1757 url_fprintf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1758 sfilename, stream->filename);
1759 url_fprintf(pb, "<td align=right> %d <td align=right> ",
1760 stream->conns_served);
1761 fmt_bytecount(pb, stream->bytes_served);
1762 switch(stream->stream_type) {
1763 case STREAM_TYPE_LIVE: {
1764 int audio_bit_rate = 0;
1765 int video_bit_rate = 0;
1766 const char *audio_codec_name = "";
1767 const char *video_codec_name = "";
1768 const char *audio_codec_name_extra = "";
1769 const char *video_codec_name_extra = "";
1771 for(i=0;i<stream->nb_streams;i++) {
1772 AVStream *st = stream->streams[i];
1773 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1774 switch(st->codec->codec_type) {
1775 case CODEC_TYPE_AUDIO:
1776 audio_bit_rate += st->codec->bit_rate;
1778 if (*audio_codec_name)
1779 audio_codec_name_extra = "...";
1780 audio_codec_name = codec->name;
1783 case CODEC_TYPE_VIDEO:
1784 video_bit_rate += st->codec->bit_rate;
1786 if (*video_codec_name)
1787 video_codec_name_extra = "...";
1788 video_codec_name = codec->name;
1791 case CODEC_TYPE_DATA:
1792 video_bit_rate += st->codec->bit_rate;
1798 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",
1801 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
1802 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
1804 url_fprintf(pb, "<td>%s", stream->feed->filename);
1806 url_fprintf(pb, "<td>%s", stream->feed_filename);
1807 url_fprintf(pb, "\n");
1811 url_fprintf(pb, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
1815 stream = stream->next;
1817 url_fprintf(pb, "</table>\n");
1819 stream = first_stream;
1820 while (stream != NULL) {
1821 if (stream->feed == stream) {
1822 url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
1824 url_fprintf(pb, "Running as pid %d.\n", stream->pid);
1826 #if defined(linux) && !defined(CONFIG_NOCUTILS)
1831 /* This is somewhat linux specific I guess */
1832 snprintf(ps_cmd, sizeof(ps_cmd),
1833 "ps -o \"%%cpu,cputime\" --no-headers %d",
1836 pid_stat = popen(ps_cmd, "r");
1841 if (fscanf(pid_stat, "%10s %64s", cpuperc,
1843 url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
1851 url_fprintf(pb, "<p>");
1853 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");
1855 for (i = 0; i < stream->nb_streams; i++) {
1856 AVStream *st = stream->streams[i];
1857 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1858 const char *type = "unknown";
1859 char parameters[64];
1863 switch(st->codec->codec_type) {
1864 case CODEC_TYPE_AUDIO:
1866 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz", st->codec->channels, st->codec->sample_rate);
1868 case CODEC_TYPE_VIDEO:
1870 snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec->width, st->codec->height,
1871 st->codec->qmin, st->codec->qmax, st->codec->time_base.den / st->codec->time_base.num);
1876 url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
1877 i, type, st->codec->bit_rate/1000, codec ? codec->name : "", parameters);
1879 url_fprintf(pb, "</table>\n");
1882 stream = stream->next;
1885 /* connection status */
1886 url_fprintf(pb, "<h2>Connection Status</h2>\n");
1888 url_fprintf(pb, "Number of connections: %d / %d<br>\n",
1889 nb_connections, nb_max_connections);
1891 url_fprintf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
1892 current_bandwidth, max_bandwidth);
1894 url_fprintf(pb, "<table>\n");
1895 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");
1896 c1 = first_http_ctx;
1898 while (c1 != NULL) {
1904 for (j = 0; j < c1->stream->nb_streams; j++) {
1905 if (!c1->stream->feed)
1906 bitrate += c1->stream->streams[j]->codec->bit_rate;
1907 else if (c1->feed_streams[j] >= 0)
1908 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
1913 p = inet_ntoa(c1->from_addr.sin_addr);
1914 url_fprintf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
1916 c1->stream ? c1->stream->filename : "",
1917 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
1920 http_state[c1->state]);
1921 fmt_bytecount(pb, bitrate);
1922 url_fprintf(pb, "<td align=right>");
1923 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
1924 url_fprintf(pb, "<td align=right>");
1925 fmt_bytecount(pb, c1->data_count);
1926 url_fprintf(pb, "\n");
1929 url_fprintf(pb, "</table>\n");
1934 url_fprintf(pb, "<hr size=1 noshade>Generated at %s", p);
1935 url_fprintf(pb, "</body>\n</html>\n");
1937 len = url_close_dyn_buf(pb, &c->pb_buffer);
1938 c->buffer_ptr = c->pb_buffer;
1939 c->buffer_end = c->pb_buffer + len;
1942 /* check if the parser needs to be opened for stream i */
1943 static void open_parser(AVFormatContext *s, int i)
1945 AVStream *st = s->streams[i];
1948 if (!st->codec->codec) {
1949 codec = avcodec_find_decoder(st->codec->codec_id);
1950 if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) {
1951 st->codec->parse_only = 1;
1952 if (avcodec_open(st->codec, codec) < 0)
1953 st->codec->parse_only = 0;
1958 static int open_input_stream(HTTPContext *c, const char *info)
1961 char input_filename[1024];
1963 int buf_size, i, ret;
1966 /* find file name */
1967 if (c->stream->feed) {
1968 strcpy(input_filename, c->stream->feed->feed_filename);
1969 buf_size = FFM_PACKET_SIZE;
1970 /* compute position (absolute time) */
1971 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1972 stream_pos = parse_date(buf, 0);
1973 if (stream_pos == INT64_MIN)
1975 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
1976 int prebuffer = strtol(buf, 0, 10);
1977 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
1979 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
1981 strcpy(input_filename, c->stream->feed_filename);
1983 /* compute position (relative time) */
1984 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1985 stream_pos = parse_date(buf, 1);
1986 if (stream_pos == INT64_MIN)
1991 if (input_filename[0] == '\0')
1995 if ((ret = av_open_input_file(&s, input_filename, c->stream->ifmt,
1996 buf_size, c->stream->ap_in)) < 0) {
1997 http_log("could not open %s: %d\n", input_filename, ret);
2000 s->flags |= AVFMT_FLAG_GENPTS;
2002 if (strcmp(s->iformat->name, "ffm") && av_find_stream_info(c->fmt_in) < 0) {
2003 http_log("Could not find stream info '%s'\n", input_filename);
2004 av_close_input_file(s);
2008 /* open each parser */
2009 for(i=0;i<s->nb_streams;i++)
2012 /* choose stream as clock source (we favorize video stream if
2013 present) for packet sending */
2014 c->pts_stream_index = 0;
2015 for(i=0;i<c->stream->nb_streams;i++) {
2016 if (c->pts_stream_index == 0 &&
2017 c->stream->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO) {
2018 c->pts_stream_index = i;
2023 if (c->fmt_in->iformat->read_seek)
2024 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2026 /* set the start time (needed for maxtime and RTP packet timing) */
2027 c->start_time = cur_time;
2028 c->first_pts = AV_NOPTS_VALUE;
2032 /* return the server clock (in us) */
2033 static int64_t get_server_clock(HTTPContext *c)
2035 /* compute current pts value from system time */
2036 return (cur_time - c->start_time) * 1000;
2039 /* return the estimated time at which the current packet must be sent
2041 static int64_t get_packet_send_clock(HTTPContext *c)
2043 int bytes_left, bytes_sent, frame_bytes;
2045 frame_bytes = c->cur_frame_bytes;
2046 if (frame_bytes <= 0)
2049 bytes_left = c->buffer_end - c->buffer_ptr;
2050 bytes_sent = frame_bytes - bytes_left;
2051 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2056 static int http_prepare_data(HTTPContext *c)
2059 AVFormatContext *ctx;
2061 av_freep(&c->pb_buffer);
2063 case HTTPSTATE_SEND_DATA_HEADER:
2064 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
2065 av_metadata_set(&c->fmt_ctx.metadata, "author" ,c->stream->author);
2066 av_metadata_set(&c->fmt_ctx.metadata, "comment" ,c->stream->comment);
2067 av_metadata_set(&c->fmt_ctx.metadata, "copyright",c->stream->copyright);
2068 av_metadata_set(&c->fmt_ctx.metadata, "title" ,c->stream->title);
2070 for(i=0;i<c->stream->nb_streams;i++) {
2073 st = av_mallocz(sizeof(AVStream));
2074 c->fmt_ctx.streams[i] = st;
2075 /* if file or feed, then just take streams from FFStream struct */
2076 if (!c->stream->feed ||
2077 c->stream->feed == c->stream)
2078 src = c->stream->streams[i];
2080 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2084 st->codec->frame_number = 0; /* XXX: should be done in
2085 AVStream, not in codec */
2087 /* set output format parameters */
2088 c->fmt_ctx.oformat = c->stream->fmt;
2089 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2091 c->got_key_frame = 0;
2093 /* prepare header and save header data in a stream */
2094 if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2095 /* XXX: potential leak */
2098 c->fmt_ctx.pb->is_streamed = 1;
2101 * HACK to avoid mpeg ps muxer to spit many underflow errors
2102 * Default value from FFmpeg
2103 * Try to set it use configuration option
2105 c->fmt_ctx.preload = (int)(0.5*AV_TIME_BASE);
2106 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2108 av_set_parameters(&c->fmt_ctx, NULL);
2109 if (av_write_header(&c->fmt_ctx) < 0) {
2110 http_log("Error writing output header\n");
2114 len = url_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2115 c->buffer_ptr = c->pb_buffer;
2116 c->buffer_end = c->pb_buffer + len;
2118 c->state = HTTPSTATE_SEND_DATA;
2119 c->last_packet_sent = 0;
2121 case HTTPSTATE_SEND_DATA:
2122 /* find a new packet */
2123 /* read a packet from the input stream */
2124 if (c->stream->feed)
2125 ffm_set_write_index(c->fmt_in,
2126 c->stream->feed->feed_write_index,
2127 c->stream->feed->feed_size);
2129 if (c->stream->max_time &&
2130 c->stream->max_time + c->start_time - cur_time < 0)
2131 /* We have timed out */
2132 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2136 if (av_read_frame(c->fmt_in, &pkt) < 0) {
2137 if (c->stream->feed && c->stream->feed->feed_opened) {
2138 /* if coming from feed, it means we reached the end of the
2139 ffm file, so must wait for more data */
2140 c->state = HTTPSTATE_WAIT_FEED;
2141 return 1; /* state changed */
2143 if (c->stream->loop) {
2144 av_close_input_file(c->fmt_in);
2146 if (open_input_stream(c, "") < 0)
2151 /* must send trailer now because eof or error */
2152 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2156 int source_index = pkt.stream_index;
2157 /* update first pts if needed */
2158 if (c->first_pts == AV_NOPTS_VALUE) {
2159 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2160 c->start_time = cur_time;
2162 /* send it to the appropriate stream */
2163 if (c->stream->feed) {
2164 /* if coming from a feed, select the right stream */
2165 if (c->switch_pending) {
2166 c->switch_pending = 0;
2167 for(i=0;i<c->stream->nb_streams;i++) {
2168 if (c->switch_feed_streams[i] == pkt.stream_index)
2169 if (pkt.flags & PKT_FLAG_KEY)
2170 do_switch_stream(c, i);
2171 if (c->switch_feed_streams[i] >= 0)
2172 c->switch_pending = 1;
2175 for(i=0;i<c->stream->nb_streams;i++) {
2176 if (c->feed_streams[i] == pkt.stream_index) {
2177 AVStream *st = c->fmt_in->streams[source_index];
2178 pkt.stream_index = i;
2179 if (pkt.flags & PKT_FLAG_KEY &&
2180 (st->codec->codec_type == CODEC_TYPE_VIDEO ||
2181 c->stream->nb_streams == 1))
2182 c->got_key_frame = 1;
2183 if (!c->stream->send_on_key || c->got_key_frame)
2188 AVCodecContext *codec;
2189 AVStream *ist, *ost;
2191 ist = c->fmt_in->streams[source_index];
2192 /* specific handling for RTP: we use several
2193 output stream (one for each RTP
2194 connection). XXX: need more abstract handling */
2195 if (c->is_packetized) {
2196 /* compute send time and duration */
2197 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2198 if (ist->start_time != AV_NOPTS_VALUE)
2199 c->cur_pts -= av_rescale_q(ist->start_time, ist->time_base, AV_TIME_BASE_Q);
2200 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2201 /* find RTP context */
2202 c->packet_stream_index = pkt.stream_index;
2203 ctx = c->rtp_ctx[c->packet_stream_index];
2205 av_free_packet(&pkt);
2208 codec = ctx->streams[0]->codec;
2209 /* only one stream per RTP connection */
2210 pkt.stream_index = 0;
2214 codec = ctx->streams[pkt.stream_index]->codec;
2217 if (c->is_packetized) {
2218 int max_packet_size;
2219 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2220 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2222 max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]);
2223 ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size);
2225 ret = url_open_dyn_buf(&ctx->pb);
2228 /* XXX: potential leak */
2231 ost = ctx->streams[pkt.stream_index];
2233 ctx->pb->is_streamed = 1;
2234 if (pkt.dts != AV_NOPTS_VALUE)
2235 pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base);
2236 if (pkt.pts != AV_NOPTS_VALUE)
2237 pkt.pts = av_rescale_q(pkt.pts, ist->time_base, ost->time_base);
2238 pkt.duration = av_rescale_q(pkt.duration, ist->time_base, ost->time_base);
2239 if (av_write_frame(ctx, &pkt) < 0) {
2240 http_log("Error writing frame to output\n");
2241 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2244 len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
2245 c->cur_frame_bytes = len;
2246 c->buffer_ptr = c->pb_buffer;
2247 c->buffer_end = c->pb_buffer + len;
2249 codec->frame_number++;
2251 av_free_packet(&pkt);
2255 av_free_packet(&pkt);
2260 case HTTPSTATE_SEND_DATA_TRAILER:
2261 /* last packet test ? */
2262 if (c->last_packet_sent || c->is_packetized)
2265 /* prepare header */
2266 if (url_open_dyn_buf(&ctx->pb) < 0) {
2267 /* XXX: potential leak */
2270 c->fmt_ctx.pb->is_streamed = 1;
2271 av_write_trailer(ctx);
2272 len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
2273 c->buffer_ptr = c->pb_buffer;
2274 c->buffer_end = c->pb_buffer + len;
2276 c->last_packet_sent = 1;
2282 /* should convert the format at the same time */
2283 /* send data starting at c->buffer_ptr to the output connection
2284 (either UDP or TCP connection) */
2285 static int http_send_data(HTTPContext *c)
2290 if (c->buffer_ptr >= c->buffer_end) {
2291 ret = http_prepare_data(c);
2295 /* state change requested */
2298 if (c->is_packetized) {
2299 /* RTP data output */
2300 len = c->buffer_end - c->buffer_ptr;
2302 /* fail safe - should never happen */
2304 c->buffer_ptr = c->buffer_end;
2307 len = (c->buffer_ptr[0] << 24) |
2308 (c->buffer_ptr[1] << 16) |
2309 (c->buffer_ptr[2] << 8) |
2311 if (len > (c->buffer_end - c->buffer_ptr))
2313 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2314 /* nothing to send yet: we can wait */
2318 c->data_count += len;
2319 update_datarate(&c->datarate, c->data_count);
2321 c->stream->bytes_served += len;
2323 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2324 /* RTP packets are sent inside the RTSP TCP connection */
2326 int interleaved_index, size;
2328 HTTPContext *rtsp_c;
2331 /* if no RTSP connection left, error */
2334 /* if already sending something, then wait. */
2335 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2337 if (url_open_dyn_buf(&pb) < 0)
2339 interleaved_index = c->packet_stream_index * 2;
2340 /* RTCP packets are sent at odd indexes */
2341 if (c->buffer_ptr[1] == 200)
2342 interleaved_index++;
2343 /* write RTSP TCP header */
2345 header[1] = interleaved_index;
2346 header[2] = len >> 8;
2348 put_buffer(pb, header, 4);
2349 /* write RTP packet data */
2351 put_buffer(pb, c->buffer_ptr, len);
2352 size = url_close_dyn_buf(pb, &c->packet_buffer);
2353 /* prepare asynchronous TCP sending */
2354 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2355 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2356 c->buffer_ptr += len;
2358 /* send everything we can NOW */
2359 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2360 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2362 rtsp_c->packet_buffer_ptr += len;
2363 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2364 /* if we could not send all the data, we will
2365 send it later, so a new state is needed to
2366 "lock" the RTSP TCP connection */
2367 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2370 /* all data has been sent */
2371 av_freep(&c->packet_buffer);
2373 /* send RTP packet directly in UDP */
2375 url_write(c->rtp_handles[c->packet_stream_index],
2376 c->buffer_ptr, len);
2377 c->buffer_ptr += len;
2378 /* here we continue as we can send several packets per 10 ms slot */
2381 /* TCP data output */
2382 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
2384 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2385 ff_neterrno() != FF_NETERROR(EINTR))
2386 /* error : close connection */
2391 c->buffer_ptr += len;
2393 c->data_count += len;
2394 update_datarate(&c->datarate, c->data_count);
2396 c->stream->bytes_served += len;
2404 static int http_start_receive_data(HTTPContext *c)
2408 if (c->stream->feed_opened)
2411 /* Don't permit writing to this one */
2412 if (c->stream->readonly)
2416 fd = open(c->stream->feed_filename, O_RDWR);
2418 http_log("Error opening feeder file: %s\n", strerror(errno));
2423 if (c->stream->truncate) {
2424 /* truncate feed file */
2425 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2426 ftruncate(c->feed_fd, FFM_PACKET_SIZE);
2427 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2429 if ((c->stream->feed_write_index = ffm_read_write_index(fd)) < 0) {
2430 http_log("Error reading write index from feed file: %s\n", strerror(errno));
2435 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
2436 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2437 lseek(fd, 0, SEEK_SET);
2439 /* init buffer input */
2440 c->buffer_ptr = c->buffer;
2441 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2442 c->stream->feed_opened = 1;
2446 static int http_receive_data(HTTPContext *c)
2450 if (c->buffer_end > c->buffer_ptr) {
2453 len = recv(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
2455 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2456 ff_neterrno() != FF_NETERROR(EINTR))
2457 /* error : close connection */
2459 } else if (len == 0)
2460 /* end of connection : close it */
2463 c->buffer_ptr += len;
2464 c->data_count += len;
2465 update_datarate(&c->datarate, c->data_count);
2469 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2470 if (c->buffer[0] != 'f' ||
2471 c->buffer[1] != 'm') {
2472 http_log("Feed stream has become desynchronized -- disconnecting\n");
2477 if (c->buffer_ptr >= c->buffer_end) {
2478 FFStream *feed = c->stream;
2479 /* a packet has been received : write it in the store, except
2481 if (c->data_count > FFM_PACKET_SIZE) {
2483 // printf("writing pos=0x%"PRIx64" size=0x%"PRIx64"\n", feed->feed_write_index, feed->feed_size);
2484 /* XXX: use llseek or url_seek */
2485 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
2486 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2487 http_log("Error writing to feed file: %s\n", strerror(errno));
2491 feed->feed_write_index += FFM_PACKET_SIZE;
2492 /* update file size */
2493 if (feed->feed_write_index > c->stream->feed_size)
2494 feed->feed_size = feed->feed_write_index;
2496 /* handle wrap around if max file size reached */
2497 if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size)
2498 feed->feed_write_index = FFM_PACKET_SIZE;
2501 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2502 http_log("Error writing index to feed file: %s\n", strerror(errno));
2506 /* wake up any waiting connections */
2507 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2508 if (c1->state == HTTPSTATE_WAIT_FEED &&
2509 c1->stream->feed == c->stream->feed)
2510 c1->state = HTTPSTATE_SEND_DATA;
2513 /* We have a header in our hands that contains useful data */
2514 AVFormatContext *s = NULL;
2516 AVInputFormat *fmt_in;
2519 /* use feed output format name to find corresponding input format */
2520 fmt_in = av_find_input_format(feed->fmt->name);
2524 url_open_buf(&pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
2525 pb->is_streamed = 1;
2527 if (av_open_input_stream(&s, pb, c->stream->feed_filename, fmt_in, NULL) < 0) {
2532 /* Now we have the actual streams */
2533 if (s->nb_streams != feed->nb_streams) {
2534 av_close_input_stream(s);
2536 http_log("Feed '%s' stream number does not match registered feed\n",
2537 c->stream->feed_filename);
2541 for (i = 0; i < s->nb_streams; i++) {
2542 AVStream *fst = feed->streams[i];
2543 AVStream *st = s->streams[i];
2544 memcpy(fst->codec, st->codec, sizeof(AVCodecContext));
2545 if (fst->codec->extradata_size) {
2546 fst->codec->extradata = av_malloc(fst->codec->extradata_size);
2547 if (!fst->codec->extradata)
2549 memcpy(fst->codec->extradata, st->codec->extradata,
2550 fst->codec->extradata_size);
2554 av_close_input_stream(s);
2557 c->buffer_ptr = c->buffer;
2562 c->stream->feed_opened = 0;
2564 /* wake up any waiting connections to stop waiting for feed */
2565 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2566 if (c1->state == HTTPSTATE_WAIT_FEED &&
2567 c1->stream->feed == c->stream->feed)
2568 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2573 /********************************************************************/
2576 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2583 switch(error_number) {
2584 case RTSP_STATUS_OK:
2587 case RTSP_STATUS_METHOD:
2588 str = "Method Not Allowed";
2590 case RTSP_STATUS_BANDWIDTH:
2591 str = "Not Enough Bandwidth";
2593 case RTSP_STATUS_SESSION:
2594 str = "Session Not Found";
2596 case RTSP_STATUS_STATE:
2597 str = "Method Not Valid in This State";
2599 case RTSP_STATUS_AGGREGATE:
2600 str = "Aggregate operation not allowed";
2602 case RTSP_STATUS_ONLY_AGGREGATE:
2603 str = "Only aggregate operation allowed";
2605 case RTSP_STATUS_TRANSPORT:
2606 str = "Unsupported transport";
2608 case RTSP_STATUS_INTERNAL:
2609 str = "Internal Server Error";
2611 case RTSP_STATUS_SERVICE:
2612 str = "Service Unavailable";
2614 case RTSP_STATUS_VERSION:
2615 str = "RTSP Version not supported";
2618 str = "Unknown Error";
2622 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2623 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2625 /* output GMT time */
2629 p = buf2 + strlen(p) - 1;
2632 url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
2635 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2637 rtsp_reply_header(c, error_number);
2638 url_fprintf(c->pb, "\r\n");
2641 static int rtsp_parse_request(HTTPContext *c)
2643 const char *p, *p1, *p2;
2649 RTSPMessageHeader header1, *header = &header1;
2651 c->buffer_ptr[0] = '\0';
2654 get_word(cmd, sizeof(cmd), &p);
2655 get_word(url, sizeof(url), &p);
2656 get_word(protocol, sizeof(protocol), &p);
2658 av_strlcpy(c->method, cmd, sizeof(c->method));
2659 av_strlcpy(c->url, url, sizeof(c->url));
2660 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2662 if (url_open_dyn_buf(&c->pb) < 0) {
2663 /* XXX: cannot do more */
2664 c->pb = NULL; /* safety */
2668 /* check version name */
2669 if (strcmp(protocol, "RTSP/1.0") != 0) {
2670 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2674 /* parse each header line */
2675 memset(header, 0, sizeof(*header));
2676 /* skip to next line */
2677 while (*p != '\n' && *p != '\0')
2681 while (*p != '\0') {
2682 p1 = strchr(p, '\n');
2686 if (p2 > p && p2[-1] == '\r')
2688 /* skip empty line */
2692 if (len > sizeof(line) - 1)
2693 len = sizeof(line) - 1;
2694 memcpy(line, p, len);
2696 rtsp_parse_line(header, line);
2700 /* handle sequence number */
2701 c->seq = header->seq;
2703 if (!strcmp(cmd, "DESCRIBE"))
2704 rtsp_cmd_describe(c, url);
2705 else if (!strcmp(cmd, "OPTIONS"))
2706 rtsp_cmd_options(c, url);
2707 else if (!strcmp(cmd, "SETUP"))
2708 rtsp_cmd_setup(c, url, header);
2709 else if (!strcmp(cmd, "PLAY"))
2710 rtsp_cmd_play(c, url, header);
2711 else if (!strcmp(cmd, "PAUSE"))
2712 rtsp_cmd_pause(c, url, header);
2713 else if (!strcmp(cmd, "TEARDOWN"))
2714 rtsp_cmd_teardown(c, url, header);
2716 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2719 len = url_close_dyn_buf(c->pb, &c->pb_buffer);
2720 c->pb = NULL; /* safety */
2722 /* XXX: cannot do more */
2725 c->buffer_ptr = c->pb_buffer;
2726 c->buffer_end = c->pb_buffer + len;
2727 c->state = RTSPSTATE_SEND_REPLY;
2731 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
2732 struct in_addr my_ip)
2734 AVFormatContext *avc;
2735 AVStream avs[MAX_STREAMS];
2738 avc = avformat_alloc_context();
2742 av_metadata_set(&avc->metadata, "title",
2743 stream->title[0] ? stream->title : "No Title");
2744 avc->nb_streams = stream->nb_streams;
2745 if (stream->is_multicast) {
2746 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2747 inet_ntoa(stream->multicast_ip),
2748 stream->multicast_port, stream->multicast_ttl);
2751 for(i = 0; i < stream->nb_streams; i++) {
2752 avc->streams[i] = &avs[i];
2753 avc->streams[i]->codec = stream->streams[i]->codec;
2755 *pbuffer = av_mallocz(2048);
2756 avf_sdp_create(&avc, 1, *pbuffer, 2048);
2759 return strlen(*pbuffer);
2762 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2764 // rtsp_reply_header(c, RTSP_STATUS_OK);
2765 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2766 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2767 url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2768 url_fprintf(c->pb, "\r\n");
2771 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2777 int content_length, len;
2778 struct sockaddr_in my_addr;
2780 /* find which url is asked */
2781 url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2786 for(stream = first_stream; stream != NULL; stream = stream->next) {
2787 if (!stream->is_feed &&
2788 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
2789 !strcmp(path, stream->filename)) {
2793 /* no stream found */
2794 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2798 /* prepare the media description in sdp format */
2800 /* get the host IP */
2801 len = sizeof(my_addr);
2802 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
2803 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
2804 if (content_length < 0) {
2805 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2808 rtsp_reply_header(c, RTSP_STATUS_OK);
2809 url_fprintf(c->pb, "Content-Type: application/sdp\r\n");
2810 url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);
2811 url_fprintf(c->pb, "\r\n");
2812 put_buffer(c->pb, content, content_length);
2815 static HTTPContext *find_rtp_session(const char *session_id)
2819 if (session_id[0] == '\0')
2822 for(c = first_http_ctx; c != NULL; c = c->next) {
2823 if (!strcmp(c->session_id, session_id))
2829 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
2831 RTSPTransportField *th;
2834 for(i=0;i<h->nb_transports;i++) {
2835 th = &h->transports[i];
2836 if (th->lower_transport == lower_transport)
2842 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
2843 RTSPMessageHeader *h)
2846 int stream_index, port;
2851 RTSPTransportField *th;
2852 struct sockaddr_in dest_addr;
2853 RTSPActionServerSetup setup;
2855 /* find which url is asked */
2856 url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2861 /* now check each stream */
2862 for(stream = first_stream; stream != NULL; stream = stream->next) {
2863 if (!stream->is_feed &&
2864 stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
2865 /* accept aggregate filenames only if single stream */
2866 if (!strcmp(path, stream->filename)) {
2867 if (stream->nb_streams != 1) {
2868 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
2875 for(stream_index = 0; stream_index < stream->nb_streams;
2877 snprintf(buf, sizeof(buf), "%s/streamid=%d",
2878 stream->filename, stream_index);
2879 if (!strcmp(path, buf))
2884 /* no stream found */
2885 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2889 /* generate session id if needed */
2890 if (h->session_id[0] == '\0')
2891 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
2892 av_lfg_get(&random_state), av_lfg_get(&random_state));
2894 /* find rtp session, and create it if none found */
2895 rtp_c = find_rtp_session(h->session_id);
2897 /* always prefer UDP */
2898 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
2900 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
2902 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2907 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
2908 th->lower_transport);
2910 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
2914 /* open input stream */
2915 if (open_input_stream(rtp_c, "") < 0) {
2916 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2921 /* test if stream is OK (test needed because several SETUP needs
2922 to be done for a given file) */
2923 if (rtp_c->stream != stream) {
2924 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
2928 /* test if stream is already set up */
2929 if (rtp_c->rtp_ctx[stream_index]) {
2930 rtsp_reply_error(c, RTSP_STATUS_STATE);
2934 /* check transport */
2935 th = find_transport(h, rtp_c->rtp_protocol);
2936 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
2937 th->client_port_min <= 0)) {
2938 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2942 /* setup default options */
2943 setup.transport_option[0] = '\0';
2944 dest_addr = rtp_c->from_addr;
2945 dest_addr.sin_port = htons(th->client_port_min);
2948 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
2949 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2953 /* now everything is OK, so we can send the connection parameters */
2954 rtsp_reply_header(c, RTSP_STATUS_OK);
2956 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
2958 switch(rtp_c->rtp_protocol) {
2959 case RTSP_LOWER_TRANSPORT_UDP:
2960 port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]);
2961 url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
2962 "client_port=%d-%d;server_port=%d-%d",
2963 th->client_port_min, th->client_port_min + 1,
2966 case RTSP_LOWER_TRANSPORT_TCP:
2967 url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
2968 stream_index * 2, stream_index * 2 + 1);
2973 if (setup.transport_option[0] != '\0')
2974 url_fprintf(c->pb, ";%s", setup.transport_option);
2975 url_fprintf(c->pb, "\r\n");
2978 url_fprintf(c->pb, "\r\n");
2982 /* find an rtp connection by using the session ID. Check consistency
2984 static HTTPContext *find_rtp_session_with_url(const char *url,
2985 const char *session_id)
2993 rtp_c = find_rtp_session(session_id);
2997 /* find which url is asked */
2998 url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3002 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3003 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3004 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3005 rtp_c->stream->filename, s);
3006 if(!strncmp(path, buf, sizeof(buf))) {
3007 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
3014 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3018 rtp_c = find_rtp_session_with_url(url, h->session_id);
3020 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3024 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3025 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3026 rtp_c->state != HTTPSTATE_READY) {
3027 rtsp_reply_error(c, RTSP_STATUS_STATE);
3031 rtp_c->state = HTTPSTATE_SEND_DATA;
3033 /* now everything is OK, so we can send the connection parameters */
3034 rtsp_reply_header(c, RTSP_STATUS_OK);
3036 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3037 url_fprintf(c->pb, "\r\n");
3040 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3044 rtp_c = find_rtp_session_with_url(url, h->session_id);
3046 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3050 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3051 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3052 rtsp_reply_error(c, RTSP_STATUS_STATE);
3056 rtp_c->state = HTTPSTATE_READY;
3057 rtp_c->first_pts = AV_NOPTS_VALUE;
3058 /* now everything is OK, so we can send the connection parameters */
3059 rtsp_reply_header(c, RTSP_STATUS_OK);
3061 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3062 url_fprintf(c->pb, "\r\n");
3065 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3068 char session_id[32];
3070 rtp_c = find_rtp_session_with_url(url, h->session_id);
3072 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3076 av_strlcpy(session_id, rtp_c->session_id, sizeof(session_id));
3078 /* abort the session */
3079 close_connection(rtp_c);
3081 /* now everything is OK, so we can send the connection parameters */
3082 rtsp_reply_header(c, RTSP_STATUS_OK);
3084 url_fprintf(c->pb, "Session: %s\r\n", session_id);
3085 url_fprintf(c->pb, "\r\n");
3089 /********************************************************************/
3092 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3093 FFStream *stream, const char *session_id,
3094 enum RTSPLowerTransport rtp_protocol)
3096 HTTPContext *c = NULL;
3097 const char *proto_str;
3099 /* XXX: should output a warning page when coming
3100 close to the connection limit */
3101 if (nb_connections >= nb_max_connections)
3104 /* add a new connection */
3105 c = av_mallocz(sizeof(HTTPContext));
3110 c->poll_entry = NULL;
3111 c->from_addr = *from_addr;
3112 c->buffer_size = IOBUFFER_INIT_SIZE;
3113 c->buffer = av_malloc(c->buffer_size);
3118 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3119 c->state = HTTPSTATE_READY;
3120 c->is_packetized = 1;
3121 c->rtp_protocol = rtp_protocol;
3123 /* protocol is shown in statistics */
3124 switch(c->rtp_protocol) {
3125 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3126 proto_str = "MCAST";
3128 case RTSP_LOWER_TRANSPORT_UDP:
3131 case RTSP_LOWER_TRANSPORT_TCP:
3138 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3139 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3141 current_bandwidth += stream->bandwidth;
3143 c->next = first_http_ctx;
3155 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3156 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3158 static int rtp_new_av_stream(HTTPContext *c,
3159 int stream_index, struct sockaddr_in *dest_addr,
3160 HTTPContext *rtsp_c)
3162 AVFormatContext *ctx;
3165 URLContext *h = NULL;
3167 int max_packet_size;
3169 /* now we can open the relevant output stream */
3170 ctx = avformat_alloc_context();
3173 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3175 st = av_mallocz(sizeof(AVStream));
3178 st->codec= avcodec_alloc_context();
3179 ctx->nb_streams = 1;
3180 ctx->streams[0] = st;
3182 if (!c->stream->feed ||
3183 c->stream->feed == c->stream)
3184 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3187 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3189 st->priv_data = NULL;
3191 /* build destination RTP address */
3192 ipaddr = inet_ntoa(dest_addr->sin_addr);
3194 switch(c->rtp_protocol) {
3195 case RTSP_LOWER_TRANSPORT_UDP:
3196 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3199 /* XXX: also pass as parameter to function ? */
3200 if (c->stream->is_multicast) {
3202 ttl = c->stream->multicast_ttl;
3205 snprintf(ctx->filename, sizeof(ctx->filename),
3206 "rtp://%s:%d?multicast=1&ttl=%d",
3207 ipaddr, ntohs(dest_addr->sin_port), ttl);
3209 snprintf(ctx->filename, sizeof(ctx->filename),
3210 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3213 if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
3215 c->rtp_handles[stream_index] = h;
3216 max_packet_size = url_get_max_packet_size(h);
3218 case RTSP_LOWER_TRANSPORT_TCP:
3221 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3227 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3228 ipaddr, ntohs(dest_addr->sin_port),
3229 c->stream->filename, stream_index, c->protocol);
3231 /* normally, no packets should be output here, but the packet size may be checked */
3232 if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
3233 /* XXX: close stream */
3236 av_set_parameters(ctx, NULL);
3237 if (av_write_header(ctx) < 0) {
3244 url_close_dyn_buf(ctx->pb, &dummy_buf);
3247 c->rtp_ctx[stream_index] = ctx;
3251 /********************************************************************/
3252 /* ffserver initialization */
3254 static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
3258 fst = av_mallocz(sizeof(AVStream));
3261 fst->codec= avcodec_alloc_context();
3262 fst->priv_data = av_mallocz(sizeof(FeedData));
3263 memcpy(fst->codec, codec, sizeof(AVCodecContext));
3264 fst->index = stream->nb_streams;
3265 av_set_pts_info(fst, 33, 1, 90000);
3266 stream->streams[stream->nb_streams++] = fst;
3270 /* return the stream number in the feed */
3271 static int add_av_stream(FFStream *feed, AVStream *st)
3274 AVCodecContext *av, *av1;
3278 for(i=0;i<feed->nb_streams;i++) {
3279 st = feed->streams[i];
3281 if (av1->codec_id == av->codec_id &&
3282 av1->codec_type == av->codec_type &&
3283 av1->bit_rate == av->bit_rate) {
3285 switch(av->codec_type) {
3286 case CODEC_TYPE_AUDIO:
3287 if (av1->channels == av->channels &&
3288 av1->sample_rate == av->sample_rate)
3291 case CODEC_TYPE_VIDEO:
3292 if (av1->width == av->width &&
3293 av1->height == av->height &&
3294 av1->time_base.den == av->time_base.den &&
3295 av1->time_base.num == av->time_base.num &&
3296 av1->gop_size == av->gop_size)
3305 fst = add_av_stream1(feed, av);
3308 return feed->nb_streams - 1;
3313 static void remove_stream(FFStream *stream)
3317 while (*ps != NULL) {
3325 /* specific mpeg4 handling : we extract the raw parameters */
3326 static void extract_mpeg4_header(AVFormatContext *infile)
3328 int mpeg4_count, i, size;
3334 for(i=0;i<infile->nb_streams;i++) {
3335 st = infile->streams[i];
3336 if (st->codec->codec_id == CODEC_ID_MPEG4 &&
3337 st->codec->extradata_size == 0) {
3344 printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
3345 while (mpeg4_count > 0) {
3346 if (av_read_packet(infile, &pkt) < 0)
3348 st = infile->streams[pkt.stream_index];
3349 if (st->codec->codec_id == CODEC_ID_MPEG4 &&
3350 st->codec->extradata_size == 0) {
3351 av_freep(&st->codec->extradata);
3352 /* fill extradata with the header */
3353 /* XXX: we make hard suppositions here ! */
3355 while (p < pkt.data + pkt.size - 4) {
3356 /* stop when vop header is found */
3357 if (p[0] == 0x00 && p[1] == 0x00 &&
3358 p[2] == 0x01 && p[3] == 0xb6) {
3359 size = p - pkt.data;
3360 // av_hex_dump_log(infile, AV_LOG_DEBUG, pkt.data, size);
3361 st->codec->extradata = av_malloc(size);
3362 st->codec->extradata_size = size;
3363 memcpy(st->codec->extradata, pkt.data, size);
3370 av_free_packet(&pkt);
3374 /* compute the needed AVStream for each file */
3375 static void build_file_streams(void)
3377 FFStream *stream, *stream_next;
3378 AVFormatContext *infile;
3381 /* gather all streams */
3382 for(stream = first_stream; stream != NULL; stream = stream_next) {
3383 stream_next = stream->next;
3384 if (stream->stream_type == STREAM_TYPE_LIVE &&
3386 /* the stream comes from a file */
3387 /* try to open the file */
3389 stream->ap_in = av_mallocz(sizeof(AVFormatParameters));
3390 if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3391 /* specific case : if transport stream output to RTP,
3392 we use a raw transport stream reader */
3393 stream->ap_in->mpeg2ts_raw = 1;
3394 stream->ap_in->mpeg2ts_compute_pcr = 1;
3397 http_log("Opening file '%s'\n", stream->feed_filename);
3398 if ((ret = av_open_input_file(&infile, stream->feed_filename,
3399 stream->ifmt, 0, stream->ap_in)) < 0) {
3400 http_log("Could not open '%s': %d\n", stream->feed_filename, ret);
3401 /* remove stream (no need to spend more time on it) */
3403 remove_stream(stream);
3405 /* find all the AVStreams inside and reference them in
3407 if (av_find_stream_info(infile) < 0) {
3408 http_log("Could not find codec parameters from '%s'\n",
3409 stream->feed_filename);
3410 av_close_input_file(infile);
3413 extract_mpeg4_header(infile);
3415 for(i=0;i<infile->nb_streams;i++)
3416 add_av_stream1(stream, infile->streams[i]->codec);
3418 av_close_input_file(infile);
3424 /* compute the needed AVStream for each feed */
3425 static void build_feed_streams(void)
3427 FFStream *stream, *feed;
3430 /* gather all streams */
3431 for(stream = first_stream; stream != NULL; stream = stream->next) {
3432 feed = stream->feed;
3434 if (!stream->is_feed) {
3435 /* we handle a stream coming from a feed */
3436 for(i=0;i<stream->nb_streams;i++)
3437 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3442 /* gather all streams */
3443 for(stream = first_stream; stream != NULL; stream = stream->next) {
3444 feed = stream->feed;
3446 if (stream->is_feed) {
3447 for(i=0;i<stream->nb_streams;i++)
3448 stream->feed_streams[i] = i;
3453 /* create feed files if needed */
3454 for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
3457 if (url_exist(feed->feed_filename)) {
3458 /* See if it matches */
3462 if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) {
3463 /* Now see if it matches */
3464 if (s->nb_streams == feed->nb_streams) {
3466 for(i=0;i<s->nb_streams;i++) {
3468 sf = feed->streams[i];
3471 if (sf->index != ss->index ||
3473 http_log("Index & Id do not match for stream %d (%s)\n",
3474 i, feed->feed_filename);
3477 AVCodecContext *ccf, *ccs;
3481 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3483 if (CHECK_CODEC(codec) || CHECK_CODEC(codec_type)) {
3484 http_log("Codecs do not match for stream %d\n", i);
3486 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3487 http_log("Codec bitrates do not match for stream %d\n", i);
3489 } else if (ccf->codec_type == CODEC_TYPE_VIDEO) {
3490 if (CHECK_CODEC(time_base.den) ||
3491 CHECK_CODEC(time_base.num) ||
3492 CHECK_CODEC(width) ||
3493 CHECK_CODEC(height)) {
3494 http_log("Codec width, height and framerate do not match for stream %d\n", i);
3497 } else if (ccf->codec_type == CODEC_TYPE_AUDIO) {
3498 if (CHECK_CODEC(sample_rate) ||
3499 CHECK_CODEC(channels) ||
3500 CHECK_CODEC(frame_size)) {
3501 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3505 http_log("Unknown codec type\n");
3513 http_log("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3514 feed->feed_filename, s->nb_streams, feed->nb_streams);
3516 av_close_input_file(s);
3518 http_log("Deleting feed file '%s' as it appears to be corrupt\n",
3519 feed->feed_filename);
3522 if (feed->readonly) {
3523 http_log("Unable to delete feed file '%s' as it is marked readonly\n",
3524 feed->feed_filename);
3527 unlink(feed->feed_filename);
3530 if (!url_exist(feed->feed_filename)) {
3531 AVFormatContext s1 = {0}, *s = &s1;
3533 if (feed->readonly) {
3534 http_log("Unable to create feed file '%s' as it is marked readonly\n",
3535 feed->feed_filename);
3539 /* only write the header of the ffm file */
3540 if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
3541 http_log("Could not open output feed file '%s'\n",
3542 feed->feed_filename);
3545 s->oformat = feed->fmt;
3546 s->nb_streams = feed->nb_streams;
3547 for(i=0;i<s->nb_streams;i++) {
3549 st = feed->streams[i];
3552 av_set_parameters(s, NULL);
3553 if (av_write_header(s) < 0) {
3554 http_log("Container doesn't supports the required parameters\n");
3557 /* XXX: need better api */
3558 av_freep(&s->priv_data);
3561 /* get feed size and write index */
3562 fd = open(feed->feed_filename, O_RDONLY);
3564 http_log("Could not open output feed file '%s'\n",
3565 feed->feed_filename);
3569 feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
3570 feed->feed_size = lseek(fd, 0, SEEK_END);
3571 /* ensure that we do not wrap before the end of file */
3572 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3573 feed->feed_max_size = feed->feed_size;
3579 /* compute the bandwidth used by each stream */
3580 static void compute_bandwidth(void)
3586 for(stream = first_stream; stream != NULL; stream = stream->next) {
3588 for(i=0;i<stream->nb_streams;i++) {
3589 AVStream *st = stream->streams[i];
3590 switch(st->codec->codec_type) {
3591 case CODEC_TYPE_AUDIO:
3592 case CODEC_TYPE_VIDEO:
3593 bandwidth += st->codec->bit_rate;
3599 stream->bandwidth = (bandwidth + 999) / 1000;
3603 /* add a codec and set the default parameters */
3604 static void add_codec(FFStream *stream, AVCodecContext *av)
3608 /* compute default parameters */
3609 switch(av->codec_type) {
3610 case CODEC_TYPE_AUDIO:
3611 if (av->bit_rate == 0)
3612 av->bit_rate = 64000;
3613 if (av->sample_rate == 0)
3614 av->sample_rate = 22050;
3615 if (av->channels == 0)
3618 case CODEC_TYPE_VIDEO:
3619 if (av->bit_rate == 0)
3620 av->bit_rate = 64000;
3621 if (av->time_base.num == 0){
3622 av->time_base.den = 5;
3623 av->time_base.num = 1;
3625 if (av->width == 0 || av->height == 0) {
3629 /* Bitrate tolerance is less for streaming */
3630 if (av->bit_rate_tolerance == 0)
3631 av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
3632 (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);
3637 if (av->max_qdiff == 0)
3639 av->qcompress = 0.5;
3642 if (!av->nsse_weight)
3643 av->nsse_weight = 8;
3645 av->frame_skip_cmp = FF_CMP_DCTMAX;
3646 av->me_method = ME_EPZS;
3647 av->rc_buffer_aggressivity = 1.0;
3650 av->rc_eq = "tex^qComp";
3651 if (!av->i_quant_factor)
3652 av->i_quant_factor = -0.8;
3653 if (!av->b_quant_factor)
3654 av->b_quant_factor = 1.25;
3655 if (!av->b_quant_offset)
3656 av->b_quant_offset = 1.25;
3657 if (!av->rc_max_rate)
3658 av->rc_max_rate = av->bit_rate * 2;
3660 if (av->rc_max_rate && !av->rc_buffer_size) {
3661 av->rc_buffer_size = av->rc_max_rate;
3670 st = av_mallocz(sizeof(AVStream));
3673 st->codec = avcodec_alloc_context();
3674 stream->streams[stream->nb_streams++] = st;
3675 memcpy(st->codec, av, sizeof(AVCodecContext));
3678 static enum CodecID opt_audio_codec(const char *arg)
3680 AVCodec *p= avcodec_find_encoder_by_name(arg);
3682 if (p == NULL || p->type != CODEC_TYPE_AUDIO)
3683 return CODEC_ID_NONE;
3688 static enum CodecID opt_video_codec(const char *arg)
3690 AVCodec *p= avcodec_find_encoder_by_name(arg);
3692 if (p == NULL || p->type != CODEC_TYPE_VIDEO)
3693 return CODEC_ID_NONE;
3698 /* simplistic plugin support */
3701 static void load_module(const char *filename)
3704 void (*init_func)(void);
3705 dll = dlopen(filename, RTLD_NOW);
3707 fprintf(stderr, "Could not load module '%s' - %s\n",
3708 filename, dlerror());
3712 init_func = dlsym(dll, "ffserver_module_init");
3715 "%s: init function 'ffserver_module_init()' not found\n",
3724 static int ffserver_opt_default(const char *opt, const char *arg,
3725 AVCodecContext *avctx, int type)
3728 const AVOption *o = av_find_opt(avctx, opt, NULL, type, type);
3730 ret = av_set_string3(avctx, opt, arg, 1, NULL);
3734 static AVOutputFormat *ffserver_guess_format(const char *short_name, const char *filename,
3735 const char *mime_type)
3737 AVOutputFormat *fmt = av_guess_format(short_name, filename, mime_type);
3740 AVOutputFormat *stream_fmt;
3741 char stream_format_name[64];
3743 snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
3744 stream_fmt = av_guess_format(stream_format_name, NULL, NULL);
3753 static int parse_ffconfig(const char *filename)
3760 int val, errors, line_num;
3761 FFStream **last_stream, *stream, *redirect;
3762 FFStream **last_feed, *feed, *s;
3763 AVCodecContext audio_enc, video_enc;
3764 enum CodecID audio_id, video_id;
3766 f = fopen(filename, "r");
3774 first_stream = NULL;
3775 last_stream = &first_stream;
3777 last_feed = &first_feed;
3781 audio_id = CODEC_ID_NONE;
3782 video_id = CODEC_ID_NONE;
3784 if (fgets(line, sizeof(line), f) == NULL)
3790 if (*p == '\0' || *p == '#')
3793 get_arg(cmd, sizeof(cmd), &p);
3795 if (!strcasecmp(cmd, "Port")) {
3796 get_arg(arg, sizeof(arg), &p);
3798 if (val < 1 || val > 65536) {
3799 fprintf(stderr, "%s:%d: Invalid port: %s\n",
3800 filename, line_num, arg);
3803 my_http_addr.sin_port = htons(val);
3804 } else if (!strcasecmp(cmd, "BindAddress")) {
3805 get_arg(arg, sizeof(arg), &p);
3806 if (resolve_host(&my_http_addr.sin_addr, arg) != 0) {
3807 fprintf(stderr, "%s:%d: Invalid host/IP address: %s\n",
3808 filename, line_num, arg);
3811 } else if (!strcasecmp(cmd, "NoDaemon")) {
3812 ffserver_daemon = 0;
3813 } else if (!strcasecmp(cmd, "RTSPPort")) {
3814 get_arg(arg, sizeof(arg), &p);
3816 if (val < 1 || val > 65536) {
3817 fprintf(stderr, "%s:%d: Invalid port: %s\n",
3818 filename, line_num, arg);
3821 my_rtsp_addr.sin_port = htons(atoi(arg));
3822 } else if (!strcasecmp(cmd, "RTSPBindAddress")) {
3823 get_arg(arg, sizeof(arg), &p);
3824 if (resolve_host(&my_rtsp_addr.sin_addr, arg) != 0) {
3825 fprintf(stderr, "%s:%d: Invalid host/IP address: %s\n",
3826 filename, line_num, arg);
3829 } else if (!strcasecmp(cmd, "MaxHTTPConnections")) {
3830 get_arg(arg, sizeof(arg), &p);
3832 if (val < 1 || val > 65536) {
3833 fprintf(stderr, "%s:%d: Invalid MaxHTTPConnections: %s\n",
3834 filename, line_num, arg);
3837 nb_max_http_connections = val;
3838 } else if (!strcasecmp(cmd, "MaxClients")) {
3839 get_arg(arg, sizeof(arg), &p);
3841 if (val < 1 || val > nb_max_http_connections) {
3842 fprintf(stderr, "%s:%d: Invalid MaxClients: %s\n",
3843 filename, line_num, arg);
3846 nb_max_connections = val;
3848 } else if (!strcasecmp(cmd, "MaxBandwidth")) {
3850 get_arg(arg, sizeof(arg), &p);
3852 if (llval < 10 || llval > 10000000) {
3853 fprintf(stderr, "%s:%d: Invalid MaxBandwidth: %s\n",
3854 filename, line_num, arg);
3857 max_bandwidth = llval;
3858 } else if (!strcasecmp(cmd, "CustomLog")) {
3859 if (!ffserver_debug)
3860 get_arg(logfilename, sizeof(logfilename), &p);
3861 } else if (!strcasecmp(cmd, "<Feed")) {
3862 /*********************************************/
3863 /* Feed related options */
3865 if (stream || feed) {
3866 fprintf(stderr, "%s:%d: Already in a tag\n",
3867 filename, line_num);
3869 feed = av_mallocz(sizeof(FFStream));
3870 get_arg(feed->filename, sizeof(feed->filename), &p);
3871 q = strrchr(feed->filename, '>');
3875 for (s = first_feed; s; s = s->next) {
3876 if (!strcmp(feed->filename, s->filename)) {
3877 fprintf(stderr, "%s:%d: Feed '%s' already registered\n",
3878 filename, line_num, s->filename);
3883 feed->fmt = av_guess_format("ffm", NULL, NULL);
3884 /* defaut feed file */
3885 snprintf(feed->feed_filename, sizeof(feed->feed_filename),
3886 "/tmp/%s.ffm", feed->filename);
3887 feed->feed_max_size = 5 * 1024 * 1024;
3889 feed->feed = feed; /* self feeding :-) */
3891 /* add in stream list */
3892 *last_stream = feed;
3893 last_stream = &feed->next;
3894 /* add in feed list */
3896 last_feed = &feed->next_feed;
3898 } else if (!strcasecmp(cmd, "Launch")) {
3902 feed->child_argv = av_mallocz(64 * sizeof(char *));
3904 for (i = 0; i < 62; i++) {
3905 get_arg(arg, sizeof(arg), &p);
3909 feed->child_argv[i] = av_strdup(arg);
3912 feed->child_argv[i] = av_malloc(30 + strlen(feed->filename));
3914 snprintf(feed->child_argv[i], 30+strlen(feed->filename),
3916 (my_http_addr.sin_addr.s_addr == INADDR_ANY) ? "127.0.0.1" :
3917 inet_ntoa(my_http_addr.sin_addr),
3918 ntohs(my_http_addr.sin_port), feed->filename);
3920 } else if (!strcasecmp(cmd, "ReadOnlyFile")) {
3922 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
3924 } else if (stream) {
3925 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
3927 } else if (!strcasecmp(cmd, "File")) {
3929 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
3931 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
3932 } else if (!strcasecmp(cmd, "Truncate")) {
3934 get_arg(arg, sizeof(arg), &p);
3935 feed->truncate = strtod(arg, NULL);
3937 } else if (!strcasecmp(cmd, "FileMaxSize")) {
3942 get_arg(arg, sizeof(arg), &p);
3944 fsize = strtod(p1, &p1);
3945 switch(toupper(*p1)) {
3950 fsize *= 1024 * 1024;
3953 fsize *= 1024 * 1024 * 1024;
3956 feed->feed_max_size = (int64_t)fsize;
3957 if (feed->feed_max_size < FFM_PACKET_SIZE*4) {
3958 fprintf(stderr, "%s:%d: Feed max file size is too small, "
3959 "must be at least %d\n", filename, line_num, FFM_PACKET_SIZE*4);
3963 } else if (!strcasecmp(cmd, "</Feed>")) {
3965 fprintf(stderr, "%s:%d: No corresponding <Feed> for </Feed>\n",
3966 filename, line_num);
3970 } else if (!strcasecmp(cmd, "<Stream")) {
3971 /*********************************************/
3972 /* Stream related options */
3974 if (stream || feed) {
3975 fprintf(stderr, "%s:%d: Already in a tag\n",
3976 filename, line_num);
3979 const AVClass *class;
3980 stream = av_mallocz(sizeof(FFStream));
3981 get_arg(stream->filename, sizeof(stream->filename), &p);
3982 q = strrchr(stream->filename, '>');
3986 for (s = first_stream; s; s = s->next) {
3987 if (!strcmp(stream->filename, s->filename)) {
3988 fprintf(stderr, "%s:%d: Stream '%s' already registered\n",
3989 filename, line_num, s->filename);
3994 stream->fmt = ffserver_guess_format(NULL, stream->filename, NULL);
3995 /* fetch avclass so AVOption works
3996 * FIXME try to use avcodec_get_context_defaults2
3997 * without changing defaults too much */
3998 avcodec_get_context_defaults(&video_enc);
3999 class = video_enc.av_class;
4000 memset(&audio_enc, 0, sizeof(AVCodecContext));
4001 memset(&video_enc, 0, sizeof(AVCodecContext));
4002 audio_enc.av_class = class;
4003 video_enc.av_class = class;
4004 audio_id = CODEC_ID_NONE;
4005 video_id = CODEC_ID_NONE;
4007 audio_id = stream->fmt->audio_codec;
4008 video_id = stream->fmt->video_codec;
4011 *last_stream = stream;
4012 last_stream = &stream->next;
4014 } else if (!strcasecmp(cmd, "Feed")) {
4015 get_arg(arg, sizeof(arg), &p);
4020 while (sfeed != NULL) {
4021 if (!strcmp(sfeed->filename, arg))
4023 sfeed = sfeed->next_feed;
4026 fprintf(stderr, "%s:%d: feed '%s' not defined\n",
4027 filename, line_num, arg);
4029 stream->feed = sfeed;
4031 } else if (!strcasecmp(cmd, "Format")) {
4032 get_arg(arg, sizeof(arg), &p);
4034 if (!strcmp(arg, "status")) {
4035 stream->stream_type = STREAM_TYPE_STATUS;
4038 stream->stream_type = STREAM_TYPE_LIVE;
4039 /* jpeg cannot be used here, so use single frame jpeg */
4040 if (!strcmp(arg, "jpeg"))
4041 strcpy(arg, "mjpeg");
4042 stream->fmt = ffserver_guess_format(arg, NULL, NULL);
4044 fprintf(stderr, "%s:%d: Unknown Format: %s\n",
4045 filename, line_num, arg);
4050 audio_id = stream->fmt->audio_codec;
4051 video_id = stream->fmt->video_codec;
4054 } else if (!strcasecmp(cmd, "InputFormat")) {
4055 get_arg(arg, sizeof(arg), &p);
4057 stream->ifmt = av_find_input_format(arg);
4058 if (!stream->ifmt) {
4059 fprintf(stderr, "%s:%d: Unknown input format: %s\n",
4060 filename, line_num, arg);
4063 } else if (!strcasecmp(cmd, "FaviconURL")) {
4064 if (stream && stream->stream_type == STREAM_TYPE_STATUS) {
4065 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4067 fprintf(stderr, "%s:%d: FaviconURL only permitted for status streams\n",
4068 filename, line_num);
4071 } else if (!strcasecmp(cmd, "Author")) {
4073 get_arg(stream->author, sizeof(stream->author), &p);
4074 } else if (!strcasecmp(cmd, "Comment")) {
4076 get_arg(stream->comment, sizeof(stream->comment), &p);
4077 } else if (!strcasecmp(cmd, "Copyright")) {
4079 get_arg(stream->copyright, sizeof(stream->copyright), &p);
4080 } else if (!strcasecmp(cmd, "Title")) {
4082 get_arg(stream->title, sizeof(stream->title), &p);
4083 } else if (!strcasecmp(cmd, "Preroll")) {
4084 get_arg(arg, sizeof(arg), &p);
4086 stream->prebuffer = atof(arg) * 1000;
4087 } else if (!strcasecmp(cmd, "StartSendOnKey")) {
4089 stream->send_on_key = 1;
4090 } else if (!strcasecmp(cmd, "AudioCodec")) {
4091 get_arg(arg, sizeof(arg), &p);
4092 audio_id = opt_audio_codec(arg);
4093 if (audio_id == CODEC_ID_NONE) {
4094 fprintf(stderr, "%s:%d: Unknown AudioCodec: %s\n",
4095 filename, line_num, arg);
4098 } else if (!strcasecmp(cmd, "VideoCodec")) {
4099 get_arg(arg, sizeof(arg), &p);
4100 video_id = opt_video_codec(arg);
4101 if (video_id == CODEC_ID_NONE) {
4102 fprintf(stderr, "%s:%d: Unknown VideoCodec: %s\n",
4103 filename, line_num, arg);
4106 } else if (!strcasecmp(cmd, "MaxTime")) {
4107 get_arg(arg, sizeof(arg), &p);
4109 stream->max_time = atof(arg) * 1000;
4110 } else if (!strcasecmp(cmd, "AudioBitRate")) {
4111 get_arg(arg, sizeof(arg), &p);
4113 audio_enc.bit_rate = atoi(arg) * 1000;
4114 } else if (!strcasecmp(cmd, "AudioChannels")) {
4115 get_arg(arg, sizeof(arg), &p);
4117 audio_enc.channels = atoi(arg);
4118 } else if (!strcasecmp(cmd, "AudioSampleRate")) {
4119 get_arg(arg, sizeof(arg), &p);
4121 audio_enc.sample_rate = atoi(arg);
4122 } else if (!strcasecmp(cmd, "AudioQuality")) {
4123 get_arg(arg, sizeof(arg), &p);
4125 // audio_enc.quality = atof(arg) * 1000;
4127 } else if (!strcasecmp(cmd, "VideoBitRateRange")) {
4129 int minrate, maxrate;
4131 get_arg(arg, sizeof(arg), &p);
4133 if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {
4134 video_enc.rc_min_rate = minrate * 1000;
4135 video_enc.rc_max_rate = maxrate * 1000;
4137 fprintf(stderr, "%s:%d: Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n",
4138 filename, line_num, arg);
4142 } else if (!strcasecmp(cmd, "Debug")) {
4144 get_arg(arg, sizeof(arg), &p);
4145 video_enc.debug = strtol(arg,0,0);
4147 } else if (!strcasecmp(cmd, "Strict")) {
4149 get_arg(arg, sizeof(arg), &p);
4150 video_enc.strict_std_compliance = atoi(arg);
4152 } else if (!strcasecmp(cmd, "VideoBufferSize")) {
4154 get_arg(arg, sizeof(arg), &p);
4155 video_enc.rc_buffer_size = atoi(arg) * 8*1024;
4157 } else if (!strcasecmp(cmd, "VideoBitRateTolerance")) {
4159 get_arg(arg, sizeof(arg), &p);
4160 video_enc.bit_rate_tolerance = atoi(arg) * 1000;
4162 } else if (!strcasecmp(cmd, "VideoBitRate")) {
4163 get_arg(arg, sizeof(arg), &p);
4165 video_enc.bit_rate = atoi(arg) * 1000;
4167 } else if (!strcasecmp(cmd, "VideoSize")) {
4168 get_arg(arg, sizeof(arg), &p);
4170 av_parse_video_frame_size(&video_enc.width, &video_enc.height, arg);
4171 if ((video_enc.width % 16) != 0 ||
4172 (video_enc.height % 16) != 0) {
4173 fprintf(stderr, "%s:%d: Image size must be a multiple of 16\n",
4174 filename, line_num);
4178 } else if (!strcasecmp(cmd, "VideoFrameRate")) {
4179 get_arg(arg, sizeof(arg), &p);
4181 AVRational frame_rate;
4182 if (av_parse_video_frame_rate(&frame_rate, arg) < 0) {
4183 fprintf(stderr, "Incorrect frame rate\n");
4186 video_enc.time_base.num = frame_rate.den;
4187 video_enc.time_base.den = frame_rate.num;
4190 } else if (!strcasecmp(cmd, "VideoGopSize")) {
4191 get_arg(arg, sizeof(arg), &p);
4193 video_enc.gop_size = atoi(arg);
4194 } else if (!strcasecmp(cmd, "VideoIntraOnly")) {
4196 video_enc.gop_size = 1;
4197 } else if (!strcasecmp(cmd, "VideoHighQuality")) {
4199 video_enc.mb_decision = FF_MB_DECISION_BITS;
4200 } else if (!strcasecmp(cmd, "Video4MotionVector")) {
4202 video_enc.mb_decision = FF_MB_DECISION_BITS; //FIXME remove
4203 video_enc.flags |= CODEC_FLAG_4MV;
4205 } else if (!strcasecmp(cmd, "AVOptionVideo") ||
4206 !strcasecmp(cmd, "AVOptionAudio")) {
4208 AVCodecContext *avctx;
4210 get_arg(arg, sizeof(arg), &p);
4211 get_arg(arg2, sizeof(arg2), &p);
4212 if (!strcasecmp(cmd, "AVOptionVideo")) {
4214 type = AV_OPT_FLAG_VIDEO_PARAM;
4217 type = AV_OPT_FLAG_AUDIO_PARAM;
4219 if (ffserver_opt_default(arg, arg2, avctx, type|AV_OPT_FLAG_ENCODING_PARAM)) {
4220 fprintf(stderr, "AVOption error: %s %s\n", arg, arg2);
4223 } else if (!strcasecmp(cmd, "VideoTag")) {
4224 get_arg(arg, sizeof(arg), &p);
4225 if ((strlen(arg) == 4) && stream)
4226 video_enc.codec_tag = AV_RL32(arg);
4227 } else if (!strcasecmp(cmd, "BitExact")) {
4229 video_enc.flags |= CODEC_FLAG_BITEXACT;
4230 } else if (!strcasecmp(cmd, "DctFastint")) {
4232 video_enc.dct_algo = FF_DCT_FASTINT;
4233 } else if (!strcasecmp(cmd, "IdctSimple")) {
4235 video_enc.idct_algo = FF_IDCT_SIMPLE;
4236 } else if (!strcasecmp(cmd, "Qscale")) {
4237 get_arg(arg, sizeof(arg), &p);
4239 video_enc.flags |= CODEC_FLAG_QSCALE;
4240 video_enc.global_quality = FF_QP2LAMBDA * atoi(arg);
4242 } else if (!strcasecmp(cmd, "VideoQDiff")) {
4243 get_arg(arg, sizeof(arg), &p);
4245 video_enc.max_qdiff = atoi(arg);
4246 if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) {
4247 fprintf(stderr, "%s:%d: VideoQDiff out of range\n",
4248 filename, line_num);
4252 } else if (!strcasecmp(cmd, "VideoQMax")) {
4253 get_arg(arg, sizeof(arg), &p);
4255 video_enc.qmax = atoi(arg);
4256 if (video_enc.qmax < 1 || video_enc.qmax > 31) {
4257 fprintf(stderr, "%s:%d: VideoQMax out of range\n",
4258 filename, line_num);
4262 } else if (!strcasecmp(cmd, "VideoQMin")) {
4263 get_arg(arg, sizeof(arg), &p);
4265 video_enc.qmin = atoi(arg);
4266 if (video_enc.qmin < 1 || video_enc.qmin > 31) {
4267 fprintf(stderr, "%s:%d: VideoQMin out of range\n",
4268 filename, line_num);
4272 } else if (!strcasecmp(cmd, "LumaElim")) {
4273 get_arg(arg, sizeof(arg), &p);
4275 video_enc.luma_elim_threshold = atoi(arg);
4276 } else if (!strcasecmp(cmd, "ChromaElim")) {
4277 get_arg(arg, sizeof(arg), &p);
4279 video_enc.chroma_elim_threshold = atoi(arg);
4280 } else if (!strcasecmp(cmd, "LumiMask")) {
4281 get_arg(arg, sizeof(arg), &p);
4283 video_enc.lumi_masking = atof(arg);
4284 } else if (!strcasecmp(cmd, "DarkMask")) {
4285 get_arg(arg, sizeof(arg), &p);
4287 video_enc.dark_masking = atof(arg);
4288 } else if (!strcasecmp(cmd, "NoVideo")) {
4289 video_id = CODEC_ID_NONE;
4290 } else if (!strcasecmp(cmd, "NoAudio")) {
4291 audio_id = CODEC_ID_NONE;
4292 } else if (!strcasecmp(cmd, "ACL")) {
4295 get_arg(arg, sizeof(arg), &p);
4296 if (strcasecmp(arg, "allow") == 0)
4297 acl.action = IP_ALLOW;
4298 else if (strcasecmp(arg, "deny") == 0)
4299 acl.action = IP_DENY;
4301 fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
4302 filename, line_num, arg);
4306 get_arg(arg, sizeof(arg), &p);
4308 if (resolve_host(&acl.first, arg) != 0) {
4309 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4310 filename, line_num, arg);
4313 acl.last = acl.first;
4315 get_arg(arg, sizeof(arg), &p);
4318 if (resolve_host(&acl.last, arg) != 0) {
4319 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4320 filename, line_num, arg);
4326 IPAddressACL *nacl = av_mallocz(sizeof(*nacl));
4327 IPAddressACL **naclp = 0;
4333 naclp = &stream->acl;
4337 fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n",
4338 filename, line_num);
4344 naclp = &(*naclp)->next;
4349 } else if (!strcasecmp(cmd, "RTSPOption")) {
4350 get_arg(arg, sizeof(arg), &p);
4352 av_freep(&stream->rtsp_option);
4353 stream->rtsp_option = av_strdup(arg);
4355 } else if (!strcasecmp(cmd, "MulticastAddress")) {
4356 get_arg(arg, sizeof(arg), &p);
4358 if (resolve_host(&stream->multicast_ip, arg) != 0) {
4359 fprintf(stderr, "%s:%d: Invalid host/IP address: %s\n",
4360 filename, line_num, arg);
4363 stream->is_multicast = 1;
4364 stream->loop = 1; /* default is looping */
4366 } else if (!strcasecmp(cmd, "MulticastPort")) {
4367 get_arg(arg, sizeof(arg), &p);
4369 stream->multicast_port = atoi(arg);
4370 } else if (!strcasecmp(cmd, "MulticastTTL")) {
4371 get_arg(arg, sizeof(arg), &p);
4373 stream->multicast_ttl = atoi(arg);
4374 } else if (!strcasecmp(cmd, "NoLoop")) {
4377 } else if (!strcasecmp(cmd, "</Stream>")) {
4379 fprintf(stderr, "%s:%d: No corresponding <Stream> for </Stream>\n",
4380 filename, line_num);
4383 if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) {
4384 if (audio_id != CODEC_ID_NONE) {
4385 audio_enc.codec_type = CODEC_TYPE_AUDIO;
4386 audio_enc.codec_id = audio_id;
4387 add_codec(stream, &audio_enc);
4389 if (video_id != CODEC_ID_NONE) {
4390 video_enc.codec_type = CODEC_TYPE_VIDEO;
4391 video_enc.codec_id = video_id;
4392 add_codec(stream, &video_enc);
4397 } else if (!strcasecmp(cmd, "<Redirect")) {
4398 /*********************************************/
4400 if (stream || feed || redirect) {
4401 fprintf(stderr, "%s:%d: Already in a tag\n",
4402 filename, line_num);
4405 redirect = av_mallocz(sizeof(FFStream));
4406 *last_stream = redirect;
4407 last_stream = &redirect->next;
4409 get_arg(redirect->filename, sizeof(redirect->filename), &p);
4410 q = strrchr(redirect->filename, '>');
4413 redirect->stream_type = STREAM_TYPE_REDIRECT;
4415 } else if (!strcasecmp(cmd, "URL")) {
4417 get_arg(redirect->feed_filename, sizeof(redirect->feed_filename), &p);
4418 } else if (!strcasecmp(cmd, "</Redirect>")) {
4420 fprintf(stderr, "%s:%d: No corresponding <Redirect> for </Redirect>\n",
4421 filename, line_num);
4424 if (!redirect->feed_filename[0]) {
4425 fprintf(stderr, "%s:%d: No URL found for <Redirect>\n",
4426 filename, line_num);
4431 } else if (!strcasecmp(cmd, "LoadModule")) {
4432 get_arg(arg, sizeof(arg), &p);
4436 fprintf(stderr, "%s:%d: Module support not compiled into this version: '%s'\n",
4437 filename, line_num, arg);
4441 fprintf(stderr, "%s:%d: Incorrect keyword: '%s'\n",
4442 filename, line_num, cmd);
4453 static void handle_child_exit(int sig)
4458 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
4461 for (feed = first_feed; feed; feed = feed->next) {
4462 if (feed->pid == pid) {
4463 int uptime = time(0) - feed->pid_start;
4466 fprintf(stderr, "%s: Pid %d exited with status %d after %d seconds\n", feed->filename, pid, status, uptime);
4469 /* Turn off any more restarts */
4470 feed->child_argv = 0;
4475 need_to_start_children = 1;
4478 static void opt_debug(void)
4481 ffserver_daemon = 0;
4482 logfilename[0] = '-';
4485 static void show_help(void)
4487 printf("usage: ffserver [options]\n"
4488 "Hyper fast multi format Audio/Video streaming server\n");
4490 show_help_options(options, "Main options:\n", 0, 0);
4493 static const OptionDef options[] = {
4494 #include "cmdutils_common_opts.h"
4495 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
4496 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
4497 { "f", HAS_ARG | OPT_STRING, {(void*)&config_filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
4501 int main(int argc, char **argv)
4503 struct sigaction sigact;
4509 config_filename = "/etc/ffserver.conf";
4511 my_program_name = argv[0];
4512 my_program_dir = getcwd(0, 0);
4513 ffserver_daemon = 1;
4515 parse_options(argc, argv, options, NULL);
4517 unsetenv("http_proxy"); /* Kill the http_proxy */
4519 av_lfg_init(&random_state, ff_random_get_seed());
4521 memset(&sigact, 0, sizeof(sigact));
4522 sigact.sa_handler = handle_child_exit;
4523 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
4524 sigaction(SIGCHLD, &sigact, 0);
4526 if (parse_ffconfig(config_filename) < 0) {
4527 fprintf(stderr, "Incorrect config file - exiting.\n");
4531 /* open log file if needed */
4532 if (logfilename[0] != '\0') {
4533 if (!strcmp(logfilename, "-"))
4536 logfile = fopen(logfilename, "a");
4537 av_log_set_callback(http_av_log);
4540 build_file_streams();
4542 build_feed_streams();
4544 compute_bandwidth();
4546 /* put the process in background and detach it from its TTY */
4547 if (ffserver_daemon) {
4554 } else if (pid > 0) {
4561 open("/dev/null", O_RDWR);
4562 if (strcmp(logfilename, "-") != 0) {
4572 signal(SIGPIPE, SIG_IGN);
4574 if (ffserver_daemon)
4577 if (http_server() < 0) {
4578 http_log("Could not start server\n");