sipcall.cpp 42.6 KB
Newer Older
yanmorin's avatar
yanmorin committed
1
/*
2
 *  Copyright (C) 2004-2019 Savoir-faire Linux Inc.
3
 *
4
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
5
 *  Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com>
jpbl's avatar
jpbl committed
6
 *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
7 8
 *  Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com>
 *  Author: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com>
jpbl's avatar
jpbl committed
9
 *
yanmorin's avatar
yanmorin committed
10 11
 *  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
12
 *  the Free Software Foundation; either version 3 of the License, or
yanmorin's avatar
yanmorin committed
13
 *  (at your option) any later version.
jpbl's avatar
jpbl committed
14
 *
yanmorin's avatar
yanmorin committed
15 16 17 18
 *  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.
jpbl's avatar
jpbl committed
19
 *
yanmorin's avatar
yanmorin committed
20 21
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
22
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
jpbl's avatar
jpbl committed
23 24
 */

25
#include "call_factory.h"
yanmorin's avatar
yanmorin committed
26
#include "sipcall.h"
27 28
#include "sipaccount.h" // for SIPAccount::ACCOUNT_TYPE
#include "sipaccountbase.h"
29
#include "sipvoiplink.h"
30
#include "logger.h" // for _debug
31
#include "sdp.h"
32
#include "manager.h"
33
#include "string_utils.h"
34
#include "upnp/upnp_control.h"
35
#include "sip_utils.h"
Guillaume Roguez's avatar
Guillaume Roguez committed
36
#include "audio/audio_rtp_session.h"
37
#include "system_codec_container.h"
38
#include "im/instant_messaging.h"
39
#include "dring/call_const.h"
40
#include "dring/media_const.h"
41
#include "client/ring_signal.h"
42
#include "ice_transport.h"
43
#include "thread_pool.h"
44

Adrien Béraud's avatar
Adrien Béraud committed
45
#ifdef ENABLE_VIDEO
46
#include "client/videomanager.h"
47
#include "video/video_rtp_session.h"
48
#include "dring/videomanager_interface.h"
49
#include <chrono>
50 51
#endif

52 53
#include "errno.h"

54 55
#include <opendht/crypto.h>

Adrien Béraud's avatar
Adrien Béraud committed
56
namespace jami {
57

58 59
using sip_utils::CONST_PJ_STR;

Adrien Béraud's avatar
Adrien Béraud committed
60
#ifdef ENABLE_VIDEO
Guillaume Roguez's avatar
Guillaume Roguez committed
61 62 63
static DeviceParams
getVideoSettings()
{
Adrien Béraud's avatar
Adrien Béraud committed
64
    const auto& videomon = jami::getVideoDeviceMonitor();
65
    return videomon.getDeviceParams(videomon.getDefaultDevice());
Guillaume Roguez's avatar
Guillaume Roguez committed
66 67 68
}
#endif

69
static constexpr int DEFAULT_ICE_INIT_TIMEOUT {35}; // seconds
70 71 72 73 74 75 76 77 78 79 80 81
static constexpr int DEFAULT_ICE_NEGO_TIMEOUT {60}; // seconds

// SDP media Ids
static constexpr int SDP_AUDIO_MEDIA_ID {0};
static constexpr int SDP_VIDEO_MEDIA_ID {1};

// ICE components Id used on SIP
static constexpr int ICE_AUDIO_RTP_COMPID {0};
static constexpr int ICE_AUDIO_RTCP_COMPID {1};
static constexpr int ICE_VIDEO_RTP_COMPID {2};
static constexpr int ICE_VIDEO_RTCP_COMPID {3};

82 83
const char* const SIPCall::LINK_TYPE = SIPAccount::ACCOUNT_TYPE;

84 85 86
SIPCall::SIPCall(SIPAccountBase& account, const std::string& id, Call::CallType type,
                 const std::map<std::string, std::string>& details)
    : Call(account, id, type, details)
Guillaume Roguez's avatar
Guillaume Roguez committed
87
    , avformatrtp_(new AudioRtpSession(id))
Adrien Béraud's avatar
Adrien Béraud committed
88
#ifdef ENABLE_VIDEO
89
    // The ID is used to associate video streams to calls
90
    , videortp_(new video::VideoRtpSession(id, getVideoSettings()))
91
    , mediaInput_(Manager::instance().getVideoManager().videoDeviceMonitor.getMRLForDefaultDevice())
92
#endif
93
    , sdp_(new Sdp(id))
94
{
95
    if (account.getUPnPActive())
96
        upnp_.reset(new upnp::Controller());
97 98

    setCallMediaLocal();
99
}
yanmorin's avatar
yanmorin committed
100

Emmanuel Milou's avatar
Emmanuel Milou committed
101 102
SIPCall::~SIPCall()
{
103
    std::lock_guard<std::recursive_mutex> lk {callMutex_};
104
    setTransport({});
105
    inv.reset(); // prevents callback usage
jpbl's avatar
jpbl committed
106
}
107

108
SIPAccountBase&
109 110
SIPCall::getSIPAccount() const
{
111
    return static_cast<SIPAccountBase&>(getAccount());
112 113 114
}

void
115
SIPCall::setCallMediaLocal()
116
{
117
    if (localAudioPort_ == 0
Adrien Béraud's avatar
Adrien Béraud committed
118
#ifdef ENABLE_VIDEO
119
        || localVideoPort_ == 0
120 121 122 123 124 125 126
#endif
        )
        generateMediaPorts();
}

void
SIPCall::generateMediaPorts()
127 128 129 130 131
{
    auto& account = getSIPAccount();

    // Reference: http://www.cs.columbia.edu/~hgs/rtp/faq.html#ports
    // We only want to set ports to new values if they haven't been set
132
    const unsigned callLocalAudioPort = account.generateAudioPort();
133 134 135
    if (localAudioPort_ != 0)
        account.releasePort(localAudioPort_);
    localAudioPort_ = callLocalAudioPort;
136
    sdp_->setLocalPublishedAudioPort(callLocalAudioPort);
137

Adrien Béraud's avatar
Adrien Béraud committed
138
#ifdef ENABLE_VIDEO
139 140
    // https://projects.savoirfairelinux.com/issues/17498
    const unsigned int callLocalVideoPort = account.generateVideoPort();
141 142
    if (localVideoPort_ != 0)
        account.releasePort(localVideoPort_);
143
    // this should already be guaranteed by SIPAccount
144 145
    assert(localAudioPort_ != callLocalVideoPort);
    localVideoPort_ = callLocalVideoPort;
146
    sdp_->setLocalPublishedVideoPort(callLocalVideoPort);
147 148 149
#endif
}

150
void SIPCall::setContactHeader(pj_str_t *contact)
151
{
152
    pj_strcpy(&contactHeader_, contact);
153 154
}

155
void
156
SIPCall::setTransport(const std::shared_ptr<SipTransport>& t)
157
{
158
    if (isSecure() and t and not t->isSecure()) {
Adrien Béraud's avatar
Adrien Béraud committed
159
        JAMI_ERR("Can't set unsecure transport to secure call.");
160 161 162
        return;
    }

163 164 165 166 167 168
    const auto list_id = reinterpret_cast<uintptr_t>(this);
    if (transport_)
        transport_->removeStateListener(list_id);
    transport_ = t;

    if (transport_) {
169
        setSecure(transport_->isSecure());
170 171 172 173
        std::weak_ptr<SIPCall> wthis_ = std::static_pointer_cast<SIPCall>(shared_from_this());

        // listen for transport destruction
        transport_->addStateListener(list_id,
174
            [wthis_] (pjsip_transport_state state, const pjsip_transport_state_info*) {
175 176
                if (auto this_ = wthis_.lock()) {
                    // end the call if the SIP transport is shut down
177
                    if (not SipTransport::isAlive(this_->transport_, state) and this_->getConnectionState() != ConnectionState::DISCONNECTED) {
Adrien Béraud's avatar
Adrien Béraud committed
178
                        JAMI_WARN("[call:%s] Ending call because underlying SIP transport was closed",
179
                                  this_->getCallId().c_str());
180
                        this_->onFailure(ECONNRESET);
181
                    }
182
                }
183 184 185 186
            });
    }
}

187 188 189 190 191
/**
 * Send a reINVITE inside an active dialog to modify its state
 * Local SDP session should be modified before calling this method
 */

192 193
int
SIPCall::SIPSessionReinvite()
194
{
195
    std::lock_guard<std::recursive_mutex> lk {callMutex_};
196
    // Do nothing if no invitation processed yet
197
    if (not inv or inv->invite_tsx)
198 199
        return PJ_SUCCESS;

Adrien Béraud's avatar
Adrien Béraud committed
200
    JAMI_DBG("[call:%s] Processing reINVITE (state=%s)", getCallId().c_str(),
201 202
             pjsip_inv_state_name(inv->state));

203 204 205 206 207
    // Generate new ports to receive the new media stream
    // LibAV doesn't discriminate SSRCs and will be confused about Seq changes on a given port
    generateMediaPorts();
    sdp_->clearIce();
    auto& acc = getSIPAccount();
208
    if (not sdp_->createOffer(acc.getActiveAccountCodecInfoList(MEDIA_AUDIO),
209 210
                              acc.getActiveAccountCodecInfoList(acc.isVideoEnabled() and not isAudioOnly() ? MEDIA_VIDEO
                                                                                                           : MEDIA_NONE),
211 212 213 214
                              acc.getSrtpKeyExchange(),
                              getState() == CallState::HOLD))
        return !PJ_SUCCESS;

215
    if (initIceMediaTransport(true))
216 217
        setupLocalSDPFromIce();

218 219 220 221 222
    pjsip_tx_data* tdata;
    auto local_sdp = sdp_->getLocalSdpSession();
    auto result = pjsip_inv_reinvite(inv.get(), nullptr, local_sdp, &tdata);
    if (result == PJ_SUCCESS) {
        if (!tdata)
223
            return PJ_SUCCESS;
224 225 226
        result = pjsip_inv_send_msg(inv.get(), tdata);
        if (result == PJ_SUCCESS)
            return PJ_SUCCESS;
Adrien Béraud's avatar
Adrien Béraud committed
227
        JAMI_ERR("[call:%s] Failed to send REINVITE msg (pjsip: %s)", getCallId().c_str(),
228 229 230 231
                 sip_utils::sip_strerror(result).c_str());
        // Canceling internals without sending (anyways the send has just failed!)
        pjsip_inv_cancel_reinvite(inv.get(), &tdata);
    } else
Adrien Béraud's avatar
Adrien Béraud committed
232
        JAMI_ERR("[call:%s] Failed to create REINVITE msg (pjsip: %s)", getCallId().c_str(),
233
                 sip_utils::sip_strerror(result).c_str());
234 235 236 237

    return !PJ_SUCCESS;
}

238 239 240
void
SIPCall::sendSIPInfo(const char *const body, const char *const subtype)
{
241
    std::lock_guard<std::recursive_mutex> lk {callMutex_};
242 243 244
    if (not inv or not inv->dlg)
        throw VoipLinkException("Couldn't get invite dialog");

245
    pj_str_t methodName = CONST_PJ_STR("INFO");
246 247
    const pj_str_t type = CONST_PJ_STR("application");

248 249 250 251 252 253 254
    pjsip_method method;
    pjsip_method_init_np(&method, &methodName);

    /* Create request message. */
    pjsip_tx_data *tdata;

    if (pjsip_dlg_create_request(inv->dlg, &method, -1, &tdata) != PJ_SUCCESS) {
Adrien Béraud's avatar
Adrien Béraud committed
255
        JAMI_ERR("[call:%s] Could not create dialog", getCallId().c_str());
256 257 258 259 260 261 262 263 264
        return;
    }

    /* Create "application/<subtype>" message body. */
    pj_str_t content;
    pj_cstr(&content, body);
    pj_str_t pj_subtype;
    pj_cstr(&pj_subtype, subtype);
    tdata->msg->body = pjsip_msg_body_create(tdata->pool, &type, &pj_subtype, &content);
265
    if (tdata->msg->body == NULL)
266
        pjsip_tx_data_dec_ref(tdata);
267 268
    else
        pjsip_dlg_send_request(inv->dlg, tdata, getSIPVoIPLink()->getModId(), NULL);
269 270
}

271 272 273 274 275 276 277 278 279
void
SIPCall::requestKeyframe()
{
    const char * const BODY =
        "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
        "<media_control><vc_primitive><to_encoder>"
        "<picture_fast_update/>"
        "</to_encoder></vc_primitive></media_control>";

Adrien Béraud's avatar
Adrien Béraud committed
280
    JAMI_DBG("Sending video keyframe request via SIP INFO");
281 282 283
    try {
        sendSIPInfo(BODY, "media_control+xml");
    } catch (const std::exception& e) {
Adrien Béraud's avatar
Adrien Béraud committed
284
        JAMI_ERR("Error sending video keyframe request: %s", e.what());
285 286 287
    }
}

288 289
void
SIPCall::updateSDPFromSTUN()
290
{
Adrien Béraud's avatar
Adrien Béraud committed
291
    JAMI_WARN("[call:%s] SIPCall::updateSDPFromSTUN() not implemented", getCallId().c_str());
292 293
}

294 295 296
void
SIPCall::terminateSipSession(int status)
{
Adrien Béraud's avatar
Adrien Béraud committed
297
    JAMI_DBG("[call:%s] Terminate SIP session", getCallId().c_str());
298
    std::lock_guard<std::recursive_mutex> lk {callMutex_};
299 300 301 302 303 304 305 306 307
    if (inv and inv->state != PJSIP_INV_STATE_DISCONNECTED) {
        pjsip_tx_data* tdata = nullptr;
        auto ret = pjsip_inv_end_session(inv.get(), status, nullptr, &tdata);
        if (ret == PJ_SUCCESS) {
            if (tdata) {
                auto contact = getSIPAccount().getContactHeader(transport_ ? transport_->get() : nullptr);
                sip_utils::addContactHeader(&contact, tdata);
                ret = pjsip_inv_send_msg(inv.get(), tdata);
                if (ret != PJ_SUCCESS)
Adrien Béraud's avatar
Adrien Béraud committed
308
                    JAMI_ERR("[call:%s] failed to send terminate msg, SIP error (%s)",
309 310 311
                             getCallId().c_str(), sip_utils::sip_strerror(ret).c_str());
            }
        } else
Adrien Béraud's avatar
Adrien Béraud committed
312
            JAMI_ERR("[call:%s] failed to terminate INVITE@%p, SIP error (%s)",
313 314 315 316 317 318 319 320
                     getCallId().c_str(), inv.get(), sip_utils::sip_strerror(ret).c_str());
    }

    inv.reset();
}

void
SIPCall::answer()
321
{
322
    std::lock_guard<std::recursive_mutex> lk {callMutex_};
323
    auto& account = getSIPAccount();
324

325
    if (not inv)
326
        throw VoipLinkException("[call:" + getCallId() + "] answer: no invite session for this call");
327

328
    if (!inv->neg) {
Adrien Béraud's avatar
Adrien Béraud committed
329
        JAMI_WARN("[call:%s] Negotiator is NULL, we've received an INVITE without an SDP",
330
                  getCallId().c_str());
331
        pjmedia_sdp_session *dummy = 0;
332
        getSIPVoIPLink()->createSDPOffer(inv.get(), &dummy);
333

334 335
        if (account.isStunEnabled())
            updateSDPFromSTUN();
336 337
    }

338
    pj_str_t contact(account.getContactHeader(transport_ ? transport_->get() : nullptr));
339 340 341 342 343 344 345
    setContactHeader(&contact);

    pjsip_tx_data *tdata;
    if (!inv->last_answer)
        throw std::runtime_error("Should only be called for initial answer");

    // answer with SDP if no SDP was given in initial invite (i.e. inv->neg is NULL)
346
    if (pjsip_inv_answer(inv.get(), PJSIP_SC_OK, NULL, !inv->neg ? sdp_->getLocalSdpSession() : NULL, &tdata) != PJ_SUCCESS)
347 348 349 350
        throw std::runtime_error("Could not init invite request answer (200 OK)");

    // contactStr must stay in scope as long as tdata
    if (contactHeader_.slen) {
Adrien Béraud's avatar
Adrien Béraud committed
351
        JAMI_DBG("[call:%s] Answering with contact header: %.*s",
352
                 getCallId().c_str(), (int)contactHeader_.slen, contactHeader_.ptr);
353 354 355
        sip_utils::addContactHeader(&contactHeader_, tdata);
    }

356 357
    if (pjsip_inv_send_msg(inv.get(), tdata) != PJ_SUCCESS) {
        inv.reset();
358
        throw std::runtime_error("Could not send invite request answer (200 OK)");
359
    }
360

361
    setState(CallState::ACTIVE, ConnectionState::CONNECTED);
362 363
}

364 365 366
void
SIPCall::hangup(int reason)
{
367
    std::lock_guard<std::recursive_mutex> lk {callMutex_};
368 369 370 371 372 373 374
    if (inv and inv->dlg) {
        pjsip_route_hdr *route = inv->dlg->route_set.next;
        while (route and route != &inv->dlg->route_set) {
            char buf[1024];
            int printed = pjsip_hdr_print_on(route, buf, sizeof(buf));
            if (printed >= 0) {
                buf[printed] = '\0';
Adrien Béraud's avatar
Adrien Béraud committed
375
                JAMI_DBG("[call:%s] Route header %s", getCallId().c_str(), buf);
376 377
            }
            route = route->next;
378
        }
379 380 381 382 383 384
        const int status = reason ? reason :
                           inv->state <= PJSIP_INV_STATE_EARLY and inv->role != PJSIP_ROLE_UAC ?
                           PJSIP_SC_CALL_TSX_DOES_NOT_EXIST :
                           inv->state >= PJSIP_INV_STATE_DISCONNECTED ? PJSIP_SC_DECLINE : 0;
        // Notify the peer
        terminateSipSession(status);
385
    }
386 387
    // Stop all RTP streams
    stopAllMedia();
388
    setState(Call::ConnectionState::DISCONNECTED, reason);
389
    removeCall();
390
}
391 392 393 394

void
SIPCall::refuse()
{
395
    if (!isIncoming() or getConnectionState() == ConnectionState::CONNECTED or !inv)
396 397
        return;

398
    stopAllMedia();
399

400
    // Notify the peer
401
    terminateSipSession(PJSIP_SC_DECLINE);
402

403
    setState(Call::ConnectionState::DISCONNECTED, ECONNABORTED);
404
    removeCall();
405
}
406 407 408 409

static void
transfer_client_cb(pjsip_evsub *sub, pjsip_event *event)
{
410 411
    auto link = getSIPVoIPLink();
    if (not link) {
Adrien Béraud's avatar
Adrien Béraud committed
412
        JAMI_ERR("no more VoIP link");
413 414 415 416
        return;
    }

    auto mod_ua_id = link->getModId();
417 418 419 420 421 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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

    switch (pjsip_evsub_get_state(sub)) {
        case PJSIP_EVSUB_STATE_ACCEPTED:
            if (!event)
                return;

            pj_assert(event->type == PJSIP_EVENT_TSX_STATE && event->body.tsx_state.type == PJSIP_EVENT_RX_MSG);
            break;

        case PJSIP_EVSUB_STATE_TERMINATED:
            pjsip_evsub_set_mod_data(sub, mod_ua_id, NULL);
            break;

        case PJSIP_EVSUB_STATE_ACTIVE: {
            if (!event)
                return;

            pjsip_rx_data* r_data = event->body.rx_msg.rdata;

            if (!r_data)
                return;

            std::string request(pjsip_rx_data_get_info(r_data));

            pjsip_status_line status_line = { 500, *pjsip_get_status_text(500) };

            if (!r_data->msg_info.msg)
                return;

            if (r_data->msg_info.msg->line.req.method.id == PJSIP_OTHER_METHOD and
                    request.find("NOTIFY") != std::string::npos) {
                pjsip_msg_body *body = r_data->msg_info.msg->body;

                if (!body)
                    return;

                if (pj_stricmp2(&body->content_type.type, "message") or
                        pj_stricmp2(&body->content_type.subtype, "sipfrag"))
                    return;

                if (pjsip_parse_status_line((char*) body->data, body->len, &status_line) != PJ_SUCCESS)
                    return;
            }

            if (!r_data->msg_info.cid)
                return;

            auto call = static_cast<SIPCall *>(pjsip_evsub_get_mod_data(sub, mod_ua_id));
            if (!call)
                return;

            if (status_line.code / 100 == 2) {
469 470
                if (call->inv)
                    call->terminateSipSession(PJSIP_SC_GONE);
471 472 473 474 475 476 477
                Manager::instance().hangupCall(call->getCallId());
                pjsip_evsub_set_mod_data(sub, mod_ua_id, NULL);
            }

            break;
        }

478 479 480 481
        case PJSIP_EVSUB_STATE_NULL:
        case PJSIP_EVSUB_STATE_SENT:
        case PJSIP_EVSUB_STATE_PENDING:
        case PJSIP_EVSUB_STATE_UNKNOWN:
482 483 484 485 486 487 488 489
        default:
            break;
    }
}

bool
SIPCall::transferCommon(pj_str_t *dst)
{
490
    if (not inv or not inv->dlg)
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
        return false;

    pjsip_evsub_user xfer_cb;
    pj_bzero(&xfer_cb, sizeof(xfer_cb));
    xfer_cb.on_evsub_state = &transfer_client_cb;

    pjsip_evsub *sub;

    if (pjsip_xfer_create_uac(inv->dlg, &xfer_cb, &sub) != PJ_SUCCESS)
        return false;

    /* Associate this voiplink of call with the client subscription
     * We can not just associate call with the client subscription
     * because after this function, we can no find the cooresponding
     * voiplink from the call any more. But the voiplink is useful!
     */
507
    pjsip_evsub_set_mod_data(sub, getSIPVoIPLink()->getModId(), this);
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

    /*
     * Create REFER request.
     */
    pjsip_tx_data *tdata;

    if (pjsip_xfer_initiate(sub, dst, &tdata) != PJ_SUCCESS)
        return false;

    /* Send. */
    if (pjsip_xfer_send_request(sub, tdata) != PJ_SUCCESS)
        return false;

    return true;
}

void
SIPCall::transfer(const std::string& to)
{
527
    auto& account = getSIPAccount();
528

529 530
    if (Recordable::isRecording())
        stopRecording();
531 532 533 534

    std::string toUri;
    pj_str_t dst = { 0, 0 };

535
    toUri = account.getToUri(to);
536
    pj_cstr(&dst, toUri.c_str());
Adrien Béraud's avatar
Adrien Béraud committed
537
    JAMI_DBG("[call:%s] Transferring to %.*s", getCallId().c_str(), (int)dst.slen, dst.ptr);
538 539 540 541 542 543

    if (!transferCommon(&dst))
        throw VoipLinkException("Couldn't transfer");
}

bool
544
SIPCall::attendedTransfer(const std::string& to)
545
{
546 547 548 549 550
    const auto toCall = Manager::instance().callFactory.getCall<SIPCall>(to);
    if (!toCall)
        return false;

    if (not toCall->inv or not toCall->inv->dlg)
551
        return false;
552

553
    pjsip_dialog *target_dlg = toCall->inv->dlg;
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    pjsip_uri *uri = (pjsip_uri*) pjsip_uri_get_uri(target_dlg->remote.info->uri);

    char str_dest_buf[PJSIP_MAX_URL_SIZE * 2] = { '<' };
    pj_str_t dst = { str_dest_buf, 1 };

    dst.slen += pjsip_uri_print(PJSIP_URI_IN_REQ_URI, uri, str_dest_buf + 1, sizeof(str_dest_buf) - 1);
    dst.slen += pj_ansi_snprintf(str_dest_buf + dst.slen,
                                 sizeof(str_dest_buf) - dst.slen,
                                 "?"
                                 "Replaces=%.*s"
                                 "%%3Bto-tag%%3D%.*s"
                                 "%%3Bfrom-tag%%3D%.*s>",
                                 (int)target_dlg->call_id->id.slen,
                                 target_dlg->call_id->id.ptr,
                                 (int)target_dlg->remote.info->tag.slen,
                                 target_dlg->remote.info->tag.ptr,
                                 (int)target_dlg->local.info->tag.slen,
                                 target_dlg->local.info->tag.ptr);

    return transferCommon(&dst);
}
575

576
bool
577 578
SIPCall::onhold()
{
Sébastien Blin's avatar
Sébastien Blin committed
579 580 581 582 583
    // If ICE is currently negotiating, we must wait before hold the call
    if (isWaitingForIceAndMedia_) {
        remainingRequest_ = Request::HoldingOn;
        return false;
    }
584
    if (not setState(CallState::HOLD))
585
        return false;
586

587
    stopAllMedia();
588

589
    if (getConnectionState() == ConnectionState::CONNECTED) {
Sébastien Blin's avatar
Sébastien Blin committed
590
        if (SIPSessionReinvite() != PJ_SUCCESS) {
Adrien Béraud's avatar
Adrien Béraud committed
591
            JAMI_WARN("[call:%s] Reinvite failed", getCallId().c_str());
Sébastien Blin's avatar
Sébastien Blin committed
592 593
            return true;
        }
594
    }
595

Sébastien Blin's avatar
Sébastien Blin committed
596 597
    isWaitingForIceAndMedia_ = true;

598
    return true;
599 600
}

601
bool
602 603
SIPCall::offhold()
{
604
    bool success = false;
Sébastien Blin's avatar
Sébastien Blin committed
605 606 607 608 609 610
    // If ICE is currently negotiating, we must wait before unhold the call
    if (isWaitingForIceAndMedia_) {
        remainingRequest_ = Request::HoldingOff;
        return false;
    }

611
    auto& account = getSIPAccount();
612 613

    try {
614
        if (account.isStunEnabled())
615
            success = internalOffHold([&] { updateSDPFromSTUN(); });
616
        else
617
            success = internalOffHold([] {});
618 619

    } catch (const SdpException &e) {
Adrien Béraud's avatar
Adrien Béraud committed
620
        JAMI_ERR("[call:%s] %s", getCallId().c_str(), e.what());
621
        throw VoipLinkException("SDP issue in offhold");
Tristan Matthews's avatar
Tristan Matthews committed
622
    }
623

Sébastien Blin's avatar
Sébastien Blin committed
624 625
    if (success) isWaitingForIceAndMedia_ = true;

626
    return success;
627 628
}

629
bool
Guillaume Roguez's avatar
Guillaume Roguez committed
630
SIPCall::internalOffHold(const std::function<void()>& sdp_cb)
631
{
632
    if (not setState(CallState::ACTIVE))
633
        return false;
634

Guillaume Roguez's avatar
Guillaume Roguez committed
635
    sdp_cb();
636

637
    if (getConnectionState() == ConnectionState::CONNECTED) {
638
        if (SIPSessionReinvite() != PJ_SUCCESS) {
Adrien Béraud's avatar
Adrien Béraud committed
639
            JAMI_WARN("[call:%s] resuming hold", getCallId().c_str());
640
            onhold();
641
            return false;
642
        }
643
    }
644 645

    return true;
646
}
647

648 649 650
void
SIPCall::switchInput(const std::string& resource)
{
651
    mediaInput_ = resource;
Sébastien Blin's avatar
Sébastien Blin committed
652 653 654 655 656 657 658
    if (isWaitingForIceAndMedia_) {
        remainingRequest_ = Request::SwitchInput;
    } else {
        if (SIPSessionReinvite() == PJ_SUCCESS) {
            isWaitingForIceAndMedia_ = true;
        }
    }
659 660
}

661 662 663
void
SIPCall::peerHungup()
{
664
    // Stop all RTP streams
Guillaume Roguez's avatar
Guillaume Roguez committed
665
    stopAllMedia();
666

667 668 669
    if (inv)
        terminateSipSession(PJSIP_SC_NOT_FOUND);
    else
Adrien Béraud's avatar
Adrien Béraud committed
670
        JAMI_ERR("[call:%s] peerHungup: no invite session for this call", getCallId().c_str());
671

672
    Call::peerHungup();
673
}
674 675 676 677

void
SIPCall::carryingDTMFdigits(char code)
{
678 679 680 681 682 683 684 685 686 687 688 689 690
    int duration = Manager::instance().voipPreferences.getPulseLength();
    char dtmf_body[1000];

    // handle flash code
    if (code == '!') {
        snprintf(dtmf_body, sizeof dtmf_body - 1, "Signal=16\r\nDuration=%d\r\n", duration);
    } else {
        snprintf(dtmf_body, sizeof dtmf_body - 1, "Signal=%c\r\nDuration=%d\r\n", code, duration);
    }

    try {
        sendSIPInfo(dtmf_body, "dtmf-relay");
    } catch (const std::exception& e) {
Adrien Béraud's avatar
Adrien Béraud committed
691
        JAMI_ERR("Error sending DTMF: %s", e.what());
692
    }
693
}
694

Adrien Béraud's avatar
Adrien Béraud committed
695 696 697 698 699 700 701 702 703
void
SIPCall::setVideoOrientation(int rotation)
{
    std::string sip_body =
        "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
        "<media_control><vc_primitive><to_encoder>"
        "<device_orientation=" + std::to_string(rotation) + "/>"
        "</to_encoder></vc_primitive></media_control>";

Adrien Béraud's avatar
Adrien Béraud committed
704
    JAMI_DBG("Sending device orientation via SIP INFO");
Adrien Béraud's avatar
Adrien Béraud committed
705 706 707 708

    sendSIPInfo(sip_body.c_str(), "media_control+xml");
}

709 710
void
SIPCall::sendTextMessage(const std::map<std::string, std::string>& messages,
711
                         const std::string& from)
712
{
713 714 715
    //TODO: for now we ignore the "from" (the previous implementation for sending this info was
    //      buggy and verbose), another way to send the original message sender will be implemented
    //      in the future
716
    if (not subcalls_.empty()) {
717
        pendingOutMessages_.emplace_back(messages, from);
718
        for (auto& c : subcalls_)
719 720
            c->sendTextMessage(messages, from);
    } else {
721
        if (inv) {
722
            try {
723
                im::sendSipMessage(inv.get(), messages);
724
            } catch (...) {}
725 726
        } else {
            pendingOutMessages_.emplace_back(messages, from);
Adrien Béraud's avatar
Adrien Béraud committed
727
            JAMI_ERR("[call:%s] sendTextMessage: no invite session for this call", getCallId().c_str());
728
        }
729
    }
730
}
731

732 733 734
void
SIPCall::removeCall()
{
735
    std::lock_guard<std::recursive_mutex> lk {callMutex_};
Adrien Béraud's avatar
Adrien Béraud committed
736
    JAMI_WARN("[call:%s] removeCall()", getCallId().c_str());
737
    Call::removeCall();
738
    mediaTransport_.reset();
739 740 741 742
    inv.reset();
    setTransport({});
}

743
void
744
SIPCall::onFailure(signed cause)
745
{
746
    setState(CallState::MERROR, ConnectionState::DISCONNECTED, cause);
747 748 749 750 751 752 753
    runOnMainThread([w = std::weak_ptr<Call>(shared_from_this())] {
        if (auto shared = w.lock()) {
            auto& call = *shared;
            Manager::instance().callFailure(call);
            call.removeCall();
        }
    });
754 755
}

756 757 758
void
SIPCall::onBusyHere()
{
759 760 761 762 763
    if (getCallType() == CallType::OUTGOING)
        setState(CallState::PEER_BUSY, ConnectionState::DISCONNECTED);
    else
        setState(CallState::BUSY, ConnectionState::DISCONNECTED);

764 765 766 767 768 769 770
    runOnMainThread([w = std::weak_ptr<Call>(shared_from_this())] {
        if (auto shared = w.lock()) {
            auto& call = *shared;
            Manager::instance().callBusy(call);
            call.removeCall();
        }
    });
771 772
}

773 774 775
void
SIPCall::onClosed()
{
776 777 778 779 780
    runOnMainThread([w = std::weak_ptr<Call>(shared_from_this())] {
        if (auto shared = w.lock()) {
            auto& call = *shared;
            Manager::instance().peerHungupCall(call);
            call.removeCall();
781
            Manager::instance().checkAudio();
782 783
        }
    });
784 785 786 787 788
}

void
SIPCall::onAnswered()
{
Adrien Béraud's avatar
Adrien Béraud committed
789
    JAMI_WARN("[call:%s] onAnswered()", getCallId().c_str());
790
    if (getConnectionState() != ConnectionState::CONNECTED) {
791
        setState(CallState::ACTIVE, ConnectionState::CONNECTED);
792 793 794 795 796 797 798
        if (not isSubcall()) {
            runOnMainThread([w = std::weak_ptr<Call>(shared_from_this())] {
                if (auto shared = w.lock()) {
                    Manager::instance().peerAnsweredCall(*shared);
                }
            });
        }
799 800
    }
}
801

802 803 804
void
SIPCall::sendKeyframe()
{
Adrien Béraud's avatar
Adrien Béraud committed
805
#ifdef ENABLE_VIDEO
806 807
    ThreadPool::instance().run([w = weak()] {
        if (auto sthis = w.lock()) {
Adrien Béraud's avatar
Adrien Béraud committed
808
            JAMI_DBG("handling picture fast update request");
809 810 811 812 813 814
            sthis->getVideoRtp().forceKeyFrame();
        }
    });
#endif
}

815 816 817
void
SIPCall::onPeerRinging()
{
818
    setState(ConnectionState::RINGING);
819 820
}

821 822 823
void
SIPCall::setupLocalSDPFromIce()
{
824 825 826
    auto media_tr = getIceMediaTransport();

    if (not media_tr) {
Adrien Béraud's avatar
Adrien Béraud committed
827
        JAMI_WARN("[call:%s] no media ICE transport, SDP not changed", getCallId().c_str());
828 829 830
        return;
    }

831
    // we need an initialized ICE to progress further
832
    if (media_tr->waitForInitialization(DEFAULT_ICE_INIT_TIMEOUT) <= 0) {
Adrien Béraud's avatar
Adrien Béraud committed
833
        JAMI_ERR("[call:%s] Medias' ICE init failed", getCallId().c_str());
834 835 836
        return;
    }

837 838 839 840 841
    if (const auto& ip = getSIPAccount().getPublishedIpAddress()) {
        for (unsigned compId = 1; compId <= media_tr->getComponentCount(); ++compId)
            media_tr->registerPublicIP(compId, ip);
    }

Adrien Béraud's avatar
Adrien Béraud committed
842
    JAMI_WARN("[call:%s] fill SDP with ICE transport %p", getCallId().c_str(), media_tr);
843
    sdp_->addIceAttributes(media_tr->getLocalAttributes());
844 845

    // Add video and audio channels
846 847
    sdp_->addIceCandidates(SDP_AUDIO_MEDIA_ID, media_tr->getLocalCandidates(ICE_AUDIO_RTP_COMPID));
    sdp_->addIceCandidates(SDP_AUDIO_MEDIA_ID, media_tr->getLocalCandidates(ICE_AUDIO_RTCP_COMPID));
Adrien Béraud's avatar
Adrien Béraud committed
848
#ifdef ENABLE_VIDEO
849 850
    sdp_->addIceCandidates(SDP_VIDEO_MEDIA_ID, media_tr->getLocalCandidates(ICE_VIDEO_RTP_COMPID));
    sdp_->addIceCandidates(SDP_VIDEO_MEDIA_ID, media_tr->getLocalCandidates(ICE_VIDEO_RTCP_COMPID));
851 852 853
#endif
}

854
std::vector<IceCandidate>
855 856
SIPCall::getAllRemoteCandidates()
{
857
    std::vector<IceCandidate> rem_candidates;
858
    auto media_tr = getIceMediaTransport();
859

860 861
    auto addSDPCandidates = [&, this](unsigned sdpMediaId,
                                      std::vector<IceCandidate>& out) {
862 863
        IceCandidate cand;
        for (auto& line : sdp_->getIceCandidates(sdpMediaId)) {
864
            if (media_tr->getCandidateFromSDP(line, cand)) {
Adrien Béraud's avatar
Adrien Béraud committed
865
                JAMI_DBG("[call:%s] add remote ICE candidate: %s", getCallId().c_str(), line.c_str());
866
                out.emplace_back(cand);
867
            }
868 869 870 871
        }
    };

    addSDPCandidates(SDP_AUDIO_MEDIA_ID, rem_candidates);
Adrien Béraud's avatar
Adrien Béraud committed
872
#ifdef ENABLE_VIDEO
873 874 875 876 877 878
    addSDPCandidates(SDP_VIDEO_MEDIA_ID, rem_candidates);
#endif

    return rem_candidates;
}

879 880 881
bool
SIPCall::useVideoCodec(const AccountVideoCodecInfo* codec) const
{
Adrien Béraud's avatar
Adrien Béraud committed
882
#ifdef ENABLE_VIDEO
883 884
    if (videortp_->isSending())
        return videortp_->useCodec(codec);
885
#endif
886
    return false;
887 888
}

889
void
890
SIPCall::startAllMedia()
891
{
Adrien Béraud's avatar
Adrien Béraud committed
892
    JAMI_WARN("[call:%s] startAllMedia()", getCallId().c_str());
893
    if (isSecure() && not transport_->isSecure()) {
Adrien Béraud's avatar
Adrien Béraud committed
894
        JAMI_ERR("[call:%s] Can't perform secure call over insecure SIP transport",
895
                 getCallId().c_str());
896
        onFailure(EPROTONOSUPPORT);
897 898
        return;
    }
Guillaume Roguez's avatar
Guillaume Roguez committed
899 900
    auto slots = sdp_->getMediaSlots();
    unsigned ice_comp_id = 0;
901
    bool peer_holding {true};
902
    int slotN = -1;
903

Adrien Béraud's avatar
Adrien Béraud committed
904
#ifdef ENABLE_VIDEO
905 906 907 908 909 910
    videortp_->setRequestKeyFrameCallback([wthis = weak()] {
        runOnMainThread([wthis] {
            if (auto this_ = wthis.lock())
                this_->requestKeyframe();
        });
    });
Adrien Béraud's avatar
Adrien Béraud committed
911 912 913 914 915 916
    videortp_->setChangeOrientationCallback([wthis = weak()] (int angle) {
        runOnMainThread([wthis, angle] {
            if (auto this_ = wthis.lock())
                this_->setVideoOrientation(angle);
        });
    });
917 918
#endif

Guillaume Roguez's avatar
Guillaume Roguez committed
919
    for (const auto& slot : slots) {
920
        ++slotN;
Guillaume Roguez's avatar
Guillaume Roguez committed
921 922
        const auto& local = slot.first;
        const auto& remote = slot.second;
923

Guillaume Roguez's avatar
Guillaume Roguez committed
924
        if (local.type != remote.type) {
Adrien Béraud's avatar
Adrien Béraud committed
925
            JAMI_ERR("[call:%s] [SDP:slot#%u] Inconsistent media types between local and remote",
926
                     getCallId().c_str(), slotN);
Guillaume Roguez's avatar
Guillaume Roguez committed
927
            continue;
928
        }
929

930 931
        RtpSession* rtp = local.type == MEDIA_AUDIO
            ? static_cast<RtpSession*>(avformatrtp_.get())
Adrien Béraud's avatar
Adrien Béraud committed
932
#ifdef ENABLE_VIDEO
933
            : static_cast<RtpSession*>(videortp_.get());
934 935 936 937 938 939 940
#else
            : nullptr;
#endif

        if (not rtp)
            continue;

941
        if (!local.codec) {
Adrien Béraud's avatar
Adrien Béraud committed
942
            JAMI_WARN("[call:%s] [SDP:slot#%u] Missing local codec", getCallId().c_str(),
943
                      slotN);
944 945 946
            continue;
        }
        if (!remote.codec) {
Adrien Béraud's avatar
Adrien Béraud committed
947
            JAMI_WARN("[call:%s] [SDP:slot#%u] Missing remote codec", getCallId().c_str(),
948
                      slotN);
949 950 951
            continue;
        }

952 953
        peer_holding &= remote.holding;

954
        if (isSecure() && (not local.crypto || not remote.crypto)) {
Adrien Béraud's avatar
Adrien Béraud committed
955
            JAMI_ERR("[call:%s] [SDP:slot#%u] Can't perform secure call over insecure RTP transport",
956
                     getCallId().c_str(), slotN);
957 958
            continue;
        }
959

960
        auto new_mtu = transport_->getTlsMtu();
961 962
        if (local.type & MEDIA_AUDIO)
            avformatrtp_->switchInput(mediaInput_);
963 964
        avformatrtp_->setMtu(new_mtu);

Adrien Béraud's avatar
Adrien Béraud committed
965
#ifdef ENABLE_VIDEO
966 967
        if (local.type & MEDIA_VIDEO)
            videortp_->switchInput(mediaInput_);
968 969
        videortp_->setMtu(new_mtu);
#endif
970
        rtp->updateMedia(remote, local);
971 972 973 974 975 976 977 978 979

        // Not restarting media loop on hold as it's a huge waste of CPU ressources
        // because of the audio loop
        if (getState() != CallState::HOLD) {
            if (isIceRunning()) {
                rtp->start(newIceSocket(ice_comp_id + 0),
                           newIceSocket(ice_comp_id + 1));
                ice_comp_id += 2;
            } else
980
                rtp->start(nullptr, nullptr);
981
        }
982 983

        switch (local.type) {
Adrien Béraud's avatar
Adrien Béraud committed
984
#ifdef ENABLE_VIDEO
985
            case MEDIA_VIDEO:
986
                isVideoMuted_ = mediaInput_.empty();
987 988 989 990 991 992 993
                break;
#endif
            case MEDIA_AUDIO:
                isAudioMuted_ = not rtp->isSending();
                break;
            default: break;
        }
994
    }
995

996
    if (not isSubcall() and peerHolding_ != peer_holding) {
997 998 999
        peerHolding_ = peer_holding;
        emitSignal<DRing::CallSignal::PeerHold>(getCallId(), peerHolding_);
    }
Sébastien Blin's avatar
Sébastien Blin committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

    // Media is restarted, we can process the last holding request.
    isWaitingForIceAndMedia_ = false;
    if (remainingRequest_ != Request::NoRequest) {
        switch (remainingRequest_) {
        case Request::HoldingOn:
            onhold();
            break;
        case Request::HoldingOff:
            offhold();
            break;
        case Request::SwitchInput:
            SIPSessionReinvite();
            break;
        default:
            break;
        }
        remainingRequest_ = Request::NoRequest;
    }
1019
}
1020

1021 1022 1023
void
SIPCall::restartMediaSender()
{
Adrien Béraud's avatar
Adrien Béraud committed
1024
    JAMI_DBG("[call:%s] restarting TX media streams", getCallId().c_str());
1025
    avformatrtp_->restartSender();
Adrien Béraud's avatar
Adrien Béraud committed
1026
#ifdef ENABLE_VIDEO
1027
    videortp_->restartSender();
1028 1029 1030
#endif
}

1031
void
Guillaume Roguez's avatar
Guillaume Roguez committed
1032
SIPCall::stopAllMedia()
1033
{
Adrien Béraud's avatar
Adrien Béraud committed
1034
    JAMI_DBG("[call:%s] stopping all medias", getCallId().c_str());
1035 1036
    if (Recordable::isRecording())
        Recordable::stopRecording(); // if call stops, finish recording
1037
    avformatrtp_->stop();
Adrien Béraud's avatar
Adrien Béraud committed
1038
#ifdef ENABLE_VIDEO
1039
    videortp_->stop();
1040 1041
#endif
}
1042

1043
void
1044
SIPCall::muteMedia(const std::string& mediaType, bool mute)
1045 1046
{
    if (mediaType.compare(DRing::Media::Details::MEDIA_TYPE_VIDEO) == 0) {
Adrien Béraud's avatar
Adrien Béraud committed
1047
#ifdef ENABLE_VIDEO
1048
        if (mute == isVideoMuted_) return;
Adrien Béraud's avatar
Adrien Béraud committed
1049
        JAMI_WARN("[call:%s] video muting %s", getCallId().c_str(), bool_to_str(mute));
1050
        isVideoMuted_ = mute;
1051 1052
        mediaInput_ = isVideoMuted_ ? "" : Manager::instance().getVideoManager().videoDeviceMonitor.getMRLForDefaultDevice();
        DRing::switchInput(getCallId(), mediaInput_);
1053
        if (not isSubcall())
1054
            emitSignal<DRing::CallSignal::VideoMuted>(getCallId(), isVideoMuted_);
1055 1056
#endif
    } else if (mediaType.compare(DRing::Media::Details::MEDIA_TYPE_AUDIO) == 0) {
1057
        if (mute == isAudioMuted_) return;
Adrien Béraud's avatar
Adrien Béraud committed
1058
        JAMI_WARN("[call:%s] audio muting %s", getCallId().c_str(), bool_to_str(mute));
1059
        isAudioMuted_ = mute;
1060
        avformatrtp_->setMuted(isAudioMuted_);
1061
        if (not isSubcall())
1062
            emitSignal<DRing::CallSignal::AudioMuted>(getCallId(), isAudioMuted_);
1063 1064 1065
    }
}

1066 1067 1068 1069 1070 1071
/// \brief Prepare media transport and launch media stream based on negotiated SDP
///
/// This method has to be called by link (ie SipVoIpLink) when SDP is negotiated and
/// media streams structures are knows.
/// In case of ICE transport used, the medias streams are launched asynchonously when
/// the transport is negotiated.
Guillaume Roguez's avatar
Guillaume Roguez committed
1072 1073 1074
void
SIPCall::onMediaUpdate()
{
Adrien Béraud's avatar
Adrien Béraud committed
1075
    JAMI_WARN("[call:%s] medias changed", getCallId().c_str());
1076 1077 1078 1079

    // If ICE is not used, start medias now
    auto rem_ice_attrs = sdp_->getIceAttributes();
    if (rem_ice_attrs.ufrag.empty() or rem_ice_attrs.pwd.empty()) {
Adrien Béraud's avatar
Adrien Béraud committed
1080
        JAMI_WARN("[call:%s] no remote ICE for medias", getCallId().c_str());
1081
        stopAllMedia();
1082
        startAllMedia();
1083
        return;
1084
    }
1085

1086 1087 1088
    // Main call (no subcalls) must wait for ICE now, the rest of code needs to access
    // to a negotiated transport.
    if (not isSubcall())
1089
        waitForIceAndStartMedia();
1090 1091 1092 1093 1094
}

void
SIPCall::waitForIceAndStartMedia()
{
1095 1096 1097 1098 1099 1100 1101 1102
    // Initialization waiting task
    auto weak_call = std::weak_ptr<SIPCall>(std::static_pointer_cast<SIPCall>(shared_from_this()));
    Manager::instance().addTask([weak_call] {
        // TODO: polling algo, to it by event
        if (auto call = weak_call.lock()) {
            auto ice = call->getIceMediaTransport();

            if (ice->isFailed()) {
Adrien Béraud's avatar
Adrien Béraud committed
1103
                JAMI_ERR("[call:%s] Media ICE init failed", call->getCallId().c_str());
1104
                call->onFailure(EIO);
1105 1106
                return false;
            }
1107 1108 1109 1110

            if (!ice->isInitialized())
                return true;

Hugo Lefeuvre's avatar
Hugo Lefeuvre committed
1111
            // Start transport on SDP data and wait for negotiation
1112 1113
            auto rem_ice_attrs = call->sdp_->getIceAttributes();
            if (rem_ice_attrs.ufrag.empty() or rem_ice_attrs.pwd.empty()) {
Adrien Béraud's avatar
Adrien Béraud committed
1114
                JAMI_ERR("[call:%s] Media ICE attributes empty", call->getCallId().c_str());
1115
                call->onFailure(EIO);
1116 1117
                return false;
            }
1118
            if (not ice->start(rem_ice_attrs, call->getAllRemoteCandidates())) {
Adrien Béraud's avatar
Adrien Béraud committed
1119
                JAMI_ERR("[call:%s] Media ICE start failed", call->getCallId().c_str());
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
                call->onFailure(EIO);
                return false;
            }

            // Negotiation waiting task
            Manager::instance().addTask([weak_call] {
                if (auto call = weak_call.lock()) {
                    auto ice = call->getIceMediaTransport();

                    if (ice->isFailed()) {
Adrien Béraud's avatar
Adrien Béraud committed
1130
                        JAMI_ERR("[call:%s] Media ICE negotiation failed", call->getCallId().c_str());
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
                        call->onFailure(EIO);
                        return false;
                    }

                    if (not ice->isRunning())
                        return true;

                    // Nego succeed: move to the new media transport
                    call->stopAllMedia();
                    if (call->tmpMediaTransport_)
                        call->mediaTransport_ = std::move(call->tmpMediaTransport_);
                    call->startAllMedia();
                    return false;
                }
                return false;
            });

            return false;
1149 1150 1151
        }
        return false;
    });
Guillaume Roguez's avatar
Guillaume Roguez committed
1152 1153
}

1154 1155 1156 1157 1158 1159 1160 1161 1162
void
SIPCall::onReceiveOffer(const pjmedia_sdp_session* offer)
{
    sdp_->clearIce();
    auto& acc = getSIPAccount();
    sdp_->receiveOffer(offer,
        acc.getActiveAccountCodecInfoList(MEDIA_AUDIO),
        acc.getActiveAccountCodecInfoList(acc.isVideoEnabled() ? MEDIA_VIDEO : MEDIA_NONE),
        acc.getSrtpKeyExchange(),
1163 1164
        getState() ==