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)
479 char *dirname, *prog;
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 /* use "ffmpeg" in the path of current program. Ignore user provided path */
499 prog = av_strdup(my_program_name);
501 dirname = av_dirname(prog);
502 pathname = *dirname ? av_asprintf("%s/%s", dirname, "ffmpeg")
503 : av_asprintf("ffmpeg");
506 if (!prog || !pathname) {
507 http_log("Could not allocate memory for children cmd line\n");
511 for (; feed; feed = feed->next) {
513 if (!feed->child_argv || feed->pid)
516 feed->pid_start = time(0);
520 http_log("Unable to create children: %s\n", strerror(errno));
530 http_log("Launch command line: ");
531 http_log("%s ", pathname);
533 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
534 http_log("%s ", feed->child_argv[i]);
537 for (i = 3; i < 256; i++)
541 if (!freopen("/dev/null", "r", stdin))
542 http_log("failed to redirect STDIN to /dev/null\n;");
543 if (!freopen("/dev/null", "w", stdout))
544 http_log("failed to redirect STDOUT to /dev/null\n;");
545 if (!freopen("/dev/null", "w", stderr))
546 http_log("failed to redirect STDERR to /dev/null\n;");
549 signal(SIGPIPE, SIG_DFL);
550 execvp(pathname, feed->child_argv);
557 /* open a listening socket */
558 static int socket_open_listen(struct sockaddr_in *my_addr)
562 server_fd = socket(AF_INET,SOCK_STREAM,0);
569 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
570 av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
572 my_addr->sin_family = AF_INET;
573 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
575 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
576 ntohs(my_addr->sin_port));
581 if (listen (server_fd, 5) < 0) {
586 if (ff_socket_nonblock(server_fd, 1) < 0)
587 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
592 closesocket(server_fd);
596 /* start all multicast streams */
597 static void start_multicast(void)
599 FFServerStream *stream;
602 struct sockaddr_in dest_addr = {0};
603 int default_port, stream_index;
604 unsigned int random0, random1;
607 for(stream = config.first_stream; stream; stream = stream->next) {
609 if (!stream->is_multicast)
612 random0 = av_lfg_get(&random_state);
613 random1 = av_lfg_get(&random_state);
615 /* open the RTP connection */
616 snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
618 /* choose a port if none given */
619 if (stream->multicast_port == 0) {
620 stream->multicast_port = default_port;
624 dest_addr.sin_family = AF_INET;
625 dest_addr.sin_addr = stream->multicast_ip;
626 dest_addr.sin_port = htons(stream->multicast_port);
628 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
629 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
633 if (open_input_stream(rtp_c, "") < 0) {
634 http_log("Could not open input stream for stream '%s'\n",
639 /* open each RTP stream */
640 for(stream_index = 0; stream_index < stream->nb_streams;
642 dest_addr.sin_port = htons(stream->multicast_port +
644 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
647 http_log("Could not open output stream '%s/streamid=%d'\n",
648 stream->filename, stream_index);
652 rtp_c->state = HTTPSTATE_SEND_DATA;
656 /* main loop of the HTTP server */
657 static int http_server(void)
659 int server_fd = 0, rtsp_server_fd = 0;
661 struct pollfd *poll_table, *poll_entry;
662 HTTPContext *c, *c_next;
664 poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
665 sizeof(*poll_table));
667 http_log("Impossible to allocate a poll table handling %d "
668 "connections.\n", config.nb_max_http_connections);
672 if (config.http_addr.sin_port) {
673 server_fd = socket_open_listen(&config.http_addr);
678 if (config.rtsp_addr.sin_port) {
679 rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
680 if (rtsp_server_fd < 0) {
681 closesocket(server_fd);
686 if (!rtsp_server_fd && !server_fd) {
687 http_log("HTTP and RTSP disabled.\n");
691 http_log("FFserver started.\n");
693 start_children(config.first_feed);
698 poll_entry = poll_table;
700 poll_entry->fd = server_fd;
701 poll_entry->events = POLLIN;
704 if (rtsp_server_fd) {
705 poll_entry->fd = rtsp_server_fd;
706 poll_entry->events = POLLIN;
710 /* wait for events on each HTTP handle */
717 case HTTPSTATE_SEND_HEADER:
718 case RTSPSTATE_SEND_REPLY:
719 case RTSPSTATE_SEND_PACKET:
720 c->poll_entry = poll_entry;
722 poll_entry->events = POLLOUT;
725 case HTTPSTATE_SEND_DATA_HEADER:
726 case HTTPSTATE_SEND_DATA:
727 case HTTPSTATE_SEND_DATA_TRAILER:
728 if (!c->is_packetized) {
729 /* for TCP, we output as much as we can
730 * (may need to put a limit) */
731 c->poll_entry = poll_entry;
733 poll_entry->events = POLLOUT;
736 /* when ffserver is doing the timing, we work by
737 * looking at which packet needs to be sent every
738 * 10 ms (one tick wait XXX: 10 ms assumed) */
743 case HTTPSTATE_WAIT_REQUEST:
744 case HTTPSTATE_RECEIVE_DATA:
745 case HTTPSTATE_WAIT_FEED:
746 case RTSPSTATE_WAIT_REQUEST:
747 /* need to catch errors */
748 c->poll_entry = poll_entry;
750 poll_entry->events = POLLIN;/* Maybe this will work */
754 c->poll_entry = NULL;
760 /* wait for an event on one connection. We poll at least every
761 * second to handle timeouts */
763 ret = poll(poll_table, poll_entry - poll_table, delay);
764 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
765 ff_neterrno() != AVERROR(EINTR)) {
770 cur_time = av_gettime() / 1000;
772 if (need_to_start_children) {
773 need_to_start_children = 0;
774 start_children(config.first_feed);
777 /* now handle the events */
778 for(c = first_http_ctx; c; c = c_next) {
780 if (handle_connection(c) < 0) {
782 /* close and free the connection */
787 poll_entry = poll_table;
789 /* new HTTP connection request ? */
790 if (poll_entry->revents & POLLIN)
791 new_connection(server_fd, 0);
794 if (rtsp_server_fd) {
795 /* new RTSP connection request ? */
796 if (poll_entry->revents & POLLIN)
797 new_connection(rtsp_server_fd, 1);
806 /* start waiting for a new HTTP/RTSP request */
807 static void start_wait_request(HTTPContext *c, int is_rtsp)
809 c->buffer_ptr = c->buffer;
810 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
812 c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
813 c->timeout = cur_time +
814 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
817 static void http_send_too_busy_reply(int fd)
820 int len = snprintf(buffer, sizeof(buffer),
821 "HTTP/1.0 503 Server too busy\r\n"
822 "Content-type: text/html\r\n"
825 "<html><head><title>Too busy</title></head><body>\r\n"
826 "<p>The server is too busy to serve your request at "
828 "<p>The number of current connections is %u, and this "
829 "exceeds the limit of %u.</p>\r\n"
830 "</body></html>\r\n",
831 nb_connections, config.nb_max_connections);
832 av_assert0(len < sizeof(buffer));
833 if (send(fd, buffer, len, 0) < len)
834 av_log(NULL, AV_LOG_WARNING,
835 "Could not send too-busy reply, send() failed\n");
839 static void new_connection(int server_fd, int is_rtsp)
841 struct sockaddr_in from_addr;
844 HTTPContext *c = NULL;
846 len = sizeof(from_addr);
847 fd = accept(server_fd, (struct sockaddr *)&from_addr,
850 http_log("error during accept %s\n", strerror(errno));
853 if (ff_socket_nonblock(fd, 1) < 0)
854 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
856 if (nb_connections >= config.nb_max_connections) {
857 http_send_too_busy_reply(fd);
861 /* add a new connection */
862 c = av_mallocz(sizeof(HTTPContext));
867 c->poll_entry = NULL;
868 c->from_addr = from_addr;
869 c->buffer_size = IOBUFFER_INIT_SIZE;
870 c->buffer = av_malloc(c->buffer_size);
874 c->next = first_http_ctx;
878 start_wait_request(c, is_rtsp);
884 av_freep(&c->buffer);
890 static void close_connection(HTTPContext *c)
892 HTTPContext **cp, *c1;
894 AVFormatContext *ctx;
897 /* remove connection from list */
898 cp = &first_http_ctx;
907 /* remove references, if any (XXX: do it faster) */
908 for(c1 = first_http_ctx; c1; c1 = c1->next) {
913 /* remove connection associated resources */
917 /* close each frame parser */
918 for(i=0;i<c->fmt_in->nb_streams;i++) {
919 st = c->fmt_in->streams[i];
920 if (st->codec->codec)
921 avcodec_close(st->codec);
923 avformat_close_input(&c->fmt_in);
926 /* free RTP output streams if any */
929 nb_streams = c->stream->nb_streams;
931 for(i=0;i<nb_streams;i++) {
934 av_write_trailer(ctx);
935 av_dict_free(&ctx->metadata);
936 av_freep(&ctx->streams[0]);
939 ffurl_close(c->rtp_handles[i]);
945 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
947 if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
948 av_write_trailer(ctx);
949 av_freep(&c->pb_buffer);
950 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
953 for(i=0; i<ctx->nb_streams; i++)
954 av_freep(&ctx->streams[i]);
955 av_freep(&ctx->streams);
956 av_freep(&ctx->priv_data);
959 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
960 current_bandwidth -= c->stream->bandwidth;
962 /* signal that there is no feed if we are the feeder socket */
963 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
964 c->stream->feed_opened = 0;
968 av_freep(&c->pb_buffer);
969 av_freep(&c->packet_buffer);
970 av_freep(&c->buffer);
975 static int handle_connection(HTTPContext *c)
981 case HTTPSTATE_WAIT_REQUEST:
982 case RTSPSTATE_WAIT_REQUEST:
984 if ((c->timeout - cur_time) < 0)
986 if (c->poll_entry->revents & (POLLERR | POLLHUP))
989 /* no need to read if no events */
990 if (!(c->poll_entry->revents & POLLIN))
994 if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
998 if (ff_neterrno() != AVERROR(EAGAIN) &&
999 ff_neterrno() != AVERROR(EINTR))
1003 /* search for end of request. */
1004 c->buffer_ptr += len;
1005 ptr = c->buffer_ptr;
1006 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
1007 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
1008 /* request found : parse it and reply */
1009 if (c->state == HTTPSTATE_WAIT_REQUEST)
1010 ret = http_parse_request(c);
1012 ret = rtsp_parse_request(c);
1016 } else if (ptr >= c->buffer_end) {
1017 /* request too long: cannot do anything */
1019 } else goto read_loop;
1023 case HTTPSTATE_SEND_HEADER:
1024 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1027 /* no need to write if no events */
1028 if (!(c->poll_entry->revents & POLLOUT))
1030 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1032 if (ff_neterrno() != AVERROR(EAGAIN) &&
1033 ff_neterrno() != AVERROR(EINTR)) {
1034 goto close_connection;
1038 c->buffer_ptr += len;
1040 c->stream->bytes_served += len;
1041 c->data_count += len;
1042 if (c->buffer_ptr >= c->buffer_end) {
1043 av_freep(&c->pb_buffer);
1044 /* if error, exit */
1047 /* all the buffer was sent : synchronize to the incoming
1049 c->state = HTTPSTATE_SEND_DATA_HEADER;
1050 c->buffer_ptr = c->buffer_end = c->buffer;
1054 case HTTPSTATE_SEND_DATA:
1055 case HTTPSTATE_SEND_DATA_HEADER:
1056 case HTTPSTATE_SEND_DATA_TRAILER:
1057 /* for packetized output, we consider we can always write (the
1058 * input streams set the speed). It may be better to verify
1059 * that we do not rely too much on the kernel queues */
1060 if (!c->is_packetized) {
1061 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1064 /* no need to read if no events */
1065 if (!(c->poll_entry->revents & POLLOUT))
1068 if (http_send_data(c) < 0)
1070 /* close connection if trailer sent */
1071 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
1073 /* Check if it is a single jpeg frame 123 */
1074 if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
1075 close_connection(c);
1078 case HTTPSTATE_RECEIVE_DATA:
1079 /* no need to read if no events */
1080 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1082 if (!(c->poll_entry->revents & POLLIN))
1084 if (http_receive_data(c) < 0)
1087 case HTTPSTATE_WAIT_FEED:
1088 /* no need to read if no events */
1089 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1092 /* nothing to do, we'll be waken up by incoming feed packets */
1095 case RTSPSTATE_SEND_REPLY:
1096 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1097 goto close_connection;
1098 /* no need to write if no events */
1099 if (!(c->poll_entry->revents & POLLOUT))
1101 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1103 if (ff_neterrno() != AVERROR(EAGAIN) &&
1104 ff_neterrno() != AVERROR(EINTR)) {
1105 goto close_connection;
1109 c->buffer_ptr += len;
1110 c->data_count += len;
1111 if (c->buffer_ptr >= c->buffer_end) {
1112 /* all the buffer was sent : wait for a new request */
1113 av_freep(&c->pb_buffer);
1114 start_wait_request(c, 1);
1117 case RTSPSTATE_SEND_PACKET:
1118 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1119 av_freep(&c->packet_buffer);
1122 /* no need to write if no events */
1123 if (!(c->poll_entry->revents & POLLOUT))
1125 len = send(c->fd, c->packet_buffer_ptr,
1126 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1128 if (ff_neterrno() != AVERROR(EAGAIN) &&
1129 ff_neterrno() != AVERROR(EINTR)) {
1130 /* error : close connection */
1131 av_freep(&c->packet_buffer);
1136 c->packet_buffer_ptr += len;
1137 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1138 /* all the buffer was sent : wait for a new request */
1139 av_freep(&c->packet_buffer);
1140 c->state = RTSPSTATE_WAIT_REQUEST;
1143 case HTTPSTATE_READY:
1152 av_freep(&c->pb_buffer);
1156 static int extract_rates(char *rates, int ratelen, const char *request)
1160 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1161 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1162 const char *q = p + 7;
1164 while (*q && *q != '\n' && av_isspace(*q))
1167 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1173 memset(rates, 0xff, ratelen);
1176 while (*q && *q != '\n' && *q != ':')
1179 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1183 if (stream_no < ratelen && stream_no >= 0)
1184 rates[stream_no] = rate_no;
1186 while (*q && *q != '\n' && !av_isspace(*q))
1193 p = strchr(p, '\n');
1203 static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec,
1207 int best_bitrate = 100000000;
1210 for (i = 0; i < feed->nb_streams; i++) {
1211 AVCodecParameters *feed_codec = feed->streams[i]->codecpar;
1213 if (feed_codec->codec_id != codec->codec_id ||
1214 feed_codec->sample_rate != codec->sample_rate ||
1215 feed_codec->width != codec->width ||
1216 feed_codec->height != codec->height)
1219 /* Potential stream */
1221 /* We want the fastest stream less than bit_rate, or the slowest
1222 * faster than bit_rate
1225 if (feed_codec->bit_rate <= bit_rate) {
1226 if (best_bitrate > bit_rate ||
1227 feed_codec->bit_rate > best_bitrate) {
1228 best_bitrate = feed_codec->bit_rate;
1233 if (feed_codec->bit_rate < best_bitrate) {
1234 best_bitrate = feed_codec->bit_rate;
1241 static int modify_current_stream(HTTPContext *c, char *rates)
1244 FFServerStream *req = c->stream;
1245 int action_required = 0;
1247 /* Not much we can do for a feed */
1251 for (i = 0; i < req->nb_streams; i++) {
1252 AVCodecParameters *codec = req->streams[i]->codecpar;
1256 c->switch_feed_streams[i] = req->feed_streams[i];
1259 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1262 /* Wants off or slow */
1263 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1265 /* This doesn't work well when it turns off the only stream! */
1266 c->switch_feed_streams[i] = -2;
1267 c->feed_streams[i] = -2;
1272 if (c->switch_feed_streams[i] >= 0 &&
1273 c->switch_feed_streams[i] != c->feed_streams[i]) {
1274 action_required = 1;
1278 return action_required;
1281 static void get_word(char *buf, int buf_size, const char **pp)
1286 #define SPACE_CHARS " \t\r\n"
1289 p += strspn(p, SPACE_CHARS);
1291 while (!av_isspace(*p) && *p != '\0') {
1292 if ((q - buf) < buf_size - 1)
1301 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1307 FFServerIPAddressACL *acl = NULL;
1311 f = fopen(stream->dynamic_acl, "r");
1313 perror(stream->dynamic_acl);
1317 acl = av_mallocz(sizeof(FFServerIPAddressACL));
1324 while (fgets(line, sizeof(line), f)) {
1327 while (av_isspace(*p))
1329 if (*p == '\0' || *p == '#')
1331 ffserver_get_arg(cmd, sizeof(cmd), &p);
1333 if (!av_strcasecmp(cmd, "ACL"))
1334 ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1342 static void free_acl_list(FFServerIPAddressACL *in_acl)
1344 FFServerIPAddressACL *pacl, *pacl2;
1354 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1356 enum FFServerIPAddressAction last_action = IP_DENY;
1357 FFServerIPAddressACL *acl;
1358 struct in_addr *src = &c->from_addr.sin_addr;
1359 unsigned long src_addr = src->s_addr;
1361 for (acl = in_acl; acl; acl = acl->next) {
1362 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1363 return (acl->action == IP_ALLOW) ? 1 : 0;
1364 last_action = acl->action;
1367 /* Nothing matched, so return not the last action */
1368 return (last_action == IP_DENY) ? 1 : 0;
1371 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1374 FFServerIPAddressACL *acl;
1376 /* if stream->acl is null validate_acl_list will return 1 */
1377 ret = validate_acl_list(stream->acl, c);
1379 if (stream->dynamic_acl[0]) {
1380 acl = parse_dynamic_acl(stream, c);
1381 ret = validate_acl_list(acl, c);
1389 * compute the real filename of a file by matching it without its
1390 * extensions to all the stream's filenames
1392 static void compute_real_filename(char *filename, int max_size)
1397 FFServerStream *stream;
1399 av_strlcpy(file1, filename, sizeof(file1));
1400 p = strrchr(file1, '.');
1403 for(stream = config.first_stream; stream; stream = stream->next) {
1404 av_strlcpy(file2, stream->filename, sizeof(file2));
1405 p = strrchr(file2, '.');
1408 if (!strcmp(file1, file2)) {
1409 av_strlcpy(filename, stream->filename, max_size);
1424 /* parse HTTP request and prepare header */
1425 static int http_parse_request(HTTPContext *c)
1429 enum RedirType redir_type;
1431 char info[1024], filename[1024];
1435 char *encoded_msg = NULL;
1436 const char *mime_type;
1437 FFServerStream *stream;
1440 const char *useragent = 0;
1443 get_word(cmd, sizeof(cmd), &p);
1444 av_strlcpy(c->method, cmd, sizeof(c->method));
1446 if (!strcmp(cmd, "GET"))
1448 else if (!strcmp(cmd, "POST"))
1453 get_word(url, sizeof(url), &p);
1454 av_strlcpy(c->url, url, sizeof(c->url));
1456 get_word(protocol, sizeof(protocol), (const char **)&p);
1457 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1460 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1463 http_log("%s - - New connection: %s %s\n",
1464 inet_ntoa(c->from_addr.sin_addr), cmd, url);
1466 /* find the filename and the optional info string in the request */
1467 p1 = strchr(url, '?');
1469 av_strlcpy(info, p1, sizeof(info));
1474 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1476 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1477 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1479 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1483 p = strchr(p, '\n');
1490 redir_type = REDIR_NONE;
1491 if (av_match_ext(filename, "asx")) {
1492 redir_type = REDIR_ASX;
1493 filename[strlen(filename)-1] = 'f';
1494 } else if (av_match_ext(filename, "asf") &&
1495 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1496 /* if this isn't WMP or lookalike, return the redirector file */
1497 redir_type = REDIR_ASF;
1498 } else if (av_match_ext(filename, "rpm,ram")) {
1499 redir_type = REDIR_RAM;
1500 strcpy(filename + strlen(filename)-2, "m");
1501 } else if (av_match_ext(filename, "rtsp")) {
1502 redir_type = REDIR_RTSP;
1503 compute_real_filename(filename, sizeof(filename) - 1);
1504 } else if (av_match_ext(filename, "sdp")) {
1505 redir_type = REDIR_SDP;
1506 compute_real_filename(filename, sizeof(filename) - 1);
1509 /* "redirect" request to index.html */
1510 if (!strlen(filename))
1511 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1513 stream = config.first_stream;
1515 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1517 stream = stream->next;
1520 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1521 http_log("File '%s' not found\n", url);
1526 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1527 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1529 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1530 c->http_error = 301;
1532 snprintf(q, c->buffer_size,
1533 "HTTP/1.0 301 Moved\r\n"
1535 "Content-type: text/html\r\n"
1538 "<html><head><title>Moved</title></head><body>\r\n"
1539 "You should be <a href=\"%s\">redirected</a>.\r\n"
1540 "</body></html>\r\n",
1541 stream->feed_filename, stream->feed_filename);
1543 /* prepare output buffer */
1544 c->buffer_ptr = c->buffer;
1546 c->state = HTTPSTATE_SEND_HEADER;
1550 /* If this is WMP, get the rate information */
1551 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1552 if (modify_current_stream(c, ratebuf)) {
1553 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1554 if (c->switch_feed_streams[i] >= 0)
1555 c->switch_feed_streams[i] = -1;
1560 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1561 current_bandwidth += stream->bandwidth;
1563 /* If already streaming this feed, do not let another feeder start */
1564 if (stream->feed_opened) {
1565 snprintf(msg, sizeof(msg), "This feed is already being received.");
1566 http_log("Feed '%s' already being received\n", stream->feed_filename);
1570 if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1571 c->http_error = 503;
1573 snprintf(q, c->buffer_size,
1574 "HTTP/1.0 503 Server too busy\r\n"
1575 "Content-type: text/html\r\n"
1578 "<html><head><title>Too busy</title></head><body>\r\n"
1579 "<p>The server is too busy to serve your request at "
1580 "this time.</p>\r\n"
1581 "<p>The bandwidth being served (including your stream) "
1582 "is %"PRIu64"kbit/s, and this exceeds the limit of "
1583 "%"PRIu64"kbit/s.</p>\r\n"
1584 "</body></html>\r\n",
1585 current_bandwidth, config.max_bandwidth);
1587 /* prepare output buffer */
1588 c->buffer_ptr = c->buffer;
1590 c->state = HTTPSTATE_SEND_HEADER;
1594 if (redir_type != REDIR_NONE) {
1595 const char *hostinfo = 0;
1597 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1598 if (av_strncasecmp(p, "Host:", 5) == 0) {
1602 p = strchr(p, '\n');
1613 while (av_isspace(*hostinfo))
1616 eoh = strchr(hostinfo, '\n');
1618 if (eoh[-1] == '\r')
1621 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1622 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1623 hostbuf[eoh - hostinfo] = 0;
1625 c->http_error = 200;
1627 switch(redir_type) {
1629 snprintf(q, c->buffer_size,
1630 "HTTP/1.0 200 ASX Follows\r\n"
1631 "Content-type: video/x-ms-asf\r\n"
1633 "<ASX Version=\"3\">\r\n"
1634 //"<!-- Autogenerated by ffserver -->\r\n"
1635 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1636 "</ASX>\r\n", hostbuf, filename, info);
1640 snprintf(q, c->buffer_size,
1641 "HTTP/1.0 200 RAM Follows\r\n"
1642 "Content-type: audio/x-pn-realaudio\r\n"
1644 "# Autogenerated by ffserver\r\n"
1645 "http://%s/%s%s\r\n", hostbuf, filename, info);
1649 snprintf(q, c->buffer_size,
1650 "HTTP/1.0 200 ASF Redirect follows\r\n"
1651 "Content-type: video/x-ms-asf\r\n"
1654 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1659 char hostname[256], *p;
1660 /* extract only hostname */
1661 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1662 p = strrchr(hostname, ':');
1665 snprintf(q, c->buffer_size,
1666 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1667 /* XXX: incorrect MIME type ? */
1668 "Content-type: application/x-rtsp\r\n"
1670 "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1679 struct sockaddr_in my_addr;
1681 snprintf(q, c->buffer_size,
1682 "HTTP/1.0 200 OK\r\n"
1683 "Content-type: application/sdp\r\n"
1687 len = sizeof(my_addr);
1689 /* XXX: Should probably fail? */
1690 if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1691 http_log("getsockname() failed\n");
1693 /* XXX: should use a dynamic buffer */
1694 sdp_data_size = prepare_sdp_description(stream,
1697 if (sdp_data_size > 0) {
1698 memcpy(q, sdp_data, sdp_data_size);
1701 av_freep(&sdp_data);
1710 /* prepare output buffer */
1711 c->buffer_ptr = c->buffer;
1713 c->state = HTTPSTATE_SEND_HEADER;
1719 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1723 stream->conns_served++;
1725 /* XXX: add there authenticate and IP match */
1728 /* if post, it means a feed is being sent */
1729 if (!stream->is_feed) {
1730 /* However it might be a status report from WMP! Let us log the
1731 * data as it might come handy one day. */
1732 const char *logline = 0;
1735 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1736 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1740 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1741 client_id = strtol(p + 18, 0, 10);
1742 p = strchr(p, '\n');
1750 char *eol = strchr(logline, '\n');
1755 if (eol[-1] == '\r')
1757 http_log("%.*s\n", (int) (eol - logline), logline);
1758 c->suppress_log = 1;
1763 http_log("\nGot request:\n%s\n", c->buffer);
1766 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1769 /* Now we have to find the client_id */
1770 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1771 if (wmpc->wmp_client_id == client_id)
1775 if (wmpc && modify_current_stream(wmpc, ratebuf))
1776 wmpc->switch_pending = 1;
1779 snprintf(msg, sizeof(msg), "POST command not handled");
1783 if (http_start_receive_data(c) < 0) {
1784 snprintf(msg, sizeof(msg), "could not open feed");
1788 c->state = HTTPSTATE_RECEIVE_DATA;
1793 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1794 http_log("\nGot request:\n%s\n", c->buffer);
1797 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1800 /* open input stream */
1801 if (open_input_stream(c, info) < 0) {
1802 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1806 /* prepare HTTP header */
1808 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1809 mime_type = c->stream->fmt->mime_type;
1811 mime_type = "application/x-octet-stream";
1812 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1814 /* for asf, we need extra headers */
1815 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1816 /* Need to allocate a client id */
1818 c->wmp_client_id = av_lfg_get(&random_state);
1820 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);
1822 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1823 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1824 q = c->buffer + strlen(c->buffer);
1826 /* prepare output buffer */
1828 c->buffer_ptr = c->buffer;
1830 c->state = HTTPSTATE_SEND_HEADER;
1833 c->http_error = 404;
1835 if (!htmlencode(msg, &encoded_msg)) {
1836 http_log("Could not encode filename '%s' as HTML\n", msg);
1838 snprintf(q, c->buffer_size,
1839 "HTTP/1.0 404 Not Found\r\n"
1840 "Content-type: text/html\r\n"
1845 "<meta charset=\"UTF-8\">\n"
1846 "<title>404 Not Found</title>\n"
1849 "</html>\n", encoded_msg? encoded_msg : "File not found");
1851 /* prepare output buffer */
1852 c->buffer_ptr = c->buffer;
1854 c->state = HTTPSTATE_SEND_HEADER;
1855 av_freep(&encoded_msg);
1859 /* horrible: we use this value to avoid
1860 * going to the send data state */
1861 c->http_error = 200;
1862 c->state = HTTPSTATE_SEND_HEADER;
1866 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1868 static const char suffix[] = " kMGTP";
1871 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1873 avio_printf(pb, "%"PRId64"%c", count, *s);
1876 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1879 const char *type = "unknown";
1880 char parameters[64];
1881 LayeredAVStream *st;
1884 stream_no = stream->nb_streams;
1886 avio_printf(pb, "<table><tr><th>Stream<th>"
1887 "type<th>kbit/s<th>codec<th>"
1890 for (i = 0; i < stream_no; i++) {
1891 st = stream->streams[i];
1892 codec = avcodec_find_encoder(st->codecpar->codec_id);
1896 switch(st->codecpar->codec_type) {
1897 case AVMEDIA_TYPE_AUDIO:
1899 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1900 st->codecpar->channels, st->codecpar->sample_rate);
1902 case AVMEDIA_TYPE_VIDEO:
1904 snprintf(parameters, sizeof(parameters),
1905 "%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
1906 st->codecpar->height, st->codec->qmin, st->codec->qmax,
1907 st->time_base.den / st->time_base.num);
1913 avio_printf(pb, "<tr><td>%d<td>%s<td>%"PRId64
1915 i, type, st->codecpar->bit_rate/1000,
1916 codec ? codec->name : "", parameters);
1919 avio_printf(pb, "</table>\n");
1922 static void clean_html(char *clean, int clean_len, char *dirty)
1926 for (o = i = 0; o+10 < clean_len && dirty[i];) {
1927 int len = strspn(dirty+i, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*(),?/ :;%");
1929 if (o + len >= clean_len)
1931 memcpy(clean + o, dirty + i, len);
1937 case '&': av_strlcat(clean+o, "&" , clean_len - o); break;
1938 case '<': av_strlcat(clean+o, "<" , clean_len - o); break;
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 default: av_strlcat(clean+o, "☹", clean_len - o); break;
1944 o += strlen(clean+o);
1950 static void compute_status(HTTPContext *c)
1953 FFServerStream *stream;
1959 if (avio_open_dyn_buf(&pb) < 0) {
1960 /* XXX: return an error ? */
1961 c->buffer_ptr = c->buffer;
1962 c->buffer_end = c->buffer;
1966 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1967 avio_printf(pb, "Content-type: text/html\r\n");
1968 avio_printf(pb, "Pragma: no-cache\r\n");
1969 avio_printf(pb, "\r\n");
1971 avio_printf(pb, "<!DOCTYPE html>\n");
1972 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1973 if (c->stream->feed_filename[0])
1974 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1975 c->stream->feed_filename);
1976 avio_printf(pb, "</head>\n<body>");
1977 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1979 avio_printf(pb, "<h2>Available Streams</h2>\n");
1980 avio_printf(pb, "<table>\n");
1981 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");
1982 stream = config.first_stream;
1984 char sfilename[1024];
1987 if (stream->feed == stream) {
1988 stream = stream->next;
1992 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1993 eosf = sfilename + strlen(sfilename);
1994 if (eosf - sfilename >= 4) {
1995 if (strcmp(eosf - 4, ".asf") == 0)
1996 strcpy(eosf - 4, ".asx");
1997 else if (strcmp(eosf - 3, ".rm") == 0)
1998 strcpy(eosf - 3, ".ram");
1999 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
2000 /* generate a sample RTSP director if
2001 * unicast. Generate an SDP redirector if
2003 eosf = strrchr(sfilename, '.');
2005 eosf = sfilename + strlen(sfilename);
2006 if (stream->is_multicast)
2007 strcpy(eosf, ".sdp");
2009 strcpy(eosf, ".rtsp");
2013 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
2014 sfilename, stream->filename);
2015 avio_printf(pb, "<td> %d <td> ",
2016 stream->conns_served);
2017 // TODO: Investigate if we can make http bitexact so it always produces the same count of bytes
2018 if (!config.bitexact)
2019 fmt_bytecount(pb, stream->bytes_served);
2021 switch(stream->stream_type) {
2022 case STREAM_TYPE_LIVE: {
2023 int audio_bit_rate = 0;
2024 int video_bit_rate = 0;
2025 const char *audio_codec_name = "";
2026 const char *video_codec_name = "";
2027 const char *audio_codec_name_extra = "";
2028 const char *video_codec_name_extra = "";
2030 for(i=0;i<stream->nb_streams;i++) {
2031 LayeredAVStream *st = stream->streams[i];
2032 AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id);
2034 switch(st->codecpar->codec_type) {
2035 case AVMEDIA_TYPE_AUDIO:
2036 audio_bit_rate += st->codecpar->bit_rate;
2038 if (*audio_codec_name)
2039 audio_codec_name_extra = "...";
2040 audio_codec_name = codec->name;
2043 case AVMEDIA_TYPE_VIDEO:
2044 video_bit_rate += st->codecpar->bit_rate;
2046 if (*video_codec_name)
2047 video_codec_name_extra = "...";
2048 video_codec_name = codec->name;
2051 case AVMEDIA_TYPE_DATA:
2052 video_bit_rate += st->codecpar->bit_rate;
2059 avio_printf(pb, "<td> %s <td> %d <td> %d <td> %s %s <td> "
2061 stream->fmt->name, stream->bandwidth,
2062 video_bit_rate / 1000, video_codec_name,
2063 video_codec_name_extra, audio_bit_rate / 1000,
2064 audio_codec_name, audio_codec_name_extra);
2067 avio_printf(pb, "<td>%s", stream->feed->filename);
2069 avio_printf(pb, "<td>%s", stream->feed_filename);
2070 avio_printf(pb, "\n");
2074 avio_printf(pb, "<td> - <td> - "
2075 "<td> - <td><td> - <td>\n");
2078 stream = stream->next;
2080 avio_printf(pb, "</table>\n");
2082 stream = config.first_stream;
2085 if (stream->feed != stream) {
2086 stream = stream->next;
2090 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
2092 avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
2099 /* This is somewhat linux specific I guess */
2100 snprintf(ps_cmd, sizeof(ps_cmd),
2101 "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
2102 (int64_t) stream->pid);
2104 pid_stat = popen(ps_cmd, "r");
2109 if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
2110 avio_printf(pb, "Currently using %s%% of the cpu. "
2111 "Total time used %s.\n",
2119 avio_printf(pb, "<p>");
2122 print_stream_params(pb, stream);
2123 stream = stream->next;
2126 /* connection status */
2127 avio_printf(pb, "<h2>Connection Status</h2>\n");
2129 avio_printf(pb, "Number of connections: %d / %d<br>\n",
2130 nb_connections, config.nb_max_connections);
2132 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2133 current_bandwidth, config.max_bandwidth);
2135 avio_printf(pb, "<table>\n");
2136 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>URL<th>Proto<th>State<th>Target "
2137 "bit/s<th>Actual bit/s<th>Bytes transferred\n");
2138 c1 = first_http_ctx;
2146 for (j = 0; j < c1->stream->nb_streams; j++) {
2147 if (!c1->stream->feed)
2148 bitrate += c1->stream->streams[j]->codecpar->bit_rate;
2149 else if (c1->feed_streams[j] >= 0)
2150 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate;
2155 p = inet_ntoa(c1->from_addr.sin_addr);
2156 clean_html(c1->clean_url, sizeof(c1->clean_url), c1->url);
2157 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td>%s"
2159 i, c1->stream ? c1->stream->filename : "",
2160 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
2163 c1->protocol, http_state[c1->state]);
2164 fmt_bytecount(pb, bitrate);
2165 avio_printf(pb, "<td>");
2166 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2167 avio_printf(pb, "<td>");
2168 fmt_bytecount(pb, c1->data_count);
2169 avio_printf(pb, "\n");
2172 avio_printf(pb, "</table>\n");
2174 if (!config.bitexact) {
2178 avio_printf(pb, "<hr>Generated at %s", p);
2180 avio_printf(pb, "</body>\n</html>\n");
2182 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2183 c->buffer_ptr = c->pb_buffer;
2184 c->buffer_end = c->pb_buffer + len;
2187 static int open_input_stream(HTTPContext *c, const char *info)
2190 char input_filename[1024];
2191 AVFormatContext *s = NULL;
2192 int buf_size, i, ret;
2195 /* find file name */
2196 if (c->stream->feed) {
2197 strcpy(input_filename, c->stream->feed->feed_filename);
2198 buf_size = FFM_PACKET_SIZE;
2199 /* compute position (absolute time) */
2200 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2201 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2202 http_log("Invalid date specification '%s' for stream\n", buf);
2205 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2206 int prebuffer = strtol(buf, 0, 10);
2207 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2209 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2211 strcpy(input_filename, c->stream->feed_filename);
2213 /* compute position (relative time) */
2214 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2215 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2216 http_log("Invalid date specification '%s' for stream\n", buf);
2222 if (!input_filename[0]) {
2223 http_log("No filename was specified for stream\n");
2224 return AVERROR(EINVAL);
2228 ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2229 &c->stream->in_opts);
2231 http_log("Could not open input '%s': %s\n",
2232 input_filename, av_err2str(ret));
2236 /* set buffer size */
2238 ret = ffio_set_buf_size(s->pb, buf_size);
2240 http_log("Failed to set buffer size\n");
2245 s->flags |= AVFMT_FLAG_GENPTS;
2247 if (strcmp(s->iformat->name, "ffm") &&
2248 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2249 http_log("Could not find stream info for input '%s'\n", input_filename);
2250 avformat_close_input(&s);
2254 /* choose stream as clock source (we favor the video stream if
2255 * present) for packet sending */
2256 c->pts_stream_index = 0;
2257 for(i=0;i<c->stream->nb_streams;i++) {
2258 if (c->pts_stream_index == 0 &&
2259 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2260 c->pts_stream_index = i;
2264 if (c->fmt_in->iformat->read_seek)
2265 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2266 /* set the start time (needed for maxtime and RTP packet timing) */
2267 c->start_time = cur_time;
2268 c->first_pts = AV_NOPTS_VALUE;
2272 /* return the server clock (in us) */
2273 static int64_t get_server_clock(HTTPContext *c)
2275 /* compute current pts value from system time */
2276 return (cur_time - c->start_time) * 1000;
2279 /* return the estimated time (in us) at which the current packet must be sent */
2280 static int64_t get_packet_send_clock(HTTPContext *c)
2282 int bytes_left, bytes_sent, frame_bytes;
2284 frame_bytes = c->cur_frame_bytes;
2285 if (frame_bytes <= 0)
2288 bytes_left = c->buffer_end - c->buffer_ptr;
2289 bytes_sent = frame_bytes - bytes_left;
2290 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2294 static int http_prepare_data(HTTPContext *c)
2297 AVFormatContext *ctx;
2299 av_freep(&c->pb_buffer);
2301 case HTTPSTATE_SEND_DATA_HEADER:
2302 ctx = avformat_alloc_context();
2304 return AVERROR(ENOMEM);
2306 av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0);
2308 for(i=0;i<c->stream->nb_streams;i++) {
2309 LayeredAVStream *src;
2310 AVStream *st = avformat_new_stream(c->pfmt_ctx, NULL);
2312 return AVERROR(ENOMEM);
2314 /* if file or feed, then just take streams from FFServerStream
2316 if (!c->stream->feed ||
2317 c->stream->feed == c->stream)
2318 src = c->stream->streams[i];
2320 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2322 unlayer_stream(c->pfmt_ctx->streams[i], src); //TODO we no longer copy st->internal, does this matter?
2323 av_assert0(!c->pfmt_ctx->streams[i]->priv_data);
2325 if (src->codec->flags & AV_CODEC_FLAG_BITEXACT)
2326 c->pfmt_ctx->flags |= AVFMT_FLAG_BITEXACT;
2328 /* set output format parameters */
2329 c->pfmt_ctx->oformat = c->stream->fmt;
2330 av_assert0(c->pfmt_ctx->nb_streams == c->stream->nb_streams);
2332 c->got_key_frame = 0;
2334 /* prepare header and save header data in a stream */
2335 if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) {
2336 /* XXX: potential leak */
2339 c->pfmt_ctx->pb->seekable = 0;
2342 * HACK to avoid MPEG-PS muxer to spit many underflow errors
2343 * Default value from FFmpeg
2344 * Try to set it using configuration option
2346 c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE);
2348 if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) {
2349 http_log("Error writing output header for stream '%s': %s\n",
2350 c->stream->filename, av_err2str(ret));
2353 av_dict_free(&c->pfmt_ctx->metadata);
2355 len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer);
2356 c->buffer_ptr = c->pb_buffer;
2357 c->buffer_end = c->pb_buffer + len;
2359 c->state = HTTPSTATE_SEND_DATA;
2360 c->last_packet_sent = 0;
2362 case HTTPSTATE_SEND_DATA:
2363 /* find a new packet */
2364 /* read a packet from the input stream */
2365 if (c->stream->feed)
2366 ffm_set_write_index(c->fmt_in,
2367 c->stream->feed->feed_write_index,
2368 c->stream->feed->feed_size);
2370 if (c->stream->max_time &&
2371 c->stream->max_time + c->start_time - cur_time < 0)
2372 /* We have timed out */
2373 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2377 ret = av_read_frame(c->fmt_in, &pkt);
2379 if (c->stream->feed) {
2380 /* if coming from feed, it means we reached the end of the
2381 * ffm file, so must wait for more data */
2382 c->state = HTTPSTATE_WAIT_FEED;
2383 return 1; /* state changed */
2385 if (ret == AVERROR(EAGAIN)) {
2386 /* input not ready, come back later */
2389 if (c->stream->loop) {
2390 avformat_close_input(&c->fmt_in);
2391 if (open_input_stream(c, "") < 0)
2396 /* must send trailer now because EOF or error */
2397 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2400 int source_index = pkt.stream_index;
2401 /* update first pts if needed */
2402 if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
2403 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2404 c->start_time = cur_time;
2406 /* send it to the appropriate stream */
2407 if (c->stream->feed) {
2408 /* if coming from a feed, select the right stream */
2409 if (c->switch_pending) {
2410 c->switch_pending = 0;
2411 for(i=0;i<c->stream->nb_streams;i++) {
2412 if (c->switch_feed_streams[i] == pkt.stream_index)
2413 if (pkt.flags & AV_PKT_FLAG_KEY)
2414 c->switch_feed_streams[i] = -1;
2415 if (c->switch_feed_streams[i] >= 0)
2416 c->switch_pending = 1;
2419 for(i=0;i<c->stream->nb_streams;i++) {
2420 if (c->stream->feed_streams[i] == pkt.stream_index) {
2421 AVStream *st = c->fmt_in->streams[source_index];
2422 pkt.stream_index = i;
2423 if (pkt.flags & AV_PKT_FLAG_KEY &&
2424 (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
2425 c->stream->nb_streams == 1))
2426 c->got_key_frame = 1;
2427 if (!c->stream->send_on_key || c->got_key_frame)
2432 AVStream *ist, *ost;
2434 ist = c->fmt_in->streams[source_index];
2435 /* specific handling for RTP: we use several
2436 * output streams (one for each RTP connection).
2437 * XXX: need more abstract handling */
2438 if (c->is_packetized) {
2439 /* compute send time and duration */
2440 if (pkt.dts != AV_NOPTS_VALUE) {
2441 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2442 c->cur_pts -= c->first_pts;
2444 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2445 /* find RTP context */
2446 c->packet_stream_index = pkt.stream_index;
2447 ctx = c->rtp_ctx[c->packet_stream_index];
2449 av_packet_unref(&pkt);
2452 /* only one stream per RTP connection */
2453 pkt.stream_index = 0;
2459 if (c->is_packetized) {
2460 int max_packet_size;
2461 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2462 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2464 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2465 ret = ffio_open_dyn_packet_buf(&ctx->pb,
2468 ret = avio_open_dyn_buf(&ctx->pb);
2471 /* XXX: potential leak */
2474 ost = ctx->streams[pkt.stream_index];
2476 ctx->pb->seekable = 0;
2477 if (pkt.dts != AV_NOPTS_VALUE)
2478 pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2480 if (pkt.pts != AV_NOPTS_VALUE)
2481 pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2483 pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2485 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2486 http_log("Error writing frame to output for stream '%s': %s\n",
2487 c->stream->filename, av_err2str(ret));
2488 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2491 av_freep(&c->pb_buffer);
2492 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2494 c->cur_frame_bytes = len;
2495 c->buffer_ptr = c->pb_buffer;
2496 c->buffer_end = c->pb_buffer + len;
2499 av_packet_unref(&pkt);
2503 av_packet_unref(&pkt);
2508 case HTTPSTATE_SEND_DATA_TRAILER:
2509 /* last packet test ? */
2510 if (c->last_packet_sent || c->is_packetized)
2513 /* prepare header */
2514 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2515 /* XXX: potential leak */
2518 c->pfmt_ctx->pb->seekable = 0;
2519 av_write_trailer(ctx);
2520 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2521 c->buffer_ptr = c->pb_buffer;
2522 c->buffer_end = c->pb_buffer + len;
2524 c->last_packet_sent = 1;
2530 /* should convert the format at the same time */
2531 /* send data starting at c->buffer_ptr to the output connection
2532 * (either UDP or TCP)
2534 static int http_send_data(HTTPContext *c)
2539 if (c->buffer_ptr >= c->buffer_end) {
2540 ret = http_prepare_data(c);
2544 /* state change requested */
2547 if (c->is_packetized) {
2548 /* RTP data output */
2549 len = c->buffer_end - c->buffer_ptr;
2551 /* fail safe - should never happen */
2553 c->buffer_ptr = c->buffer_end;
2556 len = (c->buffer_ptr[0] << 24) |
2557 (c->buffer_ptr[1] << 16) |
2558 (c->buffer_ptr[2] << 8) |
2560 if (len > (c->buffer_end - c->buffer_ptr))
2562 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2563 /* nothing to send yet: we can wait */
2567 c->data_count += len;
2568 update_datarate(&c->datarate, c->data_count);
2570 c->stream->bytes_served += len;
2572 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2573 /* RTP packets are sent inside the RTSP TCP connection */
2575 int interleaved_index, size;
2577 HTTPContext *rtsp_c;
2580 /* if no RTSP connection left, error */
2583 /* if already sending something, then wait. */
2584 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2586 if (avio_open_dyn_buf(&pb) < 0)
2588 interleaved_index = c->packet_stream_index * 2;
2589 /* RTCP packets are sent at odd indexes */
2590 if (c->buffer_ptr[1] == 200)
2591 interleaved_index++;
2592 /* write RTSP TCP header */
2594 header[1] = interleaved_index;
2595 header[2] = len >> 8;
2597 avio_write(pb, header, 4);
2598 /* write RTP packet data */
2600 avio_write(pb, c->buffer_ptr, len);
2601 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2602 /* prepare asynchronous TCP sending */
2603 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2604 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2605 c->buffer_ptr += len;
2607 /* send everything we can NOW */
2608 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2609 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2611 rtsp_c->packet_buffer_ptr += len;
2612 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2613 /* if we could not send all the data, we will
2614 * send it later, so a new state is needed to
2615 * "lock" the RTSP TCP connection */
2616 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2619 /* all data has been sent */
2620 av_freep(&c->packet_buffer);
2622 /* send RTP packet directly in UDP */
2624 ffurl_write(c->rtp_handles[c->packet_stream_index],
2625 c->buffer_ptr, len);
2626 c->buffer_ptr += len;
2627 /* here we continue as we can send several packets
2631 /* TCP data output */
2632 len = send(c->fd, c->buffer_ptr,
2633 c->buffer_end - c->buffer_ptr, 0);
2635 if (ff_neterrno() != AVERROR(EAGAIN) &&
2636 ff_neterrno() != AVERROR(EINTR))
2637 /* error : close connection */
2642 c->buffer_ptr += len;
2644 c->data_count += len;
2645 update_datarate(&c->datarate, c->data_count);
2647 c->stream->bytes_served += len;
2655 static int http_start_receive_data(HTTPContext *c)
2661 if (c->stream->feed_opened) {
2662 http_log("Stream feed '%s' was not opened\n",
2663 c->stream->feed_filename);
2664 return AVERROR(EINVAL);
2667 /* Don't permit writing to this one */
2668 if (c->stream->readonly) {
2669 http_log("Cannot write to read-only file '%s'\n",
2670 c->stream->feed_filename);
2671 return AVERROR(EINVAL);
2675 fd = open(c->stream->feed_filename, O_RDWR);
2677 ret = AVERROR(errno);
2678 http_log("Could not open feed file '%s': %s\n",
2679 c->stream->feed_filename, strerror(errno));
2684 if (c->stream->truncate) {
2685 /* truncate feed file */
2686 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2687 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2688 if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2689 ret = AVERROR(errno);
2690 http_log("Error truncating feed file '%s': %s\n",
2691 c->stream->feed_filename, strerror(errno));
2695 ret64 = ffm_read_write_index(fd);
2697 http_log("Error reading write index from feed file '%s': %s\n",
2698 c->stream->feed_filename, strerror(errno));
2701 c->stream->feed_write_index = ret64;
2704 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2706 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2707 lseek(fd, 0, SEEK_SET);
2709 /* init buffer input */
2710 c->buffer_ptr = c->buffer;
2711 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2712 c->stream->feed_opened = 1;
2713 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2717 static int http_receive_data(HTTPContext *c)
2720 int len, loop_run = 0;
2722 while (c->chunked_encoding && !c->chunk_size &&
2723 c->buffer_end > c->buffer_ptr) {
2724 /* read chunk header, if present */
2725 len = recv(c->fd, c->buffer_ptr, 1, 0);
2728 if (ff_neterrno() != AVERROR(EAGAIN) &&
2729 ff_neterrno() != AVERROR(EINTR))
2730 /* error : close connection */
2733 } else if (len == 0) {
2734 /* end of connection : close it */
2736 } else if (c->buffer_ptr - c->buffer >= 2 &&
2737 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2738 c->chunk_size = strtol(c->buffer, 0, 16);
2739 if (c->chunk_size <= 0) { // end of stream or invalid chunk size
2743 c->buffer_ptr = c->buffer;
2745 } else if (++loop_run > 10)
2746 /* no chunk header, abort */
2752 if (c->buffer_end > c->buffer_ptr) {
2753 len = recv(c->fd, c->buffer_ptr,
2754 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2756 if (ff_neterrno() != AVERROR(EAGAIN) &&
2757 ff_neterrno() != AVERROR(EINTR))
2758 /* error : close connection */
2760 } else if (len == 0)
2761 /* end of connection : close it */
2764 av_assert0(len <= c->chunk_size);
2765 c->chunk_size -= len;
2766 c->buffer_ptr += len;
2767 c->data_count += len;
2768 update_datarate(&c->datarate, c->data_count);
2772 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2773 if (c->buffer[0] != 'f' ||
2774 c->buffer[1] != 'm') {
2775 http_log("Feed stream has become desynchronized -- disconnecting\n");
2780 if (c->buffer_ptr >= c->buffer_end) {
2781 FFServerStream *feed = c->stream;
2782 /* a packet has been received : write it in the store, except
2784 if (c->data_count > FFM_PACKET_SIZE) {
2785 /* XXX: use llseek or url_seek
2786 * XXX: Should probably fail? */
2787 if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2788 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2790 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2791 http_log("Error writing to feed file: %s\n", strerror(errno));
2795 feed->feed_write_index += FFM_PACKET_SIZE;
2796 /* update file size */
2797 if (feed->feed_write_index > c->stream->feed_size)
2798 feed->feed_size = feed->feed_write_index;
2800 /* handle wrap around if max file size reached */
2801 if (c->stream->feed_max_size &&
2802 feed->feed_write_index >= c->stream->feed_max_size)
2803 feed->feed_write_index = FFM_PACKET_SIZE;
2806 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2807 http_log("Error writing index to feed file: %s\n",
2812 /* wake up any waiting connections */
2813 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2814 if (c1->state == HTTPSTATE_WAIT_FEED &&
2815 c1->stream->feed == c->stream->feed)
2816 c1->state = HTTPSTATE_SEND_DATA;
2819 /* We have a header in our hands that contains useful data */
2820 AVFormatContext *s = avformat_alloc_context();
2822 AVInputFormat *fmt_in;
2828 /* use feed output format name to find corresponding input format */
2829 fmt_in = av_find_input_format(feed->fmt->name);
2833 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2834 0, NULL, NULL, NULL, NULL);
2841 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2846 /* Now we have the actual streams */
2847 if (s->nb_streams != feed->nb_streams) {
2848 avformat_close_input(&s);
2850 http_log("Feed '%s' stream number does not match registered feed\n",
2851 c->stream->feed_filename);
2855 for (i = 0; i < s->nb_streams; i++) {
2856 LayeredAVStream *fst = feed->streams[i];
2857 AVStream *st = s->streams[i];
2858 avcodec_parameters_to_context(fst->codec, st->codecpar);
2859 avcodec_parameters_from_context(fst->codecpar, fst->codec);
2862 avformat_close_input(&s);
2865 c->buffer_ptr = c->buffer;
2870 c->stream->feed_opened = 0;
2872 /* wake up any waiting connections to stop waiting for feed */
2873 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2874 if (c1->state == HTTPSTATE_WAIT_FEED &&
2875 c1->stream->feed == c->stream->feed)
2876 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2881 /********************************************************************/
2884 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2891 str = RTSP_STATUS_CODE2STRING(error_number);
2893 str = "Unknown Error";
2895 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2896 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2898 /* output GMT time */
2901 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2902 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2905 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2907 rtsp_reply_header(c, error_number);
2908 avio_printf(c->pb, "\r\n");
2911 static int rtsp_parse_request(HTTPContext *c)
2913 const char *p, *p1, *p2;
2919 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2921 c->buffer_ptr[0] = '\0';
2924 get_word(cmd, sizeof(cmd), &p);
2925 get_word(url, sizeof(url), &p);
2926 get_word(protocol, sizeof(protocol), &p);
2928 av_strlcpy(c->method, cmd, sizeof(c->method));
2929 av_strlcpy(c->url, url, sizeof(c->url));
2930 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2932 if (avio_open_dyn_buf(&c->pb) < 0) {
2933 /* XXX: cannot do more */
2934 c->pb = NULL; /* safety */
2938 /* check version name */
2939 if (strcmp(protocol, "RTSP/1.0")) {
2940 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2944 /* parse each header line */
2945 /* skip to next line */
2946 while (*p != '\n' && *p != '\0')
2950 while (*p != '\0') {
2951 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2955 if (p2 > p && p2[-1] == '\r')
2957 /* skip empty line */
2961 if (len > sizeof(line) - 1)
2962 len = sizeof(line) - 1;
2963 memcpy(line, p, len);
2965 ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
2969 /* handle sequence number */
2970 c->seq = header->seq;
2972 if (!strcmp(cmd, "DESCRIBE"))
2973 rtsp_cmd_describe(c, url);
2974 else if (!strcmp(cmd, "OPTIONS"))
2975 rtsp_cmd_options(c, url);
2976 else if (!strcmp(cmd, "SETUP"))
2977 rtsp_cmd_setup(c, url, header);
2978 else if (!strcmp(cmd, "PLAY"))
2979 rtsp_cmd_play(c, url, header);
2980 else if (!strcmp(cmd, "PAUSE"))
2981 rtsp_cmd_interrupt(c, url, header, 1);
2982 else if (!strcmp(cmd, "TEARDOWN"))
2983 rtsp_cmd_interrupt(c, url, header, 0);
2985 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2988 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2989 c->pb = NULL; /* safety */
2991 /* XXX: cannot do more */
2994 c->buffer_ptr = c->pb_buffer;
2995 c->buffer_end = c->pb_buffer + len;
2996 c->state = RTSPSTATE_SEND_REPLY;
3000 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
3001 struct in_addr my_ip)
3003 AVFormatContext *avc;
3004 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
3005 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
3010 avc = avformat_alloc_context();
3011 if (!avc || !rtp_format)
3014 avc->oformat = rtp_format;
3015 av_dict_set(&avc->metadata, "title",
3016 entry ? entry->value : "No Title", 0);
3017 if (stream->is_multicast) {
3018 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
3019 inet_ntoa(stream->multicast_ip),
3020 stream->multicast_port, stream->multicast_ttl);
3022 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
3024 for(i = 0; i < stream->nb_streams; i++) {
3025 AVStream *st = avformat_new_stream(avc, NULL);
3028 avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
3029 unlayer_stream(st, stream->streams[i]);
3031 #define PBUFFER_SIZE 2048
3032 *pbuffer = av_mallocz(PBUFFER_SIZE);
3035 av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
3038 av_freep(&avc->streams);
3039 av_dict_free(&avc->metadata);
3042 return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
3045 static void rtsp_cmd_options(HTTPContext *c, const char *url)
3047 /* rtsp_reply_header(c, RTSP_STATUS_OK); */
3048 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
3049 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
3050 avio_printf(c->pb, "Public: %s\r\n",
3051 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
3052 avio_printf(c->pb, "\r\n");
3055 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
3057 FFServerStream *stream;
3063 struct sockaddr_in my_addr;
3065 /* find which URL is asked */
3066 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3071 for(stream = config.first_stream; stream; stream = stream->next) {
3072 if (!stream->is_feed &&
3073 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
3074 !strcmp(path, stream->filename)) {
3078 /* no stream found */
3079 rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
3083 /* prepare the media description in SDP format */
3085 /* get the host IP */
3086 len = sizeof(my_addr);
3087 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3088 content_length = prepare_sdp_description(stream, &content,
3090 if (content_length < 0) {
3091 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3094 rtsp_reply_header(c, RTSP_STATUS_OK);
3095 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
3096 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
3097 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
3098 avio_printf(c->pb, "\r\n");
3099 avio_write(c->pb, content, content_length);
3103 static HTTPContext *find_rtp_session(const char *session_id)
3107 if (session_id[0] == '\0')
3110 for(c = first_http_ctx; c; c = c->next) {
3111 if (!strcmp(c->session_id, session_id))
3117 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3119 RTSPTransportField *th;
3122 for(i=0;i<h->nb_transports;i++) {
3123 th = &h->transports[i];
3124 if (th->lower_transport == lower_transport)
3130 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3131 RTSPMessageHeader *h)
3133 FFServerStream *stream;
3134 int stream_index, rtp_port, rtcp_port;
3139 RTSPTransportField *th;
3140 struct sockaddr_in dest_addr;
3141 RTSPActionServerSetup setup;
3143 /* find which URL is asked */
3144 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3149 /* now check each stream */
3150 for(stream = config.first_stream; stream; stream = stream->next) {
3151 if (stream->is_feed || !stream->fmt ||
3152 strcmp(stream->fmt->name, "rtp")) {
3155 /* accept aggregate filenames only if single stream */
3156 if (!strcmp(path, stream->filename)) {
3157 if (stream->nb_streams != 1) {
3158 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3165 for(stream_index = 0; stream_index < stream->nb_streams;
3167 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3168 stream->filename, stream_index);
3169 if (!strcmp(path, buf))
3173 /* no stream found */
3174 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3178 /* generate session id if needed */
3179 if (h->session_id[0] == '\0') {
3180 unsigned random0 = av_lfg_get(&random_state);
3181 unsigned random1 = av_lfg_get(&random_state);
3182 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3186 /* find RTP session, and create it if none found */
3187 rtp_c = find_rtp_session(h->session_id);
3189 /* always prefer UDP */
3190 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3192 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3194 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3199 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3200 th->lower_transport);
3202 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3206 /* open input stream */
3207 if (open_input_stream(rtp_c, "") < 0) {
3208 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3213 /* test if stream is OK (test needed because several SETUP needs
3214 * to be done for a given file) */
3215 if (rtp_c->stream != stream) {
3216 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3220 /* test if stream is already set up */
3221 if (rtp_c->rtp_ctx[stream_index]) {
3222 rtsp_reply_error(c, RTSP_STATUS_STATE);
3226 /* check transport */
3227 th = find_transport(h, rtp_c->rtp_protocol);
3228 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3229 th->client_port_min <= 0)) {
3230 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3234 /* setup default options */
3235 setup.transport_option[0] = '\0';
3236 dest_addr = rtp_c->from_addr;
3237 dest_addr.sin_port = htons(th->client_port_min);
3240 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3241 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3245 /* now everything is OK, so we can send the connection parameters */
3246 rtsp_reply_header(c, RTSP_STATUS_OK);
3248 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3250 switch(rtp_c->rtp_protocol) {
3251 case RTSP_LOWER_TRANSPORT_UDP:
3252 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3253 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3254 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3255 "client_port=%d-%d;server_port=%d-%d",
3256 th->client_port_min, th->client_port_max,
3257 rtp_port, rtcp_port);
3259 case RTSP_LOWER_TRANSPORT_TCP:
3260 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3261 stream_index * 2, stream_index * 2 + 1);
3266 if (setup.transport_option[0] != '\0')
3267 avio_printf(c->pb, ";%s", setup.transport_option);
3268 avio_printf(c->pb, "\r\n");
3271 avio_printf(c->pb, "\r\n");
3276 * find an RTP connection by using the session ID. Check consistency
3279 static HTTPContext *find_rtp_session_with_url(const char *url,
3280 const char *session_id)
3288 rtp_c = find_rtp_session(session_id);
3292 /* find which URL is asked */
3293 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3297 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3298 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3299 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3300 rtp_c->stream->filename, s);
3301 if(!strncmp(path, buf, sizeof(buf)))
3302 /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3303 * if nb_streams>1? */
3307 if (len > 0 && path[len - 1] == '/' &&
3308 !strncmp(path, rtp_c->stream->filename, len - 1))
3313 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3317 rtp_c = find_rtp_session_with_url(url, h->session_id);
3319 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3323 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3324 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3325 rtp_c->state != HTTPSTATE_READY) {
3326 rtsp_reply_error(c, RTSP_STATUS_STATE);
3330 rtp_c->state = HTTPSTATE_SEND_DATA;
3332 /* now everything is OK, so we can send the connection parameters */
3333 rtsp_reply_header(c, RTSP_STATUS_OK);
3335 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3336 avio_printf(c->pb, "\r\n");
3339 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3340 RTSPMessageHeader *h, int pause_only)
3344 rtp_c = find_rtp_session_with_url(url, h->session_id);
3346 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3351 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3352 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3353 rtsp_reply_error(c, RTSP_STATUS_STATE);
3356 rtp_c->state = HTTPSTATE_READY;
3357 rtp_c->first_pts = AV_NOPTS_VALUE;
3360 /* now everything is OK, so we can send the connection parameters */
3361 rtsp_reply_header(c, RTSP_STATUS_OK);
3363 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3364 avio_printf(c->pb, "\r\n");
3367 close_connection(rtp_c);
3370 /********************************************************************/
3373 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3374 FFServerStream *stream,
3375 const char *session_id,
3376 enum RTSPLowerTransport rtp_protocol)
3378 HTTPContext *c = NULL;
3379 const char *proto_str;
3381 /* XXX: should output a warning page when coming
3382 * close to the connection limit */
3383 if (nb_connections >= config.nb_max_connections)
3386 /* add a new connection */
3387 c = av_mallocz(sizeof(HTTPContext));
3392 c->poll_entry = NULL;
3393 c->from_addr = *from_addr;
3394 c->buffer_size = IOBUFFER_INIT_SIZE;
3395 c->buffer = av_malloc(c->buffer_size);
3400 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3401 c->state = HTTPSTATE_READY;
3402 c->is_packetized = 1;
3403 c->rtp_protocol = rtp_protocol;
3405 /* protocol is shown in statistics */
3406 switch(c->rtp_protocol) {
3407 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3408 proto_str = "MCAST";
3410 case RTSP_LOWER_TRANSPORT_UDP:
3413 case RTSP_LOWER_TRANSPORT_TCP:
3420 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3421 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3423 current_bandwidth += stream->bandwidth;
3425 c->next = first_http_ctx;
3431 av_freep(&c->buffer);
3438 * add a new RTP stream in an RTP connection (used in RTSP SETUP
3439 * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3442 static int rtp_new_av_stream(HTTPContext *c,
3443 int stream_index, struct sockaddr_in *dest_addr,
3444 HTTPContext *rtsp_c)
3446 AVFormatContext *ctx;
3449 URLContext *h = NULL;
3451 int max_packet_size;
3454 /* now we can open the relevant output stream */
3455 ctx = avformat_alloc_context();
3458 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3460 st = avformat_new_stream(ctx, NULL);
3464 st_internal = st->internal;
3466 if (!c->stream->feed ||
3467 c->stream->feed == c->stream)
3468 unlayer_stream(st, c->stream->streams[stream_index]);
3471 c->stream->feed->streams[c->stream->feed_streams[stream_index]]);
3472 av_assert0(st->priv_data == NULL);
3473 av_assert0(st->internal == st_internal);
3475 /* build destination RTP address */
3476 ipaddr = inet_ntoa(dest_addr->sin_addr);
3478 switch(c->rtp_protocol) {
3479 case RTSP_LOWER_TRANSPORT_UDP:
3480 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3483 /* XXX: also pass as parameter to function ? */
3484 if (c->stream->is_multicast) {
3486 ttl = c->stream->multicast_ttl;
3489 snprintf(ctx->filename, sizeof(ctx->filename),
3490 "rtp://%s:%d?multicast=1&ttl=%d",
3491 ipaddr, ntohs(dest_addr->sin_port), ttl);
3493 snprintf(ctx->filename, sizeof(ctx->filename),
3494 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3497 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3499 c->rtp_handles[stream_index] = h;
3500 max_packet_size = h->max_packet_size;
3502 case RTSP_LOWER_TRANSPORT_TCP:
3505 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3511 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3512 ipaddr, ntohs(dest_addr->sin_port),
3513 c->stream->filename, stream_index, c->protocol);
3515 /* normally, no packets should be output here, but the packet size may
3517 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3518 /* XXX: close stream */
3521 if (avformat_write_header(ctx, NULL) < 0) {
3529 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3533 c->rtp_ctx[stream_index] = ctx;
3537 /********************************************************************/
3538 /* ffserver initialization */
3540 /* FIXME: This code should use avformat_new_stream() */
3541 static LayeredAVStream *add_av_stream1(FFServerStream *stream,
3542 AVCodecContext *codec, int copy)
3544 LayeredAVStream *fst;
3546 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3549 fst = av_mallocz(sizeof(*fst));
3553 fst->codec = avcodec_alloc_context3(codec->codec);
3558 avcodec_copy_context(fst->codec, codec);
3560 /* live streams must use the actual feed's codec since it may be
3561 * updated later to carry extradata needed by them.
3565 //NOTE we previously allocated internal & internal->avctx, these seemed uneeded though
3566 fst->codecpar = avcodec_parameters_alloc();
3567 fst->index = stream->nb_streams;
3568 fst->time_base = codec->time_base;
3569 fst->pts_wrap_bits = 33;
3570 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3571 stream->streams[stream->nb_streams++] = fst;
3575 /* return the stream number in the feed */
3576 static int add_av_stream(FFServerStream *feed, LayeredAVStream *st)
3578 LayeredAVStream *fst;
3579 AVCodecContext *av, *av1;
3583 for(i=0;i<feed->nb_streams;i++) {
3584 av1 = feed->streams[i]->codec;
3585 if (av1->codec_id == av->codec_id &&
3586 av1->codec_type == av->codec_type &&
3587 av1->bit_rate == av->bit_rate) {
3589 switch(av->codec_type) {
3590 case AVMEDIA_TYPE_AUDIO:
3591 if (av1->channels == av->channels &&
3592 av1->sample_rate == av->sample_rate)
3595 case AVMEDIA_TYPE_VIDEO:
3596 if (av1->width == av->width &&
3597 av1->height == av->height &&
3598 av1->time_base.den == av->time_base.den &&
3599 av1->time_base.num == av->time_base.num &&
3600 av1->gop_size == av->gop_size)
3609 fst = add_av_stream1(feed, av, 0);
3612 if (st->recommended_encoder_configuration)
3613 fst->recommended_encoder_configuration =
3614 av_strdup(st->recommended_encoder_configuration);
3615 return feed->nb_streams - 1;
3618 static void remove_stream(FFServerStream *stream)
3620 FFServerStream **ps;
3621 ps = &config.first_stream;
3630 /* compute the needed AVStream for each file */
3631 static void build_file_streams(void)
3633 FFServerStream *stream;
3634 AVFormatContext *infile;
3637 /* gather all streams */
3638 for(stream = config.first_stream; stream; stream = stream->next) {
3641 if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
3644 /* the stream comes from a file */
3645 /* try to open the file */
3649 /* specific case: if transport stream output to RTP,
3650 * we use a raw transport stream reader */
3651 if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
3652 av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3654 if (!stream->feed_filename[0]) {
3655 http_log("Unspecified feed file for stream '%s'\n",
3660 http_log("Opening feed file '%s' for stream '%s'\n",
3661 stream->feed_filename, stream->filename);
3663 ret = avformat_open_input(&infile, stream->feed_filename,
3664 stream->ifmt, &stream->in_opts);
3666 http_log("Could not open '%s': %s\n", stream->feed_filename,
3668 /* remove stream (no need to spend more time on it) */
3670 remove_stream(stream);
3672 /* find all the AVStreams inside and reference them in
3674 if (avformat_find_stream_info(infile, NULL) < 0) {
3675 http_log("Could not find codec parameters from '%s'\n",
3676 stream->feed_filename);
3677 avformat_close_input(&infile);
3681 for(i=0;i<infile->nb_streams;i++)
3682 add_av_stream1(stream, infile->streams[i]->codec, 1);
3684 avformat_close_input(&infile);
3690 int check_codec_match(LayeredAVStream *ccf, AVStream *ccs, int stream)
3694 /* FIXME: Missed check on AVCodecContext.flags */
3695 #define CHECK_CODEC(x) (ccf->codecpar->x != ccs->codecpar->x)
3696 if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3697 http_log("Codecs do not match for stream %d\n", stream);
3699 } else if (CHECK_CODEC(bit_rate)) {
3700 http_log("Codec bitrates do not match for stream %d\n", stream);
3702 } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3703 if (av_cmp_q(ccf->time_base, ccs->time_base) ||
3704 CHECK_CODEC(width) || CHECK_CODEC(height)) {
3705 http_log("Codec width, height or framerate do not match for stream %d\n", stream);
3708 } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3709 if (CHECK_CODEC(sample_rate) ||
3710 CHECK_CODEC(channels) ||
3711 CHECK_CODEC(frame_size)) {
3712 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
3716 http_log("Unknown codec type for stream %d\n", stream);
3723 /* compute the needed AVStream for each feed */
3724 static int build_feed_streams(void)
3726 FFServerStream *stream, *feed;
3729 /* gather all streams */
3730 for(stream = config.first_stream; stream; stream = stream->next) {
3731 feed = stream->feed;
3735 if (stream->is_feed) {
3736 for(i=0;i<stream->nb_streams;i++)
3737 stream->feed_streams[i] = i;
3740 /* we handle a stream coming from a feed */
3741 for(i=0;i<stream->nb_streams;i++)
3742 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3745 /* create feed files if needed */
3746 for(feed = config.first_feed; feed; feed = feed->next_feed) {
3748 if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
3749 AVFormatContext *s = NULL;
3752 /* See if it matches */
3754 if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
3755 http_log("Deleting feed file '%s' as it appears "
3757 feed->feed_filename);
3761 /* set buffer size */
3762 if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
3763 http_log("Failed to set buffer size\n");
3764 avformat_close_input(&s);
3768 /* Now see if it matches */
3769 if (s->nb_streams != feed->nb_streams) {
3770 http_log("Deleting feed file '%s' as stream counts "
3771 "differ (%d != %d)\n",
3772 feed->feed_filename, s->nb_streams, feed->nb_streams);
3777 for(i=0;i<s->nb_streams;i++) {
3779 LayeredAVStream *sf;
3781 sf = feed->streams[i];
3784 if (sf->index != ss->index || sf->id != ss->id) {
3785 http_log("Index & Id do not match for stream %d (%s)\n",
3786 i, feed->feed_filename);
3791 matches = check_codec_match (sf, ss, i);
3798 avformat_close_input(&s);
3801 if (feed->readonly) {
3802 http_log("Unable to delete read-only feed file '%s'\n",
3803 feed->feed_filename);
3806 unlink(feed->feed_filename);
3810 if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
3811 AVFormatContext *s = avformat_alloc_context();
3814 http_log("Failed to allocate context\n");
3818 if (feed->readonly) {
3819 http_log("Unable to create feed file '%s' as it is "
3820 "marked readonly\n",
3821 feed->feed_filename);
3822 avformat_free_context(s);
3826 /* only write the header of the ffm file */
3827 if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
3828 http_log("Could not open output feed file '%s'\n",
3829 feed->feed_filename);
3830 avformat_free_context(s);
3833 s->oformat = feed->fmt;
3834 for (i = 0; i<feed->nb_streams; i++) {
3835 AVStream *st = avformat_new_stream(s, NULL); // FIXME free this
3837 http_log("Failed to allocate stream\n");
3840 unlayer_stream(st, feed->streams[i]);
3842 if (avformat_write_header(s, NULL) < 0) {
3843 http_log("Container doesn't support the required parameters\n");
3844 avio_closep(&s->pb);
3847 avformat_free_context(s);
3850 /* XXX: need better API */
3851 av_freep(&s->priv_data);
3852 avio_closep(&s->pb);
3855 avformat_free_context(s);
3858 /* get feed size and write index */
3859 fd = open(feed->feed_filename, O_RDONLY);
3861 http_log("Could not open output feed file '%s'\n",
3862 feed->feed_filename);
3866 feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
3868 feed->feed_size = lseek(fd, 0, SEEK_END);
3869 /* ensure that we do not wrap before the end of file */
3870 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3871 feed->feed_max_size = feed->feed_size;
3881 /* compute the bandwidth used by each stream */
3882 static void compute_bandwidth(void)
3886 FFServerStream *stream;
3888 for(stream = config.first_stream; stream; stream = stream->next) {
3890 for(i=0;i<stream->nb_streams;i++) {
3891 LayeredAVStream *st = stream->streams[i];
3892 switch(st->codec->codec_type) {
3893 case AVMEDIA_TYPE_AUDIO:
3894 case AVMEDIA_TYPE_VIDEO:
3895 bandwidth += st->codec->bit_rate;
3901 stream->bandwidth = (bandwidth + 999) / 1000;
3905 static void handle_child_exit(int sig)
3911 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3912 FFServerStream *feed;
3914 for (feed = config.first_feed; feed; feed = feed->next) {
3915 if (feed->pid != pid)
3918 uptime = time(0) - feed->pid_start;
3921 "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
3923 feed->filename, (int64_t) pid, status, (int64_t)uptime);
3926 /* Turn off any more restarts */
3927 ffserver_free_child_args(&feed->child_argv);
3931 need_to_start_children = 1;
3934 static void opt_debug(void)
3937 snprintf(config.logfilename, sizeof(config.logfilename), "-");
3940 void show_help_default(const char *opt, const char *arg)
3942 printf("usage: ffserver [options]\n"
3943 "Hyper fast multi format Audio/Video streaming server\n");
3945 show_help_options(options, "Main options:", 0, 0, 0);
3948 static const OptionDef options[] = {
3949 CMDUTILS_COMMON_OPTIONS
3950 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
3951 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
3952 { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
3956 int main(int argc, char **argv)
3958 struct sigaction sigact = { { 0 } };
3960 int ret = EXIT_FAILURE;
3964 config.filename = av_strdup("/etc/ffserver.conf");
3966 parse_loglevel(argc, argv, options);
3968 avformat_network_init();
3970 show_banner(argc, argv, options);
3972 my_program_name = argv[0];
3974 parse_options(NULL, argc, argv, options, NULL);
3976 unsetenv("http_proxy"); /* Kill the http_proxy */
3978 av_lfg_init(&random_state, av_get_random_seed());
3980 sigact.sa_handler = handle_child_exit;
3981 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
3982 sigaction(SIGCHLD, &sigact, 0);
3984 if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
3985 fprintf(stderr, "Error reading configuration file '%s': %s\n",
3986 config.filename, av_err2str(cfg_parsed));
3990 /* open log file if needed */
3991 if (config.logfilename[0] != '\0') {
3992 if (!strcmp(config.logfilename, "-"))
3995 logfile = fopen(config.logfilename, "a");
3996 av_log_set_callback(http_av_log);
3999 build_file_streams();
4001 if (build_feed_streams() < 0) {
4002 http_log("Could not setup feed streams\n");
4006 compute_bandwidth();
4009 signal(SIGPIPE, SIG_IGN);
4011 if (http_server() < 0) {
4012 http_log("Could not start server\n");
4019 av_freep (&config.filename);
4020 avformat_network_deinit();