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.

969 lines
34KB

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