2 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * multiple format streaming server based on the FFmpeg libraries
28 #define closesocket close
33 #include "libavformat/avformat.h"
34 /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
35 #include "libavformat/ffm.h"
36 #include "libavformat/network.h"
37 #include "libavformat/os_support.h"
38 #include "libavformat/rtpdec.h"
39 #include "libavformat/rtpproto.h"
40 #include "libavformat/rtsp.h"
41 #include "libavformat/rtspcodes.h"
42 #include "libavformat/avio_internal.h"
43 #include "libavformat/internal.h"
44 #include "libavformat/url.h"
46 #include "libavutil/avassert.h"
47 #include "libavutil/avstring.h"
48 #include "libavutil/lfg.h"
49 #include "libavutil/dict.h"
50 #include "libavutil/intreadwrite.h"
51 #include "libavutil/mathematics.h"
52 #include "libavutil/random_seed.h"
53 #include "libavutil/parseutils.h"
54 #include "libavutil/opt.h"
55 #include "libavutil/time.h"
62 #include <sys/ioctl.h>
72 #include "ffserver_config.h"
74 #define PATH_LENGTH 1024
76 const char program_name[] = "ffserver";
77 const int program_birth_year = 2000;
79 static const OptionDef options[];
82 HTTPSTATE_WAIT_REQUEST,
83 HTTPSTATE_SEND_HEADER,
84 HTTPSTATE_SEND_DATA_HEADER,
85 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
86 HTTPSTATE_SEND_DATA_TRAILER,
87 HTTPSTATE_RECEIVE_DATA,
88 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
91 RTSPSTATE_WAIT_REQUEST,
93 RTSPSTATE_SEND_PACKET,
96 static const char * const http_state[] = {
112 #define IOBUFFER_INIT_SIZE 8192
114 /* timeouts are in ms */
115 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
116 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
118 #define SYNC_TIMEOUT (10 * 1000)
120 typedef struct RTSPActionServerSetup {
122 char transport_option[512];
123 } RTSPActionServerSetup;
126 int64_t count1, count2;
127 int64_t time1, time2;
130 /* context associated with one connection */
131 typedef struct HTTPContext {
132 enum HTTPState state;
133 int fd; /* socket file descriptor */
134 struct sockaddr_in from_addr; /* origin */
135 struct pollfd *poll_entry; /* used when polling */
137 uint8_t *buffer_ptr, *buffer_end;
140 int chunked_encoding;
141 int chunk_size; /* 0 if it needs to be read */
142 struct HTTPContext *next;
143 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
147 /* input format handling */
148 AVFormatContext *fmt_in;
149 int64_t start_time; /* In milliseconds - this wraps fairly often */
150 int64_t first_pts; /* initial pts value */
151 int64_t cur_pts; /* current pts value from the stream in us */
152 int64_t cur_frame_duration; /* duration of the current frame in us */
153 int cur_frame_bytes; /* output frame size, needed to compute
154 the time at which we send each
156 int pts_stream_index; /* stream we choose as clock reference */
157 int64_t cur_clock; /* current clock reference value in us */
158 /* output format handling */
159 struct FFServerStream *stream;
160 /* -1 is invalid stream */
161 int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
162 int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
164 AVFormatContext fmt_ctx; /* instance of FFServerStream for one user */
165 int last_packet_sent; /* true if last data packet was sent */
167 DataRateData datarate;
174 int is_packetized; /* if true, the stream is packetized */
175 int packet_stream_index; /* current stream for output in state machine */
177 /* RTSP state specific */
178 uint8_t *pb_buffer; /* XXX: use that in all the code */
180 int seq; /* RTSP sequence number */
182 /* RTP state specific */
183 enum RTSPLowerTransport rtp_protocol;
184 char session_id[32]; /* session id */
185 AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
187 /* RTP/UDP specific */
188 URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
190 /* RTP/TCP specific */
191 struct HTTPContext *rtsp_c;
192 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
195 typedef struct FeedData {
196 long long data_count;
197 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
200 static HTTPContext *first_http_ctx;
202 static FFServerConfig config = {
203 .nb_max_http_connections = 2000,
204 .nb_max_connections = 5,
205 .max_bandwidth = 1000,
209 static void new_connection(int server_fd, int is_rtsp);
210 static void close_connection(HTTPContext *c);
213 static int handle_connection(HTTPContext *c);
214 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
215 static void compute_status(HTTPContext *c);
216 static int open_input_stream(HTTPContext *c, const char *info);
217 static int http_parse_request(HTTPContext *c);
218 static int http_send_data(HTTPContext *c);
219 static int http_start_receive_data(HTTPContext *c);
220 static int http_receive_data(HTTPContext *c);
223 static int rtsp_parse_request(HTTPContext *c);
224 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
225 static void rtsp_cmd_options(HTTPContext *c, const char *url);
226 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
227 RTSPMessageHeader *h);
228 static void rtsp_cmd_play(HTTPContext *c, const char *url,
229 RTSPMessageHeader *h);
230 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
231 RTSPMessageHeader *h, int pause_only);
234 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
235 struct in_addr my_ip);
238 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
239 FFServerStream *stream,
240 const char *session_id,
241 enum RTSPLowerTransport rtp_protocol);
242 static int rtp_new_av_stream(HTTPContext *c,
243 int stream_index, struct sockaddr_in *dest_addr,
244 HTTPContext *rtsp_c);
246 static inline int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs,
249 static const char *my_program_name;
251 static int no_launch;
252 static int need_to_start_children;
254 /* maximum number of simultaneous HTTP connections */
255 static unsigned int nb_connections;
257 static uint64_t current_bandwidth;
259 /* Making this global saves on passing it around everywhere */
260 static int64_t cur_time;
262 static AVLFG random_state;
264 static FILE *logfile = NULL;
266 static void htmlstrip(char *s) {
268 s += strspn(s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,. ");
274 static int64_t ffm_read_write_index(int fd)
278 if (lseek(fd, 8, SEEK_SET) < 0)
280 if (read(fd, buf, 8) != 8)
285 static int ffm_write_write_index(int fd, int64_t pos)
291 buf[i] = (pos >> (56 - i * 8)) & 0xff;
292 if (lseek(fd, 8, SEEK_SET) < 0)
294 if (write(fd, buf, 8) != 8)
303 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
306 av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
307 av_opt_set_int(s, "write_index", pos, AV_OPT_SEARCH_CHILDREN);
308 av_opt_set_int(s, "file_size", file_size, AV_OPT_SEARCH_CHILDREN);
311 static char *ctime1(char *buf2, size_t buf_size)
322 av_strlcpy(buf2, p, buf_size);
323 p = buf2 + strlen(buf2) - 1;
329 static void http_vlog(const char *fmt, va_list vargs)
331 static int print_prefix = 1;
338 ctime1(buf, sizeof(buf));
339 fprintf(logfile, "%s ", buf);
341 print_prefix = strstr(fmt, "\n") != NULL;
342 vfprintf(logfile, fmt, vargs);
347 __attribute__ ((format (printf, 1, 2)))
349 static void http_log(const char *fmt, ...)
352 va_start(vargs, fmt);
353 http_vlog(fmt, vargs);
357 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
359 static int print_prefix = 1;
360 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
361 if (level > av_log_get_level())
363 if (print_prefix && avc)
364 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
365 print_prefix = strstr(fmt, "\n") != NULL;
366 http_vlog(fmt, vargs);
369 static void log_connection(HTTPContext *c)
374 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
375 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
376 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
379 static void update_datarate(DataRateData *drd, int64_t count)
381 if (!drd->time1 && !drd->count1) {
382 drd->time1 = drd->time2 = cur_time;
383 drd->count1 = drd->count2 = count;
384 } else if (cur_time - drd->time2 > 5000) {
385 drd->time1 = drd->time2;
386 drd->count1 = drd->count2;
387 drd->time2 = cur_time;
392 /* In bytes per second */
393 static int compute_datarate(DataRateData *drd, int64_t count)
395 if (cur_time == drd->time1)
398 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
402 static void start_children(FFServerStream *feed)
412 cmd_length = strlen(my_program_name);
415 * FIXME: WIP Safeguard. Remove after clearing all harcoded
416 * '1024' path lengths
418 if (cmd_length > PATH_LENGTH - 1) {
419 http_log("Could not start children. Command line: '%s' exceeds "
420 "path length limit (%d)\n", my_program_name, PATH_LENGTH);
424 pathname = av_strdup (my_program_name);
426 http_log("Could not allocate memory for children cmd line\n");
429 /* replace "ffserver" with "ffmpeg" in the path of current
430 * program. Ignore user provided path */
432 slash = strrchr(pathname, '/');
437 strcpy(slash, "ffmpeg");
439 for (; feed; feed = feed->next) {
441 if (!feed->child_argv || feed->pid)
444 feed->pid_start = time(0);
448 http_log("Unable to create children: %s\n", strerror(errno));
458 http_log("Launch command line: ");
459 http_log("%s ", pathname);
461 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
462 http_log("%s ", feed->child_argv[i]);
465 for (i = 3; i < 256; i++)
469 if (!freopen("/dev/null", "r", stdin))
470 http_log("failed to redirect STDIN to /dev/null\n;");
471 if (!freopen("/dev/null", "w", stdout))
472 http_log("failed to redirect STDOUT to /dev/null\n;");
473 if (!freopen("/dev/null", "w", stderr))
474 http_log("failed to redirect STDERR to /dev/null\n;");
477 signal(SIGPIPE, SIG_DFL);
478 execvp(pathname, feed->child_argv);
485 /* open a listening socket */
486 static int socket_open_listen(struct sockaddr_in *my_addr)
490 server_fd = socket(AF_INET,SOCK_STREAM,0);
497 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
498 av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
500 my_addr->sin_family = AF_INET;
501 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
503 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
504 ntohs(my_addr->sin_port));
509 if (listen (server_fd, 5) < 0) {
514 if (ff_socket_nonblock(server_fd, 1) < 0)
515 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
520 closesocket(server_fd);
524 /* start all multicast streams */
525 static void start_multicast(void)
527 FFServerStream *stream;
530 struct sockaddr_in dest_addr = {0};
531 int default_port, stream_index;
532 unsigned int random0, random1;
535 for(stream = config.first_stream; stream; stream = stream->next) {
537 if (!stream->is_multicast)
540 random0 = av_lfg_get(&random_state);
541 random1 = av_lfg_get(&random_state);
543 /* open the RTP connection */
544 snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
546 /* choose a port if none given */
547 if (stream->multicast_port == 0) {
548 stream->multicast_port = default_port;
552 dest_addr.sin_family = AF_INET;
553 dest_addr.sin_addr = stream->multicast_ip;
554 dest_addr.sin_port = htons(stream->multicast_port);
556 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
557 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
561 if (open_input_stream(rtp_c, "") < 0) {
562 http_log("Could not open input stream for stream '%s'\n",
567 /* open each RTP stream */
568 for(stream_index = 0; stream_index < stream->nb_streams;
570 dest_addr.sin_port = htons(stream->multicast_port +
572 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
575 http_log("Could not open output stream '%s/streamid=%d'\n",
576 stream->filename, stream_index);
580 rtp_c->state = HTTPSTATE_SEND_DATA;
584 /* main loop of the HTTP server */
585 static int http_server(void)
587 int server_fd = 0, rtsp_server_fd = 0;
589 struct pollfd *poll_table, *poll_entry;
590 HTTPContext *c, *c_next;
592 poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
593 sizeof(*poll_table));
595 http_log("Impossible to allocate a poll table handling %d "
596 "connections.\n", config.nb_max_http_connections);
600 if (config.http_addr.sin_port) {
601 server_fd = socket_open_listen(&config.http_addr);
606 if (config.rtsp_addr.sin_port) {
607 rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
608 if (rtsp_server_fd < 0) {
609 closesocket(server_fd);
614 if (!rtsp_server_fd && !server_fd) {
615 http_log("HTTP and RTSP disabled.\n");
619 http_log("FFserver started.\n");
621 start_children(config.first_feed);
626 poll_entry = poll_table;
628 poll_entry->fd = server_fd;
629 poll_entry->events = POLLIN;
632 if (rtsp_server_fd) {
633 poll_entry->fd = rtsp_server_fd;
634 poll_entry->events = POLLIN;
638 /* wait for events on each HTTP handle */
645 case HTTPSTATE_SEND_HEADER:
646 case RTSPSTATE_SEND_REPLY:
647 case RTSPSTATE_SEND_PACKET:
648 c->poll_entry = poll_entry;
650 poll_entry->events = POLLOUT;
653 case HTTPSTATE_SEND_DATA_HEADER:
654 case HTTPSTATE_SEND_DATA:
655 case HTTPSTATE_SEND_DATA_TRAILER:
656 if (!c->is_packetized) {
657 /* for TCP, we output as much as we can
658 * (may need to put a limit) */
659 c->poll_entry = poll_entry;
661 poll_entry->events = POLLOUT;
664 /* when ffserver is doing the timing, we work by
665 * looking at which packet needs to be sent every
666 * 10 ms (one tick wait XXX: 10 ms assumed) */
671 case HTTPSTATE_WAIT_REQUEST:
672 case HTTPSTATE_RECEIVE_DATA:
673 case HTTPSTATE_WAIT_FEED:
674 case RTSPSTATE_WAIT_REQUEST:
675 /* need to catch errors */
676 c->poll_entry = poll_entry;
678 poll_entry->events = POLLIN;/* Maybe this will work */
682 c->poll_entry = NULL;
688 /* wait for an event on one connection. We poll at least every
689 * second to handle timeouts */
691 ret = poll(poll_table, poll_entry - poll_table, delay);
692 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
693 ff_neterrno() != AVERROR(EINTR)) {
698 cur_time = av_gettime() / 1000;
700 if (need_to_start_children) {
701 need_to_start_children = 0;
702 start_children(config.first_feed);
705 /* now handle the events */
706 for(c = first_http_ctx; c; c = c_next) {
708 if (handle_connection(c) < 0) {
710 /* close and free the connection */
715 poll_entry = poll_table;
717 /* new HTTP connection request ? */
718 if (poll_entry->revents & POLLIN)
719 new_connection(server_fd, 0);
722 if (rtsp_server_fd) {
723 /* new RTSP connection request ? */
724 if (poll_entry->revents & POLLIN)
725 new_connection(rtsp_server_fd, 1);
734 /* start waiting for a new HTTP/RTSP request */
735 static void start_wait_request(HTTPContext *c, int is_rtsp)
737 c->buffer_ptr = c->buffer;
738 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
740 c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
741 c->timeout = cur_time +
742 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
745 static void http_send_too_busy_reply(int fd)
748 int len = snprintf(buffer, sizeof(buffer),
749 "HTTP/1.0 503 Server too busy\r\n"
750 "Content-type: text/html\r\n"
752 "<html><head><title>Too busy</title></head><body>\r\n"
753 "<p>The server is too busy to serve your request at "
755 "<p>The number of current connections is %u, and this "
756 "exceeds the limit of %u.</p>\r\n"
757 "</body></html>\r\n",
758 nb_connections, config.nb_max_connections);
759 av_assert0(len < sizeof(buffer));
760 if (send(fd, buffer, len, 0) < len)
761 av_log(NULL, AV_LOG_WARNING,
762 "Could not send too-busy reply, send() failed\n");
766 static void new_connection(int server_fd, int is_rtsp)
768 struct sockaddr_in from_addr;
771 HTTPContext *c = NULL;
773 len = sizeof(from_addr);
774 fd = accept(server_fd, (struct sockaddr *)&from_addr,
777 http_log("error during accept %s\n", strerror(errno));
780 if (ff_socket_nonblock(fd, 1) < 0)
781 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
783 if (nb_connections >= config.nb_max_connections) {
784 http_send_too_busy_reply(fd);
788 /* add a new connection */
789 c = av_mallocz(sizeof(HTTPContext));
794 c->poll_entry = NULL;
795 c->from_addr = from_addr;
796 c->buffer_size = IOBUFFER_INIT_SIZE;
797 c->buffer = av_malloc(c->buffer_size);
801 c->next = first_http_ctx;
805 start_wait_request(c, is_rtsp);
811 av_freep(&c->buffer);
817 static void close_connection(HTTPContext *c)
819 HTTPContext **cp, *c1;
821 AVFormatContext *ctx;
824 /* remove connection from list */
825 cp = &first_http_ctx;
834 /* remove references, if any (XXX: do it faster) */
835 for(c1 = first_http_ctx; c1; c1 = c1->next) {
840 /* remove connection associated resources */
844 /* close each frame parser */
845 for(i=0;i<c->fmt_in->nb_streams;i++) {
846 st = c->fmt_in->streams[i];
847 if (st->codec->codec)
848 avcodec_close(st->codec);
850 avformat_close_input(&c->fmt_in);
853 /* free RTP output streams if any */
856 nb_streams = c->stream->nb_streams;
858 for(i=0;i<nb_streams;i++) {
861 av_write_trailer(ctx);
862 av_dict_free(&ctx->metadata);
863 av_freep(&ctx->streams[0]);
866 ffurl_close(c->rtp_handles[i]);
871 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
873 if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
874 av_write_trailer(ctx);
875 av_freep(&c->pb_buffer);
876 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
880 for(i=0; i<ctx->nb_streams; i++)
881 av_freep(&ctx->streams[i]);
882 av_freep(&ctx->streams);
883 av_freep(&ctx->priv_data);
885 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
886 current_bandwidth -= c->stream->bandwidth;
888 /* signal that there is no feed if we are the feeder socket */
889 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
890 c->stream->feed_opened = 0;
894 av_freep(&c->pb_buffer);
895 av_freep(&c->packet_buffer);
896 av_freep(&c->buffer);
901 static int handle_connection(HTTPContext *c)
907 case HTTPSTATE_WAIT_REQUEST:
908 case RTSPSTATE_WAIT_REQUEST:
910 if ((c->timeout - cur_time) < 0)
912 if (c->poll_entry->revents & (POLLERR | POLLHUP))
915 /* no need to read if no events */
916 if (!(c->poll_entry->revents & POLLIN))
920 if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
924 if (ff_neterrno() != AVERROR(EAGAIN) &&
925 ff_neterrno() != AVERROR(EINTR))
929 /* search for end of request. */
930 c->buffer_ptr += len;
932 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
933 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
934 /* request found : parse it and reply */
935 if (c->state == HTTPSTATE_WAIT_REQUEST)
936 ret = http_parse_request(c);
938 ret = rtsp_parse_request(c);
942 } else if (ptr >= c->buffer_end) {
943 /* request too long: cannot do anything */
945 } else goto read_loop;
949 case HTTPSTATE_SEND_HEADER:
950 if (c->poll_entry->revents & (POLLERR | POLLHUP))
953 /* no need to write if no events */
954 if (!(c->poll_entry->revents & POLLOUT))
956 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
958 if (ff_neterrno() != AVERROR(EAGAIN) &&
959 ff_neterrno() != AVERROR(EINTR)) {
960 goto close_connection;
964 c->buffer_ptr += len;
966 c->stream->bytes_served += len;
967 c->data_count += len;
968 if (c->buffer_ptr >= c->buffer_end) {
969 av_freep(&c->pb_buffer);
973 /* all the buffer was sent : synchronize to the incoming
975 c->state = HTTPSTATE_SEND_DATA_HEADER;
976 c->buffer_ptr = c->buffer_end = c->buffer;
980 case HTTPSTATE_SEND_DATA:
981 case HTTPSTATE_SEND_DATA_HEADER:
982 case HTTPSTATE_SEND_DATA_TRAILER:
983 /* for packetized output, we consider we can always write (the
984 * input streams set the speed). It may be better to verify
985 * that we do not rely too much on the kernel queues */
986 if (!c->is_packetized) {
987 if (c->poll_entry->revents & (POLLERR | POLLHUP))
990 /* no need to read if no events */
991 if (!(c->poll_entry->revents & POLLOUT))
994 if (http_send_data(c) < 0)
996 /* close connection if trailer sent */
997 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
999 /* Check if it is a single jpeg frame 123 */
1000 if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
1001 close_connection(c);
1004 case HTTPSTATE_RECEIVE_DATA:
1005 /* no need to read if no events */
1006 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1008 if (!(c->poll_entry->revents & POLLIN))
1010 if (http_receive_data(c) < 0)
1013 case HTTPSTATE_WAIT_FEED:
1014 /* no need to read if no events */
1015 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1018 /* nothing to do, we'll be waken up by incoming feed packets */
1021 case RTSPSTATE_SEND_REPLY:
1022 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1023 goto close_connection;
1024 /* no need to write if no events */
1025 if (!(c->poll_entry->revents & POLLOUT))
1027 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1029 if (ff_neterrno() != AVERROR(EAGAIN) &&
1030 ff_neterrno() != AVERROR(EINTR)) {
1031 goto close_connection;
1035 c->buffer_ptr += len;
1036 c->data_count += len;
1037 if (c->buffer_ptr >= c->buffer_end) {
1038 /* all the buffer was sent : wait for a new request */
1039 av_freep(&c->pb_buffer);
1040 start_wait_request(c, 1);
1043 case RTSPSTATE_SEND_PACKET:
1044 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1045 av_freep(&c->packet_buffer);
1048 /* no need to write if no events */
1049 if (!(c->poll_entry->revents & POLLOUT))
1051 len = send(c->fd, c->packet_buffer_ptr,
1052 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1054 if (ff_neterrno() != AVERROR(EAGAIN) &&
1055 ff_neterrno() != AVERROR(EINTR)) {
1056 /* error : close connection */
1057 av_freep(&c->packet_buffer);
1062 c->packet_buffer_ptr += len;
1063 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1064 /* all the buffer was sent : wait for a new request */
1065 av_freep(&c->packet_buffer);
1066 c->state = RTSPSTATE_WAIT_REQUEST;
1069 case HTTPSTATE_READY:
1078 av_freep(&c->pb_buffer);
1082 static int extract_rates(char *rates, int ratelen, const char *request)
1086 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1087 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1088 const char *q = p + 7;
1090 while (*q && *q != '\n' && av_isspace(*q))
1093 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1099 memset(rates, 0xff, ratelen);
1102 while (*q && *q != '\n' && *q != ':')
1105 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1109 if (stream_no < ratelen && stream_no >= 0)
1110 rates[stream_no] = rate_no;
1112 while (*q && *q != '\n' && !av_isspace(*q))
1119 p = strchr(p, '\n');
1129 static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec,
1133 int best_bitrate = 100000000;
1136 for (i = 0; i < feed->nb_streams; i++) {
1137 AVCodecContext *feed_codec = feed->streams[i]->codec;
1139 if (feed_codec->codec_id != codec->codec_id ||
1140 feed_codec->sample_rate != codec->sample_rate ||
1141 feed_codec->width != codec->width ||
1142 feed_codec->height != codec->height)
1145 /* Potential stream */
1147 /* We want the fastest stream less than bit_rate, or the slowest
1148 * faster than bit_rate
1151 if (feed_codec->bit_rate <= bit_rate) {
1152 if (best_bitrate > bit_rate ||
1153 feed_codec->bit_rate > best_bitrate) {
1154 best_bitrate = feed_codec->bit_rate;
1159 if (feed_codec->bit_rate < best_bitrate) {
1160 best_bitrate = feed_codec->bit_rate;
1167 static int modify_current_stream(HTTPContext *c, char *rates)
1170 FFServerStream *req = c->stream;
1171 int action_required = 0;
1173 /* Not much we can do for a feed */
1177 for (i = 0; i < req->nb_streams; i++) {
1178 AVCodecContext *codec = req->streams[i]->codec;
1182 c->switch_feed_streams[i] = req->feed_streams[i];
1185 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1188 /* Wants off or slow */
1189 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1191 /* This doesn't work well when it turns off the only stream! */
1192 c->switch_feed_streams[i] = -2;
1193 c->feed_streams[i] = -2;
1198 if (c->switch_feed_streams[i] >= 0 &&
1199 c->switch_feed_streams[i] != c->feed_streams[i]) {
1200 action_required = 1;
1204 return action_required;
1207 static void get_word(char *buf, int buf_size, const char **pp)
1213 p += strspn(p, SPACE_CHARS);
1215 while (!av_isspace(*p) && *p != '\0') {
1216 if ((q - buf) < buf_size - 1)
1225 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1231 FFServerIPAddressACL *acl = NULL;
1235 f = fopen(stream->dynamic_acl, "r");
1237 perror(stream->dynamic_acl);
1241 acl = av_mallocz(sizeof(FFServerIPAddressACL));
1248 while (fgets(line, sizeof(line), f)) {
1251 while (av_isspace(*p))
1253 if (*p == '\0' || *p == '#')
1255 ffserver_get_arg(cmd, sizeof(cmd), &p);
1257 if (!av_strcasecmp(cmd, "ACL"))
1258 ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1266 static void free_acl_list(FFServerIPAddressACL *in_acl)
1268 FFServerIPAddressACL *pacl, *pacl2;
1278 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1280 enum FFServerIPAddressAction last_action = IP_DENY;
1281 FFServerIPAddressACL *acl;
1282 struct in_addr *src = &c->from_addr.sin_addr;
1283 unsigned long src_addr = src->s_addr;
1285 for (acl = in_acl; acl; acl = acl->next) {
1286 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1287 return (acl->action == IP_ALLOW) ? 1 : 0;
1288 last_action = acl->action;
1291 /* Nothing matched, so return not the last action */
1292 return (last_action == IP_DENY) ? 1 : 0;
1295 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1298 FFServerIPAddressACL *acl;
1300 /* if stream->acl is null validate_acl_list will return 1 */
1301 ret = validate_acl_list(stream->acl, c);
1303 if (stream->dynamic_acl[0]) {
1304 acl = parse_dynamic_acl(stream, c);
1305 ret = validate_acl_list(acl, c);
1313 * compute the real filename of a file by matching it without its
1314 * extensions to all the stream's filenames
1316 static void compute_real_filename(char *filename, int max_size)
1321 FFServerStream *stream;
1323 av_strlcpy(file1, filename, sizeof(file1));
1324 p = strrchr(file1, '.');
1327 for(stream = config.first_stream; stream; stream = stream->next) {
1328 av_strlcpy(file2, stream->filename, sizeof(file2));
1329 p = strrchr(file2, '.');
1332 if (!strcmp(file1, file2)) {
1333 av_strlcpy(filename, stream->filename, max_size);
1348 /* parse HTTP request and prepare header */
1349 static int http_parse_request(HTTPContext *c)
1353 enum RedirType redir_type;
1355 char info[1024], filename[1024];
1359 const char *mime_type;
1360 FFServerStream *stream;
1363 const char *useragent = 0;
1366 get_word(cmd, sizeof(cmd), &p);
1367 av_strlcpy(c->method, cmd, sizeof(c->method));
1369 if (!strcmp(cmd, "GET"))
1371 else if (!strcmp(cmd, "POST"))
1376 get_word(url, sizeof(url), &p);
1377 av_strlcpy(c->url, url, sizeof(c->url));
1379 get_word(protocol, sizeof(protocol), (const char **)&p);
1380 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1383 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1386 http_log("%s - - New connection: %s %s\n",
1387 inet_ntoa(c->from_addr.sin_addr), cmd, url);
1389 /* find the filename and the optional info string in the request */
1390 p1 = strchr(url, '?');
1392 av_strlcpy(info, p1, sizeof(info));
1397 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1399 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1400 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1402 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1406 p = strchr(p, '\n');
1413 redir_type = REDIR_NONE;
1414 if (av_match_ext(filename, "asx")) {
1415 redir_type = REDIR_ASX;
1416 filename[strlen(filename)-1] = 'f';
1417 } else if (av_match_ext(filename, "asf") &&
1418 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1419 /* if this isn't WMP or lookalike, return the redirector file */
1420 redir_type = REDIR_ASF;
1421 } else if (av_match_ext(filename, "rpm,ram")) {
1422 redir_type = REDIR_RAM;
1423 strcpy(filename + strlen(filename)-2, "m");
1424 } else if (av_match_ext(filename, "rtsp")) {
1425 redir_type = REDIR_RTSP;
1426 compute_real_filename(filename, sizeof(filename) - 1);
1427 } else if (av_match_ext(filename, "sdp")) {
1428 redir_type = REDIR_SDP;
1429 compute_real_filename(filename, sizeof(filename) - 1);
1432 /* "redirect" request to index.html */
1433 if (!strlen(filename))
1434 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1436 stream = config.first_stream;
1438 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1440 stream = stream->next;
1443 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1444 http_log("File '%s' not found\n", url);
1449 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1450 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1452 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1453 c->http_error = 301;
1455 snprintf(q, c->buffer_size,
1456 "HTTP/1.0 301 Moved\r\n"
1458 "Content-type: text/html\r\n"
1460 "<html><head><title>Moved</title></head><body>\r\n"
1461 "You should be <a href=\"%s\">redirected</a>.\r\n"
1462 "</body></html>\r\n",
1463 stream->feed_filename, stream->feed_filename);
1465 /* prepare output buffer */
1466 c->buffer_ptr = c->buffer;
1468 c->state = HTTPSTATE_SEND_HEADER;
1472 /* If this is WMP, get the rate information */
1473 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1474 if (modify_current_stream(c, ratebuf)) {
1475 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1476 if (c->switch_feed_streams[i] >= 0)
1477 c->switch_feed_streams[i] = -1;
1482 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1483 current_bandwidth += stream->bandwidth;
1485 /* If already streaming this feed, do not let another feeder start */
1486 if (stream->feed_opened) {
1487 snprintf(msg, sizeof(msg), "This feed is already being received.");
1488 http_log("Feed '%s' already being received\n", stream->feed_filename);
1492 if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1493 c->http_error = 503;
1495 snprintf(q, c->buffer_size,
1496 "HTTP/1.0 503 Server too busy\r\n"
1497 "Content-type: text/html\r\n"
1499 "<html><head><title>Too busy</title></head><body>\r\n"
1500 "<p>The server is too busy to serve your request at "
1501 "this time.</p>\r\n"
1502 "<p>The bandwidth being served (including your stream) "
1503 "is %"PRIu64"kbit/s, and this exceeds the limit of "
1504 "%"PRIu64"kbit/s.</p>\r\n"
1505 "</body></html>\r\n",
1506 current_bandwidth, config.max_bandwidth);
1508 /* prepare output buffer */
1509 c->buffer_ptr = c->buffer;
1511 c->state = HTTPSTATE_SEND_HEADER;
1515 if (redir_type != REDIR_NONE) {
1516 const char *hostinfo = 0;
1518 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1519 if (av_strncasecmp(p, "Host:", 5) == 0) {
1523 p = strchr(p, '\n');
1534 while (av_isspace(*hostinfo))
1537 eoh = strchr(hostinfo, '\n');
1539 if (eoh[-1] == '\r')
1542 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1543 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1544 hostbuf[eoh - hostinfo] = 0;
1546 c->http_error = 200;
1548 switch(redir_type) {
1550 snprintf(q, c->buffer_size,
1551 "HTTP/1.0 200 ASX Follows\r\n"
1552 "Content-type: video/x-ms-asf\r\n"
1554 "<ASX Version=\"3\">\r\n"
1555 //"<!-- Autogenerated by ffserver -->\r\n"
1556 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1557 "</ASX>\r\n", hostbuf, filename, info);
1561 snprintf(q, c->buffer_size,
1562 "HTTP/1.0 200 RAM Follows\r\n"
1563 "Content-type: audio/x-pn-realaudio\r\n"
1565 "# Autogenerated by ffserver\r\n"
1566 "http://%s/%s%s\r\n", hostbuf, filename, info);
1570 snprintf(q, c->buffer_size,
1571 "HTTP/1.0 200 ASF Redirect follows\r\n"
1572 "Content-type: video/x-ms-asf\r\n"
1575 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1580 char hostname[256], *p;
1581 /* extract only hostname */
1582 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1583 p = strrchr(hostname, ':');
1586 snprintf(q, c->buffer_size,
1587 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1588 /* XXX: incorrect MIME type ? */
1589 "Content-type: application/x-rtsp\r\n"
1591 "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1600 struct sockaddr_in my_addr;
1602 snprintf(q, c->buffer_size,
1603 "HTTP/1.0 200 OK\r\n"
1604 "Content-type: application/sdp\r\n"
1608 len = sizeof(my_addr);
1610 /* XXX: Should probably fail? */
1611 if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1612 http_log("getsockname() failed\n");
1614 /* XXX: should use a dynamic buffer */
1615 sdp_data_size = prepare_sdp_description(stream,
1618 if (sdp_data_size > 0) {
1619 memcpy(q, sdp_data, sdp_data_size);
1631 /* prepare output buffer */
1632 c->buffer_ptr = c->buffer;
1634 c->state = HTTPSTATE_SEND_HEADER;
1640 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1644 stream->conns_served++;
1646 /* XXX: add there authenticate and IP match */
1649 /* if post, it means a feed is being sent */
1650 if (!stream->is_feed) {
1651 /* However it might be a status report from WMP! Let us log the
1652 * data as it might come handy one day. */
1653 const char *logline = 0;
1656 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1657 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1661 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1662 client_id = strtol(p + 18, 0, 10);
1663 p = strchr(p, '\n');
1671 char *eol = strchr(logline, '\n');
1676 if (eol[-1] == '\r')
1678 http_log("%.*s\n", (int) (eol - logline), logline);
1679 c->suppress_log = 1;
1684 http_log("\nGot request:\n%s\n", c->buffer);
1687 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1690 /* Now we have to find the client_id */
1691 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1692 if (wmpc->wmp_client_id == client_id)
1696 if (wmpc && modify_current_stream(wmpc, ratebuf))
1697 wmpc->switch_pending = 1;
1700 snprintf(msg, sizeof(msg), "POST command not handled");
1704 if (http_start_receive_data(c) < 0) {
1705 snprintf(msg, sizeof(msg), "could not open feed");
1709 c->state = HTTPSTATE_RECEIVE_DATA;
1714 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1715 http_log("\nGot request:\n%s\n", c->buffer);
1718 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1721 /* open input stream */
1722 if (open_input_stream(c, info) < 0) {
1723 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1727 /* prepare HTTP header */
1729 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1730 mime_type = c->stream->fmt->mime_type;
1732 mime_type = "application/x-octet-stream";
1733 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1735 /* for asf, we need extra headers */
1736 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1737 /* Need to allocate a client id */
1739 c->wmp_client_id = av_lfg_get(&random_state);
1741 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);
1743 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1744 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1745 q = c->buffer + strlen(c->buffer);
1747 /* prepare output buffer */
1749 c->buffer_ptr = c->buffer;
1751 c->state = HTTPSTATE_SEND_HEADER;
1754 c->http_error = 404;
1757 snprintf(q, c->buffer_size,
1758 "HTTP/1.0 404 Not Found\r\n"
1759 "Content-type: text/html\r\n"
1762 "<head><title>404 Not Found</title></head>\n"
1766 /* prepare output buffer */
1767 c->buffer_ptr = c->buffer;
1769 c->state = HTTPSTATE_SEND_HEADER;
1773 /* horrible: we use this value to avoid
1774 * going to the send data state */
1775 c->http_error = 200;
1776 c->state = HTTPSTATE_SEND_HEADER;
1780 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1782 static const char suffix[] = " kMGTP";
1785 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1787 avio_printf(pb, "%"PRId64"%c", count, *s);
1790 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1793 const char *type = "unknown";
1794 char parameters[64];
1798 stream_no = stream->nb_streams;
1800 avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
1801 "type<th>kbit/s<th align=left>codec<th align=left>"
1804 for (i = 0; i < stream_no; i++) {
1805 st = stream->streams[i];
1806 codec = avcodec_find_encoder(st->codec->codec_id);
1810 switch(st->codec->codec_type) {
1811 case AVMEDIA_TYPE_AUDIO:
1813 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1814 st->codec->channels, st->codec->sample_rate);
1816 case AVMEDIA_TYPE_VIDEO:
1818 snprintf(parameters, sizeof(parameters),
1819 "%dx%d, q=%d-%d, fps=%d", st->codec->width,
1820 st->codec->height, st->codec->qmin, st->codec->qmax,
1821 st->codec->time_base.den / st->codec->time_base.num);
1827 avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
1829 i, type, (int64_t)st->codec->bit_rate/1000,
1830 codec ? codec->name : "", parameters);
1833 avio_printf(pb, "</table>\n");
1836 static void compute_status(HTTPContext *c)
1839 FFServerStream *stream;
1845 if (avio_open_dyn_buf(&pb) < 0) {
1846 /* XXX: return an error ? */
1847 c->buffer_ptr = c->buffer;
1848 c->buffer_end = c->buffer;
1852 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1853 avio_printf(pb, "Content-type: text/html\r\n");
1854 avio_printf(pb, "Pragma: no-cache\r\n");
1855 avio_printf(pb, "\r\n");
1857 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1858 if (c->stream->feed_filename[0])
1859 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1860 c->stream->feed_filename);
1861 avio_printf(pb, "</head>\n<body>");
1862 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1864 avio_printf(pb, "<h2>Available Streams</h2>\n");
1865 avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
1866 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");
1867 stream = config.first_stream;
1869 char sfilename[1024];
1872 if (stream->feed == stream) {
1873 stream = stream->next;
1877 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1878 eosf = sfilename + strlen(sfilename);
1879 if (eosf - sfilename >= 4) {
1880 if (strcmp(eosf - 4, ".asf") == 0)
1881 strcpy(eosf - 4, ".asx");
1882 else if (strcmp(eosf - 3, ".rm") == 0)
1883 strcpy(eosf - 3, ".ram");
1884 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1885 /* generate a sample RTSP director if
1886 * unicast. Generate an SDP redirector if
1888 eosf = strrchr(sfilename, '.');
1890 eosf = sfilename + strlen(sfilename);
1891 if (stream->is_multicast)
1892 strcpy(eosf, ".sdp");
1894 strcpy(eosf, ".rtsp");
1898 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1899 sfilename, stream->filename);
1900 avio_printf(pb, "<td align=right> %d <td align=right> ",
1901 stream->conns_served);
1902 fmt_bytecount(pb, stream->bytes_served);
1904 switch(stream->stream_type) {
1905 case STREAM_TYPE_LIVE: {
1906 int audio_bit_rate = 0;
1907 int video_bit_rate = 0;
1908 const char *audio_codec_name = "";
1909 const char *video_codec_name = "";
1910 const char *audio_codec_name_extra = "";
1911 const char *video_codec_name_extra = "";
1913 for(i=0;i<stream->nb_streams;i++) {
1914 AVStream *st = stream->streams[i];
1915 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1917 switch(st->codec->codec_type) {
1918 case AVMEDIA_TYPE_AUDIO:
1919 audio_bit_rate += st->codec->bit_rate;
1921 if (*audio_codec_name)
1922 audio_codec_name_extra = "...";
1923 audio_codec_name = codec->name;
1926 case AVMEDIA_TYPE_VIDEO:
1927 video_bit_rate += st->codec->bit_rate;
1929 if (*video_codec_name)
1930 video_codec_name_extra = "...";
1931 video_codec_name = codec->name;
1934 case AVMEDIA_TYPE_DATA:
1935 video_bit_rate += st->codec->bit_rate;
1942 avio_printf(pb, "<td align=center> %s <td align=right> %d "
1943 "<td align=right> %d <td> %s %s <td align=right> "
1945 stream->fmt->name, stream->bandwidth,
1946 video_bit_rate / 1000, video_codec_name,
1947 video_codec_name_extra, audio_bit_rate / 1000,
1948 audio_codec_name, audio_codec_name_extra);
1951 avio_printf(pb, "<td>%s", stream->feed->filename);
1953 avio_printf(pb, "<td>%s", stream->feed_filename);
1954 avio_printf(pb, "\n");
1958 avio_printf(pb, "<td align=center> - <td align=right> - "
1959 "<td align=right> - <td><td align=right> - <td>\n");
1962 stream = stream->next;
1964 avio_printf(pb, "</table>\n");
1966 stream = config.first_stream;
1969 if (stream->feed != stream) {
1970 stream = stream->next;
1974 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
1976 avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
1983 /* This is somewhat linux specific I guess */
1984 snprintf(ps_cmd, sizeof(ps_cmd),
1985 "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
1986 (int64_t) stream->pid);
1988 pid_stat = popen(ps_cmd, "r");
1993 if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
1994 avio_printf(pb, "Currently using %s%% of the cpu. "
1995 "Total time used %s.\n",
2003 avio_printf(pb, "<p>");
2006 print_stream_params(pb, stream);
2007 stream = stream->next;
2010 /* connection status */
2011 avio_printf(pb, "<h2>Connection Status</h2>\n");
2013 avio_printf(pb, "Number of connections: %d / %d<br>\n",
2014 nb_connections, config.nb_max_connections);
2016 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2017 current_bandwidth, config.max_bandwidth);
2019 avio_printf(pb, "<table>\n");
2020 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
2021 "bit/s<th>Actual bit/s<th>Bytes transferred\n");
2022 c1 = first_http_ctx;
2030 for (j = 0; j < c1->stream->nb_streams; j++) {
2031 if (!c1->stream->feed)
2032 bitrate += c1->stream->streams[j]->codec->bit_rate;
2033 else if (c1->feed_streams[j] >= 0)
2034 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
2039 p = inet_ntoa(c1->from_addr.sin_addr);
2040 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
2042 i, c1->stream ? c1->stream->filename : "",
2043 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
2044 c1->protocol, http_state[c1->state]);
2045 fmt_bytecount(pb, bitrate);
2046 avio_printf(pb, "<td align=right>");
2047 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2048 avio_printf(pb, "<td align=right>");
2049 fmt_bytecount(pb, c1->data_count);
2050 avio_printf(pb, "\n");
2053 avio_printf(pb, "</table>\n");
2058 avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
2059 avio_printf(pb, "</body>\n</html>\n");
2061 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2062 c->buffer_ptr = c->pb_buffer;
2063 c->buffer_end = c->pb_buffer + len;
2066 static int open_input_stream(HTTPContext *c, const char *info)
2069 char input_filename[1024];
2070 AVFormatContext *s = NULL;
2071 int buf_size, i, ret;
2074 /* find file name */
2075 if (c->stream->feed) {
2076 strcpy(input_filename, c->stream->feed->feed_filename);
2077 buf_size = FFM_PACKET_SIZE;
2078 /* compute position (absolute time) */
2079 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2080 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2081 http_log("Invalid date specification '%s' for stream\n", buf);
2084 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2085 int prebuffer = strtol(buf, 0, 10);
2086 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2088 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2090 strcpy(input_filename, c->stream->feed_filename);
2092 /* compute position (relative time) */
2093 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2094 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2095 http_log("Invalid date specification '%s' for stream\n", buf);
2101 if (!input_filename[0]) {
2102 http_log("No filename was specified for stream\n");
2103 return AVERROR(EINVAL);
2107 ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2108 &c->stream->in_opts);
2110 http_log("Could not open input '%s': %s\n",
2111 input_filename, av_err2str(ret));
2115 /* set buffer size */
2117 ret = ffio_set_buf_size(s->pb, buf_size);
2119 http_log("Failed to set buffer size\n");
2124 s->flags |= AVFMT_FLAG_GENPTS;
2126 if (strcmp(s->iformat->name, "ffm") &&
2127 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2128 http_log("Could not find stream info for input '%s'\n", input_filename);
2129 avformat_close_input(&s);
2133 /* choose stream as clock source (we favor the video stream if
2134 * present) for packet sending */
2135 c->pts_stream_index = 0;
2136 for(i=0;i<c->stream->nb_streams;i++) {
2137 if (c->pts_stream_index == 0 &&
2138 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2139 c->pts_stream_index = i;
2143 if (c->fmt_in->iformat->read_seek)
2144 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2145 /* set the start time (needed for maxtime and RTP packet timing) */
2146 c->start_time = cur_time;
2147 c->first_pts = AV_NOPTS_VALUE;
2151 /* return the server clock (in us) */
2152 static int64_t get_server_clock(HTTPContext *c)
2154 /* compute current pts value from system time */
2155 return (cur_time - c->start_time) * 1000;
2158 /* return the estimated time (in us) at which the current packet must be sent */
2159 static int64_t get_packet_send_clock(HTTPContext *c)
2161 int bytes_left, bytes_sent, frame_bytes;
2163 frame_bytes = c->cur_frame_bytes;
2164 if (frame_bytes <= 0)
2167 bytes_left = c->buffer_end - c->buffer_ptr;
2168 bytes_sent = frame_bytes - bytes_left;
2169 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2173 static int http_prepare_data(HTTPContext *c)
2176 AVFormatContext *ctx;
2178 av_freep(&c->pb_buffer);
2180 case HTTPSTATE_SEND_DATA_HEADER:
2181 ctx = avformat_alloc_context();
2183 return AVERROR(ENOMEM);
2186 av_dict_copy(&(c->fmt_ctx.metadata), c->stream->metadata, 0);
2187 c->fmt_ctx.streams = av_mallocz_array(c->stream->nb_streams,
2188 sizeof(AVStream *));
2189 if (!c->fmt_ctx.streams)
2190 return AVERROR(ENOMEM);
2192 for(i=0;i<c->stream->nb_streams;i++) {
2194 c->fmt_ctx.streams[i] = av_mallocz(sizeof(AVStream));
2196 /* if file or feed, then just take streams from FFServerStream
2198 if (!c->stream->feed ||
2199 c->stream->feed == c->stream)
2200 src = c->stream->streams[i];
2202 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2204 *(c->fmt_ctx.streams[i]) = *src;
2205 c->fmt_ctx.streams[i]->priv_data = 0;
2206 /* XXX: should be done in AVStream, not in codec */
2207 c->fmt_ctx.streams[i]->codec->frame_number = 0;
2209 /* set output format parameters */
2210 c->fmt_ctx.oformat = c->stream->fmt;
2211 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2213 c->got_key_frame = 0;
2215 /* prepare header and save header data in a stream */
2216 if (avio_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2217 /* XXX: potential leak */
2220 c->fmt_ctx.pb->seekable = 0;
2223 * HACK to avoid MPEG-PS muxer to spit many underflow errors
2224 * Default value from FFmpeg
2225 * Try to set it using configuration option
2227 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2229 if ((ret = avformat_write_header(&c->fmt_ctx, NULL)) < 0) {
2230 http_log("Error writing output header for stream '%s': %s\n",
2231 c->stream->filename, av_err2str(ret));
2234 av_dict_free(&c->fmt_ctx.metadata);
2236 len = avio_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2237 c->buffer_ptr = c->pb_buffer;
2238 c->buffer_end = c->pb_buffer + len;
2240 c->state = HTTPSTATE_SEND_DATA;
2241 c->last_packet_sent = 0;
2243 case HTTPSTATE_SEND_DATA:
2244 /* find a new packet */
2245 /* read a packet from the input stream */
2246 if (c->stream->feed)
2247 ffm_set_write_index(c->fmt_in,
2248 c->stream->feed->feed_write_index,
2249 c->stream->feed->feed_size);
2251 if (c->stream->max_time &&
2252 c->stream->max_time + c->start_time - cur_time < 0)
2253 /* We have timed out */
2254 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2258 ret = av_read_frame(c->fmt_in, &pkt);
2260 if (c->stream->feed) {
2261 /* if coming from feed, it means we reached the end of the
2262 * ffm file, so must wait for more data */
2263 c->state = HTTPSTATE_WAIT_FEED;
2264 return 1; /* state changed */
2266 if (ret == AVERROR(EAGAIN)) {
2267 /* input not ready, come back later */
2270 if (c->stream->loop) {
2271 avformat_close_input(&c->fmt_in);
2272 if (open_input_stream(c, "") < 0)
2277 /* must send trailer now because EOF or error */
2278 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2281 int source_index = pkt.stream_index;
2282 /* update first pts if needed */
2283 if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
2284 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2285 c->start_time = cur_time;
2287 /* send it to the appropriate stream */
2288 if (c->stream->feed) {
2289 /* if coming from a feed, select the right stream */
2290 if (c->switch_pending) {
2291 c->switch_pending = 0;
2292 for(i=0;i<c->stream->nb_streams;i++) {
2293 if (c->switch_feed_streams[i] == pkt.stream_index)
2294 if (pkt.flags & AV_PKT_FLAG_KEY)
2295 c->switch_feed_streams[i] = -1;
2296 if (c->switch_feed_streams[i] >= 0)
2297 c->switch_pending = 1;
2300 for(i=0;i<c->stream->nb_streams;i++) {
2301 if (c->stream->feed_streams[i] == pkt.stream_index) {
2302 AVStream *st = c->fmt_in->streams[source_index];
2303 pkt.stream_index = i;
2304 if (pkt.flags & AV_PKT_FLAG_KEY &&
2305 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2306 c->stream->nb_streams == 1))
2307 c->got_key_frame = 1;
2308 if (!c->stream->send_on_key || c->got_key_frame)
2313 AVCodecContext *codec;
2314 AVStream *ist, *ost;
2316 ist = c->fmt_in->streams[source_index];
2317 /* specific handling for RTP: we use several
2318 * output streams (one for each RTP connection).
2319 * XXX: need more abstract handling */
2320 if (c->is_packetized) {
2321 /* compute send time and duration */
2322 if (pkt.dts != AV_NOPTS_VALUE) {
2323 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2324 c->cur_pts -= c->first_pts;
2326 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2327 /* find RTP context */
2328 c->packet_stream_index = pkt.stream_index;
2329 ctx = c->rtp_ctx[c->packet_stream_index];
2331 av_packet_unref(&pkt);
2334 codec = ctx->streams[0]->codec;
2335 /* only one stream per RTP connection */
2336 pkt.stream_index = 0;
2340 codec = ctx->streams[pkt.stream_index]->codec;
2343 if (c->is_packetized) {
2344 int max_packet_size;
2345 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2346 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2348 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2349 ret = ffio_open_dyn_packet_buf(&ctx->pb,
2352 ret = avio_open_dyn_buf(&ctx->pb);
2355 /* XXX: potential leak */
2358 ost = ctx->streams[pkt.stream_index];
2360 ctx->pb->seekable = 0;
2361 if (pkt.dts != AV_NOPTS_VALUE)
2362 pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2364 if (pkt.pts != AV_NOPTS_VALUE)
2365 pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2367 pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2369 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2370 http_log("Error writing frame to output for stream '%s': %s\n",
2371 c->stream->filename, av_err2str(ret));
2372 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2375 av_freep(&c->pb_buffer);
2376 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2378 c->cur_frame_bytes = len;
2379 c->buffer_ptr = c->pb_buffer;
2380 c->buffer_end = c->pb_buffer + len;
2382 codec->frame_number++;
2384 av_packet_unref(&pkt);
2388 av_packet_unref(&pkt);
2393 case HTTPSTATE_SEND_DATA_TRAILER:
2394 /* last packet test ? */
2395 if (c->last_packet_sent || c->is_packetized)
2398 /* prepare header */
2399 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2400 /* XXX: potential leak */
2403 c->fmt_ctx.pb->seekable = 0;
2404 av_write_trailer(ctx);
2405 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2406 c->buffer_ptr = c->pb_buffer;
2407 c->buffer_end = c->pb_buffer + len;
2409 c->last_packet_sent = 1;
2415 /* should convert the format at the same time */
2416 /* send data starting at c->buffer_ptr to the output connection
2417 * (either UDP or TCP)
2419 static int http_send_data(HTTPContext *c)
2424 if (c->buffer_ptr >= c->buffer_end) {
2425 ret = http_prepare_data(c);
2429 /* state change requested */
2432 if (c->is_packetized) {
2433 /* RTP data output */
2434 len = c->buffer_end - c->buffer_ptr;
2436 /* fail safe - should never happen */
2438 c->buffer_ptr = c->buffer_end;
2441 len = (c->buffer_ptr[0] << 24) |
2442 (c->buffer_ptr[1] << 16) |
2443 (c->buffer_ptr[2] << 8) |
2445 if (len > (c->buffer_end - c->buffer_ptr))
2447 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2448 /* nothing to send yet: we can wait */
2452 c->data_count += len;
2453 update_datarate(&c->datarate, c->data_count);
2455 c->stream->bytes_served += len;
2457 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2458 /* RTP packets are sent inside the RTSP TCP connection */
2460 int interleaved_index, size;
2462 HTTPContext *rtsp_c;
2465 /* if no RTSP connection left, error */
2468 /* if already sending something, then wait. */
2469 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2471 if (avio_open_dyn_buf(&pb) < 0)
2473 interleaved_index = c->packet_stream_index * 2;
2474 /* RTCP packets are sent at odd indexes */
2475 if (c->buffer_ptr[1] == 200)
2476 interleaved_index++;
2477 /* write RTSP TCP header */
2479 header[1] = interleaved_index;
2480 header[2] = len >> 8;
2482 avio_write(pb, header, 4);
2483 /* write RTP packet data */
2485 avio_write(pb, c->buffer_ptr, len);
2486 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2487 /* prepare asynchronous TCP sending */
2488 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2489 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2490 c->buffer_ptr += len;
2492 /* send everything we can NOW */
2493 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2494 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2496 rtsp_c->packet_buffer_ptr += len;
2497 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2498 /* if we could not send all the data, we will
2499 * send it later, so a new state is needed to
2500 * "lock" the RTSP TCP connection */
2501 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2504 /* all data has been sent */
2505 av_freep(&c->packet_buffer);
2507 /* send RTP packet directly in UDP */
2509 ffurl_write(c->rtp_handles[c->packet_stream_index],
2510 c->buffer_ptr, len);
2511 c->buffer_ptr += len;
2512 /* here we continue as we can send several packets
2516 /* TCP data output */
2517 len = send(c->fd, c->buffer_ptr,
2518 c->buffer_end - c->buffer_ptr, 0);
2520 if (ff_neterrno() != AVERROR(EAGAIN) &&
2521 ff_neterrno() != AVERROR(EINTR))
2522 /* error : close connection */
2527 c->buffer_ptr += len;
2529 c->data_count += len;
2530 update_datarate(&c->datarate, c->data_count);
2532 c->stream->bytes_served += len;
2540 static int http_start_receive_data(HTTPContext *c)
2545 if (c->stream->feed_opened) {
2546 http_log("Stream feed '%s' was not opened\n",
2547 c->stream->feed_filename);
2548 return AVERROR(EINVAL);
2551 /* Don't permit writing to this one */
2552 if (c->stream->readonly) {
2553 http_log("Cannot write to read-only file '%s'\n",
2554 c->stream->feed_filename);
2555 return AVERROR(EINVAL);
2559 fd = open(c->stream->feed_filename, O_RDWR);
2561 ret = AVERROR(errno);
2562 http_log("Could not open feed file '%s': %s\n",
2563 c->stream->feed_filename, strerror(errno));
2568 if (c->stream->truncate) {
2569 /* truncate feed file */
2570 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2571 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2572 if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2573 ret = AVERROR(errno);
2574 http_log("Error truncating feed file '%s': %s\n",
2575 c->stream->feed_filename, strerror(errno));
2579 ret = ffm_read_write_index(fd);
2581 http_log("Error reading write index from feed file '%s': %s\n",
2582 c->stream->feed_filename, strerror(errno));
2585 c->stream->feed_write_index = ret;
2588 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2590 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2591 lseek(fd, 0, SEEK_SET);
2593 /* init buffer input */
2594 c->buffer_ptr = c->buffer;
2595 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2596 c->stream->feed_opened = 1;
2597 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2601 static int http_receive_data(HTTPContext *c)
2604 int len, loop_run = 0;
2606 while (c->chunked_encoding && !c->chunk_size &&
2607 c->buffer_end > c->buffer_ptr) {
2608 /* read chunk header, if present */
2609 len = recv(c->fd, c->buffer_ptr, 1, 0);
2612 if (ff_neterrno() != AVERROR(EAGAIN) &&
2613 ff_neterrno() != AVERROR(EINTR))
2614 /* error : close connection */
2617 } else if (len == 0) {
2618 /* end of connection : close it */
2620 } else if (c->buffer_ptr - c->buffer >= 2 &&
2621 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2622 c->chunk_size = strtol(c->buffer, 0, 16);
2623 if (c->chunk_size == 0) // end of stream
2625 c->buffer_ptr = c->buffer;
2627 } else if (++loop_run > 10)
2628 /* no chunk header, abort */
2634 if (c->buffer_end > c->buffer_ptr) {
2635 len = recv(c->fd, c->buffer_ptr,
2636 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2638 if (ff_neterrno() != AVERROR(EAGAIN) &&
2639 ff_neterrno() != AVERROR(EINTR))
2640 /* error : close connection */
2642 } else if (len == 0)
2643 /* end of connection : close it */
2646 c->chunk_size -= len;
2647 c->buffer_ptr += len;
2648 c->data_count += len;
2649 update_datarate(&c->datarate, c->data_count);
2653 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2654 if (c->buffer[0] != 'f' ||
2655 c->buffer[1] != 'm') {
2656 http_log("Feed stream has become desynchronized -- disconnecting\n");
2661 if (c->buffer_ptr >= c->buffer_end) {
2662 FFServerStream *feed = c->stream;
2663 /* a packet has been received : write it in the store, except
2665 if (c->data_count > FFM_PACKET_SIZE) {
2666 /* XXX: use llseek or url_seek
2667 * XXX: Should probably fail? */
2668 if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2669 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2671 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2672 http_log("Error writing to feed file: %s\n", strerror(errno));
2676 feed->feed_write_index += FFM_PACKET_SIZE;
2677 /* update file size */
2678 if (feed->feed_write_index > c->stream->feed_size)
2679 feed->feed_size = feed->feed_write_index;
2681 /* handle wrap around if max file size reached */
2682 if (c->stream->feed_max_size &&
2683 feed->feed_write_index >= c->stream->feed_max_size)
2684 feed->feed_write_index = FFM_PACKET_SIZE;
2687 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2688 http_log("Error writing index to feed file: %s\n",
2693 /* wake up any waiting connections */
2694 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2695 if (c1->state == HTTPSTATE_WAIT_FEED &&
2696 c1->stream->feed == c->stream->feed)
2697 c1->state = HTTPSTATE_SEND_DATA;
2700 /* We have a header in our hands that contains useful data */
2701 AVFormatContext *s = avformat_alloc_context();
2703 AVInputFormat *fmt_in;
2709 /* use feed output format name to find corresponding input format */
2710 fmt_in = av_find_input_format(feed->fmt->name);
2714 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2715 0, NULL, NULL, NULL, NULL);
2722 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2727 /* Now we have the actual streams */
2728 if (s->nb_streams != feed->nb_streams) {
2729 avformat_close_input(&s);
2731 http_log("Feed '%s' stream number does not match registered feed\n",
2732 c->stream->feed_filename);
2736 for (i = 0; i < s->nb_streams; i++) {
2737 AVStream *fst = feed->streams[i];
2738 AVStream *st = s->streams[i];
2739 avcodec_copy_context(fst->codec, st->codec);
2742 avformat_close_input(&s);
2745 c->buffer_ptr = c->buffer;
2750 c->stream->feed_opened = 0;
2752 /* wake up any waiting connections to stop waiting for feed */
2753 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2754 if (c1->state == HTTPSTATE_WAIT_FEED &&
2755 c1->stream->feed == c->stream->feed)
2756 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2761 /********************************************************************/
2764 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2771 str = RTSP_STATUS_CODE2STRING(error_number);
2773 str = "Unknown Error";
2775 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2776 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2778 /* output GMT time */
2781 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2782 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2785 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2787 rtsp_reply_header(c, error_number);
2788 avio_printf(c->pb, "\r\n");
2791 static int rtsp_parse_request(HTTPContext *c)
2793 const char *p, *p1, *p2;
2799 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2801 c->buffer_ptr[0] = '\0';
2804 get_word(cmd, sizeof(cmd), &p);
2805 get_word(url, sizeof(url), &p);
2806 get_word(protocol, sizeof(protocol), &p);
2808 av_strlcpy(c->method, cmd, sizeof(c->method));
2809 av_strlcpy(c->url, url, sizeof(c->url));
2810 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2812 if (avio_open_dyn_buf(&c->pb) < 0) {
2813 /* XXX: cannot do more */
2814 c->pb = NULL; /* safety */
2818 /* check version name */
2819 if (strcmp(protocol, "RTSP/1.0")) {
2820 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2824 /* parse each header line */
2825 /* skip to next line */
2826 while (*p != '\n' && *p != '\0')
2830 while (*p != '\0') {
2831 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2835 if (p2 > p && p2[-1] == '\r')
2837 /* skip empty line */
2841 if (len > sizeof(line) - 1)
2842 len = sizeof(line) - 1;
2843 memcpy(line, p, len);
2845 ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
2849 /* handle sequence number */
2850 c->seq = header->seq;
2852 if (!strcmp(cmd, "DESCRIBE"))
2853 rtsp_cmd_describe(c, url);
2854 else if (!strcmp(cmd, "OPTIONS"))
2855 rtsp_cmd_options(c, url);
2856 else if (!strcmp(cmd, "SETUP"))
2857 rtsp_cmd_setup(c, url, header);
2858 else if (!strcmp(cmd, "PLAY"))
2859 rtsp_cmd_play(c, url, header);
2860 else if (!strcmp(cmd, "PAUSE"))
2861 rtsp_cmd_interrupt(c, url, header, 1);
2862 else if (!strcmp(cmd, "TEARDOWN"))
2863 rtsp_cmd_interrupt(c, url, header, 0);
2865 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2868 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2869 c->pb = NULL; /* safety */
2871 /* XXX: cannot do more */
2874 c->buffer_ptr = c->pb_buffer;
2875 c->buffer_end = c->pb_buffer + len;
2876 c->state = RTSPSTATE_SEND_REPLY;
2880 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
2881 struct in_addr my_ip)
2883 AVFormatContext *avc;
2884 AVStream *avs = NULL;
2885 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
2886 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
2891 avc = avformat_alloc_context();
2892 if (!avc || !rtp_format)
2895 avc->oformat = rtp_format;
2896 av_dict_set(&avc->metadata, "title",
2897 entry ? entry->value : "No Title", 0);
2898 avc->nb_streams = stream->nb_streams;
2899 if (stream->is_multicast) {
2900 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2901 inet_ntoa(stream->multicast_ip),
2902 stream->multicast_port, stream->multicast_ttl);
2904 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
2906 avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
2910 avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
2914 for(i = 0; i < stream->nb_streams; i++) {
2915 avc->streams[i] = &avs[i];
2916 avc->streams[i]->codec = stream->streams[i]->codec;
2918 *pbuffer = av_mallocz(2048);
2921 av_sdp_create(&avc, 1, *pbuffer, 2048);
2924 av_freep(&avc->streams);
2925 av_dict_free(&avc->metadata);
2929 return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
2932 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2934 /* rtsp_reply_header(c, RTSP_STATUS_OK); */
2935 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2936 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2937 avio_printf(c->pb, "Public: %s\r\n",
2938 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2939 avio_printf(c->pb, "\r\n");
2942 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2944 FFServerStream *stream;
2950 struct sockaddr_in my_addr;
2952 /* find which URL is asked */
2953 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2958 for(stream = config.first_stream; stream; stream = stream->next) {
2959 if (!stream->is_feed &&
2960 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
2961 !strcmp(path, stream->filename)) {
2965 /* no stream found */
2966 rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
2970 /* prepare the media description in SDP format */
2972 /* get the host IP */
2973 len = sizeof(my_addr);
2974 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
2975 content_length = prepare_sdp_description(stream, &content,
2977 if (content_length < 0) {
2978 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2981 rtsp_reply_header(c, RTSP_STATUS_OK);
2982 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
2983 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
2984 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
2985 avio_printf(c->pb, "\r\n");
2986 avio_write(c->pb, content, content_length);
2990 static HTTPContext *find_rtp_session(const char *session_id)
2994 if (session_id[0] == '\0')
2997 for(c = first_http_ctx; c; c = c->next) {
2998 if (!strcmp(c->session_id, session_id))
3004 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3006 RTSPTransportField *th;
3009 for(i=0;i<h->nb_transports;i++) {
3010 th = &h->transports[i];
3011 if (th->lower_transport == lower_transport)
3017 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3018 RTSPMessageHeader *h)
3020 FFServerStream *stream;
3021 int stream_index, rtp_port, rtcp_port;
3026 RTSPTransportField *th;
3027 struct sockaddr_in dest_addr;
3028 RTSPActionServerSetup setup;
3030 /* find which URL is asked */
3031 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3036 /* now check each stream */
3037 for(stream = config.first_stream; stream; stream = stream->next) {
3038 if (stream->is_feed || !stream->fmt ||
3039 strcmp(stream->fmt->name, "rtp")) {
3042 /* accept aggregate filenames only if single stream */
3043 if (!strcmp(path, stream->filename)) {
3044 if (stream->nb_streams != 1) {
3045 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3052 for(stream_index = 0; stream_index < stream->nb_streams;
3054 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3055 stream->filename, stream_index);
3056 if (!strcmp(path, buf))
3060 /* no stream found */
3061 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3065 /* generate session id if needed */
3066 if (h->session_id[0] == '\0') {
3067 unsigned random0 = av_lfg_get(&random_state);
3068 unsigned random1 = av_lfg_get(&random_state);
3069 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3073 /* find RTP session, and create it if none found */
3074 rtp_c = find_rtp_session(h->session_id);
3076 /* always prefer UDP */
3077 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3079 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3081 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3086 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3087 th->lower_transport);
3089 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3093 /* open input stream */
3094 if (open_input_stream(rtp_c, "") < 0) {
3095 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3100 /* test if stream is OK (test needed because several SETUP needs
3101 * to be done for a given file) */
3102 if (rtp_c->stream != stream) {
3103 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3107 /* test if stream is already set up */
3108 if (rtp_c->rtp_ctx[stream_index]) {
3109 rtsp_reply_error(c, RTSP_STATUS_STATE);
3113 /* check transport */
3114 th = find_transport(h, rtp_c->rtp_protocol);
3115 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3116 th->client_port_min <= 0)) {
3117 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3121 /* setup default options */
3122 setup.transport_option[0] = '\0';
3123 dest_addr = rtp_c->from_addr;
3124 dest_addr.sin_port = htons(th->client_port_min);
3127 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3128 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3132 /* now everything is OK, so we can send the connection parameters */
3133 rtsp_reply_header(c, RTSP_STATUS_OK);
3135 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3137 switch(rtp_c->rtp_protocol) {
3138 case RTSP_LOWER_TRANSPORT_UDP:
3139 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3140 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3141 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3142 "client_port=%d-%d;server_port=%d-%d",
3143 th->client_port_min, th->client_port_max,
3144 rtp_port, rtcp_port);
3146 case RTSP_LOWER_TRANSPORT_TCP:
3147 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3148 stream_index * 2, stream_index * 2 + 1);
3153 if (setup.transport_option[0] != '\0')
3154 avio_printf(c->pb, ";%s", setup.transport_option);
3155 avio_printf(c->pb, "\r\n");
3158 avio_printf(c->pb, "\r\n");
3163 * find an RTP connection by using the session ID. Check consistency
3166 static HTTPContext *find_rtp_session_with_url(const char *url,
3167 const char *session_id)
3175 rtp_c = find_rtp_session(session_id);
3179 /* find which URL is asked */
3180 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3184 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3185 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3186 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3187 rtp_c->stream->filename, s);
3188 if(!strncmp(path, buf, sizeof(buf)))
3189 /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3190 * if nb_streams>1? */
3194 if (len > 0 && path[len - 1] == '/' &&
3195 !strncmp(path, rtp_c->stream->filename, len - 1))
3200 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3204 rtp_c = find_rtp_session_with_url(url, h->session_id);
3206 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3210 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3211 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3212 rtp_c->state != HTTPSTATE_READY) {
3213 rtsp_reply_error(c, RTSP_STATUS_STATE);
3217 rtp_c->state = HTTPSTATE_SEND_DATA;
3219 /* now everything is OK, so we can send the connection parameters */
3220 rtsp_reply_header(c, RTSP_STATUS_OK);
3222 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3223 avio_printf(c->pb, "\r\n");
3226 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3227 RTSPMessageHeader *h, int pause_only)
3231 rtp_c = find_rtp_session_with_url(url, h->session_id);
3233 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3238 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3239 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3240 rtsp_reply_error(c, RTSP_STATUS_STATE);
3243 rtp_c->state = HTTPSTATE_READY;
3244 rtp_c->first_pts = AV_NOPTS_VALUE;
3247 /* now everything is OK, so we can send the connection parameters */
3248 rtsp_reply_header(c, RTSP_STATUS_OK);
3250 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3251 avio_printf(c->pb, "\r\n");
3254 close_connection(rtp_c);
3257 /********************************************************************/
3260 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3261 FFServerStream *stream,
3262 const char *session_id,
3263 enum RTSPLowerTransport rtp_protocol)
3265 HTTPContext *c = NULL;
3266 const char *proto_str;
3268 /* XXX: should output a warning page when coming
3269 * close to the connection limit */
3270 if (nb_connections >= config.nb_max_connections)
3273 /* add a new connection */
3274 c = av_mallocz(sizeof(HTTPContext));
3279 c->poll_entry = NULL;
3280 c->from_addr = *from_addr;
3281 c->buffer_size = IOBUFFER_INIT_SIZE;
3282 c->buffer = av_malloc(c->buffer_size);
3287 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3288 c->state = HTTPSTATE_READY;
3289 c->is_packetized = 1;
3290 c->rtp_protocol = rtp_protocol;
3292 /* protocol is shown in statistics */
3293 switch(c->rtp_protocol) {
3294 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3295 proto_str = "MCAST";
3297 case RTSP_LOWER_TRANSPORT_UDP:
3300 case RTSP_LOWER_TRANSPORT_TCP:
3307 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3308 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3310 current_bandwidth += stream->bandwidth;
3312 c->next = first_http_ctx;
3318 av_freep(&c->buffer);
3325 * add a new RTP stream in an RTP connection (used in RTSP SETUP
3326 * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3329 static int rtp_new_av_stream(HTTPContext *c,
3330 int stream_index, struct sockaddr_in *dest_addr,
3331 HTTPContext *rtsp_c)
3333 AVFormatContext *ctx;
3336 URLContext *h = NULL;
3338 int max_packet_size;
3341 /* now we can open the relevant output stream */
3342 ctx = avformat_alloc_context();
3345 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3347 st = avformat_new_stream(ctx, NULL);
3351 av_freep(&st->codec);
3352 av_freep(&st->info);
3353 st_internal = st->internal;
3355 if (!c->stream->feed ||
3356 c->stream->feed == c->stream)
3357 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3360 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3362 st->priv_data = NULL;
3363 st->internal = st_internal;
3365 /* build destination RTP address */
3366 ipaddr = inet_ntoa(dest_addr->sin_addr);
3368 switch(c->rtp_protocol) {
3369 case RTSP_LOWER_TRANSPORT_UDP:
3370 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3373 /* XXX: also pass as parameter to function ? */
3374 if (c->stream->is_multicast) {
3376 ttl = c->stream->multicast_ttl;
3379 snprintf(ctx->filename, sizeof(ctx->filename),
3380 "rtp://%s:%d?multicast=1&ttl=%d",
3381 ipaddr, ntohs(dest_addr->sin_port), ttl);
3383 snprintf(ctx->filename, sizeof(ctx->filename),
3384 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3387 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3389 c->rtp_handles[stream_index] = h;
3390 max_packet_size = h->max_packet_size;
3392 case RTSP_LOWER_TRANSPORT_TCP:
3395 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3401 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3402 ipaddr, ntohs(dest_addr->sin_port),
3403 c->stream->filename, stream_index, c->protocol);
3405 /* normally, no packets should be output here, but the packet size may
3407 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3408 /* XXX: close stream */
3411 if (avformat_write_header(ctx, NULL) < 0) {
3419 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3423 c->rtp_ctx[stream_index] = ctx;
3427 /********************************************************************/
3428 /* ffserver initialization */
3430 /* FIXME: This code should use avformat_new_stream() */
3431 static AVStream *add_av_stream1(FFServerStream *stream,
3432 AVCodecContext *codec, int copy)
3436 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3439 fst = av_mallocz(sizeof(AVStream));
3443 fst->codec = avcodec_alloc_context3(codec->codec);
3448 avcodec_copy_context(fst->codec, codec);
3450 /* live streams must use the actual feed's codec since it may be
3451 * updated later to carry extradata needed by them.
3455 fst->priv_data = av_mallocz(sizeof(FeedData));
3456 fst->internal = av_mallocz(sizeof(*fst->internal));
3457 fst->index = stream->nb_streams;
3458 avpriv_set_pts_info(fst, 33, 1, 90000);
3459 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3460 stream->streams[stream->nb_streams++] = fst;
3464 /* return the stream number in the feed */
3465 static int add_av_stream(FFServerStream *feed, AVStream *st)
3468 AVCodecContext *av, *av1;
3472 for(i=0;i<feed->nb_streams;i++) {
3473 av1 = feed->streams[i]->codec;
3474 if (av1->codec_id == av->codec_id &&
3475 av1->codec_type == av->codec_type &&
3476 av1->bit_rate == av->bit_rate) {
3478 switch(av->codec_type) {
3479 case AVMEDIA_TYPE_AUDIO:
3480 if (av1->channels == av->channels &&
3481 av1->sample_rate == av->sample_rate)
3484 case AVMEDIA_TYPE_VIDEO:
3485 if (av1->width == av->width &&
3486 av1->height == av->height &&
3487 av1->time_base.den == av->time_base.den &&
3488 av1->time_base.num == av->time_base.num &&
3489 av1->gop_size == av->gop_size)
3498 fst = add_av_stream1(feed, av, 0);
3501 if (av_stream_get_recommended_encoder_configuration(st))
3502 av_stream_set_recommended_encoder_configuration(fst,
3503 av_strdup(av_stream_get_recommended_encoder_configuration(st)));
3504 return feed->nb_streams - 1;
3507 static void remove_stream(FFServerStream *stream)
3509 FFServerStream **ps;
3510 ps = &config.first_stream;
3519 /* specific MPEG4 handling : we extract the raw parameters */
3520 static void extract_mpeg4_header(AVFormatContext *infile)
3522 int mpeg4_count, i, size;
3527 infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
3530 for(i=0;i<infile->nb_streams;i++) {
3531 st = infile->streams[i];
3532 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3533 st->codec->extradata_size == 0) {
3540 printf("MPEG4 without extra data: trying to find header in %s\n",
3542 while (mpeg4_count > 0) {
3543 if (av_read_frame(infile, &pkt) < 0)
3545 st = infile->streams[pkt.stream_index];
3546 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3547 st->codec->extradata_size == 0) {
3548 av_freep(&st->codec->extradata);
3549 /* fill extradata with the header */
3550 /* XXX: we make hard suppositions here ! */
3552 while (p < pkt.data + pkt.size - 4) {
3553 /* stop when vop header is found */
3554 if (p[0] == 0x00 && p[1] == 0x00 &&
3555 p[2] == 0x01 && p[3] == 0xb6) {
3556 size = p - pkt.data;
3557 st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
3558 st->codec->extradata_size = size;
3559 memcpy(st->codec->extradata, pkt.data, size);
3566 av_packet_unref(&pkt);
3570 /* compute the needed AVStream for each file */
3571 static void build_file_streams(void)
3573 FFServerStream *stream;
3574 AVFormatContext *infile;
3577 /* gather all streams */
3578 for(stream = config.first_stream; stream; stream = stream->next) {
3581 if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
3584 /* the stream comes from a file */
3585 /* try to open the file */
3589 /* specific case: if transport stream output to RTP,
3590 * we use a raw transport stream reader */
3591 if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
3592 av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3594 if (!stream->feed_filename[0]) {
3595 http_log("Unspecified feed file for stream '%s'\n",
3600 http_log("Opening feed file '%s' for stream '%s'\n",
3601 stream->feed_filename, stream->filename);
3603 ret = avformat_open_input(&infile, stream->feed_filename,
3604 stream->ifmt, &stream->in_opts);
3606 http_log("Could not open '%s': %s\n", stream->feed_filename,
3608 /* remove stream (no need to spend more time on it) */
3610 remove_stream(stream);
3612 /* find all the AVStreams inside and reference them in
3614 if (avformat_find_stream_info(infile, NULL) < 0) {
3615 http_log("Could not find codec parameters from '%s'\n",
3616 stream->feed_filename);
3617 avformat_close_input(&infile);
3620 extract_mpeg4_header(infile);
3622 for(i=0;i<infile->nb_streams;i++)
3623 add_av_stream1(stream, infile->streams[i]->codec, 1);
3625 avformat_close_input(&infile);
3631 int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs, int stream)
3635 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3636 if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3637 http_log("Codecs do not match for stream %d\n", stream);
3639 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3640 http_log("Codec bitrates do not match for stream %d\n", stream);
3642 } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
3643 if (CHECK_CODEC(time_base.den) ||
3644 CHECK_CODEC(time_base.num) ||
3645 CHECK_CODEC(width) ||
3646 CHECK_CODEC(height)) {
3647 http_log("Codec width, height or framerate do not match for stream %d\n", stream);
3650 } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
3651 if (CHECK_CODEC(sample_rate) ||
3652 CHECK_CODEC(channels) ||
3653 CHECK_CODEC(frame_size)) {
3654 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
3658 http_log("Unknown codec type for stream %d\n", stream);
3665 /* compute the needed AVStream for each feed */
3666 static int build_feed_streams(void)
3668 FFServerStream *stream, *feed;
3671 /* gather all streams */
3672 for(stream = config.first_stream; stream; stream = stream->next) {
3673 feed = stream->feed;
3677 if (stream->is_feed) {
3678 for(i=0;i<stream->nb_streams;i++)
3679 stream->feed_streams[i] = i;
3682 /* we handle a stream coming from a feed */
3683 for(i=0;i<stream->nb_streams;i++)
3684 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
3687 /* create feed files if needed */
3688 for(feed = config.first_feed; feed; feed = feed->next_feed) {
3690 if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
3691 AVFormatContext *s = NULL;
3694 /* See if it matches */
3696 if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
3697 http_log("Deleting feed file '%s' as it appears "
3699 feed->feed_filename);
3703 /* set buffer size */
3704 if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
3705 http_log("Failed to set buffer size\n");
3706 avformat_close_input(&s);
3710 /* Now see if it matches */
3711 if (s->nb_streams != feed->nb_streams) {
3712 http_log("Deleting feed file '%s' as stream counts "
3713 "differ (%d != %d)\n",
3714 feed->feed_filename, s->nb_streams, feed->nb_streams);
3719 for(i=0;i<s->nb_streams;i++) {
3722 sf = feed->streams[i];
3725 if (sf->index != ss->index || sf->id != ss->id) {
3726 http_log("Index & Id do not match for stream %d (%s)\n",
3727 i, feed->feed_filename);
3732 matches = check_codec_match (sf->codec, ss->codec, i);
3739 avformat_close_input(&s);
3742 if (feed->readonly) {
3743 http_log("Unable to delete read-only feed file '%s'\n",
3744 feed->feed_filename);
3747 unlink(feed->feed_filename);
3751 if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
3752 AVFormatContext *s = avformat_alloc_context();
3755 http_log("Failed to allocate context\n");
3759 if (feed->readonly) {
3760 http_log("Unable to create feed file '%s' as it is "
3761 "marked readonly\n",
3762 feed->feed_filename);
3763 avformat_free_context(s);
3767 /* only write the header of the ffm file */
3768 if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
3769 http_log("Could not open output feed file '%s'\n",
3770 feed->feed_filename);
3771 avformat_free_context(s);
3774 s->oformat = feed->fmt;
3775 s->nb_streams = feed->nb_streams;
3776 s->streams = feed->streams;
3777 if (avformat_write_header(s, NULL) < 0) {
3778 http_log("Container doesn't support the required parameters\n");
3779 avio_closep(&s->pb);
3780 avformat_free_context(s);
3783 /* XXX: need better API */
3784 av_freep(&s->priv_data);
3785 avio_closep(&s->pb);
3788 avformat_free_context(s);
3791 /* get feed size and write index */
3792 fd = open(feed->feed_filename, O_RDONLY);
3794 http_log("Could not open output feed file '%s'\n",
3795 feed->feed_filename);
3799 feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
3801 feed->feed_size = lseek(fd, 0, SEEK_END);
3802 /* ensure that we do not wrap before the end of file */
3803 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3804 feed->feed_max_size = feed->feed_size;
3814 /* compute the bandwidth used by each stream */
3815 static void compute_bandwidth(void)
3819 FFServerStream *stream;
3821 for(stream = config.first_stream; stream; stream = stream->next) {
3823 for(i=0;i<stream->nb_streams;i++) {
3824 AVStream *st = stream->streams[i];
3825 switch(st->codec->codec_type) {
3826 case AVMEDIA_TYPE_AUDIO:
3827 case AVMEDIA_TYPE_VIDEO:
3828 bandwidth += st->codec->bit_rate;
3834 stream->bandwidth = (bandwidth + 999) / 1000;
3838 static void handle_child_exit(int sig)
3844 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3845 FFServerStream *feed;
3847 for (feed = config.first_feed; feed; feed = feed->next) {
3848 if (feed->pid != pid)
3851 uptime = time(0) - feed->pid_start;
3854 "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
3856 feed->filename, (int64_t) pid, status, uptime);
3859 /* Turn off any more restarts */
3860 ffserver_free_child_args(&feed->child_argv);
3864 need_to_start_children = 1;
3867 static void opt_debug(void)
3870 snprintf(config.logfilename, sizeof(config.logfilename), "-");
3873 void show_help_default(const char *opt, const char *arg)
3875 printf("usage: ffserver [options]\n"
3876 "Hyper fast multi format Audio/Video streaming server\n");
3878 show_help_options(options, "Main options:", 0, 0, 0);
3881 static const OptionDef options[] = {
3882 #include "cmdutils_common_opts.h"
3883 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
3884 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
3885 { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
3889 int main(int argc, char **argv)
3891 struct sigaction sigact = { { 0 } };
3893 int ret = EXIT_FAILURE;
3896 config.filename = av_strdup("/etc/ffserver.conf");
3898 parse_loglevel(argc, argv, options);
3900 avformat_network_init();
3902 show_banner(argc, argv, options);
3904 my_program_name = argv[0];
3906 parse_options(NULL, argc, argv, options, NULL);
3908 unsetenv("http_proxy"); /* Kill the http_proxy */
3910 av_lfg_init(&random_state, av_get_random_seed());
3912 sigact.sa_handler = handle_child_exit;
3913 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
3914 sigaction(SIGCHLD, &sigact, 0);
3916 if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
3917 fprintf(stderr, "Error reading configuration file '%s': %s\n",
3918 config.filename, av_err2str(cfg_parsed));
3922 /* open log file if needed */
3923 if (config.logfilename[0] != '\0') {
3924 if (!strcmp(config.logfilename, "-"))
3927 logfile = fopen(config.logfilename, "a");
3928 av_log_set_callback(http_av_log);
3931 build_file_streams();
3933 if (build_feed_streams() < 0) {
3934 http_log("Could not setup feed streams\n");
3938 compute_bandwidth();
3941 signal(SIGPIPE, SIG_IGN);
3943 if (http_server() < 0) {
3944 http_log("Could not start server\n");
3951 av_freep (&config.filename);
3952 avformat_network_deinit();