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.

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