Statistics
| Branch: | Revision:

ffmpeg / libavformat / udp.c @ 59612534

History | View | Annotate | Download (14.5 KB)

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
/**
23
 * @file
24
 * UDP protocol
25
 */
26

    
27
#define _BSD_SOURCE     /* Needed for using struct ip_mreq with recent glibc */
28
#define _DARWIN_C_SOURCE /* Needed for using IP_MULTICAST_TTL on OS X */
29
#include "avformat.h"
30
#include <unistd.h>
31
#include "internal.h"
32
#include "network.h"
33
#include "os_support.h"
34
#if HAVE_SYS_SELECT_H
35
#include <sys/select.h>
36
#endif
37
#include <sys/time.h>
38

    
39
#ifndef IPV6_ADD_MEMBERSHIP
40
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
41
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
42
#endif
43
#ifndef IN_MULTICAST
44
#define IN_MULTICAST(a) ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000)
45
#endif
46
#ifndef IN6_IS_ADDR_MULTICAST
47
#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t *) (a))[0] == 0xff)
48
#endif
49

    
50
typedef struct {
51
    int udp_fd;
52
    int ttl;
53
    int buffer_size;
54
    int is_multicast;
55
    int local_port;
56
    int reuse_socket;
57
    struct sockaddr_storage dest_addr;
58
    int dest_addr_len;
59
} UDPContext;
60

    
61
#define UDP_TX_BUF_SIZE 32768
62
#define UDP_MAX_PKT_SIZE 65536
63

    
64
static int udp_set_multicast_ttl(int sockfd, int mcastTTL,
65
                                 struct sockaddr *addr)
66
{
67
#ifdef IP_MULTICAST_TTL
68
    if (addr->sa_family == AF_INET) {
69
        if (setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &mcastTTL, sizeof(mcastTTL)) < 0) {
70
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_MULTICAST_TTL): %s\n", strerror(errno));
71
            return -1;
72
        }
73
    }
74
#endif
75
#if defined(IPPROTO_IPV6) && defined(IPV6_MULTICAST_HOPS)
76
    if (addr->sa_family == AF_INET6) {
77
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &mcastTTL, sizeof(mcastTTL)) < 0) {
78
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_MULTICAST_HOPS): %s\n", strerror(errno));
79
            return -1;
80
        }
81
    }
82
#endif
83
    return 0;
84
}
85

    
86
static int udp_join_multicast_group(int sockfd, struct sockaddr *addr)
87
{
88
#ifdef IP_ADD_MEMBERSHIP
89
    if (addr->sa_family == AF_INET) {
90
        struct ip_mreq mreq;
91

    
92
        mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
93
        mreq.imr_interface.s_addr= INADDR_ANY;
94
        if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
95
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_ADD_MEMBERSHIP): %s\n", strerror(errno));
96
            return -1;
97
        }
98
    }
99
#endif
100
#if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
101
    if (addr->sa_family == AF_INET6) {
102
        struct ipv6_mreq mreq6;
103

    
104
        memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
105
        mreq6.ipv6mr_interface= 0;
106
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
107
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_ADD_MEMBERSHIP): %s\n", strerror(errno));
108
            return -1;
109
        }
110
    }
111
#endif
112
    return 0;
113
}
114

    
115
static int udp_leave_multicast_group(int sockfd, struct sockaddr *addr)
116
{
117
#ifdef IP_DROP_MEMBERSHIP
118
    if (addr->sa_family == AF_INET) {
119
        struct ip_mreq mreq;
120

    
121
        mreq.imr_multiaddr.s_addr = ((struct sockaddr_in *)addr)->sin_addr.s_addr;
122
        mreq.imr_interface.s_addr= INADDR_ANY;
123
        if (setsockopt(sockfd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (const void *)&mreq, sizeof(mreq)) < 0) {
124
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IP_DROP_MEMBERSHIP): %s\n", strerror(errno));
125
            return -1;
126
        }
127
    }
128
#endif
129
#if HAVE_STRUCT_IPV6_MREQ && defined(IPPROTO_IPV6)
130
    if (addr->sa_family == AF_INET6) {
131
        struct ipv6_mreq mreq6;
132

    
133
        memcpy(&mreq6.ipv6mr_multiaddr, &(((struct sockaddr_in6 *)addr)->sin6_addr), sizeof(struct in6_addr));
134
        mreq6.ipv6mr_interface= 0;
135
        if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq6, sizeof(mreq6)) < 0) {
136
            av_log(NULL, AV_LOG_ERROR, "setsockopt(IPV6_DROP_MEMBERSHIP): %s\n", strerror(errno));
137
            return -1;
138
        }
139
    }
140
#endif
141
    return 0;
142
}
143

    
144
static struct addrinfo* udp_resolve_host(const char *hostname, int port,
145
                                         int type, int family, int flags)
146
{
147
    struct addrinfo hints, *res = 0;
148
    int error;
149
    char sport[16];
150
    const char *node = 0, *service = "0";
151

    
152
    if (port > 0) {
153
        snprintf(sport, sizeof(sport), "%d", port);
154
        service = sport;
155
    }
156
    if ((hostname) && (hostname[0] != '\0') && (hostname[0] != '?')) {
157
        node = hostname;
158
    }
159
    memset(&hints, 0, sizeof(hints));
160
    hints.ai_socktype = type;
161
    hints.ai_family   = family;
162
    hints.ai_flags = flags;
163
    if ((error = getaddrinfo(node, service, &hints, &res))) {
164
        res = NULL;
165
        av_log(NULL, AV_LOG_ERROR, "udp_resolve_host: %s\n", gai_strerror(error));
166
    }
167

    
168
    return res;
169
}
170

    
171
static int udp_set_url(struct sockaddr_storage *addr,
172
                       const char *hostname, int port)
173
{
174
    struct addrinfo *res0;
175
    int addr_len;
176

    
177
    res0 = udp_resolve_host(hostname, port, SOCK_DGRAM, AF_UNSPEC, 0);
178
    if (res0 == 0) return AVERROR(EIO);
179
    memcpy(addr, res0->ai_addr, res0->ai_addrlen);
180
    addr_len = res0->ai_addrlen;
181
    freeaddrinfo(res0);
182

    
183
    return addr_len;
184
}
185

    
186
static int is_multicast_address(struct sockaddr_storage *addr)
187
{
188
    if (addr->ss_family == AF_INET) {
189
        return IN_MULTICAST(ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr));
190
    }
191
#if HAVE_STRUCT_SOCKADDR_IN6
192
    if (addr->ss_family == AF_INET6) {
193
        return IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)addr)->sin6_addr);
194
    }
195
#endif
196

    
197
    return 0;
198
}
199

    
200
static int udp_socket_create(UDPContext *s,
201
                             struct sockaddr_storage *addr, int *addr_len)
202
{
203
    int udp_fd = -1;
204
    struct addrinfo *res0 = NULL, *res = NULL;
205
    int family = AF_UNSPEC;
206

    
207
    if (((struct sockaddr *) &s->dest_addr)->sa_family)
208
        family = ((struct sockaddr *) &s->dest_addr)->sa_family;
209
    res0 = udp_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE);
210
    if (res0 == 0)
211
        goto fail;
212
    for (res = res0; res; res=res->ai_next) {
213
        udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
214
        if (udp_fd > 0) break;
215
        av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
216
    }
217

    
218
    if (udp_fd < 0)
219
        goto fail;
220

    
221
    memcpy(addr, res->ai_addr, res->ai_addrlen);
222
    *addr_len = res->ai_addrlen;
223

    
224
    freeaddrinfo(res0);
225

    
226
    return udp_fd;
227

    
228
 fail:
229
    if (udp_fd >= 0)
230
        closesocket(udp_fd);
231
    if(res0)
232
        freeaddrinfo(res0);
233
    return -1;
234
}
235

    
236
static int udp_port(struct sockaddr_storage *addr, int addr_len)
237
{
238
    char sbuf[sizeof(int)*3+1];
239

    
240
    if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
241
        av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
242
        return -1;
243
    }
244

    
245
    return strtol(sbuf, NULL, 10);
246
}
247

    
248

    
249
/**
250
 * If no filename is given to av_open_input_file because you want to
251
 * get the local port first, then you must call this function to set
252
 * the remote server address.
253
 *
254
 * url syntax: udp://host:port[?option=val...]
255
 * option: 'ttl=n'       : set the ttl value (for multicast only)
256
 *         'localport=n' : set the local port
257
 *         'pkt_size=n'  : set max packet size
258
 *         'reuse=1'     : enable reusing the socket
259
 *
260
 * @param h media file context
261
 * @param uri of the remote server
262
 * @return zero if no error.
263
 */
264
int udp_set_remote_url(URLContext *h, const char *uri)
265
{
266
    UDPContext *s = h->priv_data;
267
    char hostname[256];
268
    int port;
269

    
270
    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
271

    
272
    /* set the destination address */
273
    s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
274
    if (s->dest_addr_len < 0) {
275
        return AVERROR(EIO);
276
    }
277
    s->is_multicast = is_multicast_address(&s->dest_addr);
278

    
279
    return 0;
280
}
281

    
282
/**
283
 * Return the local port used by the UDP connection
284
 * @param h media file context
285
 * @return the local port number
286
 */
287
int udp_get_local_port(URLContext *h)
288
{
289
    UDPContext *s = h->priv_data;
290
    return s->local_port;
291
}
292

    
293
/**
294
 * Return the udp file handle for select() usage to wait for several RTP
295
 * streams at the same time.
296
 * @param h media file context
297
 */
298
#if (LIBAVFORMAT_VERSION_MAJOR >= 53)
299
static
300
#endif
301
int udp_get_file_handle(URLContext *h)
302
{
303
    UDPContext *s = h->priv_data;
304
    return s->udp_fd;
305
}
306

    
307
/* put it in UDP context */
308
/* return non zero if error */
309
static int udp_open(URLContext *h, const char *uri, int flags)
310
{
311
    char hostname[1024];
312
    int port, udp_fd = -1, tmp, bind_ret = -1;
313
    UDPContext *s = NULL;
314
    int is_output;
315
    const char *p;
316
    char buf[256];
317
    struct sockaddr_storage my_addr;
318
    int len;
319

    
320
    h->is_streamed = 1;
321
    h->max_packet_size = 1472;
322

    
323
    is_output = (flags & URL_WRONLY);
324

    
325
    s = av_mallocz(sizeof(UDPContext));
326
    if (!s)
327
        return AVERROR(ENOMEM);
328

    
329
    h->priv_data = s;
330
    s->ttl = 16;
331
    s->buffer_size = is_output ? UDP_TX_BUF_SIZE : UDP_MAX_PKT_SIZE;
332

    
333
    p = strchr(uri, '?');
334
    if (p) {
335
        s->reuse_socket = find_info_tag(buf, sizeof(buf), "reuse", p);
336
        if (find_info_tag(buf, sizeof(buf), "ttl", p)) {
337
            s->ttl = strtol(buf, NULL, 10);
338
        }
339
        if (find_info_tag(buf, sizeof(buf), "localport", p)) {
340
            s->local_port = strtol(buf, NULL, 10);
341
        }
342
        if (find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
343
            h->max_packet_size = strtol(buf, NULL, 10);
344
        }
345
        if (find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
346
            s->buffer_size = strtol(buf, NULL, 10);
347
        }
348
    }
349

    
350
    /* fill the dest addr */
351
    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
352

    
353
    /* XXX: fix av_url_split */
354
    if (hostname[0] == '\0' || hostname[0] == '?') {
355
        /* only accepts null hostname if input */
356
        if (flags & URL_WRONLY)
357
            goto fail;
358
    } else {
359
        if (udp_set_remote_url(h, uri) < 0)
360
            goto fail;
361
    }
362

    
363
    if (s->is_multicast && !(h->flags & URL_WRONLY))
364
        s->local_port = port;
365
    udp_fd = udp_socket_create(s, &my_addr, &len);
366
    if (udp_fd < 0)
367
        goto fail;
368

    
369
    if (s->reuse_socket)
370
        if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
371
            goto fail;
372

    
373
    /* the bind is needed to give a port to the socket now */
374
    /* if multicast, try the multicast address bind first */
375
    if (s->is_multicast && !(h->flags & URL_WRONLY)) {
376
        bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
377
    }
378
    /* bind to the local address if not multicast or if the multicast
379
     * bind failed */
380
    if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0)
381
        goto fail;
382

    
383
    len = sizeof(my_addr);
384
    getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
385
    s->local_port = udp_port(&my_addr, len);
386

    
387
    if (s->is_multicast) {
388
        if (h->flags & URL_WRONLY) {
389
            /* output */
390
            if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
391
                goto fail;
392
        } else {
393
            /* input */
394
            if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
395
                goto fail;
396
        }
397
    }
398

    
399
    if (is_output) {
400
        /* limit the tx buf size to limit latency */
401
        tmp = s->buffer_size;
402
        if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
403
            av_log(NULL, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
404
            goto fail;
405
        }
406
    } else {
407
        /* set udp recv buffer size to the largest possible udp packet size to
408
         * avoid losing data on OSes that set this too low by default. */
409
        tmp = s->buffer_size;
410
        if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
411
            av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
412
        }
413
        /* make the socket non-blocking */
414
        ff_socket_nonblock(udp_fd, 1);
415
    }
416

    
417
    s->udp_fd = udp_fd;
418
    return 0;
419
 fail:
420
    if (udp_fd >= 0)
421
        closesocket(udp_fd);
422
    av_free(s);
423
    return AVERROR(EIO);
424
}
425

    
426
static int udp_read(URLContext *h, uint8_t *buf, int size)
427
{
428
    UDPContext *s = h->priv_data;
429
    int len;
430
    fd_set rfds;
431
    int ret;
432
    struct timeval tv;
433

    
434
    for(;;) {
435
        if (url_interrupt_cb())
436
            return AVERROR(EINTR);
437
        FD_ZERO(&rfds);
438
        FD_SET(s->udp_fd, &rfds);
439
        tv.tv_sec = 0;
440
        tv.tv_usec = 100 * 1000;
441
        ret = select(s->udp_fd + 1, &rfds, NULL, NULL, &tv);
442
        if (ret < 0) {
443
            if (ff_neterrno() == FF_NETERROR(EINTR))
444
                continue;
445
            return AVERROR(EIO);
446
        }
447
        if (!(ret > 0 && FD_ISSET(s->udp_fd, &rfds)))
448
            continue;
449
        len = recv(s->udp_fd, buf, size, 0);
450
        if (len < 0) {
451
            if (ff_neterrno() != FF_NETERROR(EAGAIN) &&
452
                ff_neterrno() != FF_NETERROR(EINTR))
453
                return AVERROR(EIO);
454
        } else {
455
            break;
456
        }
457
    }
458
    return len;
459
}
460

    
461
static int udp_write(URLContext *h, const uint8_t *buf, int size)
462
{
463
    UDPContext *s = h->priv_data;
464
    int ret;
465

    
466
    for(;;) {
467
        ret = sendto (s->udp_fd, buf, size, 0,
468
                      (struct sockaddr *) &s->dest_addr,
469
                      s->dest_addr_len);
470
        if (ret < 0) {
471
            if (ff_neterrno() != FF_NETERROR(EINTR) &&
472
                ff_neterrno() != FF_NETERROR(EAGAIN))
473
                return ff_neterrno();
474
        } else {
475
            break;
476
        }
477
    }
478
    return size;
479
}
480

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

    
485
    if (s->is_multicast && !(h->flags & URL_WRONLY))
486
        udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
487
    closesocket(s->udp_fd);
488
    av_free(s);
489
    return 0;
490
}
491

    
492
URLProtocol udp_protocol = {
493
    "udp",
494
    udp_open,
495
    udp_read,
496
    udp_write,
497
    NULL, /* seek */
498
    udp_close,
499
    .url_get_file_handle = udp_get_file_handle,
500
};