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.

993 lines
35KB

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