Statistics
| Branch: | Revision:

ffmpeg / libavformat / udp.c @ 4ec153bb

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 Libav.
6
 *
7
 * Libav 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
 * Libav 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 Libav; 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 "avio_internal.h"
31
#include "libavutil/parseutils.h"
32
#include <unistd.h>
33
#include "internal.h"
34
#include "network.h"
35
#include "os_support.h"
36
#if HAVE_POLL_H
37
#include <poll.h>
38
#endif
39
#include <sys/time.h>
40

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

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

    
58
#define UDP_TX_BUF_SIZE 32768
59
#define UDP_MAX_PKT_SIZE 65536
60

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

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

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

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

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

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

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

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

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

    
165
    return res;
166
}
167

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

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

    
180
    return addr_len;
181
}
182

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

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

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

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

    
207
    freeaddrinfo(res0);
208

    
209
    return udp_fd;
210

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

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

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

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

    
231

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

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

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

    
278
    return 0;
279
}
280

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

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

    
306
/* put it in UDP context */
307
/* return non zero if error */
308
static int udp_open(URLContext *h, const char *uri, int flags)
309
{
310
    char hostname[1024];
311
    int port, udp_fd = -1, tmp, bind_ret = -1;
312
    UDPContext *s = NULL;
313
    int is_output;
314
    const char *p;
315
    char buf[256];
316
    struct sockaddr_storage my_addr;
317
    int len;
318
    int reuse_specified = 0;
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
        if (av_find_info_tag(buf, sizeof(buf), "reuse", p)) {
336
            const char *endptr=NULL;
337
            s->reuse_socket = strtol(buf, &endptr, 10);
338
            /* assume if no digits were found it is a request to enable it */
339
            if (buf == endptr)
340
                s->reuse_socket = 1;
341
            reuse_specified = 1;
342
        }
343
        if (av_find_info_tag(buf, sizeof(buf), "ttl", p)) {
344
            s->ttl = strtol(buf, NULL, 10);
345
        }
346
        if (av_find_info_tag(buf, sizeof(buf), "localport", p)) {
347
            s->local_port = strtol(buf, NULL, 10);
348
        }
349
        if (av_find_info_tag(buf, sizeof(buf), "pkt_size", p)) {
350
            h->max_packet_size = strtol(buf, NULL, 10);
351
        }
352
        if (av_find_info_tag(buf, sizeof(buf), "buffer_size", p)) {
353
            s->buffer_size = strtol(buf, NULL, 10);
354
        }
355
        if (av_find_info_tag(buf, sizeof(buf), "connect", p)) {
356
            s->is_connected = strtol(buf, NULL, 10);
357
        }
358
    }
359

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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