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.

1583 lines
49KB

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