2 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * multiple format streaming server based on the FFmpeg libraries
28 #define closesocket close
33 #include "libavformat/avformat.h"
34 /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
35 #include "libavformat/rtpproto.h"
36 #include "libavformat/rtsp.h"
37 #include "libavformat/avio_internal.h"
38 #include "libavformat/internal.h"
40 #include "libavutil/avassert.h"
41 #include "libavutil/avstring.h"
42 #include "libavutil/lfg.h"
43 #include "libavutil/dict.h"
44 #include "libavutil/intreadwrite.h"
45 #include "libavutil/mathematics.h"
46 #include "libavutil/random_seed.h"
47 #include "libavutil/parseutils.h"
48 #include "libavutil/opt.h"
49 #include "libavutil/time.h"
56 #include <sys/ioctl.h>
66 #include "ffserver_config.h"
68 #define PATH_LENGTH 1024
70 const char program_name[] = "ffserver";
71 const int program_birth_year = 2000;
73 static const OptionDef options[];
76 HTTPSTATE_WAIT_REQUEST,
77 HTTPSTATE_SEND_HEADER,
78 HTTPSTATE_SEND_DATA_HEADER,
79 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
80 HTTPSTATE_SEND_DATA_TRAILER,
81 HTTPSTATE_RECEIVE_DATA,
82 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
85 RTSPSTATE_WAIT_REQUEST,
87 RTSPSTATE_SEND_PACKET,
90 static const char * const http_state[] = {
106 #define IOBUFFER_INIT_SIZE 8192
108 /* timeouts are in ms */
109 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
110 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
112 #define SYNC_TIMEOUT (10 * 1000)
114 typedef struct RTSPActionServerSetup {
116 char transport_option[512];
117 } RTSPActionServerSetup;
120 int64_t count1, count2;
121 int64_t time1, time2;
124 /* context associated with one connection */
125 typedef struct HTTPContext {
126 enum HTTPState state;
127 int fd; /* socket file descriptor */
128 struct sockaddr_in from_addr; /* origin */
129 struct pollfd *poll_entry; /* used when polling */
131 uint8_t *buffer_ptr, *buffer_end;
134 int chunked_encoding;
135 int chunk_size; /* 0 if it needs to be read */
136 struct HTTPContext *next;
137 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
141 /* input format handling */
142 AVFormatContext *fmt_in;
143 int64_t start_time; /* In milliseconds - this wraps fairly often */
144 int64_t first_pts; /* initial pts value */
145 int64_t cur_pts; /* current pts value from the stream in us */
146 int64_t cur_frame_duration; /* duration of the current frame in us */
147 int cur_frame_bytes; /* output frame size, needed to compute
148 the time at which we send each
150 int pts_stream_index; /* stream we choose as clock reference */
151 int64_t cur_clock; /* current clock reference value in us */
152 /* output format handling */
153 struct FFServerStream *stream;
154 /* -1 is invalid stream */
155 int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
156 int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
158 AVFormatContext fmt_ctx; /* instance of FFServerStream for one user */
159 int last_packet_sent; /* true if last data packet was sent */
161 DataRateData datarate;
168 int is_packetized; /* if true, the stream is packetized */
169 int packet_stream_index; /* current stream for output in state machine */
171 /* RTSP state specific */
172 uint8_t *pb_buffer; /* XXX: use that in all the code */
174 int seq; /* RTSP sequence number */
176 /* RTP state specific */
177 enum RTSPLowerTransport rtp_protocol;
178 char session_id[32]; /* session id */
179 AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
181 /* RTP/UDP specific */
182 URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
184 /* RTP/TCP specific */
185 struct HTTPContext *rtsp_c;
186 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
189 typedef struct FeedData {
190 long long data_count;
191 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
194 static HTTPContext *first_http_ctx;
196 static FFServerConfig config = {
197 .nb_max_http_connections = 2000,
198 .nb_max_connections = 5,
199 .max_bandwidth = 1000,
203 static void new_connection(int server_fd, int is_rtsp);
204 static void close_connection(HTTPContext *c);
207 static int handle_connection(HTTPContext *c);
208 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
209 static void compute_status(HTTPContext *c);
210 static int open_input_stream(HTTPContext *c, const char *info);
211 static int http_parse_request(HTTPContext *c);
212 static int http_send_data(HTTPContext *c);
213 static int http_start_receive_data(HTTPContext *c);
214 static int http_receive_data(HTTPContext *c);
217 static int rtsp_parse_request(HTTPContext *c);
218 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
219 static void rtsp_cmd_options(HTTPContext *c, const char *url);
220 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
221 RTSPMessageHeader *h);
222 static void rtsp_cmd_play(HTTPContext *c, const char *url,
223 RTSPMessageHeader *h);
224 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
225 RTSPMessageHeader *h, int pause_only);
228 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
229 struct in_addr my_ip);
232 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
233 FFServerStream *stream,
234 const char *session_id,
235 enum RTSPLowerTransport rtp_protocol);
236 static int rtp_new_av_stream(HTTPContext *c,
237 int stream_index, struct sockaddr_in *dest_addr,
238 HTTPContext *rtsp_c);
240 static size_t htmlencode (const char *src, char **dest);
241 static inline void cp_html_entity (char *buffer, const char *entity);
242 static inline int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs,
245 static const char *my_program_name;
247 static int no_launch;
248 static int need_to_start_children;
250 /* maximum number of simultaneous HTTP connections */
251 static unsigned int nb_connections;
253 static uint64_t current_bandwidth;
255 /* Making this global saves on passing it around everywhere */
256 static int64_t cur_time;
258 static AVLFG random_state;
260 static FILE *logfile = NULL;
262 static inline void cp_html_entity (char *buffer, const char *entity) {
263 if (!buffer || !entity)
266 *buffer++ = *entity++;
270 * Substitutes known conflicting chars on a text string with
271 * their corresponding HTML entities.
273 * Returns the number of bytes in the 'encoded' representation
274 * not including the terminating NUL.
276 static size_t htmlencode (const char *src, char **dest) {
277 const char *amp = "&";
278 const char *lt = "<";
279 const char *gt = ">";
282 size_t final_size = 0;
289 /* Compute needed dest size */
290 while (*src != '\0') {
306 *dest = av_mallocz(final_size + 1);
312 while (*src != '\0') {
315 cp_html_entity (tmp, amp);
319 cp_html_entity (tmp, lt);
323 cp_html_entity (tmp, gt);
337 static int64_t ffm_read_write_index(int fd)
341 if (lseek(fd, 8, SEEK_SET) < 0)
343 if (read(fd, buf, 8) != 8)
348 static int ffm_write_write_index(int fd, int64_t pos)
354 buf[i] = (pos >> (56 - i * 8)) & 0xff;
355 if (lseek(fd, 8, SEEK_SET) < 0)
357 if (write(fd, buf, 8) != 8)
366 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
369 av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
370 av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
371 av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
374 static char *ctime1(char *buf2, size_t buf_size)
385 av_strlcpy(buf2, p, buf_size);
386 p = buf2 + strlen(buf2) - 1;
392 static void http_vlog(const char *fmt, va_list vargs)
394 static int print_prefix = 1;
401 ctime1(buf, sizeof(buf));
402 fprintf(logfile, "%s ", buf);
404 print_prefix = strstr(fmt, "\n") != NULL;
405 vfprintf(logfile, fmt, vargs);
410 __attribute__ ((format (printf, 1, 2)))
412 static void http_log(const char *fmt, ...)
415 va_start(vargs, fmt);
416 http_vlog(fmt, vargs);
420 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
422 static int print_prefix = 1;
423 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
424 if (level > av_log_get_level())
426 if (print_prefix && avc)
427 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
428 print_prefix = strstr(fmt, "\n") != NULL;
429 http_vlog(fmt, vargs);
432 static void log_connection(HTTPContext *c)
437 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
438 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
439 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
442 static void update_datarate(DataRateData *drd, int64_t count)
444 if (!drd->time1 && !drd->count1) {
445 drd->time1 = drd->time2 = cur_time;
446 drd->count1 = drd->count2 = count;
447 } else if (cur_time - drd->time2 > 5000) {
448 drd->time1 = drd->time2;
449 drd->count1 = drd->count2;
450 drd->time2 = cur_time;
455 /* In bytes per second */
456 static int compute_datarate(DataRateData *drd, int64_t count)
458 if (cur_time == drd->time1)
461 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
465 static void start_children(FFServerStream *feed)
475 cmd_length = strlen(my_program_name);
478 * FIXME: WIP Safeguard. Remove after clearing all harcoded
479 * '1024' path lengths
481 if (cmd_length > PATH_LENGTH - 1) {
482 http_log("Could not start children. Command line: '%s' exceeds "
483 "path length limit (%d)\n", my_program_name, PATH_LENGTH);
487 pathname = av_strdup (my_program_name);
489 http_log("Could not allocate memory for children cmd line\n");
492 /* replace "ffserver" with "ffmpeg" in the path of current
493 * program. Ignore user provided path */
495 slash = strrchr(pathname, '/');
500 strcpy(slash, "ffmpeg");
502 for (; feed; feed = feed->next) {
504 if (!feed->child_argv || feed->pid)
507 feed->pid_start = time(0);
511 http_log("Unable to create children: %s\n", strerror(errno));
521 http_log("Launch command line: ");
522 http_log("%s ", pathname);
524 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
525 http_log("%s ", feed->child_argv[i]);
528 for (i = 3; i < 256; i++)
532 if (!freopen("/dev/null", "r", stdin))
533 http_log("failed to redirect STDIN to /dev/null\n;");
534 if (!freopen("/dev/null", "w", stdout))
535 http_log("failed to redirect STDOUT to /dev/null\n;");
536 if (!freopen("/dev/null", "w", stderr))
537 http_log("failed to redirect STDERR to /dev/null\n;");
540 signal(SIGPIPE, SIG_DFL);
541 execvp(pathname, feed->child_argv);
548 /* open a listening socket */
549 static int socket_open_listen(struct sockaddr_in *my_addr)
553 server_fd = socket(AF_INET,SOCK_STREAM,0);
560 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
561 av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
563 my_addr->sin_family = AF_INET;
564 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
566 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
567 ntohs(my_addr->sin_port));
572 if (listen (server_fd, 5) < 0) {
577 if (ff_socket_nonblock(server_fd, 1) < 0)
578 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
583 closesocket(server_fd);
587 /* start all multicast streams */
588 static void start_multicast(void)
590 FFServerStream *stream;
593 struct sockaddr_in dest_addr = {0};
594 int default_port, stream_index;
595 unsigned int random0, random1;
598 for(stream = config.first_stream; stream; stream = stream->next) {
600 if (!stream->is_multicast)
603 random0 = av_lfg_get(&random_state);
604 random1 = av_lfg_get(&random_state);
606 /* open the RTP connection */
607 snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
609 /* choose a port if none given */
610 if (stream->multicast_port == 0) {
611 stream->multicast_port = default_port;
615 dest_addr.sin_family = AF_INET;
616 dest_addr.sin_addr = stream->multicast_ip;
617 dest_addr.sin_port = htons(stream->multicast_port);
619 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
620 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
624 if (open_input_stream(rtp_c, "") < 0) {
625 http_log("Could not open input stream for stream '%s'\n",
630 /* open each RTP stream */
631 for(stream_index = 0; stream_index < stream->nb_streams;
633 dest_addr.sin_port = htons(stream->multicast_port +
635 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
638 http_log("Could not open output stream '%s/streamid=%d'\n",
639 stream->filename, stream_index);
643 rtp_c->state = HTTPSTATE_SEND_DATA;
647 /* main loop of the HTTP server */
648 static int http_server(void)
650 int server_fd = 0, rtsp_server_fd = 0;
652 struct pollfd *poll_table, *poll_entry;
653 HTTPContext *c, *c_next;
655 poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
656 sizeof(*poll_table));
658 http_log("Impossible to allocate a poll table handling %d "
659 "connections.\n", config.nb_max_http_connections);
663 if (config.http_addr.sin_port) {
664 server_fd = socket_open_listen(&config.http_addr);
669 if (config.rtsp_addr.sin_port) {
670 rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
671 if (rtsp_server_fd < 0) {
672 closesocket(server_fd);
677 if (!rtsp_server_fd && !server_fd) {
678 http_log("HTTP and RTSP disabled.\n");
682 http_log("FFserver started.\n");
684 start_children(config.first_feed);
689 poll_entry = poll_table;
691 poll_entry->fd = server_fd;
692 poll_entry->events = POLLIN;
695 if (rtsp_server_fd) {
696 poll_entry->fd = rtsp_server_fd;
697 poll_entry->events = POLLIN;
701 /* wait for events on each HTTP handle */
708 case HTTPSTATE_SEND_HEADER:
709 case RTSPSTATE_SEND_REPLY:
710 case RTSPSTATE_SEND_PACKET:
711 c->poll_entry = poll_entry;
713 poll_entry->events = POLLOUT;
716 case HTTPSTATE_SEND_DATA_HEADER:
717 case HTTPSTATE_SEND_DATA:
718 case HTTPSTATE_SEND_DATA_TRAILER:
719 if (!c->is_packetized) {
720 /* for TCP, we output as much as we can
721 * (may need to put a limit) */
722 c->poll_entry = poll_entry;
724 poll_entry->events = POLLOUT;
727 /* when ffserver is doing the timing, we work by
728 * looking at which packet needs to be sent every
729 * 10 ms (one tick wait XXX: 10 ms assumed) */
734 case HTTPSTATE_WAIT_REQUEST:
735 case HTTPSTATE_RECEIVE_DATA:
736 case HTTPSTATE_WAIT_FEED:
737 case RTSPSTATE_WAIT_REQUEST:
738 /* need to catch errors */
739 c->poll_entry = poll_entry;
741 poll_entry->events = POLLIN;/* Maybe this will work */
745 c->poll_entry = NULL;
751 /* wait for an event on one connection. We poll at least every
752 * second to handle timeouts */
754 ret = poll(poll_table, poll_entry - poll_table, delay);
755 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
756 ff_neterrno() != AVERROR(EINTR)) {
761 cur_time = av_gettime() / 1000;
763 if (need_to_start_children) {
764 need_to_start_children = 0;
765 start_children(config.first_feed);
768 /* now handle the events */
769 for(c = first_http_ctx; c; c = c_next) {
771 if (handle_connection(c) < 0) {
773 /* close and free the connection */
778 poll_entry = poll_table;
780 /* new HTTP connection request ? */
781 if (poll_entry->revents & POLLIN)
782 new_connection(server_fd, 0);
785 if (rtsp_server_fd) {
786 /* new RTSP connection request ? */
787 if (poll_entry->revents & POLLIN)
788 new_connection(rtsp_server_fd, 1);
797 /* start waiting for a new HTTP/RTSP request */
798 static void start_wait_request(HTTPContext *c, int is_rtsp)
800 c->buffer_ptr = c->buffer;
801 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
803 c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
804 c->timeout = cur_time +
805 (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
808 static void http_send_too_busy_reply(int fd)
811 int len = snprintf(buffer, sizeof(buffer),
812 "HTTP/1.0 503 Server too busy\r\n"
813 "Content-type: text/html\r\n"
816 "<html><head><title>Too busy</title></head><body>\r\n"
817 "<p>The server is too busy to serve your request at "
819 "<p>The number of current connections is %u, and this "
820 "exceeds the limit of %u.</p>\r\n"
821 "</body></html>\r\n",
822 nb_connections, config.nb_max_connections);
823 av_assert0(len < sizeof(buffer));
824 if (send(fd, buffer, len, 0) < len)
825 av_log(NULL, AV_LOG_WARNING,
826 "Could not send too-busy reply, send() failed\n");
830 static void new_connection(int server_fd, int is_rtsp)
832 struct sockaddr_in from_addr;
835 HTTPContext *c = NULL;
837 len = sizeof(from_addr);
838 fd = accept(server_fd, (struct sockaddr *)&from_addr,
841 http_log("error during accept %s\n", strerror(errno));
844 if (ff_socket_nonblock(fd, 1) < 0)
845 av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
847 if (nb_connections >= config.nb_max_connections) {
848 http_send_too_busy_reply(fd);
852 /* add a new connection */
853 c = av_mallocz(sizeof(HTTPContext));
858 c->poll_entry = NULL;
859 c->from_addr = from_addr;
860 c->buffer_size = IOBUFFER_INIT_SIZE;
861 c->buffer = av_malloc(c->buffer_size);
865 c->next = first_http_ctx;
869 start_wait_request(c, is_rtsp);
875 av_freep(&c->buffer);
881 static void close_connection(HTTPContext *c)
883 HTTPContext **cp, *c1;
885 AVFormatContext *ctx;
888 /* remove connection from list */
889 cp = &first_http_ctx;
898 /* remove references, if any (XXX: do it faster) */
899 for(c1 = first_http_ctx; c1; c1 = c1->next) {
904 /* remove connection associated resources */
908 /* close each frame parser */
909 for(i=0;i<c->fmt_in->nb_streams;i++) {
910 st = c->fmt_in->streams[i];
911 if (st->codec->codec)
912 avcodec_close(st->codec);
914 avformat_close_input(&c->fmt_in);
917 /* free RTP output streams if any */
920 nb_streams = c->stream->nb_streams;
922 for(i=0;i<nb_streams;i++) {
925 av_write_trailer(ctx);
926 av_dict_free(&ctx->metadata);
927 av_freep(&ctx->streams[0]);
930 ffurl_close(c->rtp_handles[i]);
935 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
937 if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
938 av_write_trailer(ctx);
939 av_freep(&c->pb_buffer);
940 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
944 for(i=0; i<ctx->nb_streams; i++)
945 av_freep(&ctx->streams[i]);
946 av_freep(&ctx->streams);
947 av_freep(&ctx->priv_data);
949 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
950 current_bandwidth -= c->stream->bandwidth;
952 /* signal that there is no feed if we are the feeder socket */
953 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
954 c->stream->feed_opened = 0;
958 av_freep(&c->pb_buffer);
959 av_freep(&c->packet_buffer);
960 av_freep(&c->buffer);
965 static int handle_connection(HTTPContext *c)
971 case HTTPSTATE_WAIT_REQUEST:
972 case RTSPSTATE_WAIT_REQUEST:
974 if ((c->timeout - cur_time) < 0)
976 if (c->poll_entry->revents & (POLLERR | POLLHUP))
979 /* no need to read if no events */
980 if (!(c->poll_entry->revents & POLLIN))
984 if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
988 if (ff_neterrno() != AVERROR(EAGAIN) &&
989 ff_neterrno() != AVERROR(EINTR))
993 /* search for end of request. */
994 c->buffer_ptr += len;
996 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
997 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
998 /* request found : parse it and reply */
999 if (c->state == HTTPSTATE_WAIT_REQUEST)
1000 ret = http_parse_request(c);
1002 ret = rtsp_parse_request(c);
1006 } else if (ptr >= c->buffer_end) {
1007 /* request too long: cannot do anything */
1009 } else goto read_loop;
1013 case HTTPSTATE_SEND_HEADER:
1014 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1017 /* no need to write if no events */
1018 if (!(c->poll_entry->revents & POLLOUT))
1020 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1022 if (ff_neterrno() != AVERROR(EAGAIN) &&
1023 ff_neterrno() != AVERROR(EINTR)) {
1024 goto close_connection;
1028 c->buffer_ptr += len;
1030 c->stream->bytes_served += len;
1031 c->data_count += len;
1032 if (c->buffer_ptr >= c->buffer_end) {
1033 av_freep(&c->pb_buffer);
1034 /* if error, exit */
1037 /* all the buffer was sent : synchronize to the incoming
1039 c->state = HTTPSTATE_SEND_DATA_HEADER;
1040 c->buffer_ptr = c->buffer_end = c->buffer;
1044 case HTTPSTATE_SEND_DATA:
1045 case HTTPSTATE_SEND_DATA_HEADER:
1046 case HTTPSTATE_SEND_DATA_TRAILER:
1047 /* for packetized output, we consider we can always write (the
1048 * input streams set the speed). It may be better to verify
1049 * that we do not rely too much on the kernel queues */
1050 if (!c->is_packetized) {
1051 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1054 /* no need to read if no events */
1055 if (!(c->poll_entry->revents & POLLOUT))
1058 if (http_send_data(c) < 0)
1060 /* close connection if trailer sent */
1061 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
1063 /* Check if it is a single jpeg frame 123 */
1064 if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
1065 close_connection(c);
1068 case HTTPSTATE_RECEIVE_DATA:
1069 /* no need to read if no events */
1070 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1072 if (!(c->poll_entry->revents & POLLIN))
1074 if (http_receive_data(c) < 0)
1077 case HTTPSTATE_WAIT_FEED:
1078 /* no need to read if no events */
1079 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1082 /* nothing to do, we'll be waken up by incoming feed packets */
1085 case RTSPSTATE_SEND_REPLY:
1086 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1087 goto close_connection;
1088 /* no need to write if no events */
1089 if (!(c->poll_entry->revents & POLLOUT))
1091 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1093 if (ff_neterrno() != AVERROR(EAGAIN) &&
1094 ff_neterrno() != AVERROR(EINTR)) {
1095 goto close_connection;
1099 c->buffer_ptr += len;
1100 c->data_count += len;
1101 if (c->buffer_ptr >= c->buffer_end) {
1102 /* all the buffer was sent : wait for a new request */
1103 av_freep(&c->pb_buffer);
1104 start_wait_request(c, 1);
1107 case RTSPSTATE_SEND_PACKET:
1108 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1109 av_freep(&c->packet_buffer);
1112 /* no need to write if no events */
1113 if (!(c->poll_entry->revents & POLLOUT))
1115 len = send(c->fd, c->packet_buffer_ptr,
1116 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1118 if (ff_neterrno() != AVERROR(EAGAIN) &&
1119 ff_neterrno() != AVERROR(EINTR)) {
1120 /* error : close connection */
1121 av_freep(&c->packet_buffer);
1126 c->packet_buffer_ptr += len;
1127 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1128 /* all the buffer was sent : wait for a new request */
1129 av_freep(&c->packet_buffer);
1130 c->state = RTSPSTATE_WAIT_REQUEST;
1133 case HTTPSTATE_READY:
1142 av_freep(&c->pb_buffer);
1146 static int extract_rates(char *rates, int ratelen, const char *request)
1150 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1151 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1152 const char *q = p + 7;
1154 while (*q && *q != '\n' && av_isspace(*q))
1157 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1163 memset(rates, 0xff, ratelen);
1166 while (*q && *q != '\n' && *q != ':')
1169 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1173 if (stream_no < ratelen && stream_no >= 0)
1174 rates[stream_no] = rate_no;
1176 while (*q && *q != '\n' && !av_isspace(*q))
1183 p = strchr(p, '\n');
1193 static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec,
1197 int best_bitrate = 100000000;
1200 for (i = 0; i < feed->nb_streams; i++) {
1201 AVCodecContext *feed_codec = feed->streams[i]->codec;
1203 if (feed_codec->codec_id != codec->codec_id ||
1204 feed_codec->sample_rate != codec->sample_rate ||
1205 feed_codec->width != codec->width ||
1206 feed_codec->height != codec->height)
1209 /* Potential stream */
1211 /* We want the fastest stream less than bit_rate, or the slowest
1212 * faster than bit_rate
1215 if (feed_codec->bit_rate <= bit_rate) {
1216 if (best_bitrate > bit_rate ||
1217 feed_codec->bit_rate > best_bitrate) {
1218 best_bitrate = feed_codec->bit_rate;
1223 if (feed_codec->bit_rate < best_bitrate) {
1224 best_bitrate = feed_codec->bit_rate;
1231 static int modify_current_stream(HTTPContext *c, char *rates)
1234 FFServerStream *req = c->stream;
1235 int action_required = 0;
1237 /* Not much we can do for a feed */
1241 for (i = 0; i < req->nb_streams; i++) {
1242 AVCodecContext *codec = req->streams[i]->codec;
1246 c->switch_feed_streams[i] = req->feed_streams[i];
1249 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1252 /* Wants off or slow */
1253 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1255 /* This doesn't work well when it turns off the only stream! */
1256 c->switch_feed_streams[i] = -2;
1257 c->feed_streams[i] = -2;
1262 if (c->switch_feed_streams[i] >= 0 &&
1263 c->switch_feed_streams[i] != c->feed_streams[i]) {
1264 action_required = 1;
1268 return action_required;
1271 static void get_word(char *buf, int buf_size, const char **pp)
1277 p += strspn(p, SPACE_CHARS);
1279 while (!av_isspace(*p) && *p != '\0') {
1280 if ((q - buf) < buf_size - 1)
1289 static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
1295 FFServerIPAddressACL *acl = NULL;
1299 f = fopen(stream->dynamic_acl, "r");
1301 perror(stream->dynamic_acl);
1305 acl = av_mallocz(sizeof(FFServerIPAddressACL));
1312 while (fgets(line, sizeof(line), f)) {
1315 while (av_isspace(*p))
1317 if (*p == '\0' || *p == '#')
1319 ffserver_get_arg(cmd, sizeof(cmd), &p);
1321 if (!av_strcasecmp(cmd, "ACL"))
1322 ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
1330 static void free_acl_list(FFServerIPAddressACL *in_acl)
1332 FFServerIPAddressACL *pacl, *pacl2;
1342 static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
1344 enum FFServerIPAddressAction last_action = IP_DENY;
1345 FFServerIPAddressACL *acl;
1346 struct in_addr *src = &c->from_addr.sin_addr;
1347 unsigned long src_addr = src->s_addr;
1349 for (acl = in_acl; acl; acl = acl->next) {
1350 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1351 return (acl->action == IP_ALLOW) ? 1 : 0;
1352 last_action = acl->action;
1355 /* Nothing matched, so return not the last action */
1356 return (last_action == IP_DENY) ? 1 : 0;
1359 static int validate_acl(FFServerStream *stream, HTTPContext *c)
1362 FFServerIPAddressACL *acl;
1364 /* if stream->acl is null validate_acl_list will return 1 */
1365 ret = validate_acl_list(stream->acl, c);
1367 if (stream->dynamic_acl[0]) {
1368 acl = parse_dynamic_acl(stream, c);
1369 ret = validate_acl_list(acl, c);
1377 * compute the real filename of a file by matching it without its
1378 * extensions to all the stream's filenames
1380 static void compute_real_filename(char *filename, int max_size)
1385 FFServerStream *stream;
1387 av_strlcpy(file1, filename, sizeof(file1));
1388 p = strrchr(file1, '.');
1391 for(stream = config.first_stream; stream; stream = stream->next) {
1392 av_strlcpy(file2, stream->filename, sizeof(file2));
1393 p = strrchr(file2, '.');
1396 if (!strcmp(file1, file2)) {
1397 av_strlcpy(filename, stream->filename, max_size);
1412 /* parse HTTP request and prepare header */
1413 static int http_parse_request(HTTPContext *c)
1417 enum RedirType redir_type;
1419 char info[1024], filename[1024];
1423 char *encoded_msg = NULL;
1424 const char *mime_type;
1425 FFServerStream *stream;
1428 const char *useragent = 0;
1431 get_word(cmd, sizeof(cmd), &p);
1432 av_strlcpy(c->method, cmd, sizeof(c->method));
1434 if (!strcmp(cmd, "GET"))
1436 else if (!strcmp(cmd, "POST"))
1441 get_word(url, sizeof(url), &p);
1442 av_strlcpy(c->url, url, sizeof(c->url));
1444 get_word(protocol, sizeof(protocol), (const char **)&p);
1445 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1448 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1451 http_log("%s - - New connection: %s %s\n",
1452 inet_ntoa(c->from_addr.sin_addr), cmd, url);
1454 /* find the filename and the optional info string in the request */
1455 p1 = strchr(url, '?');
1457 av_strlcpy(info, p1, sizeof(info));
1462 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1464 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1465 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1467 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1471 p = strchr(p, '\n');
1478 redir_type = REDIR_NONE;
1479 if (av_match_ext(filename, "asx")) {
1480 redir_type = REDIR_ASX;
1481 filename[strlen(filename)-1] = 'f';
1482 } else if (av_match_ext(filename, "asf") &&
1483 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
1484 /* if this isn't WMP or lookalike, return the redirector file */
1485 redir_type = REDIR_ASF;
1486 } else if (av_match_ext(filename, "rpm,ram")) {
1487 redir_type = REDIR_RAM;
1488 strcpy(filename + strlen(filename)-2, "m");
1489 } else if (av_match_ext(filename, "rtsp")) {
1490 redir_type = REDIR_RTSP;
1491 compute_real_filename(filename, sizeof(filename) - 1);
1492 } else if (av_match_ext(filename, "sdp")) {
1493 redir_type = REDIR_SDP;
1494 compute_real_filename(filename, sizeof(filename) - 1);
1497 /* "redirect" request to index.html */
1498 if (!strlen(filename))
1499 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1501 stream = config.first_stream;
1503 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1505 stream = stream->next;
1508 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1509 http_log("File '%s' not found\n", url);
1514 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1515 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1517 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1518 c->http_error = 301;
1520 snprintf(q, c->buffer_size,
1521 "HTTP/1.0 301 Moved\r\n"
1523 "Content-type: text/html\r\n"
1526 "<html><head><title>Moved</title></head><body>\r\n"
1527 "You should be <a href=\"%s\">redirected</a>.\r\n"
1528 "</body></html>\r\n",
1529 stream->feed_filename, stream->feed_filename);
1531 /* prepare output buffer */
1532 c->buffer_ptr = c->buffer;
1534 c->state = HTTPSTATE_SEND_HEADER;
1538 /* If this is WMP, get the rate information */
1539 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1540 if (modify_current_stream(c, ratebuf)) {
1541 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1542 if (c->switch_feed_streams[i] >= 0)
1543 c->switch_feed_streams[i] = -1;
1548 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1549 current_bandwidth += stream->bandwidth;
1551 /* If already streaming this feed, do not let another feeder start */
1552 if (stream->feed_opened) {
1553 snprintf(msg, sizeof(msg), "This feed is already being received.");
1554 http_log("Feed '%s' already being received\n", stream->feed_filename);
1558 if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
1559 c->http_error = 503;
1561 snprintf(q, c->buffer_size,
1562 "HTTP/1.0 503 Server too busy\r\n"
1563 "Content-type: text/html\r\n"
1566 "<html><head><title>Too busy</title></head><body>\r\n"
1567 "<p>The server is too busy to serve your request at "
1568 "this time.</p>\r\n"
1569 "<p>The bandwidth being served (including your stream) "
1570 "is %"PRIu64"kbit/s, and this exceeds the limit of "
1571 "%"PRIu64"kbit/s.</p>\r\n"
1572 "</body></html>\r\n",
1573 current_bandwidth, config.max_bandwidth);
1575 /* prepare output buffer */
1576 c->buffer_ptr = c->buffer;
1578 c->state = HTTPSTATE_SEND_HEADER;
1582 if (redir_type != REDIR_NONE) {
1583 const char *hostinfo = 0;
1585 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1586 if (av_strncasecmp(p, "Host:", 5) == 0) {
1590 p = strchr(p, '\n');
1601 while (av_isspace(*hostinfo))
1604 eoh = strchr(hostinfo, '\n');
1606 if (eoh[-1] == '\r')
1609 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1610 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1611 hostbuf[eoh - hostinfo] = 0;
1613 c->http_error = 200;
1615 switch(redir_type) {
1617 snprintf(q, c->buffer_size,
1618 "HTTP/1.0 200 ASX Follows\r\n"
1619 "Content-type: video/x-ms-asf\r\n"
1621 "<ASX Version=\"3\">\r\n"
1622 //"<!-- Autogenerated by ffserver -->\r\n"
1623 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1624 "</ASX>\r\n", hostbuf, filename, info);
1628 snprintf(q, c->buffer_size,
1629 "HTTP/1.0 200 RAM Follows\r\n"
1630 "Content-type: audio/x-pn-realaudio\r\n"
1632 "# Autogenerated by ffserver\r\n"
1633 "http://%s/%s%s\r\n", hostbuf, filename, info);
1637 snprintf(q, c->buffer_size,
1638 "HTTP/1.0 200 ASF Redirect follows\r\n"
1639 "Content-type: video/x-ms-asf\r\n"
1642 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1647 char hostname[256], *p;
1648 /* extract only hostname */
1649 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1650 p = strrchr(hostname, ':');
1653 snprintf(q, c->buffer_size,
1654 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1655 /* XXX: incorrect MIME type ? */
1656 "Content-type: application/x-rtsp\r\n"
1658 "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
1667 struct sockaddr_in my_addr;
1669 snprintf(q, c->buffer_size,
1670 "HTTP/1.0 200 OK\r\n"
1671 "Content-type: application/sdp\r\n"
1675 len = sizeof(my_addr);
1677 /* XXX: Should probably fail? */
1678 if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
1679 http_log("getsockname() failed\n");
1681 /* XXX: should use a dynamic buffer */
1682 sdp_data_size = prepare_sdp_description(stream,
1685 if (sdp_data_size > 0) {
1686 memcpy(q, sdp_data, sdp_data_size);
1689 av_freep(&sdp_data);
1698 /* prepare output buffer */
1699 c->buffer_ptr = c->buffer;
1701 c->state = HTTPSTATE_SEND_HEADER;
1707 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1711 stream->conns_served++;
1713 /* XXX: add there authenticate and IP match */
1716 /* if post, it means a feed is being sent */
1717 if (!stream->is_feed) {
1718 /* However it might be a status report from WMP! Let us log the
1719 * data as it might come handy one day. */
1720 const char *logline = 0;
1723 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1724 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1728 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1729 client_id = strtol(p + 18, 0, 10);
1730 p = strchr(p, '\n');
1738 char *eol = strchr(logline, '\n');
1743 if (eol[-1] == '\r')
1745 http_log("%.*s\n", (int) (eol - logline), logline);
1746 c->suppress_log = 1;
1751 http_log("\nGot request:\n%s\n", c->buffer);
1754 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1757 /* Now we have to find the client_id */
1758 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1759 if (wmpc->wmp_client_id == client_id)
1763 if (wmpc && modify_current_stream(wmpc, ratebuf))
1764 wmpc->switch_pending = 1;
1767 snprintf(msg, sizeof(msg), "POST command not handled");
1771 if (http_start_receive_data(c) < 0) {
1772 snprintf(msg, sizeof(msg), "could not open feed");
1776 c->state = HTTPSTATE_RECEIVE_DATA;
1781 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1782 http_log("\nGot request:\n%s\n", c->buffer);
1785 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1788 /* open input stream */
1789 if (open_input_stream(c, info) < 0) {
1790 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1794 /* prepare HTTP header */
1796 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1797 mime_type = c->stream->fmt->mime_type;
1799 mime_type = "application/x-octet-stream";
1800 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1802 /* for asf, we need extra headers */
1803 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1804 /* Need to allocate a client id */
1806 c->wmp_client_id = av_lfg_get(&random_state);
1808 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);
1810 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1811 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1812 q = c->buffer + strlen(c->buffer);
1814 /* prepare output buffer */
1816 c->buffer_ptr = c->buffer;
1818 c->state = HTTPSTATE_SEND_HEADER;
1821 c->http_error = 404;
1823 if (!htmlencode(msg, &encoded_msg)) {
1824 http_log("Could not encode filename '%s' as HTML\n", msg);
1826 snprintf(q, c->buffer_size,
1827 "HTTP/1.0 404 Not Found\r\n"
1828 "Content-type: text/html\r\n"
1833 "<meta charset=\"UTF-8\">\n"
1834 "<title>404 Not Found</title>\n"
1837 "</html>\n", encoded_msg? encoded_msg : "File not found");
1839 /* prepare output buffer */
1840 c->buffer_ptr = c->buffer;
1842 c->state = HTTPSTATE_SEND_HEADER;
1843 av_freep(&encoded_msg);
1847 /* horrible: we use this value to avoid
1848 * going to the send data state */
1849 c->http_error = 200;
1850 c->state = HTTPSTATE_SEND_HEADER;
1854 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1856 static const char suffix[] = " kMGTP";
1859 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1861 avio_printf(pb, "%"PRId64"%c", count, *s);
1864 static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
1867 const char *type = "unknown";
1868 char parameters[64];
1872 stream_no = stream->nb_streams;
1874 avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
1875 "type<th>kbit/s<th align=left>codec<th align=left>"
1878 for (i = 0; i < stream_no; i++) {
1879 st = stream->streams[i];
1880 codec = avcodec_find_encoder(st->codec->codec_id);
1884 switch(st->codec->codec_type) {
1885 case AVMEDIA_TYPE_AUDIO:
1887 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
1888 st->codec->channels, st->codec->sample_rate);
1890 case AVMEDIA_TYPE_VIDEO:
1892 snprintf(parameters, sizeof(parameters),
1893 "%dx%d, q=%d-%d, fps=%d", st->codec->width,
1894 st->codec->height, st->codec->qmin, st->codec->qmax,
1895 st->codec->time_base.den / st->codec->time_base.num);
1901 avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
1903 i, type, (int64_t)st->codec->bit_rate/1000,
1904 codec ? codec->name : "", parameters);
1907 avio_printf(pb, "</table>\n");
1910 static void compute_status(HTTPContext *c)
1913 FFServerStream *stream;
1919 if (avio_open_dyn_buf(&pb) < 0) {
1920 /* XXX: return an error ? */
1921 c->buffer_ptr = c->buffer;
1922 c->buffer_end = c->buffer;
1926 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1927 avio_printf(pb, "Content-type: text/html\r\n");
1928 avio_printf(pb, "Pragma: no-cache\r\n");
1929 avio_printf(pb, "\r\n");
1931 avio_printf(pb, "<!DOCTYPE html>\n");
1932 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1933 if (c->stream->feed_filename[0])
1934 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
1935 c->stream->feed_filename);
1936 avio_printf(pb, "</head>\n<body>");
1937 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1939 avio_printf(pb, "<h2>Available Streams</h2>\n");
1940 avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
1941 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");
1942 stream = config.first_stream;
1944 char sfilename[1024];
1947 if (stream->feed == stream) {
1948 stream = stream->next;
1952 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1953 eosf = sfilename + strlen(sfilename);
1954 if (eosf - sfilename >= 4) {
1955 if (strcmp(eosf - 4, ".asf") == 0)
1956 strcpy(eosf - 4, ".asx");
1957 else if (strcmp(eosf - 3, ".rm") == 0)
1958 strcpy(eosf - 3, ".ram");
1959 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1960 /* generate a sample RTSP director if
1961 * unicast. Generate an SDP redirector if
1963 eosf = strrchr(sfilename, '.');
1965 eosf = sfilename + strlen(sfilename);
1966 if (stream->is_multicast)
1967 strcpy(eosf, ".sdp");
1969 strcpy(eosf, ".rtsp");
1973 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1974 sfilename, stream->filename);
1975 avio_printf(pb, "<td align=right> %d <td align=right> ",
1976 stream->conns_served);
1977 fmt_bytecount(pb, stream->bytes_served);
1979 switch(stream->stream_type) {
1980 case STREAM_TYPE_LIVE: {
1981 int audio_bit_rate = 0;
1982 int video_bit_rate = 0;
1983 const char *audio_codec_name = "";
1984 const char *video_codec_name = "";
1985 const char *audio_codec_name_extra = "";
1986 const char *video_codec_name_extra = "";
1988 for(i=0;i<stream->nb_streams;i++) {
1989 AVStream *st = stream->streams[i];
1990 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1992 switch(st->codec->codec_type) {
1993 case AVMEDIA_TYPE_AUDIO:
1994 audio_bit_rate += st->codec->bit_rate;
1996 if (*audio_codec_name)
1997 audio_codec_name_extra = "...";
1998 audio_codec_name = codec->name;
2001 case AVMEDIA_TYPE_VIDEO:
2002 video_bit_rate += st->codec->bit_rate;
2004 if (*video_codec_name)
2005 video_codec_name_extra = "...";
2006 video_codec_name = codec->name;
2009 case AVMEDIA_TYPE_DATA:
2010 video_bit_rate += st->codec->bit_rate;
2017 avio_printf(pb, "<td align=center> %s <td align=right> %d "
2018 "<td align=right> %d <td> %s %s <td align=right> "
2020 stream->fmt->name, stream->bandwidth,
2021 video_bit_rate / 1000, video_codec_name,
2022 video_codec_name_extra, audio_bit_rate / 1000,
2023 audio_codec_name, audio_codec_name_extra);
2026 avio_printf(pb, "<td>%s", stream->feed->filename);
2028 avio_printf(pb, "<td>%s", stream->feed_filename);
2029 avio_printf(pb, "\n");
2033 avio_printf(pb, "<td align=center> - <td align=right> - "
2034 "<td align=right> - <td><td align=right> - <td>\n");
2037 stream = stream->next;
2039 avio_printf(pb, "</table>\n");
2041 stream = config.first_stream;
2044 if (stream->feed != stream) {
2045 stream = stream->next;
2049 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
2051 avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
2058 /* This is somewhat linux specific I guess */
2059 snprintf(ps_cmd, sizeof(ps_cmd),
2060 "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
2061 (int64_t) stream->pid);
2063 pid_stat = popen(ps_cmd, "r");
2068 if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
2069 avio_printf(pb, "Currently using %s%% of the cpu. "
2070 "Total time used %s.\n",
2078 avio_printf(pb, "<p>");
2081 print_stream_params(pb, stream);
2082 stream = stream->next;
2085 /* connection status */
2086 avio_printf(pb, "<h2>Connection Status</h2>\n");
2088 avio_printf(pb, "Number of connections: %d / %d<br>\n",
2089 nb_connections, config.nb_max_connections);
2091 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2092 current_bandwidth, config.max_bandwidth);
2094 avio_printf(pb, "<table>\n");
2095 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
2096 "bit/s<th>Actual bit/s<th>Bytes transferred\n");
2097 c1 = first_http_ctx;
2105 for (j = 0; j < c1->stream->nb_streams; j++) {
2106 if (!c1->stream->feed)
2107 bitrate += c1->stream->streams[j]->codec->bit_rate;
2108 else if (c1->feed_streams[j] >= 0)
2109 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
2114 p = inet_ntoa(c1->from_addr.sin_addr);
2115 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
2117 i, c1->stream ? c1->stream->filename : "",
2118 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
2119 c1->protocol, http_state[c1->state]);
2120 fmt_bytecount(pb, bitrate);
2121 avio_printf(pb, "<td align=right>");
2122 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2123 avio_printf(pb, "<td align=right>");
2124 fmt_bytecount(pb, c1->data_count);
2125 avio_printf(pb, "\n");
2128 avio_printf(pb, "</table>\n");
2133 avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
2134 avio_printf(pb, "</body>\n</html>\n");
2136 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2137 c->buffer_ptr = c->pb_buffer;
2138 c->buffer_end = c->pb_buffer + len;
2141 static int open_input_stream(HTTPContext *c, const char *info)
2144 char input_filename[1024];
2145 AVFormatContext *s = NULL;
2146 int buf_size, i, ret;
2149 /* find file name */
2150 if (c->stream->feed) {
2151 strcpy(input_filename, c->stream->feed->feed_filename);
2152 buf_size = FFM_PACKET_SIZE;
2153 /* compute position (absolute time) */
2154 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2155 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2156 http_log("Invalid date specification '%s' for stream\n", buf);
2159 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2160 int prebuffer = strtol(buf, 0, 10);
2161 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2163 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2165 strcpy(input_filename, c->stream->feed_filename);
2167 /* compute position (relative time) */
2168 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2169 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2170 http_log("Invalid date specification '%s' for stream\n", buf);
2176 if (!input_filename[0]) {
2177 http_log("No filename was specified for stream\n");
2178 return AVERROR(EINVAL);
2182 ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
2183 &c->stream->in_opts);
2185 http_log("Could not open input '%s': %s\n",
2186 input_filename, av_err2str(ret));
2190 /* set buffer size */
2192 ret = ffio_set_buf_size(s->pb, buf_size);
2194 http_log("Failed to set buffer size\n");
2199 s->flags |= AVFMT_FLAG_GENPTS;
2201 if (strcmp(s->iformat->name, "ffm") &&
2202 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2203 http_log("Could not find stream info for input '%s'\n", input_filename);
2204 avformat_close_input(&s);
2208 /* choose stream as clock source (we favor the video stream if
2209 * present) for packet sending */
2210 c->pts_stream_index = 0;
2211 for(i=0;i<c->stream->nb_streams;i++) {
2212 if (c->pts_stream_index == 0 &&
2213 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2214 c->pts_stream_index = i;
2218 if (c->fmt_in->iformat->read_seek)
2219 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2220 /* set the start time (needed for maxtime and RTP packet timing) */
2221 c->start_time = cur_time;
2222 c->first_pts = AV_NOPTS_VALUE;
2226 /* return the server clock (in us) */
2227 static int64_t get_server_clock(HTTPContext *c)
2229 /* compute current pts value from system time */
2230 return (cur_time - c->start_time) * 1000;
2233 /* return the estimated time (in us) at which the current packet must be sent */
2234 static int64_t get_packet_send_clock(HTTPContext *c)
2236 int bytes_left, bytes_sent, frame_bytes;
2238 frame_bytes = c->cur_frame_bytes;
2239 if (frame_bytes <= 0)
2242 bytes_left = c->buffer_end - c->buffer_ptr;
2243 bytes_sent = frame_bytes - bytes_left;
2244 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2248 static int http_prepare_data(HTTPContext *c)
2251 AVFormatContext *ctx;
2253 av_freep(&c->pb_buffer);
2255 case HTTPSTATE_SEND_DATA_HEADER:
2256 ctx = avformat_alloc_context();
2258 return AVERROR(ENOMEM);
2261 av_dict_copy(&(c->fmt_ctx.metadata), c->stream->metadata, 0);
2262 c->fmt_ctx.streams = av_mallocz_array(c->stream->nb_streams,
2263 sizeof(AVStream *));
2264 if (!c->fmt_ctx.streams)
2265 return AVERROR(ENOMEM);
2267 for(i=0;i<c->stream->nb_streams;i++) {
2269 c->fmt_ctx.streams[i] = av_mallocz(sizeof(AVStream));
2271 /* if file or feed, then just take streams from FFServerStream
2273 if (!c->stream->feed ||
2274 c->stream->feed == c->stream)
2275 src = c->stream->streams[i];
2277 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2279 *(c->fmt_ctx.streams[i]) = *src;
2280 c->fmt_ctx.streams[i]->priv_data = 0;
2281 /* XXX: should be done in AVStream, not in codec */
2282 c->fmt_ctx.streams[i]->codec->frame_number = 0;
2284 /* set output format parameters */
2285 c->fmt_ctx.oformat = c->stream->fmt;
2286 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2288 c->got_key_frame = 0;
2290 /* prepare header and save header data in a stream */
2291 if (avio_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2292 /* XXX: potential leak */
2295 c->fmt_ctx.pb->seekable = 0;
2298 * HACK to avoid MPEG-PS muxer to spit many underflow errors
2299 * Default value from FFmpeg
2300 * Try to set it using configuration option
2302 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2304 if ((ret = avformat_write_header(&c->fmt_ctx, NULL)) < 0) {
2305 http_log("Error writing output header for stream '%s': %s\n",
2306 c->stream->filename, av_err2str(ret));
2309 av_dict_free(&c->fmt_ctx.metadata);
2311 len = avio_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2312 c->buffer_ptr = c->pb_buffer;
2313 c->buffer_end = c->pb_buffer + len;
2315 c->state = HTTPSTATE_SEND_DATA;
2316 c->last_packet_sent = 0;
2318 case HTTPSTATE_SEND_DATA:
2319 /* find a new packet */
2320 /* read a packet from the input stream */
2321 if (c->stream->feed)
2322 ffm_set_write_index(c->fmt_in,
2323 c->stream->feed->feed_write_index,
2324 c->stream->feed->feed_size);
2326 if (c->stream->max_time &&
2327 c->stream->max_time + c->start_time - cur_time < 0)
2328 /* We have timed out */
2329 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2333 ret = av_read_frame(c->fmt_in, &pkt);
2335 if (c->stream->feed) {
2336 /* if coming from feed, it means we reached the end of the
2337 * ffm file, so must wait for more data */
2338 c->state = HTTPSTATE_WAIT_FEED;
2339 return 1; /* state changed */
2341 if (ret == AVERROR(EAGAIN)) {
2342 /* input not ready, come back later */
2345 if (c->stream->loop) {
2346 avformat_close_input(&c->fmt_in);
2347 if (open_input_stream(c, "") < 0)
2352 /* must send trailer now because EOF or error */
2353 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2356 int source_index = pkt.stream_index;
2357 /* update first pts if needed */
2358 if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
2359 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2360 c->start_time = cur_time;
2362 /* send it to the appropriate stream */
2363 if (c->stream->feed) {
2364 /* if coming from a feed, select the right stream */
2365 if (c->switch_pending) {
2366 c->switch_pending = 0;
2367 for(i=0;i<c->stream->nb_streams;i++) {
2368 if (c->switch_feed_streams[i] == pkt.stream_index)
2369 if (pkt.flags & AV_PKT_FLAG_KEY)
2370 c->switch_feed_streams[i] = -1;
2371 if (c->switch_feed_streams[i] >= 0)
2372 c->switch_pending = 1;
2375 for(i=0;i<c->stream->nb_streams;i++) {
2376 if (c->stream->feed_streams[i] == pkt.stream_index) {
2377 AVStream *st = c->fmt_in->streams[source_index];
2378 pkt.stream_index = i;
2379 if (pkt.flags & AV_PKT_FLAG_KEY &&
2380 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2381 c->stream->nb_streams == 1))
2382 c->got_key_frame = 1;
2383 if (!c->stream->send_on_key || c->got_key_frame)
2388 AVCodecContext *codec;
2389 AVStream *ist, *ost;
2391 ist = c->fmt_in->streams[source_index];
2392 /* specific handling for RTP: we use several
2393 * output streams (one for each RTP connection).
2394 * XXX: need more abstract handling */
2395 if (c->is_packetized) {
2396 /* compute send time and duration */
2397 if (pkt.dts != AV_NOPTS_VALUE) {
2398 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2399 c->cur_pts -= c->first_pts;
2401 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2402 /* find RTP context */
2403 c->packet_stream_index = pkt.stream_index;
2404 ctx = c->rtp_ctx[c->packet_stream_index];
2406 av_packet_unref(&pkt);
2409 codec = ctx->streams[0]->codec;
2410 /* only one stream per RTP connection */
2411 pkt.stream_index = 0;
2415 codec = ctx->streams[pkt.stream_index]->codec;
2418 if (c->is_packetized) {
2419 int max_packet_size;
2420 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2421 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2423 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2424 ret = ffio_open_dyn_packet_buf(&ctx->pb,
2427 ret = avio_open_dyn_buf(&ctx->pb);
2430 /* XXX: potential leak */
2433 ost = ctx->streams[pkt.stream_index];
2435 ctx->pb->seekable = 0;
2436 if (pkt.dts != AV_NOPTS_VALUE)
2437 pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
2439 if (pkt.pts != AV_NOPTS_VALUE)
2440 pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
2442 pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
2444 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2445 http_log("Error writing frame to output for stream '%s': %s\n",
2446 c->stream->filename, av_err2str(ret));
2447 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2450 av_freep(&c->pb_buffer);
2451 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2453 c->cur_frame_bytes = len;
2454 c->buffer_ptr = c->pb_buffer;
2455 c->buffer_end = c->pb_buffer + len;
2457 codec->frame_number++;
2459 av_packet_unref(&pkt);
2463 av_packet_unref(&pkt);
2468 case HTTPSTATE_SEND_DATA_TRAILER:
2469 /* last packet test ? */
2470 if (c->last_packet_sent || c->is_packetized)
2473 /* prepare header */
2474 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2475 /* XXX: potential leak */
2478 c->fmt_ctx.pb->seekable = 0;
2479 av_write_trailer(ctx);
2480 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2481 c->buffer_ptr = c->pb_buffer;
2482 c->buffer_end = c->pb_buffer + len;
2484 c->last_packet_sent = 1;
2490 /* should convert the format at the same time */
2491 /* send data starting at c->buffer_ptr to the output connection
2492 * (either UDP or TCP)
2494 static int http_send_data(HTTPContext *c)
2499 if (c->buffer_ptr >= c->buffer_end) {
2500 ret = http_prepare_data(c);
2504 /* state change requested */
2507 if (c->is_packetized) {
2508 /* RTP data output */
2509 len = c->buffer_end - c->buffer_ptr;
2511 /* fail safe - should never happen */
2513 c->buffer_ptr = c->buffer_end;
2516 len = (c->buffer_ptr[0] << 24) |
2517 (c->buffer_ptr[1] << 16) |
2518 (c->buffer_ptr[2] << 8) |
2520 if (len > (c->buffer_end - c->buffer_ptr))
2522 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2523 /* nothing to send yet: we can wait */
2527 c->data_count += len;
2528 update_datarate(&c->datarate, c->data_count);
2530 c->stream->bytes_served += len;
2532 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2533 /* RTP packets are sent inside the RTSP TCP connection */
2535 int interleaved_index, size;
2537 HTTPContext *rtsp_c;
2540 /* if no RTSP connection left, error */
2543 /* if already sending something, then wait. */
2544 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2546 if (avio_open_dyn_buf(&pb) < 0)
2548 interleaved_index = c->packet_stream_index * 2;
2549 /* RTCP packets are sent at odd indexes */
2550 if (c->buffer_ptr[1] == 200)
2551 interleaved_index++;
2552 /* write RTSP TCP header */
2554 header[1] = interleaved_index;
2555 header[2] = len >> 8;
2557 avio_write(pb, header, 4);
2558 /* write RTP packet data */
2560 avio_write(pb, c->buffer_ptr, len);
2561 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2562 /* prepare asynchronous TCP sending */
2563 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2564 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2565 c->buffer_ptr += len;
2567 /* send everything we can NOW */
2568 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2569 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2571 rtsp_c->packet_buffer_ptr += len;
2572 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2573 /* if we could not send all the data, we will
2574 * send it later, so a new state is needed to
2575 * "lock" the RTSP TCP connection */
2576 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2579 /* all data has been sent */
2580 av_freep(&c->packet_buffer);
2582 /* send RTP packet directly in UDP */
2584 ffurl_write(c->rtp_handles[c->packet_stream_index],
2585 c->buffer_ptr, len);
2586 c->buffer_ptr += len;
2587 /* here we continue as we can send several packets
2591 /* TCP data output */
2592 len = send(c->fd, c->buffer_ptr,
2593 c->buffer_end - c->buffer_ptr, 0);
2595 if (ff_neterrno() != AVERROR(EAGAIN) &&
2596 ff_neterrno() != AVERROR(EINTR))
2597 /* error : close connection */
2602 c->buffer_ptr += len;
2604 c->data_count += len;
2605 update_datarate(&c->datarate, c->data_count);
2607 c->stream->bytes_served += len;
2615 static int http_start_receive_data(HTTPContext *c)
2621 if (c->stream->feed_opened) {
2622 http_log("Stream feed '%s' was not opened\n",
2623 c->stream->feed_filename);
2624 return AVERROR(EINVAL);
2627 /* Don't permit writing to this one */
2628 if (c->stream->readonly) {
2629 http_log("Cannot write to read-only file '%s'\n",
2630 c->stream->feed_filename);
2631 return AVERROR(EINVAL);
2635 fd = open(c->stream->feed_filename, O_RDWR);
2637 ret = AVERROR(errno);
2638 http_log("Could not open feed file '%s': %s\n",
2639 c->stream->feed_filename, strerror(errno));
2644 if (c->stream->truncate) {
2645 /* truncate feed file */
2646 ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
2647 http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
2648 if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
2649 ret = AVERROR(errno);
2650 http_log("Error truncating feed file '%s': %s\n",
2651 c->stream->feed_filename, strerror(errno));
2655 ret64 = ffm_read_write_index(fd);
2657 http_log("Error reading write index from feed file '%s': %s\n",
2658 c->stream->feed_filename, strerror(errno));
2661 c->stream->feed_write_index = ret64;
2664 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
2666 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2667 lseek(fd, 0, SEEK_SET);
2669 /* init buffer input */
2670 c->buffer_ptr = c->buffer;
2671 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
2672 c->stream->feed_opened = 1;
2673 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
2677 static int http_receive_data(HTTPContext *c)
2680 int len, loop_run = 0;
2682 while (c->chunked_encoding && !c->chunk_size &&
2683 c->buffer_end > c->buffer_ptr) {
2684 /* read chunk header, if present */
2685 len = recv(c->fd, c->buffer_ptr, 1, 0);
2688 if (ff_neterrno() != AVERROR(EAGAIN) &&
2689 ff_neterrno() != AVERROR(EINTR))
2690 /* error : close connection */
2693 } else if (len == 0) {
2694 /* end of connection : close it */
2696 } else if (c->buffer_ptr - c->buffer >= 2 &&
2697 !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
2698 c->chunk_size = strtol(c->buffer, 0, 16);
2699 if (c->chunk_size == 0) // end of stream
2701 c->buffer_ptr = c->buffer;
2703 } else if (++loop_run > 10)
2704 /* no chunk header, abort */
2710 if (c->buffer_end > c->buffer_ptr) {
2711 len = recv(c->fd, c->buffer_ptr,
2712 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2714 if (ff_neterrno() != AVERROR(EAGAIN) &&
2715 ff_neterrno() != AVERROR(EINTR))
2716 /* error : close connection */
2718 } else if (len == 0)
2719 /* end of connection : close it */
2722 c->chunk_size -= len;
2723 c->buffer_ptr += len;
2724 c->data_count += len;
2725 update_datarate(&c->datarate, c->data_count);
2729 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2730 if (c->buffer[0] != 'f' ||
2731 c->buffer[1] != 'm') {
2732 http_log("Feed stream has become desynchronized -- disconnecting\n");
2737 if (c->buffer_ptr >= c->buffer_end) {
2738 FFServerStream *feed = c->stream;
2739 /* a packet has been received : write it in the store, except
2741 if (c->data_count > FFM_PACKET_SIZE) {
2742 /* XXX: use llseek or url_seek
2743 * XXX: Should probably fail? */
2744 if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
2745 http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
2747 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2748 http_log("Error writing to feed file: %s\n", strerror(errno));
2752 feed->feed_write_index += FFM_PACKET_SIZE;
2753 /* update file size */
2754 if (feed->feed_write_index > c->stream->feed_size)
2755 feed->feed_size = feed->feed_write_index;
2757 /* handle wrap around if max file size reached */
2758 if (c->stream->feed_max_size &&
2759 feed->feed_write_index >= c->stream->feed_max_size)
2760 feed->feed_write_index = FFM_PACKET_SIZE;
2763 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2764 http_log("Error writing index to feed file: %s\n",
2769 /* wake up any waiting connections */
2770 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2771 if (c1->state == HTTPSTATE_WAIT_FEED &&
2772 c1->stream->feed == c->stream->feed)
2773 c1->state = HTTPSTATE_SEND_DATA;
2776 /* We have a header in our hands that contains useful data */
2777 AVFormatContext *s = avformat_alloc_context();
2779 AVInputFormat *fmt_in;
2785 /* use feed output format name to find corresponding input format */
2786 fmt_in = av_find_input_format(feed->fmt->name);
2790 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2791 0, NULL, NULL, NULL, NULL);
2798 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2803 /* Now we have the actual streams */
2804 if (s->nb_streams != feed->nb_streams) {
2805 avformat_close_input(&s);
2807 http_log("Feed '%s' stream number does not match registered feed\n",
2808 c->stream->feed_filename);
2812 for (i = 0; i < s->nb_streams; i++) {
2813 AVStream *fst = feed->streams[i];
2814 AVStream *st = s->streams[i];
2815 avcodec_copy_context(fst->codec, st->codec);
2818 avformat_close_input(&s);
2821 c->buffer_ptr = c->buffer;
2826 c->stream->feed_opened = 0;
2828 /* wake up any waiting connections to stop waiting for feed */
2829 for(c1 = first_http_ctx; c1; c1 = c1->next) {
2830 if (c1->state == HTTPSTATE_WAIT_FEED &&
2831 c1->stream->feed == c->stream->feed)
2832 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2837 /********************************************************************/
2840 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2847 str = RTSP_STATUS_CODE2STRING(error_number);
2849 str = "Unknown Error";
2851 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2852 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2854 /* output GMT time */
2857 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2858 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2861 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2863 rtsp_reply_header(c, error_number);
2864 avio_printf(c->pb, "\r\n");
2867 static int rtsp_parse_request(HTTPContext *c)
2869 const char *p, *p1, *p2;
2875 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2877 c->buffer_ptr[0] = '\0';
2880 get_word(cmd, sizeof(cmd), &p);
2881 get_word(url, sizeof(url), &p);
2882 get_word(protocol, sizeof(protocol), &p);
2884 av_strlcpy(c->method, cmd, sizeof(c->method));
2885 av_strlcpy(c->url, url, sizeof(c->url));
2886 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2888 if (avio_open_dyn_buf(&c->pb) < 0) {
2889 /* XXX: cannot do more */
2890 c->pb = NULL; /* safety */
2894 /* check version name */
2895 if (strcmp(protocol, "RTSP/1.0")) {
2896 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2900 /* parse each header line */
2901 /* skip to next line */
2902 while (*p != '\n' && *p != '\0')
2906 while (*p != '\0') {
2907 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2911 if (p2 > p && p2[-1] == '\r')
2913 /* skip empty line */
2917 if (len > sizeof(line) - 1)
2918 len = sizeof(line) - 1;
2919 memcpy(line, p, len);
2921 ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
2925 /* handle sequence number */
2926 c->seq = header->seq;
2928 if (!strcmp(cmd, "DESCRIBE"))
2929 rtsp_cmd_describe(c, url);
2930 else if (!strcmp(cmd, "OPTIONS"))
2931 rtsp_cmd_options(c, url);
2932 else if (!strcmp(cmd, "SETUP"))
2933 rtsp_cmd_setup(c, url, header);
2934 else if (!strcmp(cmd, "PLAY"))
2935 rtsp_cmd_play(c, url, header);
2936 else if (!strcmp(cmd, "PAUSE"))
2937 rtsp_cmd_interrupt(c, url, header, 1);
2938 else if (!strcmp(cmd, "TEARDOWN"))
2939 rtsp_cmd_interrupt(c, url, header, 0);
2941 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2944 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2945 c->pb = NULL; /* safety */
2947 /* XXX: cannot do more */
2950 c->buffer_ptr = c->pb_buffer;
2951 c->buffer_end = c->pb_buffer + len;
2952 c->state = RTSPSTATE_SEND_REPLY;
2956 static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
2957 struct in_addr my_ip)
2959 AVFormatContext *avc;
2960 AVStream *avs = NULL;
2961 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
2962 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
2967 avc = avformat_alloc_context();
2968 if (!avc || !rtp_format)
2971 avc->oformat = rtp_format;
2972 av_dict_set(&avc->metadata, "title",
2973 entry ? entry->value : "No Title", 0);
2974 avc->nb_streams = stream->nb_streams;
2975 if (stream->is_multicast) {
2976 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2977 inet_ntoa(stream->multicast_ip),
2978 stream->multicast_port, stream->multicast_ttl);
2980 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
2982 avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
2986 avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
2990 for(i = 0; i < stream->nb_streams; i++) {
2991 avc->streams[i] = &avs[i];
2992 avc->streams[i]->codec = stream->streams[i]->codec;
2993 avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
2994 avc->streams[i]->codecpar = stream->streams[i]->codecpar;
2996 *pbuffer = av_mallocz(2048);
2999 av_sdp_create(&avc, 1, *pbuffer, 2048);
3002 av_freep(&avc->streams);
3003 av_dict_free(&avc->metadata);
3007 return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
3010 static void rtsp_cmd_options(HTTPContext *c, const char *url)
3012 /* rtsp_reply_header(c, RTSP_STATUS_OK); */
3013 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
3014 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
3015 avio_printf(c->pb, "Public: %s\r\n",
3016 "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
3017 avio_printf(c->pb, "\r\n");
3020 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
3022 FFServerStream *stream;
3028 struct sockaddr_in my_addr;
3030 /* find which URL is asked */
3031 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3036 for(stream = config.first_stream; stream; stream = stream->next) {
3037 if (!stream->is_feed &&
3038 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
3039 !strcmp(path, stream->filename)) {
3043 /* no stream found */
3044 rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
3048 /* prepare the media description in SDP format */
3050 /* get the host IP */
3051 len = sizeof(my_addr);
3052 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3053 content_length = prepare_sdp_description(stream, &content,
3055 if (content_length < 0) {
3056 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3059 rtsp_reply_header(c, RTSP_STATUS_OK);
3060 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
3061 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
3062 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
3063 avio_printf(c->pb, "\r\n");
3064 avio_write(c->pb, content, content_length);
3068 static HTTPContext *find_rtp_session(const char *session_id)
3072 if (session_id[0] == '\0')
3075 for(c = first_http_ctx; c; c = c->next) {
3076 if (!strcmp(c->session_id, session_id))
3082 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3084 RTSPTransportField *th;
3087 for(i=0;i<h->nb_transports;i++) {
3088 th = &h->transports[i];
3089 if (th->lower_transport == lower_transport)
3095 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3096 RTSPMessageHeader *h)
3098 FFServerStream *stream;
3099 int stream_index, rtp_port, rtcp_port;
3104 RTSPTransportField *th;
3105 struct sockaddr_in dest_addr;
3106 RTSPActionServerSetup setup;
3108 /* find which URL is asked */
3109 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3114 /* now check each stream */
3115 for(stream = config.first_stream; stream; stream = stream->next) {
3116 if (stream->is_feed || !stream->fmt ||
3117 strcmp(stream->fmt->name, "rtp")) {
3120 /* accept aggregate filenames only if single stream */
3121 if (!strcmp(path, stream->filename)) {
3122 if (stream->nb_streams != 1) {
3123 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3130 for(stream_index = 0; stream_index < stream->nb_streams;
3132 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3133 stream->filename, stream_index);
3134 if (!strcmp(path, buf))
3138 /* no stream found */
3139 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3143 /* generate session id if needed */
3144 if (h->session_id[0] == '\0') {
3145 unsigned random0 = av_lfg_get(&random_state);
3146 unsigned random1 = av_lfg_get(&random_state);
3147 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3151 /* find RTP session, and create it if none found */
3152 rtp_c = find_rtp_session(h->session_id);
3154 /* always prefer UDP */
3155 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3157 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3159 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3164 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3165 th->lower_transport);
3167 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3171 /* open input stream */
3172 if (open_input_stream(rtp_c, "") < 0) {
3173 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3178 /* test if stream is OK (test needed because several SETUP needs
3179 * to be done for a given file) */
3180 if (rtp_c->stream != stream) {
3181 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3185 /* test if stream is already set up */
3186 if (rtp_c->rtp_ctx[stream_index]) {
3187 rtsp_reply_error(c, RTSP_STATUS_STATE);
3191 /* check transport */
3192 th = find_transport(h, rtp_c->rtp_protocol);
3193 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3194 th->client_port_min <= 0)) {
3195 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3199 /* setup default options */
3200 setup.transport_option[0] = '\0';
3201 dest_addr = rtp_c->from_addr;
3202 dest_addr.sin_port = htons(th->client_port_min);
3205 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3206 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3210 /* now everything is OK, so we can send the connection parameters */
3211 rtsp_reply_header(c, RTSP_STATUS_OK);
3213 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3215 switch(rtp_c->rtp_protocol) {
3216 case RTSP_LOWER_TRANSPORT_UDP:
3217 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3218 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3219 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3220 "client_port=%d-%d;server_port=%d-%d",
3221 th->client_port_min, th->client_port_max,
3222 rtp_port, rtcp_port);
3224 case RTSP_LOWER_TRANSPORT_TCP:
3225 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3226 stream_index * 2, stream_index * 2 + 1);
3231 if (setup.transport_option[0] != '\0')
3232 avio_printf(c->pb, ";%s", setup.transport_option);
3233 avio_printf(c->pb, "\r\n");
3236 avio_printf(c->pb, "\r\n");
3241 * find an RTP connection by using the session ID. Check consistency
3244 static HTTPContext *find_rtp_session_with_url(const char *url,
3245 const char *session_id)
3253 rtp_c = find_rtp_session(session_id);
3257 /* find which URL is asked */
3258 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3262 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3263 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3264 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3265 rtp_c->stream->filename, s);
3266 if(!strncmp(path, buf, sizeof(buf)))
3267 /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
3268 * if nb_streams>1? */
3272 if (len > 0 && path[len - 1] == '/' &&
3273 !strncmp(path, rtp_c->stream->filename, len - 1))
3278 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3282 rtp_c = find_rtp_session_with_url(url, h->session_id);
3284 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3288 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3289 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3290 rtp_c->state != HTTPSTATE_READY) {
3291 rtsp_reply_error(c, RTSP_STATUS_STATE);
3295 rtp_c->state = HTTPSTATE_SEND_DATA;
3297 /* now everything is OK, so we can send the connection parameters */
3298 rtsp_reply_header(c, RTSP_STATUS_OK);
3300 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3301 avio_printf(c->pb, "\r\n");
3304 static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
3305 RTSPMessageHeader *h, int pause_only)
3309 rtp_c = find_rtp_session_with_url(url, h->session_id);
3311 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3316 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3317 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3318 rtsp_reply_error(c, RTSP_STATUS_STATE);
3321 rtp_c->state = HTTPSTATE_READY;
3322 rtp_c->first_pts = AV_NOPTS_VALUE;
3325 /* now everything is OK, so we can send the connection parameters */
3326 rtsp_reply_header(c, RTSP_STATUS_OK);
3328 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3329 avio_printf(c->pb, "\r\n");
3332 close_connection(rtp_c);
3335 /********************************************************************/
3338 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3339 FFServerStream *stream,
3340 const char *session_id,
3341 enum RTSPLowerTransport rtp_protocol)
3343 HTTPContext *c = NULL;
3344 const char *proto_str;
3346 /* XXX: should output a warning page when coming
3347 * close to the connection limit */
3348 if (nb_connections >= config.nb_max_connections)
3351 /* add a new connection */
3352 c = av_mallocz(sizeof(HTTPContext));
3357 c->poll_entry = NULL;
3358 c->from_addr = *from_addr;
3359 c->buffer_size = IOBUFFER_INIT_SIZE;
3360 c->buffer = av_malloc(c->buffer_size);
3365 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3366 c->state = HTTPSTATE_READY;
3367 c->is_packetized = 1;
3368 c->rtp_protocol = rtp_protocol;
3370 /* protocol is shown in statistics */
3371 switch(c->rtp_protocol) {
3372 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3373 proto_str = "MCAST";
3375 case RTSP_LOWER_TRANSPORT_UDP:
3378 case RTSP_LOWER_TRANSPORT_TCP:
3385 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3386 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3388 current_bandwidth += stream->bandwidth;
3390 c->next = first_http_ctx;
3396 av_freep(&c->buffer);
3403 * add a new RTP stream in an RTP connection (used in RTSP SETUP
3404 * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3407 static int rtp_new_av_stream(HTTPContext *c,
3408 int stream_index, struct sockaddr_in *dest_addr,
3409 HTTPContext *rtsp_c)
3411 AVFormatContext *ctx;
3414 URLContext *h = NULL;
3416 int max_packet_size;
3419 /* now we can open the relevant output stream */
3420 ctx = avformat_alloc_context();
3423 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3425 st = avformat_new_stream(ctx, NULL);
3429 av_freep(&st->codec);
3430 av_freep(&st->info);
3431 st_internal = st->internal;
3433 if (!c->stream->feed ||
3434 c->stream->feed == c->stream)
3435 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3438 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3440 st->priv_data = NULL;
3441 st->internal = st_internal;
3443 /* build destination RTP address */
3444 ipaddr = inet_ntoa(dest_addr->sin_addr);
3446 switch(c->rtp_protocol) {
3447 case RTSP_LOWER_TRANSPORT_UDP:
3448 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3451 /* XXX: also pass as parameter to function ? */
3452 if (c->stream->is_multicast) {
3454 ttl = c->stream->multicast_ttl;
3457 snprintf(ctx->filename, sizeof(ctx->filename),
3458 "rtp://%s:%d?multicast=1&ttl=%d",
3459 ipaddr, ntohs(dest_addr->sin_port), ttl);
3461 snprintf(ctx->filename, sizeof(ctx->filename),
3462 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3465 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3467 c->rtp_handles[stream_index] = h;
3468 max_packet_size = h->max_packet_size;
3470 case RTSP_LOWER_TRANSPORT_TCP:
3473 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3479 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3480 ipaddr, ntohs(dest_addr->sin_port),
3481 c->stream->filename, stream_index, c->protocol);
3483 /* normally, no packets should be output here, but the packet size may
3485 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
3486 /* XXX: close stream */
3489 if (avformat_write_header(ctx, NULL) < 0) {
3497 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3501 c->rtp_ctx[stream_index] = ctx;
3505 /********************************************************************/
3506 /* ffserver initialization */
3508 /* FIXME: This code should use avformat_new_stream() */
3509 static AVStream *add_av_stream1(FFServerStream *stream,
3510 AVCodecContext *codec, int copy)
3514 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3517 fst = av_mallocz(sizeof(AVStream));
3521 fst->codec = avcodec_alloc_context3(codec->codec);
3526 avcodec_copy_context(fst->codec, codec);
3528 /* live streams must use the actual feed's codec since it may be
3529 * updated later to carry extradata needed by them.
3533 fst->priv_data = av_mallocz(sizeof(FeedData));
3534 fst->internal = av_mallocz(sizeof(*fst->internal));
3535 fst->internal->avctx = avcodec_alloc_context3(NULL);
3536 fst->codecpar = avcodec_parameters_alloc();
3537 fst->index = stream->nb_streams;
3538 avpriv_set_pts_info(fst, 33, 1, 90000);
3539 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3540 stream->streams[stream->nb_streams++] = fst;
3544 /* return the stream number in the feed */
3545 static int add_av_stream(FFServerStream *feed, AVStream *st)
3548 AVCodecContext *av, *av1;
3552 for(i=0;i<feed->nb_streams;i++) {
3553 av1 = feed->streams[i]->codec;
3554 if (av1->codec_id == av->codec_id &&
3555 av1->codec_type == av->codec_type &&
3556 av1->bit_rate == av->bit_rate) {
3558 switch(av->codec_type) {
3559 case AVMEDIA_TYPE_AUDIO:
3560 if (av1->channels == av->channels &&
3561 av1->sample_rate == av->sample_rate)
3564 case AVMEDIA_TYPE_VIDEO:
3565 if (av1->width == av->width &&
3566 av1->height == av->height &&
3567 av1->time_base.den == av->time_base.den &&
3568 av1->time_base.num == av->time_base.num &&
3569 av1->gop_size == av->gop_size)
3578 fst = add_av_stream1(feed, av, 0);
3581 if (av_stream_get_recommended_encoder_configuration(st))
3582 av_stream_set_recommended_encoder_configuration(fst,
3583 av_strdup(av_stream_get_recommended_encoder_configuration(st)));
3584 return feed->nb_streams - 1;
3587 static void remove_stream(FFServerStream *stream)
3589 FFServerStream **ps;
3590 ps = &config.first_stream;
3599 /* specific MPEG4 handling : we extract the raw parameters */
3600 static void extract_mpeg4_header(AVFormatContext *infile)
3602 int mpeg4_count, i, size;
3607 infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
3610 for(i=0;i<infile->nb_streams;i++) {
3611 st = infile->streams[i];
3612 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3613 st->codec->extradata_size == 0) {
3620 printf("MPEG4 without extra data: trying to find header in %s\n",
3622 while (mpeg4_count > 0) {
3623 if (av_read_frame(infile, &pkt) < 0)
3625 st = infile->streams[pkt.stream_index];
3626 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3627 st->codec->extradata_size == 0) {
3628 av_freep(&st->codec->extradata);
3629 /* fill extradata with the header */
3630 /* XXX: we make hard suppositions here ! */
3632 while (p < pkt.data + pkt.size - 4) {
3633 /* stop when vop header is found */
3634 if (p[0] == 0x00 && p[1] == 0x00 &&
3635 p[2] == 0x01 && p[3] == 0xb6) {
3636 size = p - pkt.data;
3637 st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
3638 st->codec->extradata_size = size;
3639 memcpy(st->codec->extradata, pkt.data, size);
3646 av_packet_unref(&pkt);
3650 /* compute the needed AVStream for each file */
3651 static void build_file_streams(void)
3653 FFServerStream *stream;
3654 AVFormatContext *infile;
3657 /* gather all streams */
3658 for(stream = config.first_stream; stream; stream = stream->next) {
3661 if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
3664 /* the stream comes from a file */
3665 /* try to open the file */
3669 /* specific case: if transport stream output to RTP,
3670 * we use a raw transport stream reader */
3671 if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
3672 av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
3674 if (!stream->feed_filename[0]) {
3675 http_log("Unspecified feed file for stream '%s'\n",
3680 http_log("Opening feed file '%s' for stream '%s'\n",
3681 stream->feed_filename, stream->filename);
3683 ret = avformat_open_input(&infile, stream->feed_filename,
3684 stream->ifmt, &stream->in_opts);
3686 http_log("Could not open '%s': %s\n", stream->feed_filename,
3688 /* remove stream (no need to spend more time on it) */
3690 remove_stream(stream);
3692 /* find all the AVStreams inside and reference them in
3694 if (avformat_find_stream_info(infile, NULL) < 0) {
3695 http_log("Could not find codec parameters from '%s'\n",
3696 stream->feed_filename);
3697 avformat_close_input(&infile);
3700 extract_mpeg4_header(infile);