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.

1009 lines
36KB

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