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.

3988 lines
124KB

  1. /*
  2. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * multiple format streaming server based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #if !HAVE_CLOSESOCKET
  26. #define closesocket close
  27. #endif
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include "libavformat/avformat.h"
  32. /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
  33. #include "libavformat/rtpproto.h"
  34. #include "libavformat/rtsp.h"
  35. #include "libavformat/avio_internal.h"
  36. #include "libavformat/internal.h"
  37. #include "libavutil/avassert.h"
  38. #include "libavutil/avstring.h"
  39. #include "libavutil/lfg.h"
  40. #include "libavutil/dict.h"
  41. #include "libavutil/intreadwrite.h"
  42. #include "libavutil/mathematics.h"
  43. #include "libavutil/random_seed.h"
  44. #include "libavutil/rational.h"
  45. #include "libavutil/parseutils.h"
  46. #include "libavutil/opt.h"
  47. #include "libavutil/time.h"
  48. #include <stdarg.h>
  49. #if HAVE_UNISTD_H
  50. #include <unistd.h>
  51. #endif
  52. #include <fcntl.h>
  53. #include <sys/ioctl.h>
  54. #if HAVE_POLL_H
  55. #include <poll.h>
  56. #endif
  57. #include <errno.h>
  58. #include <time.h>
  59. #include <sys/wait.h>
  60. #include <signal.h>
  61. #include "cmdutils.h"
  62. #include "ffserver_config.h"
  63. #define PATH_LENGTH 1024
  64. const char program_name[] = "ffserver";
  65. const int program_birth_year = 2000;
  66. static const OptionDef options[];
  67. enum HTTPState {
  68. HTTPSTATE_WAIT_REQUEST,
  69. HTTPSTATE_SEND_HEADER,
  70. HTTPSTATE_SEND_DATA_HEADER,
  71. HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
  72. HTTPSTATE_SEND_DATA_TRAILER,
  73. HTTPSTATE_RECEIVE_DATA,
  74. HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
  75. HTTPSTATE_READY,
  76. RTSPSTATE_WAIT_REQUEST,
  77. RTSPSTATE_SEND_REPLY,
  78. RTSPSTATE_SEND_PACKET,
  79. };
  80. static const char * const http_state[] = {
  81. "HTTP_WAIT_REQUEST",
  82. "HTTP_SEND_HEADER",
  83. "SEND_DATA_HEADER",
  84. "SEND_DATA",
  85. "SEND_DATA_TRAILER",
  86. "RECEIVE_DATA",
  87. "WAIT_FEED",
  88. "READY",
  89. "RTSP_WAIT_REQUEST",
  90. "RTSP_SEND_REPLY",
  91. "RTSP_SEND_PACKET",
  92. };
  93. #define IOBUFFER_INIT_SIZE 8192
  94. /* timeouts are in ms */
  95. #define HTTP_REQUEST_TIMEOUT (15 * 1000)
  96. #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
  97. #define SYNC_TIMEOUT (10 * 1000)
  98. typedef struct RTSPActionServerSetup {
  99. uint32_t ipaddr;
  100. char transport_option[512];
  101. } RTSPActionServerSetup;
  102. typedef struct {
  103. int64_t count1, count2;
  104. int64_t time1, time2;
  105. } DataRateData;
  106. /* context associated with one connection */
  107. typedef struct HTTPContext {
  108. enum HTTPState state;
  109. int fd; /* socket file descriptor */
  110. struct sockaddr_in from_addr; /* origin */
  111. struct pollfd *poll_entry; /* used when polling */
  112. int64_t timeout;
  113. uint8_t *buffer_ptr, *buffer_end;
  114. int http_error;
  115. int post;
  116. int chunked_encoding;
  117. int chunk_size; /* 0 if it needs to be read */
  118. struct HTTPContext *next;
  119. int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
  120. int64_t data_count;
  121. /* feed input */
  122. int feed_fd;
  123. /* input format handling */
  124. AVFormatContext *fmt_in;
  125. int64_t start_time; /* In milliseconds - this wraps fairly often */
  126. int64_t first_pts; /* initial pts value */
  127. int64_t cur_pts; /* current pts value from the stream in us */
  128. int64_t cur_frame_duration; /* duration of the current frame in us */
  129. int cur_frame_bytes; /* output frame size, needed to compute
  130. the time at which we send each
  131. packet */
  132. int pts_stream_index; /* stream we choose as clock reference */
  133. int64_t cur_clock; /* current clock reference value in us */
  134. /* output format handling */
  135. struct FFServerStream *stream;
  136. /* -1 is invalid stream */
  137. int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  138. int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  139. int switch_pending;
  140. AVFormatContext *pfmt_ctx; /* instance of FFServerStream for one user */
  141. int last_packet_sent; /* true if last data packet was sent */
  142. int suppress_log;
  143. DataRateData datarate;
  144. int wmp_client_id;
  145. char protocol[16];
  146. char method[16];
  147. char url[128];
  148. int buffer_size;
  149. uint8_t *buffer;
  150. int is_packetized; /* if true, the stream is packetized */
  151. int packet_stream_index; /* current stream for output in state machine */
  152. /* RTSP state specific */
  153. uint8_t *pb_buffer; /* XXX: use that in all the code */
  154. AVIOContext *pb;
  155. int seq; /* RTSP sequence number */
  156. /* RTP state specific */
  157. enum RTSPLowerTransport rtp_protocol;
  158. char session_id[32]; /* session id */
  159. AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
  160. /* RTP/UDP specific */
  161. URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
  162. /* RTP/TCP specific */
  163. struct HTTPContext *rtsp_c;
  164. uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
  165. } HTTPContext;
  166. typedef struct FeedData {
  167. long long data_count;
  168. float avg_frame_size; /* frame size averaged over last frames with exponential mean */
  169. } FeedData;
  170. static HTTPContext *first_http_ctx;
  171. static FFServerConfig config = {
  172. .nb_max_http_connections = 2000,
  173. .nb_max_connections = 5,
  174. .max_bandwidth = 1000,
  175. .use_defaults = 1,
  176. };
  177. static void new_connection(int server_fd, int is_rtsp);
  178. static void close_connection(HTTPContext *c);
  179. /* HTTP handling */
  180. static int handle_connection(HTTPContext *c);
  181. static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
  182. static void compute_status(HTTPContext *c);
  183. static int open_input_stream(HTTPContext *c, const char *info);
  184. static int http_parse_request(HTTPContext *c);
  185. static int http_send_data(HTTPContext *c);
  186. static int http_start_receive_data(HTTPContext *c);
  187. static int http_receive_data(HTTPContext *c);
  188. /* RTSP handling */
  189. static int rtsp_parse_request(HTTPContext *c);
  190. static void rtsp_cmd_describe(HTTPContext *c, const char *url);
  191. static void rtsp_cmd_options(HTTPContext *c, const char *url);
  192. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  193. RTSPMessageHeader *h);
  194. static void rtsp_cmd_play(HTTPContext *c, const char *url,
  195. RTSPMessageHeader *h);
  196. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  197. RTSPMessageHeader *h, int pause_only);
  198. /* SDP handling */
  199. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  200. struct in_addr my_ip);
  201. /* RTP handling */
  202. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  203. FFServerStream *stream,
  204. const char *session_id,
  205. enum RTSPLowerTransport rtp_protocol);
  206. static int rtp_new_av_stream(HTTPContext *c,
  207. int stream_index, struct sockaddr_in *dest_addr,
  208. HTTPContext *rtsp_c);
  209. /* utils */
  210. static size_t htmlencode (const char *src, char **dest);
  211. static inline void cp_html_entity (char *buffer, const char *entity);
  212. static inline int check_codec_match(AVStream *ccf, AVStream *ccs, int stream);
  213. static const char *my_program_name;
  214. static int no_launch;
  215. static int need_to_start_children;
  216. /* maximum number of simultaneous HTTP connections */
  217. static unsigned int nb_connections;
  218. static uint64_t current_bandwidth;
  219. /* Making this global saves on passing it around everywhere */
  220. static int64_t cur_time;
  221. static AVLFG random_state;
  222. static FILE *logfile = NULL;
  223. static inline void cp_html_entity (char *buffer, const char *entity) {
  224. if (!buffer || !entity)
  225. return;
  226. while (*entity)
  227. *buffer++ = *entity++;
  228. }
  229. /**
  230. * Substitutes known conflicting chars on a text string with
  231. * their corresponding HTML entities.
  232. *
  233. * Returns the number of bytes in the 'encoded' representation
  234. * not including the terminating NUL.
  235. */
  236. static size_t htmlencode (const char *src, char **dest) {
  237. const char *amp = "&amp;";
  238. const char *lt = "&lt;";
  239. const char *gt = "&gt;";
  240. const char *start;
  241. char *tmp;
  242. size_t final_size = 0;
  243. if (!src)
  244. return 0;
  245. start = src;
  246. /* Compute needed dest size */
  247. while (*src != '\0') {
  248. switch(*src) {
  249. case 38: /* & */
  250. final_size += 5;
  251. break;
  252. case 60: /* < */
  253. case 62: /* > */
  254. final_size += 4;
  255. break;
  256. default:
  257. final_size++;
  258. }
  259. src++;
  260. }
  261. src = start;
  262. *dest = av_mallocz(final_size + 1);
  263. if (!*dest)
  264. return 0;
  265. /* Build dest */
  266. tmp = *dest;
  267. while (*src != '\0') {
  268. switch(*src) {
  269. case 38: /* & */
  270. cp_html_entity (tmp, amp);
  271. tmp += 5;
  272. break;
  273. case 60: /* < */
  274. cp_html_entity (tmp, lt);
  275. tmp += 4;
  276. break;
  277. case 62: /* > */
  278. cp_html_entity (tmp, gt);
  279. tmp += 4;
  280. break;
  281. default:
  282. *tmp = *src;
  283. tmp += 1;
  284. }
  285. src++;
  286. }
  287. *tmp = '\0';
  288. return final_size;
  289. }
  290. static int64_t ffm_read_write_index(int fd)
  291. {
  292. uint8_t buf[8];
  293. if (lseek(fd, 8, SEEK_SET) < 0)
  294. return AVERROR(EIO);
  295. if (read(fd, buf, 8) != 8)
  296. return AVERROR(EIO);
  297. return AV_RB64(buf);
  298. }
  299. static int ffm_write_write_index(int fd, int64_t pos)
  300. {
  301. uint8_t buf[8];
  302. int i;
  303. for(i=0;i<8;i++)
  304. buf[i] = (pos >> (56 - i * 8)) & 0xff;
  305. if (lseek(fd, 8, SEEK_SET) < 0)
  306. goto bail_eio;
  307. if (write(fd, buf, 8) != 8)
  308. goto bail_eio;
  309. return 8;
  310. bail_eio:
  311. return AVERROR(EIO);
  312. }
  313. static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
  314. int64_t file_size)
  315. {
  316. av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
  317. av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
  318. av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
  319. }
  320. static char *ctime1(char *buf2, size_t buf_size)
  321. {
  322. time_t ti;
  323. char *p;
  324. ti = time(NULL);
  325. p = ctime(&ti);
  326. if (!p || !*p) {
  327. *buf2 = '\0';
  328. return buf2;
  329. }
  330. av_strlcpy(buf2, p, buf_size);
  331. p = buf2 + strlen(buf2) - 1;
  332. if (*p == '\n')
  333. *p = '\0';
  334. return buf2;
  335. }
  336. static void http_vlog(const char *fmt, va_list vargs)
  337. {
  338. static int print_prefix = 1;
  339. char buf[32];
  340. if (!logfile)
  341. return;
  342. if (print_prefix) {
  343. ctime1(buf, sizeof(buf));
  344. fprintf(logfile, "%s ", buf);
  345. }
  346. print_prefix = strstr(fmt, "\n") != NULL;
  347. vfprintf(logfile, fmt, vargs);
  348. fflush(logfile);
  349. }
  350. #ifdef __GNUC__
  351. __attribute__ ((format (printf, 1, 2)))
  352. #endif
  353. static void http_log(const char *fmt, ...)
  354. {
  355. va_list vargs;
  356. va_start(vargs, fmt);
  357. http_vlog(fmt, vargs);
  358. va_end(vargs);
  359. }
  360. static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
  361. {
  362. static int print_prefix = 1;
  363. AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
  364. if (level > av_log_get_level())
  365. return;
  366. if (print_prefix && avc)
  367. http_log("[%s @ %p]", avc->item_name(ptr), ptr);
  368. print_prefix = strstr(fmt, "\n") != NULL;
  369. http_vlog(fmt, vargs);
  370. }
  371. static void log_connection(HTTPContext *c)
  372. {
  373. if (c->suppress_log)
  374. return;
  375. http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
  376. inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
  377. c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
  378. }
  379. static void update_datarate(DataRateData *drd, int64_t count)
  380. {
  381. if (!drd->time1 && !drd->count1) {
  382. drd->time1 = drd->time2 = cur_time;
  383. drd->count1 = drd->count2 = count;
  384. } else if (cur_time - drd->time2 > 5000) {
  385. drd->time1 = drd->time2;
  386. drd->count1 = drd->count2;
  387. drd->time2 = cur_time;
  388. drd->count2 = count;
  389. }
  390. }
  391. /* In bytes per second */
  392. static int compute_datarate(DataRateData *drd, int64_t count)
  393. {
  394. if (cur_time == drd->time1)
  395. return 0;
  396. return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
  397. }
  398. static void start_children(FFServerStream *feed)
  399. {
  400. char *pathname;
  401. char *slash;
  402. int i;
  403. size_t cmd_length;
  404. if (no_launch)
  405. return;
  406. cmd_length = strlen(my_program_name);
  407. /**
  408. * FIXME: WIP Safeguard. Remove after clearing all harcoded
  409. * '1024' path lengths
  410. */
  411. if (cmd_length > PATH_LENGTH - 1) {
  412. http_log("Could not start children. Command line: '%s' exceeds "
  413. "path length limit (%d)\n", my_program_name, PATH_LENGTH);
  414. return;
  415. }
  416. pathname = av_strdup (my_program_name);
  417. if (!pathname) {
  418. http_log("Could not allocate memory for children cmd line\n");
  419. return;
  420. }
  421. /* replace "ffserver" with "ffmpeg" in the path of current
  422. * program. Ignore user provided path */
  423. slash = strrchr(pathname, '/');
  424. if (!slash)
  425. slash = pathname;
  426. else
  427. slash++;
  428. strcpy(slash, "ffmpeg");
  429. for (; feed; feed = feed->next) {
  430. if (!feed->child_argv || feed->pid)
  431. continue;
  432. feed->pid_start = time(0);
  433. feed->pid = fork();
  434. if (feed->pid < 0) {
  435. http_log("Unable to create children: %s\n", strerror(errno));
  436. av_free (pathname);
  437. exit(EXIT_FAILURE);
  438. }
  439. if (feed->pid)
  440. continue;
  441. /* In child */
  442. http_log("Launch command line: ");
  443. http_log("%s ", pathname);
  444. for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
  445. http_log("%s ", feed->child_argv[i]);
  446. http_log("\n");
  447. for (i = 3; i < 256; i++)
  448. close(i);
  449. if (!config.debug) {
  450. if (!freopen("/dev/null", "r", stdin))
  451. http_log("failed to redirect STDIN to /dev/null\n;");
  452. if (!freopen("/dev/null", "w", stdout))
  453. http_log("failed to redirect STDOUT to /dev/null\n;");
  454. if (!freopen("/dev/null", "w", stderr))
  455. http_log("failed to redirect STDERR to /dev/null\n;");
  456. }
  457. signal(SIGPIPE, SIG_DFL);
  458. execvp(pathname, feed->child_argv);
  459. av_free (pathname);
  460. _exit(1);
  461. }
  462. av_free (pathname);
  463. }
  464. /* open a listening socket */
  465. static int socket_open_listen(struct sockaddr_in *my_addr)
  466. {
  467. int server_fd, tmp;
  468. server_fd = socket(AF_INET,SOCK_STREAM,0);
  469. if (server_fd < 0) {
  470. perror ("socket");
  471. return -1;
  472. }
  473. tmp = 1;
  474. if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
  475. av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
  476. my_addr->sin_family = AF_INET;
  477. if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
  478. char bindmsg[32];
  479. snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
  480. ntohs(my_addr->sin_port));
  481. perror (bindmsg);
  482. goto fail;
  483. }
  484. if (listen (server_fd, 5) < 0) {
  485. perror ("listen");
  486. goto fail;
  487. }
  488. if (ff_socket_nonblock(server_fd, 1) < 0)
  489. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  490. return server_fd;
  491. fail:
  492. closesocket(server_fd);
  493. return -1;
  494. }
  495. /* start all multicast streams */
  496. static void start_multicast(void)
  497. {
  498. FFServerStream *stream;
  499. char session_id[32];
  500. HTTPContext *rtp_c;
  501. struct sockaddr_in dest_addr = {0};
  502. int default_port, stream_index;
  503. unsigned int random0, random1;
  504. default_port = 6000;
  505. for(stream = config.first_stream; stream; stream = stream->next) {
  506. if (!stream->is_multicast)
  507. continue;
  508. random0 = av_lfg_get(&random_state);
  509. random1 = av_lfg_get(&random_state);
  510. /* open the RTP connection */
  511. snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
  512. /* choose a port if none given */
  513. if (stream->multicast_port == 0) {
  514. stream->multicast_port = default_port;
  515. default_port += 100;
  516. }
  517. dest_addr.sin_family = AF_INET;
  518. dest_addr.sin_addr = stream->multicast_ip;
  519. dest_addr.sin_port = htons(stream->multicast_port);
  520. rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
  521. RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  522. if (!rtp_c)
  523. continue;
  524. if (open_input_stream(rtp_c, "") < 0) {
  525. http_log("Could not open input stream for stream '%s'\n",
  526. stream->filename);
  527. continue;
  528. }
  529. /* open each RTP stream */
  530. for(stream_index = 0; stream_index < stream->nb_streams;
  531. stream_index++) {
  532. dest_addr.sin_port = htons(stream->multicast_port +
  533. 2 * stream_index);
  534. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
  535. continue;
  536. http_log("Could not open output stream '%s/streamid=%d'\n",
  537. stream->filename, stream_index);
  538. exit(1);
  539. }
  540. rtp_c->state = HTTPSTATE_SEND_DATA;
  541. }
  542. }
  543. /* main loop of the HTTP server */
  544. static int http_server(void)
  545. {
  546. int server_fd = 0, rtsp_server_fd = 0;
  547. int ret, delay;
  548. struct pollfd *poll_table, *poll_entry;
  549. HTTPContext *c, *c_next;
  550. poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
  551. sizeof(*poll_table));
  552. if(!poll_table) {
  553. http_log("Impossible to allocate a poll table handling %d "
  554. "connections.\n", config.nb_max_http_connections);
  555. return -1;
  556. }
  557. if (config.http_addr.sin_port) {
  558. server_fd = socket_open_listen(&config.http_addr);
  559. if (server_fd < 0)
  560. goto quit;
  561. }
  562. if (config.rtsp_addr.sin_port) {
  563. rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
  564. if (rtsp_server_fd < 0) {
  565. closesocket(server_fd);
  566. goto quit;
  567. }
  568. }
  569. if (!rtsp_server_fd && !server_fd) {
  570. http_log("HTTP and RTSP disabled.\n");
  571. goto quit;
  572. }
  573. http_log("FFserver started.\n");
  574. start_children(config.first_feed);
  575. start_multicast();
  576. for(;;) {
  577. poll_entry = poll_table;
  578. if (server_fd) {
  579. poll_entry->fd = server_fd;
  580. poll_entry->events = POLLIN;
  581. poll_entry++;
  582. }
  583. if (rtsp_server_fd) {
  584. poll_entry->fd = rtsp_server_fd;
  585. poll_entry->events = POLLIN;
  586. poll_entry++;
  587. }
  588. /* wait for events on each HTTP handle */
  589. c = first_http_ctx;
  590. delay = 1000;
  591. while (c) {
  592. int fd;
  593. fd = c->fd;
  594. switch(c->state) {
  595. case HTTPSTATE_SEND_HEADER:
  596. case RTSPSTATE_SEND_REPLY:
  597. case RTSPSTATE_SEND_PACKET:
  598. c->poll_entry = poll_entry;
  599. poll_entry->fd = fd;
  600. poll_entry->events = POLLOUT;
  601. poll_entry++;
  602. break;
  603. case HTTPSTATE_SEND_DATA_HEADER:
  604. case HTTPSTATE_SEND_DATA:
  605. case HTTPSTATE_SEND_DATA_TRAILER:
  606. if (!c->is_packetized) {
  607. /* for TCP, we output as much as we can
  608. * (may need to put a limit) */
  609. c->poll_entry = poll_entry;
  610. poll_entry->fd = fd;
  611. poll_entry->events = POLLOUT;
  612. poll_entry++;
  613. } else {
  614. /* when ffserver is doing the timing, we work by
  615. * looking at which packet needs to be sent every
  616. * 10 ms (one tick wait XXX: 10 ms assumed) */
  617. if (delay > 10)
  618. delay = 10;
  619. }
  620. break;
  621. case HTTPSTATE_WAIT_REQUEST:
  622. case HTTPSTATE_RECEIVE_DATA:
  623. case HTTPSTATE_WAIT_FEED:
  624. case RTSPSTATE_WAIT_REQUEST:
  625. /* need to catch errors */
  626. c->poll_entry = poll_entry;
  627. poll_entry->fd = fd;
  628. poll_entry->events = POLLIN;/* Maybe this will work */
  629. poll_entry++;
  630. break;
  631. default:
  632. c->poll_entry = NULL;
  633. break;
  634. }
  635. c = c->next;
  636. }
  637. /* wait for an event on one connection. We poll at least every
  638. * second to handle timeouts */
  639. do {
  640. ret = poll(poll_table, poll_entry - poll_table, delay);
  641. if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
  642. ff_neterrno() != AVERROR(EINTR)) {
  643. goto quit;
  644. }
  645. } while (ret < 0);
  646. cur_time = av_gettime() / 1000;
  647. if (need_to_start_children) {
  648. need_to_start_children = 0;
  649. start_children(config.first_feed);
  650. }
  651. /* now handle the events */
  652. for(c = first_http_ctx; c; c = c_next) {
  653. c_next = c->next;
  654. if (handle_connection(c) < 0) {
  655. log_connection(c);
  656. /* close and free the connection */
  657. close_connection(c);
  658. }
  659. }
  660. poll_entry = poll_table;
  661. if (server_fd) {
  662. /* new HTTP connection request ? */
  663. if (poll_entry->revents & POLLIN)
  664. new_connection(server_fd, 0);
  665. poll_entry++;
  666. }
  667. if (rtsp_server_fd) {
  668. /* new RTSP connection request ? */
  669. if (poll_entry->revents & POLLIN)
  670. new_connection(rtsp_server_fd, 1);
  671. }
  672. }
  673. quit:
  674. av_free(poll_table);
  675. return -1;
  676. }
  677. /* start waiting for a new HTTP/RTSP request */
  678. static void start_wait_request(HTTPContext *c, int is_rtsp)
  679. {
  680. c->buffer_ptr = c->buffer;
  681. c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
  682. c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
  683. c->timeout = cur_time +
  684. (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
  685. }
  686. static void http_send_too_busy_reply(int fd)
  687. {
  688. char buffer[400];
  689. int len = snprintf(buffer, sizeof(buffer),
  690. "HTTP/1.0 503 Server too busy\r\n"
  691. "Content-type: text/html\r\n"
  692. "\r\n"
  693. "<!DOCTYPE html>\n"
  694. "<html><head><title>Too busy</title></head><body>\r\n"
  695. "<p>The server is too busy to serve your request at "
  696. "this time.</p>\r\n"
  697. "<p>The number of current connections is %u, and this "
  698. "exceeds the limit of %u.</p>\r\n"
  699. "</body></html>\r\n",
  700. nb_connections, config.nb_max_connections);
  701. av_assert0(len < sizeof(buffer));
  702. if (send(fd, buffer, len, 0) < len)
  703. av_log(NULL, AV_LOG_WARNING,
  704. "Could not send too-busy reply, send() failed\n");
  705. }
  706. static void new_connection(int server_fd, int is_rtsp)
  707. {
  708. struct sockaddr_in from_addr;
  709. socklen_t len;
  710. int fd;
  711. HTTPContext *c = NULL;
  712. len = sizeof(from_addr);
  713. fd = accept(server_fd, (struct sockaddr *)&from_addr,
  714. &len);
  715. if (fd < 0) {
  716. http_log("error during accept %s\n", strerror(errno));
  717. return;
  718. }
  719. if (ff_socket_nonblock(fd, 1) < 0)
  720. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  721. if (nb_connections >= config.nb_max_connections) {
  722. http_send_too_busy_reply(fd);
  723. goto fail;
  724. }
  725. /* add a new connection */
  726. c = av_mallocz(sizeof(HTTPContext));
  727. if (!c)
  728. goto fail;
  729. c->fd = fd;
  730. c->poll_entry = NULL;
  731. c->from_addr = from_addr;
  732. c->buffer_size = IOBUFFER_INIT_SIZE;
  733. c->buffer = av_malloc(c->buffer_size);
  734. if (!c->buffer)
  735. goto fail;
  736. c->next = first_http_ctx;
  737. first_http_ctx = c;
  738. nb_connections++;
  739. start_wait_request(c, is_rtsp);
  740. return;
  741. fail:
  742. if (c) {
  743. av_freep(&c->buffer);
  744. av_free(c);
  745. }
  746. closesocket(fd);
  747. }
  748. static void close_connection(HTTPContext *c)
  749. {
  750. HTTPContext **cp, *c1;
  751. int i, nb_streams;
  752. AVFormatContext *ctx;
  753. AVStream *st;
  754. /* remove connection from list */
  755. cp = &first_http_ctx;
  756. while (*cp) {
  757. c1 = *cp;
  758. if (c1 == c)
  759. *cp = c->next;
  760. else
  761. cp = &c1->next;
  762. }
  763. /* remove references, if any (XXX: do it faster) */
  764. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  765. if (c1->rtsp_c == c)
  766. c1->rtsp_c = NULL;
  767. }
  768. /* remove connection associated resources */
  769. if (c->fd >= 0)
  770. closesocket(c->fd);
  771. if (c->fmt_in) {
  772. /* close each frame parser */
  773. for(i=0;i<c->fmt_in->nb_streams;i++) {
  774. st = c->fmt_in->streams[i];
  775. if (st->codec->codec)
  776. avcodec_close(st->codec);
  777. }
  778. avformat_close_input(&c->fmt_in);
  779. }
  780. /* free RTP output streams if any */
  781. nb_streams = 0;
  782. if (c->stream)
  783. nb_streams = c->stream->nb_streams;
  784. for(i=0;i<nb_streams;i++) {
  785. ctx = c->rtp_ctx[i];
  786. if (ctx) {
  787. av_write_trailer(ctx);
  788. av_dict_free(&ctx->metadata);
  789. av_freep(&ctx->streams[0]);
  790. av_freep(&ctx);
  791. }
  792. ffurl_close(c->rtp_handles[i]);
  793. }
  794. ctx = c->pfmt_ctx;
  795. if (ctx) {
  796. if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
  797. /* prepare header */
  798. if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
  799. av_write_trailer(ctx);
  800. av_freep(&c->pb_buffer);
  801. avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  802. }
  803. }
  804. for(i=0; i<ctx->nb_streams; i++)
  805. av_freep(&ctx->streams[i]);
  806. av_freep(&ctx->streams);
  807. av_freep(&ctx->priv_data);
  808. }
  809. if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
  810. current_bandwidth -= c->stream->bandwidth;
  811. /* signal that there is no feed if we are the feeder socket */
  812. if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
  813. c->stream->feed_opened = 0;
  814. close(c->feed_fd);
  815. }
  816. av_freep(&c->pb_buffer);
  817. av_freep(&c->packet_buffer);
  818. av_freep(&c->buffer);
  819. av_free(c);
  820. nb_connections--;
  821. }
  822. static int handle_connection(HTTPContext *c)
  823. {
  824. int len, ret;
  825. uint8_t *ptr;
  826. switch(c->state) {
  827. case HTTPSTATE_WAIT_REQUEST:
  828. case RTSPSTATE_WAIT_REQUEST:
  829. /* timeout ? */
  830. if ((c->timeout - cur_time) < 0)
  831. return -1;
  832. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  833. return -1;
  834. /* no need to read if no events */
  835. if (!(c->poll_entry->revents & POLLIN))
  836. return 0;
  837. /* read the data */
  838. read_loop:
  839. if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
  840. return -1;
  841. if (len < 0) {
  842. if (ff_neterrno() != AVERROR(EAGAIN) &&
  843. ff_neterrno() != AVERROR(EINTR))
  844. return -1;
  845. break;
  846. }
  847. /* search for end of request. */
  848. c->buffer_ptr += len;
  849. ptr = c->buffer_ptr;
  850. if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
  851. (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
  852. /* request found : parse it and reply */
  853. if (c->state == HTTPSTATE_WAIT_REQUEST)
  854. ret = http_parse_request(c);
  855. else
  856. ret = rtsp_parse_request(c);
  857. if (ret < 0)
  858. return -1;
  859. } else if (ptr >= c->buffer_end) {
  860. /* request too long: cannot do anything */
  861. return -1;
  862. } else goto read_loop;
  863. break;
  864. case HTTPSTATE_SEND_HEADER:
  865. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  866. return -1;
  867. /* no need to write if no events */
  868. if (!(c->poll_entry->revents & POLLOUT))
  869. return 0;
  870. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  871. if (len < 0) {
  872. if (ff_neterrno() != AVERROR(EAGAIN) &&
  873. ff_neterrno() != AVERROR(EINTR)) {
  874. goto close_connection;
  875. }
  876. break;
  877. }
  878. c->buffer_ptr += len;
  879. if (c->stream)
  880. c->stream->bytes_served += len;
  881. c->data_count += len;
  882. if (c->buffer_ptr >= c->buffer_end) {
  883. av_freep(&c->pb_buffer);
  884. /* if error, exit */
  885. if (c->http_error)
  886. return -1;
  887. /* all the buffer was sent : synchronize to the incoming
  888. * stream */
  889. c->state = HTTPSTATE_SEND_DATA_HEADER;
  890. c->buffer_ptr = c->buffer_end = c->buffer;
  891. }
  892. break;
  893. case HTTPSTATE_SEND_DATA:
  894. case HTTPSTATE_SEND_DATA_HEADER:
  895. case HTTPSTATE_SEND_DATA_TRAILER:
  896. /* for packetized output, we consider we can always write (the
  897. * input streams set the speed). It may be better to verify
  898. * that we do not rely too much on the kernel queues */
  899. if (!c->is_packetized) {
  900. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  901. return -1;
  902. /* no need to read if no events */
  903. if (!(c->poll_entry->revents & POLLOUT))
  904. return 0;
  905. }
  906. if (http_send_data(c) < 0)
  907. return -1;
  908. /* close connection if trailer sent */
  909. if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
  910. return -1;
  911. /* Check if it is a single jpeg frame 123 */
  912. if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
  913. close_connection(c);
  914. }
  915. break;
  916. case HTTPSTATE_RECEIVE_DATA:
  917. /* no need to read if no events */
  918. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  919. return -1;
  920. if (!(c->poll_entry->revents & POLLIN))
  921. return 0;
  922. if (http_receive_data(c) < 0)
  923. return -1;
  924. break;
  925. case HTTPSTATE_WAIT_FEED:
  926. /* no need to read if no events */
  927. if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
  928. return -1;
  929. /* nothing to do, we'll be waken up by incoming feed packets */
  930. break;
  931. case RTSPSTATE_SEND_REPLY:
  932. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  933. goto close_connection;
  934. /* no need to write if no events */
  935. if (!(c->poll_entry->revents & POLLOUT))
  936. return 0;
  937. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  938. if (len < 0) {
  939. if (ff_neterrno() != AVERROR(EAGAIN) &&
  940. ff_neterrno() != AVERROR(EINTR)) {
  941. goto close_connection;
  942. }
  943. break;
  944. }
  945. c->buffer_ptr += len;
  946. c->data_count += len;
  947. if (c->buffer_ptr >= c->buffer_end) {
  948. /* all the buffer was sent : wait for a new request */
  949. av_freep(&c->pb_buffer);
  950. start_wait_request(c, 1);
  951. }
  952. break;
  953. case RTSPSTATE_SEND_PACKET:
  954. if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
  955. av_freep(&c->packet_buffer);
  956. return -1;
  957. }
  958. /* no need to write if no events */
  959. if (!(c->poll_entry->revents & POLLOUT))
  960. return 0;
  961. len = send(c->fd, c->packet_buffer_ptr,
  962. c->packet_buffer_end - c->packet_buffer_ptr, 0);
  963. if (len < 0) {
  964. if (ff_neterrno() != AVERROR(EAGAIN) &&
  965. ff_neterrno() != AVERROR(EINTR)) {
  966. /* error : close connection */
  967. av_freep(&c->packet_buffer);
  968. return -1;
  969. }
  970. break;
  971. }
  972. c->packet_buffer_ptr += len;
  973. if (c->packet_buffer_ptr >= c->packet_buffer_end) {
  974. /* all the buffer was sent : wait for a new request */
  975. av_freep(&c->packet_buffer);
  976. c->state = RTSPSTATE_WAIT_REQUEST;
  977. }
  978. break;
  979. case HTTPSTATE_READY:
  980. /* nothing to do */
  981. break;
  982. default:
  983. return -1;
  984. }
  985. return 0;
  986. close_connection:
  987. av_freep(&c->pb_buffer);
  988. return -1;
  989. }
  990. static int extract_rates(char *rates, int ratelen, const char *request)
  991. {
  992. const char *p;
  993. for (p = request; *p && *p != '\r' && *p != '\n'; ) {
  994. if (av_strncasecmp(p, "Pragma:", 7) == 0) {
  995. const char *q = p + 7;
  996. while (*q && *q != '\n' && av_isspace(*q))
  997. q++;
  998. if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
  999. int stream_no;
  1000. int rate_no;
  1001. q += 20;
  1002. memset(rates, 0xff, ratelen);
  1003. while (1) {
  1004. while (*q && *q != '\n' && *q != ':')
  1005. q++;
  1006. if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
  1007. break;
  1008. stream_no--;
  1009. if (stream_no < ratelen && stream_no >= 0)
  1010. rates[stream_no] = rate_no;
  1011. while (*q && *q != '\n' && !av_isspace(*q))
  1012. q++;
  1013. }
  1014. return 1;
  1015. }
  1016. }
  1017. p = strchr(p, '\n');
  1018. if (!p)
  1019. break;
  1020. p++;
  1021. }
  1022. return 0;
  1023. }
  1024. static int find_stream_in_feed(FFServerStream *feed, AVCodecParameters *codec,
  1025. int bit_rate)
  1026. {
  1027. int i;
  1028. int best_bitrate = 100000000;
  1029. int best = -1;
  1030. for (i = 0; i < feed->nb_streams; i++) {
  1031. AVCodecParameters *feed_codec = feed->streams[i]->codecpar;
  1032. if (feed_codec->codec_id != codec->codec_id ||
  1033. feed_codec->sample_rate != codec->sample_rate ||
  1034. feed_codec->width != codec->width ||
  1035. feed_codec->height != codec->height)
  1036. continue;
  1037. /* Potential stream */
  1038. /* We want the fastest stream less than bit_rate, or the slowest
  1039. * faster than bit_rate
  1040. */
  1041. if (feed_codec->bit_rate <= bit_rate) {
  1042. if (best_bitrate > bit_rate ||
  1043. feed_codec->bit_rate > best_bitrate) {
  1044. best_bitrate = feed_codec->bit_rate;
  1045. best = i;
  1046. }
  1047. continue;
  1048. }
  1049. if (feed_codec->bit_rate < best_bitrate) {
  1050. best_bitrate = feed_codec->bit_rate;
  1051. best = i;
  1052. }
  1053. }
  1054. return best;
  1055. }
  1056. static int modify_current_stream(HTTPContext *c, char *rates)
  1057. {
  1058. int i;
  1059. FFServerStream *req = c->stream;
  1060. int action_required = 0;
  1061. /* Not much we can do for a feed */
  1062. if (!req->feed)
  1063. return 0;
  1064. for (i = 0; i < req->nb_streams; i++) {
  1065. AVCodecParameters *codec = req->streams[i]->codecpar;
  1066. switch(rates[i]) {
  1067. case 0:
  1068. c->switch_feed_streams[i] = req->feed_streams[i];
  1069. break;
  1070. case 1:
  1071. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
  1072. break;
  1073. case 2:
  1074. /* Wants off or slow */
  1075. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
  1076. #ifdef WANTS_OFF
  1077. /* This doesn't work well when it turns off the only stream! */
  1078. c->switch_feed_streams[i] = -2;
  1079. c->feed_streams[i] = -2;
  1080. #endif
  1081. break;
  1082. }
  1083. if (c->switch_feed_streams[i] >= 0 &&
  1084. c->switch_feed_streams[i] != c->feed_streams[i]) {
  1085. action_required = 1;
  1086. }
  1087. }
  1088. return action_required;
  1089. }
  1090. static void get_word(char *buf, int buf_size, const char **pp)
  1091. {
  1092. const char *p;
  1093. char *q;
  1094. #define SPACE_CHARS " \t\r\n"
  1095. p = *pp;
  1096. p += strspn(p, SPACE_CHARS);
  1097. q = buf;
  1098. while (!av_isspace(*p) && *p != '\0') {
  1099. if ((q - buf) < buf_size - 1)
  1100. *q++ = *p;
  1101. p++;
  1102. }
  1103. if (buf_size > 0)
  1104. *q = '\0';
  1105. *pp = p;
  1106. }
  1107. static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
  1108. HTTPContext *c)
  1109. {
  1110. FILE* f;
  1111. char line[1024];
  1112. char cmd[1024];
  1113. FFServerIPAddressACL *acl = NULL;
  1114. int line_num = 0;
  1115. const char *p;
  1116. f = fopen(stream->dynamic_acl, "r");
  1117. if (!f) {
  1118. perror(stream->dynamic_acl);
  1119. return NULL;
  1120. }
  1121. acl = av_mallocz(sizeof(FFServerIPAddressACL));
  1122. if (!acl) {
  1123. fclose(f);
  1124. return NULL;
  1125. }
  1126. /* Build ACL */
  1127. while (fgets(line, sizeof(line), f)) {
  1128. line_num++;
  1129. p = line;
  1130. while (av_isspace(*p))
  1131. p++;
  1132. if (*p == '\0' || *p == '#')
  1133. continue;
  1134. ffserver_get_arg(cmd, sizeof(cmd), &p);
  1135. if (!av_strcasecmp(cmd, "ACL"))
  1136. ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
  1137. line_num);
  1138. }
  1139. fclose(f);
  1140. return acl;
  1141. }
  1142. static void free_acl_list(FFServerIPAddressACL *in_acl)
  1143. {
  1144. FFServerIPAddressACL *pacl, *pacl2;
  1145. pacl = in_acl;
  1146. while(pacl) {
  1147. pacl2 = pacl;
  1148. pacl = pacl->next;
  1149. av_freep(pacl2);
  1150. }
  1151. }
  1152. static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
  1153. {
  1154. enum FFServerIPAddressAction last_action = IP_DENY;
  1155. FFServerIPAddressACL *acl;
  1156. struct in_addr *src = &c->from_addr.sin_addr;
  1157. unsigned long src_addr = src->s_addr;
  1158. for (acl = in_acl; acl; acl = acl->next) {
  1159. if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
  1160. return (acl->action == IP_ALLOW) ? 1 : 0;
  1161. last_action = acl->action;
  1162. }
  1163. /* Nothing matched, so return not the last action */
  1164. return (last_action == IP_DENY) ? 1 : 0;
  1165. }
  1166. static int validate_acl(FFServerStream *stream, HTTPContext *c)
  1167. {
  1168. int ret = 0;
  1169. FFServerIPAddressACL *acl;
  1170. /* if stream->acl is null validate_acl_list will return 1 */
  1171. ret = validate_acl_list(stream->acl, c);
  1172. if (stream->dynamic_acl[0]) {
  1173. acl = parse_dynamic_acl(stream, c);
  1174. ret = validate_acl_list(acl, c);
  1175. free_acl_list(acl);
  1176. }
  1177. return ret;
  1178. }
  1179. /**
  1180. * compute the real filename of a file by matching it without its
  1181. * extensions to all the stream's filenames
  1182. */
  1183. static void compute_real_filename(char *filename, int max_size)
  1184. {
  1185. char file1[1024];
  1186. char file2[1024];
  1187. char *p;
  1188. FFServerStream *stream;
  1189. av_strlcpy(file1, filename, sizeof(file1));
  1190. p = strrchr(file1, '.');
  1191. if (p)
  1192. *p = '\0';
  1193. for(stream = config.first_stream; stream; stream = stream->next) {
  1194. av_strlcpy(file2, stream->filename, sizeof(file2));
  1195. p = strrchr(file2, '.');
  1196. if (p)
  1197. *p = '\0';
  1198. if (!strcmp(file1, file2)) {
  1199. av_strlcpy(filename, stream->filename, max_size);
  1200. break;
  1201. }
  1202. }
  1203. }
  1204. enum RedirType {
  1205. REDIR_NONE,
  1206. REDIR_ASX,
  1207. REDIR_RAM,
  1208. REDIR_ASF,
  1209. REDIR_RTSP,
  1210. REDIR_SDP,
  1211. };
  1212. /* parse HTTP request and prepare header */
  1213. static int http_parse_request(HTTPContext *c)
  1214. {
  1215. const char *p;
  1216. char *p1;
  1217. enum RedirType redir_type;
  1218. char cmd[32];
  1219. char info[1024], filename[1024];
  1220. char url[1024], *q;
  1221. char protocol[32];
  1222. char msg[1024];
  1223. char *encoded_msg = NULL;
  1224. const char *mime_type;
  1225. FFServerStream *stream;
  1226. int i;
  1227. char ratebuf[32];
  1228. const char *useragent = 0;
  1229. p = c->buffer;
  1230. get_word(cmd, sizeof(cmd), &p);
  1231. av_strlcpy(c->method, cmd, sizeof(c->method));
  1232. if (!strcmp(cmd, "GET"))
  1233. c->post = 0;
  1234. else if (!strcmp(cmd, "POST"))
  1235. c->post = 1;
  1236. else
  1237. return -1;
  1238. get_word(url, sizeof(url), &p);
  1239. av_strlcpy(c->url, url, sizeof(c->url));
  1240. get_word(protocol, sizeof(protocol), (const char **)&p);
  1241. if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
  1242. return -1;
  1243. av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
  1244. if (config.debug)
  1245. http_log("%s - - New connection: %s %s\n",
  1246. inet_ntoa(c->from_addr.sin_addr), cmd, url);
  1247. /* find the filename and the optional info string in the request */
  1248. p1 = strchr(url, '?');
  1249. if (p1) {
  1250. av_strlcpy(info, p1, sizeof(info));
  1251. *p1 = '\0';
  1252. } else
  1253. info[0] = '\0';
  1254. av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
  1255. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1256. if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
  1257. useragent = p + 11;
  1258. if (*useragent && *useragent != '\n' && av_isspace(*useragent))
  1259. useragent++;
  1260. break;
  1261. }
  1262. p = strchr(p, '\n');
  1263. if (!p)
  1264. break;
  1265. p++;
  1266. }
  1267. redir_type = REDIR_NONE;
  1268. if (av_match_ext(filename, "asx")) {
  1269. redir_type = REDIR_ASX;
  1270. filename[strlen(filename)-1] = 'f';
  1271. } else if (av_match_ext(filename, "asf") &&
  1272. (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
  1273. /* if this isn't WMP or lookalike, return the redirector file */
  1274. redir_type = REDIR_ASF;
  1275. } else if (av_match_ext(filename, "rpm,ram")) {
  1276. redir_type = REDIR_RAM;
  1277. strcpy(filename + strlen(filename)-2, "m");
  1278. } else if (av_match_ext(filename, "rtsp")) {
  1279. redir_type = REDIR_RTSP;
  1280. compute_real_filename(filename, sizeof(filename) - 1);
  1281. } else if (av_match_ext(filename, "sdp")) {
  1282. redir_type = REDIR_SDP;
  1283. compute_real_filename(filename, sizeof(filename) - 1);
  1284. }
  1285. /* "redirect" request to index.html */
  1286. if (!strlen(filename))
  1287. av_strlcpy(filename, "index.html", sizeof(filename) - 1);
  1288. stream = config.first_stream;
  1289. while (stream) {
  1290. if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
  1291. break;
  1292. stream = stream->next;
  1293. }
  1294. if (!stream) {
  1295. snprintf(msg, sizeof(msg), "File '%s' not found", url);
  1296. http_log("File '%s' not found\n", url);
  1297. goto send_error;
  1298. }
  1299. c->stream = stream;
  1300. memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
  1301. memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
  1302. if (stream->stream_type == STREAM_TYPE_REDIRECT) {
  1303. c->http_error = 301;
  1304. q = c->buffer;
  1305. snprintf(q, c->buffer_size,
  1306. "HTTP/1.0 301 Moved\r\n"
  1307. "Location: %s\r\n"
  1308. "Content-type: text/html\r\n"
  1309. "\r\n"
  1310. "<!DOCTYPE html>\n"
  1311. "<html><head><title>Moved</title></head><body>\r\n"
  1312. "You should be <a href=\"%s\">redirected</a>.\r\n"
  1313. "</body></html>\r\n",
  1314. stream->feed_filename, stream->feed_filename);
  1315. q += strlen(q);
  1316. /* prepare output buffer */
  1317. c->buffer_ptr = c->buffer;
  1318. c->buffer_end = q;
  1319. c->state = HTTPSTATE_SEND_HEADER;
  1320. return 0;
  1321. }
  1322. /* If this is WMP, get the rate information */
  1323. if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
  1324. if (modify_current_stream(c, ratebuf)) {
  1325. for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
  1326. if (c->switch_feed_streams[i] >= 0)
  1327. c->switch_feed_streams[i] = -1;
  1328. }
  1329. }
  1330. }
  1331. if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
  1332. current_bandwidth += stream->bandwidth;
  1333. /* If already streaming this feed, do not let another feeder start */
  1334. if (stream->feed_opened) {
  1335. snprintf(msg, sizeof(msg), "This feed is already being received.");
  1336. http_log("Feed '%s' already being received\n", stream->feed_filename);
  1337. goto send_error;
  1338. }
  1339. if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
  1340. c->http_error = 503;
  1341. q = c->buffer;
  1342. snprintf(q, c->buffer_size,
  1343. "HTTP/1.0 503 Server too busy\r\n"
  1344. "Content-type: text/html\r\n"
  1345. "\r\n"
  1346. "<!DOCTYPE html>\n"
  1347. "<html><head><title>Too busy</title></head><body>\r\n"
  1348. "<p>The server is too busy to serve your request at "
  1349. "this time.</p>\r\n"
  1350. "<p>The bandwidth being served (including your stream) "
  1351. "is %"PRIu64"kbit/s, and this exceeds the limit of "
  1352. "%"PRIu64"kbit/s.</p>\r\n"
  1353. "</body></html>\r\n",
  1354. current_bandwidth, config.max_bandwidth);
  1355. q += strlen(q);
  1356. /* prepare output buffer */
  1357. c->buffer_ptr = c->buffer;
  1358. c->buffer_end = q;
  1359. c->state = HTTPSTATE_SEND_HEADER;
  1360. return 0;
  1361. }
  1362. if (redir_type != REDIR_NONE) {
  1363. const char *hostinfo = 0;
  1364. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1365. if (av_strncasecmp(p, "Host:", 5) == 0) {
  1366. hostinfo = p + 5;
  1367. break;
  1368. }
  1369. p = strchr(p, '\n');
  1370. if (!p)
  1371. break;
  1372. p++;
  1373. }
  1374. if (hostinfo) {
  1375. char *eoh;
  1376. char hostbuf[260];
  1377. while (av_isspace(*hostinfo))
  1378. hostinfo++;
  1379. eoh = strchr(hostinfo, '\n');
  1380. if (eoh) {
  1381. if (eoh[-1] == '\r')
  1382. eoh--;
  1383. if (eoh - hostinfo < sizeof(hostbuf) - 1) {
  1384. memcpy(hostbuf, hostinfo, eoh - hostinfo);
  1385. hostbuf[eoh - hostinfo] = 0;
  1386. c->http_error = 200;
  1387. q = c->buffer;
  1388. switch(redir_type) {
  1389. case REDIR_ASX:
  1390. snprintf(q, c->buffer_size,
  1391. "HTTP/1.0 200 ASX Follows\r\n"
  1392. "Content-type: video/x-ms-asf\r\n"
  1393. "\r\n"
  1394. "<ASX Version=\"3\">\r\n"
  1395. //"<!-- Autogenerated by ffserver -->\r\n"
  1396. "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
  1397. "</ASX>\r\n", hostbuf, filename, info);
  1398. q += strlen(q);
  1399. break;
  1400. case REDIR_RAM:
  1401. snprintf(q, c->buffer_size,
  1402. "HTTP/1.0 200 RAM Follows\r\n"
  1403. "Content-type: audio/x-pn-realaudio\r\n"
  1404. "\r\n"
  1405. "# Autogenerated by ffserver\r\n"
  1406. "http://%s/%s%s\r\n", hostbuf, filename, info);
  1407. q += strlen(q);
  1408. break;
  1409. case REDIR_ASF:
  1410. snprintf(q, c->buffer_size,
  1411. "HTTP/1.0 200 ASF Redirect follows\r\n"
  1412. "Content-type: video/x-ms-asf\r\n"
  1413. "\r\n"
  1414. "[Reference]\r\n"
  1415. "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
  1416. q += strlen(q);
  1417. break;
  1418. case REDIR_RTSP:
  1419. {
  1420. char hostname[256], *p;
  1421. /* extract only hostname */
  1422. av_strlcpy(hostname, hostbuf, sizeof(hostname));
  1423. p = strrchr(hostname, ':');
  1424. if (p)
  1425. *p = '\0';
  1426. snprintf(q, c->buffer_size,
  1427. "HTTP/1.0 200 RTSP Redirect follows\r\n"
  1428. /* XXX: incorrect MIME type ? */
  1429. "Content-type: application/x-rtsp\r\n"
  1430. "\r\n"
  1431. "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
  1432. q += strlen(q);
  1433. }
  1434. break;
  1435. case REDIR_SDP:
  1436. {
  1437. uint8_t *sdp_data;
  1438. int sdp_data_size;
  1439. socklen_t len;
  1440. struct sockaddr_in my_addr;
  1441. snprintf(q, c->buffer_size,
  1442. "HTTP/1.0 200 OK\r\n"
  1443. "Content-type: application/sdp\r\n"
  1444. "\r\n");
  1445. q += strlen(q);
  1446. len = sizeof(my_addr);
  1447. /* XXX: Should probably fail? */
  1448. if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
  1449. http_log("getsockname() failed\n");
  1450. /* XXX: should use a dynamic buffer */
  1451. sdp_data_size = prepare_sdp_description(stream,
  1452. &sdp_data,
  1453. my_addr.sin_addr);
  1454. if (sdp_data_size > 0) {
  1455. memcpy(q, sdp_data, sdp_data_size);
  1456. q += sdp_data_size;
  1457. *q = '\0';
  1458. av_freep(&sdp_data);
  1459. }
  1460. }
  1461. break;
  1462. default:
  1463. abort();
  1464. break;
  1465. }
  1466. /* prepare output buffer */
  1467. c->buffer_ptr = c->buffer;
  1468. c->buffer_end = q;
  1469. c->state = HTTPSTATE_SEND_HEADER;
  1470. return 0;
  1471. }
  1472. }
  1473. }
  1474. snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
  1475. goto send_error;
  1476. }
  1477. stream->conns_served++;
  1478. /* XXX: add there authenticate and IP match */
  1479. if (c->post) {
  1480. /* if post, it means a feed is being sent */
  1481. if (!stream->is_feed) {
  1482. /* However it might be a status report from WMP! Let us log the
  1483. * data as it might come handy one day. */
  1484. const char *logline = 0;
  1485. int client_id = 0;
  1486. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1487. if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
  1488. logline = p;
  1489. break;
  1490. }
  1491. if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
  1492. client_id = strtol(p + 18, 0, 10);
  1493. p = strchr(p, '\n');
  1494. if (!p)
  1495. break;
  1496. p++;
  1497. }
  1498. if (logline) {
  1499. char *eol = strchr(logline, '\n');
  1500. logline += 17;
  1501. if (eol) {
  1502. if (eol[-1] == '\r')
  1503. eol--;
  1504. http_log("%.*s\n", (int) (eol - logline), logline);
  1505. c->suppress_log = 1;
  1506. }
  1507. }
  1508. #ifdef DEBUG
  1509. http_log("\nGot request:\n%s\n", c->buffer);
  1510. #endif
  1511. if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
  1512. HTTPContext *wmpc;
  1513. /* Now we have to find the client_id */
  1514. for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
  1515. if (wmpc->wmp_client_id == client_id)
  1516. break;
  1517. }
  1518. if (wmpc && modify_current_stream(wmpc, ratebuf))
  1519. wmpc->switch_pending = 1;
  1520. }
  1521. snprintf(msg, sizeof(msg), "POST command not handled");
  1522. c->stream = 0;
  1523. goto send_error;
  1524. }
  1525. if (http_start_receive_data(c) < 0) {
  1526. snprintf(msg, sizeof(msg), "could not open feed");
  1527. goto send_error;
  1528. }
  1529. c->http_error = 0;
  1530. c->state = HTTPSTATE_RECEIVE_DATA;
  1531. return 0;
  1532. }
  1533. #ifdef DEBUG
  1534. if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
  1535. http_log("\nGot request:\n%s\n", c->buffer);
  1536. #endif
  1537. if (c->stream->stream_type == STREAM_TYPE_STATUS)
  1538. goto send_status;
  1539. /* open input stream */
  1540. if (open_input_stream(c, info) < 0) {
  1541. snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
  1542. goto send_error;
  1543. }
  1544. /* prepare HTTP header */
  1545. c->buffer[0] = 0;
  1546. av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
  1547. mime_type = c->stream->fmt->mime_type;
  1548. if (!mime_type)
  1549. mime_type = "application/x-octet-stream";
  1550. av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
  1551. /* for asf, we need extra headers */
  1552. if (!strcmp(c->stream->fmt->name,"asf_stream")) {
  1553. /* Need to allocate a client id */
  1554. c->wmp_client_id = av_lfg_get(&random_state);
  1555. av_strlcatf(c->buffer, c->buffer_size, "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);
  1556. }
  1557. av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
  1558. av_strlcatf(c->buffer, c->buffer_size, "\r\n");
  1559. q = c->buffer + strlen(c->buffer);
  1560. /* prepare output buffer */
  1561. c->http_error = 0;
  1562. c->buffer_ptr = c->buffer;
  1563. c->buffer_end = q;
  1564. c->state = HTTPSTATE_SEND_HEADER;
  1565. return 0;
  1566. send_error:
  1567. c->http_error = 404;
  1568. q = c->buffer;
  1569. if (!htmlencode(msg, &encoded_msg)) {
  1570. http_log("Could not encode filename '%s' as HTML\n", msg);
  1571. }
  1572. snprintf(q, c->buffer_size,
  1573. "HTTP/1.0 404 Not Found\r\n"
  1574. "Content-type: text/html\r\n"
  1575. "\r\n"
  1576. "<!DOCTYPE html>\n"
  1577. "<html>\n"
  1578. "<head>\n"
  1579. "<meta charset=\"UTF-8\">\n"
  1580. "<title>404 Not Found</title>\n"
  1581. "</head>\n"
  1582. "<body>%s</body>\n"
  1583. "</html>\n", encoded_msg? encoded_msg : "File not found");
  1584. q += strlen(q);
  1585. /* prepare output buffer */
  1586. c->buffer_ptr = c->buffer;
  1587. c->buffer_end = q;
  1588. c->state = HTTPSTATE_SEND_HEADER;
  1589. av_freep(&encoded_msg);
  1590. return 0;
  1591. send_status:
  1592. compute_status(c);
  1593. /* horrible: we use this value to avoid
  1594. * going to the send data state */
  1595. c->http_error = 200;
  1596. c->state = HTTPSTATE_SEND_HEADER;
  1597. return 0;
  1598. }
  1599. static void fmt_bytecount(AVIOContext *pb, int64_t count)
  1600. {
  1601. static const char suffix[] = " kMGTP";
  1602. const char *s;
  1603. for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
  1604. avio_printf(pb, "%"PRId64"%c", count, *s);
  1605. }
  1606. static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
  1607. {
  1608. int i, stream_no;
  1609. const char *type = "unknown";
  1610. char parameters[64];
  1611. AVStream *st;
  1612. AVCodec *codec;
  1613. stream_no = stream->nb_streams;
  1614. avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
  1615. "type<th>kbit/s<th align=left>codec<th align=left>"
  1616. "Parameters\n");
  1617. for (i = 0; i < stream_no; i++) {
  1618. st = stream->streams[i];
  1619. codec = avcodec_find_encoder(st->codecpar->codec_id);
  1620. parameters[0] = 0;
  1621. switch(st->codecpar->codec_type) {
  1622. case AVMEDIA_TYPE_AUDIO:
  1623. type = "audio";
  1624. snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
  1625. st->codecpar->channels, st->codecpar->sample_rate);
  1626. break;
  1627. case AVMEDIA_TYPE_VIDEO:
  1628. type = "video";
  1629. snprintf(parameters, sizeof(parameters),
  1630. "%dx%d, q=%d-%d, fps=%d", st->codecpar->width,
  1631. st->codecpar->height, st->codec->qmin, st->codec->qmax,
  1632. st->time_base.den / st->time_base.num);
  1633. break;
  1634. default:
  1635. abort();
  1636. }
  1637. avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
  1638. "<td>%s<td>%s\n",
  1639. i, type, (int64_t)st->codecpar->bit_rate/1000,
  1640. codec ? codec->name : "", parameters);
  1641. }
  1642. avio_printf(pb, "</table>\n");
  1643. }
  1644. static void compute_status(HTTPContext *c)
  1645. {
  1646. HTTPContext *c1;
  1647. FFServerStream *stream;
  1648. char *p;
  1649. time_t ti;
  1650. int i, len;
  1651. AVIOContext *pb;
  1652. if (avio_open_dyn_buf(&pb) < 0) {
  1653. /* XXX: return an error ? */
  1654. c->buffer_ptr = c->buffer;
  1655. c->buffer_end = c->buffer;
  1656. return;
  1657. }
  1658. avio_printf(pb, "HTTP/1.0 200 OK\r\n");
  1659. avio_printf(pb, "Content-type: text/html\r\n");
  1660. avio_printf(pb, "Pragma: no-cache\r\n");
  1661. avio_printf(pb, "\r\n");
  1662. avio_printf(pb, "<!DOCTYPE html>\n");
  1663. avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
  1664. if (c->stream->feed_filename[0])
  1665. avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
  1666. c->stream->feed_filename);
  1667. avio_printf(pb, "</head>\n<body>");
  1668. avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
  1669. /* format status */
  1670. avio_printf(pb, "<h2>Available Streams</h2>\n");
  1671. avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
  1672. avio_printf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbit/s<th align=left>Video<br>kbit/s<th><br>Codec<th align=left>Audio<br>kbit/s<th><br>Codec<th align=left valign=top>Feed\n");
  1673. stream = config.first_stream;
  1674. while (stream) {
  1675. char sfilename[1024];
  1676. char *eosf;
  1677. if (stream->feed == stream) {
  1678. stream = stream->next;
  1679. continue;
  1680. }
  1681. av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
  1682. eosf = sfilename + strlen(sfilename);
  1683. if (eosf - sfilename >= 4) {
  1684. if (strcmp(eosf - 4, ".asf") == 0)
  1685. strcpy(eosf - 4, ".asx");
  1686. else if (strcmp(eosf - 3, ".rm") == 0)
  1687. strcpy(eosf - 3, ".ram");
  1688. else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
  1689. /* generate a sample RTSP director if
  1690. * unicast. Generate an SDP redirector if
  1691. * multicast */
  1692. eosf = strrchr(sfilename, '.');
  1693. if (!eosf)
  1694. eosf = sfilename + strlen(sfilename);
  1695. if (stream->is_multicast)
  1696. strcpy(eosf, ".sdp");
  1697. else
  1698. strcpy(eosf, ".rtsp");
  1699. }
  1700. }
  1701. avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
  1702. sfilename, stream->filename);
  1703. avio_printf(pb, "<td align=right> %d <td align=right> ",
  1704. stream->conns_served);
  1705. fmt_bytecount(pb, stream->bytes_served);
  1706. switch(stream->stream_type) {
  1707. case STREAM_TYPE_LIVE: {
  1708. int audio_bit_rate = 0;
  1709. int video_bit_rate = 0;
  1710. const char *audio_codec_name = "";
  1711. const char *video_codec_name = "";
  1712. const char *audio_codec_name_extra = "";
  1713. const char *video_codec_name_extra = "";
  1714. for(i=0;i<stream->nb_streams;i++) {
  1715. AVStream *st = stream->streams[i];
  1716. AVCodec *codec = avcodec_find_encoder(st->codecpar->codec_id);
  1717. switch(st->codecpar->codec_type) {
  1718. case AVMEDIA_TYPE_AUDIO:
  1719. audio_bit_rate += st->codecpar->bit_rate;
  1720. if (codec) {
  1721. if (*audio_codec_name)
  1722. audio_codec_name_extra = "...";
  1723. audio_codec_name = codec->name;
  1724. }
  1725. break;
  1726. case AVMEDIA_TYPE_VIDEO:
  1727. video_bit_rate += st->codecpar->bit_rate;
  1728. if (codec) {
  1729. if (*video_codec_name)
  1730. video_codec_name_extra = "...";
  1731. video_codec_name = codec->name;
  1732. }
  1733. break;
  1734. case AVMEDIA_TYPE_DATA:
  1735. video_bit_rate += st->codecpar->bit_rate;
  1736. break;
  1737. default:
  1738. abort();
  1739. }
  1740. }
  1741. avio_printf(pb, "<td align=center> %s <td align=right> %d "
  1742. "<td align=right> %d <td> %s %s <td align=right> "
  1743. "%d <td> %s %s",
  1744. stream->fmt->name, stream->bandwidth,
  1745. video_bit_rate / 1000, video_codec_name,
  1746. video_codec_name_extra, audio_bit_rate / 1000,
  1747. audio_codec_name, audio_codec_name_extra);
  1748. if (stream->feed)
  1749. avio_printf(pb, "<td>%s", stream->feed->filename);
  1750. else
  1751. avio_printf(pb, "<td>%s", stream->feed_filename);
  1752. avio_printf(pb, "\n");
  1753. }
  1754. break;
  1755. default:
  1756. avio_printf(pb, "<td align=center> - <td align=right> - "
  1757. "<td align=right> - <td><td align=right> - <td>\n");
  1758. break;
  1759. }
  1760. stream = stream->next;
  1761. }
  1762. avio_printf(pb, "</table>\n");
  1763. stream = config.first_stream;
  1764. while (stream) {
  1765. if (stream->feed != stream) {
  1766. stream = stream->next;
  1767. continue;
  1768. }
  1769. avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
  1770. if (stream->pid) {
  1771. avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
  1772. #if defined(linux)
  1773. {
  1774. FILE *pid_stat;
  1775. char ps_cmd[64];
  1776. /* This is somewhat linux specific I guess */
  1777. snprintf(ps_cmd, sizeof(ps_cmd),
  1778. "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
  1779. (int64_t) stream->pid);
  1780. pid_stat = popen(ps_cmd, "r");
  1781. if (pid_stat) {
  1782. char cpuperc[10];
  1783. char cpuused[64];
  1784. if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
  1785. avio_printf(pb, "Currently using %s%% of the cpu. "
  1786. "Total time used %s.\n",
  1787. cpuperc, cpuused);
  1788. }
  1789. fclose(pid_stat);
  1790. }
  1791. }
  1792. #endif
  1793. avio_printf(pb, "<p>");
  1794. }
  1795. print_stream_params(pb, stream);
  1796. stream = stream->next;
  1797. }
  1798. /* connection status */
  1799. avio_printf(pb, "<h2>Connection Status</h2>\n");
  1800. avio_printf(pb, "Number of connections: %d / %d<br>\n",
  1801. nb_connections, config.nb_max_connections);
  1802. avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
  1803. current_bandwidth, config.max_bandwidth);
  1804. avio_printf(pb, "<table>\n");
  1805. avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
  1806. "bit/s<th>Actual bit/s<th>Bytes transferred\n");
  1807. c1 = first_http_ctx;
  1808. i = 0;
  1809. while (c1) {
  1810. int bitrate;
  1811. int j;
  1812. bitrate = 0;
  1813. if (c1->stream) {
  1814. for (j = 0; j < c1->stream->nb_streams; j++) {
  1815. if (!c1->stream->feed)
  1816. bitrate += c1->stream->streams[j]->codecpar->bit_rate;
  1817. else if (c1->feed_streams[j] >= 0)
  1818. bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codecpar->bit_rate;
  1819. }
  1820. }
  1821. i++;
  1822. p = inet_ntoa(c1->from_addr.sin_addr);
  1823. avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
  1824. "<td align=right>",
  1825. i, c1->stream ? c1->stream->filename : "",
  1826. c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
  1827. c1->protocol, http_state[c1->state]);
  1828. fmt_bytecount(pb, bitrate);
  1829. avio_printf(pb, "<td align=right>");
  1830. fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
  1831. avio_printf(pb, "<td align=right>");
  1832. fmt_bytecount(pb, c1->data_count);
  1833. avio_printf(pb, "\n");
  1834. c1 = c1->next;
  1835. }
  1836. avio_printf(pb, "</table>\n");
  1837. /* date */
  1838. ti = time(NULL);
  1839. p = ctime(&ti);
  1840. avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
  1841. avio_printf(pb, "</body>\n</html>\n");
  1842. len = avio_close_dyn_buf(pb, &c->pb_buffer);
  1843. c->buffer_ptr = c->pb_buffer;
  1844. c->buffer_end = c->pb_buffer + len;
  1845. }
  1846. static int open_input_stream(HTTPContext *c, const char *info)
  1847. {
  1848. char buf[128];
  1849. char input_filename[1024];
  1850. AVFormatContext *s = NULL;
  1851. int buf_size, i, ret;
  1852. int64_t stream_pos;
  1853. /* find file name */
  1854. if (c->stream->feed) {
  1855. strcpy(input_filename, c->stream->feed->feed_filename);
  1856. buf_size = FFM_PACKET_SIZE;
  1857. /* compute position (absolute time) */
  1858. if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
  1859. if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
  1860. http_log("Invalid date specification '%s' for stream\n", buf);
  1861. return ret;
  1862. }
  1863. } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
  1864. int prebuffer = strtol(buf, 0, 10);
  1865. stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
  1866. } else
  1867. stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
  1868. } else {
  1869. strcpy(input_filename, c->stream->feed_filename);
  1870. buf_size = 0;
  1871. /* compute position (relative time) */
  1872. if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
  1873. if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
  1874. http_log("Invalid date specification '%s' for stream\n", buf);
  1875. return ret;
  1876. }
  1877. } else
  1878. stream_pos = 0;
  1879. }
  1880. if (!input_filename[0]) {
  1881. http_log("No filename was specified for stream\n");
  1882. return AVERROR(EINVAL);
  1883. }
  1884. /* open stream */
  1885. ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
  1886. &c->stream->in_opts);
  1887. if (ret < 0) {
  1888. http_log("Could not open input '%s': %s\n",
  1889. input_filename, av_err2str(ret));
  1890. return ret;
  1891. }
  1892. /* set buffer size */
  1893. if (buf_size > 0) {
  1894. ret = ffio_set_buf_size(s->pb, buf_size);
  1895. if (ret < 0) {
  1896. http_log("Failed to set buffer size\n");
  1897. return ret;
  1898. }
  1899. }
  1900. s->flags |= AVFMT_FLAG_GENPTS;
  1901. c->fmt_in = s;
  1902. if (strcmp(s->iformat->name, "ffm") &&
  1903. (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
  1904. http_log("Could not find stream info for input '%s'\n", input_filename);
  1905. avformat_close_input(&s);
  1906. return ret;
  1907. }
  1908. /* choose stream as clock source (we favor the video stream if
  1909. * present) for packet sending */
  1910. c->pts_stream_index = 0;
  1911. for(i=0;i<c->stream->nb_streams;i++) {
  1912. if (c->pts_stream_index == 0 &&
  1913. c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1914. c->pts_stream_index = i;
  1915. }
  1916. }
  1917. if (c->fmt_in->iformat->read_seek)
  1918. av_seek_frame(c->fmt_in, -1, stream_pos, 0);
  1919. /* set the start time (needed for maxtime and RTP packet timing) */
  1920. c->start_time = cur_time;
  1921. c->first_pts = AV_NOPTS_VALUE;
  1922. return 0;
  1923. }
  1924. /* return the server clock (in us) */
  1925. static int64_t get_server_clock(HTTPContext *c)
  1926. {
  1927. /* compute current pts value from system time */
  1928. return (cur_time - c->start_time) * 1000;
  1929. }
  1930. /* return the estimated time (in us) at which the current packet must be sent */
  1931. static int64_t get_packet_send_clock(HTTPContext *c)
  1932. {
  1933. int bytes_left, bytes_sent, frame_bytes;
  1934. frame_bytes = c->cur_frame_bytes;
  1935. if (frame_bytes <= 0)
  1936. return c->cur_pts;
  1937. bytes_left = c->buffer_end - c->buffer_ptr;
  1938. bytes_sent = frame_bytes - bytes_left;
  1939. return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
  1940. }
  1941. static int http_prepare_data(HTTPContext *c)
  1942. {
  1943. int i, len, ret;
  1944. AVFormatContext *ctx;
  1945. av_freep(&c->pb_buffer);
  1946. switch(c->state) {
  1947. case HTTPSTATE_SEND_DATA_HEADER:
  1948. ctx = avformat_alloc_context();
  1949. if (!ctx)
  1950. return AVERROR(ENOMEM);
  1951. c->pfmt_ctx = ctx;
  1952. av_dict_copy(&(c->pfmt_ctx->metadata), c->stream->metadata, 0);
  1953. c->pfmt_ctx->streams = av_mallocz_array(c->stream->nb_streams,
  1954. sizeof(AVStream *));
  1955. if (!c->pfmt_ctx->streams)
  1956. return AVERROR(ENOMEM);
  1957. for(i=0;i<c->stream->nb_streams;i++) {
  1958. AVStream *src;
  1959. c->pfmt_ctx->streams[i] = av_mallocz(sizeof(AVStream));
  1960. /* if file or feed, then just take streams from FFServerStream
  1961. * struct */
  1962. if (!c->stream->feed ||
  1963. c->stream->feed == c->stream)
  1964. src = c->stream->streams[i];
  1965. else
  1966. src = c->stream->feed->streams[c->stream->feed_streams[i]];
  1967. *(c->pfmt_ctx->streams[i]) = *src;
  1968. c->pfmt_ctx->streams[i]->priv_data = 0;
  1969. /* XXX: should be done in AVStream, not in codec */
  1970. c->pfmt_ctx->streams[i]->codec->frame_number = 0;
  1971. }
  1972. /* set output format parameters */
  1973. c->pfmt_ctx->oformat = c->stream->fmt;
  1974. c->pfmt_ctx->nb_streams = c->stream->nb_streams;
  1975. c->got_key_frame = 0;
  1976. /* prepare header and save header data in a stream */
  1977. if (avio_open_dyn_buf(&c->pfmt_ctx->pb) < 0) {
  1978. /* XXX: potential leak */
  1979. return -1;
  1980. }
  1981. c->pfmt_ctx->pb->seekable = 0;
  1982. /*
  1983. * HACK to avoid MPEG-PS muxer to spit many underflow errors
  1984. * Default value from FFmpeg
  1985. * Try to set it using configuration option
  1986. */
  1987. c->pfmt_ctx->max_delay = (int)(0.7*AV_TIME_BASE);
  1988. if ((ret = avformat_write_header(c->pfmt_ctx, NULL)) < 0) {
  1989. http_log("Error writing output header for stream '%s': %s\n",
  1990. c->stream->filename, av_err2str(ret));
  1991. return ret;
  1992. }
  1993. av_dict_free(&c->pfmt_ctx->metadata);
  1994. len = avio_close_dyn_buf(c->pfmt_ctx->pb, &c->pb_buffer);
  1995. c->buffer_ptr = c->pb_buffer;
  1996. c->buffer_end = c->pb_buffer + len;
  1997. c->state = HTTPSTATE_SEND_DATA;
  1998. c->last_packet_sent = 0;
  1999. break;
  2000. case HTTPSTATE_SEND_DATA:
  2001. /* find a new packet */
  2002. /* read a packet from the input stream */
  2003. if (c->stream->feed)
  2004. ffm_set_write_index(c->fmt_in,
  2005. c->stream->feed->feed_write_index,
  2006. c->stream->feed->feed_size);
  2007. if (c->stream->max_time &&
  2008. c->stream->max_time + c->start_time - cur_time < 0)
  2009. /* We have timed out */
  2010. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2011. else {
  2012. AVPacket pkt;
  2013. redo:
  2014. ret = av_read_frame(c->fmt_in, &pkt);
  2015. if (ret < 0) {
  2016. if (c->stream->feed) {
  2017. /* if coming from feed, it means we reached the end of the
  2018. * ffm file, so must wait for more data */
  2019. c->state = HTTPSTATE_WAIT_FEED;
  2020. return 1; /* state changed */
  2021. }
  2022. if (ret == AVERROR(EAGAIN)) {
  2023. /* input not ready, come back later */
  2024. return 0;
  2025. }
  2026. if (c->stream->loop) {
  2027. avformat_close_input(&c->fmt_in);
  2028. if (open_input_stream(c, "") < 0)
  2029. goto no_loop;
  2030. goto redo;
  2031. } else {
  2032. no_loop:
  2033. /* must send trailer now because EOF or error */
  2034. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2035. }
  2036. } else {
  2037. int source_index = pkt.stream_index;
  2038. /* update first pts if needed */
  2039. if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
  2040. c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
  2041. c->start_time = cur_time;
  2042. }
  2043. /* send it to the appropriate stream */
  2044. if (c->stream->feed) {
  2045. /* if coming from a feed, select the right stream */
  2046. if (c->switch_pending) {
  2047. c->switch_pending = 0;
  2048. for(i=0;i<c->stream->nb_streams;i++) {
  2049. if (c->switch_feed_streams[i] == pkt.stream_index)
  2050. if (pkt.flags & AV_PKT_FLAG_KEY)
  2051. c->switch_feed_streams[i] = -1;
  2052. if (c->switch_feed_streams[i] >= 0)
  2053. c->switch_pending = 1;
  2054. }
  2055. }
  2056. for(i=0;i<c->stream->nb_streams;i++) {
  2057. if (c->stream->feed_streams[i] == pkt.stream_index) {
  2058. AVStream *st = c->fmt_in->streams[source_index];
  2059. pkt.stream_index = i;
  2060. if (pkt.flags & AV_PKT_FLAG_KEY &&
  2061. (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  2062. c->stream->nb_streams == 1))
  2063. c->got_key_frame = 1;
  2064. if (!c->stream->send_on_key || c->got_key_frame)
  2065. goto send_it;
  2066. }
  2067. }
  2068. } else {
  2069. AVCodecContext *codec;
  2070. AVStream *ist, *ost;
  2071. send_it:
  2072. ist = c->fmt_in->streams[source_index];
  2073. /* specific handling for RTP: we use several
  2074. * output streams (one for each RTP connection).
  2075. * XXX: need more abstract handling */
  2076. if (c->is_packetized) {
  2077. /* compute send time and duration */
  2078. if (pkt.dts != AV_NOPTS_VALUE) {
  2079. c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
  2080. c->cur_pts -= c->first_pts;
  2081. }
  2082. c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
  2083. /* find RTP context */
  2084. c->packet_stream_index = pkt.stream_index;
  2085. ctx = c->rtp_ctx[c->packet_stream_index];
  2086. if(!ctx) {
  2087. av_packet_unref(&pkt);
  2088. break;
  2089. }
  2090. codec = ctx->streams[0]->codec;
  2091. /* only one stream per RTP connection */
  2092. pkt.stream_index = 0;
  2093. } else {
  2094. ctx = c->pfmt_ctx;
  2095. /* Fudge here */
  2096. codec = ctx->streams[pkt.stream_index]->codec;
  2097. }
  2098. if (c->is_packetized) {
  2099. int max_packet_size;
  2100. if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
  2101. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  2102. else
  2103. max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
  2104. ret = ffio_open_dyn_packet_buf(&ctx->pb,
  2105. max_packet_size);
  2106. } else
  2107. ret = avio_open_dyn_buf(&ctx->pb);
  2108. if (ret < 0) {
  2109. /* XXX: potential leak */
  2110. return -1;
  2111. }
  2112. ost = ctx->streams[pkt.stream_index];
  2113. ctx->pb->seekable = 0;
  2114. if (pkt.dts != AV_NOPTS_VALUE)
  2115. pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
  2116. ost->time_base);
  2117. if (pkt.pts != AV_NOPTS_VALUE)
  2118. pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
  2119. ost->time_base);
  2120. pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
  2121. ost->time_base);
  2122. if ((ret = av_write_frame(ctx, &pkt)) < 0) {
  2123. http_log("Error writing frame to output for stream '%s': %s\n",
  2124. c->stream->filename, av_err2str(ret));
  2125. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2126. }
  2127. av_freep(&c->pb_buffer);
  2128. len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  2129. ctx->pb = NULL;
  2130. c->cur_frame_bytes = len;
  2131. c->buffer_ptr = c->pb_buffer;
  2132. c->buffer_end = c->pb_buffer + len;
  2133. codec->frame_number++;
  2134. if (len == 0) {
  2135. av_packet_unref(&pkt);
  2136. goto redo;
  2137. }
  2138. }
  2139. av_packet_unref(&pkt);
  2140. }
  2141. }
  2142. break;
  2143. default:
  2144. case HTTPSTATE_SEND_DATA_TRAILER:
  2145. /* last packet test ? */
  2146. if (c->last_packet_sent || c->is_packetized)
  2147. return -1;
  2148. ctx = c->pfmt_ctx;
  2149. /* prepare header */
  2150. if (avio_open_dyn_buf(&ctx->pb) < 0) {
  2151. /* XXX: potential leak */
  2152. return -1;
  2153. }
  2154. c->pfmt_ctx->pb->seekable = 0;
  2155. av_write_trailer(ctx);
  2156. len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  2157. c->buffer_ptr = c->pb_buffer;
  2158. c->buffer_end = c->pb_buffer + len;
  2159. c->last_packet_sent = 1;
  2160. break;
  2161. }
  2162. return 0;
  2163. }
  2164. /* should convert the format at the same time */
  2165. /* send data starting at c->buffer_ptr to the output connection
  2166. * (either UDP or TCP)
  2167. */
  2168. static int http_send_data(HTTPContext *c)
  2169. {
  2170. int len, ret;
  2171. for(;;) {
  2172. if (c->buffer_ptr >= c->buffer_end) {
  2173. ret = http_prepare_data(c);
  2174. if (ret < 0)
  2175. return -1;
  2176. else if (ret)
  2177. /* state change requested */
  2178. break;
  2179. } else {
  2180. if (c->is_packetized) {
  2181. /* RTP data output */
  2182. len = c->buffer_end - c->buffer_ptr;
  2183. if (len < 4) {
  2184. /* fail safe - should never happen */
  2185. fail1:
  2186. c->buffer_ptr = c->buffer_end;
  2187. return 0;
  2188. }
  2189. len = (c->buffer_ptr[0] << 24) |
  2190. (c->buffer_ptr[1] << 16) |
  2191. (c->buffer_ptr[2] << 8) |
  2192. (c->buffer_ptr[3]);
  2193. if (len > (c->buffer_end - c->buffer_ptr))
  2194. goto fail1;
  2195. if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
  2196. /* nothing to send yet: we can wait */
  2197. return 0;
  2198. }
  2199. c->data_count += len;
  2200. update_datarate(&c->datarate, c->data_count);
  2201. if (c->stream)
  2202. c->stream->bytes_served += len;
  2203. if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
  2204. /* RTP packets are sent inside the RTSP TCP connection */
  2205. AVIOContext *pb;
  2206. int interleaved_index, size;
  2207. uint8_t header[4];
  2208. HTTPContext *rtsp_c;
  2209. rtsp_c = c->rtsp_c;
  2210. /* if no RTSP connection left, error */
  2211. if (!rtsp_c)
  2212. return -1;
  2213. /* if already sending something, then wait. */
  2214. if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
  2215. break;
  2216. if (avio_open_dyn_buf(&pb) < 0)
  2217. goto fail1;
  2218. interleaved_index = c->packet_stream_index * 2;
  2219. /* RTCP packets are sent at odd indexes */
  2220. if (c->buffer_ptr[1] == 200)
  2221. interleaved_index++;
  2222. /* write RTSP TCP header */
  2223. header[0] = '$';
  2224. header[1] = interleaved_index;
  2225. header[2] = len >> 8;
  2226. header[3] = len;
  2227. avio_write(pb, header, 4);
  2228. /* write RTP packet data */
  2229. c->buffer_ptr += 4;
  2230. avio_write(pb, c->buffer_ptr, len);
  2231. size = avio_close_dyn_buf(pb, &c->packet_buffer);
  2232. /* prepare asynchronous TCP sending */
  2233. rtsp_c->packet_buffer_ptr = c->packet_buffer;
  2234. rtsp_c->packet_buffer_end = c->packet_buffer + size;
  2235. c->buffer_ptr += len;
  2236. /* send everything we can NOW */
  2237. len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
  2238. rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
  2239. if (len > 0)
  2240. rtsp_c->packet_buffer_ptr += len;
  2241. if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
  2242. /* if we could not send all the data, we will
  2243. * send it later, so a new state is needed to
  2244. * "lock" the RTSP TCP connection */
  2245. rtsp_c->state = RTSPSTATE_SEND_PACKET;
  2246. break;
  2247. } else
  2248. /* all data has been sent */
  2249. av_freep(&c->packet_buffer);
  2250. } else {
  2251. /* send RTP packet directly in UDP */
  2252. c->buffer_ptr += 4;
  2253. ffurl_write(c->rtp_handles[c->packet_stream_index],
  2254. c->buffer_ptr, len);
  2255. c->buffer_ptr += len;
  2256. /* here we continue as we can send several packets
  2257. * per 10 ms slot */
  2258. }
  2259. } else {
  2260. /* TCP data output */
  2261. len = send(c->fd, c->buffer_ptr,
  2262. c->buffer_end - c->buffer_ptr, 0);
  2263. if (len < 0) {
  2264. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2265. ff_neterrno() != AVERROR(EINTR))
  2266. /* error : close connection */
  2267. return -1;
  2268. else
  2269. return 0;
  2270. }
  2271. c->buffer_ptr += len;
  2272. c->data_count += len;
  2273. update_datarate(&c->datarate, c->data_count);
  2274. if (c->stream)
  2275. c->stream->bytes_served += len;
  2276. break;
  2277. }
  2278. }
  2279. } /* for(;;) */
  2280. return 0;
  2281. }
  2282. static int http_start_receive_data(HTTPContext *c)
  2283. {
  2284. int fd;
  2285. int ret;
  2286. int64_t ret64;
  2287. if (c->stream->feed_opened) {
  2288. http_log("Stream feed '%s' was not opened\n",
  2289. c->stream->feed_filename);
  2290. return AVERROR(EINVAL);
  2291. }
  2292. /* Don't permit writing to this one */
  2293. if (c->stream->readonly) {
  2294. http_log("Cannot write to read-only file '%s'\n",
  2295. c->stream->feed_filename);
  2296. return AVERROR(EINVAL);
  2297. }
  2298. /* open feed */
  2299. fd = open(c->stream->feed_filename, O_RDWR);
  2300. if (fd < 0) {
  2301. ret = AVERROR(errno);
  2302. http_log("Could not open feed file '%s': %s\n",
  2303. c->stream->feed_filename, strerror(errno));
  2304. return ret;
  2305. }
  2306. c->feed_fd = fd;
  2307. if (c->stream->truncate) {
  2308. /* truncate feed file */
  2309. ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
  2310. http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
  2311. if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
  2312. ret = AVERROR(errno);
  2313. http_log("Error truncating feed file '%s': %s\n",
  2314. c->stream->feed_filename, strerror(errno));
  2315. return ret;
  2316. }
  2317. } else {
  2318. ret64 = ffm_read_write_index(fd);
  2319. if (ret64 < 0) {
  2320. http_log("Error reading write index from feed file '%s': %s\n",
  2321. c->stream->feed_filename, strerror(errno));
  2322. return ret64;
  2323. }
  2324. c->stream->feed_write_index = ret64;
  2325. }
  2326. c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
  2327. FFM_PACKET_SIZE);
  2328. c->stream->feed_size = lseek(fd, 0, SEEK_END);
  2329. lseek(fd, 0, SEEK_SET);
  2330. /* init buffer input */
  2331. c->buffer_ptr = c->buffer;
  2332. c->buffer_end = c->buffer + FFM_PACKET_SIZE;
  2333. c->stream->feed_opened = 1;
  2334. c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
  2335. return 0;
  2336. }
  2337. static int http_receive_data(HTTPContext *c)
  2338. {
  2339. HTTPContext *c1;
  2340. int len, loop_run = 0;
  2341. while (c->chunked_encoding && !c->chunk_size &&
  2342. c->buffer_end > c->buffer_ptr) {
  2343. /* read chunk header, if present */
  2344. len = recv(c->fd, c->buffer_ptr, 1, 0);
  2345. if (len < 0) {
  2346. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2347. ff_neterrno() != AVERROR(EINTR))
  2348. /* error : close connection */
  2349. goto fail;
  2350. return 0;
  2351. } else if (len == 0) {
  2352. /* end of connection : close it */
  2353. goto fail;
  2354. } else if (c->buffer_ptr - c->buffer >= 2 &&
  2355. !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
  2356. c->chunk_size = strtol(c->buffer, 0, 16);
  2357. if (c->chunk_size == 0) // end of stream
  2358. goto fail;
  2359. c->buffer_ptr = c->buffer;
  2360. break;
  2361. } else if (++loop_run > 10)
  2362. /* no chunk header, abort */
  2363. goto fail;
  2364. else
  2365. c->buffer_ptr++;
  2366. }
  2367. if (c->buffer_end > c->buffer_ptr) {
  2368. len = recv(c->fd, c->buffer_ptr,
  2369. FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
  2370. if (len < 0) {
  2371. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2372. ff_neterrno() != AVERROR(EINTR))
  2373. /* error : close connection */
  2374. goto fail;
  2375. } else if (len == 0)
  2376. /* end of connection : close it */
  2377. goto fail;
  2378. else {
  2379. c->chunk_size -= len;
  2380. c->buffer_ptr += len;
  2381. c->data_count += len;
  2382. update_datarate(&c->datarate, c->data_count);
  2383. }
  2384. }
  2385. if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
  2386. if (c->buffer[0] != 'f' ||
  2387. c->buffer[1] != 'm') {
  2388. http_log("Feed stream has become desynchronized -- disconnecting\n");
  2389. goto fail;
  2390. }
  2391. }
  2392. if (c->buffer_ptr >= c->buffer_end) {
  2393. FFServerStream *feed = c->stream;
  2394. /* a packet has been received : write it in the store, except
  2395. * if header */
  2396. if (c->data_count > FFM_PACKET_SIZE) {
  2397. /* XXX: use llseek or url_seek
  2398. * XXX: Should probably fail? */
  2399. if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
  2400. http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
  2401. if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
  2402. http_log("Error writing to feed file: %s\n", strerror(errno));
  2403. goto fail;
  2404. }
  2405. feed->feed_write_index += FFM_PACKET_SIZE;
  2406. /* update file size */
  2407. if (feed->feed_write_index > c->stream->feed_size)
  2408. feed->feed_size = feed->feed_write_index;
  2409. /* handle wrap around if max file size reached */
  2410. if (c->stream->feed_max_size &&
  2411. feed->feed_write_index >= c->stream->feed_max_size)
  2412. feed->feed_write_index = FFM_PACKET_SIZE;
  2413. /* write index */
  2414. if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
  2415. http_log("Error writing index to feed file: %s\n",
  2416. strerror(errno));
  2417. goto fail;
  2418. }
  2419. /* wake up any waiting connections */
  2420. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2421. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2422. c1->stream->feed == c->stream->feed)
  2423. c1->state = HTTPSTATE_SEND_DATA;
  2424. }
  2425. } else {
  2426. /* We have a header in our hands that contains useful data */
  2427. AVFormatContext *s = avformat_alloc_context();
  2428. AVIOContext *pb;
  2429. AVInputFormat *fmt_in;
  2430. int i;
  2431. if (!s)
  2432. goto fail;
  2433. /* use feed output format name to find corresponding input format */
  2434. fmt_in = av_find_input_format(feed->fmt->name);
  2435. if (!fmt_in)
  2436. goto fail;
  2437. pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
  2438. 0, NULL, NULL, NULL, NULL);
  2439. if (!pb)
  2440. goto fail;
  2441. pb->seekable = 0;
  2442. s->pb = pb;
  2443. if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
  2444. av_freep(&pb);
  2445. goto fail;
  2446. }
  2447. /* Now we have the actual streams */
  2448. if (s->nb_streams != feed->nb_streams) {
  2449. avformat_close_input(&s);
  2450. av_freep(&pb);
  2451. http_log("Feed '%s' stream number does not match registered feed\n",
  2452. c->stream->feed_filename);
  2453. goto fail;
  2454. }
  2455. for (i = 0; i < s->nb_streams; i++) {
  2456. AVStream *fst = feed->streams[i];
  2457. AVStream *st = s->streams[i];
  2458. avcodec_copy_context(fst->codec, st->codec);
  2459. }
  2460. avformat_close_input(&s);
  2461. av_freep(&pb);
  2462. }
  2463. c->buffer_ptr = c->buffer;
  2464. }
  2465. return 0;
  2466. fail:
  2467. c->stream->feed_opened = 0;
  2468. close(c->feed_fd);
  2469. /* wake up any waiting connections to stop waiting for feed */
  2470. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2471. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2472. c1->stream->feed == c->stream->feed)
  2473. c1->state = HTTPSTATE_SEND_DATA_TRAILER;
  2474. }
  2475. return -1;
  2476. }
  2477. /********************************************************************/
  2478. /* RTSP handling */
  2479. static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
  2480. {
  2481. const char *str;
  2482. time_t ti;
  2483. struct tm *tm;
  2484. char buf2[32];
  2485. str = RTSP_STATUS_CODE2STRING(error_number);
  2486. if (!str)
  2487. str = "Unknown Error";
  2488. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
  2489. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2490. /* output GMT time */
  2491. ti = time(NULL);
  2492. tm = gmtime(&ti);
  2493. strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
  2494. avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
  2495. }
  2496. static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
  2497. {
  2498. rtsp_reply_header(c, error_number);
  2499. avio_printf(c->pb, "\r\n");
  2500. }
  2501. static int rtsp_parse_request(HTTPContext *c)
  2502. {
  2503. const char *p, *p1, *p2;
  2504. char cmd[32];
  2505. char url[1024];
  2506. char protocol[32];
  2507. char line[1024];
  2508. int len;
  2509. RTSPMessageHeader header1 = { 0 }, *header = &header1;
  2510. c->buffer_ptr[0] = '\0';
  2511. p = c->buffer;
  2512. get_word(cmd, sizeof(cmd), &p);
  2513. get_word(url, sizeof(url), &p);
  2514. get_word(protocol, sizeof(protocol), &p);
  2515. av_strlcpy(c->method, cmd, sizeof(c->method));
  2516. av_strlcpy(c->url, url, sizeof(c->url));
  2517. av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
  2518. if (avio_open_dyn_buf(&c->pb) < 0) {
  2519. /* XXX: cannot do more */
  2520. c->pb = NULL; /* safety */
  2521. return -1;
  2522. }
  2523. /* check version name */
  2524. if (strcmp(protocol, "RTSP/1.0")) {
  2525. rtsp_reply_error(c, RTSP_STATUS_VERSION);
  2526. goto the_end;
  2527. }
  2528. /* parse each header line */
  2529. /* skip to next line */
  2530. while (*p != '\n' && *p != '\0')
  2531. p++;
  2532. if (*p == '\n')
  2533. p++;
  2534. while (*p != '\0') {
  2535. p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
  2536. if (!p1)
  2537. break;
  2538. p2 = p1;
  2539. if (p2 > p && p2[-1] == '\r')
  2540. p2--;
  2541. /* skip empty line */
  2542. if (p2 == p)
  2543. break;
  2544. len = p2 - p;
  2545. if (len > sizeof(line) - 1)
  2546. len = sizeof(line) - 1;
  2547. memcpy(line, p, len);
  2548. line[len] = '\0';
  2549. ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
  2550. p = p1 + 1;
  2551. }
  2552. /* handle sequence number */
  2553. c->seq = header->seq;
  2554. if (!strcmp(cmd, "DESCRIBE"))
  2555. rtsp_cmd_describe(c, url);
  2556. else if (!strcmp(cmd, "OPTIONS"))
  2557. rtsp_cmd_options(c, url);
  2558. else if (!strcmp(cmd, "SETUP"))
  2559. rtsp_cmd_setup(c, url, header);
  2560. else if (!strcmp(cmd, "PLAY"))
  2561. rtsp_cmd_play(c, url, header);
  2562. else if (!strcmp(cmd, "PAUSE"))
  2563. rtsp_cmd_interrupt(c, url, header, 1);
  2564. else if (!strcmp(cmd, "TEARDOWN"))
  2565. rtsp_cmd_interrupt(c, url, header, 0);
  2566. else
  2567. rtsp_reply_error(c, RTSP_STATUS_METHOD);
  2568. the_end:
  2569. len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
  2570. c->pb = NULL; /* safety */
  2571. if (len < 0)
  2572. /* XXX: cannot do more */
  2573. return -1;
  2574. c->buffer_ptr = c->pb_buffer;
  2575. c->buffer_end = c->pb_buffer + len;
  2576. c->state = RTSPSTATE_SEND_REPLY;
  2577. return 0;
  2578. }
  2579. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  2580. struct in_addr my_ip)
  2581. {
  2582. AVFormatContext *avc;
  2583. AVStream *avs = NULL;
  2584. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  2585. AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
  2586. int i;
  2587. *pbuffer = NULL;
  2588. avc = avformat_alloc_context();
  2589. if (!avc || !rtp_format)
  2590. return -1;
  2591. avc->oformat = rtp_format;
  2592. av_dict_set(&avc->metadata, "title",
  2593. entry ? entry->value : "No Title", 0);
  2594. avc->nb_streams = stream->nb_streams;
  2595. if (stream->is_multicast) {
  2596. snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
  2597. inet_ntoa(stream->multicast_ip),
  2598. stream->multicast_port, stream->multicast_ttl);
  2599. } else
  2600. snprintf(avc->filename, 1024, "rtp://0.0.0.0");
  2601. avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
  2602. if (!avc->streams)
  2603. goto sdp_done;
  2604. avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
  2605. if (!avs)
  2606. goto sdp_done;
  2607. for(i = 0; i < stream->nb_streams; i++) {
  2608. avc->streams[i] = &avs[i];
  2609. avc->streams[i]->codec = stream->streams[i]->codec;
  2610. avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
  2611. avc->streams[i]->codecpar = stream->streams[i]->codecpar;
  2612. }
  2613. #define PBUFFER_SIZE 2048
  2614. *pbuffer = av_mallocz(PBUFFER_SIZE);
  2615. if (!*pbuffer)
  2616. goto sdp_done;
  2617. av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
  2618. sdp_done:
  2619. av_freep(&avc->streams);
  2620. av_dict_free(&avc->metadata);
  2621. av_free(avc);
  2622. av_free(avs);
  2623. return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
  2624. }
  2625. static void rtsp_cmd_options(HTTPContext *c, const char *url)
  2626. {
  2627. /* rtsp_reply_header(c, RTSP_STATUS_OK); */
  2628. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
  2629. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2630. avio_printf(c->pb, "Public: %s\r\n",
  2631. "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
  2632. avio_printf(c->pb, "\r\n");
  2633. }
  2634. static void rtsp_cmd_describe(HTTPContext *c, const char *url)
  2635. {
  2636. FFServerStream *stream;
  2637. char path1[1024];
  2638. const char *path;
  2639. uint8_t *content;
  2640. int content_length;
  2641. socklen_t len;
  2642. struct sockaddr_in my_addr;
  2643. /* find which URL is asked */
  2644. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2645. path = path1;
  2646. if (*path == '/')
  2647. path++;
  2648. for(stream = config.first_stream; stream; stream = stream->next) {
  2649. if (!stream->is_feed &&
  2650. stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
  2651. !strcmp(path, stream->filename)) {
  2652. goto found;
  2653. }
  2654. }
  2655. /* no stream found */
  2656. rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
  2657. return;
  2658. found:
  2659. /* prepare the media description in SDP format */
  2660. /* get the host IP */
  2661. len = sizeof(my_addr);
  2662. getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
  2663. content_length = prepare_sdp_description(stream, &content,
  2664. my_addr.sin_addr);
  2665. if (content_length < 0) {
  2666. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2667. return;
  2668. }
  2669. rtsp_reply_header(c, RTSP_STATUS_OK);
  2670. avio_printf(c->pb, "Content-Base: %s/\r\n", url);
  2671. avio_printf(c->pb, "Content-Type: application/sdp\r\n");
  2672. avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
  2673. avio_printf(c->pb, "\r\n");
  2674. avio_write(c->pb, content, content_length);
  2675. av_free(content);
  2676. }
  2677. static HTTPContext *find_rtp_session(const char *session_id)
  2678. {
  2679. HTTPContext *c;
  2680. if (session_id[0] == '\0')
  2681. return NULL;
  2682. for(c = first_http_ctx; c; c = c->next) {
  2683. if (!strcmp(c->session_id, session_id))
  2684. return c;
  2685. }
  2686. return NULL;
  2687. }
  2688. static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
  2689. {
  2690. RTSPTransportField *th;
  2691. int i;
  2692. for(i=0;i<h->nb_transports;i++) {
  2693. th = &h->transports[i];
  2694. if (th->lower_transport == lower_transport)
  2695. return th;
  2696. }
  2697. return NULL;
  2698. }
  2699. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  2700. RTSPMessageHeader *h)
  2701. {
  2702. FFServerStream *stream;
  2703. int stream_index, rtp_port, rtcp_port;
  2704. char buf[1024];
  2705. char path1[1024];
  2706. const char *path;
  2707. HTTPContext *rtp_c;
  2708. RTSPTransportField *th;
  2709. struct sockaddr_in dest_addr;
  2710. RTSPActionServerSetup setup;
  2711. /* find which URL is asked */
  2712. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2713. path = path1;
  2714. if (*path == '/')
  2715. path++;
  2716. /* now check each stream */
  2717. for(stream = config.first_stream; stream; stream = stream->next) {
  2718. if (stream->is_feed || !stream->fmt ||
  2719. strcmp(stream->fmt->name, "rtp")) {
  2720. continue;
  2721. }
  2722. /* accept aggregate filenames only if single stream */
  2723. if (!strcmp(path, stream->filename)) {
  2724. if (stream->nb_streams != 1) {
  2725. rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
  2726. return;
  2727. }
  2728. stream_index = 0;
  2729. goto found;
  2730. }
  2731. for(stream_index = 0; stream_index < stream->nb_streams;
  2732. stream_index++) {
  2733. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2734. stream->filename, stream_index);
  2735. if (!strcmp(path, buf))
  2736. goto found;
  2737. }
  2738. }
  2739. /* no stream found */
  2740. rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
  2741. return;
  2742. found:
  2743. /* generate session id if needed */
  2744. if (h->session_id[0] == '\0') {
  2745. unsigned random0 = av_lfg_get(&random_state);
  2746. unsigned random1 = av_lfg_get(&random_state);
  2747. snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
  2748. random0, random1);
  2749. }
  2750. /* find RTP session, and create it if none found */
  2751. rtp_c = find_rtp_session(h->session_id);
  2752. if (!rtp_c) {
  2753. /* always prefer UDP */
  2754. th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
  2755. if (!th) {
  2756. th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
  2757. if (!th) {
  2758. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2759. return;
  2760. }
  2761. }
  2762. rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
  2763. th->lower_transport);
  2764. if (!rtp_c) {
  2765. rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
  2766. return;
  2767. }
  2768. /* open input stream */
  2769. if (open_input_stream(rtp_c, "") < 0) {
  2770. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2771. return;
  2772. }
  2773. }
  2774. /* test if stream is OK (test needed because several SETUP needs
  2775. * to be done for a given file) */
  2776. if (rtp_c->stream != stream) {
  2777. rtsp_reply_error(c, RTSP_STATUS_SERVICE);
  2778. return;
  2779. }
  2780. /* test if stream is already set up */
  2781. if (rtp_c->rtp_ctx[stream_index]) {
  2782. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2783. return;
  2784. }
  2785. /* check transport */
  2786. th = find_transport(h, rtp_c->rtp_protocol);
  2787. if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  2788. th->client_port_min <= 0)) {
  2789. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2790. return;
  2791. }
  2792. /* setup default options */
  2793. setup.transport_option[0] = '\0';
  2794. dest_addr = rtp_c->from_addr;
  2795. dest_addr.sin_port = htons(th->client_port_min);
  2796. /* setup stream */
  2797. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
  2798. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2799. return;
  2800. }
  2801. /* now everything is OK, so we can send the connection parameters */
  2802. rtsp_reply_header(c, RTSP_STATUS_OK);
  2803. /* session ID */
  2804. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2805. switch(rtp_c->rtp_protocol) {
  2806. case RTSP_LOWER_TRANSPORT_UDP:
  2807. rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
  2808. rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
  2809. avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
  2810. "client_port=%d-%d;server_port=%d-%d",
  2811. th->client_port_min, th->client_port_max,
  2812. rtp_port, rtcp_port);
  2813. break;
  2814. case RTSP_LOWER_TRANSPORT_TCP:
  2815. avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
  2816. stream_index * 2, stream_index * 2 + 1);
  2817. break;
  2818. default:
  2819. break;
  2820. }
  2821. if (setup.transport_option[0] != '\0')
  2822. avio_printf(c->pb, ";%s", setup.transport_option);
  2823. avio_printf(c->pb, "\r\n");
  2824. avio_printf(c->pb, "\r\n");
  2825. }
  2826. /**
  2827. * find an RTP connection by using the session ID. Check consistency
  2828. * with filename
  2829. */
  2830. static HTTPContext *find_rtp_session_with_url(const char *url,
  2831. const char *session_id)
  2832. {
  2833. HTTPContext *rtp_c;
  2834. char path1[1024];
  2835. const char *path;
  2836. char buf[1024];
  2837. int s, len;
  2838. rtp_c = find_rtp_session(session_id);
  2839. if (!rtp_c)
  2840. return NULL;
  2841. /* find which URL is asked */
  2842. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2843. path = path1;
  2844. if (*path == '/')
  2845. path++;
  2846. if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
  2847. for(s=0; s<rtp_c->stream->nb_streams; ++s) {
  2848. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2849. rtp_c->stream->filename, s);
  2850. if(!strncmp(path, buf, sizeof(buf)))
  2851. /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
  2852. * if nb_streams>1? */
  2853. return rtp_c;
  2854. }
  2855. len = strlen(path);
  2856. if (len > 0 && path[len - 1] == '/' &&
  2857. !strncmp(path, rtp_c->stream->filename, len - 1))
  2858. return rtp_c;
  2859. return NULL;
  2860. }
  2861. static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
  2862. {
  2863. HTTPContext *rtp_c;
  2864. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2865. if (!rtp_c) {
  2866. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2867. return;
  2868. }
  2869. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2870. rtp_c->state != HTTPSTATE_WAIT_FEED &&
  2871. rtp_c->state != HTTPSTATE_READY) {
  2872. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2873. return;
  2874. }
  2875. rtp_c->state = HTTPSTATE_SEND_DATA;
  2876. /* now everything is OK, so we can send the connection parameters */
  2877. rtsp_reply_header(c, RTSP_STATUS_OK);
  2878. /* session ID */
  2879. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2880. avio_printf(c->pb, "\r\n");
  2881. }
  2882. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  2883. RTSPMessageHeader *h, int pause_only)
  2884. {
  2885. HTTPContext *rtp_c;
  2886. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2887. if (!rtp_c) {
  2888. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2889. return;
  2890. }
  2891. if (pause_only) {
  2892. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2893. rtp_c->state != HTTPSTATE_WAIT_FEED) {
  2894. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2895. return;
  2896. }
  2897. rtp_c->state = HTTPSTATE_READY;
  2898. rtp_c->first_pts = AV_NOPTS_VALUE;
  2899. }
  2900. /* now everything is OK, so we can send the connection parameters */
  2901. rtsp_reply_header(c, RTSP_STATUS_OK);
  2902. /* session ID */
  2903. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2904. avio_printf(c->pb, "\r\n");
  2905. if (!pause_only)
  2906. close_connection(rtp_c);
  2907. }
  2908. /********************************************************************/
  2909. /* RTP handling */
  2910. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  2911. FFServerStream *stream,
  2912. const char *session_id,
  2913. enum RTSPLowerTransport rtp_protocol)
  2914. {
  2915. HTTPContext *c = NULL;
  2916. const char *proto_str;
  2917. /* XXX: should output a warning page when coming
  2918. * close to the connection limit */
  2919. if (nb_connections >= config.nb_max_connections)
  2920. goto fail;
  2921. /* add a new connection */
  2922. c = av_mallocz(sizeof(HTTPContext));
  2923. if (!c)
  2924. goto fail;
  2925. c->fd = -1;
  2926. c->poll_entry = NULL;
  2927. c->from_addr = *from_addr;
  2928. c->buffer_size = IOBUFFER_INIT_SIZE;
  2929. c->buffer = av_malloc(c->buffer_size);
  2930. if (!c->buffer)
  2931. goto fail;
  2932. nb_connections++;
  2933. c->stream = stream;
  2934. av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
  2935. c->state = HTTPSTATE_READY;
  2936. c->is_packetized = 1;
  2937. c->rtp_protocol = rtp_protocol;
  2938. /* protocol is shown in statistics */
  2939. switch(c->rtp_protocol) {
  2940. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  2941. proto_str = "MCAST";
  2942. break;
  2943. case RTSP_LOWER_TRANSPORT_UDP:
  2944. proto_str = "UDP";
  2945. break;
  2946. case RTSP_LOWER_TRANSPORT_TCP:
  2947. proto_str = "TCP";
  2948. break;
  2949. default:
  2950. proto_str = "???";
  2951. break;
  2952. }
  2953. av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
  2954. av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
  2955. current_bandwidth += stream->bandwidth;
  2956. c->next = first_http_ctx;
  2957. first_http_ctx = c;
  2958. return c;
  2959. fail:
  2960. if (c) {
  2961. av_freep(&c->buffer);
  2962. av_free(c);
  2963. }
  2964. return NULL;
  2965. }
  2966. /**
  2967. * add a new RTP stream in an RTP connection (used in RTSP SETUP
  2968. * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
  2969. * used.
  2970. */
  2971. static int rtp_new_av_stream(HTTPContext *c,
  2972. int stream_index, struct sockaddr_in *dest_addr,
  2973. HTTPContext *rtsp_c)
  2974. {
  2975. AVFormatContext *ctx;
  2976. AVStream *st;
  2977. char *ipaddr;
  2978. URLContext *h = NULL;
  2979. uint8_t *dummy_buf;
  2980. int max_packet_size;
  2981. void *st_internal;
  2982. /* now we can open the relevant output stream */
  2983. ctx = avformat_alloc_context();
  2984. if (!ctx)
  2985. return -1;
  2986. ctx->oformat = av_guess_format("rtp", NULL, NULL);
  2987. st = avformat_new_stream(ctx, NULL);
  2988. if (!st)
  2989. goto fail;
  2990. av_freep(&st->codec);
  2991. av_freep(&st->info);
  2992. st_internal = st->internal;
  2993. if (!c->stream->feed ||
  2994. c->stream->feed == c->stream)
  2995. memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
  2996. else
  2997. memcpy(st,
  2998. c->stream->feed->streams[c->stream->feed_streams[stream_index]],
  2999. sizeof(AVStream));
  3000. st->priv_data = NULL;
  3001. st->internal = st_internal;
  3002. /* build destination RTP address */
  3003. ipaddr = inet_ntoa(dest_addr->sin_addr);
  3004. switch(c->rtp_protocol) {
  3005. case RTSP_LOWER_TRANSPORT_UDP:
  3006. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  3007. /* RTP/UDP case */
  3008. /* XXX: also pass as parameter to function ? */
  3009. if (c->stream->is_multicast) {
  3010. int ttl;
  3011. ttl = c->stream->multicast_ttl;
  3012. if (!ttl)
  3013. ttl = 16;
  3014. snprintf(ctx->filename, sizeof(ctx->filename),
  3015. "rtp://%s:%d?multicast=1&ttl=%d",
  3016. ipaddr, ntohs(dest_addr->sin_port), ttl);
  3017. } else {
  3018. snprintf(ctx->filename, sizeof(ctx->filename),
  3019. "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
  3020. }
  3021. if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
  3022. goto fail;
  3023. c->rtp_handles[stream_index] = h;
  3024. max_packet_size = h->max_packet_size;
  3025. break;
  3026. case RTSP_LOWER_TRANSPORT_TCP:
  3027. /* RTP/TCP case */
  3028. c->rtsp_c = rtsp_c;
  3029. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  3030. break;
  3031. default:
  3032. goto fail;
  3033. }
  3034. http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
  3035. ipaddr, ntohs(dest_addr->sin_port),
  3036. c->stream->filename, stream_index, c->protocol);
  3037. /* normally, no packets should be output here, but the packet size may
  3038. * be checked */
  3039. if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
  3040. /* XXX: close stream */
  3041. goto fail;
  3042. if (avformat_write_header(ctx, NULL) < 0) {
  3043. fail:
  3044. if (h)
  3045. ffurl_close(h);
  3046. av_free(st);
  3047. av_free(ctx);
  3048. return -1;
  3049. }
  3050. avio_close_dyn_buf(ctx->pb, &dummy_buf);
  3051. ctx->pb = NULL;
  3052. av_free(dummy_buf);
  3053. c->rtp_ctx[stream_index] = ctx;
  3054. return 0;
  3055. }
  3056. /********************************************************************/
  3057. /* ffserver initialization */
  3058. /* FIXME: This code should use avformat_new_stream() */
  3059. static AVStream *add_av_stream1(FFServerStream *stream,
  3060. AVCodecContext *codec, int copy)
  3061. {
  3062. AVStream *fst;
  3063. if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
  3064. return NULL;
  3065. fst = av_mallocz(sizeof(AVStream));
  3066. if (!fst)
  3067. return NULL;
  3068. if (copy) {
  3069. fst->codec = avcodec_alloc_context3(codec->codec);
  3070. if (!fst->codec) {
  3071. av_free(fst);
  3072. return NULL;
  3073. }
  3074. avcodec_copy_context(fst->codec, codec);
  3075. } else
  3076. /* live streams must use the actual feed's codec since it may be
  3077. * updated later to carry extradata needed by them.
  3078. */
  3079. fst->codec = codec;
  3080. fst->priv_data = av_mallocz(sizeof(FeedData));
  3081. fst->internal = av_mallocz(sizeof(*fst->internal));
  3082. fst->internal->avctx = avcodec_alloc_context3(NULL);
  3083. fst->codecpar = avcodec_parameters_alloc();
  3084. fst->index = stream->nb_streams;
  3085. avpriv_set_pts_info(fst, 33, 1, 90000);
  3086. fst->sample_aspect_ratio = codec->sample_aspect_ratio;
  3087. stream->streams[stream->nb_streams++] = fst;
  3088. return fst;
  3089. }
  3090. /* return the stream number in the feed */
  3091. static int add_av_stream(FFServerStream *feed, AVStream *st)
  3092. {
  3093. AVStream *fst;
  3094. AVCodecContext *av, *av1;
  3095. int i;
  3096. av = st->codec;
  3097. for(i=0;i<feed->nb_streams;i++) {
  3098. av1 = feed->streams[i]->codec;
  3099. if (av1->codec_id == av->codec_id &&
  3100. av1->codec_type == av->codec_type &&
  3101. av1->bit_rate == av->bit_rate) {
  3102. switch(av->codec_type) {
  3103. case AVMEDIA_TYPE_AUDIO:
  3104. if (av1->channels == av->channels &&
  3105. av1->sample_rate == av->sample_rate)
  3106. return i;
  3107. break;
  3108. case AVMEDIA_TYPE_VIDEO:
  3109. if (av1->width == av->width &&
  3110. av1->height == av->height &&
  3111. av1->time_base.den == av->time_base.den &&
  3112. av1->time_base.num == av->time_base.num &&
  3113. av1->gop_size == av->gop_size)
  3114. return i;
  3115. break;
  3116. default:
  3117. abort();
  3118. }
  3119. }
  3120. }
  3121. fst = add_av_stream1(feed, av, 0);
  3122. if (!fst)
  3123. return -1;
  3124. if (av_stream_get_recommended_encoder_configuration(st))
  3125. av_stream_set_recommended_encoder_configuration(fst,
  3126. av_strdup(av_stream_get_recommended_encoder_configuration(st)));
  3127. return feed->nb_streams - 1;
  3128. }
  3129. static void remove_stream(FFServerStream *stream)
  3130. {
  3131. FFServerStream **ps;
  3132. ps = &config.first_stream;
  3133. while (*ps) {
  3134. if (*ps == stream)
  3135. *ps = (*ps)->next;
  3136. else
  3137. ps = &(*ps)->next;
  3138. }
  3139. }
  3140. /* compute the needed AVStream for each file */
  3141. static void build_file_streams(void)
  3142. {
  3143. FFServerStream *stream;
  3144. AVFormatContext *infile;
  3145. int i, ret;
  3146. /* gather all streams */
  3147. for(stream = config.first_stream; stream; stream = stream->next) {
  3148. infile = NULL;
  3149. if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
  3150. continue;
  3151. /* the stream comes from a file */
  3152. /* try to open the file */
  3153. /* open stream */
  3154. /* specific case: if transport stream output to RTP,
  3155. * we use a raw transport stream reader */
  3156. if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
  3157. av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
  3158. if (!stream->feed_filename[0]) {
  3159. http_log("Unspecified feed file for stream '%s'\n",
  3160. stream->filename);
  3161. goto fail;
  3162. }
  3163. http_log("Opening feed file '%s' for stream '%s'\n",
  3164. stream->feed_filename, stream->filename);
  3165. ret = avformat_open_input(&infile, stream->feed_filename,
  3166. stream->ifmt, &stream->in_opts);
  3167. if (ret < 0) {
  3168. http_log("Could not open '%s': %s\n", stream->feed_filename,
  3169. av_err2str(ret));
  3170. /* remove stream (no need to spend more time on it) */
  3171. fail:
  3172. remove_stream(stream);
  3173. } else {
  3174. /* find all the AVStreams inside and reference them in
  3175. * 'stream' */
  3176. if (avformat_find_stream_info(infile, NULL) < 0) {
  3177. http_log("Could not find codec parameters from '%s'\n",
  3178. stream->feed_filename);
  3179. avformat_close_input(&infile);
  3180. goto fail;
  3181. }
  3182. for(i=0;i<infile->nb_streams;i++)
  3183. add_av_stream1(stream, infile->streams[i]->codec, 1);
  3184. avformat_close_input(&infile);
  3185. }
  3186. }
  3187. }
  3188. static inline
  3189. int check_codec_match(AVStream *ccf, AVStream *ccs, int stream)
  3190. {
  3191. int matches = 1;
  3192. /* FIXME: Missed check on AVCodecContext.flags */
  3193. #define CHECK_CODEC(x) (ccf->codecpar->x != ccs->codecpar->x)
  3194. if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
  3195. http_log("Codecs do not match for stream %d\n", stream);
  3196. matches = 0;
  3197. } else if (CHECK_CODEC(bit_rate)) {
  3198. http_log("Codec bitrates do not match for stream %d\n", stream);
  3199. matches = 0;
  3200. } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  3201. if (av_cmp_q(ccf->time_base, ccs->time_base) ||
  3202. CHECK_CODEC(width) || CHECK_CODEC(height)) {
  3203. http_log("Codec width, height or framerate do not match for stream %d\n", stream);
  3204. matches = 0;
  3205. }
  3206. } else if (ccf->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  3207. if (CHECK_CODEC(sample_rate) ||
  3208. CHECK_CODEC(channels) ||
  3209. CHECK_CODEC(frame_size)) {
  3210. http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
  3211. matches = 0;
  3212. }
  3213. } else {
  3214. http_log("Unknown codec type for stream %d\n", stream);
  3215. matches = 0;
  3216. }
  3217. return matches;
  3218. }
  3219. /* compute the needed AVStream for each feed */
  3220. static int build_feed_streams(void)
  3221. {
  3222. FFServerStream *stream, *feed;
  3223. int i, fd;
  3224. /* gather all streams */
  3225. for(stream = config.first_stream; stream; stream = stream->next) {
  3226. feed = stream->feed;
  3227. if (!feed)
  3228. continue;
  3229. if (stream->is_feed) {
  3230. for(i=0;i<stream->nb_streams;i++)
  3231. stream->feed_streams[i] = i;
  3232. continue;
  3233. }
  3234. /* we handle a stream coming from a feed */
  3235. for(i=0;i<stream->nb_streams;i++)
  3236. stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
  3237. }
  3238. /* create feed files if needed */
  3239. for(feed = config.first_feed; feed; feed = feed->next_feed) {
  3240. if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
  3241. AVFormatContext *s = NULL;
  3242. int matches = 0;
  3243. /* See if it matches */
  3244. if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
  3245. http_log("Deleting feed file '%s' as it appears "
  3246. "to be corrupt\n",
  3247. feed->feed_filename);
  3248. goto drop;
  3249. }
  3250. /* set buffer size */
  3251. if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
  3252. http_log("Failed to set buffer size\n");
  3253. avformat_close_input(&s);
  3254. goto bail;
  3255. }
  3256. /* Now see if it matches */
  3257. if (s->nb_streams != feed->nb_streams) {
  3258. http_log("Deleting feed file '%s' as stream counts "
  3259. "differ (%d != %d)\n",
  3260. feed->feed_filename, s->nb_streams, feed->nb_streams);
  3261. goto drop;
  3262. }
  3263. matches = 1;
  3264. for(i=0;i<s->nb_streams;i++) {
  3265. AVStream *sf, *ss;
  3266. sf = feed->streams[i];
  3267. ss = s->streams[i];
  3268. if (sf->index != ss->index || sf->id != ss->id) {
  3269. http_log("Index & Id do not match for stream %d (%s)\n",
  3270. i, feed->feed_filename);
  3271. matches = 0;
  3272. break;
  3273. }
  3274. matches = check_codec_match (sf, ss, i);
  3275. if (!matches)
  3276. break;
  3277. }
  3278. drop:
  3279. if (s)
  3280. avformat_close_input(&s);
  3281. if (!matches) {
  3282. if (feed->readonly) {
  3283. http_log("Unable to delete read-only feed file '%s'\n",
  3284. feed->feed_filename);
  3285. goto bail;
  3286. }
  3287. unlink(feed->feed_filename);
  3288. }
  3289. }
  3290. if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
  3291. AVFormatContext *s = avformat_alloc_context();
  3292. if (!s) {
  3293. http_log("Failed to allocate context\n");
  3294. goto bail;
  3295. }
  3296. if (feed->readonly) {
  3297. http_log("Unable to create feed file '%s' as it is "
  3298. "marked readonly\n",
  3299. feed->feed_filename);
  3300. avformat_free_context(s);
  3301. goto bail;
  3302. }
  3303. /* only write the header of the ffm file */
  3304. if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
  3305. http_log("Could not open output feed file '%s'\n",
  3306. feed->feed_filename);
  3307. avformat_free_context(s);
  3308. goto bail;
  3309. }
  3310. s->oformat = feed->fmt;
  3311. s->nb_streams = feed->nb_streams;
  3312. s->streams = feed->streams;
  3313. if (avformat_write_header(s, NULL) < 0) {
  3314. http_log("Container doesn't support the required parameters\n");
  3315. avio_closep(&s->pb);
  3316. s->streams = NULL;
  3317. s->nb_streams = 0;
  3318. avformat_free_context(s);
  3319. goto bail;
  3320. }
  3321. /* XXX: need better API */
  3322. av_freep(&s->priv_data);
  3323. avio_closep(&s->pb);
  3324. s->streams = NULL;
  3325. s->nb_streams = 0;
  3326. avformat_free_context(s);
  3327. }
  3328. /* get feed size and write index */
  3329. fd = open(feed->feed_filename, O_RDONLY);
  3330. if (fd < 0) {
  3331. http_log("Could not open output feed file '%s'\n",
  3332. feed->feed_filename);
  3333. goto bail;
  3334. }
  3335. feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
  3336. FFM_PACKET_SIZE);
  3337. feed->feed_size = lseek(fd, 0, SEEK_END);
  3338. /* ensure that we do not wrap before the end of file */
  3339. if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
  3340. feed->feed_max_size = feed->feed_size;
  3341. close(fd);
  3342. }
  3343. return 0;
  3344. bail:
  3345. return -1;
  3346. }
  3347. /* compute the bandwidth used by each stream */
  3348. static void compute_bandwidth(void)
  3349. {
  3350. unsigned bandwidth;
  3351. int i;
  3352. FFServerStream *stream;
  3353. for(stream = config.first_stream; stream; stream = stream->next) {
  3354. bandwidth = 0;
  3355. for(i=0;i<stream->nb_streams;i++) {
  3356. AVStream *st = stream->streams[i];
  3357. switch(st->codec->codec_type) {
  3358. case AVMEDIA_TYPE_AUDIO:
  3359. case AVMEDIA_TYPE_VIDEO:
  3360. bandwidth += st->codec->bit_rate;
  3361. break;
  3362. default:
  3363. break;
  3364. }
  3365. }
  3366. stream->bandwidth = (bandwidth + 999) / 1000;
  3367. }
  3368. }
  3369. static void handle_child_exit(int sig)
  3370. {
  3371. pid_t pid;
  3372. int status;
  3373. time_t uptime;
  3374. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  3375. FFServerStream *feed;
  3376. for (feed = config.first_feed; feed; feed = feed->next) {
  3377. if (feed->pid != pid)
  3378. continue;
  3379. uptime = time(0) - feed->pid_start;
  3380. feed->pid = 0;
  3381. fprintf(stderr,
  3382. "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
  3383. "seconds\n",
  3384. feed->filename, (int64_t) pid, status, (int64_t)uptime);
  3385. if (uptime < 30)
  3386. /* Turn off any more restarts */
  3387. ffserver_free_child_args(&feed->child_argv);
  3388. }
  3389. }
  3390. need_to_start_children = 1;
  3391. }
  3392. static void opt_debug(void)
  3393. {
  3394. config.debug = 1;
  3395. snprintf(config.logfilename, sizeof(config.logfilename), "-");
  3396. }
  3397. void show_help_default(const char *opt, const char *arg)
  3398. {
  3399. printf("usage: ffserver [options]\n"
  3400. "Hyper fast multi format Audio/Video streaming server\n");
  3401. printf("\n");
  3402. show_help_options(options, "Main options:", 0, 0, 0);
  3403. }
  3404. static const OptionDef options[] = {
  3405. #include "cmdutils_common_opts.h"
  3406. { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
  3407. { "d", 0, {(void*)opt_debug}, "enable debug mode" },
  3408. { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
  3409. { NULL },
  3410. };
  3411. int main(int argc, char **argv)
  3412. {
  3413. struct sigaction sigact = { { 0 } };
  3414. int cfg_parsed;
  3415. int ret = EXIT_FAILURE;
  3416. init_dynload();
  3417. config.filename = av_strdup("/etc/ffserver.conf");
  3418. parse_loglevel(argc, argv, options);
  3419. av_register_all();
  3420. avformat_network_init();
  3421. show_banner(argc, argv, options);
  3422. my_program_name = argv[0];
  3423. parse_options(NULL, argc, argv, options, NULL);
  3424. unsetenv("http_proxy"); /* Kill the http_proxy */
  3425. av_lfg_init(&random_state, av_get_random_seed());
  3426. sigact.sa_handler = handle_child_exit;
  3427. sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
  3428. sigaction(SIGCHLD, &sigact, 0);
  3429. if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
  3430. fprintf(stderr, "Error reading configuration file '%s': %s\n",
  3431. config.filename, av_err2str(cfg_parsed));
  3432. goto bail;
  3433. }
  3434. /* open log file if needed */
  3435. if (config.logfilename[0] != '\0') {
  3436. if (!strcmp(config.logfilename, "-"))
  3437. logfile = stdout;
  3438. else
  3439. logfile = fopen(config.logfilename, "a");
  3440. av_log_set_callback(http_av_log);
  3441. }
  3442. build_file_streams();
  3443. if (build_feed_streams() < 0) {
  3444. http_log("Could not setup feed streams\n");
  3445. goto bail;
  3446. }
  3447. compute_bandwidth();
  3448. /* signal init */
  3449. signal(SIGPIPE, SIG_IGN);
  3450. if (http_server() < 0) {
  3451. http_log("Could not start server\n");
  3452. goto bail;
  3453. }
  3454. ret=EXIT_SUCCESS;
  3455. bail:
  3456. av_freep (&config.filename);
  3457. avformat_network_deinit();
  3458. return ret;
  3459. }