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.

4041 lines
126KB

  1. /*
  2. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * multiple format streaming server based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #if !HAVE_CLOSESOCKET
  26. #define closesocket close
  27. #endif
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include "libavformat/avformat.h"
  32. /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
  33. #include "libavformat/rtpproto.h"
  34. #include "libavformat/rtsp.h"
  35. #include "libavformat/avio_internal.h"
  36. #include "libavformat/internal.h"
  37. #include "libavutil/avassert.h"
  38. #include "libavutil/avstring.h"
  39. #include "libavutil/lfg.h"
  40. #include "libavutil/dict.h"
  41. #include "libavutil/intreadwrite.h"
  42. #include "libavutil/mathematics.h"
  43. #include "libavutil/random_seed.h"
  44. #include "libavutil/parseutils.h"
  45. #include "libavutil/opt.h"
  46. #include "libavutil/time.h"
  47. #include <stdarg.h>
  48. #if HAVE_UNISTD_H
  49. #include <unistd.h>
  50. #endif
  51. #include <fcntl.h>
  52. #include <sys/ioctl.h>
  53. #if HAVE_POLL_H
  54. #include <poll.h>
  55. #endif
  56. #include <errno.h>
  57. #include <time.h>
  58. #include <sys/wait.h>
  59. #include <signal.h>
  60. #include "cmdutils.h"
  61. #include "ffserver_config.h"
  62. #define PATH_LENGTH 1024
  63. const char program_name[] = "ffserver";
  64. const int program_birth_year = 2000;
  65. static const OptionDef options[];
  66. enum HTTPState {
  67. HTTPSTATE_WAIT_REQUEST,
  68. HTTPSTATE_SEND_HEADER,
  69. HTTPSTATE_SEND_DATA_HEADER,
  70. HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
  71. HTTPSTATE_SEND_DATA_TRAILER,
  72. HTTPSTATE_RECEIVE_DATA,
  73. HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
  74. HTTPSTATE_READY,
  75. RTSPSTATE_WAIT_REQUEST,
  76. RTSPSTATE_SEND_REPLY,
  77. RTSPSTATE_SEND_PACKET,
  78. };
  79. static const char * const http_state[] = {
  80. "HTTP_WAIT_REQUEST",
  81. "HTTP_SEND_HEADER",
  82. "SEND_DATA_HEADER",
  83. "SEND_DATA",
  84. "SEND_DATA_TRAILER",
  85. "RECEIVE_DATA",
  86. "WAIT_FEED",
  87. "READY",
  88. "RTSP_WAIT_REQUEST",
  89. "RTSP_SEND_REPLY",
  90. "RTSP_SEND_PACKET",
  91. };
  92. #define IOBUFFER_INIT_SIZE 8192
  93. /* timeouts are in ms */
  94. #define HTTP_REQUEST_TIMEOUT (15 * 1000)
  95. #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
  96. #define SYNC_TIMEOUT (10 * 1000)
  97. typedef struct RTSPActionServerSetup {
  98. uint32_t ipaddr;
  99. char transport_option[512];
  100. } RTSPActionServerSetup;
  101. typedef struct {
  102. int64_t count1, count2;
  103. int64_t time1, time2;
  104. } DataRateData;
  105. /* context associated with one connection */
  106. typedef struct HTTPContext {
  107. enum HTTPState state;
  108. int fd; /* socket file descriptor */
  109. struct sockaddr_in from_addr; /* origin */
  110. struct pollfd *poll_entry; /* used when polling */
  111. int64_t timeout;
  112. uint8_t *buffer_ptr, *buffer_end;
  113. int http_error;
  114. int post;
  115. int chunked_encoding;
  116. int chunk_size; /* 0 if it needs to be read */
  117. struct HTTPContext *next;
  118. int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
  119. int64_t data_count;
  120. /* feed input */
  121. int feed_fd;
  122. /* input format handling */
  123. AVFormatContext *fmt_in;
  124. int64_t start_time; /* In milliseconds - this wraps fairly often */
  125. int64_t first_pts; /* initial pts value */
  126. int64_t cur_pts; /* current pts value from the stream in us */
  127. int64_t cur_frame_duration; /* duration of the current frame in us */
  128. int cur_frame_bytes; /* output frame size, needed to compute
  129. the time at which we send each
  130. packet */
  131. int pts_stream_index; /* stream we choose as clock reference */
  132. int64_t cur_clock; /* current clock reference value in us */
  133. /* output format handling */
  134. struct FFServerStream *stream;
  135. /* -1 is invalid stream */
  136. int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  137. int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  138. int switch_pending;
  139. AVFormatContext fmt_ctx; /* instance of FFServerStream for one user */
  140. int last_packet_sent; /* true if last data packet was sent */
  141. int suppress_log;
  142. DataRateData datarate;
  143. int wmp_client_id;
  144. char protocol[16];
  145. char method[16];
  146. char url[128];
  147. int buffer_size;
  148. uint8_t *buffer;
  149. int is_packetized; /* if true, the stream is packetized */
  150. int packet_stream_index; /* current stream for output in state machine */
  151. /* RTSP state specific */
  152. uint8_t *pb_buffer; /* XXX: use that in all the code */
  153. AVIOContext *pb;
  154. int seq; /* RTSP sequence number */
  155. /* RTP state specific */
  156. enum RTSPLowerTransport rtp_protocol;
  157. char session_id[32]; /* session id */
  158. AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
  159. /* RTP/UDP specific */
  160. URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
  161. /* RTP/TCP specific */
  162. struct HTTPContext *rtsp_c;
  163. uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
  164. } HTTPContext;
  165. typedef struct FeedData {
  166. long long data_count;
  167. float avg_frame_size; /* frame size averaged over last frames with exponential mean */
  168. } FeedData;
  169. static HTTPContext *first_http_ctx;
  170. static FFServerConfig config = {
  171. .nb_max_http_connections = 2000,
  172. .nb_max_connections = 5,
  173. .max_bandwidth = 1000,
  174. .use_defaults = 1,
  175. };
  176. static void new_connection(int server_fd, int is_rtsp);
  177. static void close_connection(HTTPContext *c);
  178. /* HTTP handling */
  179. static int handle_connection(HTTPContext *c);
  180. static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
  181. static void compute_status(HTTPContext *c);
  182. static int open_input_stream(HTTPContext *c, const char *info);
  183. static int http_parse_request(HTTPContext *c);
  184. static int http_send_data(HTTPContext *c);
  185. static int http_start_receive_data(HTTPContext *c);
  186. static int http_receive_data(HTTPContext *c);
  187. /* RTSP handling */
  188. static int rtsp_parse_request(HTTPContext *c);
  189. static void rtsp_cmd_describe(HTTPContext *c, const char *url);
  190. static void rtsp_cmd_options(HTTPContext *c, const char *url);
  191. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  192. RTSPMessageHeader *h);
  193. static void rtsp_cmd_play(HTTPContext *c, const char *url,
  194. RTSPMessageHeader *h);
  195. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  196. RTSPMessageHeader *h, int pause_only);
  197. /* SDP handling */
  198. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  199. struct in_addr my_ip);
  200. /* RTP handling */
  201. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  202. FFServerStream *stream,
  203. const char *session_id,
  204. enum RTSPLowerTransport rtp_protocol);
  205. static int rtp_new_av_stream(HTTPContext *c,
  206. int stream_index, struct sockaddr_in *dest_addr,
  207. HTTPContext *rtsp_c);
  208. /* utils */
  209. static size_t htmlencode (const char *src, char **dest);
  210. static inline void cp_html_entity (char *buffer, const char *entity);
  211. static inline int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs,
  212. int stream);
  213. static const char *my_program_name;
  214. static int no_launch;
  215. static int need_to_start_children;
  216. /* maximum number of simultaneous HTTP connections */
  217. static unsigned int nb_connections;
  218. static uint64_t current_bandwidth;
  219. /* Making this global saves on passing it around everywhere */
  220. static int64_t cur_time;
  221. static AVLFG random_state;
  222. static FILE *logfile = NULL;
  223. static inline void cp_html_entity (char *buffer, const char *entity) {
  224. if (!buffer || !entity)
  225. return;
  226. while (*entity)
  227. *buffer++ = *entity++;
  228. }
  229. /**
  230. * Substitutes known conflicting chars on a text string with
  231. * their corresponding HTML entities.
  232. *
  233. * Returns the number of bytes in the 'encoded' representation
  234. * not including the terminating NUL.
  235. */
  236. static size_t htmlencode (const char *src, char **dest) {
  237. const char *amp = "&amp;";
  238. const char *lt = "&lt;";
  239. const char *gt = "&gt;";
  240. const char *start;
  241. char *tmp;
  242. size_t final_size = 0;
  243. if (!src)
  244. return 0;
  245. start = src;
  246. /* Compute needed dest size */
  247. while (*src != '\0') {
  248. switch(*src) {
  249. case 38: /* & */
  250. final_size += 5;
  251. break;
  252. case 60: /* < */
  253. case 62: /* > */
  254. final_size += 4;
  255. break;
  256. default:
  257. final_size++;
  258. }
  259. src++;
  260. }
  261. src = start;
  262. *dest = av_mallocz(final_size + 1);
  263. if (!*dest)
  264. return 0;
  265. /* Build dest */
  266. tmp = *dest;
  267. while (*src != '\0') {
  268. switch(*src) {
  269. case 38: /* & */
  270. cp_html_entity (tmp, amp);
  271. tmp += 5;
  272. break;
  273. case 60: /* < */
  274. cp_html_entity (tmp, lt);
  275. tmp += 4;
  276. break;
  277. case 62: /* > */
  278. cp_html_entity (tmp, gt);
  279. tmp += 4;
  280. break;
  281. default:
  282. *tmp = *src;
  283. tmp += 1;
  284. }
  285. src++;
  286. }
  287. *tmp = '\0';
  288. return final_size;
  289. }
  290. static int64_t ffm_read_write_index(int fd)
  291. {
  292. uint8_t buf[8];
  293. if (lseek(fd, 8, SEEK_SET) < 0)
  294. return AVERROR(EIO);
  295. if (read(fd, buf, 8) != 8)
  296. return AVERROR(EIO);
  297. return AV_RB64(buf);
  298. }
  299. static int ffm_write_write_index(int fd, int64_t pos)
  300. {
  301. uint8_t buf[8];
  302. int i;
  303. for(i=0;i<8;i++)
  304. buf[i] = (pos >> (56 - i * 8)) & 0xff;
  305. if (lseek(fd, 8, SEEK_SET) < 0)
  306. goto bail_eio;
  307. if (write(fd, buf, 8) != 8)
  308. goto bail_eio;
  309. return 8;
  310. bail_eio:
  311. return AVERROR(EIO);
  312. }
  313. static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
  314. int64_t file_size)
  315. {
  316. av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
  317. av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
  318. av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
  319. }
  320. static char *ctime1(char *buf2, size_t buf_size)
  321. {
  322. time_t ti;
  323. char *p;
  324. ti = time(NULL);
  325. p = ctime(&ti);
  326. if (!p || !*p) {
  327. *buf2 = '\0';
  328. return buf2;
  329. }
  330. av_strlcpy(buf2, p, buf_size);
  331. p = buf2 + strlen(buf2) - 1;
  332. if (*p == '\n')
  333. *p = '\0';
  334. return buf2;
  335. }
  336. static void http_vlog(const char *fmt, va_list vargs)
  337. {
  338. static int print_prefix = 1;
  339. char buf[32];
  340. if (!logfile)
  341. return;
  342. if (print_prefix) {
  343. ctime1(buf, sizeof(buf));
  344. fprintf(logfile, "%s ", buf);
  345. }
  346. print_prefix = strstr(fmt, "\n") != NULL;
  347. vfprintf(logfile, fmt, vargs);
  348. fflush(logfile);
  349. }
  350. #ifdef __GNUC__
  351. __attribute__ ((format (printf, 1, 2)))
  352. #endif
  353. static void http_log(const char *fmt, ...)
  354. {
  355. va_list vargs;
  356. va_start(vargs, fmt);
  357. http_vlog(fmt, vargs);
  358. va_end(vargs);
  359. }
  360. static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
  361. {
  362. static int print_prefix = 1;
  363. AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
  364. if (level > av_log_get_level())
  365. return;
  366. if (print_prefix && avc)
  367. http_log("[%s @ %p]", avc->item_name(ptr), ptr);
  368. print_prefix = strstr(fmt, "\n") != NULL;
  369. http_vlog(fmt, vargs);
  370. }
  371. static void log_connection(HTTPContext *c)
  372. {
  373. if (c->suppress_log)
  374. return;
  375. http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
  376. inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
  377. c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
  378. }
  379. static void update_datarate(DataRateData *drd, int64_t count)
  380. {
  381. if (!drd->time1 && !drd->count1) {
  382. drd->time1 = drd->time2 = cur_time;
  383. drd->count1 = drd->count2 = count;
  384. } else if (cur_time - drd->time2 > 5000) {
  385. drd->time1 = drd->time2;
  386. drd->count1 = drd->count2;
  387. drd->time2 = cur_time;
  388. drd->count2 = count;
  389. }
  390. }
  391. /* In bytes per second */
  392. static int compute_datarate(DataRateData *drd, int64_t count)
  393. {
  394. if (cur_time == drd->time1)
  395. return 0;
  396. return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
  397. }
  398. static void start_children(FFServerStream *feed)
  399. {
  400. char *pathname;
  401. char *slash;
  402. int i;
  403. size_t cmd_length;
  404. if (no_launch)
  405. return;
  406. cmd_length = strlen(my_program_name);
  407. /**
  408. * FIXME: WIP Safeguard. Remove after clearing all harcoded
  409. * '1024' path lengths
  410. */
  411. if (cmd_length > PATH_LENGTH - 1) {
  412. http_log("Could not start children. Command line: '%s' exceeds "
  413. "path length limit (%d)\n", my_program_name, PATH_LENGTH);
  414. return;
  415. }
  416. pathname = av_strdup (my_program_name);
  417. if (!pathname) {
  418. http_log("Could not allocate memory for children cmd line\n");
  419. return;
  420. }
  421. /* replace "ffserver" with "ffmpeg" in the path of current
  422. * program. Ignore user provided path */
  423. slash = strrchr(pathname, '/');
  424. if (!slash)
  425. slash = pathname;
  426. else
  427. slash++;
  428. strcpy(slash, "ffmpeg");
  429. for (; feed; feed = feed->next) {
  430. if (!feed->child_argv || feed->pid)
  431. continue;
  432. feed->pid_start = time(0);
  433. feed->pid = fork();
  434. if (feed->pid < 0) {
  435. http_log("Unable to create children: %s\n", strerror(errno));
  436. av_free (pathname);
  437. exit(EXIT_FAILURE);
  438. }
  439. if (feed->pid)
  440. continue;
  441. /* In child */
  442. http_log("Launch command line: ");
  443. http_log("%s ", pathname);
  444. for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
  445. http_log("%s ", feed->child_argv[i]);
  446. http_log("\n");
  447. for (i = 3; i < 256; i++)
  448. close(i);
  449. if (!config.debug) {
  450. if (!freopen("/dev/null", "r", stdin))
  451. http_log("failed to redirect STDIN to /dev/null\n;");
  452. if (!freopen("/dev/null", "w", stdout))
  453. http_log("failed to redirect STDOUT to /dev/null\n;");
  454. if (!freopen("/dev/null", "w", stderr))
  455. http_log("failed to redirect STDERR to /dev/null\n;");
  456. }
  457. signal(SIGPIPE, SIG_DFL);
  458. execvp(pathname, feed->child_argv);
  459. av_free (pathname);
  460. _exit(1);
  461. }
  462. av_free (pathname);
  463. }
  464. /* open a listening socket */
  465. static int socket_open_listen(struct sockaddr_in *my_addr)
  466. {
  467. int server_fd, tmp;
  468. server_fd = socket(AF_INET,SOCK_STREAM,0);
  469. if (server_fd < 0) {
  470. perror ("socket");
  471. return -1;
  472. }
  473. tmp = 1;
  474. if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
  475. av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
  476. my_addr->sin_family = AF_INET;
  477. if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
  478. char bindmsg[32];
  479. snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
  480. ntohs(my_addr->sin_port));
  481. perror (bindmsg);
  482. goto fail;
  483. }
  484. if (listen (server_fd, 5) < 0) {
  485. perror ("listen");
  486. goto fail;
  487. }
  488. if (ff_socket_nonblock(server_fd, 1) < 0)
  489. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  490. return server_fd;
  491. fail:
  492. closesocket(server_fd);
  493. return -1;
  494. }
  495. /* start all multicast streams */
  496. static void start_multicast(void)
  497. {
  498. FFServerStream *stream;
  499. char session_id[32];
  500. HTTPContext *rtp_c;
  501. struct sockaddr_in dest_addr = {0};
  502. int default_port, stream_index;
  503. unsigned int random0, random1;
  504. default_port = 6000;
  505. for(stream = config.first_stream; stream; stream = stream->next) {
  506. if (!stream->is_multicast)
  507. continue;
  508. random0 = av_lfg_get(&random_state);
  509. random1 = av_lfg_get(&random_state);
  510. /* open the RTP connection */
  511. snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
  512. /* choose a port if none given */
  513. if (stream->multicast_port == 0) {
  514. stream->multicast_port = default_port;
  515. default_port += 100;
  516. }
  517. dest_addr.sin_family = AF_INET;
  518. dest_addr.sin_addr = stream->multicast_ip;
  519. dest_addr.sin_port = htons(stream->multicast_port);
  520. rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
  521. RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  522. if (!rtp_c)
  523. continue;
  524. if (open_input_stream(rtp_c, "") < 0) {
  525. http_log("Could not open input stream for stream '%s'\n",
  526. stream->filename);
  527. continue;
  528. }
  529. /* open each RTP stream */
  530. for(stream_index = 0; stream_index < stream->nb_streams;
  531. stream_index++) {
  532. dest_addr.sin_port = htons(stream->multicast_port +
  533. 2 * stream_index);
  534. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
  535. continue;
  536. http_log("Could not open output stream '%s/streamid=%d'\n",
  537. stream->filename, stream_index);
  538. exit(1);
  539. }
  540. rtp_c->state = HTTPSTATE_SEND_DATA;
  541. }
  542. }
  543. /* main loop of the HTTP server */
  544. static int http_server(void)
  545. {
  546. int server_fd = 0, rtsp_server_fd = 0;
  547. int ret, delay;
  548. struct pollfd *poll_table, *poll_entry;
  549. HTTPContext *c, *c_next;
  550. poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
  551. sizeof(*poll_table));
  552. if(!poll_table) {
  553. http_log("Impossible to allocate a poll table handling %d "
  554. "connections.\n", config.nb_max_http_connections);
  555. return -1;
  556. }
  557. if (config.http_addr.sin_port) {
  558. server_fd = socket_open_listen(&config.http_addr);
  559. if (server_fd < 0)
  560. goto quit;
  561. }
  562. if (config.rtsp_addr.sin_port) {
  563. rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
  564. if (rtsp_server_fd < 0) {
  565. closesocket(server_fd);
  566. goto quit;
  567. }
  568. }
  569. if (!rtsp_server_fd && !server_fd) {
  570. http_log("HTTP and RTSP disabled.\n");
  571. goto quit;
  572. }
  573. http_log("FFserver started.\n");
  574. start_children(config.first_feed);
  575. start_multicast();
  576. for(;;) {
  577. poll_entry = poll_table;
  578. if (server_fd) {
  579. poll_entry->fd = server_fd;
  580. poll_entry->events = POLLIN;
  581. poll_entry++;
  582. }
  583. if (rtsp_server_fd) {
  584. poll_entry->fd = rtsp_server_fd;
  585. poll_entry->events = POLLIN;
  586. poll_entry++;
  587. }
  588. /* wait for events on each HTTP handle */
  589. c = first_http_ctx;
  590. delay = 1000;
  591. while (c) {
  592. int fd;
  593. fd = c->fd;
  594. switch(c->state) {
  595. case HTTPSTATE_SEND_HEADER:
  596. case RTSPSTATE_SEND_REPLY:
  597. case RTSPSTATE_SEND_PACKET:
  598. c->poll_entry = poll_entry;
  599. poll_entry->fd = fd;
  600. poll_entry->events = POLLOUT;
  601. poll_entry++;
  602. break;
  603. case HTTPSTATE_SEND_DATA_HEADER:
  604. case HTTPSTATE_SEND_DATA:
  605. case HTTPSTATE_SEND_DATA_TRAILER:
  606. if (!c->is_packetized) {
  607. /* for TCP, we output as much as we can
  608. * (may need to put a limit) */
  609. c->poll_entry = poll_entry;
  610. poll_entry->fd = fd;
  611. poll_entry->events = POLLOUT;
  612. poll_entry++;
  613. } else {
  614. /* when ffserver is doing the timing, we work by
  615. * looking at which packet needs to be sent every
  616. * 10 ms (one tick wait XXX: 10 ms assumed) */
  617. if (delay > 10)
  618. delay = 10;
  619. }
  620. break;
  621. case HTTPSTATE_WAIT_REQUEST:
  622. case HTTPSTATE_RECEIVE_DATA:
  623. case HTTPSTATE_WAIT_FEED:
  624. case RTSPSTATE_WAIT_REQUEST:
  625. /* need to catch errors */
  626. c->poll_entry = poll_entry;
  627. poll_entry->fd = fd;
  628. poll_entry->events = POLLIN;/* Maybe this will work */
  629. poll_entry++;
  630. break;
  631. default:
  632. c->poll_entry = NULL;
  633. break;
  634. }
  635. c = c->next;
  636. }
  637. /* wait for an event on one connection. We poll at least every
  638. * second to handle timeouts */
  639. do {
  640. ret = poll(poll_table, poll_entry - poll_table, delay);
  641. if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
  642. ff_neterrno() != AVERROR(EINTR)) {
  643. goto quit;
  644. }
  645. } while (ret < 0);
  646. cur_time = av_gettime() / 1000;
  647. if (need_to_start_children) {
  648. need_to_start_children = 0;
  649. start_children(config.first_feed);
  650. }
  651. /* now handle the events */
  652. for(c = first_http_ctx; c; c = c_next) {
  653. c_next = c->next;
  654. if (handle_connection(c) < 0) {
  655. log_connection(c);
  656. /* close and free the connection */
  657. close_connection(c);
  658. }
  659. }
  660. poll_entry = poll_table;
  661. if (server_fd) {
  662. /* new HTTP connection request ? */
  663. if (poll_entry->revents & POLLIN)
  664. new_connection(server_fd, 0);
  665. poll_entry++;
  666. }
  667. if (rtsp_server_fd) {
  668. /* new RTSP connection request ? */
  669. if (poll_entry->revents & POLLIN)
  670. new_connection(rtsp_server_fd, 1);
  671. }
  672. }
  673. quit:
  674. av_free(poll_table);
  675. return -1;
  676. }
  677. /* start waiting for a new HTTP/RTSP request */
  678. static void start_wait_request(HTTPContext *c, int is_rtsp)
  679. {
  680. c->buffer_ptr = c->buffer;
  681. c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
  682. c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
  683. c->timeout = cur_time +
  684. (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
  685. }
  686. static void http_send_too_busy_reply(int fd)
  687. {
  688. char buffer[400];
  689. int len = snprintf(buffer, sizeof(buffer),
  690. "HTTP/1.0 503 Server too busy\r\n"
  691. "Content-type: text/html\r\n"
  692. "\r\n"
  693. "<!DOCTYPE html>\n"
  694. "<html><head><title>Too busy</title></head><body>\r\n"
  695. "<p>The server is too busy to serve your request at "
  696. "this time.</p>\r\n"
  697. "<p>The number of current connections is %u, and this "
  698. "exceeds the limit of %u.</p>\r\n"
  699. "</body></html>\r\n",
  700. nb_connections, config.nb_max_connections);
  701. av_assert0(len < sizeof(buffer));
  702. if (send(fd, buffer, len, 0) < len)
  703. av_log(NULL, AV_LOG_WARNING,
  704. "Could not send too-busy reply, send() failed\n");
  705. }
  706. static void new_connection(int server_fd, int is_rtsp)
  707. {
  708. struct sockaddr_in from_addr;
  709. socklen_t len;
  710. int fd;
  711. HTTPContext *c = NULL;
  712. len = sizeof(from_addr);
  713. fd = accept(server_fd, (struct sockaddr *)&from_addr,
  714. &len);
  715. if (fd < 0) {
  716. http_log("error during accept %s\n", strerror(errno));
  717. return;
  718. }
  719. if (ff_socket_nonblock(fd, 1) < 0)
  720. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  721. if (nb_connections >= config.nb_max_connections) {
  722. http_send_too_busy_reply(fd);
  723. goto fail;
  724. }
  725. /* add a new connection */
  726. c = av_mallocz(sizeof(HTTPContext));
  727. if (!c)
  728. goto fail;
  729. c->fd = fd;
  730. c->poll_entry = NULL;
  731. c->from_addr = from_addr;
  732. c->buffer_size = IOBUFFER_INIT_SIZE;
  733. c->buffer = av_malloc(c->buffer_size);
  734. if (!c->buffer)
  735. goto fail;
  736. c->next = first_http_ctx;
  737. first_http_ctx = c;
  738. nb_connections++;
  739. start_wait_request(c, is_rtsp);
  740. return;
  741. fail:
  742. if (c) {
  743. av_freep(&c->buffer);
  744. av_free(c);
  745. }
  746. closesocket(fd);
  747. }
  748. static void close_connection(HTTPContext *c)
  749. {
  750. HTTPContext **cp, *c1;
  751. int i, nb_streams;
  752. AVFormatContext *ctx;
  753. AVStream *st;
  754. /* remove connection from list */
  755. cp = &first_http_ctx;
  756. while (*cp) {
  757. c1 = *cp;
  758. if (c1 == c)
  759. *cp = c->next;
  760. else
  761. cp = &c1->next;
  762. }
  763. /* remove references, if any (XXX: do it faster) */
  764. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  765. if (c1->rtsp_c == c)
  766. c1->rtsp_c = NULL;
  767. }
  768. /* remove connection associated resources */
  769. if (c->fd >= 0)
  770. closesocket(c->fd);
  771. if (c->fmt_in) {
  772. /* close each frame parser */
  773. for(i=0;i<c->fmt_in->nb_streams;i++) {
  774. st = c->fmt_in->streams[i];
  775. if (st->codec->codec)
  776. avcodec_close(st->codec);
  777. }
  778. avformat_close_input(&c->fmt_in);
  779. }
  780. /* free RTP output streams if any */
  781. nb_streams = 0;
  782. if (c->stream)
  783. nb_streams = c->stream->nb_streams;
  784. for(i=0;i<nb_streams;i++) {
  785. ctx = c->rtp_ctx[i];
  786. if (ctx) {
  787. av_write_trailer(ctx);
  788. av_dict_free(&ctx->metadata);
  789. av_freep(&ctx->streams[0]);
  790. av_freep(&ctx);
  791. }
  792. ffurl_close(c->rtp_handles[i]);
  793. }
  794. ctx = &c->fmt_ctx;
  795. if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
  796. /* prepare header */
  797. if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
  798. av_write_trailer(ctx);
  799. av_freep(&c->pb_buffer);
  800. avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  801. }
  802. }
  803. for(i=0; i<ctx->nb_streams; i++)
  804. av_freep(&ctx->streams[i]);
  805. av_freep(&ctx->streams);
  806. av_freep(&ctx->priv_data);
  807. if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
  808. current_bandwidth -= c->stream->bandwidth;
  809. /* signal that there is no feed if we are the feeder socket */
  810. if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
  811. c->stream->feed_opened = 0;
  812. close(c->feed_fd);
  813. }
  814. av_freep(&c->pb_buffer);
  815. av_freep(&c->packet_buffer);
  816. av_freep(&c->buffer);
  817. av_free(c);
  818. nb_connections--;
  819. }
  820. static int handle_connection(HTTPContext *c)
  821. {
  822. int len, ret;
  823. uint8_t *ptr;
  824. switch(c->state) {
  825. case HTTPSTATE_WAIT_REQUEST:
  826. case RTSPSTATE_WAIT_REQUEST:
  827. /* timeout ? */
  828. if ((c->timeout - cur_time) < 0)
  829. return -1;
  830. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  831. return -1;
  832. /* no need to read if no events */
  833. if (!(c->poll_entry->revents & POLLIN))
  834. return 0;
  835. /* read the data */
  836. read_loop:
  837. if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
  838. return -1;
  839. if (len < 0) {
  840. if (ff_neterrno() != AVERROR(EAGAIN) &&
  841. ff_neterrno() != AVERROR(EINTR))
  842. return -1;
  843. break;
  844. }
  845. /* search for end of request. */
  846. c->buffer_ptr += len;
  847. ptr = c->buffer_ptr;
  848. if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
  849. (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
  850. /* request found : parse it and reply */
  851. if (c->state == HTTPSTATE_WAIT_REQUEST)
  852. ret = http_parse_request(c);
  853. else
  854. ret = rtsp_parse_request(c);
  855. if (ret < 0)
  856. return -1;
  857. } else if (ptr >= c->buffer_end) {
  858. /* request too long: cannot do anything */
  859. return -1;
  860. } else goto read_loop;
  861. break;
  862. case HTTPSTATE_SEND_HEADER:
  863. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  864. return -1;
  865. /* no need to write if no events */
  866. if (!(c->poll_entry->revents & POLLOUT))
  867. return 0;
  868. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  869. if (len < 0) {
  870. if (ff_neterrno() != AVERROR(EAGAIN) &&
  871. ff_neterrno() != AVERROR(EINTR)) {
  872. goto close_connection;
  873. }
  874. break;
  875. }
  876. c->buffer_ptr += len;
  877. if (c->stream)
  878. c->stream->bytes_served += len;
  879. c->data_count += len;
  880. if (c->buffer_ptr >= c->buffer_end) {
  881. av_freep(&c->pb_buffer);
  882. /* if error, exit */
  883. if (c->http_error)
  884. return -1;
  885. /* all the buffer was sent : synchronize to the incoming
  886. * stream */
  887. c->state = HTTPSTATE_SEND_DATA_HEADER;
  888. c->buffer_ptr = c->buffer_end = c->buffer;
  889. }
  890. break;
  891. case HTTPSTATE_SEND_DATA:
  892. case HTTPSTATE_SEND_DATA_HEADER:
  893. case HTTPSTATE_SEND_DATA_TRAILER:
  894. /* for packetized output, we consider we can always write (the
  895. * input streams set the speed). It may be better to verify
  896. * that we do not rely too much on the kernel queues */
  897. if (!c->is_packetized) {
  898. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  899. return -1;
  900. /* no need to read if no events */
  901. if (!(c->poll_entry->revents & POLLOUT))
  902. return 0;
  903. }
  904. if (http_send_data(c) < 0)
  905. return -1;
  906. /* close connection if trailer sent */
  907. if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
  908. return -1;
  909. /* Check if it is a single jpeg frame 123 */
  910. if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
  911. close_connection(c);
  912. }
  913. break;
  914. case HTTPSTATE_RECEIVE_DATA:
  915. /* no need to read if no events */
  916. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  917. return -1;
  918. if (!(c->poll_entry->revents & POLLIN))
  919. return 0;
  920. if (http_receive_data(c) < 0)
  921. return -1;
  922. break;
  923. case HTTPSTATE_WAIT_FEED:
  924. /* no need to read if no events */
  925. if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
  926. return -1;
  927. /* nothing to do, we'll be waken up by incoming feed packets */
  928. break;
  929. case RTSPSTATE_SEND_REPLY:
  930. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  931. goto close_connection;
  932. /* no need to write if no events */
  933. if (!(c->poll_entry->revents & POLLOUT))
  934. return 0;
  935. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  936. if (len < 0) {
  937. if (ff_neterrno() != AVERROR(EAGAIN) &&
  938. ff_neterrno() != AVERROR(EINTR)) {
  939. goto close_connection;
  940. }
  941. break;
  942. }
  943. c->buffer_ptr += len;
  944. c->data_count += len;
  945. if (c->buffer_ptr >= c->buffer_end) {
  946. /* all the buffer was sent : wait for a new request */
  947. av_freep(&c->pb_buffer);
  948. start_wait_request(c, 1);
  949. }
  950. break;
  951. case RTSPSTATE_SEND_PACKET:
  952. if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
  953. av_freep(&c->packet_buffer);
  954. return -1;
  955. }
  956. /* no need to write if no events */
  957. if (!(c->poll_entry->revents & POLLOUT))
  958. return 0;
  959. len = send(c->fd, c->packet_buffer_ptr,
  960. c->packet_buffer_end - c->packet_buffer_ptr, 0);
  961. if (len < 0) {
  962. if (ff_neterrno() != AVERROR(EAGAIN) &&
  963. ff_neterrno() != AVERROR(EINTR)) {
  964. /* error : close connection */
  965. av_freep(&c->packet_buffer);
  966. return -1;
  967. }
  968. break;
  969. }
  970. c->packet_buffer_ptr += len;
  971. if (c->packet_buffer_ptr >= c->packet_buffer_end) {
  972. /* all the buffer was sent : wait for a new request */
  973. av_freep(&c->packet_buffer);
  974. c->state = RTSPSTATE_WAIT_REQUEST;
  975. }
  976. break;
  977. case HTTPSTATE_READY:
  978. /* nothing to do */
  979. break;
  980. default:
  981. return -1;
  982. }
  983. return 0;
  984. close_connection:
  985. av_freep(&c->pb_buffer);
  986. return -1;
  987. }
  988. static int extract_rates(char *rates, int ratelen, const char *request)
  989. {
  990. const char *p;
  991. for (p = request; *p && *p != '\r' && *p != '\n'; ) {
  992. if (av_strncasecmp(p, "Pragma:", 7) == 0) {
  993. const char *q = p + 7;
  994. while (*q && *q != '\n' && av_isspace(*q))
  995. q++;
  996. if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
  997. int stream_no;
  998. int rate_no;
  999. q += 20;
  1000. memset(rates, 0xff, ratelen);
  1001. while (1) {
  1002. while (*q && *q != '\n' && *q != ':')
  1003. q++;
  1004. if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
  1005. break;
  1006. stream_no--;
  1007. if (stream_no < ratelen && stream_no >= 0)
  1008. rates[stream_no] = rate_no;
  1009. while (*q && *q != '\n' && !av_isspace(*q))
  1010. q++;
  1011. }
  1012. return 1;
  1013. }
  1014. }
  1015. p = strchr(p, '\n');
  1016. if (!p)
  1017. break;
  1018. p++;
  1019. }
  1020. return 0;
  1021. }
  1022. static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec,
  1023. int bit_rate)
  1024. {
  1025. int i;
  1026. int best_bitrate = 100000000;
  1027. int best = -1;
  1028. for (i = 0; i < feed->nb_streams; i++) {
  1029. AVCodecContext *feed_codec = feed->streams[i]->codec;
  1030. if (feed_codec->codec_id != codec->codec_id ||
  1031. feed_codec->sample_rate != codec->sample_rate ||
  1032. feed_codec->width != codec->width ||
  1033. feed_codec->height != codec->height)
  1034. continue;
  1035. /* Potential stream */
  1036. /* We want the fastest stream less than bit_rate, or the slowest
  1037. * faster than bit_rate
  1038. */
  1039. if (feed_codec->bit_rate <= bit_rate) {
  1040. if (best_bitrate > bit_rate ||
  1041. feed_codec->bit_rate > best_bitrate) {
  1042. best_bitrate = feed_codec->bit_rate;
  1043. best = i;
  1044. }
  1045. continue;
  1046. }
  1047. if (feed_codec->bit_rate < best_bitrate) {
  1048. best_bitrate = feed_codec->bit_rate;
  1049. best = i;
  1050. }
  1051. }
  1052. return best;
  1053. }
  1054. static int modify_current_stream(HTTPContext *c, char *rates)
  1055. {
  1056. int i;
  1057. FFServerStream *req = c->stream;
  1058. int action_required = 0;
  1059. /* Not much we can do for a feed */
  1060. if (!req->feed)
  1061. return 0;
  1062. for (i = 0; i < req->nb_streams; i++) {
  1063. AVCodecContext *codec = req->streams[i]->codec;
  1064. switch(rates[i]) {
  1065. case 0:
  1066. c->switch_feed_streams[i] = req->feed_streams[i];
  1067. break;
  1068. case 1:
  1069. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
  1070. break;
  1071. case 2:
  1072. /* Wants off or slow */
  1073. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
  1074. #ifdef WANTS_OFF
  1075. /* This doesn't work well when it turns off the only stream! */
  1076. c->switch_feed_streams[i] = -2;
  1077. c->feed_streams[i] = -2;
  1078. #endif
  1079. break;
  1080. }
  1081. if (c->switch_feed_streams[i] >= 0 &&
  1082. c->switch_feed_streams[i] != c->feed_streams[i]) {
  1083. action_required = 1;
  1084. }
  1085. }
  1086. return action_required;
  1087. }
  1088. static void get_word(char *buf, int buf_size, const char **pp)
  1089. {
  1090. const char *p;
  1091. char *q;
  1092. #define SPACE_CHARS " \t\r\n"
  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_freep(&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. #define PBUFFER_SIZE 2048
  2613. *pbuffer = av_mallocz(PBUFFER_SIZE);
  2614. if (!*pbuffer)
  2615. goto sdp_done;
  2616. av_sdp_create(&avc, 1, *pbuffer, PBUFFER_SIZE);
  2617. sdp_done:
  2618. av_freep(&avc->streams);
  2619. av_dict_free(&avc->metadata);
  2620. av_free(avc);
  2621. av_free(avs);
  2622. return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
  2623. }
  2624. static void rtsp_cmd_options(HTTPContext *c, const char *url)
  2625. {
  2626. /* rtsp_reply_header(c, RTSP_STATUS_OK); */
  2627. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
  2628. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2629. avio_printf(c->pb, "Public: %s\r\n",
  2630. "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
  2631. avio_printf(c->pb, "\r\n");
  2632. }
  2633. static void rtsp_cmd_describe(HTTPContext *c, const char *url)
  2634. {
  2635. FFServerStream *stream;
  2636. char path1[1024];
  2637. const char *path;
  2638. uint8_t *content;
  2639. int content_length;
  2640. socklen_t len;
  2641. struct sockaddr_in my_addr;
  2642. /* find which URL is asked */
  2643. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2644. path = path1;
  2645. if (*path == '/')
  2646. path++;
  2647. for(stream = config.first_stream; stream; stream = stream->next) {
  2648. if (!stream->is_feed &&
  2649. stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
  2650. !strcmp(path, stream->filename)) {
  2651. goto found;
  2652. }
  2653. }
  2654. /* no stream found */
  2655. rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
  2656. return;
  2657. found:
  2658. /* prepare the media description in SDP format */
  2659. /* get the host IP */
  2660. len = sizeof(my_addr);
  2661. getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
  2662. content_length = prepare_sdp_description(stream, &content,
  2663. my_addr.sin_addr);
  2664. if (content_length < 0) {
  2665. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2666. return;
  2667. }
  2668. rtsp_reply_header(c, RTSP_STATUS_OK);
  2669. avio_printf(c->pb, "Content-Base: %s/\r\n", url);
  2670. avio_printf(c->pb, "Content-Type: application/sdp\r\n");
  2671. avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
  2672. avio_printf(c->pb, "\r\n");
  2673. avio_write(c->pb, content, content_length);
  2674. av_free(content);
  2675. }
  2676. static HTTPContext *find_rtp_session(const char *session_id)
  2677. {
  2678. HTTPContext *c;
  2679. if (session_id[0] == '\0')
  2680. return NULL;
  2681. for(c = first_http_ctx; c; c = c->next) {
  2682. if (!strcmp(c->session_id, session_id))
  2683. return c;
  2684. }
  2685. return NULL;
  2686. }
  2687. static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
  2688. {
  2689. RTSPTransportField *th;
  2690. int i;
  2691. for(i=0;i<h->nb_transports;i++) {
  2692. th = &h->transports[i];
  2693. if (th->lower_transport == lower_transport)
  2694. return th;
  2695. }
  2696. return NULL;
  2697. }
  2698. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  2699. RTSPMessageHeader *h)
  2700. {
  2701. FFServerStream *stream;
  2702. int stream_index, rtp_port, rtcp_port;
  2703. char buf[1024];
  2704. char path1[1024];
  2705. const char *path;
  2706. HTTPContext *rtp_c;
  2707. RTSPTransportField *th;
  2708. struct sockaddr_in dest_addr;
  2709. RTSPActionServerSetup setup;
  2710. /* find which URL is asked */
  2711. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2712. path = path1;
  2713. if (*path == '/')
  2714. path++;
  2715. /* now check each stream */
  2716. for(stream = config.first_stream; stream; stream = stream->next) {
  2717. if (stream->is_feed || !stream->fmt ||
  2718. strcmp(stream->fmt->name, "rtp")) {
  2719. continue;
  2720. }
  2721. /* accept aggregate filenames only if single stream */
  2722. if (!strcmp(path, stream->filename)) {
  2723. if (stream->nb_streams != 1) {
  2724. rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
  2725. return;
  2726. }
  2727. stream_index = 0;
  2728. goto found;
  2729. }
  2730. for(stream_index = 0; stream_index < stream->nb_streams;
  2731. stream_index++) {
  2732. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2733. stream->filename, stream_index);
  2734. if (!strcmp(path, buf))
  2735. goto found;
  2736. }
  2737. }
  2738. /* no stream found */
  2739. rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
  2740. return;
  2741. found:
  2742. /* generate session id if needed */
  2743. if (h->session_id[0] == '\0') {
  2744. unsigned random0 = av_lfg_get(&random_state);
  2745. unsigned random1 = av_lfg_get(&random_state);
  2746. snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
  2747. random0, random1);
  2748. }
  2749. /* find RTP session, and create it if none found */
  2750. rtp_c = find_rtp_session(h->session_id);
  2751. if (!rtp_c) {
  2752. /* always prefer UDP */
  2753. th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
  2754. if (!th) {
  2755. th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
  2756. if (!th) {
  2757. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2758. return;
  2759. }
  2760. }
  2761. rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
  2762. th->lower_transport);
  2763. if (!rtp_c) {
  2764. rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
  2765. return;
  2766. }
  2767. /* open input stream */
  2768. if (open_input_stream(rtp_c, "") < 0) {
  2769. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2770. return;
  2771. }
  2772. }
  2773. /* test if stream is OK (test needed because several SETUP needs
  2774. * to be done for a given file) */
  2775. if (rtp_c->stream != stream) {
  2776. rtsp_reply_error(c, RTSP_STATUS_SERVICE);
  2777. return;
  2778. }
  2779. /* test if stream is already set up */
  2780. if (rtp_c->rtp_ctx[stream_index]) {
  2781. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2782. return;
  2783. }
  2784. /* check transport */
  2785. th = find_transport(h, rtp_c->rtp_protocol);
  2786. if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  2787. th->client_port_min <= 0)) {
  2788. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2789. return;
  2790. }
  2791. /* setup default options */
  2792. setup.transport_option[0] = '\0';
  2793. dest_addr = rtp_c->from_addr;
  2794. dest_addr.sin_port = htons(th->client_port_min);
  2795. /* setup stream */
  2796. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
  2797. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2798. return;
  2799. }
  2800. /* now everything is OK, so we can send the connection parameters */
  2801. rtsp_reply_header(c, RTSP_STATUS_OK);
  2802. /* session ID */
  2803. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2804. switch(rtp_c->rtp_protocol) {
  2805. case RTSP_LOWER_TRANSPORT_UDP:
  2806. rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
  2807. rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
  2808. avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
  2809. "client_port=%d-%d;server_port=%d-%d",
  2810. th->client_port_min, th->client_port_max,
  2811. rtp_port, rtcp_port);
  2812. break;
  2813. case RTSP_LOWER_TRANSPORT_TCP:
  2814. avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
  2815. stream_index * 2, stream_index * 2 + 1);
  2816. break;
  2817. default:
  2818. break;
  2819. }
  2820. if (setup.transport_option[0] != '\0')
  2821. avio_printf(c->pb, ";%s", setup.transport_option);
  2822. avio_printf(c->pb, "\r\n");
  2823. avio_printf(c->pb, "\r\n");
  2824. }
  2825. /**
  2826. * find an RTP connection by using the session ID. Check consistency
  2827. * with filename
  2828. */
  2829. static HTTPContext *find_rtp_session_with_url(const char *url,
  2830. const char *session_id)
  2831. {
  2832. HTTPContext *rtp_c;
  2833. char path1[1024];
  2834. const char *path;
  2835. char buf[1024];
  2836. int s, len;
  2837. rtp_c = find_rtp_session(session_id);
  2838. if (!rtp_c)
  2839. return NULL;
  2840. /* find which URL is asked */
  2841. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2842. path = path1;
  2843. if (*path == '/')
  2844. path++;
  2845. if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
  2846. for(s=0; s<rtp_c->stream->nb_streams; ++s) {
  2847. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2848. rtp_c->stream->filename, s);
  2849. if(!strncmp(path, buf, sizeof(buf)))
  2850. /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
  2851. * if nb_streams>1? */
  2852. return rtp_c;
  2853. }
  2854. len = strlen(path);
  2855. if (len > 0 && path[len - 1] == '/' &&
  2856. !strncmp(path, rtp_c->stream->filename, len - 1))
  2857. return rtp_c;
  2858. return NULL;
  2859. }
  2860. static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
  2861. {
  2862. HTTPContext *rtp_c;
  2863. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2864. if (!rtp_c) {
  2865. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2866. return;
  2867. }
  2868. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2869. rtp_c->state != HTTPSTATE_WAIT_FEED &&
  2870. rtp_c->state != HTTPSTATE_READY) {
  2871. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2872. return;
  2873. }
  2874. rtp_c->state = HTTPSTATE_SEND_DATA;
  2875. /* now everything is OK, so we can send the connection parameters */
  2876. rtsp_reply_header(c, RTSP_STATUS_OK);
  2877. /* session ID */
  2878. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2879. avio_printf(c->pb, "\r\n");
  2880. }
  2881. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  2882. RTSPMessageHeader *h, int pause_only)
  2883. {
  2884. HTTPContext *rtp_c;
  2885. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2886. if (!rtp_c) {
  2887. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2888. return;
  2889. }
  2890. if (pause_only) {
  2891. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2892. rtp_c->state != HTTPSTATE_WAIT_FEED) {
  2893. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2894. return;
  2895. }
  2896. rtp_c->state = HTTPSTATE_READY;
  2897. rtp_c->first_pts = AV_NOPTS_VALUE;
  2898. }
  2899. /* now everything is OK, so we can send the connection parameters */
  2900. rtsp_reply_header(c, RTSP_STATUS_OK);
  2901. /* session ID */
  2902. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2903. avio_printf(c->pb, "\r\n");
  2904. if (!pause_only)
  2905. close_connection(rtp_c);
  2906. }
  2907. /********************************************************************/
  2908. /* RTP handling */
  2909. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  2910. FFServerStream *stream,
  2911. const char *session_id,
  2912. enum RTSPLowerTransport rtp_protocol)
  2913. {
  2914. HTTPContext *c = NULL;
  2915. const char *proto_str;
  2916. /* XXX: should output a warning page when coming
  2917. * close to the connection limit */
  2918. if (nb_connections >= config.nb_max_connections)
  2919. goto fail;
  2920. /* add a new connection */
  2921. c = av_mallocz(sizeof(HTTPContext));
  2922. if (!c)
  2923. goto fail;
  2924. c->fd = -1;
  2925. c->poll_entry = NULL;
  2926. c->from_addr = *from_addr;
  2927. c->buffer_size = IOBUFFER_INIT_SIZE;
  2928. c->buffer = av_malloc(c->buffer_size);
  2929. if (!c->buffer)
  2930. goto fail;
  2931. nb_connections++;
  2932. c->stream = stream;
  2933. av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
  2934. c->state = HTTPSTATE_READY;
  2935. c->is_packetized = 1;
  2936. c->rtp_protocol = rtp_protocol;
  2937. /* protocol is shown in statistics */
  2938. switch(c->rtp_protocol) {
  2939. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  2940. proto_str = "MCAST";
  2941. break;
  2942. case RTSP_LOWER_TRANSPORT_UDP:
  2943. proto_str = "UDP";
  2944. break;
  2945. case RTSP_LOWER_TRANSPORT_TCP:
  2946. proto_str = "TCP";
  2947. break;
  2948. default:
  2949. proto_str = "???";
  2950. break;
  2951. }
  2952. av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
  2953. av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
  2954. current_bandwidth += stream->bandwidth;
  2955. c->next = first_http_ctx;
  2956. first_http_ctx = c;
  2957. return c;
  2958. fail:
  2959. if (c) {
  2960. av_freep(&c->buffer);
  2961. av_free(c);
  2962. }
  2963. return NULL;
  2964. }
  2965. /**
  2966. * add a new RTP stream in an RTP connection (used in RTSP SETUP
  2967. * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
  2968. * used.
  2969. */
  2970. static int rtp_new_av_stream(HTTPContext *c,
  2971. int stream_index, struct sockaddr_in *dest_addr,
  2972. HTTPContext *rtsp_c)
  2973. {
  2974. AVFormatContext *ctx;
  2975. AVStream *st;
  2976. char *ipaddr;
  2977. URLContext *h = NULL;
  2978. uint8_t *dummy_buf;
  2979. int max_packet_size;
  2980. void *st_internal;
  2981. /* now we can open the relevant output stream */
  2982. ctx = avformat_alloc_context();
  2983. if (!ctx)
  2984. return -1;
  2985. ctx->oformat = av_guess_format("rtp", NULL, NULL);
  2986. st = avformat_new_stream(ctx, NULL);
  2987. if (!st)
  2988. goto fail;
  2989. av_freep(&st->codec);
  2990. av_freep(&st->info);
  2991. st_internal = st->internal;
  2992. if (!c->stream->feed ||
  2993. c->stream->feed == c->stream)
  2994. memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
  2995. else
  2996. memcpy(st,
  2997. c->stream->feed->streams[c->stream->feed_streams[stream_index]],
  2998. sizeof(AVStream));
  2999. st->priv_data = NULL;
  3000. st->internal = st_internal;
  3001. /* build destination RTP address */
  3002. ipaddr = inet_ntoa(dest_addr->sin_addr);
  3003. switch(c->rtp_protocol) {
  3004. case RTSP_LOWER_TRANSPORT_UDP:
  3005. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  3006. /* RTP/UDP case */
  3007. /* XXX: also pass as parameter to function ? */
  3008. if (c->stream->is_multicast) {
  3009. int ttl;
  3010. ttl = c->stream->multicast_ttl;
  3011. if (!ttl)
  3012. ttl = 16;
  3013. snprintf(ctx->filename, sizeof(ctx->filename),
  3014. "rtp://%s:%d?multicast=1&ttl=%d",
  3015. ipaddr, ntohs(dest_addr->sin_port), ttl);
  3016. } else {
  3017. snprintf(ctx->filename, sizeof(ctx->filename),
  3018. "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
  3019. }
  3020. if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
  3021. goto fail;
  3022. c->rtp_handles[stream_index] = h;
  3023. max_packet_size = h->max_packet_size;
  3024. break;
  3025. case RTSP_LOWER_TRANSPORT_TCP:
  3026. /* RTP/TCP case */
  3027. c->rtsp_c = rtsp_c;
  3028. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  3029. break;
  3030. default:
  3031. goto fail;
  3032. }
  3033. http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
  3034. ipaddr, ntohs(dest_addr->sin_port),
  3035. c->stream->filename, stream_index, c->protocol);
  3036. /* normally, no packets should be output here, but the packet size may
  3037. * be checked */
  3038. if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
  3039. /* XXX: close stream */
  3040. goto fail;
  3041. if (avformat_write_header(ctx, NULL) < 0) {
  3042. fail:
  3043. if (h)
  3044. ffurl_close(h);
  3045. av_free(st);
  3046. av_free(ctx);
  3047. return -1;
  3048. }
  3049. avio_close_dyn_buf(ctx->pb, &dummy_buf);
  3050. ctx->pb = NULL;
  3051. av_free(dummy_buf);
  3052. c->rtp_ctx[stream_index] = ctx;
  3053. return 0;
  3054. }
  3055. /********************************************************************/
  3056. /* ffserver initialization */
  3057. /* FIXME: This code should use avformat_new_stream() */
  3058. static AVStream *add_av_stream1(FFServerStream *stream,
  3059. AVCodecContext *codec, int copy)
  3060. {
  3061. AVStream *fst;
  3062. if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
  3063. return NULL;
  3064. fst = av_mallocz(sizeof(AVStream));
  3065. if (!fst)
  3066. return NULL;
  3067. if (copy) {
  3068. fst->codec = avcodec_alloc_context3(codec->codec);
  3069. if (!fst->codec) {
  3070. av_free(fst);
  3071. return NULL;
  3072. }
  3073. avcodec_copy_context(fst->codec, codec);
  3074. } else
  3075. /* live streams must use the actual feed's codec since it may be
  3076. * updated later to carry extradata needed by them.
  3077. */
  3078. fst->codec = codec;
  3079. fst->priv_data = av_mallocz(sizeof(FeedData));
  3080. fst->internal = av_mallocz(sizeof(*fst->internal));
  3081. fst->internal->avctx = avcodec_alloc_context3(NULL);
  3082. fst->codecpar = avcodec_parameters_alloc();
  3083. fst->index = stream->nb_streams;
  3084. avpriv_set_pts_info(fst, 33, 1, 90000);
  3085. fst->sample_aspect_ratio = codec->sample_aspect_ratio;
  3086. stream->streams[stream->nb_streams++] = fst;
  3087. return fst;
  3088. }
  3089. /* return the stream number in the feed */
  3090. static int add_av_stream(FFServerStream *feed, AVStream *st)
  3091. {
  3092. AVStream *fst;
  3093. AVCodecContext *av, *av1;
  3094. int i;
  3095. av = st->codec;
  3096. for(i=0;i<feed->nb_streams;i++) {
  3097. av1 = feed->streams[i]->codec;
  3098. if (av1->codec_id == av->codec_id &&
  3099. av1->codec_type == av->codec_type &&
  3100. av1->bit_rate == av->bit_rate) {
  3101. switch(av->codec_type) {
  3102. case AVMEDIA_TYPE_AUDIO:
  3103. if (av1->channels == av->channels &&
  3104. av1->sample_rate == av->sample_rate)
  3105. return i;
  3106. break;
  3107. case AVMEDIA_TYPE_VIDEO:
  3108. if (av1->width == av->width &&
  3109. av1->height == av->height &&
  3110. av1->time_base.den == av->time_base.den &&
  3111. av1->time_base.num == av->time_base.num &&
  3112. av1->gop_size == av->gop_size)
  3113. return i;
  3114. break;
  3115. default:
  3116. abort();
  3117. }
  3118. }
  3119. }
  3120. fst = add_av_stream1(feed, av, 0);
  3121. if (!fst)
  3122. return -1;
  3123. if (av_stream_get_recommended_encoder_configuration(st))
  3124. av_stream_set_recommended_encoder_configuration(fst,
  3125. av_strdup(av_stream_get_recommended_encoder_configuration(st)));
  3126. return feed->nb_streams - 1;
  3127. }
  3128. static void remove_stream(FFServerStream *stream)
  3129. {
  3130. FFServerStream **ps;
  3131. ps = &config.first_stream;
  3132. while (*ps) {
  3133. if (*ps == stream)
  3134. *ps = (*ps)->next;
  3135. else
  3136. ps = &(*ps)->next;
  3137. }
  3138. }
  3139. /* specific MPEG4 handling : we extract the raw parameters */
  3140. static void extract_mpeg4_header(AVFormatContext *infile)
  3141. {
  3142. int mpeg4_count, i, size;
  3143. AVPacket pkt;
  3144. AVStream *st;
  3145. const uint8_t *p;
  3146. infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
  3147. mpeg4_count = 0;
  3148. for(i=0;i<infile->nb_streams;i++) {
  3149. st = infile->streams[i];
  3150. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  3151. st->codec->extradata_size == 0) {
  3152. mpeg4_count++;
  3153. }
  3154. }
  3155. if (!mpeg4_count)
  3156. return;
  3157. printf("MPEG4 without extra data: trying to find header in %s\n",
  3158. infile->filename);
  3159. while (mpeg4_count > 0) {
  3160. if (av_read_frame(infile, &pkt) < 0)
  3161. break;
  3162. st = infile->streams[pkt.stream_index];
  3163. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  3164. st->codec->extradata_size == 0) {
  3165. av_freep(&st->codec->extradata);
  3166. /* fill extradata with the header */
  3167. /* XXX: we make hard suppositions here ! */
  3168. p = pkt.data;
  3169. while (p < pkt.data + pkt.size - 4) {
  3170. /* stop when vop header is found */
  3171. if (p[0] == 0x00 && p[1] == 0x00 &&
  3172. p[2] == 0x01 && p[3] == 0xb6) {
  3173. size = p - pkt.data;
  3174. st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
  3175. st->codec->extradata_size = size;
  3176. memcpy(st->codec->extradata, pkt.data, size);
  3177. break;
  3178. }
  3179. p++;
  3180. }
  3181. mpeg4_count--;
  3182. }
  3183. av_packet_unref(&pkt);
  3184. }
  3185. }
  3186. /* compute the needed AVStream for each file */
  3187. static void build_file_streams(void)
  3188. {
  3189. FFServerStream *stream;
  3190. AVFormatContext *infile;
  3191. int i, ret;
  3192. /* gather all streams */
  3193. for(stream = config.first_stream; stream; stream = stream->next) {
  3194. infile = NULL;
  3195. if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
  3196. continue;
  3197. /* the stream comes from a file */
  3198. /* try to open the file */
  3199. /* open stream */
  3200. /* specific case: if transport stream output to RTP,
  3201. * we use a raw transport stream reader */
  3202. if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
  3203. av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
  3204. if (!stream->feed_filename[0]) {
  3205. http_log("Unspecified feed file for stream '%s'\n",
  3206. stream->filename);
  3207. goto fail;
  3208. }
  3209. http_log("Opening feed file '%s' for stream '%s'\n",
  3210. stream->feed_filename, stream->filename);
  3211. ret = avformat_open_input(&infile, stream->feed_filename,
  3212. stream->ifmt, &stream->in_opts);
  3213. if (ret < 0) {
  3214. http_log("Could not open '%s': %s\n", stream->feed_filename,
  3215. av_err2str(ret));
  3216. /* remove stream (no need to spend more time on it) */
  3217. fail:
  3218. remove_stream(stream);
  3219. } else {
  3220. /* find all the AVStreams inside and reference them in
  3221. * 'stream' */
  3222. if (avformat_find_stream_info(infile, NULL) < 0) {
  3223. http_log("Could not find codec parameters from '%s'\n",
  3224. stream->feed_filename);
  3225. avformat_close_input(&infile);
  3226. goto fail;
  3227. }
  3228. extract_mpeg4_header(infile);
  3229. for(i=0;i<infile->nb_streams;i++)
  3230. add_av_stream1(stream, infile->streams[i]->codec, 1);
  3231. avformat_close_input(&infile);
  3232. }
  3233. }
  3234. }
  3235. static inline
  3236. int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs, int stream)
  3237. {
  3238. int matches = 1;
  3239. #define CHECK_CODEC(x) (ccf->x != ccs->x)
  3240. if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
  3241. http_log("Codecs do not match for stream %d\n", stream);
  3242. matches = 0;
  3243. } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
  3244. http_log("Codec bitrates do not match for stream %d\n", stream);
  3245. matches = 0;
  3246. } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
  3247. if (CHECK_CODEC(time_base.den) ||
  3248. CHECK_CODEC(time_base.num) ||
  3249. CHECK_CODEC(width) ||
  3250. CHECK_CODEC(height)) {
  3251. http_log("Codec width, height or framerate do not match for stream %d\n", stream);
  3252. matches = 0;
  3253. }
  3254. } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
  3255. if (CHECK_CODEC(sample_rate) ||
  3256. CHECK_CODEC(channels) ||
  3257. CHECK_CODEC(frame_size)) {
  3258. http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
  3259. matches = 0;
  3260. }
  3261. } else {
  3262. http_log("Unknown codec type for stream %d\n", stream);
  3263. matches = 0;
  3264. }
  3265. return matches;
  3266. }
  3267. /* compute the needed AVStream for each feed */
  3268. static int build_feed_streams(void)
  3269. {
  3270. FFServerStream *stream, *feed;
  3271. int i, fd;
  3272. /* gather all streams */
  3273. for(stream = config.first_stream; stream; stream = stream->next) {
  3274. feed = stream->feed;
  3275. if (!feed)
  3276. continue;
  3277. if (stream->is_feed) {
  3278. for(i=0;i<stream->nb_streams;i++)
  3279. stream->feed_streams[i] = i;
  3280. continue;
  3281. }
  3282. /* we handle a stream coming from a feed */
  3283. for(i=0;i<stream->nb_streams;i++)
  3284. stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
  3285. }
  3286. /* create feed files if needed */
  3287. for(feed = config.first_feed; feed; feed = feed->next_feed) {
  3288. if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
  3289. AVFormatContext *s = NULL;
  3290. int matches = 0;
  3291. /* See if it matches */
  3292. if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
  3293. http_log("Deleting feed file '%s' as it appears "
  3294. "to be corrupt\n",
  3295. feed->feed_filename);
  3296. goto drop;
  3297. }
  3298. /* set buffer size */
  3299. if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
  3300. http_log("Failed to set buffer size\n");
  3301. avformat_close_input(&s);
  3302. goto bail;
  3303. }
  3304. /* Now see if it matches */
  3305. if (s->nb_streams != feed->nb_streams) {
  3306. http_log("Deleting feed file '%s' as stream counts "
  3307. "differ (%d != %d)\n",
  3308. feed->feed_filename, s->nb_streams, feed->nb_streams);
  3309. goto drop;
  3310. }
  3311. matches = 1;
  3312. for(i=0;i<s->nb_streams;i++) {
  3313. AVStream *sf, *ss;
  3314. sf = feed->streams[i];
  3315. ss = s->streams[i];
  3316. if (sf->index != ss->index || sf->id != ss->id) {
  3317. http_log("Index & Id do not match for stream %d (%s)\n",
  3318. i, feed->feed_filename);
  3319. matches = 0;
  3320. break;
  3321. }
  3322. matches = check_codec_match (sf->codec, ss->codec, i);
  3323. if (!matches)
  3324. break;
  3325. }
  3326. drop:
  3327. if (s)
  3328. avformat_close_input(&s);
  3329. if (!matches) {
  3330. if (feed->readonly) {
  3331. http_log("Unable to delete read-only feed file '%s'\n",
  3332. feed->feed_filename);
  3333. goto bail;
  3334. }
  3335. unlink(feed->feed_filename);
  3336. }
  3337. }
  3338. if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
  3339. AVFormatContext *s = avformat_alloc_context();
  3340. if (!s) {
  3341. http_log("Failed to allocate context\n");
  3342. goto bail;
  3343. }
  3344. if (feed->readonly) {
  3345. http_log("Unable to create feed file '%s' as it is "
  3346. "marked readonly\n",
  3347. feed->feed_filename);
  3348. avformat_free_context(s);
  3349. goto bail;
  3350. }
  3351. /* only write the header of the ffm file */
  3352. if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
  3353. http_log("Could not open output feed file '%s'\n",
  3354. feed->feed_filename);
  3355. avformat_free_context(s);
  3356. goto bail;
  3357. }
  3358. s->oformat = feed->fmt;
  3359. s->nb_streams = feed->nb_streams;
  3360. s->streams = feed->streams;
  3361. if (avformat_write_header(s, NULL) < 0) {
  3362. http_log("Container doesn't support the required parameters\n");
  3363. avio_closep(&s->pb);
  3364. s->streams = NULL;
  3365. s->nb_streams = 0;
  3366. avformat_free_context(s);
  3367. goto bail;
  3368. }
  3369. /* XXX: need better API */
  3370. av_freep(&s->priv_data);
  3371. avio_closep(&s->pb);
  3372. s->streams = NULL;
  3373. s->nb_streams = 0;
  3374. avformat_free_context(s);
  3375. }
  3376. /* get feed size and write index */
  3377. fd = open(feed->feed_filename, O_RDONLY);
  3378. if (fd < 0) {
  3379. http_log("Could not open output feed file '%s'\n",
  3380. feed->feed_filename);
  3381. goto bail;
  3382. }
  3383. feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
  3384. FFM_PACKET_SIZE);
  3385. feed->feed_size = lseek(fd, 0, SEEK_END);
  3386. /* ensure that we do not wrap before the end of file */
  3387. if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
  3388. feed->feed_max_size = feed->feed_size;
  3389. close(fd);
  3390. }
  3391. return 0;
  3392. bail:
  3393. return -1;
  3394. }
  3395. /* compute the bandwidth used by each stream */
  3396. static void compute_bandwidth(void)
  3397. {
  3398. unsigned bandwidth;
  3399. int i;
  3400. FFServerStream *stream;
  3401. for(stream = config.first_stream; stream; stream = stream->next) {
  3402. bandwidth = 0;
  3403. for(i=0;i<stream->nb_streams;i++) {
  3404. AVStream *st = stream->streams[i];
  3405. switch(st->codec->codec_type) {
  3406. case AVMEDIA_TYPE_AUDIO:
  3407. case AVMEDIA_TYPE_VIDEO:
  3408. bandwidth += st->codec->bit_rate;
  3409. break;
  3410. default:
  3411. break;
  3412. }
  3413. }
  3414. stream->bandwidth = (bandwidth + 999) / 1000;
  3415. }
  3416. }
  3417. static void handle_child_exit(int sig)
  3418. {
  3419. pid_t pid;
  3420. int status;
  3421. time_t uptime;
  3422. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  3423. FFServerStream *feed;
  3424. for (feed = config.first_feed; feed; feed = feed->next) {
  3425. if (feed->pid != pid)
  3426. continue;
  3427. uptime = time(0) - feed->pid_start;
  3428. feed->pid = 0;
  3429. fprintf(stderr,
  3430. "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
  3431. "seconds\n",
  3432. feed->filename, (int64_t) pid, status, (int64_t)uptime);
  3433. if (uptime < 30)
  3434. /* Turn off any more restarts */
  3435. ffserver_free_child_args(&feed->child_argv);
  3436. }
  3437. }
  3438. need_to_start_children = 1;
  3439. }
  3440. static void opt_debug(void)
  3441. {
  3442. config.debug = 1;
  3443. snprintf(config.logfilename, sizeof(config.logfilename), "-");
  3444. }
  3445. void show_help_default(const char *opt, const char *arg)
  3446. {
  3447. printf("usage: ffserver [options]\n"
  3448. "Hyper fast multi format Audio/Video streaming server\n");
  3449. printf("\n");
  3450. show_help_options(options, "Main options:", 0, 0, 0);
  3451. }
  3452. static const OptionDef options[] = {
  3453. #include "cmdutils_common_opts.h"
  3454. { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
  3455. { "d", 0, {(void*)opt_debug}, "enable debug mode" },
  3456. { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
  3457. { NULL },
  3458. };
  3459. int main(int argc, char **argv)
  3460. {
  3461. struct sigaction sigact = { { 0 } };
  3462. int cfg_parsed;
  3463. int ret = EXIT_FAILURE;
  3464. init_dynload();
  3465. config.filename = av_strdup("/etc/ffserver.conf");
  3466. parse_loglevel(argc, argv, options);
  3467. av_register_all();
  3468. avformat_network_init();
  3469. show_banner(argc, argv, options);
  3470. my_program_name = argv[0];
  3471. parse_options(NULL, argc, argv, options, NULL);
  3472. unsetenv("http_proxy"); /* Kill the http_proxy */
  3473. av_lfg_init(&random_state, av_get_random_seed());
  3474. sigact.sa_handler = handle_child_exit;
  3475. sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
  3476. sigaction(SIGCHLD, &sigact, 0);
  3477. if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
  3478. fprintf(stderr, "Error reading configuration file '%s': %s\n",
  3479. config.filename, av_err2str(cfg_parsed));
  3480. goto bail;
  3481. }
  3482. /* open log file if needed */
  3483. if (config.logfilename[0] != '\0') {
  3484. if (!strcmp(config.logfilename, "-"))
  3485. logfile = stdout;
  3486. else
  3487. logfile = fopen(config.logfilename, "a");
  3488. av_log_set_callback(http_av_log);
  3489. }
  3490. build_file_streams();
  3491. if (build_feed_streams() < 0) {
  3492. http_log("Could not setup feed streams\n");
  3493. goto bail;
  3494. }
  3495. compute_bandwidth();
  3496. /* signal init */
  3497. signal(SIGPIPE, SIG_IGN);
  3498. if (http_server() < 0) {
  3499. http_log("Could not start server\n");
  3500. goto bail;
  3501. }
  3502. ret=EXIT_SUCCESS;
  3503. bail:
  3504. av_freep (&config.filename);
  3505. avformat_network_deinit();
  3506. return ret;
  3507. }