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