2 * Multiple format streaming server
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #define HAVE_AV_CONFIG_H
25 #include <sys/ioctl.h>
29 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
31 #include <sys/types.h>
32 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
38 #ifdef CONFIG_HAVE_DLFCN
44 /* maximum number of simultaneous HTTP connections */
45 #define HTTP_MAX_CONNECTIONS 2000
48 HTTPSTATE_WAIT_REQUEST,
49 HTTPSTATE_SEND_HEADER,
50 HTTPSTATE_SEND_DATA_HEADER,
51 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
52 HTTPSTATE_SEND_DATA_TRAILER,
53 HTTPSTATE_RECEIVE_DATA,
54 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
57 RTSPSTATE_WAIT_REQUEST,
59 RTSPSTATE_SEND_PACKET,
62 const char *http_state[] = {
78 #define IOBUFFER_INIT_SIZE 8192
80 /* coef for exponential mean for bitrate estimation in statistics */
83 /* timeouts are in ms */
84 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
85 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
87 #define SYNC_TIMEOUT (10 * 1000)
90 int64_t count1, count2;
94 /* context associated with one connection */
95 typedef struct HTTPContext {
97 int fd; /* socket file descriptor */
98 struct sockaddr_in from_addr; /* origin */
99 struct pollfd *poll_entry; /* used when polling */
101 uint8_t *buffer_ptr, *buffer_end;
103 struct HTTPContext *next;
104 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
108 /* input format handling */
109 AVFormatContext *fmt_in;
110 long start_time; /* In milliseconds - this wraps fairly often */
111 int64_t first_pts; /* initial pts value */
112 int64_t cur_pts; /* current pts value from the stream in us */
113 int64_t cur_frame_duration; /* duration of the current frame in us */
114 int cur_frame_bytes; /* output frame size, needed to compute
115 the time at which we send each
117 int pts_stream_index; /* stream we choose as clock reference */
118 int64_t cur_clock; /* current clock reference value in us */
119 /* output format handling */
120 struct FFStream *stream;
121 /* -1 is invalid stream */
122 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
123 int switch_feed_streams[MAX_STREAMS]; /* index of streams in the feed */
125 AVFormatContext fmt_ctx; /* instance of FFStream for one user */
126 int last_packet_sent; /* true if last data packet was sent */
128 DataRateData datarate;
135 int is_packetized; /* if true, the stream is packetized */
136 int packet_stream_index; /* current stream for output in state machine */
138 /* RTSP state specific */
139 uint8_t *pb_buffer; /* XXX: use that in all the code */
141 int seq; /* RTSP sequence number */
143 /* RTP state specific */
144 enum RTSPProtocol rtp_protocol;
145 char session_id[32]; /* session id */
146 AVFormatContext *rtp_ctx[MAX_STREAMS];
148 /* RTP/UDP specific */
149 URLContext *rtp_handles[MAX_STREAMS];
151 /* RTP/TCP specific */
152 struct HTTPContext *rtsp_c;
153 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
156 static AVFrame dummy_frame;
158 /* each generated stream is described here */
162 STREAM_TYPE_REDIRECT,
165 enum IPAddressAction {
170 typedef struct IPAddressACL {
171 struct IPAddressACL *next;
172 enum IPAddressAction action;
173 /* These are in host order */
174 struct in_addr first;
178 /* description of each stream of the ffserver.conf file */
179 typedef struct FFStream {
180 enum StreamType stream_type;
181 char filename[1024]; /* stream filename */
182 struct FFStream *feed; /* feed we are using (can be null if
184 AVFormatParameters *ap_in; /* input parameters */
185 AVInputFormat *ifmt; /* if non NULL, force input format */
189 int prebuffer; /* Number of millseconds early to start */
190 long max_time; /* Number of milliseconds to run */
192 AVStream *streams[MAX_STREAMS];
193 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
194 char feed_filename[1024]; /* file name of the feed storage, or
195 input file name for a stream */
200 pid_t pid; /* Of ffmpeg process */
201 time_t pid_start; /* Of ffmpeg process */
203 struct FFStream *next;
204 int bandwidth; /* bandwidth, in kbits/s */
207 /* multicast specific */
209 struct in_addr multicast_ip;
210 int multicast_port; /* first port used for multicast */
212 int loop; /* if true, send the stream in loops (only meaningful if file) */
215 int feed_opened; /* true if someone is writing to the feed */
216 int is_feed; /* true if it is a feed */
217 int readonly; /* True if writing is prohibited to the file */
219 int64_t bytes_served;
220 int64_t feed_max_size; /* maximum storage size */
221 int64_t feed_write_index; /* current write position in feed (it wraps round) */
222 int64_t feed_size; /* current size of feed */
223 struct FFStream *next_feed;
226 typedef struct FeedData {
227 long long data_count;
228 float avg_frame_size; /* frame size averraged over last frames with exponential mean */
231 struct sockaddr_in my_http_addr;
232 struct sockaddr_in my_rtsp_addr;
234 char logfilename[1024];
235 HTTPContext *first_http_ctx;
236 FFStream *first_feed; /* contains only feeds */
237 FFStream *first_stream; /* contains all streams, including feeds */
239 static void new_connection(int server_fd, int is_rtsp);
240 static void close_connection(HTTPContext *c);
243 static int handle_connection(HTTPContext *c);
244 static int http_parse_request(HTTPContext *c);
245 static int http_send_data(HTTPContext *c);
246 static void compute_stats(HTTPContext *c);
247 static int open_input_stream(HTTPContext *c, const char *info);
248 static int http_start_receive_data(HTTPContext *c);
249 static int http_receive_data(HTTPContext *c);
252 static int rtsp_parse_request(HTTPContext *c);
253 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
254 static void rtsp_cmd_options(HTTPContext *c, const char *url);
255 static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPHeader *h);
256 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h);
257 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h);
258 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h);
261 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
262 struct in_addr my_ip);
265 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
266 FFStream *stream, const char *session_id,
267 enum RTSPProtocol rtp_protocol);
268 static int rtp_new_av_stream(HTTPContext *c,
269 int stream_index, struct sockaddr_in *dest_addr,
270 HTTPContext *rtsp_c);
272 static const char *my_program_name;
273 static const char *my_program_dir;
275 static int ffserver_debug;
276 static int ffserver_daemon;
277 static int no_launch;
278 static int need_to_start_children;
280 int nb_max_connections;
284 int current_bandwidth;
286 static long cur_time; // Making this global saves on passing it around everywhere
288 static long gettime_ms(void)
292 gettimeofday(&tv,NULL);
293 return (long long)tv.tv_sec * 1000 + (tv.tv_usec / 1000);
296 static FILE *logfile = NULL;
298 static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
304 vfprintf(logfile, fmt, ap);
310 static char *ctime1(char *buf2)
318 p = buf2 + strlen(p) - 1;
324 static void log_connection(HTTPContext *c)
331 http_log("%s - - [%s] \"%s %s %s\" %d %lld\n",
332 inet_ntoa(c->from_addr.sin_addr),
333 ctime1(buf2), c->method, c->url,
334 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
337 static void update_datarate(DataRateData *drd, int64_t count)
339 if (!drd->time1 && !drd->count1) {
340 drd->time1 = drd->time2 = cur_time;
341 drd->count1 = drd->count2 = count;
343 if (cur_time - drd->time2 > 5000) {
344 drd->time1 = drd->time2;
345 drd->count1 = drd->count2;
346 drd->time2 = cur_time;
352 /* In bytes per second */
353 static int compute_datarate(DataRateData *drd, int64_t count)
355 if (cur_time == drd->time1)
358 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
361 static int get_longterm_datarate(DataRateData *drd, int64_t count)
363 /* You get the first 3 seconds flat out */
364 if (cur_time - drd->time1 < 3000)
366 return compute_datarate(drd, count);
370 static void start_children(FFStream *feed)
375 for (; feed; feed = feed->next) {
376 if (feed->child_argv && !feed->pid) {
377 feed->pid_start = time(0);
382 fprintf(stderr, "Unable to create children\n");
391 for (i = 3; i < 256; i++) {
395 if (!ffserver_debug) {
396 i = open("/dev/null", O_RDWR);
405 pstrcpy(pathname, sizeof(pathname), my_program_name);
407 slash = strrchr(pathname, '/');
413 strcpy(slash, "ffmpeg");
415 /* This is needed to make relative pathnames work */
416 chdir(my_program_dir);
418 signal(SIGPIPE, SIG_DFL);
420 execvp(pathname, feed->child_argv);
428 /* open a listening socket */
429 static int socket_open_listen(struct sockaddr_in *my_addr)
433 server_fd = socket(AF_INET,SOCK_STREAM,0);
440 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
442 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
444 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
450 if (listen (server_fd, 5) < 0) {
455 fcntl(server_fd, F_SETFL, O_NONBLOCK);
460 /* start all multicast streams */
461 static void start_multicast(void)
466 struct sockaddr_in dest_addr;
467 int default_port, stream_index;
470 for(stream = first_stream; stream != NULL; stream = stream->next) {
471 if (stream->is_multicast) {
472 /* open the RTP connection */
473 snprintf(session_id, sizeof(session_id),
474 "%08x%08x", (int)random(), (int)random());
476 /* choose a port if none given */
477 if (stream->multicast_port == 0) {
478 stream->multicast_port = default_port;
482 dest_addr.sin_family = AF_INET;
483 dest_addr.sin_addr = stream->multicast_ip;
484 dest_addr.sin_port = htons(stream->multicast_port);
486 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
487 RTSP_PROTOCOL_RTP_UDP_MULTICAST);
491 if (open_input_stream(rtp_c, "") < 0) {
492 fprintf(stderr, "Could not open input stream for stream '%s'\n",
497 /* open each RTP stream */
498 for(stream_index = 0; stream_index < stream->nb_streams;
500 dest_addr.sin_port = htons(stream->multicast_port +
502 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
503 fprintf(stderr, "Could not open output stream '%s/streamid=%d'\n",
504 stream->filename, stream_index);
509 /* change state to send data */
510 rtp_c->state = HTTPSTATE_SEND_DATA;
515 /* main loop of the http server */
516 static int http_server(void)
518 int server_fd, ret, rtsp_server_fd, delay, delay1;
519 struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 2], *poll_entry;
520 HTTPContext *c, *c_next;
522 server_fd = socket_open_listen(&my_http_addr);
526 rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
527 if (rtsp_server_fd < 0)
530 http_log("ffserver started.\n");
532 start_children(first_feed);
534 first_http_ctx = NULL;
540 poll_entry = poll_table;
541 poll_entry->fd = server_fd;
542 poll_entry->events = POLLIN;
545 poll_entry->fd = rtsp_server_fd;
546 poll_entry->events = POLLIN;
549 /* wait for events on each HTTP handle */
556 case HTTPSTATE_SEND_HEADER:
557 case RTSPSTATE_SEND_REPLY:
558 case RTSPSTATE_SEND_PACKET:
559 c->poll_entry = poll_entry;
561 poll_entry->events = POLLOUT;
564 case HTTPSTATE_SEND_DATA_HEADER:
565 case HTTPSTATE_SEND_DATA:
566 case HTTPSTATE_SEND_DATA_TRAILER:
567 if (!c->is_packetized) {
568 /* for TCP, we output as much as we can (may need to put a limit) */
569 c->poll_entry = poll_entry;
571 poll_entry->events = POLLOUT;
574 /* when ffserver is doing the timing, we work by
575 looking at which packet need to be sent every
577 delay1 = 10; /* one tick wait XXX: 10 ms assumed */
582 case HTTPSTATE_WAIT_REQUEST:
583 case HTTPSTATE_RECEIVE_DATA:
584 case HTTPSTATE_WAIT_FEED:
585 case RTSPSTATE_WAIT_REQUEST:
586 /* need to catch errors */
587 c->poll_entry = poll_entry;
589 poll_entry->events = POLLIN;/* Maybe this will work */
593 c->poll_entry = NULL;
599 /* wait for an event on one connection. We poll at least every
600 second to handle timeouts */
602 ret = poll(poll_table, poll_entry - poll_table, delay);
603 if (ret < 0 && errno != EAGAIN && errno != EINTR)
607 cur_time = gettime_ms();
609 if (need_to_start_children) {
610 need_to_start_children = 0;
611 start_children(first_feed);
614 /* now handle the events */
615 for(c = first_http_ctx; c != NULL; c = c_next) {
617 if (handle_connection(c) < 0) {
618 /* close and free the connection */
624 poll_entry = poll_table;
625 /* new HTTP connection request ? */
626 if (poll_entry->revents & POLLIN) {
627 new_connection(server_fd, 0);
630 /* new RTSP connection request ? */
631 if (poll_entry->revents & POLLIN) {
632 new_connection(rtsp_server_fd, 1);
637 /* start waiting for a new HTTP/RTSP request */
638 static void start_wait_request(HTTPContext *c, int is_rtsp)
640 c->buffer_ptr = c->buffer;
641 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
644 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
645 c->state = RTSPSTATE_WAIT_REQUEST;
647 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
648 c->state = HTTPSTATE_WAIT_REQUEST;
652 static void new_connection(int server_fd, int is_rtsp)
654 struct sockaddr_in from_addr;
656 HTTPContext *c = NULL;
658 len = sizeof(from_addr);
659 fd = accept(server_fd, (struct sockaddr *)&from_addr,
663 fcntl(fd, F_SETFL, O_NONBLOCK);
665 /* XXX: should output a warning page when coming
666 close to the connection limit */
667 if (nb_connections >= nb_max_connections)
670 /* add a new connection */
671 c = av_mallocz(sizeof(HTTPContext));
676 c->poll_entry = NULL;
677 c->from_addr = from_addr;
678 c->buffer_size = IOBUFFER_INIT_SIZE;
679 c->buffer = av_malloc(c->buffer_size);
683 c->next = first_http_ctx;
687 start_wait_request(c, is_rtsp);
699 static void close_connection(HTTPContext *c)
701 HTTPContext **cp, *c1;
703 AVFormatContext *ctx;
707 /* remove connection from list */
708 cp = &first_http_ctx;
709 while ((*cp) != NULL) {
718 /* remove references, if any (XXX: do it faster) */
719 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
724 /* remove connection associated resources */
728 /* close each frame parser */
729 for(i=0;i<c->fmt_in->nb_streams;i++) {
730 st = c->fmt_in->streams[i];
731 if (st->codec.codec) {
732 avcodec_close(&st->codec);
735 av_close_input_file(c->fmt_in);
738 /* free RTP output streams if any */
741 nb_streams = c->stream->nb_streams;
743 for(i=0;i<nb_streams;i++) {
746 av_write_trailer(ctx);
749 h = c->rtp_handles[i];
757 if (!c->last_packet_sent) {
760 if (url_open_dyn_buf(&ctx->pb) >= 0) {
761 av_write_trailer(ctx);
762 url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
767 for(i=0; i<ctx->nb_streams; i++)
768 av_free(ctx->streams[i]) ;
771 current_bandwidth -= c->stream->bandwidth;
772 av_freep(&c->pb_buffer);
773 av_freep(&c->packet_buffer);
779 static int handle_connection(HTTPContext *c)
784 case HTTPSTATE_WAIT_REQUEST:
785 case RTSPSTATE_WAIT_REQUEST:
787 if ((c->timeout - cur_time) < 0)
789 if (c->poll_entry->revents & (POLLERR | POLLHUP))
792 /* no need to read if no events */
793 if (!(c->poll_entry->revents & POLLIN))
797 len = read(c->fd, c->buffer_ptr, 1);
799 if (errno != EAGAIN && errno != EINTR)
801 } else if (len == 0) {
804 /* search for end of request. */
806 c->buffer_ptr += len;
808 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
809 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
810 /* request found : parse it and reply */
811 if (c->state == HTTPSTATE_WAIT_REQUEST) {
812 ret = http_parse_request(c);
814 ret = rtsp_parse_request(c);
818 } else if (ptr >= c->buffer_end) {
819 /* request too long: cannot do anything */
821 } else goto read_loop;
825 case HTTPSTATE_SEND_HEADER:
826 if (c->poll_entry->revents & (POLLERR | POLLHUP))
829 /* no need to write if no events */
830 if (!(c->poll_entry->revents & POLLOUT))
832 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
834 if (errno != EAGAIN && errno != EINTR) {
835 /* error : close connection */
836 av_freep(&c->pb_buffer);
840 c->buffer_ptr += len;
842 c->stream->bytes_served += len;
843 c->data_count += len;
844 if (c->buffer_ptr >= c->buffer_end) {
845 av_freep(&c->pb_buffer);
850 /* all the buffer was sent : synchronize to the incoming stream */
851 c->state = HTTPSTATE_SEND_DATA_HEADER;
852 c->buffer_ptr = c->buffer_end = c->buffer;
857 case HTTPSTATE_SEND_DATA:
858 case HTTPSTATE_SEND_DATA_HEADER:
859 case HTTPSTATE_SEND_DATA_TRAILER:
860 /* for packetized output, we consider we can always write (the
861 input streams sets the speed). It may be better to verify
862 that we do not rely too much on the kernel queues */
863 if (!c->is_packetized) {
864 if (c->poll_entry->revents & (POLLERR | POLLHUP))
867 /* no need to read if no events */
868 if (!(c->poll_entry->revents & POLLOUT))
871 if (http_send_data(c) < 0)
874 case HTTPSTATE_RECEIVE_DATA:
875 /* no need to read if no events */
876 if (c->poll_entry->revents & (POLLERR | POLLHUP))
878 if (!(c->poll_entry->revents & POLLIN))
880 if (http_receive_data(c) < 0)
883 case HTTPSTATE_WAIT_FEED:
884 /* no need to read if no events */
885 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
888 /* nothing to do, we'll be waken up by incoming feed packets */
891 case RTSPSTATE_SEND_REPLY:
892 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
893 av_freep(&c->pb_buffer);
896 /* no need to write if no events */
897 if (!(c->poll_entry->revents & POLLOUT))
899 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
901 if (errno != EAGAIN && errno != EINTR) {
902 /* error : close connection */
903 av_freep(&c->pb_buffer);
907 c->buffer_ptr += len;
908 c->data_count += len;
909 if (c->buffer_ptr >= c->buffer_end) {
910 /* all the buffer was sent : wait for a new request */
911 av_freep(&c->pb_buffer);
912 start_wait_request(c, 1);
916 case RTSPSTATE_SEND_PACKET:
917 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
918 av_freep(&c->packet_buffer);
921 /* no need to write if no events */
922 if (!(c->poll_entry->revents & POLLOUT))
924 len = write(c->fd, c->packet_buffer_ptr,
925 c->packet_buffer_end - c->packet_buffer_ptr);
927 if (errno != EAGAIN && errno != EINTR) {
928 /* error : close connection */
929 av_freep(&c->packet_buffer);
933 c->packet_buffer_ptr += len;
934 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
935 /* all the buffer was sent : wait for a new request */
936 av_freep(&c->packet_buffer);
937 c->state = RTSPSTATE_WAIT_REQUEST;
941 case HTTPSTATE_READY:
950 static int extract_rates(char *rates, int ratelen, const char *request)
954 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
955 if (strncasecmp(p, "Pragma:", 7) == 0) {
956 const char *q = p + 7;
958 while (*q && *q != '\n' && isspace(*q))
961 if (strncasecmp(q, "stream-switch-entry=", 20) == 0) {
967 memset(rates, 0xff, ratelen);
970 while (*q && *q != '\n' && *q != ':')
973 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2) {
977 if (stream_no < ratelen && stream_no >= 0) {
978 rates[stream_no] = rate_no;
981 while (*q && *q != '\n' && !isspace(*q))
998 static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
1001 int best_bitrate = 100000000;
1004 for (i = 0; i < feed->nb_streams; i++) {
1005 AVCodecContext *feed_codec = &feed->streams[i]->codec;
1007 if (feed_codec->codec_id != codec->codec_id ||
1008 feed_codec->sample_rate != codec->sample_rate ||
1009 feed_codec->width != codec->width ||
1010 feed_codec->height != codec->height) {
1014 /* Potential stream */
1016 /* We want the fastest stream less than bit_rate, or the slowest
1017 * faster than bit_rate
1020 if (feed_codec->bit_rate <= bit_rate) {
1021 if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
1022 best_bitrate = feed_codec->bit_rate;
1026 if (feed_codec->bit_rate < best_bitrate) {
1027 best_bitrate = feed_codec->bit_rate;
1036 static int modify_current_stream(HTTPContext *c, char *rates)
1039 FFStream *req = c->stream;
1040 int action_required = 0;
1042 /* Not much we can do for a feed */
1046 for (i = 0; i < req->nb_streams; i++) {
1047 AVCodecContext *codec = &req->streams[i]->codec;
1051 c->switch_feed_streams[i] = req->feed_streams[i];
1054 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1057 /* Wants off or slow */
1058 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1060 /* This doesn't work well when it turns off the only stream! */
1061 c->switch_feed_streams[i] = -2;
1062 c->feed_streams[i] = -2;
1067 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1068 action_required = 1;
1071 return action_required;
1075 static void do_switch_stream(HTTPContext *c, int i)
1077 if (c->switch_feed_streams[i] >= 0) {
1079 c->feed_streams[i] = c->switch_feed_streams[i];
1082 /* Now update the stream */
1084 c->switch_feed_streams[i] = -1;
1087 /* XXX: factorize in utils.c ? */
1088 /* XXX: take care with different space meaning */
1089 static void skip_spaces(const char **pp)
1093 while (*p == ' ' || *p == '\t')
1098 static void get_word(char *buf, int buf_size, const char **pp)
1106 while (!isspace(*p) && *p != '\0') {
1107 if ((q - buf) < buf_size - 1)
1116 static int validate_acl(FFStream *stream, HTTPContext *c)
1118 enum IPAddressAction last_action = IP_DENY;
1120 struct in_addr *src = &c->from_addr.sin_addr;
1121 unsigned long src_addr = ntohl(src->s_addr);
1123 for (acl = stream->acl; acl; acl = acl->next) {
1124 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr) {
1125 return (acl->action == IP_ALLOW) ? 1 : 0;
1127 last_action = acl->action;
1130 /* Nothing matched, so return not the last action */
1131 return (last_action == IP_DENY) ? 1 : 0;
1134 /* compute the real filename of a file by matching it without its
1135 extensions to all the stream filenames */
1136 static void compute_real_filename(char *filename, int max_size)
1143 /* compute filename by matching without the file extensions */
1144 pstrcpy(file1, sizeof(file1), filename);
1145 p = strrchr(file1, '.');
1148 for(stream = first_stream; stream != NULL; stream = stream->next) {
1149 pstrcpy(file2, sizeof(file2), stream->filename);
1150 p = strrchr(file2, '.');
1153 if (!strcmp(file1, file2)) {
1154 pstrcpy(filename, max_size, stream->filename);
1169 /* parse http request and prepare header */
1170 static int http_parse_request(HTTPContext *c)
1174 enum RedirType redir_type;
1176 char info[1024], *filename;
1180 const char *mime_type;
1184 char *useragent = 0;
1187 get_word(cmd, sizeof(cmd), (const char **)&p);
1188 pstrcpy(c->method, sizeof(c->method), cmd);
1190 if (!strcmp(cmd, "GET"))
1192 else if (!strcmp(cmd, "POST"))
1197 get_word(url, sizeof(url), (const char **)&p);
1198 pstrcpy(c->url, sizeof(c->url), url);
1200 get_word(protocol, sizeof(protocol), (const char **)&p);
1201 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1204 pstrcpy(c->protocol, sizeof(c->protocol), protocol);
1206 /* find the filename and the optional info string in the request */
1213 pstrcpy(info, sizeof(info), p);
1219 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1220 if (strncasecmp(p, "User-Agent:", 11) == 0) {
1222 if (*useragent && *useragent != '\n' && isspace(*useragent))
1226 p = strchr(p, '\n');
1233 redir_type = REDIR_NONE;
1234 if (match_ext(filename, "asx")) {
1235 redir_type = REDIR_ASX;
1236 filename[strlen(filename)-1] = 'f';
1237 } else if (match_ext(filename, "asf") &&
1238 (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1239 /* if this isn't WMP or lookalike, return the redirector file */
1240 redir_type = REDIR_ASF;
1241 } else if (match_ext(filename, "rpm,ram")) {
1242 redir_type = REDIR_RAM;
1243 strcpy(filename + strlen(filename)-2, "m");
1244 } else if (match_ext(filename, "rtsp")) {
1245 redir_type = REDIR_RTSP;
1246 compute_real_filename(filename, sizeof(url) - 1);
1247 } else if (match_ext(filename, "sdp")) {
1248 redir_type = REDIR_SDP;
1249 compute_real_filename(filename, sizeof(url) - 1);
1252 stream = first_stream;
1253 while (stream != NULL) {
1254 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1256 stream = stream->next;
1258 if (stream == NULL) {
1259 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1264 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1265 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1267 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1268 c->http_error = 301;
1270 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 301 Moved\r\n");
1271 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Location: %s\r\n", stream->feed_filename);
1272 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: text/html\r\n");
1273 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1274 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<html><head><title>Moved</title></head><body>\r\n");
1275 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "You should be <a href=\"%s\">redirected</a>.\r\n", stream->feed_filename);
1276 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</body></html>\r\n");
1278 /* prepare output buffer */
1279 c->buffer_ptr = c->buffer;
1281 c->state = HTTPSTATE_SEND_HEADER;
1285 /* If this is WMP, get the rate information */
1286 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1287 if (modify_current_stream(c, ratebuf)) {
1288 for (i = 0; i < sizeof(c->feed_streams) / sizeof(c->feed_streams[0]); i++) {
1289 if (c->switch_feed_streams[i] >= 0)
1290 do_switch_stream(c, i);
1295 if (post == 0 && stream->stream_type == STREAM_TYPE_LIVE) {
1296 current_bandwidth += stream->bandwidth;
1299 if (post == 0 && max_bandwidth < current_bandwidth) {
1300 c->http_error = 200;
1302 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 Server too busy\r\n");
1303 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: text/html\r\n");
1304 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1305 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<html><head><title>Too busy</title></head><body>\r\n");
1306 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "The server is too busy to serve your request at this time.<p>\r\n");
1307 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "The bandwidth being served (including your stream) is %dkbit/sec, and this exceeds the limit of %dkbit/sec\r\n",
1308 current_bandwidth, max_bandwidth);
1309 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</body></html>\r\n");
1311 /* prepare output buffer */
1312 c->buffer_ptr = c->buffer;
1314 c->state = HTTPSTATE_SEND_HEADER;
1318 if (redir_type != REDIR_NONE) {
1321 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1322 if (strncasecmp(p, "Host:", 5) == 0) {
1326 p = strchr(p, '\n');
1337 while (isspace(*hostinfo))
1340 eoh = strchr(hostinfo, '\n');
1342 if (eoh[-1] == '\r')
1345 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1346 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1347 hostbuf[eoh - hostinfo] = 0;
1349 c->http_error = 200;
1351 switch(redir_type) {
1353 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 ASX Follows\r\n");
1354 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: video/x-ms-asf\r\n");
1355 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1356 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<ASX Version=\"3\">\r\n");
1357 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<!-- Autogenerated by ffserver -->\r\n");
1358 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n",
1359 hostbuf, filename, info);
1360 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</ASX>\r\n");
1363 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 RAM Follows\r\n");
1364 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: audio/x-pn-realaudio\r\n");
1365 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1366 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "# Autogenerated by ffserver\r\n");
1367 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "http://%s/%s%s\r\n",
1368 hostbuf, filename, info);
1371 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 ASF Redirect follows\r\n");
1372 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: video/x-ms-asf\r\n");
1373 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1374 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "[Reference]\r\n");
1375 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Ref1=http://%s/%s%s\r\n",
1376 hostbuf, filename, info);
1380 char hostname[256], *p;
1381 /* extract only hostname */
1382 pstrcpy(hostname, sizeof(hostname), hostbuf);
1383 p = strrchr(hostname, ':');
1386 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 RTSP Redirect follows\r\n");
1387 /* XXX: incorrect mime type ? */
1388 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: application/x-rtsp\r\n");
1389 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1390 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "rtsp://%s:%d/%s\r\n",
1391 hostname, ntohs(my_rtsp_addr.sin_port),
1398 int sdp_data_size, len;
1399 struct sockaddr_in my_addr;
1401 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
1402 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: application/sdp\r\n");
1403 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1405 len = sizeof(my_addr);
1406 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
1408 /* XXX: should use a dynamic buffer */
1409 sdp_data_size = prepare_sdp_description(stream,
1412 if (sdp_data_size > 0) {
1413 memcpy(q, sdp_data, sdp_data_size);
1425 /* prepare output buffer */
1426 c->buffer_ptr = c->buffer;
1428 c->state = HTTPSTATE_SEND_HEADER;
1434 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1438 stream->conns_served++;
1440 /* XXX: add there authenticate and IP match */
1443 /* if post, it means a feed is being sent */
1444 if (!stream->is_feed) {
1445 /* However it might be a status report from WMP! Lets log the data
1446 * as it might come in handy one day
1451 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1452 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1456 if (strncasecmp(p, "Pragma: client-id=", 18) == 0) {
1457 client_id = strtol(p + 18, 0, 10);
1459 p = strchr(p, '\n');
1467 char *eol = strchr(logline, '\n');
1472 if (eol[-1] == '\r')
1474 http_log("%.*s\n", (int) (eol - logline), logline);
1475 c->suppress_log = 1;
1480 http_log("\nGot request:\n%s\n", c->buffer);
1483 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1486 /* Now we have to find the client_id */
1487 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1488 if (wmpc->wmp_client_id == client_id)
1493 if (modify_current_stream(wmpc, ratebuf)) {
1494 wmpc->switch_pending = 1;
1499 snprintf(msg, sizeof(msg), "POST command not handled");
1503 if (http_start_receive_data(c) < 0) {
1504 snprintf(msg, sizeof(msg), "could not open feed");
1508 c->state = HTTPSTATE_RECEIVE_DATA;
1513 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0) {
1514 http_log("\nGot request:\n%s\n", c->buffer);
1518 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1521 /* open input stream */
1522 if (open_input_stream(c, info) < 0) {
1523 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1527 /* prepare http header */
1529 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
1530 mime_type = c->stream->fmt->mime_type;
1532 mime_type = "application/x-octet_stream";
1533 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Pragma: no-cache\r\n");
1535 /* for asf, we need extra headers */
1536 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1537 /* Need to allocate a client id */
1539 c->wmp_client_id = random() & 0x7fffffff;
1541 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);
1543 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-Type: %s\r\n", mime_type);
1544 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1546 /* prepare output buffer */
1548 c->buffer_ptr = c->buffer;
1550 c->state = HTTPSTATE_SEND_HEADER;
1553 c->http_error = 404;
1555 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 404 Not Found\r\n");
1556 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: %s\r\n", "text/html");
1557 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1558 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<HTML>\n");
1559 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<HEAD><TITLE>404 Not Found</TITLE></HEAD>\n");
1560 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<BODY>%s</BODY>\n", msg);
1561 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</HTML>\n");
1563 /* prepare output buffer */
1564 c->buffer_ptr = c->buffer;
1566 c->state = HTTPSTATE_SEND_HEADER;
1570 c->http_error = 200; /* horrible : we use this value to avoid
1571 going to the send data state */
1572 c->state = HTTPSTATE_SEND_HEADER;
1576 static void fmt_bytecount(ByteIOContext *pb, int64_t count)
1578 static const char *suffix = " kMGTP";
1581 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++) {
1584 url_fprintf(pb, "%lld%c", count, *s);
1587 static void compute_stats(HTTPContext *c)
1594 ByteIOContext pb1, *pb = &pb1;
1596 if (url_open_dyn_buf(pb) < 0) {
1597 /* XXX: return an error ? */
1598 c->buffer_ptr = c->buffer;
1599 c->buffer_end = c->buffer;
1603 url_fprintf(pb, "HTTP/1.0 200 OK\r\n");
1604 url_fprintf(pb, "Content-type: %s\r\n", "text/html");
1605 url_fprintf(pb, "Pragma: no-cache\r\n");
1606 url_fprintf(pb, "\r\n");
1608 url_fprintf(pb, "<HEAD><TITLE>FFServer Status</TITLE>\n");
1609 if (c->stream->feed_filename) {
1610 url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
1612 url_fprintf(pb, "</HEAD>\n<BODY>");
1613 url_fprintf(pb, "<H1>FFServer Status</H1>\n");
1615 url_fprintf(pb, "<H2>Available Streams</H2>\n");
1616 url_fprintf(pb, "<TABLE cellspacing=0 cellpadding=4>\n");
1617 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");
1618 stream = first_stream;
1619 while (stream != NULL) {
1620 char sfilename[1024];
1623 if (stream->feed != stream) {
1624 pstrcpy(sfilename, sizeof(sfilename) - 10, stream->filename);
1625 eosf = sfilename + strlen(sfilename);
1626 if (eosf - sfilename >= 4) {
1627 if (strcmp(eosf - 4, ".asf") == 0) {
1628 strcpy(eosf - 4, ".asx");
1629 } else if (strcmp(eosf - 3, ".rm") == 0) {
1630 strcpy(eosf - 3, ".ram");
1631 } else if (stream->fmt == &rtp_mux) {
1632 /* generate a sample RTSP director if
1633 unicast. Generate an SDP redirector if
1635 eosf = strrchr(sfilename, '.');
1637 eosf = sfilename + strlen(sfilename);
1638 if (stream->is_multicast)
1639 strcpy(eosf, ".sdp");
1641 strcpy(eosf, ".rtsp");
1645 url_fprintf(pb, "<TR><TD><A HREF=\"/%s\">%s</A> ",
1646 sfilename, stream->filename);
1647 url_fprintf(pb, "<td align=right> %d <td align=right> ",
1648 stream->conns_served);
1649 fmt_bytecount(pb, stream->bytes_served);
1650 switch(stream->stream_type) {
1651 case STREAM_TYPE_LIVE:
1653 int audio_bit_rate = 0;
1654 int video_bit_rate = 0;
1655 const char *audio_codec_name = "";
1656 const char *video_codec_name = "";
1657 const char *audio_codec_name_extra = "";
1658 const char *video_codec_name_extra = "";
1660 for(i=0;i<stream->nb_streams;i++) {
1661 AVStream *st = stream->streams[i];
1662 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
1663 switch(st->codec.codec_type) {
1664 case CODEC_TYPE_AUDIO:
1665 audio_bit_rate += st->codec.bit_rate;
1667 if (*audio_codec_name)
1668 audio_codec_name_extra = "...";
1669 audio_codec_name = codec->name;
1672 case CODEC_TYPE_VIDEO:
1673 video_bit_rate += st->codec.bit_rate;
1675 if (*video_codec_name)
1676 video_codec_name_extra = "...";
1677 video_codec_name = codec->name;
1680 case CODEC_TYPE_DATA:
1681 video_bit_rate += st->codec.bit_rate;
1687 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",
1690 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
1691 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
1693 url_fprintf(pb, "<TD>%s", stream->feed->filename);
1695 url_fprintf(pb, "<TD>%s", stream->feed_filename);
1697 url_fprintf(pb, "\n");
1701 url_fprintf(pb, "<TD align=center> - <TD align=right> - <TD align=right> - <td><td align=right> - <TD>\n");
1705 stream = stream->next;
1707 url_fprintf(pb, "</TABLE>\n");
1709 stream = first_stream;
1710 while (stream != NULL) {
1711 if (stream->feed == stream) {
1712 url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
1714 url_fprintf(pb, "Running as pid %d.\n", stream->pid);
1716 #if defined(linux) && !defined(CONFIG_NOCUTILS)
1721 /* This is somewhat linux specific I guess */
1722 snprintf(ps_cmd, sizeof(ps_cmd),
1723 "ps -o \"%%cpu,cputime\" --no-headers %d",
1726 pid_stat = popen(ps_cmd, "r");
1731 if (fscanf(pid_stat, "%10s %64s", cpuperc,
1733 url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
1741 url_fprintf(pb, "<p>");
1743 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");
1745 for (i = 0; i < stream->nb_streams; i++) {
1746 AVStream *st = stream->streams[i];
1747 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
1748 const char *type = "unknown";
1749 char parameters[64];
1753 switch(st->codec.codec_type) {
1754 case CODEC_TYPE_AUDIO:
1757 case CODEC_TYPE_VIDEO:
1759 snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec.width, st->codec.height,
1760 st->codec.qmin, st->codec.qmax, st->codec.frame_rate / st->codec.frame_rate_base);
1765 url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
1766 i, type, st->codec.bit_rate/1000, codec ? codec->name : "", parameters);
1768 url_fprintf(pb, "</table>\n");
1771 stream = stream->next;
1777 AVCodecContext *enc;
1781 stream = first_feed;
1782 while (stream != NULL) {
1783 url_fprintf(pb, "<H1>Feed '%s'</H1>\n", stream->filename);
1784 url_fprintf(pb, "<TABLE>\n");
1785 url_fprintf(pb, "<TR><TD>Parameters<TD>Frame count<TD>Size<TD>Avg bitrate (kbits/s)\n");
1786 for(i=0;i<stream->nb_streams;i++) {
1787 AVStream *st = stream->streams[i];
1788 FeedData *fdata = st->priv_data;
1791 avcodec_string(buf, sizeof(buf), enc);
1792 avg = fdata->avg_frame_size * (float)enc->rate * 8.0;
1793 if (enc->codec->type == CODEC_TYPE_AUDIO && enc->frame_size > 0)
1794 avg /= enc->frame_size;
1795 url_fprintf(pb, "<TR><TD>%s <TD> %d <TD> %Ld <TD> %0.1f\n",
1796 buf, enc->frame_number, fdata->data_count, avg / 1000.0);
1798 url_fprintf(pb, "</TABLE>\n");
1799 stream = stream->next_feed;
1804 /* connection status */
1805 url_fprintf(pb, "<H2>Connection Status</H2>\n");
1807 url_fprintf(pb, "Number of connections: %d / %d<BR>\n",
1808 nb_connections, nb_max_connections);
1810 url_fprintf(pb, "Bandwidth in use: %dk / %dk<BR>\n",
1811 current_bandwidth, max_bandwidth);
1813 url_fprintf(pb, "<TABLE>\n");
1814 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");
1815 c1 = first_http_ctx;
1817 while (c1 != NULL) {
1823 for (j = 0; j < c1->stream->nb_streams; j++) {
1824 if (!c1->stream->feed) {
1825 bitrate += c1->stream->streams[j]->codec.bit_rate;
1827 if (c1->feed_streams[j] >= 0) {
1828 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec.bit_rate;
1835 p = inet_ntoa(c1->from_addr.sin_addr);
1836 url_fprintf(pb, "<TR><TD><B>%d</B><TD>%s%s<TD>%s<TD>%s<TD>%s<td align=right>",
1838 c1->stream ? c1->stream->filename : "",
1839 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
1842 http_state[c1->state]);
1843 fmt_bytecount(pb, bitrate);
1844 url_fprintf(pb, "<td align=right>");
1845 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
1846 url_fprintf(pb, "<td align=right>");
1847 fmt_bytecount(pb, c1->data_count);
1848 url_fprintf(pb, "\n");
1851 url_fprintf(pb, "</TABLE>\n");
1856 url_fprintf(pb, "<HR size=1 noshade>Generated at %s", p);
1857 url_fprintf(pb, "</BODY>\n</HTML>\n");
1859 len = url_close_dyn_buf(pb, &c->pb_buffer);
1860 c->buffer_ptr = c->pb_buffer;
1861 c->buffer_end = c->pb_buffer + len;
1864 /* check if the parser needs to be opened for stream i */
1865 static void open_parser(AVFormatContext *s, int i)
1867 AVStream *st = s->streams[i];
1870 if (!st->codec.codec) {
1871 codec = avcodec_find_decoder(st->codec.codec_id);
1872 if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) {
1873 st->codec.parse_only = 1;
1874 if (avcodec_open(&st->codec, codec) < 0) {
1875 st->codec.parse_only = 0;
1881 static int open_input_stream(HTTPContext *c, const char *info)
1884 char input_filename[1024];
1889 /* find file name */
1890 if (c->stream->feed) {
1891 strcpy(input_filename, c->stream->feed->feed_filename);
1892 buf_size = FFM_PACKET_SIZE;
1893 /* compute position (absolute time) */
1894 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1895 stream_pos = parse_date(buf, 0);
1896 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
1897 int prebuffer = strtol(buf, 0, 10);
1898 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
1900 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
1903 strcpy(input_filename, c->stream->feed_filename);
1905 /* compute position (relative time) */
1906 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1907 stream_pos = parse_date(buf, 1);
1912 if (input_filename[0] == '\0')
1916 { time_t when = stream_pos / 1000000;
1917 http_log("Stream pos = %lld, time=%s", stream_pos, ctime(&when));
1922 if (av_open_input_file(&s, input_filename, c->stream->ifmt,
1923 buf_size, c->stream->ap_in) < 0) {
1924 http_log("%s not found", input_filename);
1929 /* open each parser */
1930 for(i=0;i<s->nb_streams;i++)
1933 /* choose stream as clock source (we favorize video stream if
1934 present) for packet sending */
1935 c->pts_stream_index = 0;
1936 for(i=0;i<c->stream->nb_streams;i++) {
1937 if (c->pts_stream_index == 0 &&
1938 c->stream->streams[i]->codec.codec_type == CODEC_TYPE_VIDEO) {
1939 c->pts_stream_index = i;
1944 if (c->fmt_in->iformat->read_seek) {
1945 c->fmt_in->iformat->read_seek(c->fmt_in, stream_pos);
1948 /* set the start time (needed for maxtime and RTP packet timing) */
1949 c->start_time = cur_time;
1950 c->first_pts = AV_NOPTS_VALUE;
1954 /* return the server clock (in us) */
1955 static int64_t get_server_clock(HTTPContext *c)
1957 /* compute current pts value from system time */
1958 return (int64_t)(cur_time - c->start_time) * 1000LL;
1961 /* return the estimated time at which the current packet must be sent
1963 static int64_t get_packet_send_clock(HTTPContext *c)
1965 int bytes_left, bytes_sent, frame_bytes;
1967 frame_bytes = c->cur_frame_bytes;
1968 if (frame_bytes <= 0) {
1971 bytes_left = c->buffer_end - c->buffer_ptr;
1972 bytes_sent = frame_bytes - bytes_left;
1973 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
1978 static int http_prepare_data(HTTPContext *c)
1981 AVFormatContext *ctx;
1983 av_freep(&c->pb_buffer);
1985 case HTTPSTATE_SEND_DATA_HEADER:
1986 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
1987 pstrcpy(c->fmt_ctx.author, sizeof(c->fmt_ctx.author),
1989 pstrcpy(c->fmt_ctx.comment, sizeof(c->fmt_ctx.comment),
1990 c->stream->comment);
1991 pstrcpy(c->fmt_ctx.copyright, sizeof(c->fmt_ctx.copyright),
1992 c->stream->copyright);
1993 pstrcpy(c->fmt_ctx.title, sizeof(c->fmt_ctx.title),
1996 /* open output stream by using specified codecs */
1997 c->fmt_ctx.oformat = c->stream->fmt;
1998 c->fmt_ctx.nb_streams = c->stream->nb_streams;
1999 for(i=0;i<c->fmt_ctx.nb_streams;i++) {
2001 st = av_mallocz(sizeof(AVStream));
2002 c->fmt_ctx.streams[i] = st;
2003 /* if file or feed, then just take streams from FFStream struct */
2004 if (!c->stream->feed ||
2005 c->stream->feed == c->stream)
2006 memcpy(st, c->stream->streams[i], sizeof(AVStream));
2008 memcpy(st, c->stream->feed->streams[c->stream->feed_streams[i]],
2010 st->codec.frame_number = 0; /* XXX: should be done in
2011 AVStream, not in codec */
2012 /* I'm pretty sure that this is not correct...
2013 * However, without it, we crash
2015 st->codec.coded_frame = &dummy_frame;
2017 c->got_key_frame = 0;
2019 /* prepare header and save header data in a stream */
2020 if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2021 /* XXX: potential leak */
2024 c->fmt_ctx.pb.is_streamed = 1;
2026 av_set_parameters(&c->fmt_ctx, NULL);
2027 av_write_header(&c->fmt_ctx);
2029 len = url_close_dyn_buf(&c->fmt_ctx.pb, &c->pb_buffer);
2030 c->buffer_ptr = c->pb_buffer;
2031 c->buffer_end = c->pb_buffer + len;
2033 c->state = HTTPSTATE_SEND_DATA;
2034 c->last_packet_sent = 0;
2036 case HTTPSTATE_SEND_DATA:
2037 /* find a new packet */
2041 /* read a packet from the input stream */
2042 if (c->stream->feed) {
2043 ffm_set_write_index(c->fmt_in,
2044 c->stream->feed->feed_write_index,
2045 c->stream->feed->feed_size);
2048 if (c->stream->max_time &&
2049 c->stream->max_time + c->start_time - cur_time < 0) {
2050 /* We have timed out */
2051 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2054 if (av_read_frame(c->fmt_in, &pkt) < 0) {
2055 if (c->stream->feed && c->stream->feed->feed_opened) {
2056 /* if coming from feed, it means we reached the end of the
2057 ffm file, so must wait for more data */
2058 c->state = HTTPSTATE_WAIT_FEED;
2059 return 1; /* state changed */
2061 if (c->stream->loop) {
2062 av_close_input_file(c->fmt_in);
2064 if (open_input_stream(c, "") < 0)
2069 /* must send trailer now because eof or error */
2070 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2074 /* update first pts if needed */
2075 if (c->first_pts == AV_NOPTS_VALUE) {
2076 c->first_pts = pkt.dts;
2077 c->start_time = cur_time;
2079 /* send it to the appropriate stream */
2080 if (c->stream->feed) {
2081 /* if coming from a feed, select the right stream */
2082 if (c->switch_pending) {
2083 c->switch_pending = 0;
2084 for(i=0;i<c->stream->nb_streams;i++) {
2085 if (c->switch_feed_streams[i] == pkt.stream_index) {
2086 if (pkt.flags & PKT_FLAG_KEY) {
2087 do_switch_stream(c, i);
2090 if (c->switch_feed_streams[i] >= 0) {
2091 c->switch_pending = 1;
2095 for(i=0;i<c->stream->nb_streams;i++) {
2096 if (c->feed_streams[i] == pkt.stream_index) {
2097 pkt.stream_index = i;
2098 if (pkt.flags & PKT_FLAG_KEY) {
2099 c->got_key_frame |= 1 << i;
2101 /* See if we have all the key frames, then
2102 * we start to send. This logic is not quite
2103 * right, but it works for the case of a
2104 * single video stream with one or more
2105 * audio streams (for which every frame is
2106 * typically a key frame).
2108 if (!c->stream->send_on_key ||
2109 ((c->got_key_frame + 1) >> c->stream->nb_streams)) {
2115 AVCodecContext *codec;
2118 /* specific handling for RTP: we use several
2119 output stream (one for each RTP
2120 connection). XXX: need more abstract handling */
2121 if (c->is_packetized) {
2123 /* compute send time and duration */
2124 st = c->fmt_in->streams[pkt.stream_index];
2125 c->cur_pts = pkt.dts;
2126 if (st->start_time != AV_NOPTS_VALUE)
2127 c->cur_pts -= st->start_time;
2128 c->cur_frame_duration = pkt.duration;
2130 printf("index=%d pts=%0.3f duration=%0.6f\n",
2132 (double)c->cur_pts /
2134 (double)c->cur_frame_duration /
2137 /* find RTP context */
2138 c->packet_stream_index = pkt.stream_index;
2139 ctx = c->rtp_ctx[c->packet_stream_index];
2141 av_free_packet(&pkt);
2144 codec = &ctx->streams[0]->codec;
2145 /* only one stream per RTP connection */
2146 pkt.stream_index = 0;
2150 codec = &ctx->streams[pkt.stream_index]->codec;
2153 codec->coded_frame->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);
2154 if (c->is_packetized) {
2155 int max_packet_size;
2156 if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP)
2157 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2159 max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]);
2160 ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size);
2162 ret = url_open_dyn_buf(&ctx->pb);
2165 /* XXX: potential leak */
2168 if (av_write_frame(ctx, &pkt)) {
2169 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2172 len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
2173 c->cur_frame_bytes = len;
2174 c->buffer_ptr = c->pb_buffer;
2175 c->buffer_end = c->pb_buffer + len;
2177 codec->frame_number++;
2181 av_free_packet(&pkt);
2187 case HTTPSTATE_SEND_DATA_TRAILER:
2188 /* last packet test ? */
2189 if (c->last_packet_sent || c->is_packetized)
2192 /* prepare header */
2193 if (url_open_dyn_buf(&ctx->pb) < 0) {
2194 /* XXX: potential leak */
2197 av_write_trailer(ctx);
2198 len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
2199 c->buffer_ptr = c->pb_buffer;
2200 c->buffer_end = c->pb_buffer + len;
2202 c->last_packet_sent = 1;
2209 #define SHORT_TERM_BANDWIDTH 8000000
2211 /* should convert the format at the same time */
2212 /* send data starting at c->buffer_ptr to the output connection
2213 (either UDP or TCP connection) */
2214 static int http_send_data(HTTPContext *c)
2219 if (c->buffer_ptr >= c->buffer_end) {
2220 ret = http_prepare_data(c);
2223 else if (ret != 0) {
2224 /* state change requested */
2228 if (c->is_packetized) {
2229 /* RTP data output */
2230 len = c->buffer_end - c->buffer_ptr;
2232 /* fail safe - should never happen */
2234 c->buffer_ptr = c->buffer_end;
2237 len = (c->buffer_ptr[0] << 24) |
2238 (c->buffer_ptr[1] << 16) |
2239 (c->buffer_ptr[2] << 8) |
2241 if (len > (c->buffer_end - c->buffer_ptr))
2243 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2244 /* nothing to send yet: we can wait */
2248 c->data_count += len;
2249 update_datarate(&c->datarate, c->data_count);
2251 c->stream->bytes_served += len;
2253 if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP) {
2254 /* RTP packets are sent inside the RTSP TCP connection */
2255 ByteIOContext pb1, *pb = &pb1;
2256 int interleaved_index, size;
2258 HTTPContext *rtsp_c;
2261 /* if no RTSP connection left, error */
2264 /* if already sending something, then wait. */
2265 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST) {
2268 if (url_open_dyn_buf(pb) < 0)
2270 interleaved_index = c->packet_stream_index * 2;
2271 /* RTCP packets are sent at odd indexes */
2272 if (c->buffer_ptr[1] == 200)
2273 interleaved_index++;
2274 /* write RTSP TCP header */
2276 header[1] = interleaved_index;
2277 header[2] = len >> 8;
2279 put_buffer(pb, header, 4);
2280 /* write RTP packet data */
2282 put_buffer(pb, c->buffer_ptr, len);
2283 size = url_close_dyn_buf(pb, &c->packet_buffer);
2284 /* prepare asynchronous TCP sending */
2285 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2286 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2287 c->buffer_ptr += len;
2289 /* send everything we can NOW */
2290 len = write(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2291 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr);
2293 rtsp_c->packet_buffer_ptr += len;
2295 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2296 /* if we could not send all the data, we will
2297 send it later, so a new state is needed to
2298 "lock" the RTSP TCP connection */
2299 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2302 /* all data has been sent */
2303 av_freep(&c->packet_buffer);
2306 /* send RTP packet directly in UDP */
2308 url_write(c->rtp_handles[c->packet_stream_index],
2309 c->buffer_ptr, len);
2310 c->buffer_ptr += len;
2311 /* here we continue as we can send several packets per 10 ms slot */
2314 /* TCP data output */
2315 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
2317 if (errno != EAGAIN && errno != EINTR) {
2318 /* error : close connection */
2324 c->buffer_ptr += len;
2326 c->data_count += len;
2327 update_datarate(&c->datarate, c->data_count);
2329 c->stream->bytes_served += len;
2337 static int http_start_receive_data(HTTPContext *c)
2341 if (c->stream->feed_opened)
2344 /* Don't permit writing to this one */
2345 if (c->stream->readonly)
2349 fd = open(c->stream->feed_filename, O_RDWR);
2354 c->stream->feed_write_index = ffm_read_write_index(fd);
2355 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2356 lseek(fd, 0, SEEK_SET);
2358 /* init buffer input */
2359 c->buffer_ptr = c->buffer;
2360 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2361 c->stream->feed_opened = 1;
2365 static int http_receive_data(HTTPContext *c)
2369 if (c->buffer_end > c->buffer_ptr) {
2372 len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
2374 if (errno != EAGAIN && errno != EINTR) {
2375 /* error : close connection */
2378 } else if (len == 0) {
2379 /* end of connection : close it */
2382 c->buffer_ptr += len;
2383 c->data_count += len;
2384 update_datarate(&c->datarate, c->data_count);
2388 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2389 if (c->buffer[0] != 'f' ||
2390 c->buffer[1] != 'm') {
2391 http_log("Feed stream has become desynchronized -- disconnecting\n");
2396 if (c->buffer_ptr >= c->buffer_end) {
2397 FFStream *feed = c->stream;
2398 /* a packet has been received : write it in the store, except
2400 if (c->data_count > FFM_PACKET_SIZE) {
2402 // printf("writing pos=0x%Lx size=0x%Lx\n", feed->feed_write_index, feed->feed_size);
2403 /* XXX: use llseek or url_seek */
2404 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
2405 write(c->feed_fd, c->buffer, FFM_PACKET_SIZE);
2407 feed->feed_write_index += FFM_PACKET_SIZE;
2408 /* update file size */
2409 if (feed->feed_write_index > c->stream->feed_size)
2410 feed->feed_size = feed->feed_write_index;
2412 /* handle wrap around if max file size reached */
2413 if (feed->feed_write_index >= c->stream->feed_max_size)
2414 feed->feed_write_index = FFM_PACKET_SIZE;
2417 ffm_write_write_index(c->feed_fd, feed->feed_write_index);
2419 /* wake up any waiting connections */
2420 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2421 if (c1->state == HTTPSTATE_WAIT_FEED &&
2422 c1->stream->feed == c->stream->feed) {
2423 c1->state = HTTPSTATE_SEND_DATA;
2427 /* We have a header in our hands that contains useful data */
2429 AVInputFormat *fmt_in;
2430 ByteIOContext *pb = &s.pb;
2433 memset(&s, 0, sizeof(s));
2435 url_open_buf(pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
2436 pb->buf_end = c->buffer_end; /* ?? */
2437 pb->is_streamed = 1;
2439 /* use feed output format name to find corresponding input format */
2440 fmt_in = av_find_input_format(feed->fmt->name);
2444 if (fmt_in->priv_data_size > 0) {
2445 s.priv_data = av_mallocz(fmt_in->priv_data_size);
2451 if (fmt_in->read_header(&s, 0) < 0) {
2452 av_freep(&s.priv_data);
2456 /* Now we have the actual streams */
2457 if (s.nb_streams != feed->nb_streams) {
2458 av_freep(&s.priv_data);
2461 for (i = 0; i < s.nb_streams; i++) {
2462 memcpy(&feed->streams[i]->codec,
2463 &s.streams[i]->codec, sizeof(AVCodecContext));
2465 av_freep(&s.priv_data);
2467 c->buffer_ptr = c->buffer;
2472 c->stream->feed_opened = 0;
2477 /********************************************************************/
2480 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2487 switch(error_number) {
2488 #define DEF(n, c, s) case c: str = s; break;
2489 #include "rtspcodes.h"
2492 str = "Unknown Error";
2496 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2497 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2499 /* output GMT time */
2503 p = buf2 + strlen(p) - 1;
2506 url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
2509 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2511 rtsp_reply_header(c, error_number);
2512 url_fprintf(c->pb, "\r\n");
2515 static int rtsp_parse_request(HTTPContext *c)
2517 const char *p, *p1, *p2;
2524 RTSPHeader header1, *header = &header1;
2526 c->buffer_ptr[0] = '\0';
2529 get_word(cmd, sizeof(cmd), &p);
2530 get_word(url, sizeof(url), &p);
2531 get_word(protocol, sizeof(protocol), &p);
2533 pstrcpy(c->method, sizeof(c->method), cmd);
2534 pstrcpy(c->url, sizeof(c->url), url);
2535 pstrcpy(c->protocol, sizeof(c->protocol), protocol);
2538 if (url_open_dyn_buf(c->pb) < 0) {
2539 /* XXX: cannot do more */
2540 c->pb = NULL; /* safety */
2544 /* check version name */
2545 if (strcmp(protocol, "RTSP/1.0") != 0) {
2546 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2550 /* parse each header line */
2551 memset(header, 0, sizeof(RTSPHeader));
2552 /* skip to next line */
2553 while (*p != '\n' && *p != '\0')
2557 while (*p != '\0') {
2558 p1 = strchr(p, '\n');
2562 if (p2 > p && p2[-1] == '\r')
2564 /* skip empty line */
2568 if (len > sizeof(line) - 1)
2569 len = sizeof(line) - 1;
2570 memcpy(line, p, len);
2572 rtsp_parse_line(header, line);
2576 /* handle sequence number */
2577 c->seq = header->seq;
2579 if (!strcmp(cmd, "DESCRIBE")) {
2580 rtsp_cmd_describe(c, url);
2581 } else if (!strcmp(cmd, "OPTIONS")) {
2582 rtsp_cmd_options(c, url);
2583 } else if (!strcmp(cmd, "SETUP")) {
2584 rtsp_cmd_setup(c, url, header);
2585 } else if (!strcmp(cmd, "PLAY")) {
2586 rtsp_cmd_play(c, url, header);
2587 } else if (!strcmp(cmd, "PAUSE")) {
2588 rtsp_cmd_pause(c, url, header);
2589 } else if (!strcmp(cmd, "TEARDOWN")) {
2590 rtsp_cmd_teardown(c, url, header);
2592 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2595 len = url_close_dyn_buf(c->pb, &c->pb_buffer);
2596 c->pb = NULL; /* safety */
2598 /* XXX: cannot do more */
2601 c->buffer_ptr = c->pb_buffer;
2602 c->buffer_end = c->pb_buffer + len;
2603 c->state = RTSPSTATE_SEND_REPLY;
2607 /* XXX: move that to rtsp.c, but would need to replace FFStream by
2609 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
2610 struct in_addr my_ip)
2612 ByteIOContext pb1, *pb = &pb1;
2613 int i, payload_type, port, private_payload_type, j;
2614 const char *ipstr, *title, *mediatype;
2617 if (url_open_dyn_buf(pb) < 0)
2620 /* general media info */
2622 url_fprintf(pb, "v=0\n");
2623 ipstr = inet_ntoa(my_ip);
2624 url_fprintf(pb, "o=- 0 0 IN IP4 %s\n", ipstr);
2625 title = stream->title;
2626 if (title[0] == '\0')
2628 url_fprintf(pb, "s=%s\n", title);
2629 if (stream->comment[0] != '\0')
2630 url_fprintf(pb, "i=%s\n", stream->comment);
2631 if (stream->is_multicast) {
2632 url_fprintf(pb, "c=IN IP4 %s\n", inet_ntoa(stream->multicast_ip));
2634 /* for each stream, we output the necessary info */
2635 private_payload_type = RTP_PT_PRIVATE;
2636 for(i = 0; i < stream->nb_streams; i++) {
2637 st = stream->streams[i];
2638 if (st->codec.codec_id == CODEC_ID_MPEG2TS) {
2639 mediatype = "video";
2641 switch(st->codec.codec_type) {
2642 case CODEC_TYPE_AUDIO:
2643 mediatype = "audio";
2645 case CODEC_TYPE_VIDEO:
2646 mediatype = "video";
2649 mediatype = "application";
2653 /* NOTE: the port indication is not correct in case of
2654 unicast. It is not an issue because RTSP gives it */
2655 payload_type = rtp_get_payload_type(&st->codec);
2656 if (payload_type < 0)
2657 payload_type = private_payload_type++;
2658 if (stream->is_multicast) {
2659 port = stream->multicast_port + 2 * i;
2663 url_fprintf(pb, "m=%s %d RTP/AVP %d\n",
2664 mediatype, port, payload_type);
2665 if (payload_type >= RTP_PT_PRIVATE) {
2666 /* for private payload type, we need to give more info */
2667 switch(st->codec.codec_id) {
2668 case CODEC_ID_MPEG4:
2671 url_fprintf(pb, "a=rtpmap:%d MP4V-ES/%d\n",
2672 payload_type, 90000);
2673 /* we must also add the mpeg4 header */
2674 data = st->codec.extradata;
2676 url_fprintf(pb, "a=fmtp:%d config=", payload_type);
2677 for(j=0;j<st->codec.extradata_size;j++) {
2678 url_fprintf(pb, "%02x", data[j]);
2680 url_fprintf(pb, "\n");
2685 /* XXX: add other codecs ? */
2689 url_fprintf(pb, "a=control:streamid=%d\n", i);
2691 return url_close_dyn_buf(pb, pbuffer);
2693 url_close_dyn_buf(pb, pbuffer);
2698 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2700 // rtsp_reply_header(c, RTSP_STATUS_OK);
2701 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2702 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2703 url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2704 url_fprintf(c->pb, "\r\n");
2707 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2713 int content_length, len;
2714 struct sockaddr_in my_addr;
2716 /* find which url is asked */
2717 url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2722 for(stream = first_stream; stream != NULL; stream = stream->next) {
2723 if (!stream->is_feed && stream->fmt == &rtp_mux &&
2724 !strcmp(path, stream->filename)) {
2728 /* no stream found */
2729 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2733 /* prepare the media description in sdp format */
2735 /* get the host IP */
2736 len = sizeof(my_addr);
2737 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
2738 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
2739 if (content_length < 0) {
2740 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2743 rtsp_reply_header(c, RTSP_STATUS_OK);
2744 url_fprintf(c->pb, "Content-Type: application/sdp\r\n");
2745 url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);
2746 url_fprintf(c->pb, "\r\n");
2747 put_buffer(c->pb, content, content_length);
2750 static HTTPContext *find_rtp_session(const char *session_id)
2754 if (session_id[0] == '\0')
2757 for(c = first_http_ctx; c != NULL; c = c->next) {
2758 if (!strcmp(c->session_id, session_id))
2764 static RTSPTransportField *find_transport(RTSPHeader *h, enum RTSPProtocol protocol)
2766 RTSPTransportField *th;
2769 for(i=0;i<h->nb_transports;i++) {
2770 th = &h->transports[i];
2771 if (th->protocol == protocol)
2777 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
2781 int stream_index, port;
2786 RTSPTransportField *th;
2787 struct sockaddr_in dest_addr;
2788 RTSPActionServerSetup setup;
2790 /* find which url is asked */
2791 url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2796 /* now check each stream */
2797 for(stream = first_stream; stream != NULL; stream = stream->next) {
2798 if (!stream->is_feed && stream->fmt == &rtp_mux) {
2799 /* accept aggregate filenames only if single stream */
2800 if (!strcmp(path, stream->filename)) {
2801 if (stream->nb_streams != 1) {
2802 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
2809 for(stream_index = 0; stream_index < stream->nb_streams;
2811 snprintf(buf, sizeof(buf), "%s/streamid=%d",
2812 stream->filename, stream_index);
2813 if (!strcmp(path, buf))
2818 /* no stream found */
2819 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2823 /* generate session id if needed */
2824 if (h->session_id[0] == '\0') {
2825 snprintf(h->session_id, sizeof(h->session_id),
2826 "%08x%08x", (int)random(), (int)random());
2829 /* find rtp session, and create it if none found */
2830 rtp_c = find_rtp_session(h->session_id);
2832 /* always prefer UDP */
2833 th = find_transport(h, RTSP_PROTOCOL_RTP_UDP);
2835 th = find_transport(h, RTSP_PROTOCOL_RTP_TCP);
2837 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2842 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
2845 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
2849 /* open input stream */
2850 if (open_input_stream(rtp_c, "") < 0) {
2851 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2856 /* test if stream is OK (test needed because several SETUP needs
2857 to be done for a given file) */
2858 if (rtp_c->stream != stream) {
2859 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
2863 /* test if stream is already set up */
2864 if (rtp_c->rtp_ctx[stream_index]) {
2865 rtsp_reply_error(c, RTSP_STATUS_STATE);
2869 /* check transport */
2870 th = find_transport(h, rtp_c->rtp_protocol);
2871 if (!th || (th->protocol == RTSP_PROTOCOL_RTP_UDP &&
2872 th->client_port_min <= 0)) {
2873 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2877 /* setup default options */
2878 setup.transport_option[0] = '\0';
2879 dest_addr = rtp_c->from_addr;
2880 dest_addr.sin_port = htons(th->client_port_min);
2882 /* add transport option if needed */
2883 if (ff_rtsp_callback) {
2884 setup.ipaddr = ntohl(dest_addr.sin_addr.s_addr);
2885 if (ff_rtsp_callback(RTSP_ACTION_SERVER_SETUP, rtp_c->session_id,
2886 (char *)&setup, sizeof(setup),
2887 stream->rtsp_option) < 0) {
2888 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2891 dest_addr.sin_addr.s_addr = htonl(setup.ipaddr);
2895 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
2896 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2900 /* now everything is OK, so we can send the connection parameters */
2901 rtsp_reply_header(c, RTSP_STATUS_OK);
2903 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
2905 switch(rtp_c->rtp_protocol) {
2906 case RTSP_PROTOCOL_RTP_UDP:
2907 port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]);
2908 url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
2909 "client_port=%d-%d;server_port=%d-%d",
2910 th->client_port_min, th->client_port_min + 1,
2913 case RTSP_PROTOCOL_RTP_TCP:
2914 url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
2915 stream_index * 2, stream_index * 2 + 1);
2920 if (setup.transport_option[0] != '\0') {
2921 url_fprintf(c->pb, ";%s", setup.transport_option);
2923 url_fprintf(c->pb, "\r\n");
2926 url_fprintf(c->pb, "\r\n");
2930 /* find an rtp connection by using the session ID. Check consistency
2932 static HTTPContext *find_rtp_session_with_url(const char *url,
2933 const char *session_id)
2941 rtp_c = find_rtp_session(session_id);
2945 /* find which url is asked */
2946 url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2950 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
2951 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
2952 snprintf(buf, sizeof(buf), "%s/streamid=%d",
2953 rtp_c->stream->filename, s);
2954 if(!strncmp(path, buf, sizeof(buf))) {
2955 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
2962 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h)
2966 rtp_c = find_rtp_session_with_url(url, h->session_id);
2968 rtsp_reply_error(c, RTSP_STATUS_SESSION);
2972 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
2973 rtp_c->state != HTTPSTATE_WAIT_FEED &&
2974 rtp_c->state != HTTPSTATE_READY) {
2975 rtsp_reply_error(c, RTSP_STATUS_STATE);
2980 /* XXX: seek in stream */
2981 if (h->range_start != AV_NOPTS_VALUE) {
2982 printf("range_start=%0.3f\n", (double)h->range_start / AV_TIME_BASE);
2983 av_seek_frame(rtp_c->fmt_in, -1, h->range_start);
2987 rtp_c->state = HTTPSTATE_SEND_DATA;
2989 /* now everything is OK, so we can send the connection parameters */
2990 rtsp_reply_header(c, RTSP_STATUS_OK);
2992 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
2993 url_fprintf(c->pb, "\r\n");
2996 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h)
3000 rtp_c = find_rtp_session_with_url(url, h->session_id);
3002 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3006 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3007 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3008 rtsp_reply_error(c, RTSP_STATUS_STATE);
3012 rtp_c->state = HTTPSTATE_READY;
3013 rtp_c->first_pts = AV_NOPTS_VALUE;
3014 /* now everything is OK, so we can send the connection parameters */
3015 rtsp_reply_header(c, RTSP_STATUS_OK);
3017 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3018 url_fprintf(c->pb, "\r\n");
3021 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h)
3025 rtp_c = find_rtp_session_with_url(url, h->session_id);
3027 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3031 /* abort the session */
3032 close_connection(rtp_c);
3034 if (ff_rtsp_callback) {
3035 ff_rtsp_callback(RTSP_ACTION_SERVER_TEARDOWN, rtp_c->session_id,
3037 rtp_c->stream->rtsp_option);
3040 /* now everything is OK, so we can send the connection parameters */
3041 rtsp_reply_header(c, RTSP_STATUS_OK);
3043 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3044 url_fprintf(c->pb, "\r\n");
3048 /********************************************************************/
3051 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3052 FFStream *stream, const char *session_id,
3053 enum RTSPProtocol rtp_protocol)
3055 HTTPContext *c = NULL;
3056 const char *proto_str;
3058 /* XXX: should output a warning page when coming
3059 close to the connection limit */
3060 if (nb_connections >= nb_max_connections)
3063 /* add a new connection */
3064 c = av_mallocz(sizeof(HTTPContext));
3069 c->poll_entry = NULL;
3070 c->from_addr = *from_addr;
3071 c->buffer_size = IOBUFFER_INIT_SIZE;
3072 c->buffer = av_malloc(c->buffer_size);
3077 pstrcpy(c->session_id, sizeof(c->session_id), session_id);
3078 c->state = HTTPSTATE_READY;
3079 c->is_packetized = 1;
3080 c->rtp_protocol = rtp_protocol;
3082 /* protocol is shown in statistics */
3083 switch(c->rtp_protocol) {
3084 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
3085 proto_str = "MCAST";
3087 case RTSP_PROTOCOL_RTP_UDP:
3090 case RTSP_PROTOCOL_RTP_TCP:
3097 pstrcpy(c->protocol, sizeof(c->protocol), "RTP/");
3098 pstrcat(c->protocol, sizeof(c->protocol), proto_str);
3100 current_bandwidth += stream->bandwidth;
3102 c->next = first_http_ctx;
3114 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3115 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3117 static int rtp_new_av_stream(HTTPContext *c,
3118 int stream_index, struct sockaddr_in *dest_addr,
3119 HTTPContext *rtsp_c)
3121 AVFormatContext *ctx;
3127 int max_packet_size;
3129 /* now we can open the relevant output stream */
3130 ctx = av_alloc_format_context();
3133 ctx->oformat = &rtp_mux;
3135 st = av_mallocz(sizeof(AVStream));
3138 ctx->nb_streams = 1;
3139 ctx->streams[0] = st;
3141 if (!c->stream->feed ||
3142 c->stream->feed == c->stream) {
3143 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3146 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3150 /* build destination RTP address */
3151 ipaddr = inet_ntoa(dest_addr->sin_addr);
3153 switch(c->rtp_protocol) {
3154 case RTSP_PROTOCOL_RTP_UDP:
3155 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
3158 /* XXX: also pass as parameter to function ? */
3159 if (c->stream->is_multicast) {
3161 ttl = c->stream->multicast_ttl;
3164 snprintf(ctx->filename, sizeof(ctx->filename),
3165 "rtp://%s:%d?multicast=1&ttl=%d",
3166 ipaddr, ntohs(dest_addr->sin_port), ttl);
3168 snprintf(ctx->filename, sizeof(ctx->filename),
3169 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3172 if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
3174 c->rtp_handles[stream_index] = h;
3175 max_packet_size = url_get_max_packet_size(h);
3177 case RTSP_PROTOCOL_RTP_TCP:
3180 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3186 http_log("%s:%d - - [%s] \"PLAY %s/streamid=%d %s\"\n",
3187 ipaddr, ntohs(dest_addr->sin_port),
3189 c->stream->filename, stream_index, c->protocol);
3191 /* normally, no packets should be output here, but the packet size may be checked */
3192 if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
3193 /* XXX: close stream */
3196 av_set_parameters(ctx, NULL);
3197 if (av_write_header(ctx) < 0) {
3204 url_close_dyn_buf(&ctx->pb, &dummy_buf);
3207 c->rtp_ctx[stream_index] = ctx;
3211 /********************************************************************/
3212 /* ffserver initialization */
3214 static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
3218 fst = av_mallocz(sizeof(AVStream));
3221 fst->priv_data = av_mallocz(sizeof(FeedData));
3222 memcpy(&fst->codec, codec, sizeof(AVCodecContext));
3223 fst->codec.coded_frame = &dummy_frame;
3224 fst->index = stream->nb_streams;
3225 stream->streams[stream->nb_streams++] = fst;
3229 /* return the stream number in the feed */
3230 static int add_av_stream(FFStream *feed, AVStream *st)
3233 AVCodecContext *av, *av1;
3237 for(i=0;i<feed->nb_streams;i++) {
3238 st = feed->streams[i];
3240 if (av1->codec_id == av->codec_id &&
3241 av1->codec_type == av->codec_type &&
3242 av1->bit_rate == av->bit_rate) {
3244 switch(av->codec_type) {
3245 case CODEC_TYPE_AUDIO:
3246 if (av1->channels == av->channels &&
3247 av1->sample_rate == av->sample_rate)
3250 case CODEC_TYPE_VIDEO:
3251 if (av1->width == av->width &&
3252 av1->height == av->height &&
3253 av1->frame_rate == av->frame_rate &&
3254 av1->frame_rate_base == av->frame_rate_base &&
3255 av1->gop_size == av->gop_size)
3264 fst = add_av_stream1(feed, av);
3267 return feed->nb_streams - 1;
3272 static void remove_stream(FFStream *stream)
3276 while (*ps != NULL) {
3277 if (*ps == stream) {
3285 /* specific mpeg4 handling : we extract the raw parameters */
3286 static void extract_mpeg4_header(AVFormatContext *infile)
3288 int mpeg4_count, i, size;
3294 for(i=0;i<infile->nb_streams;i++) {
3295 st = infile->streams[i];
3296 if (st->codec.codec_id == CODEC_ID_MPEG4 &&
3297 st->codec.extradata_size == 0) {
3304 printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
3305 while (mpeg4_count > 0) {
3306 if (av_read_packet(infile, &pkt) < 0)
3308 st = infile->streams[pkt.stream_index];
3309 if (st->codec.codec_id == CODEC_ID_MPEG4 &&
3310 st->codec.extradata_size == 0) {
3311 av_freep(&st->codec.extradata);
3312 /* fill extradata with the header */
3313 /* XXX: we make hard suppositions here ! */
3315 while (p < pkt.data + pkt.size - 4) {
3316 /* stop when vop header is found */
3317 if (p[0] == 0x00 && p[1] == 0x00 &&
3318 p[2] == 0x01 && p[3] == 0xb6) {
3319 size = p - pkt.data;
3320 // av_hex_dump(pkt.data, size);
3321 st->codec.extradata = av_malloc(size);
3322 st->codec.extradata_size = size;
3323 memcpy(st->codec.extradata, pkt.data, size);
3330 av_free_packet(&pkt);
3334 /* compute the needed AVStream for each file */
3335 static void build_file_streams(void)
3337 FFStream *stream, *stream_next;
3338 AVFormatContext *infile;
3341 /* gather all streams */
3342 for(stream = first_stream; stream != NULL; stream = stream_next) {
3343 stream_next = stream->next;
3344 if (stream->stream_type == STREAM_TYPE_LIVE &&
3346 /* the stream comes from a file */
3347 /* try to open the file */
3349 stream->ap_in = av_mallocz(sizeof(AVFormatParameters));
3350 if (stream->fmt == &rtp_mux) {
3351 /* specific case : if transport stream output to RTP,
3352 we use a raw transport stream reader */
3353 stream->ap_in->mpeg2ts_raw = 1;
3354 stream->ap_in->mpeg2ts_compute_pcr = 1;
3357 if (av_open_input_file(&infile, stream->feed_filename,
3358 stream->ifmt, 0, stream->ap_in) < 0) {
3359 http_log("%s not found", stream->feed_filename);
3360 /* remove stream (no need to spend more time on it) */
3362 remove_stream(stream);
3364 /* find all the AVStreams inside and reference them in
3366 if (av_find_stream_info(infile) < 0) {
3367 http_log("Could not find codec parameters from '%s'",
3368 stream->feed_filename);
3369 av_close_input_file(infile);
3372 extract_mpeg4_header(infile);
3374 for(i=0;i<infile->nb_streams;i++) {
3375 add_av_stream1(stream, &infile->streams[i]->codec);
3377 av_close_input_file(infile);
3383 /* compute the needed AVStream for each feed */
3384 static void build_feed_streams(void)
3386 FFStream *stream, *feed;
3389 /* gather all streams */
3390 for(stream = first_stream; stream != NULL; stream = stream->next) {
3391 feed = stream->feed;
3393 if (!stream->is_feed) {
3394 /* we handle a stream coming from a feed */
3395 for(i=0;i<stream->nb_streams;i++) {
3396 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3402 /* gather all streams */
3403 for(stream = first_stream; stream != NULL; stream = stream->next) {
3404 feed = stream->feed;
3406 if (stream->is_feed) {
3407 for(i=0;i<stream->nb_streams;i++) {
3408 stream->feed_streams[i] = i;
3414 /* create feed files if needed */
3415 for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
3418 if (url_exist(feed->feed_filename)) {
3419 /* See if it matches */
3423 if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) {
3424 /* Now see if it matches */
3425 if (s->nb_streams == feed->nb_streams) {
3427 for(i=0;i<s->nb_streams;i++) {
3429 sf = feed->streams[i];
3432 if (sf->index != ss->index ||
3434 printf("Index & Id do not match for stream %d (%s)\n",
3435 i, feed->feed_filename);
3438 AVCodecContext *ccf, *ccs;
3442 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3444 if (CHECK_CODEC(codec) || CHECK_CODEC(codec_type)) {
3445 printf("Codecs do not match for stream %d\n", i);
3447 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3448 printf("Codec bitrates do not match for stream %d\n", i);
3450 } else if (ccf->codec_type == CODEC_TYPE_VIDEO) {
3451 if (CHECK_CODEC(frame_rate) ||
3452 CHECK_CODEC(frame_rate_base) ||
3453 CHECK_CODEC(width) ||
3454 CHECK_CODEC(height)) {
3455 printf("Codec width, height and framerate do not match for stream %d\n", i);
3458 } else if (ccf->codec_type == CODEC_TYPE_AUDIO) {
3459 if (CHECK_CODEC(sample_rate) ||
3460 CHECK_CODEC(channels) ||
3461 CHECK_CODEC(frame_size)) {
3462 printf("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3466 printf("Unknown codec type\n");
3475 printf("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3476 feed->feed_filename, s->nb_streams, feed->nb_streams);
3479 av_close_input_file(s);
3481 printf("Deleting feed file '%s' as it appears to be corrupt\n",
3482 feed->feed_filename);
3485 if (feed->readonly) {
3486 printf("Unable to delete feed file '%s' as it is marked readonly\n",
3487 feed->feed_filename);
3490 unlink(feed->feed_filename);
3493 if (!url_exist(feed->feed_filename)) {
3494 AVFormatContext s1, *s = &s1;
3496 if (feed->readonly) {
3497 printf("Unable to create feed file '%s' as it is marked readonly\n",
3498 feed->feed_filename);
3502 /* only write the header of the ffm file */
3503 if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
3504 fprintf(stderr, "Could not open output feed file '%s'\n",
3505 feed->feed_filename);
3508 s->oformat = feed->fmt;
3509 s->nb_streams = feed->nb_streams;
3510 for(i=0;i<s->nb_streams;i++) {
3512 st = feed->streams[i];
3515 av_set_parameters(s, NULL);
3517 /* XXX: need better api */
3518 av_freep(&s->priv_data);
3521 /* get feed size and write index */
3522 fd = open(feed->feed_filename, O_RDONLY);
3524 fprintf(stderr, "Could not open output feed file '%s'\n",
3525 feed->feed_filename);
3529 feed->feed_write_index = ffm_read_write_index(fd);
3530 feed->feed_size = lseek(fd, 0, SEEK_END);
3531 /* ensure that we do not wrap before the end of file */
3532 if (feed->feed_max_size < feed->feed_size)
3533 feed->feed_max_size = feed->feed_size;
3539 /* compute the bandwidth used by each stream */
3540 static void compute_bandwidth(void)
3545 for(stream = first_stream; stream != NULL; stream = stream->next) {
3547 for(i=0;i<stream->nb_streams;i++) {
3548 AVStream *st = stream->streams[i];
3549 switch(st->codec.codec_type) {
3550 case CODEC_TYPE_AUDIO:
3551 case CODEC_TYPE_VIDEO:
3552 bandwidth += st->codec.bit_rate;
3558 stream->bandwidth = (bandwidth + 999) / 1000;
3562 static void get_arg(char *buf, int buf_size, const char **pp)
3569 while (isspace(*p)) p++;
3572 if (*p == '\"' || *p == '\'')
3584 if ((q - buf) < buf_size - 1)
3589 if (quote && *p == quote)
3594 /* add a codec and set the default parameters */
3595 static void add_codec(FFStream *stream, AVCodecContext *av)
3599 /* compute default parameters */
3600 switch(av->codec_type) {
3601 case CODEC_TYPE_AUDIO:
3602 if (av->bit_rate == 0)
3603 av->bit_rate = 64000;
3604 if (av->sample_rate == 0)
3605 av->sample_rate = 22050;
3606 if (av->channels == 0)
3609 case CODEC_TYPE_VIDEO:
3610 if (av->bit_rate == 0)
3611 av->bit_rate = 64000;
3612 if (av->frame_rate == 0){
3614 av->frame_rate_base = 1;
3616 if (av->width == 0 || av->height == 0) {
3620 /* Bitrate tolerance is less for streaming */
3621 if (av->bit_rate_tolerance == 0)
3622 av->bit_rate_tolerance = av->bit_rate / 4;
3627 if (av->max_qdiff == 0)
3629 av->qcompress = 0.5;
3633 av->rc_eq = "tex^qComp";
3634 if (!av->i_quant_factor)
3635 av->i_quant_factor = -0.8;
3636 if (!av->b_quant_factor)
3637 av->b_quant_factor = 1.25;
3638 if (!av->b_quant_offset)
3639 av->b_quant_offset = 1.25;
3640 if (!av->rc_max_rate)
3641 av->rc_max_rate = av->bit_rate * 2;
3648 st = av_mallocz(sizeof(AVStream));
3651 stream->streams[stream->nb_streams++] = st;
3652 memcpy(&st->codec, av, sizeof(AVCodecContext));
3655 static int opt_audio_codec(const char *arg)
3661 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
3666 return CODEC_ID_NONE;
3672 static int opt_video_codec(const char *arg)
3678 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
3683 return CODEC_ID_NONE;
3689 /* simplistic plugin support */
3691 #ifdef CONFIG_HAVE_DLOPEN
3692 void load_module(const char *filename)
3695 void (*init_func)(void);
3696 dll = dlopen(filename, RTLD_NOW);
3698 fprintf(stderr, "Could not load module '%s' - %s\n",
3699 filename, dlerror());
3703 init_func = dlsym(dll, "ffserver_module_init");
3706 "%s: init function 'ffserver_module_init()' not found\n",
3715 static int parse_ffconfig(const char *filename)
3722 int val, errors, line_num;
3723 FFStream **last_stream, *stream, *redirect;
3724 FFStream **last_feed, *feed;
3725 AVCodecContext audio_enc, video_enc;
3726 int audio_id, video_id;
3728 f = fopen(filename, "r");
3736 first_stream = NULL;
3737 last_stream = &first_stream;
3739 last_feed = &first_feed;
3743 audio_id = CODEC_ID_NONE;
3744 video_id = CODEC_ID_NONE;
3746 if (fgets(line, sizeof(line), f) == NULL)
3752 if (*p == '\0' || *p == '#')
3755 get_arg(cmd, sizeof(cmd), &p);
3757 if (!strcasecmp(cmd, "Port")) {
3758 get_arg(arg, sizeof(arg), &p);
3759 my_http_addr.sin_port = htons (atoi(arg));
3760 } else if (!strcasecmp(cmd, "BindAddress")) {
3761 get_arg(arg, sizeof(arg), &p);
3762 if (!inet_aton(arg, &my_http_addr.sin_addr)) {
3763 fprintf(stderr, "%s:%d: Invalid IP address: %s\n",
3764 filename, line_num, arg);
3767 } else if (!strcasecmp(cmd, "NoDaemon")) {
3768 ffserver_daemon = 0;
3769 } else if (!strcasecmp(cmd, "RTSPPort")) {
3770 get_arg(arg, sizeof(arg), &p);
3771 my_rtsp_addr.sin_port = htons (atoi(arg));
3772 } else if (!strcasecmp(cmd, "RTSPBindAddress")) {
3773 get_arg(arg, sizeof(arg), &p);
3774 if (!inet_aton(arg, &my_rtsp_addr.sin_addr)) {
3775 fprintf(stderr, "%s:%d: Invalid IP address: %s\n",
3776 filename, line_num, arg);
3779 } else if (!strcasecmp(cmd, "MaxClients")) {
3780 get_arg(arg, sizeof(arg), &p);
3782 if (val < 1 || val > HTTP_MAX_CONNECTIONS) {
3783 fprintf(stderr, "%s:%d: Invalid MaxClients: %s\n",
3784 filename, line_num, arg);
3787 nb_max_connections = val;
3789 } else if (!strcasecmp(cmd, "MaxBandwidth")) {
3790 get_arg(arg, sizeof(arg), &p);
3792 if (val < 10 || val > 100000) {
3793 fprintf(stderr, "%s:%d: Invalid MaxBandwidth: %s\n",
3794 filename, line_num, arg);
3797 max_bandwidth = val;
3799 } else if (!strcasecmp(cmd, "CustomLog")) {
3800 get_arg(logfilename, sizeof(logfilename), &p);
3801 } else if (!strcasecmp(cmd, "<Feed")) {
3802 /*********************************************/
3803 /* Feed related options */
3805 if (stream || feed) {
3806 fprintf(stderr, "%s:%d: Already in a tag\n",
3807 filename, line_num);
3809 feed = av_mallocz(sizeof(FFStream));
3810 /* add in stream list */
3811 *last_stream = feed;
3812 last_stream = &feed->next;
3813 /* add in feed list */
3815 last_feed = &feed->next_feed;
3817 get_arg(feed->filename, sizeof(feed->filename), &p);
3818 q = strrchr(feed->filename, '>');
3821 feed->fmt = guess_format("ffm", NULL, NULL);
3822 /* defaut feed file */
3823 snprintf(feed->feed_filename, sizeof(feed->feed_filename),
3824 "/tmp/%s.ffm", feed->filename);
3825 feed->feed_max_size = 5 * 1024 * 1024;
3827 feed->feed = feed; /* self feeding :-) */
3829 } else if (!strcasecmp(cmd, "Launch")) {
3833 feed->child_argv = (char **) av_mallocz(64 * sizeof(char *));
3835 feed->child_argv[0] = av_malloc(7);
3836 strcpy(feed->child_argv[0], "ffmpeg");
3838 for (i = 1; i < 62; i++) {
3841 get_arg(argbuf, sizeof(argbuf), &p);
3845 feed->child_argv[i] = av_malloc(strlen(argbuf) + 1);
3846 strcpy(feed->child_argv[i], argbuf);
3849 feed->child_argv[i] = av_malloc(30 + strlen(feed->filename));
3851 snprintf(feed->child_argv[i], 256, "http://127.0.0.1:%d/%s",
3852 ntohs(my_http_addr.sin_port), feed->filename);
3854 } else if (!strcasecmp(cmd, "ReadOnlyFile")) {
3856 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
3858 } else if (stream) {
3859 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
3861 } else if (!strcasecmp(cmd, "File")) {
3863 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
3864 } else if (stream) {
3865 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
3867 } else if (!strcasecmp(cmd, "FileMaxSize")) {
3872 get_arg(arg, sizeof(arg), &p);
3874 fsize = strtod(p1, (char **)&p1);
3875 switch(toupper(*p1)) {
3880 fsize *= 1024 * 1024;
3883 fsize *= 1024 * 1024 * 1024;
3886 feed->feed_max_size = (int64_t)fsize;
3888 } else if (!strcasecmp(cmd, "</Feed>")) {
3890 fprintf(stderr, "%s:%d: No corresponding <Feed> for </Feed>\n",
3891 filename, line_num);
3895 /* Make sure that we start out clean */
3896 if (unlink(feed->feed_filename) < 0
3897 && errno != ENOENT) {
3898 fprintf(stderr, "%s:%d: Unable to clean old feed file '%s': %s\n",
3899 filename, line_num, feed->feed_filename, strerror(errno));
3905 } else if (!strcasecmp(cmd, "<Stream")) {
3906 /*********************************************/
3907 /* Stream related options */
3909 if (stream || feed) {
3910 fprintf(stderr, "%s:%d: Already in a tag\n",
3911 filename, line_num);
3913 stream = av_mallocz(sizeof(FFStream));
3914 *last_stream = stream;
3915 last_stream = &stream->next;
3917 get_arg(stream->filename, sizeof(stream->filename), &p);
3918 q = strrchr(stream->filename, '>');
3921 stream->fmt = guess_stream_format(NULL, stream->filename, NULL);
3922 memset(&audio_enc, 0, sizeof(AVCodecContext));
3923 memset(&video_enc, 0, sizeof(AVCodecContext));
3924 audio_id = CODEC_ID_NONE;
3925 video_id = CODEC_ID_NONE;
3927 audio_id = stream->fmt->audio_codec;
3928 video_id = stream->fmt->video_codec;
3931 } else if (!strcasecmp(cmd, "Feed")) {
3932 get_arg(arg, sizeof(arg), &p);
3937 while (sfeed != NULL) {
3938 if (!strcmp(sfeed->filename, arg))
3940 sfeed = sfeed->next_feed;
3943 fprintf(stderr, "%s:%d: feed '%s' not defined\n",
3944 filename, line_num, arg);
3946 stream->feed = sfeed;
3949 } else if (!strcasecmp(cmd, "Format")) {
3950 get_arg(arg, sizeof(arg), &p);
3951 if (!strcmp(arg, "status")) {
3952 stream->stream_type = STREAM_TYPE_STATUS;
3955 stream->stream_type = STREAM_TYPE_LIVE;
3956 /* jpeg cannot be used here, so use single frame jpeg */
3957 if (!strcmp(arg, "jpeg"))
3958 strcpy(arg, "singlejpeg");
3959 stream->fmt = guess_stream_format(arg, NULL, NULL);
3961 fprintf(stderr, "%s:%d: Unknown Format: %s\n",
3962 filename, line_num, arg);
3967 audio_id = stream->fmt->audio_codec;
3968 video_id = stream->fmt->video_codec;
3970 } else if (!strcasecmp(cmd, "InputFormat")) {
3971 stream->ifmt = av_find_input_format(arg);
3972 if (!stream->ifmt) {
3973 fprintf(stderr, "%s:%d: Unknown input format: %s\n",
3974 filename, line_num, arg);
3976 } else if (!strcasecmp(cmd, "FaviconURL")) {
3977 if (stream && stream->stream_type == STREAM_TYPE_STATUS) {
3978 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
3980 fprintf(stderr, "%s:%d: FaviconURL only permitted for status streams\n",
3981 filename, line_num);
3984 } else if (!strcasecmp(cmd, "Author")) {
3986 get_arg(stream->author, sizeof(stream->author), &p);
3988 } else if (!strcasecmp(cmd, "Comment")) {
3990 get_arg(stream->comment, sizeof(stream->comment), &p);
3992 } else if (!strcasecmp(cmd, "Copyright")) {
3994 get_arg(stream->copyright, sizeof(stream->copyright), &p);
3996 } else if (!strcasecmp(cmd, "Title")) {
3998 get_arg(stream->title, sizeof(stream->title), &p);
4000 } else if (!strcasecmp(cmd, "Preroll")) {
4001 get_arg(arg, sizeof(arg), &p);
4003 stream->prebuffer = atof(arg) * 1000;
4005 } else if (!strcasecmp(cmd, "StartSendOnKey")) {
4007 stream->send_on_key = 1;
4009 } else if (!strcasecmp(cmd, "AudioCodec")) {
4010 get_arg(arg, sizeof(arg), &p);
4011 audio_id = opt_audio_codec(arg);
4012 if (audio_id == CODEC_ID_NONE) {
4013 fprintf(stderr, "%s:%d: Unknown AudioCodec: %s\n",
4014 filename, line_num, arg);
4017 } else if (!strcasecmp(cmd, "VideoCodec")) {
4018 get_arg(arg, sizeof(arg), &p);
4019 video_id = opt_video_codec(arg);
4020 if (video_id == CODEC_ID_NONE) {
4021 fprintf(stderr, "%s:%d: Unknown VideoCodec: %s\n",
4022 filename, line_num, arg);
4025 } else if (!strcasecmp(cmd, "MaxTime")) {
4026 get_arg(arg, sizeof(arg), &p);
4028 stream->max_time = atof(arg) * 1000;
4030 } else if (!strcasecmp(cmd, "AudioBitRate")) {
4031 get_arg(arg, sizeof(arg), &p);
4033 audio_enc.bit_rate = atoi(arg) * 1000;
4035 } else if (!strcasecmp(cmd, "AudioChannels")) {
4036 get_arg(arg, sizeof(arg), &p);
4038 audio_enc.channels = atoi(arg);
4040 } else if (!strcasecmp(cmd, "AudioSampleRate")) {
4041 get_arg(arg, sizeof(arg), &p);
4043 audio_enc.sample_rate = atoi(arg);
4045 } else if (!strcasecmp(cmd, "AudioQuality")) {
4046 get_arg(arg, sizeof(arg), &p);
4048 // audio_enc.quality = atof(arg) * 1000;
4050 } else if (!strcasecmp(cmd, "VideoBitRateRange")) {
4052 int minrate, maxrate;
4054 get_arg(arg, sizeof(arg), &p);
4056 if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {
4057 video_enc.rc_min_rate = minrate * 1000;
4058 video_enc.rc_max_rate = maxrate * 1000;
4060 fprintf(stderr, "%s:%d: Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n",
4061 filename, line_num, arg);
4065 } else if (!strcasecmp(cmd, "VideoBufferSize")) {
4067 get_arg(arg, sizeof(arg), &p);
4068 video_enc.rc_buffer_size = atoi(arg) * 1024;
4070 } else if (!strcasecmp(cmd, "VideoBitRateTolerance")) {
4072 get_arg(arg, sizeof(arg), &p);
4073 video_enc.bit_rate_tolerance = atoi(arg) * 1000;
4075 } else if (!strcasecmp(cmd, "VideoBitRate")) {
4076 get_arg(arg, sizeof(arg), &p);
4078 video_enc.bit_rate = atoi(arg) * 1000;
4080 } else if (!strcasecmp(cmd, "VideoSize")) {
4081 get_arg(arg, sizeof(arg), &p);
4083 parse_image_size(&video_enc.width, &video_enc.height, arg);
4084 if ((video_enc.width % 16) != 0 ||
4085 (video_enc.height % 16) != 0) {
4086 fprintf(stderr, "%s:%d: Image size must be a multiple of 16\n",
4087 filename, line_num);
4091 } else if (!strcasecmp(cmd, "VideoFrameRate")) {
4092 get_arg(arg, sizeof(arg), &p);
4094 video_enc.frame_rate_base= DEFAULT_FRAME_RATE_BASE;
4095 video_enc.frame_rate = (int)(strtod(arg, NULL) * video_enc.frame_rate_base);
4097 } else if (!strcasecmp(cmd, "VideoGopSize")) {
4098 get_arg(arg, sizeof(arg), &p);
4100 video_enc.gop_size = atoi(arg);
4102 } else if (!strcasecmp(cmd, "VideoIntraOnly")) {
4104 video_enc.gop_size = 1;
4106 } else if (!strcasecmp(cmd, "VideoHighQuality")) {
4108 video_enc.mb_decision = FF_MB_DECISION_BITS;
4110 } else if (!strcasecmp(cmd, "Video4MotionVector")) {
4112 video_enc.mb_decision = FF_MB_DECISION_BITS; //FIXME remove
4113 video_enc.flags |= CODEC_FLAG_4MV;
4115 } else if (!strcasecmp(cmd, "VideoQDiff")) {
4116 get_arg(arg, sizeof(arg), &p);
4118 video_enc.max_qdiff = atoi(arg);
4119 if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) {
4120 fprintf(stderr, "%s:%d: VideoQDiff out of range\n",
4121 filename, line_num);
4125 } else if (!strcasecmp(cmd, "VideoQMax")) {
4126 get_arg(arg, sizeof(arg), &p);
4128 video_enc.qmax = atoi(arg);
4129 if (video_enc.qmax < 1 || video_enc.qmax > 31) {
4130 fprintf(stderr, "%s:%d: VideoQMax out of range\n",
4131 filename, line_num);
4135 } else if (!strcasecmp(cmd, "VideoQMin")) {
4136 get_arg(arg, sizeof(arg), &p);
4138 video_enc.qmin = atoi(arg);
4139 if (video_enc.qmin < 1 || video_enc.qmin > 31) {
4140 fprintf(stderr, "%s:%d: VideoQMin out of range\n",
4141 filename, line_num);
4145 } else if (!strcasecmp(cmd, "LumaElim")) {
4146 get_arg(arg, sizeof(arg), &p);
4148 video_enc.luma_elim_threshold = atoi(arg);
4150 } else if (!strcasecmp(cmd, "ChromaElim")) {
4151 get_arg(arg, sizeof(arg), &p);
4153 video_enc.chroma_elim_threshold = atoi(arg);
4155 } else if (!strcasecmp(cmd, "LumiMask")) {
4156 get_arg(arg, sizeof(arg), &p);
4158 video_enc.lumi_masking = atof(arg);
4160 } else if (!strcasecmp(cmd, "DarkMask")) {
4161 get_arg(arg, sizeof(arg), &p);
4163 video_enc.dark_masking = atof(arg);
4165 } else if (!strcasecmp(cmd, "NoVideo")) {
4166 video_id = CODEC_ID_NONE;
4167 } else if (!strcasecmp(cmd, "NoAudio")) {
4168 audio_id = CODEC_ID_NONE;
4169 } else if (!strcasecmp(cmd, "ACL")) {
4173 get_arg(arg, sizeof(arg), &p);
4174 if (strcasecmp(arg, "allow") == 0) {
4175 acl.action = IP_ALLOW;
4176 } else if (strcasecmp(arg, "deny") == 0) {
4177 acl.action = IP_DENY;
4179 fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
4180 filename, line_num, arg);
4184 get_arg(arg, sizeof(arg), &p);
4186 he = gethostbyname(arg);
4188 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4189 filename, line_num, arg);
4192 /* Only take the first */
4193 acl.first.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr);
4194 acl.last = acl.first;
4197 get_arg(arg, sizeof(arg), &p);
4200 he = gethostbyname(arg);
4202 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4203 filename, line_num, arg);
4206 /* Only take the first */
4207 acl.last.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr);
4212 IPAddressACL *nacl = (IPAddressACL *) av_mallocz(sizeof(*nacl));
4213 IPAddressACL **naclp = 0;
4219 naclp = &stream->acl;
4223 fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n",
4224 filename, line_num);
4230 naclp = &(*naclp)->next;
4235 } else if (!strcasecmp(cmd, "RTSPOption")) {
4236 get_arg(arg, sizeof(arg), &p);
4238 av_freep(&stream->rtsp_option);
4239 /* XXX: av_strdup ? */
4240 stream->rtsp_option = av_malloc(strlen(arg) + 1);
4241 if (stream->rtsp_option) {
4242 strcpy(stream->rtsp_option, arg);
4245 } else if (!strcasecmp(cmd, "MulticastAddress")) {
4246 get_arg(arg, sizeof(arg), &p);
4248 if (!inet_aton(arg, &stream->multicast_ip)) {
4249 fprintf(stderr, "%s:%d: Invalid IP address: %s\n",
4250 filename, line_num, arg);
4253 stream->is_multicast = 1;
4254 stream->loop = 1; /* default is looping */
4256 } else if (!strcasecmp(cmd, "MulticastPort")) {
4257 get_arg(arg, sizeof(arg), &p);
4259 stream->multicast_port = atoi(arg);
4261 } else if (!strcasecmp(cmd, "MulticastTTL")) {
4262 get_arg(arg, sizeof(arg), &p);
4264 stream->multicast_ttl = atoi(arg);
4266 } else if (!strcasecmp(cmd, "NoLoop")) {
4270 } else if (!strcasecmp(cmd, "</Stream>")) {
4272 fprintf(stderr, "%s:%d: No corresponding <Stream> for </Stream>\n",
4273 filename, line_num);
4276 if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) {
4277 if (audio_id != CODEC_ID_NONE) {
4278 audio_enc.codec_type = CODEC_TYPE_AUDIO;
4279 audio_enc.codec_id = audio_id;
4280 add_codec(stream, &audio_enc);
4282 if (video_id != CODEC_ID_NONE) {
4283 video_enc.codec_type = CODEC_TYPE_VIDEO;
4284 video_enc.codec_id = video_id;
4285 add_codec(stream, &video_enc);
4289 } else if (!strcasecmp(cmd, "<Redirect")) {
4290 /*********************************************/
4292 if (stream || feed || redirect) {
4293 fprintf(stderr, "%s:%d: Already in a tag\n",
4294 filename, line_num);
4297 redirect = av_mallocz(sizeof(FFStream));
4298 *last_stream = redirect;
4299 last_stream = &redirect->next;
4301 get_arg(redirect->filename, sizeof(redirect->filename), &p);
4302 q = strrchr(redirect->filename, '>');
4305 redirect->stream_type = STREAM_TYPE_REDIRECT;
4307 } else if (!strcasecmp(cmd, "URL")) {
4309 get_arg(redirect->feed_filename, sizeof(redirect->feed_filename), &p);
4311 } else if (!strcasecmp(cmd, "</Redirect>")) {
4313 fprintf(stderr, "%s:%d: No corresponding <Redirect> for </Redirect>\n",
4314 filename, line_num);
4317 if (!redirect->feed_filename[0]) {
4318 fprintf(stderr, "%s:%d: No URL found for <Redirect>\n",
4319 filename, line_num);
4323 } else if (!strcasecmp(cmd, "LoadModule")) {
4324 get_arg(arg, sizeof(arg), &p);
4325 #ifdef CONFIG_HAVE_DLOPEN
4328 fprintf(stderr, "%s:%d: Module support not compiled into this version: '%s'\n",
4329 filename, line_num, arg);
4333 fprintf(stderr, "%s:%d: Incorrect keyword: '%s'\n",
4334 filename, line_num, cmd);
4348 static void write_packet(FFCodec *ffenc,
4349 uint8_t *buf, int size)
4352 AVCodecContext *enc = &ffenc->enc;
4354 mk_header(&hdr, enc, size);
4355 wptr = http_fifo.wptr;
4356 fifo_write(&http_fifo, (uint8_t *)&hdr, sizeof(hdr), &wptr);
4357 fifo_write(&http_fifo, buf, size, &wptr);
4358 /* atomic modification of wptr */
4359 http_fifo.wptr = wptr;
4360 ffenc->data_count += size;
4361 ffenc->avg_frame_size = ffenc->avg_frame_size * AVG_COEF + size * (1.0 - AVG_COEF);
4365 static void show_banner(void)
4367 printf("ffserver version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
4370 static void show_help(void)
4373 printf("usage: ffserver [-L] [-h] [-f configfile]\n"
4374 "Hyper fast multi format Audio/Video streaming server\n"
4376 "-L : print the LICENSE\n"
4378 "-f configfile : use configfile instead of /etc/ffserver.conf\n"
4382 static void show_license(void)
4386 "This library is free software; you can redistribute it and/or\n"
4387 "modify it under the terms of the GNU Lesser General Public\n"
4388 "License as published by the Free Software Foundation; either\n"
4389 "version 2 of the License, or (at your option) any later version.\n"
4391 "This library is distributed in the hope that it will be useful,\n"
4392 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4393 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
4394 "Lesser General Public License for more details.\n"
4396 "You should have received a copy of the GNU Lesser General Public\n"
4397 "License along with this library; if not, write to the Free Software\n"
4398 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
4402 static void handle_child_exit(int sig)
4407 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
4410 for (feed = first_feed; feed; feed = feed->next) {
4411 if (feed->pid == pid) {
4412 int uptime = time(0) - feed->pid_start;
4415 fprintf(stderr, "%s: Pid %d exited with status %d after %d seconds\n", feed->filename, pid, status, uptime);
4418 /* Turn off any more restarts */
4419 feed->child_argv = 0;
4425 need_to_start_children = 1;
4428 int main(int argc, char **argv)
4430 const char *config_filename;
4432 struct sigaction sigact;
4436 config_filename = "/etc/ffserver.conf";
4438 my_program_name = argv[0];
4439 my_program_dir = getcwd(0, 0);
4440 ffserver_daemon = 1;
4443 c = getopt(argc, argv, "ndLh?f:");
4459 ffserver_daemon = 0;
4462 config_filename = optarg;
4469 putenv("http_proxy"); /* Kill the http_proxy */
4471 srandom(gettime_ms() + (getpid() << 16));
4473 /* address on which the server will handle HTTP connections */
4474 my_http_addr.sin_family = AF_INET;
4475 my_http_addr.sin_port = htons (8080);
4476 my_http_addr.sin_addr.s_addr = htonl (INADDR_ANY);
4478 /* address on which the server will handle RTSP connections */
4479 my_rtsp_addr.sin_family = AF_INET;
4480 my_rtsp_addr.sin_port = htons (5454);
4481 my_rtsp_addr.sin_addr.s_addr = htonl (INADDR_ANY);
4483 nb_max_connections = 5;
4484 max_bandwidth = 1000;
4485 first_stream = NULL;
4486 logfilename[0] = '\0';
4488 memset(&sigact, 0, sizeof(sigact));
4489 sigact.sa_handler = handle_child_exit;
4490 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
4491 sigaction(SIGCHLD, &sigact, 0);
4493 if (parse_ffconfig(config_filename) < 0) {
4494 fprintf(stderr, "Incorrect config file - exiting.\n");
4498 build_file_streams();
4500 build_feed_streams();
4502 compute_bandwidth();
4504 /* put the process in background and detach it from its TTY */
4505 if (ffserver_daemon) {
4512 } else if (pid > 0) {
4520 open("/dev/null", O_RDWR);
4521 if (strcmp(logfilename, "-") != 0) {
4531 signal(SIGPIPE, SIG_IGN);
4533 /* open log file if needed */
4534 if (logfilename[0] != '\0') {
4535 if (!strcmp(logfilename, "-"))
4538 logfile = fopen(logfilename, "w");
4541 if (http_server() < 0) {
4542 fprintf(stderr, "Could not start server\n");