Statistics
| Branch: | Revision:

ffmpeg / libavformat / udp.c @ 9087a46d

History | View | Annotate | Download (15.3 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_POLL_H
35
#include <poll.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

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

    
56
#define UDP_TX_BUF_SIZE 32768
57
#define UDP_MAX_PKT_SIZE 65536
58

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

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

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

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

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

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

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

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

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

    
163
    return res;
164
}
165

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

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

    
178
    return addr_len;
179
}
180

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

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

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

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

    
205
    freeaddrinfo(res0);
206

    
207
    return udp_fd;
208

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

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

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

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

    
229

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

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

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

    
276
    return 0;
277
}
278

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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