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.

3906 lines
123KB

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