udp.c 14 KB
Newer Older
1 2 3
/*****************************************************************************
 * udp.c
 *****************************************************************************
4
 * Copyright (C) 2001-2007 VLC authors and VideoLAN
5
 * $Id$
6 7 8 9
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
 *          Eric Petit <titer@videolan.org>
 *
10 11 12
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
13 14 15 16
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
19
 *
20 21 22
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 24 25 26 27
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
28 29 30 31
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

32
#include <vlc_common.h>
33
#include <vlc_plugin.h>
34

35
#include <sys/types.h>
36
#include <unistd.h>
37
#include <assert.h>
38
#include <errno.h>
39

Clément Stenac's avatar
Clément Stenac committed
40 41
#include <vlc_sout.h>
#include <vlc_block.h>
42

43
#ifdef _WIN32
44 45 46 47 48 49
#   include <winsock2.h>
#   include <ws2tcpip.h>
#else
#   include <sys/socket.h>
#endif

Clément Stenac's avatar
Clément Stenac committed
50
#include <vlc_network.h>
51

52
#define MAX_EMPTY_BLOCKS 200
53 54 55 56

/*****************************************************************************
 * Module descriptor
 *****************************************************************************/
57 58 59
static int  Open ( vlc_object_t * );
static void Close( vlc_object_t * );

Laurent Aimar's avatar
Laurent Aimar committed
60 61
#define SOUT_CFG_PREFIX "sout-udp-"

62
#define CACHING_TEXT N_("Caching value (ms)")
63
#define CACHING_LONGTEXT N_( \
Clément Stenac's avatar
Clément Stenac committed
64 65
    "Default caching value for outbound UDP streams. This " \
    "value should be set in milliseconds." )
66

Clément Stenac's avatar
Clément Stenac committed
67 68
#define GROUP_TEXT N_("Group packets")
#define GROUP_LONGTEXT N_("Packets can be sent one by one at the right time " \
Clément Stenac's avatar
Clément Stenac committed
69
                          "or by groups. You can choose the number " \
70 71 72
                          "of packets that will be sent at a time. It " \
                          "helps reducing the scheduling load on " \
                          "heavily-loaded systems." )
Clément Stenac's avatar
Clément Stenac committed
73

74 75 76 77 78
vlc_module_begin ()
    set_description( N_("UDP stream output") )
    set_shortname( "UDP" )
    set_category( CAT_SOUT )
    set_subcategory( SUBCAT_SOUT_ACO )
79 80
    add_integer( SOUT_CFG_PREFIX "caching", DEFAULT_PTS_DELAY / 1000, CACHING_TEXT, CACHING_LONGTEXT, true )
    add_integer( SOUT_CFG_PREFIX "group", 1, GROUP_TEXT, GROUP_LONGTEXT,
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
81
                                 true )
Laurent Aimar's avatar
Laurent Aimar committed
82

83
    set_capability( "sout access", 0 )
84 85 86
    add_shortcut( "udp" )
    set_callbacks( Open, Close )
vlc_module_end ()
87

88 89 90
/*****************************************************************************
 * Exported prototypes
 *****************************************************************************/
Laurent Aimar's avatar
Laurent Aimar committed
91

92
static const char *const ppsz_sout_options[] = {
Laurent Aimar's avatar
Laurent Aimar committed
93 94 95 96 97
    "caching",
    "group",
    NULL
};

98
/* Options handled by the libvlc network core */
99
static const char *const ppsz_core_options[] = {
100 101 102 103 104 105
    "dscp",
    "ttl",
    "miface",
    NULL
};

106
static ssize_t Write   ( sout_access_out_t *, block_t * );
107
static int Control( sout_access_out_t *, int, va_list );
108

109
static void* ThreadWrite( void * );
110 111
static block_t *NewUDPPacket( sout_access_out_t *, mtime_t );

112
struct sout_access_out_sys_t
113
{
114 115
    mtime_t       i_caching;
    int           i_handle;
116
    bool          b_mtu_warning;
117
    size_t        i_mtu;
118

119 120 121
    block_fifo_t *p_fifo;
    block_fifo_t *p_empty_blocks;
    block_t      *p_buffer;
122

123
    vlc_thread_t  thread;
124
};
125

126 127
#define DEFAULT_PORT 1234

128 129 130 131 132
/*****************************************************************************
 * Open: open the file
 *****************************************************************************/
static int Open( vlc_object_t *p_this )
{
133 134
    sout_access_out_t       *p_access = (sout_access_out_t*)p_this;
    sout_access_out_sys_t   *p_sys;
135

136
    char                *psz_dst_addr = NULL;
137
    int                 i_dst_port;
138

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
139
    int                 i_handle;
140

141
    config_ChainParse( p_access, SOUT_CFG_PREFIX,
142 143 144
                       ppsz_sout_options, p_access->p_cfg );
    config_ChainParse( p_access, "",
                       ppsz_core_options, p_access->p_cfg );
145

146 147 148 149 150 151 152 153
    if (var_Create (p_access, "dst-port", VLC_VAR_INTEGER)
     || var_Create (p_access, "src-port", VLC_VAR_INTEGER)
     || var_Create (p_access, "dst-addr", VLC_VAR_STRING)
     || var_Create (p_access, "src-addr", VLC_VAR_STRING))
    {
        return VLC_ENOMEM;
    }

154
    if( !( p_sys = malloc ( sizeof( *p_sys ) ) ) )
155
        return VLC_ENOMEM;
156
    p_access->p_sys = p_sys;
157

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
158
    i_dst_port = DEFAULT_PORT;
159
    char *psz_parser = psz_dst_addr = strdup( p_access->psz_path );
160 161 162 163 164
    if( !psz_dst_addr )
    {
        free( p_sys );
        return VLC_ENOMEM;
    }
165

166 167
    if (psz_parser[0] == '[')
        psz_parser = strchr (psz_parser, ']');
168

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
169
    psz_parser = strchr (psz_parser ? psz_parser : psz_dst_addr, ':');
170 171 172 173
    if (psz_parser != NULL)
    {
        *psz_parser++ = '\0';
        i_dst_port = atoi (psz_parser);
174
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
175

176 177
    i_handle = net_ConnectDgram( p_this, psz_dst_addr, i_dst_port, -1,
                                 IPPROTO_UDP );
178 179
    free (psz_dst_addr);

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
180
    if( i_handle == -1 )
181
    {
182
         msg_Err( p_access, "failed to create raw UDP socket" );
183
         free (p_sys);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
184
         return VLC_EGENERIC;
185
    }
186 187 188 189
    else
    {
        char addr[NI_MAXNUMERICHOST];
        int port;
190

191 192
        if (net_GetSockAddress (i_handle, addr, &port) == 0)
        {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
193
            msg_Dbg (p_access, "source: %s port %d", addr, port);
194 195 196 197 198 199
            var_SetString (p_access, "src-addr", addr);
            var_SetInteger (p_access, "src-port", port);
        }

        if (net_GetPeerAddress (i_handle, addr, &port) == 0)
        {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
200
            msg_Dbg (p_access, "destination: %s port %d", addr, port);
201 202 203 204
            var_SetString (p_access, "dst-addr", addr);
            var_SetInteger (p_access, "dst-port", port);
        }
    }
205
    shutdown( i_handle, SHUT_RD );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
206

207 208 209
    p_sys->i_caching = UINT64_C(1000)
                     * var_GetInteger( p_access, SOUT_CFG_PREFIX "caching");
    p_sys->i_handle = i_handle;
210
    p_sys->i_mtu = var_CreateGetInteger( p_this, "mtu" );
211 212 213
    p_sys->b_mtu_warning = false;
    p_sys->p_fifo = block_FifoNew();
    p_sys->p_empty_blocks = block_FifoNew();
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
214
    p_sys->p_buffer = NULL;
215

216
    if( vlc_clone( &p_sys->thread, ThreadWrite, p_access,
217
                           VLC_THREAD_PRIORITY_HIGHEST ) )
218
    {
219
        msg_Err( p_access, "cannot spawn sout access thread" );
220 221
        block_FifoRelease( p_sys->p_fifo );
        block_FifoRelease( p_sys->p_empty_blocks );
222 223
        net_Close (i_handle);
        free (p_sys);
224
        return VLC_EGENERIC;
225 226
    }

227
    p_access->pf_write = Write;
228
    p_access->pf_control = Control;
229

230 231 232 233 234 235 236 237
    return VLC_SUCCESS;
}

/*****************************************************************************
 * Close: close the target
 *****************************************************************************/
static void Close( vlc_object_t * p_this )
{
238 239
    sout_access_out_t     *p_access = (sout_access_out_t*)p_this;
    sout_access_out_sys_t *p_sys = p_access->p_sys;
240

241 242 243 244
    vlc_cancel( p_sys->thread );
    vlc_join( p_sys->thread, NULL );
    block_FifoRelease( p_sys->p_fifo );
    block_FifoRelease( p_sys->p_empty_blocks );
245

246
    if( p_sys->p_buffer ) block_Release( p_sys->p_buffer );
247

248
    net_Close( p_sys->i_handle );
249
    free( p_sys );
250 251
}

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
static int Control( sout_access_out_t *p_access, int i_query, va_list args )
{
    (void)p_access;

    switch( i_query )
    {
        case ACCESS_OUT_CONTROLS_PACE:
            *va_arg( args, bool * ) = false;
            break;

        default:
            return VLC_EGENERIC;
    }
    return VLC_SUCCESS;
}

268
/*****************************************************************************
269
 * Write: standard write on a file descriptor.
270
 *****************************************************************************/
271
static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
272
{
273
    sout_access_out_sys_t *p_sys = p_access->p_sys;
274
    int i_len = 0;
275 276 277

    while( p_buffer )
    {
278
        block_t *p_next;
279
        int i_packets = 0;
280
        mtime_t now = mdate();
281 282

        if( !p_sys->b_mtu_warning && p_buffer->i_buffer > p_sys->i_mtu )
283
        {
284 285
            msg_Warn( p_access, "packet size > MTU, you should probably "
                      "increase the MTU" );
286
            p_sys->b_mtu_warning = true;
287 288
        }

289
        /* Check if there is enough space in the buffer */
290
        if( p_sys->p_buffer &&
291
            p_sys->p_buffer->i_buffer + p_buffer->i_buffer > p_sys->i_mtu )
292
        {
293
            if( p_sys->p_buffer->i_dts + p_sys->i_caching < now )
294
            {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
295
                msg_Dbg( p_access, "late packet for UDP input (%"PRId64 ")",
296
                         now - p_sys->p_buffer->i_dts
297
                          - p_sys->i_caching );
298
            }
299
            block_FifoPut( p_sys->p_fifo, p_sys->p_buffer );
300
            p_sys->p_buffer = NULL;
301 302
        }

303
        i_len += p_buffer->i_buffer;
304
        while( p_buffer->i_buffer )
305
        {
306 307
            size_t i_payload_size = p_sys->i_mtu;
            size_t i_write = __MIN( p_buffer->i_buffer, i_payload_size );
308 309 310 311 312 313 314 315

            i_packets++;

            if( !p_sys->p_buffer )
            {
                p_sys->p_buffer = NewUDPPacket( p_access, p_buffer->i_dts );
                if( !p_sys->p_buffer ) break;
            }
316

317
            memcpy( p_sys->p_buffer->p_buffer + p_sys->p_buffer->i_buffer,
318
                    p_buffer->p_buffer, i_write );
319

320
            p_sys->p_buffer->i_buffer += i_write;
321 322
            p_buffer->p_buffer += i_write;
            p_buffer->i_buffer -= i_write;
323
            if ( p_buffer->i_flags & BLOCK_FLAG_CLOCK )
324 325 326
            {
                if ( p_sys->p_buffer->i_flags & BLOCK_FLAG_CLOCK )
                    msg_Warn( p_access, "putting two PCRs at once" );
327
                p_sys->p_buffer->i_flags |= BLOCK_FLAG_CLOCK;
328
            }
329 330 331 332

            if( p_sys->p_buffer->i_buffer == p_sys->i_mtu || i_packets > 1 )
            {
                /* Flush */
333
                if( p_sys->p_buffer->i_dts + p_sys->i_caching < now )
334
                {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
335
                    msg_Dbg( p_access, "late packet for udp input (%"PRId64 ")",
336
                             mdate() - p_sys->p_buffer->i_dts
337
                              - p_sys->i_caching );
338
                }
339
                block_FifoPut( p_sys->p_fifo, p_sys->p_buffer );
340 341
                p_sys->p_buffer = NULL;
            }
342
        }
343

344
        p_next = p_buffer->p_next;
345
        block_Release( p_buffer );
346 347 348
        p_buffer = p_next;
    }

349
    return i_len;
350 351
}

352 353 354
/*****************************************************************************
 * NewUDPPacket: allocate a new UDP packet of size p_sys->i_mtu
 *****************************************************************************/
355
static block_t *NewUDPPacket( sout_access_out_t *p_access, mtime_t i_dts)
356 357
{
    sout_access_out_sys_t *p_sys = p_access->p_sys;
358
    block_t *p_buffer;
359

360
    while ( block_FifoCount( p_sys->p_empty_blocks ) > MAX_EMPTY_BLOCKS )
361
    {
362
        p_buffer = block_FifoGet( p_sys->p_empty_blocks );
363 364
        block_Release( p_buffer );
    }
365

366
    if( block_FifoCount( p_sys->p_empty_blocks ) == 0 )
367
    {
368
        p_buffer = block_Alloc( p_sys->i_mtu );
369 370 371
    }
    else
    {
372
        p_buffer = block_FifoGet(p_sys->p_empty_blocks );
373 374
        p_buffer->i_flags = 0;
        p_buffer = block_Realloc( p_buffer, 0, p_sys->i_mtu );
375 376
    }

377
    p_buffer->i_dts = i_dts;
378
    p_buffer->i_buffer = 0;
379 380 381 382

    return p_buffer;
}

383 384 385
/*****************************************************************************
 * ThreadWrite: Write a packet on the network at the good time.
 *****************************************************************************/
386
static void* ThreadWrite( void *data )
387
{
388 389 390 391 392 393 394
    sout_access_out_t *p_access = data;
    sout_access_out_sys_t *p_sys = p_access->p_sys;
    mtime_t i_date_last = -1;
    const unsigned i_group = var_GetInteger( p_access,
                                             SOUT_CFG_PREFIX "group" );
    mtime_t i_to_send = i_group;
    unsigned i_dropped_packets = 0;
395

396
    for (;;)
397
    {
398
        block_t *p_pk = block_FifoGet( p_sys->p_fifo );
399
        mtime_t       i_date, i_sent;
400

401
        i_date = p_sys->i_caching + p_pk->i_dts;
Laurent Aimar's avatar
Laurent Aimar committed
402
        if( i_date_last > 0 )
403
        {
Laurent Aimar's avatar
Laurent Aimar committed
404 405
            if( i_date - i_date_last > 2000000 )
            {
Gildas Bazin's avatar
Gildas Bazin committed
406
                if( !i_dropped_packets )
407
                    msg_Dbg( p_access, "mmh, hole (%"PRId64" > 2s) -> drop",
408
                             i_date - i_date_last );
Laurent Aimar's avatar
Laurent Aimar committed
409

410
                block_FifoPut( p_sys->p_empty_blocks, p_pk );
Laurent Aimar's avatar
Laurent Aimar committed
411 412

                i_date_last = i_date;
Gildas Bazin's avatar
Gildas Bazin committed
413
                i_dropped_packets++;
Laurent Aimar's avatar
Laurent Aimar committed
414 415
                continue;
            }
416
            else if( i_date - i_date_last < -1000 )
417
            {
418
                if( !i_dropped_packets )
419
                    msg_Dbg( p_access, "mmh, packets in the past (%"PRId64")",
420
                             i_date_last - i_date );
421
            }
422 423
        }

424
        block_cleanup_push( p_pk );
425
        i_to_send--;
426
        if( !i_to_send || (p_pk->i_flags & BLOCK_FLAG_CLOCK) )
427 428
        {
            mwait( i_date );
429
            i_to_send = i_group;
430
        }
431
        if ( send( p_sys->i_handle, p_pk->p_buffer, p_pk->i_buffer, 0 ) == -1 )
432
            msg_Warn( p_access, "send error: %s", vlc_strerror_c(errno) );
433
        vlc_cleanup_pop();
434

Gildas Bazin's avatar
Gildas Bazin committed
435 436
        if( i_dropped_packets )
        {
437
            msg_Dbg( p_access, "dropped %i packets", i_dropped_packets );
Gildas Bazin's avatar
Gildas Bazin committed
438 439 440
            i_dropped_packets = 0;
        }

441
#if 1
442 443 444
        i_sent = mdate();
        if ( i_sent > i_date + 20000 )
        {
445
            msg_Dbg( p_access, "packet has been sent too late (%"PRId64 ")",
446 447
                     i_sent - i_date );
        }
Gildas Bazin's avatar
Gildas Bazin committed
448 449
#endif

450
        block_FifoPut( p_sys->p_empty_blocks, p_pk );
451

Laurent Aimar's avatar
Laurent Aimar committed
452
        i_date_last = i_date;
453
    }
454
    return NULL;
455
}