You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1990 lines
63KB

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