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.

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