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.

2246 lines
72KB

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