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/avio_internal.h"
42 #include "libavformat/internal.h"
43 #include "libavformat/url.h"
45 #include "libavutil/avassert.h"
46 #include "libavutil/avstring.h"
47 #include "libavutil/lfg.h"
48 #include "libavutil/dict.h"
49 #include "libavutil/intreadwrite.h"
50 #include "libavutil/mathematics.h"
51 #include "libavutil/pixdesc.h"
52 #include "libavutil/random_seed.h"
53 #include "libavutil/parseutils.h"
54 #include "libavutil/opt.h"
55 #include "libavutil/time.h"
60 #include <sys/ioctl.h>
71 const char program_name[] = "ffserver";
72 const int program_birth_year = 2000;
74 static const OptionDef options[];
77 HTTPSTATE_WAIT_REQUEST,
78 HTTPSTATE_SEND_HEADER,
79 HTTPSTATE_SEND_DATA_HEADER,
80 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
81 HTTPSTATE_SEND_DATA_TRAILER,
82 HTTPSTATE_RECEIVE_DATA,
83 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
86 RTSPSTATE_WAIT_REQUEST,
88 RTSPSTATE_SEND_PACKET,
91 static const char *http_state[] = {
107 #define MAX_STREAMS 20
109 #define IOBUFFER_INIT_SIZE 8192
111 /* timeouts are in ms */
112 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
113 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
115 #define SYNC_TIMEOUT (10 * 1000)
117 typedef struct RTSPActionServerSetup {
119 char transport_option[512];
120 } RTSPActionServerSetup;
123 int64_t count1, count2;
124 int64_t time1, time2;
127 /* context associated with one connection */
128 typedef struct HTTPContext {
129 enum HTTPState state;
130 int fd; /* socket file descriptor */
131 struct sockaddr_in from_addr; /* origin */
132 struct pollfd *poll_entry; /* used when polling */
134 uint8_t *buffer_ptr, *buffer_end;
137 int chunked_encoding;
138 int chunk_size; /* 0 if it needs to be read */
139 struct HTTPContext *next;
140 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
144 /* input format handling */
145 AVFormatContext *fmt_in;
146 int64_t start_time; /* In milliseconds - this wraps fairly often */
147 int64_t first_pts; /* initial pts value */
148 int64_t cur_pts; /* current pts value from the stream in us */
149 int64_t cur_frame_duration; /* duration of the current frame in us */
150 int cur_frame_bytes; /* output frame size, needed to compute
151 the time at which we send each
153 int pts_stream_index; /* stream we choose as clock reference */
154 int64_t cur_clock; /* current clock reference value in us */
155 /* output format handling */
156 struct FFStream *stream;
157 /* -1 is invalid stream */
158 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
159 int switch_feed_streams[MAX_STREAMS]; /* index of streams in the feed */
161 AVFormatContext fmt_ctx; /* instance of FFStream for one user */
162 int last_packet_sent; /* true if last data packet was sent */
164 DataRateData datarate;
171 int is_packetized; /* if true, the stream is packetized */
172 int packet_stream_index; /* current stream for output in state machine */
174 /* RTSP state specific */
175 uint8_t *pb_buffer; /* XXX: use that in all the code */
177 int seq; /* RTSP sequence number */
179 /* RTP state specific */
180 enum RTSPLowerTransport rtp_protocol;
181 char session_id[32]; /* session id */
182 AVFormatContext *rtp_ctx[MAX_STREAMS];
184 /* RTP/UDP specific */
185 URLContext *rtp_handles[MAX_STREAMS];
187 /* RTP/TCP specific */
188 struct HTTPContext *rtsp_c;
189 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
192 /* each generated stream is described here */
196 STREAM_TYPE_REDIRECT,
199 enum IPAddressAction {
204 typedef struct IPAddressACL {
205 struct IPAddressACL *next;
206 enum IPAddressAction action;
207 /* These are in host order */
208 struct in_addr first;
212 /* description of each stream of the ffserver.conf file */
213 typedef struct FFStream {
214 enum StreamType stream_type;
215 char filename[1024]; /* stream filename */
216 struct FFStream *feed; /* feed we are using (can be null if
218 AVDictionary *in_opts; /* input parameters */
219 AVDictionary *metadata; /* metadata to set on the stream */
220 AVInputFormat *ifmt; /* if non NULL, force input format */
223 char dynamic_acl[1024];
225 int prebuffer; /* Number of millseconds early to start */
226 int64_t max_time; /* Number of milliseconds to run */
228 AVStream *streams[MAX_STREAMS];
229 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
230 char feed_filename[1024]; /* file name of the feed storage, or
231 input file name for a stream */
232 pid_t pid; /* Of ffmpeg process */
233 time_t pid_start; /* Of ffmpeg process */
235 struct FFStream *next;
236 unsigned bandwidth; /* bandwidth, in kbits/s */
239 /* multicast specific */
241 struct in_addr multicast_ip;
242 int multicast_port; /* first port used for multicast */
244 int loop; /* if true, send the stream in loops (only meaningful if file) */
247 int feed_opened; /* true if someone is writing to the feed */
248 int is_feed; /* true if it is a feed */
249 int readonly; /* True if writing is prohibited to the file */
250 int truncate; /* True if feeder connection truncate the feed file */
252 int64_t bytes_served;
253 int64_t feed_max_size; /* maximum storage size, zero means unlimited */
254 int64_t feed_write_index; /* current write position in feed (it wraps around) */
255 int64_t feed_size; /* current size of feed */
256 struct FFStream *next_feed;
259 typedef struct FeedData {
260 long long data_count;
261 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
264 static struct sockaddr_in my_http_addr;
265 static struct sockaddr_in my_rtsp_addr;
267 static char logfilename[1024];
268 static HTTPContext *first_http_ctx;
269 static FFStream *first_feed; /* contains only feeds */
270 static FFStream *first_stream; /* contains all streams, including feeds */
272 static void new_connection(int server_fd, int is_rtsp);
273 static void close_connection(HTTPContext *c);
276 static int handle_connection(HTTPContext *c);
277 static int http_parse_request(HTTPContext *c);
278 static int http_send_data(HTTPContext *c);
279 static void compute_status(HTTPContext *c);
280 static int open_input_stream(HTTPContext *c, const char *info);
281 static int http_start_receive_data(HTTPContext *c);
282 static int http_receive_data(HTTPContext *c);
285 static int rtsp_parse_request(HTTPContext *c);
286 static void rtsp_cmd_describe(HTTPContext *c, const char *url);
287 static void rtsp_cmd_options(HTTPContext *c, const char *url);
288 static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPMessageHeader *h);
289 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h);
290 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h);
291 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h);
294 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
295 struct in_addr my_ip);
298 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
299 FFStream *stream, const char *session_id,
300 enum RTSPLowerTransport rtp_protocol);
301 static int rtp_new_av_stream(HTTPContext *c,
302 int stream_index, struct sockaddr_in *dest_addr,
303 HTTPContext *rtsp_c);
305 static const char *my_program_name;
307 static const char *config_filename;
309 static int ffserver_debug;
310 static int no_launch;
311 static int need_to_start_children;
313 /* maximum number of simultaneous HTTP connections */
314 static unsigned int nb_max_http_connections = 2000;
315 static unsigned int nb_max_connections = 5;
316 static unsigned int nb_connections;
318 static uint64_t max_bandwidth = 1000;
319 static uint64_t current_bandwidth;
321 static int64_t cur_time; // Making this global saves on passing it around everywhere
323 static AVLFG random_state;
325 static FILE *logfile = NULL;
327 static void htmlstrip(char *s) {
329 s += strspn(s, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,. ");
335 static int64_t ffm_read_write_index(int fd)
339 if (lseek(fd, 8, SEEK_SET) < 0)
341 if (read(fd, buf, 8) != 8)
346 static int ffm_write_write_index(int fd, int64_t pos)
352 buf[i] = (pos >> (56 - i * 8)) & 0xff;
353 if (lseek(fd, 8, SEEK_SET) < 0)
355 if (write(fd, buf, 8) != 8)
360 static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
363 FFMContext *ffm = s->priv_data;
364 ffm->write_index = pos;
365 ffm->file_size = file_size;
368 /* FIXME: make ffserver work with IPv6 */
369 /* resolve host with also IP address parsing */
370 static int resolve_host(struct in_addr *sin_addr, const char *hostname)
373 if (!ff_inet_aton(hostname, sin_addr)) {
375 struct addrinfo *ai, *cur;
376 struct addrinfo hints = { 0 };
377 hints.ai_family = AF_INET;
378 if (getaddrinfo(hostname, NULL, &hints, &ai))
380 /* getaddrinfo returns a linked list of addrinfo structs.
381 * Even if we set ai_family = AF_INET above, make sure
382 * that the returned one actually is of the correct type. */
383 for (cur = ai; cur; cur = cur->ai_next) {
384 if (cur->ai_family == AF_INET) {
385 *sin_addr = ((struct sockaddr_in *)cur->ai_addr)->sin_addr;
394 hp = gethostbyname(hostname);
397 memcpy(sin_addr, hp->h_addr_list[0], sizeof(struct in_addr));
403 static char *ctime1(char *buf2, int buf_size)
410 av_strlcpy(buf2, p, buf_size);
411 p = buf2 + strlen(p) - 1;
417 static void http_vlog(const char *fmt, va_list vargs)
419 static int print_prefix = 1;
423 ctime1(buf, sizeof(buf));
424 fprintf(logfile, "%s ", buf);
426 print_prefix = strstr(fmt, "\n") != NULL;
427 vfprintf(logfile, fmt, vargs);
433 __attribute__ ((format (printf, 1, 2)))
435 static void http_log(const char *fmt, ...)
438 va_start(vargs, fmt);
439 http_vlog(fmt, vargs);
443 static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
445 static int print_prefix = 1;
446 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
447 if (level > av_log_get_level())
449 if (print_prefix && avc)
450 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
451 print_prefix = strstr(fmt, "\n") != NULL;
452 http_vlog(fmt, vargs);
455 static void log_connection(HTTPContext *c)
460 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
461 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
462 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
465 static void update_datarate(DataRateData *drd, int64_t count)
467 if (!drd->time1 && !drd->count1) {
468 drd->time1 = drd->time2 = cur_time;
469 drd->count1 = drd->count2 = count;
470 } else if (cur_time - drd->time2 > 5000) {
471 drd->time1 = drd->time2;
472 drd->count1 = drd->count2;
473 drd->time2 = cur_time;
478 /* In bytes per second */
479 static int compute_datarate(DataRateData *drd, int64_t count)
481 if (cur_time == drd->time1)
484 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
488 static void start_children(FFStream *feed)
493 for (; feed; feed = feed->next) {
494 if (feed->child_argv && !feed->pid) {
495 feed->pid_start = time(0);
500 http_log("Unable to create children\n");
509 /* replace "ffserver" with "ffmpeg" in the path of current
510 * program. Ignore user provided path */
511 av_strlcpy(pathname, my_program_name, sizeof(pathname));
512 slash = strrchr(pathname, '/');
517 strcpy(slash, "ffmpeg");
519 http_log("Launch command line: ");
520 http_log("%s ", pathname);
521 for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
522 http_log("%s ", feed->child_argv[i]);
525 for (i = 3; i < 256; i++)
528 if (!ffserver_debug) {
529 if (!freopen("/dev/null", "r", stdin))
530 http_log("failed to redirect STDIN to /dev/null\n;");
531 if (!freopen("/dev/null", "w", stdout))
532 http_log("failed to redirect STDOUT to /dev/null\n;");
533 if (!freopen("/dev/null", "w", stderr))
534 http_log("failed to redirect STDERR to /dev/null\n;");
537 signal(SIGPIPE, SIG_DFL);
539 execvp(pathname, feed->child_argv);
547 /* open a listening socket */
548 static int socket_open_listen(struct sockaddr_in *my_addr)
552 server_fd = socket(AF_INET,SOCK_STREAM,0);
559 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
561 my_addr->sin_family = AF_INET;
562 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
564 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
566 closesocket(server_fd);
570 if (listen (server_fd, 5) < 0) {
572 closesocket(server_fd);
575 ff_socket_nonblock(server_fd, 1);
580 /* start all multicast streams */
581 static void start_multicast(void)
586 struct sockaddr_in dest_addr = {0};
587 int default_port, stream_index;
590 for(stream = first_stream; stream != NULL; stream = stream->next) {
591 if (stream->is_multicast) {
592 unsigned random0 = av_lfg_get(&random_state);
593 unsigned random1 = av_lfg_get(&random_state);
594 /* open the RTP connection */
595 snprintf(session_id, sizeof(session_id), "%08x%08x",
598 /* choose a port if none given */
599 if (stream->multicast_port == 0) {
600 stream->multicast_port = default_port;
604 dest_addr.sin_family = AF_INET;
605 dest_addr.sin_addr = stream->multicast_ip;
606 dest_addr.sin_port = htons(stream->multicast_port);
608 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
609 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
613 if (open_input_stream(rtp_c, "") < 0) {
614 http_log("Could not open input stream for stream '%s'\n",
619 /* open each RTP stream */
620 for(stream_index = 0; stream_index < stream->nb_streams;
622 dest_addr.sin_port = htons(stream->multicast_port +
624 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
625 http_log("Could not open output stream '%s/streamid=%d'\n",
626 stream->filename, stream_index);
631 rtp_c->state = HTTPSTATE_SEND_DATA;
636 /* main loop of the HTTP server */
637 static int http_server(void)
639 int server_fd = 0, rtsp_server_fd = 0;
641 struct pollfd *poll_table, *poll_entry;
642 HTTPContext *c, *c_next;
644 if(!(poll_table = av_mallocz((nb_max_http_connections + 2)*sizeof(*poll_table)))) {
645 http_log("Impossible to allocate a poll table handling %d connections.\n", nb_max_http_connections);
649 if (my_http_addr.sin_port) {
650 server_fd = socket_open_listen(&my_http_addr);
655 if (my_rtsp_addr.sin_port) {
656 rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
657 if (rtsp_server_fd < 0)
661 if (!rtsp_server_fd && !server_fd) {
662 http_log("HTTP and RTSP disabled.\n");
666 http_log("FFserver started.\n");
668 start_children(first_feed);
673 poll_entry = poll_table;
675 poll_entry->fd = server_fd;
676 poll_entry->events = POLLIN;
679 if (rtsp_server_fd) {
680 poll_entry->fd = rtsp_server_fd;
681 poll_entry->events = POLLIN;
685 /* wait for events on each HTTP handle */
692 case HTTPSTATE_SEND_HEADER:
693 case RTSPSTATE_SEND_REPLY:
694 case RTSPSTATE_SEND_PACKET:
695 c->poll_entry = poll_entry;
697 poll_entry->events = POLLOUT;
700 case HTTPSTATE_SEND_DATA_HEADER:
701 case HTTPSTATE_SEND_DATA:
702 case HTTPSTATE_SEND_DATA_TRAILER:
703 if (!c->is_packetized) {
704 /* for TCP, we output as much as we can
705 * (may need to put a limit) */
706 c->poll_entry = poll_entry;
708 poll_entry->events = POLLOUT;
711 /* when ffserver is doing the timing, we work by
712 looking at which packet needs to be sent every
714 /* one tick wait XXX: 10 ms assumed */
719 case HTTPSTATE_WAIT_REQUEST:
720 case HTTPSTATE_RECEIVE_DATA:
721 case HTTPSTATE_WAIT_FEED:
722 case RTSPSTATE_WAIT_REQUEST:
723 /* need to catch errors */
724 c->poll_entry = poll_entry;
726 poll_entry->events = POLLIN;/* Maybe this will work */
730 c->poll_entry = NULL;
736 /* wait for an event on one connection. We poll at least every
737 second to handle timeouts */
739 ret = poll(poll_table, poll_entry - poll_table, delay);
740 if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
741 ff_neterrno() != AVERROR(EINTR))
745 cur_time = av_gettime() / 1000;
747 if (need_to_start_children) {
748 need_to_start_children = 0;
749 start_children(first_feed);
752 /* now handle the events */
753 for(c = first_http_ctx; c != NULL; c = c_next) {
755 if (handle_connection(c) < 0) {
757 /* close and free the connection */
762 poll_entry = poll_table;
764 /* new HTTP connection request ? */
765 if (poll_entry->revents & POLLIN)
766 new_connection(server_fd, 0);
769 if (rtsp_server_fd) {
770 /* new RTSP connection request ? */
771 if (poll_entry->revents & POLLIN)
772 new_connection(rtsp_server_fd, 1);
777 /* start waiting for a new HTTP/RTSP request */
778 static void start_wait_request(HTTPContext *c, int is_rtsp)
780 c->buffer_ptr = c->buffer;
781 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
784 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
785 c->state = RTSPSTATE_WAIT_REQUEST;
787 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
788 c->state = HTTPSTATE_WAIT_REQUEST;
792 static void http_send_too_busy_reply(int fd)
795 int len = snprintf(buffer, sizeof(buffer),
796 "HTTP/1.0 503 Server too busy\r\n"
797 "Content-type: text/html\r\n"
799 "<html><head><title>Too busy</title></head><body>\r\n"
800 "<p>The server is too busy to serve your request at this time.</p>\r\n"
801 "<p>The number of current connections is %u, and this exceeds the limit of %u.</p>\r\n"
802 "</body></html>\r\n",
803 nb_connections, nb_max_connections);
804 av_assert0(len < sizeof(buffer));
805 send(fd, buffer, len, 0);
809 static void new_connection(int server_fd, int is_rtsp)
811 struct sockaddr_in from_addr;
814 HTTPContext *c = NULL;
816 len = sizeof(from_addr);
817 fd = accept(server_fd, (struct sockaddr *)&from_addr,
820 http_log("error during accept %s\n", strerror(errno));
823 ff_socket_nonblock(fd, 1);
825 if (nb_connections >= nb_max_connections) {
826 http_send_too_busy_reply(fd);
830 /* add a new connection */
831 c = av_mallocz(sizeof(HTTPContext));
836 c->poll_entry = NULL;
837 c->from_addr = from_addr;
838 c->buffer_size = IOBUFFER_INIT_SIZE;
839 c->buffer = av_malloc(c->buffer_size);
843 c->next = first_http_ctx;
847 start_wait_request(c, is_rtsp);
859 static void close_connection(HTTPContext *c)
861 HTTPContext **cp, *c1;
863 AVFormatContext *ctx;
867 /* remove connection from list */
868 cp = &first_http_ctx;
869 while ((*cp) != NULL) {
877 /* remove references, if any (XXX: do it faster) */
878 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
883 /* remove connection associated resources */
887 /* close each frame parser */
888 for(i=0;i<c->fmt_in->nb_streams;i++) {
889 st = c->fmt_in->streams[i];
890 if (st->codec->codec)
891 avcodec_close(st->codec);
893 avformat_close_input(&c->fmt_in);
896 /* free RTP output streams if any */
899 nb_streams = c->stream->nb_streams;
901 for(i=0;i<nb_streams;i++) {
904 av_write_trailer(ctx);
905 av_dict_free(&ctx->metadata);
906 av_free(ctx->streams[0]);
909 h = c->rtp_handles[i];
916 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
919 if (avio_open_dyn_buf(&ctx->pb) >= 0) {
920 av_write_trailer(ctx);
921 av_freep(&c->pb_buffer);
922 avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
927 for(i=0; i<ctx->nb_streams; i++)
928 av_free(ctx->streams[i]);
929 av_freep(&ctx->streams);
930 av_freep(&ctx->priv_data);
932 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
933 current_bandwidth -= c->stream->bandwidth;
935 /* signal that there is no feed if we are the feeder socket */
936 if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
937 c->stream->feed_opened = 0;
941 av_freep(&c->pb_buffer);
942 av_freep(&c->packet_buffer);
948 static int handle_connection(HTTPContext *c)
953 case HTTPSTATE_WAIT_REQUEST:
954 case RTSPSTATE_WAIT_REQUEST:
956 if ((c->timeout - cur_time) < 0)
958 if (c->poll_entry->revents & (POLLERR | POLLHUP))
961 /* no need to read if no events */
962 if (!(c->poll_entry->revents & POLLIN))
966 len = recv(c->fd, c->buffer_ptr, 1, 0);
968 if (ff_neterrno() != AVERROR(EAGAIN) &&
969 ff_neterrno() != AVERROR(EINTR))
971 } else if (len == 0) {
974 /* search for end of request. */
976 c->buffer_ptr += len;
978 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
979 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
980 /* request found : parse it and reply */
981 if (c->state == HTTPSTATE_WAIT_REQUEST) {
982 ret = http_parse_request(c);
984 ret = rtsp_parse_request(c);
988 } else if (ptr >= c->buffer_end) {
989 /* request too long: cannot do anything */
991 } else goto read_loop;
995 case HTTPSTATE_SEND_HEADER:
996 if (c->poll_entry->revents & (POLLERR | POLLHUP))
999 /* no need to write if no events */
1000 if (!(c->poll_entry->revents & POLLOUT))
1002 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1004 if (ff_neterrno() != AVERROR(EAGAIN) &&
1005 ff_neterrno() != AVERROR(EINTR)) {
1006 goto close_connection;
1009 c->buffer_ptr += len;
1011 c->stream->bytes_served += len;
1012 c->data_count += len;
1013 if (c->buffer_ptr >= c->buffer_end) {
1014 av_freep(&c->pb_buffer);
1015 /* if error, exit */
1018 /* all the buffer was sent : synchronize to the incoming
1020 c->state = HTTPSTATE_SEND_DATA_HEADER;
1021 c->buffer_ptr = c->buffer_end = c->buffer;
1026 case HTTPSTATE_SEND_DATA:
1027 case HTTPSTATE_SEND_DATA_HEADER:
1028 case HTTPSTATE_SEND_DATA_TRAILER:
1029 /* for packetized output, we consider we can always write (the
1030 input streams set the speed). It may be better to verify
1031 that we do not rely too much on the kernel queues */
1032 if (!c->is_packetized) {
1033 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1036 /* no need to read if no events */
1037 if (!(c->poll_entry->revents & POLLOUT))
1040 if (http_send_data(c) < 0)
1042 /* close connection if trailer sent */
1043 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
1046 case HTTPSTATE_RECEIVE_DATA:
1047 /* no need to read if no events */
1048 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1050 if (!(c->poll_entry->revents & POLLIN))
1052 if (http_receive_data(c) < 0)
1055 case HTTPSTATE_WAIT_FEED:
1056 /* no need to read if no events */
1057 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
1060 /* nothing to do, we'll be waken up by incoming feed packets */
1063 case RTSPSTATE_SEND_REPLY:
1064 if (c->poll_entry->revents & (POLLERR | POLLHUP))
1065 goto close_connection;
1066 /* no need to write if no events */
1067 if (!(c->poll_entry->revents & POLLOUT))
1069 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
1071 if (ff_neterrno() != AVERROR(EAGAIN) &&
1072 ff_neterrno() != AVERROR(EINTR)) {
1073 goto close_connection;
1076 c->buffer_ptr += len;
1077 c->data_count += len;
1078 if (c->buffer_ptr >= c->buffer_end) {
1079 /* all the buffer was sent : wait for a new request */
1080 av_freep(&c->pb_buffer);
1081 start_wait_request(c, 1);
1085 case RTSPSTATE_SEND_PACKET:
1086 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
1087 av_freep(&c->packet_buffer);
1090 /* no need to write if no events */
1091 if (!(c->poll_entry->revents & POLLOUT))
1093 len = send(c->fd, c->packet_buffer_ptr,
1094 c->packet_buffer_end - c->packet_buffer_ptr, 0);
1096 if (ff_neterrno() != AVERROR(EAGAIN) &&
1097 ff_neterrno() != AVERROR(EINTR)) {
1098 /* error : close connection */
1099 av_freep(&c->packet_buffer);
1103 c->packet_buffer_ptr += len;
1104 if (c->packet_buffer_ptr >= c->packet_buffer_end) {
1105 /* all the buffer was sent : wait for a new request */
1106 av_freep(&c->packet_buffer);
1107 c->state = RTSPSTATE_WAIT_REQUEST;
1111 case HTTPSTATE_READY:
1120 av_freep(&c->pb_buffer);
1124 static int extract_rates(char *rates, int ratelen, const char *request)
1128 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1129 if (av_strncasecmp(p, "Pragma:", 7) == 0) {
1130 const char *q = p + 7;
1132 while (*q && *q != '\n' && av_isspace(*q))
1135 if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1141 memset(rates, 0xff, ratelen);
1144 while (*q && *q != '\n' && *q != ':')
1147 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
1151 if (stream_no < ratelen && stream_no >= 0)
1152 rates[stream_no] = rate_no;
1154 while (*q && *q != '\n' && !av_isspace(*q))
1161 p = strchr(p, '\n');
1171 static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
1174 int best_bitrate = 100000000;
1177 for (i = 0; i < feed->nb_streams; i++) {
1178 AVCodecContext *feed_codec = feed->streams[i]->codec;
1180 if (feed_codec->codec_id != codec->codec_id ||
1181 feed_codec->sample_rate != codec->sample_rate ||
1182 feed_codec->width != codec->width ||
1183 feed_codec->height != codec->height)
1186 /* Potential stream */
1188 /* We want the fastest stream less than bit_rate, or the slowest
1189 * faster than bit_rate
1192 if (feed_codec->bit_rate <= bit_rate) {
1193 if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) {
1194 best_bitrate = feed_codec->bit_rate;
1198 if (feed_codec->bit_rate < best_bitrate) {
1199 best_bitrate = feed_codec->bit_rate;
1208 static int modify_current_stream(HTTPContext *c, char *rates)
1211 FFStream *req = c->stream;
1212 int action_required = 0;
1214 /* Not much we can do for a feed */
1218 for (i = 0; i < req->nb_streams; i++) {
1219 AVCodecContext *codec = req->streams[i]->codec;
1223 c->switch_feed_streams[i] = req->feed_streams[i];
1226 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
1229 /* Wants off or slow */
1230 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1232 /* This doesn't work well when it turns off the only stream! */
1233 c->switch_feed_streams[i] = -2;
1234 c->feed_streams[i] = -2;
1239 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1240 action_required = 1;
1243 return action_required;
1246 /* XXX: factorize in utils.c ? */
1247 /* XXX: take care with different space meaning */
1248 static void skip_spaces(const char **pp)
1252 while (*p == ' ' || *p == '\t')
1257 static void get_word(char *buf, int buf_size, const char **pp)
1265 while (!av_isspace(*p) && *p != '\0') {
1266 if ((q - buf) < buf_size - 1)
1275 static void get_arg(char *buf, int buf_size, const char **pp)
1282 while (av_isspace(*p)) p++;
1285 if (*p == '\"' || *p == '\'')
1297 if ((q - buf) < buf_size - 1)
1302 if (quote && *p == quote)
1307 static void parse_acl_row(FFStream *stream, FFStream* feed, IPAddressACL *ext_acl,
1308 const char *p, const char *filename, int line_num)
1314 get_arg(arg, sizeof(arg), &p);
1315 if (av_strcasecmp(arg, "allow") == 0)
1316 acl.action = IP_ALLOW;
1317 else if (av_strcasecmp(arg, "deny") == 0)
1318 acl.action = IP_DENY;
1320 fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
1321 filename, line_num, arg);
1325 get_arg(arg, sizeof(arg), &p);
1327 if (resolve_host(&acl.first, arg) != 0) {
1328 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
1329 filename, line_num, arg);
1332 acl.last = acl.first;
1334 get_arg(arg, sizeof(arg), &p);
1337 if (resolve_host(&acl.last, arg) != 0) {
1338 fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
1339 filename, line_num, arg);
1345 IPAddressACL *nacl = av_mallocz(sizeof(*nacl));
1346 IPAddressACL **naclp = 0;
1352 naclp = &stream->acl;
1358 fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n",
1359 filename, line_num);
1365 naclp = &(*naclp)->next;
1373 static IPAddressACL* parse_dynamic_acl(FFStream *stream, HTTPContext *c)
1378 IPAddressACL *acl = NULL;
1382 f = fopen(stream->dynamic_acl, "r");
1384 perror(stream->dynamic_acl);
1388 acl = av_mallocz(sizeof(IPAddressACL));
1392 if (fgets(line, sizeof(line), f) == NULL)
1396 while (av_isspace(*p))
1398 if (*p == '\0' || *p == '#')
1400 get_arg(cmd, sizeof(cmd), &p);
1402 if (!av_strcasecmp(cmd, "ACL"))
1403 parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl, line_num);
1410 static void free_acl_list(IPAddressACL *in_acl)
1412 IPAddressACL *pacl,*pacl2;
1422 static int validate_acl_list(IPAddressACL *in_acl, HTTPContext *c)
1424 enum IPAddressAction last_action = IP_DENY;
1426 struct in_addr *src = &c->from_addr.sin_addr;
1427 unsigned long src_addr = src->s_addr;
1429 for (acl = in_acl; acl; acl = acl->next) {
1430 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
1431 return (acl->action == IP_ALLOW) ? 1 : 0;
1432 last_action = acl->action;
1435 /* Nothing matched, so return not the last action */
1436 return (last_action == IP_DENY) ? 1 : 0;
1439 static int validate_acl(FFStream *stream, HTTPContext *c)
1445 /* if stream->acl is null validate_acl_list will return 1 */
1446 ret = validate_acl_list(stream->acl, c);
1448 if (stream->dynamic_acl[0]) {
1449 acl = parse_dynamic_acl(stream, c);
1451 ret = validate_acl_list(acl, c);
1459 /* compute the real filename of a file by matching it without its
1460 extensions to all the stream's filenames */
1461 static void compute_real_filename(char *filename, int max_size)
1468 /* compute filename by matching without the file extensions */
1469 av_strlcpy(file1, filename, sizeof(file1));
1470 p = strrchr(file1, '.');
1473 for(stream = first_stream; stream != NULL; stream = stream->next) {
1474 av_strlcpy(file2, stream->filename, sizeof(file2));
1475 p = strrchr(file2, '.');
1478 if (!strcmp(file1, file2)) {
1479 av_strlcpy(filename, stream->filename, max_size);
1494 /* parse HTTP request and prepare header */
1495 static int http_parse_request(HTTPContext *c)
1499 enum RedirType redir_type;
1501 char info[1024], filename[1024];
1505 const char *mime_type;
1509 const char *useragent = 0;
1512 get_word(cmd, sizeof(cmd), &p);
1513 av_strlcpy(c->method, cmd, sizeof(c->method));
1515 if (!strcmp(cmd, "GET"))
1517 else if (!strcmp(cmd, "POST"))
1522 get_word(url, sizeof(url), &p);
1523 av_strlcpy(c->url, url, sizeof(c->url));
1525 get_word(protocol, sizeof(protocol), (const char **)&p);
1526 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1529 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
1532 http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);
1534 /* find the filename and the optional info string in the request */
1535 p1 = strchr(url, '?');
1537 av_strlcpy(info, p1, sizeof(info));
1542 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
1544 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1545 if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
1547 if (*useragent && *useragent != '\n' && av_isspace(*useragent))
1551 p = strchr(p, '\n');
1558 redir_type = REDIR_NONE;
1559 if (av_match_ext(filename, "asx")) {
1560 redir_type = REDIR_ASX;
1561 filename[strlen(filename)-1] = 'f';
1562 } else if (av_match_ext(filename, "asf") &&
1563 (!useragent || av_strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1564 /* if this isn't WMP or lookalike, return the redirector file */
1565 redir_type = REDIR_ASF;
1566 } else if (av_match_ext(filename, "rpm,ram")) {
1567 redir_type = REDIR_RAM;
1568 strcpy(filename + strlen(filename)-2, "m");
1569 } else if (av_match_ext(filename, "rtsp")) {
1570 redir_type = REDIR_RTSP;
1571 compute_real_filename(filename, sizeof(filename) - 1);
1572 } else if (av_match_ext(filename, "sdp")) {
1573 redir_type = REDIR_SDP;
1574 compute_real_filename(filename, sizeof(filename) - 1);
1577 // "redirect" / request to index.html
1578 if (!strlen(filename))
1579 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
1581 stream = first_stream;
1582 while (stream != NULL) {
1583 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
1585 stream = stream->next;
1587 if (stream == NULL) {
1588 snprintf(msg, sizeof(msg), "File '%s' not found", url);
1589 http_log("File '%s' not found\n", url);
1594 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1595 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1597 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1598 c->http_error = 301;
1600 snprintf(q, c->buffer_size,
1601 "HTTP/1.0 301 Moved\r\n"
1603 "Content-type: text/html\r\n"
1605 "<html><head><title>Moved</title></head><body>\r\n"
1606 "You should be <a href=\"%s\">redirected</a>.\r\n"
1607 "</body></html>\r\n", stream->feed_filename, stream->feed_filename);
1609 /* prepare output buffer */
1610 c->buffer_ptr = c->buffer;
1612 c->state = HTTPSTATE_SEND_HEADER;
1616 /* If this is WMP, get the rate information */
1617 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1618 if (modify_current_stream(c, ratebuf)) {
1619 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
1620 if (c->switch_feed_streams[i] >= 0)
1621 c->switch_feed_streams[i] = -1;
1626 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1627 current_bandwidth += stream->bandwidth;
1629 /* If already streaming this feed, do not let start another feeder. */
1630 if (stream->feed_opened) {
1631 snprintf(msg, sizeof(msg), "This feed is already being received.");
1632 http_log("Feed '%s' already being received\n", stream->feed_filename);
1636 if (c->post == 0 && max_bandwidth < current_bandwidth) {
1637 c->http_error = 503;
1639 snprintf(q, c->buffer_size,
1640 "HTTP/1.0 503 Server too busy\r\n"
1641 "Content-type: text/html\r\n"
1643 "<html><head><title>Too busy</title></head><body>\r\n"
1644 "<p>The server is too busy to serve your request at this time.</p>\r\n"
1645 "<p>The bandwidth being served (including your stream) is %"PRIu64"kbit/sec, "
1646 "and this exceeds the limit of %"PRIu64"kbit/sec.</p>\r\n"
1647 "</body></html>\r\n", current_bandwidth, max_bandwidth);
1649 /* prepare output buffer */
1650 c->buffer_ptr = c->buffer;
1652 c->state = HTTPSTATE_SEND_HEADER;
1656 if (redir_type != REDIR_NONE) {
1657 const char *hostinfo = 0;
1659 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1660 if (av_strncasecmp(p, "Host:", 5) == 0) {
1664 p = strchr(p, '\n');
1675 while (av_isspace(*hostinfo))
1678 eoh = strchr(hostinfo, '\n');
1680 if (eoh[-1] == '\r')
1683 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1684 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1685 hostbuf[eoh - hostinfo] = 0;
1687 c->http_error = 200;
1689 switch(redir_type) {
1691 snprintf(q, c->buffer_size,
1692 "HTTP/1.0 200 ASX Follows\r\n"
1693 "Content-type: video/x-ms-asf\r\n"
1695 "<ASX Version=\"3\">\r\n"
1696 //"<!-- Autogenerated by ffserver -->\r\n"
1697 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1698 "</ASX>\r\n", hostbuf, filename, info);
1702 snprintf(q, c->buffer_size,
1703 "HTTP/1.0 200 RAM Follows\r\n"
1704 "Content-type: audio/x-pn-realaudio\r\n"
1706 "# Autogenerated by ffserver\r\n"
1707 "http://%s/%s%s\r\n", hostbuf, filename, info);
1711 snprintf(q, c->buffer_size,
1712 "HTTP/1.0 200 ASF Redirect follows\r\n"
1713 "Content-type: video/x-ms-asf\r\n"
1716 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
1721 char hostname[256], *p;
1722 /* extract only hostname */
1723 av_strlcpy(hostname, hostbuf, sizeof(hostname));
1724 p = strrchr(hostname, ':');
1727 snprintf(q, c->buffer_size,
1728 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1729 /* XXX: incorrect mime type ? */
1730 "Content-type: application/x-rtsp\r\n"
1732 "rtsp://%s:%d/%s\r\n", hostname, ntohs(my_rtsp_addr.sin_port), filename);
1741 struct sockaddr_in my_addr;
1743 snprintf(q, c->buffer_size,
1744 "HTTP/1.0 200 OK\r\n"
1745 "Content-type: application/sdp\r\n"
1749 len = sizeof(my_addr);
1750 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
1752 /* XXX: should use a dynamic buffer */
1753 sdp_data_size = prepare_sdp_description(stream,
1756 if (sdp_data_size > 0) {
1757 memcpy(q, sdp_data, sdp_data_size);
1769 /* prepare output buffer */
1770 c->buffer_ptr = c->buffer;
1772 c->state = HTTPSTATE_SEND_HEADER;
1778 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
1782 stream->conns_served++;
1784 /* XXX: add there authenticate and IP match */
1787 /* if post, it means a feed is being sent */
1788 if (!stream->is_feed) {
1789 /* However it might be a status report from WMP! Let us log the
1790 * data as it might come in handy one day. */
1791 const char *logline = 0;
1794 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1795 if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1799 if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
1800 client_id = strtol(p + 18, 0, 10);
1801 p = strchr(p, '\n');
1809 char *eol = strchr(logline, '\n');
1814 if (eol[-1] == '\r')
1816 http_log("%.*s\n", (int) (eol - logline), logline);
1817 c->suppress_log = 1;
1822 http_log("\nGot request:\n%s\n", c->buffer);
1825 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1828 /* Now we have to find the client_id */
1829 for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
1830 if (wmpc->wmp_client_id == client_id)
1834 if (wmpc && modify_current_stream(wmpc, ratebuf))
1835 wmpc->switch_pending = 1;
1838 snprintf(msg, sizeof(msg), "POST command not handled");
1842 if (http_start_receive_data(c) < 0) {
1843 snprintf(msg, sizeof(msg), "could not open feed");
1847 c->state = HTTPSTATE_RECEIVE_DATA;
1852 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
1853 http_log("\nGot request:\n%s\n", c->buffer);
1856 if (c->stream->stream_type == STREAM_TYPE_STATUS)
1859 /* open input stream */
1860 if (open_input_stream(c, info) < 0) {
1861 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
1865 /* prepare HTTP header */
1867 av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
1868 mime_type = c->stream->fmt->mime_type;
1870 mime_type = "application/x-octet-stream";
1871 av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
1873 /* for asf, we need extra headers */
1874 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
1875 /* Need to allocate a client id */
1877 c->wmp_client_id = av_lfg_get(&random_state);
1879 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);
1881 av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
1882 av_strlcatf(c->buffer, c->buffer_size, "\r\n");
1883 q = c->buffer + strlen(c->buffer);
1885 /* prepare output buffer */
1887 c->buffer_ptr = c->buffer;
1889 c->state = HTTPSTATE_SEND_HEADER;
1892 c->http_error = 404;
1895 snprintf(q, c->buffer_size,
1896 "HTTP/1.0 404 Not Found\r\n"
1897 "Content-type: text/html\r\n"
1900 "<head><title>404 Not Found</title></head>\n"
1904 /* prepare output buffer */
1905 c->buffer_ptr = c->buffer;
1907 c->state = HTTPSTATE_SEND_HEADER;
1911 c->http_error = 200; /* horrible : we use this value to avoid
1912 going to the send data state */
1913 c->state = HTTPSTATE_SEND_HEADER;
1917 static void fmt_bytecount(AVIOContext *pb, int64_t count)
1919 static const char suffix[] = " kMGTP";
1922 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
1924 avio_printf(pb, "%"PRId64"%c", count, *s);
1927 static void compute_status(HTTPContext *c)
1936 if (avio_open_dyn_buf(&pb) < 0) {
1937 /* XXX: return an error ? */
1938 c->buffer_ptr = c->buffer;
1939 c->buffer_end = c->buffer;
1943 avio_printf(pb, "HTTP/1.0 200 OK\r\n");
1944 avio_printf(pb, "Content-type: text/html\r\n");
1945 avio_printf(pb, "Pragma: no-cache\r\n");
1946 avio_printf(pb, "\r\n");
1948 avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
1949 if (c->stream->feed_filename[0])
1950 avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
1951 avio_printf(pb, "</head>\n<body>");
1952 avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
1954 avio_printf(pb, "<h2>Available Streams</h2>\n");
1955 avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
1956 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");
1957 stream = first_stream;
1958 while (stream != NULL) {
1959 char sfilename[1024];
1962 if (stream->feed != stream) {
1963 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
1964 eosf = sfilename + strlen(sfilename);
1965 if (eosf - sfilename >= 4) {
1966 if (strcmp(eosf - 4, ".asf") == 0)
1967 strcpy(eosf - 4, ".asx");
1968 else if (strcmp(eosf - 3, ".rm") == 0)
1969 strcpy(eosf - 3, ".ram");
1970 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
1971 /* generate a sample RTSP director if
1972 unicast. Generate an SDP redirector if
1974 eosf = strrchr(sfilename, '.');
1976 eosf = sfilename + strlen(sfilename);
1977 if (stream->is_multicast)
1978 strcpy(eosf, ".sdp");
1980 strcpy(eosf, ".rtsp");
1984 avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
1985 sfilename, stream->filename);
1986 avio_printf(pb, "<td align=right> %d <td align=right> ",
1987 stream->conns_served);
1988 fmt_bytecount(pb, stream->bytes_served);
1989 switch(stream->stream_type) {
1990 case STREAM_TYPE_LIVE: {
1991 int audio_bit_rate = 0;
1992 int video_bit_rate = 0;
1993 const char *audio_codec_name = "";
1994 const char *video_codec_name = "";
1995 const char *audio_codec_name_extra = "";
1996 const char *video_codec_name_extra = "";
1998 for(i=0;i<stream->nb_streams;i++) {
1999 AVStream *st = stream->streams[i];
2000 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
2001 switch(st->codec->codec_type) {
2002 case AVMEDIA_TYPE_AUDIO:
2003 audio_bit_rate += st->codec->bit_rate;
2005 if (*audio_codec_name)
2006 audio_codec_name_extra = "...";
2007 audio_codec_name = codec->name;
2010 case AVMEDIA_TYPE_VIDEO:
2011 video_bit_rate += st->codec->bit_rate;
2013 if (*video_codec_name)
2014 video_codec_name_extra = "...";
2015 video_codec_name = codec->name;
2018 case AVMEDIA_TYPE_DATA:
2019 video_bit_rate += st->codec->bit_rate;
2025 avio_printf(pb, "<td align=center> %s <td align=right> %d <td align=right> %d <td> %s %s <td align=right> %d <td> %s %s",
2028 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
2029 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
2031 avio_printf(pb, "<td>%s", stream->feed->filename);
2033 avio_printf(pb, "<td>%s", stream->feed_filename);
2034 avio_printf(pb, "\n");
2038 avio_printf(pb, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
2042 stream = stream->next;
2044 avio_printf(pb, "</table>\n");
2046 stream = first_stream;
2047 while (stream != NULL) {
2048 if (stream->feed == stream) {
2049 avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
2051 avio_printf(pb, "Running as pid %d.\n", stream->pid);
2058 /* This is somewhat linux specific I guess */
2059 snprintf(ps_cmd, sizeof(ps_cmd),
2060 "ps -o \"%%cpu,cputime\" --no-headers %d",
2063 pid_stat = popen(ps_cmd, "r");
2068 if (fscanf(pid_stat, "%9s %63s", cpuperc,
2070 avio_printf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
2078 avio_printf(pb, "<p>");
2080 avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>type<th>kbits/s<th align=left>codec<th align=left>Parameters\n");
2082 for (i = 0; i < stream->nb_streams; i++) {
2083 AVStream *st = stream->streams[i];
2084 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
2085 const char *type = "unknown";
2086 char parameters[64];
2090 switch(st->codec->codec_type) {
2091 case AVMEDIA_TYPE_AUDIO:
2093 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz", st->codec->channels, st->codec->sample_rate);
2095 case AVMEDIA_TYPE_VIDEO:
2097 snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec->width, st->codec->height,
2098 st->codec->qmin, st->codec->qmax, st->codec->time_base.den / st->codec->time_base.num);
2103 avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
2104 i, type, st->codec->bit_rate/1000, codec ? codec->name : "", parameters);
2106 avio_printf(pb, "</table>\n");
2109 stream = stream->next;
2112 /* connection status */
2113 avio_printf(pb, "<h2>Connection Status</h2>\n");
2115 avio_printf(pb, "Number of connections: %d / %d<br>\n",
2116 nb_connections, nb_max_connections);
2118 avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
2119 current_bandwidth, max_bandwidth);
2121 avio_printf(pb, "<table>\n");
2122 avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
2123 c1 = first_http_ctx;
2125 while (c1 != NULL) {
2131 for (j = 0; j < c1->stream->nb_streams; j++) {
2132 if (!c1->stream->feed)
2133 bitrate += c1->stream->streams[j]->codec->bit_rate;
2134 else if (c1->feed_streams[j] >= 0)
2135 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
2140 p = inet_ntoa(c1->from_addr.sin_addr);
2141 avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
2143 c1->stream ? c1->stream->filename : "",
2144 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
2147 http_state[c1->state]);
2148 fmt_bytecount(pb, bitrate);
2149 avio_printf(pb, "<td align=right>");
2150 fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
2151 avio_printf(pb, "<td align=right>");
2152 fmt_bytecount(pb, c1->data_count);
2153 avio_printf(pb, "\n");
2156 avio_printf(pb, "</table>\n");
2161 avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
2162 avio_printf(pb, "</body>\n</html>\n");
2164 len = avio_close_dyn_buf(pb, &c->pb_buffer);
2165 c->buffer_ptr = c->pb_buffer;
2166 c->buffer_end = c->pb_buffer + len;
2169 static int open_input_stream(HTTPContext *c, const char *info)
2172 char input_filename[1024];
2173 AVFormatContext *s = NULL;
2174 int buf_size, i, ret;
2177 /* find file name */
2178 if (c->stream->feed) {
2179 strcpy(input_filename, c->stream->feed->feed_filename);
2180 buf_size = FFM_PACKET_SIZE;
2181 /* compute position (absolute time) */
2182 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2183 if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
2184 http_log("Invalid date specification '%s' for stream\n", buf);
2187 } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
2188 int prebuffer = strtol(buf, 0, 10);
2189 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
2191 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
2193 strcpy(input_filename, c->stream->feed_filename);
2195 /* compute position (relative time) */
2196 if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
2197 if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
2198 http_log("Invalid date specification '%s' for stream\n", buf);
2204 if (!input_filename[0]) {
2205 http_log("No filename was specified for stream\n");
2206 return AVERROR(EINVAL);
2210 if ((ret = avformat_open_input(&s, input_filename, c->stream->ifmt, &c->stream->in_opts)) < 0) {
2211 http_log("Could not open input '%s': %s\n", input_filename, av_err2str(ret));
2215 /* set buffer size */
2216 if (buf_size > 0) ffio_set_buf_size(s->pb, buf_size);
2218 s->flags |= AVFMT_FLAG_GENPTS;
2220 if (strcmp(s->iformat->name, "ffm") &&
2221 (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
2222 http_log("Could not find stream info for input '%s'\n", input_filename);
2223 avformat_close_input(&s);
2227 /* choose stream as clock source (we favor the video stream if
2228 * present) for packet sending */
2229 c->pts_stream_index = 0;
2230 for(i=0;i<c->stream->nb_streams;i++) {
2231 if (c->pts_stream_index == 0 &&
2232 c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2233 c->pts_stream_index = i;
2237 if (c->fmt_in->iformat->read_seek)
2238 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
2239 /* set the start time (needed for maxtime and RTP packet timing) */
2240 c->start_time = cur_time;
2241 c->first_pts = AV_NOPTS_VALUE;
2245 /* return the server clock (in us) */
2246 static int64_t get_server_clock(HTTPContext *c)
2248 /* compute current pts value from system time */
2249 return (cur_time - c->start_time) * 1000;
2252 /* return the estimated time at which the current packet must be sent
2254 static int64_t get_packet_send_clock(HTTPContext *c)
2256 int bytes_left, bytes_sent, frame_bytes;
2258 frame_bytes = c->cur_frame_bytes;
2259 if (frame_bytes <= 0)
2262 bytes_left = c->buffer_end - c->buffer_ptr;
2263 bytes_sent = frame_bytes - bytes_left;
2264 return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
2269 static int http_prepare_data(HTTPContext *c)
2272 AVFormatContext *ctx;
2274 av_freep(&c->pb_buffer);
2276 case HTTPSTATE_SEND_DATA_HEADER:
2277 ctx = avformat_alloc_context();
2280 av_dict_copy(&(c->fmt_ctx.metadata), c->stream->metadata, 0);
2281 c->fmt_ctx.streams = av_mallocz(sizeof(AVStream *) * c->stream->nb_streams);
2283 for(i=0;i<c->stream->nb_streams;i++) {
2285 c->fmt_ctx.streams[i] = av_mallocz(sizeof(AVStream));
2286 /* if file or feed, then just take streams from FFStream struct */
2287 if (!c->stream->feed ||
2288 c->stream->feed == c->stream)
2289 src = c->stream->streams[i];
2291 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2293 *(c->fmt_ctx.streams[i]) = *src;
2294 c->fmt_ctx.streams[i]->priv_data = 0;
2295 /* XXX: should be done in AVStream, not in codec */
2296 c->fmt_ctx.streams[i]->codec->frame_number = 0;
2298 /* set output format parameters */
2299 c->fmt_ctx.oformat = c->stream->fmt;
2300 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2302 c->got_key_frame = 0;
2304 /* prepare header and save header data in a stream */
2305 if (avio_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
2306 /* XXX: potential leak */
2309 c->fmt_ctx.pb->seekable = 0;
2312 * HACK to avoid mpeg ps muxer to spit many underflow errors
2313 * Default value from FFmpeg
2314 * Try to set it using configuration option
2316 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2318 if ((ret = avformat_write_header(&c->fmt_ctx, NULL)) < 0) {
2319 http_log("Error writing output header for stream '%s': %s\n",
2320 c->stream->filename, av_err2str(ret));
2323 av_dict_free(&c->fmt_ctx.metadata);
2325 len = avio_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2326 c->buffer_ptr = c->pb_buffer;
2327 c->buffer_end = c->pb_buffer + len;
2329 c->state = HTTPSTATE_SEND_DATA;
2330 c->last_packet_sent = 0;
2332 case HTTPSTATE_SEND_DATA:
2333 /* find a new packet */
2334 /* read a packet from the input stream */
2335 if (c->stream->feed)
2336 ffm_set_write_index(c->fmt_in,
2337 c->stream->feed->feed_write_index,
2338 c->stream->feed->feed_size);
2340 if (c->stream->max_time &&
2341 c->stream->max_time + c->start_time - cur_time < 0)
2342 /* We have timed out */
2343 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2347 ret = av_read_frame(c->fmt_in, &pkt);
2349 if (c->stream->feed) {
2350 /* if coming from feed, it means we reached the end of the
2351 ffm file, so must wait for more data */
2352 c->state = HTTPSTATE_WAIT_FEED;
2353 return 1; /* state changed */
2354 } else if (ret == AVERROR(EAGAIN)) {
2355 /* input not ready, come back later */
2358 if (c->stream->loop) {
2359 avformat_close_input(&c->fmt_in);
2360 if (open_input_stream(c, "") < 0)
2365 /* must send trailer now because EOF or error */
2366 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2370 int source_index = pkt.stream_index;
2371 /* update first pts if needed */
2372 if (c->first_pts == AV_NOPTS_VALUE) {
2373 c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
2374 c->start_time = cur_time;
2376 /* send it to the appropriate stream */
2377 if (c->stream->feed) {
2378 /* if coming from a feed, select the right stream */
2379 if (c->switch_pending) {
2380 c->switch_pending = 0;
2381 for(i=0;i<c->stream->nb_streams;i++) {
2382 if (c->switch_feed_streams[i] == pkt.stream_index)
2383 if (pkt.flags & AV_PKT_FLAG_KEY)
2384 c->switch_feed_streams[i] = -1;
2385 if (c->switch_feed_streams[i] >= 0)
2386 c->switch_pending = 1;
2389 for(i=0;i<c->stream->nb_streams;i++) {
2390 if (c->stream->feed_streams[i] == pkt.stream_index) {
2391 AVStream *st = c->fmt_in->streams[source_index];
2392 pkt.stream_index = i;
2393 if (pkt.flags & AV_PKT_FLAG_KEY &&
2394 (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2395 c->stream->nb_streams == 1))
2396 c->got_key_frame = 1;
2397 if (!c->stream->send_on_key || c->got_key_frame)
2402 AVCodecContext *codec;
2403 AVStream *ist, *ost;
2405 ist = c->fmt_in->streams[source_index];
2406 /* specific handling for RTP: we use several
2407 * output streams (one for each RTP connection).
2408 * XXX: need more abstract handling */
2409 if (c->is_packetized) {
2410 /* compute send time and duration */
2411 c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
2412 c->cur_pts -= c->first_pts;
2413 c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
2414 /* find RTP context */
2415 c->packet_stream_index = pkt.stream_index;
2416 ctx = c->rtp_ctx[c->packet_stream_index];
2418 av_free_packet(&pkt);
2421 codec = ctx->streams[0]->codec;
2422 /* only one stream per RTP connection */
2423 pkt.stream_index = 0;
2427 codec = ctx->streams[pkt.stream_index]->codec;
2430 if (c->is_packetized) {
2431 int max_packet_size;
2432 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
2433 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2435 max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
2436 ret = ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size);
2438 ret = avio_open_dyn_buf(&ctx->pb);
2441 /* XXX: potential leak */
2444 ost = ctx->streams[pkt.stream_index];
2446 ctx->pb->seekable = 0;
2447 if (pkt.dts != AV_NOPTS_VALUE)
2448 pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base);
2449 if (pkt.pts != AV_NOPTS_VALUE)
2450 pkt.pts = av_rescale_q(pkt.pts, ist->time_base, ost->time_base);
2451 pkt.duration = av_rescale_q(pkt.duration, ist->time_base, ost->time_base);
2452 if ((ret = av_write_frame(ctx, &pkt)) < 0) {
2453 http_log("Error writing frame to output for stream '%s': %s\n",
2454 c->stream->filename, av_err2str(ret));
2455 c->state = HTTPSTATE_SEND_DATA_TRAILER;
2458 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2459 c->cur_frame_bytes = len;
2460 c->buffer_ptr = c->pb_buffer;
2461 c->buffer_end = c->pb_buffer + len;
2463 codec->frame_number++;
2465 av_free_packet(&pkt);
2469 av_free_packet(&pkt);
2474 case HTTPSTATE_SEND_DATA_TRAILER:
2475 /* last packet test ? */
2476 if (c->last_packet_sent || c->is_packetized)
2479 /* prepare header */
2480 if (avio_open_dyn_buf(&ctx->pb) < 0) {
2481 /* XXX: potential leak */
2484 c->fmt_ctx.pb->seekable = 0;
2485 av_write_trailer(ctx);
2486 len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
2487 c->buffer_ptr = c->pb_buffer;
2488 c->buffer_end = c->pb_buffer + len;
2490 c->last_packet_sent = 1;
2496 /* should convert the format at the same time */
2497 /* send data starting at c->buffer_ptr to the output connection
2498 * (either UDP or TCP) */
2499 static int http_send_data(HTTPContext *c)
2504 if (c->buffer_ptr >= c->buffer_end) {
2505 ret = http_prepare_data(c);
2509 /* state change requested */
2512 if (c->is_packetized) {
2513 /* RTP data output */
2514 len = c->buffer_end - c->buffer_ptr;
2516 /* fail safe - should never happen */
2518 c->buffer_ptr = c->buffer_end;
2521 len = (c->buffer_ptr[0] << 24) |
2522 (c->buffer_ptr[1] << 16) |
2523 (c->buffer_ptr[2] << 8) |
2525 if (len > (c->buffer_end - c->buffer_ptr))
2527 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2528 /* nothing to send yet: we can wait */
2532 c->data_count += len;
2533 update_datarate(&c->datarate, c->data_count);
2535 c->stream->bytes_served += len;
2537 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
2538 /* RTP packets are sent inside the RTSP TCP connection */
2540 int interleaved_index, size;
2542 HTTPContext *rtsp_c;
2545 /* if no RTSP connection left, error */
2548 /* if already sending something, then wait. */
2549 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
2551 if (avio_open_dyn_buf(&pb) < 0)
2553 interleaved_index = c->packet_stream_index * 2;
2554 /* RTCP packets are sent at odd indexes */
2555 if (c->buffer_ptr[1] == 200)
2556 interleaved_index++;
2557 /* write RTSP TCP header */
2559 header[1] = interleaved_index;
2560 header[2] = len >> 8;
2562 avio_write(pb, header, 4);
2563 /* write RTP packet data */
2565 avio_write(pb, c->buffer_ptr, len);
2566 size = avio_close_dyn_buf(pb, &c->packet_buffer);
2567 /* prepare asynchronous TCP sending */
2568 rtsp_c->packet_buffer_ptr = c->packet_buffer;
2569 rtsp_c->packet_buffer_end = c->packet_buffer + size;
2570 c->buffer_ptr += len;
2572 /* send everything we can NOW */
2573 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2574 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
2576 rtsp_c->packet_buffer_ptr += len;
2577 if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
2578 /* if we could not send all the data, we will
2579 send it later, so a new state is needed to
2580 "lock" the RTSP TCP connection */
2581 rtsp_c->state = RTSPSTATE_SEND_PACKET;
2584 /* all data has been sent */
2585 av_freep(&c->packet_buffer);
2587 /* send RTP packet directly in UDP */
2589 ffurl_write(c->rtp_handles[c->packet_stream_index],
2590 c->buffer_ptr, len);
2591 c->buffer_ptr += len;
2592 /* here we continue as we can send several packets per 10 ms slot */
2595 /* TCP data output */
2596 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
2598 if (ff_neterrno() != AVERROR(EAGAIN) &&
2599 ff_neterrno() != AVERROR(EINTR))
2600 /* error : close connection */
2605 c->buffer_ptr += len;
2607 c->data_count += len;
2608 update_datarate(&c->datarate, c->data_count);
2610 c->stream->bytes_served += len;
2618 static int http_start_receive_data(HTTPContext *c)
2623 if (c->stream->feed_opened) {
2624 http_log("Stream feed '%s' was not opened\n", c->stream->feed_filename);
2625 return AVERROR(EINVAL);
2628 /* Don't permit writing to this one */
2629 if (c->stream->readonly) {
2630 http_log("Cannot write to read-only file '%s'\n", 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 ret = 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 = ret;
2665 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
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 */
2711 if (c->buffer_end > c->buffer_ptr) {
2712 len = recv(c->fd, c->buffer_ptr,
2713 FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
2715 if (ff_neterrno() != AVERROR(EAGAIN) &&
2716 ff_neterrno() != AVERROR(EINTR))
2717 /* error : close connection */
2719 } else if (len == 0)
2720 /* end of connection : close it */
2723 c->chunk_size -= len;
2724 c->buffer_ptr += len;
2725 c->data_count += len;
2726 update_datarate(&c->datarate, c->data_count);
2730 if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
2731 if (c->buffer[0] != 'f' ||
2732 c->buffer[1] != 'm') {
2733 http_log("Feed stream has become desynchronized -- disconnecting\n");
2738 if (c->buffer_ptr >= c->buffer_end) {
2739 FFStream *feed = c->stream;
2740 /* a packet has been received : write it in the store, except
2742 if (c->data_count > FFM_PACKET_SIZE) {
2743 /* XXX: use llseek or url_seek */
2744 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
2745 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2746 http_log("Error writing to feed file: %s\n", strerror(errno));
2750 feed->feed_write_index += FFM_PACKET_SIZE;
2751 /* update file size */
2752 if (feed->feed_write_index > c->stream->feed_size)
2753 feed->feed_size = feed->feed_write_index;
2755 /* handle wrap around if max file size reached */
2756 if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size)
2757 feed->feed_write_index = FFM_PACKET_SIZE;
2760 if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
2761 http_log("Error writing index to feed file: %s\n", strerror(errno));
2765 /* wake up any waiting connections */
2766 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2767 if (c1->state == HTTPSTATE_WAIT_FEED &&
2768 c1->stream->feed == c->stream->feed)
2769 c1->state = HTTPSTATE_SEND_DATA;
2772 /* We have a header in our hands that contains useful data */
2773 AVFormatContext *s = avformat_alloc_context();
2775 AVInputFormat *fmt_in;
2781 /* use feed output format name to find corresponding input format */
2782 fmt_in = av_find_input_format(feed->fmt->name);
2786 pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
2787 0, NULL, NULL, NULL, NULL);
2791 if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
2796 /* Now we have the actual streams */
2797 if (s->nb_streams != feed->nb_streams) {
2798 avformat_close_input(&s);
2800 http_log("Feed '%s' stream number does not match registered feed\n",
2801 c->stream->feed_filename);
2805 for (i = 0; i < s->nb_streams; i++) {
2806 AVStream *fst = feed->streams[i];
2807 AVStream *st = s->streams[i];
2808 avcodec_copy_context(fst->codec, st->codec);
2811 avformat_close_input(&s);
2814 c->buffer_ptr = c->buffer;
2819 c->stream->feed_opened = 0;
2821 /* wake up any waiting connections to stop waiting for feed */
2822 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
2823 if (c1->state == HTTPSTATE_WAIT_FEED &&
2824 c1->stream->feed == c->stream->feed)
2825 c1->state = HTTPSTATE_SEND_DATA_TRAILER;
2830 /********************************************************************/
2833 static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2840 switch(error_number) {
2841 case RTSP_STATUS_OK:
2844 case RTSP_STATUS_METHOD:
2845 str = "Method Not Allowed";
2847 case RTSP_STATUS_BANDWIDTH:
2848 str = "Not Enough Bandwidth";
2850 case RTSP_STATUS_SESSION:
2851 str = "Session Not Found";
2853 case RTSP_STATUS_STATE:
2854 str = "Method Not Valid in This State";
2856 case RTSP_STATUS_AGGREGATE:
2857 str = "Aggregate operation not allowed";
2859 case RTSP_STATUS_ONLY_AGGREGATE:
2860 str = "Only aggregate operation allowed";
2862 case RTSP_STATUS_TRANSPORT:
2863 str = "Unsupported transport";
2865 case RTSP_STATUS_INTERNAL:
2866 str = "Internal Server Error";
2868 case RTSP_STATUS_SERVICE:
2869 str = "Service Unavailable";
2871 case RTSP_STATUS_VERSION:
2872 str = "RTSP Version not supported";
2875 str = "Unknown Error";
2879 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
2880 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
2882 /* output GMT time */
2885 strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
2886 avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
2889 static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2891 rtsp_reply_header(c, error_number);
2892 avio_printf(c->pb, "\r\n");
2895 static int rtsp_parse_request(HTTPContext *c)
2897 const char *p, *p1, *p2;
2903 RTSPMessageHeader header1 = { 0 }, *header = &header1;
2905 c->buffer_ptr[0] = '\0';
2908 get_word(cmd, sizeof(cmd), &p);
2909 get_word(url, sizeof(url), &p);
2910 get_word(protocol, sizeof(protocol), &p);
2912 av_strlcpy(c->method, cmd, sizeof(c->method));
2913 av_strlcpy(c->url, url, sizeof(c->url));
2914 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
2916 if (avio_open_dyn_buf(&c->pb) < 0) {
2917 /* XXX: cannot do more */
2918 c->pb = NULL; /* safety */
2922 /* check version name */
2923 if (strcmp(protocol, "RTSP/1.0") != 0) {
2924 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2928 /* parse each header line */
2929 /* skip to next line */
2930 while (*p != '\n' && *p != '\0')
2934 while (*p != '\0') {
2935 p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
2939 if (p2 > p && p2[-1] == '\r')
2941 /* skip empty line */
2945 if (len > sizeof(line) - 1)
2946 len = sizeof(line) - 1;
2947 memcpy(line, p, len);
2949 ff_rtsp_parse_line(header, line, NULL, NULL);
2953 /* handle sequence number */
2954 c->seq = header->seq;
2956 if (!strcmp(cmd, "DESCRIBE"))
2957 rtsp_cmd_describe(c, url);
2958 else if (!strcmp(cmd, "OPTIONS"))
2959 rtsp_cmd_options(c, url);
2960 else if (!strcmp(cmd, "SETUP"))
2961 rtsp_cmd_setup(c, url, header);
2962 else if (!strcmp(cmd, "PLAY"))
2963 rtsp_cmd_play(c, url, header);
2964 else if (!strcmp(cmd, "PAUSE"))
2965 rtsp_cmd_pause(c, url, header);
2966 else if (!strcmp(cmd, "TEARDOWN"))
2967 rtsp_cmd_teardown(c, url, header);
2969 rtsp_reply_error(c, RTSP_STATUS_METHOD);
2972 len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
2973 c->pb = NULL; /* safety */
2975 /* XXX: cannot do more */
2978 c->buffer_ptr = c->pb_buffer;
2979 c->buffer_end = c->pb_buffer + len;
2980 c->state = RTSPSTATE_SEND_REPLY;
2984 static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
2985 struct in_addr my_ip)
2987 AVFormatContext *avc;
2988 AVStream *avs = NULL;
2989 AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
2990 AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
2993 avc = avformat_alloc_context();
2994 if (avc == NULL || !rtp_format) {
2997 avc->oformat = rtp_format;
2998 av_dict_set(&avc->metadata, "title",
2999 entry ? entry->value : "No Title", 0);
3000 avc->nb_streams = stream->nb_streams;
3001 if (stream->is_multicast) {
3002 snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
3003 inet_ntoa(stream->multicast_ip),
3004 stream->multicast_port, stream->multicast_ttl);
3006 snprintf(avc->filename, 1024, "rtp://0.0.0.0");
3009 if (avc->nb_streams >= INT_MAX/sizeof(*avc->streams) ||
3010 !(avc->streams = av_malloc(avc->nb_streams * sizeof(*avc->streams))))
3012 if (avc->nb_streams >= INT_MAX/sizeof(*avs) ||
3013 !(avs = av_malloc(avc->nb_streams * sizeof(*avs))))
3016 for(i = 0; i < stream->nb_streams; i++) {
3017 avc->streams[i] = &avs[i];
3018 avc->streams[i]->codec = stream->streams[i]->codec;
3020 *pbuffer = av_mallocz(2048);
3021 av_sdp_create(&avc, 1, *pbuffer, 2048);
3024 av_free(avc->streams);
3025 av_dict_free(&avc->metadata);
3029 return strlen(*pbuffer);
3032 static void rtsp_cmd_options(HTTPContext *c, const char *url)
3034 // rtsp_reply_header(c, RTSP_STATUS_OK);
3035 avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
3036 avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
3037 avio_printf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
3038 avio_printf(c->pb, "\r\n");
3041 static void rtsp_cmd_describe(HTTPContext *c, const char *url)
3049 struct sockaddr_in my_addr;
3051 /* find which url is asked */
3052 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3057 for(stream = first_stream; stream != NULL; stream = stream->next) {
3058 if (!stream->is_feed &&
3059 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
3060 !strcmp(path, stream->filename)) {
3064 /* no stream found */
3065 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3069 /* prepare the media description in sdp format */
3071 /* get the host IP */
3072 len = sizeof(my_addr);
3073 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
3074 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
3075 if (content_length < 0) {
3076 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3079 rtsp_reply_header(c, RTSP_STATUS_OK);
3080 avio_printf(c->pb, "Content-Base: %s/\r\n", url);
3081 avio_printf(c->pb, "Content-Type: application/sdp\r\n");
3082 avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
3083 avio_printf(c->pb, "\r\n");
3084 avio_write(c->pb, content, content_length);
3088 static HTTPContext *find_rtp_session(const char *session_id)
3092 if (session_id[0] == '\0')
3095 for(c = first_http_ctx; c != NULL; c = c->next) {
3096 if (!strcmp(c->session_id, session_id))
3102 static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
3104 RTSPTransportField *th;
3107 for(i=0;i<h->nb_transports;i++) {
3108 th = &h->transports[i];
3109 if (th->lower_transport == lower_transport)
3115 static void rtsp_cmd_setup(HTTPContext *c, const char *url,
3116 RTSPMessageHeader *h)
3119 int stream_index, rtp_port, rtcp_port;
3124 RTSPTransportField *th;
3125 struct sockaddr_in dest_addr;
3126 RTSPActionServerSetup setup;
3128 /* find which url is asked */
3129 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3134 /* now check each stream */
3135 for(stream = first_stream; stream != NULL; stream = stream->next) {
3136 if (!stream->is_feed &&
3137 stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
3138 /* accept aggregate filenames only if single stream */
3139 if (!strcmp(path, stream->filename)) {
3140 if (stream->nb_streams != 1) {
3141 rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
3148 for(stream_index = 0; stream_index < stream->nb_streams;
3150 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3151 stream->filename, stream_index);
3152 if (!strcmp(path, buf))
3157 /* no stream found */
3158 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
3162 /* generate session id if needed */
3163 if (h->session_id[0] == '\0') {
3164 unsigned random0 = av_lfg_get(&random_state);
3165 unsigned random1 = av_lfg_get(&random_state);
3166 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
3170 /* find rtp session, and create it if none found */
3171 rtp_c = find_rtp_session(h->session_id);
3173 /* always prefer UDP */
3174 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
3176 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
3178 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3183 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
3184 th->lower_transport);
3186 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
3190 /* open input stream */
3191 if (open_input_stream(rtp_c, "") < 0) {
3192 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
3197 /* test if stream is OK (test needed because several SETUP needs
3198 to be done for a given file) */
3199 if (rtp_c->stream != stream) {
3200 rtsp_reply_error(c, RTSP_STATUS_SERVICE);
3204 /* test if stream is already set up */
3205 if (rtp_c->rtp_ctx[stream_index]) {
3206 rtsp_reply_error(c, RTSP_STATUS_STATE);
3210 /* check transport */
3211 th = find_transport(h, rtp_c->rtp_protocol);
3212 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
3213 th->client_port_min <= 0)) {
3214 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3218 /* setup default options */
3219 setup.transport_option[0] = '\0';
3220 dest_addr = rtp_c->from_addr;
3221 dest_addr.sin_port = htons(th->client_port_min);
3224 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
3225 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
3229 /* now everything is OK, so we can send the connection parameters */
3230 rtsp_reply_header(c, RTSP_STATUS_OK);
3232 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3234 switch(rtp_c->rtp_protocol) {
3235 case RTSP_LOWER_TRANSPORT_UDP:
3236 rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
3237 rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
3238 avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
3239 "client_port=%d-%d;server_port=%d-%d",
3240 th->client_port_min, th->client_port_max,
3241 rtp_port, rtcp_port);
3243 case RTSP_LOWER_TRANSPORT_TCP:
3244 avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
3245 stream_index * 2, stream_index * 2 + 1);
3250 if (setup.transport_option[0] != '\0')
3251 avio_printf(c->pb, ";%s", setup.transport_option);
3252 avio_printf(c->pb, "\r\n");
3255 avio_printf(c->pb, "\r\n");
3259 /* find an rtp connection by using the session ID. Check consistency
3261 static HTTPContext *find_rtp_session_with_url(const char *url,
3262 const char *session_id)
3270 rtp_c = find_rtp_session(session_id);
3274 /* find which url is asked */
3275 av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
3279 if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
3280 for(s=0; s<rtp_c->stream->nb_streams; ++s) {
3281 snprintf(buf, sizeof(buf), "%s/streamid=%d",
3282 rtp_c->stream->filename, s);
3283 if(!strncmp(path, buf, sizeof(buf))) {
3284 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
3289 if (len > 0 && path[len - 1] == '/' &&
3290 !strncmp(path, rtp_c->stream->filename, len - 1))
3295 static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3299 rtp_c = find_rtp_session_with_url(url, h->session_id);
3301 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3305 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3306 rtp_c->state != HTTPSTATE_WAIT_FEED &&
3307 rtp_c->state != HTTPSTATE_READY) {
3308 rtsp_reply_error(c, RTSP_STATUS_STATE);
3312 rtp_c->state = HTTPSTATE_SEND_DATA;
3314 /* now everything is OK, so we can send the connection parameters */
3315 rtsp_reply_header(c, RTSP_STATUS_OK);
3317 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3318 avio_printf(c->pb, "\r\n");
3321 static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3325 rtp_c = find_rtp_session_with_url(url, h->session_id);
3327 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3331 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3332 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3333 rtsp_reply_error(c, RTSP_STATUS_STATE);
3337 rtp_c->state = HTTPSTATE_READY;
3338 rtp_c->first_pts = AV_NOPTS_VALUE;
3339 /* now everything is OK, so we can send the connection parameters */
3340 rtsp_reply_header(c, RTSP_STATUS_OK);
3342 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3343 avio_printf(c->pb, "\r\n");
3346 static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h)
3350 rtp_c = find_rtp_session_with_url(url, h->session_id);
3352 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3356 /* now everything is OK, so we can send the connection parameters */
3357 rtsp_reply_header(c, RTSP_STATUS_OK);
3359 avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3360 avio_printf(c->pb, "\r\n");
3362 /* abort the session */
3363 close_connection(rtp_c);
3367 /********************************************************************/
3370 static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
3371 FFStream *stream, const char *session_id,
3372 enum RTSPLowerTransport rtp_protocol)
3374 HTTPContext *c = NULL;
3375 const char *proto_str;
3377 /* XXX: should output a warning page when coming
3378 close to the connection limit */
3379 if (nb_connections >= nb_max_connections)
3382 /* add a new connection */
3383 c = av_mallocz(sizeof(HTTPContext));
3388 c->poll_entry = NULL;
3389 c->from_addr = *from_addr;
3390 c->buffer_size = IOBUFFER_INIT_SIZE;
3391 c->buffer = av_malloc(c->buffer_size);
3396 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
3397 c->state = HTTPSTATE_READY;
3398 c->is_packetized = 1;
3399 c->rtp_protocol = rtp_protocol;
3401 /* protocol is shown in statistics */
3402 switch(c->rtp_protocol) {
3403 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3404 proto_str = "MCAST";
3406 case RTSP_LOWER_TRANSPORT_UDP:
3409 case RTSP_LOWER_TRANSPORT_TCP:
3416 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3417 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
3419 current_bandwidth += stream->bandwidth;
3421 c->next = first_http_ctx;
3433 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3434 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3436 static int rtp_new_av_stream(HTTPContext *c,
3437 int stream_index, struct sockaddr_in *dest_addr,
3438 HTTPContext *rtsp_c)
3440 AVFormatContext *ctx;
3443 URLContext *h = NULL;
3445 int max_packet_size;
3447 /* now we can open the relevant output stream */
3448 ctx = avformat_alloc_context();
3451 ctx->oformat = av_guess_format("rtp", NULL, NULL);
3453 st = av_mallocz(sizeof(AVStream));
3456 ctx->nb_streams = 1;
3457 ctx->streams = av_mallocz(sizeof(AVStream *) * ctx->nb_streams);
3460 ctx->streams[0] = st;
3462 if (!c->stream->feed ||
3463 c->stream->feed == c->stream)
3464 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
3467 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3469 st->priv_data = NULL;
3471 /* build destination RTP address */
3472 ipaddr = inet_ntoa(dest_addr->sin_addr);
3474 switch(c->rtp_protocol) {
3475 case RTSP_LOWER_TRANSPORT_UDP:
3476 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
3479 /* XXX: also pass as parameter to function ? */
3480 if (c->stream->is_multicast) {
3482 ttl = c->stream->multicast_ttl;
3485 snprintf(ctx->filename, sizeof(ctx->filename),
3486 "rtp://%s:%d?multicast=1&ttl=%d",
3487 ipaddr, ntohs(dest_addr->sin_port), ttl);
3489 snprintf(ctx->filename, sizeof(ctx->filename),
3490 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3493 if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
3495 c->rtp_handles[stream_index] = h;
3496 max_packet_size = h->max_packet_size;
3498 case RTSP_LOWER_TRANSPORT_TCP:
3501 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3507 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
3508 ipaddr, ntohs(dest_addr->sin_port),
3509 c->stream->filename, stream_index, c->protocol);
3511 /* normally, no packets should be output here, but the packet size may
3513 if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
3514 /* XXX: close stream */
3517 if (avformat_write_header(ctx, NULL) < 0) {
3524 avio_close_dyn_buf(ctx->pb, &dummy_buf);
3527 c->rtp_ctx[stream_index] = ctx;
3531 /********************************************************************/
3532 /* ffserver initialization */
3534 static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec, int copy)
3538 if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
3541 fst = av_mallocz(sizeof(AVStream));
3545 fst->codec = avcodec_alloc_context3(NULL);
3546 memcpy(fst->codec, codec, sizeof(AVCodecContext));
3547 if (codec->extradata_size) {
3548 fst->codec->extradata = av_mallocz(codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
3549 memcpy(fst->codec->extradata, codec->extradata,
3550 codec->extradata_size);
3553 /* live streams must use the actual feed's codec since it may be
3554 * updated later to carry extradata needed by them.
3558 fst->priv_data = av_mallocz(sizeof(FeedData));
3559 fst->index = stream->nb_streams;
3560 avpriv_set_pts_info(fst, 33, 1, 90000);
3561 fst->sample_aspect_ratio = codec->sample_aspect_ratio;
3562 stream->streams[stream->nb_streams++] = fst;
3566 /* return the stream number in the feed */
3567 static int add_av_stream(FFStream *feed, AVStream *st)
3570 AVCodecContext *av, *av1;
3574 for(i=0;i<feed->nb_streams;i++) {
3575 st = feed->streams[i];
3577 if (av1->codec_id == av->codec_id &&
3578 av1->codec_type == av->codec_type &&
3579 av1->bit_rate == av->bit_rate) {
3581 switch(av->codec_type) {
3582 case AVMEDIA_TYPE_AUDIO:
3583 if (av1->channels == av->channels &&
3584 av1->sample_rate == av->sample_rate)
3587 case AVMEDIA_TYPE_VIDEO:
3588 if (av1->width == av->width &&
3589 av1->height == av->height &&
3590 av1->time_base.den == av->time_base.den &&
3591 av1->time_base.num == av->time_base.num &&
3592 av1->gop_size == av->gop_size)
3601 fst = add_av_stream1(feed, av, 0);
3604 return feed->nb_streams - 1;
3607 static void remove_stream(FFStream *stream)
3611 while (*ps != NULL) {
3619 /* specific mpeg4 handling : we extract the raw parameters */
3620 static void extract_mpeg4_header(AVFormatContext *infile)
3622 int mpeg4_count, i, size;
3627 infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
3630 for(i=0;i<infile->nb_streams;i++) {
3631 st = infile->streams[i];
3632 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3633 st->codec->extradata_size == 0) {
3640 printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename);
3641 while (mpeg4_count > 0) {
3642 if (av_read_frame(infile, &pkt) < 0)
3644 st = infile->streams[pkt.stream_index];
3645 if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
3646 st->codec->extradata_size == 0) {
3647 av_freep(&st->codec->extradata);
3648 /* fill extradata with the header */
3649 /* XXX: we make hard suppositions here ! */
3651 while (p < pkt.data + pkt.size - 4) {
3652 /* stop when vop header is found */
3653 if (p[0] == 0x00 && p[1] == 0x00 &&
3654 p[2] == 0x01 && p[3] == 0xb6) {
3655 size = p - pkt.data;
3656 // av_hex_dump_log(infile, AV_LOG_DEBUG, pkt.data, size);
3657 st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
3658 st->codec->extradata_size = size;
3659 memcpy(st->codec->extradata, pkt.data, size);
3666 av_free_packet(&pkt);
3670 /* compute the needed AVStream for each file */
3671 static void build_file_streams(void)
3673 FFStream *stream, *stream_next;
3676 /* gather all streams */
3677 for(stream = first_stream; stream != NULL; stream = stream_next) {
3678 AVFormatContext *infile = NULL;
3679 stream_next = stream->next;
3680 if (stream->stream_type == STREAM_TYPE_LIVE &&
3682 /* the stream comes from a file */
3683 /* try to open the file */