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.

4025 lines
125KB

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