Statistics
| Branch: | Revision:

ffmpeg / libavformat / udp.c @ 814c5641

History | View | Annotate | Download (14.2 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 libavformat/udp.c
24
 * UDP protocol
25
 */
26

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

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

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

    
59
#define UDP_TX_BUF_SIZE 32768
60
#define UDP_MAX_PKT_SIZE 65536
61

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

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

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

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

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

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

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

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

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

    
166
    return res;
167
}
168

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

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

    
181
    return addr_len;
182
}
183

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

    
195
    return 0;
196
}
197

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

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

    
216
    if (udp_fd < 0)
217
        goto fail;
218

    
219
    memcpy(addr, res->ai_addr, res->ai_addrlen);
220
    *addr_len = res->ai_addrlen;
221

    
222
    freeaddrinfo(res0);
223

    
224
    return udp_fd;
225

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

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

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

    
243
    return strtol(sbuf, NULL, 10);
244
}
245

    
246

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

    
268
    url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
269

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

    
277
    return 0;
278
}
279

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

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

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

    
318
    h->is_streamed = 1;
319
    h->max_packet_size = 1472;
320

    
321
    is_output = (flags & URL_WRONLY);
322

    
323
    s = av_mallocz(sizeof(UDPContext));
324
    if (!s)
325
        return AVERROR(ENOMEM);
326

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

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

    
348
    /* fill the dest addr */
349
    url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
350

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

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

    
366
    if (s->reuse_socket)
367
        if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
368
            goto fail;
369

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

    
380
    len = sizeof(my_addr);
381
    getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
382
    s->local_port = udp_port(&my_addr, len);
383

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

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

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

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

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

    
455
static int udp_write(URLContext *h, uint8_t *buf, int size)
456
{
457
    UDPContext *s = h->priv_data;
458
    int ret;
459

    
460
    for(;;) {
461
        ret = sendto (s->udp_fd, buf, size, 0,
462
                      (struct sockaddr *) &s->dest_addr,
463
                      s->dest_addr_len);
464
        if (ret < 0) {
465
            if (ff_neterrno() != FF_NETERROR(EINTR) &&
466
                ff_neterrno() != FF_NETERROR(EAGAIN))
467
                return AVERROR(EIO);
468
        } else {
469
            break;
470
        }
471
    }
472
    return size;
473
}
474

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

    
479
    if (s->is_multicast && !(h->flags & URL_WRONLY))
480
        udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
481
    closesocket(s->udp_fd);
482
    av_free(s);
483
    return 0;
484
}
485

    
486
URLProtocol udp_protocol = {
487
    "udp",
488
    udp_open,
489
    udp_read,
490
    udp_write,
491
    NULL, /* seek */
492
    udp_close,
493
    .url_get_file_handle = udp_get_file_handle,
494
};