2 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * multiple format streaming server based on the FFmpeg libraries
28 #define closesocket close
33 #include "libavformat/avformat.h"
34 /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
35 #include "libavformat/ffm.h"
36 #include "libavformat/network.h"
37 #include "libavformat/os_support.h"
38 #include "libavformat/rtpdec.h"
39 #include "libavformat/rtpproto.h"
40 #include "libavformat/rtsp.h"
41 #include "libavformat/rtspcodes.h"
42 #include "libavformat/avio_internal.h"
43 #include "libavformat/internal.h"
44 #include "libavformat/url.h"
46 #include "libavutil/avassert.h"
47 #include "libavutil/avstring.h"
48 #include "libavutil/lfg.h"
49 #include "libavutil/dict.h"
50 #include "libavutil/intreadwrite.h"
51 #include "libavutil/mathematics.h"
52 #include "libavutil/random_seed.h"
53 #include "libavutil/parseutils.h"
54 #include "libavutil/opt.h"
55 #include "libavutil/time.h"
62 #include <sys/ioctl.h>
72 #include "ffserver_config.h"
74 const char program_name[] = "ffserver";
75 const int program_birth_year = 2000;
77 static const OptionDef options[];
80 HTTPSTATE_WAIT_REQUEST,
81 HTTPSTATE_SEND_HEADER,
82 HTTPSTATE_SEND_DATA_HEADER,
83 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
84 HTTPSTATE_SEND_DATA_TRAILER,
85 HTTPSTATE_RECEIVE_DATA,
86 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
89 RTSPSTATE_WAIT_REQUEST,
91 RTSPSTATE_SEND_PACKET,
94 static const char * const http_state[] = {
110 #define IOBUFFER_INIT_SIZE 8192
112 /* timeouts are in ms */
113 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
114 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
116 #define SYNC_TIMEOUT (10 * 1000)
118 typedef struct RTSPActionServerSetup {
120 char transport_option[512];
121 } RTSPActionServerSetup;
124 int64_t count1, count2;
125 int64_t time1, time2;
128 /* context associated with one connection */
129 typedef struct HTTPContext {
130 enum HTTPState state;
131 int fd; /* socket file descriptor */
132 struct sockaddr_in from_addr; /* origin */
133 struct pollfd *poll_entry; /* used when polling */
135 uint8_t *buffer_ptr, *buffer_end;
138 int chunked_encoding;
139 int chunk_size; /* 0 if it needs to be read */
140 struct HTTPContext *next;
141 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
145 /* input format handling */
146 AVFormatContext *fmt_in;
147 int64_t start_time; /* In milliseconds - this wraps fairly often */
148 int64_t first_pts; /* initial pts value */
149 int64_t cur_pts; /* current pts value from the stream in us */
150 int64_t cur_frame_duration; /* duration of the current frame in us */
151 int cur_frame_bytes; /* output frame size, needed to compute
152 the time at which we send each
154 int pts_stream_index; /* stream we choose as clock reference */
155 int64_t cur_clock; /* current clock reference value in us */
156 /* output format handling */
157 struct FFServerStream *stream;
158 /* -1 is invalid stream */
159 int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
160 int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
162 AVFormatContext fmt_ctx; /* instance of FFServerStream for one user */
163 int last_packet_sent; /* true if last data packet was sent */
165 DataRateData datarate;
172 int is_packetized; /* if true, the stream is packetized */
173 int packet_stream_index; /* current stream for output in state machine */
175 /* RTSP state specific */
176 uint8_t *pb_buffer; /* XXX: use that in all the code */
178 int seq; /* RTSP sequence number */
180 /* RTP state specific */
181 enum RTSPLowerTransport rtp_protocol;
182 char session_id[32]; /* session id */
183 AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
185 /* RTP/UDP specific */
186 URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
188 /* RTP/TCP specific */
189 struct HTTPContext *rtsp_c;
190 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
193 typedef struct FeedData {
194 long long data_count;
195 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
198 static HTTPContext *first_http_ctx;
200 static FFServerConfig config = {
201 .nb_max_http_connections = 2000,
202 .nb_max_connections = 5,
203 .max_bandwidth = 1000,
207 static void new_connection(int server_fd, int is_rtsp);
208 static void close_connection(HTTPContext *c);
211 static int handle_connection(HTTPContext *c);
212 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
213 static void compute_status(HTTPContext *c);
214 static int open_input_stream(HTTPContext *c, const char *info);
215 static int http_parse_request(HTTPContext *c);
216 static int http_send_data(HTTPContext *c);
217 static int http_start_receive_data(HTTPContext *c);
218 static int http_receive_data(HTTPContext *c);
221 static int rtsp_parse_request(HTTPContext *c);
222 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
223 static void rtsp_cmd_options(HTTPContext *c, const char *url);
224 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
225 RTSPMessageHeader *h);
226 static void rtsp_cmd_play(HTTPContext *c, const char *url,
227 RTSPMessageHeader *h);
228 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
229 RTSPMessageHeader *h, int pause_only);
232 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
233 struct in_addr my_ip);
236 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
237 FFServerStream *stream,
238 const char *session_id,
239 enum RTSPLowerTransport rtp_protocol);
240 static int rtp_new_av_stream(HTTPContext *c,
241 int stream_index, struct sockaddr_in *dest_addr,
242 HTTPContext *rtsp_c);
244 static const char *my_program_name;
246 static int no_launch;
247 static int need_to_start_children;
249 /* maximum number of simultaneous HTTP connections */
250 static unsigned int nb_connections;
252 static uint64_t current_bandwidth;
254 /* Making this global saves on passing it around everywhere */
255 static int64_t cur_time;
257 static AVLFG random_state;
259 static FILE *logfile = NULL;
261 static void htmlstrip(char *s) {
263 s += strspn(s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,. ");
269 static int64_t ffm_read_write_index(int fd)
273 if (lseek(fd, 8, SEEK_SET) < 0)
275 if (read(fd, buf, 8) != 8)
280 static int ffm_write_write_index(int fd, int64_t pos)
286 buf[i] = (pos >> (56 - i * 8)) & 0xff;
287 if (lseek(fd, 8, SEEK_SET) < 0)
289 if (write(fd, buf, 8) != 8)
294 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
297 FFMContext *ffm = s->priv_data;
298 ffm->write_index = pos;
299 ffm->file_size = file_size;
302 static char *ctime1(char *buf2, int buf_size)
309 av_strlcpy(buf2, p, buf_size);
310 p = buf2 + strlen(p) - 1;
316 static void http_vlog(const char *fmt, va_list vargs)
318 static int print_prefix = 1;
325 ctime1(buf, sizeof(buf));
326 fprintf(logfile, "%s ", buf);
328 print_prefix = strstr(fmt, "\n") != NULL;
329 vfprintf(logfile, fmt, vargs);
334 __attribute__ ((format (printf, 1, 2)))
336 static void http_log(const char *fmt, ...)
339 va_start(vargs, fmt);
340 http_vlog(fmt, vargs);
344 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
346 static int print_prefix = 1;
347 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
348 if (level > av_log_get_level())
350 if (print_prefix && avc)
351 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
352 print_prefix = strstr(fmt, "\n") != NULL;
353 http_vlog(fmt, vargs);
356 static void log_connection(HTTPContext *c)
361 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
362 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
363 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
366 static void update_datarate(DataRateData *drd, int64_t count)
368 if (!drd->time1 && !drd->count1) {
369 drd->time1 = drd->time2 = cur_time;
370 drd->count1 = drd->count2 = count;
371 } else if (cur_time - drd->time2 > 5000) {
372 drd->time1 = drd->time2;
373 drd->count1 = drd->count2;
374 drd->time2 = cur_time;
379 /* In bytes per second */
380 static int compute_datarate(DataRateData *drd, int64_t count)
382 if (cur_time == drd->time1)
385 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
389 static void start_children(FFServerStream *feed)
398 /* replace "ffserver" with "ffmpeg" in the path of current
399 * program. Ignore user provided path */
400 av_strlcpy(pathname, my_program_name, sizeof(pathname));
402 slash = strrchr(pathname, '/');
407 strcpy(slash, "ffmpeg");
409 for (; feed; feed = feed->next) {
411 if (!feed->child_argv || feed->pid)
414 feed->pid_start = time(0);
418 http_log("Unable to create children\n");
427 http_log("Launch command line: ");
428 http_log("%s ", pathname);
430 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
431 http_log("%s ", feed->child_argv[i]);
434 for (i = 3; i < 256; i++)
438 if (!freopen("/dev/null", "r", stdin))
439 http_log("failed to redirect STDIN to /dev/null\n;");
440 if (!freopen("/dev/null", "w", stdout))
441 http_log("failed to redirect STDOUT to /dev/null\n;");
442 if (!freopen("/dev/null", "w", stderr))
443 http_log("failed to redirect STDERR to /dev/null\n;");
446 signal(SIGPIPE, SIG_DFL);
447 execvp(pathname, feed->child_argv);
452 /* open a listening socket */
453 static int socket_open_listen(struct sockaddr_in *my_addr)
457 server_fd = socket(AF_INET,SOCK_STREAM,0);
464 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
465 av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
467 my_addr->sin_family = AF_INET;
468 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
470 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
471 ntohs(my_addr->sin_port));
473 closesocket(server_fd);
477 if (listen (server_fd, 5) < 0) {
479 closesocket(server_fd);
483 if (ff_socket_nonblock(server_fd, 1) < 0)
484 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
489 /* start all multicast streams */
490 static void start_multicast(void)
492 FFServerStream *stream;
495 struct sockaddr_in dest_addr = {0};
496 int default_port, stream_index;
497 unsigned int random0, random1;
500 for(stream = config.first_stream; stream; stream = stream->next) {
502 if (!stream->is_multicast)
505 random0 = av_lfg_get(&random_state);
506 random1 = av_lfg_get(&random_state);
508 /* open the RTP connection */
509 snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
511 /* choose a port if none given */
512 if (stream->multicast_port == 0) {
513 stream->multicast_port = default_port;
517 dest_addr.sin_family = AF_INET;
518 dest_addr.sin_addr = stream->multicast_ip;
519 dest_addr.sin_port = htons(stream->multicast_port);
521 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
522 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
526 if (open_input_stream(rtp_c, "") < 0) {
527 http_log("Could not open input stream for stream '%s'\n",
532 /* open each RTP stream */
533 for(stream_index = 0; stream_index < stream->nb_streams;
535 dest_addr.sin_port = htons(stream->multicast_port +
537 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
540 http_log("Could not open output stream '%s/streamid=%d'\n",
541 stream->filename, stream_index);
545 rtp_c->state = HTTPSTATE_SEND_DATA;
549 /* main loop of the HTTP server */
550 static int http_server(void)
552 int server_fd = 0, rtsp_server_fd = 0;
554 struct pollfd *poll_table, *poll_entry;
555 HTTPContext *c, *c_next;
557 poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
558 sizeof(*poll_table));
560 http_log("Impossible to allocate a poll table handling %d "
561 "connections.\n", config.nb_max_http_connections);
565 if (config.http_addr.sin_port) {
566 server_fd = socket_open_listen(&config.http_addr);
573 if (config.rtsp_addr.sin_port) {
574 rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
575 if (rtsp_server_fd < 0) {
577 closesocket(server_fd);
582 if (!rtsp_server_fd && !server_fd) {
583 http_log("HTTP and RTSP disabled.\n");
588 http_log("FFserver started.\n");
590 start_children(config.first_feed);
595 poll_entry = poll_table;
597 poll_entry->fd = server_fd;
598 poll_entry->events = POLLIN;
601 if (rtsp_server_fd) {
602 poll_entry->fd = rtsp_server_fd;
603 poll_entry->events = POLLIN;
607 /* wait for events on each HTTP handle */
614 case HTTPSTATE_SEND_HEADER:
615 case RTSPSTATE_SEND_REPLY:
616 case RTSPSTATE_SEND_PACKET:
617 c->poll_entry = poll_entry;
619 poll_entry->events = POLLOUT;
622 case HTTPSTATE_SEND_DATA_HEADER:
623 case HTTPSTATE_SEND_DATA:
624 case HTTPSTATE_SEND_DATA_TRAILER:
625 if (!c->is_packetized) {
626 /* for TCP, we output as much as we can
627 * (may need to put a limit) */
628 c->poll_entry = poll_entry;
630 poll_entry->events = POLLOUT;
633 /* when ffserver is doing the timing, we work by
634 * looking at which packet needs to be sent every
635 * 10 ms (one tick wait XXX: 10 ms assumed) */
640 case HTTPSTATE_WAIT_REQUEST:
641 case HTTPSTATE_RECEIVE_DATA:
642 case HTTPSTATE_WAIT_FEED:
643 case RTSPSTATE_WAIT_REQUEST:
644 /* need to catch errors */
645 c->poll_entry = poll_entry;
647 poll_entry->events = POLLIN;/* Maybe this will work */
651 c->poll_entry = NULL;
657 /* wait for an event on one connection. We poll at least every
658 * second to handle timeouts */
660 ret = poll(poll_table, poll_entry - poll_table, delay);
661 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
662 ff_neterrno() != AVERROR(EINTR)) {
668 cur_time = av_gettime() / 1000;
670 if (need_to_start_children) {
671 need_to_start_children = 0;
672 start_children(config.first_feed);
675 /* now handle the events */
676 for(c = first_http_ctx; c; c = c_next) {
678 if (handle_connection(c) < 0) {
680 /* close and free the connection */
685 poll_entry = poll_table;
687 /* new HTTP connection request ? */
688 if (poll_entry->revents & POLLIN)
689 new_connection(server_fd, 0);
692 if (rtsp_server_fd) {
693 /* new RTSP connection request ? */
694 if (poll_entry->revents & POLLIN)
695 new_connection(rtsp_server_fd, 1);
700 /* start waiting for a new HTTP/RTSP request */
701 static void start_wait_request(HTTPContext *c, int is_rtsp)
703 c->buffer_ptr = c->buffer;
704 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
706 c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
707 c->timeout = cur_time +
708 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
711 static void http_send_too_busy_reply(int fd)
714 int len = snprintf(buffer, sizeof(buffer),
715 "HTTP/1.0 503 Server too busy\r\n"
716 "Content-type: text/html\r\n"
718 "<html><head><title>Too busy</title></head><body>\r\n"
719 "<p>The server is too busy to serve your request at this time.</p>\r\n"
720 "<p>The number of current connections is %u, and this exceeds the limit of %u.</p>\r\n"
721 "</body></html>\r\n",
722 nb_connections, config.nb_max_connections);
723 av_assert0(len < sizeof(buffer));
724 if (send(fd, buffer, len, 0) < len)
725 av_log(NULL, AV_LOG_WARNING,
726 "Could not send too-busy reply, send() failed\n");
730 static void new_connection(int server_fd, int is_rtsp)
732 struct sockaddr_in from_addr;
735 HTTPContext *c = NULL;
737 len = sizeof(from_addr);
738 fd = accept(server_fd, (struct sockaddr *)&from_addr,
741 http_log("error during accept %s\n", strerror(errno));
744 if (ff_socket_nonblock(fd, 1) < 0)
745 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
747 if (nb_connections >= config.nb_max_connections) {
748 http_send_too_busy_reply(fd);
752 /* add a new connection */
753 c = av_mallocz(sizeof(HTTPContext));
758 c->poll_entry = NULL;
759 c->from_addr = from_addr;
760 c->buffer_size = IOBUFFER_INIT_SIZE;
761 c->buffer = av_malloc(c->buffer_size);
765 c->next = first_http_ctx;
769 start_wait_request(c, is_rtsp);
775 av_freep(&c->buffer);
781 static void close_connection(HTTPContext *c)
783 HTTPContext **cp, *c1;
785 AVFormatContext *ctx;
788 /* remove connection from list */
789 cp = &first_http_ctx;
798 /* remove references, if any (XXX: do it faster) */
799 for(c1 = first_http_ctx; c1; c1 = c1->next) {
804 /* remove connection associated resources */
808 /* close each frame parser */
809 for(i=0;i<c->fmt_in->nb_streams;i++) {
810 st = c->fmt_in->streams[i];
811 if (st->codec->codec)
812 avcodec_close(st->codec);
814 avformat_close_input(&c->fmt_in);
817 /* free RTP output streams if any */
820 nb_streams = c->stream->nb_streams;
822 for(i=0;i<nb_streams;i++) {
825 av_write_trailer(ctx);
826 av_dict_free(&ctx->metadata);
827 av_freep(&ctx->streams[0]);
830 ffurl_close(c->rtp_handles[i]);
835 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
837 if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
838 av_write_trailer(ctx);
839 av_freep(&c->pb_buffer);
840 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
844 for(i=0; i<ctx->nb_streams; i++)
845 av_freep(&ctx->streams[i]);
846 av_freep(&ctx->streams);
847 av_freep(&ctx->priv_data);
849 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
850 current_bandwidth -= c->stream->bandwidth;
852 /* signal that there is no feed if we are the feeder socket */
853 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
854 c->stream->feed_opened = 0;
858 av_freep(&c->pb_buffer);
859 av_freep(&c->packet_buffer);
860 av_freep(&c->buffer);
865 static int handle_connection(HTTPContext *c)
871 case HTTPSTATE_WAIT_REQUEST:
872 case RTSPSTATE_WAIT_REQUEST:
874 if ((c->timeout - cur_time) < 0)
876 if (c->poll_entry->revents & (POLLERR | POLLHUP))
879 /* no need to read if no events */
880 if (!(c->poll_entry->revents & POLLIN))
884 if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
888 if (ff_neterrno() != AVERROR(EAGAIN) &&
889 ff_neterrno() != AVERROR(EINTR))
893 /* search for end of request. */
894 c->buffer_ptr += len;
896 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
897 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
898 /* request found : parse it and reply */
899 if (c->state == HTTPSTATE_WAIT_REQUEST)
900 ret = http_parse_request(c);
902 ret = rtsp_parse_request(c);
906 } else if (ptr >= c->buffer_end) {
907 /* request too long: cannot do anything */
909 } else goto read_loop;
913 case HTTPSTATE_SEND_HEADER:
914 if (c->poll_entry->revents & (POLLERR | POLLHUP))
917 /* no need to write if no events */
918 if (!(c->poll_entry->revents & POLLOUT))
920 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
922 if (ff_neterrno() != AVERROR(EAGAIN) &&
923 ff_neterrno() != AVERROR(EINTR)) {
924 goto close_connection;
928 c->buffer_ptr += len;
930 c->stream->bytes_served += len;
931 c->data_count += len;
932 if (c->buffer_ptr >= c->buffer_end) {
933 av_freep(&c->pb_buffer);
937 /* all the buffer was sent : synchronize to the incoming
939 c->state = HTTPSTATE_SEND_DATA_HEADER;
940 c->buffer_ptr = c->buffer_end = c->buffer;
944 case HTTPSTATE_SEND_DATA:
945 case HTTPSTATE_SEND_DATA_HEADER:
946 case HTTPSTATE_SEND_DATA_TRAILER:
947 /* for packetized output, we consider we can always write (the
948 * input streams set the speed). It may be better to verify
949 * that we do not rely too much on the kernel queues */
950 if (!c->is_packetized) {
951 if (c->poll_entry->revents & (POLLERR | POLLHUP))
954 /* no need to read if no events */
955 if (!(c->poll_entry->revents & POLLOUT))
958 if (http_send_data(c) < 0)
960 /* close connection if trailer sent */
961 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
963 /* Check if it is a single jpeg frame 123 */
964 if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
968 case HTTPSTATE_RECEIVE_DATA:
969 /* no need to read if no events */
970 if (c->poll_entry->revents & (POLLERR | POLLHUP))
972 if (!(c->poll_entry->revents & POLLIN))
974 if (http_receive_data(c) < 0)
977 case HTTPSTATE_WAIT_FEED:
978 /* no need to read if no events */
979 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
982 /* nothing to do, we'll be waken up by incoming feed packets */
985 case RTSPSTATE_SEND_REPLY:
986 if (c->poll_entry->revents & (POLLERR | POLLHUP))
987 goto close_connection;
988 /* no need to write if no events */
989 if (!(c->poll_entry->revents & POLLOUT))
991 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
993 if (ff_neterrno() != AVERROR(EAGAIN) &&
994 ff_neterrno() != AVERROR(EINTR)) {
995 goto close_connection;
999 c->buffer_ptr += len;
1000 c->data_count += len;
1001 if (c->buffer_ptr >= c->buffer_end) {
1002 /* all the buffer was sent : wait for a new request */
1003 av_freep(&c->pb_buffer);
1004 start_wait_request(c, 1);
1007 case RTSPSTATE_SEND_PACKET:
1008 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1009 av_freep(&c->packet_buffer);
1012 /* no need to write if no events */
1013 if (!(c->poll_entry->revents & POLLOUT))
1015 len = send(c->fd, c->packet_buffer_ptr,
1016 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1018 if (ff_neterrno() != AVERROR(EAGAIN) &&
1019 ff_neterrno() != AVERROR(EINTR)) {
1020 /* error : close connection */
1021 av_freep(&c->packet_buffer);
1026 c->packet_buffer_ptr += len;
1027 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1028 /* all the buffer was sent : wait for a new request */
1029 av_freep(&c->packet_buffer);
1030 c->state = RTSPSTATE_WAIT_REQUEST;
1033 case HTTPSTATE_READY:
1042 av_freep(&c->pb_buffer);
1046 static int extract_rates(char *rates, int ratelen, const char *request)
1050 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1051 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1052 const char *q = p + 7;
1054 while (*q && *q != '\n' && av_isspace(*q))
1057 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1063 memset(rates, 0xff, ratelen);
1066 while (*q && *q != '\n' && *q != ':')
1069 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1073 if (stream_no < ratelen && stream_no >= 0)
1074 rates[stream_no] = rate_no;
1076 while (*q && *q != '\n' && !av_isspace(*q))
1083 p = strchr(p, '\n');
1093 static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec,
1097 int best_bitrate = 100000000;
1100 for (i = 0; i < feed->nb_streams; i++) {
1101 AVCodecContext *feed_codec = feed->streams[i]->codec;
1103 if (feed_codec->codec_id != codec->codec_id ||
1104 feed_codec->sample_rate != codec->sample_rate ||
1105 feed_codec->width != codec->width ||
1106 feed_codec->height != codec->height)
1109 /* Potential stream */
1111 /* We want the fastest stream less than bit_rate, or the slowest
1112 * faster than bit_rate
1115 if (feed_codec->bit_rate <= bit_rate) {
1116 if (best_bitrate > bit_rate ||
1117 feed_codec->bit_rate > best_bitrate) {
1118 best_bitrate = feed_codec->bit_rate;
1123 if (feed_codec->bit_rate < best_bitrate) {
1124 best_bitrate = feed_codec->bit_rate;
1131 static int modify_current_stream(HTTPContext *c, char *rates)
1134 FFServerStream *req = c->stream;
1135 int action_required = 0;
1137 /* Not much we can do for a feed */
1141 for (i = 0; i < req->nb_streams; i++) {
1142 AVCodecContext *codec = req->streams[i]->codec;
1146 c->switch_feed_streams[i] = req->feed_streams[i];
1149 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1152 /* Wants off or slow */
1153 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1155 /* This doesn't work well when it turns off the only stream! */
1156 c->switch_feed_streams[i] = -2;
1157 c->feed_streams[i] = -2;
1162 if (c->switch_feed_streams[i] >= 0 &&
1163 c->switch_feed_streams[i] != c->feed_streams[i]) {
1164 action_required = 1;
1168 return action_required;
1171 static void get_word(char *buf, int buf_size, const char **pp)
1177 p += strspn(p, SPACE_CHARS);
1179 while (!av_isspace(*p) && *p != '\0') {
1180 if ((q - buf) < buf_size - 1)
1189 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1195 FFServerIPAddressACL *acl = NULL;
1199 f = fopen(stream->dynamic_acl, "r");
1201 perror(stream->dynamic_acl);
1205 acl = av_mallocz(sizeof(FFServerIPAddressACL));
1212 while (fgets(line, sizeof(line), f)) {
1215 while (av_isspace(*p))
1217 if (*p == '\0' || *p == '#')
1219 ffserver_get_arg(cmd, sizeof(cmd), &p);
1221 if (!av_strcasecmp(cmd, "ACL"))
1222 ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1230 static void free_acl_list(FFServerIPAddressACL *in_acl)
1232 FFServerIPAddressACL *pacl, *pacl2;
1242 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1244 enum FFServerIPAddressAction last_action = IP_DENY;
1245 FFServerIPAddressACL *acl;
1246 struct in_addr *src = &c->from_addr.sin_addr;
1247 unsigned long src_addr = src->s_addr;
1249 for (acl = in_acl; acl; acl = acl->next) {
1250 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1251 return (acl->action == IP_ALLOW) ? 1 : 0;
1252 last_action = acl->action;
1255 /* Nothing matched, so return not the last action */
1256 return (last_action == IP_DENY) ? 1 : 0;
1259 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1262 FFServerIPAddressACL *acl;
1264 /* if stream->acl is null validate_acl_list will return 1 */
1265 ret = validate_acl_list(stream->acl, c);
1267 if (stream->dynamic_acl[0]) {
1268 acl = parse_dynamic_acl(stream, c);
1269 ret = validate_acl_list(acl, c);
1277 * compute the real filename of a file by matching it without its
1278 * extensions to all the stream's filenames
1280 static void compute_real_filename(char *filename, int max_size)
1285 FFServerStream *stream;
1287 /* compute filename by matching without the file extensions */
1288 av_strlcpy(file1, filename, sizeof(file1));
1289 p = strrchr(file1, '.');
1292 for(stream = config.first_stream; stream; stream = stream->next) {
1293 av_strlcpy(file2, stream->filename, sizeof(file2));
1294 p = strrchr(file2, '.');
1297 if (!strcmp(file1, file2)) {
1298 av_strlcpy(filename, stream->filename, max_size);
1313 /* parse HTTP request and prepare header */
1314 static int http_parse_request(HTTPContext *c)
1318 enum RedirType redir_type;
1320 char info[1024], filename[1024];
1324 const char *mime_type;
1325 FFServerStream *stream;
1328 const char *useragent = 0;
1331 get_word(cmd, sizeof(cmd), &p);
1332 av_strlcpy(c->method, cmd, sizeof(c->method));
1334 if (!strcmp(cmd, "GET"))
1336 else if (!strcmp(cmd, "POST"))
1341 get_word(url, sizeof(url), &p);
1342 av_strlcpy(c->url, url, sizeof(c->url));
1344 get_word(protocol, sizeof(protocol), (const char **)&p);
1345 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1348 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1351 http_log("%s - - New connection: %s %s\n",
1352 inet_ntoa(c->from_addr.sin_addr), cmd, url);
1354 /* find the filename and the optional info string in the request */
1355 p1 = strchr(url, '?');
1357 av_strlcpy(info, p1, sizeof(info));
1362 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1364 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1365 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1367 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1371 p = strchr(p, '\n');
1378 redir_type = REDIR_NONE;
1379 if (av_match_ext(filename, "asx")) {
1380 redir_type = REDIR_ASX;
1381 filename[strlen(filename)-1] = 'f';
1382 } else if (av_match_ext(filename, "asf") &&
1383 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1384 /* if this isn't WMP or lookalike, return the redirector file */
1385 redir_type = REDIR_ASF;
1386 } else if (av_match_ext(filename, "rpm,ram")) {
1387 redir_type = REDIR_RAM;
1388 strcpy(filename + strlen(filename)-2, "m");
1389 } else if (av_match_ext(filename, "rtsp")) {
1390 redir_type = REDIR_RTSP;
1391 compute_real_filename(filename, sizeof(filename) - 1);
1392 } else if (av_match_ext(filename, "sdp")) {
1393 redir_type = REDIR_SDP;
1394 compute_real_filename(filename, sizeof(filename) - 1);
1397 /* "redirect" request to index.html */
1398 if (!strlen(filename))
1399 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1401 stream = config.first_stream;
1403 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1405 stream = stream->next;
1408 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1409 http_log("File '%s' not found\n", url);
1414 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1415 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1417 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1418 c->http_error = 301;
1420 snprintf(q, c->buffer_size,
1421 "HTTP/1.0 301 Moved\r\n"
1423 "Content-type: text/html\r\n"
1425 "<html><head><title>Moved</title></head><body>\r\n"
1426 "You should be <a href=\"%s\">redirected</a>.\r\n"
1427 "</body></html>\r\n",
1428 stream->feed_filename, stream->feed_filename);
1430 /* prepare output buffer */
1431 c->buffer_ptr = c->buffer;
1433 c->state = HTTPSTATE_SEND_HEADER;
1437 /* If this is WMP, get the rate information */
1438 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1439 if (modify_current_stream(c, ratebuf)) {
1440 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1441 if (c->switch_feed_streams[i] >= 0)
1442 c->switch_feed_streams[i] = -1;
1447 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1448 current_bandwidth += stream->bandwidth;
1450 /* If already streaming this feed, do not let start another feeder. */
1451 if (stream->feed_opened) {
1452 snprintf(msg, sizeof(msg), "This feed is already being received.");
1453 http_log("Feed '%s' already being received\n", stream->feed_filename);
1457 if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1458 c->http_error = 503;
1460 snprintf(q, c->buffer_size,
1461 "HTTP/1.0 503 Server too busy\r\n"
1462 "Content-type: text/html\r\n"
1464 "<html><head><title>Too busy</title></head><body>\r\n"
1465 "<p>The server is too busy to serve your request at this time.</p>\r\n"
1466 "<p>The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "
1467 "and this exceeds the limit of %"PRIu64"kbit/sec.</p>\r\n"
1468 "</body></html>\r\n",
1469 current_bandwidth, config.max_bandwidth);
1471 /* prepare output buffer */
1472 c->buffer_ptr = c->buffer;
1474 c->state = HTTPSTATE_SEND_HEADER;
1478 if (redir_type != REDIR_NONE) {
1479 const char *hostinfo = 0;
1481 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1482 if (av_strncasecmp(p, "Host:", 5) == 0) {
1486 p = strchr(p, '\n');
1497 while (av_isspace(*hostinfo))
1500 eoh = strchr(hostinfo, '\n');
1502 if (eoh[-1] == '\r')
1505 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1506 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1507 hostbuf[eoh - hostinfo] = 0;
1509 c->http_error = 200;
1511 switch(redir_type) {
1513 snprintf(q, c->buffer_size,
1514 "HTTP/1.0 200 ASX Follows\r\n"
1515 "Content-type: video/x-ms-asf\r\n"
1517 "<ASX Version=\"3\">\r\n"
1518 //"<!-- Autogenerated by ffserver -->\r\n"
1519 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1520 "</ASX>\r\n", hostbuf, filename, info);
1524 snprintf(q, c->buffer_size,
1525 "HTTP/1.0 200 RAM Follows\r\n"
1526 "Content-type: audio/x-pn-realaudio\r\n"
1528 "# Autogenerated by ffserver\r\n"
1529 "http://%s/%s%s\r\n", hostbuf, filename, info);
1533 snprintf(q, c->buffer_size,
1534 "HTTP/1.0 200 ASF Redirect follows\r\n"
1535 "Content-type: video/x-ms-asf\r\n"
1538 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1543 char hostname[256], *p;
1544 /* extract only hostname */
1545 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1546 p = strrchr(hostname, ':');
1549 snprintf(q, c->buffer_size,
1550 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1551 /* XXX: incorrect MIME type ? */
1552 "Content-type: application/x-rtsp\r\n"
1554 "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1563 struct sockaddr_in my_addr;
1565 snprintf(q, c->buffer_size,
1566 "HTTP/1.0 200 OK\r\n"
1567 "Content-type: application/sdp\r\n"
1571 len = sizeof(my_addr);
1573 /* XXX: Should probably fail? */
1574 if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1575 http_log("getsockname() failed\n");
1577 /* XXX: should use a dynamic buffer */
1578 sdp_data_size = prepare_sdp_description(stream,
1581 if (sdp_data_size > 0) {
1582 memcpy(q, sdp_data, sdp_data_size);
1594 /* prepare output buffer */
1595 c->buffer_ptr = c->buffer;
1597 c->state = HTTPSTATE_SEND_HEADER;
1603 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1607 stream->conns_served++;
1609 /* XXX: add there authenticate and IP match */
1612 /* if post, it means a feed is being sent */
1613 if (!stream->is_feed) {
1614 /* However it might be a status report from WMP! Let us log the
1615 * data as it might come handy one day. */
1616 const char *logline = 0;
1619 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1620 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1624 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1625 client_id = strtol(p + 18, 0, 10);
1626 p = strchr(p, '\n');
1634 char *eol = strchr(logline, '\n');
1639 if (eol[-1] == '\r')
1641 http_log("%.*s\n", (int) (eol - logline), logline);
1642 c->suppress_log = 1;
1647 http_log("\nGot request:\n%s\n", c->buffer);
1650 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1653 /* Now we have to find the client_id */
1654 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1655 if (wmpc->wmp_client_id == client_id)
1659 if (wmpc && modify_current_stream(wmpc, ratebuf))
1660 wmpc->switch_pending = 1;
1663 snprintf(msg, sizeof(msg), "POST command not handled");
1667 if (http_start_receive_data(c) < 0) {
1668 snprintf(msg, sizeof(msg), "could not open feed");
1672 c->state = HTTPSTATE_RECEIVE_DATA;
1677 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1678 http_log("\nGot request:\n%s\n", c->buffer);
1681 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1684 /* open input stream */
1685 if (open_input_stream(c, info) < 0) {
1686 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1690 /* prepare HTTP header */
1692 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1693 mime_type = c->stream->fmt->mime_type;
1695 mime_type = "application/x-octet-stream";
1696 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1698 /* for asf, we need extra headers */
1699 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1700 /* Need to allocate a client id */
1702 c->wmp_client_id = av_lfg_get(&random_state);
1704 av_strlcatf(c->buffer, c->buffer_size, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id);
1706 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1707 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1708 q = c->buffer + strlen(c->buffer);
1710 /* prepare output buffer */
1712 c->buffer_ptr = c->buffer;
1714 c->state = HTTPSTATE_SEND_HEADER;
1717 c->http_error = 404;
1720 snprintf(q, c->buffer_size,
1721 "HTTP/1.0 404 Not Found\r\n"
1722 "Content-type: text/html\r\n"
1725 "<head><title>404 Not Found</title></head>\n"
1729 /* prepare output buffer */
1730 c->buffer_ptr = c->buffer;
1732 c->state = HTTPSTATE_SEND_HEADER;
1736 /* horrible: we use this value to avoid
1737 * going to the send data state */
1738 c->http_error = 200;
1739 c->state = HTTPSTATE_SEND_HEADER;
1743 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1745 static const char suffix[] = " kMGTP";
1748 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1750 avio_printf(pb, "%"PRId64"%c", count, *s);
1753 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1756 const char *type = "unknown";
1757 char parameters[64];
1761 stream_no = stream->nb_streams;
1763 avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
1764 "type<th>kbits/s<th align=left>codec<th align=left>"
1767 for (i = 0; i < stream_no; i++) {
1768 st = stream->streams[i];
1769 codec = avcodec_find_encoder(st->codec->codec_id);
1773 switch(st->codec->codec_type) {
1774 case AVMEDIA_TYPE_AUDIO:
1776 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1777 st->codec->channels, st->codec->sample_rate);
1779 case AVMEDIA_TYPE_VIDEO:
1781 snprintf(parameters, sizeof(parameters),
1782 "%dx%d, q=%d-%d, fps=%d", st->codec->width,
1783 st->codec->height, st->codec->qmin, st->codec->qmax,
1784 st->codec->time_base.den / st->codec->time_base.num);
1790 avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d"
1792 i, type, st->codec->bit_rate/1000,
1793 codec ? codec->name : "", parameters);
1796 avio_printf(pb, "</table>\n");
1799 static void compute_status(HTTPContext *c)
1802 FFServerStream *stream;
1808 if (avio_open_dyn_buf(&pb) < 0) {
1809 /* XXX: return an error ? */
1810 c->buffer_ptr = c->buffer;
1811 c->buffer_end = c->buffer;
1815 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1816 avio_printf(pb, "Content-type: text/html\r\n");
1817 avio_printf(pb, "Pragma: no-cache\r\n");
1818 avio_printf(pb, "\r\n");
1820 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1821 if (c->stream->feed_filename[0])
1822 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1823 c->stream->feed_filename);
1824 avio_printf(pb, "</head>\n<body>");
1825 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1827 avio_printf(pb, "<h2>Available Streams</h2>\n");
1828 avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
1829 avio_printf(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");
1830 stream = config.first_stream;
1832 char sfilename[1024];
1835 if (stream->feed == stream) {
1836 stream = stream->next;
1840 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1841 eosf = sfilename + strlen(sfilename);
1842 if (eosf - sfilename >= 4) {
1843 if (strcmp(eosf - 4, ".asf") == 0)
1844 strcpy(eosf - 4, ".asx");
1845 else if (strcmp(eosf - 3, ".rm") == 0)
1846 strcpy(eosf - 3, ".ram");
1847 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1848 /* generate a sample RTSP director if
1849 * unicast. Generate an SDP redirector if
1851 eosf = strrchr(sfilename, '.');
1853 eosf = sfilename + strlen(sfilename);
1854 if (stream->is_multicast)
1855 strcpy(eosf, ".sdp");
1857 strcpy(eosf, ".rtsp");
1861 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1862 sfilename, stream->filename);
1863 avio_printf(pb, "<td align=right> %d <td align=right> ",
1864 stream->conns_served);
1865 fmt_bytecount(pb, stream->bytes_served);
1867 switch(stream->stream_type) {
1868 case STREAM_TYPE_LIVE: {
1869 int audio_bit_rate = 0;
1870 int video_bit_rate = 0;
1871 const char *audio_codec_name = "";
1872 const char *video_codec_name = "";
1873 const char *audio_codec_name_extra = "";
1874 const char *video_codec_name_extra = "";
1876 for(i=0;i<stream->nb_streams;i++) {
1877 AVStream *st = stream->streams[i];
1878 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1880 switch(st->codec->codec_type) {
1881 case AVMEDIA_TYPE_AUDIO:
1882 audio_bit_rate += st->codec->bit_rate;
1884 if (*audio_codec_name)
1885 audio_codec_name_extra = "...";
1886 audio_codec_name = codec->name;
1889 case AVMEDIA_TYPE_VIDEO:
1890 video_bit_rate += st->codec->bit_rate;
1892 if (*video_codec_name)
1893 video_codec_name_extra = "...";
1894 video_codec_name = codec->name;
1897 case AVMEDIA_TYPE_DATA:
1898 video_bit_rate += st->codec->bit_rate;
1905 avio_printf(pb, "<td align=center> %s <td align=right> %d "
1906 "<td align=right> %d <td> %s %s <td align=right> "
1908 stream->fmt->name, stream->bandwidth,
1909 video_bit_rate / 1000, video_codec_name,
1910 video_codec_name_extra, audio_bit_rate / 1000,
1911 audio_codec_name, audio_codec_name_extra);
1914 avio_printf(pb, "<td>%s", stream->feed->filename);
1916 avio_printf(pb, "<td>%s", stream->feed_filename);
1917 avio_printf(pb, "\n");
1921 avio_printf(pb, "<td align=center> - <td align=right> - "
1922 "<td align=right> - <td><td align=right> - <td>\n");
1925 stream = stream->next;
1927 avio_printf(pb, "</table>\n");
1929 stream = config.first_stream;
1932 if (stream->feed != stream) {
1933 stream = stream->next;
1937 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
1939 avio_printf(pb, "Running as pid %d.\n", stream->pid);
1946 /* This is somewhat linux specific I guess */
1947 snprintf(ps_cmd, sizeof(ps_cmd),
1948 "ps -o \"%%cpu,cputime\" --no-headers %d",
1951 pid_stat = popen(ps_cmd, "r");
1956 if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
1957 avio_printf(pb, "Currently using %s%% of the cpu. "
1958 "Total time used %s.\n",
1966 avio_printf(pb, "<p>");
1969 print_stream_params(pb, stream);
1970 stream = stream->next;
1973 /* connection status */
1974 avio_printf(pb, "<h2>Connection Status</h2>\n");
1976 avio_printf(pb, "Number of connections: %d / %d<br>\n",
1977 nb_connections, config.nb_max_connections);
1979 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
1980 current_bandwidth, config.max_bandwidth);
1982 avio_printf(pb, "<table>\n");
1983 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
1984 "bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
1985 c1 = first_http_ctx;
1993 for (j = 0; j < c1->stream->nb_streams; j++) {
1994 if (!c1->stream->feed)
1995 bitrate += c1->stream->streams[j]->codec->bit_rate;
1996 else if (c1->feed_streams[j] >= 0)
1997 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
2002 p = inet_ntoa(c1->from_addr.sin_addr);
2003 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
2005 i, c1->stream ? c1->stream->filename : "",
2006 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
2007 c1->protocol, http_state[c1->state]);
2008 fmt_bytecount(pb, bitrate);
2009 avio_printf(pb, "<td align=right>");
2010 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2011 avio_printf(pb, "<td align=right>");
2012 fmt_bytecount(pb, c1->data_count);
2013 avio_printf(pb, "\n");
2016 avio_printf(pb, "</table>\n");
2021 avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
2022 avio_printf(pb, "</body>\n</html>\n");
2024 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2025 c->buffer_ptr = c->pb_buffer;
2026 c->buffer_end = c->pb_buffer + len;
2029 static int open_input_stream(HTTPContext *c, const char *info)
2032 char input_filename[1024];
2033 AVFormatContext *s = NULL;
2034 int buf_size, i, ret;
2037 /* find file name */
2038 if (c->stream->feed) {
2039 strcpy(input_filename, c->stream->feed->feed_filename);
2040 buf_size = FFM_PACKET_SIZE;
2041 /* compute position (absolute time) */
2042 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2043 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2044 http_log("Invalid date specification '%s' for stream\n", buf);
2047 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2048 int prebuffer = strtol(buf, 0, 10);
2049 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2051 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2053 strcpy(input_filename, c->stream->feed_filename);
2055 /* compute position (relative time) */
2056 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2057 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2058 http_log("Invalid date specification '%s' for stream\n", buf);
2064 if (!input_filename[0]) {
2065 http_log("No filename was specified for stream\n");
2066 return AVERROR(EINVAL);
2070 ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2071 &c->stream->in_opts);
2073 http_log("Could not open input '%s': %s\n",
2074 input_filename, av_err2str(ret));
2078 /* set buffer size */
2080 ret = ffio_set_buf_size(s->pb, buf_size);
2082 http_log("Failed to set buffer size\n");
2087 s->flags |= AVFMT_FLAG_GENPTS;
2089 if (strcmp(s->iformat->name, "ffm") &&
2090 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2091 http_log("Could not find stream info for input '%s'\n", input_filename);
2092 avformat_close_input(&s);
2096 /* choose stream as clock source (we favor the video stream if
2097 * present) for packet sending */
2098 c->pts_stream_index = 0;
2099 for(i=0;i<c->stream->nb_streams;i++) {
2100 if (c->pts_stream_index == 0 &&
2101 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2102 c->pts_stream_index = i;
2106 if (c->fmt_in->iformat->read_seek)
2107 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2108 /* set the start time (needed for maxtime and RTP packet timing) */
2109 c->start_time = cur_time;
2110 c->first_pts = AV_NOPTS_VALUE;
2114 /* return the server clock (in us) */
2115 static int64_t get_server_clock(HTTPContext *c)
2117 /* compute current pts value from system time */
2118 return (cur_time - c->start_time) * 1000;
2121 /* return the estimated time (in us) at which the current packet must be sent */
2122 static int64_t get_packet_send_clock(HTTPContext *c)
2124 int bytes_left, bytes_sent, frame_bytes;
2126 frame_bytes = c->cur_frame_bytes;
2127 if (frame_bytes <= 0)
2130 bytes_left = c->buffer_end - c->buffer_ptr;
2131 bytes_sent = frame_bytes - bytes_left;
2132 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2136 static int http_prepare_data(HTTPContext *c)
2139 AVFormatContext *ctx;
2141 av_freep(&c->pb_buffer);
2143 case HTTPSTATE_SEND_DATA_HEADER:
2144 ctx = avformat_alloc_context();
2146 return AVERROR(ENOMEM);
2149 av_dict_copy(&(c->fmt_ctx.metadata), c->stream->metadata, 0);
2150 c->fmt_ctx.streams = av_mallocz_array(c->stream->nb_streams,
2151 sizeof(AVStream *));
2152 if (!c->fmt_ctx.streams)
2153 return AVERROR(ENOMEM);
2155 for(i=0;i<c->stream->nb_streams;i++) {
2157 c->fmt_ctx.streams[i] = av_mallocz(sizeof(AVStream));
2159 /* if file or feed, then just take streams from FFServerStream
2161 if (!c->stream->feed ||
2162 c->stream->feed == c->stream)
2163 src = c->stream->streams[i];
2165 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2167 *(c->fmt_ctx.streams[i]) = *src;
2168 c->fmt_ctx.streams[i]->priv_data = 0;
2169 /* XXX: should be done in AVStream, not in codec */
2170 c->fmt_ctx.streams[i]->codec->frame_number = 0;
2172 /* set output format parameters */
2173 c->fmt_ctx.oformat = c->stream->fmt;
2174 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2176 c->got_key_frame = 0;
2178 /* prepare header and save header data in a stream */
2179 if (avio_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2180 /* XXX: potential leak */
2183 c->fmt_ctx.pb->seekable = 0;
2186 * HACK to avoid MPEG-PS muxer to spit many underflow errors
2187 * Default value from FFmpeg
2188 * Try to set it using configuration option
2190 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2192 if ((ret = avformat_write_header(&c->fmt_ctx, NULL)) < 0) {
2193 http_log("Error writing output header for stream '%s': %s\n",
2194 c->stream->filename, av_err2str(ret));
2197 av_dict_free(&c->fmt_ctx.metadata);
2199 len = avio_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2200 c->buffer_ptr = c->pb_buffer;
2201 c->buffer_end = c->pb_buffer + len;
2203 c->state = HTTPSTATE_SEND_DATA;
2204 c->last_packet_sent = 0;
2206 case HTTPSTATE_SEND_DATA:
2207 /* find a new packet */
2208 /* read a packet from the input stream */
2209 if (c->stream->feed)
2210 ffm_set_write_index(c->fmt_in,
2211 c->stream->feed->feed_write_index,
2212 c->stream->feed->feed_size);
2214 if (c->stream->max_time &&
2215 c->stream->max_time + c->start_time - cur_time < 0)
2216 /* We have timed out */
2217 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2221 ret = av_read_frame(c->fmt_in, &pkt);
2223 if (c->stream->feed) {
2224 /* if coming from feed, it means we reached the end of the
2225 * ffm file, so must wait for more data */
2226 c->state = HTTPSTATE_WAIT_FEED;
2227 return 1; /* state changed */
2229 if (ret == AVERROR(EAGAIN)) {
2230 /* input not ready, come back later */
2233 if (c->stream->loop) {
2234 avformat_close_input(&c->fmt_in);
2235 if (open_input_stream(c, "") < 0)
2240 /* must send trailer now because EOF or error */
2241 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2244 int source_index = pkt.stream_index;
2245 /* update first pts if needed */
2246 if (c->first_pts == AV_NOPTS_VALUE) {
2247 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2248 c->start_time = cur_time;
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 & AV_PKT_FLAG_KEY)
2258 c->switch_feed_streams[i] = -1;
2259 if (c->switch_feed_streams[i] >= 0)
2260 c->switch_pending = 1;
2263 for(i=0;i<c->stream->nb_streams;i++) {
2264 if (c->stream->feed_streams[i] == pkt.stream_index) {
2265 AVStream *st = c->fmt_in->streams[source_index];
2266 pkt.stream_index = i;
2267 if (pkt.flags & AV_PKT_FLAG_KEY &&
2268 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2269 c->stream->nb_streams == 1))
2270 c->got_key_frame = 1;
2271 if (!c->stream->send_on_key || c->got_key_frame)
2276 AVCodecContext *codec;
2277 AVStream *ist, *ost;
2279 ist = c->fmt_in->streams[source_index];
2280 /* specific handling for RTP: we use several
2281 * output streams (one for each RTP connection).
2282 * XXX: need more abstract handling */
2283 if (c->is_packetized) {
2284 /* compute send time and duration */
2285 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2286 c->cur_pts -= c->first_pts;
2287 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2288 /* find RTP context */
2289 c->packet_stream_index = pkt.stream_index;
2290 ctx = c->rtp_ctx[c->packet_stream_index];
2292 av_free_packet(&pkt);
2295 codec = ctx->streams[0]->codec;
2296 /* only one stream per RTP connection */
2297 pkt.stream_index = 0;
2301 codec = ctx->streams[pkt.stream_index]->codec;
2304 if (c->is_packetized) {
2305 int max_packet_size;
2306 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2307 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2309 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2310 ret = ffio_open_dyn_packet_buf(&ctx->pb,
2313 ret = avio_open_dyn_buf(&ctx->pb);
2316 /* XXX: potential leak */
2319 ost = ctx->streams[pkt.stream_index];
2321 ctx->pb->seekable = 0;
2322 if (pkt.dts != AV_NOPTS_VALUE)
2323 pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2325 if (pkt.pts != AV_NOPTS_VALUE)
2326 pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2328 pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2330 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2331 http_log("Error writing frame to output for stream '%s': %s\n",
2332 c->stream->filename, av_err2str(ret));
2333 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2336 av_freep(&c->pb_buffer);
2337 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2338 c->cur_frame_bytes = len;
2339 c->buffer_ptr = c->pb_buffer;
2340 c->buffer_end = c->pb_buffer + len;
2342 codec->frame_number++;
2344 av_free_packet(&pkt);
2348 av_free_packet(&pkt);
2353 case HTTPSTATE_SEND_DATA_TRAILER:
2354 /* last packet test ? */
2355 if (c->last_packet_sent || c->is_packetized)
2358 /* prepare header */
2359 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2360 /* XXX: potential leak */
2363 c->fmt_ctx.pb->seekable = 0;
2364 av_write_trailer(ctx);
2365 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2366 c->buffer_ptr = c->pb_buffer;
2367 c->buffer_end = c->pb_buffer + len;
2369 c->last_packet_sent = 1;
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)
2379 static int http_send_data(HTTPContext *c)
2384 if (c->buffer_ptr >= c->buffer_end) {
2385 ret = http_prepare_data(c);
2389 /* 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))
2407 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2408 /* nothing to send yet: we can wait */
2412 c->data_count += len;
2413 update_datarate(&c->datarate, c->data_count);
2415 c->stream->bytes_served += len;
2417 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2418 /* RTP packets are sent inside the RTSP TCP connection */
2420 int interleaved_index, size;
2422 HTTPContext *rtsp_c;
2425 /* if no RTSP connection left, error */
2428 /* if already sending something, then wait. */
2429 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2431 if (avio_open_dyn_buf(&pb) < 0)
2433 interleaved_index = c->packet_stream_index * 2;
2434 /* RTCP packets are sent at odd indexes */
2435 if (c->buffer_ptr[1] == 200)
2436 interleaved_index++;
2437 /* write RTSP TCP header */
2439 header[1] = interleaved_index;
2440 header[2] = len >> 8;
2442 avio_write(pb, header, 4);
2443 /* write RTP packet data */
2445 avio_write(pb, c->buffer_ptr, len);
2446 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2447 /* prepare asynchronous TCP sending */
2448 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2449 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2450 c->buffer_ptr += len;
2452 /* send everything we can NOW */
2453 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2454 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2456 rtsp_c->packet_buffer_ptr += len;
2457 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2458 /* if we could not send all the data, we will
2459 * send it later, so a new state is needed to
2460 * "lock" the RTSP TCP connection */
2461 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2464 /* all data has been sent */
2465 av_freep(&c->packet_buffer);
2467 /* send RTP packet directly in UDP */
2469 ffurl_write(c->rtp_handles[c->packet_stream_index],
2470 c->buffer_ptr, len);
2471 c->buffer_ptr += len;
2472 /* here we continue as we can send several packets
2476 /* TCP data output */
2477 len = send(c->fd, c->buffer_ptr,
2478 c->buffer_end - c->buffer_ptr, 0);
2480 if (ff_neterrno() != AVERROR(EAGAIN) &&
2481 ff_neterrno() != AVERROR(EINTR))
2482 /* error : close connection */
2487 c->buffer_ptr += len;
2489 c->data_count += len;
2490 update_datarate(&c->datarate, c->data_count);
2492 c->stream->bytes_served += len;
2500 static int http_start_receive_data(HTTPContext *c)
2505 if (c->stream->feed_opened) {
2506 http_log("Stream feed '%s' was not opened\n",
2507 c->stream->feed_filename);
2508 return AVERROR(EINVAL);
2511 /* Don't permit writing to this one */
2512 if (c->stream->readonly) {
2513 http_log("Cannot write to read-only file '%s'\n",
2514 c->stream->feed_filename);
2515 return AVERROR(EINVAL);
2519 fd = open(c->stream->feed_filename, O_RDWR);
2521 ret = AVERROR(errno);
2522 http_log("Could not open feed file '%s': %s\n",
2523 c->stream->feed_filename, strerror(errno));
2528 if (c->stream->truncate) {
2529 /* truncate feed file */
2530 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2531 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2532 if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2533 ret = AVERROR(errno);
2534 http_log("Error truncating feed file '%s': %s\n",
2535 c->stream->feed_filename, strerror(errno));
2539 ret = ffm_read_write_index(fd);
2541 http_log("Error reading write index from feed file '%s': %s\n",
2542 c->stream->feed_filename, strerror(errno));
2545 c->stream->feed_write_index = ret;
2548 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2550 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2551 lseek(fd, 0, SEEK_SET);
2553 /* init buffer input */
2554 c->buffer_ptr = c->buffer;
2555 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2556 c->stream->feed_opened = 1;
2557 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2561 static int http_receive_data(HTTPContext *c)
2564 int len, loop_run = 0;
2566 while (c->chunked_encoding && !c->chunk_size &&
2567 c->buffer_end > c->buffer_ptr) {
2568 /* read chunk header, if present */
2569 len = recv(c->fd, c->buffer_ptr, 1, 0);
2572 if (ff_neterrno() != AVERROR(EAGAIN) &&
2573 ff_neterrno() != AVERROR(EINTR))
2574 /* error : close connection */
2577 } else if (len == 0) {
2578 /* end of connection : close it */
2580 } else if (c->buffer_ptr - c->buffer >= 2 &&
2581 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2582 c->chunk_size = strtol(c->buffer, 0, 16);
2583 if (c->chunk_size == 0) // end of stream
2585 c->buffer_ptr = c->buffer;
2587 } else if (++loop_run > 10)
2588 /* no chunk header, abort */
2594 if (c->buffer_end > c->buffer_ptr) {
2595 len = recv(c->fd, c->buffer_ptr,
2596 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2598 if (ff_neterrno() != AVERROR(EAGAIN) &&
2599 ff_neterrno() != AVERROR(EINTR))
2600 /* error : close connection */
2602 } else if (len == 0)
2603 /* end of connection : close it */
2606 c->chunk_size -= len;
2607 c->buffer_ptr += len;
2608 c->data_count += len;
2609 update_datarate(&c->datarate, c->data_count);
2613 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2614 if (c->buffer[0] != 'f' ||
2615 c->buffer[1] != 'm') {
2616 http_log("Feed stream has become desynchronized -- disconnecting\n");
2621 if (c->buffer_ptr >= c->buffer_end) {
2622 FFServerStream *feed = c->stream;
2623 /* a packet has been received : write it in the store, except
2625 if (c->data_count > FFM_PACKET_SIZE) {
2626 /* XXX: use llseek or url_seek
2627 * XXX: Should probably fail? */
2628 if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2629 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2631 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2632 http_log("Error writing to feed file: %s\n", strerror(errno));
2636 feed->feed_write_index += FFM_PACKET_SIZE;
2637 /* update file size */
2638 if (feed->feed_write_index > c->stream->feed_size)
2639 feed->feed_size = feed->feed_write_index;
2641 /* handle wrap around if max file size reached */
2642 if (c->stream->feed_max_size &&
2643 feed->feed_write_index >= c->stream->feed_max_size)
2644 feed->feed_write_index = FFM_PACKET_SIZE;
2647 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2648 http_log("Error writing index to feed file: %s\n",
2653 /* wake up any waiting connections */
2654 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2655 if (c1->state == HTTPSTATE_WAIT_FEED &&
2656 c1->stream->feed == c->stream->feed)
2657 c1->state = HTTPSTATE_SEND_DATA;
2660 /* We have a header in our hands that contains useful data */
2661 AVFormatContext *s = avformat_alloc_context();
2663 AVInputFormat *fmt_in;
2669 /* use feed output format name to find corresponding input format */
2670 fmt_in = av_find_input_format(feed->fmt->name);
2674 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2675 0, NULL, NULL, NULL, NULL);
2682 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2687 /* Now we have the actual streams */
2688 if (s->nb_streams != feed->nb_streams) {
2689 avformat_close_input(&s);
2691 http_log("Feed '%s' stream number does not match registered feed\n",
2692 c->stream->feed_filename);
2696 for (i = 0; i < s->nb_streams; i++) {
2697 AVStream *fst = feed->streams[i];
2698 AVStream *st = s->streams[i];
2699 avcodec_copy_context(fst->codec, st->codec);
2702 avformat_close_input(&s);
2705 c->buffer_ptr = c->buffer;
2710 c->stream->feed_opened = 0;
2712 /* wake up any waiting connections to stop waiting for feed */
2713 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2714 if (c1->state == HTTPSTATE_WAIT_FEED &&
2715 c1->stream->feed == c->stream->feed)
2716 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2721 /********************************************************************/
2724 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2731 str = RTSP_STATUS_CODE2STRING(error_number);
2733 str = "Unknown Error";
2735 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2736 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2738 /* output GMT time */
2741 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2742 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2745 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2747 rtsp_reply_header(c, error_number);
2748 avio_printf(c->pb, "\r\n");
2751 static int rtsp_parse_request(HTTPContext *c)
2753 const char *p, *p1, *p2;
2759 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2761 c->buffer_ptr[0] = '\0';
2764 get_word(cmd, sizeof(cmd), &p);
2765 get_word(url, sizeof(url), &p);
2766 get_word(protocol, sizeof(protocol), &p);
2768 av_strlcpy(c->method, cmd, sizeof(c->method));
2769 av_strlcpy(c->url, url, sizeof(c->url));
2770 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2772 if (avio_open_dyn_buf(&c->pb) < 0) {
2773 /* XXX: cannot do more */
2774 c->pb = NULL; /* safety */
2778 /* check version name */
2779 if (strcmp(protocol, "RTSP/1.0")) {
2780 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2784 /* parse each header line */
2785 /* skip to next line */
2786 while (*p != '\n' && *p != '\0')
2790 while (*p != '\0') {
2791 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2795 if (p2 > p && p2[-1] == '\r')
2797 /* skip empty line */
2801 if (len > sizeof(line) - 1)
2802 len = sizeof(line) - 1;
2803 memcpy(line, p, len);
2805 ff_rtsp_parse_line(header, line, NULL, NULL);
2809 /* handle sequence number */
2810 c->seq = header->seq;
2812 if (!strcmp(cmd, "DESCRIBE"))
2813 rtsp_cmd_describe(c, url);
2814 else if (!strcmp(cmd, "OPTIONS"))
2815 rtsp_cmd_options(c, url);
2816 else if (!strcmp(cmd, "SETUP"))
2817 rtsp_cmd_setup(c, url, header);
2818 else if (!strcmp(cmd, "PLAY"))
2819 rtsp_cmd_play(c, url, header);
2820 else if (!strcmp(cmd, "PAUSE"))
2821 rtsp_cmd_interrupt(c, url, header, 1);
2822 else if (!strcmp(cmd, "TEARDOWN"))
2823 rtsp_cmd_interrupt(c, url, header, 0);
2825 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2828 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2829 c->pb = NULL; /* safety */
2831 /* XXX: cannot do more */
2834 c->buffer_ptr = c->pb_buffer;
2835 c->buffer_end = c->pb_buffer + len;
2836 c->state = RTSPSTATE_SEND_REPLY;
2840 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
2841 struct in_addr my_ip)
2843 AVFormatContext *avc;
2844 AVStream *avs = NULL;
2845 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
2846 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
2851 avc = avformat_alloc_context();
2852 if (!avc || !rtp_format)
2855 avc->oformat = rtp_format;
2856 av_dict_set(&avc->metadata, "title",
2857 entry ? entry->value : "No Title", 0);
2858 avc->nb_streams = stream->nb_streams;
2859 if (stream->is_multicast) {
2860 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2861 inet_ntoa(stream->multicast_ip),
2862 stream->multicast_port, stream->multicast_ttl);
2864 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
2866 avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
2870 avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
2874 for(i = 0; i < stream->nb_streams; i++) {
2875 avc->streams[i] = &avs[i];
2876 avc->streams[i]->codec = stream->streams[i]->codec;
2878 *pbuffer = av_mallocz(2048);
2881 av_sdp_create(&avc, 1, *pbuffer, 2048);
2884 av_freep(&avc->streams);
2885 av_dict_free(&avc->metadata);
2889 return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
2892 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2894 /* rtsp_reply_header(c, RTSP_STATUS_OK); */
2895 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2896 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2897 avio_printf(c->pb, "Public: %s\r\n",
2898 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2899 avio_printf(c->pb, "\r\n");
2902 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2904 FFServerStream *stream;
2910 struct sockaddr_in my_addr;
2912 /* find which URL is asked */
2913 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2918 for(stream = config.first_stream; stream; stream = stream->next) {
2919 if (!stream->is_feed &&
2920 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
2921 !strcmp(path, stream->filename)) {
2925 /* no stream found */
2926 rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
2930 /* prepare the media description in SDP format */
2932 /* get the host IP */
2933 len = sizeof(my_addr);
2934 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
2935 content_length = prepare_sdp_description(stream, &content,
2937 if (content_length < 0) {
2938 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2941 rtsp_reply_header(c, RTSP_STATUS_OK);
2942 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
2943 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
2944 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
2945 avio_printf(c->pb, "\r\n");
2946 avio_write(c->pb, content, content_length);
2950 static HTTPContext *find_rtp_session(const char *session_id)
2954 if (session_id[0] == '\0')
2957 for(c = first_http_ctx; c; c = c->next) {
2958 if (!strcmp(c->session_id, session_id))
2964 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
2966 RTSPTransportField *th;
2969 for(i=0;i<h->nb_transports;i++) {
2970 th = &h->transports[i];
2971 if (th->lower_transport == lower_transport)
2977 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
2978 RTSPMessageHeader *h)
2980 FFServerStream *stream;
2981 int stream_index, rtp_port, rtcp_port;
2986 RTSPTransportField *th;
2987 struct sockaddr_in dest_addr;
2988 RTSPActionServerSetup setup;
2990 /* find which URL is asked */
2991 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2996 /* now check each stream */
2997 for(stream = config.first_stream; stream; stream = stream->next) {
2998 if (stream->is_feed || !stream->fmt ||
2999 strcmp(stream->fmt->name, "rtp")) {
3002 /* accept aggregate filenames only if single stream */
3003 if (!strcmp(path, stream->filename)) {
3004 if (stream->nb_streams != 1) {
3005 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3012 for(stream_index = 0; stream_index < stream->nb_streams;
3014 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3015 stream->filename, stream_index);
3016 if (!strcmp(path, buf))
3020 /* no stream found */
3021 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3025 /* generate session id if needed */
3026 if (h->session_id[0] == '\0') {
3027 unsigned random0 = av_lfg_get(&random_state);
3028 unsigned random1 = av_lfg_get(&random_state);
3029 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3033 /* find RTP session, and create it if none found */
3034 rtp_c = find_rtp_session(h->session_id);
3036 /* always prefer UDP */
3037 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3039 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3041 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3046 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3047 th->lower_transport);
3049 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3053 /* open input stream */
3054 if (open_input_stream(rtp_c, "") < 0) {
3055 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3060 /* test if stream is OK (test needed because several SETUP needs
3061 * to be done for a given file) */
3062 if (rtp_c->stream != stream) {
3063 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3067 /* test if stream is already set up */
3068 if (rtp_c->rtp_ctx[stream_index]) {
3069 rtsp_reply_error(c, RTSP_STATUS_STATE);
3073 /* check transport */
3074 th = find_transport(h, rtp_c->rtp_protocol);
3075 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3076 th->client_port_min <= 0)) {
3077 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3081 /* setup default options */
3082 setup.transport_option[0] = '\0';
3083 dest_addr = rtp_c->from_addr;
3084 dest_addr.sin_port = htons(th->client_port_min);
3087 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3088 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3092 /* now everything is OK, so we can send the connection parameters */
3093 rtsp_reply_header(c, RTSP_STATUS_OK);
3095 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3097 switch(rtp_c->rtp_protocol) {
3098 case RTSP_LOWER_TRANSPORT_UDP:
3099 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3100 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3101 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3102 "client_port=%d-%d;server_port=%d-%d",
3103 th->client_port_min, th->client_port_max,
3104 rtp_port, rtcp_port);
3106 case RTSP_LOWER_TRANSPORT_TCP:
3107 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3108 stream_index * 2, stream_index * 2 + 1);
3113 if (setup.transport_option[0] != '\0')
3114 avio_printf(c->pb, ";%s", setup.transport_option);
3115 avio_printf(c->pb, "\r\n");
3118 avio_printf(c->pb, "\r\n");
3123 * find an RTP connection by using the session ID. Check consistency
3126 static HTTPContext *find_rtp_session_with_url(const char *url,
3127 const char *session_id)
3135 rtp_c = find_rtp_session(session_id);
3139 /* find which URL is asked */
3140 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3144 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3145 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3146 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3147 rtp_c->stream->filename, s);
3148 if(!strncmp(path, buf, sizeof(buf)))
3149 /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3150 * if nb_streams>1? */
3154 if (len > 0 && path[len - 1] == '/' &&
3155 !strncmp(path, rtp_c->stream->filename, len - 1))
3160 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3164 rtp_c = find_rtp_session_with_url(url, h->session_id);
3166 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3170 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3171 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3172 rtp_c->state != HTTPSTATE_READY) {
3173 rtsp_reply_error(c, RTSP_STATUS_STATE);
3177 rtp_c->state = HTTPSTATE_SEND_DATA;
3179 /* now everything is OK, so we can send the connection parameters */
3180 rtsp_reply_header(c, RTSP_STATUS_OK);
3182 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3183 avio_printf(c->pb, "\r\n");
3186 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3187 RTSPMessageHeader *h, int pause_only)
3191 rtp_c = find_rtp_session_with_url(url, h->session_id);
3193 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3198 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3199 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3200 rtsp_reply_error(c, RTSP_STATUS_STATE);
3203 rtp_c->state = HTTPSTATE_READY;
3204 rtp_c->first_pts = AV_NOPTS_VALUE;
3207 /* now everything is OK, so we can send the connection parameters */
3208 rtsp_reply_header(c, RTSP_STATUS_OK);
3210 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3211 avio_printf(c->pb, "\r\n");
3214 close_connection(rtp_c);
3217 /********************************************************************/
3220 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3221 FFServerStream *stream,
3222 const char *session_id,
3223 enum RTSPLowerTransport rtp_protocol)
3225 HTTPContext *c = NULL;
3226 const char *proto_str;
3228 /* XXX: should output a warning page when coming
3229 * close to the connection limit */
3230 if (nb_connections >= config.nb_max_connections)
3233 /* add a new connection */
3234 c = av_mallocz(sizeof(HTTPContext));
3239 c->poll_entry = NULL;
3240 c->from_addr = *from_addr;
3241 c->buffer_size = IOBUFFER_INIT_SIZE;
3242 c->buffer = av_malloc(c->buffer_size);
3247 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3248 c->state = HTTPSTATE_READY;
3249 c->is_packetized = 1;
3250 c->rtp_protocol = rtp_protocol;
3252 /* protocol is shown in statistics */
3253 switch(c->rtp_protocol) {
3254 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3255 proto_str = "MCAST";
3257 case RTSP_LOWER_TRANSPORT_UDP:
3260 case RTSP_LOWER_TRANSPORT_TCP:
3267 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3268 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3270 current_bandwidth += stream->bandwidth;
3272 c->next = first_http_ctx;
3278 av_freep(&c->buffer);
3285 * add a new RTP stream in an RTP connection (used in RTSP SETUP
3286 * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3289 static int rtp_new_av_stream(HTTPContext *c,
3290 int stream_index, struct sockaddr_in *dest_addr,
3291 HTTPContext *rtsp_c)
3293 AVFormatContext *ctx;
3296 URLContext *h = NULL;
3298 int max_packet_size;
3300 /* now we can open the relevant output stream */
3301 ctx = avformat_alloc_context();
3304 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3306 st = av_mallocz(sizeof(AVStream));
3309 ctx->nb_streams = 1;
3310 ctx->streams = av_mallocz_array(ctx->nb_streams, sizeof(AVStream *));
3313 ctx->streams[0] = st;
3315 if (!c->stream->feed ||
3316 c->stream->feed == c->stream)
3317 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3320 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3322 st->priv_data = NULL;
3324 /* build destination RTP address */
3325 ipaddr = inet_ntoa(dest_addr->sin_addr);
3327 switch(c->rtp_protocol) {
3328 case RTSP_LOWER_TRANSPORT_UDP:
3329 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3332 /* XXX: also pass as parameter to function ? */
3333 if (c->stream->is_multicast) {
3335 ttl = c->stream->multicast_ttl;
3338 snprintf(ctx->filename, sizeof(ctx->filename),
3339 "rtp://%s:%d?multicast=1&ttl=%d",
3340 ipaddr, ntohs(dest_addr->sin_port), ttl);
3342 snprintf(ctx->filename, sizeof(ctx->filename),
3343 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3346 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3348 c->rtp_handles[stream_index] = h;
3349 max_packet_size = h->max_packet_size;
3351 case RTSP_LOWER_TRANSPORT_TCP:
3354 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3360 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3361 ipaddr, ntohs(dest_addr->sin_port),
3362 c->stream->filename, stream_index, c->protocol);
3364 /* normally, no packets should be output here, but the packet size may
3366 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3367 /* XXX: close stream */
3370 if (avformat_write_header(ctx, NULL) < 0) {
3378 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3381 c->rtp_ctx[stream_index] = ctx;
3385 /********************************************************************/
3386 /* ffserver initialization */
3388 static AVStream *add_av_stream1(FFServerStream *stream,
3389 AVCodecContext *codec, int copy)
3393 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3396 fst = av_mallocz(sizeof(AVStream));
3400 fst->codec = avcodec_alloc_context3(codec->codec);
3405 avcodec_copy_context(fst->codec, codec);
3407 /* live streams must use the actual feed's codec since it may be
3408 * updated later to carry extradata needed by them.
3412 fst->priv_data = av_mallocz(sizeof(FeedData));
3413 fst->index = stream->nb_streams;
3414 avpriv_set_pts_info(fst, 33, 1, 90000);
3415 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3416 stream->streams[stream->nb_streams++] = fst;
3420 /* return the stream number in the feed */
3421 static int add_av_stream(FFServerStream *feed, AVStream *st)
3424 AVCodecContext *av, *av1;
3428 for(i=0;i<feed->nb_streams;i++) {
3429 av1 = feed->streams[i]->codec;
3430 if (av1->codec_id == av->codec_id &&
3431 av1->codec_type == av->codec_type &&
3432 av1->bit_rate == av->bit_rate) {
3434 switch(av->codec_type) {
3435 case AVMEDIA_TYPE_AUDIO:
3436 if (av1->channels == av->channels &&
3437 av1->sample_rate == av->sample_rate)
3440 case AVMEDIA_TYPE_VIDEO:
3441 if (av1->width == av->width &&
3442 av1->height == av->height &&
3443 av1->time_base.den == av->time_base.den &&
3444 av1->time_base.num == av->time_base.num &&
3445 av1->gop_size == av->gop_size)
3454 fst = add_av_stream1(feed, av, 0);
3457 if (av_stream_get_recommended_encoder_configuration(st))
3458 av_stream_set_recommended_encoder_configuration(fst,
3459 av_strdup(av_stream_get_recommended_encoder_configuration(st)));
3460 return feed->nb_streams - 1;
3463 static void remove_stream(FFServerStream *stream)
3465 FFServerStream **ps;
3466 ps = &config.first_stream;
3475 /* specific MPEG4 handling : we extract the raw parameters */
3476 static void extract_mpeg4_header(AVFormatContext *infile)
3478 int mpeg4_count, i, size;
3483 infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
3486 for(i=0;i<infile->nb_streams;i++) {
3487 st = infile->streams[i];
3488 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3489 st->codec->extradata_size == 0) {
3496 printf("MPEG4 without extra data: trying to find header in %s\n",
3498 while (mpeg4_count > 0) {
3499 if (av_read_frame(infile, &pkt) < 0)
3501 st = infile->streams[pkt.stream_index];
3502 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3503 st->codec->extradata_size == 0) {
3504 av_freep(&st->codec->extradata);
3505 /* fill extradata with the header */
3506 /* XXX: we make hard suppositions here ! */
3508 while (p < pkt.data + pkt.size - 4) {
3509 /* stop when vop header is found */
3510 if (p[0] == 0x00 && p[1] == 0x00 &&
3511 p[2] == 0x01 && p[3] == 0xb6) {
3512 size = p - pkt.data;
3513 st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
3514 st->codec->extradata_size = size;
3515 memcpy(st->codec->extradata, pkt.data, size);
3522 av_free_packet(&pkt);
3526 /* compute the needed AVStream for each file */
3527 static void build_file_streams(void)
3529 FFServerStream *stream, *stream_next;
3532 /* gather all streams */
3533 for(stream = config.first_stream; stream; stream = stream_next) {
3534 AVFormatContext *infile = NULL;
3535 stream_next = stream->next;
3536 if (stream->stream_type == STREAM_TYPE_LIVE &&
3538 /* the stream comes from a file */
3539 /* try to open the file */
3541 if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3542 /* specific case : if transport stream output to RTP,
3543 * we use a raw transport stream reader */
3544 av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3547 if (!stream->feed_filename[0]) {
3548 http_log("Unspecified feed file for stream '%s'\n",
3553 http_log("Opening feed file '%s' for stream '%s'\n",
3554 stream->feed_filename, stream->filename);
3555 ret = avformat_open_input(&infile, stream->feed_filename,
3556 stream->ifmt, &stream->in_opts);
3558 http_log("Could not open '%s': %s\n", stream->feed_filename,
3560 /* remove stream (no need to spend more time on it) */
3562 remove_stream(stream);
3564 /* find all the AVStreams inside and reference them in
3566 if (avformat_find_stream_info(infile, NULL) < 0) {
3567 http_log("Could not find codec parameters from '%s'\n",
3568 stream->feed_filename);
3569 avformat_close_input(&infile);
3572 extract_mpeg4_header(infile);
3574 for(i=0;i<infile->nb_streams;i++)
3575 add_av_stream1(stream, infile->streams[i]->codec, 1);
3577 avformat_close_input(&infile);
3583 /* compute the needed AVStream for each feed */
3584 static void build_feed_streams(void)
3586 FFServerStream *stream, *feed;
3589 /* gather all streams */
3590 for(stream = config.first_stream; stream; stream = stream->next) {
3591 feed = stream->feed;
3595 if (stream->is_feed) {
3596 for(i=0;i<stream->nb_streams;i++)
3597 stream->feed_streams[i] = i;
3599 /* we handle a stream coming from a feed */
3600 for(i=0;i<stream->nb_streams;i++)
3601 stream->feed_streams[i] = add_av_stream(feed,
3602 stream->streams[i]);
3606 /* create feed files if needed */
3607 for(feed = config.first_feed; feed; feed = feed->next_feed) {
3610 if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
3611 /* See if it matches */
3612 AVFormatContext *s = NULL;
3615 if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) >= 0) {
3616 /* set buffer size */
3617 int ret = ffio_set_buf_size(s->pb, FFM_PACKET_SIZE);
3619 http_log("Failed to set buffer size\n");
3623 /* Now see if it matches */
3624 if (s->nb_streams == feed->nb_streams) {
3626 for(i=0;i<s->nb_streams;i++) {
3628 sf = feed->streams[i];
3631 if (sf->index != ss->index ||
3633 http_log("Index & Id do not match for stream %d (%s)\n",
3634 i, feed->feed_filename);
3637 AVCodecContext *ccf, *ccs;
3641 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3643 if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3644 http_log("Codecs do not match for stream %d\n", i);
3646 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3647 http_log("Codec bitrates do not match for stream %d\n", i);
3649 } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
3650 if (CHECK_CODEC(time_base.den) ||
3651 CHECK_CODEC(time_base.num) ||
3652 CHECK_CODEC(width) ||
3653 CHECK_CODEC(height)) {
3654 http_log("Codec width, height and framerate do not match for stream %d\n", i);
3657 } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
3658 if (CHECK_CODEC(sample_rate) ||
3659 CHECK_CODEC(channels) ||
3660 CHECK_CODEC(frame_size)) {
3661 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3665 http_log("Unknown codec type\n");
3673 http_log("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3674 feed->feed_filename, s->nb_streams, feed->nb_streams);
3676 avformat_close_input(&s);
3678 http_log("Deleting feed file '%s' as it appears to be corrupt\n",
3679 feed->feed_filename);
3682 if (feed->readonly) {
3683 http_log("Unable to delete feed file '%s' as it is marked readonly\n",
3684 feed->feed_filename);
3687 unlink(feed->feed_filename);
3690 if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
3691 AVFormatContext *s = avformat_alloc_context();
3694 http_log("Failed to allocate context\n");
3698 if (feed->readonly) {
3699 http_log("Unable to create feed file '%s' as it is marked readonly\n",
3700 feed->feed_filename);
3704 /* only write the header of the ffm file */
3705 if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
3706 http_log("Could not open output feed file '%s'\n",
3707 feed->feed_filename);
3710 s->oformat = feed->fmt;
3711 s->nb_streams = feed->nb_streams;
3712 s->streams = feed->streams;
3713 if (avformat_write_header(s, NULL) < 0) {
3714 http_log("Container doesn't support the required parameters\n");
3717 /* XXX: need better API */
3718 av_freep(&s->priv_data);
3719 avio_closep(&s->pb);
3722 avformat_free_context(s);
3724 /* get feed size and write index */
3725 fd = open(feed->feed_filename, O_RDONLY);
3727 http_log("Could not open output feed file '%s'\n",
3728 feed->feed_filename);
3732 feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
3733 feed->feed_size = lseek(fd, 0, SEEK_END);
3734 /* ensure that we do not wrap before the end of file */
3735 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3736 feed->feed_max_size = feed->feed_size;
3742 /* compute the bandwidth used by each stream */
3743 static void compute_bandwidth(void)
3747 FFServerStream *stream;
3749 for(stream = config.first_stream; stream; stream = stream->next) {
3751 for(i=0;i<stream->nb_streams;i++) {
3752 AVStream *st = stream->streams[i];
3753 switch(st->codec->codec_type) {
3754 case AVMEDIA_TYPE_AUDIO:
3755 case AVMEDIA_TYPE_VIDEO:
3756 bandwidth += st->codec->bit_rate;
3762 stream->bandwidth = (bandwidth + 999) / 1000;
3766 static void handle_child_exit(int sig)
3771 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3772 FFServerStream *feed;
3774 for (feed = config.first_feed; feed; feed = feed->next) {
3775 if (feed->pid != pid)
3778 uptime = time(0) - feed->pid_start;
3781 "%s: Pid %d exited with status %d after %d seconds\n",
3782 feed->filename, pid, status, uptime);
3785 /* Turn off any more restarts */
3786 ffserver_free_child_args(&feed->child_argv);
3790 need_to_start_children = 1;
3793 static void opt_debug(void)
3796 snprintf(config.logfilename, sizeof(config.logfilename), "-");
3799 void show_help_default(const char *opt, const char *arg)
3801 printf("usage: ffserver [options]\n"
3802 "Hyper fast multi format Audio/Video streaming server\n");
3804 show_help_options(options, "Main options:", 0, 0, 0);
3807 static const OptionDef options[] = {
3808 #include "cmdutils_common_opts.h"
3809 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
3810 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
3811 { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
3815 int main(int argc, char **argv)
3817 struct sigaction sigact = { { 0 } };
3820 config.filename = av_strdup("/etc/ffserver.conf");
3822 parse_loglevel(argc, argv, options);
3824 avformat_network_init();
3826 show_banner(argc, argv, options);
3828 my_program_name = argv[0];
3830 parse_options(NULL, argc, argv, options, NULL);
3832 unsetenv("http_proxy"); /* Kill the http_proxy */
3834 av_lfg_init(&random_state, av_get_random_seed());
3836 sigact.sa_handler = handle_child_exit;
3837 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
3838 sigaction(SIGCHLD, &sigact, 0);
3840 if ((ret = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
3841 fprintf(stderr, "Error reading configuration file '%s': %s\n",
3842 config.filename, av_err2str(ret));
3845 av_freep(&config.filename);
3847 /* open log file if needed */
3848 if (config.logfilename[0] != '\0') {
3849 if (!strcmp(config.logfilename, "-"))
3852 logfile = fopen(config.logfilename, "a");
3853 av_log_set_callback(http_av_log);
3856 build_file_streams();
3858 build_feed_streams();
3860 compute_bandwidth();
3863 signal(SIGPIPE, SIG_IGN);
3865 if (http_server() < 0) {
3866 http_log("Could not start server\n");