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.

4038 lines
126KB

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