chromecast_ctrl.cpp 18.5 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 30 31 32 33 34 35 36 37
/*****************************************************************************
 * chromecast_ctrl.cpp: Chromecast module for vlc
 *****************************************************************************
 * Copyright © 2014-2015 VideoLAN
 *
 * Authors: Adrien Maglo <magsoft@videolan.org>
 *          Jean-Baptiste Kempf <jb@videolan.org>
 *          Steve Lhomme <robux4@videolabs.io>
 *
 * 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.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "chromecast.h"

#include <vlc_sout.h>

#include <sstream>
38 39 40
#ifdef HAVE_POLL
# include <poll.h>
#endif
41

42 43
#include "../../misc/webservices/json.h"

44 45
#define PACKET_MAX_LEN 10 * 1024

46
// Media player Chromecast app id
47
#define APP_ID "CC1AD845" // Default media player aka DEFAULT_MEDIA_RECEIVER_APPLICATION_ID
48

49 50
#define CHROMECAST_CONTROL_PORT 8009

51 52 53 54 55 56 57
/* deadline regarding pings sent from receiver */
#define PING_WAIT_TIME 6000
#define PING_WAIT_RETRIES 0
/* deadline regarding pong we expect after pinging the receiver */
#define PONG_WAIT_TIME 500
#define PONG_WAIT_RETRIES 2

58 59
#define SOUT_CFG_PREFIX "sout-chromecast-"

60 61 62 63 64
static const std::string NAMESPACE_DEVICEAUTH       = "urn:x-cast:com.google.cast.tp.deviceauth";
static const std::string NAMESPACE_CONNECTION       = "urn:x-cast:com.google.cast.tp.connection";
static const std::string NAMESPACE_HEARTBEAT        = "urn:x-cast:com.google.cast.tp.heartbeat";
static const std::string NAMESPACE_RECEIVER         = "urn:x-cast:com.google.cast.receiver";

65 66 67 68 69 70 71 72 73
/**
 * @brief Build a CastMessage to send to the Chromecast
 * @param namespace_ the message namespace
 * @param payloadType the payload type (CastMessage_PayloadType_STRING or
 * CastMessage_PayloadType_BINARY
 * @param payload the payload
 * @param destinationId the destination idenifier
 * @return the generated CastMessage
 */
74 75
void intf_sys_t::buildMessage(const std::string & namespace_,
                              const std::string & payload,
76 77
                              const std::string & destinationId,
                              castchannel::CastMessage_PayloadType payloadType)
78 79 80 81 82 83 84 85 86 87 88 89 90
{
    castchannel::CastMessage msg;

    msg.set_protocol_version(castchannel::CastMessage_ProtocolVersion_CASTV2_1_0);
    msg.set_namespace_(namespace_);
    msg.set_payload_type(payloadType);
    msg.set_source_id("sender-vlc");
    msg.set_destination_id(destinationId);
    if (payloadType == castchannel::CastMessage_PayloadType_STRING)
        msg.set_payload_utf8(payload);
    else // CastMessage_PayloadType_BINARY
        msg.set_payload_binary(payload);

91
    sendMessage(msg);
92 93 94
}

intf_sys_t::intf_sys_t(sout_stream_t * const p_this)
95
 : p_stream(p_this)
96
 , p_tls(NULL)
97
 , conn_status(CHROMECAST_DISCONNECTED)
98
 , i_receiver_requestId(0)
99
 , i_requestId(0)
100
{
101 102
    vlc_mutex_init(&lock);
    vlc_cond_init(&loadCommandCond);
103 104 105 106
}

intf_sys_t::~intf_sys_t()
{
107 108 109 110
    vlc_cond_destroy(&loadCommandCond);
    vlc_mutex_destroy(&lock);
}

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
/**
 * @brief Connect to the Chromecast
 * @param p_stream the sout_stream_t structure
 * @return the opened socket file descriptor or -1 on error
 */
int intf_sys_t::connectChromecast(char *psz_ipChromecast)
{
    int fd = net_ConnectTCP(p_stream, psz_ipChromecast, CHROMECAST_CONTROL_PORT);
    if (fd < 0)
        return -1;

    p_creds = vlc_tls_ClientCreate(VLC_OBJECT(p_stream));
    if (p_creds == NULL)
    {
        net_Close(fd);
        return -1;
    }

129
    p_tls = vlc_tls_ClientSessionCreateFD(p_creds, fd, psz_ipChromecast,
130 131 132 133
                                               "tcps", NULL, NULL);

    if (p_tls == NULL)
    {
134
        net_Close(fd);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        vlc_tls_Delete(p_creds);
        return -1;
    }

    return fd;
}


/**
 * @brief Disconnect from the Chromecast
 */
void intf_sys_t::disconnectChromecast()
{
    if (p_tls)
    {
150
        vlc_tls_Close(p_tls);
151 152 153 154 155 156 157
        vlc_tls_Delete(p_creds);
        p_tls = NULL;
        setConnectionStatus(CHROMECAST_DISCONNECTED);
    }
}


158 159 160 161 162 163 164 165 166 167
/**
 * @brief Receive a data packet from the Chromecast
 * @param p_stream the sout_stream_t structure
 * @param b_msgReceived returns true if a message has been entirely received else false
 * @param i_payloadSize returns the payload size of the message received
 * @return the number of bytes received of -1 on error
 */
// Use here only C linkage and POD types as this function is a cancelation point.
extern "C" int recvPacket(sout_stream_t *p_stream, bool &b_msgReceived,
                          uint32_t &i_payloadSize, int i_sock_fd, vlc_tls_t *p_tls,
168
                          unsigned *pi_received, uint8_t *p_data, bool *pb_pingTimeout,
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
                          int *pi_wait_delay, int *pi_wait_retries)
{
    struct pollfd ufd[1];
    ufd[0].fd = i_sock_fd;
    ufd[0].events = POLLIN;

    /* The Chromecast normally sends a PING command every 5 seconds or so.
     * If we do not receive one after 6 seconds, we send a PING.
     * If after this PING, we do not receive a PONG, then we consider the
     * connection as dead. */
    if (poll(ufd, 1, *pi_wait_delay) == 0)
    {
        if (*pb_pingTimeout)
        {
            if (!*pi_wait_retries)
            {
                msg_Err(p_stream, "No PONG answer received from the Chromecast");
                return 0; // Connection died
            }
            (*pi_wait_retries)--;
        }
        else
        {
            /* now expect a pong */
            *pi_wait_delay = PONG_WAIT_TIME;
            *pi_wait_retries = PONG_WAIT_RETRIES;
            msg_Warn(p_stream, "No PING received from the Chromecast, sending a PING");
        }
        *pb_pingTimeout = true;
    }
    else
    {
        *pb_pingTimeout = false;
        /* reset to default ping waiting */
        *pi_wait_delay = PING_WAIT_TIME;
        *pi_wait_retries = PING_WAIT_RETRIES;
    }

    int i_ret;

    /* Packet structure:
     * +------------------------------------+------------------------------+
     * | Payload size (uint32_t big endian) |         Payload data         |
     * +------------------------------------+------------------------------+ */
213
    while (*pi_received < PACKET_HEADER_LEN)
214 215
    {
        // We receive the header.
216
        i_ret = tls_Recv(p_tls, p_data + *pi_received, PACKET_HEADER_LEN - *pi_received);
217 218 219 220 221
        if (i_ret <= 0)
            return i_ret;
        *pi_received += i_ret;
    }

222
    // We receive the payload.
223

224
    // Get the size of the payload
225
    i_payloadSize = U32_AT( p_data );
226
    const uint32_t i_maxPayloadSize = PACKET_MAX_LEN - PACKET_HEADER_LEN;
227

228 229 230 231
    if (i_payloadSize > i_maxPayloadSize)
    {
        // Error case: the packet sent by the Chromecast is too long: we drop it.
        msg_Err(p_stream, "Packet too long: droping its data");
232

233 234 235
        uint32_t i_size = i_payloadSize - (*pi_received - PACKET_HEADER_LEN);
        if (i_size > i_maxPayloadSize)
            i_size = i_maxPayloadSize;
236

237
        i_ret = tls_Recv(p_tls, p_data + PACKET_HEADER_LEN, i_size);
238 239 240 241 242 243 244 245
        if (i_ret <= 0)
            return i_ret;
        *pi_received += i_ret;

        if (*pi_received < i_payloadSize + PACKET_HEADER_LEN)
            return i_ret;

        *pi_received = 0;
246
        return -1;
247 248
    }

249 250 251 252 253 254 255 256 257 258 259 260 261 262
    // Normal case
    i_ret = tls_Recv(p_tls, p_data + *pi_received,
                     i_payloadSize - (*pi_received - PACKET_HEADER_LEN));
    if (i_ret <= 0)
        return i_ret;
    *pi_received += i_ret;

    if (*pi_received < i_payloadSize + PACKET_HEADER_LEN)
        return i_ret;

    assert(*pi_received == i_payloadSize + PACKET_HEADER_LEN);
    *pi_received = 0;
    b_msgReceived = true;
    return i_ret;
263 264
}

265 266 267 268 269
/**
 * @brief Process a message received from the Chromecast
 * @param msg the CastMessage to process
 * @return 0 if the message has been successfuly processed else -1
 */
270
void intf_sys_t::processMessage(const castchannel::CastMessage &msg)
271
{
272
    const std::string & namespace_ = msg.namespace_();
273

274 275 276 277
#ifndef NDEBUG
    msg_Dbg(p_stream,"processMessage: %s->%s %s", namespace_.c_str(), msg.destination_id().c_str(), msg.payload_utf8().c_str());
#endif

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    if (namespace_ == NAMESPACE_DEVICEAUTH)
    {
        castchannel::DeviceAuthMessage authMessage;
        authMessage.ParseFromString(msg.payload_binary());

        if (authMessage.has_error())
        {
            msg_Err(p_stream, "Authentification error: %d", authMessage.error().error_type());
        }
        else if (!authMessage.has_response())
        {
            msg_Err(p_stream, "Authentification message has no response field");
        }
        else
        {
            vlc_mutex_locker locker(&lock);
294
            setConnectionStatus(CHROMECAST_AUTHENTICATED);
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
            msgConnect(DEFAULT_CHOMECAST_RECEIVER);
            msgReceiverLaunchApp();
        }
    }
    else if (namespace_ == NAMESPACE_HEARTBEAT)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "PING")
        {
            msg_Dbg(p_stream, "PING received from the Chromecast");
            msgPong();
        }
        else if (type == "PONG")
        {
            msg_Dbg(p_stream, "PONG received from the Chromecast");
        }
        else
        {
315
            msg_Warn(p_stream, "Heartbeat command not supported: %s", type.c_str());
316 317 318 319 320 321 322 323 324 325 326 327 328
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_RECEIVER)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "RECEIVER_STATUS")
        {
            json_value applications = (*p_data)["status"]["applications"];
            const json_value *p_app = NULL;
329 330

            vlc_mutex_locker locker(&lock);
331 332 333 334 335
            for (unsigned i = 0; i < applications.u.array.length; ++i)
            {
                std::string appId(applications[i]["appId"]);
                if (appId == APP_ID)
                {
336 337 338 339 340 341
                    const char *pz_transportId = applications[i]["transportId"];
                    if (pz_transportId != NULL)
                    {
                        appTransportId = std::string(pz_transportId);
                        p_app = &applications[i];
                    }
342 343 344 345 346 347 348
                    break;
                }
            }

            if ( p_app )
            {
                if (!appTransportId.empty()
349
                        && getConnectionStatus() == CHROMECAST_AUTHENTICATED)
350 351
                {
                    msgConnect(appTransportId);
352
                    setConnectionStatus(CHROMECAST_APP_STARTED);
353
                    msgPlayerLoad();
354
                    setConnectionStatus(CHROMECAST_MEDIA_LOAD_SENT);
355 356 357 358 359
                    vlc_cond_signal(&loadCommandCond);
                }
            }
            else
            {
360
                switch(getConnectionStatus())
361 362 363 364 365 366
                {
                /* If the app is no longer present */
                case CHROMECAST_APP_STARTED:
                case CHROMECAST_MEDIA_LOAD_SENT:
                    msg_Warn(p_stream, "app is no longer present. closing");
                    msgReceiverClose(appTransportId);
367
                    setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
368 369 370 371 372 373 374 375
                    break;

                case CHROMECAST_AUTHENTICATED:
                    msg_Dbg(p_stream, "Chromecast was running no app, launch media_app");
                    appTransportId = "";
                    msgReceiverLaunchApp();
                    break;

376 377 378 379 380 381
                default:
                    break;
                }

            }
        }
382 383 384 385 386 387
        else if (type == "LAUNCH_ERROR")
        {
            json_value reason = (*p_data)["reason"];
            msg_Err(p_stream, "Failed to start the MediaPlayer: %s",
                    (const char *)reason);
        }
388 389
        else
        {
390
            msg_Warn(p_stream, "Receiver command not supported: %s",
391 392 393 394 395 396 397 398 399 400 401 402 403
                    msg.payload_utf8().c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_MEDIA)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);

        if (type == "MEDIA_STATUS")
        {
            json_value status = (*p_data)["status"];
404 405 406
            msg_Dbg(p_stream, "Player state: %s sessionId:%d",
                    status[0]["playerState"].operator const char *(),
                    (int)(json_int_t) status[0]["mediaSessionId"]);
407 408 409 410 411
        }
        else if (type == "LOAD_FAILED")
        {
            msg_Err(p_stream, "Media load failed");
            msgReceiverClose(appTransportId);
412
            vlc_mutex_locker locker(&lock);
413
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
414 415 416 417
        }
        else if (type == "INVALID_REQUEST")
        {
            msg_Dbg(p_stream, "We sent an invalid request reason:%s", (*p_data)["reason"].operator const char *());
418 419 420
        }
        else
        {
421
            msg_Warn(p_stream, "Media command not supported: %s",
422 423 424 425 426 427 428 429 430 431 432 433 434 435
                    msg.payload_utf8().c_str());
        }

        json_value_free(p_data);
    }
    else if (namespace_ == NAMESPACE_CONNECTION)
    {
        json_value *p_data = json_parse(msg.payload_utf8().c_str());
        std::string type((*p_data)["type"]);
        json_value_free(p_data);

        if (type == "CLOSE")
        {
            msg_Warn(p_stream, "received close message");
436
            vlc_mutex_locker locker(&lock);
437
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
438 439 440
        }
        else
        {
441
            msg_Warn(p_stream, "Connection command not supported: %s",
442 443 444 445 446 447 448
                    type.c_str());
        }
    }
    else
    {
        msg_Err(p_stream, "Unknown namespace: %s", msg.namespace_().c_str());
    }
449 450 451 452 453 454 455 456 457 458
}

/*****************************************************************************
 * Message preparation
 *****************************************************************************/
void intf_sys_t::msgAuth()
{
    castchannel::DeviceAuthMessage authMessage;
    authMessage.mutable_challenge();

459 460
    buildMessage(NAMESPACE_DEVICEAUTH, authMessage.SerializeAsString(),
                 DEFAULT_CHOMECAST_RECEIVER, castchannel::CastMessage_PayloadType_BINARY);
461 462 463 464 465 466
}


void intf_sys_t::msgPing()
{
    std::string s("{\"type\":\"PING\"}");
467
    buildMessage(NAMESPACE_HEARTBEAT, s);
468 469 470 471 472 473
}


void intf_sys_t::msgPong()
{
    std::string s("{\"type\":\"PONG\"}");
474
    buildMessage(NAMESPACE_HEARTBEAT, s);
475 476
}

477
void intf_sys_t::msgConnect(const std::string & destinationId)
478 479
{
    std::string s("{\"type\":\"CONNECT\"}");
480
    buildMessage(NAMESPACE_CONNECTION, s, destinationId);
481 482 483
}


484
void intf_sys_t::msgReceiverClose(std::string destinationId)
485 486
{
    std::string s("{\"type\":\"CLOSE\"}");
487
    buildMessage(NAMESPACE_CONNECTION, s, destinationId);
488 489
}

490
void intf_sys_t::msgReceiverGetStatus()
491 492
{
    std::stringstream ss;
493 494
    ss << "{\"type\":\"GET_STATUS\","
       <<  "\"requestId\":" << i_receiver_requestId++ << "}";
495

496
    buildMessage(NAMESPACE_RECEIVER, ss.str());
497 498
}

499
void intf_sys_t::msgReceiverLaunchApp()
500 501 502 503
{
    std::stringstream ss;
    ss << "{\"type\":\"LAUNCH\","
       <<  "\"appId\":\"" << APP_ID << "\","
504
       <<  "\"requestId\":" << i_receiver_requestId++ << "}";
505

506
    buildMessage(NAMESPACE_RECEIVER, ss.str());
507 508 509
}


510
void intf_sys_t::msgPlayerLoad()
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
{
    char *psz_mime = var_GetNonEmptyString(p_stream, SOUT_CFG_PREFIX "mime");
    if (psz_mime == NULL)
        return;

    std::stringstream ss;
    ss << "{\"type\":\"LOAD\","
       <<  "\"media\":{\"contentId\":\"http://" << serverIP << ":"
           << var_InheritInteger(p_stream, SOUT_CFG_PREFIX"http-port")
           << "/stream\","
       <<             "\"streamType\":\"LIVE\","
       <<             "\"contentType\":\"" << std::string(psz_mime) << "\"},"
       <<  "\"requestId\":" << i_requestId++ << "}";

    free(psz_mime);

527
    buildMessage(NAMESPACE_MEDIA, ss.str(), appTransportId);
528 529
}

530 531 532
/**
 * @brief Send a message to the Chromecast
 * @param msg the CastMessage to send
533
 * @return vlc error code
534
 */
535
int intf_sys_t::sendMessage(const castchannel::CastMessage &msg)
536
{
537 538
    int i_size = msg.ByteSize();
    uint8_t *p_data = new(std::nothrow) uint8_t[PACKET_HEADER_LEN + i_size];
539
    if (p_data == NULL)
540
        return VLC_ENOMEM;
541

542 543 544
#ifndef NDEBUG
    msg_Dbg(p_stream, "sendMessage: %s->%s %s", msg.namespace_().c_str(), msg.destination_id().c_str(), msg.payload_utf8().c_str());
#endif
545

546 547 548 549
    SetDWBE(p_data, i_size);
    msg.SerializeWithCachedSizesToArray(p_data + PACKET_HEADER_LEN);

    vlc_mutex_locker locker(&lock);
550 551
    int i_ret = tls_Send(p_tls, p_data, PACKET_HEADER_LEN + i_size);
    delete[] p_data;
552 553
    if (i_ret == PACKET_HEADER_LEN + i_size)
        return VLC_SUCCESS;
554

555
    return VLC_EGENERIC;
556 557 558 559
}

void intf_sys_t::handleMessages()
{
560
    unsigned i_received = 0;
561
    uint8_t p_packet[PACKET_MAX_LEN];
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    bool b_pingTimeout = false;

    int i_waitdelay = PING_WAIT_TIME;
    int i_retries = PING_WAIT_RETRIES;

    bool b_msgReceived = false;
    uint32_t i_payloadSize = 0;
    int i_ret = recvPacket(p_stream, b_msgReceived, i_payloadSize, i_sock_fd,
                           p_tls, &i_received, p_packet, &b_pingTimeout,
                           &i_waitdelay, &i_retries);

    int canc = vlc_savecancel();
    // Not cancellation-safe part.

#if defined(_WIN32)
    if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
    if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
    {
582
        msg_Err(p_stream, "The connection to the Chromecast died (receiving).");
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        vlc_mutex_locker locker(&lock);
        setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        vlc_restorecancel(canc);
        return;
    }

    if (b_pingTimeout)
    {
        msgPing();
        msgReceiverGetStatus();
    }

    if (b_msgReceived)
    {
        castchannel::CastMessage msg;
        msg.ParseFromArray(p_packet + PACKET_HEADER_LEN, i_payloadSize);
        processMessage(msg);
    }

    vlc_restorecancel(canc);
603
}