* If a stream gets stuck in WAIT_FEED, then disconnecting the other end
[libav.git] / ffserver.c
1 /*
2 * Multiple format streaming server
3 * Copyright (c) 2000,2001 Gerard Lantau.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19 #include <stdarg.h>
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <netinet/in.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/ioctl.h>
27 #include <sys/poll.h>
28 #include <errno.h>
29 #include <sys/time.h>
30 #include <time.h>
31 #include <getopt.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <arpa/inet.h>
35 #include <netdb.h>
36 #include <ctype.h>
37 #include <signal.h>
38 #include <assert.h>
39
40 #include "bswap.h" // needed for the bitstream writer in common.h which is included in avformat.h
41 #include "avformat.h"
42
43 /* maximum number of simultaneous HTTP connections */
44 #define HTTP_MAX_CONNECTIONS 2000
45
46 enum HTTPState {
47 HTTPSTATE_WAIT_REQUEST,
48 HTTPSTATE_SEND_HEADER,
49 HTTPSTATE_SEND_DATA_HEADER,
50 HTTPSTATE_SEND_DATA,
51 HTTPSTATE_SEND_DATA_TRAILER,
52 HTTPSTATE_RECEIVE_DATA,
53 HTTPSTATE_WAIT_FEED,
54 };
55
56 const char *http_state[] = {
57 "WAIT_REQUEST",
58 "SEND_HEADER",
59 "SEND_DATA_HEADER",
60 "SEND_DATA",
61 "SEND_DATA_TRAILER",
62 "RECEIVE_DATA",
63 "WAIT_FEED",
64 };
65
66 #define IOBUFFER_MAX_SIZE 32768
67 #define PACKET_MAX_SIZE 16384
68
69 /* coef for exponential mean for bitrate estimation in statistics */
70 #define AVG_COEF 0.9
71
72 /* timeouts are in ms */
73 #define REQUEST_TIMEOUT (15 * 1000)
74 #define SYNC_TIMEOUT (10 * 1000)
75
76 /* context associated with one connection */
77 typedef struct HTTPContext {
78 enum HTTPState state;
79 int fd; /* socket file descriptor */
80 struct sockaddr_in from_addr; /* origin */
81 struct pollfd *poll_entry; /* used when polling */
82 long timeout;
83 UINT8 *buffer_ptr, *buffer_end;
84 int http_error;
85 struct HTTPContext *next;
86 int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
87 INT64 data_count;
88 /* feed input */
89 int feed_fd;
90 /* input format handling */
91 AVFormatContext *fmt_in;
92 /* output format handling */
93 struct FFStream *stream;
94 AVFormatContext fmt_ctx;
95 int last_packet_sent; /* true if last data packet was sent */
96 int suppress_log;
97 int bandwidth;
98 char protocol[16];
99 char method[16];
100 char url[128];
101 UINT8 buffer[IOBUFFER_MAX_SIZE];
102 UINT8 pbuffer[PACKET_MAX_SIZE];
103 } HTTPContext;
104
105 /* each generated stream is described here */
106 enum StreamType {
107 STREAM_TYPE_LIVE,
108 STREAM_TYPE_STATUS,
109 };
110
111 /* description of each stream of the ffserver.conf file */
112 typedef struct FFStream {
113 enum StreamType stream_type;
114 char filename[1024]; /* stream filename */
115 struct FFStream *feed;
116 AVFormat *fmt;
117 int nb_streams;
118 int prebuffer; /* Number of millseconds early to start */
119 int send_on_key;
120 AVStream *streams[MAX_STREAMS];
121 int feed_streams[MAX_STREAMS]; /* index of streams in the feed */
122 char feed_filename[1024]; /* file name of the feed storage, or
123 input file name for a stream */
124 struct FFStream *next;
125 /* feed specific */
126 int feed_opened; /* true if someone if writing to feed */
127 int is_feed; /* true if it is a feed */
128 int conns_served;
129 INT64 bytes_served;
130 INT64 feed_max_size; /* maximum storage size */
131 INT64 feed_write_index; /* current write position in feed (it wraps round) */
132 INT64 feed_size; /* current size of feed */
133 struct FFStream *next_feed;
134 } FFStream;
135
136 typedef struct FeedData {
137 long long data_count;
138 float avg_frame_size; /* frame size averraged over last frames with exponential mean */
139 } FeedData;
140
141 struct sockaddr_in my_addr;
142 char logfilename[1024];
143 HTTPContext *first_http_ctx;
144 FFStream *first_feed; /* contains only feeds */
145 FFStream *first_stream; /* contains all streams, including feeds */
146
147 static int handle_http(HTTPContext *c, long cur_time);
148 static int http_parse_request(HTTPContext *c);
149 static int http_send_data(HTTPContext *c);
150 static void compute_stats(HTTPContext *c);
151 static int open_input_stream(HTTPContext *c, const char *info);
152 static int http_start_receive_data(HTTPContext *c);
153 static int http_receive_data(HTTPContext *c);
154
155 int nb_max_connections;
156 int nb_connections;
157
158 int nb_max_bandwidth;
159 int nb_bandwidth;
160
161 static long gettime_ms(void)
162 {
163 struct timeval tv;
164
165 gettimeofday(&tv,NULL);
166 return (long long)tv.tv_sec * 1000 + (tv.tv_usec / 1000);
167 }
168
169 static FILE *logfile = NULL;
170
171 static void http_log(char *fmt, ...)
172 {
173 va_list ap;
174 va_start(ap, fmt);
175
176 if (logfile) {
177 vfprintf(logfile, fmt, ap);
178 fflush(logfile);
179 }
180 va_end(ap);
181 }
182
183 static void log_connection(HTTPContext *c)
184 {
185 char buf1[32], buf2[32], *p;
186 time_t ti;
187
188 if (c->suppress_log)
189 return;
190
191 /* XXX: reentrant function ? */
192 p = inet_ntoa(c->from_addr.sin_addr);
193 strcpy(buf1, p);
194 ti = time(NULL);
195 p = ctime(&ti);
196 strcpy(buf2, p);
197 p = buf2 + strlen(p) - 1;
198 if (*p == '\n')
199 *p = '\0';
200 http_log("%s - - [%s] \"%s %s %s\" %d %lld\n",
201 buf1, buf2, c->method, c->url, c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
202 }
203
204 /* main loop of the http server */
205 static int http_server(struct sockaddr_in my_addr)
206 {
207 int server_fd, tmp, ret;
208 struct sockaddr_in from_addr;
209 struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 1], *poll_entry;
210 HTTPContext *c, **cp;
211 long cur_time;
212
213 server_fd = socket(AF_INET,SOCK_STREAM,0);
214 if (server_fd < 0) {
215 perror ("socket");
216 return -1;
217 }
218
219 tmp = 1;
220 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp));
221
222 if (bind (server_fd, (struct sockaddr *) &my_addr, sizeof (my_addr)) < 0) {
223 perror ("bind");
224 close(server_fd);
225 return -1;
226 }
227
228 if (listen (server_fd, 5) < 0) {
229 perror ("listen");
230 close(server_fd);
231 return -1;
232 }
233
234 http_log("ffserver started.\n");
235
236 fcntl(server_fd, F_SETFL, O_NONBLOCK);
237 first_http_ctx = NULL;
238 nb_connections = 0;
239 first_http_ctx = NULL;
240 for(;;) {
241 poll_entry = poll_table;
242 poll_entry->fd = server_fd;
243 poll_entry->events = POLLIN;
244 poll_entry++;
245
246 /* wait for events on each HTTP handle */
247 c = first_http_ctx;
248 while (c != NULL) {
249 int fd;
250 fd = c->fd;
251 switch(c->state) {
252 case HTTPSTATE_WAIT_REQUEST:
253 c->poll_entry = poll_entry;
254 poll_entry->fd = fd;
255 poll_entry->events = POLLIN;
256 poll_entry++;
257 break;
258 case HTTPSTATE_SEND_HEADER:
259 case HTTPSTATE_SEND_DATA_HEADER:
260 case HTTPSTATE_SEND_DATA:
261 case HTTPSTATE_SEND_DATA_TRAILER:
262 c->poll_entry = poll_entry;
263 poll_entry->fd = fd;
264 poll_entry->events = POLLOUT;
265 poll_entry++;
266 break;
267 case HTTPSTATE_RECEIVE_DATA:
268 c->poll_entry = poll_entry;
269 poll_entry->fd = fd;
270 poll_entry->events = POLLIN;
271 poll_entry++;
272 break;
273 case HTTPSTATE_WAIT_FEED:
274 /* need to catch errors */
275 c->poll_entry = poll_entry;
276 poll_entry->fd = fd;
277 poll_entry->events = POLLIN;/* Maybe this will work */
278 poll_entry++;
279 break;
280 default:
281 c->poll_entry = NULL;
282 break;
283 }
284 c = c->next;
285 }
286
287 /* wait for an event on one connection. We poll at least every
288 second to handle timeouts */
289 do {
290 ret = poll(poll_table, poll_entry - poll_table, 1000);
291 } while (ret == -1);
292
293 cur_time = gettime_ms();
294
295 /* now handle the events */
296
297 cp = &first_http_ctx;
298 while ((*cp) != NULL) {
299 c = *cp;
300 if (handle_http (c, cur_time) < 0) {
301 /* close and free the connection */
302 log_connection(c);
303 close(c->fd);
304 if (c->fmt_in)
305 av_close_input_file(c->fmt_in);
306 *cp = c->next;
307 nb_bandwidth -= c->bandwidth;
308 free(c);
309 nb_connections--;
310 } else {
311 cp = &c->next;
312 }
313 }
314
315 /* new connection request ? */
316 poll_entry = poll_table;
317 if (poll_entry->revents & POLLIN) {
318 int fd, len;
319
320 len = sizeof(from_addr);
321 fd = accept(server_fd, (struct sockaddr *)&from_addr,
322 &len);
323 if (fd >= 0) {
324 fcntl(fd, F_SETFL, O_NONBLOCK);
325 /* XXX: should output a warning page when coming
326 close to the connection limit */
327 if (nb_connections >= nb_max_connections) {
328 close(fd);
329 } else {
330 /* add a new connection */
331 c = av_mallocz(sizeof(HTTPContext));
332 c->next = first_http_ctx;
333 first_http_ctx = c;
334 c->fd = fd;
335 c->poll_entry = NULL;
336 c->from_addr = from_addr;
337 c->state = HTTPSTATE_WAIT_REQUEST;
338 c->buffer_ptr = c->buffer;
339 c->buffer_end = c->buffer + IOBUFFER_MAX_SIZE;
340 c->timeout = cur_time + REQUEST_TIMEOUT;
341 nb_connections++;
342 }
343 }
344 }
345 poll_entry++;
346 }
347 }
348
349 static int handle_http(HTTPContext *c, long cur_time)
350 {
351 int len;
352
353 switch(c->state) {
354 case HTTPSTATE_WAIT_REQUEST:
355 /* timeout ? */
356 if ((c->timeout - cur_time) < 0)
357 return -1;
358 if (c->poll_entry->revents & (POLLERR | POLLHUP))
359 return -1;
360
361 /* no need to read if no events */
362 if (!(c->poll_entry->revents & POLLIN))
363 return 0;
364 /* read the data */
365 len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
366 if (len < 0) {
367 if (errno != EAGAIN && errno != EINTR)
368 return -1;
369 } else if (len == 0) {
370 return -1;
371 } else {
372 /* search for end of request. XXX: not fully correct since garbage could come after the end */
373 UINT8 *ptr;
374 c->buffer_ptr += len;
375 ptr = c->buffer_ptr;
376 if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
377 (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
378 /* request found : parse it and reply */
379 if (http_parse_request(c) < 0)
380 return -1;
381 } else if (ptr >= c->buffer_end) {
382 /* request too long: cannot do anything */
383 return -1;
384 }
385 }
386 break;
387
388 case HTTPSTATE_SEND_HEADER:
389 if (c->poll_entry->revents & (POLLERR | POLLHUP))
390 return -1;
391
392 /* no need to read if no events */
393 if (!(c->poll_entry->revents & POLLOUT))
394 return 0;
395 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
396 if (len < 0) {
397 if (errno != EAGAIN && errno != EINTR) {
398 /* error : close connection */
399 return -1;
400 }
401 } else {
402 c->buffer_ptr += len;
403 c->stream->bytes_served += len;
404 c->data_count += len;
405 if (c->buffer_ptr >= c->buffer_end) {
406 /* if error, exit */
407 if (c->http_error)
408 return -1;
409 /* all the buffer was send : synchronize to the incoming stream */
410 c->state = HTTPSTATE_SEND_DATA_HEADER;
411 c->buffer_ptr = c->buffer_end = c->buffer;
412 }
413 }
414 break;
415
416 case HTTPSTATE_SEND_DATA:
417 case HTTPSTATE_SEND_DATA_HEADER:
418 case HTTPSTATE_SEND_DATA_TRAILER:
419 /* no need to read if no events */
420 if (c->poll_entry->revents & (POLLERR | POLLHUP))
421 return -1;
422
423 if (!(c->poll_entry->revents & POLLOUT))
424 return 0;
425 if (http_send_data(c) < 0)
426 return -1;
427 break;
428 case HTTPSTATE_RECEIVE_DATA:
429 /* no need to read if no events */
430 if (c->poll_entry->revents & (POLLERR | POLLHUP))
431 return -1;
432 if (!(c->poll_entry->revents & POLLIN))
433 return 0;
434 if (http_receive_data(c) < 0)
435 return -1;
436 break;
437 case HTTPSTATE_WAIT_FEED:
438 /* no need to read if no events */
439 if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
440 return -1;
441
442 /* nothing to do, we'll be waken up by incoming feed packets */
443 break;
444 default:
445 return -1;
446 }
447 return 0;
448 }
449
450
451 /* parse http request and prepare header */
452 static int http_parse_request(HTTPContext *c)
453 {
454 char *p;
455 int post;
456 int doing_asx;
457 int doing_ram;
458 char cmd[32];
459 char info[1024], *filename;
460 char url[1024], *q;
461 char protocol[32];
462 char msg[1024];
463 const char *mime_type;
464 FFStream *stream;
465 int i;
466
467 p = c->buffer;
468 q = cmd;
469 while (!isspace(*p) && *p != '\0') {
470 if ((q - cmd) < sizeof(cmd) - 1)
471 *q++ = *p;
472 p++;
473 }
474 *q = '\0';
475
476 strlcpy(c->method, cmd, sizeof(c->method));
477
478 if (!strcmp(cmd, "GET"))
479 post = 0;
480 else if (!strcmp(cmd, "POST"))
481 post = 1;
482 else
483 return -1;
484
485 while (isspace(*p)) p++;
486 q = url;
487 while (!isspace(*p) && *p != '\0') {
488 if ((q - url) < sizeof(url) - 1)
489 *q++ = *p;
490 p++;
491 }
492 *q = '\0';
493
494 strlcpy(c->url, url, sizeof(c->url));
495
496 while (isspace(*p)) p++;
497 q = protocol;
498 while (!isspace(*p) && *p != '\0') {
499 if ((q - protocol) < sizeof(protocol) - 1)
500 *q++ = *p;
501 p++;
502 }
503 *q = '\0';
504 if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
505 return -1;
506
507 strlcpy(c->protocol, protocol, sizeof(c->protocol));
508
509 /* find the filename and the optional info string in the request */
510 p = url;
511 if (*p == '/')
512 p++;
513 filename = p;
514 p = strchr(p, '?');
515 if (p) {
516 strlcpy(info, p, sizeof(info));
517 *p = '\0';
518 } else {
519 info[0] = '\0';
520 }
521
522 if (strlen(filename) > 4 && strcmp(".asx", filename + strlen(filename) - 4) == 0) {
523 doing_asx = 1;
524 filename[strlen(filename)-1] = 'f';
525 } else {
526 doing_asx = 0;
527 }
528
529 if (strlen(filename) > 4 &&
530 (strcmp(".rpm", filename + strlen(filename) - 4) == 0 ||
531 strcmp(".ram", filename + strlen(filename) - 4) == 0)) {
532 doing_ram = 1;
533 strcpy(filename + strlen(filename)-2, "m");
534 } else {
535 doing_ram = 0;
536 }
537
538 stream = first_stream;
539 while (stream != NULL) {
540 if (!strcmp(stream->filename, filename))
541 break;
542 stream = stream->next;
543 }
544 if (stream == NULL) {
545 sprintf(msg, "File '%s' not found", url);
546 goto send_error;
547 }
548
549 if (post == 0 && stream->stream_type == STREAM_TYPE_LIVE) {
550 /* See if we meet the bandwidth requirements */
551 for(i=0;i<stream->nb_streams;i++) {
552 AVStream *st = stream->streams[i];
553 switch(st->codec.codec_type) {
554 case CODEC_TYPE_AUDIO:
555 c->bandwidth += st->codec.bit_rate;
556 break;
557 case CODEC_TYPE_VIDEO:
558 c->bandwidth += st->codec.bit_rate;
559 break;
560 default:
561 abort();
562 }
563 }
564 }
565
566 c->bandwidth /= 1000;
567 nb_bandwidth += c->bandwidth;
568
569 if (post == 0 && nb_max_bandwidth < nb_bandwidth) {
570 c->http_error = 200;
571 q = c->buffer;
572 q += sprintf(q, "HTTP/1.0 200 Server too busy\r\n");
573 q += sprintf(q, "Content-type: text/html\r\n");
574 q += sprintf(q, "\r\n");
575 q += sprintf(q, "<html><head><title>Too busy</title></head><body>\r\n");
576 q += sprintf(q, "The server is too busy to serve your request at this time.<p>\r\n");
577 q += sprintf(q, "The bandwidth being served (including your stream) is %dkbit/sec, and this exceeds the limit of %dkbit/sec\r\n",
578 nb_bandwidth, nb_max_bandwidth);
579 q += sprintf(q, "</body></html>\r\n");
580
581 /* prepare output buffer */
582 c->buffer_ptr = c->buffer;
583 c->buffer_end = q;
584 c->state = HTTPSTATE_SEND_HEADER;
585 return 0;
586 }
587
588 if (doing_asx || doing_ram) {
589 char *hostinfo = 0;
590
591 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
592 if (strncasecmp(p, "Host:", 5) == 0) {
593 hostinfo = p + 5;
594 break;
595 }
596 p = strchr(p, '\n');
597 if (!p)
598 break;
599
600 p++;
601 }
602
603 if (hostinfo) {
604 char *eoh;
605 char hostbuf[260];
606
607 while (isspace(*hostinfo))
608 hostinfo++;
609
610 eoh = strchr(hostinfo, '\n');
611 if (eoh) {
612 if (eoh[-1] == '\r')
613 eoh--;
614
615 if (eoh - hostinfo < sizeof(hostbuf) - 1) {
616 memcpy(hostbuf, hostinfo, eoh - hostinfo);
617 hostbuf[eoh - hostinfo] = 0;
618
619 c->http_error = 200;
620 q = c->buffer;
621 if (doing_asx) {
622 q += sprintf(q, "HTTP/1.0 200 ASX Follows\r\n");
623 q += sprintf(q, "Content-type: video/x-ms-asf\r\n");
624 q += sprintf(q, "\r\n");
625 q += sprintf(q, "<ASX Version=\"3\">\r\n");
626 q += sprintf(q, "<!-- Autogenerated by ffserver -->\r\n");
627 q += sprintf(q, "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n",
628 hostbuf, filename, info);
629 q += sprintf(q, "</ASX>\r\n");
630 } else if (doing_ram) {
631 q += sprintf(q, "HTTP/1.0 200 RAM Follows\r\n");
632 q += sprintf(q, "Content-type: audio/x-pn-realaudio\r\n");
633 q += sprintf(q, "\r\n");
634 q += sprintf(q, "# Autogenerated by ffserver\r\n");
635 q += sprintf(q, "http://%s/%s%s\r\n",
636 hostbuf, filename, info);
637 } else
638 abort();
639
640 /* prepare output buffer */
641 c->buffer_ptr = c->buffer;
642 c->buffer_end = q;
643 c->state = HTTPSTATE_SEND_HEADER;
644 return 0;
645 }
646 }
647 }
648
649 sprintf(msg, "ASX/RAM file not handled");
650 goto send_error;
651 }
652
653 c->stream = stream;
654 stream->conns_served++;
655
656 /* XXX: add there authenticate and IP match */
657
658 if (post) {
659 /* if post, it means a feed is being sent */
660 if (!stream->is_feed) {
661 /* However it might be a status report from WMP! Lets log the data
662 * as it might come in handy one day
663 */
664 char *logline = 0;
665
666 for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
667 if (strncasecmp(p, "Pragma: log-line=", 17) == 0) {
668 logline = p;
669 break;
670 }
671 p = strchr(p, '\n');
672 if (!p)
673 break;
674
675 p++;
676 }
677
678 if (logline) {
679 char *eol = strchr(logline, '\n');
680
681 logline += 17;
682
683 if (eol) {
684 if (eol[-1] == '\r')
685 eol--;
686 http_log("%.*s\n", eol - logline, logline);
687 c->suppress_log = 1;
688 }
689 }
690
691 sprintf(msg, "POST command not handled");
692 goto send_error;
693 }
694 if (http_start_receive_data(c) < 0) {
695 sprintf(msg, "could not open feed");
696 goto send_error;
697 }
698 c->http_error = 0;
699 c->state = HTTPSTATE_RECEIVE_DATA;
700 return 0;
701 }
702
703 if (c->stream->stream_type == STREAM_TYPE_STATUS)
704 goto send_stats;
705
706 /* open input stream */
707 if (open_input_stream(c, info) < 0) {
708 sprintf(msg, "Input stream corresponding to '%s' not found", url);
709 goto send_error;
710 }
711
712 /* prepare http header */
713 q = c->buffer;
714 q += sprintf(q, "HTTP/1.0 200 OK\r\n");
715 mime_type = c->stream->fmt->mime_type;
716 if (!mime_type)
717 mime_type = "application/x-octet_stream";
718 q += sprintf(q, "Pragma: no-cache\r\n");
719
720 /* for asf, we need extra headers */
721 if (!strcmp(c->stream->fmt->name,"asf")) {
722 q += sprintf(q, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=1234\r\nPragma: features=\"broadcast\"\r\n");
723 /* mime_type = "application/octet-stream"; */
724 /* video/x-ms-asf seems better -- netscape doesn't crash any more! */
725 mime_type = "video/x-ms-asf";
726 }
727 q += sprintf(q, "Content-Type: %s\r\n", mime_type);
728 q += sprintf(q, "\r\n");
729
730 /* prepare output buffer */
731 c->http_error = 0;
732 c->buffer_ptr = c->buffer;
733 c->buffer_end = q;
734 c->state = HTTPSTATE_SEND_HEADER;
735 return 0;
736 send_error:
737 c->http_error = 404;
738 q = c->buffer;
739 q += sprintf(q, "HTTP/1.0 404 Not Found\r\n");
740 q += sprintf(q, "Content-type: %s\r\n", "text/html");
741 q += sprintf(q, "\r\n");
742 q += sprintf(q, "<HTML>\n");
743 q += sprintf(q, "<HEAD><TITLE>404 Not Found</TITLE></HEAD>\n");
744 q += sprintf(q, "<BODY>%s</BODY>\n", msg);
745 q += sprintf(q, "</HTML>\n");
746
747 /* prepare output buffer */
748 c->buffer_ptr = c->buffer;
749 c->buffer_end = q;
750 c->state = HTTPSTATE_SEND_HEADER;
751 return 0;
752 send_stats:
753 compute_stats(c);
754 c->http_error = 200; /* horrible : we use this value to avoid
755 going to the send data state */
756 c->state = HTTPSTATE_SEND_HEADER;
757 return 0;
758 }
759
760 static void compute_stats(HTTPContext *c)
761 {
762 HTTPContext *c1;
763 FFStream *stream;
764 char *q, *p;
765 time_t ti;
766 int i;
767
768 q = c->buffer;
769 q += sprintf(q, "HTTP/1.0 200 OK\r\n");
770 q += sprintf(q, "Content-type: %s\r\n", "text/html");
771 q += sprintf(q, "Pragma: no-cache\r\n");
772 q += sprintf(q, "\r\n");
773
774 q += sprintf(q, "<HEAD><TITLE>FFServer Status</TITLE></HEAD>\n<BODY>");
775 q += sprintf(q, "<H1>FFServer Status</H1>\n");
776 /* format status */
777 q += sprintf(q, "<H2>Available Streams</H2>\n");
778 q += sprintf(q, "<TABLE cellspacing=0 cellpadding=4>\n");
779 q += sprintf(q, "<TR><Th valign=top>Path<th align=left>Served<br>Conns<Th><br>kbytes<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");
780 stream = first_stream;
781 while (stream != NULL) {
782 char sfilename[1024];
783 char *eosf;
784
785 if (stream->feed != stream) {
786 strlcpy(sfilename, stream->filename, sizeof(sfilename) - 1);
787 eosf = sfilename + strlen(sfilename);
788 if (eosf - sfilename >= 4) {
789 if (strcmp(eosf - 4, ".asf") == 0) {
790 strcpy(eosf - 4, ".asx");
791 } else if (strcmp(eosf - 3, ".rm") == 0) {
792 strcpy(eosf - 3, ".ram");
793 }
794 }
795
796 q += sprintf(q, "<TR><TD><A HREF=\"/%s\">%s</A> ",
797 sfilename, stream->filename);
798 q += sprintf(q, "<td align=right> %d <td align=right> %lld",
799 stream->conns_served, stream->bytes_served / 1000);
800 switch(stream->stream_type) {
801 case STREAM_TYPE_LIVE:
802 {
803 int audio_bit_rate = 0;
804 int video_bit_rate = 0;
805 char *audio_codec_name = "";
806 char *video_codec_name = "";
807 char *audio_codec_name_extra = "";
808 char *video_codec_name_extra = "";
809
810 for(i=0;i<stream->nb_streams;i++) {
811 AVStream *st = stream->streams[i];
812 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
813 switch(st->codec.codec_type) {
814 case CODEC_TYPE_AUDIO:
815 audio_bit_rate += st->codec.bit_rate;
816 if (codec) {
817 if (*audio_codec_name)
818 audio_codec_name_extra = "...";
819 audio_codec_name = codec->name;
820 }
821 break;
822 case CODEC_TYPE_VIDEO:
823 video_bit_rate += st->codec.bit_rate;
824 if (codec) {
825 if (*video_codec_name)
826 video_codec_name_extra = "...";
827 video_codec_name = codec->name;
828 }
829 break;
830 default:
831 abort();
832 }
833 }
834 q += sprintf(q, "<TD align=center> %s <TD align=right> %d <TD align=right> %d <TD> %s %s <TD align=right> %d <TD> %s %s",
835 stream->fmt->name,
836 (audio_bit_rate + video_bit_rate) / 1000,
837 video_bit_rate / 1000, video_codec_name, video_codec_name_extra,
838 audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra);
839 if (stream->feed) {
840 q += sprintf(q, "<TD>%s", stream->feed->filename);
841 } else {
842 q += sprintf(q, "<TD>%s", stream->feed_filename);
843 }
844 q += sprintf(q, "\n");
845 }
846 break;
847 default:
848 q += sprintf(q, "<TD align=center> - <TD align=right> - <TD align=right> - <td><td align=right> - <TD>\n");
849 break;
850 }
851 }
852 stream = stream->next;
853 }
854 q += sprintf(q, "</TABLE>\n");
855
856 stream = first_stream;
857 while (stream != NULL) {
858 if (stream->feed == stream) {
859 q += sprintf(q, "<h2>Feed %s</h2>", stream->filename);
860 q += sprintf(q, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>type<th>kbits/s<th align=left>codec\n");
861
862 for (i = 0; i < stream->nb_streams; i++) {
863 AVStream *st = stream->streams[i];
864 AVCodec *codec = avcodec_find_encoder(st->codec.codec_id);
865 char *type = "unknown";
866
867 switch(st->codec.codec_type) {
868 case CODEC_TYPE_AUDIO:
869 type = "audio";
870 break;
871 case CODEC_TYPE_VIDEO:
872 type = "video";
873 break;
874 default:
875 abort();
876 }
877 q += sprintf(q, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s\n",
878 i, type, st->codec.bit_rate/1000, codec ? codec->name : "");
879 }
880 q += sprintf(q, "</table>\n");
881
882 }
883 stream = stream->next;
884 }
885
886 #if 0
887 {
888 float avg;
889 AVCodecContext *enc;
890 char buf[1024];
891
892 /* feed status */
893 stream = first_feed;
894 while (stream != NULL) {
895 q += sprintf(q, "<H1>Feed '%s'</H1>\n", stream->filename);
896 q += sprintf(q, "<TABLE>\n");
897 q += sprintf(q, "<TR><TD>Parameters<TD>Frame count<TD>Size<TD>Avg bitrate (kbits/s)\n");
898 for(i=0;i<stream->nb_streams;i++) {
899 AVStream *st = stream->streams[i];
900 FeedData *fdata = st->priv_data;
901 enc = &st->codec;
902
903 avcodec_string(buf, sizeof(buf), enc);
904 avg = fdata->avg_frame_size * (float)enc->rate * 8.0;
905 if (enc->codec->type == CODEC_TYPE_AUDIO && enc->frame_size > 0)
906 avg /= enc->frame_size;
907 q += sprintf(q, "<TR><TD>%s <TD> %d <TD> %Ld <TD> %0.1f\n",
908 buf, enc->frame_number, fdata->data_count, avg / 1000.0);
909 }
910 q += sprintf(q, "</TABLE>\n");
911 stream = stream->next_feed;
912 }
913 }
914 #endif
915
916 /* connection status */
917 q += sprintf(q, "<H2>Connection Status</H2>\n");
918
919 q += sprintf(q, "Number of connections: %d / %d<BR>\n",
920 nb_connections, nb_max_connections);
921
922 q += sprintf(q, "Bandwidth in use: %dk / %dk<BR>\n",
923 nb_bandwidth, nb_max_bandwidth);
924
925 q += sprintf(q, "<TABLE>\n");
926 q += sprintf(q, "<TR><TD>#<TD>File<TD>IP<TD>State<TD>Size\n");
927 c1 = first_http_ctx;
928 i = 0;
929 while (c1 != NULL && q < (char *) c->buffer + sizeof(c->buffer) - 2048) {
930 i++;
931 p = inet_ntoa(c1->from_addr.sin_addr);
932 q += sprintf(q, "<TR><TD><B>%d</B><TD>%s%s <TD> %s <TD> %s <TD> %Ld\n",
933 i, c1->stream->filename,
934 c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "",
935 p,
936 http_state[c1->state],
937 c1->data_count);
938 c1 = c1->next;
939 }
940 q += sprintf(q, "</TABLE>\n");
941
942 /* date */
943 ti = time(NULL);
944 p = ctime(&ti);
945 q += sprintf(q, "<HR size=1 noshade>Generated at %s", p);
946 q += sprintf(q, "</BODY>\n</HTML>\n");
947
948 c->buffer_ptr = c->buffer;
949 c->buffer_end = q;
950 }
951
952
953 static void http_write_packet(void *opaque,
954 unsigned char *buf, int size)
955 {
956 HTTPContext *c = opaque;
957
958 if (c->buffer_ptr == c->buffer_end || !c->buffer_ptr)
959 c->buffer_ptr = c->buffer_end = c->buffer;
960
961 if (c->buffer_end - c->buffer + size > IOBUFFER_MAX_SIZE)
962 abort();
963
964 memcpy(c->buffer_end, buf, size);
965 c->buffer_end += size;
966 }
967
968 static int open_input_stream(HTTPContext *c, const char *info)
969 {
970 char buf[128];
971 char input_filename[1024];
972 AVFormatContext *s;
973 int buf_size;
974 INT64 stream_pos;
975
976 /* find file name */
977 if (c->stream->feed) {
978 strcpy(input_filename, c->stream->feed->feed_filename);
979 buf_size = FFM_PACKET_SIZE;
980 /* compute position (absolute time) */
981 if (find_info_tag(buf, sizeof(buf), "date", info)) {
982 stream_pos = parse_date(buf, 0);
983 } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {
984 int prebuffer = strtol(buf, 0, 10);
985 stream_pos = gettime() - prebuffer * 1000000;
986 } else {
987 stream_pos = gettime() - c->stream->prebuffer * 1000;
988 }
989 } else {
990 strcpy(input_filename, c->stream->feed_filename);
991 buf_size = 0;
992 /* compute position (relative time) */
993 if (find_info_tag(buf, sizeof(buf), "date", info)) {
994 stream_pos = parse_date(buf, 1);
995 } else {
996 stream_pos = 0;
997 }
998 }
999 if (input_filename[0] == '\0')
1000 return -1;
1001
1002 /* open stream */
1003 s = av_open_input_file(input_filename, NULL, buf_size, NULL);
1004 if (!s)
1005 return -1;
1006 c->fmt_in = s;
1007
1008 if (c->fmt_in->format->read_seek) {
1009 c->fmt_in->format->read_seek(c->fmt_in, stream_pos);
1010 }
1011
1012 // printf("stream %s opened pos=%0.6f\n", input_filename, stream_pos / 1000000.0);
1013 return 0;
1014 }
1015
1016 static int http_prepare_data(HTTPContext *c)
1017 {
1018 int i;
1019
1020 switch(c->state) {
1021 case HTTPSTATE_SEND_DATA_HEADER:
1022 memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx));
1023 if (c->stream->feed) {
1024 /* open output stream by using specified codecs */
1025 c->fmt_ctx.format = c->stream->fmt;
1026 c->fmt_ctx.nb_streams = c->stream->nb_streams;
1027 for(i=0;i<c->fmt_ctx.nb_streams;i++) {
1028 AVStream *st;
1029 st = av_mallocz(sizeof(AVStream));
1030 c->fmt_ctx.streams[i] = st;
1031 if (c->stream->feed == c->stream)
1032 memcpy(st, c->stream->streams[i], sizeof(AVStream));
1033 else
1034 memcpy(st, c->stream->feed->streams[c->stream->feed_streams[i]], sizeof(AVStream));
1035
1036 st->codec.frame_number = 0; /* XXX: should be done in
1037 AVStream, not in codec */
1038 }
1039 c->got_key_frame = 0;
1040 } else {
1041 /* open output stream by using codecs in specified file */
1042 c->fmt_ctx.format = c->stream->fmt;
1043 c->fmt_ctx.nb_streams = c->fmt_in->nb_streams;
1044 for(i=0;i<c->fmt_ctx.nb_streams;i++) {
1045 AVStream *st;
1046 st = av_mallocz(sizeof(AVStream));
1047 c->fmt_ctx.streams[i] = st;
1048 memcpy(st, c->fmt_in->streams[i], sizeof(AVStream));
1049 st->codec.frame_number = 0; /* XXX: should be done in
1050 AVStream, not in codec */
1051 }
1052 c->got_key_frame = 0;
1053 }
1054 init_put_byte(&c->fmt_ctx.pb, c->pbuffer, PACKET_MAX_SIZE,
1055 1, c, NULL, http_write_packet, NULL);
1056 c->fmt_ctx.pb.is_streamed = 1;
1057 /* prepare header */
1058 c->fmt_ctx.format->write_header(&c->fmt_ctx);
1059 c->state = HTTPSTATE_SEND_DATA;
1060 c->last_packet_sent = 0;
1061 break;
1062 case HTTPSTATE_SEND_DATA:
1063 /* find a new packet */
1064 #if 0
1065 fifo_total_size = http_fifo_write_count - c->last_http_fifo_write_count;
1066 if (fifo_total_size >= ((3 * FIFO_MAX_SIZE) / 4)) {
1067 /* overflow : resync. We suppose that wptr is at this
1068 point a pointer to a valid packet */
1069 c->rptr = http_fifo.wptr;
1070 c->got_key_frame = 0;
1071 }
1072
1073 start_rptr = c->rptr;
1074 if (fifo_read(&http_fifo, (UINT8 *)&hdr, sizeof(hdr), &c->rptr) < 0)
1075 return 0;
1076 payload_size = ntohs(hdr.payload_size);
1077 payload = malloc(payload_size);
1078 if (fifo_read(&http_fifo, payload, payload_size, &c->rptr) < 0) {
1079 /* cannot read all the payload */
1080 free(payload);
1081 c->rptr = start_rptr;
1082 return 0;
1083 }
1084
1085 c->last_http_fifo_write_count = http_fifo_write_count -
1086 fifo_size(&http_fifo, c->rptr);
1087
1088 if (c->stream->stream_type != STREAM_TYPE_MASTER) {
1089 /* test if the packet can be handled by this format */
1090 ret = 0;
1091 for(i=0;i<c->fmt_ctx.nb_streams;i++) {
1092 AVStream *st = c->fmt_ctx.streams[i];
1093 if (test_header(&hdr, &st->codec)) {
1094 /* only begin sending when got a key frame */
1095 if (st->codec.key_frame)
1096 c->got_key_frame |= 1 << i;
1097 if (c->got_key_frame & (1 << i)) {
1098 ret = c->fmt_ctx.format->write_packet(&c->fmt_ctx, i,
1099 payload, payload_size);
1100 }
1101 break;
1102 }
1103 }
1104 if (ret) {
1105 /* must send trailer now */
1106 c->state = HTTPSTATE_SEND_DATA_TRAILER;
1107 }
1108 } else {
1109 /* master case : send everything */
1110 char *q;
1111 q = c->buffer;
1112 memcpy(q, &hdr, sizeof(hdr));
1113 q += sizeof(hdr);
1114 memcpy(q, payload, payload_size);
1115 q += payload_size;
1116 c->buffer_ptr = c->buffer;
1117 c->buffer_end = q;
1118 }
1119 free(payload);
1120 #endif
1121 {
1122 AVPacket pkt;
1123
1124 /* read a packet from the input stream */
1125 if (c->stream->feed) {
1126 ffm_set_write_index(c->fmt_in,
1127 c->stream->feed->feed_write_index,
1128 c->stream->feed->feed_size);
1129 }
1130
1131 if (av_read_packet(c->fmt_in, &pkt) < 0) {
1132 if (c->stream->feed && c->stream->feed->feed_opened) {
1133 /* if coming from feed, it means we reached the end of the
1134 ffm file, so must wait for more data */
1135 c->state = HTTPSTATE_WAIT_FEED;
1136 return 1; /* state changed */
1137 } else {
1138 /* must send trailer now because eof or error */
1139 c->state = HTTPSTATE_SEND_DATA_TRAILER;
1140 }
1141 } else {
1142 /* send it to the appropriate stream */
1143 if (c->stream->feed) {
1144 /* if coming from a feed, select the right stream */
1145 for(i=0;i<c->stream->nb_streams;i++) {
1146 if (c->stream->feed_streams[i] == pkt.stream_index) {
1147 pkt.stream_index = i;
1148 if (pkt.flags & PKT_FLAG_KEY) {
1149 c->got_key_frame |= 1 << i;
1150 }
1151 /* See if we have all the key frames, then
1152 * we start to send. This logic is not quite
1153 * right, but it works for the case of a
1154 * single video stream with one or more
1155 * audio streams (for which every frame is
1156 * typically a key frame).
1157 */
1158 if (!c->stream->send_on_key || ((c->got_key_frame + 1) >> c->stream->nb_streams)) {
1159 goto send_it;
1160 }
1161 }
1162 }
1163 } else {
1164 AVCodecContext *codec;
1165 send_it:
1166 /* Fudge here */
1167 codec = &c->fmt_ctx.streams[pkt.stream_index]->codec;
1168
1169 codec->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0);
1170
1171 #ifdef PJSG
1172 if (codec->codec_type == CODEC_TYPE_AUDIO) {
1173 codec->frame_size = (codec->sample_rate * pkt.duration + 500000) / 1000000;
1174 /* printf("Calculated size %d, from sr %d, duration %d\n", codec->frame_size, codec->sample_rate, pkt.duration); */
1175 }
1176 #endif
1177
1178 if (av_write_packet(&c->fmt_ctx, &pkt, 0))
1179 c->state = HTTPSTATE_SEND_DATA_TRAILER;
1180
1181 codec->frame_number++;
1182 }
1183
1184 av_free_packet(&pkt);
1185 }
1186 }
1187 break;
1188 default:
1189 case HTTPSTATE_SEND_DATA_TRAILER:
1190 /* last packet test ? */
1191 if (c->last_packet_sent)
1192 return -1;
1193 /* prepare header */
1194 c->fmt_ctx.format->write_trailer(&c->fmt_ctx);
1195 c->last_packet_sent = 1;
1196 break;
1197 }
1198 return 0;
1199 }
1200
1201 /* should convert the format at the same time */
1202 static int http_send_data(HTTPContext *c)
1203 {
1204 int len, ret;
1205
1206 while (c->buffer_ptr >= c->buffer_end) {
1207 ret = http_prepare_data(c);
1208 if (ret < 0)
1209 return -1;
1210 else if (ret == 0) {
1211 continue;
1212 } else {
1213 /* state change requested */
1214 return 0;
1215 }
1216 }
1217
1218 if (c->buffer_end > c->buffer_ptr) {
1219 len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
1220 if (len < 0) {
1221 if (errno != EAGAIN && errno != EINTR) {
1222 /* error : close connection */
1223 return -1;
1224 }
1225 } else {
1226 c->buffer_ptr += len;
1227 c->data_count += len;
1228 c->stream->bytes_served += len;
1229 }
1230 }
1231 return 0;
1232 }
1233
1234 static int http_start_receive_data(HTTPContext *c)
1235 {
1236 int fd;
1237
1238 if (c->stream->feed_opened)
1239 return -1;
1240
1241 /* open feed */
1242 fd = open(c->stream->feed_filename, O_RDWR);
1243 if (fd < 0)
1244 return -1;
1245 c->feed_fd = fd;
1246
1247 c->stream->feed_write_index = ffm_read_write_index(fd);
1248 c->stream->feed_size = lseek(fd, 0, SEEK_END);
1249 lseek(fd, 0, SEEK_SET);
1250
1251 /* init buffer input */
1252 c->buffer_ptr = c->buffer;
1253 c->buffer_end = c->buffer + FFM_PACKET_SIZE;
1254 c->stream->feed_opened = 1;
1255 return 0;
1256 }
1257
1258 static int http_receive_data(HTTPContext *c)
1259 {
1260 HTTPContext *c1;
1261
1262 if (c->buffer_end > c->buffer_ptr) {
1263 int len;
1264
1265 len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);
1266 if (len < 0) {
1267 if (errno != EAGAIN && errno != EINTR) {
1268 /* error : close connection */
1269 goto fail;
1270 }
1271 } else if (len == 0) {
1272 /* end of connection : close it */
1273 goto fail;
1274 } else {
1275 c->buffer_ptr += len;
1276 c->data_count += len;
1277 }
1278 }
1279
1280 if (c->buffer_ptr >= c->buffer_end) {
1281 FFStream *feed = c->stream;
1282 /* a packet has been received : write it in the store, except
1283 if header */
1284 if (c->data_count > FFM_PACKET_SIZE) {
1285
1286 // printf("writing pos=0x%Lx size=0x%Lx\n", feed->feed_write_index, feed->feed_size);
1287 /* XXX: use llseek or url_seek */
1288 lseek(c->feed_fd, feed->feed_write_index, SEEK_SET);
1289 write(c->feed_fd, c->buffer, FFM_PACKET_SIZE);
1290
1291 feed->feed_write_index += FFM_PACKET_SIZE;
1292 /* update file size */
1293 if (feed->feed_write_index > c->stream->feed_size)
1294 feed->feed_size = feed->feed_write_index;
1295
1296 /* handle wrap around if max file size reached */
1297 if (feed->feed_write_index >= c->stream->feed_max_size)
1298 feed->feed_write_index = FFM_PACKET_SIZE;
1299
1300 /* write index */
1301 ffm_write_write_index(c->feed_fd, feed->feed_write_index);
1302
1303 /* wake up any waiting connections */
1304 for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) {
1305 if (c1->state == HTTPSTATE_WAIT_FEED &&
1306 c1->stream->feed == c->stream->feed) {
1307 c1->state = HTTPSTATE_SEND_DATA;
1308 }
1309 }
1310 } else {
1311 /* We have a header in our hands that contains useful data */
1312 AVFormatContext s;
1313 ByteIOContext *pb = &s.pb;
1314 int i;
1315
1316 memset(&s, 0, sizeof(s));
1317
1318 url_open_buf(pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY);
1319 pb->buf_end = c->buffer_end; /* ?? */
1320 pb->is_streamed = 1;
1321
1322 if (feed->fmt->read_header(&s, 0) < 0) {
1323 goto fail;
1324 }
1325
1326 /* Now we have the actual streams */
1327 if (s.nb_streams != feed->nb_streams) {
1328 goto fail;
1329 }
1330 for (i = 0; i < s.nb_streams; i++) {
1331 memcpy(&feed->streams[i]->codec, &s.streams[i]->codec, sizeof(AVCodecContext));
1332 }
1333 }
1334 c->buffer_ptr = c->buffer;
1335 }
1336
1337 return 0;
1338 fail:
1339 c->stream->feed_opened = 0;
1340 close(c->feed_fd);
1341 return -1;
1342 }
1343
1344 /* return the stream number in the feed */
1345 int add_av_stream(FFStream *feed,
1346 AVStream *st)
1347 {
1348 AVStream *fst;
1349 AVCodecContext *av, *av1;
1350 int i;
1351
1352 av = &st->codec;
1353 for(i=0;i<feed->nb_streams;i++) {
1354 st = feed->streams[i];
1355 av1 = &st->codec;
1356 if (av1->codec_id == av->codec_id &&
1357 av1->codec_type == av->codec_type &&
1358 av1->bit_rate == av->bit_rate) {
1359
1360 switch(av->codec_type) {
1361 case CODEC_TYPE_AUDIO:
1362 if (av1->channels == av->channels &&
1363 av1->sample_rate == av->sample_rate)
1364 goto found;
1365 break;
1366 case CODEC_TYPE_VIDEO:
1367 if (av1->width == av->width &&
1368 av1->height == av->height &&
1369 av1->frame_rate == av->frame_rate &&
1370 av1->gop_size == av->gop_size)
1371 goto found;
1372 break;
1373 default:
1374 abort();
1375 }
1376 }
1377 }
1378
1379 fst = av_mallocz(sizeof(AVStream));
1380 if (!fst)
1381 return -1;
1382 fst->priv_data = av_mallocz(sizeof(FeedData));
1383 memcpy(&fst->codec, av, sizeof(AVCodecContext));
1384 feed->streams[feed->nb_streams++] = fst;
1385 return feed->nb_streams - 1;
1386 found:
1387 return i;
1388 }
1389
1390 /* compute the needed AVStream for each feed */
1391 void build_feed_streams(void)
1392 {
1393 FFStream *stream, *feed;
1394 int i;
1395
1396 /* gather all streams */
1397 for(stream = first_stream; stream != NULL; stream = stream->next) {
1398 feed = stream->feed;
1399 if (feed) {
1400 if (!stream->is_feed) {
1401 for(i=0;i<stream->nb_streams;i++) {
1402 stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
1403 }
1404 } else {
1405 for(i=0;i<stream->nb_streams;i++) {
1406 stream->feed_streams[i] = i;
1407 }
1408 }
1409 }
1410 }
1411
1412 /* create feed files if needed */
1413 for(feed = first_feed; feed != NULL; feed = feed->next_feed) {
1414 int fd;
1415
1416 if (!url_exist(feed->feed_filename)) {
1417 AVFormatContext s1, *s = &s1;
1418
1419 /* only write the header of the ffm file */
1420 if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) {
1421 fprintf(stderr, "Could not open output feed file '%s'\n",
1422 feed->feed_filename);
1423 exit(1);
1424 }
1425 s->format = feed->fmt;
1426 s->nb_streams = feed->nb_streams;
1427 for(i=0;i<s->nb_streams;i++) {
1428 AVStream *st;
1429 st = feed->streams[i];
1430 s->streams[i] = st;
1431 }
1432 s->format->write_header(s);
1433
1434 url_fclose(&s->pb);
1435 }
1436 /* get feed size and write index */
1437 fd = open(feed->feed_filename, O_RDONLY);
1438 if (fd < 0) {
1439 fprintf(stderr, "Could not open output feed file '%s'\n",
1440 feed->feed_filename);
1441 exit(1);
1442 }
1443
1444 feed->feed_write_index = ffm_read_write_index(fd);
1445 feed->feed_size = lseek(fd, 0, SEEK_END);
1446 /* ensure that we do not wrap before the end of file */
1447 if (feed->feed_max_size < feed->feed_size)
1448 feed->feed_max_size = feed->feed_size;
1449
1450 close(fd);
1451 }
1452 }
1453
1454 static void get_arg(char *buf, int buf_size, const char **pp)
1455 {
1456 const char *p;
1457 char *q;
1458 int quote;
1459
1460 p = *pp;
1461 while (isspace(*p)) p++;
1462 q = buf;
1463 quote = 0;
1464 if (*p == '\"' || *p == '\'')
1465 quote = *p++;
1466 for(;;) {
1467 if (quote) {
1468 if (*p == quote)
1469 break;
1470 } else {
1471 if (isspace(*p))
1472 break;
1473 }
1474 if (*p == '\0')
1475 break;
1476 if ((q - buf) < buf_size - 1)
1477 *q++ = *p;
1478 p++;
1479 }
1480 *q = '\0';
1481 if (quote && *p == quote)
1482 p++;
1483 *pp = p;
1484 }
1485
1486 /* add a codec and set the default parameters */
1487 void add_codec(FFStream *stream, AVCodecContext *av)
1488 {
1489 AVStream *st;
1490
1491 /* compute default parameters */
1492 switch(av->codec_type) {
1493 case CODEC_TYPE_AUDIO:
1494 if (av->bit_rate == 0)
1495 av->bit_rate = 64000;
1496 if (av->sample_rate == 0)
1497 av->sample_rate = 22050;
1498 if (av->channels == 0)
1499 av->channels = 1;
1500 break;
1501 case CODEC_TYPE_VIDEO:
1502 if (av->bit_rate == 0)
1503 av->bit_rate = 64000;
1504 if (av->frame_rate == 0)
1505 av->frame_rate = 5 * FRAME_RATE_BASE;
1506 if (av->width == 0 || av->height == 0) {
1507 av->width = 160;
1508 av->height = 128;
1509 }
1510 /* Bitrate tolerance is less for streaming */
1511 if (av->bit_rate_tolerance == 0)
1512 av->bit_rate_tolerance = av->bit_rate / 4;
1513 if (av->qmin == 0)
1514 av->qmin = 3;
1515 if (av->qmax == 0)
1516 av->qmax = 31;
1517 if (av->max_qdiff == 0)
1518 av->max_qdiff = 3;
1519 av->qcompress = 0.5;
1520 av->qblur = 0.5;
1521
1522 break;
1523 default:
1524 abort();
1525 }
1526
1527 st = av_mallocz(sizeof(AVStream));
1528 if (!st)
1529 return;
1530 stream->streams[stream->nb_streams++] = st;
1531 memcpy(&st->codec, av, sizeof(AVCodecContext));
1532 }
1533
1534 int opt_audio_codec(const char *arg)
1535 {
1536 AVCodec *p;
1537
1538 p = first_avcodec;
1539 while (p) {
1540 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1541 break;
1542 p = p->next;
1543 }
1544 if (p == NULL) {
1545 return CODEC_ID_NONE;
1546 }
1547
1548 return p->id;
1549 }
1550
1551 int opt_video_codec(const char *arg)
1552 {
1553 AVCodec *p;
1554
1555 p = first_avcodec;
1556 while (p) {
1557 if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1558 break;
1559 p = p->next;
1560 }
1561 if (p == NULL) {
1562 return CODEC_ID_NONE;
1563 }
1564
1565 return p->id;
1566 }
1567
1568 int parse_ffconfig(const char *filename)
1569 {
1570 FILE *f;
1571 char line[1024];
1572 char cmd[64];
1573 char arg[1024];
1574 const char *p;
1575 int val, errors, line_num;
1576 FFStream **last_stream, *stream;
1577 FFStream **last_feed, *feed;
1578 AVCodecContext audio_enc, video_enc;
1579 int audio_id, video_id;
1580
1581 f = fopen(filename, "r");
1582 if (!f) {
1583 perror(filename);
1584 return -1;
1585 }
1586
1587 errors = 0;
1588 line_num = 0;
1589 first_stream = NULL;
1590 last_stream = &first_stream;
1591 first_feed = NULL;
1592 last_feed = &first_feed;
1593 stream = NULL;
1594 feed = NULL;
1595 audio_id = CODEC_ID_NONE;
1596 video_id = CODEC_ID_NONE;
1597 for(;;) {
1598 if (fgets(line, sizeof(line), f) == NULL)
1599 break;
1600 line_num++;
1601 p = line;
1602 while (isspace(*p))
1603 p++;
1604 if (*p == '\0' || *p == '#')
1605 continue;
1606
1607 get_arg(cmd, sizeof(cmd), &p);
1608
1609 if (!strcasecmp(cmd, "Port")) {
1610 get_arg(arg, sizeof(arg), &p);
1611 my_addr.sin_port = htons (atoi(arg));
1612 } else if (!strcasecmp(cmd, "BindAddress")) {
1613 get_arg(arg, sizeof(arg), &p);
1614 if (!inet_aton(arg, &my_addr.sin_addr)) {
1615 fprintf(stderr, "%s:%d: Invalid IP address: %s\n",
1616 filename, line_num, arg);
1617 errors++;
1618 }
1619 } else if (!strcasecmp(cmd, "MaxClients")) {
1620 get_arg(arg, sizeof(arg), &p);
1621 val = atoi(arg);
1622 if (val < 1 || val > HTTP_MAX_CONNECTIONS) {
1623 fprintf(stderr, "%s:%d: Invalid MaxClients: %s\n",
1624 filename, line_num, arg);
1625 errors++;
1626 } else {
1627 nb_max_connections = val;
1628 }
1629 } else if (!strcasecmp(cmd, "MaxBandwidth")) {
1630 get_arg(arg, sizeof(arg), &p);
1631 val = atoi(arg);
1632 if (val < 10 || val > 100000) {
1633 fprintf(stderr, "%s:%d: Invalid MaxBandwidth: %s\n",
1634 filename, line_num, arg);
1635 errors++;
1636 } else {
1637 nb_max_bandwidth = val;
1638 }
1639 } else if (!strcasecmp(cmd, "CustomLog")) {
1640 get_arg(logfilename, sizeof(logfilename), &p);
1641 } else if (!strcasecmp(cmd, "<Feed")) {
1642 /*********************************************/
1643 /* Feed related options */
1644 char *q;
1645 if (stream || feed) {
1646 fprintf(stderr, "%s:%d: Already in a tag\n",
1647 filename, line_num);
1648 } else {
1649 feed = av_mallocz(sizeof(FFStream));
1650 /* add in stream list */
1651 *last_stream = feed;
1652 last_stream = &feed->next;
1653 /* add in feed list */
1654 *last_feed = feed;
1655 last_feed = &feed->next_feed;
1656
1657 get_arg(feed->filename, sizeof(feed->filename), &p);
1658 q = strrchr(feed->filename, '>');
1659 if (*q)
1660 *q = '\0';
1661 feed->fmt = guess_format("ffm", NULL, NULL);
1662 /* defaut feed file */
1663 snprintf(feed->feed_filename, sizeof(feed->feed_filename),
1664 "/tmp/%s.ffm", feed->filename);
1665 feed->feed_max_size = 5 * 1024 * 1024;
1666 feed->is_feed = 1;
1667 feed->feed = feed; /* self feeding :-) */
1668 }
1669 } else if (!strcasecmp(cmd, "File")) {
1670 if (feed) {
1671 get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p);
1672 } else if (stream) {
1673 get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p);
1674 }
1675 } else if (!strcasecmp(cmd, "FileMaxSize")) {
1676 if (feed) {
1677 const char *p1;
1678 double fsize;
1679
1680 get_arg(arg, sizeof(arg), &p);
1681 p1 = arg;
1682 fsize = strtod(p1, (char **)&p1);
1683 switch(toupper(*p1)) {
1684 case 'K':
1685 fsize *= 1024;
1686 break;
1687 case 'M':
1688 fsize *= 1024 * 1024;
1689 break;
1690 case 'G':
1691 fsize *= 1024 * 1024 * 1024;
1692 break;
1693 }
1694 feed->feed_max_size = (INT64)fsize;
1695 }
1696 } else if (!strcasecmp(cmd, "</Feed>")) {
1697 if (!feed) {
1698 fprintf(stderr, "%s:%d: No corresponding <Feed> for </Feed>\n",
1699 filename, line_num);
1700 errors++;
1701 } else {
1702 /* Make sure that we start out clean */
1703 if (unlink(feed->feed_filename) < 0
1704 && errno != ENOENT) {
1705 fprintf(stderr, "%s:%d: Unable to clean old feed file '%s': %s\n",
1706 filename, line_num, feed->feed_filename, strerror(errno));
1707 errors++;
1708 }
1709 }
1710 feed = NULL;
1711 } else if (!strcasecmp(cmd, "<Stream")) {
1712 /*********************************************/
1713 /* Stream related options */
1714 char *q;
1715 if (stream || feed) {
1716 fprintf(stderr, "%s:%d: Already in a tag\n",
1717 filename, line_num);
1718 } else {
1719 stream = av_mallocz(sizeof(FFStream));
1720 *last_stream = stream;
1721 last_stream = &stream->next;
1722
1723 get_arg(stream->filename, sizeof(stream->filename), &p);
1724 q = strrchr(stream->filename, '>');
1725 if (*q)
1726 *q = '\0';
1727 stream->fmt = guess_format(NULL, stream->filename, NULL);
1728 memset(&audio_enc, 0, sizeof(AVCodecContext));
1729 memset(&video_enc, 0, sizeof(AVCodecContext));
1730 audio_id = CODEC_ID_NONE;
1731 video_id = CODEC_ID_NONE;
1732 if (stream->fmt) {
1733 audio_id = stream->fmt->audio_codec;
1734 video_id = stream->fmt->video_codec;
1735 }
1736 }
1737 } else if (!strcasecmp(cmd, "Feed")) {
1738 get_arg(arg, sizeof(arg), &p);
1739 if (stream) {
1740 FFStream *sfeed;
1741
1742 sfeed = first_feed;
1743 while (sfeed != NULL) {
1744 if (!strcmp(sfeed->filename, arg))
1745 break;
1746 sfeed = sfeed->next_feed;
1747 }
1748 if (!sfeed) {
1749 fprintf(stderr, "%s:%d: feed '%s' not defined\n",
1750 filename, line_num, arg);
1751 } else {
1752 stream->feed = sfeed;
1753 }
1754 }
1755 } else if (!strcasecmp(cmd, "Format")) {
1756 get_arg(arg, sizeof(arg), &p);
1757 if (!strcmp(arg, "status")) {
1758 stream->stream_type = STREAM_TYPE_STATUS;
1759 stream->fmt = NULL;
1760 } else {
1761 stream->stream_type = STREAM_TYPE_LIVE;
1762 /* jpeg cannot be used here, so use single frame jpeg */
1763 if (!strcmp(arg, "jpeg"))
1764 strcpy(arg, "singlejpeg");
1765 stream->fmt = guess_format(arg, NULL, NULL);
1766 if (!stream->fmt) {
1767 fprintf(stderr, "%s:%d: Unknown Format: %s\n",
1768 filename, line_num, arg);
1769 errors++;
1770 }
1771 }
1772 if (stream->fmt) {
1773 audio_id = stream->fmt->audio_codec;
1774 video_id = stream->fmt->video_codec;
1775 }
1776 } else if (!strcasecmp(cmd, "Preroll")) {
1777 get_arg(arg, sizeof(arg), &p);
1778 if (stream) {
1779 stream->prebuffer = atoi(arg) * 1000;
1780 }
1781 } else if (!strcasecmp(cmd, "StartSendOnKey")) {
1782 if (stream) {
1783 stream->send_on_key = 1;
1784 }
1785 } else if (!strcasecmp(cmd, "AudioCodec")) {
1786 get_arg(arg, sizeof(arg), &p);
1787 audio_id = opt_audio_codec(arg);
1788 if (audio_id == CODEC_ID_NONE) {
1789 fprintf(stderr, "%s:%d: Unknown AudioCodec: %s\n",
1790 filename, line_num, arg);
1791 errors++;
1792 }
1793 } else if (!strcasecmp(cmd, "VideoCodec")) {
1794 get_arg(arg, sizeof(arg), &p);
1795 video_id = opt_video_codec(arg);
1796 if (video_id == CODEC_ID_NONE) {
1797 fprintf(stderr, "%s:%d: Unknown VideoCodec: %s\n",
1798 filename, line_num, arg);
1799 errors++;
1800 }
1801 } else if (!strcasecmp(cmd, "AudioBitRate")) {
1802 get_arg(arg, sizeof(arg), &p);
1803 if (stream) {
1804 audio_enc.bit_rate = atoi(arg) * 1000;
1805 }
1806 } else if (!strcasecmp(cmd, "AudioChannels")) {
1807 get_arg(arg, sizeof(arg), &p);
1808 if (stream) {
1809 audio_enc.channels = atoi(arg);
1810 }
1811 } else if (!strcasecmp(cmd, "AudioSampleRate")) {
1812 get_arg(arg, sizeof(arg), &p);
1813 if (stream) {
1814 audio_enc.sample_rate = atoi(arg);
1815 }
1816 } else if (!strcasecmp(cmd, "VideoBitRate")) {
1817 get_arg(arg, sizeof(arg), &p);
1818 if (stream) {
1819 video_enc.bit_rate = atoi(arg) * 1000;
1820 }
1821 } else if (!strcasecmp(cmd, "VideoSize")) {
1822 get_arg(arg, sizeof(arg), &p);
1823 if (stream) {
1824 parse_image_size(&video_enc.width, &video_enc.height, arg);
1825 if ((video_enc.width % 16) != 0 ||
1826 (video_enc.height % 16) != 0) {
1827 fprintf(stderr, "%s:%d: Image size must be a multiple of 16\n",
1828 filename, line_num);
1829 errors++;
1830 }
1831 }
1832 } else if (!strcasecmp(cmd, "VideoFrameRate")) {
1833 get_arg(arg, sizeof(arg), &p);
1834 if (stream) {
1835 video_enc.frame_rate = (int)(strtod(arg, NULL) * FRAME_RATE_BASE);
1836 }
1837 } else if (!strcasecmp(cmd, "VideoGopSize")) {
1838 get_arg(arg, sizeof(arg), &p);
1839 if (stream) {
1840 video_enc.gop_size = atoi(arg);
1841 }
1842 } else if (!strcasecmp(cmd, "VideoIntraOnly")) {
1843 if (stream) {
1844 video_enc.gop_size = 1;
1845 }
1846 } else if (!strcasecmp(cmd, "VideoHighQuality")) {
1847 if (stream) {
1848 video_enc.flags |= CODEC_FLAG_HQ;
1849 }
1850 } else if (!strcasecmp(cmd, "VideoQDiff")) {
1851 if (stream) {
1852 video_enc.max_qdiff = atoi(arg);
1853 if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) {
1854 fprintf(stderr, "%s:%d: VideoQDiff out of range\n",
1855 filename, line_num);
1856 errors++;
1857 }
1858 }
1859 } else if (!strcasecmp(cmd, "VideoQMax")) {
1860 if (stream) {
1861 video_enc.qmax = atoi(arg);
1862 if (video_enc.qmax < 1 || video_enc.qmax > 31) {
1863 fprintf(stderr, "%s:%d: VideoQMax out of range\n",
1864 filename, line_num);
1865 errors++;
1866 }
1867 }
1868 } else if (!strcasecmp(cmd, "VideoQMin")) {
1869 if (stream) {
1870 video_enc.qmin = atoi(arg);
1871 if (video_enc.qmin < 1 || video_enc.qmin > 31) {
1872 fprintf(stderr, "%s:%d: VideoQMin out of range\n",
1873 filename, line_num);
1874 errors++;
1875 }
1876 }
1877 } else if (!strcasecmp(cmd, "NoVideo")) {
1878 video_id = CODEC_ID_NONE;
1879 } else if (!strcasecmp(cmd, "NoAudio")) {
1880 audio_id = CODEC_ID_NONE;
1881 } else if (!strcasecmp(cmd, "</Stream>")) {
1882 if (!stream) {
1883 fprintf(stderr, "%s:%d: No corresponding <Stream> for </Stream>\n",
1884 filename, line_num);
1885 errors++;
1886 }
1887 if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) {
1888 if (audio_id != CODEC_ID_NONE) {
1889 audio_enc.codec_type = CODEC_TYPE_AUDIO;
1890 audio_enc.codec_id = audio_id;
1891 add_codec(stream, &audio_enc);
1892 }
1893 if (video_id != CODEC_ID_NONE) {
1894 video_enc.codec_type = CODEC_TYPE_VIDEO;
1895 video_enc.codec_id = video_id;
1896 add_codec(stream, &video_enc);
1897 }
1898 }
1899 stream = NULL;
1900 } else {
1901 fprintf(stderr, "%s:%d: Incorrect keyword: '%s'\n",
1902 filename, line_num, cmd);
1903 errors++;
1904 }
1905 }
1906
1907 fclose(f);
1908 if (errors)
1909 return -1;
1910 else
1911 return 0;
1912 }
1913
1914
1915 void *http_server_thread(void *arg)
1916 {
1917 http_server(my_addr);
1918 return NULL;
1919 }
1920
1921 #if 0
1922 static void write_packet(FFCodec *ffenc,
1923 UINT8 *buf, int size)
1924 {
1925 PacketHeader hdr;
1926 AVCodecContext *enc = &ffenc->enc;
1927 UINT8 *wptr;
1928 mk_header(&hdr, enc, size);
1929 wptr = http_fifo.wptr;
1930 fifo_write(&http_fifo, (UINT8 *)&hdr, sizeof(hdr), &wptr);
1931 fifo_write(&http_fifo, buf, size, &wptr);
1932 /* atomic modification of wptr */
1933 http_fifo.wptr = wptr;
1934 ffenc->data_count += size;
1935 ffenc->avg_frame_size = ffenc->avg_frame_size * AVG_COEF + size * (1.0 - AVG_COEF);
1936 }
1937 #endif
1938
1939 void help(void)
1940 {
1941 printf("ffserver version " FFMPEG_VERSION ", Copyright (c) 2000,2001 Gerard Lantau\n"
1942 "usage: ffserver [-L] [-h] [-f configfile]\n"
1943 "Hyper fast multi format Audio/Video streaming server\n"
1944 "\n"
1945 "-L : print the LICENCE\n"
1946 "-h : this help\n"
1947 "-f configfile : use configfile instead of /etc/ffserver.conf\n"
1948 );
1949 }
1950
1951 void licence(void)
1952 {
1953 printf(
1954 "ffserver version " FFMPEG_VERSION "\n"
1955 "Copyright (c) 2000,2001 Gerard Lantau\n"
1956 "This program is free software; you can redistribute it and/or modify\n"
1957 "it under the terms of the GNU General Public License as published by\n"
1958 "the Free Software Foundation; either version 2 of the License, or\n"
1959 "(at your option) any later version.\n"
1960 "\n"
1961 "This program is distributed in the hope that it will be useful,\n"
1962 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1963 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
1964 "GNU General Public License for more details.\n"
1965 "\n"
1966 "You should have received a copy of the GNU General Public License\n"
1967 "along with this program; if not, write to the Free Software\n"
1968 "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
1969 );
1970 }
1971
1972 int main(int argc, char **argv)
1973 {
1974 const char *config_filename;
1975 int c;
1976
1977 register_all();
1978
1979 config_filename = "/etc/ffserver.conf";
1980
1981 for(;;) {
1982 c = getopt_long_only(argc, argv, "Lh?f:", NULL, NULL);
1983 if (c == -1)
1984 break;
1985 switch(c) {
1986 case 'L':
1987 licence();
1988 exit(1);
1989 case '?':
1990 case 'h':
1991 help();
1992 exit(1);
1993 case 'f':
1994 config_filename = optarg;
1995 break;
1996 default:
1997 exit(2);
1998 }
1999 }
2000
2001 /* address on which the server will handle connections */
2002 my_addr.sin_family = AF_INET;
2003 my_addr.sin_port = htons (8080);
2004 my_addr.sin_addr.s_addr = htonl (INADDR_ANY);
2005 nb_max_connections = 5;
2006 nb_max_bandwidth = 1000;
2007 first_stream = NULL;
2008 logfilename[0] = '\0';
2009
2010 if (parse_ffconfig(config_filename) < 0) {
2011 fprintf(stderr, "Incorrect config file - exiting.\n");
2012 exit(1);
2013 }
2014
2015 build_feed_streams();
2016
2017 /* signal init */
2018 signal(SIGPIPE, SIG_IGN);
2019
2020 /* open log file if needed */
2021 if (logfilename[0] != '\0') {
2022 if (!strcmp(logfilename, "-"))
2023 logfile = stdout;
2024 else
2025 logfile = fopen(logfilename, "w");
2026 }
2027
2028 if (http_server(my_addr) < 0) {
2029 fprintf(stderr, "Could start http server\n");
2030 exit(1);
2031 }
2032
2033 return 0;
2034 }