linphonecall.c 241 KB
Newer Older
1 2 3

/*
linphone
4
Copyright (C) 2010  Belledonne Communications SARL
5 6 7 8 9 10 11 12 13 14 15 16 17 18
 (simon.morlat@linphone.org)

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.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
19
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
*/
21
#ifdef _WIN32
22 23
#include <time.h>
#endif
24 25 26
#include "linphone/core.h"
#include "linphone/sipsetup.h"
#include "linphone/lpconfig.h"
27
#include "private.h"
28
#include "conference_private.h"
29

30
#include <ortp/event.h>
31
#include <ortp/b64.h>
32
#include <math.h>
33

34 35 36
#include "mediastreamer2/mediastream.h"
#include "mediastreamer2/msvolume.h"
#include "mediastreamer2/msequalizer.h"
37
#include "mediastreamer2/msfileplayer.h"
38
#include "mediastreamer2/msjpegwriter.h"
39
#include "mediastreamer2/msogl.h"
40
#include "mediastreamer2/mseventqueue.h"
41
#include "mediastreamer2/mssndcard.h"
42
#include "mediastreamer2/msrtt4103.h"
43

44 45
#include <bctoolbox/defs.h>

46

47 48 49 50 51
inline OrtpRtcpXrStatSummaryFlag operator|(OrtpRtcpXrStatSummaryFlag a, OrtpRtcpXrStatSummaryFlag b) {
	return static_cast<OrtpRtcpXrStatSummaryFlag>(static_cast<int>(a) | static_cast<int>(b));
}


52
static const char *EC_STATE_STORE = ".linphone.ecstate";
53
#define EC_STATE_MAX_LEN 1048576 // 1Mo
54

Simon Morlat's avatar
Simon Morlat committed
55
static void linphone_call_stats_uninit(LinphoneCallStats *stats);
56
static void linphone_call_get_local_ip(LinphoneCall *call, const LinphoneAddress *remote_addr);
57
static void _linphone_call_set_next_video_frame_decoded_trigger(LinphoneCall *call);
58
void linphone_call_handle_stream_events(LinphoneCall *call, int stream_index);
Simon Morlat's avatar
Simon Morlat committed
59

60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
typedef belle_sip_object_t_vptr_t LinphoneCallCbs_vptr_t;
BELLE_SIP_DECLARE_NO_IMPLEMENTED_INTERFACES(LinphoneCallCbs);
BELLE_SIP_INSTANCIATE_VPTR(LinphoneCallCbs, belle_sip_object_t,
	NULL, // destroy
	NULL, // clone
	NULL, // Marshall
	FALSE
);

LinphoneCallCbs *_linphone_call_cbs_new(void) {
	LinphoneCallCbs *obj = belle_sip_object_new(LinphoneCallCbs);
	return obj;
}

LinphoneCallCbs *linphone_call_cbs_ref(LinphoneCallCbs *cbs) {
	return (LinphoneCallCbs *)belle_sip_object_ref(cbs);
}

void linphone_call_cbs_unref(LinphoneCallCbs *cbs) {
	belle_sip_object_unref(cbs);
}

void *linphone_call_cbs_get_user_data(const LinphoneCallCbs *cbs) {
	return cbs->user_data;
}

void linphone_call_cbs_set_user_data(LinphoneCallCbs *cbs, void *user_data) {
	cbs->user_data = user_data;
}

LinphoneCallCbsDtmfReceivedCb linphone_call_cbs_get_dtmf_received(LinphoneCallCbs *cbs) {
	return cbs->dtmf_received_cb;
}

void linphone_call_cbs_set_dtmf_received(LinphoneCallCbs *cbs, LinphoneCallCbsDtmfReceivedCb cb) {
	cbs->dtmf_received_cb = cb;
}

LinphoneCallCbsEncryptionChangedCb linphone_call_cbs_get_encryption_changed(LinphoneCallCbs *cbs) {
	return cbs->encryption_changed_cb;
}

void linphone_call_cbs_set_encryption_changed(LinphoneCallCbs *cbs, LinphoneCallCbsEncryptionChangedCb cb) {
	cbs->encryption_changed_cb = cb;
}

LinphoneCallCbsInfoMessageReceivedCb linphone_call_cbs_get_info_message_received(LinphoneCallCbs *cbs) {
	return cbs->info_message_received_cb;
}

void linphone_call_cbs_set_info_message_received(LinphoneCallCbs *cbs, LinphoneCallCbsInfoMessageReceivedCb cb) {
	cbs->info_message_received_cb = cb;
}

LinphoneCallCbsStateChangedCb linphone_call_cbs_get_state_changed(LinphoneCallCbs *cbs) {
	return cbs->state_changed_cb;
}

void linphone_call_cbs_set_state_changed(LinphoneCallCbs *cbs, LinphoneCallCbsStateChangedCb cb) {
	cbs->state_changed_cb = cb;
}

LinphoneCallCbsStatsUpdatedCb linphone_call_cbs_get_stats_updated(LinphoneCallCbs *cbs) {
	return cbs->stats_updated_cb;
}

void linphone_call_cbs_set_stats_updated(LinphoneCallCbs *cbs, LinphoneCallCbsStatsUpdatedCb cb) {
	cbs->stats_updated_cb = cb;
}

LinphoneCallCbsTransferStateChangedCb linphone_call_cbs_get_transfer_state_changed(LinphoneCallCbs *cbs) {
	return cbs->transfer_state_changed_cb;
}

void linphone_call_cbs_set_transfer_state_changed(LinphoneCallCbs *cbs, LinphoneCallCbsTransferStateChangedCb cb) {
	cbs->transfer_state_changed_cb = cb;
}

139 140 141 142 143 144 145 146
LinphoneCallCbsAckProcessingCb linphone_call_cbs_get_ack_processing(LinphoneCallCbs *cbs){
	return cbs->ack_processing;
}

void linphone_call_cbs_set_ack_processing(LinphoneCallCbs *cbs, LinphoneCallCbsAckProcessingCb cb){
	cbs->ack_processing = cb;
}

147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
bool_t linphone_call_state_is_early(LinphoneCallState state){
	switch (state){
		case LinphoneCallIdle:
		case LinphoneCallOutgoingInit:
		case LinphoneCallOutgoingEarlyMedia:
		case LinphoneCallOutgoingRinging:
		case LinphoneCallOutgoingProgress:
		case LinphoneCallIncomingReceived:
		case LinphoneCallIncomingEarlyMedia:
		case LinphoneCallEarlyUpdatedByRemote:
		case LinphoneCallEarlyUpdating:
			return TRUE;
		case LinphoneCallResuming:
		case LinphoneCallEnd:
		case LinphoneCallUpdating:
		case LinphoneCallRefered:
		case LinphoneCallPausing:
		case LinphoneCallPausedByRemote:
		case LinphoneCallPaused:
		case LinphoneCallConnected:
		case LinphoneCallError:
		case LinphoneCallUpdatedByRemote:
		case LinphoneCallReleased:
		case LinphoneCallStreamsRunning:
		break;
	}
	return FALSE;
}

177
MSWebCam *get_nowebcam_device(MSFactory* f){
178
#ifdef VIDEO_ENABLED
179
	return ms_web_cam_manager_get_cam(ms_factory_get_web_cam_manager(f),"StaticImage: Static picture");
180 181
#else
	return NULL;
182
#endif
183 184
}

185 186
static bool_t generate_b64_crypto_key(size_t key_length, char* key_out, size_t key_out_size) {
	size_t b64_size;
187 188
	uint8_t* tmp = (uint8_t*) ms_malloc0(key_length);
	if (sal_get_random_bytes(tmp, key_length)==NULL) {
189
		ms_error("Failed to generate random key");
190
		ms_free(tmp);
191 192
		return FALSE;
	}
193

194
	b64_size = b64::b64_encode((const char*)tmp, key_length, NULL, 0);
195 196 197 198 199 200 201 202 203 204
	if (b64_size == 0) {
		ms_error("Failed to get b64 result size");
		ms_free(tmp);
		return FALSE;
	}
	if (b64_size>=key_out_size){
		ms_error("Insufficient room for writing base64 SRTP key");
		ms_free(tmp);
		return FALSE;
	}
205
	b64_size = b64::b64_encode((const char*)tmp, key_length, key_out, key_out_size);
206 207
	if (b64_size == 0) {
		ms_error("Failed to b64 encode key");
208
		ms_free(tmp);
209 210 211
		return FALSE;
	}
	key_out[b64_size] = '\0';
212
	ms_free(tmp);
213 214 215
	return TRUE;
}

216 217 218 219 220 221 222 223
static bool_t linphone_call_encryption_mandatory(LinphoneCall *call){
	if (call->params->media_encryption==LinphoneMediaEncryptionDTLS) {
		ms_message("Forced encryption mandatory on call [%p] due to SRTP-DTLS",call);
		return TRUE;
	}
	return call->params->encryption_mandatory;
}

224 225 226 227
LinphoneCore *linphone_call_get_core(const LinphoneCall *call){
	return call->core;
}

228
const char* linphone_call_get_authentication_token(LinphoneCall *call){
229
	return call->auth_token;
230 231 232
}

bool_t linphone_call_get_authentication_token_verified(LinphoneCall *call){
233
	return call->auth_token_verified;
234
}
235

236 237 238 239 240 241
static bool_t at_least_one_stream_started(const LinphoneCall *call){
	return (call->audiostream && media_stream_get_state((MediaStream *)call->audiostream) == MSStreamStarted )
		|| (call->videostream && media_stream_get_state((MediaStream *)call->videostream) == MSStreamStarted)
		|| (call->textstream && media_stream_get_state((MediaStream *)call->textstream) == MSStreamStarted);
}

242
static bool_t linphone_call_all_streams_encrypted(const LinphoneCall *call) {
243 244
	int number_of_encrypted_stream = 0;
	int number_of_active_stream = 0;
245

246 247 248 249 250 251 252 253 254 255 256 257 258 259
	if (call->audiostream && media_stream_get_state((MediaStream *)call->audiostream) == MSStreamStarted) {
		number_of_active_stream++;
		if(media_stream_secured((MediaStream *)call->audiostream))
			number_of_encrypted_stream++;
	}
	if (call->videostream && media_stream_get_state((MediaStream *)call->videostream) == MSStreamStarted) {
		number_of_active_stream++;
		if (media_stream_secured((MediaStream *)call->videostream))
			number_of_encrypted_stream++;
	}
	if (call->textstream && media_stream_get_state((MediaStream *)call->textstream) == MSStreamStarted) {
		number_of_active_stream++;
		if (media_stream_secured((MediaStream *)call->textstream))
			number_of_encrypted_stream++;
260
	}
261
	return number_of_active_stream>0 && number_of_active_stream==number_of_encrypted_stream;
262 263
}

264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
static bool_t linphone_call_all_streams_avpf_enabled(const LinphoneCall *call) {
	int nb_active_streams = 0;
	int nb_avpf_enabled_streams = 0;
	if (call) {
		if (call->audiostream && media_stream_get_state((MediaStream *)call->audiostream) == MSStreamStarted) {
			nb_active_streams++;
			if (media_stream_avpf_enabled((MediaStream *)call->audiostream))
				nb_avpf_enabled_streams++;
		}
		if (call->videostream && media_stream_get_state((MediaStream *)call->videostream) == MSStreamStarted) {
			nb_active_streams++;
			if (media_stream_avpf_enabled((MediaStream *)call->videostream))
				nb_avpf_enabled_streams++;
		}
	}
	return ((nb_active_streams > 0) && (nb_active_streams == nb_avpf_enabled_streams));
}

282 283 284
static uint16_t linphone_call_get_avpf_rr_interval(const LinphoneCall *call) {
	uint16_t rr_interval = 0;
	uint16_t stream_rr_interval;
285 286 287 288 289 290 291 292 293 294
	if (call) {
		if (call->audiostream && media_stream_get_state((MediaStream *)call->audiostream) == MSStreamStarted) {
			stream_rr_interval = media_stream_get_avpf_rr_interval((MediaStream *)call->audiostream);
			if (stream_rr_interval > rr_interval) rr_interval = stream_rr_interval;
		}
		if (call->videostream && media_stream_get_state((MediaStream *)call->videostream) == MSStreamStarted) {
			stream_rr_interval = media_stream_get_avpf_rr_interval((MediaStream *)call->videostream);
			if (stream_rr_interval > rr_interval) rr_interval = stream_rr_interval;
		}
	} else {
295
		rr_interval = 5000;
296 297 298 299
	}
	return rr_interval;
}

300
static void propagate_encryption_changed(LinphoneCall *call){
301
	if (!linphone_call_all_streams_encrypted(call)) {
302
		ms_message("Some streams are not encrypted");
303
		call->current_params->media_encryption=LinphoneMediaEncryptionNone;
304
		linphone_call_notify_encryption_changed(call, FALSE, call->auth_token);
305
	} else {
johan's avatar
johan committed
306 307 308 309 310
		if (call->auth_token) {/* ZRTP only is using auth_token */
			call->current_params->media_encryption=LinphoneMediaEncryptionZRTP;
		} else { /* otherwise it must be DTLS as SDES doesn't go through this function */
			call->current_params->media_encryption=LinphoneMediaEncryptionDTLS;
		}
311
		ms_message("All streams are encrypted key exchanged using %s", call->current_params->media_encryption==LinphoneMediaEncryptionZRTP?"ZRTP":call->current_params->media_encryption==LinphoneMediaEncryptionDTLS?"DTLS":"Unknown mechanism");
312
		linphone_call_notify_encryption_changed(call, TRUE, call->auth_token);
jehan's avatar
jehan committed
313
#ifdef VIDEO_ENABLED
314
		if (linphone_call_encryption_mandatory(call) && call->videostream && media_stream_started((MediaStream *)call->videostream)) {
315 316
			video_stream_send_vfu(call->videostream); /*nothing could have been sent yet so generating key frame*/
		}
jehan's avatar
jehan committed
317
#endif
318 319 320 321
	}
}

static void linphone_call_audiostream_encryption_changed(void *data, bool_t encrypted) {
322
	char status[255]={0};
323
	LinphoneCall *call;
324

325
	call = (LinphoneCall *)data;
326

327
	if (encrypted) {
johan's avatar
johan committed
328 329 330 331
		if (call->params->media_encryption==LinphoneMediaEncryptionZRTP) { /* if encryption is DTLS, no status to be displayed */
			snprintf(status,sizeof(status)-1,_("Authentication token is %s"),call->auth_token);
			linphone_core_notify_display_status(call->core, status);
		}
332 333
	}

334 335 336 337
	propagate_encryption_changed(call);

#ifdef VIDEO_ENABLED
	// Enable video encryption
johan's avatar
johan committed
338
	if (call->params->media_encryption==LinphoneMediaEncryptionZRTP) {
339 340
		const LinphoneCallParams *params=linphone_call_get_current_params(call);
		if (params->has_video) {
johan's avatar
johan committed
341 342
			ms_message("Trying to start ZRTP encryption on video stream");
			video_stream_start_zrtp(call->videostream);
343
		}
344 345 346 347 348 349
	}
#endif
}

static void linphone_call_audiostream_auth_token_ready(void *data, const char* auth_token, bool_t verified) {
	LinphoneCall *call=(LinphoneCall *)data;
350 351
	if (call->auth_token != NULL)
		ms_free(call->auth_token);
352

353 354
	call->auth_token=ms_strdup(auth_token);
	call->auth_token_verified=verified;
355 356 357 358

	ms_message("Authentication token is %s (%s)", auth_token, verified?"verified":"unverified");
}

359
void linphone_call_set_authentication_token_verified(LinphoneCall *call, bool_t verified){
360 361 362
	if (call->audiostream==NULL || !media_stream_started(&call->audiostream->ms)){
		ms_error("linphone_call_set_authentication_token_verified(): No audio stream or not started");
		return;
363
	}
364
	if (call->audiostream->ms.sessions.zrtp_context==NULL){
365
		ms_error("linphone_call_set_authentication_token_verified(): No zrtp context.");
366
		return;
367 368
	}
	if (!call->auth_token_verified && verified){
369
		ms_zrtp_sas_verified(call->audiostream->ms.sessions.zrtp_context);
370
	}else if (call->auth_token_verified && !verified){
371
		ms_zrtp_sas_reset_verified(call->audiostream->ms.sessions.zrtp_context);
372 373 374 375
	}
	call->auth_token_verified=verified;
	propagate_encryption_changed(call);
}
376

377
static int get_max_codec_sample_rate(const bctbx_list_t *codecs){
378
	int max_sample_rate=0;
379
	const bctbx_list_t *it;
380 381
	for(it=codecs;it!=NULL;it=it->next){
		PayloadType *pt=(PayloadType*)it->data;
382
		int sample_rate;
383

384 385 386 387 388 389 390 391
		if( strcasecmp("G722",pt->mime_type) == 0 ){
			/* G722 spec says 8000 but the codec actually requires 16000 */
			sample_rate = 16000;
		}else sample_rate=pt->clock_rate;
		if (sample_rate>max_sample_rate) max_sample_rate=sample_rate;
	}
	return max_sample_rate;
}
392

393 394
static int find_payload_type_number(const bctbx_list_t *assigned, const PayloadType *pt){
	const bctbx_list_t *elem;
395 396 397 398 399 400 401 402 403 404
	const PayloadType *candidate=NULL;
	for(elem=assigned;elem!=NULL;elem=elem->next){
		const PayloadType *it=(const PayloadType*)elem->data;
		if ((strcasecmp(pt->mime_type, payload_type_get_mime(it)) == 0)
			&& (it->clock_rate==pt->clock_rate)
			&& (it->channels==pt->channels || pt->channels<=0)) {
			candidate=it;
			if ((it->recv_fmtp!=NULL && pt->recv_fmtp!=NULL && strcasecmp(it->recv_fmtp, pt->recv_fmtp)==0)
				|| (it->recv_fmtp==NULL && pt->recv_fmtp==NULL)){
				break;/*exact match*/
405
			}
406 407 408 409 410
		}
	}
	return candidate ? payload_type_get_number(candidate) : -1;
}

411 412
bool_t is_payload_type_number_available(const bctbx_list_t *l, int number, const PayloadType *ignore){
	const bctbx_list_t *elem;
413 414 415 416 417 418
	for (elem=l; elem!=NULL; elem=elem->next){
		const PayloadType *pt=(PayloadType*)elem->data;
		if (pt!=ignore && payload_type_get_number(pt)==number) return FALSE;
	}
	return TRUE;
}
419

420 421
static void linphone_core_assign_payload_type_numbers(LinphoneCore *lc, bctbx_list_t *codecs){
	bctbx_list_t *elem;
422
	int dyn_number=lc->codecs_conf.dyn_pt;
423
	PayloadType *red = NULL, *t140 = NULL;
424

425 426 427
	for (elem=codecs; elem!=NULL; elem=elem->next){
		PayloadType *pt=(PayloadType*)elem->data;
		int number=payload_type_get_number(pt);
428

429 430 431 432 433
		/*check if number is duplicated: it could be the case if the remote forced us to use a mapping with a previous offer*/
		if (number!=-1 && !(pt->flags & PAYLOAD_TYPE_FROZEN_NUMBER)){
			if (!is_payload_type_number_available(codecs, number, pt)){
				ms_message("Reassigning payload type %i %s/%i because already offered.", number, pt->mime_type, pt->clock_rate);
				number=-1; /*need to be re-assigned*/
434
			}
435
		}
436

437 438 439 440 441 442 443 444 445 446 447 448
		if (number==-1){
			while(dyn_number<127){
				if (is_payload_type_number_available(codecs, dyn_number, NULL)){
					payload_type_set_number(pt, dyn_number);
					dyn_number++;
					break;
				}
				dyn_number++;
			}
			if (dyn_number==127){
				ms_error("Too many payload types configured ! codec %s/%i is disabled.", pt->mime_type, pt->clock_rate);
				payload_type_set_enable(pt, FALSE);
449
			}
450
		}
451

452
		if (strcmp(pt->mime_type, payload_type_t140_red.mime_type) == 0) {
453 454 455
			red = pt;
		} else if (strcmp(pt->mime_type, payload_type_t140.mime_type) == 0) {
			t140 = pt;
456
		}
457
	}
458

459 460
	if (t140 && red) {
		int t140_payload_type_number = payload_type_get_number(t140);
461
		char *red_fmtp = ms_strdup_printf("%i/%i/%i", t140_payload_type_number, t140_payload_type_number, t140_payload_type_number);
462
		payload_type_set_recv_fmtp(red, red_fmtp);
463
		ms_free(red_fmtp);
464
	}
465 466
}

467 468
static bool_t has_telephone_event_at_rate(const bctbx_list_t *tev, int rate){
	const bctbx_list_t *it;
469 470 471 472 473 474 475
	for(it=tev;it!=NULL;it=it->next){
		const PayloadType *pt=(PayloadType*)it->data;
		if (pt->clock_rate==rate) return TRUE;
	}
	return FALSE;
}

476 477 478
static bctbx_list_t * create_telephone_events(LinphoneCore *lc, const bctbx_list_t *codecs){
	const bctbx_list_t *it;
	bctbx_list_t *ret=NULL;
479 480 481 482 483 484 485 486 487 488 489 490
	for(it=codecs;it!=NULL;it=it->next){
		const PayloadType *pt=(PayloadType*)it->data;
		if (!has_telephone_event_at_rate(ret,pt->clock_rate)){
			PayloadType *tev=payload_type_clone(&payload_type_telephone_event);
			tev->clock_rate=pt->clock_rate;
			/*let it choose the number dynamically as for normal codecs*/
			payload_type_set_number(tev, -1);
			if (ret==NULL){
				/*But for first telephone-event, prefer the number that was configured in the core*/
				if (is_payload_type_number_available(codecs, lc->codecs_conf.telephone_event_pt, NULL)){
					payload_type_set_number(tev, lc->codecs_conf.telephone_event_pt);
				}
491
			}
492
			ret=bctbx_list_append(ret,tev);
493 494 495 496 497
		}
	}
	return ret;
}

498 499
static bctbx_list_t *create_special_payload_types(LinphoneCore *lc, const bctbx_list_t *codecs){
	bctbx_list_t *ret=create_telephone_events(lc, codecs);
500
	if (linphone_core_generic_comfort_noise_enabled(lc)){
501 502
		PayloadType *cn=payload_type_clone(&payload_type_cn);
		payload_type_set_number(cn, 13);
503
		ret=bctbx_list_append(ret, cn);
504 505 506 507
	}
	return ret;
}

508 509 510
typedef struct _CodecConstraints{
	int bandwidth_limit;
	int max_codecs;
511
	bctbx_list_t *previously_used;
512 513
}CodecConstraints;

514 515 516
static bctbx_list_t *make_codec_list(LinphoneCore *lc, CodecConstraints * hints, SalStreamType stype, const bctbx_list_t *codecs){
	bctbx_list_t *l=NULL;
	const bctbx_list_t *it;
517 518 519 520 521
	int nb = 0;

	for(it=codecs;it!=NULL;it=it->next){
		PayloadType *pt=(PayloadType*)it->data;
		int num;
522

Sylvain Berfini's avatar
Sylvain Berfini committed
523
		if (!payload_type_enabled(pt)) {
524
			continue;
Sylvain Berfini's avatar
Sylvain Berfini committed
525
		}
526 527 528 529 530
		if (hints->bandwidth_limit>0 && !linphone_core_is_payload_type_usable_for_bandwidth(lc,pt,hints->bandwidth_limit)){
			ms_message("Codec %s/%i eliminated because of audio bandwidth constraint of %i kbit/s",
					pt->mime_type,pt->clock_rate,hints->bandwidth_limit);
			continue;
		}
531
		if (!_linphone_core_check_payload_type_usability(lc, pt)) {
532 533 534
			continue;
		}
		pt=payload_type_clone(pt);
535

536 537 538 539 540
		/*look for a previously assigned number for this codec*/
		num=find_payload_type_number(hints->previously_used, pt);
		if (num!=-1){
			payload_type_set_number(pt,num);
			payload_type_set_flag(pt, PAYLOAD_TYPE_FROZEN_NUMBER);
541
		}
542

543
		l=bctbx_list_append(l, pt);
544 545
		nb++;
		if ((hints->max_codecs > 0) && (nb >= hints->max_codecs)) break;
546
	}
547
	if (stype==SalAudio){
548 549
		bctbx_list_t *specials=create_special_payload_types(lc,l);
		l=bctbx_list_concat(l,specials);
550
	}
551
	linphone_core_assign_payload_type_numbers(lc, l);
552 553 554
	return l;
}

555
static void update_media_description_from_stun(SalMediaDescription *md, const StunCandidate *ac, const StunCandidate *vc, const StunCandidate *tc){
556
	int i;
557
	for (i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
558
		if (!sal_stream_description_active(&md->streams[i])) continue;
559
		if ((md->streams[i].type == SalAudio) && (ac->port != 0)) {
560 561
			strcpy(md->streams[i].rtp_addr,ac->addr);
			md->streams[i].rtp_port=ac->port;
562
			if ((ac->addr[0]!='\0' && vc->addr[0]!='\0' && strcmp(ac->addr,vc->addr)==0) || sal_media_description_get_nb_active_streams(md)==1){
563 564
				strcpy(md->addr,ac->addr);
			}
565 566 567 568 569 570
		} else if ((md->streams[i].type == SalVideo) && (vc->port != 0)) {
			strcpy(md->streams[i].rtp_addr,vc->addr);
			md->streams[i].rtp_port=vc->port;
		} else if ((md->streams[i].type == SalText) && (tc->port != 0)) {
			strcpy(md->streams[i].rtp_addr,tc->addr);
			md->streams[i].rtp_port=tc->port;
571 572 573 574
		}
	}
}

575
static int setup_encryption_key(SalSrtpCryptoAlgo *crypto, MSCryptoSuite suite, unsigned int tag){
576
	size_t keylen=0;
577 578 579 580 581 582 583 584 585 586
	crypto->tag=tag;
	crypto->algo=suite;
	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:
587
		case MS_AES_CM_256_SHA1_80:
588 589 590 591 592 593
		case MS_AES_256_SHA1_32:
			keylen=46;
		break;
		case MS_CRYPTO_SUITE_INVALID:
		break;
	}
594
	if (keylen==0 || !generate_b64_crypto_key(keylen, crypto->master_key, SAL_SRTP_KEY_SIZE)){
595
		ms_error("Could not generate SRTP key.");
596
		crypto->algo = MS_CRYPTO_SUITE_INVALID;
597 598 599 600
		return -1;
	}
	return 0;
}
601 602
static void setup_dtls_keys(LinphoneCall *call, SalMediaDescription *md){
	int i;
603
	for(i=0; i<SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
604 605 606 607 608 609 610 611
		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]) == TRUE) {
			strncpy(md->streams[i].dtls_fingerprint, call->dtls_certificate_fingerprint, sizeof(md->streams[i].dtls_fingerprint)); /* get the self fingerprint from call(it's computed at stream init) */
			md->streams[i].dtls_role = SalDtlsRoleUnset; /* 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 */
		} else {
			md->streams[i].dtls_fingerprint[0] = '\0';
			md->streams[i].dtls_role = SalDtlsRoleInvalid;
612

613 614 615 616
		}
	}

}
617 618
static void setup_encryption_keys(LinphoneCall *call, SalMediaDescription *md){
	LinphoneCore *lc=call->core;
619
	int i,j;
620
	SalMediaDescription *old_md=call->localdesc;
621
	bool_t keep_srtp_keys=lp_config_get_int(lc->config,"sip","keep_srtp_keys",1);
622

623
	for(i=0; i<SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
624 625
		if (!sal_stream_description_active(&md->streams[i])) continue;
		if (sal_stream_description_has_srtp(&md->streams[i]) == TRUE) {
626
			if (keep_srtp_keys && old_md && (sal_stream_description_active(&old_md->streams[i]) == TRUE) && (sal_stream_description_has_srtp(&old_md->streams[i]) == TRUE)) {
627 628 629 630 631 632
				int j;
				ms_message("Keeping same crypto keys.");
				for(j=0;j<SAL_CRYPTO_ALGO_MAX;++j){
					memcpy(&md->streams[i].crypto[j],&old_md->streams[i].crypto[j],sizeof(SalSrtpCryptoAlgo));
				}
			}else{
633 634 635 636
				const MSCryptoSuite *suites=linphone_core_get_srtp_crypto_suites(lc);
				for(j=0;suites!=NULL && suites[j]!=MS_CRYPTO_SUITE_INVALID && j<SAL_CRYPTO_ALGO_MAX;++j){
					setup_encryption_key(&md->streams[i].crypto[j],suites[j],j+1);
				}
637 638 639 640 641
			}
		}
	}
}

johan's avatar
johan committed
642 643 644

static void setup_zrtp_hash(LinphoneCall *call, SalMediaDescription *md) {
	int i;
645
	if (linphone_core_media_encryption_supported(call->core, LinphoneMediaEncryptionZRTP)) { /* set the hello hash for all streams */
johan's avatar
johan committed
646 647 648 649
		for(i=0; i<SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
			if (!sal_stream_description_active(&md->streams[i])) continue;
			if (call->sessions[i].zrtp_context!=NULL) {
				ms_zrtp_getHelloHash(call->sessions[i].zrtp_context, md->streams[i].zrtphash, 128);
johan's avatar
johan committed
650 651 652 653 654
				if (call->params->media_encryption==LinphoneMediaEncryptionZRTP) { /* turn on the flag to use it if ZRTP is set */
					md->streams[i].haveZrtpHash = 1;
				} else {
					md->streams[i].haveZrtpHash = 0;
				}
johan's avatar
johan committed
655 656 657 658 659 660 661
			} else {
				md->streams[i].haveZrtpHash = 0;
			}
		}
	}
}

662
static void setup_rtcp_fb(LinphoneCall *call, SalMediaDescription *md) {
663
	bctbx_list_t *pt_it;
664 665
	PayloadType *pt;
	PayloadTypeAvpfParams avpf_params;
666
	LinphoneCore *lc = call->core;
667 668
	int i;

669
	for (i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
670
		if (!sal_stream_description_active(&md->streams[i])) continue;
671
		md->streams[i].rtcp_fb.generic_nack_enabled = lp_config_get_int(lc->config, "rtp", "rtcp_fb_generic_nack_enabled", 0);
672
		md->streams[i].rtcp_fb.tmmbr_enabled = lp_config_get_int(lc->config, "rtp", "rtcp_fb_tmmbr_enabled", 1);
673
		md->streams[i].implicit_rtcp_fb = call->params->implicit_rtcp_fb;
674

675
		for (pt_it = md->streams[i].payloads; pt_it != NULL; pt_it = pt_it->next) {
676
			pt = (PayloadType *)pt_it->data;
677 678 679 680 681 682 683 684 685

			if (call->params->avpf_enabled == FALSE && call->params->implicit_rtcp_fb == FALSE)  {
				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 = call->params->avpf_rr_interval;
			}
686 687 688 689 690
			payload_type_set_avpf_params(pt, avpf_params);
		}
	}
}

691 692
static void setup_rtcp_xr(LinphoneCall *call, SalMediaDescription *md) {
	LinphoneCore *lc = call->core;
693
	int i;
694

695
	md->rtcp_xr.enabled = lp_config_get_int(lc->config, "rtp", "rtcp_xr_enabled", 1);
696
	if (md->rtcp_xr.enabled == TRUE) {
697
		const char *rcvr_rtt_mode = lp_config_get_string(lc->config, "rtp", "rtcp_xr_rcvr_rtt_mode", "all");
698 699 700 701
		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) {
702
			md->rtcp_xr.rcvr_rtt_max_size = lp_config_get_int(lc->config, "rtp", "rtcp_xr_rcvr_rtt_max_size", 10000);
703
		}
704
		md->rtcp_xr.stat_summary_enabled = lp_config_get_int(lc->config, "rtp", "rtcp_xr_stat_summary_enabled", 1);
705
		if (md->rtcp_xr.stat_summary_enabled == TRUE) {
706
			md->rtcp_xr.stat_summary_flags = OrtpRtcpXrStatSummaryLoss | OrtpRtcpXrStatSummaryDup | OrtpRtcpXrStatSummaryJitt | OrtpRtcpXrStatSummaryTTL;
707
		}
708
		md->rtcp_xr.voip_metrics_enabled = lp_config_get_int(lc->config, "rtp", "rtcp_xr_voip_metrics_enabled", 1);
709
	}
710
	for (i = 0; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
711
		if (!sal_stream_description_active(&md->streams[i])) continue;
712 713
		memcpy(&md->streams[i].rtcp_xr, &md->rtcp_xr, sizeof(md->streams[i].rtcp_xr));
	}
714 715
}

716 717 718 719 720
void linphone_call_increment_local_media_description(LinphoneCall *call){
	SalMediaDescription *md=call->localdesc;
	md->session_ver++;
}

721
void linphone_call_update_local_media_description_from_ice_or_upnp(LinphoneCall *call){
722
	LinphoneCore *lc = call->core;
723
	if (call->ice_session != NULL) {
724
		/*set this to FALSE once flexisip are updated everywhere, let's say in December 2016.*/
725 726
		bool_t use_nortpproxy = lp_config_get_int(lc->config, "sip", "ice_uses_nortpproxy", TRUE);
		_update_local_media_description_from_ice(call->localdesc, call->ice_session, use_nortpproxy);
727
		linphone_call_update_ice_state_in_call_stats(call);
728 729 730
	}
#ifdef BUILD_UPNP
	if(call->upnp_session != NULL) {
731 732
		linphone_call_update_local_media_description_from_upnp(call->localdesc, call->upnp_session);
		linphone_call_update_upnp_state_in_call_stats(call);
733 734 735 736
	}
#endif  //BUILD_UPNP
}

737 738
static void transfer_already_assigned_payload_types(SalMediaDescription *old, SalMediaDescription *md){
	int i;
739
	for(i=0;i<SAL_MEDIA_DESCRIPTION_MAX_STREAMS;++i){
740 741 742 743 744
		md->streams[i].already_assigned_payloads=old->streams[i].already_assigned_payloads;
		old->streams[i].already_assigned_payloads=NULL;
	}
}

745
static const char *linphone_call_get_bind_ip_for_stream(LinphoneCall *call, int stream_index){
746
	const char *bind_ip = lp_config_get_string(call->core->config,"rtp","bind_address",
747
				call->af == AF_INET6 ? "::0" : "0.0.0.0");
748
	PortConfig *pc = &call->media_ports[stream_index];
749
	if (pc->multicast_ip[0]!='\0'){
750
		if (call->dir==LinphoneCallOutgoing){
751
			/*as multicast sender, we must decide a local interface to use to send multicast, and bind to it*/
752 753 754
			linphone_core_get_local_ip_for(strchr(pc->multicast_ip,':') ? AF_INET6 : AF_INET,
				NULL, pc->multicast_bind_ip);
			bind_ip = pc->multicast_bind_ip;
755 756 757 758
		}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).*/
			bind_ip = strchr(pc->multicast_ip,':') ? "::0" : "0.0.0.0";
759 760
		}
	}
761 762 763
	return bind_ip;
}

764
static const char *linphone_call_get_public_ip_for_stream(LinphoneCall *call, int stream_index){
765
	const char *public_ip=call->media_localip;
766

767
	if (call->media_ports[stream_index].multicast_ip[0]!='\0')
768 769 770 771
		public_ip=call->media_ports[stream_index].multicast_ip;
	return public_ip;
}

772 773 774 775 776 777 778 779 780 781 782 783
void linphone_call_update_biggest_desc(LinphoneCall *call, SalMediaDescription *md){
	if (call->biggestdesc==NULL || md->nb_streams>call->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 (call->biggestdesc){
			sal_media_description_unref(call->biggestdesc);
			call->biggestdesc=NULL;
		}
		call->biggestdesc=sal_media_description_ref(md);
	}
}

784 785
static void force_streams_dir_according_to_state(LinphoneCall *call, SalMediaDescription *md){
	int i;
786

787
	for (i=0; i<SAL_MEDIA_DESCRIPTION_MAX_STREAMS; ++i){
788
		SalStreamDescription *sd = &md->streams[i];
789 790 791 792 793 794 795 796 797 798 799

		switch (call->state){
			case LinphoneCallPausing:
			case LinphoneCallPaused:
				if (sd->dir != SalStreamInactive) {
					sd->dir = SalStreamSendOnly;
					if (sd->type == SalVideo){
						if (lp_config_get_int(call->core->config, "sip", "inactive_video_on_pause", 0)) {
							sd->dir = SalStreamInactive;
						}
					}
800
				}
801 802 803 804 805 806 807 808 809 810
				break;
			default:
				break;
		}

		/* Reflect the stream directions in the call params */
		if (i == call->main_audio_stream_index) {
			linphone_call_params_set_audio_direction(call->current_params, media_direction_from_sal_stream_dir(sd->dir));
		} else if (i == call->main_video_stream_index) {
			linphone_call_params_set_video_direction(call->current_params, media_direction_from_sal_stream_dir(sd->dir));
811 812
		}
	}
813 814
}

815
void linphone_call_make_local_media_description(LinphoneCall *call) {
816
	bctbx_list_t *l;
Simon Morlat's avatar
Simon Morlat committed
817
	SalMediaDescription *old_md=call->localdesc;
818
	int i;
819
	int max_index = 0;
820
	SalMediaDescription *md=sal_media_description_new();
821
	LinphoneAddress *addr;
822 823
	const char *subject;
	CodecConstraints codec_hints={0};
824 825
	LinphoneCallParams *params = call->params;
	LinphoneCore *lc = call->core;
826
	bool_t rtcp_mux = lp_config_get_int(lc->config, "rtp", "rtcp_mux", 0);
827

jehan's avatar
jehan committed
828
	/*multicast is only set in case of outgoing call*/
829
	if (call->dir == LinphoneCallOutgoing && linphone_call_params_audio_multicast_enabled(params)) {
830 831
		md->streams[call->main_audio_stream_index].ttl=linphone_core_get_audio_multicast_ttl(lc);
		md->streams[call->main_audio_stream_index].multicast_role = SalMulticastSender;
832
	}
jehan's avatar
jehan committed
833

834
	if (call->dir == LinphoneCallOutgoing && linphone_call_params_video_multicast_enabled(params)) {
835 836
		md->streams[call->main_video_stream_index].ttl=linphone_core_get_video_multicast_ttl(lc);
		md->streams[call->main_video_stream_index].multicast_role = SalMulticastSender;
837
	}
jehan's avatar
jehan committed
838

839
	subject=linphone_call_params_get_session_name(params);
840

841
	linphone_core_adapt_to_network(lc,call->ping_time,params);
842

843 844 845 846 847
	if (call->dest_proxy) {
		addr=linphone_address_clone(linphone_proxy_config_get_identity_address(call->dest_proxy));
	} else {
		addr=linphone_address_new(linphone_core_get_identity(lc));
	}
848

Simon Morlat's avatar
Simon Morlat committed
849 850
	md->session_id=(old_md ? old_md->session_id : (rand() & 0xfff));
	md->session_ver=(old_md ? (old_md->session_ver+1) : (rand() & 0xfff));
851
	md->nb_streams=(call->biggestdesc ? call->biggestdesc->nb_streams : 1);
852

853 854
	/*re-check local ip address each time we make a new offer, because it may change in case of network reconnection*/
	linphone_call_get_local_ip(call, call->dir == LinphoneCallOutgoing ?  call->log->to : call->log->from);
855
	strncpy(md->addr,call->media_localip,sizeof(md->addr));
856 857
	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));
Simon Morlat's avatar
Simon Morlat committed
858
	if (subject) strncpy(md->name,subject,sizeof(md->name));
859

860 861
	if (params->down_bw)
		md->bandwidth=params->down_bw;
862
	else md->bandwidth=linphone_core_get_download_bandwidth(lc);
863

864 865 866
	if (params->custom_sdp_attributes)
		md->custom_sdp_attributes = sal_custom_sdp_attribute_clone(params->custom_sdp_attributes);

867
	/*set audio capabilities */
868

869 870 871 872
	codec_hints.bandwidth_limit=params->audio_bw;
	codec_hints.max_codecs=-1;
	codec_hints.previously_used=old_md ? old_md->streams[call->main_audio_stream_index].already_assigned_payloads : NULL;
	l=make_codec_list(lc, &codec_hints, SalAudio, lc->codecs_conf.audio_codecs);
873

874
	if (params->has_audio && l != NULL) {
875 876 877 878 879 880 881 882
		strncpy(md->streams[call->main_audio_stream_index].rtp_addr,linphone_call_get_public_ip_for_stream(call,call->main_audio_stream_index),sizeof(md->streams[call->main_audio_stream_index].rtp_addr));
		strncpy(md->streams[call->main_audio_stream_index].rtcp_addr,linphone_call_get_public_ip_for_stream(call,call->main_audio_stream_index),sizeof(md->streams[call->main_audio_stream_index].rtcp_addr));
		strncpy(md->streams[call->main_audio_stream_index].name,"Audio",sizeof(md->streams[call->main_audio_stream_index].name)-1);
		md->streams[call->main_audio_stream_index].rtp_port=call->media_ports[call->main_audio_stream_index].rtp_port;
		md->streams[call->main_audio_stream_index].rtcp_port=call->media_ports[call->main_audio_stream_index].rtcp_port;
		md->streams[call->main_audio_stream_index].proto=get_proto_from_call_params(params);
		md->streams[call->main_audio_stream_index].dir=get_audio_dir_from_call_params(params);
		md->streams[call->main_audio_stream_index].type=SalAudio;
883
		md->streams[call->main_audio_stream_index].rtcp_mux = rtcp_mux;
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
		if (params->down_ptime)
			md->streams[call->main_audio_stream_index].ptime=params->down_ptime;
		else
			md->streams[call->main_audio_stream_index].ptime=linphone_core_get_download_ptime(lc);
		md->streams[call->main_audio_stream_index].max_rate=get_max_codec_sample_rate(l);
		md->streams[call->main_audio_stream_index].payloads=l;
		if (call->audiostream && call->audiostream->ms.sessions.rtp_session) {
			char* me = linphone_address_as_string_uri_only(call->me);
			md->streams[call->main_audio_stream_index].rtp_ssrc=rtp_session_get_send_ssrc(call->audiostream->ms.sessions.rtp_session);
			strncpy(md->streams[call->main_audio_stream_index].rtcp_cname,me,sizeof(md->streams[call->main_audio_stream_index].rtcp_cname));
			ms_free(me);
		}
		else
			ms_warning("Cannot get audio local ssrc for call [%p]",call);
		if (call->main_audio_stream_index > max_index)
			max_index = call->main_audio_stream_index;
900 901 902
	} else {
		ms_message("Don't put audio stream on local offer for call [%p]",call);
		md->streams[call->main_audio_stream_index].dir = SalStreamInactive;
903
		if(l) l=bctbx_list_free_with_data(l, (void (*)(void *))payload_type_destroy);
904
	}
905 906
	if (params->custom_sdp_media_attributes[LinphoneStreamTypeAudio])
		md->streams[call->main_audio_stream_index].custom_sdp_attributes = sal_custom_sdp_attribute_clone(params->custom_sdp_media_attributes[LinphoneStreamTypeAudio]);
907

908 909 910
	md->streams[call->main_video_stream_index].proto=md->streams[call->main_audio_stream_index].proto;
	md->streams[call->main_video_stream_index].dir=get_video_dir_from_call_params(params);
	md->streams[call->main_video_stream_index].type=SalVideo;
911
	md->streams[call->main_video_stream_index].rtcp_mux = rtcp_mux;
912
	strncpy(md->streams[call->main_video_stream_index].name,"Video",sizeof(md->streams[call->main_video_stream_index].name)-1);
913

914 915 916 917
	codec_hints.bandwidth_limit=0;
	codec_hints.max_codecs=-1;
	codec_hints.previously_used=old_md ? old_md->streams[call->main_video_stream_index].already_assigned_payloads : NULL;
	l=make_codec_list(lc, &codec_hints, SalVideo, lc->codecs_conf.video_codecs);
918

919
	if (params->has_video && l != NULL){
920 921 922 923
		strncpy(md->streams[call->main_video_stream_index].rtp_addr,linphone_call_get_public_ip_for_stream(call,call->main_video_stream_index),sizeof(md->streams[call->main_video_stream_index].rtp_addr));
		strncpy(md->streams[call->main_video_stream_index].rtcp_addr,linphone_call_get_public_ip_for_stream(call,call->main_video_stream_index),sizeof(md->streams[call->main_video_stream_index].rtcp_addr));
		md->streams[call->main_video_stream_index].rtp_port=call->media_ports[call->main_video_stream_index].rtp_port;
		md->streams[call->main_video_stream_index].rtcp_port=call->media_ports[call->main_video_stream_index].rtcp_port;
924
		md->streams[call->main_video_stream_index].payloads=l;
925 926
		if (call->videostream && call->videostream->ms.sessions.rtp_session) {
			char* me = linphone_address_as_string_uri_only(call->me);
927 928
			md->streams[call->main_video_stream_index].rtp_ssrc=rtp_session_get_send_ssrc(call->videostream->ms.sessions.rtp_session);
			strncpy(md->streams[call->main_video_stream_index].rtcp_cname,me,sizeof(md->streams[call->main_video_stream_index].rtcp_cname));
929 930 931 932
			ms_free(me);
		}
		else
			ms_warning("Cannot get video local ssrc for call [%p]",call);
933 934
		if (call->main_video_stream_index > max_index)
			max_index = call->main_video_stream_index;
935 936
	} else {
		ms_message("Don't put video stream on local offer for call [%p]",call);
937
		md->streams[call->main_video_stream_index].dir = SalStreamInactive;
938
		if(l) l=bctbx_list_free_with_data(l, (void (*)(void *))payload_type_destroy);
939
	}
940 941 942
	if (params->custom_sdp_media_attributes[LinphoneStreamTypeVideo])
		md->streams[call->main_video_stream_index].custom_sdp_attributes = sal_custom_sdp_attribute_clone(params->custom_sdp_media_attributes[LinphoneStreamTypeVideo]);

943
	md->streams[call->main_text_stream_index].proto=md->streams[call->main_audio_stream_index].proto;
944 945
	md->streams[call->main_text_stream_index].dir=SalStreamSendRecv;
	md->streams[call->main_text_stream_index].type=SalText;
946
	md->streams[call->main_text_stream_index].rtcp_mux = rtcp_mux;
947
	strncpy(md->streams[call->main_text_stream_index].name,"Text",sizeof(md->streams[call->main_text_stream_index].name)-1);
948 949 950
	if (params->realtimetext_enabled) {
		strncpy(md->streams[call->main_text_stream_index].rtp_addr,linphone_call_get_public_ip_for_stream(call,call->main_text_stream_index),sizeof(md->streams[call->main_text_stream_index].rtp_addr));
		strncpy(md->streams[call->main_text_stream_index].rtcp_addr,linphone_call_get_public_ip_for_stream(call,call->main_text_stream_index),sizeof(md->streams[call->main_text_stream_index].rtcp_addr));
951

952 953
		md->streams[call->main_text_stream_index].rtp_port=call->media_ports[call->main_text_stream_index].rtp_port;
		md->streams[call->main_text_stream_index].rtcp_port=call->media_ports[call->main_text_stream_index].rtcp_port;
954

955 956 957 958 959 960 961 962 963 964 965 966 967
		codec_hints.bandwidth_limit=0;
		codec_hints.max_codecs=-1;
		codec_hints.previously_used=old_md ? old_md->streams[call->main_text_stream_index].already_assigned_payloads : NULL;
		l=make_codec_list(lc, &codec_hints, SalText, lc->codecs_conf.text_codecs);
		md->streams[call->main_text_stream_index].payloads=l;
		if (call->textstream && call->textstream->ms.sessions.rtp_session) {
			char* me = linphone_address_as_string_uri_only(call->me);
			md->streams[call->main_text_stream_index].rtp_ssrc=rtp_session_get_send_ssrc(call->textstream->ms.sessions.rtp_session);
			strncpy(md->streams[call->main_text_stream_index].rtcp_cname,me,sizeof(md->streams[call->main_text_stream_index].rtcp_cname));
			ms_free(me);
		}
		else
			ms_warning("Cannot get text local ssrc for call [%p]",call);
968 969
		if (call->main_text_stream_index > max_index)
			max_index = call->main_text_stream_index;
970 971
	} else {
		ms_message("Don't put text stream on local offer for call [%p]",call);
972
		md->streams[call->main_text_stream_index].dir = SalStreamInactive;
973
	}
974 975
	if (params->custom_sdp_media_attributes[LinphoneStreamTypeText])
		md->streams[call->main_text_stream_index].custom_sdp_attributes = sal_custom_sdp_attribute_clone(params->custom_sdp_media_attributes[LinphoneStreamTypeText]);
976

977
	md->nb_streams = MAX(md->nb_streams,max_index+1);
978

979 980
	/* Deactivate unused streams. */
	for (i = md->nb_streams; i < SAL_MEDIA_DESCRIPTION_MAX_STREAMS; i++) {
981 982
		if (md->streams[i].rtp_port == 0) {
			md->streams[i].dir = SalStreamInactive;
983 984 985 986 987
			if (call->biggestdesc && i < call->biggestdesc->nb_streams) {
				md->streams[i].proto = call->biggestdesc->streams[i].proto;
				md->streams[i].type = call->biggestdesc->streams[i].type;
			}
		}
988
	}
989
	setup_encryption_keys(call,md);
990
	setup_dtls_keys(call,md);
johan's avatar
johan committed
991
	setup_zrtp_hash(call, md);
992

993
	setup_rtcp_fb(call, md);
994
	setup_rtcp_xr(call, md);
995

996
	update_media_description_from_stun(md, &call->ac, &call->vc, &call->tc);
Simon Morlat's avatar
Simon Morlat committed
997
	call->localdesc=md;
998
	linphone_call_update_local_media_description_from_ice_or_upnp(call);
Simon Morlat's avatar
Simon Morlat committed
999
	linphone_address_unref(addr);
1000
	if (old_md){
1001
		transfer_already_assigned_payload_types(old_md,md);
1002 1003
		call->localdesc_changed=sal_media_description_equals(md,old_md);
		sal_media_description_unref(old_md);
1004 1005 1006 1007 1008 1009 1010 1011
		if (call->params->internal_call_update){
			/*
			 * 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 internal_call_update flag to prevent trigger an unnecessary media restart.
			 */
			call->localdesc_changed = 0;
		}
1012
	}
1013
	force_streams_dir_according_to_state(call, md);
1014 1015
}

1016
static int find_port_offset(LinphoneCore *lc, int stream_index, int base_port){
1017
	int offset;
1018
	bctbx_list_t *elem;
1019 1020
	int tried_port;
	int existing_port;
1021
	bool_t already_used=FALSE;
1022

1023
	for(offset=0;offset<100;offset+=2){
1024
		tried_port=base_port+offset;
1025 1026 1027
		already_used=FALSE;
		for(elem=lc->calls;elem!=NULL;elem=elem->next){
			LinphoneCall *call=(LinphoneCall*)elem->data;
1028
			existing_port=call->media_ports[stream_index].rtp_port;
1029
			if (existing_port==tried_port) {
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
				already_used=TRUE;
				break;
			}
		}
		if (!already_used) break;
	}
	if (offset==100){
		ms_error("Could not find any free port !");
		return -1;
	}
	return offset;
}

1043
static int select_random_port(LinphoneCore *lc, int stream_index, int min_port, int max_port) {
1044
	bctbx_list_t *elem;
1045 1046 1047 1048 1049
	int nb_tries;
	int tried_port = 0;
	int existing_port = 0;
	bool_t already_used = FALSE;

1050
	tried_port = (ortp_random() % (max_port - min_port) + min_port) & ~0x1;
1051 1052 1053 1054
	if (tried_port < min_port) tried_port = min_port + 2;
	for (nb_tries = 0; nb_tries < 100; nb_tries++) {
		for (elem = lc->calls; elem != NULL; elem = elem->next) {
			LinphoneCall *call = (LinphoneCall *)elem->data;
1055
			existing_port=call->media_ports[stream_index].rtp_port;
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
			if (existing_port == tried_port) {
				already_used = TRUE;
				break;
			}
		}
		if (!already_used) break;
	}
	if (nb_tries == 100) {
		ms_error("Could not find any free port!");
		return -1;
	}
	return tried_port;
}

1070 1071 1072 1073 1074 1075
static void port_config_set_random(LinphoneCall *call, int stream_index){
	call->media_ports[stream_index].rtp_port=-1;
	call->media_ports[stream_index].rtcp_port=-1;
}

static void port_config_set(LinphoneCall *call, int stream_index, int min_port, int max_port){
1076
	int port_offset;
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	if (min_port>0 && max_port>0){
		if (min_port == max_port) {
			/* Used fixed RTP audio port. */
			port_offset=find_port_offset(call->core, stream_index, min_port);
			if (port_offset==-1) {
				port_config_set_random(call, stream_index);
				return;
			}
			call->media_ports[stream_index].rtp_port=min_port+port_offset;
		} else {
			/* Select random RTP audio port in the specified range. */
			call->media_ports[stream_index].rtp_port = select_random_port(call->core, stream_index, min_port, max_port);
		}
		call->media_ports[stream_index].rtcp_port=call->media_ports[stream_index].rtp_port+1;
	}else port_config_set_random(call,stream_index);
}

static void linphone_call_init_common(LinphoneCall *call, LinphoneAddress *from, LinphoneAddress *to){
1095
	int min_port, max_port;
1096
	ms_message("New LinphoneCall [%p] initialized (LinphoneCore version: %s)",call,linphone_core_get_version());
1097
	call->ei = linphone_error_info_new();
1098
	call->core->send_call_stats_periodical_updates = lp_config_get_int(call->core->config, "misc", "send_call_stats_periodical_updates", 0);
1099 1100 1101
	call->main_audio_stream_index = LINPHONE_CALL_STATS_AUDIO;
	call->main_video_stream_index = LINPHONE_CALL_STATS_VIDEO;
	call->main_text_stream_index = LINPHONE_CALL_STATS_TEXT;
1102
	call->state=LinphoneCallIdle;
1103
	call->transfer_state = LinphoneCallIdle;
1104
	call->log=linphone_call_log_new(call->dir, from, to);
1105
	call->camera_enabled=TRUE;
1106 1107
	call->current_params = linphone_call_params_new();
	call->current_params->media_encryption=LinphoneMediaEncryptionNone;
johan's avatar
johan committed
1108
	call->dtls_certificate_fingerprint = NULL;
jehan's avatar
jehan committed
1109 1110 1111 1112 1113
	if (call->dir == LinphoneCallIncoming)
		call->me=to;
	 else
		call->me=from;
	linphone_address_ref(call->me);
1114

1115
	linphone_core_get_audio_port_range(call->core, &min_port, &max_port);
1116
	port_config_set(call,call->main_audio_stream_index,min_port,max_port);
1117

1118
	linphone_core_get_video_port_range(call->core, &min_port, &max_port);
1119 1120
	port_config_set(call,call->main_video_stream_index,min_port,max_port);

1121 1122
	linphone_core_get_text_port_range(call->core, &min_port, &max_port);
	port_config_set(call,call->main_text_stream_index,min_port,max_port);
1123

1124 1125 1126
	linphone_call_init_stats(call->audio_stats, LinphoneStreamTypeAudio);
	linphone_call_init_stats(call->video_stats, LinphoneStreamTypeVideo);
	linphone_call_init_stats(call->text_stats, LinphoneStreamTypeText);
1127

1128 1129 1130 1131
	if (call->dest_proxy == NULL) {
		/* Try to define the destination proxy if it has not already been done to have a correct contact field in the SIP messages */
		call->dest_proxy = linphone_core_lookup_known_proxy(call->core, call->log->to);
	}
1132 1133


1134 1135 1136 1137
	if (call->dest_proxy != NULL)
		call->nat_policy = linphone_proxy_config_get_nat_policy(call->dest_proxy);
	if (call->nat_policy == NULL)
		call->nat_policy = linphone_core_get_nat_policy(call->core);
1138

1139 1140
	linphone_nat_policy_ref(call->nat_policy);

1141
}
1142

1143
void linphone_call_init_stats(LinphoneCallStats *stats, LinphoneStreamType type) {
Yann Diorcet's avatar
Yann Diorcet committed
1144
	stats->type = type;
1145 1146
	stats->received_rtcp = NULL;
	stats->sent_rtcp = NULL;
1147
	stats->ice_state = LinphoneIceStateNotActivated;
Yann Diorcet's avatar
Yann Diorcet committed
1148 1149 1150 1151 1152
#ifdef BUILD_UPNP
	stats->upnp_state = LinphoneUpnpStateIdle;
#else
	stats->upnp_state = LinphoneUpnpStateNotAvailable;
#endif //BUILD_UPNP
1153 1154 1155 1156 1157 1158 1159 1160
}

static void discover_mtu(LinphoneCore *lc, const char *remote){
	int mtu;
	if (lc->net_conf.mtu==0	){
		/*attempt to discover mtu*/
		mtu=ms_discover_mtu(remote);
		if (mtu>0){
1161
			ms_factory_set_mtu(lc->factory, mtu);
1162
			ms_message("Discovered mtu is %i, RTP payload max size is %i",
1163
				mtu, ms_factory_get_payload_max_size(lc->factory));
Simon Morlat's avatar