manager.cpp 84.2 KB
Newer Older
1
/*
2
 *  Copyright (C) 2004-2019 Savoir-faire Linux Inc.
3
 *
4 5 6 7 8 9 10 11
 *  Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com>
 *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
 *  Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com>
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
 *  Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
 *  Author: Guillaume Carmel-Archambault <guillaume.carmel-archambault@savoirfairelinux.com>
 *  Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
 *  Author: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com>
12
 *  Author: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
13
 *  Author: Philippe Gorley <philippe.gorley@savoirfairelinux.com>
14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
27
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
28 29
 */

30 31 32 33 34
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "manager.h"
35 36

#include "logger.h"
37 38 39 40 41 42
#include "account_schema.h"

#include "fileutils.h"
#include "map_utils.h"
#include "account.h"
#include "string_utils.h"
43
#include "jamidht/jamiaccount.h"
44 45
#include <opendht/rng.h>
using random_device = dht::crypto::random_device;
46 47 48 49

#include "call_factory.h"

#include "sip/sip_utils.h"
50
#include "sip/sipvoiplink.h"
51
#include "sip/sipaccount.h"
52 53 54 55 56 57 58 59 60

#include "im/instant_messaging.h"

#include "config/yamlparser.h"

#if HAVE_ALSA
#include "audio/alsa/alsalayer.h"
#endif

61
#include "media/localrecordermanager.h"
62 63 64 65
#include "audio/sound/tonelist.h"
#include "audio/sound/dtmf.h"
#include "audio/ringbufferpool.h"

Adrien Béraud's avatar
Adrien Béraud committed
66
#ifdef ENABLE_VIDEO
67
#include "client/videomanager.h"
Alexandre Lision's avatar
Alexandre Lision committed
68
#include "video/video_scaler.h"
69 70 71 72 73 74
#endif

#include "conference.h"
#include "ice_transport.h"

#include "client/ring_signal.h"
75
#include "dring/call_const.h"
Adrien Béraud's avatar
Adrien Béraud committed
76
#include "dring/account_const.h"
77 78 79

#include "libav_utils.h"
#include "video/sinkclient.h"
80
#include "audio/tonecontrol.h"
81

82 83
#include "data_transfer.h"

Adrien Béraud's avatar
Adrien Béraud committed
84 85
#include <opendht/thread_pool.h>

86 87 88 89 90
#ifndef WIN32
#include <sys/time.h>
#include <sys/resource.h>
#endif

91 92 93 94
#ifdef TARGET_OS_IOS
#include <CoreFoundation/CoreFoundation.h>
#endif

95 96 97 98 99 100
#include <cerrno>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
101
#include <algorithm>
102 103
#include <memory>
#include <mutex>
104 105 106
#include <list>
#include <random>

Adrien Béraud's avatar
Adrien Béraud committed
107
namespace jami {
108

109 110 111 112 113 114
/** To store conference objects by conference ids */
using ConferenceMap = std::map<std::string, std::shared_ptr<Conference>>;

/** To store uniquely a list of Call ids */
using CallIDSet = std::set<std::string>;

115
static constexpr std::chrono::seconds ICE_INIT_TIMEOUT{10};
116
static constexpr const char* PACKAGE_OLD = "ring";
117

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
std::atomic_bool Manager::initialized = {false};

static void
copy_over(const std::string &srcPath, const std::string &destPath)
{
    std::ifstream src(srcPath.c_str());
    std::ofstream dest(destPath.c_str());
    dest << src.rdbuf();
    src.close();
    dest.close();
}

// Creates a backup of the file at "path" with a .bak suffix appended
static void
make_backup(const std::string &path)
{
    const std::string backup_path(path + ".bak");
    copy_over(path, backup_path);
}

// Restore last backup of the configuration file
static void
restore_backup(const std::string &path)
{
    const std::string backup_path(path + ".bak");
    copy_over(backup_path, path);
}

146 147 148
void
check_rename(const std::string& old_dir, const std::string& new_dir)
{
149 150 151 152
    if (old_dir == new_dir or not fileutils::isDirectory(old_dir))
        return;

    if (not fileutils::isDirectory(new_dir)) {
Adrien Béraud's avatar
Adrien Béraud committed
153
        JAMI_WARN() << "Migrating " << old_dir << " to " << new_dir;
154
        std::rename(old_dir.c_str(), new_dir.c_str());
155 156 157 158 159 160 161
    } else {
        for (const auto &file : fileutils::readDirectory(old_dir)) {
            auto old_dest = fileutils::getFullPath(old_dir, file);
            auto new_dest = fileutils::getFullPath(new_dir, file);
            if (fileutils::isDirectory(old_dest) and fileutils::isDirectory(new_dest)) {
                check_rename(old_dest, new_dest);
            } else {
Adrien Béraud's avatar
Adrien Béraud committed
162
                JAMI_WARN() << "Migrating " << old_dest << " to " << new_dest;
163 164 165 166
                std::rename(old_dest.c_str(), new_dest.c_str());
            }
        }
        fileutils::removeAll(old_dir);
167 168 169
    }
}

170 171 172 173 174 175 176 177 178 179 180 181 182 183
/**
 * Set OpenDHT's log level based on the DHTLOGLEVEL environment variable.
 * DHTLOGLEVEL = 0 minimum logging (=disable)
 * DHTLOGLEVEL = 1 (=ERROR only)
 * DHTLOGLEVEL = 2 (+=WARN)
 * DHTLOGLEVEL = 3 maximum logging (+=DEBUG)
 */

/** Environment variable used to set OpenDHT's logging level */
static constexpr const char* DHTLOGLEVEL = "DHTLOGLEVEL";

static void
setDhtLogLevel()
{
184
#ifndef RING_UWP
185 186 187 188 189 190 191 192 193
    char* envvar = getenv(DHTLOGLEVEL);
    int level = 0;

    if (envvar != nullptr) {
        if (not (std::istringstream(envvar) >> level))
            level = 0;

        // From 0 (min) to 3 (max)
        level = std::max(0, std::min(level, 3));
Adrien Béraud's avatar
Adrien Béraud committed
194
        JAMI_DBG("DHTLOGLEVEL=%u", level);
195 196
    }
    Manager::instance().dhtLogLevel = level;
197 198 199
#else
    Manager::instance().dhtLogLevel = 0;
#endif
200 201
}

202 203 204 205 206 207 208 209 210 211 212 213
/**
 * Set pjsip's log level based on the SIPLOGLEVEL environment variable.
 * SIPLOGLEVEL = 0 minimum logging
 * SIPLOGLEVEL = 6 maximum logging
 */

/** Environment variable used to set pjsip's logging level */
static constexpr const char* SIPLOGLEVEL = "SIPLOGLEVEL";

static void
setSipLogLevel()
{
214
#ifndef RING_UWP
215
    char* envvar = getenv(SIPLOGLEVEL);
216

217 218 219 220 221 222 223 224 225
    int level = 0;

    if (envvar != nullptr) {
        if (not (std::istringstream(envvar) >> level))
            level = 0;

        // From 0 (min) to 6 (max)
        level = std::max(0, std::min(level, 6));
    }
226 227 228
#else
    int level = 0;
#endif
229 230

    pj_log_set_level(level);
Adrien Béraud's avatar
Adrien Béraud committed
231
    pj_log_set_log_func([](int level, const char *data, int /*len*/) {
Adrien Béraud's avatar
Adrien Béraud committed
232 233 234
        if      (level < 2) JAMI_ERR() << data;
        else if (level < 4) JAMI_WARN() << data;
        else                JAMI_DBG() << data;
235
    });
236 237 238 239 240 241 242 243 244 245 246 247 248
}

/**
 * Set gnutls's log level based on the RING_TLS_LOGLEVEL environment variable.
 * RING_TLS_LOGLEVEL = 0 minimum logging (default)
 * RING_TLS_LOGLEVEL = 9 maximum logging
 */

static constexpr int RING_TLS_LOGLEVEL = 0;

static void
tls_print_logs(int level, const char* msg)
{
Adrien Béraud's avatar
Adrien Béraud committed
249
    JAMI_XDBG("[%d]GnuTLS: %s", level, msg);
250 251 252 253 254
}

static void
setGnuTlsLogLevel()
{
255
#ifndef RING_UWP
256 257 258 259 260 261 262 263 264 265 266 267 268
    char* envvar = getenv("RING_TLS_LOGLEVEL");
    int level = RING_TLS_LOGLEVEL;

    if (envvar != nullptr) {
        int var_level;
        if (std::istringstream(envvar) >> var_level)
            level = var_level;

        // From 0 (min) to 9 (max)
        level = std::max(0, std::min(level, 9));
    }

    gnutls_global_set_log_level(level);
269 270 271
#else
    gnutls_global_set_log_level(RING_TLS_LOGLEVEL);
#endif
272 273 274
    gnutls_global_set_log_function(tls_print_logs);
}

275 276 277
//==============================================================================

struct Manager::ManagerPimpl
278
{
279
    explicit ManagerPimpl(Manager& base);
280

281
    bool parseConfiguration();
282

283 284 285 286 287
    /*
     * Play one tone
     * @return false if the driver is uninitialize
     */
    void playATone(Tone::TONEID toneId);
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
    int getCurrentDeviceIndex(DeviceType type);

    /**
     * Process remaining participant given a conference and the current call id.
     * Mainly called when a participant is detached or hagned up
     * @param current call id
     * @param conference pointer
     */
    void processRemainingParticipants(Conference &conf);

    /**
     * Create config directory in home user and return configuration file path
     */
    std::string retrieveConfigPath() const;

    void unsetCurrentCall();

    void switchCall(const std::string& id);
    void switchCall(const std::shared_ptr<Call>& call);

    /**
     * Add incoming callid to the waiting list
     * @param id std::string to add
     */
    void addWaitingCall(const std::string& id);

    /**
     * Remove incoming callid to the waiting list
     * @param id std::string to remove
     */
    void removeWaitingCall(const std::string& id);

321
    void loadAccount(const YAML::Node &item, int &errorCount);
322 323 324 325 326 327 328 329 330 331 332 333

    void sendTextMessageToConference(const Conference& conf,
                                     const std::map<std::string, std::string>& messages,
                                     const std::string& from) const noexcept;

    void bindCallToConference(Call& call, Conference& conf);

    template <class T>
    std::shared_ptr<T> findAccount(const std::function<bool(const std::shared_ptr<T>&)>&);

    Manager& base_; // pimpl back-pointer

334 335 336
    /** Main scheduler */
    ScheduledExecutor scheduler_;

337 338
    std::atomic_bool autoAnswer_ {false};

Hugo Lefeuvre's avatar
Hugo Lefeuvre committed
339
    /** Application wide tone controller */
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 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
    ToneControl toneCtrl_;

    /** Current Call ID */
    std::string currentCall_;

    /** Protected current call access */
    std::mutex currentCallMutex_;

    /** Audio layer */
    std::shared_ptr<AudioLayer> audiodriver_{nullptr};

    // Main thread
    std::unique_ptr<DTMF> dtmfKey_;

    /** Buffer to generate DTMF */
    AudioBuffer dtmfBuf_;

    // To handle volume control
    // short speakerVolume_;
    // short micVolume_;
    // End of sound variable

    /**
     * Mutex used to protect audio layer
     */
    std::mutex audioLayerMutex_;

    /**
     * Waiting Call Vectors
     */
    CallIDSet waitingCalls_;

    /**
     * Protect waiting call list, access by many voip/audio threads
     */
    std::mutex waitingCallsMutex_;

    /**
     * Path of the ConfigFile
     */
    std::string path_;

    /**
     * Instance of the RingBufferPool for the whole application
     *
     * In order to send signal to other parts of the application, one must pass through the RingBufferMananger.
     * Audio instances must be registered into the RingBufferMananger and bound together via the Manager.
     *
     */
    std::unique_ptr<RingBufferPool> ringbufferpool_;

    // Map containing conference pointers
    ConferenceMap conferenceMap_;

    std::atomic_bool finished_ {false};

    std::mt19937_64 rand_;

    /* ICE support */
    std::unique_ptr<IceTransportFactory> ice_tf_;

    /* Sink ID mapping */
    std::map<std::string, std::weak_ptr<video::SinkClient>> sinkMap_;
403

Adrien Béraud's avatar
Adrien Béraud committed
404
#ifdef ENABLE_VIDEO
405
    std::unique_ptr<VideoManager> videoManager_;
406
#endif
407 408 409 410 411 412 413 414
};

Manager::ManagerPimpl::ManagerPimpl(Manager& base)
    : base_(base)
    , toneCtrl_(base.preferences)
    , currentCallMutex_()
    , dtmfKey_()
    , dtmfBuf_(0, AudioFormat::MONO())
415
    , audioLayerMutex_()
416 417 418
    , waitingCalls_()
    , waitingCallsMutex_()
    , path_()
419
    , ringbufferpool_(new RingBufferPool)
420 421
    , conferenceMap_()
    , ice_tf_()
Adrien Béraud's avatar
Adrien Béraud committed
422
#ifdef ENABLE_VIDEO
423 424
    , videoManager_(new VideoManager)
#endif
425 426 427
{
    // initialize random generator
    // mt19937_64 should be seeded with 2 x 32 bits
428 429

    random_device rdev;
430 431 432
    std::seed_seq seed {rdev(), rdev()};
    rand_.seed(seed);

Adrien Béraud's avatar
Adrien Béraud committed
433
    jami::libav_utils::ring_avcodec_init();
434 435 436
}

bool
437
Manager::ManagerPimpl::parseConfiguration()
438 439 440 441 442
{
    bool result = true;

    try {
        YAML::Node parsedFile = YAML::LoadFile(path_);
443
        const int error_count = base_.loadAccountMap(parsedFile);
444 445

        if (error_count > 0) {
Adrien Béraud's avatar
Adrien Béraud committed
446
            JAMI_WARN("Errors while parsing %s", path_.c_str());
447 448 449
            result = false;
        }
    } catch (const YAML::BadFile &e) {
Adrien Béraud's avatar
Adrien Béraud committed
450
        JAMI_WARN("Could not open configuration file");
451 452
    }

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    return result;
}

/**
 * Multi Thread
 */
void
Manager::ManagerPimpl::playATone(Tone::TONEID toneId)
{
    if (not base_.voipPreferences.getPlayTones())
        return;

    {
        std::lock_guard<std::mutex> lock(audioLayerMutex_);

        if (not audiodriver_) {
Adrien Béraud's avatar
Adrien Béraud committed
469
            JAMI_ERR("Audio layer not initialized");
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
            return;
        }

        audiodriver_->flushUrgent();
        audiodriver_->startStream();
    }

    toneCtrl_.play(toneId);
}

int
Manager::ManagerPimpl::getCurrentDeviceIndex(DeviceType type)
{
    if (not audiodriver_)
        return -1;
    switch (type) {
        case DeviceType::PLAYBACK:
            return audiodriver_->getIndexPlayback();
        case DeviceType::RINGTONE:
            return audiodriver_->getIndexRingtone();
        case DeviceType::CAPTURE:
            return audiodriver_->getIndexCapture();
        default:
            return -1;
    }
}

void
Manager::ManagerPimpl::processRemainingParticipants(Conference &conf)
{
    const std::string current_call_id(base_.getCurrentCallId());
    ParticipantSet participants(conf.getParticipantList());
    const size_t n = participants.size();
Adrien Béraud's avatar
Adrien Béraud committed
503
    JAMI_DBG("Process remaining %zu participant(s) from conference %s",
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
          n, conf.getConfID().c_str());

    if (n > 1) {
        // Reset ringbuffer's readpointers
        for (const auto &p : participants)
            base_.getRingBufferPool().flush(p);

        base_.getRingBufferPool().flush(RingBufferPool::DEFAULT_ID);
    } else if (n == 1) {
        // this call is the last participant, hence
        // the conference is over
        ParticipantSet::iterator p = participants.begin();

        if (auto call = base_.getCallFromCallID(*p)) {
            call->setConfId("");
            // if we are not listening to this conference
            if (current_call_id != conf.getConfID())
                base_.onHoldCall(call->getCallId());
            else
                switchCall(call);
        }

Adrien Béraud's avatar
Adrien Béraud committed
526
        JAMI_DBG("No remaining participants, remove conference");
527 528
        base_.removeConference(conf.getConfID());
    } else {
Adrien Béraud's avatar
Adrien Béraud committed
529
        JAMI_DBG("No remaining participants, remove conference");
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        base_.removeConference(conf.getConfID());
        unsetCurrentCall();
    }
}

/**
 * Initialization: Main Thread
 */
std::string
Manager::ManagerPimpl::retrieveConfigPath() const
{
    static const char * const PROGNAME = "dring";
    return fileutils::get_config_dir() + DIR_SEPARATOR_STR + PROGNAME + ".yml";
}

void
Manager::ManagerPimpl::unsetCurrentCall()
{
    currentCall_ = "";
}

void
Manager::ManagerPimpl::switchCall(const std::string& id)
{
    std::lock_guard<std::mutex> m(currentCallMutex_);
Adrien Béraud's avatar
Adrien Béraud committed
555
    JAMI_DBG("----- Switch current call id to '%s' -----", not id.empty() ? id.c_str() : "none");
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    currentCall_ = id;
}

void
Manager::ManagerPimpl::switchCall(const std::shared_ptr<Call>& call)
{
    switchCall(call->getCallId());
}

void
Manager::ManagerPimpl::addWaitingCall(const std::string& id)
{
    std::lock_guard<std::mutex> m(waitingCallsMutex_);
    waitingCalls_.insert(id);
}

void
Manager::ManagerPimpl::removeWaitingCall(const std::string& id)
{
    std::lock_guard<std::mutex> m(waitingCallsMutex_);
    waitingCalls_.erase(id);
}

void
580
Manager::ManagerPimpl::loadAccount(const YAML::Node &node, int &errorCount)
581 582 583 584 585 586 587 588 589
{
    using yaml_utils::parseValue;

    std::string accountType;
    parseValue(node, "type", accountType);

    std::string accountid;
    parseValue(node, "id", accountid);

590
    if (!accountid.empty()) {
591
        if (base_.accountFactory.isSupportedType(accountType.c_str())) {
592 593 594
            if (auto a = base_.accountFactory.createAccount(accountType.c_str(), accountid)) {
                a->unserialize(node);
            } else {
Adrien Béraud's avatar
Adrien Béraud committed
595
                JAMI_ERR("Failed to create account type \"%s\"", accountType.c_str());
596 597 598
                ++errorCount;
            }
        } else {
Adrien Béraud's avatar
Adrien Béraud committed
599
            JAMI_WARN("Ignoring unknown account type \"%s\"", accountType.c_str());
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
        }
    }
}

//THREAD=VoIP
void
Manager::ManagerPimpl::sendTextMessageToConference(const Conference& conf,
                                     const std::map<std::string, std::string>& messages,
                                     const std::string& from) const noexcept
{
    ParticipantSet participants(conf.getParticipantList());
    for (const auto& call_id: participants) {
        try {
            auto call = base_.getCallFromCallID(call_id);
            if (not call)
                throw std::runtime_error("no associated call");
            call->sendTextMessage(messages, from);
        } catch (const std::exception& e) {
Adrien Béraud's avatar
Adrien Béraud committed
618
            JAMI_ERR("Failed to send message to conference participant %s: %s",
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
                     call_id.c_str(), e.what());
        }
    }
}

void
Manager::ManagerPimpl::bindCallToConference(Call& call, Conference& conf)
{
    const auto& call_id = call.getCallId();
    const auto& conf_id = conf.getConfID();
    const auto& state = call.getStateStr();

    // ensure that calls are only in one conference at a time
    if (base_.isConferenceParticipant(call_id))
        base_.detachParticipant(call_id);

Adrien Béraud's avatar
Adrien Béraud committed
635
    JAMI_DBG("[call:%s] bind to conference %s (callState=%s)",
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
             call_id.c_str(), conf_id.c_str(), state.c_str());

    base_.getRingBufferPool().unBindAll(call_id);

    conf.add(call_id);
    call.setConfId(conf_id);

    if (state == "HOLD") {
        conf.bindParticipant(call_id);
        base_.offHoldCall(call_id);
    } else if (state == "INCOMING") {
        conf.bindParticipant(call_id);
        base_.answerCall(call_id);
    } else if (state == "CURRENT") {
        conf.bindParticipant(call_id);
    } else if (state == "INACTIVE") {
        conf.bindParticipant(call_id);
        base_.answerCall(call_id);
    } else
Adrien Béraud's avatar
Adrien Béraud committed
655
        JAMI_WARN("[call:%s] call state %s not recognized for conference",
656
                  call_id.c_str(), state.c_str());
657 658 659 660 661 662 663 664 665 666 667 668 669
}

//==============================================================================

Manager&
Manager::instance()
{
    // Meyers singleton
    static Manager instance;

    // This will give a warning that can be ignored the first time instance()
    // is called...subsequent warnings are more serious
    if (not Manager::initialized)
Adrien Béraud's avatar
Adrien Béraud committed
670
        JAMI_DBG("Not initialized");
671 672 673 674 675 676 677 678 679 680

    return instance;
}

Manager::Manager()
    : preferences()
    , voipPreferences()
    , hookPreference()
    , audioPreference()
    , shortcutPreferences()
Adrien Béraud's avatar
Adrien Béraud committed
681
#ifdef ENABLE_VIDEO
682 683 684 685
    , videoPreferences()
#endif
    , callFactory()
    , accountFactory()
686
    , dataTransfers(std::make_unique<DataTransferFacade>())
687 688 689 690 691 692 693 694 695 696
    , pimpl_ (new ManagerPimpl(*this))
{}

Manager::~Manager()
{}

void
Manager::setAutoAnswer(bool enable)
{
    pimpl_->autoAnswer_ = enable;
697 698 699 700 701 702 703 704
}

void
Manager::init(const std::string &config_file)
{
    // FIXME: this is no good
    initialized = true;

705 706 707 708 709 710 711 712 713 714 715
#ifndef WIN32
    // Set the max number of open files.
    struct rlimit nofiles;
    if (getrlimit(RLIMIT_NOFILE, &nofiles) == 0) {
        if (nofiles.rlim_cur < nofiles.rlim_max && nofiles.rlim_cur < 1024u) {
            nofiles.rlim_cur = std::min<rlim_t>(nofiles.rlim_max, 8192u);
            setrlimit(RLIMIT_NOFILE, &nofiles);
        }
    }
#endif

716
#define PJSIP_TRY(ret) do {                                  \
717
        if ((ret) != PJ_SUCCESS)                               \
718 719 720
            throw std::runtime_error(#ret " failed");        \
    } while (0)

721
    srand(time(nullptr)); // to get random number for RANDOM_PORT
722 723 724 725 726 727

    // Initialize PJSIP (SIP and ICE implementation)
    PJSIP_TRY(pj_init());
    setSipLogLevel();
    PJSIP_TRY(pjlib_util_init());
    PJSIP_TRY(pjnath_init());
728
#undef PJSIP_TRY
729 730

    setGnuTlsLogLevel();
731 732 733 734

    JAMI_DBG("Using PJSIP version %s for %s", pj_get_version(), PJ_OS_NAME);
    JAMI_DBG("Using GnuTLS version %s", gnutls_check_version(nullptr));
    JAMI_DBG("Using OpenDHT version %s", dht::version());
735

736 737
    setDhtLogLevel();

738 739 740 741
    check_rename(fileutils::get_cache_dir(PACKAGE_OLD), fileutils::get_cache_dir());
    check_rename(fileutils::get_data_dir(PACKAGE_OLD), fileutils::get_data_dir());
    check_rename(fileutils::get_config_dir(PACKAGE_OLD), fileutils::get_config_dir());

742
    pimpl_->ice_tf_.reset(new IceTransportFactory());
743

744
    pimpl_->path_ = config_file.empty() ? pimpl_->retrieveConfigPath() : config_file;
Adrien Béraud's avatar
Adrien Béraud committed
745
    JAMI_DBG("Configuration file path: %s", pimpl_->path_.c_str());
746 747 748 749

    bool no_errors = true;

    // manager can restart without being recreated (android)
750
    pimpl_->finished_ = false;
751 752

    try {
753
        no_errors = pimpl_->parseConfiguration();
754
    } catch (const YAML::Exception &e) {
Adrien Béraud's avatar
Adrien Béraud committed
755
        JAMI_ERR("%s", e.what());
756 757 758 759 760
        no_errors = false;
    }

    // always back up last error-free configuration
    if (no_errors) {
761
        make_backup(pimpl_->path_);
762 763
    } else {
        // restore previous configuration
Adrien Béraud's avatar
Adrien Béraud committed
764
        JAMI_WARN("Restoring last working configuration");
765

766 767 768
        // keep a reference to sipvoiplink while destroying the accounts
        const auto sipvoiplink = getSIPVoIPLink();

769 770 771
        try {
            // remove accounts from broken configuration
            removeAccounts();
772 773
            restore_backup(pimpl_->path_);
            pimpl_->parseConfiguration();
774
        } catch (const YAML::Exception &e) {
Adrien Béraud's avatar
Adrien Béraud committed
775 776
            JAMI_ERR("%s", e.what());
            JAMI_WARN("Restoring backup failed");
777 778 779 780 781 782
        }
    }

    initAudioDriver();

    {
783
        std::lock_guard<std::mutex> lock(pimpl_->audioLayerMutex_);
784

785 786 787
        if (pimpl_->audiodriver_) {
            pimpl_->toneCtrl_.setSampleRate(pimpl_->audiodriver_->getSampleRate());
            pimpl_->dtmfKey_.reset(new DTMF(getRingBufferPool().getInternalSamplingRate()));
788 789 790 791 792 793 794 795 796 797
        }
    }

    registerAccounts();
}

void
Manager::finish() noexcept
{
    bool expected = false;
798
    if (not pimpl_->finished_.compare_exchange_strong(expected, true))
799 800 801 802 803 804 805
        return;

    try {
        // Forbid call creation
        callFactory.forbid();

        // Hangup all remaining active calls
Adrien Béraud's avatar
Adrien Béraud committed
806
        JAMI_DBG("Hangup %zu remaining call(s)", callFactory.callCount());
807 808 809 810
        for (const auto call : callFactory.getAllCalls())
            hangupCall(call->getCallId());
        callFactory.clear();

811
        for (const auto &account : getAllAccounts<JamiAccount>()) {
812 813 814 815
            if (account->getRegistrationState() == RegistrationState::INITIALIZING)
                removeAccount(account->getAccountID());
        }

816 817 818 819
        saveConfig();

        // Disconnect accounts, close link stacks and free allocated ressources
        unregisterAccounts();
820
        accountFactory.clear();
821 822

        {
823
            std::lock_guard<std::mutex> lock(pimpl_->audioLayerMutex_);
824

825
            pimpl_->audiodriver_.reset();
826 827
        }

828
        pimpl_->ice_tf_.reset();
829 830

        // Flush remaining tasks (free lambda' with capture)
831
        pimpl_->scheduler_.stop();
Adrien Béraud's avatar
Adrien Béraud committed
832 833
        dht::ThreadPool::io().join();
        dht::ThreadPool::computation().join();
834

835 836
        pj_shutdown();
    } catch (const VoipLinkException &err) {
Adrien Béraud's avatar
Adrien Béraud committed
837
        JAMI_ERR("%s", err.what());
838 839 840 841 842 843
    }
}

bool
Manager::isCurrentCall(const Call& call) const
{
844
    return pimpl_->currentCall_ == call.getCallId();
845 846 847 848 849
}

bool
Manager::hasCurrentCall() const
{
850
    return not pimpl_->currentCall_.empty();
851 852 853 854 855
}

std::shared_ptr<Call>
Manager::getCurrentCall() const
{
856
    return getCallFromCallID(pimpl_->currentCall_);
857 858
}

859
const std::string&
860 861
Manager::getCurrentCallId() const
{
862
    return pimpl_->currentCall_;
863 864 865
}

void
866
Manager::unregisterAccounts()
867
{
868 869 870
    for (const auto& account : getAllAccounts()) {
        if (account->isEnabled())
            account->doUnregister();
871 872 873
    }
}

874 875 876 877 878 879
///////////////////////////////////////////////////////////////////////////////
// Management of events' IP-phone user
///////////////////////////////////////////////////////////////////////////////
/* Main Thread */

std::string
880
Manager::outgoingCall(const std::string& account_id,
881
                          const std::string& to,
882 883
                          const std::string& conf_id,
                          const std::map<std::string, std::string>& volatileCallDetails)
884
{
885
    if (not conf_id.empty() and not isConference(conf_id)) {
Adrien Béraud's avatar
Adrien Béraud committed
886
        JAMI_ERR("outgoingCall() failed, invalid conference id");
887 888 889
        return {};
    }

Adrien Béraud's avatar
Adrien Béraud committed
890
    JAMI_DBG() << "try outgoing call to '" << to << "'"
891
               << " with account '" << account_id << "'";
892

893
    const auto& current_call_id(getCurrentCallId());
894
    std::string to_cleaned = hookPreference.getNumberAddPrefix() + trim(to);
895 896 897
    std::shared_ptr<Call> call;

    try {
898
        call = newOutgoingCall(to_cleaned, account_id, volatileCallDetails);
899
    } catch (const std::exception &e) {
Adrien Béraud's avatar
Adrien Béraud committed
900
        JAMI_ERR("%s", e.what());
901 902 903 904 905 906 907 908 909 910 911 912
        return {};
    }

    if (not call)
        return {};

    auto call_id = call->getCallId();

    stopTone();

    // in any cases we have to detach from current communication
    if (hasCurrentCall()) {
Adrien Béraud's avatar
Adrien Béraud committed
913
        JAMI_DBG("Has current call (%s) put it onhold", current_call_id.c_str());
914

915
        bool isConf = isConference(current_call_id);
916
        // if this is not a conference and this and is not a conference participant
917
        if (not isConf and not isConferenceParticipant(current_call_id))
918
            onHoldCall(current_call_id);
919
        else if (isConf and not isConferenceParticipant(call_id))
920
            detachLocalParticipant();
921 922
    }

923
    pimpl_->switchCall(call);
924 925 926 927 928 929 930 931 932 933 934 935 936
    call->setConfId(conf_id);

    return call_id;
}

//THREAD=Main : for outgoing Call
bool
Manager::answerCall(const std::string& call_id)
{
    bool result = true;

    auto call = getCallFromCallID(call_id);
    if (!call) {
Adrien Béraud's avatar
Adrien Béraud committed
937
        JAMI_ERR("Call %s is NULL", call_id.c_str());
938 939 940 941 942 943 944
        return false;
    }

    // If ring is ringing
    stopTone();

    // store the current call id
945
    const auto& current_call_id(getCurrentCallId());
946 947

    // in any cases we have to detach from current communication
948
    if (hasCurrentCall() and call_id != current_call_id) {
949

Adrien Béraud's avatar
Adrien Béraud committed
950
        JAMI_DBG("Currently conversing with %s", current_call_id.c_str());
951

952 953
        bool isConf = isConference(current_call_id);
        if (not isConf and not isConferenceParticipant(current_call_id)) {
Adrien Béraud's avatar
Adrien Béraud committed
954
            JAMI_DBG("Answer call: Put the current call (%s) on hold", current_call_id.c_str());
955
            onHoldCall(current_call_id);
956
        } else if (isConf and not isConferenceParticipant(call_id)) {
957
            // if we are talking to a conference and we are answering an incoming call
Adrien Béraud's avatar
Adrien Béraud committed
958
            JAMI_DBG("Detach main participant from conference");
959
            detachLocalParticipant();
960 961 962 963 964 965
        }
    }

    try {
        call->answer();
    } catch (const std::runtime_error &e) {
Adrien Béraud's avatar
Adrien Béraud committed
966
        JAMI_ERR("%s", e.what());
967 968 969 970
        result = false;
    }

    // if it was waiting, it's waiting no more
971
    pimpl_->removeWaitingCall(call_id);
972

973 974 975 976 977
    if (!result) {
        // do not switch to this call if it was not properly started
        return false;
    }

978 979
    // if we dragged this call into a conference already
    if (isConferenceParticipant(call_id))
980
        pimpl_->switchCall(call->getConfId());
981
    else
982
        pimpl_->switchCall(call);
983

984
    addAudio(*call);
985 986 987 988 989 990 991

    return result;
}

void
Manager::checkAudio()
{
992
    // FIXME dirty, the manager should not need to be aware of local recorders
993
    if (getCallList().empty()
Adrien Béraud's avatar
Adrien Béraud committed
994
#ifdef ENABLE_VIDEO
995 996
        and not getVideoManager().audioPreview
#endif
Adrien Béraud's avatar
Adrien Béraud committed
997
        and not jami::LocalRecorderManager::instance().hasRunningRecorders()) {
998 999 1000
        std::lock_guard<std::mutex> lock(pimpl_->audioLayerMutex_);
        if (pimpl_->audiodriver_)
            pimpl_->audiodriver_->stopStream();
1001 1002 1003 1004 1005 1006 1007 1008
    }
}

//THREAD=Main
bool
Manager::hangupCall(const std::string& callId)
{
    // store the current call id
1009
    const auto& currentCallId(getCurrentCallId());
1010 1011 1012 1013 1014 1015

    stopTone();

    /* We often get here when the call was hungup before being created */
    auto call = getCallFromCallID(callId);
    if (not call) {
Adrien Béraud's avatar
Adrien Béraud committed
1016
        JAMI_WARN("Could not hang up non-existant call %s", callId.c_str());
1017 1018 1019 1020 1021
        checkAudio();
        return false;
    }

    // Disconnect streams
1022
    removeAudio(*call);
1023 1024 1025 1026 1027

    if (isConferenceParticipant(callId)) {
        removeParticipant(callId);
    } else {
        // we are not participating in a conference, current call switched to ""
1028
        if (not isConference(currentCallId) and isCurrentCall(*call))
1029
            pimpl_->unsetCurrentCall();
1030 1031 1032 1033 1034 1035
    }

    try {
        call->hangup(0);
        checkAudio();
    } catch (const VoipLinkException &e) {
Adrien Béraud's avatar
Adrien Béraud committed
1036
        JAMI_ERR("%s", e.what());
1037 1038 1039 1040 1041 1042 1043 1044 1045
        return false;
    }

    return true;
}

bool
Manager::hangupConference(const std::string& id)
{
Adrien Béraud's avatar
Adrien Béraud committed
1046
    JAMI_DBG("Hangup conference %s", id.c_str());
1047

1048
    ConferenceMap::iterator iter_conf = pimpl_->conferenceMap_.find(id);
1049

1050
    if (iter_conf != pimpl_->conferenceMap_.end()) {
1051 1052 1053 1054 1055 1056 1057 1058
        auto conf = iter_conf->second;

        if (conf) {
            ParticipantSet participants(conf->getParticipantList());

            for (const auto &item : participants)
                hangupCall(item);
        } else {
Adrien Béraud's avatar
Adrien Béraud committed
1059
            JAMI_ERR("No such conference %s", id.c_str());
1060 1061 1062 1063
            return false;
        }
    }

1064
    pimpl_->unsetCurrentCall();
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

    return true;
}

//THREAD=Main
bool
Manager::onHoldCall(const std::string& callId)
{
    bool result = true;

    stopTone();

    std::string current_call_id(getCurrentCallId());

    if (auto call = getCallFromCallID(callId)) {
        try {
1081 1082
            result = call->onhold();
            if (result)
1083
                removeAudio(*call); // Unbind calls in main buffer
1084
        } catch (const VoipLinkException &e) {
Adrien Béraud's avatar
Adrien Béraud committed
1085
            JAMI_ERR("%s", e.what());
1086 1087
            result = false;
        }
1088

1089
    } else {
Adrien Béraud's avatar
Adrien Béraud committed
1090
        JAMI_DBG("CallID %s doesn't exist in call onHold", callId.c_str());
1091 1092 1093
        return false;
    }

1094 1095
    if (result) {
        // Remove call from the queue if it was still there
1096
        pimpl_->removeWaitingCall(callId);
1097

1098 1099 1100
        // keeps current call id if the action is not holding this call
        // or a new outgoing call. This could happen in case of a conference
        if (current_call_id == callId)
1101
            pimpl_->unsetCurrentCall();
1102
    }
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114

    return result;
}

//THREAD=Main
bool
Manager::offHoldCall(const std::string& callId)
{
    bool result = true;

    stopTone();

1115
    const auto& currentCallId = getCurrentCallId();
1116
    // Place current call on hold if it isn't
1117
    if (hasCurrentCall() and currentCallId != callId) {
1118 1119
        bool isConf = isConference(currentCallId);
        if (not isConf and not isConferenceParticipant(currentCallId)) {
Adrien Béraud's avatar
Adrien Béraud committed
1120
            JAMI_DBG("Has current call (%s), put on hold", currentCallId.c_str());
1121
            onHoldCall(currentCallId);
1122
        } else if (isConf and not isConferenceParticipant(callId)) {
1123
            holdConference(currentCallId);
1124
            detachLocalParticipant();
1125
        }
1126 1127
    }

1128 1129 1130 1131
    std::shared_ptr<Call> call = getCallFromCallID(callId);
    if (!call)
        return false;

1132
    try {
1133
        result = call->offhold();
1134
    } catch (const VoipLinkException &e) {
Adrien Béraud's avatar
Adrien Béraud committed
1135
        JAMI_ERR("%s", e.what());
1136 1137 1138
        return false;
    }

1139 1140
    if (result) {
        if (isConferenceParticipant(callId))
1141
            pimpl_->switchCall(call->getConfId());
1142
        else
1143
            pimpl_->switchCall(call);
1144

1145
        addAudio(*call);
1146
    }
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

    return result;
}

bool
Manager::muteMediaCall(const std::string& callId, const std::string& mediaType, bool is_muted)
{
    if (auto call = getCallFromCallID(callId)) {
        call->muteMedia(mediaType, is_muted);
        return true;
    } else {
Adrien Béraud's avatar
Adrien Béraud committed
1158
        JAMI_DBG("CallID %s doesn't exist in call muting", callId.c_str());
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        return false;
    }
}

//THREAD=Main
bool
Manager::transferCall(const std::string& callId, const std::string& to)
{
    if (isConferenceParticipant(callId)) {
        removeParticipant(callId);
    } else if (not isConference(getCurrentCallId()))
1170
        pimpl_->unsetCurrentCall();
1171 1172 1173 1174 1175 1176 1177

    if (auto call = getCallFromCallID(callId))
        call->transfer(to);
    else
        return false;

    // remove waiting call in case we make transfer without even answer
1178
    pimpl_->removeWaitingCall(callId);
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

    return true;
}

void
Manager::transferFailed()
{
    emitSignal<DRing::CallSignal::TransferFailed>();
}

void
Manager::transferSucceeded()
{
Adrien Béraud's avatar
Adrien Béraud committed
1192
    emitSignal<DRing::CallSignal::TransferSucceeded>();
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
}

bool
Manager::attendedTransfer(const std::string& transferID,
                              const std::string& targetID)
{
    if (auto call = getCallFromCallID(transferID))
        return call->attendedTransfer(targetID);

    return false;
}

//THREAD=Main : Call:Incoming
bool
Manager::refuseCall(const std::string& id)
{
    auto call = getCallFromCallID(id);
    if (!call)
        return false;

    stopTone();

    call->refuse();

    checkAudio();

1219
    pimpl_->removeWaitingCall(id);
1220 1221

    // Disconnect streams
1222
    removeAudio(*call);
1223 1224 1225 1226 1227 1228 1229

    return true;
}

void
Manager::removeConference(const std::string& conference_id)
{
Adrien Béraud's avatar
Adrien Béraud committed
1230 1231
    JAMI_DBG("Remove conference %s", conference_id.c_str());
    JAMI_DBG("number of participants: %zu", pimpl_->conferenceMap_.size());
1232
    ConferenceMap::iterator iter = pimpl_->conferenceMap_.find(conference_id);
1233 1234 1235

    std::shared_ptr<Conference> conf;

1236
    if (iter != pimpl_->conferenceMap_.end())
1237 1238 1239
        conf = iter->second;

    if (not conf) {
Adrien Béraud's avatar
Adrien Béraud committed
1240
        JAMI_ERR("Conference not found");
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
        return;
    }

    emitSignal<DRing::CallSignal::ConferenceRemoved>(conference_id);

    // We now need to bind the audio to the remain participant

    // Unbind main participant audio from conference
    getRingBufferPool().unBindAll(RingBufferPool::DEFAULT_ID);

    ParticipantSet participants(conf->getParticipantList());

    // bind main participant audio to remaining conference call
    ParticipantSet::iterator iter_p = participants.begin();

    if (iter_p != participants.end())
        getRingBufferPool().bindCallID(*iter_p, RingBufferPool::DEFAULT_ID);

    // Then remove the conference from the conference map
1260
    if (pimpl_->conferenceMap_.erase(conference_id))
Adrien Béraud's avatar
Adrien Béraud committed
1261
        JAMI_DBG("Conference %s removed successfully", conference_id.c_str());
1262
    else
Adrien Béraud's avatar
Adrien Béraud committed
1263
        JAMI_ERR("Cannot remove conference: %s", conference_id.c_str());
1264 1265 1266 1267 1268 1269 1270 1271 1272
}

std::shared_ptr<Conference>
Manager::getConferenceFromCallID(const std::string& call_id)
{
    auto call = getCallFromCallID(call_id);
    if (!call)
        return nullptr;

1273
    ConferenceMap::const_iterator iter(pimpl_->conferenceMap_.find(call->getConfId()));
1274

1275
    if (iter != pimpl_->conferenceMap_.end())
1276 1277 1278 1279 1280 1281 1282 1283
        return iter->second;
    else
        return nullptr;
}

bool
Manager::holdConference(const std::string& id)
{
1284
    ConferenceMap::iterator iter_conf = pimpl_->conferenceMap_.find(id);
1285

1286
    if (iter_conf == pimpl_->conferenceMap_.end())
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
        return false;

    auto conf = iter_conf->second;

    bool isRec = conf->getState() == Conference::ACTIVE_ATTACHED_REC or
                 conf->getState() == Conference::ACTIVE_DETACHED_REC or
                 conf->getState() == Conference::HOLD_REC;

    ParticipantSet participants(conf->getParticipantList());

    for (const auto &item : participants) {
1298
        pimpl_->switchCall(getCallFromCallID(item));
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
        onHoldCall(item);
    }

    conf->setState(isRec ? Conference::HOLD_REC : Conference::HOLD);

    emitSignal<DRing::CallSignal::ConferenceChanged>(conf->getConfID(), conf->getStateStr());

    return true;
}

bool
Manager::unHoldConference(const std::string& id)
{
1312
    ConferenceMap::iterator iter_conf = pimpl_->conferenceMap_.find(id);
1313

1314
    if (iter_conf == pimpl_->conferenceMap_.end() or iter_conf->second == 0)
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
        return false;

    auto conf = iter_conf->second;

    bool isRec = conf->getState() == Conference::ACTIVE_ATTACHED_REC or
        conf->getState() == Conference::ACTIVE_DETACHED_REC or
        conf->getState() == Conference::HOLD_REC;

    ParticipantSet participants(conf->getParticipantList());

    for (const auto &item : participants) {
        if (auto call = getCallFromCallID(item)) {
            // if one call is currently recording, the conference is in state recording
            isRec |= call->isRecording();

1330
            pimpl_->switchCall(call);
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
            offHoldCall(item);
        }
    }

    conf->setState(isRec ? Conference::ACTIVE_ATTACHED_REC : Conference::ACTIVE_ATTACHED);

    emitSignal<DRing::CallSignal::ConferenceChanged>(conf->getConfID(), conf->getStateStr());

    return true;
}

bool
Manager::isConference(const std::string& id) const
{
1345
    return pimpl_->conferenceMap_.find(id) != pimpl_->conferenceMap_.end();
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
}

bool
Manager::isConferenceParticipant(const std::string& call_id)
{
    auto call = getCallFromCallID(call_id);
    return call and not call->getConfId().empty();
}

bool
Manager::addParticipant(const std::string& callId,
1357
                        const std::string& conferenceId)
1358
{
1359 1360
    auto iter = pimpl_->conferenceMap_.find(conferenceId);
    if (iter == pimpl_->conferenceMap_.end() or iter->second == nullptr) {
Adrien Béraud's avatar
Adrien Béraud committed
1361
        JAMI_ERR("Conference id is not valid");
1362 1363 1364 1365 1366
        return false;
    }

    auto call = getCallFromCallID(callId);
    if (!call) {
Adrien Béraud's avatar
Adrien Béraud committed
1367
        JAMI_ERR("Call id %s is not valid", callId.c_str());
1368 1369 1370
        return false;
    }

1371 1372
    // No-op if the call is already a conference participant
    if (call->getConfId() == conferenceId) {
Adrien Béraud's avatar
Adrien Béraud committed
1373
        JAMI_WARN("Call %s already participant of conf %s", callId.c_str(), conferenceId.c_str());
1374 1375 1376
        return true;
    }

Adrien Béraud's avatar
Adrien Béraud committed
1377
    JAMI_DBG("Add participant %s to %s", callId.c_str(), conferenceId.c_str());
1378

1379
    // store the current call id (it will change in offHoldCall or in answerCall)
1380
    auto current_call_id = getCurrentCallId();
1381 1382 1383 1384

    // detach from prior communication and switch to this conference
    if (current_call_id != callId) {
        if (isConference(current_call_id))
1385
            detachLocalParticipant();
1386 1387 1388 1389
        else
            onHoldCall(current_call_id);
    }

1390
    pimpl_->bindCallToConference(*call, *iter->second);
1391

1392 1393 1394
    // TODO: remove this ugly hack => There should be different calls when double clicking
    // a conference to add main participant to it, or (in this case) adding a participant
    // toconference
1395
    pimpl_->unsetCurrentCall();
1396 1397

    addMainParticipant(conferenceId);
1398
    pimpl_->switchCall(conferenceId);
1399
    addAudio(*call);
1400

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
    return true;
}

bool
Manager::addMainParticipant(const std::string& conference_id)
{
    if (hasCurrentCall()) {
        std::string current_call_id(getCurrentCallId());

        if (isConference(current_call_id))
1411
            detachLocalParticipant();
1412 1413 1414 1415 1416
        else
            onHoldCall(current_call_id);
    }

    {
1417
        std::lock_guard<std::mutex> lock(pimpl_->audioLayerMutex_);
1418

1419
        ConferenceMap::const_iterator iter = pimpl_->conferenceMap_.find(conference_id);
1420

1421
        if (iter == pimpl_->conferenceMap_.end() or iter->second == 0)
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
            return false;

        auto conf = iter->second;

        ParticipantSet participants(conf->getParticipantList());

        for (const auto &item_p : participants) {
            getRingBufferPool().bindCallID(item_p, RingBufferPool::DEFAULT_ID);
            // Reset ringbuffer's readpointers
            getRingBufferPool().flush(item_p);
        }

        getRingBufferPool().flush(RingBufferPool::DEFAULT_ID);

        if (conf->getState() == Conference::ACTIVE_DETACHED)
            conf->setState(Conference::ACTIVE_ATTACHED);
        else if (conf->getState() == Conference::ACTIVE_DETACHED_REC)
            conf->setState(Conference::ACTIVE_ATTACHED_REC);
        else
Adrien Béraud's avatar
Adrien Béraud committed
1441
            JAMI_WARN("Invalid conference state while adding main participant");
1442 1443 1444 1445

        emitSignal<DRing::CallSignal::ConferenceChanged>(conference_id, conf->getStateStr());
    }

1446
    pimpl_->switchCall(conference_id);
1447 1448 1449 1450
    return true;
}

std::shared_ptr<Call>
1451
Manager::getCallFromCallID(const std::string& callID) const
1452 1453 1454 1455 1456
{
    return callFactory.getCall(callID);
}

bool
1457
Manager::joinParticipant(const std::string& callId1, const std::string& callId2)
1458 1459
{
    if (callId1 == callId2) {
Adrien Béraud's avatar
Adrien Béraud committed
1460
        JAMI_ERR("Cannot join participant %s to itself", callId1.c_str());
1461 1462 1463 1464 1465 1466
        return false;
    }

    // Set corresponding conference ids for call 1
    auto call1 = getCallFromCallID(callId1);
    if (!call1) {
Adrien Béraud's avatar
Adrien Béraud committed
1467
        JAMI_ERR("Could not find call %s", callId1.c_str());
1468 1469 1470 1471 1472 1473
        return false;
    }

    // Set corresponding conderence details
    auto call2 = getCallFromCallID(callId2);
    if (!call2) {
Adrien Béraud's avatar
Adrien Béraud committed
1474
        JAMI_ERR("Could not find call %s", callId2.c_str());
1475 1476 1477
        return false;
    }

1478 1479
    // detach/hold current active call if it's not a participant
    auto current_call_id = getCurrentCallId();
1480 1481
    if ((current_call_id != callId1) and (current_call_id != callId2)) {
        if (isConference(current_call_id))
1482
            detachLocalParticipant();
1483 1484 1485 1486
        else
            onHoldCall(current_call_id); // currently in a call
    }

1487
    auto conf = std::make_shared<Conference>();
1488

1489
    // Bind calls according to their state
1490 1491
    pimpl_->bindCallToConference(*call1, *conf);
    pimpl_->bindCallToConference(*call2, *conf);
1492 1493

    // Switch current call id to this conference
1494
    pimpl_->switchCall(conf->getConfID());
1495 1496
    conf->setState(Conference::ACTIVE_ATTACHED);

1497
    pimpl_->conferenceMap_.insert(std::make_pair(conf->getConfID(), conf));
1498
    emitSignal<DRing::CallSignal::ConferenceCreated>(conf->getConfID());
1499 1500 1501 1502 1503 1504 1505 1506
    return true;
}

void
Manager::createConfFromParticipantList(const std::vector< std::string > &participantList)
{
    // we must at least have 2 participant for a conference
    if (participantList.size() <= 1) {
Adrien Béraud's avatar
Adrien Béraud committed
1507
        JAMI_ERR("Participant number must be higher or equal to 2");
1508 1509 1510 1511 1512 1513 1514
        return;
    }

    auto conf = std::make_shared<Conference>();

    int successCounter = 0;

Adrien Béraud's avatar
Adrien Béraud committed
1515 1516 1517
    for (const auto& numberaccount : participantList) {
        std::string tostr(numberaccount.substr(0, numberaccount.find(',')));
        std::string account(numberaccount.substr(numberaccount.find(',') + 1, numberaccount.size()));
1518

1519
        pimpl_->unsetCurrentCall();
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534

        // Create call
        auto call_id = outgoingCall(account, tostr, conf->getConfID());
        if (call_id.empty())
            continue;

        // Manager methods may behave differently if the call id participates in a conference
        conf->add(call_id);

        emitSignal<DRing::CallSignal::NewCallCreated>(account, call_id, tostr);
        successCounter++;
    }

    // Create the conference if and only if at least 2 calls have been successfully created
    if (successCounter >= 2) {
1535
        pimpl_->conferenceMap_[conf->getConfID()] = conf;
1536 1537 1538 1539 1540
        emitSignal<DRing::CallSignal::ConferenceCreated>(conf->getConfID());
    }
}