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.

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