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.

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