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.

3914 lines
124KB

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