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.

611 lines
18KB

  1. /*
  2. * UDP prototype streaming system
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * UDP protocol
  24. */
  25. #define _BSD_SOURCE /* Needed for using struct ip_mreq with recent glibc */
  26. #include "avformat.h"
  27. #include "avio_internal.h"
  28. #include "libavutil/parseutils.h"
  29. #include "libavutil/fifo.h"
  30. #include <unistd.h>
  31. #include "internal.h"
  32. #include "network.h"
  33. #include "os_support.h"
  34. #include "url.h"
  35. #include <pthread.h>
  36. #include <sys/time.h>
  37. #ifndef IPV6_ADD_MEMBERSHIP
  38. #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
  39. #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
  40. #endif
  41. typedef struct {
  42. int udp_fd;
  43. int ttl;
  44. int buffer_size;
  45. int is_multicast;
  46. int local_port;
  47. int reuse_socket;
  48. struct sockaddr_storage dest_addr;
  49. int dest_addr_len;
  50. int is_connected;
  51. /* Circular Buffer variables for use in UDP receive code */
  52. int circular_buffer_size;
  53. AVFifoBuffer *fifo;
  54. int circular_buffer_available_max;
  55. int circular_buffer_error;
  56. pthread_t circular_buffer_thread;
  57. } UDPContext;
  58. #define UDP_TX_BUF_SIZE 32768
  59. #define UDP_MAX_PKT_SIZE 65536
  60. static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
  61. struct sockaddr *addr)
  62. {
  63. #ifdef IP_MULTICAST_TTL
  64. if (addr->sa_family == AF_INET) {
  65. if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
  66. av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
  67. return -1;
  68. }
  69. }
  70. #endif
  71. #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
  72. if (addr->sa_family == AF_INET6) {
  73. if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
  74. av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
  75. return -1;
  76. }
  77. }
  78. #endif
  79. return 0;
  80. }
  81. static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
  82. {
  83. #ifdef IP_ADD_MEMBERSHIP
  84. if (addr->sa_family == AF_INET) {
  85. struct ip_mreq mreq;
  86. mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
  87. mreq.imr_interface.s_addr= INADDR_ANY;
  88. if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
  89. av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
  90. return -1;
  91. }
  92. }
  93. #endif
  94. #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
  95. if (addr->sa_family == AF_INET6) {
  96. struct ipv6_mreq mreq6;
  97. memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
  98. mreq6.ipv6mr_interface= 0;
  99. if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
  100. av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
  101. return -1;
  102. }
  103. }
  104. #endif
  105. return 0;
  106. }
  107. static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
  108. {
  109. #ifdef IP_DROP_MEMBERSHIP
  110. if (addr->sa_family == AF_INET) {
  111. struct ip_mreq mreq;
  112. mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
  113. mreq.imr_interface.s_addr= INADDR_ANY;
  114. if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
  115. av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
  116. return -1;
  117. }
  118. }
  119. #endif
  120. #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
  121. if (addr->sa_family == AF_INET6) {
  122. struct ipv6_mreq mreq6;
  123. memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
  124. mreq6.ipv6mr_interface= 0;
  125. if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
  126. av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
  127. return -1;
  128. }
  129. }
  130. #endif
  131. return 0;
  132. }
  133. static struct addrinfo* udp_resolve_host(const char *hostname, int port,
  134. int type, int family, int flags)
  135. {
  136. struct addrinfo hints, *res = 0;
  137. int error;
  138. char sport[16];
  139. const char *node = 0, *service = "0";
  140. if (port > 0) {
  141. snprintf(sport, sizeof(sport), "%d", port);
  142. service = sport;
  143. }
  144. if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
  145. node = hostname;
  146. }
  147. memset(&hints, 0, sizeof(hints));
  148. hints.ai_socktype = type;
  149. hints.ai_family = family;
  150. hints.ai_flags = flags;
  151. if ((error = getaddrinfo(node, service, &hints, &res))) {
  152. res = NULL;
  153. av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
  154. }
  155. return res;
  156. }
  157. static int udp_set_url(struct sockaddr_storage *addr,
  158. const char *hostname, int port)
  159. {
  160. struct addrinfo *res0;
  161. int addr_len;
  162. res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
  163. if (res0 == 0) return AVERROR(EIO);
  164. memcpy(addr, res0->ai_addr, res0->ai_addrlen);
  165. addr_len = res0->ai_addrlen;
  166. freeaddrinfo(res0);
  167. return addr_len;
  168. }
  169. static int udp_socket_create(UDPContext *s,
  170. struct sockaddr_storage *addr, int *addr_len)
  171. {
  172. int udp_fd = -1;
  173. struct addrinfo *res0 = NULL, *res = NULL;
  174. int family = AF_UNSPEC;
  175. if (((struct sockaddr *) &s->dest_addr)->sa_family)
  176. family = ((struct sockaddr *) &s->dest_addr)->sa_family;
  177. res0 = udp_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE);
  178. if (res0 == 0)
  179. goto fail;
  180. for (res = res0; res; res=res->ai_next) {
  181. udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
  182. if (udp_fd > 0) break;
  183. av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
  184. }
  185. if (udp_fd < 0)
  186. goto fail;
  187. memcpy(addr, res->ai_addr, res->ai_addrlen);
  188. *addr_len = res->ai_addrlen;
  189. freeaddrinfo(res0);
  190. return udp_fd;
  191. fail:
  192. if (udp_fd >= 0)
  193. closesocket(udp_fd);
  194. if(res0)
  195. freeaddrinfo(res0);
  196. return -1;
  197. }
  198. static int udp_port(struct sockaddr_storage *addr, int addr_len)
  199. {
  200. char sbuf[sizeof(int)*3+1];
  201. if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
  202. av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
  203. return -1;
  204. }
  205. return strtol(sbuf, NULL, 10);
  206. }
  207. /**
  208. * If no filename is given to av_open_input_file because you want to
  209. * get the local port first, then you must call this function to set
  210. * the remote server address.
  211. *
  212. * url syntax: udp://host:port[?option=val...]
  213. * option: 'ttl=n' : set the ttl value (for multicast only)
  214. * 'localport=n' : set the local port
  215. * 'pkt_size=n' : set max packet size
  216. * 'reuse=1' : enable reusing the socket
  217. *
  218. * @param h media file context
  219. * @param uri of the remote server
  220. * @return zero if no error.
  221. */
  222. int ff_udp_set_remote_url(URLContext *h, const char *uri)
  223. {
  224. UDPContext *s = h->priv_data;
  225. char hostname[256], buf[10];
  226. int port;
  227. const char *p;
  228. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  229. /* set the destination address */
  230. s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
  231. if (s->dest_addr_len < 0) {
  232. return AVERROR(EIO);
  233. }
  234. s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
  235. p = strchr(uri, '?');
  236. if (p) {
  237. if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
  238. int was_connected = s->is_connected;
  239. s->is_connected = strtol(buf, NULL, 10);
  240. if (s->is_connected && !was_connected) {
  241. if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
  242. s->dest_addr_len)) {
  243. s->is_connected = 0;
  244. av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
  245. return AVERROR(EIO);
  246. }
  247. }
  248. }
  249. }
  250. return 0;
  251. }
  252. /**
  253. * Return the local port used by the UDP connection
  254. * @param h media file context
  255. * @return the local port number
  256. */
  257. int ff_udp_get_local_port(URLContext *h)
  258. {
  259. UDPContext *s = h->priv_data;
  260. return s->local_port;
  261. }
  262. /**
  263. * Return the udp file handle for select() usage to wait for several RTP
  264. * streams at the same time.
  265. * @param h media file context
  266. */
  267. static int udp_get_file_handle(URLContext *h)
  268. {
  269. UDPContext *s = h->priv_data;
  270. return s->udp_fd;
  271. }
  272. static void *circular_buffer_task( void *_URLContext)
  273. {
  274. URLContext *h = _URLContext;
  275. UDPContext *s = h->priv_data;
  276. fd_set rfds;
  277. struct timeval tv;
  278. for(;;) {
  279. int left;
  280. int ret;
  281. int len;
  282. if (url_interrupt_cb()) {
  283. s->circular_buffer_error = EINTR;
  284. return NULL;
  285. }
  286. FD_ZERO(&rfds);
  287. FD_SET(s->udp_fd, &rfds);
  288. tv.tv_sec = 1;
  289. tv.tv_usec = 0;
  290. ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
  291. if (ret < 0) {
  292. if (ff_neterrno() == AVERROR(EINTR))
  293. continue;
  294. s->circular_buffer_error = EIO;
  295. return NULL;
  296. }
  297. if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))
  298. continue;
  299. /* How much do we have left to the end of the buffer */
  300. /* Whats the minimum we can read so that we dont comletely fill the buffer */
  301. left = av_fifo_space(s->fifo);
  302. left = FFMIN(left, s->fifo->end - s->fifo->wptr);
  303. /* No Space left, error, what do we do now */
  304. if( !left) {
  305. av_log(h, AV_LOG_ERROR, "circular_buffer: OVERRUN\n");
  306. s->circular_buffer_error = EIO;
  307. return NULL;
  308. }
  309. len = recv(s->udp_fd, s->fifo->wptr, left, 0);
  310. if (len < 0) {
  311. if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
  312. s->circular_buffer_error = EIO;
  313. return NULL;
  314. }
  315. }
  316. s->fifo->wptr += len;
  317. if (s->fifo->wptr >= s->fifo->end)
  318. s->fifo->wptr = s->fifo->buffer;
  319. s->fifo->wndx += len;
  320. }
  321. return NULL;
  322. }
  323. /* put it in UDP context */
  324. /* return non zero if error */
  325. static int udp_open(URLContext *h, const char *uri, int flags)
  326. {
  327. char hostname[1024];
  328. int port, udp_fd = -1, tmp, bind_ret = -1;
  329. UDPContext *s = NULL;
  330. int is_output;
  331. const char *p;
  332. char buf[256];
  333. struct sockaddr_storage my_addr;
  334. int len;
  335. int reuse_specified = 0;
  336. h->is_streamed = 1;
  337. h->max_packet_size = 1472;
  338. is_output = !(flags & AVIO_FLAG_READ);
  339. s = av_mallocz(sizeof(UDPContext));
  340. if (!s)
  341. return AVERROR(ENOMEM);
  342. h->priv_data = s;
  343. s->ttl = 16;
  344. s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
  345. s->circular_buffer_size = 7*188*4096;
  346. p = strchr(uri, '?');
  347. if (p) {
  348. if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
  349. char *endptr=NULL;
  350. s->reuse_socket = strtol(buf, &endptr, 10);
  351. /* assume if no digits were found it is a request to enable it */
  352. if (buf == endptr)
  353. s->reuse_socket = 1;
  354. reuse_specified = 1;
  355. }
  356. if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
  357. s->ttl = strtol(buf, NULL, 10);
  358. }
  359. if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
  360. s->local_port = strtol(buf, NULL, 10);
  361. }
  362. if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
  363. h->max_packet_size = strtol(buf, NULL, 10);
  364. }
  365. if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
  366. s->buffer_size = strtol(buf, NULL, 10);
  367. }
  368. if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
  369. s->is_connected = strtol(buf, NULL, 10);
  370. }
  371. if (av_find_info_tag(buf, sizeof(buf), "buf_size", p)) {
  372. s->circular_buffer_size = strtol(buf, NULL, 10)*188;
  373. }
  374. }
  375. /* fill the dest addr */
  376. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  377. /* XXX: fix av_url_split */
  378. if (hostname[0] == '\0' || hostname[0] == '?') {
  379. /* only accepts null hostname if input */
  380. if (!(flags & AVIO_FLAG_READ))
  381. goto fail;
  382. } else {
  383. if (ff_udp_set_remote_url(h, uri) < 0)
  384. goto fail;
  385. }
  386. if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
  387. s->local_port = port;
  388. udp_fd = udp_socket_create(s, &my_addr, &len);
  389. if (udp_fd < 0)
  390. goto fail;
  391. /* Follow the requested reuse option, unless it's multicast in which
  392. * case enable reuse unless explicitely disabled.
  393. */
  394. if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
  395. s->reuse_socket = 1;
  396. if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
  397. goto fail;
  398. }
  399. /* the bind is needed to give a port to the socket now */
  400. /* if multicast, try the multicast address bind first */
  401. if (s->is_multicast && (h->flags & AVIO_FLAG_READ)) {
  402. bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
  403. }
  404. /* bind to the local address if not multicast or if the multicast
  405. * bind failed */
  406. if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0)
  407. goto fail;
  408. len = sizeof(my_addr);
  409. getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
  410. s->local_port = udp_port(&my_addr, len);
  411. if (s->is_multicast) {
  412. if (!(h->flags & AVIO_FLAG_READ)) {
  413. /* output */
  414. if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
  415. goto fail;
  416. } else {
  417. /* input */
  418. if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
  419. goto fail;
  420. }
  421. }
  422. if (is_output) {
  423. /* limit the tx buf size to limit latency */
  424. tmp = s->buffer_size;
  425. if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
  426. av_log(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
  427. goto fail;
  428. }
  429. } else {
  430. /* set udp recv buffer size to the largest possible udp packet size to
  431. * avoid losing data on OSes that set this too low by default. */
  432. tmp = s->buffer_size;
  433. if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
  434. av_log(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
  435. }
  436. /* make the socket non-blocking */
  437. ff_socket_nonblock(udp_fd, 1);
  438. }
  439. if (s->is_connected) {
  440. if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
  441. av_log(h, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
  442. goto fail;
  443. }
  444. }
  445. s->udp_fd = udp_fd;
  446. if (!is_output && s->circular_buffer_size) {
  447. /* start the task going */
  448. s->fifo = av_fifo_alloc(s->circular_buffer_size);
  449. if (pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h)) {
  450. av_log(h, AV_LOG_ERROR, "pthread_create failed\n");
  451. goto fail;
  452. }
  453. }
  454. return 0;
  455. fail:
  456. if (udp_fd >= 0)
  457. closesocket(udp_fd);
  458. av_fifo_free(s->fifo);
  459. av_free(s);
  460. return AVERROR(EIO);
  461. }
  462. static int udp_read(URLContext *h, uint8_t *buf, int size)
  463. {
  464. UDPContext *s = h->priv_data;
  465. int ret;
  466. int avail;
  467. int left;
  468. fd_set rfds;
  469. struct timeval tv;
  470. if (s->fifo) {
  471. do {
  472. avail = av_fifo_size(s->fifo);
  473. if (avail) { // >=size) {
  474. // Maximum amount available
  475. size = FFMIN( avail, size);
  476. av_fifo_generic_read(s->fifo, buf, size, NULL);
  477. return size;
  478. }
  479. else {
  480. FD_ZERO(&rfds);
  481. FD_SET(s->udp_fd, &rfds);
  482. tv.tv_sec = 1;
  483. tv.tv_usec = 0;
  484. ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
  485. if (ret<0)
  486. return ret;
  487. }
  488. } while( 1);
  489. }
  490. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  491. ret = ff_network_wait_fd(s->udp_fd, 0);
  492. if (ret < 0)
  493. return ret;
  494. }
  495. ret = recv(s->udp_fd, buf, size, 0);
  496. return ret < 0 ? ff_neterrno() : ret;
  497. }
  498. static int udp_write(URLContext *h, const uint8_t *buf, int size)
  499. {
  500. UDPContext *s = h->priv_data;
  501. int ret;
  502. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  503. ret = ff_network_wait_fd(s->udp_fd, 1);
  504. if (ret < 0)
  505. return ret;
  506. }
  507. if (!s->is_connected) {
  508. ret = sendto (s->udp_fd, buf, size, 0,
  509. (struct sockaddr *) &s->dest_addr,
  510. s->dest_addr_len);
  511. } else
  512. ret = send(s->udp_fd, buf, size, 0);
  513. return ret < 0 ? ff_neterrno() : ret;
  514. }
  515. static int udp_close(URLContext *h)
  516. {
  517. UDPContext *s = h->priv_data;
  518. if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
  519. udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
  520. closesocket(s->udp_fd);
  521. av_log( h, AV_LOG_INFO, "circular_buffer_info max:%d%%\r\n", (s->circular_buffer_available_max*100)/s->circular_buffer_size);
  522. av_fifo_free(s->fifo);
  523. av_free(s);
  524. return 0;
  525. }
  526. URLProtocol ff_udp_protocol = {
  527. .name = "udp",
  528. .url_open = udp_open,
  529. .url_read = udp_read,
  530. .url_write = udp_write,
  531. .url_close = udp_close,
  532. .url_get_file_handle = udp_get_file_handle,
  533. };