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.

1824 lines
56KB

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