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.

804 lines
26KB

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