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