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.

1007 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_INT, { .i64 = -1 }, -1, 1, D|E },
  109. { "reuse_socket", "explicitly allow reusing UDP sockets", OFFSET(reuse_socket), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, .flags = D|E },
  110. { "broadcast", "explicitly allow or disallow broadcast destination", OFFSET(is_broadcast), AV_OPT_TYPE_INT, { .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_INT, { .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_INT, {.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, "udp_resolve_host: %s\n",
  238. gai_strerror(error));
  239. }
  240. return res;
  241. }
  242. static int udp_set_multicast_sources(URLContext *h,
  243. int sockfd, struct sockaddr *addr,
  244. int addr_len, char **sources,
  245. int nb_sources, int include)
  246. {
  247. #if HAVE_STRUCT_GROUP_SOURCE_REQ && defined(MCAST_BLOCK_SOURCE) && !defined(_WIN32)
  248. /* These ones are available in the microsoft SDK, but don't seem to work
  249. * as on linux, so just prefer the v4-only approach there for now. */
  250. int i;
  251. for (i = 0; i < nb_sources; i++) {
  252. struct group_source_req mreqs;
  253. int level = addr->sa_family == AF_INET ? IPPROTO_IP : IPPROTO_IPV6;
  254. struct addrinfo *sourceaddr = udp_resolve_host(h, sources[i], 0,
  255. SOCK_DGRAM, AF_UNSPEC,
  256. 0);
  257. if (!sourceaddr)
  258. return AVERROR(ENOENT);
  259. mreqs.gsr_interface = 0;
  260. memcpy(&mreqs.gsr_group, addr, addr_len);
  261. memcpy(&mreqs.gsr_source, sourceaddr->ai_addr, sourceaddr->ai_addrlen);
  262. freeaddrinfo(sourceaddr);
  263. if (setsockopt(sockfd, level,
  264. include ? MCAST_JOIN_SOURCE_GROUP : MCAST_BLOCK_SOURCE,
  265. (const void *)&mreqs, sizeof(mreqs)) < 0) {
  266. if (include)
  267. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_JOIN_SOURCE_GROUP)");
  268. else
  269. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(MCAST_BLOCK_SOURCE)");
  270. return ff_neterrno();
  271. }
  272. }
  273. #elif HAVE_STRUCT_IP_MREQ_SOURCE && defined(IP_BLOCK_SOURCE)
  274. int i;
  275. if (addr->sa_family != AF_INET) {
  276. av_log(NULL, AV_LOG_ERROR,
  277. "Setting multicast sources only supported for IPv4\n");
  278. return AVERROR(EINVAL);
  279. }
  280. for (i = 0; i < nb_sources; i++) {
  281. struct ip_mreq_source mreqs;
  282. struct addrinfo *sourceaddr = udp_resolve_host(h, sources[i], 0,
  283. SOCK_DGRAM, AF_UNSPEC,
  284. 0);
  285. if (!sourceaddr)
  286. return AVERROR(ENOENT);
  287. if (sourceaddr->ai_addr->sa_family != AF_INET) {
  288. freeaddrinfo(sourceaddr);
  289. av_log(NULL, AV_LOG_ERROR, "%s is of incorrect protocol family\n",
  290. sources[i]);
  291. return AVERROR(EINVAL);
  292. }
  293. mreqs.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
  294. mreqs.imr_interface.s_addr = INADDR_ANY;
  295. mreqs.imr_sourceaddr.s_addr = ((struct sockaddr_in *)sourceaddr->ai_addr)->sin_addr.s_addr;
  296. freeaddrinfo(sourceaddr);
  297. if (setsockopt(sockfd, IPPROTO_IP,
  298. include ? IP_ADD_SOURCE_MEMBERSHIP : IP_BLOCK_SOURCE,
  299. (const void *)&mreqs, sizeof(mreqs)) < 0) {
  300. if (include)
  301. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_SOURCE_MEMBERSHIP)");
  302. else
  303. log_net_error(NULL, AV_LOG_ERROR, "setsockopt(IP_BLOCK_SOURCE)");
  304. return ff_neterrno();
  305. }
  306. }
  307. #else
  308. return AVERROR(ENOSYS);
  309. #endif
  310. return 0;
  311. }
  312. static int udp_set_url(URLContext *h,
  313. struct sockaddr_storage *addr,
  314. const char *hostname, int port)
  315. {
  316. struct addrinfo *res0;
  317. int addr_len;
  318. res0 = udp_resolve_host(h, hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
  319. if (!res0) return AVERROR(EIO);
  320. memcpy(addr, res0->ai_addr, res0->ai_addrlen);
  321. addr_len = res0->ai_addrlen;
  322. freeaddrinfo(res0);
  323. return addr_len;
  324. }
  325. static int udp_socket_create(URLContext *h, struct sockaddr_storage *addr,
  326. socklen_t *addr_len, const char *localaddr)
  327. {
  328. UDPContext *s = h->priv_data;
  329. int udp_fd = -1;
  330. struct addrinfo *res0, *res;
  331. int family = AF_UNSPEC;
  332. if (((struct sockaddr *) &s->dest_addr)->sa_family)
  333. family = ((struct sockaddr *) &s->dest_addr)->sa_family;
  334. res0 = udp_resolve_host(h, (localaddr && localaddr[0]) ? localaddr : NULL,
  335. s->local_port,
  336. SOCK_DGRAM, family, AI_PASSIVE);
  337. if (!res0)
  338. goto fail;
  339. for (res = res0; res; res=res->ai_next) {
  340. if (s->udplite_coverage)
  341. udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, IPPROTO_UDPLITE);
  342. else
  343. udp_fd = ff_socket(res->ai_family, SOCK_DGRAM, 0);
  344. if (udp_fd != -1) break;
  345. log_net_error(NULL, AV_LOG_ERROR, "socket");
  346. }
  347. if (udp_fd < 0)
  348. goto fail;
  349. memcpy(addr, res->ai_addr, res->ai_addrlen);
  350. *addr_len = res->ai_addrlen;
  351. freeaddrinfo(res0);
  352. return udp_fd;
  353. fail:
  354. if (udp_fd >= 0)
  355. closesocket(udp_fd);
  356. if(res0)
  357. freeaddrinfo(res0);
  358. return -1;
  359. }
  360. static int udp_port(struct sockaddr_storage *addr, int addr_len)
  361. {
  362. char sbuf[sizeof(int)*3+1];
  363. int error;
  364. if ((error = getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0, sbuf, sizeof(sbuf), NI_NUMERICSERV)) != 0) {
  365. av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", gai_strerror(error));
  366. return -1;
  367. }
  368. return strtol(sbuf, NULL, 10);
  369. }
  370. /**
  371. * If no filename is given to av_open_input_file because you want to
  372. * get the local port first, then you must call this function to set
  373. * the remote server address.
  374. *
  375. * url syntax: udp://host:port[?option=val...]
  376. * option: 'ttl=n' : set the ttl value (for multicast only)
  377. * 'localport=n' : set the local port
  378. * 'pkt_size=n' : set max packet size
  379. * 'reuse=1' : enable reusing the socket
  380. * 'overrun_nonfatal=1': survive in case of circular buffer overrun
  381. *
  382. * @param h media file context
  383. * @param uri of the remote server
  384. * @return zero if no error.
  385. */
  386. int ff_udp_set_remote_url(URLContext *h, const char *uri)
  387. {
  388. UDPContext *s = h->priv_data;
  389. char hostname[256], buf[10];
  390. int port;
  391. const char *p;
  392. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  393. /* set the destination address */
  394. s->dest_addr_len = udp_set_url(h, &s->dest_addr, hostname, port);
  395. if (s->dest_addr_len < 0) {
  396. return AVERROR(EIO);
  397. }
  398. s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
  399. p = strchr(uri, '?');
  400. if (p) {
  401. if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
  402. int was_connected = s->is_connected;
  403. s->is_connected = strtol(buf, NULL, 10);
  404. if (s->is_connected && !was_connected) {
  405. if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
  406. s->dest_addr_len)) {
  407. s->is_connected = 0;
  408. log_net_error(h, AV_LOG_ERROR, "connect");
  409. return AVERROR(EIO);
  410. }
  411. }
  412. }
  413. }
  414. return 0;
  415. }
  416. /**
  417. * Return the local port used by the UDP connection
  418. * @param h media file context
  419. * @return the local port number
  420. */
  421. int ff_udp_get_local_port(URLContext *h)
  422. {
  423. UDPContext *s = h->priv_data;
  424. return s->local_port;
  425. }
  426. /**
  427. * Return the udp file handle for select() usage to wait for several RTP
  428. * streams at the same time.
  429. * @param h media file context
  430. */
  431. static int udp_get_file_handle(URLContext *h)
  432. {
  433. UDPContext *s = h->priv_data;
  434. return s->udp_fd;
  435. }
  436. #if HAVE_PTHREAD_CANCEL
  437. static void *circular_buffer_task( void *_URLContext)
  438. {
  439. URLContext *h = _URLContext;
  440. UDPContext *s = h->priv_data;
  441. int old_cancelstate;
  442. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
  443. pthread_mutex_lock(&s->mutex);
  444. if (ff_socket_nonblock(s->udp_fd, 0) < 0) {
  445. av_log(h, AV_LOG_ERROR, "Failed to set blocking mode");
  446. s->circular_buffer_error = AVERROR(EIO);
  447. goto end;
  448. }
  449. while(1) {
  450. int len;
  451. pthread_mutex_unlock(&s->mutex);
  452. /* Blocking operations are always cancellation points;
  453. see "General Information" / "Thread Cancelation Overview"
  454. in Single Unix. */
  455. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_cancelstate);
  456. len = recv(s->udp_fd, s->tmp+4, sizeof(s->tmp)-4, 0);
  457. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancelstate);
  458. pthread_mutex_lock(&s->mutex);
  459. if (len < 0) {
  460. if (ff_neterrno() != AVERROR(EAGAIN) && ff_neterrno() != AVERROR(EINTR)) {
  461. s->circular_buffer_error = ff_neterrno();
  462. goto end;
  463. }
  464. continue;
  465. }
  466. AV_WL32(s->tmp, len);
  467. if(av_fifo_space(s->fifo) < len + 4) {
  468. /* No Space left */
  469. if (s->overrun_nonfatal) {
  470. av_log(h, AV_LOG_WARNING, "Circular buffer overrun. "
  471. "Surviving due to overrun_nonfatal option\n");
  472. continue;
  473. } else {
  474. av_log(h, AV_LOG_ERROR, "Circular buffer overrun. "
  475. "To avoid, increase fifo_size URL option. "
  476. "To survive in such case, use overrun_nonfatal option\n");
  477. s->circular_buffer_error = AVERROR(EIO);
  478. goto end;
  479. }
  480. }
  481. av_fifo_generic_write(s->fifo, s->tmp, len+4, NULL);
  482. pthread_cond_signal(&s->cond);
  483. }
  484. end:
  485. pthread_cond_signal(&s->cond);
  486. pthread_mutex_unlock(&s->mutex);
  487. return NULL;
  488. }
  489. #endif
  490. static int parse_source_list(char *buf, char **sources, int *num_sources,
  491. int max_sources)
  492. {
  493. char *source_start;
  494. source_start = buf;
  495. while (1) {
  496. char *next = strchr(source_start, ',');
  497. if (next)
  498. *next = '\0';
  499. sources[*num_sources] = av_strdup(source_start);
  500. if (!sources[*num_sources])
  501. return AVERROR(ENOMEM);
  502. source_start = next + 1;
  503. (*num_sources)++;
  504. if (*num_sources >= max_sources || !next)
  505. break;
  506. }
  507. return 0;
  508. }
  509. /* put it in UDP context */
  510. /* return non zero if error */
  511. static int udp_open(URLContext *h, const char *uri, int flags)
  512. {
  513. char hostname[1024], localaddr[1024] = "";
  514. int port, udp_fd = -1, tmp, bind_ret = -1, dscp = -1;
  515. UDPContext *s = h->priv_data;
  516. int is_output;
  517. const char *p;
  518. char buf[256];
  519. struct sockaddr_storage my_addr;
  520. socklen_t len;
  521. int i, num_include_sources = 0, num_exclude_sources = 0;
  522. char *include_sources[32], *exclude_sources[32];
  523. h->is_streamed = 1;
  524. is_output = !(flags & AVIO_FLAG_READ);
  525. if (s->buffer_size < 0)
  526. s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
  527. if (s->sources) {
  528. if (parse_source_list(s->sources, include_sources,
  529. &num_include_sources,
  530. FF_ARRAY_ELEMS(include_sources)))
  531. goto fail;
  532. }
  533. if (s->block) {
  534. if (parse_source_list(s->block, exclude_sources, &num_exclude_sources,
  535. FF_ARRAY_ELEMS(exclude_sources)))
  536. goto fail;
  537. }
  538. if (s->pkt_size > 0)
  539. h->max_packet_size = s->pkt_size;
  540. p = strchr(uri, '?');
  541. if (p) {
  542. if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
  543. char *endptr = NULL;
  544. s->reuse_socket = strtol(buf, &endptr, 10);
  545. /* assume if no digits were found it is a request to enable it */
  546. if (buf == endptr)
  547. s->reuse_socket = 1;
  548. }
  549. if (av_find_info_tag(buf, sizeof(buf), "overrun_nonfatal", p)) {
  550. char *endptr = NULL;
  551. s->overrun_nonfatal = strtol(buf, &endptr, 10);
  552. /* assume if no digits were found it is a request to enable it */
  553. if (buf == endptr)
  554. s->overrun_nonfatal = 1;
  555. if (!HAVE_PTHREAD_CANCEL)
  556. av_log(h, AV_LOG_WARNING,
  557. "'overrun_nonfatal' option was set but it is not supported "
  558. "on this build (pthread support is required)\n");
  559. }
  560. if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
  561. s->ttl = strtol(buf, NULL, 10);
  562. }
  563. if (av_find_info_tag(buf, sizeof(buf), "udplite_coverage", p)) {
  564. s->udplite_coverage = strtol(buf, NULL, 10);
  565. }
  566. if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
  567. s->local_port = strtol(buf, NULL, 10);
  568. }
  569. if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
  570. s->pkt_size = strtol(buf, NULL, 10);
  571. }
  572. if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
  573. s->buffer_size = strtol(buf, NULL, 10);
  574. }
  575. if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
  576. s->is_connected = strtol(buf, NULL, 10);
  577. }
  578. if (av_find_info_tag(buf, sizeof(buf), "dscp", p)) {
  579. dscp = strtol(buf, NULL, 10);
  580. }
  581. if (av_find_info_tag(buf, sizeof(buf), "fifo_size", p)) {
  582. s->circular_buffer_size = strtol(buf, NULL, 10);
  583. if (!HAVE_PTHREAD_CANCEL)
  584. av_log(h, AV_LOG_WARNING,
  585. "'circular_buffer_size' option was set but it is not supported "
  586. "on this build (pthread support is required)\n");
  587. }
  588. if (av_find_info_tag(buf, sizeof(buf), "localaddr", p)) {
  589. av_strlcpy(localaddr, buf, sizeof(localaddr));
  590. }
  591. if (av_find_info_tag(buf, sizeof(buf), "sources", p)) {
  592. if (parse_source_list(buf, include_sources, &num_include_sources,
  593. FF_ARRAY_ELEMS(include_sources)))
  594. goto fail;
  595. }
  596. if (av_find_info_tag(buf, sizeof(buf), "block", p)) {
  597. if (parse_source_list(buf, exclude_sources, &num_exclude_sources,
  598. FF_ARRAY_ELEMS(exclude_sources)))
  599. goto fail;
  600. }
  601. if (!is_output && av_find_info_tag(buf, sizeof(buf), "timeout", p))
  602. s->timeout = strtol(buf, NULL, 10);
  603. if (is_output && av_find_info_tag(buf, sizeof(buf), "broadcast", p))
  604. s->is_broadcast = strtol(buf, NULL, 10);
  605. }
  606. /* handling needed to support options picking from both AVOption and URL */
  607. s->circular_buffer_size *= 188;
  608. if (flags & AVIO_FLAG_WRITE) {
  609. h->max_packet_size = s->pkt_size;
  610. } else {
  611. h->max_packet_size = UDP_MAX_PKT_SIZE;
  612. }
  613. h->rw_timeout = s->timeout;
  614. /* fill the dest addr */
  615. av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
  616. /* XXX: fix av_url_split */
  617. if (hostname[0] == '\0' || hostname[0] == '?') {
  618. /* only accepts null hostname if input */
  619. if (!(flags & AVIO_FLAG_READ))
  620. goto fail;
  621. } else {
  622. if (ff_udp_set_remote_url(h, uri) < 0)
  623. goto fail;
  624. }
  625. if ((s->is_multicast || s->local_port <= 0) && (h->flags & AVIO_FLAG_READ))
  626. s->local_port = port;
  627. if (localaddr[0])
  628. udp_fd = udp_socket_create(h, &my_addr, &len, localaddr);
  629. else
  630. udp_fd = udp_socket_create(h, &my_addr, &len, s->localaddr);
  631. if (udp_fd < 0)
  632. goto fail;
  633. s->local_addr_storage=my_addr; //store for future multicast join
  634. /* Follow the requested reuse option, unless it's multicast in which
  635. * case enable reuse unless explicitly disabled.
  636. */
  637. if (s->reuse_socket > 0 || (s->is_multicast && s->reuse_socket < 0)) {
  638. s->reuse_socket = 1;
  639. if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
  640. goto fail;
  641. }
  642. if (s->is_broadcast) {
  643. #ifdef SO_BROADCAST
  644. if (setsockopt (udp_fd, SOL_SOCKET, SO_BROADCAST, &(s->is_broadcast), sizeof(s->is_broadcast)) != 0)
  645. #endif
  646. goto fail;
  647. }
  648. /* Set the checksum coverage for UDP-Lite (RFC 3828) for sending and receiving.
  649. * The receiver coverage has to be less than or equal to the sender coverage.
  650. * Otherwise, the receiver will drop all packets.
  651. */
  652. if (s->udplite_coverage) {
  653. if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
  654. av_log(h, AV_LOG_WARNING, "socket option UDPLITE_SEND_CSCOV not available");
  655. if (setsockopt (udp_fd, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, &(s->udplite_coverage), sizeof(s->udplite_coverage)) != 0)
  656. av_log(h, AV_LOG_WARNING, "socket option UDPLITE_RECV_CSCOV not available");
  657. }
  658. if (dscp >= 0) {
  659. dscp <<= 2;
  660. if (setsockopt (udp_fd, IPPROTO_IP, IP_TOS, &dscp, sizeof(dscp)) != 0)
  661. goto fail;
  662. }
  663. /* If multicast, try binding the multicast address first, to avoid
  664. * receiving UDP packets from other sources aimed at the same UDP
  665. * port. This fails on windows. This makes sending to the same address
  666. * using sendto() fail, so only do it if we're opened in read-only mode. */
  667. if (s->is_multicast && !(h->flags & AVIO_FLAG_WRITE)) {
  668. bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
  669. }
  670. /* bind to the local address if not multicast or if the multicast
  671. * bind failed */
  672. /* the bind is needed to give a port to the socket now */
  673. if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0) {
  674. log_net_error(h, AV_LOG_ERROR, "bind failed");
  675. goto fail;
  676. }
  677. len = sizeof(my_addr);
  678. getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
  679. s->local_port = udp_port(&my_addr, len);
  680. if (s->is_multicast) {
  681. if (h->flags & AVIO_FLAG_WRITE) {
  682. /* output */
  683. if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
  684. goto fail;
  685. }
  686. if (h->flags & AVIO_FLAG_READ) {
  687. /* input */
  688. if (num_include_sources && num_exclude_sources) {
  689. av_log(h, AV_LOG_ERROR, "Simultaneously including and excluding multicast sources is not supported\n");
  690. goto fail;
  691. }
  692. if (num_include_sources) {
  693. if (udp_set_multicast_sources(h, udp_fd,
  694. (struct sockaddr *)&s->dest_addr,
  695. s->dest_addr_len,
  696. include_sources,
  697. num_include_sources, 1) < 0)
  698. goto fail;
  699. } else {
  700. if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage) < 0)
  701. goto fail;
  702. }
  703. if (num_exclude_sources) {
  704. if (udp_set_multicast_sources(h, udp_fd,
  705. (struct sockaddr *)&s->dest_addr,
  706. s->dest_addr_len,
  707. exclude_sources,
  708. num_exclude_sources, 0) < 0)
  709. goto fail;
  710. }
  711. }
  712. }
  713. if (is_output) {
  714. /* limit the tx buf size to limit latency */
  715. tmp = s->buffer_size;
  716. if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
  717. log_net_error(h, AV_LOG_ERROR, "setsockopt(SO_SNDBUF)");
  718. goto fail;
  719. }
  720. } else {
  721. /* set udp recv buffer size to the requested value (default 64K) */
  722. tmp = s->buffer_size;
  723. if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
  724. log_net_error(h, AV_LOG_WARNING, "setsockopt(SO_RECVBUF)");
  725. }
  726. len = sizeof(tmp);
  727. if (getsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, &len) < 0) {
  728. log_net_error(h, AV_LOG_WARNING, "getsockopt(SO_RCVBUF)");
  729. } else {
  730. av_log(h, AV_LOG_DEBUG, "end receive buffer size reported is %d\n", tmp);
  731. if(tmp < s->buffer_size)
  732. 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);
  733. }
  734. /* make the socket non-blocking */
  735. ff_socket_nonblock(udp_fd, 1);
  736. }
  737. if (s->is_connected) {
  738. if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
  739. log_net_error(h, AV_LOG_ERROR, "connect");
  740. goto fail;
  741. }
  742. }
  743. for (i = 0; i < num_include_sources; i++)
  744. av_freep(&include_sources[i]);
  745. for (i = 0; i < num_exclude_sources; i++)
  746. av_freep(&exclude_sources[i]);
  747. s->udp_fd = udp_fd;
  748. #if HAVE_PTHREAD_CANCEL
  749. if (!is_output && s->circular_buffer_size) {
  750. int ret;
  751. /* start the task going */
  752. s->fifo = av_fifo_alloc(s->circular_buffer_size);
  753. ret = pthread_mutex_init(&s->mutex, NULL);
  754. if (ret != 0) {
  755. av_log(h, AV_LOG_ERROR, "pthread_mutex_init failed : %s\n", strerror(ret));
  756. goto fail;
  757. }
  758. ret = pthread_cond_init(&s->cond, NULL);
  759. if (ret != 0) {
  760. av_log(h, AV_LOG_ERROR, "pthread_cond_init failed : %s\n", strerror(ret));
  761. goto cond_fail;
  762. }
  763. ret = pthread_create(&s->circular_buffer_thread, NULL, circular_buffer_task, h);
  764. if (ret != 0) {
  765. av_log(h, AV_LOG_ERROR, "pthread_create failed : %s\n", strerror(ret));
  766. goto thread_fail;
  767. }
  768. s->thread_started = 1;
  769. }
  770. #endif
  771. return 0;
  772. #if HAVE_PTHREAD_CANCEL
  773. thread_fail:
  774. pthread_cond_destroy(&s->cond);
  775. cond_fail:
  776. pthread_mutex_destroy(&s->mutex);
  777. #endif
  778. fail:
  779. if (udp_fd >= 0)
  780. closesocket(udp_fd);
  781. av_fifo_freep(&s->fifo);
  782. for (i = 0; i < num_include_sources; i++)
  783. av_freep(&include_sources[i]);
  784. for (i = 0; i < num_exclude_sources; i++)
  785. av_freep(&exclude_sources[i]);
  786. return AVERROR(EIO);
  787. }
  788. static int udplite_open(URLContext *h, const char *uri, int flags)
  789. {
  790. UDPContext *s = h->priv_data;
  791. // set default checksum coverage
  792. s->udplite_coverage = UDP_HEADER_SIZE;
  793. return udp_open(h, uri, flags);
  794. }
  795. static int udp_read(URLContext *h, uint8_t *buf, int size)
  796. {
  797. UDPContext *s = h->priv_data;
  798. int ret;
  799. #if HAVE_PTHREAD_CANCEL
  800. int avail, nonblock = h->flags & AVIO_FLAG_NONBLOCK;
  801. if (s->fifo) {
  802. pthread_mutex_lock(&s->mutex);
  803. do {
  804. avail = av_fifo_size(s->fifo);
  805. if (avail) { // >=size) {
  806. uint8_t tmp[4];
  807. av_fifo_generic_read(s->fifo, tmp, 4, NULL);
  808. avail= AV_RL32(tmp);
  809. if(avail > size){
  810. av_log(h, AV_LOG_WARNING, "Part of datagram lost due to insufficient buffer size\n");
  811. avail= size;
  812. }
  813. av_fifo_generic_read(s->fifo, buf, avail, NULL);
  814. av_fifo_drain(s->fifo, AV_RL32(tmp) - avail);
  815. pthread_mutex_unlock(&s->mutex);
  816. return avail;
  817. } else if(s->circular_buffer_error){
  818. int err = s->circular_buffer_error;
  819. pthread_mutex_unlock(&s->mutex);
  820. return err;
  821. } else if(nonblock) {
  822. pthread_mutex_unlock(&s->mutex);
  823. return AVERROR(EAGAIN);
  824. }
  825. else {
  826. /* FIXME: using the monotonic clock would be better,
  827. but it does not exist on all supported platforms. */
  828. int64_t t = av_gettime() + 100000;
  829. struct timespec tv = { .tv_sec = t / 1000000,
  830. .tv_nsec = (t % 1000000) * 1000 };
  831. if (pthread_cond_timedwait(&s->cond, &s->mutex, &tv) < 0) {
  832. pthread_mutex_unlock(&s->mutex);
  833. return AVERROR(errno == ETIMEDOUT ? EAGAIN : errno);
  834. }
  835. nonblock = 1;
  836. }
  837. } while( 1);
  838. }
  839. #endif
  840. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  841. ret = ff_network_wait_fd(s->udp_fd, 0);
  842. if (ret < 0)
  843. return ret;
  844. }
  845. ret = recv(s->udp_fd, buf, size, 0);
  846. return ret < 0 ? ff_neterrno() : ret;
  847. }
  848. static int udp_write(URLContext *h, const uint8_t *buf, int size)
  849. {
  850. UDPContext *s = h->priv_data;
  851. int ret;
  852. if (!(h->flags & AVIO_FLAG_NONBLOCK)) {
  853. ret = ff_network_wait_fd(s->udp_fd, 1);
  854. if (ret < 0)
  855. return ret;
  856. }
  857. if (!s->is_connected) {
  858. ret = sendto (s->udp_fd, buf, size, 0,
  859. (struct sockaddr *) &s->dest_addr,
  860. s->dest_addr_len);
  861. } else
  862. ret = send(s->udp_fd, buf, size, 0);
  863. return ret < 0 ? ff_neterrno() : ret;
  864. }
  865. static int udp_close(URLContext *h)
  866. {
  867. UDPContext *s = h->priv_data;
  868. if (s->is_multicast && (h->flags & AVIO_FLAG_READ))
  869. udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr,(struct sockaddr *)&s->local_addr_storage);
  870. closesocket(s->udp_fd);
  871. #if HAVE_PTHREAD_CANCEL
  872. if (s->thread_started) {
  873. int ret;
  874. pthread_cancel(s->circular_buffer_thread);
  875. ret = pthread_join(s->circular_buffer_thread, NULL);
  876. if (ret != 0)
  877. av_log(h, AV_LOG_ERROR, "pthread_join(): %s\n", strerror(ret));
  878. pthread_mutex_destroy(&s->mutex);
  879. pthread_cond_destroy(&s->cond);
  880. }
  881. #endif
  882. av_fifo_freep(&s->fifo);
  883. return 0;
  884. }
  885. URLProtocol ff_udp_protocol = {
  886. .name = "udp",
  887. .url_open = udp_open,
  888. .url_read = udp_read,
  889. .url_write = udp_write,
  890. .url_close = udp_close,
  891. .url_get_file_handle = udp_get_file_handle,
  892. .priv_data_size = sizeof(UDPContext),
  893. .priv_data_class = &udp_class,
  894. .flags = URL_PROTOCOL_FLAG_NETWORK,
  895. };
  896. URLProtocol ff_udplite_protocol = {
  897. .name = "udplite",
  898. .url_open = udplite_open,
  899. .url_read = udp_read,
  900. .url_write = udp_write,
  901. .url_close = udp_close,
  902. .url_get_file_handle = udp_get_file_handle,
  903. .priv_data_size = sizeof(UDPContext),
  904. .priv_data_class = &udplite_context_class,
  905. .flags = URL_PROTOCOL_FLAG_NETWORK,
  906. };