Statistics
| Branch: | Revision:

ffmpeg / libavformat / udp.c @ 28c4741a

History | View | Annotate | Download (15.4 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 "libavutil/parseutils.h"
31
#include <unistd.h>
32
#include "internal.h"
33
#include "network.h"
34
#include "os_support.h"
35
#if HAVE_POLL_H
36
#include <poll.h>
37
#endif
38
#include <sys/time.h>
39

    
40
#ifndef IPV6_ADD_MEMBERSHIP
41
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
42
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
43
#endif
44

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

    
57
#define UDP_TX_BUF_SIZE 32768
58
#define UDP_MAX_PKT_SIZE 65536
59

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

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

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

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

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

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

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

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

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

    
164
    return res;
165
}
166

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

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

    
179
    return addr_len;
180
}
181

    
182
static int udp_socket_create(UDPContext *s,
183
                             struct sockaddr_storage *addr, int *addr_len)
184
{
185
    int udp_fd = -1;
186
    struct addrinfo *res0 = NULL, *res = NULL;
187
    int family = AF_UNSPEC;
188

    
189
    if (((struct sockaddr *) &s->dest_addr)->sa_family)
190
        family = ((struct sockaddr *) &s->dest_addr)->sa_family;
191
    res0 = udp_resolve_host(0, s->local_port, SOCK_DGRAM, family, AI_PASSIVE);
192
    if (res0 == 0)
193
        goto fail;
194
    for (res = res0; res; res=res->ai_next) {
195
        udp_fd = socket(res->ai_family, SOCK_DGRAM, 0);
196
        if (udp_fd > 0) break;
197
        av_log(NULL, AV_LOG_ERROR, "socket: %s\n", strerror(errno));
198
    }
199

    
200
    if (udp_fd < 0)
201
        goto fail;
202

    
203
    memcpy(addr, res->ai_addr, res->ai_addrlen);
204
    *addr_len = res->ai_addrlen;
205

    
206
    freeaddrinfo(res0);
207

    
208
    return udp_fd;
209

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

    
218
static int udp_port(struct sockaddr_storage *addr, int addr_len)
219
{
220
    char sbuf[sizeof(int)*3+1];
221

    
222
    if (getnameinfo((struct sockaddr *)addr, addr_len, NULL, 0,  sbuf, sizeof(sbuf), NI_NUMERICSERV) != 0) {
223
        av_log(NULL, AV_LOG_ERROR, "getnameinfo: %s\n", strerror(errno));
224
        return -1;
225
    }
226

    
227
    return strtol(sbuf, NULL, 10);
228
}
229

    
230

    
231
/**
232
 * If no filename is given to av_open_input_file because you want to
233
 * get the local port first, then you must call this function to set
234
 * the remote server address.
235
 *
236
 * url syntax: udp://host:port[?option=val...]
237
 * option: 'ttl=n'       : set the ttl value (for multicast only)
238
 *         'localport=n' : set the local port
239
 *         'pkt_size=n'  : set max packet size
240
 *         'reuse=1'     : enable reusing the socket
241
 *
242
 * @param h media file context
243
 * @param uri of the remote server
244
 * @return zero if no error.
245
 */
246
int udp_set_remote_url(URLContext *h, const char *uri)
247
{
248
    UDPContext *s = h->priv_data;
249
    char hostname[256], buf[10];
250
    int port;
251
    const char *p;
252

    
253
    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
254

    
255
    /* set the destination address */
256
    s->dest_addr_len = udp_set_url(&s->dest_addr, hostname, port);
257
    if (s->dest_addr_len < 0) {
258
        return AVERROR(EIO);
259
    }
260
    s->is_multicast = ff_is_multicast_address((struct sockaddr*) &s->dest_addr);
261
    p = strchr(uri, '?');
262
    if (p) {
263
        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
264
            int was_connected = s->is_connected;
265
            s->is_connected = strtol(buf, NULL, 10);
266
            if (s->is_connected && !was_connected) {
267
                if (connect(s->udp_fd, (struct sockaddr *) &s->dest_addr,
268
                            s->dest_addr_len)) {
269
                    s->is_connected = 0;
270
                    av_log(NULL, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
271
                    return AVERROR(EIO);
272
                }
273
            }
274
        }
275
    }
276

    
277
    return 0;
278
}
279

    
280
/**
281
 * Return the local port used by the UDP connection
282
 * @param h 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 !FF_API_UDP_GET_FILE
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
    int reuse_specified = 0;
318

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

    
322
    is_output = (flags & URL_WRONLY);
323

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

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

    
332
    p = strchr(uri, '?');
333
    if (p) {
334
        if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
335
            const char *endptr=NULL;
336
            s->reuse_socket = strtol(buf, &endptr, 10);
337
            /* assume if no digits were found it is a request to enable it */
338
            if (buf == endptr)
339
                s->reuse_socket = 1;
340
            reuse_specified = 1;
341
        }
342
        if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
343
            s->ttl = strtol(buf, NULL, 10);
344
        }
345
        if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
346
            s->local_port = strtol(buf, NULL, 10);
347
        }
348
        if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
349
            h->max_packet_size = strtol(buf, NULL, 10);
350
        }
351
        if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
352
            s->buffer_size = strtol(buf, NULL, 10);
353
        }
354
        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
355
            s->is_connected = strtol(buf, NULL, 10);
356
        }
357
    }
358

    
359
    /* fill the dest addr */
360
    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
361

    
362
    /* XXX: fix av_url_split */
363
    if (hostname[0] == '\0' || hostname[0] == '?') {
364
        /* only accepts null hostname if input */
365
        if (flags & URL_WRONLY)
366
            goto fail;
367
    } else {
368
        if (udp_set_remote_url(h, uri) < 0)
369
            goto fail;
370
    }
371

    
372
    if (s->is_multicast && !(h->flags & URL_WRONLY))
373
        s->local_port = port;
374
    udp_fd = udp_socket_create(s, &my_addr, &len);
375
    if (udp_fd < 0)
376
        goto fail;
377

    
378
    /* Follow the requested reuse option, unless it's multicast in which
379
     * case enable reuse unless explicitely disabled.
380
     */
381
    if (s->reuse_socket || (s->is_multicast && !reuse_specified)) {
382
        s->reuse_socket = 1;
383
        if (setsockopt (udp_fd, SOL_SOCKET, SO_REUSEADDR, &(s->reuse_socket), sizeof(s->reuse_socket)) != 0)
384
            goto fail;
385
    }
386

    
387
    /* the bind is needed to give a port to the socket now */
388
    /* if multicast, try the multicast address bind first */
389
    if (s->is_multicast && !(h->flags & URL_WRONLY)) {
390
        bind_ret = bind(udp_fd,(struct sockaddr *)&s->dest_addr, len);
391
    }
392
    /* bind to the local address if not multicast or if the multicast
393
     * bind failed */
394
    if (bind_ret < 0 && bind(udp_fd,(struct sockaddr *)&my_addr, len) < 0)
395
        goto fail;
396

    
397
    len = sizeof(my_addr);
398
    getsockname(udp_fd, (struct sockaddr *)&my_addr, &len);
399
    s->local_port = udp_port(&my_addr, len);
400

    
401
    if (s->is_multicast) {
402
        if (h->flags & URL_WRONLY) {
403
            /* output */
404
            if (udp_set_multicast_ttl(udp_fd, s->ttl, (struct sockaddr *)&s->dest_addr) < 0)
405
                goto fail;
406
        } else {
407
            /* input */
408
            if (udp_join_multicast_group(udp_fd, (struct sockaddr *)&s->dest_addr) < 0)
409
                goto fail;
410
        }
411
    }
412

    
413
    if (is_output) {
414
        /* limit the tx buf size to limit latency */
415
        tmp = s->buffer_size;
416
        if (setsockopt(udp_fd, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp)) < 0) {
417
            av_log(NULL, AV_LOG_ERROR, "setsockopt(SO_SNDBUF): %s\n", strerror(errno));
418
            goto fail;
419
        }
420
    } else {
421
        /* set udp recv buffer size to the largest possible udp packet size to
422
         * avoid losing data on OSes that set this too low by default. */
423
        tmp = s->buffer_size;
424
        if (setsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &tmp, sizeof(tmp)) < 0) {
425
            av_log(NULL, AV_LOG_WARNING, "setsockopt(SO_RECVBUF): %s\n", strerror(errno));
426
        }
427
        /* make the socket non-blocking */
428
        ff_socket_nonblock(udp_fd, 1);
429
    }
430
    if (s->is_connected) {
431
        if (connect(udp_fd, (struct sockaddr *) &s->dest_addr, s->dest_addr_len)) {
432
            av_log(NULL, AV_LOG_ERROR, "connect: %s\n", strerror(errno));
433
            goto fail;
434
        }
435
    }
436

    
437
    s->udp_fd = udp_fd;
438
    return 0;
439
 fail:
440
    if (udp_fd >= 0)
441
        closesocket(udp_fd);
442
    av_free(s);
443
    return AVERROR(EIO);
444
}
445

    
446
static int udp_read(URLContext *h, uint8_t *buf, int size)
447
{
448
    UDPContext *s = h->priv_data;
449
    struct pollfd p = {s->udp_fd, POLLIN, 0};
450
    int len;
451
    int ret;
452

    
453
    for(;;) {
454
        if (url_interrupt_cb())
455
            return AVERROR(EINTR);
456
        ret = poll(&p, 1, 100);
457
        if (ret < 0) {
458
            if (ff_neterrno() == AVERROR(EINTR))
459
                continue;
460
            return AVERROR(EIO);
461
        }
462
        if (!(ret == 1 && p.revents & POLLIN))
463
            continue;
464
        len = recv(s->udp_fd, buf, size, 0);
465
        if (len < 0) {
466
            if (ff_neterrno() != AVERROR(EAGAIN) &&
467
                ff_neterrno() != AVERROR(EINTR))
468
                return AVERROR(EIO);
469
        } else {
470
            break;
471
        }
472
    }
473
    return len;
474
}
475

    
476
static int udp_write(URLContext *h, const uint8_t *buf, int size)
477
{
478
    UDPContext *s = h->priv_data;
479
    int ret;
480

    
481
    for(;;) {
482
        if (!s->is_connected) {
483
            ret = sendto (s->udp_fd, buf, size, 0,
484
                          (struct sockaddr *) &s->dest_addr,
485
                          s->dest_addr_len);
486
        } else
487
            ret = send(s->udp_fd, buf, size, 0);
488
        if (ret < 0) {
489
            if (ff_neterrno() != AVERROR(EINTR) &&
490
                ff_neterrno() != AVERROR(EAGAIN))
491
                return ff_neterrno();
492
        } else {
493
            break;
494
        }
495
    }
496
    return size;
497
}
498

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

    
503
    if (s->is_multicast && !(h->flags & URL_WRONLY))
504
        udp_leave_multicast_group(s->udp_fd, (struct sockaddr *)&s->dest_addr);
505
    closesocket(s->udp_fd);
506
    av_free(s);
507
    return 0;
508
}
509

    
510
URLProtocol ff_udp_protocol = {
511
    "udp",
512
    udp_open,
513
    udp_read,
514
    udp_write,
515
    NULL, /* seek */
516
    udp_close,
517
    .url_get_file_handle = udp_get_file_handle,
518
};