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.

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