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.

1180 lines
42KB

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