media-session.cpp 195 KB
Newer Older
1 2
/*
 * media-session.cpp
Ghislain MARY's avatar
Ghislain MARY committed
3
 * Copyright (C) 2010-2017 Belledonne Communications SARL
4
 *
Ghislain MARY's avatar
Ghislain MARY committed
5 6 7 8
 * 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 2
 * of the License, or (at your option) any later version.
9 10 11 12 13 14 15
 *
 * 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
Ghislain MARY's avatar
Ghislain MARY committed
16 17
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 19
 */

20 21
#include <iomanip>
#include <math.h>
22

23
#include "address/address-p.h"
24
#include "c-wrapper/c-wrapper.h"
25 26 27 28
#include "conference/session/media-session-p.h"
#include "call/call-p.h"
#include "conference/participant-p.h"
#include "conference/params/media-session-params-p.h"
29

30 31 32 33 34 35 36 37
#include "conference/session/media-session.h"
#include "utils/payload-type-handler.h"

#include "logger/logger.h"

#include "linphone/core.h"

#include <bctoolbox/defs.h>
38
#include <mediastreamer2/mediastream.h>
39 40 41 42 43 44 45 46 47 48 49
#include <mediastreamer2/msequalizer.h>
#include <mediastreamer2/mseventqueue.h>
#include <mediastreamer2/msfileplayer.h>
#include <mediastreamer2/msjpegwriter.h>
#include <mediastreamer2/msrtt4103.h>
#include <mediastreamer2/msvolume.h>
#include <ortp/b64.h>

#include "private.h"

using namespace std;
50 51 52

LINPHONE_BEGIN_NAMESPACE

53 54 55 56 57 58 59 60 61 62
#define STR_REASSIGN(dest, src) { \
	if (dest) \
		ms_free(dest); \
	dest = src; \
}

inline OrtpRtcpXrStatSummaryFlag operator|(OrtpRtcpXrStatSummaryFlag a, OrtpRtcpXrStatSummaryFlag b) {
	return static_cast<OrtpRtcpXrStatSummaryFlag>(static_cast<int>(a) | static_cast<int>(b));
}

63 64
// =============================================================================

65 66
const string MediaSessionPrivate::ecStateStore = ".linphone.ecstate";
const int MediaSessionPrivate::ecStateMaxLen = 1048576; /* 1Mo */
67 68 69

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

70 71 72 73 74
MediaSessionPrivate::MediaSessionPrivate (const Conference &conference, const CallSessionParams *csp, CallSessionListener *listener)
	: CallSessionPrivate(conference, csp, listener) {
	if (csp)
		params = new MediaSessionParams(*(reinterpret_cast<const MediaSessionParams *>(csp)));
	currentParams = new MediaSessionParams();
75

Ghislain MARY's avatar
Ghislain MARY committed
76
	audioStats = _linphone_call_stats_new();
77
	initStats(audioStats, LinphoneStreamTypeAudio);
Ghislain MARY's avatar
Ghislain MARY committed
78
	videoStats = _linphone_call_stats_new();
79
	initStats(videoStats, LinphoneStreamTypeVideo);
Ghislain MARY's avatar
Ghislain MARY committed
80
	textStats = _linphone_call_stats_new();
81 82 83 84 85 86 87 88 89 90 91 92 93 94
	initStats(textStats, LinphoneStreamTypeText);

	int minPort, maxPort;
	linphone_core_get_audio_port_range(core, &minPort, &maxPort);
	setPortConfig(mainAudioStreamIndex, make_pair(minPort, maxPort));
	linphone_core_get_video_port_range(core, &minPort, &maxPort);
	setPortConfig(mainVideoStreamIndex, make_pair(minPort, maxPort));
	linphone_core_get_text_port_range(core, &minPort, &maxPort);
	setPortConfig(mainTextStreamIndex, make_pair(minPort, maxPort));

	memset(sessions, 0, sizeof(sessions));
}

MediaSessionPrivate::~MediaSessionPrivate () {
95 96 97 98 99 100
	if (currentParams)
		delete currentParams;
	if (params)
		delete params;
	if (remoteParams)
		delete remoteParams;
101 102 103 104 105 106
	if (audioStats)
		linphone_call_stats_unref(audioStats);
	if (videoStats)
		linphone_call_stats_unref(videoStats);
	if (textStats)
		linphone_call_stats_unref(textStats);
107 108
	if (natPolicy)
		linphone_nat_policy_unref(natPolicy);
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
	if (stunClient)
		delete stunClient;
	delete iceAgent;
	if (localDesc)
		sal_media_description_unref(localDesc);
	if (biggestDesc)
		sal_media_description_unref(biggestDesc);
	if (resultDesc)
		sal_media_description_unref(resultDesc);
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::stunAuthRequestedCb (void *userData, const char *realm, const char *nonce, const char **username, const char **password, const char **ha1) {
	MediaSessionPrivate *msp = reinterpret_cast<MediaSessionPrivate *>(userData);
	msp->stunAuthRequestedCb(realm, nonce, username, password, ha1);
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::accepted () {
130
	L_Q();
131 132 133 134 135
	CallSessionPrivate::accepted();
	LinphoneTaskList tl;
	linphone_task_list_init(&tl);
	/* Reset the internal call update flag, so it doesn't risk to be copied and used in further re-INVITEs */
	params->getPrivate()->setInternalCallUpdate(false);
136 137
	SalMediaDescription *rmd = op->get_remote_media_description();
	SalMediaDescription *md = op->get_final_media_description();
138 139 140 141 142 143 144 145 146 147
	if (!md && (prevState == LinphoneCallOutgoingEarlyMedia) && resultDesc) {
		lInfo() << "Using early media SDP since none was received with the 200 OK";
		md = resultDesc;
	}
	if (md && (sal_media_description_empty(md) || linphone_core_incompatible_security(core, md)))
		md = nullptr;
	if (md) {
		/* There is a valid SDP in the response, either offer or answer, and we're able to start/update the streams */
		if (rmd) {
			/* Handle remote ICE attributes if any. */
148
			iceAgent->updateFromRemoteMediaDescription(localDesc, rmd, !op->is_offerer());
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
		}
		LinphoneCallState nextState = LinphoneCallIdle;
		string nextStateMsg;
		switch (state) {
			case LinphoneCallResuming:
			case LinphoneCallConnected:
#if 0
				if (call->referer)
					linphone_core_notify_refer_state(lc,call->referer,call);
#endif
				BCTBX_NO_BREAK; /* Intentional no break */
			case LinphoneCallUpdating:
			case LinphoneCallUpdatedByRemote:
				if (!sal_media_description_has_dir(localDesc, SalStreamInactive)
					&& (sal_media_description_has_dir(md, SalStreamRecvOnly) || sal_media_description_has_dir(md, SalStreamInactive))) {
					nextState = LinphoneCallPausedByRemote;
					nextStateMsg = "Call paused by remote";
				} else {
					if (!params->getPrivate()->getInConference() && listener)
168
						listener->onSetCurrentSession(q->getSharedFromThis());
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
					nextState = LinphoneCallStreamsRunning;
					nextStateMsg = "Streams running";
				}
				break;
			case LinphoneCallEarlyUpdating:
				nextState = prevState;
				nextStateMsg = "Early update accepted";
				break;
			case LinphoneCallPausing:
				/* When we entered the pausing state, we always reach the paused state whatever the content of the remote SDP is.
				 * Our streams are all send-only (with music), soundcard and camera are never used. */
				nextState = LinphoneCallPaused;
				nextStateMsg = "Call paused";
#if 0
				if (call->refer_pending)
					linphone_task_list_add(&tl, (LinphoneCoreIterateHook)start_pending_refer, call);
#endif
				break;
			default:
				lError() << "accepted(): don't know what to do in state [" << linphone_call_state_to_string(state) << "]";
				break;
		}

		if (nextState == LinphoneCallIdle)
			lError() << "BUG: nextState is not set in accepted(), current state is " << linphone_call_state_to_string(state);
		else {
			updateRemoteSessionIdAndVer();
			iceAgent->updateIceStateInCallStats();
			updateStreams(md, nextState);
			fixCallParams(rmd);
			setState(nextState, nextStateMsg);
		}
	} else { /* Invalid or no SDP */
		switch (prevState) {
			/* Send a bye only in case of early states */
			case LinphoneCallOutgoingInit:
			case LinphoneCallOutgoingProgress:
			case LinphoneCallOutgoingRinging:
			case LinphoneCallOutgoingEarlyMedia:
			case LinphoneCallIncomingReceived:
			case LinphoneCallIncomingEarlyMedia:
				lError() << "Incompatible SDP answer received, need to abort the call";
211
				abort("Incompatible, check codecs or security settings...");
212 213 214 215 216 217 218 219 220 221 222
				break;
			/* Otherwise we are able to resume previous state */
			default:
				lError() << "Incompatible SDP answer received";
				switch(state) {
					case LinphoneCallPausedByRemote:
					case LinphoneCallPaused:
					case LinphoneCallStreamsRunning:
						break;
					default:
						lInfo() << "Incompatible SDP answer received, restoring previous state [" << linphone_call_state_to_string(prevState) << "]";
223
						setState(prevState, "Incompatible media parameters.");
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
						break;
				}
				break;
		}
	}
	linphone_task_list_run(&tl);
	linphone_task_list_free(&tl);
}

void MediaSessionPrivate::ackReceived (LinphoneHeaders *headers) {
	CallSessionPrivate::ackReceived(headers);
	if (expectMediaInAck) {
		switch (state) {
			case LinphoneCallStreamsRunning:
			case LinphoneCallPausedByRemote:
				setState(LinphoneCallUpdatedByRemote, "UpdatedByRemote");
				break;
			default:
				break;
		}
		accepted();
	}
}

bool MediaSessionPrivate::failure () {
249
	L_Q();
250
	const SalErrorInfo *ei = op->get_error_info();
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	switch (ei->reason) {
		case SalReasonRedirect:
			stopStreams();
			break;
		case SalReasonUnsupportedContent: /* This is for compatibility: linphone sent 415 because of SDP offer answer failure */
		case SalReasonNotAcceptable:
			lInfo() << "Outgoing CallSession [" << q << "] failed with SRTP and/or AVPF enabled";
			if ((state == LinphoneCallOutgoingInit) || (state == LinphoneCallOutgoingProgress)
				|| (state == LinphoneCallOutgoingRinging) /* Push notification case */ || (state == LinphoneCallOutgoingEarlyMedia)) {
				for (int i = 0; i < localDesc->nb_streams; i++) {
					if (!sal_stream_description_active(&localDesc->streams[i]))
						continue;
					if (params->getMediaEncryption() == LinphoneMediaEncryptionSRTP) {
						if (params->avpfEnabled()) {
							if (i == 0)
								lInfo() << "Retrying CallSession [" << q << "] with SAVP";
							params->enableAvpf(false);
268
							restartInvite();
269 270 271 272 273 274
							return true;
						} else if (!linphone_core_is_media_encryption_mandatory(core)) {
							if (i == 0)
								lInfo() << "Retrying CallSession [" << q << "] with AVP";
							params->setMediaEncryption(LinphoneMediaEncryptionNone);
							memset(localDesc->streams[i].crypto, 0, sizeof(localDesc->streams[i].crypto));
275
							restartInvite();
276 277 278 279 280 281
							return true;
						}
					} else if (params->avpfEnabled()) {
						if (i == 0)
							lInfo() << "Retrying CallSession [" << q << "] with AVP";
						params->enableAvpf(false);
282
						restartInvite();
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
						return true;
					}
				}
			}
			break;
		default:
			break;
	}

	bool stop = CallSessionPrivate::failure();
	if (stop)
		return true;

#if 0
	/* Stop ringing */
	bool_t ring_during_early_media = linphone_core_get_ring_during_incoming_early_media(lc);
	bool_t stop_ringing = TRUE;
	bctbx_list_t *calls = lc->calls;
	while(calls) {
		if (((LinphoneCall *)calls->data)->state == LinphoneCallIncomingReceived || (ring_during_early_media && ((LinphoneCall *)calls->data)->state == LinphoneCallIncomingEarlyMedia)) {
			stop_ringing = FALSE;
			break;
		}
		calls = calls->next;
	}
	if(stop_ringing) {
		linphone_core_stop_ringing(lc);
	}
#endif
	stopStreams();
	return false;
}

void MediaSessionPrivate::pausedByRemote () {
317
	MediaSessionParams *newParams = new MediaSessionParams(*params);
318 319 320 321 322 323
	if (lp_config_get_int(linphone_core_get_config(core), "sip", "inactive_video_on_pause", 0))
		newParams->setVideoDirection(LinphoneMediaDirectionInactive);
	acceptUpdate(newParams, LinphoneCallPausedByRemote, "Call paused by remote");
}

void MediaSessionPrivate::remoteRinging () {
324
	L_Q();
325
	/* Set privacy */
326 327
	q->getCurrentParams()->setPrivacy((LinphonePrivacyMask)op->get_privacy());
	SalMediaDescription *md = op->get_final_media_description();
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
	if (md) {
		/* Initialize the remote call params by invoking linphone_call_get_remote_params(). This is useful as the SDP may not be present in the 200Ok */
		q->getRemoteParams();
		/* Accept early media */
		if ((audioStream && audio_stream_started(audioStream))
#ifdef VIDEO_ENABLED
			|| (videoStream && video_stream_started(videoStream))
#endif
			) {
			/* Streams already started */
			tryEarlyMediaForking(md);
#ifdef VIDEO_ENABLED
			if (videoStream)
				video_stream_send_vfu(videoStream); /* Request for iframe */
#endif
343
			return;
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
		}

		setState(LinphoneCallOutgoingEarlyMedia, "Early media");
#if 0
		linphone_core_stop_ringing(lc);
#endif
		lInfo() << "Doing early media...";
		updateStreams(md, state);
		if ((q->getCurrentParams()->getAudioDirection() == LinphoneMediaDirectionInactive) && audioStream) {
#if 0
			if (lc->ringstream != NULL) return; /* Already ringing! */
			start_remote_ring(lc, call);
#endif
		}
	} else {
		linphone_core_stop_dtmf_stream(core);
		if (state == LinphoneCallOutgoingEarlyMedia) {
			/* Already doing early media */
			return;
		}
#if 0
		if (lc->ringstream == NULL) start_remote_ring(lc, call);
#endif
		lInfo() << "Remote ringing...";
		setState(LinphoneCallOutgoingRinging, "Remote ringing");
	}
}

void MediaSessionPrivate::resumed () {
	acceptUpdate(nullptr, LinphoneCallStreamsRunning, "Connected (streams running)");
}

void MediaSessionPrivate::terminated () {
	stopStreams();
	CallSessionPrivate::terminated();
}

/* This callback is called when an incoming re-INVITE/ SIP UPDATE modifies the session */
void MediaSessionPrivate::updated (bool isUpdate) {
383
	SalMediaDescription *rmd = op->get_remote_media_description();
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
	switch (state) {
		case LinphoneCallPausedByRemote:
			if (sal_media_description_has_dir(rmd, SalStreamSendRecv) || sal_media_description_has_dir(rmd, SalStreamRecvOnly)) {
				resumed();
				return;
			}
			break;
		case LinphoneCallStreamsRunning:
		case LinphoneCallConnected:
		case LinphoneCallUpdatedByRemote: /* Can happen on UAC connectivity loss */
			if (sal_media_description_has_dir(rmd, SalStreamSendOnly) || sal_media_description_has_dir(rmd, SalStreamInactive)) {
				pausedByRemote();
				return;
			}
			break;
		default:
			/* The other cases are handled in CallSessionPrivate::updated */
			break;
	}
	CallSessionPrivate::updated(isUpdate);
}

void MediaSessionPrivate::updating (bool isUpdate) {
407
	L_Q();
408
	SalMediaDescription *rmd = op->get_remote_media_description();
409 410 411 412 413
	fixCallParams(rmd);
	if (state != LinphoneCallPaused) {
		/* Refresh the local description, but in paused state, we don't change anything. */
		if (!rmd && lp_config_get_int(linphone_core_get_config(core), "sip", "sdp_200_ack_follow_video_policy", 0)) {
			lInfo() << "Applying default policy for offering SDP on CallSession [" << q << "]";
414
			params = new MediaSessionParams();
415 416 417
			params->initDefault(core);
		}
		makeLocalMediaDescription();
418
		op->set_local_media_description(localDesc);
419 420 421 422 423
	}
	if (rmd) {
		SalErrorInfo sei;
		memset(&sei, 0, sizeof(sei));
		expectMediaInAck = false;
424
		SalMediaDescription *md = op->get_final_media_description();
425 426
		if (md && (sal_media_description_empty(md) || linphone_core_incompatible_security(core, md))) {
			sal_error_info_set(&sei, SalReasonNotAcceptable, "SIP", 0, nullptr, nullptr);
427
			op->decline_with_error_info(&sei, nullptr);
428 429 430 431 432 433 434 435 436
			sal_error_info_reset(&sei);
			return;
		}
		SalMediaDescription *prevResultDesc = resultDesc;
		if (isUpdate && prevResultDesc && md){
			int diff = sal_media_description_equals(prevResultDesc, md);
			if (diff & (SAL_MEDIA_DESCRIPTION_CRYPTO_POLICY_CHANGED | SAL_MEDIA_DESCRIPTION_STREAMS_CHANGED)) {
				lWarning() << "Cannot accept this update, it is changing parameters that require user approval";
				sal_error_info_set(&sei, SalReasonUnknown, "SIP", 504, "Cannot change the session parameters without prompting the user", nullptr);
437
				op->decline_with_error_info(&sei, nullptr);
438 439 440 441 442 443 444 445
				sal_error_info_reset(&sei);
				return;
			}
		}
		updated(isUpdate);
	} else {
		/* Case of a reINVITE or UPDATE without SDP */
		expectMediaInAck = true;
446
		op->accept(); /* Respond with an offer */
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
		/* Don't do anything else in this case, wait for the ACK to receive to notify the app */
	}
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::enableSymmetricRtp (bool value) {
	for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
		if (sessions[i].rtp_session)
			rtp_session_set_symmetric_rtp(sessions[i].rtp_session, value);
	}
}

void MediaSessionPrivate::sendVfu () {
#ifdef VIDEO_ENABLED
	if (videoStream)
		video_stream_send_vfu(videoStream);
#endif
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::clearIceCheckList (IceCheckList *cl) {
	if (audioStream && audioStream->ms.ice_check_list == cl)
		audioStream->ms.ice_check_list = nullptr;
	if (videoStream && videoStream->ms.ice_check_list == cl)
		videoStream->ms.ice_check_list = nullptr;
	if (textStream && textStream->ms.ice_check_list == cl)
		textStream->ms.ice_check_list = nullptr;
}

void MediaSessionPrivate::deactivateIce () {
	if (audioStream)
		audioStream->ms.ice_check_list = nullptr;
	if (videoStream)
		videoStream->ms.ice_check_list = nullptr;
	if (textStream)
		textStream->ms.ice_check_list = nullptr;
485 486 487
	_linphone_call_stats_set_ice_state(audioStats, LinphoneIceStateNotActivated);
	_linphone_call_stats_set_ice_state(videoStats, LinphoneIceStateNotActivated);
	_linphone_call_stats_set_ice_state(textStats, LinphoneIceStateNotActivated);
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
	stopStreamsForIceGathering();
}

void MediaSessionPrivate::prepareStreamsForIceGathering (bool hasVideo) {
	if (audioStream->ms.state == MSStreamInitialized)
		audio_stream_prepare_sound(audioStream, nullptr, nullptr);
#ifdef VIDEO_ENABLED
	if (hasVideo && videoStream && (videoStream->ms.state == MSStreamInitialized))
		video_stream_prepare_video(videoStream);
#endif
	if (params->realtimeTextEnabled() && (textStream->ms.state == MSStreamInitialized))
		text_stream_prepare_text(textStream);
}

void MediaSessionPrivate::stopStreamsForIceGathering () {
	if (audioStream && (audioStream->ms.state == MSStreamPreparing))
		audio_stream_unprepare_sound(audioStream);
#ifdef VIDEO_ENABLED
	if (videoStream && (videoStream->ms.state == MSStreamPreparing))
		video_stream_unprepare_video(videoStream);
#endif
	if (textStream && (textStream->ms.state == MSStreamPreparing))
		text_stream_unprepare_text(textStream);
}

// -----------------------------------------------------------------------------

MediaStream * MediaSessionPrivate::getMediaStream (LinphoneStreamType type) const {
	switch (type) {
		case LinphoneStreamTypeAudio:
			return &audioStream->ms;
		case LinphoneStreamTypeVideo:
			return &videoStream->ms;
		case LinphoneStreamTypeText:
			return &textStream->ms;
		case LinphoneStreamTypeUnknown:
		default:
			return nullptr;
	}
}

int MediaSessionPrivate::getRtcpPort (LinphoneStreamType type) const  {
	return mediaPorts[getStreamIndex(getMediaStream(type))].rtcpPort;
}

int MediaSessionPrivate::getRtpPort (LinphoneStreamType type) const {
	return mediaPorts[getStreamIndex(getMediaStream(type))].rtpPort;
}

LinphoneCallStats * MediaSessionPrivate::getStats (LinphoneStreamType type) const {
	switch (type) {
		case LinphoneStreamTypeAudio:
			return audioStats;
		case LinphoneStreamTypeVideo:
			return videoStats;
		case LinphoneStreamTypeText:
			return textStats;
		case LinphoneStreamTypeUnknown:
		default:
			return nullptr;
	}
}

int MediaSessionPrivate::getStreamIndex (LinphoneStreamType type) const {
	return getStreamIndex(getMediaStream(type));
}

int MediaSessionPrivate::getStreamIndex (MediaStream *ms) const {
	if (ms == &audioStream->ms)
		return mainAudioStreamIndex;
	else if (ms == &videoStream->ms)
		return mainVideoStreamIndex;
	else if (ms == &textStream->ms)
		return mainTextStreamIndex;
	return -1;
}

// -----------------------------------------------------------------------------

OrtpJitterBufferAlgorithm MediaSessionPrivate::jitterBufferNameToAlgo (const string &name) {
	if (name == "basic") return OrtpJitterBufferBasic;
	if (name == "rls") return OrtpJitterBufferRecursiveLeastSquare;
	lError() << "Invalid jitter buffer algorithm: " << name;
	return OrtpJitterBufferRecursiveLeastSquare;
}

#ifdef VIDEO_ENABLED
void MediaSessionPrivate::videoStreamEventCb (void *userData, const MSFilter *f, const unsigned int eventId, const void *args) {
	MediaSessionPrivate *msp = reinterpret_cast<MediaSessionPrivate *>(userData);
	msp->videoStreamEventCb(f, eventId, args);
}
#endif

#ifdef TEST_EXT_RENDERER
void MediaSessionPrivate::extRendererCb (void *userData, const MSPicture *local, const MSPicture *remote) {
	lInfo() << "extRendererCb, local buffer=" << local ? local->planes[0] : nullptr
		<< ", remote buffer=" << remote ? remote->planes[0] : nullptr);
}
#endif

void MediaSessionPrivate::realTimeTextCharacterReceived (void *userData, MSFilter *f, unsigned int id, void *arg) {
	MediaSessionPrivate *msp = reinterpret_cast<MediaSessionPrivate *>(userData);
	msp->realTimeTextCharacterReceived(f, id, arg);
}

// -----------------------------------------------------------------------------

float MediaSessionPrivate::aggregateQualityRatings (float audioRating, float videoRating) {
	float result;
	if ((audioRating < 0) && (videoRating < 0))
		result = -1;
	else if (audioRating < 0)
		result = videoRating * 5.0f;
	else if (videoRating < 0)
		result = audioRating * 5.0f;
	else
		result = audioRating * videoRating * 5.0f;
	return result;
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::setState (LinphoneCallState newState, const string &message) {
611
	L_Q();
612
	/* Take a ref on the session otherwise it might get destroyed during the call to setState */
613
	shared_ptr<CallSession> session = q->getSharedFromThis();
614 615 616 617 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 646 647 648 649 650 651 652 653 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 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
	CallSessionPrivate::setState(newState, message);
	updateReportingCallState();
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::computeStreamsIndexes (const SalMediaDescription *md) {
	bool audioFound = false;
	bool videoFound = false;
	bool textFound = false;
	for (int i = 0; i < md->nb_streams; i++) {
		if (md->streams[i].type == SalAudio) {
			if (audioFound)
				lInfo() << "audio stream index found: " << i << ", but main audio stream already set to " << mainAudioStreamIndex;
			else {
				mainAudioStreamIndex = i;
				audioFound = true;
				lInfo() << "audio stream index found: " << i << ", updating main audio stream index";
			}
			/* Check that the default value of a another stream doesn't match the new one */
			if (i == mainVideoStreamIndex) {
				for (int j = 0; j < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; j++) {
					if (sal_stream_description_active(&md->streams[j]))
						continue;
					if ((j != mainVideoStreamIndex) && (j != mainTextStreamIndex)) {
						lInfo() << i << " was used for video stream ; now using " << j;
						mainVideoStreamIndex = j;
						break;
					}
				}
			}
			if (i == mainTextStreamIndex) {
				for (int j = 0; j < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; j++) {
					if (sal_stream_description_active(&md->streams[j]))
						continue;
					if ((j != mainVideoStreamIndex) && (j != mainTextStreamIndex)) {
						lInfo() << i << " was used for text stream ; now using " << j;
						mainTextStreamIndex = j;
						break;
					}
				}
			}
		} else if (md->streams[i].type == SalVideo) {
			if (videoFound)
				lInfo() << "video stream index found: " << i << ", but main video stream already set to " << mainVideoStreamIndex;
			else {
				mainVideoStreamIndex = i;
				videoFound = true;
				lInfo() << "video stream index found: " << i << ", updating main video stream index";
			}
			/* Check that the default value of a another stream doesn't match the new one */
			if (i == mainAudioStreamIndex) {
				for (int j = 0; j < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; j++) {
					if (sal_stream_description_active(&md->streams[j]))
						continue;
					if ((j != mainAudioStreamIndex) && (j != mainTextStreamIndex)) {
						lInfo() << i << " was used for audio stream ; now using " << j;
						mainAudioStreamIndex = j;
						break;
					}
				}
			}
			if (i == mainTextStreamIndex) {
				for (int j = 0; j < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; j++) {
					if (sal_stream_description_active(&md->streams[j]))
						continue;
					if ((j != mainAudioStreamIndex) && (j != mainTextStreamIndex)) {
						lInfo() << i << " was used for text stream ; now using " << j;
						mainTextStreamIndex = j;
						break;
					}
				}
			}
		} else if (md->streams[i].type == SalText) {
			if (textFound)
				lInfo() << "text stream index found: " << i << ", but main text stream already set to " << mainTextStreamIndex;
			else {
				mainTextStreamIndex = i;
				textFound = true;
				lInfo() << "text stream index found: " << i << ", updating main text stream index";
			}
			/* Check that the default value of a another stream doesn't match the new one */
			if (i == mainAudioStreamIndex) {
				for (int j = 0; j < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; j++) {
					if (sal_stream_description_active(&md->streams[j]))
						continue;
					if ((j != mainVideoStreamIndex) && (j != mainAudioStreamIndex)) {
						lInfo() << i << " was used for audio stream ; now using " << j;
						mainAudioStreamIndex = j;
						break;
					}
				}
			}
			if (i == mainVideoStreamIndex) {
				for (int j = 0; j < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; j++) {
					if (sal_stream_description_active(&md->streams[j]))
						continue;
					if ((j != mainVideoStreamIndex) && (j != mainAudioStreamIndex)) {
						lInfo() << i << " was used for video stream ; now using " << j;
						mainVideoStreamIndex = j;
						break;
					}
				}
			}
		}
	}
}

/*
 * This method needs to be called at each incoming reINVITE, in order to adjust various local parameters to what is being offered by remote:
 * - the stream indexes.
 * - the video enablement parameter according to what is offered and our local policy.
 * Fixing the params to proper values avoid request video by accident during internal call updates, pauses and resumes
 */
void MediaSessionPrivate::fixCallParams (SalMediaDescription *rmd) {
729
	L_Q();
730 731 732 733 734 735 736 737 738 739 740 741
	if (rmd) {
		computeStreamsIndexes(rmd);
		updateBiggestDesc(rmd);
		/* Why disabling implicit_rtcp_fb ? It is a local policy choice actually. It doesn't disturb to propose it again and again
		 * even if the other end apparently doesn't support it.
		 * The following line of code is causing trouble, while for example making an audio call, then adding video.
		 * Due to the 200Ok response of the audio-only offer where no rtcp-fb attribute is present, implicit_rtcp_fb is set to
		 * false, which is then preventing it to be eventually used when video is later added to the call.
		 * I did the choice of commenting it out.
		 */
		/*params.getPrivate()->enableImplicitRtcpFb(params.getPrivate()->implicitRtcpFbEnabled() & sal_media_description_has_implicit_avpf(rmd));*/
	}
742
	const MediaSessionParams *rcp = q->getRemoteParams();
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
	if (rcp) {
		if (params->audioEnabled() && !rcp->audioEnabled()) {
			lInfo() << "CallSession [" << q << "]: disabling audio in our call params because the remote doesn't want it";
			params->enableAudio(false);
		}
		if (params->videoEnabled() && !rcp->videoEnabled()) {
			lInfo() << "CallSession [" << q << "]: disabling video in our call params because the remote doesn't want it";
			params->enableVideo(false);
		}
		if (rcp->videoEnabled() && core->video_policy.automatically_accept && linphone_core_video_enabled(core) && !params->videoEnabled()) {
			lInfo() << "CallSession [" << q << "]: re-enabling video in our call params because the remote wants it and the policy allows to automatically accept";
			params->enableVideo(true);
		}
		if (rcp->realtimeTextEnabled() && !params->realtimeTextEnabled())
			params->enableRealtimeText(true);
	}
}

void MediaSessionPrivate::initializeParamsAccordingToIncomingCallParams () {
	CallSessionPrivate::initializeParamsAccordingToIncomingCallParams();
	currentParams->getPrivate()->setUpdateCallWhenIceCompleted(params->getPrivate()->getUpdateCallWhenIceCompleted());
	params->enableVideo(linphone_core_video_enabled(core) && core->video_policy.automatically_accept);
765
	SalMediaDescription *md = op->get_remote_media_description();
766 767 768 769
	if (md) {
		/* It is licit to receive an INVITE without SDP, in this case WE choose the media parameters according to policy */
		setCompatibleIncomingCallParams(md);
		/* Set multicast role & address if any */
770
		if (!op->is_offerer()) {
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
			for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
				if (md->streams[i].dir == SalStreamInactive)
					continue;
				if ((md->streams[i].rtp_addr[0] != '\0') && ms_is_multicast(md->streams[i].rtp_addr)) {
					md->streams[i].multicast_role = SalMulticastReceiver;
					mediaPorts[i].multicastIp = md->streams[i].rtp_addr;
				}
			}
		}
	}
}

/**
 * Fix call parameters on incoming call to eg. enable AVPF if the incoming call propose it and it is not enabled locally.
 */
void MediaSessionPrivate::setCompatibleIncomingCallParams (SalMediaDescription *md) {
	/* Handle AVPF, SRTP and DTLS */
788
	params->enableAvpf(!!sal_media_description_has_avpf(md));
789
	if (destProxy)
Ronan's avatar
Ronan committed
790
		params->setAvpfRrInterval(static_cast<uint16_t>(linphone_proxy_config_get_avpf_rr_interval(destProxy) * 1000));
791
	else
Ronan's avatar
Ronan committed
792
		params->setAvpfRrInterval(static_cast<uint16_t>(linphone_core_get_avpf_rr_interval(core) * 1000));
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
	if (sal_media_description_has_zrtp(md) && linphone_core_media_encryption_supported(core, LinphoneMediaEncryptionZRTP))
		params->setMediaEncryption(LinphoneMediaEncryptionZRTP);
	else if (sal_media_description_has_dtls(md) && media_stream_dtls_supported())
		params->setMediaEncryption(LinphoneMediaEncryptionDTLS);
	else if (sal_media_description_has_srtp(md) && ms_srtp_supported())
		params->setMediaEncryption(LinphoneMediaEncryptionSRTP);
	else if (params->getMediaEncryption() != LinphoneMediaEncryptionZRTP)
		params->setMediaEncryption(LinphoneMediaEncryptionNone);
	/* In case of nat64, even ipv4 addresses are reachable from v6. Should be enhanced to manage stream by stream connectivity (I.E v6 or v4) */
	/*if (!sal_media_description_has_ipv6(md)){
		lInfo() << "The remote SDP doesn't seem to offer any IPv6 connectivity, so disabling IPv6 for this call";
		af = AF_INET;
	}*/
	fixCallParams(md);
}

void MediaSessionPrivate::updateBiggestDesc (SalMediaDescription *md) {
	if (!biggestDesc || (md->nb_streams > biggestDesc->nb_streams)) {
		/* We have been offered and now are ready to proceed, or we added a new stream,
		 * store the media description to remember the mapping of calls */
		if (biggestDesc) {
			sal_media_description_unref(biggestDesc);
			biggestDesc = nullptr;
		}
		biggestDesc = sal_media_description_ref(md);
	}
}

void MediaSessionPrivate::updateRemoteSessionIdAndVer () {
822
	SalMediaDescription *desc = op->get_remote_media_description();
823 824 825 826 827 828 829 830 831
	if (desc) {
		remoteSessionId = desc->session_id;
		remoteSessionVer = desc->session_ver;
	}
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::initStats (LinphoneCallStats *stats, LinphoneStreamType type) {
832 833 834 835
	_linphone_call_stats_set_type(stats, type);
	_linphone_call_stats_set_received_rtcp(stats, nullptr);
	_linphone_call_stats_set_sent_rtcp(stats, nullptr);
	_linphone_call_stats_set_ice_state(stats, LinphoneIceStateNotActivated);
836 837 838 839 840 841 842 843 844 845 846 847
}

void MediaSessionPrivate::notifyStatsUpdated (int streamIndex) const {
	LinphoneCallStats *stats = nullptr;
	if (streamIndex == mainAudioStreamIndex)
		stats = audioStats;
	else if (streamIndex == mainVideoStreamIndex)
		stats = videoStats;
	else if (streamIndex == mainTextStreamIndex)
		stats = textStats;
	else
		return;
848 849
	if (_linphone_call_stats_get_updated(stats)) {
		switch (_linphone_call_stats_get_updated(stats)) {
850 851 852 853 854 855 856 857 858 859
			case LINPHONE_CALL_STATS_RECEIVED_RTCP_UPDATE:
			case LINPHONE_CALL_STATS_SENT_RTCP_UPDATE:
#if 0
				linphone_reporting_on_rtcp_update(call, stream_index == call->main_audio_stream_index ? SalAudio : stream_index == call->main_video_stream_index ? SalVideo : SalText);
#endif
				break;
			default:
				break;
		}
		if (listener)
860
			listener->onStatsUpdated(stats);
861
		_linphone_call_stats_set_updated(stats, 0);
862 863 864 865 866 867 868 869 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
	}
}

// -----------------------------------------------------------------------------

OrtpEvQueue * MediaSessionPrivate::getEventQueue (int streamIndex) const {
	if (streamIndex == mainAudioStreamIndex)
		return audioStreamEvQueue;
	if (streamIndex == mainVideoStreamIndex)
		return videoStreamEvQueue;
	if (streamIndex == mainTextStreamIndex)
		return textStreamEvQueue;
	lError() << "getEventQueue(): no stream index " << streamIndex;
	return nullptr;
}

MediaStream * MediaSessionPrivate::getMediaStream (int streamIndex) const {
	if (streamIndex == mainAudioStreamIndex)
		return &audioStream->ms;
	if (streamIndex == mainVideoStreamIndex)
		return &videoStream->ms;
	if (streamIndex == mainTextStreamIndex)
		return &textStream->ms;
	lError() << "getMediaStream(): no stream index " << streamIndex;
	return nullptr;
}

MSWebCam * MediaSessionPrivate::getVideoDevice () const {
	bool paused = (state == LinphoneCallPausing) || (state == LinphoneCallPaused);
	if (paused || allMuted || !cameraEnabled)
		return get_nowebcam_device(core->factory);
	else
		return core->video_conf.device;
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::fillMulticastMediaAddresses () {
	if (params->audioMulticastEnabled())
		mediaPorts[mainAudioStreamIndex].multicastIp = linphone_core_get_audio_multicast_addr(core);
	if (params->videoMulticastEnabled())
		mediaPorts[mainVideoStreamIndex].multicastIp = linphone_core_get_video_multicast_addr(core);
}

int MediaSessionPrivate::selectFixedPort (int streamIndex, pair<int, int> portRange) {
	for (int triedPort = portRange.first; triedPort < (portRange.first + 100); triedPort += 2) {
		bool alreadyUsed = false;
		for (const bctbx_list_t *elem = linphone_core_get_calls(core); elem != nullptr; elem = bctbx_list_next(elem)) {
			LinphoneCall *lcall = reinterpret_cast<LinphoneCall *>(bctbx_list_get_data(elem));
911
			MediaSession *session = dynamic_cast<MediaSession *>(L_GET_PRIVATE_FROM_C_OBJECT(lcall)->getConference()->getActiveParticipant()->getPrivate()->getSession().get());
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
			int existingPort = session->getPrivate()->mediaPorts[streamIndex].rtpPort;
			if (existingPort == triedPort) {
				alreadyUsed = true;
				break;
			}
		}
		if (!alreadyUsed)
			return triedPort;
	}

	lError() << "Could not find any free port !";
	return -1;
}

int MediaSessionPrivate::selectRandomPort (int streamIndex, pair<int, int> portRange) {
	for (int nbTries = 0; nbTries < 100; nbTries++) {
		bool alreadyUsed = false;
Benjamin REIS's avatar
Benjamin REIS committed
929
		int triedPort = (static_cast<int>(ortp_random()) % (portRange.second - portRange.first) + portRange.first) & ~0x1;
930 931 932
		if (triedPort < portRange.first) triedPort = portRange.first + 2;
		for (const bctbx_list_t *elem = linphone_core_get_calls(core); elem != nullptr; elem = bctbx_list_next(elem)) {
			LinphoneCall *lcall = reinterpret_cast<LinphoneCall *>(bctbx_list_get_data(elem));
933
			MediaSession *session = dynamic_cast<MediaSession *>(L_GET_PRIVATE_FROM_C_OBJECT(lcall)->getConference()->getActiveParticipant()->getPrivate()->getSession().get());
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 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 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
			int existingPort = session->getPrivate()->mediaPorts[streamIndex].rtpPort;
			if (existingPort == triedPort) {
				alreadyUsed = true;
				break;
			}
		}
		if (!alreadyUsed)
			return triedPort;
	}

	lError() << "Could not find any free port!";
	return -1;
}

void MediaSessionPrivate::setPortConfig(int streamIndex, pair<int, int> portRange) {
	if ((portRange.first <= 0) && (portRange.second <= 0)) {
		setRandomPortConfig(streamIndex);
	} else {
		if (portRange.first == portRange.second) {
			/* Fixed port */
			int port = selectFixedPort(streamIndex, portRange);
			if (port == -1) {
				setRandomPortConfig(streamIndex);
				return;
			}
			mediaPorts[streamIndex].rtpPort = port;
		} else {
			/* Select random port in the specified range */
			mediaPorts[streamIndex].rtpPort = selectRandomPort(streamIndex, portRange);
		}
		mediaPorts[streamIndex].rtcpPort = mediaPorts[streamIndex].rtpPort + 1;
	}
}

void MediaSessionPrivate::setPortConfigFromRtpSession (int streamIndex, RtpSession *session) {
	mediaPorts[streamIndex].rtpPort = rtp_session_get_local_port(session);
	mediaPorts[streamIndex].rtcpPort = rtp_session_get_local_rtcp_port(session);
}

void MediaSessionPrivate::setRandomPortConfig (int streamIndex) {
	mediaPorts[streamIndex].rtpPort = -1;
	mediaPorts[streamIndex].rtcpPort = -1;
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::discoverMtu (const Address &remoteAddr) {
	if (core->net_conf.mtu == 0) {
		/* Attempt to discover mtu */
		int mtu = ms_discover_mtu(remoteAddr.getDomain().c_str());
		if (mtu > 0) {
			ms_factory_set_mtu(core->factory, mtu);
			lInfo() << "Discovered mtu is " << mtu << ", RTP payload max size is " << ms_factory_get_payload_max_size(core->factory);
		}
	}
}

string MediaSessionPrivate::getBindIpForStream (int streamIndex) {
	string bindIp = lp_config_get_string(linphone_core_get_config(core), "rtp", "bind_address", (af == AF_INET6) ? "::0" : "0.0.0.0");
	PortConfig *pc = &mediaPorts[streamIndex];
	if (!pc->multicastIp.empty()){
		if (direction == LinphoneCallOutgoing) {
			/* As multicast sender, we must decide a local interface to use to send multicast, and bind to it */
			char multicastBindIp[LINPHONE_IPADDR_SIZE];
			memset(multicastBindIp, 0, sizeof(multicastBindIp));
			linphone_core_get_local_ip_for(pc->multicastIp.find_first_of(':') ? AF_INET6 : AF_INET, nullptr, multicastBindIp);
			bindIp = pc->multicastBindIp = multicastBindIp;
		} else {
			/* Otherwise we shall use an address family of the same family of the multicast address, because
			 * dual stack socket and multicast don't work well on Mac OS (linux is OK, as usual). */
			bindIp = pc->multicastIp.find_first_of(':') ? "::0" : "0.0.0.0";
		}
	}
	return bindIp;
}

/**
 * Fill the local ip that routes to the internet according to the destination, or guess it by other special means.
 */
void MediaSessionPrivate::getLocalIp (const Address &remoteAddr) {
	/* Next, sometime, override from config */
	const char *ip = lp_config_get_string(linphone_core_get_config(core), "rtp", "bind_address", nullptr);
	if (ip) {
		mediaLocalIp = ip;
		return;
	}

	/* If a known proxy was identified for this call, then we may have a chance to take the local ip address
	 * from the socket that connects to this proxy */
	if (destProxy && destProxy->op) {
1024
		ip = destProxy->op->get_local_address(nullptr);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
		if (ip) {
			lInfo() << "Found media local-ip from signaling.";
			mediaLocalIp = ip;
			return;
		}
	}

	/* In last resort, attempt to find the local ip that routes to destination if given as an IP address,
	   or the default route (dest == nullptr) */
	const char *dest = nullptr;
	if (!destProxy) {
		struct addrinfo hints;
		struct addrinfo *res = nullptr;
		int err;
		/* FIXME the following doesn't work for IPv6 address because of brakets */
		memset(&hints, 0, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_DGRAM;
		hints.ai_flags = AI_NUMERICHOST;
		err = getaddrinfo(remoteAddr.getDomain().c_str(), NULL, &hints, &res);
		if (err == 0)
			dest = remoteAddr.getDomain().c_str();
		if (res) freeaddrinfo(res);
	}

	if (dest || mediaLocalIp.empty() || needMediaLocalIpRefresh) {
		needMediaLocalIpRefresh = false;
		char ip[LINPHONE_IPADDR_SIZE];
		linphone_core_get_local_ip(core, af, dest, ip);
		mediaLocalIp = ip;
	}
}

string MediaSessionPrivate::getPublicIpForStream (int streamIndex) {
	if (!mediaPorts[streamIndex].multicastIp.empty())
		return mediaPorts[streamIndex].multicastIp;
	return mediaLocalIp;
}

void MediaSessionPrivate::runStunTestsIfNeeded () {
	if (linphone_nat_policy_stun_enabled(natPolicy) && !(linphone_nat_policy_ice_enabled(natPolicy) || linphone_nat_policy_turn_enabled(natPolicy))) {
		stunClient = new StunClient(core);
		int ret = stunClient->run(mediaPorts[mainAudioStreamIndex].rtpPort, mediaPorts[mainVideoStreamIndex].rtpPort, mediaPorts[mainTextStreamIndex].rtpPort);
		if (ret >= 0)
			pingTime = ret;
	}
}

/*
 * Select IP version to use for advertising local addresses of RTP streams, for an incoming call.
 * If the call is received through a know proxy that is IPv6, use IPv6.
 * Otherwise check the remote contact address.
 * If later the resulting media description tells that we have to send IPv4, it won't be a problem because the RTP sockets
 * are dual stack.
 */
void MediaSessionPrivate::selectIncomingIpVersion () {
	if (linphone_core_ipv6_enabled(core)) {
		if (destProxy && destProxy->op)
1083
			af = destProxy->op->get_address_family();
1084
		else
1085
			af = op->get_address_family();
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
	} else
		af = AF_INET;
}

/*
 * Choose IP version we are going to use for RTP streams IP address advertised in SDP.
 * The algorithm is as follows:
 * - if ipv6 is disabled at the core level, it is always AF_INET
 * - Otherwise, if the destination address for the call is an IPv6 address, use IPv6.
 * - Otherwise, if the call is done through a known proxy config, then use the information obtained during REGISTER
 * to know if IPv6 is supported by the server.
**/
void MediaSessionPrivate::selectOutgoingIpVersion () {
	if (!linphone_core_ipv6_enabled(core)) {
		af = AF_INET;
		return;
	}

1104
	const LinphoneAddress *to = linphone_call_log_get_to_address(log);
1105
	if (sal_address_is_ipv6(L_GET_PRIVATE_FROM_C_OBJECT(to)->getInternalAddress()))
1106 1107
		af = AF_INET6;
	else if (destProxy && destProxy->op)
1108
		af = destProxy->op->get_address_family();
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
	else {
		char ipv4[LINPHONE_IPADDR_SIZE];
		char ipv6[LINPHONE_IPADDR_SIZE];
		bool haveIpv6 = false;
		bool haveIpv4 = false;
		/* Check connectivity for IPv4 and IPv6 */
		if (linphone_core_get_local_ip_for(AF_INET6, NULL, ipv6) == 0)
			haveIpv6 = true;
		if (linphone_core_get_local_ip_for(AF_INET, NULL, ipv4) == 0)
			haveIpv4 = true;
		if (haveIpv6) {
			if (!haveIpv4)
				af = AF_INET6;
			else if (lp_config_get_int(linphone_core_get_config(core), "rtp", "prefer_ipv6", 1)) /* This property tells whether ipv6 is prefered if two versions are available */
				af = AF_INET6;
			else
				af = AF_INET;
		} else
			af = AF_INET;
		/* Fill the media_localip default value since we have it here */
		mediaLocalIp = (af == AF_INET6) ? ipv6 : ipv4;
	}
}

// -----------------------------------------------------------------------------

void MediaSessionPrivate::forceStreamsDirAccordingToState (SalMediaDescription *md) {
1136
	L_Q();
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
	for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
		SalStreamDescription *sd = &md->streams[i];
		switch (state) {
			case LinphoneCallPausing:
			case LinphoneCallPaused:
				if (sd->dir != SalStreamInactive) {
					sd->dir = SalStreamSendOnly;
					if ((sd->type == SalVideo) && lp_config_get_int(linphone_core_get_config(core), "sip", "inactive_video_on_pause", 0))
						sd->dir = SalStreamInactive;
				}
				break;
			default:
				break;
		}
		/* Reflect the stream directions in the call params */
		if (i == mainAudioStreamIndex)
			q->getCurrentParams()->setAudioDirection(MediaSessionParamsPrivate::salStreamDirToMediaDirection(sd->dir));
		else if (i == mainVideoStreamIndex)
			q->getCurrentParams()->setVideoDirection(MediaSessionParamsPrivate::salStreamDirToMediaDirection(sd->dir));
	}
}

bool MediaSessionPrivate::generateB64CryptoKey (size_t keyLength, char *keyOut, size_t keyOutSize) {
	uint8_t *tmp = (uint8_t *)ms_malloc0(keyLength);
	if (sal_get_random_bytes(tmp, keyLength)) {
		lError() << "Failed to generate random key";
		ms_free(tmp);
		return false;
	}
	size_t b64Size = b64::b64_encode((const char *)tmp, keyLength, nullptr, 0);
	if (b64Size == 0) {
		lError() << "Failed to get b64 result size";
		ms_free(tmp);
		return false;
	}
	if (b64Size >= keyOutSize) {
		lError() << "Insufficient room for writing base64 SRTP key";
		ms_free(tmp);
		return false;
	}
	b64Size = b64::b64_encode((const char *)tmp, keyLength, keyOut, keyOutSize);
	if (b64Size == 0) {
		lError() << "Failed to b64 encode key";
		ms_free(tmp);
		return false;
	}
	keyOut[b64Size] = '\0';
	ms_free(tmp);
	return true;
}

void MediaSessionPrivate::makeLocalMediaDescription () {
1189
	L_Q();
1190
	int maxIndex = 0;
1191
	bool rtcpMux = !!lp_config_get_int(linphone_core_get_config(core), "rtp", "rtcp_mux", 0);
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
	SalMediaDescription *md = sal_media_description_new();
	SalMediaDescription *oldMd = localDesc;

	/* Multicast is only set in case of outgoing call */
	if (direction == LinphoneCallOutgoing) {
		if (params->audioMulticastEnabled()) {
			md->streams[mainAudioStreamIndex].ttl = linphone_core_get_audio_multicast_ttl(core);
			md->streams[mainAudioStreamIndex].multicast_role = SalMulticastSender;
		}
		if (params->videoMulticastEnabled()) {
			md->streams[mainVideoStreamIndex].ttl = linphone_core_get_video_multicast_ttl(core);
			md->streams[mainVideoStreamIndex].multicast_role = SalMulticastSender;
		}
	}

	params->getPrivate()->adaptToNetwork(core, pingTime);

	string subject = q->getParams()->getSessionName();
	if (!subject.empty())
		strncpy(md->name, subject.c_str(), sizeof(md->name));
	md->session_id = (oldMd ? oldMd->session_id : (rand() & 0xfff));
	md->session_ver = (oldMd ? (oldMd->session_ver + 1) : (rand() & 0xfff));
	md->nb_streams = (biggestDesc ? biggestDesc->nb_streams : 1);

	/* Re-check local ip address each time we make a new offer, because it may change in case of network reconnection */
1217 1218
	{
		LinphoneAddress *address = (direction == LinphoneCallOutgoing ? log->to : log->from);
1219
		getLocalIp(*L_GET_CPP_PTR_FROM_C_OBJECT(address));
1220 1221
	}

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
	strncpy(md->addr, mediaLocalIp.c_str(), sizeof(md->addr));
	LinphoneAddress *addr = nullptr;
	if (destProxy) {
		addr = linphone_address_clone(linphone_proxy_config_get_identity_address(destProxy));
	} else {
		addr = linphone_address_new(linphone_core_get_identity(core));
	}
	if (linphone_address_get_username(addr)) /* Might be null in case of identity without userinfo */
		strncpy(md->username, linphone_address_get_username(addr), sizeof(md->username));
	linphone_address_unref(addr);

	int bandwidth = params->getPrivate()->getDownBandwidth();
	if (bandwidth)
		md->bandwidth = bandwidth;
	else
		md->bandwidth = linphone_core_get_download_bandwidth(core);

	SalCustomSdpAttribute *customSdpAttributes = params->getPrivate()->getCustomSdpAttributes();
	if (customSdpAttributes)
		md->custom_sdp_attributes = sal_custom_sdp_attribute_clone(customSdpAttributes);

	PayloadTypeHandler pth(core);

	bctbx_list_t *l = pth.makeCodecsList(SalAudio, params->getAudioBandwidthLimit(), -1,
		oldMd ? oldMd->streams[mainAudioStreamIndex].already_assigned_payloads : nullptr);
	if (l && params->audioEnabled()) {
		strncpy(md->streams[mainAudioStreamIndex].rtp_addr, getPublicIpForStream(mainAudioStreamIndex).c_str(), sizeof(md->streams[mainAudioStreamIndex].rtp_addr));
		strncpy(md->streams[mainAudioStreamIndex].rtcp_addr, getPublicIpForStream(mainAudioStreamIndex).c_str(), sizeof(md->streams[mainAudioStreamIndex].rtcp_addr));
		strncpy(md->streams[mainAudioStreamIndex].name, "Audio", sizeof(md->streams[mainAudioStreamIndex].name) - 1);
		md->streams[mainAudioStreamIndex].rtp_port = mediaPorts[mainAudioStreamIndex].rtpPort;
		md->streams[mainAudioStreamIndex].rtcp_port = mediaPorts[mainAudioStreamIndex].rtcpPort;
		md->streams[mainAudioStreamIndex].proto = params->getMediaProto();
		md->streams[mainAudioStreamIndex].dir = params->getPrivate()->getSalAudioDirection();
		md->streams[mainAudioStreamIndex].type = SalAudio;
		md->streams[mainAudioStreamIndex].rtcp_mux = rtcpMux;
		int downPtime = params->getPrivate()->getDownPtime();
		if (downPtime)
			md->streams[mainAudioStreamIndex].ptime = downPtime;
		else
			md->streams[mainAudioStreamIndex].ptime = linphone_core_get_download_ptime(core);
		md->streams[mainAudioStreamIndex].max_rate = pth.getMaxCodecSampleRate(l);
		md->streams[mainAudioStreamIndex].payloads = l;
		if (audioStream && audioStream->ms.sessions.rtp_session) {
			md->streams[mainAudioStreamIndex].rtp_ssrc = rtp_session_get_send_ssrc(audioStream->ms.sessions.rtp_session);
			strncpy(md->streams[mainAudioStreamIndex].rtcp_cname, conference.getMe()->getAddress().asStringUriOnly().c_str(), sizeof(md->streams[mainAudioStreamIndex].rtcp_cname));
		}
		else
			lWarning() << "Cannot get audio local ssrc for CallSession [" << q << "]";
		if (mainAudioStreamIndex > maxIndex)
			maxIndex = mainAudioStreamIndex;
	} else {
		lInfo() << "Don't put audio stream on local offer for CallSession [" << q << "]";
		md->streams[mainAudioStreamIndex].dir = SalStreamInactive;
		if(l)
			l = bctbx_list_free_with_data(l, (bctbx_list_free_func)payload_type_destroy);
	}
	SalCustomSdpAttribute *sdpMediaAttributes = params->getPrivate()->getCustomSdpMediaAttributes(LinphoneStreamTypeAudio);
	if (sdpMediaAttributes)
		md->streams[mainAudioStreamIndex].custom_sdp_attributes = sal_custom_sdp_attribute_clone(sdpMediaAttributes);

	md->streams[mainVideoStreamIndex].proto = md->streams[mainAudioStreamIndex].proto;
	md->streams[mainVideoStreamIndex].dir = params->getPrivate()->getSalVideoDirection();
	md->streams[mainVideoStreamIndex].type = SalVideo;
	md->streams[mainVideoStreamIndex].rtcp_mux = rtcpMux;
	strncpy(md->streams[mainVideoStreamIndex].name, "Video", sizeof(md->streams[mainVideoStreamIndex].name) - 1);

	l = pth.makeCodecsList(SalVideo, 0, -1,
		oldMd ? oldMd->streams[mainVideoStreamIndex].already_assigned_payloads : nullptr);
	if (l && params->videoEnabled()){
		strncpy(md->streams[mainVideoStreamIndex].rtp_addr, getPublicIpForStream(mainVideoStreamIndex).c_str(), sizeof(md->streams[mainVideoStreamIndex].rtp_addr));
		strncpy(md->streams[mainVideoStreamIndex].rtcp_addr, getPublicIpForStream(mainVideoStreamIndex).c_str(), sizeof(md->streams[mainVideoStreamIndex].rtcp_addr));
		md->streams[mainVideoStreamIndex].rtp_port = mediaPorts[mainVideoStreamIndex].rtpPort;
		md->streams[mainVideoStreamIndex].rtcp_port = mediaPorts[mainVideoStreamIndex].rtcpPort;
		md->streams[mainVideoStreamIndex].payloads = l;
		if (videoStream && videoStream->ms.sessions.rtp_session) {
			md->streams[mainVideoStreamIndex].rtp_ssrc = rtp_session_get_send_ssrc(videoStream->ms.sessions.rtp_session);
			strncpy(md->streams[mainVideoStreamIndex].rtcp_cname, conference.getMe()->getAddress().asStringUriOnly().c_str(), sizeof(md->streams[mainVideoStreamIndex].rtcp_cname));
		} else
			lWarning() << "Cannot get video local ssrc for CallSession [" << q << "]";
		if (mainVideoStreamIndex > maxIndex)
			maxIndex = mainVideoStreamIndex;
	} else {
		lInfo() << "Don't put video stream on local offer for CallSession [" << q << "]";
		md->streams[mainVideoStreamIndex].dir = SalStreamInactive;
		if(l)
			l = bctbx_list_free_with_data(l, (bctbx_list_free_func)payload_type_destroy);
	}
	sdpMediaAttributes = params->getPrivate()->getCustomSdpMediaAttributes(LinphoneStreamTypeVideo);
	if (sdpMediaAttributes)
		md->streams[mainVideoStreamIndex].custom_sdp_attributes = sal_custom_sdp_attribute_clone(sdpMediaAttributes);

	md->streams[mainTextStreamIndex].proto = md->streams[mainAudioStreamIndex].proto;
	md->streams[mainTextStreamIndex].dir = SalStreamSendRecv;
	md->streams[mainTextStreamIndex].type = SalText;
	md->streams[mainTextStreamIndex].rtcp_mux = rtcpMux;
	strncpy(md->streams[mainTextStreamIndex].name, "Text", sizeof(md->streams[mainTextStreamIndex].name) - 1);
	if (params->realtimeTextEnabled()) {
		strncpy(md->streams[mainTextStreamIndex].rtp_addr, getPublicIpForStream(mainTextStreamIndex).c_str(), sizeof(md->streams[mainTextStreamIndex].rtp_addr));
		strncpy(md->streams[mainTextStreamIndex].rtcp_addr, getPublicIpForStream(mainTextStreamIndex).c_str(), sizeof(md->streams[mainTextStreamIndex].rtcp_addr));

		md->streams[mainTextStreamIndex].rtp_port = mediaPorts[mainTextStreamIndex].rtpPort;
		md->streams[mainTextStreamIndex].rtcp_port = mediaPorts[mainTextStreamIndex].rtcpPort;

		l = pth.makeCodecsList(SalText, 0, -1,
			oldMd ? oldMd->streams[mainTextStreamIndex].already_assigned_payloads : nullptr);
		md->streams[mainTextStreamIndex].payloads = l;
		if (textStream && textStream->ms.sessions.rtp_session) {
			md->streams[mainTextStreamIndex].rtp_ssrc = rtp_session_get_send_ssrc(textStream->ms.sessions.rtp_session);
			strncpy(md->streams[mainTextStreamIndex].rtcp_cname, conference.getMe()->getAddress().asStringUriOnly().c_str(), sizeof(md->streams[mainTextStreamIndex].rtcp_cname));
		} else
			lWarning() << "Cannot get text local ssrc for CallSession [" << q << "]";
		if (mainTextStreamIndex > maxIndex)
			maxIndex = mainTextStreamIndex;
	} else {
		lInfo() << "Don't put text stream on local offer for CallSession [" << q << "]";
		md->streams[mainTextStreamIndex].dir = SalStreamInactive;
	}
	sdpMediaAttributes = params->getPrivate()->getCustomSdpMediaAttributes(LinphoneStreamTypeText);
	if (sdpMediaAttributes)
		md->streams[mainTextStreamIndex].custom_sdp_attributes = sal_custom_sdp_attribute_clone(sdpMediaAttributes);

	md->nb_streams = MAX(md->nb_streams, maxIndex + 1);

	/* Deactivate unused streams */
	for (int i = md->nb_streams; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
		if (md->streams[i].rtp_port == 0) {
			md->streams[i].dir = SalStreamInactive;
			if (biggestDesc && (i < biggestDesc->nb_streams)) {
				md->streams[i].proto = biggestDesc->streams[i].proto;
				md->streams[i].type = biggestDesc->streams[i].type;
			}
		}
	}
	setupEncryptionKeys(md);
	setupDtlsKeys(md);
	setupZrtpHash(md);
	setupRtcpFb(md);
	setupRtcpXr(md);
	if (stunClient)
		stunClient->updateMediaDescription(md);
	localDesc = md;
	updateLocalMediaDescriptionFromIce();
	if (oldMd) {
		transferAlreadyAssignedPayloadTypes(oldMd, md);
		localDescChanged = sal_media_description_equals(md, oldMd);
		sal_media_description_unref(oldMd);
		if (params->getPrivate()->getInternalCallUpdate()) {
			/*
			 * An internal call update (ICE reINVITE) is not expected to modify the actual media stream parameters.
			 * However, the localDesc may change between first INVITE and ICE reINVITE, for example if the remote party has declined a video stream.
			 * We use the internalCallUpdate flag to prevent trigger an unnecessary media restart.
			 */
			localDescChanged = 0;
		}
	}
	forceStreamsDirAccordingToState(md);
}

void MediaSessionPrivate::setupDtlsKeys (SalMediaDescription *md) {
	for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
		if (!sal_stream_description_active(&md->streams[i]))
			continue;
		/* If media encryption is set to DTLS check presence of fingerprint in the call which shall have been set at stream init
		 * but it may have failed when retrieving certificate resulting in no fingerprint present and then DTLS not usable */
		if (sal_stream_description_has_dtls(&md->streams[i])) {
			/* Get the self fingerprint from call (it's computed at stream init) */
			strncpy(md->streams[i].dtls_fingerprint, dtlsCertificateFingerprint.c_str(), sizeof(md->streams[i].dtls_fingerprint));
			/* If we are offering, SDP will have actpass setup attribute when role is unset, if we are responding the result mediadescription will be set to SalDtlsRoleIsClient */
			md->streams[i].dtls_role = SalDtlsRoleUnset;
		} else {
			md->streams[i].dtls_fingerprint[0] = '\0';
			md->streams[i].dtls_role = SalDtlsRoleInvalid;
		}
	}
}

int MediaSessionPrivate::setupEncryptionKey (SalSrtpCryptoAlgo *crypto, MSCryptoSuite suite, unsigned int tag) {
	crypto->tag = tag;
	crypto->algo = suite;
	size_t keylen = 0;
	switch (suite) {
		case MS_AES_128_SHA1_80:
		case MS_AES_128_SHA1_32:
		case MS_AES_128_NO_AUTH:
		case MS_NO_CIPHER_SHA1_80: /* Not sure for this one */
			keylen = 30;
			break;
		case MS_AES_256_SHA1_80:
		case MS_AES_CM_256_SHA1_80:
		case MS_AES_256_SHA1_32:
			keylen = 46;
			break;
		case MS_CRYPTO_SUITE_INVALID:
			break;
	}
	if ((keylen == 0) || !generateB64CryptoKey(keylen, crypto->master_key, SAL_SRTP_KEY_SIZE)) {
		lError() << "Could not generate SRTP key";
		crypto->algo = MS_CRYPTO_SUITE_INVALID;
		return -1;
	}
	return 0;
}

void MediaSessionPrivate::setupRtcpFb (SalMediaDescription *md) {
	for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
		if (!sal_stream_description_active(&md->streams[i]))
			continue;
Ronan's avatar
Ronan committed
1429 1430
		md->streams[i].rtcp_fb.generic_nack_enabled = !!lp_config_get_int(linphone_core_get_config(core), "rtp", "rtcp_fb_generic_nack_enabled", 0);
		md->streams[i].rtcp_fb.tmmbr_enabled = !!lp_config_get_int(linphone_core_get_config(core), "rtp", "rtcp_fb_tmmbr_enabled", 1);
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
		md->streams[i].implicit_rtcp_fb = params->getPrivate()->implicitRtcpFbEnabled();
		for (const bctbx_list_t *it = md->streams[i].payloads; it != nullptr; it = bctbx_list_next(it)) {
			OrtpPayloadType *pt = reinterpret_cast<OrtpPayloadType *>(bctbx_list_get_data(it));
			PayloadTypeAvpfParams avpf_params;
			if (!params->avpfEnabled() && !params->getPrivate()->implicitRtcpFbEnabled()) {
				payload_type_unset_flag(pt, PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED);
				memset(&avpf_params, 0, sizeof(avpf_params));
			} else {
				payload_type_set_flag(pt, PAYLOAD_TYPE_RTCP_FEEDBACK_ENABLED);
				avpf_params = payload_type_get_avpf_params(pt);
				avpf_params.trr_interval = params->getAvpfRrInterval();
			}
			payload_type_set_avpf_params(pt, avpf_params);
		}
	}
}

void MediaSessionPrivate::setupRtcpXr (SalMediaDescription *md) {
Ronan's avatar
Ronan committed
1449
	md->rtcp_xr.enabled = !!lp_config_get_int(linphone_core_get_config(core), "rtp", "rtcp_xr_enabled", 1);
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
	if (md->rtcp_xr.enabled) {
		const char *rcvr_rtt_mode = lp_config_get_string(linphone_core_get_config(core), "rtp", "rtcp_xr_rcvr_rtt_mode", "all");
		if (strcasecmp(rcvr_rtt_mode, "all") == 0)
			md->rtcp_xr.rcvr_rtt_mode = OrtpRtcpXrRcvrRttAll;
		else if (strcasecmp(rcvr_rtt_mode, "sender") == 0)
			md->rtcp_xr.rcvr_rtt_mode = OrtpRtcpXrRcvrRttSender;
		else
			md->rtcp_xr.rcvr_rtt_mode = OrtpRtcpXrRcvrRttNone;
		if (md->rtcp_xr.rcvr_rtt_mode != OrtpRtcpXrRcvrRttNone)
			md->rtcp_xr.rcvr_rtt_max_size = lp_config_get_int(linphone_core_get_config(core), "rtp", "rtcp_xr_rcvr_rtt_max_size", 10000);
Ronan's avatar
Ronan committed
1460
		md->rtcp_xr.stat_summary_enabled = !!lp_config_get_int(linphone_core_get_config(core), "rtp", "rtcp_xr_stat_summary_enabled", 1);
1461 1462
		if (md->rtcp_xr.stat_summary_enabled)
			md->rtcp_xr.stat_summary_flags = OrtpRtcpXrStatSummaryLoss | OrtpRtcpXrStatSummaryDup | OrtpRtcpXrStatSummaryJitt | OrtpRtcpXrStatSummaryTTL;
Ronan's avatar
Ronan committed
1463
		md->rtcp_xr.voip_metrics_enabled = !!lp_config_get_int(linphone_core_get_config(core), "rtp", "rtcp_xr_voip_metrics_enabled", 1);
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
	}
	for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
		if (!sal_stream_description_active(&md->streams[i]))
			continue;
		memcpy(&md->streams[i].rtcp_xr, &md->rtcp_xr, sizeof(md->streams[i].rtcp_xr));
	}
}

void MediaSessionPrivate::setupZrtpHash (SalMediaDescription *md) {
	if (linphone_core_media_encryption_supported(core, LinphoneMediaEncryptionZRTP)) {
		/* Set the hello hash for all streams */
		for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
			if (!sal_stream_description_active(&md->streams[i]))
				continue;
			if (sessions[i].zrtp_context) {
				ms_zrtp_getHelloHash(sessions[i].zrtp_context, md->streams[i].zrtphash, 128);
				/* Turn on the flag to use it if ZRTP is set */
				md->streams[i].haveZrtpHash = (params->getMediaEncryption() == LinphoneMediaEncryptionZRTP);
			} else
				md->streams[i].haveZrtpHash = 0;
		}
	}
}

void MediaSessionPrivate::setupEncryptionKeys (SalMediaDescription *md) {
	SalMediaDescription *oldMd = localDesc;
1490
	bool keepSrtpKeys = !!lp_config_get_int(linphone_core_get_config(core), "sip", "keep_srtp_keys", 1);
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
	for (int i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
		if (!sal_stream_description_active(&md->streams[i]))
			continue;
		if (sal_stream_description_has_srtp(&md->streams[i])) {
			if (keepSrtpKeys && oldMd && sal_stream_description_active(&oldMd->streams[i]) && sal_stream_description_has_srtp(&oldMd->streams[i])) {
				lInfo() << "Keeping same crypto keys";
				for (int j = 0; j < SAL_CRYPTO_ALGO_MAX; j++) {
					memcpy(&md->streams[i].crypto[j], &oldMd->streams[i].crypto[j], sizeof(SalSrtpCryptoAlgo));
				}
			} else {
				const MSCryptoSuite *suites = linphone_core_get_srtp_crypto_suites(core);
				for (int j = 0; (suites != nullptr) && (suites[j] != MS_CRYPTO_SUITE_INVALID) && (j < SAL_CRYPTO_ALGO_MAX); j++) {
Benjamin REIS's avatar
Benjamin REIS committed
1503
					setupEncryptionKey(&md->streams[i].crypto[j], suites[j], static_cast<unsigned int>(j) + 1);
1504 1505 1506