conference.cc 51.7 KB
Newer Older
Simon Morlat's avatar
Simon Morlat committed
1 2 3 4 5 6 7 8 9
/*
 * Copyright (c) 2010-2019 Belledonne Communications SARL.
 *
 * This file is part of Liblinphone.
 *
 * 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.
10
 *
Simon Morlat's avatar
Simon Morlat committed
11 12 13 14 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
19

20
#include <algorithm>
21
#include <list>
22
#include <string>
23 24 25 26 27 28 29 30 31
#include <typeinfo>

#include <mediastreamer2/msvolume.h>

#include "linphone/core.h"

#include "conference_private.h"

#include "c-wrapper/c-wrapper.h"
32
#include "call/call.h"
Andrea Gianarda's avatar
Andrea Gianarda committed
33
#include "c-wrapper/internal/c-tools.h"
Ghislain MARY's avatar
Ghislain MARY committed
34 35
#include "conference/params/media-session-params-p.h"
#include "core/core-p.h"
Andrea Gianarda's avatar
Andrea Gianarda committed
36 37 38
#include "conference/notify-conference-listener.h"
#include "conference/conference.h"
#include "conference/participant.h"
Simon Morlat's avatar
Simon Morlat committed
39 40 41
#include "conference/session/mixers.h"
#include "conference/session/ms2-streams.h"
#include "conference/session/media-session.h"
Andrea Gianarda's avatar
Andrea Gianarda committed
42 43 44 45 46 47
#ifdef HAVE_ADVANCED_IM
#include "conference/handlers/local-audio-video-conference-event-handler.h"
#include "conference/handlers/local-conference-event-handler.h"
#include "conference/handlers/remote-conference-event-handler.h"
#include "conference/handlers/remote-conference-list-event-handler.h"
#endif // HAVE_ADVANCED_IM
48

49

50 51 52
// TODO: From coreapi. Remove me later.
#include "private.h"

53 54
using namespace std;

Simon Morlat's avatar
Simon Morlat committed
55
LINPHONE_BEGIN_NAMESPACE
56

Simon Morlat's avatar
Simon Morlat committed
57
namespace MediaConference{
58

59

Andrea Gianarda's avatar
Andrea Gianarda committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
Conference::Conference(
	const shared_ptr<Core> &core,
	const IdentityAddress &myAddress,
	CallSessionListener *listener,
	const std::shared_ptr<LinphonePrivate::ConferenceParams> params) :
	LinphonePrivate::Conference(core, myAddress, listener, params)
	{

	addListener(std::make_shared<NotifyConferenceListener>(this));
	setState(ConferenceInterface::State::Instantiated);

	// Video is already enable in the conference params constructor
	confParams->enableAudio(true);

}

Conference::~Conference() {
	bctbx_list_free_with_data(mCallbacks, (void(*)(void *))belle_sip_object_unref);
78 79
}

Andrea Gianarda's avatar
Andrea Gianarda committed
80
void Conference::setConferenceAddress (const ConferenceAddress &conferenceAddress) {
81 82 83 84 85 86 87 88 89 90
	if ((getState() == ConferenceInterface::State::Instantiated) || (getState() == ConferenceInterface::State::CreationPending)) {
		if (!conferenceAddress.isValid()) {
			shared_ptr<CallSession> session = getMe()->getSession();
			LinphoneErrorInfo *ei = linphone_error_info_new();
			linphone_error_info_set(ei, "SIP", LinphoneReasonUnknown, 500, "Server internal error", NULL);
			session->decline(ei);
			linphone_error_info_unref(ei);
			setState(ConferenceInterface::State::CreationFailed);
			return;
		}
Andrea Gianarda's avatar
Andrea Gianarda committed
91

92 93 94
		LinphonePrivate::Conference::setConferenceAddress(conferenceAddress);
		lInfo() << "The Conference has been given the address " << conferenceAddress.asString() << ", now finalizing its creation";
	} else {
Andrea Gianarda's avatar
Andrea Gianarda committed
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
		lError() << "Cannot set the conference address of the Conference in state " << getState();
		return;
	}

}

void Conference::setConferenceId (const ConferenceId &conferenceId) {
	LinphonePrivate::Conference::setConferenceId(conferenceId);
	getCore()->insertAudioVideoConference(getSharedFromThis());
}

bool Conference::addParticipant (const IdentityAddress &participantAddress) {
	bool success = LinphonePrivate::Conference::addParticipant(participantAddress);

	if (success == true) {
		time_t creationTime = time(nullptr);
		std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(participantAddress);
		notifyParticipantAdded(creationTime, false, p);
	}

115 116 117
	return 0;
}

Andrea Gianarda's avatar
Andrea Gianarda committed
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

bool Conference::addParticipant (std::shared_ptr<LinphonePrivate::Call> call) {
	const Address &remoteAddress = *call->getRemoteAddress();
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(remoteAddress);
	// Add a new participant only if it is not in the conference
	if (p == nullptr) {
		p = Participant::create(this,remoteAddress, call->getActiveSession());
		p->setFocus(remoteAddress == getConferenceAddress());
		p->setPreserveSession(true);
		participants.push_back(p);
	}

	_linphone_call_set_conf_ref(call->toC(), toC());
	bool success = addParticipantDevice(call);

	if (success) {
		time_t creationTime = time(nullptr);
		notifyParticipantAdded(creationTime, false, p);
	}
	return success;
}

bool Conference::addParticipantDevice(std::shared_ptr<LinphonePrivate::Call> call) {
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(call->getActiveSession());
	if (p) {
		const Address * remoteContact = static_pointer_cast<MediaSession>(call->getActiveSession())->getRemoteContactAddress();
		if (remoteContact) {
			// If device is not found, then add it
146
			if (p->findDevice(*remoteContact, false) == nullptr) {
Andrea Gianarda's avatar
Andrea Gianarda committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
				lInfo() << "Adding device with address " << remoteContact->asString() << " to participant " << p.get();
				shared_ptr<ParticipantDevice> device = p->addDevice(*remoteContact);
				_linphone_call_set_conf_ref(call->toC(), toC());
				device->setSession(call->getActiveSession());

				time_t creationTime = time(nullptr);
				notifyParticipantDeviceAdded(creationTime, false, p, device);

				return true;
			}
		}
	}

	return false;
}

int Conference::removeParticipantDevice(const std::shared_ptr<LinphonePrivate::CallSession> & session) {
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(session);
	if (p) {
		const Address * remoteContact = static_pointer_cast<MediaSession>(session)->getRemoteContactAddress();
		if (remoteContact) {
			std::shared_ptr<ParticipantDevice> device = p->findDevice(*remoteContact);
			// If device is not found, then add it
			if (device != nullptr) {

				LinphoneEvent * event = device->getConferenceSubscribeEvent();
				if (event) {
					//try to terminate subscription if any, but do not wait for anser.
					LinphoneEventCbs *cbs = linphone_event_get_callbacks(event);
					linphone_event_cbs_set_user_data(cbs, nullptr);
					linphone_event_cbs_set_notify_response(cbs, nullptr);
					linphone_event_terminate(event);
				}

				lInfo() << "Removing device with address " << remoteContact->asString() << " to participant " << p.get();
				p->removeDevice(*remoteContact);
				shared_ptr<Call> call = getCore()->getCallByRemoteAddress (*session->getRemoteAddress());
				if (call) {
					call->removeFromConference(*remoteContact);
				}

				time_t creationTime = time(nullptr);
				notifyParticipantDeviceRemoved(creationTime, false, p, device);

				return 0;
			}
		}
	}

	return -1;
}

int Conference::removeParticipant (std::shared_ptr<LinphonePrivate::Call> call) {
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(call->getActiveSession());
Ghislain MARY's avatar
Ghislain MARY committed
201 202
	if (!p)
		return -1;
Andrea Gianarda's avatar
Andrea Gianarda committed
203
	return removeParticipant(p);
204 205
}

Andrea Gianarda's avatar
Andrea Gianarda committed
206 207 208
int Conference::removeParticipant (const std::shared_ptr<LinphonePrivate::CallSession> & session, const bool preserveSession) {
	removeParticipantDevice(session);
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(session);
Ghislain MARY's avatar
Ghislain MARY committed
209 210
	if (!p)
		return -1;
Andrea Gianarda's avatar
Andrea Gianarda committed
211 212 213 214 215 216 217 218
	if (p->getDevices().empty()) {
		participants.remove(p);
		time_t creationTime = time(nullptr);
		notifyParticipantRemoved(creationTime, false, p);
	}

	checkIfTerminated();

219 220 221
	return 0;
}

Andrea Gianarda's avatar
Andrea Gianarda committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
int Conference::removeParticipant (const IdentityAddress &addr) {
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(addr);
	return removeParticipant(p);
}

bool Conference::removeParticipant (const std::shared_ptr<LinphonePrivate::Participant> &participant) {
	if (!participant)
		return false;
	// Delete all devices of a participant
	std::for_each(participant->getDevices().cbegin(), participant->getDevices().cend(), [&] (const std::shared_ptr<ParticipantDevice> & device) {
		LinphoneEvent * event = device->getConferenceSubscribeEvent();
		if (event) {
			//try to terminate subscription if any, but do not wait for anser.
			LinphoneEventCbs *cbs = linphone_event_get_callbacks(event);
			linphone_event_cbs_set_user_data(cbs, nullptr);
			linphone_event_cbs_set_notify_response(cbs, nullptr);
			linphone_event_terminate(event);
		}

		time_t creationTime = time(nullptr);
		notifyParticipantDeviceRemoved(creationTime, false, participant, device);
	});
	participant->clearDevices();
	participants.remove(participant);
	time_t creationTime = time(nullptr);
	notifyParticipantRemoved(creationTime, false, participant);

	checkIfTerminated();

	return true;
}

void Conference::checkIfTerminated() {
	if (getParticipantCount() == 0) {
		if (getState() == ConferenceInterface::State::TerminationPending) {
			setState(ConferenceInterface::State::Terminated);
		} else {
			setState(ConferenceInterface::State::TerminationPending);
		}
	}
}

Ghislain MARY's avatar
Ghislain MARY committed
264
int Conference::terminate () {
Andrea Gianarda's avatar
Andrea Gianarda committed
265
	participants.clear();
266 267 268
	return 0;
}

Andrea Gianarda's avatar
Andrea Gianarda committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282
void Conference::setState (LinphonePrivate::ConferenceInterface::State state) {
	LinphonePrivate::ConferenceInterface::State previousState = getState();
	// Change state if:
	// - current state is not Deleted
	// - current state is Deleted and trying to move to Instantiated state
	if ((previousState != ConferenceInterface::State::Deleted) || ((previousState == ConferenceInterface::State::Deleted) && (state == ConferenceInterface::State::Instantiated))) {
		shared_ptr<Conference> ref = getSharedFromThis();
		LinphonePrivate::Conference::setState(state);
		// TODO Delete
		if (previousState != state) {
			if (mStateChangedCb) {
				mStateChangedCb(toC(), (LinphoneConferenceState)state, mUserData);
			}
		}
283
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
284

285 286
}

Andrea Gianarda's avatar
Andrea Gianarda committed
287 288 289 290 291 292
void Conference::notifyStateChanged (LinphonePrivate::ConferenceInterface::State state) {
	// Call callbacks before calling listeners because listeners may change state
	linphone_core_notify_conference_state_changed(getCore()->getCCore(), toC(), (LinphoneConferenceState)getState());
	// Call listeners
	LinphonePrivate::Conference::notifyStateChanged(state);
}
293

Andrea Gianarda's avatar
Andrea Gianarda committed
294
void Conference::onConferenceTerminated (const IdentityAddress &addr) {
295

Andrea Gianarda's avatar
Andrea Gianarda committed
296 297 298 299 300 301 302 303 304 305 306
/*
	auto event = make_shared<ConferenceEvent>(
		EventLog::Type::ConferenceTerminated,
		time(nullptr),
		getConferenceId()
	);
	d->addEvent(event);
*/

	// Keep a reference to the conference to be able to set the state to Deleted
	shared_ptr<Conference> ref = getSharedFromThis();
307 308 309 310
	// If core is in Global Shutdown state, then do not remove it from the map as it will be freed by Core::uninit()
	if (linphone_core_get_global_state(getCore()->getCCore()) != LinphoneGlobalShutdown) {
		getCore()->deleteAudioVideoConference(ref);
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
311
	setState(ConferenceInterface::State::Deleted);
312 313
}

Andrea Gianarda's avatar
Andrea Gianarda committed
314 315
void Conference::setParticipantAdminStatus (const std::shared_ptr<LinphonePrivate::Participant> &participant, bool isAdmin) {

316 317
}

Andrea Gianarda's avatar
Andrea Gianarda committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
void Conference::join (const IdentityAddress &participantAddress) {
	
}

void Conference::join () {

}

bool Conference::removeParticipants (const std::list<std::shared_ptr<LinphonePrivate::Participant>> &participants) {
	bool soFarSoGood = true;
	for (const auto &p : participants)
		soFarSoGood &= removeParticipant(p);
	return soFarSoGood;
}

bctbx_list_t *Conference::getCallbacksList () const {
	return mCallbacks;
}

LinphoneConferenceCbs *Conference::getCurrentCbs () const{
	return mCurrentCbs;
}

void Conference::setCurrentCbs (LinphoneConferenceCbs *cbs) {
	mCurrentCbs = cbs;
343 344
}

Andrea Gianarda's avatar
Andrea Gianarda committed
345 346 347
void Conference::addCallbacks (LinphoneConferenceCbs *cbs) {
	mCallbacks = bctbx_list_append(mCallbacks, belle_sip_object_ref(cbs));
}
348

Andrea Gianarda's avatar
Andrea Gianarda committed
349 350 351 352
void Conference::removeCallbacks (LinphoneConferenceCbs *cbs) {
	mCallbacks = bctbx_list_remove(mCallbacks, cbs);
	belle_sip_object_unref(cbs);
}
353

Andrea Gianarda's avatar
Andrea Gianarda committed
354 355 356
void *Conference::getUserData () const{
	return userData;
}
357

Andrea Gianarda's avatar
Andrea Gianarda committed
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
void Conference::setUserData (void *ud) {
	userData = ud;
}

LocalConference::LocalConference (
	const shared_ptr<Core> &core,
	const IdentityAddress &myAddress,
	CallSessionListener *listener,
	const std::shared_ptr<LinphonePrivate::ConferenceParams> params) :
	Conference(core, myAddress, listener, params){

	// Set last notify to 1 in order to ensure that the 1st notify to remote conference is correctly processed
	// Remote conference sets last notify to 0 in its constructor
//	lastNotify = 1;

#ifdef HAVE_ADVANCED_IM
	bool_t eventLogEnabled = linphone_config_get_bool(linphone_core_get_config(getCore()->getCCore()), "misc", "conference_event_log_enabled", TRUE );
	if (eventLogEnabled) {
		eventHandler = std::make_shared<LocalAudioVideoConferenceEventHandler>(this);
		addListener(eventHandler);
	}
#endif // HAVE_ADVANCED_IM

	confParams->enableLocalParticipant(true);

	setState(ConferenceInterface::State::Instantiated);
	mMixerSession.reset(new MixerSession(*core.get()));

	// Update proxy contact address to add conference ID
	// Do not use myAddress directly as it may lack some parameter like gruu
	LinphoneAddress * cAddress = linphone_address_new(myAddress.asString().c_str());
	LinphoneProxyConfig * proxyCfg = linphone_core_lookup_known_proxy(core->getCCore(), cAddress);
390 391 392 393 394 395
	char * contactAddressStr = nullptr;
	if (proxyCfg && proxyCfg->op) {
		contactAddressStr = sal_address_as_string(proxyCfg->op->getContactAddress());
	} else {
		contactAddressStr = ms_strdup(linphone_core_find_best_identity(core->getCCore(), const_cast<LinphoneAddress *>(cAddress)));
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
396
	Address contactAddress(contactAddressStr);
397 398
	char confId[6];
	belle_sip_random_token(confId,sizeof(confId));
Andrea Gianarda's avatar
Andrea Gianarda committed
399
	contactAddress.setUriParam("conf-id",confId);
400 401 402
	if (contactAddressStr) {
		ms_free(contactAddressStr);
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
403 404 405
	linphone_address_unref(cAddress);

	setConferenceAddress(contactAddress);
406
	setState(ConferenceInterface::State::CreationPending);
407 408
}

409
LocalConference::~LocalConference() {
Andrea Gianarda's avatar
Andrea Gianarda committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
	if ((state != ConferenceInterface::State::Terminated) && (state != ConferenceInterface::State::Deleted)) {
		terminate();
	}
#ifdef HAVE_ADVANCED_IM
	eventHandler.reset();
#endif // HAVE_ADVANCED_IM
	mMixerSession.reset();
}

void LocalConference::setConferenceAddress (const ConferenceAddress &conferenceAddress) {
	Conference::setConferenceAddress(conferenceAddress);
}

void LocalConference::finalizeCreation() {
	if (getState() == ConferenceInterface::State::CreationPending) {
425 426
		const ConferenceAddress & conferenceAddress = getConferenceAddress ();
		setConferenceId(ConferenceId(conferenceAddress, conferenceAddress));
Andrea Gianarda's avatar
Andrea Gianarda committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
#ifdef HAVE_ADVANCED_IM
		if (eventHandler) {
			eventHandler->setConference(this);
		}
#endif // HAVE_ADVANCED_IM
	}
}

void LocalConference::subscribeReceived (LinphoneEvent *event) {
#ifdef HAVE_ADVANCED_IM
	if (eventHandler) {
		eventHandler->subscribeReceived(event, false);
	}
#endif // HAVE_ADVANCED_IM
}

void LocalConference::onConferenceTerminated (const IdentityAddress &addr) {
#ifdef HAVE_ADVANCED_IM
	if (eventHandler) {
		eventHandler->setConference(nullptr);
	}
#endif // HAVE_ADVANCED_IM
	Conference::onConferenceTerminated(addr);
450 451
}

Ghislain MARY's avatar
Ghislain MARY committed
452
void LocalConference::addLocalEndpoint () {
Andrea Gianarda's avatar
Andrea Gianarda committed
453
	if (!confParams->localParticipantEnabled()) return;
Simon Morlat's avatar
Simon Morlat committed
454 455 456
	
	StreamMixer *mixer = mMixerSession->getMixerByType(SalAudio);
	if (mixer) mixer->enableLocalParticipant(true);
Andrea Gianarda's avatar
Andrea Gianarda committed
457 458

	if (confParams->videoEnabled()){
Simon Morlat's avatar
Simon Morlat committed
459
		mixer = mMixerSession->getMixerByType(SalVideo);
460 461
		if (mixer){
			mixer->enableLocalParticipant(true);
Simon Morlat's avatar
Simon Morlat committed
462 463
			VideoControlInterface *vci = getVideoControlInterface();
			if (vci){
Andrea Gianarda's avatar
Andrea Gianarda committed
464 465
				vci->setNativePreviewWindowId(getCore()->getCCore()->preview_window_id);
				vci->setNativeWindowId(getCore()->getCCore()->video_window_id);
Simon Morlat's avatar
Simon Morlat committed
466
			}
467
		}
Simon Morlat's avatar
Simon Morlat committed
468 469
	}
	mIsIn = true;
470 471
}

Ghislain MARY's avatar
Ghislain MARY committed
472
int LocalConference::inviteAddresses (const list<const LinphoneAddress *> &addresses, const LinphoneCallParams *params) {
473
	for (const auto &address : addresses) {
Andrea Gianarda's avatar
Andrea Gianarda committed
474
		LinphoneCall *call = linphone_core_get_call_by_remote_address2(getCore()->getCCore(), address);
475 476 477
		char *cAddress = linphone_address_as_string(address);
		Address cppAddress(cAddress);
		free(cAddress);
478
		if (!call) {
Ghislain MARY's avatar
Ghislain MARY committed
479
			/* Start a new call by indicating that it has to be put into the conference directly */
Simon Morlat's avatar
Simon Morlat committed
480 481 482 483
			LinphoneCallParams *new_params;
			if (params){
				new_params = linphone_call_params_copy(params);
			}else{
Andrea Gianarda's avatar
Andrea Gianarda committed
484 485
				new_params = linphone_core_create_call_params(getCore()->getCCore(), nullptr);
				linphone_call_params_enable_video(new_params, confParams->videoEnabled());
Simon Morlat's avatar
Simon Morlat committed
486
			}
Andrea Gianarda's avatar
Andrea Gianarda committed
487

Simon Morlat's avatar
Simon Morlat committed
488
			linphone_call_params_set_in_conference(new_params, TRUE);
Andrea Gianarda's avatar
Andrea Gianarda committed
489

490 491 492 493
			const Address & conferenceAddress = getConferenceAddress ();
			const string & confId = conferenceAddress.getUriParamValue("conf-id");
			linphone_call_params_set_conference_id(new_params, confId.c_str());

Andrea Gianarda's avatar
Andrea Gianarda committed
494 495
			call = linphone_core_invite_address_with_params(getCore()->getCCore(), address, new_params);

496
			if (!call){
497
				ms_error("LocalConference::inviteAddresses(): could not invite participant");
Andrea Gianarda's avatar
Andrea Gianarda committed
498 499 500 501
			} else {
				addParticipant(Call::toCpp(call)->getSharedFromThis());
				const std::shared_ptr<LinphonePrivate::Participant> participant = findParticipant(cppAddress);
				participant->setPreserveSession(false);
502
			}
503
			linphone_call_params_unref(new_params);
Ghislain MARY's avatar
Ghislain MARY committed
504 505
		} else {
			/* There is already a call to this address, so simply join it to the local conference if not already done */
Andrea Gianarda's avatar
Andrea Gianarda committed
506 507 508 509 510 511
			if (!linphone_call_params_get_in_conference(linphone_call_get_current_params(call))) {
				addParticipant(Call::toCpp(call)->getSharedFromThis());

				const std::shared_ptr<LinphonePrivate::Participant> participant = findParticipant(cppAddress);
				participant->setPreserveSession(true);
			}
512
		}
Ghislain MARY's avatar
Ghislain MARY committed
513
		/* If the local participant is not yet created, created it and it to the conference */
514
		addLocalEndpoint();
515 516 517 518
	}
	return 0;
}

Andrea Gianarda's avatar
Andrea Gianarda committed
519 520
bool LocalConference::addParticipant (std::shared_ptr<LinphonePrivate::Call> call) {
	if (linphone_call_params_get_in_conference(linphone_call_get_current_params(call->toC()))) {
521
		ms_error("Already in conference");
Andrea Gianarda's avatar
Andrea Gianarda committed
522
		return false;
523
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
524 525 526 527 528 529 530

	// Add participant only if creation is successful
	bool canAddParticipant = (getParticipantCount() == 0) ? (getState() == ConferenceInterface::State::CreationPending) : (getState() == ConferenceInterface::State::Created);
	if (canAddParticipant) {
		confParams->enableLocalParticipant(true);
		LinphoneCallState state = static_cast<LinphoneCallState>(call->getState());
		bool localEndpointCanBeAdded = false;
531 532 533
		const Address & conferenceAddress = getConferenceAddress ();
		const string & confId = conferenceAddress.getUriParamValue("conf-id");

Andrea Gianarda's avatar
Andrea Gianarda committed
534 535 536 537 538 539 540
		switch(state){
			case LinphoneCallOutgoingInit:
			case LinphoneCallOutgoingProgress:
			case LinphoneCallIncomingReceived:
			case LinphoneCallPausing:
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
					L_GET_PRIVATE(call->getParams()))->setInConference(true);
541 542
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
					L_GET_PRIVATE(call->getParams()))->setConferenceId(confId);
Andrea Gianarda's avatar
Andrea Gianarda committed
543 544 545 546 547 548 549 550 551
			break;
			case LinphoneCallPaused:
			{
				/*
				 * Modifying the MediaSession's params directly is a bit hacky.
				 * However, the resume() method doesn't accept parameters.
				 */
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
					L_GET_PRIVATE(call->getParams()))->setInConference(true);
552 553
				const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
					L_GET_PRIVATE(call->getParams()))->setConferenceId(confId);
Andrea Gianarda's avatar
Andrea Gianarda committed
554 555 556 557 558 559 560 561 562 563 564 565
				const_cast<LinphonePrivate::MediaSessionParams *>(
					call->getParams())->enableVideo(getCurrentParams().videoEnabled());
				// Conference resumes call that previously paused in order to add the participant
				call->resume();

			}
			break;
			case LinphoneCallStreamsRunning:
			{
				LinphoneCallParams *params = linphone_core_create_call_params(getCore()->getCCore(), call->toC());
				linphone_call_params_set_in_conference(params, TRUE);
				linphone_call_params_enable_video(params, getCurrentParams().videoEnabled());
566
				linphone_call_params_set_conference_id(params, confId.c_str());
Andrea Gianarda's avatar
Andrea Gianarda committed
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

				linphone_call_update(call->toC(), params);
				linphone_call_params_unref(params);
				localEndpointCanBeAdded = true;
			}
			break;
			default:
				ms_error("Call is in state %s, it cannot be added to the conference",
				linphone_call_state_to_string(static_cast<LinphoneCallState>(call->getState())));
				return false;
			break;
		}

		if (call->toC() == linphone_core_get_current_call(getCore()->getCCore()))
			L_GET_PRIVATE_FROM_C_OBJECT(getCore()->getCCore())->setCurrentCall(nullptr);
		mMixerSession->joinStreamsGroup(call->getMediaSession()->getStreamsGroup());
		Conference::addParticipant(call);
		setState(ConferenceInterface::State::Created);
		if (localEndpointCanBeAdded){
586
			/*
Andrea Gianarda's avatar
Andrea Gianarda committed
587 588
			 * This needs to be done at the end, to ensure that the call in StreamsRunning state has released the local
			 * resources (mic and camera), which is done during the joinStreamsGroup() step.
589
			 */
Andrea Gianarda's avatar
Andrea Gianarda committed
590
			addLocalEndpoint();
591
		}
Andrea Gianarda's avatar
Andrea Gianarda committed
592
		return true;
593
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
594 595 596 597

	ms_error("Unable to add participant to conference %p because it is in state %s",
	this, linphone_conference_state_to_string((LinphoneConferenceState)getState()));
	return false;
598 599
}

Andrea Gianarda's avatar
Andrea Gianarda committed
600 601 602 603 604
bool LocalConference::addParticipant (const IdentityAddress &participantAddress) {
	confParams->enableLocalParticipant(true);
	bool success = Conference::addParticipant(participantAddress);
	setState(ConferenceInterface::State::Created);
	return success;
605 606
}

Andrea Gianarda's avatar
Andrea Gianarda committed
607
int LocalConference::removeParticipant (const std::shared_ptr<LinphonePrivate::CallSession> & session, const bool preserveSession) {
Simon Morlat's avatar
Simon Morlat committed
608
	int err = 0;
Andrea Gianarda's avatar
Andrea Gianarda committed
609 610 611 612 613 614 615

	shared_ptr<Call> call = getCore()->getCallByRemoteAddress (*session->getRemoteAddress());
	if (call) {
		if (linphone_call_get_conference(call->toC()) != toC()){
			lError() << "Call " << call->toC() << " is not part of conference " << toC();
			return -1;
		}
616
	}
617

Andrea Gianarda's avatar
Andrea Gianarda committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
	// It is allowed to remove a participant if
	// - there are at least 2 remote participants in the conference
	// - the remaining participant doesn't need to preserve its session after the conference ends hence the conference was not destroyed
	bool removeParticipantAllowed = ((getParticipantCount() >= 2) || ((getParticipantCount() == 1) && !preserveSession));
	if (removeParticipantAllowed) {
		if (getState() != ConferenceInterface::State::TerminationPending) {

			if (preserveSession) {
				CallSession::State sessionState = session->getState();
				// If the session is already paused,then send anupdate to kick the participant out of the conference, pause the call otherwise
				if (sessionState == CallSession::State::Paused) {
					const MediaSessionParams * params = static_pointer_cast<LinphonePrivate::MediaSession>(session)->getMediaParams();
					MediaSessionParams *currentParams = params->clone();
					currentParams->getPrivate()->setInConference(FALSE);
					ms_message("Updating call to notify of conference removal.");
					err = static_pointer_cast<LinphonePrivate::MediaSession>(session)->updateFromConference(currentParams);
				} else {
					/* Kick the session out of the conference by moving to the Paused state. */
					const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
							L_GET_PRIVATE(static_pointer_cast<LinphonePrivate::MediaSession>(session)->getMediaParams()))->setInConference(false);

					err = static_pointer_cast<LinphonePrivate::MediaSession>(session)->pauseFromConference();
				}
			} else {
				// Terminate session (i.e. send a BYE) as per RFC
				// This is the default behaviour
				err = static_pointer_cast<LinphonePrivate::MediaSession>(session)->terminate();
			}
646 647 648 649 650

			if (call) {
				call->setConference(nullptr);
			}

Andrea Gianarda's avatar
Andrea Gianarda committed
651
		}
652
	}
653
	
Andrea Gianarda's avatar
Andrea Gianarda committed
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
	// If conference is in termination pending state, all call sessions are about be kicked out of the conference hence unjoin streams
	if (removeParticipantAllowed || getState() == ConferenceInterface::State::TerminationPending) {
		std::shared_ptr<LinphonePrivate::Participant> participant = findParticipant(session);
		Conference::removeParticipant(participant);
		mMixerSession->unjoinStreamsGroup(static_pointer_cast<LinphonePrivate::MediaSession>(session)->getStreamsGroup());

	}

	// If conference is in termination pending state, terminate method is already taking care of state kicking participants out of the conference
	// No need to kick out last remainign participant as it will be done soon
	if (getState() != ConferenceInterface::State::TerminationPending) {
		/*
		 * Handle the case where only the local participant and a unique remote participant are remaining.
		 * In this case, if the session linked to the participant has to be preserved after the conference, then destroy the conference and let these two participants to connect directly thanks to a simple call.
		 * Indeed, the conference adds latency and processing that is useless to do for 1-1 conversation.
		 */
		if (getParticipantCount() == 1){
			std::shared_ptr<LinphonePrivate::Participant> remaining_participant = participants.front();
			const bool lastParticipantPreserveSession = remaining_participant->getPreserveSession();
			if (lastParticipantPreserveSession) {

				std::shared_ptr<LinphonePrivate::MediaSession> session = static_pointer_cast<LinphonePrivate::MediaSession>(remaining_participant->getSession());

				lInfo() << "Participant [" << remaining_participant << "] with " << session->getRemoteAddress()->asString() << 
					" is our last call in our conference, we will reconnect directly to it.";

				const MediaSessionParams * params = session->getMediaParams();
				// If only one participant is in the conference, the conference is destroyed.
				if (isIn()){
					MediaSessionParams *currentParams = params->clone();
					// If the local participant is in, then an update is sent in order to notify that the call is exiting the conference
					currentParams->getPrivate()->setInConference(FALSE);
					ms_message("Updating call to notify of conference removal.");
					err = session->updateFromConference(currentParams);
				} else {
					// If the local participant is not in, the call is paused as the local participant is busy
					const_cast<LinphonePrivate::MediaSessionParamsPrivate *>(
							L_GET_PRIVATE(params))->setInConference(false);

					err = session->pauseFromConference();
				}

				setState(ConferenceInterface::State::TerminationPending);

				leave();

				/* invoke removeParticipant() recursively to remove this last participant. */
				bool success = Conference::removeParticipant(remaining_participant);
				mMixerSession->unjoinStreamsGroup(session->getStreamsGroup());
703 704 705 706 707 708 709

				// Detach call from conference
				shared_ptr<Call> lastSessionCall = getCore()->getCallByRemoteAddress (*session->getRemoteAddress());
				if (lastSessionCall) {
					lastSessionCall->setConference(nullptr);
				}

Andrea Gianarda's avatar
Andrea Gianarda committed
710 711 712 713 714 715
				return success;
			}
		}
	}

	if (getParticipantCount() == 0){
716
		leave();
Andrea Gianarda's avatar
Andrea Gianarda committed
717 718 719 720 721
		if (getState() == ConferenceInterface::State::TerminationPending) {
			setState(ConferenceInterface::State::Terminated);
		} else {
			setState(ConferenceInterface::State::TerminationPending);
		}
722 723
	}
	
724 725 726
	return err;
}

Andrea Gianarda's avatar
Andrea Gianarda committed
727 728
int LocalConference::removeParticipant (const IdentityAddress &addr) {
	const std::shared_ptr<LinphonePrivate::Participant> participant = findParticipant(addr);
Ghislain MARY's avatar
Ghislain MARY committed
729 730
	if (!participant)
		return -1;
Andrea Gianarda's avatar
Andrea Gianarda committed
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
	return removeParticipant(participant);
}

bool LocalConference::removeParticipant(const std::shared_ptr<LinphonePrivate::Participant> &participant) {
	std::shared_ptr<LinphonePrivate::CallSession> callSession = participant->getSession();
	const bool preserveSession = participant->getPreserveSession();
	if (!callSession)
		return false;
	return (bool)removeParticipant(callSession, preserveSession);
}

/* ConferenceInterface */
void LocalConference::setSubject (const std::string &subject) {
	Conference::setSubject(subject);
	time_t creationTime = time(nullptr);
	notifySubjectChanged(creationTime, false, subject);
}

void LocalConference::subscriptionStateChanged (LinphoneEvent *event, LinphoneSubscriptionState state) {
#ifdef HAVE_ADVANCED_IM
	if (eventHandler) {
		eventHandler->subscriptionStateChanged(event, state);
	}
#endif // HAVE_ADVANCED_IM
755 756
}

Ghislain MARY's avatar
Ghislain MARY committed
757
int LocalConference::terminate () {
Andrea Gianarda's avatar
Andrea Gianarda committed
758 759 760 761 762 763 764 765 766 767
	setState(ConferenceInterface::State::TerminationPending);
	for (auto participant : participants){
		for (const auto & device : participant->getDevices()) {
			std::shared_ptr<LinphonePrivate::MediaSession> session = static_pointer_cast<LinphonePrivate::MediaSession>(device->getSession());
			if (session) {
				lInfo() << "Terminating session of participant " << *participant;
				session->terminate();
			}
		}
	}
768 769 770
	return 0;
}

Ghislain MARY's avatar
Ghislain MARY committed
771
int LocalConference::enter () {
Andrea Gianarda's avatar
Andrea Gianarda committed
772
	if (linphone_core_sound_resources_locked(getCore()->getCCore()))
773
		return -1;
Andrea Gianarda's avatar
Andrea Gianarda committed
774 775
	if (linphone_core_get_current_call(getCore()->getCCore()))
		linphone_call_pause(linphone_core_get_current_call(getCore()->getCCore()));
776

Andrea Gianarda's avatar
Andrea Gianarda committed
777
	confParams->enableLocalParticipant(true);
778
	addLocalEndpoint();
779 780 781
	return 0;
}

Ghislain MARY's avatar
Ghislain MARY committed
782
void LocalConference::removeLocalEndpoint () {
Simon Morlat's avatar
Simon Morlat committed
783 784
	mMixerSession->enableLocalParticipant(false);
	mIsIn = false;
785 786
}

Andrea Gianarda's avatar
Andrea Gianarda committed
787 788
void LocalConference::leave () {
	if (isIn()) {
789
		lInfo() << getMe()->getAddress() << " is leaving conference " << getConferenceAddress();
Andrea Gianarda's avatar
Andrea Gianarda committed
790
		confParams->enableLocalParticipant(false);
791
		removeLocalEndpoint();
Andrea Gianarda's avatar
Andrea Gianarda committed
792
	}
793 794
}

Andrea Gianarda's avatar
Andrea Gianarda committed
795 796
bool LocalConference::update(const LinphonePrivate::ConferenceParamsInterface &newParameters){
	const LinphonePrivate::ConferenceParams &newConfParams = static_cast<const ConferenceParams&>(newParameters);
797
	/* Only adding or removing video is supported. */
Andrea Gianarda's avatar
Andrea Gianarda committed
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
	bool previousVideoEnablement = confParams->videoEnabled();
	bool previousAudioEnablement = confParams->audioEnabled();
	bool ret = MediaConference::Conference::update(newParameters);
	// Update media conference parameter here in order to properly
	if (newConfParams.videoEnabled() != previousVideoEnablement){
		lInfo() << "LocalConference::update(): checking participants...";
		for (auto participant : participants){
			std::shared_ptr<LinphonePrivate::MediaSession> session = static_pointer_cast<LinphonePrivate::MediaSession>(participant->getSession());

			if (session){

				const MediaSessionParams * params = session->getMediaParams();
				MediaSessionParams *currentParams = params->clone();

				if ((!!currentParams->videoEnabled()) != newConfParams.videoEnabled()){
					lInfo() << "Re-INVITing participant " << participant->getAddress().asString() << " to " << (newConfParams.videoEnabled() ? "start" : "stop") << " video.";
					currentParams->enableVideo(newConfParams.videoEnabled());
					session->update(currentParams);
816 817 818
				}
			}
		}
Andrea Gianarda's avatar
Andrea Gianarda committed
819 820 821
	}
	// Update endpoints only if audio or video settings have changed
	if ((newConfParams.videoEnabled() != previousVideoEnablement) || (newConfParams.audioEnabled() != previousAudioEnablement)){
822 823 824 825
		/* Don't forget the local participant. For simplicity, a removeLocalEndpoint()/addLocalEndpoint() does the job. */
		removeLocalEndpoint();
		addLocalEndpoint();
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
826
	return ret;
827 828
}

Ghislain MARY's avatar
Ghislain MARY committed
829
int LocalConference::startRecording (const char *path) {
Simon Morlat's avatar
Simon Morlat committed
830 831 832 833 834 835 836
	MS2AudioMixer * mixer = dynamic_cast<MS2AudioMixer*> (mMixerSession->getMixerByType(SalAudio));
	if (mixer){
		mixer->setRecordPath(path);
		mixer->startRecording();
		//TODO: error reporting is absent.
	}else{
		lError() << "LocalConference::startRecording(): no audio mixer.";
837 838 839 840 841
		return -1;
	}
	return 0;
}

Ghislain MARY's avatar
Ghislain MARY committed
842
int LocalConference::stopRecording () {
Simon Morlat's avatar
Simon Morlat committed
843 844 845 846 847
	AudioControlInterface * aci = dynamic_cast<MS2AudioMixer*> (mMixerSession->getMixerByType(SalAudio));
	if (aci){
		aci->stopRecording();
	}else{
		lError() << "LocalConference::stopRecording(): no audio mixer.";
848 849 850 851 852
		return -1;
	}
	return 0;
}

Simon Morlat's avatar
Simon Morlat committed
853 854
bool LocalConference::isIn() const{
	return mIsIn;
855 856
}

Simon Morlat's avatar
Simon Morlat committed
857 858
AudioControlInterface *LocalConference::getAudioControlInterface()const{
	return dynamic_cast<AudioControlInterface*>(mMixerSession->getMixerByType(SalAudio));
859 860
}

861 862 863 864
VideoControlInterface * LocalConference::getVideoControlInterface() const{
	return dynamic_cast<VideoControlInterface*>(mMixerSession->getMixerByType(SalVideo));
}

Simon Morlat's avatar
Simon Morlat committed
865 866 867
AudioStream *LocalConference::getAudioStream(){
	MS2AudioMixer *mixer = dynamic_cast<MS2AudioMixer*>(mMixerSession->getMixerByType(SalAudio));
	return mixer ? mixer->getAudioStream() : nullptr;
868
}
869

Andrea Gianarda's avatar
Andrea Gianarda committed
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
void LocalConference::notifyFullState () {
	++lastNotify;
	Conference::notifyFullState();
}

shared_ptr<ConferenceParticipantEvent> LocalConference::notifyParticipantAdded (time_t creationTime,  const bool isFullState, const std::shared_ptr<Participant> &participant) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantAdded (creationTime,  isFullState, participant);
}

shared_ptr<ConferenceParticipantEvent> LocalConference::notifyParticipantRemoved (time_t creationTime,  const bool isFullState, const std::shared_ptr<Participant> &participant) {
	bool preserveSession = true;
	auto participantIt = std::find_if(participants.cbegin(), participants.cend(), [&] (const std::shared_ptr<Participant> & p) {
	return (p->getSession() != participant->getSession());
	});
	if (participantIt != participants.cend()) {
		const std::shared_ptr<Participant> & p = *participantIt;
		preserveSession = p->getPreserveSession();
	}

	if ((getState() != ConferenceInterface::State::TerminationPending) && ((getParticipantCount() > 1) || ((getParticipantCount() == 1) && !preserveSession))) {
		// Increment last notify before notifying participants so that the delta can be calculated correctly
		++lastNotify;
		// Send notify only if it is not in state TerminationPending and:
		// - there is more than one participant in the conference
		// - there is only participant and it didn't have a session towards the conference manager preexisting conference
		return Conference::notifyParticipantRemoved (creationTime,  isFullState, participant);
	}

	return nullptr;
}

shared_ptr<ConferenceParticipantEvent> LocalConference::notifyParticipantSetAdmin (time_t creationTime,  const bool isFullState, const std::shared_ptr<Participant> &participant, bool isAdmin) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantSetAdmin (creationTime,  isFullState, participant, isAdmin);
}

shared_ptr<ConferenceSubjectEvent> LocalConference::notifySubjectChanged (time_t creationTime, const bool isFullState, const std::string subject) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifySubjectChanged (creationTime, isFullState, subject);
}

shared_ptr<ConferenceParticipantDeviceEvent> LocalConference::notifyParticipantDeviceAdded (time_t creationTime,  const bool isFullState, const std::shared_ptr<Participant> &participant, const std::shared_ptr<ParticipantDevice> &participantDevice) {
	// Increment last notify before notifying participants so that the delta can be calculated correctly
	++lastNotify;
	return Conference::notifyParticipantDeviceAdded (creationTime,  isFullState, participant, participantDevice);
}

shared_ptr<ConferenceParticipantDeviceEvent> LocalConference::notifyParticipantDeviceRemoved (time_t creationTime,  const bool isFullState, const std::shared_ptr<Participant> &participant, const std::shared_ptr<ParticipantDevice> &participantDevice) {

	bool preserveSession = true;
	auto participantIt = std::find_if(participants.cbegin(), participants.cend(), [&] (const std::shared_ptr<Participant> & p) {
	return (p->getSession() != participant->getSession());
	});
	if (participantIt != participants.cend()) {
		const std::shared_ptr<Participant> & p = *participantIt;
		preserveSession = p->getPreserveSession();
	}

	// Increment last notify before notifying participants so that the delta can be calculated correctly
	if ((getState() != ConferenceInterface::State::TerminationPending) && ((getParticipantCount() > 2) || ((getParticipantCount() == 2) && ((participant->getDevices().empty() == false) || !preserveSession)))) {
		++lastNotify;
		// Send notify only if it is not in state TerminationPending and:
		// - there are more than two participants in the conference
		// - there are two participants and the list of devices of the current participant is not empty
		// - there are two participants and the remaining participant didn't have a session towards the conference manager preexisting conference
		return Conference::notifyParticipantDeviceRemoved (creationTime,  isFullState, participant, participantDevice);
	}
	return nullptr;
}

RemoteConference::RemoteConference (
	const shared_ptr<Core> &core,
	const IdentityAddress &focus,
	const ConferenceId &conferenceId,
	CallSessionListener *listener,
	const std::shared_ptr<LinphonePrivate::ConferenceParams> params) :
	Conference(core, conferenceId.getLocalAddress(), listener, params){
951

Andrea Gianarda's avatar
Andrea Gianarda committed
952 953 954
	// Set last notify to 0 in order to ensure that the 1st notify from local conference is correctly processed
	// Local conference sets last notify to 1 in its constructor
//	lastNotify = 0;
955

Ghislain MARY's avatar
Ghislain MARY committed
956 957 958
	m_focusContact = nullptr;
	m_focusCall = nullptr;
	m_coreCbs = nullptr;
959 960 961 962
	m_coreCbs = linphone_factory_create_core_cbs(linphone_factory_get());
	linphone_core_cbs_set_call_state_changed(m_coreCbs, callStateChangedCb);
	linphone_core_cbs_set_transfer_state_changed(m_coreCbs, transferStateChanged);
	linphone_core_cbs_set_user_data(m_coreCbs, this);
Andrea Gianarda's avatar
Andrea Gianarda committed
963 964 965 966
	_linphone_core_add_callbacks(getCore()->getCCore(), m_coreCbs, TRUE);

	confParams->enableLocalParticipant(false);

967 968
	// Store conference ID to retrieve later the local address when the focus call goes to StreamsRunning state
	this->conferenceId = conferenceId;
Andrea Gianarda's avatar
Andrea Gianarda committed
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
	setConferenceAddress(focus);
}

RemoteConference::RemoteConference (
	const shared_ptr<Core> &core,
	const std::shared_ptr<LinphonePrivate::Call>& focusCall,
	const ConferenceId &conferenceId,
	CallSessionListener *listener,
	const std::shared_ptr<LinphonePrivate::ConferenceParams> params) :
	Conference(core, conferenceId.getLocalAddress(), listener, params){

	// Set last notify to 0 in order to ensure that the 1st notify from local conference is correctly processed
	// Local conference sets last notify to 1 in its constructor
//	lastNotify = 0;

	m_focusContact = ms_strdup(focusCall->getRemoteContact().c_str());

	m_focusCall = focusCall;
	m_coreCbs = nullptr;
	m_coreCbs = linphone_factory_create_core_cbs(linphone_factory_get());
	linphone_core_cbs_set_call_state_changed(m_coreCbs, callStateChangedCb);
	linphone_core_cbs_set_transfer_state_changed(m_coreCbs, transferStateChanged);
	linphone_core_cbs_set_user_data(m_coreCbs, this);
	_linphone_core_add_callbacks(getCore()->getCCore(), m_coreCbs, TRUE);

	setConferenceId(conferenceId);

	setConferenceAddress(Address(m_focusContact));
	setState(ConferenceInterface::State::CreationPending);
	finalizeCreation();
999 1000
}

Ghislain MARY's avatar
Ghislain MARY committed
1001
RemoteConference::~RemoteConference () {
1002
	terminate();
Andrea Gianarda's avatar
Andrea Gianarda committed
1003 1004 1005 1006 1007 1008 1009
#ifdef HAVE_ADVANCED_IM
	eventHandler.reset();
#endif // HAVE_ADVANCED_IM

	ms_free(m_focusContact);

	linphone_core_remove_callbacks(getCore()->getCCore(), m_coreCbs);
1010
	linphone_core_cbs_unref(m_coreCbs);
1011 1012
}

Andrea Gianarda's avatar
Andrea Gianarda committed
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
void RemoteConference::finalizeCreation() {
	if (getState() == ConferenceInterface::State::CreationPending) {

		addListener(std::shared_ptr<ConferenceListenerInterface>(static_cast<ConferenceListenerInterface *>(this), [](ConferenceListenerInterface * p){}));
	#ifdef HAVE_ADVANCED_IM
		bool_t eventLogEnabled = linphone_config_get_bool(linphone_core_get_config(getCore()->getCCore()), "misc", "conference_event_log_enabled", TRUE );
		if (eventLogEnabled) {
			eventHandler = std::make_shared<RemoteConferenceEventHandler>(this, this);
			eventHandler->subscribe(getConferenceId());
		}
	#endif // HAVE_ADVANCED_IM
	} else {
		lError() << "Cannot finalize creation of Conference in state " << getState();
	}
}

Ghislain MARY's avatar
Ghislain MARY committed
1029
int RemoteConference::inviteAddresses (const list<const LinphoneAddress *> &addresses, const LinphoneCallParams *params) {
1030 1031 1032 1033
	ms_error("RemoteConference::inviteAddresses() not implemented");
	return -1;
}

Andrea Gianarda's avatar
Andrea Gianarda committed
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
bool RemoteConference::addParticipant (const IdentityAddress &participantAddress) {
	// Search call that matches participant session
	const std::list<std::shared_ptr<Call>> &coreCalls = getCore()->getCalls();
	auto callIt = std::find_if(coreCalls.cbegin(), coreCalls.cend(), [&] (const std::shared_ptr<Call> & c) {
		return (IdentityAddress(*c->getRemoteAddress()) == participantAddress);
	});
	bool ret = false;
	if (callIt != coreCalls.cend()) {
		std::shared_ptr<Call> call = *callIt;
		ret = addParticipant(call);
	}
	return ret;
}

bool RemoteConference::addParticipant (std::shared_ptr<LinphonePrivate::Call> call) {
1049
	LinphoneAddress *addr;
1050
	LinphoneCallParams *params;
Ghislain MARY's avatar
Ghislain MARY committed
1051
	LinphoneCallLog *callLog;
Andrea Gianarda's avatar
Andrea Gianarda committed
1052 1053 1054 1055 1056 1057
	switch (state) {
		case ConferenceInterface::State::None:
		case ConferenceInterface::State::Instantiated:
		case ConferenceInterface::State::CreationFailed:
			ms_message("Calling the conference focus (%s)", getConferenceAddress().asString().c_str());
			addr = linphone_address_new(getConferenceAddress().asString().c_str());
Ghislain MARY's avatar
Ghislain MARY committed
1058
			if (!addr)
Andrea Gianarda's avatar
Andrea Gianarda committed
1059 1060 1061 1062 1063
				return false;
			params = linphone_core_create_call_params(getCore()->getCCore(), nullptr);
			linphone_call_params_enable_video(params, confParams->videoEnabled());
			m_focusCall = Call::toCpp(linphone_core_invite_address_with_params(getCore()->getCCore(), addr, params))->getSharedFromThis();
			m_focusCall->setConference(toC());
Ghislain MARY's avatar
Ghislain MARY committed
1064
			m_pendingCalls.push_back(call);
Andrea Gianarda's avatar
Andrea Gianarda committed
1065
			callLog = m_focusCall->getLog();
Ghislain MARY's avatar
Ghislain MARY committed
1066 1067 1068
			callLog->was_conference = TRUE;
			linphone_address_unref(addr);
			linphone_call_params_unref(params);
Andrea Gianarda's avatar
Andrea Gianarda committed
1069 1070 1071 1072
			setState(ConferenceInterface::State::CreationPending);
			Conference::addParticipant(call);
			return true;
		case ConferenceInterface::State::CreationPending:
1073
			Conference::addParticipant(call);
Ghislain MARY's avatar
Ghislain MARY committed
1074
			if(focusIsReady())
1075
				transferToFocus(call);
Ghislain MARY's avatar
Ghislain MARY committed
1076
			else
1077
				m_pendingCalls.push_back(call);
Andrea Gianarda's avatar
Andrea Gianarda committed
1078 1079
			return true;
		case ConferenceInterface::State::Created:
1080
			Conference::addParticipant(call);
1081
			transferToFocus(call);
Andrea Gianarda's avatar
Andrea Gianarda committed
1082
			return true;
1083
		default:
Andrea Gianarda's avatar
Andrea Gianarda committed
1084 1085
			ms_error("Could not add call %p to the conference. Bad conference state (%s)", call.get(), Utils::toString(state).c_str());
			return false;
1086 1087 1088
	}
}

Andrea Gianarda's avatar
Andrea Gianarda committed
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
int RemoteConference::removeParticipant(const std::shared_ptr<LinphonePrivate::CallSession> & session, const bool preserveSession) {
	std::shared_ptr<LinphonePrivate::Participant> p = findParticipant(session);
	if (p) {
		return removeParticipant(p);
	}
	return -1;
}

bool RemoteConference::removeParticipant(const std::shared_ptr<LinphonePrivate::Participant> &participant) {
	return removeParticipant(participant->getAddress());
}

int RemoteConference::removeParticipant (const IdentityAddress &addr) {
	Address refer_to_addr;
1103
	int res;
1104

Andrea Gianarda's avatar
Andrea Gianarda committed
1105 1106 1107 1108 1109
	switch (state) {
		case ConferenceInterface::State::Created:
		case ConferenceInterface::State::TerminationPending:
			if(!findParticipant(addr)) {
				ms_error("Conference: could not remove participant '%s': not in the participants list", addr.asString().c_str());
1110 1111
				return -1;
			}
Andrea Gianarda's avatar
Andrea Gianarda committed
1112 1113 1114
			refer_to_addr = Address(addr);
			linphone_address_set_method_param(L_GET_C_BACK_PTR(&refer_to_addr), "BYE");
			res = m_focusCall->getOp()->refer(refer_to_addr.asString().c_str());
Ghislain MARY's avatar
Ghislain MARY committed
1115
			if (res == 0)
Andrea Gianarda's avatar
Andrea Gianarda committed
1116
				return Conference::removeParticipant(addr);
Ghislain MARY's avatar
Ghislain MARY committed
1117
			else {
Andrea Gianarda's avatar
Andrea Gianarda committed
1118
				ms_error("Conference: could not remove participant '%s': REFER with BYE has failed", addr.asString().c_str());
1119 1120
				return -1;
			}
1121
		default:
Ghislain MARY's avatar
Ghislain MARY committed
1122
			ms_error("Cannot remove %s from conference: Bad conference state (%s)",
Andrea Gianarda's avatar
Andrea Gianarda committed
1123
				addr.asString().c_str(), Utils::toString(state).c_str());
1124 1125 1126 1127
			return -1;
	}
}

Ghislain MARY's avatar
Ghislain MARY committed
1128
int RemoteConference::terminate () {
Andrea Gianarda's avatar
Andrea Gianarda committed
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
	switch (state) {
		case ConferenceInterface::State::Created:
		case ConferenceInterface::State::CreationPending:
			m_focusCall->setConference(nullptr);
			m_focusCall->terminate();
			setState(ConferenceInterface::State::TerminationPending);
			break;
		case ConferenceInterface::State::TerminationPending:
			if (m_focusCall) {
				// Do not terminate focus call when terminating the remote conference
				// This is required because the local conference creates a remote conference for every participant and the call from the participant to the local conference is the focus call
				m_focusCall = nullptr;
			}
			Conference::terminate();
			setState(ConferenceInterface::State::Terminated);
1144
			break;
Ghislain MARY's avatar
Ghislain MARY committed
1145 1146
		default:
			break;
1147 1148 1149 1150
	}
	return 0;
}

Ghislain MARY's avatar
Ghislain MARY committed
1151
int RemoteConference::enter () {
Andrea Gianarda's avatar
Andrea Gianarda committed
1152 1153
	if (state != ConferenceInterface::State::Created) {
		ms_error("Could not enter in the conference: bad conference state (%s)", Utils::toString(state).c_str());
1154 1155
		return -1;
	}
Andrea Gianarda's avatar
Andrea Gianarda committed
1156
	LinphoneCallState callState = static_cast<LinphoneCallState>(m_focusCall->getState());
Ghislain MARY's avatar
Ghislain MARY committed
1157 1158 1159
	switch (callState) {
		case LinphoneCallStreamsRunning:
			break;
1160
		case LinphoneCallPaused:
Andrea Gianarda's avatar
Andrea Gianarda committed
1161
			m_focusCall->resume();
1162 1163
			break;
		default:
Ghislain MARY's avatar
Ghislain MARY committed