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.

852 lines
29KB

  1. /*
  2. * UDP prototype streaming system
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * UDP protocol
  24. */
  25. #define _BSD_SOURCE /* Needed for using struct ip_mreq with recent glibc */
  26. #include "avformat.h"
  27. #include "avio_internal.h"
  28. #include "libavutil/parseutils.h"
  29. #include "libavutil/fifo.h"
  30. #include "libavutil/intreadwrite.h"
  31. #include "libavutil/avstring.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/log.h"
  34. #include "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. AI_NUMERICHOST);
  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. AI_NUMERICHOST);
  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 = 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. /* put it in UDP context */
  446. /* return non zero if error */
  447. static int udp_open(URLContext *h, const char *uri, int flags)
  448. {
  449. char hostname[1024], localaddr[1024] = "";
  450. int port, udp_fd = -1, tmp, bind_ret = -1;
  451. UDPContext *s = h->priv_data;
  452. int is_output;
  453. const char *p;
  454. char buf[256];
  455. struct sockaddr_storage my_addr;
  456. socklen_t len;
  457. int reuse_specified = 0;
  458. int i, include = 0, num_sources = 0;
  459. char *sources[32];
  460. h->is_streamed = 1;
  461. is_output = !(flags & AVIO_FLAG_READ);
  462. if (!s->buffer_size) /* if not set explicitly */
  463. s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
  464. p = strchr(uri, '?');
  465. if (p) {
  466. if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
  467. char *endptr = NULL;
  468. s->reuse_socket = strtol(buf, &endptr, 10);
  469. /* assume if no digits were found it is a request to enable it */
  470. if (buf == endptr)
  471. s->reuse_socket = 1;
  472. reuse_specified = 1;
  473. }
  474. if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
  475. char *endptr = NULL;
  476. s->overrun_nonfatal = strtol(buf, &endptr, 10);
  477. /* assume if no digits were found it is a request to enable it */
  478. if (buf == endptr)
  479. s->overrun_nonfatal = 1;
  480. if (!HAVE_PTHREAD_CANCEL)
  481. av_log(h, AV_LOG_WARNING,
  482. "'overrun_nonfatal' option was set but it is not supported "
  483. "on this build (pthread support is required)\n");
  484. }
  485. if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
  486. s->ttl = strtol(buf, NULL, 10);
  487. }
  488. if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
  489. s->local_port = strtol(buf, NULL, 10);
  490. }
  491. if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
  492. s->packet_size = strtol(buf, NULL, 10);
  493. }
  494. if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
  495. s->buffer_size = strtol(buf, NULL, 10);
  496. }
  497. if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
  498. s->is_connected = strtol(buf, NULL, 10);
  499. }
  500. if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
  501. s->circular_buffer_size = strtol(buf, NULL, 10);
  502. if (!HAVE_PTHREAD_CANCEL)
  503. av_log(h, AV_LOG_WARNING,
  504. "'circular_buffer_size' option was set but it is not supported "
  505. "on this build (pthread support is required)\n");
  506. }
  507. if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
  508. av_strlcpy(localaddr, buf, sizeof(localaddr));
  509. }
  510. if (av_find_info_tag(buf, sizeof(buf), "sources", p))
  511. include = 1;
  512. if (include || av_find_info_tag(buf, sizeof(buf), "block", p)) {
  513. char *source_start;
  514. source_start = buf;
  515. while (1) {
  516. char *next = strchr(source_start, ',');
  517. if (next)
  518. *next = '\0';
  519. sources[num_sources] = av_strdup(source_start);
  520. if (!sources[num_sources])
  521. goto fail;
  522. source_start = next + 1;
  523. num_sources++;
  524. if (num_sources >= FF_ARRAY_ELEMS(sources) || !next)
  525. break;
  526. }
  527. }
  528. if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
  529. s->timeout = strtol(buf, NULL, 10);
  530. }
  531. /* handling needed to support options picking from both AVOption and URL */
  532. s->circular_buffer_size *= 188;
  533. if (flags & AVIO_FLAG_WRITE) {
  534. h->max_packet_size = s->packet_size;
  535. } else {
  536. h->max_packet_size = UDP_MAX_PKT_SIZE;
  537. }
  538. h->rw_timeout = s->timeout;
  539. /* fill the dest addr */
  540. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  541. /* XXX: fix av_url_split */
  542. if (hostname[0] == '\0' || hostname[0] == '?') {
  543. /* only accepts null hostname if input */
  544. if (!(flags & AVIO_FLAG_READ))
  545. goto fail;
  546. } else {
  547. if (ff_udp_set_remote_url(h, uri) < 0)
  548. goto fail;
  549. }
  550. if ((s->is_multicast || !s->local_port) && (h->flags & AVIO_FLAG_READ))
  551. s->local_port = port;
  552. udp_fd = udp_socket_create(s, &my_addr, &len, localaddr[0] ? localaddr : s->local_addr);
  553. if (udp_fd < 0)
  554. goto fail;
  555. /* Follow the requested reuse option, unless it's multicast in which
  556. * case enable reuse unless explicitly disabled.
  557. */
  558. if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
  559. s->reuse_socket = 1;
  560. if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
  561. goto fail;
  562. }
  563. /* If multicast, try binding the multicast address first, to avoid
  564. * receiving UDP packets from other sources aimed at the same UDP
  565. * port. This fails on windows. This makes sending to the same address
  566. * using sendto() fail, so only do it if we're opened in read-only mode. */
  567. if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
  568. bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
  569. }
  570. /* bind to the local address if not multicast or if the multicast
  571. * bind failed */
  572. /* the bind is needed to give a port to the socket now */
  573. if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
  574. log_net_error(h, AV_LOG_ERROR, "bind failed");
  575. goto fail;
  576. }
  577. len = sizeof(my_addr);
  578. getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
  579. s->local_port = udp_port(&my_addr, len);
  580. if (s->is_multicast) {
  581. if (h->flags & AVIO_FLAG_WRITE) {
  582. /* output */
  583. if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
  584. goto fail;
  585. }
  586. if (h->flags & AVIO_FLAG_READ) {
  587. /* input */
  588. if (num_sources == 0 || !include) {
  589. if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
  590. goto fail;
  591. if (num_sources) {
  592. if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 0) < 0)
  593. goto fail;
  594. }
  595. } else if (include && num_sources) {
  596. if (udp_set_multicast_sources(udp_fd, (struct sockaddr *)&s->dest_addr, s->dest_addr_len, sources, num_sources, 1) < 0)
  597. goto fail;
  598. } else {
  599. av_log(NULL, AV_LOG_ERROR, "invalid udp settings: inclusive multicast but no sources given\n");
  600. goto fail;
  601. }
  602. }
  603. }
  604. if (is_output) {
  605. /* limit the tx buf size to limit latency */
  606. tmp = s->buffer_size;
  607. if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
  608. log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
  609. goto fail;
  610. }
  611. } else {
  612. /* set udp recv buffer size to the largest possible udp packet size to
  613. * avoid losing data on OSes that set this too low by default. */
  614. tmp = s->buffer_size;
  615. if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
  616. log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
  617. }
  618. /* make the socket non-blocking */
  619. ff_socket_nonblock(udp_fd, 1);
  620. }
  621. if (s->is_connected) {
  622. if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
  623. log_net_error(h, AV_LOG_ERROR, "connect");
  624. goto fail;
  625. }
  626. }
  627. for (i = 0; i < num_sources; i++)
  628. av_freep(&sources[i]);
  629. s->udp_fd = udp_fd;
  630. #if HAVE_PTHREAD_CANCEL
  631. if (!is_output && s->circular_buffer_size) {
  632. int ret;
  633. /* start the task going */
  634. s->fifo = av_fifo_alloc(s->circular_buffer_size);
  635. ret = pthread_mutex_init(&s->mutex, NULL);
  636. if (ret != 0) {
  637. av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
  638. goto fail;
  639. }
  640. ret = pthread_cond_init(&s->cond, NULL);
  641. if (ret != 0) {
  642. av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
  643. goto cond_fail;
  644. }
  645. ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
  646. if (ret != 0) {
  647. av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
  648. goto thread_fail;
  649. }
  650. s->thread_started = 1;
  651. }
  652. #endif
  653. return 0;
  654. #if HAVE_PTHREAD_CANCEL
  655. thread_fail:
  656. pthread_cond_destroy(&s->cond);
  657. cond_fail:
  658. pthread_mutex_destroy(&s->mutex);
  659. #endif
  660. fail:
  661. if (udp_fd >= 0)
  662. closesocket(udp_fd);
  663. av_fifo_free(s->fifo);
  664. for (i = 0; i < num_sources; i++)
  665. av_freep(&sources[i]);
  666. return AVERROR(EIO);
  667. }
  668. static int udp_read(URLContext *h, uint8_t *buf, int size)
  669. {
  670. UDPContext *s = h->priv_data;
  671. int ret;
  672. int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
  673. #if HAVE_PTHREAD_CANCEL
  674. if (s->fifo) {
  675. pthread_mutex_lock(&s->mutex);
  676. do {
  677. avail = av_fifo_size(s->fifo);
  678. if (avail) { // >=size) {
  679. uint8_t tmp[4];
  680. av_fifo_generic_read(s->fifo, tmp, 4, NULL);
  681. avail= AV_RL32(tmp);
  682. if(avail > size){
  683. av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
  684. avail= size;
  685. }
  686. av_fifo_generic_read(s->fifo, buf, avail, NULL);
  687. av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
  688. pthread_mutex_unlock(&s->mutex);
  689. return avail;
  690. } else if(s->circular_buffer_error){
  691. int err = s->circular_buffer_error;
  692. pthread_mutex_unlock(&s->mutex);
  693. return err;
  694. } else if(nonblock) {
  695. pthread_mutex_unlock(&s->mutex);
  696. return AVERROR(EAGAIN);
  697. }
  698. else {
  699. /* FIXME: using the monotonic clock would be better,
  700. but it does not exist on all supported platforms. */
  701. int64_t t = av_gettime() + 100000;
  702. struct timespec tv = { .tv_sec = t / 1000000,
  703. .tv_nsec = (t % 1000000) * 1000 };
  704. if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0) {
  705. pthread_mutex_unlock(&s->mutex);
  706. return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
  707. }
  708. nonblock = 1;
  709. }
  710. } while( 1);
  711. }
  712. #endif
  713. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  714. ret = ff_network_wait_fd(s->udp_fd, 0);
  715. if (ret < 0)
  716. return ret;
  717. }
  718. ret = recv(s->udp_fd, buf, size, 0);
  719. return ret < 0 ? ff_neterrno() : ret;
  720. }
  721. static int udp_write(URLContext *h, const uint8_t *buf, int size)
  722. {
  723. UDPContext *s = h->priv_data;
  724. int ret;
  725. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  726. ret = ff_network_wait_fd(s->udp_fd, 1);
  727. if (ret < 0)
  728. return ret;
  729. }
  730. if (!s->is_connected) {
  731. ret = sendto (s->udp_fd, buf, size, 0,
  732. (struct sockaddr *) &s->dest_addr,
  733. s->dest_addr_len);
  734. } else
  735. ret = send(s->udp_fd, buf, size, 0);
  736. return ret < 0 ? ff_neterrno() : ret;
  737. }
  738. static int udp_close(URLContext *h)
  739. {
  740. UDPContext *s = h->priv_data;
  741. int ret;
  742. if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
  743. udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
  744. closesocket(s->udp_fd);
  745. #if HAVE_PTHREAD_CANCEL
  746. if (s->thread_started) {
  747. pthread_cancel(s->circular_buffer_thread);
  748. ret = pthread_join(s->circular_buffer_thread, NULL);
  749. if (ret != 0)
  750. av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
  751. pthread_mutex_destroy(&s->mutex);
  752. pthread_cond_destroy(&s->cond);
  753. }
  754. #endif
  755. av_fifo_free(s->fifo);
  756. return 0;
  757. }
  758. URLProtocol ff_udp_protocol = {
  759. .name = "udp",
  760. .url_open = udp_open,
  761. .url_read = udp_read,
  762. .url_write = udp_write,
  763. .url_close = udp_close,
  764. .url_get_file_handle = udp_get_file_handle,
  765. .priv_data_size = sizeof(UDPContext),
  766. .priv_data_class = &udp_context_class,
  767. .flags = URL_PROTOCOL_FLAG_NETWORK,
  768. };