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.

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