aggregartp.c 16.8 KB
Newer Older
1 2 3
/*****************************************************************************
 * aggregartp.c: split an RTP stream for several contribution links
 *****************************************************************************
4
 * Copyright (C) 2009, 2011, 2014-2017 VideoLAN
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * Authors: Christophe Massiot <massiot@via.ecp.fr>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (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
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU 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
/* POLLRDHUP */
#define _GNU_SOURCE 1

26 27 28 29 30 31 32 33 34 35 36
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
37
#include <poll.h>
38
#include <syslog.h>
39 40

#include <bitstream/ietf/rtp.h>
41 42 43

#include "util.h"

44
#define DEFAULT_RETX_BUFFER 500 /* ms */
45 46 47 48

/*****************************************************************************
 * Local declarations
 *****************************************************************************/
49 50 51 52 53 54 55 56
typedef struct block_t
{
    uint8_t *p_data;
    unsigned int i_size;
    uint64_t i_date;
    struct block_t *p_next;
} block_t;

57 58 59 60 61 62 63 64
typedef struct output_t
{
    int i_fd;
    unsigned int i_weight;

    unsigned int i_weighted_size, i_remainder;
} output_t;

65 66 67
static size_t i_asked_payload_size = DEFAULT_PAYLOAD_SIZE;
static size_t i_rtp_header_size = RTP_HEADER_SIZE;

68
static int i_input_fd;
69 70 71 72
static bool b_input_tcp;
static block_t *p_input_block = NULL;
static output_t *p_outputs = NULL;
static int i_nb_outputs = 0;
73 74 75 76
static unsigned int i_max_weight = 0;
static bool b_overwrite_timestamps = false;
static bool b_overwrite_ssrc = false;
static in_addr_t i_ssrc = 0;
77 78 79 80 81 82 83
static uint16_t i_rtp_seqnum = 0;

static int i_retx_fd = -1;
static bool b_retx_tcp;
static block_t *p_retx_block = NULL;
static block_t *p_retx_first = NULL, *p_retx_last = NULL;
static uint64_t i_retx_buffer = DEFAULT_RETX_BUFFER * 27000;
84 85 86

static void usage(void)
{
87
    msg_Raw( NULL, "Usage: aggregartp [-i <RT priority>] [-l <syslogtag>] [-t <ttl>] [-w] [-o <SSRC IP>] [-U] [-x <retx buffer>] [-X <retx URL>] [-m <payload size>] [-R <RTP header>] @<src host> <dest host 1>[,<weight 1>] ... [<dest host N>,<weight N>]" );
88
    msg_Raw( NULL, "    host format: [<connect addr>[:<connect port>]][@[<bind addr][:<bind port>]]" );
89
    msg_Raw( NULL, "    weight: integer, higher value means more capacity, or 0 for all packets" );
90
    msg_Raw( NULL, "    -w: overwrite RTP timestamps" );
Rémi Duraffort's avatar
Rémi Duraffort committed
91
    msg_Raw( NULL, "    -o: overwrite RTP SSRC" );
92
    msg_Raw( NULL, "    -U: prepend RTP header" );
93 94 95 96
    msg_Raw( NULL, "    -x: length of the buffer for retransmission requests in ms [default 500]" );
    msg_Raw( NULL, "    -X: retransmission service @host:port[/tcp]" );
    msg_Raw( NULL, "    -m: size of the payload chunk, excluding optional RTP header (default 1316)" );
    msg_Raw( NULL, "    -R: size of the optional RTP header (default 12)" );
97 98 99 100 101 102 103 104 105 106 107
    exit(EXIT_FAILURE);
}

/*****************************************************************************
 * NextOutput: pick the output for the next packet
 *****************************************************************************/
static output_t *NextOutput(void)
{
    unsigned int i_min_size = p_outputs[0].i_weighted_size;
    int i, i_output = 0;

108
    for ( i = 1; i < i_nb_outputs && p_outputs[i].i_weight; i++ )
109 110 111 112 113 114 115 116
    {
        if ( p_outputs[i].i_weighted_size < i_min_size )
        {
            i_min_size = p_outputs[i].i_weighted_size;
            i_output = i;
        }
    }

117
    for ( i = 0; i < i_nb_outputs && p_outputs[i].i_weight; i++ )
118 119 120 121 122
        p_outputs[i].i_weighted_size -= i_min_size;

    return &p_outputs[i_output];
}

123 124 125
/*****************************************************************************
 * SendBlock: send a block to a file descriptor
 *****************************************************************************/
126
static void SendBlock( int i_fd, struct sockaddr *p_sout,
127 128
                       socklen_t i_len, block_t *p_block )
{
129 130
    if ( sendto( i_fd, p_block->p_data, p_block->i_size, 0, p_sout, i_len )
          < 0 )
131 132 133 134 135 136 137 138 139 140 141 142
    {
        if ( errno == EBADF || errno == ECONNRESET || errno == EPIPE )
        {
            msg_Err( NULL, "write error (%s)", strerror(errno) );
            exit(EXIT_FAILURE);
        }
        else
            /* otherwise do not die because these errors can be transient */
            msg_Warn( NULL, "write error (%s)", strerror(errno) );
    }
}

143 144 145 146 147 148 149 150 151 152 153
/*****************************************************************************
 * SendBlock0: send a block to all outputs with weight 0
 *****************************************************************************/
static void SendBlock0( block_t *p_block )
{
    int i;
    for ( i = 0; i < i_nb_outputs; i++ )
        if ( !p_outputs[i].i_weight )
            SendBlock( p_outputs[i].i_fd, NULL, 0, p_block);
}

154 155 156 157 158 159
/*****************************************************************************
 * RetxQueue: store a packet in the retx queue
 *****************************************************************************/
static void RetxQueue( block_t *p_block, uint64_t i_current_date )
{
    p_block->i_date = i_current_date;
160
    p_block->p_next = NULL;
161
    rtp_set_marker( p_block->p_data );
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

    /* Queue block */
    if ( p_retx_last != NULL )
    {
        p_retx_last->p_next = p_block;
        p_retx_last = p_block;
    }
    else
        p_retx_last = p_retx_first = p_block;

    /* Purge old blocks */
    while ( p_retx_first != NULL &&
            p_retx_first->i_date < i_current_date - i_retx_buffer )
    {
        block_t *p_next = p_retx_first->p_next;
        free(p_retx_first);
        p_retx_first = p_next;
    }
    if ( p_retx_first == NULL )
        p_retx_last = NULL;
}

/*****************************************************************************
 * RetxHandle: handle a retx query
 *****************************************************************************/
187
static void RetxHandle( int i_fd )
188 189 190
{
    ssize_t i_size = RETX_HEADER_SIZE - p_retx_block->i_size;
    uint8_t *p_buffer = p_retx_block->p_data + p_retx_block->i_size;
191
    sockaddr_t sout;
192 193
    socklen_t i_len = sizeof(sout);

194
    i_size = recvfrom( i_fd, p_buffer, i_size, 0, &sout.so, &i_len );
195 196
    if ( i_size < 0 && errno != EAGAIN && errno != EINTR &&
         errno != ECONNREFUSED )
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
    {
        msg_Err( NULL, "unrecoverable read error, dying (%s)",
                 strerror(errno) );
        exit(EXIT_FAILURE);
    }
    if ( i_size <= 0 ) return;

    p_retx_block->i_size += i_size;

    if ( p_retx_block->i_size != RETX_HEADER_SIZE )
    {
        if ( b_retx_tcp ) return;
        msg_Err( NULL, "invalid retx packet received, dying" );
        exit(EXIT_FAILURE);
    }

    if ( !retx_check(p_retx_block->p_data) )
    {
        msg_Err( NULL, "invalid retx packet, dying" );
        exit(EXIT_FAILURE);
    }

    uint16_t i_seqnum = retx_get_seqnum(p_retx_block->p_data);
    uint16_t i_num = retx_get_num(p_retx_block->p_data);
    block_t *p_block = p_retx_first;
    p_retx_block->i_size = 0;

    while ( p_block != NULL )
    {
        if ( rtp_get_seqnum(p_block->p_data) == i_seqnum )
            break;
        p_block = p_block->p_next;
    }

    if ( p_block == NULL )
    {
        msg_Warn( NULL, "unable to find packet %hu for retx", i_seqnum );
        return;
    }

    while ( i_num && p_block != NULL )
    {
239 240 241 242 243 244 245 246 247
        if ( i_retx_fd == -1 )
        {
            output_t *p_output = NextOutput();
            SendBlock( p_output->i_fd, NULL, 0, p_block );
        }
        else
        {
            SendBlock( i_retx_fd, i_len ? &sout.so : NULL, i_len, p_block );
        }
248 249 250 251 252 253 254 255 256
        p_block = p_block->p_next;
        i_num--;
    }

    if ( i_num )
        msg_Warn( NULL, "unable to find %hu packets after %hu", i_num,
                  i_seqnum );
}

257 258 259 260 261
/*****************************************************************************
 * Entry point
 *****************************************************************************/
int main( int i_argc, char **pp_argv )
{
262
    int c;
263
    int i_priority = -1;
264
    const char *psz_syslog_tag = NULL;
265 266
    int i_ttl = 0;
    bool b_udp = false;
267 268 269 270 271 272 273 274
    struct pollfd *pfd = malloc(sizeof(struct pollfd));
    int i_nb_retx = 1;
    int i_fd;

#define ADD_RETX                                                            \
    pfd = realloc( pfd, ++i_nb_retx * sizeof(struct pollfd) );              \
    pfd[i_nb_retx - 1].fd = i_fd;                                           \
    pfd[i_nb_retx - 1].events = POLLIN;
275

276
    while ( (c = getopt( i_argc, pp_argv, "i:l:t:wo:x:X:Um:R:h" )) != -1 )
277 278 279 280 281 282 283
    {
        switch ( c )
        {
        case 'i':
            i_priority = strtol( optarg, NULL, 0 );
            break;

284 285 286 287
        case 'l':
            psz_syslog_tag = optarg;
            break;

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        case 't':
            i_ttl = strtol( optarg, NULL, 0 );
            break;

        case 'w':
            b_overwrite_timestamps = true;
            break;

        case 'o':
        {
            struct in_addr maddr;
            if ( !inet_aton( optarg, &maddr ) )
                usage();
            i_ssrc = maddr.s_addr;
            b_overwrite_ssrc = true;
            break;
        }

306 307 308 309
        case 'x':
            i_retx_buffer = strtoll( optarg, NULL, 0 ) * 27000;
            break;

310
        case 'X':
311 312
            i_retx_fd = i_fd = OpenSocket( optarg, 0, 0, 0, NULL, &b_retx_tcp, NULL );
            if ( i_fd == -1 )
313 314 315 316 317
            {
                msg_Err( NULL, "unable to set up retx with %s\n", optarg );
                exit(EXIT_FAILURE);
            }

318
            ADD_RETX
319 320
            break;

321 322 323 324 325
        case 'U':
            b_udp = true;
            break;

        case 'm':
326 327 328 329 330
            i_asked_payload_size = strtol( optarg, NULL, 0 );
            break;

        case 'R':
            i_rtp_header_size = strtol( optarg, NULL, 0 );
331 332 333 334 335 336 337 338 339 340 341
            break;

        case 'h':
        default:
            usage();
            break;
        }
    }
    if ( optind >= i_argc - 1 )
        usage();

342 343 344
    if ( psz_syslog_tag != NULL )
        msg_Openlog( psz_syslog_tag, LOG_NDELAY, LOG_USER );

345
    i_input_fd = OpenSocket( pp_argv[optind], 0, DEFAULT_PORT, 0, NULL,
346
                             &b_input_tcp, NULL );
347
    if ( i_input_fd == -1 )
348
    {
349
        msg_Err( NULL, "unable to open input socket" );
350 351 352
        exit(EXIT_FAILURE);
    }

353 354 355 356 357
    optind++;
    pfd[0].fd = i_input_fd;
    pfd[0].events = POLLIN | POLLERR | POLLRDHUP | POLLHUP;

    while ( optind < i_argc )
358
    {
359 360 361 362 363
        bool b_multicast;
        struct opensocket_opt opt;
        memset(&opt, 0, sizeof(struct opensocket_opt));
        opt.pb_multicast = &b_multicast;

364
        p_outputs = realloc( p_outputs, ++i_nb_outputs * sizeof(output_t) );
365
        p_outputs[i_nb_outputs - 1].i_fd = i_fd =
366
            OpenSocket( pp_argv[optind++], i_ttl, 0, DEFAULT_PORT,
367
                        &p_outputs[i_nb_outputs - 1].i_weight, NULL, &opt );
368 369 370 371 372 373 374 375 376
        if ( p_outputs[i_nb_outputs - 1].i_fd == -1 )
        {
            msg_Err( NULL, "unable to open output socket" );
            exit(EXIT_FAILURE);
        }

        p_outputs[i_nb_outputs - 1].i_weighted_size =
            p_outputs[i_nb_outputs - 1].i_remainder = 0;
        i_max_weight += p_outputs[i_nb_outputs - 1].i_weight;
377

378
        if ( i_retx_fd == -1 && !b_multicast )
379 380 381
        {
            ADD_RETX
        }
382
    }
383
    msg_Dbg( NULL, "%d outputs weight %u%s", i_nb_outputs, i_max_weight,
384
             i_nb_retx > 1 ? ", with retx" : "" );
385

386 387 388 389
    p_retx_block = malloc( sizeof(block_t) + RETX_HEADER_SIZE );
    p_retx_block->p_data = (uint8_t *)p_retx_block + sizeof(block_t);
    p_retx_block->i_size = 0;

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    if ( i_priority > 0 )
    {
        struct sched_param param;
        int i_error;

        memset( &param, 0, sizeof(struct sched_param) );
        param.sched_priority = i_priority;
        if ( (i_error = pthread_setschedparam( pthread_self(), SCHED_RR,
                                               &param )) )
        {
            msg_Warn( NULL, "couldn't set thread priority: %s",
                      strerror(i_error) );
        }
    }

    for ( ; ; )
    {
407
        uint64_t i_current_date;
408
        if ( poll( pfd, i_nb_retx, -1 ) < 0 )
409
        {
410 411 412
            int saved_errno = errno;
            msg_Warn( NULL, "couldn't poll(): %s", strerror(errno) );
            if ( saved_errno == EINTR ) continue;
413 414
            exit(EXIT_FAILURE);
        }
415
        i_current_date = wall_Date();
416

417
        if ( pfd[0].revents & POLLIN )
418
        {
419 420 421
            /* Read input block */
            ssize_t i_size, i_wanted_size;
            uint8_t *p_read_buffer;
422

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
            if ( b_udp )
                i_wanted_size = i_asked_payload_size + RTP_HEADER_SIZE;
            else
                i_wanted_size = i_asked_payload_size + i_rtp_header_size;

            if ( p_input_block == NULL )
            {
                if ( b_udp )
                {
                    p_input_block = malloc( sizeof(block_t) +
                                            i_asked_payload_size +
                                            RTP_HEADER_SIZE );
                    p_input_block->i_size = RTP_HEADER_SIZE;
                }
                else
                {
                    p_input_block = malloc( sizeof(block_t) +
                                            i_asked_payload_size +
                                            i_rtp_header_size );
                    p_input_block->p_data = (uint8_t *)p_input_block +
                                            sizeof(block_t);
                    p_input_block->i_size = 0;
                }
                p_input_block->p_data = (uint8_t *)p_input_block +
                                        sizeof(block_t);
            }

            p_read_buffer = p_input_block->p_data + p_input_block->i_size;
            i_wanted_size -= p_input_block->i_size;
            i_size = read( i_input_fd, p_read_buffer, i_wanted_size );

454 455
            if ( i_size < 0 && errno != EAGAIN && errno != EINTR &&
                 errno != ECONNREFUSED )
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
            {
                msg_Err( NULL, "unrecoverable read error, dying (%s)",
                         strerror(errno) );
                exit(EXIT_FAILURE);
            }
            if ( i_size <= 0 ) continue;

            p_input_block->i_size += i_size;

            if ( b_input_tcp && i_size != i_wanted_size )
                continue;

            if ( b_udp )
            {
                rtp_set_hdr( p_input_block->p_data );
                rtp_set_type( p_input_block->p_data, RTP_TYPE_TS );
                rtp_set_seqnum( p_input_block->p_data, i_rtp_seqnum );
                i_rtp_seqnum++;
                rtp_set_ssrc( p_input_block->p_data, (uint8_t *)&i_ssrc );
                /* this isn't RFC-compliant, but we assume that at the other
                 * end, the RTP header will be stripped */
                rtp_set_timestamp( p_input_block->p_data,
                                   i_current_date / 300 );
            }
            else
            {
                if ( b_overwrite_ssrc )
                    rtp_set_ssrc( p_input_block->p_data,
                                  (uint8_t *)&i_ssrc );
                if ( b_overwrite_timestamps )
                    rtp_set_timestamp( p_input_block->p_data,
                                       i_current_date / 300 );
            }

            /* Output block */
491 492 493 494 495 496
            SendBlock0( p_input_block );

            if ( i_max_weight )
            {
                output_t *p_output = NextOutput();
                SendBlock( p_output->i_fd, NULL, 0, p_input_block );
497

498 499 500 501 502
                p_output->i_weighted_size += (i_size + p_output->i_remainder)
                                               / p_output->i_weight;
                p_output->i_remainder = (i_size + p_output->i_remainder)
                                               % p_output->i_weight;
            }
503

504
            RetxQueue( p_input_block, i_current_date );
505 506
            p_input_block = NULL;
        }
507 508 509 510 511 512
        else if ( (pfd[0].revents & (POLLERR | POLLRDHUP | POLLHUP)) )
        {
            msg_Err( NULL, "poll error\n" );
            exit(EXIT_FAILURE);
        }

513
        int i;
514
        for ( i = 1; i < i_nb_retx; i++ )
515
        {
516
            if ( pfd[i].revents & POLLIN )
517
            {
518
                RetxHandle( pfd[i].fd );
519
            }
520
        }
521 522
    }

523 524 525
    if ( psz_syslog_tag != NULL )
        msg_Closelog();

526 527
    return EXIT_SUCCESS;
}