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.

807 lines
27KB

  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 "libavutil/intreadwrite.h"
  31. #include "libavutil/avstring.h"
  32. #include "internal.h"
  33. #include "network.h"
  34. #include "os_support.h"
  35. #include "url.h"
  36. #if HAVE_PTHREAD_CANCEL
  37. #include <pthread.h>
  38. #endif
  39. #ifndef HAVE_PTHREAD_CANCEL
  40. #define HAVE_PTHREAD_CANCEL 0
  41. #endif
  42. #ifndef IPV6_ADD_MEMBERSHIP
  43. #define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
  44. #define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
  45. #endif
  46. #define UDP_TX_BUF_SIZE 32768
  47. #define UDP_MAX_PKT_SIZE 65536
  48. typedef struct {
  49. int udp_fd;
  50. int ttl;
  51. int buffer_size;
  52. int is_multicast;
  53. int local_port;
  54. int reuse_socket;
  55. int overrun_nonfatal;
  56. struct sockaddr_storage dest_addr;
  57. int dest_addr_len;
  58. int is_connected;
  59. /* Circular Buffer variables for use in UDP receive code */
  60. int circular_buffer_size;
  61. AVFifoBuffer *fifo;
  62. int circular_buffer_error;
  63. #if HAVE_PTHREAD_CANCEL
  64. pthread_t circular_buffer_thread;
  65. pthread_mutex_t mutex;
  66. pthread_cond_t cond;
  67. int thread_started;
  68. #endif
  69. uint8_t tmp[UDP_MAX_PKT_SIZE+4];
  70. int remaining_in_dg;
  71. } UDPContext;
  72. static void log_net_error(void *ctx, int level, const char* prefix)
  73. {
  74. char errbuf[100];
  75. av_strerror(ff_neterrno(), errbuf, sizeof(errbuf));
  76. av_log(ctx, level, "%s: %s\n", prefix, errbuf);
  77. }
  78. static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
  79. struct sockaddr *addr)
  80. {
  81. #ifdef IP_MULTICAST_TTL
  82. if (addr->sa_family == AF_INET) {
  83. if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
  84. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL)");
  85. return -1;
  86. }
  87. }
  88. #endif
  89. #if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
  90. if (addr->sa_family == AF_INET6) {
  91. if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
  92. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS)");
  93. return -1;
  94. }
  95. }
  96. #endif
  97. return 0;
  98. }
  99. static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
  100. {
  101. #ifdef IP_ADD_MEMBERSHIP
  102. if (addr->sa_family == AF_INET) {
  103. struct ip_mreq mreq;
  104. mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
  105. mreq.imr_interface.s_addr= INADDR_ANY;
  106. if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
  107. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP)");
  108. return -1;
  109. }
  110. }
  111. #endif
  112. #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
  113. if (addr->sa_family == AF_INET6) {
  114. struct ipv6_mreq mreq6;
  115. memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
  116. mreq6.ipv6mr_interface= 0;
  117. if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
  118. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP)");
  119. return -1;
  120. }
  121. }
  122. #endif
  123. return 0;
  124. }
  125. static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
  126. {
  127. #ifdef IP_DROP_MEMBERSHIP
  128. if (addr->sa_family == AF_INET) {
  129. struct ip_mreq mreq;
  130. mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
  131. mreq.imr_interface.s_addr= INADDR_ANY;
  132. if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
  133. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP)");
  134. return -1;
  135. }
  136. }
  137. #endif
  138. #if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
  139. if (addr->sa_family == AF_INET6) {
  140. struct ipv6_mreq mreq6;
  141. memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
  142. mreq6.ipv6mr_interface= 0;
  143. if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
  144. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP)");
  145. return -1;
  146. }
  147. }
  148. #endif
  149. return 0;
  150. }
  151. static struct addrinfo* udp_resolve_host(const char *hostname, int port,
  152. int type, int family, int flags)
  153. {
  154. struct addrinfo hints = { 0 }, *res = 0;
  155. int error;
  156. char sport[16];
  157. const char *node = 0, *service = "0";
  158. if (port > 0) {
  159. snprintf(sport, sizeof(sport), "%d", port);
  160. service = sport;
  161. }
  162. if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
  163. node = hostname;
  164. }
  165. hints.ai_socktype = type;
  166. hints.ai_family = family;
  167. hints.ai_flags = flags;
  168. if ((error = getaddrinfo(node, service, &hints, &res))) {
  169. res = NULL;
  170. av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
  171. }
  172. return res;
  173. }
  174. static int udp_set_multicast_sources(int sockfd, struct sockaddr *addr,
  175. int addr_len, char **sources,
  176. int nb_sources, int include)
  177. {
  178. #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
  179. /* These ones are available in the microsoft SDK, but don't seem to work
  180. * as on linux, so just prefer the v4-only approach there for now. */
  181. int i;
  182. for (i = 0; i < nb_sources; i++) {
  183. struct group_source_req mreqs;
  184. int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
  185. struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
  186. SOCK_DGRAM, AF_UNSPEC,
  187. AI_NUMERICHOST);
  188. if (!sourceaddr)
  189. return AVERROR(ENOENT);
  190. mreqs.gsr_interface = 0;
  191. memcpy(&mreqs.gsr_group, addr, addr_len);
  192. memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
  193. freeaddrinfo(sourceaddr);
  194. if (setsockopt(sockfd, level,
  195. include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
  196. (const void *)&mreqs, sizeof(mreqs)) < 0) {
  197. if (include)
  198. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
  199. else
  200. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
  201. return ff_neterrno();
  202. }
  203. }
  204. #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
  205. int i;
  206. if (addr->sa_family != AF_INET) {
  207. av_log(NULL, AV_LOG_ERROR,
  208. "Setting multicast sources only supported for IPv4\n");
  209. return AVERROR(EINVAL);
  210. }
  211. for (i = 0; i < nb_sources; i++) {
  212. struct ip_mreq_source mreqs;
  213. struct addrinfo *sourceaddr = udp_resolve_host(sources[i], 0,
  214. SOCK_DGRAM, AF_UNSPEC,
  215. AI_NUMERICHOST);
  216. if (!sourceaddr)
  217. return AVERROR(ENOENT);
  218. if (sourceaddr->ai_addr->sa_family != AF_INET) {
  219. freeaddrinfo(sourceaddr);
  220. av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
  221. sources[i]);
  222. return AVERROR(EINVAL);
  223. }
  224. mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
  225. mreqs.imr_interface.s_addr = INADDR_ANY;
  226. mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
  227. freeaddrinfo(sourceaddr);
  228. if (setsockopt(sockfd, IPPROTO_IP,
  229. include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
  230. (const void *)&mreqs, sizeof(mreqs)) < 0) {
  231. if (include)
  232. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
  233. else
  234. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
  235. return ff_neterrno();
  236. }
  237. }
  238. #else
  239. return AVERROR(ENOSYS);
  240. #endif
  241. return 0;
  242. }
  243. static int udp_set_url(struct sockaddr_storage *addr,
  244. const char *hostname, int port)
  245. {
  246. struct addrinfo *res0;
  247. int addr_len;
  248. res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
  249. if (res0 == 0) return AVERROR(EIO);
  250. memcpy(addr, res0->ai_addr, res0->ai_addrlen);
  251. addr_len = res0->ai_addrlen;
  252. freeaddrinfo(res0);
  253. return addr_len;
  254. }
  255. static int udp_socket_create(UDPContext *s, struct sockaddr_storage *addr,
  256. int *addr_len, const char *localaddr)
  257. {
  258. int udp_fd = -1;
  259. struct addrinfo *res0 = NULL, *res = NULL;
  260. int family = AF_UNSPEC;
  261. if (((struct sockaddr *) &s->dest_addr)->sa_family)
  262. family = ((struct sockaddr *) &s->dest_addr)->sa_family;
  263. res0 = udp_resolve_host(localaddr[0] ? localaddr : NULL, s->local_port,
  264. SOCK_DGRAM, family, AI_PASSIVE);
  265. if (res0 == 0)
  266. goto fail;
  267. for (res = res0; res; res=res->ai_next) {
  268. udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
  269. if (udp_fd != -1) break;
  270. log_net_error(NULL, AV_LOG_ERROR, "socket");
  271. }
  272. if (udp_fd < 0)
  273. goto fail;
  274. memcpy(addr, res->ai_addr, res->ai_addrlen);
  275. *addr_len = res->ai_addrlen;
  276. freeaddrinfo(res0);
  277. return udp_fd;
  278. fail:
  279. if (udp_fd >= 0)
  280. closesocket(udp_fd);
  281. if(res0)
  282. freeaddrinfo(res0);
  283. return -1;
  284. }
  285. static int udp_port(struct sockaddr_storage *addr, int addr_len)
  286. {
  287. char sbuf[sizeof(int)*3+1];
  288. int error;
  289. if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
  290. av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
  291. return -1;
  292. }
  293. return strtol(sbuf, NULL, 10);
  294. }
  295. /**
  296. * If no filename is given to av_open_input_file because you want to
  297. * get the local port first, then you must call this function to set
  298. * the remote server address.
  299. *
  300. * url syntax: udp://host:port[?option=val...]
  301. * option: 'ttl=n' : set the ttl value (for multicast only)
  302. * 'localport=n' : set the local port
  303. * 'pkt_size=n' : set max packet size
  304. * 'reuse=1' : enable reusing the socket
  305. * 'overrun_nonfatal=1': survive in case of circular buffer overrun
  306. *
  307. * @param h media file context
  308. * @param uri of the remote server
  309. * @return zero if no error.
  310. */
  311. int ff_udp_set_remote_url(URLContext *h, const char *uri)
  312. {
  313. UDPContext *s = h->priv_data;
  314. char hostname[256], buf[10];
  315. int port;
  316. const char *p;
  317. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  318. /* set the destination address */
  319. s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
  320. if (s->dest_addr_len < 0) {
  321. return AVERROR(EIO);
  322. }
  323. s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
  324. p = strchr(uri, '?');
  325. if (p) {
  326. if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
  327. int was_connected = s->is_connected;
  328. s->is_connected = strtol(buf, NULL, 10);
  329. if (s->is_connected && !was_connected) {
  330. if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
  331. s->dest_addr_len)) {
  332. s->is_connected = 0;
  333. log_net_error(h, AV_LOG_ERROR, "connect");
  334. return AVERROR(EIO);
  335. }
  336. }
  337. }
  338. }
  339. return 0;
  340. }
  341. /**
  342. * Return the local port used by the UDP connection
  343. * @param h media file context
  344. * @return the local port number
  345. */
  346. int ff_udp_get_local_port(URLContext *h)
  347. {
  348. UDPContext *s = h->priv_data;
  349. return s->local_port;
  350. }
  351. /**
  352. * Return the udp file handle for select() usage to wait for several RTP
  353. * streams at the same time.
  354. * @param h media file context
  355. */
  356. static int udp_get_file_handle(URLContext *h)
  357. {
  358. UDPContext *s = h->priv_data;
  359. return s->udp_fd;
  360. }
  361. #if HAVE_PTHREAD_CANCEL
  362. static void *circular_buffer_task( void *_URLContext)
  363. {
  364. URLContext *h = _URLContext;
  365. UDPContext *s = h->priv_data;
  366. int old_cancelstate;
  367. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
  368. ff_socket_nonblock(s->udp_fd, 0);
  369. pthread_mutex_lock(&s->mutex);
  370. while(1) {
  371. int len;
  372. pthread_mutex_unlock(&s->mutex);
  373. /* Blocking operations are always cancellation points;
  374. see "General Information" / "Thread Cancelation Overview"
  375. in Single Unix. */
  376. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
  377. len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
  378. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
  379. pthread_mutex_lock(&s->mutex);
  380. if (len < 0) {
  381. if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
  382. s->circular_buffer_error = ff_neterrno();
  383. goto end;
  384. }
  385. continue;
  386. }
  387. AV_WL32(s->tmp, len);
  388. if(av_fifo_space(s->fifo) < len + 4) {
  389. /* No Space left */
  390. if (s->overrun_nonfatal) {
  391. av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
  392. "Surviving due to overrun_nonfatal option\n");
  393. continue;
  394. } else {
  395. av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
  396. "To avoid, increase fifo_size URL option. "
  397. "To survive in such case, use overrun_nonfatal option\n");
  398. s->circular_buffer_error = AVERROR(EIO);
  399. goto end;
  400. }
  401. }
  402. av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
  403. pthread_cond_signal(&s->cond);
  404. }
  405. end:
  406. pthread_cond_signal(&s->cond);
  407. pthread_mutex_unlock(&s->mutex);
  408. return NULL;
  409. }
  410. #endif
  411. /* put it in UDP context */
  412. /* return non zero if error */
  413. static int udp_open(URLContext *h, const char *uri, int flags)
  414. {
  415. char hostname[1024], localaddr[1024] = "";
  416. int port, udp_fd = -1, tmp, bind_ret = -1;
  417. UDPContext *s = h->priv_data;
  418. int is_output;
  419. const char *p;
  420. char buf[256];
  421. struct sockaddr_storage my_addr;
  422. int len;
  423. int reuse_specified = 0;
  424. int i, include = 0, num_sources = 0;
  425. char *sources[32];
  426. h->is_streamed = 1;
  427. h->max_packet_size = 1472;
  428. is_output = !(flags & AVIO_FLAG_READ);
  429. s->ttl = 16;
  430. s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
  431. s->circular_buffer_size = 7*188*4096;
  432. p = strchr(uri, '?');
  433. if (p) {
  434. if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
  435. char *endptr = NULL;
  436. s->reuse_socket = strtol(buf, &endptr, 10);
  437. /* assume if no digits were found it is a request to enable it */
  438. if (buf == endptr)
  439. s->reuse_socket = 1;
  440. reuse_specified = 1;
  441. }
  442. if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
  443. char *endptr = NULL;
  444. s->overrun_nonfatal = strtol(buf, &endptr, 10);
  445. /* assume if no digits were found it is a request to enable it */
  446. if (buf == endptr)
  447. s->overrun_nonfatal = 1;
  448. if (!HAVE_PTHREAD_CANCEL)
  449. av_log(h, AV_LOG_WARNING,
  450. "'overrun_nonfatal' option was set but it is not supported "
  451. "on this build (pthread support is required)\n");
  452. }
  453. if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
  454. s->ttl = strtol(buf, NULL, 10);
  455. }
  456. if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
  457. s->local_port = strtol(buf, NULL, 10);
  458. }
  459. if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
  460. h->max_packet_size = strtol(buf, NULL, 10);
  461. }
  462. if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
  463. s->buffer_size = strtol(buf, NULL, 10);
  464. }
  465. if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
  466. s->is_connected = strtol(buf, NULL, 10);
  467. }
  468. if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
  469. s->circular_buffer_size = strtol(buf, NULL, 10)*188;
  470. if (!HAVE_PTHREAD_CANCEL)
  471. av_log(h, AV_LOG_WARNING,
  472. "'circular_buffer_size' option was set but it is not supported "
  473. "on this build (pthread support is required)\n");
  474. }
  475. if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
  476. av_strlcpy(localaddr, buf, sizeof(localaddr));
  477. }
  478. if (av_find_info_tag(buf, sizeof(buf), "sources", p))
  479. include = 1;
  480. if (include || av_find_info_tag(buf, sizeof(buf), "block", p)) {
  481. char *source_start;
  482. source_start = buf;
  483. while (1) {
  484. char *next = strchr(source_start, ',');
  485. if (next)
  486. *next = '\0';
  487. sources[num_sources] = av_strdup(source_start);
  488. if (!sources[num_sources])
  489. goto fail;
  490. source_start = next + 1;
  491. num_sources++;
  492. if (num_sources >= FF_ARRAY_ELEMS(sources) || !next)
  493. break;
  494. }
  495. }
  496. }
  497. /* fill the dest addr */
  498. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  499. /* XXX: fix av_url_split */
  500. if (hostname[0] == '\0' || hostname[0] == '?') {
  501. /* only accepts null hostname if input */
  502. if (!(flags & AVIO_FLAG_READ))
  503. goto fail;
  504. } else {
  505. if (ff_udp_set_remote_url(h, uri) < 0)
  506. goto fail;
  507. }
  508. if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
  509. s->local_port = port;
  510. udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
  511. if (udp_fd < 0)
  512. goto fail;
  513. /* Follow the requested reuse option, unless it's multicast in which
  514. * case enable reuse unless explicitly disabled.
  515. */
  516. if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
  517. s->reuse_socket = 1;
  518. if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
  519. goto fail;
  520. }
  521. /* If multicast, try binding the multicast address first, to avoid
  522. * receiving UDP packets from other sources aimed at the same UDP
  523. * port. This fails on windows. This makes sending to the same address
  524. * using sendto() fail, so only do it if we're opened in read-only mode. */
  525. if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
  526. bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
  527. }
  528. /* bind to the local address if not multicast or if the multicast
  529. * bind failed */
  530. /* the bind is needed to give a port to the socket now */
  531. if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
  532. log_net_error(h, AV_LOG_ERROR, "bind failed");
  533. goto fail;
  534. }
  535. len = sizeof(my_addr);
  536. getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
  537. s->local_port = udp_port(&my_addr, len);
  538. if (s->is_multicast) {
  539. if (h->flags & AVIO_FLAG_WRITE) {
  540. /* output */
  541. if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
  542. goto fail;
  543. }
  544. if (h->flags & AVIO_FLAG_READ) {
  545. /* input */
  546. if (num_sources == 0 || !include) {
  547. if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
  548. goto fail;
  549. if (num_sources) {
  550. if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 0) < 0)
  551. goto fail;
  552. }
  553. } else if (include && num_sources) {
  554. if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 1) < 0)
  555. goto fail;
  556. } else {
  557. av_log(NULL, AV_LOG_ERROR, "invalid udp settings: inclusive multicast but no sources given\n");
  558. goto fail;
  559. }
  560. }
  561. }
  562. if (is_output) {
  563. /* limit the tx buf size to limit latency */
  564. tmp = s->buffer_size;
  565. if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
  566. log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
  567. goto fail;
  568. }
  569. } else {
  570. /* set udp recv buffer size to the largest possible udp packet size to
  571. * avoid losing data on OSes that set this too low by default. */
  572. tmp = s->buffer_size;
  573. if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
  574. log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
  575. }
  576. /* make the socket non-blocking */
  577. ff_socket_nonblock(udp_fd, 1);
  578. }
  579. if (s->is_connected) {
  580. if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
  581. log_net_error(h, AV_LOG_ERROR, "connect");
  582. goto fail;
  583. }
  584. }
  585. for (i = 0; i < num_sources; i++)
  586. av_freep(&sources[i]);
  587. s->udp_fd = udp_fd;
  588. #if HAVE_PTHREAD_CANCEL
  589. if (!is_output && s->circular_buffer_size) {
  590. int ret;
  591. /* start the task going */
  592. s->fifo = av_fifo_alloc(s->circular_buffer_size);
  593. ret = pthread_mutex_init(&s->mutex, NULL);
  594. if (ret != 0) {
  595. av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
  596. goto fail;
  597. }
  598. ret = pthread_cond_init(&s->cond, NULL);
  599. if (ret != 0) {
  600. av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
  601. goto cond_fail;
  602. }
  603. ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
  604. if (ret != 0) {
  605. av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
  606. goto thread_fail;
  607. }
  608. s->thread_started = 1;
  609. }
  610. #endif
  611. return 0;
  612. #if HAVE_PTHREAD_CANCEL
  613. thread_fail:
  614. pthread_cond_destroy(&s->cond);
  615. cond_fail:
  616. pthread_mutex_destroy(&s->mutex);
  617. #endif
  618. fail:
  619. if (udp_fd >= 0)
  620. closesocket(udp_fd);
  621. av_fifo_free(s->fifo);
  622. for (i = 0; i < num_sources; i++)
  623. av_freep(&sources[i]);
  624. return AVERROR(EIO);
  625. }
  626. static int udp_read(URLContext *h, uint8_t *buf, int size)
  627. {
  628. UDPContext *s = h->priv_data;
  629. int ret;
  630. int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
  631. #if HAVE_PTHREAD_CANCEL
  632. if (s->fifo) {
  633. pthread_mutex_lock(&s->mutex);
  634. do {
  635. avail = av_fifo_size(s->fifo);
  636. if (avail) { // >=size) {
  637. uint8_t tmp[4];
  638. av_fifo_generic_read(s->fifo, tmp, 4, NULL);
  639. avail= AV_RL32(tmp);
  640. if(avail > size){
  641. av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
  642. avail= size;
  643. }
  644. av_fifo_generic_read(s->fifo, buf, avail, NULL);
  645. av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
  646. pthread_mutex_unlock(&s->mutex);
  647. return avail;
  648. } else if(s->circular_buffer_error){
  649. int err = s->circular_buffer_error;
  650. pthread_mutex_unlock(&s->mutex);
  651. return err;
  652. } else if(nonblock) {
  653. pthread_mutex_unlock(&s->mutex);
  654. return AVERROR(EAGAIN);
  655. }
  656. else {
  657. /* FIXME: using the monotonic clock would be better,
  658. but it does not exist on all supported platforms. */
  659. int64_t t = av_gettime() + 100000;
  660. struct timespec tv = { .tv_sec = t / 1000000,
  661. .tv_nsec = (t % 1000000) * 1000 };
  662. if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0)
  663. return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
  664. nonblock = 1;
  665. }
  666. } while( 1);
  667. }
  668. #endif
  669. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  670. ret = ff_network_wait_fd(s->udp_fd, 0);
  671. if (ret < 0)
  672. return ret;
  673. }
  674. ret = recv(s->udp_fd, buf, size, 0);
  675. return ret < 0 ? ff_neterrno() : ret;
  676. }
  677. static int udp_write(URLContext *h, const uint8_t *buf, int size)
  678. {
  679. UDPContext *s = h->priv_data;
  680. int ret;
  681. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  682. ret = ff_network_wait_fd(s->udp_fd, 1);
  683. if (ret < 0)
  684. return ret;
  685. }
  686. if (!s->is_connected) {
  687. ret = sendto (s->udp_fd, buf, size, 0,
  688. (struct sockaddr *) &s->dest_addr,
  689. s->dest_addr_len);
  690. } else
  691. ret = send(s->udp_fd, buf, size, 0);
  692. return ret < 0 ? ff_neterrno() : ret;
  693. }
  694. static int udp_close(URLContext *h)
  695. {
  696. UDPContext *s = h->priv_data;
  697. int ret;
  698. if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
  699. udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
  700. closesocket(s->udp_fd);
  701. #if HAVE_PTHREAD_CANCEL
  702. if (s->thread_started) {
  703. pthread_cancel(s->circular_buffer_thread);
  704. ret = pthread_join(s->circular_buffer_thread, NULL);
  705. if (ret != 0)
  706. av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
  707. pthread_mutex_destroy(&s->mutex);
  708. pthread_cond_destroy(&s->cond);
  709. }
  710. #endif
  711. av_fifo_free(s->fifo);
  712. return 0;
  713. }
  714. URLProtocol ff_udp_protocol = {
  715. .name = "udp",
  716. .url_open = udp_open,
  717. .url_read = udp_read,
  718. .url_write = udp_write,
  719. .url_close = udp_close,
  720. .url_get_file_handle = udp_get_file_handle,
  721. .priv_data_size = sizeof(UDPContext),
  722. .flags = URL_PROTOCOL_FLAG_NETWORK,
  723. };