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.

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