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/rtpproto.h"
36 #include "libavformat/rtsp.h"
37 #include "libavformat/avio_internal.h"
38 #include "libavformat/internal.h"
40 #include "libavutil/avassert.h"
41 #include "libavutil/avstring.h"
42 #include "libavutil/lfg.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/mathematics.h"
46 #include "libavutil/random_seed.h"
47 #include "libavutil/rational.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/time.h"
57 #include <sys/ioctl.h>
67 #include "ffserver_config.h"
69 #define PATH_LENGTH 1024
71 const char program_name[] = "ffserver";
72 const int program_birth_year = 2000;
74 static const OptionDef options[];
77 HTTPSTATE_WAIT_REQUEST,
78 HTTPSTATE_SEND_HEADER,
79 HTTPSTATE_SEND_DATA_HEADER,
80 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
81 HTTPSTATE_SEND_DATA_TRAILER,
82 HTTPSTATE_RECEIVE_DATA,
83 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
86 RTSPSTATE_WAIT_REQUEST,
88 RTSPSTATE_SEND_PACKET,
91 static const char * const http_state[] = {
107 #define IOBUFFER_INIT_SIZE 8192
109 /* timeouts are in ms */
110 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
111 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
113 #define SYNC_TIMEOUT (10 * 1000)
115 typedef struct RTSPActionServerSetup {
117 char transport_option[512];
118 } RTSPActionServerSetup;
121 int64_t count1, count2;
122 int64_t time1, time2;
125 /* context associated with one connection */
126 typedef struct HTTPContext {
127 enum HTTPState state;
128 int fd; /* socket file descriptor */
129 struct sockaddr_in from_addr; /* origin */
130 struct pollfd *poll_entry; /* used when polling */
132 uint8_t *buffer_ptr, *buffer_end;
135 int chunked_encoding;
136 int chunk_size; /* 0 if it needs to be read */
137 struct HTTPContext *next;
138 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
142 /* input format handling */
143 AVFormatContext *fmt_in;
144 int64_t start_time; /* In milliseconds - this wraps fairly often */
145 int64_t first_pts; /* initial pts value */
146 int64_t cur_pts; /* current pts value from the stream in us */
147 int64_t cur_frame_duration; /* duration of the current frame in us */
148 int cur_frame_bytes; /* output frame size, needed to compute
149 the time at which we send each
151 int pts_stream_index; /* stream we choose as clock reference */
152 int64_t cur_clock; /* current clock reference value in us */
153 /* output format handling */
154 struct FFServerStream *stream;
155 /* -1 is invalid stream */
156 int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
157 int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
159 AVFormatContext *pfmt_ctx; /* instance of FFServerStream for one user */
160 int last_packet_sent; /* true if last data packet was sent */
162 DataRateData datarate;
167 char clean_url[128*7];
170 int is_packetized; /* if true, the stream is packetized */
171 int packet_stream_index; /* current stream for output in state machine */
173 /* RTSP state specific */
174 uint8_t *pb_buffer; /* XXX: use that in all the code */
176 int seq; /* RTSP sequence number */
178 /* RTP state specific */
179 enum RTSPLowerTransport rtp_protocol;
180 char session_id[32]; /* session id */
181 AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
183 /* RTP/UDP specific */
184 URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
186 /* RTP/TCP specific */
187 struct HTTPContext *rtsp_c;
188 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
191 static HTTPContext *first_http_ctx;
193 static FFServerConfig config = {
194 .nb_max_http_connections = 2000,
195 .nb_max_connections = 5,
196 .max_bandwidth = 1000,
200 static void new_connection(int server_fd, int is_rtsp);
201 static void close_connection(HTTPContext *c);
204 static int handle_connection(HTTPContext *c);
205 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
206 static void compute_status(HTTPContext *c);
207 static int open_input_stream(HTTPContext *c, const char *info);
208 static int http_parse_request(HTTPContext *c);
209 static int http_send_data(HTTPContext *c);
210 static int http_start_receive_data(HTTPContext *c);
211 static int http_receive_data(HTTPContext *c);
214 static int rtsp_parse_request(HTTPContext *c);
215 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
216 static void rtsp_cmd_options(HTTPContext *c, const char *url);
217 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
218 RTSPMessageHeader *h);
219 static void rtsp_cmd_play(HTTPContext *c, const char *url,
220 RTSPMessageHeader *h);
221 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
222 RTSPMessageHeader *h, int pause_only);
225 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
226 struct in_addr my_ip);
229 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
230 FFServerStream *stream,
231 const char *session_id,
232 enum RTSPLowerTransport rtp_protocol);
233 static int rtp_new_av_stream(HTTPContext *c,
234 int stream_index, struct sockaddr_in *dest_addr,
235 HTTPContext *rtsp_c);
237 static size_t htmlencode (const char *src, char **dest);
238 static inline void cp_html_entity (char *buffer, const char *entity);
239 static inline int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream);
241 static const char *my_program_name;
243 static int no_launch;
244 static int need_to_start_children;
246 /* maximum number of simultaneous HTTP connections */
247 static unsigned int nb_connections;
249 static uint64_t current_bandwidth;
251 /* Making this global saves on passing it around everywhere */
252 static int64_t cur_time;
254 static AVLFG random_state;
256 static FILE *logfile = NULL;
258 static void unlayer_stream(AVStream *st, LayeredAVStream *lst)
260 avcodec_free_context(&st->codec);
261 avcodec_parameters_free(&st->codecpar);
262 #define COPY(a) st->a = lst->a;
269 COPY(sample_aspect_ratio)
270 COPY(recommended_encoder_configuration)
273 static inline void cp_html_entity (char *buffer, const char *entity) {
274 if (!buffer || !entity)
277 *buffer++ = *entity++;
281 * Substitutes known conflicting chars on a text string with
282 * their corresponding HTML entities.
284 * Returns the number of bytes in the 'encoded' representation
285 * not including the terminating NUL.
287 static size_t htmlencode (const char *src, char **dest) {
288 const char *amp = "&";
289 const char *lt = "<";
290 const char *gt = ">";
293 size_t final_size = 0;
300 /* Compute needed dest size */
301 while (*src != '\0') {
317 *dest = av_mallocz(final_size + 1);
323 while (*src != '\0') {
326 cp_html_entity (tmp, amp);
330 cp_html_entity (tmp, lt);
334 cp_html_entity (tmp, gt);
348 static int64_t ffm_read_write_index(int fd)
352 if (lseek(fd, 8, SEEK_SET) < 0)
354 if (read(fd, buf, 8) != 8)
359 static int ffm_write_write_index(int fd, int64_t pos)
365 buf[i] = (pos >> (56 - i * 8)) & 0xff;
366 if (lseek(fd, 8, SEEK_SET) < 0)
368 if (write(fd, buf, 8) != 8)
377 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
380 av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
381 av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
382 av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
385 static char *ctime1(char *buf2, size_t buf_size)
396 av_strlcpy(buf2, p, buf_size);
397 p = buf2 + strlen(buf2) - 1;
403 static void http_vlog(const char *fmt, va_list vargs)
405 static int print_prefix = 1;
412 ctime1(buf, sizeof(buf));
413 fprintf(logfile, "%s ", buf);
415 print_prefix = strstr(fmt, "\n") != NULL;
416 vfprintf(logfile, fmt, vargs);
421 __attribute__ ((format (printf, 1, 2)))
423 static void http_log(const char *fmt, ...)
426 va_start(vargs, fmt);
427 http_vlog(fmt, vargs);
431 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
433 static int print_prefix = 1;
434 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
435 if (level > av_log_get_level())
437 if (print_prefix && avc)
438 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
439 print_prefix = strstr(fmt, "\n") != NULL;
440 http_vlog(fmt, vargs);
443 static void log_connection(HTTPContext *c)
448 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
449 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
450 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
453 static void update_datarate(DataRateData *drd, int64_t count)
455 if (!drd->time1 && !drd->count1) {
456 drd->time1 = drd->time2 = cur_time;
457 drd->count1 = drd->count2 = count;
458 } else if (cur_time - drd->time2 > 5000) {
459 drd->time1 = drd->time2;
460 drd->count1 = drd->count2;
461 drd->time2 = cur_time;
466 /* In bytes per second */
467 static int compute_datarate(DataRateData *drd, int64_t count)
469 if (cur_time == drd->time1)
472 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
476 static void start_children(FFServerStream *feed)
486 cmd_length = strlen(my_program_name);
489 * FIXME: WIP Safeguard. Remove after clearing all harcoded
490 * '1024' path lengths
492 if (cmd_length > PATH_LENGTH - 1) {
493 http_log("Could not start children. Command line: '%s' exceeds "
494 "path length limit (%d)\n", my_program_name, PATH_LENGTH);
498 pathname = av_strdup (my_program_name);
500 http_log("Could not allocate memory for children cmd line\n");
503 /* replace "ffserver" with "ffmpeg" in the path of current
504 * program. Ignore user provided path */
506 slash = strrchr(pathname, '/');
511 strcpy(slash, "ffmpeg");
513 for (; feed; feed = feed->next) {
515 if (!feed->child_argv || feed->pid)
518 feed->pid_start = time(0);
522 http_log("Unable to create children: %s\n", strerror(errno));
532 http_log("Launch command line: ");
533 http_log("%s ", pathname);
535 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
536 http_log("%s ", feed->child_argv[i]);
539 for (i = 3; i < 256; i++)
543 if (!freopen("/dev/null", "r", stdin))
544 http_log("failed to redirect STDIN to /dev/null\n;");
545 if (!freopen("/dev/null", "w", stdout))
546 http_log("failed to redirect STDOUT to /dev/null\n;");
547 if (!freopen("/dev/null", "w", stderr))
548 http_log("failed to redirect STDERR to /dev/null\n;");
551 signal(SIGPIPE, SIG_DFL);
552 execvp(pathname, feed->child_argv);
559 /* open a listening socket */
560 static int socket_open_listen(struct sockaddr_in *my_addr)
564 server_fd = socket(AF_INET,SOCK_STREAM,0);
571 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
572 av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
574 my_addr->sin_family = AF_INET;
575 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
577 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
578 ntohs(my_addr->sin_port));
583 if (listen (server_fd, 5) < 0) {
588 if (ff_socket_nonblock(server_fd, 1) < 0)
589 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
594 closesocket(server_fd);
598 /* start all multicast streams */
599 static void start_multicast(void)
601 FFServerStream *stream;
604 struct sockaddr_in dest_addr = {0};
605 int default_port, stream_index;
606 unsigned int random0, random1;
609 for(stream = config.first_stream; stream; stream = stream->next) {
611 if (!stream->is_multicast)
614 random0 = av_lfg_get(&random_state);
615 random1 = av_lfg_get(&random_state);
617 /* open the RTP connection */
618 snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
620 /* choose a port if none given */
621 if (stream->multicast_port == 0) {
622 stream->multicast_port = default_port;
626 dest_addr.sin_family = AF_INET;
627 dest_addr.sin_addr = stream->multicast_ip;
628 dest_addr.sin_port = htons(stream->multicast_port);
630 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
631 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
635 if (open_input_stream(rtp_c, "") < 0) {
636 http_log("Could not open input stream for stream '%s'\n",
641 /* open each RTP stream */
642 for(stream_index = 0; stream_index < stream->nb_streams;
644 dest_addr.sin_port = htons(stream->multicast_port +
646 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
649 http_log("Could not open output stream '%s/streamid=%d'\n",
650 stream->filename, stream_index);
654 rtp_c->state = HTTPSTATE_SEND_DATA;
658 /* main loop of the HTTP server */
659 static int http_server(void)
661 int server_fd = 0, rtsp_server_fd = 0;
663 struct pollfd *poll_table, *poll_entry;
664 HTTPContext *c, *c_next;
666 poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
667 sizeof(*poll_table));
669 http_log("Impossible to allocate a poll table handling %d "
670 "connections.\n", config.nb_max_http_connections);
674 if (config.http_addr.sin_port) {
675 server_fd = socket_open_listen(&config.http_addr);
680 if (config.rtsp_addr.sin_port) {
681 rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
682 if (rtsp_server_fd < 0) {
683 closesocket(server_fd);
688 if (!rtsp_server_fd && !server_fd) {
689 http_log("HTTP and RTSP disabled.\n");
693 http_log("FFserver started.\n");
695 start_children(config.first_feed);
700 poll_entry = poll_table;
702 poll_entry->fd = server_fd;
703 poll_entry->events = POLLIN;
706 if (rtsp_server_fd) {
707 poll_entry->fd = rtsp_server_fd;
708 poll_entry->events = POLLIN;
712 /* wait for events on each HTTP handle */
719 case HTTPSTATE_SEND_HEADER:
720 case RTSPSTATE_SEND_REPLY:
721 case RTSPSTATE_SEND_PACKET:
722 c->poll_entry = poll_entry;
724 poll_entry->events = POLLOUT;
727 case HTTPSTATE_SEND_DATA_HEADER:
728 case HTTPSTATE_SEND_DATA:
729 case HTTPSTATE_SEND_DATA_TRAILER:
730 if (!c->is_packetized) {
731 /* for TCP, we output as much as we can
732 * (may need to put a limit) */
733 c->poll_entry = poll_entry;
735 poll_entry->events = POLLOUT;
738 /* when ffserver is doing the timing, we work by
739 * looking at which packet needs to be sent every
740 * 10 ms (one tick wait XXX: 10 ms assumed) */
745 case HTTPSTATE_WAIT_REQUEST:
746 case HTTPSTATE_RECEIVE_DATA:
747 case HTTPSTATE_WAIT_FEED:
748 case RTSPSTATE_WAIT_REQUEST:
749 /* need to catch errors */
750 c->poll_entry = poll_entry;
752 poll_entry->events = POLLIN;/* Maybe this will work */
756 c->poll_entry = NULL;
762 /* wait for an event on one connection. We poll at least every
763 * second to handle timeouts */
765 ret = poll(poll_table, poll_entry - poll_table, delay);
766 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
767 ff_neterrno() != AVERROR(EINTR)) {
772 cur_time = av_gettime() / 1000;
774 if (need_to_start_children) {
775 need_to_start_children = 0;
776 start_children(config.first_feed);
779 /* now handle the events */
780 for(c = first_http_ctx; c; c = c_next) {
782 if (handle_connection(c) < 0) {
784 /* close and free the connection */
789 poll_entry = poll_table;
791 /* new HTTP connection request ? */
792 if (poll_entry->revents & POLLIN)
793 new_connection(server_fd, 0);
796 if (rtsp_server_fd) {
797 /* new RTSP connection request ? */
798 if (poll_entry->revents & POLLIN)
799 new_connection(rtsp_server_fd, 1);
808 /* start waiting for a new HTTP/RTSP request */
809 static void start_wait_request(HTTPContext *c, int is_rtsp)
811 c->buffer_ptr = c->buffer;
812 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
814 c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
815 c->timeout = cur_time +
816 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
819 static void http_send_too_busy_reply(int fd)
822 int len = snprintf(buffer, sizeof(buffer),
823 "HTTP/1.0 503 Server too busy\r\n"
824 "Content-type: text/html\r\n"
827 "<html><head><title>Too busy</title></head><body>\r\n"
828 "<p>The server is too busy to serve your request at "
830 "<p>The number of current connections is %u, and this "
831 "exceeds the limit of %u.</p>\r\n"
832 "</body></html>\r\n",
833 nb_connections, config.nb_max_connections);
834 av_assert0(len < sizeof(buffer));
835 if (send(fd, buffer, len, 0) < len)
836 av_log(NULL, AV_LOG_WARNING,
837 "Could not send too-busy reply, send() failed\n");
841 static void new_connection(int server_fd, int is_rtsp)
843 struct sockaddr_in from_addr;
846 HTTPContext *c = NULL;
848 len = sizeof(from_addr);
849 fd = accept(server_fd, (struct sockaddr *)&from_addr,
852 http_log("error during accept %s\n", strerror(errno));
855 if (ff_socket_nonblock(fd, 1) < 0)
856 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
858 if (nb_connections >= config.nb_max_connections) {
859 http_send_too_busy_reply(fd);
863 /* add a new connection */
864 c = av_mallocz(sizeof(HTTPContext));
869 c->poll_entry = NULL;
870 c->from_addr = from_addr;
871 c->buffer_size = IOBUFFER_INIT_SIZE;
872 c->buffer = av_malloc(c->buffer_size);
876 c->next = first_http_ctx;
880 start_wait_request(c, is_rtsp);
886 av_freep(&c->buffer);
892 static void close_connection(HTTPContext *c)
894 HTTPContext **cp, *c1;
896 AVFormatContext *ctx;
899 /* remove connection from list */
900 cp = &first_http_ctx;
909 /* remove references, if any (XXX: do it faster) */
910 for(c1 = first_http_ctx; c1; c1 = c1->next) {
915 /* remove connection associated resources */
919 /* close each frame parser */
920 for(i=0;i<c->fmt_in->nb_streams;i++) {
921 st = c->fmt_in->streams[i];
922 if (st->codec->codec)
923 avcodec_close(st->codec);
925 avformat_close_input(&c->fmt_in);
928 /* free RTP output streams if any */
931 nb_streams = c->stream->nb_streams;
933 for(i=0;i<nb_streams;i++) {
936 av_write_trailer(ctx);
937 av_dict_free(&ctx->metadata);
938 av_freep(&ctx->streams[0]);
941 ffurl_close(c->rtp_handles[i]);
947 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
949 if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
950 av_write_trailer(ctx);
951 av_freep(&c->pb_buffer);
952 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
955 for(i=0; i<ctx->nb_streams; i++)
956 av_freep(&ctx->streams[i]);
957 av_freep(&ctx->streams);
958 av_freep(&ctx->priv_data);
961 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
962 current_bandwidth -= c->stream->bandwidth;
964 /* signal that there is no feed if we are the feeder socket */
965 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
966 c->stream->feed_opened = 0;
970 av_freep(&c->pb_buffer);
971 av_freep(&c->packet_buffer);
972 av_freep(&c->buffer);
977 static int handle_connection(HTTPContext *c)
983 case HTTPSTATE_WAIT_REQUEST:
984 case RTSPSTATE_WAIT_REQUEST:
986 if ((c->timeout - cur_time) < 0)
988 if (c->poll_entry->revents & (POLLERR | POLLHUP))
991 /* no need to read if no events */
992 if (!(c->poll_entry->revents & POLLIN))
996 if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
1000 if (ff_neterrno() != AVERROR(EAGAIN) &&
1001 ff_neterrno() != AVERROR(EINTR))
1005 /* search for end of request. */
1006 c->buffer_ptr += len;
1007 ptr = c->buffer_ptr;
1008 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
1009 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
1010 /* request found : parse it and reply */
1011 if (c->state == HTTPSTATE_WAIT_REQUEST)
1012 ret = http_parse_request(c);
1014 ret = rtsp_parse_request(c);
1018 } else if (ptr >= c->buffer_end) {
1019 /* request too long: cannot do anything */
1021 } else goto read_loop;
1025 case HTTPSTATE_SEND_HEADER:
1026 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1029 /* no need to write if no events */
1030 if (!(c->poll_entry->revents & POLLOUT))
1032 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1034 if (ff_neterrno() != AVERROR(EAGAIN) &&
1035 ff_neterrno() != AVERROR(EINTR)) {
1036 goto close_connection;
1040 c->buffer_ptr += len;
1042 c->stream->bytes_served += len;
1043 c->data_count += len;
1044 if (c->buffer_ptr >= c->buffer_end) {
1045 av_freep(&c->pb_buffer);
1046 /* if error, exit */
1049 /* all the buffer was sent : synchronize to the incoming
1051 c->state = HTTPSTATE_SEND_DATA_HEADER;
1052 c->buffer_ptr = c->buffer_end = c->buffer;
1056 case HTTPSTATE_SEND_DATA:
1057 case HTTPSTATE_SEND_DATA_HEADER:
1058 case HTTPSTATE_SEND_DATA_TRAILER:
1059 /* for packetized output, we consider we can always write (the
1060 * input streams set the speed). It may be better to verify
1061 * that we do not rely too much on the kernel queues */
1062 if (!c->is_packetized) {
1063 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1066 /* no need to read if no events */
1067 if (!(c->poll_entry->revents & POLLOUT))
1070 if (http_send_data(c) < 0)
1072 /* close connection if trailer sent */
1073 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
1075 /* Check if it is a single jpeg frame 123 */
1076 if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
1077 close_connection(c);
1080 case HTTPSTATE_RECEIVE_DATA:
1081 /* no need to read if no events */
1082 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1084 if (!(c->poll_entry->revents & POLLIN))
1086 if (http_receive_data(c) < 0)
1089 case HTTPSTATE_WAIT_FEED:
1090 /* no need to read if no events */
1091 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1094 /* nothing to do, we'll be waken up by incoming feed packets */
1097 case RTSPSTATE_SEND_REPLY:
1098 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1099 goto close_connection;
1100 /* no need to write if no events */
1101 if (!(c->poll_entry->revents & POLLOUT))
1103 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1105 if (ff_neterrno() != AVERROR(EAGAIN) &&
1106 ff_neterrno() != AVERROR(EINTR)) {
1107 goto close_connection;
1111 c->buffer_ptr += len;
1112 c->data_count += len;
1113 if (c->buffer_ptr >= c->buffer_end) {
1114 /* all the buffer was sent : wait for a new request */
1115 av_freep(&c->pb_buffer);
1116 start_wait_request(c, 1);
1119 case RTSPSTATE_SEND_PACKET:
1120 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1121 av_freep(&c->packet_buffer);
1124 /* no need to write if no events */
1125 if (!(c->poll_entry->revents & POLLOUT))
1127 len = send(c->fd, c->packet_buffer_ptr,
1128 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1130 if (ff_neterrno() != AVERROR(EAGAIN) &&
1131 ff_neterrno() != AVERROR(EINTR)) {
1132 /* error : close connection */
1133 av_freep(&c->packet_buffer);
1138 c->packet_buffer_ptr += len;
1139 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1140 /* all the buffer was sent : wait for a new request */
1141 av_freep(&c->packet_buffer);
1142 c->state = RTSPSTATE_WAIT_REQUEST;
1145 case HTTPSTATE_READY:
1154 av_freep(&c->pb_buffer);
1158 static int extract_rates(char *rates, int ratelen, const char *request)
1162 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1163 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1164 const char *q = p + 7;
1166 while (*q && *q != '\n' && av_isspace(*q))
1169 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1175 memset(rates, 0xff, ratelen);
1178 while (*q && *q != '\n' && *q != ':')
1181 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1185 if (stream_no < ratelen && stream_no >= 0)
1186 rates[stream_no] = rate_no;
1188 while (*q && *q != '\n' && !av_isspace(*q))
1195 p = strchr(p, '\n');
1205 static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec,
1209 int best_bitrate = 100000000;
1212 for (i = 0; i < feed->nb_streams; i++) {
1213 AVCodecParameters *feed_codec = feed->streams[i]->codecpar;
1215 if (feed_codec->codec_id != codec->codec_id ||
1216 feed_codec->sample_rate != codec->sample_rate ||
1217 feed_codec->width != codec->width ||
1218 feed_codec->height != codec->height)
1221 /* Potential stream */
1223 /* We want the fastest stream less than bit_rate, or the slowest
1224 * faster than bit_rate
1227 if (feed_codec->bit_rate <= bit_rate) {
1228 if (best_bitrate > bit_rate ||
1229 feed_codec->bit_rate > best_bitrate) {
1230 best_bitrate = feed_codec->bit_rate;
1235 if (feed_codec->bit_rate < best_bitrate) {
1236 best_bitrate = feed_codec->bit_rate;
1243 static int modify_current_stream(HTTPContext *c, char *rates)
1246 FFServerStream *req = c->stream;
1247 int action_required = 0;
1249 /* Not much we can do for a feed */
1253 for (i = 0; i < req->nb_streams; i++) {
1254 AVCodecParameters *codec = req->streams[i]->codecpar;
1258 c->switch_feed_streams[i] = req->feed_streams[i];
1261 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1264 /* Wants off or slow */
1265 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1267 /* This doesn't work well when it turns off the only stream! */
1268 c->switch_feed_streams[i] = -2;
1269 c->feed_streams[i] = -2;
1274 if (c->switch_feed_streams[i] >= 0 &&
1275 c->switch_feed_streams[i] != c->feed_streams[i]) {
1276 action_required = 1;
1280 return action_required;
1283 static void get_word(char *buf, int buf_size, const char **pp)
1288 #define SPACE_CHARS " \t\r\n"
1291 p += strspn(p, SPACE_CHARS);
1293 while (!av_isspace(*p) && *p != '\0') {
1294 if ((q - buf) < buf_size - 1)
1303 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1309 FFServerIPAddressACL *acl = NULL;
1313 f = fopen(stream->dynamic_acl, "r");
1315 perror(stream->dynamic_acl);
1319 acl = av_mallocz(sizeof(FFServerIPAddressACL));
1326 while (fgets(line, sizeof(line), f)) {
1329 while (av_isspace(*p))
1331 if (*p == '\0' || *p == '#')
1333 ffserver_get_arg(cmd, sizeof(cmd), &p);
1335 if (!av_strcasecmp(cmd, "ACL"))
1336 ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1344 static void free_acl_list(FFServerIPAddressACL *in_acl)
1346 FFServerIPAddressACL *pacl, *pacl2;
1356 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1358 enum FFServerIPAddressAction last_action = IP_DENY;
1359 FFServerIPAddressACL *acl;
1360 struct in_addr *src = &c->from_addr.sin_addr;
1361 unsigned long src_addr = src->s_addr;
1363 for (acl = in_acl; acl; acl = acl->next) {
1364 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1365 return (acl->action == IP_ALLOW) ? 1 : 0;
1366 last_action = acl->action;
1369 /* Nothing matched, so return not the last action */
1370 return (last_action == IP_DENY) ? 1 : 0;
1373 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1376 FFServerIPAddressACL *acl;
1378 /* if stream->acl is null validate_acl_list will return 1 */
1379 ret = validate_acl_list(stream->acl, c);
1381 if (stream->dynamic_acl[0]) {
1382 acl = parse_dynamic_acl(stream, c);
1383 ret = validate_acl_list(acl, c);
1391 * compute the real filename of a file by matching it without its
1392 * extensions to all the stream's filenames
1394 static void compute_real_filename(char *filename, int max_size)
1399 FFServerStream *stream;
1401 av_strlcpy(file1, filename, sizeof(file1));
1402 p = strrchr(file1, '.');
1405 for(stream = config.first_stream; stream; stream = stream->next) {
1406 av_strlcpy(file2, stream->filename, sizeof(file2));
1407 p = strrchr(file2, '.');
1410 if (!strcmp(file1, file2)) {
1411 av_strlcpy(filename, stream->filename, max_size);
1426 /* parse HTTP request and prepare header */
1427 static int http_parse_request(HTTPContext *c)
1431 enum RedirType redir_type;
1433 char info[1024], filename[1024];
1437 char *encoded_msg = NULL;
1438 const char *mime_type;
1439 FFServerStream *stream;
1442 const char *useragent = 0;
1445 get_word(cmd, sizeof(cmd), &p);
1446 av_strlcpy(c->method, cmd, sizeof(c->method));
1448 if (!strcmp(cmd, "GET"))
1450 else if (!strcmp(cmd, "POST"))
1455 get_word(url, sizeof(url), &p);
1456 av_strlcpy(c->url, url, sizeof(c->url));
1458 get_word(protocol, sizeof(protocol), (const char **)&p);
1459 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1462 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1465 http_log("%s - - New connection: %s %s\n",
1466 inet_ntoa(c->from_addr.sin_addr), cmd, url);
1468 /* find the filename and the optional info string in the request */
1469 p1 = strchr(url, '?');
1471 av_strlcpy(info, p1, sizeof(info));
1476 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1478 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1479 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1481 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1485 p = strchr(p, '\n');
1492 redir_type = REDIR_NONE;
1493 if (av_match_ext(filename, "asx")) {
1494 redir_type = REDIR_ASX;
1495 filename[strlen(filename)-1] = 'f';
1496 } else if (av_match_ext(filename, "asf") &&
1497 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1498 /* if this isn't WMP or lookalike, return the redirector file */
1499 redir_type = REDIR_ASF;
1500 } else if (av_match_ext(filename, "rpm,ram")) {
1501 redir_type = REDIR_RAM;
1502 strcpy(filename + strlen(filename)-2, "m");
1503 } else if (av_match_ext(filename, "rtsp")) {
1504 redir_type = REDIR_RTSP;
1505 compute_real_filename(filename, sizeof(filename) - 1);
1506 } else if (av_match_ext(filename, "sdp")) {
1507 redir_type = REDIR_SDP;
1508 compute_real_filename(filename, sizeof(filename) - 1);
1511 /* "redirect" request to index.html */
1512 if (!strlen(filename))
1513 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1515 stream = config.first_stream;
1517 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1519 stream = stream->next;
1522 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1523 http_log("File '%s' not found\n", url);
1528 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1529 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1531 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1532 c->http_error = 301;
1534 snprintf(q, c->buffer_size,
1535 "HTTP/1.0 301 Moved\r\n"
1537 "Content-type: text/html\r\n"
1540 "<html><head><title>Moved</title></head><body>\r\n"
1541 "You should be <a href=\"%s\">redirected</a>.\r\n"
1542 "</body></html>\r\n",
1543 stream->feed_filename, stream->feed_filename);
1545 /* prepare output buffer */
1546 c->buffer_ptr = c->buffer;
1548 c->state = HTTPSTATE_SEND_HEADER;
1552 /* If this is WMP, get the rate information */
1553 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1554 if (modify_current_stream(c, ratebuf)) {
1555 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1556 if (c->switch_feed_streams[i] >= 0)
1557 c->switch_feed_streams[i] = -1;
1562 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1563 current_bandwidth += stream->bandwidth;
1565 /* If already streaming this feed, do not let another feeder start */
1566 if (stream->feed_opened) {
1567 snprintf(msg, sizeof(msg), "This feed is already being received.");
1568 http_log("Feed '%s' already being received\n", stream->feed_filename);
1572 if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1573 c->http_error = 503;
1575 snprintf(q, c->buffer_size,
1576 "HTTP/1.0 503 Server too busy\r\n"
1577 "Content-type: text/html\r\n"
1580 "<html><head><title>Too busy</title></head><body>\r\n"
1581 "<p>The server is too busy to serve your request at "
1582 "this time.</p>\r\n"
1583 "<p>The bandwidth being served (including your stream) "
1584 "is %"PRIu64"kbit/s, and this exceeds the limit of "
1585 "%"PRIu64"kbit/s.</p>\r\n"
1586 "</body></html>\r\n",
1587 current_bandwidth, config.max_bandwidth);
1589 /* prepare output buffer */
1590 c->buffer_ptr = c->buffer;
1592 c->state = HTTPSTATE_SEND_HEADER;
1596 if (redir_type != REDIR_NONE) {
1597 const char *hostinfo = 0;
1599 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1600 if (av_strncasecmp(p, "Host:", 5) == 0) {
1604 p = strchr(p, '\n');
1615 while (av_isspace(*hostinfo))
1618 eoh = strchr(hostinfo, '\n');
1620 if (eoh[-1] == '\r')
1623 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1624 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1625 hostbuf[eoh - hostinfo] = 0;
1627 c->http_error = 200;
1629 switch(redir_type) {
1631 snprintf(q, c->buffer_size,
1632 "HTTP/1.0 200 ASX Follows\r\n"
1633 "Content-type: video/x-ms-asf\r\n"
1635 "<ASX Version=\"3\">\r\n"
1636 //"<!-- Autogenerated by ffserver -->\r\n"
1637 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1638 "</ASX>\r\n", hostbuf, filename, info);
1642 snprintf(q, c->buffer_size,
1643 "HTTP/1.0 200 RAM Follows\r\n"
1644 "Content-type: audio/x-pn-realaudio\r\n"
1646 "# Autogenerated by ffserver\r\n"
1647 "http://%s/%s%s\r\n", hostbuf, filename, info);
1651 snprintf(q, c->buffer_size,
1652 "HTTP/1.0 200 ASF Redirect follows\r\n"
1653 "Content-type: video/x-ms-asf\r\n"
1656 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1661 char hostname[256], *p;
1662 /* extract only hostname */
1663 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1664 p = strrchr(hostname, ':');
1667 snprintf(q, c->buffer_size,
1668 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1669 /* XXX: incorrect MIME type ? */
1670 "Content-type: application/x-rtsp\r\n"
1672 "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1681 struct sockaddr_in my_addr;
1683 snprintf(q, c->buffer_size,
1684 "HTTP/1.0 200 OK\r\n"
1685 "Content-type: application/sdp\r\n"
1689 len = sizeof(my_addr);
1691 /* XXX: Should probably fail? */
1692 if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1693 http_log("getsockname() failed\n");
1695 /* XXX: should use a dynamic buffer */
1696 sdp_data_size = prepare_sdp_description(stream,
1699 if (sdp_data_size > 0) {
1700 memcpy(q, sdp_data, sdp_data_size);
1703 av_freep(&sdp_data);
1712 /* prepare output buffer */
1713 c->buffer_ptr = c->buffer;
1715 c->state = HTTPSTATE_SEND_HEADER;
1721 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1725 stream->conns_served++;
1727 /* XXX: add there authenticate and IP match */
1730 /* if post, it means a feed is being sent */
1731 if (!stream->is_feed) {
1732 /* However it might be a status report from WMP! Let us log the
1733 * data as it might come handy one day. */
1734 const char *logline = 0;
1737 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1738 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1742 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1743 client_id = strtol(p + 18, 0, 10);
1744 p = strchr(p, '\n');
1752 char *eol = strchr(logline, '\n');
1757 if (eol[-1] == '\r')
1759 http_log("%.*s\n", (int) (eol - logline), logline);
1760 c->suppress_log = 1;
1765 http_log("\nGot request:\n%s\n", c->buffer);
1768 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1771 /* Now we have to find the client_id */
1772 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1773 if (wmpc->wmp_client_id == client_id)
1777 if (wmpc && modify_current_stream(wmpc, ratebuf))
1778 wmpc->switch_pending = 1;
1781 snprintf(msg, sizeof(msg), "POST command not handled");
1785 if (http_start_receive_data(c) < 0) {
1786 snprintf(msg, sizeof(msg), "could not open feed");
1790 c->state = HTTPSTATE_RECEIVE_DATA;
1795 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1796 http_log("\nGot request:\n%s\n", c->buffer);
1799 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1802 /* open input stream */
1803 if (open_input_stream(c, info) < 0) {
1804 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1808 /* prepare HTTP header */
1810 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1811 mime_type = c->stream->fmt->mime_type;
1813 mime_type = "application/x-octet-stream";
1814 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1816 /* for asf, we need extra headers */
1817 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1818 /* Need to allocate a client id */
1820 c->wmp_client_id = av_lfg_get(&random_state);
1822 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);
1824 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1825 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1826 q = c->buffer + strlen(c->buffer);
1828 /* prepare output buffer */
1830 c->buffer_ptr = c->buffer;
1832 c->state = HTTPSTATE_SEND_HEADER;
1835 c->http_error = 404;
1837 if (!htmlencode(msg, &encoded_msg)) {
1838 http_log("Could not encode filename '%s' as HTML\n", msg);
1840 snprintf(q, c->buffer_size,
1841 "HTTP/1.0 404 Not Found\r\n"
1842 "Content-type: text/html\r\n"
1847 "<meta charset=\"UTF-8\">\n"
1848 "<title>404 Not Found</title>\n"
1851 "</html>\n", encoded_msg? encoded_msg : "File not found");
1853 /* prepare output buffer */
1854 c->buffer_ptr = c->buffer;
1856 c->state = HTTPSTATE_SEND_HEADER;
1857 av_freep(&encoded_msg);
1861 /* horrible: we use this value to avoid
1862 * going to the send data state */
1863 c->http_error = 200;
1864 c->state = HTTPSTATE_SEND_HEADER;
1868 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1870 static const char suffix[] = " kMGTP";
1873 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1875 avio_printf(pb, "%"PRId64"%c", count, *s);
1878 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1881 const char *type = "unknown";
1882 char parameters[64];
1883 LayeredAVStream *st;
1886 stream_no = stream->nb_streams;
1888 avio_printf(pb, "<table><tr><th>Stream<th>"
1889 "type<th>kbit/s<th>codec<th>"
1892 for (i = 0; i < stream_no; i++) {
1893 st = stream->streams[i];
1894 codec = avcodec_find_encoder(st->codecpar->codec_id);
1898 switch(st->codecpar->codec_type) {
1899 case AVMEDIA_TYPE_AUDIO:
1901 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1902 st->codecpar->channels, st->codecpar->sample_rate);
1904 case AVMEDIA_TYPE_VIDEO:
1906 snprintf(parameters, sizeof(parameters),
1907 "%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
1908 st->codecpar->height, st->codec->qmin, st->codec->qmax,
1909 st->time_base.den / st->time_base.num);
1915 avio_printf(pb, "<tr><td>%d<td>%s<td>%"PRId64
1917 i, type, (int64_t)st->codecpar->bit_rate/1000,
1918 codec ? codec->name : "", parameters);
1921 avio_printf(pb, "</table>\n");
1924 static void clean_html(char *clean, int clean_len, char *dirty)
1928 for (o = i = 0; o+10 < clean_len && dirty[i];) {
1929 int len = strspn(dirty+i, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*(),?/ :;%");
1931 if (o + len >= clean_len)
1933 memcpy(clean + o, dirty + i, len);
1939 case '&': av_strlcat(clean+o, "&" , clean_len - o); break;
1940 case '<': av_strlcat(clean+o, "<" , clean_len - o); break;
1941 case '>': av_strlcat(clean+o, ">" , clean_len - o); break;
1942 case '\'': av_strlcat(clean+o, "'" , clean_len - o); break;
1943 case '\"': av_strlcat(clean+o, """ , clean_len - o); break;
1944 default: av_strlcat(clean+o, "☹", clean_len - o); break;
1946 o += strlen(clean+o);
1952 static void compute_status(HTTPContext *c)
1955 FFServerStream *stream;
1961 if (avio_open_dyn_buf(&pb) < 0) {
1962 /* XXX: return an error ? */
1963 c->buffer_ptr = c->buffer;
1964 c->buffer_end = c->buffer;
1968 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1969 avio_printf(pb, "Content-type: text/html\r\n");
1970 avio_printf(pb, "Pragma: no-cache\r\n");
1971 avio_printf(pb, "\r\n");
1973 avio_printf(pb, "<!DOCTYPE html>\n");
1974 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1975 if (c->stream->feed_filename[0])
1976 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1977 c->stream->feed_filename);
1978 avio_printf(pb, "</head>\n<body>");
1979 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1981 avio_printf(pb, "<h2>Available Streams</h2>\n");
1982 avio_printf(pb, "<table>\n");
1983 avio_printf(pb, "<tr><th>Path<th>Served<br>Conns<th><br>bytes<th>Format<th>Bit rate<br>kbit/s<th>Video<br>kbit/s<th><br>Codec<th>Audio<br>kbit/s<th><br>Codec<th>Feed\n");
1984 stream = config.first_stream;
1986 char sfilename[1024];
1989 if (stream->feed == stream) {
1990 stream = stream->next;
1994 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1995 eosf = sfilename + strlen(sfilename);
1996 if (eosf - sfilename >= 4) {
1997 if (strcmp(eosf - 4, ".asf") == 0)
1998 strcpy(eosf - 4, ".asx");
1999 else if (strcmp(eosf - 3, ".rm") == 0)
2000 strcpy(eosf - 3, ".ram");
2001 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
2002 /* generate a sample RTSP director if
2003 * unicast. Generate an SDP redirector if
2005 eosf = strrchr(sfilename, '.');
2007 eosf = sfilename + strlen(sfilename);
2008 if (stream->is_multicast)
2009 strcpy(eosf, ".sdp");
2011 strcpy(eosf, ".rtsp");
2015 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
2016 sfilename, stream->filename);
2017 avio_printf(pb, "<td> %d <td> ",
2018 stream->conns_served);
2019 // TODO: Investigate if we can make http bitexact so it always produces the same count of bytes
2020 if (!config.bitexact)
2021 fmt_bytecount(pb, stream->bytes_served);
2023 switch(stream->stream_type) {
2024 case STREAM_TYPE_LIVE: {
2025 int audio_bit_rate = 0;
2026 int video_bit_rate = 0;
2027 const char *audio_codec_name = "";
2028 const char *video_codec_name = "";
2029 const char *audio_codec_name_extra = "";
2030 const char *video_codec_name_extra = "";
2032 for(i=0;i<stream->nb_streams;i++) {
2033 LayeredAVStream *st = stream->streams[i];
2034 AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id);
2036 switch(st->codecpar->codec_type) {
2037 case AVMEDIA_TYPE_AUDIO:
2038 audio_bit_rate += st->codecpar->bit_rate;
2040 if (*audio_codec_name)
2041 audio_codec_name_extra = "...";
2042 audio_codec_name = codec->name;
2045 case AVMEDIA_TYPE_VIDEO:
2046 video_bit_rate += st->codecpar->bit_rate;
2048 if (*video_codec_name)
2049 video_codec_name_extra = "...";
2050 video_codec_name = codec->name;
2053 case AVMEDIA_TYPE_DATA:
2054 video_bit_rate += st->codecpar->bit_rate;
2061 avio_printf(pb, "<td> %s <td> %d <td> %d <td> %s %s <td> "
2063 stream->fmt->name, stream->bandwidth,
2064 video_bit_rate / 1000, video_codec_name,
2065 video_codec_name_extra, audio_bit_rate / 1000,
2066 audio_codec_name, audio_codec_name_extra);
2069 avio_printf(pb, "<td>%s", stream->feed->filename);
2071 avio_printf(pb, "<td>%s", stream->feed_filename);
2072 avio_printf(pb, "\n");
2076 avio_printf(pb, "<td> - <td> - "
2077 "<td> - <td><td> - <td>\n");
2080 stream = stream->next;
2082 avio_printf(pb, "</table>\n");
2084 stream = config.first_stream;
2087 if (stream->feed != stream) {
2088 stream = stream->next;
2092 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
2094 avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
2101 /* This is somewhat linux specific I guess */
2102 snprintf(ps_cmd, sizeof(ps_cmd),
2103 "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
2104 (int64_t) stream->pid);
2106 pid_stat = popen(ps_cmd, "r");
2111 if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
2112 avio_printf(pb, "Currently using %s%% of the cpu. "
2113 "Total time used %s.\n",
2121 avio_printf(pb, "<p>");
2124 print_stream_params(pb, stream);
2125 stream = stream->next;
2128 /* connection status */
2129 avio_printf(pb, "<h2>Connection Status</h2>\n");
2131 avio_printf(pb, "Number of connections: %d / %d<br>\n",
2132 nb_connections, config.nb_max_connections);
2134 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2135 current_bandwidth, config.max_bandwidth);
2137 avio_printf(pb, "<table>\n");
2138 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>URL<th>Proto<th>State<th>Target "
2139 "bit/s<th>Actual bit/s<th>Bytes transferred\n");
2140 c1 = first_http_ctx;
2148 for (j = 0; j < c1->stream->nb_streams; j++) {
2149 if (!c1->stream->feed)
2150 bitrate += c1->stream->streams[j]->codecpar->bit_rate;
2151 else if (c1->feed_streams[j] >= 0)
2152 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate;
2157 p = inet_ntoa(c1->from_addr.sin_addr);
2158 clean_html(c1->clean_url, sizeof(c1->clean_url), c1->url);
2159 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td>%s"
2161 i, c1->stream ? c1->stream->filename : "",
2162 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
2165 c1->protocol, http_state[c1->state]);
2166 fmt_bytecount(pb, bitrate);
2167 avio_printf(pb, "<td>");
2168 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2169 avio_printf(pb, "<td>");
2170 fmt_bytecount(pb, c1->data_count);
2171 avio_printf(pb, "\n");
2174 avio_printf(pb, "</table>\n");
2176 if (!config.bitexact) {
2180 avio_printf(pb, "<hr>Generated at %s", p);
2182 avio_printf(pb, "</body>\n</html>\n");
2184 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2185 c->buffer_ptr = c->pb_buffer;
2186 c->buffer_end = c->pb_buffer + len;
2189 static int open_input_stream(HTTPContext *c, const char *info)
2192 char input_filename[1024];
2193 AVFormatContext *s = NULL;
2194 int buf_size, i, ret;
2197 /* find file name */
2198 if (c->stream->feed) {
2199 strcpy(input_filename, c->stream->feed->feed_filename);
2200 buf_size = FFM_PACKET_SIZE;
2201 /* compute position (absolute time) */
2202 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2203 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2204 http_log("Invalid date specification '%s' for stream\n", buf);
2207 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2208 int prebuffer = strtol(buf, 0, 10);
2209 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2211 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2213 strcpy(input_filename, c->stream->feed_filename);
2215 /* compute position (relative time) */
2216 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2217 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2218 http_log("Invalid date specification '%s' for stream\n", buf);
2224 if (!input_filename[0]) {
2225 http_log("No filename was specified for stream\n");
2226 return AVERROR(EINVAL);
2230 ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2231 &c->stream->in_opts);
2233 http_log("Could not open input '%s': %s\n",
2234 input_filename, av_err2str(ret));
2238 /* set buffer size */
2240 ret = ffio_set_buf_size(s->pb, buf_size);
2242 http_log("Failed to set buffer size\n");
2247 s->flags |= AVFMT_FLAG_GENPTS;
2249 if (strcmp(s->iformat->name, "ffm") &&
2250 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2251 http_log("Could not find stream info for input '%s'\n", input_filename);
2252 avformat_close_input(&s);
2256 /* choose stream as clock source (we favor the video stream if
2257 * present) for packet sending */
2258 c->pts_stream_index = 0;
2259 for(i=0;i<c->stream->nb_streams;i++) {
2260 if (c->pts_stream_index == 0 &&
2261 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2262 c->pts_stream_index = i;
2266 if (c->fmt_in->iformat->read_seek)
2267 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2268 /* set the start time (needed for maxtime and RTP packet timing) */
2269 c->start_time = cur_time;
2270 c->first_pts = AV_NOPTS_VALUE;
2274 /* return the server clock (in us) */
2275 static int64_t get_server_clock(HTTPContext *c)
2277 /* compute current pts value from system time */
2278 return (cur_time - c->start_time) * 1000;
2281 /* return the estimated time (in us) at which the current packet must be sent */
2282 static int64_t get_packet_send_clock(HTTPContext *c)
2284 int bytes_left, bytes_sent, frame_bytes;
2286 frame_bytes = c->cur_frame_bytes;
2287 if (frame_bytes <= 0)
2290 bytes_left = c->buffer_end - c->buffer_ptr;
2291 bytes_sent = frame_bytes - bytes_left;
2292 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2296 static int http_prepare_data(HTTPContext *c)
2299 AVFormatContext *ctx;
2301 av_freep(&c->pb_buffer);
2303 case HTTPSTATE_SEND_DATA_HEADER:
2304 ctx = avformat_alloc_context();
2306 return AVERROR(ENOMEM);
2308 av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0);
2310 for(i=0;i<c->stream->nb_streams;i++) {
2311 LayeredAVStream *src;
2312 AVStream *st = avformat_new_stream(c->pfmt_ctx, NULL);
2314 return AVERROR(ENOMEM);
2316 /* if file or feed, then just take streams from FFServerStream
2318 if (!c->stream->feed ||
2319 c->stream->feed == c->stream)
2320 src = c->stream->streams[i];
2322 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2324 unlayer_stream(c->pfmt_ctx->streams[i], src); //TODO we no longer copy st->internal, does this matter?
2325 av_assert0(!c->pfmt_ctx->streams[i]->priv_data);
2327 if (src->codec->flags & AV_CODEC_FLAG_BITEXACT)
2328 c->pfmt_ctx->flags |= AVFMT_FLAG_BITEXACT;
2330 /* set output format parameters */
2331 c->pfmt_ctx->oformat = c->stream->fmt;
2332 av_assert0(c->pfmt_ctx->nb_streams == c->stream->nb_streams);
2334 c->got_key_frame = 0;
2336 /* prepare header and save header data in a stream */
2337 if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) {
2338 /* XXX: potential leak */
2341 c->pfmt_ctx->pb->seekable = 0;
2344 * HACK to avoid MPEG-PS muxer to spit many underflow errors
2345 * Default value from FFmpeg
2346 * Try to set it using configuration option
2348 c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE);
2350 if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) {
2351 http_log("Error writing output header for stream '%s': %s\n",
2352 c->stream->filename, av_err2str(ret));
2355 av_dict_free(&c->pfmt_ctx->metadata);
2357 len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer);
2358 c->buffer_ptr = c->pb_buffer;
2359 c->buffer_end = c->pb_buffer + len;
2361 c->state = HTTPSTATE_SEND_DATA;
2362 c->last_packet_sent = 0;
2364 case HTTPSTATE_SEND_DATA:
2365 /* find a new packet */
2366 /* read a packet from the input stream */
2367 if (c->stream->feed)
2368 ffm_set_write_index(c->fmt_in,
2369 c->stream->feed->feed_write_index,
2370 c->stream->feed->feed_size);
2372 if (c->stream->max_time &&
2373 c->stream->max_time + c->start_time - cur_time < 0)
2374 /* We have timed out */
2375 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2379 ret = av_read_frame(c->fmt_in, &pkt);
2381 if (c->stream->feed) {
2382 /* if coming from feed, it means we reached the end of the
2383 * ffm file, so must wait for more data */
2384 c->state = HTTPSTATE_WAIT_FEED;
2385 return 1; /* state changed */
2387 if (ret == AVERROR(EAGAIN)) {
2388 /* input not ready, come back later */
2391 if (c->stream->loop) {
2392 avformat_close_input(&c->fmt_in);
2393 if (open_input_stream(c, "") < 0)
2398 /* must send trailer now because EOF or error */
2399 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2402 int source_index = pkt.stream_index;
2403 /* update first pts if needed */
2404 if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
2405 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2406 c->start_time = cur_time;
2408 /* send it to the appropriate stream */
2409 if (c->stream->feed) {
2410 /* if coming from a feed, select the right stream */
2411 if (c->switch_pending) {
2412 c->switch_pending = 0;
2413 for(i=0;i<c->stream->nb_streams;i++) {
2414 if (c->switch_feed_streams[i] == pkt.stream_index)
2415 if (pkt.flags & AV_PKT_FLAG_KEY)
2416 c->switch_feed_streams[i] = -1;
2417 if (c->switch_feed_streams[i] >= 0)
2418 c->switch_pending = 1;
2421 for(i=0;i<c->stream->nb_streams;i++) {
2422 if (c->stream->feed_streams[i] == pkt.stream_index) {
2423 AVStream *st = c->fmt_in->streams[source_index];
2424 pkt.stream_index = i;
2425 if (pkt.flags & AV_PKT_FLAG_KEY &&
2426 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
2427 c->stream->nb_streams == 1))
2428 c->got_key_frame = 1;
2429 if (!c->stream->send_on_key || c->got_key_frame)
2434 AVStream *ist, *ost;
2436 ist = c->fmt_in->streams[source_index];
2437 /* specific handling for RTP: we use several
2438 * output streams (one for each RTP connection).
2439 * XXX: need more abstract handling */
2440 if (c->is_packetized) {
2441 /* compute send time and duration */
2442 if (pkt.dts != AV_NOPTS_VALUE) {
2443 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2444 c->cur_pts -= c->first_pts;
2446 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2447 /* find RTP context */
2448 c->packet_stream_index = pkt.stream_index;
2449 ctx = c->rtp_ctx[c->packet_stream_index];
2451 av_packet_unref(&pkt);
2454 /* only one stream per RTP connection */
2455 pkt.stream_index = 0;
2461 if (c->is_packetized) {
2462 int max_packet_size;
2463 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2464 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2466 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2467 ret = ffio_open_dyn_packet_buf(&ctx->pb,
2470 ret = avio_open_dyn_buf(&ctx->pb);
2473 /* XXX: potential leak */
2476 ost = ctx->streams[pkt.stream_index];
2478 ctx->pb->seekable = 0;
2479 if (pkt.dts != AV_NOPTS_VALUE)
2480 pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2482 if (pkt.pts != AV_NOPTS_VALUE)
2483 pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2485 pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2487 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2488 http_log("Error writing frame to output for stream '%s': %s\n",
2489 c->stream->filename, av_err2str(ret));
2490 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2493 av_freep(&c->pb_buffer);
2494 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2496 c->cur_frame_bytes = len;
2497 c->buffer_ptr = c->pb_buffer;
2498 c->buffer_end = c->pb_buffer + len;
2501 av_packet_unref(&pkt);
2505 av_packet_unref(&pkt);
2510 case HTTPSTATE_SEND_DATA_TRAILER:
2511 /* last packet test ? */
2512 if (c->last_packet_sent || c->is_packetized)
2515 /* prepare header */
2516 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2517 /* XXX: potential leak */
2520 c->pfmt_ctx->pb->seekable = 0;
2521 av_write_trailer(ctx);
2522 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2523 c->buffer_ptr = c->pb_buffer;
2524 c->buffer_end = c->pb_buffer + len;
2526 c->last_packet_sent = 1;
2532 /* should convert the format at the same time */
2533 /* send data starting at c->buffer_ptr to the output connection
2534 * (either UDP or TCP)
2536 static int http_send_data(HTTPContext *c)
2541 if (c->buffer_ptr >= c->buffer_end) {
2542 ret = http_prepare_data(c);
2546 /* state change requested */
2549 if (c->is_packetized) {
2550 /* RTP data output */
2551 len = c->buffer_end - c->buffer_ptr;
2553 /* fail safe - should never happen */
2555 c->buffer_ptr = c->buffer_end;
2558 len = (c->buffer_ptr[0] << 24) |
2559 (c->buffer_ptr[1] << 16) |
2560 (c->buffer_ptr[2] << 8) |
2562 if (len > (c->buffer_end - c->buffer_ptr))
2564 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2565 /* nothing to send yet: we can wait */
2569 c->data_count += len;
2570 update_datarate(&c->datarate, c->data_count);
2572 c->stream->bytes_served += len;
2574 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2575 /* RTP packets are sent inside the RTSP TCP connection */
2577 int interleaved_index, size;
2579 HTTPContext *rtsp_c;
2582 /* if no RTSP connection left, error */
2585 /* if already sending something, then wait. */
2586 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2588 if (avio_open_dyn_buf(&pb) < 0)
2590 interleaved_index = c->packet_stream_index * 2;
2591 /* RTCP packets are sent at odd indexes */
2592 if (c->buffer_ptr[1] == 200)
2593 interleaved_index++;
2594 /* write RTSP TCP header */
2596 header[1] = interleaved_index;
2597 header[2] = len >> 8;
2599 avio_write(pb, header, 4);
2600 /* write RTP packet data */
2602 avio_write(pb, c->buffer_ptr, len);
2603 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2604 /* prepare asynchronous TCP sending */
2605 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2606 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2607 c->buffer_ptr += len;
2609 /* send everything we can NOW */
2610 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2611 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2613 rtsp_c->packet_buffer_ptr += len;
2614 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2615 /* if we could not send all the data, we will
2616 * send it later, so a new state is needed to
2617 * "lock" the RTSP TCP connection */
2618 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2621 /* all data has been sent */
2622 av_freep(&c->packet_buffer);
2624 /* send RTP packet directly in UDP */
2626 ffurl_write(c->rtp_handles[c->packet_stream_index],
2627 c->buffer_ptr, len);
2628 c->buffer_ptr += len;
2629 /* here we continue as we can send several packets
2633 /* TCP data output */
2634 len = send(c->fd, c->buffer_ptr,
2635 c->buffer_end - c->buffer_ptr, 0);
2637 if (ff_neterrno() != AVERROR(EAGAIN) &&
2638 ff_neterrno() != AVERROR(EINTR))
2639 /* error : close connection */
2644 c->buffer_ptr += len;
2646 c->data_count += len;
2647 update_datarate(&c->datarate, c->data_count);
2649 c->stream->bytes_served += len;
2657 static int http_start_receive_data(HTTPContext *c)
2663 if (c->stream->feed_opened) {
2664 http_log("Stream feed '%s' was not opened\n",
2665 c->stream->feed_filename);
2666 return AVERROR(EINVAL);
2669 /* Don't permit writing to this one */
2670 if (c->stream->readonly) {
2671 http_log("Cannot write to read-only file '%s'\n",
2672 c->stream->feed_filename);
2673 return AVERROR(EINVAL);
2677 fd = open(c->stream->feed_filename, O_RDWR);
2679 ret = AVERROR(errno);
2680 http_log("Could not open feed file '%s': %s\n",
2681 c->stream->feed_filename, strerror(errno));
2686 if (c->stream->truncate) {
2687 /* truncate feed file */
2688 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2689 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2690 if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2691 ret = AVERROR(errno);
2692 http_log("Error truncating feed file '%s': %s\n",
2693 c->stream->feed_filename, strerror(errno));
2697 ret64 = ffm_read_write_index(fd);
2699 http_log("Error reading write index from feed file '%s': %s\n",
2700 c->stream->feed_filename, strerror(errno));
2703 c->stream->feed_write_index = ret64;
2706 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2708 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2709 lseek(fd, 0, SEEK_SET);
2711 /* init buffer input */
2712 c->buffer_ptr = c->buffer;
2713 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2714 c->stream->feed_opened = 1;
2715 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2719 static int http_receive_data(HTTPContext *c)
2722 int len, loop_run = 0;
2724 while (c->chunked_encoding && !c->chunk_size &&
2725 c->buffer_end > c->buffer_ptr) {
2726 /* read chunk header, if present */
2727 len = recv(c->fd, c->buffer_ptr, 1, 0);
2730 if (ff_neterrno() != AVERROR(EAGAIN) &&
2731 ff_neterrno() != AVERROR(EINTR))
2732 /* error : close connection */
2735 } else if (len == 0) {
2736 /* end of connection : close it */
2738 } else if (c->buffer_ptr - c->buffer >= 2 &&
2739 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2740 c->chunk_size = strtol(c->buffer, 0, 16);
2741 if (c->chunk_size <= 0) { // end of stream or invalid chunk size
2745 c->buffer_ptr = c->buffer;
2747 } else if (++loop_run > 10)
2748 /* no chunk header, abort */
2754 if (c->buffer_end > c->buffer_ptr) {
2755 len = recv(c->fd, c->buffer_ptr,
2756 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2758 if (ff_neterrno() != AVERROR(EAGAIN) &&
2759 ff_neterrno() != AVERROR(EINTR))
2760 /* error : close connection */
2762 } else if (len == 0)
2763 /* end of connection : close it */
2766 av_assert0(len <= c->chunk_size);
2767 c->chunk_size -= len;
2768 c->buffer_ptr += len;
2769 c->data_count += len;
2770 update_datarate(&c->datarate, c->data_count);
2774 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2775 if (c->buffer[0] != 'f' ||
2776 c->buffer[1] != 'm') {
2777 http_log("Feed stream has become desynchronized -- disconnecting\n");
2782 if (c->buffer_ptr >= c->buffer_end) {
2783 FFServerStream *feed = c->stream;
2784 /* a packet has been received : write it in the store, except
2786 if (c->data_count > FFM_PACKET_SIZE) {
2787 /* XXX: use llseek or url_seek
2788 * XXX: Should probably fail? */
2789 if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2790 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2792 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2793 http_log("Error writing to feed file: %s\n", strerror(errno));
2797 feed->feed_write_index += FFM_PACKET_SIZE;
2798 /* update file size */
2799 if (feed->feed_write_index > c->stream->feed_size)
2800 feed->feed_size = feed->feed_write_index;
2802 /* handle wrap around if max file size reached */
2803 if (c->stream->feed_max_size &&
2804 feed->feed_write_index >= c->stream->feed_max_size)
2805 feed->feed_write_index = FFM_PACKET_SIZE;
2808 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2809 http_log("Error writing index to feed file: %s\n",
2814 /* wake up any waiting connections */
2815 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2816 if (c1->state == HTTPSTATE_WAIT_FEED &&
2817 c1->stream->feed == c->stream->feed)
2818 c1->state = HTTPSTATE_SEND_DATA;
2821 /* We have a header in our hands that contains useful data */
2822 AVFormatContext *s = avformat_alloc_context();
2824 AVInputFormat *fmt_in;
2830 /* use feed output format name to find corresponding input format */
2831 fmt_in = av_find_input_format(feed->fmt->name);
2835 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2836 0, NULL, NULL, NULL, NULL);
2843 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2848 /* Now we have the actual streams */
2849 if (s->nb_streams != feed->nb_streams) {
2850 avformat_close_input(&s);
2852 http_log("Feed '%s' stream number does not match registered feed\n",
2853 c->stream->feed_filename);
2857 for (i = 0; i < s->nb_streams; i++) {
2858 LayeredAVStream *fst = feed->streams[i];
2859 AVStream *st = s->streams[i];
2860 avcodec_parameters_to_context(fst->codec, st->codecpar);
2861 avcodec_parameters_from_context(fst->codecpar, fst->codec);
2864 avformat_close_input(&s);
2867 c->buffer_ptr = c->buffer;
2872 c->stream->feed_opened = 0;
2874 /* wake up any waiting connections to stop waiting for feed */
2875 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2876 if (c1->state == HTTPSTATE_WAIT_FEED &&
2877 c1->stream->feed == c->stream->feed)
2878 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2883 /********************************************************************/
2886 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2893 str = RTSP_STATUS_CODE2STRING(error_number);
2895 str = "Unknown Error";
2897 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2898 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2900 /* output GMT time */
2903 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2904 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2907 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2909 rtsp_reply_header(c, error_number);
2910 avio_printf(c->pb, "\r\n");
2913 static int rtsp_parse_request(HTTPContext *c)
2915 const char *p, *p1, *p2;
2921 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2923 c->buffer_ptr[0] = '\0';
2926 get_word(cmd, sizeof(cmd), &p);
2927 get_word(url, sizeof(url), &p);
2928 get_word(protocol, sizeof(protocol), &p);
2930 av_strlcpy(c->method, cmd, sizeof(c->method));
2931 av_strlcpy(c->url, url, sizeof(c->url));
2932 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2934 if (avio_open_dyn_buf(&c->pb) < 0) {
2935 /* XXX: cannot do more */
2936 c->pb = NULL; /* safety */
2940 /* check version name */
2941 if (strcmp(protocol, "RTSP/1.0")) {
2942 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2946 /* parse each header line */
2947 /* skip to next line */
2948 while (*p != '\n' && *p != '\0')
2952 while (*p != '\0') {
2953 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2957 if (p2 > p && p2[-1] == '\r')
2959 /* skip empty line */
2963 if (len > sizeof(line) - 1)
2964 len = sizeof(line) - 1;
2965 memcpy(line, p, len);
2967 ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
2971 /* handle sequence number */
2972 c->seq = header->seq;
2974 if (!strcmp(cmd, "DESCRIBE"))
2975 rtsp_cmd_describe(c, url);
2976 else if (!strcmp(cmd, "OPTIONS"))
2977 rtsp_cmd_options(c, url);
2978 else if (!strcmp(cmd, "SETUP"))
2979 rtsp_cmd_setup(c, url, header);
2980 else if (!strcmp(cmd, "PLAY"))
2981 rtsp_cmd_play(c, url, header);
2982 else if (!strcmp(cmd, "PAUSE"))
2983 rtsp_cmd_interrupt(c, url, header, 1);
2984 else if (!strcmp(cmd, "TEARDOWN"))
2985 rtsp_cmd_interrupt(c, url, header, 0);
2987 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2990 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2991 c->pb = NULL; /* safety */
2993 /* XXX: cannot do more */
2996 c->buffer_ptr = c->pb_buffer;
2997 c->buffer_end = c->pb_buffer + len;
2998 c->state = RTSPSTATE_SEND_REPLY;
3002 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
3003 struct in_addr my_ip)
3005 AVFormatContext *avc;
3006 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
3007 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
3012 avc = avformat_alloc_context();
3013 if (!avc || !rtp_format)
3016 avc->oformat = rtp_format;
3017 av_dict_set(&avc->metadata, "title",
3018 entry ? entry->value : "No Title", 0);
3019 if (stream->is_multicast) {
3020 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
3021 inet_ntoa(stream->multicast_ip),
3022 stream->multicast_port, stream->multicast_ttl);
3024 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
3026 for(i = 0; i < stream->nb_streams; i++) {
3027 AVStream *st = avformat_new_stream(avc, NULL);
3030 avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
3031 unlayer_stream(st, stream->streams[i]);
3033 #define PBUFFER_SIZE 2048
3034 *pbuffer = av_mallocz(PBUFFER_SIZE);
3037 av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
3040 av_freep(&avc->streams);
3041 av_dict_free(&avc->metadata);
3044 return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
3047 static void rtsp_cmd_options(HTTPContext *c, const char *url)
3049 /* rtsp_reply_header(c, RTSP_STATUS_OK); */
3050 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
3051 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
3052 avio_printf(c->pb, "Public: %s\r\n",
3053 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
3054 avio_printf(c->pb, "\r\n");
3057 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
3059 FFServerStream *stream;
3065 struct sockaddr_in my_addr;
3067 /* find which URL is asked */
3068 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3073 for(stream = config.first_stream; stream; stream = stream->next) {
3074 if (!stream->is_feed &&
3075 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
3076 !strcmp(path, stream->filename)) {
3080 /* no stream found */
3081 rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
3085 /* prepare the media description in SDP format */
3087 /* get the host IP */
3088 len = sizeof(my_addr);
3089 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3090 content_length = prepare_sdp_description(stream, &content,
3092 if (content_length < 0) {
3093 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3096 rtsp_reply_header(c, RTSP_STATUS_OK);
3097 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
3098 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
3099 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
3100 avio_printf(c->pb, "\r\n");
3101 avio_write(c->pb, content, content_length);
3105 static HTTPContext *find_rtp_session(const char *session_id)
3109 if (session_id[0] == '\0')
3112 for(c = first_http_ctx; c; c = c->next) {
3113 if (!strcmp(c->session_id, session_id))
3119 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3121 RTSPTransportField *th;
3124 for(i=0;i<h->nb_transports;i++) {
3125 th = &h->transports[i];
3126 if (th->lower_transport == lower_transport)
3132 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3133 RTSPMessageHeader *h)
3135 FFServerStream *stream;
3136 int stream_index, rtp_port, rtcp_port;
3141 RTSPTransportField *th;
3142 struct sockaddr_in dest_addr;
3143 RTSPActionServerSetup setup;
3145 /* find which URL is asked */
3146 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3151 /* now check each stream */
3152 for(stream = config.first_stream; stream; stream = stream->next) {
3153 if (stream->is_feed || !stream->fmt ||
3154 strcmp(stream->fmt->name, "rtp")) {
3157 /* accept aggregate filenames only if single stream */
3158 if (!strcmp(path, stream->filename)) {
3159 if (stream->nb_streams != 1) {
3160 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3167 for(stream_index = 0; stream_index < stream->nb_streams;
3169 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3170 stream->filename, stream_index);
3171 if (!strcmp(path, buf))
3175 /* no stream found */
3176 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3180 /* generate session id if needed */
3181 if (h->session_id[0] == '\0') {
3182 unsigned random0 = av_lfg_get(&random_state);
3183 unsigned random1 = av_lfg_get(&random_state);
3184 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3188 /* find RTP session, and create it if none found */
3189 rtp_c = find_rtp_session(h->session_id);
3191 /* always prefer UDP */
3192 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3194 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3196 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3201 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3202 th->lower_transport);
3204 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3208 /* open input stream */
3209 if (open_input_stream(rtp_c, "") < 0) {
3210 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3215 /* test if stream is OK (test needed because several SETUP needs
3216 * to be done for a given file) */
3217 if (rtp_c->stream != stream) {
3218 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3222 /* test if stream is already set up */
3223 if (rtp_c->rtp_ctx[stream_index]) {
3224 rtsp_reply_error(c, RTSP_STATUS_STATE);
3228 /* check transport */
3229 th = find_transport(h, rtp_c->rtp_protocol);
3230 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3231 th->client_port_min <= 0)) {
3232 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3236 /* setup default options */
3237 setup.transport_option[0] = '\0';
3238 dest_addr = rtp_c->from_addr;
3239 dest_addr.sin_port = htons(th->client_port_min);
3242 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3243 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3247 /* now everything is OK, so we can send the connection parameters */
3248 rtsp_reply_header(c, RTSP_STATUS_OK);
3250 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3252 switch(rtp_c->rtp_protocol) {
3253 case RTSP_LOWER_TRANSPORT_UDP:
3254 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3255 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3256 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3257 "client_port=%d-%d;server_port=%d-%d",
3258 th->client_port_min, th->client_port_max,
3259 rtp_port, rtcp_port);
3261 case RTSP_LOWER_TRANSPORT_TCP:
3262 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3263 stream_index * 2, stream_index * 2 + 1);
3268 if (setup.transport_option[0] != '\0')
3269 avio_printf(c->pb, ";%s", setup.transport_option);
3270 avio_printf(c->pb, "\r\n");
3273 avio_printf(c->pb, "\r\n");
3278 * find an RTP connection by using the session ID. Check consistency
3281 static HTTPContext *find_rtp_session_with_url(const char *url,
3282 const char *session_id)
3290 rtp_c = find_rtp_session(session_id);
3294 /* find which URL is asked */
3295 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3299 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3300 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3301 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3302 rtp_c->stream->filename, s);
3303 if(!strncmp(path, buf, sizeof(buf)))
3304 /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3305 * if nb_streams>1? */
3309 if (len > 0 && path[len - 1] == '/' &&
3310 !strncmp(path, rtp_c->stream->filename, len - 1))
3315 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3319 rtp_c = find_rtp_session_with_url(url, h->session_id);
3321 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3325 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3326 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3327 rtp_c->state != HTTPSTATE_READY) {
3328 rtsp_reply_error(c, RTSP_STATUS_STATE);
3332 rtp_c->state = HTTPSTATE_SEND_DATA;
3334 /* now everything is OK, so we can send the connection parameters */
3335 rtsp_reply_header(c, RTSP_STATUS_OK);
3337 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3338 avio_printf(c->pb, "\r\n");
3341 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3342 RTSPMessageHeader *h, int pause_only)
3346 rtp_c = find_rtp_session_with_url(url, h->session_id);
3348 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3353 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3354 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3355 rtsp_reply_error(c, RTSP_STATUS_STATE);
3358 rtp_c->state = HTTPSTATE_READY;
3359 rtp_c->first_pts = AV_NOPTS_VALUE;
3362 /* now everything is OK, so we can send the connection parameters */
3363 rtsp_reply_header(c, RTSP_STATUS_OK);
3365 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3366 avio_printf(c->pb, "\r\n");
3369 close_connection(rtp_c);
3372 /********************************************************************/
3375 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3376 FFServerStream *stream,
3377 const char *session_id,
3378 enum RTSPLowerTransport rtp_protocol)
3380 HTTPContext *c = NULL;
3381 const char *proto_str;
3383 /* XXX: should output a warning page when coming
3384 * close to the connection limit */
3385 if (nb_connections >= config.nb_max_connections)
3388 /* add a new connection */
3389 c = av_mallocz(sizeof(HTTPContext));
3394 c->poll_entry = NULL;
3395 c->from_addr = *from_addr;
3396 c->buffer_size = IOBUFFER_INIT_SIZE;
3397 c->buffer = av_malloc(c->buffer_size);
3402 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3403 c->state = HTTPSTATE_READY;
3404 c->is_packetized = 1;
3405 c->rtp_protocol = rtp_protocol;
3407 /* protocol is shown in statistics */
3408 switch(c->rtp_protocol) {
3409 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3410 proto_str = "MCAST";
3412 case RTSP_LOWER_TRANSPORT_UDP:
3415 case RTSP_LOWER_TRANSPORT_TCP:
3422 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3423 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3425 current_bandwidth += stream->bandwidth;
3427 c->next = first_http_ctx;
3433 av_freep(&c->buffer);
3440 * add a new RTP stream in an RTP connection (used in RTSP SETUP
3441 * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3444 static int rtp_new_av_stream(HTTPContext *c,
3445 int stream_index, struct sockaddr_in *dest_addr,
3446 HTTPContext *rtsp_c)
3448 AVFormatContext *ctx;
3451 URLContext *h = NULL;
3453 int max_packet_size;
3456 /* now we can open the relevant output stream */
3457 ctx = avformat_alloc_context();
3460 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3462 st = avformat_new_stream(ctx, NULL);
3466 st_internal = st->internal;
3468 if (!c->stream->feed ||
3469 c->stream->feed == c->stream)
3470 unlayer_stream(st, c->stream->streams[stream_index]);
3473 c->stream->feed->streams[c->stream->feed_streams[stream_index]]);
3474 av_assert0(st->priv_data == NULL);
3475 av_assert0(st->internal == st_internal);
3477 /* build destination RTP address */
3478 ipaddr = inet_ntoa(dest_addr->sin_addr);
3480 switch(c->rtp_protocol) {
3481 case RTSP_LOWER_TRANSPORT_UDP:
3482 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3485 /* XXX: also pass as parameter to function ? */
3486 if (c->stream->is_multicast) {
3488 ttl = c->stream->multicast_ttl;
3491 snprintf(ctx->filename, sizeof(ctx->filename),
3492 "rtp://%s:%d?multicast=1&ttl=%d",
3493 ipaddr, ntohs(dest_addr->sin_port), ttl);
3495 snprintf(ctx->filename, sizeof(ctx->filename),
3496 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3499 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3501 c->rtp_handles[stream_index] = h;
3502 max_packet_size = h->max_packet_size;
3504 case RTSP_LOWER_TRANSPORT_TCP:
3507 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3513 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3514 ipaddr, ntohs(dest_addr->sin_port),
3515 c->stream->filename, stream_index, c->protocol);
3517 /* normally, no packets should be output here, but the packet size may
3519 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3520 /* XXX: close stream */
3523 if (avformat_write_header(ctx, NULL) < 0) {
3531 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3535 c->rtp_ctx[stream_index] = ctx;
3539 /********************************************************************/
3540 /* ffserver initialization */
3542 /* FIXME: This code should use avformat_new_stream() */
3543 static LayeredAVStream *add_av_stream1(FFServerStream *stream,
3544 AVCodecContext *codec, int copy)
3546 LayeredAVStream *fst;
3548 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3551 fst = av_mallocz(sizeof(*fst));
3555 fst->codec = avcodec_alloc_context3(codec->codec);
3560 avcodec_copy_context(fst->codec, codec);
3562 /* live streams must use the actual feed's codec since it may be
3563 * updated later to carry extradata needed by them.
3567 //NOTE we previously allocated internal & internal->avctx, these seemed uneeded though
3568 fst->codecpar = avcodec_parameters_alloc();
3569 fst->index = stream->nb_streams;
3570 fst->time_base = codec->time_base;
3571 fst->pts_wrap_bits = 33;
3572 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3573 stream->streams[stream->nb_streams++] = fst;
3577 /* return the stream number in the feed */
3578 static int add_av_stream(FFServerStream *feed, LayeredAVStream *st)
3580 LayeredAVStream *fst;
3581 AVCodecContext *av, *av1;
3585 for(i=0;i<feed->nb_streams;i++) {
3586 av1 = feed->streams[i]->codec;
3587 if (av1->codec_id == av->codec_id &&
3588 av1->codec_type == av->codec_type &&
3589 av1->bit_rate == av->bit_rate) {
3591 switch(av->codec_type) {
3592 case AVMEDIA_TYPE_AUDIO:
3593 if (av1->channels == av->channels &&
3594 av1->sample_rate == av->sample_rate)
3597 case AVMEDIA_TYPE_VIDEO:
3598 if (av1->width == av->width &&
3599 av1->height == av->height &&
3600 av1->time_base.den == av->time_base.den &&
3601 av1->time_base.num == av->time_base.num &&
3602 av1->gop_size == av->gop_size)
3611 fst = add_av_stream1(feed, av, 0);
3614 if (st->recommended_encoder_configuration)
3615 fst->recommended_encoder_configuration =
3616 av_strdup(st->recommended_encoder_configuration);
3617 return feed->nb_streams - 1;
3620 static void remove_stream(FFServerStream *stream)
3622 FFServerStream **ps;
3623 ps = &config.first_stream;
3632 /* compute the needed AVStream for each file */
3633 static void build_file_streams(void)
3635 FFServerStream *stream;
3636 AVFormatContext *infile;
3639 /* gather all streams */
3640 for(stream = config.first_stream; stream; stream = stream->next) {
3643 if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
3646 /* the stream comes from a file */
3647 /* try to open the file */
3651 /* specific case: if transport stream output to RTP,
3652 * we use a raw transport stream reader */
3653 if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
3654 av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3656 if (!stream->feed_filename[0]) {
3657 http_log("Unspecified feed file for stream '%s'\n",
3662 http_log("Opening feed file '%s' for stream '%s'\n",
3663 stream->feed_filename, stream->filename);
3665 ret = avformat_open_input(&infile, stream->feed_filename,
3666 stream->ifmt, &stream->in_opts);
3668 http_log("Could not open '%s': %s\n", stream->feed_filename,
3670 /* remove stream (no need to spend more time on it) */
3672 remove_stream(stream);
3674 /* find all the AVStreams inside and reference them in
3676 if (avformat_find_stream_info(infile, NULL) < 0) {
3677 http_log("Could not find codec parameters from '%s'\n",
3678 stream->feed_filename);
3679 avformat_close_input(&infile);
3683 for(i=0;i<infile->nb_streams;i++)
3684 add_av_stream1(stream, infile->streams[i]->codec, 1);
3686 avformat_close_input(&infile);
3692 int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream)
3696 /* FIXME: Missed check on AVCodecContext.flags */
3697 #define CHECK_CODEC(x) (ccf->codecpar->x != ccs->codecpar->x)
3698 if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3699 http_log("Codecs do not match for stream %d\n", stream);
3701 } else if (CHECK_CODEC(bit_rate)) {
3702 http_log("Codec bitrates do not match for stream %d\n", stream);
3704 } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3705 if (av_cmp_q(ccf->time_base, ccs->time_base) ||
3706 CHECK_CODEC(width) || CHECK_CODEC(height)) {
3707 http_log("Codec width, height or framerate do not match for stream %d\n", stream);
3710 } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3711 if (CHECK_CODEC(sample_rate) ||
3712 CHECK_CODEC(channels) ||
3713 CHECK_CODEC(frame_size)) {
3714 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
3718 http_log("Unknown codec type for stream %d\n", stream);
3725 /* compute the needed AVStream for each feed */
3726 static int build_feed_streams(void)
3728 FFServerStream *stream, *feed;
3731 /* gather all streams */
3732 for(stream = config.first_stream; stream; stream = stream->next) {
3733 feed = stream->feed;
3737 if (stream->is_feed) {
3738 for(i=0;i<stream->nb_streams;i++)
3739 stream->feed_streams[i] = i;
3742 /* we handle a stream coming from a feed */
3743 for(i=0;i<stream->nb_streams;i++)
3744 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3747 /* create feed files if needed */
3748 for(feed = config.first_feed; feed; feed = feed->next_feed) {
3750 if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
3751 AVFormatContext *s = NULL;
3754 /* See if it matches */
3756 if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
3757 http_log("Deleting feed file '%s' as it appears "
3759 feed->feed_filename);
3763 /* set buffer size */
3764 if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
3765 http_log("Failed to set buffer size\n");
3766 avformat_close_input(&s);
3770 /* Now see if it matches */
3771 if (s->nb_streams != feed->nb_streams) {
3772 http_log("Deleting feed file '%s' as stream counts "
3773 "differ (%d != %d)\n",
3774 feed->feed_filename, s->nb_streams, feed->nb_streams);
3779 for(i=0;i<s->nb_streams;i++) {
3781 LayeredAVStream *sf;
3783 sf = feed->streams[i];
3786 if (sf->index != ss->index || sf->id != ss->id) {
3787 http_log("Index & Id do not match for stream %d (%s)\n",
3788 i, feed->feed_filename);
3793 matches = check_codec_match (sf, ss, i);
3800 avformat_close_input(&s);
3803 if (feed->readonly) {
3804 http_log("Unable to delete read-only feed file '%s'\n",
3805 feed->feed_filename);
3808 unlink(feed->feed_filename);
3812 if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
3813 AVFormatContext *s = avformat_alloc_context();
3816 http_log("Failed to allocate context\n");
3820 if (feed->readonly) {
3821 http_log("Unable to create feed file '%s' as it is "
3822 "marked readonly\n",
3823 feed->feed_filename);
3824 avformat_free_context(s);
3828 /* only write the header of the ffm file */
3829 if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
3830 http_log("Could not open output feed file '%s'\n",
3831 feed->feed_filename);
3832 avformat_free_context(s);
3835 s->oformat = feed->fmt;
3836 for (i = 0; i<feed->nb_streams; i++) {
3837 AVStream *st = avformat_new_stream(s, NULL); // FIXME free this
3839 http_log("Failed to allocate stream\n");
3842 unlayer_stream(st, feed->streams[i]);
3844 if (avformat_write_header(s, NULL) < 0) {
3845 http_log("Container doesn't support the required parameters\n");
3846 avio_closep(&s->pb);
3849 avformat_free_context(s);
3852 /* XXX: need better API */
3853 av_freep(&s->priv_data);
3854 avio_closep(&s->pb);
3857 avformat_free_context(s);
3860 /* get feed size and write index */
3861 fd = open(feed->feed_filename, O_RDONLY);
3863 http_log("Could not open output feed file '%s'\n",
3864 feed->feed_filename);
3868 feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
3870 feed->feed_size = lseek(fd, 0, SEEK_END);
3871 /* ensure that we do not wrap before the end of file */
3872 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3873 feed->feed_max_size = feed->feed_size;
3883 /* compute the bandwidth used by each stream */
3884 static void compute_bandwidth(void)
3888 FFServerStream *stream;
3890 for(stream = config.first_stream; stream; stream = stream->next) {
3892 for(i=0;i<stream->nb_streams;i++) {
3893 LayeredAVStream *st = stream->streams[i];
3894 switch(st->codec->codec_type) {
3895 case AVMEDIA_TYPE_AUDIO:
3896 case AVMEDIA_TYPE_VIDEO:
3897 bandwidth += st->codec->bit_rate;
3903 stream->bandwidth = (bandwidth + 999) / 1000;
3907 static void handle_child_exit(int sig)
3913 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3914 FFServerStream *feed;
3916 for (feed = config.first_feed; feed; feed = feed->next) {
3917 if (feed->pid != pid)
3920 uptime = time(0) - feed->pid_start;
3923 "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
3925 feed->filename, (int64_t) pid, status, (int64_t)uptime);
3928 /* Turn off any more restarts */
3929 ffserver_free_child_args(&feed->child_argv);
3933 need_to_start_children = 1;
3936 static void opt_debug(void)
3939 snprintf(config.logfilename, sizeof(config.logfilename), "-");
3942 void show_help_default(const char *opt, const char *arg)
3944 printf("usage: ffserver [options]\n"
3945 "Hyper fast multi format Audio/Video streaming server\n");
3947 show_help_options(options, "Main options:", 0, 0, 0);
3950 static const OptionDef options[] = {
3951 #include "cmdutils_common_opts.h"
3952 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
3953 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
3954 { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
3958 int main(int argc, char **argv)
3960 struct sigaction sigact = { { 0 } };
3962 int ret = EXIT_FAILURE;
3966 config.filename = av_strdup("/etc/ffserver.conf");
3968 parse_loglevel(argc, argv, options);
3970 avformat_network_init();
3972 show_banner(argc, argv, options);
3974 my_program_name = argv[0];
3976 parse_options(NULL, argc, argv, options, NULL);
3978 unsetenv("http_proxy"); /* Kill the http_proxy */
3980 av_lfg_init(&random_state, av_get_random_seed());
3982 sigact.sa_handler = handle_child_exit;
3983 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
3984 sigaction(SIGCHLD, &sigact, 0);
3986 if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
3987 fprintf(stderr, "Error reading configuration file '%s': %s\n",
3988 config.filename, av_err2str(cfg_parsed));
3992 /* open log file if needed */
3993 if (config.logfilename[0] != '\0') {
3994 if (!strcmp(config.logfilename, "-"))
3997 logfile = fopen(config.logfilename, "a");
3998 av_log_set_callback(http_av_log);
4001 build_file_streams();
4003 if (build_feed_streams() < 0) {
4004 http_log("Could not setup feed streams\n");
4008 compute_bandwidth();
4011 signal(SIGPIPE, SIG_IGN);
4013 if (http_server() < 0) {
4014 http_log("Could not start server\n");
4021 av_freep (&config.filename);
4022 avformat_network_deinit();