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;
169 int is_packetized; /* if true, the stream is packetized */
170 int packet_stream_index; /* current stream for output in state machine */
172 /* RTSP state specific */
173 uint8_t *pb_buffer; /* XXX: use that in all the code */
175 int seq; /* RTSP sequence number */
177 /* RTP state specific */
178 enum RTSPLowerTransport rtp_protocol;
179 char session_id[32]; /* session id */
180 AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
182 /* RTP/UDP specific */
183 URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
185 /* RTP/TCP specific */
186 struct HTTPContext *rtsp_c;
187 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
190 typedef struct FeedData {
191 long long data_count;
192 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
195 static HTTPContext *first_http_ctx;
197 static FFServerConfig config = {
198 .nb_max_http_connections = 2000,
199 .nb_max_connections = 5,
200 .max_bandwidth = 1000,
204 static void new_connection(int server_fd, int is_rtsp);
205 static void close_connection(HTTPContext *c);
208 static int handle_connection(HTTPContext *c);
209 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
210 static void compute_status(HTTPContext *c);
211 static int open_input_stream(HTTPContext *c, const char *info);
212 static int http_parse_request(HTTPContext *c);
213 static int http_send_data(HTTPContext *c);
214 static int http_start_receive_data(HTTPContext *c);
215 static int http_receive_data(HTTPContext *c);
218 static int rtsp_parse_request(HTTPContext *c);
219 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
220 static void rtsp_cmd_options(HTTPContext *c, const char *url);
221 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
222 RTSPMessageHeader *h);
223 static void rtsp_cmd_play(HTTPContext *c, const char *url,
224 RTSPMessageHeader *h);
225 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
226 RTSPMessageHeader *h, int pause_only);
229 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
230 struct in_addr my_ip);
233 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
234 FFServerStream *stream,
235 const char *session_id,
236 enum RTSPLowerTransport rtp_protocol);
237 static int rtp_new_av_stream(HTTPContext *c,
238 int stream_index, struct sockaddr_in *dest_addr,
239 HTTPContext *rtsp_c);
241 static size_t htmlencode (const char *src, char **dest);
242 static inline void cp_html_entity (char *buffer, const char *entity);
243 static inline int check_codec_match(AVStream *ccf, AVStream *ccs, int stream);
245 static const char *my_program_name;
247 static int no_launch;
248 static int need_to_start_children;
250 /* maximum number of simultaneous HTTP connections */
251 static unsigned int nb_connections;
253 static uint64_t current_bandwidth;
255 /* Making this global saves on passing it around everywhere */
256 static int64_t cur_time;
258 static AVLFG random_state;
260 static FILE *logfile = NULL;
262 static inline void cp_html_entity (char *buffer, const char *entity) {
263 if (!buffer || !entity)
266 *buffer++ = *entity++;
270 * Substitutes known conflicting chars on a text string with
271 * their corresponding HTML entities.
273 * Returns the number of bytes in the 'encoded' representation
274 * not including the terminating NUL.
276 static size_t htmlencode (const char *src, char **dest) {
277 const char *amp = "&";
278 const char *lt = "<";
279 const char *gt = ">";
282 size_t final_size = 0;
289 /* Compute needed dest size */
290 while (*src != '\0') {
306 *dest = av_mallocz(final_size + 1);
312 while (*src != '\0') {
315 cp_html_entity (tmp, amp);
319 cp_html_entity (tmp, lt);
323 cp_html_entity (tmp, gt);
337 static int64_t ffm_read_write_index(int fd)
341 if (lseek(fd, 8, SEEK_SET) < 0)
343 if (read(fd, buf, 8) != 8)
348 static int ffm_write_write_index(int fd, int64_t pos)
354 buf[i] = (pos >> (56 - i * 8)) & 0xff;
355 if (lseek(fd, 8, SEEK_SET) < 0)
357 if (write(fd, buf, 8) != 8)
366 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
369 av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
370 av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
371 av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
374 static char *ctime1(char *buf2, size_t buf_size)
385 av_strlcpy(buf2, p, buf_size);
386 p = buf2 + strlen(buf2) - 1;
392 static void http_vlog(const char *fmt, va_list vargs)
394 static int print_prefix = 1;
401 ctime1(buf, sizeof(buf));
402 fprintf(logfile, "%s ", buf);
404 print_prefix = strstr(fmt, "\n") != NULL;
405 vfprintf(logfile, fmt, vargs);
410 __attribute__ ((format (printf, 1, 2)))
412 static void http_log(const char *fmt, ...)
415 va_start(vargs, fmt);
416 http_vlog(fmt, vargs);
420 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
422 static int print_prefix = 1;
423 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
424 if (level > av_log_get_level())
426 if (print_prefix && avc)
427 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
428 print_prefix = strstr(fmt, "\n") != NULL;
429 http_vlog(fmt, vargs);
432 static void log_connection(HTTPContext *c)
437 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
438 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
439 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
442 static void update_datarate(DataRateData *drd, int64_t count)
444 if (!drd->time1 && !drd->count1) {
445 drd->time1 = drd->time2 = cur_time;
446 drd->count1 = drd->count2 = count;
447 } else if (cur_time - drd->time2 > 5000) {
448 drd->time1 = drd->time2;
449 drd->count1 = drd->count2;
450 drd->time2 = cur_time;
455 /* In bytes per second */
456 static int compute_datarate(DataRateData *drd, int64_t count)
458 if (cur_time == drd->time1)
461 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
465 static void start_children(FFServerStream *feed)
475 cmd_length = strlen(my_program_name);
478 * FIXME: WIP Safeguard. Remove after clearing all harcoded
479 * '1024' path lengths
481 if (cmd_length > PATH_LENGTH - 1) {
482 http_log("Could not start children. Command line: '%s' exceeds "
483 "path length limit (%d)\n", my_program_name, PATH_LENGTH);
487 pathname = av_strdup (my_program_name);
489 http_log("Could not allocate memory for children cmd line\n");
492 /* replace "ffserver" with "ffmpeg" in the path of current
493 * program. Ignore user provided path */
495 slash = strrchr(pathname, '/');
500 strcpy(slash, "ffmpeg");
502 for (; feed; feed = feed->next) {
504 if (!feed->child_argv || feed->pid)
507 feed->pid_start = time(0);
511 http_log("Unable to create children: %s\n", strerror(errno));
521 http_log("Launch command line: ");
522 http_log("%s ", pathname);
524 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
525 http_log("%s ", feed->child_argv[i]);
528 for (i = 3; i < 256; i++)
532 if (!freopen("/dev/null", "r", stdin))
533 http_log("failed to redirect STDIN to /dev/null\n;");
534 if (!freopen("/dev/null", "w", stdout))
535 http_log("failed to redirect STDOUT to /dev/null\n;");
536 if (!freopen("/dev/null", "w", stderr))
537 http_log("failed to redirect STDERR to /dev/null\n;");
540 signal(SIGPIPE, SIG_DFL);
541 execvp(pathname, feed->child_argv);
548 /* open a listening socket */
549 static int socket_open_listen(struct sockaddr_in *my_addr)
553 server_fd = socket(AF_INET,SOCK_STREAM,0);
560 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
561 av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
563 my_addr->sin_family = AF_INET;
564 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
566 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
567 ntohs(my_addr->sin_port));
572 if (listen (server_fd, 5) < 0) {
577 if (ff_socket_nonblock(server_fd, 1) < 0)
578 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
583 closesocket(server_fd);
587 /* start all multicast streams */
588 static void start_multicast(void)
590 FFServerStream *stream;
593 struct sockaddr_in dest_addr = {0};
594 int default_port, stream_index;
595 unsigned int random0, random1;
598 for(stream = config.first_stream; stream; stream = stream->next) {
600 if (!stream->is_multicast)
603 random0 = av_lfg_get(&random_state);
604 random1 = av_lfg_get(&random_state);
606 /* open the RTP connection */
607 snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
609 /* choose a port if none given */
610 if (stream->multicast_port == 0) {
611 stream->multicast_port = default_port;
615 dest_addr.sin_family = AF_INET;
616 dest_addr.sin_addr = stream->multicast_ip;
617 dest_addr.sin_port = htons(stream->multicast_port);
619 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
620 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
624 if (open_input_stream(rtp_c, "") < 0) {
625 http_log("Could not open input stream for stream '%s'\n",
630 /* open each RTP stream */
631 for(stream_index = 0; stream_index < stream->nb_streams;
633 dest_addr.sin_port = htons(stream->multicast_port +
635 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
638 http_log("Could not open output stream '%s/streamid=%d'\n",
639 stream->filename, stream_index);
643 rtp_c->state = HTTPSTATE_SEND_DATA;
647 /* main loop of the HTTP server */
648 static int http_server(void)
650 int server_fd = 0, rtsp_server_fd = 0;
652 struct pollfd *poll_table, *poll_entry;
653 HTTPContext *c, *c_next;
655 poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
656 sizeof(*poll_table));
658 http_log("Impossible to allocate a poll table handling %d "
659 "connections.\n", config.nb_max_http_connections);
663 if (config.http_addr.sin_port) {
664 server_fd = socket_open_listen(&config.http_addr);
669 if (config.rtsp_addr.sin_port) {
670 rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
671 if (rtsp_server_fd < 0) {
672 closesocket(server_fd);
677 if (!rtsp_server_fd && !server_fd) {
678 http_log("HTTP and RTSP disabled.\n");
682 http_log("FFserver started.\n");
684 start_children(config.first_feed);
689 poll_entry = poll_table;
691 poll_entry->fd = server_fd;
692 poll_entry->events = POLLIN;
695 if (rtsp_server_fd) {
696 poll_entry->fd = rtsp_server_fd;
697 poll_entry->events = POLLIN;
701 /* wait for events on each HTTP handle */
708 case HTTPSTATE_SEND_HEADER:
709 case RTSPSTATE_SEND_REPLY:
710 case RTSPSTATE_SEND_PACKET:
711 c->poll_entry = poll_entry;
713 poll_entry->events = POLLOUT;
716 case HTTPSTATE_SEND_DATA_HEADER:
717 case HTTPSTATE_SEND_DATA:
718 case HTTPSTATE_SEND_DATA_TRAILER:
719 if (!c->is_packetized) {
720 /* for TCP, we output as much as we can
721 * (may need to put a limit) */
722 c->poll_entry = poll_entry;
724 poll_entry->events = POLLOUT;
727 /* when ffserver is doing the timing, we work by
728 * looking at which packet needs to be sent every
729 * 10 ms (one tick wait XXX: 10 ms assumed) */
734 case HTTPSTATE_WAIT_REQUEST:
735 case HTTPSTATE_RECEIVE_DATA:
736 case HTTPSTATE_WAIT_FEED:
737 case RTSPSTATE_WAIT_REQUEST:
738 /* need to catch errors */
739 c->poll_entry = poll_entry;
741 poll_entry->events = POLLIN;/* Maybe this will work */
745 c->poll_entry = NULL;
751 /* wait for an event on one connection. We poll at least every
752 * second to handle timeouts */
754 ret = poll(poll_table, poll_entry - poll_table, delay);
755 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
756 ff_neterrno() != AVERROR(EINTR)) {
761 cur_time = av_gettime() / 1000;
763 if (need_to_start_children) {
764 need_to_start_children = 0;
765 start_children(config.first_feed);
768 /* now handle the events */
769 for(c = first_http_ctx; c; c = c_next) {
771 if (handle_connection(c) < 0) {
773 /* close and free the connection */
778 poll_entry = poll_table;
780 /* new HTTP connection request ? */
781 if (poll_entry->revents & POLLIN)
782 new_connection(server_fd, 0);
785 if (rtsp_server_fd) {
786 /* new RTSP connection request ? */
787 if (poll_entry->revents & POLLIN)
788 new_connection(rtsp_server_fd, 1);
797 /* start waiting for a new HTTP/RTSP request */
798 static void start_wait_request(HTTPContext *c, int is_rtsp)
800 c->buffer_ptr = c->buffer;
801 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
803 c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
804 c->timeout = cur_time +
805 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
808 static void http_send_too_busy_reply(int fd)
811 int len = snprintf(buffer, sizeof(buffer),
812 "HTTP/1.0 503 Server too busy\r\n"
813 "Content-type: text/html\r\n"
816 "<html><head><title>Too busy</title></head><body>\r\n"
817 "<p>The server is too busy to serve your request at "
819 "<p>The number of current connections is %u, and this "
820 "exceeds the limit of %u.</p>\r\n"
821 "</body></html>\r\n",
822 nb_connections, config.nb_max_connections);
823 av_assert0(len < sizeof(buffer));
824 if (send(fd, buffer, len, 0) < len)
825 av_log(NULL, AV_LOG_WARNING,
826 "Could not send too-busy reply, send() failed\n");
830 static void new_connection(int server_fd, int is_rtsp)
832 struct sockaddr_in from_addr;
835 HTTPContext *c = NULL;
837 len = sizeof(from_addr);
838 fd = accept(server_fd, (struct sockaddr *)&from_addr,
841 http_log("error during accept %s\n", strerror(errno));
844 if (ff_socket_nonblock(fd, 1) < 0)
845 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
847 if (nb_connections >= config.nb_max_connections) {
848 http_send_too_busy_reply(fd);
852 /* add a new connection */
853 c = av_mallocz(sizeof(HTTPContext));
858 c->poll_entry = NULL;
859 c->from_addr = from_addr;
860 c->buffer_size = IOBUFFER_INIT_SIZE;
861 c->buffer = av_malloc(c->buffer_size);
865 c->next = first_http_ctx;
869 start_wait_request(c, is_rtsp);
875 av_freep(&c->buffer);
881 static void close_connection(HTTPContext *c)
883 HTTPContext **cp, *c1;
885 AVFormatContext *ctx;
888 /* remove connection from list */
889 cp = &first_http_ctx;
898 /* remove references, if any (XXX: do it faster) */
899 for(c1 = first_http_ctx; c1; c1 = c1->next) {
904 /* remove connection associated resources */
908 /* close each frame parser */
909 for(i=0;i<c->fmt_in->nb_streams;i++) {
910 st = c->fmt_in->streams[i];
911 if (st->codec->codec)
912 avcodec_close(st->codec);
914 avformat_close_input(&c->fmt_in);
917 /* free RTP output streams if any */
920 nb_streams = c->stream->nb_streams;
922 for(i=0;i<nb_streams;i++) {
925 av_write_trailer(ctx);
926 av_dict_free(&ctx->metadata);
927 av_freep(&ctx->streams[0]);
930 ffurl_close(c->rtp_handles[i]);
936 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
938 if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
939 av_write_trailer(ctx);
940 av_freep(&c->pb_buffer);
941 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
944 for(i=0; i<ctx->nb_streams; i++)
945 av_freep(&ctx->streams[i]);
946 av_freep(&ctx->streams);
947 av_freep(&ctx->priv_data);
950 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
951 current_bandwidth -= c->stream->bandwidth;
953 /* signal that there is no feed if we are the feeder socket */
954 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
955 c->stream->feed_opened = 0;
959 av_freep(&c->pb_buffer);
960 av_freep(&c->packet_buffer);
961 av_freep(&c->buffer);
966 static int handle_connection(HTTPContext *c)
972 case HTTPSTATE_WAIT_REQUEST:
973 case RTSPSTATE_WAIT_REQUEST:
975 if ((c->timeout - cur_time) < 0)
977 if (c->poll_entry->revents & (POLLERR | POLLHUP))
980 /* no need to read if no events */
981 if (!(c->poll_entry->revents & POLLIN))
985 if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
989 if (ff_neterrno() != AVERROR(EAGAIN) &&
990 ff_neterrno() != AVERROR(EINTR))
994 /* search for end of request. */
995 c->buffer_ptr += len;
997 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
998 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
999 /* request found : parse it and reply */
1000 if (c->state == HTTPSTATE_WAIT_REQUEST)
1001 ret = http_parse_request(c);
1003 ret = rtsp_parse_request(c);
1007 } else if (ptr >= c->buffer_end) {
1008 /* request too long: cannot do anything */
1010 } else goto read_loop;
1014 case HTTPSTATE_SEND_HEADER:
1015 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1018 /* no need to write if no events */
1019 if (!(c->poll_entry->revents & POLLOUT))
1021 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1023 if (ff_neterrno() != AVERROR(EAGAIN) &&
1024 ff_neterrno() != AVERROR(EINTR)) {
1025 goto close_connection;
1029 c->buffer_ptr += len;
1031 c->stream->bytes_served += len;
1032 c->data_count += len;
1033 if (c->buffer_ptr >= c->buffer_end) {
1034 av_freep(&c->pb_buffer);
1035 /* if error, exit */
1038 /* all the buffer was sent : synchronize to the incoming
1040 c->state = HTTPSTATE_SEND_DATA_HEADER;
1041 c->buffer_ptr = c->buffer_end = c->buffer;
1045 case HTTPSTATE_SEND_DATA:
1046 case HTTPSTATE_SEND_DATA_HEADER:
1047 case HTTPSTATE_SEND_DATA_TRAILER:
1048 /* for packetized output, we consider we can always write (the
1049 * input streams set the speed). It may be better to verify
1050 * that we do not rely too much on the kernel queues */
1051 if (!c->is_packetized) {
1052 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1055 /* no need to read if no events */
1056 if (!(c->poll_entry->revents & POLLOUT))
1059 if (http_send_data(c) < 0)
1061 /* close connection if trailer sent */
1062 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
1064 /* Check if it is a single jpeg frame 123 */
1065 if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
1066 close_connection(c);
1069 case HTTPSTATE_RECEIVE_DATA:
1070 /* no need to read if no events */
1071 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1073 if (!(c->poll_entry->revents & POLLIN))
1075 if (http_receive_data(c) < 0)
1078 case HTTPSTATE_WAIT_FEED:
1079 /* no need to read if no events */
1080 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1083 /* nothing to do, we'll be waken up by incoming feed packets */
1086 case RTSPSTATE_SEND_REPLY:
1087 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1088 goto close_connection;
1089 /* no need to write if no events */
1090 if (!(c->poll_entry->revents & POLLOUT))
1092 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1094 if (ff_neterrno() != AVERROR(EAGAIN) &&
1095 ff_neterrno() != AVERROR(EINTR)) {
1096 goto close_connection;
1100 c->buffer_ptr += len;
1101 c->data_count += len;
1102 if (c->buffer_ptr >= c->buffer_end) {
1103 /* all the buffer was sent : wait for a new request */
1104 av_freep(&c->pb_buffer);
1105 start_wait_request(c, 1);
1108 case RTSPSTATE_SEND_PACKET:
1109 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1110 av_freep(&c->packet_buffer);
1113 /* no need to write if no events */
1114 if (!(c->poll_entry->revents & POLLOUT))
1116 len = send(c->fd, c->packet_buffer_ptr,
1117 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1119 if (ff_neterrno() != AVERROR(EAGAIN) &&
1120 ff_neterrno() != AVERROR(EINTR)) {
1121 /* error : close connection */
1122 av_freep(&c->packet_buffer);
1127 c->packet_buffer_ptr += len;
1128 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1129 /* all the buffer was sent : wait for a new request */
1130 av_freep(&c->packet_buffer);
1131 c->state = RTSPSTATE_WAIT_REQUEST;
1134 case HTTPSTATE_READY:
1143 av_freep(&c->pb_buffer);
1147 static int extract_rates(char *rates, int ratelen, const char *request)
1151 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1152 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1153 const char *q = p + 7;
1155 while (*q && *q != '\n' && av_isspace(*q))
1158 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1164 memset(rates, 0xff, ratelen);
1167 while (*q && *q != '\n' && *q != ':')
1170 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1174 if (stream_no < ratelen && stream_no >= 0)
1175 rates[stream_no] = rate_no;
1177 while (*q && *q != '\n' && !av_isspace(*q))
1184 p = strchr(p, '\n');
1194 static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec,
1198 int best_bitrate = 100000000;
1201 for (i = 0; i < feed->nb_streams; i++) {
1202 AVCodecParameters *feed_codec = feed->streams[i]->codecpar;
1204 if (feed_codec->codec_id != codec->codec_id ||
1205 feed_codec->sample_rate != codec->sample_rate ||
1206 feed_codec->width != codec->width ||
1207 feed_codec->height != codec->height)
1210 /* Potential stream */
1212 /* We want the fastest stream less than bit_rate, or the slowest
1213 * faster than bit_rate
1216 if (feed_codec->bit_rate <= bit_rate) {
1217 if (best_bitrate > bit_rate ||
1218 feed_codec->bit_rate > best_bitrate) {
1219 best_bitrate = feed_codec->bit_rate;
1224 if (feed_codec->bit_rate < best_bitrate) {
1225 best_bitrate = feed_codec->bit_rate;
1232 static int modify_current_stream(HTTPContext *c, char *rates)
1235 FFServerStream *req = c->stream;
1236 int action_required = 0;
1238 /* Not much we can do for a feed */
1242 for (i = 0; i < req->nb_streams; i++) {
1243 AVCodecParameters *codec = req->streams[i]->codecpar;
1247 c->switch_feed_streams[i] = req->feed_streams[i];
1250 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1253 /* Wants off or slow */
1254 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1256 /* This doesn't work well when it turns off the only stream! */
1257 c->switch_feed_streams[i] = -2;
1258 c->feed_streams[i] = -2;
1263 if (c->switch_feed_streams[i] >= 0 &&
1264 c->switch_feed_streams[i] != c->feed_streams[i]) {
1265 action_required = 1;
1269 return action_required;
1272 static void get_word(char *buf, int buf_size, const char **pp)
1277 #define SPACE_CHARS " \t\r\n"
1280 p += strspn(p, SPACE_CHARS);
1282 while (!av_isspace(*p) && *p != '\0') {
1283 if ((q - buf) < buf_size - 1)
1292 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1298 FFServerIPAddressACL *acl = NULL;
1302 f = fopen(stream->dynamic_acl, "r");
1304 perror(stream->dynamic_acl);
1308 acl = av_mallocz(sizeof(FFServerIPAddressACL));
1315 while (fgets(line, sizeof(line), f)) {
1318 while (av_isspace(*p))
1320 if (*p == '\0' || *p == '#')
1322 ffserver_get_arg(cmd, sizeof(cmd), &p);
1324 if (!av_strcasecmp(cmd, "ACL"))
1325 ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1333 static void free_acl_list(FFServerIPAddressACL *in_acl)
1335 FFServerIPAddressACL *pacl, *pacl2;
1345 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1347 enum FFServerIPAddressAction last_action = IP_DENY;
1348 FFServerIPAddressACL *acl;
1349 struct in_addr *src = &c->from_addr.sin_addr;
1350 unsigned long src_addr = src->s_addr;
1352 for (acl = in_acl; acl; acl = acl->next) {
1353 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1354 return (acl->action == IP_ALLOW) ? 1 : 0;
1355 last_action = acl->action;
1358 /* Nothing matched, so return not the last action */
1359 return (last_action == IP_DENY) ? 1 : 0;
1362 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1365 FFServerIPAddressACL *acl;
1367 /* if stream->acl is null validate_acl_list will return 1 */
1368 ret = validate_acl_list(stream->acl, c);
1370 if (stream->dynamic_acl[0]) {
1371 acl = parse_dynamic_acl(stream, c);
1372 ret = validate_acl_list(acl, c);
1380 * compute the real filename of a file by matching it without its
1381 * extensions to all the stream's filenames
1383 static void compute_real_filename(char *filename, int max_size)
1388 FFServerStream *stream;
1390 av_strlcpy(file1, filename, sizeof(file1));
1391 p = strrchr(file1, '.');
1394 for(stream = config.first_stream; stream; stream = stream->next) {
1395 av_strlcpy(file2, stream->filename, sizeof(file2));
1396 p = strrchr(file2, '.');
1399 if (!strcmp(file1, file2)) {
1400 av_strlcpy(filename, stream->filename, max_size);
1415 /* parse HTTP request and prepare header */
1416 static int http_parse_request(HTTPContext *c)
1420 enum RedirType redir_type;
1422 char info[1024], filename[1024];
1426 char *encoded_msg = NULL;
1427 const char *mime_type;
1428 FFServerStream *stream;
1431 const char *useragent = 0;
1434 get_word(cmd, sizeof(cmd), &p);
1435 av_strlcpy(c->method, cmd, sizeof(c->method));
1437 if (!strcmp(cmd, "GET"))
1439 else if (!strcmp(cmd, "POST"))
1444 get_word(url, sizeof(url), &p);
1445 av_strlcpy(c->url, url, sizeof(c->url));
1447 get_word(protocol, sizeof(protocol), (const char **)&p);
1448 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1451 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1454 http_log("%s - - New connection: %s %s\n",
1455 inet_ntoa(c->from_addr.sin_addr), cmd, url);
1457 /* find the filename and the optional info string in the request */
1458 p1 = strchr(url, '?');
1460 av_strlcpy(info, p1, sizeof(info));
1465 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1467 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1468 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1470 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1474 p = strchr(p, '\n');
1481 redir_type = REDIR_NONE;
1482 if (av_match_ext(filename, "asx")) {
1483 redir_type = REDIR_ASX;
1484 filename[strlen(filename)-1] = 'f';
1485 } else if (av_match_ext(filename, "asf") &&
1486 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1487 /* if this isn't WMP or lookalike, return the redirector file */
1488 redir_type = REDIR_ASF;
1489 } else if (av_match_ext(filename, "rpm,ram")) {
1490 redir_type = REDIR_RAM;
1491 strcpy(filename + strlen(filename)-2, "m");
1492 } else if (av_match_ext(filename, "rtsp")) {
1493 redir_type = REDIR_RTSP;
1494 compute_real_filename(filename, sizeof(filename) - 1);
1495 } else if (av_match_ext(filename, "sdp")) {
1496 redir_type = REDIR_SDP;
1497 compute_real_filename(filename, sizeof(filename) - 1);
1500 /* "redirect" request to index.html */
1501 if (!strlen(filename))
1502 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1504 stream = config.first_stream;
1506 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1508 stream = stream->next;
1511 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1512 http_log("File '%s' not found\n", url);
1517 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1518 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1520 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1521 c->http_error = 301;
1523 snprintf(q, c->buffer_size,
1524 "HTTP/1.0 301 Moved\r\n"
1526 "Content-type: text/html\r\n"
1529 "<html><head><title>Moved</title></head><body>\r\n"
1530 "You should be <a href=\"%s\">redirected</a>.\r\n"
1531 "</body></html>\r\n",
1532 stream->feed_filename, stream->feed_filename);
1534 /* prepare output buffer */
1535 c->buffer_ptr = c->buffer;
1537 c->state = HTTPSTATE_SEND_HEADER;
1541 /* If this is WMP, get the rate information */
1542 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1543 if (modify_current_stream(c, ratebuf)) {
1544 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1545 if (c->switch_feed_streams[i] >= 0)
1546 c->switch_feed_streams[i] = -1;
1551 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1552 current_bandwidth += stream->bandwidth;
1554 /* If already streaming this feed, do not let another feeder start */
1555 if (stream->feed_opened) {
1556 snprintf(msg, sizeof(msg), "This feed is already being received.");
1557 http_log("Feed '%s' already being received\n", stream->feed_filename);
1561 if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1562 c->http_error = 503;
1564 snprintf(q, c->buffer_size,
1565 "HTTP/1.0 503 Server too busy\r\n"
1566 "Content-type: text/html\r\n"
1569 "<html><head><title>Too busy</title></head><body>\r\n"
1570 "<p>The server is too busy to serve your request at "
1571 "this time.</p>\r\n"
1572 "<p>The bandwidth being served (including your stream) "
1573 "is %"PRIu64"kbit/s, and this exceeds the limit of "
1574 "%"PRIu64"kbit/s.</p>\r\n"
1575 "</body></html>\r\n",
1576 current_bandwidth, config.max_bandwidth);
1578 /* prepare output buffer */
1579 c->buffer_ptr = c->buffer;
1581 c->state = HTTPSTATE_SEND_HEADER;
1585 if (redir_type != REDIR_NONE) {
1586 const char *hostinfo = 0;
1588 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1589 if (av_strncasecmp(p, "Host:", 5) == 0) {
1593 p = strchr(p, '\n');
1604 while (av_isspace(*hostinfo))
1607 eoh = strchr(hostinfo, '\n');
1609 if (eoh[-1] == '\r')
1612 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1613 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1614 hostbuf[eoh - hostinfo] = 0;
1616 c->http_error = 200;
1618 switch(redir_type) {
1620 snprintf(q, c->buffer_size,
1621 "HTTP/1.0 200 ASX Follows\r\n"
1622 "Content-type: video/x-ms-asf\r\n"
1624 "<ASX Version=\"3\">\r\n"
1625 //"<!-- Autogenerated by ffserver -->\r\n"
1626 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1627 "</ASX>\r\n", hostbuf, filename, info);
1631 snprintf(q, c->buffer_size,
1632 "HTTP/1.0 200 RAM Follows\r\n"
1633 "Content-type: audio/x-pn-realaudio\r\n"
1635 "# Autogenerated by ffserver\r\n"
1636 "http://%s/%s%s\r\n", hostbuf, filename, info);
1640 snprintf(q, c->buffer_size,
1641 "HTTP/1.0 200 ASF Redirect follows\r\n"
1642 "Content-type: video/x-ms-asf\r\n"
1645 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1650 char hostname[256], *p;
1651 /* extract only hostname */
1652 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1653 p = strrchr(hostname, ':');
1656 snprintf(q, c->buffer_size,
1657 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1658 /* XXX: incorrect MIME type ? */
1659 "Content-type: application/x-rtsp\r\n"
1661 "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1670 struct sockaddr_in my_addr;
1672 snprintf(q, c->buffer_size,
1673 "HTTP/1.0 200 OK\r\n"
1674 "Content-type: application/sdp\r\n"
1678 len = sizeof(my_addr);
1680 /* XXX: Should probably fail? */
1681 if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1682 http_log("getsockname() failed\n");
1684 /* XXX: should use a dynamic buffer */
1685 sdp_data_size = prepare_sdp_description(stream,
1688 if (sdp_data_size > 0) {
1689 memcpy(q, sdp_data, sdp_data_size);
1692 av_freep(&sdp_data);
1701 /* prepare output buffer */
1702 c->buffer_ptr = c->buffer;
1704 c->state = HTTPSTATE_SEND_HEADER;
1710 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1714 stream->conns_served++;
1716 /* XXX: add there authenticate and IP match */
1719 /* if post, it means a feed is being sent */
1720 if (!stream->is_feed) {
1721 /* However it might be a status report from WMP! Let us log the
1722 * data as it might come handy one day. */
1723 const char *logline = 0;
1726 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1727 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1731 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1732 client_id = strtol(p + 18, 0, 10);
1733 p = strchr(p, '\n');
1741 char *eol = strchr(logline, '\n');
1746 if (eol[-1] == '\r')
1748 http_log("%.*s\n", (int) (eol - logline), logline);
1749 c->suppress_log = 1;
1754 http_log("\nGot request:\n%s\n", c->buffer);
1757 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1760 /* Now we have to find the client_id */
1761 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1762 if (wmpc->wmp_client_id == client_id)
1766 if (wmpc && modify_current_stream(wmpc, ratebuf))
1767 wmpc->switch_pending = 1;
1770 snprintf(msg, sizeof(msg), "POST command not handled");
1774 if (http_start_receive_data(c) < 0) {
1775 snprintf(msg, sizeof(msg), "could not open feed");
1779 c->state = HTTPSTATE_RECEIVE_DATA;
1784 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1785 http_log("\nGot request:\n%s\n", c->buffer);
1788 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1791 /* open input stream */
1792 if (open_input_stream(c, info) < 0) {
1793 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1797 /* prepare HTTP header */
1799 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1800 mime_type = c->stream->fmt->mime_type;
1802 mime_type = "application/x-octet-stream";
1803 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1805 /* for asf, we need extra headers */
1806 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1807 /* Need to allocate a client id */
1809 c->wmp_client_id = av_lfg_get(&random_state);
1811 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);
1813 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1814 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1815 q = c->buffer + strlen(c->buffer);
1817 /* prepare output buffer */
1819 c->buffer_ptr = c->buffer;
1821 c->state = HTTPSTATE_SEND_HEADER;
1824 c->http_error = 404;
1826 if (!htmlencode(msg, &encoded_msg)) {
1827 http_log("Could not encode filename '%s' as HTML\n", msg);
1829 snprintf(q, c->buffer_size,
1830 "HTTP/1.0 404 Not Found\r\n"
1831 "Content-type: text/html\r\n"
1836 "<meta charset=\"UTF-8\">\n"
1837 "<title>404 Not Found</title>\n"
1840 "</html>\n", encoded_msg? encoded_msg : "File not found");
1842 /* prepare output buffer */
1843 c->buffer_ptr = c->buffer;
1845 c->state = HTTPSTATE_SEND_HEADER;
1846 av_freep(&encoded_msg);
1850 /* horrible: we use this value to avoid
1851 * going to the send data state */
1852 c->http_error = 200;
1853 c->state = HTTPSTATE_SEND_HEADER;
1857 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1859 static const char suffix[] = " kMGTP";
1862 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1864 avio_printf(pb, "%"PRId64"%c", count, *s);
1867 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1870 const char *type = "unknown";
1871 char parameters[64];
1875 stream_no = stream->nb_streams;
1877 avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
1878 "type<th>kbit/s<th align=left>codec<th align=left>"
1881 for (i = 0; i < stream_no; i++) {
1882 st = stream->streams[i];
1883 codec = avcodec_find_encoder(st->codecpar->codec_id);
1887 switch(st->codecpar->codec_type) {
1888 case AVMEDIA_TYPE_AUDIO:
1890 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1891 st->codecpar->channels, st->codecpar->sample_rate);
1893 case AVMEDIA_TYPE_VIDEO:
1895 snprintf(parameters, sizeof(parameters),
1896 "%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
1897 st->codecpar->height, st->codec->qmin, st->codec->qmax,
1898 st->time_base.den / st->time_base.num);
1904 avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
1906 i, type, (int64_t)st->codecpar->bit_rate/1000,
1907 codec ? codec->name : "", parameters);
1910 avio_printf(pb, "</table>\n");
1913 static void compute_status(HTTPContext *c)
1916 FFServerStream *stream;
1922 if (avio_open_dyn_buf(&pb) < 0) {
1923 /* XXX: return an error ? */
1924 c->buffer_ptr = c->buffer;
1925 c->buffer_end = c->buffer;
1929 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1930 avio_printf(pb, "Content-type: text/html\r\n");
1931 avio_printf(pb, "Pragma: no-cache\r\n");
1932 avio_printf(pb, "\r\n");
1934 avio_printf(pb, "<!DOCTYPE html>\n");
1935 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1936 if (c->stream->feed_filename[0])
1937 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1938 c->stream->feed_filename);
1939 avio_printf(pb, "</head>\n<body>");
1940 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1942 avio_printf(pb, "<h2>Available Streams</h2>\n");
1943 avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
1944 avio_printf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbit/s<th align=left>Video<br>kbit/s<th><br>Codec<th align=left>Audio<br>kbit/s<th><br>Codec<th align=left valign=top>Feed\n");
1945 stream = config.first_stream;
1947 char sfilename[1024];
1950 if (stream->feed == stream) {
1951 stream = stream->next;
1955 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1956 eosf = sfilename + strlen(sfilename);
1957 if (eosf - sfilename >= 4) {
1958 if (strcmp(eosf - 4, ".asf") == 0)
1959 strcpy(eosf - 4, ".asx");
1960 else if (strcmp(eosf - 3, ".rm") == 0)
1961 strcpy(eosf - 3, ".ram");
1962 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1963 /* generate a sample RTSP director if
1964 * unicast. Generate an SDP redirector if
1966 eosf = strrchr(sfilename, '.');
1968 eosf = sfilename + strlen(sfilename);
1969 if (stream->is_multicast)
1970 strcpy(eosf, ".sdp");
1972 strcpy(eosf, ".rtsp");
1976 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1977 sfilename, stream->filename);
1978 avio_printf(pb, "<td align=right> %d <td align=right> ",
1979 stream->conns_served);
1980 fmt_bytecount(pb, stream->bytes_served);
1982 switch(stream->stream_type) {
1983 case STREAM_TYPE_LIVE: {
1984 int audio_bit_rate = 0;
1985 int video_bit_rate = 0;
1986 const char *audio_codec_name = "";
1987 const char *video_codec_name = "";
1988 const char *audio_codec_name_extra = "";
1989 const char *video_codec_name_extra = "";
1991 for(i=0;i<stream->nb_streams;i++) {
1992 AVStream *st = stream->streams[i];
1993 AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id);
1995 switch(st->codecpar->codec_type) {
1996 case AVMEDIA_TYPE_AUDIO:
1997 audio_bit_rate += st->codecpar->bit_rate;
1999 if (*audio_codec_name)
2000 audio_codec_name_extra = "...";
2001 audio_codec_name = codec->name;
2004 case AVMEDIA_TYPE_VIDEO:
2005 video_bit_rate += st->codecpar->bit_rate;
2007 if (*video_codec_name)
2008 video_codec_name_extra = "...";
2009 video_codec_name = codec->name;
2012 case AVMEDIA_TYPE_DATA:
2013 video_bit_rate += st->codecpar->bit_rate;
2020 avio_printf(pb, "<td align=center> %s <td align=right> %d "
2021 "<td align=right> %d <td> %s %s <td align=right> "
2023 stream->fmt->name, stream->bandwidth,
2024 video_bit_rate / 1000, video_codec_name,
2025 video_codec_name_extra, audio_bit_rate / 1000,
2026 audio_codec_name, audio_codec_name_extra);
2029 avio_printf(pb, "<td>%s", stream->feed->filename);
2031 avio_printf(pb, "<td>%s", stream->feed_filename);
2032 avio_printf(pb, "\n");
2036 avio_printf(pb, "<td align=center> - <td align=right> - "
2037 "<td align=right> - <td><td align=right> - <td>\n");
2040 stream = stream->next;
2042 avio_printf(pb, "</table>\n");
2044 stream = config.first_stream;
2047 if (stream->feed != stream) {
2048 stream = stream->next;
2052 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
2054 avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
2061 /* This is somewhat linux specific I guess */
2062 snprintf(ps_cmd, sizeof(ps_cmd),
2063 "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
2064 (int64_t) stream->pid);
2066 pid_stat = popen(ps_cmd, "r");
2071 if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
2072 avio_printf(pb, "Currently using %s%% of the cpu. "
2073 "Total time used %s.\n",
2081 avio_printf(pb, "<p>");
2084 print_stream_params(pb, stream);
2085 stream = stream->next;
2088 /* connection status */
2089 avio_printf(pb, "<h2>Connection Status</h2>\n");
2091 avio_printf(pb, "Number of connections: %d / %d<br>\n",
2092 nb_connections, config.nb_max_connections);
2094 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2095 current_bandwidth, config.max_bandwidth);
2097 avio_printf(pb, "<table>\n");
2098 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
2099 "bit/s<th>Actual bit/s<th>Bytes transferred\n");
2100 c1 = first_http_ctx;
2108 for (j = 0; j < c1->stream->nb_streams; j++) {
2109 if (!c1->stream->feed)
2110 bitrate += c1->stream->streams[j]->codecpar->bit_rate;
2111 else if (c1->feed_streams[j] >= 0)
2112 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate;
2117 p = inet_ntoa(c1->from_addr.sin_addr);
2118 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
2120 i, c1->stream ? c1->stream->filename : "",
2121 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
2122 c1->protocol, http_state[c1->state]);
2123 fmt_bytecount(pb, bitrate);
2124 avio_printf(pb, "<td align=right>");
2125 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2126 avio_printf(pb, "<td align=right>");
2127 fmt_bytecount(pb, c1->data_count);
2128 avio_printf(pb, "\n");
2131 avio_printf(pb, "</table>\n");
2136 avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
2137 avio_printf(pb, "</body>\n</html>\n");
2139 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2140 c->buffer_ptr = c->pb_buffer;
2141 c->buffer_end = c->pb_buffer + len;
2144 static int open_input_stream(HTTPContext *c, const char *info)
2147 char input_filename[1024];
2148 AVFormatContext *s = NULL;
2149 int buf_size, i, ret;
2152 /* find file name */
2153 if (c->stream->feed) {
2154 strcpy(input_filename, c->stream->feed->feed_filename);
2155 buf_size = FFM_PACKET_SIZE;
2156 /* compute position (absolute time) */
2157 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2158 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2159 http_log("Invalid date specification '%s' for stream\n", buf);
2162 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2163 int prebuffer = strtol(buf, 0, 10);
2164 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2166 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2168 strcpy(input_filename, c->stream->feed_filename);
2170 /* compute position (relative time) */
2171 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2172 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2173 http_log("Invalid date specification '%s' for stream\n", buf);
2179 if (!input_filename[0]) {
2180 http_log("No filename was specified for stream\n");
2181 return AVERROR(EINVAL);
2185 ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2186 &c->stream->in_opts);
2188 http_log("Could not open input '%s': %s\n",
2189 input_filename, av_err2str(ret));
2193 /* set buffer size */
2195 ret = ffio_set_buf_size(s->pb, buf_size);
2197 http_log("Failed to set buffer size\n");
2202 s->flags |= AVFMT_FLAG_GENPTS;
2204 if (strcmp(s->iformat->name, "ffm") &&
2205 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2206 http_log("Could not find stream info for input '%s'\n", input_filename);
2207 avformat_close_input(&s);
2211 /* choose stream as clock source (we favor the video stream if
2212 * present) for packet sending */
2213 c->pts_stream_index = 0;
2214 for(i=0;i<c->stream->nb_streams;i++) {
2215 if (c->pts_stream_index == 0 &&
2216 c->stream->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
2217 c->pts_stream_index = i;
2221 if (c->fmt_in->iformat->read_seek)
2222 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2223 /* set the start time (needed for maxtime and RTP packet timing) */
2224 c->start_time = cur_time;
2225 c->first_pts = AV_NOPTS_VALUE;
2229 /* return the server clock (in us) */
2230 static int64_t get_server_clock(HTTPContext *c)
2232 /* compute current pts value from system time */
2233 return (cur_time - c->start_time) * 1000;
2236 /* return the estimated time (in us) at which the current packet must be sent */
2237 static int64_t get_packet_send_clock(HTTPContext *c)
2239 int bytes_left, bytes_sent, frame_bytes;
2241 frame_bytes = c->cur_frame_bytes;
2242 if (frame_bytes <= 0)
2245 bytes_left = c->buffer_end - c->buffer_ptr;
2246 bytes_sent = frame_bytes - bytes_left;
2247 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2251 static int http_prepare_data(HTTPContext *c)
2254 AVFormatContext *ctx;
2256 av_freep(&c->pb_buffer);
2258 case HTTPSTATE_SEND_DATA_HEADER:
2259 ctx = avformat_alloc_context();
2261 return AVERROR(ENOMEM);
2263 av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0);
2264 c->pfmt_ctx->streams = av_mallocz_array(c->stream->nb_streams,
2265 sizeof(AVStream *));
2266 if (!c->pfmt_ctx->streams)
2267 return AVERROR(ENOMEM);
2269 for(i=0;i<c->stream->nb_streams;i++) {
2271 c->pfmt_ctx->streams[i] = av_mallocz(sizeof(AVStream));
2273 /* if file or feed, then just take streams from FFServerStream
2275 if (!c->stream->feed ||
2276 c->stream->feed == c->stream)
2277 src = c->stream->streams[i];
2279 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2281 *(c->pfmt_ctx->streams[i]) = *src;
2282 c->pfmt_ctx->streams[i]->priv_data = 0;
2283 /* XXX: should be done in AVStream, not in codec */
2284 c->pfmt_ctx->streams[i]->codec->frame_number = 0;
2286 /* set output format parameters */
2287 c->pfmt_ctx->oformat = c->stream->fmt;
2288 c->pfmt_ctx->nb_streams = c->stream->nb_streams;
2290 c->got_key_frame = 0;
2292 /* prepare header and save header data in a stream */
2293 if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) {
2294 /* XXX: potential leak */
2297 c->pfmt_ctx->pb->seekable = 0;
2300 * HACK to avoid MPEG-PS muxer to spit many underflow errors
2301 * Default value from FFmpeg
2302 * Try to set it using configuration option
2304 c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE);
2306 if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) {
2307 http_log("Error writing output header for stream '%s': %s\n",
2308 c->stream->filename, av_err2str(ret));
2311 av_dict_free(&c->pfmt_ctx->metadata);
2313 len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer);
2314 c->buffer_ptr = c->pb_buffer;
2315 c->buffer_end = c->pb_buffer + len;
2317 c->state = HTTPSTATE_SEND_DATA;
2318 c->last_packet_sent = 0;
2320 case HTTPSTATE_SEND_DATA:
2321 /* find a new packet */
2322 /* read a packet from the input stream */
2323 if (c->stream->feed)
2324 ffm_set_write_index(c->fmt_in,
2325 c->stream->feed->feed_write_index,
2326 c->stream->feed->feed_size);
2328 if (c->stream->max_time &&
2329 c->stream->max_time + c->start_time - cur_time < 0)
2330 /* We have timed out */
2331 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2335 ret = av_read_frame(c->fmt_in, &pkt);
2337 if (c->stream->feed) {
2338 /* if coming from feed, it means we reached the end of the
2339 * ffm file, so must wait for more data */
2340 c->state = HTTPSTATE_WAIT_FEED;
2341 return 1; /* state changed */
2343 if (ret == AVERROR(EAGAIN)) {
2344 /* input not ready, come back later */
2347 if (c->stream->loop) {
2348 avformat_close_input(&c->fmt_in);
2349 if (open_input_stream(c, "") < 0)
2354 /* must send trailer now because EOF or error */
2355 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2358 int source_index = pkt.stream_index;
2359 /* update first pts if needed */
2360 if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
2361 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2362 c->start_time = cur_time;
2364 /* send it to the appropriate stream */
2365 if (c->stream->feed) {
2366 /* if coming from a feed, select the right stream */
2367 if (c->switch_pending) {
2368 c->switch_pending = 0;
2369 for(i=0;i<c->stream->nb_streams;i++) {
2370 if (c->switch_feed_streams[i] == pkt.stream_index)
2371 if (pkt.flags & AV_PKT_FLAG_KEY)
2372 c->switch_feed_streams[i] = -1;
2373 if (c->switch_feed_streams[i] >= 0)
2374 c->switch_pending = 1;
2377 for(i=0;i<c->stream->nb_streams;i++) {
2378 if (c->stream->feed_streams[i] == pkt.stream_index) {
2379 AVStream *st = c->fmt_in->streams[source_index];
2380 pkt.stream_index = i;
2381 if (pkt.flags & AV_PKT_FLAG_KEY &&
2382 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2383 c->stream->nb_streams == 1))
2384 c->got_key_frame = 1;
2385 if (!c->stream->send_on_key || c->got_key_frame)
2390 AVCodecContext *codec;
2391 AVStream *ist, *ost;
2393 ist = c->fmt_in->streams[source_index];
2394 /* specific handling for RTP: we use several
2395 * output streams (one for each RTP connection).
2396 * XXX: need more abstract handling */
2397 if (c->is_packetized) {
2398 /* compute send time and duration */
2399 if (pkt.dts != AV_NOPTS_VALUE) {
2400 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2401 c->cur_pts -= c->first_pts;
2403 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2404 /* find RTP context */
2405 c->packet_stream_index = pkt.stream_index;
2406 ctx = c->rtp_ctx[c->packet_stream_index];
2408 av_packet_unref(&pkt);
2411 codec = ctx->streams[0]->codec;
2412 /* only one stream per RTP connection */
2413 pkt.stream_index = 0;
2417 codec = ctx->streams[pkt.stream_index]->codec;
2420 if (c->is_packetized) {
2421 int max_packet_size;
2422 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2423 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2425 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2426 ret = ffio_open_dyn_packet_buf(&ctx->pb,
2429 ret = avio_open_dyn_buf(&ctx->pb);
2432 /* XXX: potential leak */
2435 ost = ctx->streams[pkt.stream_index];
2437 ctx->pb->seekable = 0;
2438 if (pkt.dts != AV_NOPTS_VALUE)
2439 pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2441 if (pkt.pts != AV_NOPTS_VALUE)
2442 pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2444 pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2446 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2447 http_log("Error writing frame to output for stream '%s': %s\n",
2448 c->stream->filename, av_err2str(ret));
2449 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2452 av_freep(&c->pb_buffer);
2453 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2455 c->cur_frame_bytes = len;
2456 c->buffer_ptr = c->pb_buffer;
2457 c->buffer_end = c->pb_buffer + len;
2459 codec->frame_number++;
2461 av_packet_unref(&pkt);
2465 av_packet_unref(&pkt);
2470 case HTTPSTATE_SEND_DATA_TRAILER:
2471 /* last packet test ? */
2472 if (c->last_packet_sent || c->is_packetized)
2475 /* prepare header */
2476 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2477 /* XXX: potential leak */
2480 c->pfmt_ctx->pb->seekable = 0;
2481 av_write_trailer(ctx);
2482 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2483 c->buffer_ptr = c->pb_buffer;
2484 c->buffer_end = c->pb_buffer + len;
2486 c->last_packet_sent = 1;
2492 /* should convert the format at the same time */
2493 /* send data starting at c->buffer_ptr to the output connection
2494 * (either UDP or TCP)
2496 static int http_send_data(HTTPContext *c)
2501 if (c->buffer_ptr >= c->buffer_end) {
2502 ret = http_prepare_data(c);
2506 /* state change requested */
2509 if (c->is_packetized) {
2510 /* RTP data output */
2511 len = c->buffer_end - c->buffer_ptr;
2513 /* fail safe - should never happen */
2515 c->buffer_ptr = c->buffer_end;
2518 len = (c->buffer_ptr[0] << 24) |
2519 (c->buffer_ptr[1] << 16) |
2520 (c->buffer_ptr[2] << 8) |
2522 if (len > (c->buffer_end - c->buffer_ptr))
2524 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2525 /* nothing to send yet: we can wait */
2529 c->data_count += len;
2530 update_datarate(&c->datarate, c->data_count);
2532 c->stream->bytes_served += len;
2534 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2535 /* RTP packets are sent inside the RTSP TCP connection */
2537 int interleaved_index, size;
2539 HTTPContext *rtsp_c;
2542 /* if no RTSP connection left, error */
2545 /* if already sending something, then wait. */
2546 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2548 if (avio_open_dyn_buf(&pb) < 0)
2550 interleaved_index = c->packet_stream_index * 2;
2551 /* RTCP packets are sent at odd indexes */
2552 if (c->buffer_ptr[1] == 200)
2553 interleaved_index++;
2554 /* write RTSP TCP header */
2556 header[1] = interleaved_index;
2557 header[2] = len >> 8;
2559 avio_write(pb, header, 4);
2560 /* write RTP packet data */
2562 avio_write(pb, c->buffer_ptr, len);
2563 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2564 /* prepare asynchronous TCP sending */
2565 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2566 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2567 c->buffer_ptr += len;
2569 /* send everything we can NOW */
2570 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2571 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2573 rtsp_c->packet_buffer_ptr += len;
2574 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2575 /* if we could not send all the data, we will
2576 * send it later, so a new state is needed to
2577 * "lock" the RTSP TCP connection */
2578 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2581 /* all data has been sent */
2582 av_freep(&c->packet_buffer);
2584 /* send RTP packet directly in UDP */
2586 ffurl_write(c->rtp_handles[c->packet_stream_index],
2587 c->buffer_ptr, len);
2588 c->buffer_ptr += len;
2589 /* here we continue as we can send several packets
2593 /* TCP data output */
2594 len = send(c->fd, c->buffer_ptr,
2595 c->buffer_end - c->buffer_ptr, 0);
2597 if (ff_neterrno() != AVERROR(EAGAIN) &&
2598 ff_neterrno() != AVERROR(EINTR))
2599 /* error : close connection */
2604 c->buffer_ptr += len;
2606 c->data_count += len;
2607 update_datarate(&c->datarate, c->data_count);
2609 c->stream->bytes_served += len;
2617 static int http_start_receive_data(HTTPContext *c)
2623 if (c->stream->feed_opened) {
2624 http_log("Stream feed '%s' was not opened\n",
2625 c->stream->feed_filename);
2626 return AVERROR(EINVAL);
2629 /* Don't permit writing to this one */
2630 if (c->stream->readonly) {
2631 http_log("Cannot write to read-only file '%s'\n",
2632 c->stream->feed_filename);
2633 return AVERROR(EINVAL);
2637 fd = open(c->stream->feed_filename, O_RDWR);
2639 ret = AVERROR(errno);
2640 http_log("Could not open feed file '%s': %s\n",
2641 c->stream->feed_filename, strerror(errno));
2646 if (c->stream->truncate) {
2647 /* truncate feed file */
2648 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2649 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2650 if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2651 ret = AVERROR(errno);
2652 http_log("Error truncating feed file '%s': %s\n",
2653 c->stream->feed_filename, strerror(errno));
2657 ret64 = ffm_read_write_index(fd);
2659 http_log("Error reading write index from feed file '%s': %s\n",
2660 c->stream->feed_filename, strerror(errno));
2663 c->stream->feed_write_index = ret64;
2666 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2668 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2669 lseek(fd, 0, SEEK_SET);
2671 /* init buffer input */
2672 c->buffer_ptr = c->buffer;
2673 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2674 c->stream->feed_opened = 1;
2675 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2679 static int http_receive_data(HTTPContext *c)
2682 int len, loop_run = 0;
2684 while (c->chunked_encoding && !c->chunk_size &&
2685 c->buffer_end > c->buffer_ptr) {
2686 /* read chunk header, if present */
2687 len = recv(c->fd, c->buffer_ptr, 1, 0);
2690 if (ff_neterrno() != AVERROR(EAGAIN) &&
2691 ff_neterrno() != AVERROR(EINTR))
2692 /* error : close connection */
2695 } else if (len == 0) {
2696 /* end of connection : close it */
2698 } else if (c->buffer_ptr - c->buffer >= 2 &&
2699 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2700 c->chunk_size = strtol(c->buffer, 0, 16);
2701 if (c->chunk_size == 0) // end of stream
2703 c->buffer_ptr = c->buffer;
2705 } else if (++loop_run > 10)
2706 /* no chunk header, abort */
2712 if (c->buffer_end > c->buffer_ptr) {
2713 len = recv(c->fd, c->buffer_ptr,
2714 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2716 if (ff_neterrno() != AVERROR(EAGAIN) &&
2717 ff_neterrno() != AVERROR(EINTR))
2718 /* error : close connection */
2720 } else if (len == 0)
2721 /* end of connection : close it */
2724 c->chunk_size -= len;
2725 c->buffer_ptr += len;
2726 c->data_count += len;
2727 update_datarate(&c->datarate, c->data_count);
2731 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2732 if (c->buffer[0] != 'f' ||
2733 c->buffer[1] != 'm') {
2734 http_log("Feed stream has become desynchronized -- disconnecting\n");
2739 if (c->buffer_ptr >= c->buffer_end) {
2740 FFServerStream *feed = c->stream;
2741 /* a packet has been received : write it in the store, except
2743 if (c->data_count > FFM_PACKET_SIZE) {
2744 /* XXX: use llseek or url_seek
2745 * XXX: Should probably fail? */
2746 if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2747 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2749 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2750 http_log("Error writing to feed file: %s\n", strerror(errno));
2754 feed->feed_write_index += FFM_PACKET_SIZE;
2755 /* update file size */
2756 if (feed->feed_write_index > c->stream->feed_size)
2757 feed->feed_size = feed->feed_write_index;
2759 /* handle wrap around if max file size reached */
2760 if (c->stream->feed_max_size &&
2761 feed->feed_write_index >= c->stream->feed_max_size)
2762 feed->feed_write_index = FFM_PACKET_SIZE;
2765 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2766 http_log("Error writing index to feed file: %s\n",
2771 /* wake up any waiting connections */
2772 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2773 if (c1->state == HTTPSTATE_WAIT_FEED &&
2774 c1->stream->feed == c->stream->feed)
2775 c1->state = HTTPSTATE_SEND_DATA;
2778 /* We have a header in our hands that contains useful data */
2779 AVFormatContext *s = avformat_alloc_context();
2781 AVInputFormat *fmt_in;
2787 /* use feed output format name to find corresponding input format */
2788 fmt_in = av_find_input_format(feed->fmt->name);
2792 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2793 0, NULL, NULL, NULL, NULL);
2800 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2805 /* Now we have the actual streams */
2806 if (s->nb_streams != feed->nb_streams) {
2807 avformat_close_input(&s);
2809 http_log("Feed '%s' stream number does not match registered feed\n",
2810 c->stream->feed_filename);
2814 for (i = 0; i < s->nb_streams; i++) {
2815 AVStream *fst = feed->streams[i];
2816 AVStream *st = s->streams[i];
2817 avcodec_copy_context(fst->codec, st->codec);
2820 avformat_close_input(&s);
2823 c->buffer_ptr = c->buffer;
2828 c->stream->feed_opened = 0;
2830 /* wake up any waiting connections to stop waiting for feed */
2831 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2832 if (c1->state == HTTPSTATE_WAIT_FEED &&
2833 c1->stream->feed == c->stream->feed)
2834 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2839 /********************************************************************/
2842 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2849 str = RTSP_STATUS_CODE2STRING(error_number);
2851 str = "Unknown Error";
2853 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2854 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2856 /* output GMT time */
2859 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2860 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2863 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2865 rtsp_reply_header(c, error_number);
2866 avio_printf(c->pb, "\r\n");
2869 static int rtsp_parse_request(HTTPContext *c)
2871 const char *p, *p1, *p2;
2877 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2879 c->buffer_ptr[0] = '\0';
2882 get_word(cmd, sizeof(cmd), &p);
2883 get_word(url, sizeof(url), &p);
2884 get_word(protocol, sizeof(protocol), &p);
2886 av_strlcpy(c->method, cmd, sizeof(c->method));
2887 av_strlcpy(c->url, url, sizeof(c->url));
2888 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2890 if (avio_open_dyn_buf(&c->pb) < 0) {
2891 /* XXX: cannot do more */
2892 c->pb = NULL; /* safety */
2896 /* check version name */
2897 if (strcmp(protocol, "RTSP/1.0")) {
2898 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2902 /* parse each header line */
2903 /* skip to next line */
2904 while (*p != '\n' && *p != '\0')
2908 while (*p != '\0') {
2909 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2913 if (p2 > p && p2[-1] == '\r')
2915 /* skip empty line */
2919 if (len > sizeof(line) - 1)
2920 len = sizeof(line) - 1;
2921 memcpy(line, p, len);
2923 ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
2927 /* handle sequence number */
2928 c->seq = header->seq;
2930 if (!strcmp(cmd, "DESCRIBE"))
2931 rtsp_cmd_describe(c, url);
2932 else if (!strcmp(cmd, "OPTIONS"))
2933 rtsp_cmd_options(c, url);
2934 else if (!strcmp(cmd, "SETUP"))
2935 rtsp_cmd_setup(c, url, header);
2936 else if (!strcmp(cmd, "PLAY"))
2937 rtsp_cmd_play(c, url, header);
2938 else if (!strcmp(cmd, "PAUSE"))
2939 rtsp_cmd_interrupt(c, url, header, 1);
2940 else if (!strcmp(cmd, "TEARDOWN"))
2941 rtsp_cmd_interrupt(c, url, header, 0);
2943 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2946 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2947 c->pb = NULL; /* safety */
2949 /* XXX: cannot do more */
2952 c->buffer_ptr = c->pb_buffer;
2953 c->buffer_end = c->pb_buffer + len;
2954 c->state = RTSPSTATE_SEND_REPLY;
2958 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
2959 struct in_addr my_ip)
2961 AVFormatContext *avc;
2962 AVStream *avs = NULL;
2963 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
2964 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
2969 avc = avformat_alloc_context();
2970 if (!avc || !rtp_format)
2973 avc->oformat = rtp_format;
2974 av_dict_set(&avc->metadata, "title",
2975 entry ? entry->value : "No Title", 0);
2976 avc->nb_streams = stream->nb_streams;
2977 if (stream->is_multicast) {
2978 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2979 inet_ntoa(stream->multicast_ip),
2980 stream->multicast_port, stream->multicast_ttl);
2982 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
2984 avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
2988 avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
2992 for(i = 0; i < stream->nb_streams; i++) {
2993 avc->streams[i] = &avs[i];
2994 avc->streams[i]->codec = stream->streams[i]->codec;
2995 avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
2996 avc->streams[i]->codecpar = stream->streams[i]->codecpar;
2998 #define PBUFFER_SIZE 2048
2999 *pbuffer = av_mallocz(PBUFFER_SIZE);
3002 av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
3005 av_freep(&avc->streams);
3006 av_dict_free(&avc->metadata);
3010 return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
3013 static void rtsp_cmd_options(HTTPContext *c, const char *url)
3015 /* rtsp_reply_header(c, RTSP_STATUS_OK); */
3016 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
3017 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
3018 avio_printf(c->pb, "Public: %s\r\n",
3019 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
3020 avio_printf(c->pb, "\r\n");
3023 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
3025 FFServerStream *stream;
3031 struct sockaddr_in my_addr;
3033 /* find which URL is asked */
3034 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3039 for(stream = config.first_stream; stream; stream = stream->next) {
3040 if (!stream->is_feed &&
3041 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
3042 !strcmp(path, stream->filename)) {
3046 /* no stream found */
3047 rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
3051 /* prepare the media description in SDP format */
3053 /* get the host IP */
3054 len = sizeof(my_addr);
3055 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3056 content_length = prepare_sdp_description(stream, &content,
3058 if (content_length < 0) {
3059 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3062 rtsp_reply_header(c, RTSP_STATUS_OK);
3063 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
3064 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
3065 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
3066 avio_printf(c->pb, "\r\n");
3067 avio_write(c->pb, content, content_length);
3071 static HTTPContext *find_rtp_session(const char *session_id)
3075 if (session_id[0] == '\0')
3078 for(c = first_http_ctx; c; c = c->next) {
3079 if (!strcmp(c->session_id, session_id))
3085 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3087 RTSPTransportField *th;
3090 for(i=0;i<h->nb_transports;i++) {
3091 th = &h->transports[i];
3092 if (th->lower_transport == lower_transport)
3098 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3099 RTSPMessageHeader *h)
3101 FFServerStream *stream;
3102 int stream_index, rtp_port, rtcp_port;
3107 RTSPTransportField *th;
3108 struct sockaddr_in dest_addr;
3109 RTSPActionServerSetup setup;
3111 /* find which URL is asked */
3112 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3117 /* now check each stream */
3118 for(stream = config.first_stream; stream; stream = stream->next) {
3119 if (stream->is_feed || !stream->fmt ||
3120 strcmp(stream->fmt->name, "rtp")) {
3123 /* accept aggregate filenames only if single stream */
3124 if (!strcmp(path, stream->filename)) {
3125 if (stream->nb_streams != 1) {
3126 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3133 for(stream_index = 0; stream_index < stream->nb_streams;
3135 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3136 stream->filename, stream_index);
3137 if (!strcmp(path, buf))
3141 /* no stream found */
3142 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3146 /* generate session id if needed */
3147 if (h->session_id[0] == '\0') {
3148 unsigned random0 = av_lfg_get(&random_state);
3149 unsigned random1 = av_lfg_get(&random_state);
3150 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3154 /* find RTP session, and create it if none found */
3155 rtp_c = find_rtp_session(h->session_id);
3157 /* always prefer UDP */
3158 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3160 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3162 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3167 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3168 th->lower_transport);
3170 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3174 /* open input stream */
3175 if (open_input_stream(rtp_c, "") < 0) {
3176 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3181 /* test if stream is OK (test needed because several SETUP needs
3182 * to be done for a given file) */
3183 if (rtp_c->stream != stream) {
3184 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3188 /* test if stream is already set up */
3189 if (rtp_c->rtp_ctx[stream_index]) {
3190 rtsp_reply_error(c, RTSP_STATUS_STATE);
3194 /* check transport */
3195 th = find_transport(h, rtp_c->rtp_protocol);
3196 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3197 th->client_port_min <= 0)) {
3198 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3202 /* setup default options */
3203 setup.transport_option[0] = '\0';
3204 dest_addr = rtp_c->from_addr;
3205 dest_addr.sin_port = htons(th->client_port_min);
3208 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3209 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3213 /* now everything is OK, so we can send the connection parameters */
3214 rtsp_reply_header(c, RTSP_STATUS_OK);
3216 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3218 switch(rtp_c->rtp_protocol) {
3219 case RTSP_LOWER_TRANSPORT_UDP:
3220 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3221 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3222 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3223 "client_port=%d-%d;server_port=%d-%d",
3224 th->client_port_min, th->client_port_max,
3225 rtp_port, rtcp_port);
3227 case RTSP_LOWER_TRANSPORT_TCP:
3228 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3229 stream_index * 2, stream_index * 2 + 1);
3234 if (setup.transport_option[0] != '\0')
3235 avio_printf(c->pb, ";%s", setup.transport_option);
3236 avio_printf(c->pb, "\r\n");
3239 avio_printf(c->pb, "\r\n");
3244 * find an RTP connection by using the session ID. Check consistency
3247 static HTTPContext *find_rtp_session_with_url(const char *url,
3248 const char *session_id)
3256 rtp_c = find_rtp_session(session_id);
3260 /* find which URL is asked */
3261 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3265 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3266 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3267 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3268 rtp_c->stream->filename, s);
3269 if(!strncmp(path, buf, sizeof(buf)))
3270 /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3271 * if nb_streams>1? */
3275 if (len > 0 && path[len - 1] == '/' &&
3276 !strncmp(path, rtp_c->stream->filename, len - 1))
3281 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3285 rtp_c = find_rtp_session_with_url(url, h->session_id);
3287 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3291 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3292 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3293 rtp_c->state != HTTPSTATE_READY) {
3294 rtsp_reply_error(c, RTSP_STATUS_STATE);
3298 rtp_c->state = HTTPSTATE_SEND_DATA;
3300 /* now everything is OK, so we can send the connection parameters */
3301 rtsp_reply_header(c, RTSP_STATUS_OK);
3303 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3304 avio_printf(c->pb, "\r\n");
3307 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3308 RTSPMessageHeader *h, int pause_only)
3312 rtp_c = find_rtp_session_with_url(url, h->session_id);
3314 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3319 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3320 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3321 rtsp_reply_error(c, RTSP_STATUS_STATE);
3324 rtp_c->state = HTTPSTATE_READY;
3325 rtp_c->first_pts = AV_NOPTS_VALUE;
3328 /* now everything is OK, so we can send the connection parameters */
3329 rtsp_reply_header(c, RTSP_STATUS_OK);
3331 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3332 avio_printf(c->pb, "\r\n");
3335 close_connection(rtp_c);
3338 /********************************************************************/
3341 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3342 FFServerStream *stream,
3343 const char *session_id,
3344 enum RTSPLowerTransport rtp_protocol)
3346 HTTPContext *c = NULL;
3347 const char *proto_str;
3349 /* XXX: should output a warning page when coming
3350 * close to the connection limit */
3351 if (nb_connections >= config.nb_max_connections)
3354 /* add a new connection */
3355 c = av_mallocz(sizeof(HTTPContext));
3360 c->poll_entry = NULL;
3361 c->from_addr = *from_addr;
3362 c->buffer_size = IOBUFFER_INIT_SIZE;
3363 c->buffer = av_malloc(c->buffer_size);
3368 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3369 c->state = HTTPSTATE_READY;
3370 c->is_packetized = 1;
3371 c->rtp_protocol = rtp_protocol;
3373 /* protocol is shown in statistics */
3374 switch(c->rtp_protocol) {
3375 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3376 proto_str = "MCAST";
3378 case RTSP_LOWER_TRANSPORT_UDP:
3381 case RTSP_LOWER_TRANSPORT_TCP:
3388 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3389 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3391 current_bandwidth += stream->bandwidth;
3393 c->next = first_http_ctx;
3399 av_freep(&c->buffer);
3406 * add a new RTP stream in an RTP connection (used in RTSP SETUP
3407 * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3410 static int rtp_new_av_stream(HTTPContext *c,
3411 int stream_index, struct sockaddr_in *dest_addr,
3412 HTTPContext *rtsp_c)
3414 AVFormatContext *ctx;
3417 URLContext *h = NULL;
3419 int max_packet_size;
3422 /* now we can open the relevant output stream */
3423 ctx = avformat_alloc_context();
3426 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3428 st = avformat_new_stream(ctx, NULL);
3432 av_freep(&st->codec);
3433 av_freep(&st->info);
3434 st_internal = st->internal;
3436 if (!c->stream->feed ||
3437 c->stream->feed == c->stream)
3438 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3441 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3443 st->priv_data = NULL;
3444 st->internal = st_internal;
3446 /* build destination RTP address */
3447 ipaddr = inet_ntoa(dest_addr->sin_addr);
3449 switch(c->rtp_protocol) {
3450 case RTSP_LOWER_TRANSPORT_UDP:
3451 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3454 /* XXX: also pass as parameter to function ? */
3455 if (c->stream->is_multicast) {
3457 ttl = c->stream->multicast_ttl;
3460 snprintf(ctx->filename, sizeof(ctx->filename),
3461 "rtp://%s:%d?multicast=1&ttl=%d",
3462 ipaddr, ntohs(dest_addr->sin_port), ttl);
3464 snprintf(ctx->filename, sizeof(ctx->filename),
3465 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3468 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3470 c->rtp_handles[stream_index] = h;
3471 max_packet_size = h->max_packet_size;
3473 case RTSP_LOWER_TRANSPORT_TCP:
3476 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3482 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3483 ipaddr, ntohs(dest_addr->sin_port),
3484 c->stream->filename, stream_index, c->protocol);
3486 /* normally, no packets should be output here, but the packet size may
3488 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3489 /* XXX: close stream */
3492 if (avformat_write_header(ctx, NULL) < 0) {
3500 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3504 c->rtp_ctx[stream_index] = ctx;
3508 /********************************************************************/
3509 /* ffserver initialization */
3511 /* FIXME: This code should use avformat_new_stream() */
3512 static AVStream *add_av_stream1(FFServerStream *stream,
3513 AVCodecContext *codec, int copy)
3517 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3520 fst = av_mallocz(sizeof(AVStream));
3524 fst->codec = avcodec_alloc_context3(codec->codec);
3529 avcodec_copy_context(fst->codec, codec);
3531 /* live streams must use the actual feed's codec since it may be
3532 * updated later to carry extradata needed by them.
3536 fst->priv_data = av_mallocz(sizeof(FeedData));
3537 fst->internal = av_mallocz(sizeof(*fst->internal));
3538 fst->internal->avctx = avcodec_alloc_context3(NULL);
3539 fst->codecpar = avcodec_parameters_alloc();
3540 fst->index = stream->nb_streams;
3541 avpriv_set_pts_info(fst, 33, 1, 90000);
3542 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3543 stream->streams[stream->nb_streams++] = fst;
3547 /* return the stream number in the feed */
3548 static int add_av_stream(FFServerStream *feed, AVStream *st)
3551 AVCodecContext *av, *av1;
3555 for(i=0;i<feed->nb_streams;i++) {
3556 av1 = feed->streams[i]->codec;
3557 if (av1->codec_id == av->codec_id &&
3558 av1->codec_type == av->codec_type &&
3559 av1->bit_rate == av->bit_rate) {
3561 switch(av->codec_type) {
3562 case AVMEDIA_TYPE_AUDIO:
3563 if (av1->channels == av->channels &&
3564 av1->sample_rate == av->sample_rate)
3567 case AVMEDIA_TYPE_VIDEO:
3568 if (av1->width == av->width &&
3569 av1->height == av->height &&
3570 av1->time_base.den == av->time_base.den &&
3571 av1->time_base.num == av->time_base.num &&
3572 av1->gop_size == av->gop_size)
3581 fst = add_av_stream1(feed, av, 0);
3584 if (av_stream_get_recommended_encoder_configuration(st))
3585 av_stream_set_recommended_encoder_configuration(fst,
3586 av_strdup(av_stream_get_recommended_encoder_configuration(st)));
3587 return feed->nb_streams - 1;
3590 static void remove_stream(FFServerStream *stream)
3592 FFServerStream **ps;
3593 ps = &config.first_stream;
3602 /* specific MPEG4 handling : we extract the raw parameters */
3603 static void extract_mpeg4_header(AVFormatContext *infile)
3605 int mpeg4_count, i, size;
3610 infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
3613 for(i=0;i<infile->nb_streams;i++) {
3614 st = infile->streams[i];
3615 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3616 st->codec->extradata_size == 0) {
3623 printf("MPEG4 without extra data: trying to find header in %s\n",
3625 while (mpeg4_count > 0) {
3626 if (av_read_frame(infile, &pkt) < 0)
3628 st = infile->streams[pkt.stream_index];
3629 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3630 st->codec->extradata_size == 0) {
3631 av_freep(&st->codec->extradata);
3632 /* fill extradata with the header */
3633 /* XXX: we make hard suppositions here ! */
3635 while (p < pkt.data + pkt.size - 4) {
3636 /* stop when vop header is found */
3637 if (p[0] == 0x00 && p[1] == 0x00 &&
3638 p[2] == 0x01 && p[3] == 0xb6) {
3639 size = p - pkt.data;
3640 st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
3641 st->codec->extradata_size = size;
3642 memcpy(st->codec->extradata, pkt.data, size);
3649 av_packet_unref(&pkt);
3653 /* compute the needed AVStream for each file */
3654 static void build_file_streams(void)
3656 FFServerStream *stream;
3657 AVFormatContext *infile;
3660 /* gather all streams */
3661 for(stream = config.first_stream; stream; stream = stream->next) {
3664 if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
3667 /* the stream comes from a file */
3668 /* try to open the file */
3672 /* specific case: if transport stream output to RTP,
3673 * we use a raw transport stream reader */
3674 if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
3675 av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3677 if (!stream->feed_filename[0]) {
3678 http_log("Unspecified feed file for stream '%s'\n",
3683 http_log("Opening feed file '%s' for stream '%s'\n",
3684 stream->feed_filename, stream->filename);
3686 ret = avformat_open_input(&infile, stream->feed_filename,
3687 stream->ifmt, &stream->in_opts);
3689 http_log("Could not open '%s': %s\n", stream->feed_filename,
3691 /* remove stream (no need to spend more time on it) */
3693 remove_stream(stream);
3695 /* find all the AVStreams inside and reference them in
3697 if (avformat_find_stream_info(infile, NULL) < 0) {
3698 http_log("Could not find codec parameters from '%s'\n",
3699 stream->feed_filename);
3700 avformat_close_input(&infile);
3703 extract_mpeg4_header(infile);
3705 for(i=0;i<infile->nb_streams;i++)
3706 add_av_stream1(stream, infile->streams[i]->codec, 1);
3708 avformat_close_input(&infile);
3714 int check_codec_match(AVStream *ccf, AVStream *ccs, int stream)
3718 /* FIXME: Missed check on AVCodecContext.flags */
3719 #define CHECK_CODEC(x) (ccf->codecpar->x != ccs->codecpar->x)
3720 if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3721 http_log("Codecs do not match for stream %d\n", stream);
3723 } else if (CHECK_CODEC(bit_rate)) {
3724 http_log("Codec bitrates do not match for stream %d\n", stream);
3726 } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
3727 if (av_cmp_q(ccf->time_base, ccs->time_base) ||
3728 CHECK_CODEC(width) || CHECK_CODEC(height)) {
3729 http_log("Codec width, height or framerate do not match for stream %d\n", stream);
3732 } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
3733 if (CHECK_CODEC(sample_rate) ||
3734 CHECK_CODEC(channels) ||
3735 CHECK_CODEC(frame_size)) {
3736 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
3740 http_log("Unknown codec type for stream %d\n", stream);
3747 /* compute the needed AVStream for each feed */
3748 static int build_feed_streams(void)
3750 FFServerStream *stream, *feed;
3753 /* gather all streams */
3754 for(stream = config.first_stream; stream; stream = stream->next) {
3755 feed = stream->feed;
3759 if (stream->is_feed) {
3760 for(i=0;i<stream->nb_streams;i++)
3761 stream->feed_streams[i] = i;
3764 /* we handle a stream coming from a feed */
3765 for(i=0;i<stream->nb_streams;i++)
3766 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3769 /* create feed files if needed */
3770 for(feed = config.first_feed; feed; feed = feed->next_feed) {
3772 if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
3773 AVFormatContext *s = NULL;
3776 /* See if it matches */
3778 if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
3779 http_log("Deleting feed file '%s' as it appears "
3781 feed->feed_filename);
3785 /* set buffer size */
3786 if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
3787 http_log("Failed to set buffer size\n");
3788 avformat_close_input(&s);
3792 /* Now see if it matches */
3793 if (s->nb_streams != feed->nb_streams) {
3794 http_log("Deleting feed file '%s' as stream counts "
3795 "differ (%d != %d)\n",
3796 feed->feed_filename, s->nb_streams, feed->nb_streams);
3801 for(i=0;i<s->nb_streams;i++) {
3804 sf = feed->streams[i];
3807 if (sf->index != ss->index || sf->id != ss->id) {
3808 http_log("Index & Id do not match for stream %d (%s)\n",
3809 i, feed->feed_filename);
3814 matches = check_codec_match (sf, ss, i);
3821 avformat_close_input(&s);
3824 if (feed->readonly) {
3825 http_log("Unable to delete read-only feed file '%s'\n",
3826 feed->feed_filename);
3829 unlink(feed->feed_filename);
3833 if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
3834 AVFormatContext *s = avformat_alloc_context();
3837 http_log("Failed to allocate context\n");
3841 if (feed->readonly) {
3842 http_log("Unable to create feed file '%s' as it is "
3843 "marked readonly\n",
3844 feed->feed_filename);
3845 avformat_free_context(s);
3849 /* only write the header of the ffm file */
3850 if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
3851 http_log("Could not open output feed file '%s'\n",
3852 feed->feed_filename);
3853 avformat_free_context(s);
3856 s->oformat = feed->fmt;
3857 s->nb_streams = feed->nb_streams;
3858 s->streams = feed->streams;
3859 if (avformat_write_header(s, NULL) < 0) {
3860 http_log("Container doesn't support the required parameters\n");
3861 avio_closep(&s->pb);
3864 avformat_free_context(s);
3867 /* XXX: need better API */
3868 av_freep(&s->priv_data);
3869 avio_closep(&s->pb);
3872 avformat_free_context(s);
3875 /* get feed size and write index */
3876 fd = open(feed->feed_filename, O_RDONLY);
3878 http_log("Could not open output feed file '%s'\n",
3879 feed->feed_filename);
3883 feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
3885 feed->feed_size = lseek(fd, 0, SEEK_END);
3886 /* ensure that we do not wrap before the end of file */
3887 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3888 feed->feed_max_size = feed->feed_size;
3898 /* compute the bandwidth used by each stream */
3899 static void compute_bandwidth(void)
3903 FFServerStream *stream;
3905 for(stream = config.first_stream; stream; stream = stream->next) {
3907 for(i=0;i<stream->nb_streams;i++) {
3908 AVStream *st = stream->streams[i];
3909 switch(st->codec->codec_type) {
3910 case AVMEDIA_TYPE_AUDIO:
3911 case AVMEDIA_TYPE_VIDEO:
3912 bandwidth += st->codec->bit_rate;
3918 stream->bandwidth = (bandwidth + 999) / 1000;
3922 static void handle_child_exit(int sig)
3928 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3929 FFServerStream *feed;
3931 for (feed = config.first_feed; feed; feed = feed->next) {
3932 if (feed->pid != pid)
3935 uptime = time(0) - feed->pid_start;
3938 "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
3940 feed->filename, (int64_t) pid, status, (int64_t)uptime);
3943 /* Turn off any more restarts */
3944 ffserver_free_child_args(&feed->child_argv);
3948 need_to_start_children = 1;
3951 static void opt_debug(void)
3954 snprintf(config.logfilename, sizeof(config.logfilename), "-");
3957 void show_help_default(const char *opt, const char *arg)
3959 printf("usage: ffserver [options]\n"
3960 "Hyper fast multi format Audio/Video streaming server\n");
3962 show_help_options(options, "Main options:", 0, 0, 0);
3965 static const OptionDef options[] = {
3966 #include "cmdutils_common_opts.h"
3967 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
3968 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
3969 { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
3973 int main(int argc, char **argv)
3975 struct sigaction sigact = { { 0 } };
3977 int ret = EXIT_FAILURE;
3981 config.filename = av_strdup("/etc/ffserver.conf");
3983 parse_loglevel(argc, argv, options);
3985 avformat_network_init();
3987 show_banner(argc, argv, options);
3989 my_program_name = argv[0];
3991 parse_options(NULL, argc, argv, options, NULL);
3993 unsetenv("http_proxy"); /* Kill the http_proxy */
3995 av_lfg_init(&random_state, av_get_random_seed());
3997 sigact.sa_handler = handle_child_exit;
3998 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
3999 sigaction(SIGCHLD, &sigact, 0);
4001 if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
4002 fprintf(stderr, "Error reading configuration file '%s': %s\n",
4003 config.filename, av_err2str(cfg_parsed));
4007 /* open log file if needed */
4008 if (config.logfilename[0] != '\0') {
4009 if (!strcmp(config.logfilename, "-"))
4012 logfile = fopen(config.logfilename, "a");
4013 av_log_set_callback(http_av_log);
4016 build_file_streams();
4018 if (build_feed_streams() < 0) {
4019 http_log("Could not setup feed streams\n");
4023 compute_bandwidth();
4026 signal(SIGPIPE, SIG_IGN);
4028 if (http_server() < 0) {
4029 http_log("Could not start server\n");
4036 av_freep (&config.filename);
4037 avformat_network_deinit();