udp.c 13.2 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1 2
/*
 * UDP prototype streaming system
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard.
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
Fabrice Bellard's avatar
Fabrice Bellard committed
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Fabrice Bellard's avatar
Fabrice Bellard committed
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 *
Fabrice Bellard's avatar
Fabrice Bellard committed
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
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
Fabrice Bellard's avatar
Fabrice Bellard committed
21
#include "avformat.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
22
#include <unistd.h>
23
#include "network.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
24

25 26 27 28 29
#ifndef IPV6_ADD_MEMBERSHIP
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#endif

Fabrice Bellard's avatar
Fabrice Bellard committed
30
typedef struct {
31 32 33 34
    int udp_fd;
    int ttl;
    int is_multicast;
    int local_port;
35
    int reuse_socket;
36
#ifndef CONFIG_IPV6
37
    struct sockaddr_in dest_addr;
38 39 40
#else
    struct sockaddr_storage dest_addr;
#endif
41
    size_t dest_addr_len;
Fabrice Bellard's avatar
Fabrice Bellard committed
42 43 44
} UDPContext;

#define UDP_TX_BUF_SIZE 32768
Ramiro Polla's avatar
Ramiro Polla committed
45
#define UDP_MAX_PKT_SIZE 65536
Fabrice Bellard's avatar
Fabrice Bellard committed
46

47
static int udp_set_multicast_ttl(int sockfd, int mcastTTL, struct sockaddr *addr) {
48
#ifdef IP_MULTICAST_TTL
49 50 51 52 53 54
    if (addr->sa_family == AF_INET) {
        if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
            perror("setsockopt(IP_MULTICAST_TTL)");
            return -1;
        }
    }
55 56
#endif
#ifdef CONFIG_IPV6
57 58 59 60 61 62
    if (addr->sa_family == AF_INET6) {
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
            perror("setsockopt(IPV6_MULTICAST_HOPS)");
            return -1;
        }
    }
63
#endif
64 65 66
    return 0;
}

67
static int udp_join_multicast_group(int sockfd, struct sockaddr *addr) {
68
#ifdef IP_ADD_MEMBERSHIP
69
    if (addr->sa_family == AF_INET) {
70 71
        struct ip_mreq mreq;

72 73 74 75 76 77 78
        mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
        mreq.imr_interface.s_addr= INADDR_ANY;
        if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
            perror("setsockopt(IP_ADD_MEMBERSHIP)");
            return -1;
        }
    }
79 80
#endif
#ifdef CONFIG_IPV6
81
    if (addr->sa_family == AF_INET6) {
82 83
        struct ipv6_mreq mreq6;

84 85 86 87 88 89 90
        memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
        mreq6.ipv6mr_interface= 0;
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
            perror("setsockopt(IPV6_ADD_MEMBERSHIP)");
            return -1;
        }
    }
91
#endif
92 93 94
    return 0;
}

95
static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr) {
96
#ifdef IP_DROP_MEMBERSHIP
97
    if (addr->sa_family == AF_INET) {
98 99
        struct ip_mreq mreq;

100 101 102 103 104 105 106
        mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
        mreq.imr_interface.s_addr= INADDR_ANY;
        if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
            perror("setsockopt(IP_DROP_MEMBERSHIP)");
            return -1;
        }
    }
107 108
#endif
#ifdef CONFIG_IPV6
109
    if (addr->sa_family == AF_INET6) {
110 111
        struct ipv6_mreq mreq6;

112 113 114 115 116 117 118
        memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
        mreq6.ipv6mr_interface= 0;
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
            perror("setsockopt(IPV6_DROP_MEMBERSHIP)");
            return -1;
        }
    }
119
#endif
120 121 122
    return 0;
}

123
#ifdef CONFIG_IPV6
124
static struct addrinfo* udp_ipv6_resolve_host(const char *hostname, int port, int type, int family, int flags) {
125 126 127
    struct addrinfo hints, *res = 0;
    int error;
    char sport[16];
128
    const char *node = 0, *service = "0";
129 130

    if (port > 0) {
Michael Niedermayer's avatar
Michael Niedermayer committed
131
        snprintf(sport, sizeof(sport), "%d", port);
132 133 134 135 136
        service = sport;
    }
    if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
        node = hostname;
    }
Luca Abeni's avatar
Luca Abeni committed
137 138 139 140 141 142 143 144
    memset(&hints, 0, sizeof(hints));
    hints.ai_socktype = type;
    hints.ai_family   = family;
    hints.ai_flags = flags;
    if ((error = getaddrinfo(node, service, &hints, &res))) {
        av_log(NULL, AV_LOG_ERROR, "udp_ipv6_resolve_host: %s\n", gai_strerror(error));
    }

145 146 147
    return res;
}

148
static int udp_ipv6_set_remote_url(URLContext *h, const char *uri) {
149 150 151 152 153 154
    UDPContext *s = h->priv_data;
    char hostname[256];
    int port;
    struct addrinfo *res0;
    url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
    res0 = udp_ipv6_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
155
    if (res0 == 0) return AVERROR(EIO);
156 157 158 159 160 161
    memcpy(&s->dest_addr, res0->ai_addr, res0->ai_addrlen);
    s->dest_addr_len = res0->ai_addrlen;
    freeaddrinfo(res0);
    return 0;
}

162
static int udp_ipv6_set_local(URLContext *h) {
163 164 165 166 167 168
    UDPContext *s = h->priv_data;
    int udp_fd = -1;
    struct sockaddr_storage clientaddr;
    socklen_t addrlen;
    char sbuf[NI_MAXSERV];
    char hbuf[NI_MAXHOST];
169
    struct addrinfo *res0 = NULL, *res = NULL;
170
    int family = AF_UNSPEC;
171

172 173 174
    if (((struct sockaddr *) &s->dest_addr)->sa_family)
        family = ((struct sockaddr *) &s->dest_addr)->sa_family;
    res0 = udp_ipv6_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE);
Luca Abeni's avatar
Luca Abeni committed
175 176 177 178 179 180 181
    if (res0 == 0)
        goto fail;
    for (res = res0; res; res=res->ai_next) {
        udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
        if (udp_fd > 0) break;
        perror("socket");
    }
182 183

    if (udp_fd < 0)
184
        goto fail;
185

Luca Abeni's avatar
Luca Abeni committed
186 187 188 189 190
    if (bind(udp_fd, res0->ai_addr, res0->ai_addrlen) < 0) {
        perror("bind");
        goto fail;
    }
    freeaddrinfo(res0);
191
        res0 = NULL;
192 193 194 195 196 197 198 199 200 201 202 203 204

    addrlen = sizeof(clientaddr);
    if (getsockname(udp_fd, (struct sockaddr *)&clientaddr, &addrlen) < 0) {
        perror("getsockname");
        goto fail;
    }

    if (getnameinfo((struct sockaddr *)&clientaddr, addrlen, hbuf, sizeof(hbuf),  sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
        perror("getnameinfo");
        goto fail;
    }

    s->local_port = strtol(sbuf, NULL, 10);
205

206
    return udp_fd;
207

208 209 210
 fail:
    if (udp_fd >= 0)
        closesocket(udp_fd);
211 212
    if(res0)
        freeaddrinfo(res0);
213 214 215
    return -1;
}

216
#endif /* CONFIG_IPV6 */
217 218


219 220 221 222 223 224
/**
 * If no filename is given to av_open_input_file because you want to
 * get the local port first, then you must call this function to set
 * the remote server address.
 *
 * url syntax: udp://host:port[?option=val...]
225
 * option: 'multicast=1' : enable multicast
226 227
 *         'ttl=n'       : set the ttl value (for multicast only)
 *         'localport=n' : set the local port
228
 *         'pkt_size=n'  : set max packet size
229
 *         'reuse=1'     : enable reusing the socket
230 231 232 233 234 235 236
 *
 * @param s1 media file context
 * @param uri of the remote server
 * @return zero if no error.
 */
int udp_set_remote_url(URLContext *h, const char *uri)
{
237 238 239
#ifdef CONFIG_IPV6
    return udp_ipv6_set_remote_url(h, uri);
#else
240 241 242
    UDPContext *s = h->priv_data;
    char hostname[256];
    int port;
243

244
    url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
Fabrice Bellard's avatar
Fabrice Bellard committed
245

246 247
    /* set the destination address */
    if (resolve_host(&s->dest_addr.sin_addr, hostname) < 0)
248
        return AVERROR(EIO);
249 250
    s->dest_addr.sin_family = AF_INET;
    s->dest_addr.sin_port = htons(port);
251
    s->dest_addr_len = sizeof(s->dest_addr);
252
    return 0;
253
#endif
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
}

/**
 * Return the local port used by the UDP connexion
 * @param s1 media file context
 * @return the local port number
 */
int udp_get_local_port(URLContext *h)
{
    UDPContext *s = h->priv_data;
    return s->local_port;
}

/**
 * Return the udp file handle for select() usage to wait for several RTP
 * streams at the same time.
 * @param h media file context
 */
int udp_get_file_handle(URLContext *h)
{
    UDPContext *s = h->priv_data;
    return s->udp_fd;
}

/* put it in UDP context */
Fabrice Bellard's avatar
Fabrice Bellard committed
279 280 281 282
/* return non zero if error */
static int udp_open(URLContext *h, const char *uri, int flags)
{
    char hostname[1024];
283 284
    int port, udp_fd = -1, tmp;
    UDPContext *s = NULL;
285
    int is_output;
286 287
    const char *p;
    char buf[256];
288 289 290 291
#ifndef CONFIG_IPV6
    struct sockaddr_in my_addr, my_addr1;
    int len;
#endif
Fabrice Bellard's avatar
Fabrice Bellard committed
292 293

    h->is_streamed = 1;
294
    h->max_packet_size = 1472;
Fabrice Bellard's avatar
Fabrice Bellard committed
295

296
    is_output = (flags & URL_WRONLY);
297

298
    s = av_mallocz(sizeof(UDPContext));
299
    if (!s)
300
        return AVERROR(ENOMEM);
301 302 303 304

    h->priv_data = s;
    s->ttl = 16;
    s->is_multicast = 0;
305
    s->local_port = 0;
306
    s->reuse_socket = 0;
307 308 309
    p = strchr(uri, '?');
    if (p) {
        s->is_multicast = find_info_tag(buf, sizeof(buf), "multicast", p);
310
        s->reuse_socket = find_info_tag(buf, sizeof(buf), "reuse", p);
311 312 313 314 315 316
        if (find_info_tag(buf, sizeof(buf), "ttl", p)) {
            s->ttl = strtol(buf, NULL, 10);
        }
        if (find_info_tag(buf, sizeof(buf), "localport", p)) {
            s->local_port = strtol(buf, NULL, 10);
        }
317 318 319
        if (find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
            h->max_packet_size = strtol(buf, NULL, 10);
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
320
    }
321 322

    /* fill the dest addr */
323
    url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
324

325 326 327 328 329 330 331 332
    /* XXX: fix url_split */
    if (hostname[0] == '\0' || hostname[0] == '?') {
        /* only accepts null hostname if input */
        if (s->is_multicast || (flags & URL_WRONLY))
            goto fail;
    } else {
        udp_set_remote_url(h, uri);
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
333

334 335 336
    if(!ff_network_init())
        return AVERROR(EIO);

337
#ifndef CONFIG_IPV6
338
    udp_fd = socket(AF_INET, SOCK_DGRAM, 0);
339 340 341
    if (udp_fd < 0)
        goto fail;

Fabrice Bellard's avatar
Fabrice Bellard committed
342 343
    my_addr.sin_family = AF_INET;
    my_addr.sin_addr.s_addr = htonl (INADDR_ANY);
344
    if (s->is_multicast && !(h->flags & URL_WRONLY)) {
Fabrice Bellard's avatar
Fabrice Bellard committed
345 346
        /* special case: the bind must be done on the multicast address port */
        my_addr.sin_port = s->dest_addr.sin_port;
347 348 349
    } else {
        my_addr.sin_port = htons(s->local_port);
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
350

351 352 353 354
    if (s->reuse_socket)
        if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
            goto fail;

Fabrice Bellard's avatar
Fabrice Bellard committed
355
    /* the bind is needed to give a port to the socket now */
356
    if (bind(udp_fd,(struct sockaddr *)&my_addr, sizeof(my_addr)) < 0)
Fabrice Bellard's avatar
Fabrice Bellard committed
357 358
        goto fail;

359 360 361
    len = sizeof(my_addr1);
    getsockname(udp_fd, (struct sockaddr *)&my_addr1, &len);
    s->local_port = ntohs(my_addr1.sin_port);
362 363 364 365 366 367
#else
    if (s->is_multicast && !(h->flags & URL_WRONLY))
        s->local_port = port;
    udp_fd = udp_ipv6_set_local(h);
    if (udp_fd < 0)
        goto fail;
368
#endif /* CONFIG_IPV6 */
369 370
    if (s->is_multicast) {
        if (h->flags & URL_WRONLY) {
371
            /* output */
372
            if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
373 374
                goto fail;
        } else {
375
            /* input */
376
            if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
377 378 379
                goto fail;
        }
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
380

381 382 383 384 385 386 387
    if (is_output) {
        /* limit the tx buf size to limit latency */
        tmp = UDP_TX_BUF_SIZE;
        if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
            perror("setsockopt sndbuf");
            goto fail;
        }
Ramiro Polla's avatar
Ramiro Polla committed
388 389 390 391 392
    } else {
        /* set udp recv buffer size to the largest possible udp packet size to
         * avoid losing data on OSes that set this too low by default. */
        tmp = UDP_MAX_PKT_SIZE;
        setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp));
393 394 395
    }

    s->udp_fd = udp_fd;
Fabrice Bellard's avatar
Fabrice Bellard committed
396 397
    return 0;
 fail:
398
    if (udp_fd >= 0)
399
        closesocket(udp_fd);
400
    av_free(s);
401
    return AVERROR(EIO);
Fabrice Bellard's avatar
Fabrice Bellard committed
402 403
}

404
static int udp_read(URLContext *h, uint8_t *buf, int size)
Fabrice Bellard's avatar
Fabrice Bellard committed
405 406
{
    UDPContext *s = h->priv_data;
407
#ifndef CONFIG_IPV6
408
    struct sockaddr_in from;
409 410 411
#else
    struct sockaddr_storage from;
#endif
Måns Rullgård's avatar
Måns Rullgård committed
412 413
    socklen_t from_len;
    int len;
414 415 416 417 418 419

    for(;;) {
        from_len = sizeof(from);
        len = recvfrom (s->udp_fd, buf, size, 0,
                        (struct sockaddr *)&from, &from_len);
        if (len < 0) {
420 421
            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
                ff_neterrno() != FF_NETERROR(EINTR))
422
                return AVERROR(EIO);
423 424 425 426 427
        } else {
            break;
        }
    }
    return len;
Fabrice Bellard's avatar
Fabrice Bellard committed
428 429
}

430
static int udp_write(URLContext *h, uint8_t *buf, int size)
Fabrice Bellard's avatar
Fabrice Bellard committed
431 432
{
    UDPContext *s = h->priv_data;
433 434 435
    int ret;

    for(;;) {
436
        ret = sendto (s->udp_fd, buf, size, 0,
437
                      (struct sockaddr *) &s->dest_addr,
438
                      s->dest_addr_len);
439
        if (ret < 0) {
440 441
            if (ff_neterrno() != FF_NETERROR(EINTR) &&
                ff_neterrno() != FF_NETERROR(EAGAIN))
442
                return AVERROR(EIO);
443 444 445
        } else {
            break;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
446
    }
447 448 449 450 451 452 453
    return size;
}

static int udp_close(URLContext *h)
{
    UDPContext *s = h->priv_data;

454
    if (s->is_multicast && !(h->flags & URL_WRONLY))
455
        udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
456
    closesocket(s->udp_fd);
457
    ff_network_close();
458 459
    av_free(s);
    return 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
460 461 462 463 464
}

URLProtocol udp_protocol = {
    "udp",
    udp_open,
465
    udp_read,
Fabrice Bellard's avatar
Fabrice Bellard committed
466 467 468 469
    udp_write,
    NULL, /* seek */
    udp_close,
};