udp.c 29 KB

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