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.

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