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.

3872 lines
122KB

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