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
22 #define _XOPEN_SOURCE 600
26 #define closesocket close
31 #include "libavformat/avformat.h"
32 #include "libavformat/network.h"
33 #include "libavformat/os_support.h"
34 #include "libavformat/rtpdec.h"
35 #include "libavformat/rtsp.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/lfg.h"
38 #include "libavutil/random_seed.h"
39 #include "libavcodec/opt.h"
43 #include <sys/ioctl.h>
58 const char program_name
[] = "FFserver";
59 const int program_birth_year
= 2000;
61 static const OptionDef options
[];
64 HTTPSTATE_WAIT_REQUEST
,
65 HTTPSTATE_SEND_HEADER
,
66 HTTPSTATE_SEND_DATA_HEADER
,
67 HTTPSTATE_SEND_DATA
, /* sending TCP or UDP data */
68 HTTPSTATE_SEND_DATA_TRAILER
,
69 HTTPSTATE_RECEIVE_DATA
,
70 HTTPSTATE_WAIT_FEED
, /* wait for data from the feed */
73 RTSPSTATE_WAIT_REQUEST
,
75 RTSPSTATE_SEND_PACKET
,
78 static const char *http_state
[] = {
94 #define IOBUFFER_INIT_SIZE 8192
96 /* timeouts are in ms */
97 #define HTTP_REQUEST_TIMEOUT (15 * 1000)
98 #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
100 #define SYNC_TIMEOUT (10 * 1000)
102 typedef struct RTSPActionServerSetup
{
104 char transport_option
[512];
105 } RTSPActionServerSetup
;
108 int64_t count1
, count2
;
109 int64_t time1
, time2
;
112 /* context associated with one connection */
113 typedef struct HTTPContext
{
114 enum HTTPState state
;
115 int fd
; /* socket file descriptor */
116 struct sockaddr_in from_addr
; /* origin */
117 struct pollfd
*poll_entry
; /* used when polling */
119 uint8_t *buffer_ptr
, *buffer_end
;
122 int chunked_encoding
;
123 int chunk_size
; /* 0 if it needs to be read */
124 struct HTTPContext
*next
;
125 int got_key_frame
; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
129 /* input format handling */
130 AVFormatContext
*fmt_in
;
131 int64_t start_time
; /* In milliseconds - this wraps fairly often */
132 int64_t first_pts
; /* initial pts value */
133 int64_t cur_pts
; /* current pts value from the stream in us */
134 int64_t cur_frame_duration
; /* duration of the current frame in us */
135 int cur_frame_bytes
; /* output frame size, needed to compute
136 the time at which we send each
138 int pts_stream_index
; /* stream we choose as clock reference */
139 int64_t cur_clock
; /* current clock reference value in us */
140 /* output format handling */
141 struct FFStream
*stream
;
142 /* -1 is invalid stream */
143 int feed_streams
[MAX_STREAMS
]; /* index of streams in the feed */
144 int switch_feed_streams
[MAX_STREAMS
]; /* index of streams in the feed */
146 AVFormatContext fmt_ctx
; /* instance of FFStream for one user */
147 int last_packet_sent
; /* true if last data packet was sent */
149 DataRateData datarate
;
156 int is_packetized
; /* if true, the stream is packetized */
157 int packet_stream_index
; /* current stream for output in state machine */
159 /* RTSP state specific */
160 uint8_t *pb_buffer
; /* XXX: use that in all the code */
162 int seq
; /* RTSP sequence number */
164 /* RTP state specific */
165 enum RTSPLowerTransport rtp_protocol
;
166 char session_id
[32]; /* session id */
167 AVFormatContext
*rtp_ctx
[MAX_STREAMS
];
169 /* RTP/UDP specific */
170 URLContext
*rtp_handles
[MAX_STREAMS
];
172 /* RTP/TCP specific */
173 struct HTTPContext
*rtsp_c
;
174 uint8_t *packet_buffer
, *packet_buffer_ptr
, *packet_buffer_end
;
177 /* each generated stream is described here */
181 STREAM_TYPE_REDIRECT
,
184 enum IPAddressAction
{
189 typedef struct IPAddressACL
{
190 struct IPAddressACL
*next
;
191 enum IPAddressAction action
;
192 /* These are in host order */
193 struct in_addr first
;
197 /* description of each stream of the ffserver.conf file */
198 typedef struct FFStream
{
199 enum StreamType stream_type
;
200 char filename
[1024]; /* stream filename */
201 struct FFStream
*feed
; /* feed we are using (can be null if
203 AVFormatParameters
*ap_in
; /* input parameters */
204 AVInputFormat
*ifmt
; /* if non NULL, force input format */
208 int prebuffer
; /* Number of millseconds early to start */
209 int64_t max_time
; /* Number of milliseconds to run */
211 AVStream
*streams
[MAX_STREAMS
];
212 int feed_streams
[MAX_STREAMS
]; /* index of streams in the feed */
213 char feed_filename
[1024]; /* file name of the feed storage, or
214 input file name for a stream */
219 pid_t pid
; /* Of ffmpeg process */
220 time_t pid_start
; /* Of ffmpeg process */
222 struct FFStream
*next
;
223 unsigned bandwidth
; /* bandwidth, in kbits/s */
226 /* multicast specific */
228 struct in_addr multicast_ip
;
229 int multicast_port
; /* first port used for multicast */
231 int loop
; /* if true, send the stream in loops (only meaningful if file) */
234 int feed_opened
; /* true if someone is writing to the feed */
235 int is_feed
; /* true if it is a feed */
236 int readonly
; /* True if writing is prohibited to the file */
237 int truncate
; /* True if feeder connection truncate the feed file */
239 int64_t bytes_served
;
240 int64_t feed_max_size
; /* maximum storage size, zero means unlimited */
241 int64_t feed_write_index
; /* current write position in feed (it wraps around) */
242 int64_t feed_size
; /* current size of feed */
243 struct FFStream
*next_feed
;
246 typedef struct FeedData
{
247 long long data_count
;
248 float avg_frame_size
; /* frame size averaged over last frames with exponential mean */
251 static struct sockaddr_in my_http_addr
;
252 static struct sockaddr_in my_rtsp_addr
;
254 static char logfilename
[1024];
255 static HTTPContext
*first_http_ctx
;
256 static FFStream
*first_feed
; /* contains only feeds */
257 static FFStream
*first_stream
; /* contains all streams, including feeds */
259 static void new_connection(int server_fd
, int is_rtsp
);
260 static void close_connection(HTTPContext
*c
);
263 static int handle_connection(HTTPContext
*c
);
264 static int http_parse_request(HTTPContext
*c
);
265 static int http_send_data(HTTPContext
*c
);
266 static void compute_status(HTTPContext
*c
);
267 static int open_input_stream(HTTPContext
*c
, const char *info
);
268 static int http_start_receive_data(HTTPContext
*c
);
269 static int http_receive_data(HTTPContext
*c
);
272 static int rtsp_parse_request(HTTPContext
*c
);
273 static void rtsp_cmd_describe(HTTPContext
*c
, const char *url
);
274 static void rtsp_cmd_options(HTTPContext
*c
, const char *url
);
275 static void rtsp_cmd_setup(HTTPContext
*c
, const char *url
, RTSPMessageHeader
*h
);
276 static void rtsp_cmd_play(HTTPContext
*c
, const char *url
, RTSPMessageHeader
*h
);
277 static void rtsp_cmd_pause(HTTPContext
*c
, const char *url
, RTSPMessageHeader
*h
);
278 static void rtsp_cmd_teardown(HTTPContext
*c
, const char *url
, RTSPMessageHeader
*h
);
281 static int prepare_sdp_description(FFStream
*stream
, uint8_t **pbuffer
,
282 struct in_addr my_ip
);
285 static HTTPContext
*rtp_new_connection(struct sockaddr_in
*from_addr
,
286 FFStream
*stream
, const char *session_id
,
287 enum RTSPLowerTransport rtp_protocol
);
288 static int rtp_new_av_stream(HTTPContext
*c
,
289 int stream_index
, struct sockaddr_in
*dest_addr
,
290 HTTPContext
*rtsp_c
);
292 static const char *my_program_name
;
293 static const char *my_program_dir
;
295 static const char *config_filename
;
296 static int ffserver_debug
;
297 static int ffserver_daemon
;
298 static int no_launch
;
299 static int need_to_start_children
;
301 /* maximum number of simultaneous HTTP connections */
302 static unsigned int nb_max_http_connections
= 2000;
303 static unsigned int nb_max_connections
= 5;
304 static unsigned int nb_connections
;
306 static uint64_t max_bandwidth
= 1000;
307 static uint64_t current_bandwidth
;
309 static int64_t cur_time
; // Making this global saves on passing it around everywhere
311 static AVLFG random_state
;
313 static FILE *logfile
= NULL
;
315 static char *ctime1(char *buf2
)
323 p
= buf2
+ strlen(p
) - 1;
329 static void http_vlog(const char *fmt
, va_list vargs
)
331 static int print_prefix
= 1;
336 fprintf(logfile
, "%s ", buf
);
338 print_prefix
= strstr(fmt
, "\n") != NULL
;
339 vfprintf(logfile
, fmt
, vargs
);
344 static void __attribute__ ((format (printf
, 1, 2))) http_log(const char *fmt
, ...)
347 va_start(vargs
, fmt
);
348 http_vlog(fmt
, vargs
);
352 static void http_av_log(void *ptr
, int level
, const char *fmt
, va_list vargs
)
354 static int print_prefix
= 1;
355 AVClass
*avc
= ptr ?
*(AVClass
**)ptr
: NULL
;
356 if (level
> av_log_get_level())
358 if (print_prefix
&& avc
)
359 http_log("[%s @ %p]", avc
->item_name(ptr
), ptr
);
360 print_prefix
= strstr(fmt
, "\n") != NULL
;
361 http_vlog(fmt
, vargs
);
364 static void log_connection(HTTPContext
*c
)
369 http_log("%s - - [%s] \"%s %s\" %d %"PRId64
"\n",
370 inet_ntoa(c
->from_addr
.sin_addr
), c
->method
, c
->url
,
371 c
->protocol
, (c
->http_error ? c
->http_error
: 200), c
->data_count
);
374 static void update_datarate(DataRateData
*drd
, int64_t count
)
376 if (!drd
->time1
&& !drd
->count1
) {
377 drd
->time1
= drd
->time2
= cur_time
;
378 drd
->count1
= drd
->count2
= count
;
379 } else if (cur_time
- drd
->time2
> 5000) {
380 drd
->time1
= drd
->time2
;
381 drd
->count1
= drd
->count2
;
382 drd
->time2
= cur_time
;
387 /* In bytes per second */
388 static int compute_datarate(DataRateData
*drd
, int64_t count
)
390 if (cur_time
== drd
->time1
)
393 return ((count
- drd
->count1
) * 1000) / (cur_time
- drd
->time1
);
397 static void start_children(FFStream
*feed
)
402 for (; feed
; feed
= feed
->next
) {
403 if (feed
->child_argv
&& !feed
->pid
) {
404 feed
->pid_start
= time(0);
409 http_log("Unable to create children\n");
418 av_strlcpy(pathname
, my_program_name
, sizeof(pathname
));
420 slash
= strrchr(pathname
, '/');
425 strcpy(slash
, "ffmpeg");
427 http_log("Launch commandline: ");
428 http_log("%s ", pathname
);
429 for (i
= 1; feed
->child_argv
[i
] && feed
->child_argv
[i
][0]; i
++)
430 http_log("%s ", feed
->child_argv
[i
]);
433 for (i
= 3; i
< 256; i
++)
436 if (!ffserver_debug
) {
437 i
= open("/dev/null", O_RDWR
);
446 /* This is needed to make relative pathnames work */
447 chdir(my_program_dir
);
449 signal(SIGPIPE
, SIG_DFL
);
451 execvp(pathname
, feed
->child_argv
);
459 /* open a listening socket */
460 static int socket_open_listen(struct sockaddr_in
*my_addr
)
464 server_fd
= socket(AF_INET
,SOCK_STREAM
,0);
471 setsockopt(server_fd
, SOL_SOCKET
, SO_REUSEADDR
, &tmp
, sizeof(tmp
));
473 if (bind (server_fd
, (struct sockaddr
*) my_addr
, sizeof (*my_addr
)) < 0) {
475 snprintf(bindmsg
, sizeof(bindmsg
), "bind(port %d)", ntohs(my_addr
->sin_port
));
477 closesocket(server_fd
);
481 if (listen (server_fd
, 5) < 0) {
483 closesocket(server_fd
);
486 ff_socket_nonblock(server_fd
, 1);
491 /* start all multicast streams */
492 static void start_multicast(void)
497 struct sockaddr_in dest_addr
;
498 int default_port
, stream_index
;
501 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
502 if (stream
->is_multicast
) {
503 /* open the RTP connection */
504 snprintf(session_id
, sizeof(session_id
), "%08x%08x",
505 av_lfg_get(&random_state
), av_lfg_get(&random_state
));
507 /* choose a port if none given */
508 if (stream
->multicast_port
== 0) {
509 stream
->multicast_port
= default_port
;
513 dest_addr
.sin_family
= AF_INET
;
514 dest_addr
.sin_addr
= stream
->multicast_ip
;
515 dest_addr
.sin_port
= htons(stream
->multicast_port
);
517 rtp_c
= rtp_new_connection(&dest_addr
, stream
, session_id
,
518 RTSP_LOWER_TRANSPORT_UDP_MULTICAST
);
522 if (open_input_stream(rtp_c
, "") < 0) {
523 http_log("Could not open input stream for stream '%s'\n",
528 /* open each RTP stream */
529 for(stream_index
= 0; stream_index
< stream
->nb_streams
;
531 dest_addr
.sin_port
= htons(stream
->multicast_port
+
533 if (rtp_new_av_stream(rtp_c
, stream_index
, &dest_addr
, NULL
) < 0) {
534 http_log("Could not open output stream '%s/streamid=%d'\n",
535 stream
->filename
, stream_index
);
540 /* change state to send data */
541 rtp_c
->state
= HTTPSTATE_SEND_DATA
;
546 /* main loop of the http server */
547 static int http_server(void)
549 int server_fd
= 0, rtsp_server_fd
= 0;
550 int ret
, delay
, delay1
;
551 struct pollfd
*poll_table
, *poll_entry
;
552 HTTPContext
*c
, *c_next
;
554 if(!(poll_table
= av_mallocz((nb_max_http_connections
+ 2)*sizeof(*poll_table
)))) {
555 http_log("Impossible to allocate a poll table handling %d connections.\n", nb_max_http_connections
);
559 if (my_http_addr
.sin_port
) {
560 server_fd
= socket_open_listen(&my_http_addr
);
565 if (my_rtsp_addr
.sin_port
) {
566 rtsp_server_fd
= socket_open_listen(&my_rtsp_addr
);
567 if (rtsp_server_fd
< 0)
571 if (!rtsp_server_fd
&& !server_fd
) {
572 http_log("HTTP and RTSP disabled.\n");
576 http_log("FFserver started.\n");
578 start_children(first_feed
);
583 poll_entry
= poll_table
;
585 poll_entry
->fd
= server_fd
;
586 poll_entry
->events
= POLLIN
;
589 if (rtsp_server_fd
) {
590 poll_entry
->fd
= rtsp_server_fd
;
591 poll_entry
->events
= POLLIN
;
595 /* wait for events on each HTTP handle */
602 case HTTPSTATE_SEND_HEADER
:
603 case RTSPSTATE_SEND_REPLY
:
604 case RTSPSTATE_SEND_PACKET
:
605 c
->poll_entry
= poll_entry
;
607 poll_entry
->events
= POLLOUT
;
610 case HTTPSTATE_SEND_DATA_HEADER
:
611 case HTTPSTATE_SEND_DATA
:
612 case HTTPSTATE_SEND_DATA_TRAILER
:
613 if (!c
->is_packetized
) {
614 /* for TCP, we output as much as we can (may need to put a limit) */
615 c
->poll_entry
= poll_entry
;
617 poll_entry
->events
= POLLOUT
;
620 /* when ffserver is doing the timing, we work by
621 looking at which packet need to be sent every
623 delay1
= 10; /* one tick wait XXX: 10 ms assumed */
628 case HTTPSTATE_WAIT_REQUEST
:
629 case HTTPSTATE_RECEIVE_DATA
:
630 case HTTPSTATE_WAIT_FEED
:
631 case RTSPSTATE_WAIT_REQUEST
:
632 /* need to catch errors */
633 c
->poll_entry
= poll_entry
;
635 poll_entry
->events
= POLLIN
;/* Maybe this will work */
639 c
->poll_entry
= NULL
;
645 /* wait for an event on one connection. We poll at least every
646 second to handle timeouts */
648 ret
= poll(poll_table
, poll_entry
- poll_table
, delay
);
649 if (ret
< 0 && ff_neterrno() != FF_NETERROR(EAGAIN
) &&
650 ff_neterrno() != FF_NETERROR(EINTR
))
654 cur_time
= av_gettime() / 1000;
656 if (need_to_start_children
) {
657 need_to_start_children
= 0;
658 start_children(first_feed
);
661 /* now handle the events */
662 for(c
= first_http_ctx
; c
!= NULL
; c
= c_next
) {
664 if (handle_connection(c
) < 0) {
665 /* close and free the connection */
671 poll_entry
= poll_table
;
673 /* new HTTP connection request ? */
674 if (poll_entry
->revents
& POLLIN
)
675 new_connection(server_fd
, 0);
678 if (rtsp_server_fd
) {
679 /* new RTSP connection request ? */
680 if (poll_entry
->revents
& POLLIN
)
681 new_connection(rtsp_server_fd
, 1);
686 /* start waiting for a new HTTP/RTSP request */
687 static void start_wait_request(HTTPContext
*c
, int is_rtsp
)
689 c
->buffer_ptr
= c
->buffer
;
690 c
->buffer_end
= c
->buffer
+ c
->buffer_size
- 1; /* leave room for '\0' */
693 c
->timeout
= cur_time
+ RTSP_REQUEST_TIMEOUT
;
694 c
->state
= RTSPSTATE_WAIT_REQUEST
;
696 c
->timeout
= cur_time
+ HTTP_REQUEST_TIMEOUT
;
697 c
->state
= HTTPSTATE_WAIT_REQUEST
;
701 static void http_send_too_busy_reply(int fd
)
704 int len
= snprintf(buffer
, sizeof(buffer
),
705 "HTTP/1.0 200 Server too busy\r\n"
706 "Content-type: text/html\r\n"
708 "<html><head><title>Too busy</title></head><body>\r\n"
709 "<p>The server is too busy to serve your request at this time.</p>\r\n"
710 "<p>The number of current connections is %d, and this exceeds the limit of %d.</p>\r\n"
711 "</body></html>\r\n",
712 nb_connections
, nb_max_connections
);
713 send(fd
, buffer
, len
, 0);
717 static void new_connection(int server_fd
, int is_rtsp
)
719 struct sockaddr_in from_addr
;
721 HTTPContext
*c
= NULL
;
723 len
= sizeof(from_addr
);
724 fd
= accept(server_fd
, (struct sockaddr
*)&from_addr
,
727 http_log("error during accept %s\n", strerror(errno
));
730 ff_socket_nonblock(fd
, 1);
732 if (nb_connections
>= nb_max_connections
) {
733 http_send_too_busy_reply(fd
);
737 /* add a new connection */
738 c
= av_mallocz(sizeof(HTTPContext
));
743 c
->poll_entry
= NULL
;
744 c
->from_addr
= from_addr
;
745 c
->buffer_size
= IOBUFFER_INIT_SIZE
;
746 c
->buffer
= av_malloc(c
->buffer_size
);
750 c
->next
= first_http_ctx
;
754 start_wait_request(c
, is_rtsp
);
766 static void close_connection(HTTPContext
*c
)
768 HTTPContext
**cp
, *c1
;
770 AVFormatContext
*ctx
;
774 /* remove connection from list */
775 cp
= &first_http_ctx
;
776 while ((*cp
) != NULL
) {
784 /* remove references, if any (XXX: do it faster) */
785 for(c1
= first_http_ctx
; c1
!= NULL
; c1
= c1
->next
) {
790 /* remove connection associated resources */
794 /* close each frame parser */
795 for(i
=0;i
<c
->fmt_in
->nb_streams
;i
++) {
796 st
= c
->fmt_in
->streams
[i
];
797 if (st
->codec
->codec
)
798 avcodec_close(st
->codec
);
800 av_close_input_file(c
->fmt_in
);
803 /* free RTP output streams if any */
806 nb_streams
= c
->stream
->nb_streams
;
808 for(i
=0;i
<nb_streams
;i
++) {
811 av_write_trailer(ctx
);
814 h
= c
->rtp_handles
[i
];
821 if (!c
->last_packet_sent
&& c
->state
== HTTPSTATE_SEND_DATA_TRAILER
) {
824 if (url_open_dyn_buf(&ctx
->pb
) >= 0) {
825 av_write_trailer(ctx
);
826 av_freep(&c
->pb_buffer
);
827 url_close_dyn_buf(ctx
->pb
, &c
->pb_buffer
);
832 for(i
=0; i
<ctx
->nb_streams
; i
++)
833 av_free(ctx
->streams
[i
]);
835 if (c
->stream
&& !c
->post
&& c
->stream
->stream_type
== STREAM_TYPE_LIVE
)
836 current_bandwidth
-= c
->stream
->bandwidth
;
838 /* signal that there is no feed if we are the feeder socket */
839 if (c
->state
== HTTPSTATE_RECEIVE_DATA
&& c
->stream
) {
840 c
->stream
->feed_opened
= 0;
844 av_freep(&c
->pb_buffer
);
845 av_freep(&c
->packet_buffer
);
851 static int handle_connection(HTTPContext
*c
)
856 case HTTPSTATE_WAIT_REQUEST
:
857 case RTSPSTATE_WAIT_REQUEST
:
859 if ((c
->timeout
- cur_time
) < 0)
861 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
864 /* no need to read if no events */
865 if (!(c
->poll_entry
->revents
& POLLIN
))
869 len
= recv(c
->fd
, c
->buffer_ptr
, 1, 0);
871 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
872 ff_neterrno() != FF_NETERROR(EINTR
))
874 } else if (len
== 0) {
877 /* search for end of request. */
879 c
->buffer_ptr
+= len
;
881 if ((ptr
>= c
->buffer
+ 2 && !memcmp(ptr
-2, "\n\n", 2)) ||
882 (ptr
>= c
->buffer
+ 4 && !memcmp(ptr
-4, "\r\n\r\n", 4))) {
883 /* request found : parse it and reply */
884 if (c
->state
== HTTPSTATE_WAIT_REQUEST
) {
885 ret
= http_parse_request(c
);
887 ret
= rtsp_parse_request(c
);
891 } else if (ptr
>= c
->buffer_end
) {
892 /* request too long: cannot do anything */
894 } else goto read_loop
;
898 case HTTPSTATE_SEND_HEADER
:
899 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
902 /* no need to write if no events */
903 if (!(c
->poll_entry
->revents
& POLLOUT
))
905 len
= send(c
->fd
, c
->buffer_ptr
, c
->buffer_end
- c
->buffer_ptr
, 0);
907 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
908 ff_neterrno() != FF_NETERROR(EINTR
)) {
909 /* error : close connection */
910 av_freep(&c
->pb_buffer
);
914 c
->buffer_ptr
+= len
;
916 c
->stream
->bytes_served
+= len
;
917 c
->data_count
+= len
;
918 if (c
->buffer_ptr
>= c
->buffer_end
) {
919 av_freep(&c
->pb_buffer
);
923 /* all the buffer was sent : synchronize to the incoming stream */
924 c
->state
= HTTPSTATE_SEND_DATA_HEADER
;
925 c
->buffer_ptr
= c
->buffer_end
= c
->buffer
;
930 case HTTPSTATE_SEND_DATA
:
931 case HTTPSTATE_SEND_DATA_HEADER
:
932 case HTTPSTATE_SEND_DATA_TRAILER
:
933 /* for packetized output, we consider we can always write (the
934 input streams sets the speed). It may be better to verify
935 that we do not rely too much on the kernel queues */
936 if (!c
->is_packetized
) {
937 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
940 /* no need to read if no events */
941 if (!(c
->poll_entry
->revents
& POLLOUT
))
944 if (http_send_data(c
) < 0)
946 /* close connection if trailer sent */
947 if (c
->state
== HTTPSTATE_SEND_DATA_TRAILER
)
950 case HTTPSTATE_RECEIVE_DATA
:
951 /* no need to read if no events */
952 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
))
954 if (!(c
->poll_entry
->revents
& POLLIN
))
956 if (http_receive_data(c
) < 0)
959 case HTTPSTATE_WAIT_FEED
:
960 /* no need to read if no events */
961 if (c
->poll_entry
->revents
& (POLLIN
| POLLERR
| POLLHUP
))
964 /* nothing to do, we'll be waken up by incoming feed packets */
967 case RTSPSTATE_SEND_REPLY
:
968 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
)) {
969 av_freep(&c
->pb_buffer
);
972 /* no need to write if no events */
973 if (!(c
->poll_entry
->revents
& POLLOUT
))
975 len
= send(c
->fd
, c
->buffer_ptr
, c
->buffer_end
- c
->buffer_ptr
, 0);
977 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
978 ff_neterrno() != FF_NETERROR(EINTR
)) {
979 /* error : close connection */
980 av_freep(&c
->pb_buffer
);
984 c
->buffer_ptr
+= len
;
985 c
->data_count
+= len
;
986 if (c
->buffer_ptr
>= c
->buffer_end
) {
987 /* all the buffer was sent : wait for a new request */
988 av_freep(&c
->pb_buffer
);
989 start_wait_request(c
, 1);
993 case RTSPSTATE_SEND_PACKET
:
994 if (c
->poll_entry
->revents
& (POLLERR
| POLLHUP
)) {
995 av_freep(&c
->packet_buffer
);
998 /* no need to write if no events */
999 if (!(c
->poll_entry
->revents
& POLLOUT
))
1001 len
= send(c
->fd
, c
->packet_buffer_ptr
,
1002 c
->packet_buffer_end
- c
->packet_buffer_ptr
, 0);
1004 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
1005 ff_neterrno() != FF_NETERROR(EINTR
)) {
1006 /* error : close connection */
1007 av_freep(&c
->packet_buffer
);
1011 c
->packet_buffer_ptr
+= len
;
1012 if (c
->packet_buffer_ptr
>= c
->packet_buffer_end
) {
1013 /* all the buffer was sent : wait for a new request */
1014 av_freep(&c
->packet_buffer
);
1015 c
->state
= RTSPSTATE_WAIT_REQUEST
;
1019 case HTTPSTATE_READY
:
1028 static int extract_rates(char *rates
, int ratelen
, const char *request
)
1032 for (p
= request
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
1033 if (strncasecmp(p
, "Pragma:", 7) == 0) {
1034 const char *q
= p
+ 7;
1036 while (*q
&& *q
!= '\n' && isspace(*q
))
1039 if (strncasecmp(q
, "stream-switch-entry=", 20) == 0) {
1045 memset(rates
, 0xff, ratelen
);
1048 while (*q
&& *q
!= '\n' && *q
!= ':')
1051 if (sscanf(q
, ":%d:%d", &stream_no
, &rate_no
) != 2)
1055 if (stream_no
< ratelen
&& stream_no
>= 0)
1056 rates
[stream_no
] = rate_no
;
1058 while (*q
&& *q
!= '\n' && !isspace(*q
))
1065 p
= strchr(p
, '\n');
1075 static int find_stream_in_feed(FFStream
*feed
, AVCodecContext
*codec
, int bit_rate
)
1078 int best_bitrate
= 100000000;
1081 for (i
= 0; i
< feed
->nb_streams
; i
++) {
1082 AVCodecContext
*feed_codec
= feed
->streams
[i
]->codec
;
1084 if (feed_codec
->codec_id
!= codec
->codec_id
||
1085 feed_codec
->sample_rate
!= codec
->sample_rate
||
1086 feed_codec
->width
!= codec
->width
||
1087 feed_codec
->height
!= codec
->height
)
1090 /* Potential stream */
1092 /* We want the fastest stream less than bit_rate, or the slowest
1093 * faster than bit_rate
1096 if (feed_codec
->bit_rate
<= bit_rate
) {
1097 if (best_bitrate
> bit_rate
|| feed_codec
->bit_rate
> best_bitrate
) {
1098 best_bitrate
= feed_codec
->bit_rate
;
1102 if (feed_codec
->bit_rate
< best_bitrate
) {
1103 best_bitrate
= feed_codec
->bit_rate
;
1112 static int modify_current_stream(HTTPContext
*c
, char *rates
)
1115 FFStream
*req
= c
->stream
;
1116 int action_required
= 0;
1118 /* Not much we can do for a feed */
1122 for (i
= 0; i
< req
->nb_streams
; i
++) {
1123 AVCodecContext
*codec
= req
->streams
[i
]->codec
;
1127 c
->switch_feed_streams
[i
] = req
->feed_streams
[i
];
1130 c
->switch_feed_streams
[i
] = find_stream_in_feed(req
->feed
, codec
, codec
->bit_rate
/ 2);
1133 /* Wants off or slow */
1134 c
->switch_feed_streams
[i
] = find_stream_in_feed(req
->feed
, codec
, codec
->bit_rate
/ 4);
1136 /* This doesn't work well when it turns off the only stream! */
1137 c
->switch_feed_streams
[i
] = -2;
1138 c
->feed_streams
[i
] = -2;
1143 if (c
->switch_feed_streams
[i
] >= 0 && c
->switch_feed_streams
[i
] != c
->feed_streams
[i
])
1144 action_required
= 1;
1147 return action_required
;
1151 static void do_switch_stream(HTTPContext
*c
, int i
)
1153 if (c
->switch_feed_streams
[i
] >= 0) {
1155 c
->feed_streams
[i
] = c
->switch_feed_streams
[i
];
1158 /* Now update the stream */
1160 c
->switch_feed_streams
[i
] = -1;
1163 /* XXX: factorize in utils.c ? */
1164 /* XXX: take care with different space meaning */
1165 static void skip_spaces(const char **pp
)
1169 while (*p
== ' ' || *p
== '\t')
1174 static void get_word(char *buf
, int buf_size
, const char **pp
)
1182 while (!isspace(*p
) && *p
!= '\0') {
1183 if ((q
- buf
) < buf_size
- 1)
1192 static void get_arg(char *buf
, int buf_size
, const char **pp
)
1199 while (isspace(*p
)) p
++;
1202 if (*p
== '\"' || *p
== '\'')
1214 if ((q
- buf
) < buf_size
- 1)
1219 if (quote
&& *p
== quote
)
1224 static int validate_acl(FFStream
*stream
, HTTPContext
*c
)
1226 enum IPAddressAction last_action
= IP_DENY
;
1228 struct in_addr
*src
= &c
->from_addr
.sin_addr
;
1229 unsigned long src_addr
= src
->s_addr
;
1231 for (acl
= stream
->acl
; acl
; acl
= acl
->next
) {
1232 if (src_addr
>= acl
->first
.s_addr
&& src_addr
<= acl
->last
.s_addr
)
1233 return (acl
->action
== IP_ALLOW
) ?
1 : 0;
1234 last_action
= acl
->action
;
1237 /* Nothing matched, so return not the last action */
1238 return (last_action
== IP_DENY
) ?
1 : 0;
1241 /* compute the real filename of a file by matching it without its
1242 extensions to all the stream filenames */
1243 static void compute_real_filename(char *filename
, int max_size
)
1250 /* compute filename by matching without the file extensions */
1251 av_strlcpy(file1
, filename
, sizeof(file1
));
1252 p
= strrchr(file1
, '.');
1255 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
1256 av_strlcpy(file2
, stream
->filename
, sizeof(file2
));
1257 p
= strrchr(file2
, '.');
1260 if (!strcmp(file1
, file2
)) {
1261 av_strlcpy(filename
, stream
->filename
, max_size
);
1276 /* parse http request and prepare header */
1277 static int http_parse_request(HTTPContext
*c
)
1280 enum RedirType redir_type
;
1282 char info
[1024], filename
[1024];
1286 const char *mime_type
;
1290 char *useragent
= 0;
1293 get_word(cmd
, sizeof(cmd
), (const char **)&p
);
1294 av_strlcpy(c
->method
, cmd
, sizeof(c
->method
));
1296 if (!strcmp(cmd
, "GET"))
1298 else if (!strcmp(cmd
, "POST"))
1303 get_word(url
, sizeof(url
), (const char **)&p
);
1304 av_strlcpy(c
->url
, url
, sizeof(c
->url
));
1306 get_word(protocol
, sizeof(protocol
), (const char **)&p
);
1307 if (strcmp(protocol
, "HTTP/1.0") && strcmp(protocol
, "HTTP/1.1"))
1310 av_strlcpy(c
->protocol
, protocol
, sizeof(c
->protocol
));
1313 http_log("%s - - New connection: %s %s\n", inet_ntoa(c
->from_addr
.sin_addr
), cmd
, url
);
1315 /* find the filename and the optional info string in the request */
1316 p
= strchr(url
, '?');
1318 av_strlcpy(info
, p
, sizeof(info
));
1323 av_strlcpy(filename
, url
+ ((*url
== '/') ?
1 : 0), sizeof(filename
)-1);
1325 for (p
= c
->buffer
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
1326 if (strncasecmp(p
, "User-Agent:", 11) == 0) {
1328 if (*useragent
&& *useragent
!= '\n' && isspace(*useragent
))
1332 p
= strchr(p
, '\n');
1339 redir_type
= REDIR_NONE
;
1340 if (av_match_ext(filename
, "asx")) {
1341 redir_type
= REDIR_ASX
;
1342 filename
[strlen(filename
)-1] = 'f';
1343 } else if (av_match_ext(filename
, "asf") &&
1344 (!useragent
|| strncasecmp(useragent
, "NSPlayer", 8) != 0)) {
1345 /* if this isn't WMP or lookalike, return the redirector file */
1346 redir_type
= REDIR_ASF
;
1347 } else if (av_match_ext(filename
, "rpm,ram")) {
1348 redir_type
= REDIR_RAM
;
1349 strcpy(filename
+ strlen(filename
)-2, "m");
1350 } else if (av_match_ext(filename
, "rtsp")) {
1351 redir_type
= REDIR_RTSP
;
1352 compute_real_filename(filename
, sizeof(filename
) - 1);
1353 } else if (av_match_ext(filename
, "sdp")) {
1354 redir_type
= REDIR_SDP
;
1355 compute_real_filename(filename
, sizeof(filename
) - 1);
1358 // "redirect" / request to index.html
1359 if (!strlen(filename
))
1360 av_strlcpy(filename
, "index.html", sizeof(filename
) - 1);
1362 stream
= first_stream
;
1363 while (stream
!= NULL
) {
1364 if (!strcmp(stream
->filename
, filename
) && validate_acl(stream
, c
))
1366 stream
= stream
->next
;
1368 if (stream
== NULL
) {
1369 snprintf(msg
, sizeof(msg
), "File '%s' not found", url
);
1370 http_log("File '%s' not found\n", url
);
1375 memcpy(c
->feed_streams
, stream
->feed_streams
, sizeof(c
->feed_streams
));
1376 memset(c
->switch_feed_streams
, -1, sizeof(c
->switch_feed_streams
));
1378 if (stream
->stream_type
== STREAM_TYPE_REDIRECT
) {
1379 c
->http_error
= 301;
1381 q
+= snprintf(q
, c
->buffer_size
,
1382 "HTTP/1.0 301 Moved\r\n"
1384 "Content-type: text/html\r\n"
1386 "<html><head><title>Moved</title></head><body>\r\n"
1387 "You should be <a href=\"%s\">redirected</a>.\r\n"
1388 "</body></html>\r\n", stream
->feed_filename
, stream
->feed_filename
);
1389 /* prepare output buffer */
1390 c
->buffer_ptr
= c
->buffer
;
1392 c
->state
= HTTPSTATE_SEND_HEADER
;
1396 /* If this is WMP, get the rate information */
1397 if (extract_rates(ratebuf
, sizeof(ratebuf
), c
->buffer
)) {
1398 if (modify_current_stream(c
, ratebuf
)) {
1399 for (i
= 0; i
< FF_ARRAY_ELEMS(c
->feed_streams
); i
++) {
1400 if (c
->switch_feed_streams
[i
] >= 0)
1401 do_switch_stream(c
, i
);
1406 if (c
->post
== 0 && stream
->stream_type
== STREAM_TYPE_LIVE
)
1407 current_bandwidth
+= stream
->bandwidth
;
1409 /* If already streaming this feed, do not let start another feeder. */
1410 if (stream
->feed_opened
) {
1411 snprintf(msg
, sizeof(msg
), "This feed is already being received.");
1412 http_log("Feed '%s' already being received\n", stream
->feed_filename
);
1416 if (c
->post
== 0 && max_bandwidth
< current_bandwidth
) {
1417 c
->http_error
= 200;
1419 q
+= snprintf(q
, c
->buffer_size
,
1420 "HTTP/1.0 200 Server too busy\r\n"
1421 "Content-type: text/html\r\n"
1423 "<html><head><title>Too busy</title></head><body>\r\n"
1424 "<p>The server is too busy to serve your request at this time.</p>\r\n"
1425 "<p>The bandwidth being served (including your stream) is %"PRIu64
"kbit/sec, "
1426 "and this exceeds the limit of %"PRIu64
"kbit/sec.</p>\r\n"
1427 "</body></html>\r\n", current_bandwidth
, max_bandwidth
);
1428 /* prepare output buffer */
1429 c
->buffer_ptr
= c
->buffer
;
1431 c
->state
= HTTPSTATE_SEND_HEADER
;
1435 if (redir_type
!= REDIR_NONE
) {
1438 for (p
= c
->buffer
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
1439 if (strncasecmp(p
, "Host:", 5) == 0) {
1443 p
= strchr(p
, '\n');
1454 while (isspace(*hostinfo
))
1457 eoh
= strchr(hostinfo
, '\n');
1459 if (eoh
[-1] == '\r')
1462 if (eoh
- hostinfo
< sizeof(hostbuf
) - 1) {
1463 memcpy(hostbuf
, hostinfo
, eoh
- hostinfo
);
1464 hostbuf
[eoh
- hostinfo
] = 0;
1466 c
->http_error
= 200;
1468 switch(redir_type
) {
1470 q
+= snprintf(q
, c
->buffer_size
,
1471 "HTTP/1.0 200 ASX Follows\r\n"
1472 "Content-type: video/x-ms-asf\r\n"
1474 "<ASX Version=\"3\">\r\n"
1475 //"<!-- Autogenerated by ffserver -->\r\n"
1476 "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
1477 "</ASX>\r\n", hostbuf
, filename
, info
);
1480 q
+= snprintf(q
, c
->buffer_size
,
1481 "HTTP/1.0 200 RAM Follows\r\n"
1482 "Content-type: audio/x-pn-realaudio\r\n"
1484 "# Autogenerated by ffserver\r\n"
1485 "http://%s/%s%s\r\n", hostbuf
, filename
, info
);
1488 q
+= snprintf(q
, c
->buffer_size
,
1489 "HTTP/1.0 200 ASF Redirect follows\r\n"
1490 "Content-type: video/x-ms-asf\r\n"
1493 "Ref1=http://%s/%s%s\r\n", hostbuf
, filename
, info
);
1497 char hostname
[256], *p
;
1498 /* extract only hostname */
1499 av_strlcpy(hostname
, hostbuf
, sizeof(hostname
));
1500 p
= strrchr(hostname
, ':');
1503 q
+= snprintf(q
, c
->buffer_size
,
1504 "HTTP/1.0 200 RTSP Redirect follows\r\n"
1505 /* XXX: incorrect mime type ? */
1506 "Content-type: application/x-rtsp\r\n"
1508 "rtsp://%s:%d/%s\r\n", hostname
, ntohs(my_rtsp_addr
.sin_port
), filename
);
1514 int sdp_data_size
, len
;
1515 struct sockaddr_in my_addr
;
1517 q
+= snprintf(q
, c
->buffer_size
,
1518 "HTTP/1.0 200 OK\r\n"
1519 "Content-type: application/sdp\r\n"
1522 len
= sizeof(my_addr
);
1523 getsockname(c
->fd
, (struct sockaddr
*)&my_addr
, &len
);
1525 /* XXX: should use a dynamic buffer */
1526 sdp_data_size
= prepare_sdp_description(stream
,
1529 if (sdp_data_size
> 0) {
1530 memcpy(q
, sdp_data
, sdp_data_size
);
1542 /* prepare output buffer */
1543 c
->buffer_ptr
= c
->buffer
;
1545 c
->state
= HTTPSTATE_SEND_HEADER
;
1551 snprintf(msg
, sizeof(msg
), "ASX/RAM file not handled");
1555 stream
->conns_served
++;
1557 /* XXX: add there authenticate and IP match */
1560 /* if post, it means a feed is being sent */
1561 if (!stream
->is_feed
) {
1562 /* However it might be a status report from WMP! Let us log the
1563 * data as it might come in handy one day. */
1567 for (p
= c
->buffer
; *p
&& *p
!= '\r' && *p
!= '\n'; ) {
1568 if (strncasecmp(p
, "Pragma: log-line=", 17) == 0) {
1572 if (strncasecmp(p
, "Pragma: client-id=", 18) == 0)
1573 client_id
= strtol(p
+ 18, 0, 10);
1574 p
= strchr(p
, '\n');
1582 char *eol
= strchr(logline
, '\n');
1587 if (eol
[-1] == '\r')
1589 http_log("%.*s\n", (int) (eol
- logline
), logline
);
1590 c
->suppress_log
= 1;
1595 http_log("\nGot request:\n%s\n", c
->buffer
);
1598 if (client_id
&& extract_rates(ratebuf
, sizeof(ratebuf
), c
->buffer
)) {
1601 /* Now we have to find the client_id */
1602 for (wmpc
= first_http_ctx
; wmpc
; wmpc
= wmpc
->next
) {
1603 if (wmpc
->wmp_client_id
== client_id
)
1607 if (wmpc
&& modify_current_stream(wmpc
, ratebuf
))
1608 wmpc
->switch_pending
= 1;
1611 snprintf(msg
, sizeof(msg
), "POST command not handled");
1615 if (http_start_receive_data(c
) < 0) {
1616 snprintf(msg
, sizeof(msg
), "could not open feed");
1620 c
->state
= HTTPSTATE_RECEIVE_DATA
;
1625 if (strcmp(stream
->filename
+ strlen(stream
->filename
) - 4, ".asf") == 0)
1626 http_log("\nGot request:\n%s\n", c
->buffer
);
1629 if (c
->stream
->stream_type
== STREAM_TYPE_STATUS
)
1632 /* open input stream */
1633 if (open_input_stream(c
, info
) < 0) {
1634 snprintf(msg
, sizeof(msg
), "Input stream corresponding to '%s' not found", url
);
1638 /* prepare http header */
1640 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "HTTP/1.0 200 OK\r\n");
1641 mime_type
= c
->stream
->fmt
->mime_type
;
1643 mime_type
= "application/x-octet-stream";
1644 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Pragma: no-cache\r\n");
1646 /* for asf, we need extra headers */
1647 if (!strcmp(c
->stream
->fmt
->name
,"asf_stream")) {
1648 /* Need to allocate a client id */
1650 c
->wmp_client_id
= av_lfg_get(&random_state
);
1652 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
);
1654 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "Content-Type: %s\r\n", mime_type
);
1655 q
+= snprintf(q
, q
- (char *) c
->buffer
+ c
->buffer_size
, "\r\n");
1657 /* prepare output buffer */
1659 c
->buffer_ptr
= c
->buffer
;
1661 c
->state
= HTTPSTATE_SEND_HEADER
;
1664 c
->http_error
= 404;
1666 q
+= snprintf(q
, c
->buffer_size
,
1667 "HTTP/1.0 404 Not Found\r\n"
1668 "Content-type: text/html\r\n"
1671 "<head><title>404 Not Found</title></head>\n"
1674 /* prepare output buffer */
1675 c
->buffer_ptr
= c
->buffer
;
1677 c
->state
= HTTPSTATE_SEND_HEADER
;
1681 c
->http_error
= 200; /* horrible : we use this value to avoid
1682 going to the send data state */
1683 c
->state
= HTTPSTATE_SEND_HEADER
;
1687 static void fmt_bytecount(ByteIOContext
*pb
, int64_t count
)
1689 static const char *suffix
= " kMGTP";
1692 for (s
= suffix
; count
>= 100000 && s
[1]; count
/= 1000, s
++);
1694 url_fprintf(pb
, "%"PRId64
"%c", count
, *s
);
1697 static void compute_status(HTTPContext
*c
)
1706 if (url_open_dyn_buf(&pb
) < 0) {
1707 /* XXX: return an error ? */
1708 c
->buffer_ptr
= c
->buffer
;
1709 c
->buffer_end
= c
->buffer
;
1713 url_fprintf(pb
, "HTTP/1.0 200 OK\r\n");
1714 url_fprintf(pb
, "Content-type: %s\r\n", "text/html");
1715 url_fprintf(pb
, "Pragma: no-cache\r\n");
1716 url_fprintf(pb
, "\r\n");
1718 url_fprintf(pb
, "<html><head><title>%s Status</title>\n", program_name
);
1719 if (c
->stream
->feed_filename
[0])
1720 url_fprintf(pb
, "<link rel=\"shortcut icon\" href=\"%s\">\n", c
->stream
->feed_filename
);
1721 url_fprintf(pb
, "</head>\n<body>");
1722 url_fprintf(pb
, "<h1>%s Status</h1>\n", program_name
);
1724 url_fprintf(pb
, "<h2>Available Streams</h2>\n");
1725 url_fprintf(pb
, "<table cellspacing=0 cellpadding=4>\n");
1726 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");
1727 stream
= first_stream
;
1728 while (stream
!= NULL
) {
1729 char sfilename
[1024];
1732 if (stream
->feed
!= stream
) {
1733 av_strlcpy(sfilename
, stream
->filename
, sizeof(sfilename
) - 10);
1734 eosf
= sfilename
+ strlen(sfilename
);
1735 if (eosf
- sfilename
>= 4) {
1736 if (strcmp(eosf
- 4, ".asf") == 0)
1737 strcpy(eosf
- 4, ".asx");
1738 else if (strcmp(eosf
- 3, ".rm") == 0)
1739 strcpy(eosf
- 3, ".ram");
1740 else if (stream
->fmt
&& !strcmp(stream
->fmt
->name
, "rtp")) {
1741 /* generate a sample RTSP director if
1742 unicast. Generate an SDP redirector if
1744 eosf
= strrchr(sfilename
, '.');
1746 eosf
= sfilename
+ strlen(sfilename
);
1747 if (stream
->is_multicast
)
1748 strcpy(eosf
, ".sdp");
1750 strcpy(eosf
, ".rtsp");
1754 url_fprintf(pb
, "<tr><td><a href=\"/%s\">%s</a> ",
1755 sfilename
, stream
->filename
);
1756 url_fprintf(pb
, "<td align=right> %d <td align=right> ",
1757 stream
->conns_served
);
1758 fmt_bytecount(pb
, stream
->bytes_served
);
1759 switch(stream
->stream_type
) {
1760 case STREAM_TYPE_LIVE
: {
1761 int audio_bit_rate
= 0;
1762 int video_bit_rate
= 0;
1763 const char *audio_codec_name
= "";
1764 const char *video_codec_name
= "";
1765 const char *audio_codec_name_extra
= "";
1766 const char *video_codec_name_extra
= "";
1768 for(i
=0;i
<stream
->nb_streams
;i
++) {
1769 AVStream
*st
= stream
->streams
[i
];
1770 AVCodec
*codec
= avcodec_find_encoder(st
->codec
->codec_id
);
1771 switch(st
->codec
->codec_type
) {
1772 case CODEC_TYPE_AUDIO
:
1773 audio_bit_rate
+= st
->codec
->bit_rate
;
1775 if (*audio_codec_name
)
1776 audio_codec_name_extra
= "...";
1777 audio_codec_name
= codec
->name
;
1780 case CODEC_TYPE_VIDEO
:
1781 video_bit_rate
+= st
->codec
->bit_rate
;
1783 if (*video_codec_name
)
1784 video_codec_name_extra
= "...";
1785 video_codec_name
= codec
->name
;
1788 case CODEC_TYPE_DATA
:
1789 video_bit_rate
+= st
->codec
->bit_rate
;
1795 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",
1798 video_bit_rate
/ 1000, video_codec_name
, video_codec_name_extra
,
1799 audio_bit_rate
/ 1000, audio_codec_name
, audio_codec_name_extra
);
1801 url_fprintf(pb
, "<td>%s", stream
->feed
->filename
);
1803 url_fprintf(pb
, "<td>%s", stream
->feed_filename
);
1804 url_fprintf(pb
, "\n");
1808 url_fprintf(pb
, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
1812 stream
= stream
->next
;
1814 url_fprintf(pb
, "</table>\n");
1816 stream
= first_stream
;
1817 while (stream
!= NULL
) {
1818 if (stream
->feed
== stream
) {
1819 url_fprintf(pb
, "<h2>Feed %s</h2>", stream
->filename
);
1821 url_fprintf(pb
, "Running as pid %d.\n", stream
->pid
);
1823 #if defined(linux) && !defined(CONFIG_NOCUTILS)
1828 /* This is somewhat linux specific I guess */
1829 snprintf(ps_cmd
, sizeof(ps_cmd
),
1830 "ps -o \"%%cpu,cputime\" --no-headers %d",
1833 pid_stat
= popen(ps_cmd
, "r");
1838 if (fscanf(pid_stat
, "%10s %64s", cpuperc
,
1840 url_fprintf(pb
, "Currently using %s%% of the cpu. Total time used %s.\n",
1848 url_fprintf(pb
, "<p>");
1850 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");
1852 for (i
= 0; i
< stream
->nb_streams
; i
++) {
1853 AVStream
*st
= stream
->streams
[i
];
1854 AVCodec
*codec
= avcodec_find_encoder(st
->codec
->codec_id
);
1855 const char *type
= "unknown";
1856 char parameters
[64];
1860 switch(st
->codec
->codec_type
) {
1861 case CODEC_TYPE_AUDIO
:
1863 snprintf(parameters
, sizeof(parameters
), "%d channel(s), %d Hz", st
->codec
->channels
, st
->codec
->sample_rate
);
1865 case CODEC_TYPE_VIDEO
:
1867 snprintf(parameters
, sizeof(parameters
), "%dx%d, q=%d-%d, fps=%d", st
->codec
->width
, st
->codec
->height
,
1868 st
->codec
->qmin
, st
->codec
->qmax
, st
->codec
->time_base
.den
/ st
->codec
->time_base
.num
);
1873 url_fprintf(pb
, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
1874 i
, type
, st
->codec
->bit_rate
/1000, codec ? codec
->name
: "", parameters
);
1876 url_fprintf(pb
, "</table>\n");
1879 stream
= stream
->next
;
1882 /* connection status */
1883 url_fprintf(pb
, "<h2>Connection Status</h2>\n");
1885 url_fprintf(pb
, "Number of connections: %d / %d<br>\n",
1886 nb_connections
, nb_max_connections
);
1888 url_fprintf(pb
, "Bandwidth in use: %"PRIu64
"k / %"PRIu64
"k<br>\n",
1889 current_bandwidth
, max_bandwidth
);
1891 url_fprintf(pb
, "<table>\n");
1892 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");
1893 c1
= first_http_ctx
;
1895 while (c1
!= NULL
) {
1901 for (j
= 0; j
< c1
->stream
->nb_streams
; j
++) {
1902 if (!c1
->stream
->feed
)
1903 bitrate
+= c1
->stream
->streams
[j
]->codec
->bit_rate
;
1904 else if (c1
->feed_streams
[j
] >= 0)
1905 bitrate
+= c1
->stream
->feed
->streams
[c1
->feed_streams
[j
]]->codec
->bit_rate
;
1910 p
= inet_ntoa(c1
->from_addr
.sin_addr
);
1911 url_fprintf(pb
, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
1913 c1
->stream ? c1
->stream
->filename
: "",
1914 c1
->state
== HTTPSTATE_RECEIVE_DATA ?
"(input)" : "",
1917 http_state
[c1
->state
]);
1918 fmt_bytecount(pb
, bitrate
);
1919 url_fprintf(pb
, "<td align=right>");
1920 fmt_bytecount(pb
, compute_datarate(&c1
->datarate
, c1
->data_count
) * 8);
1921 url_fprintf(pb
, "<td align=right>");
1922 fmt_bytecount(pb
, c1
->data_count
);
1923 url_fprintf(pb
, "\n");
1926 url_fprintf(pb
, "</table>\n");
1931 url_fprintf(pb
, "<hr size=1 noshade>Generated at %s", p
);
1932 url_fprintf(pb
, "</body>\n</html>\n");
1934 len
= url_close_dyn_buf(pb
, &c
->pb_buffer
);
1935 c
->buffer_ptr
= c
->pb_buffer
;
1936 c
->buffer_end
= c
->pb_buffer
+ len
;
1939 /* check if the parser needs to be opened for stream i */
1940 static void open_parser(AVFormatContext
*s
, int i
)
1942 AVStream
*st
= s
->streams
[i
];
1945 if (!st
->codec
->codec
) {
1946 codec
= avcodec_find_decoder(st
->codec
->codec_id
);
1947 if (codec
&& (codec
->capabilities
& CODEC_CAP_PARSE_ONLY
)) {
1948 st
->codec
->parse_only
= 1;
1949 if (avcodec_open(st
->codec
, codec
) < 0)
1950 st
->codec
->parse_only
= 0;
1955 static int open_input_stream(HTTPContext
*c
, const char *info
)
1958 char input_filename
[1024];
1960 int buf_size
, i
, ret
;
1963 /* find file name */
1964 if (c
->stream
->feed
) {
1965 strcpy(input_filename
, c
->stream
->feed
->feed_filename
);
1966 buf_size
= FFM_PACKET_SIZE
;
1967 /* compute position (absolute time) */
1968 if (find_info_tag(buf
, sizeof(buf
), "date", info
)) {
1969 stream_pos
= parse_date(buf
, 0);
1970 if (stream_pos
== INT64_MIN
)
1972 } else if (find_info_tag(buf
, sizeof(buf
), "buffer", info
)) {
1973 int prebuffer
= strtol(buf
, 0, 10);
1974 stream_pos
= av_gettime() - prebuffer
* (int64_t)1000000;
1976 stream_pos
= av_gettime() - c
->stream
->prebuffer
* (int64_t)1000;
1978 strcpy(input_filename
, c
->stream
->feed_filename
);
1980 /* compute position (relative time) */
1981 if (find_info_tag(buf
, sizeof(buf
), "date", info
)) {
1982 stream_pos
= parse_date(buf
, 1);
1983 if (stream_pos
== INT64_MIN
)
1988 if (input_filename
[0] == '\0')
1992 if ((ret
= av_open_input_file(&s
, input_filename
, c
->stream
->ifmt
,
1993 buf_size
, c
->stream
->ap_in
)) < 0) {
1994 http_log("could not open %s: %d\n", input_filename
, ret
);
1997 s
->flags
|= AVFMT_FLAG_GENPTS
;
1999 if (strcmp(s
->iformat
->name
, "ffm") && av_find_stream_info(c
->fmt_in
) < 0) {
2000 http_log("Could not find stream info '%s'\n", input_filename
);
2001 av_close_input_file(s
);
2005 /* open each parser */
2006 for(i
=0;i
<s
->nb_streams
;i
++)
2009 /* choose stream as clock source (we favorize video stream if
2010 present) for packet sending */
2011 c
->pts_stream_index
= 0;
2012 for(i
=0;i
<c
->stream
->nb_streams
;i
++) {
2013 if (c
->pts_stream_index
== 0 &&
2014 c
->stream
->streams
[i
]->codec
->codec_type
== CODEC_TYPE_VIDEO
) {
2015 c
->pts_stream_index
= i
;
2020 if (c
->fmt_in
->iformat
->read_seek
)
2021 av_seek_frame(c
->fmt_in
, -1, stream_pos
, 0);
2023 /* set the start time (needed for maxtime and RTP packet timing) */
2024 c
->start_time
= cur_time
;
2025 c
->first_pts
= AV_NOPTS_VALUE
;
2029 /* return the server clock (in us) */
2030 static int64_t get_server_clock(HTTPContext
*c
)
2032 /* compute current pts value from system time */
2033 return (cur_time
- c
->start_time
) * 1000;
2036 /* return the estimated time at which the current packet must be sent
2038 static int64_t get_packet_send_clock(HTTPContext
*c
)
2040 int bytes_left
, bytes_sent
, frame_bytes
;
2042 frame_bytes
= c
->cur_frame_bytes
;
2043 if (frame_bytes
<= 0)
2046 bytes_left
= c
->buffer_end
- c
->buffer_ptr
;
2047 bytes_sent
= frame_bytes
- bytes_left
;
2048 return c
->cur_pts
+ (c
->cur_frame_duration
* bytes_sent
) / frame_bytes
;
2053 static int http_prepare_data(HTTPContext
*c
)
2056 AVFormatContext
*ctx
;
2058 av_freep(&c
->pb_buffer
);
2060 case HTTPSTATE_SEND_DATA_HEADER
:
2061 memset(&c
->fmt_ctx
, 0, sizeof(c
->fmt_ctx
));
2062 av_metadata_set(&c
->fmt_ctx
.metadata
, "author" ,c
->stream
->author
);
2063 av_metadata_set(&c
->fmt_ctx
.metadata
, "comment" ,c
->stream
->comment
);
2064 av_metadata_set(&c
->fmt_ctx
.metadata
, "copyright",c
->stream
->copyright
);
2065 av_metadata_set(&c
->fmt_ctx
.metadata
, "title" ,c
->stream
->title
);
2067 for(i
=0;i
<c
->stream
->nb_streams
;i
++) {
2070 st
= av_mallocz(sizeof(AVStream
));
2071 c
->fmt_ctx
.streams
[i
] = st
;
2072 /* if file or feed, then just take streams from FFStream struct */
2073 if (!c
->stream
->feed
||
2074 c
->stream
->feed
== c
->stream
)
2075 src
= c
->stream
->streams
[i
];
2077 src
= c
->stream
->feed
->streams
[c
->stream
->feed_streams
[i
]];
2081 st
->codec
->frame_number
= 0; /* XXX: should be done in
2082 AVStream, not in codec */
2084 /* set output format parameters */
2085 c
->fmt_ctx
.oformat
= c
->stream
->fmt
;
2086 c
->fmt_ctx
.nb_streams
= c
->stream
->nb_streams
;
2088 c
->got_key_frame
= 0;
2090 /* prepare header and save header data in a stream */
2091 if (url_open_dyn_buf(&c
->fmt_ctx
.pb
) < 0) {
2092 /* XXX: potential leak */
2095 c
->fmt_ctx
.pb
->is_streamed
= 1;
2098 * HACK to avoid mpeg ps muxer to spit many underflow errors
2099 * Default value from FFmpeg
2100 * Try to set it use configuration option
2102 c
->fmt_ctx
.preload
= (int)(0.5*AV_TIME_BASE
);
2103 c
->fmt_ctx
.max_delay
= (int)(0.7*AV_TIME_BASE
);
2105 av_set_parameters(&c
->fmt_ctx
, NULL
);
2106 if (av_write_header(&c
->fmt_ctx
) < 0) {
2107 http_log("Error writing output header\n");
2111 len
= url_close_dyn_buf(c
->fmt_ctx
.pb
, &c
->pb_buffer
);
2112 c
->buffer_ptr
= c
->pb_buffer
;
2113 c
->buffer_end
= c
->pb_buffer
+ len
;
2115 c
->state
= HTTPSTATE_SEND_DATA
;
2116 c
->last_packet_sent
= 0;
2118 case HTTPSTATE_SEND_DATA
:
2119 /* find a new packet */
2120 /* read a packet from the input stream */
2121 if (c
->stream
->feed
)
2122 ffm_set_write_index(c
->fmt_in
,
2123 c
->stream
->feed
->feed_write_index
,
2124 c
->stream
->feed
->feed_size
);
2126 if (c
->stream
->max_time
&&
2127 c
->stream
->max_time
+ c
->start_time
- cur_time
< 0)
2128 /* We have timed out */
2129 c
->state
= HTTPSTATE_SEND_DATA_TRAILER
;
2133 if (av_read_frame(c
->fmt_in
, &pkt
) < 0) {
2134 if (c
->stream
->feed
&& c
->stream
->feed
->feed_opened
) {
2135 /* if coming from feed, it means we reached the end of the
2136 ffm file, so must wait for more data */
2137 c
->state
= HTTPSTATE_WAIT_FEED
;
2138 return 1; /* state changed */
2140 if (c
->stream
->loop
) {
2141 av_close_input_file(c
->fmt_in
);
2143 if (open_input_stream(c
, "") < 0)
2148 /* must send trailer now because eof or error */
2149 c
->state
= HTTPSTATE_SEND_DATA_TRAILER
;
2153 int source_index
= pkt
.stream_index
;
2154 /* update first pts if needed */
2155 if (c
->first_pts
== AV_NOPTS_VALUE
) {
2156 c
->first_pts
= av_rescale_q(pkt
.dts
, c
->fmt_in
->streams
[pkt
.stream_index
]->time_base
, AV_TIME_BASE_Q
);
2157 c
->start_time
= cur_time
;
2159 /* send it to the appropriate stream */
2160 if (c
->stream
->feed
) {
2161 /* if coming from a feed, select the right stream */
2162 if (c
->switch_pending
) {
2163 c
->switch_pending
= 0;
2164 for(i
=0;i
<c
->stream
->nb_streams
;i
++) {
2165 if (c
->switch_feed_streams
[i
] == pkt
.stream_index
)
2166 if (pkt
.flags
& PKT_FLAG_KEY
)
2167 do_switch_stream(c
, i
);
2168 if (c
->switch_feed_streams
[i
] >= 0)
2169 c
->switch_pending
= 1;
2172 for(i
=0;i
<c
->stream
->nb_streams
;i
++) {
2173 if (c
->feed_streams
[i
] == pkt
.stream_index
) {
2174 AVStream
*st
= c
->fmt_in
->streams
[source_index
];
2175 pkt
.stream_index
= i
;
2176 if (pkt
.flags
& PKT_FLAG_KEY
&&
2177 (st
->codec
->codec_type
== CODEC_TYPE_VIDEO
||
2178 c
->stream
->nb_streams
== 1))
2179 c
->got_key_frame
= 1;
2180 if (!c
->stream
->send_on_key
|| c
->got_key_frame
)
2185 AVCodecContext
*codec
;
2186 AVStream
*ist
, *ost
;
2188 ist
= c
->fmt_in
->streams
[source_index
];
2189 /* specific handling for RTP: we use several
2190 output stream (one for each RTP
2191 connection). XXX: need more abstract handling */
2192 if (c
->is_packetized
) {
2193 /* compute send time and duration */
2194 c
->cur_pts
= av_rescale_q(pkt
.dts
, ist
->time_base
, AV_TIME_BASE_Q
);
2195 if (ist
->start_time
!= AV_NOPTS_VALUE
)
2196 c
->cur_pts
-= av_rescale_q(ist
->start_time
, ist
->time_base
, AV_TIME_BASE_Q
);
2197 c
->cur_frame_duration
= av_rescale_q(pkt
.duration
, ist
->time_base
, AV_TIME_BASE_Q
);
2198 /* find RTP context */
2199 c
->packet_stream_index
= pkt
.stream_index
;
2200 ctx
= c
->rtp_ctx
[c
->packet_stream_index
];
2202 av_free_packet(&pkt
);
2205 codec
= ctx
->streams
[0]->codec
;
2206 /* only one stream per RTP connection */
2207 pkt
.stream_index
= 0;
2211 codec
= ctx
->streams
[pkt
.stream_index
]->codec
;
2214 if (c
->is_packetized
) {
2215 int max_packet_size
;
2216 if (c
->rtp_protocol
== RTSP_LOWER_TRANSPORT_TCP
)
2217 max_packet_size
= RTSP_TCP_MAX_PACKET_SIZE
;
2219 max_packet_size
= url_get_max_packet_size(c
->rtp_handles
[c
->packet_stream_index
]);
2220 ret
= url_open_dyn_packet_buf(&ctx
->pb
, max_packet_size
);
2222 ret
= url_open_dyn_buf(&ctx
->pb
);
2225 /* XXX: potential leak */
2228 ost
= ctx
->streams
[pkt
.stream_index
];
2230 ctx
->pb
->is_streamed
= 1;
2231 if (pkt
.dts
!= AV_NOPTS_VALUE
)
2232 pkt
.dts
= av_rescale_q(pkt
.dts
, ist
->time_base
, ost
->time_base
);
2233 if (pkt
.pts
!= AV_NOPTS_VALUE
)
2234 pkt
.pts
= av_rescale_q(pkt
.pts
, ist
->time_base
, ost
->time_base
);
2235 pkt
.duration
= av_rescale_q(pkt
.duration
, ist
->time_base
, ost
->time_base
);
2236 if (av_write_frame(ctx
, &pkt
) < 0) {
2237 http_log("Error writing frame to output\n");
2238 c
->state
= HTTPSTATE_SEND_DATA_TRAILER
;
2241 len
= url_close_dyn_buf(ctx
->pb
, &c
->pb_buffer
);
2242 c
->cur_frame_bytes
= len
;
2243 c
->buffer_ptr
= c
->pb_buffer
;
2244 c
->buffer_end
= c
->pb_buffer
+ len
;
2246 codec
->frame_number
++;
2248 av_free_packet(&pkt
);
2252 av_free_packet(&pkt
);
2257 case HTTPSTATE_SEND_DATA_TRAILER
:
2258 /* last packet test ? */
2259 if (c
->last_packet_sent
|| c
->is_packetized
)
2262 /* prepare header */
2263 if (url_open_dyn_buf(&ctx
->pb
) < 0) {
2264 /* XXX: potential leak */
2267 c
->fmt_ctx
.pb
->is_streamed
= 1;
2268 av_write_trailer(ctx
);
2269 len
= url_close_dyn_buf(ctx
->pb
, &c
->pb_buffer
);
2270 c
->buffer_ptr
= c
->pb_buffer
;
2271 c
->buffer_end
= c
->pb_buffer
+ len
;
2273 c
->last_packet_sent
= 1;
2279 /* should convert the format at the same time */
2280 /* send data starting at c->buffer_ptr to the output connection
2281 (either UDP or TCP connection) */
2282 static int http_send_data(HTTPContext
*c
)
2287 if (c
->buffer_ptr
>= c
->buffer_end
) {
2288 ret
= http_prepare_data(c
);
2292 /* state change requested */
2295 if (c
->is_packetized
) {
2296 /* RTP data output */
2297 len
= c
->buffer_end
- c
->buffer_ptr
;
2299 /* fail safe - should never happen */
2301 c
->buffer_ptr
= c
->buffer_end
;
2304 len
= (c
->buffer_ptr
[0] << 24) |
2305 (c
->buffer_ptr
[1] << 16) |
2306 (c
->buffer_ptr
[2] << 8) |
2308 if (len
> (c
->buffer_end
- c
->buffer_ptr
))
2310 if ((get_packet_send_clock(c
) - get_server_clock(c
)) > 0) {
2311 /* nothing to send yet: we can wait */
2315 c
->data_count
+= len
;
2316 update_datarate(&c
->datarate
, c
->data_count
);
2318 c
->stream
->bytes_served
+= len
;
2320 if (c
->rtp_protocol
== RTSP_LOWER_TRANSPORT_TCP
) {
2321 /* RTP packets are sent inside the RTSP TCP connection */
2323 int interleaved_index
, size
;
2325 HTTPContext
*rtsp_c
;
2328 /* if no RTSP connection left, error */
2331 /* if already sending something, then wait. */
2332 if (rtsp_c
->state
!= RTSPSTATE_WAIT_REQUEST
)
2334 if (url_open_dyn_buf(&pb
) < 0)
2336 interleaved_index
= c
->packet_stream_index
* 2;
2337 /* RTCP packets are sent at odd indexes */
2338 if (c
->buffer_ptr
[1] == 200)
2339 interleaved_index
++;
2340 /* write RTSP TCP header */
2342 header
[1] = interleaved_index
;
2343 header
[2] = len
>> 8;
2345 put_buffer(pb
, header
, 4);
2346 /* write RTP packet data */
2348 put_buffer(pb
, c
->buffer_ptr
, len
);
2349 size
= url_close_dyn_buf(pb
, &c
->packet_buffer
);
2350 /* prepare asynchronous TCP sending */
2351 rtsp_c
->packet_buffer_ptr
= c
->packet_buffer
;
2352 rtsp_c
->packet_buffer_end
= c
->packet_buffer
+ size
;
2353 c
->buffer_ptr
+= len
;
2355 /* send everything we can NOW */
2356 len
= send(rtsp_c
->fd
, rtsp_c
->packet_buffer_ptr
,
2357 rtsp_c
->packet_buffer_end
- rtsp_c
->packet_buffer_ptr
, 0);
2359 rtsp_c
->packet_buffer_ptr
+= len
;
2360 if (rtsp_c
->packet_buffer_ptr
< rtsp_c
->packet_buffer_end
) {
2361 /* if we could not send all the data, we will
2362 send it later, so a new state is needed to
2363 "lock" the RTSP TCP connection */
2364 rtsp_c
->state
= RTSPSTATE_SEND_PACKET
;
2367 /* all data has been sent */
2368 av_freep(&c
->packet_buffer
);
2370 /* send RTP packet directly in UDP */
2372 url_write(c
->rtp_handles
[c
->packet_stream_index
],
2373 c
->buffer_ptr
, len
);
2374 c
->buffer_ptr
+= len
;
2375 /* here we continue as we can send several packets per 10 ms slot */
2378 /* TCP data output */
2379 len
= send(c
->fd
, c
->buffer_ptr
, c
->buffer_end
- c
->buffer_ptr
, 0);
2381 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
2382 ff_neterrno() != FF_NETERROR(EINTR
))
2383 /* error : close connection */
2388 c
->buffer_ptr
+= len
;
2390 c
->data_count
+= len
;
2391 update_datarate(&c
->datarate
, c
->data_count
);
2393 c
->stream
->bytes_served
+= len
;
2401 static int http_start_receive_data(HTTPContext
*c
)
2405 if (c
->stream
->feed_opened
)
2408 /* Don't permit writing to this one */
2409 if (c
->stream
->readonly
)
2413 fd
= open(c
->stream
->feed_filename
, O_RDWR
);
2415 http_log("Error opening feeder file: %s\n", strerror(errno
));
2420 if (c
->stream
->truncate
) {
2421 /* truncate feed file */
2422 ffm_write_write_index(c
->feed_fd
, FFM_PACKET_SIZE
);
2423 ftruncate(c
->feed_fd
, FFM_PACKET_SIZE
);
2424 http_log("Truncating feed file '%s'\n", c
->stream
->feed_filename
);
2426 if ((c
->stream
->feed_write_index
= ffm_read_write_index(fd
)) < 0) {
2427 http_log("Error reading write index from feed file: %s\n", strerror(errno
));
2432 c
->stream
->feed_write_index
= FFMAX(ffm_read_write_index(fd
), FFM_PACKET_SIZE
);
2433 c
->stream
->feed_size
= lseek(fd
, 0, SEEK_END
);
2434 lseek(fd
, 0, SEEK_SET
);
2436 /* init buffer input */
2437 c
->buffer_ptr
= c
->buffer
;
2438 c
->buffer_end
= c
->buffer
+ FFM_PACKET_SIZE
;
2439 c
->stream
->feed_opened
= 1;
2440 c
->chunked_encoding
= !!av_stristr(c
->buffer
, "Transfer-Encoding: chunked");
2444 static int http_receive_data(HTTPContext
*c
)
2447 int len
, loop_run
= 0;
2449 while (c
->chunked_encoding
&& !c
->chunk_size
&&
2450 c
->buffer_end
> c
->buffer_ptr
) {
2451 /* read chunk header, if present */
2452 len
= recv(c
->fd
, c
->buffer_ptr
, 1, 0);
2455 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
2456 ff_neterrno() != FF_NETERROR(EINTR
))
2457 /* error : close connection */
2459 } else if (len
== 0) {
2460 /* end of connection : close it */
2462 } else if (c
->buffer_ptr
- c
->buffer
>= 2 &&
2463 !memcmp(c
->buffer_ptr
- 1, "\r\n", 2)) {
2464 c
->chunk_size
= strtol(c
->buffer
, 0, 16);
2465 if (c
->chunk_size
== 0) // end of stream
2467 c
->buffer_ptr
= c
->buffer
;
2469 } else if (++loop_run
> 10) {
2470 /* no chunk header, abort */
2477 if (c
->buffer_end
> c
->buffer_ptr
) {
2478 len
= recv(c
->fd
, c
->buffer_ptr
,
2479 FFMIN(c
->chunk_size
, c
->buffer_end
- c
->buffer_ptr
), 0);
2481 if (ff_neterrno() != FF_NETERROR(EAGAIN
) &&
2482 ff_neterrno() != FF_NETERROR(EINTR
))
2483 /* error : close connection */
2485 } else if (len
== 0)
2486 /* end of connection : close it */
2489 c
->chunk_size
-= len
;
2490 c
->buffer_ptr
+= len
;
2491 c
->data_count
+= len
;
2492 update_datarate(&c
->datarate
, c
->data_count
);
2496 if (c
->buffer_ptr
- c
->buffer
>= 2 && c
->data_count
> FFM_PACKET_SIZE
) {
2497 if (c
->buffer
[0] != 'f' ||
2498 c
->buffer
[1] != 'm') {
2499 http_log("Feed stream has become desynchronized -- disconnecting\n");
2504 if (c
->buffer_ptr
>= c
->buffer_end
) {
2505 FFStream
*feed
= c
->stream
;
2506 /* a packet has been received : write it in the store, except
2508 if (c
->data_count
> FFM_PACKET_SIZE
) {
2510 // printf("writing pos=0x%"PRIx64" size=0x%"PRIx64"\n", feed->feed_write_index, feed->feed_size);
2511 /* XXX: use llseek or url_seek */
2512 lseek(c
->feed_fd
, feed
->feed_write_index
, SEEK_SET
);
2513 if (write(c
->feed_fd
, c
->buffer
, FFM_PACKET_SIZE
) < 0) {
2514 http_log("Error writing to feed file: %s\n", strerror(errno
));
2518 feed
->feed_write_index
+= FFM_PACKET_SIZE
;
2519 /* update file size */
2520 if (feed
->feed_write_index
> c
->stream
->feed_size
)
2521 feed
->feed_size
= feed
->feed_write_index
;
2523 /* handle wrap around if max file size reached */
2524 if (c
->stream
->feed_max_size
&& feed
->feed_write_index
>= c
->stream
->feed_max_size
)
2525 feed
->feed_write_index
= FFM_PACKET_SIZE
;
2528 if (ffm_write_write_index(c
->feed_fd
, feed
->feed_write_index
) < 0) {
2529 http_log("Error writing index to feed file: %s\n", strerror(errno
));
2533 /* wake up any waiting connections */
2534 for(c1
= first_http_ctx
; c1
!= NULL
; c1
= c1
->next
) {
2535 if (c1
->state
== HTTPSTATE_WAIT_FEED
&&
2536 c1
->stream
->feed
== c
->stream
->feed
)
2537 c1
->state
= HTTPSTATE_SEND_DATA
;
2540 /* We have a header in our hands that contains useful data */
2541 AVFormatContext
*s
= NULL
;
2543 AVInputFormat
*fmt_in
;
2546 /* use feed output format name to find corresponding input format */
2547 fmt_in
= av_find_input_format(feed
->fmt
->name
);
2551 url_open_buf(&pb
, c
->buffer
, c
->buffer_end
- c
->buffer
, URL_RDONLY
);
2552 pb
->is_streamed
= 1;
2554 if (av_open_input_stream(&s
, pb
, c
->stream
->feed_filename
, fmt_in
, NULL
) < 0) {
2559 /* Now we have the actual streams */
2560 if (s
->nb_streams
!= feed
->nb_streams
) {
2561 av_close_input_stream(s
);
2563 http_log("Feed '%s' stream number does not match registered feed\n",
2564 c
->stream
->feed_filename
);
2568 for (i
= 0; i
< s
->nb_streams
; i
++) {
2569 AVStream
*fst
= feed
->streams
[i
];
2570 AVStream
*st
= s
->streams
[i
];
2571 memcpy(fst
->codec
, st
->codec
, sizeof(AVCodecContext
));
2572 if (fst
->codec
->extradata_size
) {
2573 fst
->codec
->extradata
= av_malloc(fst
->codec
->extradata_size
);
2574 if (!fst
->codec
->extradata
)
2576 memcpy(fst
->codec
->extradata
, st
->codec
->extradata
,
2577 fst
->codec
->extradata_size
);
2581 av_close_input_stream(s
);
2584 c
->buffer_ptr
= c
->buffer
;
2589 c
->stream
->feed_opened
= 0;
2591 /* wake up any waiting connections to stop waiting for feed */
2592 for(c1
= first_http_ctx
; c1
!= NULL
; c1
= c1
->next
) {
2593 if (c1
->state
== HTTPSTATE_WAIT_FEED
&&
2594 c1
->stream
->feed
== c
->stream
->feed
)
2595 c1
->state
= HTTPSTATE_SEND_DATA_TRAILER
;
2600 /********************************************************************/
2603 static void rtsp_reply_header(HTTPContext
*c
, enum RTSPStatusCode error_number
)
2610 switch(error_number
) {
2611 case RTSP_STATUS_OK
:
2614 case RTSP_STATUS_METHOD
:
2615 str
= "Method Not Allowed";
2617 case RTSP_STATUS_BANDWIDTH
:
2618 str
= "Not Enough Bandwidth";
2620 case RTSP_STATUS_SESSION
:
2621 str
= "Session Not Found";
2623 case RTSP_STATUS_STATE
:
2624 str
= "Method Not Valid in This State";
2626 case RTSP_STATUS_AGGREGATE
:
2627 str
= "Aggregate operation not allowed";
2629 case RTSP_STATUS_ONLY_AGGREGATE
:
2630 str
= "Only aggregate operation allowed";
2632 case RTSP_STATUS_TRANSPORT
:
2633 str
= "Unsupported transport";
2635 case RTSP_STATUS_INTERNAL
:
2636 str
= "Internal Server Error";
2638 case RTSP_STATUS_SERVICE
:
2639 str
= "Service Unavailable";
2641 case RTSP_STATUS_VERSION
:
2642 str
= "RTSP Version not supported";
2645 str
= "Unknown Error";
2649 url_fprintf(c
->pb
, "RTSP/1.0 %d %s\r\n", error_number
, str
);
2650 url_fprintf(c
->pb
, "CSeq: %d\r\n", c
->seq
);
2652 /* output GMT time */
2656 p
= buf2
+ strlen(p
) - 1;
2659 url_fprintf(c
->pb
, "Date: %s GMT\r\n", buf2
);
2662 static void rtsp_reply_error(HTTPContext
*c
, enum RTSPStatusCode error_number
)
2664 rtsp_reply_header(c
, error_number
);
2665 url_fprintf(c
->pb
, "\r\n");
2668 static int rtsp_parse_request(HTTPContext
*c
)
2670 const char *p
, *p1
, *p2
;
2676 RTSPMessageHeader header1
, *header
= &header1
;
2678 c
->buffer_ptr
[0] = '\0';
2681 get_word(cmd
, sizeof(cmd
), &p
);
2682 get_word(url
, sizeof(url
), &p
);
2683 get_word(protocol
, sizeof(protocol
), &p
);
2685 av_strlcpy(c
->method
, cmd
, sizeof(c
->method
));
2686 av_strlcpy(c
->url
, url
, sizeof(c
->url
));
2687 av_strlcpy(c
->protocol
, protocol
, sizeof(c
->protocol
));
2689 if (url_open_dyn_buf(&c
->pb
) < 0) {
2690 /* XXX: cannot do more */
2691 c
->pb
= NULL
; /* safety */
2695 /* check version name */
2696 if (strcmp(protocol
, "RTSP/1.0") != 0) {
2697 rtsp_reply_error(c
, RTSP_STATUS_VERSION
);
2701 /* parse each header line */
2702 memset(header
, 0, sizeof(*header
));
2703 /* skip to next line */
2704 while (*p
!= '\n' && *p
!= '\0')
2708 while (*p
!= '\0') {
2709 p1
= strchr(p
, '\n');
2713 if (p2
> p
&& p2
[-1] == '\r')
2715 /* skip empty line */
2719 if (len
> sizeof(line
) - 1)
2720 len
= sizeof(line
) - 1;
2721 memcpy(line
, p
, len
);
2723 ff_rtsp_parse_line(header
, line
);
2727 /* handle sequence number */
2728 c
->seq
= header
->seq
;
2730 if (!strcmp(cmd
, "DESCRIBE"))
2731 rtsp_cmd_describe(c
, url
);
2732 else if (!strcmp(cmd
, "OPTIONS"))
2733 rtsp_cmd_options(c
, url
);
2734 else if (!strcmp(cmd
, "SETUP"))
2735 rtsp_cmd_setup(c
, url
, header
);
2736 else if (!strcmp(cmd
, "PLAY"))
2737 rtsp_cmd_play(c
, url
, header
);
2738 else if (!strcmp(cmd
, "PAUSE"))
2739 rtsp_cmd_pause(c
, url
, header
);
2740 else if (!strcmp(cmd
, "TEARDOWN"))
2741 rtsp_cmd_teardown(c
, url
, header
);
2743 rtsp_reply_error(c
, RTSP_STATUS_METHOD
);
2746 len
= url_close_dyn_buf(c
->pb
, &c
->pb_buffer
);
2747 c
->pb
= NULL
; /* safety */
2749 /* XXX: cannot do more */
2752 c
->buffer_ptr
= c
->pb_buffer
;
2753 c
->buffer_end
= c
->pb_buffer
+ len
;
2754 c
->state
= RTSPSTATE_SEND_REPLY
;
2758 static int prepare_sdp_description(FFStream
*stream
, uint8_t **pbuffer
,
2759 struct in_addr my_ip
)
2761 AVFormatContext
*avc
;
2762 AVStream avs
[MAX_STREAMS
];
2765 avc
= avformat_alloc_context();
2769 av_metadata_set(&avc
->metadata
, "title",
2770 stream
->title
[0] ? stream
->title
: "No Title");
2771 avc
->nb_streams
= stream
->nb_streams
;
2772 if (stream
->is_multicast
) {
2773 snprintf(avc
->filename
, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
2774 inet_ntoa(stream
->multicast_ip
),
2775 stream
->multicast_port
, stream
->multicast_ttl
);
2778 for(i
= 0; i
< stream
->nb_streams
; i
++) {
2779 avc
->streams
[i
] = &avs
[i
];
2780 avc
->streams
[i
]->codec
= stream
->streams
[i
]->codec
;
2782 *pbuffer
= av_mallocz(2048);
2783 avf_sdp_create(&avc
, 1, *pbuffer
, 2048);
2786 return strlen(*pbuffer
);
2789 static void rtsp_cmd_options(HTTPContext
*c
, const char *url
)
2791 // rtsp_reply_header(c, RTSP_STATUS_OK);
2792 url_fprintf(c
->pb
, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK
, "OK");
2793 url_fprintf(c
->pb
, "CSeq: %d\r\n", c
->seq
);
2794 url_fprintf(c
->pb
, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
2795 url_fprintf(c
->pb
, "\r\n");
2798 static void rtsp_cmd_describe(HTTPContext
*c
, const char *url
)
2804 int content_length
, len
;
2805 struct sockaddr_in my_addr
;
2807 /* find which url is asked */
2808 url_split(NULL
, 0, NULL
, 0, NULL
, 0, NULL
, path1
, sizeof(path1
), url
);
2813 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
2814 if (!stream
->is_feed
&&
2815 stream
->fmt
&& !strcmp(stream
->fmt
->name
, "rtp") &&
2816 !strcmp(path
, stream
->filename
)) {
2820 /* no stream found */
2821 rtsp_reply_error(c
, RTSP_STATUS_SERVICE
); /* XXX: right error ? */
2825 /* prepare the media description in sdp format */
2827 /* get the host IP */
2828 len
= sizeof(my_addr
);
2829 getsockname(c
->fd
, (struct sockaddr
*)&my_addr
, &len
);
2830 content_length
= prepare_sdp_description(stream
, &content
, my_addr
.sin_addr
);
2831 if (content_length
< 0) {
2832 rtsp_reply_error(c
, RTSP_STATUS_INTERNAL
);
2835 rtsp_reply_header(c
, RTSP_STATUS_OK
);
2836 url_fprintf(c
->pb
, "Content-Type: application/sdp\r\n");
2837 url_fprintf(c
->pb
, "Content-Length: %d\r\n", content_length
);
2838 url_fprintf(c
->pb
, "\r\n");
2839 put_buffer(c
->pb
, content
, content_length
);
2842 static HTTPContext
*find_rtp_session(const char *session_id
)
2846 if (session_id
[0] == '\0')
2849 for(c
= first_http_ctx
; c
!= NULL
; c
= c
->next
) {
2850 if (!strcmp(c
->session_id
, session_id
))
2856 static RTSPTransportField
*find_transport(RTSPMessageHeader
*h
, enum RTSPLowerTransport lower_transport
)
2858 RTSPTransportField
*th
;
2861 for(i
=0;i
<h
->nb_transports
;i
++) {
2862 th
= &h
->transports
[i
];
2863 if (th
->lower_transport
== lower_transport
)
2869 static void rtsp_cmd_setup(HTTPContext
*c
, const char *url
,
2870 RTSPMessageHeader
*h
)
2873 int stream_index
, port
;
2878 RTSPTransportField
*th
;
2879 struct sockaddr_in dest_addr
;
2880 RTSPActionServerSetup setup
;
2882 /* find which url is asked */
2883 url_split(NULL
, 0, NULL
, 0, NULL
, 0, NULL
, path1
, sizeof(path1
), url
);
2888 /* now check each stream */
2889 for(stream
= first_stream
; stream
!= NULL
; stream
= stream
->next
) {
2890 if (!stream
->is_feed
&&
2891 stream
->fmt
&& !strcmp(stream
->fmt
->name
, "rtp")) {
2892 /* accept aggregate filenames only if single stream */
2893 if (!strcmp(path
, stream
->filename
)) {
2894 if (stream
->nb_streams
!= 1) {
2895 rtsp_reply_error(c
, RTSP_STATUS_AGGREGATE
);
2902 for(stream_index
= 0; stream_index
< stream
->nb_streams
;
2904 snprintf(buf
, sizeof(buf
), "%s/streamid=%d",
2905 stream
->filename
, stream_index
);
2906 if (!strcmp(path
, buf
))
2911 /* no stream found */
2912 rtsp_reply_error(c
, RTSP_STATUS_SERVICE
); /* XXX: right error ? */
2916 /* generate session id if needed */
2917 if (h
->session_id
[0] == '\0')
2918 snprintf(h
->session_id
, sizeof(h
->session_id
), "%08x%08x",
2919 av_lfg_get(&random_state
), av_lfg_get(&random_state
));
2921 /* find rtp session, and create it if none found */
2922 rtp_c
= find_rtp_session(h
->session_id
);
2924 /* always prefer UDP */
2925 th
= find_transport(h
, RTSP_LOWER_TRANSPORT_UDP
);
2927 th
= find_transport(h
, RTSP_LOWER_TRANSPORT_TCP
);
2929 rtsp_reply_error(c
, RTSP_STATUS_TRANSPORT
);
2934 rtp_c
= rtp_new_connection(&c
->from_addr
, stream
, h
->session_id
,
2935 th
->lower_transport
);
2937 rtsp_reply_error(c
, RTSP_STATUS_BANDWIDTH
);
2941 /* open input stream */
2942 if (open_input_stream(rtp_c
, "") < 0) {
2943 rtsp_reply_error(c
, RTSP_STATUS_INTERNAL
);
2948 /* test if stream is OK (test needed because several SETUP needs
2949 to be done for a given file) */
2950 if (rtp_c
->stream
!= stream
) {
2951 rtsp_reply_error(c
, RTSP_STATUS_SERVICE
);
2955 /* test if stream is already set up */
2956 if (rtp_c
->rtp_ctx
[stream_index
]) {
2957 rtsp_reply_error(c
, RTSP_STATUS_STATE
);
2961 /* check transport */
2962 th
= find_transport(h
, rtp_c
->rtp_protocol
);
2963 if (!th
|| (th
->lower_transport
== RTSP_LOWER_TRANSPORT_UDP
&&
2964 th
->client_port_min
<= 0)) {
2965 rtsp_reply_error(c
, RTSP_STATUS_TRANSPORT
);
2969 /* setup default options */
2970 setup
.transport_option
[0] = '\0';
2971 dest_addr
= rtp_c
->from_addr
;
2972 dest_addr
.sin_port
= htons(th
->client_port_min
);
2975 if (rtp_new_av_stream(rtp_c
, stream_index
, &dest_addr
, c
) < 0) {
2976 rtsp_reply_error(c
, RTSP_STATUS_TRANSPORT
);
2980 /* now everything is OK, so we can send the connection parameters */
2981 rtsp_reply_header(c
, RTSP_STATUS_OK
);
2983 url_fprintf(c
->pb
, "Session: %s\r\n", rtp_c
->session_id
);
2985 switch(rtp_c
->rtp_protocol
) {
2986 case RTSP_LOWER_TRANSPORT_UDP
:
2987 port
= rtp_get_local_port(rtp_c
->rtp_handles
[stream_index
]);
2988 url_fprintf(c
->pb
, "Transport: RTP/AVP/UDP;unicast;"
2989 "client_port=%d-%d;server_port=%d-%d",
2990 th
->client_port_min
, th
->client_port_min
+ 1,
2993 case RTSP_LOWER_TRANSPORT_TCP
:
2994 url_fprintf(c
->pb
, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
2995 stream_index
* 2, stream_index
* 2 + 1);
3000 if (setup
.transport_option
[0] != '\0')
3001 url_fprintf(c
->pb
, ";%s", setup
.transport_option
);
3002 url_fprintf(c
->pb
, "\r\n");
3005 url_fprintf(c
->pb
, "\r\n");
3009 /* find an rtp connection by using the session ID. Check consistency
3011 static HTTPContext
*find_rtp_session_with_url(const char *url
,
3012 const char *session_id
)
3020 rtp_c
= find_rtp_session(session_id
);
3024 /* find which url is asked */
3025 url_split(NULL
, 0, NULL
, 0, NULL
, 0, NULL
, path1
, sizeof(path1
), url
);
3029 if(!strcmp(path
, rtp_c
->stream
->filename
)) return rtp_c
;
3030 for(s
=0; s
<rtp_c
->stream
->nb_streams
; ++s
) {
3031 snprintf(buf
, sizeof(buf
), "%s/streamid=%d",
3032 rtp_c
->stream
->filename
, s
);
3033 if(!strncmp(path
, buf
, sizeof(buf
))) {
3034 // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1?
3041 static void rtsp_cmd_play(HTTPContext
*c
, const char *url
, RTSPMessageHeader
*h
)
3045 rtp_c
= find_rtp_session_with_url(url
, h
->session_id
);
3047 rtsp_reply_error(c
, RTSP_STATUS_SESSION
);
3051 if (rtp_c
->state
!= HTTPSTATE_SEND_DATA
&&
3052 rtp_c
->state
!= HTTPSTATE_WAIT_FEED
&&
3053 rtp_c
->state
!= HTTPSTATE_READY
) {
3054 rtsp_reply_error(c
, RTSP_STATUS_STATE
);
3058 rtp_c
->state
= HTTPSTATE_SEND_DATA
;
3060 /* now everything is OK, so we can send the connection parameters */
3061 rtsp_reply_header(c
, RTSP_STATUS_OK
);
3063 url_fprintf(c
->pb
, "Session: %s\r\n", rtp_c
->session_id
);
3064 url_fprintf(c
->pb
, "\r\n");
3067 static void rtsp_cmd_pause(HTTPContext
*c
, const char *url
, RTSPMessageHeader
*h
)
3071 rtp_c
= find_rtp_session_with_url(url
, h
->session_id
);
3073 rtsp_reply_error(c
, RTSP_STATUS_SESSION
);
3077 if (rtp_c
->state
!= HTTPSTATE_SEND_DATA
&&
3078 rtp_c
->state
!= HTTPSTATE_WAIT_FEED
) {
3079 rtsp_reply_error(c
, RTSP_STATUS_STATE
);
3083 rtp_c
->state
= HTTPSTATE_READY
;
3084 rtp_c
->first_pts
= AV_NOPTS_VALUE
;
3085 /* now everything is OK, so we can send the connection parameters */
3086 rtsp_reply_header(c
, RTSP_STATUS_OK
);
3088 url_fprintf(c
->pb
, "Session: %s\r\n", rtp_c
->session_id
);
3089 url_fprintf(c
->pb
, "\r\n");
3092 static void rtsp_cmd_teardown(HTTPContext
*c
, const char *url
, RTSPMessageHeader
*h
)
3095 char session_id
[32];
3097 rtp_c
= find_rtp_session_with_url(url
, h
->session_id
);
3099 rtsp_reply_error(c
, RTSP_STATUS_SESSION
);
3103 av_strlcpy(session_id
, rtp_c
->session_id
, sizeof(session_id
));
3105 /* abort the session */
3106 close_connection(rtp_c
);
3108 /* now everything is OK, so we can send the connection parameters */
3109 rtsp_reply_header(c
, RTSP_STATUS_OK
);
3111 url_fprintf(c
->pb
, "Session: %s\r\n", session_id
);
3112 url_fprintf(c
->pb
, "\r\n");
3116 /********************************************************************/
3119 static HTTPContext
*rtp_new_connection(struct sockaddr_in
*from_addr
,
3120 FFStream
*stream
, const char *session_id
,
3121 enum RTSPLowerTransport rtp_protocol
)
3123 HTTPContext
*c
= NULL
;
3124 const char *proto_str
;
3126 /* XXX: should output a warning page when coming
3127 close to the connection limit */
3128 if (nb_connections
>= nb_max_connections
)
3131 /* add a new connection */
3132 c
= av_mallocz(sizeof(HTTPContext
));
3137 c
->poll_entry
= NULL
;
3138 c
->from_addr
= *from_addr
;
3139 c
->buffer_size
= IOBUFFER_INIT_SIZE
;
3140 c
->buffer
= av_malloc(c
->buffer_size
);
3145 av_strlcpy(c
->session_id
, session_id
, sizeof(c
->session_id
));
3146 c
->state
= HTTPSTATE_READY
;
3147 c
->is_packetized
= 1;
3148 c
->rtp_protocol
= rtp_protocol
;
3150 /* protocol is shown in statistics */
3151 switch(c
->rtp_protocol
) {
3152 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST
:
3153 proto_str
= "MCAST";
3155 case RTSP_LOWER_TRANSPORT_UDP
:
3158 case RTSP_LOWER_TRANSPORT_TCP
:
3165 av_strlcpy(c
->protocol
, "RTP/", sizeof(c
->protocol
));
3166 av_strlcat(c
->protocol
, proto_str
, sizeof(c
->protocol
));
3168 current_bandwidth
+= stream
->bandwidth
;
3170 c
->next
= first_http_ctx
;
3182 /* add a new RTP stream in an RTP connection (used in RTSP SETUP
3183 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
3185 static int rtp_new_av_stream(HTTPContext
*c
,
3186 int stream_index
, struct sockaddr_in
*dest_addr
,
3187 HTTPContext
*rtsp_c
)
3189 AVFormatContext
*ctx
;
3192 URLContext
*h
= NULL
;
3194 int max_packet_size
;
3196 /* now we can open the relevant output stream */
3197 ctx
= avformat_alloc_context();
3200 ctx
->oformat
= av_guess_format("rtp", NULL
, NULL
);
3202 st
= av_mallocz(sizeof(AVStream
));
3205 st
->codec
= avcodec_alloc_context();
3206 ctx
->nb_streams
= 1;
3207 ctx
->streams
[0] = st
;
3209 if (!c
->stream
->feed
||
3210 c
->stream
->feed
== c
->stream
)
3211 memcpy(st
, c
->stream
->streams
[stream_index
], sizeof(AVStream
));
3214 c
->stream
->feed
->streams
[c
->stream
->feed_streams
[stream_index
]],
3216 st
->priv_data
= NULL
;
3218 /* build destination RTP address */
3219 ipaddr
= inet_ntoa(dest_addr
->sin_addr
);
3221 switch(c
->rtp_protocol
) {
3222 case RTSP_LOWER_TRANSPORT_UDP
:
3223 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST
:
3226 /* XXX: also pass as parameter to function ? */
3227 if (c
->stream
->is_multicast
) {
3229 ttl
= c
->stream
->multicast_ttl
;
3232 snprintf(ctx
->filename
, sizeof(ctx
->filename
),
3233 "rtp://%s:%d?multicast=1&ttl=%d",
3234 ipaddr
, ntohs(dest_addr
->sin_port
), ttl
);
3236 snprintf(ctx
->filename
, sizeof(ctx
->filename
),
3237 "rtp://%s:%d", ipaddr
, ntohs(dest_addr
->sin_port
));
3240 if (url_open(&h
, ctx
->filename
, URL_WRONLY
) < 0)
3242 c
->rtp_handles
[stream_index
] = h
;
3243 max_packet_size
= url_get_max_packet_size(h
);
3245 case RTSP_LOWER_TRANSPORT_TCP
: