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.

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