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.

868 lines
30KB

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