Add missing stdlib.h #include, fixes the warnings:
[libav.git] / ffserver.c
CommitLineData
85f07f22
FB
1/*
2 * Multiple format streaming server
773a21b8 3 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
85f07f22 4 *
b78e7197
DB
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
773a21b8
FB
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
b78e7197 10 * version 2.1 of the License, or (at your option) any later version.
85f07f22 11 *
b78e7197 12 * FFmpeg is distributed in the hope that it will be useful,
85f07f22 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
773a21b8
FB
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
85f07f22 16 *
773a21b8 17 * You should have received a copy of the GNU Lesser General Public
b78e7197 18 * License along with FFmpeg; if not, write to the Free Software
5509bffa 19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
85f07f22 20 */
364a9607 21
29d3ed3b
AJ
22#define _XOPEN_SOURCE 600
23
0f4e8165 24#include "config.h"
b250f9c6 25#if !HAVE_CLOSESOCKET
0f4e8165
RB
26#define closesocket close
27#endif
28#include <string.h>
ea452b54 29#include <strings.h>
0f4e8165 30#include <stdlib.h>
245976da
DB
31#include "libavformat/avformat.h"
32#include "libavformat/network.h"
33#include "libavformat/os_support.h"
302879cb 34#include "libavformat/rtpdec.h"
245976da 35#include "libavformat/rtsp.h"
959da985 36#include "libavutil/avstring.h"
042819c5
BC
37#include "libavutil/lfg.h"
38#include "libavutil/random_seed.h"
7ab08864 39#include "libavcodec/opt.h"
85f07f22 40#include <stdarg.h>
85f07f22
FB
41#include <unistd.h>
42#include <fcntl.h>
43#include <sys/ioctl.h>
b250f9c6 44#if HAVE_POLL_H
f8cda19e 45#include <poll.h>
b0c858d8 46#endif
85f07f22
FB
47#include <errno.h>
48#include <sys/time.h>
49#include <time.h>
5eb765ef 50#include <sys/wait.h>
85f07f22 51#include <signal.h>
b250f9c6 52#if HAVE_DLFCN_H
2effd274 53#include <dlfcn.h>
6638d424 54#endif
2effd274 55
4ce5df08 56#include "cmdutils.h"
85f07f22 57
64555bd9 58const char program_name[] = "FFserver";
ea9c581f 59const int program_birth_year = 2000;
86074ed1 60
5a635bc7
SS
61static const OptionDef options[];
62
85f07f22
FB
63enum HTTPState {
64 HTTPSTATE_WAIT_REQUEST,
65 HTTPSTATE_SEND_HEADER,
66 HTTPSTATE_SEND_DATA_HEADER,
2effd274 67 HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
85f07f22 68 HTTPSTATE_SEND_DATA_TRAILER,
115329f1 69 HTTPSTATE_RECEIVE_DATA,
2effd274 70 HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
2effd274
FB
71 HTTPSTATE_READY,
72
73 RTSPSTATE_WAIT_REQUEST,
74 RTSPSTATE_SEND_REPLY,
bc351386 75 RTSPSTATE_SEND_PACKET,
85f07f22
FB
76};
77
9507a12e 78static const char *http_state[] = {
2effd274
FB
79 "HTTP_WAIT_REQUEST",
80 "HTTP_SEND_HEADER",
81
85f07f22
FB
82 "SEND_DATA_HEADER",
83 "SEND_DATA",
84 "SEND_DATA_TRAILER",
85 "RECEIVE_DATA",
86 "WAIT_FEED",
2effd274
FB
87 "READY",
88
89 "RTSP_WAIT_REQUEST",
90 "RTSP_SEND_REPLY",
bc351386 91 "RTSP_SEND_PACKET",
85f07f22
FB
92};
93
cde25790 94#define IOBUFFER_INIT_SIZE 8192
85f07f22 95
85f07f22 96/* timeouts are in ms */
2effd274
FB
97#define HTTP_REQUEST_TIMEOUT (15 * 1000)
98#define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
99
85f07f22
FB
100#define SYNC_TIMEOUT (10 * 1000)
101
b516ecdd
RB
102typedef struct RTSPActionServerSetup {
103 uint32_t ipaddr;
104 char transport_option[512];
105} RTSPActionServerSetup;
106
5eb765ef 107typedef struct {
0c1a9eda 108 int64_t count1, count2;
c3f58185 109 int64_t time1, time2;
5eb765ef
PG
110} DataRateData;
111
85f07f22
FB
112/* context associated with one connection */
113typedef 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 */
c3f58185 118 int64_t timeout;
0c1a9eda 119 uint8_t *buffer_ptr, *buffer_end;
85f07f22 120 int http_error;
edfdd798 121 int post;
19c8c4ec
RB
122 int chunked_encoding;
123 int chunk_size; /* 0 if it needs to be read */
85f07f22 124 struct HTTPContext *next;
42a63c6a 125 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
0c1a9eda 126 int64_t data_count;
85f07f22
FB
127 /* feed input */
128 int feed_fd;
129 /* input format handling */
130 AVFormatContext *fmt_in;
c3f58185 131 int64_t start_time; /* In milliseconds - this wraps fairly often */
0c1a9eda 132 int64_t first_pts; /* initial pts value */
e240a0bb
FB
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
137 packet */
138 int pts_stream_index; /* stream we choose as clock reference */
139 int64_t cur_clock; /* current clock reference value in us */
85f07f22
FB
140 /* output format handling */
141 struct FFStream *stream;
cde25790
PG
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 */
145 int switch_pending;
2effd274 146 AVFormatContext fmt_ctx; /* instance of FFStream for one user */
85f07f22 147 int last_packet_sent; /* true if last data packet was sent */
7434ba6d 148 int suppress_log;
5eb765ef 149 DataRateData datarate;
3120d2a2 150 int wmp_client_id;
7434ba6d
PG
151 char protocol[16];
152 char method[16];
153 char url[128];
cde25790 154 int buffer_size;
0c1a9eda 155 uint8_t *buffer;
2effd274
FB
156 int is_packetized; /* if true, the stream is packetized */
157 int packet_stream_index; /* current stream for output in state machine */
115329f1 158
2effd274 159 /* RTSP state specific */
0c1a9eda 160 uint8_t *pb_buffer; /* XXX: use that in all the code */
2effd274
FB
161 ByteIOContext *pb;
162 int seq; /* RTSP sequence number */
115329f1 163
2effd274 164 /* RTP state specific */
90abbdba 165 enum RTSPLowerTransport rtp_protocol;
2effd274
FB
166 char session_id[32]; /* session id */
167 AVFormatContext *rtp_ctx[MAX_STREAMS];
e240a0bb 168
bc351386
FB
169 /* RTP/UDP specific */
170 URLContext *rtp_handles[MAX_STREAMS];
171
172 /* RTP/TCP specific */
173 struct HTTPContext *rtsp_c;
174 uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
85f07f22
FB
175} HTTPContext;
176
177/* each generated stream is described here */
178enum StreamType {
179 STREAM_TYPE_LIVE,
180 STREAM_TYPE_STATUS,
cde25790 181 STREAM_TYPE_REDIRECT,
85f07f22
FB
182};
183
8256c0a3
PG
184enum IPAddressAction {
185 IP_ALLOW = 1,
186 IP_DENY,
187};
188
189typedef struct IPAddressACL {
190 struct IPAddressACL *next;
191 enum IPAddressAction action;
efa04ce2 192 /* These are in host order */
8256c0a3
PG
193 struct in_addr first;
194 struct in_addr last;
195} IPAddressACL;
196
85f07f22
FB
197/* description of each stream of the ffserver.conf file */
198typedef struct FFStream {
199 enum StreamType stream_type;
200 char filename[1024]; /* stream filename */
2effd274
FB
201 struct FFStream *feed; /* feed we are using (can be null if
202 coming from file) */
e240a0bb
FB
203 AVFormatParameters *ap_in; /* input parameters */
204 AVInputFormat *ifmt; /* if non NULL, force input format */
bd7cf6ad 205 AVOutputFormat *fmt;
8256c0a3 206 IPAddressACL *acl;
85f07f22 207 int nb_streams;
42a63c6a 208 int prebuffer; /* Number of millseconds early to start */
c3f58185 209 int64_t max_time; /* Number of milliseconds to run */
79c4ea3c 210 int send_on_key;
85f07f22
FB
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 */
2ac887ba
PG
215 char author[512];
216 char title[512];
217 char copyright[512];
218 char comment[512];
cde25790 219 pid_t pid; /* Of ffmpeg process */
5eb765ef 220 time_t pid_start; /* Of ffmpeg process */
cde25790 221 char **child_argv;
85f07f22 222 struct FFStream *next;
177d2564 223 unsigned bandwidth; /* bandwidth, in kbits/s */
2effd274
FB
224 /* RTSP options */
225 char *rtsp_option;
829ac53d
FB
226 /* multicast specific */
227 int is_multicast;
228 struct in_addr multicast_ip;
229 int multicast_port; /* first port used for multicast */
6edd6884
FB
230 int multicast_ttl;
231 int loop; /* if true, send the stream in loops (only meaningful if file) */
829ac53d 232
85f07f22 233 /* feed specific */
2effd274 234 int feed_opened; /* true if someone is writing to the feed */
85f07f22 235 int is_feed; /* true if it is a feed */
e322ea48 236 int readonly; /* True if writing is prohibited to the file */
861ec13a 237 int truncate; /* True if feeder connection truncate the feed file */
a6e14edd 238 int conns_served;
0c1a9eda 239 int64_t bytes_served;
6b0bdc75 240 int64_t feed_max_size; /* maximum storage size, zero means unlimited */
8bfb108b 241 int64_t feed_write_index; /* current write position in feed (it wraps around) */
0c1a9eda 242 int64_t feed_size; /* current size of feed */
85f07f22
FB
243 struct FFStream *next_feed;
244} FFStream;
245
246typedef struct FeedData {
247 long long data_count;
8bfb108b 248 float avg_frame_size; /* frame size averaged over last frames with exponential mean */
85f07f22
FB
249} FeedData;
250
18405874
AB
251static struct sockaddr_in my_http_addr;
252static struct sockaddr_in my_rtsp_addr;
2effd274 253
33f5e2ec
AB
254static char logfilename[1024];
255static HTTPContext *first_http_ctx;
256static FFStream *first_feed; /* contains only feeds */
257static FFStream *first_stream; /* contains all streams, including feeds */
85f07f22 258
2effd274
FB
259static void new_connection(int server_fd, int is_rtsp);
260static void close_connection(HTTPContext *c);
261
262/* HTTP handling */
263static int handle_connection(HTTPContext *c);
85f07f22 264static int http_parse_request(HTTPContext *c);
5eb765ef 265static int http_send_data(HTTPContext *c);
dca21085 266static void compute_status(HTTPContext *c);
85f07f22
FB
267static int open_input_stream(HTTPContext *c, const char *info);
268static int http_start_receive_data(HTTPContext *c);
269static int http_receive_data(HTTPContext *c);
2effd274
FB
270
271/* RTSP handling */
272static int rtsp_parse_request(HTTPContext *c);
273static void rtsp_cmd_describe(HTTPContext *c, const char *url);
0df65975 274static void rtsp_cmd_options(HTTPContext *c, const char *url);
a9e534d5
RB
275static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPMessageHeader *h);
276static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h);
277static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h);
278static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h);
2effd274 279
829ac53d 280/* SDP handling */
115329f1 281static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
829ac53d
FB
282 struct in_addr my_ip);
283
2effd274 284/* RTP handling */
115329f1 285static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
bc351386 286 FFStream *stream, const char *session_id,
90abbdba 287 enum RTSPLowerTransport rtp_protocol);
115329f1 288static int rtp_new_av_stream(HTTPContext *c,
bc351386
FB
289 int stream_index, struct sockaddr_in *dest_addr,
290 HTTPContext *rtsp_c);
85f07f22 291
cde25790 292static const char *my_program_name;
d6562d2c 293static const char *my_program_dir;
cde25790 294
5a635bc7 295static const char *config_filename;
2ac887ba 296static int ffserver_debug;
2effd274 297static int ffserver_daemon;
2ac887ba 298static int no_launch;
5eb765ef 299static int need_to_start_children;
2ac887ba 300
1c9ff179
SS
301/* maximum number of simultaneous HTTP connections */
302static unsigned int nb_max_http_connections = 2000;
4af92de6
SS
303static unsigned int nb_max_connections = 5;
304static unsigned int nb_connections;
85f07f22 305
f69bb0cc 306static uint64_t max_bandwidth = 1000;
1ad8289e 307static uint64_t current_bandwidth;
42a63c6a 308
c3f58185 309static int64_t cur_time; // Making this global saves on passing it around everywhere
5eb765ef 310
042819c5 311static AVLFG random_state;
1df93ae9 312
85f07f22
FB
313static FILE *logfile = NULL;
314
9fd3442f
BC
315static char *ctime1(char *buf2)
316{
317 time_t ti;
318 char *p;
319
320 ti = time(NULL);
321 p = ctime(&ti);
322 strcpy(buf2, p);
323 p = buf2 + strlen(p) - 1;
324 if (*p == '\n')
325 *p = '\0';
326 return buf2;
327}
328
bcd3ce59 329static void http_vlog(const char *fmt, va_list vargs)
85f07f22 330{
124ed1c0 331 static int print_prefix = 1;
7434ba6d 332 if (logfile) {
124ed1c0 333 if (print_prefix) {
9fd3442f
BC
334 char buf[32];
335 ctime1(buf);
336 fprintf(logfile, "%s ", buf);
124ed1c0
BC
337 }
338 print_prefix = strstr(fmt, "\n") != NULL;
bcd3ce59 339 vfprintf(logfile, fmt, vargs);
7434ba6d
PG
340 fflush(logfile);
341 }
bcd3ce59
BC
342}
343
7f6a384a 344static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...)
bcd3ce59
BC
345{
346 va_list vargs;
347 va_start(vargs, fmt);
348 http_vlog(fmt, vargs);
349 va_end(vargs);
350}
351
352static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
353{
354 static int print_prefix = 1;
355 AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
49ceb58b 356 if (level > av_log_get_level())
bcd3ce59
BC
357 return;
358 if (print_prefix && avc)
59e7894c 359 http_log("[%s @ %p]", avc->item_name(ptr), ptr);
bcd3ce59
BC
360 print_prefix = strstr(fmt, "\n") != NULL;
361 http_vlog(fmt, vargs);
85f07f22
FB
362}
363
6edd6884
FB
364static void log_connection(HTTPContext *c)
365{
115329f1 366 if (c->suppress_log)
6edd6884
FB
367 return;
368
82e0be62
BC
369 http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
370 inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
6edd6884 371 c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
cde25790
PG
372}
373
0c1a9eda 374static void update_datarate(DataRateData *drd, int64_t count)
5eb765ef
PG
375{
376 if (!drd->time1 && !drd->count1) {
377 drd->time1 = drd->time2 = cur_time;
378 drd->count1 = drd->count2 = count;
eeffbdea 379 } else if (cur_time - drd->time2 > 5000) {
33a4ecbe
AB
380 drd->time1 = drd->time2;
381 drd->count1 = drd->count2;
382 drd->time2 = cur_time;
383 drd->count2 = count;
5eb765ef
PG
384 }
385}
386
387/* In bytes per second */
0c1a9eda 388static int compute_datarate(DataRateData *drd, int64_t count)
5eb765ef
PG
389{
390 if (cur_time == drd->time1)
391 return 0;
115329f1 392
5eb765ef
PG
393 return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
394}
395
a782f209 396
cde25790
PG
397static void start_children(FFStream *feed)
398{
2ac887ba
PG
399 if (no_launch)
400 return;
401
cde25790 402 for (; feed; feed = feed->next) {
5eb765ef
PG
403 if (feed->child_argv && !feed->pid) {
404 feed->pid_start = time(0);
405
cde25790
PG
406 feed->pid = fork();
407
408 if (feed->pid < 0) {
b4befb99 409 http_log("Unable to create children\n");
cde25790
PG
410 exit(1);
411 }
412 if (!feed->pid) {
413 /* In child */
414 char pathname[1024];
415 char *slash;
416 int i;
417
40444a59
SS
418 av_strlcpy(pathname, my_program_name, sizeof(pathname));
419
420 slash = strrchr(pathname, '/');
421 if (!slash)
422 slash = pathname;
423 else
424 slash++;
425 strcpy(slash, "ffmpeg");
426
8bf61f5b
SS
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]);
431 http_log("\n");
40444a59 432
611c5741 433 for (i = 3; i < 256; i++)
5eb765ef 434 close(i);
cde25790 435
5eb765ef 436 if (!ffserver_debug) {
2ac887ba 437 i = open("/dev/null", O_RDWR);
3296409d 438 if (i != -1) {
2ac887ba 439 dup2(i, 0);
3296409d
BC
440 dup2(i, 1);
441 dup2(i, 2);
5eb765ef 442 close(i);
3296409d 443 }
2ac887ba 444 }
cde25790 445
d6562d2c
PG
446 /* This is needed to make relative pathnames work */
447 chdir(my_program_dir);
448
a4d70941
PG
449 signal(SIGPIPE, SIG_DFL);
450
cde25790
PG
451 execvp(pathname, feed->child_argv);
452
453 _exit(1);
454 }
455 }
456 }
7434ba6d
PG
457}
458
2effd274
FB
459/* open a listening socket */
460static int socket_open_listen(struct sockaddr_in *my_addr)
85f07f22 461{
2effd274 462 int server_fd, tmp;
85f07f22
FB
463
464 server_fd = socket(AF_INET,SOCK_STREAM,0);
465 if (server_fd < 0) {
466 perror ("socket");
467 return -1;
468 }
115329f1 469
85f07f22
FB
470 tmp = 1;
471 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
472
2effd274 473 if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
b17d099d
PG
474 char bindmsg[32];
475 snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port));
476 perror (bindmsg);
d96633bb 477 closesocket(server_fd);
85f07f22
FB
478 return -1;
479 }
115329f1 480
85f07f22
FB
481 if (listen (server_fd, 5) < 0) {
482 perror ("listen");
d96633bb 483 closesocket(server_fd);
85f07f22
FB
484 return -1;
485 }
ba472aaf 486 ff_socket_nonblock(server_fd, 1);
2effd274
FB
487
488 return server_fd;
489}
490
6edd6884
FB
491/* start all multicast streams */
492static void start_multicast(void)
493{
494 FFStream *stream;
495 char session_id[32];
496 HTTPContext *rtp_c;
497 struct sockaddr_in dest_addr;
498 int default_port, stream_index;
499
500 default_port = 6000;
501 for(stream = first_stream; stream != NULL; stream = stream->next) {
502 if (stream->is_multicast) {
503 /* open the RTP connection */
1df93ae9 504 snprintf(session_id, sizeof(session_id), "%08x%08x",
042819c5 505 av_lfg_get(&random_state), av_lfg_get(&random_state));
6edd6884
FB
506
507 /* choose a port if none given */
508 if (stream->multicast_port == 0) {
509 stream->multicast_port = default_port;
510 default_port += 100;
511 }
512
513 dest_addr.sin_family = AF_INET;
514 dest_addr.sin_addr = stream->multicast_ip;
515 dest_addr.sin_port = htons(stream->multicast_port);
516
115329f1 517 rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
90abbdba 518 RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
611c5741 519 if (!rtp_c)
6edd6884 520 continue;
611c5741 521
6edd6884 522 if (open_input_stream(rtp_c, "") < 0) {
b4befb99
BC
523 http_log("Could not open input stream for stream '%s'\n",
524 stream->filename);
6edd6884
FB
525 continue;
526 }
527
6edd6884 528 /* open each RTP stream */
115329f1 529 for(stream_index = 0; stream_index < stream->nb_streams;
6edd6884 530 stream_index++) {
115329f1 531 dest_addr.sin_port = htons(stream->multicast_port +
6edd6884 532 2 * stream_index);
bc351386 533 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) {
b4befb99
BC
534 http_log("Could not open output stream '%s/streamid=%d'\n",
535 stream->filename, stream_index);
0fa45e19 536 exit(1);
6edd6884
FB
537 }
538 }
539
540 /* change state to send data */
541 rtp_c->state = HTTPSTATE_SEND_DATA;
542 }
543 }
544}
2effd274
FB
545
546/* main loop of the http server */
547static int http_server(void)
548{
d2a1ea1d
BC
549 int server_fd = 0, rtsp_server_fd = 0;
550 int ret, delay, delay1;
1c9ff179 551 struct pollfd *poll_table, *poll_entry;
2effd274
FB
552 HTTPContext *c, *c_next;
553
a7f361eb 554 if(!(poll_table = av_mallocz((nb_max_http_connections + 2)*sizeof(*poll_table)))) {
1c9ff179
SS
555 http_log("Impossible to allocate a poll table handling %d connections.\n", nb_max_http_connections);
556 return -1;
557 }
558
d2a1ea1d 559 if (my_http_addr.sin_port) {
2b9cd1e7
BC
560 server_fd = socket_open_listen(&my_http_addr);
561 if (server_fd < 0)
562 return -1;
d2a1ea1d 563 }
85f07f22 564
d2a1ea1d 565 if (my_rtsp_addr.sin_port) {
2b9cd1e7
BC
566 rtsp_server_fd = socket_open_listen(&my_rtsp_addr);
567 if (rtsp_server_fd < 0)
568 return -1;
d2a1ea1d
BC
569 }
570
571 if (!rtsp_server_fd && !server_fd) {
572 http_log("HTTP and RTSP disabled.\n");
573 return -1;
574 }
115329f1 575
a3341b9d 576 http_log("FFserver started.\n");
85f07f22 577
cde25790
PG
578 start_children(first_feed);
579
6edd6884
FB
580 start_multicast();
581
85f07f22
FB
582 for(;;) {
583 poll_entry = poll_table;
d2a1ea1d 584 if (server_fd) {
2b9cd1e7
BC
585 poll_entry->fd = server_fd;
586 poll_entry->events = POLLIN;
587 poll_entry++;
d2a1ea1d
BC
588 }
589 if (rtsp_server_fd) {
2b9cd1e7
BC
590 poll_entry->fd = rtsp_server_fd;
591 poll_entry->events = POLLIN;
592 poll_entry++;
d2a1ea1d 593 }
2effd274 594
85f07f22
FB
595 /* wait for events on each HTTP handle */
596 c = first_http_ctx;
2effd274 597 delay = 1000;
85f07f22
FB
598 while (c != NULL) {
599 int fd;
600 fd = c->fd;
601 switch(c->state) {
2effd274
FB
602 case HTTPSTATE_SEND_HEADER:
603 case RTSPSTATE_SEND_REPLY:
bc351386 604 case RTSPSTATE_SEND_PACKET:
85f07f22
FB
605 c->poll_entry = poll_entry;
606 poll_entry->fd = fd;
2effd274 607 poll_entry->events = POLLOUT;
85f07f22
FB
608 poll_entry++;
609 break;
85f07f22
FB
610 case HTTPSTATE_SEND_DATA_HEADER:
611 case HTTPSTATE_SEND_DATA:
612 case HTTPSTATE_SEND_DATA_TRAILER:
2effd274
FB
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;
616 poll_entry->fd = fd;
617 poll_entry->events = POLLOUT;
618 poll_entry++;
619 } else {
e240a0bb
FB
620 /* when ffserver is doing the timing, we work by
621 looking at which packet need to be sent every
622 10 ms */
623 delay1 = 10; /* one tick wait XXX: 10 ms assumed */
624 if (delay1 < delay)
625 delay = delay1;
2effd274 626 }
85f07f22 627 break;
2effd274 628 case HTTPSTATE_WAIT_REQUEST:
85f07f22 629 case HTTPSTATE_RECEIVE_DATA:
85f07f22 630 case HTTPSTATE_WAIT_FEED:
2effd274 631 case RTSPSTATE_WAIT_REQUEST:
85f07f22
FB
632 /* need to catch errors */
633 c->poll_entry = poll_entry;
634 poll_entry->fd = fd;
a6e14edd 635 poll_entry->events = POLLIN;/* Maybe this will work */
85f07f22
FB
636 poll_entry++;
637 break;
638 default:
639 c->poll_entry = NULL;
640 break;
641 }
642 c = c->next;
643 }
644
645 /* wait for an event on one connection. We poll at least every
646 second to handle timeouts */
647 do {
2effd274 648 ret = poll(poll_table, poll_entry - poll_table, delay);
8da4034f
AB
649 if (ret < 0 && ff_neterrno() != FF_NETERROR(EAGAIN) &&
650 ff_neterrno() != FF_NETERROR(EINTR))
53e2f9ca 651 return -1;
e8d658df 652 } while (ret < 0);
115329f1 653
c3f58185 654 cur_time = av_gettime() / 1000;
85f07f22 655
5eb765ef
PG
656 if (need_to_start_children) {
657 need_to_start_children = 0;
658 start_children(first_feed);
659 }
660
85f07f22 661 /* now handle the events */
2effd274
FB
662 for(c = first_http_ctx; c != NULL; c = c_next) {
663 c_next = c->next;
664 if (handle_connection(c) < 0) {
85f07f22 665 /* close and free the connection */
7434ba6d 666 log_connection(c);
2effd274 667 close_connection(c);
85f07f22
FB
668 }
669 }
670
85f07f22 671 poll_entry = poll_table;
d2a1ea1d 672 if (server_fd) {
2b9cd1e7
BC
673 /* new HTTP connection request ? */
674 if (poll_entry->revents & POLLIN)
675 new_connection(server_fd, 0);
676 poll_entry++;
d2a1ea1d
BC
677 }
678 if (rtsp_server_fd) {
2b9cd1e7
BC
679 /* new RTSP connection request ? */
680 if (poll_entry->revents & POLLIN)
681 new_connection(rtsp_server_fd, 1);
d2a1ea1d 682 }
85f07f22
FB
683 }
684}
685
2effd274
FB
686/* start waiting for a new HTTP/RTSP request */
687static void start_wait_request(HTTPContext *c, int is_rtsp)
85f07f22 688{
2effd274
FB
689 c->buffer_ptr = c->buffer;
690 c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
691
692 if (is_rtsp) {
693 c->timeout = cur_time + RTSP_REQUEST_TIMEOUT;
694 c->state = RTSPSTATE_WAIT_REQUEST;
695 } else {
696 c->timeout = cur_time + HTTP_REQUEST_TIMEOUT;
697 c->state = HTTPSTATE_WAIT_REQUEST;
698 }
699}
700
0bdd8b85
BC
701static void http_send_too_busy_reply(int fd)
702{
703 char buffer[300];
704 int len = snprintf(buffer, sizeof(buffer),
705 "HTTP/1.0 200 Server too busy\r\n"
706 "Content-type: text/html\r\n"
707 "\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);
714}
715
716
2effd274
FB
717static void new_connection(int server_fd, int is_rtsp)
718{
719 struct sockaddr_in from_addr;
720 int fd, len;
721 HTTPContext *c = NULL;
722
723 len = sizeof(from_addr);
115329f1 724 fd = accept(server_fd, (struct sockaddr *)&from_addr,
2effd274 725 &len);
050056d0
BC
726 if (fd < 0) {
727 http_log("error during accept %s\n", strerror(errno));
2effd274 728 return;
050056d0 729 }
ba472aaf 730 ff_socket_nonblock(fd, 1);
2effd274 731
0bdd8b85
BC
732 if (nb_connections >= nb_max_connections) {
733 http_send_too_busy_reply(fd);
2effd274 734 goto fail;
0bdd8b85 735 }
115329f1 736
2effd274
FB
737 /* add a new connection */
738 c = av_mallocz(sizeof(HTTPContext));
739 if (!c)
740 goto fail;
115329f1 741
2effd274
FB
742 c->fd = fd;
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);
747 if (!c->buffer)
748 goto fail;
8bc80f8b
PG
749
750 c->next = first_http_ctx;
751 first_http_ctx = c;
2effd274 752 nb_connections++;
115329f1 753
2effd274
FB
754 start_wait_request(c, is_rtsp);
755
756 return;
757
758 fail:
759 if (c) {
760 av_free(c->buffer);
761 av_free(c);
762 }
d96633bb 763 closesocket(fd);
2effd274
FB
764}
765
766static void close_connection(HTTPContext *c)
767{
768 HTTPContext **cp, *c1;
769 int i, nb_streams;
770 AVFormatContext *ctx;
771 URLContext *h;
772 AVStream *st;
773
774 /* remove connection from list */
775 cp = &first_http_ctx;
776 while ((*cp) != NULL) {
777 c1 = *cp;
611c5741 778 if (c1 == c)
2effd274 779 *cp = c->next;
611c5741 780 else
2effd274 781 cp = &c1->next;
2effd274
FB
782 }
783
bc351386
FB
784 /* remove references, if any (XXX: do it faster) */
785 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
786 if (c1->rtsp_c == c)
787 c1->rtsp_c = NULL;
788 }
789
2effd274
FB
790 /* remove connection associated resources */
791 if (c->fd >= 0)
d96633bb 792 closesocket(c->fd);
2effd274
FB
793 if (c->fmt_in) {
794 /* close each frame parser */
795 for(i=0;i<c->fmt_in->nb_streams;i++) {
796 st = c->fmt_in->streams[i];
611c5741 797 if (st->codec->codec)
01f4895c 798 avcodec_close(st->codec);
2effd274
FB
799 }
800 av_close_input_file(c->fmt_in);
801 }
802
803 /* free RTP output streams if any */
804 nb_streams = 0;
115329f1 805 if (c->stream)
2effd274 806 nb_streams = c->stream->nb_streams;
115329f1 807
2effd274
FB
808 for(i=0;i<nb_streams;i++) {
809 ctx = c->rtp_ctx[i];
810 if (ctx) {
811 av_write_trailer(ctx);
812 av_free(ctx);
813 }
814 h = c->rtp_handles[i];
611c5741 815 if (h)
2effd274 816 url_close(h);
2effd274 817 }
115329f1 818
b88ba823
MH
819 ctx = &c->fmt_ctx;
820
637b638e 821 if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
87638494
PG
822 if (ctx->oformat) {
823 /* prepare header */
824 if (url_open_dyn_buf(&ctx->pb) >= 0) {
825 av_write_trailer(ctx);
f8b06be9 826 av_freep(&c->pb_buffer);
899681cd 827 url_close_dyn_buf(ctx->pb, &c->pb_buffer);
87638494
PG
828 }
829 }
830 }
831
115329f1 832 for(i=0; i<ctx->nb_streams; i++)
0bd53967 833 av_free(ctx->streams[i]);
f0ef6240 834
edfdd798 835 if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
6edd6884 836 current_bandwidth -= c->stream->bandwidth;
5400e092
AB
837
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;
841 close(c->feed_fd);
842 }
843
2effd274 844 av_freep(&c->pb_buffer);
bc351386 845 av_freep(&c->packet_buffer);
2effd274
FB
846 av_free(c->buffer);
847 av_free(c);
848 nb_connections--;
849}
850
851static int handle_connection(HTTPContext *c)
852{
853 int len, ret;
115329f1 854
85f07f22
FB
855 switch(c->state) {
856 case HTTPSTATE_WAIT_REQUEST:
2effd274 857 case RTSPSTATE_WAIT_REQUEST:
85f07f22
FB
858 /* timeout ? */
859 if ((c->timeout - cur_time) < 0)
860 return -1;
861 if (c->poll_entry->revents & (POLLERR | POLLHUP))
862 return -1;
863
864 /* no need to read if no events */
865 if (!(c->poll_entry->revents & POLLIN))
866 return 0;
867 /* read the data */
1bc1cfdd 868 read_loop:
c60202df 869 len = recv(c->fd, c->buffer_ptr, 1, 0);
85f07f22 870 if (len < 0) {
8da4034f
AB
871 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
872 ff_neterrno() != FF_NETERROR(EINTR))
85f07f22
FB
873 return -1;
874 } else if (len == 0) {
875 return -1;
876 } else {
94d9ad5f 877 /* search for end of request. */
0c1a9eda 878 uint8_t *ptr;
85f07f22
FB
879 c->buffer_ptr += len;
880 ptr = c->buffer_ptr;
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 */
2effd274
FB
884 if (c->state == HTTPSTATE_WAIT_REQUEST) {
885 ret = http_parse_request(c);
886 } else {
887 ret = rtsp_parse_request(c);
888 }
889 if (ret < 0)
85f07f22
FB
890 return -1;
891 } else if (ptr >= c->buffer_end) {
892 /* request too long: cannot do anything */
893 return -1;
1bc1cfdd 894 } else goto read_loop;
85f07f22
FB
895 }
896 break;
897
898 case HTTPSTATE_SEND_HEADER:
899 if (c->poll_entry->revents & (POLLERR | POLLHUP))
900 return -1;
901
2effd274 902 /* no need to write if no events */
85f07f22
FB
903 if (!(c->poll_entry->revents & POLLOUT))
904 return 0;
c60202df 905 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
85f07f22 906 if (len < 0) {
8da4034f
AB
907 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
908 ff_neterrno() != FF_NETERROR(EINTR)) {
85f07f22 909 /* error : close connection */
2effd274 910 av_freep(&c->pb_buffer);
85f07f22
FB
911 return -1;
912 }
913 } else {
914 c->buffer_ptr += len;
2e04edb3
PG
915 if (c->stream)
916 c->stream->bytes_served += len;
a6e14edd 917 c->data_count += len;
85f07f22 918 if (c->buffer_ptr >= c->buffer_end) {
2effd274 919 av_freep(&c->pb_buffer);
85f07f22 920 /* if error, exit */
611c5741 921 if (c->http_error)
85f07f22 922 return -1;
2effd274 923 /* all the buffer was sent : synchronize to the incoming stream */
85f07f22
FB
924 c->state = HTTPSTATE_SEND_DATA_HEADER;
925 c->buffer_ptr = c->buffer_end = c->buffer;
926 }
927 }
928 break;
929
930 case HTTPSTATE_SEND_DATA:
931 case HTTPSTATE_SEND_DATA_HEADER:
932 case HTTPSTATE_SEND_DATA_TRAILER:
2effd274
FB
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))
938 return -1;
115329f1 939
2effd274
FB
940 /* no need to read if no events */
941 if (!(c->poll_entry->revents & POLLOUT))
942 return 0;
943 }
5eb765ef 944 if (http_send_data(c) < 0)
85f07f22 945 return -1;
638831aa
AB
946 /* close connection if trailer sent */
947 if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
948 return -1;
85f07f22
FB
949 break;
950 case HTTPSTATE_RECEIVE_DATA:
951 /* no need to read if no events */
952 if (c->poll_entry->revents & (POLLERR | POLLHUP))
953 return -1;
954 if (!(c->poll_entry->revents & POLLIN))
955 return 0;
956 if (http_receive_data(c) < 0)
957 return -1;
958 break;
959 case HTTPSTATE_WAIT_FEED:
960 /* no need to read if no events */
a6e14edd 961 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
85f07f22
FB
962 return -1;
963
964 /* nothing to do, we'll be waken up by incoming feed packets */
965 break;
2effd274 966
2effd274
FB
967 case RTSPSTATE_SEND_REPLY:
968 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
969 av_freep(&c->pb_buffer);
970 return -1;
971 }
972 /* no need to write if no events */
973 if (!(c->poll_entry->revents & POLLOUT))
974 return 0;
c60202df 975 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
2effd274 976 if (len < 0) {
8da4034f
AB
977 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
978 ff_neterrno() != FF_NETERROR(EINTR)) {
2effd274
FB
979 /* error : close connection */
980 av_freep(&c->pb_buffer);
981 return -1;
982 }
983 } else {
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);
990 }
991 }
992 break;
bc351386
FB
993 case RTSPSTATE_SEND_PACKET:
994 if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
995 av_freep(&c->packet_buffer);
996 return -1;
997 }
998 /* no need to write if no events */
999 if (!(c->poll_entry->revents & POLLOUT))
1000 return 0;
c60202df
AB
1001 len = send(c->fd, c->packet_buffer_ptr,
1002 c->packet_buffer_end - c->packet_buffer_ptr, 0);
bc351386 1003 if (len < 0) {
8da4034f
AB
1004 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
1005 ff_neterrno() != FF_NETERROR(EINTR)) {
bc351386
FB
1006 /* error : close connection */
1007 av_freep(&c->packet_buffer);
1008 return -1;
1009 }
1010 } else {
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;
1016 }
1017 }
1018 break;
2effd274
FB
1019 case HTTPSTATE_READY:
1020 /* nothing to do */
1021 break;
85f07f22
FB
1022 default:
1023 return -1;
1024 }
1025 return 0;
1026}
1027
3120d2a2
PG
1028static int extract_rates(char *rates, int ratelen, const char *request)
1029{
1030 const char *p;
1031
1032 for (p = request; *p && *p != '\r' && *p != '\n'; ) {
1033 if (strncasecmp(p, "Pragma:", 7) == 0) {
1034 const char *q = p + 7;
1035
1036 while (*q && *q != '\n' && isspace(*q))
1037 q++;
1038
1039 if (strncasecmp(q, "stream-switch-entry=", 20) == 0) {
1040 int stream_no;
1041 int rate_no;
1042
1043 q += 20;
1044
cde25790 1045 memset(rates, 0xff, ratelen);
3120d2a2
PG
1046
1047 while (1) {
1048 while (*q && *q != '\n' && *q != ':')
1049 q++;
1050
611c5741 1051 if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
3120d2a2 1052 break;
611c5741 1053
3120d2a2 1054 stream_no--;
611c5741 1055 if (stream_no < ratelen && stream_no >= 0)
3120d2a2 1056 rates[stream_no] = rate_no;
3120d2a2
PG
1057
1058 while (*q && *q != '\n' && !isspace(*q))
1059 q++;
1060 }
1061
1062 return 1;
1063 }
1064 }
1065 p = strchr(p, '\n');
1066 if (!p)
1067 break;
1068
1069 p++;
1070 }
1071
1072 return 0;
1073}
1074
cde25790 1075static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate)
3120d2a2
PG
1076{
1077 int i;
cde25790
PG
1078 int best_bitrate = 100000000;
1079 int best = -1;
1080
1081 for (i = 0; i < feed->nb_streams; i++) {
01f4895c 1082 AVCodecContext *feed_codec = feed->streams[i]->codec;
cde25790
PG
1083
1084 if (feed_codec->codec_id != codec->codec_id ||
1085 feed_codec->sample_rate != codec->sample_rate ||
1086 feed_codec->width != codec->width ||
611c5741 1087 feed_codec->height != codec->height)
cde25790 1088 continue;
cde25790
PG
1089
1090 /* Potential stream */
1091
115329f1 1092 /* We want the fastest stream less than bit_rate, or the slowest
cde25790
PG
1093 * faster than bit_rate
1094 */
1095
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;
1099 best = i;
1100 }
1101 } else {
1102 if (feed_codec->bit_rate < best_bitrate) {
1103 best_bitrate = feed_codec->bit_rate;
1104 best = i;
1105 }
1106 }
1107 }
1108
1109 return best;
1110}
1111
1112static int modify_current_stream(HTTPContext *c, char *rates)
1113{
1114 int i;
1115 FFStream *req = c->stream;
1116 int action_required = 0;
3120d2a2 1117
001bcd29
PG
1118 /* Not much we can do for a feed */
1119 if (!req->feed)
1120 return 0;
1121
3120d2a2 1122 for (i = 0; i < req->nb_streams; i++) {
01f4895c 1123 AVCodecContext *codec = req->streams[i]->codec;
3120d2a2 1124
3120d2a2
PG
1125 switch(rates[i]) {
1126 case 0:
cde25790 1127 c->switch_feed_streams[i] = req->feed_streams[i];
3120d2a2
PG
1128 break;
1129 case 1:
cde25790 1130 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
3120d2a2
PG
1131 break;
1132 case 2:
cde25790
PG
1133 /* Wants off or slow */
1134 c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
1135#ifdef WANTS_OFF
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;
1139#endif
3120d2a2
PG
1140 break;
1141 }
3120d2a2 1142
cde25790
PG
1143 if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i])
1144 action_required = 1;
1145 }
3120d2a2 1146
cde25790
PG
1147 return action_required;
1148}
3120d2a2 1149
3120d2a2 1150
cde25790
PG
1151static void do_switch_stream(HTTPContext *c, int i)
1152{
1153 if (c->switch_feed_streams[i] >= 0) {
115329f1 1154#ifdef PHILIP
cde25790
PG
1155 c->feed_streams[i] = c->switch_feed_streams[i];
1156#endif
3120d2a2 1157
cde25790 1158 /* Now update the stream */
3120d2a2 1159 }
cde25790 1160 c->switch_feed_streams[i] = -1;
3120d2a2 1161}
7434ba6d 1162
2effd274
FB
1163/* XXX: factorize in utils.c ? */
1164/* XXX: take care with different space meaning */
1165static void skip_spaces(const char **pp)
1166{
1167 const char *p;
1168 p = *pp;
1169 while (*p == ' ' || *p == '\t')
1170 p++;
1171 *pp = p;
1172}
1173
1174static void get_word(char *buf, int buf_size, const char **pp)
1175{
1176 const char *p;
1177 char *q;
1178
1179 p = *pp;
1180 skip_spaces(&p);
1181 q = buf;
1182 while (!isspace(*p) && *p != '\0') {
1183 if ((q - buf) < buf_size - 1)
1184 *q++ = *p;
1185 p++;
1186 }
1187 if (buf_size > 0)
1188 *q = '\0';
1189 *pp = p;
1190}
1191
c64c0a9b
BL
1192static void get_arg(char *buf, int buf_size, const char **pp)
1193{
1194 const char *p;
1195 char *q;
1196 int quote;
1197
1198 p = *pp;
1199 while (isspace(*p)) p++;
1200 q = buf;
1201 quote = 0;
1202 if (*p == '\"' || *p == '\'')
1203 quote = *p++;
1204 for(;;) {
1205 if (quote) {
1206 if (*p == quote)
1207 break;
1208 } else {
1209 if (isspace(*p))
1210 break;
1211 }
1212 if (*p == '\0')
1213 break;
1214 if ((q - buf) < buf_size - 1)
1215 *q++ = *p;
1216 p++;
1217 }
1218 *q = '\0';
1219 if (quote && *p == quote)
1220 p++;
1221 *pp = p;
1222}
1223
8256c0a3
PG
1224static int validate_acl(FFStream *stream, HTTPContext *c)
1225{
1226 enum IPAddressAction last_action = IP_DENY;
1227 IPAddressACL *acl;
1228 struct in_addr *src = &c->from_addr.sin_addr;
2bd8416e 1229 unsigned long src_addr = src->s_addr;
8256c0a3
PG
1230
1231 for (acl = stream->acl; acl; acl = acl->next) {
611c5741 1232 if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
8256c0a3 1233 return (acl->action == IP_ALLOW) ? 1 : 0;
8256c0a3
PG
1234 last_action = acl->action;
1235 }
1236
1237 /* Nothing matched, so return not the last action */
1238 return (last_action == IP_DENY) ? 1 : 0;
1239}
1240
829ac53d
FB
1241/* compute the real filename of a file by matching it without its
1242 extensions to all the stream filenames */
1243static void compute_real_filename(char *filename, int max_size)
1244{
1245 char file1[1024];
1246 char file2[1024];
1247 char *p;
1248 FFStream *stream;
1249
1250 /* compute filename by matching without the file extensions */
f7d78f36 1251 av_strlcpy(file1, filename, sizeof(file1));
829ac53d
FB
1252 p = strrchr(file1, '.');
1253 if (p)
1254 *p = '\0';
1255 for(stream = first_stream; stream != NULL; stream = stream->next) {
f7d78f36 1256 av_strlcpy(file2, stream->filename, sizeof(file2));
829ac53d
FB
1257 p = strrchr(file2, '.');
1258 if (p)
1259 *p = '\0';
1260 if (!strcmp(file1, file2)) {
f7d78f36 1261 av_strlcpy(filename, stream->filename, max_size);
829ac53d
FB
1262 break;
1263 }
1264 }
1265}
1266
1267enum RedirType {
1268 REDIR_NONE,
1269 REDIR_ASX,
1270 REDIR_RAM,
1271 REDIR_ASF,
1272 REDIR_RTSP,
1273 REDIR_SDP,
1274};
1275
85f07f22
FB
1276/* parse http request and prepare header */
1277static int http_parse_request(HTTPContext *c)
1278{
1279 char *p;
829ac53d 1280 enum RedirType redir_type;
85f07f22 1281 char cmd[32];
bae79c04 1282 char info[1024], filename[1024];
85f07f22
FB
1283 char url[1024], *q;
1284 char protocol[32];
1285 char msg[1024];
1286 const char *mime_type;
1287 FFStream *stream;
42a63c6a 1288 int i;
3120d2a2 1289 char ratebuf[32];
cde25790 1290 char *useragent = 0;
85f07f22
FB
1291
1292 p = c->buffer;
2effd274 1293 get_word(cmd, sizeof(cmd), (const char **)&p);
f7d78f36 1294 av_strlcpy(c->method, cmd, sizeof(c->method));
7434ba6d 1295
85f07f22 1296 if (!strcmp(cmd, "GET"))
edfdd798 1297 c->post = 0;
85f07f22 1298 else if (!strcmp(cmd, "POST"))
edfdd798 1299 c->post = 1;
85f07f22
FB
1300 else
1301 return -1;
1302
2effd274 1303 get_word(url, sizeof(url), (const char **)&p);
f7d78f36 1304 av_strlcpy(c->url, url, sizeof(c->url));
7434ba6d 1305
2effd274 1306 get_word(protocol, sizeof(protocol), (const char **)&p);
85f07f22
FB
1307 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
1308 return -1;
7434ba6d 1309
f7d78f36 1310 av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
90f9c440
AB
1311
1312 if (ffserver_debug)
77553ae3 1313 http_log("%s - - New connection: %s %s\n", inet_ntoa(c->from_addr.sin_addr), cmd, url);
115329f1 1314
85f07f22 1315 /* find the filename and the optional info string in the request */
bae79c04 1316 p = strchr(url, '?');
85f07f22 1317 if (p) {
f7d78f36 1318 av_strlcpy(info, p, sizeof(info));
85f07f22 1319 *p = '\0';
611c5741 1320 } else
85f07f22 1321 info[0] = '\0';
85f07f22 1322
f7d78f36 1323 av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
bae79c04 1324
cde25790
PG
1325 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1326 if (strncasecmp(p, "User-Agent:", 11) == 0) {
1327 useragent = p + 11;
1328 if (*useragent && *useragent != '\n' && isspace(*useragent))
1329 useragent++;
1330 break;
1331 }
1332 p = strchr(p, '\n');
1333 if (!p)
1334 break;
1335
1336 p++;
1337 }
1338
829ac53d 1339 redir_type = REDIR_NONE;
aa13b573 1340 if (av_match_ext(filename, "asx")) {
829ac53d 1341 redir_type = REDIR_ASX;
7434ba6d 1342 filename[strlen(filename)-1] = 'f';
aa13b573 1343 } else if (av_match_ext(filename, "asf") &&
cde25790
PG
1344 (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) {
1345 /* if this isn't WMP or lookalike, return the redirector file */
829ac53d 1346 redir_type = REDIR_ASF;
aa13b573 1347 } else if (av_match_ext(filename, "rpm,ram")) {
829ac53d 1348 redir_type = REDIR_RAM;
42a63c6a 1349 strcpy(filename + strlen(filename)-2, "m");
aa13b573 1350 } else if (av_match_ext(filename, "rtsp")) {
829ac53d 1351 redir_type = REDIR_RTSP;
bae79c04 1352 compute_real_filename(filename, sizeof(filename) - 1);
aa13b573 1353 } else if (av_match_ext(filename, "sdp")) {
829ac53d 1354 redir_type = REDIR_SDP;
bae79c04 1355 compute_real_filename(filename, sizeof(filename) - 1);
42a63c6a 1356 }
115329f1 1357
bae79c04
AB
1358 // "redirect" / request to index.html
1359 if (!strlen(filename))
f7d78f36 1360 av_strlcpy(filename, "index.html", sizeof(filename) - 1);
bae79c04 1361
85f07f22
FB
1362 stream = first_stream;
1363 while (stream != NULL) {
8256c0a3 1364 if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
85f07f22
FB
1365 break;
1366 stream = stream->next;
1367 }
1368 if (stream == NULL) {
d445a7e9 1369 snprintf(msg, sizeof(msg), "File '%s' not found", url);
77553ae3 1370 http_log("File '%s' not found\n", url);
85f07f22
FB
1371 goto send_error;
1372 }
42a63c6a 1373
cde25790
PG
1374 c->stream = stream;
1375 memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
1376 memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
1377
1378 if (stream->stream_type == STREAM_TYPE_REDIRECT) {
1379 c->http_error = 301;
1380 q = c->buffer;
a3aa4fed
BC
1381 q += snprintf(q, c->buffer_size,
1382 "HTTP/1.0 301 Moved\r\n"
1383 "Location: %s\r\n"
1384 "Content-type: text/html\r\n"
1385 "\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);
cde25790
PG
1389 /* prepare output buffer */
1390 c->buffer_ptr = c->buffer;
1391 c->buffer_end = q;
1392 c->state = HTTPSTATE_SEND_HEADER;
1393 return 0;
1394 }
1395
3120d2a2
PG
1396 /* If this is WMP, get the rate information */
1397 if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
cde25790 1398 if (modify_current_stream(c, ratebuf)) {
37d3e066 1399 for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
cde25790
PG
1400 if (c->switch_feed_streams[i] >= 0)
1401 do_switch_stream(c, i);
1402 }
1403 }
3120d2a2
PG
1404 }
1405
d8f28a77
BC
1406 if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
1407 current_bandwidth += stream->bandwidth;
1408
755bfeab 1409 /* If already streaming this feed, do not let start another feeder. */
d0a5513b
AB
1410 if (stream->feed_opened) {
1411 snprintf(msg, sizeof(msg), "This feed is already being received.");
77553ae3 1412 http_log("Feed '%s' already being received\n", stream->feed_filename);
d0a5513b
AB
1413 goto send_error;
1414 }
1415
edfdd798 1416 if (c->post == 0 && max_bandwidth < current_bandwidth) {
42a63c6a
PG
1417 c->http_error = 200;
1418 q = c->buffer;
a3aa4fed
BC
1419 q += snprintf(q, c->buffer_size,
1420 "HTTP/1.0 200 Server too busy\r\n"
1421 "Content-type: text/html\r\n"
1422 "\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"
0be4b8d9
BC
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"
a3aa4fed 1427 "</body></html>\r\n", current_bandwidth, max_bandwidth);
42a63c6a
PG
1428 /* prepare output buffer */
1429 c->buffer_ptr = c->buffer;
1430 c->buffer_end = q;
1431 c->state = HTTPSTATE_SEND_HEADER;
1432 return 0;
1433 }
115329f1 1434
829ac53d 1435 if (redir_type != REDIR_NONE) {
7434ba6d 1436 char *hostinfo = 0;
115329f1 1437
7434ba6d
PG
1438 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1439 if (strncasecmp(p, "Host:", 5) == 0) {
1440 hostinfo = p + 5;
1441 break;
1442 }
1443 p = strchr(p, '\n');
1444 if (!p)
1445 break;
1446
1447 p++;
1448 }
1449
1450 if (hostinfo) {
1451 char *eoh;
1452 char hostbuf[260];
1453
1454 while (isspace(*hostinfo))
1455 hostinfo++;
1456
1457 eoh = strchr(hostinfo, '\n');
1458 if (eoh) {
1459 if (eoh[-1] == '\r')
1460 eoh--;
1461
1462 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
1463 memcpy(hostbuf, hostinfo, eoh - hostinfo);
1464 hostbuf[eoh - hostinfo] = 0;
1465
1466 c->http_error = 200;
1467 q = c->buffer;
829ac53d
FB
1468 switch(redir_type) {
1469 case REDIR_ASX:
a3aa4fed
BC
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"
1473 "\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);
829ac53d
FB
1478 break;
1479 case REDIR_RAM:
a3aa4fed
BC
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"
1483 "\r\n"
1484 "# Autogenerated by ffserver\r\n"
1485 "http://%s/%s%s\r\n", hostbuf, filename, info);
829ac53d
FB
1486 break;
1487 case REDIR_ASF:
a3aa4fed
BC
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"
1491 "\r\n"
1492 "[Reference]\r\n"
1493 "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
829ac53d
FB
1494 break;
1495 case REDIR_RTSP:
1496 {
1497 char hostname[256], *p;
1498 /* extract only hostname */
f7d78f36 1499 av_strlcpy(hostname, hostbuf, sizeof(hostname));
829ac53d
FB
1500 p = strrchr(hostname, ':');
1501 if (p)
1502 *p = '\0';
a3aa4fed
BC
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"
1507 "\r\n"
1508 "rtsp://%s:%d/%s\r\n", hostname, ntohs(my_rtsp_addr.sin_port), filename);
829ac53d
FB
1509 }
1510 break;
1511 case REDIR_SDP:
1512 {
0c1a9eda 1513 uint8_t *sdp_data;
829ac53d
FB
1514 int sdp_data_size, len;
1515 struct sockaddr_in my_addr;
1516
a3aa4fed
BC
1517 q += snprintf(q, c->buffer_size,
1518 "HTTP/1.0 200 OK\r\n"
1519 "Content-type: application/sdp\r\n"
1520 "\r\n");
829ac53d
FB
1521
1522 len = sizeof(my_addr);
1523 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
115329f1 1524
829ac53d 1525 /* XXX: should use a dynamic buffer */
115329f1
DB
1526 sdp_data_size = prepare_sdp_description(stream,
1527 &sdp_data,
829ac53d
FB
1528 my_addr.sin_addr);
1529 if (sdp_data_size > 0) {
1530 memcpy(q, sdp_data, sdp_data_size);
1531 q += sdp_data_size;
1532 *q = '\0';
1533 av_free(sdp_data);
1534 }
1535 }
1536 break;
1537 default:
0f4e8165 1538 abort();
829ac53d 1539 break;
2effd274 1540 }
7434ba6d
PG
1541
1542 /* prepare output buffer */
1543 c->buffer_ptr = c->buffer;
1544 c->buffer_end = q;
1545 c->state = HTTPSTATE_SEND_HEADER;
1546 return 0;
1547 }
1548 }
1549 }
1550
d445a7e9 1551 snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
7434ba6d 1552 goto send_error;
85f07f22
FB
1553 }
1554
a6e14edd 1555 stream->conns_served++;
7434ba6d 1556
85f07f22
FB
1557 /* XXX: add there authenticate and IP match */
1558
edfdd798 1559 if (c->post) {
85f07f22
FB
1560 /* if post, it means a feed is being sent */
1561 if (!stream->is_feed) {
e16190fa
DB
1562 /* However it might be a status report from WMP! Let us log the
1563 * data as it might come in handy one day. */
7434ba6d 1564 char *logline = 0;
3120d2a2 1565 int client_id = 0;
115329f1 1566
7434ba6d
PG
1567 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
1568 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
1569 logline = p;
1570 break;
1571 }
611c5741 1572 if (strncasecmp(p, "Pragma: client-id=", 18) == 0)
3120d2a2 1573 client_id = strtol(p + 18, 0, 10);
7434ba6d
PG
1574 p = strchr(p, '\n');
1575 if (!p)
1576 break;
1577
1578 p++;
1579 }
1580
1581 if (logline) {
1582 char *eol = strchr(logline, '\n');
1583
1584 logline += 17;
1585
1586 if (eol) {
1587 if (eol[-1] == '\r')
1588 eol--;
7906085f 1589 http_log("%.*s\n", (int) (eol - logline), logline);
7434ba6d
PG
1590 c->suppress_log = 1;
1591 }
1592 }
3120d2a2 1593
cde25790
PG
1594#ifdef DEBUG_WMP
1595 http_log("\nGot request:\n%s\n", c->buffer);
3120d2a2
PG
1596#endif
1597
1598 if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
1599 HTTPContext *wmpc;
1600
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)
1604 break;
1605 }
1606
2d563d2f
AB
1607 if (wmpc && modify_current_stream(wmpc, ratebuf))
1608 wmpc->switch_pending = 1;
3120d2a2 1609 }
115329f1 1610
d445a7e9 1611 snprintf(msg, sizeof(msg), "POST command not handled");
cb275dd9 1612 c->stream = 0;
85f07f22
FB
1613 goto send_error;
1614 }
1615 if (http_start_receive_data(c) < 0) {
d445a7e9 1616 snprintf(msg, sizeof(msg), "could not open feed");
85f07f22
FB
1617 goto send_error;
1618 }
1619 c->http_error = 0;
1620 c->state = HTTPSTATE_RECEIVE_DATA;
1621 return 0;
1622 }
1623
cde25790 1624#ifdef DEBUG_WMP
611c5741 1625 if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
cde25790 1626 http_log("\nGot request:\n%s\n", c->buffer);
3120d2a2
PG
1627#endif
1628
85f07f22 1629 if (c->stream->stream_type == STREAM_TYPE_STATUS)
dca21085 1630 goto send_status;
85f07f22
FB
1631
1632 /* open input stream */
1633 if (open_input_stream(c, info) < 0) {
d445a7e9 1634 snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
85f07f22
FB
1635 goto send_error;
1636 }
1637
1638 /* prepare http header */
1639 q = c->buffer;
d445a7e9 1640 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n");
85f07f22
FB
1641 mime_type = c->stream->fmt->mime_type;
1642 if (!mime_type)
087fa475 1643 mime_type = "application/x-octet-stream";
d445a7e9 1644 q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Pragma: no-cache\r\n");
85f07f22
FB
1645
1646 /* for asf, we need extra headers */
8256c0a3 1647 if (!strcmp(c->stream->fmt->name,"asf_stream")) {
3120d2a2 1648 /* Need to allocate a client id */
3120d2a2 1649
042819c5 1650 c->wmp_client_id = av_lfg_get(&random_state);
3120d2a2 1651
d445a7e9 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);
85f07f22 1653 }
d445a7e9
PG
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");
115329f1 1656
85f07f22
FB
1657 /* prepare output buffer */
1658 c->http_error = 0;
1659 c->buffer_ptr = c->buffer;
1660 c->buffer_end = q;
1661 c->state = HTTPSTATE_SEND_HEADER;
1662 return 0;
1663 send_error:
1664 c->http_error = 404;
1665 q = c->buffer;
a3aa4fed
BC
1666 q += snprintf(q, c->buffer_size,
1667 "HTTP/1.0 404 Not Found\r\n"
1668 "Content-type: text/html\r\n"
1669 "\r\n"
5e567aae
DB
1670 "<html>\n"
1671 "<head><title>404 Not Found</title></head>\n"
1672 "<body>%s</body>\n"
1673 "</html>\n", msg);
85f07f22
FB
1674 /* prepare output buffer */
1675 c->buffer_ptr = c->buffer;
1676 c->buffer_end = q;
1677 c->state = HTTPSTATE_SEND_HEADER;
1678 return 0;
dca21085
SS
1679 send_status:
1680 compute_status(c);
85f07f22
FB
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;
1684 return 0;
1685}
1686
0c1a9eda 1687static void fmt_bytecount(ByteIOContext *pb, int64_t count)
2ac887ba
PG
1688{
1689 static const char *suffix = " kMGTP";
1690 const char *s;
1691
611c5741 1692 for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
2ac887ba 1693
4733abcb 1694 url_fprintf(pb, "%"PRId64"%c", count, *s);
2ac887ba
PG
1695}
1696
dca21085 1697static void compute_status(HTTPContext *c)
85f07f22
FB
1698{
1699 HTTPContext *c1;
1700 FFStream *stream;
2effd274 1701 char *p;
85f07f22 1702 time_t ti;
2effd274 1703 int i, len;
899681cd 1704 ByteIOContext *pb;
cde25790 1705
899681cd 1706 if (url_open_dyn_buf(&pb) < 0) {
2effd274 1707 /* XXX: return an error ? */
cde25790 1708 c->buffer_ptr = c->buffer;
2effd274
FB
1709 c->buffer_end = c->buffer;
1710 return;
cde25790 1711 }
85f07f22 1712
2effd274
FB
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");
115329f1 1717
5e567aae 1718 url_fprintf(pb, "<html><head><title>%s Status</title>\n", program_name);
0679719d 1719 if (c->stream->feed_filename[0])
2effd274 1720 url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename);
5e567aae
DB
1721 url_fprintf(pb, "</head>\n<body>");
1722 url_fprintf(pb, "<h1>%s Status</h1>\n", program_name);
85f07f22 1723 /* format status */
5e567aae
DB
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");
85f07f22
FB
1727 stream = first_stream;
1728 while (stream != NULL) {
42a63c6a
PG
1729 char sfilename[1024];
1730 char *eosf;
1731
a6e14edd 1732 if (stream->feed != stream) {
f7d78f36 1733 av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
a6e14edd
PG
1734 eosf = sfilename + strlen(sfilename);
1735 if (eosf - sfilename >= 4) {
611c5741 1736 if (strcmp(eosf - 4, ".asf") == 0)
a6e14edd 1737 strcpy(eosf - 4, ".asx");
611c5741 1738 else if (strcmp(eosf - 3, ".rm") == 0)
a6e14edd 1739 strcpy(eosf - 3, ".ram");
25e3e53d 1740 else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
829ac53d
FB
1741 /* generate a sample RTSP director if
1742 unicast. Generate an SDP redirector if
1743 multicast */
2effd274
FB
1744 eosf = strrchr(sfilename, '.');
1745 if (!eosf)
1746 eosf = sfilename + strlen(sfilename);
829ac53d
FB
1747 if (stream->is_multicast)
1748 strcpy(eosf, ".sdp");
1749 else
1750 strcpy(eosf, ".rtsp");
a6e14edd 1751 }
42a63c6a 1752 }
115329f1 1753
5e567aae 1754 url_fprintf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
a6e14edd 1755 sfilename, stream->filename);
2effd274 1756 url_fprintf(pb, "<td align=right> %d <td align=right> ",
2ac887ba 1757 stream->conns_served);
2effd274 1758 fmt_bytecount(pb, stream->bytes_served);
a6e14edd 1759 switch(stream->stream_type) {
ace21da3 1760 case STREAM_TYPE_LIVE: {
a6e14edd
PG
1761 int audio_bit_rate = 0;
1762 int video_bit_rate = 0;
58445440
ZK
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 = "";
a6e14edd
PG
1767
1768 for(i=0;i<stream->nb_streams;i++) {
1769 AVStream *st = stream->streams[i];
01f4895c
MN
1770 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
1771 switch(st->codec->codec_type) {
a6e14edd 1772 case CODEC_TYPE_AUDIO:
01f4895c 1773 audio_bit_rate += st->codec->bit_rate;
a6e14edd
PG
1774 if (codec) {
1775 if (*audio_codec_name)
1776 audio_codec_name_extra = "...";
1777 audio_codec_name = codec->name;
1778 }
1779 break;
1780 case CODEC_TYPE_VIDEO:
01f4895c 1781 video_bit_rate += st->codec->bit_rate;
a6e14edd
PG
1782 if (codec) {
1783 if (*video_codec_name)
1784 video_codec_name_extra = "...";
1785 video_codec_name = codec->name;
1786 }
1787 break;
e240a0bb 1788 case CODEC_TYPE_DATA:
01f4895c 1789 video_bit_rate += st->codec->bit_rate;
e240a0bb 1790 break;
a6e14edd 1791 default:
0f4e8165 1792 abort();
79c4ea3c 1793 }
85f07f22 1794 }
5e567aae 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",
a6e14edd 1796 stream->fmt->name,
6edd6884 1797 stream->bandwidth,
a6e14edd
PG
1798 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
1799 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
611c5741 1800 if (stream->feed)
5e567aae 1801 url_fprintf(pb, "<td>%s", stream->feed->filename);
611c5741 1802 else
5e567aae 1803 url_fprintf(pb, "<td>%s", stream->feed_filename);
2effd274 1804 url_fprintf(pb, "\n");
85f07f22 1805 }
a6e14edd
PG
1806 break;
1807 default:
5e567aae 1808 url_fprintf(pb, "<td align=center> - <td align=right> - <td align=right> - <td><td align=right> - <td>\n");
a6e14edd 1809 break;
85f07f22 1810 }
85f07f22
FB
1811 }
1812 stream = stream->next;
1813 }
5e567aae 1814 url_fprintf(pb, "</table>\n");
a6e14edd
PG
1815
1816 stream = first_stream;
1817 while (stream != NULL) {
1818 if (stream->feed == stream) {
2effd274 1819 url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename);
cde25790 1820 if (stream->pid) {
2effd274 1821 url_fprintf(pb, "Running as pid %d.\n", stream->pid);
cde25790 1822
2effd274
FB
1823#if defined(linux) && !defined(CONFIG_NOCUTILS)
1824 {
1825 FILE *pid_stat;
1826 char ps_cmd[64];
1827
1828 /* This is somewhat linux specific I guess */
115329f1
DB
1829 snprintf(ps_cmd, sizeof(ps_cmd),
1830 "ps -o \"%%cpu,cputime\" --no-headers %d",
2effd274 1831 stream->pid);
115329f1 1832
2effd274
FB
1833 pid_stat = popen(ps_cmd, "r");
1834 if (pid_stat) {
1835 char cpuperc[10];
1836 char cpuused[64];
115329f1
DB
1837
1838 if (fscanf(pid_stat, "%10s %64s", cpuperc,
2effd274
FB
1839 cpuused) == 2) {
1840 url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n",
1841 cpuperc, cpuused);
1842 }
1843 fclose(pid_stat);
cde25790 1844 }
cde25790
PG
1845 }
1846#endif
1847
2effd274 1848 url_fprintf(pb, "<p>");
cde25790 1849 }
2effd274 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");
a6e14edd
PG
1851
1852 for (i = 0; i < stream->nb_streams; i++) {
1853 AVStream *st = stream->streams[i];
01f4895c 1854 AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
b29f97d1 1855 const char *type = "unknown";
b582f314
PG
1856 char parameters[64];
1857
1858 parameters[0] = 0;
a6e14edd 1859
01f4895c 1860 switch(st->codec->codec_type) {
a6e14edd
PG
1861 case CODEC_TYPE_AUDIO:
1862 type = "audio";
acdc8520 1863 snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz", st->codec->channels, st->codec->sample_rate);
a6e14edd
PG
1864 break;
1865 case CODEC_TYPE_VIDEO:
1866 type = "video";
01f4895c
MN
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);
a6e14edd
PG
1869 break;
1870 default:
0f4e8165 1871 abort();
a6e14edd 1872 }
2effd274 1873 url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n",
01f4895c 1874 i, type, st->codec->bit_rate/1000, codec ? codec->name : "", parameters);
a6e14edd 1875 }
2effd274 1876 url_fprintf(pb, "</table>\n");
a6e14edd 1877
115329f1 1878 }
a6e14edd
PG
1879 stream = stream->next;
1880 }
115329f1 1881
85f07f22 1882 /* connection status */
5e567aae 1883 url_fprintf(pb, "<h2>Connection Status</h2>\n");
85f07f22 1884
5e567aae 1885 url_fprintf(pb, "Number of connections: %d / %d<br>\n",
85f07f22
FB
1886 nb_connections, nb_max_connections);
1887
5e567aae 1888 url_fprintf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
6edd6884 1889 current_bandwidth, max_bandwidth);
42a63c6a 1890
5e567aae
DB
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");
85f07f22
FB
1893 c1 = first_http_ctx;
1894 i = 0;
2effd274 1895 while (c1 != NULL) {
cde25790
PG
1896 int bitrate;
1897 int j;
1898
1899 bitrate = 0;
2effd274
FB
1900 if (c1->stream) {
1901 for (j = 0; j < c1->stream->nb_streams; j++) {
2d563d2f 1902 if (!c1->stream->feed)
01f4895c 1903 bitrate += c1->stream->streams[j]->codec->bit_rate;
2d563d2f
AB
1904 else if (c1->feed_streams[j] >= 0)
1905 bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
cde25790
PG
1906 }
1907 }
1908
85f07f22
FB
1909 i++;
1910 p = inet_ntoa(c1->from_addr.sin_addr);
5e567aae 1911 url_fprintf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s<td align=right>",
115329f1
DB
1912 i,
1913 c1->stream ? c1->stream->filename : "",
2effd274 1914 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
115329f1 1915 p,
2effd274
FB
1916 c1->protocol,
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");
85f07f22
FB
1924 c1 = c1->next;
1925 }
5e567aae 1926 url_fprintf(pb, "</table>\n");
115329f1 1927
85f07f22
FB
1928 /* date */
1929 ti = time(NULL);
1930 p = ctime(&ti);
5e567aae
DB
1931 url_fprintf(pb, "<hr size=1 noshade>Generated at %s", p);
1932 url_fprintf(pb, "</body>\n</html>\n");
85f07f22 1933
2effd274
FB
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;
85f07f22
FB
1937}
1938
2effd274
FB
1939/* check if the parser needs to be opened for stream i */
1940static void open_parser(AVFormatContext *s, int i)
85f07f22 1941{
2effd274
FB
1942 AVStream *st = s->streams[i];
1943 AVCodec *codec;
31def229 1944
01f4895c
MN
1945 if (!st->codec->codec) {
1946 codec = avcodec_find_decoder(st->codec->codec_id);
2effd274 1947 if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) {
01f4895c 1948 st->codec->parse_only = 1;
611c5741 1949 if (avcodec_open(st->codec, codec) < 0)
01f4895c 1950 st->codec->parse_only = 0;
cde25790
PG
1951 }
1952 }
85f07f22
FB
1953}
1954
1955static int open_input_stream(HTTPContext *c, const char *info)
1956{
1957 char buf[128];
1958 char input_filename[1024];
1959 AVFormatContext *s;
c351cc7f 1960 int buf_size, i, ret;
0c1a9eda 1961 int64_t stream_pos;
85f07f22
FB
1962
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) */
ace21da3 1968 if (find_info_tag(buf, sizeof(buf), "date", info)) {
85f07f22 1969 stream_pos = parse_date(buf, 0);
f9436161
SS
1970 if (stream_pos == INT64_MIN)
1971 return -1;
ace21da3 1972 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
f747e6d3 1973 int prebuffer = strtol(buf, 0, 10);
0c1a9eda 1974 stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
611c5741 1975 } else
0c1a9eda 1976 stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
85f07f22
FB
1977 } else {
1978 strcpy(input_filename, c->stream->feed_filename);
1979 buf_size = 0;
1980 /* compute position (relative time) */
ace21da3 1981 if (find_info_tag(buf, sizeof(buf), "date", info)) {
85f07f22 1982 stream_pos = parse_date(buf, 1);
f9436161
SS
1983 if (stream_pos == INT64_MIN)
1984 return -1;
ace21da3 1985 } else
85f07f22 1986 stream_pos = 0;
85f07f22
FB
1987 }
1988 if (input_filename[0] == '\0')
1989 return -1;
1990
1991 /* open stream */
c351cc7f
BC
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);
85f07f22 1995 return -1;
2effd274 1996 }
9dc0bc3d 1997 s->flags |= AVFMT_FLAG_GENPTS;
85f07f22 1998 c->fmt_in = s;
85fe4ae0 1999 if (strcmp(s->iformat->name, "ffm") && av_find_stream_info(c->fmt_in) < 0) {
20f93c3c
BC
2000 http_log("Could not find stream info '%s'\n", input_filename);
2001 av_close_input_file(s);
2002 return -1;
2003 }
115329f1 2004
2effd274
FB
2005 /* open each parser */
2006 for(i=0;i<s->nb_streams;i++)
2007 open_parser(s, i);
2008
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++) {
115329f1 2013 if (c->pts_stream_index == 0 &&
01f4895c 2014 c->stream->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO) {
2effd274
FB
2015 c->pts_stream_index = i;
2016 }
2017 }
85f07f22 2018
e8d27bc3 2019#if 1
611c5741 2020 if (c->fmt_in->iformat->read_seek)
60a04f7f 2021 av_seek_frame(c->fmt_in, -1, stream_pos, 0);
e240a0bb 2022#endif
2effd274
FB
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;
85f07f22
FB
2026 return 0;
2027}
2028
e240a0bb
FB
2029/* return the server clock (in us) */
2030static int64_t get_server_clock(HTTPContext *c)
2effd274 2031{
e240a0bb 2032 /* compute current pts value from system time */
c3f58185 2033 return (cur_time - c->start_time) * 1000;
2effd274
FB
2034}
2035
e240a0bb
FB
2036/* return the estimated time at which the current packet must be sent
2037 (in us) */
2038static int64_t get_packet_send_clock(HTTPContext *c)
2effd274 2039{
e240a0bb 2040 int bytes_left, bytes_sent, frame_bytes;
115329f1 2041
e240a0bb 2042 frame_bytes = c->cur_frame_bytes;
611c5741 2043 if (frame_bytes <= 0)
e240a0bb 2044 return c->cur_pts;
611c5741 2045 else {
e240a0bb
FB
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;
2effd274 2049 }
2effd274 2050}
2effd274 2051
2effd274 2052
2effd274
FB
2053static int http_prepare_data(HTTPContext *c)
2054{
2055 int i, len, ret;
2056 AVFormatContext *ctx;
2057
bc351386 2058 av_freep(&c->pb_buffer);
2effd274
FB
2059 switch(c->state) {
2060 case HTTPSTATE_SEND_DATA_HEADER:
2061 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
5ee999b8
AJ
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);
2effd274 2066
3d9cc27d 2067 for(i=0;i<c->stream->nb_streams;i++) {
2effd274 2068 AVStream *st;
bb270c08 2069 AVStream *src;
2effd274
FB
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 */
115329f1 2073 if (!c->stream->feed ||
2effd274 2074 c->stream->feed == c->stream)
7c054ea7 2075 src = c->stream->streams[i];
2effd274 2076 else
7c054ea7
PG
2077 src = c->stream->feed->streams[c->stream->feed_streams[i]];
2078
bb270c08
DB
2079 *st = *src;
2080 st->priv_data = 0;
01f4895c 2081 st->codec->frame_number = 0; /* XXX: should be done in
2effd274
FB
2082 AVStream, not in codec */
2083 }
3d9cc27d
BC
2084 /* set output format parameters */
2085 c->fmt_ctx.oformat = c->stream->fmt;
2086 c->fmt_ctx.nb_streams = c->stream->nb_streams;
2087
2effd274
FB
2088 c->got_key_frame = 0;
2089
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 */
2093 return -1;
2094 }
899681cd 2095 c->fmt_ctx.pb->is_streamed = 1;
2effd274 2096
8aae202e
BC
2097 /*
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
2101 */
2102 c->fmt_ctx.preload = (int)(0.5*AV_TIME_BASE);
2103 c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
2104
3c27199b 2105 av_set_parameters(&c->fmt_ctx, NULL);
929a9b75
BC
2106 if (av_write_header(&c->fmt_ctx) < 0) {
2107 http_log("Error writing output header\n");
f75cdda7 2108 return -1;
929a9b75 2109 }
2effd274 2110
899681cd 2111 len = url_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
2effd274
FB
2112 c->buffer_ptr = c->pb_buffer;
2113 c->buffer_end = c->pb_buffer + len;
2114
2115 c->state = HTTPSTATE_SEND_DATA;
85f07f22
FB
2116 c->last_packet_sent = 0;
2117 break;
2118 case HTTPSTATE_SEND_DATA:
2119 /* find a new packet */
3b371676
BC
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);
2125
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;
2130 else {
2131 AVPacket pkt;
2132 redo:
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 */
2effd274 2139 } else {
3b371676
BC
2140 if (c->stream->loop) {
2141 av_close_input_file(c->fmt_in);
2142 c->fmt_in = NULL;
2143 if (open_input_stream(c, "") < 0)
2144 goto no_loop;
2145 goto redo;
2146 } else {
2147 no_loop:
2148 /* must send trailer now because eof or error */
2149 c->state = HTTPSTATE_SEND_DATA_TRAILER;
1bc1cfdd 2150 }
3b371676
BC
2151 }
2152 } else {
084a8912 2153 int source_index = pkt.stream_index;
3b371676
BC
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;
2158 }
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;
cde25790 2164 for(i=0;i<c->stream->nb_streams;i++) {
3b371676 2165 if (c->switch_feed_streams[i] == pkt.stream_index)
611c5741 2166 if (pkt.flags & PKT_FLAG_KEY)
3b371676
BC
2167 do_switch_stream(c, i);
2168 if (c->switch_feed_streams[i] >= 0)
2169 c->switch_pending = 1;
cde25790 2170 }
3b371676
BC
2171 }
2172 for(i=0;i<c->stream->nb_streams;i++) {
2173 if (c->feed_streams[i] == pkt.stream_index) {
78728064 2174 AVStream *st = c->fmt_in->streams[source_index];
3b371676 2175 pkt.stream_index = i;
180b7026
BC
2176 if (pkt.flags & PKT_FLAG_KEY &&
2177 (st->codec->codec_type == CODEC_TYPE_VIDEO ||
2178 c->stream->nb_streams == 1))
0332f549
BC
2179 c->got_key_frame = 1;
2180 if (!c->stream->send_on_key || c->got_key_frame)
3b371676
BC
2181 goto send_it;
2182 }
2183 }
2184 } else {
2185 AVCodecContext *codec;
dc3a6a36
BC
2186 AVStream *ist, *ost;
2187 send_it:
2188 ist = c->fmt_in->streams[source_index];
3b371676
BC
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) {
3b371676 2193 /* compute send time and duration */
8f56ccca
BC
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);
3b371676
BC
2198 /* find RTP context */
2199 c->packet_stream_index = pkt.stream_index;
2200 ctx = c->rtp_ctx[c->packet_stream_index];
2201 if(!ctx) {
8a0b55ff 2202 av_free_packet(&pkt);
3b371676 2203 break;
8a0b55ff 2204 }
3b371676
BC
2205 codec = ctx->streams[0]->codec;
2206 /* only one stream per RTP connection */
2207 pkt.stream_index = 0;
2208 } else {
2209 ctx = &c->fmt_ctx;
2210 /* Fudge here */
3ab29d8e 2211 codec = ctx->streams[pkt.stream_index]->codec;
3b371676
BC
2212 }
2213
2214 if (c->is_packetized) {
2215 int max_packet_size;
90abbdba 2216 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
3b371676
BC
2217 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
2218 else
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);
2221 } else {
2222 ret = url_open_dyn_buf(&ctx->pb);
2223 }
2224 if (ret < 0) {
2225 /* XXX: potential leak */
2226 return -1;
2227 }
3ab29d8e
BC
2228 ost = ctx->streams[pkt.stream_index];
2229
b0675954 2230 ctx->pb->is_streamed = 1;
3b371676 2231 if (pkt.dts != AV_NOPTS_VALUE)
d80904cc 2232 pkt.dts = av_rescale_q(pkt.dts, ist->time_base, ost->time_base);
3b371676 2233 if (pkt.pts != AV_NOPTS_VALUE)
d80904cc
BC
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);
3766ed72
BC
2236 if (av_write_frame(ctx, &pkt) < 0) {
2237 http_log("Error writing frame to output\n");
3b371676 2238 c->state = HTTPSTATE_SEND_DATA_TRAILER;
3766ed72 2239 }
3b371676
BC
2240
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;
2245
2246 codec->frame_number++;
2247 if (len == 0) {
2248 av_free_packet(&pkt);
2249 goto redo;
f747e6d3 2250 }
85f07f22 2251 }
3b371676 2252 av_free_packet(&pkt);
85f07f22 2253 }
3b371676 2254 }
85f07f22
FB
2255 break;
2256 default:
2257 case HTTPSTATE_SEND_DATA_TRAILER:
2258 /* last packet test ? */
2effd274 2259 if (c->last_packet_sent || c->is_packetized)
85f07f22 2260 return -1;
2effd274 2261 ctx = &c->fmt_ctx;
85f07f22 2262 /* prepare header */
2effd274
FB
2263 if (url_open_dyn_buf(&ctx->pb) < 0) {
2264 /* XXX: potential leak */
2265 return -1;
2266 }
58bd615f 2267 c->fmt_ctx.pb->is_streamed = 1;
2effd274 2268 av_write_trailer(ctx);
899681cd 2269 len = url_close_dyn_buf(ctx->pb, &c->pb_buffer);
2effd274
FB
2270 c->buffer_ptr = c->pb_buffer;
2271 c->buffer_end = c->pb_buffer + len;
2272
85f07f22
FB
2273 c->last_packet_sent = 1;
2274 break;
2275 }
2276 return 0;
2277}
2278
2279/* should convert the format at the same time */
bc351386
FB
2280/* send data starting at c->buffer_ptr to the output connection
2281 (either UDP or TCP connection) */
5eb765ef 2282static int http_send_data(HTTPContext *c)
85f07f22 2283{
e240a0bb 2284 int len, ret;
85f07f22 2285
bc351386
FB
2286 for(;;) {
2287 if (c->buffer_ptr >= c->buffer_end) {
2288 ret = http_prepare_data(c);
2289 if (ret < 0)
2290 return -1;
611c5741 2291 else if (ret != 0)
bc351386
FB
2292 /* state change requested */
2293 break;
2effd274 2294 } else {
bc351386
FB
2295 if (c->is_packetized) {
2296 /* RTP data output */
2297 len = c->buffer_end - c->buffer_ptr;
2298 if (len < 4) {
2299 /* fail safe - should never happen */
2300 fail1:
2301 c->buffer_ptr = c->buffer_end;
2effd274
FB
2302 return 0;
2303 }
bc351386
FB
2304 len = (c->buffer_ptr[0] << 24) |
2305 (c->buffer_ptr[1] << 16) |
2306 (c->buffer_ptr[2] << 8) |
2307 (c->buffer_ptr[3]);
2308 if (len > (c->buffer_end - c->buffer_ptr))
2309 goto fail1;
e240a0bb
FB
2310 if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
2311 /* nothing to send yet: we can wait */
2312 return 0;
2313 }
2314
2315 c->data_count += len;
2316 update_datarate(&c->datarate, c->data_count);
2317 if (c->stream)
2318 c->stream->bytes_served += len;
2319
90abbdba 2320 if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
bc351386 2321 /* RTP packets are sent inside the RTSP TCP connection */
899681cd 2322 ByteIOContext *pb;
bc351386
FB
2323 int interleaved_index, size;
2324 uint8_t header[4];
2325 HTTPContext *rtsp_c;
115329f1 2326
bc351386
FB
2327 rtsp_c = c->rtsp_c;
2328 /* if no RTSP connection left, error */
2329 if (!rtsp_c)
2330 return -1;
2331 /* if already sending something, then wait. */
611c5741 2332 if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
bc351386 2333 break;
899681cd 2334 if (url_open_dyn_buf(&pb) < 0)
bc351386
FB
2335 goto fail1;
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 */
2341 header[0] = '$';
2342 header[1] = interleaved_index;
2343 header[2] = len >> 8;
2344 header[3] = len;
2345 put_buffer(pb, header, 4);
2346 /* write RTP packet data */
2347 c->buffer_ptr += 4;
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;
e240a0bb 2353 c->buffer_ptr += len;
115329f1 2354
e240a0bb 2355 /* send everything we can NOW */
c60202df
AB
2356 len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
2357 rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
611c5741 2358 if (len > 0)
e240a0bb 2359 rtsp_c->packet_buffer_ptr += len;
e240a0bb
FB
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;
2365 break;
611c5741 2366 } else
e240a0bb
FB
2367 /* all data has been sent */
2368 av_freep(&c->packet_buffer);
e240a0bb
FB
2369 } else {
2370 /* send RTP packet directly in UDP */
bc351386 2371 c->buffer_ptr += 4;
115329f1 2372 url_write(c->rtp_handles[c->packet_stream_index],
bc351386 2373 c->buffer_ptr, len);
e240a0bb
FB
2374 c->buffer_ptr += len;
2375 /* here we continue as we can send several packets per 10 ms slot */
bc351386 2376 }
bc351386
FB
2377 } else {
2378 /* TCP data output */
c60202df 2379 len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
bc351386 2380 if (len < 0) {
8da4034f 2381 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
611c5741 2382 ff_neterrno() != FF_NETERROR(EINTR))
bc351386
FB
2383 /* error : close connection */
2384 return -1;
611c5741 2385 else
bc351386 2386 return 0;
611c5741 2387 } else
bc351386 2388 c->buffer_ptr += len;
611c5741 2389
e240a0bb
FB
2390 c->data_count += len;
2391 update_datarate(&c->datarate, c->data_count);
2392 if (c->stream)
2393 c->stream->bytes_served += len;
2394 break;
2effd274 2395 }
85f07f22 2396 }
bc351386 2397 } /* for(;;) */
85f07f22
FB
2398 return 0;
2399}
2400
2401static int http_start_receive_data(HTTPContext *c)
2402{
2403 int fd;
2404
2405 if (c->stream->feed_opened)
2406 return -1;
2407
e322ea48
PG
2408 /* Don't permit writing to this one */
2409 if (c->stream->readonly)
2410 return -1;
2411
85f07f22
FB
2412 /* open feed */
2413 fd = open(c->stream->feed_filename, O_RDWR);
929a9b75
BC
2414 if (fd < 0) {
2415 http_log("Error opening feeder file: %s\n", strerror(errno));
85f07f22 2416 return -1;
929a9b75 2417 }
85f07f22 2418 c->feed_fd = fd;
115329f1 2419
861ec13a
BC
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);
2425 } else {
1f611549
BC
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));
2428 return -1;
2429 }
861ec13a
BC
2430 }
2431
7e24aa0c 2432 c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);
85f07f22
FB
2433 c->stream->feed_size = lseek(fd, 0, SEEK_END);
2434 lseek(fd, 0, SEEK_SET);
2435
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;
fd7bec5e 2440 c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
85f07f22
FB
2441 return 0;
2442}
115329f1 2443
85f07f22
FB
2444static int http_receive_data(HTTPContext *c)
2445{
85f07f22 2446 HTTPContext *c1;
19c8c4ec 2447 int len, loop_run = 0;
85f07f22 2448
19c8c4ec
RB
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);
2453
2454 if (len < 0) {
2455 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
2456 ff_neterrno() != FF_NETERROR(EINTR))
2457 /* error : close connection */
2458 goto fail;
2459 } else if (len == 0) {
2460 /* end of connection : close it */
2461 goto fail;
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
2466 goto fail;
2467 c->buffer_ptr = c->buffer;
2468 break;
2469 } else if (++loop_run > 10) {
2470 /* no chunk header, abort */
2471 goto fail;
2472 } else {
2473 c->buffer_ptr++;
2474 }
2475 }
a6e14edd 2476
19c8c4ec
RB
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);
a6e14edd 2480 if (len < 0) {
8da4034f 2481 if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
611c5741 2482 ff_neterrno() != FF_NETERROR(EINTR))
a6e14edd
PG
2483 /* error : close connection */
2484 goto fail;
611c5741 2485 } else if (len == 0)
a6e14edd
PG
2486 /* end of connection : close it */
2487 goto fail;
611c5741 2488 else {
19c8c4ec 2489 c->chunk_size -= len;
a6e14edd
PG
2490 c->buffer_ptr += len;
2491 c->data_count += len;
5eb765ef 2492 update_datarate(&c->datarate, c->data_count);
a6e14edd
PG
2493 }
2494 }
2495
d445a7e9
PG
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");
2500 goto fail;
2501 }
2502 }
2503
85f07f22 2504 if (c->buffer_ptr >= c->buffer_end) {
f747e6d3 2505 FFStream *feed = c->stream;
85f07f22
FB
2506 /* a packet has been received : write it in the store, except
2507 if header */
2508 if (c->data_count > FFM_PACKET_SIZE) {
115329f1 2509
949b1a13 2510 // printf("writing pos=0x%"PRIx64" size=0x%"PRIx64"\n", feed->feed_write_index, feed->feed_size);
85f07f22
FB
2511 /* XXX: use llseek or url_seek */
2512 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
929a9b75
BC
2513 if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
2514 http_log("Error writing to feed file: %s\n", strerror(errno));
2515 goto fail;
2516 }
115329f1 2517
85f07f22
FB
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;
2522
2523 /* handle wrap around if max file size reached */
6b0bdc75 2524 if (c->stream->feed_max_size && feed->feed_write_index >= c->stream->feed_max_size)
85f07f22
FB
2525 feed->feed_write_index = FFM_PACKET_SIZE;
2526
2527 /* write index */
2779cdad
PK
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));
2530 goto fail;
2531 }
85f07f22
FB
2532
2533 /* wake up any waiting connections */
2534 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
115329f1 2535 if (c1->state == HTTPSTATE_WAIT_FEED &&
611c5741 2536 c1->stream->feed == c->stream->feed)
85f07f22 2537 c1->state = HTTPSTATE_SEND_DATA;
85f07f22 2538 }
f747e6d3
PG
2539 } else {
2540 /* We have a header in our hands that contains useful data */
f2972c8c
BC
2541 AVFormatContext *s = NULL;
2542 ByteIOContext *pb;
bd7cf6ad 2543 AVInputFormat *fmt_in;
f747e6d3
PG
2544 int i;
2545
bd7cf6ad
FB
2546 /* use feed output format name to find corresponding input format */
2547 fmt_in = av_find_input_format(feed->fmt->name);
2548 if (!fmt_in)
2549 goto fail;
2550
697efa36
BC
2551 url_open_buf(&pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
2552 pb->is_streamed = 1;
2553
e6f0deab
BC
2554 if (av_open_input_stream(&s, pb, c->stream->feed_filename, fmt_in, NULL) < 0) {
2555 av_free(pb);
2556 goto fail;
2557 }
f747e6d3
PG
2558
2559 /* Now we have the actual streams */
f2972c8c
BC
2560 if (s->nb_streams != feed->nb_streams) {
2561 av_close_input_stream(s);
86771c68 2562 av_free(pb);
77553ae3
BC
2563 http_log("Feed '%s' stream number does not match registered feed\n",
2564 c->stream->feed_filename);
f747e6d3
PG
2565 goto fail;
2566 }
f2972c8c 2567
cb51aef1
BC
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)
2575 goto fail;
2576 memcpy(fst->codec->extradata, st->codec->extradata,
2577 fst->codec->extradata_size);
2578 }
2579 }
f2972c8c
BC
2580
2581 av_close_input_stream(s);
86771c68 2582 av_free(pb);
85f07f22
FB
2583 }
2584 c->buffer_ptr = c->buffer;
2585 }
2586
85f07f22
FB
2587 return 0;
2588 fail:
2589 c->stream->feed_opened = 0;
2590 close(c->feed_fd);
c1593d0e
BC
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;
2596 }
85f07f22
FB
2597 return -1;
2598}
2599
2effd274
FB
2600/********************************************************************/
2601/* RTSP handling */
2602
2603static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
2604{
2605 const char *str;
2606 time_t ti;
2607 char *p;
2608 char buf2[32];
2609
2610 switch(error_number) {
7e665cd3
LA
2611 case RTSP_STATUS_OK:
2612 str = "OK";
2613 break;
2614 case RTSP_STATUS_METHOD:
2615 str = "Method Not Allowed";
2616 break;
2617 case RTSP_STATUS_BANDWIDTH:
2618 str = "Not Enough Bandwidth";
2619 break;
2620 case RTSP_STATUS_SESSION:
2621 str = "Session Not Found";
2622 break;
2623 case RTSP_STATUS_STATE:
2624 str = "Method Not Valid in This State";
2625 break;
2626 case RTSP_STATUS_AGGREGATE:
2627 str = "Aggregate operation not allowed";
2628 break;
2629 case RTSP_STATUS_ONLY_AGGREGATE:
2630 str = "Only aggregate operation allowed";
2631 break;
2632 case RTSP_STATUS_TRANSPORT:
2633 str = "Unsupported transport";
2634 break;
2635 case RTSP_STATUS_INTERNAL:
2636 str = "Internal Server Error";
2637 break;
2638 case RTSP_STATUS_SERVICE:
2639 str = "Service Unavailable";
2640 break;
2641 case RTSP_STATUS_VERSION:
2642 str = "RTSP Version not supported";
2643 break;
2effd274
FB
2644 default:
2645 str = "Unknown Error";
2646 break;
2647 }
115329f1 2648
2effd274
FB
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);
2651
2652 /* output GMT time */
2653 ti = time(NULL);
2654 p = ctime(&ti);
2655 strcpy(buf2, p);
2656 p = buf2 + strlen(p) - 1;
2657 if (*p == '\n')
2658 *p = '\0';
2659 url_fprintf(c->pb, "Date: %s GMT\r\n", buf2);
2660}
2661
2662static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
2663{
2664 rtsp_reply_header(c, error_number);
2665 url_fprintf(c->pb, "\r\n");
2666}
2667
2668static int rtsp_parse_request(HTTPContext *c)
2669{
2670 const char *p, *p1, *p2;
2671 char cmd[32];
2672 char url[1024];
2673 char protocol[32];
2674 char line[1024];
2effd274 2675 int len;
a9e534d5 2676 RTSPMessageHeader header1, *header = &header1;
115329f1 2677
2effd274
FB
2678 c->buffer_ptr[0] = '\0';
2679 p = c->buffer;
115329f1 2680
2effd274
FB
2681 get_word(cmd, sizeof(cmd), &p);
2682 get_word(url, sizeof(url), &p);
2683 get_word(protocol, sizeof(protocol), &p);
2684
f7d78f36
MR
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));
2effd274 2688
899681cd 2689 if (url_open_dyn_buf(&c->pb) < 0) {
2effd274
FB
2690 /* XXX: cannot do more */
2691 c->pb = NULL; /* safety */
2692 return -1;
2693 }
2694
2695 /* check version name */
2696 if (strcmp(protocol, "RTSP/1.0") != 0) {
2697 rtsp_reply_error(c, RTSP_STATUS_VERSION);
2698 goto the_end;
2699 }
2700
2701 /* parse each header line */
d541a7d2 2702 memset(header, 0, sizeof(*header));
2effd274
FB
2703 /* skip to next line */
2704 while (*p != '\n' && *p != '\0')
2705 p++;
2706 if (*p == '\n')
2707 p++;
2708 while (*p != '\0') {
2709 p1 = strchr(p, '\n');
2710 if (!p1)
2711 break;
2712 p2 = p1;
2713 if (p2 > p && p2[-1] == '\r')
2714 p2--;
2715 /* skip empty line */
2716 if (p2 == p)
2717 break;
2718 len = p2 - p;
2719 if (len > sizeof(line) - 1)
2720 len = sizeof(line) - 1;
2721 memcpy(line, p, len);
2722 line[len] = '\0';
3307e6ea 2723 ff_rtsp_parse_line(header, line);
2effd274
FB
2724 p = p1 + 1;
2725 }
2726
2727 /* handle sequence number */
2728 c->seq = header->seq;
2729
611c5741 2730 if (!strcmp(cmd, "DESCRIBE"))
2effd274 2731 rtsp_cmd_describe(c, url);
611c5741 2732 else if (!strcmp(cmd, "OPTIONS"))
0df65975 2733 rtsp_cmd_options(c, url);
611c5741 2734 else if (!strcmp(cmd, "SETUP"))
2effd274 2735 rtsp_cmd_setup(c, url, header);
611c5741 2736 else if (!strcmp(cmd, "PLAY"))
2effd274 2737 rtsp_cmd_play(c, url, header);
611c5741 2738 else if (!strcmp(cmd, "PAUSE"))
2effd274 2739 rtsp_cmd_pause(c, url, header);
611c5741 2740 else if (!strcmp(cmd, "TEARDOWN"))
2effd274 2741 rtsp_cmd_teardown(c, url, header);
611c5741 2742 else
2effd274 2743 rtsp_reply_error(c, RTSP_STATUS_METHOD);
611c5741 2744
2effd274
FB
2745 the_end:
2746 len = url_close_dyn_buf(c->pb, &c->pb_buffer);
2747 c->pb = NULL; /* safety */
2748 if (len < 0) {
2749 /* XXX: cannot do more */
2750 return -1;
2751 }
2752 c->buffer_ptr = c->pb_buffer;
2753 c->buffer_end = c->pb_buffer + len;
2754 c->state = RTSPSTATE_SEND_REPLY;
2755 return 0;
2756}
2757
115329f1 2758static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer,
829ac53d 2759 struct in_addr my_ip)
2effd274 2760{
dd723472
LA
2761 AVFormatContext *avc;
2762 AVStream avs[MAX_STREAMS];
2763 int i;
115329f1 2764
8e2fd8e1 2765 avc = avformat_alloc_context();
dd723472 2766 if (avc == NULL) {
2effd274 2767 return -1;
dd723472 2768 }
5ee999b8
AJ
2769 av_metadata_set(&avc->metadata, "title",
2770 stream->title[0] ? stream->title : "No Title");
dd723472
LA
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);
2776 }
115329f1 2777
2effd274 2778 for(i = 0; i < stream->nb_streams; i++) {
dd723472
LA
2779 avc->streams[i] = &avs[i];
2780 avc->streams[i]->codec = stream->streams[i]->codec;
2effd274 2781 }
dd723472
LA
2782 *pbuffer = av_mallocz(2048);
2783 avf_sdp_create(&avc, 1, *pbuffer, 2048);
2784 av_free(avc);
2785
2786 return strlen(*pbuffer);
2effd274
FB
2787}
2788
0df65975
AR
2789static void rtsp_cmd_options(HTTPContext *c, const char *url)
2790{
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");
2796}
2797
2effd274
FB
2798static void rtsp_cmd_describe(HTTPContext *c, const char *url)
2799{
2800 FFStream *stream;
2801 char path1[1024];
2802 const char *path;
0c1a9eda 2803 uint8_t *content;
829ac53d
FB
2804 int content_length, len;
2805 struct sockaddr_in my_addr;
115329f1 2806
2effd274 2807 /* find which url is asked */
c5c6e67c 2808 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2effd274
FB
2809 path = path1;
2810 if (*path == '/')
2811 path++;
2812
2813 for(stream = first_stream; stream != NULL; stream = stream->next) {
25e3e53d
LA
2814 if (!stream->is_feed &&
2815 stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
2effd274
FB
2816 !strcmp(path, stream->filename)) {
2817 goto found;
2818 }
2819 }
2820 /* no stream found */
2821 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2822 return;
2823
2824 found:
2825 /* prepare the media description in sdp format */
829ac53d
FB
2826
2827 /* get the host IP */
2828 len = sizeof(my_addr);
2829 getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
829ac53d 2830 content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);
2effd274
FB
2831 if (content_length < 0) {
2832 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2833 return;
2834 }
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);
2840}
2841
2842static HTTPContext *find_rtp_session(const char *session_id)
2843{
2844 HTTPContext *c;
2845
2846 if (session_id[0] == '\0')
2847 return NULL;
2848
2849 for(c = first_http_ctx; c != NULL; c = c->next) {
2850 if (!strcmp(c->session_id, session_id))
2851 return c;
2852 }
2853 return NULL;
2854}
2855
a9e534d5 2856static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
2effd274
FB
2857{
2858 RTSPTransportField *th;
2859 int i;
2860
2861 for(i=0;i<h->nb_transports;i++) {
2862 th = &h->transports[i];
90abbdba 2863 if (th->lower_transport == lower_transport)
2effd274
FB
2864 return th;
2865 }
2866 return NULL;
2867}
2868
115329f1 2869static void rtsp_cmd_setup(HTTPContext *c, const char *url,
a9e534d5 2870 RTSPMessageHeader *h)
2effd274
FB
2871{
2872 FFStream *stream;
2873 int stream_index, port;
2874 char buf[1024];
2875 char path1[1024];
2876 const char *path;
2877 HTTPContext *rtp_c;
2878 RTSPTransportField *th;
2879 struct sockaddr_in dest_addr;
2880 RTSPActionServerSetup setup;
115329f1 2881
2effd274 2882 /* find which url is asked */
c5c6e67c 2883 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2effd274
FB
2884 path = path1;
2885 if (*path == '/')
2886 path++;
2887
2888 /* now check each stream */
2889 for(stream = first_stream; stream != NULL; stream = stream->next) {
25e3e53d
LA
2890 if (!stream->is_feed &&
2891 stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
2effd274
FB
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);
2896 return;
2897 }
2898 stream_index = 0;
2899 goto found;
2900 }
115329f1 2901
2effd274
FB
2902 for(stream_index = 0; stream_index < stream->nb_streams;
2903 stream_index++) {
115329f1 2904 snprintf(buf, sizeof(buf), "%s/streamid=%d",
2effd274
FB
2905 stream->filename, stream_index);
2906 if (!strcmp(path, buf))
2907 goto found;
2908 }
2909 }
2910 }
2911 /* no stream found */
2912 rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
2913 return;
2914 found:
2915
2916 /* generate session id if needed */
611c5741 2917 if (h->session_id[0] == '\0')
1df93ae9 2918 snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
042819c5 2919 av_lfg_get(&random_state), av_lfg_get(&random_state));
2effd274
FB
2920
2921 /* find rtp session, and create it if none found */
2922 rtp_c = find_rtp_session(h->session_id);
2923 if (!rtp_c) {
bc351386 2924 /* always prefer UDP */
90abbdba 2925 th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
bc351386 2926 if (!th) {
90abbdba 2927 th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
bc351386
FB
2928 if (!th) {
2929 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2930 return;
2931 }
2932 }
2933
2934 rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
90abbdba 2935 th->lower_transport);
2effd274
FB
2936 if (!rtp_c) {
2937 rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
2938 return;
2939 }
2940
2941 /* open input stream */
2942 if (open_input_stream(rtp_c, "") < 0) {
2943 rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
2944 return;
2945 }
2effd274 2946 }
115329f1 2947
2effd274
FB
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);
2952 return;
2953 }
115329f1 2954
2effd274
FB
2955 /* test if stream is already set up */
2956 if (rtp_c->rtp_ctx[stream_index]) {
2957 rtsp_reply_error(c, RTSP_STATUS_STATE);
2958 return;
2959 }
2960
2961 /* check transport */
2962 th = find_transport(h, rtp_c->rtp_protocol);
90abbdba 2963 if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
2effd274
FB
2964 th->client_port_min <= 0)) {
2965 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2966 return;
2967 }
2968
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);
115329f1 2973
2effd274 2974 /* setup stream */
bc351386 2975 if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
2effd274
FB
2976 rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
2977 return;
2978 }
2979
2980 /* now everything is OK, so we can send the connection parameters */
2981 rtsp_reply_header(c, RTSP_STATUS_OK);
2982 /* session ID */
2983 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
2984
2985 switch(rtp_c->rtp_protocol) {
90abbdba 2986 case RTSP_LOWER_TRANSPORT_UDP:
2effd274
FB
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,
2991 port, port + 1);
2992 break;
90abbdba 2993 case RTSP_LOWER_TRANSPORT_TCP:
2effd274
FB
2994 url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
2995 stream_index * 2, stream_index * 2 + 1);
2996 break;
2997 default:
2998 break;
2999 }
611c5741 3000 if (setup.transport_option[0] != '\0')
2effd274 3001 url_fprintf(c->pb, ";%s", setup.transport_option);
2effd274 3002 url_fprintf(c->pb, "\r\n");
115329f1 3003
2effd274
FB
3004
3005 url_fprintf(c->pb, "\r\n");
3006}
3007
3008
3009/* find an rtp connection by using the session ID. Check consistency
3010 with filename */
115329f1 3011static HTTPContext *find_rtp_session_with_url(const char *url,
2effd274
FB
3012 const char *session_id)
3013{
3014 HTTPContext *rtp_c;
3015 char path1[1024];
3016 const char *path;
94d9ad5f
GF
3017 char buf[1024];
3018 int s;
2effd274
FB
3019
3020 rtp_c = find_rtp_session(session_id);
3021 if (!rtp_c)
3022 return NULL;
3023
3024 /* find which url is asked */
c5c6e67c 3025 ff_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
2effd274
FB
3026 path = path1;
3027 if (*path == '/')
3028 path++;
94d9ad5f
GF
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?
3035 return rtp_c;
3036 }
3037 }
3038 return NULL;
2effd274
FB
3039}
3040
a9e534d5 3041static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
2effd274
FB
3042{
3043 HTTPContext *rtp_c;
3044
3045 rtp_c = find_rtp_session_with_url(url, h->session_id);
3046 if (!rtp_c) {
3047 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3048 return;
3049 }
115329f1 3050
2effd274
FB
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);
3055 return;
3056 }
3057
3058 rtp_c->state = HTTPSTATE_SEND_DATA;
115329f1 3059
2effd274
FB
3060 /* now everything is OK, so we can send the connection parameters */
3061 rtsp_reply_header(c, RTSP_STATUS_OK);
3062 /* session ID */
3063 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3064 url_fprintf(c->pb, "\r\n");
3065}
3066
a9e534d5 3067static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPMessageHeader *h)
2effd274
FB
3068{
3069 HTTPContext *rtp_c;
3070
3071 rtp_c = find_rtp_session_with_url(url, h->session_id);
3072 if (!rtp_c) {
3073 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3074 return;
3075 }
115329f1 3076
2effd274
FB
3077 if (rtp_c->state != HTTPSTATE_SEND_DATA &&
3078 rtp_c->state != HTTPSTATE_WAIT_FEED) {
3079 rtsp_reply_error(c, RTSP_STATUS_STATE);
3080 return;
3081 }
115329f1 3082
2effd274 3083 rtp_c->state = HTTPSTATE_READY;
1bc1cfdd 3084 rtp_c->first_pts = AV_NOPTS_VALUE;
2effd274
FB
3085 /* now everything is OK, so we can send the connection parameters */
3086 rtsp_reply_header(c, RTSP_STATUS_OK);
3087 /* session ID */
3088 url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id);
3089 url_fprintf(c->pb, "\r\n");
3090}
3091
a9e534d5 3092static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPMessageHeader *h)
2effd274
FB
3093{
3094 HTTPContext *rtp_c;
b0b2faa7 3095 char session_id[32];
2effd274
FB
3096
3097 rtp_c = find_rtp_session_with_url(url, h->session_id);
3098 if (!rtp_c) {
3099 rtsp_reply_error(c, RTSP_STATUS_SESSION);
3100 return;
3101 }
115329f1 3102
f7d78f36 3103 av_strlcpy(session_id, rtp_c->session_id, sizeof(session_id));
b0b2faa7 3104
2effd274
FB
3105 /* abort the session */
3106 close_connection(rtp_c);
3107
2effd274
FB
3108 /* now everything is OK, so we can send the connection parameters */
3109 rtsp_reply_header(c, RTSP_STATUS_OK);
3110 /* session ID */
b0b2faa7 3111 url_fprintf(c->pb, "Session: %s\r\n", session_id);
2effd274
FB
3112 url_fprintf(c->pb, "\r\n");
3113}
3114
3115
3116/********************************************************************/
3117/* RTP handling */
3118
115329f1 3119static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
bc351386 3120 FFStream *stream, const char *session_id,
90abbdba 3121 enum RTSPLowerTransport rtp_protocol)
2effd274
FB
3122{
3123 HTTPContext *c = NULL;
bc351386 3124 const char *proto_str;
115329f1 3125
2effd274
FB
3126 /* XXX: should output a warning page when coming
3127 close to the connection limit */
3128 if (nb_connections >= nb_max_connections)
3129 goto fail;
115329f1 3130
2effd274
FB
3131 /* add a new connection */
3132 c = av_mallocz(sizeof(HTTPContext));
3133 if (!c)
3134 goto fail;
115329f1 3135
2effd274
FB
3136 c->fd = -1;
3137 c->poll_entry = NULL;
6edd6884 3138 c->from_addr = *from_addr;
2effd274
FB
3139 c->buffer_size = IOBUFFER_INIT_SIZE;
3140 c->buffer = av_malloc(c->buffer_size);
3141 if (!c->buffer)
3142 goto fail;
3143 nb_connections++;
3144 c->stream = stream;
f7d78f36 3145 av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
2effd274
FB
3146 c->state = HTTPSTATE_READY;
3147 c->is_packetized = 1;
bc351386
FB
3148 c->rtp_protocol = rtp_protocol;
3149
2effd274 3150 /* protocol is shown in statistics */
bc351386 3151 switch(c->rtp_protocol) {
90abbdba 3152 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
bc351386
FB
3153 proto_str = "MCAST";
3154 break;
90abbdba 3155 case RTSP_LOWER_TRANSPORT_UDP:
bc351386
FB
3156 proto_str = "UDP";
3157 break;
90abbdba 3158 case RTSP_LOWER_TRANSPORT_TCP:
bc351386
FB
3159 proto_str = "TCP";
3160 break;
3161 default:
3162 proto_str = "???";
3163 break;
3164 }
f7d78f36
MR
3165 av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
3166 av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
2effd274 3167
6edd6884
FB
3168 current_bandwidth += stream->bandwidth;
3169
2effd274
FB
3170 c->next = first_http_ctx;
3171 first_http_ctx = c;
3172 return c;
115329f1 3173
2effd274
FB
3174 fail:
3175 if (c) {
3176 av_free(c->buffer);
3177 av_free(c);
3178 }
3179 return NULL;
3180}
3181
3182/* add a new RTP stream in an RTP connection (used in RTSP SETUP
bc351386 3183 command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
2effd274 3184 used. */
115329f1 3185static int rtp_new_av_stream(HTTPContext *c,
bc351386
FB
3186 int stream_index, struct sockaddr_in *dest_addr,
3187 HTTPContext *rtsp_c)
2effd274
FB
3188{
3189 AVFormatContext *ctx;
3190 AVStream *st;
3191 char *ipaddr;
75480e86 3192 URLContext *h = NULL;
0c1a9eda 3193 uint8_t *dummy_buf;
bc351386 3194 int max_packet_size;
115329f1 3195
2effd274 3196 /* now we can open the relevant output stream */
8e2fd8e1 3197 ctx = avformat_alloc_context();
2effd274
FB
3198 if (!ctx)
3199 return -1;
0f52ef1a 3200 ctx->oformat = av_guess_format("rtp", NULL, NULL);
2effd274
FB
3201
3202 st = av_mallocz(sizeof(AVStream));
3203 if (!st)
3204 goto fail;
8d931070 3205 st->codec= avcodec_alloc_context();
2effd274
FB
3206 ctx->nb_streams = 1;
3207 ctx->streams[0] = st;
3208
115329f1 3209 if (!c->stream->feed ||
611c5741 3210 c->stream->feed == c->stream)
2effd274 3211 memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
611c5741 3212 else
115329f1 3213 memcpy(st,
2effd274
FB
3214 c->stream->feed->streams[c->stream->feed_streams[stream_index]],
3215 sizeof(AVStream));
57dbe08b 3216 st->priv_data = NULL;
115329f1 3217
bc351386
FB
3218 /* build destination RTP address */
3219 ipaddr = inet_ntoa(dest_addr->sin_addr);
3220
3221 switch(c->rtp_protocol) {
90abbdba
RB
3222 case RTSP_LOWER_TRANSPORT_UDP:
3223 case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
bc351386 3224 /* RTP/UDP case */
115329f1 3225
6edd6884
FB
3226 /* XXX: also pass as parameter to function ? */
3227 if (c->stream->is_multicast) {
3228 int ttl;
3229 ttl = c->stream->multicast_ttl;
3230 if (!ttl)
3231 ttl = 16;
3232 snprintf(ctx->filename, sizeof(ctx->filename),
115329f1 3233 "rtp://%s:%d?multicast=1&ttl=%d",
6edd6884
FB
3234 ipaddr, ntohs(dest_addr->sin_port), ttl);
3235 } else {
3236 snprintf(ctx->filename, sizeof(ctx->filename),
3237 "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
3238 }
2effd274
FB
3239
3240 if (url_open(&h, ctx->filename, URL_WRONLY) < 0)
3241 goto fail;
3242 c->rtp_handles[stream_index] = h;
bc351386
FB
3243 max_packet_size = url_get_max_packet_size(h);
3244 break;
90abbdba 3245 case RTSP_LOWER_TRANSPORT_TCP:
bc351386
FB
3246 /* RTP/TCP case */
3247 c->rtsp_c = rtsp_c;
3248 max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
3249 break;
3250 default:
2effd274
FB
3251 goto fail;
3252 }
3253
e21ac209 3254 http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
115329f1 3255 ipaddr, ntohs(dest_addr->sin_port),
bc351386 3256 c->stream->filename, stream_index, c->protocol);
6edd6884 3257
2effd274 3258 /* normally, no packets should be output here, but the packet size may be checked */
bc351386 3259 if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) {
2effd274
FB
3260 /* XXX: close stream */
3261 goto fail;
3262 }
3c27199b 3263 av_set_parameters(ctx, NULL);
2effd274
FB
3264 if (av_write_header(ctx) < 0) {
3265 fail:
3266 if (h)
3267 url_close(h);
3268 av_free(ctx);
3269 return -1;
3270 }
899681cd 3271 url_close_dyn_buf(ctx->pb, &dummy_buf);
2effd274 3272 av_free(dummy_buf);
115329f1 3273
2effd274
FB
3274 c->rtp_ctx[stream_index] = ctx;
3275 return 0;
3276}
3277
3278/********************************************************************/
3279/* ffserver initialization */
3280
b29f97d1 3281static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec)
2effd274
FB
3282{
3283 AVStream *fst;
3284
3285 fst = av_mallocz(sizeof(AVStream));
3286 if (!fst)
3287 return NULL;
8d931070 3288 fst->codec= avcodec_alloc_context();
2effd274 3289 fst->priv_data = av_mallocz(sizeof(FeedData));
01f4895c 3290 memcpy(fst->codec, codec, sizeof(AVCodecContext));
d445a7e9 3291 fst->index = stream->nb_streams;
7c054ea7 3292 av_set_pts_info(fst, 33, 1, 90000);
2effd274
FB
3293 stream->streams[stream->nb_streams++] = fst;
3294 return fst;
3295}
3296
85f07f22 3297/* return the stream number in the feed */
b29f97d1 3298static int add_av_stream(FFStream *feed, AVStream *st)
85f07f22
FB
3299{
3300 AVStream *fst;
3301 AVCodecContext *av, *av1;
3302 int i;
3303
01f4895c 3304 av = st->codec;
85f07f22
FB
3305 for(i=0;i<feed->nb_streams;i++) {
3306 st = feed->streams[i];
01f4895c 3307 av1 = st->codec;
f747e6d3
PG
3308 if (av1->codec_id == av->codec_id &&
3309 av1->codec_type == av->codec_type &&
85f07f22
FB
3310 av1->bit_rate == av->bit_rate) {
3311
3312 switch(av->codec_type) {
3313 case CODEC_TYPE_AUDIO:
3314 if (av1->channels == av->channels &&
3315 av1->sample_rate == av->sample_rate)
3316 goto found;
3317 break;
3318 case CODEC_TYPE_VIDEO:
3319 if (av1->width == av->width &&
3320 av1->height == av->height &&
c0df9d75
MN
3321 av1->time_base.den == av->time_base.den &&
3322 av1->time_base.num == av->time_base.num &&
85f07f22
FB
3323 av1->gop_size == av->gop_size)
3324 goto found;
3325 break;
f747e6d3 3326 default:
0f4e8165 3327 abort();
85f07f22
FB
3328 }
3329 }
3330 }
115329f1 3331
2effd274 3332 fst = add_av_stream1(feed, av);
85f07f22
FB
3333 if (!fst)
3334 return -1;
85f07f22
FB
3335 return feed->nb_streams - 1;
3336 found:
3337 return i;
3338}
3339
b29f97d1 3340static void remove_stream(FFStream *stream)
2effd274
FB
3341{
3342 FFStream **ps;
3343 ps = &first_stream;
3344 while (*ps != NULL) {
611c5741 3345 if (*ps == stream)
2effd274 3346 *ps = (*ps)->next;
611c5741 3347 else
2effd274 3348 ps = &(*ps)->next;
2effd274
FB
3349 }
3350}
3351
0fa45e19 3352/* specific mpeg4 handling : we extract the raw parameters */
b29f97d1 3353static void extract_mpeg4_header(AVFormatContext *infile)
0fa45e19
FB
3354{
3355 int mpeg4_count, i, size;
3356 AVPacket pkt;
3357 AVStream *st;
0c1a9eda 3358 const uint8_t *p;
0fa45e19
FB
3359
3360 mpeg4_count = 0;
3361 for(i=0;i<infile->nb_streams;i++) {
3362 st = infile->streams[i];
01f4895c
MN
3363 if (st->codec->codec_id == CODEC_ID_MPEG4 &&
3364 st->codec->extradata_size == 0) {
0fa45e19
FB