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.

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