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.

3955 lines
123KB

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