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.

896 lines
31KB

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