satip.c 23.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*****************************************************************************
 * satip.c: SAT>IP input module
 *****************************************************************************
 * Copyright © 2016 VLC authors and VideoLAN
 * Copyright © 2016 jusst technologies GmbH
 * Copyright © 2016 Videolabs SAS
 * Copyright © 2016 Julian Scheel
 *
 * Authors: Julian Scheel <julian@jusst.de>
 *
 * 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
 * (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 Lesser General Public License for more details.
 *
 * 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.
 *****************************************************************************/

#include "config.h"

#include <unistd.h>
#include <ctype.h>
30 31 32
#ifdef HAVE_SYS_UIO_H
# include <sys/uio.h>
#endif
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

#include <vlc_common.h>
#include <vlc_plugin.h>
#include <vlc_access.h>
#include <vlc_network.h>
#include <vlc_block.h>
#include <vlc_rand.h>
#include <vlc_url.h>
#include <vlc_interrupt.h>

#ifdef HAVE_POLL
#include <poll.h>
#endif
#include <fcntl.h>
#include <errno.h>
#include <assert.h>

#define RTSP_DEFAULT_PORT 554
#define RTSP_RECEIVE_BUFFER 2048
#define RTP_HEADER_SIZE 12
#define VLEN 100
#define KEEPALIVE_INTERVAL 60
#define KEEPALIVE_MARGIN 5

57 58
static int satip_open(vlc_object_t *);
static void satip_close(vlc_object_t *);
59 60 61 62 63 64 65

#define BUFFER_TEXT N_("Receive buffer")
#define BUFFER_LONGTEXT N_("UDP receive buffer size (bytes)")

#define MULTICAST_TEXT N_("Request multicast stream")
#define MULTICAST_LONGTEXT N_("Request server to send stream as multicast")

66 67
#define SATIP_HOST_TEXT N_("Host")

68 69 70 71 72 73 74 75 76
vlc_module_begin()
    set_shortname("satip")
    set_description( N_("SAT>IP Receiver Plugin") )
    set_capability("access", 201)
    set_callbacks(satip_open, satip_close)
    set_category(CAT_INPUT)
    set_subcategory(SUBCAT_INPUT_ACCESS)
    add_integer("satip-buffer", 0x400000, BUFFER_TEXT, BUFFER_LONGTEXT, true)
    add_bool("satip-multicast", false, MULTICAST_TEXT, MULTICAST_LONGTEXT, true)
77 78 79
    add_string("satip-host", "", SATIP_HOST_TEXT, SATIP_HOST_TEXT, true)
    change_safe()
    add_shortcut("rtsp", "satip")
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
vlc_module_end()

enum rtsp_state {
    RTSP_IDLE,
    RTSP_DESCRIBE,
    RTSP_SETUP,
    RTSP_PLAY,
    RTSP_RUNNING
};

enum rtsp_result {
    RTSP_RESULT_OK = 200,
};

#define UDP_ADDRESS_LEN 16
95
struct access_sys_t {
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    char *content_base;
    char *control;
    char session_id[64];
    uint16_t stream_id;
    int keepalive_interval;

    char udp_address[UDP_ADDRESS_LEN];
    uint16_t udp_port;

    int tcp_sock;
    int udp_sock;
    int rtcp_sock;

    enum rtsp_state state;
    int cseq;

    size_t fifo_size;
    block_fifo_t *fifo;
    vlc_thread_t thread;
    uint16_t last_seq_nr;

    bool woken;
118
};
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150

static void parse_session(char *request_line, char *session, unsigned max, int *timeout) {
    char *state;
    char *tok;

    tok = strtok_r(request_line, ";", &state);
    if (tok == NULL)
        return;
    strncpy(session, tok, __MIN(strlen(tok), max - 1));

    while ((tok = strtok_r(NULL, ";", &state)) != NULL) {
        if (strncmp(tok, "timeout=", 8) == 0) {
            *timeout = atoi(tok + 8);
            if (*timeout > 5)
                *timeout -= KEEPALIVE_MARGIN;
            else if (*timeout > 0)
                *timeout = 1;
        }
    }
}

static int parse_port(char *str, uint16_t *port)
{
    int p = atoi(str);
    if (p < 0 || p > UINT16_MAX)
        return VLC_EBADVAR;

    *port = p;

    return 0;
}

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
151
static int parse_transport(stream_t *access, char *request_line) {
152 153 154 155 156 157 158 159 160 161 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 187 188 189 190 191 192 193 194 195 196 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
    access_sys_t *sys = access->p_sys;
    char *state;
    char *tok;
    int err;

    tok = strtok_r(request_line, ";", &state);
    if (tok == NULL || strncmp(tok, "RTP/AVP", 7) != 0)
        return VLC_EGENERIC;

    tok = strtok_r(NULL, ";", &state);
    if (tok == NULL || strncmp(tok, "multicast", 9) != 0)
        return 0;

    while ((tok = strtok_r(NULL, ";", &state)) != NULL) {
        if (strncmp(tok, "destination=", 12) == 0) {
            strncpy(sys->udp_address, tok + 12, __MIN(strlen(tok + 12), UDP_ADDRESS_LEN - 1));
        } else if (strncmp(tok, "port=", 5) == 0) {
            char port[6];
            char *end;

            memset(port, 0x00, 6);
            strncpy(port, tok + 5, __MIN(strlen(tok + 5), 5));
            if ((end = strstr(port, "-")) != NULL)
                *end = '\0';
            err = parse_port(port, &sys->udp_port);
            if (err)
                return err;
        }
    }

    return 0;
}

/*
 * Semi-interruptible net_Gets replacement.
 * If an interruption is occuring it will fallback to non-interruptible read
 * with a given timeout before it returns.
 *
 * interrupted: Informs the caller whether an interrupt occured or not
 */
static char *net_readln_timeout(vlc_object_t *obj, int fd, int timeout, bool *interrupted)
{
    char *buf = NULL;
    size_t size = 0, len = 0;
    bool intr = false;

    for (;;)
    {
        if (len == size)
        {
            if (unlikely(size >= (1 << 16)))
            {
                errno = EMSGSIZE;
                goto error; /* put sane buffer size limit */
            }

            char *newbuf = realloc(buf, size + 1024);
            if (unlikely(newbuf == NULL))
                goto error;
            buf = newbuf;
            size += 1024;
        }
        assert(len < size);

        ssize_t val = 0;
        if (!intr) {
            val = vlc_recv_i11e(fd, buf + len, size - len, MSG_PEEK);
            if (val <= 0 && errno == EINTR) {
                intr = true;
                if (interrupted)
                    *interrupted = true;
                continue;
            }
            if (val <= 0)
                goto error;
        } else {
            struct pollfd pfd = {
                .fd = fd,
                .events = POLLIN,
            };
            int ret;

234 235
            while((ret = poll(&pfd, 1, timeout)) < 0)
                ;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

            val = recv(fd, buf + len, size - len, MSG_PEEK);
            if (val <= 0)
                goto error;
        }

        char *end = memchr(buf + len, '\n', val);
        if (end != NULL)
            val = (end + 1) - (buf + len);
        if (recv(fd, buf + len, val, 0) != val)
            goto error;
        len += val;
        if (end != NULL)
            break;
    }

    assert(len > 0);
    buf[--len] = '\0';
    if (len > 0 && buf[--len] == '\r')
        buf[len] = '\0';
    return buf;
error:
    msg_Err(obj, "read error: %s", vlc_strerror_c(errno));
    free(buf);
    return NULL;
}

#define skip_whitespace(x) while(*x == ' ') x++
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
264
static enum rtsp_result rtsp_handle(stream_t *access, bool *interrupted) {
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
    access_sys_t *sys = access->p_sys;
    uint8_t buffer[512];
    int rtsp_result = 0;
    bool have_header = false;
    size_t content_length = 0;
    size_t read = 0;
    char *in, *val;

    /* Parse header */
    while (!have_header) {
        in = net_readln_timeout((vlc_object_t*)access, sys->tcp_sock, 5000,
                interrupted);
        if (in == NULL)
            break;

        if (strncmp(in, "RTSP/1.0 ", 9) == 0) {
            rtsp_result = atoi(in + 9);
        } else if (strncmp(in, "Content-Base:", 13) == 0) {
            free(sys->content_base);

            val = in + 13;
            skip_whitespace(val);

            sys->content_base = strdup(val);
        } else if (strncmp(in, "Content-Length:", 15) == 0) {
            val = in + 16;
            skip_whitespace(val);

            content_length = atoi(val);
        } else if (strncmp("Session:", in, 8) == 0) {
            val = in + 8;
            skip_whitespace(val);

            parse_session(val, sys->session_id, 64, &sys->keepalive_interval);
        } else if (strncmp("Transport:", in, 10) == 0) {
            val = in + 10;
            skip_whitespace(val);

            if (parse_transport(access, val) != 0) {
                rtsp_result = VLC_EGENERIC;
                break;
            }
        } else if (strncmp("com.ses.streamID:", in, 17) == 0) {
            val = in + 17;
            skip_whitespace(val);

            sys->stream_id = atoi(val);
        } else if (in[0] == '\0') {
            have_header = true;
        }

        free(in);
    }

    /* Discard further content */
    while (content_length > 0 &&
            (read = net_Read(access, sys->tcp_sock, buffer, __MIN(sizeof(buffer), content_length))))
        content_length -= read;

    return rtsp_result;
}

#ifdef HAVE_RECVMMSG
328
static void satip_cleanup_blocks(void *data)
329
{
330
    block_t **input_blocks = data;
331

332 333 334
    for (size_t i = 0; i < VLEN; i++)
        if (input_blocks[i] != NULL)
            block_Release(input_blocks[i]);
335 336 337
}
#endif

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
338
static int check_rtp_seq(stream_t *access, block_t *block)
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
{
    access_sys_t *sys = access->p_sys;
    uint16_t seq_nr = block->p_buffer[2] << 8 | block->p_buffer[3];

    if (seq_nr == sys->last_seq_nr) {
        msg_Warn(access, "Received duplicate packet (seq_nr=%"PRIu16")", seq_nr);
        return VLC_EGENERIC;
    } else if (seq_nr < (uint16_t)(sys->last_seq_nr + 1)) {
        msg_Warn(access, "Received out of order packet (seq_nr=%"PRIu16" < %"PRIu16")",
                seq_nr, sys->last_seq_nr);
        return VLC_EGENERIC;
    } else if (++sys->last_seq_nr > 1 && seq_nr > sys->last_seq_nr) {
        msg_Warn(access, "Gap in seq_nr (%"PRIu16" > %"PRIu16"), probably lost a packet",
                seq_nr, sys->last_seq_nr);
    }

    sys->last_seq_nr = seq_nr;
    return 0;
}

static void satip_teardown(void *data) {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
360
    stream_t *access = data;
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    access_sys_t *sys = access->p_sys;
    int ret;

    if (sys->tcp_sock > 0) {
        if (sys->session_id[0] > 0) {
            char discard_buf[32];
            struct pollfd pfd = {
                .fd = sys->tcp_sock,
                .events = POLLOUT,
            };
            char *msg;

            ssize_t len = asprintf(&msg, "TEARDOWN %s RTSP/1.0\r\n"
                    "CSeq: %d\r\n"
                    "Session: %s\r\n\r\n",
                    sys->control, sys->cseq++, sys->session_id);
            if (len < 0)
                return;

            /* make socket non-blocking, to avoid blocking when output buffer
             * has not enough space */
#ifndef _WIN32
            fcntl(sys->tcp_sock, F_SETFL, fcntl(sys->tcp_sock, F_GETFL) | O_NONBLOCK);
#else
            ioctlsocket(sys->tcp_sock, FIONBIO, &(unsigned long){ 1 });
#endif

            for (unsigned sent = 0; sent < len;) {
                ret = poll(&pfd, 1, 5000);
                if (ret == 0) {
                    msg_Err(access, "Timed out sending RTSP teardown\n");
                    free(msg);
                    return;
                }

                ret = send(sys->tcp_sock, msg + sent, len, MSG_NOSIGNAL);
                if (ret < 0) {
                    msg_Err(access, "Failed to send RTSP teardown: %d\n", ret);
                    free(msg);
                    return;
                }
                sent += ret;
            }
            free(msg);

            if (rtsp_handle(access, NULL) != RTSP_RESULT_OK) {
                msg_Err(access, "Failed to teardown RTSP session");
                return;
            }

            /* Some SATIP servers send a few empty extra bytes after TEARDOWN.
             * Try to read them, to avoid a TCP socket reset */
            while ((len = recv(sys->tcp_sock, discard_buf, sizeof(discard_buf), 0) > 0));

            /* Extra sleep for compatibility with some satip servers, that
             * can't handle new sessions right after teardown */
            msleep(150000);
        }
    }
}

#define RECV_TIMEOUT 2 * 1000 * 1000
static void *satip_thread(void *data) {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
424
    stream_t *access = data;
425 426
    access_sys_t *sys = access->p_sys;
    int sock = sys->udp_sock;
427
    mtime_t last_recv = mdate();
428 429 430 431 432
    ssize_t len;
    mtime_t next_keepalive = mdate() + sys->keepalive_interval * 1000 * 1000;
#ifdef HAVE_RECVMMSG
    struct mmsghdr msgs[VLEN];
    struct iovec iovecs[VLEN];
433 434 435 436 437 438 439
    block_t *input_blocks[VLEN];
    int retval;

    for (size_t i = 0; i < VLEN; i++) {
        memset(&msgs[i], 0, sizeof (msgs[i]));
        msgs[i].msg_hdr.msg_iov = &iovecs[i];
        msgs[i].msg_hdr.msg_iovlen = 1;
440
        iovecs[i].iov_base = NULL;
441 442 443 444 445 446 447 448
        iovecs[i].iov_len = RTSP_RECEIVE_BUFFER;
        input_blocks[i] = NULL;
    }
#else
    struct pollfd ufd;

    ufd.fd = sock;
    ufd.events = POLLIN;
449 450 451 452
#endif

    while (last_recv > mdate() - RECV_TIMEOUT) {
#ifdef HAVE_RECVMMSG
453 454 455 456 457 458 459
        for (size_t i = 0; i < VLEN; i++) {
            if (input_blocks[i] != NULL)
                continue;

            input_blocks[i] = block_Alloc(RTSP_RECEIVE_BUFFER);
            if (unlikely(input_blocks[i] == NULL))
                break;
460

461
            iovecs[i].iov_base = input_blocks[i]->p_buffer;
462
        }
463 464

        vlc_cleanup_push(satip_cleanup_blocks, input_blocks);
465
        retval = recvmmsg(sock, msgs, VLEN, MSG_WAITFORONE, NULL);
466
        vlc_cleanup_pop();
467 468 469 470
        if (retval == -1)
            continue;

        last_recv = mdate();
Thomas Guillem's avatar
Thomas Guillem committed
471
        for (int i = 0; i < retval; ++i) {
472 473
            block_t *block = input_blocks[i];

474 475 476 477 478 479 480
            len = msgs[i].msg_len;
            if (check_rtp_seq(access, block))
                continue;

            block->p_buffer += RTP_HEADER_SIZE;
            block->i_buffer = len - RTP_HEADER_SIZE;
            block_FifoPut(sys->fifo, block);
481
            input_blocks[i] = NULL;
482 483 484 485 486
        }
#else
        if (poll(&ufd, 1, 20) == -1)
            continue;

487
        block_t *block = block_Alloc(RTSP_RECEIVE_BUFFER);
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        if (block == NULL) {
            msg_Err(access, "Failed to allocate memory for input buffer");
            break;
        }

        block_cleanup_push(block);
        len = recv(sock, block->p_buffer, RTSP_RECEIVE_BUFFER, 0);
        vlc_cleanup_pop();

        if (len < RTP_HEADER_SIZE) {
            block_Release(block);
            continue;
        }

        if (check_rtp_seq(access, block)) {
            block_Release(block);
            continue;
        }
        last_recv = mdate();
        block->p_buffer += RTP_HEADER_SIZE;
        block->i_buffer = len - RTP_HEADER_SIZE;
        block_FifoPut(sys->fifo, block);
#endif

        if (sys->keepalive_interval > 0 && mdate() > next_keepalive) {
            net_Printf(access, sys->tcp_sock,
                    "OPTIONS %s RTSP/1.0\r\n"
                    "CSeq: %d\r\n"
                    "Session: %s\r\n\r\n",
                    sys->control, sys->cseq++, sys->session_id);
            if (rtsp_handle(access, NULL) != RTSP_RESULT_OK)
                msg_Warn(access, "Failed to keepalive RTSP session");

            next_keepalive = mdate() + sys->keepalive_interval * 1000 * 1000;
        }
    }

525 526 527
#ifdef HAVE_RECVMMSG
    satip_cleanup_blocks(input_blocks);
#endif
528 529 530 531 532 533 534 535 536
    msg_Dbg(access, "timed out waiting for data...");
    vlc_fifo_Lock(sys->fifo);
    sys->woken = true;
    vlc_fifo_Signal(sys->fifo);
    vlc_fifo_Unlock(sys->fifo);

    return NULL;
}

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
537
static block_t* satip_block(stream_t *access, bool *restrict eof) {
538 539 540 541 542 543 544 545 546 547 548 549
    access_sys_t *sys = access->p_sys;
    block_t *block;

    vlc_fifo_Lock(sys->fifo);

    while (vlc_fifo_IsEmpty(sys->fifo)) {
        if (sys->woken)
            break;
        vlc_fifo_Wait(sys->fifo);
    }

    if ((block = vlc_fifo_DequeueUnlocked(sys->fifo)) == NULL)
550
        *eof = true;
551 552 553 554 555 556
    sys->woken = false;
    vlc_fifo_Unlock(sys->fifo);

    return block;
}

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
557
static int satip_control(stream_t *access, int i_query, va_list args) {
558 559 560 561 562
    bool *pb_bool;
    int64_t *pi_64;

    switch(i_query)
    {
563 564 565
        case STREAM_CAN_CONTROL_PACE:
        case STREAM_CAN_SEEK:
        case STREAM_CAN_PAUSE:
566
            pb_bool = va_arg(args, bool *);
567 568 569
            *pb_bool = false;
            break;

570
        case STREAM_GET_PTS_DELAY:
571
            pi_64 = va_arg(args, int64_t *);
572 573 574 575 576 577 578 579 580 581 582 583 584
            *pi_64 = INT64_C(1000) * var_InheritInteger(access, "live-caching");
            break;

        default:
            return VLC_EGENERIC;

    }
    return VLC_SUCCESS;
}

/* Bind two adjacent free ports, of which the first one is even (for RTP data)
 * and the second is odd (RTCP). This is a requirement of the satip
 * specification */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
585
static int satip_bind_ports(stream_t *access)
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
{
    access_sys_t *sys = access->p_sys;
    uint8_t rnd;

    vlc_rand_bytes(&rnd, 1);
    sys->udp_port = 9000 + (rnd * 2); /* randomly chosen, even start point */
    while (sys->udp_sock < 0) {
        sys->udp_sock = net_OpenDgram(access, "0.0.0.0", sys->udp_port, NULL,
                0, IPPROTO_UDP);
        if (sys->udp_sock < 0) {
            if (sys->udp_port == 65534)
                break;

            sys->udp_port += 2;
            continue;
        }

        sys->rtcp_sock = net_OpenDgram(access, "0.0.0.0", sys->udp_port + 1, NULL,
                0, IPPROTO_UDP);
        if (sys->rtcp_sock < 0) {
            close(sys->udp_sock);
            sys->udp_port += 2;
            continue;
        }
    }

    if (sys->udp_sock < 0) {
        msg_Err(access, "Could not open two adjacent ports for RTP and RTCP data");
        return VLC_EGENERIC;
    }

    return 0;
}

620 621
static int satip_open(vlc_object_t *obj)
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
622
    stream_t *access = (stream_t *)obj;
623 624 625 626 627
    access_sys_t *sys;
    vlc_url_t url;

    bool multicast = var_InheritBool(access, "satip-multicast");

628
    access->p_sys = sys = vlc_obj_calloc(obj, 1, sizeof(*sys));
629 630 631
    if (sys == NULL)
        return VLC_ENOMEM;

632
    msg_Dbg(access, "try to open '%s'", access->psz_url);
633

634 635
    char *psz_host = var_InheritString(access, "satip-host");

636 637
    sys->udp_sock = -1;
    sys->rtcp_sock = -1;
638
    sys->tcp_sock = -1;
639 640 641 642 643

    /* convert url to lowercase, some famous m3u playlists for satip contain
     * uppercase parameters while most (all?) satip servers do only understand
     * parameters matching lowercase spelling as defined in the specification
     * */
644 645
    char *psz_lower_url = strdup(access->psz_url);
    if (psz_lower_url == NULL)
646 647 648 649
    {
        free( psz_host );
        return VLC_ENOMEM;
    }
650

651 652
    for (unsigned i = 0; i < strlen(psz_lower_url); i++)
        psz_lower_url[i] = tolower(psz_lower_url[i]);
653

654
    vlc_UrlParse(&url, psz_lower_url);
655 656
    if (url.i_port <= 0)
        url.i_port = RTSP_DEFAULT_PORT;
657
    if (psz_host == NULL && url.psz_host )
658
        psz_host = strdup(url.psz_host);
659 660
    if (psz_host == NULL )
        goto error;
661

662 663 664 665 666 667
    if (url.psz_host == NULL || url.psz_host[0] == '\0')
    {
        msg_Dbg(access, "malformed URL: %s", psz_lower_url);
        goto error;
    }

668 669
    msg_Dbg(access, "connect to host '%s'", psz_host);
    sys->tcp_sock = net_ConnectTCP(access, psz_host, url.i_port);
670 671
    if (sys->tcp_sock < 0) {
        msg_Err(access, "Failed to connect to RTSP server %s:%d",
672
                psz_host, url.i_port);
673 674 675 676
        goto error;
    }
    setsockopt (sys->tcp_sock, SOL_SOCKET, SO_KEEPALIVE, &(int){ 1 }, sizeof (int));

677
    if (asprintf(&sys->content_base, "rtsp://%s:%d/", psz_host,
678 679 680 681 682 683 684 685
             url.i_port) < 0) {
        sys->content_base = NULL;
        goto error;
    }

    sys->last_seq_nr = 0;
    sys->keepalive_interval = (KEEPALIVE_INTERVAL - KEEPALIVE_MARGIN);

686 687 688 689 690 691 692 693
    vlc_url_t setup_url = url;

    // substitute "sat.ip" if present with an the host IP that was fetched during device discovery
    if( !strncasecmp( setup_url.psz_host, "sat.ip", 6 ) ) {
        setup_url.psz_host = psz_host;
    }

    // reverse the satip protocol trick, as SAT>IP believes to be RTSP
694 695 696
    if( setup_url.psz_protocol == NULL ||
        strncasecmp( setup_url.psz_protocol, "satip", 5 ) == 0 )
    {
697 698 699 700
        setup_url.psz_protocol = (char *)"rtsp";
    }

    char *psz_setup_url = vlc_uri_compose(&setup_url);
701 702 703
    if( psz_setup_url == NULL )
        goto error;

704 705
    if (multicast) {
        net_Printf(access, sys->tcp_sock,
706
                "SETUP %s RTSP/1.0\r\n"
707 708
                "CSeq: %d\r\n"
                "Transport: RTP/AVP;multicast\r\n\r\n",
709
                psz_setup_url, sys->cseq++);
710 711
    } else {
        /* open UDP socket to acquire a free port to use */
712 713
        if (satip_bind_ports(access)) {
            free(psz_setup_url);
714
            goto error;
715
        }
716 717

        net_Printf(access, sys->tcp_sock,
718
                "SETUP %s RTSP/1.0\r\n"
719 720
                "CSeq: %d\r\n"
                "Transport: RTP/AVP;unicast;client_port=%d-%d\r\n\r\n",
721
                psz_setup_url, sys->cseq++, sys->udp_port, sys->udp_port + 1);
722
    }
723
    free(psz_setup_url);
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

    bool interrupted = false;
    if (rtsp_handle(access, &interrupted) != RTSP_RESULT_OK) {
        msg_Err(access, "Failed to setup RTSP session");
        goto error;
    }

    if (asprintf(&sys->control, "%sstream=%d", sys->content_base, sys->stream_id) < 0) {
        sys->control = NULL;
        goto error;
    }

    if (interrupted) {
        msg_Warn(access, "SETUP was interrupted, abort startup");
        goto error;
    }

    /* Extra sleep for compatibility with some satip servers, that
     * can't handle PLAY right after SETUP */
    if (vlc_msleep_i11e(50000) < 0)
        goto error;

    /* Open UDP socket for reading if not done */
    if (multicast) {
        sys->udp_sock = net_OpenDgram(access, sys->udp_address, sys->udp_port, "", sys->udp_port, IPPROTO_UDP);
        if (sys->udp_sock < 0) {
            msg_Err(access, "Failed to open UDP socket for listening.");
            goto error;
        }

        sys->rtcp_sock = net_OpenDgram(access, sys->udp_address, sys->udp_port + 1, "", sys->udp_port + 1, IPPROTO_UDP);
        if (sys->rtcp_sock < 0) {
            msg_Err(access, "Failed to open RTCP socket for listening.");
            goto error;
        }
    }

    net_Printf(access, sys->tcp_sock,
            "PLAY %s RTSP/1.0\r\n"
            "CSeq: %d\r\n"
            "Session: %s\r\n\r\n",
            sys->control, sys->cseq++, sys->session_id);

    if (rtsp_handle(access, NULL) != RTSP_RESULT_OK) {
        msg_Err(access, "Failed to play RTSP session");
        goto error;
    }

    sys->fifo = block_FifoNew();
    if (!sys->fifo) {
        msg_Err(access, "Failed to allocate block fifo.");
        goto error;
    }
    sys->fifo_size = var_InheritInteger(access, "satip-buffer");

    if (vlc_clone(&sys->thread, satip_thread, access, VLC_THREAD_PRIORITY_INPUT)) {
        msg_Err(access, "Failed to create worker thread.");
        goto error;
    }

    access->pf_control = satip_control;
    access->pf_block = satip_block;

787
    free(psz_host);
788
    free(psz_lower_url);
789 790 791
    return VLC_SUCCESS;

error:
792
    free(psz_host);
793
    free(psz_lower_url);
794 795 796 797 798 799
    vlc_UrlClean(&url);

    satip_teardown(access);

    if (sys->fifo)
        block_FifoRelease(sys->fifo);
800
    if (sys->udp_sock >= 0)
801
        net_Close(sys->udp_sock);
802
    if (sys->rtcp_sock >= 0)
803
        net_Close(sys->rtcp_sock);
804
    if (sys->tcp_sock >= 0)
805 806 807 808
        net_Close(sys->tcp_sock);

    free(sys->content_base);
    free(sys->control);
809 810 811 812 813
    return VLC_EGENERIC;
}

static void satip_close(vlc_object_t *obj)
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
814
    stream_t *access = (stream_t *)obj;
815 816 817 818 819 820 821 822 823 824 825 826 827
    access_sys_t *sys = access->p_sys;

    vlc_cancel(sys->thread);
    vlc_join(sys->thread, NULL);

    satip_teardown(access);

    block_FifoRelease(sys->fifo);
    net_Close(sys->udp_sock);
    net_Close(sys->rtcp_sock);
    net_Close(sys->tcp_sock);
    free(sys->content_base);
    free(sys->control);
828
}