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);
605 cur_time = gettime_ms();
607 if (need_to_start_children) {
608 need_to_start_children = 0;
609 start_children(first_feed);
612 /* now handle the events */
613 for(c = first_http_ctx; c != NULL; c = c_next) {
615 if (handle_connection(c) < 0) {
616 /* close and free the connection */
622 poll_entry = poll_table;
623 /* new HTTP connection request ? */
624 if (poll_entry->revents & POLLIN) {
625 new_connection(server_fd, 0);
628 /* new RTSP connection request ? */
629 if (poll_entry->revents & POLLIN) {
630 new_connection(rtsp_server_fd, 1);
635 /* start waiting for a new HTTP/RTSP request */
636 static void start_wait_request(HTTPContext *c, int is_rtsp)
638 c->buffer_ptr = c->buffer;
639 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
642 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
643 c->state = RTSPSTATE_WAIT_REQUEST;
645 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
646 c->state = HTTPSTATE_WAIT_REQUEST;
650 static void new_connection(int server_fd, int is_rtsp)
652 struct sockaddr_in from_addr;
654 HTTPContext *c = NULL;
656 len = sizeof(from_addr);
657 fd = accept(server_fd, (struct sockaddr *)&from_addr,
661 fcntl(fd, F_SETFL, O_NONBLOCK);
663 /* XXX: should output a warning page when coming
664 close to the connection limit */
665 if (nb_connections >= nb_max_connections)
668 /* add a new connection */
669 c = av_mallocz(sizeof(HTTPContext));
674 c->poll_entry = NULL;
675 c->from_addr = from_addr;
676 c->buffer_size = IOBUFFER_INIT_SIZE;
677 c->buffer = av_malloc(c->buffer_size);
681 c->next = first_http_ctx;
685 start_wait_request(c, is_rtsp);
697 static void close_connection(HTTPContext *c)
699 HTTPContext **cp, *c1;
701 AVFormatContext *ctx;
705 /* remove connection from list */
706 cp = &first_http_ctx;
707 while ((*cp) != NULL) {
716 /* remove references, if any (XXX: do it faster) */
717 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
722 /* remove connection associated resources */
726 /* close each frame parser */
727 for(i=0;i<c->fmt_in->nb_streams;i++) {
728 st = c->fmt_in->streams[i];
729 if (st->codec.codec) {
730 avcodec_close(&st->codec);
733 av_close_input_file(c->fmt_in);
736 /* free RTP output streams if any */
739 nb_streams = c->stream->nb_streams;
741 for(i=0;i<nb_streams;i++) {
744 av_write_trailer(ctx);
747 h = c->rtp_handles[i];
755 if (!c->last_packet_sent) {
758 if (url_open_dyn_buf(&ctx->pb) >= 0) {
759 av_write_trailer(ctx);
760 url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
765 for(i=0; i<ctx->nb_streams; i++)
766 av_free(ctx->streams[i]) ;
769 current_bandwidth -= c->stream->bandwidth;
770 av_freep(&c->pb_buffer);
771 av_freep(&c->packet_buffer);
777 static int handle_connection(HTTPContext *c)
782 case HTTPSTATE_WAIT_REQUEST:
783 case RTSPSTATE_WAIT_REQUEST:
785 if ((c->timeout - cur_time) < 0)
787 if (c->poll_entry->revents & (POLLERR | POLLHUP))
790 /* no need to read if no events */
791 if (!(c->poll_entry->revents & POLLIN))
795 len = read(c->fd, c->buffer_ptr, 1);
797 if (errno != EAGAIN && errno != EINTR)
799 } else if (len == 0) {
802 /* search for end of request. */
804 c->buffer_ptr += len;
806 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
807 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
808 /* request found : parse it and reply */
809 if (c->state == HTTPSTATE_WAIT_REQUEST) {
810 ret = http_parse_request(c);
812 ret = rtsp_parse_request(c);
816 } else if (ptr >= c->buffer_end) {
817 /* request too long: cannot do anything */
819 } else goto read_loop;
823 case HTTPSTATE_SEND_HEADER:
824 if (c->poll_entry->revents & (POLLERR | POLLHUP))
827 /* no need to write if no events */
828 if (!(c->poll_entry->revents & POLLOUT))
830 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
832 if (errno != EAGAIN && errno != EINTR) {
833 /* error : close connection */
834 av_freep(&c->pb_buffer);
838 c->buffer_ptr += len;
840 c->stream->bytes_served += len;
841 c->data_count += len;
842 if (c->buffer_ptr >= c->buffer_end) {
843 av_freep(&c->pb_buffer);
848 /* all the buffer was sent : synchronize to the incoming stream */
849 c->state = HTTPSTATE_SEND_DATA_HEADER;
850 c->buffer_ptr = c->buffer_end = c->buffer;
855 case HTTPSTATE_SEND_DATA:
856 case HTTPSTATE_SEND_DATA_HEADER:
857 case HTTPSTATE_SEND_DATA_TRAILER:
858 /* for packetized output, we consider we can always write (the
859 input streams sets the speed). It may be better to verify
860 that we do not rely too much on the kernel queues */
861 if (!c->is_packetized) {
862 if (c->poll_entry->revents & (POLLERR | POLLHUP))
865 /* no need to read if no events */
866 if (!(c->poll_entry->revents & POLLOUT))
869 if (http_send_data(c) < 0)
872 case HTTPSTATE_RECEIVE_DATA:
873 /* no need to read if no events */
874 if (c->poll_entry->revents & (POLLERR | POLLHUP))
876 if (!(c->poll_entry->revents & POLLIN))
878 if (http_receive_data(c) < 0)
881 case HTTPSTATE_WAIT_FEED:
882 /* no need to read if no events */
883 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
886 /* nothing to do, we'll be waken up by incoming feed packets */
889 case RTSPSTATE_SEND_REPLY:
890 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
891 av_freep(&c->pb_buffer);
894 /* no need to write if no events */
895 if (!(c->poll_entry->revents & POLLOUT))
897 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
899 if (errno != EAGAIN && errno != EINTR) {
900 /* error : close connection */
901 av_freep(&c->pb_buffer);
905 c->buffer_ptr += len;
906 c->data_count += len;
907 if (c->buffer_ptr >= c->buffer_end) {
908 /* all the buffer was sent : wait for a new request */
909 av_freep(&c->pb_buffer);
910 start_wait_request(c, 1);
914 case RTSPSTATE_SEND_PACKET:
915 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
916 av_freep(&c->packet_buffer);
919 /* no need to write if no events */
920 if (!(c->poll_entry->revents & POLLOUT))
922 len = write(c->fd, c->packet_buffer_ptr,
923 c->packet_buffer_end - c->packet_buffer_ptr);
925 if (errno != EAGAIN && errno != EINTR) {
926 /* error : close connection */
927 av_freep(&c->packet_buffer);
931 c->packet_buffer_ptr += len;
932 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
933 /* all the buffer was sent : wait for a new request */
934 av_freep(&c->packet_buffer);
935 c->state = RTSPSTATE_WAIT_REQUEST;
939 case HTTPSTATE_READY:
948 static int extract_rates(char *rates, int ratelen, const char *request)
952 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
953 if (strncasecmp(p, "Pragma:", 7) == 0) {
954 const char *q = p + 7;
956 while (*q && *q != '\n' && isspace(*q))
959 if (strncasecmp(q, "stream-switch-entry=", 20) == 0) {
965 memset(rates, 0xff, ratelen);
968 while (*q && *q != '\n' && *q != ':')
971 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2) {
975 if (stream_no < ratelen && stream_no >= 0) {
976 rates[stream_no] = rate_no;
979 while (*q && *q != '\n' && !isspace(*q))
996 static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
999 int best_bitrate = 100000000;
1002 for (i = 0; i < feed->nb_streams; i++) {
1003 AVCodecContext *feed_codec = &feed->streams[i]->codec;
1005 if (feed_codec->codec_id != codec->codec_id ||
1006 feed_codec->sample_rate != codec->sample_rate ||
1007 feed_codec->width != codec->width ||
1008 feed_codec->height != codec->height) {
1012 /* Potential stream */
1014 /* We want the fastest stream less than bit_rate, or the slowest
1015 * faster than bit_rate
1018 if (feed_codec->bit_rate <= bit_rate) {
1019 if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
1020 best_bitrate = feed_codec->bit_rate;
1024 if (feed_codec->bit_rate < best_bitrate) {
1025 best_bitrate = feed_codec->bit_rate;
1034 static int modify_current_stream(HTTPContext *c, char *rates)
1037 FFStream *req = c->stream;
1038 int action_required = 0;
1040 /* Not much we can do for a feed */
1044 for (i = 0; i < req->nb_streams; i++) {
1045 AVCodecContext *codec = &req->streams[i]->codec;
1049 c->switch_feed_streams[i] = req->feed_streams[i];
1052 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1055 /* Wants off or slow */
1056 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1058 /* This doesn't work well when it turns off the only stream! */
1059 c->switch_feed_streams[i] = -2;
1060 c->feed_streams[i] = -2;
1065 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1066 action_required = 1;
1069 return action_required;
1073 static void do_switch_stream(HTTPContext *c, int i)
1075 if (c->switch_feed_streams[i] >= 0) {
1077 c->feed_streams[i] = c->switch_feed_streams[i];
1080 /* Now update the stream */
1082 c->switch_feed_streams[i] = -1;
1085 /* XXX: factorize in utils.c ? */
1086 /* XXX: take care with different space meaning */
1087 static void skip_spaces(const char **pp)
1091 while (*p == ' ' || *p == '\t')
1096 static void get_word(char *buf, int buf_size, const char **pp)
1104 while (!isspace(*p) && *p != '\0') {
1105 if ((q - buf) < buf_size - 1)
1114 static int validate_acl(FFStream *stream, HTTPContext *c)
1116 enum IPAddressAction last_action = IP_DENY;
1118 struct in_addr *src = &c->from_addr.sin_addr;
1119 unsigned long src_addr = ntohl(src->s_addr);
1121 for (acl = stream->acl; acl; acl = acl->next) {
1122 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr) {
1123 return (acl->action == IP_ALLOW) ? 1 : 0;
1125 last_action = acl->action;
1128 /* Nothing matched, so return not the last action */
1129 return (last_action == IP_DENY) ? 1 : 0;
1132 /* compute the real filename of a file by matching it without its
1133 extensions to all the stream filenames */
1134 static void compute_real_filename(char *filename, int max_size)
1141 /* compute filename by matching without the file extensions */
1142 pstrcpy(file1, sizeof(file1), filename);
1143 p = strrchr(file1, '.');
1146 for(stream = first_stream; stream != NULL; stream = stream->next) {
1147 pstrcpy(file2, sizeof(file2), stream->filename);
1148 p = strrchr(file2, '.');
1151 if (!strcmp(file1, file2)) {
1152 pstrcpy(filename, max_size, stream->filename);
1167 /* parse http request and prepare header */
1168 static int http_parse_request(HTTPContext *c)
1172 enum RedirType redir_type;
1174 char info[1024], *filename;
1178 const char *mime_type;
1182 char *useragent = 0;
1185 get_word(cmd, sizeof(cmd), (const char **)&p);
1186 pstrcpy(c->method, sizeof(c->method), cmd);
1188 if (!strcmp(cmd, "GET"))
1190 else if (!strcmp(cmd, "POST"))
1195 get_word(url, sizeof(url), (const char **)&p);
1196 pstrcpy(c->url, sizeof(c->url), url);
1198 get_word(protocol, sizeof(protocol), (const char **)&p);
1199 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1202 pstrcpy(c->protocol, sizeof(c->protocol), protocol);
1204 /* find the filename and the optional info string in the request */
1211 pstrcpy(info, sizeof(info), p);
1217 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1218 if (strncasecmp(p, "User-Agent:", 11) == 0) {
1220 if (*useragent && *useragent != '\n' && isspace(*useragent))
1224 p = strchr(p, '\n');
1231 redir_type = REDIR_NONE;
1232 if (match_ext(filename, "asx")) {
1233 redir_type = REDIR_ASX;
1234 filename[strlen(filename)-1] = 'f';
1235 } else if (match_ext(filename, "asf") &&
1236 (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1237 /* if this isn't WMP or lookalike, return the redirector file */
1238 redir_type = REDIR_ASF;
1239 } else if (match_ext(filename, "rpm,ram")) {
1240 redir_type = REDIR_RAM;
1241 strcpy(filename + strlen(filename)-2, "m");
1242 } else if (match_ext(filename, "rtsp")) {
1243 redir_type = REDIR_RTSP;
1244 compute_real_filename(filename, sizeof(url) - 1);
1245 } else if (match_ext(filename, "sdp")) {
1246 redir_type = REDIR_SDP;
1247 compute_real_filename(filename, sizeof(url) - 1);
1250 stream = first_stream;
1251 while (stream != NULL) {
1252 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1254 stream = stream->next;
1256 if (stream == NULL) {
1257 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1262 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1263 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1265 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1266 c->http_error = 301;
1268 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 301 Moved\r\n");
1269 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Location: %s\r\n", stream->feed_filename);
1270 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: text/html\r\n");
1271 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1272 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<html><head><title>Moved</title></head><body>\r\n");
1273 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "You should be <a href=\"%s\">redirected</a>.\r\n", stream->feed_filename);
1274 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</body></html>\r\n");
1276 /* prepare output buffer */
1277 c->buffer_ptr = c->buffer;
1279 c->state = HTTPSTATE_SEND_HEADER;
1283 /* If this is WMP, get the rate information */
1284 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1285 if (modify_current_stream(c, ratebuf)) {
1286 for (i = 0; i < sizeof(c->feed_streams) / sizeof(c->feed_streams[0]); i++) {
1287 if (c->switch_feed_streams[i] >= 0)
1288 do_switch_stream(c, i);
1293 if (post == 0 && stream->stream_type == STREAM_TYPE_LIVE) {
1294 current_bandwidth += stream->bandwidth;
1297 if (post == 0 && max_bandwidth < current_bandwidth) {
1298 c->http_error = 200;
1300 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 Server too busy\r\n");
1301 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: text/html\r\n");
1302 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1303 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<html><head><title>Too busy</title></head><body>\r\n");
1304 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");
1305 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",
1306 current_bandwidth, max_bandwidth);
1307 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</body></html>\r\n");
1309 /* prepare output buffer */
1310 c->buffer_ptr = c->buffer;
1312 c->state = HTTPSTATE_SEND_HEADER;
1316 if (redir_type != REDIR_NONE) {
1319 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1320 if (strncasecmp(p, "Host:", 5) == 0) {
1324 p = strchr(p, '\n');
1335 while (isspace(*hostinfo))
1338 eoh = strchr(hostinfo, '\n');
1340 if (eoh[-1] == '\r')
1343 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1344 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1345 hostbuf[eoh - hostinfo] = 0;
1347 c->http_error = 200;
1349 switch(redir_type) {
1351 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 ASX Follows\r\n");
1352 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: video/x-ms-asf\r\n");
1353 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1354 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<ASX Version=\"3\">\r\n");
1355 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<!-- Autogenerated by ffserver -->\r\n");
1356 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n",
1357 hostbuf, filename, info);
1358 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</ASX>\r\n");
1361 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 RAM Follows\r\n");
1362 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: audio/x-pn-realaudio\r\n");
1363 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1364 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "# Autogenerated by ffserver\r\n");
1365 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "http://%s/%s%s\r\n",
1366 hostbuf, filename, info);
1369 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 ASF Redirect follows\r\n");
1370 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: video/x-ms-asf\r\n");
1371 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1372 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "[Reference]\r\n");
1373 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Ref1=http://%s/%s%s\r\n",
1374 hostbuf, filename, info);
1378 char hostname[256], *p;
1379 /* extract only hostname */
1380 pstrcpy(hostname, sizeof(hostname), hostbuf);
1381 p = strrchr(hostname, ':');
1384 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 RTSP Redirect follows\r\n");
1385 /* XXX: incorrect mime type ? */
1386 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: application/x-rtsp\r\n");
1387 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1388 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "rtsp://%s:%d/%s\r\n",
1389 hostname, ntohs(my_rtsp_addr.sin_port),
1396 int sdp_data_size, len;
1397 struct sockaddr_in my_addr;
1399 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
1400 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: application/sdp\r\n");
1401 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1403 len = sizeof(my_addr);
1404 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
1406 /* XXX: should use a dynamic buffer */
1407 sdp_data_size = prepare_sdp_description(stream,
1410 if (sdp_data_size > 0) {
1411 memcpy(q, sdp_data, sdp_data_size);
1423 /* prepare output buffer */
1424 c->buffer_ptr = c->buffer;
1426 c->state = HTTPSTATE_SEND_HEADER;
1432 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1436 stream->conns_served++;
1438 /* XXX: add there authenticate and IP match */
1441 /* if post, it means a feed is being sent */
1442 if (!stream->is_feed) {
1443 /* However it might be a status report from WMP! Lets log the data
1444 * as it might come in handy one day
1449 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1450 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1454 if (strncasecmp(p, "Pragma: client-id=", 18) == 0) {
1455 client_id = strtol(p + 18, 0, 10);
1457 p = strchr(p, '\n');
1465 char *eol = strchr(logline, '\n');
1470 if (eol[-1] == '\r')
1472 http_log("%.*s\n", (int) (eol - logline), logline);
1473 c->suppress_log = 1;
1478 http_log("\nGot request:\n%s\n", c->buffer);
1481 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1484 /* Now we have to find the client_id */
1485 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1486 if (wmpc->wmp_client_id == client_id)
1491 if (modify_current_stream(wmpc, ratebuf)) {
1492 wmpc->switch_pending = 1;
1497 snprintf(msg, sizeof(msg), "POST command not handled");
1501 if (http_start_receive_data(c) < 0) {
1502 snprintf(msg, sizeof(msg), "could not open feed");
1506 c->state = HTTPSTATE_RECEIVE_DATA;
1511 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0) {
1512 http_log("\nGot request:\n%s\n", c->buffer);
1516 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1519 /* open input stream */
1520 if (open_input_stream(c, info) < 0) {
1521 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1525 /* prepare http header */
1527 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
1528 mime_type = c->stream->fmt->mime_type;
1530 mime_type = "application/x-octet_stream";
1531 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Pragma: no-cache\r\n");
1533 /* for asf, we need extra headers */
1534 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1535 /* Need to allocate a client id */
1537 c->wmp_client_id = random() & 0x7fffffff;
1539 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);
1541 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-Type: %s\r\n", mime_type);
1542 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1544 /* prepare output buffer */
1546 c->buffer_ptr = c->buffer;
1548 c->state = HTTPSTATE_SEND_HEADER;
1551 c->http_error = 404;
1553 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 404 Not Found\r\n");
1554 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: %s\r\n", "text/html");
1555 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n");
1556 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<HTML>\n");
1557 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<HEAD><TITLE>404 Not Found</TITLE></HEAD>\n");
1558 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<BODY>%s</BODY>\n", msg);
1559 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</HTML>\n");
1561 /* prepare output buffer */
1562 c->buffer_ptr = c->buffer;
1564 c->state = HTTPSTATE_SEND_HEADER;
1568 c->http_error = 200; /* horrible : we use this value to avoid
1569 going to the send data state */
1570 c->state = HTTPSTATE_SEND_HEADER;
1574 static void fmt_bytecount(ByteIOContext *pb, int64_t count)
1576 static const char *suffix = " kMGTP";
1579 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++) {
1582 url_fprintf(pb, "%lld%c", count, *s);
1585 static void compute_stats(HTTPContext *c)
1592 ByteIOContext pb1, *pb = &pb1;
1594 if (url_open_dyn_buf(pb) < 0) {
1595 /* XXX: return an error ? */
1596 c->buffer_ptr = c->buffer;
1597 c->buffer_end = c->buffer;
1601 url_fprintf(pb, "HTTP/1.0 200 OK\r\n");
1602 url_fprintf(pb, "Content-type: %s\r\n", "text/html");
1603 url_fprintf(pb, "Pragma: no-cache\r\n");
1604 url_fprintf(pb, "\r\n");
1606 url_fprintf(pb, "<HEAD><TITLE>FFServer Status</TITLE>\n");
1607 if (c->stream->feed_filename) {
1608 url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
1610 url_fprintf(pb, "</HEAD>\n<BODY>");
1611 url_fprintf(pb, "<H1>FFServer Status</H1>\n");
1613 url_fprintf(pb, "<H2>Available Streams</H2>\n");
1614 url_fprintf(pb, "<TABLE cellspacing=0 cellpadding=4>\n");
1615 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");
1616 stream = first_stream;
1617 while (stream != NULL) {
1618 char sfilename[1024];
1621 if (stream->feed != stream) {
1622 pstrcpy(sfilename, sizeof(sfilename) - 10, stream->filename);
1623 eosf = sfilename + strlen(sfilename);
1624 if (eosf - sfilename >= 4) {
1625 if (strcmp(eosf - 4, ".asf") == 0) {
1626 strcpy(eosf - 4, ".asx");
1627 } else if (strcmp(eosf - 3, ".rm") == 0) {
1628 strcpy(eosf - 3, ".ram");
1629 } else if (stream->fmt == &rtp_mux) {
1630 /* generate a sample RTSP director if
1631 unicast. Generate an SDP redirector if
1633 eosf = strrchr(sfilename, '.');
1635 eosf = sfilename + strlen(sfilename);
1636 if (stream->is_multicast)
1637 strcpy(eosf, ".sdp");
1639 strcpy(eosf, ".rtsp");
1643 url_fprintf(pb, "<TR><TD><A HREF=\"/%s\">%s</A> ",
1644 sfilename, stream->filename);
1645 url_fprintf(pb, "<td align=right> %d <td align=right> ",
1646 stream->conns_served);
1647 fmt_bytecount(pb, stream->bytes_served);
1648 switch(stream->stream_type) {
1649 case STREAM_TYPE_LIVE:
1651 int audio_bit_rate = 0;
1652 int video_bit_rate = 0;
1653 const char *audio_codec_name = "";
1654 const char *video_codec_name = "";
1655 const char *audio_codec_name_extra = "";
1656 const char *video_codec_name_extra = "";
1658 for(i=0;i<stream->nb_streams;i++) {
1659 AVStream *st = stream->streams[i];
1660 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
1661 switch(st->codec.codec_type) {
1662 case CODEC_TYPE_AUDIO:
1663 audio_bit_rate += st->codec.bit_rate;
1665 if (*audio_codec_name)
1666 audio_codec_name_extra = "...";
1667 audio_codec_name = codec->name;
1670 case CODEC_TYPE_VIDEO:
1671 video_bit_rate += st->codec.bit_rate;
1673 if (*video_codec_name)
1674 video_codec_name_extra = "...";
1675 video_codec_name = codec->name;
1678 case CODEC_TYPE_DATA:
1679 video_bit_rate += st->codec.bit_rate;
1685 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",
1688 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
1689 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
1691 url_fprintf(pb, "<TD>%s", stream->feed->filename);
1693 url_fprintf(pb, "<TD>%s", stream->feed_filename);
1695 url_fprintf(pb, "\n");
1699 url_fprintf(pb, "<TD align=center> - <TD align=right> - <TD align=right> - <td><td align=right> - <TD>\n");
1703 stream = stream->next;
1705 url_fprintf(pb, "</TABLE>\n");
1707 stream = first_stream;
1708 while (stream != NULL) {
1709 if (stream->feed == stream) {
1710 url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
1712 url_fprintf(pb, "Running as pid %d.\n", stream->pid);
1714 #if defined(linux) && !defined(CONFIG_NOCUTILS)
1719 /* This is somewhat linux specific I guess */
1720 snprintf(ps_cmd, sizeof(ps_cmd),
1721 "ps -o \"%%cpu,cputime\" --no-headers %d",
1724 pid_stat = popen(ps_cmd, "r");
1729 if (fscanf(pid_stat, "%10s %64s", cpuperc,
1731 url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
1739 url_fprintf(pb, "<p>");
1741 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");
1743 for (i = 0; i < stream->nb_streams; i++) {
1744 AVStream *st = stream->streams[i];
1745 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
1746 const char *type = "unknown";
1747 char parameters[64];
1751 switch(st->codec.codec_type) {
1752 case CODEC_TYPE_AUDIO:
1755 case CODEC_TYPE_VIDEO:
1757 snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec.width, st->codec.height,
1758 st->codec.qmin, st->codec.qmax, st->codec.frame_rate / st->codec.frame_rate_base);
1763 url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
1764 i, type, st->codec.bit_rate/1000, codec ? codec->name : "", parameters);
1766 url_fprintf(pb, "</table>\n");
1769 stream = stream->next;
1775 AVCodecContext *enc;
1779 stream = first_feed;
1780 while (stream != NULL) {
1781 url_fprintf(pb, "<H1>Feed '%s'</H1>\n", stream->filename);
1782 url_fprintf(pb, "<TABLE>\n");
1783 url_fprintf(pb, "<TR><TD>Parameters<TD>Frame count<TD>Size<TD>Avg bitrate (kbits/s)\n");
1784 for(i=0;i<stream->nb_streams;i++) {
1785 AVStream *st = stream->streams[i];
1786 FeedData *fdata = st->priv_data;
1789 avcodec_string(buf, sizeof(buf), enc);
1790 avg = fdata->avg_frame_size * (float)enc->rate * 8.0;
1791 if (enc->codec->type == CODEC_TYPE_AUDIO && enc->frame_size > 0)
1792 avg /= enc->frame_size;
1793 url_fprintf(pb, "<TR><TD>%s <TD> %d <TD> %Ld <TD> %0.1f\n",
1794 buf, enc->frame_number, fdata->data_count, avg / 1000.0);
1796 url_fprintf(pb, "</TABLE>\n");
1797 stream = stream->next_feed;
1802 /* connection status */
1803 url_fprintf(pb, "<H2>Connection Status</H2>\n");
1805 url_fprintf(pb, "Number of connections: %d / %d<BR>\n",
1806 nb_connections, nb_max_connections);
1808 url_fprintf(pb, "Bandwidth in use: %dk / %dk<BR>\n",
1809 current_bandwidth, max_bandwidth);
1811 url_fprintf(pb, "<TABLE>\n");
1812 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");
1813 c1 = first_http_ctx;
1815 while (c1 != NULL) {
1821 for (j = 0; j < c1->stream->nb_streams; j++) {
1822 if (!c1->stream->feed) {
1823 bitrate += c1->stream->streams[j]->codec.bit_rate;
1825 if (c1->feed_streams[j] >= 0) {
1826 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec.bit_rate;
1833 p = inet_ntoa(c1->from_addr.sin_addr);
1834 url_fprintf(pb, "<TR><TD><B>%d</B><TD>%s%s<TD>%s<TD>%s<TD>%s<td align=right>",
1836 c1->stream ? c1->stream->filename : "",
1837 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
1840 http_state[c1->state]);
1841 fmt_bytecount(pb, bitrate);
1842 url_fprintf(pb, "<td align=right>");
1843 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
1844 url_fprintf(pb, "<td align=right>");
1845 fmt_bytecount(pb, c1->data_count);
1846 url_fprintf(pb, "\n");
1849 url_fprintf(pb, "</TABLE>\n");
1854 url_fprintf(pb, "<HR size=1 noshade>Generated at %s", p);
1855 url_fprintf(pb, "</BODY>\n</HTML>\n");
1857 len = url_close_dyn_buf(pb, &c->pb_buffer);
1858 c->buffer_ptr = c->pb_buffer;
1859 c->buffer_end = c->pb_buffer + len;
1862 /* check if the parser needs to be opened for stream i */
1863 static void open_parser(AVFormatContext *s, int i)
1865 AVStream *st = s->streams[i];
1868 if (!st->codec.codec) {
1869 codec = avcodec_find_decoder(st->codec.codec_id);
1870 if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) {
1871 st->codec.parse_only = 1;
1872 if (avcodec_open(&st->codec, codec) < 0) {
1873 st->codec.parse_only = 0;
1879 static int open_input_stream(HTTPContext *c, const char *info)
1882 char input_filename[1024];
1887 /* find file name */
1888 if (c->stream->feed) {
1889 strcpy(input_filename, c->stream->feed->feed_filename);
1890 buf_size = FFM_PACKET_SIZE;
1891 /* compute position (absolute time) */
1892 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1893 stream_pos = parse_date(buf, 0);
1894 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
1895 int prebuffer = strtol(buf, 0, 10);
1896 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
1898 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
1901 strcpy(input_filename, c->stream->feed_filename);
1903 /* compute position (relative time) */
1904 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1905 stream_pos = parse_date(buf, 1);
1910 if (input_filename[0] == '\0')
1914 { time_t when = stream_pos / 1000000;
1915 http_log("Stream pos = %lld, time=%s", stream_pos, ctime(&when));
1920 if (av_open_input_file(&s, input_filename, c->stream->ifmt,
1921 buf_size, c->stream->ap_in) < 0) {
1922 http_log("%s not found", input_filename);
1927 /* open each parser */
1928 for(i=0;i<s->nb_streams;i++)
1931 /* choose stream as clock source (we favorize video stream if
1932 present) for packet sending */
1933 c->pts_stream_index = 0;
1934 for(i=0;i<c->stream->nb_streams;i++) {
1935 if (c->pts_stream_index == 0 &&
1936 c->stream->streams[i]->codec.codec_type == CODEC_TYPE_VIDEO) {
1937 c->pts_stream_index = i;
1942 if (c->fmt_in->iformat->read_seek) {
1943 c->fmt_in->iformat->read_seek(c->fmt_in, stream_pos);
1946 /* set the start time (needed for maxtime and RTP packet timing) */
1947 c->start_time = cur_time;
1948 c->first_pts = AV_NOPTS_VALUE;
1952 /* return the server clock (in us) */
1953 static int64_t get_server_clock(HTTPContext *c)
1955 /* compute current pts value from system time */
1956 return (int64_t)(cur_time - c->start_time) * 1000LL;
1959 /* return the estimated time at which the current packet must be sent
1961 static int64_t get_packet_send_clock(HTTPContext *c)
1963 int bytes_left, bytes_sent, frame_bytes;
1965 frame_bytes = c->cur_frame_bytes;
1966 if (frame_bytes <= 0) {
1969 bytes_left = c->buffer_end - c->buffer_ptr;
1970 bytes_sent = frame_bytes - bytes_left;
1971 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
1976 static int http_prepare_data(HTTPContext *c)
1979 AVFormatContext *ctx;
1981 av_freep(&c->pb_buffer);
1983 case HTTPSTATE_SEND_DATA_HEADER:
1984 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
1985 pstrcpy(c->fmt_ctx.author, sizeof(c->fmt_ctx.author),
1987 pstrcpy(c->fmt_ctx.comment, sizeof(c->fmt_ctx.comment),
1988 c->stream->comment);
1989 pstrcpy(c->fmt_ctx.copyright, sizeof(c->fmt_ctx.copyright),
1990 c->stream->copyright);
1991 pstrcpy(c->fmt_ctx.title, sizeof(c->fmt_ctx.title),
1994 /* open output stream by using specified codecs */
1995 c->fmt_ctx.oformat = c->stream->fmt;
1996 c->fmt_ctx.nb_streams = c->stream->nb_streams;
1997 for(i=0;i<c->fmt_ctx.nb_streams;i++) {
1999 st = av_mallocz(sizeof(AVStream));
2000 c->fmt_ctx.streams[i] = st;
2001 /* if file or feed, then just take streams from FFStream struct */
2002 if (!c->stream->feed ||
2003 c->stream->feed == c->stream)
2004 memcpy(st, c->stream->streams[i], sizeof(AVStream));
2006 memcpy(st, c->stream->feed->streams[c->stream->feed_streams[i]],
2008 st->codec.frame_number = 0; /* XXX: should be done in
2009 AVStream, not in codec */
2010 /* I'm pretty sure that this is not correct...
2011 * However, without it, we crash
2013 st->codec.coded_frame = &dummy_frame;
2015 c->got_key_frame = 0;
2017 /* prepare header and save header data in a stream */
2018 if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2019 /* XXX: potential leak */
2022 c->fmt_ctx.pb.is_streamed = 1;
2024 av_set_parameters(&c->fmt_ctx, NULL);
2025 av_write_header(&c->fmt_ctx);
2027 len = url_close_dyn_buf(&c->fmt_ctx.pb, &c->pb_buffer);
2028 c->buffer_ptr = c->pb_buffer;
2029 c->buffer_end = c->pb_buffer + len;
2031 c->state = HTTPSTATE_SEND_DATA;
2032 c->last_packet_sent = 0;
2034 case HTTPSTATE_SEND_DATA:
2035 /* find a new packet */
2039 /* read a packet from the input stream */
2040 if (c->stream->feed) {
2041 ffm_set_write_index(c->fmt_in,
2042 c->stream->feed->feed_write_index,
2043 c->stream->feed->feed_size);
2046 if (c->stream->max_time &&
2047 c->stream->max_time + c->start_time - cur_time < 0) {
2048 /* We have timed out */
2049 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2052 if (av_read_frame(c->fmt_in, &pkt) < 0) {
2053 if (c->stream->feed && c->stream->feed->feed_opened) {
2054 /* if coming from feed, it means we reached the end of the
2055 ffm file, so must wait for more data */
2056 c->state = HTTPSTATE_WAIT_FEED;
2057 return 1; /* state changed */
2059 if (c->stream->loop) {
2060 av_close_input_file(c->fmt_in);
2062 if (open_input_stream(c, "") < 0)
2067 /* must send trailer now because eof or error */
2068 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2072 /* update first pts if needed */
2073 if (c->first_pts == AV_NOPTS_VALUE) {
2074 c->first_pts = pkt.dts;
2075 c->start_time = cur_time;
2077 /* send it to the appropriate stream */
2078 if (c->stream->feed) {
2079 /* if coming from a feed, select the right stream */
2080 if (c->switch_pending) {
2081 c->switch_pending = 0;
2082 for(i=0;i<c->stream->nb_streams;i++) {
2083 if (c->switch_feed_streams[i] == pkt.stream_index) {
2084 if (pkt.flags & PKT_FLAG_KEY) {
2085 do_switch_stream(c, i);
2088 if (c->switch_feed_streams[i] >= 0) {
2089 c->switch_pending = 1;
2093 for(i=0;i<c->stream->nb_streams;i++) {
2094 if (c->feed_streams[i] == pkt.stream_index) {
2095 pkt.stream_index = i;
2096 if (pkt.flags & PKT_FLAG_KEY) {
2097 c->got_key_frame |= 1 << i;
2099 /* See if we have all the key frames, then
2100 * we start to send. This logic is not quite
2101 * right, but it works for the case of a
2102 * single video stream with one or more
2103 * audio streams (for which every frame is
2104 * typically a key frame).
2106 if (!c->stream->send_on_key ||
2107 ((c->got_key_frame + 1) >> c->stream->nb_streams)) {
2113 AVCodecContext *codec;
2116 /* specific handling for RTP: we use several
2117 output stream (one for each RTP
2118 connection). XXX: need more abstract handling */
2119 if (c->is_packetized) {
2121 /* compute send time and duration */
2122 st = c->fmt_in->streams[pkt.stream_index];
2123 c->cur_pts = pkt.dts;
2124 if (st->start_time != AV_NOPTS_VALUE)
2125 c->cur_pts -= st->start_time;
2126 c->cur_frame_duration = pkt.duration;
2128 printf("index=%d pts=%0.3f duration=%0.6f\n",
2130 (double)c->cur_pts /
2132 (double)c->cur_frame_duration /
2135 /* find RTP context */
2136 c->packet_stream_index = pkt.stream_index;
2137 ctx = c->rtp_ctx[c->packet_stream_index];
2139 av_free_packet(&pkt);
2142 codec = &ctx->streams[0]->codec;
2143 /* only one stream per RTP connection */
2144 pkt.stream_index = 0;
2148 codec = &ctx->streams[pkt.stream_index]->codec;
2151 codec->coded_frame->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);
2152 if (c->is_packetized) {
2153 int max_packet_size;
2154 if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP)
2155 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2157 max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]);
2158 ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size);
2160 ret = url_open_dyn_buf(&ctx->pb);
2163 /* XXX: potential leak */
2166 if (av_write_frame(ctx, pkt.stream_index, pkt.data, pkt.size)) {
2167 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2170 len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
2171 c->cur_frame_bytes = len;
2172 c->buffer_ptr = c->pb_buffer;
2173 c->buffer_end = c->pb_buffer + len;
2175 codec->frame_number++;
2179 av_free_packet(&pkt);
2185 case HTTPSTATE_SEND_DATA_TRAILER:
2186 /* last packet test ? */
2187 if (c->last_packet_sent || c->is_packetized)
2190 /* prepare header */
2191 if (url_open_dyn_buf(&ctx->pb) < 0) {
2192 /* XXX: potential leak */
2195 av_write_trailer(ctx);
2196 len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
2197 c->buffer_ptr = c->pb_buffer;
2198 c->buffer_end = c->pb_buffer + len;
2200 c->last_packet_sent = 1;
2207 #define SHORT_TERM_BANDWIDTH 8000000
2209 /* should convert the format at the same time */
2210 /* send data starting at c->buffer_ptr to the output connection
2211 (either UDP or TCP connection) */
2212 static int http_send_data(HTTPContext *c)
2217 if (c->buffer_ptr >= c->buffer_end) {
2218 ret = http_prepare_data(c);
2221 else if (ret != 0) {
2222 /* state change requested */
2226 if (c->is_packetized) {
2227 /* RTP data output */
2228 len = c->buffer_end - c->buffer_ptr;
2230 /* fail safe - should never happen */
2232 c->buffer_ptr = c->buffer_end;
2235 len = (c->buffer_ptr[0] << 24) |
2236 (c->buffer_ptr[1] << 16) |
2237 (c->buffer_ptr[2] << 8) |
2239 if (len > (c->buffer_end - c->buffer_ptr))
2241 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2242 /* nothing to send yet: we can wait */
2246 c->data_count += len;
2247 update_datarate(&c->datarate, c->data_count);
2249 c->stream->bytes_served += len;
2251 if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP) {
2252 /* RTP packets are sent inside the RTSP TCP connection */
2253 ByteIOContext pb1, *pb = &pb1;
2254 int interleaved_index, size;
2256 HTTPContext *rtsp_c;
2259 /* if no RTSP connection left, error */
2262 /* if already sending something, then wait. */
2263 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST) {
2266 if (url_open_dyn_buf(pb) < 0)
2268 interleaved_index = c->packet_stream_index * 2;
2269 /* RTCP packets are sent at odd indexes */
2270 if (c->buffer_ptr[1] == 200)
2271 interleaved_index++;
2272 /* write RTSP TCP header */
2274 header[1] = interleaved_index;
2275 header[2] = len >> 8;
2277 put_buffer(pb, header, 4);
2278 /* write RTP packet data */
2280 put_buffer(pb, c->buffer_ptr, len);
2281 size = url_close_dyn_buf(pb, &c->packet_buffer);
2282 /* prepare asynchronous TCP sending */
2283 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2284 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2285 c->buffer_ptr += len;
2287 /* send everything we can NOW */
2288 len = write(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2289 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr);
2291 rtsp_c->packet_buffer_ptr += len;
2293 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2294 /* if we could not send all the data, we will
2295 send it later, so a new state is needed to
2296 "lock" the RTSP TCP connection */
2297 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2300 /* all data has been sent */
2301 av_freep(&c->packet_buffer);
2304 /* send RTP packet directly in UDP */
2306 url_write(c->rtp_handles[c->packet_stream_index],
2307 c->buffer_ptr, len);
2308 c->buffer_ptr += len;
2309 /* here we continue as we can send several packets per 10 ms slot */
2312 /* TCP data output */
2313 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
2315 if (errno != EAGAIN && errno != EINTR) {
2316 /* error : close connection */
2322 c->buffer_ptr += len;
2324 c->data_count += len;
2325 update_datarate(&c->datarate, c->data_count);
2327 c->stream->bytes_served += len;
2335 static int http_start_receive_data(HTTPContext *c)
2339 if (c->stream->feed_opened)
2342 /* Don't permit writing to this one */
2343 if (c->stream->readonly)
2347 fd = open(c->stream->feed_filename, O_RDWR);
2352 c->stream->feed_write_index = ffm_read_write_index(fd);
2353 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2354 lseek(fd, 0, SEEK_SET);
2356 /* init buffer input */
2357 c->buffer_ptr = c->buffer;
2358 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2359 c->stream->feed_opened = 1;
2363 static int http_receive_data(HTTPContext *c)
2367 if (c->buffer_end > c->buffer_ptr) {
2370 len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
2372 if (errno != EAGAIN && errno != EINTR) {
2373 /* error : close connection */
2376 } else if (len == 0) {
2377 /* end of connection : close it */
2380 c->buffer_ptr += len;
2381 c->data_count += len;
2382 update_datarate(&c->datarate, c->data_count);
2386 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2387 if (c->buffer[0] != 'f' ||
2388 c->buffer[1] != 'm') {
2389 http_log("Feed stream has become desynchronized -- disconnecting\n");
2394 if (c->buffer_ptr >= c->buffer_end) {
2395 FFStream *feed = c->stream;
2396 /* a packet has been received : write it in the store, except
2398 if (c->data_count > FFM_PACKET_SIZE) {
2400 // printf("writing pos=0x%Lx size=0x%Lx\n", feed->feed_write_index, feed->feed_size);
2401 /* XXX: use llseek or url_seek */
2402 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
2403 write(c->feed_fd, c->buffer, FFM_PACKET_SIZE);
2405 feed->feed_write_index += FFM_PACKET_SIZE;
2406 /* update file size */
2407 if (feed->feed_write_index > c->stream->feed_size)
2408 feed->feed_size = feed->feed_write_index;
2410 /* handle wrap around if max file size reached */
2411 if (feed->feed_write_index >= c->stream->feed_max_size)
2412 feed->feed_write_index = FFM_PACKET_SIZE;
2415 ffm_write_write_index(c->feed_fd, feed->feed_write_index);
2417 /* wake up any waiting connections */
2418 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2419 if (c1->state == HTTPSTATE_WAIT_FEED &&
2420 c1->stream->feed == c->stream->feed) {
2421 c1->state = HTTPSTATE_SEND_DATA;
2425 /* We have a header in our hands that contains useful data */
2427 AVInputFormat *fmt_in;
2428 ByteIOContext *pb = &s.pb;
2431 memset(&s, 0, sizeof(s));
2433 url_open_buf(pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
2434 pb->buf_end = c->buffer_end; /* ?? */
2435 pb->is_streamed = 1;
2437 /* use feed output format name to find corresponding input format */
2438 fmt_in = av_find_input_format(feed->fmt->name);
2442 if (fmt_in->priv_data_size > 0) {
2443 s.priv_data = av_mallocz(fmt_in->priv_data_size);
2449 if (fmt_in->read_header(&s, 0) < 0) {
2450 av_freep(&s.priv_data);
2454 /* Now we have the actual streams */
2455 if (s.nb_streams != feed->nb_streams) {
2456 av_freep(&s.priv_data);
2459 for (i = 0; i < s.nb_streams; i++) {
2460 memcpy(&feed->streams[i]->codec,
2461 &s.streams[i]->codec, sizeof(AVCodecContext));
2463 av_freep(&s.priv_data);
2465 c->buffer_ptr = c->buffer;
2470 c->stream->feed_opened = 0;
2475 /********************************************************************/
2478 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2485 switch(error_number) {
2486 #define DEF(n, c, s) case c: str = s; break;
2487 #include "rtspcodes.h"
2490 str = "Unknown Error";
2494 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2495 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2497 /* output GMT time */
2501 p = buf2 + strlen(p) - 1;
2504 url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
2507 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2509 rtsp_reply_header(c, error_number);
2510 url_fprintf(c->pb, "\r\n");
2513 static int rtsp_parse_request(HTTPContext *c)
2515 const char *p, *p1, *p2;
2522 RTSPHeader header1, *header = &header1;
2524 c->buffer_ptr[0] = '\0';
2527 get_word(cmd, sizeof(cmd), &p);
2528 get_word(url, sizeof(url), &p);
2529 get_word(protocol, sizeof(protocol), &p);
2531 pstrcpy(c->method, sizeof(c->method), cmd);
2532 pstrcpy(c->url, sizeof(c->url), url);
2533 pstrcpy(c->protocol, sizeof(c->protocol), protocol);
2536 if (url_open_dyn_buf(c->pb) < 0) {
2537 /* XXX: cannot do more */
2538 c->pb = NULL; /* safety */
2542 /* check version name */
2543 if (strcmp(protocol, "RTSP/1.0") != 0) {
2544 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2548 /* parse each header line */
2549 memset(header, 0, sizeof(RTSPHeader));
2550 /* skip to next line */
2551 while (*p != '\n' && *p != '\0')
2555 while (*p != '\0') {
2556 p1 = strchr(p, '\n');
2560 if (p2 > p && p2[-1] == '\r')
2562 /* skip empty line */
2566 if (len > sizeof(line) - 1)
2567 len = sizeof(line) - 1;
2568 memcpy(line, p, len);
2570 rtsp_parse_line(header, line);
2574 /* handle sequence number */
2575 c->seq = header->seq;
2577 if (!strcmp(cmd, "DESCRIBE")) {
2578 rtsp_cmd_describe(c, url);
2579 } else if (!strcmp(cmd, "OPTIONS")) {
2580 rtsp_cmd_options(c, url);
2581 } else if (!strcmp(cmd, "SETUP")) {
2582 rtsp_cmd_setup(c, url, header);
2583 } else if (!strcmp(cmd, "PLAY")) {
2584 rtsp_cmd_play(c, url, header);
2585 } else if (!strcmp(cmd, "PAUSE")) {
2586 rtsp_cmd_pause(c, url, header);
2587 } else if (!strcmp(cmd, "TEARDOWN")) {
2588 rtsp_cmd_teardown(c, url, header);
2590 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2593 len = url_close_dyn_buf(c->pb, &c->pb_buffer);
2594 c->pb = NULL; /* safety */
2596 /* XXX: cannot do more */
2599 c->buffer_ptr = c->pb_buffer;
2600 c->buffer_end = c->pb_buffer + len;
2601 c->state = RTSPSTATE_SEND_REPLY;
2605 /* XXX: move that to rtsp.c, but would need to replace FFStream by
2607 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
2608 struct in_addr my_ip)
2610 ByteIOContext pb1, *pb = &pb1;
2611 int i, payload_type, port, private_payload_type, j;
2612 const char *ipstr, *title, *mediatype;
2615 if (url_open_dyn_buf(pb) < 0)
2618 /* general media info */
2620 url_fprintf(pb, "v=0\n");
2621 ipstr = inet_ntoa(my_ip);
2622 url_fprintf(pb, "o=- 0 0 IN IP4 %s\n", ipstr);
2623 title = stream->title;
2624 if (title[0] == '\0')
2626 url_fprintf(pb, "s=%s\n", title);
2627 if (stream->comment[0] != '\0')
2628 url_fprintf(pb, "i=%s\n", stream->comment);
2629 if (stream->is_multicast) {
2630 url_fprintf(pb, "c=IN IP4 %s\n", inet_ntoa(stream->multicast_ip));
2632 /* for each stream, we output the necessary info */
2633 private_payload_type = RTP_PT_PRIVATE;
2634 for(i = 0; i < stream->nb_streams; i++) {
2635 st = stream->streams[i];
2636 if (st->codec.codec_id == CODEC_ID_MPEG2TS) {
2637 mediatype = "video";
2639 switch(st->codec.codec_type) {
2640 case CODEC_TYPE_AUDIO:
2641 mediatype = "audio";
2643 case CODEC_TYPE_VIDEO:
2644 mediatype = "video";
2647 mediatype = "application";
2651 /* NOTE: the port indication is not correct in case of
2652 unicast. It is not an issue because RTSP gives it */
2653 payload_type = rtp_get_payload_type(&st->codec);
2654 if (payload_type < 0)
2655 payload_type = private_payload_type++;
2656 if (stream->is_multicast) {
2657 port = stream->multicast_port + 2 * i;
2661 url_fprintf(pb, "m=%s %d RTP/AVP %d\n",
2662 mediatype, port, payload_type);
2663 if (payload_type >= RTP_PT_PRIVATE) {
2664 /* for private payload type, we need to give more info */
2665 switch(st->codec.codec_id) {
2666 case CODEC_ID_MPEG4:
2669 url_fprintf(pb, "a=rtpmap:%d MP4V-ES/%d\n",
2670 payload_type, 90000);
2671 /* we must also add the mpeg4 header */
2672 data = st->codec.extradata;
2674 url_fprintf(pb, "a=fmtp:%d config=", payload_type);
2675 for(j=0;j<st->codec.extradata_size;j++) {
2676 url_fprintf(pb, "%02x", data[j]);
2678 url_fprintf(pb, "\n");
2683 /* XXX: add other codecs ? */
2687 url_fprintf(pb, "a=control:streamid=%d\n", i);
2689 return url_close_dyn_buf(pb, pbuffer);
2691 url_close_dyn_buf(pb, pbuffer);
2696 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2698 // rtsp_reply_header(c, RTSP_STATUS_OK);
2699 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2700 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2701 url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2702 url_fprintf(c->pb, "\r\n");
2705 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2711 int content_length, len;
2712 struct sockaddr_in my_addr;
2714 /* find which url is asked */
2715 url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2720 for(stream = first_stream; stream != NULL; stream = stream->next) {
2721 if (!stream->is_feed && stream->fmt == &rtp_mux &&
2722 !strcmp(path, stream->filename)) {
2726 /* no stream found */
2727 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2731 /* prepare the media description in sdp format */
2733 /* get the host IP */
2734 len = sizeof(my_addr);
2735 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
2736 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
2737 if (content_length < 0) {
2738 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2741 rtsp_reply_header(c, RTSP_STATUS_OK);
2742 url_fprintf(c->pb, "Content-Type: application/sdp\r\n");
2743 url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);
2744 url_fprintf(c->pb, "\r\n");
2745 put_buffer(c->pb, content, content_length);
2748 static HTTPContext *find_rtp_session(const char *session_id)
2752 if (session_id[0] == '\0')
2755 for(c = first_http_ctx; c != NULL; c = c->next) {
2756 if (!strcmp(c->session_id, session_id))
2762 static RTSPTransportField *find_transport(RTSPHeader *h, enum RTSPProtocol protocol)
2764 RTSPTransportField *th;
2767 for(i=0;i<h->nb_transports;i++) {
2768 th = &h->transports[i];
2769 if (th->protocol == protocol)
2775 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
2779 int stream_index, port;
2784 RTSPTransportField *th;
2785 struct sockaddr_in dest_addr;
2786 RTSPActionServerSetup setup;
2788 /* find which url is asked */
2789 url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2794 /* now check each stream */
2795 for(stream = first_stream; stream != NULL; stream = stream->next) {
2796 if (!stream->is_feed && stream->fmt == &rtp_mux) {
2797 /* accept aggregate filenames only if single stream */
2798 if (!strcmp(path, stream->filename)) {
2799 if (stream->nb_streams != 1) {
2800 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
2807 for(stream_index = 0; stream_index < stream->nb_streams;
2809 snprintf(buf, sizeof(buf), "%s/streamid=%d",
2810 stream->filename, stream_index);
2811 if (!strcmp(path, buf))
2816 /* no stream found */
2817 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2821 /* generate session id if needed */
2822 if (h->session_id[0] == '\0') {
2823 snprintf(h->session_id, sizeof(h->session_id),
2824 "%08x%08x", (int)random(), (int)random());
2827 /* find rtp session, and create it if none found */
2828 rtp_c = find_rtp_session(h->session_id);
2830 /* always prefer UDP */
2831 th = find_transport(h, RTSP_PROTOCOL_RTP_UDP);
2833 th = find_transport(h, RTSP_PROTOCOL_RTP_TCP);
2835 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2840 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
2843 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
2847 /* open input stream */
2848 if (open_input_stream(rtp_c, "") < 0) {
2849 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2854 /* test if stream is OK (test needed because several SETUP needs
2855 to be done for a given file) */
2856 if (rtp_c->stream != stream) {
2857 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
2861 /* test if stream is already set up */
2862 if (rtp_c->rtp_ctx[stream_index]) {
2863 rtsp_reply_error(c, RTSP_STATUS_STATE);
2867 /* check transport */
2868 th = find_transport(h, rtp_c->rtp_protocol);
2869 if (!th || (th->protocol == RTSP_PROTOCOL_RTP_UDP &&
2870 th->client_port_min <= 0)) {
2871 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2875 /* setup default options */
2876 setup.transport_option[0] = '\0';
2877 dest_addr = rtp_c->from_addr;
2878 dest_addr.sin_port = htons(th->client_port_min);
2880 /* add transport option if needed */
2881 if (ff_rtsp_callback) {
2882 setup.ipaddr = ntohl(dest_addr.sin_addr.s_addr);
2883 if (ff_rtsp_callback(RTSP_ACTION_SERVER_SETUP, rtp_c->session_id,
2884 (char *)&setup, sizeof(setup),
2885 stream->rtsp_option) < 0) {
2886 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2889 dest_addr.sin_addr.s_addr = htonl(setup.ipaddr);
2893 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
2894 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2898 /* now everything is OK, so we can send the connection parameters */
2899 rtsp_reply_header(c, RTSP_STATUS_OK);
2901 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
2903 switch(rtp_c->rtp_protocol) {
2904 case RTSP_PROTOCOL_RTP_UDP:
2905 port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]);
2906 url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
2907 "client_port=%d-%d;server_port=%d-%d",
2908 th->client_port_min, th->client_port_min + 1,
2911 case RTSP_PROTOCOL_RTP_TCP:
2912 url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
2913 stream_index * 2, stream_index * 2 + 1);
2918 if (setup.transport_option[0] != '\0') {
2919 url_fprintf(c->pb, ";%s", setup.transport_option);
2921 url_fprintf(c->pb, "\r\n");
2924 url_fprintf(c->pb, "\r\n");
2928 /* find an rtp connection by using the session ID. Check consistency
2930 static HTTPContext *find_rtp_session_with_url(const char *url,
2931 const char *session_id)
2939 rtp_c = find_rtp_session(session_id);
2943 /* find which url is asked */
2944 url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2948 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
2949 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
2950 snprintf(buf, sizeof(buf), "%s/streamid=%d",
2951 rtp_c->stream->filename, s);
2952 if(!strncmp(path, buf, sizeof(buf))) {
2953 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
2960 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h)
2964 rtp_c = find_rtp_session_with_url(url, h->session_id);
2966 rtsp_reply_error(c, RTSP_STATUS_SESSION);
2970 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
2971 rtp_c->state != HTTPSTATE_WAIT_FEED &&
2972 rtp_c->state != HTTPSTATE_READY) {
2973 rtsp_reply_error(c, RTSP_STATUS_STATE);
2978 /* XXX: seek in stream */
2979 if (h->range_start != AV_NOPTS_VALUE) {
2980 printf("range_start=%0.3f\n", (double)h->range_start / AV_TIME_BASE);
2981 av_seek_frame(rtp_c->fmt_in, -1, h->range_start);
2985 rtp_c->state = HTTPSTATE_SEND_DATA;
2987 /* now everything is OK, so we can send the connection parameters */
2988 rtsp_reply_header(c, RTSP_STATUS_OK);
2990 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
2991 url_fprintf(c->pb, "\r\n");
2994 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h)
2998 rtp_c = find_rtp_session_with_url(url, h->session_id);
3000 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3004 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3005 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3006 rtsp_reply_error(c, RTSP_STATUS_STATE);
3010 rtp_c->state = HTTPSTATE_READY;
3011 rtp_c->first_pts = AV_NOPTS_VALUE;
3012 /* now everything is OK, so we can send the connection parameters */
3013 rtsp_reply_header(c, RTSP_STATUS_OK);
3015 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3016 url_fprintf(c->pb, "\r\n");
3019 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h)
3023 rtp_c = find_rtp_session_with_url(url, h->session_id);
3025 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3029 /* abort the session */
3030 close_connection(rtp_c);
3032 if (ff_rtsp_callback) {
3033 ff_rtsp_callback(RTSP_ACTION_SERVER_TEARDOWN, rtp_c->session_id,
3035 rtp_c->stream->rtsp_option);
3038 /* now everything is OK, so we can send the connection parameters */
3039 rtsp_reply_header(c, RTSP_STATUS_OK);
3041 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3042 url_fprintf(c->pb, "\r\n");
3046 /********************************************************************/
3049 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3050 FFStream *stream, const char *session_id,
3051 enum RTSPProtocol rtp_protocol)
3053 HTTPContext *c = NULL;
3054 const char *proto_str;
3056 /* XXX: should output a warning page when coming
3057 close to the connection limit */
3058 if (nb_connections >= nb_max_connections)
3061 /* add a new connection */
3062 c = av_mallocz(sizeof(HTTPContext));
3067 c->poll_entry = NULL;
3068 c->from_addr = *from_addr;
3069 c->buffer_size = IOBUFFER_INIT_SIZE;
3070 c->buffer = av_malloc(c->buffer_size);
3075 pstrcpy(c->session_id, sizeof(c->session_id), session_id);
3076 c->state = HTTPSTATE_READY;
3077 c->is_packetized = 1;
3078 c->rtp_protocol = rtp_protocol;
3080 /* protocol is shown in statistics */
3081 switch(c->rtp_protocol) {
3082 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
3083 proto_str = "MCAST";
3085 case RTSP_PROTOCOL_RTP_UDP:
3088 case RTSP_PROTOCOL_RTP_TCP:
3095 pstrcpy(c->protocol, sizeof(c->protocol), "RTP/");
3096 pstrcat(c->protocol, sizeof(c->protocol), proto_str);
3098 current_bandwidth += stream->bandwidth;
3100 c->next = first_http_ctx;
3112 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3113 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3115 static int rtp_new_av_stream(HTTPContext *c,
3116 int stream_index, struct sockaddr_in *dest_addr,
3117 HTTPContext *rtsp_c)
3119 AVFormatContext *ctx;
3125 int max_packet_size;
3127 /* now we can open the relevant output stream */
3128 ctx = av_alloc_format_context();
3131 ctx->oformat = &rtp_mux;
3133 st = av_mallocz(sizeof(AVStream));
3136 ctx->nb_streams = 1;
3137 ctx->streams[0] = st;
3139 if (!c->stream->feed ||
3140 c->stream->feed == c->stream) {
3141 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3144 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3148 /* build destination RTP address */
3149 ipaddr = inet_ntoa(dest_addr->sin_addr);
3151 switch(c->rtp_protocol) {
3152 case RTSP_PROTOCOL_RTP_UDP:
3153 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
3156 /* XXX: also pass as parameter to function ? */
3157 if (c->stream->is_multicast) {
3159 ttl = c->stream->multicast_ttl;
3162 snprintf(ctx->filename, sizeof(ctx->filename),
3163 "rtp://%s:%d?multicast=1&ttl=%d",
3164 ipaddr, ntohs(dest_addr->sin_port), ttl);
3166 snprintf(ctx->filename, sizeof(ctx->filename),
3167 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3170 if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
3172 c->rtp_handles[stream_index] = h;
3173 max_packet_size = url_get_max_packet_size(h);
3175 case RTSP_PROTOCOL_RTP_TCP:
3178 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3184 http_log("%s:%d - - [%s] \"PLAY %s/streamid=%d %s\"\n",
3185 ipaddr, ntohs(dest_addr->sin_port),
3187 c->stream->filename, stream_index, c->protocol);
3189 /* normally, no packets should be output here, but the packet size may be checked */
3190 if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
3191 /* XXX: close stream */
3194 av_set_parameters(ctx, NULL);
3195 if (av_write_header(ctx) < 0) {
3202 url_close_dyn_buf(&ctx->pb, &dummy_buf);
3205 c->rtp_ctx[stream_index] = ctx;
3209 /********************************************************************/
3210 /* ffserver initialization */
3212 static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
3216 fst = av_mallocz(sizeof(AVStream));
3219 fst->priv_data = av_mallocz(sizeof(FeedData));
3220 memcpy(&fst->codec, codec, sizeof(AVCodecContext));
3221 fst->codec.coded_frame = &dummy_frame;
3222 fst->index = stream->nb_streams;
3223 stream->streams[stream->nb_streams++] = fst;
3227 /* return the stream number in the feed */
3228 static int add_av_stream(FFStream *feed, AVStream *st)
3231 AVCodecContext *av, *av1;
3235 for(i=0;i<feed->nb_streams;i++) {
3236 st = feed->streams[i];
3238 if (av1->codec_id == av->codec_id &&
3239 av1->codec_type == av->codec_type &&
3240 av1->bit_rate == av->bit_rate) {
3242 switch(av->codec_type) {
3243 case CODEC_TYPE_AUDIO:
3244 if (av1->channels == av->channels &&
3245 av1->sample_rate == av->sample_rate)
3248 case CODEC_TYPE_VIDEO:
3249 if (av1->width == av->width &&
3250 av1->height == av->height &&
3251 av1->frame_rate == av->frame_rate &&
3252 av1->frame_rate_base == av->frame_rate_base &&
3253 av1->gop_size == av->gop_size)
3262 fst = add_av_stream1(feed, av);
3265 return feed->nb_streams - 1;
3270 static void remove_stream(FFStream *stream)
3274 while (*ps != NULL) {
3275 if (*ps == stream) {
3283 /* specific mpeg4 handling : we extract the raw parameters */
3284 static void extract_mpeg4_header(AVFormatContext *infile)
3286 int mpeg4_count, i, size;
3292 for(i=0;i<infile->nb_streams;i++) {
3293 st = infile->streams[i];
3294 if (st->codec.codec_id == CODEC_ID_MPEG4 &&
3295 st->codec.extradata_size == 0) {
3302 printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
3303 while (mpeg4_count > 0) {
3304 if (av_read_packet(infile, &pkt) < 0)
3306 st = infile->streams[pkt.stream_index];
3307 if (st->codec.codec_id == CODEC_ID_MPEG4 &&
3308 st->codec.extradata_size == 0) {
3309 av_freep(&st->codec.extradata);
3310 /* fill extradata with the header */
3311 /* XXX: we make hard suppositions here ! */
3313 while (p < pkt.data + pkt.size - 4) {
3314 /* stop when vop header is found */
3315 if (p[0] == 0x00 && p[1] == 0x00 &&
3316 p[2] == 0x01 && p[3] == 0xb6) {
3317 size = p - pkt.data;
3318 // av_hex_dump(pkt.data, size);
3319 st->codec.extradata = av_malloc(size);
3320 st->codec.extradata_size = size;
3321 memcpy(st->codec.extradata, pkt.data, size);
3328 av_free_packet(&pkt);
3332 /* compute the needed AVStream for each file */
3333 static void build_file_streams(void)
3335 FFStream *stream, *stream_next;
3336 AVFormatContext *infile;
3339 /* gather all streams */
3340 for(stream = first_stream; stream != NULL; stream = stream_next) {
3341 stream_next = stream->next;
3342 if (stream->stream_type == STREAM_TYPE_LIVE &&
3344 /* the stream comes from a file */
3345 /* try to open the file */
3347 stream->ap_in = av_mallocz(sizeof(AVFormatParameters));
3348 if (stream->fmt == &rtp_mux) {
3349 /* specific case : if transport stream output to RTP,
3350 we use a raw transport stream reader */
3351 stream->ap_in->mpeg2ts_raw = 1;
3352 stream->ap_in->mpeg2ts_compute_pcr = 1;
3355 if (av_open_input_file(&infile, stream->feed_filename,
3356 stream->ifmt, 0, stream->ap_in) < 0) {
3357 http_log("%s not found", stream->feed_filename);
3358 /* remove stream (no need to spend more time on it) */
3360 remove_stream(stream);
3362 /* find all the AVStreams inside and reference them in
3364 if (av_find_stream_info(infile) < 0) {
3365 http_log("Could not find codec parameters from '%s'",
3366 stream->feed_filename);
3367 av_close_input_file(infile);
3370 extract_mpeg4_header(infile);
3372 for(i=0;i<infile->nb_streams;i++) {
3373 add_av_stream1(stream, &infile->streams[i]->codec);
3375 av_close_input_file(infile);
3381 /* compute the needed AVStream for each feed */
3382 static void build_feed_streams(void)
3384 FFStream *stream, *feed;
3387 /* gather all streams */
3388 for(stream = first_stream; stream != NULL; stream = stream->next) {
3389 feed = stream->feed;
3391 if (!stream->is_feed) {
3392 /* we handle a stream coming from a feed */
3393 for(i=0;i<stream->nb_streams;i++) {
3394 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3400 /* gather all streams */
3401 for(stream = first_stream; stream != NULL; stream = stream->next) {
3402 feed = stream->feed;
3404 if (stream->is_feed) {
3405 for(i=0;i<stream->nb_streams;i++) {
3406 stream->feed_streams[i] = i;
3412 /* create feed files if needed */
3413 for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
3416 if (url_exist(feed->feed_filename)) {
3417 /* See if it matches */
3421 if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) {
3422 /* Now see if it matches */
3423 if (s->nb_streams == feed->nb_streams) {
3425 for(i=0;i<s->nb_streams;i++) {
3427 sf = feed->streams[i];
3430 if (sf->index != ss->index ||
3432 printf("Index & Id do not match for stream %d (%s)\n",
3433 i, feed->feed_filename);
3436 AVCodecContext *ccf, *ccs;
3440 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3442 if (CHECK_CODEC(codec) || CHECK_CODEC(codec_type)) {
3443 printf("Codecs do not match for stream %d\n", i);
3445 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3446 printf("Codec bitrates do not match for stream %d\n", i);
3448 } else if (ccf->codec_type == CODEC_TYPE_VIDEO) {
3449 if (CHECK_CODEC(frame_rate) ||
3450 CHECK_CODEC(frame_rate_base) ||
3451 CHECK_CODEC(width) ||
3452 CHECK_CODEC(height)) {
3453 printf("Codec width, height and framerate do not match for stream %d\n", i);
3456 } else if (ccf->codec_type == CODEC_TYPE_AUDIO) {
3457 if (CHECK_CODEC(sample_rate) ||
3458 CHECK_CODEC(channels) ||
3459 CHECK_CODEC(frame_size)) {
3460 printf("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3464 printf("Unknown codec type\n");
3473 printf("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3474 feed->feed_filename, s->nb_streams, feed->nb_streams);
3477 av_close_input_file(s);
3479 printf("Deleting feed file '%s' as it appears to be corrupt\n",
3480 feed->feed_filename);
3483 if (feed->readonly) {
3484 printf("Unable to delete feed file '%s' as it is marked readonly\n",
3485 feed->feed_filename);
3488 unlink(feed->feed_filename);
3491 if (!url_exist(feed->feed_filename)) {
3492 AVFormatContext s1, *s = &s1;
3494 if (feed->readonly) {
3495 printf("Unable to create feed file '%s' as it is marked readonly\n",
3496 feed->feed_filename);
3500 /* only write the header of the ffm file */
3501 if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
3502 fprintf(stderr, "Could not open output feed file '%s'\n",
3503 feed->feed_filename);
3506 s->oformat = feed->fmt;
3507 s->nb_streams = feed->nb_streams;
3508 for(i=0;i<s->nb_streams;i++) {
3510 st = feed->streams[i];
3513 av_set_parameters(s, NULL);
3515 /* XXX: need better api */
3516 av_freep(&s->priv_data);
3519 /* get feed size and write index */
3520 fd = open(feed->feed_filename, O_RDONLY);
3522 fprintf(stderr, "Could not open output feed file '%s'\n",
3523 feed->feed_filename);
3527 feed->feed_write_index = ffm_read_write_index(fd);
3528 feed->feed_size = lseek(fd, 0, SEEK_END);
3529 /* ensure that we do not wrap before the end of file */
3530 if (feed->feed_max_size < feed->feed_size)
3531 feed->feed_max_size = feed->feed_size;
3537 /* compute the bandwidth used by each stream */
3538 static void compute_bandwidth(void)
3543 for(stream = first_stream; stream != NULL; stream = stream->next) {
3545 for(i=0;i<stream->nb_streams;i++) {
3546 AVStream *st = stream->streams[i];
3547 switch(st->codec.codec_type) {
3548 case CODEC_TYPE_AUDIO:
3549 case CODEC_TYPE_VIDEO:
3550 bandwidth += st->codec.bit_rate;
3556 stream->bandwidth = (bandwidth + 999) / 1000;
3560 static void get_arg(char *buf, int buf_size, const char **pp)
3567 while (isspace(*p)) p++;
3570 if (*p == '\"' || *p == '\'')
3582 if ((q - buf) < buf_size - 1)
3587 if (quote && *p == quote)
3592 /* add a codec and set the default parameters */
3593 static void add_codec(FFStream *stream, AVCodecContext *av)
3597 /* compute default parameters */
3598 switch(av->codec_type) {
3599 case CODEC_TYPE_AUDIO:
3600 if (av->bit_rate == 0)
3601 av->bit_rate = 64000;
3602 if (av->sample_rate == 0)
3603 av->sample_rate = 22050;
3604 if (av->channels == 0)
3607 case CODEC_TYPE_VIDEO:
3608 if (av->bit_rate == 0)
3609 av->bit_rate = 64000;
3610 if (av->frame_rate == 0){
3612 av->frame_rate_base = 1;
3614 if (av->width == 0 || av->height == 0) {
3618 /* Bitrate tolerance is less for streaming */
3619 if (av->bit_rate_tolerance == 0)
3620 av->bit_rate_tolerance = av->bit_rate / 4;
3625 if (av->max_qdiff == 0)
3627 av->qcompress = 0.5;
3631 av->rc_eq = "tex^qComp";
3632 if (!av->i_quant_factor)
3633 av->i_quant_factor = -0.8;
3634 if (!av->b_quant_factor)
3635 av->b_quant_factor = 1.25;
3636 if (!av->b_quant_offset)
3637 av->b_quant_offset = 1.25;
3638 if (!av->rc_min_rate)
3639 av->rc_min_rate = av->bit_rate / 2;
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");