2 * Multiple format streaming server
3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #ifndef HAVE_CLOSESOCKET
24 #define closesocket close
28 #include "libavutil/random.h"
29 #include "libavutil/avstring.h"
30 #include "libavformat/avformat.h"
31 #include "libavformat/network.h"
32 #include "libavformat/os_support.h"
33 #include "libavformat/rtp.h"
34 #include "libavformat/rtsp.h"
39 #include <sys/ioctl.h>
45 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
59 const char program_name
[] = "FFserver";
60 static const int program_birth_year
= 2000;
62 static const OptionDef options
[];
64 /* maximum number of simultaneous HTTP connections */
65 #define HTTP_MAX_CONNECTIONS 2000
68 HTTPSTATE_WAIT_REQUEST
,
69 HTTPSTATE_SEND_HEADER
,
70 HTTPSTATE_SEND_DATA_HEADER
,
71 HTTPSTATE_SEND_DATA
, /* sending TCP or UDP data */
72 HTTPSTATE_SEND_DATA_TRAILER
,
73 HTTPSTATE_RECEIVE_DATA
,
74 HTTPSTATE_WAIT_FEED
, /* wait for data from the feed */
77 RTSPSTATE_WAIT_REQUEST
,
79 RTSPSTATE_SEND_PACKET
,
82 const char *http_state
[] = {
98 #define IOBUFFER_INIT_SIZE 8192
100 /* timeouts are in ms */
101 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
102 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
104 #define SYNC_TIMEOUT (10 * 1000)
107 int64_t count1
, count2
;
108 int64_t time1
, time2
;
111 /* context associated with one connection */
112 typedef struct HTTPContext
{
113 enum HTTPState state
;
114 int fd
; /* socket file descriptor */
115 struct sockaddr_in from_addr
; /* origin */
116 struct pollfd
*poll_entry
; /* used when polling */
118 uint8_t *buffer_ptr
, *buffer_end
;
121 struct HTTPContext
*next
;
122 int got_key_frame
; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
126 /* input format handling */
127 AVFormatContext
*fmt_in
;
128 int64_t start_time
; /* In milliseconds - this wraps fairly often */
129 int64_t first_pts
; /* initial pts value */
130 int64_t cur_pts
; /* current pts value from the stream in us */
131 int64_t cur_frame_duration
; /* duration of the current frame in us */
132 int cur_frame_bytes
; /* output frame size, needed to compute
133 the time at which we send each
135 int pts_stream_index
; /* stream we choose as clock reference */
136 int64_t cur_clock
; /* current clock reference value in us */
137 /* output format handling */
138 struct FFStream
*stream
;
139 /* -1 is invalid stream */
140 int feed_streams
[MAX_STREAMS
]; /* index of streams in the feed */
141 int switch_feed_streams
[MAX_STREAMS
]; /* index of streams in the feed */
143 AVFormatContext fmt_ctx
; /* instance of FFStream for one user */
144 int last_packet_sent
; /* true if last data packet was sent */
146 DataRateData datarate
;
153 int is_packetized
; /* if true, the stream is packetized */
154 int packet_stream_index
; /* current stream for output in state machine */
156 /* RTSP state specific */
157 uint8_t *pb_buffer
; /* XXX: use that in all the code */
159 int seq
; /* RTSP sequence number */
161 /* RTP state specific */
162 enum RTSPProtocol rtp_protocol
;
163 char session_id
[32]; /* session id */
164 AVFormatContext
*rtp_ctx
[MAX_STREAMS
];
166 /* RTP/UDP specific */
167 URLContext
*rtp_handles
[MAX_STREAMS
];
169 /* RTP/TCP specific */
170 struct HTTPContext
*rtsp_c
;
171 uint8_t *packet_buffer
, *packet_buffer_ptr
, *packet_buffer_end
;
174 static AVFrame dummy_frame
;
176 /* each generated stream is described here */
180 STREAM_TYPE_REDIRECT
,
183 enum IPAddressAction
{
188 typedef struct IPAddressACL
{
189 struct IPAddressACL
*next
;
190 enum IPAddressAction action
;
191 /* These are in host order */
192 struct in_addr first
;
196 /* description of each stream of the ffserver.conf file */
197 typedef struct FFStream
{
198 enum StreamType stream_type
;
199 char filename
[1024]; /* stream filename */
200 struct FFStream
*feed
; /* feed we are using (can be null if
202 AVFormatParameters
*ap_in
; /* input parameters */
203 AVInputFormat
*ifmt
; /* if non NULL, force input format */
207 int prebuffer
; /* Number of millseconds early to start */
208 int64_t max_time
; /* Number of milliseconds to run */
210 AVStream
*streams
[MAX_STREAMS
];
211 int feed_streams
[MAX_STREAMS
]; /* index of streams in the feed */
212 char feed_filename
[1024]; /* file name of the feed storage, or
213 input file name for a stream */
218 pid_t pid
; /* Of ffmpeg process */
219 time_t pid_start
; /* Of ffmpeg process */
221 struct FFStream
*next
;
222 int bandwidth
; /* bandwidth, in kbits/s */
225 /* multicast specific */
227 struct in_addr multicast_ip
;
228 int multicast_port
; /* first port used for multicast */
230 int loop
; /* if true, send the stream in loops (only meaningful if file) */
233 int feed_opened
; /* true if someone is writing to the feed */
234 int is_feed
; /* true if it is a feed */
235 int readonly
; /* True if writing is prohibited to the file */
237 int64_t bytes_served
;
238 int64_t feed_max_size
; /* maximum storage size, zero means unlimited */
239 int64_t feed_write_index
; /* current write position in feed (it wraps around) */
240 int64_t feed_size
; /* current size of feed */
241 struct FFStream
*next_feed
;
244 typedef struct FeedData
{
245 long long data_count
;
246 float avg_frame_size
; /* frame size averaged over last frames with exponential mean */
249 static struct sockaddr_in my_http_addr
;
250 static struct sockaddr_in my_rtsp_addr
;
252 static char logfilename
[1024];
253 static HTTPContext
*first_http_ctx
;
254 static FFStream
*first_feed
; /* contains only feeds */
255 static FFStream
*first_stream
; /* contains all streams, including feeds */
257 static void new_connection(int server_fd
, int is_rtsp
);
258 static void close_connection(HTTPContext
*c
);
261 static int handle_connection(HTTPContext
*c
);
262 static int http_parse_request(HTTPContext
*c
);
263 static int http_send_data(HTTPContext
*c
);
264 static void compute_stats(HTTPContext
*c
);
265 static int open_input_stream(HTTPContext
*c
, const char *info
);
266 static int http_start_receive_data(HTTPContext
*c
);
267 static int http_receive_data(HTTPContext
*c
);
270 static int rtsp_parse_request(HTTPContext
*c
);
271 static void rtsp_cmd_describe(HTTPContext
*c
, const char *url
);
272 static void rtsp_cmd_options(HTTPContext
*c
, const char *url
);
273 static void rtsp_cmd_setup(HTTPContext
*c
, const char *url
, RTSPHeader
*h
);
274 static void rtsp_cmd_play(HTTPContext
*c
, const char *url
, RTSPHeader
*h
);
275 static void rtsp_cmd_pause(HTTPContext
*c
, const char *url
, RTSPHeader
*h
);
276 static void rtsp_cmd_teardown(HTTPContext
*c
, const char *url
, RTSPHeader
*h
);
279 static int prepare_sdp_description(FFStream
*stream
, uint8_t **pbuffer
,
280 struct in_addr my_ip
);
283 static HTTPContext
*rtp_new_connection(struct sockaddr_in
*from_addr
,
284 FFStream
*stream
, const char *session_id
,
285 enum RTSPProtocol rtp_protocol
);
286 static int rtp_new_av_stream(HTTPContext
*c
,
287 int stream_index
, struct sockaddr_in
*dest_addr
,
288 HTTPContext
*rtsp_c
);
290 static const char *my_program_name
;
291 static const char *my_program_dir
;
293 static const char *config_filename
;
294 static int ffserver_debug
;
295 static int ffserver_daemon
;
296 static int no_launch
;
297 static int need_to_start_children
;
299 static int nb_max_connections
;
300 static int nb_connections
;
302 static int max_bandwidth
;
303 static int current_bandwidth
;
305 static int64_t cur_time
; // Making this global saves on passing it around everywhere
307 static AVRandomState random_state
;
309 static FILE *logfile
= NULL
;
311 static void __attribute__ ((format (printf
, 1, 2))) http_log(const char *fmt
, ...)
317 vfprintf(logfile
, fmt
, ap
);
323 static char *ctime1(char *buf2
)
331 p
= buf2
+ strlen(p
) - 1;
337 static void log_connection(HTTPContext
*c
)
344 http_log("%s - - [%s] \"%s %s %s\" %d %"PRId64
"\n",
345 inet_ntoa(c
->from_addr
.sin_addr
),
346 ctime1(buf2
), c
->method
, c
->url
,
347 c
->protocol
, (c
->http_error
? c
->http_error
: 200), c
->data_count
);
350 static void update_datarate(DataRateData
*drd
, int64_t count
)
352 if (!drd
->time1
&& !drd
->count1
) {
353 drd
->time1
= drd
->time2
= cur_time
;
354 drd
->count1
= drd
->count2
= count
;
355 } else if (cur_time
- drd
->time2
> 5000) {
356 drd
->time1
= drd
->time2
;
357 drd
->count1
= drd
->count2
;
358 drd
->time2
= cur_time
;
363 /* In bytes per second */
364 static int compute_datarate(DataRateData
*drd
, int64_t count
)
366 if (cur_time
== drd
->time1
)
369 return ((count
- drd
->count1
) * 1000) / (cur_time
- drd
->time1
);
373 static void start_children(FFStream
*feed
)
378 for (; feed
; feed
= feed
->next
) {
379 if (feed
->child_argv
&& !feed
->pid
) {
380 feed
->pid_start
= time(0);
385 fprintf(stderr
, "Unable to create children\n");
394 for (i
= 3; i
< 256; i
++)
397 if (!ffserver_debug
) {
398 i
= open("/dev/null", O_RDWR
);
407 av_strlcpy(pathname
, my_program_name
, sizeof(pathname
));
409 slash
= strrchr(pathname
, '/');
414 strcpy(slash
, "ffmpeg");
416 /* This is needed to make relative pathnames work */
417 chdir(my_program_dir
);
419 signal(SIGPIPE
, SIG_DFL
);
421 execvp(pathname
, feed
->child_argv
);
429 /* open a listening socket */
430 static int socket_open_listen(struct sockaddr_in
*my_addr
)
434 server_fd
= socket(AF_INET
,SOCK_STREAM
,0);
441 setsockopt(server_fd
, SOL_SOCKET
, SO_REUSEADDR
, &tmp
, sizeof(tmp
));
443 if (bind (server_fd
, (struct sockaddr
*) my_addr
, sizeof (*my_addr
)) < 0) {
445 snprintf(bindmsg
, sizeof(bindmsg
), "bind(port %d)", ntohs(my_addr
->sin_port
));
447 closesocket(server_fd
);
451 if (listen (server_fd
, 5) < 0) {
453 closesocket(server_fd
);
456 ff_socket_nonblock(server_fd
, 1);
461 /* start all multicast streams */
462 static void start_multicast(void)
467 struct sockaddr_in dest_addr
;
468 int default_port
, stream_index
;
471 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
472 if (stream
->is_multicast
) {
473 /* open the RTP connection */
474 snprintf(session_id
, sizeof(session_id
), "%08x%08x",
475 av_random(&random_state
), av_random(&random_state
));
477 /* choose a port if none given */
478 if (stream
->multicast_port
== 0) {
479 stream
->multicast_port
= default_port
;
483 dest_addr
.sin_family
= AF_INET
;
484 dest_addr
.sin_addr
= stream
->multicast_ip
;
485 dest_addr
.sin_port
= htons(stream
->multicast_port
);
487 rtp_c
= rtp_new_connection(&dest_addr
, stream
, session_id
,
488 RTSP_PROTOCOL_RTP_UDP_MULTICAST
);
492 if (open_input_stream(rtp_c
, "") < 0) {
493 fprintf(stderr
, "Could not open input stream for stream '%s'\n",
498 /* open each RTP stream */
499 for(stream_index
= 0; stream_index
< stream
->nb_streams
;
501 dest_addr
.sin_port
= htons(stream
->multicast_port
+
503 if (rtp_new_av_stream(rtp_c
, stream_index
, &dest_addr
, NULL
) < 0) {
504 fprintf(stderr
, "Could not open output stream '%s/streamid=%d'\n",
505 stream
->filename
, stream_index
);
510 /* change state to send data */
511 rtp_c
->state
= HTTPSTATE_SEND_DATA
;
516 /* main loop of the http server */
517 static int http_server(void)
519 int server_fd
, ret
, rtsp_server_fd
, delay
, delay1
;
520 struct pollfd poll_table
[HTTP_MAX_CONNECTIONS
+ 2], *poll_entry
;
521 HTTPContext
*c
, *c_next
;
523 server_fd
= socket_open_listen(&my_http_addr
);
527 rtsp_server_fd
= socket_open_listen(&my_rtsp_addr
);
528 if (rtsp_server_fd
< 0)
531 http_log("ffserver started.\n");
533 start_children(first_feed
);
535 first_http_ctx
= NULL
;
541 poll_entry
= poll_table
;
542 poll_entry
->fd
= server_fd
;
543 poll_entry
->events
= POLLIN
;
546 poll_entry
->fd
= rtsp_server_fd
;
547 poll_entry
->events
= POLLIN
;
550 /* wait for events on each HTTP handle */
557 case HTTPSTATE_SEND_HEADER
:
558 case RTSPSTATE_SEND_REPLY
:
559 case RTSPSTATE_SEND_PACKET
:
560 c
->poll_entry
= poll_entry
;
562 poll_entry
->events
= POLLOUT
;
565 case HTTPSTATE_SEND_DATA_HEADER
:
566 case HTTPSTATE_SEND_DATA
:
567 case HTTPSTATE_SEND_DATA_TRAILER
:
568 if (!c
->is_packetized
) {
569 /* for TCP, we output as much as we can (may need to put a limit) */
570 c
->poll_entry
= poll_entry
;
572 poll_entry
->events
= POLLOUT
;
575 /* when ffserver is doing the timing, we work by
576 looking at which packet need to be sent every
578 delay1
= 10; /* one tick wait XXX: 10 ms assumed */
583 case HTTPSTATE_WAIT_REQUEST
:
584 case HTTPSTATE_RECEIVE_DATA
:
585 case HTTPSTATE_WAIT_FEED
:
586 case RTSPSTATE_WAIT_REQUEST
:
587 /* need to catch errors */
588 c
->poll_entry
= poll_entry
;
590 poll_entry
->events
= POLLIN
;/* Maybe this will work */
594 c
->poll_entry
= NULL
;
600 /* wait for an event on one connection. We poll at least every
601 second to handle timeouts */
603 ret
= poll(poll_table
, poll_entry
- poll_table
, delay
);
604 if (ret
< 0 && ff_neterrno() != FF_NETERROR(EAGAIN
) &&
605 ff_neterrno() != FF_NETERROR(EINTR
))
609 cur_time
= av_gettime() / 1000;
611 if (need_to_start_children
) {
612 need_to_start_children
= 0;
613 start_children(first_feed
);
616 /* now handle the events */
617 for(c
= first_http_ctx
; c
!= NULL
; c
= c_next
) {
619 if (handle_connection(c
) < 0) {
620 /* close and free the connection */
626 poll_entry
= poll_table
;
627 /* new HTTP connection request ? */
628 if (poll_entry
->revents
& POLLIN
)
629 new_connection(server_fd
, 0);
631 /* new RTSP connection request ? */
632 if (poll_entry
->revents
& POLLIN
)
633 new_connection(rtsp_server_fd
, 1);
637 /* start waiting for a new HTTP/RTSP request */
638 static void start_wait_request(HTTPContext
*c
, int is_rtsp
)
640 c
->buffer_ptr
= c
->buffer
;
641 c
->buffer_end
= c
->buffer
+ c
->buffer_size
- 1; /* leave room for '\0' */
644 c
->timeout
= cur_time
+ RTSP_REQUEST_TIMEOUT
;
645 c
->state
= RTSPSTATE_WAIT_REQUEST
;
647 c
->timeout
= cur_time
+ HTTP_REQUEST_TIMEOUT
;
648 c
->state
= HTTPSTATE_WAIT_REQUEST
;
652 static void new_connection(int server_fd
, int is_rtsp
)
654 struct sockaddr_in from_addr
;
656 HTTPContext
*c
= NULL
;
658 len
= sizeof(from_addr
);
659 fd
= accept(server_fd
, (struct sockaddr
*)&from_addr
,
663 ff_socket_nonblock(fd
, 1);
665 /* XXX: should output a warning page when coming
666 close to the connection limit */
667 if (nb_connections
>= nb_max_connections
)
670 /* add a new connection */
671 c
= av_mallocz(sizeof(HTTPContext
));
676 c
->poll_entry
= NULL
;
677 c
->from_addr
= from_addr
;
678 c
->buffer_size
= IOBUFFER_INIT_SIZE
;
679 c
->buffer
= av_malloc(c
->buffer_size
);
683 c
->next
= first_http_ctx
;
687 start_wait_request(c
, is_rtsp
);
699 static void close_connection(HTTPContext
*c
)
701 HTTPContext
**cp
, *c1
;
703 AVFormatContext
*ctx
;
707 /* remove connection from list */
708 cp
= &first_http_ctx
;
709 while ((*cp
) != NULL
) {
717 /* remove references, if any (XXX: do it faster) */
718 for(c1
= first_http_ctx
; c1
!= NULL
; c1
= c1
->next
) {
723 /* remove connection associated resources */
727 /* close each frame parser */
728 for(i
=0;i
<c
->fmt_in
->nb_streams
;i
++) {
729 st
= c
->fmt_in
->streams
[i
];
730 if (st
->codec
->codec
)
731 avcodec_close(st
->codec
);
733 av_close_input_file(c
->fmt_in
);
736 /* free RTP output streams if any */
739 nb_streams
= c
->stream
->nb_streams
;
741 for(i
=0;i
<nb_streams
;i
++) {
744 av_write_trailer(ctx
);
747 h
= c
->rtp_handles
[i
];
754 if (!c
->last_packet_sent
) {
757 if (url_open_dyn_buf(&ctx
->pb
) >= 0) {
758 av_write_trailer(ctx
);
759 url_close_dyn_buf(ctx
->pb
, &c
->pb_buffer
);
764 for(i
=0; i
<ctx
->nb_streams
; i
++)
765 av_free(ctx
->streams
[i
]);
767 if (c
->stream
&& !c
->post
&& c
->stream
->stream_type
== STREAM_TYPE_LIVE
)
768 current_bandwidth
-= c
->stream
->bandwidth
;
770 /* signal that there is no feed if we are the feeder socket */
771 if (c
->state
== HTTPSTATE_RECEIVE_DATA
&& c
->stream
) {
772 c
->stream
->feed_opened
= 0;
776 av_freep(&c
->pb_buffer
);
777 av_freep(&c
->packet_buffer
);
783 static int handle_connection(HTTPContext
*c
)
788 case HTTPSTATE_WAIT_REQUEST
:
789 case RTSPSTATE_WAIT_REQUEST
:
791 if ((c
->timeout
- cur_time
) < 0)
793 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
796 /* no need to read if no events */
797 if (!(c
->poll_entry
->revents
& POLLIN
))
801 len
= recv(c
->fd
, c
->buffer_ptr
, 1, 0);
803 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
804 ff_neterrno() != FF_NETERROR(EINTR
))
806 } else if (len
== 0) {
809 /* search for end of request. */
811 c
->buffer_ptr
+= len
;
813 if ((ptr
>= c
->buffer
+ 2 && !memcmp(ptr
-2, "\n\n", 2)) ||
814 (ptr
>= c
->buffer
+ 4 && !memcmp(ptr
-4, "\r\n\r\n", 4))) {
815 /* request found : parse it and reply */
816 if (c
->state
== HTTPSTATE_WAIT_REQUEST
) {
817 ret
= http_parse_request(c
);
819 ret
= rtsp_parse_request(c
);
823 } else if (ptr
>= c
->buffer_end
) {
824 /* request too long: cannot do anything */
826 } else goto read_loop
;
830 case HTTPSTATE_SEND_HEADER
:
831 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
834 /* no need to write if no events */
835 if (!(c
->poll_entry
->revents
& POLLOUT
))
837 len
= send(c
->fd
, c
->buffer_ptr
, c
->buffer_end
- c
->buffer_ptr
, 0);
839 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
840 ff_neterrno() != FF_NETERROR(EINTR
)) {
841 /* error : close connection */
842 av_freep(&c
->pb_buffer
);
846 c
->buffer_ptr
+= len
;
848 c
->stream
->bytes_served
+= len
;
849 c
->data_count
+= len
;
850 if (c
->buffer_ptr
>= c
->buffer_end
) {
851 av_freep(&c
->pb_buffer
);
855 /* all the buffer was sent : synchronize to the incoming stream */
856 c
->state
= HTTPSTATE_SEND_DATA_HEADER
;
857 c
->buffer_ptr
= c
->buffer_end
= c
->buffer
;
862 case HTTPSTATE_SEND_DATA
:
863 case HTTPSTATE_SEND_DATA_HEADER
:
864 case HTTPSTATE_SEND_DATA_TRAILER
:
865 /* for packetized output, we consider we can always write (the
866 input streams sets the speed). It may be better to verify
867 that we do not rely too much on the kernel queues */
868 if (!c
->is_packetized
) {
869 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
872 /* no need to read if no events */
873 if (!(c
->poll_entry
->revents
& POLLOUT
))
876 if (http_send_data(c
) < 0)
878 /* close connection if trailer sent */
879 if (c
->state
== HTTPSTATE_SEND_DATA_TRAILER
)
882 case HTTPSTATE_RECEIVE_DATA
:
883 /* no need to read if no events */
884 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
886 if (!(c
->poll_entry
->revents
& POLLIN
))
888 if (http_receive_data(c
) < 0)
891 case HTTPSTATE_WAIT_FEED
:
892 /* no need to read if no events */
893 if (c
->poll_entry
->revents
& (POLLIN
| POLLERR
| POLLHUP
))
896 /* nothing to do, we'll be waken up by incoming feed packets */
899 case RTSPSTATE_SEND_REPLY
:
900 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
)) {
901 av_freep(&c
->pb_buffer
);
904 /* no need to write if no events */
905 if (!(c
->poll_entry
->revents
& POLLOUT
))
907 len
= send(c
->fd
, c
->buffer_ptr
, c
->buffer_end
- c
->buffer_ptr
, 0);
909 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
910 ff_neterrno() != FF_NETERROR(EINTR
)) {
911 /* error : close connection */
912 av_freep(&c
->pb_buffer
);
916 c
->buffer_ptr
+= len
;
917 c
->data_count
+= len
;
918 if (c
->buffer_ptr
>= c
->buffer_end
) {
919 /* all the buffer was sent : wait for a new request */
920 av_freep(&c
->pb_buffer
);
921 start_wait_request(c
, 1);
925 case RTSPSTATE_SEND_PACKET
:
926 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
)) {
927 av_freep(&c
->packet_buffer
);
930 /* no need to write if no events */
931 if (!(c
->poll_entry
->revents
& POLLOUT
))
933 len
= send(c
->fd
, c
->packet_buffer_ptr
,
934 c
->packet_buffer_end
- c
->packet_buffer_ptr
, 0);
936 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
937 ff_neterrno() != FF_NETERROR(EINTR
)) {
938 /* error : close connection */
939 av_freep(&c
->packet_buffer
);
943 c
->packet_buffer_ptr
+= len
;
944 if (c
->packet_buffer_ptr
>= c
->packet_buffer_end
) {
945 /* all the buffer was sent : wait for a new request */
946 av_freep(&c
->packet_buffer
);
947 c
->state
= RTSPSTATE_WAIT_REQUEST
;
951 case HTTPSTATE_READY
:
960 static int extract_rates(char *rates
, int ratelen
, const char *request
)
964 for (p
= request
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
965 if (strncasecmp(p
, "Pragma:", 7) == 0) {
966 const char *q
= p
+ 7;
968 while (*q
&& *q
!= '\n' && isspace(*q
))
971 if (strncasecmp(q
, "stream-switch-entry=", 20) == 0) {
977 memset(rates
, 0xff, ratelen
);
980 while (*q
&& *q
!= '\n' && *q
!= ':')
983 if (sscanf(q
, ":%d:%d", &stream_no
, &rate_no
) != 2)
987 if (stream_no
< ratelen
&& stream_no
>= 0)
988 rates
[stream_no
] = rate_no
;
990 while (*q
&& *q
!= '\n' && !isspace(*q
))
1007 static int find_stream_in_feed(FFStream
*feed
, AVCodecContext
*codec
, int bit_rate
)
1010 int best_bitrate
= 100000000;
1013 for (i
= 0; i
< feed
->nb_streams
; i
++) {
1014 AVCodecContext
*feed_codec
= feed
->streams
[i
]->codec
;
1016 if (feed_codec
->codec_id
!= codec
->codec_id
||
1017 feed_codec
->sample_rate
!= codec
->sample_rate
||
1018 feed_codec
->width
!= codec
->width
||
1019 feed_codec
->height
!= codec
->height
)
1022 /* Potential stream */
1024 /* We want the fastest stream less than bit_rate, or the slowest
1025 * faster than bit_rate
1028 if (feed_codec
->bit_rate
<= bit_rate
) {
1029 if (best_bitrate
> bit_rate
|| feed_codec
->bit_rate
> best_bitrate
) {
1030 best_bitrate
= feed_codec
->bit_rate
;
1034 if (feed_codec
->bit_rate
< best_bitrate
) {
1035 best_bitrate
= feed_codec
->bit_rate
;
1044 static int modify_current_stream(HTTPContext
*c
, char *rates
)
1047 FFStream
*req
= c
->stream
;
1048 int action_required
= 0;
1050 /* Not much we can do for a feed */
1054 for (i
= 0; i
< req
->nb_streams
; i
++) {
1055 AVCodecContext
*codec
= req
->streams
[i
]->codec
;
1059 c
->switch_feed_streams
[i
] = req
->feed_streams
[i
];
1062 c
->switch_feed_streams
[i
] = find_stream_in_feed(req
->feed
, codec
, codec
->bit_rate
/ 2);
1065 /* Wants off or slow */
1066 c
->switch_feed_streams
[i
] = find_stream_in_feed(req
->feed
, codec
, codec
->bit_rate
/ 4);
1068 /* This doesn't work well when it turns off the only stream! */
1069 c
->switch_feed_streams
[i
] = -2;
1070 c
->feed_streams
[i
] = -2;
1075 if (c
->switch_feed_streams
[i
] >= 0 && c
->switch_feed_streams
[i
] != c
->feed_streams
[i
])
1076 action_required
= 1;
1079 return action_required
;
1083 static void do_switch_stream(HTTPContext
*c
, int i
)
1085 if (c
->switch_feed_streams
[i
] >= 0) {
1087 c
->feed_streams
[i
] = c
->switch_feed_streams
[i
];
1090 /* Now update the stream */
1092 c
->switch_feed_streams
[i
] = -1;
1095 /* XXX: factorize in utils.c ? */
1096 /* XXX: take care with different space meaning */
1097 static void skip_spaces(const char **pp
)
1101 while (*p
== ' ' || *p
== '\t')
1106 static void get_word(char *buf
, int buf_size
, const char **pp
)
1114 while (!isspace(*p
) && *p
!= '\0') {
1115 if ((q
- buf
) < buf_size
- 1)
1124 static int validate_acl(FFStream
*stream
, HTTPContext
*c
)
1126 enum IPAddressAction last_action
= IP_DENY
;
1128 struct in_addr
*src
= &c
->from_addr
.sin_addr
;
1129 unsigned long src_addr
= src
->s_addr
;
1131 for (acl
= stream
->acl
; acl
; acl
= acl
->next
) {
1132 if (src_addr
>= acl
->first
.s_addr
&& src_addr
<= acl
->last
.s_addr
)
1133 return (acl
->action
== IP_ALLOW
) ? 1 : 0;
1134 last_action
= acl
->action
;
1137 /* Nothing matched, so return not the last action */
1138 return (last_action
== IP_DENY
) ? 1 : 0;
1141 /* compute the real filename of a file by matching it without its
1142 extensions to all the stream filenames */
1143 static void compute_real_filename(char *filename
, int max_size
)
1150 /* compute filename by matching without the file extensions */
1151 av_strlcpy(file1
, filename
, sizeof(file1
));
1152 p
= strrchr(file1
, '.');
1155 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
1156 av_strlcpy(file2
, stream
->filename
, sizeof(file2
));
1157 p
= strrchr(file2
, '.');
1160 if (!strcmp(file1
, file2
)) {
1161 av_strlcpy(filename
, stream
->filename
, max_size
);
1176 /* parse http request and prepare header */
1177 static int http_parse_request(HTTPContext
*c
)
1180 enum RedirType redir_type
;
1182 char info
[1024], filename
[1024];
1186 const char *mime_type
;
1190 char *useragent
= 0;
1193 get_word(cmd
, sizeof(cmd
), (const char **)&p
);
1194 av_strlcpy(c
->method
, cmd
, sizeof(c
->method
));
1196 if (!strcmp(cmd
, "GET"))
1198 else if (!strcmp(cmd
, "POST"))
1203 get_word(url
, sizeof(url
), (const char **)&p
);
1204 av_strlcpy(c
->url
, url
, sizeof(c
->url
));
1206 get_word(protocol
, sizeof(protocol
), (const char **)&p
);
1207 if (strcmp(protocol
, "HTTP/1.0") && strcmp(protocol
, "HTTP/1.1"))
1210 av_strlcpy(c
->protocol
, protocol
, sizeof(c
->protocol
));
1213 http_log("New connection: %s %s\n", cmd
, url
);
1215 /* find the filename and the optional info string in the request */
1216 p
= strchr(url
, '?');
1218 av_strlcpy(info
, p
, sizeof(info
));
1223 av_strlcpy(filename
, url
+ ((*url
== '/') ? 1 : 0), sizeof(filename
)-1);
1225 for (p
= c
->buffer
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
1226 if (strncasecmp(p
, "User-Agent:", 11) == 0) {
1228 if (*useragent
&& *useragent
!= '\n' && isspace(*useragent
))
1232 p
= strchr(p
, '\n');
1239 redir_type
= REDIR_NONE
;
1240 if (match_ext(filename
, "asx")) {
1241 redir_type
= REDIR_ASX
;
1242 filename
[strlen(filename
)-1] = 'f';
1243 } else if (match_ext(filename
, "asf") &&
1244 (!useragent
|| strncasecmp(useragent
, "NSPlayer", 8) != 0)) {
1245 /* if this isn't WMP or lookalike, return the redirector file */
1246 redir_type
= REDIR_ASF
;
1247 } else if (match_ext(filename
, "rpm,ram")) {
1248 redir_type
= REDIR_RAM
;
1249 strcpy(filename
+ strlen(filename
)-2, "m");
1250 } else if (match_ext(filename
, "rtsp")) {
1251 redir_type
= REDIR_RTSP
;
1252 compute_real_filename(filename
, sizeof(filename
) - 1);
1253 } else if (match_ext(filename
, "sdp")) {
1254 redir_type
= REDIR_SDP
;
1255 compute_real_filename(filename
, sizeof(filename
) - 1);
1258 // "redirect" / request to index.html
1259 if (!strlen(filename
))
1260 av_strlcpy(filename
, "index.html", sizeof(filename
) - 1);
1262 stream
= first_stream
;
1263 while (stream
!= NULL
) {
1264 if (!strcmp(stream
->filename
, filename
) && validate_acl(stream
, c
))
1266 stream
= stream
->next
;
1268 if (stream
== NULL
) {
1269 snprintf(msg
, sizeof(msg
), "File '%s' not found", url
);
1274 memcpy(c
->feed_streams
, stream
->feed_streams
, sizeof(c
->feed_streams
));
1275 memset(c
->switch_feed_streams
, -1, sizeof(c
->switch_feed_streams
));
1277 if (stream
->stream_type
== STREAM_TYPE_REDIRECT
) {
1278 c
->http_error
= 301;
1280 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 301 Moved\r\n");
1281 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Location: %s\r\n", stream
->feed_filename
);
1282 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: text/html\r\n");
1283 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1284 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<html><head><title>Moved</title></head><body>\r\n");
1285 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "You should be <a href=\"%s\">redirected</a>.\r\n", stream
->feed_filename
);
1286 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "</body></html>\r\n");
1288 /* prepare output buffer */
1289 c
->buffer_ptr
= c
->buffer
;
1291 c
->state
= HTTPSTATE_SEND_HEADER
;
1295 /* If this is WMP, get the rate information */
1296 if (extract_rates(ratebuf
, sizeof(ratebuf
), c
->buffer
)) {
1297 if (modify_current_stream(c
, ratebuf
)) {
1298 for (i
= 0; i
< sizeof(c
->feed_streams
) / sizeof(c
->feed_streams
[0]); i
++) {
1299 if (c
->switch_feed_streams
[i
] >= 0)
1300 do_switch_stream(c
, i
);
1305 /* If already streaming this feed, do not let start another feeder. */
1306 if (stream
->feed_opened
) {
1307 snprintf(msg
, sizeof(msg
), "This feed is already being received.");
1311 if (c
->post
== 0 && stream
->stream_type
== STREAM_TYPE_LIVE
)
1312 current_bandwidth
+= stream
->bandwidth
;
1314 if (c
->post
== 0 && max_bandwidth
< current_bandwidth
) {
1315 c
->http_error
= 200;
1317 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 Server too busy\r\n");
1318 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: text/html\r\n");
1319 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1320 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<html><head><title>Too busy</title></head><body>\r\n");
1321 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<p>The server is too busy to serve your request at this time.</p>\r\n");
1322 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<p>The bandwidth being served (including your stream) is %dkbit/sec, and this exceeds the limit of %dkbit/sec.</p>\r\n",
1323 current_bandwidth
, max_bandwidth
);
1324 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "</body></html>\r\n");
1326 /* prepare output buffer */
1327 c
->buffer_ptr
= c
->buffer
;
1329 c
->state
= HTTPSTATE_SEND_HEADER
;
1333 if (redir_type
!= REDIR_NONE
) {
1336 for (p
= c
->buffer
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
1337 if (strncasecmp(p
, "Host:", 5) == 0) {
1341 p
= strchr(p
, '\n');
1352 while (isspace(*hostinfo
))
1355 eoh
= strchr(hostinfo
, '\n');
1357 if (eoh
[-1] == '\r')
1360 if (eoh
- hostinfo
< sizeof(hostbuf
) - 1) {
1361 memcpy(hostbuf
, hostinfo
, eoh
- hostinfo
);
1362 hostbuf
[eoh
- hostinfo
] = 0;
1364 c
->http_error
= 200;
1366 switch(redir_type
) {
1368 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 ASX Follows\r\n");
1369 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: video/x-ms-asf\r\n");
1370 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1371 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<ASX Version=\"3\">\r\n");
1372 //q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<!-- Autogenerated by ffserver -->\r\n");
1373 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n",
1374 hostbuf
, filename
, info
);
1375 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "</ASX>\r\n");
1378 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 RAM Follows\r\n");
1379 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: audio/x-pn-realaudio\r\n");
1380 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1381 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "# Autogenerated by ffserver\r\n");
1382 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "http://%s/%s%s\r\n",
1383 hostbuf
, filename
, info
);
1386 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 ASF Redirect follows\r\n");
1387 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: video/x-ms-asf\r\n");
1388 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1389 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "[Reference]\r\n");
1390 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Ref1=http://%s/%s%s\r\n",
1391 hostbuf
, filename
, info
);
1395 char hostname
[256], *p
;
1396 /* extract only hostname */
1397 av_strlcpy(hostname
, hostbuf
, sizeof(hostname
));
1398 p
= strrchr(hostname
, ':');
1401 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 RTSP Redirect follows\r\n");
1402 /* XXX: incorrect mime type ? */
1403 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: application/x-rtsp\r\n");
1404 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1405 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "rtsp://%s:%d/%s\r\n",
1406 hostname
, ntohs(my_rtsp_addr
.sin_port
),
1413 int sdp_data_size
, len
;
1414 struct sockaddr_in my_addr
;
1416 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 OK\r\n");
1417 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: application/sdp\r\n");
1418 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1420 len
= sizeof(my_addr
);
1421 getsockname(c
->fd
, (struct sockaddr
*)&my_addr
, &len
);
1423 /* XXX: should use a dynamic buffer */
1424 sdp_data_size
= prepare_sdp_description(stream
,
1427 if (sdp_data_size
> 0) {
1428 memcpy(q
, sdp_data
, sdp_data_size
);
1440 /* prepare output buffer */
1441 c
->buffer_ptr
= c
->buffer
;
1443 c
->state
= HTTPSTATE_SEND_HEADER
;
1449 snprintf(msg
, sizeof(msg
), "ASX/RAM file not handled");
1453 stream
->conns_served
++;
1455 /* XXX: add there authenticate and IP match */
1458 /* if post, it means a feed is being sent */
1459 if (!stream
->is_feed
) {
1460 /* However it might be a status report from WMP! Lets log the data
1461 * as it might come in handy one day
1466 for (p
= c
->buffer
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
1467 if (strncasecmp(p
, "Pragma: log-line=", 17) == 0) {
1471 if (strncasecmp(p
, "Pragma: client-id=", 18) == 0)
1472 client_id
= strtol(p
+ 18, 0, 10);
1473 p
= strchr(p
, '\n');
1481 char *eol
= strchr(logline
, '\n');
1486 if (eol
[-1] == '\r')
1488 http_log("%.*s\n", (int) (eol
- logline
), logline
);
1489 c
->suppress_log
= 1;
1494 http_log("\nGot request:\n%s\n", c
->buffer
);
1497 if (client_id
&& extract_rates(ratebuf
, sizeof(ratebuf
), c
->buffer
)) {
1500 /* Now we have to find the client_id */
1501 for (wmpc
= first_http_ctx
; wmpc
; wmpc
= wmpc
->next
) {
1502 if (wmpc
->wmp_client_id
== client_id
)
1506 if (wmpc
&& modify_current_stream(wmpc
, ratebuf
))
1507 wmpc
->switch_pending
= 1;
1510 snprintf(msg
, sizeof(msg
), "POST command not handled");
1514 if (http_start_receive_data(c
) < 0) {
1515 snprintf(msg
, sizeof(msg
), "could not open feed");
1519 c
->state
= HTTPSTATE_RECEIVE_DATA
;
1524 if (strcmp(stream
->filename
+ strlen(stream
->filename
) - 4, ".asf") == 0)
1525 http_log("\nGot request:\n%s\n", c
->buffer
);
1528 if (c
->stream
->stream_type
== STREAM_TYPE_STATUS
)
1531 /* open input stream */
1532 if (open_input_stream(c
, info
) < 0) {
1533 snprintf(msg
, sizeof(msg
), "Input stream corresponding to '%s' not found", url
);
1537 /* prepare http header */
1539 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 OK\r\n");
1540 mime_type
= c
->stream
->fmt
->mime_type
;
1542 mime_type
= "application/x-octet-stream";
1543 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Pragma: no-cache\r\n");
1545 /* for asf, we need extra headers */
1546 if (!strcmp(c
->stream
->fmt
->name
,"asf_stream")) {
1547 /* Need to allocate a client id */
1549 c
->wmp_client_id
= av_random(&random_state
) & 0x7fffffff;
1551 q
+= snprintf(q
, q
- (char *) 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
);
1553 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-Type: %s\r\n", mime_type
);
1554 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1556 /* prepare output buffer */
1558 c
->buffer_ptr
= c
->buffer
;
1560 c
->state
= HTTPSTATE_SEND_HEADER
;
1563 c
->http_error
= 404;
1565 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 404 Not Found\r\n");
1566 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-type: %s\r\n", "text/html");
1567 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1568 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<HTML>\n");
1569 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<HEAD><TITLE>404 Not Found</TITLE></HEAD>\n");
1570 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "<BODY>%s</BODY>\n", msg
);
1571 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "</HTML>\n");
1573 /* prepare output buffer */
1574 c
->buffer_ptr
= c
->buffer
;
1576 c
->state
= HTTPSTATE_SEND_HEADER
;
1580 c
->http_error
= 200; /* horrible : we use this value to avoid
1581 going to the send data state */
1582 c
->state
= HTTPSTATE_SEND_HEADER
;
1586 static void fmt_bytecount(ByteIOContext
*pb
, int64_t count
)
1588 static const char *suffix
= " kMGTP";
1591 for (s
= suffix
; count
>= 100000 && s
[1]; count
/= 1000, s
++);
1593 url_fprintf(pb
, "%"PRId64
"%c", count
, *s
);
1596 static void compute_stats(HTTPContext
*c
)
1605 if (url_open_dyn_buf(&pb
) < 0) {
1606 /* XXX: return an error ? */
1607 c
->buffer_ptr
= c
->buffer
;
1608 c
->buffer_end
= c
->buffer
;
1612 url_fprintf(pb
, "HTTP/1.0 200 OK\r\n");
1613 url_fprintf(pb
, "Content-type: %s\r\n", "text/html");
1614 url_fprintf(pb
, "Pragma: no-cache\r\n");
1615 url_fprintf(pb
, "\r\n");
1617 url_fprintf(pb
, "<HEAD><TITLE>FFServer Status</TITLE>\n");
1618 if (c
->stream
->feed_filename
)
1619 url_fprintf(pb
, "<link rel=\"shortcut icon\" href=\"%s\">\n", c
->stream
->feed_filename
);
1620 url_fprintf(pb
, "</HEAD>\n<BODY>");
1621 url_fprintf(pb
, "<H1>FFServer Status</H1>\n");
1623 url_fprintf(pb
, "<H2>Available Streams</H2>\n");
1624 url_fprintf(pb
, "<TABLE cellspacing=0 cellpadding=4>\n");
1625 url_fprintf(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");
1626 stream
= first_stream
;
1627 while (stream
!= NULL
) {
1628 char sfilename
[1024];
1631 if (stream
->feed
!= stream
) {
1632 av_strlcpy(sfilename
, stream
->filename
, sizeof(sfilename
) - 10);
1633 eosf
= sfilename
+ strlen(sfilename
);
1634 if (eosf
- sfilename
>= 4) {
1635 if (strcmp(eosf
- 4, ".asf") == 0)
1636 strcpy(eosf
- 4, ".asx");
1637 else if (strcmp(eosf
- 3, ".rm") == 0)
1638 strcpy(eosf
- 3, ".ram");
1639 else if (stream
->fmt
&& !strcmp(stream
->fmt
->name
, "rtp")) {
1640 /* generate a sample RTSP director if
1641 unicast. Generate an SDP redirector if
1643 eosf
= strrchr(sfilename
, '.');
1645 eosf
= sfilename
+ strlen(sfilename
);
1646 if (stream
->is_multicast
)
1647 strcpy(eosf
, ".sdp");
1649 strcpy(eosf
, ".rtsp");
1653 url_fprintf(pb
, "<TR><TD><A HREF=\"/%s\">%s</A> ",
1654 sfilename
, stream
->filename
);
1655 url_fprintf(pb
, "<td align=right> %d <td align=right> ",
1656 stream
->conns_served
);
1657 fmt_bytecount(pb
, stream
->bytes_served
);
1658 switch(stream
->stream_type
) {
1659 case STREAM_TYPE_LIVE
:
1661 int audio_bit_rate
= 0;
1662 int video_bit_rate
= 0;
1663 const char *audio_codec_name
= "";
1664 const char *video_codec_name
= "";
1665 const char *audio_codec_name_extra
= "";
1666 const char *video_codec_name_extra
= "";
1668 for(i
=0;i
<stream
->nb_streams
;i
++) {
1669 AVStream
*st
= stream
->streams
[i
];
1670 AVCodec
*codec
= avcodec_find_encoder(st
->codec
->codec_id
);
1671 switch(st
->codec
->codec_type
) {
1672 case CODEC_TYPE_AUDIO
:
1673 audio_bit_rate
+= st
->codec
->bit_rate
;
1675 if (*audio_codec_name
)
1676 audio_codec_name_extra
= "...";
1677 audio_codec_name
= codec
->name
;
1680 case CODEC_TYPE_VIDEO
:
1681 video_bit_rate
+= st
->codec
->bit_rate
;
1683 if (*video_codec_name
)
1684 video_codec_name_extra
= "...";
1685 video_codec_name
= codec
->name
;
1688 case CODEC_TYPE_DATA
:
1689 video_bit_rate
+= st
->codec
->bit_rate
;
1695 url_fprintf(pb
, "<TD align=center> %s <TD align=right> %d <TD align=right> %d <TD> %s %s <TD align=right> %d <TD> %s %s",
1698 video_bit_rate
/ 1000, video_codec_name
, video_codec_name_extra
,
1699 audio_bit_rate
/ 1000, audio_codec_name
, audio_codec_name_extra
);
1701 url_fprintf(pb
, "<TD>%s", stream
->feed
->filename
);
1703 url_fprintf(pb
, "<TD>%s", stream
->feed_filename
);
1704 url_fprintf(pb
, "\n");
1708 url_fprintf(pb
, "<TD align=center> - <TD align=right> - <TD align=right> - <td><td align=right> - <TD>\n");
1712 stream
= stream
->next
;
1714 url_fprintf(pb
, "</TABLE>\n");
1716 stream
= first_stream
;
1717 while (stream
!= NULL
) {
1718 if (stream
->feed
== stream
) {
1719 url_fprintf(pb
, "<h2>Feed %s</h2>", stream
->filename
);
1721 url_fprintf(pb
, "Running as pid %d.\n", stream
->pid
);
1723 #if defined(linux) && !defined(CONFIG_NOCUTILS)
1728 /* This is somewhat linux specific I guess */
1729 snprintf(ps_cmd
, sizeof(ps_cmd
),
1730 "ps -o \"%%cpu,cputime\" --no-headers %d",
1733 pid_stat
= popen(ps_cmd
, "r");
1738 if (fscanf(pid_stat
, "%10s %64s", cpuperc
,
1740 url_fprintf(pb
, "Currently using %s%% of the cpu. Total time used %s.\n",
1748 url_fprintf(pb
, "<p>");
1750 url_fprintf(pb
, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>type<th>kbits/s<th align=left>codec<th align=left>Parameters\n");
1752 for (i
= 0; i
< stream
->nb_streams
; i
++) {
1753 AVStream
*st
= stream
->streams
[i
];
1754 AVCodec
*codec
= avcodec_find_encoder(st
->codec
->codec_id
);
1755 const char *type
= "unknown";
1756 char parameters
[64];
1760 switch(st
->codec
->codec_type
) {
1761 case CODEC_TYPE_AUDIO
:
1763 snprintf(parameters
, sizeof(parameters
), "%d channel(s), %d Hz", st
->codec
->channels
, st
->codec
->sample_rate
);
1765 case CODEC_TYPE_VIDEO
:
1767 snprintf(parameters
, sizeof(parameters
), "%dx%d, q=%d-%d, fps=%d", st
->codec
->width
, st
->codec
->height
,
1768 st
->codec
->qmin
, st
->codec
->qmax
, st
->codec
->time_base
.den
/ st
->codec
->time_base
.num
);
1773 url_fprintf(pb
, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
1774 i
, type
, st
->codec
->bit_rate
/1000, codec
? codec
->name
: "", parameters
);
1776 url_fprintf(pb
, "</table>\n");
1779 stream
= stream
->next
;
1785 AVCodecContext
*enc
;
1789 stream
= first_feed
;
1790 while (stream
!= NULL
) {
1791 url_fprintf(pb
, "<H1>Feed '%s'</H1>\n", stream
->filename
);
1792 url_fprintf(pb
, "<TABLE>\n");
1793 url_fprintf(pb
, "<TR><TD>Parameters<TD>Frame count<TD>Size<TD>Avg bitrate (kbits/s)\n");
1794 for(i
=0;i
<stream
->nb_streams
;i
++) {
1795 AVStream
*st
= stream
->streams
[i
];
1796 FeedData
*fdata
= st
->priv_data
;
1799 avcodec_string(buf
, sizeof(buf
), enc
);
1800 avg
= fdata
->avg_frame_size
* (float)enc
->rate
* 8.0;
1801 if (enc
->codec
->type
== CODEC_TYPE_AUDIO
&& enc
->frame_size
> 0)
1802 avg
/= enc
->frame_size
;
1803 url_fprintf(pb
, "<TR><TD>%s <TD> %d <TD> %"PRId64
" <TD> %0.1f\n",
1804 buf
, enc
->frame_number
, fdata
->data_count
, avg
/ 1000.0);
1806 url_fprintf(pb
, "</TABLE>\n");
1807 stream
= stream
->next_feed
;
1812 /* connection status */
1813 url_fprintf(pb
, "<H2>Connection Status</H2>\n");
1815 url_fprintf(pb
, "Number of connections: %d / %d<BR>\n",
1816 nb_connections
, nb_max_connections
);
1818 url_fprintf(pb
, "Bandwidth in use: %dk / %dk<BR>\n",
1819 current_bandwidth
, max_bandwidth
);
1821 url_fprintf(pb
, "<TABLE>\n");
1822 url_fprintf(pb
, "<TR><th>#<th>File<th>IP<th>Proto<th>State<th>Target bits/sec<th>Actual bits/sec<th>Bytes transferred\n");
1823 c1
= first_http_ctx
;
1825 while (c1
!= NULL
) {
1831 for (j
= 0; j
< c1
->stream
->nb_streams
; j
++) {
1832 if (!c1
->stream
->feed
)
1833 bitrate
+= c1
->stream
->streams
[j
]->codec
->bit_rate
;
1834 else if (c1
->feed_streams
[j
] >= 0)
1835 bitrate
+= c1
->stream
->feed
->streams
[c1
->feed_streams
[j
]]->codec
->bit_rate
;
1840 p
= inet_ntoa(c1
->from_addr
.sin_addr
);
1841 url_fprintf(pb
, "<TR><TD><B>%d</B><TD>%s%s<TD>%s<TD>%s<TD>%s<td align=right>",
1843 c1
->stream
? c1
->stream
->filename
: "",
1844 c1
->state
== HTTPSTATE_RECEIVE_DATA
? "(input)" : "",
1847 http_state
[c1
->state
]);
1848 fmt_bytecount(pb
, bitrate
);
1849 url_fprintf(pb
, "<td align=right>");
1850 fmt_bytecount(pb
, compute_datarate(&c1
->datarate
, c1
->data_count
) * 8);
1851 url_fprintf(pb
, "<td align=right>");
1852 fmt_bytecount(pb
, c1
->data_count
);
1853 url_fprintf(pb
, "\n");
1856 url_fprintf(pb
, "</TABLE>\n");
1861 url_fprintf(pb
, "<HR size=1 noshade>Generated at %s", p
);
1862 url_fprintf(pb
, "</BODY>\n</HTML>\n");
1864 len
= url_close_dyn_buf(pb
, &c
->pb_buffer
);
1865 c
->buffer_ptr
= c
->pb_buffer
;
1866 c
->buffer_end
= c
->pb_buffer
+ len
;
1869 /* check if the parser needs to be opened for stream i */
1870 static void open_parser(AVFormatContext
*s
, int i
)
1872 AVStream
*st
= s
->streams
[i
];
1875 if (!st
->codec
->codec
) {
1876 codec
= avcodec_find_decoder(st
->codec
->codec_id
);
1877 if (codec
&& (codec
->capabilities
& CODEC_CAP_PARSE_ONLY
)) {
1878 st
->codec
->parse_only
= 1;
1879 if (avcodec_open(st
->codec
, codec
) < 0)
1880 st
->codec
->parse_only
= 0;
1885 static int open_input_stream(HTTPContext
*c
, const char *info
)
1888 char input_filename
[1024];
1890 int buf_size
, i
, ret
;
1893 /* find file name */
1894 if (c
->stream
->feed
) {
1895 strcpy(input_filename
, c
->stream
->feed
->feed_filename
);
1896 buf_size
= FFM_PACKET_SIZE
;
1897 /* compute position (absolute time) */
1898 if (find_info_tag(buf
, sizeof(buf
), "date", info
))
1900 stream_pos
= parse_date(buf
, 0);
1901 if (stream_pos
== INT64_MIN
)
1904 else if (find_info_tag(buf
, sizeof(buf
), "buffer", info
)) {
1905 int prebuffer
= strtol(buf
, 0, 10);
1906 stream_pos
= av_gettime() - prebuffer
* (int64_t)1000000;
1908 stream_pos
= av_gettime() - c
->stream
->prebuffer
* (int64_t)1000;
1910 strcpy(input_filename
, c
->stream
->feed_filename
);
1912 /* compute position (relative time) */
1913 if (find_info_tag(buf
, sizeof(buf
), "date", info
))
1915 stream_pos
= parse_date(buf
, 1);
1916 if (stream_pos
== INT64_MIN
)
1922 if (input_filename
[0] == '\0')
1926 { time_t when
= stream_pos
/ 1000000;
1927 http_log("Stream pos = %"PRId64
", time=%s", stream_pos
, ctime(&when
));
1932 if ((ret
= av_open_input_file(&s
, input_filename
, c
->stream
->ifmt
,
1933 buf_size
, c
->stream
->ap_in
)) < 0) {
1934 http_log("could not open %s: %d\n", input_filename
, ret
);
1937 s
->flags
|= AVFMT_FLAG_GENPTS
;
1939 av_find_stream_info(c
->fmt_in
);
1941 /* open each parser */
1942 for(i
=0;i
<s
->nb_streams
;i
++)
1945 /* choose stream as clock source (we favorize video stream if
1946 present) for packet sending */
1947 c
->pts_stream_index
= 0;
1948 for(i
=0;i
<c
->stream
->nb_streams
;i
++) {
1949 if (c
->pts_stream_index
== 0 &&
1950 c
->stream
->streams
[i
]->codec
->codec_type
== CODEC_TYPE_VIDEO
) {
1951 c
->pts_stream_index
= i
;
1956 if (c
->fmt_in
->iformat
->read_seek
)
1957 c
->fmt_in
->iformat
->read_seek(c
->fmt_in
, 0, stream_pos
, 0);
1959 /* set the start time (needed for maxtime and RTP packet timing) */
1960 c
->start_time
= cur_time
;
1961 c
->first_pts
= AV_NOPTS_VALUE
;
1965 /* return the server clock (in us) */
1966 static int64_t get_server_clock(HTTPContext
*c
)
1968 /* compute current pts value from system time */
1969 return (cur_time
- c
->start_time
) * 1000;
1972 /* return the estimated time at which the current packet must be sent
1974 static int64_t get_packet_send_clock(HTTPContext
*c
)
1976 int bytes_left
, bytes_sent
, frame_bytes
;
1978 frame_bytes
= c
->cur_frame_bytes
;
1979 if (frame_bytes
<= 0)
1982 bytes_left
= c
->buffer_end
- c
->buffer_ptr
;
1983 bytes_sent
= frame_bytes
- bytes_left
;
1984 return c
->cur_pts
+ (c
->cur_frame_duration
* bytes_sent
) / frame_bytes
;
1989 static int http_prepare_data(HTTPContext
*c
)
1992 AVFormatContext
*ctx
;
1994 av_freep(&c
->pb_buffer
);
1996 case HTTPSTATE_SEND_DATA_HEADER
:
1997 memset(&c
->fmt_ctx
, 0, sizeof(c
->fmt_ctx
));
1998 av_strlcpy(c
->fmt_ctx
.author
, c
->stream
->author
,
1999 sizeof(c
->fmt_ctx
.author
));
2000 av_strlcpy(c
->fmt_ctx
.comment
, c
->stream
->comment
,
2001 sizeof(c
->fmt_ctx
.comment
));
2002 av_strlcpy(c
->fmt_ctx
.copyright
, c
->stream
->copyright
,
2003 sizeof(c
->fmt_ctx
.copyright
));
2004 av_strlcpy(c
->fmt_ctx
.title
, c
->stream
->title
,
2005 sizeof(c
->fmt_ctx
.title
));
2007 /* open output stream by using specified codecs */
2008 c
->fmt_ctx
.oformat
= c
->stream
->fmt
;
2009 c
->fmt_ctx
.nb_streams
= c
->stream
->nb_streams
;
2010 for(i
=0;i
<c
->fmt_ctx
.nb_streams
;i
++) {
2013 st
= av_mallocz(sizeof(AVStream
));
2014 st
->codec
= avcodec_alloc_context();
2015 c
->fmt_ctx
.streams
[i
] = st
;
2016 /* if file or feed, then just take streams from FFStream struct */
2017 if (!c
->stream
->feed
||
2018 c
->stream
->feed
== c
->stream
)
2019 src
= c
->stream
->streams
[i
];
2021 src
= c
->stream
->feed
->streams
[c
->stream
->feed_streams
[i
]];
2025 st
->codec
->frame_number
= 0; /* XXX: should be done in
2026 AVStream, not in codec */
2027 /* I'm pretty sure that this is not correct...
2028 * However, without it, we crash
2030 st
->codec
->coded_frame
= &dummy_frame
;
2032 c
->got_key_frame
= 0;
2034 /* prepare header and save header data in a stream */
2035 if (url_open_dyn_buf(&c
->fmt_ctx
.pb
) < 0) {
2036 /* XXX: potential leak */
2039 c
->fmt_ctx
.pb
->is_streamed
= 1;
2041 av_set_parameters(&c
->fmt_ctx
, NULL
);
2042 if (av_write_header(&c
->fmt_ctx
) < 0)
2045 len
= url_close_dyn_buf(c
->fmt_ctx
.pb
, &c
->pb_buffer
);
2046 c
->buffer_ptr
= c
->pb_buffer
;
2047 c
->buffer_end
= c
->pb_buffer
+ len
;
2049 c
->state
= HTTPSTATE_SEND_DATA
;
2050 c
->last_packet_sent
= 0;
2052 case HTTPSTATE_SEND_DATA
:
2053 /* find a new packet */
2057 /* read a packet from the input stream */
2058 if (c
->stream
->feed
)
2059 ffm_set_write_index(c
->fmt_in
,
2060 c
->stream
->feed
->feed_write_index
,
2061 c
->stream
->feed
->feed_size
);
2063 if (c
->stream
->max_time
&&
2064 c
->stream
->max_time
+ c
->start_time
- cur_time
< 0)
2065 /* We have timed out */
2066 c
->state
= HTTPSTATE_SEND_DATA_TRAILER
;
2069 if (av_read_frame(c
->fmt_in
, &pkt
) < 0) {
2070 if (c
->stream
->feed
&& c
->stream
->feed
->feed_opened
) {
2071 /* if coming from feed, it means we reached the end of the
2072 ffm file, so must wait for more data */
2073 c
->state
= HTTPSTATE_WAIT_FEED
;
2074 return 1; /* state changed */
2076 if (c
->stream
->loop
) {
2077 av_close_input_file(c
->fmt_in
);
2079 if (open_input_stream(c
, "") < 0)
2084 /* must send trailer now because eof or error */
2085 c
->state
= HTTPSTATE_SEND_DATA_TRAILER
;
2089 /* update first pts if needed */
2090 if (c
->first_pts
== AV_NOPTS_VALUE
) {
2091 c
->first_pts
= av_rescale_q(pkt
.dts
, c
->fmt_in
->streams
[pkt
.stream_index
]->time_base
, AV_TIME_BASE_Q
);
2092 c
->start_time
= cur_time
;
2094 /* send it to the appropriate stream */
2095 if (c
->stream
->feed
) {
2096 /* if coming from a feed, select the right stream */
2097 if (c
->switch_pending
) {
2098 c
->switch_pending
= 0;
2099 for(i
=0;i
<c
->stream
->nb_streams
;i
++) {
2100 if (c
->switch_feed_streams
[i
] == pkt
.stream_index
)
2101 if (pkt
.flags
& PKT_FLAG_KEY
)
2102 do_switch_stream(c
, i
);
2103 if (c
->switch_feed_streams
[i
] >= 0)
2104 c
->switch_pending
= 1;
2107 for(i
=0;i
<c
->stream
->nb_streams
;i
++) {
2108 if (c
->feed_streams
[i
] == pkt
.stream_index
) {
2109 pkt
.stream_index
= i
;
2110 if (pkt
.flags
& PKT_FLAG_KEY
)
2111 c
->got_key_frame
|= 1 << i
;
2112 /* See if we have all the key frames, then
2113 * we start to send. This logic is not quite
2114 * right, but it works for the case of a
2115 * single video stream with one or more
2116 * audio streams (for which every frame is
2117 * typically a key frame).
2119 if (!c
->stream
->send_on_key
||
2120 ((c
->got_key_frame
+ 1) >> c
->stream
->nb_streams
))
2125 AVCodecContext
*codec
;
2128 /* specific handling for RTP: we use several
2129 output stream (one for each RTP
2130 connection). XXX: need more abstract handling */
2131 if (c
->is_packetized
) {
2133 /* compute send time and duration */
2134 st
= c
->fmt_in
->streams
[pkt
.stream_index
];
2135 c
->cur_pts
= av_rescale_q(pkt
.dts
, st
->time_base
, AV_TIME_BASE_Q
);
2136 if (st
->start_time
!= AV_NOPTS_VALUE
)
2137 c
->cur_pts
-= av_rescale_q(st
->start_time
, st
->time_base
, AV_TIME_BASE_Q
);
2138 c
->cur_frame_duration
= av_rescale_q(pkt
.duration
, st
->time_base
, AV_TIME_BASE_Q
);
2140 printf("index=%d pts=%0.3f duration=%0.6f\n",
2142 (double)c
->cur_pts
/
2144 (double)c
->cur_frame_duration
/
2147 /* find RTP context */
2148 c
->packet_stream_index
= pkt
.stream_index
;
2149 ctx
= c
->rtp_ctx
[c
->packet_stream_index
];
2151 av_free_packet(&pkt
);
2154 codec
= ctx
->streams
[0]->codec
;
2155 /* only one stream per RTP connection */
2156 pkt
.stream_index
= 0;
2160 codec
= ctx
->streams
[pkt
.stream_index
]->codec
;
2163 codec
->coded_frame
->key_frame
= ((pkt
.flags
& PKT_FLAG_KEY
) != 0);
2164 if (c
->is_packetized
) {
2165 int max_packet_size
;
2166 if (c
->rtp_protocol
== RTSP_PROTOCOL_RTP_TCP
)
2167 max_packet_size
= RTSP_TCP_MAX_PACKET_SIZE
;
2169 max_packet_size
= url_get_max_packet_size(c
->rtp_handles
[c
->packet_stream_index
]);
2170 ret
= url_open_dyn_packet_buf(&ctx
->pb
, max_packet_size
);
2172 ret
= url_open_dyn_buf(&ctx
->pb
);
2175 /* XXX: potential leak */
2178 if (pkt
.dts
!= AV_NOPTS_VALUE
)
2179 pkt
.dts
= av_rescale_q(pkt
.dts
,
2180 c
->fmt_in
->streams
[pkt
.stream_index
]->time_base
,
2181 ctx
->streams
[pkt
.stream_index
]->time_base
);
2182 if (pkt
.pts
!= AV_NOPTS_VALUE
)
2183 pkt
.pts
= av_rescale_q(pkt
.pts
,
2184 c
->fmt_in
->streams
[pkt
.stream_index
]->time_base
,
2185 ctx
->streams
[pkt
.stream_index
]->time_base
);
2186 if (av_write_frame(ctx
, &pkt
))
2187 c
->state
= HTTPSTATE_SEND_DATA_TRAILER
;
2189 len
= url_close_dyn_buf(ctx
->pb
, &c
->pb_buffer
);
2190 c
->cur_frame_bytes
= len
;
2191 c
->buffer_ptr
= c
->pb_buffer
;
2192 c
->buffer_end
= c
->pb_buffer
+ len
;
2194 codec
->frame_number
++;
2196 av_free_packet(&pkt
);
2200 av_free_packet(&pkt
);
2206 case HTTPSTATE_SEND_DATA_TRAILER
:
2207 /* last packet test ? */
2208 if (c
->last_packet_sent
|| c
->is_packetized
)
2211 /* prepare header */
2212 if (url_open_dyn_buf(&ctx
->pb
) < 0) {
2213 /* XXX: potential leak */
2216 av_write_trailer(ctx
);
2217 len
= url_close_dyn_buf(ctx
->pb
, &c
->pb_buffer
);
2218 c
->buffer_ptr
= c
->pb_buffer
;
2219 c
->buffer_end
= c
->pb_buffer
+ len
;
2221 c
->last_packet_sent
= 1;
2227 /* should convert the format at the same time */
2228 /* send data starting at c->buffer_ptr to the output connection
2229 (either UDP or TCP connection) */
2230 static int http_send_data(HTTPContext
*c
)
2235 if (c
->buffer_ptr
>= c
->buffer_end
) {
2236 ret
= http_prepare_data(c
);
2240 /* state change requested */
2243 if (c
->is_packetized
) {
2244 /* RTP data output */
2245 len
= c
->buffer_end
- c
->buffer_ptr
;
2247 /* fail safe - should never happen */
2249 c
->buffer_ptr
= c
->buffer_end
;
2252 len
= (c
->buffer_ptr
[0] << 24) |
2253 (c
->buffer_ptr
[1] << 16) |
2254 (c
->buffer_ptr
[2] << 8) |
2256 if (len
> (c
->buffer_end
- c
->buffer_ptr
))
2258 if ((get_packet_send_clock(c
) - get_server_clock(c
)) > 0) {
2259 /* nothing to send yet: we can wait */
2263 c
->data_count
+= len
;
2264 update_datarate(&c
->datarate
, c
->data_count
);
2266 c
->stream
->bytes_served
+= len
;
2268 if (c
->rtp_protocol
== RTSP_PROTOCOL_RTP_TCP
) {
2269 /* RTP packets are sent inside the RTSP TCP connection */
2271 int interleaved_index
, size
;
2273 HTTPContext
*rtsp_c
;
2276 /* if no RTSP connection left, error */
2279 /* if already sending something, then wait. */
2280 if (rtsp_c
->state
!= RTSPSTATE_WAIT_REQUEST
)
2282 if (url_open_dyn_buf(&pb
) < 0)
2284 interleaved_index
= c
->packet_stream_index
* 2;
2285 /* RTCP packets are sent at odd indexes */
2286 if (c
->buffer_ptr
[1] == 200)
2287 interleaved_index
++;
2288 /* write RTSP TCP header */
2290 header
[1] = interleaved_index
;
2291 header
[2] = len
>> 8;
2293 put_buffer(pb
, header
, 4);
2294 /* write RTP packet data */
2296 put_buffer(pb
, c
->buffer_ptr
, len
);
2297 size
= url_close_dyn_buf(pb
, &c
->packet_buffer
);
2298 /* prepare asynchronous TCP sending */
2299 rtsp_c
->packet_buffer_ptr
= c
->packet_buffer
;
2300 rtsp_c
->packet_buffer_end
= c
->packet_buffer
+ size
;
2301 c
->buffer_ptr
+= len
;
2303 /* send everything we can NOW */
2304 len
= send(rtsp_c
->fd
, rtsp_c
->packet_buffer_ptr
,
2305 rtsp_c
->packet_buffer_end
- rtsp_c
->packet_buffer_ptr
, 0);
2307 rtsp_c
->packet_buffer_ptr
+= len
;
2308 if (rtsp_c
->packet_buffer_ptr
< rtsp_c
->packet_buffer_end
) {
2309 /* if we could not send all the data, we will
2310 send it later, so a new state is needed to
2311 "lock" the RTSP TCP connection */
2312 rtsp_c
->state
= RTSPSTATE_SEND_PACKET
;
2315 /* all data has been sent */
2316 av_freep(&c
->packet_buffer
);
2318 /* send RTP packet directly in UDP */
2320 url_write(c
->rtp_handles
[c
->packet_stream_index
],
2321 c
->buffer_ptr
, len
);
2322 c
->buffer_ptr
+= len
;
2323 /* here we continue as we can send several packets per 10 ms slot */
2326 /* TCP data output */
2327 len
= send(c
->fd
, c
->buffer_ptr
, c
->buffer_end
- c
->buffer_ptr
, 0);
2329 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
2330 ff_neterrno() != FF_NETERROR(EINTR
))
2331 /* error : close connection */
2336 c
->buffer_ptr
+= len
;
2338 c
->data_count
+= len
;
2339 update_datarate(&c
->datarate
, c
->data_count
);
2341 c
->stream
->bytes_served
+= len
;
2349 static int http_start_receive_data(HTTPContext
*c
)
2353 if (c
->stream
->feed_opened
)
2356 /* Don't permit writing to this one */
2357 if (c
->stream
->readonly
)
2361 fd
= open(c
->stream
->feed_filename
, O_RDWR
);
2366 c
->stream
->feed_write_index
= ffm_read_write_index(fd
);
2367 c
->stream
->feed_size
= lseek(fd
, 0, SEEK_END
);
2368 lseek(fd
, 0, SEEK_SET
);
2370 /* init buffer input */
2371 c
->buffer_ptr
= c
->buffer
;
2372 c
->buffer_end
= c
->buffer
+ FFM_PACKET_SIZE
;
2373 c
->stream
->feed_opened
= 1;
2377 static int http_receive_data(HTTPContext
*c
)
2381 if (c
->buffer_end
> c
->buffer_ptr
) {
2384 len
= recv(c
->fd
, c
->buffer_ptr
, c
->buffer_end
- c
->buffer_ptr
, 0);
2386 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
2387 ff_neterrno() != FF_NETERROR(EINTR
))
2388 /* error : close connection */
2390 } else if (len
== 0)
2391 /* end of connection : close it */
2394 c
->buffer_ptr
+= len
;
2395 c
->data_count
+= len
;
2396 update_datarate(&c
->datarate
, c
->data_count
);
2400 if (c
->buffer_ptr
- c
->buffer
>= 2 && c
->data_count
> FFM_PACKET_SIZE
) {
2401 if (c
->buffer
[0] != 'f' ||
2402 c
->buffer
[1] != 'm') {
2403 http_log("Feed stream has become desynchronized -- disconnecting\n");
2408 if (c
->buffer_ptr
>= c
->buffer_end
) {
2409 FFStream
*feed
= c
->stream
;
2410 /* a packet has been received : write it in the store, except
2412 if (c
->data_count
> FFM_PACKET_SIZE
) {
2414 // printf("writing pos=0x%"PRIx64" size=0x%"PRIx64"\n", feed->feed_write_index, feed->feed_size);
2415 /* XXX: use llseek or url_seek */
2416 lseek(c
->feed_fd
, feed
->feed_write_index
, SEEK_SET
);
2417 write(c
->feed_fd
, c
->buffer
, FFM_PACKET_SIZE
);
2419 feed
->feed_write_index
+= FFM_PACKET_SIZE
;
2420 /* update file size */
2421 if (feed
->feed_write_index
> c
->stream
->feed_size
)
2422 feed
->feed_size
= feed
->feed_write_index
;
2424 /* handle wrap around if max file size reached */
2425 if (c
->stream
->feed_max_size
&& feed
->feed_write_index
>= c
->stream
->feed_max_size
)
2426 feed
->feed_write_index
= FFM_PACKET_SIZE
;
2429 ffm_write_write_index(c
->feed_fd
, feed
->feed_write_index
);
2431 /* wake up any waiting connections */
2432 for(c1
= first_http_ctx
; c1
!= NULL
; c1
= c1
->next
) {
2433 if (c1
->state
== HTTPSTATE_WAIT_FEED
&&
2434 c1
->stream
->feed
== c
->stream
->feed
)
2435 c1
->state
= HTTPSTATE_SEND_DATA
;
2438 /* We have a header in our hands that contains useful data */
2440 AVInputFormat
*fmt_in
;
2443 memset(&s
, 0, sizeof(s
));
2445 url_open_buf(&s
.pb
, c
->buffer
, c
->buffer_end
- c
->buffer
, URL_RDONLY
);
2446 s
.pb
->is_streamed
= 1;
2448 /* use feed output format name to find corresponding input format */
2449 fmt_in
= av_find_input_format(feed
->fmt
->name
);
2453 if (fmt_in
->priv_data_size
> 0) {
2454 s
.priv_data
= av_mallocz(fmt_in
->priv_data_size
);
2460 if (fmt_in
->read_header(&s
, 0) < 0) {
2461 av_freep(&s
.priv_data
);
2465 /* Now we have the actual streams */
2466 if (s
.nb_streams
!= feed
->nb_streams
) {
2467 av_freep(&s
.priv_data
);
2470 for (i
= 0; i
< s
.nb_streams
; i
++)
2471 memcpy(feed
->streams
[i
]->codec
,
2472 s
.streams
[i
]->codec
, sizeof(AVCodecContext
));
2473 av_freep(&s
.priv_data
);
2475 c
->buffer_ptr
= c
->buffer
;
2480 c
->stream
->feed_opened
= 0;
2485 /********************************************************************/
2488 static void rtsp_reply_header(HTTPContext
*c
, enum RTSPStatusCode error_number
)
2495 switch(error_number
) {
2496 case RTSP_STATUS_OK
:
2499 case RTSP_STATUS_METHOD
:
2500 str
= "Method Not Allowed";
2502 case RTSP_STATUS_BANDWIDTH
:
2503 str
= "Not Enough Bandwidth";
2505 case RTSP_STATUS_SESSION
:
2506 str
= "Session Not Found";
2508 case RTSP_STATUS_STATE
:
2509 str
= "Method Not Valid in This State";
2511 case RTSP_STATUS_AGGREGATE
:
2512 str
= "Aggregate operation not allowed";
2514 case RTSP_STATUS_ONLY_AGGREGATE
:
2515 str
= "Only aggregate operation allowed";
2517 case RTSP_STATUS_TRANSPORT
:
2518 str
= "Unsupported transport";
2520 case RTSP_STATUS_INTERNAL
:
2521 str
= "Internal Server Error";
2523 case RTSP_STATUS_SERVICE
:
2524 str
= "Service Unavailable";
2526 case RTSP_STATUS_VERSION
:
2527 str
= "RTSP Version not supported";
2530 str
= "Unknown Error";
2534 url_fprintf(c
->pb
, "RTSP/1.0 %d %s\r\n", error_number
, str
);
2535 url_fprintf(c
->pb
, "CSeq: %d\r\n", c
->seq
);
2537 /* output GMT time */
2541 p
= buf2
+ strlen(p
) - 1;
2544 url_fprintf(c
->pb
, "Date: %s GMT\r\n", buf2
);
2547 static void rtsp_reply_error(HTTPContext
*c
, enum RTSPStatusCode error_number
)
2549 rtsp_reply_header(c
, error_number
);
2550 url_fprintf(c
->pb
, "\r\n");
2553 static int rtsp_parse_request(HTTPContext
*c
)
2555 const char *p
, *p1
, *p2
;
2561 RTSPHeader header1
, *header
= &header1
;
2563 c
->buffer_ptr
[0] = '\0';
2566 get_word(cmd
, sizeof(cmd
), &p
);
2567 get_word(url
, sizeof(url
), &p
);
2568 get_word(protocol
, sizeof(protocol
), &p
);
2570 av_strlcpy(c
->method
, cmd
, sizeof(c
->method
));
2571 av_strlcpy(c
->url
, url
, sizeof(c
->url
));
2572 av_strlcpy(c
->protocol
, protocol
, sizeof(c
->protocol
));
2574 if (url_open_dyn_buf(&c
->pb
) < 0) {
2575 /* XXX: cannot do more */
2576 c
->pb
= NULL
; /* safety */
2580 /* check version name */
2581 if (strcmp(protocol
, "RTSP/1.0") != 0) {
2582 rtsp_reply_error(c
, RTSP_STATUS_VERSION
);
2586 /* parse each header line */
2587 memset(header
, 0, sizeof(RTSPHeader
));
2588 /* skip to next line */
2589 while (*p
!= '\n' && *p
!= '\0')
2593 while (*p
!= '\0') {
2594 p1
= strchr(p
, '\n');
2598 if (p2
> p
&& p2
[-1] == '\r')
2600 /* skip empty line */
2604 if (len
> sizeof(line
) - 1)
2605 len
= sizeof(line
) - 1;
2606 memcpy(line
, p
, len
);
2608 rtsp_parse_line(header
, line
);
2612 /* handle sequence number */
2613 c
->seq
= header
->seq
;
2615 if (!strcmp(cmd
, "DESCRIBE"))
2616 rtsp_cmd_describe(c
, url
);
2617 else if (!strcmp(cmd
, "OPTIONS"))
2618 rtsp_cmd_options(c
, url
);
2619 else if (!strcmp(cmd
, "SETUP"))
2620 rtsp_cmd_setup(c
, url
, header
);
2621 else if (!strcmp(cmd
, "PLAY"))
2622 rtsp_cmd_play(c
, url
, header
);
2623 else if (!strcmp(cmd
, "PAUSE"))
2624 rtsp_cmd_pause(c
, url
, header
);
2625 else if (!strcmp(cmd
, "TEARDOWN"))
2626 rtsp_cmd_teardown(c
, url
, header
);
2628 rtsp_reply_error(c
, RTSP_STATUS_METHOD
);
2631 len
= url_close_dyn_buf(c
->pb
, &c
->pb_buffer
);
2632 c
->pb
= NULL
; /* safety */
2634 /* XXX: cannot do more */
2637 c
->buffer_ptr
= c
->pb_buffer
;
2638 c
->buffer_end
= c
->pb_buffer
+ len
;
2639 c
->state
= RTSPSTATE_SEND_REPLY
;
2643 static int prepare_sdp_description(FFStream
*stream
, uint8_t **pbuffer
,
2644 struct in_addr my_ip
)
2646 AVFormatContext
*avc
;
2647 AVStream avs
[MAX_STREAMS
];
2650 avc
= av_alloc_format_context();
2654 if (stream
->title
[0] != 0) {
2655 av_strlcpy(avc
->title
, stream
->title
, sizeof(avc
->title
));
2657 av_strlcpy(avc
->title
, "No Title", sizeof(avc
->title
));
2659 avc
->nb_streams
= stream
->nb_streams
;
2660 if (stream
->is_multicast
) {
2661 snprintf(avc
->filename
, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2662 inet_ntoa(stream
->multicast_ip
),
2663 stream
->multicast_port
, stream
->multicast_ttl
);
2666 for(i
= 0; i
< stream
->nb_streams
; i
++) {
2667 avc
->streams
[i
] = &avs
[i
];
2668 avc
->streams
[i
]->codec
= stream
->streams
[i
]->codec
;
2670 *pbuffer
= av_mallocz(2048);
2671 avf_sdp_create(&avc
, 1, *pbuffer
, 2048);
2674 return strlen(*pbuffer
);
2677 static void rtsp_cmd_options(HTTPContext
*c
, const char *url
)
2679 // rtsp_reply_header(c, RTSP_STATUS_OK);
2680 url_fprintf(c
->pb
, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK
, "OK");
2681 url_fprintf(c
->pb
, "CSeq: %d\r\n", c
->seq
);
2682 url_fprintf(c
->pb
, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2683 url_fprintf(c
->pb
, "\r\n");
2686 static void rtsp_cmd_describe(HTTPContext
*c
, const char *url
)
2692 int content_length
, len
;
2693 struct sockaddr_in my_addr
;
2695 /* find which url is asked */
2696 url_split(NULL
, 0, NULL
, 0, NULL
, 0, NULL
, path1
, sizeof(path1
), url
);
2701 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
2702 if (!stream
->is_feed
&&
2703 stream
->fmt
&& !strcmp(stream
->fmt
->name
, "rtp") &&
2704 !strcmp(path
, stream
->filename
)) {
2708 /* no stream found */
2709 rtsp_reply_error(c
, RTSP_STATUS_SERVICE
); /* XXX: right error ? */
2713 /* prepare the media description in sdp format */
2715 /* get the host IP */
2716 len
= sizeof(my_addr
);
2717 getsockname(c
->fd
, (struct sockaddr
*)&my_addr
, &len
);
2718 content_length
= prepare_sdp_description(stream
, &content
, my_addr
.sin_addr
);
2719 if (content_length
< 0) {
2720 rtsp_reply_error(c
, RTSP_STATUS_INTERNAL
);
2723 rtsp_reply_header(c
, RTSP_STATUS_OK
);
2724 url_fprintf(c
->pb
, "Content-Type: application/sdp\r\n");
2725 url_fprintf(c
->pb
, "Content-Length: %d\r\n", content_length
);
2726 url_fprintf(c
->pb
, "\r\n");
2727 put_buffer(c
->pb
, content
, content_length
);
2730 static HTTPContext
*find_rtp_session(const char *session_id
)
2734 if (session_id
[0] == '\0')
2737 for(c
= first_http_ctx
; c
!= NULL
; c
= c
->next
) {
2738 if (!strcmp(c
->session_id
, session_id
))
2744 static RTSPTransportField
*find_transport(RTSPHeader
*h
, enum RTSPProtocol protocol
)
2746 RTSPTransportField
*th
;
2749 for(i
=0;i
<h
->nb_transports
;i
++) {
2750 th
= &h
->transports
[i
];
2751 if (th
->protocol
== protocol
)
2757 static void rtsp_cmd_setup(HTTPContext
*c
, const char *url
,
2761 int stream_index
, port
;
2766 RTSPTransportField
*th
;
2767 struct sockaddr_in dest_addr
;
2768 RTSPActionServerSetup setup
;
2770 /* find which url is asked */
2771 url_split(NULL
, 0, NULL
, 0, NULL
, 0, NULL
, path1
, sizeof(path1
), url
);
2776 /* now check each stream */
2777 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
2778 if (!stream
->is_feed
&&
2779 stream
->fmt
&& !strcmp(stream
->fmt
->name
, "rtp")) {
2780 /* accept aggregate filenames only if single stream */
2781 if (!strcmp(path
, stream
->filename
)) {
2782 if (stream
->nb_streams
!= 1) {
2783 rtsp_reply_error(c
, RTSP_STATUS_AGGREGATE
);
2790 for(stream_index
= 0; stream_index
< stream
->nb_streams
;
2792 snprintf(buf
, sizeof(buf
), "%s/streamid=%d",
2793 stream
->filename
, stream_index
);
2794 if (!strcmp(path
, buf
))
2799 /* no stream found */
2800 rtsp_reply_error(c
, RTSP_STATUS_SERVICE
); /* XXX: right error ? */
2804 /* generate session id if needed */
2805 if (h
->session_id
[0] == '\0')
2806 snprintf(h
->session_id
, sizeof(h
->session_id
), "%08x%08x",
2807 av_random(&random_state
), av_random(&random_state
));
2809 /* find rtp session, and create it if none found */
2810 rtp_c
= find_rtp_session(h
->session_id
);
2812 /* always prefer UDP */
2813 th
= find_transport(h
, RTSP_PROTOCOL_RTP_UDP
);
2815 th
= find_transport(h
, RTSP_PROTOCOL_RTP_TCP
);
2817 rtsp_reply_error(c
, RTSP_STATUS_TRANSPORT
);
2822 rtp_c
= rtp_new_connection(&c
->from_addr
, stream
, h
->session_id
,
2825 rtsp_reply_error(c
, RTSP_STATUS_BANDWIDTH
);
2829 /* open input stream */
2830 if (open_input_stream(rtp_c
, "") < 0) {
2831 rtsp_reply_error(c
, RTSP_STATUS_INTERNAL
);
2836 /* test if stream is OK (test needed because several SETUP needs
2837 to be done for a given file) */
2838 if (rtp_c
->stream
!= stream
) {
2839 rtsp_reply_error(c
, RTSP_STATUS_SERVICE
);
2843 /* test if stream is already set up */
2844 if (rtp_c
->rtp_ctx
[stream_index
]) {
2845 rtsp_reply_error(c
, RTSP_STATUS_STATE
);
2849 /* check transport */
2850 th
= find_transport(h
, rtp_c
->rtp_protocol
);
2851 if (!th
|| (th
->protocol
== RTSP_PROTOCOL_RTP_UDP
&&
2852 th
->client_port_min
<= 0)) {
2853 rtsp_reply_error(c
, RTSP_STATUS_TRANSPORT
);
2857 /* setup default options */
2858 setup
.transport_option
[0] = '\0';
2859 dest_addr
= rtp_c
->from_addr
;
2860 dest_addr
.sin_port
= htons(th
->client_port_min
);
2863 if (rtp_new_av_stream(rtp_c
, stream_index
, &dest_addr
, c
) < 0) {
2864 rtsp_reply_error(c
, RTSP_STATUS_TRANSPORT
);
2868 /* now everything is OK, so we can send the connection parameters */
2869 rtsp_reply_header(c
, RTSP_STATUS_OK
);
2871 url_fprintf(c
->pb
, "Session: %s\r\n", rtp_c
->session_id
);
2873 switch(rtp_c
->rtp_protocol
) {
2874 case RTSP_PROTOCOL_RTP_UDP
:
2875 port
= rtp_get_local_port(rtp_c
->rtp_handles
[stream_index
]);
2876 url_fprintf(c
->pb
, "Transport: RTP/AVP/UDP;unicast;"
2877 "client_port=%d-%d;server_port=%d-%d",
2878 th
->client_port_min
, th
->client_port_min
+ 1,
2881 case RTSP_PROTOCOL_RTP_TCP
:
2882 url_fprintf(c
->pb
, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
2883 stream_index
* 2, stream_index
* 2 + 1);
2888 if (setup
.transport_option
[0] != '\0')
2889 url_fprintf(c
->pb
, ";%s", setup
.transport_option
);
2890 url_fprintf(c
->pb
, "\r\n");
2893 url_fprintf(c
->pb
, "\r\n");
2897 /* find an rtp connection by using the session ID. Check consistency
2899 static HTTPContext
*find_rtp_session_with_url(const char *url
,
2900 const char *session_id
)
2908 rtp_c
= find_rtp_session(session_id
);
2912 /* find which url is asked */
2913 url_split(NULL
, 0, NULL
, 0, NULL
, 0, NULL
, path1
, sizeof(path1
), url
);
2917 if(!strcmp(path
, rtp_c
->stream
->filename
)) return rtp_c
;
2918 for(s
=0; s
<rtp_c
->stream
->nb_streams
; ++s
) {
2919 snprintf(buf
, sizeof(buf
), "%s/streamid=%d",
2920 rtp_c
->stream
->filename
, s
);
2921 if(!strncmp(path
, buf
, sizeof(buf
))) {
2922 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
2929 static void rtsp_cmd_play(HTTPContext
*c
, const char *url
, RTSPHeader
*h
)
2933 rtp_c
= find_rtp_session_with_url(url
, h
->session_id
);
2935 rtsp_reply_error(c
, RTSP_STATUS_SESSION
);
2939 if (rtp_c
->state
!= HTTPSTATE_SEND_DATA
&&
2940 rtp_c
->state
!= HTTPSTATE_WAIT_FEED
&&
2941 rtp_c
->state
!= HTTPSTATE_READY
) {
2942 rtsp_reply_error(c
, RTSP_STATUS_STATE
);
2947 /* XXX: seek in stream */
2948 if (h
->range_start
!= AV_NOPTS_VALUE
) {
2949 printf("range_start=%0.3f\n", (double)h
->range_start
/ AV_TIME_BASE
);
2950 av_seek_frame(rtp_c
->fmt_in
, -1, h
->range_start
);
2954 rtp_c
->state
= HTTPSTATE_SEND_DATA
;
2956 /* now everything is OK, so we can send the connection parameters */
2957 rtsp_reply_header(c
, RTSP_STATUS_OK
);
2959 url_fprintf(c
->pb
, "Session: %s\r\n", rtp_c
->session_id
);
2960 url_fprintf(c
->pb
, "\r\n");
2963 static void rtsp_cmd_pause(HTTPContext
*c
, const char *url
, RTSPHeader
*h
)
2967 rtp_c
= find_rtp_session_with_url(url
, h
->session_id
);
2969 rtsp_reply_error(c
, RTSP_STATUS_SESSION
);
2973 if (rtp_c
->state
!= HTTPSTATE_SEND_DATA
&&
2974 rtp_c
->state
!= HTTPSTATE_WAIT_FEED
) {
2975 rtsp_reply_error(c
, RTSP_STATUS_STATE
);
2979 rtp_c
->state
= HTTPSTATE_READY
;
2980 rtp_c
->first_pts
= AV_NOPTS_VALUE
;
2981 /* now everything is OK, so we can send the connection parameters */
2982 rtsp_reply_header(c
, RTSP_STATUS_OK
);
2984 url_fprintf(c
->pb
, "Session: %s\r\n", rtp_c
->session_id
);
2985 url_fprintf(c
->pb
, "\r\n");
2988 static void rtsp_cmd_teardown(HTTPContext
*c
, const char *url
, RTSPHeader
*h
)
2991 char session_id
[32];
2993 rtp_c
= find_rtp_session_with_url(url
, h
->session_id
);
2995 rtsp_reply_error(c
, RTSP_STATUS_SESSION
);
2999 av_strlcpy(session_id
, rtp_c
->session_id
, sizeof(session_id
));
3001 /* abort the session */
3002 close_connection(rtp_c
);
3004 /* now everything is OK, so we can send the connection parameters */
3005 rtsp_reply_header(c
, RTSP_STATUS_OK
);
3007 url_fprintf(c
->pb
, "Session: %s\r\n", session_id
);
3008 url_fprintf(c
->pb
, "\r\n");
3012 /********************************************************************/
3015 static HTTPContext
*rtp_new_connection(struct sockaddr_in
*from_addr
,
3016 FFStream
*stream
, const char *session_id
,
3017 enum RTSPProtocol rtp_protocol
)
3019 HTTPContext
*c
= NULL
;
3020 const char *proto_str
;
3022 /* XXX: should output a warning page when coming
3023 close to the connection limit */
3024 if (nb_connections
>= nb_max_connections
)
3027 /* add a new connection */
3028 c
= av_mallocz(sizeof(HTTPContext
));
3033 c
->poll_entry
= NULL
;
3034 c
->from_addr
= *from_addr
;
3035 c
->buffer_size
= IOBUFFER_INIT_SIZE
;
3036 c
->buffer
= av_malloc(c
->buffer_size
);
3041 av_strlcpy(c
->session_id
, session_id
, sizeof(c
->session_id
));
3042 c
->state
= HTTPSTATE_READY
;
3043 c
->is_packetized
= 1;
3044 c
->rtp_protocol
= rtp_protocol
;
3046 /* protocol is shown in statistics */
3047 switch(c
->rtp_protocol
) {
3048 case RTSP_PROTOCOL_RTP_UDP_MULTICAST
:
3049 proto_str
= "MCAST";
3051 case RTSP_PROTOCOL_RTP_UDP
:
3054 case RTSP_PROTOCOL_RTP_TCP
:
3061 av_strlcpy(c
->protocol
, "RTP/", sizeof(c
->protocol
));
3062 av_strlcat(c
->protocol
, proto_str
, sizeof(c
->protocol
));
3064 current_bandwidth
+= stream
->bandwidth
;
3066 c
->next
= first_http_ctx
;
3078 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3079 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3081 static int rtp_new_av_stream(HTTPContext
*c
,
3082 int stream_index
, struct sockaddr_in
*dest_addr
,
3083 HTTPContext
*rtsp_c
)
3085 AVFormatContext
*ctx
;
3091 int max_packet_size
;
3093 /* now we can open the relevant output stream */
3094 ctx
= av_alloc_format_context();
3097 ctx
->oformat
= guess_format("rtp", NULL
, NULL
);
3099 st
= av_mallocz(sizeof(AVStream
));
3102 st
->codec
= avcodec_alloc_context();
3103 ctx
->nb_streams
= 1;
3104 ctx
->streams
[0] = st
;
3106 if (!c
->stream
->feed
||
3107 c
->stream
->feed
== c
->stream
)
3108 memcpy(st
, c
->stream
->streams
[stream_index
], sizeof(AVStream
));
3111 c
->stream
->feed
->streams
[c
->stream
->feed_streams
[stream_index
]],
3113 st
->priv_data
= NULL
;
3115 /* build destination RTP address */
3116 ipaddr
= inet_ntoa(dest_addr
->sin_addr
);
3118 switch(c
->rtp_protocol
) {
3119 case RTSP_PROTOCOL_RTP_UDP
:
3120 case RTSP_PROTOCOL_RTP_UDP_MULTICAST
:
3123 /* XXX: also pass as parameter to function ? */
3124 if (c
->stream
->is_multicast
) {
3126 ttl
= c
->stream
->multicast_ttl
;
3129 snprintf(ctx
->filename
, sizeof(ctx
->filename
),
3130 "rtp://%s:%d?multicast=1&ttl=%d",
3131 ipaddr
, ntohs(dest_addr
->sin_port
), ttl
);
3133 snprintf(ctx
->filename
, sizeof(ctx
->filename
),
3134 "rtp://%s:%d", ipaddr
, ntohs(dest_addr
->sin_port
));
3137 if (url_open(&h
, ctx
->filename
, URL_WRONLY
) < 0)
3139 c
->rtp_handles
[stream_index
] = h
;
3140 max_packet_size
= url_get_max_packet_size(h
);
3142 case RTSP_PROTOCOL_RTP_TCP
:
3145 max_packet_size
= RTSP_TCP_MAX_PACKET_SIZE
;
3151 http_log("%s:%d - - [%s] \"PLAY %s/streamid=%d %s\"\n",
3152 ipaddr
, ntohs(dest_addr
->sin_port
),
3154 c
->stream
->filename
, stream_index
, c
->protocol
);
3156 /* normally, no packets should be output here, but the packet size may be checked */
3157 if (url_open_dyn_packet_buf(&ctx
->pb
, max_packet_size
) < 0) {
3158 /* XXX: close stream */
3161 av_set_parameters(ctx
, NULL
);
3162 if (av_write_header(ctx
) < 0) {
3169 url_close_dyn_buf(ctx
->pb
, &dummy_buf
);
3172 c
->rtp_ctx
[stream_index
] = ctx
;
3176 /********************************************************************/
3177 /* ffserver initialization */
3179 static AVStream
*add_av_stream1(FFStream
*stream
, AVCodecContext
*codec
)
3183 fst
= av_mallocz(sizeof(AVStream
));
3186 fst
->codec
= avcodec_alloc_context();
3187 fst
->priv_data
= av_mallocz(sizeof(FeedData
));
3188 memcpy(fst
->codec
, codec
, sizeof(AVCodecContext
));
3189 fst
->codec
->coded_frame
= &dummy_frame
;
3190 fst
->index
= stream
->nb_streams
;
3191 av_set_pts_info(fst
, 33, 1, 90000);
3192 stream
->streams
[stream
->nb_streams
++] = fst
;
3196 /* return the stream number in the feed */
3197 static int add_av_stream(FFStream
*feed
, AVStream
*st
)
3200 AVCodecContext
*av
, *av1
;
3204 for(i
=0;i
<feed
->nb_streams
;i
++) {
3205 st
= feed
->streams
[i
];
3207 if (av1
->codec_id
== av
->codec_id
&&
3208 av1
->codec_type
== av
->codec_type
&&
3209 av1
->bit_rate
== av
->bit_rate
) {
3211 switch(av
->codec_type
) {
3212 case CODEC_TYPE_AUDIO
:
3213 if (av1
->channels
== av
->channels
&&
3214 av1
->sample_rate
== av
->sample_rate
)
3217 case CODEC_TYPE_VIDEO
:
3218 if (av1
->width
== av
->width
&&
3219 av1
->height
== av
->height
&&
3220 av1
->time_base
.den
== av
->time_base
.den
&&
3221 av1
->time_base
.num
== av
->time_base
.num
&&
3222 av1
->gop_size
== av
->gop_size
)
3231 fst
= add_av_stream1(feed
, av
);
3234 return feed
->nb_streams
- 1;
3239 static void remove_stream(FFStream
*stream
)
3243 while (*ps
!= NULL
) {
3251 /* specific mpeg4 handling : we extract the raw parameters */
3252 static void extract_mpeg4_header(AVFormatContext
*infile
)
3254 int mpeg4_count
, i
, size
;
3260 for(i
=0;i
<infile
->nb_streams
;i
++) {
3261 st
= infile
->streams
[i
];
3262 if (st
->codec
->codec_id
== CODEC_ID_MPEG4
&&
3263 st
->codec
->extradata_size
== 0) {
3270 printf("MPEG4 without extra data: trying to find header in %s\n", infile
->filename
);
3271 while (mpeg4_count
> 0) {
3272 if (av_read_packet(infile
, &pkt
) < 0)
3274 st
= infile
->streams
[pkt
.stream_index
];
3275 if (st
->codec
->codec_id
== CODEC_ID_MPEG4
&&
3276 st
->codec
->extradata_size
== 0) {
3277 av_freep(&st
->codec
->extradata
);
3278 /* fill extradata with the header */
3279 /* XXX: we make hard suppositions here ! */
3281 while (p
< pkt
.data
+ pkt
.size
- 4) {
3282 /* stop when vop header is found */
3283 if (p
[0] == 0x00 && p
[1] == 0x00 &&
3284 p
[2] == 0x01 && p
[3] == 0xb6) {
3285 size
= p
- pkt
.data
;
3286 // av_hex_dump_log(infile, AV_LOG_DEBUG, pkt.data, size);
3287 st
->codec
->extradata
= av_malloc(size
);
3288 st
->codec
->extradata_size
= size
;
3289 memcpy(st
->codec
->extradata
, pkt
.data
, size
);
3296 av_free_packet(&pkt
);
3300 /* compute the needed AVStream for each file */
3301 static void build_file_streams(void)
3303 FFStream
*stream
, *stream_next
;
3304 AVFormatContext
*infile
;
3307 /* gather all streams */
3308 for(stream
= first_stream
; stream
!= NULL
; stream
= stream_next
) {
3309 stream_next
= stream
->next
;
3310 if (stream
->stream_type
== STREAM_TYPE_LIVE
&&
3312 /* the stream comes from a file */
3313 /* try to open the file */
3315 stream
->ap_in
= av_mallocz(sizeof(AVFormatParameters
));
3316 if (stream
->fmt
&& !strcmp(stream
->fmt
->name
, "rtp")) {
3317 /* specific case : if transport stream output to RTP,
3318 we use a raw transport stream reader */
3319 stream
->ap_in
->mpeg2ts_raw
= 1;
3320 stream
->ap_in
->mpeg2ts_compute_pcr
= 1;
3323 if ((ret
= av_open_input_file(&infile
, stream
->feed_filename
,
3324 stream
->ifmt
, 0, stream
->ap_in
)) < 0) {
3325 http_log("could not open %s: %d\n", stream
->feed_filename
, ret
);
3326 /* remove stream (no need to spend more time on it) */
3328 remove_stream(stream
);
3330 /* find all the AVStreams inside and reference them in
3332 if (av_find_stream_info(infile
) < 0) {
3333 http_log("Could not find codec parameters from '%s'",
3334 stream
->feed_filename
);
3335 av_close_input_file(infile
);
3338 extract_mpeg4_header(infile
);
3340 for(i
=0;i
<infile
->nb_streams
;i
++)
3341 add_av_stream1(stream
, infile
->streams
[i
]->codec
);
3343 av_close_input_file(infile
);
3349 /* compute the needed AVStream for each feed */
3350 static void build_feed_streams(void)
3352 FFStream
*stream
, *feed
;
3355 /* gather all streams */
3356 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
3357 feed
= stream
->feed
;
3359 if (!stream
->is_feed
) {
3360 /* we handle a stream coming from a feed */
3361 for(i
=0;i
<stream
->nb_streams
;i
++)
3362 stream
->feed_streams
[i
] = add_av_stream(feed
, stream
->streams
[i
]);
3367 /* gather all streams */
3368 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
3369 feed
= stream
->feed
;
3371 if (stream
->is_feed
) {
3372 for(i
=0;i
<stream
->nb_streams
;i
++)
3373 stream
->feed_streams
[i
] = i
;
3378 /* create feed files if needed */
3379 for(feed
= first_feed
; feed
!= NULL
; feed
= feed
->next_feed
) {
3382 if (url_exist(feed
->feed_filename
)) {
3383 /* See if it matches */
3387 if (av_open_input_file(&s
, feed
->feed_filename
, NULL
, FFM_PACKET_SIZE
, NULL
) >= 0) {
3388 /* Now see if it matches */
3389 if (s
->nb_streams
== feed
->nb_streams
) {
3391 for(i
=0;i
<s
->nb_streams
;i
++) {
3393 sf
= feed
->streams
[i
];
3396 if (sf
->index
!= ss
->index
||
3398 printf("Index & Id do not match for stream %d (%s)\n",
3399 i
, feed
->feed_filename
);
3402 AVCodecContext
*ccf
, *ccs
;
3406 #define CHECK_CODEC(x) (ccf->x != ccs->x)
3408 if (CHECK_CODEC(codec
) || CHECK_CODEC(codec_type
)) {
3409 printf("Codecs do not match for stream %d\n", i
);
3411 } else if (CHECK_CODEC(bit_rate
) || CHECK_CODEC(flags
)) {
3412 printf("Codec bitrates do not match for stream %d\n", i
);
3414 } else if (ccf
->codec_type
== CODEC_TYPE_VIDEO
) {
3415 if (CHECK_CODEC(time_base
.den
) ||
3416 CHECK_CODEC(time_base
.num
) ||
3417 CHECK_CODEC(width
) ||
3418 CHECK_CODEC(height
)) {
3419 printf("Codec width, height and framerate do not match for stream %d\n", i
);
3422 } else if (ccf
->codec_type
== CODEC_TYPE_AUDIO
) {
3423 if (CHECK_CODEC(sample_rate
) ||
3424 CHECK_CODEC(channels
) ||
3425 CHECK_CODEC(frame_size
)) {
3426 printf("Codec sample_rate, channels, frame_size do not match for stream %d\n", i
);
3430 printf("Unknown codec type\n");
3438 printf("Deleting feed file '%s' as stream counts differ (%d != %d)\n",
3439 feed
->feed_filename
, s
->nb_streams
, feed
->nb_streams
);
3441 av_close_input_file(s
);
3443 printf("Deleting feed file '%s' as it appears to be corrupt\n",
3444 feed
->feed_filename
);
3447 if (feed
->readonly
) {
3448 printf("Unable to delete feed file '%s' as it is marked readonly\n",
3449 feed
->feed_filename
);
3452 unlink(feed
->feed_filename
);
3455 if (!url_exist(feed
->feed_filename
)) {
3456 AVFormatContext s1
, *s
= &s1
;
3458 if (feed
->readonly
) {
3459 printf("Unable to create feed file '%s' as it is marked readonly\n",
3460 feed
->feed_filename
);
3464 /* only write the header of the ffm file */
3465 if (url_fopen(&s
->pb
, feed
->feed_filename
, URL_WRONLY
) < 0) {
3466 fprintf(stderr
, "Could not open output feed file '%s'\n",
3467 feed
->feed_filename
);
3470 s
->oformat
= feed
->fmt
;
3471 s
->nb_streams
= feed
->nb_streams
;
3472 for(i
=0;i
<s
->nb_streams
;i
++) {
3474 st
= feed
->streams
[i
];
3477 av_set_parameters(s
, NULL
);
3478 if (av_write_header(s
) < 0) {
3479 fprintf(stderr
, "Container doesn't supports the required parameters\n");
3482 /* XXX: need better api */
3483 av_freep(&s
->priv_data
);
3486 /* get feed size and write index */
3487 fd
= open(feed
->feed_filename
, O_RDONLY
);
3489 fprintf(stderr
, "Could not open output feed file '%s'\n",
3490 feed
->feed_filename
);
3494 feed
->feed_write_index
= ffm_read_write_index(fd
);
3495 feed
->feed_size
= lseek(fd
, 0, SEEK_END
);
3496 /* ensure that we do not wrap before the end of file */
3497 if (feed
->feed_max_size
&& feed
->feed_max_size
< feed
->feed_size
)
3498 feed
->feed_max_size
= feed
->feed_size
;
3504 /* compute the bandwidth used by each stream */
3505 static void compute_bandwidth(void)
3510 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
3512 for(i
=0;i
<stream
->nb_streams
;i
++) {
3513 AVStream
*st
= stream
->streams
[i
];
3514 switch(st
->codec
->codec_type
) {
3515 case CODEC_TYPE_AUDIO
:
3516 case CODEC_TYPE_VIDEO
:
3517 bandwidth
+= st
->codec
->bit_rate
;
3523 stream
->bandwidth
= (bandwidth
+ 999) / 1000;
3527 static void get_arg(char *buf
, int buf_size
, const char **pp
)
3534 while (isspace(*p
)) p
++;
3537 if (*p
== '\"' || *p
== '\'')
3549 if ((q
- buf
) < buf_size
- 1)
3554 if (quote
&& *p
== quote
)
3559 /* add a codec and set the default parameters */
3560 static void add_codec(FFStream
*stream
, AVCodecContext
*av
)
3564 /* compute default parameters */
3565 switch(av
->codec_type
) {
3566 case CODEC_TYPE_AUDIO
:
3567 if (av
->bit_rate
== 0)
3568 av
->bit_rate
= 64000;
3569 if (av
->sample_rate
== 0)
3570 av
->sample_rate
= 22050;
3571 if (av
->channels
== 0)
3574 case CODEC_TYPE_VIDEO
:
3575 if (av
->bit_rate
== 0)
3576 av
->bit_rate
= 64000;
3577 if (av
->time_base
.num
== 0){
3578 av
->time_base
.den
= 5;
3579 av
->time_base
.num
= 1;
3581 if (av
->width
== 0 || av
->height
== 0) {
3585 /* Bitrate tolerance is less for streaming */
3586 if (av
->bit_rate_tolerance
== 0)
3587 av
->bit_rate_tolerance
= FFMAX(av
->bit_rate
/ 4,
3588 (int64_t)av
->bit_rate
*av
->time_base
.num
/av
->time_base
.den
);
3593 if (av
->max_qdiff
== 0)
3595 av
->qcompress
= 0.5;
3598 if (!av
->nsse_weight
)
3599 av
->nsse_weight
= 8;
3601 av
->frame_skip_cmp
= FF_CMP_DCTMAX
;
3602 av
->me_method
= ME_EPZS
;
3603 av
->rc_buffer_aggressivity
= 1.0;
3606 av
->rc_eq
= "tex^qComp";
3607 if (!av
->i_quant_factor
)
3608 av
->i_quant_factor
= -0.8;
3609 if (!av
->b_quant_factor
)
3610 av
->b_quant_factor
= 1.25;
3611 if (!av
->b_quant_offset
)
3612 av
->b_quant_offset
= 1.25;
3613 if (!av
->rc_max_rate
)
3614 av
->rc_max_rate
= av
->bit_rate
* 2;
3616 if (av
->rc_max_rate
&& !av
->rc_buffer_size
) {
3617 av
->rc_buffer_size
= av
->rc_max_rate
;
3626 st
= av_mallocz(sizeof(AVStream
));
3629 st
->codec
= avcodec_alloc_context();
3630 stream
->streams
[stream
->nb_streams
++] = st
;
3631 memcpy(st
->codec
, av
, sizeof(AVCodecContext
));
3634 static int opt_audio_codec(const char *arg
)
3636 AVCodec
*p
= avcodec_find_encoder_by_name(arg
);
3638 if (p
== NULL
|| p
->type
!= CODEC_TYPE_AUDIO
)
3639 return CODEC_ID_NONE
;
3644 static int opt_video_codec(const char *arg
)
3646 AVCodec
*p
= avcodec_find_encoder_by_name(arg
);
3648 if (p
== NULL
|| p
->type
!= CODEC_TYPE_VIDEO
)
3649 return CODEC_ID_NONE
;
3654 /* simplistic plugin support */
3657 static void load_module(const char *filename
)
3660 void (*init_func
)(void);
3661 dll
= dlopen(filename
, RTLD_NOW
);
3663 fprintf(stderr
, "Could not load module '%s' - %s\n",
3664 filename
, dlerror());
3668 init_func
= dlsym(dll
, "ffserver_module_init");
3671 "%s: init function 'ffserver_module_init()' not found\n",
3680 static int parse_ffconfig(const char *filename
)
3687 int val
, errors
, line_num
;
3688 FFStream
**last_stream
, *stream
, *redirect
;
3689 FFStream
**last_feed
, *feed
;
3690 AVCodecContext audio_enc
, video_enc
;
3691 int audio_id
, video_id
;
3693 f
= fopen(filename
, "r");
3701 first_stream
= NULL
;
3702 last_stream
= &first_stream
;
3704 last_feed
= &first_feed
;
3708 audio_id
= CODEC_ID_NONE
;
3709 video_id
= CODEC_ID_NONE
;
3711 if (fgets(line
, sizeof(line
), f
) == NULL
)
3717 if (*p
== '\0' || *p
== '#')
3720 get_arg(cmd
, sizeof(cmd
), &p
);
3722 if (!strcasecmp(cmd
, "Port")) {
3723 get_arg(arg
, sizeof(arg
), &p
);
3725 if (val
< 1 || val
> 65536) {
3726 fprintf(stderr
, "%s:%d: Invalid port: %s\n",
3727 filename
, line_num
, arg
);
3730 my_http_addr
.sin_port
= htons(val
);
3731 } else if (!strcasecmp(cmd
, "BindAddress")) {
3732 get_arg(arg
, sizeof(arg
), &p
);
3733 if (resolve_host(&my_http_addr
.sin_addr
, arg
) != 0) {
3734 fprintf(stderr
, "%s:%d: Invalid host/IP address: %s\n",
3735 filename
, line_num
, arg
);
3738 } else if (!strcasecmp(cmd
, "NoDaemon")) {
3739 ffserver_daemon
= 0;
3740 } else if (!strcasecmp(cmd
, "RTSPPort")) {
3741 get_arg(arg
, sizeof(arg
), &p
);
3743 if (val
< 1 || val
> 65536) {
3744 fprintf(stderr
, "%s:%d: Invalid port: %s\n",
3745 filename
, line_num
, arg
);
3748 my_rtsp_addr
.sin_port
= htons(atoi(arg
));
3749 } else if (!strcasecmp(cmd
, "RTSPBindAddress")) {
3750 get_arg(arg
, sizeof(arg
), &p
);
3751 if (resolve_host(&my_rtsp_addr
.sin_addr
, arg
) != 0) {
3752 fprintf(stderr
, "%s:%d: Invalid host/IP address: %s\n",
3753 filename
, line_num
, arg
);
3756 } else if (!strcasecmp(cmd
, "MaxClients")) {
3757 get_arg(arg
, sizeof(arg
), &p
);
3759 if (val
< 1 || val
> HTTP_MAX_CONNECTIONS
) {
3760 fprintf(stderr
, "%s:%d: Invalid MaxClients: %s\n",
3761 filename
, line_num
, arg
);
3764 nb_max_connections
= val
;
3766 } else if (!strcasecmp(cmd
, "MaxBandwidth")) {
3767 get_arg(arg
, sizeof(arg
), &p
);
3769 if (val
< 10 || val
> 100000) {
3770 fprintf(stderr
, "%s:%d: Invalid MaxBandwidth: %s\n",
3771 filename
, line_num
, arg
);
3774 max_bandwidth
= val
;
3775 } else if (!strcasecmp(cmd
, "CustomLog")) {
3776 get_arg(logfilename
, sizeof(logfilename
), &p
);
3777 } else if (!strcasecmp(cmd
, "<Feed")) {
3778 /*********************************************/
3779 /* Feed related options */
3781 if (stream
|| feed
) {
3782 fprintf(stderr
, "%s:%d: Already in a tag\n",
3783 filename
, line_num
);
3785 feed
= av_mallocz(sizeof(FFStream
));
3786 /* add in stream list */
3787 *last_stream
= feed
;
3788 last_stream
= &feed
->next
;
3789 /* add in feed list */
3791 last_feed
= &feed
->next_feed
;
3793 get_arg(feed
->filename
, sizeof(feed
->filename
), &p
);
3794 q
= strrchr(feed
->filename
, '>');
3797 feed
->fmt
= guess_format("ffm", NULL
, NULL
);
3798 /* defaut feed file */
3799 snprintf(feed
->feed_filename
, sizeof(feed
->feed_filename
),
3800 "/tmp/%s.ffm", feed
->filename
);
3801 feed
->feed_max_size
= 5 * 1024 * 1024;
3803 feed
->feed
= feed
; /* self feeding :-) */
3805 } else if (!strcasecmp(cmd
, "Launch")) {
3809 feed
->child_argv
= av_mallocz(64 * sizeof(char *));
3811 for (i
= 0; i
< 62; i
++) {
3812 get_arg(arg
, sizeof(arg
), &p
);
3816 feed
->child_argv
[i
] = av_strdup(arg
);
3819 feed
->child_argv
[i
] = av_malloc(30 + strlen(feed
->filename
));
3821 snprintf(feed
->child_argv
[i
], 30+strlen(feed
->filename
),
3823 (my_http_addr
.sin_addr
.s_addr
== INADDR_ANY
) ? "127.0.0.1" :
3824 inet_ntoa(my_http_addr
.sin_addr
),
3825 ntohs(my_http_addr
.sin_port
), feed
->filename
);
3830 fprintf(stdout
, "Launch commandline: ");
3831 for (j
= 0; j
<= i
; j
++)
3832 fprintf(stdout
, "%s ", feed
->child_argv
[j
]);
3833 fprintf(stdout
, "\n");
3836 } else if (!strcasecmp(cmd
, "ReadOnlyFile")) {
3838 get_arg(feed
->feed_filename
, sizeof(feed
->feed_filename
), &p
);
3840 } else if (stream
) {
3841 get_arg(stream
->feed_filename
, sizeof(stream
->feed_filename
), &p
);
3843 } else if (!strcasecmp(cmd
, "File")) {
3845 get_arg(feed
->feed_filename
, sizeof(feed
->feed_filename
), &p
);
3847 get_arg(stream
->feed_filename
, sizeof(stream
->feed_filename
), &p
);
3848 } else if (!strcasecmp(cmd
, "FileMaxSize")) {
3853 get_arg(arg
, sizeof(arg
), &p
);
3855 fsize
= strtod(p1
, &p1
);
3856 switch(toupper(*p1
)) {
3861 fsize
*= 1024 * 1024;
3864 fsize
*= 1024 * 1024 * 1024;
3867 feed
->feed_max_size
= (int64_t)fsize
;
3869 } else if (!strcasecmp(cmd
, "</Feed>")) {
3871 fprintf(stderr
, "%s:%d: No corresponding <Feed> for </Feed>\n",
3872 filename
, line_num
);
3876 } else if (!strcasecmp(cmd
, "<Stream")) {
3877 /*********************************************/
3878 /* Stream related options */
3880 if (stream
|| feed
) {
3881 fprintf(stderr
, "%s:%d: Already in a tag\n",
3882 filename
, line_num
);
3884 stream
= av_mallocz(sizeof(FFStream
));
3885 *last_stream
= stream
;
3886 last_stream
= &stream
->next
;
3888 get_arg(stream
->filename
, sizeof(stream
->filename
), &p
);
3889 q
= strrchr(stream
->filename
, '>');
3892 stream
->fmt
= guess_stream_format(NULL
, stream
->filename
, NULL
);
3893 memset(&audio_enc
, 0, sizeof(AVCodecContext
));
3894 memset(&video_enc
, 0, sizeof(AVCodecContext
));
3895 audio_id
= CODEC_ID_NONE
;
3896 video_id
= CODEC_ID_NONE
;
3898 audio_id
= stream
->fmt
->audio_codec
;
3899 video_id
= stream
->fmt
->video_codec
;
3902 } else if (!strcasecmp(cmd
, "Feed")) {
3903 get_arg(arg
, sizeof(arg
), &p
);
3908 while (sfeed
!= NULL
) {
3909 if (!strcmp(sfeed
->filename
, arg
))
3911 sfeed
= sfeed
->next_feed
;
3914 fprintf(stderr
, "%s:%d: feed '%s' not defined\n",
3915 filename
, line_num
, arg
);
3917 stream
->feed
= sfeed
;
3919 } else if (!strcasecmp(cmd
, "Format")) {
3920 get_arg(arg
, sizeof(arg
), &p
);
3921 if (!strcmp(arg
, "status")) {
3922 stream
->stream_type
= STREAM_TYPE_STATUS
;
3925 stream
->stream_type
= STREAM_TYPE_LIVE
;
3926 /* jpeg cannot be used here, so use single frame jpeg */
3927 if (!strcmp(arg
, "jpeg"))
3928 strcpy(arg
, "mjpeg");
3929 stream
->fmt
= guess_stream_format(arg
, NULL
, NULL
);
3931 fprintf(stderr
, "%s:%d: Unknown Format: %s\n",
3932 filename
, line_num
, arg
);
3937 audio_id
= stream
->fmt
->audio_codec
;
3938 video_id
= stream
->fmt
->video_codec
;
3940 } else if (!strcasecmp(cmd
, "InputFormat")) {
3941 get_arg(arg
, sizeof(arg
), &p
);
3942 stream
->ifmt
= av_find_input_format(arg
);
3943 if (!stream
->ifmt
) {
3944 fprintf(stderr
, "%s:%d: Unknown input format: %s\n",
3945 filename
, line_num
, arg
);
3947 } else if (!strcasecmp(cmd
, "FaviconURL")) {
3948 if (stream
&& stream
->stream_type
== STREAM_TYPE_STATUS
) {
3949 get_arg(stream
->feed_filename
, sizeof(stream
->feed_filename
), &p
);
3951 fprintf(stderr
, "%s:%d: FaviconURL only permitted for status streams\n",
3952 filename
, line_num
);
3955 } else if (!strcasecmp(cmd
, "Author")) {
3957 get_arg(stream
->author
, sizeof(stream
->author
), &p
);
3958 } else if (!strcasecmp(cmd
, "Comment")) {
3960 get_arg(stream
->comment
, sizeof(stream
->comment
), &p
);
3961 } else if (!strcasecmp(cmd
, "Copyright")) {
3963 get_arg(stream
->copyright
, sizeof(stream
->copyright
), &p
);
3964 } else if (!strcasecmp(cmd
, "Title")) {
3966 get_arg(stream
->title
, sizeof(stream
->title
), &p
);
3967 } else if (!strcasecmp(cmd
, "Preroll")) {
3968 get_arg(arg
, sizeof(arg
), &p
);
3970 stream
->prebuffer
= atof(arg
) * 1000;
3971 } else if (!strcasecmp(cmd
, "StartSendOnKey")) {
3973 stream
->send_on_key
= 1;
3974 } else if (!strcasecmp(cmd
, "AudioCodec")) {
3975 get_arg(arg
, sizeof(arg
), &p
);
3976 audio_id
= opt_audio_codec(arg
);
3977 if (audio_id
== CODEC_ID_NONE
) {
3978 fprintf(stderr
, "%s:%d: Unknown AudioCodec: %s\n",
3979 filename
, line_num
, arg
);
3982 } else if (!strcasecmp(cmd
, "VideoCodec")) {
3983 get_arg(arg
, sizeof(arg
), &p
);
3984 video_id
= opt_video_codec(arg
);
3985 if (video_id
== CODEC_ID_NONE
) {
3986 fprintf(stderr
, "%s:%d: Unknown VideoCodec: %s\n",
3987 filename
, line_num
, arg
);
3990 } else if (!strcasecmp(cmd
, "MaxTime")) {
3991 get_arg(arg
, sizeof(arg
), &p
);
3993 stream
->max_time
= atof(arg
) * 1000;
3994 } else if (!strcasecmp(cmd
, "AudioBitRate")) {
3995 get_arg(arg
, sizeof(arg
), &p
);
3997 audio_enc
.bit_rate
= atoi(arg
) * 1000;
3998 } else if (!strcasecmp(cmd
, "AudioChannels")) {
3999 get_arg(arg
, sizeof(arg
), &p
);
4001 audio_enc
.channels
= atoi(arg
);
4002 } else if (!strcasecmp(cmd
, "AudioSampleRate")) {
4003 get_arg(arg
, sizeof(arg
), &p
);
4005 audio_enc
.sample_rate
= atoi(arg
);
4006 } else if (!strcasecmp(cmd
, "AudioQuality")) {
4007 get_arg(arg
, sizeof(arg
), &p
);
4009 // audio_enc.quality = atof(arg) * 1000;
4011 } else if (!strcasecmp(cmd
, "VideoBitRateRange")) {
4013 int minrate
, maxrate
;
4015 get_arg(arg
, sizeof(arg
), &p
);
4017 if (sscanf(arg
, "%d-%d", &minrate
, &maxrate
) == 2) {
4018 video_enc
.rc_min_rate
= minrate
* 1000;
4019 video_enc
.rc_max_rate
= maxrate
* 1000;
4021 fprintf(stderr
, "%s:%d: Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n",
4022 filename
, line_num
, arg
);
4026 } else if (!strcasecmp(cmd
, "Debug")) {
4028 get_arg(arg
, sizeof(arg
), &p
);
4029 video_enc
.debug
= strtol(arg
,0,0);
4031 } else if (!strcasecmp(cmd
, "Strict")) {
4033 get_arg(arg
, sizeof(arg
), &p
);
4034 video_enc
.strict_std_compliance
= atoi(arg
);
4036 } else if (!strcasecmp(cmd
, "VideoBufferSize")) {
4038 get_arg(arg
, sizeof(arg
), &p
);
4039 video_enc
.rc_buffer_size
= atoi(arg
) * 8*1024;
4041 } else if (!strcasecmp(cmd
, "VideoBitRateTolerance")) {
4043 get_arg(arg
, sizeof(arg
), &p
);
4044 video_enc
.bit_rate_tolerance
= atoi(arg
) * 1000;
4046 } else if (!strcasecmp(cmd
, "VideoBitRate")) {
4047 get_arg(arg
, sizeof(arg
), &p
);
4049 video_enc
.bit_rate
= atoi(arg
) * 1000;
4051 } else if (!strcasecmp(cmd
, "VideoSize")) {
4052 get_arg(arg
, sizeof(arg
), &p
);
4054 av_parse_video_frame_size(&video_enc
.width
, &video_enc
.height
, arg
);
4055 if ((video_enc
.width
% 16) != 0 ||
4056 (video_enc
.height
% 16) != 0) {
4057 fprintf(stderr
, "%s:%d: Image size must be a multiple of 16\n",
4058 filename
, line_num
);
4062 } else if (!strcasecmp(cmd
, "VideoFrameRate")) {
4063 get_arg(arg
, sizeof(arg
), &p
);
4065 video_enc
.time_base
.num
= DEFAULT_FRAME_RATE_BASE
;
4066 video_enc
.time_base
.den
= (int)(strtod(arg
, NULL
) * video_enc
.time_base
.num
);
4068 } else if (!strcasecmp(cmd
, "VideoGopSize")) {
4069 get_arg(arg
, sizeof(arg
), &p
);
4071 video_enc
.gop_size
= atoi(arg
);
4072 } else if (!strcasecmp(cmd
, "VideoIntraOnly")) {
4074 video_enc
.gop_size
= 1;
4075 } else if (!strcasecmp(cmd
, "VideoHighQuality")) {
4077 video_enc
.mb_decision
= FF_MB_DECISION_BITS
;
4078 } else if (!strcasecmp(cmd
, "Video4MotionVector")) {
4080 video_enc
.mb_decision
= FF_MB_DECISION_BITS
; //FIXME remove
4081 video_enc
.flags
|= CODEC_FLAG_4MV
;
4083 } else if (!strcasecmp(cmd
, "VideoTag")) {
4084 get_arg(arg
, sizeof(arg
), &p
);
4085 if ((strlen(arg
) == 4) && stream
)
4086 video_enc
.codec_tag
= ff_get_fourcc(arg
);
4087 } else if (!strcasecmp(cmd
, "BitExact")) {
4089 video_enc
.flags
|= CODEC_FLAG_BITEXACT
;
4090 } else if (!strcasecmp(cmd
, "DctFastint")) {
4092 video_enc
.dct_algo
= FF_DCT_FASTINT
;
4093 } else if (!strcasecmp(cmd
, "IdctSimple")) {
4095 video_enc
.idct_algo
= FF_IDCT_SIMPLE
;
4096 } else if (!strcasecmp(cmd
, "Qscale")) {
4097 get_arg(arg
, sizeof(arg
), &p
);
4099 video_enc
.flags
|= CODEC_FLAG_QSCALE
;
4100 video_enc
.global_quality
= FF_QP2LAMBDA
* atoi(arg
);
4102 } else if (!strcasecmp(cmd
, "VideoQDiff")) {
4103 get_arg(arg
, sizeof(arg
), &p
);
4105 video_enc
.max_qdiff
= atoi(arg
);
4106 if (video_enc
.max_qdiff
< 1 || video_enc
.max_qdiff
> 31) {
4107 fprintf(stderr
, "%s:%d: VideoQDiff out of range\n",
4108 filename
, line_num
);
4112 } else if (!strcasecmp(cmd
, "VideoQMax")) {
4113 get_arg(arg
, sizeof(arg
), &p
);
4115 video_enc
.qmax
= atoi(arg
);
4116 if (video_enc
.qmax
< 1 || video_enc
.qmax
> 31) {
4117 fprintf(stderr
, "%s:%d: VideoQMax out of range\n",
4118 filename
, line_num
);
4122 } else if (!strcasecmp(cmd
, "VideoQMin")) {
4123 get_arg(arg
, sizeof(arg
), &p
);
4125 video_enc
.qmin
= atoi(arg
);
4126 if (video_enc
.qmin
< 1 || video_enc
.qmin
> 31) {
4127 fprintf(stderr
, "%s:%d: VideoQMin out of range\n",
4128 filename
, line_num
);
4132 } else if (!strcasecmp(cmd
, "LumaElim")) {
4133 get_arg(arg
, sizeof(arg
), &p
);
4135 video_enc
.luma_elim_threshold
= atoi(arg
);
4136 } else if (!strcasecmp(cmd
, "ChromaElim")) {
4137 get_arg(arg
, sizeof(arg
), &p
);
4139 video_enc
.chroma_elim_threshold
= atoi(arg
);
4140 } else if (!strcasecmp(cmd
, "LumiMask")) {
4141 get_arg(arg
, sizeof(arg
), &p
);
4143 video_enc
.lumi_masking
= atof(arg
);
4144 } else if (!strcasecmp(cmd
, "DarkMask")) {
4145 get_arg(arg
, sizeof(arg
), &p
);
4147 video_enc
.dark_masking
= atof(arg
);
4148 } else if (!strcasecmp(cmd
, "NoVideo")) {
4149 video_id
= CODEC_ID_NONE
;
4150 } else if (!strcasecmp(cmd
, "NoAudio")) {
4151 audio_id
= CODEC_ID_NONE
;
4152 } else if (!strcasecmp(cmd
, "ACL")) {
4155 get_arg(arg
, sizeof(arg
), &p
);
4156 if (strcasecmp(arg
, "allow") == 0)
4157 acl
.action
= IP_ALLOW
;
4158 else if (strcasecmp(arg
, "deny") == 0)
4159 acl
.action
= IP_DENY
;
4161 fprintf(stderr
, "%s:%d: ACL action '%s' is not ALLOW or DENY\n",
4162 filename
, line_num
, arg
);
4166 get_arg(arg
, sizeof(arg
), &p
);
4168 if (resolve_host(&acl
.first
, arg
) != 0) {
4169 fprintf(stderr
, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4170 filename
, line_num
, arg
);
4173 acl
.last
= acl
.first
;
4175 get_arg(arg
, sizeof(arg
), &p
);
4178 if (resolve_host(&acl
.last
, arg
) != 0) {
4179 fprintf(stderr
, "%s:%d: ACL refers to invalid host or ip address '%s'\n",
4180 filename
, line_num
, arg
);
4186 IPAddressACL
*nacl
= av_mallocz(sizeof(*nacl
));
4187 IPAddressACL
**naclp
= 0;
4193 naclp
= &stream
->acl
;
4197 fprintf(stderr
, "%s:%d: ACL found not in <stream> or <feed>\n",
4198 filename
, line_num
);
4204 naclp
= &(*naclp
)->next
;
4209 } else if (!strcasecmp(cmd
, "RTSPOption")) {
4210 get_arg(arg
, sizeof(arg
), &p
);
4212 av_freep(&stream
->rtsp_option
);
4213 stream
->rtsp_option
= av_strdup(arg
);
4215 } else if (!strcasecmp(cmd
, "MulticastAddress")) {
4216 get_arg(arg
, sizeof(arg
), &p
);
4218 if (resolve_host(&stream
->multicast_ip
, arg
) != 0) {
4219 fprintf(stderr
, "%s:%d: Invalid host/IP address: %s\n",
4220 filename
, line_num
, arg
);
4223 stream
->is_multicast
= 1;
4224 stream
->loop
= 1; /* default is looping */
4226 } else if (!strcasecmp(cmd
, "MulticastPort")) {
4227 get_arg(arg
, sizeof(arg
), &p
);
4229 stream
->multicast_port
= atoi(arg
);
4230 } else if (!strcasecmp(cmd
, "MulticastTTL")) {
4231 get_arg(arg
, sizeof(arg
), &p
);
4233 stream
->multicast_ttl
= atoi(arg
);
4234 } else if (!strcasecmp(cmd
, "NoLoop")) {
4237 } else if (!strcasecmp(cmd
, "</Stream>")) {
4239 fprintf(stderr
, "%s:%d: No corresponding <Stream> for </Stream>\n",
4240 filename
, line_num
);
4243 if (stream
->feed
&& stream
->fmt
&& strcmp(stream
->fmt
->name
, "ffm") != 0) {
4244 if (audio_id
!= CODEC_ID_NONE
) {
4245 audio_enc
.codec_type
= CODEC_TYPE_AUDIO
;
4246 audio_enc
.codec_id
= audio_id
;
4247 add_codec(stream
, &audio_enc
);
4249 if (video_id
!= CODEC_ID_NONE
) {
4250 video_enc
.codec_type
= CODEC_TYPE_VIDEO
;
4251 video_enc
.codec_id
= video_id
;
4252 add_codec(stream
, &video_enc
);
4256 } else if (!strcasecmp(cmd
, "<Redirect")) {
4257 /*********************************************/
4259 if (stream
|| feed
|| redirect
) {
4260 fprintf(stderr
, "%s:%d: Already in a tag\n",
4261 filename
, line_num
);
4264 redirect
= av_mallocz(sizeof(FFStream
));
4265 *last_stream
= redirect
;
4266 last_stream
= &redirect
->next
;
4268 get_arg(redirect
->filename
, sizeof(redirect
->filename
), &p
);
4269 q
= strrchr(redirect
->filename
, '>');
4272 redirect
->stream_type
= STREAM_TYPE_REDIRECT
;
4274 } else if (!strcasecmp(cmd
, "URL")) {
4276 get_arg(redirect
->feed_filename
, sizeof(redirect
->feed_filename
), &p
);
4277 } else if (!strcasecmp(cmd
, "</Redirect>")) {
4279 fprintf(stderr
, "%s:%d: No corresponding <Redirect> for </Redirect>\n",
4280 filename
, line_num
);
4283 if (!redirect
->feed_filename
[0]) {
4284 fprintf(stderr
, "%s:%d: No URL found for <Redirect>\n",
4285 filename
, line_num
);
4289 } else if (!strcasecmp(cmd
, "LoadModule")) {
4290 get_arg(arg
, sizeof(arg
), &p
);
4294 fprintf(stderr
, "%s:%d: Module support not compiled into this version: '%s'\n",
4295 filename
, line_num
, arg
);
4299 fprintf(stderr
, "%s:%d: Incorrect keyword: '%s'\n",
4300 filename
, line_num
, cmd
);
4312 static void handle_child_exit(int sig
)
4317 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0) {
4320 for (feed
= first_feed
; feed
; feed
= feed
->next
) {
4321 if (feed
->pid
== pid
) {
4322 int uptime
= time(0) - feed
->pid_start
;
4325 fprintf(stderr
, "%s: Pid %d exited with status %d after %d seconds\n", feed
->filename
, pid
, status
, uptime
);
4328 /* Turn off any more restarts */
4329 feed
->child_argv
= 0;
4334 need_to_start_children
= 1;
4337 static void opt_debug()
4340 ffserver_daemon
= 0;
4343 static void opt_show_help(void)
4345 printf("usage: ffserver [options]\n"
4346 "Hyper fast multi format Audio/Video streaming server\n");
4348 show_help_options(options
, "Main options:\n", 0, 0);
4351 static const OptionDef options
[] = {
4352 { "h", OPT_EXIT
, {(void*)opt_show_help
}, "show help" },
4353 { "version", OPT_EXIT
, {(void*)show_version
}, "show version" },
4354 { "L", OPT_EXIT
, {(void*)show_license
}, "show license" },
4355 { "formats", OPT_EXIT
, {(void*)show_formats
}, "show available formats, codecs, protocols, ..." },
4356 { "n", OPT_BOOL
, {(void *)&no_launch
}, "enable no-launch mode" },
4357 { "d", 0, {(void*)opt_debug
}, "enable debug mode" },
4358 { "f", HAS_ARG
| OPT_STRING
, {(void*)&config_filename
}, "use configfile instead of /etc/ffserver.conf", "configfile" },
4362 int main(int argc
, char **argv
)
4364 struct sigaction sigact
;
4368 show_banner(program_name
, program_birth_year
);
4370 config_filename
= "/etc/ffserver.conf";
4372 my_program_name
= argv
[0];
4373 my_program_dir
= getcwd(0, 0);
4374 ffserver_daemon
= 1;
4376 parse_options(argc
, argv
, options
, NULL
);
4378 putenv("http_proxy"); /* Kill the http_proxy */
4380 av_init_random(av_gettime() + (getpid() << 16), &random_state
);
4382 /* address on which the server will handle HTTP connections */
4383 my_http_addr
.sin_family
= AF_INET
;
4384 my_http_addr
.sin_port
= htons (8080);
4385 my_http_addr
.sin_addr
.s_addr
= htonl (INADDR_ANY
);
4387 /* address on which the server will handle RTSP connections */
4388 my_rtsp_addr
.sin_family
= AF_INET
;
4389 my_rtsp_addr
.sin_port
= htons (5454);
4390 my_rtsp_addr
.sin_addr
.s_addr
= htonl (INADDR_ANY
);
4392 nb_max_connections
= 5;
4393 max_bandwidth
= 1000;
4394 first_stream
= NULL
;
4395 logfilename
[0] = '\0';
4397 memset(&sigact
, 0, sizeof(sigact
));
4398 sigact
.sa_handler
= handle_child_exit
;
4399 sigact
.sa_flags
= SA_NOCLDSTOP
| SA_RESTART
;
4400 sigaction(SIGCHLD
, &sigact
, 0);
4402 if (parse_ffconfig(config_filename
) < 0) {
4403 fprintf(stderr
, "Incorrect config file - exiting.\n");
4407 build_file_streams();
4409 build_feed_streams();
4411 compute_bandwidth();
4413 /* put the process in background and detach it from its TTY */
4414 if (ffserver_daemon
) {
4421 } else if (pid
> 0) {
4429 open("/dev/null", O_RDWR
);
4430 if (strcmp(logfilename
, "-") != 0) {
4440 signal(SIGPIPE
, SIG_IGN
);
4442 /* open log file if needed */
4443 if (logfilename
[0] != '\0') {
4444 if (!strcmp(logfilename
, "-"))
4447 logfile
= fopen(logfilename
, "a");
4450 if (http_server() < 0) {
4451 fprintf(stderr
, "Could not start server\n");