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.

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