Statistics
| Branch: | Revision:

ffmpeg / libavformat / udp.c @ ebba2b3e

History | View | Annotate | Download (14.9 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
#include <sys/time.h>
37

    
38
#ifndef IPV6_ADD_MEMBERSHIP
39
#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
40
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
41
#endif
42

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

    
55
#define UDP_TX_BUF_SIZE 32768
56
#define UDP_MAX_PKT_SIZE 65536
57

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

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

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

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

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

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

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

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

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

    
162
    return res;
163
}
164

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

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

    
177
    return addr_len;
178
}
179

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

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

    
198
    if (udp_fd < 0)
199
        goto fail;
200

    
201
    memcpy(addr, res->ai_addr, res->ai_addrlen);
202
    *addr_len = res->ai_addrlen;
203

    
204
    freeaddrinfo(res0);
205

    
206
    return udp_fd;
207

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

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

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

    
225
    return strtol(sbuf, NULL, 10);
226
}
227

    
228

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

    
251
    av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port, NULL, 0, uri);
252

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

    
275
    return 0;
276
}
277

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

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

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

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

    
320
    is_output = (flags & URL_WRONLY);
321

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

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

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

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

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

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

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

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

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

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

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

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

    
444
static int udp_read(URLContext *h, uint8_t *buf, int size)
445
{
446
    UDPContext *s = h->priv_data;
447
    int ret;
448

    
449
    if (!(h->flags & URL_FLAG_NONBLOCK)) {
450
        ret = ff_network_wait_fd(s->udp_fd, 0);
451
        if (ret < 0)
452
            return ret;
453
    }
454
    ret = recv(s->udp_fd, buf, size, 0);
455
    return ret < 0 ? ff_neterrno() : ret;
456
}
457

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

    
463
    if (!(h->flags & URL_FLAG_NONBLOCK)) {
464
        ret = ff_network_wait_fd(s->udp_fd, 1);
465
        if (ret < 0)
466
            return ret;
467
    }
468

    
469
    if (!s->is_connected) {
470
        ret = sendto (s->udp_fd, buf, size, 0,
471
                      (struct sockaddr *) &s->dest_addr,
472
                      s->dest_addr_len);
473
    } else
474
        ret = send(s->udp_fd, buf, size, 0);
475

    
476
    return ret < 0 ? ff_neterrno() : ret;
477
}
478

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

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

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