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>
30 #include <sys/types.h>
31 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
37 #ifdef CONFIG_HAVE_DLFCN
43 /* maximum number of simultaneous HTTP connections */
44 #define HTTP_MAX_CONNECTIONS 2000
47 HTTPSTATE_WAIT_REQUEST,
48 HTTPSTATE_SEND_HEADER,
49 HTTPSTATE_SEND_DATA_HEADER,
50 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
51 HTTPSTATE_SEND_DATA_TRAILER,
52 HTTPSTATE_RECEIVE_DATA,
53 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
54 HTTPSTATE_WAIT, /* wait before sending next packets */
55 HTTPSTATE_WAIT_SHORT, /* short wait for short term
56 bandwidth limitation */
59 RTSPSTATE_WAIT_REQUEST,
61 RTSPSTATE_SEND_PACKET,
64 const char *http_state[] = {
82 #define IOBUFFER_INIT_SIZE 8192
84 /* coef for exponential mean for bitrate estimation in statistics */
87 /* timeouts are in ms */
88 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
89 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
91 #define SYNC_TIMEOUT (10 * 1000)
94 int64_t count1, count2;
98 /* context associated with one connection */
99 typedef struct HTTPContext {
100 enum HTTPState state;
101 int fd; /* socket file descriptor */
102 struct sockaddr_in from_addr; /* origin */
103 struct pollfd *poll_entry; /* used when polling */
105 uint8_t *buffer_ptr, *buffer_end;
107 struct HTTPContext *next;
108 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
112 /* input format handling */
113 AVFormatContext *fmt_in;
114 long start_time; /* In milliseconds - this wraps fairly often */
115 int64_t first_pts; /* initial pts value */
116 int64_t cur_pts; /* current pts value */
117 int pts_stream_index; /* stream we choose as clock reference */
118 /* output format handling */
119 struct FFStream *stream;
120 /* -1 is invalid stream */
121 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
122 int switch_feed_streams[MAX_STREAMS]; /* index of streams in the feed */
124 AVFormatContext fmt_ctx; /* instance of FFStream for one user */
125 int last_packet_sent; /* true if last data packet was sent */
127 DataRateData datarate;
134 int is_packetized; /* if true, the stream is packetized */
135 int packet_stream_index; /* current stream for output in state machine */
137 /* RTSP state specific */
138 uint8_t *pb_buffer; /* XXX: use that in all the code */
140 int seq; /* RTSP sequence number */
142 /* RTP state specific */
143 enum RTSPProtocol rtp_protocol;
144 char session_id[32]; /* session id */
145 AVFormatContext *rtp_ctx[MAX_STREAMS];
146 /* RTP short term bandwidth limitation */
147 int packet_byte_count;
148 int packet_start_time_us; /* used for short durations (a few
150 /* RTP/UDP specific */
151 URLContext *rtp_handles[MAX_STREAMS];
153 /* RTP/TCP specific */
154 struct HTTPContext *rtsp_c;
155 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
158 static AVFrame dummy_frame;
160 /* each generated stream is described here */
164 STREAM_TYPE_REDIRECT,
167 enum IPAddressAction {
172 typedef struct IPAddressACL {
173 struct IPAddressACL *next;
174 enum IPAddressAction action;
175 /* These are in host order */
176 struct in_addr first;
180 /* description of each stream of the ffserver.conf file */
181 typedef struct FFStream {
182 enum StreamType stream_type;
183 char filename[1024]; /* stream filename */
184 struct FFStream *feed; /* feed we are using (can be null if
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);
250 static int compute_send_delay(HTTPContext *c);
253 static int rtsp_parse_request(HTTPContext *c);
254 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
255 static void rtsp_cmd_options(HTTPContext *c, const char *url);
256 static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPHeader *h);
257 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h);
258 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h);
259 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h);
262 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
263 struct in_addr my_ip);
266 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
267 FFStream *stream, const char *session_id,
268 enum RTSPProtocol rtp_protocol);
269 static int rtp_new_av_stream(HTTPContext *c,
270 int stream_index, struct sockaddr_in *dest_addr,
271 HTTPContext *rtsp_c);
273 static const char *my_program_name;
274 static const char *my_program_dir;
276 static int ffserver_debug;
277 static int ffserver_daemon;
278 static int no_launch;
279 static int need_to_start_children;
281 int nb_max_connections;
285 int current_bandwidth;
287 static long cur_time; // Making this global saves on passing it around everywhere
289 static long gettime_ms(void)
293 gettimeofday(&tv,NULL);
294 return (long long)tv.tv_sec * 1000 + (tv.tv_usec / 1000);
297 static FILE *logfile = NULL;
299 static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
305 vfprintf(logfile, fmt, ap);
311 static char *ctime1(char *buf2)
319 p = buf2 + strlen(p) - 1;
325 static void log_connection(HTTPContext *c)
332 http_log("%s - - [%s] \"%s %s %s\" %d %lld\n",
333 inet_ntoa(c->from_addr.sin_addr),
334 ctime1(buf2), c->method, c->url,
335 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
338 static void update_datarate(DataRateData *drd, int64_t count)
340 if (!drd->time1 && !drd->count1) {
341 drd->time1 = drd->time2 = cur_time;
342 drd->count1 = drd->count2 = count;
344 if (cur_time - drd->time2 > 5000) {
345 drd->time1 = drd->time2;
346 drd->count1 = drd->count2;
347 drd->time2 = cur_time;
353 /* In bytes per second */
354 static int compute_datarate(DataRateData *drd, int64_t count)
356 if (cur_time == drd->time1)
359 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
362 static int get_longterm_datarate(DataRateData *drd, int64_t count)
364 /* You get the first 3 seconds flat out */
365 if (cur_time - drd->time1 < 3000)
367 return compute_datarate(drd, count);
371 static void start_children(FFStream *feed)
376 for (; feed; feed = feed->next) {
377 if (feed->child_argv && !feed->pid) {
378 feed->pid_start = time(0);
383 fprintf(stderr, "Unable to create children\n");
392 for (i = 3; i < 256; i++) {
396 if (!ffserver_debug) {
397 i = open("/dev/null", O_RDWR);
406 pstrcpy(pathname, sizeof(pathname), my_program_name);
408 slash = strrchr(pathname, '/');
414 strcpy(slash, "ffmpeg");
416 /* This is needed to make relative pathnames work */
417 chdir(my_program_dir);
419 signal(SIGPIPE, SIG_DFL);
421 execvp(pathname, feed->child_argv);
429 /* open a listening socket */
430 static int socket_open_listen(struct sockaddr_in *my_addr)
434 server_fd = socket(AF_INET,SOCK_STREAM,0);
441 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
443 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
445 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
451 if (listen (server_fd, 5) < 0) {
456 fcntl(server_fd, F_SETFL, O_NONBLOCK);
461 /* start all multicast streams */
462 static void start_multicast(void)
467 struct sockaddr_in dest_addr;
468 int default_port, stream_index;
471 for(stream = first_stream; stream != NULL; stream = stream->next) {
472 if (stream->is_multicast) {
473 /* open the RTP connection */
474 snprintf(session_id, sizeof(session_id),
475 "%08x%08x", (int)random(), (int)random());
477 /* choose a port if none given */
478 if (stream->multicast_port == 0) {
479 stream->multicast_port = default_port;
483 dest_addr.sin_family = AF_INET;
484 dest_addr.sin_addr = stream->multicast_ip;
485 dest_addr.sin_port = htons(stream->multicast_port);
487 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
488 RTSP_PROTOCOL_RTP_UDP_MULTICAST);
492 if (open_input_stream(rtp_c, "") < 0) {
493 fprintf(stderr, "Could not open input stream for stream '%s'\n",
498 /* open each RTP stream */
499 for(stream_index = 0; stream_index < stream->nb_streams;
501 dest_addr.sin_port = htons(stream->multicast_port +
503 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
504 fprintf(stderr, "Could not open output stream '%s/streamid=%d'\n",
505 stream->filename, stream_index);
510 /* change state to send data */
511 rtp_c->state = HTTPSTATE_SEND_DATA;
516 /* main loop of the http server */
517 static int http_server(void)
519 int server_fd, ret, rtsp_server_fd, delay, delay1;
520 struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 2], *poll_entry;
521 HTTPContext *c, *c_next;
523 server_fd = socket_open_listen(&my_http_addr);
527 rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
528 if (rtsp_server_fd < 0)
531 http_log("ffserver started.\n");
533 start_children(first_feed);
535 first_http_ctx = NULL;
541 poll_entry = poll_table;
542 poll_entry->fd = server_fd;
543 poll_entry->events = POLLIN;
546 poll_entry->fd = rtsp_server_fd;
547 poll_entry->events = POLLIN;
550 /* wait for events on each HTTP handle */
557 case HTTPSTATE_SEND_HEADER:
558 case RTSPSTATE_SEND_REPLY:
559 case RTSPSTATE_SEND_PACKET:
560 c->poll_entry = poll_entry;
562 poll_entry->events = POLLOUT;
565 case HTTPSTATE_SEND_DATA_HEADER:
566 case HTTPSTATE_SEND_DATA:
567 case HTTPSTATE_SEND_DATA_TRAILER:
568 if (!c->is_packetized) {
569 /* for TCP, we output as much as we can (may need to put a limit) */
570 c->poll_entry = poll_entry;
572 poll_entry->events = POLLOUT;
575 /* not strictly correct, but currently cannot add
576 more than one fd in poll entry */
580 case HTTPSTATE_WAIT_REQUEST:
581 case HTTPSTATE_RECEIVE_DATA:
582 case HTTPSTATE_WAIT_FEED:
583 case RTSPSTATE_WAIT_REQUEST:
584 /* need to catch errors */
585 c->poll_entry = poll_entry;
587 poll_entry->events = POLLIN;/* Maybe this will work */
591 c->poll_entry = NULL;
592 delay1 = compute_send_delay(c);
596 case HTTPSTATE_WAIT_SHORT:
597 c->poll_entry = NULL;
598 delay1 = 10; /* one tick wait XXX: 10 ms assumed */
603 c->poll_entry = NULL;
609 /* wait for an event on one connection. We poll at least every
610 second to handle timeouts */
612 ret = poll(poll_table, poll_entry - poll_table, delay);
615 cur_time = gettime_ms();
617 if (need_to_start_children) {
618 need_to_start_children = 0;
619 start_children(first_feed);
622 /* now handle the events */
623 for(c = first_http_ctx; c != NULL; c = c_next) {
625 if (handle_connection(c) < 0) {
626 /* close and free the connection */
632 poll_entry = poll_table;
633 /* new HTTP connection request ? */
634 if (poll_entry->revents & POLLIN) {
635 new_connection(server_fd, 0);
638 /* new RTSP connection request ? */
639 if (poll_entry->revents & POLLIN) {
640 new_connection(rtsp_server_fd, 1);
645 /* start waiting for a new HTTP/RTSP request */
646 static void start_wait_request(HTTPContext *c, int is_rtsp)
648 c->buffer_ptr = c->buffer;
649 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
652 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
653 c->state = RTSPSTATE_WAIT_REQUEST;
655 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
656 c->state = HTTPSTATE_WAIT_REQUEST;
660 static void new_connection(int server_fd, int is_rtsp)
662 struct sockaddr_in from_addr;
664 HTTPContext *c = NULL;
666 len = sizeof(from_addr);
667 fd = accept(server_fd, (struct sockaddr *)&from_addr,
671 fcntl(fd, F_SETFL, O_NONBLOCK);
673 /* XXX: should output a warning page when coming
674 close to the connection limit */
675 if (nb_connections >= nb_max_connections)
678 /* add a new connection */
679 c = av_mallocz(sizeof(HTTPContext));
684 c->poll_entry = NULL;
685 c->from_addr = from_addr;
686 c->buffer_size = IOBUFFER_INIT_SIZE;
687 c->buffer = av_malloc(c->buffer_size);
691 c->next = first_http_ctx;
695 start_wait_request(c, is_rtsp);
707 static void close_connection(HTTPContext *c)
709 HTTPContext **cp, *c1;
711 AVFormatContext *ctx;
715 /* remove connection from list */
716 cp = &first_http_ctx;
717 while ((*cp) != NULL) {
726 /* remove references, if any (XXX: do it faster) */
727 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
732 /* remove connection associated resources */
736 /* close each frame parser */
737 for(i=0;i<c->fmt_in->nb_streams;i++) {
738 st = c->fmt_in->streams[i];
739 if (st->codec.codec) {
740 avcodec_close(&st->codec);
743 av_close_input_file(c->fmt_in);
746 /* free RTP output streams if any */
749 nb_streams = c->stream->nb_streams;
751 for(i=0;i<nb_streams;i++) {
754 av_write_trailer(ctx);
757 h = c->rtp_handles[i];
765 if (!c->last_packet_sent) {
768 if (url_open_dyn_buf(&ctx->pb) >= 0) {
769 av_write_trailer(ctx);
770 url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
775 for(i=0; i<ctx->nb_streams; i++)
776 av_free(ctx->streams[i]) ;
779 current_bandwidth -= c->stream->bandwidth;
780 av_freep(&c->pb_buffer);
781 av_freep(&c->packet_buffer);
787 static int handle_connection(HTTPContext *c)
792 case HTTPSTATE_WAIT_REQUEST:
793 case RTSPSTATE_WAIT_REQUEST:
795 if ((c->timeout - cur_time) < 0)
797 if (c->poll_entry->revents & (POLLERR | POLLHUP))
800 /* no need to read if no events */
801 if (!(c->poll_entry->revents & POLLIN))
805 len = read(c->fd, c->buffer_ptr, 1);
807 if (errno != EAGAIN && errno != EINTR)
809 } else if (len == 0) {
812 /* search for end of request. */
814 c->buffer_ptr += len;
816 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
817 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
818 /* request found : parse it and reply */
819 if (c->state == HTTPSTATE_WAIT_REQUEST) {
820 ret = http_parse_request(c);
822 ret = rtsp_parse_request(c);
826 } else if (ptr >= c->buffer_end) {
827 /* request too long: cannot do anything */
829 } else goto read_loop;
833 case HTTPSTATE_SEND_HEADER:
834 if (c->poll_entry->revents & (POLLERR | POLLHUP))
837 /* no need to write if no events */
838 if (!(c->poll_entry->revents & POLLOUT))
840 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
842 if (errno != EAGAIN && errno != EINTR) {
843 /* error : close connection */
844 av_freep(&c->pb_buffer);
848 c->buffer_ptr += len;
850 c->stream->bytes_served += len;
851 c->data_count += len;
852 if (c->buffer_ptr >= c->buffer_end) {
853 av_freep(&c->pb_buffer);
858 /* all the buffer was sent : synchronize to the incoming stream */
859 c->state = HTTPSTATE_SEND_DATA_HEADER;
860 c->buffer_ptr = c->buffer_end = c->buffer;
865 case HTTPSTATE_SEND_DATA:
866 case HTTPSTATE_SEND_DATA_HEADER:
867 case HTTPSTATE_SEND_DATA_TRAILER:
868 /* for packetized output, we consider we can always write (the
869 input streams sets the speed). It may be better to verify
870 that we do not rely too much on the kernel queues */
871 if (!c->is_packetized) {
872 if (c->poll_entry->revents & (POLLERR | POLLHUP))
875 /* no need to read if no events */
876 if (!(c->poll_entry->revents & POLLOUT))
879 if (http_send_data(c) < 0)
882 case HTTPSTATE_RECEIVE_DATA:
883 /* no need to read if no events */
884 if (c->poll_entry->revents & (POLLERR | POLLHUP))
886 if (!(c->poll_entry->revents & POLLIN))
888 if (http_receive_data(c) < 0)
891 case HTTPSTATE_WAIT_FEED:
892 /* no need to read if no events */
893 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
896 /* nothing to do, we'll be waken up by incoming feed packets */
900 /* if the delay expired, we can send new packets */
901 if (compute_send_delay(c) <= 0)
902 c->state = HTTPSTATE_SEND_DATA;
904 case HTTPSTATE_WAIT_SHORT:
905 /* just return back to send data */
906 c->state = HTTPSTATE_SEND_DATA;
909 case RTSPSTATE_SEND_REPLY:
910 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
911 av_freep(&c->pb_buffer);
914 /* no need to write if no events */
915 if (!(c->poll_entry->revents & POLLOUT))
917 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
919 if (errno != EAGAIN && errno != EINTR) {
920 /* error : close connection */
921 av_freep(&c->pb_buffer);
925 c->buffer_ptr += len;
926 c->data_count += len;
927 if (c->buffer_ptr >= c->buffer_end) {
928 /* all the buffer was sent : wait for a new request */
929 av_freep(&c->pb_buffer);
930 start_wait_request(c, 1);
934 case RTSPSTATE_SEND_PACKET:
935 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
936 av_freep(&c->packet_buffer);
939 /* no need to write if no events */
940 if (!(c->poll_entry->revents & POLLOUT))
942 len = write(c->fd, c->packet_buffer_ptr,
943 c->packet_buffer_end - c->packet_buffer_ptr);
945 if (errno != EAGAIN && errno != EINTR) {
946 /* error : close connection */
947 av_freep(&c->packet_buffer);
951 c->packet_buffer_ptr += len;
952 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
953 /* all the buffer was sent : wait for a new request */
954 av_freep(&c->packet_buffer);
955 c->state = RTSPSTATE_WAIT_REQUEST;
959 case HTTPSTATE_READY:
968 static int extract_rates(char *rates, int ratelen, const char *request)
972 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
973 if (strncasecmp(p, "Pragma:", 7) == 0) {
974 const char *q = p + 7;
976 while (*q && *q != '\n' && isspace(*q))
979 if (strncasecmp(q, "stream-switch-entry=", 20) == 0) {
985 memset(rates, 0xff, ratelen);
988 while (*q && *q != '\n' && *q != ':')
991 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2) {
995 if (stream_no < ratelen && stream_no >= 0) {
996 rates[stream_no] = rate_no;
999 while (*q && *q != '\n' && !isspace(*q))
1006 p = strchr(p, '\n');
1016 static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
1019 int best_bitrate = 100000000;
1022 for (i = 0; i < feed->nb_streams; i++) {
1023 AVCodecContext *feed_codec = &feed->streams[i]->codec;
1025 if (feed_codec->codec_id != codec->codec_id ||
1026 feed_codec->sample_rate != codec->sample_rate ||
1027 feed_codec->width != codec->width ||
1028 feed_codec->height != codec->height) {
1032 /* Potential stream */
1034 /* We want the fastest stream less than bit_rate, or the slowest
1035 * faster than bit_rate
1038 if (feed_codec->bit_rate <= bit_rate) {
1039 if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
1040 best_bitrate = feed_codec->bit_rate;
1044 if (feed_codec->bit_rate < best_bitrate) {
1045 best_bitrate = feed_codec->bit_rate;
1054 static int modify_current_stream(HTTPContext *c, char *rates)
1057 FFStream *req = c->stream;
1058 int action_required = 0;
1060 /* Not much we can do for a feed */
1064 for (i = 0; i < req->nb_streams; i++) {
1065 AVCodecContext *codec = &req->streams[i]->codec;
1069 c->switch_feed_streams[i] = req->feed_streams[i];
1072 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1075 /* Wants off or slow */
1076 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1078 /* This doesn't work well when it turns off the only stream! */
1079 c->switch_feed_streams[i] = -2;
1080 c->feed_streams[i] = -2;
1085 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1086 action_required = 1;
1089 return action_required;
1093 static void do_switch_stream(HTTPContext *c, int i)
1095 if (c->switch_feed_streams[i] >= 0) {
1097 c->feed_streams[i] = c->switch_feed_streams[i];
1100 /* Now update the stream */
1102 c->switch_feed_streams[i] = -1;
1105 /* XXX: factorize in utils.c ? */
1106 /* XXX: take care with different space meaning */
1107 static void skip_spaces(const char **pp)
1111 while (*p == ' ' || *p == '\t')
1116 static void get_word(char *buf, int buf_size, const char **pp)
1124 while (!isspace(*p) && *p != '\0') {
1125 if ((q - buf) < buf_size - 1)
1134 static int validate_acl(FFStream *stream, HTTPContext *c)
1136 enum IPAddressAction last_action = IP_DENY;
1138 struct in_addr *src = &c->from_addr.sin_addr;
1139 unsigned long src_addr = ntohl(src->s_addr);
1141 for (acl = stream->acl; acl; acl = acl->next) {
1142 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr) {
1143 return (acl->action == IP_ALLOW) ? 1 : 0;
1145 last_action = acl->action;
1148 /* Nothing matched, so return not the last action */
1149 return (last_action == IP_DENY) ? 1 : 0;
1152 /* compute the real filename of a file by matching it without its
1153 extensions to all the stream filenames */
1154 static void compute_real_filename(char *filename, int max_size)
1161 /* compute filename by matching without the file extensions */
1162 pstrcpy(file1, sizeof(file1), filename);
1163 p = strrchr(file1, '.');
1166 for(stream = first_stream; stream != NULL; stream = stream->next) {
1167 pstrcpy(file2, sizeof(file2), stream->filename);
1168 p = strrchr(file2, '.');
1171 if (!strcmp(file1, file2)) {
1172 pstrcpy(filename, max_size, stream->filename);
1187 /* parse http request and prepare header */
1188 static int http_parse_request(HTTPContext *c)
1192 enum RedirType redir_type;
1194 char info[1024], *filename;
1198 const char *mime_type;
1202 char *useragent = 0;
1205 get_word(cmd, sizeof(cmd), (const char **)&p);
1206 pstrcpy(c->method, sizeof(c->method), cmd);
1208 if (!strcmp(cmd, "GET"))
1210 else if (!strcmp(cmd, "POST"))
1215 get_word(url, sizeof(url), (const char **)&p);
1216 pstrcpy(c->url, sizeof(c->url), url);
1218 get_word(protocol, sizeof(protocol), (const char **)&p);
1219 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1222 pstrcpy(c->protocol, sizeof(c->protocol), protocol);
1224 /* find the filename and the optional info string in the request */
1231 pstrcpy(info, sizeof(info), p);
1237 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1238 if (strncasecmp(p, "User-Agent:", 11) == 0) {
1240 if (*useragent && *useragent != '\n' && isspace(*useragent))
1244 p = strchr(p, '\n');
1251 redir_type = REDIR_NONE;
1252 if (match_ext(filename, "asx")) {
1253 redir_type = REDIR_ASX;
1254 filename[strlen(filename)-1] = 'f';
1255 } else if (match_ext(filename, "asf") &&
1256 (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1257 /* if this isn't WMP or lookalike, return the redirector file */
1258 redir_type = REDIR_ASF;
1259 } else if (match_ext(filename, "rpm,ram")) {
1260 redir_type = REDIR_RAM;
1261 strcpy(filename + strlen(filename)-2, "m");
1262 } else if (match_ext(filename, "rtsp")) {
1263 redir_type = REDIR_RTSP;
1264 compute_real_filename(filename, sizeof(url) - 1);
1265 } else if (match_ext(filename, "sdp")) {
1266 redir_type = REDIR_SDP;
1267 compute_real_filename(filename, sizeof(url) - 1);
1270 stream = first_stream;
1271 while (stream != NULL) {
1272 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1274 stream = stream->next;
1276 if (stream == NULL) {
1277 sprintf(msg, "File '%s' not found", url);
1282 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1283 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1285 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1286 c->http_error = 301;
1288 q += sprintf(q, "HTTP/1.0 301 Moved\r\n");
1289 q += sprintf(q, "Location: %s\r\n", stream->feed_filename);
1290 q += sprintf(q, "Content-type: text/html\r\n");
1291 q += sprintf(q, "\r\n");
1292 q += sprintf(q, "<html><head><title>Moved</title></head><body>\r\n");
1293 q += sprintf(q, "You should be <a href=\"%s\">redirected</a>.\r\n", stream->feed_filename);
1294 q += sprintf(q, "</body></html>\r\n");
1296 /* prepare output buffer */
1297 c->buffer_ptr = c->buffer;
1299 c->state = HTTPSTATE_SEND_HEADER;
1303 /* If this is WMP, get the rate information */
1304 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1305 if (modify_current_stream(c, ratebuf)) {
1306 for (i = 0; i < sizeof(c->feed_streams) / sizeof(c->feed_streams[0]); i++) {
1307 if (c->switch_feed_streams[i] >= 0)
1308 do_switch_stream(c, i);
1313 if (post == 0 && stream->stream_type == STREAM_TYPE_LIVE) {
1314 current_bandwidth += stream->bandwidth;
1317 if (post == 0 && max_bandwidth < current_bandwidth) {
1318 c->http_error = 200;
1320 q += sprintf(q, "HTTP/1.0 200 Server too busy\r\n");
1321 q += sprintf(q, "Content-type: text/html\r\n");
1322 q += sprintf(q, "\r\n");
1323 q += sprintf(q, "<html><head><title>Too busy</title></head><body>\r\n");
1324 q += sprintf(q, "The server is too busy to serve your request at this time.<p>\r\n");
1325 q += sprintf(q, "The bandwidth being served (including your stream) is %dkbit/sec, and this exceeds the limit of %dkbit/sec\r\n",
1326 current_bandwidth, max_bandwidth);
1327 q += sprintf(q, "</body></html>\r\n");
1329 /* prepare output buffer */
1330 c->buffer_ptr = c->buffer;
1332 c->state = HTTPSTATE_SEND_HEADER;
1336 if (redir_type != REDIR_NONE) {
1339 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1340 if (strncasecmp(p, "Host:", 5) == 0) {
1344 p = strchr(p, '\n');
1355 while (isspace(*hostinfo))
1358 eoh = strchr(hostinfo, '\n');
1360 if (eoh[-1] == '\r')
1363 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1364 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1365 hostbuf[eoh - hostinfo] = 0;
1367 c->http_error = 200;
1369 switch(redir_type) {
1371 q += sprintf(q, "HTTP/1.0 200 ASX Follows\r\n");
1372 q += sprintf(q, "Content-type: video/x-ms-asf\r\n");
1373 q += sprintf(q, "\r\n");
1374 q += sprintf(q, "<ASX Version=\"3\">\r\n");
1375 q += sprintf(q, "<!-- Autogenerated by ffserver -->\r\n");
1376 q += sprintf(q, "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n",
1377 hostbuf, filename, info);
1378 q += sprintf(q, "</ASX>\r\n");
1381 q += sprintf(q, "HTTP/1.0 200 RAM Follows\r\n");
1382 q += sprintf(q, "Content-type: audio/x-pn-realaudio\r\n");
1383 q += sprintf(q, "\r\n");
1384 q += sprintf(q, "# Autogenerated by ffserver\r\n");
1385 q += sprintf(q, "http://%s/%s%s\r\n",
1386 hostbuf, filename, info);
1389 q += sprintf(q, "HTTP/1.0 200 ASF Redirect follows\r\n");
1390 q += sprintf(q, "Content-type: video/x-ms-asf\r\n");
1391 q += sprintf(q, "\r\n");
1392 q += sprintf(q, "[Reference]\r\n");
1393 q += sprintf(q, "Ref1=http://%s/%s%s\r\n",
1394 hostbuf, filename, info);
1398 char hostname[256], *p;
1399 /* extract only hostname */
1400 pstrcpy(hostname, sizeof(hostname), hostbuf);
1401 p = strrchr(hostname, ':');
1404 q += sprintf(q, "HTTP/1.0 200 RTSP Redirect follows\r\n");
1405 /* XXX: incorrect mime type ? */
1406 q += sprintf(q, "Content-type: application/x-rtsp\r\n");
1407 q += sprintf(q, "\r\n");
1408 q += sprintf(q, "rtsp://%s:%d/%s\r\n",
1409 hostname, ntohs(my_rtsp_addr.sin_port),
1416 int sdp_data_size, len;
1417 struct sockaddr_in my_addr;
1419 q += sprintf(q, "HTTP/1.0 200 OK\r\n");
1420 q += sprintf(q, "Content-type: application/sdp\r\n");
1421 q += sprintf(q, "\r\n");
1423 len = sizeof(my_addr);
1424 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
1426 /* XXX: should use a dynamic buffer */
1427 sdp_data_size = prepare_sdp_description(stream,
1430 if (sdp_data_size > 0) {
1431 memcpy(q, sdp_data, sdp_data_size);
1443 /* prepare output buffer */
1444 c->buffer_ptr = c->buffer;
1446 c->state = HTTPSTATE_SEND_HEADER;
1452 sprintf(msg, "ASX/RAM file not handled");
1456 stream->conns_served++;
1458 /* XXX: add there authenticate and IP match */
1461 /* if post, it means a feed is being sent */
1462 if (!stream->is_feed) {
1463 /* However it might be a status report from WMP! Lets log the data
1464 * as it might come in handy one day
1469 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1470 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1474 if (strncasecmp(p, "Pragma: client-id=", 18) == 0) {
1475 client_id = strtol(p + 18, 0, 10);
1477 p = strchr(p, '\n');
1485 char *eol = strchr(logline, '\n');
1490 if (eol[-1] == '\r')
1492 http_log("%.*s\n", eol - logline, logline);
1493 c->suppress_log = 1;
1498 http_log("\nGot request:\n%s\n", c->buffer);
1501 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1504 /* Now we have to find the client_id */
1505 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1506 if (wmpc->wmp_client_id == client_id)
1511 if (modify_current_stream(wmpc, ratebuf)) {
1512 wmpc->switch_pending = 1;
1517 sprintf(msg, "POST command not handled");
1521 if (http_start_receive_data(c) < 0) {
1522 sprintf(msg, "could not open feed");
1526 c->state = HTTPSTATE_RECEIVE_DATA;
1531 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0) {
1532 http_log("\nGot request:\n%s\n", c->buffer);
1536 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1539 /* open input stream */
1540 if (open_input_stream(c, info) < 0) {
1541 sprintf(msg, "Input stream corresponding to '%s' not found", url);
1545 /* prepare http header */
1547 q += sprintf(q, "HTTP/1.0 200 OK\r\n");
1548 mime_type = c->stream->fmt->mime_type;
1550 mime_type = "application/x-octet_stream";
1551 q += sprintf(q, "Pragma: no-cache\r\n");
1553 /* for asf, we need extra headers */
1554 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1555 /* Need to allocate a client id */
1557 c->wmp_client_id = random() & 0x7fffffff;
1559 q += sprintf(q, "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);
1561 q += sprintf(q, "Content-Type: %s\r\n", mime_type);
1562 q += sprintf(q, "\r\n");
1564 /* prepare output buffer */
1566 c->buffer_ptr = c->buffer;
1568 c->state = HTTPSTATE_SEND_HEADER;
1571 c->http_error = 404;
1573 q += sprintf(q, "HTTP/1.0 404 Not Found\r\n");
1574 q += sprintf(q, "Content-type: %s\r\n", "text/html");
1575 q += sprintf(q, "\r\n");
1576 q += sprintf(q, "<HTML>\n");
1577 q += sprintf(q, "<HEAD><TITLE>404 Not Found</TITLE></HEAD>\n");
1578 q += sprintf(q, "<BODY>%s</BODY>\n", msg);
1579 q += sprintf(q, "</HTML>\n");
1581 /* prepare output buffer */
1582 c->buffer_ptr = c->buffer;
1584 c->state = HTTPSTATE_SEND_HEADER;
1588 c->http_error = 200; /* horrible : we use this value to avoid
1589 going to the send data state */
1590 c->state = HTTPSTATE_SEND_HEADER;
1594 static void fmt_bytecount(ByteIOContext *pb, int64_t count)
1596 static const char *suffix = " kMGTP";
1599 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++) {
1602 url_fprintf(pb, "%lld%c", count, *s);
1605 static void compute_stats(HTTPContext *c)
1612 ByteIOContext pb1, *pb = &pb1;
1614 if (url_open_dyn_buf(pb) < 0) {
1615 /* XXX: return an error ? */
1616 c->buffer_ptr = c->buffer;
1617 c->buffer_end = c->buffer;
1621 url_fprintf(pb, "HTTP/1.0 200 OK\r\n");
1622 url_fprintf(pb, "Content-type: %s\r\n", "text/html");
1623 url_fprintf(pb, "Pragma: no-cache\r\n");
1624 url_fprintf(pb, "\r\n");
1626 url_fprintf(pb, "<HEAD><TITLE>FFServer Status</TITLE>\n");
1627 if (c->stream->feed_filename) {
1628 url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
1630 url_fprintf(pb, "</HEAD>\n<BODY>");
1631 url_fprintf(pb, "<H1>FFServer Status</H1>\n");
1633 url_fprintf(pb, "<H2>Available Streams</H2>\n");
1634 url_fprintf(pb, "<TABLE cellspacing=0 cellpadding=4>\n");
1635 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");
1636 stream = first_stream;
1637 while (stream != NULL) {
1638 char sfilename[1024];
1641 if (stream->feed != stream) {
1642 pstrcpy(sfilename, sizeof(sfilename) - 10, stream->filename);
1643 eosf = sfilename + strlen(sfilename);
1644 if (eosf - sfilename >= 4) {
1645 if (strcmp(eosf - 4, ".asf") == 0) {
1646 strcpy(eosf - 4, ".asx");
1647 } else if (strcmp(eosf - 3, ".rm") == 0) {
1648 strcpy(eosf - 3, ".ram");
1649 } else if (stream->fmt == &rtp_mux) {
1650 /* generate a sample RTSP director if
1651 unicast. Generate an SDP redirector if
1653 eosf = strrchr(sfilename, '.');
1655 eosf = sfilename + strlen(sfilename);
1656 if (stream->is_multicast)
1657 strcpy(eosf, ".sdp");
1659 strcpy(eosf, ".rtsp");
1663 url_fprintf(pb, "<TR><TD><A HREF=\"/%s\">%s</A> ",
1664 sfilename, stream->filename);
1665 url_fprintf(pb, "<td align=right> %d <td align=right> ",
1666 stream->conns_served);
1667 fmt_bytecount(pb, stream->bytes_served);
1668 switch(stream->stream_type) {
1669 case STREAM_TYPE_LIVE:
1671 int audio_bit_rate = 0;
1672 int video_bit_rate = 0;
1673 const char *audio_codec_name = "";
1674 const char *video_codec_name = "";
1675 const char *audio_codec_name_extra = "";
1676 const char *video_codec_name_extra = "";
1678 for(i=0;i<stream->nb_streams;i++) {
1679 AVStream *st = stream->streams[i];
1680 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
1681 switch(st->codec.codec_type) {
1682 case CODEC_TYPE_AUDIO:
1683 audio_bit_rate += st->codec.bit_rate;
1685 if (*audio_codec_name)
1686 audio_codec_name_extra = "...";
1687 audio_codec_name = codec->name;
1690 case CODEC_TYPE_VIDEO:
1691 video_bit_rate += st->codec.bit_rate;
1693 if (*video_codec_name)
1694 video_codec_name_extra = "...";
1695 video_codec_name = codec->name;
1702 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",
1705 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
1706 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
1708 url_fprintf(pb, "<TD>%s", stream->feed->filename);
1710 url_fprintf(pb, "<TD>%s", stream->feed_filename);
1712 url_fprintf(pb, "\n");
1716 url_fprintf(pb, "<TD align=center> - <TD align=right> - <TD align=right> - <td><td align=right> - <TD>\n");
1720 stream = stream->next;
1722 url_fprintf(pb, "</TABLE>\n");
1724 stream = first_stream;
1725 while (stream != NULL) {
1726 if (stream->feed == stream) {
1727 url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
1729 url_fprintf(pb, "Running as pid %d.\n", stream->pid);
1731 #if defined(linux) && !defined(CONFIG_NOCUTILS)
1736 /* This is somewhat linux specific I guess */
1737 snprintf(ps_cmd, sizeof(ps_cmd),
1738 "ps -o \"%%cpu,cputime\" --no-headers %d",
1741 pid_stat = popen(ps_cmd, "r");
1746 if (fscanf(pid_stat, "%10s %64s", cpuperc,
1748 url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
1756 url_fprintf(pb, "<p>");
1758 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");
1760 for (i = 0; i < stream->nb_streams; i++) {
1761 AVStream *st = stream->streams[i];
1762 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
1763 const char *type = "unknown";
1764 char parameters[64];
1768 switch(st->codec.codec_type) {
1769 case CODEC_TYPE_AUDIO:
1772 case CODEC_TYPE_VIDEO:
1774 sprintf(parameters, "%dx%d, q=%d-%d, fps=%d", st->codec.width, st->codec.height,
1775 st->codec.qmin, st->codec.qmax, st->codec.frame_rate / st->codec.frame_rate_base);
1780 url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
1781 i, type, st->codec.bit_rate/1000, codec ? codec->name : "", parameters);
1783 url_fprintf(pb, "</table>\n");
1786 stream = stream->next;
1792 AVCodecContext *enc;
1796 stream = first_feed;
1797 while (stream != NULL) {
1798 url_fprintf(pb, "<H1>Feed '%s'</H1>\n", stream->filename);
1799 url_fprintf(pb, "<TABLE>\n");
1800 url_fprintf(pb, "<TR><TD>Parameters<TD>Frame count<TD>Size<TD>Avg bitrate (kbits/s)\n");
1801 for(i=0;i<stream->nb_streams;i++) {
1802 AVStream *st = stream->streams[i];
1803 FeedData *fdata = st->priv_data;
1806 avcodec_string(buf, sizeof(buf), enc);
1807 avg = fdata->avg_frame_size * (float)enc->rate * 8.0;
1808 if (enc->codec->type == CODEC_TYPE_AUDIO && enc->frame_size > 0)
1809 avg /= enc->frame_size;
1810 url_fprintf(pb, "<TR><TD>%s <TD> %d <TD> %Ld <TD> %0.1f\n",
1811 buf, enc->frame_number, fdata->data_count, avg / 1000.0);
1813 url_fprintf(pb, "</TABLE>\n");
1814 stream = stream->next_feed;
1819 /* connection status */
1820 url_fprintf(pb, "<H2>Connection Status</H2>\n");
1822 url_fprintf(pb, "Number of connections: %d / %d<BR>\n",
1823 nb_connections, nb_max_connections);
1825 url_fprintf(pb, "Bandwidth in use: %dk / %dk<BR>\n",
1826 current_bandwidth, max_bandwidth);
1828 url_fprintf(pb, "<TABLE>\n");
1829 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");
1830 c1 = first_http_ctx;
1832 while (c1 != NULL) {
1838 for (j = 0; j < c1->stream->nb_streams; j++) {
1839 if (!c1->stream->feed) {
1840 bitrate += c1->stream->streams[j]->codec.bit_rate;
1842 if (c1->feed_streams[j] >= 0) {
1843 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec.bit_rate;
1850 p = inet_ntoa(c1->from_addr.sin_addr);
1851 url_fprintf(pb, "<TR><TD><B>%d</B><TD>%s%s<TD>%s<TD>%s<TD>%s<td align=right>",
1853 c1->stream ? c1->stream->filename : "",
1854 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
1857 http_state[c1->state]);
1858 fmt_bytecount(pb, bitrate);
1859 url_fprintf(pb, "<td align=right>");
1860 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
1861 url_fprintf(pb, "<td align=right>");
1862 fmt_bytecount(pb, c1->data_count);
1863 url_fprintf(pb, "\n");
1866 url_fprintf(pb, "</TABLE>\n");
1871 url_fprintf(pb, "<HR size=1 noshade>Generated at %s", p);
1872 url_fprintf(pb, "</BODY>\n</HTML>\n");
1874 len = url_close_dyn_buf(pb, &c->pb_buffer);
1875 c->buffer_ptr = c->pb_buffer;
1876 c->buffer_end = c->pb_buffer + len;
1879 /* check if the parser needs to be opened for stream i */
1880 static void open_parser(AVFormatContext *s, int i)
1882 AVStream *st = s->streams[i];
1885 if (!st->codec.codec) {
1886 codec = avcodec_find_decoder(st->codec.codec_id);
1887 if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) {
1888 st->codec.parse_only = 1;
1889 if (avcodec_open(&st->codec, codec) < 0) {
1890 st->codec.parse_only = 0;
1896 static int open_input_stream(HTTPContext *c, const char *info)
1899 char input_filename[1024];
1904 /* find file name */
1905 if (c->stream->feed) {
1906 strcpy(input_filename, c->stream->feed->feed_filename);
1907 buf_size = FFM_PACKET_SIZE;
1908 /* compute position (absolute time) */
1909 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1910 stream_pos = parse_date(buf, 0);
1911 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
1912 int prebuffer = strtol(buf, 0, 10);
1913 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
1915 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
1918 strcpy(input_filename, c->stream->feed_filename);
1920 /* compute position (relative time) */
1921 if (find_info_tag(buf, sizeof(buf), "date", info)) {
1922 stream_pos = parse_date(buf, 1);
1927 if (input_filename[0] == '\0')
1931 { time_t when = stream_pos / 1000000;
1932 http_log("Stream pos = %lld, time=%s", stream_pos, ctime(&when));
1937 if (av_open_input_file(&s, input_filename, NULL, buf_size, NULL) < 0) {
1938 http_log("%s not found", input_filename);
1943 /* open each parser */
1944 for(i=0;i<s->nb_streams;i++)
1947 /* choose stream as clock source (we favorize video stream if
1948 present) for packet sending */
1949 c->pts_stream_index = 0;
1950 for(i=0;i<c->stream->nb_streams;i++) {
1951 if (c->pts_stream_index == 0 &&
1952 c->stream->streams[i]->codec.codec_type == CODEC_TYPE_VIDEO) {
1953 c->pts_stream_index = i;
1957 if (c->fmt_in->iformat->read_seek) {
1958 c->fmt_in->iformat->read_seek(c->fmt_in, stream_pos);
1960 /* set the start time (needed for maxtime and RTP packet timing) */
1961 c->start_time = cur_time;
1962 c->first_pts = AV_NOPTS_VALUE;
1966 /* currently desactivated because the new PTS handling is not
1968 //#define AV_READ_FRAME
1969 #ifdef AV_READ_FRAME
1971 /* XXX: generalize that in ffmpeg for picture/audio/data. Currently
1972 the return packet MUST NOT be freed */
1973 int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1976 int len, ret, old_nb_streams, i;
1978 /* see if remaining frames must be parsed */
1980 if (s->cur_len > 0) {
1981 st = s->streams[s->cur_pkt.stream_index];
1982 len = avcodec_parse_frame(&st->codec, &pkt->data, &pkt->size,
1983 s->cur_ptr, s->cur_len);
1985 /* error: get next packet */
1991 /* init pts counter if not done */
1992 if (st->pts.den == 0) {
1993 switch(st->codec.codec_type) {
1994 case CODEC_TYPE_AUDIO:
1995 st->pts_incr = (int64_t)s->pts_den;
1996 av_frac_init(&st->pts, st->pts.val, 0,
1997 (int64_t)s->pts_num * st->codec.sample_rate);
1999 case CODEC_TYPE_VIDEO:
2000 st->pts_incr = (int64_t)s->pts_den * st->codec.frame_rate_base;
2001 av_frac_init(&st->pts, st->pts.val, 0,
2002 (int64_t)s->pts_num * st->codec.frame_rate);
2009 /* a frame was read: return it */
2010 pkt->pts = st->pts.val;
2012 printf("add pts=%Lx num=%Lx den=%Lx incr=%Lx\n",
2013 st->pts.val, st->pts.num, st->pts.den, st->pts_incr);
2015 switch(st->codec.codec_type) {
2016 case CODEC_TYPE_AUDIO:
2017 av_frac_add(&st->pts, st->pts_incr * st->codec.frame_size);
2019 case CODEC_TYPE_VIDEO:
2020 av_frac_add(&st->pts, st->pts_incr);
2025 pkt->stream_index = s->cur_pkt.stream_index;
2026 /* we use the codec indication because it is
2027 more accurate than the demux flags */
2029 if (st->codec.coded_frame->key_frame)
2030 pkt->flags |= PKT_FLAG_KEY;
2035 /* free previous packet */
2036 av_free_packet(&s->cur_pkt);
2038 old_nb_streams = s->nb_streams;
2039 ret = av_read_packet(s, &s->cur_pkt);
2042 /* open parsers for each new streams */
2043 for(i = old_nb_streams; i < s->nb_streams; i++)
2045 st = s->streams[s->cur_pkt.stream_index];
2047 /* update current pts (XXX: dts handling) from packet, or
2048 use current pts if none given */
2049 if (s->cur_pkt.pts != AV_NOPTS_VALUE) {
2050 av_frac_set(&st->pts, s->cur_pkt.pts);
2052 s->cur_pkt.pts = st->pts.val;
2054 if (!st->codec.codec) {
2055 /* no codec opened: just return the raw packet */
2058 /* no codec opened: just update the pts by considering we
2059 have one frame and free the packet */
2060 if (st->pts.den == 0) {
2061 switch(st->codec.codec_type) {
2062 case CODEC_TYPE_AUDIO:
2063 st->pts_incr = (int64_t)s->pts_den * st->codec.frame_size;
2064 av_frac_init(&st->pts, st->pts.val, 0,
2065 (int64_t)s->pts_num * st->codec.sample_rate);
2067 case CODEC_TYPE_VIDEO:
2068 st->pts_incr = (int64_t)s->pts_den * st->codec.frame_rate_base;
2069 av_frac_init(&st->pts, st->pts.val, 0,
2070 (int64_t)s->pts_num * st->codec.frame_rate);
2076 av_frac_add(&st->pts, st->pts_incr);
2079 s->cur_ptr = s->cur_pkt.data;
2080 s->cur_len = s->cur_pkt.size;
2086 static int compute_send_delay(HTTPContext *c)
2088 int64_t cur_pts, delta_pts, next_pts;
2091 /* compute current pts value from system time */
2092 cur_pts = ((int64_t)(cur_time - c->start_time) * c->fmt_in->pts_den) /
2093 (c->fmt_in->pts_num * 1000LL);
2094 /* compute the delta from the stream we choose as
2095 main clock (we do that to avoid using explicit
2096 buffers to do exact packet reordering for each
2098 /* XXX: really need to fix the number of streams */
2099 if (c->pts_stream_index >= c->fmt_in->nb_streams)
2102 next_pts = c->fmt_in->streams[c->pts_stream_index]->pts.val;
2103 delta_pts = next_pts - cur_pts;
2104 if (delta_pts <= 0) {
2107 delay1 = (delta_pts * 1000 * c->fmt_in->pts_num) / c->fmt_in->pts_den;
2113 /* just fall backs */
2114 static int av_read_frame(AVFormatContext *s, AVPacket *pkt)
2116 return av_read_packet(s, pkt);
2119 static int compute_send_delay(HTTPContext *c)
2121 int datarate = 8 * get_longterm_datarate(&c->datarate, c->data_count);
2126 if (datarate > c->stream->bandwidth * 2000) {
2129 if (!c->stream->feed && c->first_pts!=AV_NOPTS_VALUE) {
2130 time_pts = ((int64_t)(cur_time - c->start_time) * c->fmt_in->pts_den) /
2131 ((int64_t) c->fmt_in->pts_num*1000);
2132 delta_pts = c->cur_pts - time_pts;
2133 m_delay = (delta_pts * 1000 * c->fmt_in->pts_num) / c->fmt_in->pts_den;
2134 return m_delay>0 ? m_delay : 0;
2142 static int http_prepare_data(HTTPContext *c)
2145 AVFormatContext *ctx;
2147 av_freep(&c->pb_buffer);
2149 case HTTPSTATE_SEND_DATA_HEADER:
2150 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
2151 pstrcpy(c->fmt_ctx.author, sizeof(c->fmt_ctx.author),
2153 pstrcpy(c->fmt_ctx.comment, sizeof(c->fmt_ctx.comment),
2154 c->stream->comment);
2155 pstrcpy(c->fmt_ctx.copyright, sizeof(c->fmt_ctx.copyright),
2156 c->stream->copyright);
2157 pstrcpy(c->fmt_ctx.title, sizeof(c->fmt_ctx.title),
2160 /* open output stream by using specified codecs */
2161 c->fmt_ctx.oformat = c->stream->fmt;
2162 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2163 for(i=0;i<c->fmt_ctx.nb_streams;i++) {
2165 st = av_mallocz(sizeof(AVStream));
2166 c->fmt_ctx.streams[i] = st;
2167 /* if file or feed, then just take streams from FFStream struct */
2168 if (!c->stream->feed ||
2169 c->stream->feed == c->stream)
2170 memcpy(st, c->stream->streams[i], sizeof(AVStream));
2172 memcpy(st, c->stream->feed->streams[c->stream->feed_streams[i]],
2174 st->codec.frame_number = 0; /* XXX: should be done in
2175 AVStream, not in codec */
2176 /* I'm pretty sure that this is not correct...
2177 * However, without it, we crash
2179 st->codec.coded_frame = &dummy_frame;
2181 c->got_key_frame = 0;
2183 /* prepare header and save header data in a stream */
2184 if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2185 /* XXX: potential leak */
2188 c->fmt_ctx.pb.is_streamed = 1;
2190 av_set_parameters(&c->fmt_ctx, NULL);
2191 av_write_header(&c->fmt_ctx);
2193 len = url_close_dyn_buf(&c->fmt_ctx.pb, &c->pb_buffer);
2194 c->buffer_ptr = c->pb_buffer;
2195 c->buffer_end = c->pb_buffer + len;
2197 c->state = HTTPSTATE_SEND_DATA;
2198 c->last_packet_sent = 0;
2200 case HTTPSTATE_SEND_DATA:
2201 /* find a new packet */
2205 /* read a packet from the input stream */
2206 if (c->stream->feed) {
2207 ffm_set_write_index(c->fmt_in,
2208 c->stream->feed->feed_write_index,
2209 c->stream->feed->feed_size);
2212 if (c->stream->max_time &&
2213 c->stream->max_time + c->start_time - cur_time < 0) {
2214 /* We have timed out */
2215 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2217 if (1 || c->is_packetized) {
2218 if (compute_send_delay(c) > 0) {
2219 c->state = HTTPSTATE_WAIT;
2220 return 1; /* state changed */
2224 if (av_read_frame(c->fmt_in, &pkt) < 0) {
2225 if (c->stream->feed && c->stream->feed->feed_opened) {
2226 /* if coming from feed, it means we reached the end of the
2227 ffm file, so must wait for more data */
2228 c->state = HTTPSTATE_WAIT_FEED;
2229 return 1; /* state changed */
2231 if (c->stream->loop) {
2232 av_close_input_file(c->fmt_in);
2234 if (open_input_stream(c, "") < 0)
2239 /* must send trailer now because eof or error */
2240 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2244 /* update first pts if needed */
2245 if (c->first_pts == AV_NOPTS_VALUE) {
2246 c->first_pts = pkt.pts;
2247 c->start_time = cur_time;
2249 c->cur_pts = pkt.pts;
2250 /* send it to the appropriate stream */
2251 if (c->stream->feed) {
2252 /* if coming from a feed, select the right stream */
2253 if (c->switch_pending) {
2254 c->switch_pending = 0;
2255 for(i=0;i<c->stream->nb_streams;i++) {
2256 if (c->switch_feed_streams[i] == pkt.stream_index) {
2257 if (pkt.flags & PKT_FLAG_KEY) {
2258 do_switch_stream(c, i);
2261 if (c->switch_feed_streams[i] >= 0) {
2262 c->switch_pending = 1;
2266 for(i=0;i<c->stream->nb_streams;i++) {
2267 if (c->feed_streams[i] == pkt.stream_index) {
2268 pkt.stream_index = i;
2269 if (pkt.flags & PKT_FLAG_KEY) {
2270 c->got_key_frame |= 1 << i;
2272 /* See if we have all the key frames, then
2273 * we start to send. This logic is not quite
2274 * right, but it works for the case of a
2275 * single video stream with one or more
2276 * audio streams (for which every frame is
2277 * typically a key frame).
2279 if (!c->stream->send_on_key ||
2280 ((c->got_key_frame + 1) >> c->stream->nb_streams)) {
2286 AVCodecContext *codec;
2289 /* specific handling for RTP: we use several
2290 output stream (one for each RTP
2291 connection). XXX: need more abstract handling */
2292 if (c->is_packetized) {
2293 c->packet_stream_index = pkt.stream_index;
2294 ctx = c->rtp_ctx[c->packet_stream_index];
2296 av_free_packet(&pkt);
2299 codec = &ctx->streams[0]->codec;
2300 /* only one stream per RTP connection */
2301 pkt.stream_index = 0;
2305 codec = &ctx->streams[pkt.stream_index]->codec;
2308 codec->coded_frame->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);
2311 if (codec->codec_type == CODEC_TYPE_AUDIO) {
2312 codec->frame_size = (codec->sample_rate * pkt.duration + 500000) / 1000000;
2313 /* printf("Calculated size %d, from sr %d, duration %d\n", codec->frame_size, codec->sample_rate, pkt.duration); */
2317 if (c->is_packetized) {
2318 int max_packet_size;
2319 if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP)
2320 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2322 max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]);
2323 ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size);
2324 c->packet_byte_count = 0;
2325 c->packet_start_time_us = av_gettime();
2327 ret = url_open_dyn_buf(&ctx->pb);
2330 /* XXX: potential leak */
2333 if (av_write_frame(ctx, pkt.stream_index, pkt.data, pkt.size)) {
2334 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2337 len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
2338 c->buffer_ptr = c->pb_buffer;
2339 c->buffer_end = c->pb_buffer + len;
2341 codec->frame_number++;
2343 #ifndef AV_READ_FRAME
2344 av_free_packet(&pkt);
2351 case HTTPSTATE_SEND_DATA_TRAILER:
2352 /* last packet test ? */
2353 if (c->last_packet_sent || c->is_packetized)
2356 /* prepare header */
2357 if (url_open_dyn_buf(&ctx->pb) < 0) {
2358 /* XXX: potential leak */
2361 av_write_trailer(ctx);
2362 len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer);
2363 c->buffer_ptr = c->pb_buffer;
2364 c->buffer_end = c->pb_buffer + len;
2366 c->last_packet_sent = 1;
2373 #define SHORT_TERM_BANDWIDTH 8000000
2375 /* should convert the format at the same time */
2376 /* send data starting at c->buffer_ptr to the output connection
2377 (either UDP or TCP connection) */
2378 static int http_send_data(HTTPContext *c)
2383 if (c->buffer_ptr >= c->buffer_end) {
2384 ret = http_prepare_data(c);
2387 else if (ret != 0) {
2388 /* state change requested */
2392 if (c->is_packetized) {
2393 /* RTP data output */
2394 len = c->buffer_end - c->buffer_ptr;
2396 /* fail safe - should never happen */
2398 c->buffer_ptr = c->buffer_end;
2401 len = (c->buffer_ptr[0] << 24) |
2402 (c->buffer_ptr[1] << 16) |
2403 (c->buffer_ptr[2] << 8) |
2405 if (len > (c->buffer_end - c->buffer_ptr))
2408 if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP) {
2409 /* RTP packets are sent inside the RTSP TCP connection */
2410 ByteIOContext pb1, *pb = &pb1;
2411 int interleaved_index, size;
2413 HTTPContext *rtsp_c;
2416 /* if no RTSP connection left, error */
2419 /* if already sending something, then wait. */
2420 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST) {
2423 if (url_open_dyn_buf(pb) < 0)
2425 interleaved_index = c->packet_stream_index * 2;
2426 /* RTCP packets are sent at odd indexes */
2427 if (c->buffer_ptr[1] == 200)
2428 interleaved_index++;
2429 /* write RTSP TCP header */
2431 header[1] = interleaved_index;
2432 header[2] = len >> 8;
2434 put_buffer(pb, header, 4);
2435 /* write RTP packet data */
2437 put_buffer(pb, c->buffer_ptr, len);
2438 size = url_close_dyn_buf(pb, &c->packet_buffer);
2439 /* prepare asynchronous TCP sending */
2440 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2441 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2442 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2444 /* send RTP packet directly in UDP */
2446 /* short term bandwidth limitation */
2447 dt = av_gettime() - c->packet_start_time_us;
2451 if ((c->packet_byte_count + len) * (int64_t)1000000 >=
2452 (SHORT_TERM_BANDWIDTH / 8) * (int64_t)dt) {
2453 /* bandwidth overflow : wait at most one tick and retry */
2454 c->state = HTTPSTATE_WAIT_SHORT;
2459 url_write(c->rtp_handles[c->packet_stream_index],
2460 c->buffer_ptr, len);
2462 c->buffer_ptr += len;
2463 c->packet_byte_count += len;
2465 /* TCP data output */
2466 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
2468 if (errno != EAGAIN && errno != EINTR) {
2469 /* error : close connection */
2475 c->buffer_ptr += len;
2478 c->data_count += len;
2479 update_datarate(&c->datarate, c->data_count);
2481 c->stream->bytes_served += len;
2488 static int http_start_receive_data(HTTPContext *c)
2492 if (c->stream->feed_opened)
2495 /* Don't permit writing to this one */
2496 if (c->stream->readonly)
2500 fd = open(c->stream->feed_filename, O_RDWR);
2505 c->stream->feed_write_index = ffm_read_write_index(fd);
2506 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2507 lseek(fd, 0, SEEK_SET);
2509 /* init buffer input */
2510 c->buffer_ptr = c->buffer;
2511 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2512 c->stream->feed_opened = 1;
2516 static int http_receive_data(HTTPContext *c)
2520 if (c->buffer_end > c->buffer_ptr) {
2523 len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
2525 if (errno != EAGAIN && errno != EINTR) {
2526 /* error : close connection */
2529 } else if (len == 0) {
2530 /* end of connection : close it */
2533 c->buffer_ptr += len;
2534 c->data_count += len;
2535 update_datarate(&c->datarate, c->data_count);
2539 if (c->buffer_ptr >= c->buffer_end) {
2540 FFStream *feed = c->stream;
2541 /* a packet has been received : write it in the store, except
2543 if (c->data_count > FFM_PACKET_SIZE) {
2545 // printf("writing pos=0x%Lx size=0x%Lx\n", feed->feed_write_index, feed->feed_size);
2546 /* XXX: use llseek or url_seek */
2547 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
2548 write(c->feed_fd, c->buffer, FFM_PACKET_SIZE);
2550 feed->feed_write_index += FFM_PACKET_SIZE;
2551 /* update file size */
2552 if (feed->feed_write_index > c->stream->feed_size)
2553 feed->feed_size = feed->feed_write_index;
2555 /* handle wrap around if max file size reached */
2556 if (feed->feed_write_index >= c->stream->feed_max_size)
2557 feed->feed_write_index = FFM_PACKET_SIZE;
2560 ffm_write_write_index(c->feed_fd, feed->feed_write_index);
2562 /* wake up any waiting connections */
2563 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2564 if (c1->state == HTTPSTATE_WAIT_FEED &&
2565 c1->stream->feed == c->stream->feed) {
2566 c1->state = HTTPSTATE_SEND_DATA;
2570 /* We have a header in our hands that contains useful data */
2572 AVInputFormat *fmt_in;
2573 ByteIOContext *pb = &s.pb;
2576 memset(&s, 0, sizeof(s));
2578 url_open_buf(pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
2579 pb->buf_end = c->buffer_end; /* ?? */
2580 pb->is_streamed = 1;
2582 /* use feed output format name to find corresponding input format */
2583 fmt_in = av_find_input_format(feed->fmt->name);
2587 if (fmt_in->priv_data_size > 0) {
2588 s.priv_data = av_mallocz(fmt_in->priv_data_size);
2594 if (fmt_in->read_header(&s, 0) < 0) {
2595 av_freep(&s.priv_data);
2599 /* Now we have the actual streams */
2600 if (s.nb_streams != feed->nb_streams) {
2601 av_freep(&s.priv_data);
2604 for (i = 0; i < s.nb_streams; i++) {
2605 memcpy(&feed->streams[i]->codec,
2606 &s.streams[i]->codec, sizeof(AVCodecContext));
2608 av_freep(&s.priv_data);
2610 c->buffer_ptr = c->buffer;
2615 c->stream->feed_opened = 0;
2620 /********************************************************************/
2623 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2630 switch(error_number) {
2631 #define DEF(n, c, s) case c: str = s; break;
2632 #include "rtspcodes.h"
2635 str = "Unknown Error";
2639 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2640 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2642 /* output GMT time */
2646 p = buf2 + strlen(p) - 1;
2649 url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
2652 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2654 rtsp_reply_header(c, error_number);
2655 url_fprintf(c->pb, "\r\n");
2658 static int rtsp_parse_request(HTTPContext *c)
2660 const char *p, *p1, *p2;
2667 RTSPHeader header1, *header = &header1;
2669 c->buffer_ptr[0] = '\0';
2672 get_word(cmd, sizeof(cmd), &p);
2673 get_word(url, sizeof(url), &p);
2674 get_word(protocol, sizeof(protocol), &p);
2676 pstrcpy(c->method, sizeof(c->method), cmd);
2677 pstrcpy(c->url, sizeof(c->url), url);
2678 pstrcpy(c->protocol, sizeof(c->protocol), protocol);
2681 if (url_open_dyn_buf(c->pb) < 0) {
2682 /* XXX: cannot do more */
2683 c->pb = NULL; /* safety */
2687 /* check version name */
2688 if (strcmp(protocol, "RTSP/1.0") != 0) {
2689 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2693 /* parse each header line */
2694 memset(header, 0, sizeof(RTSPHeader));
2695 /* skip to next line */
2696 while (*p != '\n' && *p != '\0')
2700 while (*p != '\0') {
2701 p1 = strchr(p, '\n');
2705 if (p2 > p && p2[-1] == '\r')
2707 /* skip empty line */
2711 if (len > sizeof(line) - 1)
2712 len = sizeof(line) - 1;
2713 memcpy(line, p, len);
2715 rtsp_parse_line(header, line);
2719 /* handle sequence number */
2720 c->seq = header->seq;
2722 if (!strcmp(cmd, "DESCRIBE")) {
2723 rtsp_cmd_describe(c, url);
2724 } else if (!strcmp(cmd, "OPTIONS")) {
2725 rtsp_cmd_options(c, url);
2726 } else if (!strcmp(cmd, "SETUP")) {
2727 rtsp_cmd_setup(c, url, header);
2728 } else if (!strcmp(cmd, "PLAY")) {
2729 rtsp_cmd_play(c, url, header);
2730 } else if (!strcmp(cmd, "PAUSE")) {
2731 rtsp_cmd_pause(c, url, header);
2732 } else if (!strcmp(cmd, "TEARDOWN")) {
2733 rtsp_cmd_teardown(c, url, header);
2735 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2738 len = url_close_dyn_buf(c->pb, &c->pb_buffer);
2739 c->pb = NULL; /* safety */
2741 /* XXX: cannot do more */
2744 c->buffer_ptr = c->pb_buffer;
2745 c->buffer_end = c->pb_buffer + len;
2746 c->state = RTSPSTATE_SEND_REPLY;
2750 /* XXX: move that to rtsp.c, but would need to replace FFStream by
2752 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
2753 struct in_addr my_ip)
2755 ByteIOContext pb1, *pb = &pb1;
2756 int i, payload_type, port, private_payload_type, j;
2757 const char *ipstr, *title, *mediatype;
2760 if (url_open_dyn_buf(pb) < 0)
2763 /* general media info */
2765 url_fprintf(pb, "v=0\n");
2766 ipstr = inet_ntoa(my_ip);
2767 url_fprintf(pb, "o=- 0 0 IN IP4 %s\n", ipstr);
2768 title = stream->title;
2769 if (title[0] == '\0')
2771 url_fprintf(pb, "s=%s\n", title);
2772 if (stream->comment[0] != '\0')
2773 url_fprintf(pb, "i=%s\n", stream->comment);
2774 if (stream->is_multicast) {
2775 url_fprintf(pb, "c=IN IP4 %s\n", inet_ntoa(stream->multicast_ip));
2777 /* for each stream, we output the necessary info */
2778 private_payload_type = 96;
2779 for(i = 0; i < stream->nb_streams; i++) {
2780 st = stream->streams[i];
2781 switch(st->codec.codec_type) {
2782 case CODEC_TYPE_AUDIO:
2783 mediatype = "audio";
2785 case CODEC_TYPE_VIDEO:
2786 mediatype = "video";
2789 mediatype = "application";
2792 /* NOTE: the port indication is not correct in case of
2793 unicast. It is not an issue because RTSP gives it */
2794 payload_type = rtp_get_payload_type(&st->codec);
2795 if (payload_type < 0)
2796 payload_type = private_payload_type++;
2797 if (stream->is_multicast) {
2798 port = stream->multicast_port + 2 * i;
2802 url_fprintf(pb, "m=%s %d RTP/AVP %d\n",
2803 mediatype, port, payload_type);
2804 if (payload_type >= 96) {
2805 /* for private payload type, we need to give more info */
2806 switch(st->codec.codec_id) {
2807 case CODEC_ID_MPEG4:
2810 url_fprintf(pb, "a=rtpmap:%d MP4V-ES/%d\n",
2811 payload_type, 90000);
2812 /* we must also add the mpeg4 header */
2813 data = st->codec.extradata;
2815 url_fprintf(pb, "a=fmtp:%d config=", payload_type);
2816 for(j=0;j<st->codec.extradata_size;j++) {
2817 url_fprintf(pb, "%02x", data[j]);
2819 url_fprintf(pb, "\n");
2824 /* XXX: add other codecs ? */
2828 url_fprintf(pb, "a=control:streamid=%d\n", i);
2830 return url_close_dyn_buf(pb, pbuffer);
2832 url_close_dyn_buf(pb, pbuffer);
2837 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2839 // rtsp_reply_header(c, RTSP_STATUS_OK);
2840 url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2841 url_fprintf(c->pb, "CSeq: %d\r\n", c->seq);
2842 url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2843 url_fprintf(c->pb, "\r\n");
2846 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2852 int content_length, len;
2853 struct sockaddr_in my_addr;
2855 /* find which url is asked */
2856 url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2861 for(stream = first_stream; stream != NULL; stream = stream->next) {
2862 if (!stream->is_feed && stream->fmt == &rtp_mux &&
2863 !strcmp(path, stream->filename)) {
2867 /* no stream found */
2868 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2872 /* prepare the media description in sdp format */
2874 /* get the host IP */
2875 len = sizeof(my_addr);
2876 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
2878 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
2879 if (content_length < 0) {
2880 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2883 rtsp_reply_header(c, RTSP_STATUS_OK);
2884 url_fprintf(c->pb, "Content-Type: application/sdp\r\n");
2885 url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);
2886 url_fprintf(c->pb, "\r\n");
2887 put_buffer(c->pb, content, content_length);
2890 static HTTPContext *find_rtp_session(const char *session_id)
2894 if (session_id[0] == '\0')
2897 for(c = first_http_ctx; c != NULL; c = c->next) {
2898 if (!strcmp(c->session_id, session_id))
2904 static RTSPTransportField *find_transport(RTSPHeader *h, enum RTSPProtocol protocol)
2906 RTSPTransportField *th;
2909 for(i=0;i<h->nb_transports;i++) {
2910 th = &h->transports[i];
2911 if (th->protocol == protocol)
2917 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
2921 int stream_index, port;
2926 RTSPTransportField *th;
2927 struct sockaddr_in dest_addr;
2928 RTSPActionServerSetup setup;
2930 /* find which url is asked */
2931 url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2936 /* now check each stream */
2937 for(stream = first_stream; stream != NULL; stream = stream->next) {
2938 if (!stream->is_feed && stream->fmt == &rtp_mux) {
2939 /* accept aggregate filenames only if single stream */
2940 if (!strcmp(path, stream->filename)) {
2941 if (stream->nb_streams != 1) {
2942 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
2949 for(stream_index = 0; stream_index < stream->nb_streams;
2951 snprintf(buf, sizeof(buf), "%s/streamid=%d",
2952 stream->filename, stream_index);
2953 if (!strcmp(path, buf))
2958 /* no stream found */
2959 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2963 /* generate session id if needed */
2964 if (h->session_id[0] == '\0') {
2965 snprintf(h->session_id, sizeof(h->session_id),
2966 "%08x%08x", (int)random(), (int)random());
2969 /* find rtp session, and create it if none found */
2970 rtp_c = find_rtp_session(h->session_id);
2972 /* always prefer UDP */
2973 th = find_transport(h, RTSP_PROTOCOL_RTP_UDP);
2975 th = find_transport(h, RTSP_PROTOCOL_RTP_TCP);
2977 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2982 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
2985 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
2989 /* open input stream */
2990 if (open_input_stream(rtp_c, "") < 0) {
2991 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2996 /* test if stream is OK (test needed because several SETUP needs
2997 to be done for a given file) */
2998 if (rtp_c->stream != stream) {
2999 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3003 /* test if stream is already set up */
3004 if (rtp_c->rtp_ctx[stream_index]) {
3005 rtsp_reply_error(c, RTSP_STATUS_STATE);
3009 /* check transport */
3010 th = find_transport(h, rtp_c->rtp_protocol);
3011 if (!th || (th->protocol == RTSP_PROTOCOL_RTP_UDP &&
3012 th->client_port_min <= 0)) {
3013 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3017 /* setup default options */
3018 setup.transport_option[0] = '\0';
3019 dest_addr = rtp_c->from_addr;
3020 dest_addr.sin_port = htons(th->client_port_min);
3022 /* add transport option if needed */
3023 if (ff_rtsp_callback) {
3024 setup.ipaddr = ntohl(dest_addr.sin_addr.s_addr);
3025 if (ff_rtsp_callback(RTSP_ACTION_SERVER_SETUP, rtp_c->session_id,
3026 (char *)&setup, sizeof(setup),
3027 stream->rtsp_option) < 0) {
3028 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3031 dest_addr.sin_addr.s_addr = htonl(setup.ipaddr);
3035 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3036 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3040 /* now everything is OK, so we can send the connection parameters */
3041 rtsp_reply_header(c, RTSP_STATUS_OK);
3043 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3045 switch(rtp_c->rtp_protocol) {
3046 case RTSP_PROTOCOL_RTP_UDP:
3047 port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]);
3048 url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3049 "client_port=%d-%d;server_port=%d-%d",
3050 th->client_port_min, th->client_port_min + 1,
3053 case RTSP_PROTOCOL_RTP_TCP:
3054 url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3055 stream_index * 2, stream_index * 2 + 1);
3060 if (setup.transport_option[0] != '\0') {
3061 url_fprintf(c->pb, ";%s", setup.transport_option);
3063 url_fprintf(c->pb, "\r\n");
3066 url_fprintf(c->pb, "\r\n");
3070 /* find an rtp connection by using the session ID. Check consistency
3072 static HTTPContext *find_rtp_session_with_url(const char *url,
3073 const char *session_id)
3081 rtp_c = find_rtp_session(session_id);
3085 /* find which url is asked */
3086 url_split(NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3090 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3091 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3092 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3093 rtp_c->stream->filename, s);
3094 if(!strncmp(path, buf, sizeof(buf))) {
3095 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
3102 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h)
3106 rtp_c = find_rtp_session_with_url(url, h->session_id);
3108 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3112 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3113 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3114 rtp_c->state != HTTPSTATE_READY) {
3115 rtsp_reply_error(c, RTSP_STATUS_STATE);
3119 rtp_c->state = HTTPSTATE_SEND_DATA;
3121 /* now everything is OK, so we can send the connection parameters */
3122 rtsp_reply_header(c, RTSP_STATUS_OK);
3124 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3125 url_fprintf(c->pb, "\r\n");
3128 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h)
3132 rtp_c = find_rtp_session_with_url(url, h->session_id);
3134 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3138 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3139 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3140 rtsp_reply_error(c, RTSP_STATUS_STATE);
3144 rtp_c->state = HTTPSTATE_READY;
3145 rtp_c->first_pts = AV_NOPTS_VALUE;
3146 /* now everything is OK, so we can send the connection parameters */
3147 rtsp_reply_header(c, RTSP_STATUS_OK);
3149 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3150 url_fprintf(c->pb, "\r\n");
3153 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h)
3157 rtp_c = find_rtp_session_with_url(url, h->session_id);
3159 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3163 /* abort the session */
3164 close_connection(rtp_c);
3166 if (ff_rtsp_callback) {
3167 ff_rtsp_callback(RTSP_ACTION_SERVER_TEARDOWN, rtp_c->session_id,
3169 rtp_c->stream->rtsp_option);
3172 /* now everything is OK, so we can send the connection parameters */
3173 rtsp_reply_header(c, RTSP_STATUS_OK);
3175 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3176 url_fprintf(c->pb, "\r\n");
3180 /********************************************************************/
3183 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3184 FFStream *stream, const char *session_id,
3185 enum RTSPProtocol rtp_protocol)
3187 HTTPContext *c = NULL;
3188 const char *proto_str;
3190 /* XXX: should output a warning page when coming
3191 close to the connection limit */
3192 if (nb_connections >= nb_max_connections)
3195 /* add a new connection */
3196 c = av_mallocz(sizeof(HTTPContext));
3201 c->poll_entry = NULL;
3202 c->from_addr = *from_addr;
3203 c->buffer_size = IOBUFFER_INIT_SIZE;
3204 c->buffer = av_malloc(c->buffer_size);
3209 pstrcpy(c->session_id, sizeof(c->session_id), session_id);
3210 c->state = HTTPSTATE_READY;
3211 c->is_packetized = 1;
3212 c->rtp_protocol = rtp_protocol;
3214 /* protocol is shown in statistics */
3215 switch(c->rtp_protocol) {
3216 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
3217 proto_str = "MCAST";
3219 case RTSP_PROTOCOL_RTP_UDP:
3222 case RTSP_PROTOCOL_RTP_TCP:
3229 pstrcpy(c->protocol, sizeof(c->protocol), "RTP/");
3230 pstrcat(c->protocol, sizeof(c->protocol), proto_str);
3232 current_bandwidth += stream->bandwidth;
3234 c->next = first_http_ctx;
3246 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3247 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3249 static int rtp_new_av_stream(HTTPContext *c,
3250 int stream_index, struct sockaddr_in *dest_addr,
3251 HTTPContext *rtsp_c)
3253 AVFormatContext *ctx;
3259 int max_packet_size;
3261 /* now we can open the relevant output stream */
3262 ctx = av_mallocz(sizeof(AVFormatContext));
3265 ctx->oformat = &rtp_mux;
3267 st = av_mallocz(sizeof(AVStream));
3270 ctx->nb_streams = 1;
3271 ctx->streams[0] = st;
3273 if (!c->stream->feed ||
3274 c->stream->feed == c->stream) {
3275 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3278 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3282 /* build destination RTP address */
3283 ipaddr = inet_ntoa(dest_addr->sin_addr);
3285 switch(c->rtp_protocol) {
3286 case RTSP_PROTOCOL_RTP_UDP:
3287 case RTSP_PROTOCOL_RTP_UDP_MULTICAST:
3290 /* XXX: also pass as parameter to function ? */
3291 if (c->stream->is_multicast) {
3293 ttl = c->stream->multicast_ttl;
3296 snprintf(ctx->filename, sizeof(ctx->filename),
3297 "rtp://%s:%d?multicast=1&ttl=%d",
3298 ipaddr, ntohs(dest_addr->sin_port), ttl);
3300 snprintf(ctx->filename, sizeof(ctx->filename),
3301 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3304 if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
3306 c->rtp_handles[stream_index] = h;
3307 max_packet_size = url_get_max_packet_size(h);
3309 case RTSP_PROTOCOL_RTP_TCP:
3312 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3318 http_log("%s:%d - - [%s] \"PLAY %s/streamid=%d %s\"\n",
3319 ipaddr, ntohs(dest_addr->sin_port),
3321 c->stream->filename, stream_index, c->protocol);
3323 /* normally, no packets should be output here, but the packet size may be checked */
3324 if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
3325 /* XXX: close stream */
3328 av_set_parameters(ctx, NULL);
3329 if (av_write_header(ctx) < 0) {
3336 url_close_dyn_buf(&ctx->pb, &dummy_buf);
3339 c->rtp_ctx[stream_index] = ctx;
3343 /********************************************************************/
3344 /* ffserver initialization */
3346 static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
3350 fst = av_mallocz(sizeof(AVStream));
3353 fst->priv_data = av_mallocz(sizeof(FeedData));
3354 memcpy(&fst->codec, codec, sizeof(AVCodecContext));
3355 fst->codec.coded_frame = &dummy_frame;
3356 stream->streams[stream->nb_streams++] = fst;
3360 /* return the stream number in the feed */
3361 static int add_av_stream(FFStream *feed, AVStream *st)
3364 AVCodecContext *av, *av1;
3368 for(i=0;i<feed->nb_streams;i++) {
3369 st = feed->streams[i];
3371 if (av1->codec_id == av->codec_id &&
3372 av1->codec_type == av->codec_type &&
3373 av1->bit_rate == av->bit_rate) {
3375 switch(av->codec_type) {
3376 case CODEC_TYPE_AUDIO:
3377 if (av1->channels == av->channels &&
3378 av1->sample_rate == av->sample_rate)
3381 case CODEC_TYPE_VIDEO:
3382 if (av1->width == av->width &&
3383 av1->height == av->height &&
3384 av1->frame_rate == av->frame_rate &&
3385 av1->frame_rate_base == av->frame_rate_base &&
3386 av1->gop_size == av->gop_size)
3395 fst = add_av_stream1(feed, av);
3398 return feed->nb_streams - 1;
3403 static void remove_stream(FFStream *stream)
3407 while (*ps != NULL) {
3408 if (*ps == stream) {
3416 /* specific mpeg4 handling : we extract the raw parameters */
3417 static void extract_mpeg4_header(AVFormatContext *infile)
3419 int mpeg4_count, i, size;
3425 for(i=0;i<infile->nb_streams;i++) {
3426 st = infile->streams[i];
3427 if (st->codec.codec_id == CODEC_ID_MPEG4 &&
3428 st->codec.extradata_size == 0) {
3435 printf("MPEG4 without extra data: trying to find header\n");
3436 while (mpeg4_count > 0) {
3437 if (av_read_packet(infile, &pkt) < 0)
3439 st = infile->streams[pkt.stream_index];
3440 if (st->codec.codec_id == CODEC_ID_MPEG4 &&
3441 st->codec.extradata_size == 0) {
3442 av_freep(&st->codec.extradata);
3443 /* fill extradata with the header */
3444 /* XXX: we make hard suppositions here ! */
3446 while (p < pkt.data + pkt.size - 4) {
3447 /* stop when vop header is found */
3448 if (p[0] == 0x00 && p[1] == 0x00 &&
3449 p[2] == 0x01 && p[3] == 0xb6) {
3450 size = p - pkt.data;
3451 // av_hex_dump(pkt.data, size);
3452 st->codec.extradata = av_malloc(size);
3453 st->codec.extradata_size = size;
3454 memcpy(st->codec.extradata, pkt.data, size);
3461 av_free_packet(&pkt);
3465 /* compute the needed AVStream for each file */
3466 static void build_file_streams(void)
3468 FFStream *stream, *stream_next;
3469 AVFormatContext *infile;
3472 /* gather all streams */
3473 for(stream = first_stream; stream != NULL; stream = stream_next) {
3474 stream_next = stream->next;
3475 if (stream->stream_type == STREAM_TYPE_LIVE &&
3477 /* the stream comes from a file */
3478 /* try to open the file */
3480 if (av_open_input_file(&infile, stream->feed_filename,
3481 NULL, 0, NULL) < 0) {
3482 http_log("%s not found", stream->feed_filename);
3483 /* remove stream (no need to spend more time on it) */
3485 remove_stream(stream);
3487 /* find all the AVStreams inside and reference them in
3489 if (av_find_stream_info(infile) < 0) {
3490 http_log("Could not find codec parameters from '%s'",
3491 stream->feed_filename);
3492 av_close_input_file(infile);
3495 extract_mpeg4_header(infile);
3497 for(i=0;i<infile->nb_streams;i++) {
3498 add_av_stream1(stream, &infile->streams[i]->codec);
3500 av_close_input_file(infile);
3506 /* compute the needed AVStream for each feed */
3507 static void build_feed_streams(void)
3509 FFStream *stream, *feed;
3512 /* gather all streams */
3513 for(stream = first_stream; stream != NULL; stream = stream->next) {
3514 feed = stream->feed;
3516 if (!stream->is_feed) {
3517 /* we handle a stream coming from a feed */
3518 for(i=0;i<stream->nb_streams;i++) {
3519 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3525 /* gather all streams */
3526 for(stream = first_stream; stream != NULL; stream = stream->next) {
3527 feed = stream->feed;
3529 if (stream->is_feed) {
3530 for(i=0;i<stream->nb_streams;i++) {
3531 stream->feed_streams[i] = i;
3537 /* create feed files if needed */
3538 for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
3541 if (url_exist(feed->feed_filename)) {
3542 /* See if it matches */
3546 if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) {
3547 /* Now see if it matches */
3548 if (s->nb_streams == feed->nb_streams) {
3550 for(i=0;i<s->nb_streams;i++) {
3552 sf = feed->streams[i];
3555 if (sf->index != ss->index ||
3557 printf("Index & Id do not match for stream %d\n", i);
3560 AVCodecContext *ccf, *ccs;
3564 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3566 if (CHECK_CODEC(codec) || CHECK_CODEC(codec_type)) {
3567 printf("Codecs do not match for stream %d\n", i);
3569 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3570 printf("Codec bitrates do not match for stream %d\n", i);
3572 } else if (ccf->codec_type == CODEC_TYPE_VIDEO) {
3573 if (CHECK_CODEC(frame_rate) ||
3574 CHECK_CODEC(frame_rate_base) ||
3575 CHECK_CODEC(width) ||
3576 CHECK_CODEC(height)) {
3577 printf("Codec width, height and framerate do not match for stream %d\n", i);
3580 } else if (ccf->codec_type == CODEC_TYPE_AUDIO) {
3581 if (CHECK_CODEC(sample_rate) ||
3582 CHECK_CODEC(channels) ||
3583 CHECK_CODEC(frame_size)) {
3584 printf("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3588 printf("Unknown codec type\n");
3597 printf("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3598 feed->feed_filename, s->nb_streams, feed->nb_streams);
3601 av_close_input_file(s);
3603 printf("Deleting feed file '%s' as it appears to be corrupt\n",
3604 feed->feed_filename);
3607 if (feed->readonly) {
3608 printf("Unable to delete feed file '%s' as it is marked readonly\n",
3609 feed->feed_filename);
3612 unlink(feed->feed_filename);
3615 if (!url_exist(feed->feed_filename)) {
3616 AVFormatContext s1, *s = &s1;
3618 if (feed->readonly) {
3619 printf("Unable to create feed file '%s' as it is marked readonly\n",
3620 feed->feed_filename);
3624 /* only write the header of the ffm file */
3625 if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
3626 fprintf(stderr, "Could not open output feed file '%s'\n",
3627 feed->feed_filename);
3630 s->oformat = feed->fmt;
3631 s->nb_streams = feed->nb_streams;
3632 for(i=0;i<s->nb_streams;i++) {
3634 st = feed->streams[i];
3637 av_set_parameters(s, NULL);
3639 /* XXX: need better api */
3640 av_freep(&s->priv_data);
3643 /* get feed size and write index */
3644 fd = open(feed->feed_filename, O_RDONLY);
3646 fprintf(stderr, "Could not open output feed file '%s'\n",
3647 feed->feed_filename);
3651 feed->feed_write_index = ffm_read_write_index(fd);
3652 feed->feed_size = lseek(fd, 0, SEEK_END);
3653 /* ensure that we do not wrap before the end of file */
3654 if (feed->feed_max_size < feed->feed_size)
3655 feed->feed_max_size = feed->feed_size;
3661 /* compute the bandwidth used by each stream */
3662 static void compute_bandwidth(void)
3667 for(stream = first_stream; stream != NULL; stream = stream->next) {
3669 for(i=0;i<stream->nb_streams;i++) {
3670 AVStream *st = stream->streams[i];
3671 switch(st->codec.codec_type) {
3672 case CODEC_TYPE_AUDIO:
3673 case CODEC_TYPE_VIDEO:
3674 bandwidth += st->codec.bit_rate;
3680 stream->bandwidth = (bandwidth + 999) / 1000;
3684 static void get_arg(char *buf, int buf_size, const char **pp)
3691 while (isspace(*p)) p++;
3694 if (*p == '\"' || *p == '\'')
3706 if ((q - buf) < buf_size - 1)
3711 if (quote && *p == quote)
3716 /* add a codec and set the default parameters */
3717 static void add_codec(FFStream *stream, AVCodecContext *av)
3721 /* compute default parameters */
3722 switch(av->codec_type) {
3723 case CODEC_TYPE_AUDIO:
3724 if (av->bit_rate == 0)
3725 av->bit_rate = 64000;
3726 if (av->sample_rate == 0)
3727 av->sample_rate = 22050;
3728 if (av->channels == 0)
3731 case CODEC_TYPE_VIDEO:
3732 if (av->bit_rate == 0)
3733 av->bit_rate = 64000;
3734 if (av->frame_rate == 0){
3736 av->frame_rate_base = 1;
3738 if (av->width == 0 || av->height == 0) {
3742 /* Bitrate tolerance is less for streaming */
3743 if (av->bit_rate_tolerance == 0)
3744 av->bit_rate_tolerance = av->bit_rate / 4;
3749 if (av->max_qdiff == 0)
3751 av->qcompress = 0.5;
3755 av->rc_eq = "tex^qComp";
3756 if (!av->i_quant_factor)
3757 av->i_quant_factor = -0.8;
3758 if (!av->b_quant_factor)
3759 av->b_quant_factor = 1.25;
3760 if (!av->b_quant_offset)
3761 av->b_quant_offset = 1.25;
3762 if (!av->rc_min_rate)
3763 av->rc_min_rate = av->bit_rate / 2;
3764 if (!av->rc_max_rate)
3765 av->rc_max_rate = av->bit_rate * 2;
3772 st = av_mallocz(sizeof(AVStream));
3775 stream->streams[stream->nb_streams++] = st;
3776 memcpy(&st->codec, av, sizeof(AVCodecContext));
3779 static int opt_audio_codec(const char *arg)
3785 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
3790 return CODEC_ID_NONE;
3796 static int opt_video_codec(const char *arg)
3802 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
3807 return CODEC_ID_NONE;
3813 /* simplistic plugin support */
3815 #ifdef CONFIG_HAVE_DLOPEN
3816 void load_module(const char *filename)
3819 void (*init_func)(void);
3820 dll = dlopen(filename, RTLD_NOW);
3822 fprintf(stderr, "Could not load module '%s' - %s\n",
3823 filename, dlerror());
3827 init_func = dlsym(dll, "ffserver_module_init");
3830 "%s: init function 'ffserver_module_init()' not found\n",
3839 static int parse_ffconfig(const char *filename)
3846 int val, errors, line_num;
3847 FFStream **last_stream, *stream, *redirect;
3848 FFStream **last_feed, *feed;
3849 AVCodecContext audio_enc, video_enc;
3850 int audio_id, video_id;
3852 f = fopen(filename, "r");
3860 first_stream = NULL;
3861 last_stream = &first_stream;
3863 last_feed = &first_feed;
3867 audio_id = CODEC_ID_NONE;
3868 video_id = CODEC_ID_NONE;
3870 if (fgets(line, sizeof(line), f) == NULL)
3876 if (*p == '\0' || *p == '#')
3879 get_arg(cmd, sizeof(cmd), &p);
3881 if (!strcasecmp(cmd, "Port")) {
3882 get_arg(arg, sizeof(arg), &p);
3883 my_http_addr.sin_port = htons (atoi(arg));
3884 } else if (!strcasecmp(cmd, "BindAddress")) {
3885 get_arg(arg, sizeof(arg), &p);
3886 if (!inet_aton(arg, &my_http_addr.sin_addr)) {
3887 fprintf(stderr, "%s:%d: Invalid IP address: %s\n",
3888 filename, line_num, arg);
3891 } else if (!strcasecmp(cmd, "NoDaemon")) {
3892 ffserver_daemon = 0;
3893 } else if (!strcasecmp(cmd, "RTSPPort")) {
3894 get_arg(arg, sizeof(arg), &p);
3895 my_rtsp_addr.sin_port = htons (atoi(arg));
3896 } else if (!strcasecmp(cmd, "RTSPBindAddress")) {
3897 get_arg(arg, sizeof(arg), &p);
3898 if (!inet_aton(arg, &my_rtsp_addr.sin_addr)) {
3899 fprintf(stderr, "%s:%d: Invalid IP address: %s\n",
3900 filename, line_num, arg);
3903 } else if (!strcasecmp(cmd, "MaxClients")) {
3904 get_arg(arg, sizeof(arg), &p);
3906 if (val < 1 || val > HTTP_MAX_CONNECTIONS) {
3907 fprintf(stderr, "%s:%d: Invalid MaxClients: %s\n",
3908 filename, line_num, arg);
3911 nb_max_connections = val;
3913 } else if (!strcasecmp(cmd, "MaxBandwidth")) {
3914 get_arg(arg, sizeof(arg), &p);
3916 if (val < 10 || val > 100000) {
3917 fprintf(stderr, "%s:%d: Invalid MaxBandwidth: %s\n",
3918 filename, line_num, arg);
3921 max_bandwidth = val;
3923 } else if (!strcasecmp(cmd, "CustomLog")) {
3924 get_arg(logfilename, sizeof(logfilename), &p);
3925 } else if (!strcasecmp(cmd, "<Feed")) {
3926 /*********************************************/
3927 /* Feed related options */
3929 if (stream || feed) {
3930 fprintf(stderr, "%s:%d: Already in a tag\n",
3931 filename, line_num);
3933 feed = av_mallocz(sizeof(FFStream));
3934 /* add in stream list */
3935 *last_stream = feed;
3936 last_stream = &feed->next;
3937 /* add in feed list */
3939 last_feed = &feed->next_feed;
3941 get_arg(feed->filename, sizeof(feed->filename), &p);
3942 q = strrchr(feed->filename, '>');
3945 feed->fmt = guess_format("ffm", NULL, NULL);
3946 /* defaut feed file */
3947 snprintf(feed->feed_filename, sizeof(feed->feed_filename),
3948 "/tmp/%s.ffm", feed->filename);
3949 feed->feed_max_size = 5 * 1024 * 1024;
3951 feed->feed = feed; /* self feeding :-) */
3953 } else if (!strcasecmp(cmd, "Launch")) {
3957 feed->child_argv = (char **) av_mallocz(64 * sizeof(char *));
3959 feed->child_argv[0] = av_malloc(7);
3960 strcpy(feed->child_argv[0], "ffmpeg");
3962 for (i = 1; i < 62; i++) {
3965 get_arg(argbuf, sizeof(argbuf), &p);
3969 feed->child_argv[i] = av_malloc(strlen(argbuf) + 1);
3970 strcpy(feed->child_argv[i], argbuf);
3973 feed->child_argv[i] = av_malloc(30 + strlen(feed->filename));
3975 snprintf(feed->child_argv[i], 256, "http://127.0.0.1:%d/%s",
3976 ntohs(my_http_addr.sin_port), feed->filename);
3978 } else if (!strcasecmp(cmd, "ReadOnlyFile")) {
3980 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
3982 } else if (stream) {
3983 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
3985 } else if (!strcasecmp(cmd, "File")) {
3987 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
3988 } else if (stream) {
3989 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
3991 } else if (!strcasecmp(cmd, "FileMaxSize")) {
3996 get_arg(arg, sizeof(arg), &p);
3998 fsize = strtod(p1, (char **)&p1);
3999 switch(toupper(*p1)) {
4004 fsize *= 1024 * 1024;
4007 fsize *= 1024 * 1024 * 1024;
4010 feed->feed_max_size = (int64_t)fsize;
4012 } else if (!strcasecmp(cmd, "</Feed>")) {
4014 fprintf(stderr, "%s:%d: No corresponding <Feed> for </Feed>\n",
4015 filename, line_num);
4019 /* Make sure that we start out clean */
4020 if (unlink(feed->feed_filename) < 0
4021 && errno != ENOENT) {
4022 fprintf(stderr, "%s:%d: Unable to clean old feed file '%s': %s\n",
4023 filename, line_num, feed->feed_filename, strerror(errno));
4029 } else if (!strcasecmp(cmd, "<Stream")) {
4030 /*********************************************/
4031 /* Stream related options */
4033 if (stream || feed) {
4034 fprintf(stderr, "%s:%d: Already in a tag\n",
4035 filename, line_num);
4037 stream = av_mallocz(sizeof(FFStream));
4038 *last_stream = stream;
4039 last_stream = &stream->next;
4041 get_arg(stream->filename, sizeof(stream->filename), &p);
4042 q = strrchr(stream->filename, '>');
4045 stream->fmt = guess_stream_format(NULL, stream->filename, NULL);
4046 memset(&audio_enc, 0, sizeof(AVCodecContext));
4047 memset(&video_enc, 0, sizeof(AVCodecContext));
4048 audio_id = CODEC_ID_NONE;
4049 video_id = CODEC_ID_NONE;
4051 audio_id = stream->fmt->audio_codec;
4052 video_id = stream->fmt->video_codec;
4055 } else if (!strcasecmp(cmd, "Feed")) {
4056 get_arg(arg, sizeof(arg), &p);
4061 while (sfeed != NULL) {
4062 if (!strcmp(sfeed->filename, arg))
4064 sfeed = sfeed->next_feed;
4067 fprintf(stderr, "%s:%d: feed '%s' not defined\n",
4068 filename, line_num, arg);
4070 stream->feed = sfeed;
4073 } else if (!strcasecmp(cmd, "Format")) {
4074 get_arg(arg, sizeof(arg), &p);
4075 if (!strcmp(arg, "status")) {
4076 stream->stream_type = STREAM_TYPE_STATUS;
4079 stream->stream_type = STREAM_TYPE_LIVE;
4080 /* jpeg cannot be used here, so use single frame jpeg */
4081 if (!strcmp(arg, "jpeg"))
4082 strcpy(arg, "singlejpeg");
4083 stream->fmt = guess_stream_format(arg, NULL, NULL);
4085 fprintf(stderr, "%s:%d: Unknown Format: %s\n",
4086 filename, line_num, arg);
4091 audio_id = stream->fmt->audio_codec;
4092 video_id = stream->fmt->video_codec;
4094 } else if (!strcasecmp(cmd, "FaviconURL")) {
4095 if (stream && stream->stream_type == STREAM_TYPE_STATUS) {
4096 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
4098 fprintf(stderr, "%s:%d: FaviconURL only permitted for status streams\n",
4099 filename, line_num);
4102 } else if (!strcasecmp(cmd, "Author")) {
4104 get_arg(stream->author, sizeof(stream->author), &p);
4106 } else if (!strcasecmp(cmd, "Comment")) {
4108 get_arg(stream->comment, sizeof(stream->comment), &p);
4110 } else if (!strcasecmp(cmd, "Copyright")) {
4112 get_arg(stream->copyright, sizeof(stream->copyright), &p);
4114 } else if (!strcasecmp(cmd, "Title")) {
4116 get_arg(stream->title, sizeof(stream->title), &p);
4118 } else if (!strcasecmp(cmd, "Preroll")) {
4119 get_arg(arg, sizeof(arg), &p);
4121 stream->prebuffer = atof(arg) * 1000;
4123 } else if (!strcasecmp(cmd, "StartSendOnKey")) {
4125 stream->send_on_key = 1;
4127 } else if (!strcasecmp(cmd, "AudioCodec")) {
4128 get_arg(arg, sizeof(arg), &p);
4129 audio_id = opt_audio_codec(arg);
4130 if (audio_id == CODEC_ID_NONE) {
4131 fprintf(stderr, "%s:%d: Unknown AudioCodec: %s\n",
4132 filename, line_num, arg);
4135 } else if (!strcasecmp(cmd, "VideoCodec")) {
4136 get_arg(arg, sizeof(arg), &p);
4137 video_id = opt_video_codec(arg);
4138 if (video_id == CODEC_ID_NONE) {
4139 fprintf(stderr, "%s:%d: Unknown VideoCodec: %s\n",
4140 filename, line_num, arg);
4143 } else if (!strcasecmp(cmd, "MaxTime")) {
4144 get_arg(arg, sizeof(arg), &p);
4146 stream->max_time = atof(arg) * 1000;
4148 } else if (!strcasecmp(cmd, "AudioBitRate")) {
4149 get_arg(arg, sizeof(arg), &p);
4151 audio_enc.bit_rate = atoi(arg) * 1000;
4153 } else if (!strcasecmp(cmd, "AudioChannels")) {
4154 get_arg(arg, sizeof(arg), &p);
4156 audio_enc.channels = atoi(arg);
4158 } else if (!strcasecmp(cmd, "AudioSampleRate")) {
4159 get_arg(arg, sizeof(arg), &p);
4161 audio_enc.sample_rate = atoi(arg);
4163 } else if (!strcasecmp(cmd, "AudioQuality")) {
4164 get_arg(arg, sizeof(arg), &p);
4166 // audio_enc.quality = atof(arg) * 1000;
4168 } else if (!strcasecmp(cmd, "VideoBitRateRange")) {
4170 int minrate, maxrate;
4172 get_arg(arg, sizeof(arg), &p);
4174 if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) {
4175 video_enc.rc_min_rate = minrate * 1000;
4176 video_enc.rc_max_rate = maxrate * 1000;
4178 fprintf(stderr, "%s:%d: Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n",
4179 filename, line_num, arg);
4183 } else if (!strcasecmp(cmd, "VideoBitRateTolerance")) {
4185 get_arg(arg, sizeof(arg), &p);
4186 video_enc.bit_rate_tolerance = atoi(arg) * 1000;
4188 } else if (!strcasecmp(cmd, "VideoBitRate")) {
4189 get_arg(arg, sizeof(arg), &p);
4191 video_enc.bit_rate = atoi(arg) * 1000;
4193 } else if (!strcasecmp(cmd, "VideoSize")) {
4194 get_arg(arg, sizeof(arg), &p);
4196 parse_image_size(&video_enc.width, &video_enc.height, arg);
4197 if ((video_enc.width % 16) != 0 ||
4198 (video_enc.height % 16) != 0) {
4199 fprintf(stderr, "%s:%d: Image size must be a multiple of 16\n",
4200 filename, line_num);
4204 } else if (!strcasecmp(cmd, "VideoFrameRate")) {
4205 get_arg(arg, sizeof(arg), &p);
4207 video_enc.frame_rate_base= DEFAULT_FRAME_RATE_BASE;
4208 video_enc.frame_rate = (int)(strtod(arg, NULL) * video_enc.frame_rate_base);
4210 } else if (!strcasecmp(cmd, "VideoGopSize")) {
4211 get_arg(arg, sizeof(arg), &p);
4213 video_enc.gop_size = atoi(arg);
4215 } else if (!strcasecmp(cmd, "VideoIntraOnly")) {
4217 video_enc.gop_size = 1;
4219 } else if (!strcasecmp(cmd, "VideoHighQuality")) {
4221 video_enc.mb_decision = FF_MB_DECISION_BITS;
4223 } else if (!strcasecmp(cmd, "Video4MotionVector")) {
4225 video_enc.mb_decision = FF_MB_DECISION_BITS; //FIXME remove
4226 video_enc.flags |= CODEC_FLAG_4MV;
4228 } else if (!strcasecmp(cmd, "VideoQDiff")) {
4229 get_arg(arg, sizeof(arg), &p);
4231 video_enc.max_qdiff = atoi(arg);
4232 if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) {
4233 fprintf(stderr, "%s:%d: VideoQDiff out of range\n",
4234 filename, line_num);
4238 } else if (!strcasecmp(cmd, "VideoQMax")) {
4239 get_arg(arg, sizeof(arg), &p);
4241 video_enc.qmax = atoi(arg);
4242 if (video_enc.qmax < 1 || video_enc.qmax > 31) {
4243 fprintf(stderr, "%s:%d: VideoQMax out of range\n",
4244 filename, line_num);
4248 } else if (!strcasecmp(cmd, "VideoQMin")) {
4249 get_arg(arg, sizeof(arg), &p);
4251 video_enc.qmin = atoi(arg);
4252 if (video_enc.qmin < 1 || video_enc.qmin > 31) {
4253 fprintf(stderr, "%s:%d: VideoQMin out of range\n",
4254 filename, line_num);
4258 } else if (!strcasecmp(cmd, "LumaElim")) {
4259 get_arg(arg, sizeof(arg), &p);
4261 video_enc.luma_elim_threshold = atoi(arg);
4263 } else if (!strcasecmp(cmd, "ChromaElim")) {
4264 get_arg(arg, sizeof(arg), &p);
4266 video_enc.chroma_elim_threshold = atoi(arg);
4268 } else if (!strcasecmp(cmd, "LumiMask")) {
4269 get_arg(arg, sizeof(arg), &p);
4271 video_enc.lumi_masking = atof(arg);
4273 } else if (!strcasecmp(cmd, "DarkMask")) {
4274 get_arg(arg, sizeof(arg), &p);
4276 video_enc.dark_masking = atof(arg);
4278 } else if (!strcasecmp(cmd, "NoVideo")) {
4279 video_id = CODEC_ID_NONE;
4280 } else if (!strcasecmp(cmd, "NoAudio")) {
4281 audio_id = CODEC_ID_NONE;
4282 } else if (!strcasecmp(cmd, "ACL")) {
4286 get_arg(arg, sizeof(arg), &p);
4287 if (strcasecmp(arg, "allow") == 0) {
4288 acl.action = IP_ALLOW;
4289 } else if (strcasecmp(arg, "deny") == 0) {
4290 acl.action = IP_DENY;
4292 fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
4293 filename, line_num, arg);
4297 get_arg(arg, sizeof(arg), &p);
4299 he = gethostbyname(arg);
4301 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4302 filename, line_num, arg);
4305 /* Only take the first */
4306 acl.first.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr);
4307 acl.last = acl.first;
4310 get_arg(arg, sizeof(arg), &p);
4313 he = gethostbyname(arg);
4315 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4316 filename, line_num, arg);
4319 /* Only take the first */
4320 acl.last.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr);
4325 IPAddressACL *nacl = (IPAddressACL *) av_mallocz(sizeof(*nacl));
4326 IPAddressACL **naclp = 0;
4332 naclp = &stream->acl;
4336 fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n",
4337 filename, line_num);
4343 naclp = &(*naclp)->next;
4348 } else if (!strcasecmp(cmd, "RTSPOption")) {
4349 get_arg(arg, sizeof(arg), &p);
4351 av_freep(&stream->rtsp_option);
4352 /* XXX: av_strdup ? */
4353 stream->rtsp_option = av_malloc(strlen(arg) + 1);
4354 if (stream->rtsp_option) {
4355 strcpy(stream->rtsp_option, arg);
4358 } else if (!strcasecmp(cmd, "MulticastAddress")) {
4359 get_arg(arg, sizeof(arg), &p);
4361 if (!inet_aton(arg, &stream->multicast_ip)) {
4362 fprintf(stderr, "%s:%d: Invalid IP address: %s\n",
4363 filename, line_num, arg);
4366 stream->is_multicast = 1;
4367 stream->loop = 1; /* default is looping */
4369 } else if (!strcasecmp(cmd, "MulticastPort")) {
4370 get_arg(arg, sizeof(arg), &p);
4372 stream->multicast_port = atoi(arg);
4374 } else if (!strcasecmp(cmd, "MulticastTTL")) {
4375 get_arg(arg, sizeof(arg), &p);
4377 stream->multicast_ttl = atoi(arg);
4379 } else if (!strcasecmp(cmd, "NoLoop")) {
4383 } else if (!strcasecmp(cmd, "</Stream>")) {
4385 fprintf(stderr, "%s:%d: No corresponding <Stream> for </Stream>\n",
4386 filename, line_num);
4389 if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) {
4390 if (audio_id != CODEC_ID_NONE) {
4391 audio_enc.codec_type = CODEC_TYPE_AUDIO;
4392 audio_enc.codec_id = audio_id;
4393 add_codec(stream, &audio_enc);
4395 if (video_id != CODEC_ID_NONE) {
4396 video_enc.codec_type = CODEC_TYPE_VIDEO;
4397 video_enc.codec_id = video_id;
4398 add_codec(stream, &video_enc);
4402 } else if (!strcasecmp(cmd, "<Redirect")) {
4403 /*********************************************/
4405 if (stream || feed || redirect) {
4406 fprintf(stderr, "%s:%d: Already in a tag\n",
4407 filename, line_num);
4410 redirect = av_mallocz(sizeof(FFStream));
4411 *last_stream = redirect;
4412 last_stream = &redirect->next;
4414 get_arg(redirect->filename, sizeof(redirect->filename), &p);
4415 q = strrchr(redirect->filename, '>');
4418 redirect->stream_type = STREAM_TYPE_REDIRECT;
4420 } else if (!strcasecmp(cmd, "URL")) {
4422 get_arg(redirect->feed_filename, sizeof(redirect->feed_filename), &p);
4424 } else if (!strcasecmp(cmd, "</Redirect>")) {
4426 fprintf(stderr, "%s:%d: No corresponding <Redirect> for </Redirect>\n",
4427 filename, line_num);
4430 if (!redirect->feed_filename[0]) {
4431 fprintf(stderr, "%s:%d: No URL found for <Redirect>\n",
4432 filename, line_num);
4436 } else if (!strcasecmp(cmd, "LoadModule")) {
4437 get_arg(arg, sizeof(arg), &p);
4438 #ifdef CONFIG_HAVE_DLOPEN
4441 fprintf(stderr, "%s:%d: Module support not compiled into this version: '%s'\n",
4442 filename, line_num, arg);
4446 fprintf(stderr, "%s:%d: Incorrect keyword: '%s'\n",
4447 filename, line_num, cmd);
4461 static void write_packet(FFCodec *ffenc,
4462 uint8_t *buf, int size)
4465 AVCodecContext *enc = &ffenc->enc;
4467 mk_header(&hdr, enc, size);
4468 wptr = http_fifo.wptr;
4469 fifo_write(&http_fifo, (uint8_t *)&hdr, sizeof(hdr), &wptr);
4470 fifo_write(&http_fifo, buf, size, &wptr);
4471 /* atomic modification of wptr */
4472 http_fifo.wptr = wptr;
4473 ffenc->data_count += size;
4474 ffenc->avg_frame_size = ffenc->avg_frame_size * AVG_COEF + size * (1.0 - AVG_COEF);
4478 static void show_banner(void)
4480 printf("ffserver version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n");
4483 static void show_help(void)
4486 printf("usage: ffserver [-L] [-h] [-f configfile]\n"
4487 "Hyper fast multi format Audio/Video streaming server\n"
4489 "-L : print the LICENSE\n"
4491 "-f configfile : use configfile instead of /etc/ffserver.conf\n"
4495 static void show_license(void)
4499 "This library is free software; you can redistribute it and/or\n"
4500 "modify it under the terms of the GNU Lesser General Public\n"
4501 "License as published by the Free Software Foundation; either\n"
4502 "version 2 of the License, or (at your option) any later version.\n"
4504 "This library is distributed in the hope that it will be useful,\n"
4505 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4506 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
4507 "Lesser General Public License for more details.\n"
4509 "You should have received a copy of the GNU Lesser General Public\n"
4510 "License along with this library; if not, write to the Free Software\n"
4511 "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
4515 static void handle_child_exit(int sig)
4520 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
4523 for (feed = first_feed; feed; feed = feed->next) {
4524 if (feed->pid == pid) {
4525 int uptime = time(0) - feed->pid_start;
4528 fprintf(stderr, "%s: Pid %d exited with status %d after %d seconds\n", feed->filename, pid, status, uptime);
4531 /* Turn off any more restarts */
4532 feed->child_argv = 0;
4538 need_to_start_children = 1;
4541 int main(int argc, char **argv)
4543 const char *config_filename;
4545 struct sigaction sigact;
4549 config_filename = "/etc/ffserver.conf";
4551 my_program_name = argv[0];
4552 my_program_dir = getcwd(0, 0);
4553 ffserver_daemon = 1;
4556 c = getopt(argc, argv, "ndLh?f:");
4572 ffserver_daemon = 0;
4575 config_filename = optarg;
4582 putenv("http_proxy"); /* Kill the http_proxy */
4584 srandom(gettime_ms() + (getpid() << 16));
4586 /* address on which the server will handle HTTP connections */
4587 my_http_addr.sin_family = AF_INET;
4588 my_http_addr.sin_port = htons (8080);
4589 my_http_addr.sin_addr.s_addr = htonl (INADDR_ANY);
4591 /* address on which the server will handle RTSP connections */
4592 my_rtsp_addr.sin_family = AF_INET;
4593 my_rtsp_addr.sin_port = htons (5454);
4594 my_rtsp_addr.sin_addr.s_addr = htonl (INADDR_ANY);
4596 nb_max_connections = 5;
4597 max_bandwidth = 1000;
4598 first_stream = NULL;
4599 logfilename[0] = '\0';
4601 memset(&sigact, 0, sizeof(sigact));
4602 sigact.sa_handler = handle_child_exit;
4603 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
4604 sigaction(SIGCHLD, &sigact, 0);
4606 if (parse_ffconfig(config_filename) < 0) {
4607 fprintf(stderr, "Incorrect config file - exiting.\n");
4611 build_file_streams();
4613 build_feed_streams();
4615 compute_bandwidth();
4617 /* put the process in background and detach it from its TTY */
4618 if (ffserver_daemon) {
4625 } else if (pid > 0) {
4633 open("/dev/null", O_RDWR);
4634 if (strcmp(logfilename, "-") != 0) {
4644 signal(SIGPIPE, SIG_IGN);
4646 /* open log file if needed */
4647 if (logfilename[0] != '\0') {
4648 if (!strcmp(logfilename, "-"))
4651 logfile = fopen(logfilename, "w");
4654 if (http_server() < 0) {
4655 fprintf(stderr, "Could not start server\n");