media-session.cpp 201 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 29
#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"
#include "conference/session/media-session.h"
30
#include "core/core.h"
31 32 33 34 35 36 37
#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
#include <mediastreamer2/msequalizer.h>
#include <mediastreamer2/mseventqueue.h>
#include <mediastreamer2/msfileplayer.h>
#include <mediastreamer2/msjpegwriter.h>
Ghislain MARY's avatar
Ghislain MARY committed
43
#include <mediastreamer2/msogl.h>
44 45 46 47 48 49 50
#include <mediastreamer2/msrtt4103.h>
#include <mediastreamer2/msvolume.h>
#include <ortp/b64.h>

#include "private.h"

using namespace std;
51 52 53

LINPHONE_BEGIN_NAMESPACE

54 55 56 57 58 59 60 61 62 63
#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));
}

64 65
// =============================================================================

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

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

71 72 73 74 75 76 77 78
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 () {
79
	L_Q();
80 81 82 83
	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 */
84
	getParams()->getPrivate()->setInternalCallUpdate(false);
85 86
	SalMediaDescription *rmd = op->get_remote_media_description();
	SalMediaDescription *md = op->get_final_media_description();
87 88 89 90
	if (!md && (prevState == LinphoneCallOutgoingEarlyMedia) && resultDesc) {
		lInfo() << "Using early media SDP since none was received with the 200 OK";
		md = resultDesc;
	}
91
	if (md && (sal_media_description_empty(md) || linphone_core_incompatible_security(q->getCore()->getCCore(), md)))
92 93 94 95 96
		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. */
97
			iceAgent->updateFromRemoteMediaDescription(localDesc, rmd, !op->is_offerer());
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
		}
		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 {
116
					if (!getParams()->getPrivate()->getInConference() && listener)
117
						listener->onSetCurrentSession(q->getSharedFromThis());
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 146 147 148 149 150 151 152 153 154 155 156 157 158 159
					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";
160
				abort("Incompatible, check codecs or security settings...");
161 162 163 164 165 166 167 168 169 170 171
				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) << "]";
172
						setState(prevState, "Incompatible media parameters.");
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
						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 () {
198
	L_Q();
199
	const SalErrorInfo *ei = op->get_error_info();
200 201 202 203 204 205 206 207 208 209 210 211
	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;
212 213
					if (getParams()->getMediaEncryption() == LinphoneMediaEncryptionSRTP) {
						if (getParams()->avpfEnabled()) {
214 215
							if (i == 0)
								lInfo() << "Retrying CallSession [" << q << "] with SAVP";
216
							getParams()->enableAvpf(false);
217
							restartInvite();
218
							return true;
219
						} else if (!linphone_core_is_media_encryption_mandatory(q->getCore()->getCCore())) {
220 221
							if (i == 0)
								lInfo() << "Retrying CallSession [" << q << "] with AVP";
222
							getParams()->setMediaEncryption(LinphoneMediaEncryptionNone);
223
							memset(localDesc->streams[i].crypto, 0, sizeof(localDesc->streams[i].crypto));
224
							restartInvite();
225 226
							return true;
						}
227
					} else if (getParams()->avpfEnabled()) {
228 229
						if (i == 0)
							lInfo() << "Retrying CallSession [" << q << "] with AVP";
230
						getParams()->enableAvpf(false);
231
						restartInvite();
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 264 265
						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 () {
266
	L_Q();
267
	MediaSessionParams *newParams = new MediaSessionParams(*getParams());
268
	if (lp_config_get_int(linphone_core_get_config(q->getCore()->getCCore()), "sip", "inactive_video_on_pause", 0))
269 270 271 272 273
		newParams->setVideoDirection(LinphoneMediaDirectionInactive);
	acceptUpdate(newParams, LinphoneCallPausedByRemote, "Call paused by remote");
}

void MediaSessionPrivate::remoteRinging () {
274
	L_Q();
275
	/* Set privacy */
276
	getCurrentParams()->setPrivacy((LinphonePrivacyMask)op->get_privacy());
277
	SalMediaDescription *md = op->get_final_media_description();
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
	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
293
			return;
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
		}

		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 {
309
		linphone_core_stop_dtmf_stream(q->getCore()->getCCore());
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
		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) {
333
	SalMediaDescription *rmd = op->get_remote_media_description();
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	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) {
357
	L_Q();
358
	SalMediaDescription *rmd = op->get_remote_media_description();
359 360 361
	fixCallParams(rmd);
	if (state != LinphoneCallPaused) {
		/* Refresh the local description, but in paused state, we don't change anything. */
362
		if (!rmd && lp_config_get_int(linphone_core_get_config(q->getCore()->getCCore()), "sip", "sdp_200_ack_follow_video_policy", 0)) {
363
			lInfo() << "Applying default policy for offering SDP on CallSession [" << q << "]";
364
			setParams(new MediaSessionParams());
365
			params->initDefault(q->getCore());
366 367
		}
		makeLocalMediaDescription();
368
		op->set_local_media_description(localDesc);
369 370 371 372 373
	}
	if (rmd) {
		SalErrorInfo sei;
		memset(&sei, 0, sizeof(sei));
		expectMediaInAck = false;
374
		SalMediaDescription *md = op->get_final_media_description();
375
		if (md && (sal_media_description_empty(md) || linphone_core_incompatible_security(q->getCore()->getCCore(), md))) {
376
			sal_error_info_set(&sei, SalReasonNotAcceptable, "SIP", 0, nullptr, nullptr);
377
			op->decline_with_error_info(&sei, nullptr);
378 379 380 381 382 383 384 385 386
			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);
387
				op->decline_with_error_info(&sei, nullptr);
388 389 390 391 392 393 394 395
				sal_error_info_reset(&sei);
				return;
			}
		}
		updated(isUpdate);
	} else {
		/* Case of a reINVITE or UPDATE without SDP */
		expectMediaInAck = true;
396
		op->accept(); /* Respond with an offer */
397 398 399 400 401 402 403 404 405 406 407 408 409
		/* 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);
	}
}

Ghislain MARY's avatar
Ghislain MARY committed
410 411 412 413 414 415 416
void MediaSessionPrivate::oglRender () const {
#ifdef VIDEO_ENABLED
	if (videoStream && videoStream->output && (ms_filter_get_id(videoStream->output) == MS_OGL_ID))
		ms_filter_call_method(videoStream->output, MS_OGL_RENDER, nullptr);
#endif
}

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
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;
442 443 444
	_linphone_call_stats_set_ice_state(audioStats, LinphoneIceStateNotActivated);
	_linphone_call_stats_set_ice_state(videoStats, LinphoneIceStateNotActivated);
	_linphone_call_stats_set_ice_state(textStats, LinphoneIceStateNotActivated);
445 446 447 448 449 450 451 452 453 454
	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
455
	if (getParams()->realtimeTextEnabled() && (textStream->ms.state == MSStreamInitialized))
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
		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);
}

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

472 473 474 475 476 477
void MediaSessionPrivate::setCurrentParams (MediaSessionParams *msp) {
	if (currentParams)
		delete currentParams;
	currentParams = msp;
}

478 479 480 481 482 483
void MediaSessionPrivate::setParams (MediaSessionParams *msp) {
	if (params)
		delete params;
	params = msp;
}

484 485 486 487 488 489
void MediaSessionPrivate::setRemoteParams (MediaSessionParams *msp) {
	if (remoteParams)
		delete remoteParams;
	remoteParams = msp;
}

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
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;
}

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

585 586 587 588 589 590 591 592 593
shared_ptr<Participant> MediaSessionPrivate::getMe () const {
	shared_ptr<Participant> participant = me.lock();
	if (!participant) {
		lWarning() << "Unable to get valid Participant instance";
		throw std::bad_weak_ptr();
	}
	return participant;
}

594
void MediaSessionPrivate::setState (LinphoneCallState newState, const string &message) {
595
	L_Q();
596
	/* Take a ref on the session otherwise it might get destroyed during the call to setState */
Ghislain MARY's avatar
Ghislain MARY committed
597
	shared_ptr<CallSession> sessionRef = q->getSharedFromThis();
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 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
	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) {
713
	L_Q();
714 715 716 717 718 719 720 721 722 723 724 725
	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));*/
	}
726
	const MediaSessionParams *rcp = q->getRemoteParams();
727
	if (rcp) {
728
		if (getParams()->audioEnabled() && !rcp->audioEnabled()) {
729
			lInfo() << "CallSession [" << q << "]: disabling audio in our call params because the remote doesn't want it";
730
			getParams()->enableAudio(false);
731
		}
732
		if (getParams()->videoEnabled() && !rcp->videoEnabled()) {
733
			lInfo() << "CallSession [" << q << "]: disabling video in our call params because the remote doesn't want it";
734
			getParams()->enableVideo(false);
735
		}
736
		if (rcp->videoEnabled() && q->getCore()->getCCore()->video_policy.automatically_accept && linphone_core_video_enabled(q->getCore()->getCCore()) && !getParams()->videoEnabled()) {
737
			lInfo() << "CallSession [" << q << "]: re-enabling video in our call params because the remote wants it and the policy allows to automatically accept";
738
			getParams()->enableVideo(true);
739
		}
740 741
		if (rcp->realtimeTextEnabled() && !getParams()->realtimeTextEnabled())
			getParams()->enableRealtimeText(true);
742 743 744 745
	}
}

void MediaSessionPrivate::initializeParamsAccordingToIncomingCallParams () {
746
	L_Q();
747
	CallSessionPrivate::initializeParamsAccordingToIncomingCallParams();
748
	getCurrentParams()->getPrivate()->setUpdateCallWhenIceCompleted(getParams()->getPrivate()->getUpdateCallWhenIceCompleted());
749
	getParams()->enableVideo(linphone_core_video_enabled(q->getCore()->getCCore()) && q->getCore()->getCCore()->video_policy.automatically_accept);
750
	SalMediaDescription *md = op->get_remote_media_description();
751 752 753 754
	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 */
755
		if (!op->is_offerer()) {
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
			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) {
772
	L_Q();
773
	/* Handle AVPF, SRTP and DTLS */
774
	getParams()->enableAvpf(!!sal_media_description_has_avpf(md));
775
	if (destProxy)
776
		getParams()->setAvpfRrInterval(static_cast<uint16_t>(linphone_proxy_config_get_avpf_rr_interval(destProxy) * 1000));
777
	else
778 779
		getParams()->setAvpfRrInterval(static_cast<uint16_t>(linphone_core_get_avpf_rr_interval(q->getCore()->getCCore()) * 1000));
	if (sal_media_description_has_zrtp(md) && linphone_core_media_encryption_supported(q->getCore()->getCCore(), LinphoneMediaEncryptionZRTP))
780
		getParams()->setMediaEncryption(LinphoneMediaEncryptionZRTP);
781
	else if (sal_media_description_has_dtls(md) && media_stream_dtls_supported())
782
		getParams()->setMediaEncryption(LinphoneMediaEncryptionDTLS);
783
	else if (sal_media_description_has_srtp(md) && ms_srtp_supported())
784 785 786
		getParams()->setMediaEncryption(LinphoneMediaEncryptionSRTP);
	else if (getParams()->getMediaEncryption() != LinphoneMediaEncryptionZRTP)
		getParams()->setMediaEncryption(LinphoneMediaEncryptionNone);
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
	/* 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 () {
808
	SalMediaDescription *desc = op->get_remote_media_description();
809 810 811 812 813 814 815 816 817
	if (desc) {
		remoteSessionId = desc->session_id;
		remoteSessionVer = desc->session_ver;
	}
}

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

void MediaSessionPrivate::initStats (LinphoneCallStats *stats, LinphoneStreamType type) {
818 819 820 821
	_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);
822 823 824 825 826 827 828 829 830 831 832 833
}

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;
834 835
	if (_linphone_call_stats_get_updated(stats)) {
		switch (_linphone_call_stats_get_updated(stats)) {
836 837 838 839 840 841 842 843 844 845
			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)
846
			listener->onStatsUpdated(stats);
847
		_linphone_call_stats_set_updated(stats, 0);
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
	}
}

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

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 {
876
	L_Q();
877 878
	bool paused = (state == LinphoneCallPausing) || (state == LinphoneCallPaused);
	if (paused || allMuted || !cameraEnabled)
879
		return get_nowebcam_device(q->getCore()->getCCore()->factory);
880
	else
881
		return q->getCore()->getCCore()->video_conf.device;
882 883 884 885 886
}

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

void MediaSessionPrivate::fillMulticastMediaAddresses () {
887
	L_Q();
888
	if (getParams()->audioMulticastEnabled())
889
		mediaPorts[mainAudioStreamIndex].multicastIp = linphone_core_get_audio_multicast_addr(q->getCore()->getCCore());
890
	if (getParams()->videoMulticastEnabled())
891
		mediaPorts[mainVideoStreamIndex].multicastIp = linphone_core_get_video_multicast_addr(q->getCore()->getCCore());
892 893 894
}

int MediaSessionPrivate::selectFixedPort (int streamIndex, pair<int, int> portRange) {
895
	L_Q();
896 897
	for (int triedPort = portRange.first; triedPort < (portRange.first + 100); triedPort += 2) {
		bool alreadyUsed = false;
898
		for (const bctbx_list_t *elem = linphone_core_get_calls(q->getCore()->getCCore()); elem != nullptr; elem = bctbx_list_next(elem)) {
899
			LinphoneCall *lcall = reinterpret_cast<LinphoneCall *>(bctbx_list_get_data(elem));
900
			shared_ptr<MediaSession> session = static_pointer_cast<MediaSession>(L_GET_CPP_PTR_FROM_C_OBJECT(lcall)->getPrivate()->getActiveSession());
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
			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) {
916
	L_Q();
917 918
	for (int nbTries = 0; nbTries < 100; nbTries++) {
		bool alreadyUsed = false;
919 920
		unsigned int rangeSize = static_cast<unsigned int>(portRange.second - portRange.first);
		unsigned int randomInRangeSize = ortp_random() % rangeSize;
Benjamin REIS's avatar
Benjamin REIS committed
921
		unsigned int mask = 1;
922 923
		unsigned int realRandom = randomInRangeSize + static_cast<unsigned int >(portRange.first);
		int triedPort = static_cast<int>(realRandom & ~mask);
924
		if (triedPort < portRange.first) triedPort = portRange.first + 2;
925
		for (const bctbx_list_t *elem = linphone_core_get_calls(q->getCore()->getCCore()); elem != nullptr; elem = bctbx_list_next(elem)) {
926
			LinphoneCall *lcall = reinterpret_cast<LinphoneCall *>(bctbx_list_get_data(elem));
927
			shared_ptr<MediaSession> session = static_pointer_cast<MediaSession>(L_GET_CPP_PTR_FROM_C_OBJECT(lcall)->getPrivate()->getActiveSession());
928 929 930 931 932 933 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
			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) {
975 976
	L_Q();
	if (q->getCore()->getCCore()->net_conf.mtu == 0) {
977 978 979
		/* Attempt to discover mtu */
		int mtu = ms_discover_mtu(remoteAddr.getDomain().c_str());
		if (mtu > 0) {
980 981
			ms_factory_set_mtu(q->getCore()->getCCore()->factory, mtu);
			lInfo() << "Discovered mtu is " << mtu << ", RTP payload max size is " << ms_factory_get_payload_max_size(q->getCore()->getCCore()->factory);
982 983 984 985 986
		}
	}
}

string MediaSessionPrivate::getBindIpForStream (int streamIndex) {
987 988
	L_Q();
	string bindIp = lp_config_get_string(linphone_core_get_config(q->getCore()->getCCore()), "rtp", "bind_address", (af == AF_INET6) ? "::0" : "0.0.0.0");
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
	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) {
1010
	L_Q();
1011
	/* Next, sometime, override from config */
1012
	const char *ip = lp_config_get_string(linphone_core_get_config(q->getCore()->getCCore()), "rtp", "bind_address", nullptr);
1013 1014 1015 1016 1017 1018 1019 1020
	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) {
1021
		ip = destProxy->op->get_local_address(nullptr);
1022 1023 1024 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
		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];
1050
		linphone_core_get_local_ip(q->getCore()->getCCore(), af, dest, ip);
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
		mediaLocalIp = ip;
	}
}

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

void MediaSessionPrivate::runStunTestsIfNeeded () {
1062
	L_Q();
1063
	if (linphone_nat_policy_stun_enabled(natPolicy) && !(linphone_nat_policy_ice_enabled(natPolicy) || linphone_nat_policy_turn_enabled(natPolicy))) {
1064
		stunClient = new StunClient(q->getCore());
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
		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 () {
1079 1080
	L_Q();
	if (linphone_core_ipv6_enabled(q->getCore()->getCCore())) {
1081
		if (destProxy && destProxy->op)
1082
			af = destProxy->op->get_address_family();
1083
		else
1084
			af = op->get_address_family();
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
	} 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 () {
1098 1099
	L_Q();
	if (!linphone_core_ipv6_enabled(q->getCore()->getCCore())) {
1100 1101 1102 1103
		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
	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;
1122
			else if (lp_config_get_int(linphone_core_get_config(q->getCore()->getCCore()), "rtp", "prefer_ipv6", 1)) /* This property tells whether ipv6 is prefered if two versions are available */
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
				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
	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;
1144
					if ((sd->type == SalVideo) && lp_config_get_int(linphone_core_get_config(q->getCore()->getCCore()), "sip", "inactive_video_on_pause", 0))
1145 1146 1147 1148 1149 1150 1151 1152
						sd->dir = SalStreamInactive;
				}
				break;
			default:
				break;
		}
		/* Reflect the stream directions in the call params */
		if (i == mainAudioStreamIndex)
1153
			getCurrentParams()->setAudioDirection(MediaSessionParamsPrivate::salStreamDirToMediaDirection(sd->dir));
1154
		else if (i == mainVideoStreamIndex)
1155
			getCurrentParams()->setVideoDirection(MediaSessionParamsPrivate::salStreamDirToMediaDirection(sd->dir));
1156 1157 1158 1159 1160
	}
}

bool MediaSessionPrivate::generateB64CryptoKey (size_t keyLength, char *keyOut, size_t keyOutSize) {
	uint8_t *tmp = (uint8_t *)ms_malloc0(keyLength);
1161
	if (!sal_get_random_bytes(tmp, keyLength)) {
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
		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(q->getCore()->getCCore()), "rtp", "rtcp_mux", 0);
1192 1193 1194 1195 1196
	SalMediaDescription *md = sal_media_description_new();
	SalMediaDescription *oldMd = localDesc;

	/* Multicast is only set in case of outgoing call */
	if (direction == LinphoneCallOutgoing) {
1197
		if (getParams()->audioMulticastEnabled()) {
1198
			md->streams[mainAudioStreamIndex].ttl = linphone_core_get_audio_multicast_ttl(q->getCore()->getCCore());
1199 1200
			md->streams[mainAudioStreamIndex].multicast_role = SalMulticastSender;
		}
1201
		if (getParams()->videoMulticastEnabled()) {
1202
			md->streams[mainVideoStreamIndex].ttl = linphone_core_get_video_multicast_ttl(q->getCore()->getCCore());
1203 1204 1205 1206
			md->streams[mainVideoStreamIndex].multicast_role = SalMulticastSender;
		}
	}

1207
	getParams()->getPrivate()->adaptToNetwork(q->getCore()->getCCore(), pingTime);
1208 1209 1210 1211 1212 1213 1214 1215 1216

	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
	strncpy(md->addr, mediaLocalIp.c_str(), sizeof(md->addr));
	LinphoneAddress *addr = nullptr;
	if (destProxy) {
		addr = linphone_address_clone