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.

809 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. if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
  497. h->rw_timeout = strtol(buf, NULL, 10);
  498. }
  499. /* fill the dest addr */
  500. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  501. /* XXX: fix av_url_split */
  502. if (hostname[0] == '\0' || hostname[0] == '?') {
  503. /* only accepts null hostname if input */
  504. if (!(flags & AVIO_FLAG_READ))
  505. goto fail;
  506. } else {
  507. if (ff_udp_set_remote_url(h, uri) < 0)
  508. goto fail;
  509. }
  510. if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
  511. s->local_port = port;
  512. udp_fd = udp_socket_create(s, &my_addr, &len, localaddr);
  513. if (udp_fd < 0)
  514. goto fail;
  515. /* Follow the requested reuse option, unless it's multicast in which
  516. * case enable reuse unless explicitly disabled.
  517. */
  518. if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
  519. s->reuse_socket = 1;
  520. if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
  521. goto fail;
  522. }
  523. /* If multicast, try binding the multicast address first, to avoid
  524. * receiving UDP packets from other sources aimed at the same UDP
  525. * port. This fails on windows. This makes sending to the same address
  526. * using sendto() fail, so only do it if we're opened in read-only mode. */
  527. if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
  528. bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
  529. }
  530. /* bind to the local address if not multicast or if the multicast
  531. * bind failed */
  532. /* the bind is needed to give a port to the socket now */
  533. if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
  534. log_net_error(h, AV_LOG_ERROR, "bind failed");
  535. goto fail;
  536. }
  537. len = sizeof(my_addr);
  538. getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
  539. s->local_port = udp_port(&my_addr, len);
  540. if (s->is_multicast) {
  541. if (h->flags & AVIO_FLAG_WRITE) {
  542. /* output */
  543. if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
  544. goto fail;
  545. }
  546. if (h->flags & AVIO_FLAG_READ) {
  547. /* input */
  548. if (num_sources == 0 || !include) {
  549. if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
  550. goto fail;
  551. if (num_sources) {
  552. if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 0) < 0)
  553. goto fail;
  554. }
  555. } else if (include && num_sources) {
  556. if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 1) < 0)
  557. goto fail;
  558. } else {
  559. av_log(NULL, AV_LOG_ERROR, "invalid udp settings: inclusive multicast but no sources given\n");
  560. goto fail;
  561. }
  562. }
  563. }
  564. if (is_output) {
  565. /* limit the tx buf size to limit latency */
  566. tmp = s->buffer_size;
  567. if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
  568. log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
  569. goto fail;
  570. }
  571. } else {
  572. /* set udp recv buffer size to the largest possible udp packet size to
  573. * avoid losing data on OSes that set this too low by default. */
  574. tmp = s->buffer_size;
  575. if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
  576. log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
  577. }
  578. /* make the socket non-blocking */
  579. ff_socket_nonblock(udp_fd, 1);
  580. }
  581. if (s->is_connected) {
  582. if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
  583. log_net_error(h, AV_LOG_ERROR, "connect");
  584. goto fail;
  585. }
  586. }
  587. for (i = 0; i < num_sources; i++)
  588. av_freep(&sources[i]);
  589. s->udp_fd = udp_fd;
  590. #if HAVE_PTHREAD_CANCEL
  591. if (!is_output && s->circular_buffer_size) {
  592. int ret;
  593. /* start the task going */
  594. s->fifo = av_fifo_alloc(s->circular_buffer_size);
  595. ret = pthread_mutex_init(&s->mutex, NULL);
  596. if (ret != 0) {
  597. av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
  598. goto fail;
  599. }
  600. ret = pthread_cond_init(&s->cond, NULL);
  601. if (ret != 0) {
  602. av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
  603. goto cond_fail;
  604. }
  605. ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
  606. if (ret != 0) {
  607. av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
  608. goto thread_fail;
  609. }
  610. s->thread_started = 1;
  611. }
  612. #endif
  613. return 0;
  614. #if HAVE_PTHREAD_CANCEL
  615. thread_fail:
  616. pthread_cond_destroy(&s->cond);
  617. cond_fail:
  618. pthread_mutex_destroy(&s->mutex);
  619. #endif
  620. fail:
  621. if (udp_fd >= 0)
  622. closesocket(udp_fd);
  623. av_fifo_free(s->fifo);
  624. for (i = 0; i < num_sources; i++)
  625. av_freep(&sources[i]);
  626. return AVERROR(EIO);
  627. }
  628. static int udp_read(URLContext *h, uint8_t *buf, int size)
  629. {
  630. UDPContext *s = h->priv_data;
  631. int ret;
  632. int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
  633. #if HAVE_PTHREAD_CANCEL
  634. if (s->fifo) {
  635. pthread_mutex_lock(&s->mutex);
  636. do {
  637. avail = av_fifo_size(s->fifo);
  638. if (avail) { // >=size) {
  639. uint8_t tmp[4];
  640. av_fifo_generic_read(s->fifo, tmp, 4, NULL);
  641. avail= AV_RL32(tmp);
  642. if(avail > size){
  643. av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
  644. avail= size;
  645. }
  646. av_fifo_generic_read(s->fifo, buf, avail, NULL);
  647. av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
  648. pthread_mutex_unlock(&s->mutex);
  649. return avail;
  650. } else if(s->circular_buffer_error){
  651. int err = s->circular_buffer_error;
  652. pthread_mutex_unlock(&s->mutex);
  653. return err;
  654. } else if(nonblock) {
  655. pthread_mutex_unlock(&s->mutex);
  656. return AVERROR(EAGAIN);
  657. }
  658. else {
  659. /* FIXME: using the monotonic clock would be better,
  660. but it does not exist on all supported platforms. */
  661. int64_t t = av_gettime() + 100000;
  662. struct timespec tv = { .tv_sec = t / 1000000,
  663. .tv_nsec = (t % 1000000) * 1000 };
  664. if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0)
  665. return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
  666. nonblock = 1;
  667. }
  668. } while( 1);
  669. }
  670. #endif
  671. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  672. ret = ff_network_wait_fd(s->udp_fd, 0);
  673. if (ret < 0)
  674. return ret;
  675. }
  676. ret = recv(s->udp_fd, buf, size, 0);
  677. return ret < 0 ? ff_neterrno() : ret;
  678. }
  679. static int udp_write(URLContext *h, const uint8_t *buf, int size)
  680. {
  681. UDPContext *s = h->priv_data;
  682. int ret;
  683. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  684. ret = ff_network_wait_fd(s->udp_fd, 1);
  685. if (ret < 0)
  686. return ret;
  687. }
  688. if (!s->is_connected) {
  689. ret = sendto (s->udp_fd, buf, size, 0,
  690. (struct sockaddr *) &s->dest_addr,
  691. s->dest_addr_len);
  692. } else
  693. ret = send(s->udp_fd, buf, size, 0);
  694. return ret < 0 ? ff_neterrno() : ret;
  695. }
  696. static int udp_close(URLContext *h)
  697. {
  698. UDPContext *s = h->priv_data;
  699. int ret;
  700. if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
  701. udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
  702. closesocket(s->udp_fd);
  703. #if HAVE_PTHREAD_CANCEL
  704. if (s->thread_started) {
  705. pthread_cancel(s->circular_buffer_thread);
  706. ret = pthread_join(s->circular_buffer_thread, NULL);
  707. if (ret != 0)
  708. av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
  709. pthread_mutex_destroy(&s->mutex);
  710. pthread_cond_destroy(&s->cond);
  711. }
  712. #endif
  713. av_fifo_free(s->fifo);
  714. return 0;
  715. }
  716. URLProtocol ff_udp_protocol = {
  717. .name = "udp",
  718. .url_open = udp_open,
  719. .url_read = udp_read,
  720. .url_write = udp_write,
  721. .url_close = udp_close,
  722. .url_get_file_handle = udp_get_file_handle,
  723. .priv_data_size = sizeof(UDPContext),
  724. .flags = URL_PROTOCOL_FLAG_NETWORK,
  725. };