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.

847 lines
29KB

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