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 const char *my_program_name;
248 static int no_launch;
249 static int need_to_start_children;
251 /* maximum number of simultaneous HTTP connections */
252 static unsigned int nb_connections;
254 static uint64_t current_bandwidth;
256 /* Making this global saves on passing it around everywhere */
257 static int64_t cur_time;
259 static AVLFG random_state;
261 static FILE *logfile = NULL;
263 static void htmlstrip(char *s) {
265 s += strspn(s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,. ");
271 static int64_t ffm_read_write_index(int fd)
275 if (lseek(fd, 8, SEEK_SET) < 0)
277 if (read(fd, buf, 8) != 8)
282 static int ffm_write_write_index(int fd, int64_t pos)
288 buf[i] = (pos >> (56 - i * 8)) & 0xff;
289 if (lseek(fd, 8, SEEK_SET) < 0)
291 if (write(fd, buf, 8) != 8)
296 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
299 FFMContext *ffm = s->priv_data;
300 ffm->write_index = pos;
301 ffm->file_size = file_size;
304 static char *ctime1(char *buf2, int buf_size)
311 av_strlcpy(buf2, p, buf_size);
312 p = buf2 + strlen(p) - 1;
318 static void http_vlog(const char *fmt, va_list vargs)
320 static int print_prefix = 1;
327 ctime1(buf, sizeof(buf));
328 fprintf(logfile, "%s ", buf);
330 print_prefix = strstr(fmt, "\n") != NULL;
331 vfprintf(logfile, fmt, vargs);
336 __attribute__ ((format (printf, 1, 2)))
338 static void http_log(const char *fmt, ...)
341 va_start(vargs, fmt);
342 http_vlog(fmt, vargs);
346 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
348 static int print_prefix = 1;
349 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
350 if (level > av_log_get_level())
352 if (print_prefix && avc)
353 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
354 print_prefix = strstr(fmt, "\n") != NULL;
355 http_vlog(fmt, vargs);
358 static void log_connection(HTTPContext *c)
363 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
364 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
365 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
368 static void update_datarate(DataRateData *drd, int64_t count)
370 if (!drd->time1 && !drd->count1) {
371 drd->time1 = drd->time2 = cur_time;
372 drd->count1 = drd->count2 = count;
373 } else if (cur_time - drd->time2 > 5000) {
374 drd->time1 = drd->time2;
375 drd->count1 = drd->count2;
376 drd->time2 = cur_time;
381 /* In bytes per second */
382 static int compute_datarate(DataRateData *drd, int64_t count)
384 if (cur_time == drd->time1)
387 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
391 static void start_children(FFServerStream *feed)
401 cmd_length = strlen(my_program_name);
404 * FIXME: WIP Safeguard. Remove after clearing all harcoded
405 * '1024' path lengths
407 if (cmd_length > PATH_LENGTH - 1) {
408 http_log("Could not start children. Command line: '%s' exceeds "
409 "path length limit (%d)\n", my_program_name, PATH_LENGTH);
413 pathname = av_strdup (my_program_name);
415 http_log("Could not allocate memory for children cmd line\n");
418 /* replace "ffserver" with "ffmpeg" in the path of current
419 * program. Ignore user provided path */
421 slash = strrchr(pathname, '/');
426 strcpy(slash, "ffmpeg");
428 for (; feed; feed = feed->next) {
430 if (!feed->child_argv || feed->pid)
433 feed->pid_start = time(0);
437 http_log("Unable to create children\n");
446 http_log("Launch command line: ");
447 http_log("%s ", pathname);
449 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
450 http_log("%s ", feed->child_argv[i]);
453 for (i = 3; i < 256; i++)
457 if (!freopen("/dev/null", "r", stdin))
458 http_log("failed to redirect STDIN to /dev/null\n;");
459 if (!freopen("/dev/null", "w", stdout))
460 http_log("failed to redirect STDOUT to /dev/null\n;");
461 if (!freopen("/dev/null", "w", stderr))
462 http_log("failed to redirect STDERR to /dev/null\n;");
465 signal(SIGPIPE, SIG_DFL);
466 execvp(pathname, feed->child_argv);
472 /* open a listening socket */
473 static int socket_open_listen(struct sockaddr_in *my_addr)
477 server_fd = socket(AF_INET,SOCK_STREAM,0);
484 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
485 av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
487 my_addr->sin_family = AF_INET;
488 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
490 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
491 ntohs(my_addr->sin_port));
496 if (listen (server_fd, 5) < 0) {
501 if (ff_socket_nonblock(server_fd, 1) < 0)
502 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
507 closesocket(server_fd);
511 /* start all multicast streams */
512 static void start_multicast(void)
514 FFServerStream *stream;
517 struct sockaddr_in dest_addr = {0};
518 int default_port, stream_index;
519 unsigned int random0, random1;
522 for(stream = config.first_stream; stream; stream = stream->next) {
524 if (!stream->is_multicast)
527 random0 = av_lfg_get(&random_state);
528 random1 = av_lfg_get(&random_state);
530 /* open the RTP connection */
531 snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
533 /* choose a port if none given */
534 if (stream->multicast_port == 0) {
535 stream->multicast_port = default_port;
539 dest_addr.sin_family = AF_INET;
540 dest_addr.sin_addr = stream->multicast_ip;
541 dest_addr.sin_port = htons(stream->multicast_port);
543 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
544 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
548 if (open_input_stream(rtp_c, "") < 0) {
549 http_log("Could not open input stream for stream '%s'\n",
554 /* open each RTP stream */
555 for(stream_index = 0; stream_index < stream->nb_streams;
557 dest_addr.sin_port = htons(stream->multicast_port +
559 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
562 http_log("Could not open output stream '%s/streamid=%d'\n",
563 stream->filename, stream_index);
567 rtp_c->state = HTTPSTATE_SEND_DATA;
571 /* main loop of the HTTP server */
572 static int http_server(void)
574 int server_fd = 0, rtsp_server_fd = 0;
576 struct pollfd *poll_table, *poll_entry;
577 HTTPContext *c, *c_next;
579 poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
580 sizeof(*poll_table));
582 http_log("Impossible to allocate a poll table handling %d "
583 "connections.\n", config.nb_max_http_connections);
587 if (config.http_addr.sin_port) {
588 server_fd = socket_open_listen(&config.http_addr);
593 if (config.rtsp_addr.sin_port) {
594 rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
595 if (rtsp_server_fd < 0) {
596 closesocket(server_fd);
601 if (!rtsp_server_fd && !server_fd) {
602 http_log("HTTP and RTSP disabled.\n");
606 http_log("FFserver started.\n");
608 start_children(config.first_feed);
613 poll_entry = poll_table;
615 poll_entry->fd = server_fd;
616 poll_entry->events = POLLIN;
619 if (rtsp_server_fd) {
620 poll_entry->fd = rtsp_server_fd;
621 poll_entry->events = POLLIN;
625 /* wait for events on each HTTP handle */
632 case HTTPSTATE_SEND_HEADER:
633 case RTSPSTATE_SEND_REPLY:
634 case RTSPSTATE_SEND_PACKET:
635 c->poll_entry = poll_entry;
637 poll_entry->events = POLLOUT;
640 case HTTPSTATE_SEND_DATA_HEADER:
641 case HTTPSTATE_SEND_DATA:
642 case HTTPSTATE_SEND_DATA_TRAILER:
643 if (!c->is_packetized) {
644 /* for TCP, we output as much as we can
645 * (may need to put a limit) */
646 c->poll_entry = poll_entry;
648 poll_entry->events = POLLOUT;
651 /* when ffserver is doing the timing, we work by
652 * looking at which packet needs to be sent every
653 * 10 ms (one tick wait XXX: 10 ms assumed) */
658 case HTTPSTATE_WAIT_REQUEST:
659 case HTTPSTATE_RECEIVE_DATA:
660 case HTTPSTATE_WAIT_FEED:
661 case RTSPSTATE_WAIT_REQUEST:
662 /* need to catch errors */
663 c->poll_entry = poll_entry;
665 poll_entry->events = POLLIN;/* Maybe this will work */
669 c->poll_entry = NULL;
675 /* wait for an event on one connection. We poll at least every
676 * second to handle timeouts */
678 ret = poll(poll_table, poll_entry - poll_table, delay);
679 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
680 ff_neterrno() != AVERROR(EINTR)) {
685 cur_time = av_gettime() / 1000;
687 if (need_to_start_children) {
688 need_to_start_children = 0;
689 start_children(config.first_feed);
692 /* now handle the events */
693 for(c = first_http_ctx; c; c = c_next) {
695 if (handle_connection(c) < 0) {
697 /* close and free the connection */
702 poll_entry = poll_table;
704 /* new HTTP connection request ? */
705 if (poll_entry->revents & POLLIN)
706 new_connection(server_fd, 0);
709 if (rtsp_server_fd) {
710 /* new RTSP connection request ? */
711 if (poll_entry->revents & POLLIN)
712 new_connection(rtsp_server_fd, 1);
721 /* start waiting for a new HTTP/RTSP request */
722 static void start_wait_request(HTTPContext *c, int is_rtsp)
724 c->buffer_ptr = c->buffer;
725 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
727 c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
728 c->timeout = cur_time +
729 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
732 static void http_send_too_busy_reply(int fd)
735 int len = snprintf(buffer, sizeof(buffer),
736 "HTTP/1.0 503 Server too busy\r\n"
737 "Content-type: text/html\r\n"
739 "<html><head><title>Too busy</title></head><body>\r\n"
740 "<p>The server is too busy to serve your request at this time.</p>\r\n"
741 "<p>The number of current connections is %u, and this exceeds the limit of %u.</p>\r\n"
742 "</body></html>\r\n",
743 nb_connections, config.nb_max_connections);
744 av_assert0(len < sizeof(buffer));
745 if (send(fd, buffer, len, 0) < len)
746 av_log(NULL, AV_LOG_WARNING,
747 "Could not send too-busy reply, send() failed\n");
751 static void new_connection(int server_fd, int is_rtsp)
753 struct sockaddr_in from_addr;
756 HTTPContext *c = NULL;
758 len = sizeof(from_addr);
759 fd = accept(server_fd, (struct sockaddr *)&from_addr,
762 http_log("error during accept %s\n", strerror(errno));
765 if (ff_socket_nonblock(fd, 1) < 0)
766 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
768 if (nb_connections >= config.nb_max_connections) {
769 http_send_too_busy_reply(fd);
773 /* add a new connection */
774 c = av_mallocz(sizeof(HTTPContext));
779 c->poll_entry = NULL;
780 c->from_addr = from_addr;
781 c->buffer_size = IOBUFFER_INIT_SIZE;
782 c->buffer = av_malloc(c->buffer_size);
786 c->next = first_http_ctx;
790 start_wait_request(c, is_rtsp);
796 av_freep(&c->buffer);
802 static void close_connection(HTTPContext *c)
804 HTTPContext **cp, *c1;
806 AVFormatContext *ctx;
809 /* remove connection from list */
810 cp = &first_http_ctx;
819 /* remove references, if any (XXX: do it faster) */
820 for(c1 = first_http_ctx; c1; c1 = c1->next) {
825 /* remove connection associated resources */
829 /* close each frame parser */
830 for(i=0;i<c->fmt_in->nb_streams;i++) {
831 st = c->fmt_in->streams[i];
832 if (st->codec->codec)
833 avcodec_close(st->codec);
835 avformat_close_input(&c->fmt_in);
838 /* free RTP output streams if any */
841 nb_streams = c->stream->nb_streams;
843 for(i=0;i<nb_streams;i++) {
846 av_write_trailer(ctx);
847 av_dict_free(&ctx->metadata);
848 av_freep(&ctx->streams[0]);
851 ffurl_close(c->rtp_handles[i]);
856 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
858 if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
859 av_write_trailer(ctx);
860 av_freep(&c->pb_buffer);
861 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
865 for(i=0; i<ctx->nb_streams; i++)
866 av_freep(&ctx->streams[i]);
867 av_freep(&ctx->streams);
868 av_freep(&ctx->priv_data);
870 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
871 current_bandwidth -= c->stream->bandwidth;
873 /* signal that there is no feed if we are the feeder socket */
874 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
875 c->stream->feed_opened = 0;
879 av_freep(&c->pb_buffer);
880 av_freep(&c->packet_buffer);
881 av_freep(&c->buffer);
886 static int handle_connection(HTTPContext *c)
892 case HTTPSTATE_WAIT_REQUEST:
893 case RTSPSTATE_WAIT_REQUEST:
895 if ((c->timeout - cur_time) < 0)
897 if (c->poll_entry->revents & (POLLERR | POLLHUP))
900 /* no need to read if no events */
901 if (!(c->poll_entry->revents & POLLIN))
905 if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
909 if (ff_neterrno() != AVERROR(EAGAIN) &&
910 ff_neterrno() != AVERROR(EINTR))
914 /* search for end of request. */
915 c->buffer_ptr += len;
917 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
918 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
919 /* request found : parse it and reply */
920 if (c->state == HTTPSTATE_WAIT_REQUEST)
921 ret = http_parse_request(c);
923 ret = rtsp_parse_request(c);
927 } else if (ptr >= c->buffer_end) {
928 /* request too long: cannot do anything */
930 } else goto read_loop;
934 case HTTPSTATE_SEND_HEADER:
935 if (c->poll_entry->revents & (POLLERR | POLLHUP))
938 /* no need to write if no events */
939 if (!(c->poll_entry->revents & POLLOUT))
941 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
943 if (ff_neterrno() != AVERROR(EAGAIN) &&
944 ff_neterrno() != AVERROR(EINTR)) {
945 goto close_connection;
949 c->buffer_ptr += len;
951 c->stream->bytes_served += len;
952 c->data_count += len;
953 if (c->buffer_ptr >= c->buffer_end) {
954 av_freep(&c->pb_buffer);
958 /* all the buffer was sent : synchronize to the incoming
960 c->state = HTTPSTATE_SEND_DATA_HEADER;
961 c->buffer_ptr = c->buffer_end = c->buffer;
965 case HTTPSTATE_SEND_DATA:
966 case HTTPSTATE_SEND_DATA_HEADER:
967 case HTTPSTATE_SEND_DATA_TRAILER:
968 /* for packetized output, we consider we can always write (the
969 * input streams set the speed). It may be better to verify
970 * that we do not rely too much on the kernel queues */
971 if (!c->is_packetized) {
972 if (c->poll_entry->revents & (POLLERR | POLLHUP))
975 /* no need to read if no events */
976 if (!(c->poll_entry->revents & POLLOUT))
979 if (http_send_data(c) < 0)
981 /* close connection if trailer sent */
982 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
984 /* Check if it is a single jpeg frame 123 */
985 if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
989 case HTTPSTATE_RECEIVE_DATA:
990 /* no need to read if no events */
991 if (c->poll_entry->revents & (POLLERR | POLLHUP))
993 if (!(c->poll_entry->revents & POLLIN))
995 if (http_receive_data(c) < 0)
998 case HTTPSTATE_WAIT_FEED:
999 /* no need to read if no events */
1000 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1003 /* nothing to do, we'll be waken up by incoming feed packets */
1006 case RTSPSTATE_SEND_REPLY:
1007 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1008 goto close_connection;
1009 /* no need to write if no events */
1010 if (!(c->poll_entry->revents & POLLOUT))
1012 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1014 if (ff_neterrno() != AVERROR(EAGAIN) &&
1015 ff_neterrno() != AVERROR(EINTR)) {
1016 goto close_connection;
1020 c->buffer_ptr += len;
1021 c->data_count += len;
1022 if (c->buffer_ptr >= c->buffer_end) {
1023 /* all the buffer was sent : wait for a new request */
1024 av_freep(&c->pb_buffer);
1025 start_wait_request(c, 1);
1028 case RTSPSTATE_SEND_PACKET:
1029 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1030 av_freep(&c->packet_buffer);
1033 /* no need to write if no events */
1034 if (!(c->poll_entry->revents & POLLOUT))
1036 len = send(c->fd, c->packet_buffer_ptr,
1037 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1039 if (ff_neterrno() != AVERROR(EAGAIN) &&
1040 ff_neterrno() != AVERROR(EINTR)) {
1041 /* error : close connection */
1042 av_freep(&c->packet_buffer);
1047 c->packet_buffer_ptr += len;
1048 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1049 /* all the buffer was sent : wait for a new request */
1050 av_freep(&c->packet_buffer);
1051 c->state = RTSPSTATE_WAIT_REQUEST;
1054 case HTTPSTATE_READY:
1063 av_freep(&c->pb_buffer);
1067 static int extract_rates(char *rates, int ratelen, const char *request)
1071 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1072 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1073 const char *q = p + 7;
1075 while (*q && *q != '\n' && av_isspace(*q))
1078 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1084 memset(rates, 0xff, ratelen);
1087 while (*q && *q != '\n' && *q != ':')
1090 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1094 if (stream_no < ratelen && stream_no >= 0)
1095 rates[stream_no] = rate_no;
1097 while (*q && *q != '\n' && !av_isspace(*q))
1104 p = strchr(p, '\n');
1114 static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec,
1118 int best_bitrate = 100000000;
1121 for (i = 0; i < feed->nb_streams; i++) {
1122 AVCodecContext *feed_codec = feed->streams[i]->codec;
1124 if (feed_codec->codec_id != codec->codec_id ||
1125 feed_codec->sample_rate != codec->sample_rate ||
1126 feed_codec->width != codec->width ||
1127 feed_codec->height != codec->height)
1130 /* Potential stream */
1132 /* We want the fastest stream less than bit_rate, or the slowest
1133 * faster than bit_rate
1136 if (feed_codec->bit_rate <= bit_rate) {
1137 if (best_bitrate > bit_rate ||
1138 feed_codec->bit_rate > best_bitrate) {
1139 best_bitrate = feed_codec->bit_rate;
1144 if (feed_codec->bit_rate < best_bitrate) {
1145 best_bitrate = feed_codec->bit_rate;
1152 static int modify_current_stream(HTTPContext *c, char *rates)
1155 FFServerStream *req = c->stream;
1156 int action_required = 0;
1158 /* Not much we can do for a feed */
1162 for (i = 0; i < req->nb_streams; i++) {
1163 AVCodecContext *codec = req->streams[i]->codec;
1167 c->switch_feed_streams[i] = req->feed_streams[i];
1170 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1173 /* Wants off or slow */
1174 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1176 /* This doesn't work well when it turns off the only stream! */
1177 c->switch_feed_streams[i] = -2;
1178 c->feed_streams[i] = -2;
1183 if (c->switch_feed_streams[i] >= 0 &&
1184 c->switch_feed_streams[i] != c->feed_streams[i]) {
1185 action_required = 1;
1189 return action_required;
1192 static void get_word(char *buf, int buf_size, const char **pp)
1198 p += strspn(p, SPACE_CHARS);
1200 while (!av_isspace(*p) && *p != '\0') {
1201 if ((q - buf) < buf_size - 1)
1210 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1216 FFServerIPAddressACL *acl = NULL;
1220 f = fopen(stream->dynamic_acl, "r");
1222 perror(stream->dynamic_acl);
1226 acl = av_mallocz(sizeof(FFServerIPAddressACL));
1233 while (fgets(line, sizeof(line), f)) {
1236 while (av_isspace(*p))
1238 if (*p == '\0' || *p == '#')
1240 ffserver_get_arg(cmd, sizeof(cmd), &p);
1242 if (!av_strcasecmp(cmd, "ACL"))
1243 ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1251 static void free_acl_list(FFServerIPAddressACL *in_acl)
1253 FFServerIPAddressACL *pacl, *pacl2;
1263 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1265 enum FFServerIPAddressAction last_action = IP_DENY;
1266 FFServerIPAddressACL *acl;
1267 struct in_addr *src = &c->from_addr.sin_addr;
1268 unsigned long src_addr = src->s_addr;
1270 for (acl = in_acl; acl; acl = acl->next) {
1271 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1272 return (acl->action == IP_ALLOW) ? 1 : 0;
1273 last_action = acl->action;
1276 /* Nothing matched, so return not the last action */
1277 return (last_action == IP_DENY) ? 1 : 0;
1280 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1283 FFServerIPAddressACL *acl;
1285 /* if stream->acl is null validate_acl_list will return 1 */
1286 ret = validate_acl_list(stream->acl, c);
1288 if (stream->dynamic_acl[0]) {
1289 acl = parse_dynamic_acl(stream, c);
1290 ret = validate_acl_list(acl, c);
1298 * compute the real filename of a file by matching it without its
1299 * extensions to all the stream's filenames
1301 static void compute_real_filename(char *filename, int max_size)
1306 FFServerStream *stream;
1308 av_strlcpy(file1, filename, sizeof(file1));
1309 p = strrchr(file1, '.');
1312 for(stream = config.first_stream; stream; stream = stream->next) {
1313 av_strlcpy(file2, stream->filename, sizeof(file2));
1314 p = strrchr(file2, '.');
1317 if (!strcmp(file1, file2)) {
1318 av_strlcpy(filename, stream->filename, max_size);
1333 /* parse HTTP request and prepare header */
1334 static int http_parse_request(HTTPContext *c)
1338 enum RedirType redir_type;
1340 char info[1024], filename[1024];
1344 const char *mime_type;
1345 FFServerStream *stream;
1348 const char *useragent = 0;
1351 get_word(cmd, sizeof(cmd), &p);
1352 av_strlcpy(c->method, cmd, sizeof(c->method));
1354 if (!strcmp(cmd, "GET"))
1356 else if (!strcmp(cmd, "POST"))
1361 get_word(url, sizeof(url), &p);
1362 av_strlcpy(c->url, url, sizeof(c->url));
1364 get_word(protocol, sizeof(protocol), (const char **)&p);
1365 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1368 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1371 http_log("%s - - New connection: %s %s\n",
1372 inet_ntoa(c->from_addr.sin_addr), cmd, url);
1374 /* find the filename and the optional info string in the request */
1375 p1 = strchr(url, '?');
1377 av_strlcpy(info, p1, sizeof(info));
1382 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1384 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1385 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1387 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1391 p = strchr(p, '\n');
1398 redir_type = REDIR_NONE;
1399 if (av_match_ext(filename, "asx")) {
1400 redir_type = REDIR_ASX;
1401 filename[strlen(filename)-1] = 'f';
1402 } else if (av_match_ext(filename, "asf") &&
1403 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1404 /* if this isn't WMP or lookalike, return the redirector file */
1405 redir_type = REDIR_ASF;
1406 } else if (av_match_ext(filename, "rpm,ram")) {
1407 redir_type = REDIR_RAM;
1408 strcpy(filename + strlen(filename)-2, "m");
1409 } else if (av_match_ext(filename, "rtsp")) {
1410 redir_type = REDIR_RTSP;
1411 compute_real_filename(filename, sizeof(filename) - 1);
1412 } else if (av_match_ext(filename, "sdp")) {
1413 redir_type = REDIR_SDP;
1414 compute_real_filename(filename, sizeof(filename) - 1);
1417 /* "redirect" request to index.html */
1418 if (!strlen(filename))
1419 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1421 stream = config.first_stream;
1423 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1425 stream = stream->next;
1428 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1429 http_log("File '%s' not found\n", url);
1434 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1435 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1437 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1438 c->http_error = 301;
1440 snprintf(q, c->buffer_size,
1441 "HTTP/1.0 301 Moved\r\n"
1443 "Content-type: text/html\r\n"
1445 "<html><head><title>Moved</title></head><body>\r\n"
1446 "You should be <a href=\"%s\">redirected</a>.\r\n"
1447 "</body></html>\r\n",
1448 stream->feed_filename, stream->feed_filename);
1450 /* prepare output buffer */
1451 c->buffer_ptr = c->buffer;
1453 c->state = HTTPSTATE_SEND_HEADER;
1457 /* If this is WMP, get the rate information */
1458 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1459 if (modify_current_stream(c, ratebuf)) {
1460 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1461 if (c->switch_feed_streams[i] >= 0)
1462 c->switch_feed_streams[i] = -1;
1467 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1468 current_bandwidth += stream->bandwidth;
1470 /* If already streaming this feed, do not let another feeder start */
1471 if (stream->feed_opened) {
1472 snprintf(msg, sizeof(msg), "This feed is already being received.");
1473 http_log("Feed '%s' already being received\n", stream->feed_filename);
1477 if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1478 c->http_error = 503;
1480 snprintf(q, c->buffer_size,
1481 "HTTP/1.0 503 Server too busy\r\n"
1482 "Content-type: text/html\r\n"
1484 "<html><head><title>Too busy</title></head><body>\r\n"
1485 "<p>The server is too busy to serve your request at this time.</p>\r\n"
1486 "<p>The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "
1487 "and this exceeds the limit of %"PRIu64"kbit/sec.</p>\r\n"
1488 "</body></html>\r\n",
1489 current_bandwidth, config.max_bandwidth);
1491 /* prepare output buffer */
1492 c->buffer_ptr = c->buffer;
1494 c->state = HTTPSTATE_SEND_HEADER;
1498 if (redir_type != REDIR_NONE) {
1499 const char *hostinfo = 0;
1501 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1502 if (av_strncasecmp(p, "Host:", 5) == 0) {
1506 p = strchr(p, '\n');
1517 while (av_isspace(*hostinfo))
1520 eoh = strchr(hostinfo, '\n');
1522 if (eoh[-1] == '\r')
1525 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1526 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1527 hostbuf[eoh - hostinfo] = 0;
1529 c->http_error = 200;
1531 switch(redir_type) {
1533 snprintf(q, c->buffer_size,
1534 "HTTP/1.0 200 ASX Follows\r\n"
1535 "Content-type: video/x-ms-asf\r\n"
1537 "<ASX Version=\"3\">\r\n"
1538 //"<!-- Autogenerated by ffserver -->\r\n"
1539 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1540 "</ASX>\r\n", hostbuf, filename, info);
1544 snprintf(q, c->buffer_size,
1545 "HTTP/1.0 200 RAM Follows\r\n"
1546 "Content-type: audio/x-pn-realaudio\r\n"
1548 "# Autogenerated by ffserver\r\n"
1549 "http://%s/%s%s\r\n", hostbuf, filename, info);
1553 snprintf(q, c->buffer_size,
1554 "HTTP/1.0 200 ASF Redirect follows\r\n"
1555 "Content-type: video/x-ms-asf\r\n"
1558 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1563 char hostname[256], *p;
1564 /* extract only hostname */
1565 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1566 p = strrchr(hostname, ':');
1569 snprintf(q, c->buffer_size,
1570 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1571 /* XXX: incorrect MIME type ? */
1572 "Content-type: application/x-rtsp\r\n"
1574 "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1583 struct sockaddr_in my_addr;
1585 snprintf(q, c->buffer_size,
1586 "HTTP/1.0 200 OK\r\n"
1587 "Content-type: application/sdp\r\n"
1591 len = sizeof(my_addr);
1593 /* XXX: Should probably fail? */
1594 if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1595 http_log("getsockname() failed\n");
1597 /* XXX: should use a dynamic buffer */
1598 sdp_data_size = prepare_sdp_description(stream,
1601 if (sdp_data_size > 0) {
1602 memcpy(q, sdp_data, sdp_data_size);
1614 /* prepare output buffer */
1615 c->buffer_ptr = c->buffer;
1617 c->state = HTTPSTATE_SEND_HEADER;
1623 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1627 stream->conns_served++;
1629 /* XXX: add there authenticate and IP match */
1632 /* if post, it means a feed is being sent */
1633 if (!stream->is_feed) {
1634 /* However it might be a status report from WMP! Let us log the
1635 * data as it might come handy one day. */
1636 const char *logline = 0;
1639 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1640 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1644 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1645 client_id = strtol(p + 18, 0, 10);
1646 p = strchr(p, '\n');
1654 char *eol = strchr(logline, '\n');
1659 if (eol[-1] == '\r')
1661 http_log("%.*s\n", (int) (eol - logline), logline);
1662 c->suppress_log = 1;
1667 http_log("\nGot request:\n%s\n", c->buffer);
1670 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1673 /* Now we have to find the client_id */
1674 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1675 if (wmpc->wmp_client_id == client_id)
1679 if (wmpc && modify_current_stream(wmpc, ratebuf))
1680 wmpc->switch_pending = 1;
1683 snprintf(msg, sizeof(msg), "POST command not handled");
1687 if (http_start_receive_data(c) < 0) {
1688 snprintf(msg, sizeof(msg), "could not open feed");
1692 c->state = HTTPSTATE_RECEIVE_DATA;
1697 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1698 http_log("\nGot request:\n%s\n", c->buffer);
1701 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1704 /* open input stream */
1705 if (open_input_stream(c, info) < 0) {
1706 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1710 /* prepare HTTP header */
1712 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1713 mime_type = c->stream->fmt->mime_type;
1715 mime_type = "application/x-octet-stream";
1716 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1718 /* for asf, we need extra headers */
1719 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1720 /* Need to allocate a client id */
1722 c->wmp_client_id = av_lfg_get(&random_state);
1724 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);
1726 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1727 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1728 q = c->buffer + strlen(c->buffer);
1730 /* prepare output buffer */
1732 c->buffer_ptr = c->buffer;
1734 c->state = HTTPSTATE_SEND_HEADER;
1737 c->http_error = 404;
1740 snprintf(q, c->buffer_size,
1741 "HTTP/1.0 404 Not Found\r\n"
1742 "Content-type: text/html\r\n"
1745 "<head><title>404 Not Found</title></head>\n"
1749 /* prepare output buffer */
1750 c->buffer_ptr = c->buffer;
1752 c->state = HTTPSTATE_SEND_HEADER;
1756 /* horrible: we use this value to avoid
1757 * going to the send data state */
1758 c->http_error = 200;
1759 c->state = HTTPSTATE_SEND_HEADER;
1763 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1765 static const char suffix[] = " kMGTP";
1768 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1770 avio_printf(pb, "%"PRId64"%c", count, *s);
1773 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1776 const char *type = "unknown";
1777 char parameters[64];
1781 stream_no = stream->nb_streams;
1783 avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
1784 "type<th>kbits/s<th align=left>codec<th align=left>"
1787 for (i = 0; i < stream_no; i++) {
1788 st = stream->streams[i];
1789 codec = avcodec_find_encoder(st->codec->codec_id);
1793 switch(st->codec->codec_type) {
1794 case AVMEDIA_TYPE_AUDIO:
1796 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1797 st->codec->channels, st->codec->sample_rate);
1799 case AVMEDIA_TYPE_VIDEO:
1801 snprintf(parameters, sizeof(parameters),
1802 "%dx%d, q=%d-%d, fps=%d", st->codec->width,
1803 st->codec->height, st->codec->qmin, st->codec->qmax,
1804 st->codec->time_base.den / st->codec->time_base.num);
1810 avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
1812 i, type, (int64_t)st->codec->bit_rate/1000,
1813 codec ? codec->name : "", parameters);
1816 avio_printf(pb, "</table>\n");
1819 static void compute_status(HTTPContext *c)
1822 FFServerStream *stream;
1828 if (avio_open_dyn_buf(&pb) < 0) {
1829 /* XXX: return an error ? */
1830 c->buffer_ptr = c->buffer;
1831 c->buffer_end = c->buffer;
1835 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1836 avio_printf(pb, "Content-type: text/html\r\n");
1837 avio_printf(pb, "Pragma: no-cache\r\n");
1838 avio_printf(pb, "\r\n");
1840 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1841 if (c->stream->feed_filename[0])
1842 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1843 c->stream->feed_filename);
1844 avio_printf(pb, "</head>\n<body>");
1845 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1847 avio_printf(pb, "<h2>Available Streams</h2>\n");
1848 avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
1849 avio_printf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbits/s<th align=left>Video<br>kbits/s<th><br>Codec<th align=left>Audio<br>kbits/s<th><br>Codec<th align=left valign=top>Feed\n");
1850 stream = config.first_stream;
1852 char sfilename[1024];
1855 if (stream->feed == stream) {
1856 stream = stream->next;
1860 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1861 eosf = sfilename + strlen(sfilename);
1862 if (eosf - sfilename >= 4) {
1863 if (strcmp(eosf - 4, ".asf") == 0)
1864 strcpy(eosf - 4, ".asx");
1865 else if (strcmp(eosf - 3, ".rm") == 0)
1866 strcpy(eosf - 3, ".ram");
1867 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1868 /* generate a sample RTSP director if
1869 * unicast. Generate an SDP redirector if
1871 eosf = strrchr(sfilename, '.');
1873 eosf = sfilename + strlen(sfilename);
1874 if (stream->is_multicast)
1875 strcpy(eosf, ".sdp");
1877 strcpy(eosf, ".rtsp");
1881 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1882 sfilename, stream->filename);
1883 avio_printf(pb, "<td align=right> %d <td align=right> ",
1884 stream->conns_served);
1885 fmt_bytecount(pb, stream->bytes_served);
1887 switch(stream->stream_type) {
1888 case STREAM_TYPE_LIVE: {
1889 int audio_bit_rate = 0;
1890 int video_bit_rate = 0;
1891 const char *audio_codec_name = "";
1892 const char *video_codec_name = "";
1893 const char *audio_codec_name_extra = "";
1894 const char *video_codec_name_extra = "";
1896 for(i=0;i<stream->nb_streams;i++) {
1897 AVStream *st = stream->streams[i];
1898 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1900 switch(st->codec->codec_type) {
1901 case AVMEDIA_TYPE_AUDIO:
1902 audio_bit_rate += st->codec->bit_rate;
1904 if (*audio_codec_name)
1905 audio_codec_name_extra = "...";
1906 audio_codec_name = codec->name;
1909 case AVMEDIA_TYPE_VIDEO:
1910 video_bit_rate += st->codec->bit_rate;
1912 if (*video_codec_name)
1913 video_codec_name_extra = "...";
1914 video_codec_name = codec->name;
1917 case AVMEDIA_TYPE_DATA:
1918 video_bit_rate += st->codec->bit_rate;
1925 avio_printf(pb, "<td align=center> %s <td align=right> %d "
1926 "<td align=right> %d <td> %s %s <td align=right> "
1928 stream->fmt->name, stream->bandwidth,
1929 video_bit_rate / 1000, video_codec_name,
1930 video_codec_name_extra, audio_bit_rate / 1000,
1931 audio_codec_name, audio_codec_name_extra);
1934 avio_printf(pb, "<td>%s", stream->feed->filename);
1936 avio_printf(pb, "<td>%s", stream->feed_filename);
1937 avio_printf(pb, "\n");
1941 avio_printf(pb, "<td align=center> - <td align=right> - "
1942 "<td align=right> - <td><td align=right> - <td>\n");
1945 stream = stream->next;
1947 avio_printf(pb, "</table>\n");
1949 stream = config.first_stream;
1952 if (stream->feed != stream) {
1953 stream = stream->next;
1957 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
1959 avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
1966 /* This is somewhat linux specific I guess */
1967 snprintf(ps_cmd, sizeof(ps_cmd),
1968 "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
1969 (int64_t) stream->pid);
1971 pid_stat = popen(ps_cmd, "r");
1976 if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
1977 avio_printf(pb, "Currently using %s%% of the cpu. "
1978 "Total time used %s.\n",
1986 avio_printf(pb, "<p>");
1989 print_stream_params(pb, stream);
1990 stream = stream->next;
1993 /* connection status */
1994 avio_printf(pb, "<h2>Connection Status</h2>\n");
1996 avio_printf(pb, "Number of connections: %d / %d<br>\n",
1997 nb_connections, config.nb_max_connections);
1999 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2000 current_bandwidth, config.max_bandwidth);
2002 avio_printf(pb, "<table>\n");
2003 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
2004 "bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
2005 c1 = first_http_ctx;
2013 for (j = 0; j < c1->stream->nb_streams; j++) {
2014 if (!c1->stream->feed)
2015 bitrate += c1->stream->streams[j]->codec->bit_rate;
2016 else if (c1->feed_streams[j] >= 0)
2017 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
2022 p = inet_ntoa(c1->from_addr.sin_addr);
2023 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
2025 i, c1->stream ? c1->stream->filename : "",
2026 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
2027 c1->protocol, http_state[c1->state]);
2028 fmt_bytecount(pb, bitrate);
2029 avio_printf(pb, "<td align=right>");
2030 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2031 avio_printf(pb, "<td align=right>");
2032 fmt_bytecount(pb, c1->data_count);
2033 avio_printf(pb, "\n");
2036 avio_printf(pb, "</table>\n");
2041 avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
2042 avio_printf(pb, "</body>\n</html>\n");
2044 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2045 c->buffer_ptr = c->pb_buffer;
2046 c->buffer_end = c->pb_buffer + len;
2049 static int open_input_stream(HTTPContext *c, const char *info)
2052 char input_filename[1024];
2053 AVFormatContext *s = NULL;
2054 int buf_size, i, ret;
2057 /* find file name */
2058 if (c->stream->feed) {
2059 strcpy(input_filename, c->stream->feed->feed_filename);
2060 buf_size = FFM_PACKET_SIZE;
2061 /* compute position (absolute time) */
2062 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2063 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2064 http_log("Invalid date specification '%s' for stream\n", buf);
2067 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2068 int prebuffer = strtol(buf, 0, 10);
2069 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2071 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2073 strcpy(input_filename, c->stream->feed_filename);
2075 /* compute position (relative time) */
2076 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2077 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2078 http_log("Invalid date specification '%s' for stream\n", buf);
2084 if (!input_filename[0]) {
2085 http_log("No filename was specified for stream\n");
2086 return AVERROR(EINVAL);
2090 ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2091 &c->stream->in_opts);
2093 http_log("Could not open input '%s': %s\n",
2094 input_filename, av_err2str(ret));
2098 /* set buffer size */
2100 ret = ffio_set_buf_size(s->pb, buf_size);
2102 http_log("Failed to set buffer size\n");
2107 s->flags |= AVFMT_FLAG_GENPTS;
2109 if (strcmp(s->iformat->name, "ffm") &&
2110 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2111 http_log("Could not find stream info for input '%s'\n", input_filename);
2112 avformat_close_input(&s);
2116 /* choose stream as clock source (we favor the video stream if
2117 * present) for packet sending */
2118 c->pts_stream_index = 0;
2119 for(i=0;i<c->stream->nb_streams;i++) {
2120 if (c->pts_stream_index == 0 &&
2121 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2122 c->pts_stream_index = i;
2126 if (c->fmt_in->iformat->read_seek)
2127 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2128 /* set the start time (needed for maxtime and RTP packet timing) */
2129 c->start_time = cur_time;
2130 c->first_pts = AV_NOPTS_VALUE;
2134 /* return the server clock (in us) */
2135 static int64_t get_server_clock(HTTPContext *c)
2137 /* compute current pts value from system time */
2138 return (cur_time - c->start_time) * 1000;
2141 /* return the estimated time (in us) at which the current packet must be sent */
2142 static int64_t get_packet_send_clock(HTTPContext *c)
2144 int bytes_left, bytes_sent, frame_bytes;
2146 frame_bytes = c->cur_frame_bytes;
2147 if (frame_bytes <= 0)
2150 bytes_left = c->buffer_end - c->buffer_ptr;
2151 bytes_sent = frame_bytes - bytes_left;
2152 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2156 static int http_prepare_data(HTTPContext *c)
2159 AVFormatContext *ctx;
2161 av_freep(&c->pb_buffer);
2163 case HTTPSTATE_SEND_DATA_HEADER:
2164 ctx = avformat_alloc_context();
2166 return AVERROR(ENOMEM);
2169 av_dict_copy(&(c->fmt_ctx.metadata), c->stream->metadata, 0);
2170 c->fmt_ctx.streams = av_mallocz_array(c->stream->nb_streams,
2171 sizeof(AVStream *));
2172 if (!c->fmt_ctx.streams)
2173 return AVERROR(ENOMEM);
2175 for(i=0;i<c->stream->nb_streams;i++) {
2177 c->fmt_ctx.streams[i] = av_mallocz(sizeof(AVStream));
2179 /* if file or feed, then just take streams from FFServerStream
2181 if (!c->stream->feed ||
2182 c->stream->feed == c->stream)
2183 src = c->stream->streams[i];
2185 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2187 *(c->fmt_ctx.streams[i]) = *src;
2188 c->fmt_ctx.streams[i]->priv_data = 0;
2189 /* XXX: should be done in AVStream, not in codec */
2190 c->fmt_ctx.streams[i]->codec->frame_number = 0;
2192 /* set output format parameters */
2193 c->fmt_ctx.oformat = c->stream->fmt;
2194 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2196 c->got_key_frame = 0;
2198 /* prepare header and save header data in a stream */
2199 if (avio_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2200 /* XXX: potential leak */
2203 c->fmt_ctx.pb->seekable = 0;
2206 * HACK to avoid MPEG-PS muxer to spit many underflow errors
2207 * Default value from FFmpeg
2208 * Try to set it using configuration option
2210 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2212 if ((ret = avformat_write_header(&c->fmt_ctx, NULL)) < 0) {
2213 http_log("Error writing output header for stream '%s': %s\n",
2214 c->stream->filename, av_err2str(ret));
2217 av_dict_free(&c->fmt_ctx.metadata);
2219 len = avio_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2220 c->buffer_ptr = c->pb_buffer;
2221 c->buffer_end = c->pb_buffer + len;
2223 c->state = HTTPSTATE_SEND_DATA;
2224 c->last_packet_sent = 0;
2226 case HTTPSTATE_SEND_DATA:
2227 /* find a new packet */
2228 /* read a packet from the input stream */
2229 if (c->stream->feed)
2230 ffm_set_write_index(c->fmt_in,
2231 c->stream->feed->feed_write_index,
2232 c->stream->feed->feed_size);
2234 if (c->stream->max_time &&
2235 c->stream->max_time + c->start_time - cur_time < 0)
2236 /* We have timed out */
2237 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2241 ret = av_read_frame(c->fmt_in, &pkt);
2243 if (c->stream->feed) {
2244 /* if coming from feed, it means we reached the end of the
2245 * ffm file, so must wait for more data */
2246 c->state = HTTPSTATE_WAIT_FEED;
2247 return 1; /* state changed */
2249 if (ret == AVERROR(EAGAIN)) {
2250 /* input not ready, come back later */
2253 if (c->stream->loop) {
2254 avformat_close_input(&c->fmt_in);
2255 if (open_input_stream(c, "") < 0)
2260 /* must send trailer now because EOF or error */
2261 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2264 int source_index = pkt.stream_index;
2265 /* update first pts if needed */
2266 if (c->first_pts == AV_NOPTS_VALUE) {
2267 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2268 c->start_time = cur_time;
2270 /* send it to the appropriate stream */
2271 if (c->stream->feed) {
2272 /* if coming from a feed, select the right stream */
2273 if (c->switch_pending) {
2274 c->switch_pending = 0;
2275 for(i=0;i<c->stream->nb_streams;i++) {
2276 if (c->switch_feed_streams[i] == pkt.stream_index)
2277 if (pkt.flags & AV_PKT_FLAG_KEY)
2278 c->switch_feed_streams[i] = -1;
2279 if (c->switch_feed_streams[i] >= 0)
2280 c->switch_pending = 1;
2283 for(i=0;i<c->stream->nb_streams;i++) {
2284 if (c->stream->feed_streams[i] == pkt.stream_index) {
2285 AVStream *st = c->fmt_in->streams[source_index];
2286 pkt.stream_index = i;
2287 if (pkt.flags & AV_PKT_FLAG_KEY &&
2288 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2289 c->stream->nb_streams == 1))
2290 c->got_key_frame = 1;
2291 if (!c->stream->send_on_key || c->got_key_frame)
2296 AVCodecContext *codec;
2297 AVStream *ist, *ost;
2299 ist = c->fmt_in->streams[source_index];
2300 /* specific handling for RTP: we use several
2301 * output streams (one for each RTP connection).
2302 * XXX: need more abstract handling */
2303 if (c->is_packetized) {
2304 /* compute send time and duration */
2305 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2306 c->cur_pts -= c->first_pts;
2307 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2308 /* find RTP context */
2309 c->packet_stream_index = pkt.stream_index;
2310 ctx = c->rtp_ctx[c->packet_stream_index];
2312 av_free_packet(&pkt);
2315 codec = ctx->streams[0]->codec;
2316 /* only one stream per RTP connection */
2317 pkt.stream_index = 0;
2321 codec = ctx->streams[pkt.stream_index]->codec;
2324 if (c->is_packetized) {
2325 int max_packet_size;
2326 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2327 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2329 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2330 ret = ffio_open_dyn_packet_buf(&ctx->pb,
2333 ret = avio_open_dyn_buf(&ctx->pb);
2336 /* XXX: potential leak */
2339 ost = ctx->streams[pkt.stream_index];
2341 ctx->pb->seekable = 0;
2342 if (pkt.dts != AV_NOPTS_VALUE)
2343 pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2345 if (pkt.pts != AV_NOPTS_VALUE)
2346 pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2348 pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2350 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2351 http_log("Error writing frame to output for stream '%s': %s\n",
2352 c->stream->filename, av_err2str(ret));
2353 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2356 av_freep(&c->pb_buffer);
2357 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2358 c->cur_frame_bytes = len;
2359 c->buffer_ptr = c->pb_buffer;
2360 c->buffer_end = c->pb_buffer + len;
2362 codec->frame_number++;
2364 av_free_packet(&pkt);
2368 av_free_packet(&pkt);
2373 case HTTPSTATE_SEND_DATA_TRAILER:
2374 /* last packet test ? */
2375 if (c->last_packet_sent || c->is_packetized)
2378 /* prepare header */
2379 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2380 /* XXX: potential leak */
2383 c->fmt_ctx.pb->seekable = 0;
2384 av_write_trailer(ctx);
2385 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2386 c->buffer_ptr = c->pb_buffer;
2387 c->buffer_end = c->pb_buffer + len;
2389 c->last_packet_sent = 1;
2395 /* should convert the format at the same time */
2396 /* send data starting at c->buffer_ptr to the output connection
2397 * (either UDP or TCP)
2399 static int http_send_data(HTTPContext *c)
2404 if (c->buffer_ptr >= c->buffer_end) {
2405 ret = http_prepare_data(c);
2409 /* state change requested */
2412 if (c->is_packetized) {
2413 /* RTP data output */
2414 len = c->buffer_end - c->buffer_ptr;
2416 /* fail safe - should never happen */
2418 c->buffer_ptr = c->buffer_end;
2421 len = (c->buffer_ptr[0] << 24) |
2422 (c->buffer_ptr[1] << 16) |
2423 (c->buffer_ptr[2] << 8) |
2425 if (len > (c->buffer_end - c->buffer_ptr))
2427 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2428 /* nothing to send yet: we can wait */
2432 c->data_count += len;
2433 update_datarate(&c->datarate, c->data_count);
2435 c->stream->bytes_served += len;
2437 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2438 /* RTP packets are sent inside the RTSP TCP connection */
2440 int interleaved_index, size;
2442 HTTPContext *rtsp_c;
2445 /* if no RTSP connection left, error */
2448 /* if already sending something, then wait. */
2449 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2451 if (avio_open_dyn_buf(&pb) < 0)
2453 interleaved_index = c->packet_stream_index * 2;
2454 /* RTCP packets are sent at odd indexes */
2455 if (c->buffer_ptr[1] == 200)
2456 interleaved_index++;
2457 /* write RTSP TCP header */
2459 header[1] = interleaved_index;
2460 header[2] = len >> 8;
2462 avio_write(pb, header, 4);
2463 /* write RTP packet data */
2465 avio_write(pb, c->buffer_ptr, len);
2466 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2467 /* prepare asynchronous TCP sending */
2468 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2469 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2470 c->buffer_ptr += len;
2472 /* send everything we can NOW */
2473 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2474 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2476 rtsp_c->packet_buffer_ptr += len;
2477 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2478 /* if we could not send all the data, we will
2479 * send it later, so a new state is needed to
2480 * "lock" the RTSP TCP connection */
2481 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2484 /* all data has been sent */
2485 av_freep(&c->packet_buffer);
2487 /* send RTP packet directly in UDP */
2489 ffurl_write(c->rtp_handles[c->packet_stream_index],
2490 c->buffer_ptr, len);
2491 c->buffer_ptr += len;
2492 /* here we continue as we can send several packets
2496 /* TCP data output */
2497 len = send(c->fd, c->buffer_ptr,
2498 c->buffer_end - c->buffer_ptr, 0);
2500 if (ff_neterrno() != AVERROR(EAGAIN) &&
2501 ff_neterrno() != AVERROR(EINTR))
2502 /* error : close connection */
2507 c->buffer_ptr += len;
2509 c->data_count += len;
2510 update_datarate(&c->datarate, c->data_count);
2512 c->stream->bytes_served += len;
2520 static int http_start_receive_data(HTTPContext *c)
2525 if (c->stream->feed_opened) {
2526 http_log("Stream feed '%s' was not opened\n",
2527 c->stream->feed_filename);
2528 return AVERROR(EINVAL);
2531 /* Don't permit writing to this one */
2532 if (c->stream->readonly) {
2533 http_log("Cannot write to read-only file '%s'\n",
2534 c->stream->feed_filename);
2535 return AVERROR(EINVAL);
2539 fd = open(c->stream->feed_filename, O_RDWR);
2541 ret = AVERROR(errno);
2542 http_log("Could not open feed file '%s': %s\n",
2543 c->stream->feed_filename, strerror(errno));
2548 if (c->stream->truncate) {
2549 /* truncate feed file */
2550 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2551 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2552 if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2553 ret = AVERROR(errno);
2554 http_log("Error truncating feed file '%s': %s\n",
2555 c->stream->feed_filename, strerror(errno));
2559 ret = ffm_read_write_index(fd);
2561 http_log("Error reading write index from feed file '%s': %s\n",
2562 c->stream->feed_filename, strerror(errno));
2565 c->stream->feed_write_index = ret;
2568 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2570 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2571 lseek(fd, 0, SEEK_SET);
2573 /* init buffer input */
2574 c->buffer_ptr = c->buffer;
2575 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2576 c->stream->feed_opened = 1;
2577 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2581 static int http_receive_data(HTTPContext *c)
2584 int len, loop_run = 0;
2586 while (c->chunked_encoding && !c->chunk_size &&
2587 c->buffer_end > c->buffer_ptr) {
2588 /* read chunk header, if present */
2589 len = recv(c->fd, c->buffer_ptr, 1, 0);
2592 if (ff_neterrno() != AVERROR(EAGAIN) &&
2593 ff_neterrno() != AVERROR(EINTR))
2594 /* error : close connection */
2597 } else if (len == 0) {
2598 /* end of connection : close it */
2600 } else if (c->buffer_ptr - c->buffer >= 2 &&
2601 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2602 c->chunk_size = strtol(c->buffer, 0, 16);
2603 if (c->chunk_size == 0) // end of stream
2605 c->buffer_ptr = c->buffer;
2607 } else if (++loop_run > 10)
2608 /* no chunk header, abort */
2614 if (c->buffer_end > c->buffer_ptr) {
2615 len = recv(c->fd, c->buffer_ptr,
2616 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2618 if (ff_neterrno() != AVERROR(EAGAIN) &&
2619 ff_neterrno() != AVERROR(EINTR))
2620 /* error : close connection */
2622 } else if (len == 0)
2623 /* end of connection : close it */
2626 c->chunk_size -= len;
2627 c->buffer_ptr += len;
2628 c->data_count += len;
2629 update_datarate(&c->datarate, c->data_count);
2633 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2634 if (c->buffer[0] != 'f' ||
2635 c->buffer[1] != 'm') {
2636 http_log("Feed stream has become desynchronized -- disconnecting\n");
2641 if (c->buffer_ptr >= c->buffer_end) {
2642 FFServerStream *feed = c->stream;
2643 /* a packet has been received : write it in the store, except
2645 if (c->data_count > FFM_PACKET_SIZE) {
2646 /* XXX: use llseek or url_seek
2647 * XXX: Should probably fail? */
2648 if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2649 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2651 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2652 http_log("Error writing to feed file: %s\n", strerror(errno));
2656 feed->feed_write_index += FFM_PACKET_SIZE;
2657 /* update file size */
2658 if (feed->feed_write_index > c->stream->feed_size)
2659 feed->feed_size = feed->feed_write_index;
2661 /* handle wrap around if max file size reached */
2662 if (c->stream->feed_max_size &&
2663 feed->feed_write_index >= c->stream->feed_max_size)
2664 feed->feed_write_index = FFM_PACKET_SIZE;
2667 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2668 http_log("Error writing index to feed file: %s\n",
2673 /* wake up any waiting connections */
2674 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2675 if (c1->state == HTTPSTATE_WAIT_FEED &&
2676 c1->stream->feed == c->stream->feed)
2677 c1->state = HTTPSTATE_SEND_DATA;
2680 /* We have a header in our hands that contains useful data */
2681 AVFormatContext *s = avformat_alloc_context();
2683 AVInputFormat *fmt_in;
2689 /* use feed output format name to find corresponding input format */
2690 fmt_in = av_find_input_format(feed->fmt->name);
2694 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2695 0, NULL, NULL, NULL, NULL);
2702 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2707 /* Now we have the actual streams */
2708 if (s->nb_streams != feed->nb_streams) {
2709 avformat_close_input(&s);
2711 http_log("Feed '%s' stream number does not match registered feed\n",
2712 c->stream->feed_filename);
2716 for (i = 0; i < s->nb_streams; i++) {
2717 AVStream *fst = feed->streams[i];
2718 AVStream *st = s->streams[i];
2719 avcodec_copy_context(fst->codec, st->codec);
2722 avformat_close_input(&s);
2725 c->buffer_ptr = c->buffer;
2730 c->stream->feed_opened = 0;
2732 /* wake up any waiting connections to stop waiting for feed */
2733 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2734 if (c1->state == HTTPSTATE_WAIT_FEED &&
2735 c1->stream->feed == c->stream->feed)
2736 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2741 /********************************************************************/
2744 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2751 str = RTSP_STATUS_CODE2STRING(error_number);
2753 str = "Unknown Error";
2755 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2756 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2758 /* output GMT time */
2761 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2762 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2765 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2767 rtsp_reply_header(c, error_number);
2768 avio_printf(c->pb, "\r\n");
2771 static int rtsp_parse_request(HTTPContext *c)
2773 const char *p, *p1, *p2;
2779 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2781 c->buffer_ptr[0] = '\0';
2784 get_word(cmd, sizeof(cmd), &p);
2785 get_word(url, sizeof(url), &p);
2786 get_word(protocol, sizeof(protocol), &p);
2788 av_strlcpy(c->method, cmd, sizeof(c->method));
2789 av_strlcpy(c->url, url, sizeof(c->url));
2790 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2792 if (avio_open_dyn_buf(&c->pb) < 0) {
2793 /* XXX: cannot do more */
2794 c->pb = NULL; /* safety */
2798 /* check version name */
2799 if (strcmp(protocol, "RTSP/1.0")) {
2800 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2804 /* parse each header line */
2805 /* skip to next line */
2806 while (*p != '\n' && *p != '\0')
2810 while (*p != '\0') {
2811 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2815 if (p2 > p && p2[-1] == '\r')
2817 /* skip empty line */
2821 if (len > sizeof(line) - 1)
2822 len = sizeof(line) - 1;
2823 memcpy(line, p, len);
2825 ff_rtsp_parse_line(header, line, NULL, NULL);
2829 /* handle sequence number */
2830 c->seq = header->seq;
2832 if (!strcmp(cmd, "DESCRIBE"))
2833 rtsp_cmd_describe(c, url);
2834 else if (!strcmp(cmd, "OPTIONS"))
2835 rtsp_cmd_options(c, url);
2836 else if (!strcmp(cmd, "SETUP"))
2837 rtsp_cmd_setup(c, url, header);
2838 else if (!strcmp(cmd, "PLAY"))
2839 rtsp_cmd_play(c, url, header);
2840 else if (!strcmp(cmd, "PAUSE"))
2841 rtsp_cmd_interrupt(c, url, header, 1);
2842 else if (!strcmp(cmd, "TEARDOWN"))
2843 rtsp_cmd_interrupt(c, url, header, 0);
2845 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2848 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2849 c->pb = NULL; /* safety */
2851 /* XXX: cannot do more */
2854 c->buffer_ptr = c->pb_buffer;
2855 c->buffer_end = c->pb_buffer + len;
2856 c->state = RTSPSTATE_SEND_REPLY;
2860 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
2861 struct in_addr my_ip)
2863 AVFormatContext *avc;
2864 AVStream *avs = NULL;
2865 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
2866 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
2871 avc = avformat_alloc_context();
2872 if (!avc || !rtp_format)
2875 avc->oformat = rtp_format;
2876 av_dict_set(&avc->metadata, "title",
2877 entry ? entry->value : "No Title", 0);
2878 avc->nb_streams = stream->nb_streams;
2879 if (stream->is_multicast) {
2880 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2881 inet_ntoa(stream->multicast_ip),
2882 stream->multicast_port, stream->multicast_ttl);
2884 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
2886 avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
2890 avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
2894 for(i = 0; i < stream->nb_streams; i++) {
2895 avc->streams[i] = &avs[i];
2896 avc->streams[i]->codec = stream->streams[i]->codec;
2898 *pbuffer = av_mallocz(2048);
2901 av_sdp_create(&avc, 1, *pbuffer, 2048);
2904 av_freep(&avc->streams);
2905 av_dict_free(&avc->metadata);
2909 return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
2912 static void rtsp_cmd_options(HTTPContext *c, const char *url)
2914 /* rtsp_reply_header(c, RTSP_STATUS_OK); */
2915 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
2916 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2917 avio_printf(c->pb, "Public: %s\r\n",
2918 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2919 avio_printf(c->pb, "\r\n");
2922 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2924 FFServerStream *stream;
2930 struct sockaddr_in my_addr;
2932 /* find which URL is asked */
2933 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2938 for(stream = config.first_stream; stream; stream = stream->next) {
2939 if (!stream->is_feed &&
2940 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
2941 !strcmp(path, stream->filename)) {
2945 /* no stream found */
2946 rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
2950 /* prepare the media description in SDP format */
2952 /* get the host IP */
2953 len = sizeof(my_addr);
2954 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
2955 content_length = prepare_sdp_description(stream, &content,
2957 if (content_length < 0) {
2958 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2961 rtsp_reply_header(c, RTSP_STATUS_OK);
2962 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
2963 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
2964 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
2965 avio_printf(c->pb, "\r\n");
2966 avio_write(c->pb, content, content_length);
2970 static HTTPContext *find_rtp_session(const char *session_id)
2974 if (session_id[0] == '\0')
2977 for(c = first_http_ctx; c; c = c->next) {
2978 if (!strcmp(c->session_id, session_id))
2984 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
2986 RTSPTransportField *th;
2989 for(i=0;i<h->nb_transports;i++) {
2990 th = &h->transports[i];
2991 if (th->lower_transport == lower_transport)
2997 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
2998 RTSPMessageHeader *h)
3000 FFServerStream *stream;
3001 int stream_index, rtp_port, rtcp_port;
3006 RTSPTransportField *th;
3007 struct sockaddr_in dest_addr;
3008 RTSPActionServerSetup setup;
3010 /* find which URL is asked */
3011 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3016 /* now check each stream */
3017 for(stream = config.first_stream; stream; stream = stream->next) {
3018 if (stream->is_feed || !stream->fmt ||
3019 strcmp(stream->fmt->name, "rtp")) {
3022 /* accept aggregate filenames only if single stream */
3023 if (!strcmp(path, stream->filename)) {
3024 if (stream->nb_streams != 1) {
3025 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3032 for(stream_index = 0; stream_index < stream->nb_streams;
3034 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3035 stream->filename, stream_index);
3036 if (!strcmp(path, buf))
3040 /* no stream found */
3041 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3045 /* generate session id if needed */
3046 if (h->session_id[0] == '\0') {
3047 unsigned random0 = av_lfg_get(&random_state);
3048 unsigned random1 = av_lfg_get(&random_state);
3049 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3053 /* find RTP session, and create it if none found */
3054 rtp_c = find_rtp_session(h->session_id);
3056 /* always prefer UDP */
3057 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3059 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3061 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3066 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3067 th->lower_transport);
3069 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3073 /* open input stream */
3074 if (open_input_stream(rtp_c, "") < 0) {
3075 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3080 /* test if stream is OK (test needed because several SETUP needs
3081 * to be done for a given file) */
3082 if (rtp_c->stream != stream) {
3083 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3087 /* test if stream is already set up */
3088 if (rtp_c->rtp_ctx[stream_index]) {
3089 rtsp_reply_error(c, RTSP_STATUS_STATE);
3093 /* check transport */
3094 th = find_transport(h, rtp_c->rtp_protocol);
3095 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3096 th->client_port_min <= 0)) {
3097 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3101 /* setup default options */
3102 setup.transport_option[0] = '\0';
3103 dest_addr = rtp_c->from_addr;
3104 dest_addr.sin_port = htons(th->client_port_min);
3107 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3108 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3112 /* now everything is OK, so we can send the connection parameters */
3113 rtsp_reply_header(c, RTSP_STATUS_OK);
3115 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3117 switch(rtp_c->rtp_protocol) {
3118 case RTSP_LOWER_TRANSPORT_UDP:
3119 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3120 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3121 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3122 "client_port=%d-%d;server_port=%d-%d",
3123 th->client_port_min, th->client_port_max,
3124 rtp_port, rtcp_port);
3126 case RTSP_LOWER_TRANSPORT_TCP:
3127 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3128 stream_index * 2, stream_index * 2 + 1);
3133 if (setup.transport_option[0] != '\0')
3134 avio_printf(c->pb, ";%s", setup.transport_option);
3135 avio_printf(c->pb, "\r\n");
3138 avio_printf(c->pb, "\r\n");
3143 * find an RTP connection by using the session ID. Check consistency
3146 static HTTPContext *find_rtp_session_with_url(const char *url,
3147 const char *session_id)
3155 rtp_c = find_rtp_session(session_id);
3159 /* find which URL is asked */
3160 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3164 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3165 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3166 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3167 rtp_c->stream->filename, s);
3168 if(!strncmp(path, buf, sizeof(buf)))
3169 /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3170 * if nb_streams>1? */
3174 if (len > 0 && path[len - 1] == '/' &&
3175 !strncmp(path, rtp_c->stream->filename, len - 1))
3180 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3184 rtp_c = find_rtp_session_with_url(url, h->session_id);
3186 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3190 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3191 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3192 rtp_c->state != HTTPSTATE_READY) {
3193 rtsp_reply_error(c, RTSP_STATUS_STATE);
3197 rtp_c->state = HTTPSTATE_SEND_DATA;
3199 /* now everything is OK, so we can send the connection parameters */
3200 rtsp_reply_header(c, RTSP_STATUS_OK);
3202 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3203 avio_printf(c->pb, "\r\n");
3206 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3207 RTSPMessageHeader *h, int pause_only)
3211 rtp_c = find_rtp_session_with_url(url, h->session_id);
3213 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3218 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3219 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3220 rtsp_reply_error(c, RTSP_STATUS_STATE);
3223 rtp_c->state = HTTPSTATE_READY;
3224 rtp_c->first_pts = AV_NOPTS_VALUE;
3227 /* now everything is OK, so we can send the connection parameters */
3228 rtsp_reply_header(c, RTSP_STATUS_OK);
3230 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3231 avio_printf(c->pb, "\r\n");
3234 close_connection(rtp_c);
3237 /********************************************************************/
3240 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3241 FFServerStream *stream,
3242 const char *session_id,
3243 enum RTSPLowerTransport rtp_protocol)
3245 HTTPContext *c = NULL;
3246 const char *proto_str;
3248 /* XXX: should output a warning page when coming
3249 * close to the connection limit */
3250 if (nb_connections >= config.nb_max_connections)
3253 /* add a new connection */
3254 c = av_mallocz(sizeof(HTTPContext));
3259 c->poll_entry = NULL;
3260 c->from_addr = *from_addr;
3261 c->buffer_size = IOBUFFER_INIT_SIZE;
3262 c->buffer = av_malloc(c->buffer_size);
3267 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3268 c->state = HTTPSTATE_READY;
3269 c->is_packetized = 1;
3270 c->rtp_protocol = rtp_protocol;
3272 /* protocol is shown in statistics */
3273 switch(c->rtp_protocol) {
3274 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3275 proto_str = "MCAST";
3277 case RTSP_LOWER_TRANSPORT_UDP:
3280 case RTSP_LOWER_TRANSPORT_TCP:
3287 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3288 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3290 current_bandwidth += stream->bandwidth;
3292 c->next = first_http_ctx;
3298 av_freep(&c->buffer);
3305 * add a new RTP stream in an RTP connection (used in RTSP SETUP
3306 * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3309 static int rtp_new_av_stream(HTTPContext *c,
3310 int stream_index, struct sockaddr_in *dest_addr,
3311 HTTPContext *rtsp_c)
3313 AVFormatContext *ctx;
3316 URLContext *h = NULL;
3318 int max_packet_size;
3320 /* now we can open the relevant output stream */
3321 ctx = avformat_alloc_context();
3324 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3326 st = av_mallocz(sizeof(AVStream));
3329 ctx->nb_streams = 1;
3330 ctx->streams = av_mallocz_array(ctx->nb_streams, sizeof(AVStream *));
3333 ctx->streams[0] = st;
3335 if (!c->stream->feed ||
3336 c->stream->feed == c->stream)
3337 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3340 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3342 st->priv_data = NULL;
3344 /* build destination RTP address */
3345 ipaddr = inet_ntoa(dest_addr->sin_addr);
3347 switch(c->rtp_protocol) {
3348 case RTSP_LOWER_TRANSPORT_UDP:
3349 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3352 /* XXX: also pass as parameter to function ? */
3353 if (c->stream->is_multicast) {
3355 ttl = c->stream->multicast_ttl;
3358 snprintf(ctx->filename, sizeof(ctx->filename),
3359 "rtp://%s:%d?multicast=1&ttl=%d",
3360 ipaddr, ntohs(dest_addr->sin_port), ttl);
3362 snprintf(ctx->filename, sizeof(ctx->filename),
3363 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3366 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3368 c->rtp_handles[stream_index] = h;
3369 max_packet_size = h->max_packet_size;
3371 case RTSP_LOWER_TRANSPORT_TCP:
3374 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3380 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3381 ipaddr, ntohs(dest_addr->sin_port),
3382 c->stream->filename, stream_index, c->protocol);
3384 /* normally, no packets should be output here, but the packet size may
3386 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3387 /* XXX: close stream */
3390 if (avformat_write_header(ctx, NULL) < 0) {
3398 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3401 c->rtp_ctx[stream_index] = ctx;
3405 /********************************************************************/
3406 /* ffserver initialization */
3408 static AVStream *add_av_stream1(FFServerStream *stream,
3409 AVCodecContext *codec, int copy)
3413 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3416 fst = av_mallocz(sizeof(AVStream));
3420 fst->codec = avcodec_alloc_context3(codec->codec);
3425 avcodec_copy_context(fst->codec, codec);
3427 /* live streams must use the actual feed's codec since it may be
3428 * updated later to carry extradata needed by them.
3432 fst->priv_data = av_mallocz(sizeof(FeedData));
3433 fst->index = stream->nb_streams;
3434 avpriv_set_pts_info(fst, 33, 1, 90000);
3435 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3436 stream->streams[stream->nb_streams++] = fst;
3440 /* return the stream number in the feed */
3441 static int add_av_stream(FFServerStream *feed, AVStream *st)
3444 AVCodecContext *av, *av1;
3448 for(i=0;i<feed->nb_streams;i++) {
3449 av1 = feed->streams[i]->codec;
3450 if (av1->codec_id == av->codec_id &&
3451 av1->codec_type == av->codec_type &&
3452 av1->bit_rate == av->bit_rate) {
3454 switch(av->codec_type) {
3455 case AVMEDIA_TYPE_AUDIO:
3456 if (av1->channels == av->channels &&
3457 av1->sample_rate == av->sample_rate)
3460 case AVMEDIA_TYPE_VIDEO:
3461 if (av1->width == av->width &&
3462 av1->height == av->height &&
3463 av1->time_base.den == av->time_base.den &&
3464 av1->time_base.num == av->time_base.num &&
3465 av1->gop_size == av->gop_size)
3474 fst = add_av_stream1(feed, av, 0);
3477 if (av_stream_get_recommended_encoder_configuration(st))
3478 av_stream_set_recommended_encoder_configuration(fst,
3479 av_strdup(av_stream_get_recommended_encoder_configuration(st)));
3480 return feed->nb_streams - 1;
3483 static void remove_stream(FFServerStream *stream)
3485 FFServerStream **ps;
3486 ps = &config.first_stream;
3495 /* specific MPEG4 handling : we extract the raw parameters */
3496 static void extract_mpeg4_header(AVFormatContext *infile)
3498 int mpeg4_count, i, size;
3503 infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
3506 for(i=0;i<infile->nb_streams;i++) {
3507 st = infile->streams[i];
3508 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3509 st->codec->extradata_size == 0) {
3516 printf("MPEG4 without extra data: trying to find header in %s\n",
3518 while (mpeg4_count > 0) {
3519 if (av_read_frame(infile, &pkt) < 0)
3521 st = infile->streams[pkt.stream_index];
3522 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3523 st->codec->extradata_size == 0) {
3524 av_freep(&st->codec->extradata);
3525 /* fill extradata with the header */
3526 /* XXX: we make hard suppositions here ! */
3528 while (p < pkt.data + pkt.size - 4) {
3529 /* stop when vop header is found */
3530 if (p[0] == 0x00 && p[1] == 0x00 &&
3531 p[2] == 0x01 && p[3] == 0xb6) {
3532 size = p - pkt.data;
3533 st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
3534 st->codec->extradata_size = size;
3535 memcpy(st->codec->extradata, pkt.data, size);
3542 av_free_packet(&pkt);
3546 /* compute the needed AVStream for each file */
3547 static void build_file_streams(void)
3549 FFServerStream *stream, *stream_next;
3552 /* gather all streams */
3553 for(stream = config.first_stream; stream; stream = stream_next) {
3554 AVFormatContext *infile = NULL;
3555 stream_next = stream->next;
3556 if (stream->stream_type == STREAM_TYPE_LIVE &&
3558 /* the stream comes from a file */
3559 /* try to open the file */
3561 if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3562 /* specific case : if transport stream output to RTP,
3563 * we use a raw transport stream reader */
3564 av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3567 if (!stream->feed_filename[0]) {
3568 http_log("Unspecified feed file for stream '%s'\n",
3573 http_log("Opening feed file '%s' for stream '%s'\n",
3574 stream->feed_filename, stream->filename);
3575 ret = avformat_open_input(&infile, stream->feed_filename,
3576 stream->ifmt, &stream->in_opts);
3578 http_log("Could not open '%s': %s\n", stream->feed_filename,
3580 /* remove stream (no need to spend more time on it) */
3582 remove_stream(stream);
3584 /* find all the AVStreams inside and reference them in
3586 if (avformat_find_stream_info(infile, NULL) < 0) {
3587 http_log("Could not find codec parameters from '%s'\n",
3588 stream->feed_filename);
3589 avformat_close_input(&infile);
3592 extract_mpeg4_header(infile);
3594 for(i=0;i<infile->nb_streams;i++)
3595 add_av_stream1(stream, infile->streams[i]->codec, 1);
3597 avformat_close_input(&infile);
3603 /* compute the needed AVStream for each feed */
3604 static void build_feed_streams(void)
3606 FFServerStream *stream, *feed;
3609 /* gather all streams */
3610 for(stream = config.first_stream; stream; stream = stream->next) {
3611 feed = stream->feed;
3615 if (stream->is_feed) {
3616 for(i=0;i<stream->nb_streams;i++)
3617 stream->feed_streams[i] = i;
3619 /* we handle a stream coming from a feed */
3620 for(i=0;i<stream->nb_streams;i++)
3621 stream->feed_streams[i] = add_av_stream(feed,
3622 stream->streams[i]);
3626 /* create feed files if needed */
3627 for(feed = config.first_feed; feed; feed = feed->next_feed) {
3630 if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
3631 /* See if it matches */
3632 AVFormatContext *s = NULL;
3635 if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) >= 0) {
3636 /* set buffer size */
3637 int ret = ffio_set_buf_size(s->pb, FFM_PACKET_SIZE);
3639 http_log("Failed to set buffer size\n");
3643 /* Now see if it matches */
3644 if (s->nb_streams == feed->nb_streams) {
3646 for(i=0;i<s->nb_streams;i++) {
3648 sf = feed->streams[i];
3651 if (sf->index != ss->index ||
3653 http_log("Index & Id do not match for stream %d (%s)\n",
3654 i, feed->feed_filename);
3657 AVCodecContext *ccf, *ccs;
3661 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3663 if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
3664 http_log("Codecs do not match for stream %d\n", i);
3666 } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
3667 http_log("Codec bitrates do not match for stream %d\n", i);
3669 } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
3670 if (CHECK_CODEC(time_base.den) ||
3671 CHECK_CODEC(time_base.num) ||
3672 CHECK_CODEC(width) ||
3673 CHECK_CODEC(height)) {
3674 http_log("Codec width, height and framerate do not match for stream %d\n", i);
3677 } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
3678 if (CHECK_CODEC(sample_rate) ||
3679 CHECK_CODEC(channels) ||
3680 CHECK_CODEC(frame_size)) {
3681 http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);
3685 http_log("Unknown codec type\n");
3693 http_log("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3694 feed->feed_filename, s->nb_streams, feed->nb_streams);
3696 avformat_close_input(&s);
3698 http_log("Deleting feed file '%s' as it appears to be corrupt\n",
3699 feed->feed_filename);
3702 if (feed->readonly) {
3703 http_log("Unable to delete feed file '%s' as it is marked readonly\n",
3704 feed->feed_filename);
3707 unlink(feed->feed_filename);
3710 if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
3711 AVFormatContext *s = avformat_alloc_context();
3714 http_log("Failed to allocate context\n");
3718 if (feed->readonly) {
3719 http_log("Unable to create feed file '%s' as it is marked readonly\n",
3720 feed->feed_filename);
3724 /* only write the header of the ffm file */
3725 if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
3726 http_log("Could not open output feed file '%s'\n",
3727 feed->feed_filename);
3730 s->oformat = feed->fmt;
3731 s->nb_streams = feed->nb_streams;
3732 s->streams = feed->streams;
3733 if (avformat_write_header(s, NULL) < 0) {
3734 http_log("Container doesn't support the required parameters\n");
3737 /* XXX: need better API */
3738 av_freep(&s->priv_data);
3739 avio_closep(&s->pb);
3742 avformat_free_context(s);
3744 /* get feed size and write index */
3745 fd = open(feed->feed_filename, O_RDONLY);
3747 http_log("Could not open output feed file '%s'\n",
3748 feed->feed_filename);
3752 feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
3753 feed->feed_size = lseek(fd, 0, SEEK_END);
3754 /* ensure that we do not wrap before the end of file */
3755 if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
3756 feed->feed_max_size = feed->feed_size;
3762 /* compute the bandwidth used by each stream */
3763 static void compute_bandwidth(void)
3767 FFServerStream *stream;
3769 for(stream = config.first_stream; stream; stream = stream->next) {
3771 for(i=0;i<stream->nb_streams;i++) {
3772 AVStream *st = stream->streams[i];
3773 switch(st->codec->codec_type) {
3774 case AVMEDIA_TYPE_AUDIO:
3775 case AVMEDIA_TYPE_VIDEO:
3776 bandwidth += st->codec->bit_rate;
3782 stream->bandwidth = (bandwidth + 999) / 1000;
3786 static void handle_child_exit(int sig)
3791 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
3792 FFServerStream *feed;
3794 for (feed = config.first_feed; feed; feed = feed->next) {
3795 if (feed->pid != pid)
3798 uptime = time(0) - feed->pid_start;
3801 "%s: Pid %"PRId64" exited with status %d after %d seconds\n",
3802 feed->filename, (int64_t) pid, status, uptime);
3805 /* Turn off any more restarts */
3806 ffserver_free_child_args(&feed->child_argv);
3810 need_to_start_children = 1;
3813 static void opt_debug(void)
3816 snprintf(config.logfilename, sizeof(config.logfilename), "-");
3819 void show_help_default(const char *opt, const char *arg)
3821 printf("usage: ffserver [options]\n"
3822 "Hyper fast multi format Audio/Video streaming server\n");
3824 show_help_options(options, "Main options:", 0, 0, 0);
3827 static const OptionDef options[] = {
3828 #include "cmdutils_common_opts.h"
3829 { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
3830 { "d", 0, {(void*)opt_debug}, "enable debug mode" },
3831 { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
3835 int main(int argc, char **argv)
3837 struct sigaction sigact = { { 0 } };
3840 config.filename = av_strdup("/etc/ffserver.conf");
3842 parse_loglevel(argc, argv, options);
3844 avformat_network_init();
3846 show_banner(argc, argv, options);
3848 my_program_name = argv[0];
3850 parse_options(NULL, argc, argv, options, NULL);
3852 unsetenv("http_proxy"); /* Kill the http_proxy */
3854 av_lfg_init(&random_state, av_get_random_seed());
3856 sigact.sa_handler = handle_child_exit;
3857 sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
3858 sigaction(SIGCHLD, &sigact, 0);
3860 if ((ret = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
3861 fprintf(stderr, "Error reading configuration file '%s': %s\n",
3862 config.filename, av_err2str(ret));
3863 av_freep(&config.filename);
3866 av_freep(&config.filename);
3868 /* open log file if needed */
3869 if (config.logfilename[0] != '\0') {
3870 if (!strcmp(config.logfilename, "-"))
3873 logfile = fopen(config.logfilename, "a");
3874 av_log_set_callback(http_av_log);
3877 build_file_streams();
3879 build_feed_streams();
3881 compute_bandwidth();
3884 signal(SIGPIPE, SIG_IGN);
3886 if (http_server() < 0) {
3887 http_log("Could not start server\n");